As Aaron mentions, one of our colleagues recently posted a "brain teaser" on the whiteboard at work.
A/BC + D/EF + G/HI = 1
All variables are unique digits from 1 - 9. Two
variables next to each other is equivalent to 10 * var1 + var2. For
example, if B = 2, C = 5 then the result is 10 * 2 + 5 which equals 25.
Since my language of this year is Ruby, I figured out the answer with the code below. I had some of the code sketched out in my head, but I wrote it after seeing Aaron's post last night, so the way I went about implementing it pretty much matched the approach Aaron took. I should also mention that I'm a Ruby newbie so there might be better ways to go about writing the below code. If so, I'd love to here them since I'm still learning what idiomatic Ruby is :)
#!/usr/bin/env ruby
class FigureItOuter
def run
set = generate_set
while (calculate(set)) != 1
set = generate_set
end
puts format("%d/%d%d + %d/%d%d + %d/%d%d = 1", set[0], set[1], set[2], set[3], set[4], set[5], set[6], set[7],set[8])
end
private
def calculate(s)
(s[0] / (10 * s[1] + s[2])) + (s[3] / (10 * s[4] + s[5])) + (s[6] / (10 * s[7] + s[8]))
end
def generate_set
s = []
while s.size != 9
n = rand(9) + 1
s << n.to_f unless s.include?(n)
end
s
end
end
# a/bc + d/ef + g/hi = 1
f = FigureItOuter.new
f.run