Startec
Startec

Reputation: 13206

How to randomly iterate through an array once, and then repeatedly iterate in that order

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)

Upvotes: 3

Views: 7535

Answers (2)

Jason
Jason

Reputation: 1079

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).

Upvotes: -1

SingleStepper
SingleStepper

Reputation: 348

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.

Upvotes: 1

Related Questions