001    /*
002    Galois, a framework to exploit amorphous data-parallelism in irregular
003    programs.
004    
005    Copyright (C) 2010, The University of Texas at Austin. All rights reserved.
006    UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS SOFTWARE
007    AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR ANY
008    PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF PERFORMANCE, AND ANY
009    WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF DEALING OR USAGE OF TRADE.
010    NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH RESPECT TO THE USE OF THE
011    SOFTWARE OR DOCUMENTATION. Under no circumstances shall University be liable
012    for incidental, special, indirect, direct or consequential damages or loss of
013    profits, interruption of business, or related expenses which may arise from use
014    of Software or Documentation, including but not limited to those resulting from
015    defects in Software and/or Documentation, or loss or inaccuracy of data of any
016    kind.
017    
018    File: Graphs.java 
019    
020     */
021    
022    package galois.objects.graph;
023    
024    import galois.objects.GObject;
025    import util.Launcher;
026    import util.MutableInteger;
027    import util.MutableReference;
028    import util.fn.LambdaVoid;
029    
030    /**
031     * This class contains static utility methods that operate on or return objects of type {@link Graph}
032     */
033    public class Graphs {
034    
035      /**
036       * Retrieves a random node from the graph.
037       * @param graph the graph to choose the node from
038       * @param <N> the type of the data contained in a node
039       * @return a random vertex contained in the indicated graph
040       */
041      public static <N extends GObject> GNode<N> getRandom(Graph<N> graph) {
042        return getRandom(graph, graph.size());
043      }
044    
045      /**
046       * Retrieves a random node from the graph.
047       * @param graph the graph to choose the node from
048       * @param seed a seed used to initialize the random generator
049       * @param <N> the type of the data contained in a node
050       * @return a random vertex contained in the indicated graph
051       */
052      public static <N extends GObject> GNode<N> getRandom(Graph<N> graph, int seed) {
053        final int size = graph.size();
054        final int random = Launcher.getLauncher().getRandom(seed).nextInt(size);
055        final MutableInteger counter = new MutableInteger(0);
056        final MutableReference<GNode<N>> ret = new MutableReference<GNode<N>>();
057        graph.map(new LambdaVoid<GNode<N>>() {
058          @Override
059          public void call(GNode<N> node) {
060            if (counter.getAndIncrement() == random) {
061              ret.set(node);
062            }
063          }
064        });
065        return ret.get();
066      }
067    }