r/adventofcode • • Dec 16 '16

SOLUTION MEGATHREAD --- 2016 Day 16 Solutions ---

--- Day 16: Dragon Checksum ---

Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag/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".


DRINKING YOUR OVALTINE IS MANDATORY [?]

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!

5 Upvotes

116 comments sorted by

View all comments

1

u/Scroph Dec 16 '16

C++. At first I wanted to be all clever and use std::bitset but after writing a few lines of code, I began to realize that it only made the code unnecessarily complex. String manipulation it is !

#include <iostream>
#include <algorithm>

const int disk_size = 35651584;

std::string generate_data(const std::string& input);
std::string generate_checksum(std::string input);
int main(void)
{
	std::string input = "11110010111001001";
	std::cout << input << std::endl;
	if(input.length() < disk_size)
		input = generate_data(input);
	std::cout << generate_checksum(input) << std::endl;
	return 0;
}

std::string generate_data(const std::string& input)
{
	std::string result = input;
	while(result.length() < disk_size)
	{
		std::string a = result;
		std::string b = result;
		std::reverse(b.begin(), b.end());
		std::transform(b.begin(), b.end(), b.begin(), [](char c) {return c == '1' ? '0' : '1';});
		result = a + "0" + b;
	}
	return result.substr(0, disk_size + 1);
}

std::string generate_checksum(std::string input)
{
	std::string result;
	while(true)
	{
		for(size_t i = 0; i < input.length() - 1; i += 2)
		{
			result += input[i] == input[i + 1] ? "1" : "0";
		}
		if(result.length() % 2 != 0)
			break;
		input = result;
		result = "";
	}
	return result;
}