How can I ensure both randomly generated colors are not the same?
Solved
QML and Qt Quick
-
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)] } }
-
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);