如何测试集合是否包含集合中其他两个数字的总和

时间:2014-02-02 20:55:37

标签: java recursion

假设我的isSumAB中有数字7和43,如果a和b在isSumAB中,那么我当然可以a + b。所以我要做的是有一个布尔递归函数来测试我的数组,如果它的真实与否,那么我怎么能有一个布尔函数让我用int a和b做这个?

int[] numbers = {10, 51,137, 464, 589 ...};

     for(int num: numbers){
                System.out.println("isSumAB()-- is " + num + " Sum of A and B in Java :" + isSumAB(num));
    }

这个方法有些东西

public boolean isSumAB(int a, int b){

   if ( a > b )
     return false
   else if 
        y + sum( x, y - 1 );
      return true 
      //something

}

1 个答案:

答案 0 :(得分:1)

import  java.util.Iterator;
import  java.util.Map;
import  java.util.Set;
import  java.util.TreeMap;
/**
   <P>{@code java FindElementsThatAreSumsOfOthers}</P>
 **/
public class FindElementsThatAreSumsOfOthers  {
   public static final void main(String[] igno_red)  {
      int[] ai = new int[]{10, 51, 137, 464, 589, 61, 452};

      //All numbers in a map, key is array-value, value is array-index
      Map<Integer,Integer> mpValIdxAll = new TreeMap<Integer,Integer>();

      for(int i = 0; i < ai.length; i++)  {
         mpValIdxAll.put(ai[i], i);
      }

      //Only those elements in the array that are *sums* of other elements
      //Key is array-index of sum, value is SumInfo object
      Map<Integer,SumInfo> mpValIdxSums = new TreeMap<Integer,SumInfo>();

      for(int i = 0; i < ai.length; i++)  {
         //j + 1: So we don't test the same combination twice.
         for(int j = i + 1; j < ai.length; j++)  {
            int iSum = ai[i] + ai[j];

            if(mpValIdxAll.containsKey(iSum))  {
               //The all-map contains the sum, so add it to the sum-map
               mpValIdxSums.put(mpValIdxAll.get(iSum), new SumInfo(ai[i], i, ai[j], j));
            }
         }
      }

      Set<Integer> stSumIdxs = mpValIdxSums.keySet();
      Iterator<Integer> itrSumIdxs = stSumIdxs.iterator();
      while(itrSumIdxs.hasNext())  {
         int iIdxSum = itrSumIdxs.next();
         SumInfo si = mpValIdxSums.get(iIdxSum);
         System.out.println(ai[iIdxSum] + " (element " + iIdxSum + ")  is the sum of elements " + si.iA + " (idx=" + si.iIdxA + ") and " + si.iB + " (idx=" + si.iIdxB + ")");
      }
   }
}
//The two elements that are a sum of another element
class SumInfo  {
   public final int iA;
   public final int iIdxA;
   public final int iB;
   public final int iIdxB;
   public SumInfo(int i_addendA, int i_ndexA, int i_addendB, int i_ndexB)  {
      iA = i_addendA;
      iIdxA = i_ndexA;
      iB = i_addendB;
      iIdxB = i_ndexB;
   }
}

输出:

[C:\java_code\]java FindElementsThatAreSumsOfOthers
589 (element 4)  is the sum of elements 137 (idx=2) and 452 (idx=6)
61 (element 5)  is the sum of elements 10 (idx=0) and 51 (idx=1)