Advertisement
rockdrilla

wtf, rev.0

Mar 31st, 2017
553
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.81 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2. n = STDIN.readline.strip.to_i
  3. numbers = STDIN.readline.split(/\s/).compact.map(&:to_i)
  4. answer = STDIN.readline.strip.to_i
  5.  
  6. if (numbers.length != n) then
  7.   puts "array size mismatch"; exit
  8. end
  9.  
  10. def exit_no_solution(); puts "no solution"; exit; end
  11.  
  12. min = numbers.reduce(numbers[0] * 2) {|s, i| s -= i }
  13. exit_no_solution if (answer < min)
  14.  
  15. max = numbers.reduce(0) {|s, i| s += i }
  16. exit_no_solution if (answer > max)
  17.  
  18. [:-, :+].repeated_permutation(n-1) do |signs|
  19.   signs.insert(0, :+)
  20.   result = (0..n-1).each.reduce(0) do |s, i|
  21.     s = s.method(signs[i]).call(numbers[i])
  22.   end
  23.   next if result != answer
  24.   formula = (0..n-1).each.reduce("") do |s, i|
  25.     s += (" %s " % signs[i].to_s) if i != 0
  26.     s += numbers[i].to_s
  27.   end
  28.   puts "#{answer} = #{formula}"; exit
  29. end
  30. exit_no_solution
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement