Advertisement
Guest User

AoC #4 (Welltype)

a guest
Dec 4th, 2016
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.62 KB | None | 0 0
  1. declare
  2. {
  3.     record Name
  4.     {
  5.         string name;
  6.         int id;
  7.         string cksum;
  8.     }
  9.  
  10.     record State
  11.     {
  12.         seq<Name> reals;
  13.     }
  14. }
  15.  
  16. function parse(string ln) : Name
  17. {
  18.     Name n;
  19.  
  20.     seq<string> toks = strtok(ln, "[]");
  21.     n.cksum = toks[1u];
  22.     uint pos = strrchr(toks[0u], '-');
  23.     n.name = substr(toks[0u], 0u, pos);
  24.     n.id = toi32(substr(toks[0u], pos+1u, strlen(toks[0u])));
  25.  
  26.     return n;
  27. }
  28.  
  29. function cksum(Name n) : string
  30. {
  31.     seq<uint> ap = seqfill(0u, 26u);
  32.     uint m = 0u;
  33.  
  34.     foreach(ch in n.name which '-'!=ch)
  35.     {
  36.         uint idx = tou32(ch - 'a');
  37.         ap[idx] = ap[idx] + 1u;
  38.         if(m<ap[idx]) { m = ap[idx]; }
  39.     }
  40.  
  41.     string s;
  42.  
  43.     foreach(cnt in 1u .. m reverse)
  44.     {
  45.         foreach(idx in 0u .. seqlen(ap) exclusive which ap[idx]==cnt)
  46.         {
  47.             s = s + tos('a' + idx);
  48.  
  49.             if(strlen(s)==5u)
  50.             {
  51.                 return s;
  52.             }
  53.         }
  54.     }
  55.  
  56.     return s;
  57. }
  58.  
  59. function decrypt(Name n) : string
  60. {
  61.     int rot = n.id % 26;
  62.     string s = n.name;
  63.  
  64.     foreach(i in 0u .. strlen(s) exclusive)
  65.     {
  66.         if('-'!=s[i])
  67.         {
  68.             int offs = s[i] - 'a';
  69.             s[i] = 'a' + ((offs + rot) % 26);
  70.         }
  71.         else
  72.         {
  73.             s[i] = ' ';
  74.         }
  75.     }
  76.  
  77.     return s;
  78. }
  79.  
  80. impure function part1(mutable State s)
  81. {
  82.     file f = fopen("input", 'r');
  83.     string ln;
  84.  
  85.     for(ln=freadln(f);!empty(ln);ln=freadln(f))
  86.     {
  87.         Name n = parse(ln);
  88.  
  89.         if(n.cksum==cksum(n))
  90.         {
  91.             s.reals = hiext(s.reals, n);
  92.         }
  93.     }
  94. }
  95.  
  96. main
  97. {
  98.     State s;
  99.     part1(s);
  100.  
  101.     int sum = 0;
  102.     foreach(n in s.reals) { sum = sum + n.id; }
  103.     write(tos(sum) + "\n");
  104.  
  105.     // part2
  106.  
  107.     foreach(n in s.reals)
  108.     {
  109.         string d = decrypt(n);
  110.  
  111.         if(strstr(d, "north")<strlen(d))
  112.         {
  113.             write(d + ": " + tos(n.id) + "\n");
  114.         }
  115.     }
  116. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement