Karen
Karen

Reputation: 195

how to find largest value in an array without using any enumerables?

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

Answers (3)

Cary Swoveland
Cary Swoveland

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

PhiAgent
PhiAgent

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

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33420

You could use sort plus last:

[4, 6, 8, 7].sort.last # 8

both Array methods.

Upvotes: 2

Related Questions