Created
April 17, 2019 15:58
-
-
Save leosabbir/7dce08d5d0d12e569eaaec93ed013cc8 to your computer and use it in GitHub Desktop.
Generates nth look-and-say sequence
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
func countAndSay(n int) string { | |
prev := "1" | |
if n == 1 { | |
return prev | |
} | |
for i := 2; i <= n; i++ { | |
prev = compute(prev) | |
} | |
return prev | |
} | |
func compute(term string) string { | |
var sb strings.Builder | |
prev := rune(term[0]) | |
var count int = 0 | |
for _, v := range term { | |
if v == prev { | |
count++ | |
} else { | |
fmt.Fprintf(&sb, "%d", count) | |
sb.WriteRune(prev) | |
prev = v | |
count = 1 | |
} | |
} | |
fmt.Fprintf(&sb, "%d", count) | |
sb.WriteRune(prev) | |
return sb.String() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment