Draw the Swiss Flag

46

8

Task: Output the Swiss flag.

Happy Swiss National Day / Schweizer Bundesfeiertag / Fête nationale suisse / Festa nazionale svizzera / Fiasta naziunala svizra!

Details: The flag consists of a white (#FFFFFF) cross on a red (#FF0000) background. The cross consists of a 6x6 square with arms of size 6x7 glued to each side. The cross is in the center of the 32x32 square background having a distance of 6 units to each side. (Source)

The output size can be chosen by the participant, but the image must exactly match these proportions, this means its size must be a multiple of 32.

A minimal version would look like so:

flawr

Posted 2017-07-31T22:23:49.970

Reputation: 40 560

1In some versions of the flag challenges, colored ASCII output was allowed, but you have not included [tag:ascii-art]. Just to confirm, ASCII output is not allowed? – Stephen – 2017-07-31T22:25:28.537

1Right, only the widely known image formats are allowed as well as output on the screen. – flawr – 2017-07-31T22:26:34.473

20echo - I assume this is not allowed – Digital Trauma – 2017-07-31T23:03:02.910

I see a blue CH, I don't see why this should be allowed. – flawr – 2017-07-31T23:18:00.440

How widely-known do you mean? Does something like pbm qualify?

– Tutleman – 2017-07-31T23:22:49.827

1

@Tutleman I think it does

– Luis Mendo – 2017-08-01T00:33:48.560

Are the usage of library allowed ? Low level languages does not provide graphic tools in their standard library – HatsuPointerKun – 2017-08-01T01:12:37.617

@Hatsu this is always allowed if you specify the ones you use – Felix Dombek – 2017-08-01T03:35:31.083

Can the white portion of the flag be transparent? – Post Rock Garf Hunter – 2017-08-01T15:25:16.777

No it should be white. – flawr – 2017-08-01T15:57:27.567

Holy shit, I was browsing pastebin yesterday (don't ask) and I found a paste of someone making the flag of switzerland. Is this you? https://pastebin.com/v8pVcQpD

– sagiksp – 2017-08-02T10:23:19.733

@HatsuPointerKun Any language that can save/output a text file can output net ppm format

– trichoplax – 2017-08-02T22:43:54.150

@trichoplax Interesting. I didn't know about that file format... – HatsuPointerKun – 2017-08-02T23:05:04.480

does there need to be a border of non-red pixels? – 12Me21 – 2017-10-15T13:13:49.320

No, is there anything that would suggest that? – flawr – 2017-10-15T14:14:40.847

Many of the answers seem to assume that there needs to be a border. I imagine that setting the background color to red might be shorter than drawing a 32x32 pixel red square. – 12Me21 – 2017-10-15T14:42:04.227

Well the image needs to satisfy those criteria, if the background is larger or smaller than the given dimensions it is not valid. – flawr – 2017-10-15T15:00:13.330

Oh, so I can't just say "the flag is drawn in front of a red background but you can't see the edge because they're the same color"? – 12Me21 – 2017-10-15T20:33:35.337

Answers

40

SVG (HTML5), 94 83 82 64 bytes

<svg><path d=M0,0V32H32V0M6,13h7V6h6v7h7v6H19v6H13V19H6 fill=red

Saved 2 bytes thanks to @ThePirateBay. Saved 1 byte thanks to @ATaco. Saved 18 bytes thanks to @CraigAyre pointing out that a 32×32 image was acceptable. As pointed out by @Shaggy, this assumes your default background is white; add 22 bytes for a flag that works on any background:

<svg><path d=M0,0V32H32V0 fill=red /><path d=M6,13h7V6h6v7h7v6H19v6H13V19H6 fill=#FFF

Neil

Posted 2017-07-31T22:23:49.970

Reputation: 95 035

No need to close the path. You can save 4 bytes by leaving the path open. – None – 2017-08-01T00:22:08.950

As ThePirateBay said, the right > in your path tag is optional. – ATaco – 2017-08-01T00:26:04.183

@ATaco. I was actually thinking about Z command which is used to close path, but there are only two lines so no need to close the path. But you are right, > can be removed too, I forgot about it. – None – 2017-08-01T00:39:08.440

6SVG has its own "golfing language"? O.o – ETHproductions – 2017-08-01T01:09:00.163

16Being used to writing XML syntax, this code makes my eyes bleed – Nayuki – 2017-08-01T03:13:42.157

3Can you remove viewBox for the minimal version? <svg><path d=M0,0V32H32V0M6,13h7V6h6v7h7v6H19v6H13V19H6 fill=red – Craig Ayre – 2017-08-01T09:08:29.607

@ETHproductions I think this is mostly only allowed because the challenge explicitly allows well-known image formats. – pipe – 2017-08-01T21:10:34.990

@pipe I was referring to the M0,0V32H32V0M6,13h7V6h6v7h7v6H19v6H13V19H6 part – ETHproductions – 2017-08-01T21:42:42.183

You should probably mention that this is reliant on the SVGs parent element having a white background. – Shaggy – 2017-08-03T10:22:22.590

Shouldn't be too hard to write a golfing language that outputs HTML5 SVG, right? – JollyJoker – 2017-08-04T08:52:55.187

31

x86-16 Machine Code for DOS, 43 bytes

               ; Draw 32x32 red square
B8 0C 28          mov  ax, 0x0C28   ; AL == color red, AH == set pixel function
B9 00 1F          mov  cx, 31
               DrawBox:
BA 00 1F          mov  dx, 31
               DrawRow:
CD 10             int  0x10
4A                dec  dx
75 FB             jnz  DrawRow
E2 F6             loop DrawBox

               ; Draw the interior white cross
B0 0F             mov  al, 0x0F    ; high byte already set
B1 06             mov  cl, 6       ; high byte already 0
               DrawCross:
B2 0D             mov  dl, 13      ; high byte already 0
               DrawCrossInner:
CD 10             int  0x10        ; plot CX, DX
87 D1             xchg dx, cx
CD 10             int  0x10        ; plot DX, CX
87 D1             xchg dx, cx
42                inc  dx
80 FA 12          cmp  dl, 13+6
75 F2             jne  DrawCrossInner
41                inc  cx
80 F9 19          cmp  cl, 6+(32-6-6)
75 EA             jne  DrawCross

C3                ret

The above code is designed to be assembled as a COM file and then run under DOS. It invokes the ROM BIOS video services to plot the individual pixels of the flag, forming a 32×32 representation of the Swiss flag in the upper-left corner of the screen.

The code assumes that the video mode is already set to mode 0x13, which also means that it requires a VGA display. Other video modes could be used, but requiring VGA gives you two things: (1) square pixels, and (2) a default palette that includes a true 100% red (0xFF0000) (meaning you don't have to waste bytes changing the palette colors). Before running this program, you will therefore need to switch your display to mode 0x13; the following code is all you need to do that:

mov  ax, 0x13
int  0x10

The code makes no other assumptions, and should run on any x86-compatible hardware under a DOS-compatible operating system.

However, the program terminates immediately after drawing the flag, so the DOS prompt will normally be re-printed at the top-left corner of the screen, covering up the top few lines of the flag. Therefore, if you want to marvel at the true output, you need to hang/pause the system before it RETurns. Here's a screenshot of what that looks like, running in a FreeDOS virtual machine:

It might be possible to golf this down further by writing pixel data directly to the video buffer, especially since I'm already assuming mode 0x13. I haven't tried that yet. INT 0x10 is already a pretty short instruction, but if I can use the one-byte string instructions to write pixel data directly to memory, then that could result in a significant code savings.

Cody Gray

Posted 2017-07-31T22:23:49.970

Reputation: 2 639

Impressive! I don't see asm a lot but when I do it's always very interesting – Adrian Zhang – 2017-08-01T21:36:30.797

Nice to see fans of ASM. – Billal Begueradj – 2017-08-04T06:07:44.850

You could do it with three 32 pixel wide tiles iterating over all the rows. It uses more data, but saves in the number of operations. Alternatively, you could use three 16 pixel wide tiles for the left side and perform a symetrical operation by reversing the left side. – ATL_DEV – 2017-08-04T12:42:21.903

21

MATL, 29 bytes

2Y66t&Y"OJQht3$)6thYaQK7hBoYG

Try it at MATL Online!

Explanation

2Y6     % Push predefined literal: 3×3 matrix [0 1 0; 1 1 1; 0 1 0]
6t&Y"   % Repeat each entry 6 times in the two dimensions. Gives an 18×18 matrix
OJQh    % Push [0 1j+1]. Used as an index, this means [0 1 ... end+1]. Indexing
        % is 1-based and modular, so 0 is the same as end
t3$)    % Apply that index in the two dimensions. This extends by 1 entry in 
        % each dimension, so that the arms have length 7. Gives a 20×20 matrix
6thYa   % Pad with 6 zeros in the two dimensions. Gives a 32×32 matrix
Q       % Add 1. The matrix now contains values 1 (will become red) and 2 (white)
K7hBo   % Convert array [4 7] to binary. Gives [1 0 0; 1 1 1], to be used as
        % colormap. First row is red, second is white
YG      % Show image using colormap

Luis Mendo

Posted 2017-07-31T22:23:49.970

Reputation: 87 464

17

Java 8, 246 + 42 = 288 bytes

Thanks to @Aaron for -64 bytes.
-4 bytes by outputting to file a without extension.

import java.awt.*;import java.awt.image.*;
x->{BufferedImage i=new BufferedImage(32,32,1);Graphics g=i.getGraphics();g.setColor(Color.RED);g.fillRect(0,0,32,32);g.setColor(Color.WHITE);g.fillRect(13,6,6,20);g.fillRect(6,13,20,6);javax.imageio.ImageIO.write(i,"png",new java.io.File("a"));}

A lamba expression that can be assigned to a functional interface method that throws an exception. Creates an image file named a (an image file) in the directory running this file.

Surrounding code used to run it: Try it online!

Ungolfed

x->{
    BufferedImage i=new BufferedImage(32,32,1);
    Graphics g=i.getGraphics();
    g.setColor(Color.RED);
    g.fillRect(0,0,32,32);
    g.setColor(Color.WHITE);
    g.fillRect(13,6,6,20);
    g.fillRect(6,13,20,6);
    javax.imageio.ImageIO.write(i,"png",new java.io.File("a"));
}

Result

Grid provided by the IntelliJ IDEA image preview (apparently).

Justin Mariner

Posted 2017-07-31T22:23:49.970

Reputation: 4 746

You can shave quite a few bytes by changing your fillPolygon call into two fillRect calls. I'm not sure I respected the dimensions but I came up with g.fillRect(7,13,18,6);g.fillRect(13,7,6,18) which is shorter by 64 bytes – Aaron – 2017-08-01T14:28:57.993

@Aaron Good call, for some reason I thought that'd be longer... Thanks! – Justin Mariner – 2017-08-01T21:15:29.607

You could name the file .png instead of a.png and save a byte. – user2428118 – 2017-08-02T09:55:48.093

@user2428118 Nice, would it be allowed to take it further and just name it a, without an extension? It can still be opened, just needs to be told to open in a photo viewer. – Justin Mariner – 2017-08-02T10:17:53.040

I don't know. The meta post regarding acceptable output formats for graphical output doesn't seem to rule it out, but I don't recall seeing it it being done in practice either. (I haven't been very active on PPCG lately though.)

– user2428118 – 2017-08-02T10:41:39.603

@JustinMariner Yes, you may. Also, since you create a file image, wouldn't it be shorter to output svg directly? java.nio.file.Files.write(java.nio.file.Paths.get("a");"<svg...>".getBytes()) – Olivier Grégoire – 2017-08-02T14:01:19.383

1@OlivierGrégoire I feel that's too far from the idea of my solution, but you're welcome to post that as your own – Justin Mariner – 2017-08-02T14:20:03.273

216 + 18 bytes, using AWT: import java.awt.*;()->{new Frame(){{setSize(32,32);add(new Panel(){public void paint(Graphics g){g.setColor(Color.RED);g.fillRect(0,0,32,32);g.setColor(Color.WHITE);g.fillRect(13,6,6,20);g.fillRect(6,13,20,6);}});setVisible(true);}};} (Be aware, SE adds invisible splitting characters, so this answer is actually of the size I mentioned.) – Olivier Grégoire – 2017-08-02T14:32:16.080

Hmmm... Use setSize(99,99) instead of setSize(32,32). Somehow it doesn't show up properly on Windows. – Olivier Grégoire – 2017-08-02T14:37:17.977

Java can do method references, right? Would you be able to use them to save on typing setColor and fillRect? – n0rd – 2017-08-02T22:03:24.000

@OlivierGrégoire I'm just gonna stick to image file output. @n0rd That would require creating Consumer<Color>c=g::setColor;, which adds too many bytes. And for fillRect: there's no builtin object (afaik) that accepts 4 args. Great idea, though; I've never considered used method refs in that way. – Justin Mariner – 2017-08-02T22:12:37.840

16

Excel VBA, 86 85 79 Bytes

Code

Anonymous VBE immediate window function that takes no input and outputs the Swiss flag onto the range [A1:F32] of the ActiveSheet object. This works by first making the cells square, then drawing the red region and finally drawing in the white cross.

Cells.RowHeight=48:[A1:AF32].Interior.Color=255:[G14:Z19,N7:S26].Interior.Color=-1

Note that arrangements which that remove the step of coloring the "cross" of the Swiss flag after putting in the red background are actually longer than the above configuration, as they require at least 16 cell addresses, which coordinate to the 8 distinct regions of the flag

-1 Byte thanks to @Greedo's for RowHeight=48 over ColumnWidth=2

-6 Bytes thanks to @Greedo's for -1 instead rgbWhite

Output

enter image description here

Taylor Scott

Posted 2017-07-31T22:23:49.970

Reputation: 6 709

1Fantastic; but you can still save 6 bytes with Interior.Color=-1 instead of Interior.Color=rgbWhite – Greedo – 2017-08-03T09:48:03.487

@Greedo, huh, what do you know - that's fantastic. I had used rgbWhite over its decimal value of 16777215 for clarity, I had no idea that -1 would have the same effect. Thanks! – Taylor Scott – 2017-08-03T11:43:07.980

1

according to this link: (https://www.reddit.com/r/compsci/comments/62x9g9/powerpoint_is_turing_complete/) PowerPoint is Turing complete so I wonder how could this be ported to PowerPoint

– Suhrid Mulay – 2017-10-29T15:22:24.547

13

C++, SFML, 406 399 394 bytes

-2 bytes thanks to pdpi
-10 bytes thanks to Zacharý

SFML ( Simple and Fast Multimedia Library ) is a C++ library written to ease the developpement of video games and multimedia programs

The code :

#include<SFML\Graphics.hpp>
using namespace sf;int main(){for(RenderWindow t(VideoMode(128,128),"");t.isOpen();){t.clear();RectangleShape r({128.f,128.f});r.setFillColor(Color::Red);t.draw(r);r.setFillColor(Color::White);r.setPosition({24.f,52.f});r.setSize({80.f,24.f});t.draw(r);r.rotate(90);r.setPosition({76.f,24.f});t.draw(r);t.display();for(Event e;t.pollEvent(e);)if(!e.type)t.close();}}

The flag get displayed in a 128x128 window. Your OS have to be able to display a 128x128 window ( my Win8.1 can't display with smaller width )

WARNING : you may want to add these 2 lines of code : t.setFramerateLimit(60);t.setVerticalSyncEnabled(true);, so your CPU won't heat when you run the code. I did not put them in the original code for golfing reasons.

HatsuPointerKun

Posted 2017-07-31T22:23:49.970

Reputation: 1 891

You can shrink this a bit by replacing your whiles with fors, and initialising t and e in there:

int main(){for(sf::RenderWindow t(sf::VideoMode(128,128),"");t.isOpen();){t.clear();sf::RectangleShape r({128.f,128.f});r.setFillColor(sf::Color::Red);t.draw(r);r.setFillColor(sf::Color::White);r.setPosition({24.f,52.f});r.setSize({80.f,24.f});t.draw(r);r.rotate(90);r.setPosition({76.f,24.f });t.draw(r);t.display();for(sf::Event e;t.pollEvent(e);)if(e.type == 0)t.close();}} – pdpi – 2017-08-01T12:23:33.093

Also, you can save two bytes by removing spaces: e.type == 0 => e.type==0, maybe even !e.type (don't remember the precedence). 24.f } => 24.f} – Zacharý – 2017-08-01T12:25:59.787

Oh, and is using namespace sf; possible? – Zacharý – 2017-08-01T13:42:09.917

12

Braindraw, 227 bytes (Non-competing) (Updated to actually work)

Ungolfed version (241 bytes)

r<<^++++++++[-^++++v]^[->>[>]>++++++++[-<++++>]<[<]<]>>[[-vv[v]-[^]^]>]vv<[<]>>>>>>>>>>>>>>vvvvvvg<<^^++++++[->>[>]>+++++[-<++++>]<[<]<]>>[[-vv[v]b-g-[^]^]>]<vv[<]><<<<<<<vvvvvvv<<^^++++++[-vv[v]++++++++++++++[^]^]vv[[->>[>]b[+]-g[+]-[<]<]v]

Lightly golfed version (227 bytes)

r<<^++++++++[-^++++v]^[->>[>]>++++++++[-<++++>]<[<]<]>>[[-vv[v]-[^]^]>]vv<[<]g>>>>>>>>>>>>vvvv++++++[->>[>]>+++++[-<++++>]<[<]<]>>[[-vv[v]b-g-[^]^]>]<vv[<]<<<<<<vvvvv<<++++++[-vv[v]++++++++++++++[^]^]vv[[->>[>]b[+]-g[+]-[<]<]v]

Braindraw is a programming language of my own design. As of 3:08 pm today, I do have a working interpreter and have checked that the program runs properly. However, the interpreter did not exist before this competition began, so I am not competing.

Braindraw is the same as Brainf***, except that it operates on three two-dimensional arrays, rather than one one-dimensional array. These arrays are called r, g, and b, and act as the red green and blue color channels. The operator r moves the pointer to the red channel, etc etc. Up is ^, down is v.

benzene

Posted 2017-07-31T22:23:49.970

Reputation: 257

9Looking forward to seeing an interpreter for this, could be fun to try out – Darren H – 2017-08-01T08:07:06.183

1It certainly a fun idea, I'm looking forward to an interpreter too! (Technically we only allow languages that have been implemented, and we consider the interpreter as their definition.) – flawr – 2017-08-01T08:26:31.567

Is it correct that you do not explicitly output anything, but just output the whole "canvas" in the end? Do you assume the canvas is infinite? – flawr – 2017-08-01T08:29:42.557

In re: no interpreter, I guess that means my entry is non-competing. Oh well. But yes, this program has no output per se, the computing space is displayed while and after the program is run. The canvas is theoretically infinite, but in implementation, I will probably just make it some large-ish fixed width like maybe 512x512 – benzene – 2017-08-01T14:36:22.797

This language seems capable of kolmogorov complexity image challenges. And are you currently working on an interpreter? – Zacharý – 2017-08-01T14:51:53.757

https://esolangs.org/wiki/Graphical_Brainfuck appears to be basically the same, though it laks an interpreter too. – Laikoni – 2017-08-01T15:45:51.653

@Zacharý I am working on an interpreter, but it's not going to be very good :P – benzene – 2017-08-01T15:56:52.090

@benzene I made a fist draft of an interpreter, but it doesn't work for your program. Do you have the specs written down somewhere or do you see some points I did not interpret correctly?

– flawr – 2017-08-01T16:56:49.857

@flawr It looks like you're using integers for the cell values, where I was envisioning bytes that wrap around, so the program r- should draw one pixel with the color #FF0000 – benzene – 2017-08-01T17:00:41.263

@ flawr Actually, it looks like something is not working with either the - operator or the brackets, since when I run the program +++++[->+++++<], the output should only have one non-black pixel, but when I run it on your interpreter I see two. – benzene – 2017-08-01T17:20:12.010

@flawr So I finished my (shabby) interpreter, and the Braindraw program did have several bugs, but it should work now. – benzene – 2017-08-01T19:20:40.583

Does this apply? – TehPers – 2017-08-02T01:08:15.690

@TehPers, yes, but as @benzene already stated in the body of their answer, their answer is non-competing. That said, they should include (Non-Competing) in the header of their answer – Taylor Scott – 2017-08-02T21:14:55.943

I made one – Confuse – 2017-08-03T14:14:42.100

@Benzene Several things: (1) Does the interpreter start by pointing to a specific channel such as red? (2) What is the output region? Do you treat a specific corner as (0,0) and ignore pixels with negative row/column index? (3) Would you add more language features e.g. dot "." for input, and "a" for pointing to alpha channel? (4) Can a command line argument be passed so that the output is automatically filled with a "background colour"? It would be very interesting if this language can be used in other challenges ;) – tonychow0929 – 2017-08-05T05:12:59.807

tony200910041 (1) In my interpreter, red is default, but Braindraw style says to always specify channel. (2) All pixels are displayed after runtime, but Braindraw also retains "." and "," from Brainf***. I treat the upper right corner as (0, 0), and treat the edges of the canvas as hard walls, but I could make the canvas expand with the pointer or wrap around etc. (3) I might, but I think features like "a" and would make the language more pragmatic than I want. (4) No, you have to do that manually. I'm planning to use Braindraw for other challenges, but haven't gotten around to it yet. – benzene – 2017-08-05T14:43:22.343

I wrote an interpreter in Python (https://jonathanfrech.wordpress.com/2017/08/26/brainfuck-x/), which allows for a dynamically growing tape. Although I implemented calling the color planes by their names rgb, I thought it was too readable, which lead me to implement one character * to cycle through the color planes, starting with the red one.

– Jonathan Frech – 2017-08-26T10:14:36.107

10

Mathematica, 83 bytes

R=Rectangle;Graphics[{Red,{0,0}~R~{32,32},White,{6,13}~R~{26,19},{13,6}~R~{19,26}}]

next one is from @ASCII-only (I thought it was a joke but it works!)

Mathematica, 23 bytes

"CH"~CountryData~"Flag"

-10 bytes from @Jonathan Frech

J42161217

Posted 2017-07-31T22:23:49.970

Reputation: 15 931

4Mathematica doesn't have a built-in for the Swiss flag? – CJ Dennis – 2017-08-01T00:47:04.780

my bad..I thought built-ins were not allowed! – J42161217 – 2017-08-01T00:48:47.997

4CountryData["Switzerland","Flag"] but it might not have the right proportions – ASCII-only – 2017-08-01T00:49:14.283

looks perfect!!!! – J42161217 – 2017-08-01T00:58:53.723

6Mathematica has a built-in for everything, but this? – sergiol – 2017-08-01T07:39:54.497

10"Switzerland"~CountryData~"Flag" saves you some more – A Simmons – 2017-08-01T13:51:10.733

1"CH"~CountryData~"Flag" only takes 23 bytes. – Jonathan Frech – 2017-08-24T21:47:06.457

@JonathanFrech cool! – J42161217 – 2017-08-24T21:49:37.303

10

TI-BASIC (TI-84 Plus C(S)E only), 58 bytes

:For(A,0,31
:For(B,0,31
:Pxl-On(A,B,RED
:End
:End
:For(A,6,25
:For(B,13,18
:Pxl-Off(A,B
:Pxl-Off(B,A
:End
:End

Scott Milner

Posted 2017-07-31T22:23:49.970

Reputation: 1 806

This is an awesome answer. I just made an account to upvote it. TI-BASIC is great – Zags – 2017-08-03T12:17:33.467

1Oh what a deluxe third parameter Pxl-On has now... it makes me cry only having had monochrome :( – Ray – 2017-08-05T15:12:33.410

9

HTML + CSS, 15 + 117 bytes = 132 bytes

Using a flexbox wrapper with an inset box-shadow.

b{display:flex;box-shadow:red 0 0 0 6px inset;padding:2px;width:28px;flex-wrap:wrap}a{border:solid red 4px;margin:3px
<b><a><a><a><a>


HTML + CSS, 18 + 139 137 122 bytes = 140 bytes

Previous answer using border and an intermediate flexbox wrapper with negative margin.

i,b,a{display:inline-flex}i{border:solid red 6px}b{margin:-4px;width:28px;flex-wrap:wrap}a{border:solid red 4px;margin:3px
<i><b><a><a><a><a>

darrylyeo

Posted 2017-07-31T22:23:49.970

Reputation: 6 214

7

JavaScript + HTML, 99 + 13 = 112 bytes

Saved 2 bytes thanks to user2428118
Saved 2 bytes thanks to Matheus Avellar

JSFiddle

with(c.getContext`2d`)fillStyle='red',fillRect(0,0,32,32),clearRect(6,13,20,6),clearRect(13,6,6,20)
<canvas id=c>

Pure JavaScript, 194 129 bytes

JSFiddle

with(document.write`<canvas id=c>`,c.getContext`2d`)fillStyle='red',fillRect(0,0,32,32),clearRect(6,13,20,6),clearRect(13,6,6,20)

user72349

Posted 2017-07-31T22:23:49.970

Reputation:

2I believe you have to do this from scratch. – Stephen – 2017-07-31T22:45:36.067

@StepHen. Ok, I added it too. – None – 2017-07-31T22:50:47.947

1... You need to include it in the bytecount – ASCII-only – 2017-08-01T00:48:21.443

@ASCII-only. Included. – None – 2017-08-01T00:54:36.740

1

For future reference, whenever you need a <canvas> you can include the HTML directly in your answer. See https://codegolf.stackexchange.com/a/136972/47097

– darrylyeo – 2017-08-01T02:03:54.313

You can change c.getContext('2d') to c.getContext`2d` – user2428118 – 2017-08-01T09:10:26.313

@user2428118. Oh, of course, thanks. I somehow forget that getContext is a native function. – None – 2017-08-01T11:42:24.200

Sorry if I wasn't clear - you'll have to include the HTML as part of the byte count as well. – darrylyeo – 2017-08-01T18:04:44.610

@darrylyeo. I left my pure JavaScript answer (but included document.write part), but I also added JavaScript + HTML answer. However, I still feel uncomfortable with PPCG snippets because if someone want to try to improve the code, they need to copy it to some testing environment which discourages lazy people. JSFiddle links are much better, because everyone can easily edit it and test other approaches. – None – 2017-08-01T21:35:26.097

You know Stack Snippets exist right? Then people can copy with one button – ASCII-only – 2017-08-01T21:48:42.913

@ASCII-only. Well, if code snippets are so favorized here, no problem. I just included it, hope it is better now :) – None – 2017-08-01T21:54:52.003

@ThePirateBay Thanks a lot! – ASCII-only – 2017-08-01T23:49:55.637

It is techincally valid HTML5 to omit the quotation marks on element attributes, so you could cut off 2 bytes by doing <canvas id=c>, both on the JS + HTML answers as well as on the JS-only one

– Matheus Avellar – 2017-08-04T02:28:48.660

7

GraphicsMagick (?), 96 bytes

gm convert -size 32x32 xc:red -fill #fff -draw "rectangle 13,6 18,25 rectangle 6,13 25,18" 1.bmp

Not sure how to golf with GM (should this be considered as a language?). Also not sure how to count bytes here...

With GM installed, type the given code in windows cmd, you will get an image with name 1.bmp. You may want change double quote to single quote if you are using bash (it should work, but i had not tested this).

Thanks to Digital Trauma. use only one -draw save 8 bytes

tsh

Posted 2017-07-31T22:23:49.970

Reputation: 13 072

Not sure if its the same in GraphicsMagick, but with ImageMagick you can put both rectangles in the same -draw string: convert -size 32x32 xc:red -fill white -draw "rectangle 13,6 18,25 rectangle 6,13 25,18" i.png – Digital Trauma – 2017-08-02T17:14:57.933

@DigitalTrauma it is same. edited. – tsh – 2017-08-03T02:37:59.360

6

JavaScript (ES6) in HTML4(?), 178 176 bytes

document.write('<table cellspacing=0>'+[...Array(32)].map((_,y,p)=>p.map((_,x)=>`<td bgcolor=${x>5&&x<26&&y>12&&y<19||y>5&&y<26&&x>12&&x<19?'#fff':'red'}>`).join``).join`<tr>`)

Yes! We do not need <canvas> nor <svg> or even <img>!

Thanks to Justin Mariner, save 2 bytes.

tsh

Posted 2017-07-31T22:23:49.970

Reputation: 13 072

5

Löve2D, 139 138 Bytes

l=love g=l.graphics c=g.setColor r=g.rectangle f="fill"w=255 l.draw=loadstring"c(w,0,0)r(f,0,0,32,32)c(w,w,w)r(f,13,6,6,20)r(f,6,13,20,6)"

Saved one byte thanks to ThePirateBay

Ungolfed

function love.draw()
    love.graphics.setColor(255,0,0)
    love.graphics.rectangle("fill",0,0,32,32)
    love.graphics.setColor(255,255,255)
    love.graphics.rectangle("fill",13,6,6,20)
    love.graphics.rectangle("fill",6,13,20,6)
end

ATaco

Posted 2017-07-31T22:23:49.970

Reputation: 7 898

5

GIF, 97 Bytes

GIF87a    ð  ÿ  ÿÿÿ,         @„©Ëí£œ´Ú;ƒÞXmÞ!ŸŠcyŒj¨,àZê<Cô
:8nïtï‹é‚BJ1tì$1ËKSvb=_ÔªõŠe  ;

Cheap and byte-heavy, but worth it.

EDIT: Some characters aren't in the code above, here's a pastebin for the GIF's hexdump.

EDIT: compressed down to 97 bytes with online tool.

Adrian Zhang

Posted 2017-07-31T22:23:49.970

Reputation: 199

1It seems that some unprintable characters were removed from your code snippet. Maybe try posting a hex dump. – None – 2017-08-01T01:49:42.213

18How do you pronounce the language? – Oliver – 2017-08-01T16:16:01.933

1

@Oliver ZHAIF

– Neil – 2017-08-01T17:22:11.947

1

Gimp produces a GIF file that looks identical in only 95 bytes (less than many other solutions). Here's a hex dump of it.

– Armin Rigo – 2017-08-01T22:39:05.930

Funny. I used Pelles-C, which is probably suboptimal. – Adrian Zhang – 2017-08-01T23:21:48.980

6Since when is GIF a programming language? – Adám – 2017-08-02T08:44:43.713

1

Please everyone note that we allow non-programming-language submissions as per this consensus, so this submission is perfectly fine. (And IMO a nice benchmark to have.)

– flawr – 2017-08-03T09:58:20.520

5

GFA BASIC (Atari ST), 62 bytes

A manually edited listing in .LST format. All lines end with CR, including the last one.

DEFFILL2
PBOX0,0,31,31
DEFFILL0
PBOX13,6,18,25
PBOX6,13,25,18

Expanded and commented:

DEFFILL 2         ! set fill color: default system color #2 is red (&H700)
PBOX 0,0,31,31    ! draw the red square
DEFFILL 0         ! set fill color: default system color #0 is white (&H777)
PBOX 13,6,18,25   ! draw a vertical white rectangle
PBOX 6,13,25,18   ! draw a horizontal white rectangle

Output

The output is 32x32.

GFA output

NB: This is indeed using the 'white' color, although it's gray-looking on the emulator (and on the real thing as well, unless you turn the brightness quite high).

Arnauld

Posted 2017-07-31T22:23:49.970

Reputation: 111 334

5

Octave, 105 bytes 73 bytes

Note: line feeds added for clarity, not included in byte count

x(32,32,3)=0;
x(:,:,1)=1;
x(7:26,14:19,:)=1;
x(14:19,7:26,:)=1;
imshow(x*255)

EDIT: thanks to flawr for saving quite a lot of bytes!

Here is the result on octave-online.net, thanks to sanchises

Results

bracco23

Posted 2017-07-31T22:23:49.970

Reputation: 151

I'm not sure about Octave, but in MATLAB following should work: x(32,32,3)=0; x(:,:,1)=1; x(7:26,14:19,:)=1; x(14:19,7:26,:)=1; imshow(x*255) – flawr – 2017-08-01T15:53:25.507

BTW: Welcome to PPCG!!! – flawr – 2017-08-01T15:54:23.000

Octave-online.net does show pictures. – Sanchises – 2017-08-01T18:43:47.090

5

Python 3, 190 bytes

Save output as image.xpm and open with your favorite text editor.

r=range;print('! XPM2\n32 32 2 1\nr c #FF0000\nw c #FFFFFF\n');d=[bytearray(b'r'*32)for _ in r(32)]
for i in r(20):
 for j in r(6):d[i+6][j+13]=d[j+13][i+6]=119
print(b'\n'.join(d).decode())

Try it online!

Output:

! XPM2
32 32 2 1
r c #FF0000
w c #FFFFFF

rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
rrrrrrrrrrrrrwwwwwwrrrrrrrrrrrrr
rrrrrrrrrrrrrwwwwwwrrrrrrrrrrrrr
rrrrrrrrrrrrrwwwwwwrrrrrrrrrrrrr
rrrrrrrrrrrrrwwwwwwrrrrrrrrrrrrr
rrrrrrrrrrrrrwwwwwwrrrrrrrrrrrrr
rrrrrrrrrrrrrwwwwwwrrrrrrrrrrrrr
rrrrrrrrrrrrrwwwwwwrrrrrrrrrrrrr
rrrrrrwwwwwwwwwwwwwwwwwwwwrrrrrr
rrrrrrwwwwwwwwwwwwwwwwwwwwrrrrrr
rrrrrrwwwwwwwwwwwwwwwwwwwwrrrrrr
rrrrrrwwwwwwwwwwwwwwwwwwwwrrrrrr
rrrrrrwwwwwwwwwwwwwwwwwwwwrrrrrr
rrrrrrwwwwwwwwwwwwwwwwwwwwrrrrrr
rrrrrrrrrrrrrwwwwwwrrrrrrrrrrrrr
rrrrrrrrrrrrrwwwwwwrrrrrrrrrrrrr
rrrrrrrrrrrrrwwwwwwrrrrrrrrrrrrr
rrrrrrrrrrrrrwwwwwwrrrrrrrrrrrrr
rrrrrrrrrrrrrwwwwwwrrrrrrrrrrrrr
rrrrrrrrrrrrrwwwwwwrrrrrrrrrrrrr
rrrrrrrrrrrrrwwwwwwrrrrrrrrrrrrr
rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr

Andrew Dunai

Posted 2017-07-31T22:23:49.970

Reputation: 321

I had to remove the empty 5th line to open it with gimp on linux. – Tim – 2017-08-05T07:16:05.177

5

Perl 5, 184 bytes

176 bytes code + 8 for -Mutf8 -p.

I'm not entirely sure this is as required, it relies on empty input being supplied as per this meta post, which doesn't work on TIO so it supplies a new line (which is not used). Output is to the terminal and looks like this:

enter image description here

Proportions should be to scale based on one character space being two vertical 'pixels'.

%a=qw(R 101 W 107 A 101;97 B 91;107);$_=R.($a="32 
"x3).($b="13 W6 R13 
"x3)."6 A7▄W6 A7▄"."R6 
6 W20 "x2 ."R6 
6 B7▄W6 B7▄R6 
$b$a";s/\d+(.)/$1x$&/ge;s/\pL/[$a{$&}m/g

Try it online!

You can preview the output by copying from TIO and pasting in here (this shows the control characters when hovered over the element).

Dom Hastings

Posted 2017-07-31T22:23:49.970

Reputation: 16 415

5

R, 171 140 bytes.

x = rep(c(6,13,19,26,19,13),e=2)
l=c(0,32)
par(bg="red",mar=0*1:4)
plot(0,0,'n',l,l,xaxs="i",yaxs="i")
polygon(x,c(x,x)[4:15],c="white",b=0)

(somewhat) ungolfed:

x <- rep(c(6,13,19,26,19,13),each=2)
y <- c(x,x)[4:15] # index by 3 positions
par(bg="red",mar=c(0,0,0,0)) # prepare the plot space
plot(0,type='n', xaxs="i",yaxs="i",xlim=c(0,32),ylim=c(0,32))
polygon(x,y,col="white",border=0)

Thanks to @gregor for saving some bytes

Run it!

Alex Axthelm

Posted 2017-07-31T22:23:49.970

Reputation: 61

1Welcome to the site! :) – James – 2017-08-01T17:50:38.860

Nice! You can save quite a few bytes with partial matching of argument names: e=2 instead of each=2, t instead of type, c for col, b for border. And 0*1:4 is shorter than c(0,0,0,0). – Gregor Thomas – 2017-08-01T18:00:50.530

Actually you can get away with positional matching on plot: plot(0,0,'n',l,l,xaxs="i",yaxs="i") (assigning m="i" actually costs you one byte). With all of that it gets down to 141 bytes. – Gregor Thomas – 2017-08-01T18:06:39.827

I forgot entirely about partial matching. Thanks! – Alex Axthelm – 2017-08-01T20:46:38.047

Couple more bytes off: l and the xlim/ylim aren't needed, just plot(0:32,0:32,...). I also adapted your approach and got it down to 117 here, using rect instead of polygon.

– Gregor Thomas – 2017-08-01T22:41:20.170

2 can replace "red" in bg. If the exact RGB of the white wasn't specified you could have saved an extra byte with the visually indistinct "snow" (255,250,250). – Jonathan Carroll – 2017-08-04T05:26:14.997

4

HTML + JavaScript (ES6), 13 + 112 = 125 bytes

C=c.getContext`2d`
C[s='fillStyle']='red'
C[r='fillRect'](0,0,32,32)
C[s]='#fff'
C[r](6,13,20,6)
C[r](13,6,6,20)
<canvas id=c>

HTML + JavaScript (ES6), 13 + 114 = 127 bytes

with(c.getContext`2d`)fillStyle='red',fillRect(0,0,32,32),fillStyle='#fff',fillRect(6,13,20,6),fillRect(13,6,6,20)
<canvas id=c>

darrylyeo

Posted 2017-07-31T22:23:49.970

Reputation: 6 214

I've stolen your rectangle approach and improved it to 117 bytes using clearRect, I hope you're ok with that? – None – 2017-08-01T21:51:03.113

That's clever, but unfortunately the OP says transparent pixels aren't allowed. https://codegolf.stackexchange.com/questions/136927/draw-the-swiss-flag/136972?noredirect=1#comment335362_136927

– darrylyeo – 2017-08-02T04:30:01.000

Actually, it is white. By default, all webpages have white background and the flag is transparent itself, but it is just an internal definition of transparency. External definition of transparency would be if pixels in that region (white plus) may change its color in some conditions (or may be set randomly). However, because I'm using both HTML and JavaScript, the whole output is the red flag with white cross. You cannot consider the canvas and background separately. How canvas is displayed on the background is well defined and the result always contains white cross by spec definitions. – None – 2017-08-02T09:41:28.427

I hope its a bit more clear now, I mean you may disagree, but if you really think about it I am sure you'll find my answer fully consistent with OP's requirements. – None – 2017-08-02T09:42:32.643

@ThePirateBay Fair enough. – darrylyeo – 2017-08-02T17:47:20.090

4

Postscript, 301 286 187 bytes

/m{moveto}def
/s{setrgbcolor}def
/r{rlineto}def
/c{closepath fill}def
1 0 0 s
0 0 m
0 320 r
320 0 r
0 -320 r
c
1 1 1 s
130 60 m
60 0 r
0 200 r
-60 0 r
c
60 130 m
0 60 r
200 0 r
0 -60 r c

Thanks to the anonymous editor who suggested a 99 byte reduction!

ceilingcat

Posted 2017-07-31T22:23:49.970

Reputation: 5 503

Just to let you know: somebody submitted a golfing edit to this post. Per our policy, it was rejected, but you may want to consider implementing some of the changes. – Rɪᴋᴇʀ – 2017-08-03T19:09:59.160

4

C# 265/266 209 bytes

 using System;using c=System.Console;class P{static void Main(){for(int i=0,j;i<32;i++){for(j=0;j<32;j++){if((6<i&&i<26&&j>13&&j<19)||(6<j&&j<26&&i>13&&i<19))c.BackgroundColor=ConsoleColor.White;else c.BackgroundColor=ConsoleColor.Red;c.Write(" ");}c.WriteLine();}}}     

I wrote "space" characters into console while changing Background Color. But if you think it is too tall and you count single character as 8 x 16 pixels, you simply double values near "j" like this (+ 1 byte and + c.ReadKey(); so it stops):

  using System;using c=System.Console;class P{static void Main(){for(int i=0,j;i<32;i++){for(j=0;j<64;j++){if((6<i&&i<26&&j>26&&j<38)||(12<j&&j<52&&i>13&&i<19))c.BackgroundColor=ConsoleColor.White;else c.BackgroundColor=ConsoleColor.Red;c.Write(" ");}c.WriteLine();} c.ReadKey(); }}     

56 bytes saved thanks to TheLethalCoder

 namespace System{using static Console;class P{static void Main(){for(int i=0,j;i<32;i++,WriteLine())for(j=0;j<32;Write(""))BackgroundColor=(ConsoleColor)((6<i&i<26&j>13&j<19)|(j++<26&i>13&i<19&6<j​)?15:12);}}}

Jan Ivan

Posted 2017-07-31T22:23:49.970

Reputation: 169

209 bytes namespace System{using static Console;class P{static void Main(){for(int i=0,j;i<32;i++,WriteLine())for(j=0;j<32;Write(" "))BackgroundColor=(ConsoleColor)((6<i&i<26&j>13&j<19)|(6<j&j++<26&i>13&i<19)?15:12);}}} – TheLethalCoder – 2017-08-01T09:34:54.527

4

Tikz, 145 143 bytes

\documentclass[tikz]{standalone}\begin{document}\tikz{\def~{)rectangle(}\fill[red](,~33,33);\fill[white](7,14~27,20)(14,7~20,27)}\end{document}

Here it is "ungolfed"

\documentclass[tikz]{standalone}
\begin{document}
\tikz{
\def~{)rectangle(}
  \fill[red](,~33,33);
  \fill[white](7,14~27,20)(14,7~20,27)
}\end{document}

Here it is ungolfed a little more

\documentclass[tikz]{standalone}
\begin{document}
\tikz{
  \fill[red](1,1)rectangle(33,33);
  \fill[white](7,14)rectangle(27,20)(14,7)rectangle(20,27)
}\end{document}

This makes 3 rectangles a big red one and two smaller white ones for the plus.

Here's what it looks like. It doesn't really look any different than the others.

flag

Post Rock Garf Hunter

Posted 2017-07-31T22:23:49.970

Reputation: 55 382

I put a golfing documentclass on github a few weeks ago. and there doesn't seem to be any window background requirement. With that \documentclass{g}\input tikz should work to save 5B. You can probably save more by working in plain TeX, even with TikZ

– Chris H – 2017-08-01T15:35:01.753

4

R, 112 bytes

par(bg=2,mar=0*1:4)
plot(0:32,0:32,'n',xaxs="i",yaxs="i")
rect(c(6,13),c(13,6),c(26,19),c(19,26),c="white",b=NA)

Though, to guarantee the aspect ratio, we need 5 more bytes for a total of 117:

par(bg=2,mar=0*1:4)
plot(0:32,0:32,'n',xaxs="i",yaxs="i",as=1)
rect(c(6,13),c(13,6),c(26,19),c(19,26),c="white",b=NA)

With lots of inspiration from Alex Axthelm's answer, and thanks to Rift for saving a few more bytes.

Gregor Thomas

Posted 2017-07-31T22:23:49.970

Reputation: 271

3you could save 4 bytes changing bg="red" to bg=2 which is the same in the default palette – Rift – 2017-08-02T08:22:56.173

4

R, 109 bytes

par(mar=0*1:4,bg=2,xaxs="i",yaxs="i")
frame()
rect(a<-c(6,13)/32,rev(a),b<-c(26,19)/32,rev(b),c="white",b=NA)

Uses frame to avoid presetting a plot, but default plotting region is on interval [0,1] instead of [0,32]. Also uses the fact that rect is vectorized. The default size of the plotting window is 7in x 7in. It outputs the following:

Swiss flag in plotting window

R, 125 bytes

png()
par(mar=0*1:4,bg=2,xaxs="i",yaxs="i")
frame()
rect(a<-c(6,13)/32,rev(a),b<-c(26,19)/32,rev(b),c="white",b=NA)
dev.off()

Default for png is a square of 480x480 pixels. Output is the following png file:

Swiss flag

plannapus

Posted 2017-07-31T22:23:49.970

Reputation: 8 610

3

Bitmap, 160 bytes

Here's a bitmap with 1-bit colour depth, using a 24-bit colour definition. The last six bytes of the second line is the palette and following that is the pixel array. Every four bytes contains a whole row of pixels.

42 4D A0 00 00 00 00 00 00 00 20 00 00 00 0C 00
00 00 20 00 20 00 01 00 01 00 00 00 FF FF FF FF
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 07 E0 00 00 07 E0 00
00 07 E0 00 00 07 E0 00 00 07 E0 00 00 07 E0 00
00 07 E0 00 03 FF FF C0 03 FF FF C0 03 FF FF C0
03 FF FF C0 03 FF FF C0 03 FF FF C0 00 07 E0 00
00 07 E0 00 00 07 E0 00 00 07 E0 00 00 07 E0 00
00 07 E0 00 00 07 E0 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

I tried to truncate the trailing zeroes, but image viewers require there are enough pixels defined for the entire canvas.

Swiss.bmp

Hand-E-Food

Posted 2017-07-31T22:23:49.970

Reputation: 7 912

3"Any suggestions where I can save arbitrary files permanently?" - on GitHub. – None – 2017-08-01T06:31:12.073

1Can you use RLE encoding? – Neil – 2017-08-01T17:24:26.807

1Haha, you've 1up'd my GIF example. – Adrian Zhang – 2017-08-01T22:05:40.830

Maybe just convert it to base64 and show it with an HTML snippet? <img src="data:image/bmp;base64,Qk2gAAAAAAAAACAAAAAMAAAAIAAgAAEAAQAAAP////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB+AAAAfgAAAH4AAAB+AAAAfgAAAH4AAAB+AAA///wAP//8AD///AA///wAP//8AD///AAAfgAAAH4AAAB+AAAAfgAAAH4AAAB+AAAAfgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==" /> – tsh – 2017-08-02T01:52:26.767

1I think this is not a valid programming language. IFAICT, BMP can neither check primeness, nor add numbers. – Adám – 2017-08-02T08:46:09.427

1I checked and RLE encoding doesn't help for a file this small; if the image was twice as big you'd start seeing savings though. – Neil – 2017-08-02T13:01:13.070

@Adám, thanks! After posting this, I actually wondered what constituted a valid language. I figured this was code that is compiled into pixels. But something closer to Turing-complete makes more sense. Either way, even if it's non-competing, I still wanted to try this method. – Hand-E-Food – 2017-08-03T00:32:43.897

3

Please everyone note that we allow non-programming-language submissions as per this consensus, so this submission is perfectly fine. (And IMO a nice benchmark to have.)

– flawr – 2017-08-03T09:56:51.560

3

Tcl/Tk, 94

If it runs on the interactive shell, one can abbreviate canvas to can and grid to gri

gri [can .c -bg red -w 32 -he 32]
lmap R {{8 15 28 21} {15 8 21 28}} {.c cr r $R -f #FFF -w 0}

Tcl/Tk, 98

If it runs on the interactive shell, one can abbreviate canvas to can

grid [can .c -bg red -w 32 -he 32]
.c cr r 8 15 28 21 -f #FFF -w 0
.c cr r 15 8 21 28 -f #FFF -w 0

Tcl/Tk, 101

pack [canvas .c -bg red -w 32 -he 32]
.c cr r 8 15 28 21 -f #FFF -w 0
.c cr r 15 8 21 28 -f #FFF -w 0

enter image description here

sergiol

Posted 2017-07-31T22:23:49.970

Reputation: 3 055

3

Red, 79 Bytes

Code:

view[base 32x32 red draw[fill-pen white pen off box 6x13 26x19 box 13x6 19x26]]

Result:

window

Explanation:

view [              ; activate view engine
base 32x32 red      ; draw a 32 by 32 red box as base
 draw [             ; draw on top of the base
  fill-pen white    ; fill color is white
  pen off           ; turn off outline, alternatively could use white
  box 6x13 26x19    ; draw a horizontal rectangle, specified as 2 corners XxY
  box 13x6 19x26    ; draw vertical rectangle
]]

Geeky I

Posted 2017-07-31T22:23:49.970

Reputation: 201

3

Python 2, 92 91 89 bytes

r,w=' \0\0',' '*3
A,B=192*r,(13*r+6*w+13*r)*7
print"P6 "+"32 "*3+A+B+(6*r+20*w+6*r)*6+B+A

Output as binary ppm, usage:

python golf_swiss.py > swiss.ppm

Increasing the color depth allowed me to use space for maximum value

Karl Napf

Posted 2017-07-31T22:23:49.970

Reputation: 4 131

2

Ruby + ruby2d, 106+8 = 114 bytes

Uses the -rruby2d flag.

[[32,32],[6,20,13,6],[20,6,6,13]].map{|w,h,x,y|Rectangle.new width:w,height:h,x:x,y:y}[0].color='red'
show

Image output:

Ruby 2D output

Value Ink

Posted 2017-07-31T22:23:49.970

Reputation: 10 608

2

LibreLogo, 58 bytes

Code:

pc [3]fc [5]square 25 fc [3]rectangle[4,15]rectangle[15,4]

Result:

enter image description here

Explanation:

pc [3]                   ; Pen Color  = #FFFFFF
fc [5]                   ; Fill Color = #FF0000
square 25                ; Square     = 25 pt
fc [3]                   ; Fill Color = #FFFFFF
rectangle [4, 15]        ; Rectangle  = 4 x 15 pt
rectangle [15, 4]        ; Rectangle  = 15 x 4 pt

Grant Miller

Posted 2017-07-31T22:23:49.970

Reputation: 706

2

Processing, 85 bytes

size(32,32);background(#FF0000);fill(255);noStroke();rect(6,13,20,6);rect(13,6,6,20);

A very straightforward implementation. Open the window to the minimum size, draw a red background, set the fill to white and shapes to not have borders, and draw two rectangles.

Swiss flag in a Processing drawing window.

Cody

Posted 2017-07-31T22:23:49.970

Reputation: 447

2

Haskell, 112 bytes

import Graphics.Gloss
(#)=rectangleSolid
main=display(InWindow""(32,32)(0,0))red$color white$pictures[6#20,20#6]

A full program that uses the Gloss library and opens a window of size 32x32 with red background and two white rectangles (size 6x20 and size 20x6) placed at the center of the window.

nimi

Posted 2017-07-31T22:23:49.970

Reputation: 34 639

2

HTML + CSS 215+80 bytes

Try Online

CSS

table{ all:unset } th{ background:red }
   #a{ height: 6 } #b{ height: 7 }
   #c{  width: 6 } #d{  width: 7 }

HTML

<table>
    <tr id=a> <th                                    colspan=5>
    <tr id=b> <th id=c> <th id=d> <td id=c> <th id=d> <th id=c>
    <tr id=a> <th id=c> <td id=d> <td id=c> <td id=d> <th id=c>
    <tr id=b> <th id=c> <th id=d> <td id=c> <th id=d> <th id=c>
    <tr id=a> <th                                    colspan=5>

enter image description here

Inaccurate Version 223+40 179+40 139+40 bytes

  • saved 44 bytes, thanks to @manatwork
  • saved 40 bytes, thanks to @SteveBennett

Try Online

CSS

table{ all:unset } th{ background:red }

HTML

<table>
    <tr> <th                     colspan=5>
    <tr> <th colspan=2> <td> <th colspan=2>
    <tr> <th>   <td>    <td>    <td>   <th>
    <tr> <th colspan=2> <td> <th colspan=2>
    <tr> <th                     colspan=5>

enter image description here

Khaled.K

Posted 2017-07-31T22:23:49.970

Reputation: 1 435

3

Use shorthand properties where possible: backgroud-colorbackground; merge cells: <td><td><td><td><td><td colspan=5>; write crappy HTML (most of the world does it anyway and they are not even codegolfing): classid. http://liveweave.com/oVLiqH

– manatwork – 2017-08-02T10:29:14.570

@manatwork note taken – Khaled.K – 2017-08-02T10:47:05.560

1Save a lot of characters by using th for the red cells, instead of r class:

<table> <tr><th colspan=5> <tr><th colspan=2><td><th colspan=2> <tr><th><td><td><td><th> <tr><th colspan=2><td><th colspan=2> <tr><th colspan=5> http://liveweave.com/0WQ3Vm – Steve Bennett – 2017-08-03T05:40:06.100

@SteveBennett note taken – Khaled.K – 2017-08-03T15:25:04.890

Also I have to point out that it sadly doesn't technically meet the requirements, because the ratios aren't exactly right. The arms of the cross need to be slightly longer (7/6th) than their widths. – Steve Bennett – 2017-08-03T23:42:13.090

2

Excel VBA, 315 313 bytes

2 bytes saved thanks to Taylor Scott!

Golfed

Sub m
Set r=[A1:AF32]
r.RowHeight=48
r.NumberFormat=";"
Set p=r.FormatConditions.AddColorScale(2).ColorScaleCriteria
s 1,255,p
s 2,-1,p
r.Formula=Replace("=IFS(OR(ROW()<6,ROW()>26,|<6,|>26),0,OR(AND(ROW()>13,ROW()<19),AND(|>13,|<19)),1,1,0)", "|", "COLUMN()")
End Sub
Sub s(n,v,p)
p(n).FormatColor.Color=v
End Sub

And commented

Sub m
Set r=[A1:AF32]          'Evaluates range reference to return 32 square range object
r.RowHeight=48           'set row height to make grid cells square - assumes default font
r.NumberFormat=";"       'make text in cells invisible
Set p=r.FormatConditions.AddColorScale(2).ColorScaleCriteria 
                         'add 2-colour scale conditional formatting
s 1,255,p                'where lowest value is red
s 2,-1,p                 'highest is white
r.Formula=Replace("=IFS(OR(ROW()<6,ROW()>26,|<6,|>26),0,OR(AND(ROW()>13,ROW()<19),AND(|>13,|<19)),1,1,0)", "|", "COLUMN()") ''#apply grid of 1s and 0s is flag shape
End Sub
Sub s(n,v,p)             'exploits ByRef default (thanks Gaffi)
p(n).FormatColor.Color=v 'set colour for 2-colour scale conditional formatting
End Sub

I wanted to do something that didn't involve looping

Assumes font is the default Calibri size 11

Greedo

Posted 2017-07-31T22:23:49.970

Reputation: 267

1My preliminary measurements suggest that you would be better off using a row height of 48 rather than 42 as this (so far as I can see) makes the individual cells square - aside from that, you ought to remove the () in m() as it is not necessary; You ought to put in an uncommented version of your code as well, so that others may easily verify the functionality and length of your code - Cheers – Taylor Scott – 2017-08-02T17:46:44.547

You can make some small optimizations to this for -6 bytes : ... Set c=Cells c.RowHeight=48 c.NumberFormat=";" Set p=c.FormatConditions..... ...[A1:AF32]=Replace(... – Taylor Scott – 2017-08-02T20:34:39.707

2

C#, 195 bytes

Try it online(Rextester)!

Hi, this is my first code golf and I'm a C# programmer, so I thought I might submit this entry that I quickly made. It correctly outputs a 32 x 32 bitmap image called "s" in the directory of the executable.

var b=new Bitmap(32,32);var g=Graphics.FromImage(b);g.Clear(Color.Red);g.FillRectangle(Brushes.White,new Rectangle(13,0,6,32));g.FillRectangle(Brushes.White,new Rectangle(0,13,32,6));b.Save("s");

Explanation:

C# offers an extensive GDI+ image manipulation APIs built into the default .NET framework. The System.Drawing namespace contains two such very powerful wrapper classes: Bitmap and Graphics. I merely used those two classes to generate a Swiss flag bitmap.

Ungolfed:

// Creates a new 32 x 32 bitmap object.
var b = new Bitmap(32, 32);
// Creates a new graphics object from the bitmap image.
var g = Graphics.FromImage(b);
// Clears the bitmap with a red(ARGB: FFFF0000) fill color.
g.Clear(Color.Red);
// Draws the vertical rectangle with a white(ARGB: FFFFFFFF) color.
g.FillRectangle(Brushes.White, new Rectangle(13, 0, 6, 32));
// Draws the horizontal rectangle with a white(ARGB: FFFFFFFF) color.
g.FillRectangle(Brushes.White, new Rectangle(0, 13, 32, 6));
// Save the bitmap to a file named: "s."
b.Save("s");

video_error

Posted 2017-07-31T22:23:49.970

Reputation: 21

Welcome to PPCG! – Stephen – 2017-08-03T18:58:40.363

2

C++ with OpenGL, 373 Bytes.

This is my first time really working with C++ and OpenGL on a challenge, so let me know what I can improve.

#include<GL/glut.h>
#define v glVertex2d
#define r(w,x,y,z) v(w,x);v(w,z);v(y,z);v(y,x);
void d(){glScaled(1/16.0f,1/16.0f,1);glBegin(GL_QUADS);glColor3f(1,0,0);r(-16,-16,16,16)glColor3f(1,1,1);r(-3,-10,3,10)r(-10,-3,10,3)glEnd();glFlush();}int main(int c,char**a){glutInit(&c,a);glutInitWindowSize(320,320);glutCreateWindow("");glutDisplayFunc(d);glutMainLoop();return 0;}

Compiled with the MinGW version of g++ on Windows with FreeGlut.

Creates a 320 x 320 screen displaying the Flag. flag

Whenever a redraw happens, it spawns a smaller flag inside itself. This is because I never clear the screen, nor reset the matrix.

bug

However, a redraw does not happen automatically.

Ungolfed Code

#include <GL/glut.h>
#define rect(w,x,y,z) glVertex2d(w,x);glVertex2d(w,z);glVertex2d(y,z);glVertex2d(y,x);
void display(){
    glClear();
    glScaled(1/16.0f,1/16.0f,1);
    glBegin(GL_QUADS);
        glColor3f(1,0,0);
        rect(-16,-16,16,16)
        glColor3f(1,1,1);
        rect(-3,-10,3,10)
        rect(-10,-3,10,3)
    glEnd();
    glFlush();
}

int main(int argc, char **argv){
    glutInit(&argc, argv);
    glutInitWindowSize(320,320);
    glutCreateWindow("Swiss Flag");
    glutDisplayFunc(display);
    glutMainLoop();
    return 0;
}

Link to the Compiled Executable

ATaco

Posted 2017-07-31T22:23:49.970

Reputation: 7 898

You can remove the space between the r macro and the definition. Also, r's definition can be changed to v(-w,-x);v(-w,z);v(y,z);v(y,-x); if you remove all -s in the calls to r. – Zacharý – 2018-01-08T16:07:39.267

1

PostScript, 85 80 bytes

Code:

1 0 0 setrgbcolor
0 0 32 32 rectfill
1 setgray
[13 6 6 20 6 13 20 6] rectfill

Result:

enter image description here

Thomas Fritsch

Posted 2017-07-31T22:23:49.970

Reputation: 361

Welcome to the site! :) – James – 2017-08-03T15:21:41.467

1

Processing, 74 bytes

size(32,32);background(-65536);noStroke();rect(13,6,6,20);rect(6,13,20,6);

I have honestly no idea if that's legal here but here it is.

Outputs:

Window output in windows 10 64bit

Explanation:

size(32,32);            //Set the window size to 32x32
background(-65536);     //Draw the background as red. This is a hack that works because the color datatype uses an int but does not use it as a number. The int equivalent to #FF0000 is -65536 apparently. and it saves me a byte.
noStroke();             //Disable the stroke when drawing shapes like rect
rect(13,6,6,20);        //Draws a rectangle of size 6x20, starting the top-left corner at position (13, 6)
rect(6,13,20,6);        //Draws a rectangle of size 20x6, starting the top-left corner at position (6, 13)

Raphaël Côté

Posted 2017-07-31T22:23:49.970

Reputation: 81

Note that I could have gotten -65536 by using a bitshift operator, -1<<16, though that gives us the same amount of bytes. I'm just leaving this here to lead someone to a better solution. – Raphaël Côté – 2017-08-04T04:37:01.697

1

R , 75 bytes

x=matrix(2,32,32);x[7:26,14:19]=NA;x[14:19,7:26]=NA;image(x,c=2,ax=F,as=1)

Results in:

enter image description here With aspect ratio 1:1 and no axes are drawn.

R.Jagdhuber

Posted 2017-07-31T22:23:49.970

Reputation: 21

1Welcome on the site! – Dada – 2017-08-04T08:24:25.163

@Dada Thank you. Seems like fun here :-) – R.Jagdhuber – 2017-08-04T09:01:14.757

1

SmileBASIC, 42 bytes

GCLS #RED
GFILL 6,13,25,18GFILL 13,6,18,25

Alternatively -1<<16 or -8<<16 can be used instead of #RED for the same length.

12Me21

Posted 2017-07-31T22:23:49.970

Reputation: 6 110

1The output isn't correct. The cross is too small and not centred in the red field, which itself is rectangular (5:3) and not square like it should be. – Anonymous – 2017-10-15T18:42:09.797

1

GW-Basic, 68 bytes (tokenised)

0 SCREEN 9:PALETTE 9,36:FOR I=0 TO 3:LINE(X,Y)-(31-X,31-Y),Y+9,BF
  ↪ :Y=I*7 MOD 14+6:SWAP X,Y:NEXT:LOCATE 4

To get it down to 68 bytes you have to manually edit the file GW-Basic saves to remove all spaces and the trailing end of file and null characters. The PALETTE statement is necessary because GW-Basic has no VGA support and the reds in the default EGA palette are too dark (4) and too washed out (12). The final LOCATE statement ensures that GW-Basic's Ok isn't printed on top of the flag.

Anonymous

Posted 2017-07-31T22:23:49.970

Reputation: 161

1

PowerShell, 108 bytes

$1=($r='2 0 0 ')*192
$2=($r*13+($w='2 '*3)*6+$r*13)*7
$3=($r*6+$w*20+$r*6)*6
"P3 32 32 2 $1$2$3$2$1"|sc .ppm

Outputs a PPM file called .ppm (checked with IrfanView). It sets '2' as the maximum value for each channel, so $r is 2 0 0 for red, $w is 2 2 2 for white, and the rest is string multiplication and a file header; $1 is a horizontal red line for the very top and bottom of the flag, $2 is wide red, narrow white, wide red for the top and bottom parts of the cross, 3 is the centre narrow red, wide white, narrow red. sc is set-content and used because > makes a 2-byte+BOM Unicode file which doesn't work.

TessellatingHeckler

Posted 2017-07-31T22:23:49.970

Reputation: 2 412

0

BBC BASIC, 70 bytes

V.19;16,255|25,97,64;64;25,4,12;26;25,99,40;12;25,4,26;12;25,99,12;40;

Download interpreter at http://www.bbcbasic.co.uk/bbcwin/download.html

Program runs in default mode for this interpreter (white background, black foreground.) 2x2 units = 1 pixel. Flag is 64x64 units = 32 x 32 pixels.

The VDU or V. command sends characters to the screen controller. These include a number of machine specific control characters for graphics. Number followed by , sends 1 byte, by ; sends 2 bytes. Number followed by | sends "sufficient" bytes to finish a multibyte command.

Ungolfed

  VDU 19,0,16,255|   :REM Reprogram colour 0 (foreground) to #0000FF red (BBC BASIC is little endian.)
  VDU 25,97,64;64;   :REM Cursor is already at 0,0. Move to 64,64 and draw a rectangle in foreground colour (red.)
  VDU 25,4,12;26;    :REM Move to 12,26
  VDU 25,99,40;12;   :REM and draw a rectangle in backgorund colour (white) 40 units wide x 12 units high,
  VDU 25,4,26;12;    :REM Then move to 26,12
  VDU 25,99,12;40;   :REM and draw a vertical rectangle of simiar dimensions.

Level River St

Posted 2017-07-31T22:23:49.970

Reputation: 22 049

0

Batch File, 584 497 bytes

EDIT: -87 bytes! Replaced rem with hh as it is a no-op when no arguments are passed, removed a bunch of quotation marks and some other stuff.

I'm sure this can be compressed some more, but for the moment it's the best I got.

@!! 2>nul||cmd/q/v/c%0&&exit/b
for /f "tokens=1,2delims=#" %%a in ('"prompt #$H#&for %%b in (1)do hh"')do set K=%%a
set s=aaaaaa
set g=%s%%s%b
:d
set/ai+=1
set t=%i%
if %t%==5 set t=1
if %t%==4 set t=2
if %t%==1 for /l %%a in (1,1,6)do call:c 44 %g%%g%%s%&echo(
if %t%==2 for /l %%a in (1,1,7)do call:c 44 %g%&call:c ff %s%&call:c 44 %g%&echo(
if %t%==3 for /l %%a in (1,1,6)do call:c 44 %s%&call:c ff %g%%s%c&call:c 44 %s%&echo(
if %t%==6 exit
goto d
:c
<nul set/p.=%K%>%~2&findstr/a:%1 . %~2 nul

This code produces the following output (tested on Windows version 10.0.15063):

Beautiful flag screenshot

As a negative side-effect, it creates 4 different files on the same directory with some weird names and gibberish in them. You're free to delete them.

Also, in order for this to look right, CMD's properties must be changed (if not already set correctly):

CMD configuration

This code requires that the font chosen has a 1:1 width to height ratio.

Matheus Avellar

Posted 2017-07-31T22:23:49.970

Reputation: 273

0

Bash + core utils, 147 bytes

echo H4sICBkuh1kAA2ZsYWcueHBtAFNUiAjwNeIyNlIAIiMFQ64ihWQFZTc3AyDgKoewQYCLq4gAGIIKysFg+CooxwKGngI6BNQgUoAFDA0FXABVWXDvSwQAAA|base64 -d|gunzip>1.xpm

Decodes base64-encoded GZipped image data, unGZips it and writes into 1.xpm.

Andrew Dunai

Posted 2017-07-31T22:23:49.970

Reputation: 321

0

Python 2, 170 bytes

Uses Pillow 2.8.0 with PIL 1.1.7 for the old (and deprecated) offset method.

from PIL.ImageDraw import*
i=Image.new('RGB',(20,20),-1)
Draw(i).rectangle((3,3,18,18),'red',-1)
k=Image.new('RGB',(32,32),'red')
k.paste(i.offset(9),(6,6))
k.show()

Gábor Fekete

Posted 2017-07-31T22:23:49.970

Reputation: 2 809

-3

PNG - 101 bytes :p

âPNG


IHDR  I¥Ë∑PLTEˇˇˇˇA4IDAT◊c`¿ÿ"òˇˇ?Äõ ¬º)’   «√IENDÆB`Ç

Swiss Flag .png

Explanation :

Ctrl+C -> Ctrl+V

Anu Shibin Joseph Raj

Posted 2017-07-31T22:23:49.970

Reputation: 107

"PNG" or "keyboard" are not programming languages, as they cannot add two inputs or check the primality of an input. – Stephen – 2017-08-02T11:08:31.387

2

According to meta consensus on Do submissions have to be answered with a programming language? there is no longer a requirement that answers be in a programming language.

– trichoplax – 2017-08-02T22:39:35.090

Clearly PNG isn't a programming language, but –at the risk of stating the obvious– this isn't "drawing" anything, it's just the pre-drawn output file handed out on a platter. That makes a profoundly un-interesting submission. Whereas most submissions could be tweaked for different parameters, this would just have to be redrawn and and the output re-pasted into the answer. – Caleb – 2017-08-03T09:03:08.460

Why is PNG unacceptable while GIF is not? – JollyJoker – 2017-08-04T08:42:30.313

Both are, see the comment above. – flawr – 2017-08-04T10:19:24.687

Actually, I think it's kind of interesting that a generic commonly used image format like PNG can come close in size to the solutions using code tailor-made to this particular image. Also, people regularly submit Bubblegum solutions, which is designed to be used without input (and as a commentary on Stephen's criteria). – Anonymous – 2017-10-15T18:33:02.187