Write a static method called split that takes an ArrayList of integer values as a parameter and that replaces each value in the list with a pair of values, each half the original. If a number in the original list is odd, then the first number in the new pair should be one higher than the second so that the sum equals the original number. For example, if a variable called list stores this sequence of values:

Respuesta :

Answer:

The method is as follows:

public static void split(ArrayList<Integer> mylist) {

   System.out.print("Before Split: ");

   for (int elem = 0; elem < mylist.size(); elem++) { System.out.print(mylist.get(elem) + ", ");    }

   System.out.println();

   for (int elem = 0; elem < mylist.size(); elem+=2) {

       int val = mylist.get(elem);

       int right = val / 2;

       int left = right;

       if (val % 2 != 0) {            left++;        }

       mylist.add(elem, left);

       mylist.set(elem + 1, right);    }        

   System.out.print("After Split: ");

   for (int elem = 0; elem < mylist.size(); elem++) { System.out.print(mylist.get(elem) + ", ");    }

}

Explanation:

This declares the method

public static void split(ArrayList<Integer> mylist) {

This prints the arraylist before split

   System.out.print("Before Split: ");

   for (int elem = 0; elem < mylist.size(); elem++) { System.out.print(mylist.get(elem) + ", ");    }

   System.out.println();

This iterates through the list

   for (int elem = 0; elem < mylist.size(); elem+=2) {

This gets the current list element

       int val = mylist.get(elem);

This gets the right and left element

       int right = val / 2;

       int left = right;

If the list element is odd, this increases the list element by 1

       if (val % 2 != 0) {            left++;        }

This adds the two numbers to the list

       mylist.add(elem, left);

       mylist.set(elem + 1, right);    }      

This prints the arraylist after split

   System.out.print("After Split: ");

   for (int elem = 0; elem < mylist.size(); elem++) { System.out.print(mylist.get(elem) + ", ");    }

}