#development

1 messages · Page 297 of 1

neon leaf
#

@quartz kindle its alive!!

lyric mountain
#
def file = new File('values.txt')
file.text.split(',')*.split('-')
    .collect { it*.toInteger() as IntRange }
    .collect {
        [it, it.findAll { (it as String) =~ /^(.+)\1$/ }]
    }
    .each { range, vals -> println "For $range.from..$range.to: $vals" }
quartz kindle
#

feed it properly will ya

neon leaf
#

trust me i will once prices go down atleast a bit more

#

currently running yabs

quartz kindle
#

xD

neon leaf
#

I think btop is confused

quartz kindle
#

LOl

neon leaf
#

im also waiting for nvme prices to chill out again

#

500€ for 2x4TB before, now its like 620€

#

not as bad as ram but still

quartz kindle
#

meanwhile i still have an external 500gb hdd stored around here somewhere

#

xD

neon leaf
#

mmm

lyric mountain
#

oh wait, ur supposed to sum the invalid ids

#
def vals = new File('values.txt').text
def totalWrongIds = vals.split(',')*.split('-')
    .collect { it*.toBigInteger() as NumberRange }
    .flatten { it.findAll { it =~ /^(.+)\1$/ } }
    .sum()

println totalWrongIds
stark kestrel
#

crashes with my user input 🗿

#

and totalWrongIds prints the ids

lyric mountain
stark kestrel
#

some quite big numbers

#
Caught: java.lang.NumberFormatException: For input string: "9393862801"
java.lang.NumberFormatException: For input string: "9393862801"
queen needle
#

not supposed to share your inputs

lyric mountain
#

ah yes, integer issues

queen needle
#

11-22,95-115,998-1012,1188511880-1188511890,222220-222224, 1698522-1698528,446443-446449,38593856-38593862,565653-565659, 824824821-824824827,2121212118-2121212124

#

This is the example input

stark kestrel
#

the example input works

#

it just prints the ids themselves instead of summing them up

lyric mountain
#

huh, doesnt for me

queen needle
#

in groovy what is *.

lyric mountain
#

runs the following function on every entry

queen needle
#

so like js map?

#
for item in items:
    run(item)```
lyric mountain
#

yep

#

but it also returns the result

queen needle
#

Ah yeah so js map instead of like for each

lyric mountain
#

it's shorthand for map yeah

stark kestrel
#

thank god java is stable as always

#

can't run it anymore 🗿

lyric mountain
queen needle
#

Oh groovy is just a java subset?

lyric mountain
#

superset

queen needle
#

Or superset whatever it's called

lyric mountain
#

yea, any java code works on groovy

queen needle
#

that's cool

lyric mountain
#

the println wasnt even necessary tbh

lyric mountain
#

aight, did day 1 to just for completion

#
def input = new File('../inputs/day1.txt').readLines()

int zeros, dial = 50
(input =~ /([LR])(\d+)/).each { _, dir, num ->
    def val = num as int
    dial = ((dial + (dir == 'R' ? val : -val)) + 100) % 100

    if (dial == 0) zeros++
}

println zeros
queen needle
#

My exact solution lmaoo

#
import * as fs from "fs";

type Line = `${"L" | "R"}${number}`;

const inputFile = "input.txt";

const fileContent = fs.readFileSync(inputFile, "utf-8");
const lines = fileContent.trim().split("\n") as Line[];

let dial = 50;

let password = 0;

for (const line of lines) {
  const direction = line[0];
  const value = parseInt(line.slice(1));
  const sign = direction === "L" ? -1 : 1;
  dial = (dial + sign * value + 100) % 100;

  if (dial === 0) password++;
}

console.log(password);```
prime cliff
#

Gonna do permissions stuff differently with 4 categories 🙂

clever tundra
#

@neon leaf how much do you know about CF tunnels

pearl trail
#

ask the question, i might be able to help

wheat mesa
#

same

clever tundra
#

I've got it all configured but I keep getting an I/O error.
I'm pretty sure:

  • DNS not cause
  • ports not blocked
  • internet is good and stable

But when I visit the site I get error 1003 and my logs are all just I/o errors about port 7844

#

If you need any more specific info lmk, no guarantees how fast I'll be to reply thi

pearl trail
clever tundra
#

Wdym

#

It got an http smth or other when I curled it let me find it

patent bramble
#

Ice heard discord has been known to "lax API restrictions for larger bots". Does anyone here happen to know what all that entails? My main thought ATM is the 50 req/sec per bot. Don't want to have to worry about that being an issue (way down the road ofc), but gotta know so I can plan better.

pearl trail
# clever tundra Wdym

like, what are you trying to do here? tunneling local port to be accessible through domain?

quartz kindle
#

google gave me extra access to gemini 3 pro because i have the 2tb google drive plan, time to test their new antigravity code editor

lyric mountain
#

aight, day 3 done too

#
println input
    .collect { it.split('') as List<String> }
    *.with {
        def head = it.dropRight(1).max()
        return head + it.drop(it.indexOf(head) + 1).max() as int
    }
    .sum()
neon leaf
quartz kindle
lyric mountain
#

it's groovy yk :3

queen needle
#

How is it so small

lyric mountain
#

oh it's simple, u dont need to compare every number against eachother, simply get the largest number in the row (that's not the last index) then do it again but starting from the previous index + 1

queen needle
#

oh my god

#

im a little dumb

#
for (const line of lines) {
  let arrayOfNumbers = line.split("").map(Number);
  let currentLargestJoltage = 0;
  for (let i = 0; i < arrayOfNumbers.length; i++) {
    const number = arrayOfNumbers.at(i)!;
    const mutatedArray = arrayOfNumbers.slice(i + 1);
    for (let j = 0; j < mutatedArray.length; j++) {
      const compareNumber = mutatedArray.at(j)!;
      if (!compareNumber) continue;
      const finalNumber = number * 10 + compareNumber;
      if (finalNumber > currentLargestJoltage) {
        currentLargestJoltage = finalNumber;
      }
    }
  }
  joltageSum += currentLargestJoltage;
}```
lyric mountain
#

nah the important part is whether u got the correct answer

queen needle
#

How did you do day3 part 2?

lyric mountain
#

part 2?

#

there's only one problem per day no?

queen needle
#

When you solve the first one, and put in your answer, it opens up part 2

lyric mountain
#

oh I didn't see it

queen needle
#

nevermind i fixed it, for some reason i have to do line.trim()

lyric mountain
#

hm, for the second part I can use the same code I think

#

just need to add support for nth values

queen needle
#

i would love to see what you come up with

#

i struggled a lot

#

but eventually got there

#

although i am confused ```ts
import * as fs from "fs";

type Line = ${number};
const inputFile = "input.txt";

const fileContent = fs.readFileSync(inputFile, "utf-8");
const lines = fileContent.trim().split("\n") as Line[];

let joltageSum = 0;

for (const line of lines) {
let arrayOfNumbers = line.trim().split("").map(Number);
const largest = Math.max(...arrayOfNumbers.slice(0, -1));

joltageSum += (largest * 10 + Math.max(...arrayOfNumbers.slice(arrayOfNumbers.indexOf(largest) + 1)));
}
console.log(joltageSum);
``` returns 16927 if i remove .trim() it returns 16946 and there is no empty space in my input.txt so im confused as to how this happens

clever tundra
swift barn
pearl trail
clever tundra
clever tundra
pearl trail
#

that is zero trust yes, well not the vpn, but the tunnel one

clever tundra
#

mine is a bit different to yours

#

ahhhh i found it

#

aaaa nevermind it already existed

lyric mountain
# queen needle i would love to see what you come up with
int digits = 12
println input
    .collect { it.split('') as List<String> }
    *.with {
        def prio = it.toUnique().toSorted().reversed()
        def queue = it

        return (0..<digits)*.with {i ->
            for (p in prio) {
                int v = queue.dropRight(digits - i - 1).indexOf(p)
                if (v > -1) {
                    queue = queue.drop(v + 1)
                    return p
                }
            }

            throw "Reached end of input" as Throwable
        }.join() as long
    }
    .sum()
queen needle
#

INteresting

#

Better approach then I have

lyric mountain
#

basically u make a list of priorities, then scan the digits excluding n - 1 indexes from the tail

queen needle
#
for (const line of lines) {
  const arrayOfNumbers = line.trim().split("").map(Number)
  let currentLargestJoltage = 0;
  let maxId = -1;
  const poweredBatteries = 12;
  for (let i = 0; i < poweredBatteries; i++) {
    maxId++;
    if (maxId >= arrayOfNumbers.length) break;
    let max = arrayOfNumbers.at(maxId)!;
    let upperBound = arrayOfNumbers.length - (poweredBatteries - i - 1);
    for (let j = maxId + 1; j < upperBound; j++) {
      if (arrayOfNumbers.at(j)! > max) {
        max = arrayOfNumbers.at(j)!;
        maxId = j;
      }
    }
    currentLargestJoltage = currentLargestJoltage * 10 + max;
  }
  joltageSum += currentLargestJoltage;
}```
lyric mountain
#

and every time u find the value u shorten the head so u always start from the same place

clever tundra
queen needle
lyric mountain
#

probably, cant stop at 4 stars KEKW

queen needle
#

good

queen needle
#

Groovy is so small compared to java

lyric mountain
#

yea, I love that lang ngl

#

it's very sugary tho, like, nearly everything has a "groovy way"

queen needle
#

Fair enough

#

The python oneline solutions for today were interesting

lyric mountain
#

oh wait lmao, all puzzles had 2 parts

#

gotta do the other 2

queen needle
#

make a github repo with all your solutions

lyric mountain
#

I did

queen needle
#

Ohh i thought I was following you on github but i wasn't

pearl trail
# clever tundra yes

weird that it shows healthy on the dashboard,, do you use host-installed cloudflared or through docker?

quartz kindle
#

you guys doing advent of code? i always forget that it exists lol

#

catching up now, did day 2 and 3, didnt do day 1 yet

#

anyways thought id share mine too xD

day 3 part 1:

input.split("\n").reduce((a,t) => {
    const first = Math.max(...t.slice(0, -1));
    const second = Math.max(...t.slice(t.indexOf(first) + 1));
    return a + Number(`${first}${second}`);
}, 0);

day 3 part 2:

input.split("\n").reduce((a,t) => {
    const out = [Math.max(...t.slice(0, -11))];
    for(let i = 0, n = t.indexOf(out.at(-1)) + 1; i < 11; i++) {
        const s = t.slice(n, -(10-i) || undefined);
        const d = Math.max(...s);
        n = t.indexOf(d, n) + 1;
        out.push(d);
    }
    console.log(t, out)
    return a + Number(out.join(""));
}, 0);
clever tundra
#

twas degraded yesterday

#

when i try to run it i use:
cloudflared tunnel --protocol http2 run dashboard

#

if i remove --protocol http2 i get:
error="already connected to this server, trying another address"

#

if i go back to http2 i get:
2025-12-03T17:27:23Z ERR Unable to establish connection with Cloudflare edge error="DialContext error: dial tcp 198.censor:7844: i/o timeout" connIndex=0 event=0 ip=198.censor 2025-12-03T17:27:23Z ERR Serve tunnel error error="DialContext error: dial tcp 198.4censor:7844: i/o timeout" connIndex=0 event=0 ip=198.censor 2025-12-03T17:27:23Z INF Retrying connection in up to 2s connIndex=0 event=0 ip=198.censor

#

sometimes i get a mix of both errors

queen needle
quartz kindle
#

just whatever gets the job done and its not overcomplicated

#

my shit for day 2 was absolute garbage that took some solid 10 seconds to run

queen needle
#

LMAO

#

show it

#

i don't even understand your day 3 part 2

quartz kindle
#

day 2 part 2:

n = 0;
"4487-9581,755745207-755766099,954895848-955063124,4358832-4497315,15-47,1-12,9198808-9258771,657981-762275,6256098346-6256303872,142-282,13092529-13179528,96201296-96341879,19767340-19916378,2809036-2830862,335850-499986,172437-315144,764434-793133,910543-1082670,2142179-2279203,6649545-6713098,6464587849-6464677024,858399-904491,1328-4021,72798-159206,89777719-90005812,91891792-91938279,314-963,48-130,527903-594370,24240-60212".split(",").forEach(x => {
    const [start, end] = x.split("-").map(x => Number(x));
    for(let i = start; i < end + 1; i++) {
        const str = i.toString();
        const z = str.length;
        const divisors = [...Array(z + 1).keys()].slice(1).filter(i => z % i === 0);
        for(const div of divisors) {
            const match = str.match(new RegExp(`.{1,${div}}`, 'g'));
            if(match.length > 1 && new Set(match).size === 1) { n += i; break; }
        }
    }
});
console.log(n)
#

lmao

#

i just hardcoded the input

queen needle
#

interesting

#
import * as fs from "fs";

type Line = `${number}-${number}`;

const inputFile = "input.txt";

const fileContent = fs.readFileSync(inputFile, "utf-8");
const lines = fileContent.trim().split(",") as Line[];

let totalWrongIds = 0;
for (const line of lines) {
  const [lowerRange, upperRange] = line.split("-").map(Number) as [
    number,
    number
  ];
  for (let i = 0; i <= upperRange - lowerRange; i++) {
    const id = String(lowerRange + i);
    const doubled = id + id;
    const substring = doubled.slice(1, -1);
    if (substring.includes(id)) {
      totalWrongIds += parseInt(id);
      continue;
    }
  }
}

console.log(totalWrongIds);```
#

this was mine

quartz kindle
#

thats for part 1 or 2?

#

brb

pearl trail
clever tundra
#

i have no clue

#

either way regardless of what I do i always get error 1033

pearl trail
#

idk why the connector status is healthy, but you might want to redo installing the connector

clever tundra
#

well i tried again removing --protocol http and get a mix of i/o timeout, already connected, and about 2 registered connection

clever tundra
pearl trail
#

that works too, make sure that you use this one for simplicity

#

then you will never need to touch your server, you manage everything on the cf's dashboard

clever tundra
#

yeah im just deleting the old tunnel and starting fresh lmao

lyric mountain
#

damn day 1 part 2 had hands

#
int zeros, dial = 50
(input =~ /([LR])(\d+)/).each { _, dir, num ->
    int val = num as int
    if (val > 99) {
        zeros += val / 100 as int
        val %= 100
    }

    int rot = dial + val * (dir == 'R' ? 1 : -1)
    if (rot < 0) {
        rot += 100
        if (dial != 0) zeros++
    }

    dial = (rot + 100) % 100
    zeros += dial ? (rot.abs() / 100 as int) : 1
}

println zeros
queen needle
#

yeah i just did another loop instead of doing it the mathmatical way

queen needle
clever tundra
#

holy shit it just works

#

i just ran the service install, and it just worked

#

lmao

quartz kindle
lyric mountain
#

bro, day 2 part 2 was so silly lmao

#

all I had to do is add ONE character

#

regex is op

queen needle
lyric mountain
#

from /^(.+)\1$/ to /^(.+)\1+$/

queen needle
#

Yeah i wish I woud have done regex after seeing everyone elses solutions

quartz kindle
#

the only way that would happen is if somehow your file has spaces in it for some reason

#

i tested your code in mine and there was no difference with or without trims

lyric mountain
#

linebreak

#

ur splitting by \n, but \r exists too

queen needle
#

hmm

quartz kindle
#

ah yes, if your file has \n\r newlines because windows, then yeah

queen needle
#

what's odd is that for part 1 of today it works with or without change, but if I use my part 2 solution but target 2 digits instead of 12, it needs trim

quartz kindle
queen needle
#

You should make a most performant solution for each one

quartz kindle
#

lmao

queen needle
#

do it

#

listen to the voices

quartz kindle
#

they are telling me to run

queen needle
#

run as in run the most performant code

lyric mountain
queen needle
#

so should I split my input into lines my \r\n

lyric mountain
#

yes and no

#

your code would fail on linux if u did

quartz kindle
#

just hardcode the string

queen needle
#

well what's also weird is this \r\n issue only appears with certain solutions

lyric mountain
#

u can use readLines() to get file lines

quartz kindle
#

hardcode + browser console

#

:^)

lyric mountain
#

tim stop

#

seek help

quartz kindle
#

icba setting up a code editor for function prototyping lmao

lyric mountain
queen needle
#

I just don't understand how 1 needs the trim and one doesn't

#

both ouput the correct answer

lyric mountain
#

try console.loging the number arrays

#

also use the example so u dont get printed a huge array

quartz kindle
#

in the second one you dont actually traverse the entire line

#

you just filter and extract high numbers from it

#

so the zeroes that are appended from the \r doesnt affect anything

queen needle
#

but part 2 is the one that needs teh trim?

quartz kindle
#

oh i thought you meant part 1 needs the trim

queen needle
#

did you mean part 1

quartz kindle
queen needle
#

because printing the array in part 1, I see what you mean ts [ 9, 8, 7, 6, 5, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 0 ] [ 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 0 ] [ 2, 3, 4, 2, 3, 4, 2, 3, 4, 2, 3, 4, 2, 7, 8, 0 ] [ 8, 1, 8, 1, 8, 1, 9, 1, 1, 1, 1, 2, 1, 1, 1 ]

lyric mountain
#

for both parts u can use the same code, as in, your solution for part 2 must work for any n < length

queen needle
#

ahh i see now

#

is there anyway to do it without doing \r\n without having to have an anonymous async function?

lyric mountain
#

or u can split by regex

#

\n works for all cases in regex

queen needle
#

so just .split(/\n/g)

lyric mountain
#

yes

#

if that doesnt work try /\s+/g

#

or more aggressively, /\D+/g

queen needle
#

Well i want to try and find a global solution that works no matter the input

#

because i use the same boilerplate day to day

lyric mountain
#

\n should work with regex

queen needle
#

Wait but why does the .trim have to be on the line when i already trim the file contents

lyric mountain
#

cuz ur reading the whole file

quartz kindle
#

trim only affects the ends

#

ends as in both ends

#

xD

lyric mountain
#

nvm u said ends with an s

dire valve
#

guys where can i generate an api key

queen needle
#

you meant like this right, const lines = fileContent.trim().split(/\n/g) as Line[];?

lyric mountain
dire valve
lyric mountain
#

submit said bot

dire valve
#

ok ty

#

yo im sry to ask but where do i do that 😭

#

no option to create anything here

lyric mountain
lyric mountain
dire valve
#

ty

dire valve
#

is that allowed?

lyric mountain
#

no

dire valve
#

aw shit

#

now i gotta manually list relevant servers

#

well tnx for the help anyways

lyric mountain
#

well, even with access to the api you'd not be able to list the servers

#

since there's no endpoint for that afaik

dire valve
#

oh

#

ok

queen needle
#

using .split(regex) still gives the wrong answer

#

\s+ works

lyric mountain
#

odd

queen needle
#

thank you I never would have thought \r being the issue

lyric mountain
#

yw

patent bramble
#

Does anyone here know if "Embed Links" is needed for ephemeral responses? My guess is no since it's only a response and less "advertisement"

lyric mountain
#

embed links afaik is only necessary to send embeds

patent bramble
#

embeds wouldn't be links though

#

embeds are just messages with style

#

links direct users to sites

lyric mountain
#

no no, you see, even without that perm u can send links size they're text

#

when I say "embeds" I mean this block thing

patent bramble
#

or you mean the link preview embed yeah

lyric mountain
#

without that perm u can send the link, but the embed wont show

patent bramble
#

gotcha

#
#

that thing

lyric mountain
#

yes

#

it'll also prevent sending any embed at all

#

including the non-link ones

patent bramble
#

oop I best check that lmao

#

might be an issue

#

o shit u rite

#

I need to update that lmao

lyric mountain
#

it's confusing af the naming of that perm

patent bramble
#

should just be embeds tbh

lyric mountain
#

or SEND_EMBEDS

patent bramble
#

tru

#

I love how we're supposed to account for the new BYPASS_SLOWMODE but it's not even an option for installing apps

#

or are they exempt from slowmode?

#

Note: This primarily affects users, as bots are not affected by slowmode restrictions.
ok nvm

stark kestrel
#

Part 2 made me rewrite part 1 lmao

queen needle
#

Lmaooo

stark kestrel
#

I also got the max then the max after the first max for part 1

queen needle
#

I've seen that for most people, they wrote one, and then wrote two so it was dynamic

stark kestrel
#

Part 2 I was like angeryBOYE

#
fn get_max_joltage(battery: &Vec<usize>, n: usize) -> usize {
    let mut stack = Vec::with_capacity(n);
    let mut possible_removals = battery.len() - n;

    for &row in battery {
        while possible_removals > 0 && !stack.is_empty() && *stack.last().unwrap() < row {
            stack.pop();
            possible_removals -= 1;
        }
        stack.push(row);
    }
    stack.truncate(n);

    stack.iter().fold(0, |value, &elem| value * 10 + elem)
}

ended up with that

queen needle
#

Today makes me miss the global leaderboard

#

you would have seen the people who wrote part 1 dynamic vs those who didn't

stark kestrel
#

and i first read wrong, the word column triggered me

#

so i read the columns as being the battery

stark kestrel
#

n=2 for part 1

#

n=12 for 2

#
fn part_one(test: bool) -> usize {
    let columns = aoc_rs::input::read_file_grid_usize(aoc_rs::input::get_path(3, test));
    columns.iter().map(|col| get_max_joltage(col, 2)).sum()
}

fn part_two(test: bool) -> usize {
    let columns = aoc_rs::input::read_file_grid_usize(aoc_rs::input::get_path(3, test));
    columns.iter().map(|col| get_max_joltage(col, 12)).sum()
}
queen needle
#

usually I stay up until midnight to do them but last night I passed out early, and I feel like if I stayed up and saw part 2 I would have just gone to bed

stark kestrel
#

fair KEKW

#

I never really bother the time, i do them the evening after work

queen needle
#

well I used to them in my 1st hour during school but now I have college where only 2 in person classes in the week, both later in the afternoon

#

Last year I got to the leaderboard a couple of times so like I'll never top that

wheat mesa
queen needle
prime cliff
#

🙂 got permissions mapped out

queen needle
#

Awesome

shell tundra
prime cliff
#

Yup

shell tundra
#

🔥

warm surge
prime cliff
#

Oh hi you've been released from shawshank

warm surge
patent bramble
#

Does Discord have any built in insights for apps to track growth/engagement? 👀

pearl trail
#

i am not sure about that

patent bramble
#

Is there a list of the error codes returned by the API for 4XX errors? For instance 670006 is missing guild feature (specifically gradient, if it's that specific).

spark flint
patent bramble
spark flint
#

yeah its unoffficial

#

.food is for user API errors

#

but its. a big list of every known API error regardless of bot / user

patent bramble
#

nice

patent bramble
spark flint
#

just discord

patent bramble
#

ah lol gotcha

pearl trail
queen needle
#

Today's advent of code was hard lmao

lyric mountain
#

oooo I once coded smth similar to today's puzzle

queen needle
lyric mountain
#

aren't the inputs individually generated?

queen needle
lyric mountain
#

oh

#

aight I'll gitignore them

queen needle
queen needle
stark kestrel
#

repo is currently private either way but yeah

#

gonna see what day 4 looks like tonight

queen needle
#

Day 4 is fun

lyric mountain
#

aight, done

#

this one ended longer than usual

#
def input = getClass().getResource('/day4.txt').readLines()
boolean COUNT_ONLY = false

def mat = input.flatten { it.split('') as List<String> } as List<String>
int cols = input.first.length()
int rows = input.size()
int total = 0

boolean loop = true
while (loop) {
    loop = false

    for (i in mat.indices) {
        if (mat[i] == '@') {
            def (x, y) = [i % cols, i / cols as int]
            int count = (Math.max(0, y - 1)..Math.min(y + 1, rows - 1)).collect {
                int col = cols * it
                return mat.subList(
                        col + Math.max(0, x - 1),
                        col + Math.min(x + 2, rows)
                ).count { it == '@' }
            }.sum() as int

            if (count <= 4) {
                total++

                if (!COUNT_ONLY) {
                    mat[i] = '.'
                    loop = true
                }
            }
        }
    }
}

println total
queen needle
#

Do you not do any grid handling

#

Or like

#

Like this

quartz kindle
#

lol the second one was just a tiny change in the code

#

part 1:

n = 0;
cells = document.body.innerText.split("\n").map(x => x.split(""));
grid = [cells.length, Math.max(...cells.map(x => x.length))];
for(let y = 0; y < grid[0]; y++) {
    for(let x = 0; x < grid[1]; x++) {
        const current = cells[y][x];
        const adjacent = [cells[y-1]?.[x-1],cells[y-1]?.[x],cells[y-1]?.[x+1],cells[y]?.[x-1],cells[y]?.[x+1],cells[y+1]?.[x-1],cells[y+1]?.[x],cells[y+1]?.[x+1]];
        if(current === "@" && adjacent.filter(x => x === "@").length < 4) {
            n++;
        }
    }
}
console.log(n)

part 2:

n = 0;
cells = document.body.innerText.split("\n").map(x => x.split(""));
grid = [cells.length, Math.max(...cells.map(x => x.length))];
while(true) {
    const prev = n;
    for(let y = 0; y < grid[0]; y++) {
        for(let x = 0; x < grid[1]; x++) {
            const current = cells[y][x];
            const adjacent = [cells[y-1]?.[x-1],cells[y-1]?.[x],cells[y-1]?.[x+1],cells[y]?.[x-1],cells[y]?.[x+1],cells[y+1]?.[x-1],cells[y+1]?.[x],cells[y+1]?.[x+1]];
            if(current === "@" && adjacent.filter(x => x === "@").length < 4) {
                n++;
                cells[y][x] = ".";
            }
        }
    }
    if(n === prev) { break; }
}
console.log(n)
queen needle
#

I was stumped on the second one for sometime, and then I realized I just need to change my function to return a count, and put it all in a while loop

quartz kindle
#

things would be totally different if we went for performance, but since we dont care about performance, we just brute force xd

queen needle
#

you don't need to find the maximum

quartz kindle
queen needle
#

I saw some people talking about it, but didn't see anyone post there's that was

quartz kindle
#

you need to do what you can to keep it in a single loop, for example on each find only backtrack enough to check the cells that could be affected by the swap and then proceed from where you left off

#

there are also tricks to improve adjacent checking so you dont need to check all 8 cells

queen needle
#

how so?

#

Also I screwed myself over for so long, I used .at instead of [index] and that caused it to grab the very last row on the first one because .at handles negatives and it took me way too long to realize and fix it

quartz kindle
#

xD

#

the only reason to use .at() is to use negatives, otherwise [] is faster

queen needle
#

Pfft I didn't know that

#

I used .at because function syntax is nicer imo and I assumed it had some performance things under the hood

quartz kindle
#

general rule in js is new things are always more convenient but slower than old things

queen needle
#

that's not fun

quartz kindle
#

then with time they improve the new things so that they are only 1% slower instead of 200% slower

#

i dont think there is a single new thing in js that was introduced to make something faster

queen needle
quartz kindle
#

if out of 8 fields, the first 4 alreadt have a roll, you can skip the rest

#

if out of 8 fields, 5 are empty, you can skip the last 3

#

otherwise you can also try a minesweeper style of marking the number of adjacents on each cell so you dont need to check certain neighbours again

#

these are all more complex to do, but performance-wise they would be quite effective

queen needle
#

I saw lots of people using queues today

queen needle
#

I also originally dynamically made the adjacent cells array

quartz kindle
#

generally, advanced algorithms all look for doing as much as they can in a single pass and avoid multiple passes as much as possible, so it involves a lot of going back and forth with indexes and stuff, remembering positions/pointers, resuming where it left of, etc...

#

this goes back to the old ways of seeking HDDs, it would be much faster to work with nearby data than to go back to the beginning and scan the entire thing again

queen needle
#

I wish I found an efficient algorithm for today

#

I just check every character, check the 8 adjacent, and then move on to the next character

quartz kindle
#

yeah thats what i did too

#

its the fastest way to prototype a working function / solve the problem

lyric mountain
queen needle
#

well I mean it's the only way I could really think to do it, only micro optimization I know how to do would be to only check possible cells so don't check above if it isn't there

queen needle
#

I wish I could optimize my day 2

#

It takes like 1.5s

lyric mountain
#

I used the scan method

queen needle
#

Scan method?

lyric mountain
#

as in, do a pass -> if anything is removed -> repeat

#

so I do a full scan to remove any valid slots, and if anything is removed, I scan again to check if any can be removed now

#

the loop only ends when no slots are removed

#

this also lets me use the same func for both parts, since it wont loop again

#

btw done removing the inputs from git history

twilit knot
#

Chat what I'm supposed to do here? I just want my bot to have working cmds and a command button type thing on the profile, My bot have like 9 working slash cmds

lyric mountain
#

mine takes abt 1.25s and 37 full scans

#

ran the entire task 10 times beforehand to let jit do its thing

lyric mountain
quartz kindle
lyric mountain
#

wtf

quartz kindle
#

the string is hardcoded

#

already in memory

twilit knot
lyric mountain
quartz kindle
#

same

#

actually 47 passes, i did trhe z++ wrong

lyric mountain
#

but well, u also hardcoded the cell accesses, that's prolly faster than extracting views

quartz kindle
#

ye

#

could do without arrays tho, just using string indexes

#

let me test

lyric mountain
quartz kindle
#

nvm strings are not mutable

lyric mountain
#

just realized, I might be able to reduce the amount of scans by jumping to the first subview index, instead of index 0

queen needle
#

That's why I have this mess

#

I need to create a timing system for each of these

twilit knot
lyric mountain
#

slash commands show in your bot profile when they're used frequently

twilit knot
quartz kindle
#

@lyric mountain@queen needle
from ~85ms to ~15ms (can still be further improved)

function THEJOB(input) {
    let n = 0;
    const grid = input.split("\n").map(x => x.split(""));
    const size = [grid.length, grid[0].length];
    const marks = [];
    for(let y = 0; y < size[0]; y++) {
        for(let x = 0; x < size[1]; x++) {
            CHECK(y, x);
        }
    }
    while(marks.length) {
        const m = [...marks];
        marks.length = 0;
        for(const mark of m) {
            for(let i = 0; i < 9; i++) {
                const ny = mark[0] - 1 + Math.floor(i / 3);
                const nx = mark[1] - 1 + (i % 3);
                CHECK(ny, nx);
            }
        }
    }
    function CHECK(y, x) {
        const current = grid[y]?.[x];
        if(!current) { return; }
        const adjacent = [
            grid[y-1]?.[x-1], grid[y-1]?.[x], grid[y-1]?.[x+1],
            grid[y]?.[x-1], grid[y]?.[x+1],
            grid[y+1]?.[x-1], grid[y+1]?.[x], grid[y+1]?.[x+1]
        ];
        const l = adjacent.filter(x => x === "@").length;
        if(current === "@" && l < 4) {
            n++;
            grid[y][x] = ".";
            marks.push([y,x]);
        }
    }
    return n;
}
#

one full scan, remember all the changes, then followup scans only check adjacents of changed cells

queen needle
#

Bruh wtf

#

What further improvements could be done

lyric mountain
#

now it's 1.12s

#

oh wait, I forgot to skip the full scan

#

nvm, didn't matter

prime trellis
#

why everyone still using old components for embeds?

quartz kindle
#

@queen needle@lyric mountain down to 4ms

#
function THEJOB(input) {
    let n = 0;
    const grid = input.split("\n").map(x => x.split(""));
    const size = [grid.length, grid[0].length];
    let marks = [];
    for(let y = 0; y < size[0]; y++) {
        for(let x = 0; x < size[1]; x++) {
            CHECK(y, x);
        }
    }
    while(marks.length) {
        const length = marks.length;
        for(let m = 0; m < length; m++) {
            const mark = marks[m];
            const y = mark >> 8;
            const x = mark & 255;
            CHECK(y-1, x-1);
            CHECK(y-1, x);
            CHECK(y-1, x+1);
            CHECK(y, x-1);
            CHECK(y, x+1);
            CHECK(y+1, x-1);
            CHECK(y+1, x);
            CHECK(y+1, x+1);
        }
        marks = marks.slice(length);
    }
    function CHECK(y, x) {
        const gy = grid[y];
        if(gy) {
            const gx = gy[x];
            if(gx === "@") {
                let brazil = 0;
                const gyminus = grid[y-1];
                const gyplus = grid[y+1];
                if(gy[x-1] === "@") {brazil++}
                if(gy[x+1] === "@") {brazil++}
                if(gyminus) {
                    if(gyminus[x-1] === "@") {brazil++}
                    if(gyminus[x] === "@") {brazil++}
                    if(gyminus[x+1] === "@") {brazil++}
                }
                if(gyplus) {
                    if(gyplus[x-1] === "@") {brazil++}
                    if(gyplus[x] === "@") {brazil++}
                    if(gyplus[x+1] === "@") {brazil++}
                }
                if(brazil < 4) {
                    n++;
                    gy[x] = ".";
                    marks.push((y << 8) + x);
                }
            }
        }
    }
    return n;
}
queen needle
#

I genuinely do not understand my code or the algorithm you two describe enough to speed my solution up

lyric mountain
#

ah cmon

queen needle
#

Bro literally wtf

quartz kindle
#

caching variables as much as possible, avoiding short loops, avoiding dead/unneeded code, avoiding unnecessary array allocations

queen needle
#

brazil++ is peak

lyric mountain
#

next time u iterate, run over these instead

quartz kindle
#

bonus, store y x coordinates as bitfield xD

quartz kindle
lyric mountain
#

dont see u doing that

queen needle
#

Okay I'm just stupid ig

#

I thought that's what that was lmao

prime trellis
#

check dm @quartz kindle

#

@quartz kindle:
VM67:170 Result: 9446 @ removed
VM67:171 Time: 4.10 ms
VM67:172 Speed: 9756.1 cells/ms
VM67:175
v2:
VM67:180 Result: 9446 @ removed
VM67:181 Time: 3.00 ms
VM67:182 Speed: 13333.3 cells/ms

quartz kindle
#

show code?

prime trellis
#

let me speed up this

#

1sec

queen needle
#

Damn improving tims code?

#

Got me curious

quartz kindle
#

asking AI to do it?

#

lmao

queen needle
#

AI can't compare to Tim

prime trellis
queen needle
prime trellis
#

on ai

quartz kindle
#

im asking chatgpt to improve mine and see how it does

prime trellis
#

im using deepseek

quartz kindle
#

so far it produced 1 wrong code, and 1 slower code

prime trellis
#

30ms faster than u now

quartz kindle
#

lmao

prime trellis
#

let me see opus

quartz kindle
#

show then

queen needle
#

I Wanna see

prime trellis
#

i think opus can do better

queen needle
#

I don't see many improvements left in his code of any at all

neon leaf
#

rewrite it in rust ofc

quartz kindle
#

xD

queen needle
#

oh true true

prime trellis
#

XD

queen needle
#

rust in the browser console

quartz kindle
#

so far every solution chatgpt gave me was slower or equivalent to mine

#

but tbh this is too small of a job to get meaningful results

#

you would need a much larger input to get a better assessment

queen needle
#

make your own input

quartz kindle
#

well you can simply multiply the input

#

xD

queen needle
#

input * (input.length ** input.length)

quartz kindle
#

input.repeat(100)

quartz kindle
#

you wanna end the universe or what

queen needle
#

Yes

#

For day 3 the 12 batteries my friend just did 12 for loops

quartz kindle
#

xD

queen needle
#

time complexity from hell

quartz kindle
#

chances are 12 for loops are faster than 90% of other methods out there

prime trellis
#

ultra = opus

queen needle
#

I mean, he never got an answer

#

Not his code but basically this

quartz kindle
#

because AI doesnt actually run the code

#

it just gives you random benchmark results

queen needle
#

And is it giving the right answer still

quartz kindle
prime trellis
#

he skip u

quartz kindle
#

lmao

prime trellis
queen needle
prime trellis
#

with test everything i just copy that

queen needle
#

I wanna look but I'm on mobt

#

Mobile

prime trellis
quartz kindle
#

nice

prime trellis
#

opus make slower than u

queen needle
#

Don't generate a grid, use the grid from aoc

queen needle
prime trellis
#

just go into deepseek and test it too

#

sometimes is good

queen needle
#
..@@.@@@@.
@@@.@.@.@@
@@@@@.@.@@
@.@@@@..@.
@@.@@@@.@@
.@@@@@@@.@
.@.@.@.@@@
@.@@@.@@@@
.@@@@@@@@.
@.@.@@@.@.```
#

Test the fastest solution with this input

quartz kindle
#

a lot of the changes are not actually meaningful, what actually matters is that it flattened the 2d array into a single continuous block and then used multiplication to simulate rows and colummns

prime trellis
quartz kindle
#

for example instead of
abc
xyz
123

it stored as
abcxyz123

and then it gets rows and columns like this
cell = block[rowindex * rowsize + colindex]

queen needle
neon leaf
#

thats the same value

prime trellis
#

yeah

queen needle
#

what is the result from deep seek

#

Not the time

prime trellis
#

?????

queen needle
#

The result

#

what answer does it's code give

prime trellis
#

bro

#

u have pc?

#

go into deepseek and test that ok

queen needle
#

No I'm on mobile

#

in class

#

I just want to know if it gets the right answer 😭

prime trellis
prime trellis
#
VM40:198 
:mag: TESTING ORIGINAL VERSION...
VM40:203   Result: 43 @ removed
VM40:204   Time: 0.10 ms
VM40:205   Speed: 1000.0 cells/ms
VM40:208 
:zap: TESTING ULTRA FAST VERSION...
VM40:213   Result: 43 @ removed
VM40:214   Time: 0.100 ms
VM40:215   Speed: 1000.0 cells/ms
VM40:218 
:bar_chart: PERFORMANCE COMPARISON:
VM40:219   Results match: :white_check_mark: YES
VM40:220   Speedup: 1.0x faster
VM40:221   Time saved: 0.00 ms
VM40:224 
:chart_with_upwards_trend: GRID ANALYSIS:
VM40:233   Size: 10×10 = 100 cells
VM40:234   @ symbols: 71 (71%)
VM40:235   . symbols: 29 (29%)
VM40:238 
:dart: GRID AFTER FIRST REMOVAL WAVE:
VM40:273 
After first removal wave (only @ with <4 neighbors):
VM40:274 .......@..
.@@.@.@.@@
@@@@@...@@
@.@@@@..@.
.@.@@@@.@.
.@@@@@@@.@
.@.@.@.@@@
..@@@.@@@@
.@@@@@@@@.
....@@@...
VM40:277 
:abacus: SUMMARY:
VM40:279   Initial @ count: 71
VM40:280   Total removed @: 43
VM40:281   Remaining @: 28
VM40:282   @ after first wave: 58
VM40:283   Additional removed in propagation: 30
VM40:285 
==================================================
VM40:286 :checkered_flag: TEST COMPLETE```
#

Speed: 1000.0 cells/ms

queen needle
#

Okay so it still gets the correct answer

#

That's what I was curious about

prime cliff
prime trellis
#

any feedback?

prime cliff
#

Do you really need to add "secure oauth 2.0" xD like what does 2.0 mean?

quartz kindle
#

yeah it often halucinates about what improves performance and what doesnt. for example it will say "this change massively improves performance" and it actually makes it worse.
AI is good at finding good algorithms, but not as good at microoptimizing

neon leaf
#

cuz the standard is oauth2 ig

prime cliff
#

Regular users don't need to know about what oauth2 is though

queen needle
#

Why have a pill button in a slightly rounded container, and why does the button have a slight border but transparent background? It makes the button look odd

prime trellis
#

i making few login page

#

and pushing it into community

queen needle
#

Are you making it or is AI 🤔🤔🤔

prime trellis
#

front opus

#

pancake and tim why u are mad on ai?

#

tell me

#

u dont like it?

#

helps alot btw

#

changed @prime cliff all happy rn

prime cliff
#

I would just get rid of the text tbh

queen needle
#

^

prime trellis
#

yea?

queen needle
#

The standard for login seperator components is to provide Oauth methods after you already have a login/sign up screen

prime trellis
#

or with -- | --

queen needle
#

If it's just one login method you do not really need a seperator

prime cliff
#

Only you and other developers will know what "oauth" is and at that point they already know what oauth is unless you're building a developer oriented app

queen needle
#

and why separate the button and the text about the button?

prime cliff
#

The seperator and text is better imo design wise

prime trellis
#

without

#

mhm

queen needle
# prime cliff The seperator and text is better imo design wise

That's fair, I mean it kind of works in this scenario but also the button being so large but providing so little, being a pill with a transparent background, and the text being so far away, it all just creates empty space and some noise when it isn't needed

prime trellis
#

okay @queen needle

#

u wanna give me feedback about 1 more thing?

queen needle
#

I mean I can but my feedback is very biased @prime cliff is a very good developer who would be more help

prime cliff
#

I'm not that good ;-;

queen needle
#

Better than me at least

prime trellis
prime trellis
prime trellis
queen needle
#

I'll have to wait until after class the video is too small on mobile

prime trellis
#

wait let me upload somewhere

#

oh i cant send it

prime cliff
prime trellis
queen needle
prime trellis
#

everything is compatible with mobile version...

prime trellis
queen needle
prime trellis
#

omg i love this loading

prime trellis
#

soo good

queen needle
#

I don't think you're supposed to say stuff like that in here (idk the rules) but you can always dm me

lyric mountain
#

aight @queen needle @quartz kindle I'm back

#

managed to reduce it to 5ms :v

#

but the code got big af cuz I went raw java

queen needle
#

Bro went raw

lyric mountain
#

lemme create a gist

#

hm, how do u?

queen needle
#

so what I'm hearing is when I get home I'm going to have to add timing to mine and do a bunch of optimization s

lyric mountain
#

anyway imma just send it to git

queen needle
lyric mountain
#

for part 1

#

for part 2

queen needle
#

Literally what the fuck

#

I still don't understand how

#

I have some ideas to improve part 1

#

But that's it

lyric mountain
#

it applied as much optimization as I knew on it

#

oh actually

#

the time in the prints might actually be wrong

#

cuz I'm reading the file inside the task

queen needle
#

I literally know like one thing I can optimize on mine that's it

#

I'm going to include file reading into the time for mine

lyric mountain
#

yeah lmao

#

removing the file access from the task shaved 2ms off it

queen needle
#

The only optimization I know I can do is handle the checks normally and don't use an array and loop through it

lyric mountain
#

things u can do to shave processing time off it

  • use the lowest array type you have (faster creation)
  • save changed indexes to a secondary array, iterate over it from the second pass onwards
  • use bitwise whenever possible
#

also try to stay low on array accesses

#

if u need to use the access index more than once make a var for it

queen needle
#

I'll work on implementing those when I get home

stark kestrel
#

today's part 2 is what i feared

#

part one was fun as always

fn part_one(test: bool) -> usize {
    let adj = aoc_rs::parsing::get_adjacent_8_grid_char(aoc_rs::input::read_file_grid_char(
        aoc_rs::input::get_path(4, test),
    ));

    adj.get(&'@')
        .unwrap_or(&Vec::new())
        .iter()
        .filter(|neighbors| neighbors.iter().filter(|v| **v == Some('@')).count() < 4)
        .count()
}
#

gonna work on part 2

queen needle
#

part one i got 5ms

stark kestrel
#

time for the code cleanup of part 2

queen needle
#

okay got 2ms

lyric mountain
#

ayo nice

#

I think this is the absolute bottom lul, cant see how I'd go any lower

queen needle
#

2ms for part 1

lyric mountain
#

maybe if I used in-memory changes or partitioned the input

queen needle
#

part2 im stuck at 16ms

lyric mountain
#

oh

queen needle
#

can't break 16ms 🙁

lyric mountain
#

link still the same right?

queen needle
#

that's about 30ms-20ms

stark kestrel
#

both parts

queen needle
#

bruh

stark kestrel
#

rust my beloved

lyric mountain
stark kestrel
#

it is

lyric mountain
lyric mountain
#

unless ur doing it just for the answer

stark kestrel
#

i just do it for the answer honestly

#

but it's quite fast so yeah

#

and if i do it a second time it gets quite stable to 5ms likely because of some optimizations of the OS

lyric mountain
#

best I could get was 2ms (for part 2)

queen needle
#

i couldn't pass 11ms

#

I'm trying to find one from a previous year where i had a stupidly fast one

lyric mountain
#

u can try profilling it, if js has smth like that

#

to find out what's taking too long

stark kestrel
neon leaf
#

written in rust ofc its nice

frosty gale
#

ive gotten sick of rust recently so im going to try go instead

neon leaf
#

but cold starting the bins every time doesnt sound very effective

stark kestrel
#

go is nice because it teaches you principles that you must use in rust

lyric mountain
#

wait, this doesnt make sense lul (time is big cuz it's also counting the 1000 warmup runs)

#

why tf is the first taking 10x as long

frosty gale
#

if thats js its probably because it does a lot of hidden optimizations under the hood like hidden caches and precomputations to make future access/operations faster

lyric mountain
#

it's java

frosty gale
#

no idea then 💀

#

jvm broken

lyric mountain
#

lmao

frosty gale
#

maybe jit is warming up idk

lyric mountain
#

perhaps, dont think I can profile only the last run tho

#

oh wait, I can just not warmup

frosty gale
#

or it could just be the profiler thats doing something thats making it take so long

small tangle
#

what jdk are u using? 25 has some improvements regarding warmup time

wheat mesa
#

ngl day 4 was easier than the other days lol

#

been using python for this, relatively convenient

#

I figure I should get better at doing it for interviews anyways

lyric mountain
#

I'm trying to see if it's possible to reduce to 1ms

neon leaf
#

ty github

stark kestrel
neon leaf
#

ye

stark kestrel
#

yeah the macos ones are not cheap

neon leaf
#

indeed

#

atleast they run decently fast

#

unlike my windows builds that take 15min+ with cached deps

stark kestrel
#

normal windows behavior

lyric mountain
#

ok, not possible, 2ms is the rock bottom

covert gale
#

i still gotta start day 4

#

i took a peak earlier today and it seems pretty easy

#

one of the previous aoc's had something similar

warm surge
#

wsp @covert gale

covert gale
#

hello

wheat mesa
queen needle
#

Another stupid easy day

queen needle
#
const ranges = new Set(`3-5
10-14
16-20
12-18`.split("\n").map(x => x.split("-")).map(x => ({lower: Number(x[0]), upper: Number(x[1]) + 1})).map(x => Array.from({length: x.upper - x.lower}, (_, i) => i + x.lower)).flat()).size;
ranges;```
#

doesn't work on real input due to array sizes

#

the solution i actually used is a lot better

#

I'll be interested to see the optimizations done

wheat mesa
#

This one was a pretty well known leetcode medium

#

||merging intervals||

#

(Spoiler)

frosty gale
#

cloudflare is down AGAIN lmao

#

shopify, downdetector and LinkedIn bye bye

#

atp they're just playing an early April fools joke

deft wolf
#

The fact that downdetector is down is very ironic kappalul

neon leaf
#

works for me, tho it has been 10min so idk

pearl trail
#

yeah, not down just latency spike

#

on some region

#

*at least the sites on cf not down

frosty gale
#

it did cause a temporary outage of many sites

#

so basically an outage
(source: all my work related sites went down and the countless news articles)

lyric mountain
#

oh, today's the first day where I cant use the same code for both parts

#

cuz part 2 is completely backwards to part 1

neon leaf
#

A change made to how Cloudflare's Web Application Firewall parses requests caused Cloudflare's network to be unavailable for several minutes this morning. This was not an attack; the change was deployed by our team to help mitigate the industry-wide vulnerability disclosed this week in React Server Components. We will share more information as we have it today.

#

typical react moment

prime trellis
#

u saw this guys?

pearl trail
# frosty gale

oh, so must be some only on specific datacenter(?) im in asia

