/aocg/ - Advent of Code General #9

Nathaniel Parker
Nathaniel Parker

Don't drop the dinnerware edition
Previous thread /g/thread/63714083#p63714083

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 

All urls found in this thread:
http://adventofcode.com/
https://ghostbin.com/paste/stsza
https://projecteuler.net/problem=2),
https://pastebin.com/BcbqviyV
https://pastebin.com/FG8AL6Bb
https://github.com/Smatchcube/Advent-of-Code-2017/blob/master/day7.py
https://www.youtube.com/watch?v=dO5ZauOP2BA
https://pastebin.com/raw/wRRMCMDH
https://pastebin.com/jeHW3kCd
https://docs.python.org/3/tutorial/classes.html
https://pastebin.com/raw/2i8x1h5t
https://gist.githubusercontent.com/angch/214faafbf98e91888a44c9adf0924d35/raw/aa7a77471bf723c6554e719cd9d50f25b9a048fb/adventofcode2017day7input.txt
https://github.com/Smatchcube/Advent-of-Code-2017/blob/master/day7.py
https://github.com/CubicProgramming/adventOfCode2017/blob/master/Day7.c
https://ghostbin.com/paste/zvn4f
https://pastebin.com/c5pDExaa
https://pastebin.com/Pr9jZYA4
http://adventofcode.com/2017/leaderboard/day/7
http://adventofcode.com/2017/leaderboard/day/8
https://pastebin.com/dJYhtaMc
https://github.com/DuSTman31/AoC2017/blob/master/AoC8.cpp
https://www.youtube.com/watch?v=d3dMWMsU6NU
https://play.rust-lang.org/?gist=c31d71638b010b7c3c197b48f564db19
https://doc.rust-lang.org/stable/book/
https://danielkeep.github.io/tlborm/book/index.html
https://hastebin.com/pacevojixo.cpp
https://github.com/Smatchcube/Advent-of-Code-2017/blob/master/day8.py
Andrew Kelly
Andrew Kelly

has anybody tried a recursive approach on python for part 2? Does it work or do you hit the recursion limit?

Owen Richardson
Owen Richardson

I used recursion for finding weights and constructing a tree (which I didn't need), without any problems.

Luke Allen
Luke Allen

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.

Nicholas Bailey
Nicholas Bailey

Whoops, forgot the first function

Asher Cook
Asher Cook

Yes, here:
https://ghostbin.com/paste/stsza

Jaxon Jenkins
Jaxon Jenkins

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.

Cameron Moore
Cameron Moore

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.

Colton Flores
Colton Flores

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.

Isaiah Miller
Isaiah Miller

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.

Charles Bailey
Charles Bailey

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

Logan Gonzalez
Logan Gonzalez

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

Dominic Edwards
Dominic Edwards

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.

Joseph Martin
Joseph Martin

Eric we love U

Carter Reed
Carter Reed

can people explain their coding strategies in plain english? What algos are you using? Traversing tree bottom-up or top-down? Recursively? etc

Jaxon Thomas
Jaxon Thomas

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.

Joshua Brown
Joshua Brown

Stackoverflow is offline. How am I supposed to solve this puzzles?

Ryder Long
Ryder Long

Up for me.

Carson Harris
Carson Harris

pajeet, my son...

Owen Morgan
Owen Morgan

thanks, I was going about it the wrong way... Was gonna build the whole tree, then calculate every tower weight, etc

Landon Bailey
Landon Bailey

Yeah it went into maintenance for a second

Jackson Long
Jackson Long

Python's yield is really nice.

Parker Brooks
Parker Brooks

coding challenge
have to balance a fucking TREE
fuck this math bullshit

Carter Myers
Carter Myers

Balancing a tree actually means something else entirely.

Jordan Collins
Jordan Collins

who told you that

Matthew Evans
Matthew Evans

math is hard

Gavin Morgan
Gavin Morgan

So what is the right answer for the test input? 243 or 60?

Ryan Phillips
Ryan Phillips

Is it asking you for the weight of the program or the weight of the program and all its children programs?

Nathan Taylor
Nathan Taylor

60

Adam Gonzalez
Adam Gonzalez

I'm a filthy ESL so I got confused.

Thanks.

Brody Perry
Brody Perry

module DaySeven where

import AOC
import qualified Data.Set as S
import qualified Data.List as L

import Data.Ord

data Task = Task String Int [Task] deriving Show

-- here we only identify tasks by their name
instance Eq Task where
(Task n _ _) == (Task b _ _) = n == b
instance Ord Task where
(Task n _ _) `compare` (Task b _ _) = n `compare` b

getWeight (Task n w _) = w

simpleTask str = Task str 0 []

parseTask :: [String] -> Task
parseTask [] = Task "bad" 0 []
parseTask (n : w : rem) =
let t sub = Task n (read w) sub
in case rem of
("->": subs) -> t (map simpleTask subs)
[] -> t []

breakLine = wordsWhen (`elem` " ,()\t")
breakFile str = breakLine <$> lines str

lookupInSet v set =
let idx = S.findIndex v set
in S.elemAt idx set

parse str = parseTask <$> breakFile str

-- This is n log(n) which is far better than the previous n^2
part1' tasks = L.sortBy (comparing snd) $ countOccurences $ concatMap getSubs tasks
where getSubs [email protected](Task _ _ subs) = t:subs

part1 = fst . head . part1' . parse

makeTree :: Task -> S.Set Task -> Task
makeTree (Task n w subs) set = Task n w (map recur subs)
where recur t = makeTree (lookupInSet t set) set

getBalance :: Task -> Either Int Int
getBalance tsk = case tsk of
Task _ w [] -> return w
Task n w subs -> do
nSubs <- mapM getBalance subs
let size = length nSubs
duplicates = removeDups nSubs
mapping = zip nSubs (map getWeight subs)
case duplicates of
-- because of the way remove dups work bad will be the "off" element
(good : bad : _) -> do
let weight = maybe 0 id $ L.lookup bad mapping
offBy = good - bad
Left (weight + offBy)
_ -> return (w + sum nSubs)

part2 str = getBalance tree
where start = part1 str
tree = makeTree start (S.fromList $ parse str)

I should have used a map instead of a set and weird Eq/Ord instances, but oh well.

Noah Cook
Noah Cook

finally did it, now I have to go back and do yesterday's challenges, was too lay to do them

Austin Perry
Austin Perry

test input gives the right answer but the real one doesn't

Nolan Parker
Nolan Parker

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

Ayden Robinson
Ayden Robinson

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

Carson Jackson
Carson Jackson

[laughs in code]

Nathan Diaz
Nathan Diaz

>>63730614
sort
log n

Brody Moore
Brody Moore

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

Asher Rodriguez
Asher Rodriguez

>>63730614
so day 7 can be sorting in log n time

Jordan Long
Jordan Long

did you seriously draw your graph out by hand you fucking ape

Ethan Jenkins
Ethan Jenkins

/g/thread/63714083#p63727506
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.

Blake Thompson
Blake Thompson

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).

Cameron Fisher
Cameron Fisher

Weight of a stack includes the weight of EVERYTHING in the stack, not just the base. All children of ifyja have total weight 412.

Leo White
Leo White

Fuck.

Jeremiah Long
Jeremiah Long

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.

Benjamin Long
Benjamin Long

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)

Cooper Roberts
Cooper Roberts

What if a disk hold only two subtowers ?
If this is the case we can't know wich tower is unbalanced ?

Matthew Allen
Matthew Allen

Doesn't matter. The disks will become balanced if you adjust either.

Jackson Nguyen
Jackson Nguyen

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.

Xavier Wilson
Xavier Wilson

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.

Levi Fisher
Levi Fisher

Cleaned it up a bit, not sure how I can make it any better, I guess I'll leave it at that.

Ethan Barnes
Ethan Barnes

Aaand I'm a fucking retard.

Jayden Sanchez
Jayden Sanchez

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.

Kayden Harris
Kayden Harris

https://www.youtube.com/watch?v=dO5ZauOP2BA

If you guys didnt't score top 10 global today you're worse than a literal pajeet.

Angel Watson
Angel Watson

I improved the calendar image

Jeremiah Powell
Jeremiah Powell

Don't think I'm worse than someone who sits there refreshing a page until midnight desu

Nicholas Bailey
Nicholas Bailey

Do you want us Europeans to stay up past 6 am or go up before 6 am?

Eli Gomez
Eli Gomez

took me a bit to figure out how to recurse

Aaron Rivera
Aaron Rivera

Every American gets up before 6 am you lazy eurocuck

Angel Collins
Angel Collins

Ah, and then stays up past midnight I presume?
So all Americans get less than 6 hours of sleep.
Land of the free

Levi Jones
Levi Jones

iktf user (/g/thread/63714083#p63721151)

Joseph Williams
Joseph Williams

this, didn't sign up for math shit

Evan Murphy
Evan Murphy

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?

Leo Foster
Leo Foster

Nevermind, I'm an idiot. Silver are people who have completed only part 1, I got it backwards.

Elijah Howard
Elijah Howard

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

Juan Taylor
Juan Taylor

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.

James Richardson
James Richardson

I mean, that you need to find where the tree begin to be unbalanced.
The problem is really hard to explain.

Sebastian Cooper
Sebastian Cooper

Yeah I still dont get it.

Dominic Carter
Dominic Carter

you have to compute the weight of the whole subtree

Levi Rodriguez
Levi Rodriguez

So I did

avpklqy:48284
tytbgx:48284
bdohoaa:48284
smaygo:48292
pvvbn:48284
hgizeb:48284
tchfafn:48284

Jeremiah Wright
Jeremiah Wright

just check the unbalanced branch to see if there is an unbalanced branch inside.
In your example you should check the 'smaygo' branch

Eli Adams
Eli Adams

Oh I see

Owen Ortiz
Owen Ortiz

Is there really only 1 unbalanced node?

Am I looking for the deepest node that has an unbalanced weight?

Eli Martinez
Eli Martinez

Correct and correct.

Aaron Robinson
Aaron Robinson

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;
}

Jason Bell
Jason Bell

stuck on day 3
tfw brainlet

Jose Hughes
Jose Hughes

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.

Nathan Ross
Nathan Ross

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.

Kevin King
Kevin King

Ok I think I finally solved it, was busy all day

Can someone give me their input and answeers to double-check?

Jackson Foster
Jackson Foster

Keep at it my friend

Wyatt Perez
Wyatt Perez

https://pastebin.com/raw/wRRMCMDH
Part One: dgoocsw
Part Two: 1275

Alexander Gutierrez
Alexander Gutierrez

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;

Brayden Lewis
Brayden Lewis

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.

Lincoln Stewart
Lincoln Stewart

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

Chase Campbell
Chase Campbell

What's your input?

Cameron Russell
Cameron Russell

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 ?

Michael Gomez
Michael Gomez

https://pastebin.com/jeHW3kCd

Oliver Richardson
Oliver Richardson

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;
}

Matthew Kelly
Matthew Kelly

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.

Ethan Morales
Ethan Morales

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.

Andrew Martin
Andrew Martin

The example worked out as it should, but I'll check my recursion to see if something funky happened.

Easton Sanders
Easton Sanders

Well i wont have any time to fix today and tomororw as well and by next day I will move on

Anthony Garcia
Anthony Garcia

All your branches except one should have the cumulative weight "119424". Hope that helps.

Oliver Allen
Oliver Allen

I think the fact that the example has even weights for all the children is confusing people trying to complete part 2

Zachary Wright
Zachary Wright

Refactored my problem 7 code from this morning /g/thread/63714083#p63727865
but it barely got any simpler

Henry Wilson
Henry Wilson

You are just a brainlet

Blake Jones
Blake Jones

can part2 be done without nodes?

Jacob Jenkins
Jacob Jenkins

What data structure did you use for part 1?

Jose Lee
Jose Lee

I'm so dumb that i have used set, dict and list only for the part one.

Liam White
Liam White

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

Jordan Wilson
Jordan Wilson

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

Jaxon Smith
Jaxon Smith

Everyone already gets a random input you faggot

Benjamin Anderson
Benjamin Anderson

hashmap and treeset

Thomas Murphy
Thomas Murphy

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.

Christopher Sanders
Christopher Sanders

I did it in python with just dictionaries, you should be able to extend your Java (?) solution with the data structures you have

Cameron Rogers
Cameron Rogers

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?

Jonathan Harris
Jonathan Harris

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.
is my input file so no need to reply this file

Cameron Lopez
Cameron Lopez

what does the asterisk mean? python has pointers?

Cooper Peterson
Cooper Peterson

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?

Owen Stewart
Owen Stewart

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.

Daniel Thomas
Daniel Thomas

Give me input file and solution please, i need it.

Colton Young
Colton Young

https://docs.python.org/3/tutorial/classes.html
See 9.3.5

Andrew Campbell
Andrew Campbell

https://pastebin.com/raw/2i8x1h5t
hmvwl
1853

Cameron Young
Cameron Young

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.

Joseph Reed
Joseph Reed

You beauty! I'll save santa in your name, user.

Ian Edwards
Ian Edwards

Don't know if your file is broken or if it's a joke but your file miss the mofkds node.

Landon Reyes
Landon Reyes

Got you! :^)

William Lopez
William Lopez

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;

Matthew Powell
Matthew Powell

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.

Benjamin Powell
Benjamin Powell

<?php

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

$wow
$fgt
$idkhowtocallthis

Charles Miller
Charles Miller

Post your setup for the event.

Wath is this kind of "asci art" this year ? It looks like nothing at the moment.

Thomas Reed
Thomas Reed

The theme of the story is repairing a printer.
Looks like a printed circuit.

Jacob Turner
Jacob Turner

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 $_)) {$_} }

Julian Wilson
Julian Wilson

tfw anonymous user stole my top 20 spot again
feels bad man

Kayden Stewart
Kayden Stewart

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

Nolan Perez
Nolan Perez

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?

Jaxon Barnes
Jaxon Barnes

Wew lad

Gavin Peterson
Gavin Peterson

mine was the second disc.

Joshua Fisher
Joshua Fisher

hahahahaahhhahh LOL
I have warned you
shitty code

Jaxon Ward
Jaxon Ward

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

Samuel Edwards
Samuel Edwards

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

Noah Rogers
Noah Rogers

just output to a graphviz dot file

Carson Ramirez
Carson Ramirez

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]

Jose Turner
Jose Turner

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

Carter Williams
Carter Williams

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))

Ethan Davis
Ethan Davis

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

Carson Hall
Carson Hall

i'd say just go ahead and axe people who don't have at least one star for five days

Julian Garcia
Julian Garcia

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.

Angel Murphy
Angel Murphy

There's plenty of room in the other board

Jacob Lewis
Jacob Lewis

you have submitted too many incorrect answers you have been disqualified from completing this puzzle

Connor Phillips
Connor Phillips

How many?

Charles Sullivan
Charles Sullivan

poor lil thing

Xavier Perez
Xavier Perez

I would fucking fire the person who gave me day 7s data in that format. Bitch you ever heard of JSON?

Isaac Reyes
Isaac Reyes

Is

┤|├
supposed to be a battery?

Andrew Perry
Andrew Perry

Th-this isn't a thing is it?

Jordan Gutierrez
Jordan Gutierrez

I agree it would be nice for a standardized input, but it's not that hard to regex it out.

Ian Cruz
Ian Cruz

Reading the input is like half the challenge.

People keep saying it's the hardest part.

Lincoln Wright
Lincoln Wright

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.

Parker Flores
Parker Flores

What would be a good language to do this directly?

Jayden Sanchez
Jayden Sanchez

do what directly?

Justin Brooks
Justin Brooks

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.

Luis Moore
Luis Moore

Tokenize input without having to write boilerplate code

Chase Nelson
Chase Nelson

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))

Cameron Harris
Cameron Harris

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

Xavier Rodriguez
Xavier Rodriguez

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.

Nathan Hill
Nathan Hill

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.

Jayden Perez
Jayden Perez

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.

Cameron Cruz
Cameron Cruz

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.

Jordan Collins
Jordan Collins

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.

Jack Miller
Jack Miller

Were those take home tests? Websocket chat server is like 10 lines of code in node.js

Asher Fisher
Asher Fisher

The first two yes, the third it was in person. However trivial it is they are mainly looking for good ideas to steal.

Christian Bennett
Christian Bennett

30 minutes. It's going to be a hard one today, I can feel it.

Luke Hill
Luke Hill

for yesterdays
https://pastebin.com/c5pDExaa
any suggestions?

Ethan Hughes
Ethan Hughes

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
Yes, keep posting solutions for the redditors to steal, I’m sure it will bring you good karma. (It will actually do the opposite)

Brayden Jenkins
Brayden Jenkins

its nearly time for the next one, how long do you expect me to wait?

Connor Thompson
Connor Thompson

Why are you even talking to the shitposter?

Charles Peterson
Charles Peterson

tfw never finished part2 from today
tfw lost resolve to continue

good luck, lads

Jack Thompson
Jack Thompson

you can do it user

Justin Brooks
Justin Brooks

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);
}
}
}

Alexander Thompson
Alexander Thompson

Don't give up user, 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.

Elijah Flores
Elijah Flores

5 minutes

Dominic Morgan
Dominic Morgan

everyone get ur snac ready

Leo Jackson
Leo Jackson

put on your programming music and your programming socks

Jace Williams
Jace Williams

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.

Austin Evans
Austin Evans

don't have any programming music
don't have any programming socks
Am I doomed?

Isaac Evans
Isaac Evans

1 Minute remains. Good luck.

David Bailey
David Bailey

That's my secret
I'm always wearing programming socks

David Williams
David Williams

LETS GO BOYOS

Jason Gutierrez
Jason Gutierrez

this isnt even hard its just annoying

Jaxon White
Jaxon White

WINNER WINNER CHICKEN DINNER

Robert Sullivan
Robert Sullivan

Holy shit user

Parker White
Parker White

Frick

Aaron Cox
Aaron Cox

Do I have to act on a register if it hasn't been declared yet?

This is important.

David Cox
David Cox

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

Yes. All register names are valid at all times, and they all start initialized to zero.

Noah Torres
Noah Torres

They're all initialized to 0, so they're all declared

Isaac Edwards
Isaac Edwards

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

Nathan Gonzalez
Nathan Gonzalez

i wish i was as smart as you

Liam Butler
Liam Butler

Rank 236 today. By this rate of improvement, I should reach top 100 on Sunday.
That's a really nice solution, user.

Charles Stewart
Charles Stewart

And done

Fuck, parsing that was difficult.

Well, difficult for a brainlet like me.

Luke Phillips
Luke Phillips

Also, 544/507 (personal best!)

Camden Green
Camden Green

Got slowed down because I was comparing the register's name and the number instead of the register value RIP.

Brandon Brown
Brandon Brown

done but i still didn't do yesterdays ><

Adrian Ramirez
Adrian Ramirez

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.

Kevin Harris
Kevin Harris

I'm still designing the symboltable lookup. :(

Jordan King
Jordan King

whew back to top 15 :3

Nicholas Carter
Nicholas Carter

Oh wow, I didn't even know eval() was a thing. That would have been useful to know.

Kayden Long
Kayden Long

Dec 3 broke the gold stars but gold+silver is still monotonic. How many hours until Dec 8 beats Dec 7?

Jaxson Brown
Jaxson Brown

comfy problem done, time to cook nice food

Nolan Adams
Nolan Adams

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

Blake Parker
Blake Parker

Why do you think it will? Day 7 wasn't any harder than this one, I'd say.

Ryan Lewis
Ryan Lewis

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?

Nathan Young
Nathan Young

rust was a mistake: https://pastebin.com/Pr9jZYA4

Nicholas Nelson
Nicholas Nelson

Really easy.

Thomas James
Thomas James

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 user showed it has to be a full expression

Camden Moore
Camden Moore

this, especially if you have a nice language and can just call eval

Camden Perry
Camden Perry

You're not thinking like a brainlet. Trees are hard.

Lincoln Murphy
Lincoln Murphy

Ayy.

Julian Thompson
Julian Thompson

Nice language
I'm challenging myself by only using C
Guess I'm fucked then

John Rogers
John Rogers

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.

Jacob Ross
Jacob Ross

Any ideas for the calendar image /g/-famalam?

Ryder Butler
Ryder Butler

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.

Jack Rodriguez
Jack Rodriguez

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.

Owen Roberts
Owen Roberts

Oh wow. People were really slow yesterday. My today's solution was actually longer than my yesterday's.

Jack Price
Jack Price

You could go the intellectually lazy route and have a surgeon / game of Operation over a cash register

Carson Nelson
Carson Nelson

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.

Isaac Watson
Isaac Watson

C code works and spits out the right answer on your first compile with zero errors

is there anything more comfy?

Nicholas Barnes
Nicholas Barnes

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?

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

Leo Thompson
Leo Thompson

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()?

Joshua Evans
Joshua Evans

Definitely something about Chad eval and virgin switch.

Austin Reyes
Austin Reyes

Too easy desu senpai

Benjamin Ramirez
Benjamin Ramirez

Hey I was right. I wonder if this will be the input to the last day or something.

When you're using a language that isn't C which compiles and spits out the correct result on your first try.

Adam Johnson
Adam Johnson

if conditional == "==" {
if operation == "inc" {
//...
} else if operation == "dec" {
//....
}
} else if conditional == "!=" {
if operation == "inc" {
//...
//....

Thomas Barnes
Thomas Barnes

tfw can use switch for strings in sepples
JUST

Xavier Phillips
Xavier Phillips

Oh jeez

Julian Brown
Julian Brown

hahahaha

Colton Hill
Colton Hill

Absolutely ENTERPRISE

https://pastebin.com/dJYhtaMc

Nicholas Hughes
Nicholas Hughes

The people complaining about parsing the input string are not going to be happy today

Hudson Fisher
Hudson Fisher

Nice

Bentley Davis
Bentley Davis

Eh, it's easier than yesterday since all the separators are spaces (and newlines).

Ayden Lopez
Ayden Lopez

How are people writing this shit in under 2 minutes?

eval?

Michael Gray
Michael Gray

It doesn't have to be so bad.

if ((c == "==" && a == b) || (c == "<" && a < b) || /* ... */)
inc_or_dec(reg, op, val);

This one is as easy as pie to parse. The difficulty is to map what you parsed to program constructs.

Andrew Phillips
Andrew Phillips

Anyone successfully golfed today's problem?

Post them.

Luke Cruz
Luke Cruz

That's perfect

Joseph Harris
Joseph Harris

I was thinking about reverse-golfing it by interpreting the instructions char by char but I can't be assed at the moment.

Easton Martinez
Easton Martinez

Definitely.

Charles Walker
Charles Walker

Tons of pre written stuff plus adderall. Kudos to them, honesty.

Wyatt Lee
Wyatt Lee

See People using dynamic languages (especially python) have a huge advantage over us.

Carter Garcia
Carter Garcia

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.

Adrian Carter
Adrian Carter

Yeah I didn't realize it was a reply to the chad / virgin idea until after I posted. :(

Jose Sanders
Jose Sanders

pretty fucking based. gj man, giving hope to brainlets like me

Chase Hill
Chase Hill

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

Eli Butler
Eli Butler

Well, looks like random blocks appear now.

Cameron Cook
Cameron Cook

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);

Cameron Butler
Cameron Butler

Are you doing this to yourself on purpose?

Ryder Brooks
Ryder Brooks

Thanks

Jaxson Garcia
Jaxson Garcia

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

Nolan Turner
Nolan Turner

I'd say 95% of the top 100 for this problem used python with eval

Xavier Rogers
Xavier Rogers

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.

Owen Long
Owen Long

finished both parts of today
now back to debugging yesterday's part 2

it never ends

Nolan Harris
Nolan Harris

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.

Christian Cooper
Christian Cooper

Don't give up!
You can do it!
Ganbare!
https://www.youtube.com/watch?v=d3dMWMsU6NU

Daniel Edwards
Daniel Edwards

Nice

Daniel Brown
Daniel Brown

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.

Jace Thompson
Jace Thompson

Dear god. Just use std::regex

Benjamin Hall
Benjamin Hall

Javascript has the same eval function as well. Unfortunately, string manipulation is a bit more difficult in javascript.

Justin Fisher
Justin Fisher

why don't you look up if it exists first before adding it?

Easton Gonzalez
Easton Gonzalez

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__

Jace Adams
Jace Adams

What font is this?

Ethan Gomez
Ethan Gomez

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.

Eli Bennett
Eli Bennett

I looked it up, it was actually Droid Mono, google just merged it with the Noto font set.

Matthew Bailey
Matthew Bailey

Thanks!

Joshua Taylor
Joshua Taylor

This isnt fair

Easton Rodriguez
Easton Rodriguez

tfw comfy exec

Aiden Young
Aiden Young

lisp is objectively unreadable.

Julian Jones
Julian Jones

no

Nathaniel Jenkins
Nathaniel Jenkins

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.

Brayden Hall
Brayden Hall

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.

Brandon Brown
Brandon Brown

He's probably talking about the disc names, not their weights.

Easton Howard
Easton Howard

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)

Blake Myers
Blake Myers

I'm writing python atm. But the issue was with a list containing the names of programs - so it had to be a string.

yeah

Asher Ramirez
Asher Ramirez

is there a nicer looking way than doing line.split()[n]

Asher Ward
Asher Ward

see , the single split and tuple unpacking will do, you could also just split once and then index these to optimize a bit

Joshua Morris
Joshua Morris

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

Aiden Ortiz
Aiden Ortiz

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"]();

Michael Baker
Michael Baker

god dammit i should by studying for my math exam tomorrow but I cant yesterdays fucking part 2

Isaiah Perez
Isaiah Perez

what's the problem

Nathaniel Thompson
Nathaniel Thompson

having exams on weekend
What.

Alexander Bailey
Alexander Bailey

Man, this day was disappointing. Hopefully tomorrow brings a better challenge.

Gabriel Johnson
Gabriel Johnson

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)
}

James Green
James Green

I thought today's was pretty fun. Like building a little compiler.

Dominic Parker
Dominic Parker

just mapping out the recursive function. I think I can probably figure it out if I just play with it for a while...

yeah, and it's a tough one too -__-

Logan Cruz
Logan Cruz

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
);
}

retard

Elijah Parker
Elijah Parker

Teach me rust, senpai

Owen Russell
Owen Russell

https://doc.rust-lang.org/stable/book/
https://danielkeep.github.io/tlborm/book/index.html

Hunter Reed
Hunter Reed

E-Z

Dylan Ross
Dylan Ross

C Dull:

https://hastebin.com/pacevojixo.cpp

Cant post because it break 4chan's parser

Julian Scott
Julian Scott

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

Daniel Thomas
Daniel Thomas

mfw time measurement:
00:00:00.0006069

I assume this is microseconds

Luis Peterson
Luis Peterson

mfw people with less than 8 stars are higher than me on the leaderboard.
This shit is so unfair.

Carter Russell
Carter Russell

Man, I'm gonna have to read the python docs through again. Writing those switches felt horrible.

Eli Hill
Eli Hill

My suggestion for the calendar

Ian Bell
Ian Bell

thread getting slower and slower as all the pajeets drop out

Jose Green
Jose Green

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.

Thomas Martin
Thomas Martin

I am nowhere near artistic enough to attempt this

Owen Bailey
Owen Bailey

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

Jason Kelly
Jason Kelly

FUCKING FINALLY FINISHED DAY 7 PART 2.
Fucking hell I feel like a total brainlet.

Liam Harris
Liam Harris

What part caused you difficulties?
building the tree
computing the cumulated tree
finding the answer

Isaac Jackson
Isaac Jackson

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.

Gabriel Torres
Gabriel Torres

The only cool bit is eval(l.gsub('dec','-=').gsub('inc','+=')).
Yeah that is fucking legit. Nice job user

Asher Sullivan
Asher Sullivan

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.

Elijah Sanders
Elijah Sanders

r8 and h8 my day 8
pls no bully

Oliver Scott
Oliver Scott

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

William Mitchell
William Mitchell

p-post code user

Tyler Diaz
Tyler Diaz

What language user?

Juan Butler
Juan Butler

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 Sup Forums

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

Jack Powell
Jack Powell

NEW THREAD
/g/thread/63746461#p63746461
/g/thread/63746461#p63746461
/g/thread/63746461#p63746461
NEW THREAD

Alexander Long
Alexander Long

Use a recursive solution

Cooper Allen
Cooper Allen

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.

Easton Diaz
Easton Diaz

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 ?

Nathan Barnes
Nathan Barnes

Why are you here?

Colton Garcia
Colton Garcia

Sorry, firefox kept my tab during the day and i didn't see the message

Disable AdBlock to view this page

Disable AdBlock to view this page