Skip to content

Instantly share code, notes, and snippets.

@angch
Created August 19, 2015 16:02
Show Gist options
  • Save angch/866eaaa284e22d1d9b56 to your computer and use it in GitHub Desktop.
Save angch/866eaaa284e22d1d9b56 to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"regexp"
"strconv"
)
func doCluster(input io.Reader) {
re, _ := regexp.Compile("(?i)[0-9]+")
scanner := bufio.NewScanner(input) // was os.Stdin
scanner.Scan()
// I'm getting lazy
scannedText := scanner.Text()
words := re.FindAllStringSubmatch(scannedText, -1)
//maxFriends, _ := strconv.Atoi(words[0][0])
maxPairs, _ := strconv.Atoi(words[1][0])
clusters := make([][]int, 0)
clusterMap := make(map[int]int, 0)
for i := 0; i < maxPairs; i++ {
scanner.Scan()
scannedText := scanner.Text()
words = re.FindAllStringSubmatch(scannedText, -1)
one, _ := strconv.Atoi(words[0][0])
two, _ := strconv.Atoi(words[1][0])
oneIdx, oneInCluster := clusterMap[one]
twoIdx, twoInCluser := clusterMap[two]
if !oneInCluster && !twoInCluser {
newCluster := []int{one, two}
clusters = append(clusters, newCluster)
clusterMap[one] = len(clusters) - 1
clusterMap[two] = len(clusters) - 1
} else if oneInCluster && !twoInCluser {
clusters[oneIdx] = append(clusters[oneIdx], two)
clusterMap[two] = oneIdx
} else if twoInCluser && !oneInCluster {
clusters[twoIdx] = append(clusters[twoIdx], one)
clusterMap[one] = twoIdx
}
}
maxClusterLength := 0
for _, cluster := range clusters {
if len(cluster) > maxClusterLength {
maxClusterLength = len(cluster)
}
}
fmt.Println(maxClusterLength)
}
func main() {
input := bytes.NewBufferString(`5 3
1 2
3 2
4 5`)
doCluster(input)
input = bytes.NewBufferString(`10 12
1 2
3 1
3 4
5 4
3 5
4 6
5 2
2 1
7 10
1 2
9 10
8 9`)
doCluster(input)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment