How to populate an array with increasing Ruby values

I am trying to solve http://projecteuler.net/problem=1 .

I want to create a method that takes an integer, and then creates an array of all the integers preceding it, and an integer as the values ​​in the array.

Below I am still. The code does not work.

def make_array(num) numbers = Array.new num count = 1 numbers.each do |number| numbers << number = count count = count + 1 end return numbers end make_array(10) 
+4
source share
2 answers

(1..num).to_a is all you need to do in Ruby.

1..num will create a Range object with a start at 1 and end with any num value. Range objects have a to_a method to explode them into real Arrays by listing each element within the range.

For most purposes, you really don't need Array - Range . This includes iteration (this is what I am assuming you want, given the problem you are working on).

However, knowing how to create such an Array β€œmanually” is a valuable learning experience, so you may need to work a bit on this. Hint: you want to start with an empty array ( [] ) instead of Array.new num , then repeat something num.times and add numbers to Array . If you already start with an Array size num , and then insert num elements into it, you end up with two num elements. If, as in your case, you add elements during iteration of the array, the loop never ends, because for each element that you process, you add one more. It's like chasing a metal ball with the repulsive side of a magnet.

+8
source

To answer Euler's question:

 (1 ... 1000).to_a.select{|x| x%3==0 || x%5==0}.reduce(:+) # => 233168 

Sometimes a single-line font is more readable than the more verbose code that I think.

Assuming you are learning Ruby with ProjectEuler examples, I will explain what the line does:

 (1 ... 1000).to_a 

will create an array with numbers from 1 to 999. Euler-Question wants numbers below 1000. Using three points in the range will create it without the most boundary value.

 .select{|x| x%3==0 || x%5==0} 

selects only those elements that are divisible by 3 or 5 and therefore multiplied by 3 or 5. The remaining values ​​are discarded. The result of this operation is a new array with short values ​​of 3 or 5.

 .reduce(:+) 

Finally, this operation sums all the numbers in the array (or reduces them) by one number: the amount needed to solve.

What I want to illustrate: many of the methods that you write manually every day are already integrated into the ruby, as it is a programmer language for programmers. be pragmatic;)

+2
source

All Articles