Skip to content

Instantly share code, notes, and snippets.

@trubachev
Created September 29, 2018 21:24
Show Gist options
  • Save trubachev/90d98bb2fa7155d837d2ddbc5b5d3412 to your computer and use it in GitHub Desktop.
Save trubachev/90d98bb2fa7155d837d2ddbc5b5d3412 to your computer and use it in GitHub Desktop.
const day = ([...holes]) => {
const currentHole = holes.indexOf(1);
holes[currentHole] = 0;
if (currentHole === 0) {
holes[1] = 1;
} else if (currentHole === 4) {
holes[3] = 1;
} else {
holes[currentHole + [-1, 1][getRandomInt(2)]] = 1;
}
return holes;
};
const getRandomInt = max => {
return Math.floor(Math.random() * Math.floor(max));
};
const checkHole = (holes, hole) => {
return !!holes[hole];
};
const getHoles = () => {
const holes = [0, 0, 0, 0, 0];
holes[getRandomInt(5)] = 1;
return holes;
};
const maxDays = 6;
const checkAlg = alg => {
let daysPassed = 0;
let success = false;
let currentHoles = getHoles();
for (let i = 0; i < maxDays; i++) {
daysPassed++;
const check = checkHole(currentHoles, alg[i]);
if (check) {
success = true;
break;
}
currentHoles = day(currentHoles);
}
return {
days: daysPassed,
success: success,
alg: alg
};
};
const tryAlg = alg => {
const attemptsCount = 1000;
const results = {
count: attemptsCount,
successRate: 0.0,
successCount: 0,
days: [],
daysAvg: 0
};
for (let i = 0; i < attemptsCount; i++) {
const result = checkAlg(alg);
if (result.success) {
results.successCount += 1;
results.days.push(result.days);
}
}
results.daysAvg =
results.days.reduce((a, b) => a + b, 0) / results.days.length;
results.successRate = results.successCount / results.count;
console.log(
`rate: ${results.successRate.toFixed(2)} days: ${results.daysAvg.toFixed(
2
)} ${alg}`
);
return results;
};
const mutate = ([...alg]) => {
const randomStep = getRandomInt(alg.length);
const oldValue = alg[randomStep];
let newValue = getRandomInt(5);
while (oldValue === newValue) {
newValue = getRandomInt(5);
}
alg[randomStep] = newValue;
return alg;
};
const start = () => {
let alg = [];
for (let i = 0; i < maxDays; i++) {
alg[i] = getRandomInt(5);
}
let couner = 0;
let results = tryAlg(alg);
while (results.successRate !== 1.0) {
alg = mutate(alg);
results = tryAlg(alg);
console.log(++couner, results.successRate);
}
console.log("Alg done!");
console.log(alg);
};
start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment