This time I often use standard input for programming problems, so I'll leave a note. The language used is Ruby.
Standard input
Tokyo
line = gets
p line
Output result
"Tokyo"
Standard input
Tokyo Osaka Kyoto
line = gets.split(' ')
p line
Output result
["Tokyo", "Osaka", "Kyoto"]
By using the split method, the three elements are stored in the array as separate ones.
Standard input
Tokyo
Osaka
Kyoto
line = readlines
len = line.length
i = 0
while i < len
line[i] = line[i].chomp
i += 1
end
p line
Output result
["Tokyo", "Osaka", "Kyoto"]
A concise way to write the above is to use the map method.
Standard input
Tokyo
Osaka
Kyoto
line = readlines.map(&:chomp)
p line
Output result
["Tokyo", "Osaka", "Kyoto"]
Standard input
Tokyo Osaka Kyoto
Japan USA China
line = readlines
len = line.length
i = 0
while i < len
line[i] = line[i].chomp.split(' ')
i += 1
end
p line
Output result
[["Tokyo", "Osaka", "Kyoto"], ["Japan", "USA", "China"]]
There is also the following as a concise way of writing the above
Standard input
Tokyo Osaka Kyoto
Japan USA China
lines = []
while line = gets
lines << line.chomp.split(' ')
end
p lines
Output result
[["Tokyo", "Osaka", "Kyoto"], ["Japan", "USA", "China"]]
By setting while line = gets, it will be repeated until all the standard input values are acquired.
Standard input
Tokyo Osaka Kyoto
Japan USA China
lines = readlines(chomp: true).map{|line| line.split(' ')}
p lines
Output result
[["Tokyo", "Osaka", "Kyoto"], ["Japan", "USA", "China"]]
Looking at the output result, the received value is a character string, so if you want to receive a numerical value, do as follows
Standard input
123
line = gets.to_i
p line
Output result
123
Standard input
1 2 3
line = gets.split(' ')
p line
Output result
["1", "2", "3"]
If this is left as it is, it will be treated as a character string, so use map to convert it to a numeric type array.
Standard input
1 2 3
line = gets.split(' ').map(&:to_i)
p line
Output result
[1, 2, 3]
Standard input
1
2
3
line = readlines.map(&:to_i)
p line
Output result
[1, 2, 3]
Standard input
1 2 3
4 5 6
lines = []
while line = gets
lines << line.chomp.split(' ').map(&:to_i)
end
p lines
Output result
[[1, 2, 3], [4, 5, 6]]
Here's how to write more concisely
Standard input
1 2 3
4 5 6
lines = readlines(chomp: true).map{|line| line.split(' ').map(&:to_i)}
p lines
Output result
[[1, 2, 3], [4, 5, 6]]
I think there are various other methods, so I will update them from time to time.
Recommended Posts