-
-
Save ChALkeR/2b7414c4a037d8b4f65c6fca2d4e3d28 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const count = 10e6 | |
| const length = 100 | |
| const letter = () => { | |
| const l = Math.random() * 52 | 0 | |
| return String.fromCharCode(l < 26 ? l + 65 : l + 71) | |
| } | |
| const word = () => { | |
| const arr = [] | |
| for (let i = 0; i < length; i++) arr.push(letter()) | |
| return arr.join('') | |
| } | |
| const pool = [] | |
| console.time('generate') | |
| for (let i = 0; i < count; i++) pool.push(word()) | |
| console.timeEnd('generate') | |
| console.time('sort') | |
| pool.sort() | |
| console.timeEnd('sort') | |
| if (typeof process !== 'undefined') | |
| console.log(`${process.memoryUsage().rss / 2**20} MiB`) | |
| const query = (q) => { | |
| let pos = count / 2 | 0, delta = count / 4, res | |
| while (res = q(pos)) { | |
| if (res < 0) pos -= delta | 0 || 1 | |
| if (res > 0) pos += delta | 0 || 1 | |
| if (pos < 0 || pos >= count) return null | |
| delta /= 2 | |
| } | |
| return pos | |
| } | |
| const search = (prefix) => { | |
| console.time('search') | |
| const start = query((pos) => { | |
| if (pool[pos] < prefix) return +1 | |
| if (pos - 1 < 0) return pool[pos].startsWith(prefix) ? 0 : -1 | |
| if (pool[pos - 1] >= prefix) return -1 | |
| return 0 | |
| }) | |
| const end = query((pos) => { | |
| if (pool[pos] >= prefix && !pool[pos].startsWith(prefix)) return -1 | |
| if (pos + 1 >= count) return pool[pos].startsWith(prefix) ? 0 : +1 | |
| if (pool[pos + 1] < prefix || pool[pos + 1].startsWith(prefix)) return +1 | |
| return 0 | |
| }) | |
| if (start === null || end === null) return 0 | |
| console.timeEnd('search') | |
| return end - start + 1 | |
| } | |
| console.log(search('Tst')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment