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

Write a complete program called \"compress\" that takes an ArrayList of Strings

ID: 3643877 • Letter: W

Question

Write a complete program called "compress" that takes an ArrayList of Strings as a parameter. It should replace each sequence of two or more equal Strings in the ArrayList with a single String consisting of the number of Strings that were equal, an asterisk, and the original String.

For example, suppose that the parameter is an ArrayList named a containing:
["clam", "squid", "squid", "squid", "clam", "octopus", "octopus"]

Then after calling "compress" the ArrayList a should contain:
["clam", "3*squid", "clam", "2*octopus"]

So the 3 occurrences of "squid" were replaced with "3*squid", and the 2 occurrences of "octopus" were replaced with "2*octopus". The two occurrences of "clam" aren

Explanation / Answer

Please rate...

import java.util.*;
public class Compress {
    public static void main(String[] args) {
// ["clam", "squid", "squid", "squid", "clam", "octopus", "octopus"]
        ArrayList<String> list = new ArrayList<String>();
        list.add("clam");
        list.add("squid");
        list.add("squid");
        list.add("squid");
        list.add("clam");
        list.add("octopus");
        list.add("octopus");
        compress(list);
        System.out.println(list.toString()); // [clam, 3*squid, clam, 2*octopus]
    }
    public static void compress(ArrayList list)
    {
        int i,c=1,j,k;
        for(i=0;i<list.size();i++)
        {
            c=1;
            for(j=i+1;j<list.size();j++)
            {
                if(list.get(i)==list.get(j))c++;
                else break;
            }
            if(c>1)
            {
                for(k=i;k<i+c-1;k++)
                {
                    list.remove(k);
                }
                list.set(i,c+"*"+list.get(i));
            }
        }
    }
}

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