 |
BorlandTalk.com Borland discussion newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
Alan Guest
|
Posted: Thu Feb 15, 2007 4:30 am Post subject: Shuffling zero-based arrays |
|
|
I'm having a problem using the following shuffling algorithm I
found searching the Internet and newsgroups:
for J := Max downto 2 do Swap(A[J], A[Succ(Random(J))]) ;
When using the above algorithm with a zero-based array (dynamic
array), the first element of the array always seems to be
consistent. I have called Randomize once in my program, and the
array is sorted using QuickSort.
Here's a brief sample of the shuffle code I am using:
type
TStrArray = array of string;
procedure ShuffleStrs(var a: TStrArray);
var
j, x : integer;
temp : string;
begin
for j := High(a) downto 2 do
begin
x := Succ(Random(j));
temp := a[j];
a[j] := a[x];
a[x] := temp;
end;
end; |
|
| Back to top |
|
 |
Les Pawelczyk Guest
|
Posted: Thu Feb 15, 2007 5:02 am Post subject: Re: Shuffling zero-based arrays |
|
|
| Quote: | I'm having a problem using the following shuffling algorithm I
found searching the Internet and newsgroups:
for J := Max downto 2 do Swap(A[J], A[Succ(Random(J))]) ;
When using the above algorithm with a zero-based array (dynamic
array), the first element of the array always seems to be
consistent. I have called Randomize once in my program, and the
array is sorted using QuickSort.
|
Succ(Random(J)) is never zero.
Les. |
|
| Back to top |
|
 |
Marc Rohloff [TeamB] Guest
|
Posted: Thu Feb 15, 2007 7:49 am Post subject: Re: Shuffling zero-based arrays |
|
|
On 14 Feb 2007 14:30:08 -0800, Alan wrote:
| Quote: | I'm having a problem using the following shuffling algorithm I
found searching the Internet and newsgroups:
for J := Max downto 2 do Swap(A[J], A[Succ(Random(J))]) ;
|
How about:
for J := Max-1 downto 1 do Swap(A[J], A[Random(J)]) ;
--
Marc Rohloff [TeamB]
marc -at- marc rohloff -dot- com |
|
| Back to top |
|
 |
John Herbster Guest
|
Posted: Thu Feb 15, 2007 8:55 am Post subject: Re: Shuffling zero-based arrays |
|
|
"Marc Rohloff [TeamB]" wrote
| Quote: | for J := Max-1 downto 1 do Swap(A[J], A[Random(J)]) ;
|
What does the last step "Swap(A[0], A[Random(0)])" do?
What does the step "Swap(A[1], A[Random(1)])" do?
<g>
Maybe we should start thinking backwards::
Swap(A[1],A[random(2)]);
looks all right, so let's proceed that with
Swap(A[2],A[random(3)]);
and so on to
Swap(A[NbrElem-1],A[random(NbrElem)]);
Now then, we can put this all in a loop like this
For j := NbrElem downto 2 do Swap(A[j-1],A[random(j)]);
HTH, JohnH |
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|