/aocg/ - Advent of Code 2018 General #14

Fine I'll Make The New Thread 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: 1530801101048.png (1000x1000, 712K)

Other urls found in this thread:

pastebin.com/qwSjEqBb
pastebin.com/MZyeeAnD
pastebin.com/3fW3sf3a
pastebin.com/MqB5dksa
mega.nz/#!Ro1BkKyS!asDqLa5PRI-JTJJnv6k9Ujt3fjxJ1gTG55vg9E2yHxg
pastebin.com/x5UcedBR
pastebin.com/3gCxhyQ5
twitter.com/NSFWRedditGif

Will post question here again.
def part1(logs):
guards = defaultdict(list)
currentGuardID = None
minuteFallenAsleep = None
for log in logs:
currentMinute = int(log.split(" ")[1][3:5])
if "Guard" in log:
currentGuardID = int(log.split(" ")[3][1:])
minuteFallenAsleep = None
elif "falls asleep" in log:
minuteFallenAsleep = currentMinute
elif "wakes up" in log:
guards[currentGuardID] = guards[currentGuardID] + \
list(range(minuteFallenAsleep, currentMinute))

sleepyGuard = None
currentMax = 0
for k, v in guards.items():
if len(v) > currentMax:
currentMax = len(v)
sleepyGuard = k
return sleepyGuard * Counter(guards[sleepyGuard]).most_common(1)[0][0]

Anyone have any clue why I'm not getting mine to work? I'm adding every guard and a list of all the minutes the dude is sleeping, then I'm checking which guard has the most minutes slept and returning his ID * the minute he slept the most. The logs are sorted

Who here survived the wall?

Remember that if you consider this a wall, there's going to be a rude awakening two days from now

How does the Jow Forums leaderboards rank people? why are people with 3 stars above people with 4 stars?

not considering this wall.
What I am considering is not waking up earlier to attempt and solve these issues before going to work.

Repostan for ideas what happened:

Welp, that was tougher than I thought it would be. I got the math right but the dates got fucked during sorting.
Background: I had to add +1 to the month because it was 0-11. After sorting, the values were back to -1. Tried with std::sort and my own implementation of merge sort but same happened with both.

I had a std::vector where entry had a timestamp field with a std::tm struct where I changed the month with timestamp.tm_mon = 1 + timestamp.tm_mon.

Looks reasonable, does it work on the test input? Try printing a slice of data at a few points to see where it's going wrong

>tfw there's probably a way to abstract all the various queries I'm doing to one higher order function
>tfw don't know what it is

Wait until the multi threaded knot hashing emulator reverse engineering a bridge to the finale shows up

map part1bb() {
vector input;
string line;
ifstream file("bigboye.txt");
map sleepings;
vector::iterator falls, wakes;
pair < map::iterator, bool> ret;
pair sleepiest(0, 0);

while (getline(file, line)) {
vector tokens;
stringstream ss(line);
string temp;
if (line[19] == 'G') {
ret = sleepings.insert(pair(stoi(line.substr(26,4)), vector(60)));
}
if (line[19] == 'f') {
falls = ret.first->second.begin() + stoi(line.substr(15,2));
}
if (line[19] == 'w') {
wakes = ret.first->second.begin() + stoi(line.substr(15,2));
while (falls != wakes) {
(*falls)++;
falls++;
}
}
}
for (auto it = sleepings.begin(); it != sleepings.end(); it++) {
int sum = 0;
for (int x : it->second) {
sum += x;
}
if (sum > sleepiest.second) {
sleepiest.second = sum;
sleepiest.first = it->first;
}
}
auto max = max_element(sleepings.find(sleepiest.first)->second.begin(), sleepings.find(sleepiest.first)->second.end());
cout second.begin(), max) second) {
if (x > sl.second) {
sl.first = it->first;
sl.second = x;
}
}
}
cout second.begin(), find(sleepings.find(sl.first)->second.begin(), sleepings.find(sl.first)->second.end(), sl.second));
}

Still pretty dogshit.

Post times

Attached: IMG-20181204-WA0024.jpg (283x157, 13K)

Because of stuff like this. I started late into day 2

Attached: Screenshot_2018-12-04-18-47-54-804_org.mozilla.firefox.jpg (1080x346, 53K)

Same here. Started on evening of second day so I'm fucked

If you stick with it, you'll probably still come out ahead. Not everybody is going to stay around the whole 25 days.

who /lexicographic sort/ here

repostan
Whacha mean don't need it sorted globally?
Also I'm kinda proud of doing this without getting any cheaty help here. Maybe I'll make it after all.

Attached: day4.png (331x104, 3K)

I still hate it
import java.io.File
import kotlin.collections.HashMap

fun main(args: Array) {
val input = File("day4.txt").bufferedReader().readLines().sorted()
val regex1 = Regex("[:](\\d+)] (\\w)")
val regex2 = Regex("#(\\d+)")
var map: HashMap = HashMap()

var currentGuard = -1
var sleepTime = -1
input.forEach {
if (it[19] == 'G'){
val matches = regex2.find(it)
currentGuard = matches!!.destructured.component1().toInt()
if (!map.contains(currentGuard))
map[currentGuard] = IntArray(60)
} else {
val matches = regex1.find(it)
val (t, r) = matches!!.destructured
if (r == "f"){
sleepTime = t.toInt()
} else if (r == "w") {
for (i in sleepTime until t.toInt()) {
map[currentGuard]!![i] = map[currentGuard]!![i] + 1
}
}
}
}

// part 1
var sleepiestGuard = -1
var mostTimeSlept = -1
var sleepiestMinute: Int
map.forEach {
if (it.value.sum() > mostTimeSlept) {
sleepiestGuard = it.key
mostTimeSlept = it.value.sum()
}
}
sleepiestMinute = map[sleepiestGuard]?.indexOf(map[sleepiestGuard]?.max()!!)!!
println("part1: ${sleepiestMinute * sleepiestGuard}")

// part 2
var reliableGuard = -1
var mostSleptMinute = -1
map.forEach {
if (it.value.max()!! > mostSleptMinute) {
mostSleptMinute = it.value.max()!!
reliableGuard = it.key
}
}
println("part2: ${reliableGuard * map[reliableGuard]!!.indexOf(mostSleptMinute)}")
}

Kinda fun if you think of it like a tiny cpu with 3 instructions.

Guard
Wakes
Falls

Besides the initial freak out over sorting this problem was comfy.

Oh it works fine.... I don't know what I've been doing for the past hour my brain probably shut off.
I probably typed the wrong number in the website and thought my code was wrong ¯\_(ツ)_/¯

Ye I expect that to happen, and I'm not worried anyways since I'm learning to write better code quicker

saw
>import java.io.File
and thought that one more user is doing java.
Started skimming code...
>map[currentGuard]!![i]
>!! ?!
Good job user. Had me really confused for a while

>!!
>?
How to turn code in Java with Kotlin syntax :(

Can't sentence. up too late last night.
Meant:
>How to code in Java with Kotlin syntax :(

>>How to code in Java with Kotlin syntax :(
code in java... with kotlin syntax?... well user... use kotlin! It is java with kotlin syntax! (I don't know any kotlin by the way....)

who /lines.sort()/ here?

im the php guy

part 1
pastebin.com/qwSjEqBb
part 2
pastebin.com/MZyeeAnD

im in utc+1 timezone fuck

If you want to check the leaderboard for stars, here the most basic bitch js to drop in the console of your shitty browser to check in-page

var jq = document.createElement('script');
jq.src = "ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
console.log(document.querySelectorAll('.privboard-row .privboard-star-both').length, 'Gold Stars');
console.log(document.querySelectorAll('.privboard-row .privboard-star-firstonly').length,'Silver stars');
console.log(document.querySelectorAll('.privboard-row .privboard-star-unlocked').length, 'No Stars');
console.log(document.querySelectorAll('.privboard-row').length-1, 'In Leaderboard');
console.log($(".privboard-row:has(.privboard-star-unlocked)").length, "Pajeets with at least 1 problem unsoled");

Attached: file.png (560x43, 6K)

Well it compiles to java bytecode but by default kotlin is null safe, !! and ? basically force NPEs to be possible, so it's kind of frowned upon, but I'm not sure how to avoid it in all cases. With problems like these though, NPEs aren't too big a concern so maybe it's not that bad here.

Waking up every day at 5:50 is taking a bigger toll than I was expecting. Today I was tired and sleepy all day. I don't know if I can do this all the way through.

I read that as
>Today I was fired.
Just take more naps, user. This is important.

Alright I've been rewriting my solution and I stumbled on something fucking retarded. My program runs fine but if I remove one debug print I get an
panic: runtime error: invalid memory address or nil pointer dereference
Fucking wew lad.

language?

Looks like go, he's mutating something while evaluating the arguments.

Brainlet here, Can anyone help me figure out why my program isn't returning the correct minute for pt 1? I've verified that the part the gets the guardid is correct.
minutetracker = [0 for _ in range(0,60)]
k = guard[guardid]
for sl,w in k:
for minutemark in range(sl, w):
minutetracker[minutemark] += 1
print(guardid)
print(minutetracker.index(max(minutetracker)))
print(guardid * minutetracker.index(max(minutetracker)))

Attached: 1503200562241.gif (500x333, 900K)

I don't like it when my runtime tells me to panic.

Code?

>problem clearly states only the seconds 0-59 are relevant
>lines can simply be sorted lexicographically then iterated downwards in groups of two once an ID line is seen
>yet some people are parsing out the dates and sorting via them

Attached: 1412559397883.jpg (447x444, 35K)

s-shut up...

>>yet some people are parsing out the dates and sorting via them
I started doing this, even npm install moment...

And then I realised I can do the native JS lexicographic sort.

But counting and finding maxes in JS is painful.

You missed the people trying to turn it into a RDB

i feel like my code is degenerating as the days pass. i'm messing around with classes, but at least it's decently fast (total of ~17 ms with regular python for today)

how do i get better?

>this problem was comfy.
Definitely. I enjoyed putting together the analysis algorithm thinking about it like you. On each line you're given an instruction on what to do that cycle. Switch to a new guard, set the sleep flag, unset the sleep flag

Haskal

import Data.List
import qualified Data.Map as M

data Record = Record Int [(Int, Int)] deriving (Show, Eq)
type Table = M.Map (Int, Int) Int

parse :: [String] -> [Record]
parse [] = []
parse (x:xs) = (Record id sleeps) : (parse . drop (2 * length sleeps)) xs
where
id = (read . head . words . drop 26) x
sleeps = parseSleep xs

parseSleep :: [String] -> [(Int, Int)]
parseSleep [] = []
parseSleep xs
| (take 5 . drop 19 . head) xs == "Guard" = []
| otherwise = sleep : parseSleep (drop 2 xs)
where
minute x = (read . drop 15 . take 17) x
sleep = (minute (xs !! 0), minute (xs !! 1))

addRange :: Int -> (Int, Int) -> Table -> Table
addRange id (s, e) t = foldr (\k -> M.insertWith (+) (id, k) 1) t [s..(e - 1)]

add :: Record -> Table -> Table
add (Record id xs) t = foldr (addRange id) t xs

argmax :: (Ord b) => (a -> b) -> [a] -> a
argmax f as = maximumBy (\x y -> compare (f x) (f y)) as

main = do
input id)) events
let t = foldr add M.empty events

let idTime id m = M.findWithDefault 0 (id, m) t
let times id = map (idTime id) [0..59]

let sleepiest = argmax (sum . times) ids
print $ sleepiest * argmax (idTime sleepiest) [0..59]

let most = argmax (maximum . times) ids
print $ most * argmax (idTime most) [0..59]

>while evaluating the arguments.
What do you mean?

I fucking wish I had stuck with haskell the few months leading up to this. I wish I could be cool too.

Why isn't this regex working for capturing the date? "\[(.+)\s.+\]"

I'm using Java if that helps.

the stuff that you are passing to println

Don't know java, but a common problem in C-likes is that backslash is overloaded for inserting special chars so you need 2 backslashes for every 1 backslash you want in your regex

>regex
The date strings are always the same length. The values you're looking for will always start and stop at the exact same spot in the string. You don't need regex to find it.

The regex captures everything between the [ ] (including the [ ] characters).

Not enough info. Have you found the ID with the largest sum at this point? Does k have each instance of sleep, wake? And is "sl" "sleep-length"? You want sleep-start and the range you're updating should be the sleep length. If you're starting from the sleep length, it's obviously wrong.

Java forces you to escape correctly anyway because it throws errors otherwise
I suppose that's true.

Actually it still happens with or without the print, it's just less common to panic with the print. I'm assuming the garbage collector is fucking my shit up for some reason.

Why are you writing JS? I thought you were an engineer/professional athlete?

Are you sure you're actually using a computer?

I am starting to doubt it.

This is a test post. Please ignore.

Hi

ok noted

Not that I'm going to make the wrong decision, but I'm a lot more torn than I thought I would be on whether or not to ditch the girl I like on Friday night so I can keep a decent spot on the leaderboards. Maybe I'll bring my laptop...

are you using goroutines? if so it's more likely that you have a synchronization problem. Otherwise you actually found a runtime bug, you should report it to the go team.

I'm doing it in C# JS (the two languages I use at work on a day to day basis) and Ruby (the language I like best) rotating between each.

I'm a hobbyist athlete, I pay to compete and go to internationals. But sometimes my federation pays my entry fee (but not flights or accomodation)

rate me lads

pastebin.com/3fW3sf3a
pastebin.com/MqB5dksa

am i doing anything wrong?

Yes I have found the correct ID.
sl & w are the minute values for when the guard falls asleep and when he wakes up. k is used to retrieve sl & w and will look something like [(44,45), (35,55),....]
Here is all my code that I have so far.
def pt1():
guard = {}
currentguard = 0
woke = 0
slep = 0
for line in sleepschedule:
l = line.replace("[", "").split(']')
if l[1][1] == 'G':
k = l[1].split(' ')
currentguard = int(k[2][1:])
if int(k[2][1:]) not in guard.keys():
guard[int(k[2][1:])] = []
elif l[1][1] == 'f':
slep = int(l[0][14:])
else:
woke = int(l[0][14:])
guard[currentguard] += [(slep,woke)]

maxslep = 0
guardid = 0
for slpyguard in guard.keys():
totslp = 0
for slep,woke in guard[slpyguard]:
totslp += woke - slep
if totslp > maxslep:
maxslep = totslp
guardid = slpyguard
print(guardid)

minutetracker = [0 for _ in range(0,60)]
k = guard[guardid]
print(k)
for sl,w in k:
for minutemark in range(sl, w):
minutetracker[minutemark] += 1
print(guardid)
print(minutetracker.index(max(minutetracker)))
print(guardid * minutetracker.index(max(minutetracker)))

>are you using goroutines?
Nope
>Otherwise you actually found a runtime bug, you should report it to the go team.
Eh? I'm not doing anything complicated. I'll keep the assumption I'm doing something retarded for now.

>maximumBy (\x y -> compare (f x) (f y))
maximumBy (comparing f)

Haskell user mind sharing a paste of all their solutions or a fake github repo? I'm trying to learn the language and seeing how it's used on problems I'm familiar with would be really useful. Thanks.

>guard.keys()
heh

She might complain, but she'll probably see you as more desirable

Attached: times.png (667x117, 13K)

When I tried to async sort and early execute for part one (big boy data set), I got the same result for part one (Wrong) as part 2(Correct).
What gives?

Yes. I was, in fact, a complete retard.
You know how in Go you have to implement your own Len, Less and Swap functions to satisfy the Sort interface? Test that shit.

you could impress her (male) with you coding skills.

That's probably not gonna happen. If anything she'll find out I'm a fraud about 45 minutes in when I start putting the turban on and whipping out the nested for loops, souts, and excessive variables.

Who SQL here?
-- create table guard_log (time timestamp, event text)

with shifts (guard, start, stop) as (
select
substring(event, '#(\d+)'),
time,
max(time) over (
order by time asc
rows between current row and 1 following
)
from guard_log
where event ~ '#'
), sleeps (guard, start, stop) as (
select
s.guard, b.time, e.time
from shifts s
join guard_log b on b.time > s.start and b.time < s.stop
join lateral (
select *
from guard_log e
where e.time > b.time
order by e.time asc
limit 1
) e on true
where b.event = 'falls asleep' and e.event = 'wakes up'
)
select guard::int * minute
from sleeps s
join generate_series(0, 59) minute on
extract(minute from s.start)

Are you using an uninitialized struct or something else that requires initialization as a map or slice value?

I survived, but I may not be able to spend so much time on problems in the next week or so. I've got finals coming up.

I converted the lines into a custom timestamp format and then implemented my own comparator, which I used to sort them.

FUCK

I got the the point where I have all the info I should need, but somehow the sleepiest guard has multiple minutes where he is asleep for the same number of times. I.e. he's asleep 14 times each at minute 42,45,46. I have no clue what I'm missing.

Basically what I do is this (not gonna post my code I have like 200 lines and I'm bruteforcing this stuff with babysteps, it's an ugly mess and I'm ashamed)

>sort input
>extract relevant information into a List( List( ID, sleep, wake, [...] ), [...] )
>combine information into a Map (ID -> List(sleep, wake, [...]))
>turn this into a List( (ID, Array[60]) ), by incrementing the corresponding index for the minutes between each sleep/awake pair
>gets me a List with Elements like this: (73, [0,0,1,1,1,2,2,3,...]) for each guard ID
>find guard with the largest sum of the array
>find index of the maximum of the array

post input

link to bigboi input?

I had the same happen when where I "logged" when he was asleep forgot to set the loop starting point to the proper offset.

mega.nz/#!Ro1BkKyS!asDqLa5PRI-JTJJnv6k9Ujt3fjxJ1gTG55vg9E2yHxg

Part 1:
Sleepiest Guard: #2039
Minutes Spent Dozing: 469
Most Snoozed Time: 00:49
Result: 99911
Part 2:
Guard with Most Visits From Sandman: #1733
Number of Black-outs: 17
Optimum Rest Time: 00:38
Result: 65854
./day4.py 0.04s user 0.01s system 99% cpu 0.050 total

what language are you using?

>110MB
oh shit

C#
I got sorting down to 300ms by sorting subgroups, but concatting them to a result curiously took nearly as long as sorting the original large input (go figure, sorting is fast). But modding the program to be able to use async results from the smaller sorted parts was too much for me to go into right now.

Hashmaps!

pastebin.com/x5UcedBR

I just tried a solution from >leddit and the result isn't right either wtf.

I get 3122 and 4966

Attached: file.png (155x67, 4K)

real 3m24.130s
user 2m3.166s
sys 1m20.725s

Both tasks combined on poorly optimized sepples code and big boye input.

>sepples
The heck is that

with pypy:
pypy ./day4.py
16.55s user
0.78s system
99% cpu
17.368 total

but 57.7s with python3

Did you solve today's puzzle graphically?

Attached: 1134653624.png (606x766, 22K)

Can someone check my big boye results?
Solution 1: 146493
Solution 2: 154938
13.6057782s

Yeah it's a bit slow. I could easily save 5/10 seconds on the parsing by not converting strings to real dates but I learned about Go's time.Parse and I love it so I won't change it.

nice.
yeah, that's what I got too.

real 0m1,862s
user 0m1,770s
sys 0m0,092s

Beat that

Post code m8

same here

pastebin.com/3gCxhyQ5