Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check in Scala if String is 'alphabetically growing'?

Lets define that String is 'alphabetically growing' when:

  1. Every letter is alphabetically bigger then previous one.
  2. It doesn't matter if letter is uppercase or not.

These Strings are 'alphabetically growing':

  • "abcde"
  • "aBfJz"

And these are not:

  • "abbcd"
  • "abdDz"
  • "zba"

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 = ......
like image 465
rtruszk Avatar asked Mar 17 '23 17:03

rtruszk


1 Answers

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
like image 112
Marth Avatar answered Mar 21 '23 04:03

Marth