208,499 views
43 votes
43 votes
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:

User Amir Saleem
by
3.2k points

1 Answer

22 votes
22 votes

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) + ", "); }

}

Step-by-step 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) + ", "); }

}

User Schmudde
by
2.6k points