How to shorten classpath?

Shorten ArrayLists in Java?

  • 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’t changed, since they aren’t next to each other. What I have so far: import java.util.*; public class FinalPractice7{ public static void main(String args[]){ 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); shorten(list); } public static void shorten(ArrayList<Integer> list) { for(int i = 0; i < list.size()-1; i++){ int first = list.get(i); int second = list.get(i+1); while(first == second){ first +=second; list.remove(i); list.remove(i+1); list.add(i,first); // System.out.println(first); } } System.out.println(list); } } Any guidance/tips would be appreciated. Thank you!

  • Answer:

    public static void shorten(ArrayList<Integer> list) { for(int i = 0; i < list.size()-1; i++){ int sum = list.get(i); for(int j=i; list.get(j)==list.get(j+1)&&j< list.size()-1;j++){ sum+=list.get(j); } for(int j=0;j<((sum/list.get(i))-1); j++) list.remove(i+1); list.set(i, sum); } System.out.println(list); }

Ryan at Yahoo! Answers Visit the source

Was this solution helpful to you?

Other answers

I suggest looking at the solution I gave here to this other person. http://answers.yahoo.com/question/index;_ylt=AuOtiNay1R_AQfQ84CqqKazty6IX;_ylv=3?qid=20120516105610AAM5W8J I recommend changing the code, the syntax structures, so that you're not plagiarizing. I don't know if this is a school assignment or not, but your teacher can actually look up the code online just by copy and paste. Make sure you debug and see what it does in the background, otherwise you won't learn anything.

The Shadowman

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.