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.
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
Chase Ramirez
What are the chances this thread gets deleted due to the OP image being """""not advertiser friendly"""""?
Brandon Fisher
those aren`t tiddies, just some ascii chars
Easton Jackson
Huh, didn't notice you were adding to the map before changing frequency
Leo Barnes
>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
Xavier Lopez
It's not as bad as it sounds, I had visual studio running in the background while developing in LINQPad
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 }
Ayden Torres
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))
William Morris
Based
Andrew Lewis
Reminder to use defaultdicts with complex numbers for indices for any grid problems.
Julian Miller
Got correct results too
0.10ms
Damn fucking fast
Jackson Cruz
>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); }
Isaiah Rogers
>>> squares = (n**2 for n in [1, 2, 3, 4, 5]) >>> 9 in squares True >>> 9 in squares False
pyfags explain yourselves
Hudson Turner
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()
Carson Bennett
Your iterator is dried up. "in" iterates over the iterator passed to it, using it up. Squares should be a list.
Parker Sanchez
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
Samuel Martinez
Then explain this shit: >>> squares = list(n**2 for n in [1, 2, 3, 4, 5]) >>> 9 in squares True >>> 9 in squares False
You have to use list() because the creates an iterator or some shit werks on my machine
Henry Lewis
>not always writing with modularity in mind technical debt builder detected
Connor Nguyen
The explanation for that is you're lying.
Adrian Hill
>>> 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?
Blake Lee
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
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)))
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
Jacob James
Where do you newfags come from?
Jordan Wright
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)
Using a set over an array will change your runtime from 20s to about 0.000001 s
Ethan Hughes
>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...
Bentley Baker
Nice. I used a tie'd hash that initializes values to 1 automatically after a failed lookup
Grayson Garcia
Not me. I am going to bed. It is fucking 4am here.
Ryan Mitchell
Tuck, my 'ol pal? Fancy running into you on Jow Forums!
Eli Hernandez
that's a rookie move Eurofriend, start waking up bright and early at 6am
Aiden Thomas
It looped 144 times on mine.
Carter Murphy
ok now you're just trolling
Luke Martinez
It loops 100+ times, make sure you're using a hash based data structure if you want it to run fast.
Cooper Wilson
>day one is literally arithmetic is the creator getting lazy
Nolan Adams
then doing readall is probably faster but mine reads from the file line by line without holding it all in memory at once
Jacob Flores
My first match was around index 130000, so the list looped like 140 times
Adam Young
your implementation is wrong or has a god awful complexity
Hunter Ross
I hope day 3 is going to be the great filter this year too
Christian Powell
day 2 will be making a neural net from scratch, u happy?
Caleb Clark
brainlet here. i finally got it. it only took 5 minutes for the cmd to show 750
Someone told me to use itertools. i was using it before you combinations
Michael Watson
No, I gave him that answer, with an explanation (), and he still fucked it up
Ian Rodriguez
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.
Nolan Rodriguez
Project Euler no. 1 is harder. Speaking of, how many have you guys done? I got bored of Pythagorean triples at problem 86.
James Cooper
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
Nathaniel Smith
>open(... 'r+') >open(... 'r')
You don't need to specify 'r' if you're reading. Why did you do 'r+' on part 1?
Connor Williams
"produces the correct answer" vs good
Evan Martin
user I believe you may have contracted Boolean Distortion Aura
Adrian Collins
>You don't need to specify 'r' if you're reading.
you should anyway because explicit is better than implicit
Jaxson Lopez
>yield >SyntaxError: invalid syntax Explain. That line breaks it for me.
Benjamin Nguyen
I was looking up tutorials for reading files and that's what they did
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.
Lucas Torres
probably. i used inputB, _ := ioutil.ReadFile("./input") for _, n := range strings.Split(string(inputB), "\n") { which seems fast enough
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
Jordan Bennett
Typo. Main point is you're overriding the native list type in python. Why?
Benjamin Reyes
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.
Wyatt Nelson
>tfw official Advent of Code programming socks don't go up to the thighs