Conditional numerical calculation

The condition this time is ・ Sum all the numbers in the array ・ However, if the numbers are the same, they will not be calculated.

(Example) array1 = [1, 2, 3] sum1 = 1 + 2 + 3 = 6

array2 = [2, 4, 2] sum2 = 4

array3 = [3, 3, 3] sum3 = 0

something like.

  1. Define an empty array to make the sumizable numbers into an array. image.png

  2. Assign each method argument (array) to the block variable i.

In 3.2, assign each method argument (array) to the block variable n. Then, when "i = n", 1 is added to the count defined in 2. image.png

  1. Add the variable i to the array uniq_nums only when the count is less than 2, that is, 1. image.png

  2. Substitute each array uniq_nums into the block variable uniq_num and add it to sum = 0. And finally, sum is output to complete the method. image.png

  3. Whole code image.png

For example, if it is an array [1,2,3] When i = 1, it is compared with n = 1,2,3, and count is incremented by 1 only when the numerical value is 1. The same applies to 2 and 3. Since each passed the conditions and was assigned to the array uniq_nums, it is calculated as 5 above and becomes 6.

that's all.

I don't know what it can be applied to.

Recommended Posts

Conditional numerical calculation
Object-oriented numerical calculation
Is WebAssembly really fast? [Numerical calculation]
Ruby / Rust linkage (3) Numerical calculation with FFI
Ruby / Rust linkage (4) Numerical calculation with Rutie
Ruby / Rust linkage (5) Numerical calculation with Rutie ② Bezier