Shuffling An Array

Anything Sinclair ZX Basic related; history, development, tips - differences between BASIC on the ZX80 and ZX81
MrVertigo
Posts: 112
Joined: Fri May 27, 2022 9:06 pm

Re: Shuffling An Array

Post by MrVertigo »

We already have the ideal solution to shuffling an array randomly. This is the method from earlier in the thread:
XavSnap wrote: Wed May 17, 2023 6:01 am Hi,
The better way to shuffling an array is to reduce its length if the value is selected...
Only 5 loops to get a string.
Have a look to : https://www.sinclairzxworld.com/viewtop ... 938#p47938

The int(RND*5)+1, and put a space on the value, was a very bad purpose and loop many time on the same value !
RND=1,2,2,5,1,1,5,3,2,1,3,1,3,3,4 ( 15 times )


This purpose only chose unselected values: 4,2,3,1,5 ( 5 times )

Code: Select all

   100 LET P=6
   110 LET CN=0
   112 LET T=13*P
   115 DIM C(T)
   
   120  FOR N=1 TO T
   150  LET C(N)=N
   170  NEXT N

  7000 LET V=INT ((RND*T)+1)
  7010 LET CN=CN+1
  7050 LET R=C(V)
  7100 IF V<>T THEN LET C(V)=C(T)
  7110 LET T=T-1
  7120 PRINT R;";";
  7130 IF T<>0 THEN GOTO 7000
  7200 PRINT "END OF ";CN;" VALUES"
  

The thing I’m working on now is a method to find a SPECIFIC permutation of a set. The Nth permutation. It involves initially converting the decimal number represented by N into a number using the Factorial Number System (using factorials as a base: 1,2,3,6,24,120,720 etc). I posted an attempt at the code a few posts back. Wondering if anyone can simplify or improve it.

We would then simply assign a random number to N. Just a bit of fun. :D
MrVertigo
Posts: 112
Joined: Fri May 27, 2022 9:06 pm

Re: Shuffling An Array

Post by MrVertigo »

Revisiting this thread after a couple of years, I came up with a much shorter piece of code to achieve my initial goal of shuffling an array, and having each item appear only once in the result. I’ll post it here incase anyone needs it in future. (You might also want to add a RAND statement at the beginning):
2968E874-D71F-4136-B4CB-CB5CA7966AF4.jpeg
Post Reply