I'm attempting to solve http://projecteuler.net/problem=1.
I want to create a method which takes in an integer and then creates an array of all the integers preceding it and the integer itself as values within the array.
Below is what I have so far. Code doesn't 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)
Unlike other programming languages like Java, Ruby only has dynamic arrays but no static arrays.
Ruby | Array class first() function first() is a Array class method which returns the first element of the array or the first 'n' elements from the array.
(1..num).to_a
is all you need to do in Ruby.
1..num
will create a Range
object with start at 1
and end at whatever value num
is. Range
objects have to_a
method to blow them up into real Arrays
by enumerating each element within the range.
For most purposes, you won't actually need the Array
- Range
will work fine. That includes iteration (which is what I assume you want, given the problem you're working on).
That said, knowing how to create such an Array
"by hand" is valuable learning experience, so you might want to keep working on it a bit. Hint: you want to start with an empty array ([]
) instead with Array.new num
, then iterate something num.times
, and add numbers into the Array
. If you already start with an Array
of size num
, and then push num
elements into it, you'll end up with twice num
elements. If, as is your case, you're adding elements while you're iterating the array, the loop never exits, because for each element you process, you add another one. It's like chasing a metal ball with the repulsing side of a magnet.
To answer the Euler Question:
(1 ... 1000).to_a.select{|x| x%3==0 || x%5==0}.reduce(:+) # => 233168
Sometimes a one-liner is more readable than more detailed code i think.
Assuming you are learning Ruby by examples on ProjectEuler, i'll explain what the line does:
(1 ... 1000).to_a
will create an array with the numbers one to 999. Euler-Question wants numbers below 1000. Using three dots in a Range will create it without the boundary-value itself.
.select{|x| x%3==0 || x%5==0}
chooses only elements which are divideable by 3 or 5, and therefore multiples of 3 or 5. The other values are discarded. The result of this operation is a new Array with only multiples of 3 or 5.
.reduce(:+)
Finally this operation will sum up all the numbers in the array (or reduce it to) a single number: The sum you need for the solution.
What i want to illustrate: many methods you would write by hand everyday are already integrated in ruby, since it is a language from programmers for programmers. be pragmatic ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With