Skip to content

Instantly share code, notes, and snippets.

@yi-mei-wang
Created July 16, 2019 13:37
Show Gist options
  • Save yi-mei-wang/21fba335e84453110a70a8678a7009a7 to your computer and use it in GitHub Desktop.
Save yi-mei-wang/21fba335e84453110a70a8678a7009a7 to your computer and use it in GitHub Desktop.
16 Jul 2019 Office Hours Notes

const favSingers = [
        "Yuna",
        "Britney Spears",
        "Backsteet Boys",
        "Spice Girls",
        "Meatloaf"
];

  1. programmatically print out the numbers
  2. generate numbers from 1 to n (the number of elements inside the array)
  3. print out "My #n favourite singer is <name of singer>"

for (let i = 0; i < favSingers.length; i++) {
        console.log("My #" + (i + 1) + " favourite singer is " + favSingers[i]);
}

How to randomize the sequence of the singers in such a way that each singer appears only once?

  1. Keep track of elements that have been printed
  2. Once an element has been printed, remove it from the main array
  3. Pick a random one from the remaining elements in the array
  4. Repeat until no elements are left

let arrCopy = [...favSingers];
// Repeat this program as long as there are still elements in the array
while (arrCopy.length > 0) {
     let randomDigit = Math.floor(Math.random() * arrCopy.length);
     // USE BACK TICKS WOOOHOOOO
     console.log(`My #${randomDigit + 1} favourite singer is ${arrCopy[randomDigit]}.`);
     arrCopy.splice(randomDigit, 1);
}

To ensure that the numbers do not repeat

  1. Similar process as above
  2. Programmatically generate a list of numbers 1 - N, N = length of the array

To insert at a specific index into an array

favSingers.splice(1, 1, "Bruno Mars");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment