Skip to content

Instantly share code, notes, and snippets.

@fils
Created May 8, 2013 17:26
Show Gist options
  • Save fils/5542047 to your computer and use it in GitHub Desktop.
Save fils/5542047 to your computer and use it in GitHub Desktop.
Working on some Go code to read in weighted relations in a graph (non-directional)
package main
// Reads in a file formated like"
// 8,9,5 // string1, string2, weightInt
// where string1 is a node, string 2 is a node connected
// to string1 by weightInt
// Needs a way to enter the key value relation for
// string1 and string2 (which is not in the data file right now)
import (
"bufio"
"bytes"
"fmt"
graph "github.com/sauerbraten/graph"
"io"
"os"
"strconv"
"strings"
)
func main() {
set := make(map[string]struct{})
g := graph.New()
// Read in the lines
lines, err := readLines("data.graph")
if err != nil {
fmt.Println("Error: %s\n", err)
return
}
// Look for uniques and add them
for _, line := range lines {
lineArray := strings.Split(line, ",")
if _, ok := set[lineArray[0]]; ok {
//fmt.Println("element found")
} else {
fmt.Printf("g.Set with %s\n", lineArray[0])
set[lineArray[0]] = struct{}{}
g.Set(lineArray[0], 678)
}
if _, ok := set[lineArray[1]]; ok {
//fmt.Println("element found")
} else {
fmt.Printf("g.Set with %s\n", lineArray[1])
set[lineArray[1]] = struct{}{}
g.Set(lineArray[1], 678)
}
}
// set the connections with weight
for _, line := range lines {
lineArray := strings.Split(line, ",")
weight, _ := strconv.Atoi(lineArray[2])
g.Connect(lineArray[0], lineArray[1], weight)
fmt.Printf("Setting connections %s %s %d \n", lineArray[0], lineArray[1], weight)
}
neighbors := g.Get("8").GetNeighbors()
for _, n := range neighbors {
fmt.Printf("Found a neighbor %s \n", n.V)
}
}
// Read a whole file into the memory and store it as array of lines
func readLines(path string) (lines []string, err error) {
var (
file *os.File
part []byte
prefix bool
)
if file, err = os.Open(path); err != nil {
return
}
defer file.Close()
reader := bufio.NewReader(file)
buffer := bytes.NewBuffer(make([]byte, 0))
for {
if part, prefix, err = reader.ReadLine(); err != nil {
break
}
buffer.Write(part)
if !prefix {
lines = append(lines, buffer.String())
buffer.Reset()
}
}
if err == io.EOF {
err = nil
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment