#Function optimization

14 messages · Page 1 of 1 (latest)

rigid cipher
#

My badly coded function:

function generateDotSeparatedWords(word) {
    let results = new Set();

    // base case
    if (word.split(".").length === Math.ceil(word.length / 2)) {
        return results;
    }
    
    // check each letter (or dot) of the word, except the first letter
    for (let i = 1; i < word.length; i++) {
        // if char at pos i or any of its neighbors is a dot, we skip
        if (word[i - 1] === "." || word[i] === "." || word[i + 1] === ".") {
            continue;
        }
        // we add a dot: ab -> a.b (at letter 'b')
        let dotSeparatedWord = word.slice(0, i) + "." + word.slice(i);
        results.add(dotSeparatedWord);
    
        // results = new Set([...results, ...generateDotSeparatedWords(dotSeparatedWord)]);
        for (let w of generateDotSeparatedWords(dotSeparatedWord).values()) {
            results.add(w);
        }
    }
    return results;
}

Example:

In: "word"
Out: ["w.ord","w.o.rd","w.o.r.d","wo.rd","wor.d","w.or.d"]

Any suggestions to optimize this? Or even completely rewrite it?

lofty kayak
#

well... highly debatable if this is actually optimised. Functionally more or less the same. But here's a take

const insertSymbol = (word, index, symbol) => word.slice(0, index) + symbol + word.slice(index)

const intersperse = (word, start, space, symbol) => {
    const res = []
    for (let i = start; i < word.length; i += space + 1) {
        word = insertSymbol(word, i, symbol)
        res.push(word)
    }
    return res
}

const generateSymbolSeparatedWords = (word, symbol = '.') => {
    const res = []
    for (let space = 1; space < word.length; space++) {
        for (let i = 1; i <= word.length; i++) {
            res.push(...intersperse(word, i, space, symbol))
        }
    }
    return new Set(res)
}

console.log(generateSymbolSeparatedWords('word'))
rigid cipher
#

ok

#

yours is instant

#

which is great

#

except it does not calculate everything

#

top is yours vs mine at bottom

#

interesting

#

generateSymbolSeparatedWords = yours
generateDotSeparatedWords = mine

#

i guess the key is to avoid recursion, which you did

#

we just gotta fix it, so it generates all

lofty kayak
#

I wouldn't say the problem lies in recursion per se. If your version produces an order of magnitude more results, then it will naturally take longer. Running both on input wordw reveals that your approach produces "w.o.rd.w", which mine doesn't. I am not really sure what the rule here is. I assumed you wanted to chunk the input into differently sized bits, starting at all possible indices. Now I am no longer sure what you are actually trying to generate.