Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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