Array: Random Characters generator + counter

Question: Generate 10 random characters and store them in an array. Count and display the occurrence of each letter in the character array

Example:

Output 1:

h e b w v s k a b j
a:1
b:2
c:0
d:0
e:1
f:0
g:0
h:1
i:0
j:1
k:1
l:0
m:0
n:0
o:0
p:0
q:0
r:0
s:1
t:0
u:0
v:1
w:1
x:0
y:0
z:0

Output 2:

d r k u d e u b b v
a:0
b:2
c:0
d:2
e:1
f:0
g:0
h:0
i:0
j:0
k:1
l:0
m:0
n:0
o:0
p:0
q:0
r:1
s:0
t:0
u:2
v:1
w:0
x:0
y:0
z:0

package Array;

/**
 * Created by aarushi on 1/5/21.
 * Q: Generate 10 random characters and store in array. Count the occurrence of each letter in the character array
 */
public class ArrayCountLetters {

    public static char[] createRandomCharArray (char [] ch){
        for (int i=0; i< ch.length; i++){
            //generate a random number between 0 and 25
            int randNumber= (int)(Math.random()*25);
            //the ascii values of lower case letters range from 97-122
            //add the random value to 97 and type cast it to char to get a random lower case character
            ch[i]= (char)(97+randNumber);
            //display the random character
            System.out.print(ch[i] + " ");
        }
        //return the char array
        return ch;
    }

    public static void displayArray (int [] count){
        for(int i=0; i<count.length; i++){
            //display in the form "<letter>: <count>"
            System.out.println(((char)(97+i))+ ":" + count[i]);
        }
    }

    public static void main (String [] args){
        //create an integer array of size 26 to store the count of each letter
        int [] count= new int[26];
        //initialize each element to 0
        for (int i=0; i<count.length; i++){
            count[i]=0;
        }
        char ch[]= new char[10];
        ch= createRandomCharArray(ch);

        for (int i=0; i<ch.length; i++){
            //increase the count of the letter
            count[(int)(ch[i]-97)]++;
        }
        System.out.println();
        displayArray(count);
    }


}

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.