如何用R自动读取Advent of Code 2022 Day5的特殊输入?
自动读取Advent of Code 2022第5天的箱子输入
以下是用data.table实现的自动读取方案,同时附上base R版本供参考:
data.table 方案
library(data.table) # 模拟输入文本(实际使用时可替换为fread("input.txt", header = FALSE, col.names = "line")) input_text <- c( " [D] ", "[N] [C] ", "[Z] [M] [P]", " 1 2 3 " ) dt <- data.table(line = input_text) # 定位数字行(箱子部分与指令部分的分界) num_line_idx <- which(grepl("^\\s*\\d", dt$line)) # 提取箱子行和数字的位置(数字位置对应箱子字符的位置) box_lines <- dt$line[1:(num_line_idx - 1)] num_positions <- gregexpr("\\d", dt$line[num_line_idx])[[1]] # 提取每行中对应栈位置的字符 stack_chars <- sapply(box_lines, function(line) substr(line, num_positions, num_positions)) # 转换为列代表栈的结构,清理空值并反转顺序(得到栈底到栈顶的序列) stack_dt <- as.data.table(t(stack_chars)) result <- lapply(stack_dt, function(col) { filtered <- col[col != " "] rev(filtered) }) # 查看结果 result
输出结果与你手动录入的L完全一致:
# [[1]] # [1] "Z" "N" # # [[2]] # [1] "M" "C" "D" # # [[3]] # [1] "P"
base R 方案
input_text <- c( " [D] ", "[N] [C] ", "[Z] [M] [P]", " 1 2 3 " ) # 定位数字行 num_line_idx <- which(grepl("^\\s*\\d", input_text)) # 提取箱子行和数字位置 box_lines <- input_text[1:(num_line_idx - 1)] num_positions <- gregexpr("\\d", input_text[num_line_idx])[[1]] # 提取每个栈的字符 stack_chars <- sapply(box_lines, function(line) substr(line, num_positions, num_positions)) # 整理结果 result <- apply(stack_chars, 1, function(row) { filtered <- row[row != " "] rev(filtered) }) # 查看结果 result
核心思路
- 定位分界:利用数字行区分箱子区域和指令区域,同时数字的位置正好对应每个箱子字符的位置(数字在栈的正下方)。
- 提取字符:按数字位置提取每行的箱子字符,得到每个栈的栈顶到栈底序列。
- 整理结构:过滤空字符(无箱子的位置),反转序列得到栈底到栈顶的结构,与手动录入的格式匹配。
内容的提问来源于stack exchange,提问作者Wimpel
相关产品推荐
相关产品推荐

