Guest User

Untitled

a guest
Dec 7th, 2017
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.21 KB | None | 0 0
  1. import java.util.Arrays;
  2. import java.util.Random;
  3.  
  4. class Global {//INITIALIZE GENERATOR ONLY ONCE TO HAVE UNIFORM DISTRIBUTION
  5. public static Random generator = new Random();//since this variable is public and static it can be used everywhere
  6. }
  7.  
  8. class pickRand {
  9.  
  10. public static <T> T getElement(T[] array) {//WILL NOT WORK FOR PRIMITIVE ARRAYS//returns an random element from the array
  11. //public static int getIndex(char[] array) {
  12. int rnd = Global.generator.nextInt(array.length);
  13. return array[rnd];
  14. }
  15. }
  16.  
  17. public class Rectangles {
  18.  
  19. public static boolean canFill(int row, int col, int size, String vh, int[][] filled) {//checks if box of current size can be filled into grid
  20. boolean can_fill=false;
  21. if(filled[row][col]==0) {
  22. int k=0;
  23. try {
  24. for(int i=0;i<size;i++) {
  25. if(vh=="v") {
  26. if(filled[row+i][col]==0) {
  27. k++;
  28. }else {
  29. break;
  30. }
  31. }else {
  32. if(filled[row][col+i]==0) {
  33. k++;
  34. }else {
  35. break;
  36. }
  37. }
  38. }
  39. if(k==size) {
  40. can_fill=true;
  41. }
  42. }catch ( Exception e ) {
  43. //System.out.println("Caught exception");
  44. //e.printStackTrace(); // prints the stack trace
  45. }
  46. }
  47. return can_fill;
  48. }
  49.  
  50. public static int[][] fillBlocks(int row, int col, int size, String vh, int[][] filled) {//marks filled postions
  51. for(int i=0;i<size;i++) {
  52. if(vh == "v")
  53. filled[row+i][col] = 1;
  54. else
  55. filled[row][col+i] = 1;
  56. }
  57. return filled;
  58. }
  59.  
  60. public static void main(String[] args) {
  61. String[][] grid = new String[7][7];
  62. int[][] filled = new int[7][7];
  63.  
  64. for(int i=0;i<grid.length;i++) {
  65. for(int k=0;k<grid[i].length;k++) {
  66. grid[i][k]="0e";
  67. }
  68. //System.out.println("grid["+i+"]: "+Arrays.toString(grid[i]));
  69. }
  70.  
  71. String[] vertHor={"v", "h"};
  72. String vh;
  73. int size;
  74. for(int row=0;row<filled.length;row++) {
  75. for(int col=0;col<filled[row].length;col++) {
  76. while(filled[row][col]==0) {
  77. // vh = vertHor[pickRand.getIndex(vertHor)];
  78. vh = pickRand.getElement(vertHor);
  79. size = Global.generator.nextInt(7)+1;
  80. if(canFill(row, col, size, vh, filled)) {
  81. grid[row][col]=size+vh;
  82. filled = fillBlocks(row, col, size, vh, filled);
  83. }
  84. }
  85. }
  86. }
  87.  
  88. for(int i=0;i<grid.length;i++) {
  89. //System.out.println("grid["+i+"]: "+Arrays.toString(grid[i]));
  90. System.out.println(Arrays.toString(grid[i]));
  91. }
  92. for(int i=0;i<filled.length;i++){
  93. System.out.println("filled["+i+"]: "+Arrays.toString(filled[i]));
  94. }
  95.  
  96. }
  97. }
Add Comment
Please, Sign In to add comment