#Day 1 - Historian Hysteria

58 messages Β· Page 1 of 1 (latest)

boreal kindle
low ferry
#

A gentle start

limber wren
#

πŸ‘€ ah, starts today

#

||```cpp
void AocMain(std::string_view input) {
std::vector<int32_t> leftList;
std::vector<int32_t> rightList;

for (auto line : input | Split('\n')) {
    std::size_t space = line.find(' ');
    leftList.emplace_back(ParseNumber<int32_t>(line.substr(0, space)));
    rightList.emplace_back(ParseNumber<int32_t>(line.substr(space + 3)));
}

ranges::sort(leftList);
ranges::sort(rightList);

int64_t diff{};
for (auto [lhs, rhs] : views::zip(leftList, rightList)) {
    diff += std::abs(rhs - lhs);
}
logger.solution("{}", diff);

int64_t part2{};
auto rightIt = rightList.begin();
for (const int32_t left : leftList) {
    rightIt = ranges::find_if(rightIt, rightList.end(), [left](int32_t right) { return right >= left; });
    if (rightIt == rightList.end()) {
        break;
    }
    int32_t right = *rightIt;
    if (right > left) {
        continue;
    }
    auto greaterIt = ranges::find_if(rightIt, rightList.end(), [left](int32_t right) { return right > left; });
    part2 += right * (greaterIt - rightIt);
}
logger.solution("{}", part2);

}

nocturne loom
azure vessel
#

good old python one liners

past fog
#

not too bad today

rose creek
#

Day 1, so obviously I had to do it in a stupid way:

Nix
||```nix
with builtins; let
input = readFile ./day1.txt
|> split "\n"
|> filter isString
|> map (match "([-0-9]+) +([-0-9]+)")
|> filter isList
|> map (l: fromJSON "[${elemAt l 0},${elemAt l 1}]");

left = sort lessThan (map head input);
right = sort lessThan (map (l: elemAt l 1) input);

abs = n: if n > 0 then n else -n;
sum = foldl' add 0;
eachLeft = op: genList (n: op n (elemAt left n)) (length left);

part1 = sum (eachLeft (n: l: abs (sub l (elemAt right n))));
part2 = sum (eachLeft (n: l: mul l (length (filter (e: e == l) right))));

in [part1 part2]

#

-# yes there's no builtin parseInt function that I know of so I used the JSON parser

idle rover
#

Is it just me or ||part 2 was slightly easier than part 1?||

#

||Took me just 20 minutes for full completion... I just... know this'll be the last day I have an easy time cringeharold||

#

First rawdogged version

#

Exactly 50 lines feelsgoodman

#

Now i'll try to condense it more and make it ✨ smarter ✨

past fog
#

||took me about 10 minutes for part 1, 2 minutes to adapt to part 2, then about an hour doing pointless optimisations πŸ˜„ ||

#

|| I did do 2 versions tho, one LinQ, then a normal one - I prefer the normal one ||

signal plover
#

||I've cleaned this up to use ranges where applicable and got rid of a couple unnecessary includes||

past fog
#

remind me where to paste the code for that fancy fomatting again?

#

nm, found it I think

#

carbon?

signal plover
#

I used a vscode extension called Polacode

past fog
#

ooh, fancy πŸ˜„

#

Anyway, here's mine:

#

|| uses SIMD to process 8 ints at once ||

signal plover
#

fancy!

past fog
#

|| final form i think - I now use a Dictionary to store the counts which is calc'd at the same time as the strings are parsed, which happens anyway ||

limber wren
#

πŸ€” haven't seen anyone else ||take advantage of the sorted array for part 2. I guess the inputs are too small for it to matter.||

azure vessel
#

I suspect there will definitely be runtime issues in future days though

#

I know they love doing that thingwhere part two is just a bigger version of part one

#

Holy shit i can’t spell

twin plinth
#

Just a couple comprehensions in python today
||

def read_input(filename):
    with open(filename, 'r') as input:
        left, right = zip(*(map(int, line.split()) for line in input))
    return list(left), list(right)


def part1(left, right):
    return sum(abs(r-l) for l, r in zip(sorted(left), sorted(right)))


def part2(left, right):
    right_ct = {r: right.count(r) for r in set(right)}
    return sum(l * right_ct.get(l, 0) for l in left)

||

limber wren
#

O(N) instead of O(N^2)

#

||not counting the sorting itself||

past fog
#

probably me ||but I don't see how you can take advantage of if being sorted for p2?||

past fog
#

I'm confused πŸ˜„

limber wren
#

That's what I did

past fog
#

ah, I see what you mean now - didn't see your code before

#

not that yours is code, it's hieroglyphics πŸ˜„

#

hmm

#

I was finished, but might put that in

past fog
limber wren
#

||Ah, C# Dictionary is unordered so I guess it technically would be O(N)||

#

||Just an expensive O(N)||

mild hinge
nocturne gorge
#

spent like 5 hours today trying to get an ocaml solution before giving up and writing a quick and dirty rust solution

#

||```rust
pub fn main() {
let input = fs::read_to_string("./src/1/input").expect("Unable to read file");

let lines = input.lines().collect::<Vec<&str>>();
let mut left: Vec<i64> = Vec::new();
let mut right: Vec<i64> = Vec::new();

for line in lines {
    let lr: Vec<&str> = line.split("   ").collect::<Vec<&str>>();
    left.push(lr[0].parse::<i64>().unwrap());
    right.push(lr[1].parse::<i64>().unwrap());
}
left.sort();
right.sort();

let z = std::iter::zip(left.clone(), right.clone());
let result1 = z.map(|e| (e.1 - e.0).abs()).fold(0, |acc, x| acc + x);
println!("result: {result1}");

let result2 = left
    .iter()
    .map(|e| e * right.iter().filter(|f| *f == e).count() as i64)
    .fold(0, |acc, e| acc + e);
println!("result2: {result2}");

}

velvet dew
#

||```julia
println(sum(abs(a - b) for (a, b) in zip([sort(col) for col in eachcol([e[i] for e in [parse.(Int64, [m.match for m in eachmatch(r"(\d+)", line)]) for line in eachline("input.txt")], i in 1:2])]...)))


Part 1
boreal kindle
boreal kindle
#

ahhh, I wondered about that

velvet dew
#

Both parts (no more oneliner Yuki_Furry_Sad)

idle rover