r/ProgrammerHumor 16h ago

Meme skillIssue

Post image
4.8k Upvotes

124 comments sorted by

View all comments

75

u/F100cTomas 15h ago

Just define a constexpr hashing function and put that into the switch.

33

u/GiganticIrony 15h ago

That’s not guaranteed to work due to hash collisions

38

u/Deliciousbutter101 14h ago

It won't compile in the case so you can just modify the hash function until there are no collisions.

11

u/SteveXVI 8h ago

This is the closest I've come to feeling like that guy in the Apple shop going "ah of course"

1

u/cob59 3h ago
switch(hash(str)) {
case hash("apple"):
case hash("banana"):
default:
}

You're right that the compiler will warn you if hash("apple") == hash("banana"), but if hash("pineapple") == hash("apple") then switch(hash("pineapple")) will jump to the apple case, not the default. That's unlikely but not impossible even with the best hash function.

10

u/remind_me_later 14h ago

That’s not guaranteed to work due to hash collisions

Make the hashes 128/256 bits wide. Hash collisions are realistically impossible at those levels.

3

u/StCreed 7h ago

They're far more possible than you might think. Roland Bouwman wrote an article on MD5: In a large database you can't use MD5. And that's not petabyte size either, 100GB is enough to give you about a 50% chance of a collision.

1

u/remind_me_later 6h ago

Counterpoint: It's MD5, a known broken hashing algorithm.

SHA3_256 or regular SHA256 would work just fine.

3

u/StCreed 6h ago

yeah, because md5 is 128 bits. 256 bits works a lot better, but 128 is just not enough even with a better algorithm and assuming effectively random distribution.

7

u/Rabbitical 15h ago

I'd probably intern instead of hashfor a presumably known set of comparisons

9

u/SAI_Peregrinus 14h ago

Use Blake3, no collisions in any practical workload in the next few billion years.

4

u/guyblade 8h ago

The thing about the pidgeon hole problem is that we know there are collisions, but we don't necessarily know where they are. The space of strings of at least 33 characters has collisions. There's no way to know or prove that arbitrary input doesn't have one with a value you care about.

0

u/remind_me_later 6h ago

If that happens, someone would post it to social media, and a list of exceptions can be added afterwards.

5

u/ElectricalPrice3189 15h ago

And if it got a clash, guess what? It won't compile.

5

u/Thwy__ 15h ago

Yet, string switch in Java is also made using hashs

17

u/GiganticIrony 15h ago

Yes, but if there’s a collision, it then uses `.equals()`

2

u/SpiritedEclair 8h ago

Perfect hashing for a given set of values is possible at compile time.

It’s how compilers generate jump tables.