diff options
author | EliteTK <tomasz.kramkowski@gmail.com> | 2015-06-19 19:12:12 +0100 |
---|---|---|
committer | EliteTK <tomasz.kramkowski@gmail.com> | 2015-06-19 19:12:12 +0100 |
commit | da87fcf25e0c94e57f00df84679cd6fadc56ed46 (patch) | |
tree | 3c53eea9db01039990455af870a2ca65e7e5a123 /shufflechars.c | |
parent | 75d2e00662416224f4b745e0004f48f1fc1d9665 (diff) | |
parent | 7bf25fb8f0e4643a67894417a95d39e5901b1824 (diff) | |
download | c-stuff-da87fcf25e0c94e57f00df84679cd6fadc56ed46.tar.gz c-stuff-da87fcf25e0c94e57f00df84679cd6fadc56ed46.tar.xz c-stuff-da87fcf25e0c94e57f00df84679cd6fadc56ed46.zip |
Merge branch 'master' of https://github.com/EliteTK/c-stuff
Diffstat (limited to 'shufflechars.c')
-rw-r--r-- | shufflechars.c | 59 |
1 files changed, 59 insertions, 0 deletions
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 <tk@the-tk.com> + * + * 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 <stdio.h> +#include <stdlib.h> +#include <stdbool.h> +#include <string.h> +#include <time.h> + +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 <text>\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; +} |