Search code examples
javascripthtmlstringrandomgenerator

Random string generator without repeating a combination


I have tried to implement that the combinations are not repeated. in the image you can see how "sd" is repeated twice.

sd

const characters ='qwertyuiopasdfghjklzxcvbnm0987654321';

function generateString(length) {
    let result = ' ';
    const charactersLength = characters.length;
    for ( let i = 0; i < length; i++ ) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }

    return result;
}



function captura(){
    lon=2;
    can=600;
    for (let i = 0; i < can; i++) {
        document.write(i+1 + ".- " + generateString(lon) + "<br>");
    }

}
captura();

Any help please?


Solution

  • Just save the results in a Set and make sure that what you return at the end isn't in the Set already.

    const characters ='qwertyuiopasdfghjklzxcvbnm0987654321';
    
    function generateString(length) {
        let result = ' ';
        const charactersLength = characters.length;
        for ( let i = 0; i < length; i++ ) {
            result += characters.charAt(Math.floor(Math.random() * charactersLength));
        }
    
        return result;
    }
    const set = new Set();
    const generateUniqueString = (len) => {
      let str;
      do {
        str = generateString(len);
      } while (set.has(str));
      set.add(str);
      return str;
    };
    
    
    function captura(){
        for (let i = 0; i < 50; i++) {
            document.write(i+1 + ".- " + generateUniqueString(2) + '<br>');
        }
    
    }
    captura();

    If you use this in a situation where you'll start getting anywhere near the limit of uniques, a better approach would be to generate all possible combinations in advance, randomize the array, then continually pop strings from the array when the function is called.