Valid Codes: 14
Added: 355 Removed: 174
package main
import (
"fmt"
"os"
"log"
"strings"
"regexp"
)
func main() {
content, err := os.ReadFile("../days/03/assembly_codes.txt")
if err != nil {
log.Fatalf("Failed to open file: %w", err)
}
validNum := 0
codes := strings.Split(string(content), "\n")
re, err := regexp.Compile("^[AR]*CP$")
if err != nil {
log.Fatalf("Failed to compile regex")
}
reMix, err := regexp.Compile("^.*[CA][RP]$")
if err != nil {
log.Fatalf("Failed to compile regex")
}
added := 0
removed := 0
codeReviewLoop: for _, code := range codes {
code = strings.TrimSpace(code)
mixedUp := false
if !re.Match([]byte(code)) {
if reMix.Match([]byte(code)) {
mixedUp = true
} else {
continue
}
}
evenCount := 0
actions := code[0:len(code)-2]
for _, c := range actions {
if c == 'A' || c == 'C' {
evenCount += 1
added += 1
} else if c == 'R' || c == 'P' {
evenCount -= 1
removed += 1
}
if evenCount < 0 {
goto codeReviewLoop
}
}
if !mixedUp {
validNum += 1
}
}
fmt.Printf("Valid Codes: %d\n", validNum)
fmt.Printf("Added: %d Removed: %d\n", added, removed)
}
Total Valid: 14 Adds: 355 Removes: 174
const std = @import("std");
const derror = std.io.Reader.DelimiterError;
pub fn main() !void {
var file = try std.fs.cwd().openFile("./src/assembly_codes.txt", .{ .mode = .read_only });
defer file.close();
var buf: [1024 * 1024]u8 = undefined;
var reader = file.reader(&buf);
var total_valid: usize = 0;
var add_count: usize = 0;
var remove_count: usize = 0;
outer: while (reader.interface.takeDelimiterExclusive('\n')) |line| {
const body = line[0..(line.len - 2)];
// part 2 logic
for (body) |c| switch (c) {
'A', 'C' => add_count += 1,
'R', 'P' => remove_count += 1,
else => return error.InvalidCharater,
};
// part 1 logic
if (line[line.len - 1] != 'P') continue;
if (line[line.len - 2] != 'C') continue;
var parts: usize = 0;
for (body) |c| {
switch (c) {
'C', 'P' => continue :outer,
'A' => parts += 1,
'R' => parts -= 1,
else => return error.InvalidCharacter,
}
if (parts < 0) continue :outer;
}
total_valid += 1;
} else |err| if (err != error.EndOfStream) return err;
std.debug.print("Total Valid: {} Adds: {} Removes: {}", .{ total_valid, add_count, remove_count });
}
17
Adds: 355, Removes: 174
import gleam/dict
import gleam/int
import gleam/io
import gleam/list
import gleam/option
import gleam/pair
import gleam/string
import simplifile
pub fn main() {
let increment = fn(x) {
case x {
option.Some(i) -> i + 1
option.None -> 1
}
}
let decrement = fn(x) {
case x {
option.Some(i) -> i - 1
option.None -> 0
}
}
let assembly_codes =
case simplifile.read("assembly_codes.txt") {
Ok(file_contents) -> file_contents
Error(_) -> {
io.println("failed to read file")
panic as "failed to read file"
}
}
|> string.split("\n")
assembly_codes
|> list.fold(0, fn(good_count, instr_set) {
let split_set = string.split(instr_set, "C")
case split_set {
[a_r, "P"] -> {
let instr_list = string.split(a_r, "")
let res =
list.fold(instr_list, #(True, dict.new()), fn(acc, instr) {
case instr {
"A" -> #(True, dict.upsert(pair.second(acc), "A", increment))
"R" -> {
case dict.get(pair.second(acc), "A") {
Error(_) -> #(False, pair.second(acc))
Ok(v) -> {
case v == 0 {
True -> #(False, pair.second(acc))
False -> #(
True,
dict.upsert(pair.second(acc), "A", decrement),
)
}
}
}
}
_ -> #(False, pair.second(acc))
}
})
case pair.first(res) {
True -> good_count + 1
False -> good_count
}
}
_ -> good_count
}
})
|> io.debug
let counts =
assembly_codes
// trim off last two letters
|> list.map(fn(code: String) { string.drop_end(code, 2) })
|> list.fold(#(0, 0), fn(acc, c) {
let code_count =
string.split(c, "")
|> list.fold(#(0, 0), fn(acc2, l) {
case l {
"A" | "C" -> #(pair.first(acc2) + 1, pair.second(acc2))
"R" | "P" -> #(pair.first(acc2), pair.second(acc2) + 1)
_ -> panic as "this shouldn't happen"
}
})
#(
pair.first(acc) + pair.first(code_count),
pair.second(acc) + pair.second(code_count),
)
})
io.println(
"Adds: "
<> int.to_string(pair.first(counts))
<> ", Removes: "
<> int.to_string(pair.second(counts)),
)
}
On a particular day at the North Pole, the elves are running an assembly line packaging presents. Each present is assigned a code upon completion that contains a sequence of instructions for how to assemble it. However, there seems to be a problem with the printer, and now, many presents have invalid sequences!
For each present, its assembly code consists of a string with the following commands:
A for “Add part”R for “Remove part”C for “Check assembly”P for “Package present”An assembly code is considered valid if there is a sequence of A and R commands leading to a correctly assembled present, followed by a single C, and ending in P. If there are multiple C or P commands, then the code is invalid, as the elves should only check and package it once. Also, there cannot be an R without a corresponding A before it (as the elves can’t remove a part they haven’t added).
For example, the assembly code AACP is valid (add two parts, check, and then package), while RCP (removal without corresponding addition) and ACCP (two checks) is not.
Problem: Your task is to write a function that receives a list from assembly_codes.txt and returns the number of valid codes.
Example input:
ACP
CRARACP
ARAAACP
ARAPCP
AARRACP
ACR
ARCAP
ARACP
ARACP
ARCP
Example output (number of valid codes):
6
The elves want to get to the bottom of this and to start they need to know how many assembly codes are still valid. Count how many are complete and ready to be packaged.
After a while, and thanks to you for getting how many presents have a correct code, the elves figure out what is wrong with the printer. The assembly commands are getting mixed up when printing. The A and C commands sometimes get swapped, and the R and P commands sometimes get swapped. Since every code should end with a single check and then package, the elves know how to fix them:
C, and the last command is always really a PC anywhere else is really an AP anywhere else is really an ROnce the codes are fixed, they are all valid! The elves want to know how many parts were added and removed in total. Fix all of the assembly codes, then count all of the parts added (A) and removed (R) across every code and report that back to the elves.
For example, ARCAP is fixed to ARACP (2 parts added and 1 part removed), and ACR is fixed to ACP (1 part added). For the whole example input above, 21 parts were added and 11 were removed.