samedi 7 janvier 2023

How to make every index of 2D array a random integer?

`import java.util.Random;

public class Main {

    public static void main(String[] args) {
        int[][] board = new int[5][5];
        int sNA = 5;

//        new GUI();

        sequenceMaker(board);
        drawBoard(board);
    }
//
    public static void drawBoard(int[][] board2D) {
        int m=1;

        for(int i = 0; i < board2D.length; i++){
            for(int j=0; j < board2D.length; j++){
                System.out.print(board2D[i][j]+" ");
            }
            System.out.println();
        }
    }

    public static void sequenceMaker(int[][] board2D) {
        Random rand = new Random();
        int m = 1;
        int x = 0;

        while(x < 24){
            int columnRandom = rand.nextInt(5);
            int rowsRandom = rand.nextInt(5);
            x += 1;

            if(board2D[columnRandom][rowsRandom] == 0) {
                board2D[columnRandom][rowsRandom] = m;
                m += 1;
            }
            else if(board2D[columnRandom][rowsRandom] == m) {
                while(board2D[columnRandom][rowsRandom] == m) {
                    columnRandom = rand.nextInt(5);
                    rowsRandom = rand.nextInt(5);

                    board2D[columnRandom][rowsRandom] = m;
                    m+=1;
                }
            }
        }
    }
}`

This is what I wrote to this point, but the output doesn't include every index, maximally going to 15-16ish.

I tried a while loop, so that if another integer is in the place of randomally generated number, it generates those number once again. I don't know why my output is incomplete though.




Aucun commentaire:

Enregistrer un commentaire