Constrained random points on a circle: Difference between revisions

m
 
(148 intermediate revisions by 68 users not shown)
Line 1:
{{task|Probability and statistics}}
 
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that <math>10 \leq \sqrt{ x^2 + y^2 } \leq 15 </math>. 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.
;Task:
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that <br><math>10 \leq \sqrt{ x^2 + y^2 } \leq 15 </math>. <br>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.
Line 8 ⟶ 10:
 
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
<br><br>
 
=={{header|11l}}==
{{trans|Julia}}
<syntaxhighlight lang="11l">F print_circle(lo, hi, ndots)
V canvas = [[0B] * (2*hi+1)] * (2*hi+1)
V i = 0
L i < ndots
V x = random:(-hi..hi)
V y = random:(-hi..hi)
I x^2 + y^2 C lo^2 .. hi^2
canvas[x + hi][y + hi] = 1B
i++
 
L(i) 0 .. 2*hi
print(canvas[i].map(j -> I j {‘♦ ’} E ‘ ’).join(‘’))
print_circle(10, 15, 100)</syntaxhighlight>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC DrawCircle(BYTE rmin,rmax,max,x0,y0)
BYTE count,limit
INT x,y,r2,rmin2,rmax2
 
limit=rmax*2+1
rmin2=rmin*rmin
rmax2=rmax*rmax
count=0
WHILE count<max
DO
x=Rand(limit) y=Rand(limit)
x==-rmax y==-rmax
r2=x*x+y*y
IF r2>=rmin2 AND r2<=rmax2 THEN
Plot(x+x0,y+y0)
count==+1
FI
OD
RETURN
 
PROC Main()
BYTE CH=$02FC,COLOR0=$02C4
 
Graphics(5+16)
Color=1
COLOR0=$0C
 
DrawCircle(10,15,100,40,24)
 
DO UNTIL CH#$FF OD
CH=$FF
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Constrained_random_points_on_a_circle.png Screenshot from Atari 8-bit computer]
 
=={{header|Ada}}==
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
with Ada.Numerics.Discrete_Random;
procedure Circle is
Line 104 ⟶ 160:
Ada.Text_IO.Put_Line ("Chosen from precalculated:");
Print_Points (My_Circle_Precalculated);
end Circle;</langsyntaxhighlight>
 
Output:
Line 179 ⟶ 235:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to use of '''format'''[ted] ''transput''}}
<langsyntaxhighlight lang="algol68">PROC clrscr = VOID:
printf(($g"[2J"$,REPR 27)); # ansi.sys #
 
Line 250 ⟶ 306:
gotoxy(2*radius+1, 2*radius+1);
newline(stand in)
)</langsyntaxhighlight>
Sample output:
<pre>
Line 285 ⟶ 341:
</pre>
 
=={{header|BBC BASICAutoHotkey}}==
Requires the GDI+ standard library by tic: http://www.autohotkey.com/forum/viewtopic.php?t=32238<br /> Works with individual pixels.
<lang bbcbasic> MODE 8
[[File:Ahk_fuzzycircle.png|thumb|right]]<syntaxhighlight lang="ahk">z=100 ; x = x-coord; y = y-coord; z = count; pBitmap = a pointer to the image; f = filename
 
pToken := Gdip_Startup()
pBitmap := Gdip_CreateBitmap(31, 32)
 
While z
{
Random, x, -20, 20
Random, y, -20,20
If ( t := sqrt(x**2 + y**2) ) >= 10 && t <= 15
Gdip_SetPixel(pBitmap, x+15, y+16, 255<<24), z--
}
 
Gdip_SaveBitmapToFile(pBitmap, f := A_ScriptDir "\ahk_fuzzycircle.png")
run % f
 
Gdip_DisposeImage(pBitmap)
Gdip_Shutdown(pToken)</syntaxhighlight>
 
=={{header|BASIC}}==
 
==={{header|BASIC256}}===
{{trans|PureBasic}}
<syntaxhighlight lang="freebasic">graphsize 31, 31
 
for i = 1 to 100
do
x = int(rand * 30) - 15
y = int(rand * 30) - 15
r = sqr(x*x + y*y)
until 10 <= r and r <= 15
color rgb(255, 0, 0)
plot(x+15, y+15)
next i
end</syntaxhighlight>
 
==={{header|BBC BASIC}}===
<syntaxhighlight lang="bbcbasic"> MODE 8
ORIGIN 640, 512
FOR i% = 1 TO 1000
Line 293 ⟶ 387:
r = SQR(x%^2 + y%^2)
IF r >= 10 IF r <= 15 PLOT x%*2, y%*2
NEXT</langsyntaxhighlight>
 
==={{header|FreeBASIC}}===
Pre calculate and plot 100 points to the console
<syntaxhighlight lang="freebasic">'Free Basic version .9
 
#define Intrange(f,l) int(Rnd*(((l)+1)-(f))+(f))
 
Type pair
As Integer x,y
End Type
 
Operator =(a As pair,b As pair) As Integer
Return a.x=b.x And a.y=b.y
End Operator
 
Function NotInArray(a() As pair,n As pair) As Integer
For z As Integer=Lbound(a) To Ubound(a)
If a(z)=n Then Return 0
Next z
Return -1
End Function
 
Redim As pair pts(0)
Dim As Integer x,y,counter
Do
counter=counter+1
x=IntRange(-20,20)
y=IntRange(-20,20)
var root=Sqr(x*x+y*y)
If 10<= root And root<=15 Then
If NotInArray(pts(),Type<pair>(x,y)) Then
Redim Preserve pts(1 To Ubound(pts)+1)
pts(Ubound(pts))=Type<pair>(x,y)
End If
End If
Loop Until counter=100000
 
'============== Plot to Console ======================
 
dim as integer yres=hiword(width)
dim as integer xres=loword(width)
 
#define map(a,b,x,c,d) ((d)-(c))*((x)-(a))/((b)-(a))+(c)
#define _X(num) int( map(0,xres,(num),0,loword(width)))
#define _Y(num) int( map(0,yres,(num),0,hiword(width)))
 
counter=0
For n As Integer=Lbound(pts) To Ubound(pts)
counter=counter+1
if counter <=100 then
var xpos=map(-20,20,pts(n).x,0,xres)
var ypos=map(-20,20,pts(n).y,0,yres)
locate _Y(ypos),_X(xpos)
print "*"
end if
Next n
 
print
locate 1,1
Print "Total number of points "; counter
print "Total number plotted ";100
print "done"
Sleep
</syntaxhighlight>
Console output:
<pre>
Total number of points 404
Total number plotted 100
done * *
* * *
* * * * * *
* * * * * * * * * *
* * * * *
* * * * * *
*
* * * * *
* * * * * *
* * * *
* * * * *
 
* * * * *
* * * * * *
* * *
* * * * * * * *
* * * *
* * * * * * * * * * *
* * * * *
 
 
</pre>
 
==={{header|Yabasic}}===
{{trans|PureBasic}}
<syntaxhighlight lang="yabasic">open window 100, 100
clear window
 
for i = 1 to 100
repeat
x = ran(30)-15
y = ran(30)-15
r = sqr(x*x + y*y)
until 10 <= r and r <= 15
color 255, 0, 0
dot x+15, y+15
next i
end</syntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 330 ⟶ 530:
 
return 0;
}</langsyntaxhighlight>Output<syntaxhighlight lang="text"> . . . .
. . .
. . . .
Line 359 ⟶ 559:
. . . .
.
. </langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
 
<syntaxhighlight lang="csharp">using System;
using System.Diagnostics;
using System.Drawing;
 
namespace RosettaConstrainedRandomCircle
{
class Program
{
static void Main(string[] args)
{
var points = new Point[404];
int i = 0;
for (int y = -15; y <= 15; y++)
for (int x = -15; x <= 15 && i < 404; x++)
{
var c = Math.Sqrt(x * x + y * y);
if (10 <= c && c <= 15)
{
points[i++] = new Point(x, y);
}
}
 
var bm = new Bitmap(600, 600);
var g = Graphics.FromImage(bm);
var brush = new SolidBrush(Color.Magenta);
 
var r = new System.Random();
for (int count = 0; count < 100; count++)
{
var p = points[r.Next(404)];
g.FillEllipse(brush, new Rectangle(290 + 19 * p.X, 290 + 19 * p.Y, 10, 10));
}
const string filename = "Constrained Random Circle.png";
bm.Save(filename);
Process.Start(filename);
}
}
}</syntaxhighlight>
 
=={{header|C++}}==
[[File:constrained_rnd_pts_on_circle.png]]
<syntaxhighlight lang="cpp">
#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;
}
//--------------------------------------------------------------------------------------------------
</syntaxhighlight>
 
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">(ns rosettacode.circle-random-points
<lang Clojure>(import '[java.awt Color Graphics Dimension]
(:import [java.awt Color Graphics Dimension]
'[javax.swing JFrame JPanel])
[javax.swing JFrame JPanel]))
(let [points (->> (for [x (range -15 16), y (range -15 16)
:when (<= 10 (Math/hypot x y) 15)]
y (range -15 16)
:when (<= 10 (Math/sqrt (+ (* x x) (* y y))) 15)]
[(+ x 15) (+ y 15)])
shuffle
(take 100 ,))]
(doto (JFrame.)
(.add (doto (proxy [JPanel] []
(paint [^Graphics g]
(doseq [[x y] points]
(.fillRect g (* 10 x) (* 10 y) 10 10))))
(.setPreferredSize (Dimension. 310 310))))
(.setResizable false)
(.setDefaultCloseOperation JFrame/DISPOSE_ON_CLOSE)
.pack
.show))</langsyntaxhighlight>
 
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
identification division.
program-id. circle.
environment division.
input-output section.
file-control.
select plot-file assign "circle.txt".
data division.
file section.
fd plot-file report plot.
working-storage section.
1 binary.
2 seed pic 9(18).
2 x pic s9(4).
2 y pic s9(4).
2 i pic 9(4).
2 dot-count pic 9(4) value 0.
2 dot-count-save pic 9(4) value 0.
2 temp-points.
3 pic s9(4) occurs 2.
2 xy-table.
3 point-pair occurs 0 to 404 depending dot-count.
4 x-point pic s9(4).
4 y-point pic s9(4).
1 plot-table value all "0".
2 occurs 31.
3 dot pic 9 occurs 31.
1 cur-date-time.
2 yyyymmdd pic 9(8).
2 hh pic 9(2).
2 mm pic 9(2).
2 ss pic 9(2).
1 plot-work.
2 plot-item pic xb occurs 31.
report section.
rd plot.
1 plot-line type de.
2 line plus 1.
3 column is 1 source is plot-work pic x(62).
procedure division.
begin.
perform compute-seed
perform find-all-valid-points
perform shuffle-point-pairs
perform select-100-dots
perform print-dots
stop run
.
 
find-all-valid-points.
perform varying x from -15 by 1 until x > +15
perform varying y from -15 by 1 until y > +15
if (function sqrt (x ** 2 + y ** 2))
>= 10 and <= 15
then
move 1 to dot (x + 16 y + 16)
add 1 to dot-count
compute x-point (dot-count) = x + 16
compute y-point (dot-count) = y + 16
end-if
end-perform
end-perform
display "Total points: " dot-count
.
 
shuffle-point-pairs.
move dot-count to dot-count-save
compute i = function random (seed) * dot-count + 1
perform varying dot-count from dot-count by -1
until dot-count < 2
move point-pair (i) to temp-points
move point-pair (dot-count) to point-pair (i)
move temp-points to point-pair (dot-count)
compute i = function random * dot-count + 1
end-perform
move dot-count-save to dot-count
.
 
select-100-dots.
perform varying i from 1 by 1
until i > 100
compute x = x-point (i)
compute y = y-point (i)
move 2 to dot (x y)
end-perform
.
 
print-dots.
open output plot-file
initiate plot
perform varying y from 1 by 1 until y > 31
move spaces to plot-work
perform varying x from 1 by 1 until x > 31
if dot (x y) = 2
move "o" to plot-item (x)
end-if
end-perform
generate plot-line
end-perform
terminate plot
close plot-file
.
 
compute-seed.
unstring function current-date into
yyyymmdd hh mm ss
compute seed =
(function integer-of-date (yyyymmdd) * 86400)
compute seed = seed
+ (hh * 3600) + (mm * 60) + ss
compute seed = function mod (seed 32768)
.
 
end program circle.
</syntaxhighlight>
<pre>
 
o o o
o o o o
o o o o
o o o o o o o
o o o o o o o
o o o o o o o o
o o o o
o o
o o
o o o o
o o
o
o o o
o o
o o o o
o o o
o o o
o
o o o
o o
o
o o o o
o o
o o o
o o o o o
o o o
o o o o o o
o o o
o o o
o
</pre>
 
=={{header|CoffeeScript}}==
<syntaxhighlight lang="coffeescript">
NUM_POINTS = 100
MIN_R = 10
MAX_R = 15
 
random_circle_points = ->
rand_point = ->
Math.floor (Math.random() * (MAX_R * 2 + 1) - MAX_R)
points = {}
cnt = 0
while cnt < 100
x = rand_point()
y = rand_point()
continue unless MIN_R * MIN_R <= x*x + y*y <= MAX_R * MAX_R
points["#{x},#{y}"] = true
cnt += 1
points
plot = (points) ->
range = [-1 * MAX_R .. MAX_R]
for y in range
s = ''
for x in range
s += if points["#{x},#{y}"] then '*' else ' '
console.log s
plot random_circle_points()
</syntaxhighlight>
 
The output may be a bit distorted, since even monospace fonts take more vertical space per character than horizontal space.
<syntaxhighlight lang="text">
> coffee foo.coffee
** *
* ** * *
* * * *
* ** *
* * * *
* *
*
* *
***
** **** *
* *
* *
**
*
* **
* * *
**
* * **
* *
* *
* *
* *
***
*** * * * * *
*** *
* * * * *
* * *
</syntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(flet ((good-p (x y) (<= 100 (+ (* x x) (* y y)) 255)))
(loop with x with y with cnt = 0
with scr = (loop repeat 31 collect (loop repeat 31 collect " "))
Line 391 ⟶ 917:
(setf (elt (elt scr y) x) "@ ")
(incf cnt))
finally (mapc #'(lambda (row) (format t "~{~a~^~}~%" row)) scr)))</langsyntaxhighlight>
 
=={{header|D}}==
This uses std.complex because D built-in complex numbers will be deprecated.
<lang d>import std.stdio, std.random, std.math;
<syntaxhighlight lang="d">import std.stdio, std.random, std.math, std.complex;
 
void main() {
char[31][31] table = ' ';
 
foreach (iimmutable _; 0 .. 100) {
int x, y;
do {
x = uniform(-15, 16);
y = uniform(-15, 16);
} while(abs(12.5 - abscomplex(x +, y * 1i).abs) > 2.5);
table[x + 15][y + 15] = '*';
}
 
foreach writefln(row;"%-(%s\n%)", table);
}</syntaxhighlight>
writeln(row);
{{out}}
}</lang>
<pre>
*
Line 441 ⟶ 968:
* * * *
** </pre>
=={{header|Delphi}}==
{{libheader| Winapi.Windows}}
{{libheader| System.SysUtils}}
{{libheader| Vcl.Graphics}}
{{libheader| Vcl.Controls}}
{{libheader| Vcl.Forms}}
{{libheader| Vcl.ExtCtrls}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
unit Main;
 
interface
 
uses
Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.ExtCtrls;
 
type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormPaint(Sender: TObject);
end;
 
var
Form1: TForm1;
Points: TArray<TPoint>;
 
implementation
 
{$R *.dfm}
 
procedure TForm1.FormCreate(Sender: TObject);
begin
ClientHeight := 600;
ClientWidth := 600;
end;
 
procedure TForm1.FormPaint(Sender: TObject);
var
i: integer;
p: TPoint;
index: integer;
begin
SetLength(Points, 404);
i := 0;
for var y := -15 to 15 do
for var x := -15 to 15 do
begin
if i >= 404 then
Break;
var c := Sqrt(x * x + y * y);
if (10 <= c) and (c <= 15) then
begin
inc(i);
points[i] := TPoint.Create(x, y);
end;
end;
var bm := TBitmap.create;
bm.SetSize(600, 600);
with bm.Canvas do
begin
Pen.Color := clRed;
Brush.Color := clRed;
Brush.Style := bsSolid;
Randomize;
 
for var count := 0 to 99 do
begin
repeat
index := Random(404);
p := points[index];
until (not p.IsZero);
points[index] := TPoint.Zero;
 
var cx := 290 + 19 * p.X;
var cy := 290 + 19 * p.Y;
Ellipse(cx - 5, cy - 5, cx + 5, cy + 5);
end;
end;
Canvas.Draw(0, 0, bm);
bm.Free;
end;
end.</syntaxhighlight>
 
=={{header|EasyLang}}==
[https://easylang.dev/show/#cod=bY0xDsIwFEP3nOKN0Igqv6hMzWGqtohIJYhPBMntUShsbLafZb8uYV2YYmJAnDNAxqNjnENMHIUDcqpx+R8rnsddE7tMQ8ZSaCj7ysIZcQweZYwzWqX0lcDn03rka6+350LvsNSdbpN1qvv1g07rsvVb05o3 Run it]
 
<syntaxhighlight>
while cnt < 100
x = randint 31 - 16
y = randint 31 - 16
r = sqrt (x * x + y * y)
if 10 <= r and r <= 15
cnt += 1
move 50 + x * 2 50 + y * 2
circle 1
.
.
</syntaxhighlight>
 
=={{header|EchoLisp}}==
Using the '''plot''' library. For a greater visual appeal, points are plotted as circles of random radius and color. The resulting image is at [http://www.echolalie.org/echolisp/images/circle.png].
<syntaxhighlight lang="scheme">
(lib 'math)
(lib 'plot)
 
(define (points (n 100) (radius 10) (rmin 10) (rmax 15) (x) (y))
(plot-clear)
(plot-x-minmax (- rmax))
(plot-y-minmax( - rmax))
(for [(i n)]
(set! x (round (* (random -1) rmax)))
(set! y (round (* (random -1) rmax)))
#:when (in-interval? (pythagore x y) rmin rmax)
;; add a little bit of randomness : dots color and radius
(plot-fill-color (hsv->rgb (random) 0.9 0.9))
(plot-circle x y (random radius)))
(plot-edit))
</syntaxhighlight>
 
=={{header|Elixir}}==
===Algorithm 1: Generate random pairs===
{{works with|Elixir|1.1}}
<syntaxhighlight lang="elixir">defmodule Random do
defp generate_point(0, _, _, set), do: set
defp generate_point(n, f, condition, set) do
point = {x,y} = {f.(), f.()}
if x*x + y*y in condition and not point in set,
do: generate_point(n-1, f, condition, MapSet.put(set, point)),
else: generate_point(n, f, condition, set)
end
def circle do
f = fn -> :rand.uniform(31) - 16 end
points = generate_point(100, f, 10*10..15*15, MapSet.new)
range = -15..15
for x <- range do
for y <- range do
IO.write if {x,y} in points, do: "x", else: " "
end
IO.puts ""
end
end
end
 
Random.circle</syntaxhighlight>
 
'''Example output:'''
<pre>
x
x x xx x
x x x x xxx x
x x x xx x
x x x x x x
xx x
xx x x
xxx
xxx
xxx
x x
 
x xx
xx x
x
xx
x x x
xx
x x
xx x x x
x x x
x x
x xx xx
x x x
x x x x
x xx x xx
x xx x x
x xx x
x xx
</pre>
 
===Algorithm 2: Precalculate===
{{trans|Ruby}}
{{works with|Elixir|1.2}}
<syntaxhighlight lang="elixir">defmodule Constrain do
def circle do
range = -15..15
r2 = 10*10..15*15
all_points = for x <- range, y <- range, x*x+y*y in r2, do: {x,y}
IO.puts "Precalculate: #{length(all_points)}"
points = Enum.take_random(all_points, 100)
Enum.each(range, fn x ->
IO.puts Enum.map(range, fn y -> if {x,y} in points, do: "o ", else: " " end)
end)
end
end
 
Constrain.circle</syntaxhighlight>
 
{{out|Example}}
<pre>
Precalculate: 404
 
o o
o
o o o o o o
o o o o o
o o o o o o o
o o o o
o o o o o
o o o o
o o o o o
o o o
 
o o o
o o
o o o
o o o o o
o
o o o
o o o o o o
o
o o
o o o
o o o
o o o o o
o o o
o o o o o o o
o o o o o o
o
o o
o o
 
</pre>
 
=={{header|Euphoria}}==
{{works with|Euphoria|4.0.3, 4.0.0 or later}}
This program generates the set of 404 possible points in the ring. It randomly chooses 100 pairs from the set. The 100 pairs are a subset of that set because duplicates are discarded.
<syntaxhighlight lang="euphoria">include std/console.e
 
sequence validpoints = {}
sequence discardedpoints = {}
sequence rand100points = {}
atom coordresult
integer randindex
 
--scan for all possible values. store discarded ones in another sequence, for extra reference.
for y = -15 to 15 do
for x = -15 to 15 do
coordresult = sqrt( x * x + y * y )
if coordresult >= 10 and coordresult <= 15 then --if it would fall in the ring area
validpoints &= {{x, y, coordresult}} --concatenate (add to the end) the coordinate pair x, y and the
-- result into a subsequence of sequence validpoints
else
discardedpoints &= {{x, y, coordresult}} --else put it in the discarded sequence
end if
end for
end for
 
for i = 1 to 100 label "oneofhundred" do --make 100 random coordinate pairs
randindex = rand(length(validpoints) ) --random value from 1 to the number of 3 value subsequences in validpoints (the data)
 
if length(rand100points) = 0 then --if rand100points sequence is empty, add the first subsequence to it.
rand100points &= {validpoints[randindex]}
else --if it isn't empty, then..
for j = 1 to length(rand100points) do --loop through each "data chunk" in rand100points
if equal(validpoints[randindex], rand100points[j]) = 1 then --if any are the same as the randomly chosen chunk in
retry "oneofhundred" -- validpoints, then retry from one line below the "oneofhundred" loop without incrementing i.
end if --the continue keyword would increment i instead.
 
end for
rand100points &= {validpoints[randindex]} --length of rand100points isnt 0 and no data chunks match ones that the program
--already picked before, so add this subsequence chunk to rand100points.
end if
end for
 
for i = 1 to 32 do --32 lines
printf(1,"\n")
for j = 1 to 32 label "xscan" do --32 characters on each line
for k = 1 to length(rand100points) do --for every subsequence in this
if rand100points[k][1]+16 = j and rand100points[k][2]+16 = i then --if the x and y coordinates in the picked points
printf(1, 178) --(adjusted to minimum of 1,1) are at the same place as in the console output grid
continue "xscan" --print a funny character and continue to the next "xscan"
end if
end for
printf(1, 176) --if no picked points were there, print another funny character to represent a blank space
end for
end for
 
printf(1, "\nNumber of valid coordinate pairs %d :", length(validpoints) )
printf(1, "\nNumber of discarded coordinate pairs : %d", length(discardedpoints) )
printf(1, "\nNumber of randomly picked coordinate pairs : %d\n", length(rand100points) )
any_key()</syntaxhighlight>
Output:
<pre>
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░▓░░░░░░░░░░░░░░
░░░░░░░░░░░░░▓░░░░░░░░░░░░░░░░░░
░░░░░░░░░▓░░░▓▓░▓░░░▓░░░░░░░░░░░
░░░░░░▓░░░░░░▓░░░▓░░░░░▓░▓░░░░░░
░░░░░░░░░▓░▓░░░░░░░▓░░▓░░▓▓░░░░░
░░░▓░░░░▓░▓░░░░░░░░░░░░▓░░░░░░░░
░░░░░░░░░▓░░░░░░░░░░░▓░░░▓░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░▓▓░░▓░░░
░░░░░░▓▓░░░░░░░░░░░░░░░▓░░░░░░░░
░░░░░░▓░░░░░░░░░░░░░░░░░░░░░░░░░
░▓░░▓▓░░░░░░░░░░░░░░░░░░░░░░░▓░░
░░░░░▓░░░░░░░░░░░░░░░░░░░░░░▓░░░
░░▓░░░░░░░░░░░░░░░░░░░░░░▓▓▓▓░░░
░▓░░▓░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░▓░░░░░░░░░░░░░░░░░░░░▓▓▓░▓░░
░░░▓░░░░░░░░░░░░░░░░░░░░░▓░▓░▓░░
░▓▓░░░░░░░░░░░░░░░░░░░░░░░▓▓░░░░
░░░▓░▓░░░░░░░░░░░░░░░░░░░▓░░░░░░
░░░▓░░░░░░░░░░░░░░░░░░░░░▓░░░▓░░
░░▓░▓░░░░░░░░░░░░░░░░░░░▓░░░▓░░░
░░░░░░░▓░░░░░░░░░░░░░░░▓░░░░░░░░
░░░▓░░░░░░░░░░░░░░░░░░░▓░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░▓░░░░░░░
░░░░░░▓░░▓░░░░░░░░░░░▓░▓░░░░░░░░
░░░░░░░░░░░░░░░░░▓░░░░░░░░░░░░░░
░░░░░░░▓░░▓░░░░░░░░░░░░▓░░░░░░░░
░░░░░░░░░░░░░▓░▓▓▓▓░░░▓▓░░░░░░░░
░░░░░░░░░▓▓░░▓░░▓░░▓▓░░░░░░░░░░░
░░░░░░░░░░▓░░▓░▓▓▓░░▓░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
Number of valid coordinate pairs 404 :
Number of discarded coordinate pairs : 557
Number of randomly picked coordinate pairs : 100
Press Any Key to continue...</pre>Extra EuSDL code : <syntaxhighlight lang="euphoria">
for i = 1 to length(validpoints) do --simple each pixel output to screen surface
dummy=pixelColor(surface,validpoints[i][1]+18,validpoints[i][2]+18,#AA0202FF) --i is index number of each subsequence 'chunk'.
--index 1 is x, index 2 is y, inside that chunk.
end for
for i = 1 to length(discardedpoints) do
dummy=pixelColor(surface,discardedpoints[i][1]+18,discardedpoints[i][2]+52,#0202AAFF)
end for
for i = 1 to length(rand100points) do
dummy=pixelColor(surface,rand100points[i][1]+55,rand100points[i][2]+52,#02AA02FF)
end for
 
dummy=boxColor(surface,0,71,395,111,#232323FF) --background box
dummy=stringColor(surface,0,73,sprintf("Number of valid coordinate pairs %d :", length(validpoints) ),#AA0202FF)
 
dummy=stringColor(surface,0,83,sprintf("Number of discarded coordinate pairs : %d", length(discardedpoints) ),#0202AAFF)
 
dummy=stringColor(surface,0,93,sprintf("Number of randomly picked coordinate pairs : %d", length(rand100points) ),#02AA02FF)</syntaxhighlight>SDL Output :
[[File:Fuzzy_circle_Euphoria.png]] That particular program used a -16 to +16 square area, so more was discarded.
 
=={{header|F_Sharp|F#}}==
This version uses method 1 from the task description and just calculates 100 suitable points to plot.
The INTERACTIVE bit just permits this code in a .fsx file to be run with the interactive interpreter or compiled to an exe.
<langsyntaxhighlight lang="fsharp">module CirclePoints =
let main args =
let rnd = new System.Random()
Line 468 ⟶ 1,355:
[<EntryPoint>]
let main args = CirclePoints.main args
#endif</langsyntaxhighlight>
An example of the output:
<pre>
Line 500 ⟶ 1,387:
o o o oo o
o o</pre>
 
=={{header|Factor}}==
{{works with|Factor|0.99 2020-01-23}}
<syntaxhighlight lang="factor">USING: io kernel math.matrices math.order math.ranges
math.statistics math.vectors random sequences strings ;
 
CHAR: X -15 15 [a,b] dup cartesian-product concat
[ sum-of-squares 100 225 between? ] filter 100 sample
[ 15 v+n ] map 31 31 32 <matrix> [ matrix-set-nths ] keep
[ >string print ] each</syntaxhighlight>
{{out}}
<pre>
XX X X
XX XXX X X X
X XXX
XX X X
X X XX X X X
X X X
X X X XXXX
X X X XXX
XXX
X
XXX XX
X XX
X
X X
X
X X
X
XXX X
X X
XX X
XX X
XX X X
X X
XXX X X
X X XX XX
X X XX X XX
X X
</pre>
 
=={{header|Falcon}}==
<syntaxhighlight lang="falcon">
// Generate points in [min,max]^2 with constraint
function random_point (min, max, constraint)
[x, y] = [random(min, max), random(min, max)]
return constraint(x, y) ? [x, y] : random_point(min, max, constraint)
end
 
// Generate point list
in_circle = { x, y => 10**2 <= x**2 + y**2 and x**2 + y**2 <= 15**2 }
points = [].comp([0:100], {__ => random_point(-15, 15, in_circle)})
 
// Show points
for i in [-15:16]
for j in [-15:16]
>> [i, j] in points ? "x" : " "
end
>
end
</syntaxhighlight>
Example output:
<pre>
xxx x
xx x x xx
x xx xx
x x x x x x x x
x x
xx x x
x x x
xx
x x xx
x x
x x
x xx
x
xx
x xx
x xx x
x
xx x xx
xx x x
x x
x x x x
x x x
x x x x x x
x x
x x x x
</pre>
 
=={{header|Forth}}==
{{works with|gforth|0.7.3}}
<br>
<syntaxhighlight lang=forth>#! /usr/bin/gforth
\ Constrained random points on a circle
 
require random.fs
 
\ initialize the random number generator with a time-dependent seed
utime drop seed !
 
\ generates a random integer in [-15,15]
: random-coord ( -- n )
31 random 15 -
;
 
\ generates a random point on the constrained circle
: random-point ( -- x y )
0 0
BEGIN
2drop
random-coord random-coord
2dup dup * swap dup * +
dup 100 >= swap 225 <= and
UNTIL
;
 
31 31 * CONSTANT SIZE
CREATE GRID SIZE cells allot GRID SIZE cells erase
 
\ get the address of point (x,y)
: point-addr ( x y -- addr )
15 + 31 * + 15 + cells GRID +
;
 
\ generate 100 random points and mark them in the grid
: gen-points ( -- )
100 0 ?DO
true random-point point-addr !
LOOP
;
 
\ prints the grid
: print-grid ( -- )
16 -15 ?DO
16 -15 ?DO
i j point-addr @
IF
42
ELSE
32
THEN
emit
LOOP
cr
LOOP
;
 
gen-points print-grid
bye</syntaxhighlight>
 
{{out}}
<pre>
*
*****
* ** **
* * * *
* **
***
* ** *
* *
* * **
*
*
* *
* * *
*
**
* *
* * * *
*
* **
* ** * **
* * *
* * ** *
** * * * * *
*
*** * *
** **
* *
</pre>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">program Constrained_Points
implicit none
Line 577 ⟶ 1,654:
end do
end program</langsyntaxhighlight>
Output
<pre>
Line 609 ⟶ 1,686:
* * ** *
*</pre>
 
=={{header|Frink}}==
<syntaxhighlight lang="frink">g = new graphics
 
count = 0
do
{
x = random[-15,15]
y = random[-15,15]
r = sqrt[x^2 + y^2]
if 10 <= r and r <= 15
{
count = count + 1
g.fillEllipseCenter[x,y,.3, .3]
}
} while count < 100
 
g.show[]</syntaxhighlight>
 
=={{header|gnuplot}}==
{{Works with|gnuplot|5.0 (patchlevel 3) and above}}
[[File:RingRandPntsGnu.png|right|thumb|Output RingRandPntsGnu.png]]
 
<syntaxhighlight lang="gnuplot">
## Ring of random points 2/18/17 aev
reset
fn="RingRandPntsGnu";
ttl="Ring of random points"
ofn=fn.".png"; lim=1000;
randgp(top) = floor(rand(0)*top)
set terminal png font arial 12 size 640,640
set output ofn
set title ttl font "Arial:Bold,12"
unset key;
set size square
set parametric
set xrange [-20:20]; set yrange [-20:20];
set style line 1 lt rgb "red"
$rring << EOD
EOD
set print $rring append
do for [i=1:lim] {
x=randgp(30); y=randgp(30);
r=sqrt(x**2+y**2);
if (r>=10&&r<=15) \
{print x," ",y; print -x," ",-y;print x," ",-y; print -x," ",y;}
}
plot [0:2*pi] sin(t)*10,cos(t)*10, sin(t)*15,cos(t)*15 ls 1,\
$rring using 1:2 with points pt 7 ps 0.5 lc "black"
set output
unset print
</syntaxhighlight>
{{Output}}
<pre>
File: RingRandPntsGnu.png
</pre>
 
=={{header|Go}}==
'''Algorithm 1:'''
<langsyntaxhighlight lang="go">package main
 
import (
"bytes"
"fmt"
"math/rand"
"time"
)
 
const (
type pt struct {
x,nPts y= int100
rMin = 10
}
rMax = 15
)
 
func main() {
rand.Seed(time.NanosecondsNow().Unix())
span := rMax + 1 + rMax
// generate random points, accumulate 100 distinct points meeting condition
mrows := make(map[int]pt[]byte, span) // key is buffer index
for len(m)r <:= 100range rows {
prows[r] := pt{randbytes.IntnRepeat(31)[]byte{' - 15'}, rand.Intn(31span*2) - 15}
}
rs := p.x*p.x + p.y*p.y
u if 100 <:= rs0 &&// rs <=count 225unique {points
min2 := rMin * rMin
m[(p.x+15)*2+(p.y+15)*31*2] = p
max2 := rMax * rMax
for n := 0; n < nPts; {
x := rand.Intn(span) - rMax
y := rand.Intn(span) - rMax
// x, y is the generated coordinate pair
rs := x*x + y*y
if rs < min2 || rs > max2 {
continue
}
n++ // count pair as meeting condition
r := y + rMax
c := (x + rMax) * 2
if rows[r][c] == ' ' {
rows[r][c] = '*'
u++
}
}
//for plot_, torow buffer:= range rows {
fmt.Println(string(row))
b := bytes.Repeat([]byte{' '}, 31*31*2)
for i := range m {
b[i] = '*'
}
fmt.Println(u, "unique points")
// print buffer to screen
}</syntaxhighlight>
for i := 0; i < 31; i++ {
'''Algorithm 2:'''
fmt.Println(string(b[i*31*2 : (i+1)*31*2]))
<syntaxhighlight lang="go">package main
}
}</lang>
Algorithm 2:
<lang go>package main
 
import (
"bytes"
"fmt"
"math/rand"
"time"
)
 
const (
type pt struct {
x,nPts y= int100
rMin = 10
}
rMax = 15
)
 
func main() {
rand.Seed(time.Now().Unix())
// generate possible points
allvar :=poss make([]pt,struct{ 0x, 404)y int }
for xmin2 := -15; x <= 15;rMin x++* {rMin
for ymax2 := -15; y <= 15;rMax y++* {rMax
for y := -rMax; y rs :<= x*xrMax; y++ y*y{
for x := -rMax; if 100x <= rs && rs <=rMax; 225x++ {
if r2 := x*x all+ y*y; r2 >= append(all,min2 pt{x,&& y})r2 <= max2 {
poss = append(poss, struct{ x, y int }{x, y})
}
}
}
if fmt.Println(len(allposs), !="possible 404 {points")
span := rMax + panic(len(all))1 + rMax
rows := make([][]byte, span)
for r := range rows {
rows[r] = bytes.Repeat([]byte{' '}, span*2)
}
//u randomly:= order0
rpfor n := rand.Perm(404)0; n < nPts; n++ {
// plot 100 of themi to:= a bufferrand.Intn(len(poss))
b r := bytes.Repeat(poss[i]byte{'.y '},+ 31*31*2)rMax
for i c := 0; (poss[i].x <+ 100;rMax) i++* {2
pif := allrows[rpr][i]c] == ' ' {
b rows[(p.x+15)*2+(p.y+15)*31*2r][c] = '*'
u++
}
}
//for print_, bufferrow to:= screenrange rows {
fmt.Println(string(row))
for i := 0; i < 31; i++ {
fmt.Println(string(b[i*31*2 : (i+1)*31*2]))
}
fmt.Println(u, "unique points")
}</lang>
}</syntaxhighlight>
Output:
{{out}}
<pre>
404 possible points
* * * *
* * *
* * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * *
* * * * * * * *
* * * * *
* * * * * *
* * * * * * * *
* * * * * *
* * * * *
* * *
* *
* * * *
* * * * *
* * *
*
* *
* * *
* *
*
* * * *
* * * * *
* * * *
* * * * * * * * *
* * * * * * *
* * * * *
* * * * * * *
* * * * *
* * * * * * *
90 unique points
* * * * * * *
* *
* * * *
</pre>
 
=={{header|Haskell}}==
Using [http://rosettacode.org/wiki/Knuth_shuffle[Knuth shuffle#Haskell |Knuth Shuffle]]
<langsyntaxhighlight lang="haskell">import Data.List
import Control.Monad
import Control.Arrow
Line 734 ⟶ 1,893:
let canvas = foldl (\cs [x,y] -> replaceAt (31*(x+15)+y+15) "/ " cs ) blanco (take 100 pts)
-- show canvas
mapM_ (putStrLn.concat). takeWhile(not.null). mapunfoldr (takeJust . splitAt 31) $ iterate (drop 31) canvas</langsyntaxhighlight>
Output (added a trailing space per 'pixel'
<pre>*Main> task
Line 767 ⟶ 1,926:
/ / / / / / / /
/ / /</pre>
 
=={{header|Hy}}==
<syntaxhighlight lang="lisp">(import
math [sqrt]
random [choice]
matplotlib.pyplot :as plt)
(setv possible-points
(lfor
x (range -15 16)
y (range -15 16)
:if (<= 10 (sqrt (+ (** x 2) (** y 2))) 15)
[x y]))
 
(setv [xs ys] (zip #* (map (fn [_] (choice possible-points)) (range 100))))
; We can't use random.sample because that samples without replacement.
; #* is also known as unpack-iterable
(plt.plot xs ys "bo")
(plt.show)</syntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Generate random points in the bounded by the outside edge. Reject any found out of the prescribed bounds and stop when the required numbers of points have been generated. [[File:Fuzzycircle-unicon.PNG|thumb|plot of 2000, 100, 120]]
<langsyntaxhighlight Iconlang="icon">link graphics
 
procedure main(A) # points, inside r, outside r in pixels - default to task values
Line 794 ⟶ 1,972:
WDone()
 
end</langsyntaxhighlight>
 
=={{header|J}}==
Line 800 ⟶ 1,978:
This version deals 100 distinct coordinates from the set of acceptable coordinates (much like dealing cards from a shuffled deck):
 
<langsyntaxhighlight lang="j">gen=: ({~ 100?#)bind((#~ 1=99 225 I.+/"1@:*:),/,"0/~i:15)</langsyntaxhighlight>
 
Example use (<code><nowiki>gen''</nowiki></code> generates the points, the rest of the example code deals with rendering them as a text array):
<langsyntaxhighlight lang="j"> '*' (<"1]15+gen '')} 31 31$' '
*
Line 833 ⟶ 2,011:
**
* * *
** * </langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.util.Random;
 
public class FuzzyCircle {
Line 863 ⟶ 2,042:
}
}
}</langsyntaxhighlight>
Output:
<pre>
Line 899 ⟶ 2,078:
=={{header|JavaScript}}==
JavaScript embedded in HTML, using canvas:
<langsyntaxhighlight lang="javascript"><html><head><title>Circle</title></head>
<body>
<canvas id="cv" width="320" height="320"></canvas>
Line 944 ⟶ 2,123:
}
 
</script></body></html></langsyntaxhighlight>
 
=={{header|jq}}==
{{works with|jq}}
This solution uses a "generate and test" approach to find exactly 100 points within the specified annulus.
 
Since jq does not have a built-in PRNG, /dev/random is used instead. gnuplot and a bash or bash-like environment are also assumed.
 
<syntaxhighlight lang="bash">
#!/bin/bash
 
< /dev/random tr -cd '0-9' | fold -w 1 | jq -Mcnr '
 
# Output: a PRN in range(0;$n) where $n is .
def prn:
if . == 1 then 0
else . as $n
| (($n-1)|tostring|length) as $w
| [limit($w; inputs)] | join("") | tonumber
| if . < $n then . else ($n | prn) end
end;
 
def ss: map(.*.) | add;
 
# Input: [x,y]
# Emit . iff ss lies within the given bounds
def annulus($min; $max) : ss as $sum | select($min <= $sum and $sum <= $max);
 
limit(100;
repeat([((30 | prn) - 15), ((30 | prn) - 15)]
| select( annulus(100; 225)) ))
| "\(.[0]) \(.[1])"
' > rc-annulus.dat
</syntaxhighlight>
 
The plot can now be generated as a .png file using these gnuplot commands:
<syntaxhighlight lang="bash">
reset
set terminal pngcairo
set output 'rc-annulus.png'
set xrange [-20:20]
set yrange [-20:20]
plot "rc-annulus.dat" with points pt 1
</syntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
This solution uses the "pick random x, y and cull" rather than the "calculate valid and choose randomly" approach.
<syntaxhighlight lang="julia">function printcircle(lo::Integer, hi::Integer, ndots::Integer; pad::Integer = 2)
canvas = falses(2hi + 1, 2hi + 1)
i = 0
while i < ndots
x, y = rand(-hi:hi, 2)
if lo ^ 2 - 1 < x ^ 2 + y ^ 2 < hi ^ 2 + 1
canvas[x + hi + 1, y + hi + 1] = true
i += 1
end
end
# print
for i in 1:(2hi + 1)
row = map(j -> j ? "\u25cf " : " ", canvas[i, :])
println(" " ^ pad, join(row))
end
return canvas
end
 
printcircle(10, 15, 100)</syntaxhighlight>
 
{{out}}
<pre>
● ●
● ● ● ● ●
● ● ● ●
● ● ● ●
● ● ● ●
● ●
● ● ●
● ● ●
● ●
● ● ● ●
● ●
● ● ● ● ●
● ●
● ● ●
● ● ●
● ●
● ●
● ● ● ● ●
● ● ● ●
● ● ● ● ●
● ● ● ● ● ● ● ● ● ●
● ● ● ● ● ●
● ● ●
● ●
● ●
</pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.1.3
 
fun main(args: Array<String>) {
val r = java.util.Random()
val points = Array(31) { CharArray(31) { ' ' } }
var count = 0
while (count < 100) {
val x = r.nextInt(31) - 15
val y = r.nextInt(31) - 15
val h = x * x + y * y
if (h in 100..225) {
points[x + 15][y + 15] = 'o'
count++
}
}
for (i in 0..30) println(points[i].joinToString(""))
}</syntaxhighlight>
 
Sample output:
<pre>
ooo oo o
o
oo oo
o oo o
o ooo oo
o oo
o o o
o o oo o
o o
o o
o ooo
o oo
o oo
o o
o o o
o o
o ooo
o o o
o
oo o oo
oo o
o o o
ooo o
oo o
o o o
oo o o
o o
o o
</pre>
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{def circ
{lambda {:cx :cy :r}
{div {@ style="position:absolute;
top: {- :cy :r}px; left: {- :cx :r}px;
width: {* 2 :r}px; height: {* 2 :r}px;
border: 1px solid #000; border-radius: :rpx;"}} }}
-> circ
 
{def fuzzy_circle
{lambda {:cx :cy :rmin :rmax :n}
{circ :cx :cy :rmax}
{circ :cx :cy :rmin}
{S.map {{lambda {:cx :cy :rmin :rmax :i}
{let { {:cx :cx} {:cy :cy}
{:rmin :rmin} {:rmax :rmax}
{:x {- {round {* {random} {* 2 :rmax}}} :rmax}}
{:y {- {round {* {random} {* 2 :rmax}}} :rmax}}
} {let { {:x {+ :cx :x }}
{:y {+ :cy :y }}
{:rr {+ {* :x :x} {* :y :y}}}
{:r2min {* :rmin :rmin}}
{:r2max {* :rmax :rmax}}
} {if {or {< :rr :r2min} {> :rr :r2max}}
then else {circ :x :y 2}}
}}} :cx :cy :rmin :rmax}
{S.serie 1 :n}} }}
-> fuzzy_circle
 
{fuzzy_circle 200 700 80 120 1000}
-> plots 1000 dots between the circles r=80 and r=120 centered at [200,700]
directly in the wiki page (out of any canvas or svg contexts) as it
can be seen in http://lambdaway.free.fr/lambdawalks/?view=fuzzy_circle
 
</syntaxhighlight>
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">' RC Constrained Random Points on a Circle
 
nomainwin
Line 976 ⟶ 2,345:
[quit]
close #w
end</langsyntaxhighlight>
 
=={{header|Locomotive Basic}}==
 
<langsyntaxhighlight lang="locobasic">10 MODE 1:RANDOMIZE TIME
20 FOR J=1 TO 100
30 X=INT(RND*30-15)
Line 988 ⟶ 2,357:
70 PLOT 320+10*X,200+10*Y:LOCATE 1,1:PRINT J
80 NEXT
90 CALL &BB06 ' wait for key press</langsyntaxhighlight>
 
[[File:Points on a circle locomotive basic.png]]
=={{header|Lua}}==
Method 1, modified so that the 100 points must be unique..
<syntaxhighlight lang="lua">t, n = {}, 0
for y=1,31 do t[y]={} for x=1,31 do t[y][x]=" " end end
repeat
x, y = math.random(-15,15), math.random(-15,15)
rsq = x*x + y*y
if rsq>=100 and rsq<=225 and t[y+16][x+16]==" " then
t[y+16][x+16], n = "██", n+1
end
until n==100
for y=1,31 do print(table.concat(t[y])) end</syntaxhighlight>
{{out}}
<pre style="font-size:50%"> ██ ██
██ ████ ██ ██
████ ████ ██
██ ██ ████ ██ ██
██ ████ ██ ██
██ ██ ██ ██
██ ██ ██ ██ ██ ████
██ ████
██ ██
████ ██
██████
██
██ ██ ██
██ ██ ██
██ ██ ██
██
██
██ ██ ██
██
██████
██ ██ ██
████
██ ██
████ ██
████ ██████ ████ ██
██ ████ ██ ██ ██ ██ ██
████ ██ ████
██ ██
██ ████</pre>
 
=={{header|MathematicaMaple}}==
<syntaxhighlight lang="maple"> a := table():
 
i := 1:
<lang Mathematica>
while i < 100 do
sample = RandomSample[Select[Partition[Flatten[Table[{x, y}, {x, -15, 15, 1}, {y, -15, 15, 1}]], 2],10 <= Sqrt[#[[1]]^2 + #[[2]]^2] <= 15 &], 100];
ba := (rand(-15 .. 15))():
bb := (rand(-15 .. 15))():
b := evalf(sqrt(ba^2+bb^2)):
if b <= 15 and b >= 10
then a[i] := [ba, bb]:
i := i+1:
end if:
end do:
plots:-pointplot(convert(a,list));</syntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Show[{RegionPlot[10 <= Sqrt[x^2 + y^2] <= 15, {x, -16, 16}, {y, -16, 16}, Axes -> True, GridLines -> Automatic], ListPlot[sample]}]
This algorithm generates 500 pairs of random integers between +/- 15, picks out the ones that satisfy the inequality, and then takes the first 100 of those. It oversamples to reduce the chance of having less than 100 "candidates", which is not impossible, though extremely unlikely.
</lang>
<syntaxhighlight lang="mathematica">sample = Take[Cases[RandomInteger[{-15, 15}, {500, 2}], {x_, y_} /; 10 <= Sqrt[x^2 + y^2] <= 15], 100];
 
Show[{RegionPlot[10 <= Sqrt[x^2 + y^2] <= 15, {x, -16, 16}, {y, -16, 16}, Axes -> True], ListPlot[sample]}]</syntaxhighlight>
 
=={{header|MATLAB}}==
Uses the Monte-Carlo method described above.
 
<langsyntaxhighlight MATLABlang="matlab">function [xCoordinates,yCoordinates] = randomDisc(numPoints)
 
xCoordinates = [];
Line 1,034 ⟶ 2,456:
yCoordinates(numPoints+1:end) = [];
end</langsyntaxhighlight>
 
Output:
<langsyntaxhighlight MATLABlang="matlab">>> [x,y] = randomDisc(100);
>> plot(x,y,'.')</langsyntaxhighlight>
[[File:Matlab-randomDisc-output.png]]
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">randomDisc(numPoints):= block([p: []],
local(goodp, random_int),
goodp(x, y):=block([r: sqrt(x^2+y^2)],
r>=10 and r<=15
),
random_int():= block([m: 15], m - random(2*(m+1)-1)),
while length(p)<numPoints do block (
[x: random_int(), y : random_int()],
if goodp(x, y) then (
p: cons([x, y], p)
)
),
p)$
p: randomDisc(100)$
plot2d(['discrete, p], ['style, 'points]);</syntaxhighlight>
 
=={{header|Nim}}==
{{trans|Python}}
<syntaxhighlight lang="nim">import tables, math, complex, random
 
type Point = tuple[x, y: int]
 
var world = initCountTable[Point]()
var possiblePoints = newSeq[Point]()
 
for x in -15..15:
for y in -15..15:
if abs(complex(x.float, y.float)) in 10.0..15.0:
possiblePoints.add((x,y))
 
randomize()
for i in 0..100: world.inc possiblePoints.sample
 
for x in -15..15:
for y in -15..15:
let key = (x, y)
if key in world and world[key] > 0:
stdout.write ' ' & $min(9, world[key])
else:
stdout.write " "
echo ""</syntaxhighlight>
 
{{out}}
<pre> 1
1 1 1
3
1 1 1 1
1 2 1 1 1 1 1
2
1 1 1 1 1 1
1
1 1 1 1
1 2 1
1 1
1 1
1 1 1
1 1
1
1 1 1 1 1 1
1
1 1
2
1 1 2
1 1
1 1 1 1 1
1
1 2 2 1 1
1 1 1 1
1 1 1
1 1 1
1 1
1 1 2 1 1 2
1 1 1 1
1 </pre>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let p x y =
let d = sqrt(x ** 2.0 +. y ** 2.0) in
10.0 <= d && d <= 15.0
Line 1,065 ⟶ 2,563:
g.(y).[x] <- 'o'
) points;
Array.iter print_endline g</langsyntaxhighlight>
 
Line 1,095 ⟶ 2,593:
o
oo o
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">crpc()={
my(v=vector(404),t=0,i=0,vx=vy=vector(100));
for(x=1,14,for(y=1,14,
Line 1,121 ⟶ 2,618:
);
plothraw(vx,vy)
};</langsyntaxhighlight>
 
=={{header|Perl}}==
===Graphical output===
<lang perl>my @points;
<syntaxhighlight lang="perl">my @points;
while (@points < 100) {
my ($x, $y) = (int(rand(31))-15, int(rand(31)) - 15);
Line 1,145 ⟶ 2,643:
 
print "@$_ pt\n" for @points;
print "%%EOF";</langsyntaxhighlight>
 
Randomly generates points and reject ones not in the ring. Writes an EPS file.
 
===Plain-text output===
=={{header|Perl 6}}==
<syntaxhighlight lang="perl">@range = -15..16;
 
<langfor perl6>my$x (@range) = -15..16;{
for $y (@range) {
 
my @points = gather for @range X @range ->$radius = sqrt $x,**2 + $y {**2;
take push @points, [$x,$y] if 10 <= sqrt($x*radius and $x+$y*$y)radius <= 15
}
}
my @samples = @points.roll(100); # or .pick(100) to get distinct points
 
push @sample, @points[int rand @points] for 1..100;
# format and print
push @matrix, ' ' x @range for 1..@range;
my %matrix;
substr $matrix[15+$$_[1]], 15+$$_[0], 1, '*' for @sample;
for @range X @range -> $x, $y { %matrix{$y}{$x} = ' ' }
print join(' ', split '', $_) . "\n" for @matrix;</syntaxhighlight>
%matrix{$_[1]}{$_[0]} = '*' for @samples;
{{out}}
%matrix{$_}{@range}.join(' ').say for @range;</lang>
<pre> * * *
* * *
* * *
* *
* * * *
* *
* * * *
* * *
* *
* *
* * * * * * *
*
 
* * *
Turning that program completely inside-out and reducing to a single statement with a single non-parameter variable, we get this version, which also works:
*
* * * *
* *
* * *
* * *
* * * *
* * *
* * * *
* *
* *
* * * *
* * * * *
* * * * *
* *
*</pre>
 
=={{header|Phix}}==
<lang perl6>(say ~.map: { $_ // ' ' } for my @matrix) given do
<!--<syntaxhighlight lang="phix">(phixonline)-->
-> [$x, $y] { @matrix[$x][$y] = '*' } for pick 100, do
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
for ^32 X ^32 -> $x, $y {
<span style="color: #004080;">sequence</span> <span style="color: #000000;">screen</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">,</span><span style="color: #000000;">31</span><span style="color: #0000FF;">),</span><span style="color: #000000;">31</span><span style="color: #0000FF;">)</span>
[$x,$y] when 100..225 given [+] ($x,$y X- 15) X** 2;
<span style="color: #004080;">integer</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
}
<span style="color: #004080;">atom</span> <span style="color: #000000;">r</span>
</lang>
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
 
<span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #000000;">31</span><span style="color: #0000FF;">)</span>
This uses, among other things, a 0-based matrix rather than a hash, a <tt>given</tt> on the first line that allows us to print the final value of the matrix straight from its initial declaration, a <tt>for</tt> statement feeding a <tt>for</tt> statement modifier, a lambda that unpacks a single x-y argument into two variables, the functional form of pick rather than the method form, a quasi-list comprehension in the middle loop that filters each <tt>given</tt> with a <tt>when</tt>, precalculated squared limits so we don't have to take the square root, use of X- and X** to subtract and exponentiate both <tt>$x</tt> and <tt>$y</tt> in parallel.
<span style="color: #000000;">y</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #000000;">31</span><span style="color: #0000FF;">)</span>
 
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">-</span><span style="color: #000000;">16</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)+</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">y</span><span style="color: #0000FF;">-</span><span style="color: #000000;">16</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">))</span>
After the <tt>given do</tt> has loaded up <tt>@matrix</tt> with our circle, the <tt>map</tt> on the first line substitutes a space for any undefined matrix element, and the extra space between elements is supplied by the stringification of the list value, performed by the prefix <tt>~</tt> operator, the unary equivalent of concatenation in Perl&nbsp;6.
<span style="color: #008080;">if</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">10</span> <span style="color: #008080;">and</span> <span style="color: #000000;">r</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">15</span> <span style="color: #008080;">then</span>
 
<span style="color: #000000;">screen</span><span style="color: #0000FF;">[</span><span style="color: #000000;">x</span><span style="color: #0000FF;">][</span><span style="color: #000000;">y</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">'x'</span>
At this point you would be justified in concluding that we are completely mad. <tt>:-)</tt>
<span style="color: #000000;">count</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">count</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">100</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #000000;">screen</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">))</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
x xx
x x x
x x x x x
x x x x
x x xx
x x x x
xx xx x
x
x
x
x x
x
x x x
xx xxxx
x x
x x
x
x x x
x
x x
xx x x x
x x
x x x
x x x x
x x xx x
x x x xx xx
xx x
x xx
x x x
</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(let Area (make (do 31 (link (need 31 " "))))
(use (X Y)
(do 100
Line 1,192 ⟶ 2,756:
10 ) )
(set (nth Area (+ 16 X) (+ 16 Y)) "#") ) )
(mapc prinl Area) )</langsyntaxhighlight>
Output:
<pre> #
Line 1,226 ⟶ 2,790:
 
=={{header|PL/I}}==
===version 1===
<lang PL/I>
<syntaxhighlight lang="pl/i">
constrain: procedure options (main);
declare 1 point (100),
Line 1,254 ⟶ 2,819:
end;
end constrain;
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,285 ⟶ 2,850:
*
</pre>
===version 2===
<syntaxhighlight lang="pl/i">*process source attributed xref or(!);
annulus: procedure options (main);
/* version 1 does not handle (0/15) etc. this does. */
/* we show 1000 points here */
declare 1 point(10000),
2 x fixed binary,
2 y fixed binary;
declare (i, j, a, b, a2, b2, c) fixed binary(31);
j = 0;
do i = 1 to 1000;
r=rand(31); a=r-16;
r=rand(31); b=r-16;
a2=a*a;
b2=b*b;
c2=a2+b2;
if c2>= 100 & c2 <= 225 then
do; j = j + 1; x(j) = a; y(j) = b;
/* put Edit(a,b,c)(3(F(3))); */ end;
end;
/* PLOT */
declare table(-15:15, -15:15) character (2);
table = ' ';
do i = 1 to j;
table(x(i), y(i)) = '*';
end;
do i = -15 to 15;
put skip;
do j = -15 to 15;
put edit (table(i,j)) (a);
end;
end;
 
rand: Proc(n) Returns(Bin Fixed(31));
/*--------------------------------------------------------------------
* Return a random integer between 1 and n
*-------------------------------------------------------------------*/
Dcl r Bin Float(31);
Dcl (n,d) Bin Fixed(31);
r=random();
d=r*n+1;
Return(d);
End;
End annulus;</syntaxhighlight>
'''output'''
<pre> *
* * * * * * *
* * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * *
* * * * * * * *
* * * * * * *
* * * * * * * * *
* * * * *
* * * * * * * * * *
* * * * * *
* * * * * *
* * * * * * *
* * * * * * *
* * * * * * *
* * * * * *
* * * * * * * *
* * * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * *
* * * * * *
</pre>
 
=={{header|PowerShell}}==
{{works with|PowerShell|3}}
<syntaxhighlight lang="powershell">$MinR2 = 10 * 10
$MaxR2 = 15 * 15
$Points = @{}
While ( $Points.Count -lt 100 )
{
$X = Get-Random -Minimum -16 -Maximum 17
$Y = Get-Random -Minimum -16 -Maximum 17
$R2 = $X * $X + $Y * $Y
If ( $R2 -ge $MinR2 -and $R2 -le $MaxR2 -and "$X,$Y" -notin $Points.Keys )
{
$Points += @{ "$X,$Y" = 1 }
}
}
ForEach ( $Y in -16..16 ) { ( -16..16 | ForEach { ( " ", "*" )[[int]$Points["$_,$Y"]] } ) -join '' }</syntaxhighlight>
{{out}}
<pre> ***
* ** *
* *** *
* * * ** * *
* * * *
* * *
* * *** *
* *****
** * *
* * ***
** * ***
* * *
*
* * *
*
*
** *
* * **
*
*
* **
* * * *
* * ** *
* ** ** *
* * * * *
*
**
** * </pre>
 
=={{header|Prolog}}==
Works with SWI-Prolog
<langsyntaxhighlight Prologlang="prolog">:- use_module(library(clpfd)).
 
circle :-
Line 1,324 ⟶ 3,016:
send(D, display, C))),
send(D, open).
</syntaxhighlight>
</lang>
[[FILE:Prolog-Circle.jpg‎ ]]
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">CreateImage(0,31,31)
StartDrawing(ImageOutput(0))
For i=1 To 100
Line 1,344 ⟶ 3,036:
OpenWindow(0,#PB_Ignore,#PB_Ignore,ImageWidth(0),ImageHeight(0),Title$,Flags)
ImageGadget(0,0,0,ImageWidth(0),ImageHeight(0),ImageID(0))
Repeat: Until WaitWindowEvent()=#PB_Event_CloseWindow</langsyntaxhighlight>
[[File:PureBasic_Circle_plot.png‎|155px]]
 
=={{header|Python}}==
Note that the diagram shows the number of points at any given position (up to a maximum of 9 points).
<langsyntaxhighlight lang="python">>>> from collections import defaultdict
>>> from random import choice
>>> world = defaultdict(int)
Line 1,392 ⟶ 3,084:
1 1 1
2 2 1
1 </langsyntaxhighlight>
If the number of samples is increased to 1100:
<langsyntaxhighlight lang="python">>>> for i in range(1000): world[choice(possiblepoints)] += 1
 
>>> for x in range(-15,16):
Line 1,431 ⟶ 3,123:
2131181233 424
47414232164
4 </langsyntaxhighlight>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="Quackery"> [ 0 31 of ] is grid ( --> [ )
 
[ dup * ] is squared ( n --> n )
 
[ squared swap squared +
10 squared 15 squared 1+
within ] is inrange ( n n --> b )
 
[ 32 random 16 -
32 random 16 -
2dup inrange not while
2drop again ] is randxy ( --> n n )
 
[ 15 + swap 15 +
dip [ 2dup peek ]
bit | unrot poke ] is plot ( [ n n --> [ )
 
[ witheach
[ 31 times
[ dup
i^ bit & iff
[ $ "[]" ]
else
[ $ " " ]
echo$ ]
drop
cr ] ] is draw ( [ --> )
 
[ grid
swap times
[ randxy plot ]
draw ] is circle ( n --> )
 
100 circle</syntaxhighlight>
 
{{out}}
 
<pre>
[] [] []
[] [] []
[] [][] []
[] [] [] [][]
[] [] [][][][] [] []
[]
[] []
[] [][]
[]
[][] []
[] [] [] []
[] []
[]
[] []
[][] []
[][] []
[] [][][]
[] []
[] [] [] []
[]
[] []
[] []
[][][] []
[] [] [][] [] []
[] [][][] [] [] []
[] [] []
[] [][]
[] []
</pre>
 
Code check as per task discussion, as a dialogue in the Quackery shell.
 
<pre>/O> 10000 circle
...
[]
[][][][][][][][][][][]
[][][][][][][][][][][][][][][]
[][][][][][][][][][][][][][][][][][][]
[][][][][][][][][][][][][][][][][][][][][]
[][][][][][][][][][][][][][][][][][][][][][][]
[][][][][][][][] [][][][][][][][]
[][][][][][][] [][][][][][][]
[][][][][][] [][][][][][]
[][][][][][] [][][][][][]
[][][][][][] [][][][][][]
[][][][][] [][][][][]
[][][][][] [][][][][]
[][][][][] [][][][][]
[][][][][] [][][][][]
[][][][][][] [][][][][][]
[][][][][] [][][][][]
[][][][][] [][][][][]
[][][][][] [][][][][]
[][][][][] [][][][][]
[][][][][][] [][][][][][]
[][][][][][] [][][][][][]
[][][][][][] [][][][][][]
[][][][][][][] [][][][][][][]
[][][][][][][][] [][][][][][][][]
[][][][][][][][][][][][][][][][][][][][][][][]
[][][][][][][][][][][][][][][][][][][][][]
[][][][][][][][][][][][][][][][][][][]
[][][][][][][][][][][][][][][]
[][][][][][][][][][][]
[]
 
Stack empty.
</pre>
 
=={{header|R}}==
<syntaxhighlight lang="r">
<lang R>
RMin <- 10
RMax <- 15
Line 1,453 ⟶ 3,256:
plot(X[Valid][1:NPts],Y[Valid][1:NPts], pch=19, cex=0.25, col="blue",
xlab="x",ylab="y",main="Fuzzy circle", xlim=c(-RMax,RMax), ylim=c(-RMax,RMax) )
</syntaxhighlight>
</lang>
 
Example of solution
 
[[File:FuzzyCircle.jpg]]
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">#lang racket
 
(require plot plot/utils)
 
(plot (points (for*/lists (result)
([_ (in-naturals)]
#:break (= 100 (length result))
[xy (in-value (v- (vector (random 31) (random 31))
#(15 15)))]
#:when (<= 10 (vmag xy) 15))
xy)))</syntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|rakudo|2015.09}}
<syntaxhighlight lang="raku" line>my @range = -15..16;
 
my @points = gather for @range X @range -> ($x, $y) {
take [$x,$y] if 10 <= sqrt($x*$x+$y*$y) <= 15
}
my @samples = @points.roll(100); # or .pick(100) to get distinct points
 
# format and print
my %matrix;
for @range X @range -> ($x, $y) { %matrix{$y}{$x} = ' ' }
%matrix{.[1]}{.[0]} = '*' for @samples;
%matrix{$_}{@range}.join(' ').say for @range;</syntaxhighlight>
{{out}}
<pre> *
* *
* * * * *
* * * *
* * * * *
* *
* * *
* * * *
*
* * * *
* * *
* * * *
*
* *
* * *
* * * *
* * *
*
* *
* *
* * *
* * *
* *
* * *
* * * * * * *
* * * * * *
* * * *
* *
* * *</pre>
Turning that program completely inside-out and reducing to a single statement with a single non-parameter variable, we get another version that also works.
 
This uses, among other things, a 0-based matrix rather than a hash, a <tt>given</tt> on the first line that allows us to print the final value of the matrix straight from its initial declaration, a <tt>for</tt> statement feeding a <tt>for</tt> statement modifier, a lambda that unpacks a single x-y argument into two variables, the functional form of pick rather than the method form, a quasi-list comprehension in the middle loop that filters each <tt>given</tt> with a <tt>when</tt>, precalculated squared limits so we don't have to take the square root, use of X- and X** to subtract and exponentiate both <tt>$x</tt> and <tt>$y</tt> in parallel.
 
After the <tt>given do</tt> has loaded up <tt>@matrix</tt> with our circle, the <tt>map</tt> on the first line substitutes a space for any undefined matrix element, and the extra space between elements is supplied by the stringification of the list value, performed by the prefix <tt>~</tt> operator, the unary equivalent of concatenation in Raku.
 
At this point you would be justified in concluding that we are completely mad. <tt>:-)</tt>
 
<syntaxhighlight lang="raku" line>(say ~.map: { $_ // ' ' } for my @matrix) given do
-> [$x, $y] { @matrix[$x][$y] = '*' } for pick 100, do
for ^32 X ^32 -> ($x, $y) {
[$x,$y] when 100..225 given [+] ($x,$y X- 15) X** 2;
}
</syntaxhighlight>
{{out}}
<pre> * * *
* * *
* * * * * *
* * * * * *
* * * * * *
* * *
* * * * *
* * * *
* *
* *
*
* * *
 
* *
* * * * * *
* *
 
* * * *
* * *
* * * *
* *
* *
* * *
* * * * * *
* * * *
* * * * * *
* * * *
* * * * *
* * *</pre>
 
=={{header|REXX}}==
===version 1===
This REXX version uses aspect adjustment for the plot of the (sparse) annulus.
<syntaxhighlight lang="rexx">/*REXX program generates 100 random points in an annulus: 10 ≤ √(x²≤y²) ≤ 15 */
parse arg pts LO HI . /*obtain optional args from the C.L. */
if pts=='' then pts= 100 /*Not specified? Then use the default.*/
if LO=='' then LO= 10; LO2= LO**2 /*define a shortcut for squaring LO. */
if HI=='' then HI= 15; HI2= HI**2 /* " " " " " HI. */
$=
do x=-HI; xx= x*x /*generate all possible annulus points.*/
if x>0 & xx>HI2 then leave /*end of annulus points generation ? */
do y=-HI; s= xx + y*y
if (y<0 & s>HI2) | s<LO2 then iterate
if y>0 & s>HI2 then leave
$= $ x','y /*add a point─set to the $ list. */
end /*y*/
end /*x*/
#= words($); @.= /*def: plotchr; #pts; lines*/
do pts; parse value word($, random(1,#)) with x ',' y /*get rand point in annulus*/
@.y= overlay('☼', @.y, x+x + HI+HI + 1) /*put a plot char on a line*/
end /*pts*/ /* [↑] maintain aspect ratio on X axis*/
/*stick a fork in it, we're all done. */
do y=-HI to HI; say @.y; end /*display the annulus to the terminal. */</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
 
☼ ☼
☼ ☼ ☼
☼ ☼ ☼ ☼ ☼
☼ ☼ ☼
☼ ☼ ☼ ☼
☼ ☼ ☼
☼ ☼
☼ ☼ ☼
☼ ☼ ☼
☼ ☼ ☼ ☼
☼ ☼ ☼
☼ ☼
☼ ☼
 
☼ ☼ ☼
☼ ☼ ☼ ☼
☼ ☼
☼ ☼ ☼
☼ ☼ ☼ ☼
☼ ☼ ☼ ☼ ☼
☼ ☼ ☼ ☼
☼ ☼ ☼
☼ ☼ ☼
☼ ☼ ☼ ☼ ☼
☼ ☼ ☼ ☼
☼ ☼ ☼ ☼ ☼
☼ ☼
</pre>
 
===version 2===
{{trans|REXX version 1}}
<syntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* show 100 random points of an annulus with radius 10 to 15
* 18.06.2014 Walter Pachl 'derived/simplified' from REXX version 1
*--------------------------------------------------------------------*/
Parse Arg points low high scale . /* allow parms from command line.*/
If points=='' Then points=100 /* number of points */
If low=='' Then low=10 /* inner radius */
If high=='' Then high=15 /* outer radius */
If scale=='' Then scale=2 /* horizontal scaling */
low2=low**2
high2=high**2
/* first compute all possible points */
point.=0
Do x=-high To high
x2=x*x
Do y=-high To high
y2=y*y
s=x2+y2
If s>=low2 &s<=high2 Then Do
z=point.0+1
point.z=x y
point.0=z
End
End
End
plotchar='O'
line.=''
np=point.0 /* available points */
Do j=1 To points /* pick the needed points */
r=random(1,np)
Parse Var point.r x y /* coordinates */
line.y=overlay(plotchar,line.y,scale*(x+high)+1) /* put into line*/
point.r=point.np /* replace taken point by last*/
np=np-1 /* reduce available points */
If np=0 Then Leave /* all possible points taken */
End
/* now draw the picture */
Do y=-high To high
Say line.y
End</syntaxhighlight>
'''output''' using default parameters
<pre>
O
O O O
O O O O O
O O O O O O O O O
O O O O O O O O
O O O O O O O
O O
O
O O
O O
O
O O O O O
O O O
O
O O O
O
O
O
O O
O O O O
O O O
O O O O O
O O O O O
O O
O O O O O
O O
O O O O O O O O O
O O O O O
O O
 
</pre>
'''output''' using rexx fcaa 100 3 4 2
<pre> O
O O O O O
O O
O O
O O O O
O O
O O
O O O O O
O </pre>
 
===version 3===
<syntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* 19.06.2014 Walter Pachl alternate algorithm
* the idea: yl is a list of y coordinates which may have unused points
* one of the y's is picked at random
* Then we look for unused x coordinates in this line
* we pick one at random or drop the y from yl if none is found
* When yl becomes empty, all points are used and we stop
*--------------------------------------------------------------------*/
Parse Arg n r rr scale
If r='' Then r=10
If rr='' Then rr=15
If n='' Then n=100
If scale='' Then scale=2
r2=r*r
rr2=rr*rr
ymin=0
ymax=rr*2
ol=''
pp.=0
used.=0
yl='' /* list of available y values */
Do y=-rr To rr
yl=yl y
End
Do Until pp.0=n /*look for the required points*/
If yl='' Then Do /* no more points available */
Say 'all points filled'
Leave
End
yi=random(1,words(yl)) /* pick a y */
y=word(yl,yi)
y2=y*y
p.=0
Do x=0 To rr /* Loop through possible x's */
x2=x*x
xy2=x2+y2
If xy2>=r2&xy2<=rr2 Then Do /* within the annulus */
Call take x y
Call take (-x) y
End
End
If p.0>0 Then Do /* some x's found (or just 1) */
xi=random(1,p.0) /* pick an x */
z=pp.0+1
pp.z=p.xi
pp.0=z
Parse Var pp.z xa ya
used.xa.ya=1 /* remember it's taken */
End
Else Do /* no x for this y */
yi=wordpos(y,yl) /* remove y from yl */
Select
When yi=1 Then yl=subword(yl,yi+1)
When yi=words(yl) Then yl=subword(yl,1,yi-1)
Otherwise yl=subword(yl,1,yi-1) subword(yl,yi+1)
End
End
End
line.='' /* empty the raster */
Do i=1 To pp.0 /* place the points */
Parse Var pp.i x y
line.y=overlay('+',line.y,scale*(rr+x)+1)
End
Do y=-rr To rr /* show the result */
Say line.y
End
say pp.0 'points filled'
Exit
Return
 
take: Procedure Expose p. used. /* add x to p. if its not used*/
Parse Arg x y
If used.x.y=0 Then Do
z=p.0+1
p.z=x y
p.0=z
End
Return</syntaxhighlight>
'''output''' using rexx fcaa 100 3 5 2
<pre>all points filled
+
+ + + + + + +
+ + + + + + + + +
+ + + +
+ + + +
+ + + + + +
+ + + +
+ + + +
+ + + + + + + + +
+ + + + + + +
+
56 points filled</pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
load "guilib.ring"
 
new qapp
{
win1 = new qwidget() {
setwindowtitle("drawing using qpainter")
setgeometry(100,100,500,500)
label1 = new qlabel(win1) {
setgeometry(10,10,400,400)
settext("")
}
new qpushbutton(win1) {
setgeometry(200,400,100,30)
settext("draw")
setclickevent("draw()")
}
show()
}
exec()
}
 
func draw
p1 = new qpicture()
color = new qcolor() {
setrgb(0,0,255,255)
}
pen = new qpen() {
setcolor(color)
setwidth(1)
}
new qpainter() {
begin(p1)
setpen(pen)
 
for i = 1 to 1000
x = random(31)-16
y = random(31)-16
r = sqrt (pow(x,2) + pow(y,2))
if r >= 10 if r <= 15 drawpoint(x*2, y*2) ok ok
next
 
endpaint()
}
label1 { setpicture(p1) show() }
</syntaxhighlight>
 
Output:
 
[[File:CalmoSoftDrawCircle.jpg]]
 
=={{header|RPL}}==
{{works with|HP|48G}}
« ERASE -15 15 DUP2 XRNG YRNG <span style="color:grey">@ set graphics boundaries</span>
DEG -19 SF 0 <span style="color:grey">@ set degrees mode, polar vector mode, count = 0</span>
'''DO''' RAND 5 * 10 + RAND 360 * →V2 <span style="color:grey">@ z = rand(10..15).exp(i.rand(360))</span>
C→R IP SWAP IP R→C <span style="color:grey">@ make z a complex with integer coordinates</span>
'''IF''' DUP ABS DUP 10 ≥ SWAP 15 ≤ AND <span style="color:grey">@ if 10 ≤ | z | ≤ 15</span>
'''THEN''' PIXON 1 + <span style="color:grey">@ then set pixel and increment count</span>
'''ELSE''' DROP '''END'''
'''UNTIL''' DUP 100 ≥ '''END'''
DROP { } PVIEW
-19 CF
» '<span style="color:blue">TASK</span>' STO
[[File:Constrained.png|alt=Screenshot of a HP-48G emulator, displaying constrained random points on a circle|HP-48G emulator screenshot]]
 
The circle is actually an ellipse because RPL display screens are not squared.
 
=={{header|Ruby}}==
Create the image with [[Raster graphics operations/Ruby]]
{{incorrect|Ruby|<x,y> points do not have equal probability: points at low radius capture more probability than ones at higher radius; also, points near the "edges" of the dount have less probability}}
<langsyntaxhighlight Rubylang="ruby">points = (1...100).map {do
# choose a random radius and angle
angle = rand * 2.0 * Math::PI
rad = rand * 5.0 + 10.0
# convert back from polar to cartesian coordinates
[rad * Math::cos(angle), rad * Math::sin(angle)].map(&:round)
end
}
 
(-15..15).each do |row|
puts( (-15..15).map { |col| points.include?([row, col]) ? "X" : " " }.join)
end</lang>
 
load 'raster_graphics.rb'
 
pixmap = Pixmap.new(321,321)
pixmap.draw_circle(Pixel.new(160,160),90,RGBColour::BLACK)
pixmap.draw_circle(Pixel.new(160,160),160,RGBColour::BLACK)
points.each {|(x,y)| pixmap[10*(x+16),10*(y+16)] = RGBColour::BLACK}
pngfile = __FILE__
pngfile[/\.rb/] = ".png"
pixmap.save_as_png(pngfile)</syntaxhighlight>
 
{{out}}
[[File:constrainedrandompointsonacircle.png|thumg|right|Sample output from Ruby program]]
<pre> X X
X XX
X XXX
XX X X X X X
XXXXX
XX XX
X X X
X X
X X
X X XXX
X
XX X X
X X
X X
XXX X
XX X
XXX X X
 
XX X X X
XX X X
X X
X
XX X X
X X X
X X X
X
X X X
X X X
X X</pre>
 
===algorithm 2:===
<syntaxhighlight lang="ruby">r2 = 10*10..15*15
range = (-15..15).to_a
points = range.product(range).select {|i,j| r2.cover?(i*i + j*j)}
 
puts "Precalculate: #{points.size}"
pt = Hash.new(" ")
points.sample(100).each{|ij| pt[ij] = " o"}
puts range.map{|i| range.map{|j| pt[[i,j]]}.join}</syntaxhighlight>
 
{{out}}
<pre>
Precalculate: 404
o o o
o o o o
o o o o o
o o o o o o
o o o o o
o o
o o
o o o
o o o
o o o o
o o
o
o
o o
o o o
o
o o o o o
o o o
o o o o
o
o o o
o o o
o o o o o o
o o o o o o o o o
o o o o o
o o o o o o
o o o o o
o o
o
</pre>
 
=={{header|Run BASIC}}==
<syntaxhighlight lang="runbasic">w = 320
h = 320
dim canvas(w,h)
for pts = 1 to 1000
x = (rnd(1) * 31) - 15
y = (rnd(1) * 31) - 15
r = x * x + y * y
if (r > 100) and (r < 225) then
x = int(x * 10 + w/2)
y = int(y * 10 + h/2)
canvas(x,y) = 1
end if
next pts
 
' -----------------------------
' display the graphic
' -----------------------------
graphic #g, w,h
for x = 1 to w
for y = 1 to h
if canvas(x,y) = 1 then #g "color green ; set "; x; " "; y else #g "color blue ; set "; x; " "; y
next y
next x
render #g
#g "flush"</syntaxhighlight>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">extern crate rand;
 
use rand::Rng;
 
const POINTS_N: usize = 100;
 
fn generate_point<R: Rng>(rng: &mut R) -> (i32, i32) {
loop {
let x = rng.gen_range(-15, 16); // exclusive
let y = rng.gen_range(-15, 16);
 
let r2 = x * x + y * y;
if r2 >= 100 && r2 <= 225 {
return (x, y);
}
}
}
 
fn filtering_method<R: Rng>(rng: &mut R) {
let mut rows = [[" "; 62]; 31];
 
// Generate points
for _ in 0..POINTS_N {
let (x, y) = generate_point(rng);
rows[(y + 15) as usize][(x + 15) as usize * 2] = "*";
}
 
// draw the points
for row in &rows {
println!("{}", row.concat());
}
}
 
fn precalculating_method<R: Rng>(rng: &mut R) {
// Generate all possible points
let mut possible_points = Vec::with_capacity(404);
for y in -15..=15 {
for x in -15..=15 {
let r2 = x * x + y * y;
if r2 >= 100 && r2 <= 225 {
possible_points.push((x, y));
}
}
}
 
// A truncated Fisher-Yates shuffle
let len = possible_points.len();
for i in (len - POINTS_N..len).rev() {
let j = rng.gen_range(0, i + 1);
possible_points.swap(i, j);
}
 
// turn the selected points into "pixels"
let mut rows = [[" "; 62]; 31];
for &(x, y) in &possible_points[len - POINTS_N..] {
rows[(y + 15) as usize][(x + 15) as usize * 2] = "*";
}
 
// draw the "pixels"
for row in &rows {
println!("{}", row.concat());
}
}
 
fn main() {
let mut rng = rand::weak_rng();
 
filtering_method(&mut rng);
 
precalculating_method(&mut rng);
}</syntaxhighlight>
 
=={{header|Scala}}==
{{libheader|Scala}}<syntaxhighlight lang="scala">import java.awt.{ Color, geom,Graphics2D ,Rectangle}
import scala.math.hypot
import scala.swing.{MainFrame,Panel,SimpleSwingApplication}
import scala.swing.Swing.pair2Dimension
import scala.util.Random
 
object CirculairConstrainedRandomPoints extends SimpleSwingApplication {
//min/max of display-x resp. y
val dx0, dy0 = 30; val dxm, dym = 430
val prefSizeX, prefSizeY = 480
 
val palet = Map("b" -> Color.blue, "g" -> Color.green, "r" -> Color.red, "s" -> Color.black)
val cs = List((0, 0, 10, "b"), (0, 0, 15, "g")) //circle position and color
val xmax, ymax = 20; val xmin, ymin = -xmax
 
class Coord(x: Double, y: Double) {
def dx = (((dxm - dx0) / 2 + x.toDouble / xmax * (dxm - dx0) / 2) + dx0).toInt
def dy = (((dym - dy0) / 2 - y.toDouble / ymax * (dym - dy0) / 2) + dy0).toInt
}
 
object Coord {
def apply(x: Double, y: Double) = new Coord(x, y)
}
 
//points:
val points =
new Iterator[Int] { val r = new Random;def next = r.nextInt(31) - 15; def hasNext = true }.toStream.
zip(new Iterator[Int] { val r = new Random; def next = r.nextInt(31) - 15; def hasNext = true }.toStream).
map { case (x, y) => (x, y, hypot(x, y)) }.filter { case (x, y, r) => r >= 10 && r <= 15 }.take(100).toSeq.
map { case (x, y, r) => new Rectangle(Coord(x, y).dx - 2, Coord(x, y).dy - 2, 4, 4) }
 
private def ui = new Panel {
background = Color.white
preferredSize = (prefSizeX, prefSizeY)
 
class Circle(center: Coord, r: Double, val color: Color) {
val dr = (Coord(r, 0).dx - pcentre.dx) * 2
val dx = center.dx - dr / 2
val dy = center.dy - dr / 2
}
 
object Circle {
def apply(x: Double, y: Double, r: Double, color: Color) =
new Circle(Coord(x, y), r, color)
}
 
val pcentre = Coord(0, 0)
val pxmax = Coord(xmax, 0); val pxmin = Coord(xmin, 0)
val pymax = Coord(0, ymax); val pymin = Coord(0, ymin)
 
//axes:
val a_path = new geom.GeneralPath
a_path.moveTo(pxmin.dx, pxmin.dy); a_path.lineTo(pxmax.dx, pxmax.dy) //x-axis
a_path.moveTo(pymin.dx, pymin.dy); a_path.lineTo(pymax.dx, pymax.dy) //y-axis
 
//labeling:
val labels = List(-20, -15, -10, -5, 5, 10, 15, 20)
labels.foreach { x => { val p = Coord(x, 0); a_path.moveTo(p.dx, p.dy - 3); a_path.lineTo(p.dx, p.dy + 3) } }
labels.foreach { y => { val p = Coord(0, y); a_path.moveTo(p.dx - 3, p.dy); a_path.lineTo(p.dx + 3, p.dy) } }
val xlabels = labels.map(x => { val p = Coord(x, 0); Triple(x.toString, p.dx - 3, p.dy + 20) })
val ylabels = labels.map(y => { val p = Coord(0, y); Triple(y.toString, p.dx - 20, p.dy + 5) })
 
//circles:
val circles = cs.map { case (x, y, r, c) => Circle(x, y, r, palet(c)) }
 
override def paintComponent(g: Graphics2D) = {
super.paintComponent(g)
circles.foreach { c => { g.setColor(c.color); g.drawOval(c.dx, c.dy, c.dr, c.dr) } }
g.setColor(palet("r")); points.foreach(g.draw(_))
g.setColor(palet("s")); g.draw(a_path)
xlabels.foreach { case (text, px, py) => g.drawString(text, px, py) }
ylabels.foreach { case (text, px, py) => g.drawString(text, px, py) }
}
} // def ui
 
def top = new MainFrame {
title = "Rosetta Code >>> Task: Constrained random points on a circle | Language: Scala"
contents = ui
}
}</syntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Perl}}
Generates an EPS file.
<syntaxhighlight lang="ruby">var points = []
while (points.len < 100) {
var (x, y) = 2.of{ 30.irand - 15 }...
var r2 = (x**2 + y**2)
if ((r2 >= 100) && (r2 <= 225)) {
points.append([x, y])
}
}
 
print <<'HEAD'
%!PS-Adobe-3.0 EPSF-3.0
%%BoundingBox 0 0 400 400
200 200 translate 10 10 scale
0 setlinewidth
1 0 0 setrgbcolor
0 0 10 0 360 arc stroke
0 0 15 360 0 arcn stroke
0 setgray
/pt { .1 0 360 arc fill } def
HEAD
 
points.each { |pt| say "#{pt.join(' ')} pt" }
print '%%EOF'</syntaxhighlight>
 
=={{header|Standard ML}}==
Works with PolyML. Plotting function from 'Draw a pixel' task. Uniform random generator: copy from [[Random_numbers#Standard_ML]]. x,y plotted scaled x 10 px
<syntaxhighlight lang="standard ml">open XWindows ;
open Motif ;
 
val plotWindow = fn coords => (* input list of int*int within 'dim' *)
let
val dim = {tw=325,th=325} ;
val shell = XtAppInitialise "" "demo" "top" [] [ XmNwidth (#tw dim), XmNheight (#th dim) ] ; (* single call only *)
val main = XmCreateMainWindow shell "main" [ XmNmappedWhenManaged true ] ;
val canvas = XmCreateDrawingArea main "drawarea" [ XmNwidth (#tw dim), XmNheight (#th dim) ] ;
val usegc = DefaultGC (XtDisplay canvas) ;
val put = fn (w,s,t)=> (
XSetForeground usegc 0xfffffff ;
XFillRectangle (XtWindow canvas) usegc (Area{x=0,y=0,w = #tw dim, h= #th dim}) ;
XSetForeground usegc 0 ;
XDrawPoints (XtWindow canvas) usegc ( List.map (fn (x,y)=>XPoint {x=x,y=y}) coords ) CoordModeOrigin ;
t )
in
(
XtSetCallbacks canvas [ (XmNexposeCallback , put) ] XmNarmCallback ;
XtManageChild canvas ;
XtManageChild main ;
XtRealizeWidget shell
)
end;
 
val urandomlist = fn seed => fn n =>
(* put code from (www.rosettacode.org) wiki/Random_numbers#Standard_ML 'urandomlist' here
input : seed and number of drawings *)
end;
 
val normalizedPts = fn () => (* select ([0,1]*[0,1]) points in normalized bandwidth *)
let
val realseeds = ( 972.1 , 10009.3 ) ;
val usum = fn (u,v) => u*(u-1.0) + v*(v-1.0) ;
val lim = ( ~350.0/900.0, ~225.0/900.0 ) ; (* limits to usum *)
val select = fn i => usum i <= #2 lim andalso usum i >= #1 lim ; (* select according to inequalities *)
val uv = ListPair.zip ( urandomlist (#1 realseeds) 2500 , urandomlist (#2 realseeds) 2500 ) (* take 2500 couples *)
in
List.take ( List.filter select uv , 1000 )
end ;</syntaxhighlight>
call
> val scaledXY = map (fn (x,y)=>
( Real.toInt IEEEReal.TO_NEAREST (10.0+300.0*x), Real.toInt IEEEReal.TO_NEAREST (10.0+300.0*y) )) (normalizedPts ()) ;
> plotWindow scaledXY ;
 
=={{header|Swift}}==
 
{{trans|Rust}}
 
<syntaxhighlight lang="swift">let nPoints = 100
 
func generatePoint() -> (Int, Int) {
while true {
let x = Int.random(in: -15...16)
let y = Int.random(in: -15...16)
let r2 = x * x + y * y
 
if r2 >= 100 && r2 <= 225 {
return (x, y)
}
}
}
 
func filteringMethod() {
var rows = [[String]](repeating: Array(repeating: " ", count: 62), count: 31)
 
for _ in 0..<nPoints {
let (x, y) = generatePoint()
 
rows[y + 15][x + 15 * 2] = "*"
}
 
for row in rows {
print(row.joined())
}
}
 
func precalculatingMethod() {
var possiblePoints = [(Int, Int)]()
 
for y in -15...15 {
for x in -15...15 {
let r2 = x * x + y * y
 
if r2 >= 100 && r2 <= 225 {
possiblePoints.append((x, y))
}
}
}
 
possiblePoints.shuffle()
 
var rows = [[String]](repeating: Array(repeating: " ", count: 62), count: 31)
 
for (x, y) in possiblePoints {
rows[y + 15][x + 15 * 2] = "*"
}
 
for row in rows {
print(row.joined())
}
}
 
print("Filtering method:")
filteringMethod()
 
print("Precalculating method:")
precalculatingMethod()</syntaxhighlight>
 
{{out}}
 
<pre>Filtering method:
*
** *
** ** *
* ** * *
** * *
* ** **
* *
*
* ** *
* *
* * * ***
*
* * *
**
* *
* *
*
* * *
*
* **
*
* * *
* *
*
** **
* **
*** * *
* ** * *
* *
* * *
*
Precalculating method:
*
***********
***************
*******************
*********************
***********************
******** ********
******* *******
****** ******
****** ******
****** ******
***** *****
***** *****
***** *****
***** *****
****** ******
***** *****
***** *****
***** *****
***** *****
****** ******
****** ******
****** ******
******* *******
******** ********
***********************
*********************
*******************
***************
***********
*
</pre>
 
=={{header|SystemVerilog}}==
<langsyntaxhighlight SystemVeriloglang="systemverilog">program main;
 
bit [39:0] bitmap [40];
Line 1,499 ⟶ 4,190:
end
 
endprogram</langsyntaxhighlight>
 
Piping the output through sed to improve the contrast of the output:
Line 1,541 ⟶ 4,232:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
# Generate random point at specified distance from the centre
Line 1,574 ⟶ 4,265:
}
puts ""
}</langsyntaxhighlight>
Example output:
<pre>
Line 1,609 ⟶ 4,300:
1
</pre>
 
=={{header|Wren}}==
{{libheader|DOME}}
<syntaxhighlight lang="wren">import "graphics" for Canvas, Color
import "dome" for Window
import "random" for Random
 
class Game {
static init() {
Window.title = "Constrained random points on a circle"
var width = 800
var height = 800
Window.resize(width, height)
Canvas.resize(width, height)
var rand = Random.new()
var count = 0
var max = 100 // set to 1000 to produce a much more pronounced annulus
while (true) {
var x = rand.int(-15, 16)
var y = rand.int(-15, 16)
var dist = (x*x + y*y).sqrt
if (10 <= dist && dist <= 15) {
// translate coordinates to fit in the window
Canvas.circlefill((x + 16) * 25, (y + 16) * 25, 2, Color.white)
count = count + 1
if (count == max) break
}
}
}
 
static update() {}
 
static draw(alpha) {}
}</syntaxhighlight>
 
=={{header|XPL0}}==
[[File:DonutXPL0.gif|right]]
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
int X, Y, C, R2;
[SetVid($13); \set 320x200x8 graphics mode
C:= 0; \initialize point counter
repeat X:= Ran(31)-15; \range -15..+15
Y:= Ran(31)-15;
R2:= X*X + Y*Y;
if R2>=10*10 & R2<=15*15 then
[Point(X+160, Y+100, $F); C:= C+1];
until C >= 100;
C:= ChIn(1); \wait for keystroke
SetVid(3); \restore normal text mode
]</syntaxhighlight>
 
=={{header|zkl}}==
<syntaxhighlight lang="zkl">xy:=(0).walker(*).tweak(fcn{ // generate infinite random pairs (lazy)
x:=(-15).random(16); y:=(-15).random(16);
if(not (100<=(x*x + y*y)<=225)) Void.Skip else T(x,y)
});
 
const N=31; // [-15..15] includes 0
array:=(" ,"*N*N).split(",").copy(); // bunch of spaces (list)
 
xy.walk(100).apply2(fcn([(x,y)],array){array[x+15 + N*(y+15)]="*"},array);
foreach n in ([0..30]){ array[n*N,30].concat().println(); }</syntaxhighlight>
{{out}}
<pre>
* * *
** ***
* * * ** *
* **
* * * *
* * *
* * ***
*
* *
* * * *
* *
* *
*
* *
**** **
*
*
* *
* *
** * *
* *
* * *
* *
* *
** * **
* * ***
* * *
* *
*
</pre>
 
=={{header|ZX Spectrum Basic}}==
{{trans|BBC_BASIC}}
<syntaxhighlight lang="zxbasic">10 FOR i=1 TO 1000
20 LET x=RND*31-16
30 LET y=RND*31-16
40 LET r=SQR (x*x+y*y)
50 IF (r>=10) AND (r<=15) THEN PLOT 127+x*2,88+y*2
60 NEXT i</syntaxhighlight>
2,078

edits