Reputation: 339
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
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
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