get all combinations for a string

前端 未结 8 1706
傲寒
傲寒 2020-12-01 19:34

I\'m trying to create a function in JavaScript that given a string will return an array of all possible combinations of the letters with each used at most once, starting wit

8条回答
  •  难免孤独
    2020-12-01 20:21

    Generators allow a very clean implementation:

    // Very short generator produces all possible strings composed of the given chars!
    let allStrings = function*(chars) {
      yield '';
      for (let prefix of allStrings(chars)) for (let c of chars) yield `${prefix}${c}`;
    };
    
    // Render the first 1000 strings
    document.body.style.fontFamily = 'monospace';
    let count = 0;
    for (let str of allStrings('abcd')) {
      let div = document.createElement('div');
      div.innerHTML = `${(count + 1).toString().padStart(4, '0')}: ${str}`;
      document.body.appendChild(div);
      if (count++ > 1000) break;
    }

    Note that the very first result from allStrings is the empty string. If it's crucial to avoid this the following implementation can be used:

    let allStrings = function*(chars, includeEmpty=false) {
      if (includeEmpty) yield '';
      for (let prefix of allStrings(chars, true)) for (let c of chars) yield `${prefix}${c}`;
    };
    

提交回复
热议问题