Reputation: 495
val args = "To now was far back saw the *$# giant planet itself, het a won"
Find and sort distinct anagram pairs from "args":
now won
was saw
the het
First I clean up the args and put them in an array.
val argsArray = args.replaceAll("[^a-zA-Z0-9\\s]", "").toLowerCase.split(" ").distinct.sorted
argsArray: Array[String] = Array("", a, back, far, giant, het, itself, now, planet, saw, the, to, was, won)
My idea is to reduce each word to an array of char, then sort, then compare. But I get stuck because the following returns the wrong data type ---- String = [C@2736f24a
for (i <- 0 until argsArray.length - 1){
val j = i + 1
if(argsArray(i).toCharArray.sorted == argsArray(j).toCharArray.sorted) {
println(argsArray(i).toCharArray + " " + argsArray(j).toCharArray)
}
}
I assume there are better ways to solve this, but what I really want to learn is how to deal with this data type problem, so please help me solve that and then I will refactor later. Thank you.
Upvotes: 0
Views: 1276
Reputation: 170713
[C@<whatever>
is just how Array[Char]
is converted to String
on JVM. Remove calls to toCharArray
from println
and it'll print the strings you want. The second error, with the current code in the question, is the equality check: ==
on arrays checks that they are the same object, and since sorted
will always create a new array, the left and right sides are always different objects even if they have the same elements.
Upvotes: 1