Tuesday, August 10, 2010

Thought experiment:: Suduko Solver

So, I'm trying to teach myself Ruby, after a long hiatus in the process.  Mainly reading the pickaxe, haven't coded much yet by hand.  My Dad's one of the great programmers of this age, in my mind, so when he said one of his first experiments was a logical Suduko solver, I thought, "Hey, I should at least try to emulate him."  (Yeah, everyone loves their dad and respects him, let me tell you about a time my dad and his best friend turned a few dozen mall stands into a multinational corporation with the inventory tracking system.)

Here's where it starts to get interesting.

*Note, I'm not sitting here with the pickax in hand, just running it through my head, this is not language dependent, but a test for me as a logical person, ie, a programmer*

The first thought I had was, brute force, we can try for elegance later, after I have a good understanding of the problem.  The first thought I had after a quick glance through the doc is a hash, each key being x, y, quad (obviously not quad, whatever the nine piece equivalent is).  The values of the hash being the solved value.

My quick 5 minute run through told me I *could* use regular expressions to pull confirmed values, there is a function in Ruby to return an array of values with REs in a hash, and then use exclude (I don't think that's the right term) to do a negative match.  That is, I could go through and say "The point at x, y, in quad (nine) can exclude these values, does that leave one?  Several passes could do a lot of the puzzle.

Then I thought some more, and realize that a logic puzzle like suduko would also need me to find positive matches, that is, of a given number of cells, which one could hold the value I'm looking for?
To illustrate:

The row has the following values:  1  2  3  4  5  6  X  Y  Z

X, Y, and Z have to have the values 7,8, and 9, this is obvious.

If Y can't be 9 and Z can't be 9, this is less obvious, but just as important.  I say less obvious because I chose a simple example.  This can be extremely complex, let me choose a less obvious example:

The column (just for fun) has the values:  1  A  2  B  3  C  4  D  5

Now here's where it get's interesting.  A and B only have the option to be 6 or 7, and since they only have the option to be those values, they have to occupy that space together, and C could be 8, 7 or 6, and D could be 9, 7, or 6.   A human mind could read that and say C=8, and D=9.  How to code that though?

And that is my thought experiment, it took me longer to write it than it did for me to think it, but that's what I'm working on.

Measure twice, cut once.

No comments:

Post a Comment