aboutsummaryrefslogtreecommitdiffstats
path: root/randtest.c
diff options
context:
space:
mode:
authorEliteTK <tomasz.kramkowski@gmail.com>2015-06-19 19:12:12 +0100
committerEliteTK <tomasz.kramkowski@gmail.com>2015-06-19 19:12:12 +0100
commitda87fcf25e0c94e57f00df84679cd6fadc56ed46 (patch)
tree3c53eea9db01039990455af870a2ca65e7e5a123 /randtest.c
parent75d2e00662416224f4b745e0004f48f1fc1d9665 (diff)
parent7bf25fb8f0e4643a67894417a95d39e5901b1824 (diff)
downloadc-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 'randtest.c')
-rw-r--r--randtest.c56
1 files changed, 38 insertions, 18 deletions
diff --git a/randtest.c b/randtest.c
index 06a71de..fcd394d 100644
--- a/randtest.c
+++ b/randtest.c
@@ -1,3 +1,12 @@
+/*
+ * 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 <stdint.h>
#include <stdio.h>
#include <stdlib.h>
@@ -8,28 +17,39 @@
int8_t randrange(int8_t from, int8_t to)
{
- int base_random = rand();
- if (RAND_MAX == base_random) return randrange(from, to);
- int range = to - from,
- remainder = RAND_MAX % range,
- bucket = RAND_MAX / range;
- if (base_random < RAND_MAX - remainder) {
- return from + base_random/bucket;
- } else {
- return randrange(from, to);
- }
+ int base_random = rand();
+ if (RAND_MAX == base_random) return randrange(from, to);
+ int range = to - from,
+ remainder = RAND_MAX % range,
+ bucket = RAND_MAX / range;
+ if (base_random < RAND_MAX - remainder) {
+ return from + base_random/bucket;
+ } else {
+ return randrange(from, to);
+ }
+}
+
+
+static 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)
{
- srand(time(NULL));
- int r;
- uint16_t *amounts = calloc(sizeof(uint16_t), (TO - FROM + 1));
- for (int i = 0; i < 1000; i++)
- amounts[randrange(FROM, TO) - FROM]++;
+ srand(time(NULL));
+
+ uint64_t counter[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
+
+ for (int i = 0; i < 1000000; i++)
+ counter[rand_to_max(9)]++;
- for (int i = 0; i < TO - FROM + 1; i++)
- printf("%d: %d\n", i, amounts[i]);
+ for (int i = 0; i < 10; i++)
+ printf("%d: %lu\n", i, counter[i]);
- return 0;
+ return EXIT_SUCCESS;
}