/aocg/ - Advent of Code 2018 General #13

The First Filter 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: quick1.png (1000x1000, 886K)

Other urls found in this thread:

pastebin.com/raw/MKdJDymC
pastebin.com/MGbwZim3
pastebin.com/LWnqvVvv
ghostbin.com/paste/km4q5
paste.ofcode.org/6nVuYkeZta5Njz8FRvirGU
mega.nz/#!Ro1BkKyS!asDqLa5PRI-JTJJnv6k9Ujt3fjxJ1gTG55vg9E2yHxg
twitter.com/SFWRedditGifs

First for FUCK datetimes and fuck date people

second for india superpower by 2020

alright, which one of you Jow Forumsentlemen had the most pajeet solution to day 4? show me at your worst

pastebin.com/raw/MKdJDymC

Attached: jeet.png (1155x998, 154K)

>my code is so bad it gives a connection error

Attached: ohno.gif (400x300, 1.7M)

rate

I am not proud of this

Attached: day4.png (1702x1794, 266K)

thanks to the user who helped me realize how fucked my usage of range() was
# imports...
def record_sleep(data):
sleep_times = defaultdict(lambda: [0]*60)
guard_id = -1
sleep_date = None
for current_date, message in data:
if message > 0: # shift change
guard_id = message
sleep_date = None
else:
if sleep_date is None: # falls asleep
sleep_date = current_date
else: # wakes up
for m in range(sleep_date.minute, current_date.minute):
sleep_times[guard_id][m] += 1
sleep_date = None
return sleep_times

def p1(sleep_times):
guard = max(sleep_times.items(), key=lambda x: sum(x[1]))
minute = max(guard[1])
return guard[0] * sleep_times[guard[0]].index(minute)

def p2(sleep_times):
guard = max(sleep_times.items(), key=lambda x: max(x[1]))
minute = max(guard[1])
return guard[0] * guard[1].index(minute)

# if name main
# parsing
data = []
for i in input:
j = [k for k in i.split() if k]
date = parser.parse(' '.join(j[0:2]))
message = int(j[2])
data.append((date, message))
# execution
sleep_times = record_sleep(data)
print(p1(sleep_times))
print(p2(sleep_times))

I'm not sure if it's even possible to apply any algorithmic nonsense to this. It's just a parsing problem.

>completely pajeeted out
>still moved up 2 spots on Jow Forums leaderboard
I'll take it, i guess. Strongly considering switching to haskell even though I'm still a novice with it.

all the money's gone nowhere to go

jesus christ

Attached: uhhh.png (70x727, 8K)

also for some reason Jow Forums was blocking my post but my inputs look like this
input = '''
1518-02-03 00:03 691
1518-11-23 00:50 -2
'''.strip().splitlines()

>the absolute state of pastefags

hey lads i passed out and i just peeked at the thing it looks like more retarded string parsing, is it?

do it, i'm literally in these threads 20 hours a day helping with haskell

Here's my Enterprise Codeā„¢ from last thread.

Attached: 1543903954421.png (1548x4326, 324K)

