3

This is my array: arr = [0, 1, 2, 3, 4, 5] I want to randomly iterate through it the first time and then iterate through it in the same (random) order each time after that. How would I do it? The only way I can think of would be to shuffle the arr, using something like this shuffle function and then iterate through sequentially. For example:

newArr = shuffle(arr);
for(j = 0; j <5; j++) {
    for(i = 0; i < newArr.length; i++)
}

I am wondering if there is an easier, inline way, so that if items get appended to the array I do not have to reshuffle (and make a new array each time)

Community
  • 1
  • 1
Startec
  • 12,496
  • 23
  • 93
  • 160
  • but the sequence would change either way when you change the array so shuffling seems like a good idea – Alex Jul 31 '14 at 19:51

2 Answers2

1

I'm pretty sure there no built-in function for that. So... make a list of ints the same size as the array, and assign them 0..count-1. Then choose a number at random from 0 to the size of the list(-1) and REMOVE the number at that location and ADD it to a new (second) list. Repeat until you the first list is empty. The second list will be a random set of offset into the original range.

SingleStepper
  • 348
  • 1
  • 10
0

Create a second array. Next, populate the array with random numbers (ranging from 0 to array.length). Now create a for loop iterating through the secondary array. Each number in the array corresponds to an index in array.

Result: you can now iterate randomly through array without modifying the order of array.

Later on you can use the splice() function to add to the second array at random points (and push() to add to the main array).

Jason
  • 1,081
  • 10
  • 24
  • This was the idea I figured, however, if I fill a second array with random numbers, there is the chance that a number could be duplicated, and a number could be left out (for instance the number 2 could randomly be generated twice)...right? – Startec Jul 31 '14 at 20:17
  • @Startec you would need to add a second for loop inside the random generator while loop which checks to see if there are any duplicate numbers generated. I've done some random number generation like this before for a Java random map generator. If you'd like, I could expand on this answer with some pseudo code. – Jason Jul 31 '14 at 20:27
  • Not necessary, it seems like the best way would be to shuffle the array and then sequentially loop. – Startec Jul 31 '14 at 20:35
  • @Startec oh yeah shuffle would work better I guess. I was thinking about it the hard way. – Jason Jul 31 '14 at 20:39