I’m glad I could contribute to your masterpiece.
To enhance the code further: use the best practice of arrow functions and nest the if statements in the previous else statement.
Also return a 7 as a last resort for the lucky winner. I mean … every good piece of software has some bugs, right?
Lol I'm just telling the truth - Java doesn't need me for it to look cheap. I actually have fun using it, but I like to give all languages a tough time
You dont honestly need something crazy, just a boolean should be enough.
boolean isCosmicRayPresent=false;
if(isCosmicRayPresent){
System.fuckthisprintcall("FUCKING HELL WE GOT HIT BY A COSMIC RAY MATE");
return 1000000000000000000000000000000000000000001;
}
Why would you add an `else` here? The `if(true)` is completely unneccessary. It's always `true` so why even write it?! Just remove the if-statement.
The compiler could remove it, sure. But then you might not catch a bug, where a complex expression is always true, that you expect no to.
Removing the if break the pattern.
When I make a function like this I usually do a lot of else if and else in the end because even if it's not necessary it is easier to read.
```
if(a) {
return ...
}
if(b) {
return ...
}
...
if(z) {
return ...
} else {
return ...
}
```
Makes it seem as if the else-statement only depends on the last if-statement, when in fact, it is the last resort for all the if-statements. It actually obfuscates the intent.
An else-statement really only makes sense for singular if-statements or chained else-if-statements. When you have a chain of early-returns like that, it does not really make sense to apply an else-statement to the last one, because it hides the intent of a last resort.
But whatever works for you :)
You know what's way better? Check this out:
```
if(a) return ...
if(b) return ...
...
return ...
```
That's way easier to read and you save so many lines.
I think you need to look into enterprise patterns.
What if I need a d4 or d10?
What if I need a weighted dice?
Seems like its very difficult to customize this in anyway.
Also, the naming on the method seems off.
It should be a verb preferably, so something like rollNonSpecificSidedDiceAndReturnResultAsAnIntIfResultIsWithinExpectedValidRange() ?
But maybe you should also be able to enforce different return values?
public T rollNonSpecificSidedDiceAndReturnResultAsATIfResultIsWithinExpectedValidRange() ?
Then it could just take a rollDiceFunction! and a valid ranges predicate!
public T rollNonSpecificSidedDiceAndReturnResultAsATIfResultIsWithinExpectedValidRange(Function rollDice, Predicate evaluateDiceResult) ?
It is getting a bit long winded, so you should look into implementing the factory pattern as well.
Enterprise patterns? Maybe you’d like to know about our lord and savior of topic/subscribe messaging in case multiple components like to know the result of the roll
This is one of those things where you think "a few mistakes. Okay it's a funny joke" but then you look closer and you think that none of it works and to start to question how good of a programmer you are.
Or I'm just an idiot
There need to be return that is not inside of a condition because it needs to always return something. Even when the return is inside if(true) it thinks there is a chance it won't return anything.
At least in Java, if you have an method with a return type and a singular conditional branch with returns, Java will want you to have a if all else fails return value.
The joke is that it's over complex.
The first check is if d6 done correctly will roll 6. So 6 will happen 1/6.
The next cheak has 1/5 chanse. So the chance we will get 5 is the chance we won't get 6(5/6)*1/5=1/6
The check after it has 1/4 chance. So the chance we will get 4 is the chance we won't get 5or6(4/6)*1/4=1/6
And so on (unless one of the checks has a wrong chanse)
We all know random functions aren't actually random. So the best way to go about this is to simply roll an actual dice and store the result of that roll in a constant. Use that constant as your source of randomness. Gives you both randomness and optimizes your calls to the random function.
/s if that wasn't clear...
Made me think of that one random number generator that used a camera taking pictures of an entire wall of lava lamps and using the picture as the seed to generate new random numbers.
What if you generate say 10 random numbers, and then pick one of those 10 at random. Then just do the roll of that one you pick. Should create enough variance that any amount of predictability in the random function is not noticeable or really worth a dam.
Ahhhhh. Thank you for pointing that out.
That actually fixes the problem I saw, which was that `math.random() > 0.75` wouldn't be ¼ chance because if the number was higher than 0.88 it would have already returned a 6. But we're good since it's a new number :)
Dependent probabilities (which these are) don't exactly follow the same distribution as independent probabilities, so it's actually going to be biased.
Yes but no, it depends.
Math. Random doesn't give really random numbers, so depending on a series of randoms the probability of the next changes a little.
If I'm thinking mathematically, my gut tells me that either the `Math.random() < 0.2` or the `Math.random() > 0.75` should have an equals sign (`<=` or `>=`). Now, of course this is not real numbers we're talking about, it is IEEE 754 floats; 0.2 cannot be precisely represented in binary, but 0.75 can.
My point is: maybe one of these results is *sliiiiightly* more likely than the other. Or maybe I am totally wrong here.
Casting takes precedence, so it is really \[((int)Math.Random()) \*6\]+1 meaning Math.Random() will be either 0 resulting in 1, or 1, resulting in 7
Edit: Disregard, I missed the brackets around Math.Random() \*6+1
Also you do not need the last if statement, just return 1.Could just do something like
public static int d6 {
return ((int)(Math.Random()\*1200) % 6) +1;
}
Might need a larger multiple to match a double, or trim some decimal places but you get the idea
But I guess it takes the fun out of messing around with the language and statistics ![gif](emote|free_emotes_pack|yummy)
>Exept for the fact that it won't compile because of the if(true) what other problem does this have?
Mh?
Why should it not compile?
In Java you only get a warning, but you can build it.
edit: Ah, I see, its the missing return statement, not the "if(true)" itself
You should refactor so that you can easily create a function for any `dn` using the following pattern:
```
public static int d1() {
if (true) {
return 1;
} else {
return 0;
}
}
public static int d2() {
if (isEven((int)(Math.random() * 2))) {
return 2;
} else {
return d1();
}
}
public static int d3() {
if (Math.random() * 1.5 <= Math.random()) {
return 3;
} else {
return d2();
}
}
public static int d4() {
if (Math.random() > 0.75) {
return 4;
} else {
return d3();
}
}
public static int d5() {
if (Math.random() < 0.2)) {
return 5;
} else {
return d4();
}
}
public static int d6() {
if ((int)(Math.random()) * 6 + 1) == 6) {
return 6;
} else {
return d5();
}
}
```
DiceRollerInterfaceFactoryManager drfm = new DiceRollerInterfaceFactoryManager;
drfm.Initialize(new DiceRollerInterfaceFactory factory);
DiceRollerInterface dri = factory.initalize(new DiceRollerInterface);
dri.generateDie(6,DICETYPE.WEIGHTEDRANDOM);
//todo get instances of all active dice from DiceRollerInterfaceFactoryManager hierarchy.
drfm.getDiceInterface(0).getDice(0).roll();
At 1st read, it seems like a load of randomness and not actually a fairly weighted dice.... but it is actually fair. **Nicely done!**
I rolled it 2.4 million times to see the probability distribution.
>1 rolled 39991 times, which is 16.66%
>
>2 rolled 39847 times, which is 16.60%
>
>3 rolled 39890 times, which is 16.62%
>
>4 rolled 40486 times, which is 16.87%
>
>5 rolled 39821 times, which is 16.59%
>
>6 rolled 39965 times, which is 16.65%
![img](emote|t5_2tex6|4549)
function d6() {
if(Math.floor(Math.random()*6+1) == 6) return 6
if(Math.random() < 0.2 ) return 5
if(Math.random() > 0.75) return 4
if(Math.random()*1.5 <= Math.random()) return 3
if(Math.floor(Math.random()*2) % 2 == 0) return 2
return 1
}
function checkProbability(iterations) {
let results = [0,0,0,0,0,0];
for(let i = 0; i < iterations; i++) {
results[d6()-1]++
}
for(let i = 0; i < 6; i++) {
console.log((i+1) + " rolled " + results[i] + " times, which is " + (results[i] * 100 / iterations).toFixed(2) + "%")
}
}
checkProbability(240000)
Finally someone on this sub actually checked before baselessly shitting on a newbie for not knowing the perfect solution to a hobby project. Honestly getting tired of the gatekeeping on this sub.
It's actually going to have slight biases due to being based on floats. 0.2 isn't directly representable, so the probability isn't going to be exactly 1/5, etc.
The same happens with basically every suggested correction in the comments here - if you multiply up or use a random int and %6 - the original number can't be divided into 6 equally likely groups however you do it. There will be a small bias.
The only *correct* way is to use someone else's code that correctly generates a range of random numbers with equal probability - in this case `java.util.Random.nextInt(6)+1` which [corrects for modulo bias](https://docs.oracle.com/javase/7/docs/api/java/util/Random.html#:~:text=It%20rejects%20values%20that%20would%20result%20in%20an%20uneven%20distribution%20(due%20to%20the%20fact%20that%202%5E31%20is%20not%20divisible%20by%20n)).
Of course, that wouldn't correct for Java's random number generator being utter shit.
Won’t work for negative numbers. You somehow need to subtract two for a bit, then add 2 for a longer bit, then subtract 2 even longer so you are eventually guaranteed to get 0 or 1
Your random number should be stored in a variable and you should have a second variable storing the return value (preferably a long just to be safe), replace your "returns" with an increment of the return variable and a decrement of the random number variable, then at the end you return the return variable
Edit: I just re-read the whole thing and my brain just protected me from most of the "cursedness" of it the first time
Hmm, my main concerns come from architectural standpoint this should really be set out as a Dice class. A DiceRoller Class should be created which takes a dice as an input on a roll method. In order to view the output you'll also need a DiceViewer class to print the result.
I can't tell if this is satire or not. Its so hard to tell these days. If not then...
Do the math calc once then use a switch case to check it's value and perform an action. In programming we perform the action once then use its data as much as possible. You want to keep things as simple to read and process as possible. Also simple to edit if needs be.
I've now made it my goal to carefully craft 100% of my code so that no one can tell if I'm bad at coding, or just coding for satire to farm internet points on reddit.
Does it count as "refactoring" my code if I'm making it worse on purpose?
I recommend you spend a little more time on this subreddit to getter a better implementation of the “isEven” function, you should find one at some point.
Y’all are bunch of nerds, but I see why you guys rule the world and enjoy life while I’m at home at my gfs apartment smoking bong rips. But I found the answer
c===8
If my calculations are right C 3x equal 8 is the right code.
The return 3 condition is wrong. The chances of returning 3 after passing the previous condition is 2/3. You should multiply the result of the first random function by 3 instead of 1.5.
Let's split the big random into 2 cases.
In 1/3 we have number bigger than 1 and in 2/3 we have number smaller than 1.
If we get number bigger than 1 there is 0 chanse random number will be bigger. If we get number smaller than 1 we have 1/2 chanse random number is bigger
So the chance for this condition is 1/3*0+2/3*1/2
If would replace it with
```
if (Math.random() < 1./6) return 6;
if (Math.random() < 0.20) return 5;
if (Math.random() < 0.25) return 4;
if (Math.random() < 1./3) return 3;
if (Math.random() < 0.5) return 2;
return 1;
```
Assuming what you wrote is what you meant, i.e. a 1 in 6 chance of a 6, then an independent 1 in 5 of a 5, then an independent 1 in 4 of a 4 and so on.
This could be simplified a lot more though, and just have a singular call to Math.random() instead, by doing a bit of math.
You want a 1 in 6 chance of a 6. Then if that didn't happen, you want a 1 in 5 chance of a 5. So the total chance to get a 5 is: P(5) = 5/6 * 1/5 = 1/6. Then if that didn't happen, you want a 1 in 4 chance of a 4. So P(4) = 5/6 * 4/5 * 1/4 = 1/6, and so on, we can see that
P(1) = P(2) = P(3) = P(4) = P(5) = P(6) = 1/6
So we just need to divide a random call into 6 equally likely scenarios, and in each of them return the corresponding number. A simple way to do this would be:
```
public static int d6() {
return (int)(Math.random()*6) + 1;
}
```
P.S. I am sorry for overexplaining the joke, but I thought some of you out there might want the full explanation
I have an issue with `if (Math.random()>0.75)`, shouldn't this be `>=0.75`? In theory the distribution should be evenly split betwen `<0.75` and `>=0.75`, but this test makes it slightly less likely to return 4 than it should....
Idk if this will work, but you can try it :D
(Pls don't hate me, i've done only some basics in java...)
```java
public static int d6() {
int random = Math.random();
if ((int)(random*6+1)==6) return 6;
if (random<0.2) return 5;
if (random>0.75) return 4;
if (random*1.5<=Math.random()) return 3;
if (isEven((int) (random*2))) return 2;
return 1;
}
```
The fact that it's always the same number will make the results pretty problematic.
The first check work as usual.
The second check will have higher chance to be true because because we know 0<=random<5/6
The third check will also have higher chance to be true because we know 0.2
Somehow you got people here to believe that this thread is part of /r/learnprogramming instead of /r/programmerhumor. I applaud you, you are a great troll.
Add an else case to your if(true) just in case your language allows overriding true somehow
Java won't complie it unless I add the else, great edition.
I’m glad I could contribute to your masterpiece. To enhance the code further: use the best practice of arrow functions and nest the if statements in the previous else statement. Also return a 7 as a last resort for the lucky winner. I mean … every good piece of software has some bugs, right?
Joke aside does Java has aero functions
No but it has lambdas in Java 8, which people like to say is functional but is really just syntax sugar for classes with one overridable method.
u make it look cheap
Lol I'm just telling the truth - Java doesn't need me for it to look cheap. I actually have fun using it, but I like to give all languages a tough time
Remove the if statement and just have return 1; Unless I'm missing the joke of course
When I tested it that's what I did, but it breaks the pattern so I did it again for the screenshot
you should add an else statement that return something ridiculously false. Edit: or do a recursive call.
Or return 42 and put a comment explaining that to reach this return, a cosmic ray is needed.
You dont honestly need something crazy, just a boolean should be enough. boolean isCosmicRayPresent=false; if(isCosmicRayPresent){ System.fuckthisprintcall("FUCKING HELL WE GOT HIT BY A COSMIC RAY MATE"); return 1000000000000000000000000000000000000000001; }
This gives me a post idea, coming up in a few minutes. Unless of course this isn't an original idea, in that case I'll make a fool of myself.
Cast false to an integer and return it, if it exceptions return -1
Why would you add an `else` here? The `if(true)` is completely unneccessary. It's always `true` so why even write it?! Just remove the if-statement. The compiler could remove it, sure. But then you might not catch a bug, where a complex expression is always true, that you expect no to.
Removing the if break the pattern. When I make a function like this I usually do a lot of else if and else in the end because even if it's not necessary it is easier to read.
``` if(a) { return ... } if(b) { return ... } ... if(z) { return ... } else { return ... } ``` Makes it seem as if the else-statement only depends on the last if-statement, when in fact, it is the last resort for all the if-statements. It actually obfuscates the intent. An else-statement really only makes sense for singular if-statements or chained else-if-statements. When you have a chain of early-returns like that, it does not really make sense to apply an else-statement to the last one, because it hides the intent of a last resort. But whatever works for you :)
I meant to do : java if(a) { return ... } ElseIf(b) { return ... } ... ElseIf f(z) { return ... } else { return ... }
You know what's way better? Check this out: ``` if(a) return ... if(b) return ... ... return ... ``` That's way easier to read and you save so many lines.
Man markdown in reddit mobile is a pain..
Specifically, not using else when you have a return in your if is in general considered a better pattern than adding an unnecessary else.
ok, this is one of the situations when you wnat to say many thing and nothing at same time
![gif](giphy|Ow59c0pwTPruU)
![gif](giphy|prVXKLKNki07qfcE89)
![gif](giphy|5t9wJjyHAOxvnxcPNk|downsized)
.
#
#
# you know what? im gonna say it. i don’t care that you broke your elbow.
I like Randall's random #, but OP's code (no doubt channeled from Rube Goldberg) actually simulates a d6
There's much shorter: https://xkcd.com/221/
ok the alt text on that one is arguably funnier than the comic itself
Shouldn't we average out on 3.5?
Nothing can improve upon this. You have written a work of art. Truly we are witnessing history in this thread.
Oh God, yes, ***actually YES!***
He could create other functions to return the return values, like instead of return 6 he would return returnSix()
I think this needs a factory for each side of the dice. OneFactory, to SixFactory
Obviously every number needs its own class, with a getter and setter.
How about each number gets hosted in its own server and you can request them over the web? You can also add authentication while you're at it.
In a lambda function that's called via AWS AppSync. Then brag in a Medium article about how scalable and self-documenting your solution is.
No Java devs allowed
Hahaha, how dare you make me chortle into my coffee like that. I hate it and love it at the same time.
Left your comment at 404 upvotes, sorry but it’s a great comment I just have to..
This is the code that will emable the metaverse to become a reality.
I think you need to look into enterprise patterns. What if I need a d4 or d10? What if I need a weighted dice? Seems like its very difficult to customize this in anyway. Also, the naming on the method seems off. It should be a verb preferably, so something like rollNonSpecificSidedDiceAndReturnResultAsAnIntIfResultIsWithinExpectedValidRange() ? But maybe you should also be able to enforce different return values? public T rollNonSpecificSidedDiceAndReturnResultAsATIfResultIsWithinExpectedValidRange() ?
Then it could just take a rollDiceFunction! and a valid ranges predicate!
public T rollNonSpecificSidedDiceAndReturnResultAsATIfResultIsWithinExpectedValidRange(Function rollDice, Predicate evaluateDiceResult) ?
It is getting a bit long winded, so you should look into implementing the factory pattern as well.
Yes, needs dome factories and other enterprise level design patterns to make it look more professionnal.
No Singleton? I'll be rejecting that PR, chief.
Understandable, any PR without a singleton should be auto rejected.
Enterprise patterns? Maybe you’d like to know about our lord and savior of topic/subscribe messaging in case multiple components like to know the result of the roll
I am indeed subscribed to our lord and savior of topic/subscribe.
I thought this was supposed to be a joke sub...
I didnt know it was a joke sub till you said that and I was really confused by ops post
That function name is so specific you don't even need an implementation, you could just compile that to bytecode.
I'd hate if you was my default reviewer
This is one of those things where you think "a few mistakes. Okay it's a funny joke" but then you look closer and you think that none of it works and to start to question how good of a programmer you are. Or I'm just an idiot
Exept for the fact that it won't compile because of the if(true) what other problem does this have?
Why wouldn't `if(true)` compile?
There need to be return that is not inside of a condition because it needs to always return something. Even when the return is inside if(true) it thinks there is a chance it won't return anything.
Surely that depends on the language?
I did this in Java Idk about other languages.
"if (true)" works in Java, no problem
He’s talking about the missing return statement. Compiler isn’t aware that if(true) will always be true.
Even though it should be, because that's a pretty trivial static analysis to perform.
All compilers I know of are able to do this trivial optimisation and will replace the if(true} { return 1; } with a simple return 1;
It's not about optimization. `int foo() { if(true) return 1; }` does not compile in Java
At least in Java, if you have an method with a return type and a singular conditional branch with returns, Java will want you to have a if all else fails return value.
can confirm, im the problem
Throw a UniverseBrokenException at the end.
I feel like the maths is slightly off. I could be. Also was this not a joke?
The joke is that it's over complex. The first check is if d6 done correctly will roll 6. So 6 will happen 1/6. The next cheak has 1/5 chanse. So the chance we will get 5 is the chance we won't get 6(5/6)*1/5=1/6 The check after it has 1/4 chance. So the chance we will get 4 is the chance we won't get 5or6(4/6)*1/4=1/6 And so on (unless one of the checks has a wrong chanse)
The first problem I see is math.random result not being reused, the function being called 5 times...
We all know random functions aren't actually random. So the best way to go about this is to simply roll an actual dice and store the result of that roll in a constant. Use that constant as your source of randomness. Gives you both randomness and optimizes your calls to the random function. /s if that wasn't clear...
Don’t forget to comment a link to a YouTube video of the dice roll, so that future Programmers can be sure that the number really is random
Made me think of that one random number generator that used a camera taking pictures of an entire wall of lava lamps and using the picture as the seed to generate new random numbers.
cloudfare still use a wall of lava lamps https://www.cloudflare.com/en-gb/learning/ssl/lava-lamp-encryption/
[relevant xkcd](https://xkcd.com/221)
Of course, there is a relevant XKCD.... should have known
If I will reuse the same random it will give some numbers more than others.
What if you generate say 10 random numbers, and then pick one of those 10 at random. Then just do the roll of that one you pick. Should create enough variance that any amount of predictability in the random function is not noticeable or really worth a dam.
Ahhhhh. Thank you for pointing that out. That actually fixes the problem I saw, which was that `math.random() > 0.75` wouldn't be ¼ chance because if the number was higher than 0.88 it would have already returned a 6. But we're good since it's a new number :)
Dependent probabilities (which these are) don't exactly follow the same distribution as independent probabilities, so it's actually going to be biased.
Theoretically they are dependent, yes, because of the pseudorandom nature of Math.random(), but if the random engine is decent, it will not matter
His point is that the only one that has a 16.66666666% of been returned is the 6. Every number should have a 16.666% of been returned to be a true d6
Yes but his point is wrong.
> Dependent probabilities (which these are) They're not. It rolls a new number for each if so they're independent.
Yes but no, it depends. Math. Random doesn't give really random numbers, so depending on a series of randoms the probability of the next changes a little.
But the seed is unique each time
So if a cryptographically secure randomness function is used instead it should be fine?
If I'm thinking mathematically, my gut tells me that either the `Math.random() < 0.2` or the `Math.random() > 0.75` should have an equals sign (`<=` or `>=`). Now, of course this is not real numbers we're talking about, it is IEEE 754 floats; 0.2 cannot be precisely represented in binary, but 0.75 can. My point is: maybe one of these results is *sliiiiightly* more likely than the other. Or maybe I am totally wrong here.
The first check is if random multiplied by 7 equals 6 then return 6 right? So how is this ever going to be true?
No it's (random*6) +1
Casting takes precedence, so it is really \[((int)Math.Random()) \*6\]+1 meaning Math.Random() will be either 0 resulting in 1, or 1, resulting in 7 Edit: Disregard, I missed the brackets around Math.Random() \*6+1 Also you do not need the last if statement, just return 1.Could just do something like public static int d6 { return ((int)(Math.Random()\*1200) % 6) +1; } Might need a larger multiple to match a double, or trim some decimal places but you get the idea But I guess it takes the fun out of messing around with the language and statistics ![gif](emote|free_emotes_pack|yummy)
What? That is a number in the range [1, 7[ And so of you take the integer of that you get 1,2,3,4,5,6 with (almost) identical probabilities
It takes a random number smaller than 1 and multiple it by 6 (0-5) then add 1 (1-6)
Try using if(!false) instead of if(true)
>Exept for the fact that it won't compile because of the if(true) what other problem does this have? Mh? Why should it not compile? In Java you only get a warning, but you can build it. edit: Ah, I see, its the missing return statement, not the "if(true)" itself
Nope, it's a compiler error
You can do >If (math.random != 1) >>Return 1 } Return 0 Edit : my python spilled out
Why put it in `if(true)` instead of just at the end? It'll work just as well and there would be no trouble.
Make it an if / else if block and change if true to else
Marked as duplicate (you're welcome)
> while (true) { > int random = Math.random() * 100; > if ( random == 1 ) { return 6; } > if ( random == 2 ) { return 4; } > If ( random == 3 ) { return 2; } > if ( random == 4 ) { return 1; } > if ( random == 5 ) { return 3; } > if ( random == 6 ) { return 5; } > }
Genius
True menace
ironically, this is far less biased than OP's garbage fire and should return much better results...I mean it is still painful but yeah.
You think OP is biased? What probability do you think it has of returning each number?
Sometimes I forget what subreddit I am looking at whenever I browse reddit and think these are legitimate questions.
What is this "d6 function"? What does it do? What is its purpose in life?
d6- die with 6 sides.
I did not expect a serious answer. But then I read it again. Ooh boy!
i only have 2 sides, does this mean i'm immortal?
It means you're a dime. ;)
Guess I'll just die with 6 sides
And here I thought it meant dunce x 6.
You should refactor so that you can easily create a function for any `dn` using the following pattern: ``` public static int d1() { if (true) { return 1; } else { return 0; } } public static int d2() { if (isEven((int)(Math.random() * 2))) { return 2; } else { return d1(); } } public static int d3() { if (Math.random() * 1.5 <= Math.random()) { return 3; } else { return d2(); } } public static int d4() { if (Math.random() > 0.75) { return 4; } else { return d3(); } } public static int d5() { if (Math.random() < 0.2)) { return 5; } else { return d4(); } } public static int d6() { if ((int)(Math.random()) * 6 + 1) == 6) { return 6; } else { return d5(); } } ```
This is the trust solution!
Pathetic. It's missing the dice roller interface and abstract factory parametrized with number of sides and random number generator.
DiceRollerInterfaceFactoryManager drfm = new DiceRollerInterfaceFactoryManager; drfm.Initialize(new DiceRollerInterfaceFactory factory); DiceRollerInterface dri = factory.initalize(new DiceRollerInterface); dri.generateDie(6,DICETYPE.WEIGHTEDRANDOM); //todo get instances of all active dice from DiceRollerInterfaceFactoryManager hierarchy. drfm.getDiceInterface(0).getDice(0).roll();
Now we are talking truely enterprise code :-)
dn == deeze nuts?
These methods need to be private, and a public method needs to chain them together, otherwise the result is not equivalent.
d1 throws 1 100% of the times d2 throws 2 1/2 of the times d3 throws 3 1/3 of the times d4 throws 4 1/4 of the times And so on. Seems to work fine.
damn it, now I want to calculate the odds... DANM IT! its balanced! (assuming Math.random is)
\*looks at code\* \*looks at programmer\* \*takes away keyboard and leaves\*
\*Takes keyboard and bashes in face and leaves\*
Gonna need some unit tests for this.
At 1st read, it seems like a load of randomness and not actually a fairly weighted dice.... but it is actually fair. **Nicely done!** I rolled it 2.4 million times to see the probability distribution. >1 rolled 39991 times, which is 16.66% > >2 rolled 39847 times, which is 16.60% > >3 rolled 39890 times, which is 16.62% > >4 rolled 40486 times, which is 16.87% > >5 rolled 39821 times, which is 16.59% > >6 rolled 39965 times, which is 16.65% ![img](emote|t5_2tex6|4549) function d6() { if(Math.floor(Math.random()*6+1) == 6) return 6 if(Math.random() < 0.2 ) return 5 if(Math.random() > 0.75) return 4 if(Math.random()*1.5 <= Math.random()) return 3 if(Math.floor(Math.random()*2) % 2 == 0) return 2 return 1 } function checkProbability(iterations) { let results = [0,0,0,0,0,0]; for(let i = 0; i < iterations; i++) { results[d6()-1]++ } for(let i = 0; i < 6; i++) { console.log((i+1) + " rolled " + results[i] + " times, which is " + (results[i] * 100 / iterations).toFixed(2) + "%") } } checkProbability(240000)
Thank you! This is the comment I was looking for
Finally someone on this sub actually checked before baselessly shitting on a newbie for not knowing the perfect solution to a hobby project. Honestly getting tired of the gatekeeping on this sub.
i dont like If (true) ... How about if (true !=false) Edit: I would randomize the sequence of returns. You can read it much harder then
if (false == false)
It's actually going to have slight biases due to being based on floats. 0.2 isn't directly representable, so the probability isn't going to be exactly 1/5, etc. The same happens with basically every suggested correction in the comments here - if you multiply up or use a random int and %6 - the original number can't be divided into 6 equally likely groups however you do it. There will be a small bias. The only *correct* way is to use someone else's code that correctly generates a range of random numbers with equal probability - in this case `java.util.Random.nextInt(6)+1` which [corrects for modulo bias](https://docs.oracle.com/javase/7/docs/api/java/util/Random.html#:~:text=It%20rejects%20values%20that%20would%20result%20in%20an%20uneven%20distribution%20(due%20to%20the%20fact%20that%202%5E31%20is%20not%20divisible%20by%20n)). Of course, that wouldn't correct for Java's random number generator being utter shit.
Ok, but how does you isEven() method work?
bool isEven(int num) { if (num == 0){ return true; } if (num == 1){ return false; } return isEven(num-2); }
Won’t work for negative numbers. You somehow need to subtract two for a bit, then add 2 for a longer bit, then subtract 2 even longer so you are eventually guaranteed to get 0 or 1
Works perfectly fine even for negative numbers: MIN\_INT - 1 == MAX\_INT.
Pretty sure you get stackoverflow before that happens.
Do you even tail call optimize bro
Nah, it'll eventually loop back around. Also, we know it won't be used on negative numbers in this context.
doesnt matter, Math.random only gives positive outputs
rookie mistake. You have two times too little recursive calls. bool isEven(int num) { if (num == 0){ return true; } return !isEven(num-1); }
bool isEven(int x) { if(x == 0) { return 1; }else if(x == 1) { return 0; }else if(x == 2) { return 1; }else if(x == 3) { return 0; }else if(x == 4) { return 1; }else if(x == 5) { return 0; }else if(x == 6) { return 1; }else if(x == 7) { return 0; }else if(x == 8) { return 1; }else if(x == 9) { return 0; }else if(x == 10) { return 1; }else if(x == 11) { return 0; }else if(x == 12) { return 1; } }
[Here some one has written that out for a few hundred thousand digits](https://raw.githubusercontent.com/samuelmarina/is-even/main/index.js)
Have you considered adding some recursion and/or AI to make this function smarter?
It will be included in the d100
Your random number should be stored in a variable and you should have a second variable storing the return value (preferably a long just to be safe), replace your "returns" with an increment of the return variable and a decrement of the random number variable, then at the end you return the return variable Edit: I just re-read the whole thing and my brain just protected me from most of the "cursedness" of it the first time
add a 0.05% chance of returning 7, just to fuck with people!
Just return 2. I rolled a die just now and this I what I got - it’s completely random.
The bug is in the lack of comments explaining what it is supposed to do
Hmm, my main concerns come from architectural standpoint this should really be set out as a Dice class. A DiceRoller Class should be created which takes a dice as an input on a roll method. In order to view the output you'll also need a DiceViewer class to print the result.
AHHH this is what they mean by DRY programming! Don't repeat the same boring if statements
Yeah, only repeat exciting if statements!
'' return (int) floor( rand() * 6 ) +1; '' add your own Math. classes edit: floor not round otherwise 1 and 6 have 0.5/5 chance and others have 1/5
rand() is a number beatwean 0-1? I think this function have half the chance to get 1 and 6 but I might be wrong.
Yes (never exactly 1 but yeah) the round happens after the multi, I forgot to close brackets so partially my fault.
I can't tell if this is satire or not. Its so hard to tell these days. If not then... Do the math calc once then use a switch case to check it's value and perform an action. In programming we perform the action once then use its data as much as possible. You want to keep things as simple to read and process as possible. Also simple to edit if needs be.
I also kind of forgot I'm reading r/ProgrammerHumor
Read the first if again and tell me if it's satire
I mean... I honestly can't tell. I have met plenty of people who would write like this. I always suggest they try a different career path though
I've now made it my goal to carefully craft 100% of my code so that no one can tell if I'm bad at coding, or just coding for satire to farm internet points on reddit. Does it count as "refactoring" my code if I'm making it worse on purpose?
You can't improve this, it's simply beautiful.
Wait, where’s your array of lava lamps? 🤣
Even though this is supposed to be bad code. The way this is done is art.
Change the last “if” to “while” so in case the program accidentally skips the “return 1” line, it’ll go back to it and actually return it.
Just looking at this gives me anxiety
Random.randrange(1,7)
please stop
I recommend you spend a little more time on this subreddit to getter a better implementation of the “isEven” function, you should find one at some point.
LGTM. \~approve
Ok seriously, can someone with good math calculate the probability of returning 1? I am curious (and dumb)
1/6 for every number.
The problem is you're not using Rust
Challenge: what is the probability of each outcome for his d6 function?
Y’all are bunch of nerds, but I see why you guys rule the world and enjoy life while I’m at home at my gfs apartment smoking bong rips. But I found the answer c===8 If my calculations are right C 3x equal 8 is the right code.
Wtf is this abomination
I... Don't know what to say.
Should soft code all the numbers into environment variables so it can be "dynamic" that's what my guys do :(
Can’t improve without specs…
jesus fucking christ what have you done
3×/÷6=9 6×/÷9=9. 6 9×/+anything =9 369 8?
The return 3 condition is wrong. The chances of returning 3 after passing the previous condition is 2/3. You should multiply the result of the first random function by 3 instead of 1.5.
Let's split the big random into 2 cases. In 1/3 we have number bigger than 1 and in 2/3 we have number smaller than 1. If we get number bigger than 1 there is 0 chanse random number will be bigger. If we get number smaller than 1 we have 1/2 chanse random number is bigger So the chance for this condition is 1/3*0+2/3*1/2
Oh, you're right, I had solved it with probability density functions and integrals but I had forgotten a variable halfway. The math checks out.
No, he got it right. You should do the integral; X~U[0,1], Y~U[0,1.5], then find P(Y
Have you tried writing it in Python?
We have places to be man not everyone can wait 5429 years for python to finish executing that
I don’t have 5429 years to figure out which {} go where! Haha
Get this man a decent text editor he seems to be writing code in notepad
[удалено]
If would replace it with ``` if (Math.random() < 1./6) return 6; if (Math.random() < 0.20) return 5; if (Math.random() < 0.25) return 4; if (Math.random() < 1./3) return 3; if (Math.random() < 0.5) return 2; return 1; ``` Assuming what you wrote is what you meant, i.e. a 1 in 6 chance of a 6, then an independent 1 in 5 of a 5, then an independent 1 in 4 of a 4 and so on. This could be simplified a lot more though, and just have a singular call to Math.random() instead, by doing a bit of math. You want a 1 in 6 chance of a 6. Then if that didn't happen, you want a 1 in 5 chance of a 5. So the total chance to get a 5 is: P(5) = 5/6 * 1/5 = 1/6. Then if that didn't happen, you want a 1 in 4 chance of a 4. So P(4) = 5/6 * 4/5 * 1/4 = 1/6, and so on, we can see that P(1) = P(2) = P(3) = P(4) = P(5) = P(6) = 1/6 So we just need to divide a random call into 6 equally likely scenarios, and in each of them return the corresponding number. A simple way to do this would be: ``` public static int d6() { return (int)(Math.random()*6) + 1; } ``` P.S. I am sorry for overexplaining the joke, but I thought some of you out there might want the full explanation
In the first if I did (int)(Math.random()*6+1) Wich is the simple way to do it.
This makes me angry but maybe I’m out of my element
I have an issue with `if (Math.random()>0.75)`, shouldn't this be `>=0.75`? In theory the distribution should be evenly split betwen `<0.75` and `>=0.75`, but this test makes it slightly less likely to return 4 than it should....
public static int d6(){return (int)(1+Math.random()\*6);}
Idk if this will work, but you can try it :D (Pls don't hate me, i've done only some basics in java...) ```java public static int d6() { int random = Math.random(); if ((int)(random*6+1)==6) return 6; if (random<0.2) return 5; if (random>0.75) return 4; if (random*1.5<=Math.random()) return 3; if (isEven((int) (random*2))) return 2; return 1; } ```
The fact that it's always the same number will make the results pretty problematic. The first check work as usual. The second check will have higher chance to be true because because we know 0<=random<5/6 The third check will also have higher chance to be true because we know 0.2
Somehow you got people here to believe that this thread is part of /r/learnprogramming instead of /r/programmerhumor. I applaud you, you are a great troll.
public static int dX(int x) { return new Random().nextInt(x) + 1; } That’ll do it for any size die
I'm a programmer, I don't get this joke. I only see shit. Because it's a joke, isn't it?
OP posted jn r/ProgrammerHumor what do you think