January 26, 2021, 11:44:19 AM

Author Topic: [bb] Permutations Function by Kevin_ [ 1+ years ago ]  (Read 423 times)

Offline BlitzBot

  • Jr. Member
  • **
  • Posts: 1
[bb] Permutations Function by Kevin_ [ 1+ years ago ]
« on: June 29, 2017, 12:28:41 AM »
Title : Permutations Function
Author : Kevin_
Posted : 1+ years ago

Description : 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.


Code :
Code: BlitzBasic
  1. ;
  2. ;   Non-Recursive Permutations Function By Prof
  3. ;
  4. ;                    Examples
  5. ;
  6. ;                3 will return 6
  7. ;                4 will return 24
  8. ;                5 will return 120 etc...
  9. ;
  10. ;
  11. Graphics 640,480,32,2
  12. SetBuffer BackBuffer()
  13.  
  14. N_Values=5                      ; Number of values
  15. Perms=Permutations(N_Values)    ; Get the Number of permutations
  16.  
  17. Text 10,10,Str(Perms)+" possible arrangements (Permutations) of "+Str(N_Values)+" Values."
  18. Flip
  19. WaitKey()
  20. End
  21.  
  22. ; ***************************************************************
  23.  
  24. Function Permutations(N)
  25.   ; Returns the number of Permutations of N Values
  26.   ; N is an Int and must be greater than Zero otherwise Zero is returned
  27.   ;
  28.   If N>1
  29.      Result=N*(N-1)
  30.      For X=N-2 To 1 Step-1
  31.          Result=Result*X
  32.      Next
  33.   ElseIf N=1
  34.      Result=1
  35.   Else
  36.      Result=0
  37.   EndIf
  38.   Return Result
  39. End Function
  40.  
  41. ; ***************************************************************


Comments :


Diego(Posted 1+ years ago)

 It's nice. But think 0! := 1. To correct this, just change:ElseIf N=1intoElseIf N>=0


 

SimplePortal 2.3.6 © 2008-2014, SimplePortal