Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (498)
Games in Android Showcase (115)
games submitted by our members
Games in WIP (562)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1] 2
  ignore  |  Print  
  Generating three random booleans  (Read 3022 times)
0 Members and 1 Guest are viewing this topic.
Offline dagz

Junior Newbie





« Posted 2013-04-10 22:27:39 »

Hello everyone,

So i am working on a simple game to play in the java console where you can choose between three cups This is my first program ive written myself. the only problem I am having is making sure two of the cups return false while one is true. Some ideas would be greatly appreciated ballIncup() assigns a true or false variable but it keep returning true when I test it out.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
import java.util.Random;
import java.util.Scanner;

public class pickAcup {
   static Scanner input = new Scanner(System.in);
   static Random ball = new Random();
   static String name;
   static int turn = 1;
   static boolean cup1, cup2, cup3 = false;
   static String choice;
   
   public static void main(String[] args){
      intro();
      ballIncup();
      playerChoice();
   
   }
   
    public static void intro(){
      // Introduction Takes in player name and welcomes them to the game
     System.out.println("Welcome to pick a cup please enter your name");
      name= input.nextLine();
      System.out.println("Hello " + name);
     
   }

    public static void ballIncup(){
       cup1 = ball.nextBoolean();
       cup2 = ball.nextBoolean();
       cup3 = ball.nextBoolean();
       if(cup1 == false && cup2 == false){
          cup3 = true;
       }else if(cup1 == false && cup3 == false){
          cup2 = true;
       }else if(cup2 == false && cup3 == false){
          cup1 = true;
       }
    }
   
    public static void playerChoice(){
       System.out.println("Please pick cup 1, cup 2, or cup 3" + name);
       choice = input.nextLine();
       if(choice.equals("cup 1")){
          if(cup1 = true){
             System.out.println("You win!");
          }else if(cup1 = false){
             System.out.println("Please pick again");
          }
         
       }
    }
}
Offline ctomni231

JGO Wizard


Medals: 99
Projects: 1
Exp: 7 years


Not a glitch. Just have a lil' pixelexia...


« Reply #1 - Posted 2013-04-10 22:44:18 »

Well, since your learning how to code, I'll bail you out of this one with a solution Smiley

Instead of this...

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
 public static void ballIncup(){
       cup1 = ball.nextBoolean();
       cup2 = ball.nextBoolean();
       cup3 = ball.nextBoolean();
       if(cup1 == false && cup2 == false){
          cup3 = true;
       }else if(cup1 == false && cup3 == false){
          cup2 = true;
       }else if(cup2 == false && cup3 == false){
          cup1 = true;
       }
    }


Try this...
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
 public static void ballIncup(){
       int temp = ball.nextInt(3);
       cup1 = false;
       cup2 = false;
       cup3 = false;
       if(temp == 0){
          cup3 = true;
       }else if(temp == 1){
          cup2 = true;
       }else if(temp == 2){
          cup1 = true;
       }
    }


