/aocg/ - Advent of Code 2018 General #10

blanket edition

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

Private leaderboard join code:

368748-e33dcae3


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

Alternative leaderboard for those waiting for inactives to be kicked from the first:

208834-4a1a9383

Attached: hqdefault.jpg (480x360, 15K)

Other urls found in this thread:

twitch.tv/tremorai
regex101.com/r/SuuOg7/2
pastebin.com/xLxKN6at
twitter.com/NSFWRedditImage

took 3 tries

>want to work on aoc, but have to go to sleep because of CS final review tomorrow morning

boys...

You're up now. Are you not done day 3 yet?

its not hard, you can do it

I lost an hour to myself being horrible.

help
>How many square inches of fabric are within two or more claims?

Seriously who the fuck thought """lists""" were a good idea?
>C
>simply allocate an array of pointers with fixed len
>Python
>ayyo chant this incantation
list = [[0 for i in range(1024)] for j in range(1024)]

I lost 10 min because reading while half asleep is really hard... It posibly saved 10min on second part though....

>array of pointers
>for a multidimensional array

I solved today's problems by making a huge 2d list representing the fabric.

But surely there's a better way right? Is there some kind of anti-brainlet tree data structure that can find overlaps between claims?

God this is so fucking ugly, but it works so okay.
Time is 0.49s

from numpy import *
from time import *
start = time()


class Cut:

def __init__(self, x, y, w, h, c):
self.x1 = x
self.y1 = y
self.x2 = x + w
self.y2 = y + h
self.check = w * h * c
self.c = c


file = open("day3input.txt", "r")
claims = []
for line in file:
line = line.rstrip("\n")
line = line.split(" ")
claim_num = int(line[0][1:])
coords = line[2].split(" ")
coords = coords[0].split(",")
coords[1] = coords[1].rstrip(":")
size = line[3].split("x")
new_cut = Cut(int(coords[0]), int(coords[1])
, int(size[0]), int(size[1]), claim_num)
claims.append(new_cut)

fabric = zeros((1001,1001), dtype=int)
for claim in claims:
for y in range(claim.y1, claim.y2):
for x in range(claim.x1, claim.x2):
fabric[x][y] += claim.c

for claim in claims:
checker = 0
for y in range(claim.y1, claim.y2):
for x in range(claim.x1, claim.x2):
if claim.c != fabric[x][y]:
break
checker += fabric[x][y]
if claim.c != fabric[x][y]:
break
if checker == claim.check:
print(claim.c)
break

print(time() - start)

Attached: source.gif (500x250, 875K)

[haskell]
import HigherOrderFunctions
import Data.List.Split
import qualified Data.Set as Set

main :: IO ()
main = do
input ((Int, Int), (Int, Int))
parseLine s = ((xPos, xPos + width - 1), (yPos, yPos + height - 1)) where
startPos = words s !! 2
xPos = read $ splitOn "," startPos !! 0
yPos = read $ init $ splitOn "," startPos !! 1
lengthWidth = words s !! 3
width = read $ splitOn "x" lengthWidth !! 0
height = read $ splitOn "x" lengthWidth !! 1

expandBox :: ((Int, Int), (Int, Int)) -> [(Int, Int)]
expandBox (xs, ys) = [(x, y) | x 1) . expandBox . parseLine $ l

soln1 :: [String] -> Int
soln1 ls = length $ filter (\(k,v) -> v /= 1) $ reduceByKey (+) $ flatMap explodeLine ls

parseLineWithId :: String -> (Int, ((Int, Int), (Int, Int)))
parseLineWithId s = (read . tail $ words s !! 0, parseLine s)

explodeLineWithId :: String -> [((Int, Int), Int)]
explodeLineWithId l = keyMap (\x -> lineId) . expandBox $ box where
(lineId,box) = parseLineWithId l

soln2 :: [String] -> Int
soln2 ls = missingNum !! 0 where
boxesWithIds = collect $ flatMap explodeLineWithId ls
withTwoValues = filter (\(k,v) -> length v /= 1) boxesWithIds
overlapIds = unique . flatMap snd $ withTwoValues
missingNum = Set.toList $ Set.difference (Set.fromList [1..(length ls)]) (Set.fromList overlapIds)


$ time ./soln
124850
1097

real 0m1.932s
user 0m1.843s
sys 0m0.084s

I had to rewrite parts of HigherOrderFunctions to use Data.Set and Data.Map, so the majority of my time was spent on plumbing. But damn, once that's done, using these concepts feels so smooth.

Attached: 1517917941476.jpg (1137x1635, 301K)

You know, when you make a new thread you should link it in the old one

I think you could use a range tree to do this somehow. But implementation would be hell.

>range tree
never heard of it, will take a look

>2d
Pfff... you can use simple array as pseudo matrix to solve this.

Alright lads. Just got off work. How bad is it today?

Cont: most of these type signatures are stolen from Spark. I'd kinda like to do a few in PySpark, but learning haskell is fun too. Maybe I'll do both...

Its literally the same amount of memory and computation, I'm looking for a more drastic improvement

Why is this not linked in the old thread?

Rectangles aren't strictly-orderable so it'd be a tough ask to cut down on the memory requirements too much without increasing processing growth complexity. Could be fun, but I've learned that as a rule of thumb, memory is meant to be abused so that the processor doesn't need to work as hard. So I wouldn't worry too hard.

Easy math wise, but I spent 30 minutes string parsing. I hope this isn't a trend, because there's nothing stimulating by doing literal codemonkey work.

Someone tell my how Pythonic my code is. Obviously it would be nicer to bundle in functions, but nobodies got time for that and Python is after all a scripting language.

Attached: Screenshot_2018-12-02_23-14-00.png (587x798, 82K)

How long do your programs take to parse the inputs? 35ms seems way too long.

pretty nifty. I used parsec for my parsing which felt like overkill
parseClaim :: Parser Claim
parseClaim = do
char '#'
id

IMO this is one place where regex shines.

twitch.tv/tremorai

Remember: These guys are competing with you for programming jobs.

Attached: simple_iq.webm (720x720, 1.28M)

was my issue

Who made lst[[0]*1000]*1000 a 2d matrix of pointers pointing to a list of 0s

yeah, but so is /ourguy/
always try to compete at the highest level you can. you're not gonna improve if your benchmark is some retard on twitch

regex101.com/r/SuuOg7/2

Yeah, that sounds about right (depending on processor speed). It's 32 KB of text data that's being trawled through sequentially, that's just what it takes.

Unless you wanted to do some parallel stuff. It's a pretty parallel-able problem.

Good work user, quick tip: expandBox is just from range from Data.Ix.

Attached: 8pm9s15cbbiy.jpg (1000x1000, 75K)

Brutalized the formatting, but you know what I mean.

def advent3():
import re, itertools
lines = read_to_string().splitlines()
# good regex from another user
table = [[int(n) for n in re.split(",|:|@|x", l.replace('#', ''))] for l in lines]
sets = {r[0]: set(
[p for p in itertools.product(
range(r[1], r[1]+r[3]),
range(r[2], r[2]+r[4]))])
for r in table}
total = set([])
dbl = set([])
# part 1----------------------------------
for s in sets.values():
dbl |= (total & s)
total |= s
print(len(dbl))
# part 2----------------------------------
for s in sets:
if(len(dbl & sets[s]) == 0):
print(s)
break
i think it's a pretty elegant solution

Attached: aoc3.png (600x600, 257K)

how can I get that fire animation in vim?

yup that's exactly how I did it...eventually
originally I tried [[Claim]] but that was obviously horrible

For reference, I just tried the regex, and compared to my 35ms splitting, it only takes about 25ms, so it's a tad better.

>2:40 AM local time
>have work at 9:00
>enjoying comfy brainlet coding stream with aoc creator

fuck i don't wanna go to sleep

is that an accurate visualization of today's problem?

waiting on big boy input UwU

also fuck you jewgle

Attached: recaptcha.png (300x249, 8K)

Yes, there were a few posted

This took me 2h due to rust's shit limitations concerning arrays on windows

It's coming.

I keep getting captcha connection errors for some reason too

Datum = namedtuple('datum', 'id x y w h')
with open('input3.txt') as f:

lines = [re.sub(r'[#@,:x\n]', ' ', line) for line in f.readlines()]
lines = [Datum(*map(int,line.split())) for line in lines]

def do_the_thing(lines):
plan = Counter()
lapper = set()
for line in lines:
overlap = False
for x in range(line.x, line.x+line.w):
for y in range(line.y, line.y+line.h):
if plan[(x,y)]:
overlap = True
plan[(x,y)] += 1

if not overlap:
lapper.add(line.id)
return lapper, plan

lapper, plan = do_the_thing(lines)

print(lapper.intersection(do_the_thing(lines[::-1])[0]))
print(sum(1 for x in plan.values() if x > 1))


I did it the brainlet way. Any comments Jow Forumsentlemen?

pic for comment bait.

Attached: girl.jpg (736x1104, 157K)

pay up goyim

That went better than I expected. Second solution is completely unoptimized.

Attached: done.png (646x395, 51K)

I don't have good goy coins

lolno

Attached: sticks.jpg (614x461, 87K)

About as clear and concise as I can make it. Runs entirely in about 14 ms.

Attached: aoc18d3.png (431x537, 27K)

>gifs
>vim

pick 1

what do you mean? i didn't run into any problems with arrays

what are you talking about user... ?

Got it down to 440ms
main :: IO ()
main = do
file

Attached: day3.png (874x722, 61K)

Does reading haskell get easier over time?
I typically work in python, and I can read most python pretty fluently. But python's known for being basically pseudocode so that might not count for much.
Meanwhile I can barely read the haskell I just wrote myself.
Is there something I should be doing better stylistically? (Besides just comments)
I guess learning the standard libraries is probably one of the first steps

Absolutely, it's kind of like reading music if you've done that. At first it's just bizarre but eventually you learn what the patterns mean.
If you post a code sample we can talk about specific style improvements. Otherwise...just read and write a lot of Haskell I guess.

Any programming review/advice/input would be appreciated.
import re

ls = open('input', 'r').read().strip().split('\n')

def part_one():
c = 0
t = [[-1 for i in range(1000)] for j in range(1000)]
for l in ls:
id, x, y, w, h = list(map(int, re.findall(r'[\d]+', l)))
for i in range(y, y+h):
for j in range(x, x+w):
if t[i][j] != -1:
if t[i][j] != 0:
t[i][j] = 0
c += 1
else:
t[i][j] = id
print(c)

Is there anyway I can make part two any less ugly by not having to check the set at every point of collision?

def part_two():
s = set(range(1,len(ls)+1))
d = {}
for l in ls:
id, x, y, w, h = list(map(int, re.findall(r'[\d]+', l)))
for i in range(y, y+h):
for j in range(x, x+w):
if (i,j) in d:
if id in s:
s.remove(id)
if d[(i,j)] in s:
s.remove(d[(i,j)])
d[(i,j)] = id
print(s)

part_one()
part_two()

tested=set({})
conflicts=set({})
data=dict({})
for line in open("clothesInput.txt"):
line=line.split()
data[line[0]]=line[2].replace(':','').split(','),line[3].split('x')
###{key:[[x,y],[widthStart,heightStart]]}
for line in data.values():
pos=[int(line[0][0])+1,int(line[0][1])+1]
for x in range(0,int(line[1][0])):
for y in range(0,int(line[1][1])):
if (pos[0],pos[1]) in tested:
conflicts.add((pos[0],pos[1]))
else:
tested.add((pos[0],pos[1]))
pos[1]=int(line[0][1])+1+y
pos[0]=int(line[0][0])+1+x
print(len(conflicts))

Why am I so wrong?

Attached: a book or some shit.jpg (297x475, 25K)

my python abomination
def addClaim(claim, graph):
for i in range(claim[4]):
for j in range(claim[3]):
graph[i + claim[2]][j + claim[1]] = 'X' if graph[i +
claim[2]][ j + claim[1]] != '.' else '#'


def parseClaims(claims):
result = []
for claim in claims:
s = claim.replace(',',' ').replace('x',' ').replace(':','').split(' ')
result.append([s[0], int(s[2]), int(s[3]), int(s[4]), int(s[5])])
return result


def checkClaim(claim, graph):
flag = True

for i in range(claim[4]):
for j in range(claim[3]):
if graph[i + claim[2]][j + claim[1]] == 'X':
return
print(claim[0])


with open('input.txt') as f:
claims = f.readlines()

fabric = [['.']*1000 for i in range(1000)]
claims = parseClaims(claims)
count = 0

for claim in claims:
addClaim(claim, fabric)
for line in fabric:
count += line.count('X')
print(count)
for claim in claims:
checkClaim(claim, fabric)

anything more than this and your a tryhard faggot
for (int i = x; i < x + w; i++)
for (int j = y; j < y + h; j++)

learn to press enter

This looks very similar to mine, having trouble pushing it down further. Almost all the time is spent on part 1.
I like how you used M.unionWith, I'm just using a foldl' inside a foldl'.

so what's the good runtimes for day3 so far?

USE YOUR FUCKING SPACEBAR
HOLY FUCK THAT IS UGLY

>she reddit spaces her code

CL?

Today wasn't too bad! It was essentially asking us whether a) We can parse a string (yes, string.split() and string.substr() are fairly cool functions), and b) how to traverse arrays in a way that allows us to build towards a solution.

I got both solutions on the first try, but I am kind of mad I took over 100 LOC in ruby. I would have finished it faster, but I was at work until two hours ago. Ah well. At least I finished, right?

Anyone mind helping me see how I can condense this?
Pastebin: pastebin.com/xLxKN6at

Attached: 1539998379264.jpg (1024x576, 71K)

I use a small screen. Sorry.

I have 37ms with my shitty solution (somewhat old
Core i5 laptop), that good?

To add, when you start to see the connections between typeclasses, your memory will become better, and you'll parse Haskell better. The functions sort of reinforce each other once you understand the relationships between them. Post code on that modifiable code website for help.

who /regex masterrace/ here?

Thread needs more haskell

I was hoping there was a better way of initialising the Map, I tried insertWith (+) but it was even slower.

Regex::new(r"#(\d+) @ (\d+),(\d+): (\d+)x(\d+)")?;

Attached: yukko_epic.png (459x410, 120K)

Attached: day3.png (876x717, 114K)

re.findall(r'[\d]+', l)

>he's a regex using virgin

Attached: dummy.png (657x539, 110K)

Yep. I'm learning the language while doing this, so I basically didn't understand how arrays in CL worked until I used them.

>set({})
constructs a set out of the keys of an empty dict. "set()" would be better
Same with dict({}) vs dict() or just {} but that's slightly less weird

>line[0][1]
>line[0][0]
>line[1][1]
and name your damn variables

Basically cheating.

does look like python to you user

I don't think I am good at doing these puzzle very quickly. It's quite amazing how quick some of these dudes are.

Attached: day3.jpg (1000x1000, 356K)

>sub 4 minutes for both stars

The fuck? I don't think I could even type my solutions out that fast.

Attached: sub4.png (541x73, 14K)

This is my suggestion for the calendar. Needs more posts.

Attached: day3.png (800x640, 699K)

it sure does. or are there ''two'' languages with that stupid r"" syntax?

How do you define cheating? Wouldn't anyone using regex be cheating?

Needs a quilt.

Why would you search that up when you can just type help(str) into the interpreter?

this is cool what did you use to make the image?

>tfw connection errors when trying to post my code

>it sure does. or are there ''two'' languages with that stupid r"" syntax?
so you literally don't even into python, but you are trying to be clever, fuck right off. raw/verbatim strings are in at least 5 languages i can think of right now

these guys have a lot of their boilerplate shit pre-written. it takes them four minutes because all they have to write is

step1 = function12422(data)
step2 = function342155(step1)
print(function18(step2))

Yea, pretty amazing if you ask me.

Moot put in a filter that filters out shit code. It's biased toward shit languages.

Attached: 1497669701711.jpg (846x900, 104K)

fuck hell, the cancer shouldn't have spread that far.
>raw/verbatim strings
You can do them lots of ways. Python's way is not the way.

looks great, just needs something in top left corner

Hopefully this is more readable
tested = set()

conflicts = set()

data = {}


for line in open("clothesInput.txt"):

line = line.split()

data[ line[0] ] = line[2].replace(':','').split( ',' ), line[3].split( 'x' )



for line in data.values():

cornerX = posX = int( line[0][0] ) + 1

cornerY = posY = int( line[0][1] ) + 1

width = int( line[1][0] )

height = int( line[1][1] )

for x in range( 0, width ):

for y in range(0, height ):

if ( posX , posY ) in tested:

conflicts.add( ( posX , posY ) )

else:

tested.add( ( posX , posY ) )

posY = cornerY + y

posX = cornerX + x

print( len( conflicts ) )

Why is codemonkey-tied string parsing part of the problem? Why not give the dataset as 1,151,671,11,15 or even just space-deliminated?

where dat big boy input at? i need it. i'm a big guy