Alternate Capitalization in Golang


The challenge

Given a string, capitalize the letters that occupy even indexes and odd indexes separately, and return as shown below. Index `` will be considered even.

For example, capitalize("abcdef") = ['AbCdEf', 'aBcDeF']. See test cases for more examples.

The input will be a lowercase string with no spaces.

The solution in Golang

Option 1:

package solution

import "unicode"

func Capitalize(s string) []string {
  a, b := []rune(s),[]rune(s)
  for i := range a {
    if i%2 == 0 {
      a[i] = unicode.ToUpper(a[i])
    } else {
      b[i] = unicode.ToUpper(b[i])
    }
  }
  return []string{string(a), string(b)}
}

Option 2:

package solution

import "strings"

func Capitalize(st string) []string {
  s1 := ""
  s2 := ""
  for i, c :=range st {
    if i%2==0 {
      s1 += strings.ToUpper(string(c))
      s2 += strings.ToLower(string(c))
    } else {
      s1 += strings.ToLower(string(c))
      s2 += strings.ToUpper(string(c))
    }
  }
  
  return []string{s1,s2}
}

Option 3:

package solution

import "unicode"

func Capitalize(st string) []string {
  result := make([]string, 2)
  for p, s := range st {
    result[p % 2 & 1] += string(unicode.ToUpper(s))
    result[p % 2 & 1 ^ 1] += string(unicode.ToLower(s))
  }
  return result
}

Test cases to validate our solution

package our_test
import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)

func dotest(st string, exp []string) {
    var ans = Capitalize(st)
    Expect(ans).To(Equal(exp))
}

var _ = Describe("Example tests", func() {
  It("It should work for basic tests", func() {         
    dotest("abcdef", []string{"AbCdEf", "aBcDeF"})   
    dotest("abracadabra", []string{"AbRaCaDaBrA", "aBrAcAdAbRa"})
    dotest("indexinglessons", []string{"TeStInG", "tEsTiNg"})
    dotest("codingisafunactivity", []string{"ThIsIsCoOl", "tHiSiScoOl"})
  })
})