oh and one more thing...

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
public static void playerChoice(){
       System.out.println("Please pick cup 1, cup 2, or cup 3" + name);
       choice = input.nextLine();
       if(choice.equals("cup 1")){
-         if(cup1 = true){
+        if(cup1 == true){
             System.out.println("You win!");
-         }else if(cup1 = false){
+         }else if(cup1 == false){
             System.out.println("Please pick again");
          }
         
       }
    }


Be careful not to mix up the assignment operator (=) with the equality operator (==). The code is still, incomplete, but I'll leave you to figure out the rest.

Offline brollysan

Junior Member


Medals: 1



« Reply #2 - Posted 2013-04-10 23:24:24 »

Pick a random number [0, int_max].

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
u = random...
v = random...
w = random..

a = int[] {u,v,w}
b = boolean[] {false, false, false}

m = min(u,min(v,w))
if (a[0] == m ) {b[0] = true};
if (a[1] == m) { b[1] = true};
if (a[2] == m) { b[2] = true};




Always gives you 1 true 2 false at random, unless you roll the same number at the same time, once in a blue moon.
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline ReBirth
« Reply #3 - Posted 2013-04-11 02:06:06 »

No, there is even chance three of randoms produce same number Grin ctonmi231's solution is the best.

Offline SHC
« Reply #4 - Posted 2013-04-11 02:15:58 »

Use this.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
/**
 * Returns a random real number between 0 and x. The number is always
 * smaller than x.
 *
 * @param x The maximum range
 * @return A random real number
 */

public static int random(int x){
    return (int) (Math.floor(Math.random() * x));
}

Then in code

1  
2  
3  
boolean cup1 = (random(1)==0) ? true : false;
boolean cup2 = (random(1)==0) ? true : false;
boolean cup3 = (random(1)==0) ? true : false;


Here's the Util class I use

https://code.google.com/p/game-engine-for-java/source/browse/src/com/gej/util/GUtil.java

Offline SimonH
« Reply #5 - Posted 2013-04-11 02:18:38 »

How about;
1  
2  
3  
4  
double rnd=Math.random();
boolean b1=(rnd<=(1f/3));
boolean b2=(rnd>(1f/3) && rnd<=(2f/3));
boolean b3=(rnd>(2f/3));

People make games and games make people
Offline dagz

Junior Newbie





« Reply #6 - Posted 2013-04-11 03:01:15 »

Thank you guys so much for the help I got it working
Offline brollysan

Junior Member


Medals: 1



« Reply #7 - Posted 2013-04-11 10:55:30 »

Nextint isn't magic, it can roll the same numbers 3 times in a row, it just asks for the next integer in the sequence that is built pseudo-randomly., the sequence can contain 3 same numbers in a row.
Offline Grunnt

JGO Wizard


Medals: 69
Projects: 8
Exp: 5 years


Complex != complicated


« Reply #8 - Posted 2013-04-11 11:07:36 »

Funny thing is that humans tend to be terribly bad at judging what is random and what is not.

Which of the following dot distributions is random?




Most people guess the top one, but instead it is the bottom one. We're just too good at recognizing patterns I guess. The pictures are from: this article, which is a nice read.

Offline ReBirth
« Reply #9 - Posted 2013-04-11 11:20:45 »

I picked bottom, whose the white area/free space's deviation looks low.

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline delt0r

JGO Knight


Medals: 27
Exp: 18 years


Computers can do that?


« Reply #10 - Posted 2013-04-12 14:19:19 »

Also this is a good example why sometimes we want to use the top "random" case because it will give better math properties on some problems. For example stochastic integration.

Now we have thoroughly confused the new guy... Our work is done.

I have no special talents. I am only passionately curious.--Albert Einstein
Offline Longor1996
« Reply #11 - Posted 2013-04-12 15:24:52 »

How about this?
1  
boolean bool = (System.nanoTime() & 0b1) == 0;

That should be pretty random, i think...

- Longor1996

Sorry for my bad English! That's because i am from Germany.
Offline delt0r

JGO Knight


Medals: 27
Exp: 18 years


Computers can do that?


« Reply #12 - Posted 2013-04-12 15:56:05 »

That is an awful random boolean. There is no guarantee on the resolution of the timer. They are never accurate to the nanosecond. So you have good odds that 2 calls in a row would give the same result. In fact that would almost always happen.

Seriously what is wrong with random.nextBoolean()? 

I have no special talents. I am only passionately curious.--Albert Einstein
Offline Riven
« League of Dukes »

JGO Overlord


Medals: 799
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #13 - Posted 2013-04-12 16:50:02 »

Seriously what is wrong with random.nextBoolean()?  

The problem that is posted here is slightly different. There is 1 ball and 3 cups. This whole fiddling with booleans is extremely error prone and leads to many if-else chains/trees. This very thread is full of blatantly wrong suggestions.

What we need is:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
    private final int cupCount = 3;
    private int ballFilledCupIndex = -1;

    public static void ballIncup(){
       ballFilledCupIndex = random.nextInt(cupCount);
    }
   
    public static void playerChoice(){
       System.out.println("Please pick cup 1, cup 2, or cup 3, " + name);
       choice = input.nextLine();
       if(choice.equals("cup "+(ballFilledCupIndex+1))){
          System.out.println("You win!");
       }
       else
          System.out.println("Please pick again");
       }
    }

