Skip to content

Instantly share code, notes, and snippets.

@eduardonunesp
Created November 20, 2023 16:08
Show Gist options
  • Save eduardonunesp/ce4fa17a16a564118f2d34fed5a2fe11 to your computer and use it in GitHub Desktop.
Save eduardonunesp/ce4fa17a16a564118f2d34fed5a2fe11 to your computer and use it in GitHub Desktop.
Some random question
// Given a string, cycle the first letter of each word back one word,
// and cycle the last letter of each word forward one word.
// Example input: "who welld horly"
// Example output: "why hello world"
// Do this example by hand:
// Input: "bes le uoogit"
// Output: ""
package main
import (
"fmt"
"strings"
)
func cycleLetters(input string) string {
stringSlice := strings.Split(input, " ")
result := make([]string, len(stringSlice))
for currIdx := 0; currIdx < len(stringSlice); currIdx++ {
prevIdx := currIdx - 1
nextIdx := currIdx + 1
if prevIdx < 0 {
prevIdx = len(stringSlice) - 1
}
if nextIdx > len(stringSlice)-1 {
nextIdx = 0
}
currentWord := stringSlice[currIdx]
firstLetterNextWord := string(stringSlice[nextIdx][0])
lastLetterPrevWord := string(stringSlice[prevIdx][len(stringSlice[prevIdx])-1])
result[currIdx] = firstLetterNextWord + currentWord[1:len(currentWord)-1] + lastLetterPrevWord
}
return strings.Join(result, " ")
}
func main() {
fmt.Println(cycleLetters("who welld horly"))
fmt.Println(cycleLetters("bes le uoogit"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment