简体   繁体   English

在Java中对随机生成的2维数组进行排序?

[英]Sorting a randomly generated 2 Dimensional Array in java?

I am trying to make a program that prints out an 2 Dimensional array in ascending order throughout the entire array. 我正在尝试制作一个程序,该程序在整个数组中以升序打印出二维数组。 Any of the elements in the array can not be repeating anywhere in the array. 数组中的任何元素都不能在数组中的任何地方重复。 Anything you need to do to make it work is greatly appreciated. 非常感谢您需要做的任何事情。

08 11 14 19 21 22 25 08 11 14 19 21 22 25
15 22 25 28 32 37 41 15 22 25 28 32 37 41
20 28 31 32 39 40 48 20 28 31 32 39 40 48
24 34 41 47 53 54 56 24 34 41 47 53 54 56
28 37 47 50 57 60 66 28 37 47 50 57 60 66
29 38 50 57 64 70 71 29 38 50 57 64 70 71
31 43 52 62 65 75 78 31 43 52 62 65 75 78

It is gererated with the followint code but isn't sorted: 它与followint代码分叉,但未排序:

public static int[][] getRandomSorted2DArray(int size)
{
    int bigger = (int)Math.pow(2, size) + 1;
    int[][] data = new int[bigger][bigger];
    for (int i = 0; i < data.length; i++)
    {
        for (int j = 0; j < data[0].length; j++)
        {
            data[i][j] = new java.util.Random().nextInt(90);
        }
    }        
    return data;
}

Again I need help with this program but needs two things. 同样,我需要该程序的帮助,但需要两件事。
1. Sort the entire array in ascending order. 1.以升序对整个数组进行排序。
2. No repeating any of the other elements. 2.不要重复任何其他元素。

You could generate a sorted array, by making each element at least 1 bigger than the last one: 您可以通过将每个元素比最后一个元素大至少1个来生成排序数组:

Keep track of the last asserted value and, instead of a completely random number, choose a random number between lastValue and 99 - valuesToGo (so there is still space left for the next numbers. Maybe this works: 跟踪最后一个声明的值,而不是一个完全随机的数字,请在lastValue99 - valuesToGo之间选择一个随机数(这样,下一个数字仍然有空间。也许这99 - valuesToGo

public static int[][] getRandomSorted2DArray(int size)
{
    int bigger = (int)Math.pow(2, size) + 1;
    int[][] data = new int[bigger][bigger];
    lastValue = 0;
    valuesToGo = data.length * data[0].length;
    for (int i = 0; i < data.length; i++) {
        for (int j = 0; j < data[0].length; j++) {
            data[i][j] = lastValue + 1 + new java.util.Random().nextInt(99 - 1 - lastValue - valuesToGo);
            lastValue = data[i][j];
        }
    }        
    return data;
}

The values might get a little distributed around 100, but I guess you'll be able to fix that yourself, if you want to. 这些值可能会在100左右分布一些,但我想您可以根据需要自己解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM