英文:
Returning the lenght of a vector idiomatically
问题
我正在编写一个返回可变长度数字序列的函数:
func fib(n int) ??? {
retval := ???
a, b := 0, 1
for ; n > 0; n-- {
??? // 在这里将 a 添加到 retval
c := a + b
a = b
b = c
}
}
可以观察到返回序列的最终长度将为 n。为了实现符合 Go 语言惯用法,fib 应该如何返回?如果事先不知道长度,返回值和使用方式会有什么不同?如何将值插入到 retval 中?
英文:
I'm writing a function that returns a sequence of numbers of variable length:
func fib(n int) ??? {
retval := ???
a, b := 0, 1
for ; n > 0; n-- {
??? // append a onto retval here
c := a + b
a = b
b = c
}
}
It can be observed that the final length of the returned sequence will be n. How and what should fib return to achieve idiomatic Go? If the length was not known in advance, how would the return value, and usage differ? How do I insert values into retval?
答案1
得分: 7
这里,我们知道有多少个数字;我们想要n个斐波那契数。
package main
import "fmt"
func fib(n int) (f []int) {
if n < 0 {
n = 0
}
f = make([]int, n)
a, b := 0, 1
for i := 0; i < len(f); i++ {
f[i] = a
a, b = b, a+b
}
return
}
func main() {
f := fib(7)
fmt.Println(len(f), f)
}
输出:7 [0 1 1 2 3 5 8]
这里,我们不知道有多少个数字;我们想要所有小于或等于n的斐波那契数。
package main
import "fmt"
func fibMax(n int) (f []int) {
a, b := 0, 1
for a <= n {
f = append(f, a)
a, b = b, a+b
}
return
}
func main() {
f := fibMax(42)
fmt.Println(len(f), f)
}
输出:10 [0 1 1 2 3 5 8 13 21 34]
你也可以使用Go的向量包中的IntVector。注意type IntVector []int。
英文:
Here, we know how many numbers; we want n Fibonacci numbers.
package main
import "fmt"
func fib(n int) (f []int) {
if n < 0 {
n = 0
}
f = make([]int, n)
a, b := 0, 1
for i := 0; i < len(f); i++ {
f[i] = a
a, b = b, a+b
}
return
}
func main() {
f := fib(7)
fmt.Println(len(f), f)
}
Output: 7 [0 1 1 2 3 5 8]
Here, we don't know how many numbers; we want all the Fibonacci numbers less than or equal to n.
package main
import "fmt"
func fibMax(n int) (f []int) {
a, b := 0, 1
for a <= n {
f = append(f, a)
a, b = b, a+b
}
return
}
func main() {
f := fibMax(42)
fmt.Println(len(f), f)
}
Output: 10 [0 1 1 2 3 5 8 13 21 34]
You could also use IntVector from the Go vector package. Note that type IntVector []int.
答案2
得分: 1
不要使用Vectors,使用slices。这里有一些将各种vector操作映射为惯用的slice操作的方法。
英文:
Don't use Vectors, use slices. Here are some mapping of various vector operations to idiomatic slice operations.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论