Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Thursday, May 4, 2017

Generate String without concurrent 1's


For this we are using recursion approach.we will start from starting of array and check whether the n-1 th position is having 0 or 1.


If 0 then we will go with placing 0 , 1 at nth position and call it again by recursion and if 1 then place 0.


We will call recursion until 

length of generated string = given length.
We are going to check all the cases in recursion.


Code:
import java.util.*;
class generate1
{
static void generatestring(int k,int arr[],int n)
{
if(k==n)
{
for(int c:arr)
System.out.print(c);
System.out.print(" ");
return;
}
if(arr[n-1]==0)
{
arr[n]=0;
generatestring(k,arr,n+1);
arr[n]=1;
generatestring(k,arr,n+1);
}
if(arr[n-1]==1)
{
arr[n]=0;
generatestring(k,arr,n+1);
}
}
static void generate(int k)
{
int arr[]=new int[k];
arr[0]=0;
generatestring(k,arr,1);
arr[0]=1;
generatestring(k,arr,1);
}
public static void main(String args[])
{
Scanner ab=new Scanner(System.in);
int n=ab.nextInt();
generate(n);
}
}

0 Comments:

Post a Comment

Stats