Q. Elevator (Ruby edition)
Elevator floor calculation problem (Ruby edition)
problem
Complete a program that calculates how many floors the elevator has traveled.
However, the elevator must initially be on the ground floor.
Example
From the 1st floor to the 3rd floor → 2nd floor has been moved, so a total of 2nd floor
From the 3rd floor to the 1st floor → 2 floors have been moved, so a total of 4 floors
From the 1st floor to the 4th floor → 3 floors have been moved, so a total of 7 floors
Value to be entered
The input is given in the following format.
N
f_1
...
f_N
-The first line is given an integer N that indicates the number of lines in the log.
・ In the following N lines, the floor f_i (1 ≤ i ≤ N) where the elevator stopped is entered in order as an integer.
• The total input is N + 1 lines, with one line break at the end of the last line.
Expected output
Please output the number of floors the elevator has moved as an integer.
Input example 1
3
3
1
4
Output example 1
7
My answer (I referred to the volunteer site)
python
n = gets.to_i
i = 1
s = 0
n.times {
a = gets.to_i
s += (a - i).abs
i = a
}
puts s
There is no mistake in the output result with this, but I did not understand the contents of {} so I wrote it as an article. It is repeated for any input value in n.times, but I did not understand why s + = (a --i) .abs </ font> on the 6th line is like this. .. If you apply all the arbitrary numbers, it becomes "0 + = (3-1) .abs". It doesn't make any sense. Also, the i = a </ font> on the 7th line is like 1 = 3 when applied. Why is this happening? I did a lot of research on the process of repeating gets.to_i when I don't know how many arbitrary input values there are like this time, but the number of applicable sites is quite small, and it was a difficult code for me as a beginner. I understand each method, but I found that I couldn't write the code like line 6.7 this time with my own knowledge, probably because I didn't have a programming brain. But I don't know, so there is fun there.
that's all!