# Draw the USA flag

I noticed that it seems nobody has posted a non-ASCII (related) USA flag challenge yet, so what better time than the 4th of July?

## The Challenge

Draw the current (as of 2022) flag of the United States of America. Here is the flag: ### Specifications • Hoist (height) of the flag: A = 1.0
• Fly (width) of the flag: B = 1.9
• Hoist (height) of the canton ("union"): C = 0.5385 (A × 7/13, spanning seven stripes)
• Fly (width) of the canton: D = 0.76 (B × 2/5, two-fifths of the flag width)
• E = F = 0.0538 (C/10, one-tenth of the height of the canton)
• G = H = 0.0633 (D/12, one twelfth of the width of the canton)
• Diameter of star: K = 0.0616 (L × 4/5, four-fifths of the stripe width, the calculation only gives 0.0616 if L is first rounded to 0.077)
• Width of stripe: L = 0.0769 (A/13, one thirteenth of the flag height)

The colors used are (as RGB tuples and hex codes):

• White: 255,255,255 or #FFFFFF;
• Old Glory Red: 179,25,66 or #B31942;
• Old Glory Blue: 10,49,97 or #0A3161.

Source: Wikipedia

### Rules

• The image must be sized at a 19:10 ratio, and at least 760 by 400 pixels (if it is a raster image).
• If your language does not allow to use arbitrary RGB colors you may use any colors reasonably recognizable as "white", "red", and "blue".
• The image can be saved to a file or piped raw to STDOUT in any common image file format, or it can be displayed in a window.
• Your program must create the image and not just load it from a website.
• Built-in flag images, flag-drawing libraries, horrendously upscaling a flag emoji or any other emoji are prohibited.

### Scoring

This is , so shortest code wins!

Since the flag can change at any time following the admission of one or more new states, let's make our programs futureproof! -10 bonus points if your program can draw other star dispositions by accepting as an optional argument a list of star coordinates (which may be a number different than 50) in any coordinate system of your choice (inspired by this challenge).

• If such optional argument is not provided, your program must draw the flag as previously described.
• If an empty list is passed as a parameter, you can either draw no stars, or treat it as if no argument has been given (and hence draw the standard flag).
• The other parts of the flag (the stripes and the blue background) must be the same in any case.

Sandbox

• If the default for a given language/interpreter is a white background, then the white stripes don't need to be painted and the output will look correct. Is this OK, or does the image need to be "portable" to a non-white background? Jul 7, 2022 at 10:51
• @bartyslartfast In general I would follow standard graphical output rules Jul 7, 2022 at 12:55
• I think a solution has to work just on the specified language/interpreter, and it does not have to work in other cases. For example, there are C solutions that use features of the specific compiler, so I think what you ask is perfectly acceptable. Jul 7, 2022 at 12:58

# PostScript, 193185170 158 bytes - 10 = 148

00000000: 2f73 7b92 4e38 2e32 3392 6c92 3e37 926c  /s{.N8.23.l.>7.l
00000010: 3630 9201 92ad 3020 3492 6b34 7b31 3434  60....0 4.k4{144
00000020: 9288 3020 3492 637d 9283 9242 924d 7d92  ..0 4.c}...B.M}.
00000030: 3328 0a31 61b3 1942 297b 3235 3592 367d  3(.1a..B){255.6}
00000040: 9249 929d 3088 1488 787b 3092 3e32 3437  .I..0...x{0.>247
00000050: 880a 9280 7d92 4892 9d30 883c 3938 2e38  ....}.H..0.<98.8
00000060: 8846 9280 3192 9692 1a30 923d 7b31 8801  .F..1....0.={1..
00000070: 327b 2f69 923e 9233 6920 3288 0b7b 6988  2{/i.>.3i 2..{i.
00000080: 0239 7b31 9258 737d 9248 7d92 487d 9248  .9{1.Xs}.H}.H}.H
00000090: 7d7b 7b7b 737d 9265 7d92 a37d 9255       }{{{s}.e}..}.U


Untokenized version:

/s{                                            % y x s -
gsave                                      % star of radius 4 at (x,y)
8.23 mul exch 7 mul 60 add                 % scale and translate position
translate                                  % move origin
0 4 moveto 4{144 rotate 0 4 lineto}repeat  % draw star
fill                                       % fill it
grestore
}def
<0a3161b31942>{255 div}forall                  % push blue, red color values
setrgbcolor                                    % red
0 20 120{0 exch 247 10 rectfill}for            % stripes
setrgbcolor                                    % blue
0 60 98.8 70 rectfill                          % rectangle
1 setgray                                      % white
count 0 eq{                                    % if stack empty: standard stars
1 1 2{/i exch def
i 2 11{i 2 9{1 index s}for}for           % grid of stars, offset i=1,2
}for
}{                                             % if stack not empty
{{s}loop}stopped                           % place stars until stack empty
}ifelse


If called without arguments, produces the standard flag. Takes optional arguments from the stack, which can be inserted from the command line like this:

gs -c '3 2 5 4' -- usflag.ps

That plots two stars at (2,3) and (4,5), where (1,1) is the position of the bottom-left star in the standard flag, and the horizontal and vertical units are chosen so that H=1 and F=1. ### Without custom star placement: 131 bytes

Removing the custom star placement code saves 27 bytes:

00000000: 280a 3161 b319 4229 7b32 3535 9236 7d92  (.1a..B){255.6}.
00000010: 4992 9d30 8814 8878 7b30 923e 3234 3788  I..0...x{0.>247.
00000020: 0a92 807d 9248 929d 3088 3c39 382e 3888  ...}.H..0.<98.8.
00000030: 4692 8031 9296 3188 0132 7b2f 6992 3e92  F..1..1..2{/i.>.
00000040: 3369 2032 880b 7b69 8802 397b 3192 5892  3i 2..{i..9{1.X.
00000050: 4e38 2e32 3392 6c92 3e37 926c 3630 9201  N8.23.l.>7.l60..
00000060: 92ad 3020 3492 6b34 7b31 3434 9288 3020  ..0 4.k4{144..0
00000070: 3492 637d 9283 9242 924d 7d92 487d 9248  4.c}...B.M}.H}.H
00000080: 7d92 48                                  }.H


which only draws the standard flag, and is equivalent to

<0a3161b31942>{255 div}forall                  % push blue, red color values
setrgbcolor                                    % red
0 20 120{0 exch 247 10 rectfill}for            % stripes
setrgbcolor                                    % blue
0 60 98.8 70 rectfill                          % rectangle
1 setgray                                      % white
1 1 2{/i exch def i 2 11{i 2 9{
1 index
gsave                                      % star of radius 4 at (x,y)
8.23 mul exch 7 mul 60 add                 % scale and translate position
translate                                  % move origin
0 4 moveto 4{144 rotate 0 4 lineto}repeat  % draw star
fill                                       % fill it
grestore
}for}for}for


# BBC BASIC, 210 199 bytes

V.19;45840;25,66
F.i=0TO13j=1ANDi+1PLOT101-j,1852*j,i*75N.V.19;2576;49,97,25881;741;450;
F.i=9TO107V.29,i DIV9*61.75;i MOD9*52.5+502;
MOVE0,30F.j=1TO5k=j*88/35MOVE0,0PLOT88-i MOD2,SINk*30,COSk*30N.N.


The golfed code contains many of the following obfuscations:

• Abbreviated keywords
• Commands like PLOT and MOVE rendered as lower level VDU commands where expedient for golfing reasons.
• Many pairs of 8-bit VDU codes (terminated by comma) are replaced by 16-bit VDU codes (terminated by semicolon.)

The following are all equivalent: MOVE x,y, PLOT 4,x,y, VDU 25,4,x,y. The value 4 in the plot statement can take many values for everything from moving to drawing rectangles and triangles. BBC basic keeps track of the last two positions of the graphics cursor to facilitate these operations.

Interpreter

This interpreter has several differences from the original BBC basic. Firstly the default screen mode is black on white, with the white background being set to 255,255,255 by default.

Secondly, the palette reprogramming VDU 19operates quite differently. Original BBC basic could display (depending on mode) up to 16 different logical colours at a time (to save memory) and these could be assigned to any 18-bit physical colour. Reprogramming the palette would immediately change all existing pixels of that logical colour to the new physical colour. With this interpreter, full 24-bit colour is supported and only pixels drawn after the VDU 19 are affected.

Explanation

I selected a value of L=75 and scaled the flag accordingly, in order to make most dimensions integers.

Hopefully the comments below are fairly self explanatory. We draw the stripes first, leaving the cursor at top left to conveniently draw the blue canton by specifying its bottom right corner.

Stars are plotted in the background colour (white.) The origin is changed to the centre of each star prior to plotting for convenience. Stars are plotted on a 9x11 checkerboard grid. Only odd number stars are plotted. For the even number stars, the cursor still moves to trace out the star, but nothing is plotted.

BBC basic keeps track of the last two coordinates visited by the cursor. The stars are drawn as a series of five thin triangles by defining the current point, centre of the star, and the previous point 144 degrees away.

Ungolfed code

  VDU19,0,16,179,25,66                   :REM Change foreground colour to red
FORi=0TO13                             :REM Iterate 14 times from bottom to top
j=1ANDi                              :REM j=0 at bottom of red stripe, j=1 at top
PLOT100+j,1852*(1-j),i*75            :REM   If j=0 move to bottom right of stripe
NEXT                                   :REM   If j=1 draw a rectangle from bottom right to top left
VDU19,0,16,10,49,97                    :REM Change foreground colour to blue
PLOT101,741,450                        :REM Draw blue canton from top left to bottom right
FORi=9TO107                            :REM Iterate through 99 possible star positions in checkerboard
VDU29,i DIV9*61.75;i MOD9*52.5+502.5;:REM Reset the origin to centre of star on 9x11 grid
MOVE0,30                             :REM Move cursor to top of star
FORj=1TO5                            :REM Iterate through star points
k=j*88/35                          :REM k = j * (4/5*PI = 4/5 * 22/7 = 144 degrees)
MOVE0,0                            :REM Move to centre of star
PLOT84+i MOD2*3,30*SIN k,30*COS k  :REM If i is odd draw a triangle linking the latest point to the last 2
NEXT                                 :REM   cursor positions, namely the centre and the previous point
NEXT                                   :REM   If i is even draw nothing. • I thought BBC Basic was only allowed for the Union Jack. Jul 5, 2022 at 23:18
• @manassehkatz-Moving2Codidact The first US flag had a Union Jack on it, that's my excuse. en.wikipedia.org/wiki/Grand_Union_Flag That and the fact that I hate QBasic. Maybe we should do Hawaii next, that flag still has a Union Jack on it. Jul 6, 2022 at 1:09

# Scratch, 588 535 bytes

Try it online!

define(W)(H
repeat(H
change y by(1
pen down
set x to(W
set x to(-190
pen up
define(X)(Y)(Q
set[y v]to(Y
repeat(Q
set[x v]to(X
change[y v]by(21
repeat((Q)+(1
pen up
go to x(x)y(y
set pen color to[#fff
pen down
set[c v]to[
repeat(5
point in direction(
move(1)steps
turn cw(162)degrees
change[c v]by(2
repeat(5
move(c)steps
turn cw(144)degrees
end
change[x v]by(-5
when gf clicked
go to x(-190)y(-93
set pen color to[#b31942
erase all
repeat(7
[15
change y by(16
end
set y to(
set pen color to[668001
[-38][108
(-52)(-8)(5
(-64)(2)(4


@att saved 42 bytes by forgoing the -10 byte bonus, and combined the star placement and generation scripts. att also removed the function (custom block) names and converted a hex color to Scratch's RGB system.

## Explanation

define(W)(H     custom rectangle function
repeat(H        loop for each px of height
change y by(1   moves up 1px
pen down        applies pen
set x to(W      moves horizontally a specified amount
set x to(-190   resets x-position
pen up          stops applying pen

define(X)(Y)(Q          custom star & placement function
set[y v]to(Y            sets starting y to a specified amount
repeat(Q                loop for each row of stars
set[x v]to(X            sets starting x to a specified amount
change[y v]by(21        increases y value by 21px
repeat((Q)+(1           loop for each star in the width
pen up                  stops applying pen
go to x(x)y(y           goes to coordinate specified by vars
set pen color to[#fff   sets pen color to white
pen down                applies pen
set[c v]to[             sets a counter to null (implicit 0)
repeat(5                loop enough to fill star
point in direction(     resets facing angle
move(1)steps            move 1px in the facing angle
turn cw(162)degrees     rotates 162 degrees
change[c v]by(2         increases the counter 'c'
repeat(5                loop for each point of the star
move(c)steps            moves 'c'px in the facing angle
turn cw(144)degrees     rotates 144 degrees
end                     syntax
change[x v]by(-5        increases the x position

when gf clicked            syntax
go to x(-190)y(-93         resets position
set pen color to[#b31942   sets color to Old Glory Red*
erase all                  clears stage
repeat(7                   loop for each stripe
[15                   draw a red stripe
change y by(16             skip over a white stripe
end                        syntax
set y to(                  resets y position
set pen color to[668001    sets color to Old Glory Blue*
[-38][108                  draws the canton
(-52)(-8)(5                draws a 6 by 5 array of stars
(-64)(2)(4                 draws a 5 by 4 array of stars

*The project uses HSB approximations of the specified colors.
This code uses HEX values and base-10 equivalents.

• 546 bytes
– att
Jul 7, 2022 at 4:00
• There's a spurious space in go to x(-190) y(-93, oops, -1. The "built-in color" is just the decimal value of the hexcode; you can confirm it works by putting e.g. (round) into the color picker.
– att
Jul 7, 2022 at 19:15

# Desmos, 305 bytes

l=[0...9]
a=[1...13]
b=[1...5]
P(x,y)=polygon(x+WcosR,y+WsinR)
W=[1,2/(3+\sqrt5)][mod(l,2)+1]120
R=l\pi/5+\pi/2
0<=x<=7410\{3a-3<=.01y<=3a\}
0<=x<=2964\{18<=.01y<=39\}
w=hsv(0,0,1)
v=rgb(10,49,97)
r=[w,rgb(179,25,66)][mod(a,2)+1]
[P(494i-247,4110-420j)fori=[1...6],j=b]
[P(494i,3900-420j)fori=b,j=[1...4]]


Try it on Desmos!

-35 bytes thanks to Aiden Chow

• 305 Jul 7, 2022 at 2:15

# R, 398 bytes

\(w='#FFFFFF',r='#B31942',g=\(x,y,d)polygon(x,y,,,F,d),c=7/13,l=c/7,f=c/10,b=1.9,d=.76,h=d/12,z=rep,x=c(z(1:6,5)-.5,z(1:5,4))*2*h,y=1-c(z(1:5,,,6)-.5,z(1:4,,,5))*f*2,p=\(x,y,s=sinpi,d=l*.4,a=0:9/5,e=d*(s(.2)/s(.4))^2)g(x+c(d,e)*s(a),y+c(d,e)*cospi(a),w)){frame();plot.window(c(0,b),0:1);for(i in 0:6)g(c(d*(i>2),d*(i>2),b,b),c(0,l,l,0)+l*i*2,r);g(c(0,0,d,d),c(1-c,1,1,1-c),'#0A3161');mapply(p,x,y)}

Attempt This Online!

Takes optional inputs x, y which are the x- and y- components of a list of coordinates.

Multiline form:

j=\(w='#FFFFFF',r='#B31942',g=\(x,y,d)polygon(x,y,,,F,d),
c=7/13,l=c/7,f=c/10,b=1.9,d=.76,h=d/12,z=rep,x=c(z(1:6,5)-.5,z(1:5,4))*2*h,y=1-c(z(1:5,,,6)-.5,z(1:4,,,5))*f*2,
p=\(x,y,s=sinpi,d=l*.4,a=0:9/5,e=d*(s(.2)/s(.4))^2)g(x+c(d,e)*s(a),y+c(d,e)*cospi(a),w)){
frame()
plot.window(c(0,b),0:1)
for(i in 0:6)g(c(d*(i>2),d*(i>2),b,b),c(0,l,l,0)+l*i*2,r)
g(c(0,0,d,d),c(1-c,1,1,1-c),'#0A3161')
mapply(p,x,y)
}


The ratio of inner to outer diameters of the pentagonal star was calculated using a pair of similar isoceles triangles with tip angle pi/5 (36 degrees).

j() plots the following: j(x=c(0.2,0.3),y=c(0.7,0.8)) plots the following: A few bytes could be saved by not pre-defining w/r since they are only used once.

• When I try the 'Attempt this online!' link, it generates a list of [] NULL. Is that expected? Is there a way to see the flag? Jul 6, 2022 at 5:51
• by default the aspect ratio is not respected in the plot, you could replace plot.window(c(0,b),0:1) with plot.window(c(0,b),0:1,asp=1) to fix it Jul 6, 2022 at 8:15
• @stevec on your local R interpreter, or on something like rstudio.cloud or rdrr.io Jul 6, 2022 at 8:19
• Thank you Matteo C., that explains why it looks weird. Jul 6, 2022 at 9:17

# SVG(HTML5), 576560 522 bytes

<svg viewBox=0,0,741,390><path d=M0,15H741m0,60H0m0,60H741m0,60H0m0,60H741m0,60H0m0,60H741m0,60H0 stroke=#B31942 stroke-width=30 /><rect width=296.4 height=210 fill=#0A3161 /><g fill=#fff><g id=8><g id=9><g id=5><g id=4><g id=2><path id=1 d=M24.7,9,31.7534230,30.7082039,13.2873218,17.2917961H36.1126782L17.6465770,30.7082039z /><use href=#1 y=42 /></g><use href=#2 y=84 /></g><use href=#1 y=168 /></g><use href=#4 x=24.7 y=21 /></g><use href=#9 x=49.4 /></g><use href=#8 x=98.8 /><use href=#9 x=197.6 /><use href=#5 x=247

I started trying to code this manually but half-way though I discovered that Jay Bala's Wikipedia specification image linked in the question had already golfed the repetition of the stars, so I just removed the explanation, updated the colours to match the question, and golfed it down to the bare minimum acceptable in HTML5. Edit: Turns out that I'd been looking at the wrong image all along - as @Deadcode points out the flag itself is linked in the question, and it uses #fff instead of #ffffff in two places, thus saving 6 bytes, but I was able to save a further 10 bytes by golfing the star repetition even further. Edit: Saved 38 bytes thanks to @bartyslartfast by dividing all the lengths by 10 and by assuming a white background and only drawing the red stripes.

• I set out to do the same thing, but lost interest when I found that the only golfs still available were ones unrelated to the drawing commands (which is what I was most interested in golfing). It's still a worthwhile golf though. And I didn't realize it could be golfed down more as an .html file than a .svg, so good job with that. Anyway, you can golf down the #ffffff to #fff (I don't know why you changed it – it was already #fff in the original). Jul 7, 2022 at 2:22
• @Deadcode Because I was using the spec to create my SVG, it was that version that I ended up golfing down. In particular it uses inline CSS for some reason, including the use of #ffffff.
– Neil
Jul 7, 2022 at 6:04
• @Deadcode Although looking at it I did find a real 10-byte golf, so that's something.
– Neil
Jul 7, 2022 at 6:11
• 481 bytes Jul 7, 2022 at 10:05
• @bartyslartfast I'm not sure a transparent background is acceptable (you'd have to ask the OP to be sure) and I'll have to think about those decimals but I liked the idea of dividing everything by 10 so much that I divided everything by 100 instead to save another couple of bytes.
– Neil
Jul 7, 2022 at 10:38

## SVG(HTML5), 369 bytes

At first glance, repeating the stars with a <use> element looks like a good idea, but it isn't. A <pattern> element, even with the pesky patternUnits=userSpaceOnUse gets much better results.

Node positions of the stars have been rounded to integers, but that leaves the error <1.25% (0.5 for diameter=40).

<svg viewBox=0,0,1235,650><pattern id=p x=22 y=16 width=82 height=70 patternUnits=userSpaceOnUse><path d=M7,35,19,0,31,35,0,13H38ZM48,70,60,35,72,70,41,48H79Z fill=#fff /></pattern><path d=M0,25H1235m0,100H0m0,100H1235m0,100H0m0,100H1235m0,100H0m0,100H1235 stroke=#B31942 stroke-width=50 /><path d=M0,0H494V350H0Z fill=#0A3161 /><path d=M22,16h451v315H22Z fill=url(#p)

# Mathematica, 40 bytes

Entity["Country", "UnitedStates"]["Flag"]


This is not competing, since it does not follow the rules. But it shows off the power of Mathematica, IMHO.

• The rules say: "Built-in flag images, flag-drawing libraries, horrendously upscaling a flag emoji or any other emoji are prohibited." You can probably keep this around though, as long as you state that it's not competing. :) Jul 7, 2022 at 15:12

# Python3 (pillow), 403

from PIL import Image,ImageDraw as X
W,R,I,O,N=0xffffff,range,Image.new('RGB',(1001,520),4331955),56,66
d=X.Draw(I);Q=d.rectangle
[Q((0,j,1001,40+j),fill=W)for j in R(40,520,80)];Q((0,0,400,279),fill=6359601)
d.polygon([x-20for x in map(ord,'2 0*\$*-0+:239:70@*4*2 ')],fill=W)
s,P=I.crop((16,12,44,38)),I.paste;[(P(s,(16+i*N,12+j*O)),P(s,(50+j*N,40+k*O)))for i in R(6)for j in R(5)for k in R(4)]
I.show()