Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <sstream>
- #include <iostream>
- #include <fstream>
- const unsigned int MAX_LAYERS = 100;
- // https://pastebin.com/bNAaTL1e
- void updateLayer(unsigned int * layer) {
- unsigned int range = layer[0];
- unsigned int position = layer[1];
- unsigned int direction = layer[2];
- if(direction == 0) {
- // down v
- if(position == range - 1) {
- layer[1] = range - 2;
- layer[2] = 1; // change direction to up
- }else {
- layer[1]++;
- }
- }else {
- // up ^
- if(position == 0) {
- layer[1] = 1; // second position
- layer[2] = 0; // go down
- }else {
- layer[1]--;
- }
- }
- }
- int main(int argc, char ** argv) {
- std::ifstream inputFile("input.txt");
- unsigned int ** layers = new unsigned int * [MAX_LAYERS];
- unsigned int ** delayState = new unsigned int * [MAX_LAYERS];
- for(unsigned int i = 0; i < MAX_LAYERS; i++) {
- layers[i] = new unsigned int[3];
- layers[i][0] = 0; // range
- layers[i][1] = 0; // current scanner position
- layers[i][2] = 0; // current scanner direction (0 down, 1 up)
- delayState[i] = new unsigned int[3];
- delayState[i][0] = 0; // range
- delayState[i][1] = 0; // current scanner position
- delayState[i][2] = 0; // current scanner direction (0 down, 1 up)
- }
- if(!inputFile.is_open()) {
- std::cout << "Could not read file." << std::endl;
- return 1;
- }
- std::string line;
- while(std::getline(inputFile, line)) {
- std::stringstream ss(line);
- unsigned int source = 0;
- unsigned int range = 0;
- ss >> source;
- ss.ignore(1, ':');
- ss.ignore(1);
- ss >> range;
- layers[source][0] = range;
- delayState[source][0] = range;
- }
- unsigned int delay = 0;
- while(true) {
- // Reset layers to next delay state:
- for(unsigned int i = 0; i < MAX_LAYERS; i++) {
- layers[i][1] = delayState[i][1]; // current scanner position
- layers[i][2] = delayState[i][2]; // direction
- }
- // Look for crashes:
- bool crash = false;
- for(unsigned int depth = 0; depth < MAX_LAYERS; depth++) {
- unsigned int * currentLayer = layers[depth];
- if(currentLayer[0] > 0 && currentLayer[1] == 0) {
- crash = true;
- break;
- }
- // Update all layers from current depth onward:
- for(unsigned int i = depth; i < MAX_LAYERS; i++) {
- updateLayer(layers[i]);
- }
- }
- if(!crash) {
- break;
- }
- // Next delay state simulation
- for(unsigned int i = 0; i < MAX_LAYERS; i++) {
- updateLayer(delayState[i]);
- }
- delay++;
- }
- std::cout << "Delay: " << delay << std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement