Guest User

AoC #2 (Welltype)

a guest
Dec 2nd, 2016
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.28 KB | None | 0 0
  1. declare
  2. {
  3.     record State
  4.     {
  5.         seq<string> lo;
  6.         uint x;
  7.         uint y;
  8.         string code;
  9.     }
  10. }
  11.  
  12. function is_valid(State s, uint nx, uint ny) : bool
  13. {
  14.     if(ny>=seqlen(s.lo)) { return false; }
  15.     if(nx>=strlen(s.lo[ny])) { return false; }
  16.     return ' ' != s.lo[ny][nx];
  17. }
  18.  
  19. function step(mutable State s, char ch)
  20. {
  21.     uint nx, ny = s.x, s.y;
  22.  
  23.     if('R'==ch)
  24.     {
  25.         nx = nx + 1u;
  26.     }
  27.     elif('L'==ch)
  28.     {
  29.         nx = nx - 1u;
  30.     }
  31.     elif('D'==ch)
  32.     {
  33.         ny = ny + 1u;
  34.     }
  35.     elif('U'==ch)
  36.     {
  37.         ny = ny - 1u;
  38.     }
  39.  
  40.     if(is_valid(s, nx, ny))
  41.     {
  42.         s.x, s.y = nx, ny;
  43.     }
  44. }
  45.  
  46. function append(mutable State s)
  47. {
  48.     s.code = s.code + tos(s.lo[s.y][s.x]);
  49. }
  50.  
  51. impure function part_1_and_2(mutable State s1, mutable State s2)
  52. {
  53.     file f = fopen("input", 'r');
  54.     string ln;
  55.  
  56.     for(ln=freadln(f);!empty(ln);ln=freadln(f))
  57.     {
  58.         foreach(ch in ln)
  59.         {
  60.             step(s1, ch);
  61.             step(s2, ch);
  62.         }
  63.  
  64.         append(s1);
  65.         append(s2);
  66.     }
  67.  
  68.     exception(IOException)
  69.     {
  70.         // skip
  71.     }
  72. }
  73.  
  74. main
  75. {
  76.     State s1 = State
  77.     {
  78.         .x = 1u;
  79.         .y = 1u;
  80.         .lo = seq
  81.         {
  82.             "123",
  83.             "456",
  84.             "789"
  85.         };
  86.     };
  87.  
  88.     State s2 = State
  89.     {
  90.         .x = 0u;
  91.         .y = 2u;
  92.         .lo = seq
  93.         {
  94.             "  1  ",
  95.             " 234 ",
  96.             "56789",
  97.             " ABC ",
  98.             "  D  "
  99.         };
  100.     };
  101.  
  102.     part_1_and_2(s1, s2);
  103.  
  104.     write(s1.code + "\n");
  105.     write(s2.code + "\n");
  106. }
Advertisement
Add Comment
Please, Sign In to add comment