I'm trying to find the most frequent number and the least frequent duplicate number in an array E.g
[7, 5, 6, 4, 6, 5, 5, 8, 7, 0, 7, 5, 2, 9, 7, 9, 3, 4, 6]
These are the duplicate number in the array above:
"7" and "5" are the most frequent number, "4" is the least frequent duplicate.
When I tried to code, I was able to get the number 7, but then I don't know how to implement the least frequent.
This is the code I wrote:
String[] numbers = "7564655870752979346".split("");
String elements = "";
int count = 0;
for (String tempElement : numbers) {
int tempCount = 0;
for (n = 0; n < numbers.length; n++) {
if (numbers[n].equals(tempElement)) {
tempCount++;
if (tempCount > count) {
elements = tempElement;
// System.out.println(elements);
count = tempCount;
}
}
}
}
System.out.println("Frequent number is: " + elements + " It appeared " + count+" times");
My solution above only prints out 7, and I don't know how to check for the least duplicate.
Write a function to find Min Repeated number(started from 2)
public static String findMin(String[] numbers, int counter) {
int count = 0;
String elements = "";
for (String tempElement : numbers) {
int tempCount = 0;
for (int n = 0; n < numbers.length; n++) {
if (numbers[n].equals(tempElement)) {
tempCount++;
if (tempCount > counter) {
count = 0;
break;
}
if (tempCount > count) {
elements = tempElement;
// System.out.println(elements);
count = tempCount;
}
}
}
if(count == counter) {
return elements;
}
}
if(count < counter) {
return "";
}
return elements;
}
A loop over numbers:
String x = "";
int c = 2;
do {
x = findMin(numbers, c ++);
} while(x == "");
The whole code will be
public class X {
public static String findMin(String[] numbers, int counter) {
int count = 0;
String elements = "";
for (String tempElement: numbers) {
int tempCount = 0;
for (int n = 0; n < numbers.length; n++) {
if (numbers[n].equals(tempElement)) {
tempCount++;
if (tempCount > counter) {
count = 0;
break;
}
if (tempCount > count) {
elements = tempElement;
// System.out.println(elements);
count = tempCount;
}
}
}
if (count == counter) {
return elements;
}
}
if (count < counter) {
return "";
}
return elements;
}
public static void main(String[] args) {
String[] numbers = "756655874075297346".split("");
String elements = "";
int count = 0;
for (String tempElement: numbers) {
int tempCount = 0;
for (int n = 0; n < numbers.length; n++) {
if (numbers[n].equals(tempElement)) {
tempCount++;
if (tempCount > count) {
elements = tempElement;
// System.out.println(elements);
count = tempCount;
}
}
}
}
String x = "";
int c = 2;
do {
x = findMin(numbers, c++);
} while (x == "");
System.out.println("Frequent number is: " + elements + " It appeared " + count + " times");
System.out.println("Min Frequent number is: " + x + " It appeared " + (c - 1) + " times");
}
}