Course Overlap

两名学生的课程overlap

You are a developer for a university. Your current project is to develop a system for students to find courses they share with friends. The university has a system for querying courses students are enrolled in, returned as a list of (ID, course) pairs. Write a function that takes in a list of (student ID number, course name) pairs and returns, for every pair of students, a list of all courses they share.

Sample Input:

student_course_pairs_1 = [
  ["58", "Software Design"],
  ["58", "Linear Algebra"],
  ["94", "Art History"],
  ["94", "Operating Systems"],
  ["17", "Software Design"],
  ["58", "Mechanics"],
  ["58", "Economics"],
  ["17", "Linear Algebra"],
  ["17", "Political Science"],
  ["94", "Economics"],
  ["25", "Economics"],
]

Sample Output (pseudocode, in any order):

find_pairs(student_course_pairs_1) =>
{
  [58, 17]: ["Software Design", "Linear Algebra"]
  [58, 94]: ["Economics"]
  [58, 25]: ["Economics"]
  [94, 25]: ["Economics"]
  [17, 94]: []
  [17, 25]: []
}

Additional test cases:

Sample Input:

student_course_pairs_2 = [
  ["42", "Software Design"],
  ["0", "Advanced Mechanics"],
  ["9", "Art History"],
]

Sample output:

find_pairs(student_course_pairs_2) =>
{
  [0, 42]: []
  [0, 9]: []
  [9, 42]: []
}

Solution:

Brute force

public class Main {

    public List<ResultType> courseOverlaps(String[][] studentCoursePairs)
    {
        List<ResultType> res = new ArrayList<>();
        Map<Integer, List<String>> map = new HashMap<>();
        for(int i = 0; i< studentCoursePairs.length; i++)
        {
            int student = Integer.valueOf(studentCoursePairs[i][0]);
            String course = studentCoursePairs[i][1];
            map.putIfAbsent(student, new ArrayList<String>());
            map.get(student).add(course);
        }

        Integer[] studentList = map.keySet();
        for(int i = 0; i< studentList.length; i++)
        {
            for(int j = 1; j < studentList.length; j++)
            {
                List<String> overlap =  overlaps = getInterSection(map.get(studentList[i]) , map.get(studentList[j]));
                res.add(new int[]{studentList[i], studentList[j]}, overlap);
            }
        }
        return res;
    }

    public List<String> getInterSection(List<String> set1, List<String> set2)
    {
        List<String> result = new ArrayList<>();
        for(String element: set1)
        {
            if(set2.contains(element))
            {
                result.add(element);
            }
        }
        return result;
    }
    
}

class ResultType
{
    int[] pairs;
    List<String> courses;
}

Last updated