Write a recursive function that will test to see if the input String parameter b
ID: 3846160 • Letter: W
Question
Write a recursive function that will test to see if the input String parameter belongs to the following format:
L = {S : S is in the form of AnB3n, for some n >= 0} where n and 3n are powers.
Test your function in main function.
----------------------------------------------------------------
The class should have two methods:
public static boolean IsIn(String w){ //body};
public static void main(String[] args)
----------------------------------------------------------------
Coding requirement:
public static void main(String[] args)
{
String str ="AABBBBBB";
if(IsIn(str))
System.out.println("The string " + str + " is in the language.");
else
System.out.println("The string " + str + " is in NOT the language.");
}
-----------------------------------------------------------------------------------------------------
• A recursive method calls itself.
IsIn(String w)
• Each recursive call, solves an identical, but smaller problem.
AABBBBBB
ABBB
• A test for the base case enables the recursive calls to stop
One of the smaller case?
w.length()==0
---------------------------------------------------------------------------------------------
Pseudocode
If base case == 0
return true
Else if check the characters
return IsIn(diminished string)
Else
return false
Explanation / Answer
#include<stdio.h>
char temp[100];
int fun(char str[])
{
int len=0,i=0;
// Base condition
if(str == '')
return 1;
len=strlen(str)-1;
//Base condition
if (len == -1)
return 1;
//Create temporary string with smaller substring eg if str="AABBBBBB" then temp="ABBB"
//note that in java you can use inbuilt function for that.
if((str[len] == str[len-1]) && (str[len-1] == str[len-2]) && str[0]=='A')
{
for(i=0;i<(len-3);i++)
{
temp[i]=str[i+1];
}
temp[i]='';
fun(temp);
}
else
return 0;
}
int main()
{
char str[]="AABBBBBB";
printf(" ans is %d", fun(str));
return 0;
}
Dear friend I have given you C program. You can implement similar thing any other language using similar logic
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.