0

I'm attempting to write a sudoku solver in ruby and I've run into an issue. Consider the following code:

@grid = Array.new(9,Array.new(9,Cell.new))

where Cell is defined as:

class Cell
    def initialize
        @value = 0
        @possibles = Array (1..9)
    end

    attr_accessor :value, :possibles
end

When I initialize my 9x9 @grid 2D array, it prints out the values

0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0

which is what I expect. However, when I try running something like @grid[5][5].value = 7 then the @grid prints out the values

7 7 7 7 7 7 7 7 7
7 7 7 7 7 7 7 7 7
7 7 7 7 7 7 7 7 7
7 7 7 7 7 7 7 7 7
7 7 7 7 7 7 7 7 7
7 7 7 7 7 7 7 7 7
7 7 7 7 7 7 7 7 7
7 7 7 7 7 7 7 7 7
7 7 7 7 7 7 7 7 7

I realize that my 9x9 @grid 2D array is full of the same instance of Cell

What is the syntax to create a 2D array of unique instances so that I can manipulate them individually?

daviscodesbugs
  • 657
  • 7
  • 17
  • 2
    Also look at matrix http://dpaste.com/36FVG6F – JLB Mar 22 '16 at 16:40
  • Further to @JLB's suggestion, the [Matrix](http://ruby-doc.org/stdlib-2.2.0/libdoc/matrix/rdoc/Matrix.html) and [Vector](http://ruby-doc.org/stdlib-2.2.0/libdoc/matrix/rdoc/Vector.html) classes have several methods that would be convenient here, including ones for stabbing out columns and 3x3 submatrices. Note that an easy way to see if a 3x3 submatrix `m` contains any duplicates is to test `arr = m.to_a.flatten; arr == arr.uniq`. A similar approach could be taken for rows and columns, of course. – Cary Swoveland Mar 22 '16 at 17:08

1 Answers1

4

You need to use a block

@grid = Array.new(9) { Array.new(9) { Cell.new } }
Rob Di Marco
  • 43,054
  • 9
  • 66
  • 56
  • 1
    dpears, If you leave a comment on a question or answer the author of the comment/question will be notified by SO. It is only when you leave a comment for someone else that you need to include @username in the comment for that person to be notified of the comment. – Cary Swoveland Mar 22 '16 at 16:58
  • 1
    Also, don't use comments to say "thanks". The comment-box specifically mentions that. They only clog the system. – the Tin Man Mar 22 '16 at 17:08