finish day 5

This commit is contained in:
2026-06-24 10:15:12 -04:00
parent e757f90858
commit f93eb1728f

View File

@@ -18,22 +18,23 @@ Parsing_State :: enum {
} }
Range :: struct { Range :: struct {
min: int; min: u64;
max: int; max: u64;
} }
range_contains :: (range: Range, id: int) -> bool { range_contains :: (range: Range, id: u64) -> bool {
return range.min <= id && id <= range.max; return range.min <= id && id <= range.max;
} }
main :: () { main :: () {
content := read_entire_file("day5.input"); content := read_entire_file("day5.input");
solve_first(content); solve_first(content);
solve_second(content);
} }
solve_first :: (input: string) { solve_first :: (input: string) {
fresh_ids: [..]Range; fresh_ids: [..]Range;
ingredients: [..]int; ingredients: [..]u64;
parsing_state: Parsing_State; parsing_state: Parsing_State;
for line: split(input, #char "\n") { for line: split(input, #char "\n") {
if line.count == 0 { if line.count == 0 {
@@ -42,11 +43,11 @@ solve_first :: (input: string) {
} }
if parsing_state == .Fresh_Ids { if parsing_state == .Fresh_Ids {
_, left, right := split_from_left(line, #char "-"); _, left, right := split_from_left(line, #char "-");
min := parse_int(*left); min := parse_int(*left, u64);
max := parse_int(*right); max := parse_int(*right, u64);
array_add(*fresh_ids, .{min=min, max=max}); array_add(*fresh_ids, .{min=min, max=max});
} else if parsing_state == .Ingredient_Ids { } else if parsing_state == .Ingredient_Ids {
id := parse_int(*line); id := parse_int(*line, u64);
array_add(*ingredients, id); array_add(*ingredients, id);
} }
} }
@@ -60,14 +61,60 @@ solve_first :: (input: string) {
if range_contains(range, ingredient) { if range_contains(range, ingredient) {
total_fresh += 1; total_fresh += 1;
continue ingredient_loop; continue ingredient_loop;
} }
} }
} }
print("%\n", total_fresh); print("%\n", total_fresh);
} }
solve_second :: (input: string) {
fresh_ids: [..]Range;
for line: split(input, #char "\n") {
if line.count == 0 {
break;
}
_, left, right := split_from_left(line, #char "-");
min := parse_int(*left, u64);
max := parse_int(*right, u64);
array_add(*fresh_ids, .{min=min, max=max});
}
sorted_fresh_ids := quick_sort(fresh_ids, (a: Range, b: Range) -> s32 {
if a.min < b.min {
return -1;
} else if b.min < a.min {
return 1;
} else {
return 0;
}
});
smooshed_ids: [..]Range;
current_i := 0;
for range: sorted_fresh_ids {
if smooshed_ids.count == 0 {
array_add(*smooshed_ids, range);
continue;
}
smooshed_range := *smooshed_ids[current_i];
if range.min <= smooshed_range.max + 1 && smooshed_range.max < range.max {
smooshed_range.max = range.max;
} else if smooshed_range.max + 1 < range.min {
array_add(*smooshed_ids, range);
current_i += 1;
}
}
total : u64 = 0;
for smooshed_ids {
total += (it.max - it.min) + 1;
}
print("%\n", total);
}
#import "Basic"; #import "Basic";
#import "Hash_Table"; #import "Hash_Table";
#import "File"; #import "File";
#import "Sort";
#import "String"; #import "String";