Search code examples
javascriptgeneratorbrute-force

How can I recursively create a string with a set of chars until it matches the desired string?


I want to recursively create every possible string until it matches another.

If I want to create "ab", and have the below set of chars

[
  'a', 'b', 'c',
  'd', 'e', 'f'
]

it will have to go through:

a
b
c
d
e
f
aa
ab // this

until it stops.

I have tried but I can only get it to work with 1 char:

function bruteforceTo(text) {
    const charset = "abdef".split("");
    const bf = bruteforcer(charset);
    let x;

    do {
        x = bf.next().value;
        console.log(x);
    } while (x != text);

    function* bruteforcer(charset) {
        let i = 0;

        while (true) {
            yield charset[i++];
        }
    }
}

console.time();
bruteforceTo("ab");
console.timeEnd();

The above script is something i would like to build on, rather than completely get rid of it (I like generators) but if it just cannot work I am happy to do something else.


Solution

  • You actually don't need recursion for that, just place generated substrings in a queue, and for each 'head' substring push N longer strings back.

    function *generate(chars) {
        let len = chars.length
        let queue = Array(len).fill(0).map((_, n) => [n])
    
        while (1) {
            let a = queue.shift()
            yield a.map(n => chars[n]).join('')
            for (let n = a[a.length - 1]; n < len; n++)
                queue.push(a.concat(n))
        }
    }
    
    //
    
    let max = 0
    for (let p of generate('abcd')) {
        if (max++ > 100)
            break
        document.write(p + ' ')
    }

    Note that this generator is endless, it won't stop until you tell it to (or you go out of memory).