Untitled

mail@pastecode.io avatar
unknown
plain_text
6 months ago
1.7 kB
0
Indexable
Never
const textRepresentations = [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
function getFirstDigit(str) {
    for(let i = 0; i < str.length; i++) {
        const code = str.charCodeAt(i);
        const char = str.charAt(i);
        if(code >= 48 && code <= 57) {
            return char;
        } 
        if((code >= 65 && code <= 90) || (code >= 97 && code <= 122)) {
            const substring = str.substring(i, i + 5);
            for(let t = 0; t < textRepresentations.length; t++) {
                if(substring.indexOf(textRepresentations[t]) === 0) {
                    return t;
                }
            }
        }   
    }
}
function getLastDigit(str) {
    let num = '';
    for(let i = 0; i < str.length; i++) {
        const code = str.charCodeAt(i);
        const char = str.charAt(i);
        if(code >= 48 && code <= 57) {
            num = char;
        } 
        if((code >= 65 && code <= 90) || (code >= 97 && code <= 122)) {
            const substring = str.substring(i, i + 5);
            for(let t = 0; t < textRepresentations.length; t++) {
                if(substring.indexOf(textRepresentations[t])=== 0) {
                    num = `${t}`;
                }
            }
        }   
    }
    return num;
}
async function getCalibration() {
    let calibration = 0;
    const lines = (await (await fetch('https://adventofcode.com/2023/day/1/input')).text()).split('\n');
    lines.forEach((line) => {
        const num = Number(`${getFirstDigit(line) ?? ''}${getLastDigit(line) ?? ''}`);
        if(isNaN(num)) {
            console.log(line);
        }
        calibration += isNaN(num) ? 0 : num;
    });
    console.log('Calibration: ', calibration);
}
Leave a Comment