728x90
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 shuffle(array) { | |
// array.sort(() => Math.random() - 0.5); | |
// } | |
// let arr = [1, 2, 3]; | |
// shuffle(arr); | |
// console.log(arr); | |
// shuffle(arr); | |
// console.log(arr); | |
// shuffle(arr); | |
// console.log(arr); | |
// Fisher-Yates Shuffle | |
function shuffle(array) { | |
for (let i = array.length - 1; i > 0; i--) { | |
let j = Math.floor(Math.random() * (i + 1)); | |
[array[i], array[j]] = [array[j], array[i]]; | |
} | |
} | |
// counts of appearances for all possible permutations | |
let count = { | |
'123': 0, | |
'132': 0, | |
'213': 0, | |
'231': 0, | |
'321': 0, | |
'312': 0 | |
}; | |
for (let i = 0; i < 1000000; i++) { | |
let array = [1, 2, 3]; | |
shuffle(array); | |
count[array.join('')]++; | |
} | |
// show counts of all possible permutations | |
for (let key in count) { | |
console.log(`${key}: ${count[key]}`); | |
} |
'Algorithm > JavaScript(Node.js)' 카테고리의 다른 글
The Modern JS Tutorial: array-methods: filter unique array members (0) | 2021.09.22 |
---|---|
The Modern JS Tutorial: array-methods: Get average age (0) | 2021.09.22 |
The Modern JS Tutorial: array-methods: sort users by age (0) | 2021.09.20 |
The Modern JS Tutorial: array-methods: map to objects (0) | 2021.09.20 |
The Modern JS Tutorial: array-methods: map to names (0) | 2021.09.20 |