Using an array

From Progzoo
Jump to: navigation, search

In these tutorials you are passed an array of numbers (all numbers are between 0 and 9), you must process it using another array.

Show the frequency of each digit

You can create an array with ten items - one for each digit (you may be sure that all numbers in x are between 0 and 9).

if x is the list [1,1,1,5,9,9]
then the result will be

freq
0      0
1      3
2      0
3      0
4      0
5      1
6      0
7      0
8      0
9      2

Print the frequency of each digit


[Font] [Default] [Show] [Resize] [History] [Profile]

Show the number of different digits

If x is the list [1,1,1,5,9,9] then the result will be 3 because there are three different number (namely 1,5 and 9)

You can use the freq array created as above - then just count the number of non-zero elements using an accumulator:

 int acc = 0;
 for (int i=0;i<freq.length;i++)
   if (freq[i]>0)
     acc++;
 System.out.println(acc);

Print the number of different digits


[Font] [Default] [Show] [Resize] [History] [Profile]

Show the repeated digits

If x is the list [1,1,1,5,9,9] then the result will be 1 and 9 because 1 occurs more than once and 9 occurs twice.

You can use the freq array created as above - then just show the index when the freq is more than 1:

 for (int i=0;i<freq.length;i++)
   if (freq[i]>1)
     System.out.println(i);

Print the repeated digits


[Font] [Default] [Show] [Resize] [History] [Profile]

Show the missing digits

If x is the list [1,1,1,5,9,9] then the result will be 2 3 4 6 7 8 because these digits are not in the input list.

You can use the freq array created as above - then just print the indexes when the freq is 0:

 for (int i=0;i<freq.length;i++)
   if (freq[i]==0)
     System.out.println(i);

Print the missing digits


[Font] [Default] [Show] [Resize] [History] [Profile]