2020-04-25

Tcl: loop (calculates the Harmonic series)

用來練習迴圈的問題。

#!/usr/bin/env tclsh
#
# Calculates the Harmonic series.
# h(n) = 1 + 1/2 + 1/3 + … + 1/n
#

if {$argc >= 1} {
    set N [lindex $argv 0]
} elseif {$argc == 0} {
    puts "Please input a number."
    exit    
}

if {[string is integer $N]==0} {
    puts "It is not a number."
    exit
}

set h 0.0
for {set count $N} {$count >= 1} {incr count -1} {
    set h [expr $h + 1.0 / $count]
}

puts [format "%5E" $h]

再來是使用 while 迴圈計算 Harmonic series 的程式:
#!/usr/bin/env tclsh
#
# Calculates the Harmonic series.
# h(n) = 1 + 1/2 + 1/3 + … + 1/n
#

if {$argc >= 1} {
    set N [lindex $argv 0]
} elseif {$argc == 0} {
    puts "Please input a number."
    exit    
}

if {[string is integer $N]==0} {
    puts "It is not a number."
    exit
}

set h 0.0
set I 1
while {$I <= $N} {
    set h [expr $h + 1.0 / $I]
    incr I
}

puts [format "%5E" $h]

2020-04-20

Tcl: Nth Item In A List

假設有一個 List,
set mylist [list 2 4 6 8 10]

如果要取得 List 中 nth 的 item,可以使用 lindex,如下面的例子:
lindex $mylist 1
這樣就會得到 4 這個值。

2020-04-12

Tcl: divmod

Given positive integers C and N, find N numbers that sum up to C and the difference between the highest and the lowest of these number should not be more than one. For example: with C = 26 and N = 7, the desired output is [4 4 4 4 4 3 3].

#!/usr/bin/tclsh

proc divmod {C N} {
    set answer [list]

    if {($C <= 0) || ($N <= 0) || ($C < $N)} {
        return $answer
    }

    set element [expr $C / $N]
    set remainder [expr $C % $N]
    
    for {set count 0} {$count < $N} {incr count} {
        lappend answer $element
    }

    if {$remainder != 0} {
        for {set count 0} {$count < $remainder} {incr count} {
            set myvalue [lindex $answer $count]
            incr myvalue 1
            lset answer $count $myvalue
        }
    }

    return $answer
}

puts -nonewline "Please input a number C: "
flush stdout
gets stdin C
puts -nonewline "Please input a number N: "
flush stdout
gets stdin N

set myanswer [divmod $C $N]
puts "The answer list: $myanswer"