brilliant_moves

ArraySplitter.java

Nov 30th, 2019
566
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. "isaac" asked on YA:
  3.  
  4. java method help ?
  5.  
  6. Write a method  called splitArray that will accept a single 1-D integer array and return two arrays.  The method should copy the elements from even-indexed array indices to one array and odd-valued array indices to the other array. Each array should be of the precise length of the number of elements it contains.
  7.  
  8. */
  9.  
  10. import java.util.Arrays;
  11.  
  12. public class ArraySplitter {
  13.  
  14.     /**
  15.       * Program:    ArraySplitter.java
  16.       * Purpose:    Yahoo! Answers
  17.       * Creator:    Chris Clarke
  18.       * Created:    18-29.11.2019
  19.       * Notes:      Function splitArray() returns a 2-D array containing two 1-D arrays.
  20.       */
  21.  
  22.     public int[][] splitArray (int[] anArray) {
  23.         int[][] numbers = new int[2][];
  24.         int len = anArray.length;
  25.         int size = len/2;
  26.         int cOdd = 0, cEven = 0;
  27.  
  28.         numbers[1] = new int[size]; // for odd indices
  29.         if (len%2==1) size++;
  30.         numbers[0] = new int[size]; // for even indices
  31.  
  32.         for (int i=0; i<len; i++)
  33.             if (i%2 == 1)   numbers[1][cOdd++] = anArray[i];
  34.             else        numbers[0][cEven++] = anArray[i];
  35.  
  36.         return numbers;
  37.     }//splitArray()
  38.  
  39.     public static void main (String[] args) {
  40.         ArraySplitter splitter = new ArraySplitter();
  41.         int[] x = { 5, 10, 1, 33, 12, 75, 3, 4, 99 };
  42.         int[][] result = splitter .splitArray (x);
  43.         System.out.println ("Original array: " + Arrays.toString (x));
  44.         System.out.println ("Even indices: " + Arrays.toString (result[0]));
  45.         System.out.println ("Odd indices: " + Arrays.toString (result[1]));
  46.     }//main()
  47.  
  48. }//class ArraySplitter
RAW Paste Data