-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path10.cpp
112 lines (99 loc) · 1.96 KB
/
10.cpp
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
105
106
107
108
109
110
111
112
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
class Procesador {
public:
Procesador(const string &fname);
void Cycle();
void CycleUntil(int n);
bool Done();
long X() { return reg_x; }
unsigned int Cycles() { return cycles; }
private:
void LoadNextInstruction();
void Postconditions();
vector<string> program;
vector<string> current;
long reg_ip = 0;
long reg_x = 1;
unsigned int cycles = 0, cycle_count = 0;
};
void Procesador::CycleUntil(int n) {
while (cycles < n) {
Cycle();
}
}
Procesador::Procesador(const string &fname) {
ifstream file(fname);
string line;
while (getline(file, line)) {
program.push_back(line);
}
}
void Procesador::Cycle() {
if (cycle_count == 0) {
Postconditions();
LoadNextInstruction();
}
cycle_count--;
cycles++;
}
bool Procesador::Done() { return reg_ip == program.size(); }
void Procesador::Postconditions() {
if (current.empty()) {
return;
}
if (current[0] == "addx") {
int value = atoi(current[1].c_str());
reg_x += value;
}
}
void Procesador::LoadNextInstruction() {
string token, next = program[reg_ip++];
stringstream ss(next);
current.clear();
while (getline(ss, token, ' ')) {
current.push_back(token);
}
if (current[0] == "noop") {
cycle_count = 1;
} else if (current[0] == "addx") {
cycle_count = 2;
}
}
void P1() {
Procesador p("10.txt");
int acc = 0;
for (int c = 20; c <= 220; c += 40) {
p.CycleUntil(c);
acc += (c * p.X());
}
cout << "P1: " << acc << endl;
}
void P2() {
cout << "P2:" << endl;
Procesador p("10.txt");
for (int i = 0; i < 240; i++) {
p.Cycle();
int x = p.X() % 40;
int coord = i % 40;
if (x >= coord - 1 && x <= coord + 1) {
cout << "█";
} else {
cout << " ";
}
if (i % 40 == 39) {
cout << endl;
}
}
}
int main() {
P1();
P2();
return 0;
}