-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.coffee
140 lines (124 loc) · 2.49 KB
/
util.coffee
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
shuffle = (a) ->
a = [a...]
len = a.length
for i in [len-1...0] by -1
r = (Math.random() * (i+1)) | 0
tmp = a[i]
a[i] = a[r]
a[r] = tmp
a
memoize = (fn) ->
cache = new Map
(args...) ->
value = cache.get(args)
if value is undefined
value = fn(args...)
cache.set args
value
value
int = (f) -> f | 0
gzwriter = (filename) ->
if filename == '-'
process.stdout
else
ws = require('fs').createWriteStream filename
if filename.endsWith '.gz'
gz = require('zlib').createGzip()
gz.pipe ws
gz
else
ws
lru_cache = (max) ->
cache = {}
head = {}
head.prev = head.next = head
n = 0
hit = 0
miss = 0
evict = 0
remove = (item) ->
item.next.prev = item.prev
item.prev.next = item.next
insert = (item) ->
item.prev = head
item.next = head.next
head.next.prev = item
head.next = item
put: (key, data) ->
item = cache[key]
if item
remove item
else
if n >= max
evict += 1
last = head.prev
remove last
delete cache[last.key]
else
n++
item = {key, data}
insert item
cache[key] = item
get: (key) ->
item = cache[key]
unless item
miss += 1
return null
hit += 1
if item != head.next
remove item
insert item
item.data
stats: ->
{n, hit, miss, evict}
round_value = (value) -> Math.round(value * 1e4) / 1e4
INFINITY = 1<<30
unique_moves = (board, me, moves=null) ->
{encode_normalized} = require './encode'
moves or= board.list_moves(me)
codes = {}
result = []
for move in moves
flips = board.move me, move
code = encode_normalized(board)
board.undo me, move, flips
unless codes[code]
codes[code] = true
result.push move
result
watch_file = (filename) ->
fs = require 'fs'
get_mtime = ->
if fs.existsSync(filename)
fs.statSync(filename).mtime.getTime()
else
null
last_mtime = get_mtime()
->
mtime = get_mtime()
if mtime != last_mtime
last_mtime = mtime
true
else
false
format_eval = (score, logistic, solved) ->
{ SCORE_MULT } = require './pattern'
{ LOG_MULT, to_probability } = require './logutil'
if solved
score
else if logistic
Math.round(to_probability(score) * 1000) / 1000
else
Math.round(score / SCORE_MULT * 100) / 100
module.exports = {
shuffle
memoize
int
gzwriter
lru_cache
round_value
INFINITY
unique_moves
watch_file
format_eval
}