In: Computer Science
JAVA JAVA JAVA JAVA, How to determine if there is more than one number that appeared the X amount of times. (For example there are 3 numbers which occured 50 times so I want the output to show which 3 numbers occured 50 times) This is the code
import java.util.Random; public class MostLeastOccurring { public static void main(String[] args) { Random random = new Random(); int x = 1000; int[] array = new int[x]; for (int i = 0; i < x; i++) { array[i] = random.nextInt(101); } int leastOccurring = array[0], mostOccurring = array[0], leastCount = 0, mostCount = 0; for (int i = 0; i < x; i++) { int count = 0; for (int j = 0; j < x; j++) { if (array[i] == array[j]) ++count; } if (i == 0 || count > mostCount) { mostCount = count; mostOccurring = array[i]; } if (i == 0 || count < leastCount) { leastCount = count; leastOccurring = array[i]; } } System.out.println("Most occurring number is " + mostOccurring + ", it occurs " + mostCount + " times."); System.out.println("Least occurring number is " + leastOccurring + ", it occurs " + leastCount + " times."); } }
Algorithm: We can use a frequency array to store the count of all elements which are in range of (0,101).
Have a look at the below code. I have put comments wherever required for better understanding.
import java.util.Random;
class Main {
public static void main(String[] args) {
Random random = new Random();
int x = 1000;
int X = 10; // Take X as 10 as sample case, then this prgram will print all numbers which occurs 10 times, it can be anything
int[] array = new int[x];
for (int i = 0; i < x; i++) {
array[i] = random.nextInt(101);
}
// create a frequence array
int[] count = new int[101];
// populate the frequency array
for (int i=0;i<x;i++){
count[array[i]]+=1;
}
// Display all those elements whose count is X
for (int i=0;i<101;i++){
if (count[i]==X){
System.out.println(i);
}
}
}
}
Happy Learning!