In: Computer Science
Problem 1: Recursive anagram finder
please used Java please
Write a program that will take a word and print out every combination of letters in that word. For example, "sam" would print out sam, sma, asm, ams, mas, msa (the ordering doesn't matter)
input:
cram
output:
cram
crma
carm
camr
cmra
cmar
rcam
rcma
racm
ramc
rmca
rmac
acrm
acmr
arcm
armc
amcr
amrc
mcra
mcar
mrca
mrac
macr
marc
Hints:
Your recursive function should have no return value and two parameters: string letters and string wordSoFar. You can initially call it getComb("sam","");
Base case:
no letters left. print out the word and return
Recursive case:
go through each letter from the word, remove it from letters (use substring), add it to wordSoFar, call the recursive function
Program Code Screenshot :
Sample Output :
Program Code to Copy
class Main{ static void getComb(String a, String b){ //If first string is empty, second string is the anagram if(a.isEmpty()){ System.out.println(b); return; } for(int i=0;i<a.length();i++){ //Add ith character to b recursively and proceed getComb(a.substring(0,i)+a.substring(i+1),b+a.charAt(i)); } } public static void main(String[] args) { getComb("abc",""); } }