Finding the smallest integer that appears at least k times - java

You are given an array A of integers and an integer k. Implement an algorithm that determines, in linear time, the smallest integer that appears at least k times in A.
I have been struggling with this problem for awhile, coding in Java, I need to use a HashTable to find the smallest integer that appears at least k times, it also must be in linear time.
This is what I attempted but it does not pass any of the tests
private static int problem1(int[] arr, int k)
{
// Implement me!
HashMap<Integer, Integer> table = new HashMap<Integer, Integer>();
int ans = Integer.MAX_VALUE;
for (int i=0; i < arr.length; i++) {
if(table.containsKey(arr[i])) {
table.put(arr[i], table.get(arr[i]) + 1);
if (k <= table.get(arr[i])) {
ans = Math.min(ans, arr[i]);
}
}else{
table.put(arr[i], 1);
}
}
return ans;
}
Here is the empty code with all of the test cases:
import java.io.*;
import java.util.*;
public class Lab5
{
/**
* Problem 1: Find the smallest integer that appears at least k times.
*/
private static int problem1(int[] arr, int k)
{
// Implement me!
return 0;
}
/**
* Problem 2: Find two distinct indices i and j such that A[i] = A[j] and |i - j| <= k.
*/
private static int[] problem2(int[] arr, int k)
{
// Implement me!
int i = -1;
int j = -1;
return new int[] { i, j };
}
// ---------------------------------------------------------------------
// Do not change any of the code below!
private static final int LabNo = 5;
private static final String quarter = "Fall 2020";
private static final Random rng = new Random(123456);
private static boolean testProblem1(int[][] testCase)
{
int[] arr = testCase[0];
int k = testCase[1][0];
int answer = problem1(arr.clone(), k);
Arrays.sort(arr);
for (int i = 0, j = 0; i < arr.length; i = j)
{
for (; j < arr.length && arr[i] == arr[j]; j++) { }
if (j - i >= k)
{
return answer == arr[i];
}
}
return false; // Will never happen.
}
private static boolean testProblem2(int[][] testCase)
{
int[] arr = testCase[0];
int k = testCase[1][0];
int[] answer = problem2(arr.clone(), k);
if (answer == null || answer.length != 2)
{
return false;
}
Arrays.sort(answer);
// Check answer
int i = answer[0];
int j = answer[1];
return i != j
&& j - i <= k
&& i >= 0
&& j < arr.length
&& arr[i] == arr[j];
}
public static void main(String args[])
{
System.out.println("CS 302 -- " + quarter + " -- Lab " + LabNo);
testProblems(1);
testProblems(2);
}
private static void testProblems(int prob)
{
int noOfLines = prob == 1 ? 100000 : 500000;
System.out.println("-- -- -- -- --");
System.out.println(noOfLines + " test cases for problem " + prob + ".");
boolean passedAll = true;
for (int i = 1; i <= noOfLines; i++)
{
int[][] testCase = null;
boolean passed = false;
boolean exce = false;
try
{
switch (prob)
{
case 1:
testCase = createProblem1(i);
passed = testProblem1(testCase);
break;
case 2:
testCase = createProblem2(i);
passed = testProblem2(testCase);
break;
}
}
catch (Exception ex)
{
passed = false;
exce = true;
}
if (!passed)
{
System.out.println("Test " + i + " failed!" + (exce ? " (Exception)" : ""));
passedAll = false;
break;
}
}
if (passedAll)
{
System.out.println("All test passed.");
}
}
private static int[][] createProblem1(int testNo)
{
int size = rng.nextInt(Math.min(1000, testNo)) + 5;
int[] numbers = getRandomNumbers(size, size);
Arrays.sort(numbers);
int maxK = 0;
for (int i = 0, j = 0; i < size; i = j)
{
for (; j < size && numbers[i] == numbers[j]; j++) { }
maxK = Math.max(maxK, j - i);
}
int k = rng.nextInt(maxK) + 1;
shuffle(numbers);
return new int[][] { numbers, new int[] { k } };
}
private static int[][] createProblem2(int testNo)
{
int size = rng.nextInt(Math.min(1000, testNo)) + 5;
int[] numbers = getRandomNumbers(size, size);
int i = rng.nextInt(size);
int j = rng.nextInt(size - 1);
if (i <= j) j++;
numbers[i] = numbers[j];
return new int[][] { numbers, new int[] { Math.abs(i - j) } };
}
private static void shuffle(int[] arr)
{
for (int i = 0; i < arr.length - 1; i++)
{
int rndInd = rng.nextInt(arr.length - i) + i;
int tmp = arr[i];
arr[i] = arr[rndInd];
arr[rndInd] = tmp;
}
}
private static int[] getRandomNumbers(int range, int size)
{
int numbers[] = new int[size];
for (int i = 0; i < size; i++)
{
numbers[i] = rng.nextInt(2 * range) - range;
}
return numbers;
}
}

private static int problem1(int[] arr, int k) {
// Implement me!
Map<Integer, Integer> table = new TreeMap<Integer, Integer>();
for (int i = 0; i < arr.length; i++) {
if (table.containsKey(arr[i])) {
table.put(arr[i], table.get(arr[i]) + 1);
} else {
table.put(arr[i], 1);
}
}
for (Map.Entry<Integer,Integer> entry : table.entrySet()) {
//As treemap is sorted, we return the first key with value >=k.
if(entry.getValue()>=k)
return entry.getKey();
}
//Not found
return -1;
}

