Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace LightBulbs
- {
- public class LightBulbs : ILightBulbs
- {
- public new static ILightBulbs GetInstance()
- {
- return lightBulbsInstance ?? (lightBulbsInstance = new LightBulbs());
- }
- public override int CountLightsOn(bool[,] lightsBoard, int s)
- {
- int rows = lightsBoard.GetLength(0);
- int cols = lightsBoard.GetLength(1);
- for (int i = 0; i < s; ++i)
- {
- var copy = this.Copy(lightsBoard);
- for (int r = 0; r < rows; ++r)
- {
- for (int c = 0; c < cols; ++c)
- {
- if (this.IsCorner(copy, r, c))
- continue;
- int turnedOnNeighbors = this.FindTurnedOnNeighbors(copy, r, c);
- if (copy[r, c])
- {
- if (!(turnedOnNeighbors == 2 || turnedOnNeighbors == 3))
- lightsBoard[r, c] = false;
- }
- else
- {
- if (turnedOnNeighbors == 3)
- lightsBoard[r, c] = true;
- }
- }
- }
- }
- int count = 0;
- for (int r = 0; r < rows; ++r)
- {
- for (int c = 0; c < cols; ++c)
- {
- if (lightsBoard[r, c])
- count++;
- }
- }
- return count;
- }
- private bool[,] Copy(bool[,] from)
- {
- int rows = from.GetLength(0);
- int cols = from.GetLength(1);
- bool[,] copy = new bool[rows, cols];
- for (int r = 0; r < rows; ++r)
- for (int c = 0; c < cols; ++c)
- copy[r, c] = from[r, c];
- return copy;
- }
- private bool IsCorner(bool[,] lightsBoard, int row, int col)
- {
- int rows = lightsBoard.GetLength(0);
- int cols = lightsBoard.GetLength(1);
- if (row == 0 && col == 0 ||
- row == 0 && col == cols - 1 ||
- row == rows - 1 && col == 0 ||
- row == rows - 1 && col == cols - 1)
- {
- return true;
- }
- return false;
- }
- private int FindTurnedOnNeighbors(bool[,] lightsBoard, int row, int col)
- {
- int count = 0;
- int rows = lightsBoard.GetLength(0);
- int cols = lightsBoard.GetLength(1);
- for (int r = -1; r <= 1; ++r)
- {
- for (int c = -1; c <= 1; ++c)
- {
- int nRow = row + r;
- int nCol = col + c;
- if (nRow == row && nCol == col)
- continue;
- if (nRow >= 0 && nCol >= 0 && nRow <= rows - 1 && nCol <= cols - 1)
- {
- if (lightsBoard[nRow, nCol])
- count++;
- }
- }
- }
- return count;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement