{"id":191,"date":"2006-02-12T09:12:34","date_gmt":"2006-02-11T22:12:34","guid":{"rendered":"http:\/\/www.somethinkodd.com\/oddthinking\/2006\/02\/12\/a-kakuro-solver\/"},"modified":"2006-02-12T09:12:34","modified_gmt":"2006-02-11T22:12:34","slug":"a-kakuro-solver","status":"publish","type":"post","link":"https:\/\/www.somethinkodd.com\/oddthinking\/2006\/02\/12\/a-kakuro-solver\/","title":{"rendered":"A Kakuro Solver"},"content":{"rendered":"<h3>Introducing Kakuro<\/h3>\n<p>In the footsteps of the Sudoku craze comes a wannabe replacement: <a href=\"http:\/\/www.kakuro.com\">Kakuro<\/a>. (Visit the link to learn more; I won&#8217;t bother explaining the rules here.)<\/p>\n<p>I have been doing a few of these. Only a handful. Certainly not as many as Andrew at <a href=\"http:\/\/otherleg.com\/anotherblog\/archives\/892\">Anotherblog<\/a>.<\/p>\n<p>As my regular readers will know, <a href=\"http:\/\/www.somethinkodd.com\/oddthinking\/2005\/05\/21\/puzzling-over-puzzles\/\">I prefer to solve the general case<\/a>, rather than solving individual puzzles, and preferably with an elegant algorithm than using an elephant gun, like backtracking.<\/p>\n<p>So let&#8217;s look at Kakuro&#8230;<\/p>\n<h3>What&#8217;s the Algorithm?<\/h3>\n<p>How do I solve Kakuro puzzles?  <\/p>\n<p>I looked at my approach. I seemed to ask a lot of &#8220;What If?&#8221; style questions (&#8220;If this cell was the maximum it could be, and this cell was the maximum it could be, then that would dictate the minimum value the last cell could be.&#8221;)<\/p>\n<p>However, it all seemed to boil down to:<\/p>\n<ul>\n<li>Work out what combinations of numbers add up to the total, given the restrictions on the individual cells.<\/li>\n<li>Eliminating illegal values: ones that aren&#8217;t in both the horizontal and vertical lists of possible values.<\/li>\n<li>Repeat, repeat, repeat<\/li>\n<\/ul>\n<p>It seemed pretty simplistic and obvious. However, I&#8217;ve been fooled before. Sudoku didn&#8217;t fall to the simplistic and obvious. <\/p>\n<div class=\"aside\">I once spent <em>months<\/em> at a job trying to debug a simple program that solved a problem that could be solved by hand moderately easily, but no-one (including me) could exactly explain the algorithm they used. I implemented potential algorithm after algorithm, and then produced brain-inverting test cases that proved they didn&#8217;t work. So, I am acutely aware that the simple heuristic you <em>think<\/em> you are using isn&#8217;t always the one you are actually using.<\/div>\n<p>Time to implement a Kakuro solver to find out.<\/p>\n<h3>The Implementation<\/h3>\n<p>I&#8217;ve done this a couple of times before (<a href=\"http:\/\/www.somethinkodd.com\/oddthinking\/2005\/06\/12\/the-no-nos-and-yes-yeses-of-the-nonogram-solution\/\">Nonograms<\/a>, <a href=\"http:\/\/www.somethinkodd.com\/oddthinking\/2005\/05\/21\/21\/\">Sudoku<\/a>, <a href=\"http:\/\/www.somethinkodd.com\/oddthinking\/2005\/06\/06\/analysis-of-the-australian-bush-game\/\">Australian Bush Game<\/a>) so the approach was familiar. As usual, I was careful not to see look to see how anyone else approached it.<\/p>\n<h4>Technology<\/h4>\n<p>I rounded up the usual suspects: about 350 lines of Python code with the help of PyGame and Python Imaging Library for the animation.<\/p>\n<h4>Data Structures<\/h4>\n<p>The objects were straightforward:<\/p>\n<p>The Grid represents the whole table, full of Cells. <\/p>\n<p>Cells represent a square on the grid, and know what values that they can have. <\/p>\n<p>Rows represent <em>horizontal and vertical<\/em> sets of Cells with a total &#8211; i.e. the clues to the puzzle. They don&#8217;t record the actual values of the cells. Rows really only have a responsibility during the start-up phase, and then they are redundant.<\/p>\n<p>PossibleRowValues represent a set of values for each Cell in a row.<\/p>\n<p>The only complexity in the data structure was that Cells have a list of all the PossibleRowValues, grouped by the value the cell would have to take to fit. Meanwhile each PossibleRowValues object has links back to the Cells that are affected by it.<\/p>\n<h4>Interactions<\/h4>\n<h5>Start Up<\/h5>\n<p>The main program creates the Grid. The Grid creates and owns the Cells. <\/p>\n<p>The main program creates the Rows. The Rows register themselves with the Grid, which returns the set of cells associated with them. The Rows then create the PossibleRowValues (discussed more later), and help create the mapping from the Cells to the PossibleRowValues and vice versa. <\/p>\n<h5>Calculation<\/h5>\n<p>When triggered, each Cell compares the horizontal PossibleRowValues to the Vertical PossibleRowValues with the aim of eliminating cell values that are not in common with both. <\/p>\n<p>Once a cell value is marked for elimination, all of the corresponding PossibleRowValues are &#8220;deleted&#8221;. During their deletion, the PossibleRowValues inform the other cells in the same row that the PossibleRowValue is being deleted.<\/p>\n<h5>Flow of the Trigger<\/h5>\n<p>This is a recursive algorithm. Once a Cell is informed that a PossibleRowValue has been deleted, it can be considered a trigger to redo its own calculations.<\/p>\n<p>In past puzzles, I have used two different approaches here.<\/p>\n<p>The obvious approach is to do this recursively &#8211; have each cell trigger other cells directly, and let the program stack keep track of the progress.<\/p>\n<p>I have <a href=\"http:\/\/www.somethinkodd.com\/oddthinking\/2005\/06\/12\/the-no-nos-and-yes-yeses-of-the-nonogram-solution\/\">written before<\/a> about using a Command pattern and a queue of Commands to turn recursion into iteration.<\/p>\n<p>Both of those solutions probably would have worked here, but I went for a third approach this time.<\/p>\n<p>I ignored triggers, and simply looped through each cell in the grid telling it to update whether it needed it or not. This wasn&#8217;t a decision based on careful evaluation of the optimal efficiency. It just struck me as fairly simple to implement.<\/p>\n<h5>Complexity<\/h5>\n<p>As an accidental side-effect of this iteration, it offered a simpler upper-bound complexity analysis.<\/p>\n<p>The <code>alphabet<\/code> is the numbers from 1 to 9 that each cell can take.<\/p>\n<p>The worst case time to evaluate every cell is the deletion of the PossibleRowValues corresponding to <code>|alphabet| - 1<\/code> values. The deletion of PossibleRowValues has a constant upper-bound. So each cell, worst-case, takes <code>O(|alphabet|)<\/code> to evaluate.<\/p>\n<p><code>|Grid|<\/code> is the total number of cells in the grid (typically 9&#215;9 = 81, although the labels make it appear to be 10&#215;10).<\/p>\n<p>The time taken to loop through the grid and trigger each cell is therefore <code>O(|grid|.|alphabet|)<\/code>.<\/p>\n<p><em>If this algorithm worked<\/em>, it would need to eliminate <em>at least one<\/em> value in each pass through the grid. There are at most <code>|grid|.|alphabet|<\/code> values in the grid, so the worst-case complexity is <code>O(|grid|<sup>2<\/sup>.|alphabet|<sup>2<\/sup>)<\/code>.<\/p>\n<h4>Permutations<\/h4>\n<p>The Row object must create one PossibleRowValues for every permutation of every set of values that add up to the total.<\/p>\n<p>How many of these are there? <\/p>\n<p>I&#8217;m glad you asked.<\/p>\n<p>There are 8 possible row lengths from 2 to 9. Each has its own minimum and maximum total value. For example, the totals of a row of length 5 range between 15 and 35.<\/p>\n<p>There are a total of 120 different length\/total pairs.<\/p>\n<p>The theoretical row with the most number of permutations  is a row of length=9 and total=45. That has 9! = 362880 permutations.<\/p>\n<p>The worst example I have found in &#8220;real-life&#8221; in the handful of Kakuro I have done is a row if length=7 and total=41, which has 5040 permutations.<\/p>\n<p>I started out expecting the worst. I pondered how I could cache these calculated values and optimise them. (That would require space for just under a million permutations). Fortunately, I held back and just implemented a naive solution first. It takes about 7 seconds to generate all the combinations required for the typical puzzle. I didn&#8217;t feel the need to optimise further.<\/p>\n<h4>Algorithm Animation<\/h4>\n<p>Drawing on my past experience, I gave development priority to the graphical display of the algorithm&#8217;s progress. The aim was to make debugging of the algorithm easier.<\/p>\n<p>The debugging of this implementation went very quickly and painlessly. I don&#8217;t know whether that means that my effort to make debugging easier was wasted, or extremely well spent!<\/p>\n<p>The largest source of errors was the data-entry of the clues into the grid. The graphical display certainly helped proof-reading those values.<\/p>\n<h3>Outcome<\/h3>\n<p>I entered a Novice-level puzzle that I had previously solved. The software churned for about 7 seconds computing permutations, then displayed the grid on screen, and progressively solved it in about 25 seconds.<\/p>\n<p>Hooray!<\/p>\n<p>I entered a Ninja-level puzzle that I had previously half-solved. The software churned for about 7 seconds computing permutations, then displayed the grid on screen, and progressively solved it in about 25 seconds. No real difference!<\/p>\n<p>Double Hooray!<\/p>\n<p>For <code>n=2<\/code>, it looks like the simplistic algorithm works!<\/p>\n<h3>Solver in Action<\/h3>\n<p>Legend:<\/p>\n<ul>\n<li>White numbers: clues<\/li>\n<li>Blue numbers: solutions to cells<\/li>\n<li>Red Numbers: possible value this cell might take.<\/li>\n<li>Grey Background: Out-of-date; this cell has been updated since the last time it calculated the possible values.<\/li>\n<li>White Background: Up-to-date; no change since the last recalculation.<\/li>\n<\/ul>\n<h4>Ready to Begin Calculations<\/h4>\n<p><img decoding=\"async\" id=\"image192\" alt=\"Kakuro Solver - Just Started\" src=\"http:\/\/www.somethinkodd.com\/oddthinking\/wp-content\/uploads\/2006\/02\/kakuro_startup.PNG\" \/><\/p>\n<h4>Half Solved<\/h4>\n<p><img decoding=\"async\" id=\"image193\" alt=\"kakuro Solver - Halfway\" src=\"http:\/\/www.somethinkodd.com\/oddthinking\/wp-content\/uploads\/2006\/02\/kakuro_halfway.PNG\" \/><\/p>\n<h4>Solved!<\/h4>\n<p><img decoding=\"async\" id=\"image194\" alt=\"Kakuro Solver - Completed\" src=\"http:\/\/www.somethinkodd.com\/oddthinking\/wp-content\/uploads\/2006\/02\/kakuro_solved.PNG\" \/><\/p>\n","protected":false},"excerpt":{"rendered":"<p>An implementation of a Kakuro Solver.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_s2mail":"","footnotes":""},"categories":[33,34],"tags":[],"class_list":["post-191","post","type-post","status-publish","format-standard","hentry","category-puzzle-solving","category-software-development"],"_links":{"self":[{"href":"https:\/\/www.somethinkodd.com\/oddthinking\/wp-json\/wp\/v2\/posts\/191","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.somethinkodd.com\/oddthinking\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.somethinkodd.com\/oddthinking\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.somethinkodd.com\/oddthinking\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.somethinkodd.com\/oddthinking\/wp-json\/wp\/v2\/comments?post=191"}],"version-history":[{"count":0,"href":"https:\/\/www.somethinkodd.com\/oddthinking\/wp-json\/wp\/v2\/posts\/191\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.somethinkodd.com\/oddthinking\/wp-json\/wp\/v2\/media?parent=191"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.somethinkodd.com\/oddthinking\/wp-json\/wp\/v2\/categories?post=191"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.somethinkodd.com\/oddthinking\/wp-json\/wp\/v2\/tags?post=191"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}