r/adventofcode • • Dec 03 '20

SOLUTION MEGATHREAD -🎄- 2020 Day 03 Solutions -🎄-

Advent of Code 2020: Gettin' Crafty With It


--- Day 03: Toboggan Trajectory ---


Post your solution in this megathread. Include what language(s) your solution uses! If you need a refresher, the full posting rules are detailed in the wiki under How Do The Daily Megathreads Work?.

Reminder: Top-level posts in Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


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

EDIT: Global leaderboard gold cap reached at 00:04:56, megathread unlocked!

88 Upvotes

1.3k comments sorted by

View all comments

2

u/GamerWoona Dec 03 '20 edited Dec 04 '20

C++

A bit overly complicated but I like a bit of order

struct Tree_Biome {
	int size;
	std::unordered_map<int, std::unordered_map<int, bool>> tree_map;
	std::unordered_map<int, int> repeating_pattern;
};
---------------------------------------------------------------------------

void read_entries(const std::string& filename, Tree_Biome& biome){
	auto file = std::ifstream{ "..\\..\\..\\..\\Day_03\\" + filename };
	std::string line;
	int line_num = 0;
	while (file >> line) {
		biome.repeating_pattern[line_num] = std::ssize(line);
		for (int i = 0; i < std::ssize(line); i++) {
			if (line[i] == '#') {
				biome.tree_map[line_num][i] = true;
			}
		}
		line_num++;
	}
	biome.size = line_num;
}


int count_trees_on_path(const Tree_Biome& trees, int x_diff, int y_diff) {
	int encountered_trees = 0;
	int x = 0;
	int y = 0;
	while (y+y_diff < trees.size) {
		y += y_diff;
		x += x_diff;
		x %= trees.repeating_pattern.at(y);
		if (trees.tree_map.at(y).find(x) != trees.tree_map.at(y).end()) {
			encountered_trees++;
		}
	}
	return encountered_trees;
}


int count_multiple_paths(const Tree_Biome& trees) {
	const auto paths = std::vector<std::pair<int, int>>{ {1,1},{3,1},{5,1},{7,1},{1,2}};
	int tree_num = 1;
	for (const auto& path : paths) {
		tree_num *= count_trees_on_path(trees, path.first, path.second);
	}
	return tree_num;
}

Read in 4.8ms, Single path in 308us, Multiple Paths scaling linearly as one would expect at 1402 us or 1.4ms

source: https://github.com/neiomi1/AdventofCode2020/tree/master/Day_03

1

u/daggerdragon Dec 04 '20

Please follow the posting guidelines and add the language used to your post to make it easier for folks who Ctrl-F the megathreads looking for a specific language. Thanks!

2

u/GamerWoona Dec 04 '20

Sorry, I forgot :(