Code archives/Algorithms/Permutations Function

This code has been declared by its author to be Public Domain code.

Download source code

Permutations Function by Kevin_2005
A handy function that returns the number of different arrangements that are possible from a list of 'N' values.
Handy for random number generators, lottery-type programs and 'brute force' attacking.
; 
;   Non-Recursive Permutations Function By Prof
;
;                    Examples
;
;                3 will return 6
;                4 will return 24
;                5 will return 120 etc...
;
;
Graphics 640,480,32,2
SetBuffer BackBuffer()

N_Values=5                      ; Number of values
Perms=Permutations(N_Values)    ; Get the Number of permutations

Text 10,10,Str(Perms)+" possible arrangements (Permutations) of "+Str(N_Values)+" Values."
Flip
WaitKey()
End

; ***************************************************************

Function Permutations(N)
  ; Returns the number of Permutations of N Values
  ; N is an Int and must be greater than Zero otherwise Zero is returned
  ;
  If N>1 
     Result=N*(N-1)
     For X=N-2 To 1 Step-1
         Result=Result*X
     Next
  ElseIf N=1
     Result=1
  Else
     Result=0
  EndIf
  Return Result
End Function

; ***************************************************************

Comments

Diego2008
It's nice. But think 0! := 1. To correct this, just change:

ElseIf N=1

into

ElseIf N>=0


Code Archives Forum