Replace each element in ArrayList with pair of Ints which sum to existing element

Posted on

Problem

Looking for general feedback and considerations to make for the next time :).

Write a method stretch that doubles the size of an ArrayList of integers by replacing every integer in the list with a pair of integers, each half the original. If a number in the original list is odd, then the first number in the replacement 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:

[18, 7, 4, 24, 11]

and you make the following call:

stretch(list);

Then the number 18 is stretched into the pair (9, 9), the number 7 is stretched into (4, 3), the number 4 is stretched into (2, 2), the number 24 is stretched into (12, 12) and the number 11 is stretched into (6, 5) yielding the following overall list which is twice the length of the original list:

[9, 9, 4, 3, 2, 2, 12, 12, 6, 5]

public void stretch(ArrayList<Integer> list) {
    for (int i = 0; i < list.size(); i+=2) {
        int value = list.get(i);
        int right = value / 2;
        int left = right;
        if (value % 2 != 0) {
            left++;
        }
        list.add(i, left);
        list.set(i + 1, right);
    }       

}

Solution

You don’t need the if statement that is calculating left. You can just make it the value that completes right into value:

int left = value - right;

Also, it is bad practice to modify a collection while you are iterating over it. Make a new list and populate it, and just assign the reference at the end of the method.

Leave a Reply

Your email address will not be published. Required fields are marked *