count the number of n letter word of the alphabet a b that
count the number of n letter word of the alphabet ? = (a, b) that don\'t contain the string aa
Implement in JAVA.
Question 2 {a,b} that do Write a function that counts the number of n-letter words of the alphabet not contain the string aa; use dynamic programming to speed-up the functionSolution
Answer:
Program code:
import java.io.*;
// Implements the class PrintLength string count
class PrintAllKLengthStringsCount
{
// Main method for testing the other methods
public static void main(String[] args)
{
//Prints the result
System.out.println(\"First Test\");
//defines the value
char setVal1[] = {\'a\', \'b\'};
int k1 =2;
//calls the printing all the Length
printAllKLengthCount(setVal1, k1);
//defines the count variable
int countVal=k1+1;
System.out.println(\"Number of letters that do not
contain \'aa\' is:\"+countVal);
}
//defines the method print all the lenght count
static void printAllKLengthCount(char setVal[], int k1)
{
//defines the length
int nth = setVal.length;
//calls the method
printAllKLengthRecCount(setVal, \"\", nth, k1);
}
//method that defines the prints the all recCount
static void printAllKLengthRecCount(char setVal[], String prefixs, int nth, int k1)
{
//checks the value k1 is 0
if (k1 == 0)
{
//prints the prefixes
System.out.println(prefixs);
return;
}
//adds the one by one character
for (int it = 0; it < nth; it++)
{
//input character is added
String newPrefixs = prefixs + setVal[it];
//recursive call of the function
printAllKLengthRecCount(setVal, newPrefixs, nth,
k1-1);
}
}
}
Sample output:
C:\\jdk1.6\\bin>javac PrintAllKLengthStringsCount.java
C:\\jdk1.6\\bin>java PrintAllKLengthStringsCount
First Test
aa
ab
ba
bb
Number of letters that do not contain \'aa\' is:3