pearl trail
frosty gale
frosty gale
# prime trellis u saw this guys?

atp for my nextjs project I haven't touched for a year I get at least one CVE alert from github every month so doesn't surprise me

queen needle
queen needle
#

i could reuse like 70% of the code

lyric mountain
#

Ngl I'm finding this one harder than the past 4

queen needle
#

how??!

lyric mountain
#

idk, never had to face smth similar

queen needle
#

part 1 or part 2?

wheat mesa
#

I think it’s harder than the past 4 for sure

lyric mountain
#

part 1 was very easy

queen needle
#

generate an entire array for all the ranges, remove duplicates, get the length

wheat mesa
#

It’s too slow for how large the ranges are

#

There is an O(n) solution for merging the ranges instead of needing to iterate over every single number within the ranges

queen needle
#

I think my actual solution is O(n)

#

i might be wrong

lyric mountain
#

O(n) would mean for n ranges you're iterating n times

#

if you're expanding the ranges then it's much larger than that

queen needle
#

would it be O(n^3) if i go over the number-number once to turn it into {upper:..., lower:...} and then go through it again to merge, and then the last time to add to the fresh ingredients?

lyric mountain
#

no idea how to do big-O when the expanded inputs vary in magnitude

wheat mesa
#

Yeah this wouldn’t be an easy comparison

queen needle
#

I assume my way can be optimized I just don't know how

wheat mesa
#

Expanding the ranges is incredibly slow in comparison to merging them

queen needle
#

this is my soluition

wheat mesa
#

That’s the “correct” O(n) solution for merging the ranges

#

If you were doing the naive way of throwing every number in a range into a set then it would be infinitely slower

queen needle
#

oh no no

#

i did that as a joke because I got bored

#

that solution still takes about a second though

stark kestrel
#

