0

For example, a random number between 1 and 10 , and the value is more likely to be 7.

  • 1
    I think it is difficult to do, in particular the requirement *and the value is more likely to be 7*. The question is how to you define *random* then? It is certainly not uniform anymore. – Ely Dec 30 '16 at 16:37
  • 2
    Look at http://stackoverflow.com/questions/1761626/weighted-random-numbers – Joe Dec 30 '16 at 16:38
  • If you want to predict the next 'random' value, you can use a pseudo-random number generator _with a known seed_. – ForceBru Dec 30 '16 at 16:40
  • 1
    `int values[] = {0, 1, 2, 3, 3, 3, 3, 3, 4, 5};` then select a random element of the array. – pmg Dec 30 '16 at 16:42
  • 2
    You need to quantify "more likely". – dbush Dec 30 '16 at 16:45
  • You can define an array which consists of the numbers that you want to generate randomly and keep the frequency of that number more which you want to generate the most. For ex - if you want to generate only 3,5 and 6 with 6 occuring most of the time then one such array could be - [ 6,6,6,6,3,3,3,5,5]. But for this approach you have to know which number you want to generate most of the time – GAURANG VYAS Dec 30 '16 at 17:09
  • 1
    Well, I'm quite amused. @Joe provided link to the existing question, which covers current question in all aspects: it has clear wording (no undefined terms like "more likely"), precise and detailed answer with pseudo-code and recommendations on implementation. Why Joe's comment doesn't have a single upvote, while hacky solution with adding more 7s to list of values (neither flexible enough to fully control percentage of 7, nor scalable for larger sets) has 6 so far? – nnovich-OK Dec 30 '16 at 17:11

1 Answers1

6

You could do something like pulling a random value from an array 1-10 where 7 appears twice

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(int argc, char *argv[])
{
    // note that 7 appears twice
    int data[11] = { 1, 2, 3, 4, 5, 6, 7, 7, 8, 9, 10 };
    int i;

    srand((unsigned)time(NULL));
    for(i = 0; i < 100; i++)
        printf("%d\n", data[rand()%11]);

    return 0;
}

The (sorted) output I got from this was:

1
1
1
1
1
1
1
1
2
2
2
2
2
2
2
2
2
3
3
3
3
3
3
3
3
3
4
4
4
4
4
4
4
5
5
5
5
5
5
5
5
5
5
5
6
6
6
6
6
7
7
7
7
7
7
7
7
7
7
7
7
7
7
7
7
7
7
7
7
7
8
8
8
8
8
8
8
8
9
9
9
9
9
9
9
9
9
10
10
10
10
10
10
10
10
10
10
10
10
10

Note that 7 appears more frequently than any other number (about twice as frequent). To increase the frequency, put more 7s in the array.

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85