문제

I'm working on a small programming assignment for my Algorithms class in JAVA.

I'm trying to figure out how to implement my while loop correctly, but I'm having no luck.

I have this program set up to where the method I created puts an edge on 1, to where a 1 is returned more likely than a 0 would be. I'm trying to get the while loop to run 10,000 times and have two counters, countZeros and countOnes to see how many of each showed up out of the 10,000 times.

public class BiasedRandom {
  public static void main(String[] args) {
    int countZeros = 0, countOnes = 0;
    double value = randomNumberGen(1); 

    // while loop here
    // while(value < 10000)
  }

  public static double randomNumberGen(double n) {
    double r = Math.random();
    double p = 0.6;
    if (r > p)
      return 0;
    else
      return 1;
  }
}
도움이 되었습니까?

해결책

public static void main(String[] args) {
    int countZeros = 0, countOnes = 0;

    for (int i=0; i<10000; i++) {
        int value = randomNumberGen();
        if (value==0)
            countZeros++;
        else if (value==1)
            countOnes++;
        else
            throw new RuntimeException("Bad number");
    }

    System.out.println("0: "+countZeros);
    System.out.println("1: "+countOnes);
}

public static int randomNumberGen() {
    double r = Math.random();
    double p = 0.6;
    if (r > p)
        return 0;
    else
        return 1;
}

I used the classical for loop format for the loop, and changed the return type and parameters of randomNumberGen() to match what is done in the method.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top