draq,
Array mixes in Enumerable, so inject works.
I added some asserts to be able to understand what your code does.
As I can see, this solves only a partial problem: generating all
combinations, given a sum and number of squares. This is calc(sum,
count).
Next step would probably be intersection(sum1, count1, sum2, count2)
between a row and a column, listing the possible combinations.
Curiousity: The list for arr(2) below, was too long. So I decided to cut
it by writing a method for Array. Then I found it's already defined!
First accepts zero or one argument.
Defining a kakuro, so a program can solve it, seems to be a lot more
hassle than defining a sudoku.
Christer
def sum (arr) arr.inject { |sum,i| sum += i } end
def arr (depth, min=1, max=10-depth,t=[], arr=[])
(min..max).each do |i|
t[depth-1] = i if depth > 0
arr(depth-1, i+1, max+1, t, arr) if depth > 1
arr << t.reverse.clone if depth == 1
end
arr
end
def calc (number, depth)
arri = arr(depth)
arri.each do |a|
arri.delete_if { |a| sum(a) != number }
end
arri
end
require 'test/unit'
class TestKakuro < Test::Unit::TestCase
def test_all
assert_equal 12, sum([3,4,5])
assert_equal [[1, 2], [1, 3], [1, 4], [1, 5], [1, 6],
[1, 7], [1, 8], [1, 9], [2, 3], [2, 4]],
arr(2).first(10)
assert_equal 9, arr(1).size
assert_equal 36, arr(2).size
assert_equal 84, arr(3).size
assert_equal 126, arr(4).size
assert_equal 126, arr(5).size
assert_equal 84, arr(6).size
assert_equal 36, arr(7).size
assert_equal 9, arr(8).size
assert_equal 1, arr(9).size
assert_equal [[7, 8, 9]], calc(24,3)
assert_equal [[1, 6, 8, 9],[2, 5, 8, 9],
[2, 6, 7, 9],[3, 4, 8, 9],
[3, 5, 7, 9],[3, 6, 7, 8],
[4, 5, 6, 9],[4, 5, 7, 8]], calc(24, 4)
assert_equal [[1, 2, 3, 4, 5, 6, 7, 8, 9]], calc(45, 9)
end
end