Jump to content

Constrained random points on a circle: Difference between revisions

m (→‎{{header|PureBasic}}: Optimized the code a little)
Line 8:
 
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
 
=={{header|C}}==
 
The general scheme is :
 
1. All points satisfying the inequality are enumerated.
2. 100 points are chosen at random from this set and plotted.
3. To ensure that the same point is not picked twice and hence speed up the plotting, the chosen point is swapped with the last point after plotting. The new point is then chosen from the new set minus the last element. The position of this last element moves towards the head as the loop progresses.
 
<lang C>
 
#include<stdlib.h>
#include<stdio.h>
#include<conio.h>
#include<math.h>
 
typedef struct{
int x,y;
}points;
 
points set[500];
int last;
 
void swapWithLast(int position,int whereLast)
{
int temp = set[position].x;
set[position].x=set[whereLast].x;
set[whereLast].x = temp;
 
temp = set[position].y;
set[position].y=set[whereLast].y;
set[whereLast].y = temp;
}
 
void createSet()
{
int x,y,i=0;
 
for(x=-15;x<=15;x++)
{
for(y=-15;y<=15;y++)
{
if(sqrt(x*x+y*y)>=10.0 && sqrt(x*x+y*y)<=15.0)
{
set[i].x = x;
set[i].y = y;
i++;
}
}
}
 
last = i;
}
 
void plotFuzzySet(char ch)
{
int pos,i;
 
for(i=0;i<100;i++)
{
pos = rand()%last;
 
gotoxy(40 + set[pos].x,30 + set[pos].y);
 
printf("%c",ch);
 
swapWithLast(pos,last-1);
 
last--;
}
}
 
int main()
{
srand((unsigned int)time(NULL));
 
clrscr();
createSet();
plotFuzzySet('*');
 
getch();
return 0;
}
</lang C>
 
Output will differ from system to system. A better rendering would be to use graphics libraries like OpenGL or Turbo BGI.
 
<Output>
 
 
* * *
* ** *
* *** ** *
** * ** *
** * * * *
* * * **
* ** *
* * *
** * **
*
* *
**
* *
**
* ** *
* *
* *
** *
* *
* * *
*
** * *
* * * ***
* * *
** *
* * ** * *
* * *
* **
* **
</Output>
 
=={{header|D}}==
503

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.