[a / b / c / d / e / f / g / gif / h / hr / k / m / o / p / r / s / t / u / v / vg / vr / w / wg] [i / ic] [r9k / s4s / vip / qa] [cm / hm / lgbt / y] [3 / aco / adv / an / asp / bant / biz / cgl / ck / co / diy / fa / fit / gd / hc / his / int / jp / lit / mlp / mu / n / news / out / po / pol / qst / sci / soc / sp / tg / toy / trv / tv / vp / wsg / wsr / x] [Settings] [Home]
Board
Settings Home
/g/ - Technology



Thread archived.
You cannot reply anymore.



File: 1512636468870.jpg (34 KB, 720x540)
34 KB
34 KB JPG
Don't drop the dinnerware edition
Previous thread >>63714083

http://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.

The new leaderboard with empty space is
join-code:
 43046-941b8011 


The old (full) leaderboard is
join-code:
 194764-c554ff91 
>>
has anybody tried a recursive approach on python for part 2? Does it work or do you hit the recursion limit?
>>
>>63729519
I used recursion for finding weights and constructing a tree (which I didn't need), without any problems.
>>
File: D7P2.png (38 KB, 963x586)
38 KB
38 KB PNG
>>63729519
This works for me.

I'm still not sure where on a scale of brainlet to pajeet this places me, because this code looks ugly as fuck at first glance.
>>
File: D7P2.png (42 KB, 958x684)
42 KB
42 KB PNG
>>63729558
Whoops, forgot the first function
>>
>>63729519
Yes, here:
https://ghostbin.com/paste/stsza
>>
with open('adv7.txt') as tree:
names = []
weights = []
subbranches = []
for line in tree:
names.append(line.split(" (")[0])
weights.append(int(line.split("(")[1].split(")")[0]))
if "->" in line:
subbranches.append(line.split("-> ")[1].split("\n")[0].split(", "))
else:
subbranches.append(" ")

discs = dict(zip(names, weights))
subdiscs = dict(zip(names,subbranches))
namestorage = names[:]

flag = False
while names:
if flag:
break

for x in names:
if flag:
break

if subdiscs[x] == " ":
names.remove(x)

flag2 = True
else:
for y in subdiscs[x]:
if subdiscs[y] != " ":
flag2 = False
break
if flag2:
check = min([discs[z] for z in subdiscs[x]])
for z in subdiscs[x]:
if discs[z] > check:
flag = True
print weights[namestorage.index(z)] - (discs[z] - check)
break
discs[x] = discs[x] + discs[z]
subdiscs[x] = " "


Don't ask me how long this took.
>>
File: me.jpg (86 KB, 800x673)
86 KB
86 KB JPG
>>63729575
I just spent two hours debugging why my solution for day 7 problem 1 didn't work.
It turns out I forgot about the ',' at the end of some words.

It hurts to be a brainlet.
>>
>>63729604
It's okay m8, as I said in previous thread, I spent 30 minutes wondering why all my weights are 10 digits numbers and I thought I fucked up the recursion, until I realized I forgot to convert it to int, so it was concatenating the numbers instead of adding them together.
>>
>>63729604
Spent hours trying to figure out why my code was reporting loads of unbalanced nodes that had no relation to each other. Turns out I'd assumed the weights in the data file included the weights of everything above, instead of just the node's weight.
>>
Shit, I don't have any single dumb mistake I made, I was just dumb overall and slow to figure out how to solve it
>>
I don't know why I bothered checking, but there's a comment in the page source for anyone who bothered to check.
Oh, hello!  Funny seeing you here.

I appreciate your enthusiasm, but you aren't going to find much down here.
There certainly aren't clues to any of the puzzles. The best surprises don't
even appear in the source until you unlock them for real.

Please be careful with automated requests; I'm not Google, and I can only take
so much traffic. Please be considerate so that everyone gets to play.

If you're curious about how Advent of Code works, it's running on some custom
Perl code. Other than a few integrations (auth, analytics, ads, social media),
I built the whole thing myself, including the design, animations, prose, and
all of the puzzles.

The puzzles probably took the longest; the easiest ones took an hour or two
each, but the harder ones took 4-5 hours, and a few even longer than that. A
lot of effort went into building this thing - I hope you're enjoying playing it
as much as I enjoyed making it for you!

If you'd like to hang out, I'm @ericwastl on Twitter.

- Eric Wastl
>>
So on the topic of programming challenges (which I haven't done before AoC), I figured I'd try Project Euler.
For Problem 2 (https://projecteuler.net/problem=2), I got the following code:
def fib(x,y):
yield x
yield y
while True:
z=x+y
yield z
x=y
y=z

sum = 0
for y in fib(1,2):
if y%2==0:
sum +=y
if y>4000000:
break
print(sum)


It just feels wrong somehow, but I'm not sure how. I mean it got me the right answer, but I feel there's definitely a better way.
>>
Eric we love U
>>
can people explain their coding strategies in plain english? What algos are you using? Traversing tree bottom-up or top-down? Recursively? etc
>>
>>63730013
Have a recursive function that calculates the total weight of a node (as its own weight plus total weight of its direct children, if any).

During the calculation process, if this function finds that children's weight is unbalanced, it stops execution and alerts the user.

Call this function on the root node.

That's it.
>>
Stackoverflow is offline. How am I supposed to solve this puzzles?
>>
>>63730067
Up for me.
>>
>>63730067
pajeet, my son...
>>
>>63730037
thanks, I was going about it the wrong way... Was gonna build the whole tree, then calculate every tower weight, etc
>>
>>63730093
Yeah it went into maintenance for a second
>>
>>63729797
Python's yield is really nice.
>>
>coding challenge
>have to balance a fucking TREE
fuck this math bullshit
>>
>>63730431
Balancing a tree actually means something else entirely.
>>
>>63730431
who told you that
>>
File: plantoys-balancing-tree.jpg (119 KB, 1200x1200)
119 KB
119 KB JPG
>>63730431
>math is hard
>>
File: 121314.png (21 KB, 1082x137)
21 KB
21 KB PNG
So what is the right answer for the test input? 243 or 60?
>>
>>63730578
Is it asking you for the weight of the program or the weight of the program and all its children programs?
>>
>>63730578
60
>>
>>63730595
I'm a filthy ESL so I got confused.

>>63730601
Thanks.
>>
finally did it, now I have to go back and do yesterday's challenges, was too lay to do them
>>
File: 1511722672118.jpg (101 KB, 668x1370)
101 KB
101 KB JPG
>test input gives the right answer but the real one doesn't
>>
>>63730578
60, the stack needs to weigh 243 and to achieve the thing you need to go from 68 to 60 so that the children weight with the disc's weight goes down from 251 to 243
>>
File: birch.jpg (81 KB, 634x672)
81 KB
81 KB JPG
>hang on, the stack weight of all the children is equal... how can I adjust that without unbalancing the rest
>mfw I forgot that nodes themselves have weight
>>
[laughs in code]
>>
>>63730614
>sort
>log n
>>
File: 1213145161.png (97 KB, 1668x1092)
97 KB
97 KB PNG
>Given that exactly one program is the wrong weight
Then why all these five nodes have different sums? Can someone check my input? What is the answer?
https://pastebin.com/BcbqviyV
>>
>>63730614
so day 7 can be sorting in log n time
>>
>>63731225
did you seriously draw your graph out by hand you fucking ape
>>
>>63727506
>>from advent import *
>What is advent here?
A collection of random helper functions.
https://pastebin.com/FG8AL6Bb
Most useful so far have been get1 and get2 for reading in 1D and 2D arrays of data.
>>
>>63731249
I'm trying to figure out what's wrong with it. I'm getting a node where all childrens sums are different (including the parent node).
>>
>>63731225
Weight of a stack includes the weight of EVERYTHING in the stack, not just the base. All children of ifyja have total weight 412.
>>
>>63731288
Fuck.
>>
def getSumLeg(data, value_pair, parent):
ret_v = 0
if data[parent] != None:
for v in data[parent]:
ret_v += getSumLeg(data, value_pair, v) + value_pair[v]
else:
return value_pair[parent]
return ret_v


data is a dict with the key/value pair data[parent = (children), if a parent has no children it's value is None.

value_pair is a dict with the key/value pair value_pair[parent] = int(parent value).

If I run this once for every child of the topmost parent I am supposed to get the total value of that child and all it's children and children's children.

I am not used to recursive functions, what is wrong with my implementation? Because it's giving me completely different values for all the topmost parent's children.
>>
Well fuck the entire file with tests and runninig won't fit in the reply so here's the relevant part, any idea how to tidy it up?

from util import to_string_rows, get_input_string_rows, test, run
from itertools import combinations
from re import compile

def main():
input = get_input_string_rows(7)

RE_DISC = compile(r'(\S+) \((\d+)\)( -> ([\S ]+))?')

class Disc(object):
def __init__(self, name, weight, children):
self.name = name
self.weight = int(weight)
self.children = [] if children is None else children.strip().split(', ')
self.parent = None

def get_children(discs, disc):
return [discs.get(child) for child in disc.children]

def get_weight(discs, disc):
return disc.weight + sum([get_weight(discs, child) for child in get_children(discs, disc)])

def get_root_name(discs, root):
return root.name

def get_weight_correction(discs, root):
prev = dict()
while True:
weights = {child.name: get_weight(discs, child) for child in get_children(discs, root)}
values = weights.values()

diff = max(values) - min(values)
if diff == 0:
return root.weight - (max(prev.values()) - min(prev.values()))

prev = weights
root = discs.get(list(weights.keys())[list(values).index(max(values))])

return 0

def solve(input, fun):
discs = {
m.group(1): Disc(m.group(1), m.group(2), m.group(4))
for m in [RE_DISC.match(row) for row in input]
}

for disc in discs.values():
for child in get_children(discs, disc):
child.parent = disc

root = list(filter(lambda disc: not disc.parent, discs.values()))[0]
return fun(discs, root)
>>
What if a disk hold only two subtowers ?
If this is the case we can't know wich tower is unbalanced ?
>>
>>63731666
Doesn't matter. The disks will become balanced if you adjust either.
>>
>>63731360
def getSumLeg2(data, value_pair, parent, tier):
ret_v = 0
if tier == 0:
ret_v += value_pair[parent]
tier += 1
if data[parent] != None:
for v in data[parent]:
ret_v += getSumLeg2(data, value_pair, v, tier) + value_pair[v]
else:
return 0
return ret_v

I sovled it myself, however its pajeet tier.
>>
Daily pajeet code in Python:
https://github.com/Smatchcube/Advent-of-Code-2017/blob/master/day7.py
Part one only, i will solve part two later.
>>
>>63731411
Cleaned it up a bit, not sure how I can make it any better, I guess I'll leave it at that.
>>
File: Untitled.png (164 KB, 1920x1030)
164 KB
164 KB PNG
>>63731868
Aaand I'm a fucking retard.
>>
got all my starts so far. Just finished day 6 cause I was too lazy yesterday, and fuck me, part 2 was the stupidest thing ever.
>>
https://www.youtube.com/watch?v=dO5ZauOP2BA

If you guys didnt't score top 10 global today you're worse than a literal pajeet.
>>
File: 1512643820898.jpg (184 KB, 720x540)
184 KB
184 KB JPG
>>63729483
I improved the calendar image
>>
>>63732271
Don't think I'm worse than someone who sits there refreshing a page until midnight desu
>>
File: 1512567851011.png (811 KB, 2188x1650)
811 KB
811 KB PNG
>>63732297
>>63729483
>>
>>63732271
Do you want us Europeans to stay up past 6 am or go up before 6 am?
>>
File: scrot.png (493 KB, 704x863)
493 KB
493 KB PNG
took me a bit to figure out how to recurse
>>
>>63732497
Every American gets up before 6 am you lazy eurocuck
>>
>>63732523
Ah, and then stays up past midnight I presume?
So all Americans get less than 6 hours of sleep.
Land of the free
>>
File: 1503779242961.gif (3.1 MB, 400x300)
3.1 MB
3.1 MB GIF
>>63729604
iktf anon (>>63721151)
>>
>>63730431
this, didn't sign up for math shit
>>
File: 1508575796295.png (42 KB, 586x627)
42 KB
42 KB PNG
>>63733480
>>
File: Capture.png (11 KB, 684x164)
11 KB
11 KB PNG
What's the deal with day 5 and 6 part 2? Day three and today are definitely harder, and the part 2 sections are just tiny extensions of the original problems. What's everyone having such an issue with?
>>
>>63733739
Nevermind, I'm an idiot. Silver are people who have completed only part 1, I got it backwards.
>>
I dont get, what does part2 wants me to find?

I found faulty program name inside the children of root, it weights +8 more than needed. I deduct the weight from the faulty value and submit but it says wrong
>>
>>63734229
You need to also check the entire tree recursively (each branch that weight more or less than others) because the weight can be unbalanced at any branch of the tree.
>>
>>63734265
I mean, that you need to find where the tree begin to be unbalanced.
The problem is really hard to explain.
>>
>>63734282
Yeah I still dont get it.
>>
>>63734229
you have to compute the weight of the whole subtree
>>
>>63734326
So I did
avpklqy:48284
tytbgx:48284
bdohoaa:48284
smaygo:48292
pvvbn:48284
hgizeb:48284
tchfafn:48284

>>
>>63734351
just check the unbalanced branch to see if there is an unbalanced branch inside.
In your example you should check the 'smaygo' branch
>>
>>63734368
Oh I see
>>
Is there really only 1 unbalanced node?

Am I looking for the deepest node that has an unbalanced weight?
>>
>>63734503
Correct and correct.
>>
I've never written a tree data structure or learned how to traverse one using recursion.

every single branch seems to have a mismatched weight and I know that's wrong

what am I doing wrong?

unsigned node_weight(struct prog *node, unsigned weight)
{
if (!node)
return 0;
unsigned i;
for (i = 0; i < node->deps; i++)
{
weight += node->sub[i]->weight;
node_weight(node->sub[i], weight);
}
return weight + node->weight;
}
>>
File: 5943726.jpg.png (257 KB, 832x680)
257 KB
257 KB PNG
>stuck on day 3
>tfw brainlet
>>
>>63734762
you're not storing the return of node_weight() anywhere in your loop, not exactly sure what you're trying to do. Also, you should store the weight of each node above a node in the node itself, you won't be able to do much with just the total in the end, or if you're running it every time you traverse down a branch, you're wasting a lot of cycles.
>>
>too lazy to write a function to retrurn the unbalanced node.
>type the unbalanced branch manually until the the rest of the tree is balanced.
>calcule the difference in the python interpreter manually to find what the weight should be.
>this "just" work
>i hate being a brainlet, i want to kill myself
>knowing that genuises solve can solve the problem under 3 minutes make me even more sad.
>>
Ok I think I finally solved it, was busy all day

Can someone give me their input and answeers to double-check?
>>
File: rmyt.png (175 KB, 600x600)
175 KB
175 KB PNG
>>63734784
Keep at it my friend
>>
>>63734940
https://pastebin.com/raw/wRRMCMDH
Part One: dgoocsw
Part Two: 1275
>>
>>63734762
post kode for the node struct,
don't pass weight since the way you use it doesn't really make sense
don't directly grab the child node weight, get it indirectly from the return value of your recursive func
return only cur node weight + sum of children weight
in the loop you still need an accumulator but should be initialized to 0 before looping; acc+=node_weight(node->sub[i]);
...
return node->weight + acc;
>>
>only one program needs to have its weight changed to balance the tower
>every subtower supported by the bottom program has a distinct weight for me

The example input checked out, unless I'm misunderstanding balancing here there's no way changing one weight is gonna balance the tree.
>>
>>63734991
>Faulty lowest child: szmnwnx, its weight: 3808, correct weight will be 3800

I know why, I even left a comment that the logic for deviant sum must be revisited later. Unfortunately no time left for today
>>
>>63735020
What's your input?
>>
>>63735033
I don't know how your programm work but the difference is 8 as in your output, maybe your programm is not counting the end of the tree ?
>>
>>63735048
https://pastebin.com/jeHW3kCd
>>
>>63735070
Nah it is this shit:

if (lweight > 0 && curWeight != lweight) // this is wrong, the check does not account first encounter of bad weight!
{
steps = map[name].Value.Length-1; deltaW = lweight; faulty = curProg = name; lweight = 0;
continue;
}
>>
>>63735084
My code correctly finds only one fitting program, are you sure you're understanding the problem correctly? There's been a lot of goofy mistakes in today's challenge.
>>
>>63735094
That's a fucking brainlet error man.
But i'm also a brainlet so that's why i runed the programm manually. I'm now trying to find the solution in python.
>>
>>63735124
The example worked out as it should, but I'll check my recursion to see if something funky happened.
>>
>>63735144
Well i wont have any time to fix today and tomororw as well and by next day I will move on
>>
>>63735084
All your branches except one should have the cumulative weight "119424". Hope that helps.
>>
I think the fact that the example has even weights for all the children is confusing people trying to complete part 2
>>
Refactored my problem 7 code from this morning >>63727865
but it barely got any simpler
>>
>>63735507
You are just a brainlet
>>
can part2 be done without nodes?
>>
>>63735778
What data structure did you use for part 1?
>>
I'm so dumb that i have used set, dict and list only for the part one.
>>
>>63729483
Whoever wrote problem 7 could have fucked some people up if he wanted to by allowing for the possibility of the incorrectly weighted disc being above a disc with two towers, but it looks like nobody had such an input
>>
is there going to be a challenge that weeds out cheaters by giving different puzzle inputs to people

suppose it could backfire if someone genuinely fucks up their code enough to get a different correct answer
>>
>>63736026
Everyone already gets a random input you faggot
>>
>>63735894
hashmap and treeset
>>
Well that took an embarrassingly long time for me to do, also just had the tree traversal printed as it went because maintaining state for the right thing to return to solve the puzzle would be a bitch.
>>
>>63736173
I did it in python with just dictionaries, you should be able to extend your Java (?) solution with the data structures you have
>>
annoying problem with my recursion ( not done it since uni)

class Node:

children = []
childdata = []

def __init__(self, name, weight, *childdata):
self.name = name
self.weight = int(weight)
self.childdata = childdata
for i in self.childdata:
t = Node(*d[i])
self.children.append(t)


variable d is a dictionary using the node as a key, its values being the whole line as an array.

the recursion is working, but when I check the tree afterwards, the root node contains 1000+ children. anyone help me out?
>>
I have solved the problem but i would like to test my programm, can you give me the input and your solution for both parts pls.
>>63734991 is my input file so no need to reply this file
>>
>>63736247
what does the asterisk mean? python has pointers?
>>
>>63736361
it unpacks a list so it can act as several args. any ideas on why it's shoving every node into the root's children list?
>>
This one was fun. I kind of shot myself in the foot doing it in Go and not having a lot of experience with pointers but at least now I'll never get them wrong again.
>>
Give me input file and solution please, i need it.
>>
>>63736247
https://docs.python.org/3/tutorial/classes.html
See 9.3.5
>>
>>63736454
https://pastebin.com/raw/2i8x1h5t
hmvwl
1853
>>
>>63736454
Here is one from reddit : https://gist.githubusercontent.com/angch/214faafbf98e91888a44c9adf0924d35/raw/aa7a77471bf723c6554e719cd9d50f25b9a048fb/adventofcode2017day7input.txt
soluion are 'mkxke' and 268.
I'm so happy to have a working code.
>>
>>63736490
You beauty! I'll save santa in your name, anon.
>>
>>63736496
Don't know if your file is broken or if it's a joke but your file miss the mofkds node.
>>
>>63736693
Got you! :^)
>>
Day 6

why isn't my code working?
I have checked all the steps


here is the shitty code I wrote:

<?php

$a = '0 2 7 0';
$table = array();
$table = preg_split('/\s+/', $a);
$values = array();

$howmany = count($table);
$i = 0;
while(!in_multidimensional_array($table, $values)) {
$values[] = $table;
$max_key = array_search(max($table), $table);
$max_value = $table[$max_key];

print_r($table);

$count = 0;
foreach($table as $key => $value) {
if($key == $max_key) {
if($max_value < (count($table) - 1)) {
$table[$key] = 0;
} else {
$table[$key] = $max_value % (count($table) - 1);
}
} else {
$wow = $max_value - count($table) + 1;
if(($wow < 0 && $count < $max_value) || $wow >= 0) {
$fgt = $max_value / (count($table) - 1);
if($wow < 0){
$table[$key] += ceil($fgt);
} else {
$table[$key] += floor($fgt);
}
$count++;
}
}
}
$i++;

}

function in_multidimensional_array($array, $multidimensional_array) {
foreach($multidimensional_array as $idkhowtocallthis) {
if($array == $idkhowtocallthis) {
return true;
}
}
return false;
}

echo $i;
>>
I have added my second part in python, brainlet edition : https://github.com/Smatchcube/Advent-of-Code-2017/blob/master/day7.py
My first part is clean but the second part is ugly
Today's problem was really fun imo.
>>
File: 1511387714055.jpg (101 KB, 1280x720)
101 KB
101 KB JPG
>>63736754
>
<?php

>
preg_split('/\s+/', $a);

>$wow
>$fgt
>
$idkhowtocallthis
>>
Post your setup for the event.

Wath is this kind of "asci art" this year ? It looks like nothing at the moment.
>>
>>63736893
The theme of the story is repairing a printer.
Looks like a printed circuit.
>>
File: reimu.jpg (318 KB, 500x638)
318 KB
318 KB JPG
day 7 part 1
learning powershell
$tail = Get-Content .\input.txt | foreach { $_.split()[2..($_.length-1)] }
Get-Content .\input.txt | foreach { $_.split() | select -First 1} | foreach { if (-not($tail -match $_)) {$_} }
>>
>tfw anonymous user stole my top 20 spot again
feels bad man
>>
>>63736893
>>
Holy shit

300+ Lines of C Code
Please tell me I'm not a fucking moron

Solution WAYYY too long to post here, so please feel free to shit on my code here:
https://github.com/CubicProgramming/adventOfCode2017/blob/master/Day7.c

Basic algorithm:
Store each "program" in an array. Write downt he names of a program's children
--Find each program's children and load it into the program structure
--Use recursion the find the weights (updateWeights)
--Sort the programs by their weight. This allows us to do an O(1) search for unbalance
----If it's sorted, then any unbalance is either at the beginning or the end (because the entries in the array are all the same except for one)

Then, simply find the children and go further down until you stop finding unbalancing
>>
wtf the unbalanced disc is literally always the first fucking one. I can remove half of my code ffs.
Fucking nigger codemonkey tier """puzzle""", when will these get harder?
>>
File: 2 SECONDS.png (10 KB, 563x47)
10 KB
10 KB PNG
>>63732271
Wew lad
>>
>>63737338
mine was the second disc.
>>
>>63736836
hahahahaahhhahh LOL
I have warned you
>shitty code
>>
>restructure git repos of previous years to combine into a single repo
>no folder 25 last year
>remember that I did it on paper and never took a picture of the notes
shit, maybe I should resolve it
>>
File: atree.png (25 KB, 238x403)
25 KB
25 KB PNG
Every fucking time I see shit like this it'll waste me some time to figure out how to pritn it.
https://ghostbin.com/paste/zvn4f
>>
>>63737578
just output to a graphviz dot file
>>
File: magi.jpg (40 KB, 1024x576)
40 KB
40 KB JPG
>>63729483
Hey guys, just finished part 2, please rate my solution. Part 1 was easy, but part 2 took me a couple hours.
Was there an easier way to solve this?

f = open('input', 'r')
lines = f.read().splitlines()
f.close()

lines_dict = {}
graph_table = {}

# Parse input
for line in lines:
line_list = line.split()
name = line_list[0]
weight = int(line_list[1][1:-1])
child_list = []
for i in range(3, len(line_list)):
if line_list[i][-1:] == ',':
child_list.append(line_list[i][:-1])
else:
child_list.append(line_list[i])
lines_dict[name] = (weight, child_list)

# Generate graph table
for i in lines_dict:
graph_table[i] = {}
for j in lines_dict:
if i != j:
graph_table[i][j] = None

# Fill graph table and find root node
temp_list = []
root = None
for (item, (weight, children)) in lines_dict.iteritems():
for child in children:
temp_list.append(child)
graph_table[item][child] = lines_dict[child][0]
for i in lines_dict.keys():
if i not in temp_list:
root = i
break

# Check balance
def getTotalWeightAtThisNode(node):
total = 0
temp_dict = {}
for i in graph_table[node]:
if graph_table[node][i] is not None:
temp = getTotalWeightAtThisNode(i)
if temp[0] == 'done':
return temp
total += temp[1]
temp_dict[temp[1]] = (lines_dict[i][0], temp_dict.get(temp[1], (lines_dict[i][0], 0))[1] + 1)
if len(temp_dict.keys()) > 1:
diff_arr = sorted(temp_dict.iteritems(), key=lambda (key, (weight, count)): count)
diff_amt = diff_arr[0][0] - diff_arr[1][0]
return ('done', diff_arr[0][1][0] - diff_amt)
total += lines_dict[node][0]
return ('notdone', total)

print getTotalWeightAtThisNode(root)[1]
>>
FUCK I wrote nearly the exactly right thing for part 2, worked for test solution but not for the actual input, and I just forgot to sort by weight before I grouped the values

Was pretty fun, I've never actually used trees in haskell and they're pretty good to work with
>>
who here /set/?
#!/usr/bin/env python3

parents = set()
children = set()
parenthood = set()
weights = dict()

for line in open('input'):
arr = line.split()
parents.add(arr[0])
weights[arr[0]] = arr[1][1:-1]
if '->' in line:
for child in arr[arr.index('->')+1:]:
children.add(child.strip(","))
parenthood.add( (arr[0], child) )

print("Bottom is {}".format(parents - children))
>>
>>63729483
Whoever runs 194764-c554ff91 should kick out the 7 or so people who don't have a single gold star yet, to make room for active users
>>
>>63738007
i'd say just go ahead and axe people who don't have at least one star for five days
>>
>>63738007
>>63738215
I'd like to keep the list like that to see what it will look like on the 25th. There's a lot of room in the other leaderboard anyway. Also I don't want to bother writing scripts to manage the list.
>>
>>63738007
There's plenty of room in the other board
>>
File: WAAAAAAAAAAH.jpg (297 KB, 1280x720)
297 KB
297 KB JPG
>you have submitted too many incorrect answers you have been disqualified from completing this puzzle
>>
>>63738349
How many?
>>
>>63738349
poor lil thing
>>
I would fucking fire the person who gave me day 7s data in that format. Bitch you ever heard of JSON?
>>
Is
┤|├
supposed to be a battery?
>>
>>63738349
Th-this isn't a thing is it?
>>
>>63738901
I agree it would be nice for a standardized input, but it's not that hard to regex it out.
>>
>>63739520
Reading the input is like half the challenge.

People keep saying it's the hardest part.
>>
>>63739774
it's not if you write boilerplate ahead of time to tokenize input and read it in line by line.
Or just use a language that does this already.
>>
>>63739804
What would be a good language to do this directly?
>>
>>63739921
do what directly?
>>
What does everyone hope to achieve by doing this stupid thing? Redditors are just going to come and steal your solutions, posting it to their GitHub claiming it’s theirs.
>>
>>63739934
Tokenize input without having to write boilerplate code
>>
Finally got around to doing Day 6 Part 1 in Haskell. I feel like this is really stupid but it works so whatever.

import           Data.List
import qualified Data.HashMap.Lazy as M
import Data.Hashable

main :: IO ()
main = do
banks <- readFile "Input.txt" >>= (\x -> mapM readIO $ words x) :: IO ([Int])
print $ reallocate 0 M.empty banks

reallocate :: (Integral a) => a -> M.HashMap [Int] a -> [Int] -> a
reallocate n map banks
| M.member banks map = n
| otherwise = reallocate (n + 1) (M.insert banks n map) (distribute max (ind + 1) banks)
where
max = maximum banks
ind = head $ elemIndices max banks

distribute :: (Integral a) => Int -> Int -> [a] -> [a]
distribute n i x = foldr (zipWith (+)) (replicate size 0) grouped
where
size = length x
cycles = ceiling $ (fromIntegral (n + i)) / (fromIntegral size)
adds = (replicate i 0) ++ (replicate n 1) ++ (replicate ((cycles*size) - (i+n)) 0)
grouped = groupByN size ((replaceNth (i - 1) 0 x) ++ adds)

replaceNth :: Int -> a -> [a] -> [a]
replaceNth n new (x : xs)
| n == 0 = new : xs
| otherwise = x : replaceNth (n - 1) new xs

groupByN :: Int -> [a] -> [[a]]
groupByN _ [] = []
groupByN n x = (take n x) : (groupByN n (drop n x))
>>
>>63738901
>>63739774
>complains about how the problems require too much math
>proceeds to complain about the non-math portion of the problems being too hard
come on my man
>>
>>63739987
This, dishonest people who do software development for a living are going to steal people’s solutions using it in their work while the people who did it stay at home being NEETs. This is pretty much what happens in Silicon Valley, these people steal like crazy.
>>
>>63740036
>This is pretty much what happens in Silicon Valley, these people steal like crazy.
This 100x, a common tactic is to give people “take home assignments” and to steal the things that the candidate did for free. Some companies can pretty much just rely on that completely.
>>
>>63740077
There's absolutely no way in hell you can create an entire deliverable from take-home assignments.
It's much easier to hire unpaid interns and then fire them for a round of new ones.
>>
>>63740091
They don’t directly copy the assignments to get the deliverables, it’s more the design and ideas for how to implement things that they steal from candidates. Obviously the better ideas the candidates give them the less need there is to actually hire the candidate.
>>
>>63740077
I once had a company in SV interview me, they gave me an assignment to write a whole websocket chat server. Another assignments I’ve completed (and subsequently didn’t get hired for the position) was a TCP client like software. One startup even put me in front of their actual production code and told me to implement a feature. None of the aforementioned companies actually hired me.
>>
>>63740177
Were those take home tests? Websocket chat server is like 10 lines of code in node.js
>>
>>63740207
The first two yes, the third it was in person. However trivial it is they are mainly looking for good ideas to steal.
>>
30 minutes. It's going to be a hard one today, I can feel it.
>>
for yesterdays
https://pastebin.com/c5pDExaa
any suggestions?
>>
>>63740177
Also, don’t assume all companies in the Bay Area are dishonest, some of them have SJW infiltrators in them that will sabotage the good candidates by leaving negative and false feedback to help the competition
>>63740307
Yes, keep posting solutions for the redditors to steal, I’m sure it will bring you good karma. (It will actually do the opposite)
>>
>>63740350
its nearly time for the next one, how long do you expect me to wait?
>>
>>63740386
Why are you even talking to the shitposter?
>>
File: notears.png (185 KB, 274x300)
185 KB
185 KB PNG
>tfw never finished part2 from today
>tfw lost resolve to continue

good luck, lads
>>
>>63740411
you can do it anon
>>
>>63740411
kek this. im trying to figure out an efficient way to build the actual tree.

here is the class file:

public class TreeNode {

String name;
int weight;
ArrayList<TreeNode> children;

public TreeNode(String name, int weight) {
this.name = name;
this.weight = weight;
this.children = new ArrayList<TreeNode>();
}

public void addChild(TreeNode newChild) {
children.add(newChild);
}

public void print(String prefix, boolean isTail) {
System.out.println(prefix + (isTail ? "└── " : "├── ") + name);
for (int i = 0; i < children.size() - 1; i++) {
children.get(i).print(prefix + (isTail ? " " : "│ "), false);
}
if (children.size() > 0) {
children.get(children.size() - 1)
.print(prefix + (isTail ?" " : "│ "), true);
}
}
}
>>
>>63740411
Don't give up anon, I'm in the same spot. Going to jump in and do tonight's and then tomorrow go back and keep hammering at yesterday's.
>>
5 minutes
>>
File: yuuri_attac.png (685 KB, 1062x1220)
685 KB
685 KB PNG
everyone get ur snac ready
>>
put on your programming music and your programming socks
>>
>>63740469
The way I did it was create a flat list of program structs from parsing the input, each struct holds a static list of node names it's supposed to be a parent of

then when every node is accounted for, I just add pointers to every node mentioned in the static node name list

this creates a directed graph, or an k-ary tree, as I understand it.
i couldn't into recursion at first, so I just determined the root node by finding the single node name that wasn't referenced by any other node.
>>
>>63740543
>don't have any programming music
>don't have any programming socks
Am I doomed?
>>
1 Minute remains. Good luck.
>>
File: 1511968345884.png (230 KB, 1200x1486)
230 KB
230 KB PNG
>>63740543
That's my secret
I'm always wearing programming socks
>>
LETS GO BOYOS
>>
this isnt even hard its just annoying
>>
File: day8.png (7 KB, 573x52)
7 KB
7 KB PNG
WINNER WINNER CHICKEN DINNER
>>
>>63740603
Holy shit anon
>>
>>63740603
Frick
>>
Do I have to act on a register if it hasn't been declared yet?

This is important.
>>
File: day8code.png (53 KB, 958x1184)
53 KB
53 KB PNG
>>63740603
>defaultdict so I don't need to know register names up front
>parsing with split() + destructuring assignment
>mother fucking eval avoids a 6-way branch on conditional types
God I love python

>>63740674
Yes. All register names are valid at all times, and they all start initialized to zero.
>>
>>63740674
They're all initialized to 0, so they're all declared
>>
rank 208/211 fuck me

I used AWK again and it was perfect except that I had to spend time manually mapping from strings to conditions.

34 lines all told
>>
i wish i was as smart as you
>>
Rank 236 today. By this rate of improvement, I should reach top 100 on Sunday.
>>63740681
That's a really nice solution, anon.
>>
And done

Fuck, parsing that was difficult.

Well, difficult for a brainlet like me.
>>
>>63740741
Also, 544/507 (personal best!)
>>
Got slowed down because I was comparing the register's name and the number instead of the register value RIP.
>>
done but i still didn't do yesterdays ><
>>
File: 1495956511285.jpg (98 KB, 545x476)
98 KB
98 KB JPG
>>63740785
Yeah I spent the longest fucking time debugging the fact that I was changing the number from the conditional check, not the one at the beginning of the command.

At least I made the leaderboard tonight! Now to go back to part two from yesterday.
>>
I'm still designing the symboltable lookup. :(
>>
File: 1512199548850.png (6 KB, 209x171)
6 KB
6 KB PNG
whew back to top 15 :3
>>
Oh wow, I didn't even know eval() was a thing. That would have been useful to know.
>>
File: advent-stats-dec8.png (26 KB, 685x661)
26 KB
26 KB PNG
Dec 3 broke the gold stars but gold+silver is still monotonic. How many hours until Dec 8 beats Dec 7?
>>
File: enjoyee.jpg (471 KB, 750x750)
471 KB
471 KB JPG
comfy problem done, time to cook nice food
>>
I'm off to bed, anons. Gotta be rested for tomorrow's challenge.

input = File.read('input.txt').chomp

vars = Hash.new
vars.default = 0
highest = 0

input.each_line do |line|
matches = /^(\w+) (\w+) (-?\d+) if (\w+) (.+) (-?\d+)/.match(line)
highest = [highest, vars.values.max].max if !vars.empty?

if vars[matches[4]].public_send(matches[5], matches[6].to_i)
vars[matches[1]] += matches[2] == 'inc' ? matches[3].to_i : -1 * matches[3].to_i
end
end

puts vars.values.max
puts highest
>>
>>63740882
Why do you think it will? Day 7 wasn't any harder than this one, I'd say.
>>
I've been busy for the past couple of hours, and I won't be able to do today's problem until tomorrow.

How bad is it lads?
>>
rust was a mistake: https://pastebin.com/Pr9jZYA4
>>
>>63740948
Really easy.
>>
>>63740850
I knew it was a thing but forgot how to use it
I thought I could just do eval(cond) and have it insert the conditional operator directly in the line, but as other anon showed it has to be a full expression
>>
File: sad_parser.png (29 KB, 600x385)
29 KB
29 KB PNG
>>63740948
>>63740955
this, especially if you have a nice language and can just call eval
>>
>>63740931
You're not thinking like a brainlet. Trees are hard.
>>
File: 1480529706908.jpg (16 KB, 251x242)
16 KB
16 KB JPG
>>63740951
Ayy.
>>
>>63740971
>Nice language
>I'm challenging myself by only using C
Guess I'm fucked then
>>
>>63740931

Compare the two-star leaderboard.
http://adventofcode.com/2017/leaderboard/day/7
http://adventofcode.com/2017/leaderboard/day/8

Day 7 is objectively harder. The 100th user had two stars on day 8 before the first user had two stars on day 7.
>>
File: 9id48r1ewyoy.png (154 KB, 1576x344)
154 KB
154 KB PNG
>>63729483
Any ideas for the calendar image /g/-famalam?
>>
>end up spending a few hours on day 7 part 2 (in good part because I didn't realize iterating through generator expressions in Python empties them)
>today's was actually pretty damn simple

I did part of 2015's and it seemed like it was harder by this point, though that's probably a good thing because fuck that JSON accounting one.
>>
>>63740980

Doing it in C is fine unless you want to get in the top 100. You just have to spend an extra minute enumerating conditionals.
>>
>>63740985
Oh wow. People were really slow yesterday. My today's solution was actually longer than my yesterday's.
>>
>>63740999
You could go the intellectually lazy route and have a surgeon / game of Operation over a cash register
>>
>>63741011

It was intentionally not straightforward to parse, and if you aren't good at data structures you could wind up making life harder for yourself on how you build the tree.

Language choice also mattered for that one. For me I had to choose between easy parsing in AWK and better structs in C. In the I wound up doing everything with associative arrays in AWK but some of it felt like bashing my head against the wall. I almost think I should have just used AWK to preprocess it to something easier to read in C.
>>
File: comfy kotatsu :3.jpg (351 KB, 813x861)
351 KB
351 KB JPG
>C code works and spits out the right answer on your first compile with zero errors

is there anything more comfy?
>>
File: 1497494661024.jpg (24 KB, 350x256)
24 KB
24 KB JPG
I stayed up all night for this. At least I'll probably go up a few places in our board since I'm not starting working 16 hours after the problem is unlocked.

What should today's calendar image be? Something like this?

>>63740603
Holy fuck, congratulations.
I'm so slow, it took me almost 2 minutes to do part 2.
>>
package main

import ("fmt"
"strconv"
"io/ioutil")

func eval(sign, current string, amount int, register map[string]int) {
if sign == "dec" {
register[current] -= amount
} else {
register[current] += amount
}
}

func main() {
var lines [][]string
data, _ := ioutil.ReadFile("AdventOfCode8.txt")
currentword := ""
var currentline []string
for _, char := range data {
if char == '\n' {
currentline = append(currentline, currentword)
lines = append(lines, currentline)
currentline = nil
currentword = ""
} else if char == ' ' {
currentline = append(currentline, currentword)
currentword = ""
} else {
currentword += string(char)
}
}
register := make(map[string]int)
for _, l := range lines {
register[l[0]] = 0
}
max := 0
for _, l := range lines {
current := l[0]
reference := l[4]
cond, _ := strconv.Atoi(l[6])
comp := l[5]
sign := l[1]
amount, _ := strconv.Atoi(l[2])
switch comp {
case "==":
if cond == register[reference] {
eval(sign, current, amount, register)
}
case "<=":
if cond >= register[reference] {
eval(sign, current, amount, register)
}
case ">=":
if cond <= register[reference] {
eval(sign, current, amount, register)
}
case "!=":
if cond != register[reference] {
eval(sign, current, amount, register)
}
case ">":
if cond < register[reference] {
eval(sign, current, amount, register)
}
case "<":
if cond > register[reference] {
eval(sign, current, amount, register)
}
}
if register[current] > max {
max = register[current]
}
}
fmt.Println(max)
}


Does Go have and equivalent to eval()?
>>
File: 1502657762663.jpg (36 KB, 397x500)
36 KB
36 KB JPG
>>63740999
>>63741082
>>
>>63741082
Definitely something about Chad eval and virgin switch.
>>
Too easy desu senpai
>>
File: x86_64_registers.png (125 KB, 1280x450)
125 KB
125 KB PNG
>>63741049
>>
File: 1481453155428.png (21 KB, 803x309)
21 KB
21 KB PNG
Hey I was right. I wonder if this will be the input to the last day or something.

>>63741074
When you're using a language that isn't C which compiles and spits out the correct result on your first try.
>>
>>63741111
if conditional == "==" {
if operation == "inc" {
//...
} else if operation == "dec" {
//....
}
} else if conditional == "!=" {
if operation == "inc" {
//...
//....
>>
>>63741111
>tfw can use switch for strings in sepples
JUST
>>
>>63741138
Oh jeez
>>
>>63741138
hahahaha
>>
Absolutely ENTERPRISE

https://pastebin.com/dJYhtaMc
>>
The people complaining about parsing the input string are not going to be happy today
>>
File: 1486421301260.jpg (108 KB, 1280x720)
108 KB
108 KB JPG
>>63741138
Nice
>>
>>63741179
Eh, it's easier than yesterday since all the separators are spaces (and newlines).
>>
How are people writing this shit in under 2 minutes?

eval?
>>
>>63741138

It doesn't have to be so bad.
if ((c == "==" && a == b) || (c == "<" && a < b) || /* ... */)
inc_or_dec(reg, op, val);


>>63741179

This one is as easy as pie to parse. The difficulty is to map what you parsed to program constructs.
>>
Anyone successfully golfed today's problem?

>>63741011
Post them.
>>
>>63741111
That's perfect
>>
>>63741211
I was thinking about reverse-golfing it by interpreting the instructions char by char but I can't be assed at the moment.
>>
>>63741111
Definitely.
>>
>>63741207
Tons of pre written stuff plus adderall. Kudos to them, honesty.
>>
>>63741207
See >>63740681
People using dynamic languages (especially python) have a huge advantage over us.
>>
File: Ici1lvN[1].png (114 KB, 694x670)
114 KB
114 KB PNG
>>63741209
>>63741209
>It doesn't have to be so bad.
I think the point the comment you are replying to do was trying to make was how to write it out in the most pic related way possible.
>>
>>63741263

Yeah I didn't realize it was a reply to the chad / virgin idea until after I posted. :(
>>
>>63740603
pretty fucking based. gj man, giving hope to brainlets like me
>>
Took me over an hour to parse the input.

My code's too long to post again.
https://github.com/DuSTman31/AoC2017/blob/master/AoC8.cpp
>>
File: test block.png (17 KB, 629x322)
17 KB
17 KB PNG
>>63741135
Well, looks like random blocks appear now.
>>
var r = {};
var b = -1;
for(var i of input){
var p=i.split(' ')
eval((r[p[4]]||0)+p[5]+(+p[6]))&&(r[p[0]]=(r[p[0]]||0)+(+p[2])*(p[1]=='dec'?-1:1))&&r[p[0]]>b&&(b=r[p[0]]);
}
console.log(Math.max(...Object.values(r)));
console.log(b);
>>
>>63741356
Are you doing this to yourself on purpose?
>>
>>63731258
Thanks
>>
R8
from operator import *

def day_08(data_in):
operat = {'<':lt,'<=':le,'==':eq,'!=':ne,'>=':ge,'>':gt}
changer = {'inc':add,'dec':sub}
registers = {}
ttt = list()
for j in data_in.strip().splitlines():
thing = j.split(' ')
reg,chg,amt,condl,cond,condr = thing[0],thing[1],int(thing[2]),thing[4],thing[5],int(thing[6])
if reg not in registers:
registers[reg]=0
if condl not in registers:
registers[condl]=0
if operat[cond](registers[condl],condr):
registers[reg]=changer[chg](registers[reg],amt)
ttt.append(registers[reg])

print(max(list(registers.values())))
print(max(ttt))
return

day_08(data)


Note: I didn't know eval was a thing when writing this
>>
>>63741207
I'd say 95% of the top 100 for this problem used python with eval
>>
File: good-and-eval[1].png (17 KB, 400x400)
17 KB
17 KB PNG
>>63740999
>>
>>63741378
Could be, could be.
Haven't really put much investigation into properly making compact parsers for C++. Maybe I should get bison involved, or something.
>>
File: cannot_continue.png (142 KB, 434x434)
142 KB
142 KB PNG
>finished both parts of today
>now back to debugging yesterday's part 2

it never ends
>>
>>63741453
Where the fuck did you learn C++?
Why are you even sorting the vector containing your register table?
Just loop through it or use a hashmap or something.

I don't even want to read any more it's painful to look at.
>>
File: 1497679022692.jpg (310 KB, 1920x1080)
310 KB
310 KB JPG
>>63741464
Don't give up!
You can do it!
Ganbare!
https://www.youtube.com/watch?v=d3dMWMsU6NU
>>
>>63741436
Nice
>>
>>63741482
That was part of a pass to remove duplicates. Though I suppose it was redundant considering I put the register states into a map later.
>>
>>63741356
Dear god. Just use std::regex
>>
>>63741414
Javascript has the same eval function as well. Unfortunately, string manipulation is a bit more difficult in javascript.
>>
>>63741562
why don't you look up if it exists first before adding it?
>>
File: 51.gif (12 KB, 250x237)
12 KB
12 KB GIF
Disappointing for day 8.

use List::Util qw/max/;

for(<DATA>){
/^(\w+) (inc|dec) (-?\d+) if (\w+) (>|<|==|!=|>=|<=) (-?\d+)$/ or die $_;
my($reg,$incdec,$operand,$reg2,$op,$value)=($1,$2,$3,$4,$5,$6);

next unless eval (($registers{$reg2}||0)." $op $value");
$registers{$reg} += ($incdec eq 'inc' ? 1 : -1) * $operand;
}

print max values %registers;

__DATA__
>>
>>63741207
What font is this?
>>
>>63741699
on debian 8, it was called deja vu sans mono, then on debian 9 it was replaced with something called noto mono, while staying visually identical.
I don't know which is which, but it's probably one of those.
>>
>>63741728
I looked it up, it was actually Droid Mono, google just merged it with the Noto font set.
>>
>>63741767
Thanks!
>>
>>63740681
This isnt fair
>>
File: thicc_exec.png (18 KB, 794x132)
18 KB
18 KB PNG
>tfw comfy exec
>>
>>63741822
lisp is objectively unreadable.
>>
File: listen_up_yuu.png (632 KB, 1250x1490)
632 KB
632 KB PNG
>>63741865
no
>>
I'm only just now finishing up part 1 on yesterdays challenge. It took me fucking forever to figure out I had a trailing whitespace in one of my variables and I feel like an idiot.
>>
>>63742064
What language are you using? In Python you can just call int(" 5 "), and it will parse it correctly. In Javascript you can call parseInt(" 5 "), and it will work. Both also have eval(" 5 "), which also works fine.
>>
>>63742154
He's probably talking about the disc names, not their weights.
>>
from util import to_string_rows, get_input_string_rows, test, run
from collections import defaultdict
import operator

def main():
input = get_input_string_rows(8)

OPERATOR_LUT = dict({
'>': operator.gt,
'<': operator.lt,
'>=': operator.ge,
'<=': operator.le,
'==': operator.eq,
'!=': operator.ne,
})

INSTRUCTION_LUT = dict({
'inc': operator.add,
'dec': operator.sub,
})

def check_operator(op, src_val, cmp):
check_op = OPERATOR_LUT.get(op, None)
if not check_op:
return False

return check_op(src_val, cmp)

def get_largest_register(regs):
return max(list(regs.values()))

def solve(input, fun):
regs = defaultdict(int)
largest_ever = 0

for row in input:
(dst, ins, val, _, src, op, cmp, ) = tuple(row.split())

dst_val = regs.get(dst, 0)
src_val = regs.get(src, 0)

val = int(val)
cmp = int(cmp)

if check_operator(op, src_val, cmp):
regs[dst] = INSTRUCTION_LUT.get(ins, lambda x, y: 0)(regs[dst], val)

if fun is None and regs:
largest_ever = max(get_largest_register(regs), largest_ever)

if fun is None:
return largest_ever

return fun(regs)
>>
>>63742154
I'm writing python atm. But the issue was with a list containing the names of programs - so it had to be a string.
>>63742164
yeah
>>
is there a nicer looking way than doing line.split()[n]
>>
>>63742307
see >>63742172, the single split and tuple unpacking will do, you could also just split once and then index these to optimize a bit
>>
>>63742326
i didn't know about tuple unpacking i've never had to do it before uwu

i wish i could name my vars like 'src' 'op' 'cmp' im too dumb and dont think of short hands
>>
>mfw you can execute all code just by looping through dictionary in c# ONCE:

delegate void DoStuff();

...

IDictionary<string, DoStuff> dict = new Dictionary<string, DoStuff>();
dict["foo"] = delegate { Console.WriteLine("some logic here"); };
dict["bar"] = delegate { Console.WriteLine("something else here"); };
dict["raboof"] = delegate { Console.WriteLine("of course I need more than just Writeln"); };
dict["foo"]();
>>
god dammit i should by studying for my math exam tomorrow but I cant yesterdays fucking part 2
>>
>>63742991
what's the problem
>>
>>63742991
>having exams on weekend
What.
>>
Man, this day was disappointing. Hopefully tomorrow brings a better challenge.
>>
>>63741096
It won't because Go is sane and also compiled so eval() wouldn't work unless they added an interpreter to the binary

In my solution I used a map of anonymous functions instead of a switch

package main

import (
"os"
"bufio"
"regexp"
"strconv"
"fmt"
)

var re = regexp.MustCompile("^(\\w*) (inc|dec) (\\S*) if (\\w*) (\\S*) (\\S*)$")
var registers = map[string]int{}
var highestValue = 0

var comparators = map[string]func(int, int) (bool){
">": func(a int, b int) bool { return a > b },
"<": func(a int, b int) bool { return a < b },
">=": func(a int, b int) bool { return a >= b },
"<=": func(a int, b int) bool { return a <= b },
"==": func(a int, b int) bool { return a == b },
"!=": func(a int, b int) bool { return a != b },
}

func eval(str string) {
matches := re.FindStringSubmatch(str)

integer1, _ := registers[matches[4]]
integer2, _ := strconv.Atoi(matches[6])

if comparators[matches[5]](integer1, integer2) {
registerArg, _ := strconv.Atoi(matches[3])

if matches[2] == "dec" {
registerArg = 0 - registerArg
}

registers[matches[1]] += registerArg

if registers[matches[1]] > highestValue {
highestValue = registers[matches[1]]
}
}
}

func getHighestRegister() string {
bestReg := ""

for register, value := range registers {
if value > registers[bestReg] {
bestReg = register
}
}

return bestReg
}

func main() {
dat, _ := os.Open("./day08_input.txt")
scanner := bufio.NewScanner(bufio.NewReader(dat))

for scanner.Scan() {
eval(scanner.Text())
}

highest := getHighestRegister()

fmt.Printf("Part 1: Highest register is %s (%d)\n", highest, registers[highest])
fmt.Printf("Part 2: Highest recorded value was %d\n", highestValue)
}
>>
I thought today's was pretty fun. Like building a little compiler.
>>
>>63743037
just mapping out the recursive function. I think I can probably figure it out if I just play with it for a while...

>>63743112
yeah, and it's a tough one too -__-
>>
Superior Rust solution coming through: https://play.rust-lang.org/?gist=c31d71638b010b7c3c197b48f564db19

macro_rules! cmp {
(($op:expr, $l:expr, $r:expr), ($($cmp:tt),*)) => {
match $op {
$(stringify!($cmp) => { $l $cmp $r })*
_ => { unreachable!() }
}
}
}

macro_rules! parse {
($iter:ident) => {(
$iter.next().unwrap(),
$iter.next().unwrap(),
$iter.next().unwrap().parse::<i32>().unwrap()
)}
}

fn main() {
let instant = std::time::Instant::now();
let mut registers = std::collections::HashMap::new();
let mut b = 0;

for l in INPUT.lines() {
let mut iter = l.split_whitespace();

let (l1, op1, r1) = parse!(iter);
iter.next();
let (l2, op2, r2) = parse!(iter);
let l2 = *registers.entry(l2).or_insert(0);

if cmp!((op2, l2, r2), (<, <=, >, >=, ==, !=)) {
let l1 = registers.entry(l1).or_insert(0);

match op1 {
"inc" => { *l1 += r1; }
"dec" => { *l1 -= r1; }
_ => { unreachable!() }
}

b = std::cmp::max(b, *l1);
}
}

let a = registers.values().max().unwrap();

let d = instant.elapsed();
println!(
"Part 1: {}\nPart 2: {}\nTime: {} ms",
a,
b,
(d.as_secs() as f64 + d.subsec_nanos() as f64 / 1000000000.0) * 1000.0
);
}


>>63740951
retard
>>
>>63743336
Teach me rust, senpai
>>
>>63743446
https://doc.rust-lang.org/stable/book/
https://danielkeep.github.io/tlborm/book/index.html
>>
File: scrot.png (185 KB, 632x345)
185 KB
185 KB PNG
E-Z
>>
C Dull:

https://hastebin.com/pacevojixo.cpp

Cant post because it break 4chan's parser
>>
For day 8, I used vim macros to quickly convert the entire file into normal python code, Then just browsed through the variables to find the max, and the unevenly weighted disk
>>
>>63743701
>mfw time measurement:
00:00:00.0006069

I assume this is microseconds
>>
File: 1503510675262.png (231 KB, 470x612)
231 KB
231 KB PNG
>mfw people with less than 8 stars are higher than me on the leaderboard.
This shit is so unfair.
>>
Man, I'm gonna have to read the python docs through again. Writing those switches felt horrible.
>>
File: php.png (169 KB, 597x286)
169 KB
169 KB PNG
>>63729483
My suggestion for the calendar
>>
File: highimpactsexuallatza.jpg (13 KB, 195x243)
13 KB
13 KB JPG
>thread getting slower and slower as all the pajeets drop out
>>
Guys I'm hungover as fuck and my arse is on fire from some dodgy pickled chilis. I think I just literally shat out this solution.

$registers = "a afu bfx ev fkp g ghj jh jq k lpi m nkr pr qdq qn qrc rlq sh t u vh w wfk yo".split
a = afu = bfx = ev = fkp = g = ghj = jh = jq = k = lpi = m = nkr = pr = qdq = qn = qrc = rlq = sh = t = u = vh = w = wfk = yo = 0
max = 0

File.open('input-8-1.txt').each do |l|
eval(l.gsub('dec','-=').gsub('inc','+='))
$registers.each do |r|
max = eval(r) if eval(r) > max
end
end

puts max


Its all just hackery because scope and abuse of eval. The only cool bit is eval(l.gsub('dec','-=').gsub('inc','+=')). Why have $registers = 'blah bla'.split, and an additional a = b =... = 0? Cause fuck you that's why.
>>
File: 1493155149645.png (416 KB, 2272x1024)
416 KB
416 KB PNG
I am nowhere near artistic enough to attempt this
>>
It sucks to be a eurofag, I have to do these after work, well after the reveal.
Anyway, this is another episode of "just implement it, don't think about it". It's kinda disappointing desu, I feel like the goal is to find the quickest Xi Wong Chang, there is no real algorithmic challenge.
I did this in python, with
if L[5] == '==':

type of instructions.

At least I learned about this eval() function by reading the thread today, so there is some gain
>>
FUCKING FINALLY FINISHED DAY 7 PART 2.
Fucking hell I feel like a total brainlet.
>>
>>63745672
What part caused you difficulties?
>building the tree
>computing the cumulated tree
>finding the answer
>>
>>63745696
It took me some time to realize the unbalanced node is the deepest into the tree. I was balancing the first one I encountered.
I know I'm a retard, day 8 looks interesting tho.
>>
>>63745579
>The only cool bit is eval(l.gsub('dec','-=').gsub('inc','+=')).
Yeah that is fucking legit. Nice job anon
>>
>>63745657
It's actually pretty nice to start solving problems immediatelly after you open your eyes in the morning really kicks you into day. I refuse to wake up at 6 am regulary tho, but I'm not competing.
>>
File: Untitled.png (460 KB, 1842x824)
460 KB
460 KB PNG
r8 and h8 my day 8
pls no bully
>>
>>63745672
>tfw my code only works on my solution
>tfw still trying to fix it
>tfw at the same time trying to find a way to reduce loops
>tfw total amount of loops is 6 now
>>
>>63746364
p-post code anon
>>
>>63746364
What language anon?
>>
>>63746379
Irrelevant but C#. And no, language itself has nothing to do with my inability to come up better solution, I know that this is exactly the witty remark you wanted to make, big boy. Too classy for /b/^W /g/

I already saw fast and compact solution in my language, in fact - 3 of them, one crazier then another. But I want to do it myself
>>
>>63745640
NEW THREAD
>>63746461
>>63746461
>>63746461
NEW THREAD
>>
>>63746364
Use a recursive solution
>>
I'm a brainlet, i used the code from yesterday but i kept the part of my code that was deleting useless characters from yesterday input (the ">" character).
I was wondering why my code wasn't working.
>>
Here is my solution : https://github.com/Smatchcube/Advent-of-Code-2017/blob/master/day8.py
How can you compete with python without the eval() function ?
>>
>>63747270
>>63747623
Why are you here?
>>
>>63747658
Sorry, firefox kept my tab during the day and i didn't see the >>63746471 message




Delete Post: [File Only] Style:
[Disable Mobile View / Use Desktop Site]

[Enable Mobile View / Use Mobile Site]

All trademarks and copyrights on this page are owned by their respective parties. Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.