As others have pointed out, there are a few mistakes. First, the line where you initialize ans,
int ans = 0;
You should initialize ans to Integer.MAX_VALUE so that when you find an integer that appears at least k times for the first time that ans gets set to that integer appropriately. Second, in your for loop, there's no reason to skip the first element while iterating the array so i should be initialized to 0 instead of 1. Also, in that same line, you want to iterate through the entire array, and in your loop's condition right now you have i < k when k is not the length of the array. The length of the array is denoted by arr.length so the condition should instead be i < arr.length. Third, in this line,
if (k < table.get(arr[i])){
where you are trying to check if an integer has occurred at least k times in the array so far while iterating through the array, the < operator should be changed to <= since the keyword here is at least k times, not "more than k times". Fourth, k should never change so you can get rid of this line of code,
k = table.get(arr[i]);
After applying all of those changes, your function should look like this:
private static int problem1(int[] arr, int k)
{
// Implement me!
HashMap<Integer, Integer> table = new HashMap<Integer, Integer>();
int ans = Integer.MAX_VALUE;
for (int i=0; i < arr.length; i++) {
if(table.containsKey(arr[i])) {
table.put(arr[i], table.get(arr[i]) + 1);
if (k <= table.get(arr[i])) {
ans = Math.min(ans, arr[i]);
}
}else{
table.put(arr[i], 1);
}
}
return ans;
}

Pseudo code:
collect frequencies of each number in a Map<Integer, Integer> (number and its count)
set least to a large value
iterate over entries
ignore entry if its value is less than k
if entry key is less than current least, store it as least
return least
One line implementation:
private static int problem1(int[] arr, int k) {
return Arrays.stream(arr).boxed()
.collect(groupingBy(identity(), counting()))
.entrySet().stream()
.filter(entry -> entry.getValue() >= k)
.map(Map.Entry::getKey)
.reduce(MAX_VALUE, Math::min);
}

This was able to pass all the cases! Thank you to everyone who helped!!
private static int problem1(int[] arr, int k)
{
// Implement me!
HashMap<Integer, Integer> table = new HashMap<Integer, Integer>();
int ans = Integer.MAX_VALUE;
for (int i=0; i < arr.length; i++) {
if(table.containsKey(arr[i])) {
table.put(arr[i], table.get(arr[i]) + 1);
}else{
table.put(arr[i], 1);
}
}
Set<Integer> keys = table.keySet();
for(int i : keys){
if(table.get(i) >= k){
ans = Math.min(ans,i);
}
}
if(ans != Integer.MAX_VALUE){
return ans;
}else{
return 0;
}
}

Related

Find the max value of the same length nails after hammered

I'm trying to solve this problem:
Given an array of positive integers, and an integer Y, you are allowed to replace at most Y array-elements with lesser values. Your goal is for the array to end up with as large a subset of identical values as possible. Return the size of this largest subset.
The array is originally sorted in increasing order, but you do not need to preserve that property.
So, for example, if the array is [10,20,20,30,30,30,40,40,40] and Y = 3, the result should be 6, because you can get six 30s by replacing the three 40s with 30s. If the array is [20,20,20,40,50,50,50,50] and Y = 2, the result should be 5, because you can get five 20s by replacing two of the 50s with 20s.
Below is my solution with O(nlogn) time complexity. (is that right?) I wonder if I can further optimize this solution?
Thanks in advance.
public class Nails {
public static int Solutions(int[] A, int Y) {
int N = A.length;
TreeMap < Integer, Integer > nailMap = new TreeMap < Integer, Integer > (Collections.reverseOrder());
for (int i = 0; i < N; i++) {
if (!nailMap.containsKey(A[i])) {
nailMap.put(A[i], 1);
} else {
nailMap.put(A[i], nailMap.get(A[i]) + 1);
}
}
List < Integer > nums = nailMap.values().stream().collect(Collectors.toList());
if (nums.size() == 1) {
return nums.get(0);
}
//else
int max = nums.get(0);
int longer = 0;
for (int j = 0; j < nums.size(); j++) {
int count = 0;
if (Y < longer) {
count = Y + nums.get(j);
} else {
count = longer + nums.get(j);
}
if (max < count) {
max = count;
}
longer += nums.get(j);
}
return max;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String[] input = scanner.nextLine().replaceAll("\\[|\\]", "").split(",");
System.out.println(Arrays.toString(input));
int[] A = new int[input.length - 1];
int Y = Integer.parseInt(input[input.length - 1]);
for (int i = 0; i < input.length; i++) {
if (i < input.length - 1) {
A[i] = Integer.parseInt(input[i]);
} else {
break;
}
}
int result = Solutions(A, Y);
System.out.println(result);
}
}
}
A C++ implementation would like the following where A is the sorted pin size array and K is the number of times the pins can be hammered.
{1,1,3,3,4,4,4,5,5}, K=2 should give 5 as the answer
{1,1,3,3,4,4,4,5,5,6,6,6,6,6,6}, K=2 should give 6 as the answer
int maxCount(vector<int>& A, int K) {
int n = A.size();
int best = 0;
int count = 1;
for (int i = 0; i < n-K-1; i++) {
if (A[i] == A[i + 1])
count = count + 1;
else
count = 1;
if (count > best)
best = count;
}
int result = max(best+K, min(K+1, n));
return result;
}
Since the array is sorted to begin with, a reasonably straightforward O(n) solution is, for each distinct value, to count how many elements have that value (by iteration) and how many elements have a greater value (by subtraction).
public static int doIt(final int[] array, final int y) {
int best = 0;
int start = 0;
while (start < array.length) {
int end = start;
while (end < array.length && array[end] == array[start]) {
++end;
}
// array[start .. (end-1)] is now the subarray consisting of a
// single value repeated (end-start) times.
best = Math.max(best, end - start + Math.min(y, array.length - end));
start = end; // skip to the next distinct value
}
assert best >= Math.min(y + 1, array.length); // sanity-check
return best;
}
First, iterate through all the nails and create a hash H that stores the number of nails for each size. For [1,2,2,3,3,3,4,4,4], H should be:
size count
1 : 1
2 : 2
3 : 3
4 : 3
Now create an little algorithm to evaluate the maximum sum for each size S, given Y:
BestForSize(S, Y){
total = H[S]
while(Y > 0){
S++
if(Y >= H[S] and S < biggestNailSize){
total += H[S]
Y -= H[S]
}
else{
total += Y
Y = 0
}
}
return total;
}
Your answer should be max(BestForSize(0, Y), BestForSize(1, Y), ..., BestForSize(maxSizeOfNail, Y)).
The complexity is O(n²). A tip to optimize is to start from the end. For example, after you have the maximum value of nails in the size 4, how can you use your answer to find the maximum number of size 3?
Here is my java implementation: First I build a reversed map of each integer and its occurence for example {1,1,1,1,3,3,4,4,5,5} would give {5=2, 4=2, 3=2, 1=4}, then for each integer I calculate the max occurence that we can get of it regarding the K and the occurences of the highest integers in the array.
public static int ourFunction(final int[] A, final int K) {
int length = A.length;
int a = 0;
int result = 0;
int b = 0;
int previousValue = 0;
TreeMap < Integer, Integer > ourMap = new TreeMap < Integer, Integer > (Collections.reverseOrder());
for (int i = 0; i < length; i++) {
if (!ourMap.containsKey(A[i])) {
ourMap.put(A[i], 1);
} else {
ourMap.put(A[i], ourMap.get(A[i]) + 1);
}
}
for (Map.Entry<Integer, Integer> entry : ourMap.entrySet()) {
if( a == 0) {
a++;
result = entry.getValue();
previousValue = entry.getValue();
} else {
if( K < previousValue)
b = K;
else
b = previousValue;
if ( b + entry.getValue() > result )
result = b + entry.getValue();
previousValue += entry.getValue();
}
}
return result;
}
Since the array is sorted, we can have an O(n) solution by iterating and checking if current element is equals to previous element and keeping track of the max length.
static int findMax(int []a,int y) {
int n = a.length,current = 1,max = 0,diff = 0;
for(int i = 1; i< n; i++) {
if(a[i] == a[i-1]) {
current++;
diff = Math.min(y, n-i-1);
max = Math.max(max, current+diff);
}else {
current = 1;
}
}
return max;
}
given int array is not sorted than you should sort
public static int findMax(int []A,int K) {
int current = 1,max = 0,diff = 0;
List<Integer> sorted=Arrays.stream(A).sorted().boxed().collect(Collectors.toList());
for(int i = 1; i< sorted.size(); i++) {
if(sorted.get(i).equals(sorted.get(i-1))) {
current++;
diff = Math.min(K, sorted.size()-i-1);
max = Math.max(max, current+diff);
}else {
current = 1;
}
}
return max;
}
public static void main(String args[]) {
List<Integer> A = Arrays.asList(3,1,5,3,4,4,3,3,5,5,5,1);
int[] Al = A.stream().mapToInt(Integer::intValue).toArray();
int result=findMax(Al, 5);
System.out.println(result);
}

How can I find the mode of a number in an array? [duplicate]

