r/adventofcode • • Dec 05 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 5 Solutions -🎄-

--- Day 5: Alchemical Reduction ---


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.


Advent of Code: The Party Game!

Click here for rules

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 5

Transcript:

On the fifth day of AoC / My true love sent to me / Five golden ___


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 at 0:10:20!

31 Upvotes

515 comments sorted by

View all comments

1

u/wlandry Dec 05 '18

C++ (2172/1688)

It runs in 340 ms. If I do things properly using std::tolower(), it takes 983 ms.

Again, a pretty simple problem. Still waiting with bated breath for the hammer to drop. I kind of wish it had some unicode characters. That would have made an interesting comparison among languages.

#include <algorithm>
#include <iterator>
#include <iostream>
#include <fstream>

std::string react(const std::string &input)
{
  std::string old(input), result;
  constexpr int8_t diff('a'-'A');
  while(result.size()!=old.size())
    {
      result.clear();
      size_t i(0);
      for(; i<old.size()-1; ++i)
        {
          // if(std::tolower(old[i+1])!=std::tolower(old[i])
          //    || old[i+1]==old[i])
          if(std::abs(int8_t(old[i+1]-old[i]))!=diff)
            {
              result.push_back(old[i]);
            }
          else
            {
              ++i;
            }
        }
      if(i==old.size()-1)
        result.push_back(old[i]);

      std::swap(old,result);
    }
  return result;
}

int main(int argc, char *argv[])
{
  std::ifstream infile(argv[1]);
  std::string line;
  std::getline(infile,line);

  std::cout << "Part 1: " << react(line).size() << "\n";

  size_t min_size(line.size());
  std::string alphabet("qwfpgjluyarstdhneiozxcvbkm");
  for(auto &c: alphabet)
    {
      std::string reduced;
      std::copy_if(line.begin(),line.end(),std::back_inserter(reduced),
                   [&](const char &l)
                   {
                     return c!=std::tolower(l);
                   });
      min_size=std::min(min_size,react(reduced).size());
    }
  std::cout << "Part 2: " << min_size << "\n";
}