Your logic seems wrong...
To get each encounter only once, better way is to store them in random order in pending_encounters variable, that way you just take from that pile, and you don't need to do while loop until you find one that hasn't happened, that is very inefficient, imagine having 100 and after 99 you have 1% chance to get the remaining one, your while loop would spin for a while until you hit that one.
Based on what you said what you want I generated this with chatgpt (was faster than writing by hand, adjust as needed):
Code: Select all
// Constants
const number_of_encounters = 10;
let pending_encounters = [];
let done_encounters = [0];
let next_encounter = 0;
// Initialize pending_encounters with 1..10 in random order
function initializePendingEncounters() {
pending_encounters = Array.from({ length: number_of_encounters }, (_, i) => i + 1); // this creates list with sequential items
// Shuffle using Fisher-Yates algorithm
for (let i = pending_encounters.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[pending_encounters[i], pending_encounters[j]] = [pending_encounters[j], pending_encounters[i]];
}
}
// Function to get the next encounter
function get_next_encounter() {
if (pending_encounters.length === 0) {
console.log("No more encounters remaining!");
return null;
}
const value = pending_encounters.shift(); // Take first element
done_encounters.push(value);
next_encounter = value;
return value;
}
// Example usage:
initializePendingEncounters();
console.log("Pending encounters:", pending_encounters);
console.log("Next encounter:", get_next_encounter());
console.log("Updated pending:", pending_encounters);
console.log("Done encounters:", done_encounters);
console.log("Current next_encounter:", next_encounter);
Explanation:
pending_encounters starts as an empty array and gets filled with numbers 1..number_of_encounters in random order using Fisher-Yates shuffle.
done_encounters starts with [0] as requested.
get_next_encounter():
Pops the first element from pending_encounters (FIFO order).
Pushes it to done_encounters.
Updates next_encounter.
Returns the value.
You could place the code from initializePendingEncounters function directly into initialization block, so you don't need the function (since you only need it to run once).