生成一个整数范围的数组。

huangapple go评论81阅读模式
英文:

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 &gt;= lo; hi-- {
	s[hi-len(s)+1] = hi
}

Or incrementing lo:

for ; lo &lt;= 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
}

huangapple
  • 本文由 发表于 2016年3月1日 00:48:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/35704948.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定