2020-05-10

Tcl: List Rotation

#!/usr/bin/tclsh
#
# Given a length-n list like (a b c d e), the rotations of the list are
# the n lists (a b c d e), (b c d e a), (c d e a b), (d e a b c), and (e a b c d), 
# in any order.
#
if {$argc == 0} {
    puts "Please input a string"
    exit
}

set len [llength $argv]
set rorateList $argv
for {set index 0} {$index < $len} {incr index} {
    puts $rorateList
    set first [lindex $rorateList 0]
    set rorateList2 [lrange $rorateList 1 [expr $len - 1]]
    lappend rorateList2 $first
    set rorateList $rorateList2
}

使用 lindex 取得頭以後,中間部份使用 lrange 取得,然後再排列出來。

沒有留言: