Created
April 13, 2020 07:33
-
-
Save ATGardner/6f65569edb3a2ef7590b91312b27d215 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function shuffleArray(array) { | |
for (let i = array.length - 1; i > 0; i--) { | |
const j = Math.floor(Math.random() * (i + 1)); | |
[array[i], array[j]] = [array[j], array[i]]; | |
} | |
} | |
function alg(n) { | |
const array = [...Array(n).keys()]; | |
shuffleArray(array); | |
// console.log(`array: ${array}`); | |
for (let i = 0; i < n; i += 1) { | |
let temp = array[i]; | |
let attempt = 0; | |
let target = i; | |
while (attempt !== n / 2 && target < n) { | |
// console.log(`i: ${i}, attempt: ${attempt}, temp: ${temp}, target: ${target}`) | |
while (temp !== target && attempt !== n / 2) { | |
const newTemp = array[temp]; | |
array[temp] = temp; | |
temp = newTemp; | |
// console.log(`after switch, temp: ${temp}, array[temp]: ${array[temp]}, array: ${array}`); | |
attempt += 1; | |
} | |
target += 1; | |
} | |
if (array[i] !== i) { | |
return false; | |
} | |
} | |
return true; | |
} | |
function prob(n = 100, attempts = 100000) { | |
const successes = [...Array(attempts).keys()].map(() => alg(n)).reduce((total, res) => { | |
total += res ? 1 : 0; | |
return total; | |
}, 0); | |
console.log(successes / attempts); | |
} | |
prob(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment