java—按每行的平均值对2d数组排序

2fjabf4q  于 2021-06-29  发布在  Java
关注(0)|答案(3)|浏览(394)

我有一项复杂的任务,手动对二维数组进行不同的排序。到目前为止,我完成了这些任务:
用户需要输入10-20之间的行大小,
生成二维数组,其中行大小是用户输入,列大小是从10-50随机生成的,
每个数组都填充了从100到999之间随机生成的数字,
按其降序值输出每个数组行,
输出每行数组的平均值,
输出最大平均值的屏幕数组,
到目前为止我还不能解决第七项任务。输出按每行平均值排序的二维数组。尝试在循环中实现新的arrayaverage来对行进行排序,但没有成功。数组只需要排序,而不需要创建新的数组。

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

public class SortArray2D {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Sorting two dimennsional arrays!!!");
        System.out.print("Enter arrays 1st dimmension size 10 - 20: ");
        int array1stDsize = sc.nextInt();
        int array2ndDsize = new Random().nextInt(40) + 10;
        System.out.println();
        sc.close();

        if (array1stDsize > 20 || array1stDsize < 10) {
            System.out.println("The number you enteraed is too big or too small!!!");
        } else {
            //initializing array 
            int[][] array = new int[array1stDsize][array2ndDsize];
            for (int i = 0; i < array.length; i = i + 1) {
                for (int j = 0; j < array[i].length; j = j + 1) {
                    int input = new Random().nextInt(900) + 100;
                    array[i][j] = input;
                }
            }
            System.out.println("Array element output: ");
            arrayOutput(array);
            // array element sorting from biggest to smallest 
            for (int k = 0; k < array.length; k++) {
                for (int i = 1; i < array[k].length; i++) {
                    for (int j = i; j > 0; j--) {
                        if (array[k][j] > array[k][j - 1]) {
                            int element = array[k][j];
                            array[k][j] = array[k][j - 1];
                            array[k][j - 1] = element;
                        }
                    }
                }
            }
            System.out.println();
            System.out.println("Descending Array element output: ");
            arrayOutput(array);

            System.out.println();
            System.out.println("Average value output by array: ");
            float[] arrayAverage = new float[array1stDsize];
            float average = 0;
            for (int i = 0; i < array.length; i = i + 1) {
                for (int j = 0; j < array[i].length; j = j + 1) {
                    average = average + array[i][j];
                }
                average = (float) (Math.round((average / array[i].length) * 100.0) / 100.0);
                System.out.println(i + ". array average value: " + average);
                arrayAverage[i] = average;
            }

            System.out.println();
            System.out.println("New array from average values: ");
            System.out.println(Arrays.toString(arrayAverage));

            System.out.println();
            System.out.println("Most valuest array is: ");
            double max = 100;
            int row = 0;
            for (int i = 0; i < arrayAverage.length; i++) {

                if (max < arrayAverage[i]) {
                    max = arrayAverage[i];
                    row = i;
                }
            }
            System.out.print("Its founded " + row + ". row and it's value is: ");
            for (int j = 0; j < array[row].length; j = j + 1) {
                System.out.print(" " + array[row][j]);
            }

            System.out.println();
            System.out.println();

            //2D array sorting by average values
        }
    }

    public static int[][] arrayOutput(int[][] array) {
        for (int i = 0; i < array.length; i = i + 1) {
            for (int j = 0; j < array[i].length; j = j + 1) {
                if (j == 0) {
                    System.out.print("{ " + array[i][j]);
                } else {

                    System.out.print(", " + array[i][j]);
                }
            }
            System.out.print(" }");
            System.out.println();

        }
        return array;
    }
}
5cg8jx4n

5cg8jx4n1#

按升序输出排序的二维数组:

int[][] arr = {
        {12, 54, 87},  // avg 51
        {98, 56, 32},  // avg 62
        {19, 73, 46}}; // avg 46

Arrays.stream(arr)
        // sort an array by the
        // average value of the row
        .sorted(Comparator.comparing(row ->
                // get the average value or 0 if the row is empty {}
                Arrays.stream(row).average().orElse(0)))
        // string representation
        // of the row content
        .map(Arrays::toString)
        // output line by line
        .forEach(System.out::println);

输出:

[19, 73, 46]
[12, 54, 87]
[98, 56, 32]
nom7f22z

nom7f22z2#

计算平均值的代码部分:

float[] arrayAverage = new float[array1stDsize];
    float average = 0;
    for (int i = 0; i < array.length; i = i + 1) {
        for (int j = 0; j < array[i].length; j = j + 1) {
            average = average + array[i][j];
        }
        average = (float) (Math.round((average / array[i].length) * 100.0) / 100.0);
        System.out.println(i + ". array average value: " + average);
        arrayAverage[i] = average;
    }

稍有错误,您需要设置 average 在计算下一行的平均值之前,将变量设置为零:

...
  arrayAverage[i] = average;
  average = 0;

使用java流,可以非常优雅地按行的平均值排序矩阵,即:

Arrays.sort(array, comparingDouble(row -> IntStream.of(row)
                                                   .average()
                                                   .getAsDouble()));

要对数组排序,可以使用以下方法 Arrays.sort ,然后每行取其平均值作为双倍值 IntStream.of(row).average().getAsDouble() ,并用作排序参数 comparingDouble(....) .
运行示例:

import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.IntStream;
import static java.util.Comparator.comparingDouble;

public class Test {
    public static void main(String[] args) {
        int array[][] = {{10, 20, 30},{40, 50, 60}, {1,2,3} };
        Arrays.sort(array, comparingDouble(row -> IntStream.of(row).average().getAsDouble()));
        Arrays.stream(array).map(Arrays::toString).forEach(System.out::println);
    }
}

