Skip to content

Commit

Permalink
ex03
Browse files Browse the repository at this point in the history
  • Loading branch information
Shunpoco committed Feb 4, 2021
1 parent b474b02 commit 9166487
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 0 deletions.
3 changes: 3 additions & 0 deletions ch11/ex03/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module ch11/ex03

go 1.15
43 changes: 43 additions & 0 deletions ch11/ex03/random_word_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package word

import (
"math/rand"
"testing"
"time"
)

func randomPalindrome(rng *rand.Rand) string {
n := rng.Intn(25) // random length up to 24
runes := make([]rune, n)
for i := 0; i < (n+1)/2; i++ {
r := rune(rng.Intn(0x1000)) // random rune up to '\u0999'
runes[i] = r
runes[n-1-i] = r
}
return string(runes)
}

func randomNonPalindrome(rng *rand.Rand) string {
n := rng.Intn(23) + 3
runes := make([]rune, n)
for i := 0; i < (n+1)/2; i++ {
r1 := rune(65 + rng.Intn(13))
r2 := rune(78 + rng.Intn(13))
runes[i] = r1
runes[n-1-i] = r2
}
return string(runes)
}

func TestRandomPalindrome(t *testing.T) {
seed := time.Now().UTC().UnixNano()
t.Logf("Random seed: %d", seed)
rng := rand.New(rand.NewSource(seed))

for i := 0; i < 1000; i++ {
p := randomNonPalindrome(rng)
if IsPalindrome(p) {
t.Errorf("IsPalindrome(%q) = true", p)
}
}
}
20 changes: 20 additions & 0 deletions ch11/ex03/word.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package word

import (
"unicode"
)

func IsPalindrome(s string) bool {
var letters []rune
for _, r := range s {
if unicode.IsLetter(r) {
letters = append(letters, unicode.ToLower(r))
}
}
for i := range letters {
if letters[i] != letters[len(letters)-1-i] {
return false
}
}
return true
}

0 comments on commit 9166487

Please sign in to comment.