java - 尝试求 1-45 抽奖中不出现任何连续号码的概率

标签 java arrays

试图找出 1-45 彩票抽奖中不会有任何连续数字的概率,无法弄清楚如何检查数字是否不是连续的,例如 8,9 或 15,14 任何人都可以帮忙;编辑。我更改了代码,现在它将值放入 int 数组中以对数字进行排序和比较,但现在每次都只输出零。

    import java.util.Random;
    public class Lotto {
        Random rangen = new Random();
        private int result;

        public Lotto()
        {
            result = spin();
        }
        public int getSpin()
        {
            return spin();
        }
        private int spin()
        {
            return rangen.nextInt(45)+1;
        }

    } // this is my spin class with constructors


    import java.util.Arrays;
public class con2
{
    public static void main(String args[])
    {

        int num = 100;
        int count = 0;

        Lotto[] myarray = new Lotto[5]; //an array to hold the lotto spins
        int[] numarray = new int[5];

        for(int i=0; i<myarray.length; i++)//loop to go trough array
        {
            myarray[i] = new Lotto();//fill array with balls or spins
            numarray[i] = myarray[i].getSpin();//fill int array with value of lotto spin
            //Arrays.sort(myarray);//sort the array
        }

        Arrays.sort(numarray);//sort the number array

        for(int i =0; i<num; i++)//monte carlo loop
        {
            for(int z=0;z<numarray.length*2;z++) //loop to go trough the array
            {
               if(numarray[z] == numarray[z+1])
               {
                   count++;//here i want to add 1 to count if number is one larger than position at z
               }
               else if(numarray[z] == numarray[z-1])
               {
                   count++;//here i want to add 1 to count if number is one less than position at z
               }

               else
               {
                   break;//if numbers are the same break out of loop
               }
            }
        }
        System.out.println(count/num);

    }
}

最佳答案

Spin方法应避免多次出现。乍一看应该改一下。您可以使用专门设置的集合。

关于java - 尝试求 1-45 抽奖中不出现任何连续号码的概率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28394920/

相关文章:

java - <identifier> HashSet 上的 add 方法出现预期 Java 编译时错误

java - JFrame 窗口不显示

php - 如何将多维数组转换为一维数组?

ios - 带字符串的 Objective C 替代方法触发器名称

php - 调用未定义函数 session_is_registered()

java - 如何从处理草图外部调用处理方法?

java - 无法理解这个 findMinimum 数组方法

用于 XML 树可视化的 Java-lib

java - 列出目录中丢失的文件并删除任何多余的文件

python - Cython numpy 数组索引