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.
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)
Nicholas Carter
You should choke on a dick.
John Barnes
LITERALLY SEE THE OP IMAGE YOU DROOLING RETARD
Josiah Parker
look at the OP picture you nigger.
Zachary Brooks
>mixing camel case and snake case That's what I get for "porting" my C++ solution I guess.
Cooper Wright
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
public long Duplicate() { while (true) { foreach (var n in _input) { _curfreq += n; if (!_seen.Add(_curfreq)) { return _curfreq; } } } }
I made it work though :)
Michael Mitchell
>>caring about normie conventions ISHYGDDT.mp9
Brayden Lopez
>var names > 1 char
Jordan Edwards
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 ;;
Kevin Reyes
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
I can safely paste the whole thing into TempleOS now. However, + turns into / and - into }
Xavier Edwards
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
Sebastian Gutierrez
What's the cut line for a non-brainlet runtime?
Aaron Long
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.
Ryder Phillips
swift switch case is betterr
Alexander Carter
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.
Christian Howard
...
Ayden Diaz
no all generated inputs are tested to be working before the puzzle releases
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.
Hudson Perez
The input file repeats itself over and over until there's two repeating frequencies
Brandon Rogers
>converting to int for every repeat yikes
Cameron Reyes
(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-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)))))
Easton Morris
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 } } } }
Jaxson Hughes
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
And the hacked-together dict implementation some use is even uglier
Leo Baker
"""ugly""" lol
Jaxson Johnson
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.
Adrian Ortiz
use os.Stdin instead of fighting with the file.
Dominic Scott
What's your execution times bros? C# 10-17 ms including method calls and stopwatch instantiations
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
Justin Scott
sed? the problem is I can't even fucking get the list of numbers to get imported
Ethan Reyes
>it is worse for runtime but easier on memory which is kinda stupid since you're trading a
and then when you get all the stars the boobs will start jiggling
Jeremiah Clark
People comparing times here, you doing it for both parts, or just for part 2?
Bentley Lee
We have a warrior. I'm with you user.
Brayden Fisher
p2 since p1 runs in less than 1ms anyway
Juan Brooks
Part one time is almost negligible anyway
Brayden Reyes
>using loop >using double loop Disgusting
William Scott
thanks, using this as an opportunity to move away from python
Colton Moore
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
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"
Brayden King
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.
Lucas Jackson
>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
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
Jonathan Bennett
Nice
Andrew Lee
2 ms in C.
Landon Roberts
Please calm down.
Jason Barnes
Woah, look at this duuude
Adam Smith
(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.
Isaiah Morgan
Plebbit had an interesting writeup on reducing part 2 to a simpler problem.
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.
Jonathan Foster
Getting slightly better performance when using a BTreeSet instead of a HashSet in Rust
Anthony Morris
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){
I forgot about cyclical lists, and I wanted to use an array anyway.
Jace Murphy
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); } } }
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.
Christopher Gomez
>wHaT iF yOuR iNpUt Is OnE GoRiLLiOn you have to go back
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
There were challenges last year with input that caused exactly that kind of runtime when brute-forced, regardless of data structure.
Luke Thompson
gotta catch those exceptions user
Matthew Brown
I had the same intuition some hours ago.
James Carter
>needing a PhD in Frequency Analysis for a Xmas coding challenge yes patterns need to be exploited when the naive sol'n fails
Adam Flores
Is the the cycle length for part two supposed to be super long or am I brainlet who fucked up the simplest exercise?
Hudson Bennett
Use a hashmap.
Leo Wilson
there's no upper bound defined
Alexander Anderson
>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;