There’s Always Room For Improvement (a clearer solution to AoC Day 10)
Published in
2 min readJan 6, 2016
In A Real-World(ish) Example of Great Developers Being Infinitely Better I gave a solution to the tenth day problem of the very entertaining Advent of Code (hat tip to @ericwastl), which involves transforming strings per the Look and Say Sequence. The solution works backward and scales with efficiency O(n) — linearly. But it isn’t the clearest algorithm, not by a long shot.
After thinking about it some more (part of trying to be a better developer is never being satisfied) I realized that it is possible to work forward. It just requires holding off on the actual length calculation until the end. Here is code that does that:
local transformArray
local lengthArrayon mouseUp
initTransformArray
put startArray() into E
repeat iterationCount()
put seeAndSay(E) into E
end repeat
put lengthOfArray(E)
end mouseUpon initTransformArray
-- sets up the seeAndSay transform if necessary
if the keys of transformArray is not empty
then exit initTransformArray
repeat for each line L in fld 5
repeat for each item i in word 2 of L
add 1 to transformArray[word 1 of L][i]
end repeat
end repeat
end initTransformArrayfunction seeAndSay E
-- returns seeAndSay algo applied to E
repeat for each key K in E
repeat for each key K2 in transformArray[K]
repeat transformArray[K][K2]
put bAdd(E[K],R[K2]) into R[K2]
end repeat
end repeat
end repeat
return R
end seeAndSayfunction lengthOfArray E
-- returns the char length of an array E
-- E contains the count of each indexed element
if the keys of lengthArray is empty then
put fld 7 into F
split F using cr and tab
end if
put 0 into R
repeat for each key K in E
put bAdd(bTimes(E[K],F[K]),R) into R
end repeat
return R
end lengthOfArray