Re: Help with Arrays
Posted: Wed Jul 16, 2025 5:27 pm
Your while loop will enter first time because the condition is true (the done_encounters contains current value of next_encounter=0 because you pushed it in initialization), and it will be executed once where it will assign it some value between one and number of encounters, since done_encounters at that moment only has one element, [0] - the while will end since it is false now. So you will always end up with an array of 2 elements in done_encounters which will be [0, some_random_number].
If you want to have an array of encounters, each appearing only once, then you can use Fisher-Yates algorithm to randomize an order of array of n encounters. First you have to have all of them in an array (you can also exclude some based on certain condition), then shuffle them:
In this case you would have randomized encounters in "done_encounters" array, but you could save it to some like "pending_encounters" and you can do
next_encounter = pending_encounters.pop(); // this will take last element from the array and assign it to next_encounter
and you can do while (pending_encounters.length>0) since each time you do pop, the element is removed from array.
If you want to have an array of encounters, each appearing only once, then you can use Fisher-Yates algorithm to randomize an order of array of n encounters. First you have to have all of them in an array (you can also exclude some based on certain condition), then shuffle them:
Code: Select all
function getRandomArray(n) {
// Step 1: Initialize the array with numbers from 0 to n
const arr = [];
for (let i = 0; i <= n; i++) {
arr.push(i);
}
// Step 2: Shuffle using Fisher-Yates algorithm
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1)); // Random index
[arr[i], arr[j]] = [arr[j], arr[i]]; // Swap elements
}
return arr;
}
// Example usage:
done_encounters = getRandomArray(9);
console.log(done_encounters ); // i.e. (10) [3, 6, 8, 0, 5, 1, 2, 9, 4, 7]
next_encounter = pending_encounters.pop(); // this will take last element from the array and assign it to next_encounter
and you can do while (pending_encounters.length>0) since each time you do pop, the element is removed from array.