Created
November 5, 2012 16:07
-
-
Save iwinux/4018005 to your computer and use it in GitHub Desktop.
a naive typoglycemia generator
This file contains 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 ( | |
"fmt" | |
"math/rand" | |
"io/ioutil" | |
"os" | |
"bytes" | |
"unicode" | |
) | |
func main() { | |
input, _ := ioutil.ReadAll(os.Stdin) | |
fmt.Printf("\n\n%v", string(shuffleWords(input))) | |
} | |
func shuffleWords(input []byte) []byte { | |
words := bytes.Fields(input) | |
if len(words) == 0 { return input } | |
lenOfSeeds := len(words[0]) | |
seeds := rand.Perm(lenOfSeeds) // [0, lenOfSeeds) | |
for _, word := range words { | |
lenOfWord := len(word) | |
if lenOfWord <= 3 { continue } | |
if lenOfWord > lenOfSeeds { | |
lenOfSeeds = lenOfWord | |
seeds = rand.Perm(lenOfSeeds) | |
} | |
lastAlphaIndex := findLastAlpha(word, lenOfWord - 1) | |
if lastAlphaIndex == -1 || lastAlphaIndex <= 2 { continue } | |
shuffleWord(word, seeds, 1, lastAlphaIndex - 1) | |
} | |
return bytes.Join(words, []byte(" ")) | |
} | |
func shuffleWord(word []byte, seeds []int, start, end int) { | |
for i := start; i <= end; i++ { | |
j := seeds[i] | |
if j == 0 || j > end { continue } | |
word[i], word[j] = word[j], word[i] | |
} | |
} | |
func findLastAlpha(str []byte, lastIndex int) int { | |
for i := lastIndex; i > 1; i-- { | |
if unicode.IsLetter(rune(str[i])) { return i } | |
} | |
return -1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment