GreyGoat93
GreyGoat93

Reputation: 107

How not to make two consecutive same numbers come in Math.random()

I am doing a quote display site by learning from youtube. I have a curiosity about a problem. When i press the button, it comes same quote two or more than two times but sometimes, not always (I use Math.random() so it can be usually). I want that when i press the button, it will change, not will stay at the same quote.

I have no idea, so i didn't do anything.

const quotes = [
    {
        author: 'Ramiz Karaeski',
        quote: 'Meyvayı soymadan içinden ne çıkacak bilemem, kardeş.'
    },
    {
        author: 'Franz Kafka',
        quote: 'Beyinlerimiz savaşsın isterdim ama görüyorum ki silahsınız bayım.'
    },
    {
        author: 'Fyodor Dostoyevski',
        quote: 'Cehennem nedir? Sevginin artık imkansız olduğuna dair çekilen bir acıdır.'
    },
    {
        author: 'Lev Tolstoy',
        quote: 'Herkes dünyayı değiştirmeyi düşünür, ama kimse kendini değiştirmeyi düşünmez.'
    },
    {
        author: 'Charles Bukowski',
        quote: 'İnsan her zaman ihanet eder sonunda. Kimseye güvenme.'
    },
    {
        author: 'Friedrich Nietzsche',
        quote: 'Oysa güzelliğin sesi kısıktır konuşurken; sadece en uyanık ruhlara yanaşır.'
    },
    {
        author: 'Sabahattin Ali',
        quote: 'On beş günlük ömrü on beş seneye sığdıramazsın da, on beş senelik ömrü on beş günde yaşayıverirsin!'
    }
]

const quoteAuthor = document.getElementById('author');
const displayQuote = document.getElementById('quote');
const buttonChange = document.getElementById('button-change-quote');

buttonChange.addEventListener('click', change);


let random = 0;
change();

function change() {
    random = Math.floor(Math.random() * quotes.length);
    quoteAuthor.innerHTML = quotes[random].author;
    displayQuote.innerHTML = quotes[random].quote;
}

Upvotes: 3

Views: 797

Answers (7)

Maheer Ali
Maheer Ali

Reputation: 36564

You need to use the do-while loop and keep generating a new random number till its not different from previous

let random = 0;
change();

function change() {
    let newRandom;
    do{
       newRandom = Math.floor(Math.random() * quotes.length);
    }
    while(newRandom === random)
    random = newRandom
    quoteAuthor.innerHTML = quotes[random].author;
    displayQuote.innerHTML = quotes[random].quote;
}

Upvotes: 7

Matt Timmermans
Matt Timmermans

Reputation: 59144

Just choose from the other possibilities:

let random = Math.floor(Math.random() * quotes.length);
change();

function change() {
    let previous = random;
    random = Math.floor(Math.random() * (quotes.length-1));
    if (random >= previous) {
        random+=1;
    }
    quoteAuthor.innerHTML = quotes[random].author;
    displayQuote.innerHTML = quotes[random].quote;
}

Upvotes: 0

Tyler Roper
Tyler Roper

Reputation: 21672

I never liked much using loops for this myself. The idea of "keep trying until it works" just feels somewhat inelegant, to me personally.

An alternative that I might use is to simply remove the previously-selected item from the array and store it in a variable (prev). Then, select your randomized item from the remaining options.

const quotes = [ { author: 'Ramiz Karaeski', quote: 'Meyvayı soymadan içinden ne çıkacak bilemem, kardeş.' }, { author: 'Franz Kafka', quote: 'Beyinlerimiz savaşsın isterdim ama görüyorum ki silahsınız bayım.' }, { author: 'Fyodor Dostoyevski', quote: 'Cehennem nedir? Sevginin artık imkansız olduğuna dair çekilen bir acıdır.' }, { author: 'Lev Tolstoy', quote: 'Herkes dünyayı değiştirmeyi düşünür, ama kimse kendini değiştirmeyi düşünmez.' }, { author: 'Charles Bukowski', quote: 'İnsan her zaman ihanet eder sonunda. Kimseye güvenme.' }, { author: 'Friedrich Nietzsche', quote: 'Oysa güzelliğin sesi kısıktır konuşurken; sadece en uyanık ruhlara yanaşır.' }, { author: 'Sabahattin Ali', quote: 'On beş günlük ömrü on beş seneye sığdıramazsın da, on beş senelik ömrü on beş günde yaşayıverirsin!' } ];

