Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- import java.util.Random;
- class Global {//INITIALIZE GENERATOR ONLY ONCE TO HAVE UNIFORM DISTRIBUTION
- public static Random generator = new Random();//since this variable is public and static it can be used everywhere
- }
- class pickRand {
- public static <T> T getElement(T[] array) {//WILL NOT WORK FOR PRIMITIVE ARRAYS//returns an random element from the array
- //public static int getIndex(char[] array) {
- int rnd = Global.generator.nextInt(array.length);
- return array[rnd];
- }
- }
- public class Rectangles {
- 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
- boolean can_fill=false;
- if(filled[row][col]==0) {
- int k=0;
- try {
- for(int i=0;i<size;i++) {
- if(vh=="v") {
- if(filled[row+i][col]==0) {
- k++;
- }else {
- break;
- }
- }else {
- if(filled[row][col+i]==0) {
- k++;
- }else {
- break;
- }
- }
- }
- if(k==size) {
- can_fill=true;
- }
- }catch ( Exception e ) {
- //System.out.println("Caught exception");
- //e.printStackTrace(); // prints the stack trace
- }
- }
- return can_fill;
- }
- public static int[][] fillBlocks(int row, int col, int size, String vh, int[][] filled) {//marks filled postions
- for(int i=0;i<size;i++) {
- if(vh == "v")
- filled[row+i][col] = 1;
- else
- filled[row][col+i] = 1;
- }
- return filled;
- }
- public static void main(String[] args) {
- String[][] grid = new String[7][7];
- int[][] filled = new int[7][7];
- for(int i=0;i<grid.length;i++) {
- for(int k=0;k<grid[i].length;k++) {
- grid[i][k]="0e";
- }
- //System.out.println("grid["+i+"]: "+Arrays.toString(grid[i]));
- }
- String[] vertHor={"v", "h"};
- String vh;
- int size;
- for(int row=0;row<filled.length;row++) {
- for(int col=0;col<filled[row].length;col++) {
- while(filled[row][col]==0) {
- // vh = vertHor[pickRand.getIndex(vertHor)];
- vh = pickRand.getElement(vertHor);
- size = Global.generator.nextInt(7)+1;
- if(canFill(row, col, size, vh, filled)) {
- grid[row][col]=size+vh;
- filled = fillBlocks(row, col, size, vh, filled);
- }
- }
- }
- }
- for(int i=0;i<grid.length;i++) {
- //System.out.println("grid["+i+"]: "+Arrays.toString(grid[i]));
- System.out.println(Arrays.toString(grid[i]));
- }
- for(int i=0;i<filled.length;i++){
- System.out.println("filled["+i+"]: "+Arrays.toString(filled[i]));
- }
- }
- }
Add Comment
Please, Sign In to add comment