re: AoC Day 1: Chronal Calibration VIEW POST

FULL DISCUSSION
 

This seemed easiest to do in awk:

Part 1
BEGIN {
    f = 0
}

{
    f += $1
}

END {
    print f
}
awk -f 1.1.awk 1.1.input
Part 2

awk's arrays are basically hashes/associative arrays, so you can just use the frequencies as keys much like the Python dictionary solutions. Because awk is really focused on processing a list of files, this uses a hack on the built-in variable that tracks where on that list awk has gotten to, so it only stops once it's found the duplicate.

BEGIN {
    f = 0
    a[0] = 1
}

{
    f += $1
    if (f in a) {
        a[f] += 1
    } else {
        a[f] = 1
    }
    if (a[f] == 2) {
        print(f)
        exit 0
    }
    # Resets what file is the next to process
    ARGIND=0
}
awk -f 1.2.awk 1.2.input
code of conduct - report abuse