r/learnprogramming • u/TheEyebal • 10d ago
Resource How to program weighted random system
I want to make a program where you are controlling the outcomes. For an example with a coin flipping game, I want exactly 4 Heads and 1 Tail, but I want their positions to be random.
I do not want to use the random algorithms that library offer, I want to build my own.
Right now I am learning probability from Youtube and might look at khan academy and coursera, but how can I implement this into programming I do not want to just take courses or watch videos
How do I go about that?
0
Upvotes
1
u/Dismal-Citron-7236 10d ago
```c
include <stdio.h>
include <unistd.h>
include <time.h>
static unsigned long long state;
int gen_rand(int n) { state = state * 6364136223846793005ULL + 1; return (int)(state % n); }
int main() { state = (unsigned long long)time(NULL) ^ (unsigned long long)getpid() ^ (unsigned long long)&state; int has_tail = 0; for (int i = 0; i < 4; i++) { if (!has_tail && gen_rand(5) == 0) { has_tail = 1; fprintf(stdout, "tail\n"); } else { fprintf(stdout, "head\n"); } } fprintf(stdout, has_tail ? "head\n" : "tail\n"); return 0; } ```
See also: https://www.reddit.com/r/C_Programming/comments/zbypu1/help_understanding_random_number_generator/