Last active
November 1, 2022 08:02
-
-
Save sarkologist/02f8831b9637a53e91022b1970b37fde to your computer and use it in GitHub Desktop.
multiply then add numbers, in one pass
This file contains 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
assert(eval("2+2*3+12+4*5*2+10*1") == 70) | |
def eval(input: String): Int = { | |
input.splitEfficientlyOn("+").foldLeft(0)((n, str) => n + mul(str)) | |
} | |
def mul(input: String): Int = { | |
input.splitEfficientlyOn("*").foldLeft(1)((n, x) => n * x.toInt) | |
} | |
implicit class StringCanSplitEfficiently(str: String) { | |
def splitEfficientlyOn(delimiter: String) = | |
new StringTokenizerIterator(new StringTokenizer(str, delimiter, false)) | |
final class StringTokenizerIterator( | |
private val tokenizer: StringTokenizer | |
) extends Iterator[String] { | |
def hasNext: Boolean = tokenizer.hasMoreTokens | |
def next(): String = tokenizer.nextToken() | |
} | |
} |
This file contains 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
def eval(input: String): Int = { | |
input.split('+').map(mul).fold(0)(_ + _) | |
} | |
def mul(input: String): Int = { | |
input.split('*').map(_.toInt).fold(1)(_ * _) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment