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

1 Answer

0 votes
import kotlin.random.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()
 */

const val BOARD_SIZE: Int = 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
 */
fun initializeBoard(board: Array<IntArray>) {
    val rng: Random = Random.Default

    for (row in 0 until BOARD_SIZE) {

        // Set entire row to zero
        for (col in 0 until BOARD_SIZE) {
            board[row][col] = 0
        }

        // Choose a random column index
        val randomCol: Int = rng.nextInt(BOARD_SIZE)

        // Place a random non-zero value (1..100)
        val randomValue: Int = rng.nextInt(1, 101)

        board[row][randomCol] = randomValue
    }
}

/*
 * printBoard:
 *   - Prints the 8x8 board in a readable grid format
 */
fun printBoard(board: Array<IntArray>) {
    for (row in board) {
        println(row.joinToString(" "))
    }
}

fun main() {
    // Create an 8x8 board initialized to zero
    val board: Array<IntArray> =
        Array(BOARD_SIZE) { IntArray(BOARD_SIZE) { 0 } }

    initializeBoard(board)
    printBoard(board)
}


/*
run:

30 0 0 0 0 0 0 0
0 0 0 0 0 0 80 0
0 0 0 0 0 0 0 86
0 0 0 0 0 29 0 0
0 0 0 0 0 0 38 0
36 0 0 0 0 0 0 0
0 0 0 0 67 0 0 0
0 0 0 0 0 0 0 91

*/

 



answered 1 day ago by avibootz

Related questions

...