given a dictionary file of words, provide 5x 5 letter words that do not share any similar characters in javascript

Here is one approach:

  1. Read the dictionary file and store all the 5-letter words in an array.
  2. For each word in the array, create a set of its characters.
  3. Compare the set of characters of each word with all the previous words in the array. If there is no intersection, add the word to a list of valid words.
  4. Stop when the list of valid words has at least 5 words.

Here's the code:

index.tsx
const fs = require('fs');

const words = fs.readFileSync('dictionary.txt', 'utf8').split('\n');

let validWords = [];

for (let i = 0; i < words.length; i++) {
  const word = words[i];
  if (word.length === 5) {
    const set = new Set(word.split(''));
    let isValid = true;
    for (let j = 0; j < validWords.length; j++) {
      if (new Set([...set].filter(x => validWords[j].includes(x))).size > 0) {
        isValid = false;
        break;
      }
    }
    if (isValid) {
      validWords.push(word);
      if (validWords.length >= 5) break;
    }
  }
}

console.log(validWords);
587 chars
26 lines

Note that this approach could be slow for large dictionary files, as it compares each word with all the previous ones. There are faster algorithms to solve this problem, such as using a variation of the bitset technique.

gistlibby LogSnag