#Day 1 - Historian Hysteria
58 messages Β· Page 1 of 1 (latest)
A gentle start
π 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);
}
ah it's that time again. https://github.com/Redcrafter/AdventOfCode/blob/master/js/2024/day-1.js
good old python one liners
not too bad today
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
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
||
First rawdogged version
Exactly 50 lines 
Now i'll try to condense it more and make it β¨ smarter β¨
||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 ||
||I've cleaned this up to use ranges where applicable and got rid of a couple unnecessary includes||
remind me where to paste the code for that fancy fomatting again?
nm, found it I think
carbon?
I used a vscode extension called Polacode
fancy!
|| 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 ||
π€ 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.||
Yeah, I thought about it, but first wanted to see if I can just do list.count(foo) and get a solution
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
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)
||
how so?
or how will it help, rather
probably me ||but I don't see how you can take advantage of if being sorted for p2?||
or did you mean I already do it and you've not seen anyone else?
I'm confused π
That's what I did
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
mine's O(N) anyway, isn't it? ||Also, my occurrence counts is a dictionary lookup that's created while parsing the numbers||
π€ ||dictionary lookup for each element on the left would be O(N*log(N))||
||Ah, C# Dictionary is unordered so I guess it technically would be O(N)||
||Just an expensive O(N)||
||yeah it also felt a bit easier for me :p||
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}");
}
||```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
what lang is that in? it looks vaguely like python, but I know it's not
Julia
ahhh, I wondered about that
Both parts (no more oneliner
)
Improved (IMO, at least)