Write in Java, a recursive method countBinaryStrings() that has one integer para
ID: 3823436 • Letter: W
Question
Write in Java, a recursive method countBinaryStrings() that has one integer parameter n and returns the number of binary strings of length n that do not have two consecutive 0's. For example, for n = 4, the number of binary strings of length 4 that do not contain two consecutive 0's is 8: 1111, 1110, 1101, 1011, 1010, 0111, 0110, 0101. For this problem, your method needs to return only the number of such strings, not the strings themselves. You may assume that the integer specified in the parameter is positive. Looking at the example above will give you a hint about how such strings start. The method should be static and embedded in a class called Recursion. This class should also have a main method. In this case, we will call the main method with an argument, the number of bits n. This argument will be in args[0]. You should convert it to an int using the Integer.parselnt method. Look this method up in the Java documentation to see what it does.Explanation / Answer
public class Combinations {
private static int stringCount = 0;
public static void countBinaryString(int i,int k,char[]buff) {
if(i<k)
{
buff[i] = '0';
countBinaryString(i+1,k,buff);
buff[i] = '1';
countBinaryString(i+1,k,buff);
}
// one combination ready
else
{
System.out.println(String.valueOf(buff));
boolean count = false;
// iterate and check if 2 consecutive 0's are there in array
for(int i1=0; i1<buff.length-1; i1++)
{
if(buff[i1]=='0' && buff[i1+1]=='0')
{
//System.out.println("Inside count true");
count = true;
System.out.println("Two adjacent 0 found ... stringCount is: "+stringCount +" ");
break;
}
}
if(count==false)
{
stringCount++;
System.out.println("One Such Non Adjacent 0 string found ... stringCount is: "+stringCount+" ");
}
}
}
public static void main(String[] args) {
int k = 4;
countBinaryString(0,k,new char[k]);
System.out.println(" ############ Total Count of strings are: "+stringCount + " ################");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.