/aocg/ - Advent of Code 2018 General #21

Plight of the brainlet edition

Previous thread adventofcode.com/
>Advent of Code is a series of small programming puzzles for a variety of skill levels. They are self-contained and are just as appropriate for an expert who wants to stay sharp as they are for a beginner who is just learning to code. Each puzzle calls upon different skills and has two parts that build on a theme.
You need to register with an account but you can appear as anonymous.

Private leaderboard join code (currently full):
368748-e33dcae3

People who are inactive for 5 days will be kicked, but other leaderboards can be made if desired.

Alternative leaderboard for those waiting for inactives to be kicked from the first:
208834-4a1a9383

Attached: Lennart_poettering_foss.in_2007.jpg (1599x1066, 178K)

Other urls found in this thread:

pastebin.com/vtTexAV1
pastebin.com/VGAbNbyM
my.mixtape.moe/rapvjn.txt
paste.ofcode.org/5af8dXeudNi8hNbMPSpe5C
maurits.vdschee.nl/scatterplot/
spit.mixtape.moe/view/5ebd631d
twitter.com/SFWRedditGifs

dab

i think i got filtered out yesterday...but this should be easier right?
from collections import *
ls = open('input', 'r').read().strip().split('\n')
instrs = []
for l in ls:
instr = l.split(' must be finished before step ')
instrs.append((instr[0][-1],instr[1][0]))
print(instrs)
d = defaultdict(list)
for instn in instns:
d[instn[0]].append(instn[1])
# ns, not start
ns = set()
for k in d.keys():
for v in d[k]:
ns.add(v)
alphabet = "qwertyuiopasdfghjklzxcvbnm".upper()
alphaset = set()
for ch in alphabet:
alphaset.add(ch)
for elem in ns:
alphaset.remove(elem)
alphaset
# B is start
res = ""
used = set()
stack = set()
stack.add('B')
stack.add('K')
stack.add('V')
while len(stack) != 0:
ss = list(stack)
ss.sort()
pop = ss[0]
res += pop
used.add(pop)
stack.remove(pop)
for v in d[pop]:
if v not in stack and v not in used:
stack.add(v)

I bet this confuses you too

Attached: 0 and null.jpg (1024x576, 104K)

I'm burnt out already.

>alphabet = "qwertyuiopasdfghjklzxcvbnm".upper()
string.ascii_uppercase ?

Hoo boy, lots of brainlet tears for the calendar today

too tired for this I guess
my first idea for step 1 was flawed and lost a decent amount of time

step 2 was very easy, I don't know why it took me 13 mins to solve.
I really should have had that part in under 3 minutes

Attached: day7.png (616x200, 11K)

My solution isn't working am I seriously getting filtered?
It works on the example

this

shooting for the calendar pic here
(line[5], line[36])

Part 1 or 2? What are you doing?

For part 1, I thought I'd do what I normally do for graph problems and start from the finish line and work backwards. That was wrong. You can't get ```sorted''' output that way.
So I decided to start from 'A-Z', and for nodes with no dependencies, go through the inverse dependency list and remove it from those lists of dependencies, along with the global list of variables remaining to be solved, ad nauseum.
Rate my apparently wrong solution
def graph_search(data):
graph = {}
graph2 = {}
global remaining
remaining = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for i in remaining:
graph[i] = []
graph2[i] = []
for i,j in data:
graph[j].append(i)
graph2[i].append(j)
result = []
while remaining:
for i in remaining:
if len(graph[i]) == 0:
result.append(i)
for j in graph2[i]:
graph[j].remove(i)
remaining = remaining.replace(i, '')

return ''.join(result)

Apparently it's wrong for this input: pastebin.com/vtTexAV1
The output is BETUVWADFNPRGLOJMXZHKQCISY

im thinking of simulating time step for part 2 even though it's pajeet tier but it seems like the simpler of the possible solutions.

yeah im gonna do that. bless me stallman.

Wow, thread is dead today
huge number of anons are still working on it or gave up and went to bed

ahh fuck, im stuck on part 2.

People got massively burnt out after the bug in yesterday's challenge.

Yeah, you really should just do the simple brain-dead solution
because it's going to work on almost every problem and requires little thinking

that question was bullshit.

Looks like i'm getting filtered

>didn't read the description and assumed it was a DFS
>read the description when my DFS didnt work
>its actually a BFS with autistic restrictions

FUCK
EVERYTHING

Attached: 1533210137256.jpg (479x328, 23K)

Seriously, this should be working, but it isn't accepting my result

Part 1 still, I can't figure out what's wrong.
Each step is parsed earlier to look like this
{
letter: char,
required: char[],
done: bool
}

Attached: Screenshot from 2018-12-07 07-03-52.png (727x288, 56K)

When you have multiple possible choices, are you picking them in alphabetical order?

Man, these aren't that good this year. Last year's had maybe three or five screenshots of posts for like half of the days, but this year every single image so far is absolutely fucking plastered with them like some kind of garish reddit screencap. It's not original nor funny to cover 50% of the image in that shit.

Attached: 1537317823350.jpg (650x613, 330K)

Agreed, not all need to be dense with posts.

>last night
>doing puzzle
>on it for 2 hours
>frustrated as fuck
>jerk off
>come back and do it in 20 minutes

>today
>doing puzzle
>i know this is easy but I can't do it FUCK FUCK FUCK
>jerk off
>come back and knock it out in ten minutes

holy fuck... what is this power i've unlocked???

Attached: oshitimwoke.jpg (374x406, 80K)

Oh no, that doesn't matter at all for my solution
The problem is that I was missing a break.
When you iterate through a list, you must NEVER modify that list. It is undefined (or at least poorly defined) behavior.
So when you remove an item from a list, you have to start over and work from a clean state.
Check em. It works.
def graph_search(data):
dependencies = defaultdict(list)
inverse = defaultdict(list)
global remaining
remaining = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for i,j in data:
dependencies[j].append(i)
inverse[i].append(j)
result = []
while remaining:
for i in remaining:
if len(dependencies[i]) == 0:
result.append(i)
for j in inverse[i]:
dependencies[j].remove(i)
remaining = remaining.replace(i, '')
break

return ''.join(result)

Noice.

This desu

>mfw part two will require me to basically toss out my part one solution

great puzzle

Attached: getouttamyoffice.png (234x233, 96K)

I haven't nutted in like 5 days
I need to try your strategy

Why is this thread so dead?

Attached: 1500494762001.jpg (1052x1402, 504K)

Work or sleep
I got to go in 10 minutes myself

pretty sure this has gotten to the point where much fewer people care about leaderboards, the threads are much more active during the day (US time). they are (rightly) deciding that staying up late for an anonymous dick measuring contest is stupid

fuck, i have the test input working
cant figure out what im doing wrong.

People are either done, busy, or sleeping to do it later while less tired.

Same issue here

anyone mind giving their test data and solution to their test data for part one?

what test input?

>try to "cheat" part 1 by using tsort, graphviz, and my eyes
>waste 20 minutes
>finally give up and start writing code
>solve part 1 in 10 minutes
nice

yup, the same
mine is: IBECGFDAHJKLMNOPQRSTUVWXYZ

Part 1: 1399
Part 2: 867
Next thread should be "Read the Fucking Problem Statement" edition
Oh well. Last year I didn't rank in the leaderboard until problem 13, I still have time to improve on that


def AOC7(file):
pairs = []
for line in file.read().splitlines():
words = line.split()
a, b = words[1], words[7]
pairs.append((a,b))

requirements = set(pairs)
IDs = set(reduce(lambda a,b: a+b, pairs))
timer = 0
tasks = dict()
while IDs or tasks:
if not(len(tasks) == 5 or not IDs):
can_do = set()
for ID in IDs:
for a, b in requirements:
if ID == b: break
else: can_do.add(ID)
while len(tasks) < 5 and can_do:
to_do = min(can_do)
tasks[to_do] = 60 + ord(to_do) - ord('A') + 1
can_do.remove(to_do)
IDs.remove(to_do)

elapse = min(tasks.values())
for x in tasks:
tasks[x] -= elapse
for x in list(tasks.keys()):
if tasks[x] == 0:
tasks.pop(x)
for a,b in list(requirements):
if a == x:
requirements.remove((a,b))
timer += elapse
return timer

Attached: 1512593410955.gif (500x373, 1020K)

reduced population due to two consecutive brainlet filters, burnout from yesterday's bug and general attrition.

Trying to get all roads string like this
iteration i
0 1 2 4
'C' 'CA' 'CAB' 'CABE'
'CF' 'CAD' 'CADE'
'CFE' 'CFE'

Yet my shitty python compiler keep telling me
>> File "1.py", line 24, in
>> for check in roads:
>> RuntimeError: Set changed size during iteration

nxt_roads = set()
new_road_flag = True
while new_road_flag:
new_road_flag = False
for check in roads:
check_flag = True
for element in rules:
if check[len(check)-1] == element[0]:
nxt_roads.add(check+element[1])
check_flag = False
new_road_flag = True
if check_flag:
nxt_roads.add(check)
roads = nxt_roads

I need to take a shower or I would tear apart my laptop. t(ಠ益ಠt)

See There's no joy in this.

This was too easy. Hope the next graph puzzle will be actually interesting

It's pretty much what it says, can't modify a set while you're iterating over it.

Just make a copy before the iteration and you're all good.

>withdrawal symptoms from dopaminergic addiction include inability to focus
>indulge in addiction to stave off withdrawal symptom
>focus briefly returns
Not claiming I have any better handle on my fapping habits by the way

Attached: 1519775050660.jpg (679x960, 141K)

pastebin.com/VGAbNbyM
BFKEGNOVATIHXYZRMCJDLSUPWQ
1020

Graph puzzles are death for those who are inexperienced

Things that are in every AoC checklist:

x sum and modulo problem to make brainlets happy
x character counting problem
x infinite matrix problem
x graph theory problem
- assembly interpreter
- exhaustive enumeration problem
- dijkstra
- algorithmic optimization problem

How is it easy?

REEEEE my test input is working but not my challenge input.

Looking forward to ASM when I wrap my head around this shit, emulators are fun to write

I want an interpreter puzzle next

>make array of tasks that have already been done (initialized to empty list)
>make array of tasks that have yet to be done (initialized to full alphabet)

>inside of a loop:
>make a list of all tasks that can be done at this moment by checking the to_do list against the done list and the rules
>take the alphabetic minimum of that list
>move it from the to_do list to the done list
>repeat

Easy

t-that was the filter right guys?

Attached: 1524387244515.jpg (640x427, 46K)

Sounds like bullshit.

You goys have no chance against me

Attached: Screenshot_2018-12-07-14-45-42-759_com.android.chrome~01.png (1079x665, 172K)

Literally the only way to solve the challenge

>Rabbi Shlomo Shekelberg Goldstein
user, you have to make it on the global leaderboard for pic related

Attached: god and country.jpg (491x333, 67K)

its more about sleep deprivation than fap addiction right now desu senpai

>part 2 killing me
>want to put it off and go to bed
>will have smash bros tomorrow and therefore 0 motivation to do this puzzle
>will have no motivation to do future puzzles while i have earlier ones incomplete
>incomplete puzzles will build up very quickly

welp, i think this is it for me guys. guess this means i'm /filtered/. see ya next year?

Attached: idontfeelsogoodrightmeow.jpg (750x933, 517K)

Be sure to let us know if Eric Wasdf bans you for memeing too hard.

before you go tell me how you did question 6 part one and two in psuedo code

tfw TopologicalSort[ ] in Mathematica doesn't let you supply an additional ordering function.

Nick?

Anyone got data + solution for part 2?

Part 1
>find the binding box of all locations by finding the min and max of x coordinates and min and max of y coordinates
>For every point on the 4 edges of the bounding box, find the closest location
>Every location that is the closest location of a point on the bounding box has an infinite number of points for which it is the closest location (that extend perpendicularly out from the edge) and so can be disregarded
>For every point within the bounding box figure out which is the closest location, add store the counts in a dictionary, add them up and get the max out of locations that weren't filtered out earlier

just make a 400x400 array of zeroes

for each coordinate, calculate the distance to every input value. record the input coordinate of the minimum distance to that array point instead of the zero place holder. if there is a tie for the minimum, record an x instead.

to get rid of infinites, iterate through the edges of your map array (top, bottom, left, and right). any input coordinate that has its value recorded on any of the edges is an infinite and can be ignored for the final part.

now you just iterate through the map again and record the totals times each input coordinate appears in the map. ignore the infinites that you detected in the last step, and the max counter from the remaining inputs is your answer.

part 2 is baby tier once you have part 1.

Never done graphs before My result after getting the example input to work, and putting in the real input is Hilariously wrong.

>binding box
Meant to say bounding box

not sure what's wrong with my answer then. i think i'm just not filtering properly. which is quite retarded...since i've was attempting it all night.

part one was very easy but i'm having trouble with part 2. is there a way to sync up the workers that isn't extremely convoluted?

Are you handling pixels with equal distance? And ignoring them?

data = '''
Step F must be finished before step X can begin.
'''.strip()

from collections import defaultdict
from itertools import count
import re

data = [x.groups() for x in re.finditer(r'Step (\w) must be finished before step (\w) can begin.', data)]

class Node:
def __init__(self):
self.ch = ''
self.before = []
self.after = []
def __repr__(self):
return f"Node(ch={self.ch}, before={[x.ch for x in self.before]})"

def p1(data):
nd = defaultdict(Node)
for f, t in data:
nd[f].after.append(t)
nd[t].before.append(f)
for k,v in nd.items():
v.ch = k
v.before = [nd[x] for x in v.before]
v.after = [nd[x] for x in v.after]
nodes = list(nd.values())
result = []
while True:
g = [n for n in sorted(nodes, key=lambda x: x.ch) if all(x in result for x in n.before)][:1]
if not g:
return ''.join(x.ch for x in result), nd
result.extend(g)
nodes = [n for n in nodes if n not in g]

def getnew(nodes, w, done):
doing = [z[0] for z in w if type(z) == list]
pots = [x for x in nodes if x not in doing+done and all(y in done for y in x.before)]
if pots:
return [pots[0], 0]

def p2(nodes):
nodes = sorted(nodes.values(), key=lambda x: x.ch)
nw = 5
w = [None]*nw
done = []
for s in count():
for i in range(nw):
if w[i] is None:
w[i] = getnew(nodes, w, done)
else:
try:
w[i][1] += 1
except TypeError:
print(w[i])
if w[i][1] == ord(w[i][0].ch)-4:
done.append(w[i][0])
w[i] = None
w[i] = getnew(nodes, w, done)
if set(done) == set(nodes):
return s

if __name__ == '__main__':
p1r, nodes = (p1(data))
print(p1r)
print(p2(nodes))

Have you tried testing your solution against the inputs and answers that were posted 3 threads ago?

are you certain you're understanding my description of handling the infinites correctly? for everyone who had trouble with yesterday's puzzle, the issue was handling the infinites

It hasn't happened yet. I'm still here.

Attached: filter.png (539x60, 2K)

i initiate them to -1, and zip my points to range(len(points)) so they're between 0 and 49. equal distance i check the length of a list initialized with one element each time it finds an min distance to a point. so if they're equal distance apart then the list would contain more than one element.

[c for c in candidates if not c.brainlet]

make sure you're only triggering if there is a tie for the minimum. if you trigger any time there is a tie, even if its not the minimum, then it wont be right. that's the only obvious thing i can think of

can one of you wonderful NIGGERS post your data and part 2 solution

Attached: 1540556224719.png (340x290, 24K)

candidates.reject!(&:brainlet?)

Am I the brainlet for not knowing what language this is?

I liked this.
import re, string, time
with open('input.txt') as f:
parse = lambda x: tuple(re.findall(r'[A-Z]', x)[1:])
routes = [*map(parse, f.read().splitlines())]
def value_seconds(letter, offset):
return string.ascii_uppercase.find(letter) + offset
def double_map(routes):
return {chr for line in routes for chr in line}
def forwards(routes, workers = 2, offset = 0):
table = {k: set() for k in double_map(routes)}
for (req, key) in routes:
table[key].add(req)
accum, queue = "", dict()
for seconds in range(1000000):
queue = {k: v-1 for k,v in queue.items()}
for worker in queue.copy():
if queue[worker] < 1:
for rest in table.copy():
table[rest].discard(worker)
accum += worker; del queue[worker]
nexts = [*sorted(k for k,v in table.items() if not v)]
for i in range(min(len(nexts), workers)):
if len(queue) < workers:
queue[nexts[i]] = value_seconds(nexts[i],
offset+1) if isinstance(offset, int) else 0
del table[nexts[i]]
if not len(table)+len(queue):
return (seconds, accum)
print('part 1:', forwards(routes, workers = 1, offset = None)[1])
print('part 2:', forwards(routes, workers = 5, offset = 60)[0])

Attached: Head Scratch.gif (500x536, 1.21M)

The hero us brainlets need

I'm such a pajeet it causes me physical pain... it isn't even satisfying to solve a step when your code looks like street poo.

Attached: 1537490117304.png (560x560, 123K)

my.mixtape.moe/rapvjn.txt

code for just part 1 because part 2 is too messy
in =: 5 36&{&> cutLF fread 'input'
next =: [: {.@/:~ ~.@, -. {:"1
remove =: -.@e."1 # ]
''"_`(next , [: $: next remove ]) @. (0 < #) (, '_' ,.~ ~.@,) in


>my solution to part 1 was GLMVWXZDKOUCEJRHFAPITSBQNY
>FAPIT
our god has spoken

>for seconds in range(1000000):
for seconds in itertools.count()

I masturbated but I still don't know the answer to part 2.
I mean, I got a solution, but I don't think it's right

It's just Ruby
candidates.reject!(&:brainlet?)
candidates = candidates.reject(&:brainlet?)
candidates = candidates.reject { |c| c.brainlet? }

all same

For part 2 I'm getting 772. Apparently it's wrong.
pastebin.com/vtTexAV1

For each step, I gather all of the work-items and find the least impacted worker and simply add the value to the worker.
Then I bring everyone else who did not work up to speed with the lowest value of those who did work.
It's pretty simple. I don't know what I'm doing wrong, and it works for the example once I adjust `remaining`
def p2(data):
dependencies = defaultdict(list)
inverse = defaultdict(list)
global remaining
remaining = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
workers = [0] * 5
while remaining:
workset = [i for i in remaining if len(dependencies[i]) == 0]
worked = []
min_time = min(workers)
for i in workset:
least_worker = min(enumerate(workers), key=lambda x: x[1])[0]
worked.append(least_worker)
workers[least_worker] += work(i)
min_time = min([workers[least_worker], min_time])

for j in inverse[i]:
dependencies[j].remove(i)
remaining = remaining.replace(i, '')

for non_worker in set(range(5)) - set(worked):
workers[non_worker] = min_time

return max(enumerate(workers), key=lambda x: x[1])[1]

>772
actually 441 but still wrong

It took me two hours to make that. How am I a hero for brainlets? Unless you mean that, among the brainlets, I am a hero because I managed to finish it despite being a brainlet.

gotta try again until you get it, the high wears off after a bit

BEHOLD

paste.ofcode.org/5af8dXeudNi8hNbMPSpe5C

I refuse to be filtered one week in. I'm going to finish this by tomorrow

maurits.vdschee.nl/scatterplot/

>those two people who finished 3.5 minutes before anyone else

Weird.

Attached: bf.png (966x506, 36K)

i run your input and for some reason it doesn't work. i don't know why.

anybody wanna take a look?

spit.mixtape.moe/view/5ebd631d