Advertisement
DulcetAirman

pairwiseSum

Dec 26th, 2017
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.60 KB | None | 0 0
  1. package ch.claude_martin.playground;
  2.  
  3. import java.util.*;
  4.  
  5. public final class SomeClass {
  6.     public static void main(String[] args) {
  7.         int[] a = { 2, 1, 18, -5 };
  8.         int[] pairwiseSum = pairwiseSum(a);
  9.         System.out.println(Arrays.toString(pairwiseSum));
  10.     }
  11.  
  12.     public static int[] pairwiseSum(int[] a) {
  13.         if (Objects.requireNonNull(a, "array can't be null").length % 2 != 0)
  14.             throw new IllegalArgumentException("length must be even");
  15.         int[] result = new int[a.length / 2];
  16.         for (int i = 0, k = 0; k < result.length; i = i + 2) {
  17.             result[k++] = a[i] + a[i + 1];
  18.         }
  19.         return result;
  20.     }
  21.  
  22. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement