Guest User

Untitled

a guest
Jan 22nd, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.94 KB | None | 0 0
  1. if (ARGV.length != 4)
  2. puts 'Usage: ruby comp24.rb <num1> <num2> <num3> <num4>'
  3. exit
  4. end
  5.  
  6. input = ARGV.map {|s| s.to_f }
  7. puts "Number List: #{input.inspect}"
  8.  
  9. #now start...
  10. results=[]
  11. lists = input.permutation(4).to_a
  12.  
  13. def for24(list,results)
  14. ops=['+','-','*','/']
  15. ops.each do |op|
  16. exp1="(#{list[0]}#{op}#{list[1]})"
  17. if(list.length == 2)
  18. results << exp1 if eval(exp1)==24
  19. else
  20. for24([exp1].concat(list[2,4]),results) if (0..24).to_a.include?(eval(exp1))
  21. if list.length == 3
  22. exp2="(#{list[1]}#{op}#{list[2]})"
  23. for24([list[0],exp2],results) if (0..24).to_a.include?(eval(exp2))
  24. end
  25. end
  26. end
  27. end
  28.  
  29. lists.each do |list|
  30. for24(list,results)
  31. end
  32. #compute end....
  33. #puts results.inspect
  34.  
  35. if (results.length == 0)
  36. puts "No solution!"
  37. else
  38. puts "Solutions:"
  39. results.sort.uniq.each {|r| puts r.gsub(/\.0/,'')[1..-2]}
  40. end
Add Comment
Please, Sign In to add comment