Skip to content

Instantly share code, notes, and snippets.

@chastell chastell/145.rb
Created Jun 2, 2010

What would you like to do?
# 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') { |i| opers[i] }
exp =
results[exp] = eval exp
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 #{ { |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
You can’t perform that action at this time.