Skip to content

Instantly share code, notes, and snippets.

@andream16
Created December 15, 2017 23:07
Show Gist options
  • Select an option

  • Save andream16/7f27d51819584bfdd9de68c969e02b68 to your computer and use it in GitHub Desktop.

Select an option

Save andream16/7f27d51819584bfdd9de68c969e02b68 to your computer and use it in GitHub Desktop.
Find First Occurrent Letter given an array of Letters - Golang
package main
import (
"errors"
"fmt"
"strings"
)
func main() {
s := []string{"A","B","C","D","B","A","C","C"}
occurrentLetter, err := returnFirstOccurrence(s); if err != nil {
fmt.Println(err.Error())
} else {
fmt.Println(fmt.Sprintf("The first occurrent letter was %s", occurrentLetter))
}
}
func returnFirstOccurrence(s []string) (string, error) {
m := make(map[string]int)
for _, c := range s {
r := m[c]; if r > 0 {
return c, nil
}
m[c] = 1
}
return "", errors.New(fmt.Sprintf("No occurrent value found for string %s", strings.Join(s, "")))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment