Skip to content

Instantly share code, notes, and snippets.

@alex-quiterio
Created August 3, 2014 00:14
Show Gist options
  • Save alex-quiterio/ca4515b7cbad016e6da5 to your computer and use it in GitHub Desktop.
Save alex-quiterio/ca4515b7cbad016e6da5 to your computer and use it in GitHub Desktop.
Simple programming exercise with unionSets
package main
import "fmt"
type Set struct {
pos int
value int
}
func makeSet(position int, value int) Set {
return Set{position, value}
}
func findSet(setA Set, unionList [][]Set) (*[]Set, [][]Set) {
for i := 0; i < len(unionList); i++ {
for _, set := range(unionList[i]) {
if set.pos == setA.pos {
return &unionList[i], unionList
}
}
}
newUnion := []Set{setA}
newList := append(unionList, newUnion)
return &newUnion, newList
}
func unionSet(union *[]Set, set Set) {
*union = append(*union, set)
}
func validUnion(union []Set, startPos int, endPos int) bool {
return (union[0].pos != startPos) && (union[len(union)-1].pos != endPos)
}
func validMerge(unionA []Set, setB Set) bool {
lastSet := unionA[len(unionA)-1]
return (lastSet.pos < setB.pos) && (lastSet.pos + 1 == setB.pos)
}
func getExtremes(area []int) (int, int) {
min := 100000
max := 0
for _, value := range area {
if min > value {
min = value
}
if max < value {
max = value
}
}
return min, max
}
func waterRetention(area []int) int {
var setList []Set
var unionA *[]Set
var unionList [][]Set
total := 0
min, max := getExtremes(area)
for max >= min {
setList = make([]Set, 0)
unionList = make([][]Set, 0)
for index, value := range area {
if value <= min {
setList = append(setList, makeSet(index, value))
}
}
for _, setA := range setList {
for _, setB := range setList {
unionA, unionList = findSet(setA, unionList)
if validMerge(*unionA, setB) {
unionSet(unionA, setB)
}
}
}
for _, union := range unionList {
if validUnion(union, 0, ) {
total += len(union)
}
}
min += 1
}
fmt.Printf("[W] Total Retained Water Value: %d!\n", total)
return total
}
func main () {
waterRetention([]int{ 2, 5, 1, 2, 3, 4, 7, 7, 6 })
waterRetention([]int{ 2, 5, 1, 2, 3, 4, 7, 7, 6, 5, 4, 4, 4, 2, 3 })
waterRetention([]int{ 2, 5, 1, 3, 1, 2, 1, 7, 7, 6 })
waterRetention([]int{ 2, 7, 2, 7, 4, 7, 1, 7, 3, 7 })
waterRetention([]int{ 7, 7, 7, 2, 7, 7, 7, 7, 7, 7, 7 })
waterRetention([]int{ 6, 7, 7, 4, 3, 2, 1, 5, 2 })
waterRetention([]int{ 2, 5, 1, 2, 3, 4, 7, 6, 2, 7, 1, 2, 3, 4, 5, 4 })
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment