Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a static method called shorten that takes an ArrayList of Integers as a pa

ID: 3660850 • Letter: W

Question

Write a static method called shorten that takes an ArrayList of Integers as a parameter. It should replace each sequence of two or more equal Integers in the ArrayList with a single Integer equal to the sum of the Integers that were equal. For example, suppose that the parameter is an ArrayList named a containing: [3, 7, 7, 7, 3, 6, 6, 14] Then after calling shorten the ArrayList a should contain: [3, 21, 3, 12, 14] So the 3 occurrences of 7 were replaced with 21, and the 2 occurrences of 6 were replaced with 12. The two occurrences of 3 aren

Explanation / Answer

ShortenTest.java

import java.util.ArrayList;


public class ShortenTest {

    /**
    * @param args
    */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(3);
        list.add(7);
        list.add(7);
        list.add(7);
        list.add(3);
        list.add(6);
        list.add(6);
       
        list.add(14);
        System.out.println("Before Shorten: " + list);
        shorten(list);
        System.out.println("After Shorten: " + list);
    }
    public static void shorten(ArrayList<Integer> list) {
        for(int i = 0 ; i < list.size(); i++) {
            int currentElement = list.get(i);
            int sum = currentElement;
            for(int j=i+1; j< list.size(); j++) {
                if(currentElement == list.get(j)) {
                    sum += list.remove(j--);
                }
                else
                    break;
               
            }
            if(sum > currentElement) {
                list.remove(i);
                list.add(i, sum);
            }
        }
    }
   

}

Output:

Before Shorten: [3, 7, 7, 7, 3, 6, 6, 14]
After Shorten: [3, 21, 3, 12, 14]

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote