horiuchi #5379(2008/01/18 09:00 GMT) [ C# ] Rating0/0=0.00
C#で書いてみました。特に「間引き」の処理は入れていません。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
using System; public class LifeGame { private int time_ = 0; private readonly bool[][] matrix_; public LifeGame(int rows, int cols) { Random random = new Random(); matrix_ = new bool[rows][]; for (int rowIndex = 0; rowIndex < rows; rowIndex++) { matrix_[rowIndex] = new bool[cols]; for (int index = 0; index < cols; index++) { if (random.NextDouble() < 0.3) { matrix_[rowIndex][index] = true; } } } } public int Time { get { return time_; } } public String GetDisplayMatrix() { System.Text.StringBuilder builder = new System.Text.StringBuilder(); foreach (bool[] row in matrix_) { foreach (bool cell in row) { builder.AppendFormat("[{0}]", cell? "*": " "); } builder.Append('\n'); } return builder.ToString(); } public void NextStep() { bool[][] oldMatrix = CopyMatrix(matrix_); for (int rowIndex = 0; rowIndex < matrix_.Length; rowIndex++) { for (int colIndex = 0; colIndex < matrix_[rowIndex].Length; colIndex++) { matrix_[rowIndex][colIndex] = Next(rowIndex, colIndex, oldMatrix); } } time_++; } private bool[][] CopyMatrix(bool[][] matrix) { bool[][] result = new bool[matrix.Length][]; for (int index = 0; index < matrix.Length; index++) { result[index] = new bool[matrix[index].Length]; matrix[index].CopyTo(result[index], 0); } return result; } private bool Next(int row, int col, bool[][] matrix) { bool now = matrix[row][col]; int count = GetCell(matrix, row - 1, col - 1) + GetCell(matrix, row - 1, col) + GetCell(matrix, row - 1, col + 1) + GetCell(matrix, row, col - 1) + GetCell(matrix, row, col + 1) + GetCell(matrix, row + 1, col - 1) + GetCell(matrix, row + 1, col) + GetCell(matrix, row + 1, col + 1); if (now) { return (count == 2 || count == 3); } else { return (count == 3); } } private int GetCell(bool[][] matrix, int rowIndex, int colIndex) { int y = rowIndex; while (y < 0) y += matrix.Length; while (y >= matrix.Length) y -= matrix.Length; bool[] row = matrix[y]; int x = colIndex; while (x < 0) x += row.Length; while (x >= row.Length) x -= row.Length; return row[x]? 1: 0; } [STAThread] static void Main(string[] args) { LifeGame game = new LifeGame(10, 10); Console.WriteLine("t={0}", game.Time); Console.WriteLine(game.GetDisplayMatrix()); game.NextStep(); Console.WriteLine("t={0}", game.Time); Console.WriteLine(game.GetDisplayMatrix()); Console.ReadLine(); } }
Rating0/0=0.00-0+
[ reply ]
horiuchi
#5379()
[
C#
]
Rating0/0=0.00
C#で書いてみました。特に「間引き」の処理は入れていません。
Rating0/0=0.00-0+
[ reply ]