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.

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.

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