fork(1) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import java.util.Map.Entry;
  7. import java.util.AbstractMap.SimpleEntry;
  8.  
  9. /* Name of the class has to be "Main" only if the class is public. */
  10. class Ideone{
  11. public static void main (String[] args) throws java.lang.Exception{
  12. int row, col, n = 6;
  13. int[][] grid = new int[n][n], cCount = new int[n][2], rCount = new int[n][2];
  14. Deque<Entry<Integer,Integer>> s = new ArrayDeque<Entry<Integer,Integer>>();
  15.  
  16. Random rand=new Random();
  17. for(int i = 0; i < grid.length; i++){
  18. for(int j = 0; j < grid[0].length; j++){
  19. // Constraints: row, col {-1, 0, 1}. -1 = no constraint.
  20. row = j > 1 && grid[i][j-2] == grid[i][j-1] ? (grid[i][j-1] == 0 ? 1:0):
  21. (rCount[i][0] >= n/2 ? 1: (rCount[i][1] >= n/2 ? 0:-1));
  22. col = i > 1 && grid[i-2][j] == grid[i-1][j] ? (grid[i-1][j] == 0 ? 1:0):
  23. (cCount[j][0] >= n/2 ? 1: (cCount[j][1] >= n/2 ? 0:-1));
  24. grid[i][j] = row == -1 && col == -1 ? rand.nextInt(2):(row > -1 ? row:col);
  25.  
  26. if( row == -1 && col == -1){ // no constraint
  27. s.push(new SimpleEntry<Integer,Integer>(i, j));
  28. } else if( (row > -1 && col > -1 && row != col) // constraint conflict
  29. || (row > -1 && rCount[i][row] == n/2) // count conflict
  30. || (col > -1 && cCount[j][col] == n/2)){ // count conflict
  31. Entry<Integer, Integer> last = s.pop();
  32. while(i > last.getKey() || j > last.getValue()){
  33. j = (j-1+ n)%n; // step indices back
  34. i = (j == n-1) ? i-1:i;
  35. rCount[i][grid[i][j]]--; // reduce counters
  36. cCount[j][grid[i][j]]--;
  37. }
  38. grid[i][j] = grid[i][j] == 0 ? 1:0; // flip value
  39. }
  40.  
  41. rCount[i][grid[i][j]]++; // increment counters
  42. cCount[j][grid[i][j]]++;
  43. }
  44. }
  45.  
  46. for(int i = 0; i < grid.length; i++){
  47. for(int j = 0; j < grid[0].length; j++)
  48. System.out.print(grid[i][j] + " ");
  49. System.out.println();
  50. }
  51. }
  52. }
Success #stdin #stdout 0.08s 381184KB
stdin
Standard input is empty
stdout
0  0  1  1  0  1  
1  0  0  1  0  1  
0  1  1  0  1  0  
0  1  1  0  1  0  
1  0  0  1  0  1  
1  1  0  0  1  0