Sign in to follow this  
duHOSSval

Weighted Graph using a matrix

Recommended Posts

duHOSSval    122
I'm having a small problem implementing my weighted graph. I have a class called Graphs, and from there i created a class for a graph using a matrix, a graph using a linked list, and now im creating a graph that is weighted. I'll put what i have for my weighted class below. Basically what im having trouble with is i dont seem to be getting random numbers for my "weights". In my main method i have this, where c is the weight being randomized.
[/Random rand = new Random( 37 );
    for( i = 0; i < E; i++ )
    {
      a = rand.nextInt( V );
      b = rand.nextInt( V );
      c = rand.nextInt( V );
      gm.addEdge( a , b );
      gl.addEdge( a, b );
      wgm.addEdge(a, b, c );
    }]

gm and gl are for the other classes so just disregard those.  the wgm.addEdge is my method for adding an edge, a and b are setting the vertices and those work fine.  Here is the rest of my code for the weighted class, any suggestions would be great.

[/class WGraphM extends Graphs
{
  int data[][];
  int V;
  
  public WGraphM()
  {
    data = new int [10][10];
  }
  public WGraphM(int v)
  {
    V = v;
    data = new int [V][V];
    for(int i = 0; i < V; i++)
    {
      for( int j = 0; j < V; j++)
      {
        data[i][j] = 1;
      }
    }
  }
  public void addEdge(int a, int b, int c)
  {
    data[a][b] = c;
    data[b][a] = c;
  }
  
  public void deleteEdge(int a, int b)
  {
    data[a][b] = 0;
    data[b][a] = 0;
  }
  public int adjacent( int a, int b)
  {
    return data[a][b];
  }
  public void display()
  {
    for( int i = 0; i < V; i++)
    {
      System.out.print(i + ": ");
      for(int j = 0; j < V; j++)
      {
        if(data[i][j] > 0)
        {
          System.out.print(j + " ");
        }
      }
      System.out.println();
    }
  }
}]

also trying, in my display method, to display the weight with each edge.  Any help will be greatly appriciated.

Share this post


Link to post
Share on other sites
dwahler    313
What output are you getting, and what output do you expect?

If you're saying the output is the same every time you run the program, then that's to be expected; you're giving the RNG the same seed each time.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this