Question

In: Computer Science

Purpose To learn how to use the JCF classes (HashSet, HashMap, TreeSet, TreeMap). You do not...

Purpose

  • To learn how to use the JCF classes (HashSet, HashMap, TreeSet, TreeMap).
    • You do not need to implement these classes.
  • To practice using the StringBuilder class to reduce runtime when working with Strings.

Time Estimate

4-5 hours to complete.

Background

You have been given the following:

Code

  • setAndMaps.java

Input files

  • imdb.txt
  • sight_and_sound.txt
  • 3_lists.txt

Sample output

  • output_intersection.txt
  • output_frequent.txt
  • output_groupByNumChars.txt

The sample output is produced for the provided main function; mainly, the following cases:

// intersection
System.out.println(setAndMaps.intersection(list1, list2));

// frequent
System.out.println(setAndMaps.frequent(list3, 3));

// groupByNumChars
System.out.println(setAndMaps.groupByNumChars(list2));

Problem Statement

Three of the methods in setAndMaps.java are incomplete. Write the code so it works correctly. You should only code in one file, setAndMaps.java.

Do not change the method signatures. Each method should return the output as a String.

Code Structure

public static List getList(String filename){};

  • This method has been done for you.
    • It takes a filename as a parameter and returns a List of movies.
  • Each file contains one movie per line.
    • 3_lists.txt has duplicates because it contains 3 lists
    • the other files do not have duplicates

public static String intersection(List list1, List list2){};

  • Return all movies that occur in both lists as a String.
    • Your output MUST be ordered alphanumerically (from a-z, 0-9).
  • The expected runtime must be O(nlogn) where n is the total number of movies in the lists.
  • Use a HashSet to store one of the lists, so you can search the HashSet efficiently.
    • You may assume that the expected runtime of searching or inserting into a hash table is O(1).
  • Do not call the list's contains method, because it is too slow.
  • Return all entries (do not deduplicate your result).

public static String frequent(List list, int k){};

  • Return all movies in the list that occur at least k times as a String.
    • Your output MUST be ordered alphanumerically (from a-z, 0-9).
  • The output String will contain the movie followed by the number of occurrences in parentheses, as in the sample output.
  • The expected runtime must be O(nlogn) where n is the total number of movies in the list.
  • Use a HashMap to count occurrences
    • the key is the movie
    • the value is the number of occurrences
  • For each movie, check if it's a key in the map.
    • If it is, update its value.
    • Otherwise add a new entry to the map.
  • Then iterate through the map and print the frequent movies.
    • See UsingSetsMaps for an example of how use a for-each loop with a map.

public static String groupByNumChars(List list){};

  • Return all movies in the list, grouped by number of characters, as a String.
    • All movies with the same number of characters should be printed on the same line
    • Movies with fewer characters should be printed first.
    • Your output MUST be ordered alphanumerically (from a-z, 0-9).

Advice

  • There is more than one way to solve this problem, but one way is to use a map.
    • The key is the number of characters, and the value is a list of movies with that number of characters.
    • You can declare it like this:
Map> map = new ... // Choose the appropriate map class
  • For each movie, you can use the String class's length function to get the number of characters.

    • If the map doesn't already have an entry for this length, create a new entry
      • use the map's put method
    • If the map already has an entry for this length:
      • first call the map's get method (which returns a reference to a list)
      • then add the movie to the list
  • Do not use a single String to store more than one movie, because it will slow down the runtime

    • a StringBuilder is fine.

Requirements

  • The program takes in text files that are then converted to lists. Your solutions will operate on the parameterized lists.

  • The code must properly complete the setAndMaps.java class and work with the provided Main.java class.

  • All functions in the setAndMaps.java class MUST be implemented.

  • All code you write should exist solely in the specified methods and additional helper functions. NO CODE SHOULD BE ADDED TO THE MAIN FUNCTION

  • Base your code on the given template. Any code not adhering to the given template may work, but may not pass all tests upon submission.

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

class Main {
   // Returns a List of all movies in the specified file (assume there is one movie per line).
   public static ArrayList getList(String filename) {
   ArrayList list = new ArrayList<>();
   try (Scanner in = new Scanner(new FileReader(filename))) {
   while (in.hasNextLine()) {
   String line = in.nextLine();
   list.add(line);
   }
   } catch (FileNotFoundException e) {
   e.printStackTrace();
   }
   return list;
   }
   public static void main(String[] args) {
       ArrayList list1 = getList("imdb.txt");
       ArrayList list2 = getList("sight_and_sound.txt");
       ArrayList list3 = getList("3_lists.txt");

//Sort lists
Collections.sort(list1);
Collections.sort(list2);
Collections.sort(list3);
  
       System.out.println("***\nintersection\n***");
       System.out.println(setAndMaps.intersection(list1, list2));

       System.out.println("***\nfrequent\n***");
       System.out.println(setAndMaps.frequent(list3, 3));

       System.out.println("***\ngroupByNumChars\n***");
       System.out.println(setAndMaps.groupByNumChars(list2));
   }
}

import java.util.*;

BELOW IS WHERE WE DO THE CODE

public class setAndMaps {

// Prints all movies that occur in both lists.
public static String intersection(List<String> list1, List<String> list2) {
//Add code below
return "";
}

// Prints all movies in the list that occur at least k times
// (print the movie followed by the number of occurrences in parentheses).
public static String frequent(List<String> list, int k) {
//Add code below
return "";
}

// Prints all movies in the list, grouped by number of characters.
// All movies with the same number of characters are printed on the same line.
// Movies with fewer characters are listed first.
public static String groupByNumChars(List<String> list) {
//Add code below
return "";
}
}

Solutions

Expert Solution

  • import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Scanner;

    class Main {
       //Array list of movies
        public static ArrayList<String> getList(String filename) {
            ArrayList<String> arrayList = new ArrayList<>();
            try (Scanner scanner = new Scanner(new FileReader(filename))) {
                while (scanner.hasNextLine()) {
                    String line = scanner.nextLine();
                    arrayList.add(line);
                }
            } catch (FileNotFoundException exception) {
                exception.printStackTrace();
            }
            return arrayList;
        }
        //main method
        public static void main(String[] args) {
            ArrayList<String> list1 = getList("/Users/swapnil/IdeaProjects/MovieList/src/imdb.txt");
            ArrayList<String> list2 = getList("/Users/swapnil/IdeaProjects/MovieList/src/sight_and_sound.txt");
            ArrayList<String> list3 = getList("/Users/swapnil/IdeaProjects/MovieList/src/3_lists.txt");

            //Sort lists
            Collections.sort(list1);
            Collections.sort(list2);
            Collections.sort(list3);

            System.out.println("My test" + SetAndMaps.groupByNumChars(list3));

            System.out.println("***\nintersection\n***");
            System.out.println(SetAndMaps.intersection(list1, list2));

            System.out.println("***\nfrequent\n***");
            System.out.println(SetAndMaps.frequent(list3, 3));

            System.out.println("***\ngroupByNumChars\n***");
            System.out.println(SetAndMaps.groupByNumChars(list2));
        }
    }
    ------------------------------------------------------------------------------------------------------------------------------------------------------------------
    import java.util.*;

    public class SetAndMaps {

        // Prints all movies present in the both the files/ lists
        public static String intersection(List<String> list1, List<String> list2) {
            Set<String> movieList1 = new HashSet<>(list1);
            Set<String> movieList2 = new HashSet<>(list2);
            Set<String> intersection = new HashSet<>();

            if(movieList1.size() < movieList2.size() ){
                intersection = movieList2;
                intersection.retainAll(movieList1);
            }else{
                intersection = movieList1;
                intersection.retainAll(movieList2);
            }

            ArrayList<String> matchingVals = new ArrayList<>();
            for (String element : intersection) {
                matchingVals.add(element);
            }
            Collections.sort(matchingVals); //nlogn
            String result = "";
            for (String element : matchingVals) {
                result = result + element;
                result = result + "\n";
            }
            return result;
        }

        // method to prints all movies that occur frequent
        public static String frequent(List<String> list, int k) {
            Map<String, Integer> movieTMap = new TreeMap<String, Integer>();
            for (String element : list) {
                Integer num = movieTMap.get(element);
                if (num == null) movieTMap.put(element, 1);
                else movieTMap.put(element, num + 1);
            }
            String result = "";
            for (Map.Entry<String, Integer> entry : movieTMap.entrySet()) {
                if (entry.getValue() >= k) {
                    result = result + entry.getKey() + "(" + entry.getValue() + ")";
                    result = result + "\n";
                }
            }
            return result;
        }

        //method to print the movies grouped by number of characters.
        public static String groupByNumChars(List<String> list) {

            Map<Integer, List<String>> movieMap = new TreeMap<Integer, List<String>>();
            for (String element : list) {
                int count = 0;
                for (int i = 0; i < element.length(); i++) {
                    count++;
                }

                List<String> movieNames = movieMap.get(count);
                if (movieNames == null) {
                    movieNames = new ArrayList<String>();
                    movieNames.add(element);
                    movieMap.put(count, movieNames);
                }
                else {
                    if (!movieNames.contains(element)) movieNames.add(element);
                }
            }
            String result = "";
            for (Map.Entry<Integer, List<String>> entry : movieMap.entrySet()) {
                ArrayList<String> temp = (ArrayList<String>) entry.getValue();
                Collections.sort(temp);
                result = result + temp + "\n";
            }
            return result;

        }

    }


    ------------------------------------------------------------------------------------------------------------------------------------------------------------------

    Program Output :



Related Solutions

JAVA * create Q3 class to implement comparator for a TreeSet. The purpose of       ...
JAVA * create Q3 class to implement comparator for a TreeSet. The purpose of        * the comparator is to compare the alphabetic order of integers. With Q3,        * the order of Integer elements will be sort according to the order of        * digit Unicode.        * For example, the value of {11,3,31,2} will return {11,2,3,31}        * NOTE: You don't need to compare each digit one by one. Just compare them System.out.println("Q3...
How do organizations learn (or fail to learn)? Use a contemporary business example to illustrate your...
How do organizations learn (or fail to learn)? Use a contemporary business example to illustrate your answer. (2-3 pages)
The purpose of this assignment is to learn how to apply the t-test to a sample...
The purpose of this assignment is to learn how to apply the t-test to a sample dataset. For this assignment, students will use IBM SPSS Statistics and the "Example Dataset." Using the "Example Dataset" and SPSS, apply the t-test to assess the following statement: "Men and women have different incomes in this city." Show your calculations and copy of the SPSS output in a Word document. In a separate 250-500 Word document, address the following questions: Describe what t-test is...
how do you like to learn the bridge engineering (300 words)
how do you like to learn the bridge engineering (300 words)
What do you learn from seeing a museum exhibit? What do you learn about yourself?
What do you learn from seeing a museum exhibit? What do you learn about yourself?
Purpose: The purpose of this assignment is to learn the content of a 10K report using...
Purpose: The purpose of this assignment is to learn the content of a 10K report using a real company. It is also a requirement for ACC 230. Audience: Your audience is someone who wants to know more about this company (ex: potential investor or employee). Background: Publicly traded companies in the United States are required to file a 10K report with the Securities Exchange Commission (SEC), which gives an overview of the company's financial position. Directions: You have already been...
In this lab you will learn how to use methods from the Math class in order...
In this lab you will learn how to use methods from the Math class in order to calculate the area or the volume of several different shapes. If you are confused about the Methods you can access from the Math class and would like to see some examples click here. Hint: Most of these methods can be done in one line. Step 1 - circleArea In this method you will calculate the area of a circle. Before you can calculate...
Please show how you got the answers so that I can learn how to do this!...
Please show how you got the answers so that I can learn how to do this! 200.00mL of 2.00 M solution of a weak acid is mixed with 300.00 mL of a 2.00 M solution containing its conjugate base. 50.000 g of the slightly soluble salt silver acetate (AgC2H3O2) is added to this buffer solution. After thorough mixing, the solution is assumed to be saturated. To determine the amount of the solid which remains undissolved, the solution is filtered, and...
Instruction: when you do the frequency distribution use 10 classes. You can attach a pdf or...
Instruction: when you do the frequency distribution use 10 classes. You can attach a pdf or word document file. This is another similar question in determining normality (section 6.2). Each part worth 4 points. Question: The numbers of branches of the 50 top banks are shown below:    67 84 80 77 97 59 62 37 33 42 36 54 18 12 19 33 49 24 25 22 24 29 9 21    21 24 31 17 15 21 13...
Code in Java, Use both Set and TreeSet to show the differences between the Set and...
Code in Java, Use both Set and TreeSet to show the differences between the Set and TreeSet that Set still remove the duplicate but won't sort the elements. Create a class named DictionaryWord as: DictionaryWord - word: String                                                              - meanings: String + DictionaryWord (String word, String meanings) + getWord(): String + setWord (String word): void + getMeanings(): String + setMeanings(String meanings): void Write a program with the following requirements: Creates 8 DictionaryWord objects with: Word and meanings as the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT