我正在尝试计算一组中两个人在给定组的大小时拥有相同生日的次数。我也得到了模拟运行的次数。我试图返回正确的百分比,即我们有两个人在给定数量的模拟中共享同一个生日的次数。 我首先创建了一个数组,然后调用了一个方法将元素放在一个hashMap中,然后在hashMap中有两个相同的值时显示。但是,在Android Studio上运行时,我得不到正确的百分比。事实上,我正在走一段路。我还在这个块上面声明了一个int类型的全局静态匹配变量。
/**
* sameBday: Create a word count mapping from an array
*/
public void sameBday(int[] valueHolder) {
Map<Integer, Integer> myMap = new HashMap<Integer, Integer>();
for(int number: valueHolder){
if(!myMap.containsKey(number)){
myMap.put(number, 1);
}
else if(myMap.containsKey(number)){
myMap.put(number, myMap.get(number) + 1);
match++;
break;
}
}
}
public double calculate(int size, int count) {
double percentage = 0.0;
int[] myArray = new int[size];
for(int i = 1; i <= count; i++){
Random r = new Random(i);
for(int j = 0; j < size; j++){
myArray[j] = r.nextInt(365) + 1;
}
sameBday(myArray);
if(i == count){
percentage = (match * (100.0/i));
}
}
return percentage;
}
答案 0 :(得分:1)
你的代码充满了奇怪的东西,但是我们都做到了。首先是Map,你不需要它。您可以为循环创建好的旧,并且通过额外检查您将无法比较同一个人(它是i != j
条件),但如果您真的想通过地图执行此操作,则需要在添加数字(作为关键字)的最后,检查一下key的某个值是否大于1,如果为true则匹配。
如何在循环结束时做某事?
if(i == count){
percentage = (match * (100.0/i));
}
不,只需在循环后执行此操作:)
//At the beginning there is int match = 0;
public void sameDayBirthday(int[] birthdays) {
for(int i = 0; i < birthdays.length; i++) {
for(int j = 0; j < birthdays.length; j++) {
if(birthdays[i] == birthdays[j] && i != j) {
match++;
return;
}
}
}
}
public double calculate(int size, int count) {
int[] birthdays = new int[size];
Random r = new Random();
for(int i = 1; i <= count; i++){ //looping through i counts (or 20 counts in this case
for(int j = 0; j < size; j++){ //looping through j times every i iteration
birthdays[j] = r.nextInt(365) + 1;
}
sameDayBirthday(birthdays);
}
return (match * (100.0/(double) count));
}
此代码致电calculate(23, 1000000)
给了我50.7685%的机会,22人47.48690%
如果我得罪你,我很抱歉,我不是故意的。如果您有任何疑问,请发表评论。
答案 1 :(得分:0)
我会使用HashSet并跳过sameBday函数:
public double calculate(int size, int count) {
int match = 0;
Random r = new Random();
for(int i = 1; i <= count; i++){ //looping through i counts (or 20 counts in this case
Set<Integer> birthdays = new HashSet<Integer>(size);
for(int j = 0; j < size; j++){ //looping through j times every i iteration
Integer birthday = r.nextInt(365) + 1;
if (birthdays.contains(birthday)) {
match++;
break;
} else {
birthdays.add(birthday);
}
}
}
return (match * (100.0/count));
}