Reputation: 138
I would like to randomly select words (with or without meaning) from 26 letters. The word contains 6 letters, and letter repetitions are allowed.
How can this be done with a program in C (or Objective C)? I would be very grateful for any ideas.
Upvotes: 2
Views: 629
Reputation: 118470
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
main()
{
srand(time(NULL));
for (int i = 0; i < 6; ++i)
{
putchar('a' + (rand() % 26));
}
putchar('\n');
return EXIT_SUCCESS;
}
Salt to taste.
It would seem the OP does not know how to compile the above. If saved into a file called so.c
, compile it with make so CFLAGS=-std=c99
from the same folder.
Upvotes: 5
Reputation: 49793
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* Written by kaizer.se */
void randword(char *buf, size_t len)
{
char alphabet[] = "abcdefghijklmnopqrstuvxyz";
size_t i;
for (i = 0; i < len; i++) {
size_t idx = ((float)rand()/RAND_MAX) * (sizeof(alphabet) -1);
buf[i] = alphabet[idx];
}
buf[len] = '\0';
}
int main(void) {
char buf[1024];
srand(time(NULL));
randword(buf, 7);
printf("Word: %s\n", buf);
return 0;
}
Test:
$ ./rword
Word: xoilfvv
Upvotes: 0