Random function - divide a number each time differently

Started by erezpaz, December 25, 2016, 12:21:06 PM

Previous topic - Next topic

erezpaz

Hi

I am trying to build a simple random function that will give divide me a number each time differently but keep the original sum. What i mean is that if i push it number 4 it will return: 1,3 or 2,2 or 4 or 0,2,0,1,1 etc.
Each time deferent combination but never more then the total sum of the number i pushed.

Thanks
Erez

td

Code (winbatch) Select
#DefineFunction RandomList( _nLimit )

   IntControl(81, GetTickCount(),0,0,0) ; Seed.
   lReturn = ""
   nSum = 0

   while nSum < _nLimit
      nTemp = Random(_nLimit)
      if nSum + nTemp <= _nLimit
         lReturn = ItemInsert(nTemp, -1, lReturn, @Tab)
         nSum += nTemp
      endif
   endwhile

   return lReturn ; List of numbers with limit range and sum to limit.
#EndFunction

Pause("Pseudo Random List", RandomList(4))
exit
"No one who sees a peregrine falcon fly can ever forget the beauty and thrill of that flight."
  - Dr. Tom Cade

stanl

Interesting solution Tony. Now if the OP wanted to list all combinations that equaled a sum, he would need some sort of factorial() function or recursion and I remember Detlev posting something to that effect years ago: i.e.    5 =  (5+0), (4+1), (3+2), (2+3), (1+4),(0+5).   

td

The recursive formula for calculating a factorial is n! = n Ãâ€" (n−1)! but that doesn't appear to be what the OP is looking for.  The script above, which could be written recursively, is a straight forward, simple approach that is intended to help the OP figuring out their own solution to generating a list of integers.
"No one who sees a peregrine falcon fly can ever forget the beauty and thrill of that flight."
  - Dr. Tom Cade

stanl

Gee Tony, you are no fun anymore. I know what a combination is (and a permutation). Just wanted to check is the Op had a business question or just needed help on a test.