1

Here is the array I can access randomly for the ten values.

var numArray = [1,2,3,4,5,6,7,8,9,10];
var rand = Math.floor(Math.random()*10);
var answer = numArray[rand];
console.log(answer);

However, it repeats the same value sometimes. How do I ensure that the display value doesn't repeat consecutively?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
thirdEye
  • 47
  • 3
  • 2
    Well if it didn't have a chance to be the same number twice in a row it wouldn't be random would it? – Albzi Jul 11 '17 at 14:31
  • 1
    you coud splice the array each time you pick a number, and decrement the amount of random each time also. – Darren Crabb Jul 11 '17 at 14:32
  • IN general, sort the array randomly and take them one at a time. – Jamiec Jul 11 '17 at 14:32
  • 2
    if you want to have always the unique result, one case is to remove the selected index from the array – Yordan Nikolov Jul 11 '17 at 14:32
  • As Albzi said - if you want it to give a different number each time, you're asking for a different solution. The simplest way is to remove the entry when you 'read' it, and instead of Math.random()*10, use Math.random()*numArray.length. With the simplicity of this example I imagine this is programming homework, though. – Liam MacDonald Jul 11 '17 at 14:33
  • what is the point of such task? want to accumulate randomely picked items - use `Set` object to obtain unique list – RomanPerekhrest Jul 11 '17 at 14:34
  • It is not necessarily an exact answer since OP might want 10 random numbers that do not repeat consecutively as he said - so 1,2,3,4,3,2,1,2,3,1 might be ok but 1,1,2,3,4,5,6,7,8,9 is not. PS: thirdEye is member for 2 years – mplungjan Jul 11 '17 at 14:40

0 Answers0