Created
June 2, 2010 20:11
-
-
Save chastell/422922 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# Form all the arithmetic expressions that consist of the digits one | |
# through nine, in order, with a plus-sign, a times-sign, or a null | |
# character interpolated between each pair of digits; for instance, | |
# 12+34*56+7*89 is a valid expression that evaluates to 2539. What | |
# number is the most frequent result of evaluating all possible | |
# arithmetic expressions formed as described above? How many times | |
# does it occur? What are the expressions that evaluate to that result? | |
digits = ('1'..'9').to_a | |
opers = ['', '+', '*'] | |
slots = digits.size - 1 | |
results = {} | |
# generate all eight-digit base-three numbers (00000000..22222222), | |
# turn them into oper sequences and then zip them between the digits | |
(0...(opers.size ** slots)).each do |num| | |
seq = num.to_s(opers.size).rjust(slots, '0').chars.map(&:to_i).map { |i| opers[i] } | |
exp = digits.zip(seq).join | |
results[exp] = eval exp | |
end | |
top = results.values.group_by(&:to_i).values.max_by &:size | |
puts "most frequent result is #{top.first}, which occurs #{top.size} times" | |
puts "and is the result of #{results.select { |exp, val| val == top.first }.keys.join(', ')}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment