C ++ random number from set

Is it possible to print a random number in C ++ from a set of numbers using the ONE SINGLE statement?

Let, say, the set {2, 5, 22, 55, 332}

I looked at rand (), but I doubt it can be done in one statement.

+3
source share
5 answers

Say these numbers are in a set of size 5, all you have to do is find a random value times 5 (to make it equally probable). Suppose the rand () method returns you a random value between a range from 0 to 1. Multiply the same by 5 and drop it to the integer, you will get equiprobable values ​​between 0 and 4. Use this to extract from the index.

++.

my_rand_val = my_set[(int)(rand()*arr_size)]

, rand() - , 0 1.

+2
int numbers[] = { 2, 5, 22, 55, 332 };
int length = sizeof(numbers) / sizeof(int);
int randomNumber = numbers[rand() % length];
+10

- , ( ):

std::cout << ((rand()%5==0) ? 2 : 
              (rand()%4==0) ? 5 : 
              (rand()%3==0) ? 22 : 
              (rand()%2==0) ? 55 : 
              332
             ) << std::endl;

, .

Ah, , ( , rand() ) , " " .

, for , . . : , , for(...), . , , " " -, . :

// weasel #1: #define for brevity. If that against the rules,
// it can be copy and pasted 7 times below.
#define CHUNK ((((unsigned int)RAND_MAX) + 1) / 5)

// weasel #2: for loop lets me define and use a variable in C++ (not C89)
for (unsigned int n = 5*CHUNK; n >= 5*CHUNK;)
    // weasel #3: sequence point in the ternary operator
    ((n = rand()) < CHUNK) ? std::cout << 2 << "\n" :
             (n < 2*CHUNK) ? std::cout << 5 << "\n" :
             (n < 3*CHUNK) ? std::cout << 22 << "\n" :
             (n < 4*CHUNK) ? std::cout << 55 << "\n" :
             (n < 5*CHUNK) ? std::cout << 332 << "\n" :
             (void)0;
             // weasel #4: retry if we get one of the few biggest values
             // that stop us distributing values evenly between 5 options.

, , , srand(). , . :

for (unsigned int n = (srand((time(0) % UINT_MAX)), 5*CHUNK); n >= 5*CHUNK;)

, .

+5

, . , :

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

int main()
{
    srand(time(0));

    int randomNumber = ((int[]) {2, 5, 22, 55, 332})[rand() % 5];

    std::cout << randomNumber << std::endl;

    return 0;
}    
0

Your "one statement" criterion is very vague. Do you mean one machine instruction, one call to stdlib?

If you mean one machine instruction, the answer is no, without special equipment.

If you mean one function call, then of course it is possible. You can write a simple function to do what you want:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int setSize = 5;
    int set[] = {2, 5, 22, 55, 332 };
    srand( time(0) );

    int number = rand() % setSize;
    printf("%d %d", number, set[number]);
    return 0;
}
0
source

Source: https://habr.com/ru/post/1736904/


All Articles