On my never ending saga to learn Ruby, I am trying to write a program to
solve Sudoku puzzles.
Given a multidimensional array (9x9) I am trying to inspect each row and
each column as follows:
Assume the following represents a typical row in my 9x9 array:
Row**
23
689
7
12345689
1359
9
2468
359
235
Row
23
689
7
12345689
1359
9
2468
359
235
Row
23
689
7
12345689
1359
9
2468
359
235
Row
23
689
7
12345689
1359
9
2468
359
235
Furthermore, assume the following is a typical column:
Column**
23
689
7
12345689
1359
9
2468
359
235
I would like to be able to count the frequency of each digit on either
row
or column, separate of course!
Number**
1
2
3
4
5
6
7
8
9
Frequency**
2
4
5
2
4
3
1
3
5
I can do this with some ugly looking and probably inefficient loop.
However,
Ruby has so many tools and “tricks” that perhaps there might be some way
of
doing this quicker and easy to understand.
Given a multidimensional array (9x9) I am trying to inspect each row and
each column as follows:
I can do this with some ugly looking and probably inefficient loop. However,
Ruby has so many tools and “tricks” that perhaps there might be some way of
doing this quicker and easy to understand.
I don’t think there’s any way to do this without looking at every
cell. I was a little confused by your massive amount of text, so I
assume you’re saying that each cell has more than one number in it.
(As occurs when writing down possibilities.)
Following is a simple iteration that will go through every cell and,
in a single pass, update the count of instances of a particular digit
in each row and column. I’ve implemented the multiple-numbers-per-cell
as an array per cell. If you have a string…well, don’t do that,
because it’d be silly.
Hope this helps you with some insight into Ruby. As I’m offering this
code up to a newbie to learn from, others please feel free to post
followups ripping it apart and suggesting better ways to accomplish
the same goals.
Create a 9x9 array, where each cell is an empty array
cells = Array.new(9){
Array.new(9){ [] }
}
Fill each cell with dummy data (not sudoku-ready)
of zero or more integers
cells.each{ |row|
row.each{ |cell|
1.upto(9){ |i|
# 20% chance of each number in some cell leaves
# us with a 13% chance of no numbers per cell.
# There’s thus a 99.999% chance that at least one
# cell will be left empty (if my math is correct)
cell << i if rand < 0.2
}
}
}