2025

— R Day 6 Part 1 —

solve_day6_part1 <- function(input) {
    worksheet = read.table(text = input)

    nums <- worksheet[1:(NROW(worksheet)-1), ]
    nums <- apply(nums, 2, as.numeric, simplify = FALSE)

    ops <- worksheet[NROW(worksheet), ]
    ops <- ifelse(ops == "+", list(sum), list(prod))

    ans <- mapply(\(fn, group) fn(group), ops, nums)

    sum(ans)
}
Run
aoc_source(day = 6, part = 1)

input = aoc_read(day = 6)

aoc_run(solve_day6_part1(input))
Elapsed: 0.054 seconds
Memory:  8624 KB

— R Day 6 Part 2 —

solve_day6_part2 <- function(input) {
  worksheet <- strsplit(input, "")
  nrows <- length(worksheet)

  nums <- worksheet[1:(nrows-1)]
  nums <- as.data.frame(nums)

  ops_row <- worksheet[[nrows]]
  starts <- which(ops_row != " ")
  ends <- c(starts[-1] - 2, NROW(nums))

  nums <- as.numeric(apply(nums, 1, \(x) paste0(x, collapse = "")))
  groups <- Map(\(start, end) nums[start:end], starts, ends)

  ops <- ops_row[starts]
  op_map <- list("+" = sum, "*" = prod)
  op_fns <- op_map[ops]

  ans <- mapply(\(fn, group) fn(group), op_fns, groups)

  sum(ans)
}
Run
aoc_source(day = 6, part = 2)

input = aoc_read(day = 6)

aoc_run(solve_day6_part2(input))
Elapsed: 0.018 seconds
Memory:  745 KB

— Python Day 6 Part 1 —

from math import prod

def solve_day6_part1(text):
    text = [line.rstrip().split() for line in text]

    nrows = len(text)
    nums = text[:(nrows-1)]
    ops = text[nrows-1]

    ans = 0
    n_problems = len(nums[0])

    for i in range(n_problems):
        group = []
        for row in range(nrows-1):
            group += [int(nums[row][i])]

        if ops[i] == "+":
            ans += sum(group)
        else:
            ans += prod(group)

    return(ans)
Run
aoc_source(day = 6, part = 1)

input = aoc_read(day = 6)

result = aoc_run("solve_day6_part1(input)")
Elapsed: 0.019 seconds
Memory:  229 KB

— Python Day 6 Part 2 —

from math import prod

def solve_day6_part2(text):
    text = [[*line.rstrip("\n")] for line in text]

    nrows = len(text)
    nums = text[:(nrows-1)]
    ops_row = text[nrows-1]

    starts = [i for i, val in enumerate(ops_row) if val != " "]
    n_problems = len(starts)
    ops = [ops_row[i] for i in starts]

    ncols = len(nums[1])
    ends = [pos - 1 for pos in starts[1:]]
    ends += [ncols]

    v_nums = ["" for _ in range(ncols)]
    for col in range(ncols):
        for row in range(nrows-1):
            v_nums[col] += nums[row][col]

    groups = [v_nums[start:end] for start, end in zip(starts, ends)]

    ans = 0
    for i in range(n_problems):
        group = [int(num) for num in groups[i]]
        if ops[i] == "+":
            ans += sum(group)
        else:
            ans += prod(group)

    return ans
Run
aoc_source(day = 6, part = 2)

input = aoc_read(day = 6)

result = aoc_run("solve_day6_part2(input)")
Elapsed: 0.027 seconds
Memory:  541 KB
Back to top