0

I am trying to find anagrams of subsets of letters in a word; for example, if the word is "hello", the program will check the whole word, then the word with 1 letter missing and so on.

Here is my code, I'm not sure where I am doing wrong:

import java.util.*;
import java.io.*;
class Perm {
    public static void main(String[] args) {

        System.out.println(permutations("hello")); 
    }

    public static String permutations(String word) {
        String s = "";
        for(int i=0; i<word.length(); i++) {
            char ithChar = word.charAt(i);
            String newWord = word.substring(0,i) + word.substring(i+1);
            s = permutations(newWord);
        }
        return s;

    }
}
Unheilig
  • 16,196
  • 193
  • 68
  • 98
  • See http://stackoverflow.com/questions/4240080/generating-all-permutations-of-a-given-string on how to properly get all the permutations of a String in Java – smichak Mar 08 '15 at 13:14

2 Answers2

0

As I think you don't need this misunderstanding in the method. Try to rewrite it something like this:

public static void permutations(String word) {
    for(int i = word.length(); i > 0; i--){
        System.out.println(word.substring(0, i));
    }        
}

It is okay if you don't need to store this, just for printing. But as you guess the main idea is about to use decrementing loop.

sttimchenko
  • 401
  • 3
  • 15
0

Try something like this:

public class Perm {
  public static void main(String[] args) { 
    String word = "hello";
    for(int i=word.length(); i!=0; i--) {
        String permutation = word.substring(0, i);
        System.out.println(permutation);
    }
  }
}

It will take one character off the end of the word each time the loop runs, and you will get output like this:

hello
hell
hel
he
h

(It should also be easy to change it to take the letter off the beginning of the word).

I hope this is what you want, since the question is not very clear. (You may also want to look at this answer .)

Community
  • 1
  • 1
Jonas Czech
  • 12,018
  • 6
  • 44
  • 65