Lets define that String is 'alphabetically growing' when:
These Strings are 'alphabetically growing':
And these are not:
Lets assume that we are checking Strings which contain only letters. Checking if String is 'growing' can be done in Scala with following code:
val str = "aBgjz"
val growing = str.map(_.toLower).toSet.toList.sortWith( _ < _ ).mkString.equals(str.map(_.toLower))
This code works good but only for English letters. For Strings with Polish letters the result is wrong. In Polish alphabet letters are in following order:
a, ą, b, c, ć, d, e ...
so for:
val str = "aąbćdgz"
the result should be 'true'. So the question is:
How to check in Scala if given String is 'alphabetically growing' for a given locale?
val str = "aąbćdgz"
val locale_id = "pl_PL"
....
val growing = ......
scala> import java.util.Locale
scala> import java.text.Collator
scala> val collator = Collator.getInstance(new Locale("pl_PL"))
scala> val str = "aąbćdgz"
str: String = aąbćdgz
scala> str.map(_.toLower).toSet.toList.sortWith( (s1:Char, s2:Char) => collator.compare(s1.toString, s2.toString) < 0 ).mkString.equals(str.map(_.toLower))
res06: Boolean = true
Though I do find this easier to read :
scala> (str, str.tail).zipped.forall { case (s1,s2) => collator.compare(s1.toString,s2.toString) < 0 }
res08: Boolean = true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With