Question

In: Computer Science

[JAVA] Please make sure there are FIVE (5) different source codes. Do not copy your answers...

[JAVA]

Please make sure there are FIVE (5) different source codes. Do not copy your answers or someone’s else answers from different Cheggs. I did not post this question to see the same answers. All information that was given is included. Thank you. I will upvote if you do it properly.

Task 1: Add three methods: union, intersection, and difference to the interface BagInterface for the ADT bag.

Task 2: Implement the three methods, union, intersection, and difference, for the class ResizeableArrayBag. Note: the class ResizeableArrayBag presents an implementation of the ADT bag using a resizable array.

Task 3: Implement the three methods, union, intersection, and difference, for the class LinkedBag. Note: the class LinkedBag presents an implementation of the ADT bag using a linked chain.

Task 4: Write a client program, “ArrayBagTest.java”, which contains a main method to test the three methods (union, intersection, and difference) you implemented for the class ResizeableArrayBag.

Task 5: Write a client program, “LinkedBagTest.java”, which contains a main method to test the three methods (union, intersection, and difference) you implemented for the class LinkedBag.

  • • Union

The union of two collections consists of their contents combined into a new collection. Add a method union to the interface BagInterface for the ADT bag that returns as a new bag the union of the bag receiving the call to the method and the bag that is the method’s one argument. Include sufficient comments to fully specify the method.

Note that the union of two bags might contain duplicate items. For example, if object x occurs five times in one bag and twice in another, the union of these bags contains x seven times. Specifically, suppose that bag1 and bag2 are Bag objects, where Bag implements BagInterface; bag1 contains the String objects a, b, and c; and bag2 contains the String objects b, b, d, and e. After the statement

BagInterface everything = bag1.union(bag2);

executes, the bag everything contains the strings a, b, b, b, c, d, and e. Note that union does not affect the contents of bag1 and bag2.

  • • Intersection

The intersection of two collections is a new collection of the entries that occur in both collections. That is, it contains the overlapping entries. Add a method intersection to the interface BagInterface for the ADT bag that returns as a new bag the intersection of the bag receiving the call to the method and the bag that is the method’s one argument. Include sufficient comments to fully specify the method. 3

Note that the intersection of two bags might contain duplicate items. For example, if object x occurs five times in one bag and twice in another, the intersection of these bags contains x twice. Specifically, suppose that bag1 and bag2 are Bag objects, where Bag implements BagInterface; bag1 contains the String objects a, b, and c; and bag2 contains the String objects b, b, d, and e. After the statement

BagInterface commonItems = bag1.intersection(bag2);

executes, the bag commonItems contains only the string b. If b had occurred in bag1 twice, commonItems would have contained two occurrences of b, since bag2 also contains two occurrences of b. Note that intersection does not affect the contents of bag1 and bag2.

  • Difference

The difference of two collections is a new collection of the entries that would be left in one collection after removing those that also occur in the second. Add a method difference to the interface BagInterface for the ADT bag that returns as a new bag the difference of the bag receiving the call to the method and the bag that is the method’s one argument. Include sufficient comments to fully specify the method.

Note that the difference of two bags might contain duplicate items. For example, if object x occurs five times in one bag and twice in another, the difference of these bags contains x three times. Specifically, suppose that bag1 and bag2 are Bag objects, where Bag implements BagInterface; bag1 contains the String objects a, b, and c; and bag2 contains the String objects b, b, d, and e. After the statement

BagInterface leftOver1 = bag1.difference(bag2);

executes, the bag leftOver1 contains the strings a and c. After the statement

BagInterface leftOver2 = bag2.difference(bag1);

executes, the bag leftOver2 contains the strings b, d, and e. Note that difference does not affect the contents of bag1 and bag2.

Solutions

Expert Solution

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

// TODO could be well documented java doc
// and classes can be put into different files

// bag contract
// custom type T should implement equals and hashcode
// data order in the bag does not matter 
abstract class Bag<T> {
        
        // this list has to initialized as per implementation strategy
        protected List<T> data;
        
        // add collections of data
        public void addAll(Collection<T> data) {
                this.data.addAll(data);
        }
        
        // add data one by one
        public void add(T ... data) {
                for(T d : data) {
                        this.data.add(d);
                }
        }
        
        // union of two bags
        public final Bag<T> union(Bag<T> bag) {
                // union with another bag
                // here new bag data order does not matter
                Bag<T> newbag = new ResizableArrayBag<T>();
                newbag.addAll(this.data);
                newbag.addAll(bag.data);
                return newbag;
        }
        
        // internal usage
        Map<T, Integer> map(Bag<T> bag) {
                Map<T, Integer> elements = new HashMap<>(); // track duplicate elements
                for(T d : bag.data) {
                        if(elements.containsKey(d)) {
                                elements.put(d, elements.get(d) + 1);
                        } else {
                                elements.put(d, 1);
                        }
                }
                return elements;
        }
        
        // intersection of two bags
        public final Bag<T> intersection(Bag<T> bag) {
                Map<T, Integer> elements = map(this);
                // intersection
                // here new bag data order does not matter
                Bag<T> newbag = new ResizableArrayBag<T>();
                for(T d : bag.data) {
                        if(elements.containsKey(d)) {
                                // common
                                int c = elements.get(d);
                                newbag.add(d);
                                c--;
                                // track common elements
                                if(c == 0) {
                                        elements.remove(d);
                                } else {
                                        elements.put(d, c);
                                }
                        }
                }
                return newbag;
        }
        
        // difference of two bags
        public final Bag<T> difference(Bag<T> bag) {
                Map<T, Integer> elements = map(bag);
                // difference
                // here new bag data order does not matter
                Bag<T> newbag = new ResizableArrayBag<T>();
                for(T d : this.data) {
                        if(elements.containsKey(d)) {
                                int c = elements.get(d);
                                c--;
                                // remove common elements from another bag
                                if(c == 0) {
                                        elements.remove(d);
                                } else {
                                        elements.put(d, c);
                                }
                        } else {
                                // can be put into new bag directly
                                newbag.add(d);
                        }
                }
                return newbag;
        }
        
        // text representation
        @Override
        public String toString() {
                StringBuilder text = new StringBuilder();
                text.append('[');
                int s = data.size();
                if(s > 0) {
                        text.append(data.get(0));
                        for(int i = 1; i < s; i++) {
                                text.append(", ").append(data.get(i));
                        }
                }
                text.append(']');
                
                return text.toString();
        }
}

// one implementation using array-list
class ResizableArrayBag<T> extends Bag<T> {
        // constructor
        public ResizableArrayBag() {
                this.data = new ArrayList<T>();
        }
}

// another implementation is based on linked list
class LinkedBag<T> extends Bag<T> {
        public LinkedBag() {
                this.data = new LinkedList<T>();
        }
}

// collection bag implementations
public class CollectionBag {
        
        // test method (instead of client program and putting all test cases into main method)
        public static void main(String[] args) {
                // resizable array bag
                Bag<Character> bag1 = new ResizableArrayBag<Character>();
                bag1.add('a', 'b', 'b', 'c');
                Bag<Character> bag2 = new ResizableArrayBag<Character>();
                bag2.add('b', 'b', 'b', 'c', 'd', 'e');
                
                // test 3 methods
                System.out.println(bag1.union(bag2));
                System.out.println(bag1.intersection(bag2));
                System.out.println(bag1.difference(bag2));
                
                // linked bag
                bag1 = new LinkedBag<Character>();
                bag1.add('a', 'b', 'b', 'c');
                bag2 = new LinkedBag<Character>();
                bag2.add('b', 'b', 'b', 'c', 'd', 'e');
                
                // test 3 methods
                System.out.println(bag1.union(bag2));
                System.out.println(bag1.intersection(bag2));
                System.out.println(bag1.difference(bag2));
        }
}

I created one java file and there is a main class and all other utility classes are defined there. All utility classes could be defined in different files. And I didn't create ArrayBagTest.java and LinkedBagTest.java instead I put all test cases into the main method of the main class.


Related Solutions

Fundamentals of Programming USING JAVA Please copy here your source codes, including your input and output...
Fundamentals of Programming USING JAVA Please copy here your source codes, including your input and output screenshots. Please upload this document along with your source files (i.e., the .java files) on Blackboard by the due date. 1. (Display three messages) Write a program that displays Welcome to Java, Welcome to Computer Science, and Programming is fun. 2. (Convert feet into meters) Write a program that reads a number in feet, converts it to meters, and displays the result. One foot...
Please circle the answers and please make sure that it is true answer. Thank you. A...
Please circle the answers and please make sure that it is true answer. Thank you. A particle executes linear SHM with frequency 0.11 Hz about the point x = 0. At t = 0, it has displacement x = 0.33 cm and zero velocity. For the motion, determine the (a) displacement at t = 2.2 s, and (b) velocity at t = 2.2 s.
It is essential that your answers are IN YOUR WORDS. Do NOT copy sentences or phrases....
It is essential that your answers are IN YOUR WORDS. Do NOT copy sentences or phrases. Do NOT take a sentence and change a word here and there. Take the idea and express it the way YOU would say it. Answers to be paragraph length, not just a short sentence or two. Explain your answers. 1. What is an example of a metaphysical question? Explain. 2. What is an argument? What is the difference between a good argument and a...
TASK: ( answers should be computerized and in details - please do not copy and paste...
TASK: ( answers should be computerized and in details - please do not copy and paste - about 1500 words ) Select an organization of your choice and carry out the following tasks. Conduct a research on the marketing and promotional strategies of the organization selected. Your Report should include the following: 1. Introduction 2. Summarize the various promotional strategies used by the organization in implementing an Integrated Marketing Strategy. Identify the risks associated with promotional campaigns and discuss how...
In your opinion what is the main source for development?  MAKE YOUR ANSWERS AS DETAILED AS POSSIBLE....
In your opinion what is the main source for development?  MAKE YOUR ANSWERS AS DETAILED AS POSSIBLE. INCLUDE BOTH THEORY, POLICY AND YOUR INTERPRETENTIONS WITHIN THE ANSWER.
Create a portfolio using the four stocks and information below: ((((please please make sure the answers...
Create a portfolio using the four stocks and information below: ((((please please make sure the answers are correct please)))) Expected Return Standard Deviation Weight in Portfolio Stock A 21.00% 21.00% 15.00% Stock B 5.00% 17.00% 28.00% Stock C 7.00% 12.00% 11.00% Stock D 22.00% 22.00% 46.00% ---------------------- ---------------------- ---------------------- ---------------------- Correlation (A,B) 0.7000 ---------------------- ---------------------- Correlation (A,C) 0.4900 ---------------------- ---------------------- Correlation (A,D) 0.2500 ---------------------- ---------------------- Correlation (B,C) 0.4400 ---------------------- ---------------------- Correlation (B,D) 0.9600 ---------------------- ---------------------- Correlation (C,D) 0.2000 ---------------------- ----------------------...
JAVA PROGRAM (Make sure that programs are running. Please discuss, if there is any compilation or...
JAVA PROGRAM (Make sure that programs are running. Please discuss, if there is any compilation or run error.) Q. 1 Calculate the expression a)         x= 7.0 + (12 %3)*5 – 3;                    b)         x= 7 + (11 / 2)*5 + 3;            Q 2: Write a program that prompts the user to enter five test scores and then prints the average test score. (Assume that the test scores are decimal numbers.) Q 3. Write a program that prompts the capacity, in gallons,...
Please don't copy and paste answers from several sources. Write in your own words! Do you...
Please don't copy and paste answers from several sources. Write in your own words! Do you feel teams help or hurt creativity? Give specific examples. How should you handle a freeloader (someone not willing to do their share of the work) on a team where you are a member? Be specific. For an organization where you have worked, list three ways the organization helped you do your job. (This can be any type of organization if you have never worked.)...
Please discuss the following concepts. Longer answers do not mean better answers; however, be sure to...
Please discuss the following concepts. Longer answers do not mean better answers; however, be sure to demonstrate that you understand each of these concepts. cite works a.         Enforceable Contract b.         Voidable Contract c.         Unenforceable Contract d.         Void Contract
**** PLEASE DO NOT COPY AND PASTE FROM ANOTHER SOURCE BECAUSE THE ANSWER IS INCOMPLETE********* Introduction:...
**** PLEASE DO NOT COPY AND PASTE FROM ANOTHER SOURCE BECAUSE THE ANSWER IS INCOMPLETE********* Introduction: IN C PROGRAMMING For this assignment you will write an encoder and a decoder for a modified "book cipher." A book cipher uses a document or book as the cipher key, and the cipher itself uses numbers that reference the words within the text. For example, one of the Beale ciphers used an edition of The Declaration of Independence as the cipher key. The...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT