2

So I'm making an app for a computer science class and basically, the premise is that you work at a pizza place and you have to select the toppings that a customer wants, which are randomly selected. Currently, I have the toppings in a list that will pick them with randomNumber() but I can't figure out how to remove the topping after it is chosen, to avoid repeats.

    var toppings = ["pepperoni", "mushrooms", "pineapple", "peppers", "sausage", "sardines", 
    "bacon"];
    function newCustomer() {
      showElement("customerPic");
      for (var i = 0; i < 3; i++) {
        toppings[(randomNumber(0, 6))];
        console.log(("I would like " + toppings[(randomNumber(0,6))]) + " on my pizza, 
    please");
      }
    }
Tom O.
  • 5,133
  • 2
  • 19
  • 33
  • It's like when you play poker you don't want to deal the same card twice. So shuffle the deck and serve the top card. So [shufffle it properly](https://stackoverflow.com/a/45967133/4543207) and just `.pop()` one item. – Redu Apr 22 '21 at 20:07

2 Answers2

2

To me the easiest way to do this seems to be by creating a new array that contains the strings in your original toppings array, but in a randomized order - you can treat that array as a stack and continue to pop the randomized elements off it until none remain. See the code comments for more details:

// Your original data
var toppings = [
  "pepperoni",
  "mushrooms",
  "pineapple",
  "peppers",
  "sausage",
  "sardines",
  "bacon"
];

// A new array that contains same strings as `toppings`, but their order's randomized
const shuffledToppings = [...toppings].sort(() => Math.random() - 0.5);

// `pop` is an Array.prototype function that removes the and returns the last item in the array - this means `shuffledToppings` is shrinks by 1 each time this function is called
function newCustomer() {
  console.log(`I'd like a pizza with ${shuffledToppings.pop()}`);
}

// Call `newCustomer` function until all strings have been popped off `shuffledToppings` (i.e.< it is empty).
while (shuffledToppings.length > 0) {
  newCustomer();
}

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop

Tom O.
  • 5,133
  • 2
  • 19
  • 33
0

Basically, you need to remove an element from the original array on every iteration and then get a random number with a max value equals to the size of filtered array.

Try this code (obviously it can be improved, eg copying original array ecc):

function removeItemOnce(arr, value) {
  var index = arr.indexOf(value);
  if (index > -1) {
    arr.splice(index, 1);
  }
  return arr;
}


function newCustomer() {
  showElement("customerPic");
  for (var i = 0; i < 3; i++) {
    let ix = randomNumber(0, toppings.length);
    let v = toppings[ix];
    toppings = removeItemOnce(toppings,v)
    console.log("I would like " + v + " on my pizza, please");
  }
}

More info about array item removing: How can I remove a specific item from an array?

atx
  • 365
  • 2
  • 9