gpt4 book ai didi

java - 切换二维数组的列

转载 作者:行者123 更新时间:2023-12-01 15:53:55 25 4
gpt4 key购买 nike

所以我的问题是我无法像在单个变量数组中那样切换二维数组的元素。它们不是切换元素,而是不断重写......

for (int column = 0; column < m[0].length; column++) {
shufcol = (int)(Math.random()*4);
temp = column;
System.out.println(shufcol);

for(int row = 0; row < m.length; row++) {
temp = row;
m[row][temp]=m[row][column];
m[row][column]= m[row][shufcol];
m[row][temp] = m[row][shufcol];
}
}

输入数组 (3X4){{0 1 2 3}{1 4 5 6}{0 7 8 9}}

输出数组{{2 2 3 2}{5 5 6 5}{8 8 9 8}}

如果您对 math.random 感到好奇,那只是生成一个 0 到 3 之间的随机列来进行切换。问题又是为什么它只重写元素而不切换它们?

最佳答案

我不完全明白你最后想要实现什么(因为你没有告诉),但我想,如果你重读这段代码:

temp = row;
m[row][temp]=m[row][column];
m[row][column]= m[row][shufcol];
m[row][temp] = m[row][shufcol];

尝试用纸和笔执行几次,你就会发现错误。

关于java - 切换二维数组的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5451726/

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