r/adventofcode • • Dec 10 '15

SOLUTION MEGATHREAD --- Day 10 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 10: Elves Look, Elves Say ---

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

11 Upvotes

212 comments sorted by

View all comments

1

u/FuriousProgrammer Dec 10 '15 edited Dec 10 '15

Uh, I can't submit my solution to part 1? Says I'm trying to POST too much data...

I cannot believe that I missed that highlighted text at the end. Holy. Shit.

Lua:

inpt = "1321131112"

function oneSay()
	local out = ""
	local last = nil
	local total = 0

	for i = 1, #inpt do
		c = inpt:sub(i,i)
		if not last then last = c end
		if c == last then
			total = total + 1
		else
			out = out .. total .. last
			last = c
			total = 1;
		end
	end
	out = out .. total .. last

	inpt = out
end
for i = 1, 50 do
    oneSay()
    if i == 40 then
	    print("\nPart 1: " .. inpt:len())
    end
end
print("\nPart 2: " .. inpt:len())

1

u/FuriousProgrammer Dec 10 '15 edited Dec 10 '15

Well, how about that. Treating Lua Tables as C Strings instead of using actual Lua strings gives me a total run time of 15.3 seconds to calculate 50 of these. 7.4 with LuaJIT optimizations. <.>

require("socket") -- for gettime
ins = "1321131112"

local inpt = {}
for i = 1, #ins do
	table.insert(inpt, ins:sub(i,i))
end

function oneSay()
	local last = nil
	local count = 0
	inpt.next = {}
	for i = 1, #inpt do
		if not last then last = inpt[i] end
		if inpt[i] == last then
			count = count + 1
		else
			table.insert(inpt.next, tostring(count))
			table.insert(inpt.next, last)
			count = 1
			last = inpt[i]
		end
	end
	table.insert(inpt.next, tostring(count))
	table.insert(inpt.next, last)
	inpt = inpt.next
end

local st = socket.gettime()*1000
for i = 1, 50 do
	oneSay()
	if i == 40 then
		print("Part 1: ", #inpt)
	end
end
print("Part 2: ", #inpt)
print(socket.gettime()*1000 - st .. " ms")

1

u/spc476 Dec 11 '15

I used LPeg to solve this one:

local lpeg = require "lpeg"

local function expand(c)
  return string.format("%d%s",#c,c:sub(1,1))
end
   
local num  = lpeg.P(false)

for i = 0 , 9 do
  num = num + lpeg.P(tostring(i))^1 / expand
end
   
local nums = lpeg.Cs(num^1)
local res  = "1113122113"  

for i = 1 , 40 do
  res = nums:match(res)
end

print(#res)

On my system, going up to 40 took 1.7s, and 50 took 24.5s.

1

u/FuriousProgrammer Dec 11 '15

If you look at my other comment, using Tables as C Strings is almost twice as fast as even that, assuming you're not using LuaJIT.