gpt4 book ai didi

sorting - Golang Sort包-模糊排序错误

转载 作者:IT王子 更新时间:2023-10-29 01:47:57 27 4
gpt4 key购买 nike

我尝试修改标准排序方法并为排序 Less 接口(interface)添加一定的随机性。当

if (u[i] - u[j]) <= 0

if u[i] < u[j]

它按预期工作但是

if (u[i] - u[j]) <= rv

条件在多次执行后产生 panic

package main
import (
"crypto/rand"
"fmt"
"math/big"
"sort"
)

type FuzzySorter []float64

func (u FuzzySorter) Len() int {
return len(u)
}
func (u FuzzySorter) Swap(i, j int) {
u[i], u[j] = u[j], u[i]
}
func (u FuzzySorter) Less(i, j int) bool {
pom, _ := rand.Int(rand.Reader, big.NewInt(int64(2)))
rv := float64(pom.Int64())
if (u[i] - u[j]) <= rv {
return true
} else {
return false
}

}
func (u FuzzySorter) Sort() FuzzySorter {
sort.Sort(u)
return u
}

func main() {
unsorted := FuzzySorter{
0,
1,
1,
1,
1,
6,
0,
4,
6,
1,
1,
1,
0,
2,
8,
1,
5,
4,
6,
6,
6,
16,
12,
6,
1,
1,
1,
0,
0,
11,
2,
14,
16,
6,
12,
0,
4,
1,
0,
16,
2,
6,
0,
0,
0,
0,
1,
11,
1,
0,
2,
1,
1,
1,
1,
0,
1,
12,
10,
1,
5,
2,
6,
4,
1,
0,
0,
11,
1,
1,
2,
2,
1,
0,
0,
1,
0,
1,
17,
2,
1,
1,
2,
0,
3,
7,
1,
5,
1,
0,
1,
0,
0,
0,
1,
3,
1,
1,
1,
2,
1,
0,
3,
1,
6,
1,
1,
0,
1,
12,
0,
1,
1,
0,
1,
0,
0,
6,
1,
2,
2,
0,
0,
2,
1,
1,
0,
4,
4,
1,
1,
1,
0,
1,
1,
1,
2,
0,
0,
1,
0,
1,
2,
1,
2,
1,
1,
0,
0,
4,
1,
0,
1,
0,
1,
1,
3,
1,
0,
}
unsorted.Sort()
fmt.Println(unsorted)

}

https://play.golang.org/p/4AxNRN4VD7

panic 信息

panic: runtime error: index out of range

goroutine 1 [running]:
panic(0x176ba0, 0x1040a010)
/usr/local/go/src/runtime/panic.go:464 +0x700
main.FuzzySorter.Less(0x10456000, 0x9f, 0x9f, 0x19, 0xffffffff, 0x4, 0x1, 0xd)
/tmp/sandbox201242525/main.go:21 +0x140
main.(*FuzzySorter).Less(0x10434140, 0x19, 0xffffffff, 0x5c, 0x1, 0x10434140)
<autogenerated>:3 +0xc0
sort.doPivot(0xfef741b0, 0x10434140, 0x19, 0x9f, 0x7, 0x19)
/usr/local/go/src/sort/sort.go:128 +0x280
sort.quickSort(0xfef741b0, 0x10434140, 0x19, 0x9f, 0xe, 0xfef741b0)
/usr/local/go/src/sort/sort.go:195 +0xa0
sort.Sort(0xfef741b0, 0x10434140)
/usr/local/go/src/sort/sort.go:229 +0x80
main.FuzzySorter.Sort(0x10456000, 0x9f, 0x9f, 0x1, 0x0, 0x0, 0x0, 0x1777a0)
/tmp/sandbox201242525/main.go:29 +0xa0
main.main()
/tmp/sandbox201242525/main.go:195 +0xc0

最佳答案

据我所知,Go 排序实现需要两个否定比较,例如。 Less(i, j)Less(j, i) 都返回 false,它将其视为相等,但不是正数。例如 Less(i, j)Less(j, i) 不能同时返回 true。因此,您可以轻松地以逻辑正确和确定性的方式获得所需的结果,只需

if (u[i] - u[j]) < -1 {
return true
} else {
return false
}

https://play.golang.org/p/VcKI9uzcM9

关于sorting - Golang Sort包-模糊排序错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36578109/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com