Skip to content

Instantly share code, notes, and snippets.

@thentenaar
Created November 25, 2012 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thentenaar/4143585 to your computer and use it in GitHub Desktop.
Save thentenaar/4143585 to your computer and use it in GitHub Desktop.
C Implementatation of TI BASIC's RND function
/* Equivalent to PRINT RND in TI Basic */
char *rnd() {
uint8_t rnds[7]; int i; char *n;
/* Try up to 64 times to come up with a non-zero pseudo-random integer */
for (i=0;i<63;i++) if ((rnds[0] = gpl_rand(100)) != 0) break;
if (rnds[0] == 0) return strdup("0");
/* Generate the rest of the set */
for (i=1;i<7;i++) rnds[i] = gpl_rand(100);
/* PRINT rounds up if the 6th number generated is >= 0x32 (50) */
if (rnds[5] >= 0x32) rnds[4]++;
/* PRINT prepends a leading zero if the first byte is < 0x10 */
if (rnds[0] < 0x10) {
memmove(&rnds[1],&rnds[0],6);
rnds[0] = 0;
}
/* Convert to string */
n = malloc(22);
snprintf(n,22,".%02d%02d%02d%02d%02d",rnds[0],rnds[1],rnds[2],rnds[3],rnds[4]);
return n;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment