forked from titzer/virgil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCommon.v3
48 lines (44 loc) · 1.25 KB
/
Common.v3
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
// Copyright 2011 Google Inc. All rights reserved.
// See LICENSE for details of Apache 2.0 license.
// Utility code for all benchmarks.
component Int {
// parse a string as an integer, without any error checking
def parse(a: Array<byte>) -> int {
var accum = 0;
for (i < a.length) {
var dig = int.!(a[i]);
accum = accum * 10 + dig - int.!('0');
}
return accum;
}
}
component Util {
var dots: int;
def intArg(args: Array<string>, default: int) -> int {
if (args != null && args.length > 0) return Int.parse(args[0]);
return default;
}
def dot() {
System.putc('.');
dots = dots + 1;
if (dots % 78 == 0) System.ln();
}
}
component Random {
var seed = 121013;
// return a pseudo-random number
def random(max: int) -> int {
return random2(max, 0);
}
// return a pseudo-random number with an extra source of entropy
def random2(max: int, extra: int) -> int {
seed = seed * 1664525 + 1013904223 + extra; // multiplicative random
seed = seed ^ (seed >>> 16) ^ (seed >>> 24); // XOR in some higher bits
var result = (seed & 2147483647) % max; // limit to max
return result;
}
// use a random number to flip a coin with a given probability
def flip(num: int, denom: int) -> bool {
return (random2(denom, num) % denom) < num;
}
}