Created
December 15, 2017 23:07
-
-
Save andream16/7f27d51819584bfdd9de68c969e02b68 to your computer and use it in GitHub Desktop.
Find First Occurrent Letter given an array of Letters - Golang
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
| 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