下面是使用 Tcl 試著解 Count Number 的答案:
#!/usr/bin/tclsh
#
# You are given a positive number $N.
# Write a script to count number and display as you read it.
#
# For example,
# Input: $N = 1122234
# Output: 21321314
# as we read "two 1 three 2 one 3 one 4"
#
puts -nonewline "Please input a number: "
flush stdout
gets stdin number
if {$number <= 0} {
puts "Number requires > 0."
exit
}
array set mapping [list 1 one 2 two 3 three 4 four 5 five 6 six 7 seven 8 eight 9 nine]
set last [string index $number 0]
set index 0
set results [list]
lset results $index [list 1 $last]
for {set i 1} {$i < [string length $number]} {incr i} {
set current [string index $number $i]
if {$current == $last} {
set indexlist [lindex $results $index]
set curval [lindex $indexlist 0]
incr curval
set indexlist [list $curval $current]
} else {
incr index
set indexlist [list 1 $current]
}
lset results $index $indexlist
set last $current
}
set answer {}
foreach r $results {
append answer [join $r ""]
}
puts "\nOutput: $answer"
puts -nonewline "as we read \""
set nresults [list]
for {set index 0} {$index < [llength $results]} {incr index} {
set r [lindex $results $index]
set key [lindex $r 0]
set value [lindex $r 1]
lappend nresults "$mapping($key) $value"
}
puts -nonewline [join $nresults " "]
puts "\""
沒有留言:
張貼留言