Skip to content

Instantly share code, notes, and snippets.

@abelmartin
Created March 26, 2012 05:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abelmartin/2203155 to your computer and use it in GitHub Desktop.
Save abelmartin/2203155 to your computer and use it in GitHub Desktop.
Alg for Rubyque question #
# 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
@dghollingsworth
Copy link

nice code.

@caseydm
Copy link

caseydm commented Jun 16, 2014

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