Little by little output of what I learned through the recently started Codewar
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in. Note: If the number is a multiple of both 3 and 5, only count it once. Also, if a number is negative, return 0(for languages that do have them)
Create a method that sums numbers less than 10 and is a multiple of 3 and 5 and returns that value. If the number is a multiple of both 3 and 5 (a multiple of 15), count only once.
Almost almost FizzBuzz's answer. https://qiita.com/Fendo181/items/425293e8e638d7fd7cea
def solution(number)
i = 1
nums_array = []
number -= 1
number.times do
nums_array << i
i += 1
end
sum = 0
nums_array.each do |num|
if num % 3 == 0 && num % 5 == 0
sum += num
elsif num % 3 == 0
sum += num
elsif num % 5 == 0
sum += num
end
end
sum
end
"I see" and "What is this?" Are mixed.
def solution(number)
(1...number).select {|i| i%3==0 || i%5==0}.inject(:+)
end
(1...number)
As you can see in the problem statement, I'm searching for the corresponding multiple with a number less than ** 10, so I'm giving it as 1 ... 10
, which does not include the last number. By the way, if you want to include the last number, use 1..10
and two commas.
select {|i| i%3==0 || i%5==0}
Each element is evaluated in blocks by select, and elements that are multiples of 3 or 5 are extracted. Even if this is a multiple of 15, it will not be counted twice.
inject(:+)
inject is a method that repeats like each and map. That is, we are trying to add the results of extracting elements that are multiples of 3 or 5 in order. It seems that iterative calculations are often used.
https://blog.toshimaru.net/ruby-inject/
Array object.inject {|initial value,element|Block processing}
array = 1..6
array.inject (0){ |sum,num| p sum+=num}
=>1
3
6
10
15
21
#inject(0)0 sets the initial value of sum.
#However, since the default argument setting of inject is 0, it can be omitted as shown below.
#num is an element of array
If you pass the operator as a symbol, you can abbreviate it as follows.
array = 1..10
array.inject {|sum,num| sum+=num}
=> 55
#Same result even if omitted
array = 1..10
array.inject(:+)
=> 55
I used to try to calculate in that block using the ʻeach method`, but in the future I will use the inject method when calculating by iterative processing! !! !!
Recommended Posts