int[] a = new int[10]{1,2,3,4,5,6,7,7,7,7};
how can I write a method and return 7?
I want to keep it native without the help of lists, maps or other helpers.
Only arrays[].
Try this answer. First, the data:
int[] a = {1,2,3,4,5,6,7,7,7,7};
Here, we build a map counting the number of times each number appears:
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i : a) {
Integer count = map.get(i);
map.put(i, count != null ? count+1 : 1);
}
Now, we find the number with the maximum frequency and return it:
Integer popular = Collections.max(map.entrySet(),
new Comparator<Map.Entry<Integer, Integer>>() {
#Override
public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
}).getKey();
As you can see, the most popular number is seven:
System.out.println(popular);
> 7
EDIT
Here's my answer without using maps, lists, etc. and using only arrays; although I'm sorting the array in-place. It's O(n log n) complexity, better than the O(n^2) accepted solution.
public int findPopular(int[] a) {
if (a == null || a.length == 0)
return 0;
Arrays.sort(a);
int previous = a[0];
int popular = a[0];
int count = 1;
int maxCount = 1;
for (int i = 1; i < a.length; i++) {
if (a[i] == previous)
count++;
else {
if (count > maxCount) {
popular = a[i-1];
maxCount = count;
}
previous = a[i];
count = 1;
}
}
return count > maxCount ? a[a.length-1] : popular;
}
public int getPopularElement(int[] a)
{
int count = 1, tempCount;
int popular = a[0];
int temp = 0;
for (int i = 0; i < (a.length - 1); i++)
{
temp = a[i];
tempCount = 0;
for (int j = 1; j < a.length; j++)
{
if (temp == a[j])
tempCount++;
}
if (tempCount > count)
{
popular = temp;
count = tempCount;
}
}
return popular;
}
Take a map to map element - > count
Iterate through array and process the map
Iterate through map and find out the popular
Assuming your array is sorted (like the one you posted) you could simply iterate over the array and count the longest segment of elements, it's something like #narek.gevorgyan's post but without the awfully big array, and it uses the same amount of memory regardless of the array's size:
private static int getMostPopularElement(int[] a){
int counter = 0, curr, maxvalue, maxcounter = -1;
maxvalue = curr = a[0];
for (int e : a){
if (curr == e){
counter++;
} else {
if (counter > maxcounter){
maxcounter = counter;
maxvalue = curr;
}
counter = 0;
curr = e;
}
}
if (counter > maxcounter){
maxvalue = curr;
}
return maxvalue;
}
public static void main(String[] args) {
System.out.println(getMostPopularElement(new int[]{1,2,3,4,5,6,7,7,7,7}));
}
If the array is not sorted, sort it with Arrays.sort(a);
Using Java 8 Streams
int data[] = { 1, 5, 7, 4, 6, 2, 0, 1, 3, 2, 2 };
Map<Integer, Long> count = Arrays.stream(data)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), counting()));
int max = count.entrySet().stream()
.max((first, second) -> {
return (int) (first.getValue() - second.getValue());
})
.get().getKey();
System.out.println(max);
Explanation
We convert the int[] data array to boxed Integer Stream. Then we collect by groupingBy on the element and use a secondary counting collector for counting after the groupBy.
Finally we sort the map of element -> count based on count again by using a stream and lambda comparator.
This one without maps:
public class Main {
public static void main(String[] args) {
int[] a = new int[]{ 1, 2, 3, 4, 5, 6, 7, 7, 7, 7 };
System.out.println(getMostPopularElement(a));
}
private static int getMostPopularElement(int[] a) {
int maxElementIndex = getArrayMaximumElementIndex(a);
int[] b = new int[a[maxElementIndex] + 1]
for (int i = 0; i < a.length; i++) {
++b[a[i]];
}
return getArrayMaximumElementIndex(b);
}
private static int getArrayMaximumElementIndex(int[] a) {
int maxElementIndex = 0;
for (int i = 1; i < a.length; i++) {
if (a[i] >= a[maxElementIndex]) {
maxElementIndex = i;
}
}
return maxElementIndex;
}
}
You only have to change some code if your array can have elements which are < 0.
And this algorithm is useful when your array items are not big numbers.
If you don't want to use a map, then just follow these steps:
Sort the array (using Arrays.sort())
Use a variable to hold the most popular element (mostPopular), a variable to hold its number of occurrences in the array (mostPopularCount), and a variable to hold the number of occurrences of the current number in the iteration (currentCount)
Iterate through the array. If the current element is the same as mostPopular, increment currentCount. If not, reset currentCount to 1. If currentCount is > mostPopularCount, set mostPopularCount to currentCount, and mostPopular to the current element.
Seems like you are looking for the Mode value (Statistical Mode) , have a look at Apache's Docs for Statistical functions.
package frequent;
import java.util.HashMap;
import java.util.Map;
public class Frequent_number {
//Find the most frequent integer in an array
public static void main(String[] args) {
int arr[]= {1,2,3,4,3,2,2,3,3};
System.out.println(getFrequent(arr));
System.out.println(getFrequentBySorting(arr));
}
//Using Map , TC: O(n) SC: O(n)
static public int getFrequent(int arr[]){
int ans=0;
Map<Integer,Integer> m = new HashMap<>();
for(int i:arr){
if(m.containsKey(i)){
m.put(i, m.get(i)+1);
}else{
m.put(i, 1);
}
}
int maxVal=0;
for(Integer in: m.keySet()){
if(m.get(in)>maxVal){
ans=in;
maxVal = m.get(in);
}
}
return ans;
}
//Sort the array and then find it TC: O(nlogn) SC: O(1)
public static int getFrequentBySorting(int arr[]){
int current=arr[0];
int ansCount=0;
int tempCount=0;
int ans=current;
for(int i:arr){
if(i==current){
tempCount++;
}
if(tempCount>ansCount){
ansCount=tempCount;
ans=i;
}
current=i;
}
return ans;
}
}
Array elements value should be less than the array length for this one:
public void findCounts(int[] arr, int n) {
int i = 0;
while (i < n) {
if (arr[i] <= 0) {
i++;
continue;
}
int elementIndex = arr[i] - 1;
if (arr[elementIndex] > 0) {
arr[i] = arr[elementIndex];
arr[elementIndex] = -1;
}
else {
arr[elementIndex]--;
arr[i] = 0;
i++;
}
}
Console.WriteLine("Below are counts of all elements");
for (int j = 0; j < n; j++) {
Console.WriteLine(j + 1 + "->" + Math.Abs(arr[j]));
}
}
Time complexity of this will be O(N) and space complexity will be O(1).
import java.util.Scanner;
public class Mostrepeatednumber
{
public static void main(String args[])
{
int most = 0;
int temp=0;
int count=0,tempcount;
Scanner in=new Scanner(System.in);
System.out.println("Enter any number");
int n=in.nextInt();
int arr[]=new int[n];
System.out.print("Enter array value:");
for(int i=0;i<=n-1;i++)
{
int n1=in.nextInt();
arr[i]=n1;
}
//!!!!!!!! user input concept closed
//logic can be started
for(int j=0;j<=n-1;j++)
{
temp=arr[j];
tempcount=0;
for(int k=1;k<=n-1;k++)
{
if(temp==arr[k])
{
tempcount++;
}
if(count<tempcount)
{
most=arr[k];
count=tempcount;
}
}
}
System.out.println(most);
}
}
Best approach will be using map where key will be element and value will be the count of each element. Along with that keep an array of size that will contain the index of most popular element . Populate this array while map construction itself so that we don't have to iterate through map again.
Approach 2:-
If someone want to go with two loop, here is the improvisation from accepted answer where we don't have to start second loop from one every time
public class TestPopularElements {
public static int getPopularElement(int[] a) {
int count = 1, tempCount;
int popular = a[0];
int temp = 0;
for (int i = 0; i < (a.length - 1); i++) {
temp = a[i];
tempCount = 0;
for (int j = i+1; j < a.length; j++) {
if (temp == a[j])
tempCount++;
}
if (tempCount > count) {
popular = temp;
count = tempCount;
}
}
return popular;
}
public static void main(String[] args) {
int a[] = new int[] {1,2,3,4,5,6,2,7,7,7};
System.out.println("count is " +getPopularElement(a));
}
}
Assuming your int array is sorted, i would do...
int count = 0, occur = 0, high = 0, a;
for (a = 1; a < n.length; a++) {
if (n[a - 1] == n[a]) {
count++;
if (count > occur) {
occur = count;
high = n[a];
}
} else {
count = 0;
}
}
System.out.println("highest occurence = " + high);
public static int getMostCommonElement(int[] array) {
Arrays.sort(array);
int frequency = 1;
int biggestFrequency = 1;
int mostCommonElement = 0;
for(int i=0; i<array.length-1; i++) {
frequency = (array[i]==array[i+1]) ? frequency+1 : 1;
if(frequency>biggestFrequency) {
biggestFrequency = frequency;
mostCommonElement = array[i];
}
}
return mostCommonElement;
}
Mine Linear O(N)
Using map to save all the differents elements found in the array and saving the number of times ocurred, then just getting the max from the map.
import java.util.HashMap;
import java.util.Map;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.IntStream;
public class MosftOftenNumber {
// for O(N) + map O(1) = O(N)
public static int mostOftenNumber(int[] a)
{
final Map m = new HashMap<Integer,Integer>();
int max = 0;
int element = 0;
for (int i=0; i<a.length; i++){
//initializing value for the map the value will have the counter of each element
//first time one new number its found will be initialize with zero
if (m.get(a[i]) == null)
m.put(a[i],0);
//save each value from the array and increment the count each time its found
m.put(a[i] , (Integer) m.get(a[i]) + 1);
//check the value from each element and comparing with max
if ( (Integer) m.get(a[i]) > max){
max = (Integer) m.get(a[i]);
element = a[i];
}
}
System.out.println("Times repeated: " + max);
return element;
}
public static int mostOftenNumberWithLambdas(int[] a)
{
Integer max = IntStream.of(a).boxed().max(Integer::compareTo).get();
Integer coumtMax = Math.toIntExact(IntStream.of(a).boxed().filter(number -> number.equals(max)).count());
System.out.println("Times repeated: " + coumtMax);
return max;
}
public static void main(String args[]) {
// int[] array = {1,1,2,1,1};
// int[] array = {2,2,1,2,2};
int[] array = {1,2,3,4,5,6,7,7,7,7};
System.out.println("Most often number with loops: " + mostOftenNumber(array));
System.out.println("Most often number with lambdas: " + mostOftenNumberWithLambdas(array));
}
}
Solution 1: Hashmap: O(n)
def most_freq_elem(arr):
frequency = {}
most_frequent, most_count = -1, 0
for num in arr:
frequency[num] = frequency.get(num, 0) + 1
if frequency[num] > most_count:
most_count = frequency[num]
most_frequent = num
return most_frequent
Solution 2: Hashmap + Max: O(n)
def most_freq_elem(arr):
frequency = {}
for num in arr:
frequency[num] = frequency.get(num, 0) + 1
return max(frequency, key=frequency.get)
public static void main(String[] args) {
int[] myArray = {1,5,4,4,22,4,9,4,4,8};
Map<Integer,Integer> arrayCounts = new HashMap<>();
Integer popularCount = 0;
Integer popularValue = 0;
for(int i = 0; i < myArray.length; i++) {
Integer count = arrayCounts.get(myArray[i]);
if (count == null) {
count = 0;
}
arrayCounts.put(myArray[i], count == 0 ? 1 : ++count);
if (count > popularCount) {
popularCount = count;
popularValue = myArray[i];
}
}
System.out.println(popularValue + " --> " + popularCount);
}
below code can be put inside a main method
// TODO Auto-generated method stub
Integer[] a = { 11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 1, 2, 2, 2, 2, 3, 4, 2 };
List<Integer> list = new ArrayList<Integer>(Arrays.asList(a));
Set<Integer> set = new HashSet<Integer>(list);
int highestSeq = 0;
int seq = 0;
for (int i : set) {
int tempCount = 0;
for (int l : list) {
if (i == l) {
tempCount = tempCount + 1;
}
if (tempCount > highestSeq) {
highestSeq = tempCount;
seq = i;
}
}
}
System.out.println("highest sequence is " + seq + " repeated for " + highestSeq);
public class MostFrequentIntegerInAnArray {
public static void main(String[] args) {
int[] items = new int[]{2,1,43,1,6,73,5,4,65,1,3,6,1,1};
System.out.println("Most common item = "+getMostFrequentInt(items));
}
//Time Complexity = O(N)
//Space Complexity = O(N)
public static int getMostFrequentInt(int[] items){
Map<Integer, Integer> itemsMap = new HashMap<Integer, Integer>(items.length);
for(int item : items){
if(!itemsMap.containsKey(item))
itemsMap.put(item, 1);
else
itemsMap.put(item, itemsMap.get(item)+1);
}
int maxCount = Integer.MIN_VALUE;
for(Entry<Integer, Integer> entry : itemsMap.entrySet()){
if(entry.getValue() > maxCount)
maxCount = entry.getValue();
}
return maxCount;
}
}
int largest = 0;
int k = 0;
for (int i = 0; i < n; i++) {
int count = 1;
for (int j = i + 1; j < n; j++) {
if (a[i] == a[j]) {
count++;
}
}
if (count > largest) {
k = a[i];
largest = count;
}
}
So here n is the length of the array, and a[] is your array.
First, take the first element and check how many times it is repeated and increase the counter (count) as to see how many times it occurs.
Check if this maximum number of times that a number has so far occurred if yes, then change the largest variable (to store the maximum number of repetitions) and if you would like to store the variable as well, you can do so in another variable (here k).
I know this isn't the fastest, but definitely, the easiest way to understand
import java.util.HashMap;
import java.util.Map;
import java.lang.Integer;
import java.util.Iterator;
public class FindMood {
public static void main(String [] args){
int arrayToCheckFrom [] = {1,2,4,4,5,5,5,3,3,3,3,3,3,3,3};
Map map = new HashMap<Integer, Integer>();
for(int i = 0 ; i < arrayToCheckFrom.length; i++){
int sum = 0;
for(int k = 0 ; k < arrayToCheckFrom.length ; k++){
if(arrayToCheckFrom[i]==arrayToCheckFrom[k])
sum += 1;
}
map.put(arrayToCheckFrom[i], sum);
}
System.out.println(getMaxValue(map));
}
public static Integer getMaxValue( Map<Integer,Integer> map){
Map.Entry<Integer,Integer> maxEntry = null;
Iterator iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<Integer,Integer> pair = (Map.Entry<Integer,Integer>) iterator.next();
if(maxEntry == null || pair.getValue().compareTo(maxEntry.getValue())>0){
maxEntry = pair;
}
}
return maxEntry.getKey();
}
}
Comparing two arrays, I Hope for that this is useful for you.
public static void main(String []args){
int primerArray [] = {1,2,1,3,5};
int arrayTow [] = {1,6,7,8};
int numberMostRepetly = validateArrays(primerArray,arrayTow);
System.out.println(numberMostRepetly);
}
public static int validateArrays(int primerArray[], int arrayTow[]){
int numVeces = 0;
for(int i = 0; i< primerArray.length; i++){
for(int c = i+1; c < primerArray.length; c++){
if(primerArray[i] == primerArray[c]){
numVeces = primerArray[c];
// System.out.println("Numero que mas se repite");
//System.out.println(numVeces);
}
}
for(int a = 0; a < arrayTow.length; a++){
if(numVeces == arrayTow[a]){
// System.out.println(numVeces);
return numVeces;
}
}
}
return 0;
}
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class MostOccuringEleementInArrayOfIntegers {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 4, 5, 3, 2, 1, 6, 7, 1, 2, 3, 2 };
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int num : arr) {
if (map.containsKey(num)) {
map.put(num, map.get(num) + 1);
} else {
map.put(num, 1);
}
}
Set<Entry<Integer, Integer>> entrySet = map.entrySet();
int max = 1;
int mostFrequent = 1;
for (Entry<Integer, Integer> e : map.entrySet()) {
// Swapping of the elements who is occuring most
if (e.getValue() > max) {
mostFrequent = e.getKey();
max = e.getValue();
}
}
// Print most frequent element
System.out.println("Most frequent element: " + mostFrequent);
}
}
public class MostFrequentNumber {
public MostFrequentNumber() {
}
int frequentNumber(List<Integer> list){
int popular = 0;
int holder = 0;
for(Integer number: list) {
int freq = Collections.frequency(list,number);
if(holder < freq){
holder = freq;
popular = number;
}
}
return popular;
}
public static void main(String[] args){
int[] numbers = {4,6,2,5,4,7,6,4,7,7,7};
List<Integer> list = new ArrayList<Integer>();
for(Integer num : numbers){
list.add(num);
}
MostFrequentNumber mostFrequentNumber = new MostFrequentNumber();
System.out.println(mostFrequentNumber.frequentNumber(list));
}
}
You can count the occurrences of the different numbers, then look for the highest one. This is an example that uses a Map, but could relatively easily be adapted to native arrays.
Second largest element:
Let us take example : [1,5,4,2,3] in this case,
Second largest element will be 4.
Sort the Array in descending order, once the sort done output will be
A = [5,4,3,2,1]
Get the Second Largest Element from the sorted array Using Index 1. A[1] -> Which will give the Second largest element 4.
private static int getMostOccuringElement(int[] A) {
Map occuringMap = new HashMap();
//count occurences
for (int i = 0; i < A.length; i++) {
if (occuringMap.get(A[i]) != null) {
int val = occuringMap.get(A[i]) + 1;
occuringMap.put(A[i], val);
} else {
occuringMap.put(A[i], 1);
}
}
//find maximum occurence
int max = Integer.MIN_VALUE;
int element = -1;
for (Map.Entry<Integer, Integer> entry : occuringMap.entrySet()) {
if (entry.getValue() > max) {
max = entry.getValue();
element = entry.getKey();
}
}
return element;
}
I hope this helps.
public class Ideone {
public static void main(String[] args) throws java.lang.Exception {
int[] a = {1,2,3,4,5,6,7,7,7};
int len = a.length;
System.out.println(len);
for (int i = 0; i <= len - 1; i++) {
while (a[i] == a[i + 1]) {
System.out.println(a[i]);
break;
}
}
}
}
This is the wrong syntax. When you create an anonymous array you MUST NOT give its size.
When you write the following code :
new int[] {1,23,4,4,5,5,5};
You are here creating an anonymous int array whose size will be determined by the number of values that you provide in the curly braces.
You can assign this a reference as you have done, but this will be the correct syntax for the same :-
int[] a = new int[]{1,2,3,4,5,6,7,7,7,7};
Now, just Sysout with proper index position:
System.out.println(a[7]);

Returning the index of the n-th highest value of an unsorted list

I have written the following code and am now trying to figure out the best way to achieve what is explained in the four comments:
Integer[] expectedValues = new Integer[4];
for (int i = 0; i <= 3; i++) {
expectedValues[i] = getExpectedValue(i);
}
int choice = randomNumGenerator.nextInt(100) + 1;
if (choice <= intelligence) {
// return index of highest value in expectedValues
} else if (choice <= intelligence * 2) {
// return index of 2nd highest value in expectedValues
} else if (choice <= intelligence * 3) {
// return index of 3rd highest value in expectedValues
} else {
// return index of lowest value in expectedValues
}
What would be an elegant way o doing so? I do not need to keep expected values as an array - I am happy to use any data structure.
You could create a new array containing the indices and sort on the values - in semi-pseudo code it could look like this (to be adapted):
int[][] valueAndIndex = new int[n][2];
//fill array:
valueAndIndex[i][0] = i;
valueAndIndex[i][1] = expectedValues[i];
//sort on values in descending order
Arrays.sort(valueAndIndex, (a, b) -> Integer.compare(b[1], a[1]));
//find n-th index
int n = 3; //3rd largest number
int index = valueAndIndex[n - 1][0];
If you want to work with simple arrays, maybe this might be a solution:
public static void main(String[] args) {
int[] arr = new int[] { 1, 4, 2, 3 };
int[] sorted = sortedCopy(arr);
int choice = randomNumGenerator.nextInt(100) + 1;
if (choice <= intelligence) {
System.out.println(findIndex(arr, sorted[3])); // 1
} else if (choice <= intelligence * 2) {
System.out.println(findIndex(arr, sorted[2])); // 3
} else if (choice <= intelligence * 3) {
System.out.println(findIndex(arr, sorted[1])); // 2
} else {
System.out.println(findIndex(arr, sorted[0])); // 0
}
}
static int[] sortedCopy(int[] arr) {
int[] copy = new int[arr.length];
System.arraycopy(arr, 0, copy, 0, arr.length);
Arrays.sort(copy);
return copy;
}
static int findIndex(int[] arr, int val) {
int index = -1;
for (int i = 0; i < arr.length; ++i) {
if (arr[i] == val) {
index = i;
break;
}
}
return index;
}
You can "wipe out" the highest value n-1 times. After this the highest value is the n-th highest value of the original array:
public static void main(String[] args) {
int[] numbers = new int[]{5, 9, 1, 4};
int n = 2; // n-th index
for (int i = 0; i < n - 1; ++i) {
int maxIndex = findMaxIndex(numbers);
numbers[maxIndex] = Integer.MIN_VALUE;
}
int maxIndex = findMaxIndex(numbers);
System.out.println(maxIndex + " -> " + numbers[maxIndex]);
}
public static int findMaxIndex(int[] numbers) {
int maxIndex = 0;
for (int j = 1; j < numbers.length; ++j) {
if (numbers[j] > numbers[maxIndex]) {
maxIndex = j;
}
}
return maxIndex;
}
The complexity is O(n * numbers.length).

