Write a recursive method that parses a binary number as a string into a decimal
ID: 3681042 • Letter: W
Question
Write a recursive method that parses a binary number as a string into a decimal integer. (String permutation) Write a recursive method to print all the permutations of a string. For example, for the string abc: abc acb bac bca cab cba using following two methods: public Static void displayPermutations (String s) public Static void display Permutations (String s2)//helper method, uses a loop to move a character from s2 to s1 and recursively invokes it with a new s1 and s2. The base case is that s2 is empty and print s1 to the console. Write a test program that prompts the user to enter a string and displays all is permutations.Explanation / Answer
/**The java program TestPermutation that prompts
* the user to enter a string and prints
* the permuations of string.*/
//TestPermutation.java
import java.util.Scanner;
public class TestPermutation {
public static void main(String[] args) {
//Create a scanner class object
Scanner scanner=new Scanner(System.in);
System.out.println("Enter string to permute");
//read string from usre
String s=scanner.nextLine();
//call permutation
permutation(s);
}
/**The method permutation that takes string s and
* calls the helper metod permuation that takes an empty
* string and s as input and prints the permuations of string
* s*/
public static void permutation(String s) {
permutation("", s);
}
private static void permutation(String s1, String s2) {
int n = s2.length();
if (n == 0)
System.out.println(s1);
else
{
//loop to get permuation of each character
//from the string,s2
for (int i = 0; i < n; i++)
//Remove first character from s2 and add to s1
//Call permuation to find the permutations
permutation(s1 + s2.charAt(i),
s2.substring(0, i) + s2.substring(i+1, n));
}
}
}
--------------------------------------------------------------------------------------------------------------------
Sample output:
Enter string to permute
abc
abc
acb
bac
bca
cab
cba
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.