2017 Day 4 Complete!
This commit is contained in:
91
2017/day04/day04.go
Normal file
91
2017/day04/day04.go
Normal file
@@ -0,0 +1,91 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func main() {
|
||||
inp := StdinToStrings()
|
||||
part1(inp)
|
||||
part2(inp)
|
||||
}
|
||||
|
||||
func part1(inp []string) {
|
||||
fmt.Println("== Part 1 ==")
|
||||
cnt := 0
|
||||
for _, v := range inp {
|
||||
wrds := strings.Split(v, " ")
|
||||
isGood := true
|
||||
for i := range wrds {
|
||||
for j := i + 1; j < len(wrds); j++ {
|
||||
if wrds[i] == wrds[j] {
|
||||
isGood = false
|
||||
}
|
||||
if !isGood {
|
||||
break
|
||||
}
|
||||
}
|
||||
if !isGood {
|
||||
break
|
||||
}
|
||||
}
|
||||
if isGood {
|
||||
cnt++
|
||||
}
|
||||
}
|
||||
fmt.Println("Valid Passphrases:", cnt)
|
||||
}
|
||||
|
||||
func part2(inp []string) {
|
||||
fmt.Println("== Part 2 ==")
|
||||
cnt := 0
|
||||
for _, v := range inp {
|
||||
wrds := strings.Split(v, " ")
|
||||
isGood := true
|
||||
for i := range wrds {
|
||||
for j := i + 1; j < len(wrds); j++ {
|
||||
if isAnagram(wrds[i], wrds[j]) {
|
||||
isGood = false
|
||||
}
|
||||
if !isGood {
|
||||
break
|
||||
}
|
||||
}
|
||||
if !isGood {
|
||||
break
|
||||
}
|
||||
}
|
||||
if isGood {
|
||||
cnt++
|
||||
}
|
||||
}
|
||||
fmt.Println("Valid Passphrases:", cnt)
|
||||
}
|
||||
|
||||
func isAnagram(wrd1, wrd2 string) bool {
|
||||
charMap := make(map[byte]int)
|
||||
for i := range wrd1 {
|
||||
charMap[wrd1[i]]++
|
||||
}
|
||||
for i := range wrd2 {
|
||||
charMap[wrd2[i]]--
|
||||
}
|
||||
for _, v := range charMap {
|
||||
if v != 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func StdinToStrings() []string {
|
||||
var input []string
|
||||
scanner := bufio.NewScanner(os.Stdin)
|
||||
for scanner.Scan() {
|
||||
input = append(input, scanner.Text())
|
||||
}
|
||||
return input
|
||||
}
|
||||
Reference in New Issue
Block a user