【问题标题】:Make a coin be unfair in java在java中使硬币不公平
【发布时间】:2013-11-28 00:23:12
【问题描述】:

我需要让硬币不公平,让硬币正面的次数是反面的两倍。我目前不知道从哪里开始转动 flip() 类,以便它显示的正面是反面的两倍。我要问的是,我必须实施什么算法才能让头部的显示频率是尾部的两倍?

这是硬币文件:

public class Coin {
     private final int HEADS = 0;
     private boolean face;

    public Coin() {
        flip();
    }

    public void flip() {
        face = ((int) (Math.random() * 2) != 0);
    }

    public boolean isHeads() {
        return face;
    }

    public String toString() {
        return (isHeads()) ? "Heads" : "Tails";
    }
}

这里是 CountFilps 文件:

public class CoinFlips {
    public static void main(String[] args) {
        final int FLIPS = 1000;
        int heads = 0, tails = 0;

        Coin myCoin = new Coin();

        for (int count = 1; count <= FLIPS; count++) {
            myCoin.flip();

            if (myCoin.isHeads()) {
                heads++;
            } else {
                tails++;
            }
        }
        System.out.println("Number of flips: " + FLIPS);
        System.out.println("Number of heads: " + heads);
        System.out.println("Number of tails: " + tails);
    }
}

编辑:感谢大家的快速回复!不知道这就是我需要做的一切,我感到很傻。

【问题讨论】:

  • 公平是2 中的一尾机会。您正在3 中寻找机会。
  • math.random() 在 0.000 和 0.6667 之间时为头,否则为尾

标签: java


【解决方案1】:
Random rand = new Random();
int value = rand.nextInt(3); // Possible values are 0, 1 & 2

if(value == 0) {
   System.out.println("heads");
} else { 
   System.out.println("tail");
}

公平是 50% 的机会。不公平与 50% 的机会不同(3 分之 1 = 33% 的机会)。

【讨论】:

  • 更正:可能的值 = 0,1,2。你的 33% 仍然成立,但解释有点不正确。
【解决方案2】:

用这个替换翻转():

face = (Math.random() >= 1/3.0);

希望这就是你要找的。​​p>

【讨论】:

  • Nitpick: 1/3 计算结果为 0。
  • 嗯?你什么意思? 1/3 = 0.3333333333
【解决方案3】:

将您的 flip() 方法更改为

face = ((int) (Math.random() * 3) < 2);

【讨论】:

    【解决方案4】:

    只需将翻转方法更改为如下所示

    public void flip() {
        face = ((int) (Math.random() * 3) != 0);
    }
    

    理论上,这将使硬币正面的概率为 66.6%,反面的概率为 33.3%。

    当然,您可以切换真/假逻辑,使反面 66.6% 和正面 33.3%。

    您可以将3 更改为任意数字,使用 5 表示反面为 80%,正面为 20%。

    【讨论】:

      【解决方案5】:

      试试下面的翻转方法。

      public void flip() {
          face = (Math.random() >= 1.0 / 3.0);
      }
      

      【讨论】:

      • Nitpick: 1/3 计算结果为 0。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-22
      • 1970-01-01
      • 2016-05-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多