3 Replies - 3128 Views - Last Post: 25 March 2012 - 01:51 AM Rate Topic: ***** 1 Votes

#1 tetroel  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 24-March 12

How do I find a minimal element of an array? Ruby gives me an error

Posted 24 March 2012 - 11:34 AM

so i have an array

m=Array.new(20)
for i in 1..20
 m[i]=rand(1001)
end
puts m.min


if i try to run it, ruby says:

Attached Image

What's wrong with my code?
Is This A Good Question/Topic? 0
  • +

Replies To: How do I find a minimal element of an array? Ruby gives me an error

#2 Atli  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 3716
  • View blog
  • Posts: 5,975
  • Joined: 08-June 10

Re: How do I find a minimal element of an array? Ruby gives me an error

Posted 24 March 2012 - 01:24 PM

*
POPULAR

You are looping through 1 to 20, assigning each element in the array at those indexes a random number. However arrays are zero-indexed, which means you are skipping the first index: 0. This is causing the min call to fail.

To fix this, loop through 0 to 19 instead.

You can also simplify this by doing:
m=Array.new(20) {|i| rand(1001)}
puts m.min


Each element in the new array will then be initialized with a random number.
Was This Post Helpful? 5
  • +
  • -

#3 xclite  Icon User is offline

  • LIKE A BOSS
  • member icon


Reputation: 899
  • View blog
  • Posts: 3,162
  • Joined: 12-May 09

Re: How do I find a minimal element of an array? Ruby gives me an error

Posted 24 March 2012 - 01:26 PM

So, arrays are indexed starting at 0. You create an array of size 20. Then you initialize the elements at index 1 to 20 to a number. Then you calculate the minimum, which includes the element at index 0...

Your array looks like this:
[nil, rand(1001), rand(1001).... and so on]

You want to change the for i in 1..20 to for i in 0..19

Atli's solution is more idiomatic, while mine just changes the numbers.

This post has been edited by xclite: 24 March 2012 - 01:26 PM

Was This Post Helpful? 3
  • +
  • -

#4 tetroel  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 24-March 12

Re: How do I find a minimal element of an array? Ruby gives me an error

Posted 25 March 2012 - 01:51 AM

Thank you guys very much!!!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1