#advent code
1 messages ยท Page 1 of 1 (latest)
How do maths on string sir. I don't want to convert to char then get ascii offsets to subtract because that isn't clean
advent day 2 part 2
document.body.innerText.split("\n").slice(0,-1)
.map(a=>["ABC".indexOf(a[0]), "XYZ".indexOf(a[2])])
.map(a=>a[1]*3+(((a[0]+a[1]-1)%3)+3)%3+1)
.reduce((a,b)=>a+b)
nice
@grave vortexwhere day 3
Lick my elf bag sack
||```js
// https://stackoverflow.com/a/55435856/8133370
function* chunks(arr, n) {
for (let i = 0; i < arr.length; i += n) {
yield arr.slice(i, i + n);
}
}
// https://stackoverflow.com/a/41708135/8133370
var strIntersect = (a,b) => a.match(new RegExp([${b}], "g")).join('')
var elfSacks = document.body.innerText.split("\n").slice(0,-1)
var elfSackTrios = [...chunks(elfSacks, 3)]
var elfSackBadges = elfSackTrios
.map(elfSackTrio=> strIntersect(strIntersect(elfSackTrio[0], elfSackTrio[1]), elfSackTrio[2])[0])
var priority = item => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.indexOf(item)+1
elfSackBadges.map(priority).reduce((a,b)=>a+b)
I couldn't make this one into a cursed oneliner because I relied on a stackoverflow function I don't understand how it works
@grave vortexwhere day 4
I havent done it
Day 4 Part 1
||```js
var pairs = document.body.innerText.split("\n").slice(0,-1)
.map(pair => pair.split(",") // split into the two ranges
.map(range=>range.split("-").map(Number))) // split ranges into their two numbers while parsing them
.filter(pair => {
// check if either pair contains the other entirely, tossing ones that dont
var rangeA = pair[0]
var rangeB = pair[1]
if (rangeB[0]>=rangeA[0] && rangeB[1]<=rangeA[1]) return true
if (rangeA[0]>=rangeB[0] && rangeA[1]<=rangeB[1]) return true
return false
})
console.log(pairs.length)
My dayz position in queue is 8 so I may have time for part 2
Day 4 Part 2
||```js
var pairs = document.body.innerText.split("\n").slice(0,-1)
.map(pair => pair.split(",") // split into the two ranges
.map(range=>range.split("-").map(Number))) // split ranges into their two numbers while parsing them
.filter(pair => {
// check if either pair contains the other entirely, tossing ones that dont
var rangeA = pair[0]
var rangeB = pair[1]
if (rangeB[0]>=rangeA[0] && rangeB[0]<=rangeA[1]) return true
if (rangeA[0]>=rangeB[0] && rangeA[0]<=rangeB[1]) return true
if (rangeB[1]>=rangeA[0] && rangeB[1]<=rangeA[1]) return true
if (rangeA[1]>=rangeB[0] && rangeA[1]<=rangeB[1]) return true
return false
})
console.log(pairs.length)
That was a super easy part 2, I am only 6 in queue, now what do I do to wait
@analog drum are you doing aoc daily at challenge start time
i forgot this is real
it comes out at 20:00 every night for me so it's pretty easy for me to do it somewhat close to start time
tonight I was a bit late though as I was at a family member's house
I'm not super going for speed but at the same time it's nice to see how fast I can do things xP
okie
i wasted so much time on parsing today
it took me 8 minutes just to parse the stacks
i honestly didn't realise just hardcoding the input in source was an option, would've been off much better if i just did that
It took me a minute to figure out how I should parse things but I think I figured out an okay way
of course once I finished I thought of a way that would be a lot more efficient though
haven't implemented it yet but will probably later tonight
what language are you writing in?
i did it in ts
so far I've done ts and nim, whichever I think would work better for the puzzle
the complicated parsing for today looks like it really killed off a lot of participants
it'll be interesting to see how many people come back
parsing today was 10x easier than yesterday's part two
yesterday I spent like 30 minutes working on parsing where today I spent like 3
the parsing for the parts was the same for yesterday? do you mean the logic for yesterday?
by "today" I mean day 4
it's very very late for me, I wont be doing day 5 till I wake up
yesterday's parsing required grouping an array into chunks
today's parsing is just a bunch of .splits with one number parse
you can group with a .map and a .filter pretty easily
how so?
.map((_, i, t) => !(i % n) && t.slice(i, i + 3)).filter(Boolean)
I am aware of .map giving an index for the second arg, what is t?
t is the array you're calling .map on
oh my god that is so useful
yea for oneliners
if you're calling it on something that's already in a variable you can just a.map((_, i) => !(i % n) && a.slice(i, i + 3)).filter(Boolean)
god its almost 1 am and I am going to rewrite my day 3 now
Oh my god thank you so much
||```js
// https://stackoverflow.com/a/41708135/8133370
var strIntersect = (a,b) => a.match(new RegExp([${b}], "g")).join('')
var elfSacks = document.body.innerText.split("\n").slice(0,-1)
var elfSackTrios = elfSacks.map((_, i, t) => !(i % 3) && t.slice(i, i + 3)).filter(Boolean)
var elfSackBadges = elfSackTrios
.map(elfSackTrio=> strIntersect(strIntersect(elfSackTrio[0], elfSackTrio[1]), elfSackTrio[2])[0])
var priority = item => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.indexOf(item)+1
elfSackBadges.map(priority).reduce((a,b)=>a+b)
no more accursed function* that I dont understand at all
that feels like a super cursed regex still
why not just a.includes(b)
oh I see now, that wouldn't work for your immediate case but I think it'd make more sense if you had originally used includes instead of the regex
but it works
this was my attempt at onelining part 2
part 2
input.split('\n')
.map((_, i, t) => !(i % n) && t.slice(i, i + 3))
.filter(Boolean)
.map(g => [ ...g[0] ].find(c => g[1].includes(c) && g[2].includes(c)).charCodeAt())
.reduce((a, b) => a + b - (b > 96 ? 96 : 38), 0)
but i did that after initially using lodash _.chunk and being challenged not to use it, you can make it a single map+reduce if you just check for falsy values in the reduce
i just didn't feel like bothering
I just did manual chunking
let queue = input
while (queue.length > 0) {
const [one, two, three] = queue
queue = queue.slice(3)
// whatever
}
though I was dumb and should have used splice instead of spread and slice
that's true
if getting the input into ruby was as easy as document.body.innerText in my browser, I would be using ruby in a heartbeat over js
is it not just File.read("filename")?
that splits on newlines I guess but just join the array back into a string if you need to
you underestimate my laziness if you think I can be bothered to save a file into a path accessable to my WSL
that too
very fun parsing
i thought of a really slick way to do it that I'm a tiny bit proud of
sleep good
my initial approach was to ||take the last number of the last line, make a new array of that length, and then fill the array by iterating the stack lines in reverse and getting the (i * 4) + 1th char||
only afterwards realised that ||the stack indexes are on the same columns as their crates so if you instead iterate the last line you don't need to do the math||
said math also took me way too long, wasted most of my time on it
Couldn't you start by ||using regex to filter out non \w|\d, then just use map to turn rows into cols? ||
My initial approach was ||allocate and generate a 2d char array with the length of the line / 4, then I chunked the line into groups of four and read the 1th char from - that ended up being silly, so now I just iterate with for (let i = 0; i < lines[0].length / 4; ++i) to get the letter of each box in a row - but your solution gives me an idea to combine the two but I'm not sure it'd be any more efficient than what I already have||
but slow
Array.reduce would probably work better than map for that too
what i had actually written
||```ts
const [ stacksRaw, movesRaw ] = inputRaw.split('\n\n');
const [ indexes, ...contents ] = stacksRaw.split('\n').reverse();
const stacks = Array.from({
length: +indexes.trim().split(/\s+/).at(-1),
}, (_, i) => {
const idx = (i * 4) + 1;
return contents.map(c => c[idx]).filter(c => c !== ' ');
});
you love how codeblocks can't be spoilered
My preferred language is javascript since when has speed ever been a consideration /s
huh, what platform
desktop
Same
wacky, it's never worked for me on any platform
you can see the other spoilers working and my cursor shows it as a spoiler (pointer cursor) and changes once I click on it
Maybe it's a Mac/ios thing that its broken on
on linux
I've never had it work on any client for several years, I've even had to make workarounds for previous advent of codes because of it (other people had the same issue at the time as well)
Are you using discord-arch-electron? I think I remember code spoilers not working when I used manjaro
just normal discord, no system electron
do you have spoilers disabled in appearance settings
no, you can see the other spoiler in the reply
wtf lol
and my theme is just changing discord's bg variables

Lmao

inb4 it's a patch I just hadn't reloaded and gotten in the last few days or something
do you mind posting it? the solution i came up with was very ugly and i wanna see how else it could be done
It's not a very compact way to do it but sure (my variable names suck)
||```ts
import { readFileSync } from 'fs'
const [stackString, moveString] = readFileSync('./inputs/05.txt').toString().split('\n\n')
const stackStringArray = stackString.split('\n')
stackStringArray.pop() // Get rid of the column labels
// Initialze the stacks of crates, one for each star
const stacksOne: string[][] = []
const stacksTwo: string[][] = []
for (let i = 0; i < stackStringArray[0].length / 4; ++i) {
stacksOne.push([])
stacksTwo.push([])
}
// Populate the initial crate configuration
for (const line of stackStringArray) {
for (let i = 1; i < line.length; i += 4) {
const box = line[i]
if (box === ' ') continue
stacksOne[Math.floor(i / 4)].unshift(box)
stacksTwo[Math.floor(i / 4)].unshift(box)
}
}
oo I just thought of a way to do it without splitting the input into lines
I need to finish my homework then maybe I'll do that and benchmark it to see how much faster it is
if I was doing this in a language that wasn't TS/JS I'd use a string instead of a string array but eh
aeth's solution is pretty fancy and elegant on its own though, I didn't know ||the Array constructor could do that||
||it's not the constructor, it's the static from method||
but yea
i've used that in like 3/5 days so far lol
also only realising this now, ||the split to get the last char is unnecessary because all of the indices are single digits, that could've just been +indexes.trim().at(-1)||
@grave vortex 5 & 6... NOW!
6??
is 6 not out?
no lol
I caught some kind of cold/virus and slept all day
Gonna go back to bed
I will do 5 and 6 together tomorrow
aeth is catching up to me 
i was slow today
the lack of sleep is slowly getting to me, these are at 6am for me
at least part 2 was easy
yeah, that makes sense
I didn't get to my PC until about 10 after the hour
once I go to visit my parents for the holidays I'll probably be a lot slower too, it'll be later at night
ah fair
Day 5, part 1,
Still sick, some of the worst code I have ever written
||```js
var input = document.body.innerText.split("\n")
var erduish = input.splice(0,9).map(a=>a.split(""));
// row to col
var stacks = ([...new Array(34)]).map((_,i)=>erduish.map(a=>a[i])).filter(a=>Number(a.slice(-1))).map(a=>a.slice(0,-1).filter(b=>b!==" ").reverse())
// move [0] from [1] to [2]
var commands = input.map(str=>str.match(/\d*/g).filter(a=>a!=="").map(Number)).filter(a=>a.length===3)
commands.forEach(command=>{
// do [0] times
([...new Array(command[0])]).forEach(_=>{
// take last from [1] and push onto [2]
stacks[command[2]-1].push(stacks[command[1]-1].pop())
})
})
// get top element from each stack
stacks.map(stack=>stack.slice(-1)[0]).join("")
Day 5 part 2
||```js
var input = document.body.innerText.split("\n")
var erduish = input.splice(0,9).map(a=>a.split(""));
// row to col
var stacks = ([...new Array(34)]).map((_,i)=>erduish.map(a=>a[i])).filter(a=>Number(a.slice(-1))).map(a=>a.slice(0,-1).filter(b=>b!==" ").reverse())
// move [0] from [1] to [2]
var commands = input.map(str=>str.match(/\d*/g).filter(a=>a!=="").map(Number)).filter(a=>a.length===3)
commands.forEach(command=>{
// take last [0] from [1] and push onto [2]
stacks[command[2]-1].push(...stacks[command[1]-1].splice(-1*command[0]))
})
// get top element from each stack
stacks.map(stack=>stack.slice(-1)[0]).join("")
day 6 part 1 and 2
|| To change from 1 to 2 just make marker_len = 14
// https://stackoverflow.com/a/53526999/8133370
var unique = (a,t={}) => a.split("").filter(e=>!(t[e]=e in t));
var input = document.body.innerText
var marker_len = 4
for (let i = 0; i < input.length; i++) {
if (unique(input.slice(i,i+marker_len)).length == marker_len) {
console.log(i+marker_len)
break;
}
}
```||
you will stop using var
idk why it does this, someone help?
||```julia
struct file
size::Int64
end
struct dir
subdirs::Dict{String, dir}
files::Dict{String, file}
parent::Union{dir, Nothing}
end
lines = split(read("input.txt", String), "\n")
baseDir = dir(Dict(), Dict(), nothing)
curDir = baseDir
for l in 2:length(lines)-1
line = lines[l]
if(startswith(line, "$"))
if(contains(line, "ls"))
continue
end
_, cmd, args = split(line, " ")
if(args == "..")
global curDir = curDir.parent
continue
end
@info curDir
global curDir = curDir.subdirs[args]
continue
end
if(startswith(line, "dir"))
_, name = split(line, " ")
curDir.subdirs[name] = dir(Dict(), Dict(), curDir)
continue
end
size, name = split(line, " ")
curDir.files[name] = file(parse(Int64, size))
end
@info baseDir
||
does it run correctly with the example input? I don't see anything immediately wrong it it but I'm not sure how far into your input you got before it missed something
it runs correctly until it tries to change into that dir
I mean, is that the first dir that it tries to change into
does it fail on the example input?
it's a lot easier to debug things when you're using the smaller example since the puzzle tells you what output to expect
true
the dir names aren't unique
idk julia and didn't read the error
but that's why the example worked for me and the actual input didn't
well yeah
yea that should be fine in my implementation though
also idk julia either
i cant run the example cuz theres some \r that i cant remove
what. it never goes into vlwl
I write in firefox, running my code frequently to debug it.
If I use anything other than var I end up redeclaring it after running it again, causing errro
that is absolutely horrid.
lmao
you cant afford to run vsc?
I cant be assed to download the input into a file then import it in a language
its one line..
eh
LMAO
firefox's editor has most of the vscode features I like, and I am too lazy to do anything otherwise
have you not noticed how my code takes its input from document.body.innerText?
i didnt bother to read it before
lmao
I am aware of how cursed my development method is
its very easy to just open devtools and start writing
This advent day is making me want to kill myself
yeah i hate tree like structures
haha yes i got it finally
day 7:
|| ```julia
struct dir
subdirs::Dict{String, dir}
files::Dict{String, Int64}
parent::Union{dir, Nothing}
end
lines = split(read("input.txt", String), "\n")
baseDir = dir(Dict(), Dict(), nothing)
curDir = baseDir
for l in 2:length(lines) - 1
line = lines[l]
if(startswith(line, "\$"))
if(startswith(line, "\$ ls"))
continue
end
_, cmd, args = split(line, " ")
if(args == "..")
global curDir = curDir.parent
continue
end
global curDir = curDir.subdirs[args]
continue
end
if(startswith(line, "dir"))
_, name = split(line, " ")
curDir.subdirs[name] = dir(Dict(), Dict(), curDir)
continue
end
size, name = split(line, " ")
curDir.files[name] = parse(Int64, size)
end
cache = Dict{String, Int64}()
sumDirsBelow = 0;
function computeSize(path::String, directory::dir)
if(haskey(cache, path))
return cache[path]
end
sum = 0;
for (name, size) in directory.files
sum += size
end
for (name, dir) in directory.subdirs
sum += computeSize(path * "/" * name, dir)
end
cache[path] = sum
if(sum <= 100000)
global sumDirsBelow += sum
end
return sum
end
totalUsed = computeSize("", baseDir)
@info "part one: " * string(totalUsed)
needToFree = totalUsed - 40000000
sorted = sort!(collect(values(cache)))
for i in eachindex(sorted)
if(sorted[i] > needToFree)
@info "part two: " * string(sorted[i])
break
end
end
I forgot that I should only be including directories with sizes over 100000, and just summed everything
||```js
var input = document.body.innerText
var folders = {}
input.split("cd ").slice(1).filter(dir=>dir.slice(0,2) !== "..").forEach(dir=>{
const split_folder = dir.split("\n")
const folder_name = split_folder[0]
const folder_contents = split_folder.slice(2, -1)
const sub_folders = folder_contents.filter(name=>name.slice(0,3) === "dir").map(name=>name.slice(4))
const files = folder_contents.filter(name=>name.slice(0,3) !== "dir").map(file=>Number(file.split(" ")[0]))
folders[folder_name] = {
sub_folders: sub_folders,
files: files
}
})
// gets the sum of all the numbers in an array
function sum(arr) { return arr.reduce((a,b)=>a+b, 0) }
// recursively sums the sizes of all the files in an array
function folder_size(name) {
const folder = folders[name]
return sum(folder.files) + sum(folder.sub_folders.map(folder_size))
}
// start recursive sum at root
folder_size("/")
god i need to fix this shiki bug
this is garbage because they duplicate folder names
ugh, today is one that will be annoying
my solution solves the star two example just fine and with the same exact results but then it doesn't get the right answer for my star two input
i had this too
today was hard actually
I finally got it by rewriting my logic 
tiny little printRope() function really pulling its weight for this one
this was pretty fun to do though
kinda want to animate it but also don't wan to put in too much more effort
i should've done that a lot sooner
this one was really hard to visualise
i also think the explanation was hella confusing
right off the bat the planck thing confused me so much
yeah, it was a bit confusing
it took me a bit to understand what the logic for moving diagonally should be but I did finally get it
I was over thinking it quite a bit
the explanation was so confusing but reading the images made it make sense forme
yeah i got stuck on this too
worked for the example, not for the real impl
my diagonal logic was already janky so i suspected it and just threw variations at it until it passed
aw cmon discord
lol why do spoilers have more precedence
remember how I said that spoilers and codeblocks are super broken 
i thought u meant the bug i fixed with shiki
i mean I never enabled the vencord version of shiki until earlier today
codeblocks with other formatting is just super janky in general
welovebeing able to dothis
it does but it's still funny
that's an interesting way to do it
how did you do it, i finished so much slower than everyone else i wonder if i grossly overcomplicated it
it did take me really long
just fixing stupid shit
I'll share mine in just a sec, cleaning it up just a bit (console.logs everywhere moment)
I used the Array.from thing that I saw you use a few days ago, super useful xP
ah shit mapping the direction to increments would've been a lot simpler
I also didn't bother keeping track of the entire grid
yeah lmao jeez that's exactly what i was afraid of, i did grossly overcomplicate it
I feel like your solution would be slower just because it has to allocate so much more memory (comparatively)
yeah it would be
you don't need to allocate a grid
the logic to grow it as well took me so long
oh well
a few years ago there was a puzzle that was 3d conway's game of life
I didn't want to deal with resizing a 3d grid in space so I just had a const world = Map<string, bool>() and to set tiles I'd world.set(${x},${y},${z}) xP
it wasn't very fast but it was faster than me trying to implement the growing algorithms xP
smart
my solution looks like this if i don't implement the unnecessary grid (and optimized the step logic based on yours too, but that didn't take me much time)
the core of it is completely unchanged lmao
aaaaaaaaaaaaaaaaaaaaaaaaaaa
i never actually used the grid
i only used it to track visits but that could've been done in any other ways
oh using an object for directions instead of a switch case is smart
I've done that in the past but completely forgot about it today
DIRECTIONS = {'U': -1J, 'D': 1J, 'L': -1, 'R': 1}
def sign(num: complex):
return complex((num.real > 0) - (num.real < 0), (num.imag > 0) - (num.imag < 0))
def get_new_tail_pos(head: complex, tail: complex):
diff = head - tail
if abs(diff) >= 2:
tail += complex(sign(diff.real), sign(diff.imag))
return tail
def move_snake(data, tail_size):
snake = [0] * (1 + tail_size)
tail_seen = set()
for line in data:
cmd, size = line.split()
for _ in range(int(size)):
snake[0] += DIRECTIONS[cmd]
for i, tail in enumerate(snake[1:], 1):
snake[i] = get_new_tail_pos(snake[i-1], tail)
tail_seen.add(snake[-1])
return len(tail_seen)
if __name__ == '__main__':
print(move_snake(input_str.split('\n'), 1))
what the hell

one of my professors wrote that
using imaginary numbers or something
๐ตโ๐ซ
goodness sake
yeah
that's
storing x in the real part and y in the imaginary part
definitely bigbrain time
my part 1 solution looks similars to this lol
import sys
Direction = {
"R": 1 + 0j,
"U": 1j,
"D": -1j,
"L": -1 + 0j,
}
visited = set()
head = 0j
tail = 0j
for line in sys.stdin:
if line == "\n":
break
dir = Direction[line[0]]
for _ in range(int(line[2:])):
head += dir
if abs(head - tail) >= 2:
if (head.real != tail.real and head.imag != tail.imag):
if (abs(head.real - tail.real) == 1):
tail = head.real + tail.imag * 1j
else:
tail = tail.real + head.imag * 1j
tail += dir
visited.add(tail)
print(len(visited))
imagine yourself some bitches
cope
is it normal to abuse complete numbers like that in python or are you just equally insane as aeth's professor
im just a math person and im used to complex numbers representing coords in 2d space
feels more like a usage than an abuse
i suppose so
as soon as i had the thought "how do i condense a coordinate into one value" i was like yo complex

i will not do part 2 too soon https://github.com/dzshn/aoc2022/blob/main/09/pt1.lpy
fucj
how delete
it's not really misleading?
it depends how you laid out your data structures and logic
today's was fun though, wish I could have been able to start on it earlier
||if you had a language like lua that indexes arrays starting at 1 this that layout wouldn't have even looked strange, and in others you should be used to the fact that 0th = first||
||julia uses 1 as array start
though i do think that the cycle thing leads you to believe to start with 1, cycle 1 is clearly the first requested pixel||
somehow it worked for task one
i dont even want to know how
like I said, it entirely depends on how you implemented or logic and/or data structures
for example, ||if you were off by one, just write the pixel before incrementing the cycle counter||

today was fun
i slept in and these are so much more enjoyable if you don't go for speed
it was so hard to understand though (part 2), i didn't understand what the problem description was asking at all
the example got me there but i didn't immediately understand what it was doing either
also the text output itself was so hard to read lol
wtf why did noone tell me this existed
yeah lmao it took me longer to understand the assignment than to actually code the solution
so confusing
yop
you love my solution
**DayTen.kt: **
package days
import inputs.dayTenInput
object DayTen: Day {
private val program = dayTenInput.lines()
private var x = 1
private val cycles = mutableListOf<Int>()
private val display = ".".repeat(240).toMutableList()
private var sprite = x-1..x+1
override fun solve() {
program.forEach {
val command = it.split(" ")
when(command[0]) {
"noop" -> cycle()
"addx" -> {
cycle()
cycle()
x += command[1].toInt()
}
}
}
val answer = cycles.sumOfIndexed { i, reg ->
if(((i + 1) - 20) % 40 == 0) reg * (i + 1)
else 0
}
println("Part 1: $answer")
println("Part 2:")
display.chunked(40).map {
it.joinToString("")
}.forEach(::println)
}
private fun cycle() {
val pos = cycles.lastIndex
if(sprite.contains(pos % 40)) {
display[pos] = '#'
}
cycles.add(x)
sprite = x-1..x+1
}
private fun <T> Iterable<T>.sumOfIndexed(selector: (Int, T) -> Int): Int {
var sum = 0
iterator().withIndex().forEach { (index, value) ->
sum += selector(index, value)
}
return sum
}
}
guh bad bot
i actually made my display a 2d array
i didn't make it any more complicated than it needed to be
**solution.cc: **Line 11
char crt[6][40];
i originally did 2d array but realized it was not necessary
display[pos] = '#'
bad bot
I'm upset I didn't see the +20 %40
but that's honestly not much cleaner than just hardcoding the numbers
so eh its fine
either way
i didn't know how many cycles there were when i first wrote it
didn't bother to check 
huh
i didn't originally check how many cycles had passed before totaling the power
i just assumed i got at least that part right
i actually didn't get it right at first
i love part 2, finally getting to scalability problems
damn
thats how i ended up with
of today?
LOL
this reminds me of the someone else already uses this password meme
weird coincidence
my main struggle was reading the task incorrectly
aka incrementing number before incrementing cycle
i just added to x register after the first cycle of addx
instead of after the second
oh we both had the same issue

im guessing bc theres different kinds of ints and strings?
me when rust .parse::<u64>()
std::stoi
std::stol
atoi
stol
stoi
std::stoll
stream >> i
sscanf(str, "%d", &i)
they're all different ๐
how are any of those int parsing functions
.toInt more readable imo
so unreadable
just more direct in what it does
string to long long
stoi = string to int
stol = string to long
stoll = string to long long
atoi = ascii to int
stream >> i reads from stream into i
sscanf is reverse printf
I was referring to the c ones
toInt makes sense
i thought it was ajoke
ah
At least for languages without 5 billion int types
the ones without namespaces are C and will return junk if it's invalid input and you need to use errno, the name space ones will throw exception, sscanf is a terrible idea because yes, stream one is probably okay

kotlin has int and long, both signed and unsigned
maybe bigint too?
idk
yeah it does
I like the type parameter style
although bigint is part of java stdlib
feels like deserialization 
day 7 was still one of my favorites
was day 7 the crane?
day 7 was the command line
$ cd /
$ ls
dir a
14848514 b.txt
8504156 c.dat
dir d
$ cd a
$ ls
dir e
29116 f
2557 g
62596 h.lst
$ cd e
$ ls
584 i
$ cd ..
$ cd ..
$ cd d
$ ls
4060174 j
8033020 d.log
5626152 d.ext
7214296 k
i had a solution but it didnt work for real input because duplicate folder names
that's why u're supposed to build a tree
I dont like data structures in JS and I refuse to switch to python/java/ruby because I am too lazy to import one file
it went pretty fine for me https://github.com/dzshn/aoc2022/blob/main/07/pt2.d
well u can always skip days!
and come back to them later, or not
I did 8 today because I realized that
I used or (||) so I cant post code in block because spoiler bug
day 7 was nice
monkeys 
mokeys
Day 9
by the way, in case you didn't know, you can use parentheses around an object in an arrow function to save yourself from needing the body + return statement
var chain = Array.from({length:9}, _ => { return { x: 0, y: 0 }});
->
var chain = Array.from({length:9}, _ => ({ x: 0, y: 0 }));
thanks
i dont know why but my brain so stupid i thought no () would just work but ofc it doesnt
this code reminds me how the length attribute is not read-only
> arr = [0, 1, 2]
[ 0, 1, 2 ]
> arr.length--
3
> arr
[ 0, 1 ]
> arr.length += 2
4
> arr
[ 0, 1, <2 empty items> ]
>
###..###..###...##..###...##...##..#####
#..#.#..#.#..#.#..#.#..#.#..#.#..#.#...#
#..#.###..#..#.#..#.#..#.#..#.#....###.#
###..#..#.###..####.###..####.#.##.#....
#.#..#..#.#....#..#.#.#..#..#.#..#.#...#
#..#.###..#....#..#.#..#.#..#..###.#....
How on earth does this say RBPARAGF
that is most certainly not an F at the end there
Day 10
||```js
var input = document.body.innerText.split("\n").slice(0,-1);
var cycle = 0;
var X = 1;
var screen = ""
function crtDraw(){
const pixel = cycle%40;
if (pixel>=X && pixel<=X+2) {
screen+="#"
} else {screen+="."}
}
input.forEach(instruction=>{
cycle += 1;
crtDraw()
if (instruction !== "noop") {
cycle += 1;
crtDraw()
X += Number(instruction.split(" ")[1]);
}
})
// Resize console until each line displays 40 characters
console.log(screen)
what the hell is up with RBPARAGF, i've seen three people with that specific answer
i thought the answers were unique per person
huh
roblox for girlfriend
holy shit real
hint
that sounds so cool i cant wait to do day 11
or is that day 10
that's 11
oh ok
im so excited i might do it rn
this might be the one i do in mathematica let me read it
oh day 11 was day 10 in my head
fyi it's more thinking than actually writing mathy logic
i read this last night
oho
this one im gonna do in dz's lispy
i gave up on part 2
part 2 is just knowing math and coming up with the solution then adding like 2 lines of code to make it work
small tip: || you need to find a way to reduce the number while not affecting the result of the "dividable by x" for each monkey ||
oh god is today Dijkstra problem
I might skip today cause I hate path finding algorithms
yeah
i will too
@pliant pebble did u do Dijkstra
yeh
I hope they don't do more tasks like that
no fun to just use an algorithm without having to use brain
i hope so too. i learned from it but it was not fun lol
i also didn't bother with a real pq impl which means my part 2 took 2 mins to run :^)
part 2 makes you find the shortest distance to the end node from any height-0 (a) node
pq?
priority queue
oh
i just iterate the entire list on each node
const lowestCostNode = () => {
let lowest: Position;
for (const [ position, cost ] of costs) {
if (!seen.has(position) && (!lowest || cost < costs.get(lowest))) {
lowest = position;
}
}
return lowest;
};
instead of using a pq like you typically do with dijkstras
guh idk whats wrong with mine
first is right but second is wrong
gives me wrong answer for sample
ugh ive spent literally all day on this
whh now the sample is right but my input is the same
can someone just look at my code and figure out what god awful mistake im doing because im tired of wasting my time on this
day 14 was cool
cool day 12 visual https://www.youtube.com/watch?v=QIhoGfhb6CY
aoc is getting too hard to the point that it's easier to make a visualization than to to the problems ;w;
soon
code of advent
coded
you know whats coming

fucking love how you IMMEDIATELY knew
what
no
small grammatical error (it was very grave)
โค๏ธ
I will do it in typescript this year
oh wow julia actually looks so fun i almost forgot
might use again 
vap asm
golfscript
APL
Uiua
Typescript
Rust
vap asm 
No
yes
oh yea swift
I made a proper git for my solutions and finally did 2022 #7
https://github.com/CodeF53/AdventOfCode/blob/main/src/2022/07.ts
Contribute to CodeF53/AdventOfCode development by creating an account on GitHub.
julia
zig
rust?
typescript whenever
elixir?
purescript?
go surely
haskell?
anything else worth trying?
rael
that was quick
beam will not be real because rust sucks
no,,,,,,,
ruby
I generally just like it's niceities and macros
it has the best map syntax there is imo
['a','b','c'].map(&:upcase)
vs
['a','b','c'].map(a=>a.toUpperCase())
It lets you directly access object functions/values through &: instead of having to define a function that takes an entry
and for advent of code, where you are so very often mapping arrays, its amazing
oh java has that too iirc
did you know
i wrote multiple days of aoc in js with just arrow functions and no variables
no thats me
look at the first message of this thread
I don't know how to do that quickly
/firstmessage is not a vencord thing
and?
does that mean i didnt
its a dumb thing where I just insist I'm the only person who did the thing jokingly.
I have no idea why im like this
idk where i put them :(
I ate
think they were on thr laptop arch install i wiped
Oofie!
i think i will start with sane languages
then suffer doing the insane ones as it gets harder
from a scale of ruby to erlang to golfscript to uiua
first (ish) message of the thread
i was gonna do the opposite
start with insane ones
laame
then when it starts getting impossible
do sane ones
cus it will still be hard
i just dont wanna do what i did last year and
have too hard a time
and then get backlogged and give up
25 pt2 in vap asm
NO
ill pay you
lina fix my beam encoder
Nuh uh
what am i yapping about
there is a file
but i'd have to make my cpu more than 8 bit
blehhh
too busy doing cursed matrix stuff
watch me
HOW
Do
Graph Al
something catastrophic about rust using result types: no backtraces
yeah bitch WHERE
@winter gust trace my calls pls
invite 1776680-321d3007
yea anyhow
but i didnt think of that lol
they exist across all the years
oo
but only show the data for the year ur lookin at
what does that do
are function exports just labels
yes
how do arguments work
registers
rrrftyuiop[']
thats why the arity is there
NO transp eople allowed
what lang are u guys doing first
uiua is cis lang
im prolly gonna just stick with swift all the way thru
i realized the "no" sign is
actually a diagonal line
cus transposing a matrix mirrors across the diagonal
uhh day 1 im gonna do
i mean first day and second is like whatever
my assembly thing
nop
and then uiua as well
day 3 at least
i wanna get that one out of the way
day 1 and 2 not real
i dont think imma actually do the assembly cus
it would require a lot of set up
for the input
**globals.ts: **Lines 1-9
import type { LoDashStatic } from 'lodash'
import lodash from 'lodash'
// make lodash global while covering TypeScript's loud sobs of "YOU CAN'T DO THAT"
// eslint-disable-next-line ts/no-unsafe-member-access
(globalThis as any)._ = lodash
// convince TypeScript not to scream when it sees lodash used in other files
declare global { const _: LoDashStatic }
super husk react this man
just make a
ambient types file
be sane and autoimport from lodash
f35 do you really need lodash
oh true that yes
I refuse to be sane
the military propoganda got to me
ambient types files can't globalThis._ = lodash
set it like normal as in?
as in globalThis._ = lodash rather than (globalThis as any)._ = lodash
it gets mad about that
yea because you dont have it declared as a member on your global interface
is this a webapp
is this how you would declare it as a member on the global interface
global.d.ts
import type { LoDashStatic } from 'lodash'
// convince typescript that having lodash be global isn't a sin
declare global {
const _: LoDashStatic
}
no
what is globalThis
why am i getting eof parsing the atu8
in this context
globalThis is what ts tells me to use because global is bad
globalThis is globalThis
my chunk lengths are wrong help
ohh
ok then what u did should work
but just use var instead of const
so u can actually assign it
var is evil and also doesn't fix the issue
I think I am happy with the cursed solution I had
typescript SUCKS
is rini doing old advent or do they somehow already have 2023 day 1
(to be fair this is your eslint config sucking but typescript still sucks)
yapping about my beam compiler
no shes trying to write a compiler for something
before day1
so that she can use it
i'll compile your beans
erl's beam_disasm has better errors than erlang itself
I have eslint and typescript set very strict because I have a problem
I would fix the global lodash thing, but I don't want to fuck with esbuild or something
I want global lodash
and I don't want to stop using the really stupid easy typescript runtime thing I use
sane
Adding my strict typescript and eslint config to my job's codebase to ensure no one can replace me due to how horrid it is to write in
you will go to jail for sabotage /j
apparently beam is mad im not adding function info sections
oh
i set max labels to 0 thinking it wouldnt care
i showed an advent of code problem to my little cousin
and explained its like christmas code puzzles
and she insisted on doing one by hand
shes doing this one by hand now on my actual puzzle input https://adventofcode.com/2022/day/1
oh god
@winter gust have they given up yet?
new aoc challenge: modify your own dna to solve the puzzle
it also modifies ur dna to make u wifi compatible
bioluminescence except its at wifi wavelength
thats kinda firee
called Result::unwrap() on an Err value: DecompressError { status: Failed, output: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] }
of course ishouldve used miniz_oxide::inflate::decompress_to_vec_with_limit instead of miniz_oxide::inflate::decompress_to_vec_zlib_with_limit
<t:1701406800:R>
@lyric saddle what should i do day 1 in first
im doing ruby first
do we have a private leaderboard set up
the venboard
I blame not getting first on new Date() having no easy way to specify a timezone for everything to be based off off
i spent 30 minutes putting together the cli
@winter gust did u complete
no
wait i can check
uiua is funny
how are yall approaching part 2
i was gonna write it in js terms but
||going thru each index of the string, if it starts with a number replace the number, then add the char at that index to a result||
||im surprised everyone is doing that im just matching both numbers and strings, indexing the value and then % 10||
||tbf i might be able to do that cus i think uiua has regex but||
||thats cheating (in uiua)||
rate part 1 ||```rb
p$<.map{(f,*,l)=_1.scan(/[0-9]/);(f+(l|โโ|f)).to_i}.sum
banger
zero width char to the rescue
beautiful
I am very happy with how well my AOC repo works and I want to share it
FUCK
||fiveightwo||?
||5igh2|| right?
no, that doesn't happen
here is my really simple fix for part 2
||```ts
const stringNums = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
export function partTwo(input: string): number {
// turn string nums into their numerical equivalents, surrounding numerical equivalent with self, as to not fuck up combos like "fiveightwo"
stringNums.forEach((num, i) => input = input.replaceAll(num, ${num.at(0)}${(i + 1)}${num.at(-1)}))
return partOne(input)
}
yeah FUCK thats so dumb
man idk what im doing wrong
have you checked your code against the example?
part one or two
two
can I see spoiler code and try and give a hint
yea one sec tho cus i'll have to rewrite it in js
fair, I can't read much else
somewhat . ?
its more like a data analysis language
linear algebra language
||```ts
function fix(str: string) {
let res = ""
for (let i = 0; i < str.length; i++) {
const match = nums.find(n => str.startsWith(n))
if (match) str = str.replace(match, nums.indexOf(match))
res[i] += str[0]
str = str.slice(1)
}
return res
}
i believe this is equivalent
yeah i got this multiple times
i know what the edge case is and how to fix it but simultaneously i'm lying down and cuddling my plushies and that's more important to me than funny points on the internet game
what does it give for fiveightwo?
solving the problem is piss easy
I need to come up with a better example one sec
it worked on eightwothree 
wait do you mean like
||fiveight should be 58?||
idk if it should
yes
oh fuck
my code should've done that from the start wtf
||and eightwo should be 82||
it was right in the example
this is so shit
yea but ||it doesnt say it should be 8 2 3||
exactly
I saw it, and was immediately like, ||I need to fix the overlaps||, I didn't even read the rest of the prompt of part two
the example definitely should've had at least one instance where not accounting for it would fuck you up
yea basically imo
||
numbers = {
"zero" => "0",
"one" => "1",
"two" => "2",
"three" => "3",
"four" => "4",
"five" => "5",
"six" => "6",
"seven" => "7",
"eight" => "8",
"nine" => "9"
}
puts File.read("input.txt").then{|s| numbers.each{|k, v| s.gsub!(k, "#{k}#{v}#{k}") }; s}.lines.map{|x|x.scan(/\d/).then{|y|y.first+y.last}.to_i}.sum```||
this one is fucking me the fuck up mannn
haven't tested this but i'm pretty sure it works
is it implementing this that is the problem?
yes
also variable declaration is for pussies!!!
did the instructions even mention zero?
i put it in there just in case
good idea
i could make this smaller by using actual variables but i don't like doing variable assignment because semicolons are the plague when it comes to one liners
feels like i'm cheating if i do that...
tbf .then is a variable equivalent anyways lmao
every single time i rush to beat someone i end up taking like 3 hours lol
this was right by the way
why not use new hash syntax?
numbers = {
zero: "0",
one: "1",
two: "2",
symbols are autocasted to strings, so it would be equivalant
used to using older versions of ruby so just muscle memory
or better yet just do ['zero', 'one', 'two'] and then do each_with_index
that's actually a really fun way of doing it yeah
thats effectively how I did it, but I didn't include 0, so I added 1 to every index
have you managed to get 5,8,2?
when you are scanning for string numbers, how do you do that
just to make this as unreadable as possible for non-ruby devs:
||rb ["zero","one","two","three","four","five","six","seven","eight","nine"].each_with_index.then{|numbers|puts File.read("input.txt").then{|s|numbers.each{|k, v|s.gsub!(k,"#{k}#{v}#{k}") };s}.lines.map{|x|x.scan(/\d/).then{_1.first+_1.last}.to_i}.sum}||
here's today's bigboy:
oh i know why the fuck its fucking fuck
you need to make sure you leave characters for the other numbers to form
truly the most performant solution by far
OMG I HAVE A GREAT IDEA
i know why my shit is still fucked
look at my answer now
oh i already looked at it
i was trying to avoid variable declaration as much as possible
$< so good
what should the expected output be?
please stop making ruby unreadable.
I write ruby daily at work and yet I can' barily understand whats going on
feto
according to my solution: ||55015199||
the inputs are personal
i try my best to not make it completely unreadable in cases other than this
everyones answer is different
i am aware, i spoilered it just in case anyone wanted to avoid having something to test against since the provided example doesn't show every edge case
you fucking crashed my node
can someone send me their full input and their answer I feel like my code doesn't cover some edge case that wasn't in my full input
||55701||
danke
55712
55413
@lyric saddle holy shit
so basically
the correct way to think about every problem
is with matrixes
vap is a scalar
swift makes these things unfun
u wish u were this data structure
i like some aspects of it but it definitely made the regex bit harder
@violet crow what times did you get on the big boy?
this was my bigboy times
i recommend using hyperfine for this
yeah okay apparently my part two didn't have any of the edge cases that people were having issues with
welp 
External timers are a no for me.
I run my solutions in a hot reloading environment and I have no easy way to run them outside of it.
IT'S DECEMBER
HIII
wild right
indeed
SHOULD I BRING LEADERBOARD BACK
yes
YES
YES
itsok
is vee at a disadvantage due to waking up after the problem releases?
fair, though hyperfine gives averages which accounts for warmup
leaderboardwise yea
midnight EST
that's 6am for me
i think Americans with a normal sleep schedule are more at disadvantage
yea defe
thats 10pm for me, so I am way past bed time
comes out at 20:00 for this american 
please use the normal horrible 12 hour time, I can't read that
how do i get hyperfine to not fuck up args
are u in li ke Alaske
by doing timing internally after reading the file (not using hyperfine)
horror timezone
10h behind
blud living like a day in the past it's so over for u
it would be 19:00/7PM but alaska merged timezones a while ago (for some reason) and chose the timezone further in the future
function ppAndTime(func: (input: string) => unknown) {
const start = performance.now()
const answer = func(input)
const end = performance.now()
const time = `${(end - start).toFixed(3)}ms`
console.log(`Day ${day} ${func.name}: ${answer as any}\t${time}`)
}
ppAndTime(partOne)
ppAndTime(partTwo)
beautiful timer
cba to figure that in swift
oh fire
my swift shit takes.. time
javascript is far faster than it has any right to be
with big input or normal
bigboy
did you just write it in a really inefficient way?
because there is no way my lazy ass solution is more than 5x faster
part 2 then part 1
I will not read your images, please use a code block like a grown adult
i couldnt spoil them
./s
aaa
unless u can spoil those
you can!

