func main() { var inputfile string // Get the input file if sent as command line argument or use default flag.StringVar(&inputfile, "input", "input.txt", "<NAME OF INPUT FILE>") flag.Parse() file, err := os.Open(inputfile) if err != nil { log.Fatal(err) } defer file.Close() scanner := bufio.NewScanner(file) scanner.Scan() line := scanner.Text() inputs := strings.Fields(line) numnodes, _ := strconv.Atoi(inputs[0]) uf := unionfind.New(numnodes) edges := make(EdgesSorted, 0) heap.Init(&edges) for scanner.Scan() { line = scanner.Text() if len(line) == 0 { continue } inputs = strings.Fields(line) source, err := strconv.Atoi(inputs[0]) if err != nil { log.Fatal("Wrong format") } destination, err := strconv.Atoi(inputs[1]) if err != nil { log.Fatal("Wrong format") } weight, err := strconv.Atoi(inputs[2]) if err != nil { log.Fatal("Wrong format") } heap.Push(&edges, &Edge{source, destination, weight}) } MST := make([]*Edge, 0) for edges.Len() > 0 && uf.GetNumClusters() > 1 { edgeout := heap.Pop(&edges).(*Edge) if uf.Connected(edgeout.source, edgeout.peer) != true { uf.Union(edgeout.source, edgeout.peer) MST = append(MST, edgeout) } } if uf.GetNumClusters() > 1 { fmt.Println("Could not get Minimum Spanning Tree") } else { for x := range MST { fmt.Println("Edges in MST") fmt.Println(*MST[x]) } } }
func main() { var inputfile string // Get the input file if sent as command line argument or use default flag.StringVar(&inputfile, "input", "input.txt", "<NAME OF INPUT FILE>") flag.Parse() //fmt.Println(inputfile) file, err := os.Open(inputfile) if err != nil { log.Fatal(err) } defer file.Close() scanner := bufio.NewScanner(file) scanner.Scan() line := scanner.Text() //fmt.Println(line) inputs := strings.Fields(line) //fmt.Println(inputs) grid_x, _ = strconv.Atoi(inputs[0]) // fmt.Println("Grid dimension", grid_x) grid_dim = grid_x * grid_x upper = grid_dim + 1 lower = grid_dim + 2 uf := unionfind.New(lower) opened := make([]bool, lower) for entry := range opened { opened[entry] = false } // inputs = inputs[1:] //for i := 0; i < len(inputs); i = i + 2 { linenum := 0 for scanner.Scan() { line = scanner.Text() //fmt.Println(line) if len(line) == 0 { continue } inputs = strings.Fields(line) linenum++ //fmt.Println("---") x, err := strconv.Atoi(inputs[0]) if err != nil { log.Fatal(linenum, err) } y, err := strconv.Atoi(inputs[1]) if err != nil { log.Fatal(linenum, err) } if !isvalidinput(grid_x, x, y) { continue } open(uf, opened, x, y) } //fmt.Println(opened) fmt.Println(uf.Connected(upper-1, lower-1)) draw(uf, grid_x, opened) //fmt.Println(uf) }