Last active
February 13, 2017 09:57
-
-
Save manhdaovan/87ea038302051709c0ecf754444dbc34 to your computer and use it in GitHub Desktop.
Split String into 2 strings with lower and upper case. Eg: split("HelloWorld") returns ["HW", "elloorld"]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* `benchmark` function took: | |
* scala -nc SplitString.scala 14.71s user 0.50s system 274% cpu 5.532 total | |
* on MacbookPro Late 2012 (Core i5 2.5, DDR3 8GB @1600) | |
*/ | |
object SplitString { | |
def split(string: String): (String, String) = { | |
def loop(chars: List[Char], upper: String, lower: String): (String, String) = | |
chars match { | |
case Nil => (upper, lower) | |
case char :: remainChars => | |
if (char.isLower) loop(remainChars, upper, lower + char) | |
else loop(remainChars, upper + char, lower) | |
} | |
loop(string.toList, "", "") | |
} | |
val (upper, lower) = split("HelloWorld") | |
println(upper + lower) | |
def benchmark = | |
for (_ <- 1 to 1000 * 1000) { split("HelloWorld") } | |
benchmark | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
split
can be implemented withpartition
of List.This took:
time scala -nc ~/new_split.scala 11.00s user 0.46s system 247% cpu 4.631 total
better result?