Skip to content

Instantly share code, notes, and snippets.

@ozjimbob
Last active December 7, 2022 10:12
Show Gist options
  • Save ozjimbob/39bbd1b46ac87faba6f630bfa8c21078 to your computer and use it in GitHub Desktop.
Save ozjimbob/39bbd1b46ac87faba6f630bfa8c21078 to your computer and use it in GitHub Desktop.
data <- readLines("data_07.txt")
files <- data.frame(id=1,parent=0,name="/",type="dir",size=0)
find_next <- function(x){
while(x < length(data)){
x=x+1
if(strsplit(data[x]," ")[[1]][1]=="$" || x > length(data)){
return(x)
}
}
return(length(data)-1)
}
id = 1
for(line in 2:length(data)){
this_line <- strsplit(data[line]," ")[[1]]
this_command <- this_line[1]
print(line)
if(this_command=="$"){
print("$ command")
if(this_line[2]=="ls"){ # Listing
print("..ls")
line_seq = (line+1):(find_next(line)-1)
for(i in line_seq){
this_data <- strsplit(data[i]," ")[[1]]
print(this_data)
if(this_data[1] == "dir"){
print("....dir")
new_row <- data.frame(id=max(files$id)+1,
parent = id,
name = this_data[2],
type="dir",
size = 0)
files <- rbind(files,new_row)
}else{
print("....file")
new_row <- data.frame(id=max(files$id)+1,
parent = id,
name = this_data[2],
type="file",
size = this_data[1])
files <- rbind(files,new_row)
}
}
line = find_next(line)
next
}
if(this_line[2]=="cd"){
print("cd")
if(this_line[3]==".."){
print("....")
tid <- id
id <- subset(files,files$id==tid)$parent
}else{
print("forward")
tid <- id
id <- subset(files,files$name==this_line[3] & files$parent == tid)$id
}
}
}
}
files <- subset(files,!name %in% c("ls","cd"))
files$size = as.numeric(files$size)
files <- files[order(-files$parent),]
for(i in 1:nrow(files)){
this_row <- files[i,]
if(this_row$type=="file"){
this_parent = this_row$parent
size = this_row$size
while(this_parent != 1){
files$size[files$id == this_parent]= files$size[files$id == this_parent ] + as.numeric(size)
parent_row <- subset(files,files$id==this_parent)
this_parent <- parent_row$parent
}
files$size[files$id==1]=files$size[files$id==1]+size
}
}
fx <- subset(files,size <= 100000 & type=="dir")
print(sum(fx$size))
# part 2
used = subset(files,id==1)$size
total = 70000000
update = 30000000
difr = total-used
need = update - difr
fy = subset(files,type=="dir" & size >= need)
min(fy$size)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment