試著使用 Tcl 解 Longest Consecutive Sequences 問題。
#!/usr/bin/env tclsh
#
# You are given an unsorted array of integers.
# Write a script to find the longest consecutive sequence.
# Print 0 if none sequence found.
#
if {$argc <= 1} {
puts "Please input a list."
exit
}
# To compare two list's length
proc mysortproc {x y} {
set len1 [llength $x]
set len2 [llength $y]
if {$len1 > $len2} {
return -1
} elseif {$len1 < $len2} {
return 1
} else {
return 0
}
}
set len [llength $argv]
set mylist [lsort -integer $argv]
set last [lindex $mylist 0]
set index 0
set results [list]
lset results $index [list $last]
for {set count 1} {$count < $len} {incr count} {
set current [lindex $mylist $count]
if {$current != [expr $last + 1]} {
incr index
}
set indexlist [lindex $results $index]
set indexlist [lappend indexlist $current]
lset results $index $indexlist
set last $current
}
# Sort our results by using sublists's length
set results [lsort -command mysortproc $results]
if {[llength [lindex $results 0]] > 1} {
puts [lindex $results 0]
} else {
puts 0
}
如果要使用 anonymous function,則可以改寫如下:
#!/usr/bin/env tclsh
#
# You are given an unsorted array of integers.
# Write a script to find the longest consecutive sequence.
# Print 0 if none sequence found.
#
if {$argc <= 1} {
puts "Please input a list."
exit
}
set len [llength $argv]
set mylist [lsort -integer $argv]
set last [lindex $mylist 0]
set index 0
set results [list]
lset results $index [list $last]
for {set count 1} {$count < $len} {incr count} {
set current [lindex $mylist $count]
if {$current != [expr $last + 1]} {
incr index
}
set indexlist [lindex $results $index]
set indexlist [lappend indexlist $current]
lset results $index $indexlist
set last $current
}
# Sort our results by using sublists's length
set results [lsort -command {apply {{x y} {
set len1 [llength $x]
set len2 [llength $y]
if {$len1 > $len2} {
return -1
} elseif {$len1 < $len2} {
return 1
} else {
return 0
}
}}} $results]
if {[llength [lindex $results 0]] > 1} {
puts [lindex $results 0]
} else {
puts 0
}
也可以使用其它的方式,直接記錄 Longest Consecutive Sequences 的排序,如下所示:
#!/usr/bin/env tclsh
#
# You are given an unsorted array of integers.
# Write a script to find the longest consecutive sequence.
# Print 0 if none sequence found.
#
if {$argc <= 1} {
puts "Please input a list."
exit
}
set len [llength $argv]
set mylist [lsort -integer $argv]
set last [lindex $mylist 0]
set index 0
set curresult [list $last]
set maxresult [list $last]
set curval 1
set maxval 1
for {set count 1} {$count < $len} {incr count} {
set current [lindex $mylist $count]
if {$current == [expr $last + 1]} {
lappend curresult $current
incr curval
if {$curval > $maxval} {
set maxresult $curresult
set maxval $curval
}
} else {
set curval 1
set curresult [list $current]
}
set last $current
}
if {$maxval > 1} {
puts $maxresult
} else {
puts "0"
}