psotirov

Fall Down

Dec 10th, 2012
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.59 KB | None | 0 0
  1. using System;
  2.  
  3. class FallDown
  4. {
  5.     static void Main()
  6.     {
  7.         int[] grid = new int[8];
  8.         bool hasChanged = true;
  9.         for (int i = 0; i < 8; i++) // Loop to enter byte masks
  10.         {
  11.             grid[i] = int.Parse(Console.ReadLine()); // reads a number from the console
  12.         }
  13.  
  14.         while (hasChanged) // Main loop - executes until the grid is not modified since last operation
  15.         {
  16.             hasChanged = false; // there must be any change to become true
  17.             for (int i = 0; i < 8; i++) // Horizontal loop - the grid is processed from column 0 (least bits) to column 7(most bits)
  18.             {
  19.                 int mask = (1 << i); // sets the mask bit for i-th cell
  20.                 for (int j = 7; j > 0; j--) // Vertical loop - lines are processed from bottom to top
  21.                 {
  22.                     if ((grid[j] & mask) == 0) // there is empty space at cell (i, j)
  23.                     {
  24.                         int temp = grid[j];
  25.                         grid[j] = grid[j] | (grid[j - 1] & mask); //moves the bit from the upper cell (i, j-1)
  26.                         grid[j - 1] = grid[j - 1] & (~mask); // then empties the upper cell (sets the corresponding bit to 0)
  27.                         // this operation also empties the most upper cell (i,0) at the end of the loop
  28.                         if (grid[j] != temp) hasChanged = true;
  29.                     }
  30.                 }
  31.             }
  32.         }
  33.  
  34.  
  35.  
  36.         foreach (byte line in grid) // Loop to print result byte masks
  37.         {
  38.             Console.WriteLine(line);
  39.         }
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment