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

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

Generate array with with range of integers

问题

我有两个值:

> [3:6]

我试图在Golang中尝试一些操作,但是我找不到一个好的方法来根据这些值创建一个数组。

这是我想要实现的:

  1. [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:

  1. [3,4,5,6]

答案1

得分: 5

你可以使用for ... range结构使代码更简洁,甚至可能更快:

  1. lo, hi := 3, 6
  2. s := make([]int, hi-lo+1)
  3. for i := range s {
  4. s[i] = i + lo
  5. }

作为一种好奇,循环可以在没有循环变量的情况下实现,但速度会较慢,代码也会更长。通过递减hi

  1. for ; hi >= lo; hi-- {
  2. s[hi-len(s)+1] = hi
  3. }

或者递增lo

  1. for ; lo <= hi; lo++ {
  2. s[len(s)-1-hi+lo] = lo
  3. }
英文:

You can make use of the for ... range construct to make it more compact and maybe even faster:

  1. lo, hi := 3, 6
  2. s := make([]int, hi-lo+1)
  3. for i := range s {
  4. s[i] = i + lo
  5. }

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:

  1. for ; hi &gt;= lo; hi-- {
  2. s[hi-len(s)+1] = hi
  3. }

Or incrementing lo:

  1. for ; lo &lt;= hi; lo++ {
  2. s[len(s)-1-hi+lo] = lo
  3. }

答案2

得分: 0

我正在寻找一个类似的答案,@icza的答案是一个很好的起点。最终,我根据icza的答案创建了一个辅助函数:

  1. func createNumbers(lo int, hi int) []int {
  2. s := make([]int, hi-lo+1)
  3. for i:= range s {
  4. s[i] = i + lo
  5. }
  6. return s
  7. }
英文:

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:

  1. func createNumbers(lo int, hi int) []int {
  2. s := make([]int, hi-lo+1)
  3. for i:= range s {
  4. s[i] = i + lo
  5. }
  6. return s
  7. }

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:

确定