1. Conclusion </ b>
2. How to code </ b>
Use arrays, each methods, if statements </ b>!
def any_three_sum(array)
unique_nums = [] #---❶
array.each do |num| #---❷
count = 0
array.each do |i| #---❸
if num == i
count += 1
end
end
if count < 2 #---❹
unique_nums << num
end
end
three_sum = 0 #---❺
unique_nums.each do |unique_num|
three_sum += unique_num
end
puts three_sum
end
First of all, I am coding a program that retrieves numbers that are not covered. For example, consider any_three_sum ([4,3,4]).
❶: We have prepared a box to put unique numbers in the array. Use it again in ❺.
❷: num = 4, num = 3, num = 4, and each is taken out.
❸: If the number taken out in ❷ and the number in ❸i = [4,3,4] are the same, count is set to +1. I am doing important coding when duplicating ❹.
❹: When count <2, it is included in the array in unique_nums. Since count counts duplicate numbers, if num = 4, count = 2, so it is not added to unique_sums. So num = 3 is added to unique_sums.
❺: Since only unique_sums = [3], puts three_sum will be “3”. The values of unique_sums are taken out (= each) and all are summed (the first and second numbers are also reflected by three_sum + =) and assigned to the three_sum variable.
Recommended Posts