let random = 0;
  
function change() {
    let prev = quotes.splice(random,1)[0]; //remove the previous selection from the choices
    random = Math.floor(Math.random() * quotes.length);
    
    //quoteAuthor.innerHTML = quotes[random].author;
    //displayQuote.innerHTML = quotes[random].quote;
    console.log(`"${quotes[random].quote}" - ${quotes[random].author}`);
    
    quotes.push(prev); //add the previous selection back
}

//DEMO
for(let i=0;i<10;i++) change();

Upvotes: 1

Prune
Prune

Reputation: 77837

There's a better way: have an extra variable that will hold the previous quotation. Choose a new one at random. Then swap the two, so that the newly-chosen quotation is now removed from the choice list.

const chosen = quotes.splice(random,1)[0]

function change() {
    new_choice = Math.floor(Math.random() * quotes.length);
    // display quotes[new_choice]

    // Swap the "disabled" quote back into the list, removing the one just chosen.
    temp = chosen
    chosen = quotes[new_choice]
    quotes[new_choice] = temp
}

Upvotes: 1

Sim1-81
Sim1-81

Reputation: 626

intoduce another variable in your code

let random = 0;
let last_random = 0;
change();

function change() {
   random = Math.floor(Math.random() * quotes.length);

   if(random != last_random){
      last_random = random;
      quoteAuthor.innerHTML = quotes[random].author;
      displayQuote.innerHTML = quotes[random].quote;
   }else{
     change();
   }
}

Upvotes: 2

ShubhamD
ShubhamD

Reputation: 112

Another approach can be like this It will call change(); if random number is same as old random number

<script>
const quotes = [
     {
        author: 'Ramiz Karaeski',
        quote: 'Meyvayı soymadan içinden ne çıkacak bilemem, kardeş.'
    },
    {
        author: 'Franz Kafka',
        quote: 'Beyinlerimiz savaşsın isterdim ama görüyorum ki silahsınız bayım.'
    },
    {
        author: 'Fyodor Dostoyevski',
        quote: 'Cehennem nedir? Sevginin artık imkansız olduğuna dair çekilen bir acıdır.'
    },
    {
        author: 'Lev Tolstoy',
        quote: 'Herkes dünyayı değiştirmeyi düşünür, ama kimse kendini değiştirmeyi düşünmez.'
    },
    {
        author: 'Charles Bukowski',
        quote: 'İnsan her zaman ihanet eder sonunda. Kimseye güvenme.'
    },
    {
        author: 'Friedrich Nietzsche',
        quote: 'Oysa güzelliğin sesi kısıktır konuşurken; sadece en uyanık ruhlara yanaşır.'
    },
    {
        author: 'Sabahattin Ali',
        quote: 'On beş günlük ömrü on beş seneye sığdıramazsın da, on beş senelik ömrü on beş günde yaşayıverirsin!'
    }
]


const quoteAuthor = document.getElementById('author');
const displayQuote = document.getElementById('quote');
const buttonChange = document.getElementById('button-change-quote');

buttonChange.addEventListener('click', change);

let random = 0;
change();

function change() {
var new_index = Math.floor(Math.random() * quotes.length);
if(new_index==random){
change();
return;
}else{
random=new_index;
}
    quoteAuthor.innerHTML = quotes[random].author;
    displayQuote.innerHTML = quotes[random].quote;
} 
</script>

Upvotes: 1

John
John

Reputation: 579

You need to keep track of your current/old random number then compare that with the new random number and keep generating new numbers until you get a new number, like the following:

let random = 0;
let lastRandom = null;

function change() {
    do {
      random = Math.floor(Math.random() * quotes.length);
    } while(random === lastRandom);
    lastRandom = random;
    quoteAuthor.innerHTML = quotes[random].author;
    displayQuote.innerHTML = quotes[random].quote;
}

Upvotes: 1

Related Questions