DEV Community

Discussion on: AoC Day 1: Chronal Calibration

Collapse
 
magicleon94 profile image
Antonello Galipò • Edited

Hi there!
I've used Javascript.
Here's my part one solution:

const fs = require('fs');

// Read the input
let contents = fs.readFileSync('frequenciesDiff.txt','utf8');

// Parse to a int array
let diffs = contents.split("\n").map(item => parseInt(item));

// Reduce
let result = diffs.reduce((a,b) => a+b);


// Profit!
console.log(result);

I just read the input from file, parsed to a int array and used the reduce function.

Talking about the second part, I've user a dictionary to store frequencies and retrieve them quickly (access is O(1)), cycling in a circular manner through the provided diffs:

const fs = require('fs');

function duplicateFinder(diffs) {
    // Init an empty memo. We'll store here frequency values for easy retrieval
    let memo = {};

    let currentFrequency = 0;
    let i = 0;

    // Loop until currentFrequency is already in the memo.
    // When the loop breaks, it will be because currentFrequency got a value that had before. 
    // This means it's the second time it appears
    while (!(currentFrequency in memo)) {
        memo[currentFrequency] = currentFrequency.toString();

        currentFrequency += diffs[i];
        i = ++i % diffs.length
    }
    return currentFrequency;
}

// Read the input
let contents = fs.readFileSync('frequenciesDiff.txt', 'utf8');

// Parse to a int array
let diffs = contents.split("\n").map(item => parseInt(item));

// Do the work
let result = duplicateFinder(diffs);

// Profit!
console.log(result);

I'm planning to do this in Go too, since I'd love to practice this language, but I haven't much time for now :(