chiark / gitweb /
James H profiled the new Same Game grid generator and discovered it
authorSimon Tatham <anakin@pobox.com>
Fri, 22 Jul 2005 11:06:57 +0000 (11:06 +0000)
committerSimon Tatham <anakin@pobox.com>
Fri, 22 Jul 2005 11:06:57 +0000 (11:06 +0000)
was spending 60% of its time in shuffle(). The purpose of the
shuffle() call was to go through a largish array in random order
until we found an element that worked, so there's no actual need to
shuffle the whole array every time and I only did it out of
laziness. So I now pick a random element each time I go round the
loop, meaning I save a lot of shuffling effort whenever the loop
terminates early (which is often). I get about a factor of two speed
improvement from this small change.

[originally from svn r6125]

samegame.c

index 60e0272fef074adafbcb968120e2f3c0b0499525..b9078eb63533cad6aae386e6547cd64db038c15b 100644 (file)
@@ -398,11 +398,6 @@ static void gen_grid(int w, int h, int nc, int *grid, random_state *rs)
             if (n == 0)
                 break;                /* we're done */
 
-            /*
-             * Shuffle the list.
-             */
-            shuffle(list, n, sizeof(*list), rs);
-
 #ifdef GENERATION_DIAGNOSTICS
             printf("initial grid:\n");
             {
@@ -420,13 +415,17 @@ static void gen_grid(int w, int h, int nc, int *grid, random_state *rs)
 #endif
 
             /*
-             * Now go through the list one element at a time and
-             * actually attempt to insert something there.
+             * Now go through the list one element at a time in
+             * random order, and actually attempt to insert
+             * something there.
              */
             while (n-- > 0) {
                 int dirs[4], ndirs, dir;
 
-                pos = list[n];
+                i = random_upto(rs, n+1);
+                pos = list[i];
+                list[i] = list[n];
+
                 x = pos % w;
                 y = pos / w;