This time, we will calculate the difference between the two numbers in the array.
You want to know how many daily temperatures change from the highest and lowest temperatures in the weather forecast to manage your physical condition.
Since the maximum temperature t and the minimum temperature u of a day are input separated by spaces, output how many temperatures are changing in a day.
For example, if you enter the following, it means that the maximum temperature is 7 degrees and the minimum temperature is -3 degrees.
7 -3
Since the temperature difference is 10, output as follows.
10
input_line = gets.split(' ').map(&:to_i)
#Make an array before and after
before_after = input_line.each_cons(2)
before_after.each do |ba|
puts (ba[1] - ba[0]).abs
end
#↓ Same meaning(Disassemble and fix for easy understanding)
before_after.each do |a, b|
puts (b - a).abs
end
input_line = gets.split(' ').map(&:to_i)
-Get the input value with the gets method -Split the elements of the array with the split method separated by commas -The map method takes out the elements one by one and converts them to integers.
before_after = input_line.each_cons(2)
-Each_cons (2) can be obtained by shifting two consecutive elements one by one.
before_after.each do |a, b|
puts (b - a).abs
end
-Calculate the difference by substituting the two elements into the ʻa, b` variables -Convert to absolute value with ads method
finds
[[1, 2], [2, 3], [3, 4], [4, 5]]from
[1, 2, 3, 4, 5]Method 1 so not very useful in this case With each_slice (2), you can find
10 3 via
[[7, -3], [5, 2]] when multiple continuations such as
7 -3 5 2`. ..a, b = gets.split.map &:to_i
puts (a - b).abs
#If you force it to write in one line
puts gets.split.map(&:to_i).inject(:-)
a, b = gets.split.map &:to_i
・ Since this time we are limited to two elements, we divide the variables into ʻa and b`. -Get the input value with the gets method -Split the elements of the array with the split method -The map method takes out the elements one by one and converts them to integers.
puts (a - b).abs
Calculate the difference between ʻa and b` and convert it to an absolute value with the ads method.
I was able to calculate with this description, but I couldn't understand the end, so I would appreciate it if you could teach me.
Thank you for your professor this time as well. It will be a great learning experience as you will be able to discover and point out various things by sending them out. We will continue to send messages!
Recommended Posts