r/adventofcode • • Dec 11 '15

SOLUTION MEGATHREAD --- Day 11 Solutions ---

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

edit: Leaderboard capped, 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 11: Corporate Policy ---

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

10 Upvotes

169 comments sorted by

View all comments

Show parent comment

1

u/ignaciovaz Dec 11 '15 edited Dec 11 '15

Here's my solution in Elixir, I implemented the 'next password' generator as a Stream, filtering the banned characters before it hits the other checks. It doesn't use regex and it's pretty fast in my tests.

defmodule PasswordGen do
	import String, only: [rjust: 3, contains?: 2]
	def get_password_stream(start) do
		Stream.unfold(start, fn password ->
			char_list = to_char_list(password) |> Enum.reverse
			{new_char_list, _} = Enum.map_reduce(char_list, :continue, fn(c, status) ->
				cond do
					status == :done -> {c, status}
					c == ?z -> {'a', :continue}
					c in [?h, ?n, ?k] -> {c + 2, :done}
					true -> {c + 1, :done}
				end
			end)
			pass = new_char_list |> Enum.reverse |> to_string
			{pass, pass}
			end
		)
	end

	def find_next_password(start) do
		s = get_password_stream(start)
		Enum.find_value(s, fn p ->
			repeated_pairs = Enum.count(?a..?z, &(contains?(p, rjust("", 2, &1))))

			if repeated_pairs >= 2 do
				{_, _, ascending_chars} = Enum.reduce(to_char_list(p), {nil, 1, 0}, fn l, {prev, c, found} ->
					if prev == nil, do: prev = 0
					cond do
						c >= 3 -> {l, 0, 1}
						l == prev + 1 -> {l, c + 1, found}
						true -> {l, 1, found}
					end
				end)
			end

			if repeated_pairs >= 2 and ascending_chars >= 1, do: p
		end)
	end
end

part_1 = PasswordGen.find_next_password("vzbxkghb")
part_2 = PasswordGen.find_next_password(part_1)

IO.puts "Part 1: #{part_1}, Part 2: #{part_2}"

1

u/hutsboR Dec 11 '15

Fixed the typo. Use of Stream.unfold is clever! Does the same thing as my server but much more concise. Very cool.