# C++: Constrained Random Points on a Circle

Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that $10 \leq \sqrt{ x^2 + y^2 } \leq 15$. Then display/plot them. The outcome should be a “fuzzy” circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.

There are several possible approaches to accomplish this. Here are two possible algorithms.

1) Generate random pairs of integers and filter out those that don’t satisfy this condition:

$10 \leq \sqrt{ x^2 + y^2 } \leq 15$.

2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.

#include <windows.h>
#include <list>
#include <iostream>

//--------------------------------------------------------------------------------------------------
using namespace std;

//--------------------------------------------------------------------------------------------------
class point
{
public:
int x, y;
point()                  { x = y = 0; }
point( int a, int b )    { x = a; y = b; }
void set( int a, int b ) { x = a; y = b; }
};
//--------------------------------------------------------------------------------------------------
class rndCircle
{
public:
void draw()
{
createPoints();
drawPoints();
}

private:
void createPoints()
{
point pt;
for( int x = 0; x < 200; x++ )
{
int a, b, c;
while( true )
{
a = rand() % 31 - 15;
b = rand() % 31 - 15;
c = a * a + b * b;
if( c >= 100 && c <= 225 ) break;
}
pt.set( a, b );
_ptList.push_back( pt );
}
}

void drawPoints()
{
HDC dc = GetDC( GetConsoleWindow() );
for( list<point>::iterator it = _ptList.begin(); it != _ptList.end(); it++ )
SetPixel( dc, 300 + 10 * ( *it ).x, 300 + 10 * ( *it ).y, RGB( 255, 255, 0 ) );
}

list<point> _ptList;
};
//--------------------------------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );
srand( GetTickCount() );
rndCircle c;
c.draw();
system( "pause" );
return 0;
}
//--------------------------------------------------------------------------------------------------


SOURCE

Content is available under GNU Free Documentation License 1.2.