Reputation: 195
nums = [4, 6, 8, 7]
until num[index] == nil
if num[index] > num[index + 1]
puts num[index]
index += 1
elsif
index = index + 1
end
For some reason, the output I get is:
8
Traceback (most recent call last):
1: from main.rb:21:in <main>' main.rb:21:in
>': comparison of Integer with nil failed (ArgumentError)
Not sure how to fix the code to not get the ArgumentError.
Upvotes: 0
Views: 87
Reputation: 110675
We should of course keep the computational complexity to O(nums.size
) (by making a single pass through the array). My friend @Sergio points out that there can be nothing simpler than
nums.max
#=> 8
which uses the method Array#max. This would also work well at Code Golf.
Upvotes: 2
Reputation: 158
This should work, it'll return the largest in the array:
nums = [4, 6, 8, 7]
index=0
until index==nums.length-1 #
if nums[index] > nums[index + 1]
largest= nums[index]
index += 1
else
index = index + 1
end
end
puts largest
Upvotes: 0