Skip to content

Instantly share code, notes, and snippets.

@bisby
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bisby/78cfe51bcf8467c9a2b3 to your computer and use it in GitHub Desktop.
Save bisby/78cfe51bcf8467c9a2b3 to your computer and use it in GitHub Desktop.
KenKen Factorizor
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")
@bisby
Copy link
Author

bisby commented May 26, 2015

Sample output:

$ ruby factor.rb 108 4
Raw factors: 2, 2, 3, 3, 3
Possible in 2-9: 2, 3, 4, 6, 9
All possible combinations: 
2*2*3*9
2*3*3*6
2*6*9*1
3*3*3*4
3*4*9*1
3*6*6*1

3_3_3*4 is obviously not a real possible combination in KenKen. But all other possibilties should be covered

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment