Subject: An Interesting Big Loop Problem + Solution

Started by BrWarburto, January 31, 2007, 03:33:47 PM

Previous topic - Next topic

BrWarburto

   This issue came to light while building a programme to construct strings of nine random integers in the range 1 - 9. There are several library subroutines which will deliver pseudo random numbers (eg 'C' rand & srand). However the same sequence of random integers is produced every time. A popular solution to this limitation is to call an application such as GetSystemTime. This will fill a structure with time elements and the last byte of the structure will contain the last system time at the 1/100 second inteval. If this appl. is called 'on the fly' the byte mentioned will virtually contain a random integer in the range 0 - 99.
We can then ensure a truly random integer by calling 'rand' a set number of times equal to this time fraction.

The programme developed performed well most of the time but occasionaly it hung myteriously for a very long time without giving an obvious execution error such as an exception. The reason for this rested on the case where the 'random' integer returned was zero.

The value is put into ECX and the code:

.Begin
call ......rand
..
..
LOOP .Begin

executed.
Unfortunately should ECX contain zero, LOOP is executed to the full possible value of ECX! A solution to this problem is to INC ECX, before entering the loop. As Jeremy has pointed out, this 'fix' will not always work in the general case (eg suppose ECX should equal -1), so the given value of ECX should be carefully checked.

BeeWarb