Unable to load image

Day 21 AoC: use Z3 b-words

Post code, boast about it.

13
Jump in the discussion.

No email address required.

const input = fs.readFileSync(process.argv[2], 'utf-8').trim();
const part2 = Number(process.argv[3]) === 2;

type str = string;
class Node {
  static nodes: {[key:str]:Node} = {};
  name:str = '';
  val?:number;
  op?:str;
  pDeps?:Node[];
  cDeps?:Node[];
  constructor(name:str) {
    this.name=name;
    Node.nodes[name] = this;
  };
}
const todo:Node[] = [];
const getParentNode = (pName:str, n:Node): Node => {
  const p = Node.nodes[pName] || new Node(pName);
  (p.cDeps ??= []).push(n);
  return p;
}

input.split('\n')
  .forEach(l => {
    const [name, valStr] = l.split(': ');
    const n = Node.nodes[name] || new Node(name);

    if (part2 && name === 'humn') return;

    const valM = valStr.match(/\S+/g) || [];
    const num = valM?.length === 1 ? Number(valStr) : false;
    if (num) { 
      n.val = num;
      todo.push(n);
    }
    const [p0, op, p1] = valM;
    if (p0 && op && p1) {
      n.op = op;
      n.pDeps = [getParentNode(p0, n), getParentNode(p1, n)];
    }
  });

let n: Node|undefined;
while(n = todo.shift()) {
  if (part2 && n.name === 'root') continue;
  if(!n.val && n.op) {
    const [val1, val2] = n.pDeps?.map(p => p.val!) || [];
    n.val
      = n.op === '*' ? val1 * val2
      : n.op === '+' ? val1 + val2
      : n.op === '-' ? val1 - val2
      : n.op === '/' ? val1 / val2
      : undefined;
  }
  n.cDeps?.forEach(c => {
    if (c.pDeps?.
      reduce((p, cp) => p && !!cp.val, true)) {
      toDo.push(c);
    }
  });
}

if (part2) {
  todo.push(Node.nodes['root']);
  while (n = todo.shift()) {
    if (n.name === 'humn') break;

    const [p0, p1] = n.pDeps || [];
    if (!p0.val && p1.val) {
      todo.push(p0);
      p0.val
        = n.name === 'root' ? p1.val
        : n.op === '*' ? n.val! / p1.val
        : n.op === '+' ? n.val! - p1.val
        : n.op === '-' ? n.val! + p1.val
        : n.op === '/' ? n.val! * p1.val
        : undefined
    } else if (!p1.val && p0.val) {
      todo.push(p1)
      p1.val
        = n.name === 'root' ? p0.val
        : n.op === '*' ? n.val! / p0.val
        : n.op === '+' ? n.val! - p0.val
        : n.op === '-' ? p0.val - n.val!
        : n.op === '/' ? p0.val / n.val!
        : undefined
    } else {
      throw new Error(`Invalid state n:${n.val} p0:${p0.val} p1:${p1.val}`);
    }
  }

  console.log(Node.nodes['humn'].val);
} else {
  console.log(Node.nodes['root'].val);
}
Jump in the discussion.

No email address required.

😴😴😴

Jump in the discussion.

No email address required.

:#chadcopecapy::#chadsneedcapy:

Jump in the discussion.

No email address required.



Now playing: King K. Rool Returns (DKC2).mp3

Link copied to clipboard
Action successful!
Error, please refresh the page and try again.