Go lang sort a 2D Array of variable size

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

Go lang sort a 2D Array of variable size

问题

我想在golang中对一个二维数组进行排序,例如:

        {40, 100, 20},
		{30, 100},
		{40, 10},
		{30, 100, 80},
		{30, 60},
		{30, 80},
		{100, 20},
		{10, 80},
		{50, 30},

我参考了这个go playground的例子。在上面的情况下它工作得很好,但是如果我改变数组的顺序如下:

	    {40, 100, 20},
		{40, 10},
		{30, 100},
		{30, 100, 80},
		{30, 60},
		{30, 80},
		{100, 20},
		{10, 80},
		{50, 30},

有时会出现以下错误:

panic: runtime error: index out of range [2] with length 2

有什么建议,为什么它在某些情况下工作正常而在其他情况下不工作?

谢谢!

英文:

I would like to sort a 2D array in golang, for e.g:

        {40, 100, 20},
		{30, 100},
		{40, 10},
		{30, 100, 80},
		{30, 60},
		{30, 80},
		{100, 20},
		{10, 80},
		{50, 30},

I referred to this go playground example. It works fine in the case above but if I change the order of the array as below:

	    {40, 100, 20},
		{40, 10},
		{30, 100},
		{30, 100, 80},
		{30, 60},
		{30, 80},
		{100, 20},
		{10, 80},
		{50, 30},

it sometimes gives error like so:

panic: runtime error: index out of range [2] with length 2

Any suggestions on what might be wrong, why it works in some cases and not in others?

Thanks!

答案1

得分: 2

你提供的代码只适用于固定长度的数组。错误出现在程序需要将一个包含3个元素的数组与一个包含2个元素的数组进行比较时,因为它无法访问第二个数组的第三个元素。这在第一个情况下可以工作,是因为比较的顺序,不会出现3比2的情况,只会出现2比3的情况,这是可以做到的,但在这种情况下,第二个数组的第三个元素将不会被考虑。

你需要修改你的代码,只循环最小元素数量的次数:

for x := 0; x < int(math.Min(float64(len(matrix[i])), float64(len(matrix[j])))); x++ {
    if matrix[i][x] == matrix[j][x] {
        continue
    }
    return matrix[i][x] < matrix[j][x]
}

但在这种情况下,当任一可比较数组中有更多元素时,代码没有处理。

英文:

The code you've provided is only suitable for fixed length arrays. The error comes from where the program needs to compare a 3 element array with a 2 element one, since it can't access the second array's third element. This works for the first case because of the comparing order, there wouldn't be any case where there is a 3 to 2 comparison, only a 2 to 3, which can be done, but in this case the second array's third element will not be take into account.

You have to modify your code to loop as many times only as minimum element count of the two arrays:

	for x := 0; x &lt; int(math.Min(float64(len(matrix[i])), float64(len(matrix[j])))); x++ {
		if matrix[i][x] == matrix[j][x] {
			continue
		}
		return matrix[i][x] &lt; matrix[j][x]
	}

But in this case it's not handled when there is more elements in any of the comparable arrays.

huangapple
  • 本文由 发表于 2022年5月9日 19:27:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/72171235.html
匿名

发表评论

匿名网友

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

确定