How can I ensure both randomly generated colors are not the same?



  • I'm making a simple game where two shapes change colors repeatedly using a timer, I have an array of colors to choose from how can I make sure both shapes will have be colored differently?

    My code:

    property variant colorArray: ["#008499","#963A65","#01FF97","#FF4140"] //colors to choose from
    Timer{
            id: color_switch
            interval: 1000; running: true; repeat: true
            onTriggered: {
                shape1.color = colorArray[Math.floor(Math.random()*3)]
                shape2.color = colorArray[Math.floor(Math.random()*3)]
            }
        }
    


  • @newbisoso
    So in some shape or form you have to write a tiny bit of code there which checks: while the second call to Math.random() * 3 returns the same as the first call did, call it again!



  • Just genereate 2nd index until it is not same as 1st index:

            let idx1 = Math.floor(Math.random() * 3);
            let idx2 = Math.floor(Math.random() * 3);
            while (idx2 === idx1)
                idx2 = Math.floor(Math.random() * 3);
    

Log in to reply