Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.util.*;
- import java.lang.*;
- class RNG {
- public static int getRandomNumber(int min, int max) {//random number generator
- Random rand = new Random();
- return rand.nextInt((max - min) + 1) + min;
- }
- }
- public class Probability {
- public static void main(String[] args) {
- int silver = 0, golden = 0, runs = 1000000;
- String result;
- for (int i = 0; i < runs; i++) {//a million runs just to be more consistent
- result = testRun();
- if (result == "Nothing") {
- i--;//we ignore entirely runs when we draw silver from the first box
- continue;
- } else if (result == "Silver") {//if the second draw is silver
- silver++;
- } else if (result == "Golden")//if the second draw is gold
- golden++;
- }
- System.out.println("Results from " + runs + " simulation runs :");
- System.out.println("Golden:" + golden);
- System.out.println("Silver:" + silver);
- }
- static String testRun() {
- List<Box> list = new ArrayList<Box>();
- Box box1 = new Box("Golden", "Golden");
- Box box2 = new Box("Silver", "Golden"); //order doesn't matter, we pick at random
- Box box3 = new Box("Silver", "Silver");
- list.add(box1);
- list.add(box2);
- list.add(box3);
- int boxChosen = RNG.getRandomNumber(0, 2); //boxes 0, 1, 2
- String result = list.get(boxChosen).returnBall();
- String result2;
- if (result == "Golden") {//first box draw is Golden
- result2 = list.get(boxChosen).returnBall();//we draw another one
- return result2;//return the result of the second draw
- }
- else {
- return "Nothing"; //this means first result was not Silver
- }
- }
- }
- class Box {
- int isEmpty = 2;
- List<String> list = new ArrayList<>();
- public Box(String box1, String box2) {
- list.add(box1);
- list.add(box2);
- }
- public String returnBall() {
- if (isEmpty == 0) {
- return "Empty Ball !";
- } else if (isEmpty == 1) {
- String result = list.get(0);
- list.remove(0);
- isEmpty--;
- return result;
- } else {
- int randomNum = RNG.getRandomNumber(0, 1);
- String result = list.get(randomNum);
- list.remove(result);
- isEmpty--;
- return result;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement