Scala Program: Checking if a set is disjoint from another set
Write a Scala program to create a set and check if it is disjoint with another set.
Sample Solution:
Scala Code:
object DisjointCheckExample {
def main(args: Array[String]): Unit = {
// Create two sets
val set1 = Set(1, 2, 3, 4)
val set2 = Set(5, 6, 7)
// Print the sets
println("Set1: " + set1)
println("Set2: " + set2)
// Check if set1 is disjoint with set2
val isDisjoint = set1.intersect(set2).isEmpty
// Print the result
if (isDisjoint) {
println("Set1 is disjoint with Set2.")
} else {
println("Set1 is not disjoint with Set2.")
}
}
}
Sample Output:
Set1: Set(1, 2, 3, 4) Set2: Set(5, 6, 7) Set1 is disjoint with Set2.
Explanation:
In the above exercise,
- First, we create two sets set1 and set2 where set1 contains the elements 1, 2, 3, and 4, and set2 contains the elements 5, 6, and 7.
- To check if set1 is disjoint with set2, we use the intersect method to find common elements between the two sets. If the intersection is empty, the sets are disjoint.
- In the program, we check if set1 is disjoint with set2 by using the line val isDisjoint = set1.intersect(set2).isEmpty.
- Finally, we print the sets and the result of the disjoint check
Scala Code Editor :
Previous: Checking superset relationships between sets.
Next: Find the maximum element in a set.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics