-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathletters.mjs
116 lines (94 loc) · 2.36 KB
/
letters.mjs
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
import { readFile } from 'node:fs/promises';
const permutationsOf = (array, callback) => {
const swap = (array, pos1, pos2) => {
var temp = array[pos1];
array[pos1] = array[pos2];
array[pos2] = temp;
};
const heaps = (n, heapArr, results = [], cb = null) => {
if (n < 1) {
if (cb) {
cb(heapArr)
} else {
results.push(heapArr.slice());
}
return;
}
heaps(n-1, heapArr, results, cb);
for (let i = 0; i < n-1; i++) {
if (n % 2 === 0) {
swap(heapArr, i, n-1);
} else {
swap(heapArr, 0, n-1);
}
heaps(n-1, heapArr, results, cb);
}
return results;
}
if (typeof(array) === 'string') {
return heaps(array.length, array.split(''), [], callback);
} else if (Array.isArray(array)) {
return heaps(array.length, array.slice(), [], callback);
} else {
console.error(`called permutations with a non array arg: ${array}`);
return [];
}
}
class Trie {
constructor() {
this.root = {};
}
insert(word) {
let node = this.root;
for (let i = 0; i < word.length; i++) {
const char = word[i];
if (!node[char]) {
node[char] = {};
}
node = node[char];
if (i === word.length-1) {
node.END = true;
}
}
}
contains(word) {
let node = this.root;
for (let i = 0; i < word.length; i++) {
const char = word[i];
if (!node[char]) {
return false;
}
node = node[char];
}
return !!node.END;
}
}
// LETTERS
const MIN_WORD_LENGTH = 4;
const args = process.argv.slice(2);
const letters = args[0].toUpperCase();
console.log(letters);
console.log(`n = ${letters.length}`);
const t1 = performance.now();
const rawWords = await readFile('./words.txt');
const wordsList = String(rawWords).toUpperCase().split(/\r?\n/);
console.log(`searching ${wordsList.length} words...`);
const wordsTrie = new Trie();
for (const word of wordsList) {
wordsTrie.insert(word);
}
const answers = new Set();
permutationsOf(letters, (perm) => {
let word = perm.join('');
while (word.length >= MIN_WORD_LENGTH) {
if (wordsTrie.contains(word)) {
answers.add(word);
break;
}
word = word.slice(0, -1);
}
});
const sorted = Array.from(answers).sort((a,b) => b.length - a.length);
const t2 = performance.now();
console.log(sorted);
console.log(`took ${t2-t1}ms`);