带有if-else的随机票,用于有偏见的彩票

时间:2017-10-11 11:03:08

标签: java switch-statement

我已经拥有以下内容:

public class RandomTickets
{
   public static void main(String[] args)
   {
      final int MIN = 0, MAX = 3;
      int ticketQuant = ((int)(Math.random() * (MAX + 1 - MIN))) + MIN;

      System.out.println();
      System.out.print("You have won " + ticketQuant);
      System.out.println(ticketQuant == 1 ? " ticket." : " tickets.");
      System.out.println();
   }
}

但我想要做的是改变程序,以便:

  • 赢得3张门票的机会为1/15
  • 赢得2张门票的机会中有2次
  • 赢得1张门票的机会中有4次

我想使用switch语句。

任何想法?!

2 个答案:

答案 0 :(得分:0)

非常简单的解决方案:

final Random random = new Random();
final int r = 1 + random.nextInt(15);
final ticketCount;

if (r <= 4) {
    ticketCount = 1;
} else if (r <= 6) {
    ticketCount = 2;
} else if (r <= 7) {
    ticketCount = 3;
}

有点花哨:

ticketCount = ((r ^ 15) == 0 ? 3 : 0) + 
    (((r | 1) ^ 9) == 0 ? 2 : 0) +
    (((r | 3) ^ 7) == 0 ? 1 : 0);

答案 1 :(得分:0)

    // Designate numbers for each luck
    final List<Integer> luck1OutOf15 = Arrays.asList(1);
    final List<Integer> luck2OutOf15 = Arrays.asList(2, 3);
    final List<Integer> luck4OutOf15 = Arrays.asList(4, 5, 6, 7);

    final Random random = new Random();
    final int luck = random.nextInt(15) + 1;
    final int ticketCount;
    if (luck1OutOf15.contains(luck)) {
        ticketCount = 3;
    } else if (luck2OutOf15.contains(luck)) {
        ticketCount = 2;
    } else if (luck4OutOf15.contains(luck)) {
        ticketCount = 1;
    } else {
        ticketCount = 0;
    }