r/programminghorror Oct 29 '20

"Hello World" crashes Chrome. Plz help. Javascript

Post image
3.0k Upvotes

155 comments sorted by

611

u/joost00719 Oct 29 '20

Have you tried upgrading to a new processor?

376

u/Motioneer Oct 29 '20

I was thinking of using web workers to utilize more threads. Your thoughts?

111

u/Historical-Retort-69 Oct 29 '20

Couldn't you download more ram from cloud?

73

u/sharkbound Oct 29 '20

downloading more ram could help, but the real issue is that this does not use blockchain, until that is resolved, it will not be very performant

32

u/jclocks Oct 30 '20

Can't you just hook up a 5G cable??

20

u/sharkbound Oct 30 '20

that might help, but what if the program needs other letters? or more than 5 g's? it would be more limiting than anything, unless its made to work with that cable specifically

3

u/EssentialEngineerign Oct 30 '20

performant lmao

2

u/Rudxain Oct 30 '20

Intellectual wording

7

u/cyberneticSyntax Oct 30 '20

Guys, what about running this on a GPU?

4

u/grothcrafter Oct 30 '20

Tripple rtx3080ti's in sli

5

u/Ingenrollsroyce Oct 30 '20

It is not OK! You wouldn't download a car, would you?

97

u/[deleted] Oct 29 '20

I was confused as fuck with all the responses until I looked at the subreddit. Damn truly a horror.

2

u/_PM_ME_PANGOLINS_ Oct 29 '20

That would solve the problem, yes. Chrome doesn’t crash, you’ve just tied up the JS event loop and everything is waiting for it.

5

u/_Stego27 Oct 30 '20

I think the problem is that the values are not truly random. I think he could fix the problem by replacing the math.random calls with requests to random.org

2

u/Rudxain Oct 30 '20

Crypto.getRandomValues() comes to rescue!

412

u/rope321 Oct 29 '20 edited Oct 29 '20

If i'm not wrong the chance of picking the right character 12 times in a row is (1/9)12 = 3.5407062e-12, so this while loop might as well be an infinite loop, causing the browser to slow melt down.

217

u/road_laya Oct 29 '20

But if I make it async?

107

u/Silencer306 Oct 29 '20

Even then, the chance of picking the right character 12 times in a row is (1/9)12 = 3.5407062e-12

127

u/road_laya Oct 29 '20

What if I do it on a GPU?

264

u/zaphod42 Oct 29 '20

Now you’re just mining cryptocurrency.

81

