Pacific-Design.com

    
Home Index

1. Algorithms

2. Permutation

Algorithms / Permutation /

Premutation

import java.util.*;

public class Permutation {

    /*-----------------------------------------------------------------------*/
    public static List<String> permuteList(String str) {

        if (str.length() == 1) {
            return new ArrayList<>(Arrays.asList(str));
        }
        List<String> result = new ArrayList<>();

        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            String rest = replace(str, i, "");
            List<String> restPermutations = permuteList(rest);

            if (restPermutations == null) {
                continue;
            }
            for (String s : restPermutations) {
                result.add(c + s);
            }
        }
        return result;
    }

    /*-----------------------------------------------------------------------*/

    public static String replace(String str, int idx, String rep) {
        return str.substring(0, idx) + rep + str.substring(idx + 1);
    }
    /*-----------------------------------------------------------------------*/

    public static void main(String[] args) {

        int counter = 0;
        List<String> list = permuteList("thomas");
        for (int i = 0; i < list.size(); i++) {
            System.out.println(++counter + " " + list.get(i));
        }
    }
    /*-----------------------------------------------------------------------*/

}

/*

Output

1 thomas
2 thomsa
3 thoams
4 thoasm
5 thosma
6 thosam
7 thmoas
8 thmosa
9 thmaos
10 thmaso
11 thmsoa
12 thmsao
13 thaoms
14 thaosm
15 thamos
16 thamso
17 thasom
18 thasmo
19 thsoma
20 thsoam
21 thsmoa
22 thsmao
23 thsaom
24 thsamo
25 tohmas
26 tohmsa
27 tohams
28 tohasm
29 tohsma
30 tohsam
31 tomhas
32 tomhsa
33 tomahs
*/