Commits

Evan Gates committed b85ff9f

propper shuffle for stand alone rand

  • Participants
  • Parent commits 874bd0d

Comments (0)

Files changed (1)

File stand_alone/rand.c

 #include <sys/time.h>
 
 char *names[] = { "UFU", "URU", "UBU", "ULU", "DFD", "DRD", "DBD", "DLD", "FRF", "FLF", "BRB", "BLB",
-    "UFRUF", "URBUR", "UBLUB", "ULFUL", "DRFDR", "DFLDF", "DLBDL", "DBRDB" };
+                  "UFRUF", "URBUR", "UBLUB", "ULFUL", "DRFDR", "DFLDF", "DLBDL", "DBRDB" };
 
-int main()
+int parity = 0;
+
+void shuffle(char **perm, int len)
 {
-    char *tmp;
-    long int r;
-    int i, o;
+	char i, r, *temp;
+
+	for (i = len - 1; i > 0; i--) {
+		r = random() % (i + 1);
+		temp    = perm[i];
+		perm[i] = perm[r];
+		perm[r] = temp;
+
+		if (r != i)
+			parity = !parity;
+	}
+}
+
+void twist_and_print(char **perm, int len, int mod)
+{
+	int i, r, o;
+
+	for (i = o = 0; i < len - 1; i++) {
+		r = random() % mod;
+		o = (o + mod - r) % mod;
+		printf("%0.*s ", mod, perm[i] + r);
+	}
+	printf("%0.*s ", mod, perm[i] + o);
+}
+
+int main(int argc, char **argv)
+{
+	int num = 1;
 
     struct timeval tv;
     gettimeofday(&tv, NULL);
     srandom(tv.tv_usec);
 
-    for (i = 0; i < 12; i++) {
-	   r = random() % 12;
-	   if (r == i) {
-		  i--;
-		  continue;
-	   }
-	   tmp = names[i];
-	   names[i] = names[r];
-	   names[r] = tmp;
-    }
+	if (argc == 1) {
+		// assume one random cube
+	} else if (argc == 2) {
+		// one argument, number of random cubes
+		num = atoi(argv[1]);
+	} else {
+		fprintf(stderr, "supply number of random cubes as argument\n");
+		exit(EXIT_FAILURE);
+	}
 
-    for (i = 0; i < 8; i++) {
-	   r = random() % 8;
-	   if (r == i) {
-		  i--;
-		  continue;
-	   }
-	   tmp = names[i + 12];
-	   names[i + 12] = names[r + 12];
-	   names[r + 12] = tmp;
-    }
+	while (num-- > 0) {
+		do {
+			shuffle(names     , 12);
+			shuffle(names + 12,  8);
+		} while (parity);
 
-    o = 0;
-    for (i = 0; i < 11; i++) {
-	   r = random() % 2;
-	   o = (o + r) % 2;
-	   printf("%0.2s ", names[i] + r);
-    }
-    printf("%0.2s ", names[11] + o);
+		twist_and_print(names     , 12, 2);
+		twist_and_print(names + 12,  8, 3);
 
-    o = 0;
-    for (i = 0; i < 7; i++) {
-	   r = random() % 3;
-	   o = (o + 3 - r) % 3;
-	   printf("%0.3s ", names[i + 12] + r);
-    }
-    printf("%0.3s\n", names[19] + o);
+		printf("\n");
+	}
 
     return 0;
 }