Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,239 questions

56,142 answers

573 users

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 Jul 4 by avibootz

Related questions

...