1. Introduction
Anagrams are words or phrases made up of the same letters in a different order. In this post, we will write a Scala program to determine if two provided strings are anagrams of each other.
2. Program Steps
1. Set up the Scala environment.
2. Create an object to house the main function.
3. Obtain the two strings.
4. Implement a function to check if the two strings are anagrams.
5. Invoke the function and display the result.
6. Execute the program.
3. Code Program
object AnagramCheckerApp {
def main(args: Array[String]): Unit = {
// Input two strings
val string1 = "listen"
val string2 = "silent"
println(s"String 1: $string1")
println(s"String 2: $string2")
// Check if they are anagrams and print the result
if (areAnagrams(string1, string2)) {
println("\nThe strings are anagrams.")
} else {
println("\nThe strings are not anagrams.")
}
}
// Function to check if two strings are anagrams
def areAnagrams(s1: String, s2: String): Boolean = {
s1.sorted.equalsIgnoreCase(s2.sorted)
}
}
Output:
String 1: listen String 2: silent The strings are anagrams.
Explanation:
1. We initiate the program with an object named AnagramCheckerApp. Within this object, the main method serves as the entry point.
2. We define string1 and string2 with respective values.
3. The program then prints out the contents of both strings.
4. The areAnagrams function is crafted to determine if two strings are anagrams. This function sorts both strings and then checks if they are equivalent, ignoring case.
5. Within the main function, the program calls the areAnagrams method, assesses if the strings are anagrams, and then displays the outcome.
6. The output indicates whether the two input strings are anagrams.
Comments
Post a Comment