and all boolean fields should be removed.

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Offline ReBirth
« Reply #14 - Posted 2013-04-13 12:15:06 »

You all did it wrong. See how the lord did it? KNEEL!

Offline delt0r

JGO Knight


Medals: 27
Exp: 18 years


Computers can do that?


« Reply #15 - Posted 2013-04-13 14:25:39 »

riven is right of course. I should also at least read the first post.

I have no special talents. I am only passionately curious.--Albert Einstein
Offline xsvenson
« Reply #16 - Posted 2013-04-13 21:58:37 »

Well there was nothing wrong with the answers per se. The difference is that everyone answered the question while Riven provided the solution for the problem.

“The First Rule of Program Optimization: Don't do it. The Second Rule of Program Optimization (for experts only!): Don't do it yet.” - Michael A. Jackson
Offline Riven
« League of Dukes »

JGO Overlord


Medals: 799
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #17 - Posted 2013-04-13 22:11:18 »

Well there was nothing wrong with the answers per se.
O RLY...


Pick a random number [0, int_max].

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
u = random...
v = random...
w = random..

a = int[] {u,v,w}
b = boolean[] {false, false, false}

m = min(u,min(v,w))
if (a[0] == m ) {b[0] = true};
if (a[1] == m) { b[1] = true};
if (a[2] == m) { b[2] = true};




Always gives you 1 true 2 false at random, unless you roll the same number at the same time, once in a blue moon.

Will lead to potentially multiple 'true' values.

Use this.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
/**
 * Returns a random real number between 0 and x. The number is always
 * smaller than x.
 *
 * @param x The maximum range
 * @return A random real number
 */

public static int random(int x){
    return (int) (Math.floor(Math.random() * x));
}

Then in code

1  
2  
3  
boolean cup1 = (random(1)==0) ? true : false;
boolean cup2 = (random(1)==0) ? true : false;
boolean cup3 = (random(1)==0) ? true : false;


Here's the Util class I use

https://code.google.com/p/game-engine-for-java/source/browse/src/com/gej/util/GUtil.java
Will lead to guaranteed multiple 'true' values, as random(1) always returns 0.

How about this?
1  
boolean bool = (System.nanoTime() & 0b1) == 0;

That should be pretty random, i think...

- Longor1996
Horrible entrophy (zero bits), as explained by delt0r - and not answering any question.


This thread is better left unseen.

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Offline ctomni231

JGO Wizard


Medals: 99
Projects: 1
Exp: 7 years


Not a glitch. Just have a lil' pixelexia...


« Reply #18 - Posted 2013-04-13 22:22:09 »

Whew, well the OP got it working way before they got down here, hopefully. I just hope other people would be able to figure out the right solution through trial and error Tongue...

Offline xsvenson
« Reply #19 - Posted 2013-04-13 22:55:21 »

I'm sorry, mr Riven, I didn't mean the code. I meant the target of the answers.
On the code side, You are of course, right.

“The First Rule of Program Optimization: Don't do it. The Second Rule of Program Optimization (for experts only!): Don't do it yet.” - Michael A. Jackson
Offline ReBirth
« Reply #20 - Posted 2013-04-14 02:36:33 »

Actually Riven provide solution on smaller context, the game, while rest of you provide a learn how to make 1 true 2 false which MAYBE he will need on his later job programming rocket controller or whatever. It's about giving fish or teaching to fish.

