choose random number with weight
Here is an example of how you can choose a random number with weight in C:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int weightedRandomNumber(int weights[], int size) {
int totalWeight = 0;
int i;
// Calculate the total weight
for (i = 0; i < size; i++) {
totalWeight += weights[i];
}
// Generate a random number between 0 and the total weight
int randomNumber = rand() % totalWeight;
// Find the index of the chosen number based on the weights
int chosenIndex = 0;
int sum = weights[chosenIndex];
while (randomNumber >= sum) {
chosenIndex++;
sum += weights[chosenIndex];
}
return chosenIndex;
}
int main() {
srand(time(NULL));
// Array of weights
int weights[] = {1, 3, 2, 4};
int size = sizeof(weights) / sizeof(weights[0]);
// Use the weightedRandomNumber function to choose a random number
int randomNumber = weightedRandomNumber(weights, size);
printf("Chosen number: %d\n", randomNumber);
return 0;
}
This code defines a function called weightedRandomNumber
that takes an array of weights and its size as parameters. The function calculates the total weight and then generates a random number between 0 and the total weight. It then finds the index of the chosen number based on the weights and returns it.
In the main
function, an array of weights is defined and the size is determined. The weightedRandomNumber
function is called with these parameters, and the chosen number is printed.
Please note that this code uses the rand
function from the stdlib.h
library, which generates pseudo-random numbers. The srand
function is used to seed the random number generator with the current time, ensuring different random numbers are generated each time the program is run.