How to generate N random 1s in a zero-based matrix with Ruby

1 Answer

0 votes
#
#   Generate N random 1s in a zero-based matrix.
#
#   Strategy:
#   - Treat the matrix as a flat index space [0 ... rows*cols - 1].
#   - Randomly pick unique positions using a Set to ensure uniqueness.
#   - Convert each chosen flat index back to (row, col).
#   - This avoids repeatedly searching for empty cells and keeps the logic simple.
#

require "set"

# Allocate a rows×cols matrix initialized to zero
def allocate_matrix(rows, cols)
  # Array.new keeps the code compact and expressive
  Array.new(rows) { Array.new(cols, 0) }
end

# Print the matrix
def print_matrix(matrix)
  matrix.each do |row|
    puts row.join(" ")
  end
end

# Generate N random 1s in a zero-based matrix
def generate_random_matrix(rows, cols, count)
  total = rows * cols

  if count > total
    raise ArgumentError, "Requested more 1s than available cells."
  end

  matrix = allocate_matrix(rows, cols)

  # Use a Set to ensure unique positions
  chosen = Set.new

  # Draw unique positions
  while chosen.size < count
    index = rand(total)   # rand(total) gives 0..total-1
    chosen << index
  end

  # Convert flat indices to (row, col)
  chosen.each do |index|
    r = index / cols
    c = index % cols
    matrix[r][c] = 1
  end

  matrix
end

# Example usage
rows = 5
cols = 7
number_of_ones = 10

result = generate_random_matrix(rows, cols, number_of_ones)
print_matrix(result)


=begin
run:

0 1 0 0 0 0 1
1 0 0 0 1 0 0
0 0 1 1 1 1 0
0 0 0 0 0 0 0
0 1 0 0 0 1 0

=end

 



answered Aug 21 by avibootz
...