Question

In: Computer Science

public static BagInterface<String> intersection (BagInterface<String> bagA, BagInterface bagB) This method must return a new bag which...

public static BagInterface<String> intersection (BagInterface<String> bagA, BagInterface bagB)

This method must return a new bag which is the intersection of the two bags: bagA and bagB. An element appears in the intersection of two bags the minimum of the number of times it appears in either. For example, {1,1,2} ∩{1,1,2,2,3}= {1,1,2}. Do not forget to state the big Oof your method implementation.

two file java main and test

by netbeans java

data structure and algorithem

Solutions

Expert Solution

Please find the code below,

BagInterface.java

import java.util.*;

public class BagInterface {

    private List<Integer> data;

    public BagInterface(){
        data = new ArrayList<>();
    }

    public void addItem(int item){
        data.add(item);
    }

    public void addAllItems(List<Integer> items){
        data.addAll(items);
    }

    public BagInterface intersection(BagInterface bagA){
        BagInterface bagB = this;
        Map<Integer, Integer> freqMap = new HashMap<>();
        for(Integer item : bagA.data){
            freqMap.put(item, freqMap.getOrDefault(item, 0)+1);
        }
        BagInterface result = new BagInterface();
        for(Integer item : bagB.data){
            if(freqMap.containsKey(item)){
                result.data.add(item);
                freqMap.put(item, freqMap.get(item)-1);
                if(freqMap.get(item) == 0) freqMap.remove(item);
            }
        }
        return result;
    }

    @Override
    public String toString() {
        StringBuilder output = new StringBuilder();
        for(int i=0; i<data.size(); i++){
            output.append(data.get(i));
            if(i != data.size()-1) output.append(",");
        }
        output.insert(0, "{");
        output.append("}");
        return output.toString();
    }
}

RunnerTest.java

import java.util.*;

public class RunnerTest {

    // Testing code
    public static void main(String[] args) {
        BagInterface bagA = new BagInterface();
        bagA.addAllItems(Arrays.asList(1,1,2));

        BagInterface bagB = new BagInterface();
        bagB.addAllItems(Arrays.asList(1,1,2,2,3));

        BagInterface result = bagA.intersection(bagB);
        System.out.println(bagA + " ∩ " + bagB + " = " + result);
    }

}

OUTPUT:

If you have any doubts put in the comments, also do upvote the solution.


Related Solutions

Write the method: public static String removeSubstring(String s1, String s2) Method removeSubstring(String s1, String s2) Must...
Write the method: public static String removeSubstring(String s1, String s2) Method removeSubstring(String s1, String s2) Must do 3 things: 1. Take two parameters, the original String (String s1) and the substring (String s2) that is to be removed; 2. Create a new String that consists of the original String data less all occurrences of the substring data; 3. Return the new String. Note: 1. The data to be removed is each occurrence of the complete substring, not individual characters of...
Write in Java: Write a method called: public static String[] noIdenticalCombine(String[] array1, String[] array2) { //...
Write in Java: Write a method called: public static String[] noIdenticalCombine(String[] array1, String[] array2) { // instructions: returns an array that contains all the Strings in array1 and array2 but without repetition. order does not matter, but it will return array1's elements and then array2's element that are not in array1. Assume there are no duplicates are in array1 and array2. Could use count which is how many str there are in array2, where !contains(array1, str). May an array of...
public static char mostFrequent(String str) {        if(str.length()==0) {            return '0';   ...
public static char mostFrequent(String str) {        if(str.length()==0) {            return '0';        }        String temp="";        for (int i = 0; i < str.length(); i++) {                 if(!temp.contains(String.valueOf(str.charAt(i)))) {                     temp += String.valueOf(str.charAt(i));                 }             }        char[] tempArray=stringToArray(temp);        int[] countArr=new int[tempArray.length];        int max=0;        for(int i=0;i<tempArray.length;i++) {            int cnt=numOccurences(tempArray[i],str);            countArr[i]=cnt;...
public class OOPExercises {     public static void main(String[] args) {         A objA = new...
public class OOPExercises {     public static void main(String[] args) {         A objA = new A();         B objB = new B();         System.out.println("in main(): ");         System.out.println("objA.a = "+objA.getA());         System.out.println("objB.b = "+objB.getB());         objA.setA (222);         objB.setB (333.33);       System.out.println("objA.a = "+objA.getA());         System.out.println("objB.b = "+objB.getB());     } } Output: public class A {     int a = 100;     public A() {         System.out.println("in the constructor of class A: ");         System.out.println("a = "+a);         a =...
How do you write a Java method that is called : public static String[] noIdenticalCombine(String[] array1,...
How do you write a Java method that is called : public static String[] noIdenticalCombine(String[] array1, String[] array2) { // instructions: returns an array that contains all the Strings in array1 and array2 but without repetition. order does not matter, but it will return array1's elements and then array2's element that are not in array1. Assume there are no duplicates are in array1 and array2. Could use count which is how many str there are in array2, where !contains(array1, str)....
public static void main(String[] args) {        Scanner input = new Scanner(System.in);        String[]...
public static void main(String[] args) {        Scanner input = new Scanner(System.in);        String[] strings = new String[100];        for (int i = 0; i < strings.length; i++) {            System.out.println("Enter Strings: stop ");            strings[i]=input.nextLine();            if(strings[i].equalsIgnoreCase("stop"))                break;        }               MaxLength(strings);//here is the error    }    public static int MaxLength(String[] array) {        int max = array[0].length();       ...
How to write Method in Java: public static in firstLetterFreq(char letter, String[] words] { // it...
How to write Method in Java: public static in firstLetterFreq(char letter, String[] words] { // it returns 0 if (words == null OR words.length == 0) // returns number of times letter is the first letter of a String in words array // use equalIgnoreCase to check if letter and str.charAt(0) are equal and ignoring case }
Complete the following method in java: public static List<Integer> runningMedianOfThree(List items) Create and return a new...
Complete the following method in java: public static List<Integer> runningMedianOfThree(List items) Create and return a new List<Integer> instance (of any subtype of List of your choice) whose first two elements are the same as that of original items, after which each element equals the median of the three elements in the original list ending in that position. For example, when called with a list that prints out as [5, 2, 9, 1, 7, 4, 6, 3, 8], this method would...
public class AllEqual { // You must define the allEqual method, which will return // true...
public class AllEqual { // You must define the allEqual method, which will return // true if either: // 1.) The given array contains fewer than two elements, or... // 2.) All elements of the array are equal to each other. // As a hint, you only need to compare the first element // to all subsequent elements for this check. // // TODO - define your code below this comment // // DO NOT MODIFY parseStrings! public static int[]...
public class Main{ public static void main (String[] args) { Map<Integer, String> ssnMap = new HashMap<Integer,...
public class Main{ public static void main (String[] args) { Map<Integer, String> ssnMap = new HashMap<Integer, String>(); ssnMap.put (8675309,"Jenney"); ssnMap.put (42, "Answer to Everything"); ssnMap.put (8675309, "Stacy"); ssnMap.put (1006, "Peter"); System.out.println(ssnMap.get (8675309)); } } What is the output of the above code. Why?
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT