Created
January 16, 2012 00:14
-
-
Save amarburg/1618159 to your computer and use it in GitHub Desktop.
Ruby solution to New Scientist Enigma 1656
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
#!/usr/bin/env ruby | |
def divisible a,b | |
p = a.to_f/b | |
(a - p.to_i*b) == 0 | |
end | |
def indivisible a,b | |
not divisible a,b | |
end | |
# Given a list, computes the "enigma test": is the sum divisible by the | |
# last array but not by any of the other entries. | |
# | |
def enigma_test list | |
s = list.inject(:+) | |
p = list.slice(0, list.length-1).map { |m| indivisible s, m } << divisible( s, list[-1] ) | |
p.inject( true ) { |s,i| s and i } | |
end | |
# Given an array of N arrays, returns an array of 9N arrays, each of the | |
# original with the digits 1..9 tacked on the end. | |
# | |
def add_digit list | |
list.map { |l| Array.new(9) { |i| [ *l, (i+1)] } }.flatten(1) | |
end | |
# Seed the original array... | |
# | |
a = (1..9).to_a.map { |i| [i] } | |
4.times { |j| | |
a = add_digit a | |
a.delete_if { |i| not enigma_test i } | |
puts "For length #{j+2}" | |
p a | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment