Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #include <vector>
- class IntCode
- {
- private:
- std::vector<int> memory{};
- enum Opcode {
- ADD = 1,
- MUL = 2,
- INP = 3,
- OUT = 4,
- HALT = 99
- };
- class ModesList
- {
- private:
- std::vector<bool> modes{};
- public:
- void push_back(bool val) { modes.push_back(val); }
- bool operator[](size_t idx)
- {
- if (idx >= modes.size())
- return 0;
- return modes[idx];
- }
- };
- struct ModedOp
- {
- int opcode;
- ModesList modes;
- };
- ModedOp toModedOp(int val)
- {
- int opcode = val % 100;
- ModesList modes{};
- val -= opcode;
- for (int i = 1000; val != 0; i *= 10)
- {
- int nMode = val % i;
- modes.push_back(nMode);
- val -= nMode;
- }
- return { opcode, modes };
- }
- int& addr(int loc) { return memory[memory[loc]]; }
- int read(int val, bool mode) { return (mode) ? memory[val] : addr(val); }
- public:
- IntCode() {}
- IntCode(std::vector<int> intCode) : memory(intCode) {}
- int& operator[](int loc) { return memory[loc]; }
- std::vector<int> run(const std::vector<int>& input)
- {
- int inputPtr = 0;
- std::vector<int> out{};
- for (int ptr = 0; memory[ptr] != HALT;)
- {
- ModedOp mop = toModedOp(memory[ptr]);
- switch (mop.opcode)
- {
- case ADD:
- addr(ptr + 3) = read(ptr + 1, mop.modes[0]) + read(ptr + 2, mop.modes[1]);
- ptr += 4;
- break;
- case MUL:
- addr(ptr + 3) = read(ptr + 1, mop.modes[0]) * read(ptr + 2, mop.modes[1]);
- ptr += 4;
- break;
- case INP:
- addr(ptr + 1) = input[inputPtr++];
- ptr += 2;
- break;
- case OUT:
- out.push_back(addr(ptr + 1));
- ptr += 2;
- break;
- }
- }
- return out;
- }
- void readFrom(const std::string& fileName)
- {
- std::ifstream inf(fileName);
- int temp{};
- while (inf >> temp)
- {
- memory.push_back(temp);
- inf.ignore(2, ',');
- }
- }
- };
- void part1()
- {
- IntCode code;
- code.readFrom("input.txt");
- auto out = code.run({1});
- for (auto val : out)
- std::cout << val << " ";
- // 3 0 0 0 0 0 0 0 0 9219874
- }
- void part2()
- {
- }
- int main()
- {
- part1();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement