Grasping `all-the-apples-at-once' › 解法样本 Sample solutions › GO (Group II) [#280]

我知道这是一个 Clojure 的帖子,但是出于好奇,我用 Go 编写了它(我最近一直在使用 Go)。只是为了看看是否可以快速解决。我花了大约 10 分钟,减去 3-4 分钟与 runes 战斗的时间。 这不是特别优雅,但能工作。
``I know this is a Clojure post, but out of curiosity I wrote it in Go (what I've been working in lately) just to see if I could solve it quickly. Took about 10 minutes, subtract 3-4 for fighting with runes. It's not particularly elegant, but it works.''

type result struct {
        letter string
        count  int
        }

func main() {
   const input = "aaaabbbcca"
   var ret []result

   currentLetter := string(input[0])
   countCurrentLetter := 1

   for _, elem := range input[1:] {
           elemAsString := string(elem)
           if currentLetter == elemAsString {
                   countCurrentLetter++
           } else {
                   ret = append(ret, result{currentLetter, countCurrentLetter})
                   currentLetter = elemAsString
                   countCurrentLetter = 1
           }
   }
   ret = append(ret, result{currentLetter, countCurrentLetter})
   fmt.Printf("%+v", ret)
}

该解法与类似解法的显著特征是明确的迭代:for 循环。
The salient feature of this and similar solutions is explicit iteration: the for loop.