CodingTrain / CodingTrain/Suggestion-Box
Genetic Algorithm: Simple and Efficient Random Pool Selection
- Dominant language
- No language data
- Stars
- 570
- Forks
- 85
- PR merge metrics
- No merged PRs in 30d
Description
Hi. I found out that the selection can be made much simpler.
The idea is the same: making a rectangle with their lengths and pick a random number between [0, height). The one which has the length bigger is much more likely to be picked.
The rectangle is represented as an array of partial sums.
Below is the code.
```
let arr = [
{fruit: 'ananas', quality: 6},
{fruit: 'apple', quality: 12},
{fruit: 'broccoli', quality: 3},
{fruit: 'melon', quality: 9},
{fruit: 'banana', quality: 20},
];
// for testing purposes
let nrRep = 75;
let selection = [0, 0, 0, 0, 0];
while (nrRep !== 0) {
let index = pickRandom(arr);
selection[index]++;
nrRep--;
}
console.log("The final result:");
console.log(selection);
function pickRandom(arr) {
let partialSum = [];
partialSum.push(0);
arr.forEach( (el, i) => {
partialSum.push(partialSum[i] + el.quality);
});
let psLen = partialSum.length;
let maxSum = partialSum[psLen - 1];
let choise = Math.floor(Math.random() * maxSum);
// loop back to see which one is selected
let i;
for (i = psLen - 1; i >= 0; i--) {
if (choise >= partialSum[i]) {
console.log(arr[i]);
break;
}
}
// for testing purposes
return i;
}
```
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.