views:

1427

answers:

3
public static List<Vertex<Integer>> petersenGraph()
{
    List<Vertex<Integer>> v = new ArrayList<Vertex<Integer>>();

    for (int i = 0; i < 10; i++)
    {
        v.add(new Vertex<Integer>(i));
    }

    int[][] edges =
    {{0,1}, {1,0}, {1,2}, {2,1}, {2,3}, {3,2}, {3,4}, {4,3}, {4,0}, {0,4},
    {5,6}, {6,5}, {6,7}, {7,6}, {7,8}, {8,7}, {8,9}, {9,8}, {9,5}, {5,9},
    {5,0}, {0,5}, {6,2}, {2,6}, {7,4}, {4,7}, {8,1}, {1,8}, {9,3}, {3,9}};

    for (int[] e : edges)
     v.get(e[0]).successors().add(v.get(e[1]));

    return v;
}

I understand everything up to the point where there's the for which iterates over the edges. What is exactly is going on there?

edit: why are they accessed using e[0] and e[1]? is e[0] the first number and e[1] the second?

A: 

The multi-dimensional array edges is effectively an "array of arrays." The for statement is extracting one element from edges at a time, and each element of edges is an int[].

So the first time through the loop, e will be {0, 1}. The second time it will be {1, 0}. The third time it will be {1, 2}. And so on.

Sean Bright
+1  A: 

Argh, that's ugly.

edges is a bidimensional array, so it is an array of int arrays. In the actual definition, it is an array of pairs.

The line for (int[] e: edges) simply means that in each iteration, e will become a different array of ints, so in each iteration it is a different pair.

Then, e[0] represents the first item in the pair and e[1] represents the other. So the first coordinate is used to look up a vertex, and then something happens and the second coordinate gets added in. Without seeing vertex or knowing the algorithm, it's unclear.

Uri
A: 

The wikipedia page on the graph it's creating is http://en.wikipedia.org/wiki/Petersen_graph.

From the look of it, edges in the graph are represented by the Vertex.successors collection, and the edges array is used to construct the graph, using the first index as the from node and the second index as the to node for each edge.

This would also explain why each pair is followed by its opposite, eg {0,1}, {1,0}, as the Peterson Graph is undirected, so connections between nodes must be represented in both directions.

MHarris