Day 2: Fulminating Farmland
Megathread guidelines
- Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
- You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL
FAQ
- What is this?: Here is a post with a large amount of details: https://programming.dev/post/6637268
- Where do I participate?: https://adventofcode.com/
- Is there a leaderboard for the community?: We have a programming.dev leaderboard with the info on how to join in this post: https://programming.dev/post/6631465


C++
Part 1 is trivial, part 2 is ‘can you do a slightly odd sorting of the input’. 50 microseconds.
const auto rainbow = std::string{"roygbv"}; const auto longest = std::string{"rvbgyo"}; auto part1(const std::string& input) { auto distance = size_t{}; auto offset = size_t{}; for (auto c : input) do { offset = (offset + 1) % rainbow.size(); ++distance; } while (rainbow.at(offset) != c); return distance; } auto part2(const std::string& input) { auto counts = boost::unordered_flat_map<char, size_t>{}; for (auto c : input) ++counts[c]; auto solution = std::string{}; for (auto c : longest) solution.insert(solution.size(), counts[c], c); return part1(solution); }I am not complaining, but it’s kinda peculiar that we got 2 “Counting HashMap + sorting” problems in a row :)
definitely weird, maybe we are being softened up so he can completely crush our spirit later
That’s actually hella clever, now I feel dump for doing it iteratively.
I understand the logic behind your part 2, how you’d always end up with groups of repeated letters, going backwards, but I’m confused by your statement “slightly odd sorting of the input”. What does this have to do with sorting?
Hey! Thanks.
By ‘odd sorting’, I mean that you want to sort the input in the order
rvbgyo. So in the example given in the question itself,vrvbvg->rvvvbg. Thinking about it, you could do it like this as well:std::sort(input.begin(), input.end(), [](auto a, auto b) { return "find position of a in longest" < "find position of b in longest"; });…which would make it more obvious that it’s a sort. Probably implement the position finding as a hashmap, character -> position. My part2 solution regenerates the string using a bucket count in the desired order, but there’s other ways to do it.
Iterating on your solution in crystal (should be readable even if you’re not familiar with crystal), I’ve found an even cleaner solution, that requires no passing back to part 1, nor any string construction:
def find_longest(input : Array(Char)) last = input.max_of { |c| "rvbgyo".index!(c) } # assumes non-empty input of only roygbv letters 6 * input.size - last endruns in about 10us, excluding io, though it’s possible to get it under 1us by skipping the
indexcall andArray(Char)allocation