How to resolve the algorithm Combinations and permutations step by step in the Tcl programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Combinations and permutations step by step in the Tcl programming language
Table of Contents
Problem Statement
Implement the combination (nCk) and permutation (nPk) operators in the target language:
See the Wikipedia articles for a more detailed description. To test, generate and print examples of:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Combinations and permutations step by step in the Tcl programming language
Source code in the tcl programming language
# Exact integer versions
proc tcl::mathfunc::P {n k} {
set t 1
for {set i $n} {$i > $n-$k} {incr i -1} {
set t [expr {$t * $i}]
}
return $t
}
proc tcl::mathfunc::C {n k} {
set t [P $n $k]
for {set i $k} {$i > 1} {incr i -1} {
set t [expr {$t / $i}]
}
return $t
}
# Floating point versions using the Gamma function
package require math
proc tcl::mathfunc::lnGamma n {math::ln_Gamma $n}
proc tcl::mathfunc::fP {n k} {
expr {exp(lnGamma($n+1) - lnGamma($n-$k+1))}
}
proc tcl::mathfunc::fC {n k} {
expr {exp(lnGamma($n+1) - lnGamma($n-$k+1) - lnGamma($k+1))}
}
# Using the exact integer versions
puts "A sample of Permutations from 1 to 12:"
for {set i 4} {$i <= 12} {incr i} {
set ii [expr {$i - 2}]
set iii [expr {$i - int(sqrt($i))}]
puts "$i P $ii = [expr {P($i,$ii)}], $i P $iii = [expr {P($i,$iii)}]"
}
puts "A sample of Combinations from 10 to 60:"
for {set i 10} {$i <= 60} {incr i 10} {
set ii [expr {$i - 2}]
set iii [expr {$i - int(sqrt($i))}]
puts "$i C $ii = [expr {C($i,$ii)}], $i C $iii = [expr {C($i,$iii)}]"
}
# Using the approximate floating point versions
puts "A sample of Permutations from 5 to 15000:"
for {set i 5} {$i <= 150} {incr i 10} {
set ii [expr {$i - 2}]
set iii [expr {$i - int(sqrt($i))}]
puts "$i P $ii = [expr {fP($i,$ii)}], $i P $iii = [expr {fP($i,$iii)}]"
}
puts "A sample of Combinations from 100 to 1000:"
for {set i 100} {$i <= 1000} {incr i 100} {
set ii [expr {$i - 2}]
set iii [expr {$i - int(sqrt($i))}]
puts "$i C $ii = [expr {fC($i,$ii)}], $i C $iii = [expr {fC($i,$iii)}]"
}
You may also check:How to resolve the algorithm Rosetta Code/Count examples step by step in the Julia programming language
You may also check:How to resolve the algorithm Number reversal game step by step in the Prolog programming language
You may also check:How to resolve the algorithm Averages/Median step by step in the 11l programming language
You may also check:How to resolve the algorithm Odd word problem step by step in the J programming language
You may also check:How to resolve the algorithm Additive primes step by step in the PILOT programming language