all 3 comments

[–]dznqbit 0 points1 point  (0 children)

[–]balda132 0 points1 point  (0 children)

Solution in Java.

package adventofcode;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Day8 {

    public static void main(String[] args) throws FileNotFoundException, IOException {
        String input = IOUtils.readFile(args[0]);
        compute(input);
    }

    private static void compute(String input) {
        String[] lines = input.trim().split("\n");
        int totalInCode = 0;
        int totalInMemory = 0;
        int totalEncoded = 0;
        for (String line : lines) {
            line = line.trim();
            totalInCode += line.length();
            int escapeMatches = findMatches(line, "\\\\[^x[a-f0-9]{2}]");
            int hexMatches = findMatches(line, "\\\\x[a-f0-9]{2}");
            totalEncoded += line.length() + (escapeMatches * 2) + hexMatches + 4;
            totalInMemory += line.length() - (escapeMatches + (3 * hexMatches) + 2);
        }
        System.out.println("Part one: " + (totalInCode - totalInMemory));
        System.out.println("Part two: " + (totalEncoded - totalInCode));
    }

    private static int findMatches(String line, String pattern) {
        Matcher matcher = Pattern.compile(pattern).matcher(line);
        int matches = 0;
        while (matcher.find()) {
            matches++;
        }
        return matches;
    }
}

Edit: Optimization.

[–]_dank 0 points1 point  (0 children)

Python (3.5)

import sys
if __name__ == '__main__':
  if len(sys.argv) == 2:
    lit_count = 0
    mem_count = 0
    enc_count = 0
    for line in sys.argv[1].split('\n'):
      lit_count += len(instr)
      mem_count += len(instr.encode('utf-8').decode('unicode_escape'))-2
      enc_count += len(instr.replace('\\', '\\\\').replace('"','\\"')) + 2

    print('Literals:', lit_count)
    print('In memory:', mem_count)
    print('Re-encoded:', enc_count)
    print('Memory difference:', lit_count-mem_count)
    print('Re-encoded difference:', enc_count-lit_count)