-
Notifications
You must be signed in to change notification settings - Fork 0
/
day4-2.go
73 lines (68 loc) · 1.25 KB
/
day4-2.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main
import (
"bufio"
"fmt"
"os"
"sort"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
sum := 0
for {
exists := false
fmt.Print("Enter text: ")
text, _ := reader.ReadString('\n')
text = strings.TrimRight(text, "\r\n")
if strings.Compare(text, "end") == 0 {
break
} else if len(text) == 0 {
continue
}
encountered := map[string]int{}
password := strings.Fields(text)
for i := range password {
if encountered[password[i]] > 0 { // base anagram
exists = true
break
}
for j := range password {
if j == i {
continue
}
if isAnagram(password[i], password[j]) {
exists = true
fmt.Println("Anagram found: ", password[i], password[j])
break
}
}
if exists {
break
}
encountered[password[i]] = 1
}
if exists {
fmt.Println("Bad password Sum:", sum)
continue
} else {
sum++
fmt.Println("Good password Sum:", sum)
}
}
}
func isAnagram(old, newer string) bool {
if len(old) != len(newer) {
return false
}
old = SortString(old)
newer = SortString(newer)
if strings.Compare(old, newer) == 0 {
return true
}
return false
}
func SortString(s string) string {
newS := strings.Split(s, "")
sort.Strings(newS)
return strings.Join(newS, "")
}