text:
Compress an image to a 4 KiB preview
In this challenge you will be creating an image preview compression algorithm. It's goal is to
reduce an arbitrary image file to a 4 KiB preview image, that can be used to quickly identify images
with very little bandwidth.
You must write two programs (or one combined program): a compressor and a decompressor. Both must
take a file or stdin as input, and output to a file or stdout. The compressor must accept one image
in a mainstream lossless image format of choice (e.g. PNG, BMP, PPM), and output a file of at
most 4096 bytes. The decompressor must accept any file generated by the compressor, and output an image as close as possible to the input. Note that there is no source code size limit for the encoder/decoder, so you
can be creative in your algorithm.
Restrictions:

No 'cheating'. Your programs may not use hidden inputs, storing data on the internet, etc. You are
also forbidden from including features / data pertaining only to the set of scoring images.

For libraries / tools / built-ins you are allowed to use generic image processing operations
(scaling, blurring, color space transformation, etc), but not image decoding / encoding /
compression operations (except for compressor input and decompressor output). Generic compression / decompression is also disallowed. It is intended
that you implement your own compression for this challenge.

The dimensions of the image output by the decompressor must exactly match those of the original
file given to the compressor. You may assume that the image dimensions do not exceed
216 in either direction.

Your compressor must run on an average consumer PC in under 5 minutes, and the decompressor must
run in under 10 seconds for any image in the set below.

Scoring
To help quick verification and visual comparison, please include a lossless image album of the test corpus after compression using your answer.
Your compressor will be tested using the following corpus of images:

You can download all images in a zip file here.
Your score will be the average structural similarity index for your compressor on all the images. We will be using the open source dssim for this challenge. It is easily built from source, or if you're on Ubuntu it also has a PPA. It is preferred if you score your own answer, but if you do not know how to build C applications and you do not run Debian/Ubuntu, you can let someone else score for you. dssim expects input/output in PNG, so convert your output to PNG first if you output in a different format.
To make scoring painless, here's a quick helper Python script, usage python score.py corpus_dir compressed_dir:
import glob, sys, os, subprocess

scores = []
for img in sorted(os.listdir(sys.argv[1])):
    ref, preview = (os.path.join(sys.argv[i], img) for i in (1, 2))
    sys.stdout.write("Comparing {} to {}... ".format(ref, preview))
    out = subprocess.check_output(["dssim", ref, preview]).decode("utf-8").split()[0]
    print(out)
    scores.append(float(out))

print("Average score: {:.6f}".format(sum(scores) / len(scores)))

Lowest score wins.

does the compressed picture have to be viewable?

@Eumel You can consider the decompressor as a viewer. So no, your compressed format can be arbitrary and is entirely up to you. Only after decompression a viewable image has to come out.

You may assume that the image dimensions do not exceed 2^32 in either direction. Isn't this a little excessive? This means I have to use up 16 bytes to store a pair of (x,y) coordinates. Few image files have dimensions of more than 2^16 (65536) pixels in either direction, and 2^11 is sufficient for all the images in the corpus.

@PeterOlson I'll change it to 2^16.

@orlp The rules state that the decompressor must take less than ten seconds to decode an image. The idea I have will potentially take a few minutes to generate reference files that will be used in subsequent calls to the decompressor. i.e. it is a once off activity similar to "installing" an application. Would this solution be disqualified?

@Moogie That is allowed iff those reference files are unrelated to any of the image files in the corpus.

@orlp well yes, they will be related... i.e. it would create data used for the compression of the files, however they will not be derived from the files at all... (if i could generate the image files then i would do so directly :P )

Is the 5-minute rule for the compression for any single image, or for the entire corpus?

@Mego Single image.

To be a bit pedantic DSSIM actually measures dis-similarity : 1/SSIM - 1, but as you can see it is very related to SSIM. For a good match, SSIM values should be close to 1 and DSSIM should instead be close to 0. However dis-similarity does not have any upper bound as SSIM can get arbitrarily close to 0.

Am I allowed to make a 1x1 pixel preview image?

@12Me21 No. "The dimensions of the image output by the decompressor must exactly match those of the original file given to the compressor. You may assume that the image dimensions do not exceed 216 in either direction."

Python with PIL, score 0.094218
Compressor:
#!/usr/bin/env python
from __future__ import division
import sys, traceback, os
from PIL import Image
from fractions import Fraction
import time, io

def image_bytes(img, scale):
    w,h = [int(dim*scale) for dim in img.size]
    bio = io.BytesIO()
    img.resize((w,h), Image.LANCZOS).save(bio, format='PPM')
    return len(bio.getvalue())

def compress(img):
    w,h = img.size
    w1,w2 = w // 256, w % 256
    h1,h2 = h // 256, h % 256
    n = w*h
    total_size = 4*1024 - 8 #4 KiB minus 8 bytes for
                            # original and new sizes
    #beginning guess for the optimal scaling
    scale = Fraction(total_size, image_bytes(img, 1))
    #now we do a binary search for the optimal dimensions,
    # with the restriction that we maintain the scale factor
    low,high = Fraction(0),Fraction(1)
    best = None
    start_time = time.time()
    iter_count = 0
    while iter_count < 100: #scientifically chosen, not arbitrary at all
        #make sure we don't take longer than 5 minutes for the whole program
        #10 seconds is more than reasonable for the loading/saving
        if time.time() - start_time >= 5*60-10:
            break
        size = image_bytes(img, scale)
        if size > total_size:
            high = scale
        elif size < total_size:
            low = scale
            if best is None or total_size-size < best[1]:
                best = (scale, total_size-size)
        else:
            break
        scale = (low+high)/2
        iter_count += 1
    w_new, h_new = [int(dim*best[0]) for dim in (w,h)]
    wn1,wn2 = w_new // 256, w_new % 256
    hn1, hn2 = h_new // 256, h_new % 256
    i_new = img.resize((w_new, h_new), Image.LANCZOS)
    bio = io.BytesIO()
    i_new.save(bio, format='PPM')
    return ''.join(map(chr, (w1,w2,h1,h2,wn1,wn2,hn1,hn2))) + bio.getvalue()

if __name__ == '__main__':
    for f in sorted(os.listdir(sys.argv[1])):
        try:
            print("Compressing {}".format(f))
            with Image.open(os.path.join(sys.argv[1],f)) as img:
                with open(os.path.join(sys.argv[2], f), 'wb') as out:
                    out.write(compress(img.convert(mode='RGB')))
        except:
            print("Exception with {}".format(f))
            traceback.print_exc()
            continue

Decompressor:
#!/usr/bin/env python
from __future__ import division
import sys, traceback, os
from PIL import Image
from fractions import Fraction
import io

def process_rect(rect):
    return rect

def decompress(compressed):
    w1,w2,h1,h2,wn1,wn2,hn1,hn2 = map(ord, compressed[:8])
    w,h = (w1*256+w2, h1*256+h2)
    wc, hc = (wn1*256+wn2, hn1*256+hn2)
    img_bytes = compressed[8:]
    bio = io.BytesIO(img_bytes)
    img = Image.open(bio)
    return img.resize((w,h), Image.LANCZOS)

if __name__ == '__main__':
    for f in sorted(os.listdir(sys.argv[1])):
        try:
            print("Decompressing {}".format(f))
            with open(os.path.join(sys.argv[1],f), 'rb') as img:
                decompress(img.read()).save(os.path.join(sys.argv[2],f))
        except:
            print("Exception with {}".format(f))
            traceback.print_exc()
            continue

Both scripts take input via command line arguments, as two directories (input and output), and convert all images in the input directory.
The idea is to find a size that fits under 4 KiB and has the same aspect ratio as the original, and use a Lanczos filter to get as high of a quality out of the downsampled image as possible.
Imgur album of compressed images, after resizing to original dimensions
Scoring script output:
Comparing corpus/1 - starry.png to test/1 - starry.png... 0.159444
Comparing corpus/2 - source.png to test/2 - source.png... 0.103666
Comparing corpus/3 - room.png to test/3 - room.png... 0.065547
Comparing corpus/4 - rainbow.png to test/4 - rainbow.png... 0.001020
Comparing corpus/5 - margin.png to test/5 - margin.png... 0.282746
Comparing corpus/6 - llama.png to test/6 - llama.png... 0.057997
Comparing corpus/7 - kid.png to test/7 - kid.png... 0.061476
Comparing corpus/8 - julia.png to test/8 - julia.png... 0.021848
Average score: 0.094218

I just realized that your solution uses WebP, which is disallowed. Your solution is invalid.

@orlp It's fixed now to use PPM, which is an uncompressed format.

Alright. This challenge does expose quite a bit weakness of DSSIM though. I would argue that most of Moogie's images look substantially better.

@orlp They look good as thumbnails. When blown up to their original dimensions (using Lanczos), they look about the same quality or worse. I'm working on getting thumbnails of my output uploaded.

Java (vanilla, should work with java 1.5+), score 0.672
It does not generate particularly good dssim scores but, to my eye it produces more human friendly images...

Album: https://i.stack.imgur.com/ZU3hc.jpg
Scoring script output:
Comparing corpus/1 - starry.png to test/1 - starry.png... 2.3521
Comparing corpus/2 - source.png to test/2 - source.png... 1.738
Comparing corpus/3 - room.png to test/3 - room.png... 0.1829
Comparing corpus/4 - rainbow.png to test/4 - rainbow.png... 0.0633
Comparing corpus/5 - margin.png to test/5 - margin.png... 0.4224
Comparing corpus/6 - llama.png to test/6 - llama.png... 0.204
Comparing corpus/7 - kid.png to test/7 - kid.png... 0.36335
Comparing corpus/8 - julia.png to test/8 - julia.png... 0.05
Average score: 0.672

The compression chain:
1. if filter data has already been generated goto step 6
2. create sample images from random shapes and colours
3. take sample patches from these sample images
4. perform k-clustering of patches based on similarity of luminosity and chomanosity.
5. generate similarity ordered lists for each patch as compared to the other patches.
6. read in image
7. reduce image size to current multiplier * blocksize
8. iterate over image comparing each blocksize block against the list of clustered luminosity patches and chromanosity patches, selecting the closest match
9. output the index of the closet match from the similarity ordered list (of the previous block) (repeat 8 for chromanosity)
10. perform entropy encoding using deflate.
11. if output size is < 4096 bytes then increment current multiplier and repeat step 7
12. write previous output to disk.

