BreakContinuePractice

Bekerley final exercise 4:

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.

https://sp18.datastructur.es/materials/hw/hw0/hw0.html#optional-exercise-4

Method1: continue+break

public class BREAKCONTINUE1 {
  public static void windowPosSum(int[] a, int n) {
    for(int i=0;i<a.length;i++)
     {  int sum=0;
        if(a[i]<0)
        {
          // System.out.println(a[i]);
          continue;
        }
        for(int j=i;j<=n+i;j++)
        {
          if(j==a.length)break;
          sum+=a[j];
          a[i]=sum;
        }
        // System.out.println(a[i]);
      }
    }

    /** your code here */ 
    public static void main(String[] args) {
      int[] a = {1, 2, -3, 4, 5, 4};
      int n = 3;
      windowPosSum(a, n);
      System.out.println(java.util.Arrays.toString(a));

      // Should print 4, 8, -3, 13, 9, 4

        // int[] a={1, -1, -1, 10, 5, -1};
        // int n=2;
        // windowPosSum(a,n);
        // System.out.println(java.util.Arrays.toString(a));
    }
  }

 Method2: continue only

public class BREAKCONTINUE1 {
  public static void windowPosSum(int[] a, int n) {
    int[] newArray=new int[6];
    for(int i=0;i<a.length;i++){
      int s=0;
      if(a[i]<0){
        System.out.println(i);
        newArray[i]=a[i];
        continue;
      }
      for(int j=i;j<=n;j++)
        s=s+a[j];
      newArray[i]=s;
      if(n<a.length-1)
        n++;  
      else continue;
    }
    System.out.println(java.util.Arrays.toString(newArray));
  }
  /** your code here */ 
  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));

        // int[] a={1, -1, -1, 10, 5, -1};
        // int n=2;
        // windowPosSum(a,n);
  }
}

 

posted on 2019-08-20 19:45  鸣动我心  阅读(345)  评论(0编辑  收藏  举报