public
Created

  • Download Gist
145.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
# 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(', ')}"

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.