I want to create a program to help me with the statistics, but I'm having problems from the beginning and I'm making a huge mess to calculate the relative frequency of an array with random numbers and only one dimension.
For example to generate these numbers:
{3, 5, 5, 2, 4, 1, 3, 5, 4}
I want that the program tell me that the 3 is repeated 2 times, the 4 3 times and 5 5 times
I've created a class to sort these values in order to calculate the median, the first and third quartile, but I still do not know how to find the frequency in order to calculate other values
Thanks for your time
PS: Do not know if this affects anything but I'm using netbeans
You are looking for this for sure: Collections: frequency
If you dont have a Collection, convert your array to list first:
Collections.frequency(Arrays.asList(yourArray), new Integer(3))
If your range of numbers is relatively small, using an array of counters could be preferred.
For example, if your random numbers are in the interval [1,5] then you can use an array of size 5 to store and update the frequency counters:
int[] numbers = {3, 5, 5, 2, 4, 1, 3, 5, 4} ;
int[] frequencies = new int[5];
for(int n : numbers)
frequencies[n-1]++;
Output array (frequencies):
1 1 2 2 3
EDIT:
This method can be applied to all ranges. For example, let's say you have numbers in the range [500,505]:
int[] frequencies = new int[6];
for(int n : numbers)
frequencies[n-500]++;
Edit: You can use a map for storing frequency like below :
import java.util.HashMap;
import java.util.Map;
public class Frequency {
public static void main(String[] args) {
int[] nums = { 3, 5, 5, 2, 4, 1, 3, 5, 4 };
int count = 1;
// number,frequency type map.
Map<Integer, Integer> frequencyMap = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
if (nums[i] != -1) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] != -1) {
if (nums[i] == nums[j]) {
// -1 is an indicator that this number is already counted.
// You should replace it such a number which is sure to be not coming in array.
nums[j] = -1;
count++;
}
}
}
frequencyMap.put(nums[i], count);
count = 1;
}
}
for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {
System.out.println(" Number :" + entry.getKey()
+ " has frequence :" + entry.getValue());
}
}
}
With Output :
Number :1 has frequence :1
Number :2 has frequence :1
Number :3 has frequence :2
Number :4 has frequence :2
Number :5 has frequence :3
int[] numbers = {100, 101, 102, 103, 5 , 4, 4 , 6} ;
Map<Integer, Integer> m = new HashMap<Integer, Integer>();
for(int num: numbers){
if(m.containsKey(num)){
m.put(num, m.get(num)+1);
}else{
m.put(num, 1);
}
}
for (Map.Entry<Integer, Integer> entry : m.entrySet()) {
System.out.println("Key: " + entry.getKey() + " | Frequencey: " + entry.getValue());
}
Related
I'm working on the following task.
Given an array of n integers and two integer numbers m and k.
You can add any positive integer to any element of the array such that
the total value does not exceed k.
The task is to maximize the
multiples of m in the resultant array.
Consider the following example.
Input:
n = 5, m = 2, k = 2, arr[] = [1, 2, 3, 4, 5]
Let's add 1 to the element arr[0] and 1 to arr[2] then the final array would be:
[2, 2, 4, 4, 5]
Now there are four (4) elements which are multiples of m (2).
I am not getting correct output.
My code:
public class Main {
public static void main(String[] args) {
int n = 5;
int m = 4;
int k = 3;
int count = 0;
int[] arr = {17, 8, 9, 1, 4};
for (int i = 0; i < n; i++) {
for (int j = 0; j <= k; j++) {
// check initial
if (arr[i] % m == 0) {
break;
}
// add
arr[i] = arr[i] + j;
// check again
if (arr[i] % m == 0) {
count++;
break;
}
}
}
System.out.println("Final Array : " + Arrays.toString(arr));
System.out.println("Count : " + count);
}
}
This task boils down to a well-known Dynamic programming algorithm called Knapsack problem after a couple of simple manipulations with the given array.
This approach doesn't require sorting and would be advantages when k is much smaller n.
We can address the problem in the following steps:
Iterate over the given array and count all the numbers that are already divisible by m (this number is stored in the variable count in the code below).
While iterating, for every element of the array calculate the difference between m and remainder from the division of this element by m. Which would be equal to m - currentElement % m. If the difference is smaller or equal to k (it can cave this difference) it should be added to the list (differences in the code below) and also accumulated in a variable which is meant to store the total difference (totalDiff). All the elements which produce difference that exceeds k would be omitted.
If the total difference is less than or equal to k - we are done, the return value would be equal to the number of elements divisible by m plus the size of the list of differences.
Otherwise, we need to apply the logic of the Knapsack problem to the list of differences.
The idea behind the method getBestCount() (which is an implementation Knapsack problem) boils down to generating the "2D" array (a nested array of length equal to the size of the list of differences +1, in which every inner array having the length of k+1) and populating it with maximum values that could be achieved for various states of the Knapsack.
Each element of this array would represent the maximum total number of elements which can be adjusted to make them divisible by m for the various sizes of the Knapsack, i.e. number of items available from the list of differences, and different number of k (in the range from 0 to k inclusive).
The best way to understand how the algorithm works is to draw a table on a piece of paper and fill it with numbers manually (follow the comments in the code, some intermediate variables were introduced only for the purpose of making it easier to grasp, and also see the Wiki article linked above).
For instance, if the given array is [1, 8, 3, 9, 5], k=3 and m=3. We can see 2 elements divisible by m - 3 and 9. Numbers 1, 8, 5 would give the following list of differences [2, 1, 1]. Applying the logic of the Knapsack algorithm, we should get the following table:
[0, 0, 0, 0]
[0, 0, 1, 1]
[0, 1, 1, 2]
[0, 1, 2, 2]
We are interested in the value right most column of the last row, which is 2 plus 2 (number of elements divisible by 3) would give us 4.
Note: that code provided below can dial only with positive numbers. I don't want to shift the focus from the algorithm to such minor details. If OP or reader of the post are interested in making the code capable to work with negative number as well, I'm living the task of adjusting the code for them as an exercise. Hint: only a small change in the countMultiplesOfM() required for that purpose.
That how it might be implemented:
public static int countMultiplesOfM(int[] arr, int k, int m) {
List<Integer> differences = new ArrayList<>();
int count = 0;
long totalDiff = 0; // counter for the early kill - case when `k >= totalDiff`
for (int next : arr) {
if (next % m == 0)
count++; // number is already divisible by `m` we can increment the count and from that moment we are no longer interested in it
else if (m - next % m <= k) {
differences.add(m - next % m);
totalDiff += m - next % m;
}
}
if (totalDiff <= k) { // early kill - `k` is large enough to adjust all numbers in the `differences` list
return count + differences.size();
}
return count + getBestCount(differences, k); // fire the rest logic
}
// Knapsack Algorithm implementation
public static int getBestCount(List<Integer> differences, int knapsackSize) {
int[][] tab = new int[differences.size() + 1][knapsackSize + 1];
for (int numItemAvailable = 1; numItemAvailable < tab.length; numItemAvailable++) {
int next = differences.get(numItemAvailable - 1); // next available item which we're trying to place to knapsack to Maximize the current total
for (int size = 1; size < tab[numItemAvailable].length; size++) {
int prevColMax = tab[numItemAvailable][size - 1]; // maximum result for the current size - 1 in the current row of the table
int prevRowMax = tab[numItemAvailable - 1][size]; // previous maximum result for the current knapsack's size
if (next <= size) { // if it's possible to fit the next item in the knapsack
int prevRowMaxWithRoomForNewItem = tab[numItemAvailable - 1][size - next] + 1; // maximum result from the previous row for the size = `current size - next` (i.e. the closest knapsack size which guarantees that there would be a space for the new item)
tab[numItemAvailable][size] = Math.max(prevColMax, prevRowMaxWithRoomForNewItem);
} else {
tab[numItemAvailable][size] = Math.max(prevRowMax, prevColMax); // either a value in the previous row or a value in the previous column of the current row
}
}
}
return tab[differences.size()][knapsackSize];
}
main()
public static void main(String[] args) {
System.out.println(countMultiplesOfM(new int[]{17, 8, 9, 1, 4}, 3, 4));
System.out.println(countMultiplesOfM(new int[]{1, 2, 3, 4, 5}, 2, 2));
System.out.println(countMultiplesOfM(new int[]{1, 8, 3, 9, 5}, 3, 3));
}
Output:
3 // input array [17, 8, 9, 1, 4], m = 4, k = 3
4 // input array [1, 2, 3, 4, 5], m = 2, k = 2
4 // input array [1, 8, 3, 9, 5], m = 3, k = 3
A link to Online Demo
You must change 2 line in your code :
if(arr[i]%m==0)
{
count++; // add this line
break;
}
// add
arr[i]=arr[i]+1; // change j to 1
// check again
if(arr[i]%m==0)
{
count++;
break;
}
The first is because the number itself is divisible.
and The second is because you add a number to it each time.That is wrong.
for example chenge your arr to :
int[] arr ={17,8,10,2,4};
your output is :
Final Array : [20, 8, 16, 8, 4]
and That is wrong because 16-10=6 and is bigger than k=3.
I believe the problem is that you aren't processing the values in ascending order of the amount by which to adjust.
To solve this I started by using a stream to preprocess the array. This could be done using other methods.
map the values to the amount to make each one, when added, divisible by m.
filter out those that equal to m' (already divisible by m`)
sort in ascending order.
Once that is done. Intialize max to the difference between the original array length and the processed length. This is the number already divisible by m.
As the list is iterated
check to see if k > amount needed. If so, subtract from k and increment max
otherwise break out of the loop (because of the sort, no value remaining can be less than k)
public static int maxDivisors(int m, int k, int[] arr) {
int[] need = Arrays.stream(arr).map(v -> m - v % m)
.filter(v -> v != m).sorted().toArray();
int max = arr.length - need.length;
for (int val : need) {
if (k >= val) {
k -= val;
max++;
} else {
break;
}
}
return max;
}
int m = 4;
int k = 3;
int[] arr ={17,8,9,1,4};
int count = maxDivisors(m, k, arr);
System.out.println(count);
prints
3
I am working on an HW assignment that asks to write a method called count that determines the number of times a target value appears in an array. For example, if your array is [2, 3, 3, 3, 4, 6, 7, 8, 8, 9], the value 8 appears twice and the number 4 appears once. You should know that the method has two parameters and one return value. The code works but the problem that I am having is when I print the statement "The value x[i] appears count(x,x[i]) times" it repeats the same statement when it should only print the statement for each value. I need help on making it so it will only print the statement as long as the value is different from the one before it if it is the same as the value before it the code should skip and move on to the next value in the array until it prints everything.
import java.util.Arrays;
public class Q7 {
public static void main(String[] args) {
int[] x = { 2, 3, 3, 3, 4, 6, 7, 8, 8, 9 };
System.out.println(Arrays.toString(x));
for (int i = 0; i < x.length; i++) {
System.out.println("The value " + x[i] + " appears " + count(x, x[i]) + " times.");
}
}
public static int count(int[] array, int target) {
int counter = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == target) {
counter++;
}
}
return counter;
}
}
Output:
[2, 3, 3, 3, 4, 6, 7, 8, 8, 9]
The value 2 appears 1 times.
The value 3 appears 3 times.
The value 3 appears 3 times.
The value 3 appears 3 times.
The value 4 appears 1 times.
The value 6 appears 1 times.
The value 7 appears 1 times.
The value 8 appears 2 times.
The value 8 appears 2 times.
The value 9 appears 1 times.
in the case of your example (because the array is sorted), you can just
change
for (int i = 0; i < x.length; i++)
to
for (int i = 0; i < x.length; i = i + count(x, x[i]))
It will skip duplicate items.
You must somehow remember for which values you have already printed the message. there are several ways to do this. For example, you could sort your array and only output the message if you hit a value you didn't have yet while iterating. Another simple approach would be to add the elements to a set to get unique values of the array. Example with a set:
public static void main(String[] args) {
int[] x = { 2, 3, 3, 3, 4, 6, 7, 8, 8, 9 };
System.out.println(Arrays.toString(x));
Set<Integer> set = new HashSet<>();
for (int i = 0; i < x.length; i++) {
if(set.add(x[i])){
System.out.println("The value " + x[i] + " appears " + count(x, x[i]) + " times.");
}
}
}
Suppose we have a list of integers. I would like to detect and print on the screen the most frequently repeated item . I know how to do it when the most common element is only one. However, if we have such a list which contains these elements:
10, 5, 2, 1, 2, 4, 6, 6, 6, 6, 10, 10, 10
i want to print a six and a ten so I mean I want to print all the most frequently repeated elements no matter how many there are..
You would need a map (aka dictionary) data structure to solve this problem. This is the fastest and most concise solution I could come up with.
public static void main(String[] args){
int[] arr = new int[]{10, 5, 2, 1, 2, 4, 6, 6, 6, 6, 10, 10, 10};
printMostFrequent(arr);
}
private static void printMostFrequent(int[] arr){
// Key: number in input array
// Value: amount of times that number appears in the input array
Map<Integer, Integer> counts = new HashMap<>();
// The most amount of times the same number appears in the input array. In this example, it's 4.
int highestFrequency = 0;
// Iterate through input array, populating map.
for (int num : arr){
// If number doesn't exist in map already, its frequency is 1. Otherwise, add 1 to its current frequency.
int currFrequency = counts.getOrDefault(num, 0) + 1;
// Update frequency of current number.
counts.put(num, currFrequency);
// If the current number has the highest frequency so far, store its frequency for later use.
highestFrequency = Math.max(currFrequency, highestFrequency);
}
// Iterate through unique numbers in array (remember, a Map in Java allows no duplicate keys).
for (int key : counts.keySet()){
// If the current number has the highest frequency, then print it to console.
if (counts.get(key) == highestFrequency){
System.out.println(key);
}
}
}
Output
6
10
nums = [10, 5, 2, 1, 2, 4, 6, 6, 6, 6, 10, 10, 10]
def most_recurrent_ints(arr):
log = {}
for i in arr:
if i in log:
log[i] += 1
else:
log[i] = 1
current_max = 0
for i in log.values():
if i > current_max:
current_max = i
results = []
for k, v in log.items():
if v == current_max:
results.append(k)
return results
print(most_recurrent_ints(nums))
I'm bad at Java but this is the Python solution, maybe someone can translate. I can do it in JS if you need.
Have you considered using a dictionary-type data structure? I am not a java person, so this may not be pretty, but it does what you are looking for:
final int[] array = new int[]{ 10, 5, 2, 1, 2, 4, 6, 6, 6, 6, 10, 10, 10 };
Map<Integer, Integer> dictionary = new HashMap<Integer,Integer>();
for(int i = 0; i < array.length; ++i){
int val = array[i];
if(dictionary.containsKey(val)){
dictionary.put(val, dictionary.get(val) + 1);
}else{
dictionary.put(val, 1);
}
}
for(Map.Entry<Integer,Integer> entry : dictionary.entrySet()){
System.out.println(entry.getKey() + ": " + entry.getValue());
}
This would output:
1: 1
2: 2
4: 1
5: 1
6: 4
10: 4
public static void main(String[] args) {
MostFrequent(new Integer[] {10, 5, 2, 1, 2, 4, 6, 6, 6, 6, 10, 10, 10});
}
static void MostFrequent(Integer[] arr) {
Map<Integer, Integer> count = new HashMap<Integer, Integer>();
for (Integer element : arr) {
if (!count.containsKey(element)) {
count.put(element,0);
}
count.put(element, count.get(element) + 1);
}
Map.Entry<Integer, Integer> maxEntry = null;
ArrayList<Integer> list = new ArrayList<Integer>();
for (Map.Entry<Integer, Integer> entry : count.entrySet()) {
if (maxEntry == null || entry.getValue() > maxEntry.getValue()) {
list.clear();
list.add(entry.getKey());
maxEntry = entry;
}
else if (entry.getValue() == maxEntry.getValue()) {
list.add(entry.getKey());
}
}
for (Integer item: list) {
System.out.println(item);
}
}
Output:
6
10
I am a newbie to programming. I am trying to create a program that would display an array in reverse. Plus also find the even and odd numbers of an array,sum the count and also display the even and odd numbers. The code works but the problem is that it also reverses the even and odd arrays and it shows this weird zero in those arrays. What am I doing wrong?
Please also provide explanation. Thanks!
import java.util.Arrays;
public class ArrayTest {
public static void main(String[] args)
{
int[] array = {1,2,3,4,5,6,7,8,9,10,11,12,13};
for ( int i=0; i<array.length/2; i++ )
{
int temp = array[i];
array[i] = array[array.length-(1+i)];
array[array.length-(1+i)] = temp;
}
System.out.println("Array after reverse: \n" + Arrays.toString(array));
int even=0;
int odd=0;
int[] Even = new int[13];
int[] Odd = new int[13];
for ( int i=0; i<array.length; i++)
{
if (array[i] % 2 == 0)
{
Even[i] = array[i];
even++;
}
else
{
Odd[i] = array[i];
odd++;
}
}
System.out.println("Even: "+even+" ");
System.out.println(Arrays.toString(Even));
System.out.println("Odd: "+odd+" ");
System.out.println(Arrays.toString(Odd));
}
}
The output is:
Array after reverse:
[13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Even: 6
[0, 12, 0, 10, 0, 8, 0, 6, 0, 4, 0, 2, 0]
Odd: 7
[13, 0, 11, 0, 9, 0, 7, 0, 5, 0, 3, 0, 1]
You need to correct your logic
int[] Even = new int[(array.length/2)+1];
int[] Odd = new int[(array.length/2)+1];
for ( int i=0; i<array.length; i++)
{
if (array[i] % 2 == 0)
{
Even[even] = array[i];
even++;
}
else
{
Odd[odd] = array[i];
odd++;
}
}
As per you code, you are initializing array of size 13 for odd and even, which is not correct.
int[] Even = new int[13];
int[] Odd = new int[13];
So, by default, Even and Odd array will be initialized by 0 value. Then, you are setting value as per main array, which a size of 13 on alternate basis (even/odd).
==Updated==
Since, you don't want Even and Odd array in reverse order. Then, you can move the code up.
>>Demo<<
You faced 2 problems (I guess so)
The odd and even arrays are also in reverse order
Reason: The first For loop reverses the 'array' and stores the results in array itself. So, the next time when you try working with 'array' to find odd/even numbers, you are actually working with the reversed array.
Solution: You can assign the original array to a backup array and use that backup array to find odd and even nos.
Unnecessary zeros:
Reason: In your second for loop you used odd[i]=array[i] which seems to be a logical error in your code. Consider the case:
value of i : 0 1 2 3 4 5 ... 12
value of array[i]: 1 2 3 4 5 6 ... 13
value of odd[i] : 1 0 3 0 5 0 ... 13
value of even[i] : 0 2 0 4 0 6 ... 0
This means, the control inside for loop is made to flow either to if{} block or the else{} block and not the both. So, when if(condition) is satisfied, then even[i] array will be updated. But meanwhile what happens to the odd[i] array? It retains the inital value '0'. That's it!
I hope the following code helps you:
import java.util.Arrays;
public class A
{
public static void main(String[] args)
{
int[] array = {1,2,3,4,5,6,7,8,9,10,11,12,13};
int[] arr2 = new int[array.length]; // backup array
arr2=Arrays.copyOfRange(array,0,array.length);
for ( int i=0; i<arr2.length/2; i++ )
{
int temp = arr2[i];
arr2[i] = arr2[arr2.length-(1+i)];
arr2[arr2.length-(1+i)] = temp;
}
System.out.println("Array after reverse: \n" + Arrays.toString(arr2));
int even=0;
int odd=0;
int[] Even = new int[13];
int[] Odd = new int[13];
for ( int i=0; i<array.length; i++)
{
if (array[i] % 2 == 0)
{
Even[even] = array[i];
even++;
}
else
{
Odd[odd] = array[i];
odd++;
}
}
Even=Arrays.copyOfRange(Even,0,even);
Odd=Arrays.copyOfRange(Odd,0,odd);
System.out.println("Even: "+even+" ");
System.out.println(Arrays.toString(Even));
System.out.println("Odd: "+odd+" ");
System.out.println(Arrays.toString(Odd));
}
}
Note: I have used Arrays.copyOfRange(array,start,end) function to copy a certain part of the array from start to end-1 position.
Output:
Array after reverse:
[13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Even: 6
[2, 4, 6, 8, 10, 12]
Odd: 7
[1, 3, 5, 7, 9, 11, 13]
Hope this helps :)
--Mathan Madhav
You select even and odd numbers from reversed array.
You use wrong index for even and odd arrays.
If you don't want to see zeros in output, use print in for statement. Another solution - firstly count odd and even numbers and create arrays with exact size.
import java.util.Arrays;
public class ArrayTest {
public static void main(String[] args)
{
int[] array = {1,2,3,4,5,6,7,8,9,10,11,12,13};
int even=0;
int odd=0;
int[] Even = new int[13];
int[] Odd = new int[13];
for ( int i=0; i<array.length; i++)
{
if (array[i] % 2 == 0)
{
Even[even++] = array[i];
}
else
{
Odd[odd++] = array[i];
}
}
for ( int i=0; i<array.length/2; i++ )
{
int temp = array[i];
array[i] = array[array.length-(1+i)];
array[array.length-(1+i)] = temp;
}
System.out.println("Array after reverse: \n" + Arrays.toString(array));
System.out.println("Even: "+even+" ");
System.out.println(Arrays.toString(Even));
System.out.println("Odd: "+odd+" ");
System.out.println(Arrays.toString(Odd));
}
}
I have an integer array: int[] numbers = new int[...n]; // n being limitless.
Where all the numbers are between 0 and 100.
Say numbers[] was equal to: [52, 67, 32, 43, 32, 21, 12, 5, 0, 3, 2, 0, 0];
I want to count how often each of those numbers occur.
I've got a second array: int[] occurrences = new int[100];.
I'd like to be able to store the amounts like such:
for(int i = 0; i < numbers.length; i++) {
// Store amount of 0's in numbers[] to occurrences[0]
// Store amount of 1's in numbers[] to occurrences[1]
}
So that occurrences[0] would be equal to 3, occurrences[1] would be equal to 0 etc.
Is there any efficient way of doing this without having to resort to external libraries? thanks.
You can simply do something like this:
for (int a : numbers) {
occurrences[a]++;
}
Also, if you mean 0 to 100 inclusive then occurrences will need to be of size 101 (i.e. 100 will need to be the maximum index).
You might also want to perform an "assertion" to ensure that each element of numbers is indeed in the valid range before you update occurrences.
Updated to put results in the 100-array.
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/**
<P>{#code java IntOccurancesInArray}</P>
**/
public class IntOccurancesInArray {
public static final void main(String[] igno_red) {
int[] ai = new int[]{52, 67, 32, 43, 32, 21, 12, 5, 0, 3, 2, 0, 0};
Map<Integer,Integer> mpNumWHits = new TreeMap<Integer,Integer>();
for(int i = 0; i < ai.length; i++) {
int iValue = ai[i];
if(!mpNumWHits.containsKey(iValue)) {
mpNumWHits.put(iValue, 1);
} else {
mpNumWHits.put(iValue, (mpNumWHits.get(iValue) + 1));
}
}
Set<Integer> stInts = mpNumWHits.keySet();
Iterator<Integer> itrInts = stInts.iterator();
int[] ai100 = new int[100];
int i = 0;
while(itrInts.hasNext()) {
int iValue = itrInts.next();
int iHits = mpNumWHits.get(iValue);
System.out.println(iValue + " found " + iHits + " times");
ai100[iValue] = iHits;
}
for(int j = 0; j < ai100.length; j++) {
if(ai100[j] > 0) {
System.out.println("ai100[" + j + "]=" + ai100[j]);
}
}
}
}
Output:
[C:\java_code\]java IntOccurancesInArray
0 found 3 times
2 found 1 times
3 found 1 times
5 found 1 times
12 found 1 times
21 found 1 times
32 found 2 times
43 found 1 times
52 found 1 times
67 found 1 times
ai100[0]=3
ai100[2]=1
ai100[3]=1
ai100[5]=1
ai100[12]=1
ai100[21]=1
ai100[32]=2
ai100[43]=1
ai100[52]=1
ai100[67]=1
This method is useful for knowing occurrences of all elements
You can reduce the space by finding the length of new array using sorting and taking value of last element + 1
import java.util.Arrays;
public class ArrayMain {
public static void main(String[] args) {
int a[] = {52, 67, 32, 43, 32, 21, 12, 5, 0, 3, 2, 0, 0};
Arrays.sort(a);
int len=a[a.length-1]+1;
int count[]=new int[len];
for(int n:a){
count[n]++;
}
for(int j=0;j<count.length;j++){
if(count[j]>=1){
System.out.println("count:"+j+"---"+count[j]);
}
}
}
}
Time Complexity : O(n)
Space Complexity : O(R) // last element value +1
Note : Creating new array may not be good idea if you have extreme numbers like 1, 2 and 96, 99 etc in terms of space.
For this case sorting and comparing next element is better approach
import java.util.Scanner;
public class CountNumOccurences {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[] frequency = new int[100];
System.out.println("Enter the first integer: ");
int number = input.nextInt();
//Enter up to 100 integers, 0 to terminate
while (number != 0){
++frequency[number];
//read the next integer
System.out.print(
"Enter the next int value (zero to exit): ");
number = input.nextInt();
}
input.close();
System.out.println("Value\tFrequency");
for (int i = 0; i < frequency.length; i++) {
if (frequency[i] > 0){
if (frequency[i] > 1)
System.out.println(i + " occurs " + frequency[i] + " times");
else
System.out.println(i + " occurs " + frequency[i] + " time");
}
}
}
}