Created
February 14, 2017 04:35
-
-
Save sinanduman/b8df31b80b290e460ff8ab0c26256884 to your computer and use it in GitHub Desktop.
Scala solution for the algorithm explained in https://en.wikipedia.org/wiki/Look-and-say_sequence. But in this soluition, letter comes first, count comes after that.
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
package hackoranko | |
object LookAndSay { | |
def LookAndSay(start: String, n: Int): String = { | |
var first = start(0) | |
var tmpStart = new StringBuilder(start(0).toString() + "1") | |
for (t <- start.tail) { | |
if (first.equals(t)) { | |
tmpStart(tmpStart.size - 1) = (tmpStart.last.toInt + 1).toChar | |
} else { | |
tmpStart.append(t + "1") | |
} | |
first = t | |
} | |
if ((n - 1) == 0) { | |
tmpStart.toString() | |
} else { | |
LookAndSay(tmpStart.toString(), n - 1) | |
} | |
} | |
def main(args: Array[String]) { | |
val start = "1" | |
val cycle = 6 | |
println("Result: " + LookAndSay(start, cycle)) // -> 12221131 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment