简体   繁体   中英

how to find list of all words from a given array of characters

I am trying to solve a word puzzle with 5 alphabets, which can have 3 , 4 and 5 letter words . how should I write my algorithm to make this happen?

I have tried making a 5 nested loops to go through the characters of array and then adding all the loops , it works for small words but crashes due to time complexity.

const addandlog = (array) => {
  for (var i = 0; i < array.length; i++) {
    for (var j = 0; j < array.length; j++) {
      for (var k = 0; i < array.length; k++) {

        console.log(array[i] + array[j] + array[k]);

      }
    }
  }
}
addandlog(['A', 'G', 'R', 'N', 'D']);

I expect the output to be all the words that can be made and not just the dictionary words

You could take an iterative approach by taking an array of arrays with the wanted items.

 function getWords(letters, length) { return Array .from({ length }) .fill(letters) .reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), [])) .map(a => a.join('')) } console.log(getWords(['A', 'G', 'R', 'N', 'D'], 5)); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM