问题描述
我一直在尝试HackerRank,其中问题经常需要将整数行读入数组(切片)中.
I have been giving HackerRank a try where the problems often require reading lines of integers into arrays (slices).
对于许多问题,我的解析代码最终要比解决方案的算法要大.例如,在 Sherlock和数组
For many of the problems, my parsing code ends up being larger than the algorithmic meat of the solution. For instance, that was the case in Sherlock and Array
关于如何将以空格分隔的整数行简洁地解析为切片的任何想法? fmt.Scanf
不支持切片,当使用bufio
时,我得到了很长的解决方案.
Any ideas on how to concisely parse a space-separated line of integers into a slice? fmt.Scanf
doesn't support slices and when using bufio
I get long solutions.
一些要求:
- 您只能使用标准库.
- 解决方案应该简洁明了,越短越好.
- 不应跳过错误检查.我知道输入在HackerRank中定义良好,您应该可以偷工减料,但是请不要这样做,这是一个不好的做法.
- 应该合理有效.
注意:解析器应该只消耗一行,而不消耗全部输入.
NOTE:The parser should only consume a single line and not the full input.
推荐答案
好吧,我也做了一些hackerrank问题,这就是我想出的.通常,问题始于数组中的项目数:
Well, I have done some hackerrank problems too, and here is what I came up with. Typically, problems start with the number of items in the array:
func main() {
var N int
fmt.Scanf("%d", &N)
line := make([]int, N)
for i, _ := range line {
fmt.Scanf("%d", &line[i])
}
// Do something with the values
}
这篇关于简洁健壮的方式在Go中读取以空格分隔的整数行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!