It's EXTRA retarded string posting. If you can't figure out what the problem is (yes it's that bad) we can tell you

pretty colours

Attached: 123.png (692x423, 30K)

>kwrite
based and redpilled
Please tell me you didn't write that main function manually, that has to be reasonably easy to generate using awk

It finishes in 1ms though.

says the leaderboard is full

you'll have to wait until the no-star brainlets get removed for inactivity

Try the second

Only used kwrite for the code overview on the right.
I used a vim macro to make the code. Never learned sed or awk.

Well, yeah... the processing went into generating the code.

There's only a single no-star in the leaderboard, it was purged yesterday and it filled back again.

What's the point of the private leaderboards? I'm not sure how it works.

Python / pyspark
import pyspark
sc = pyspark.SparkContext()

data = sc.textFile('./input')
sorted_data = data.sortBy(lambda x: x).collect()
# Screw it, not doing this part in spark, it's totally sequential
assign_guards = []
for row in sorted_data:
if 'Guard' in row:
guard = int(row.split(' ')[3][1:])
else:
assign_guards.append((guard, row))
data = sc.parallelize(assign_guards)


fall_events = data.filter(lambda x: 'falls' in x[1])
wake_events = data.filter(lambda x: 'wakes' in x[1])

take_minute = lambda x: (x[0], x[1][15:17])
fall_asleep = fall_events.map(take_minute).zipWithIndex().map(lambda x: (x[1], x[0]))
wake_up = wake_events.map(take_minute).zipWithIndex().map(lambda x: (x[1], x[0]))

sleep_intervals = fall_asleep.join(wake_up).map(lambda x: x[1])

sleep_ranges = sleep_intervals.map(lambda x: (x[0][0], (int(x[0][1]), int(x[1][1]))))

guards_sleeping_minutes = sleep_ranges.mapValues(lambda x: x[1] - x[0]).reduceByKey(lambda x, y: x + y)
first_guard = guards_sleeping_minutes.sortBy(lambda x: x[1], ascending=False).take(1)[0][0]

sleep_minutes = sleep_ranges.filter(lambda x: x[0] == first_guard).flatMapValues(lambda x: range(x[0], x[1])).map(lambda x: x[1])
first_time = sleep_minutes.map(lambda x: (x, 1)).reduceByKey(lambda x, y: x + y).sortBy(lambda x: x[1], ascending=False).take(1)[0][0]

print('Part 1: ' + str(first_guard * first_time))

full_sleep_minutes = sleep_ranges.flatMapValues(lambda x: range(x[0], x[1]))
second_guard, second_time = full_sleep_minutes.map(lambda x: (x, 1)).reduceByKey(lambda x, y: x + y).sortBy(lambda x: x[1], ascending=False).take(1)[0][0]

print('Part 2: ' + str(second_guard * second_time))


Fuck that first bit, I have no idea how to properly distribute something like that where it basically needs to be done in sequence.

//...

fn part_one(guards: &HashMap) -> i32 {
let max_guard = guards
.iter()
.map(|(_, g)| g)
.max_by_key(|g| g.get_total_sleep())
.unwrap();

max_guard.id * max_guard.get_highest_freq_minute().0
}

fn part_two(guards: &HashMap) -> i32 {
let guard = guards
.iter()
.max_by_key(|(_, v)| v.get_highest_freq_minute().1)
.map(|(_, v)| v)
.unwrap();

guard.id * guard.get_highest_freq_minute().0 // can't map above, lifetime issues ahoy
}

//...

#[derive(Debug)]
struct Duration {
minutes: i32,
sleep_minutes: Vec,
}

impl Duration {
fn from_sleep(start: i32, end: i32) -> Duration {
Duration {
minutes: end - start,
sleep_minutes: (start..end).collect(),
}
}
}

type Minute = i32;
type Frequency = i32;

#[derive(Debug)]
struct Guard {
pub id: i32,
pub sleep_durations: Vec,
}

impl Guard {
fn new(id: i32) -> Guard {
Guard {
id,
sleep_durations: Vec::new(),
}
}

fn add_sleep_duration(&mut self, duration: Duration) {
self.sleep_durations.push(duration);
}

fn get_total_sleep(&self) -> i32 {
self.sleep_durations.iter().map(|d| d.minutes).sum()
}

fn get_highest_freq_minute(&self) -> (Minute, Frequency) {
let mut numbers = HashMap::new();

self.sleep_durations
.iter()
.flat_map(|d| d.sleep_minutes.clone())
.for_each(|min| {
*numbers.entry(min).or_insert(0) += 1;
});

let result = numbers
.iter()
.max_by_key(|&(_, count)| count)
.unwrap_or_else(|| (&0, &0)); //some guards don't sleep apparently...

(result.0.clone(), result.1.clone())
}
}


spent too long fucking around with data structures, should've just gone straight in with some imperative shit
whatever time to sleep

i have work in a few hours so honestly i cba right now but thanks

Just curious, did any of last year's problems involve trees or graphs? I am hoping to get some data structure practice soon

Reposting test data from last thread:

pastebin.com/MGbwZim3

Part 1
GUARD: 3457
MINUTE: 40
TOTAL: 138280

Part 2
GUARD: 1901
MINUTE: 47
TOTAL: 89347


pastebin.com/LWnqvVvv
part 1:
ID: 131
MINUTE: 36
TOTAL: 4716
part 2:
ID: 2389
MINUTE: 49
TOTAL: 117061

from collections import *
import re

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

ds = defaultdict(int)
dm = defaultdict(lambda : [0]*60)
curr, s, e = None, None, None

for l in ls:
l = l.split(' ')
y,m,d = list(map(int,re.findall(r'[\d]+', l[0])))
hh,mm = list(map(int,re.findall(r'[\d]+', l[1])))
if l[3][0] == '#':
curr = int(l[3][1:])
elif l[3] == "asleep":
s = mm
else:
e = mm
ds[curr] += e-s
for m in range(s,e):
dm[curr][m] += 1

mms = max((ds.values()))

gid = None
for k in ds.keys():
if ds[k] == mms:
gid = k

fmm = dm[gid].index(max(dm[gid]))

print("guard id: ", gid)
print("minutes slept: ", mms)
print("frequent minute: ", fmm)
print("(guard id) x (frequent minute): ", gid * fmm)

Kotlin meme coming through:
class Guard {
val timesAsleepOnMinute = Array(60){ 0 }
var totalSleep = 0
}

fun main(args: Array) {
val guards = mutableMapOf()
var lastGuard: Guard? = null
var lastSleep: Int? = null
input.sortedBy{ it }.forEach {
val tokens = it.split(' ')
val time = tokens[1].substring(3, 5).toInt()
when(tokens[2]) {
"Guard" -> lastGuard = guards.getOrPut(tokens[3].drop(1).toInt(), ::Guard)
"falls" -> lastSleep = time
"wakes" -> {
(lastSleep!! until time).forEach{ lastGuard!!.timesAsleepOnMinute[it]++ }
lastGuard!!.totalSleep += time - lastSleep!!
}
}
}

val sleepiest = guards.maxBy{ (_,v) -> v.totalSleep }!!
val commonMinute = sleepiest.value.timesAsleepOnMinute.indices.maxBy{ sleepiest.value.timesAsleepOnMinute[it] }!!
println(sleepiest.key * commonMinute)

guards
.maxBy { (_, v) -> v.timesAsleepOnMinute.max()!! }!!
.also{ (k, v) -> println(k * v.timesAsleepOnMinute.indices.maxBy{ v.timesAsleepOnMinute[it] }!!) }
}

#return difference in minutes
>tfw didn't read the whole thing and tried to take into account both hour and minutes to calculate the difference
def time_diff(before, after):
bh = int(before[0])
bm = int(before[1])
ah = int(after[0])
am = int(after[1])
if (ah < bh): ah += 24
diff = (ah*60 + am) - (bh*60 + bm)

return diff

Attached: 1543795560164.png (407x446, 27K)

FUCK ME this took way too long.

ghostbin.com/paste/km4q5

2 and a half hours. A hash map is the most logical option to store values when keys are integers and not in sequential order. However, values in Rust hashmaps are not mutable. You have to copy them out, and then insert them back in. On top of that, making things sortable requires implementing a number of traits. I wasted time attempting to impl PartialEq for EventKind (and learning that you can't match on the same enum value twice), only to realize there's this nice little derive macro that can make things not hellish.

Then I had an issue where I misread the first problem because for some reason I thought it wanted the starting minute of the time the guard who slept most, had the longest sleeping streak. Turns out the best guard fell asleep at minute 0 and woke up at minute 52 on one day. Then I realized my assumptions were wrong, and I had to keep track of the number of times he slept on a given minute, which became very difficult because now I'm cloning vectors.

But hey, my solution runs in 3 milliseconds, and I learned quite a bit more about Rust, so that's a positive.

Even my lame python code takes

hurr hurr the entire scoring is based on who's awake when !!
why not score on execution speed or something
stupid bullshit im not skewing my sleep schedule for this

Attached: fffuck you.png (615x118, 4K)

How the fuck? My hello world script in python takes 25ms to execute.

even if that was your master plan, you could have just used the datetime module.
I had Anaconda installed so I just used python-dateutil's parser function.
Works on pretty much every reasonable date format.

I DID IT Jow Forums, are you proud? review my code papi

import re
import datetime
import pprint
from collections import namedtuple, Counter, defaultdict

Line = namedtuple('Line', 'year month day hour min text')
pp = pprint.PrettyPrinter(indent=4)

with open('input4.txt') as f:
def time_key(n):
return datetime.datetime(*list(map(int,(n.year,n.month,n.day,n.hour,n.min))))

lines = f.readlines()
lines = [re.sub(r"[]\[\-\:]", ' ', line) for line in lines]
lines = [x.split() for x in lines]
lines = [Line(x[0],x[1],x[2],x[3],x[4]," ".join(x[5:])) for x in lines]

lines = sorted(lines, key=time_key)

guards_timeout = defaultdict(Counter)
current_guard = None
asleep = None
for line in lines:
if 'begins' in line.text:
current_guard = int(line.text.split()[1][1:])
elif 'wakes' in line.text:
guards_timeout[(current_guard)] += Counter({x:1 for x in range(asleep,int(line.min))})

elif 'falls' in line.text:
asleep = int(line.min)
else:
print("this shouldn't happen")

guards_timeout = sorted(guards_timeout.items(), key=lambda x: sum(x[1].values()), reverse=True)
id = guards_timeout[0][0]
minute = guards_timeout[0][1].most_common(1)[0][0]

print (id * minute)

guards_most_asleep = [(i,c.most_common(1)[0]) for i,c in guards_timeout]
sleepy = sorted(guards_most_asleep, key=lambda x: x[1][1])[::len(guards_most_asleep)-1]

print (sleepy[1][0] * sleepy[1][1][0])

SURELY a pythonfag coukldn't be this stupid

they're mutable if you use table.get_mut(k)

What are some essential modules for python? I mostly use C and some meme scripting language for Windows so raw data manipulation is all I know.

I'm glad somebody here actually knows how to write kotlin so I have something to compare my garbage to.

You can add Counters together?
Shit, good to know

if the scoring doesn't mean anything why are you so assblasted about it, chink?

Basic python is usually pretty good. But if you want a little extra edge, learn
from collections import defaultdict, Counter

cus i do wanna compete but i have work user

yikes! Little pao lu is gonna cry his eyes out on his dakimakura this evening

felt like you should be able to so i looked up reference. at first i was hoping i could add an iterable directly but I didn't see any example, only one with adding Counters together so I Counter() the iterable first.

numpy (matrices and shit), pytz (timezones)

I'm still undershooting.

Are guards always awake at the start of their shifts? Was I unreasonable to assume this?

they are

just look at the input file you brainlet

The data is already read in and it's in jupyter so the python interpreter is already running.

Who else /nim/ here? I'm getting 16ms runtime with this
import algorithm, re, sequtils, strutils, tables

proc solution(input: seq[seq[int]]): tuple[part_1, part_2: int] =
var records = initTable[int, CountTable[int]]()
var time = initTable[int, int]()
var sleep = true
var id, offset, max, hold = 0

for i in input:
if i.len == 5 and sleep:
offset = if i[3] == 0: i[4] else: 0
sleep = false
elif i.len == 5:
if not records.hasKey(id): records[id] = initCountTable[int]()
if not time.hasKey(id): time[id] = i[4] - offset
else: time[id] += i[4] - offset

for j in offset.. max:
max = v
id = k
hold = records[id].largest()[0] * id
offset = 0

for k, v in records.pairs():
if v.largest()[1] > offset:
offset = v.largest()[1]
max = v.largest()[0]
id = k

return (hold, max * id)

var input = map(split(strip(readFile("input.txt")), "\n"),
proc(x: string): seq[int] = map(findall(x, re"\d+"),
proc(x: string): int = parseInt(x)))

for i in countDown(4, 1):
sort(input) do (x, y: seq[int]) -> int: cmp(x[i], y[i])

echo solution(input)

My rust solution, it was painful.
paste.ofcode.org/6nVuYkeZta5Njz8FRvirGU

Welp. I'll have to keep that in mind in the future.

Still... FUCKING 174 LINES OF RUST GODDAMN.

import re

def day_4(lines: sorted):
guards = {}
minutes = [0]*60 + [0]
for s in lines:
match = re.search(r'Guard #(\d+) begins', s)
if match:
id = int(match.group(1))
if id not in guards:
guards[id] = minutes[:]
elif 'falls' in s:
m = int(s.split(' ')[1][3:5])
elif 'wakes' in s:
m2 = int(s.split(' ')[1][3:5])
guards[id][-1] += m2 - m
for i in range(m, m2):
guards[id][i] += 1

id = max(guards.keys(), key=lambda x: guards[x][-1])
part1 = id * max(range(60), key=lambda x: guards[id][x])

id = max(guards.keys(), key=lambda x: max(sorted(guards[x][:60])))
part2 = id * max(range(60), key=lambda x: guards[id][x])

return part1, part2
For some reason, I couldn't get nested lambdas to work in part 2, that is with both max() functions having lambda keys. So I resorted to sorting, which is inefficient but works just as well.

This looks like Python.

>couldn't get nested lambdas to work
as long as you're using different variables and properly keeping parentheses in check it should work
also doing that would have been cancer and I would slap you.

WHERE IS 8BIT SOLITION?

Attached: CPM_CLUB13.png (986x849, 55K)

Let it be known that day 4 is the day that we Rustfags scream in agony.

python with the speed of C
:D

>a language that claims to be a system language fails to produce concise parsing code
who would have guessed

Why doesn't this work then?
id = max(guards.keys(), key=lambda k: max(range(60), key=lambda x: guards[k][x]))

I get 28 ms including sorting with Python, so I doubt it. With a dataset this small, C will do it in

:^(

works on my machine
from collections import Counter
d = {'u': [1 , 2 ,3], 'v': [4, 5, 6]}
max(d.items(), key=lambda x: max(x[1], key=lambda y: y))

you're probably getting your `k` or `guards.keys()` wrong.

sorry for the noob haskell question...is there a better way to write this? like bimap or some crazy shit?
f :: (a, [a]) -> (a, [a]) -> (a, [a])
f (a, b) (c, d) = (a + c, b ++ d)

Admittedly, the parsing was not the hard part for me.
impl Event {
fn new(s: &str) -> Event {
// Timestamp format: [YYYY-MM-DD hh:mm]
let mo = s.get(6 .. 8).unwrap().parse::().unwrap();
let da = s.get(9 ..11).unwrap().parse::().unwrap();
let ho = s.get(12..14).unwrap().parse::().unwrap();
let mi = s.get(15..17).unwrap().parse::().unwrap();

// Event strings, to our credit, can be interpreted from exactly
// 5 characters. If a guard ID needs to be parsed, the number of
// digits in his ID will vary, but always start at position 26.
let event_type = s.get(19..24).unwrap();
let kind = match event_type {
"falls" => EventKind::FallAsleep,
"wakes" => EventKind::WakeUp,
"Guard" => EventKind::BeginShift(
get_guard_id(s.get(26..).unwrap())
),
_ => EventKind::BadEvent
};

Event { month: mo, date: da, hour: ho, minute: mi, kind: kind }
}
}

What the fuck. On some days, the guard never starts their shift, yet he falls asleep and wakes up several times. How am I supposed to know who's doing that if he never clocked in?

read the op image brainlet

Did you sort it?

I need to figure out how to parse better
load 'regex'

in =: /:~ cutLF fread 'input'
g =: '#' e.&> ]
NB. Remove competent guards
in =: in #~ -.@(*. |.!.0) g in

guards =: ".&> ('#(\d+)' ; 1)&rxall&> (#~ g) in

mins =: (g in) ([: );._1 in
interval =: 4 : '1 (60 | x + i. 60 | y - x) } 60 $ 0'
shifts =: +/&> _2 interval/\ each mins

timetable =: guards +//. shifts
guards =: ~. guards

i =: (i. >./) +/"1 timetable
p1 =: (i { guards) * (i. >./) i { timetable

i =: (i. >./) , timetable
p2 =: (guards {~ i

There's the biapplicative class, or you could wrap your first type in sum, which would provide a semigroup instance for tuple. Can't give example, am phone posting.

Alright guys what the fuck did i miss here? It posts an answer but not the right one. This is the main part. Posting the biggest var part next.
vector sortedVector;
map guardTimer;
map idAsleepAtMin;
int timeStart;
int timeEnd;
int timeAsleep;


sort(inputVector.begin(), inputVector.end());

for(int i = 0;i < inputVector.size();i++){
//cout

Sometimes the guard starts near the end of the previous day.

where's the bigboy input?

Yeah fuck I'm retarded. They're starting the previous day but looking for same month, day-1 doesn't work because when the month ticks over a new day starts. I need to calendar sort everything and I guess treat it as 'days since first day' or something.

int maxTime;
int laziestGuard;
int minMostSlept;
int minSleptTimes;
for(pair item:guardTimer){
cout

parsing wasn't hard at all, I didn't even use regex

fn parse_guard_id(input: String) -> i32 {
input
.split("#")
.nth(1)
.unwrap()
.split_whitespace()
.next()
.unwrap()
.parse::()
.unwrap()
}

fn parse_time(input: String) -> i32 {
input
.split_whitespace()
.nth(1)
.unwrap()
.split("]")
.nth(0)
.unwrap()
.split(":")
.nth(1)
.unwrap()
.parse::()
.unwrap()
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_guard_parse() {
let guard_string = "[1518-03-21 00:00] Guard #1759 begins shift".to_string();
let id = parse_guard_id(guard_string);

assert_eq!(id, 1759);
}

#[test]
fn test_minute_parse() {
let time_string = "[1518-11-13 00:25] falls asleep".to_string();
let time = parse_time(time_string);

assert_eq!(time, 25);
}
}

perfect, thanks!
f = biliftA2 (+) (++)

>I need to calendar sort everything
You can use any generic sort since lexicographic order is applicable.
Just sort data into new file via $ sort if on (li)unix.

Rewrote in haskell, it performs much better and was easier to write
I think I'll stick with this from now on
import HigherOrderFunctions
import Data.List (sort, isInfixOf)

main :: IO()
main = do
s [(Int, String)]
withGuards ls = withGuards' (-1) ls where
withGuards' :: Int -> [String] -> [(Int, String)]
withGuards' g [] = []
withGuards' g (x:xs) = if isInfixOf "Guard" x then withGuards' (extractGuard x) xs else (g,x) : withGuards' g xs
extractGuard :: String -> Int
extractGuard s = read $ drop 1 $ words s !! 3

sleepRanges :: [(Int, String)] -> [(Int, (Int, Int))]
sleepRanges [] = []
sleepRanges (x:y:xs) = (fst x, (extractMinute $ snd x, extractMinute $ snd y)) : sleepRanges xs where
extractMinute :: String -> Int
extractMinute s = read $ take 2 $ drop 3 $ words s !! 1

explodeMinutes :: [(Int, (Int, Int))] -> [(Int, Int)]
explodeMinutes xs = flatMap explode $ map (\(x,y) -> (x, [fst y .. snd y - 1])) xs

soln1 :: [String] -> Int
soln1 xs = bestMinute * mostSleepyGuard where
fullMinutes = explodeMinutes . sleepRanges . withGuards $ xs
sleepyGuards = reduceByKey (\x -> \y -> x + y) $ mapByKey (\x -> 1) fullMinutes
mostSleepyGuard = snd . head . reverse . sort . invert $ sleepyGuards
guardMinutes = map snd $ filter (\x -> fst x == mostSleepyGuard) fullMinutes
countMinutes = reduceByKey (\x -> \y -> x + y) $ keyMap (\x -> 1) guardMinutes
bestMinute = snd . head . reverse . sort . invert $ countMinutes

soln2 :: [String] -> Int
soln2 xs = fst bestGm * snd bestGm where
fullMinutes = explodeMinutes . sleepRanges . withGuards $ xs
gmCount = reduceByKey (\x -> \y -> x + y) $ keyMap (\x -> 1) fullMinutes
bestGm = snd . head . reverse . sort . invert $ gmCount

$ time ./soln
94040
39940

real 0m0.038s
user 0m0.031s
sys 0m0.007s

>(\x -> \y -> x + y)
(+)

Godammit. I blame the python syntax
lambda x, y: x + y

I 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)}")
}

>2 spots
If you were below 30 then one of spots is me :( had to leave for work before finishing.

Beautiful color theme.

Agreed.
Tasks are released hour before I have to run to work. So if I can't solve it in 50min I insta get >12 hours.

This.
What fucking giard ever starts shift before it starts? This task in unrealistic thus unsolvable.

BIG BOYE input here
a fucking millenium of guard shifts
post your times

mega.nz/#!Ro1BkKyS!asDqLa5PRI-JTJJnv6k9Ujt3fjxJ1gTG55vg9E2yHxg

42 seconds for my poo

I will refactor the guard part after watching X-Files, but this is what I used for the answer 5 hours ago

Attached: aoc4.png (1085x742, 183K)

2.5s in rust

Attached: ConEmu64_2018-12-04_21-04-44.png (650x105, 9K)

>not skipping work
>not telling your boss you'll do home office while you solve AoC
get rekt fag

an amazing 17 seconds