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

1 Answer

0 votes
package main

import (
    "fmt"
    "math/rand"
    "time"
)

/*
 * 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 BoardSize 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 *[BoardSize][BoardSize]int) {
    for row := 0; row < BoardSize; row++ {

        // Set entire row to zero
        for col := 0; col < BoardSize; col++ {
            board[row][col] = 0
        }

        // Choose a random column index
        randomCol := rand.Intn(BoardSize)

        // Place a random non-zero value (1..100)
        randomValue := rand.Intn(100) + 1

        board[row][randomCol] = randomValue
    }
}

// printBoard:
//   - Prints the 8x8 board in a readable grid format
func printBoard(board *[BoardSize][BoardSize]int) {
    for row := 0; row < BoardSize; row++ {
        for col := 0; col < BoardSize; col++ {
            fmt.Printf("%3d ", board[row][col])
        }
        fmt.Println()
    }
}

func main() {
    rand.Seed(time.Now().UnixNano()) // Seed RNG once

    var board [BoardSize][BoardSize]int

    initializeBoard(&board)
    printBoard(&board)
}


/*
run:

  0   0   0   0   0   0   0  88 
  0  67   0   0   0   0   0   0 
  0   0   0   0   0  55   0   0 
  0   0   0   0  60   0   0   0 
  0   0   0   0   0   0   0  93 
  0   0   0  32   0   0   0   0 
  0  12   0   0   0   0   0   0 
  0   0   0   0  68   0   0   0 

*/

 



answered 2 days ago by avibootz

Related questions

...