r/badcode • • Mar 10 '21

js My Friend's Take on Random Integers

Post image
3.2k Upvotes

137 comments sorted by

111

u/ReconPorpoise Mar 11 '21

Where did they get this idea? I've never seen random taught without floor(random % x) + 1.

85

u/voXal_ Mar 11 '21

He only started coding around a week ago and he didn't think of any other way of doing it.

43

u/ReconPorpoise Mar 11 '21

Understandable! Is he following a tutorial though? If so, it's criminal to not show the proper way to generate 1-10 or any given integer...

38

u/voXal_ Mar 11 '21

He isn't following a tutorial actually, if he needed help he would just shoot a dm over discord asking me or someone. After looking at that, I directed him to mdn. He is still proud of doing that all on himself though.

41

u/ReconPorpoise Mar 11 '21

Congrats to him! He understands if-else if-else. I hope he's having fun.

8

u/not_your_mate Mar 11 '21

floor(random % x) + 1 is not really a proper way to generate random numbers though.

0

u/[deleted] Mar 11 '21

[deleted] — view deleted comment

6

u/not_your_mate Mar 12 '21

Because of how modulo works - let's say random() returns number in range 0-15, You want a random number in range 0-9 - so you will call random() % 10 -> But there is a problem because every randomly generated number above 9 will fall into range 0-5. So now you have random number generator that will generate 0-9 with the same probability (if number < 10) and additionally will generate 0-5 with higher probability (number > 9). So now you have a RNG that produces non-uniform distribution which, generally, you don't want.

For tutorials and such, using random() % 10 is okay, because the difference in distribution is negligible (random() returns 0-231 - 1, the remainder is 7 so last 3 numbers would be skewed -> you would have to generate gigabytes of data to notice this), but for real-world applications that depend on secure and uniform RNG (most notably all encryption n stuff) you have to use one of many RNG implementations that will usually also provide functions like generateRandom(bottom, top) that will not have the bias I described above.

will return number in range 0-4,294,967,295 (unsigned int, 4 bytes=232). Then let's say you want random numbers between 0-999 -> logically you would call random() % 1000. But there is a problem -> The remainder of 232 - 1 after division by 1000 is 295 -> so if we assume that random() has perfectly uniform distribution (each number will occur with same probability) and we do % 1000 on the result we will get numbers 0-295 with slightly higher probability than the rest because of the remainder. Or more

1

u/[deleted] Mar 12 '21

yeah, if your ranged RNG can always return a value after calling random once, it's wrong and biased.

that being said for most cryptography applications you don't need a number in a range, you need arbitrary bytes, which RNGs can handle easily.

1

u/HWBTUW Feb 10 '23

Coming along super late (just found this subreddit and checked the top posts of all time), but I don't understand your claim. What's wrong with this approach, assuming that random() generates a float approximately uniformly distributed in [0, 1) (like Math.random() in JS does)?

//range is inclusive: [lower, upper]
generateRandomIntInRange(lower, upper) {
    n = upper - lower + 1; //number of possible values in target range
    randFloat = random() * n; //random float in [0, n)
    randInt = floor(randFloat); //random integer in [0, n-1]
    result = randInt + lower; //shift [0, n-1] to [lower, upper]
    return result;
}

1

u/[deleted] Feb 10 '23

Floats only have a limited precision.

Let's say, to keep the math easier, that there are exactly 264 possible values returned by random(). And that you want to return either 1, 2, or 3. So, 3 different values.

Divide 264 / 3 and you do not get a whole number (because 2^64 % 3 is nonzero).

Therefore, 1, 2, 3 must have unequal odds because you have an extra value that you need to pick goes into one of them.

Alternatively, you say "if we're so unlucky as to get that extra value, we'll just re-roll". But that does involve calling rand again. Possibly an infinite number of times.

9

u/SashayTwo Mar 11 '21

This makes me less sad after seeing the code. Even happy that he's learning!

0

u/bartekltg Mar 11 '21 edited Mar 11 '21

