-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.lua
More file actions
121 lines (102 loc) · 2.5 KB
/
index.lua
File metadata and controls
121 lines (102 loc) · 2.5 KB
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
Json = require('cjson')
print('hello')
function hashWord (word)
-- TODO Your code here
return string.len(word)
end
blue = '\x1b[34m'
red = '\x1b[31m'
green = '\x1b[32m'
white = '\x1b[37m'
yellow = '\x1b[33m'
cyan = '\x1b[36m'
reset = '\x1b[0m'
function len(arr)
n = 0
if arr == nil then
return 0
end
for i, v in pairs(arr) do
n = n + 1
end
return n
end
function timeKey(key)
return key .. ' took ' .. blue
end
times = {}
function time(key)
times[key] = os.clock()
end
function timeEnd(key)
elapsed = os.clock() - times[key]
print(timeKey(key) .. elapsed .. 'ms' .. reset)
end
function loadJson(filename)
local contents = ''
local myTable = {}
local file, error = io.open(filename, 'r')
if error then
print(error)
end
if file then
-- read all contents of file into a string
local contents = file:read( '*a' )
myTable = Json.decode(contents);
io.close( file )
return myTable
end
return myTable
end
function firstTen(arr)
newArr = {}
i = 0
for key, value in pairs(arr) do
newArr[key] = value
i = i + 1
if (i > 10) then
return newArr
end
end
return newArr
end
function arrToString(arr)
s = ''
for key, value in pairs(arr) do
s = s .. ', ' .. value
end
return s
end
function testHash(hashFunction)
time('load words')
words = loadJson('words_dictionary.json')
timeEnd('load words')
print('You are about to work on ' .. green .. len(words) .. reset .. ' words')
results = {}
time('iterate over words')
for word, i in pairs(words) do
hash = hashFunction(word)
actualWords = results[hash]
if actualWords then
table.insert(actualWords, word)
else
results[hash] = { word }
end
end
timeEnd('iterate over words')
if (len(results) < len(words)) then
for hash, words in pairs(results) do
if (len(words) > 1) then
print(
'Found:' .. white .. arrToString(firstTen(words)) .. reset .. ' for ' .. cyan .. hash .. reset ..
' so ' .. red .. len(words) .. reset .. 'collisions'
)
end
end
collisionCount = len(words) - len(results)
print('There was a total of ' .. red .. collisionCount .. reset .. 'collisions')
else
print(green .. 'WOW, no collision' .. reset)
end
end
testHash(hashWord)