Бросаем два кубика, пока dice1 не станет больше, чем dice2, два раза в java - PullRequest
0 голосов
/ 17 октября 2018

Вывод кубиков рандомизирован, и я создал для этого функцию.Я хочу записать, сколько «попыток» потребовалось, чтобы одна игральная кость была больше, чем игральная кость 2, два раза подряд.Поэтому, когда он будет больше двух раз подряд, я бы хотел, чтобы он напечатал («потребовалось» + trials + «чтобы d1 был больше d2 два раза подряд»).Пока у меня есть это, но я застрял:

public static int Dice() {
  return (int)(Math.random() * 6.0) + 1;
}

public static void main(String[] args) {

              int d1 = Dice();
              int d2 = Dice();
              int trials = 0;

              for (int i = 0; i < 100000; i++) {
               if (t1 > t2) {
               trials++;
               if (t1 > t2) {
                trials++ 
               }
              }
             }

            System.out.println(trials);
    } 
} 

Ответы [ 5 ]

0 голосов
/ 17 октября 2018

Вот что я придумал

import java.util.Random;

Публичный класс main {

public static int Dice() {
    return (int) (Math.random() * 6.0) + 1;
}

public static void main(String[] args) {
    Random rand = new Random();


    int trials = 0;
    int twoTimes = 0;

    do {
        int d1 = rand.nextInt(25) + 1;
        int d2 = rand.nextInt(25) + 1;
        trials++;
        if (d1 > d2) {
            twoTimes++;
            System.out.printf("%s time greater\nd1 was " + d1 + "\nd2 was " + d2 + "\n-------\n", twoTimes);
        }
    }

    while (twoTimes != 2);
    System.out.printf("\nIt took %s times", trials);

}

}

0 голосов
/ 17 октября 2018

Вы можете легко выполнить это в основной функции, если нет необходимости использовать внешнюю функцию для возврата случайного числа.строка

Пример вывода

0 голосов
/ 17 октября 2018

Я бы пошел с

public static int Dice() {
  return (int)(Math.random() * 6.0) + 1;
}

public static void main(String[] args) {
  int trials = 0;
  int count = 0;

  while (count < 2) {
    int d1 = Dice();
    int d2 = Dice();

    if (d1 > d2) {
      ++count;
    } else {
      count = 0;
    }

    ++trials;
  }

  println("It took " + trials + " trials for d1 to be larger than d2 " + count + " times in a row.")
}
0 голосов
/ 17 октября 2018

Добро пожаловать на ТАК!Это должно работать.Смотрите комментарии о некоторых вещах, которые вы делали неправильно, и некоторых объяснениях.

public static int Dice() {
  return (int)(Math.random() * 6.0) + 1;
}

public static void main(String[] args) {

  // initialize variables to be updated in the loop
  int trials = 0;
  Boolean lastTimeD1WasGreater = false;

  for (int i = 0; i < 100000; i++) {
    // always increment the counter!
    trials++;

    // you had the wrong variable names here.
    // also they must be INSIDE the loop or else they would always come out the same
    int d1 = Dice();
    int d2 = Dice();

    if (d1 > d2) {
      if (lastTimeD1WasGreater) {
        // if it was greater both last time and this time then we're done!
        System.out.println("it took " + trials + " trials.");
        break;
      } else {
        // otherwise set this variable so we can be on the lookout next time.
        lastTimeD1WasGreater = true;
      }
    } else {
      // d1 was not greater, so we'll start looking for a pair in the next loop.
      lastTimeD1WasGreater = false;
    }
  }
}
0 голосов
/ 17 октября 2018

Сделайте что-то подобное (обработайте следующее как псевдокод):

public static int[] Dice() {
    int[] diceThrownTwoTimes = new int[2];
    diceThrownTwoTimes[0] = (int)(Math.random() * 6.0) + 1;
    diceThrownTwoTimes[1] = (int)(Math.random() * 6.0) + 1;
    return diceThrownTwoTimes;
} 

public static void main(String[] args) {
    int trials = 0;

    for (int i = 0; i < 100000; i++) {
        int[] d1 = Dice();
        int[] d2 = Dice();
        if (d1[0] > d2[0] && d1[1] > d2[1]) {
            trials++;
        }
    }
    System.out.println(trials);
}

РЕДАКТИРОВАТЬ:

Чтобы получить попытки, до которых значение dice1 больше значения dice2 два раза подрядможно сделать следующее:

public static int[] Dice() {
    int[] diceThrownTwoTimes = new int[2];
    diceThrownTwoTimes[0] = (int)(Math.random() * 6.0) + 1;
    diceThrownTwoTimes[1] = (int)(Math.random() * 6.0) + 1;
    return diceThrownTwoTimes;
} 

public static void main(String[] args) {
    int trials = 0;

    for (int i = 0; i < 100000; i++) {
        int[] d1 = Dice();
        int[] d2 = Dice();
        if (d1[0] > d2[0] && d1[1] > d2[1]) {
            break;
        }else{
            trials++;
        }
    }
    System.out.println(trials);
}
...