-
Notifications
You must be signed in to change notification settings - Fork 7
/
utils.oc
72 lines (58 loc) · 1.7 KB
/
utils.oc
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
//* Miscellaneous utilities
import std::vector::Vector
[extern] def strsep(s: &str, delim: str): str
const MAX_N: u32 = 128
const MAX_M: u32 = 128
def edit_distance(str1: str, str2: str): u32 {
let n = str1.len()
let m = str2.len()
if n > MAX_N or m > MAX_M return n + m
let stride = m + 1
// The stack _should_ be large enough to hold the entire matrix.
let d: [[u32; MAX_M]; MAX_N]
for let i = 0; i <= n; i += 1 {
d[i][0] = i
}
for let j = 0; j <= m; j += 1 {
d[0][j] = j
}
for let i = 1; i <= n; i += 1 {
for let j = 1; j <= m; j += 1 {
let x = d[i - 1][j] + 1
let y = d[i][j - 1] + 1
let z = if str1[i - 1] == str2[j - 1] {
yield d[i - 1][j - 1]
} else {
yield d[i - 1][j - 1] + 1
}
d[i][j] = x.min(y).min(z)
}
}
let result = d[n][m]
return result
}
def find_word_suggestion(s: str, options: &Vector<str>): str {
let threshold = 5 // edit distance threshold
if options.size == 0 return null
let closest = options.at(0) as str
let closest_distance = edit_distance(s, closest)
for option in options.iter() {
let distance = edit_distance(s, option)
if distance < closest_distance {
closest = option
closest_distance = distance
}
}
if closest_distance > threshold return null
return closest
}
@compiler c_include "dirent.h"
[extern] struct DIR
[extern] def opendir(path: str): &DIR
[extern] def closedir(dir: &DIR)
def directory_exists(path: str): bool {
let dir = opendir(path)
if dir == null return false
closedir(dir)
return true
}