aboutsummaryrefslogtreecommitdiff
path: root/2025/src/day01.cpp
blob: 2650b3cd429332b9f935a566ca245c17c0638f81 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

namespace {

vector<string>
read_file(const filesystem::path& filename)
{
	ifstream       file{ filename };
	vector<string> lines;

	for ( string line; getline(file, line); ) {
		lines.emplace_back(line);
	}

	return lines;
}

void
part1(const vector<string>& lines)
{
	auto zeros = 0;
	auto pos   = 50;

	for ( const auto& line: lines ) {
		const auto value = stoi(line.substr(1)) % 100;
		pos += (line[0] == 'L') ? (100 - value) : value;
		if ( pos % 100 == 0 ) {
			++zeros;
		}
	}
	cout << "Part 1: " << zeros << '\n';
}

void
part2(const vector<string>& lines)
{
	auto zeros = 0;
	auto pos   = 50;

	for ( const auto& line: lines ) {
		const auto delta = (line[0] == 'L') ? 99 : 1;
		for ( auto value = stoi(line.substr(1)); value > 0; --value ) {
			pos += delta;
			if ( pos % 100 == 0 ) {
				++zeros;
			}
		}
	}
	cout << "Part 2: " << zeros << '\n';
}

void
part2_opti(const vector<string>& lines)
{
	auto zeros = 0;
	auto pos   = 50;

	auto is_zero = [&pos] {
		return pos % 100 == 0;
	};

	for ( const auto& line: lines ) {
		const auto delta = (line[0] == 'L') ? 99 : 1;
		auto       value = stoi(line.substr(1));

		if ( !is_zero() ) {
			for ( ; value > 0 && !is_zero(); --value ) {
				pos += delta;
			}

			if ( is_zero() ) {
				++zeros;
			}
		}

		zeros += value / 100;
		value %= 100;

		for ( ; value > 0; --value ) {
			pos += delta;
			if ( is_zero() ) {
				++zeros;
			}
		}
	}
	cout << "Part2 (Opti): " << zeros << '\n';
}

} // namespace

int
main()
{
	auto data = read_file("data/day01.txt");
	part1(data);
	part2(data);
	part2_opti(data);
}