输出:

[1, 2, 3]
[10, 20, 30]
[40, 50, 60]

相反的顺序使用:

Arrays.sort(array, comparing(row -> IntStream.of(row).average().getAsDouble(), reverseOrder()));

输出:

[40, 50, 60]
[10, 20, 30]
[1, 2, 3]

编辑:没有流
不使用流,您可以执行以下操作:
1-使用矩阵行的平均值获取数组:

float[] arrayAverage = average(matrix);

您已经知道如何计算平均值,因此只需要从您创建的代码中提取一个方法,即:

private static float[]average(int[][] array) {
    float[] arrayAverage = new float[array.length];
    float sum = 0;
    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array[i].length; j++) {
            sum += array[i][j];
        }
        arrayAverage[i] = (float) (Math.round((sum / array[i].length) * 100.0) / 100.0);
        sum = 0;
    }
    return arrayAverage;
}

2-创建一个表示行的数组,并按以下方式初始化:

int [] row_position = new int [arrayAverage.length];
for(int i = 0; i < row_position.length; i++)
    row_position[i] = i;

3-排序 arrayAverage 使用最简单的排序,气泡排序。排序该数组时,相应地更新存储在 row_position :

for(int i=0; i < arrayAverage.length; i++){
    for(int j=1; j < (arrayAverage.length-i); j++){
        if(arrayAverage[j-1] > arrayAverage[j]){
            float temp = arrayAverage[j-1];
            arrayAverage[j-1] = arrayAverage[j];
            arrayAverage[j] = temp;
            int temp_pos = row_position[j-1];
            row_position[j-1] = row_position[j];
            row_position[j] = temp_pos;
        }
    }
}

4-既然你有 row_positions 数组,它告诉您应该如何重新排列已排序的行,您只需要相应地交换行:

int[][] tmp_matrix = new int [matrix.lenght][];
    for (int i = 0; i < tmp_matrix.length; i++) {
        tmp_matrix[i] = matrix[row_position[i]];
    }
    matrix = new_matrix;

但是,请记住,为了简单起见,我假设了 NxN ,并且可以从性能方面改进上述解决方案。

svdrlsy4

svdrlsy43#

最后,成功了,就像这样。

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

public class SortArray2D {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Sorting two dimennsional arrays!!!");
        System.out.print("Enter arrays 1st dimmension size 10 - 20: ");
        int array1stDsize = sc.nextInt();
        System.out.println();
        sc.close();

        if (array1stDsize > 20 || array1stDsize < 10) {
            System.out.println("The number you enteraed is too big or too small!!!");
        } else {

            int[][] array = new int[array1stDsize][];
            Random random = new Random();
            for (int i = 0; i < array.length; i++) {
                array[i] = new int[random.nextInt(31) + 10];
                for (int j = 0; j < array[i].length; j++) {
                    int input = new Random().nextInt(900) + 100;
                    array[i][j] = input;
                }
            }
            System.out.println("Array element output: ");
            arrayOutput(array);
            // array element sorting from biggest to smallest
            for (int k = 0; k < array.length; k++) {
                for (int i = 1; i < array[k].length; i++) {
                    for (int j = i; j > 0; j--) {
                        if (array[k][j] > array[k][j - 1]) {
                            int element = array[k][j];
                            array[k][j] = array[k][j - 1];
                            array[k][j - 1] = element;

                        }
                    }
                }
            }
            System.out.println();
            System.out.println("Descending Array element output: ");
            arrayOutput(array);

            System.out.println();
            System.out.println("Average value output by array: ");
            float[] arrayAverage = new float[array1stDsize];

            for (int i = 0; i < array.length; i = i + 1) {
                float sum = 0;
                for (int j = 0; j < array[i].length; j = j + 1) {
                    sum = sum + array[i][j];
                }
                float average = (float) (Math.round((sum / array[i].length) * 100.0) / 100.0);
                System.out.println(i + ". array average value: " + average);
                arrayAverage[i] = average;
            }
            // array lines sorting from by average value increasing
            for (int i = 0; i < arrayAverage.length; i = i + 1) {
                for (int j = i; j > 0; j--) {
                    if (arrayAverage[j] < arrayAverage[j - 1]) {
                        float tmpor = arrayAverage[j];
                        arrayAverage[j] = arrayAverage[j - 1];
                        arrayAverage[j - 1] = tmpor;

                        int[] tmp = array[j];
                        array[j] = array[j - 1];
                        array[j - 1] = tmp;
                    }
                }
            }
            System.out.println();
            System.out.print("Array from average values sorted: ");
            System.out.println(Arrays.toString(arrayAverage));
            System.out.println();
            System.out.println("Incerasing Array line output: ");
            arrayOutput(array);
            System.out.println();
            System.out.print("Most valuest array is array: ");
            double max = 100;
            int row = 0;
            for (int i = 0; i < arrayAverage.length; i++) {

                if (max < arrayAverage[i]) {
                    max = arrayAverage[i];
                    row = i;

                }
            }
            for (int j = 0; j < array[row].length; j = j + 1) {
                System.out.print(" " + array[row][j]);
            }
        }
    }

    public static int[][] arrayOutput(int[][] array) {
        for (int i = 0; i < array.length; i = i + 1) {
            for (int j = 0; j < array[i].length; j = j + 1) {
                if (j == 0) {
                    System.out.print("{ " + array[i][j]);
                } else {

                    System.out.print(", " + array[i][j]);
                }
            }
            System.out.print(" }");
            System.out.println();

        }
        return array;
    }
}

相关问题