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!
CodePudding user response:
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 < 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]
}
But in this case it's not handled when there is more elements in any of the comparable arrays.