Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Randomly sorting TMemo, code bug? 1

Status
Not open for further replies.

KempCGDR

Programmer
Jan 10, 2003
445
GB
I have the following code:

Code:
      Randomize;
      For i := 1 to frmMain.memOrig.Lines.Count do
      begin
         RandNo := Random(frmMain.memOrig.Lines.Count)+1;
         frmMain.memNew.Lines.Add(frmMain.memOrig.Lines[RandNo]);
         frmMain.memOrig.Lines.Delete(RandNo);
      end;

It is meant to put the contents of memOrig into memNew in a random order. For some reason that I can't see, there is are always some items left in memOrig (usually two, but not always). I tried changing the For statement to a fixed number (the number of items in it), with the same result. I've got to be missing something obvious as this is only a small, simple piece of code. Can anyone spot it?
 
Now changed for ease of reading, same basic code:

Code:
      Randomize;
      With frmMain do
      begin
         For i := 1 to memOrig.Lines.Count do
         begin
            RandNo := Random(memOrig.Lines.Count)+1;
            memNew.Lines.Add(memOrig.Lines[RandNo]);
            memOrig.Lines.Delete(RandNo);
         end;
      end;
 
Try changing the first statement after the begin to:
[blue]
Code:
  RandNo := Random(memOrig.Lines.Count - 1);
[/color]

That seems to work for me.


 
Doh! The number of lines is 60, but the numbering will be 0 -> 59. I'll try

Code:
      Randomize;
      With frmMain do
      begin
         For i := 1 to memOrig.Lines.Count do
         begin
            RandNo := Random(memOrig.Lines.Count)+1;
            memNew.Lines.Add(memOrig.Lines[RandNo-1]);
            memOrig.Lines.Delete(RandNo-1);
         end;
      end;

and get back.
 
Works! Thanks for triggering that memory, and it can be obviously simplified now by dropping the +1 and -1 on the various bits. Thanks again.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top