zerodb
zerodb

Reputation: 61

Split a list of numbers into smaller list based on a range in TCL

I have a sorted list of numbers and I am trying to split the list into smaller lists based on range of 50 and find the average in TCL.

For eg: set xlist {1 2 3 4 5 ...50 51 52 ... 100 ... 101 102}

split lists: {1 ... 50} { 51 .. 100} {101 102}

result: sum(1:50)/50; sum(51:100)/50; sum(101:102)/2

Upvotes: 0

Views: 990

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137577

The lrange command is the core of what you need here. Combined with a for loop, that'll give you the splitting that you're after.

proc splitByCount {list count} {
    set result {}
    for {set i 0} {$i < [llength $list]} {incr i $count} {
        lappend result [lrange $list $i [expr {$i + $count - 1}]]
    }
    return $result
}

Testing that interactively (with a smaller input dataset) looks good to me:

% splitByCount {a b c d e f g h i j k l} 5
{a b c d e} {f g h i j} {k l}

The rest of what you want is a trivial application of lmap and tcl::mathop::+ (the command form of the + expression operator).

set sums [lmap sublist [splitByCount $inputList 50] {
    expr {[tcl::mathop::+ {*}$sublist] / double([llength $sublist])}
}]

We can make that slightly neater by defining a custom function:

proc tcl::mathfunc::average {list} {expr {
    [tcl::mathop::+ 0.0 {*}$list] / [llength $list]
}}

set sums [lmap sublist [splitByCount $inputList 50] {expr {
    average($sublist)
}}]

(I've moved the expr command to the previous line in the two cases so that I can pretend that the body of the procedure/lmap is an expression instead of a script.)

Upvotes: 2

Related Questions