From b99f95ef777000743404902c76c9c8f0b207e5ba Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Sat, 4 Apr 2015 20:42:29 +0200 Subject: shufflechars: Shuffle characters around. --- shufflechars.c | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 shufflechars.c diff --git a/shufflechars.c b/shufflechars.c new file mode 100644 index 0000000..84a2c55 --- /dev/null +++ b/shufflechars.c @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2015 Tomasz Kramkowski + * + * This program is free software. It is licensed under version 3 of the + * GNU General Public License. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see [http://www.gnu.org/licenses/]. + */ +#include +#include +#include +#include +#include + +static inline unsigned rand_to_max(unsigned max) +{ + double random; + + while ((random = rand()) == (double)RAND_MAX); + + return random / (double)RAND_MAX * (double)max; +} + +int main(int argc, char **argv) +{ + size_t length; + char *text, *dest; + + srand(time(NULL)); + + if (argc != 2) { + fprintf(stderr, "Usage: %s \a\n", argv[0]); + exit(EXIT_FAILURE); + } + + text = argv[1]; + length = strlen(text); + + bool relocated[length]; + + memset(relocated, 0, length); + dest = malloc(length + 1); + + for (size_t i = 0; i < length; i++) { + size_t index; + while (index = rand_to_max(length), relocated[index]) + ; + + dest[i] = text[index]; + relocated[index] = true; + } + + dest[length] = '\0'; + + printf("%s\n", dest); + + return EXIT_SUCCESS; +} -- cgit v1.2.3-54-g00ecf