the advantage of having read the input first for part 1 made me solve part 2 within seconds KEKW

#

made the merging directly

queen needle
#

If you make the merging directly could you still do part 1 with the merges?

stark kestrel
#

yeah

#
items
        .into_iter()
        .filter(|&i| {
            let x = i as isize;
            merged_ranges.iter().any(|&(l, r)| x >= l && x <= r)
        })
        .count()
#

part 2

merged_ranges
        .iter()
        .map(|&(l, r)| (r - l + 1) as usize)
        .sum()
queen needle
#

dang

stark kestrel
#

my merging is likely not the cleanest

fn read_and_merge_ranges(test: bool) -> (Vec<(isize, isize)>, Vec<usize>) {
    let sections = aoc_rs::input::read_file_in_sections(aoc_rs::input::get_path(5, test), "\n\n");
    let mut ranges = aoc_rs::regex::ranges(&sections[0]);
    ranges.sort();
    let items = sections[1]
        .lines()
        .map(|line| line.parse().unwrap())
        .collect();

    let mut merged = Vec::with_capacity(ranges.len());
    for (l, r) in ranges {
        if let Some((_, last_r)) = merged.last_mut() {
            if l <= *last_r {
                *last_r = (*last_r).max(r);
                continue;
            }
        }
        merged.push((l, r));
    }

    (merged, items)
}
#

made the capacity of the merged vec the len of the ranges, as it can't go higher

#

i took my first range, saw it was like 5 trillion of diff

#

so i was like, yeah ain't making a vec of those items 🤣

#

would've done the lazy technique otherwise

#

add all items and slap a .contains

queen needle
#

lmaoo

stark kestrel
#

always reminds me of the rocks/fish problem of previous years

queen needle
#

which problem?

stark kestrel
#

let me find them again

stark kestrel
queen needle
#
let { readFileSync } = require("node:fs"), { EOL } = require("node:os"), ageCounts = Array(9).fill(0);
const fishies = readFileSync("../input.txt", "utf-8").split(",").map(Number);
for (let fish of fishies) {
  ageCounts[fish]++;
}
for (let i = 0; i < 80; i++) {
  ageCounts[(i + 7) % 9] += ageCounts[i % 9]
}
console.log(ageCounts.reduce((a, b) => a + b));```
wheat mesa
#

AoC in 2021 😭 unc status achieved

queen needle
#

my beautiful solution for 2021 day 6

stark kestrel
#

fishies

#

i did 2021 & 2022 in go

#

2023 skipped because military

#

2024 & 2025 rust because learning it

#

and pre-2021 in python

wheat mesa
#

I did some of 2024 in rust (or maybe it was 23, can’t remember)

stark kestrel
#

iirc 19&20

queen needle
#

no day11 sadly

#

guess i gotta do it now

stark kestrel
wheat mesa
#

I’m doing 25 in python

#

Since I need to learn python

queen needle
#

last year i tried to do as many languages as i could

#

for python i tried to also do a oneline version everyday

wheat mesa
#

I’ve been putting off python practice for years

#

It’s lowkey been biting me in the ass for interviews though, figured I might as well practice LC-style questions with it

#

I use Java in my interviews but I’m realizing how much time I’m wasting

queen needle
#

use BF

#

I think I saw someone use BF for day 4

wheat mesa
#

I’ll pass

#

I have enough PTSD from my automata class with Turing machines

queen needle
#

lmao

queen needle
#

the general problem just looks like ```
stones = []
loop(25){
stones = blink(stones)
}
stones.length

quartz kindle
#

man

#

would you guys believe i spent like 3 fucking hours on part 2

queen needle
#

yes

stark kestrel
quartz kindle
#

because i decided to do some stupid linked list shenanigans instead of doing something remotely normal

#

but oh well, it takes 0.4ms to run /shrug

queen needle
# stark kestrel yeah ```rs pub fn execute(test: bool) { println!("{}", blink(25, test)); ...

could you help me understand the rules of "blinking"?

