# CS61B HW0 - widowPosSum ###### tags: `Java` `Practice` 題目: > Write a function windowPosSum(int[] a, int n) that replaces each element a[i] with the sum of a[i] through a[i + n], but only if a[i] is positive valued. If there are not enough values because we reach the end of the array, we sum only as many values as we have. > > For example, suppose we call windowPosSum with the array a = {1, 2, -3, 4, 5, 4}, and n = 3. In this case, we’d: > > Replace a[0] with a[0] + a[1] + a[2] + a[3]. > Replace a[1] with a[1] + a[2] + a[3] + a[4]. > Not do anything to a[2] because it’s negative. > Replace a[3] with a[3] + a[4] + a[5]. > Replace a[4] with a[4] + a[5]. > Not do anything with a[5] because there are no values after a[5]. > Thus, the result after calling windowPosSum would be {4, 8, -3, 13, 9, 4}. > > As another example, if we called windowPosSum with the array a = {1, -1, -1, 10, 5, -1}, and n = 2, we’d get {-1, -1, -1, 14, 4, -1}. 解: ``` public class BreakContinue { public static void windowPosSum(int[] a, int n) { for (int i = 0; i < a.length; i++) { if (a[i] < 0) { continue; } if (i == a.length - 1) { break; } for (int j = 1; j <= n; j++) { if (i + j >= a.length) { break; } else { a[i] = a[i] + a[i + j]; } } } } public static void main(String[] args) { int[] a = {1, 2, -3, 4, 5, 4}; int n = 3; windowPosSum(a, n); // Should print 4, 8, -3, 13, 9, 4 System.out.println(java.util.Arrays.toString(a)); } } ``` 1. 迴圈1先解決elements為負數以及撞到陣列尾巴的情況:負數的情況跳過(continue), 撞到尾巴的情況break 2. 迴圈2開始計算加總,loop從1開始(迴圈1的下一個位置)到間隔n為上限,如果加總的各數超過陣列範圍(包含陣列最後一個位置)就break 3. 承上,沒超過就加總,加到間隔n的位置後停止