Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return index of duplicates in list of list in tcl 8.4

Tags:

list

tcl

I have this kind of list : { A D C } { D S D } { A S D } { Y D D }

I want to list all the index that have duplicates in the same index of the sublist. For example if I want to serach every "D" at index 2 in sublist, I want to know the index of the list (here 0 and 3)

here is the code :

proc findElement {lst idx value} {
    set i 0
    foreach sublist $lst {
        if {[string equal [lindex $sublist $idx] $value]} {
            return $i
        }
        incr i
    }
    return -1
}

When i call it findElement $toto 1 D

it returns only 0 !

Why ?

like image 912
heyhey Avatar asked Jan 28 '26 10:01

heyhey


2 Answers

Because you have a return statement when it finds a match when $i = 0.

Try the following which instead returns a list of all the matching indexes

proc findElement {lst idx value} {
    set i 0
    set return_list [list]
    foreach sublist $lst {
       puts "i=$i sublist=$sublist"
        if {[string equal [lindex $sublist $idx] $value]} {
            puts "Found $i"
            lappend return_list $i
        }
        incr i
    }
    return $return_list
}
like image 184
TrojanName Avatar answered Jan 31 '26 05:01

TrojanName


You can do a shorter and faster version with lsearch -all -exact -index.

proc findElement {lst idx value} {
   return [lsearch -all -exact -index $idx $lst $value]
}
like image 24
schlenk Avatar answered Jan 31 '26 04:01

schlenk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!