0

I'm not from a blogging background, but I need to integrate a random generator in a post. This JS code works fine but it generate duplicates. Anyone can help me to avoid this issue. I'll be really thankful.

Kind Regards.

var logancopy = ["Pahari-Potwari<br><span class='country'>Pakistan</span>", "Minangkabau<br><span class='country'>Indonesia</span>", "Slovenian<br><span class='country'>Slovenia</span>", "Mesopotamian Arabic<br><span class='country'>Iraq</span>",
                //More here
            ];

$(document).ready(function() {
    initbutton();
});

function initbutton(){
    $('#generate').on('click', function(){
        cleardisplay();
        speak();
    });
}

function cleardisplay(){
    $('#display').empty();
}

function speak(){
    var num = parseInt($('#num').val());
    var typ = $('#typ').val();
    if(typ === 'w'){
        createwords(num);
    }
    else if(typ ==='s'){
        createsentences(num);
    }
    else{/*If drop down fails default to paragraphs*/
        createparagraphs(num);
    }
}
function createsentences(n){
    for(var i = 0; i <= (n - 1); i++){
        var r = Math.floor(Math.random() * logancopy.length);
        var sent = '<span class="wrd">' + logancopy[r] + '</span>';
        $('#display').append(sent);
    }
}
Nesha
  • 1
  • Why not just shuffle the array? https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array – epascarello Apr 01 '21 at 17:13
  • Ever heard about the birthday paradox? This kind of relates to that. The more times you generate random numbers within a certain static range, the greater the chance that a duplicate will appear. Random isn't unique *every time* (although it aims to be uninfluenced by patterns, but it's just not [possible](https://math.stackexchange.com/a/2056931) (see first comment under answer)), so you will likely experience dupes. – Reality Apr 01 '21 at 17:17

0 Answers0