Hey ya'll I was looking for some guidance. I'm building a "workout generator" for fun and got stuck. I want my program pick a random assortment of exercises and write them to a new file.

What is the best way to randomly pick strings from a list of exercises; jump rope 20 mins, 15 push-ups, run 1 mi, etc.

Make an array with every exercise and randomly pick one? How would I go about doing that? Any help is appreciated.

Make an array with every exercise and randomly pick one?

Yup. Though for a workout generator you probably don't want to pick the same exercise twice, so a random shuffle may be more appropriate.

How would I go about doing that?

Here's an example:

#include <stdio.h>
#include <stdlib.h>

#define length(x) sizeof (x) / sizeof *(x)

static const char* data[] =
{
    "test 1",
    "test 2",
    "test 3",
    "test 4",
    "test 5"
};

int main(void)
{
    int indices[length(data)];
    int i;

    /* Initialize the indices */
    for (i = 0; i < length(data); ++i)
    {
        indices[i] = i;
    }

    /* Randomly shuffle the indices */
    for (i = 0; i < length(data) - 1; ++i)
    {
        int r = i + (rand() % length(data) + 1);
        int temp = indices[i];
        indices[i] = indices[r];
        indices[r] = temp;
    }

    /* Select a portion of the shuffled array */
    for (i = 0; i < length(data); ++i)
    {
        printf("%s\n", data[indices[i]]);
    }

    return 0;
}
This article has been dead for over six months. Start a new discussion instead.