Let's create a method that outputs the sum of any three numbers. However, if the same number is included It does not count towards the total.

- If you don't understand, use the API to solve the problem. Reference URL: https://docs.ruby-lang.org/ja/search/

lone_sum([1, 2, 3]) → 6 lone_sum([3, 2, 3]) → 2 lone_sum([3, 3, 3]) → 0

The question this time was a difficult and completely misguided answer! I wasn't sure that the arguments were arrays. However, when an array appears as a tendency, each statement feels like an iron plate.

Below is the answer.

```
def lone_sum(ary)
#Extract only unique elements from the array
uniq_nums = []
ary.each do |num|
count = 0
ary.each do |i|
if num == i
count += 1
end
end
if count < 2
uniq_nums << num
end
end
# uniq_Total in nums array
sum = 0
uniq_nums.each do |unique_num|
sum += unique_num
end
puts sum
end
```

For example, consider calling a method with lone_sum ([3, 2, 3]). ① ary = [3,2,3] ②ary.each do |num|Then, take out the contents of the array one by one. ③ The first number taken out is 3, so num = 3. ④ The second each statement, ary.each do |i|Then i= 3,2,It becomes 3. ⑤ When the conditional expression if num (3 is taken out) == i, that is, when they are duplicated, the count increases. (6) Add a value to the uniq_nums array only when there is one duplicate value in the 11th line. When num = 3, count = 2, so no value is added to the uniq_nums array. ⑦ As a result of repeating this two more times, only 2 is added to the uniq_nums array. ⑧ The sum in the uniq_nums array is written with sum = 0 or less. ⑨ In this case, sum = sum + 2, that is, sum = 0 + 2. Finally the total is output as 2.

I understand, but how long will it take to reach a level where this can be solved in the future? If anyone knows what kind of study method can be used to get closer to the correct answer, please let me know. For the time being, all I can do is study.

Recommended Posts