我已经编写了一个代码来查找在数组n上重复一个随机数的概率。的迭代。如何提高这段代码的效率? [关闭]

问题描述 投票:0回答:1

此代码显示在一定数量的模拟或实验中,一组人中两个人在同一日期生日的概率。如何提高这段代码的效率?假定有365,则日期格式为整数(0表示1月1日,364表示12月31日)。此外,如何在此处使用随机种子?我是编程新手。我不知道什么是种子。请帮助我。

package BirthdayProblem;

import java.util.Scanner;
import java.util.Random;
import java.util.Map;
import java.util.HashMap;

public class Birthday {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System. in );
        System.out.printf("Enter number of people: ");
        int n = scan.nextInt();
        System.out.printf("Enter number of simulations: ");
        int simulations = scan.nextInt();
        Random rand = new Random();

        int[] birthDay = new int[n];
        int i,
        j,
        positive = 0;
        float probability;
        for (j = 0; j < simulations; j++) {
            for (i = 0; i < n; i++) {
                birthDay[i] = rand.nextInt(364);
            }
            Map < Integer, Integer > hm = new HashMap < Integer, Integer > ();
            for (int x: birthDay) {
                if (!hm.containsKey(x)) {
                    hm.put(x, 1);
                }
                else {
                    hm.put(x, hm.get(x) + 1);
                }
            }
            for (int x: hm.keySet()) {
                if (hm.get(x) > 1) {
                    positive++;
                    break;
                }
            }
        }
        float p = positive;
        float k = simulations;
        probability = (p / k) * 100;
        System.out.println(probability + "%");

    }
}
arrays random hashmap duplicates probability
1个回答
0
投票

如果不需要每个生日的确切计数,则不需要HashMap,一旦一个生日发生两次,您可以中止。

Set<Integer> previousBirthdays = new HashSet<>();
for(int x : birthDay){
  if(!previousBirthdays.add(x)){
    positive++;
    break;
  }
}

实际上,如果您拥有HashSet,甚至不需要将所有n个生日都存储在数组中,并且一旦有重复项,就可以中止1..n循环。

for(j=0;j<simulations;j++)
{
    Set<Integer> previousBirthdays = new HashSet<>();
    for(i=0;i<n;i++)
    {
       if(!previousBirthdays.add(rand.nextInt(364))){
          positive++;
          break;
       }
    }
}

考虑种子,java使用System.currentTimeMillis()作为默认种子IIRC,我认为这对您的用例足够好。

© www.soinside.com 2019 - 2024. All rights reserved.