Unable to load image

Advent of Code 2022: Day 7

https://adventofcode.com
with open('AdventOfCode2022/input.txt', 'r') as input:
    commands = input.read().split('\n')

    def new_dict(name, parent=None):
        return {
        'name': name,
        'parent':parent,
        'files': 0,
        'dirs': {}
    }

    root_dict = new_dict(name='/', parent=None)
    curr_dict = root_dict

    #Build tree of dicts
    for i in range(len(commands)):
        command_parts = commands[i].split(' ')
        if command_parts[0] == '$':
            if command_parts[1] == 'cd':
                if command_parts[2] == '..':
                    curr_dict = curr_dict['parent']
                elif command_parts[2] == '/':
                    pass
                else:
                    curr_dict = curr_dict['dirs'][command_parts[2]]
        elif command_parts[0] == 'dir':
            if command_parts[1] not in curr_dict:
                curr_dict['dirs'][command_parts[1]] = new_dict(name=command_parts[1], parent=curr_dict)
        elif command_parts[0] == '':
            pass
        else:
            curr_dict['files'] += int(command_parts[0])

    #PART ONE

    MAX_THRESHOLD = 100000
    FINAL_COUNTER = 0
    dict_list = []
    
    def parse_dict(t_dict):
        folder_total = t_dict['files']

        for c_dict in t_dict['dirs'].keys():
            folder_total += parse_dict(t_dict['dirs'][c_dict])

        global dict_list
        dict_list.append(folder_total)

        if folder_total < MAX_THRESHOLD:
            global FINAL_COUNTER # this is the most embarrassing thing I've ever done
            FINAL_COUNTER += folder_total
        return folder_total

    total_used = parse_dict(root_dict)
    print(FINAL_COUNTER)

    #PART TWO
    TOTAL_SPACE = 70000000
    WANTED_SPACE = 30000000
    curr_wanted = WANTED_SPACE - (TOTAL_SPACE - total_used)
    
    larger_than_wanted = []
    for i in dict_list:
        if i > curr_wanted:
            larger_than_wanted.append(i)

    print(min(larger_than_wanted))
32
Jump in the discussion.

No email address required.

Finally into the fun problems :marseyexcited: Congrats to whichever one of you is Sneeds-Feeduck-And-Seeduck! Per usual, cleaned up a bit before posting.

![](/images/16703933184853573.webp)

Jump in the discussion.

No email address required.

I got the recursive functions to one line of barely legible python :marseywholesome:

lines = []
with open("7.input", "r") as f:
    lines = f.readlines()

lines = [i.strip() for i in lines]

class Directory:
    def __init__(self, parent) -> None:
        self.parent = parent
        self.directories = dict()
        self.direct_size = 0
    
    def add_directory(self, name) -> None:
        self.directories[name] = Directory(self)
    
    def add_to_size(self, size) -> None:
        self.direct_size += size
    
    def get_directory(self, name) -> 'Directory':
        return self.directories[name]
    
    def get_parent(self) -> 'Directory':
        return self.parent

root = Directory(None)
current = None
for line in lines:
    args = line.split(" ")
    if args[0] == "$":
        if args[1] == "cd": 
            if "/" in line: current = root
            elif ".." in line: current = current.get_parent()
            else: current = current.get_directory(args[2])
    else:
        if args[0] == "dir": current.add_directory(args[1])
        else: current.add_to_size(int(args[0]))
    
def get_total_size(start): return sum([start.direct_size] + [get_total_size(i) for i in start.directories.values()])

def find_small_directories(start): return list(filter(None, sum([find_small_directories(i) for i in start.directories.values()], []))) + ([start] if get_total_size(start) < 100000 else [])

def get_closest_directory_to_size(start, size): return min([get_closest_directory_to_size(directory, size) for directory in start.directories.values() if get_total_size(directory) > size] + ([get_total_size(start)] if get_total_size(start) > size else []))

def solve_part_1(root) : return sum([get_total_size(i) for i in find_small_directories(root)])

part_1 = sum([get_total_size(i) for i in find_small_directories(root)])
part_2 = get_closest_directory_to_size(root, 30000000 - (70000000 - get_total_size(root)))

assert part_1 == 1141028
assert part_2 == 8278005
Jump in the discussion.

No email address required.

Some people are able to display their intelligence by going on at length on a subject and never actually saying anything. This ability is most common in trades such as politics, public relations, and law. You have impressed me by being able to best them all, while still coming off as an absolute idiot.

Jump in the discussion.

No email address required.

worried a bit about full paths but they never appeared :marseybeanrelieved:

![](/images/16703927328255818.webp)

Jump in the discussion.

No email address required.

God i didnt even want to think about what part 2 would be. I just banked on it being a 2-3 line modification like the others.

Once that stops im gonna get reamed

Jump in the discussion.

No email address required.

I guess I'm smart enough to code this, but dumb enough to try to submit the directory name for part 2 over and over and then get angry when it won't accept my answer. Apparently, I have forgotten how to read.

Jump in the discussion.

No email address required.

trans lives matter :marseygiveup:

I ended up taking a break halfway through. Coding in C was always going to be a challenge but I wanted to do it because I like C :marseyspecial:. Overall my program is super incomplete - I didn't bother freeing any of the memory and I think I still have some errors in valgrind. I need to learn to use gdb one day. For the second part I didn't even bother writing a sorting algorithm - I just listed all the numbers and used an online sorter because I was tired :marseygiveup: :marseysleep:.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define NUM_LINES 1009
//#define NUM_LINES 22

typedef struct directory{
	int numFiles;
	char **files;
	int *fileSizes;
	
	struct directory *parent;
	
	int numDirectories;
	char **directories;
	struct directory *subdirectories;
	
	int rel_size;
} Directory;

int total_directories = 1; // root counts as a directory
int *directory_sizes;

int directoryInc = 0;
void printDirectories(Directory *root){
	for(int i=0;i < root->numDirectories;i++){
		printDirectories(root->subdirectories+i);
		root->rel_size += root->subdirectories[i].rel_size;
		//printf("%s\n",root->directories[i]);
	}
	for(int i=0;i < root->numFiles;i++){
		root->rel_size += root->fileSizes[i];
		//printf("%d %s\n",root->fileSizes[i],root->files[i]);
	}
	printf("rel_size: %d\n",root->rel_size);
	directory_sizes[directoryInc++] = root->rel_size;
	if(root->rel_size <= 100000){
		answer += root->rel_size;
	}
}

int main(void){
	FILE *f = fopen("input.txt","r");
	char buffer[NUM_LINES][1024];
	int i=0;
	fgets(buffer[0],1024,f);
	while(fgets(buffer[i++],1024,f) != NULL);
	//for(i=0;i<NUM_LINES;i++){
	//	printf("%s",buffer[i]);
	//}
	
	Directory *root = (Directory*)malloc(sizeof(Directory));
	root->rel_size = 0;
	Directory *current = root;
	i=0;
	while(i < NUM_LINES){
		printf("%d %s",i+2,buffer[i]);
		if(buffer[i][2] == 'l'){//ls
			int numFiles=0,numDirectories=0;
			int f = 1;
			
			while(i+f < NUM_LINES && buffer[i+f][0] != '$'){
				if(buffer[i+f][0] == 'd')
					numDirectories++;
				else
					numFiles++;
				f++;
			}
			
			total_directories += numDirectories;
			
			current->numFiles = numFiles;
			current->numDirectories = numDirectories;
			if(numFiles != 0){
				current->files = (char**)malloc(numFiles*sizeof(char*));
				current->fileSizes = (int*)malloc(numFiles*sizeof(int));
			}
			if(numDirectories != 0){
				current->subdirectories = (Directory*)malloc(numDirectories*sizeof(Directory));
				current->directories = (char**)malloc(numDirectories*sizeof(char*));
			}
			
			int k = 1,directoryNum=0,fileNum=0;
			while(i+ k < NUM_LINES && buffer[i+k][0] != '$'){
				if(buffer[i+k][0] == 'd'){
					//create directory
					current->subdirectories[directoryNum].parent = current;
					char dir[4];
					char *name = strdup(buffer[i+k]);
					sscanf(buffer[i+k],"%s%s",dir,name);
					current->directories[directoryNum] = name;
					directoryNum++;
				}else{
					//create file
					int fsize;
					char *fname = strdup(buffer[i+k]);
					sscanf(buffer[i+k],"%d%s",&fsize,fname);
					current->files[fileNum] = fname;
					current->fileSizes[fileNum] = fsize;
					fileNum++;
				}
				k++;
			}
			@useragent13 += f;
		}else if(buffer[i][2] == 'c'){//cd
			
			char cd[4];
			char *name = strdup(buffer[i]);
			sscanf(buffer[i],"%s%s%s",cd,cd,name);
			if(name[0] == '.' && name[1] == '.'){
				current = current->parent;
			}else{
				//linear search too find the directory corresponding too name
				int q;
				for(q=0;q < current->numDirectories;q++){
					if(strcmp(name,current->directories[q]) == 0)
						break;
				}
				current = &current->subdirectories[q];
			}
			
			i++;
		}
	}
	directory_sizes = (int*)malloc(total_directories*sizeof(int));
	printDirectories(root);
	//printf("answer:%d\n",answer);
	//sort here - too lazy
	
	fclose(f);
	return 0;
}
Jump in the discussion.

No email address required.

I didn't even bother writing a sorting algorithm

do c-cels really

Jump in the discussion.

No email address required.

true programmers don’t need generics, they simply use macros

:ragemask:

Jump in the discussion.

No email address required.

All them words won't bring your pa back.

Jump in the discussion.

No email address required.

Excel stopped being viable day 3, but gl my programmer sock friends :marseyhacker:

Jump in the discussion.

No email address required.

file = open("input.txt")

class Directory:
    def __init__(self):
        self.name = None
        self.child_dirs= []
        self.child_files= []
        self.parent = None
    
class File:
    name = None
    size = None
    
sizearr=[]
answer = 0
def get_size(node):
    global answer
    size = 0
    if node.child_dirs:
        for dirs in node.child_dirs:
            size += get_size(dirs)       
    if node.child_files:
        for files in node.child_files:
            size += int(files.size)
    if size <= 100000: 
        answer += size
    sizearr.append(size)
    return size

file.readline()
root = Directory()
root.name = "root"
current_dir = root

def command(args):
    global current_dir
    if(args[0] == "cd"):
        if args[1] == "..":
            current_dir = current_dir.parent
        else:
            for i in current_dir.child_dirs:
                if i.name == args[1]: 
                    current_dir = i
                    break

for line in file:
    line = line.rstrip().split()
    if line[0] == "$":
        command(line[1:])
    else:
        if line[0] == "dir":
            new_dir = Directory()
            new_dir.name = line[1]
            new_dir.parent = current_dir
            current_dir.child_dirs.append(new_dir)
        else:
            new_file = File()
            new_file.name = line[1]
            new_file.size = line[0]
            current_dir.child_files.append(new_file)
        
current_dir = root
rootsize = get_size(root)
neededspace = 30000000- (70000000- rootsize)

sizearr.sort()
for item in sizearr:
    if item > neededspace:
        print(item)
        break
print(answer)

I did this during a conference call and people kept asking me questions and i kept losing my place but I got there eventually

Jump in the discussion.

No email address required.

APLchads.... :marseydisintegrate:

from collections import defaultdict

def size(f: tuple[str]) -> int:
    return sum(x if isinstance(x, int) else size(f+(x,)) for x in dirs[f])

with open('7', 'r') as file:
    raw = file.read().strip().split('\n')
dirs = defaultdict(list)
loc = []
for line in raw:
    match line.split():
        case ['$', 'cd', '..']:
            loc.pop(-1)
        case ['$', 'ls']:
            continue
        case ['$', 'cd', newloc]:
            loc.append(newloc)
        case ['dir', subfolder]:
            dirs[tuple(loc)].append(subfolder)
        case [filesize, *x]:
            dirs[tuple(loc)].append(int(filesize))
sizes = {k: size(k) for k in dirs}
to_remove = sizes[tuple('/')] - 40000000
a = sum(x for x in sizes.values() if x <= 100000)
b = min(x for x in sizes.values() if x >= to_remove)
print(f'Day 7: {a} {b}')
Jump in the discussion.

No email address required.

it got super messy, but i had fun solving this one tbh. the way i built my all_dirs list in particular is pretty hacky and scuffed, please tell me the smarter way to do it

from typing import Dict, Any

with open("day7input.txt") as f:
    input = f.read().split("\n")

class Dir:
    def __init__(self, directories: Dict[str, Any], files: Dict[str, int], origin): # directories' values are of type Dir but type hints wouldnt let me do it
        self.directories = directories
        self.files = files
        self.origin = origin

    def get_size(self):
        size = sum(self.files.values()) + sum(directory.get_size() for directory in self.directories.values())
        return size

    def enter_directory(self, name):
        return self.directories[name]

    def leave_directory(self, name):
        return self.origin

main = Dir({}, {}, None)

for line in input[2:10]:
    if line.startswith("dir"):
        _, name = line.split(" ")
        main.directories[name] = Dir({}, {}, main)
    elif line[0] in tuple("1234567890"):
        line = line.split(" ")
        size, name = int(line[0]), line[1]
        main.files[name] = size

current = main

for line in input[10:]:
    if line.startswith("dir"):
        _, name = line.split(" ")
        current.directories[name] = Dir({}, {}, current)
    elif line[0] in tuple("1234567890"):
        line = line.split(" ")
        size, name = int(line[0]), line[1]
        current.files[name] = size
    elif line.startswith("$ cd"):
        if line.split(" ")[2] == "..":
            current = current.origin
        else:
            name = line.split(" ")[2]
            current = current.directories[name]

all_dirs = [dir for dir in main.directories.values()]
for _ in range(1000):
    for dir in all_dirs:
        for sub_dir in dir.directories.values():
            if sub_dir not in all_dirs:
                all_dirs.append(sub_dir)

# part 1

answer = 0
for dir in all_dirs:
    if dir.get_size() <= 100000:
        answer += dir.get_size()

print(answer)

# part 2

main_size = main.get_size()
options: Dict[int, Dir] = {}
for dir in all_dirs:
    if main_size - dir.get_size() < 40000000:
        options[dir.get_size()] = dir
answer = options[sorted(list(options))[0]].get_size()
print(answer)
Jump in the discussion.

No email address required.

You are the first dramatard who managed to subtract 3 from 7 LMAO.

Jump in the discussion.

No email address required.

But that's a magic number! Those are bad!

Jump in the discussion.

No email address required.

hey atheists, if you don't believe in magic, how come you are afraid of magic numbers? checkmate

Jump in the discussion.

No email address required.

:#marseybigbrain:

Jump in the discussion.

No email address required.

Don't get too proud of yourself, if line[0] in tuple("1234567890") is unnecessary on several levels, also for _ in range(1000): is quite pointless.

Jump in the discussion.

No email address required.

if line[0] in tuple("1234567890") is unnecessary on several levels

which way is better?

for _ in range(1000): is quite pointless.

true it's r-slurred but it just werked

Jump in the discussion.

No email address required.

if line[0] in "1234567890" would work but at that point why not just force-cast the whole thing to int and see what happens?

for _ in range(1000):

I honestly don't get what it does: is it the megatard way of building subdirectory trees?

Jump in the discussion.

No email address required.

>if line[0] in "1234567890" would work

oh :marseyxd:

>I honestly don't get what it does: is it the megatard way of building subdirectory trees?

:marseyagree: it gets a layer deeper every pass. i decided to do that because i thought of it fast. unlike many other (cowardly) uses here, i dont change my code at all before posting other than adding # part 1 and # part 2. embrace the megatard within.

Jump in the discussion.

No email address required.

>tfw solve a tree problem without recursion

tardking shit my neighbor :marseykneel:

Jump in the discussion.

No email address required.

Have you owned the libs yet?

Jump in the discussion.

No email address required.

:tayhyperdab:

r←⊢⎕FIO[49]'7' ⋄ d←'' ⋄ f←''
∇p i
→({⍵≡'$ cd ..'} i)⍴ Lu
→({⍵≡'$ ls'} i)⍴ Ls
→({('$ cd '≡5↑⍵)∧(⍵≢'$ cd ..')} i)⍴ Ln
→({'dir '≡4↑⍵} i)⍴ Ld
→({'0123456789'∊⍨1⌷⍵} i)⍴ Lf
Lu: d←⌽1↓⌽d ⋄ →0
Ls: →0
Ln: d←d,⊂5↓i ⋄ →0
Ld: x←d,⊂4↓i ⋄ f←f,(⊂d x) ⋄ →0
Lf: x←{⍎⊃1⌷⍵⊂⍨' '≠⍵}i ⋄ f←f,(⊂d x) ⋄ →0 ∇
p¨r ⋄ ul←↑¨∪{1⌷⍵}¨f
li←(ul⍳{⊃1⌷⍵}¨f)⊂↑¨{2⌷⍵}¨f
∇z←eo v
→(0≡↑⍴v)⍴ Ln
→(1≡ul∊⍨(⊂v))⍴ Lu
→(~((0≡↑⍴v)∨1≡ul∊⍨(⊂v)))⍴ Le
Ln: z←v ⋄ →0
Lu: z←+/ex ((ul⍳⊂v)⌷li) ⋄ →0
Le: z←ex v ⋄ →0 ∇
∇z←ex c
z←+/eo¨c ∇
s←ex¨li
↑+/⊃,/(s≤100000)⊂s
⌊/⊃,/(s≥((⌈/s)+¯40000000))⊂s
Jump in the discussion.

No email address required.

Is this (picrel) the same language? If yes that's quite the mogging

Why are your solutions so lengthy? Am I missing something?

![](/images/16704604139879818.webp)

Jump in the discussion.

No email address required.

They're using dyalog APL (still being developed today), I'm stuck with GNU APL (was cutting edge in the 1980s). If you have a choice definitely go for dyalog.

Jump in the discussion.

No email address required.

do you own an apl keyboard?

also i checked out https://www.dyalog.com/uploads/documents/MasteringDyalogAPL.pdf and had a hearty chuckle at this considering what most apl looks like.

You can see that APL behaves like any hand-held calculator with, however, a small difference; multiplication is represented by the multiplication symbol ( × ) which is used in schools in many countries; likewise for division ( ÷ ).

In most other computer languages, a star * is used for Multiply and / for Divide. This is a legacy of the early days of computers, when the character set was limited to the one available on a typewriter. At the time it was decided to use * and / in place of × and ÷. But it is now possible to display any type of symbol on a screen and on a printer, and this transposition is no longer justifyable. The use of common symbols, which are taught all over the world, aids the understanding of APL by non programmers.

Jump in the discussion.

No email address required.

What language?

Ah, APL?

Jump in the discussion.

No email address required.

C++chads simply cannot stop winning

![](/images/16704381349654489.webp)

Jump in the discussion.

No email address required.

let d=(fs.readFileSync('file', 'utf8')).split('\n').map(a=>
  a == '$ ls' ? { type: 'ls' } :
  a.startsWith('$ cd ') ? { type: 'cd', name: a.slice(5) } :
  a.startsWith('dir ') ? { type: 'dir', name: a.slice(4) } :
  ({ type: 'file', size: +a.split(' ')[0], name: a.split(' ').slice(1).join(' ') }))

let root = {}, stack
for (let {type, name, size} of d) {
  if (type == 'cd' && name == '/') stack = [root]
  else if (type == 'cd' && name == '..') stack.pop()
  else if (type == 'cd') stack.push(stack.at(-1).ch[name])
  else if (type !== 'ls') (stack.at(-1).ch??={})[name] = { type, size }
}

let sizes = []
let ac = d => {
  if (d.type == 'file') return d.size
  let s = (Object.values(d.ch).map(ac)).reduce((a,b)=>a+b)
  sizes.push(s)
  return s
}
let total = ac(root)

console.error((sizes.filter(a=>a < 100000)).reduce((a,b)=>a+b))
console.error((sizes.filter(a=>total - (70000000 - 30000000) <= a)).reduce((a,b)=>Math.min(a,b)))

javascript needs a standard library, and rust-style pattern matching (just a combination of switch statements and struct unpacking), and also pattern matching on strings (like - match (string) { "$ ls": ...; "$ cd ${f}": ...; "dir ${f}": ...; "${size} ${file}": ...; })

you could combine the parsing and directory creating parts to make it shorter - that's bad code in a larger piece of software because you'll need to read it later, but this is throwaway code lol

Jump in the discussion.

No email address required.

c++

fml got stuck for minutes because I am too dumb to read. First I was looking for directories bigger than 100.000 and then looked for 70.000.000 - total_size, instead of 30.000.000 - 70.000.000 - total_size


#include <memory>
#include <string>
#include <fstream>
#include <iostream>
#include <vector>

class Directory {
public:
	Directory* parent;
	std::vector<Directory*> childs;
	int files;
	int total_size;
	std::string name;
	Directory(Directory* parent, std::string name) {
		this->parent = parent;
		this->name = name;
		files = 0;
	}
	Directory* find_child(std::string name) {
		for (Directory* child : this->childs) {
			if (child->name == name) return child;
		}
		return nullptr;
	}
};

void parseFile(std::ifstream& file, Directory* root) {
	Directory* current;
	current = root;
	std::string cmd1;
	while (file >> cmd1) {
		if (cmd1 == "$") {
			std::string command;
			file >> command;
			if (command == "cd") {
				std::string parameter;
				file >> parameter;
				if (parameter == "/") continue;
				else if (parameter == "..") current = current->parent;
				else {
					current = current->find_child(parameter);
				}
			}
			else if (command == "ls") {
				continue;
			}
		}
		else if (cmd1 == "dir") {
			std::string folder;
			file >> folder;
			Directory* child = new Directory(current, folder);
			current->childs.push_back(child);
		}
		else {
			int file_size = std::stoi(cmd1);
			std::string file_name;
			file >> file_name;
			current->files += file_size;
		}
	}
}

int partOne(Directory* dir, int limit, int& counter) {
	int size{ dir->files };
	if (dir->childs.size() >= 0) {
		for (Directory* child : dir->childs) {
			size += partOne(child, limit, counter);
		}
	}
	if (size <= limit) counter += size;
	dir->total_size = size;
	return size;
}

void partTwo(Directory* dir, int needToBeFreed, std::vector<Directory*>& store) {
	if (dir->total_size >= needToBeFreed) store.push_back(dir);
	for (Directory* child : dir->childs) {
		partTwo(child, needToBeFreed, store);
	}
}

int main() {
	std::ifstream file("input.txt");
	Directory root = Directory(nullptr, "/");
	parseFile(file, &root);
	int counter{ 0 };
	int total_size = partOne(&root, 100'000, counter);
	std::cout << "Part 1: " << counter << '\n';

	std::vector<Directory*> store;
	int needToBeFreed = 30'000'000 - (70'000'000 - total_size);
	partTwo(&root, needToBeFreed, store);
	int min_size = INT_MAX;
	for (Directory* a : store) {
		min_size = std::min(min_size, a->total_size);
	}
	std::cout << "Part 2: " << '\n' << '\t' << "need to be freed: " << needToBeFreed << '\n' << '\t' << "Result: " << min_size;
	return 0;
}
Jump in the discussion.

No email address required.

Your C++ code looks pretty clean compared to my C code :marseyill: :marseyschizotwitch::marseydeadinside3::marseygunshotsuicide:

Jump in the discussion.

No email address required.

Lua > C > all other programming languages > c++

@BeauBiden @SoreNoell @grizzly @MarseyIsMyWaifu @nekobit @jc @sneks discuss


:#capysneedboat2::#capyantischizo::#space:

Jump in the discussion.

No email address required.

i program in CMake

Jump in the discussion.

No email address required.

:marseyc#pat:

c is hard all that malloc

Jump in the discussion.

No email address required.

Are you feeling okay bud?

Jump in the discussion.

No email address required.

:marseyitsover:

Jump in the discussion.

No email address required.

gonna need to start pastebinning these as the answers get longer. what's the nicest anonymous one? http://dpaste.org?

https://i.rdrama.net/images/1684128833935388.webp

Jump in the discussion.

No email address required.

Jump in the discussion.

No email address required.

Oh FRICK I FORGOT ABOUT IT

Jump in the discussion.

No email address required.

wtf they added a timeout if you enter wrong things? and i wasnt even spamming stuff

![](/images/16704022161217477.webp)

Jump in the discussion.

No email address required.

:#marseyastronaut::!#marseygun::#marseyastronaut2:

Also you were spamming stuff lol.

Jump in the discussion.

No email address required.

i don't understand how people have this happen, just run your code against the dummy input they give you and verify you get the right output

Jump in the discussion.

No email address required.

Not necessarily, I'm getting the right answer with their testinput and the wrong answer on the real one :marseyxd:

Jump in the discussion.

No email address required.

how tho

Jump in the discussion.

No email address required.

Not sure yet. I'm fairly certain I must be miscounting something as the file paths get deeper but haven't had time to hunt down exactly what I did wrong yet.

fileDict = dict()

lsFound = False

with open('input', 'r') as f:

    location = ['.']

    for line in f:

        line = line.strip()

        if (line[0] is '$'):

            lsFound = False

        if lsFound and line[:3] not in 'dir':

            file_path = '/'.join(location)

            if (file_path in fileDict.keys()):

                if line not in fileDict.get(file_path):

                    fileDict.get(file_path).add(line)

                else:

                    print('Line already present')

            else:

                fileDict[file_path] = set()

                fileDict[file_path].add(line)

        if not lsFound:

            command = []

            if line[0] is '$':

                command = line[1:].strip().split(' ')

                if 'dir' in command[0]:

                    continue

                if 'cd' in command[0]:

                    if command[1] in '/':

                        location = ['.']

                    elif command[1] in '..':

                        location.pop()

                    else:

                        if (command[1] not in '/'):

                            location.append(command[1])

                elif 'ls' in command[0]:

                    lsFound = True

def computeSize(nameKey) -> int:

    tempSum = 0

    files = fileDict[nameKey]

    for size_name in files:

        pair = size_name.split(' ')

        if pair[0] in 'dir':

            continue

        tempSum += int(pair[0].strip())

    for key2 in fileDict.keys():

        if nameKey + '/' in key2 and nameKey is not key2:

            tempSum += computeSize(key2)

    return tempSum

totalSum = 0

print(fileDict)

for key in fileDict.keys():

    dirSum = computeSize(key)

    if dirSum <= 100000:

        totalSum += dirSum

print(totalSum)
Jump in the discussion.

No email address required.

Not 100% sure, but I think you are forgetting that the size of a directory is the size of the files in it and all the files in directories beneath it. So, its recursive

Jump in the discussion.

No email address required.

That was a mistake. You're about to find out the hard way why.

Jump in the discussion.

No email address required.

guess who does not know data structures and spent way too long looking at debug prints to figure out wtf was going on

![](/images/16704472416843498.webp)

Jump in the discussion.

No email address required.

import * as fs from 'fs'

interface Node {size: number, parent?: Node, childs?: {[key: string]: Node}}
const postOrder = (n: Node, func: (n: Node) => any) => {
  Object.values(n.childs || {}).map(c => postOrder(func, c));
  func(n);
}

// build tree
const root: Node = {size: 0, childs: {}}
let curNode: Node = root;
fs.readFileSync(process.argv[2], 'utf-8').split('\n').map(l => {
  const m = l.match(/\S+/g) || [];
  if (m[1] === 'cd') {
    if (m[2] === '/') curNode = root;
    else if (m[2] === '..') curNode = curNode.parent || curNode;
    else curNode = curNode.childs![m[2]];
  }  else if (m[0] === 'dir') {
    curNode.childs![m[1]] = {size: 0, parent: curNode, childs: {}};
  } else if (m[0] !== '$') {
    curNode.childs![m[1]] = {size: Number(m[0]), parent: curNode};
  }
});

// traversal to size folders
postOrder(root, (n: Node) => n.parent && (n.parent.size += n.size));
// traversal to find best folder
const sizeReq = 30000000 - (70000000 - root.size)
let minSize = root.size;
postOrder(root,
  (n: Node) => n.childs && sizeReq <= n.size && n.size < minSize && (minSize = n.size),
);

console.log(minSize); 
Jump in the discussion.

No email address required.

i hate python i hate python i hate python

Jump in the discussion.

No email address required.

Me while trying to figure out why my str variables got saved to each constructed object but my array variables didn't

Jump in the discussion.

No email address required.

Frick it's gonna filter me so hard

I know how 2 tree in OCaml but I never even touched OOP in Matlab

Jump in the discussion.

No email address required.

ogey I've done it

too ashamed of my code so I'll clean it up after I sleep before posting

Jump in the discussion.

No email address required.

Completed it.

My code is really messy :marseyworried:. I don't wanna share :marseysmugretard:

nvm posted as OP without cleanup

Jump in the discussion.

No email address required.

:#marseyjewoftheorient:

Snapshots:

Jump in the discussion.

No email address required.

SNAPPY NOOOOOO

Jump in the discussion.

No email address required.

cleaned my MATLAB (:gigachad2:) code, merged both parts and made it a bit better

![](/images/16704602463582208.webp)

Jump in the discussion.

No email address required.

foo = []
with open('day7_input.txt', 'r') as inp:
    foo = inp.read().split('\n')

class File:
    def __init__(self, name, size, parent):
        self.name = name
        self.size = size
        self.parent = parent

class Folder:
    def __init__(self, name, parent=None):
        self.name = name
        self.children = []
        self.files = []
        self.size = 0
        self.parent = parent

    def update_size(self, val):
        self.size += val
        if self.parent != self:
            self.parent.update_size(val)

    def add_child(self, name):
        for f in self.children:
            if name == f.name:
                return
        self.children.append(Folder(name, self))

    def add_file(self, name, size):
        for f in self.children:
            if name == f.name:
                return
        self.files.append(File(name, size, self))
        self.update_size(size)

    def star_1(self):      
        total = 0
        if self.size < 100000:
            total += self.size
        for c in self.children:
            total += c.star_1()
        return total
    
    def star_2(self, space_req):
        folders = []
        if(self.size >= space_req):
            folders.append(self.size)
        for c in self.children:
            child = c.star_2(space_req)
            if len(child) > 0:
                folders += child
        return folders


filesystem = Folder('')
filesystem.parent = filesystem
current_folder = filesystem
listing = False


i = 0
while i < len(foo):
    if listing:
        if foo[i][0] == '$':
            listing = False
        elif foo[i].startswith('dir'):
            current_folder.add_child(foo[i][4:])
        else:
            current_folder.add_file(foo[i].split(' ')[1], int(foo[i].split(' ')[0]))
    if not listing:
        if foo[i] == '$ cd /':
            current_folder = filesystem
        elif foo[i] == '$ cd ..':
            current_folder = current_folder.parent
        elif foo[i] == '$ ls':
            listing = True
        elif foo[i].startswith('$ cd'):
            for c in current_folder.children:
                if c.name == foo[i][5:]:
                    current_folder = c
                    break
    i += 1

print(filesystem.star_1())
print(sorted(filesystem.star_2(filesystem.size - 40000000))[0])

Probably went over the top on this one but was a fun step-up from the previous challenges so far.

Jump in the discussion.

No email address required.

If only you could put that energy into your relationships

Jump in the discussion.

No email address required.

Fricking graphs in Rust made me wanna keep myself safe and reconsider the choice of language for this shit

At least the task itself was pretty easy

(And the fricking site died just I was submitting solution for the 2nd part)

If anyone wants to see the code: https://pastebin.com/7vMxeBJN

Can't be bothered to clean it up

Jump in the discussion.

No email address required.

import java.io.*;
import java.util.*;
public class Main {
    
    public static void main(String args[]) {
        try {
            BufferedReader br = new BufferedReader(new FileReader("betterName.txt"));
            String line = null;
            TreeNode initialParentNode = new TreeNode("Start", 0, null);
            TreeNode currentNode = initialParentNode;
            while ((line = br.readLine()) != null) {
                if(line.contains("$ cd")) {
                    if(line.equals("$ cd /")) {
                        continue;
                    }
                    else if(line.equals("$ cd ..")) {
                        currentNode.getParent().setData(currentNode.getData());
                        currentNode = currentNode.getParent();
                    }
                    else {
                        currentNode = currentNode.addChild(line.split(" ")[2], 0);
                    }
                }
                else if(isNumeric(line.split(" ")[0])) {
                    currentNode.setData(Integer.parseInt(line.split(" ")[0]));
                }
            }
            br.close();
            //initialParentNode.printTree(initialParentNode);
            System.out.println(initialParentNode.sumTree(initialParentNode));
            // System.out.println(count);
        }
        catch(FileNotFoundException ex) {
            System.out.println("1 Sad!");
        }
        catch(IOException ex) {
            System.out.println("2 Sad!");
        }
    }
    
    public static boolean isNumeric(String string) {
        int intValue;
    		
        if(string == null || string.equals("")) {
            return false;
        }
        
        try {
            intValue = Integer.parseInt(string);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }
}

public class TreeNode<T> {
    private T value = null;
    private int data = 0;
    private TreeNode[] childrens = new TreeNode[100];
    private TreeNode parent = null;
    private int childCount = 0;

    TreeNode(T value, int data, TreeNode<T> parent) {
        this.value = value;
        this.data = data;
        this.parent = parent;
    }

    public TreeNode addChild(T value, int data) {
        TreeNode newChild = new TreeNode(value, data, this);
        childrens[childCount++] = newChild;
        return newChild;
    }

    public int getData() {
        return this.data;
    }

    public TreeNode getParent() {
        return this.parent;
    }

    public Object getParentName() {
        if(this.parent != null) {
            return this.parent.value;
        }
        return "Start";
    }

    public void setData(int data) {
        this.data += data;
    }

    static void traverse(String trail, TreeNode obj) {
        if (obj != null) {
            for (int i = 0; i < obj.childCount; i++) {
                System.out.println(trail + obj.childrens[i].value + " - " + obj.childrens[i].data);
                traverse(trail + "    ", obj.childrens[i]);
            }
        }
        return;
    }

    static int traverseSum(TreeNode obj, int deletion, int smallestSize) {
        if (obj != null) {
            for (int i = 0; i < obj.childCount; i++) {
                if(obj.childrens[i].data >= deletion && obj.childrens[i].data < smallestSize) {
                    smallestSize = obj.childrens[i].data;
                }
                smallestSize = traverseSum(obj.childrens[i], deletion, smallestSize);
            }
            return smallestSize;
        }
        return 0;
    }

    void printTree(TreeNode obj) {
        System.out.println(obj.value + " - " + obj.data);
        traverse("    ", obj);
    }

    int sumTree(TreeNode obj) {
        int smallestSize = obj.data;
        int deletion = 30000000 - (70000000 - obj.data);
        return traverseSum(obj, deletion, smallestSize);
    }
}
Jump in the discussion.

No email address required.

:#marseyparty: first Java programmer I’ve seen :marseysadpat:

Jump in the discussion.

No email address required.

I don't have enough spoons to read this shit

Jump in the discussion.

No email address required.

Start - 38345214

bsnqsfm - 179236

dtqvbspj - 494450

hhhtrws - 10632043

    gcbg - 3658797

        bgcwh - 211273

        bsnqsfm - 1069939

            bsnqsfm - 292856

            gpcpgfh - 177703

        jjgpvcqv - 2003950

            jjgpvcqv - 1421197

                bqnctqvn - 418596

                    nzrst - 12412

                        whtfvrl - 12412

                bsnqsfm - 293832

                gpcpgfh - 196159

        rqbnd - 154008

    jjgpvcqv - 6259122

        dvsst - 805852

        gpcpgfh - 2165662

            tbrbw - 1406757

                rmqlpvq - 629460

                    gjgfvt - 242867

                    wqfcnlzq - 62647

                        vhhscrvb - 62647

            vvm - 296046

            wplf - 292899

        jjgpvcqv - 2134045

            dhfcbc - 421258

            jjgpvcqv - 406609

            ltclg - 1066921

                fdfn - 32987

                mgvdbtl - 448220

            ptbsgmlr - 239257

        mhrzj - 493324

        tmh - 152958

        vmwz - 253867

    mgvdbtl - 24916

    qhv - 660064

        hncvrlbw - 506825

ldmsq - 8687846

    jngnzc - 1069913

        dzlcq - 70984

        gpcpgfh - 288159

        rlwwwngc - 641181

        swrlvd - 69589

    psgrjgr - 1142486

        fcvqsp - 209758

    rgwp - 11060

    rtsmnzm - 2842225

        rdv - 291554

        sdwmbsz - 2083367

            dfzw - 168631

            jbnsvcv - 659560

                bsnqsfm - 74345

                qfmj - 480838

                    bfvwng - 207083

                        qzdpp - 207083

                            jjgpvcqv - 207083

                    jjgpvcqv - 273755

            jjgpvcqv - 1114349

                vtbln - 395727

                wph - 174151

        tjwht - 467304

            mgvdbtl - 330718

                gtmbf - 330718

    wsd - 3622162

        gpcpgfh - 460025

            qtnqzql - 242800

        jdnfsqzd - 604210

        lspqh - 367991

            pspghgw - 367991

        pfcmb - 1412584

            dmlsqf - 553324

            dtqvbspj - 197079

                fpq - 98034

pqcndb - 17831881

    dtqvbspj - 134541

    fvrtmdg - 600719

        gpcpgfh - 64193

    gpcpgfh - 5416300

        cmg - 1331103

            vsjs - 779098

                dqpqvsfn - 91215

                ghw - 394357

                    bwhn - 61301

                        gpcpgfh - 61301

        jjgpvcqv - 281936

        lmb - 60362

            mmqr - 60362

        lzgc - 211543

        nqvzvfb - 513390

        rbh - 2481982

            cwgc - 254910

            gpcpgfh - 419940

            hdmmgms - 1266376

                dtqvbspj - 61268

                gpcpgfh - 306663

                tgqbtw - 460625

                    bsnqsfm - 279305

                    nnn - 181320

            jwqdv - 306471

            mzt - 159120

    jjgpvcqv - 4424554

        drmmqldt - 690999

            bsnqsfm - 200217

            gpcpgfh - 302915

            jjgpvcqv - 187867

                bzhsjfq - 37713

                lptnp - 150154

        jjgpvcqv - 149237

            csvpf - 149237

        mzj - 216100

        qcclcdd - 550287

            mgvdbtl - 142184

                dtqvbspj - 142184

        rtnnjct - 2247380

            bsnqsfm - 157447

                gbp - 157447

                    gpcpgfh - 157447

            dtqvbspj - 882344

                fbpz - 118001

                mgvdbtl - 764343

                    gtbpnhhm - 422909

                    rvjdhdvf - 341434

                        vnlq - 99356

                            zwtwvdb - 99356

            ftlr - 439951

                fdm - 439951

                    pdzbthz - 439951

                        gmpzrfv - 121073

            grpln - 351247

                thsbgczd - 231385

                vdmt - 119862

                    qzwzwlpr - 119862

            wtjfbzjq - 416391

        trgbfqb - 219127

            mhhbp - 159237

                bsnqsfm - 80555

                hvjtmr - 78682

    mgvdbtl - 1399019

        gpcpgfh - 695093

            bfjb - 9385

            dtqvbspj - 115949

                zrtpvzh - 115949

            lwtj - 396961

        tdnhp - 25816

    pftswtnl - 5349656

        cjzl - 51636

        mgvdbtl - 490254

            dtlr - 43065

        rdhdqvm - 108607

        swgdh - 2615714

            dwznjd - 379176

            mgvdbtl - 880115

                pbw - 242621

            nbpdfrv - 629718

        tgwws - 1617577

            bhr - 1310649

                wfjfvb - 1310649

                    jgfbpwjh - 1258789

                        vsmgcv - 197093

                            dpdmspz - 197093

                                bsnqsfm - 197093

            gpcpgfh - 306928

    zwph - 204738

        cmznd - 204738

            zhhm - 204738

pwtqzwv - 3913926

    hthq - 2002618

        dtqvbspj - 417341

            lrvftwzb - 125914

            nzvbpcwd - 251094

                tzvclhw - 251094

        mgvdbtl - 817653

        wgcss - 767624

            jjgpvcqv - 116833

    jcsmcf - 146144

    jjgpvcqv - 977695

        gdrqbn - 151579

        nwbqdd - 826116

            gpcpgfh - 275833

    twrjfd - 503531

        gqlqnpvm - 180568

    zzclqz - 217719

The file system for anyone interested.

Jump in the discussion.

No email address required.

K

Jump in the discussion.

No email address required.

Link copied to clipboard
Action successful!
Error, please refresh the page and try again.