Home > other >  Find Max Element in a list by comparing value of each element in Tcl
Find Max Element in a list by comparing value of each element in Tcl

Time:01-27

I am trying to sort a list and find the max value by comparing each element of the list with every other element using simple command and not inbuilt commands.

For Example:

    set a 9 ; set b 2 ; set c 11; set d 1
    
    set list [list $a $b $c $d]
    
    set max [tcl::mathfunc::max {*}$list]

    11

This returns answer as 11 correctly

but when I do this:

for {set i 0} {$i < [llength $list]}  {incr i} {
    set tmp1 [lindex $list  $i]
    set tmp2  [lindex $list  $i 1]
    if {$tmp1 > $tmp2 } {
        set results $tmp1
    } else {
    set results $tmp2
    }
}

I get "puts $results" as 1

I try to print all variable values and see tmp1 becomes 1 in the end.

tmp1: 9 i: 0 tmp2: 2
tmp1: 2 i: 1 tmp2: 11
tmp1: 11 i: 2 tmp2: 1
tmp1: 1 i: 3 tmp2:

Please advise what I am doing wrong.

Thanks in advance

CodePudding user response:

As this is a learning exercise for you, I'm not going to give a complete answer.

You sort integers using lsort -integer. Then you can use lindex to pick a value from that; you might find either the index 0 (the first value) or end (the last value) rather helpful.

Alternatively, the standard way to loop over a list of values is with foreach, and this leads to this natural way to find the maximum:

foreach val $values {
    if {$val > $max} {
        set max $val
    }
}

However, you need to think what the initial value of max should be; what does it mean to be less than everything else? What is the maximum of an empty list?


The method in the question is totally how I'd find the maximum, provided I needed just that. If I need anything more complex, I'd probably do a linear scan unless I have information about whether the list is sorted.

  •  Tags:  
  • Related