Computer Science Canada

permutations & combinations

Author:  Prince [ Thu Apr 10, 2003 10:41 am ]
Post subject:  permutations & combinations

code:

% function Get_Positive_Integer
% purpose: gets a positive number from the user
% parameters: name:string
% result n

function Get_Positive_Integer (name : string) : int
    var n : int
    loop
        put "Please enter a positive integer for ", name, " -> " ..
        get n
        exit when n >= 0
        put "-------------------------------------------"
        put "                 ERROR!                    "
        put "-------------------------------------------"
    end loop
    result n
end Get_Positive_Integer

% function nFactorial
% purpose: finds factorial of n
% parameters: n
% result N

function nFactorial (n : int) : real
    var N : real := 1
    for j : 1 .. n
        N := N * j
    end for
    result N
end nFactorial

% function rFactorial
% purpose: finds factorial of r
% parameters: r
% result R

function rFactorial (r : int) : real
    var R : real := 1
    for j : 1 .. r
        R := R * j
    end for
    result R
end rFactorial

function nrFactorial (var n, r : int) : real
    var NR : real := 1
    for j : 1 .. n - r
        NR := NR * j
    end for
    result NR
end nrFactorial

function Combination (var N, R, NR : real) : real
    result N / (R * NR)
end Combination

function Permutation (var N, NR : real) : real
    result N / NR
end Permutation
% ---------- Main ----------

var n, r : int
var N, R, NR, P, C : real
var key : string (1)

loop
    cls
    loop
        n := Get_Positive_Integer ("n")
        r := Get_Positive_Integer ("r")
        exit when n >= r
        put
            "N Value MUST be greater than or equal to R value. Please try again!!!"
    end loop

    N := nFactorial (n)
    R := rFactorial (r)
    NR := nrFactorial (n, r)
    P := Permutation (N, NR)
    C := Combination (N, R, NR)

    put ""
    put "Combinations (", n, ",", r, ") = ", C
    put "Permutations (", n, ",", r, ") = ", P
    put ""
    put "Would you like to do another calculation? [y/n] " ..
    getch (key)
    exit when key = "N" or key = "n"
end loop


some description of the program would be nice. +7Bits though - Tony

Author:  Asok [ Thu Apr 10, 2003 10:54 am ]
Post subject: 

hm... instead of making it so that n HAS to be greater than r, you could just add an if statement to see which one was bigger then just use that to continue the calculations.

Author:  Prince [ Thu Apr 10, 2003 4:29 pm ]
Post subject: 

meh...


: