func rule_exists[rules_left: Array, rules_right: Array, a: i64, b: i64] : bool for k in 0..rules_left->size if rules_left->nth(k) == a && rules_right->nth(k) == b return true return false func check[update: Array, rules_left: Array, rules_right: Array] : bool for i in 0..update->size for j in 0..i if rule_exists(rules_left, rules_right, update->nth(i), update->nth(j)) return false return true func sort_by_rules[update: Array, rules_left: Array, rules_right: Array] : void swapped := true while swapped swapped = false for i in 0..update->size-1 a : i64 = update->nth(i) b : i64 = update->nth(i+1) if rule_exists(rules_left, rules_right, b, a) tmp := a update->set(i, b) update->set(i+1, tmp) swapped = true func part1[updates: Array, rules_left: Array, rules_right: Array] : void out := 0 for i in 0..updates->size update : Array = updates->nth(i) if check(update, rules_left, rules_right) out += update->nth(update->size / 2) io.println_i64(out) func part2[updates: Array, rules_left: Array, rules_right: Array] : void out := 0 for i in 0..updates->size update : Array = updates->nth(i) if !check(update, rules_left, rules_right) sort_by_rules(update, rules_left, rules_right) out += update->nth(update->size / 2) io.println_i64(out) func main[] : i64 ~input, ok := io.read_text_file("input.txt") if !ok panic("failed to open input.txt") data := input->split("\n\n") rules_left := [] rules_right := [] rules_lines := (data->nth(0) as str)->split("\n") for i in 0..rules_lines->size line : str = rules_lines->nth(i) parts := line->split("|") rules_left->push((parts->nth(0) as str)->parse_i64()) rules_right->push((parts->nth(1) as str)->parse_i64()) updates := [] updates_lines := (data->nth(1) as str)->split("\n") for i in 0..updates_lines->size line : str = updates_lines->nth(i) xs := line->split(",") for i in 0..xs->size xs->set(i, (xs->nth(i) as str)->parse_i64()) updates->push(xs) part1(updates, rules_left, rules_right) part2(updates, rules_left, rules_right)