If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.)```
I don't get what it means by 1000 becoming 10 and 0, and then also in the example it shows 99 becoming two 9's? but that isn't in any of the rules
queen needle
#

send your solution rn

stark kestrel
queen needle
#

yeah but, 99 isn't even?

stark kestrel
#

The "is even" is for the number of digits in the number

queen needle
#

oh

quartz kindle
#

part 1:

function UGANDA(input) {
    const breakpoint = input.indexOf("\n\n");
    const ranges = input.slice(0, breakpoint).split("\n").map(x => x.split("-"));
    const values = input.slice(breakpoint + 2).split("\n");
    let n = 0;
    for(const val of values) {
        const num = Number(val);
        if(ranges.find(x => num > Number(x[0]) && num < Number(x[1]))) {
            n++;
        }
    }
    return n;
}
#

part 2:

function UGANDA2(input) {
    const breakpoint = input.indexOf("\n\n");
    const ranges = input.slice(0, breakpoint).split("\n").map(x => x.split("-").map(Number));
    const list = { start: ranges[0][0], end: ranges[0][1], prev: null, next: null };
    let first = list;
    for(let i = 1; i < ranges.length; i++) {
        const [start, end] = ranges[i];
        let current = list;
        if(start < current.start) {
            while(current.prev && current.prev.start > start) {
                current = current.prev;
            }
            const node = { start, end, prev: current.prev, next: current };
            if(current.prev) {
                current.prev.next = node;
            }
            current.prev = node;
            if(!node.prev) {
                first = node;
            }
        } else {
            while(current.next && current.next.start < start) {
                current = current.next;
            }
            const node = { start, end, prev: current, next: current.next };
            if(current.next) {
                current.next.prev = node;
            }
            current.next = node;
        }
    }
    let n = 0;
    let start = first.start;
    let end = first.end;
    while(first.next) {
        first = first.next;
        if(first.start > end) {
            n += end - start + 1;
            start = first.start;
            end = first.end;
        } else if(first.end > end) {
            end = first.end;
        }
    }
    return n + (end-start+1);
}
stark kestrel
#

If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. [...]

queen needle
#

okay i might be bad at reading lmao

stark kestrel
#

iirc i got super confused for that day while reading it at the beginning

#

sometimes i just read half the words lmao

queen needle
quartz kindle
#

the general idea is sort using a linked list and then traverse the sorted list

stark kestrel
#

bro got matrixed by linked lists

quartz kindle
#

initially i wanted to run the mergining while sorting, but it got too complex and i gave up

#

this is basically just a glorified version of sorting an array lol

#

i have no idea why the fuck i decided to do it this way

#

im a fucking idiot

queen needle
#

i mean hats off to you, i've seen no one else do it that way

quartz kindle
#

this works just as well, if not better:

function UGANDA2(input) {
    const breakpoint = input.indexOf("\n\n");
    const ranges = input.slice(0, breakpoint).split("\n").map(x => x.split("-").map(Number));
    const sorted = ranges.toSorted((a,b) => a[0] - b[0]);
    let n = 0;
    let start = sorted[0][0];
    let end = sorted[0][1];
    for(let i = 1; i < sorted.length; i++) {
        const [s,e] = sorted[i];
        if(s > end) {
            n += end - start + 1;
            start = s;
            end = e;
        } else if(e > end) {
            end = e;
        }
    }
    return n + (end-start+1);
}
#

fml

#

spent 3 hours for nothing

queen needle
#

is the time the same?

quartz kindle
#

better, 0.2ms

#

lol

queen needle
#

how tf

#
import * as fs from "fs";

const inputFile = "input.txt";
const fileContent = fs.readFileSync(inputFile, "utf-8");

let stones = fileContent.split(" ").map(Number);

function blink(arr: number[]): number[] {
  const out: number[] = [];

  for (const stone of arr) {
    if (stone === 0) {
      out.push(1);
      continue;
    }

    const digits = Math.floor(Math.log10(stone)) + 1;

    if (digits % 2 === 0) {
      const half = digits / 2;
      const div = 10 ** half;
      const left = Math.floor(stone / div);
      const right = stone % div;
      out.push(left, right);
    } else {
      out.push(stone * 2024);
    }
  }

  return out;
}

for (let i = 0; i < 25; i++) {
  stones = blink(stones);
}

console.log(stones.length);
#

2024 day 11 part 1 solution

#

i mean also part2

#

considering you just change one number

#

oh nevermind, it doesn't work for part 2

quartz kindle
queen needle
#

No

#

i can do that rq

queen needle
# queen needle 2024 day 11 part 1 solution
import * as fs from "fs";

const inputFile = "input.txt";
const fileContent = fs.readFileSync(inputFile, "utf-8");

let counts = new Map<number, number>();
for (const n of fileContent.split(" ").map(Number)) {
  counts.set(n, (counts.get(n) || 0) + 1);
}

function step(map: Map<number, number>): Map<number, number> {
  const next = new Map<number, number>();

  for (const [stone, count] of map) {
    if (stone === 0) {
      next.set(1, (next.get(1) || 0) + count);
      continue;
    }

    const digits = Math.floor(Math.log10(stone)) + 1;

    if (digits % 2 === 0) {
      const half = digits / 2;
      const div = 10 ** half;
      const left = Math.floor(stone / div);
      const right = stone % div;

      next.set(left, (next.get(left) || 0) + count);
      next.set(right, (next.get(right) || 0) + count);
    } else {
      const v = stone * 2024;
      next.set(v, (next.get(v) || 0) + count);
    }
  }

  return next;
}

for (let i = 0; i < 75; i++) counts = step(counts);

let total = 0;
for (const v of counts.values()) total += v;
console.log(total);
#

part 2

#

just changed it to a map

quartz kindle
#

your's shouldnt be much slower, just add the timers after reading the file from disk

stark kestrel
#

similar to today's problem imo

#

as well as the fishes

queen needle
#

for the fishes i didn't have to change the data structure

#

array still worked

#

day 5
Part 1: 14ms
Part 2: 9ms

#

I swear it ran slower last night

#

maybe the code got scared it was being timed and ran faster

quartz kindle
#

lmao

queen needle
#

Well also i think it was running fast, it just takes a little bit to show in the terminal

lyric mountain
#

aight, done it

queen needle
#

lets see it

#

did you have to go to java or no?

lyric mountain
#

no, still groovy

#
def input = getClass().getResource('/day5.txt').readLines()

def map = new TreeMap<Tuple2<Long, Long>, Integer>((a, b) -> a.v1 <=> b.v1 ?: a.v2 <=> b.v2)
def ranges = input.inject(map) {
    tot, v ->
        if (!v.empty) {
            def (a, b) = v.split('-').collect { it as long }

            if (b != null) {
                tot[Tuple.tuple(a, b)] = 0
            } else {
                for (p in tot.keySet()) {
                    if (a >= p.v1 && a <= p.v2) {
                        tot[p] += 1
                        break
                    }
                }
            }
        }

        return tot
}

def ids = ranges.keySet().toList()
def merged = new ArrayList<Tuple2<Long, Long>>()
for (id in ids) {
    def (aMin, aMax) = id

    if (!merged || merged.last.v2 < aMin) {
        merged << id
        continue
    }

    def (bMin, bMax) = merged.last
    merged[-1] = Tuple.tuple(bMin, Math.max(aMax, bMax))
}

println "Fresh: ${ranges.values().sum()}"
println "IDs: ${merged.sum { it.v2 - it.v1 + 1 }}"
queen needle
#

Whats the time look like for it

#

tf is <=>

lyric mountain
#

compare

#

aka spaceship operator KEKW

queen needle
#

lmao

stark kestrel
#

spaceship operator in groovy

#

turbofish operator in rust

#

sounds like based languages

queen needle
#

turbofish?

stark kestrel
#

::<>

lyric mountain
#

we also have elvis ?:

quartz kindle
#

lmao

lyric mountain
#

and churros =~

queen needle
#

okay well js has 1..a = undefined

#

so

#

clearly the superior

stark kestrel
lyric mountain
queen needle
#

gotta speed that up

lyric mountain
#

eh, aint spending more time on that one :v

queen needle
#

that's fair lmao

stark kestrel
#

I didn't hyperfine mine, gonna do it later, probably not super fast though

quartz kindle
#

its including file loading probably

lyric mountain
#

yep

queen needle
#

ahh

lyric mountain
#

but file access doesnt change much in java/groovy, they get cached

#

what's slowing it down is groovy itself, it aint exactly used for speed since all that sugar adds extra processing

quartz kindle
#

the algorithm itself shouldnt take more than 10ms

queen needle
#

what if you implement it wrong

#

lmao

quartz kindle
#

adding a while(true){} counts as implementing it wrong lmao

stark kestrel
#

realized that for searching the range that matches for part 1 you can likely do a binary search

#

can be faster by some ms 🤷‍♂️

queen needle
quartz kindle
#

lmao

lyric mountain
#

ok, made the optimized version

#

gonna benchmark now

#

@quartz kindle @queen needle can I get any faster?

queen needle
#

wtf

#

how

#

i just got 2ms and i switched to c++

lyric mountain
#

it floats between 0ms and 1ms

#

lemme switch to nanosecs

queen needle
#

is that ns?

#

or

#

nvm im dumb

lyric mountain
#

ns / 1e6

queen needle
#

good news: i got 0.2ms
bad news: now the answer is wrong

keen stag
#

halo

queen needle
#

Alright i got 0.36ms using c++

#

i can't do faster

#

and then a friend of mine immediately got 0.24ms using zig

#

need someone who actually knows c++

#

wheres brain

lyric mountain
#

I think the only way I can get faster with java is by building a native image

#

or using native arrays

queen needle
#

try

queen needle
#

Bruh

lyric mountain
#

cant go any lower

#

I'll try building a nat img

quartz kindle
#

bro using zig lmao

lyric mountain
#

nah it gets even slower

#

50% slower

queen needle
quartz kindle
queen needle
#

He's using AOC to learn it

lyric mountain
#

what's this even supposed to be?

#

a house?

queen needle
#

That was my thought

#

They haven't released any specific year merch unfortunately

#

I usually buy the hoodie with the design

deft wolf
#

Discord is removing active dev badge Classic

deft wolf
#

From the ddevs faq channel

clever tundra
#

thats obscene

#

well i still have mine

deft wolf
#

Not for too long probably kekw2

swift barn
deft wolf
#

Dev chat in ddevs is such a mess right know kappalul

#

People are arguing about the badges

warped glacier
#

Any idea why this could be causing a discord ratelimit on boot

#
@tasks.loop(minutes=30)
    async def update_topgg_stats(self):
        await self.wait_until_ready()
        if not self.topgg_token:
            return

        url = f"https://top.gg/api/bots/{self.user.id}/stats"
        headers = {
            "Authorization": self.topgg_token,
            "Content-Type": "application/json",
        }

        try:
            data = {"server_count": len(self.guilds)}

            async with aiohttp.ClientSession() as session:
                async with session.post(url, headers=headers, json=data) as resp:
                    if resp.status == 200:
                        print(f"[TOP.GG] Posted server count: {data['server_count']}")
                    else:
                        error = await resp.text()
                        print(f"[TOP.GG ERROR] Status {resp.status}: {error}")
        except Exception as e:
            print(f"[TOP.GG EXCEPTION] {e}")```
#

This is the only place its called

    async def setup_hook(self):
        self.update_topgg_stats.start()
        await self.tree.sync()
        print("[DEBUG] setup_hook running")```
#

And if i remove it i have no issues

harsh nova
#

I still dont understand how that code would be doing that. self.guild should(?) not make and calls to d API. I dont know what wait_unti\l_ready() does under the hood but my guess it it just waits for the discord ready event which should also not make calls to d API.

My very very loosely formed idea is that some part of that code crashes and it tries to restart, crashed again, and enters a loop? That might cause the repeated auth api calls to issue ratelimits but it seems like you are doing proper error handling

stark kestrel
#

how many times did you start the bot

warm surge
warped glacier
stark kestrel
#

you sync on every start/setup, only thing that can rate limit

warped glacier
warm surge
#

im watching it rn @deft wolf

stark kestrel
#

You have a limited number of syncs per day

warped glacier
stark kestrel
#

Sync only when needed

warped glacier
stark kestrel
#

Make it a command or something

warped glacier
#

Like today i hadent touched it in 3 weeks till now and immediantly got that ratelimit error

stark kestrel
#

Running on your pc i suppose

warped glacier
#

Where else would it be

stark kestrel
#

A shared IP VPS

#

Which is common for rate limit errors

warped glacier
#

You think i can afford a VPS for a bot that is free all around?

stark kestrel
#

Lots of people can

#

Since you didn't mention anything, I'm trying to isolate the issue

#

Seeing your responses I'll pass

warped glacier
#

I want to know what there jobs are then Bc i barely make enough to live.

#

Sidetracked

warped glacier
harsh nova
warped glacier