gpt4 book ai didi

java - Java中如何对重复数字进行排序?

转载 作者:行者123 更新时间:2023-12-02 04:35:47 26 4
gpt4 key购买 nike

现在我想做排序部分......什么是排序?我对排序很困惑,我需要删除重复的数字......以及如何删除数字并对该编码进行排序?p/s:重复的数字我只得到了几个...

import java.lang.*; 
// import java.util.Random;

class UniqueRandomIntArray {

// static Random rnGen = new Random();

private static void uriArray(int[] rray) {
int low = 0;
int high = 100;

int rn;
int haveit = -1;
int i = 0;
int j;

while((haveit == -1) && i < rray.length) {
rn = randNum(low, high);

for(j = 0; j <= i; j++) {
if(rn == rray[j]) {
haveit = j;
j = i;
}
}

if(haveit != -1) {
System.out.println("a[" + haveit + "] is " + rn + " already");
haveit = -1;
}
else {
System.out.println("a[" + i + "] is " + rn);
rray[i] = rn;
i++;
}

} // end while
} // end uriArray


private static int randNum(int min, int max) {
int range = (max - min) + 1;
// int randnum = rnGen.nextInt(range) + min;
int randnum = (int) (Math.random() * range) + min;
return randnum;
}


public static void main(String[] args) {
int[] arra = new int[20];
uriArray(arra);
for(int i=0; i<arra.length; i++) {
System.out.print(" | " + arra[i]);
}
System.out.println(" | ");
}

} //class ends

最佳答案

这是生成唯一的随机整数列表的简单方法:

    new Random().ints(0, 101)// generate a stream of random integers from 0 (incl.) to 100
.distinct() // unique
.limit(20) // we only need 20 random numbers
.sorted() // sort
.forEach(System.out::println);

因此,如果您想要与旧代码相同的结果,这是完整的新代码:

class UniqueRandomIntArray {
public static void main(String[] args) {
new Random().ints(0, 101).distinct() // generate a stream of random
// integers
.limit(20) // we only need 20 random numbers
.sorted().forEach((int i) -> System.out.print(" | " + i));
System.out.println(" | ");
}
} // class ends

关于java - Java中如何对重复数字进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30782288/

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