Random Number

Pages: 12
That was intentional. If the screen is center 0,0 and +- 1000 pixels, off then we don't want -1000 to -1 (those would be on-screen?).

I am admittedly guessing @ what he wants though. It could be +- 500 or 0-1000 or something else entirely, and odds are very high his screen isn't square (some multiple of 640x480 or whatever).

If the OP provides distribution requirements, I will take a stab at meeting them. Otherwise I assume biased random is random .. it saves a lot of trouble.

The overflow can be corrected if it is a concern.
Last edited on
Thanks guys!

Basically the screen starts a t (0, 0), the left most corner.
Would want anything outside the screen size, how large the value outside the screen size doesn't matter much. Say [-10...0 included], [1...999 excluded] and [1000, 1010 included].
But as long as the [1-999] is excluded is what I am looking for.

Your solutions help a lot, learnt a lot from this. Thanks!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <random>
#include <utility>
#include <limits>
#include <iostream>

using point = std::pair<int,int> ;

// random integer not in [low,high] invariant: low <= high
int random_int_not_in( int low, int high )
{
    static std::mt19937 rng( std::random_device{}() ) ;

    const int span = high - low + 1 ;
    using limits = std::numeric_limits<int> ;
    const int r = std::uniform_int_distribution<int>( limits::min(), limits::max()-span )(rng) ;
    return r < low ? r : r+span ;
}

// note: both x and y co-ordinates are outside the range of the rect
point random_point_ouside_rect( point top_left, point bottom_right )
{
    return { random_int_not_in( top_left.first, bottom_right.first ),
             random_int_not_in( top_left.second, bottom_right.second ) } ;
}

// invariant: top left is (0,0), width > 0, height > 0
// note: both x and y co-ordinates are outside the range of valid screen co-ordinates
point random_point_ouside_screen( int width, int height ) 
{ return random_point_ouside_rect( {0,0}, { width-1, height-1 } ) ; }

int main() // usage
{
    for( int i = 0 ; i < 25 ; ++i )
    {
        // screen size is 1000x1000 with top left at (0,0)
        const point pt = random_point_ouside_screen( 1000, 1000 ) ;
        std::cout << "( " << pt.first << ", " << pt.second << " )\n" ;
    }
}
Last edited on
Topic archived. No new replies allowed.
Pages: 12