最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How not to make two consecutive same numbers come in Math.random() - Stack Overflow

programmeradmin2浏览0评论

I am doing a quote display site by learning from youtube. I have a curiosity about a problem. When i press the button, it es 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;
}

I am doing a quote display site by learning from youtube. I have a curiosity about a problem. When i press the button, it es 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;
}
Share Improve this question asked Sep 4, 2019 at 15:09 GreyGoat93GreyGoat93 1072 silver badges11 bronze badges 5
  • 8 Put the call to Math.random() in a while loop and keep trying until you get a different one. – Pointy Commented Sep 4, 2019 at 15:10
  • 1 An alternative would be to temporarily remove the chosen element and add it back after a new one has been chosen. – Tyler Roper Commented Sep 4, 2019 at 15:14
  • 2 Use the random number to be, not the selection, but the distance from the previous selection decreased by one. This way you don't need to do that wasteful discarding of random numbers. – aligur Commented Sep 4, 2019 at 15:15
  • @aligur Please add that as an answer. It's simple and elegant. – Jim Mischel Commented Sep 4, 2019 at 21:17
  • This task is mostly done by first properly shuffling the array and consuming items one by one. – Redu Commented Apr 2, 2020 at 19:04
Add a ment  | 

7 Answers 7

Reset to default 7

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;
}

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();
   }
}

You need to keep track of your current/old random number then pare 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;
}

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>

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
}

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();

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;
}
发布评论

评论列表(0)

  1. 暂无评论