Reputation: 793
i am trying to solve some basic java question:
i have an array like int[] x = { 12, 24, 33 };.
I need to break it into digits like {1, 2, 2, 4, 3 ,3}
and then count the repeating numbers this way: 1:1, 2:2, 3:2, 4:1.
Until now i got this code but i can't save the digits into array. Can some one help me ?
public class targil_2_3 {
public static void main(String[] args) {
int[] x = { 12, 24, 33 };
int[] ara = new int[x.length * 2];
for (int i = 0; i < x.length; i++) {
for (int j = 0; j < 2; j++) {
ara[j] = x[i] % 10;
x[i] = x[i] / 10;
System.out.println(ara[j]);
}
}
}
}
Upvotes: 0
Views: 153
Reputation: 4091
import java.util.Arrays;
import java.util.Map;
import static java.util.stream.Collectors.*;
public class Use {
public static void main(String[] args) {
int[] x = { 12, 24, 33 };
Map<Integer, Long> result = Arrays.stream(x).boxed()
.map(String::valueOf)
.collect(joining())
.chars().boxed()
.collect(groupingBy(Character::getNumericValue, counting()));
System.out.println(result); //prints {1=1, 2=2, 3=2, 4=1}
}
}
int[]
to a Stream<Integer>
(for each element)Stream<Integer>
to Stream<String>
Stream<String>
to String
Stream<Integer>
(for each digit)Map
Upvotes: 2
Reputation: 3391
we have only 10 decimal digits from 0 to 9 , [0..9]
so we make an array with length 10 , like count :
int count[] = new int[10];
for(int i = 0 ; i < x.length ; i++){
if( x[i] == 0 ){
count[0]++;
continue;
}
while(x[i]!=0){
int index = x[i] % 10;
count[index]++;
x[i] /= 10;
}
}
then we will have the number of digits in count array , so we can print it :
for(int i = 0 ; i < 10 ; i++)
System.out.println(i+" : "+count[i]);
if your data is so big it is better to use Map there are many ways to do this
Upvotes: 1
Reputation: 583
You dont need to store individual digits, you need to store just count for digits. Lets assume, that you're working with 10 based numbers, then code can looks like
public static void main(String[] args) {
int[] x = { 12, 24, 33, 0, 10, 555 };
int[] count = new int[10];
for (int i = 0; i < x.length; i++) {
int num = x[i];
if (num == 0) {
count[0]++;
continue;
}
while (num > 0) {
count[num % 10]++;
num = num / 10;
}
}
System.out.println(Arrays.toString(count));
}
Output is
[2, 2, 2, 2, 1, 3, 0, 0, 0, 0]
Upvotes: 3
Reputation: 1546
Digits are 0-9. Build a counter array of size 10, and count each digit extracted in the proper index of the counter array ("counter[digit]++").
Edit: Of- course, in the end you can build the desired result array based on the counter array.
For example: result[0] = "0:" + counter[0];"
Good Luck!
Upvotes: 0