To decompress, inflate and then read the block indexes and output the corresponding patch to the output file, then resize to the original dimensions.
Unfortunately the code is too large for stackoverflow so can be found at https://gist.github.com/anonymous/989ab8a1bb6ec14f6ea9
To run:
Usage:
       For single image compression: java CompressAnImageToA4kibPreview -c <INPUT IMAGE> [<COMPRESSED IMAGE>]
       For multiple image compression: java CompressAnImageToA4kibPreview -c <INPUT IMAGES DIR> [<COMPRESSED IMAGE DIR>]
       For single image decompression: java CompressAnImageToA4kibPreview -d <COMPRESSED IMAGE> [<DECOMPRESSED IMAGE>
       For multiple image decompression: java CompressAnImageToA4kibPreview -d <COMPRESSED IMAGE DIR> [<DECOMPRESSED IMAGES DIR>]

If optional parameters are not set then defaults will be used:
       For single image compression, compressed image will be created in same directory are input image and have '.compressed' file extension.
       For multiple image compression, compressed images will be created in a new 'out' sub directory of <INPUT IMAGES DIR> and have '.compressed' file extensions.
       For single image decompression, decompressed image will be created in same directory are input image and have '.out.png' file extension.
       For multiple image decompression, decompressed images will be created a new 'out' sub directory of <COMPRESSED IMAGE DIR> and have '.png' file extensions.

The first time this application is run, required files will be generated and saved in a directory relative to execution working dir. This may take a few minutes. For subsequent executions, this step will not need to be performed.

This looks amazing. Just to confirm, steps 1-6 do not rely on the corpus at all? Also, would you mind if I rehost your code on gist.github.com instead?

Correct, does not use any of the corpus files as input. you can see the images it produces to generate the patches buy changing the constant "OUTPUT_SAMPLE_IMAGES" to true. It will output these images to the working folder: data/images/working/

@orlp now using gist.github

The results are stunning, but doesn't using deflate/inflate break the rule about disallowing generic compression/decompression?

@algmyr It has been a while, but i think i had interpreted the no generic compression rule as meaning no generic 'image' compression... i.e. jpeg, etc. But I may have interpreted that incorrectly, in which case, yes, this submission should be diqualified.


text:
Official Dyalog APL 2016 Year Game
If you think this could be fun, but too much work, consider participating in this much smaller challenge.

A bit of fun (and possibly frustration!) for 2016... Dyalog's "puzzle of the year". Enjoy!
The Objective
Find Dyalog APL (download) expressions (other languages are allowed, see Eligibility below) involving exactly the digits 2 0 1 6 in that order to equal the numbers 0 to 100. For example:
20=16
×2016
2⌊016
2+0+1*6
...
The aim is to use as few characters as possible in each expression (the minimum number of characters for an expression is 5 – the four digits 2 0 1 6 and a single primitive function/operator).
The Rules

Each expression must contain the digits 2 0 1 6 (in that order) and
no other digits. Pre-set constants and variables are also not allowed.
In addition to the four digits 2 0 1 6, only built-in symbols and names, parentheses/braces, spaces, high minus signs and
decimal points can be used. The resultant expressions must be
deterministic (that is, give the same result on repeated
evaluations). For non-APLs, functions/operators with a name are also allowed; same rules as here.
Assume all default settings for your language. For Dyalog APL, this means ⎕ML and ⎕IO are both 1, and ⎕PP is 10.
Each entry comprising correct expressions for all the numbers from 0
to 100 inclusive will be rated according to the number of characters
used by those expressions excluding redundant spaces (minimum 505 for
all 101 expressions).

Eligibility
Anyone can enter. You may answer in any language, but only APL answers will be considered for accepting. If you use another language than APL, you may use snippets, programs, functions, etc. as alternatives to expressions, and you may print, leave the number in an accessible memory location, or otherwise return the result, as long as your code directly evaluates to the desired number as any standard numeric data type for your language.
Closing Date
30 November 2016.
Prizes

Have your answer accepted
Be immortalised in Dyalog's 2016 Hall of Fame!

Submitting Your Entry
After 30 November 2016, I will accept the shortest answer, and submit your answer, in your name, to Dyalog's 2016 Hall of Fame.
FAQ

Is J (e.g. 37=⌈⍟!20J16) allowed?
No: In addition to the four digits 2 0 1 6, only only built-in symbols and names, parentheses/braces, spaces, high minus signs and decimal points can be used.

Is output as a string acceptable?
No: equal the numbers 0 to 100.

Physical digits, or data digits?
Data digits, as per OP: same rules as here, where one of the examples contain LOG10(.

Is assigning variables then using them as part of the expression (e.g. 56=a+16+a←20) allowed?
Yes, but you may not use an assignment from one expression in another one.

I have explicit written permission to post this challenge here from the original author of this challenge. Feel free to verify by following the provided link and contacting the author. I gave the original competition author the link to this page within the minute I posted it, so they can check if I submit someone's answer as my own.

Related: http://codegolf.stackexchange.com/q/48917/34718

So many answer and no one APL solution?

@ChristianIrwan Right, that is to be expected: anyone doing it in APL may rather want to submit to the real competition instead of revealing his secrets here.

@Adám, this might be late, but would using ⎕ML and ⎕IO (assumed to be 1) be acceptable?

@ZacharyT You mean putting quad names into the expression? Sounds like a lot of extra characters for little win. Can you give me an example?

⎕IO+20+16 for 37.

@ZacharyT Same count, no question: 20(++≠)16

Sorry, bad example. ⎕PP+20∧1⊢6 for 70.

@ZacharyT Yes, that is ok. I've updated OP.

Just to be sure, that would be acceptable for the actual Dyalog submission, correct? Nothing of ⎕PP was specified http://dyalog.com/2016-year-game.htm

Yes, I asked my colleague in charge of the the official competition. Btw, ⎕PP=10, not 6 as on TryAPL.

Float acceptable?

@null Yes. (Indeed, in APL, there's no difference.)

Jelly, 686 bytes
20=16
20>16
2+0%16
201%6
20%16
20%16‘
201a6
20>1+6
20%16Ḥ
2016DS
20Ho16
2016BL
20:1.6
20_1_6
20×1_6
20+1_6
20&16
20:+16
2+0+16
20+1^6
20|16
20|16‘
20|16‘‘
20%16!’
20%16!
20²:16
20H+16
20+1+6
20×1_6Ḥ
20×1_6Ḥ‘
20+1_6Ḥ
2016&½’
2016&½
201:6
201:6‘
20Cạ16
20+16
20+16‘
20+1^6Ḥ
20|16Ḥ’
20|16Ḥ
20|16Ḥ‘
20|16‘Ḥ
2016½Ḟ’
2016½Ḟ
2016½Ċ
2016½Ċ‘
20Ḥ+1+6
2r0×16S
201a6‘²
20²:16Ḥ
2r016+S
201ÆC+6
20&16ÆN
20H_1×6
20ạC+16
20Ḥ+16
20_1×6H
20_1×6H‘
20_1×6H‘‘
20+1_6ḤḤ
2+0+16ÆN
20:.16H
20+1×6H
2²+0×16
201:6Ḥ’
201:6Ḥ
201Ḥ:6
201Ḥ:6‘
20Cạ16Ḥ’
20Cạ16Ḥ
20+16Ḥ’
20+16Ḥ
20+16Ḥ‘
20+16Ḥ‘‘
20+ÆN_16
20+1^6ḤḤ
20+1^6ḤḤ‘
20×16HH’’
20×16HH’
20×16HH
20×16HH‘
20|16Ḥ‘Ḥ
20|16Ḥ‘Ḥ‘
20|16‘ḤḤ
201½×6Ḟ
201½×6Ċ
20ÆN+16
2016½ḞḤ
20Æn16¡
20r16S
20r16S‘
20r16S‘‘
20Ḥ+1+6Ḥ’
20Ḥ+1+6Ḥ
20ḤḤ+16’
20ḤḤ+16
20ḤḤ+16‘
201a6‘²Ḥ
201’Ho6’
201’Ho6

I wrote about 50 of these, then autogenerated the rest by appending Ḥ (×2) and ‘’ (±1) as needed. I’ll improve them later!

46 can become 201ÆCo6. I don't think you can use Ṿ (which was implemented in February), but 20|16Ḥ‘Ḥ and 20|16‘ḤḤ’ are equally short.

@Dennis Oops, my Python script actually erroneously preferred Ḥ over ‘’ – 46, among with four other numbers, should have been one character shorter. I’ve replaced it with 2016½Ċ‘ which is as long as yours.

Hexagony, 888 bytes
Okay, first some ground rules for Hexagony, in case anyone wants to beat this:

I'm interpreting "snippet" as a linear piece of code that can be dumped into any sufficiently large program, provided the current and adjacent memory edges are zero.
The snippet has to be entered from the left and exited from the right. I'd be able to save quite a bunch of bytes without that (e.g. 2|016 for 22), but it seems most in the spirit of the challenge.
The snippet "produces" a given number, if any memory edge (not necessarily the current one) holds that value after execution.
The rule forbidding any other numbers in the snippet affects both other digits as well as any letters, since they effectively act as integer literals in Hexagony. (Those would save a ton of bytes.)

So here is the list. I did test most of them but not all (some are trivial modifications of others), so I hope I didn't make any mistakes:
2016
20&1}6
2}016
2)}016
20{16'-
201}6(
201}6
201}6)
2}016":
2(0(}16
2(0}16
2(0)}16
)2}016
)2)}016
20}16((
20}16(
20}16
20}16)
20}16))
20(}16
20}16
20)}16
20))}16
20)))}16
20}1)6((
20}1)6(
20}1)6
20}1)6)
201{6)':
2)0(}16
2)0}16
2)0)}16
2{016'*
201{6':
2{016)'*
20}1))6(
20}1))6
20}1))6)
20}1))6))
2))0(}16
2))0}16
2))0)}16
2))0))}16
2))0)))}16
20)){1)'6*
2){016('*
2){016('*)
2){016'*(
2){016'*
2){016'*)
2)))0}16
2){016)'*
2){016)'*)
2{01)6)'*(
2{01)6)'*
2{01)6)'*)
2{01)6)'*))
2{01)6)'*)))
2))))0((}16
2))))0(}16
2))))0}16
2))))0)}16
2)0){1)'6*
2)){016'*(
2)){016'*
2)){016'*)
2)){016'*))
2)){016'*)))
2{01))6('*(
2{01))6('*
2{01))6'*((
2{01))6'*(
2{01))6'*
2{01))6'*)
2{01))6)'*
2){01)6('*
2){01)6'*((
2){01)6'*(
2){01)6'*
2){01)6'*)
20{1)))'6*
2){01)6)'*
2){01)6)'*)
2){01)6)'*))
2){01)6))'*
2){01)6))'*)
2){01)6))'*))
2){01)6)))'*
2{01)))6(('*
2{01)))6('*(
2{01)))6('*
2{01)))6'*(
2{01)))6'*
2{01)))6'*)
2{01)))6)'*
2{01)))6)'*)
2{01)))6))'*
2(01((((}16
2(01(((}16
2(01((}16
2(01(}16

I got a bit lazy towards the end, so I'm sure this isn't optimal. Might be interesting (and possible) to brute force these.

Very nice. Remember you have 10 months (or forever, really) to improve this. I suppose Hexagony has few enough commands that brute-forcing is reasonable. It took me a week of 100% single-core usage to brute-force 4 inserted APL chars.

So you have done it? Did you get an optimal solution?

@NBZ Since incrementing and decrementing the result is always possible, for a single byte it might be easiest for Hexagony to check programs for any numbers (instead of one number at a time), and if I find something shorter than the current best for that number and can shorten that and potentially a few numbers around it as well. And yes, once you remove the digits and letters (and some other characters that are useless here) it should be quite brute forcible.

@jimmy23013 Almost done. Missing the optimal solution for two out of the 101 numbers.

@NBZ You only have to brute-force 4 character solutions to prove there isn't such a solution. I think it's likely you can write a 5 character solution by hand and that would be optimal.

@jimmy23013 Right, but hand-writing those two 5-char expressions may be hard. Some of the 4-char exprs are rather "ingenious", like 85=2⊥⍒01⍕¯6...

@NBZ I had a lot of exprs just by stacking Pi... for example, ⌈○20+1+6.

@jimmy23013 Yes, most numbers are easy to find using ⌈⌊+-○*. The remaining ones are interesting.

@jimmy23013 One of my colleagues at Dyalog did exactly that. He keeps asking me if I found 5-char solutions to the last two...

Is there really a reason to restrict winning answers to APL only? There doesn't seem to be one, and there isn't a single APL answer so far.

J, 1041 ... 838 bytes
981 961 952 860 859
I got a little lazy to the end, but it should be more fixed than less. I don't think I'll ever overtake Hexagony, but you never know! beating hexagony! Saved 9 bytes thanks to Zgarb! and so much more to Lynn!
20=16
*2016
2[016
2+01[6
20-16
p:2[016
201]6
2+0-1-6
-:20]16
2+01+6
-:20[16
p:20-16
+/2$01]6
<:20-1]6
20-1]6
<:20]16
20]16
p:201]6
2+016
20-1[6
20[16
20+1[6
20++~1[6
+/q:2016
20-(+:1)-6
<:20+1]6
20+1]6
20+1+6
+:20-1]6
p:2+01+6
-2-+:016
<:2*016
2*016
>.201%6
<.201%6
<:20+16
20+16
20+>:16
+~20-1[6
-20-p:16
+:20[16
p:2*01*6
>:p:2*01*6
<:<.%:2016
<.%:2016
>.%:2016
+/q:*:2016
p:20-1]6
>:p:20-1]6
*:2+0-1-6
+:20-1-6
20++:16
<.%:20^%:1+6
20+#i:i:16
*/2,01]$~-:6
<:<.o.2+016
<.o.2+016
>.o.2+016
<:p:20]16
p:20]16
>:p:20]16
2+p:016
<.o.20[16
<:2^01]6
2^01]6
>:2^01]6
<:p:2+016
p:2+016
>:p:2+016
>:>:p:2+016
<:p:20-1[6
p:20-1[6
+/+~20 16
p:20[16
>:p:20[16
>:>:p:20[16
-:+/2+i.016
<:<:p:20+1[6
<:p:20+1[6
20+p:16
20*.16
*:2+01+6
>:*:2+01+6
p:20++~1[6
<.o.20+1+6
>.o.20+1+6
>:>.o.20+1+6
<.o.+:20-1]6
>.o.+:20-1]6
p:+/q:2016
>:p:+/q:2016
<.o.p:2+01+6
>.o.p:2+01+6
(*:-:20)-1+6
>:(*:-:20)-1+6
<:(++:)2*016
(++:)2*016
p:20-(+:1)-6
2**~p:-:01]6
<:*:-:20[16
*:-:20[16

Highlights and Notes
I used prime numbers a lot in this. In fact, I used p: (the Nth prime) function 37 times in this thing.
 *:-:20[16

90 was made using a fork. Yay! It's approximate to this:
(*+&1)2+01+6

Translated as
inc =: + &1
mul =: *
nin =: 2 + 1 + 6
NB. since (f g) y = y f (g y):
  (mul inc) nin   = nin mul (inc y)
                  =  9   *    9+1
                  =  90

54 uses a shaping ravel!
*/2,01]$~-:6

Is equivalent to
*/ 2 , $~ -:6
*/ 2 , -:6 $ -:6
*/ 2 , 3 $ 3
*/ 2 , 3 , 3 , 3
   2 * 3 * 3 * 3
   54

Well, you have 3/4 year to make improvements.

24: !20-16
54: <.^20-16
55: >.^20-16
97: p:!20-16

Nice trick with the four factorial!

That 94 seems suspiciously long... how about +:p:-2-016 (4 bytes shorter)?

I think 7 can be 2]01+6, 8 can be 2%~016 and 12 can be 2*01]6.

Also, 20-1-6 for 25.

JavaScript, 1021 bytes
Fixed and saved two bytes thanks to Charlie Wynn and ETHProductions.
201&6
-~!2016
2%016
201%6
20%16
2^0^1^6
2*0*1+6
2|0|1|6
2*01+6
2-~01+6
~2+016
~2+016
2^016
20-1-6
2|016
20+1-6
20&16
2-~016
2.0+16
20^1+6
20|16
-~20|16
20*1|6
20|1|6
-2*~01*6
20-1+6
20+1*6
20+1+6
2*016
-~(2*016)
2*-~016
~-(2.0*16)
2.0*16
-~(2.0*16)
2.0*-~16
~-20+16
20+16
-~20+16
-~-~20+16
-~2*~-016
20*-~1.6
~-(-~2*016)
-~2*016
~-~-(~2*~016)
~-(~2*~016)
~2*~016
20<<1|6
20*-~1-~6
~2*~-~016
-~(~2*~-~016)
~-~(~-~2*~-016)
~2*~-~-~016
-~-~2*~-016
20*-~-~1+~6
20*-~-~1-6
20*-~-~1-~-6
-~-~2*016
-~20*-~-~1-6
-~-~(-~-~2*016)
~-(20*~-~(1-6))
~-~2*~016
-~(20*~-~(1-6))
-~-~(20*~-~(1-6))
-~20*~-~(1-6)
~-~2*~-~016
20*-~-~1+~-6
20*-~-~1+6
20*-~-~1-~6
~-~2*~16
-~20*-~-~1+6
-~-~-~2*016
~-(~-~2*~-~16)
~-~2.0*~-~16
-~(~-~2*~-~16)
20*-~-~-~1-6
~-~-~2*~016
~-20*~(1-6)
-~(~-20*~(1-6))
~-~-(20*~(1-6))
~-(20*~(1-6))
20*~(1-6)
-~(20*~(1-6))
~-~-(~20*-~(1-6))
~-(~20*-~(1-6))
~20*-~(1-6)
20*-~-~-~1+~-6
20*-~-~-~1+6
20*-~-~-~1+-~6
20*-~-~-~1+-~-~6
~-(~-~-20*-(1-6))
~-~-20*-(1-6)
-~(~-~-20*-(1-6))
~-~-~-(~-20*-(1-6))
~-~-(~-20*-(1-6))
~-(~-20*-(1-6))
~-20*-(1-6)
-~(~-20*-(1-6))
~-~-~-(20*-(1-6))
~-~-(20*-(1-6))
~-(20*-(1-6))
20*-(1-6)

20^1+6 saves one for 19  (is it ok if you put the number next to each entry?)

20<<1|6 saves one for 46 (should I just be editing your answer?)

@CharlieWynn No. Use comment suggestions. There's a meta post on it.

Testing on Firefox 44, your 1 is actually 2, and your 10 is 11. You can use your current 10 as 11 (it's three bytes shorter), 2-~01+6 as 10, and -~!2016 as 1.

wow someone managed to beat my 5244-character solution

JavaScript (ES7), 836 bytes
Everything should work in any browser except 81, 88, and 97, which use the new ** operator.
Mostly everything here was done by hand. I've been working on a brute-forcer to improve anything that can be improved. Currently it has saved 103 bytes on various items.
  0: 201&6
  1: 2-01%6
  2: 2%016
  3: 201%6
  4: 20%16
  5: 201%~6
  6: 2%01+6
  7: 2-01+6
  8: 2*01+6
  9: 2+01+6
 10: 2-~01+6
 11: ~2+016
 12: 2^016
 13: 20-1-6
 14: 2|016
 15: 20+1-6
 16: 2+016
 17: 2-~016
 18: 2+0+16
 19: 20-1%6
 20: 20|16
 21: 20+1%6
 22: 20*1|6
 23: 20+1|6
 24: 20+~1+6
 25: 20-1+6
 26: 20*1+6
 27: 20+1+6
 28: 2*016
 29: 20-~1-~6
 30: -2*~016
 31: 20|~-16
 32: 20*1.6
 33: 20*~1^~6
 34: -20*~1-6
 35: 20+~-16
 36: 20+16
 37: 20-~16
 38: 20-~-~16
 39: -~2*~-016
 40: 20<<1%6
 41: -20*~1-~!6
 42: ~2*-016
 43: ~20^-1<<6
 44: ~20*~1^6
 45: ~2*~016
 46: 20<<1|6
 47: -20*~1-~6
 48: ~20*~1+6
 49: ~20*~1-~6
 50: ~2/.01/-6
 51: ~2.0*~16
 52: 20|1<<~-6
 53: -20*~-~1+~6
 54: ~2.0*~-~16
 55: -20*~-~1-~-6
 56: ~-~2*-016
 57: ~20*~-~1-6
 58: -20*~-~1^6
 59: ~(20/~1*6)
 60: -20/~1*6
 61: ~2^0-1<<6
 62: -2^0-1<<6
 63: ~20/~1*6
 64: 2-01<<6
 65: 2+~0|1<<6
 66: 2|01<<6
 67: 2-~0|1<<6
 68: 2*~!0*~16
 69: ~20*~-~1+6
 70: 20/~1*~6
 71: -~(20/~1*~6)
 72: 2+~0/.1*~6
 73: -20<<-~1^~6
 74: -20<<-~1^-6
 75: ~-~-~2*~016
 76: ~-20*(~1+6)
 77: ~-~20/~1*-~6
 78: ~-20<<-~1|6
 79: -20<<-~1^~!6
 80: 20*(~1+6)
 81: ~2*~0**(~1+6)
 82: ~-~-20|1<<6
 83: ~-20|1<<6
 84: 20|1<<6
 85: -~20|1<<6
 86: 20<<-~1|6
 87: 20<<-~1|-~6
 88: .2**~!0|1<<6
 89: ~20*~-~-~1+~-6
 90: ~2*~!0*~-16
 91: ~20*~-~-~1-~6
 92: ~-2/.01+~-~6
 93: ~-2/.01+~6
 94: ~-2/.01-6
 95: ~-20*1*~-6
 96: 2+01<<~-6
 97: ~2+.01**~.6
 98: ~-2/.01^6
 99: ~-2/.01+~.6
100: 20*1*~-6

Brute-forcer
It ain't the prettiest code, but that doesn't seem to matter around these parts.
WARNING: Do not run unless you are prepared for your browser/engine to freeze for a few minutes. Nobody likes to calculate 7 nested loops.
var a=new Array().fill("000000000000000000000000000"), // An array of non-solutions to start
    time=new Date(),                                   // For timing how long this takes
    o=["","+","-","*","/","%","&","|","^",".","<<"],   // Operators for between numbers
    p=["",".","~.","-","~","~-","-~","~-~","~-~-","~!"];        // Prefixes for each number
for(i=0;i<o.length;i++)
for(j=0;j<o.length;j++)
for(k=0;k<o.length;k++)
for(I=0;I<p.length;I++)
for(J=0;J<p.length;J++)
for(K=0;K<p.length;K++)
for(L=0;L<p.length;L++) {      // 7 nested loops = O(len(o)^3 * len(p)^4)
    z=      p[I]+2
      +o[i]+p[J]+0
      +o[j]+p[K]+1
      +o[k]+p[L]+6;            // Put all the current chars in one string.
    try { v=eval(z) }          // Try setting v to the evaluated value of z.
    catch(e) { v=-1 }          // If an error occurs, set v to -1.
    if( (v === (v|0)) &&       // If v is an integer, and
        v>=0 && v<=100 &&      // v is between 0 and 100, inclusive, and
        z.length<a[v].length ) // z is shorter than the current entry,
        a[v]=z;                // overwrite the current entry.
}

console.log("time: " + ((new Date()-time)/1e3) + "seconds\n"
           + "length: " + (a.join("").length) + "\n"
           + a.map((x,y) => y + ": " + x).join("\n"))

Yeah, prettiness doesn't matter here.  We are not CR. :P

wow someone managed to beat my 5244-character solution

Dyalog APL (This is a joke, please don't submit), 25,957 bytes.
2016⊢≢⍬
2016⊢(⊢+≢)≢⍬
2016⊢(⊢+≢)(⊢+≢)≢⍬
...

Yeah, this is a joke entry, we need an APL solution, even if it's completely horrible.
Works by incrementing ≢⍬ (0) n times. I don't want to give any secrets away from my actual submission.
Obviously could be golfed much more.

LOL. I got two upvotes.

Seriously, why are people upvoting this?

Because it's fun.

PowerShell v3+, 1575 1499 bytes
2*0*16
2*0+1%6
2%016
201%6
20%16
2*0+-1+6
2*0+1*6
2*0+1+6
2+0*1+6
2+01+6
2*(0-1+6)                #10
2*($a=01)*6-$a           ################################## First variable
2*01*6
20-1-6
20*1-6
20+1-6
2*0+16
!!20+16                  ################################## First Boolean not
2+016
2+!0+16
20+!16                   #20
20+1+!6
!2+0x16                  ################################## First use of 0x16
(20+1)-bor6              ################################## First binary or
2+0x16
20-1+6
20*1+6
20+1+6
20+($a=1)+6+$a
20+($a=1)+6+$a+$a
2*-bnot-016              #30 ############################## First binary not
-bnot(-2*016)
2*016
-(-bnot(2*016))
-2*-bnot016
-bnot(-20)+16
20+16
20-(-bnot16)
-(-bnot20)-(-bnot16)
(20-shl1)-!!6            ################################## First binary shl
(20-shl1)+!6             #40
(20-shl1)+!!6
($a=2)*0x16-$a
($a=2)*0x16-$a/$a
2*0x16
-(-bnot2)*(-bnot-016)
(20-shl1)+6
$a=20;$b=1;$a+$a+$b+6
-(-bnot2*016)
2*0+($a=1+6)*$a
(20-shr($a=1))*(6-$a)    #50
(-bnot2)*(-bnot016)
20+($a=16)+$a
($b=20*($a=1)+6)+$b+$a
($a=20+1+6)+$a
($a=20+($b=1)+6)+$a+$b
($a=20)+16+$a
(($a=(2+!0))+16)*$a
(20-shr($a=1))*6-$a-$a
(20-shr($a=1))*6-$a
(20-shr1)*6              #60
(20-shr($a=1))*6+$a
(($a=2)*0+1-shl6)-$a
-bnot-(2*0+1-shl6)
2*0+1-shl6
(2*0+($a=1)-shl6)+$a
(-bnot2)*-0x16
($a=201)/($a%6)
20+($a=16)+$a+$a
20+($a=16)+$a+$a+$a/$a
-($a=2)*-bnot016*$a+$a   #70
2*01*($a=6)*$a-$a/$a
2*01*($a=6)*$a
($a=2+01+6)*$a-$a+$a/$a
($a=2)*01*($b=6)*$b+$a
($a=20)+16+$a+$a-$a/$a
($a=20)+16+$a+$a
($a=20)+16+$a+$a+$a/$a
2*01*($a=6)*$a+$a
($a=20)%16*$a-$a/$a
($a=20)%16*$a            #80
($a=2+01+6)*$a
($a=2)*0x16*$a-$a*$a-$a
20+(($a=1)-shl6)-$a
20+(1-shl6)
20+(($a=1)-shl6)+$a
($a=2)*0x16*$a-$a
($a=2)*0x16*$a-$a/$a
($a=2)*0x16*$a
($a=2)*0x16*$a+$a/$a
($a=2)*0x16*$a+$a        #90
($a=2)*0x16*$a+$a+$a/$a
($a=2)*0x16*$a+$a+$a
20*(-1+($a=6))-$a-$a/$a
20*(-1+($a=6))-$a
20*($a=-1+6)-$a
2*(!0+1+($a=6))*$a
20*(($a=-1)+6)+$a+$a+$a
($a=2)*($b=01+6)*$b
20*(($a=-1)+6)+$a
20*(-1+6)                #100

100% manually golfed - no brute force programs or other aids enlisted.
I feel that 1500 is maybe within reach
Sub-1500 achieved! Let's see how well I can do on getting this lower. (NB - This was only tested in v4, but should work in v3 and v5 without modification. Will not work in v2 or v1 as those versions did not have bitwise shift operators.)
Key points are marked with ##.hashes.## in the above code.
#11 is the first assignment to variable $a. Unlike some other languages, variables don't need to be pre-initialized for parsing, and it's only during execution that variables are resolved. Since the ($a=01) is surrounded by parens, it's evaluated first and so the second -$a is equivalent to -1. This is used rather extensively from here on out, and is one of the biggest things keeping the bytecount down.
#17 shows the first use of ! for Boolean not. In PowerShell, types are pretty loosely cast, so if casting can be implied, it'll work. Here, we're using the fact that !!20 equals !$false, which is $true, which can be implicitly cast as [int]1, which results in 17. This is used several times to either get another 1 or make a portion go to 0.
#22 Showcases the 0x hexadecimal cast operator, here turning 0x16 into 22. However, since 0x16 is the only number we can get, its usefulness is limited.
#23 has the -bor operator, for "binary or." However, since both -bor and -bxor have lower precedence than simple arithmetic operators, using them usually requires parens, which severely limits usefulness. This is the only one I've found where it's shorter to use the binary or operator (I eliminated the -bxor operator from 22).
#30 is the first time the -bnot operator is introduced. This is the "binary not" operator, and functions similarly to ~ in (e.g.) JavaScript. However, it usually needs parens, since the negation will show as --bnot and result in a parse/syntax error, and since it's five characters compared to one for ~, it gets used sparingly.
#39 is the first use of our binary shift operators, -shl and -shr. These are similar to << or >> in other languages, but are explicitly dyadic, meaning we need a number on both sides for them to work, which limits their usefulness in this challenge. Additionally, their precedence isn't explicitly called out in documentation, but testing shows them to be lower than simple arithmetic, meaning that parens need to be used liberally, so they don't make as much of an appearance as in other language answers.

Great answer. Thanks for explaining your techniques so thoroughly.

CJam, 792 791 bytes
I kind of got lazy near the end, a lot of them just ended up being increments and decrements (101 is a lot!), although I'm not sure if there is any other way for a few of the numbers. There's still plenty of time to golf it if I need to.
Around #40 there are some winky faces ;)
2016!          e# 0
2016g
2016g)
201 6%
20 16-
20)16-
20 1>6*
20 1>6+
201mQ6-
201mQ6-)
2 01 6*(*      e# 10
2 01*6*(
2 01*6*
2~016+
-2 016+
2)016(|
20;16
2(016+
2 016+
2)016+
20 16|         e# 20
20)16|
20 1*6|
20 1|6|
20 16mQ+
20_*16/
20 1 6*+
20 1+6+
20 1)6++
20)1)6++
2 016(*        e# 30
2 016*(
2 016*
201 6/
2 016)*
20(16+
20 16+
20)16+
20)16)+
20_+16;(
20_+16;        e# 40
20_+16;)
20)_+16;
20)_+16;)
20(1m<6+
2)016(*
20 1m<6+
2)016*(
2)016*
2)016*)
2)016)*(       e# 50
2)016)*
20 16_++
20)1 6(m<+
20(_16++
20_16++(
20_16++
20_16++)
20)_16++
20)_16++)
20 16mQ(*      e# 60
20 16mQ(*)
2 01*6#((
2 01*6#(
2 01*6#
2 01*6#)
201_+6/(
201_+6/
201_+6/)
201mQ6(*(
201mQ6(*       e# 70
20_16_+++(
20_16_+++
20_16_+++)
20)_16_+++
20(16mQ*(
20(16mQ*
20(16mQ*)
20_16^*((
20_16^*(
20_16^*        e# 80
2)016mQ#
201mQ6*((
201mQ6*(
201mQ6*
201mQ6*)
201mQ6*))
201mQ6*)))
[20_16__]:+
[20_16__]:+)
[20)_16__]:+   e# 90
[20_16)__]:+
[20__16_]:+
20(1*6(*((
20(1*6(*(
20(1*6(*
20(1*6(*)
201mQ6)*(
201mQ6)*
20 1*6(*(
20 1*6(*       e# 100

Wanted to upvote for the winky faces, but I noticed you had exactly 1,000 rep, so I don't want to ruin it. ;) Will upvote later. :P

and now its 1089 :P (another magic number for maths :P)

Mathematica, 2912 2502 2282 2180 bytes
Could definitely be golfed further. Mostly just solves a few separate Frobenius equations, which yields O(n) length solutions. The rest were generated by my brute-forcer.
2 0 16
2-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
a=2;b=016;a+b+b+b+b+b+b
a=2;b=01;c=6;a+b+c+c+c+c+c+c+c+c+c+c+c+c+c+c+c+c
a=20;16;a+a+a+a+a

Hrm, unless I misunderstood the question, shouldn't you be able to save a lot of bytes by assigning c to 16 when the number is even and large? Like for 96, etc. Not sure how your equation solver works, but using a=20 should also be helpful for several of these?

Yeah, then I dunno how long it would take to run it with 16 and 20 as well, but I expect that'll trim quite a bit for bigger numbers.

JavaScript, 5244 chars
Could probably be golfed a lot further. Test in the Chrome console. I kinda gave up at 10.
201&6
!!2016
2%016
20+~16
20-16
-2+0+1+6
2*0*1+6
2*0+1+6
2*01+6
2+01+6
-~-~-~-~-~-~20-16
-~-~-~-~-~-~-~20-16
-~-~-~-~-~-~-~-~20-16
-~-~-~-~-~-~-~-~-~20-16
20*1-6
!!2+016
2+016
!!20+16
2.0+16
2+!0+16
20+!16
20+!!16
-~20+!!16
-~-~20+!!16
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20-16
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20-16
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20-16
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20-16
2*016
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20-16
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20-16
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20-16
(2+0)*16
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20-16
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20-16
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-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~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20+16
20*-(1-6)

If 101 expressions was a bit much, you may want to have a go at this. There's already a JavaScript answer, but maybe you can do better - or differently...

Java 7, 1,083 bytes
For the byte-count I've only counted the expressions itself between the parenthesis. So I've excluded the System.out.printlns and class. Including those it would be 3,049 bytes.
PS: Not entirely sure if the int-cast for 72 is valid.. Although it does add 5 bytes anyway..
201&6
2-01%6
2%016
201%6
20-16
201%~6
2%01+6
2-01+6
2*01+6
2+01+6
~2+016
~2+016
2^016
20-1-6
2|016
20+1-6
2+016
2-~016
2+0+16
20-1%6
20|16
20+1%6
20*1|6
20|1|6
20+~1+6
20-1+6
20*1+6
20+1+6
2*016
20-~1-~6
-2*~016
20|~-16
(2+0)*16
20*~1^~6
-20*~1-6
20+~-16
20+16
20-~16
20-~-~16
-~2*~-016
20<<1%6
~-(-~2*016)
~2*-016
~20^-1<<6
~20*~1^6
~2*~016
20<<1|6
-20*~1-~6
~20*~1+6
~20*~1-~6
-20/~1*~-6
~2*~-~-~016
20|1<<~-6
-20*~-~1+~6
20*-~-~1-6
-20*~-~1-~-6
~-~2*-016
~20*~-~1-6
-20*~-~1^6
~(20/~1*6)
-20/~1*6
~2^(0-1)<<6
-2^(0-1)<<6
~20/~1*6
(2-01)<<6
(2+~0)|1<<6
2|01<<6
2-~0|1<<6
~-~2*~16
~20*~-~1+6
20/~1*~6
-~(20/~1*~6)
~-~(int)2.0*~-~16
-20<<-~1^~6
-20<<-~1^-6
~-~-~2*~016
~-20*(~1+6)
~-~20/~1*-~6
~-20<<-~1|6
~-(20*~(1-6))
20*(~1+6)
-~(20*~(1-6))
~-~-20|1<<6
~-20|1<<6
20|1<<6
-~20|1<<6
20<<-~1|6
20<<-~1|-~6
-~-~20*(~1+6)
~20*~-~-~1+~-6
~-~-20*-(1-6)
~20*~-~-~1-~6
~20*~-~-~1-~-~6
~2^~-~01<<~-6
-2^~-~01<<~-6
~-20*1*~-6
(2+01)<<~-6
-~(~2*~-~0*16)
~-~-(20*-(1-6))
~-(20*1*~-6)
20*-(1-6)

Ungolfed & test code:
Try it here.
class M{
  public static void main(String[]a){
    System.out.println(201&6);
    System.out.println(2-01%6);
    System.out.println(2%016);
    System.out.println(201%6);
    System.out.println(20-16);
    System.out.println(201%~6);
    System.out.println(2%01+6);
    System.out.println(2-01+6);
    System.out.println(2*01+6);
    System.out.println(2+01+6);
    System.out.println(~2+016);
    System.out.println(~2+016);
    System.out.println(2^016);
    System.out.println(20-1-6);
    System.out.println(2|016);
    System.out.println(20+1-6);
    System.out.println(2+016);
    System.out.println(2-~016);
    System.out.println(2+0+16);
    System.out.println(20-1%6);
    System.out.println(20|16);
    System.out.println(20+1%6);
    System.out.println(20*1|6);
    System.out.println(20|1|6);
    System.out.println(20+~1+6);
    System.out.println(20-1+6);
    System.out.println(20*1+6);
    System.out.println(20+1+6);
    System.out.println(2*016);
    System.out.println(20-~1-~6);
    System.out.println(-2*~016);
    System.out.println(20|~-16);
    System.out.println((2+0)*16);
    System.out.println(20*~1^~6);
    System.out.println(-20*~1-6);
    System.out.println(20+~-16);
    System.out.println(20+16);
    System.out.println(20-~16);
    System.out.println(20-~-~16);
    System.out.println(-~2*~-016);
    System.out.println(20<<1%6);
    System.out.println(~-(-~2*016));
    System.out.println(~2*-016);
    System.out.println(~20^-1<<6);
    System.out.println(~20*~1^6);
    System.out.println(~2*~016);
    System.out.println(20<<1|6);
    System.out.println(-20*~1-~6);
    System.out.println(~20*~1+6);
    System.out.println(~20*~1-~6);
    System.out.println(-20/~1*~-6);
    System.out.println(~2*~-~-~016);
    System.out.println(20|1<<~-6);
    System.out.println(-20*~-~1+~6);
    System.out.println(20*-~-~1-6);
    System.out.println(-20*~-~1-~-6);
    System.out.println(~-~2*-016);
    System.out.println(~20*~-~1-6);
    System.out.println(-20*~-~1^6);
    System.out.println(~(20/~1*6));
    System.out.println(-20/~1*6);
    System.out.println(~2^(0-1)<<6);
    System.out.println(-2^(0-1)<<6);
    System.out.println(~20/~1*6);
    System.out.println((2-01)<<6);
    System.out.println((2+~0)|1<<6);
    System.out.println(2|01<<6);
    System.out.println(2-~0|1<<6);
    System.out.println(~-~2*~16);
    System.out.println(~20*~-~1+6);
    System.out.println(20/~1*~6);
    System.out.println(-~(20/~1*~6));
    System.out.println(~-~(int)2.0*~-~16);
    System.out.println(-20<<-~1^~6);
    System.out.println(-20<<-~1^-6);
    System.out.println(~-~-~2*~016);
    System.out.println(~-20*(~1+6));
    System.out.println(~-~20/~1*-~6);
    System.out.println(~-20<<-~1|6);
    System.out.println(~-(20*~(1-6)));
    System.out.println(20*(~1+6));
    System.out.println(-~(20*~(1-6)));
    System.out.println(~-~-20|1<<6);
    System.out.println(~-20|1<<6);
    System.out.println(20|1<<6);
    System.out.println(-~20|1<<6);
    System.out.println(20<<-~1|6);
    System.out.println(20<<-~1|-~6);
    System.out.println(-~-~20*(~1+6));
    System.out.println(~20*~-~-~1+~-6);
    System.out.println(~-~-20*-(1-6));
    System.out.println(~20*~-~-~1-~6);
    System.out.println(~20*~-~-~1-~-~6);
    System.out.println(~2^~-~01<<~-6);
    System.out.println(-2^~-~01<<~-6);
    System.out.println(~-20*1*~-6);
    System.out.println((2+01)<<~-6);
    System.out.println(-~(~2*~-~0*16));
    System.out.println(~-~-(20*-(1-6)));
    System.out.println(~-(20*1*~-6));
    System.out.println(20*-(1-6));
  }
}

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Windows batch polyglot/hybrids challenge with any language possible
/* I hope such question is suitable for here*/
As the batch scripts are pretty limited, hybrid files that embed a code from another language into a batch file are used a lot lately.
Though usually  there are some requirements for a good hybrid script:

The embedded code should be usable as-it-is - without any ugly batch escaping sequences.
There should not be redundant output. E.g. a lot of languages use /* */ for multi-line comments. If the batch script executes a line that starts with / * it will print an error message an will continue to the next line .Though it will allow you to hybridize C/C++/C#/Java/...  with a batch file  the error message cannot be surpassed so this will not count as a good hybrid.
No temp files.It's easy to output a lot of code into a temp file that will be later executed , the IO operations will slow the script and on of the main advantages of batch scripting (the speed) will be lost. And more over is a challenging constraint. But this will be not possible for compiling languages and for extension sensitive languages.

Some examples will follow:
JScript (good for example as it comes with every windows installation) technique invented somewhere in the link by Tom Lavedas :
@if (true == false) @end /*
@echo off
cscript //nologo //e:javascript "%~dpnx0" %*
echo Output from the batch.
goto :EOF */

WScript.Echo('Output from the jscript.');

The output will be:

Output from the jscript.
Output from the batch.

The technique uses the JScript (javascript has no such thing) specific @ directives to make the code valid (or silent) both for both languages.
Another example (again with JScript) invented by Ryan Biesemeyer:
0</* :
@echo off
echo Output from the batch.
cscript /nologo /E:jscript %~f0 %*
exit /b %errorlevel%
*/0;

WScript.Echo('Output from the jscript.');

This time is used the redirection priority in batch scripts and 0</* : will be parsed as 0:</* .
Here are some info that can help you:

every line that starts with @ will be silent - even the invalid commands.
every line that starts with : will be taken as label in batch and will be not executed
every line that starts with something like <someWord : someWord will be silent because of redirection priority
every line that starts with something like digit<someWord : someWord will be silent because of redirection priority (this time the output will be redirected to a stream).In this case will be best to use 0
you can use <space><tab> ; , = at the beginning of every line - these will be ignored as standard delimiters in batch.Can be useful if some language use some of these as comment.
if you start a line with %not_existing_variable% it will be replaced with nothing.Could be useful if in some language comments start with percent.
If you finish a line with a caret ^ the next line will be appended at the end.With the caret in batch you can escape the new line.

here's a little bit more inspiration
And here's the challenge. Your script should be with .bat or .cmd extension . It should contain a code from another language - the code should be used by the second language as it is (no escapes symbols)  .REPL tools are accepted with the condition of no escape symbols - except in the line where the REPL tool is invoked. There should not be redundant output. There should be not temp files (with the exception of compiling languages , and file extension sensitive languages - then the file should copy itself in the %TEMP% folder).
Each script should accept one command line argument which will be printed 5 (five) times . Both from the batch part of the code and from the second language prefixed by the language name (for the batch case it should be BATCH: for example.If the second language is Ruby it should be RUBY:)
For sure this will be not possible with every language , but for many it is achievable.
The winner should propose the most solutions with different languages (or if the language is the same a different kind of techniques should be used like in the two examples above).In case of equal number of solutions the first one wins.

Only read the first bit of the question so far, but you should use the sandbox to start with. You don't lose reputation from downvotes, and you can improve your challenge before posting it. The sandbox is a featured meta post, so you can see it in the yellow box at the right near the top of the page. It might be worth deleting the question and reposting it to the sandbox.

What is the winning criterion?

Welcome to Programming Puzzles & Code Golf! All challenges on this site require an objective winning criterion, such as fewest bytes of source code (code golf), so that it's clear which entry should win.

@AlexA. - sorry. My first time here. I've added a winner criteria.

No problem! We're here to help. It's not clear what you mean by "propose the most solutions." Can you be more specific?

I do think this should be (temporarily) moved to the sandbox. Then you can edit it and people can comment on it in the place that that's meant to be done, and you can copy the final challenge text back here.

@AlexA. edited. Hope it's more clear now.If not it's ok to be moves in the sandbox

I think it would benefit from more feedback from the community. What I recommend doing is posting the challenge as an answer here (the sandbox), then deleting this question. Once things are sorted out in the sandbox, this can be edited and undeleted or reposted. How does that sound?

@AlexA. - agreed.Can I put it myself in the sandbox?

You sure can! You just have to post it as an answer at the link I included in my previous comment. :)

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Construct the Identity Matrix
The challenge is very simple. Given an integer input n, output the n x n identity matrix. The identity matrix is one that has 1s spanning from the top left down to the bottom right. You will write a program or a function that will return or output the identity matrix you constructed. Your output may be a 2D array, or numbers separated by spaces/tabs and newlines.
Example input and output
1: [[1]]
2: [[1, 0], [0, 1]]
3: [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
4: [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]
5: [[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]

1
===
1

2
===
1 0
0 1

3
===
1 0 0
0 1 0
0 0 1

etc.

This is code-golf, so the shortest code in bytes wins.

Given an integer input n ... -- I assume you mean a natural number?

MATL, 2 bytes
Xy

A translation of my Octave answer.
Try it online.
A 4 byte version with no built-ins (thanks to Luis Mendo):
:t!=
:     take input n and a generate row array [1,2,...n]
 t    duplicate
  !   zip
   =  thread compare over the result

It must have been difficult, to translate this very sophisticated code :D

@flawr You have no idea. This is truly my masterpiece.

This seems vaguely familiar... ;)

Now I see why you were asking! :-D

Without builtins: :t!=

TI-BASIC, 2 bytes
identity(Ans

Fun fact: The shortest way to get a list {N,N} is dim(identity(N.
Here's the shortest way without the builtin, in 8 bytes:
randM(Ans,Ans)^0

randM( creates a random matrix with entries all integers between -9 and 9 inclusive (that sounds oddly specific because it is). We then take this matrix to the 0th power.

"that sounds oddly specific because it is" TI-BASIC is weird. O_o

Hell yes. TI-BASIC. +1

isn't the shortest way to get a list {N,N}, umm, {N,N}?

@Cyoce No; dim( and identity( are each one byte because TI-BASIC is tokenized.

Julia, 9 3 bytes
eye

This is just a built-in function that accepts an integer n and returns an nxn Array{Float64,2} (i.e. a 2D array). Call it like eye(n).
Note that submissions of this form are acceptable per this policy.

I see what you did there! Nice one!

This also works in Math.JS

APL, 5 bytes
∘.=⍨⍳

This is a monadic function train that accepts an integer on the right and returns the identity matrix.
Try it here

Python 2, 42 bytes
lambda n:zip(*[iter(([1]+[0]*n)*n)]*n)[:n]

An anonymous function, produces output like [(1, 0, 0), (0, 1, 0), (0, 0, 1)],
First, creates the list ([1]+[0]*n)*n, which for n=3 looks like
[1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]

Using the zip/iter trick zip(*[iter(_)]*n to make groups of n gives
[(1, 0, 0), (0, 1, 0), (0, 0, 1), (0, 0, 0)]

Note that the 1 comes one index later each time, giving the identity matrix. But, there's an extra all-zero row, which is removed with [:n].

Damn that zip/iter trick is ingenious

Octave, 10 4 bytes
@eye

Returns an anonymous function that takes a number n and returns the identity matrix.

@eye is sufficient.

@flawr Thanks, I knew there was a way to do it like that but I always forget :P

eye produces the identity matrix in a lot/some numerically oriented languages.

What does the @ do?

@Cyoce @ is the "function handle operator", it works like a lambda and also as a reference to a particular function, so for instance, @(x)x.^2 is the squaring function and @sqrt is a reference to the square root function. You can read more about that here

R, 4 bytes
diag

When given a matrix, diag returns the diagonal of the matrix. However, when given an integer n, diag(n) returns the identity matrix.
Try it online

Jelly, 4 bytes
R=€R

Doesn't use a built-in. Try it online!
How it works
R=€R    Main link. Input: n

R       Range; yield [1, ..., n].
   R    Range; yield [1, ..., n].
 =€     Compare each.
        This compares each element of the left list with the right list, so it
        yields [1 = [1, ..., n], ..., n = [1, ..., n]], where comparison is
        performed on the integers.

This code is unacceptably long.

@flawr Twice the length of the shortest one. That's indeed an unusual encounter.

@flawr Yes, and no shorter than J. FAIL!

In modern versions of Jelly, =þ is two bytes, and makes fun of the longer answers.

@Lynn That's still twice as long as the shortest oneS.

J, 4 bytes
=@i.

This is a function that takes an integer and returns the matrix.

I think you can do it in 3: =i.

@SamElliott that doesn't work. For example, (=i.) 10 => 0 0 0 0 0 0 0 0 0 0

JavaScript ES6, 68 62 52 bytes
Saved 10 bytes thanks to a neat trick from @Neil
x=>[...Array(x)].map((_,y,x)=>x.map((_,z)=>+(y==z)))

Trying a different approach than @Cᴏɴᴏʀ O'Bʀɪᴇɴ's. Could possibly be improved.

This was exactly what I wrote before I scrolled down to find out that you'd beaten me to it.

So, in response to your challenge, I give you the (in hindsight) obvious x=>[...Array(x)].map((_,y,x)=>x.map((_,z)=>+(y==z))) for a saving of 10 bytes.

@Neil Thanks a lot! I'll mention that it's your trick in the answer.

x=>[...Array(x)].map((_,y,x)=>x.map(_=>+!y--))

@l4m2 May be it will be better to post your own answer because the user is inactive

Haskell, 43 37 bytes
f n=[[0^abs(x-y)|y<-[1..n]]|x<-[1..n]]

Pretty straightforward, though I think one can do better (without a language that already has this function built in, as many have done).
Edit: dropped some bytes thanks to Ørjan Johansen

You can cheat the fromEnum as sum[1|x==y].

pretty sure you can remove the space in fromEnum (y==x)

@xnor One byte shorter than that: 0^abs(x-y).

@xnor Oh, you just used 0^(x-y)^2 yourself in another answer, even shorter.

@ØrjanJohansen Yes, seeing your comment was nice timing :)

Pyth, 7 bytes
XRm0Q1Q

Try it online: Demonstration
Creating a matrix of zeros and replacing the diagonal elements with ones.

You can save one byte by removing the final Q

@jim Thanks, but that would actually be not allowed. The feature (implicit Q at the end) was implemented after the challenge was posted.

Python 3, 48
Saved 1 byte thanks to sp3000.
I love challenges I can solve in one line. Pretty simple, build a line out of 1 and 0 equal to the length of the int passed in. Outputs as a 2d array. If you wrap the part after the : in '\n'.join(), it'll pretty print it.
lambda x:[[0]*i+[1]+[0]*(x+~i)for i in range(x)]

x-i-1 -> x+~i

Retina, 25
Credit to @randomra and @Martin for extra golfing.
\B.
 0
+`(.*) 0$
$0¶0 $1

Try it online.
Note this takes input as a unary.  If this is not acceptable, then decimal input may be given as follows:
Retina, 34
.+
$0$*1
\B.
 0
+`(.*) 0$
$0¶0 $1

Try it online.

...whoa. Retina is becoming powerful as a language for more than regex.

@ETHproductions yes, though this is answer pretty much all regex substitution.  The only special thing is the use of $*0 to replace a number n with n 0s.

Haskell, 54 bytes
(#)=replicate
f n=map(\x->x#0++[1]++(n-x-1)#0)[0..n-1]

f returns the identity matrix for input n. Far from optimal.

You can save a handful of bytes using a list comprehension instead of a map call.

Lua, 77 75 65 bytes
x,v=z.rep,io.read()for a=1,v do print(x(0,a-1)..'1'..x(0,v-a))end

Well, I'm not sure if lua is the best language for this with the two period concatenation... But hey, there's a shot at it. I'll see if there's any improvements to be made.
EDIT:
I figured something out on accident which I find rather odd, but, it works.
In Lua, everyone knows you have the ability to assign functions to variables. This is one of the more useful CodeGolf features.
This means instead of:
string.sub("50", 1, 1) -- = 5
string.sub("50", 2, 2) -- = 0
string.sub("40", 1, 1) -- = 4
string.sub("40", 2, 2) -- = 0

You can do this:
s = string.sub
s("50", 1, 1) -- = 5
s("50", 2, 2) -- = 0
s("40", 1, 1) -- = 4
s("40", 2, 2) -- = 0

But wait, Lua allows some amount of OOP. So you could potentially even do:
z=""
s = z.sub
s("50", 1, 1) -- = 5
s("50", 2, 2) -- = 0
s("40", 1, 1) -- = 4
s("40", 2, 2) -- = 0

That will work as well and cuts characters.
Now here comes the weird part. You don't even need to assign a string at any point. Simply doing:
s = z.sub
s("50", 1, 1) -- = 5
s("50", 2, 2) -- = 0
s("40", 1, 1) -- = 4
s("40", 2, 2) -- = 0

Will work.

So you can visually see the difference, take a look at the golfed results of this:
Using string.sub (88 characters)
string.sub("50", 1, 1)string.sub("50", 2, 2)string.sub("40", 1, 1)string.sub("40", 2, 2)

Assigning string.sub to a variable (65 characters)
s=string.sub s("50", 1, 1)s("50", 2, 2)s("40", 1, 1)s("40", 2, 2)

Assigning string.sub using an OOP approach (64 characters)
z=""s=z.sub s("50", 1, 1)s("50", 2, 2)s("40", 1, 1)s("40", 2, 2)

Assigning string.sub using a.. nil approach? (60 characters)
s=z.sub s("50", 1, 1)s("50", 2, 2)s("40", 1, 1)s("40", 2, 2)

If someone knows why this works, I'd be interested.

The "z.rep" line is breaking on mine.  I'm betting there should be a z='' somewhere?  A shorter variant of z=''z.rep would just be ('').rep .
You can also use the cmdline ... for reading input, and widdle the bytecount down to 57 as follows:
z='0'for i=1,...do print(z:rep(i-1)..1 ..z:rep(...-i))end

I found someone suggesting ("").rep before, but I was unable to get it to work. It'd always error out. Maybe my interpreter is the problem here.
I'm struggling to find any documentation on this command line input, do you know where it can be found?

C,  59 or 59  56 or 56
Two versions of identical length.
3 bytes saved due to suggestion from anatolyg: (n+1) --> ~n
Iterates i from n*n-1 to zero. Prints a 1 if i%(n+1) is zero, otherwise 0. Then prints a newline if i%n=0 otherwise a space.
i;f(n){for(i=n*n;i--;)printf(i%n?"%d ":"%d\n",!(i%~n));}

i;f(n){for(i=n*n;i--;)printf("%d%c",!(i%~n),i%n?32:10);}

n+1 is too dull. Use ~n instead!

Thanks! I should have spotted that, because it occured to me when I looked at NBZ's challenge today.

I'm not too familiar with C. What does i; do?

@Cyoce i; just declares the variable i. In C you always have to declare a variable before using it, indicating the type so the compiler knows how much memory to allocate. With the GCC compiler, if you don't specify a type it is assumed to be int.

@LevelRiverSt thanks. Since it didn't specify a type I was unsure if it was a declaration

You can take 1 more byte off of the second one, since tabs are allowed, you can replace 32, with 9.

Mata, 4 bytes
I(3)

Output
[symmetric]
       1   2   3
    +-------------+
  1 |  1          |
  2 |  0   1      |
  3 |  0   0   1  |
    +-------------+

Mata is the matrix programming language available within the Stata statistical package. I(n) creates an identity matrix of size n*n

Welcome to Programming Puzzles and Code Golf Stack Exchange. This is a good answer; (ab)use of built-ins is great for golfing. I noticed that your answer is actually 1 byte: I, and the other 3 bytes are just calling the function. That would make your answer one of the lowest on this challenge! :-)

Brain-Flak, 206 170 162 bytes
(([{}])){({}<>(())<><(({})<{({}()(<>)<>)}{}>)>)}{}(({}<><(())>)){({}()<({[()]<({}()<({}<>((((()()()()){}){}){})((()()()()){}){})<>>)>}{})>)<>((()()()()()){})<>}<>

Try it online!

K6, 1 byte
=

= is exactly this
Try it online!

Japt, 14 12 10 bytes
Uo £Z®¥X|0

Test it online! Note: this version has a few extra bytes to pretty-print the output.
Uo £Z®¥X|0    // Implicit: U = input integer
Uo £          // Create the range [0..U). Map each item X and the full array Z to:
    Z®        //  Take the full array Z, and map each item Z to:
      ¥X|0    //   (X == Z) converted to a number. 1 for equal, 0 for non-equal.
              // Implicit: output result of last expression

K, 7 bytes
t=\:t:!

Take the equality cross product of two vectors containing [0,n).
In action:
  t=\:t:!3
(1 0 0
 0 1 0
 0 0 1)
  t=\:t:!5
(1 0 0 0 0
 0 1 0 0 0
 0 0 1 0 0
 0 0 0 1 0
 0 0 0 0 1)

Pyth, 8 bytes
mmsqdkQQ

Try it here.

I must say, it's highly unusual that the Pyth answer is four times longer than the shortest answer...

Hrm, this was the best I was able to get that looks 100% valid, but I did find qRRQQ which seems to work except you get True and False instead of 1 and 0, however fixing this afaik requires using three bytes for sMM which doesn't help...

@FryAmTheEggman I also found qRRQQ. I've tried a number of other programs, and none of them were shorter.

Mathematica, 14 bytes
IdentityMatrix

Test case
IdentityMatrix[4]
(* {{1,0,0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1}} *)

Mathematica, 35 Bytes
without using IdentityMatrix
Table[Boole[i==j],{i,1,#},{j,1,#}]&

Javascript, 40

f=
n=>'0'.repeat(n).replace(/./g,"$`1$'\n")

I.oninput=_=>O.innerHTML=f(+I.value)
I.oninput()
<input id=I value=5>
<pre id=O>

R, 28 bytes
function(n,x=1:n)+!x%o%x-x^2

Try it online!
For pure fun, just another attempt at a non-built-in R solution. Uses the shortcut %o% version of the outer function.

05AB1E, 4 bytes
°¨œÙ

Try it online!
Unique permutations of (10^input)[0:-1]

Nice answer! An alternative is LDδQ, for 4 bytes as well.

Jolf, 7 + 1 = 8 bytes
Replace all ☺s with \x01 and \xad with a soft hyphen, or use the online interpreter. (Turn pretty output on for one byte.)
!☺!X\xad☺j
  !X       eye
    \xad☺   take one argument
         j  (the input)
!☺         get the data
           implicit printing

Probably more interesting, a solution without a builtin is 11 + 1 = 12 bytes
ZXZyjjdP=Sn
  Zyjj       create a matrix of width = height = j (input)
ZX    d      matrix map
        =Sn  if x-marker is y-marker
       P     as a number

JavaScript, 75 74 bytes
n=>eval("for(a=[],i=0;i<n;i++){a[i]=[];for(j=0;j<n;)a[i][j]=+(i==j++)};a")

Can be improved, probably.
If n=0 isn't necessary... 70 bytes
n=>eval("for(a=[i=0];i<n;i++)for(a[i]=[j=0];j<n;)a[i][j]=+(i==j++);a")

Since the zero by zero identity matrix is of questionable existence, a=[],i=0 could be golfed to a=[i=0].

I feel like one could argue that your other version also does not appropriately address n=0, since it outputs [], not [[]]; open for interpretation, though ...

Based on this consensus, I think you could even drop the +(...).

@JonathanFrech True. this challenge predates that consensus tho

Python 3.5 with NumPy - 57 49 30 bytes
import numpy
numpy.identity

NumPy.identity takes in an integer, n, and returns a n by n identity matrix. This answer is allowable via this policy.

Actually I believeimport numpy\nnumpy.identityis a legitimate answer.

Thanks for the tip @MorganThrapp! And @FryAmTheEggman, you mean that my answer could just be import numpy\nnumpy.identity() which is 30 bytes?

I got so confused by \nnumpy lol... This would also be valid, @FryAmTheEggman, no? from numpy import identity. 26 bytes.

Also, see my answer something similar

@Ogaday I don't think that is correct, the line you've given does not evaluate to a function. You would need to do from numpy import identidy\nidentity (in which case it would be shorter to use * instead of the specific builtin)

@FryAmTheEggman Ok, I see what you're getting at, in which case the solution would be from from numpy import*;identity at 27 bytes. According to the wording of the link, however, I think just importing satisfies the conditions: before the code is executed, there is no function "identity" in the scope, after execution there is. Think of importing as assignment: look at the language here and here: they both bind variables to names in the local scope.

Similar to how s=sum is valid even though it doesn't evaluate to anything because it binds a value to new name in the local scope. I'm open to contradiction on this though, because the logical conclusion, therefore, is that from numpy import* is a valid solution, because it populates the namespace with all of the names from numpy... Which I don't think is a particularly satisfying solution.

@Ogaday The piece of code in the answer that is the actual function to be run (usually the last line) should evaluate to a function, and thus be assignable and callable. Simply importing a function doesn't result in a function object that can be assigned and called.

Java, 60 bytes
n->{int[][]i=new int[n][n];for(;n-->0;)i[n][n]=1;return i;};

Creates a 2D array and replaces elements where row and column are equal with 1.

You don't have to add the trailing semicolon to the byte-count for Java lambda answers.

CJam, 7 bytes
{,_ff=}

This is a code block that pops an integer from the stack and pushes a 2D array in return.
Try it online!

Perl, 39 33 bytes
/$/,say map$`==$_|0,@%for@%=1..<>

Thanks to Ton Hospel for saving 6 bytes
Running with the -E perlrun:
$ echo 3 | perl -E'@%=1..<>;$a=$_,say map{$a==$_|0}@%for@%'
100
010
001

Golfing a bit more: /$/,say map$`==$_|0,@%for@%=1..<> or even better //,say map$'==$_|0,@%for@%=1..<> but like that you can't put it in single quotes anymore

@TonHospel Wow thats cool, thanks. The later would require the use of print instead of say, because -E is only free on the command line.

R, 50 bytes
f=function(n)matrix(c(1,rep(c(rep(0,n),1),n-1)),n)

Without using diag(), because I started coding without checking if there was a command for that... Also, I like my solution, despite being way too long.

36 bytes by abusing recycling (but gives a warning about non-multiple of length in recycling)

R, 32 31 bytes
function(n)+outer(1:n,1:n,"==")

Try it online!
Thanks to Kirill L. for -1 byte
Alternative to Ivanneke's solution, but obviously far longer than just plain old diag.

You can swap *1 for +: 31 bytes

@KirillL. ah, yes, thank you.

Octave, 15 bytes
Because built-ins are no fun!
@(x)(k=1:x)==k'
@(x)~~diag(1:x)

Try it online!
The first one creates a vector from 1, 2, .. x, and compares it to itself transposed, expanding it to a square matrix where the diagonal elements are 1.
The second one creates a diagonal matrix with 1, 2, .. x is on the diagonal, then negates it twice, to get the diagonal equal 1, 1, .. 1.

PowerShell, 52 bytes
param($a)1..$a|%{$d++;(1..$a|%{+($d-eq$_)})-join' '}

Since the only built-in .NET class for matrices is ... umm ... inadequate, shall we say, we're just going to construct and output a string representation here...
Takes input $a then executes a double-for-loop over range 1..$a. Each outer loop we increment helper variable $d (the first loop, since $d isn't initialized, turns $d++ into $null + 1 = 1 ... in PowerShell logic it makes sense), and each inner loop is simply an integer-cast with + of an equality between $d and the current element $_. Each inner loop is -joined together with spaces so it prints nicely, and each outer loop causes a newline, so output code is pretty cheap.
Example
PS C:\Tools\Scripts\golfing> .\construct-identity-matrix.ps1 10
1 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 1

Haskell, 27 bytes
import Data.Matrix
identity

Maybe a little bit boring.
Usage example:
Prelude Data.Matrix> identity 4
( 1 0 0 0 )
( 0 1 0 0 )
( 0 0 1 0 )
( 0 0 0 1 )

Ruby, 56 48 bytes
->n{(([1]+[0]*n)*(n-1)+[1]).each_slice(n).to_a}

Explanation:
Concatenates n - 1 sequences of 1 followed by n 0s into an array, and appends 1 to the end.  Then slices the result into n arrays of length n and evaluates to an array having the slices as its elements.
Per Alex A., shaved 8 bytes by putting it in the form of a lambda.

Perl 6,  41 37  35 bytes
{$/=1..$_;$/.map: {$/.map: {+($^a==$_)}}} # 41 bytes
{$/=1..$_;$/.map: {$/.map: +(*==$_)}}     # 37 bytes
{$_=1..$^a;.map: {.map: +(*==$^a)}}       # 35 bytes

This outputs a list of lists.
Usage:
# give it a lexical name
my &identity-matrix = {…}

# format it so that it is readable
sub readable ( @_ ) { @_.join: "\n" }

say readable identity-matrix 10

1 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 1

Ruby,38 bytes
Returns a 2D array.
->n{(0..n-1).map{|i|s=[0]*n;s[i]=1;s}}

Iterates through each row of the array. For each iteration generates a row of n zeros, then changes one of them to a 1
Usage
f=->n{(0..n-1).map{|i|s=[0]*n;s[i]=1;s}}
p f[5]

[[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]

A different approach (string):
Ruby, 47 bytes
->n{(0..n-1).map{|i|s='0 '*n;s[i*2]=?1;puts s}}

for each row, makes a string of '0 'repeated n times, changes one of the 0s to 1, and prints it

(0...n) is equivalent to (0..n-1).

PARI/GP, 11 5 bytes
matid

is sufficient, or
n->matid(n)

(11 bytes) as a 'roll-your-own' closure. If you want to work entirely by hand,
n->matrix(n,n,i,j,i==j)

(23 bytes) should suffice.

Python 3, 116 107 characters
def M(n):
 x=[]
 for i in range(n):
  r=[]
  for j in range(n):
   r+=[1 if i==j else 0]
  x+=[r]
 return x

Output
iM(1)
[[1]]
iM(2)
[[1, 0], [0, 1]]
iM(3)

r.append(i) is the same as r+=[i] i think

There's a lot of further golfing that can be done here

Yeah, 1 if i==j else 0 can be int(i==j).

58 bytes

Perl, 31 24 bytes
Includes +3 for -p (code contains ' so I can't just use the implied -e)
Run with the count on STDIN, e.g.
./diagonal.pl <<< 3

Outputs:
100
010
001

diagonal.pl:
#!/usr/bin/perl -p
$_=0 x$_;s/./$`1$'
/g

Matlab, 3 bytes
eye

Does exactly this. eye(n) for an n-by-n matrix.
and also one without eye, 15 bytes:
diag(ones(1,n))

Bash (w/ coreutils and awk), 51 50 45 bytes
yes 0|head -$((N*N))|xargs -n$N|awk {\$NR=1}1

Usage
Set the N environment variable to the matrix size
$ N=5
$ yes 0|head -$((N*N))|xargs -n$N|awk {\$NR=1}1
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1

Explanation

yes 0 generates an endless stream of 0s to stdout;
head -$((N*N)) takes the first N2 lines;
xargs -n$N groups every N lines and outputs them together;
awk {\$NR=1}1 changes the value of the field whose index matches the line number to a 1 (otherwise it remains 0) and then outputs the whole record.

There may be a shorter way to generate N2 lines of 0s, but I haven't found one yet...

APL (Dyalog Extended), 11 bytes
{⍵ ⍵⍴1,⍵/0}

Try it online!
Just for fun dfn submission
⍵/0 replicate ⍵ zeros
1, prepend a 1
⍵ ⍵⍴ mold to ⍵×⍵ square
So like for left argument 4 it will construct
1 0 0 0 0

And molding cycles from the beginning so, it will generate
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

the 4×4 identity matrix.

Are intentionally using the Extended variant? Then you could use ⊤2*⍵ to save a byte over 1,⍵/0

@ovs genius golf! But I am not sure how ⊤2*⍵ works (This works in extended variant too)

After knowing how this works I will edit the answer along with explanation

⊤2*⍵ only works in Extended, in this variant ⊤ without a left argument returns the base-2 digits of the right argument

Knight, 35 bytes
;=nP;=i~1W<=i+1i nO S*"0 "n *2i 1 1

Try it online!
Outputs a bunch of strings. It works by generating the string 0 0 ... 0  (a space-separated string of \$n\$ 0s), then changing the \$2i\$th character to 1 and outputting the result for each \$i\$ between \$0\$ and \$n-1\$.
Expanded code:
;=n PROMPT
;=i~1
WHILE <(=i +1 i) n
  OUTPUT (SET (*"0 " n) (*2 i) 1 1)

Husk, 4 bytes
´Ṫ=ḣ

Try it online!
´         # argdup: use input as both arguments to function
 Ṫ        # table: generate the outer product of all pairs
  =       # equals: 1 if arguments equal, zero otherwise
   ḣ      # heads: 1..input

Arturo, 36 bytes
$=>[unique permutate[1]++@.of:&-1,0]

Try it

, 3 chars / 6 bytes
Мƕï

Try it here (Firefox only).
I'm finding a lot of these 3-char solutions. It's just a builtin.
Bonus solution, 11 chars / 22 bytes
⩥ïⓜãĉ⇝+($≔a

Try it here (Firefox only).
The code in the interpreter link uses some more bytes to pretty-print output.
Explanation
⩥ïⓜãĉ⇝+($≔a // implicit: ï=input
⩥ïⓜ         // create a range [0,ï) and map over it
    ãĉ⇝      // get a copy of range ã and map over it
       +($≔a // output 1 or 0 depending on whether item in first map == item in current map
             // implicit output

How does this work?

It's just a builtin. I'll post a bonus solution soon.

Alright, updated.

Scala, 53 51 bytes
(n:Int)=>Seq.tabulate(n,n){(i,j)=>if(i==j)1 else 0}

I am unfamiliar with Scala, though is the space in 1 else necessary?

@JonathanFrech yes, it actually won’t compile without it, with “Invalid literal number” message. Thanks anyway! And you should learn Scala, it is beautiful.

Samau, 5 bytes
,;`=o

It's a function that takes a number and return a 2D array.
,;`=o
,      range from 0 to n-1
 ;     duplicate
    o  take the outer product by
  `=   equality

Mouse, 75 bytes
N:1I:(I.N.1+<^1J:(J.I.<^0!32!'1J.+J:)1!32!'(J.N.<^0!32!'1J.+J:)10!'1I.+I:)$

This is a full program that reads from STDIN and prints to STDOUT. Each line will have a single trailing space and there will be one trailing newline at the end of the output.
Explanation:
~ Read N from STDIN
? N:

~ Initialize a row index
1 I:

~ Loop while we've printed fewer than N+1 rows
( I. N. 1 + < ^

  ~ Initialize a column index
  1 J:

  ~ Print I-1 space-separated zeros
  ( J. I. < ^
    0 !
    32 !'
    1 J. + J:
  )

  ~ Print 1 and a space
  1 !
  32 !'

  ~ Print the remaining zeros
  ( J. N. < ^
    0 !
    32 !'
    1 J. + J:
  )

  ~ Newline
  10 !'

  ~ Increment the row index
  1 I. + I:
)
$

Java, 200 Bytes
This is the shortest working java code i could come up with. Nothing to special ;)
class a{public static void main(String[]a){int c=Integer.parseInt(a[0]);int[][]b=new int[c][c];for(int d=0;d<c;d++){for(int e=0;e<c;e++){b[d][d]=1;System.out.print(b[d][e]);}System.out.println();}}}

Partly posting this hoping someone could explain why TNT 's answer is valid (it has no class declaration and no main(String[] args))? I'm new to code golf and i thought that answers had to be a working program?

The answer in question is a function, which is a valid submission by our rules. You can make this shorter by changing class to interface, which allows you to drop the public.

Python 3, 22 bytes
from numpy import*;eye

It's a bit boring, but it's short! Because of discussion on meta, I think this follows the spirit of the rules a bit more closely.

I'm unsure about your points, why don't you try adding an answer to the meta question, so it can get feedback from more people? The main thing that bothers me about it is the arguments against the empty file being valid, because then you could write a library that defined all functions to make all your answers extremely small. But I'm uncertain of how to differentiate between import and def now that you've brought it up.

@FryAmTheEggman +1 I'll open it to the floor.

Ruby 42 bytes
->n{([1]+[0]*(n-1)).permutation.to_a.uniq}

creates every permutation of the array [1,0,0,0...] and then takes the unique ones. this will end up with the ones we want, in the correct order.

C++, 111 bytes
I love abusing for loops.
#include <stdio.h>
void f(int n){for(int j,i=0;i++<n;putchar(10))for(j=0;j++<n;putchar(32))putchar(i-j?48:49);}

Oracle SQL 11.2, 102 bytes
SELECT SUBSTR(RPAD(0,:1,0),:1-LEVEL+2)||1||SUBSTR(RPAD(0,:1,0),LEVEL+1)FROM DUAL CONNECT BY LEVEL<=:1;

Sage, 15 bytes
identity_matrix

Exactly what it says on the tin
Try it online
Thanks to Lynn for pointing out that I was being a doofus.

Why not eta-reduce this to identity_matrix?

Jellyfish, 12 bytes
P`N(Rri
   -

Try it online!
This entry is non-competing.
Explanation

i is input, and r computes the range from 0 to input-1.
The operator ( is a left hook. On inputs - and R, it applies R (rotate) to the range and its negated version. This gives the i×i matrix whose rows are the ranges ri, rotated k steps to the right for each row k.
`N computes the logical negation of each entry: 0 goes to 1 and everything else to 0. Since the 0s are on the diagonal, this gives the identity matrix.
P prints the matrix.

picTuring - 16 States (320 bytes)
I thought this challenge might be a good chance to show off my new Turing Machine interpreter.
0 * 0 * r
0 _ 1 * r
1 * 2 1 l
2 * 2 * l
2 _ d * l
d _ f * r
d 0 d 1 l
d 1 p 0 r
p * p * r
p _ q * r
q * q * r
q _ 2 0 l
f * f _ r
f _ g * r
g 1 g _ r
g 0 r 1 r
r * r * l
r _ c * r
c _ n * d
c 0 o * d
c 1 i * d
o * e 0 u
i * j 0 r
j * h 1 u
h * k * r
k _ halt * *
k * c * *
e * c * r
n * r * l

The input must be in binary (1 / 0), with the number terminating at the head (the white circle).
How to Run it:
In case you didn't realize that the link in the header leads to my interpreter, you can find it here -> http://fred-choi.com/projects/picTuring/index.html
Here is the compressed test case (since my interpreter does not support permalinks yet):
AwAlH0QRhBaGLTgJjCSMg AwAgVCoQTgUKB9EBGcI6ogJhSANrDtmgTkgCYmyyVIBmaclolqBrIADpOtdxP17ckAR0awxESbzFIcoArAYQGSOKpABzcbG2pta3T2i44sEzComkAYx12kAOzTlYd0AHsXb3AEtvsF4QAKY8AK7U-hAAVsawsRAAFrgRyRAA1uKZSIkAhngALmhgsJkQdhAlsKHlOs6WEHhAA

To use it, just hover over save, paste the compressed code in the text box, and click load.

To edit the tape, make sure you're in "Type" mode (Edit -> Paint), then double click the tape, and a red box should show up, indicating that you're now editing the tape.
Once you're finished, hit Edit -> Ok to save the tape, then Controls -> Run. Controls -> Reset will restore the tape to when you hit Edit -> Ok.
Again, this is interpreter is still indev, I don't have a manual yet, so feel free to leave comments if I left anything out.

PHP, 106 bytes
<?php $i=$argv[1];for($j=0;$j<$i;$j++){for($h=0;$h<$i;$h++){$l="0 ";if($h==$j)$l="1 ";echo$l;}echo"\n";}?>

Based on a double for loop, it uses the command-line argument for the input.
php 70365.php 3
1 0 0
0 1 0
0 0 1

Expanded code:
<?php
    $i = $argv[1];
    for($j = 0; $j < $i; $j++)
    {
        for($h = 0; $h < $i; $h++)
        {
            $l="0 ";
            if($h == $j)
                $l="1 ";
            echo $l;
        }
        echo "\n";
    }
?>

PHP, 64 bytes
for(;$i<$argn**2;$m?:$k++)echo$k==$m?:0,($m=++$i%$argn)?" ":"
";

Try it online!

Jelly, 2 bytes
=þ

Try it online!

Rust, 59 bytes
|n|{let mut l=vec![vec![0;n];n];for i in 0..n{l[i][i]=1};l}

Defines an anonymous function, creates a vector of vectors of the specified length, sets the diagonals to 1 and returns it. Boring, but shorter than any iterator-based approaches due to .collect overhead.
Alternatively, if returning an iterator of iterators is allowed it can be done in 44 characters:
|n|(0..n).map(|i|(0..n).map(|j|(j==i)as u8))

tinylisp repl, 107 bytes
(d =(q((A R C S)(i C(=(c(e R C)A)R(s C 1)S)A
(d #(q((A R S)(i R(#(c(=()R S S)A)(s R 1)S)A
(d f(q((S)(#()S S

Using the repl saves 6 bytes in implied closing parentheses at the ends of lines. Defines a function f which takes a positive integer and returns the identity matrix of that size as a nested list. Try it online!
Explanation
The function = constructs a row in the matrix. Its arguments are (in order) an Accumulator, the Row number, the current Column number, and the Size of the matrix. If the column is not zero (i C ...), then cons a number to the accumulator (1 if the row and column are equal, 0 otherwise) (c (e R C) A), decrease the column number (s C 1), and recurse (= ...). Otherwise, return the accumulator A.
The function # constructs the matrix as a list of rows. Its arguments are an Accumulator, the current Row number, and the Size of the matrix. If the row number is not zero (i R ...), then generate a row (=()R S S) and cons it to the accumulator (c ... A), decrease the row number (s R 1), and recurse (# ...). Otherwise, return the accumulator A.
Finally, the function f is simply a single-argument wrapper function that calls #.

Clojure, 45 bytes
#(for[i(range %)](assoc(vec(repeat % 0))i 1))

PHP, 49 bytes
function($n){for(;$n--;)$k[$n][$n]=1;return $k;};

There is a bit of a caveat with this answer, and I will delete it or mark it as non-competing if it is deemed invalid.
The array returned by this function technically only has n elements, those being a 1 at every intersection. ie: 0:0 1:1, 2:2, etc
However, not only does this satisfy the definition of the identity matrix as given by the question:

The identity matrix is one that has 1s spanning from the top left down to the bottom right

It also works if used as an identity matrix, as an empty value in an array in PHP is treated as 0 if used arithmetically.

Axiom, 68 bytes
f(n:PI):Matrix INT==matrix([[(i=j=>1;0)for i in 1..n]for j in 1..n])

test and results
(30) -> for i in 1..3 repeat output f(i)
   [1]
   +1  0+
   |    |
   +0  1+
   +1  0  0+
   |       |
   |0  1  0|
   |       |
   +0  0  1+
                                                               Type: Void

Python 2, 52 bytes
y=x=2**input()
while~-x:x/=2;print str(bin(y+x))[3:]

Try it online!
Using binary representation of powers of 2.

Mathematica ,26 bytes
without using IdentityMatrix
Boole[#==#2]&~Array~{#,#}&

PowerShell, 45 bytes
{param($n)0..--$n|%{"$(,0*$_+1+,0*($n-$_))"}}

Try It Online!

Excel VBA, 55 52 43 Bytes
Anonymous VBE immediate window function that takes input as number from cell [A1] and outputs the identity matrix to the range of [A1].Resize(n,n)
[A1].Resize([A1],[A1])="=1*(Row()=Column())

-2 bytes thanks to Engineer Toast
Previous Version
n=[A1]:[A1].Resize(n,n)=0:For i=1To n:Cells(i,i)=1:Next

Save 1 byte: "=1*(Row()=Column())"

Vim, 47 keystrokes
"zy$␘a@q␛"xYoa␛"zPy$qqo␛@"0␛q@x3Gqqr1jlq@x1G2dd

␘ is CtrlX and ␛ is Esc
Explanation
"zy$␘           Save n for use later
a@q␛"xY         Create the macro `x` that repeats the macro `q` n-1 times
oa␛"zPy$        Create an anonymous macro that inserts a character n times
qqo␛@"0␛q@x    Create the macro `q` that adds a new line with n zeroes and run it n times
3G               Go to the top-left corner of the matrix
qqr1jlq@x        Redefine `q` as a macro that replaces the character at the cursor with
                   a one and moves the cursor one step down-right. Run `q` n times
1G2dd            Delete the two lines used in macro defenitions

Tcl, 92 bytes
proc I n {time {incr j;set a "";set i 0;time {lappend a [expr [incr i]==$j]} $n;puts $a} $n}

Try it online!

Husk, 4 bytes
´Ṫ=ḣ

Try it online!
Explanation
´Ṫ=ḣ  -- example input: 2
   ḣ  -- range: [1,2]
´     -- duplicate argument: [1,2] [1,2]
 Ṫ    -- outer product by
  =   -- | equality: [[1==1,1==2],[2==1,2==2]]
      -- : [[1,0],[0,1]]

Gol><>, 10 bytes
IR0PlF}D|;

Try it online!
The output for n = 5 looks like this:
[1 0 0 0 0]
[0 1 0 0 0]
[0 0 1 0 0]
[0 0 0 1 0]
[0 0 0 0 1]

How it works
IR0PlF}D|;

IR0P       Take input n, then fill the stack with that many 0s
           and then make the top 1; stack = [0 ... 0 1]
    lF..|  Do the following n times...
      }D   Rotate the stack once to the right, and print the whole stack
         ; Terminate

05AB1E, 6 bytes
Lã€Ësô

Try it online.
Explanation:
L         # List in range [1,n]
          #  i.e. 3 → [1,2,3]
 ã        # Cartesian power of this list
          #  i.e. [1,2,3] → [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]
  €Ë      # Check for every pair if they are equal or not
          #  i.e. [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]
          #   → [1,0,0,0,1,0,0,0,1]
    sô    # Split it into parts equal to the input
          #  i.e. [1,0,0,0,1,0,0,0,1] and 3 → [[1,0,0],[0,1,0],[0,0,1]]

Alternative 6-byter °¨IF=Á

@Kaldo Ah, that's quite a bit different than my approach, but also pretty cool. And I just saw your 4-byte answer, +1 from me. :)

Jellyfish, 8 7 bytes
P&O`=ri

Try it online!
Explanation
P&O`=ri
     ri  Range(input)
 &       With that list and itself,
  O      make a table (outer product)
   `=    using vectorized equality
P        Print as matrix

Vyxal, 2 bytes
Þ□

Try it Online!
Vyxal literally has a builtin for this.

Factor + math.matrices, 15 bytes
identity-matrix

Try it online!

BQN, 4 bytes
=⌜˜↕

Anonymous tacit function; returns a 2D array. Try it at BQN online!
Explanation
   ↕  Range(argument)
=⌜    Create an equality table
  ˜   between that list and itself

Pip -P, 6 bytes
_=BMCa

Try It Online!
Just for completeness sake, here's the shortest non-builtin answer that I could find in Pip. In other words, an answer without the usage of EY.
_=BMCa         Input is "a"
   MCa         Map over all x,y pairs in an a by a coordinate grid
_=B            Is the x-coordinate equal to the y-coordinate?
               Implicit output joined by newlines (-P flag)

K (ngn/k), 1 byte
=

Try it online!

Pyt, 5 bytes
řĐɐ=Ɩ

Try it online!
ř              implicit input; create řange [1,2,...,n]
 Đ             Đuplicate
  ɐ=           for ɐll pairs: are elements equal?
    Ɩ          cast to Ɩnteger; implicit print

Nekomata, 3 bytes
ᵒ-¬

Attempt This Online!
ᵒ-     Generate a 2d table with subtraction
  ¬    Logical not (converts 0 to 1 and other numbers to 0)

Fortran (GFortran), 110 bytes
allocatable K(:,:);read*,n;allocate(K(n,n));K=0;forall(i=1:n)K(i,i)=1
do i=1,n;print*,(K(i,j),j=1,n);enddo;end

Try it online!

Thunno 2, 4 bytes
RD€=

Attempt This Online!
Explanation
RD€=  # Implicit input
R     # Push the range [1..n]
  €   # For each number,
   =  # Compare it with
 D    # The range [1..n]
      # Implicit output

Itr, 4 bytes
ºµÍT
using array operations, returns a nested array
online interpreter
¹®0^
using matrix operations, returns a matrix
online interpreter
Explanation
ºµÍT  ; implicit input
º     ; convert to zero-based array
 µÍ   ; replace each element with an array that has a 1 at the specified position
   T  ; transpose to fill in missing zero elements
      ; implicit output

¹®0^ ; implicit input
¹    ; 1-based range
 ®   ; converted to matrix
  0^ ; to the 0th power (matrix implicitly padded with zeros)
     ; implicit output

T-SQL, 202 bytes
DECLARE @s VARCHAR(MAX);SELECT @s='SELECT '+STRING_AGG('CASE WHEN value='+CAST(value AS CHAR)+' THEN 1 ELSE 0 END',',')+' FROM GENERATE_SERIES(1,'+CAST(@n AS CHAR)+')'FROM GENERATE_SERIES(1,@n);EXEC(@s)
dbfiddle
Explanation:
DECLARE @n INT = 5; -- Input integer assigned to the variable @n. Not counted in byte count
DECLARE @s VARCHAR(MAX); -- string variable to house the upcoming dynamic sql

-- dynamically builds a sql query that will have @n many columns and stores it in @s.
SELECT @s='SELECT '+STRING_AGG('CASE WHEN value='+CAST(value AS CHAR)+' THEN 1 ELSE 0 END',',')+' FROM GENERATE_SERIES(1,'+CAST(@n AS CHAR)+')'
FROM GENERATE_SERIES(1,@n);
EXEC(@s) -- Executes the string @s as t-sql code.

    --Example, dynamically built query looks like this for @n = 5
    SELECT CASE WHEN value=1                              THEN 1 ELSE 0 END
        ,CASE WHEN value=2                              THEN 1 ELSE 0 END
        ,CASE WHEN value=3                              THEN 1 ELSE 0 END
        ,CASE WHEN value=4                              THEN 1 ELSE 0 END
        ,CASE WHEN value=5                              THEN 1 ELSE 0 END
    FROM GENERATE_SERIES(1,5                             )
    --Note, white space after integer values due to casting as CHAR. casting as VARCHAR would clean this up but cost an extra 3 bytes per call.

Output for @n=5

Will only work on SQL server 2022 or greater (GENERATE_SERIES needs compatibility level 160 or greater). Likely also work on Azure SQL database etc...
There is already a superior (in terms of byte count) oracle sql answer. But that answer produces a single string column of zeros and ones, whereas this answer produces an n by n table of numeric zeros and ones. So I figured this was different enough to still share.

jamforth, 152 bytes
: F DUP DUP 2* 1- DUP ALLOT SWAP DFOR 2DUP + 48 SWAP C! REPEAT TUCK + 1- 49 SWAP C! SWAP TUCK + 1- SWAP DUP DFOR -ROT 2DUP TELL CR -ROT 1- -ROT REPEAT ;
196 bytes compiled, theoretically half that on a 16 bit machine or token threaded forth with 16 bit tokens. F, when called, prints the NxN identity matrix where N is the number on top of the stack.
Here it is deobfuscated:

: POPULATE ( len )
    DUP 2* 1- ( len 2len-1 )
    DUP ALLOT ( len 2len-1 ptr )
    SWAP DFOR
        2DUP + [CHAR] 0 SWAP C!
    REPEAT
    TUCK + 1- [CHAR] 1 SWAP C!
;
: PRINT ( ptr len )
    TUCK + 1- SWAP
    DUP DFOR
        ( ptr len idx )
        -ROT 2DUP TELL CR
        -ROT 1-
        -ROT
    REPEAT
;
: GO DUP POPULATE SWAP PRINT ;

I know I committed to jamforth about 25 minutes before posting this, but I wrote DFOR a few weeks back and just didn't get around to committing it.

Kamilalisp, 16 bytes
[$(⌼ =) #0 #0]∘⍳

Attempt This Online!

Malbolge Unshackled, 1,664,383 bytes.
A link to GitHub as StackExchange does not allow posting answers so long. One of my fastest Malbolge programs.

Babe wake up new Malbolge program just dropped

Seriously, 24 bytes
,;╗r`╙k╜#"{:0%sb}"%f#`MR

Try it online!
Explanation:
,;╗r`╙k╜#"{:0%sb}"%f#`MR
,;╗                       get input (n), save a copy in register 0
   r                      push [0..n-1]
    `                `M   map the function:
     ╙k                     push [2**a]
       ╜#"{:0%sb}"%         push "{:0nb}"
                   f#       format and explode string
                            (push binary representation, padded with zeroes to n digits)
                       R  reverse list

V, 16, 11 bytes
Ài0 ÀÄòjl

Try it online!

Common Lisp, 96 94 92 bytes
(lambda(n)(set'a(make-array(list n n):initial-element 0))(dotimes(i n)(setf(aref a i i)1))a)

Try it online!

PHP, 55 bytes
while($p**.5<$z=+$argn)echo$p%-~$z?0:1,"
 "[++$p%$z>0];

requires PHP 5.6 or later for the power operator. Note that the second line begins with a space!
Run as pipe with -nR or try it online.

Charcoal, 7 bytes
ＥθＥθ⁼κμ

Try it online!
This returns an array, which in Charcoal is not readable in its default format. A version using Wolfram Lists is included below for readability.
Explanation
Ｅθ       Map for each number from 0 to first input
   Ｅθ    Map for each number from 0 to first input
      ⁼κμ Return whether both loop indices (yes, indices) are the same. The variables here are: i = first loop variable, k = first loop index, l = second loop variable, m = second loop index.

Readable version
Even accepts input as unary :P

PHP 88 Bytes
Try it online
Code
<?php for($i=0;$i++<$argv;){$a=array_fill(1,$argv,0);$a[$i]=1;echo implode(",",$a)."
";}

Explanation
<?php
  for($i=0;$i++<$argv;){          // loop up to the argument
      $a=array_fill(1,$argv,0);   // create an array fill with 0 with length = $argv value
      $a[$i]=1;                   // use the current iteration to place the "1"
      echo implode(",",$a)."      // implode to output the matrix
     ";}

Output
  $argv=5

  1,0,0,0,0
  0,1,0,0,0
  0,0,1,0,0
  0,0,0,1,0
  0,0,0,0,1

Forth (gforth), 48 bytes
: f dup 0 do dup 0 do 0 i j = - . loop cr loop ;

Try it online!
Explanation
uses nested loops to output the matrix. For each element it outputs 1 if the indexes are equal, and 0 otherwise.
Code Explanation
:f           \ start a new word definition
  dup        \ duplicate input
  0 do       \ outer counted loop from 0 to input - 1
    dup      \ duplicate input again
    0 do     \ inner counted loop from 0 to input - 1
      0      \ put a 0 on the stack (used to convert -1 to 1)
      i j =  \ -1 if i equals j, 0 otherwise
      - .    \ subtract from 0 to convert -1 to 1, and output
    loop     \ end inner loop
    cr       \ output a newline
  loop       \ end outer loop
;            \ end word definition

D, 114 bytes
void f(int n){import std.stdio;int N=n*n;while(N--){if(N%(n+1))write("0 ");else write("1 ");if(N%n==0)writeln();}}

Try it online!

PARI/GP, 14 bytes
n->matrix(n)^0
Attempt This Online!
Takes the zeroth power of the zero matrix.
See also Charles's answer,

Pip, 3 bytes
EYa

Try It Online!
Builtin.

What's the shortest non-builtin solution you can find?

@DLosc I found a non-builtin solution of 6 bytes.

Nibbles, 6 5 bytes (10 nibbles)
.;,$.@==$_

.               # map across each value of
  ,$            # 1..input
 ;              # (saving this range)
    .           #   map across each value of
     @          #   the saved range (1..input again)
      ==$_      #     are the two values equal?

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/