DEV Community

Discussion on: Daily Coding Puzzles - Nov 11th - Nov 16th

Collapse
 
clandau profile image
Courtney

I had to resort to following along with a youtube video of the challenge, but I understand it now, so...learning?

But seriously, tons of new things learned this week, like handling stdin and stdout data, reading test data from a file and writing answers to a file. Glad to have these challenges to follow!

function processData(input) {
    let resultStr = '';
    const inputArray = input.split('\n');
    const cases = parseInt(inputArray.shift());
    for(let i=0; i<cases; i++) {
        resultStr += `Case # ${i+1}: `;
        let me = inputArray.shift().split(' ');
        let destination = parseFloat(me[0]);
        let numHorses = parseInt(me[1]);
        let horses = [];
        for(let j=0; j<numHorses; j++) {
            let horse = inputArray.shift().split(' ');
            horses.push({ velocity: parseFloat(horse[1]), location: parseFloat(horse[0])});
        }
        let sortedHorses = horses.sort((a, b) => b.location-a.location);
        resultStr += `${cruiseControl(destination, sortedHorses)}\n`;
    }
    return process.stdout.write(resultStr);
}

function cruiseControl(dest, horseArry) {
    let B = horseArry[0].location, vB = horseArry[0].velocity;
    for (let i=1; i<horseArry.length; i++) {
        let A = horseArry[i].location, vA = horseArry[i].velocity;
        if(vB === vA) B = A, vB = vA;
        else {
            let x = (vB * A - vA * B) / (vB - vA);
            if(x > dest || x < A) {
                B = A, vB = vA;
            } 
        }
    }
    let tB = (dest - B) / vB;
    return dest / tB;
}