Scala Program: Checking if a set is a subset of another set
Scala Set Exercise-10 with Solution
Write a Scala program to create a set and check if it is a subset of another set.
Sample Solution:
Scala Code:
object SubsetCheckExample {
def main(args: Array[String]): Unit = {
// Create two sets
val set1 = Set(1, 2, 3, 4)
val set2 = Set(2, 4)
// Print the sets
println("Set1: " + set1)
println("Set2: " + set2)
// Check if set2 is a subset of set1
val isSubset = set2.subsetOf(set1)
// Print the result
if (isSubset) {
println("Set2 is a subset of Set1.")
} else {
println("Set2 is not a subset of Set1.")
}
}
}
Sample Output:
Set1: Set(1, 2, 3, 4) Set2: Set(2, 4) Set2 is a subset of Set1
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 2 and 4.
- To check if set2 is a subset of set1, we use the subsetOf method.
- In the program, we check if set2 is a subset of set1 by using the line val isSubset = set2.subsetOf(set1).
- Finally, we print the sets and the subset check result.
Scala Code Editor :
Previous: Convert a set to a list.
Next: Checking superset relationships between sets.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/scala-exercises/sets/scala-set-exercise-10.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics