1

据我所知,几率应该高出 10%。但是,即使进行 7000 次测试,我也永远无法超过 7%。我认为它必须是匹配计数的计算,但我无法弄清楚它是怎么错的。

import java.util.ArrayList;
import java.util.Random;

public class PersonRoom {
    
    private int persons;

    private int loops;
    
    public int getPersons() {
        return persons;
    }

    public int getLoops() {
        return loops;
    }
    
    public PersonRoom(int persons, int loops) {
        this.persons = persons;
        this.loops = loops;
    }

    public void generatePersons(ArrayList<Person> students) {
        
        Random rng = new Random();
        
        for(int i = 0; i < persons; i++) {
            students.add(new Person(rng.nextInt(365) + 1));
        }
    }
    
    public boolean matchBirthday(ArrayList<Person> students) {
        
        for(int i = 0; i < students.size() - 1; i++) {
                if(students.get(i).getBirthday() == students.get(i + 1).getBirthday()) {
                    return true;
                }
            }
        return false;
        }
    
    public double probability() {
        
        double matchCount = 0;
        
        for(int i = 0; i < loops; i++) {
            
            ArrayList<Person> students = new ArrayList<>();
            
            generatePersons(students);
            
            if(matchBirthday(students)) {
                matchCount++;
            }
            
        }
        return (matchCount/loops) * 100;
    }
    
}
4

0 回答 0