Last active
August 29, 2015 14:21
-
-
Save bisby/78cfe51bcf8467c9a2b3 to your computer and use it in GitHub Desktop.
KenKen Factorizor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'prime' | |
def factorize x | |
factors = [] | |
if x == 1 then return factors end | |
while !Prime.prime? x | |
lf = lowestFactor x | |
factors.push lf | |
x = x/lf | |
end | |
return factors.push x | |
end | |
def lowestFactor x | |
Prime.each x do |p| | |
if (x/p)*p == x | |
return p | |
end | |
end | |
end | |
def possibles arr, n=9 | |
return arr.push(1).push(1).combination(3) | |
.map { |x| x[0]*x[1]*x[2] } | |
.sort.uniq.select{ |num| num <= 9 } | |
end | |
def combos val, arr, n=4 | |
return arr.push(1).repeated_combination(n).sort | |
.select { |x| x.reduce { |c, i| c*i } == val } | |
.sort.uniq.map { |x| x.join("*") } | |
end | |
v = ARGV[0] ? ARGV[0].to_i : 2 | |
n = ARGV[1] ? ARGV[1].to_i : 4 | |
r = 9 | |
f = factorize v | |
puts "Raw factors: " + f.join(", ") | |
p = possibles(f, r) | |
puts "Possible in 2-#{r}: " + p.join(", ") | |
c = combos(v, p, n) | |
puts "All possible combinations: " # including ones with duplicates | |
puts c.join("\n") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample output:
3_3_3*4 is obviously not a real possible combination in KenKen. But all other possibilties should be covered