Ruby algorithm (inject, method definition)

Introduction

I will explain the code created when learning the Ruby algorithm.

What I learned

I challenged the following technology.

What I tried

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.

Contents

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 conclusion

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

Ruby algorithm (inject, method definition)
definition of ruby method
[Ruby] Method definition summary
How to use Ruby inject method
Ruby to_s method
[Ruby] From the basics to the inject method
[Ruby] slice method
[Ruby] end_with? method
[Ruby] Method memorandum
[Ruby] initialize method
Ruby build method
Ruby accessor method
ruby map method
Ruby Learning # 30 Initialize Method
abbreviation for ruby method
Ruby Learning # 24 Exponent Method
Ruby Thread # [] = method notes
Studying at CodeWar (ruby) ⑥ inject
Integer check method with ruby
Basic knowledge in method definition
[Ruby] Notes on gets method
[Ruby] Method that returns truth
Ruby deposit system, algorithm problem
[ruby] Method call with argument
Ruby design pattern template method pattern memo
[Ruby] Method to count specific characters
[Ruby] present/blank method and postfix if.
[Ruby] Extracting elements with slice method
[Ruby basics] split method and to_s method
[Ruby] How to use any? Method
String output method memo in Ruby
[Swift] Protocol concept and definition method
[Ruby] Search problem using index method
[Ruby on Rails] Convenient helper method
[Ruby] undefined method `dark?'occurs in rqr_code