-
Notifications
You must be signed in to change notification settings - Fork 5
/
chance.jq
57 lines (48 loc) · 1.3 KB
/
chance.jq
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
module {
name: "math/chance",
description: "Basic pseudo-random generators",
namespace: "fadado.github.io",
author: {
name: "Joan Josep Ordinas Rosa",
email: "jordinas@gmail.com"
}
};
include "fadado.github.io/prelude";
# TODO: adapt to future jq builtins (expected in jq 1.6)
########################################################################
# Random
########################################################################
# Advances a seed producing random bits and a new seed.
#
def _NXTGEN: #:: number => [number,number]
. as $previous_seed
| (((214013 * $previous_seed) + 2531011) % 2147483648) as $seed # mod 2^31
| ($seed / 65536 | trunc) as $value # >> 16
| [ $value, $seed ]
;
# Makes a seed from a starting value.
#
def randomize($seed): #:: (number) => number
$seed | _NXTGEN[1]
;
def randomize: #:: => number
now | _NXTGEN[1]
;
# Generates a stream of random 2^15 values.
#
def rand($seed): #:: (number) => *number
$seed|unfold(_NXTGEN)
;
# Generates a stream of random [0..1) values.
#
def rnd($seed): #:: (number) => *number
$seed|unfold(_NXTGEN)
| . / 32768
;
# Generates a random [0..n) stream.
#
def random($n; $seed): #:: (number;number) => *number
$seed|unfold(_NXTGEN)
| .%($n)
;
# vim:ai:sw=4:ts=4:et:syntax=jq