tcl:根据数组排序列表

tcl: sorting list depending on array

如果List1是:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

array1是:

{3 4 5} {12 13} {20 21}

如何通过替换 array1 的每个元素的反向列表,根据 array1 转换 list1,即生成此 输出:

1 2 5 4 3 6 7 8 9 10 11 13 12 14 15 16 17 18 19 21 20 22 23 24 25
    ^^^^^               ^^^^^                   ^^^^^

这不是排序任务,这是搜索任务。

如果您假设要反转的范围不重叠,但也不一定存在(即 not 使用它们是连续数字的事实),您会得到一些东西像这样:

# Iterate over each of the replacement patterns
foreach range $array1 {
    # Iterate over each of the locations where the first element of the current
    # replacement pattern is found
    foreach pos [lsearch -all -exact $list1 [lindex $range 0]] {
        # This will be the index of the *last* element in each subrange
        set pos2 [expr {$pos + [llength $range] - 1}]

        # Do the reversed replacement if the ranges match
        if {[lrange $list1 $pos $pos2] eq $range} {
            set list1 [lreplace $list1 $pos $pos2 {*}[lreverse $range]]
        }
    }
}

这之后的结果将在 updated list1 变量中。包装成过程留作练习。