Fifty Shades of Grey

90

22

Boys and girls are excited to see Fifty Shades of Grey on the silver screen, we just want to code without being bothered, so here's a challenge to pick our brain.

You have to:

  • Print on the screen fifty squares filled each with a different shade of grey
  • If your language of choice lacks image processing capabilities, you could output an image file
  • Squares must be visible, at least 20 x 20 pixels
  • You cannot use random numbers unless you make sure each shade is unique.
  • You cannot connect to any service over any network
  • You cannot read any files in your program.
  • You cannot use any libraries out of the standard libraries of your language of choice.

This is code golf so shortest code wins.

jsedano

Posted 2015-02-16T01:30:52.100

Reputation: 1 607

21Were they bothering us? – Calvin's Hobbies – 2015-02-16T03:05:10.760

Can't use C++... ;-( – Mukul Kumar – 2015-02-16T08:29:51.407

1Can we also generate an image file if our language lacks image processing capabilities? – FUZxxl – 2015-02-16T10:38:56.480

@FUZxxl yes, that's ok – jsedano – 2015-02-16T14:18:26.330

6Objection: misleading title! – George Chalhoub – 2015-02-16T17:31:46.407

23

Will we see a Piet submission?

– randomra – 2015-02-16T20:12:20.183

@MukulKumar why not? – BWG – 2015-02-16T21:00:13.303

@BWG: presumably Mukul means because C++ has no standard means to access a screen. Terminal, yes, and you could do it assuming certain terminal properties (background colour control codes) and the aspect ratio of the terminal characters (to get a square). – Steve Jessop – 2015-02-16T21:12:13.300

@SteveJessop I didn't read the request fully, but couldn't you just write a bitmap? The header is pretty trivial, and the rest is just plain bytes. – BWG – 2015-02-16T22:12:25.737

@randomra If I could understand what "The interpreter finds the edge of the current colour block which is furthest in the direction of the DP. (This edge may be disjoint if the block is of a complex shape.) The interpreter finds the codel of the current colour block on that edge which is furthest to the CC's direction of the DP's direction of travel. (Visualise this as standing on the program and walking in the direction of the DP; see table at right.)" meant, I would be working on a Piet submission – KSFT – 2015-02-16T22:39:12.053

1@BWG: that's what the CJam answer below does, so of course you could do that. It's clearly not what the question says, but I think the questioner has been overruled by the voters. – Steve Jessop – 2015-02-17T08:07:37.920

8Not the pictures I thought we'd be generating for a 50 shades of grey contest. – corsiKa – 2015-02-18T15:54:49.663

3

@randomra ask and you shall receive: http://codegolf.stackexchange.com/questions/45736/fifty-shades-of-grey/46877#46877

– captncraig – 2015-02-19T15:20:19.260

Is jquery allowed? – SalmonKiller – 2015-02-19T18:34:50.613

1Do black and white count as shades of grey? Or should they be excluded? – aditsu quit because SE is EVIL – 2015-02-19T18:42:06.880

http://codepen.io/anon/pen/gbeKjR html: 666bytes – superUntitled – 2015-02-19T18:52:48.770

*devil in the details – superUntitled – 2015-02-19T19:04:51.733

@BWG Oh...I was so much immersed in array handling that I forgot to use graphical header files....LOL I was still thinking of ASCII characters....:P – Mukul Kumar – 2015-02-20T15:31:37.657

1@SalmonKiller Sure, if you include jquery.js in the byte count. – nyuszika7h – 2015-02-22T21:03:47.120

1Why has not the shortest code won? – Steffen – 2015-03-25T08:47:26.103

@Steffen sorry I thought that was the shortest answer that didn't break any of the rules, what is the answer that you mention? – jsedano – 2015-03-25T11:52:39.313

What about sanchises "MATLAB, 24 bytes"? – Steffen – 2015-03-25T13:21:42.020

@Steffen you're right, thanks! – jsedano – 2015-03-25T13:45:34.440

1Now that Fifty Shades Darker has come out, should we make all these answers darker by 50 shades? – caird coinheringaahing – 2017-07-21T22:21:53.673

Answers

24

MATLAB, 24 bytes

Second attempt, now actually conforming to the rules.

imshow(0:1/49:1,'I',2e3)

The 'I' stands for 'InitialMagnification', but apparently Matlab will autocomplete names in name/value pairs. Sure is a good golfing trick!

enter image description here

Sanchises

Posted 2015-02-16T01:30:52.100

Reputation: 8 530

58

Mathematica, 30 bytes

Here is another Mathematica approach:

ArrayPlot[#+5#2&~Array~{5,10}]

enter image description here

or

ArrayPlot[5#+#2&~Array~{10,5}]

enter image description here

The first one simply creates an array

{{6, 11, 16, 21, 26, 31, 36, 41, 46, 51}, 
 {7, 12, 17, 22, 27, 32, 37, 42, 47, 52}, 
 {8, 13, 18, 23, 28, 33, 38, 43, 48, 53}, 
 {9, 14, 19, 24, 29, 34, 39, 44, 49, 54}, 
 {10, 15, 20, 25, 30, 35, 40, 45, 50, 55}}

and the second one

{{6, 7, 8, 9, 10},
 {11, 12, 13, 14, 15},
 {16, 17, 18, 19, 20},
 {21, 22, 23, 24, 25},
 {26, 27, 28, 29, 30},
 {31, 32, 33, 34, 35},
 {36, 37, 38, 39, 40},
 {41, 42, 43, 44, 45},
 {46, 47, 48, 49, 50},
 {51, 52, 53, 54, 55}}

Then, ArrayPlot plots them as a grid and, by default, uses greyscale to visualise the values.

Martin Ender

Posted 2015-02-16T01:30:52.100

Reputation: 184 808

Lovely use of ArrayPlot. – DavidC – 2015-02-16T14:42:09.943

4That's funny, MatrixPlot seems to use colors by default, it's lucky for this challenge that ArrayPlot uses grayscale and it is one letter shorter than MatrixPlot. – Omar – 2015-02-16T15:00:08.607

You could do ArrayPlot@{Range@50}, which is only 20 bytes. – Chip Hurst – 2015-09-08T19:43:59.620

@ChipHurst when I do that, the default size is too small to meet the 20x20 pixels requirement. – Martin Ender – 2015-09-08T20:17:17.443

36

CJam - 23 (no actual graphical output)

Since CJam can't draw on the screen (yet?), I wrote a program that outputs an image in plain pgm format.
Save the output to a file called 50.pgm and open with an image viewer/editor.

"P2"1e3K51_,1>K*$K*~]N*

Try it online

The result looks like this:

50.png

Explanation:

"P2"     push "P2" (netpbm magic number)
1e3K     push 1000 and K=20 (image size)
51       push 51 (value of white)
_,       duplicate 51 and convert to an array [0 1 2 ... 50]
1>       remove 0 (slice from 1)
K*       repeat the array 20 times
$        sort, to get [(20 1's) (20 2's) ... (20 50's)]
K*       repeat the array 20 times
~        dump the elements on the stack
]        put everything from the stack in an array
N*       join with newlines

aditsu quit because SE is EVIL

Posted 2015-02-16T01:30:52.100

Reputation: 22 326

3So being happy increments the elements!? – Caridorc – 2015-02-16T20:11:22.720

7@Caridorc of arrays containing numbers, yes. And being sad decrements them :p – aditsu quit because SE is EVIL – 2015-02-16T21:05:47.720

You don't follow the PGM's specification: No line should be longer than 70 characters. – kiwixz – 2015-02-19T01:39:27.407

@iKiWiXz updated – aditsu quit because SE is EVIL – 2015-02-19T06:47:05.967

1@iKiWiXz Should, not must. Lines may be longer than that but programs that generate PGM images should try to keep them under 70 characters. – FUZxxl – 2015-02-19T10:47:26.623

@FUZxxl Feel free to check: http://netpbm.sourceforge.net/doc/pgm.html

– kiwixz – 2015-02-19T11:40:19.730

30

Mathematica 72 61 59 43 35 34 bytes

Current version (34 bytes)

GrayLevel[#/50]~Style~50 &~Array~50    

grid2


Earlier version (59 bytes), thanks to Martin Büttner.

Graphics[{GrayLevel[#/50],Cuboid@{#~Mod~9,#/9}}&/@Range@50]

Blue borders added to highlight position of squares.

Graphics[{EdgeForm[Blue], GrayLevel[#/50], Cuboid@{#~Mod~9, #/9}} & /@Range@50]

blue

Number of squares:

    Length[%[[1]]]

50


First attempt (72 bytes)

If the squares can overlap. As Zgarb notes, there is a remote possibility that one square would hide another.

  Graphics@Table[{GrayLevel@k,Cuboid[{0,15}~RandomReal~2]},{k,.4,.89,.01}]

enter image description here

DavidC

Posted 2015-02-16T01:30:52.100

Reputation: 24 524

I'm guessing that one square could in principle cover another completely, so that less than 50 would be visible? – Zgarb – 2015-02-16T12:29:40.907

2Definitely the most esthetically pleasing answer. – Dan – 2015-02-17T14:08:15.160

30

Sage - 26 24 35 29 characters

matrix(5,10,range(50)).plot()

It looks like this:

5x10 shades of grey

Previous attempts: First I had Matrix([range(50)]).plot(), then matrix_plot([range(50)]). These looked like this:

50 shades of grey

User @flawr pointed out that the squares produced with default settings are too small. Adding a figsize options fixes it, but it is 6 characters longer than the 5x10 version at the top of this answer:

matrix_plot([range(50)],figsize=20)

Omar

Posted 2015-02-16T01:30:52.100

Reputation: 1 154

Looks like 51 shades and the squares look smaller than 20x20px, is it bigger when produced by your program? – flawr – 2015-02-16T13:50:36.757

I don't think extra output is forbidden, @flawr, I didn't bother removing the frame, tickmarks and numbers either. You might be right about the squares being too small, I'll check. – Omar – 2015-02-16T14:48:54.807

Argh! @flawr is right the squares are smaller than 20px by 20px. – Omar – 2015-02-16T15:04:55.803

I would say extra output should be forbidden. The question specifies '50', not '50 or more'. – Joe – 2015-02-16T18:16:06.217

1Am I understanding correctly, @Joe, that you don't object to the frame and the numbers outside the frame, only to the number of squares? If that's the case, just replace 50 with 49. – Omar – 2015-02-16T18:26:49.257

22

R, 47 42 39 38 37 36 35 bytes

Assuming they're allowed to overlap, this works. Symbols requires a vector that holds the size for each square, and I'm saving space by reusing the same vector for all function parameters. The largest square is always 1 inch wide. With 50:99 as the range of integers, the smallest square will be around half an inch wide, so 36 pixels at 72 dpi.

symbols(x,,,x<-50:99,bg=gray(x/99))

Thanks to everyone for the comments and suggestions, I'm pretty new to R so this is all very educational.

new and improved?

Previous versions:

symbols(x,sq=x<-50:99,bg=gray(x/99))            #36
x=50:99;symbols(x,sq=x,bg=gray(x/99))           #37
x<-50:99;symbols(x,sq=x,bg=gray(x/99))          #38
x<-1:50;symbols(x,sq=x/x,bg=gray(x/50))         #39
x<-1:50/50;symbols(x,sq=x/x,bg=rgb(x,x,x))      #42
x<-1:50/50;symbols(x,squares=x/x,bg=rgb(x,x,x)) #47

Previous image: 50 shades of R

freekvd

Posted 2015-02-16T01:30:52.100

Reputation: 909

Could save a few more with symbols(x<-50:99,sq=x,bg=gray(x/99)) – MickyT – 2015-02-16T19:03:25.783

Minus two! Thanks @MickyT, I thought it was done already. – freekvd – 2015-02-16T19:19:34.370

Whoops, and undo. Doesn't work. You can create in-line variables but you can't reference them in the same line. – freekvd – 2015-02-16T19:54:13.237

Sorry about that ... must of had a object floating around when I tested it. You can get one more from changing <- to = – MickyT – 2015-02-16T20:08:27.023

1@freekvd It does in general, it depends on the order in which the arguments are accessed inside the function (since arguments are lazily evaluated). You can test this by having f = function (a, b) { a; b} and then calling f(x <- 5, x). This works as expected. Once you reverse the arguments in f’s definition (and rm(x)), it doesn’t work any more. – Konrad Rudolph – 2015-02-17T15:40:07.780

1Looks like evaluation starts at sq=x, so I can trim off another char with this. Thanks @KonradRudolph – freekvd – 2015-02-17T16:13:33.267

1Cut down by 1 byte symbols(x,,,x<-50:99,bg=gray(x/99)) – Vlo – 2015-02-17T20:04:30.593

20

Java - 180

Pretty straightforward, just drawing boxes.

import java.awt.*;void f(){new Frame(){public void paint(Graphics g){for(int i=1;i<51;g.setColor(new Color(328965*i)),g.fillRect(i%8*20,i++/8*20,20,20))setSize(600,600);}}.show();}

enter image description here

With line breaks:

import java.awt.*;
    void f(){
        new Frame(){
            public void paint(Graphics g){
                for(int i=1;
                    i<51;
                    g.setColor(new Color(328965*i)),
                    g.fillRect(i%8*20,i++/8*20,20,20))
                    setSize(600,600);
            }
        }.show();
    }

Geobits

Posted 2015-02-16T01:30:52.100

Reputation: 19 061

If anyone objects to the last box being technically white, just change the color multiplier to 263172. Same byte count, I just think it looks better this way. – Geobits – 2015-02-16T02:40:24.977

I think you could also use int i; instead of int i=1 but then use ++i on the first use of i instead of i++ in the last occurence, would save 2 bytes. BTW: I didn't even know you can make a java program without class MyClass ... public static void main(...!!! – flawr – 2015-02-16T14:18:22.973

@flawr Nah, Java won't initialize local variables to default values. It might work if I moved it outside the function. If I was giving a full program instead, I'd try it that way (this is just a function, plus the necessary import). Thanks, though :) – Geobits – 2015-02-16T14:28:36.503

Ah I forgot, it was initializing arrays where the default values are set. Sorry=) But still, I always thought you need a class and I am not the only one. Or is this a feature of a newer version?

– flawr – 2015-02-16T14:34:25.430

2

@flawr If it was a full program then yes, you'd need that. This is just a function, since the question doesn't specify.

– Geobits – 2015-02-16T14:36:48.767

You could get rid of most of the overhead by writing it as a Processing sketch. Your program would then just be size(600,600);for(int i=1;i<51;fill(++i/51.))rect(i%8*20,i++/8*20,20,20); (or something thereabouts, anyway) – AJMansfield – 2015-02-16T16:27:06.033

1@AJMansfield I know, but I consider Processing a different language, and I like to golf in Java Java. – Geobits – 2015-02-16T17:58:54.580

You can save 1 character by making your squares 51*51 and making your for loop for(int i=1,t=51;i<t;... and changing all your 20's to t. – corsiKa – 2015-02-17T21:39:51.630

You can save 2 characters by changing void f(){ to static{. – corsiKa – 2015-02-17T21:41:09.213

I think you could save lots of bytes by just drawing them in a line. – kiwixz – 2015-02-19T01:47:10.940

@iKiWiXz I was being friendly to those with <1000px resolution ;) – Geobits – 2015-02-19T02:06:59.990

17

ipython 2, 54 bytes

The best I could do was with an ipython program. Starting ipython with ipython -pylab and executing this program will show a graph with 50 shades of grey in 50 squares:

t=arange(50);c=t/50.;scatter(t%5,t,500,zip(c,c,c),'s')

Output:

grey50

Solution 2:

Here is another program (61 bytes):

imshow(arange(50).reshape(5,10)*.02,'Greys',None,1,'nearest')

that displays the following window:

grey50b

Logic Knight

Posted 2015-02-16T01:30:52.100

Reputation: 6 622

1However note that ipython is not a language and what you used is Python library matplotlib, which is an external lib. – Stefano Sanfilippo – 2015-02-20T13:14:27.960

17

BBC BASIC, 57

FORn=51TO2STEP-1VDU19;-1,n,n,n:RECTANGLEFILL0,0,n*20NEXT

The squares have to be at least 20 pixels but there's nothing to say they have to be the same size, so I guess this qualifies.

It may be possible to shorten this by using more low-level VDU codes. But changing from this pattern to a less interesting one is unlikely to make it shorter.

enter image description here

Level River St

Posted 2015-02-16T01:30:52.100

Reputation: 22 049

2Remember your BBC Basic abbreviations? F.,N.,S.,V. -> F.n=51TO2S.-1V.19;-1,n,n,n:RECTANGLEFILL0,0,n*20N. – SeanC – 2015-02-17T23:29:03.103

@SeanCheshire http://www.bbcbasic.co.uk/bbcwin/bbcwin.html does support those abbreviations, I never thought to check! Your way counts as 50. The tokenised filesize is 41 bytes (each keyword tokenisied to a single byte outside the ASCII range) though I don't often count that way. I will use your tip in future though!

– Level River St – 2015-02-17T23:59:16.290

15

JavaScript (72, 70, 67 bytes)

72: original (borrowing the clever &#9632; usage from Sphinxxx's answer):

for(i=90;i>40;)document.write('<font color=#'+i+i+i--+' size=7>&#9632;')

70: stealing shamelessly from Ismael Miguel (who deserves the votes), a shorter for loop and allowing the browser to correct for a lack of # proceeding the colour code...

for(i=60;--i>9;)document.write('<font color='+i+i+i+' size=7>&#9632;')

67 bytes (65 chars): swapping the entity for the unicode character:

for(i=60;--i>9;)document.write('<font color='+i+i+i+' size=7>■')

JcT

Posted 2015-02-16T01:30:52.100

Reputation: 251

I think you should start at i=51. If I counted correctly, there are only 49 squares? – flawr – 2015-02-16T14:02:16.217

Hi, this should be a comment and rather there already exists a similar comment. Thus, this answer is an exact copy of another already existing. – Optimizer – 2015-02-16T14:02:36.967

Fair enough. I've attempted to better differentiate - if still too close, I'll delete permanently. Don't have enough rep for commenting, sorry. – JcT – 2015-02-16T14:31:23.707

1I really like your answer! Dear lord, why I didn't though about it? +1 on this one! I would reduce this one to for(i=0;i++<50;)document.write('<font color=#'+i+i+i+' size=7>&#9632;') or similar. Untested but it might work! – Ismael Miguel – 2015-02-16T15:25:42.533

I like it - unfortunately I think that method generates duplicates when i <= 5, since #555 (etc) is equivalent to #555555. Looping additional times to generate more swatches to give us a unique 50 probably bends the wording of the rules too far, yeah? – JcT – 2015-02-17T02:35:25.683

On the other hand, your use of for(i=60;--i>9;) as the loop in your JavaScript answer certainly does the trick of producing double-digit values of i (avoiding the duplicates issue) while still only requiring one double-digit number within the for statement... nice. ;) – JcT – 2015-02-17T08:31:28.247

1Since you are stealing from me, at least steal properly. Remove the # character to have a 70-byte long solution. – Ismael Miguel – 2015-02-18T12:02:14.180

Great tip (on both the # and the stealing). Actually I'm a little unclear on the etiquette around "incorporating others' brilliance"; always happy to retract an edit, more interested in shorter code than points. At least I finally have enough rep for commenting. – JcT – 2015-02-18T14:38:00.050

What are the rules around inputting a unicode character directly? For instance, instead of using the entity &#9632;, just directly using ■? A quick search on meta seemed to indicate the question should specify whether scoring characters or bytes (and I'm assuming bytes by default). In any case, the unicode is also shorter in bytes, yes? – JcT – 2015-02-18T14:40:35.637

1I was just about to recommend that. The default is counting bytes, but you should use the Unicode character because it is still fewer bytes. – NinjaBearMonkey – 2015-02-18T14:42:14.973

for(i=50;i--;) = 14 characters and iterates 50 times, like your loop which takes 16 characters. (0 evaluates to false in JS so the loop exits when i hits 0) That should knock off two more bytes for you. – JessieArr – 2015-02-18T19:43:24.890

I just realized that my comment won't work. Once i becomes 4 it will output '444' which in HTML is a duplicate color of '444444' which would have been output by the i=44 iteration. So close. – JessieArr – 2015-02-18T22:16:39.560

I managed to get caught out by that a few times! – JcT – 2015-02-18T22:55:46.913

1Did the question say exactly 50 squares? :) (The other solutions also draw extra stuff.) With that and the unicode literal, down to 65 bytes (63 chars): for(i=90;i;)document.write('<font color=#'+i+i+i--+' size=7>■') - BUT at least on my browser's default settings (OSX/Chrome) the box is a bit smaller than 20x20 pixels anyway, so these ■ based solutions are questionable. – tuomassalo – 2015-02-19T13:44:38.163

Might have to confer with a code golf lawyer regarding rule 1. ;) Interesting regarding the pixel sizing; Win7/Chrome has it at 21x21 px... of course I'd only previously eyeballed it and am somewhat relieved to be able to confirm it now! I believe on my system it's being rendered as a Times New Roman glyph at font-size 48px. – JcT – 2015-02-19T14:01:32.950

13

C++, 98 83 characters

Okay so, you are going to need a terminal emulator that supports true colors. For mac os there are the nightly builds of iTerm2, for example. For unix I believe konsole supports it. Here's a list, just in case: https://gist.github.com/XVilka/8346728#now-supporting-truecolor

Compile with g++ (\e is compiler dependent).

For the squares to have enough area, you will have to change your terminal font size.

#include <cstdio>
int main(){for(int i=51;i--;)printf("\e[48;2;%i;%i;%im ",i,i,i);}

Using C libraries instead of C++ allows for shaving some characters.

C, 61 58 characters

This is the same program but in C, which assumes untyped function declarations to return int, and which doesn't need includes for some of the standard library functions, like in this case, printf. Suggested by @cartographer. Three characters less thanks to @user3601420

main(i){for(i=51;i--;)printf("\e[48;2;%i;%i;%im ",i,i,i);}

Compiles with a couple of warnings (for assuming main's return type to be int and for implicitly including the declaration of printf).

rorlork

Posted 2015-02-16T01:30:52.100

Reputation: 1 421

2If you switch this to C you can drop the include and the int in front of main and have it compile with just a couple of warnings with gcc. – cartographer – 2015-02-17T00:55:34.550

Yes, but that would be another language. Anyway, I'll append it, thank you! – rorlork – 2015-02-17T08:42:58.830

1You can remove a few characters from the C version if you make i the first argument to main, as in: main(i){for(i=51;i--;)printf(... – Functino – 2015-02-17T20:44:11.127

Only one additional character to make it standard: \e\33 – Holger – 2015-02-19T12:45:25.083

This is code-golf! – rorlork – 2015-02-20T21:38:07.900

11

Python 2, 125 115 104 bytes

from turtle import*
shape("square")
bk(500)
ht()
pu()
exec'color((xcor()/2e3+.5,)*3);stamp();fd(21);'*50

Sample output:

enter image description here

Good old turtle. This was the only method I could think of in Python which prints images to a screen using only the standard libraries.

The square turtle shape just happens to be 21 by 21, which is very convenient. This can be seen by digging through turtle.py:

"square" : Shape("polygon", ((10,-10), (10,10), (-10,10), (-10,-10)))

If you have a high res monitor or don't mind a few squares being off-screen, then this is 93 bytes:

from turtle import*
shape("square")
ht()
pu()
exec'color((xcor()/2e3,)*3);stamp();fd(21);'*50

Demo

(This demo uses Skulpt by adapting the snippet found here. It is only included to give an idea as to what the code does — I had to modify a few bits to get it working.)

function out(a){var b=document.getElementById("output");b.innerHTML+=a}function builtinRead(a){if(void 0===Sk.builtinFiles||void 0===Sk.builtinFiles.files[a])throw"File not found: '"+a+"'";return Sk.builtinFiles.files[a]}
$(document).ready(function run(){Sk.canvas="canvas";Sk.configure({output:out,read:builtinRead});try{Sk.importMainWithBody("<stdin>",!1,'import turtle\nt=turtle.Turtle()\nt.speed(9)\nt.shape("square")\n\nt.bk(500)\nt.ht()\nt.pu()\nfor i in range(50):t.color(64+2*i,64+2*i,64+2*i);t.stamp();t.fd(21)')}catch(a){throw Error(a.toString());}})
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script><script src="http://www.skulpt.org/static/skulpt.min.js" type="text/javascript"></script><script src="http://www.skulpt.org/static/skulpt-stdlib.js" type="text/javascript"></script>
<canvas height="100" width="1200" id="canvas" style="border:1px solid gray">Your browser does not support HTML5 Canvas!</canvas>

Sp3000

Posted 2015-02-16T01:30:52.100

Reputation: 58 729

Ah I see how you realised skulpt has updated. Thanks for this, I will probably use it to update the snippet. – ArtOfCode – 2015-02-19T01:18:44.733

11

J (43 41 40 38 33 29 characters)

After suggestions from randomra.

1!:2&4'P2 ',":(,*:,],*:#?~)50

This solution does not display anything as the standard library of J does not contain GUI routines. Instead, I generate an image and write it to standard output. The output is randomized, it ensured that all shades are distinct. Here is a some sample output and the image converted to png and rotated by 90° for easier viewing:

50 shades of gray

FUZxxl

Posted 2015-02-16T01:30:52.100

Reputation: 9 656

Pushing the 50 from the header into the generated part using 5050 squares saves 1 byte: `1!:2&4'P2 50 2500 ',":(,:#i.)50`. – randomra – 2015-02-16T15:59:36.790

That's a neat idea. – FUZxxl – 2015-02-16T16:03:30.273

Even more: push all numbers in 1!:2&4'P2 ',":(,*:,],*:#i.)50 for 29 chars! Btw plot isn't part of the standard J library? – randomra – 2015-02-16T16:05:28.710

@randomra plot is one of the auxiliary packages you can download from the package manager. I would hardly see it as a part of the standard library.

– FUZxxl – 2015-02-16T16:10:29.887

10

Excel vba, 81

In the immediate window:

for i=1 to 9:for j=1 to 9:k=i+j*10:cells(i,j).interior.color=rgb(k,k,k):next:next

on the active sheet:

81 shades is just as much code as 50

{81 shades is just as much code as 50}

SeanC

Posted 2015-02-16T01:30:52.100

Reputation: 1 117

Well, some people are interpreting the "50" to mean exactly 50. In that case, it's probably one more character to get 50=105 than it is to get 81=99. – Omar – 2015-02-17T17:41:02.597

@Omar, 0 to 9 and 1 to 5 will produce exactly 50 in the same number of characters.... This also means I can write the sequel too, in the same number of bytes - 0 to 9 twice – SeanC – 2015-02-17T23:22:12.970

1Oh, 0 to 9! I thought that for the cells(i,j) you needed i>0 and j>0. – Omar – 2015-02-18T04:27:22.383

@Omar, damn, you're right. I couldn't use zero – SeanC – 2015-02-18T14:03:22.137

1Slightly shorter (61) For i=1 To 50:Cells(i,1).Interior.Color=RGB(i*5,i*5,i*5):Next – OldCurmudgeon – 2015-02-18T17:22:24.330

you can also condense Next:Next to next j,i – Taylor Scott – 2017-11-01T12:06:58.607

8

Matlab 35 thanks to sanchises

imshow(int8(ones(20,1)*(0:.05:51)))

Matlab 36

imshow(uint8(ones(20,1)*(0:.05:51)))

Displays 50 squares filled with gray values 1 to 50 and 2 additional rectangles filled with gray value 0 and 51:

enter image description here

Matlab, 45

imshow(uint8(ones(20,1)*floor(1:0.05:50.95)))

Steffen

Posted 2015-02-16T01:30:52.100

Reputation: 221

You can shave off a whopping 1 byte by using int8 instead of uint8. – Sanchises – 2015-02-19T18:05:34.253

sanchises's solution is better! – Memming – 2015-02-21T15:37:50.460

@Memming It does hinge on some obscure (undocumented?) feature that I only found out by trying it out for the heck of it. Give Steffen credit were it's due :) – Sanchises – 2015-02-25T19:23:16.777

@TheBestOne / JaBe: Your answer actually doesn't work since it does not display squares. Steffen uses int8 to round the 1000 or so values to 50 squares. – Sanchises – 2015-02-26T11:51:27.977

8

R, 37 32 characters1:

image(t(1:50),c=gray.colors(50))

However, the display for this looks … meh (image rotated 90° to fit better into text; compressed, original square side length > 20px):

boring

Here’s a nicer version which plots the squares in random order inside a matrix (50 characters):

image(matrix(sample(1:50),10),c=gray.colors(50))

exciting!

(And yes, the three adjacent squares of seemingly identical colours are actually three different shades of grey.)

1 Yes, another R answer, and not even the shortest (now the shortest for R) – apologies. I was missing a pretty rendering in R.

Konrad Rudolph

Posted 2015-02-16T01:30:52.100

Reputation: 1 067

1How did you fix the aspect ratio? – koekenbakker – 2015-02-17T19:38:03.303

? Basically the same as second version @ 37 image(matrix(1:50,5),c=gray(1:50/51)) – Vlo – 2015-02-17T20:18:41.827

@koekenbakker It’s not fixed, I’m manually adjusting the output window. It’s not perfect but the code does produce squares for a given window, and other code here has comparable issues. – Konrad Rudolph – 2015-02-17T21:09:22.070

7

JavaScript, 87 90 bytes

for(i=90;i>40;)document.write('<p style=background:#'+i+i+i--+';height:9ex;width:9ex>')

This outputs squares to the HTML, because it is really JavaScript's only method of graphical output. Thanks to edc65 for shaving off 3 bytes.

NinjaBearMonkey

Posted 2015-02-16T01:30:52.100

Reputation: 9 925

1Save 3 bytes: for(i=90;i>40;)document.write('<p style=background:#'+i+i+i--+';height:9ex;width:9ex>'). Can't use single digits because grays would not be unique (#111 same color as #111111) – edc65 – 2015-02-16T07:49:02.990

You can use other units. 1cm or 19mm would be better and more widely supported. Without changing your byte count. – Ismael Miguel – 2015-02-18T12:03:37.603

7

PHP, 96 88 74 bytes

Thanks to Ismael Miguel for saving 22 bytes!

for($i=60;--$i>9;)echo"<p style=background:#$i$i$i;height:9mm;width:9mm>";

Writes 50 <p>s with 9mm as height and width (which should be bigger than 20px on the majority of screens), stacked on each other, all with a minor difference in shade.

Generated result (the image is zoomed out and 90° rotated):

Result

ProgramFOX

Posted 2015-02-16T01:30:52.100

Reputation: 8 017

7

Javascript (77 71 bytes):

This answer is no longer IE11 based. It works because the browser converts the bad color codes into usable ones (by adding # to the number).

Here is the code:

for(i=59;i-->9;)document.write("<hr color="+i+i+i+" size=20 width=20>")

Firefox still has the quirk of making circles.

(Small edit: Changed for(i=61;i-->9;) to for(i=59;i-->9;) because it was producing 52 squares)


Old answer:

This is based on my PHP answer, and uses almost the same ways to make the squares:

for(i=51;i--;)document.write("<hr color=rgb("+[i,i,i]+") size=20 width=20>");

Not the shortest answer, but it's worth adding here.


This solution isn't compatible with Chrome (produces multiple green colors) and Firefox (same result, but produces circles? o.O WTH?)

Since this is code-golf, a solution working with a specific version or a specific software is acceptable.

Ismael Miguel

Posted 2015-02-16T01:30:52.100

Reputation: 6 797

2It might just be me, but running this code snippet produces mostly green and blue circles. I see @MartinBüttner beat me to this comment so it's not just me... – MrLemon – 2015-02-16T14:43:25.873

@MrLemon I guess chrome doesn't like RGB -.- But it does work on IE11. Since I'm not trying to make a cross-browser solution, this is acceptable. I will add this to the answer. – Ismael Miguel – 2015-02-16T15:06:54.233

@IsmaelMiguel That's alright I guess. But just for clarity, I'm on FF right now. Can confirm it working on IE11 though. – MrLemon – 2015-02-16T15:09:24.373

@MrLemon It works on IE11, since I tried at home. I can provide print-screen if required. Firefox makes circles with it. I have no f#$%ing idea how. There is no way to revert it. I was expecting IE to have the quirks, not Firefox. – Ismael Miguel – 2015-02-16T15:10:02.933

Firefox seems to put half-circles on the ends of <hr>, probably to make it look more smooth. No clue as to what happens with the colors. Anyway have my +1 for baffling me. – MrLemon – 2015-02-16T15:17:11.660

@MrLemon I'm speachless as well. I was quite happy with the final result. I came from home and found that Chrome doesn't like it :/ (and yes, I use IE at home. I must use IE :/ Sad sad life). But thank you for the +1. I will try to "baffle" (?) you again. – Ismael Miguel – 2015-02-16T15:20:47.893

@MrLemon I've made a new answer which doesn't produce weird colors on Chrome. – Ismael Miguel – 2015-02-16T16:13:56.140

@MartinBüttner I've updated the answer and no longer produces those weird colors. – Ismael Miguel – 2015-02-16T16:15:19.767

@MartinBüttner Actually, it was a SyntaxError. I've fixed it. Now it is showing and the byte count is the same. – Ismael Miguel – 2015-02-16T16:20:16.490

I am very tempted to downvote for passing on the opportunity to use the "goes to" operator: --i>9 should be i-->9 which is read "as i goes to 9". – corsiKa – 2015-02-17T21:46:29.470

@corsiKa What? o.O What are you talking about? – Ismael Miguel – 2015-02-17T21:47:38.517

Lol it was a joke. http://stackoverflow.com/questions/1642028/what-is-the-name-of-the-operator

– corsiKa – 2015-02-17T22:00:10.020

@corsiKa Oh, it makes sense.... I will try to get something to work. – Ismael Miguel – 2015-02-17T22:01:58.370

@corsiKa Better on this way? – Ismael Miguel – 2015-02-17T22:04:54.310

Hahaha awesome! It was a joke, but haha nice! – corsiKa – 2015-02-17T22:45:54.663

7

Matlab - 33 bytes

surf(meshgrid(1:7)),colormap gray

Despite the verbose commands, the result is still quite compact. It looks a bit better if you replace surf with surface but that costs 3 chars.

If you don't notice the 50th gray square that is because it is a bit bigger than the others!

Dennis Jaheruddin

Posted 2015-02-16T01:30:52.100

Reputation: 1 848

Use ndgrid! (2 bytes less). And, is each square a different gray? – Luis Mendo – 2015-02-22T21:04:24.680

7

Piet- 2*103 = 206

This is unique in that the source code and the output fulfill the challenge:

piet

Most of it is decorative, so I only counted the top two rows, which stand alone just fine. Outputs a grayscale ppm like some others have done.

captncraig

Posted 2015-02-16T01:30:52.100

Reputation: 4 373

6

JavaScript - 70 bytes

for(i=51;i-=1;)document.write('<a style=opacity:'+i/50+'>&#9632;</a>')

Sphinxxx

Posted 2015-02-16T01:30:52.100

Reputation: 179

6The box size is smaller than 20 pixel – edc65 – 2015-02-16T07:29:38.713

1Then you need to adjust your browser's font size ;) – Sphinxxx – 2015-02-16T09:22:49.633

1You have to use font:3em a or font-size:3em. I'm downvoting this one due to the size of the boxes. Until you fix. – Ismael Miguel – 2015-02-16T09:37:08.450

3You can use i-- instead of i-=1. – flawr – 2015-02-16T14:05:57.403

1You can use the <b> tag. It won't change the code in any way, except ensuring that the text will be black. This isn't a requirement, but it might be a good idea. – Ismael Miguel – 2015-02-16T15:44:41.397

@IsmaelMiguel what specification says b must be black? To my knowledge it inherits the font color… – idmean – 2015-02-21T22:17:38.533

@idmean The <a> tag usually has a different color. It may be blue with underline in some browsers. The <b> tag has the default black color. That is the only reason. – Ismael Miguel – 2015-02-22T00:03:36.957

6

PHP (62 60 63 72 71 62 59 bytes):

I've made the shortest I could find:

for($i=59;$i-->9;)echo"<hr color=$i$i$i size=20 width=20>";

This is exactly the same code as my Javascript answer (with 71 bytes).

But SO MUCH shorter!

This have a quirk in Firefox: instead of squares, Firefox makes circles! (Go insanity!)
Othen than that, all the browsers produce the right color (even with the missing # on the color attribute).


Invalid submits and changelog:

Old answer, with 62 bytes.

while($i++<51)echo"<hr color=rgb($i,$i,$i) size=20 width=20>";

All shades are perfectly aligned.

This solution won't work for Chrome (will produce squares with multiple colors) and Firefox (which makes circles o.O Yes, circles with <hr>! Horizontal ruler is a circle on Firefox!).
You can test it on IE11 and it should be fine.


(simply removed from above)

I've noticed something awful: It was outputting #111 instead of #010101 for some colors.

This meant that some colors were repeating.

Therefore, I had to sacrifice a few bytes:

<?while(f>$c=dechex(65-$i++))echo"<hr color=#$c$c$c size=20 width=20>";

Outputs the 50 shades in perfect order, from lighter to darker.

Due to a correct point made by @edc65, I had to add width=20, to produce perfect squares.

Reduced one more byte by replacing f!=$c with f>$c, which works perfectly.


Final version, without width=20:

<?while(f!=$c=dechex(65-$i++))echo"<hr color=#$c$c$c size=20>";

This is invalid because it is required to output squares.
This outputs the shades from lighter to darker.


Reduced 1 byte by switching to a while loop, like this:

<?while($c=dechex(50-$i++))echo"<hr color=#$c$c$c size=20>";

First solution:

<?for($i=50;$c=dechex($i--);)echo"<hr color=#$c$c$c size=20>";

This doesn't have the shades neatly ordered, but there are 50 different ones.

There is nothing stating that they must be ordered, but there is a requirement on size.

I hope I can reduce it a lot more.

You can test it on http://writecodeonline.com/php/ (click on "Display as HTML").

Ismael Miguel

Posted 2015-02-16T01:30:52.100

Reputation: 6 797

6

Processing, 66 characters:

size(1000,20);for(int i=0;i<981;i+=20){fill(i/4);rect(i,0,20,20);}

gray shades in Processing

Kevin Workman

Posted 2015-02-16T01:30:52.100

Reputation: 308

5

CSS (87 chars)

Uses animation ;)

:after{content:'\25A0';font:9em z;animation:g 8s steps(50)}@keyframes g{to{color:#fff}}

The runnable version is longer since Webkit still needs the vendor prefix. :(

:after{content:'\25A0';font:9em z;-webkit-animation:g 8s steps(50);animation:g 8s steps(50)}@-webkit-keyframes g{to{color:#fff}}@keyframes g{to{color:#fff}}

If we're allowed a random, empty <a> element, we can get it down to just 72 characters:

a{padding:3em;animation:g 8s steps(50)}@keyframes g{to{background:#000}}

See? CSS is a legit programming language!

Casey Chu

Posted 2015-02-16T01:30:52.100

Reputation: 1 661

4

PostScript, 34 bytes

In ISO-Latin-1 encoding:

20’›‡üˆì0{’81e3’6’–10’k0ˆ                   (note, this is a Line Feed)
’c’§}’H

This is the binary equivalent to:

20 setlinewidth 1020 -20 0 { dup 1e3 div setgray 10 moveto 0 10 lineto stroke } for

(This assumes that you are using it on a device that is at least 1000 points [= 10 inches = 25.4 cm] wide.)

AJMansfield

Posted 2015-02-16T01:30:52.100

Reputation: 2 758

Give us a series of hex encoded octets (ie: 0f 4e 75 a3 ...). – haneefmubarak – 2015-02-16T16:29:51.230

@haneefmubarak I will, I just need to get home so I can use my golfer program. (The online postscript compactor doesn't ever seem to work.) – AJMansfield – 2015-02-16T16:38:07.673

@haneefmubarak OK, updated with a direct representation of the file, although its not the hex octets. (I'll add that later once I can use the real converter program.) – AJMansfield – 2015-02-16T17:54:37.353

4

R, 36 bytes

I can make freekvd's answer shorter trivially.

x=9:59/59;symbols(x,sq=x,bg=gray(x))

Output

(Sorry for not making a comment under his solution. Stackexchange does not allow me to make comments, vote etc yet).

Met

Posted 2015-02-16T01:30:52.100

Reputation: 149

Doesn't this produce 51 squares? – MickyT – 2015-02-16T19:16:48.193

This makes the smallest square less than 20 pixels wide? It depends on your dpi, but the largest square is 1 inch so a 72 dpi image will have a smalllest square of 11 pixels. – freekvd – 2015-02-17T05:48:47.700

Though if you make it 1:99 you could argue that the 50 largest squares meet the criteria. – freekvd – 2015-02-17T05:50:14.257

4

C# - 173

Using LINQPAD

var b=new Bitmap(1000,20);var g=Graphics.FromImage(b);for(int i=0;i<50;i++)g.FillRectangle(new SolidBrush(Color.FromArgb(i*5,i*5,i*5)),new Rectangle(i*20,0,20,20));b.Dump();

Expanded:

var b = new Bitmap(1000, 20);
var g = Graphics.FromImage(b);
for (int i = 0; i < 50; i++)
    g.FillRectangle(new SolidBrush(Color.FromArgb(i * 5, i * 5, i * 5)), new Rectangle(i * 20, 0, 20, 20));
b.Dump();

Output:

output

jzm

Posted 2015-02-16T01:30:52.100

Reputation: 369

Suggestion: for(int i=0;i<250;i+=5) and then FromArgb(i,i,i) and Rectangle(i*4,0,20,20) gives 168 – Thomas Weller – 2015-03-05T23:05:43.740

Furthermore, FillRectangle() has an overload which takes the rectangle coordinates directly, so you can remove the new Rectangle() and get away with 153 – Thomas Weller – 2015-03-05T23:07:18.160

4

DrRacket - 83

Just for the sake of firing up DrRacket 1 year after "Introduction to Systematic Program Design".

EDIT:

(require htdp/image)(map(λ(i)(rectangle 50 50'solid(make-color i i i)))(range 50))

Ming-Tang

Posted 2015-02-16T01:30:52.100

Reputation: 5 383

Save a couple of characters: switch from 2htdp/image to htdp/image, change the string "solid" to the symbol 'solid. For bigger savings, change the (range 9 209 4) to (range 50): the shades of grey are just required to be distinct, not easy to tell apart for the human eye! – Omar – 2015-02-17T17:38:26.530

You can save a few characters using for/set: (require htdp/image)(for/set([i 50])(rectangle 50 50'solid(make-color i i i))) – Alexis King – 2015-02-22T10:31:32.063

4

JavaScript, 152 bytes.

Okay, so maybe this isn't the best solution but here is mine.

function b(a){c=document
e=c.createElement('p')
with(e.style){background="rgb("+[a,a,a]+")"
width=height="20px"}c.body.appendChild(e)
a<245&&b(a+5)}b(0)

Here is the output with css float left (just so it is easier to count the squares) and without:

with css float

without css float

Devon Taylor

Posted 2015-02-16T01:30:52.100

Reputation: 41

2You can save some bytes by using one-letter variable names, dropping all var keywords and removing unnecessary whitespace. Also, please include the language name and the byte count in your answer. – ProgramFOX – 2015-02-18T19:11:07.623

Thanks for the input. I reduced white space and added byte count but I'm not sure what you mean by dropping the var keywords. – Devon Taylor – 2015-02-18T19:28:02.093

Never mind. I feel dumb. – Devon Taylor – 2015-02-18T19:29:49.257

Use c+=5 instead of c=c+5. Also, you can save 2 chars by putting n=c.toString() at the end of the previous line, and then that line at the end of the previous line again. So your 2nd line would be function w(){if(c<250){n=c.toString() – mbomb007 – 2015-02-20T22:42:05.193

Also, I'm pretty sure you can omit px for the height and width. – mbomb007 – 2015-02-20T22:44:31.290

I've cut it down to 173 for you :) http://jsfiddle.net/87ofo7zx/

– Eric Lagergren – 2015-02-23T04:58:27.607

@eric_lagergren I've reduced it by 1 byte: http://jsfiddle.net/87ofo7zx/1/. And again, reduced to 169: http://jsfiddle.net/87ofo7zx/2/. And now to 166 bytes: http://jsfiddle.net/87ofo7zx/3/

– Ismael Miguel – 2015-02-23T12:17:57.180

@eric_lagergren Reduced once more to 162: http://jsfiddle.net/87ofo7zx/4/. And now again to 155: http://jsfiddle.net/87ofo7zx/5/

– Ismael Miguel – 2015-02-23T12:23:58.963

@eric_lagergren Sorry the spam, here is another one with 153 bytes: http://jsfiddle.net/87ofo7zx/6/ And 151: http://jsfiddle.net/87ofo7zx/7/

– Ismael Miguel – 2015-02-23T12:31:29.430

@Ismael Miguel awesome! Updated the post. – Devon Taylor – 2015-02-24T05:37:35.123

You're wellcome. I can try to see where I can reduce it a tiny bit more. – Ismael Miguel – 2015-02-24T09:12:39.620

3

R 45 42 characters

New version, after some comments (thanks!):

plot(1:50%%5,col=gray(1:50/60),ce=5,pc=15)

enter image description here

Old version

It generates an error, but works fine :)

plot(x<-1:50,x%%5,col=gray(x/60),lw=30,pc=22)

enter image description here

bartektartanus

Posted 2015-02-16T01:30:52.100

Reputation: 131

Those are not squares though, they’re circles. – Konrad Rudolph – 2015-02-17T21:14:17.930

Better now? :)) – bartektartanus – 2015-02-17T22:51:16.397

2,ce=3,pc=15 gives real squares and saves a character – koekenbakker – 2015-02-18T08:39:42.000

2You can shorten it further by replacing x<-1:50,x%%5 with 1:50%%5 and gray(x/60) with gray(1:50/60). Also, it seems to work with co instead of col. – freekvd – 2015-02-18T09:39:11.090

3

C++ Win32: 141 chars and 171 chars

C++ 171 chars

#include"stdafx.h"#include<windows.h>int _tmain(){HDC h=GetDC(0);for(int i=0;i<50;i++){SelectObject(h,CreatePen(0,9,RGB(64+i,64+i,64)));Rectangle(h,i*9,i*9,i*9+9,i*9+9);}}

This draws 50 grey boxes to your desktop.

Which is super long, but pretty good for actually drawing squares in C++. I doesn't think I was ever going to win/not-come-last but I'm pretty satisfied with this. I can't guarantee the whole pixel thing as I use coordinates, but IWOMM :D.

I don't know if win32 counts as a standard library of c++, but I was more interested in the win32 than the c++ tbh. I had a crack at GDI, which look prettier but is super verbose. I was hoping I could get a win32 ColorChooser and turn them all grey for instant victory, but alas no.

Here's the idea (I've removed the resource leak from this extended version):

#include "stdafx.h"
#include <windows.h>
int _tmain(int a, _TCHAR* b[])
{
   HDC h=GetWindowDC(GetDesktopWindow()); //Zero works for GetDesktopWindow() as  Konrad Rudolph points out. GetDC is a good as GetWindowDC.
   for (int i = 0; i < 50; i++){
       HPEN p = CreatePen(PS_COSMETIC, 9, RGB(64 + i, 64 + i, 64)); //PS_COSMETIC is 0
       SelectObject(h, p); MoveToEx(h, 0, 0, NULL); //We can get away with removing MoveToEx and assuming it starts in the top left
       Rectangle(h, i * 9, i * 9, i * 9 + 9, i * 9 + 9); DeleteObject(p);
   }
   DeleteDC(h); //Or was it releaseDC? Who cares. The golf'd code leaks it anyway.
}

enter image description here

Also this can happen. When you want to get rid of it you just 'wipe' it away with another window. You would also not believe how slow this is to execute. Output

Konrad Rudolph's comment: C++ 141

// stdafx.h isn’t needed.
// However, we DO need the line break after the include,
// even in the golf version.
#include <windows.h>
// _tmain => main; VC++ accepts both.
int main()
{
   HDC h = GetDC(0);
  // Remove i++ here …
  for (int i = 0; i < 50;){
  // 65793 == 0x010101; multiplying with 1…50 generates
  // grey tones and is much shorter than RGB macro use
  SelectObject(h, CreatePen(0, 9, i*65793));
  // i * 9 + 9 == i * 10
  // … add i++ here.
  Rectangle(h, i * 9, i * 9, i * 10, i++ * 10);
  }
}

short.cpp

#include <windows.h>
int main(){HDC h=GetDC(0);for(int i=0;i<50;){SelectObject(h,CreatePen(0,9,i*65793));Rectangle(h,i*9,i*9,i*10,i++*10);}}
//141 with the line break

Nathan Cooper

Posted 2015-02-16T01:30:52.100

Reputation: 617

I vaguely remember that it sometimes worked to use 0 instead of the Desktop DC (or was it the hWND?). However, that’s definitely not kosher and it might not work any more (it never worked reliably, as far as I remember). – Konrad Rudolph – 2015-02-18T11:30:18.410

@KonradRudolph Good trick. Apparently in WinUser.h it defines: #define HWND_DESKTOP ((HWND)0) and MapWindowPoints doco seems to suggest HWND_DESKTOP and NULL are both kosher. However, obviously outside of golfing using 0 would be horrible. Also, I've just noticed GetDCis just as good as GetWindowDC

– Nathan Cooper – 2015-02-19T15:11:40.653

1

You can make this much shorter actually. Since it’s too much for a comment, I’ve created a gist with the changes: https://gist.github.com/klmr/864a87d25c048736a11f – Result: 140 characters. There’s probably more room for improvement if you accept different colours/positions, by choosing colours and positions so that fewer computations are necessary. But then, according to the rules the squares probably shouldn’t overlap and be larger.

– Konrad Rudolph – 2015-02-19T15:37:19.370

1Okay. Wow. (You could tweet that now). Good stuff, thanks for the link. Thinking back, I should have seen that having macros probably means that the code isn't effectively golfed. I hope you don't mind if I add an attributed section. – Nathan Cooper – 2015-02-19T15:55:20.807

3

Pyth - 23 21 bytes

Is similar to CJam solution. Outputs is PGM format, save output as foo.pgm and view here. Edited it to make it conform to PGM specs so that lines are less than 70 chars long, in fact they are only one pixel long.

K50"P2"*KKKKVKjbS*UKK

Generates: Is fifty fifty by fifty squares. Goes from black to 49/50 of the way to white.

K50             K=50
"P2"            Prints P2 or pgm header magic #
*KK             Prints the length: 50*50
K               Prints width: 50
K               Prints value of white: 50
V         K     Do 50 times to make height of square 50
 j              joins by
  b             linebreaks
   S            Sort to bring out make each shade consecutive
    *  K        Times 50 to make length 50
     UK         Unary range 50 (0-49)

Maltysen

Posted 2015-02-16T01:30:52.100

Reputation: 25 023

1So you include black as a shade of grey? – aditsu quit because SE is EVIL – 2015-02-19T06:51:36.670

@aditsu is that not allowed? The only reason I didn't include white was because range(50) only goes up to 49. – Maltysen – 2015-02-19T17:34:21.690

I'm not sure, but I excluded it. Otherwise I can also get 21 bytes. I guess I should ask... – aditsu quit because SE is EVIL – 2015-02-19T18:41:28.560

@aditsu yeah it takes me 22 to get not black, replace UK with R1K – Maltysen – 2015-02-19T23:21:09.060

3

R - 35 characters

Barplot uses gray.colors by default, helpful to save some bytes. To make sure the size is sufficient regardless of the screen size, the window size has to be defined beforehand, with x and y size picked as to generate a 1:1 aspect ratio.

x11(,1.7,23);barplot(matrix(1,50))

Output, rotated 90° and sized down:

enter image description here

As per comments below, the x11() results vary between machines. Hence, a safer option - also forcing aspect ratio of 1 - is dev.new. Run from terminal:

dev.new(height=20);barplot(matrix(1,50),as=1) 

That's 46 characters. If manual resizing is allowed, barplot(matrix(1,50),as=1) is enough - only 27 characters.

koekenbakker

Posted 2015-02-16T01:30:52.100

Reputation: 141

The x11 doesn’t actually yield reliable results. On my OS X the code doesn’t produce squares anyway. Just remove it. As far as I’m concerned, barplot(matrix(1,50)) is the shortest valid R code so far. 21 characters. It’s just a shame that rep(1,50) doesn’t work in place of matrix; t(t(rep(1,50)) does, but it’s longer. – Konrad Rudolph – 2015-02-18T11:38:32.483

You're right. Worked fine on my Linux machine, but not so on Windows. Added an alternative avoiding this. – koekenbakker – 2015-02-18T12:08:01.277

xcode-select: note: no developer tools were found at '/Applications/Xcode.app', requesting install. Choose an option in the dialog to download the command line developer tools. Error in x11(h = 20) : X11 module cannot be loaded. I can't use this on OSX :( – freekvd – 2015-02-18T18:47:44.190

I have provided a longer alternative, hope that works across platform – koekenbakker – 2015-02-18T20:53:48.490

3

HTML/CSS - 81 characters

This is a very borderline solution because the shades aren't displayed very accurately (Chrome and Firefox both just use dithering), but in theory it "should" display 50 distinct shades. Also, the code is probably not very W3C compliant, but it compiles on any browser that knows CSS3.

<div style="height:1000px;width:20px;background:linear-gradient(#000,#303030);"/>

Note that 0x30 is 50 and 1000 is 50*20.

Jack M

Posted 2015-02-16T01:30:52.100

Reputation: 221

3

C (73 65 characters)

Outputs a binary PGM to stdout, 20x20 squares.

s;main(){puts("P5 1000 20 50");while(s<2e4)putchar(s++%1000/20);}

Moar tricks would have been possible with 2^n instead of 50 shades, but nevermind.

Stefano Sanfilippo

Posted 2015-02-16T01:30:52.100

Reputation: 1 059

2

CoffeeScript, 86 bytes

As per edc56's comment on the JavaScript solution:

i=90;document.write '<p style=background:#'+i+i+i--+';height:1em;width:1em>'while i>40

rink.attendant.6

Posted 2015-02-16T01:30:52.100

Reputation: 2 776

2

Python 2, 78 characters

This prints an image in PGM format to standard output (I took the idea from aditsu's CJam answer):

print"P2 2500 50 51"
r=range(50)
for x in r:
 for y in r:
  for z in r:print y

I wish Python would let me put all 3 fors on the same line. At least it lets me use a single space (or single tab) for each indentation level. I tried using variants of for t in itertools.product(r,r,r) instead, but the import is long and kills the benefit.

Omar

Posted 2015-02-16T01:30:52.100

Reputation: 1 154

Thanks, @KSFT! I forgot my editor adds (and counts) a final newline automatically. – Omar – 2015-02-17T19:14:36.997

you can save a byte trivially by indenting your last line with one tab instead of two spaces – undergroundmonorail – 2015-02-18T03:25:11.997

1

Mathematica, 20 characters

ArrayPlot@{Range@50}

gives the following output:

ArrayPlot@{Range@50}

Thomas

Posted 2015-02-16T01:30:52.100

Reputation: 127

2I deliberately did not post this, because you need to scale up the result manually in order to make the squares 20 pixels on a side. The default size is much smaller than that. – Martin Ender – 2015-02-17T18:53:39.223

This is a good point... – Thomas – 2015-02-17T20:22:48.737

Isn't that the same as ArrayPlot[Range@50], which is one character shorter? – Omar – 2015-02-17T21:32:21.653

@Omar No, ArrayPlot needs a 2-dim array. In your case it is 1-dim. – Thomas – 2015-02-17T21:34:30.347

Oh, sorry, I misread the first @ as @@. Ignore my comment. – Omar – 2015-02-17T21:48:51.550

1

enter image description here

A basic javaScript code is given by:

<script>
"use strict";
var Div=null;
window.onload=function ()
{
 Div=document.getElementsByTagName("div")[0];
 var c=150,n=0,p=null;
 do {
     p=document.createElement("p");
     p.style.backgroundColor="rgb(" + c + "," + c + "," + c + ")";
     Div.appendChild(p);
     if ( ++n<50 ) c+=2; else break;
 } while ( true );
};
</script>

Felix Marin

Posted 2015-02-16T01:30:52.100

Reputation: 111

5

Welcome to the site. You should make some attempt to actually golf your answer (that means make it as short as possible). After you are done with that, tack on a header like #HTML - X Characters where X is the length of your code, including newlines and other whitespace. Lettercount.com works fine if you wrote your code in ASCII (which you did). Read the tag wiki for [tag:code-golf] for a better explanation. Check out the other answers to get an idea of what yours should look like.

– Rainbolt – 2015-02-18T02:08:07.130

@Rainbolt Thanks. I'll check it by following your advice. – Felix Marin – 2015-02-18T02:09:47.583

1The question asks to output squares, but from your image it looks like you output rectangles. – ProgramFOX – 2015-02-18T07:18:27.753

@ProgramFOX Thanks. Maybe I didn't read it carefully. I'll check everything a little bit later. – Felix Marin – 2015-02-19T20:29:44.823

1

Haskell 133

import Data.List
r=replicate 20
f 0=""
f i=(f(i-1))++(concat$r$'\n':(intercalate " "$r$show i))
main=putStr $"P2\n20 1000\n50"++f 50

outputs in Netpbm Format to stdout

HEGX64

Posted 2015-02-16T01:30:52.100

Reputation: 313

1

FFmpeg, 61 bytes

ffplay -f lavfi color=s=1000x20,format=y8,geq=8+4*trunc(X/20)

enter image description here

Gyan

Posted 2015-02-16T01:30:52.100

Reputation: 521

0

Excel VBA, 60 Bytes

Anonymous VBE immediate window function that takes no input and outputs to the range [A1:A50] on the ActiveSheet object

For i=1To 50:j=5*i:Cells(i,1).Interior.Color=RGB(j,j,j):Next

Taylor Scott

Posted 2015-02-16T01:30:52.100

Reputation: 6 709

0

Javascript (60 char)

for(i=51;i--;)document.write("<hr color="+i+i+i+" size=20>")

Motocarota

Posted 2015-02-16T01:30:52.100

Reputation: 129

8These don't look very square to me. (in Chrome) – Martin Ender – 2015-02-17T10:04:31.857

2@MartinBüttner There are definitely squares. There are just also round parts. There's no rule against extra output. – KSFT – 2015-02-17T16:47:26.930

4@KSFT I see rectangles. – Martin Ender – 2015-02-17T16:49:30.193

Okay, there are rectangles, too. There are still squares, just with long rectangles and round things on the ends. Do you see something like this? http://imgur.com/faT4CD4 I see squares in these places: http://imgur.com/ZD7hxHe

– KSFT – 2015-02-17T16:55:43.720

1

@KSFT I think this falls under this standard loophole. The question asks for 50 squares, not for squares embedded in arbitrary shapes.

– Martin Ender – 2015-02-17T18:58:14.197

@MartinBüttner If extra output weren't allowed, then a lot of other answers would be disqualified. – KSFT – 2015-02-17T19:02:41.743

2@KSFT I didn't say they shouldn't be. But still, IMHO, just printing arbitrary shapes and saying there's a square in there is a lot more cheating than printing 50 squares, and also plotting axes or something like that. – Martin Ender – 2015-02-17T19:04:29.303

@MartinBüttner I disagree. It's just extra output, and fifty different shades are still being drawn. – KSFT – 2015-02-17T19:07:52.720

0

Python, 72 bytes

print'P2 1000 20 50 '+20*(''.join([20*(str(x)+' ')for x in range(50)]))

Another PPM answer, usage:

python golf_grey.py > grey.ppm

Karl Napf

Posted 2015-02-16T01:30:52.100

Reputation: 4 131