r/adventofcode • • Dec 09 '15

SOLUTION MEGATHREAD --- Day 9 Solutions ---

This thread will be unlocked when there are a significant amount of people on the leaderboard with gold stars.

edit: Leaderboard capped, achievement thread unlocked!

We know we can't control people posting solutions elsewhere and trying to exploit the leaderboard, but this way we can try to reduce the leaderboard gaming from the official subreddit.

Please and thank you, and much appreciated!


--- Day 9: All in a Single Night ---

Post your solution as a comment. Structure your post like previous daily solution threads.

10 Upvotes

178 comments sorted by

View all comments

Show parent comment

1

u/willkill07 Dec 09 '15

Here's another C++ / C++11 / C++14 implementation:

I don't keep track of the paths at all. Just an overall min/max. I also avoid the need to do the (b,a) lookup by exploiting std::minmax to give them to me in the proper order I inserted them.

https://github.com/willkill07/adventofcode/blob/master/src/day9/day9.cpp

#include <iostream>
#include <limits>
#include <map>
#include <numeric>
#include <set>
#include <string>
#include <vector>
#include "timer.hpp"

using City = std::string;
using Road = std::pair <City, City>;
using FnType = int const & (*)(int const &, int const &);

int main (int argc, char* argv[]) {
  bool part2 { argc == 2 };
  std::map <Road, int> dist;
  std::set <City> p;
  City c1, c2, junk;
  int val;
  while (std::cin >> c1 >> junk >> c2 >> junk >> val) {
    p.insert (c1);
    p.insert (c2);
    dist.emplace (std::minmax (c1, c2), val);
  }
  std::vector <City> order { std::begin (p), std::end (p) };
  int d { part2 ? 0 : std::numeric_limits <int>::max() };
  FnType f { part2 ? (FnType)std::max <int> : (FnType)std::min <int> };
  do {
    auto prev = std::begin (order);
    d = f (d, std::accumulate (prev + 1, std::end (order), 0, [&] (int sum, const City & a) {
      return sum + dist.at (std::minmax (a, *(prev++)));
    }));
  } while (std::next_permutation (std::begin (order), std::end (order)));
  std::cout << d << std::endl;
  return 0;
}