this repo has no description
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

turn each line into frames to search for digits

+48 -14
+31 -11
2023/day01/part2.ts
··· 1 - const intWords = [ 1 + const digitWords = [ 2 2 "one", 3 3 "two", 4 4 "three", ··· 9 9 "eight", 10 10 "nine", 11 11 ]; 12 - const numRegex = new RegExp(`(\\d|${intWords.join("|")})`, "g"); 12 + const digits = "123456789".split(""); 13 + const wordsAndDigits = [...digitWords, ...digits]; 14 + const frameSize = Math.max(...wordsAndDigits.map((s) => s.length)); 15 + 16 + const charsFromTo = (str: string, from: number, to: number) => { 17 + const strs = []; 18 + for (let i = from; i <= to; i++) { 19 + if (i >= str.length) continue; 20 + strs.push(str.slice(from, i + 1)); 21 + } 22 + return strs; 23 + }; 24 + 25 + export const frames = (str: string, maxSize: number): string[] => 26 + str 27 + .split("") 28 + .reduce<string[]>( 29 + (acc, _, idx) => [...acc, ...charsFromTo(str, idx, idx + maxSize - 1)], 30 + [], 31 + ); 13 32 14 33 export const calibrationValue = (line: string): number => { 15 - const ints = line.match(numRegex)?.map((iStr) => { 16 - if (iStr.match(/^\d$/)) return iStr; 34 + const digits = frames(line, frameSize) 35 + .filter((f) => wordsAndDigits.includes(f)) 36 + .map((digitStr) => { 37 + if (digitStr.match(/^\d$/)) return digitStr; 17 38 18 - const wordIdx = intWords.indexOf(iStr); 19 - if (wordIdx !== -1) return (wordIdx + 1).toString(); 39 + const wordIdx = digitWords.indexOf(digitStr); 40 + if (wordIdx !== -1) return (wordIdx + 1).toString(); 20 41 21 - throw new Error(`no digit for match: ${iStr}`); 22 - }); 42 + throw new Error(`no digit for match: ${digitStr}`); 43 + }); 23 44 24 - if (!ints) throw new Error(`no ints in line: ${line}`); 45 + if (!digits) throw new Error(`no ints in line: ${line}`); 25 46 26 - const numStr = `${ints[0]}${ints[ints.length - 1]}`; 27 - console.log(`${line}: ${ints} -- ${numStr}`); 47 + const numStr = `${digits[0]}${digits[digits.length - 1]}`; 28 48 return parseInt(numStr); 29 49 }; 30 50
+17 -3
2023/day01/test.ts
··· 40 40 ); 41 41 }); 42 42 43 - // Deno.test("frames", () => { 44 - // assertEquals(p2.frames("abc", 2), ["ab", "bc", "c"]); 45 - // }); 43 + Deno.test("frames", () => { 44 + assertEquals(p2.frames("abc", 2), ["a", "ab", "b", "bc", "c"]); 45 + assertEquals(p2.frames("abcde", 3), [ 46 + "a", 47 + "ab", 48 + "abc", 49 + "b", 50 + "bc", 51 + "bcd", 52 + "c", 53 + "cd", 54 + "cde", 55 + "d", 56 + "de", 57 + "e", 58 + ]); 59 + });