I’ve written a java prog that stores some values:
public class array05 { public static void main(String[] args) { //placement of value int arryNum[] = {2,3,4,5,4,4,3}; //placement of index, to start at 0 for(int counter=0;counter<arryNum.length;counter++){ System.out.println(counter + ":" + arryNum[counter]); } } }
which generate such output:
0:2
1:3
2:4
3:5
4:4
5:4
6:3
and now I need to count numbers in this output #1. Output #2 should be this:
1: 0
2: 1
3: 2
4: 3
5: 1
It means it counts ONE 2, TWO 3, THREE 4, and only One 5.
I am not sure how to write the code for output 2. Is a binary search needed here?
can anybody shed a light?
Advertisement
Answer
if you are expecting in your array values between 1-5 (i assuming this from your expected output)
int arryNum[] = { 2, 3, 4, 5, 4, 4, 3 }; int[] counter = new int[] { 0, 0, 0, 0, 0 }; for (int i = 0; i < arryNum.length; i++) { counter[arryNum[i] - 1]++; } for (int i = 0; i < counter.length; i++) System.out.println((i + 1) + ":" + counter[i]);