find the most popular element in int array in java array {2,3,4,2,3,3,2,9,5} [duplicate]

int[] a = new int[10]{1,2,3,4,5,6,7,7,7,7};
how can I write a method and return 7?
I want to keep it native without the help of lists, maps or other helpers.
Only arrays[].
Try this answer. First, the data:
int[] a = {1,2,3,4,5,6,7,7,7,7};
Here, we build a map counting the number of times each number appears:
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i : a) {
Integer count = map.get(i);
map.put(i, count != null ? count+1 : 1);
}
Now, we find the number with the maximum frequency and return it:
Integer popular = Collections.max(map.entrySet(),
new Comparator<Map.Entry<Integer, Integer>>() {
#Override
public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
}).getKey();
As you can see, the most popular number is seven:
System.out.println(popular);
> 7
EDIT
Here's my answer without using maps, lists, etc. and using only arrays; although I'm sorting the array in-place. It's O(n log n) complexity, better than the O(n^2) accepted solution.
public int findPopular(int[] a) {
if (a == null || a.length == 0)
return 0;
Arrays.sort(a);
int previous = a[0];
int popular = a[0];
int count = 1;
int maxCount = 1;
for (int i = 1; i < a.length; i++) {
if (a[i] == previous)
count++;
else {
if (count > maxCount) {
popular = a[i-1];
maxCount = count;
}
previous = a[i];
count = 1;
}
}
return count > maxCount ? a[a.length-1] : popular;
}
public int getPopularElement(int[] a)
{
int count = 1, tempCount;
int popular = a[0];
int temp = 0;
for (int i = 0; i < (a.length - 1); i++)
{
temp = a[i];
tempCount = 0;
for (int j = 1; j < a.length; j++)
{
if (temp == a[j])
tempCount++;
}
if (tempCount > count)
{
popular = temp;
count = tempCount;
}
}
return popular;
}
Take a map to map element - > count
Iterate through array and process the map
Iterate through map and find out the popular
Assuming your array is sorted (like the one you posted) you could simply iterate over the array and count the longest segment of elements, it's something like #narek.gevorgyan's post but without the awfully big array, and it uses the same amount of memory regardless of the array's size:
private static int getMostPopularElement(int[] a){
int counter = 0, curr, maxvalue, maxcounter = -1;
maxvalue = curr = a[0];
for (int e : a){
if (curr == e){
counter++;
} else {
if (counter > maxcounter){
maxcounter = counter;
maxvalue = curr;
}
counter = 0;
curr = e;
}
}
if (counter > maxcounter){
maxvalue = curr;
}
return maxvalue;
}
public static void main(String[] args) {
System.out.println(getMostPopularElement(new int[]{1,2,3,4,5,6,7,7,7,7}));
}
If the array is not sorted, sort it with Arrays.sort(a);
Using Java 8 Streams
int data[] = { 1, 5, 7, 4, 6, 2, 0, 1, 3, 2, 2 };
Map<Integer, Long> count = Arrays.stream(data)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), counting()));
int max = count.entrySet().stream()
.max((first, second) -> {
return (int) (first.getValue() - second.getValue());
})
.get().getKey();
System.out.println(max);
Explanation
We convert the int[] data array to boxed Integer Stream. Then we collect by groupingBy on the element and use a secondary counting collector for counting after the groupBy.
Finally we sort the map of element -> count based on count again by using a stream and lambda comparator.
This one without maps:
public class Main {
public static void main(String[] args) {
int[] a = new int[]{ 1, 2, 3, 4, 5, 6, 7, 7, 7, 7 };
System.out.println(getMostPopularElement(a));
}
private static int getMostPopularElement(int[] a) {
int maxElementIndex = getArrayMaximumElementIndex(a);
int[] b = new int[a[maxElementIndex] + 1]
for (int i = 0; i < a.length; i++) {
++b[a[i]];
}
return getArrayMaximumElementIndex(b);
}
private static int getArrayMaximumElementIndex(int[] a) {
int maxElementIndex = 0;
for (int i = 1; i < a.length; i++) {
if (a[i] >= a[maxElementIndex]) {
maxElementIndex = i;
}
}
return maxElementIndex;
}
}
You only have to change some code if your array can have elements which are < 0.
And this algorithm is useful when your array items are not big numbers.
If you don't want to use a map, then just follow these steps:
Sort the array (using Arrays.sort())
Use a variable to hold the most popular element (mostPopular), a variable to hold its number of occurrences in the array (mostPopularCount), and a variable to hold the number of occurrences of the current number in the iteration (currentCount)
Iterate through the array. If the current element is the same as mostPopular, increment currentCount. If not, reset currentCount to 1. If currentCount is > mostPopularCount, set mostPopularCount to currentCount, and mostPopular to the current element.
Seems like you are looking for the Mode value (Statistical Mode) , have a look at Apache's Docs for Statistical functions.
package frequent;
import java.util.HashMap;
import java.util.Map;
public class Frequent_number {
//Find the most frequent integer in an array
public static void main(String[] args) {
int arr[]= {1,2,3,4,3,2,2,3,3};
System.out.println(getFrequent(arr));
System.out.println(getFrequentBySorting(arr));
}
//Using Map , TC: O(n) SC: O(n)
static public int getFrequent(int arr[]){
int ans=0;
Map<Integer,Integer> m = new HashMap<>();
for(int i:arr){
if(m.containsKey(i)){
m.put(i, m.get(i)+1);
}else{
m.put(i, 1);
}
}
int maxVal=0;
for(Integer in: m.keySet()){
if(m.get(in)>maxVal){
ans=in;
maxVal = m.get(in);
}
}
return ans;
}
//Sort the array and then find it TC: O(nlogn) SC: O(1)
public static int getFrequentBySorting(int arr[]){
int current=arr[0];
int ansCount=0;
int tempCount=0;
int ans=current;
for(int i:arr){
if(i==current){
tempCount++;
}
if(tempCount>ansCount){
ansCount=tempCount;
ans=i;
}
current=i;
}
return ans;
}
}
Array elements value should be less than the array length for this one:
public void findCounts(int[] arr, int n) {
int i = 0;
while (i < n) {
if (arr[i] <= 0) {
i++;
continue;
}
int elementIndex = arr[i] - 1;
if (arr[elementIndex] > 0) {
arr[i] = arr[elementIndex];
arr[elementIndex] = -1;
}
else {
arr[elementIndex]--;
arr[i] = 0;
i++;
}
}
Console.WriteLine("Below are counts of all elements");
for (int j = 0; j < n; j++) {
Console.WriteLine(j + 1 + "->" + Math.Abs(arr[j]));
}
}
Time complexity of this will be O(N) and space complexity will be O(1).
import java.util.Scanner;
public class Mostrepeatednumber
{
public static void main(String args[])
{
int most = 0;
int temp=0;
int count=0,tempcount;
Scanner in=new Scanner(System.in);
System.out.println("Enter any number");
int n=in.nextInt();
int arr[]=new int[n];
System.out.print("Enter array value:");
for(int i=0;i<=n-1;i++)
{
int n1=in.nextInt();
arr[i]=n1;
}
//!!!!!!!! user input concept closed
//logic can be started
for(int j=0;j<=n-1;j++)
{
temp=arr[j];
tempcount=0;
for(int k=1;k<=n-1;k++)
{
if(temp==arr[k])
{
tempcount++;
}
if(count<tempcount)
{
most=arr[k];
count=tempcount;
}
}
}
System.out.println(most);
}
}
Best approach will be using map where key will be element and value will be the count of each element. Along with that keep an array of size that will contain the index of most popular element . Populate this array while map construction itself so that we don't have to iterate through map again.
Approach 2:-
If someone want to go with two loop, here is the improvisation from accepted answer where we don't have to start second loop from one every time
public class TestPopularElements {
public static int getPopularElement(int[] a) {
int count = 1, tempCount;
int popular = a[0];
int temp = 0;
for (int i = 0; i < (a.length - 1); i++) {
temp = a[i];
tempCount = 0;
for (int j = i+1; j < a.length; j++) {
if (temp == a[j])
tempCount++;
}
if (tempCount > count) {
popular = temp;
count = tempCount;
}
}
return popular;
}
public static void main(String[] args) {
int a[] = new int[] {1,2,3,4,5,6,2,7,7,7};
System.out.println("count is " +getPopularElement(a));
}
}
Assuming your int array is sorted, i would do...
int count = 0, occur = 0, high = 0, a;
for (a = 1; a < n.length; a++) {
if (n[a - 1] == n[a]) {
count++;
if (count > occur) {
occur = count;
high = n[a];
}
} else {
count = 0;
}
}
System.out.println("highest occurence = " + high);
public static int getMostCommonElement(int[] array) {
Arrays.sort(array);
int frequency = 1;
int biggestFrequency = 1;
int mostCommonElement = 0;
for(int i=0; i<array.length-1; i++) {
frequency = (array[i]==array[i+1]) ? frequency+1 : 1;
if(frequency>biggestFrequency) {
biggestFrequency = frequency;
mostCommonElement = array[i];
}
}
return mostCommonElement;
}
Mine Linear O(N)
Using map to save all the differents elements found in the array and saving the number of times ocurred, then just getting the max from the map.
import java.util.HashMap;
import java.util.Map;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.IntStream;
public class MosftOftenNumber {
// for O(N) + map O(1) = O(N)
public static int mostOftenNumber(int[] a)
{
final Map m = new HashMap<Integer,Integer>();
int max = 0;
int element = 0;
for (int i=0; i<a.length; i++){
//initializing value for the map the value will have the counter of each element
//first time one new number its found will be initialize with zero
if (m.get(a[i]) == null)
m.put(a[i],0);
//save each value from the array and increment the count each time its found
m.put(a[i] , (Integer) m.get(a[i]) + 1);
//check the value from each element and comparing with max
if ( (Integer) m.get(a[i]) > max){
max = (Integer) m.get(a[i]);
element = a[i];
}
}
System.out.println("Times repeated: " + max);
return element;
}
public static int mostOftenNumberWithLambdas(int[] a)
{
Integer max = IntStream.of(a).boxed().max(Integer::compareTo).get();
Integer coumtMax = Math.toIntExact(IntStream.of(a).boxed().filter(number -> number.equals(max)).count());
System.out.println("Times repeated: " + coumtMax);
return max;
}
public static void main(String args[]) {
// int[] array = {1,1,2,1,1};
// int[] array = {2,2,1,2,2};
int[] array = {1,2,3,4,5,6,7,7,7,7};
System.out.println("Most often number with loops: " + mostOftenNumber(array));
System.out.println("Most often number with lambdas: " + mostOftenNumberWithLambdas(array));
}
}
Solution 1: Hashmap: O(n)
def most_freq_elem(arr):
frequency = {}
most_frequent, most_count = -1, 0
for num in arr:
frequency[num] = frequency.get(num, 0) + 1
if frequency[num] > most_count:
most_count = frequency[num]
most_frequent = num
return most_frequent
Solution 2: Hashmap + Max: O(n)
def most_freq_elem(arr):
frequency = {}
for num in arr:
frequency[num] = frequency.get(num, 0) + 1
return max(frequency, key=frequency.get)
public static void main(String[] args) {
int[] myArray = {1,5,4,4,22,4,9,4,4,8};
Map<Integer,Integer> arrayCounts = new HashMap<>();
Integer popularCount = 0;
Integer popularValue = 0;
for(int i = 0; i < myArray.length; i++) {
Integer count = arrayCounts.get(myArray[i]);
if (count == null) {
count = 0;
}
arrayCounts.put(myArray[i], count == 0 ? 1 : ++count);
if (count > popularCount) {
popularCount = count;
popularValue = myArray[i];
}
}
System.out.println(popularValue + " --> " + popularCount);
}
below code can be put inside a main method
// TODO Auto-generated method stub
Integer[] a = { 11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 1, 2, 2, 2, 2, 3, 4, 2 };
List<Integer> list = new ArrayList<Integer>(Arrays.asList(a));
Set<Integer> set = new HashSet<Integer>(list);
int highestSeq = 0;
int seq = 0;
for (int i : set) {
int tempCount = 0;
for (int l : list) {
if (i == l) {
tempCount = tempCount + 1;
}
if (tempCount > highestSeq) {
highestSeq = tempCount;
seq = i;
}
}
}
System.out.println("highest sequence is " + seq + " repeated for " + highestSeq);
public class MostFrequentIntegerInAnArray {
public static void main(String[] args) {
int[] items = new int[]{2,1,43,1,6,73,5,4,65,1,3,6,1,1};
System.out.println("Most common item = "+getMostFrequentInt(items));
}
//Time Complexity = O(N)
//Space Complexity = O(N)
public static int getMostFrequentInt(int[] items){
Map<Integer, Integer> itemsMap = new HashMap<Integer, Integer>(items.length);
for(int item : items){
if(!itemsMap.containsKey(item))
itemsMap.put(item, 1);
else
itemsMap.put(item, itemsMap.get(item)+1);
}
int maxCount = Integer.MIN_VALUE;
for(Entry<Integer, Integer> entry : itemsMap.entrySet()){
if(entry.getValue() > maxCount)
maxCount = entry.getValue();
}
return maxCount;
}
}
int largest = 0;
int k = 0;
for (int i = 0; i < n; i++) {
int count = 1;
for (int j = i + 1; j < n; j++) {
if (a[i] == a[j]) {
count++;
}
}
if (count > largest) {
k = a[i];
largest = count;
}
}
So here n is the length of the array, and a[] is your array.
First, take the first element and check how many times it is repeated and increase the counter (count) as to see how many times it occurs.
Check if this maximum number of times that a number has so far occurred if yes, then change the largest variable (to store the maximum number of repetitions) and if you would like to store the variable as well, you can do so in another variable (here k).
I know this isn't the fastest, but definitely, the easiest way to understand
import java.util.HashMap;
import java.util.Map;
import java.lang.Integer;
import java.util.Iterator;
public class FindMood {
public static void main(String [] args){
int arrayToCheckFrom [] = {1,2,4,4,5,5,5,3,3,3,3,3,3,3,3};
Map map = new HashMap<Integer, Integer>();
for(int i = 0 ; i < arrayToCheckFrom.length; i++){
int sum = 0;
for(int k = 0 ; k < arrayToCheckFrom.length ; k++){
if(arrayToCheckFrom[i]==arrayToCheckFrom[k])
sum += 1;
}
map.put(arrayToCheckFrom[i], sum);
}
System.out.println(getMaxValue(map));
}
public static Integer getMaxValue( Map<Integer,Integer> map){
Map.Entry<Integer,Integer> maxEntry = null;
Iterator iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<Integer,Integer> pair = (Map.Entry<Integer,Integer>) iterator.next();
if(maxEntry == null || pair.getValue().compareTo(maxEntry.getValue())>0){
maxEntry = pair;
}
}
return maxEntry.getKey();
}
}
Comparing two arrays, I Hope for that this is useful for you.
public static void main(String []args){
int primerArray [] = {1,2,1,3,5};
int arrayTow [] = {1,6,7,8};
int numberMostRepetly = validateArrays(primerArray,arrayTow);
System.out.println(numberMostRepetly);
}
public static int validateArrays(int primerArray[], int arrayTow[]){
int numVeces = 0;
for(int i = 0; i< primerArray.length; i++){
for(int c = i+1; c < primerArray.length; c++){
if(primerArray[i] == primerArray[c]){
numVeces = primerArray[c];
// System.out.println("Numero que mas se repite");
//System.out.println(numVeces);
}
}
for(int a = 0; a < arrayTow.length; a++){
if(numVeces == arrayTow[a]){
// System.out.println(numVeces);
return numVeces;
}
}
}
return 0;
}
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class MostOccuringEleementInArrayOfIntegers {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 4, 5, 3, 2, 1, 6, 7, 1, 2, 3, 2 };
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int num : arr) {
if (map.containsKey(num)) {
map.put(num, map.get(num) + 1);
} else {
map.put(num, 1);
}
}
Set<Entry<Integer, Integer>> entrySet = map.entrySet();
int max = 1;
int mostFrequent = 1;
for (Entry<Integer, Integer> e : map.entrySet()) {
// Swapping of the elements who is occuring most
if (e.getValue() > max) {
mostFrequent = e.getKey();
max = e.getValue();
}
}
// Print most frequent element
System.out.println("Most frequent element: " + mostFrequent);
}
}
public class MostFrequentNumber {
public MostFrequentNumber() {
}
int frequentNumber(List<Integer> list){
int popular = 0;
int holder = 0;
for(Integer number: list) {
int freq = Collections.frequency(list,number);
if(holder < freq){
holder = freq;
popular = number;
}
}
return popular;
}
public static void main(String[] args){
int[] numbers = {4,6,2,5,4,7,6,4,7,7,7};
List<Integer> list = new ArrayList<Integer>();
for(Integer num : numbers){
list.add(num);
}
MostFrequentNumber mostFrequentNumber = new MostFrequentNumber();
System.out.println(mostFrequentNumber.frequentNumber(list));
}
}
You can count the occurrences of the different numbers, then look for the highest one. This is an example that uses a Map, but could relatively easily be adapted to native arrays.
Second largest element:
Let us take example : [1,5,4,2,3] in this case,
Second largest element will be 4.
Sort the Array in descending order, once the sort done output will be
A = [5,4,3,2,1]
Get the Second Largest Element from the sorted array Using Index 1. A[1] -> Which will give the Second largest element 4.
private static int getMostOccuringElement(int[] A) {
Map occuringMap = new HashMap();
//count occurences
for (int i = 0; i < A.length; i++) {
if (occuringMap.get(A[i]) != null) {
int val = occuringMap.get(A[i]) + 1;
occuringMap.put(A[i], val);
} else {
occuringMap.put(A[i], 1);
}
}
//find maximum occurence
int max = Integer.MIN_VALUE;
int element = -1;
for (Map.Entry<Integer, Integer> entry : occuringMap.entrySet()) {
if (entry.getValue() > max) {
max = entry.getValue();
element = entry.getKey();
}
}
return element;
}
I hope this helps.
public class Ideone {
public static void main(String[] args) throws java.lang.Exception {
int[] a = {1,2,3,4,5,6,7,7,7};
int len = a.length;
System.out.println(len);
for (int i = 0; i <= len - 1; i++) {
while (a[i] == a[i + 1]) {
System.out.println(a[i]);
break;
}
}
}
}
This is the wrong syntax. When you create an anonymous array you MUST NOT give its size.
When you write the following code :
new int[] {1,23,4,4,5,5,5};
You are here creating an anonymous int array whose size will be determined by the number of values that you provide in the curly braces.
You can assign this a reference as you have done, but this will be the correct syntax for the same :-
int[] a = new int[]{1,2,3,4,5,6,7,7,7,7};
Now, just Sysout with proper index position:
System.out.println(a[7]);