Offline brollysan

Junior Member


Medals: 1



« Reply #21 - Posted 2013-04-15 17:01:44 »

Seriously what is wrong with random.nextBoolean()?  

The problem that is posted here is ......

How was my suggestion wrong?
Offline Jimmt
« League of Dukes »

JGO Kernel


Medals: 131
Projects: 4
Exp: 3 years



« Reply #22 - Posted 2013-04-15 17:47:58 »

Like Riven said, there is a chance that there will be multiple true values, when the OP specifically requested 1 true and 2 false. You can't exactly have 2 cups that are "true", that's not how the game works. Let's look at what you posted:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
u = random...
v = random...
w = random..

a = int[] {u,v,w}
b = boolean[] {false, false, false}

m = min(u,min(v,w))
if (a[0] == m ) {b[0] = true};
if (a[1] == m) { b[1] = true};
if (a[2] == m) { b[2] = true};

If two of the numbers are the same, there will be 2 true values. If 3, then 3 true values. -other stuff edited out due to math problems-
Offline delt0r

JGO Knight


Medals: 27
Exp: 18 years


Computers can do that?


« Reply #23 - Posted 2013-04-15 18:08:05 »

The math is wrong. You would get duplicates a little bit more than 1% of the time. Given that you have a duplicate it will be the smallest number just a little bit more than half the time. So a total error of more than one true of a little over .5%

The little over are for 3 way ties.

And still this thread refuses to die... Its a Zombie. Eating unsuspecting brains for breakfast.

[edit] This is assuming as in the previous post that the ints are chosen between 0 and 99 (aka nextInt(100))

I have no special talents. I am only passionately curious.--Albert Einstein
Offline brollysan

Junior Member


Medals: 1



« Reply #24 - Posted 2013-04-16 22:13:01 »

Like Riven said, there is a chance that there will be multiple true values, when the OP specifically requested 1 true and 2 false. You can't exactly have 2 cups that are "true", that's not how the game works. Let's look at what you posted:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
u = random...
v = random...
w = random..

a = int[] {u,v,w}
b = boolean[] {false, false, false}

m = min(u,min(v,w))
if (a[0] == m ) {b[0] = true};
if (a[1] == m) { b[1] = true};
if (a[2] == m) { b[2] = true};

If two of the numbers are the same, there will be 2 true values. If 3, then 3 true values. -other stuff edited out due to math problems-

The likelihood of two numbers being the same is a factor of 1/Integer.MAX_VALUE. This is no different than rivens suggestion in terms of getting the same number twice. NextInt is not magic.
Offline Roquen
« Reply #25 - Posted 2013-04-16 22:26:58 »

Wrong..try again.
Offline theagentd
« Reply #26 - Posted 2013-04-16 22:34:38 »

The likelihood of two numbers being the same is a factor of 1/Integer.MAX_VALUE. This is no different than rivens suggestion in terms of getting the same number twice. NextInt is not magic.
It can fail so it's not a good solution. Unlikely != impossible. Try doing some multithreading.

Seriously, how is that code superior to simply
1  
2  
3  
4  
5  
6  
Random random = new Random();

...

Arrays.fill(a, false); //Clear to false
a[random.nextInt(3)] = true; //Set one random element to true

Myomyomyo.
Offline brollysan

Junior Member


Medals: 1



« Reply #27 - Posted 2013-04-16 22:48:41 »

I never said it was superior but everyone is dragging down everyone else besides Riven here. Granted he is well-versed in Java (I have seen some of his posts, especially the green-thread supports this claim) his answer is just as fallible as ours (mine) even if the code for it is shorter (because of not converting to booleans). He is using the java library, so am I , his NextInt call will be just as likely to reproduce the same number twice as mine is.

But my mistake for expecting polite and reasonable behavior from the members here, I am too used with sites like SO. Instead of constructive criticism (like pointing out why my answer is wrong, providing proof for it failing 1% of the time) that would better the community we turn to condescension.
Offline Riven
« League of Dukes »

JGO Overlord


Medals: 799
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #28 - Posted 2013-04-17 00:05:27 »

I think there is a misunderstanding here. It isn't about whether random.nextInt(n) returns the same number twice, it's perfectly fine if 1 ball is under the same cup in a few games in a row. It's not fine when the program tells you that the ball is in cup 1 and 3 in the very same game.

He is using the java library, so am I , his NextInt call will be just as likely to reproduce the same number twice as mine is.
The difference is that the way your code calls nextInt(...) results in the possibility that two or three booleans fields are set to true, which is an incorrect state. My code will always leave exactly 1 ball in 3 cups, all the time, without any chance of an incorrect state. That we're both using nextInt(n) and your implementation potentially causes the program to reach an invalid state, doesn't mean that my code suffers from the same flaw.

But my mistake for expecting polite and reasonable behavior from the members here, I am too used with sites like SO. Instead of constructive criticism (like pointing out why my answer is wrong, providing proof for it failing 1% of the time) that would better the community we turn to condescension.
Sigh. Oh well, here's is the proof, not by obscure reasoning, but simply by bruteforcing your algorithm, and counting the number of times it reaches an invalid state:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
         Random r = new Random(123L);

         int[] ballHistogram = new int[4];

         for (int i = 0; i < 1000 * 1000; i++) {
            int u = r.nextInt(3);
            int v = r.nextInt(3);
            int w = r.nextInt(3);

            int[] a = new int[] {u, v, w};
            boolean[] b = new boolean[] {false, false, false};

            int m = Math.min(u, Math.min(v, w));
            if (a[0] == m) {
               b[0] = true;
            }
            if (a[1] == m) {
               b[1] = true;
            }
            if (a[2] == m) {
               b[2] = true;
            }

            // verify internal state
           int ballCount = 0;
            if (b[0]) {
               ballCount++;
            }
            if (b[1]) {
               ballCount++;
            }
            if (b[2]) {
               ballCount++;
            }
            ballHistogram[ballCount]++;
         }

         System.out.println("total games: " + (ballHistogram[0] + ballHistogram[1] + ballHistogram[2] + ballHistogram[3]));
         for (int i = 0; i < ballHistogram.length; i++) {
            System.out.println("games with " + i + " balls in 3 cups: " + ballHistogram[i]);
         }


Output:
1  
2  
3  
4  
5  
total games: 1000000
games with 0 balls in 3 cups: 0
games with 1 balls in 3 cups: 555142
games with 2 balls in 3 cups: 333727
games with 3 balls in 3 cups: 111131

In short: over 44% of the games end up in an invalid state, a far cry from 1/Integer.MAX_VALUE, or the proposed 0.5% and 1.0%.

I hope this elaborate explaination brings JGO back to 'StackOverflow quality' Kiss

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Offline theagentd
« Reply #29 - Posted 2013-04-17 00:31:40 »

Sigh. The sad part is that this whole thread could have been avoided if someone had just reformulated the question from "I need to set 1 boolean to true and 2 to false randomly" to "I need to place a ball in a random cup" instead...

Myomyomyo.
Pages: [1] 2
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

BurntPizza (28 views)
2014-09-21 02:42:18

BurntPizza (18 views)
2014-09-21 01:30:30

moogie (20 views)
2014-09-21 00:26:15

UprightPath (27 views)
2014-09-20 20:14:06

BurntPizza (29 views)
2014-09-19 03:14:18

Dwinin (46 views)
2014-09-12 09:08:26

Norakomi (74 views)
2014-09-10 13:57:51

TehJavaDev (101 views)
2014-09-10 06:39:09

Tekkerue (50 views)
2014-09-09 02:24:56

mitcheeb (71 views)
2014-09-08 06:06:29
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!