Created
June 6, 2014 03:07
-
-
Save kaddopur/952b6f008f6c83c1b322 to your computer and use it in GitHub Desktop.
This file contains 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
def twenty_four(*operands) | |
p operands | |
operators = %w(+ - * /) | |
operands.map! {|op| op.to_f} | |
operands.permutation.to_a.uniq.each do |ordered_operands| | |
operators.repeated_permutation(operands.length-1) do |ordered_operators| | |
check_answer(ordered_operands, ordered_operators) | |
end | |
end | |
puts '' | |
end | |
def check_answer(operands, operators) | |
add_parentheses(operands).each do |p_operands| | |
formula = make_formula(p_operands, operators) | |
puts "#{make_formula(p_operands.map {|op| op.is_a?(Numeric) ? op.to_i : op}, operators)}=24" if eval(formula) == 24 | |
end | |
end | |
def add_parentheses(sequence) | |
results = [] | |
if sequence.length <= 1 | |
results << sequence | |
else | |
0.upto(sequence.length-2) do |i| | |
add_parentheses(sequence[0..i]).each do |left| | |
add_parentheses(sequence[(i+1)..-1]).each do |right| | |
results << ['('] + left + right + [')'] | |
end | |
end | |
end | |
end | |
results | |
end | |
def make_formula(p_operands, operators) | |
formula = '' | |
this_operators = operators.clone | |
p_operands.each_with_index do |operand, i| | |
formula += operand.to_s | |
formula += this_operators.shift if operand.is_a?(Numeric) && p_operands[i+1] != ')' | |
formula += this_operators.shift if operand == ')' && p_operands[i+1].is_a?(Numeric) | |
formula += this_operators.shift if operand == ')' && p_operands[i+1] == '(' | |
end | |
formula | |
end | |
twenty_four(2, 3, 4) | |
twenty_four(5, 1, 5) | |
twenty_four(3, 8) | |
twenty_four(3, 4, 5, 6) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment