Exemplo n.º 1
0
// CreateGraphFromFile takes a path as a parameter and creates rewards, nodes and edges before
// returning a pointer to a graph.
func CreateGraphFromFile(path string) (*m.Graph, error) {
	file, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}

	var g graph
	err = json.Unmarshal(file, &g)
	if err != nil {
		return nil, err
	}

	rewards := make(map[string]*m.Reward)
	//ugly loop to make sure to handle different ordered rewards
	for rewardAdded := true; rewardAdded == true; {
		rewardAdded = false
		for _, r := range g.Rewards {
			if rewards[r.ID] == nil && (r.IsA == "" || rewards[r.IsA] != nil) {
				rewards[r.ID] = m.CreateReward(r.ID, r.Unique, rewards[r.IsA])
				rewardAdded = true
			}
		}
	}

	nodes := make(map[string]*m.Node)
	for _, n := range g.Nodes {
		node := m.CreateNode(n.ID, n.Revisitable)
		for _, rewardRef := range n.Rewards {
			node.AddReward(rewards[rewardRef.RewardID], getPointerValueOrOne(rewardRef.Quantity)) //duplicate code
		}
		nodes[node.ID()] = node
	}

	for _, e := range g.Edges {
		edge := m.CreateEdge(nodes[e.From], nodes[e.To])
		for _, w := range e.Weights {
			time, err := parseTime(w.Time)
			if err != nil {
				return nil, err
			}
			weight := m.CreateWeight(time)
			for _, rewardRef := range w.Requirements {
				weight.AddRequirement(rewards[rewardRef.RewardID], getPointerValueOrOne(rewardRef.Quantity)) //duplicate code
			}
			edge.AddWeight(weight)
		}
	}
	return m.CreateGraph(nodes[g.StartID], nodes[g.EndID]), nil
}
Exemplo n.º 2
0
func createWeightedEdge(from, to *m.Node, time int) *m.Edge {
	edge := m.CreateEdge(from, to)
	edge.AddWeight(m.CreateWeight(rand.Intn(10000) + 1))
	return edge
}