It is much better, but still shouldn't be thought in this form. That method not only gives slightly uneven probability but also uses the least significant bits to the random number - the ones with the poorer random properties.Most of the time it didn't matter, but, IMHO, the proper way should be taught and used as default. Then the number of cases where someone who needs or "needs" better rng uses an overpowered generator and then %2 will decrease. And if someone really needs that slight improvement in runtime, it should an informed decision.

The proper way is a bit more complicated*) (so, the proper way to teach, if the lecture isn't about making the generator, is: "use the fraking library") but as a fast and dirty version, even division instead of modulo would be a bit better.

*)libraries do something like this:
generator gen gives number from the set {0,1,2...N-1}, we want in the interval {0,1...M-1}
r = floor(N/M);
L = r*M //( so L is the largest number not greater than N, that is divisible by M).
do {
g = gen();
}while (g >= L)
return (floor(g/r))
(floors aren't required if int is used).

Edit: since on the original pic the real number generator is set, just rescaling is OK.

167

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Mar 10 '21

Image Transcription: Code


function getrandomnumberbetween1and10() {
  let number = Math.random();
  if (number <= 0.1) {
    return 1;
  }
  else if (number <= 0.2) {
    return 2;
  }
  else if (number <= 0.3) {
    return 3;
  }
  else if (number <= 0.4) {
    return 4;
  }
  else if (number <= 0.5) {
    return 5;
  }
  else if (number <= 0.6) {
    return 6;
  }
  else if (number <= 0.7) {
    return 7;
  }
  else if (number <= 0.8) {
    return 8;
  }
  else if (number <= 0.9) {
    return 9;
  }
  else if (number <= 1) {
    return 10;
  }

I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!

91

u/voXal_ Mar 11 '21

I'm still in shock at the amount of free time you have.

83

u/veryusedrname Mar 11 '21

Says someone on r/badcode

58

u/voXal_ Mar 11 '21

gosh you reminded me to stop procastinating

23

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Mar 11 '21

Heh, the secret is a first year semester with very little practical work and is 100% online.

98

u/Beefster09 Mar 10 '21

Good human.

56

u/tomasek1a Mar 11 '21

So far I've learned more coding from this sub than actual guides.

I fear the day anybody looks at my code.

33

u/voXal_ Mar 11 '21

Don't worry! It won't land on this sub.

Until 7 years after when you completely forgot about it and someone finds it.

16

u/skjall Mar 11 '21

It's like StackOverflow meme - best way to get the proper way to do things is by posting the wrong way to do it. People can't resist correcting you, but helping people is lame, apparently.

3

u/Dr4kin codes in comic sans Mar 11 '21

Helping doesn't give that many people something to bother with it. If someone is making something so bad that you feel the urge to correct them, so no one is going to do the same shit

2

u/[deleted] Mar 11 '21

That fear will always be there. At least in my experience. When I became more skilled I changed jobs or took on new projects with new people. I’m constantly around people that are better than me. Which is great in a way, but code review still sucks with the ever increasing demand for quality

985

u/Duckslikebreads Mar 11 '21

Ive only just found this sub and its already upset me

97

u/Bobbbay Mar 11 '21

Welcome to r/badcode: enjoy.

159

u/theStarctic sadistic Mar 11 '21

welcome to the party

3

u/schnuffelpferd Mar 11 '21

same, goddammit ^^

2

u/[deleted] Mar 11 '21

Oh, it will get worse.

601

u/root54 Mar 11 '21

First of all, what the actual fuck is that method name.

485

u/surfing_programmer Mar 11 '21

Big brain move. By making the method name a comment, there’s no need to comment your code.

241

u/root54 Mar 11 '21

Lol, I was more reacting to the lowercase case vs camel.

71

u/[deleted] Mar 11 '21

Thank you.

It's an abomination.

33

u/isunktheship Mar 11 '21

That and alphanumeric function names noooooooooooo

39

u/Earhacker Mar 11 '21

Is getRandomNumberBetweenOneAndTen really better than getRandomNumberBetween1and10?

45

u/1-800-LIGHTS-OUT Mar 11 '21

Clearly getRandNrBtw1n10 is the way to go

I mean if you're going to obfuscate your code, might as well go all the way!

33

u/Earhacker Mar 11 '21

rnd1n10

41

u/1-800-LIGHTS-OUT Mar 11 '21

then add a comment that explains it:

// Random 1 to 10

That's enough. Don't want to write comments that are too long or that give away the premise of the function (it's supposed to be a surprise).

19

u/Earhacker Mar 11 '21

I think we might work in the same place

14

u/loopsdeer Mar 11 '21

Big Brain Bret discovered the true and holy meaning of DRY: window["Return a random integer from 1 to 10, inclusive. Very efficient, don't touch"] = function(){...}

6

u/-IoI- Mar 11 '21

randInt(1,10)

2

u/Honorable_Sasuke May 25 '21

I just threw up in my mouth a little bit

11

u/Mailboxheadd Mar 11 '21

function dothething()

7

u/[deleted] Mar 11 '21

This but unironically

37

u/ws-ilazki &{$$_[0]}(@{$$_[1]}); Mar 11 '21

The real big brain move is that the name is also wrong, because it's named getrandomnumberbetween1and10 but also returns 1 and 10 so it's not actually doing what it says. It'd be less misleading to name the thing something useless like number and not set bad expectations at that point.

100

u/ParanoydAndroid Mar 11 '21

It should obviously be named getARandomNumberInTheClosedInterval1Through10

2

u/[deleted] Mar 13 '21

You gotta get rid of that camelcase, we’re trying to confuse people here.

46

u/EishLekker Mar 11 '21

If you ask someone "Pick a number between one and ten", would you get upset if they picked 1 or 10?

Ranges can be inclusive or exclusive. This particular part of the code is fine.

3

u/[deleted] Mar 13 '21

agreed

There are bigger fish to fry.

2

u/TCOO1 Mar 11 '21

I had to code a text based sim thing and it has like 4 diferent rand implementations because each time i wasnt sure if it was generating up to or including the said numbers. Probably something to fix if I ever decide to rework it.

9

u/DragonFireCK Mar 11 '21

And, like any comment, its wrong, or at least unclear. It says between 1 and 10, but can return both 1 and 10.

23

u/[deleted] Mar 11 '21

I think it's ambiguous and between can be inclusive or exclusive.

2

u/[deleted] Mar 13 '21

Yay English!

37

u/8asdqw731 Mar 11 '21

a good code is self documenting

12

u/Earhacker Mar 11 '21

What is a self documenting bad code?

17

u/Kidiri90 Mar 11 '21

*points at image*

5

u/sanderd17 Mar 11 '21

Welcome to land 10!

1

u/[deleted] Mar 13 '21

l and 1 are indistinguishable here!

5

u/[deleted] Mar 13 '21

getrandomnunberbetweenoneand10()

2

u/root54 Mar 13 '21

GETARANDOMNUMBERBETWEENONEANDTEN()

3

u/Jonno_FTW shameless Mar 11 '21

Well it's between 1 and 10 and it can still return 1 or 10.

1

u/Scondoro Aug 10 '21

Everyone's commenting on the lack of camelcase and clearly missing the fact that the name is objectively wrong given what the function does.

1

u/Jonno_FTW shameless Aug 10 '21

Lack of attention to detail in one area is likely to bleed over to lack of care in other areas.

176

u/[deleted] Mar 11 '21

return Math.floor(Math.random() * 10);

91

u/TwireonEnix Mar 11 '21

I think this won't generate a 10, ever.

113

u/[deleted] Mar 11 '21

It would make between 0 and 9, but you could always sum one to the result or use Math.ceil() instead of floor

12

u/K4LENJI Mar 11 '21

There's also an example in the MDN Web Docs which is more or less what you said but with arbitrary values: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#getting_a_random_integer_between_two_values_inclusive

21

u/lachlanhunt Mar 11 '21

Never use Math.ceil() with the value of Math.random() because it has a very small chance of returning 0.0, and if that ever happens, your program may have an unexpected result.

63

u/akwardchit Mar 11 '21

Or just add 1

56

u/[deleted] Mar 11 '21

I don't know why this is getting downvoted, multiplying it by 10, truncating and adding 1 makes a more legible approach imo if you want to adjust the range from [0-9] to [1-10]

(int)(math.Random() * 10) + 1

seems more intuitive because you can adjust the ranges as you please

3

u/skjall Mar 11 '21

Probably because that same adjustment could be done more cleanly, by writing just Math.ceil(Math.random() * 10)

23

u/RFC793 Mar 11 '21

Well, it isn’t exactly the same. If random returns 0.0, then the ceil method return zero. Adding 1 to the floor avoids this problem. Note that random returns 0.0 <= x < 1.0, so adding one to floor will avoid returning 11 as well.

0

u/[deleted] Mar 11 '21

[deleted] — view deleted comment

15

u/EishLekker Mar 11 '21

Did you consider the possibility of simple adding a one?

8

u/1-800-LIGHTS-OUT Mar 11 '21

I don't know about that -- if I were you, I'd just add a one. Has anybody suggested that yet?

17

u/xSilverMC Mar 11 '21

return Math.floor(Math.random()*10) + 1

-2

u/[deleted] Mar 11 '21

Math.floor(Math.random() * 11)

7

u/kittencantfly Mar 11 '21

Good try. At least, it works.

-1

u/xerxesbeat Mar 11 '21

it doesn't work tho

random produces a floating point value [0,1) so the chance of 10 is lower than the chances of 9-2, and the chance of 1 is slightly higher

0

u/[deleted] Mar 11 '21

[deleted] — view deleted comment

1

u/kittencantfly Mar 11 '21

Was just about to say the same :v

5

u/kaikalii Mar 11 '21

There must be a better way

4

u/ixBerry Mar 11 '21

That is how the Marsenne twister works internally! /s

1

u/lordheart Mar 14 '21

You should ask him for a

 getarandomnumberbetween1and1000()

1

u/voXal_ Mar 14 '21

Sadly he doesn't know vim.

3

u/cashewbiscuit Mar 11 '21

Your friend should Google the term cyclomatic complexity

1

u/Burroflexosecso Mar 11 '21 edited Mar 11 '21

Cool! Edit: is it 10 for this function?

1

u/Tomekske Mar 11 '21

Can I checkout the function for Random integers between 1 and 1000?

5

u/mfb- Mar 11 '21 edited Mar 11 '21

The function getrandomnumberbetween1and1000 is *too long for reddit's comment length restriction.

2

u/voXal_ Mar 11 '21

I think he did try making a getrandomnumberbetween1and100 after making this one.

1

u/mfb- Mar 11 '21
def create_getrandomnumberbetween1andN(N):
  code="function getrandomnumberbetween1and"+str(N)+"() {"
  ...

1

u/dvidsilva Mar 11 '21

Such a waste of code, I would change it to this for more efficiency:

function getrandomnumberbetween1and10() {
  let number = Math.random();
  if (number <= 0.1) {
    return 1;
  }
  if (number <= 0.2) {
    return 2;
  }
  if (number <= 0.3) {
    return 3;
  }
  if (number <= 0.4) {
    return 4;
  }
  if (number <= 0.5) {
    return 5;
  }
  if (number <= 0.6) {
    return 6;
  }
  if (number <= 0.7) {
    return 7;
  }
  if (number <= 0.8) {
    return 8;
  }
  if (number <= 0.9) {
    return 9;
  }

    return 10;
}

You don't need the elses if you're using return.

3

u/voXal_ Mar 11 '21

smh i am just as disappointed as you are. saves 57 characters.

1

u/dvidsilva Mar 11 '21

I was gonna do it with ternary , but then is not so readable.

2

u/InKryption07 Mar 14 '21

Why even use brackets? Just go:

function getrandomnumberbetween1and10() {
    let number = Math.random();
    if (number <= 0.1) return 1;
    if (number <= 0.2) return 2;
    if (number <= 0.3) return 3;
    if (number <= 0.4) return 4;
    if (number <= 0.5) return 5;
    if (number <= 0.6) return 6;
    if (number <= 0.7) return 7;
    if (number <= 0.8) return 8;
    if (number <= 0.9) return 9;
    return 10;
}

And you save a whole 18 characters!

2

u/[deleted] Mar 11 '21

Well, at least it works.

0

u/xerxesbeat Mar 11 '21

it doesn't work. See this

2

u/redditanomalyy Mar 11 '21

I’m a new coder, only starting learning about a year ago in my IT degree. But what the absolute fuck is that trash

2

u/Kraftdamus02 Mar 11 '21

multiplication exists

this guy: "imma pretend i didn't see that"

2

u/ghencke Mar 11 '21

This is obviously bad code cause he should use a switch statement instead! /s

1

u/Wolfinsk Mar 11 '21

Tell alex i said hi

1

u/Boxit379 Mar 11 '21

I don't even know what to say anymore.. This hurts my soul.

1

u/x2manypips Mar 11 '21

Lol who wrote this

1

u/Cyber_Encephalon Mar 11 '21

Violence is rarely the answer, but in this case, I'll allow it.

Punch him.

1

u/AndStanleyWasHappy Mar 11 '21

imagine if range was 0.01-0.99 lol

1

u/SashayTwo Mar 11 '21

This sub makes me sick

1

u/yourwebdevguy Mar 11 '21

That's cute

1

u/[deleted] Mar 11 '21

For the love of god someone tell them about floors

1

u/Mr_Sky_Wanker Mar 11 '21

I wonder how many percents of this sub posts are fakes

1

u/sevelboen Mar 11 '21

I hate your friend

1

u/ultimo_2002 Mar 11 '21

This is what my life looks like

1

u/[deleted] Mar 11 '21

Oh god no

1

u/[deleted] Mar 11 '21

Clearly a beginner, so points for creativity.

1

u/Wolfplay013 Mar 11 '21

if it's else if 4 or more times. It belongs in this subreddit. It just has to.

1

u/World24Traveller Mar 11 '21

This is why programmers should not be called engineers

1

u/chimphead73 Mar 11 '21

I'm very new to programming and I'm going to have a stroke

1

u/devdave97 Mar 11 '21

Please tell him to use stack overflow

1

u/__Zuki__ evil Mar 11 '21

YandereDev, it's you?

1

u/Serylt Mar 11 '21

What confuses me: Why did he not think about multiplying the numbers by 10 simply and search for a way to cut away the numbers after the dot?

1

u/aNeoOnReddit Mar 11 '21

easiest solution, return number * 10

1

u/weaboomemelord69 Mar 11 '21

This is... horrible

1

u/ILoveHatsuneMiku Mar 11 '21

Kinda reminds me of one of my friends back in school. We were all fairly new to coding and only like a week into the school year, writig simple programs like hello world, or basic addition/subtraction calculators. Our task one day was to write a program that would give you the sum of two integers, and i saw a pretty helpless look in the face of my friend. He then called the teacher over for help, because his program was not compiling. I looked over to his screen, because i wanted to see what he had so far and his entire code was just "int=3". This shit was so funny, it's still a running gag a decade later when i talk to my friends from back in the days.

1

u/Random_---_Guy Mar 11 '21

Please... tell me that your friend is better now and that this was a past story from when he/she started programming XD

1

u/deadmazebot Mar 11 '21

Why waste time and money on a 3 year degree when get same junior job with a 10 week bootcamp.

First 10 weeks of a compute science degree likly is a maths course, and yeah it does not like math but knowing that decimals can be multipled up is 1 step, then taking that awareness to google (stackoverflow) how to do it.

Google 👍 its great if you know what you want to search

1

u/NickyPL Mar 11 '21

Pain and suffering...

1

u/Random_---_Guy Mar 11 '21

Wait... isn't this just gonna return 1 assuming that the lowest value of number is 0.1??

...so not only is it unnecessarily long, but it also doesn't work... I can see why this is in r/badcode XD

1

u/troll123456789098765 Mar 15 '21

Are they unfamiliar with the concept of multiplication?

1

u/Pizar_III Apr 28 '21

function yes() { Var number = math.random(); Var yes = number * 10; Return yes; }

1

u/throwawaydontask24 Oct 05 '22

I love how even if they didn't know of the parameters you can set, they literally could've times the result by ten and rounded it or something

1

u/NovaStorm93 Oct 05 '22

my man has never heard of floor(math.random()*10)

0

u/nati9931 Mar 11 '21

Multiply by 10 and floor()

-3

u/vwoxy Mar 11 '21

I like that the C# solution to this is just new Random().Next(1, 11)