Day 8, Part 2

This commit is contained in:
Correl Roush 2015-12-15 13:28:02 -05:00
parent 308d83c0f4
commit ff6e5d2ad4

View file

@ -4108,3 +4108,59 @@ number of characters in memory for string values =(0 + 3 + 7 + 1 =
#+RESULTS[acaa7a9432ace3b411d0bfcd4c61620b43ce21c5]: #+RESULTS[acaa7a9432ace3b411d0bfcd4c61620b43ce21c5]:
: 1350 : 1350
** Part 2
Now, let's go the other way. In addition to finding the number of
characters of code, you should now *encode each code representation as
a new string* and find the number of characters of the new encoded
representation, including the surrounding double quotes.
For example:
- =""= encodes to ="\"\""=, an increase from =2= characters to =6=.
- ="abc"= encodes to ="\"abc\""=, an increase from =5= characters to
=9=.
- ="aaa\"aaa"= encodes to ="\"aaa\\\"aaa\""=, an increase from =10=
characters to =16=.
- ="\x27"= encodes to ="\"\\x27\""=, an increase from =6= characters
to =11=.
Your task is to find *the total number of characters to represent the
newly encoded strings* minus *the number of characters of code in each
original string literal*. For example, for the strings above, the
total encoded length (=6 + 9 + 16 + 11 = 42=) minus the characters in
the original code representation (=23=, just like in the first part of
this puzzle) is =42 - 23 = 19=.
----------------------------------------------------------------------
#+BEGIN_SRC emacs-lisp :var input=8-input :exports both
(defun day8/encode-string (string-literal)
(format "\"%s\""
(-reduce-from
(lambda (acc replacement)
(s-replace (car replacement)
(cdr replacement)
acc))
string-literal
'(("\\" . "\\\\")
("\"" . "\\\"")))))
(ert-deftest day8/encode-string ()
(should (string-equal "\"\\\"\\\"\""
(day8/encode-string "\"\"")))
(should (string-equal "\"\\\"abc\\\"\""
(day8/encode-string "\"abc\"")))
(should (string-equal "\"\\\"aaa\\\\\\\"aaa\\\"\""
(day8/encode-string "\"aaa\\\"aaa\"")))
(should (string-equal "\"\\\"\\\\x27\\\"\""
(day8/encode-string "\"\\x27\""))))
(let* ((code-strings (split-string input "\n" t))
(encoded-values (-map #'day8/encode-string code-strings)))
(- (-sum (-map #'length encoded-values))
(-sum (-map #'length code-strings))))
#+END_SRC
#+RESULTS[bb50e3c25f6d0d1247acdefae2e5c755c90fe7a7]:
: 2085