查找数组中加起来的数字对的数量

时间:2014-03-20 18:14:02

标签: java arrays dice

我正在尝试提出一个程序,它将搜索一个数组内部,该数组由用户提供一个长度,该数组选择是否有一对总和为7的数字。这个想法是,如果有k投掷骰子的数量,投出的骰子中有多少对数加起来为7.到目前为止,这是我能想到的所有内容,但我很困难。

这是该程序的驱动程序类。我必须写一个能使这个驱动程序正常运行的类。

import java.util.Scanner;   
public class SevenDriver{       
   public static void main(String[] args){      
      System.out.println("Enter number of dice to toss");     
      Scanner s = new Scanner(System.in);      
      int diceCount = s.nextInt(); 
      SevenTally t = new SevenTally(diceCount);
      int experiments = 1000000;
      int wins = 0;
      for(int j = 0; j < experiments; j++)
         if(t.experiment()) wins++;
     System.out.println((double)wins/experiments);

   } 
}   

这是我到目前为止所拥有的。它目前无法正常工作或编译。我正在寻找一些让我走的想法。谢谢!

public class SevenTally{
   private int diceCount;

   public SevenTally(int die){
      diceCount = die;
}

   public int genDice(){
      return 1 + (int)(Math.random()*6);
   }

   public boolean experiment(){

      boolean[] nums = new boolean[diceCount];
      int ranNum;
      int sum = 7;
      for(int i = 0; i < nums.length; i++){
         ranNum = genDice();
         if (nums[ranNum] == sum){
            return true;
         }
      }

      int left = 0;
      int right = nums.length - 1;
      while(left<right){
      int tempSum = nums[left] + nums[right];
      if(tempSum == 7){
         return true;
      }
      else if(tempSum>7){
         right--;
     }
     return false;
  }

}

4 个答案:

答案 0 :(得分:1)

首先使用[1; 6]

中的随机int填充长度为k的array

长度为k的数组中可能的对数是数组中2组合的数量,即(k-1)* k / 2(http://en.wikipedia.org/wiki/Combination

您可以像array那样测试所有可能的对(i,j):

int win = 0;
int tally = 7;

for(int i=0; i<k-1; i++){
  for(int j=i+1; j<k; j++){
    if(array[i]+array[j] == tally){
      win++;
    }
  }
}

这样做是因为它将该对的第一个元素设置为数组的第一个元素,并将其与其他元素相继求和。

array[0] for循环的第一遍中,array[1]array[k-1]i成对,即k对。 然后在第二次通过时k-1对,依此类推。

你最终得到(k)+(k-1)+(k-2)+ ... + 1对,那就是(k-1)* k / 2对。

done =]

编辑:抱歉,还没看完整件事。方法experiment()应该返回一个布尔值。你可以return win>0?true:false;例如......

答案 1 :(得分:0)

您在ranNum中生成一个随机数,然后将其用作数组nums的索引。同时,nums永远不会被填充,所以无论你索引哪个盒子,它都不会包含7。

如果我理解你的问题,你想做什么,是用模具滚动的结果填充数组中的每个空格,然后比较每两个位置(滚动)以查看它们是否总和为7。你可以使用嵌套的for循环来做到这一点。

基本上,你想这样做:(以伪代码编写,因为我不是java程序员)

int[] results[numrolls]
for (count = 0 to numrolls-1) { results[numrolls]=dieRoller() }
for (outer = 0 to numrolls-2)
 for (inner = outer+1 to numrolls-1)
  if (results[outer] + results[inner] == 7) return true
return false;

但是,在这种情况下,还有一种更简单的方法。你知道在2d6上得到7的总和的唯一方法是(1,6),(2,5),(3,4),(4,3),(5,2),(6,1) 。设置一个6长度的布尔数组,滚动你的骰子,并在每次滚动后将res [result]设置为true。然后返回(基于1的数组用于简单)((res [1]&amp;&amp; res [6])||(res [2]&amp;&amp; res [5])||(res [3]&amp; ;&amp; res [4]))。

答案 2 :(得分:0)

Wiki页面有一些算法可以做到这一点。这不是一个微不足道的问题......

答案 3 :(得分:0)

ArrayIndexOutOfBoundsException表示您正在尝试访问尚未分配的数组元素。

在你的代码中,你创建一个长度为d的新数组diceCount,但是你总是在6个元素上创建genDice()。