Saturday, September 30, 2023
HomeSoftware EngineeringDiscover Depend of Most Frequent Merchandise in an Array in Java

Discover Depend of Most Frequent Merchandise in an Array in Java


The problem

Full the operate to search out the rely of probably the most frequent merchandise of an array. You possibly can assume that enter is an array of integers. For an empty array return “

Instance

enter array: [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3]
ouptut: 5 

The answer in Java code

Possibility 1:

import java.util.*;

public class Answer {
  public static int mostFrequentItemCount(int[] assortment) {
    if (assortment.size==0) return 0;
    Map<Integer, Integer> m = new HashMap<>();
    for (Integer i : assortment)
      m.merge(i, 1, Integer::sum);
    return Collections.max(m.values());
  }
}

Possibility 2:

import java.util.stream.Stream;
import java.util.Arrays;
import java.util.stream.Collectors;
import static java.util.operate.Operate.id;
import static java.util.stream.Collectors.counting;

public class Answer {
  public static int mostFrequentItemCount(int[] assortment) {
    return (int)Arrays.stream(assortment).mapToObj(i -> i)
        .gather(Collectors.groupingBy(id(), counting()))
        .values().stream().mapToLong(c -> (lengthy)c).max().orElse(0);
  }
}

Possibility 3:

import java.util.Collections;
import java.util.ArrayList;

public class Answer {
    public static int mostFrequentItemCount(int[] assortment) {
        ArrayList<Integer> arr = new ArrayList<>();
        for (Integer i : assortment)
            arr.add(i);
        int most = 0;
        for (Integer i: arr) {
            int b = Collections.frequency(arr,i);
            if (b>most)
            most=b;
        }
        return most;
    }
}

Take a look at instances to validate our answer

import org.junit.Take a look at;
import static org.junit.Assert.assertEquals;

public class FrequentExampleTests {
  @Take a look at
  public void assessments() {
    assertEquals(2, Answer.mostFrequentItemCount(new int[] {3, -1, -1}));
    assertEquals(5, Answer.mostFrequentItemCount(new int[] {3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3}));
  }
}
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments