2017-06-21 31 views
1

我在NS2中有下面的代碼,它計算兩個節點之間的距離並將其放入列表「nbr」中。我想按照值「d」的升序對列表進行整理,然後再次將它存儲在一個列表中以供進一步使用,因爲我使用了lsort命令,但它給了我相同的未排序列表。 請幫忙無法在tcl中對列表進行排序

code :.

proc distance { n1 n2 nd1 nd2} { 
    set x1 [expr int([$n1 set X_])] 
    set y1 [expr int([$n1 set Y_])] 
    set x2 [expr int([$n2 set X_])] 
    set y2 [expr int([$n2 set Y_])] 
    set d [expr int(sqrt(pow(($x2-$x1),2)+pow(($y2-$y1),2)))] 
    if {$d<300} { 
     if {$nd2!=$nd1 && $nd2 == 11} { 
      set nbr "{$nd1 $nd2 $x1 $y1 $d}" 
      set m [lsort -increasing -index 4 $nbr] 
      puts $m 
     } 
    } 
} 

for {set i 1} {$i < $val(nn)} {incr i} { 
    for {set j 1} {$j < $val(nn)} {incr j} { 
     $ns at 5.5 "distance $node_($i) $node_($j) $i $j" 
    } 
} 

輸出:

{1 11 305 455 273} 
{4 11 308 386 208} 
{5 11 378 426 274} 
{7 11 403 377 249} 
{8 11 244 405 215} 
{9 11 256 343 154} 
{10 11 342 328 172} 
{12 11 319 192 81} 
{13 11 395 196 157} 
{14 11 469 191 231} 
{15 11 443 140 211} 
{16 11 363 115 145} 
{17 11 290 135 75} 
{18 11 234 121 69} 
{19 11 263 60 132} 
{20 11 347 60 169} 

回答

1

現在,你分別計算每一個距離,但實際上並沒有收集他們全​​部轉換爲可排序的列表。

讓我們首先重寫distance只是做了距離計算自己解決這個問題:

proc distance {n1 n2 nd1 nd2} { 
    set x1 [expr int([$n1 set X_])] 
    set y1 [expr int([$n1 set Y_])] 
    set x2 [expr int([$n2 set X_])] 
    set y2 [expr int([$n2 set Y_])] 

    set d [expr int(sqrt(pow(($x2-$x1),2)+pow(($y2-$y1),2)))] 
    # Why not: set d [expr hypot($x2-$x1,$y2-$y1)] 

    # I'm keeping *everything* we know at this point 
    return [list $nd1 $nd2 $n1 $n2 $d $x1 $y1 $x2 $y2] 
} 

然後,我們需要另外一個程序將處理整個集合(在模擬器調用它的時間)和做排序。由於我們已將這些信息計算在內,因此它會撥打distance獲取個人記錄。

proc processDistances {count threshold {filter ""}} { 
    global node_ 
    set distances {} 
    for {set i 1} {$i < $count} {incr i} { 
     for {set j 1} {$j < $count} {incr j} { 
      # Skip self comparisons 
      if {$i == $j} continue 

      # Apply target filter 
      if {$filter ne "" && $j != $filter} continue 

      # Get the distance information 
      set thisDistance [distance $node_($i) $node_($j) $i $j] 

      # Check that the nodes are close enough 
      if {[lindex $thisDistance 4] < $threshold} { 
       lappend distances $thisDistance 
      } 
     } 
    } 

    # Sort the pairs, by distances 
    set distances [lsort -real -increasing -index 4 $distances] 

    # Print the sorted list 
    foreach tuple $distances { 
     puts "{$tuple}" 
    } 
} 

然後我們安排的是全過程,在正確的時間被稱爲:

# We recommend building callbacks using [list], not double quotes 
$ns at 5.5 [list processDistances $val(nn) 300 11] 
+0

謝謝你這麼多的help.I多了一個question.I要訪問外部的程序這個排序列表。就像我必須'lassign [lindex $ sortedfile 0 2] a'..我應該調用代替「$ sortedfile」的文件 –

+0

我試圖使用距離文件即外部程序使用全局排序列表。我在'set distance'後面創建了一個更多的變量,使其成爲全局變量,並將距離文件分配給該變量。但是,當我在程序外部使用該文件時,發生錯誤'不能讀取'文件':no such variable' –