From: Robert Klemme Date: 2005-08-11T00:31:11+09:00 Subject: Re: Matrix type ? zimba-tm wrote: > Hello ruby fellows, > > Maybe you can help me. > > I'm currently trying to make a Sudoku solver for my first ruby > program. Sudoku is a nice 9x9 board game with simple rules, but it > can be tough to solve. More infos at http://www.sudoku.com/ if you > want to launch a RubyQuizz :-P > > What I would do, is use a kind of 2D Matrix that would represent the > board but couldn't find a satisfying method. > > This is my current implementation using arrays : > ---- > board = Array.new > > (1..9).each do |row_num| > board[row_num] = Array.new > (1..9).each do |col_num| > board[row_num][col_num] = "X" > end > end That can be simplified to board = Array.new(9) { Array.new(9) { "X" } } In your case I'd create a customer class that does this internally and provides access methods to cells. This class then also can check the validity of moves etc. class Board def initialize(size=9) @board = Array.new(size) { Array.new(size) { "X" } } end def move(from_x, from_y, to_x, to_y) raise "Invalid move" if ... # do the move ... end def to_s # generate reasonable string representation ... end end You might also need / want classes for figures if they behave differently etc. > ---- > If I "puts board", I'd like to have a 2D view instead. > How does puts work, does it call the to_str method ? No, it's #to_s: >> o=Object.new => # >> puts o # => nil >> def o.to_s() "foo" end => nil >> puts o foo => nil > Also, I'd like to access the console as a 2D Array too, > so that I can write on screen directly like a text-framebuffer. Hm, I think there is (n)curses support somewhere. You can check with the RAA http://raa.ruby-lang.org/ > I have so many questions.. :-) > /me is refraining to flood ruby-talk Keep coming! Kind regards robert