Skip to content

Instantly share code, notes, and snippets.

@lpeabody
Last active August 29, 2015 14:20
Show Gist options
  • Save lpeabody/dcfa299627fcfbc45c96 to your computer and use it in GitHub Desktop.
Save lpeabody/dcfa299627fcfbc45c96 to your computer and use it in GitHub Desktop.
Iterative Ruby solution to "Problem 5"
def get_operands(comma_indexes)
base = (1..9).to_a
last_index = 0
operands = []
comma_indexes.each do |comma_index|
operands.push(base[last_index..(comma_index-1)].join)
last_index = comma_index
end
operands.push(base[last_index..8].join)
get_plus_minus_combinations_100(operands)
end
def get_plus_minus_combinations_100(operands)
# create a clean copy
operands_copy = operands.clone
# get the number of operators
num_operators = operands.length - 1
# available operators
operations = ['+','-']
operations.repeated_permutation(num_operators).each_with_index do |operation_order|
count = 1
operation_order.each do |operation|
operands.insert(count, operation)
count = count + 2
end
count = 0
if eval(operands.join) == 100
puts operands.join(' ')
end
operands = operands_copy.clone
end
end
# We are going to do varied sizes of combinations of indexes to indicate where
# the splits should be for each number of commas
indexes = [1,2,3,4,5,6,7,8]
# Find the combinations of indexes for one comma, then two commas...
(1..8).each do |i|
indexes.combination(i).each do |comb|
get_operands(comb)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment