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

1 Answer

0 votes
import Foundation

/*
 * 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()
 */

let 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
 */
func initializeBoard(_ board: inout [[Int]]) {
    for row in 0..<BOARD_SIZE {

        // Set entire row to zero
        for col in 0..<BOARD_SIZE {
            board[row][col] = 0
        }

        // Choose a random column index
        let randomCol: Int = Int.random(in: 0..<BOARD_SIZE)

        // Place a random non-zero value (1..100)
        let randomValue: Int = Int.random(in: 1...100)

        board[row][randomCol] = randomValue
    }
}

/*
 * printBoard:
 *   - Prints the 8x8 board in a readable grid format
 */
func printBoard(_ board: [[Int]]) {
    for row in board {
        print(row.map { String($0) }.joined(separator: " "))
    }
}

// ------------------------
// Main program
// ------------------------

var board: [[Int]] = Array(
    repeating: Array(repeating: 0, count: BOARD_SIZE),
    count: BOARD_SIZE
)

initializeBoard(&board)
printBoard(board)


/*
run:

0 0 0 0 0 0 1 0
76 0 0 0 0 0 0 0
0 0 0 58 0 0 0 0
87 0 0 0 0 0 0 0
0 0 0 0 0 0 0 66
0 0 0 0 51 0 0 0
0 0 70 0 0 0 0 0
0 0 0 66 0 0 0 0

*/

 



answered 1 day ago by avibootz

Related questions

...