gpt4 book ai didi

java - 求最大的行和列,解不一致

转载 作者:行者123 更新时间:2023-12-02 04:57:33 24 4
gpt4 key购买 nike

逻辑错误在哪里?...有时解是正确的,有时却不是。该程序假设计算总和最大的行和总和最大的列。例如:

1 1 1 1

0 0 1 0

0 0 1 0

0 0 1 0

那么输出将是:最大行 = 0最大列 = 2//因为计数从 0 开始

这就是我所拥有的:

import java.util.Random;

public class LargestRowAndColumn {

public static void main(String[] args) {

Random f = new Random();

int[][] m = new int[4][4];

for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
m[i][j] = f.nextInt(2);
}
}
for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
System.out.print(m[i][j] + " ");
}
System.out.println();
}
System.out.println("The largest row is index: " + computeRow(m));
System.out.println("The largest column is index: " + computeColumn(m));
}

public static int computeRow(int[][] m) {

int[] count = new int[m.length];

int sum;

for (int i = 0; i < 4; i++) {
sum = 0;
for (int j = 0; j < 4; j++) {
sum = sum + m[i][j];
}
count[i] = sum;
}

int maxIndex = 0;

for (int i = 0; i < i + 1; i++) {
for (int j = count.length - 1; j >= i; j--) {
if (count[i] < count[j]) {
maxIndex = j;
break;
}
}
}
return maxIndex;
}

public static int computeColumn(int[][] m) {

int[] count = new int[m.length];

int sum = 0;

for (int i = 0; i < 4; i++) {
sum = 0;
for (int j = 0; j < 4; j++) {
sum = sum + m[j][i];
}
count[i] = sum;
}

int maxIndex = 0;

for (int i = 0; i < i + 1; i++) {
for (int j = count.length - 1; j >= i; j--) {
if (count[i] < count[j]) {
maxIndex = j;
break;
}
}
}
return maxIndex;
}
}

最佳答案

您的 maxIndex 嵌套循环太复杂。它应该是一个循环,检查循环中当前项目迄今为止看到的当前最大值。像这样的事情:

    int maxIndex = 0;

for (int i = 1; i < count.length; i++) {
if (count[i] > count[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;

关于java - 求最大的行和列,解不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28627529/

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