Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to generate all variants of a word

i would like to explain my problem by the following example.

assume the word: abc a has variants: ä, à
b has no variants.
c has variants: ç

so the possible words are:

abc
äbc
àbc
abç
äbç
àbç

now i am looking for the algorithm that prints all word variantions for abritray words with arbitray lettervariants.

like image 486
clamp Avatar asked Oct 18 '25 10:10

clamp


1 Answers

I would recommend you to solve this recursively. Here's some Java code for you to get started:

static Map<Character, char[]> variants = new HashMap<Character, char[]>() {{
    put('a', new char[] {'ä', 'à'});
    put('b', new char[] {        });
    put('c', new char[] { 'ç'    });
}}; 

public static Set<String> variation(String str) {

    Set<String> result = new HashSet<String>();

    if (str.isEmpty()) {
        result.add("");
        return result;
    }

    char c = str.charAt(0);
    for (String tailVariant : variation(str.substring(1))) {
        result.add(c + tailVariant);
        for (char variant : variants.get(c))
            result.add(variant + tailVariant);
    }

    return result;
}

Test:

public static void main(String[] args) {
    for (String str : variation("abc"))
        System.out.println(str);
}

Output:

abc
àbç
äbc
àbc
äbç
abç
like image 136
aioobe Avatar answered Oct 20 '25 02:10

aioobe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!