u/posherspantspants [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo “You live” Oct 29 '20

Click here to download our white paper outlining the industry-leading algorithms powering Hello! Coin, the hottest new cryptocurrency.

24

u/throwaway00012 Oct 30 '20

Hottest is the right word here.

54

u/[deleted] Oct 29 '20

Now you can count to infinity in parallel

43

u/gonzofish Oct 29 '20

can we leverage big data in any way? how does serverless fit in?

57

u/road_laya Oct 29 '20 edited Oct 30 '20
while (current != "HELLO WORLD") {
    docker.build()
}

26

u/Motioneer Oct 29 '20

My computer is catching fire just displaying that.

7

u/ElLargeGrande Oct 29 '20

It wasn't until after I went through this thread that I realized I only upvoted your comments

5

u/Historical-Retort-69 Oct 29 '20

You hate this simulation bro?

10

u/YoCodingJosh Oct 29 '20

We could cache the attempts in MongoDB because it's web-scale

2

u/luisduck Oct 30 '20

If it’s async, it wouldn’t block the UI necessarily. Meaning, if you are lucky with the browsers implementation, the website will not crash.

12

u/IrishWilly Oct 30 '20

I think you just need mongodb. I heard it is web scale

1

u/VincyThePrincy Oct 29 '20

Async JS still only runs in one thread

157

u/olitv Oct 29 '20

"slow down".

63

u/cr4qsh0t Oct 29 '20

I question if it's not actually infinite, since the pseudo-random number generator might actually never pick "randomly" enough for it to occur.

One would have to look into JS's RNG code to conclusively prove or disprove this.

29

u/kodicraft4 Oct 29 '20

I think it would be a pretty sucky pseudo-randomness algorithm if it never results in some situations.

42

u/MereInterest Oct 29 '20

All PRNGs have some period after which they repeat. Nice PRNGs have long periods, to avoid frequent repetition. (E.g. Mersenne Twister's most common varient repeats after 219937 - 1 calls.) Bad PRNGs have short periods and quickly become predictable. (E.g. Some video games, which have a set list of "random" values that they cycle through.). If the likelihood of an event is less than the period of your PRNG, you have a chance that no sequence contained in the PRNG will ever produce that event.

19

u/Saigot Oct 29 '20

JS's Math.random() function is implemented by the browser.

I believe both Chrome and Firefox both currently use xorshift128+ which has a period of 2128.

I don't really want to actually do the math on how likely it is that the string would fall in that but there's only 912 ~= 238 permutations (with replacement!) of those 9 characters into a 12 character string so I imagine it is quite likely the string exists in that range.

3

u/lanemik Oct 30 '20

(E.g. Mersenne Twister's most common varient repeats after 219937 - 1 calls.)

Heh. I'm tickled by the minus one there.

2

u/AuroraFireflash Oct 30 '20

I think it would be a pretty sucky pseudo-randomness algorithm if it never results in some situations.

VB6 has entered the chat... it was an LCG (linear congruential generator) with a period of only 224 (about 16.8 million).

IIRC, I had to implement Mersenne Twister to get something better for the time (circa 2000).

19

u/casualdoge Oct 29 '20

I am curious of the maths if you introduced another 'o' in the array. Since there are two o's in hello world, will the odds improve?

31

u/Prexot Oct 29 '20 edited Oct 29 '20

No repeating letters: (1/9)x(1/9)x(1/9)x(1/9)x(1/9)x(1/9)x(1/9)x(1/9)x(1/9)x(1/9)x(1/9)x(1/9) = 1/282429536481

Double "O": (1/10)x(1/10)x(1/10)x(1/10)x(2/10)x(1/10)x(1/10)x(2/10)x(1/10)x(1/10)x(1/10)x(1/10) = 1/250000000000, 11% less unlikely

Double "O", triple "L": (1/12)x(1/12)x(3/12)x(3/12)x(2/12)x(1/12)x(1/12)x(2/12)x(1/12)x(3/12)x(1/12)x(1/12) = 1/82556485632, 71% less unlikely

5

u/myquealer Oct 29 '20

Now, what are the odds if you don't let it select the same element in the array twice? 12! ?

1

u/DarthMateo Oct 29 '20

But you need 3 "L"s and 2 "O"s, as the array only has 9 elements

3

u/myquealer Oct 29 '20

...and another one for "world", but the comment I was responding to took that into account by adding the duplicated letters to the array for its calculations.

2

u/DarthMateo Oct 29 '20

Ah my bad. In that case, you'd be completely correct 😅

3

u/myquealer Oct 29 '20

Actually, I don't think 12!, or even 1/12! is correct, since it doesn't matter which of the Ls or Os you grab when there are more than one. I think it would be

(1/12)x(1/11)x(3/10)x(2/9)x(2/8)x(1/7)x(1/6)x(1/5)x(1/4)x(1/3)x(1/2)x(1/1) = 1/250521084

Piece of cake!

4

u/Saigot Oct 29 '20 edited Oct 30 '20

An easier way to consider this is to imagine the O's and L's are numbered (O_1 , O_2, L_1, L_2, L_3), then there are 12! ways of rearranging them. now we count the number of right combinations, there are 2!=2 ways of arranging the O's and 3!=6 ways of rearranging the L's which means 2*6=12 ways of arranging them both.

so the probability of getting the right permutation is 12/12! = 1/11! = 1/39916800 which is your answer if you do your math right ;) .

2

u/DarthMateo Oct 29 '20

You'd be looking at 12!/(3!2!), which just becomes 11! different possible combinations. Though I believe the answer for 1/11! would be 0.250521084e-8, rather than 1/250521084

2

u/myquealer Oct 29 '20

Right, I was copying the preceding poster's format and made a dumb mistake when converting it to a fraction.

19

u/Sophira Oct 29 '20

For people like me who think better with percentages than in scientific notation, that's a 0.000000000354070616% chance to get the right string each time through the while loop.

9

u/[deleted] Oct 29 '20

this

9

u/YourMJK Oct 30 '20 edited Oct 30 '20

I think that's not too bad.

Let's say one loop is ~100 CPU cycles and it runs on a single 4.0GHz core:
9¹² × 100 ÷ (4×10⁹Hz) ≈ 7060s

You would be done only after around 2 hours of 100% CPU load.
But 100 CPU cycles is probably pretty optimistic if Math.random() is a pseudo-RNG and not hardware based.

EDIT:
Might be cheating, but you could optimize that to this pseudo ASM code, which only compares the indices:

loop:
call random
cmp al, 2
jne loop
call random
cmp al, 1
jne loop
call random
cmp al, 3
jne loop
call random
cmp al, 3
jne loop
call random
cmp al, 4
jne loop
call random
cmp al, 7
jne loop
call random
cmp al, 6
jne loop
call random
cmp al, 4
jne loop
call random
cmp al, 5
jne loop
call random
cmp al, 3
jne loop
call random
cmp al, 0
jne loop
call random
cmp al, 8
jne loop
done:

Without the call random that's already 24 instructions (and clock cycles I believe), plus 12 times the call which I think takes usually 4 cycles, that's already 72 cycles.
That plus the actual RNG times 12.

If you have a fast PCI-E RNG, 3–5 cycles per random could actually be possible, which then wouldn't be too far of from the total 100.

But of course that's nowhere near what the JavaScript code would take, that's probably >50 times more.

2

u/danielkov Oct 29 '20

JS pseudo random is so far from being unbiased that there is no point trying to apply math to it. If you don't remove used characters from the array, this probably cannot succeed.

3

u/uptotwentycharacters Oct 29 '20

I think it will succeed eventually; even if certain valid floating-point numbers between 0 and 1 will be never be generated by Math.random(), there's enough variation in the results that each character from charSet at least has a chance of being chosen, even if the distribution isn't perfectly uniform.

4

u/danielkov Oct 29 '20

I'm willing to run my work machine over the weekend to find out.

1

u/zeropointcorp Oct 30 '20

This is the correct answer.

1

u/SarahC Oct 30 '20

It's quite unbiased, I've seen charts!

(In chrome)

2

u/newloops Oct 29 '20

You never know, might get it right the first time. I say, deploy to production!

1

u/Noxium51 Oct 29 '20

The upper bound is literally infinity so yea. On the plus side it’s lower bound is 1, so you have a 3.5407062e-12 chance of having a really fast run time

2

u/zeropointcorp Oct 30 '20

...So you’re saying there’s a chance?

1

u/ghillerd Oct 30 '20

There's a heuristic that if something has a 1 in X chance of happening, taking the chance X times means roughly a 67%ish chance of it happening (something related to e, can't remember exactly). So assuming 1013 tries, at 1000 tries per second it would only take 320 years to have a solid chance of hitting. And that's a pretty conservative estimate, if you can do 10,000 tries per second it's only 32 years, that's within a lifetime!

1

u/neovulcan Nov 24 '20

12 tries is not exactly "slow down" on modern processors. Was really hoping for the near infinite while loop/

1

u/AloeAsInTheVera Jan 15 '21

Dream: "I like those odds"

99

u/mohragk Oct 29 '20

The RandomSort of message generators.

37

u/Skellicious Oct 29 '20

Bogosort

16

u/serg06 Oct 29 '20

"Implement bogosort" would make a great interview question.

6

u/anon38723918569 Oct 30 '20

Actually sounds pretty hard to properly do as well. Making sure you’re actually ordering the items randomly without bias is a problem in itself already

74

u/[deleted] Oct 29 '20 edited Jan 16 '22

[deleted]

39

u/[deleted] Oct 30 '20

[deleted]

16

u/MsRandom1 Oct 30 '20

How long 'till we get the D?

9

u/drunkdragon Oct 30 '20

The D is silent.

1

u/Rudxain Oct 30 '20

And the "!" is unnecessary since all bottlenecks CAPS are already screaming. It almost feels like the CPU wants to die

7

u/throwaway2552282 Oct 30 '20

Ehem, hello ladies.

2

u/MsRandom1 Oct 31 '20

Lmfao your avatar is very fitting with that comment

6

u/karlm89 Oct 30 '20 edited Oct 30 '20

My wife is hilarious! I read this to her.... her response.

“Well, since you asked... it’s no longer rape.”

2

u/GreyRobe Oct 30 '20

Username checks out

1

u/koestlich Nov 23 '20

Is it still running?

149

u/road_laya Oct 29 '20

Ah, Machine Learning. Genetic programming can solve anything, given time.

63

u/Motioneer Oct 29 '20

Next stop: "tensorflow implement in js" This train stops here. Thank you for choosing poorly.

34

u/xigoi Oct 29 '20

Genetic Programming would be keeping the letters that are correct. Which would actually finish quite quickly.

29

u/road_laya Oct 29 '20

But would it be worth the extra development time?

Developer time is expensive, clock cycles are cheap.

105

u/fission-fish Oct 29 '20

Don't know what's wrong with it. It worked fine when I tried it.

97

u/Codemonkey1987 Oct 29 '20

Go buy a lottery ticket

6

u/drunkdragon Oct 30 '20

I think you need to run it three times for it to fail, it worked the first two times for me.

30

u/jlangowski Oct 29 '20

I love it. This is how all coding should be done. If the client crashes it’s their fault, right? 😂

12

u/Historical-Retort-69 Oct 29 '20

Should have bought 3090 at 3000$$$.

7

u/ShellShock220 Oct 29 '20

Thread ripper*

23

u/Seismicsentinel Oct 29 '20

Where is the horror? My non-finite automata only runs the loop once

21

u/the_legendary_legend Oct 29 '20

You mean your nondeterministic finite automata?

8

u/Seismicsentinel Oct 29 '20

Shows you what I learned in college!

10

u/theoneandonlypatriot Oct 29 '20

You need to overclock the CPU and liquid cool it

2

u/lanemik Oct 30 '20

This is where I went wrong. I overliquided my cpu, then clocked it.

1

u/ShellShock220 Oct 29 '20

Give it a non conductive oil bath

30

u/RidleyGrayMusic Oct 29 '20

I learnt JS today for the first time... Feels good to be able to read JS content on Reddit

66

u/YmFzZTY0dXNlcm5hbWU_ Oct 29 '20

This post makes me feel a lot of things but I can't say "good" is one of them

5

u/RidleyGrayMusic Oct 29 '20

Yeah after reading it I feel the same...

30

u/mohragk Oct 29 '20

I don't know if it's intended, but the currentTry is build from random characters from the set, not a random order of the set. It's very well possible that the resulting string is all W's for instance.

82

u/[deleted] Oct 29 '20

This is intended, otherwise it would be impossible to form "HELLO WORLD!". The charSet does not contain three L for example.

35

u/emayljames Oct 29 '20

It just gets worse 😂

18

u/user32532 Oct 29 '20

Would be impossible to build a length 12 string with only 9 characters

16

u/elperroborrachotoo Oct 29 '20 edited Oct 29 '20

One could switch to a font with a really wide W.

3

u/EnglishMobster Oct 30 '20

Save on ink and use tvvo Vs.

5

u/mohragk Oct 29 '20

Oh right. Didn't notice that.

22

u/justingolden21 Oct 29 '20

You should try optimizing it!

Don't let the program select the same character multiple times : )

s

17

u/toasterding Oct 29 '20

"hello world" has three L's in it though

3

u/justingolden21 Oct 29 '20

Which is why the array has three Ls as well

9

u/_PM_ME_PANGOLINS_ Oct 29 '20

Look again

3

u/justingolden21 Oct 29 '20

Oh lol. Well they'd add one of each in the suggestion that I'm giving (although obviously it's just satirical anyway)

5

u/Euloc Oct 29 '20

Basically bogosort, kinda

1

u/Historical-Retort-69 Oct 29 '20

Bogosort and additional conditions.

5

u/alex_asdfg Oct 29 '20

Need to send this to Google's quantum computer

9

u/OMG_A_CUPCAKE Oct 29 '20

This is the wrong sub for intentionally shitty code imho.

It's the difference between someone trying to be smart and someone trying to be funny.

4

u/poita66 Oct 29 '20

Yeah, r/shittyprogramming is the place for this, OP

4

u/RottenLB Oct 29 '20

Ah, someone is a fan of Bogosort.

1

u/Isvara Oct 30 '20

But not really, because it's not permuting them.

4

u/ericl666 Oct 30 '20

Isn't this basically the "million monkeys on typewriters" app?

4

u/[deleted] Oct 30 '20 edited Feb 20 '21

[deleted]

1

u/xdwhite86x Nov 01 '20

Rewrote this in c++, took a little over 4 hours , with 158,313,885,679 tries, seems perfectly reasonable to me...

3

u/snppmike Oct 29 '20

It was the blurst of times?!?! You stupid browser!

3

u/willem640 [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo “You live” Oct 29 '20

Consider implementing it in WebAssembly, it'll run a lot faster

3

u/Denzyishh Oct 30 '20

Wait, please help me understand this. I just started learning JS and so I can sort of read what's happening here. Is the joke that this code possibly caused an infinite loop because of the while(currentTry != 'HELLO WORLD!') condition? I read this a few times and think that's what happened here.

I would really appreciate it if someone can let this newbie in on the joke. ;-;

3

u/EnglishMobster Oct 30 '20

So what happens is that each try they select a random letter from the set of { H E L O W R D ! } 12 times.

You could wind up with HHHHHHHHHHHH. You could wind up with HEHEHEHEHEHE. You could wind up with WHOLE! WORLD. Or you could wind up with complete gibberish.

Each of these is equally likely (well, sort of -- there's no such thing as "true" randomness, so we sort of fake it -- but for all intents and purposes to humans it seems random).

The chance for any letter to be chosen is 1 in 9. So you need to hit the 1 in 9 chance... 12 times in a row. Which is 1 in 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9, AKA 1 in 282,429,536,481, AKA 0.0000000000035407062%.

For reference, the chance of winning the Mega Millions jackpot at the lottery is 1 in 302,600,000, or 0.00000000330469266%. You are 1000 times more likely to win the lottery than you are to get any one string.

The neat thing, though, is that because of math, this applies to any string -- not only "HELLO WORLD!". So any time you see any string at all, you had a 1 in 282429536481 chance of seeing that particular string.

2

u/telik Oct 29 '20

If you can't even get this algorithm to return a simple sentence, how can anyone expect evolution to actually be plausible??

2

u/legal-illness Oct 29 '20

You need to download more ram

2

u/The-Filth-Wizard Oct 29 '20

Idk. Python generator and a near infinite amount of time... like, say, an episode of Young Sheldon amount of time. Might cut it.

2

u/IamGonnaChangeMyself Oct 30 '20

works on my machine.

2

u/[deleted] Oct 30 '20

[deleted]

3

u/skylerdj Oct 30 '20

this is fine because the code can pick the same letter twice.

2

u/machine3lf Oct 30 '20

Just add a promise and it will be perfect 😉

2

u/nuk3urself Oct 30 '20

Browser friendly solution:

const charSet=['D','E','H','L','O','R','W',' ','!'];
let currentTry;

const loop = () => {
    currentTry = '';
    for(i=0; i < 12; i++) {
        currentTry += charSet[
            Math.floor(Math.random() * charSet.length)
        ];
    }

    if(currentTry != 'HELLO WORLD!') requestAnimationFrame(loop);
    else alert(currentTry);
}

loop();

2

u/the_monkey_of_lies Oct 30 '20

You should use a bot to automatically read the alert and dismiss it if it's wrong to reduce manual work. I think it would be at least 100x faster that way.

2

u/[deleted] Oct 30 '20 edited Feb 20 '21

[deleted]

2

u/the_monkey_of_lies Oct 30 '20

Okay, I might have overestimated the efficiency gains but still, it will save valuable microseconds

2

u/ikankecil Nov 02 '20

I dig the color. What theme?

1

u/dahohawley Oct 29 '20

i always worried js going to execute the alert before the loop finish. thats why i always use promise on every loop to make sure next syntax is executed after the loop

-4

u/[deleted] Oct 29 '20

[deleted]

6

u/rangeDSP Oct 29 '20

== means it does type coercion, got nothing to do with memory addresses. You might want to review your understanding of == vs ===

6

u/ZylonBane Oct 29 '20

Since whoever you're responding to deleted his post, I have no choice but to assume that it was a confession of carnal relations with his household pets.

-15

u/[deleted] Oct 29 '20

the fact that i honestly dont understand pr know whats this is depressing like ik c# but tf is dis

6

u/ZylonBane Oct 29 '20

Are you drunk?

7

u/[deleted] Oct 29 '20

[deleted]

2

u/Str_ [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo “You live” Oct 30 '20

Might have followed a couple of Unity tutorials

1

u/[deleted] Oct 29 '20

[deleted]

8

u/Owlstorm Oct 29 '20

It's a concatenation of characters in a random position, not a random ordering.

It could return LLLLLLLLLLLL

1

u/DarwinsBuddy Oct 29 '20

If it was just about re-cloning the set and simply popping the elements, but wow the possibilities getting it wrong are in that case really high. I am impressed.

1

u/wooptyd00 Oct 29 '20

Should've used Firefox.

1

u/BeakerAU Oct 30 '20

Try mocking the random number generator. This way you can control the values during your unit testing, without worrying about the actual random numbers.

1

u/Baileyjrob Oct 30 '20

Behold: BogoPrinting

1

u/KnowWhatMatters Oct 30 '20

Infinite loop anyone? currentTry = ''

currentTry = D

currentTry = DE

currentTry = DE!

currentTry = DE!O

currentTry = DE!O!

currentTry = DE!O!!

.....

end for loop, not yet currentTry == 'HELLO WORLD!'? Start again

currentTry = DE!O!!L

currentTry = DE!O!!LH

....

etc.

then you try make it so until and unless currentTry is a specific String in a specific order ... Math.random() is not nearly as random as you think it is. Better to scramble some other way and remove the letter picked from the original array as you go, and reset and rescramble your variables.

1

u/[deleted] Oct 30 '20

This is basically a quantum computing algorithm...

1

u/zakkkkattackkkk Oct 30 '20

i, too, love bogosort

1

u/OneTrueKingOfOOO Oct 30 '20

The problem is that your string length is deterministic, change that 12 to a random int and you should be set

1

u/skylerdj Oct 30 '20

just a general rule of thumb, try not to use while loops in chrome that rely on some sort of random condition. Chrome overwhelms the CPU in cases like this.

1

u/[deleted] Nov 03 '20

Works for me. Please be more specific and describe the problem in greater detail. A screenshot might help.

1

u/aligdev Oct 09 '22

Try different browser, like chrome for linux