Skip to content

Instantly share code, notes, and snippets.

@jniac
Last active June 21, 2020 20:38
Show Gist options
  • Save jniac/31829fe9f7d903c6f473812de52eb869 to your computer and use it in GitHub Desktop.
Save jniac/31829fe9f7d903c6f473812de52eb869 to your computer and use it in GitHub Desktop.
roll some dices
D = n => Math.ceil(n * Math.random())
run = ({ name = 'run', d1, d2, n = 100000 } = {}) => {
result = {
win: 0,
loose: 0,
equals: 0,
}
for (let i = 0; i < n; i++) {
const a = d1()
const b = d2()
if (a > b) {
result.win++
} else if (a === b) {
result.equals++
} else {
result.loose++
}
}
const r = Object.entries(result)
.map(([k,v]) => `${(k + ':').padEnd(12)} ${(v / n * 100).toFixed(3).padStart(4)}%`)
.join('\n')
const s = `${name}:\n${r}\n`
console.log(s)
}
run({
d1: () => D(6) + D(12),
d2: () => D(6) + D(8),
})
D6 = () => Math.ceil(6 * Math.random())
round = () => {
let joker = 0
let stack = [
{ d:1, c: 0 },
{ d:2, c: 0 },
{ d:3, c: 0 },
{ d:4, c: 0 },
{ d:5, c: 0 },
]
let draw = [1, 2, 3, 4, 5]
let max = null
let rollCount = 0
const nextRoll = () => {
draw = draw.map(() => D6())
draw = draw.filter(d => {
if (d === 6) {
joker++
return false
}
stack[d - 1].c++
return true
})
max = stack.reduce((cur, max) => cur.c > max.c ? cur : max)
draw = draw.filter(d => {
if (d === max.d)
return false
stack[d - 1].c--
return true
})
//console.log(rollCount, { joker }, max, draw)
rollCount++
}
nextRoll() // 1
if (draw.length === 0)
return 'critical!!!'
nextRoll() // 2
if (draw.length === 0)
return 'critical!!'
nextRoll() // 3
if (draw.length === 0)
return 'critical!'
if (draw.length === 1)
return 'success'
return 'miss'
}
result = {
miss: 0,
success: 0,
critical: 0,
'critical!': 0,
'critical!!': 0,
'critical!!!': 0,
}
n = 1e6
for (let i = 0; i < n; i++) {
const r = round()
result[r]++
if (/critical/.test(r))
result.critical++
}
Object.entries(result)
.map(([k,v]) => `${(k + ':').padEnd(12)} ${(v/n*100).toFixed(1).padStart(4)}%`)
.join('\n')
@jniac
Copy link
Author

jniac commented Jun 18, 2020

fiveDicesThreeAttempts.js

n = 10 000 000

miss:        17.4%
success:     43.7%
critical:    38.8%
critical!:   20.3%
critical!!:  16.5%
critical!!!:  2.0%

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment