[英]Finding the 10 highest frequencies in a randomized array-Java
The project description is to create an array of 1000 randomized numbers from 1-50 and to display the 10 highest numbers by frequency.项目描述是创建一个由 1-50 的 1000 个随机数字组成的数组,并按频率显示 10 个最高的数字。 I cut down the numbers in my code for easier testing.我减少了代码中的数字以便于测试。
I have created the array with randomized numbers and displayed how many times each number occurred.我用随机数创建了数组并显示了每个数字出现的次数。
I am having trouble figuring out how to sort the numbers from highest highest to lowest.我无法弄清楚如何从最高到最低对数字进行排序。
Any help would be appreciated.任何帮助,将不胜感激。
import java.util.*; //import random class and arrays
class MaxArray{
public static void main(String[]args){
Random rand = new Random(1); //create random object and sets seed to one
int[] randArray = new int [51];
int[] newArray = new int[51];
for(int i = 0; i < randArray.length; i++){
randArray[i] = rand.nextInt(50) + 1; // returns a single random integer between 1 and 50
}
Arrays.sort(randArray);
System.out.println(Arrays.toString(randArray));
for(int j = 0; j < randArray.length; j++){
newArray[randArray[j]] += 1;
}
System.out.println(Arrays.toString(newArray));
for(int k = 0; k < newArray.length; k++){
System.out.println("Number " + k + " occurred " + newArray[k] + " times");
}
}// end main
}//end class
This is how you get from highest to lowest这就是你从最高到最低的方式
for (int i = randArray.length-1; i >=0 ; i--) {
System.out.print(randArray[i]+" ");
}
and this is how you find 10 highest numbers:这就是你如何找到 10 个最高数字:
int CheckingDublicate = 0, count = 1;
for(int i = 1; i <= randArray.length; i++){
if(count<=10{
if(CheckingDublicate!=randArray[randArray.length-i])
{
//Ignoring if dublicate
System.out.print(randArray[randArray.length-i]+" ");
CheckingDublicate = randArray[randArray.length-i];
count++;
}
}
else
break;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.