Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- "isaac" asked on YA:
- java method help ?
- 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.
- */
- import java.util.Arrays;
- public class ArraySplitter {
- /**
- * Program: ArraySplitter.java
- * Purpose: Yahoo! Answers
- * Creator: Chris Clarke
- * Created: 18-29.11.2019
- * Notes: Function splitArray() returns a 2-D array containing two 1-D arrays.
- */
- public int[][] splitArray (int[] anArray) {
- int[][] numbers = new int[2][];
- int len = anArray.length;
- int size = len/2;
- int cOdd = 0, cEven = 0;
- numbers[1] = new int[size]; // for odd indices
- if (len%2==1) size++;
- numbers[0] = new int[size]; // for even indices
- for (int i=0; i<len; i++)
- if (i%2 == 1) numbers[1][cOdd++] = anArray[i];
- else numbers[0][cEven++] = anArray[i];
- return numbers;
- }//splitArray()
- public static void main (String[] args) {
- ArraySplitter splitter = new ArraySplitter();
- int[] x = { 5, 10, 1, 33, 12, 75, 3, 4, 99 };
- int[][] result = splitter .splitArray (x);
- System.out.println ("Original array: " + Arrays.toString (x));
- System.out.println ("Even indices: " + Arrays.toString (result[0]));
- System.out.println ("Odd indices: " + Arrays.toString (result[1]));
- }//main()
- }//class ArraySplitter
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement