I have an array that its size is 15 and has a positive digit in each element. How do I count how many times each digit between 0 til 9 has been in my array and print out " o has been appears x times, 1 appears y times, 2 appears z times" and on till 9
CodePudding user response:
This is what I will do (assuming numbers in first array are only one digit):
let numbersCount = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] //each index is for numbers from 0 to 9
let myArray = [1, 1, 1, 2,...] // array of numbers with positive digits
myArray.foreach(num => numbersCount[num] );
console.log(numbersCount) // numbersCount = [0, 3, 1, ...];
which 0 is the count of 0 in myArray, 3 is the count of 1, 1 is the count of 2, ... .
CodePudding user response:
The logic is similar to counting sort. I think it will be good for you to read the explanation about counting sort: Counting Sort.
The following code might answer your question:
#include <stdio.h>
#define ARR_SIZE 15
#define COUNT_ARR_SIZE 10
int main()
{
int i = 0;
int arr[ARR_SIZE] = {0,1,1,2,2,2,9,3,4,3,2,5,6,7,8};
int countArr[COUNT_ARR_SIZE] = {0};
for(i = 0; i < ARR_SIZE; i )
countArr[arr[i]] ;
for(i = 0; i < COUNT_ARR_SIZE; i )
printf("Number %d appears %d times in the array\n", i,countArr[i]);
return 0;
}
Note: The code is written in C language.
CodePudding user response:
The question asked here is to calculate the frequency of each digits in your array. So better you use a hashmap data structure to calculate it in leaner time complexity. and the key of the hashmap will be each of the digits of your array and corresponding value is its frequency. This approach is dynamic and no need to initialize an auxiliary array with fixed size to hold the frequency.
Map<Integer, Integer> map = new HashMap<>();
for(Integer digit: Array){
if(map.containsKey(digit)){
map.put(digit, map.get(digit) 1);
}
else map.put(digit,1);
}
So the map will contain: key-> digits; value-> corresponding frequency