p2or
p2or

Reputation: 339

How to get random string by click from array without repetition?

The Idea is: click a button to replace a headline with a unique string of an array. The problem with this is that I've used a string of the array before like this:

headlines = new Array("Good", "Bad", "Ugly", "Random Headline");
var randomNumberBefore = 4;
alert (headlines[randomNumberBefore]);

but I dont want to display the same headline again, thatswhy it is key check that the actual index randomNumberBefore is not the same number like new index randomNumber. The following function makes sense to me, but sometimes it returns the same number, that causes the headline is replaced by itself and the user noticed no change.

function randomNumberByRange (range, number) {
    var r;
    do {
        var r = Math.floor(Math.random() * range);
    } while (r == number);
    return r;
}

$(document).on('click','.nextquote' , function() {
    var randomNumber = randomNumberByRange( headlines.length, randomNumberBefore);
    var nextHeadline = headlines[randomNumber];

    $(".bannertext").text(nextHeadline);
    console.log(nextHeadline);

});

Any Ideas to get unique headlines per click?

Here is my starting fiddle.

--

Here is the final fiddle.

Upvotes: 0

Views: 199

Answers (2)

Etheryte
Etheryte

Reputation: 25318

If you don't want repetition, simply remove the used elements from the array.

var h = new Array("Good", "Bad", "Ugly", "Random Headline");
while (h.length > 0) {
    var i = Math.floor(Math.random() * h.length);
    var t = h.splice(i, 1);
    console.log(t);
}

Upvotes: 1

Dinu Sorin
Dinu Sorin

Reputation: 215

You forgot to assign the old value to randomNumberBefore; after

var randomNumber = randomNumberByRange( headlines.length, randomNumberBefore);

put

randomNumberBefore = randomNumber;

PS: There is a way to make the randomNumberByRange function more performant:

function randomNumberByRange (range, number) {
    var r = Math.floor(Math.random() * (range-1));
    if(r >= number)r++;
    return r;
}

but, if you have many headlines, your function is good enough (as collision probability drops with the number of items you have in the list)

Upvotes: 2

Related Questions