Find smallest number K , if exists, such that product of its digits is N. Eg:when N = 6, smallest number is k=16(1*6=6) and not k=23(2*3=6)

I have made this program using array concept in java. I am getting Exception as ArrayIndexOutOfBound while trying to generate product.
I made the function generateFNos(int max) to generate factors of the given number. For example a number 6 will have factors 1,2,3,6. Now,i tried to combine the first and the last digit so that the product becomes equal to 6.
I have not used the logic of finding the smallest number in that array right now. I will do it later.
Question is Why i am getting Exception as ArrayIndexOutOfBound? [i couldn't figure out]
Below is my code
public class SmallestNoProduct {
public static void generateFNos(int max) {
int ar[] = new int[max];
int k = 0;
for (int i = 1; i <= max; i++) {
if (max % i == 0) {
ar[k] = i;
k++;
}
}
smallestNoProduct(ar);
}
public static void smallestNoProduct(int x[]) {
int j[] = new int[x.length];
int p = x.length;
for (int d = 0; d < p / 2;) {
String t = x[d++] + "" + x[p--];
int i = Integer.parseInt(t);
j[d] = i;
}
for (int u = 0; u < j.length; u++) {
System.out.println(j[u]);
}
}
public static void main(String s[]) {
generateFNos(6);
}
}
****OutputShown****
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at SmallestNoProduct.smallestNoProduct(SmallestNoProduct.java:36)
at SmallestNoProduct.generateFNos(SmallestNoProduct.java:27)
at SmallestNoProduct.main(SmallestNoProduct.java:52)
#Edit
The improved Code using array only.
public class SmallestNoProduct {
public static void generateFNos(int max) {
int s = 0;
int ar[] = new int[max];
int k = 0;
for (int i = 1; i <= max; i++) {
if (max % i == 0) {
ar[k] = i;
k++;
s++;
}
}
for (int g = 0; g < s; g++) {
System.out.println(ar[g]);
}
smallestNoProduct(ar, s);
}
public static void smallestNoProduct(int x[], int s) {
int j[] = new int[x.length];
int p = s - 1;
for (int d = 0; d < p;) {
String t = x[d++] + "" + x[p--];
System.out.println(t);
int i = Integer.parseInt(t);
j[d] = i;
}
/*for (int u = 0; u < j.length; u++) {
System.out.println(j[u]);
}*/
}
public static void main(String s[]) {
generateFNos(6);
}
}
Maybe it better:
public class SmallestNoProduct {
public static int smallest(int n) {
int small = n*n;
for(int i = 1; i < Math.sqrt(n); i++) {
if(n%i == 0) {
int temp = Integer.parseInt(""+i+""+n/i);
int temp2 = Integer.parseInt(""+n/i+""+i);
temp = temp2 < temp? temp2: temp;
if(temp < small) {
small = temp;
}
}
}
return small;
}
public static void main(String[] args) {
System.out.println(smallest(6)); //6
System.out.println(smallest(10)); //25
System.out.println(smallest(100)); //205
}
}
Problem lies in this line
String t=x[d++]+""+x[p--];
x[p--] will try to fetch 7th position value, as p is length of array x i.e. 6 which results in ArrayIndexOutOfBound exception. Array index starts from 0, so max position is 5 and not 6.
You can refer this question regarding postfix expression.
Note: I haven't checked your logic, this answer is only to point out the cause of exception.
We are unnecessarily using array here...
below method should work....
public int getSmallerMultiplier(int n)
{
if(n >0 && n <10) // if n is 6
return (1*10+n); // it will be always (1*10+6) - we cannot find smallest number than this
else
{
int number =10;
while(true)
{
//loop throuogh the digits of n and check for their multiplication
number++;
}
}
}
int num = n;
for(i=9;i>1;i--)
{
while(n%d==0)
{
n=n/d;
arr[i++] = d;
}
}
if(num<=9)
arr[i++] = 1;
//printing array in reverse order;
for(j=i-1;j>=0;j--)
system.out.println(arr[j]);

Categories

Resources