2014-08-29 67 views
-7
public long weightedSum(int[] a, int[] b, int n) { 
    long value = 0; 
    long sum = 0; 

    for (int i = 0; i < a.length; i++) { 
     value = a[i] * b[i]; 
     sum = sum + value; 

    } 

    return sum; 
} 

以兩個一維整數數組和一個整數n作爲參數,並返回兩個數組中前n個元素的乘積之和。例如,給定以下兩個一維數組:如何將代碼改成遞歸Java?

int[] arr1 = {1, 2, 3, 4, 5}; 
int[] arr2 = {6, 7, 8, 9, 10}; 

第一4個ARR1和ARR2的元素,即,1 * 6 + 2 * 7 + 3 * 8 + 4 * 9 = 80作爲結果。

+4

你到目前爲止嘗試過什麼? – 2014-08-29 08:06:44

+2

你爲什麼想要? – 2014-08-29 08:08:35

+0

爲第n對計算「值」,並將其與n-1遞歸結果相加。如果n == 0,則返回0。 (@ScaryWombat - 因爲它是一個任務?) – 2014-08-29 08:09:00

回答

0
public static long weightedSum(int[] a, int[] b, int n) { 
    if (n == 0) 
     return 0; 
    else 
     return a[n - 1] * b[n - 1] + weightedSum(a, b, n - 1); 
} 

輸出:

int[] arr1 = { 1, 2, 3, 4, 5 }; 
int[] arr2 = { 6, 7, 8, 9, 10 }; 

System.out.println(weightedSum(arr1, arr2, 1)); // output : 6 
System.out.println(weightedSum(arr1, arr2, 2)); // output : 20 
System.out.println(weightedSum(arr1, arr2, 3)); // output : 44 
System.out.println(weightedSum(arr1, arr2, 4)); // output : 80 
System.out.println(weightedSum(arr1, arr2, 5)); // output : 130 
+0

非常感謝你:)我真的非常感謝你 – 2014-08-29 08:40:04

+0

@BLACKFLAME歡迎你:) – sujithvm 2014-08-29 08:49:03

0

她是你的問題的一個示例解決方案:

public static long recusiveWeightedSum(int [] a ,int [] b, int index) 
    { 
     if (index == a.length) { 
      return 0; 
     } else { 
      return a[index] * b[index] + recusiveWeightedSum(a, b, index + 1); 
     } 
    } 

public static void main(String[] args) { 
     int[] arr1 = {1, 2, 3, 4, 5}; 
     int[] arr2 = {6, 7, 8, 9, 10}; 

     System.out.println("Sum1:" + Sample.weightedSum(arr1, arr2)); 
     System.out.println("Sum2:" + Sample.recusiveWeightedSum(arr1, arr2, 0)); 
    } 
+0

非常感謝你:)我真的很感謝 – 2014-08-29 08:39:34

0

繼承人一個我已經做了,但你必須在0到通過正第一次你叫它。

public long sum(int[] a, int[] b, int n){ 


     while(a.length != 1){ 
      return sum(Arrays.copyOfRange(a, 0, a.length-1), 
         Arrays.copyOfRange(b, 0, a.length-1), 
         a[a.length-1]*b[b.length-1] + n); 
     } 

     return a[0] * b[0] + n; 
    } 
+0

非常感謝你:) – 2014-08-29 08:58:46

+0

歡迎你。然而,像其他人所說的那樣,你的原始解決方案更好(並且不要求n作爲參數,因爲它然後不被使用) – Chris 2014-08-29 09:01:10

+0

羅傑先生我會這樣做:)願上帝保佑你 – 2014-08-29 09:02:40