Find the max repeated 2 array values , such as //{1,2,4,4,3,1,1,4,1,3,3,4,4} = {4,1}
package test;
import java.io.*;
import java.util.*;
public class FindMostRepeatingNumber {
public static void main(String[] args) {
int[] intArray = {1,2,4,4,3,1,1,4,1,3,3,4,4};
int[] finalArray = findValues(intArray);
System.out.println("Final Array = " + Arrays.toString(finalArray));
}
public static int[] findValues(int[] intArray) {
//int[] intArray = {1,2,4,4,3,1,1,4,1,3,3,4,4};
int arrayLength = intArray.length;
ArrayList<Integer> alist = new ArrayList<>();
ArrayList<Integer> blist = new ArrayList<>();
Arrays.sort(intArray);
for (int i = 0; i < arrayLength - 1; i++) {
if (!(intArray[i] == intArray[i + 1])) {
alist.add(intArray[i]);
blist.add(i);
}
}
alist.add(intArray[arrayLength - 1]); // gives each unique values
blist.add(arrayLength - 1);// gives Index
System.out.println("alist = " + alist);
System.out.println("blist = " + blist);
//to find the occurance of each Element
ArrayList<Integer> clist = new ArrayList<>();
clist.add(blist.get(0) + 1);
for (int i = 1; i < alist.size(); i++) {
clist.add((blist.get(i)) - (blist.get(i - 1)));
}
System.out.println("clist = " + clist);//occurance of each Element
int[] intArray1 = new int[alist.size()];
for (int i = 0; i < clist.size(); i++) {
intArray1[i] = clist.get(i); // adding clist values to intArray1 so that this can be sorted.
}
System.out.println("before sorting = " + Arrays.toString(intArray1));
Arrays.sort(intArray1);//sorting clist arraylist through intArray1
System.out.println("sorted Array = " + Arrays.toString(intArray1));
int firstOcc = intArray1[intArray1.length - 1];
System.out.println("firstOcc = " + firstOcc);
int SecondOcc = intArray1[intArray1.length - 2];
System.out.println("SecondOcc = " + SecondOcc);
int firstValue = alist.get(clist.indexOf(firstOcc));
int secondValue = alist.get(clist.indexOf(SecondOcc));
System.out.println("The two expected values are : " + firstValue + " " + secondValue);
int[] finalArray = new int[2];
finalArray[0] = firstValue;
finalArray[1] = secondValue;
return finalArray;
}
}
Output:
alist = [1, 2, 3, 4]
blist = [3, 4, 7, 12]
clist = [4, 1, 3, 5]
before sorting = [4, 1, 3, 5]
sorted Array = [1, 3, 4, 5]
firstOcc = 5
SecondOcc = 4
The two expected values are : 4 1
Final Array = [4, 1]
No comments:
Post a Comment