Pacific-Design.com

    
Home Index

1. Algorithms

2. Hash Set

Algorithms / Hash Set /

HashSet

This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.

import java.util.*;

public class Permutation {

    /*-----------------------------------------------------------------------*/
    public static Set<String> permuteSet(String str) {

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

        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            String rest = replace(str, i, "");
            Set<String> restPermutations = permuteSet(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;
        Set<String> set = permuteSet("kevin");
        for (String s : set) {
            System.out.println(++counter + " " + s);
        }
    }
    /*-----------------------------------------------------------------------*/
}

/*
Output

1 vkien
2 nievk
3 neivk
4 kievn
5 inkev
6 kvnei
7 enkiv
8 nveik
9 eivkn
10 vnkei
11 nkvei
12 enikv
13 knvei
14 eiknv
15 iekvn
16 vkine
17 ieknv
18 nivke
19 ievkn
20 envik
21 kniev
22 ekvni
23 knevi
24 nvkei
25 vniek
26 vkeni
27 keinv
28 keivn
29 knive
30 viekn
31 veikn
32 eikvn
33 ivnek
34 nkeiv
35 kvien
36 nvkie
37 kevin
38 ikevn
39 iknev
40 vekin
41 nviek
42 vknie
43 nevki
44 ivken
45 ivkne
46 ekivn
47 nikev
48 vinke
49 nevik
50 inkve
51 evikn
52 vikne
53 inekv
54 iknve
55 kvine
56 ivekn
57 kienv
58 ikven
59 nekvi
60 kinev
61 nikve
62 kinve
63 viken
64 vkein
65 eknvi
66 kveni
67 ienvk
68 nkiev
69 venki
*/