|
1 | 1 | /*
|
2 |
| -Build a Sieve of Eratosthenes up to a limit |
| 2 | +Determine if two strings are palindromes |
3 | 3 | */
|
4 | 4 |
|
5 | 5 | package main
|
6 | 6 |
|
7 | 7 | import (
|
8 | 8 | "fmt"
|
9 |
| - "math" |
10 | 9 | )
|
11 | 10 |
|
12 | 11 | type test struct {
|
13 |
| - limit float64 |
14 |
| - composite []bool |
| 12 | + str1 string |
| 13 | + str2 string |
| 14 | + result bool |
15 | 15 | }
|
16 | 16 |
|
17 | 17 | var tests []test
|
18 | 18 |
|
19 | 19 | func main() {
|
| 20 | + |
20 | 21 | for _, t := range tests {
|
21 |
| - buildSieve(t) |
22 |
| - fmt.Printf("Primes (limit: %d): ", int(t.limit)) |
23 |
| - for index, val := range t.composite { |
24 |
| - if !val && index > 1 { |
25 |
| - fmt.Printf("%d ", index) |
26 |
| - } |
| 22 | + if isPalindrome(t.str1, t.str2) { |
| 23 | + fmt.Println("Strings" + " " + t.str1 + " " + t.str2 + " are palindromes") |
| 24 | + } else { |
| 25 | + fmt.Println("Strings" + " " + t.str1 + " " + t.str2 + " are not palindromes") |
27 | 26 | }
|
28 |
| - fmt.Println() |
29 | 27 | }
|
30 | 28 | }
|
31 | 29 |
|
32 |
| -func buildSieve(t test) { |
33 |
| - for i := 2; i <= int(math.Sqrt(t.limit)); i = i + 1 { |
34 |
| - if !t.composite[i] { |
35 |
| - for p := 2; ; p++ { |
36 |
| - next := p * i |
37 |
| - if next > int(t.limit) { |
38 |
| - break |
39 |
| - } |
40 |
| - t.composite[next] = true |
41 |
| - } |
| 30 | +func isPalindrome(str1, str2 string) bool { |
| 31 | + len1 := len(str1) |
| 32 | + len2 := len(str2) |
| 33 | + diff := len1 - len2 |
| 34 | + |
| 35 | + if diff != 0 { |
| 36 | + return false |
| 37 | + } |
| 38 | + |
| 39 | + for idx, ch := range str1 { |
| 40 | + pos := len2 - idx - 1 |
| 41 | + if ch != int32(str2[pos]) { |
| 42 | + return false |
| 43 | + } |
| 44 | + if idx >= pos-1 { |
| 45 | + break |
42 | 46 | }
|
43 | 47 | }
|
44 |
| - return |
| 48 | + return true |
45 | 49 | }
|
46 | 50 |
|
47 | 51 | func init() {
|
48 | 52 | tests = make([]test, 0)
|
49 |
| - tests = append(tests, test{10, make([]bool, 11)}) |
50 |
| - tests = append(tests, test{25, make([]bool, 26)}) |
51 |
| - tests = append(tests, test{50, make([]bool, 51)}) |
52 |
| - tests = append(tests, test{100, make([]bool, 101)}) |
| 53 | + tests = append(tests, test{"a", "a", true}) |
| 54 | + tests = append(tests, test{"dad", "dad", true}) |
| 55 | + tests = append(tests, test{"hannah", "hannah", true}) |
| 56 | + tests = append(tests, test{"abe", "normal", false}) |
| 57 | + tests = append(tests, test{"one", "ones", false}) |
| 58 | + tests = append(tests, test{"abba", "abba", true}) |
| 59 | + tests = append(tests, test{"", "", true}) |
| 60 | + |
53 | 61 | }
|
0 commit comments