Created
March 26, 2012 05:18
-
-
Save abelmartin/2203155 to your computer and use it in GitHub Desktop.
Alg for Rubyque question #
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
# For RubyQue question: http://rubeque.com/problems/home-on-the-range | |
def find_range | |
min = 0 | |
default_max = 99 | |
max = default_max | |
goal = 4494 | |
while min <= max | |
current_sum = (1..100).to_a[min..max].reduce(:+) | |
if current_sum == 4494 | |
#We found it! | |
break | |
elsif current_sum > goal | |
#Reduce the max | |
max -= 1 | |
else #current_sum < goal | |
#Reset the max and increment the min. | |
min += 1 | |
max = default_max | |
end | |
end | |
puts "FOUND it. MIN: #{min} MAX: #{max}" if min <= max | |
puts "NO CLUE!!" if min >= max | |
end | |
puts find_range |
I just worked through this same problem and used the following code to solve the problem:
def finder(target)
arr = (1..100).to_a
arr.each do |i|
arr.each do |x|
if arr[i..x].reduce(:+) == target
return puts "Range is #{i}..#{x}"
end
x += 1
end
i += 1
end
end
finder(4494)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice code.