How to randomly place a random value in each row of an 8x8 int array with zero values in Java

1 Answer

0 votes
import java.util.Random;

/**
 * This program creates an 8x8 integer board.
 * For each row:
 *   - All values are set to zero
 *   - One random column is chosen
 *   - A random value (1..100) is placed in that column
 *
 * It mirrors the structure of the C++ version:
 *   initializeBoard()
 *   printBoard()
 *   main()
 */
public class RandomBoard {

    private static final int SIZE = 8;

    /**
     * initializeBoard:
     *   - Sets all values to zero
     *   - For each row:
     *       * randomly selects one column (0..7)
     *       * places a random integer (1..100) in that column
     */
    public static void initializeBoard(int[][] board) {
        Random rng = new Random();  // Java's standard random generator

        for (int row = 0; row < SIZE; row++) {

            // Set entire row to zero
            for (int col = 0; col < SIZE; col++) {
                board[row][col] = 0;
            }

            // Choose a random column index
            int col = rng.nextInt(SIZE);

            // Place a random value between 1 and 100 (never zero)
            board[row][col] = rng.nextInt(100) + 1;
        }
    }

    /**
     * printBoard:
     *   - Prints the 8x8 board in a readable grid format
     */
    public static void printBoard(int[][] board) {
        for (int row = 0; row < SIZE; row++) {
            for (int col = 0; col < SIZE; col++) {
                System.out.printf("%3d ", board[row][col]);
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int[][] board = new int[SIZE][SIZE];  // Zero-initialized by Java

        initializeBoard(board);
        printBoard(board);
    }
}


/*
run:

  0   0  29   0   0   0   0   0 
  0  90   0   0   0   0   0   0 
 12   0   0   0   0   0   0   0 
  0  13   0   0   0   0   0   0 
  0   0   0   0   0   0   0  79 
  0   0   0   0   0   0  17   0 
  0   0   0  16   0   0   0   0 
  0   0   0   8   0   0   0   0 

*/

 



answered 2 days ago by avibootz

Related questions

...