I will explain the code created when learning the Ruby algorithm.
I challenged the following technology.
Use two arrays with 10 numbers each. Compare the 1st, 1st to 2nd sum, 3rd sum ... of each array, Write code to show which is larger.
First of all, anything is fine, so prepare two arrays.
a = [1,2,3,4,5,6,7,8,9,10]
b = [10,2,2,2,2,2,2,2,2,2]
next Create a method to find the sum of the arrays. There are various methods, but here we will use the inject method.
def sum(array,n)
sum = array[0,n].inject(:+)
return sum
end
In the part of ʻarray [0, n] .inject (: +)`, the sum of the 1st to n + 1th of the array assigned as an argument is calculated.
Finally, the above process is executed for all the elements of the array, and the magnitude is judged each time.
(1..10).each{|i|
if sum(a,i) > sum(b,i)
puts "#{i}: A is large"
elsif sum(a,i) < sum(b,i)
puts "#{i}: B is large"
else
puts "#{i}:equal"
end
}
The total is as follows.
a = [1,2,3,4,5,6,7,8,9,10]
b = [10,2,2,2,2,2,2,2,2,2]
def sum(array,n)
ans = array[0,n].inject(:+)
return ans
end
(1..10).each{|i|
if sum(a,i) > sum(b,i)
puts "#{i}: A is large"
elsif sum(a,i) < sum(b,i)
puts "#{i}: B is large"
else
puts "#{i}:equal"
end
}
that's all.
In addition to learning how to use the inject method newly in this code, I realized that it is possible to compare the size of method return values. In the future, I would like to continue to acquire new knowledge and pursue new ways of using the knowledge I already know.
Recommended Posts