As part of learning Ruby, we will challenge "competitive programming (competitive professional)". We will output what we have learned in the learning for that purpose. This time from the sixth question (Some Sums) of "At Coder Beginners Selection". https://atcoder.jp/contests/abs

Of integers between 1 and N Find the sum of things that are greater than or equal to A and less than or equal to B in decimal notation.

Constraint 1 ≤ N ≤ 10,000 1 ≤ A ≤ B ≤ 36 All inputs are integers

The input is given in the following form.

```
N A B
#Example
20 2 5
```

```
Output example
#In the case of the above example
=> 84
```

Of the integers of 20 or less, the sum of each digit is 2 or more and 5 or less. It is 2,3,4,5,11,12,13,14,20. Outputs 84, which is the sum of these.

First of all, from my answer.

```
n, a, b = gets.split(" ").map(&:to_i)
r = 0
(1..n).each do |i|
r += i if i.to_s.split("").map(&:to_i).inject(:+).between?(a, b)
end
print r
```

The methods I learned while answering this question are summarized below.

I used to use it when I received input, By using it in each statement this time, I was able to recognize it as a method of the String class again. The answer is to convert it to String type once, use the split method, and then return it to Integer type.

```
#Example
print "1234".split("")
=> ["1", "2", "3", "4"]
```

```
self.between?(min, max)
#self is between min and max (min,Returns true if (including max)
#Example
print 6.between?(1, 5)
=> false
```

Using this method, which specifies the minimum and maximum values and returns true if self is within that range, It is judged whether the sum of each digit is within the range of a or more and b or less.

Let's see the other person's answer.

```
n, a, b = gets.split.map(&:to_i)
puts (1..n).select{|e|(a..b).include?(e.to_s.chars.map(&:to_i).inject(&:+))}.inject(&:+)
```

Up to the point of receiving the input, it is almost the same as answer ①. Looking at the flow after that, (1) Use the include? Method to determine whether the sum of each digit of the integer is greater than or equal to a and less than or equal to b. (2) For integers that have passed (1), use the select method to create a new array and add it to it. (3) When all the integers that meet the conditions are available, use the inject method at the end to find the sum of the integers and output them.

Here is a brief summary of the methods used here.

Returns true if the object is within range.

```
#Example
print (1..5).include?(4)
=> true
```

Gets the elements that match the criteria and returns them as a new array.

```
#Example
print [1,2,3,4,5].select { |num| num > 3 }
=> [4, 5]
```

So far, I have introduced the methods I learned while solving AtCoder Beginners Selection [Some Sums].

If you have any mistakes, I would be grateful if you could point them out.

Recommended Posts