Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env ruby
- n = STDIN.readline.strip.to_i
- numbers = STDIN.readline.split(/\s/).compact.map(&:to_i)
- answer = STDIN.readline.strip.to_i
- if (numbers.length != n) then
- puts "array size mismatch"; exit
- end
- def exit_no_solution(); puts "no solution"; exit; end
- min = numbers.reduce(numbers[0] * 2) {|s, i| s -= i }
- exit_no_solution if (answer < min)
- max = numbers.reduce(0) {|s, i| s += i }
- exit_no_solution if (answer > max)
- [:-, :+].repeated_permutation(n-1) do |signs|
- signs.insert(0, :+)
- result = (0..n-1).each.reduce(0) do |s, i|
- s = s.method(signs[i]).call(numbers[i])
- end
- next if result != answer
- formula = (0..n-1).each.reduce("") do |s, i|
- s += (" %s " % signs[i].to_s) if i != 0
- s += numbers[i].to_s
- end
- puts "#{answer} = #{formula}"; exit
- end
- exit_no_solution
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement