/aocg/ - Advent of Code 2018 General #3

Previous thread: Read the instructions 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: read_the_instructions.png (717x558, 344K)

Other urls found in this thread:

stackoverflow.com/questions/1494178/how-to-define-hash-tables-in-bash
gist.github.com/CameronAavik/2cd37a899290da1e8ad43c6d51a28796
artima.com/weblogs/viewpost.jsp?thread=98196
pastebin.com/ZHCfLavQ
twitter.com/SFWRedditImages

You should put SICP in the picture.

Swift

func partOne(_ input: [String]) -> Int {
return input.map { Int(String($0)) ?? 0 }.reduce(0, +)
}

print(partOne(input))

func partTwo(_ input: [String]) {
let inputFixed = input.map { Int(String($0)) ?? 0 }
var already_seen = Set()
var freq = 0
var found_repeat = false
while !found_repeat {
for val in inputFixed {
freq += val
let (insertWasSuccessful, insertedValue) = already_seen.insert(freq)
if !insertWasSuccessful {
print(insertedValue)
found_repeat = !insertWasSuccessful
break
}
}
}
}

partTwo(input)

You should choke on a dick.

LITERALLY
SEE
THE
OP
IMAGE
YOU
DROOLING
RETARD

look at the OP picture you nigger.

>mixing camel case and snake case
That's what I get for "porting" my C++ solution I guess.

Nah, algos book much more represents the current situation.

tfw this is only point in the year where I am motivated to learn to code shit
I don't even browse chans anymore

Attached: u-xYG6DTedo_00:00:55.666_0002.png.jpg (1280x720, 113K)

sorry :c

public long Duplicate()
{
while (true)
{
foreach (var n in _input)
{
_curfreq += n;
if (!_seen.Add(_curfreq))
{
return _curfreq;
}
}
}
}


I made it work though :)

>>caring about normie conventions
ISHYGDDT.mp9

>var names > 1 char

let main_2 nums =
let freqs = Hashtbl.create 256 in
let l = Array.length nums in
let rec loop s i =
let x = nums.(i) in
let s = s + x in
if Hashtbl.mem freqs s then
s
else
begin
Hashtbl.add freqs s ();
loop s (succ i mod l)
end in
let s = loop 0 0 in
print_int s
;;

check out my shitty bash solution for part 2 from someone who doesnt know bash
i had to wait a couple minutes for it to run

Attached: 2018-12-01-135813_459x478_scrot.png (459x478, 12K)

Put code tags you nigger

I did it mum.

def main():
frequency = 0
frequencies = set([frequency])
data = open('input', 'rt').readlines()

while True:
for frequency_drift in data:
frequency += int(frequency_drift.strip())

if frequency not in frequencies:
frequencies.add(frequency)
else:
return print(frequency)


I am pretty sure I will be dropping soon.

>day one
>will be dropping soon

Attached: file.png (885x1000, 338K)

How can we make Advent of Code more lewd?

Attached: judy_lewd.jpg (587x606, 78K)

implement FUCKING HASH/SET/MAP/DICTIN BASH RIGHT NOW
is there something that Guido would not implement in python?
we are on 4channel, sorry

Attached: byNaVrE0KrA_00:25:51.240_0004.png.jpg (320x240, 15K)

>is there something that Guido would not implement in python?
switch/case statements

: get-data ( path -- data )
utf8 file-contents "\n"
split [ string>number ] map
f swap remove ;

: solution-1 ( path -- n )
get-data sum ;

: search-frequency ( fset cur -- fset cur )
[ + ] accumulate ;

: find-frequency ( fset lset -- res )
swap [ over member? ] find 2nip ;

: return-frequency ( fset rset -- lset )
2dup [ over member? ] filter nip dup empty?
[ drop append ]
[ nip find-frequency ] if ;

: solution-2-loop ( fset cur list -- fset cur list )
[ 2dup search-frequency ] dip
[ nip ] 2dip return-frequency
dup sequence? [ solution-2-loop ]
[ ] if ;

: solution-2 ( fset cur -- fset cur )
2dup search-frequency [ nip ] dip
solution-2-loop swap . ;

Attached: asd.png (297x200, 21K)

useless

I can safely paste the whole thing into TempleOS now. However, + turns into / and - into }

my post is more likely to be read if it has an image tho
#!/bin/bash

IFS=$'\n'

fsum=0
sum=0
iters=1

>sums

for m in $(cat $1); do # get all frequencies for one iteration of the inputs
echo $fsum >> sums
fsum=$((fsum$(echo $m))) # final frequency after one iteration of inputs
done

echo "final sum: $fsum"

c_sums=$(cat sums)
eqs=$@

while true; do # continue reading from input
echo "iter: $iters"
for n in $c_sums; do # iterate through all frequencies
for s in $c_sums; do
su=$(($s+($iters*$fsum))) # compare with frequency + input reads * final freq
if [ $su -eq $n ]; then # save all matches for that iteration
eqs+=( $n )
fi
done
done
for z in $c_sums; do # return match that occurred first in that iteration
for e in ${eqs[@]}; do
if [[ $(($z+($iters*$fsum))) == $e ]]; then
echo $e
exit
fi
done
done
unset eqs
iters=$((iters+1)) # times input was read
done

commented it as best i could this time

What's the cut line for a non-brainlet runtime?

fun part1 (): Int {
var frequency = 0
File("day1.txt").bufferedReader().readLines()
.forEach {frequency += Integer.valueOf(it)}
return frequency
}
fun part2 (): Int {
val input = File("day1.txt").bufferedReader().readLines()
var frequency = 0
var map: HashMap = HashMap()
while(true){
input.forEach {
frequency += Integer.valueOf(it)
if (map.containsKey(frequency))
return frequency
map[frequency] = 0
}
}
}

Sort of cleaned up my code from last night.

swift switch case is betterr

Is it possible that my input has no repeated frequency? I know my code works on a constructed example of "-1, 2, 3, -3" and correctly yields 1. But the supplied input doesn't work.

...

no all generated inputs are tested to be working before the puzzle releases

implement sed on TempleOS
stackoverflow.com/questions/1494178/how-to-define-hash-tables-in-bash
oh I forget how bash has tons of features that do not make any sense (but if you implement it yourself it will be much better)

Attached: glenda_glassesblack.png (300x326, 23K)

I hope that ms means minutes

are we still doing the offset one? also how do i time this shit properly?

module Main where
import System.Environment
import Control.Lens
import Data.Maybe
import Text.Read

getSign :: String -> Maybe Int
getSign line = do
(line ^? element 0) >>= signToBool
where⸱
signToBool '+' = Just 1
signToBool '-' = Just (-1)
signToBool _ = Nothing

getOffset :: String -> Maybe Int
getOffset line = do
sign

Attached: aoc.png (993x77, 11K)

No. You're doing it wrong. Read the threads.
To be fair, I don't think Any of the previous years had something that would trip people up on data structure choice in the first day.

The input file repeats itself over and over until there's two repeating frequencies

>converting to int for every repeat
yikes

(defun read-frequency-changes ()
(let ((input (open "input" :if-does-not-exist nil))
(frequency-changes (make-array 5 :fill-pointer 0 :adjustable t)))
(loop for line = (read-line input nil)
while line do (vector-push-extend (parse-integer line) frequency-changes))
frequency-changes))

(defun part-one ()
(reduce #'+ (read-frequency-changes)))

(defun part-two ()
(let ((visited-frequencies (make-hash-table))
(frequency 0))
(loop (loop for change across (read-frequency-changes)
if (gethash frequency visited-frequencies) do
(return-from part-two frequency)
else do (setf (gethash frequency visited-frequencies) t)
do (incf frequency change)))))

Go! Below 20ms.
func main() {
var moves []int
file, _ := os.Open("input.txt")
scanner := bufio.NewScanner(file)
for scanner.Scan() {
i, _ := strconv.Atoi(scanner.Text())
moves = append(moves, i)
}

freq := 0
previous := make(map[int]bool)

for {
for _, j := range moves {
previous[freq] = true
freq += j
if previous[freq] {
fmt.Println(freq)
return
}
}
}
}

no milliseconds, my lua solution runs in 16ms without jit so if you can't get a lower level language under 30 you're doing something completely fucking wrong

>if elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif elif
>good

And the hacked-together dict implementation some use is even uglier

"""ugly""" lol

F#. Seems to be limited at a couple hundred iterations a second. The fuck?
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 rec findfreqcycle (s:int Set) (data:int seq) =
let head, tail = Seq.head data, Seq.tail data
match s.Contains(head) with
| false -> findfreqcycle (s.Add(head)) (tail)
| true -> head

let data = input.Trim().Split('\n') |> Seq.map int |> cycle
accumusum data |> findfreqcycle Set.empty

Think I'm gonna bust out Visual Studio's debugger for this one.

use os.Stdin instead of fighting with the file.

What's your execution times bros?
C# 10-17 ms including method calls and stopwatch instantiations

Attached: 1444225448641.jpg (362x362, 30K)

nice. i had no idea bash had dicts or anything like that. I should probably learn it more.
my solution doesnt really use dicts or anything though. it is worse for runtime but easier on memory

sed?
the problem is I can't even fucking get the list of numbers to get imported

>it is worse for runtime but easier on memory
which is kinda stupid since you're trading a

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

and then when you get all the stars the boobs will start jiggling

People comparing times here, you doing it for both parts, or just for part 2?

We have a warrior. I'm with you user.

p2 since p1 runs in less than 1ms anyway

Part one time is almost negligible anyway

>using loop
>using double loop
Disgusting

thanks, using this as an opportunity to move away from python

def starone(listf):
result = 0
for i in listf:
result += int(i)
return(result)
def startwo(listf):
frequency, seen = 0, {0:1}
i, l = 0, len(listf)
while 1:
while i < l:
frequency += int(listf[i])
if frequency in seen: return(frequency)
else: seen[frequency] = 1
i += 1
i = 0

if __name__ == '__main__':
import timeit
file = open("Z:\input.txt", 'r')
lists = [i for i in file.readlines()]
print(starone(lists))
print(startwo(lists))
j = timeit.timeit('starone(lists)', setup="from __main__ import starone", globals=globals(), number=100)
print("starone(lists) took", j, "for 100 loops at", j/100, "per loop")
j = timeit.timeit('startwo(lists)', setup="from __main__ import startwo", globals=globals(), number=100)
print("startwo(lists) took", j, "for 100 loops at", j/100, "per loop")

I wonder if it's faster to search a list than a dict or if try-catch can be even faster for dict search than "key in dict"

Just tried Initializing a new Int only list initially via map, and then during the first cycle. Both took about 10ms LONGER than parsing the int every cycle. I'm actually kinda surprised, I thought it would have been way better.

>I wonder if it's faster to search a list than a dict
no, just use a set, also you could convert to int before the while loops so you don't do that for every iteration

what the fuck is the second part asking?

It's asking for a number.

pretend the list is circular now

My code runs for over 20minutes now

Attached: 1507841079654g.jpg (960x960, 291K)

STOP COMING TO THREADS WITH SOLUTIONS BEFORE YOU SOLVE IT YOURSELVES YOU NIGGERS
you're literally missing the point of the challenge entirely like why do you even participate retards

Nice

2 ms in C.

Please calm down.

Woah, look at this duuude

(defun 1-1 (input-file)
(with-open-file (stream input-file)
(apply #'+
(loop for line = (read-line stream nil)
while line
collect (parse-integer line)))))

(defun 1-2 (input-file)
(with-open-file (stream input-file)
(labels ((rec (list current seen)
(let ((new (+ current (car list))))
(if (gethash new seen)
new
(progn
(setf (gethash new seen) t)
(rec (cdr list) new seen))))))
(let ((list (loop for line = (read-line stream nil)
while line
collect (parse-integer line))))
(setf (cdr (last list)) list)
(rec list 0 (make-hash-table))))))


Is there a benefit to having your changes in a vector if you're going to walk over them all anyways?
Also your use of loop is unreadable. And return-from too.

Plebbit had an interesting writeup on reducing part 2 to a simpler problem.

gist.github.com/CameronAavik/2cd37a899290da1e8ad43c6d51a28796

Attached: 1521383779588.png (872x1481, 210K)

I'd fucked my timers up, the actual time was 5ms. That's still a pretty yuge difference though. I suppose object instantiations and methods call are taking a bit longer under the hood when doing timers and such.

Getting slightly better performance when using a BTreeSet instead of a HashSet in Rust

import java.io.*;
import java.util.*;
public class FrequencyReader {
public static void main(String[] args){
List list = new ArrayList();
File file = new File("C:\\Users\\niggers\\Desktop\\freqread.txt");
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
String text = null;
while ((text = br.readLine()) != null) {
list.add(Long.parseLong(text));
}
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
try {
if (br != null) {
br.close();
}
}catch(IOException e){

}
}
System.out.println(list.stream().mapToLong(i ->i).sum());
}
}


shit on my day 1 solution bros

I forgot about cyclical lists, and I wanted to use an array anyway.

function* frequencies(offsets) {
let i = 0;
let frequency = 0;
while (true) {
frequency += offsets[i];
yield frequency;
i++;
if (i >= offsets.length) {
i = 0;
}
}
}

function findDuplicateFrequency(offsets) {
const s = new Set();
s.add(0);
for (let frequency of frequencies(offsets)) {
if (s.has(frequency)) {
console.log(frequency);
return frequency;
} else {
s.add(frequency);
}
}
}

findDuplicateFrequency(document.querySelector('pre').innerText.split('\n').map((n) => Number.parseInt(n, 10)).filter((n) => !isNaN(n)));


ES6 generators are pretty nice.

What can I say, a man likes his LOOPs. My use of vector was arbitrary; I just wanted to learn about arrays. Who knows, maybe iterating over an array is faster than a linked list.

>wHaT iF yOuR iNpUt Is OnE GoRiLLiOn
you have to go back

>try{} catch(){} catch(){} finally{try{} catch(){}}

Attached: 1532421245163.jpg (1300x956, 89K)

Absolutely niggerlicious.

Attached: 1502072398517.gif (255x145, 595K)

try:
return(seen[frequency])
except KeyError as e:
seen[frequency] = frequency runs 100 in 13.8 seconds
if frequency in seen: return(frequency)
else: seen[frequency] = 1 runs 100 in 8 seconds
parsing int on list creation knocks down the time for both to 11.4 and 5.8 seconds respectively, nice
if frequency in seen: return(frequency)
else: seen.add(frequency) runs in about 6.2 seconds using seen as a set instead of a dict

Anything functionally-oriented, if he had his way.
artima.com/weblogs/viewpost.jsp?thread=98196

There were challenges last year with input that caused exactly that kind of runtime when brute-forced, regardless of data structure.

gotta catch those exceptions user

I had the same intuition some hours ago.

>needing a PhD in Frequency Analysis for a Xmas coding challenge
yes patterns need to be exploited when the naive sol'n fails

Is the the cycle length for part two supposed to be super long or am I brainlet who fucked up the simplest exercise?

Use a hashmap.

there's no upper bound defined

>BufferedReader
Bruh you can do all that in one line, shit like that is why people call java verbose.
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.IntStream;

public class Challenge {
private static IntStream streamFreqs() {
try {
return Files.lines(Path.of(Challenge.class.getResource("/input1").toURI())).mapToInt(Integer::valueOf);
} catch (IOException | URISyntaxException e) {
return IntStream.empty();
}
}

public static void main(String[] args) {
int[] freqs = streamFreqs().toArray();
Set reached = new HashSet();
IntStream.iterate(1, i -> i + 1)
.map(i -> IntStream.generate(() -> 0)
.flatMap(ï -> Arrays.stream(freqs))
.limit(i)
.reduce(0, (a, b) -> a + b)
).dropWhile(reached::add)
.findFirst()
.ifPresent(System.out::println);
}
}

I know, my question is if the naive approach is good enough or is it going to be sixteen trillion steps before we reach a repeat.

For what?

>shit like that is why people call java verbose.
proceeds to post that disgusting code. poo in loo.

Send your input, we gonna tell you.

Can't really go below 100ms so I'll just blame my computer.

and is that supposed to look any better

>For what?
state of neo Jow Forums

>8 imports for a fizzbuzz tier algorithm

post solution

>For what?
Storing the previous frequencies. The most common mistake in this thread has been using a list/array.

Way too late here so I won't be submitting the HolyC solution today.

Don't forget to post it tomorrow. I want to see it!

pastebin.com/ZHCfLavQ

Chill out mate, I'm tired. If you mean for lookup I guess that answers my question as to the scale of the loop we're looking at.