chiark / gitweb /
Introduce a `shuffle' utility function.
authorSimon Tatham <anakin@pobox.com>
Thu, 14 Jul 2005 17:37:05 +0000 (17:37 +0000)
committerSimon Tatham <anakin@pobox.com>
Thu, 14 Jul 2005 17:37:05 +0000 (17:37 +0000)
[originally from svn r6090]

misc.c
puzzles.h

diff --git a/misc.c b/misc.c
index 025083dc81204555bf9a11fc6f01d707f05d2e1b..17ec48c4cc0683735e00e08bfcd79922597794ee 100644 (file)
--- a/misc.c
+++ b/misc.c
@@ -196,4 +196,20 @@ void game_mkhighlight(frontend *fe, float *ret,
     }
 }
 
+void shuffle(void *array, int nelts, int eltsize, random_state *rs)
+{
+    char *tmp = smalloc(eltsize);
+    char *carray = (char *)array;
+    int i;
+
+    for (i = nelts; i-- > 1 ;) {
+        int j = random_upto(rs, i+1);
+        if (j != i) {
+            memcpy(tmp, carray + eltsize * i, eltsize);
+            memcpy(carray + eltsize * i, carray + eltsize * j, eltsize);
+            memcpy(carray + eltsize * j, tmp, eltsize);
+        }
+    }
+}
+
 /* vim: set shiftwidth=4 tabstop=8: */
index e05a3e489daab83df7724877bae2bfd18a5be003..1c3ae591ed1535a7ab31ad4e7e7a5018c0621384 100644 (file)
--- a/puzzles.h
+++ b/puzzles.h
@@ -223,6 +223,9 @@ unsigned char *hex2bin(const char *in, int outlen);
 void game_mkhighlight(frontend *fe, float *ret,
                       int background, int highlight, int lowlight);
 
+/* Randomly shuffles an array of items. */
+void shuffle(void *array, int nelts, int eltsize, random_state *rs);
+
 /*
  * version.c
  */