使用者輸入2 印1-98 (11, 22, 33等重複的不印)
使用者輸入3 印1-987 (121, 988, 667等有重複的不印)
#!/usr/bin/tclsh
#
# Test on Tcl 8.6
#
puts -nonewline "Please input a number: "
flush stdout
gets stdin number
if {$number <= 0 || $number >= 10} {
puts "The range is 1 - 9."
exit
}
set max [expr 10 ** $number]
puts "\nNow get the result:"
puts "==========="
puts "Start"
puts "==========="
puts -nonewline "1"
for {set i 2} {$i < $max} {incr i} {
set var [regexp "1.*1|2.*2|3.*3|4.*4|5.*5|6.*6|7.*7|8.*8|9.*9|0.*0" $i]
if {$var != 1} {
puts -nonewline ", $i"
}
}
puts "\n==========="
puts "End"
puts "==========="
也可以使用 lsort -unique 建立 set 來解題。
puts -nonewline "Please input a number: "
flush stdout
gets stdin number
if {$number <= 0 || $number >= 10} {
puts "The range is 1 - 9."
exit
}
set max [expr pow(10, $number)]
set result [list]
puts "\nNow get the result:"
puts "==========="
puts "Start"
puts "==========="
for {set i 1} {$i < $max} {incr i} {
set tmpstring [format %s $i]
set tmpList [lsort -unique [split $tmpstring ""]]
if {[string length $tmpstring] == [llength $tmpList]} {
lappend result $i
}
}
puts [join $result ", "]
puts "\n==========="
puts "End"
puts "==========="
也可以用 permutations 的方式來解題,下面是 Tcl 的版本:
#!/usr/bin/env tclsh
proc permutations { list size } {
if { $size == 0 } {
return [list [list]]
}
set retval {}
for { set i 0 } { $i < [llength $list] } { incr i } {
set firstElement [lindex $list $i]
set remainingElements [lreplace $list $i $i]
foreach subset [permutations $remainingElements [expr { $size - 1 }]] {
lappend retval [linsert $subset 0 $firstElement]
}
}
return $retval
}
puts -nonewline "Please input a number: "
flush stdout
gets stdin number
if {$number <= 0 || $number >= 10} {
puts "The range is 1 - 9."
exit
}
set allresult [list]
for {set i 1} {$i <= $number} {incr i} {
set res [permutations [list 0 1 2 3 4 5 6 7 8 9] $i]
set allresult [list {*}$allresult {*}$res]
}
puts -nonewline "1"
set len [llength $allresult]
for {set i 2} {$i < $len} {incr i} {
set r [lindex $allresult $i]
set first [lindex $r 0]
if {[string compare $first "0"]==0} {
continue
}
puts -nonewline ", "
puts -nonewline [join $r ""]
}
puts "\n"
flush stdout
沒有留言:
張貼留言