r/adventofcode • • Dec 13 '17

SOLUTION MEGATHREAD -๐ŸŽ„- 2017 Day 13 Solutions -๐ŸŽ„-

--- Day 13: Packet Scanners ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Need a hint from the Hugely* Handyโ€  Haversackโ€ก of Helpfulยง Hintsยค?

Spoiler


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!

15 Upvotes

199 comments sorted by

View all comments

0

u/wlandry Dec 13 '17

C++ 14

710/322. I guess people found the second part harder than the first. This required some thinking to navigate around off-by-one errors. With my inputs on my machine, the program completed in 1.7 seconds. This version is for part 2. Part 1 is commented out.

#include <fstream>
#include <vector>
#include <iostream>

int main(int argc, char *argv[])
{
  std::ifstream infile(argv[1]);
  std::vector<int> ranges;
  int layer;
  infile >> layer;
  while(infile)
    {
      int range;
      infile.get();
      infile >> range;
      if(ranges.size()<=layer)
        { ranges.resize(layer+1); }
      ranges[layer]=range;
      infile >> layer;
    }

  std::vector<int> state(ranges.size());
  int offset (0);
  bool caught (true);
  for(; caught; ++offset)
    {
      // int severity=0;
      caught=false;
      for(size_t t=0; t<ranges.size(); ++t)
        {
          bool caught_here (ranges[t]!=0 && (t+offset)%(2*ranges[t] - 2)==0);
          caught=caught || caught_here;
          // if(caught_here)
          //   { severity+=ranges[t]*t; }
        }
      // std::cout << "offset: " << offset << " " << std::boolalpha
      //           << caught << " "
      //           << severity << "\n";
    }
  std::cout << offset << "\n";
}

2

u/joker_mkd Dec 13 '17
  if(ranges.size()<=layer)
    { ranges.resize(layer+1); }
  ranges[layer]=range;

Why are you using a vector and resizing it, wasting so much space, instead of just using a map?

2

u/wlandry Dec 13 '17

It uses less space than a map. The filling factor is about 50%. So a vector uses O(2N) elements. A map, on the other hand, has to store the key, the value, and parent-child information. So a map uses about O(2N + logN). Also, lookups for vector's is O(1), while for a map it is O(logN).

1

u/wlandry Dec 13 '17

Forcing an early return by changing the second for loop to

for(size_t t=0; t<ranges.size() && !caught; ++t)

reduced the run time to 0.1 seconds.