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

1 Answer

0 votes
# 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:
#   initialize_board()
#   print_board()
#   main logic

BOARD_SIZE = 8

# initialize_board:
#   - Sets all values to zero
#   - For each row:
#       * randomly selects one column (0..7)
#       * places a random integer (1..100) in that column
def initialize_board(board)
  board.each_with_index do |row, r|
    # Set entire row to zero
    (0...BOARD_SIZE).each { |c| row[c] = 0 }

    # Choose a random column index
    random_col = rand(BOARD_SIZE)

    # Place a random non-zero value (1..100)
    random_value = rand(1..100)

    row[random_col] = random_value
  end
end

# print_board:
#   - Prints the 8x8 board in a readable grid format
def print_board(board)
  board.each do |row|
    puts row.join(" ")
  end
end

# ------------------------
# Main program
# ------------------------

board = Array.new(BOARD_SIZE) { Array.new(BOARD_SIZE, 0) }

initialize_board(board)
print_board(board)


=begin
run:

0 30 0 0 0 0 0 0
0 0 0 0 0 0 86 0
0 0 0 0 56 0 0 0
0 0 0 45 0 0 0 0
0 0 0 0 0 0 88 0
0 0 60 0 0 0 0 0
0 0 0 0 0 0 0 43
0 0 0 0 31 0 0 0

=end

 



answered 1 day ago by avibootz

Related questions

...