Divide list with the single number in tcl NS-2

663 Views Asked by At

i want to divide the whole list with one number.Lets say i take a variable $Content and i want to divide the following list with the 300 nodes. so i take the command $Content/300

  1. $Content= {1 2 3 4 5}{ 2 3 4 5 6} { 4 5 6 7 8 9}{3 4 6 8 9 0}

As a result output comes out {1 2 3 4 5}{ 2 3 4 5 6} { 4 5 6 7 8 9}{3 4 6 8 9 0}/300 with the parenthesis missing and invalid arguments.

Please tell me how we divide all list with the single number(300 nodes) because in curly brackets each number comes as an output of some arguments

1

There are 1 best solutions below

11
glenn jackman On

Note that Tcl is a very whitespace-sensitive language, so you need a space between the close and open braces in your $Content declaration.

You can iterate over $Content, and for each sublist, iterate over the elements and divide by 300, collecting the results:

set Content {{1 2 3 4 5} { 2 3 4 5 6} { 4 5 6 7 8 9} {3 4  6 8 9 0}}
# note the spaces ......^............^..............^
set divisor 300
set newContent [list]
foreach sublist $Content {
    set newSublist [list]
    foreach elem $sublist {
        lappend newSublist [expr {$elem * 1.0 / $divisor}]
    }
    lappend newContent $newSublist
}
puts $newContent

Output is

{0.0033333333333333335 0.006666666666666667 0.01 0.013333333333333334 0.016666666666666666} {0.006666666666666667 0.01 0.013333333333333334 0.016666666666666666 0.02} {0.013333333333333334 0.016666666666666666 0.02 0.023333333333333334 0.02666666666666667 0.03} {0.01 0.013333333333333334 0.02 0.02666666666666667 0.03 0.0}

If your Tcl version is 8.6 you can use the lmap command to shorten up the code:

set newContent [lmap sublist $Content {
    lmap elem $sublist {expr {$elem * 1.0 / $divisor}}
}]

Note that I multiply by 1.0 in order to use float division and not integer division.