object CasingVerifier {
def verifyAllUpperOrAllLowerOrIsCapitalized(word: String): Boolean = {
val (upper, lower) = word.foldLeft((0, 0)) {
case ((u, l), ch) if ch.isLower => (u, l + 1)
case ((u, l), ch) if ch.isUpper => (u + 1, l)
case (acc, _) => acc
}
// Case 1: all lowercase
if (upper == 0) true
// Case 2: all uppercase
else if (lower == 0) true
// Case 3: capitalized (only first letter uppercase)
else if (upper == 1 && word.headOption.exists(_.isUpper)) true
// Otherwise, mixed casing
else false
}
def runTest(word: String): Unit = {
println(s"""Testing word: "$word"""")
if (verifyAllUpperOrAllLowerOrIsCapitalized(word)) {
println("OK\n")
} else {
println("Error\n")
}
}
def main(args: Array[String]): Unit = {
runTest("PROGRAMMING")
runTest("programming")
runTest("Programming")
runTest("ProGramMing")
}
}
/*
run:
Testing word: "PROGRAMMING"
OK
Testing word: "programming"
OK
Testing word: "Programming"
OK
Testing word: "ProGramMing"
Error
*/