4

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 = ......
1

2 Answers 2

7
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
Sign up to request clarification or add additional context in comments.

Comments

0

i guess to check if String is 'alphabetically growing' in scala you could simply check it with provided sorted method for strings like this:

def isAlphabetic(s: String): Boolean = s == s.sorted

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.