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:
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
Jonathan Thomas
Who here survived the wall?
Jayden Long
Remember that if you consider this a wall, there's going to be a rude awakening two days from now
Eli Brooks
How does the Jow Forums leaderboards rank people? why are people with 3 stars above people with 4 stars?
Easton Kelly
not considering this wall. What I am considering is not waking up earlier to attempt and solve these issues before going to work.
Isaiah Scott
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.
Lucas Butler
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
Aaron Fisher
>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
Jaxson Edwards
Wait until the multi threaded knot hashing emulator reverse engineering a bridge to the finale shows up
Same here. Started on evening of second day so I'm fucked
Juan Williams
If you stick with it, you'll probably still come out ahead. Not everybody is going to stay around the whole 25 days.
Wyatt Mitchell
who /lexicographic sort/ here
Aaron Walker
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.
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)}") }
Jordan Scott
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.
Cooper Long
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 ¯\_(ツ)_/¯
Xavier Hughes
Ye I expect that to happen, and I'm not worried anyways since I'm learning to write better code quicker
Nathaniel Watson
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
Ethan Sanchez
>!! >? How to turn code in Java with Kotlin syntax :(
Aiden Ortiz
Can't sentence. up too late last night. Meant: >How to code in Java with Kotlin syntax :(
Brandon Taylor
>>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....)
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.
Angel Parker
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.
Xavier Walker
I read that as >Today I was fired. Just take more naps, user. This is important.
Aaron Cook
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.
Bentley Robinson
language?
Caleb Hill
Looks like go, he's mutating something while evaluating the arguments.
Joshua Adams
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)))
I don't like it when my runtime tells me to panic.
Sebastian Myers
Code?
Easton Brooks
>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
>>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.
Joseph Miller
You missed the people trying to turn it into a RDB
Owen Peterson
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?
Asher Young
>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
Kayden Lee
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 most = argmax (maximum . times) ids print $ most * argmax (idTime most) [0..59]
Jaxon Wood
>while evaluating the arguments. What do you mean?
Oliver Diaz
I fucking wish I had stuck with haskell the few months leading up to this. I wish I could be cool too.
Xavier Jones
Why isn't this regex working for capturing the date? "\[(.+)\s.+\]"
I'm using Java if that helps.
Cooper Torres
the stuff that you are passing to println
Logan Reyes
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
Landon White
>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).
Nathan Reyes
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.
Jeremiah Ward
Java forces you to escape correctly anyway because it throws errors otherwise I suppose that's true.
Asher Jackson
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.
Leo Scott
Why are you writing JS? I thought you were an engineer/professional athlete?
Jose Peterson
Are you sure you're actually using a computer?
Xavier Clark
I am starting to doubt it.
Anthony Young
This is a test post. Please ignore.
Parker Brooks
Hi
Ayden Cook
ok noted
Henry Nguyen
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...
Lucas Reyes
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.
Nathaniel Torres
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)
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)))
Austin Morris
>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.
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.
Alexander Morales
>guard.keys() heh
Dylan Phillips
She might complain, but she'll probably see you as more desirable
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?
John Barnes
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.
Dylan Wilson
you could impress her (male) with you coding skills.
Asher Young
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.
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)
Caleb Cruz
Are you using an uninitialized struct or something else that requires initialization as a map or slice value?
Isaac Allen
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.
Brayden Jenkins
I converted the lines into a custom timestamp format and then implemented my own comparator, which I used to sort them.
Chase Nelson
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
Caleb Myers
post input
Ian Gomez
link to bigboi input?
Luke Sanchez
I had the same happen when where I "logged" when he was asleep forgot to set the loop starting point to the proper offset.
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
Ayden Edwards
what language are you using?
Ethan Diaz
>110MB oh shit
Cooper Bennett
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.
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.