Skip to content

Commit

Permalink
Advent of code day 1
Browse files Browse the repository at this point in the history
  • Loading branch information
lerno committed Dec 2, 2022
1 parent 78d7d3f commit 2a5578b
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
33 changes: 33 additions & 0 deletions day1_1.c3
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import std::io;
import libc;

fn void main()
{
File f;
f.open("calories.txt", "rb")!!;
defer catch(f.close());
usz current_entry = 0;
usz max_entry = 0;
usz max_elf = 1;
usz index_elf = 1;
while (!f.eof())
{
@pool()
{
char[] line = f.tgetline();
if (!line.len)
{
current_entry = 0;
index_elf++;
continue;
}
current_entry += str::to_int(line)!!;
if (current_entry > max_entry)
{
max_elf = index_elf;
max_entry = current_entry;
}
};
}
io::printfln("Elf #%d carries the most calories (%d)", max_elf, max_entry);
}
45 changes: 45 additions & 0 deletions day1_2.c3
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import std::io;

int[3] entry_max;

fn void update_max(int entry)
{
for (int i = 0; i < 3; i++)
{
if (entry > entry_max[i])
{
for (int j = 2; j > i; j--)
{
entry_max[j] = entry_max[j - 1];
}
entry_max[i] = entry;
return;
}
}
}

fn void main()
{
File f;
f.open("calories.txt", "rb")!!;
defer catch(f.close());
int current_entry = 0;
while (!f.eof())
{
@pool()
{
char[] line = f.tgetline();
if (!line.len)
{
update_max(current_entry);
current_entry = 0;
continue;
}
current_entry += str::to_int(line)!!;
};
}
if (current_entry) update_max(current_entry);
int sum = 0;
foreach (val : entry_max) sum += val;
io::printfln("Top three elves carries: %d", sum);
}

0 comments on commit 2a5578b

Please sign in to comment.