Advertisement
sarumeister

AoC-2024 Day 7b -- single pass, no allocs

Dec 7th, 2024 (edited)
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.06 KB | Source Code | 0 0
  1. const std = @import("std");
  2. const Allocator = std.mem.Allocator;
  3.  
  4. const data = @embedFile("input0.txt");
  5.  
  6. // arena for ints
  7. var numsArr: [20]i64 = undefined;
  8. var numsCnt: u8 = 0;
  9. var testVal: i64 = 0;
  10. var cnt: i64 = 0;
  11.  
  12. fn recursiveOp(op: u8, len: u8, accum: i64) bool {
  13.     if (len == numsCnt) {
  14.         if (accum == testVal)
  15.             return true;
  16.         return false;
  17.     }
  18.  
  19.     var newval: i64 = undefined;
  20.     if (op == '+') {
  21.         newval = accum + numsArr[len];
  22.     }
  23.     if (op == '*') {
  24.         newval = accum * numsArr[len];
  25.     }
  26.  
  27.     if (op == '|') {
  28.         newval = accum;
  29.         var b = numsArr[len];
  30.         while (b > 0) {
  31.             newval *= 10;
  32.             b = @divTrunc(b, 10);
  33.         }
  34.         newval += numsArr[len];
  35.     }
  36.  
  37.     if (recursiveOp('+', len + 1, newval))
  38.         return true;
  39.  
  40.     if (recursiveOp('*', len + 1, newval))
  41.         return true;
  42.  
  43.     if (recursiveOp('|', len + 1, newval))
  44.         return true;
  45.  
  46.     return false;
  47. }
  48.  
  49. fn doProcessing() void {
  50.     const accum = numsArr[0];
  51.     if (recursiveOp('+', 1, accum)) {
  52.         cnt += testVal;
  53.         return;
  54.     }
  55.  
  56.     if (recursiveOp('*', 1, accum)) {
  57.         cnt += testVal;
  58.         return;
  59.     }
  60.  
  61.     if (recursiveOp('|', 1, accum)) {
  62.         cnt += testVal;
  63.         return;
  64.     }
  65. }
  66.  
  67. pub fn main() !void {
  68.     var currNum: i64 = 0;
  69.     for (data) |c| {
  70.         if (c == '\r')
  71.             continue;
  72.  
  73.         if (c == ':') {
  74.             testVal = currNum;
  75.             currNum = 0;
  76.             continue;
  77.         }
  78.  
  79.         if ((c == ' ') or (c == '\n')) {
  80.             if (0 == currNum)
  81.                 continue;
  82.  
  83.             numsArr[numsCnt] = currNum;
  84.             numsCnt += 1;
  85.             currNum = 0;
  86.             if (c == ' ')
  87.                 continue;
  88.         }
  89.         if (c == '\n') {
  90.             doProcessing();
  91.             currNum = 0;
  92.             numsCnt = 0;
  93.             continue;
  94.         }
  95.  
  96.         currNum *= 10;
  97.         currNum += c - '0';
  98.     }
  99.  
  100.     std.debug.print("Result: {d}.\n", .{cnt});
  101. }
  102.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement