英文:
Generate array with with range of integers
问题
我有两个值:
> [3:6]
我试图在Golang中尝试一些操作,但是我找不到一个好的方法来根据这些值创建一个数组。
这是我想要实现的:
[3,4,5,6]
英文:
I have two values:
> [3:6]
I was trying to play something around in Golang but I can't manage to find a good method to create an array according to those values.
This what I would like to achieve:
[3,4,5,6]
答案1
得分: 5
你可以使用for ... range
结构使代码更简洁,甚至可能更快:
lo, hi := 3, 6
s := make([]int, hi-lo+1)
for i := range s {
s[i] = i + lo
}
作为一种好奇,循环可以在没有循环变量的情况下实现,但速度会较慢,代码也会更长。通过递减hi
:
for ; hi >= lo; hi-- {
s[hi-len(s)+1] = hi
}
或者递增lo
:
for ; lo <= hi; lo++ {
s[len(s)-1-hi+lo] = lo
}
英文:
You can make use of the for ... range
construct to make it more compact and maybe even faster:
lo, hi := 3, 6
s := make([]int, hi-lo+1)
for i := range s {
s[i] = i + lo
}
As a matter of curiosity, the loop can be implemented without a loop variable, but it will be slower, and the code longer. By decrementing hi
:
for ; hi >= lo; hi-- {
s[hi-len(s)+1] = hi
}
Or incrementing lo
:
for ; lo <= hi; lo++ {
s[len(s)-1-hi+lo] = lo
}
答案2
得分: 0
我正在寻找一个类似的答案,@icza的答案是一个很好的起点。最终,我根据icza的答案创建了一个辅助函数:
func createNumbers(lo int, hi int) []int {
s := make([]int, hi-lo+1)
for i:= range s {
s[i] = i + lo
}
return s
}
英文:
I was looking for a similar answer and @icza's answer was a great start. I ended up creating a helper function based on icza's answer:
func createNumbers(lo int, hi int) []int {
s := make([]int, hi-lo+1)
for i:= range s {
s[i] = i + lo
}
return s
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论