Repeating a pickrandom

Trying to repeat a pickrandom 4 times and I can’t remember how.

If you want to run the same block of code multiple times, try using a for loop. For example:

let colors = ['red', 'green', 'blue'];

for (let i = 0; i < 10; i++) {
    drawBox(pickRandom(colors));
}

That’s what I thought I had tired last time, but it’s working now, thanks!! How would I make sure it doesn’t select an item from the array twice? Ex. Let’s say I was picking from an array [ 1, 2, 3, 4] and I wanted to pick randomly, four times. This would give me four outputs between 1 and 4, but may include two 3’s. How could I ensure I see 1, 2, 3, and 4 presented, but in a different order?

Hey there, good question! Now we’re getting into (basic) algorithms! I’m going to turn this into a small challenge for you to solve in the playground.

Let’s review what you want…

You want a function that:

  • Randomly picks an item from an array.
  • If that item has been picked previously, that item is skipped, and the function tries picking again.

This means you need to:

  • Remember what items have already been picked, or alternately, the index locations of previously-picked items.
  • Decide what to do if the item has been previously picked.
  • Decide what to do if the item has not been previously picked.

A few questions:

  • What is the function going to take? An array? A string?
  • Is the function going to return anything? If so, what? (It’s ok if the function doesn’t return anything. You could just console.log() each of the picked items.)

Good luck! Let me know if you have any questions.
Ben