-1

I want to randomly iterate an array runs while randomly selecting a mainSamplers and a secondarySamplers. The below code works but will repeat runs and I need to keep running it over and over.

// program to get a random samplestrong text

function getRandomItem(arr) {

  // get random index value
  const randomIndex = Math.floor(Math.random() * arr.length);

  // get random item
  const item = arr[randomIndex];

  return item;
}

let runs = ["W1", "W2/W3", "W4/W6", "W5", "W7/W8", "E1/E2", "E3/E4", "E5/RB", "SA/SB", "LT",
  "LR1", "LR2", "LR3", "LR4", "LR5", "LR6", "LR7", "LR8", "Mullet Creek"];
let mainSamplers = ["RAB", "CJ", "AMR", "ND", "RB", "ED", "SD", "MEF"];
let secondarySamplers = ["KD", "SA", "AF", "JT", "EV"];



//1st sample set
const result1 = getRandomItem(runs) + " " + getRandomItem(mainSamplers) + " " +
  getRandomItem(secondarySamplers);

console.log("Run" + " " + "Samplers");
console.log(result1);
  // need to run this as many times as there are runs and not repeat the runs
pilchard
  • 12,414
  • 5
  • 11
  • 23
RAB
  • 3
  • 1

1 Answers1

0

You can delete each random element from run.

// program to get a random samplestrong text

function getRandomItem(arr) {
  // get random index value
  const randomIndex = Math.floor(Math.random() * arr.length);

  // get random item
  const item = arr[randomIndex];

  return item;
}

let runs = ["W1", "W2/W3", "W4/W6", "W5", "W7/W8", "E1/E2", "E3/E4", "E5/RB", "SA/SB", "LT",
  "LR1", "LR2", "LR3", "LR4", "LR5", "LR6", "LR7", "LR8", "Mullet Creek"
];
let mainSamplers = ["RAB", "CJ", "AMR", "ND", "RB", "ED", "SD", "MEF"];
let secondarySamplers = ["KD", "SA", "AF", "JT", "EV"];


console.log("Run" + " " + "Samplers");
while (runs.length) {
  //1st sample set
  let val = getRandomItem(runs);
  const result1 = val + " " + getRandomItem(mainSamplers) + " " +
    getRandomItem(secondarySamplers);

  console.log(result1);
  
  runs.splice(runs.indexOf(val), 1);
}
minhazmiraz
  • 442
  • 4
  • 12
  • Thanks for your answer. Do you know how to make my final list of the random runs list only select a certain number of random mainSamplers instead of just randomly selecting one. I would need some to be selected 3 times and some only twice. I want them randomly selected but with some being selected 3 times (RAB, CJ, AMR, MH, ED, ND) and the others only selected 2 times through the randomly selected runs array. – RAB Sep 15 '22 at 11:38