Set Intersection
Part of the Logic & Flow section of Coddy's Dart journey — lesson 23 of 65.
When you need to find elements that exist in both of two Set collections, the intersection() method provides the perfect solution. This operation identifies the common elements between two sets, creating a new set that contains only the items that appear in both original collections.
The intersection() method works by comparing the elements of two sets and returning a new set containing only the shared values. Like other set operations, it automatically handles uniqueness, so each common element appears only once in the result.
Set<String> aliceFriends = {'Bob', 'Charlie', 'Diana', 'Eve'};
Set<String> bobFriends = {'Alice', 'Charlie', 'Frank', 'Diana'};
Set<String> mutualFriends = aliceFriends.intersection(bobFriends);
print(mutualFriends); // {Charlie, Diana}This operation is particularly useful for finding overlaps in data, such as common interests between users, shared skills in teams, or matching criteria in filtering operations. The intersection helps you identify what two collections have in common, making it valuable for comparison and analysis tasks.
Challenge
EasyCreate a program that manages a social media platform by finding mutual connections between two users. Your program should:
- Read a string input representing the first user's name
- Read multiple string inputs representing the first user's connections (the input will end when you receive
"user1_done") - Read a string input representing the second user's name
- Read multiple string inputs representing the second user's connections (the input will end when you receive
"user2_done") - Create two separate Sets to store each user's connections
- Use the
intersection()method to find mutual connections between both users - Print the connection analysis results in the exact format shown below
For example, if the first user is "Alice" with connections "Bob", "Charlie", "Diana", "Eve", and the second user is "Bob" with connections "Alice", "Charlie", "Frank", "Diana", your program should output:
User Analysis: Finding mutual connections
Alice's connections: {Bob, Charlie, Diana, Eve}
Bob's connections: {Alice, Charlie, Frank, Diana}
Mutual connections: {Charlie, Diana}
Total mutual connections: 2
Connection strength: Strong (2+ mutual connections)
Status: Users have mutual connectionsIf the first user is "Sarah" with connections "John", "Mike", "Lisa", and the second user is "Tom" with connections "Emma", "David", "Kate", your program should output:
User Analysis: Finding mutual connections
Sarah's connections: {John, Mike, Lisa}
Tom's connections: {Emma, David, Kate}
Mutual connections: {}
Total mutual connections: 0
Connection strength: None (no mutual connections)
Status: Users have no mutual connectionsIf the first user is "Emma" with connections "Alex", "Jordan", "Taylor", "Morgan", and the second user is "Jordan" with connections "Emma", "Taylor", "Casey", your program should output:
User Analysis: Finding mutual connections
Emma's connections: {Alex, Jordan, Taylor, Morgan}
Jordan's connections: {Emma, Taylor, Casey}
Mutual connections: {Taylor}
Total mutual connections: 1
Connection strength: Weak (1 mutual connection)
Status: Users have mutual connectionsYour program must use the intersection() method to find common connections between the two user Sets. Determine the connection strength based on the number of mutual connections: "None" for 0 mutual connections, "Weak" for exactly 1 mutual connection, and "Strong" for 2 or more mutual connections. If there are mutual connections, show "Users have mutual connections" as the status, otherwise show "Users have no mutual connections".
Cheat sheet
The intersection() method finds common elements between two sets, returning a new set containing only the shared values:
Set<String> aliceFriends = {'Bob', 'Charlie', 'Diana', 'Eve'};
Set<String> bobFriends = {'Alice', 'Charlie', 'Frank', 'Diana'};
Set<String> mutualFriends = aliceFriends.intersection(bobFriends);
print(mutualFriends); // {Charlie, Diana}This operation automatically handles uniqueness and is useful for finding overlaps in data, such as common interests, shared skills, or matching criteria in filtering operations.
Try it yourself
import 'dart:io';
void main() {
// Read first user's name
String? user1Name = stdin.readLineSync();
// Read first user's connections until "user1_done"
Set<String> user1Connections = <String>{};
String? connection;
while ((connection = stdin.readLineSync()) != "user1_done") {
if (connection != null) {
user1Connections.add(connection);
}
}
// Read second user's name
String? user2Name = stdin.readLineSync();
// Read second user's connections until "user2_done"
Set<String> user2Connections = <String>{};
while ((connection = stdin.readLineSync()) != "user2_done") {
if (connection != null) {
user2Connections.add(connection);
}
}
// TODO: Write your code below
// Find mutual connections using intersection() method
// Determine connection strength based on mutual connections count
// Generate the required output format
// Print the analysis results
print("User Analysis: Finding mutual connections");
// Add your output statements here
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced List Manipulation
List Properties: first & lastList State: isEmpty & isNotEmpReversing a ListAdding to a List: insertList Removal: removeWhereFinding in a List: indexOfSorting a ListShuffling a ListRecap - List Organizer4Advanced Map Manipulation
Iterating Over a MapChecking for Keys and ValuesMap Properties: keys & valuesConditional Add: putIfAbsentRemoving Entries from a MapNested MapsRecap - Inventory Update2Functional List Operations
Transforming with 'map'Filtering with 'where'Using '.toList()'Checking Conditions with 'any'Conditions with 'every'Finding with 'firstWhere'Recap - Data Filtering5Project: Shopping Cart Calc
Project SetupAdding Items to the Cart3Sets
What is a Set?Creating a SetAdding and Removing from SetsChecking for Elements in a SetConverting a List to a SetSet UnionSet IntersectionSet DifferenceRecap - Unique Guest List