Sunday, May 6, 2012

DVHint

Code for node1.cpp


#include "stdafx.h"
#include "DV.h"


extern int TRACE;
extern int YES;
extern int NO;

int connectcosts1[4] = { 0,  1,  3, 7};

static distance_table dt;


/* students to write the following two routines, and maybe some others */

void rtinit1()
{
   struct rtpkt  rtpacket;
   // for all destinations y in N:
    for(int j=0;j<4;j++)
  for(int k=0;k<4;k++) dt.costs[j][k] = 999;
   dt.costs[0][0] = connectcosts1[0];
   dt.costs[0][1] = connectcosts1[1];
   dt.costs[0][2] = connectcosts1[2];
   dt.costs[0][3] = connectcosts1[3];

 

   // for each neighbor  source is "me" must change in other files.
   rtpacket.sourceid = 1;
   rtpacket.mincost[0] = dt.costs[rtpacket.sourceid][0];
   rtpacket.mincost[1] = dt.costs[rtpacket.sourceid][1];
   rtpacket.mincost[2] = dt.costs[rtpacket.sourceid][2];
   rtpacket.mincost[3] = dt.costs[rtpacket.sourceid][3];

   for(int i = 0;i<4;i++)
  if ((i!=rtpacket.sourceid)&&(dt.costs[rtpacket.sourceid][i]!=999))
  {
          rtpacket.destid = i;
 tolayer2(rtpacket);
  }
}


void rtupdate1(struct rtpkt *rcvdpkt)
{
   struct rtpkt  rtpacket;
   // the node sending me information is "from" or v in the text on page 383
   int v = rcvdpkt->sourceid;
 

   // x is "me"  the node that i am at.  must change in other files.
   int x = 1;

   //
   bool DV_Changed = false;

   // update the location in my cost table
   dt.costs[v][0] = rcvdpkt->mincost[0];
   dt.costs[v][1] = rcvdpkt->mincost[1];
   dt.costs[v][2] = rcvdpkt->mincost[2];
   dt.costs[v][3] = rcvdpkt->mincost[3];
 
   // The node that sent me information is v;
   // page 383

   // dt.costs os c on page 383 in the text
   int c_v_x = dt.costs[x][v];  // this is part of line 14
   for (int y = 0;y<4;y++)
   {  
  if (y != x)
  {
  int D_x_y = dt.costs[x][y];
           int D_v_y = dt.costs[v][y];
  int new_D_x_y = c_v_x + D_v_y;
  if (new_D_x_y < D_x_y)
  {
  dt.costs[x][y] = new_D_x_y;
               DV_Changed = true;
  }
  }
   }
   if (DV_Changed)
   {
  // tell my neighbors
  rtpacket.sourceid = x;
  rtpacket.mincost[0] = dt.costs[rtpacket.sourceid][0];
  rtpacket.mincost[1] = dt.costs[rtpacket.sourceid][1];
  rtpacket.mincost[2] = dt.costs[rtpacket.sourceid][2];
  rtpacket.mincost[3] = dt.costs[rtpacket.sourceid][3];

  for(int i = 0;i<4;i++)
if ((i!=rtpacket.sourceid)&&(dt.costs[rtpacket.sourceid][i]!=999))
{
rtpacket.destid = i;
tolayer2(rtpacket);
}
   }
}


void printdt1(struct distance_table *dtptr)
 
{
  printf("                via     \n");
  printf("   D0 |    1     2    3 \n");
  printf("  ----|-----------------\n");
  printf("     1|  %3d   %3d   %3d\n",dtptr->costs[1][1],
dtptr->costs[1][2],dtptr->costs[1][3]);
  printf("dest 2|  %3d   %3d   %3d\n",dtptr->costs[2][1],
dtptr->costs[2][2],dtptr->costs[2][3]);
  printf("     3|  %3d   %3d   %3d\n",dtptr->costs[3][1],
dtptr->costs[3][2],dtptr->costs[3][3]);
}