英文:
how to reverse array | slice in golang without using for statement
问题
我正在寻找一种在Golang中反转[][]string|int
的方法,而不使用任何for
语句。
我找不到任何解决方案。我找到了这篇帖子How do I reverse a slice in go?,但每个解决方案都使用了for
语句。我知道处理这个问题的最佳方法是使用for
,但我正在寻找其他不使用for
的解决方案。
list := [][]int{
{2,3,4},
{6,8,1},
}
结果应该是这样的:[[2 3 4] [6 8 1]].
但我需要像这样的结果:[[6 8 1] [2 3 4]].
在不使用for
语句的情况下,我该怎么做?有什么想法吗?
英文:
I'm looking for a way to reverse [][]string|int
in Golang without using any for
statement.
I couldn't find any solution. I found this post How do I reverse a slice in go?, but every solution is used for
statement. I know the best way to handle this problem is using for
, but I'm looking for other solutions without having for
list := [][]int{
{2,3,4},
{6,8,1},
}
the result is like this: [[2 3 4] [6 8 1]].
but I need something like this: [[6 8 1] [2 3 4]].
What should I do without using the for
statement? Is there any idea?
答案1
得分: 1
在这里使用for
循环是最简单的解决方案。
PS:你可以尝试使用硬编码的解决方案,像这样:
list2 := [][]int{list[1], list[0]}
但这更像是一个hack而不是解决方案,
所以最好使用基于for
循环的简洁而优雅的编程解决方案。
英文:
Using for
loop here - is the simplest solution.
PS: You can try to use hardcoded solution like this one:
list2 := [][]int{list[1], list[0]}
but it's rather hack than solution,
<br>so better to use nice and concise programmatic solution base on for
loop.
答案2
得分: 1
不使用for语句,你可以考虑使用递归调用或者goto语句来实现相同的功能。
递归调用的示例代码如下:
package main
import (
"fmt"
)
func main() {
list := [][]int{
{2, 3, 4},
{6, 8, 1},
}
reverse(list)
fmt.Println(list)
}
func reverse(d [][]int) {
j := len(d) - 1
i := 0
var h func()
h = func() {
if i < j {
d[i], d[j] = d[j], d[i]
i, j = i+1, j-1
h()
}
}
h()
}
使用goto语句的示例代码如下:
package main
import (
"fmt"
)
func main() {
list := [][]int{
{2, 3, 4},
{6, 8, 1},
}
reverse(list)
fmt.Println(list)
}
func reverse(d [][]int) {
j := len(d) - 1
i := 0
START:
if i < j {
d[i], d[j] = d[j], d[i]
i, j = i+1, j-1
goto START
}
}
如果你已经阅读到这里,可以参考这个常规解决方案:https://stackoverflow.com/a/28058324/4466350
英文:
> What should I do without using the for statement? Is there any idea?
recursive calls
package main
import (
"fmt"
)
func main() {
list := [][]int{
{2, 3, 4},
{6, 8, 1},
}
reverse(list)
fmt.Println(list)
}
func reverse(d [][]int) {
j := len(d) - 1
i := 0
var h func()
h = func() {
if i<j {
d[i], d[j] = d[j], d[i]
i, j = i+1, j-1
h()
}
}
h()
}
goto statements
package main
import (
"fmt"
)
func main() {
list := [][]int{
{2, 3, 4},
{6, 8, 1},
}
reverse(list)
fmt.Println(list)
}
func reverse(d [][]int) {
j := len(d) - 1
i := 0
START:
if i < j {
d[i], d[j] = d[j], d[i]
i, j = i+1, j-1
goto START
}
}
if you read that far, read about a regular solution https://stackoverflow.com/a/28058324/4466350
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论