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"

沒有留言: