0

I'm creating a grid using a 2-d array and i want to put different values in it I have tried:

grid =(Array.new(10,Array.new(10," ") ))
for row in rand(1..9)
     for column in rand(1..9)
        grid[row][column] == 'a'
3
  • 1
    Use rand(1..9).each { |row| ... }; no one uses for in Ruby except those unfamiliar with it :-) Commented Dec 16, 2014 at 15:47
  • 1
    try printing p rand(1..9), you will see that it doesn't give you an array, but a random integer within that range. You cannot loop over integers. They also don't have "each" method. They are not enumerables. Commented Dec 16, 2014 at 15:59
  • You are creating grid incorrectly. After executing the first line, run grid[0][0]='X'; p grid and you'll see what I mean. It's defined correctly in the answers. Commented Dec 17, 2014 at 4:39

2 Answers 2

2
grid = Array.new(10) { Array.new(10, "") }

otherwise you'll get the same array repeated 10 times, which is presumably not what you want.

I am not sure what you want to do with your iterations. Do note that Ruby arrays are 0-indexed, so a 10-element array will have an index in 0...9. Also note that iteration over an array is usually done with each, as Carpetsmoker notes in comments:

grid.each do |row|
  row.each_index do |index|
    row[index] = "abcde"[rand(5)]
  end
end

EDIT: Thanks Cary!

Sign up to request clarification or add additional context in comments.

Comments

1

Your question is not clear. If you want to put the letter 'a' at n random locations in grid, you could do this:

def salt(grid, obj, n)
  m = grid.size
  locs = (0...m*m).to_a.sample(n)
  locs.each do |l|
    row, col = l.divmod(m)
    grid[row][col] = obj
  end
end

grid = Array.new(10) { Array.new(10, ' ') }

salt(grid,'a',30)
grid
  #=> [[" ", "a", " ", " ", "a", "a", "a", " ", " ", " "],
  #    ["a", "a", " ", "a", "a", " ", " ", "a", " ", " "],
  #    [" ", "a", " ", " ", "a", " ", " ", " ", "a", " "],
  #    [" ", " ", " ", "a", " ", " ", "a", " ", " ", "a"],
  #    [" ", " ", " ", "a", " ", " ", " ", " ", " ", " "],
  #    [" ", " ", "a", " ", " ", " ", " ", " ", " ", " "],
  #    ["a", " ", " ", " ", " ", " ", "a", " ", " ", "a"],
  #    [" ", " ", "a", " ", " ", "a", " ", "a", " ", " "],
  #    [" ", "a", " ", " ", "a", " ", " ", " ", "a", "a"],
  #    [" ", " ", "a", "a", "a", " ", " ", " ", " ", " "]]

You could instead write:

locs =  n.times.map { rand(m*m) }

but that will likely result in some duplicates, in which case fewer than n cells will be filled with "a"'s. For example, when I computed locs that way for n=30 I found:

locs.uniq.size
  #=> 27

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.