Last active
September 22, 2015 14:44
-
-
Save makevoid/dcf4736f8de7083323c6 to your computer and use it in GitHub Desktop.
Fun math operators challenge solved with programming
This file contains hidden or 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
| # problem: figure out the operations | |
| # | |
| # expression: | |
| # | |
| # "7 # 7 # 77 # 7 # 7 = 497" | |
| # I'm not good at math so I made this program to solve the problem | |
| operators = %w(+ - * /) | |
| values = [7, 7, 77, 7, 7] | |
| expected_result = 497 | |
| loop do | |
| operations = ["+"] | |
| (values.length-1).times do | |
| operations << operators.sample | |
| end | |
| result = 0 | |
| values.each_with_index do |val, idx| | |
| result = result.send operations[idx], val | |
| end | |
| if result == expected_result | |
| puts "\noperations are: #{operations[1..-1].inspect}" | |
| break | |
| end | |
| print "." | |
| end | |
| # run this program to see the result |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
here's the program running online: http://opalrb.org/try/?code:operators%20%3D%20%25w(%2B%20-%20*%20%2F)%0Avalues%20%3D%20%5B7%2C%207%2C%2077%2C%207%2C%207%5D%0Aresult%20%3D%20497%0A%0Aloop%20do%0A%20%20operations%20%3D%20%5B%22%2B%22%5D%0A%20%20(values.length-1).times%20do%0A%20%20%20%20operations%20%3C%3C%20operators.sample%0A%20%20end%0A%20%20result%20%3D%200%0A%20%20values.each_with_index%20do%20%7Cval%2C%20idx%7C%0A%20%20%20%20result%20%3D%20result.send%20operations%5Bidx%5D%2C%20val%0A%20%20end%0A%20%20if%20result%20%3D%3D%20497%0A%20%20%20%20puts%20%22%5Cnoperations%20are%3A%20%23%7Boperations%5B1..-1%5D.inspect%7D%22%0A%20%20%20%20break%0A%20%20end%0A%0A%20%20print%20%22.%22%0Aend