Created
January 3, 2022 17:00
-
-
Save meesterdude/aa9bbb58d354100b4725bd4cbc530706 to your computer and use it in GitHub Desktop.
problem: find all pairs of numbers in a range of 1..n that add up to n
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
# $ time ruby total_pairs.rb | |
# there are 999 pairs that create 2000 between 1 and 2000 | |
# real 0m0.129s | |
# user 0m0.074s | |
# sys 0m0.046s | |
max_size = 2000 | |
numbers = (1..max_size).to_a | |
numbers.delete_at(-1) unless numbers.size.even? | |
split_size = numbers.size / 2 | |
above = numbers[..split_size - 1] | |
below = numbers[split_size..].reverse! | |
above.delete_at(-1) | |
below.delete_at(0) | |
# the remaining split arrays are the valid combinations that can result in the numbers total | |
# so it's just the array size to get the count, or [above[i], below[i]] to get the pairs | |
print "there are #{below.size} pairs that create #{numbers.size} between #{numbers.first} and #{max_size}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment