/aocg/ - Advent of Code 2018 General #4

Previous thread: Why we fight edition

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.

Attached: 1513438190970.png (912x855, 59K)

Other urls found in this thread:

stackoverflow.com/a/53576032/8039441
Jow
repl.it/repls/FavorableRectangularPrediction
twitter.com/SFWRedditImages

I finally solved it for F# using an infinite sequence. is a perfectly correct solution but takes over an hour to produce a result
let input = @"
+1
-1
"
let cycle xs = seq { while true do yield! xs }
let accumusum xs = Seq.scan(fun acc elem -> acc + elem) 0 xs

let tryfind (sum, s:int Set) =
match s.Contains(sum) with
| true -> Some(sum)
| false -> None

let scanstate (sum, s:int Set) el =
el, s.Add(sum)

let findfreqcycle (data:int seq) =
let seen = Seq.scan scanstate (Seq.head data, Set.empty) (Seq.tail data)
Seq.pick tryfind seen

let data = cycle Seq.map int |> Seq.toList)
accumusum data |> findfreqcycle


I had to ask on StackOverflow what the problem was, it turns out that Seq.tail is ridiculously inefficient because it has the hidden cost of iteration and creating new IEnumerables that you don't normally think of.
The guy who answered my question made a better implementation of my first attempt, refer to stackoverflow.com/a/53576032/8039441

What are the chances this thread gets deleted due to the OP image being """""not advertiser friendly"""""?

those aren`t tiddies, just some ascii chars

Huh, didn't notice you were adding to the map before changing frequency

>1 hour
I can't believe you let it run that long. I would have figured I made a mistake after less than a minute

It's not as bad as it sounds, I had visual studio running in the background while developing in LINQPad

>mfw finally reading the backstory in Day 1

Attached: 1536640434430.jpg (1600x1130, 482K)

perl 5, runs in 64ms
#!/usr/bin/env perl
use 5.010;

@lines = `cat input.txt`;
$sum = 0;
$sum_seen = {};
while (1) {
foreach (@lines) {
$sum += $_;
if ($sum_seen->{$sum} == 1) {
say $sum;
exit;
}
$sum_seen->{$sum} = 1;
}
}

Comfy go
package main

import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"strconv"
)

const filename = "input"

func main() {
sol1()
sol2()
}

func sol1() {
inputs := getInputs()
var res int
for _, input := range inputs {
res = res + input
}
fmt.Printf("Res is %d after %d operations\n", res, len(inputs))

}

func sol2() {
inputs := getInputs()
reachedFreqs := make(map[int]struct{})
var res int
var found bool
var fullIterations int
for !found {
for i, input := range inputs {
reachedFreqs[res] = struct{}{}
res = res + input
_, ok := reachedFreqs[res]
if ok {
fmt.Printf("Res is %d after %d operations\n", res, i+1+len(inputs)*fullIterations)
found = true
break
}
}
fullIterations = fullIterations + 1
}
}
func getInputs() []int {
f, err := os.Open(filename)
defer f.Close()
if err != nil {
panic(err)
}
var inputs []int
r := bufio.NewReader(f)
for {
line, err := r.ReadSlice('\n')
if err != nil && err != io.EOF {
panic(err)
}
input, err2 := strconv.Atoi(string(bytes.Trim(line, "\n")))
if err2 != nil {
panic(err)
}
inputs = append(inputs, input)
if err == io.EOF {
break
}
}
return inputs
}

boilerplate
data = '''
data goes here retard
'''.strip().splitlines()

from collections import defaultdict
from itertools import cycle
from functools import reduce

def p1(data):
return

def p2(data):
return

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

Based

Reminder to use defaultdicts with complex numbers for indices for any grid problems.

Got correct results too

0.10ms

Damn fucking fast

>almost 2019
>not using simd

pub fn part1() {
let input = include_str!("../inputs/day1");
let mut frequencies: Vec = Vec::new();

for i in input.lines() {
frequencies.push(i.parse::().unwrap());
}

let mut sum = packed_simd::i32x4::splat(0);
let mut iteration = 0;
while let Some(slice) = frequencies.get(iteration..(iteration + 4)) {
sum += packed_simd::i32x4::from_slice_unaligned(slice);
iteration += 4;
}

let mut sum: i32 = sum.wrapping_sum();
if iteration < frequencies.len() {
for i in frequencies.iter().skip(iteration) {
sum += i;
}
}

println!("sum: {}", sum);
}

>>> squares = (n**2 for n in [1, 2, 3, 4, 5])
>>> 9 in squares
True
>>> 9 in squares
False

pyfags explain yourselves

rate my answer Jow Forums
runs real quick like and took all of about 5 minutes to write

import sys

def get_inputs(path='.'):
with open(path) as f:
return f.readlines()

def do_sum(list, mapping=False):
sum = 0
most_recent_freq = set()
most_recent_freq.add(sum)
while 1:
for freq in list:
sum += int(freq)
if (mapping):
if sum in most_recent_freq:
return sum
most_recent_freq.add(sum)
return sum

def main():
parsed_inputs = [inputs.strip() for inputs in get_inputs('./input.txt')]
print(do_sum(parsed_inputs, mapping=True))

if __name__ == '__main__':
main()

Your iterator is dried up. "in" iterates over the iterator passed to it, using it up. Squares should be a list.

it's a generator and it done generated
>>> squares = list(n**2 for n in [1, 2, 3, 4, 5])
>>> 9 in squares
True
>>> 9 in squares
True

Then explain this shit:
>>> squares = list(n**2 for n in [1, 2, 3, 4, 5])
>>> 9 in squares
True
>>> 9 in squares
False

Attached: tumblr_nral70hzfo1s71q1zo1_1280.png (1078x729, 444K)

if __name__ == '__main__':
main()

>tiny single use script

Attached: 1536431646867.png (400x400, 253K)

You have to use list() because the creates an iterator or some shit
werks on my machine

>not always writing with modularity in mind
technical debt builder detected

The explanation for that is you're lying.

>>> squares = list(n**2 for n in [1, 2, 3, 4, 5])
>>> 9 in squares
True
>>> 9 in squares
You think people would do that, just go on the internet and tell lies?

hi new go friend

it appears that the order in which benchmarks run advantages the solutions that are run later in the tests

D:\REPOS\adventofcode2018\D1\P2>go test -bench=.
goos: windows
goarch: amd64
BenchmarkMine-8 100 12447274 ns/op
BenchmarkAnon-8 100 12287396 ns/op
BenchmarkAnon2-8 100 12357252 ns/op
PASS
ok _/D_/REPOS/adventofcode2018/D1/P2 3.877s

D:\REPOS\adventofcode2018\D1\P2>go test -bench=.
goos: windows
goarch: amd64
BenchmarkAnon2-8 100 12326750 ns/op
BenchmarkAnon-8 100 12257445 ns/op
BenchmarkMine-8 100 12348055 ns/op
PASS
ok _/D_/REPOS/adventofcode2018/D1/P2 3.857s

D:\REPOS\adventofcode2018\D1\P2>go test -bench=.
goos: windows
goarch: amd64
BenchmarkAnon-8 100 12357442 ns/op
BenchmarkAnon2-8 100 12337038 ns/op
BenchmarkMine-8 100 12307337 ns/op
PASS
ok _/D_/REPOS/adventofcode2018/D1/P2 3.867s

Attached: 3way.jpg (600x239, 35K)

Needlessly verbose and structured for the purpose, but good otherwise. Don't know why you're importing sys though

Attached: 1513831092529.png (571x125, 12K)

how do you post code that looks good on here?

This is really shit but it works and I don't feel like spending more time on it.
(let* ((hash-table (make-hash-table))
(current-freq 0)
(iteration 1000))
(while (and (> iteration 0))
(setq iteration (- iteration 1))
(mapc (lambda (x)
(let ((next-freq (+ current-freq x)))
(setq current-freq next-freq)
(when (gethash current-freq hash-table)
(error "%s after %s iterations" current-freq iteration))
(puthash current-freq t hash-table)
))
advent-input-list)))

Like this

Attached: Capture.png (316x284, 12K)

Explain

Attached: wtf.png (710x169, 7K)

[ c o d e ] code that looks good [ / c o d e]
without spaces between the brackets

Jow Forums.org/rules
section Jow Forums

thanks

wtf??

Attached: worksonmymachine.png (200x193, 31K)

Have you tried turning it off and on again?

Are you also benching the file read? Probably better to just bench it with the slice of ints already populated.
Also be careful not to shadow the result while benching or it will just optimize it away
You can do b.Run after the bench setup just like tests to only bench what you want

Where do you newfags come from?

Here's my shitty code that took a minute to find the solution.
infile = open("day1.txt", "r")
lines = infile.readlines()
total = 0
listOfTotals = [0]
flag = True
while flag:

for line in lines :

# add to total if '+' found
if line[0] == "+":
newLine = line.split("+")
total += int(newLine[1])

# subtract total if '-' found
elif line[0] == "-":
newLine = line.split("-")
total -= int(newLine[1])

# if total is not a duplicate append to total list
if total not in listOfTotals:
listOfTotals.append(total)


else :
print(total)
flag = False

photoshopped

repl.it/repls/FavorableRectangularPrediction
press run button at top

>that python code
>VS
So this is the power of a Windows user.

each time you are searching the entire list, which is an O(n) operation... so your algorithm is running at O(n^2)

Nope

Attached: ueu.png (514x234, 8K)

Too fucking late Tucker.
Initiating Hacking...

how else would you do it?

what's up you stupid bastards who's ready for day 2

use a data structure that's easier to do lookups on, a hash/dictionary instead of an array

Jesus Christ, use a hash table. A list is a flat array that is O(n) to iterate each time you check total not in listOfTotals.

Use a set/dict, like literally everyone seems to have said already

I am, since we each approached loading the input differently while essentially using the same approach for p1 and p2

Attached: wtf.png (582x270, 19K)

Using a set over an array will change your runtime from 20s to about 0.000001 s

>run my part2 code on some of the test lists
>get the correct answer for each in milliseconds
>run my p2 code on the real list
>5 minutes later it's still running
How many times does the list loop because i've looped like 10 times already and no duplicates so far...

Nice. I used a tie'd hash that initializes values to 1 automatically after a failed lookup

Not me. I am going to bed.
It is fucking 4am here.

Tuck, my 'ol pal? Fancy running into you on Jow Forums!

that's a rookie move Eurofriend, start waking up bright and early at 6am

It looped 144 times on mine.

ok now you're just trolling

It loops 100+ times, make sure you're using a hash based data structure if you want it to run fast.

>day one is literally arithmetic
is the creator getting lazy

then doing readall is probably faster but mine reads from the file line by line without holding it all in memory at once

My first match was around index 130000, so the list looped like 140 times

your implementation is wrong or has a god awful complexity

I hope day 3 is going to be the great filter this year too

day 2 will be making a neural net from scratch, u happy?

brainlet here. i finally got it. it only took 5 minutes for the cmd to show 750

Attached: solution-1.png (633x576, 69K)

literally arithmetic followed by "do you know what a hashmap is"

nice

you used the wrong datastructure type
read above

>using itertools cycle
you 100% looked that answer up

No you fuck we said to use set not list
[CODE]FREQUENCY = {0}[/CODE]

>is a perfectly correct solution but takes over an hour to produce a result

Attached: thefuck.gif (320x289, 1.12M)

Someone told me to use itertools. i was using it before you combinations

No, I gave him that answer, with an explanation (), and he still fucked it up

The solution I used to solve the problem was still Python, but resembling C.
In real life I usually avoid doing that because it tends to blend implementation with logic, which makes code difficult to understand.
functional-style code, as written in the stackoverflow post, is usually compartmentalized such that the individual parts are very easy to understand, which then compose in a way that is also easy to understand.

Project Euler no. 1 is harder. Speaking of, how many have you guys done? I got bored of Pythagorean triples at problem 86.

class list:
def __init__(self, it):
self.it = it
def __contains__(self, th):
print(yield(self.it))
return th in self.it

10/10 had me going

>open(... 'r+')
>open(... 'r')

You don't need to specify 'r' if you're reading. Why did you do 'r+' on part 1?

"produces the correct answer" vs good

user I believe you may have contracted Boolean Distortion Aura

>You don't need to specify 'r' if you're reading.

you should anyway because explicit is better than implicit

>yield
>SyntaxError: invalid syntax
Explain. That line breaks it for me.

I was looking up tutorials for reading files and that's what they did

I'm proud of you.

How fucking pajeet can you be?

Attached: anger.jpg (1280x720, 77K)

what is the point of the leaderboard?

protip: people who write tutorials have no fucking clue what they're doing
they produce something that works and parade around it as if it were the fuckin holy grail.

probably. i used inputB, _ := ioutil.ReadFile("./input")
for _, n := range strings.Split(string(inputB), "\n") {
which seems fast enough

individual benches:
BenchmarkMine-8 100 12297365 ns/op
BenchmarkAnon-8 100 12317312 ns/op
BenchmarkAnon2-8 100 12247420 ns/op


finding the cause for a spread of 0.00007s isnt something im gonna get in to, I just wanted to dick around with benchmarking

looking forward to your day2 solutions

Typo. Main point is you're overriding the native list type in python. Why?

I get the new number and check to see if it's the array of previous numbers. If it isn't I add it to the array of previous numbers and continue. It's obvious checking this massive list constantly is slowing things down so I figured I'd just generate a massive list of numbers and then check that for duplicates. I get a ton of duplicates but now the challenge is which is the "first" that appears as the list is being created.

I was wanting to do this in C but it seems like languages like Python can do this quite easily since they have a much faster built-in way of checking to see if a number already exists in a list.

>tfw official Advent of Code programming socks don't go up to the thighs

Attached: 1541816092119.jpg (480x480, 131K)

that's not child porn, just some colors

>go
>benchmarking
ahahahahahahaaha

To see if I could recreate the results in for laffs

How deep does this troll rabbit hole go?

You're on the right track. What kind of data structure could you use instead of an array that can contain only one of each element?

>she doesn't know about the doctor who easter egg

Attached: TARDIS.png (837x160, 18K)