24
\$\begingroup\$

The goal of this code golf is to draw a regular polygon (one with equal side lengths) given the number of sides and radius (distance from center to vertex).

  • The number of sides and the radius can be entered via a file, STDIN, or just a plain old variable. Use whatever is shorter in your language.
  • -25% of total characters/bytes if the image is actually drawn instead of ASCII art.
\$\endgroup\$
10
  • 3
    \$\begingroup\$ What is the radius of a polygon? The radius of its incircle? Its outcircle? \$\endgroup\$ Commented Apr 16, 2014 at 7:25
  • \$\begingroup\$ There. I fixed it. Sorry about that :P. \$\endgroup\$
    – Taconut
    Commented Apr 16, 2014 at 13:49
  • 2
    \$\begingroup\$ @PeterTaylor The radius of a regular polygon is the distance to any vertex (radius outcircle or circumradius). The incircle's radius(or distance to sides) is called the apothem. This shouldn't be "unclear what you're asking", since it has an easily found definition (#1 result for "radius of a polygon" on google). \$\endgroup\$
    – Geobits
    Commented Apr 16, 2014 at 13:57
  • \$\begingroup\$ @Geobits I agree, but I still edited it anyway. \$\endgroup\$
    – Taconut
    Commented Apr 16, 2014 at 14:03
  • \$\begingroup\$ @PeterTaylor I'll tag it as both then :I \$\endgroup\$
    – Taconut
    Commented Apr 16, 2014 at 14:03

29 Answers 29

20
\$\begingroup\$

LOGO 37 - 25% = 27.75 (with variables)

REPEAT:S[FD:R*2*sin(180/:S)RT 360/:S]

LOGO 49 - 25% = 36.75 (as a function)

TO P:R:S REPEAT:S[FD:R*2*sin(180/:S)RT 360/:S]END

Triangle

Called with variables

Make "R 100
Make "S 3
REPEAT:S[FD:R*2*sin(180/:S)RT 360/:S]

Used as a function P 100 3

enter image description here

Square

Called with variables

Make "R 100
Make "S 4
REPEAT:S[FD:R*2*sin(180/:S)RT 360/:S]

Used as a function P 100 4

enter image description here

Pentagon

Called with variables

Make "R 100
Make "S 5
REPEAT:S[FD:R*2*sin(180/:S)RT 360/:S]

Used as a function P 100 5

enter image description here

Decagon

Called with variables

Make "R 100
Make "S 10
REPEAT:S[FD:R*2*sin(180/:S)RT 360/:S]

Used as a function P 100 10

enter image description here

Circle

Called with variables

Make "R 100
Make "S 360
REPEAT:S[FD:R*2*sin(180/:S)RT 360/:S]

Used as a function P 100 360

enter image description here

\$\endgroup\$
3
  • 2
    \$\begingroup\$ Can you post a screen shot? \$\endgroup\$
    – Gabe
    Commented Apr 16, 2014 at 12:22
  • \$\begingroup\$ To my eye the polygons have the same side, not radius. \$\endgroup\$ Commented Apr 16, 2014 at 16:06
  • \$\begingroup\$ @RossMillikan: The Images were not to scale. I just updated the images \$\endgroup\$
    – Abhijit
    Commented Apr 16, 2014 at 16:10
17
\$\begingroup\$

Mathematica, 40 - 25% = 30

ListPolarPlot[r&~Array~n]/.PointPolygon

enter image description here

\$\endgroup\$
6
  • \$\begingroup\$ Great. That beat what I tried with Graphics. \$\endgroup\$
    – DavidC
    Commented Apr 17, 2014 at 0:04
  • 2
    \$\begingroup\$ No fair! Too easy! \$\endgroup\$
    – Robin
    Commented Apr 17, 2014 at 0:38
  • \$\begingroup\$ Nicely done, this would never have occurred to me. \$\endgroup\$ Commented Apr 17, 2014 at 15:11
  • \$\begingroup\$ Is Graphics@RegularPolygon not allowed? \$\endgroup\$ Commented Sep 16, 2016 at 23:50
  • \$\begingroup\$ @GregMartin It's allowed, but it's much harder to specify radius with it. \$\endgroup\$
    – ASCII-only
    Commented Oct 16, 2016 at 4:41
12
\$\begingroup\$

Java 8 : 533 322 - 25% = 241.5

Well, it's Java :/ Just draws lines, point to point. Should work for any arbitrarily sized polygon. Cut it down quite a bit from original size. Huge credit to Vulcan (in comments) for the golf lesson.

import java.awt.*;class D{public static void main(String[]v){new Frame(){public void paint(Graphics g){int i=0,r=Short.valueOf(v[0]),s=Short.valueOf(v[1]),o=r+30,x[]=new int[s],y[]=x.clone();for(setSize(o*2,o*2);i<s;x[i]=(int)(Math.cos(6.28*i/s)*r+o),y[i]=(int)(Math.sin(6.28*i++/s)*r+o));g.drawPolygon(x,y,s);}}.show();}}

Line Breaks:

import java.awt.*;
class D{
    public static void main(String[]v){
        new Frame(){
            public void paint(Graphics g){
                int i=0,r=Short.valueOf(v[0]),s=Short.valueOf(v[1]),o=r+30,x[]=new int[s],y[]=x.clone();
                for(setSize(o*2,o*2);i<s;x[i]=(int)(Math.cos(6.28*i/s)*r+o),y[i]=(int)(Math.sin(6.28*i++/s)*r+o));
                g.drawPolygon(x,y,s);
            }
        }.show();
    }
}

Input is arguments [radius] [sides]:

java D 300 7

Output:

a polygon!

\$\endgroup\$
15
  • 2
    \$\begingroup\$ Eliminate 12 bytes by importing java.awt.image.* instead of java.awt.image.BufferedImage \$\endgroup\$
    – FThompson
    Commented Apr 16, 2014 at 15:32
  • 1
    \$\begingroup\$ I've reduced it to 500 bytes using a few tricks. 1) Use Short.valueOf instead of Integer.valueOf to save four bytes, as input should never exceed the range of shorts. 2) y[]=x.clone() saves one byte over y[]=new int[s]. 3) Use the deprecated f.show(); instead of f.setVisible(1>0); to save an addition nine bytes. 4) Use 6.28 instead of Math.PI*2, as the estimation is accurate enough for this purpose, saving three bytes. 5) Declare Graphics g instead of Graphics2D g when creating the graphics instance to save two bytes. \$\endgroup\$
    – FThompson
    Commented Apr 16, 2014 at 22:15
  • 1
    \$\begingroup\$ @Vulcan I got it down another 120 (mainly by trashing the BufferedImage and Graphics altogether and just throwing everything in paint()). It did change the color of the image, though it still looks good IMO. Thanks for making me take another look at this :) \$\endgroup\$
    – Geobits
    Commented Apr 16, 2014 at 23:26
  • 1
    \$\begingroup\$ @Geobits Great improvements. Working off of your reduced version, I've cut it down further to 349 bytes by eliminating the Frame as a local variable, removing the d integer, and using/abusing the for-loop to save a few characters, mainly semicolons. Here's a version with whitespace as well. \$\endgroup\$
    – FThompson
    Commented Apr 17, 2014 at 2:37
  • 1
    \$\begingroup\$ Reduced to 325 bytes by using drawPolygon instead of drawLine. Whitespace version. \$\endgroup\$
    – FThompson
    Commented Apr 17, 2014 at 4:25
11
\$\begingroup\$

TeX/TikZ (60 – 80.25)

File polygon.tex:

\input tikz \tikz\draw(0:\r)\foreach\!in{1,...,\n}{--(\!*360/\n:\r)}--cycle;\bye

(80 bytes)

The radius and number of sides are provided as variables/macros \r and \n. Any TeX unit can be given for the radius. Without unit, the default unit cm is used. Examples:

\def\r{1}\def\n{5}    % pentagon with radius 1cm
\def\r{10mm}\def\n{8} % octagon with radius 10mm

(16 bytes without values)

If the page number should be suppressed, then it can be done by

\footline{}

(11 bytes)

Examples for generating PDF files:

pdftex "\def\r{1}\def\n{3}\input polygon"

Triangle

pdftex "\def\r{1}\def\n{5}\input polygon"

Polygon

pdftex "\def\r{1}\def\n{8}\input polygon"

Octagon

pdftex "\def\r{1}\def\n{12}\input polygon"

Dodecagon

Score:

It is not clear to, what needs counting. The range for the score would be:

  • The base code is 80 bytes minus 25% = 60

  • Or all inclusive (input variable definitions, no page number): (80 + 16 + 11) minus 25% = 80.25

  • If the connection between the first and last point do not need to be smooth, then --cycle could be removed, saving 7 bytes.

\$\endgroup\$
8
\$\begingroup\$

Geogebra, 42 – 25% = 31.5 bytes

If you count in characters instead of bytes, this would be 41 – 25% = 30.75 characters.

(That is, if you consider Geogebra a language...)

Assumes the radius is stored in the variable r and the number of sides stored in the variable s.

Polygon[(0,0),(sqrt(2-2cos(2π/s))r,0),s]

This uses the cosine theorem c2 = a2 + b2 – 2 a b cos C to calculate the side length from the given radius.

Sample output for s=7, r=5

enter image description here

\$\endgroup\$
6
\$\begingroup\$

C, 359 Chars

My first attempt at golfing. At least it beats the Java solution ;-)

int r,n,l,g,i,j,x,y;char* b;float a,c,u,z,p,q,s,t;main(int j,char**v){r=atoi(v[1]);b=malloc(g=(l=r*2+1)*r*2+1);memset(b,32,g);for(j=g-2;j>0;j-=l){b[j]='\n';}b[g-1]=0;a=2*3.14/(n=atoi(v[2]));for(;i<=n;i++,p=s,q=t){c=i*a;s=sin(c)*r+r;t=cos(c)*r+r;if(i>0){u=(s-p)/r,z=(t-q)/r;for(j=0;j<r;j++){x=p+u*j;y=q+z*j;if(x>=0&&y>=0&&y<r*2&&x<l-1)b[y*l+x]='#';}}}puts(b);}

ungolfed:

int r,n,l,g,i,j,x,y;
char* b;
float a,c,u,z,p,q,s,t;
main(int j,char**v){
    r=atoi(v[1]);
    b=malloc(g=(l=r*2+1)*r*2+1);
    memset(b,32,g);
    for(j=g-2;j>0;j-=l){b[j]='\n';} 
    b[g-1]=0;
    a=2*3.14/(n=atoi(v[2]));
    for(;i<=n;i++,p=s,q=t){
        c=i*a;s=sin(c)*r+r;t=cos(c)*r+r;
        if(i>0){
            u=(s-p)/r,z=(t-q)/r;
            for(j=0;j<r;j++){
                x=p+u*j;y=q+z*j;
                if(x>=0&&y>=0&&y<r*2&&x<l-1)b[y*l+x]='#';
            }
        }
    }
    puts(b);
}

And it's the only program that outputs the polygon in ASCII instead of drawing it. Because of this and some floating point rounding issues, the output doesn't look particularly pretty (ASCII Chars are not as high as wide).

                 ######
               ###    ###
            ####        ####
          ###              ###
        ###                  ####
     ###                        ###
     #                            #
     #                            ##
    #                              #
    #                              #
   ##                              ##
   #                                #
  ##                                ##
  #                                  #
  #                                  #
 ##                                  ##
 #                                    #
##                                    ##
#                                      #
#                                      #
#                                      #
#                                      #
##                                    ##
 #                                    #
 ##                                  ##
  #                                  #
  #                                  #
  ##                                ##
   #                                #
   ##                              ##
    #                              #
    #                              #
     #                            ##
     #                            #
     ###                        ###
        ###                  ####
          ###              ###
            ###         ####
               ###    ###
                 ######
\$\endgroup\$
2
  • \$\begingroup\$ The first int can be removed since they are assumed to be int by the compiler. Also, the last for loop can be changed to for(j=0;j<r;){x=p+u*j;y=q+z*j++;//... \$\endgroup\$
    – user12205
    Commented Apr 16, 2014 at 15:02
  • \$\begingroup\$ The if(i<0) could be changed to if(i). Which is still only needed in one iteration, but couldn't find an efficient way to take it out :( \$\endgroup\$
    – Allbeert
    Commented Apr 16, 2014 at 19:10
6
\$\begingroup\$

C: 229 180

#include<stdio.h>
#include<math.h>
main(){float n=5,r=10,s=tan(1.57*(1.-(n-2.)/n))*r*2.,i=0,j,x,c,t;int u,v;for(;i<n;i++)for(j=0;j<s;j++)x=i*6.28/n,c=cos(x),t=sin(x),x=j-s/2.,u=c*r+t*x+r*2.,v=-t*r+c*x+r*2,printf("\e[%d;%dH*",v,u);}

(r is radius of incircle)

Please run in ANSI terminal

Edit:

  • take ace's suggestion
  • use old variables (or #define) as input
  • use circumcircle radius now
u;main(v){float p=3.14,r=R*cos(p/n),s=tan(p/n)*r*2,i=0,j,x,c,t;for(;i++<n;)for(j=0;j<s;)x=i*p/n*2,c=cos(x),t=sin(x),x=j++-s/2,u=c*r+t*x+r*2,v=c*x-t*r+r*2,printf("\e[%d;%dH*",v,u);}

compile:

gcc -opoly poly.c -Dn=sides -DR=radius -lm
\$\endgroup\$
1
  • \$\begingroup\$ When you use gcc you can actually omit the #includes. Also, you can declare v as global outside main, and declare u as a parameter of main, then you don't need int (i.e. v;main(u){//...). Finally, you can change the last for loop into for(j=0;j<s;)/*...*/x=j++-s/2.,//... \$\endgroup\$
    – user12205
    Commented Apr 16, 2014 at 15:07
4
\$\begingroup\$

Mathematica, 54 * 75% = 40.5

Graphics@Polygon@Table[r{Cos@t,Sin@t},{t,0,2Pi,2Pi/n}]

I don't even think there's a point for an ungolfed version. It would only contain more whitespace.

Expects the radius in variable r and number of sides in variable n. The radius is a bit meaningless without displaying axes, because Mathematica scales all images to fit.

Example usage:

enter image description here

\$\endgroup\$
2
  • \$\begingroup\$ Graphics@Polygon@Array[r{Sin@#,Cos@#}&,n+1,{0,2π}] \$\endgroup\$
    – chyanog
    Commented Jun 15, 2014 at 8:19
  • \$\begingroup\$ @chyaong ah, I tend to forget about Array . \$\endgroup\$ Commented Jun 15, 2014 at 8:24
4
\$\begingroup\$

HTML/JavaScript : 215 - 25% = 161.25, 212 - 25% = 159

<canvas><script>R=100;i=S=10;c=document.currentScript.parentNode;c.width=c.height=R*2;M=Math;with(c.getContext("2d")){moveTo(R*2,R);for(;i-->0;){a=M.PI*2*(i/S);lineTo(R+M.cos(a)*R,R+M.sin(a)*R)}stroke()}</script>

Ungolfed version :

<canvas><script>
    var RADIUS = 100;
    var SIDES_COUNT = 10;
    var canvas = document.currentScript.parentNode;
    canvas.width = canvas.height = RADIUS * 2;
    var context = canvas.getContext("2d");
    context.moveTo(RADIUS * 2, RADIUS);
    for(i = 1 ; i <= SIDES_COUNT ; i++) {
        var angle = Math.PI * 2 * (i / SIDES_COUNT);
        context.lineTo(
            RADIUS + Math.cos(angle) * RADIUS,
            RADIUS + Math.sin(angle) * RADIUS
        );
    }
    context.stroke();
</script>
\$\endgroup\$
5
  • \$\begingroup\$ Save 4 chars by i=S=5; and for(;i-->0;). \$\endgroup\$
    – Matt
    Commented Apr 17, 2014 at 1:06
  • \$\begingroup\$ @Matt Thank you ! I didn't know this syntax, and can't find any information about it. How is it called ? \$\endgroup\$
    – sebcap26
    Commented Apr 17, 2014 at 14:49
  • \$\begingroup\$ @sebcap26 Do you mean the i-->0 part? It's the same as i-- > 0. Some people also call it the arrow operator or the goes to operator ;) \$\endgroup\$
    – ComFreek
    Commented Apr 17, 2014 at 19:19
  • \$\begingroup\$ No worries :) As @sebcap26 said, it's just decrementing every time the for loop evaluates the condition. \$\endgroup\$
    – Matt
    Commented Apr 18, 2014 at 2:45
  • \$\begingroup\$ I think you can save chars removing c=document.currentScript.parentNode; and replacing <canvas> by <canvas id="c"> \$\endgroup\$
    – Hedi
    Commented Sep 16, 2016 at 21:24
3
\$\begingroup\$

Postscript 156 - 25% = 117

translate exch 1 exch dup dup scale div currentlinewidth mul setlinewidth
1 0 moveto dup{360 1 index div rotate 1 0 lineto}repeat closepath stroke showpage

Pass the radius, number of sides, and center point on the command line

gs -c "100 9 300 200" -- polyg.ps

or prepend to the source

echo 100 9 300 200 | cat - polyg.ps | gs -

Translate to the center, scale up to the radius, move to (1,0); then repeat n times: rotate by 360/n, draw line to (1,0); draw final line, stroke and emit the page.

\$\endgroup\$
3
\$\begingroup\$

Sage, 44 - 25% = 33

Assumes the number of sides is stored in the s variable and the radius is stored in the r variable.

polytopes.regular_polygon(s).show(figsize=r)

Sample output:

s=5, r=3

enter image description here

s=5, r=6

enter image description here

s=12, r=5

enter image description here

\$\endgroup\$
2
  • \$\begingroup\$ The scaling of the axes is misleading. Is that fixable? (e.g first point at (0,3) when radius=3, instead of (0,1)) \$\endgroup\$ Commented Apr 17, 2014 at 15:30
  • 1
    \$\begingroup\$ @DigitalTrauma My program basically generates the "standard" regular polygon, then enlarges the image by a scale factor. As far as I know the regular_polygon function always generates polygons with the first vertex at (0,1). A fix would be to not show the axes with an additional 7 bytes (,axes=0 after figsize=r) \$\endgroup\$
    – user12205
    Commented Apr 17, 2014 at 17:45
3
\$\begingroup\$

bc + ImageMagick + xview + bash, 104.25 (139 bytes - 25%)

This challenge would be incomplete without an ImageMagick answer...

convert -size $[$2*2]x$[$2*2] xc: -draw "polygon `bc -l<<Q
for(;i++<$1;){t=6.28*i/$1;print s(t)*$2+$2,",";c(t)*$2+$2}
Q`" png:-|xview stdin

For example, ./polygon.sh 8 100 produces this image:

enter image description here

\$\endgroup\$
2
\$\begingroup\$

JavaScript 584 (867 ungolfed)

This code uses N Complex Roots of unity and translates the angles to X,Y points. Then the origin is moved to centre of the canvas.

Golfed

function createPolygon(c,r,n){
c.width=3*r;
c.height=3*r;
var t=c.getContext("2d");
var m=c.width/2;
t.beginPath(); 
t.lineWidth="5";
t.strokeStyle="green";
var q=C(r, n);
var p=pts[0];
var a=p.X+m;
var b=p.Y+m;
t.moveTo(a,b);
for(var i=1;i<q.length;i++)
{
p=q[i];
t.lineTo(p.X+m,p.Y+m);
t.stroke();
}
t.lineTo(a,b);
t.stroke();
}
function P(x,y){
this.X=x;
this.Y=y;
}
function C(r,n){
var p=Math.PI;
var x,y,i;
var z=[];
var k=n;
var a;
for(i=0;i<k;i++)
{
a = 2*i*p/n;
x = r*Math.cos(a);
y = r*Math.sin(a);
z.push(new P(x,y));
}
return z;
}

Sample output:

Output in Chrome

Ungolfed

function createPolygon(c,r,n) {
c.width = 3*r;
c.height = 3*r;
var ctx=c.getContext("2d");
var mid = c.width/2;
ctx.beginPath(); 
ctx.lineWidth="5";
ctx.strokeStyle="green";
var pts = ComplexRootsN(r, n);
if(null===pts || pts.length===0)
{
alert("no roots!");
return;
}
var p=pts[0];
var x0 = p.X + mid;
var y0 = p.Y + mid;
ctx.moveTo(x0,y0);
for(var i=1;i<pts.length;i++)
{
p=pts[i];
console.log(p.X +"," + p.Y);
ctx.lineTo(p.X + mid, p.Y + mid);
ctx.stroke();
}
ctx.lineTo(x0,y0);
ctx.stroke();
}

function Point(x,y){
this.X=x;
this.Y=y;
}

function ComplexRootsN(r, n){
var pi = Math.PI;
var x,y,i;
var arr = [];
var k=n;
var theta;
for(i=0;i<k;i++)
{
theta = 2*i*pi/n;
console.log('theta: ' + theta);
x = r*Math.cos(theta);
y = r*Math.sin(theta);
console.log(x+","+y);
arr.push(new Point(x,y));
}
return arr;
}

This code requires HTML5 canvas element, c is canvas object, r is radius and n is # of sides.

\$\endgroup\$
0
2
\$\begingroup\$

PHP 140 - 25% = 105

<?
for(;$i++<$p;$a[]=$r-cos($x)*$r)$a[]=$r-sin($x+=2*M_PI/$p)*$r;
imagepolygon($m=imagecreatetruecolor($r*=2,$r),$a,$p,0xFFFFFF);
imagepng($m);

Assumes two predefined variables: $p the number of points, and $r the radius in pixels. Alternatively, one could prepend list(,$r,$p)=$argv; and use command line arguments instead. Output will be a png, which should be piped to a file.


Output

$r=100; $p=5;

$r=100; $p=6;

$r=100; $p=7;

$r=100; $p=50;

\$\endgroup\$
2
\$\begingroup\$

HTML + JavaScript, 12 + 127 = 139 bytes

<canvas id=c
s=>r=>(g=n=>n?g(n-1,d.lineTo(r+r*M.cos(x=M.PI*2*n/s),r+r*M.sin(x))):d.fill())(s,c.width=c.height=r+r,d=c.getContext`2d`,M=Math)

Try it on Codepen

HTML (SVG) + JavaScript, 20 + 140 = 160 bytes

<svg id=c><path id=p
s=>r=>p.setAttribute(`d`,`M${M=Math,v=c.style,v.width=v.height=r+r},`+r+(g=n=>n?`L${r+r*M.cos(x=M.PI*2*n/s)},`+(r+r*M.sin(x))+g(n-1):``)(s))

Try it on Codepen

\$\endgroup\$
5
  • \$\begingroup\$ Japt canvas commands when? \$\endgroup\$
    – Razetime
    Commented Oct 21, 2020 at 16:45
  • \$\begingroup\$ Not my language, @Razetime and its creator hasn't been seen in about 2 years. \$\endgroup\$
    – Shaggy
    Commented Oct 22, 2020 at 9:50
  • \$\begingroup\$ Ah, welp. Thought I might ask, since you wrote your own interpreter for it. \$\endgroup\$
    – Razetime
    Commented Oct 22, 2020 at 9:54
  • \$\begingroup\$ 'Cause the official one was no longer fit for purpose ;) I have contributed a few features to Japt in the past but don't have write permissions on the repo to continue doing so. \$\endgroup\$
    – Shaggy
    Commented Oct 22, 2020 at 9:56
  • \$\begingroup\$ Maybe I can help with writing a fork! \$\endgroup\$
    – Razetime
    Commented Oct 22, 2020 at 10:03
2
\$\begingroup\$

R, 42 bytes -25% = 31.5

function(n,r,p=r*1i^(4/n*0:n))plot(p,,"l")

Try it at rdrr.io

Calculates coordinates of vertices in the complex plane as r times a power-series of the (4/n)th-root of i.

Example output of regular_polygon(7,3):

enter image description here

\$\endgroup\$
1
\$\begingroup\$

TI-80 BASIC, 25 bytes - 25% = 18.75

PARAM
2π/ANS->TSTEP
"COS T->X1ᴛ
"SIN T->Y1ᴛ
DISPGRAPH

Assumes all settings are set to the default values. Run the program like 5:PRGM_POLYGON (for a pentagon)

It works by drawing a circle with a very low number of steps. For example, a pentagon would have steps of 2π/5 radians.

The window settings are good enough by default, and TMIN and TMAX are set to 0 and , so all we need to change is TSTEP.

\$\endgroup\$
1
\$\begingroup\$

SmileBASIC 3, 183 159 - 25% = 119.25 bytes

Takes the sides and radius from INPUT, calculates and stores the points, and then draws them by using GLINE. I feel like this could be shorter but it's like 1 AM, whatever. Assumes a clean and default display env, so you might need to ACLS when running it from DIRECT.

INPUT S,R
DIM P[S,2]FOR I=0TO S-1
A=RAD(I/S*360)P[I,0]=COS(A)*R+200P[I,1]=SIN(A)*R+120NEXT
FOR I=0TO S-1GLINE P[I,0],P[I,1],P[(I+1)MOD S,0],P[(I+1)MOD S,1]NEXT

screenshot

\$\endgroup\$
2
  • 1
    \$\begingroup\$ A byte is a byte, you can't say it's only a half. \$\endgroup\$
    – 12Me21
    Commented Feb 9, 2017 at 8:09
  • \$\begingroup\$ Subtracting 25% rule. \$\endgroup\$ Commented Feb 13, 2017 at 15:17
1
\$\begingroup\$

OpenSCAD: 31 less 25% = 23.25

module p(n,r){circle(r,$fn=n);}

First post here! I know I'm late to the party, but this seemed like as good a question as any to start with. Call using p(n,r).

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Welcome to the site! \$\endgroup\$
    – Wheat Wizard
    Commented Mar 13, 2017 at 22:41
1
+100
\$\begingroup\$

APL (dzaima/APL), 50 - 12.5 = 37.5 37 - 9.25 = 27.75 bytes

P5.draw←{P5.G.ln ↑r+r×2 1○ᑈs÷⍨2×○0…s}

Shortened heavily with the help of The APL Orchard.

Explanation:

P5.draw←{P5.G.ln ↑r+r×2 1○ᑈs÷⍨2×○0…s}
P5.draw←{                           } Draw the following on the canvas every frame:
         P5.G.ln                      Draw a line using array(x1,y1,x2,y2...)
                                 0…s  Range from 0 to number of sides
                              2×○     times 2π
                           s÷⍨        divided by number of sides
                      2 1○ᑈ           Take cos and sin of each of the values from the left
                 ↑r+r×                Multiply the list by r and add r to center it, 
                                      then mix the values of the list together

Previous version:

p←(2×○⍳s+1)÷s
P5.draw←{P5.G.ln r+r×⍉(2○p)↑⍤⍮(1○p)}

Takes input as variables r and s, draws polygon with center at \$(r,r)\$.

Made with the help of the formula used here.

Outputs:

100 3

enter image description here

100 5

enter image description here

200 7

enter image description here

To execute the program, use the setup here, for a full view of the drawn polygon.

\$\endgroup\$
0
\$\begingroup\$

ActionScript 1, Flash Player 6: 92 - 25% = 69

n=6
r=100
M=Math
P=M.PI*2
lineStyle(1)
moveTo(r,0)
while((t+=P/n)<=P)lineTo(M.cos(t)*r,M.sin(t)*r)
\$\endgroup\$
0
\$\begingroup\$

C# in LINQPAD

Credit for the math part goes to Geobits (I hope you don't mind!) with the Java answer. I'm hopeless at math :)

I did this in LINQPAD as it's got a built in output window. So essentially you can drag and drop the following in to it and it'll draw the polygon. Just switch it to 'C# Program', and import the System.Drawing lib into the query properties.

//using System.Drawing;

void Main()
{
// Usage: (sides, radius)
    DrawSomething(4, 50);
}

void DrawSomething(int sides, int radius)
{
    var points = new Point[sides];
    var bmpSize = radius*sides;
    var bmp = new Bitmap(bmpSize,bmpSize);
    using (Graphics g = Graphics.FromImage(bmp))
    {   
        var o = radius+30;
        for(var i=0; i < points.Length; i++)
        {
            // math thanks to Geobits
            double w = Math.PI*2*i/sides;
            points[i].X = (int)(Math.Cos(w)*radius+o);
            points[i].Y = (int)(Math.Sin(w)*radius+o);
        }
        g.DrawPolygon(new Pen(Color.Red), points);
    }
    Console.Write(bmp);
}

enter image description here

\$\endgroup\$
0
\$\begingroup\$

Matlab 58 bytes - 25% = 43.5

Saw no Matlab solution, so here is one which is pretty straightforward:

f=@(n,r) plot(r*cos(0:2*pi/n:2*pi),r*sin(0:2*pi/n:2*pi));

You can shave off some bytes if r and n are already in the workspace.

Example call:

f(7,8)

7-gon with radius 8

\$\endgroup\$
0
\$\begingroup\$

Python 2, 222 bytes

from math import*
def f(s,r):
 r*=cos(pi/s)
 v,R=2*pi/s,[(2*t)/98.-1for t in range(99)]
 print"P1 99 99 "+" ".join(["0","1"][all(w*(w-x)+z*(z-y)>0for w,z in[(r*cos(a*v),r*sin(a*v))for a in range(s)])]for x in R for y in R)

Checks if a pixel is on the inner side of all hyperplanes (lines) of the polygon. The radius is touched because actually the apothem is used.

enter image description here enter image description here

\$\endgroup\$
0
\$\begingroup\$

Mathematica 27 ( = 36 - 25%)

Graphics[Polygon[CirclePoints[r, n]]]

When we submit Mathematica code we often forget about new functions that keep getting built into the language, with current language vocabulary amassing around 5000 core functions. Large and expanding language vocabulary is btw quite handy for code-golfing. CirclePoints were introduced in the current version 11.X. A specific example of 7-sided radius 5 is:

enter image description here

Also you just need to enter angle parameter to control orientation of your polygon:

Graphics[Polygon[CirclePoints[{1, 2}, 5]]]

enter image description here

\$\endgroup\$
0
\$\begingroup\$

Python 2, 74 bytes - 25% = 55.5

Input is in the variables r,n. If included in the count, it would be r,n=input(), for 12 bytes more.

import math,turtle as t
exec"t.fd(2*r*math.sin(180/n));t.rt(360/n);"*n

Try it online - (uses different code since exec is not implemented in the online interpreter)

\$\endgroup\$
0
\$\begingroup\$

SmileBASIC, 85 75 - 25% = 56.25 bytes

FOR I=0TO S
A=I/S*6.28N=X
M=Y
X=R+R*COS(A)Y=R+R*SIN(A)GLINE N,M,X,Y,-I
NEXT

Variables S and R are used for input.

Explained:

FOR I=0 TO Sides        'Draw n+1 sides (since 0 is skip)
 Angle=I/Sides*6.28     'Get angle in radians
 OldX=X:OldY=Y          'Store previous x/y values
 X=Radius+Radius*COS(A) 'Calculate x and y
 Y=Radius+Radius*SIN(A)
 GLINE OldX,OldY,X,Y,-I 'Draw line. Skip if I is 0 (since old x and y aren't set then)
NEXT

The sides are drawn using the color -I, which is usually close to -1 (&HFFFFFFFF white) (except when I is 0, when it's transparent).

You can also draw a filled polygon by using GTRI N,M,X,Y,R,R,-I instead of GLINE...

\$\endgroup\$
0
\$\begingroup\$

Tikz, 199 bytes

\documentclass[tikz]{standalone}\usetikzlibrary{shapes.geometric}\begin{document}\tikz{\def\p{regular polygo}\typein[\n]{}\typein[\r]{}\node[draw,minimum size=\r,\p n,\p n sides=\n]{}}\end{document}

This solution uses the tikz library shapes.geometric.

Here is what a polygon with 5 sides and radius 8in looks like when viewed in evince.

Obligatory Picture

\$\endgroup\$
0
\$\begingroup\$

MATLAB/Octave, 26.25 bytes (35 bytes-25%)

@(n,r)polar((0:n)/n*2*pi,r+(0:n)*0)

Can be tested on octave-online.
@ptev already posted a MATLAB answer but mine uses far less bytes and isn't distorted.
We can save up another 6 bytes (or 4.5 including bonus) if we assume input can be given as variables r&n already existing in workspace - then just calling polar((0:n)/n*2*pi,r+(0:n)*0) is enough.

Also, example output (n=5,r=3):
enter image description here

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.