“随机漫步”算法如何工作?

时间:2014-04-09 06:49:58

标签: algorithm routing pseudocode tor

下面的算法是用伪代码编写的,为简单起见,不包括在数据结构中存储实际路由。

LengthFromSrc   = 0;
    LengthFromDest  = 0;
    TotalNumberHops = 0;

    X = SRC;  /*Last Node Visited from Random walk starting at SRC;*/
    Y = DEST; /*Last Node Visited from Random walk starting at DEST;*/
    /* Randomly select a route length */
    do {
        Length = rand( ) % Max;
        while( Length < Min );


    while( TotalNumberHops < Length ) {           

      Next = Toss Coin to Pick Random Walk from Src or from Dest;

      if( Next == RandWalkFromSrc ) {
      Z = Randomly select an adjacent node to X;
      TotalNumberHops = 1 + LengthFromSrc + LengthFromDest
                            + shortest-path from Z to Y; 
      if( TotalNumberHops > Length )  
          break;
      X = Z;            /*include the node in the route*/
              Store X in the route data structure 
          LengthFromSrc++;
      }
      else {  /* Next = RandWalkFromDest */
      Z = Randomly select an adjacent node to Y;
      TotalNumberHops = 1 + LengthFromSrc + LengthFromDest
                            + shortest-path from Z to X; 
      if( TotalNumberHops > Length )  
          break;
      Y = Z;            
              Store Y in the route data structure 
          LengthFromDest++;
       }
      }

有人会给我一个简要的算法分析/或者告诉我代码,因为我想更好地理解它吗?我的主要问题是理解第一部分:

      do {
          Length = rand( ) % Max;
          while( Length < Min );


          while( TotalNumberHops < Length )

PS:我的来源是http://www.onion-router.net/Archives/Route/

1 个答案:

答案 0 :(得分:0)

我会说代码缺少}(尽管它是伪代码,所以一切都真的发生了)

do {
    Length = rand() % Max;
}
while( Length < Min );

rand()a function is C++,它生成一个介于0和最小32767之间的整数(尽管出于此目的,我认为我们应该假设可以生成的最大数量大于{ {1}})。

Max会将剩余的数字除以% Max,因此Max将介于Length0之间(包括)。

然后重复此操作直到Max-1,最后,Length >= Min将在LengthMin之间(包括在内)。

我们可以完全避免使用此代码的循环:

Max-1

或者,因为这是伪代码:

Length = Min + rand() % (Max - Min);

其余代码从源和目标同时生成两条路径,然后在链接它们时停止(使用最短路径)会导致行走时间超过Length = random number in the range [Min, Max)