title: Draw a Dragon Curve

text:
# Question
Title: Draw a Dragon Curve
You task for today: draw a dragon curve!

In case you don't know what a Dragon Curve is, here is an introductory ViHart video (Really cool, please watch!)

Your task: draw a dragon curve, iterated at least 9 times. You don't have to show iterations 1 through 9, you just have to show the final curve produced after completing (at least) 9 iterations. The curve must be drawn as straight lines connecting the points on the curve; the output should match one of the images below that shows 9 or more iterations (up to reflection, rotation, scaling, and variation in line width, line color, and background color). Your output must be large enough that the individual lines and the "boxes" that they form can be distinguished from each other; if two lines don't intersect in the curve, they shouldn't occupy the same or adjacent pixels in the output (there should be at least one pixel of the background visible between them). You can either display the image to the screen or saved the image to a file is accepted. The output must be graphical - it can't be ASCII art.

The shortest code in bytes wins, *however* include directives for libraries shouldn't be included in the byte count, and you may use graphics libraries or other libraries written for your language of choice if they were written before the posting.

Please include an image of the output of your program.

**Skip this paragraph if you watched the video:** For those of you who decided not to watch the video, the first 12 iterations of the dragon curve are shown below. For the purposes of this task, a dragon curve is a curve generated by the following rule: take the end-point of the current curve, create a second curve rotated 90 degrees around that end-point so that the end-point of the original curve is the starting point of the new curve, and join the two curves into a single curve where they meet. In the images shown below, each new iteration is generated by rotating the previous iteration 90 degrees clock-wise around the end-point each iteration. When the curve is displayed on the screen, it's not obvious which end counts as the "end-point", however when the curve is stored as a array of points, it's easy to define the "end-point" as the last point in the array.

Ascii art is appreciated, but not accepted: This is graphical output, not ascii-art.

# Answer
> 7 votes
**x86, MSDOS, 16 bytes**

I wrote this a while ago, to my knowledge the smallest routine for producing a dragon fractal. It uses no real iterations, rather plots every contained discrete pixel inside the fractal directly, showing the *final* image. It's included with many other tiny productions in this pack. The 16 byte version was the end of my effort to get the dragon fractal as small as possible, starting 2014 with this 32 byte production.

Hex

```
14 10 19 CA D1 FA 10 DE 01 D1 CD 10 B4 0C EB F0

```

Code

```
S:
adc al,0x10
sbb dx,cx
sar dx,0x01
adc dh,bl
add cx,dx
int 0x10
mov ah,0x0C
jmp short S

```

# Answer
> 9 votes
## Python 2/3, ~~169~~ ~~167~~ ~~150~~ ~~111~~ ~~98~~ 78 Bytes

*Note that the import is not included in the byte count, according to the challenge specs.*

Thanks to @AlexHall for saving 39(!) bytes and @nedla2004 for another 13

```
from turtle import*
o=[90]
for z in o*9:o+=[90]+[-x for x in o[::-1]]
fd(5)
for i in o:rt(i);fd(5)

```

Starts by generating a list or right (90) and left (-90) turns, then goes through the list and moves the turtle.

Generated Output:

EDIT: If this is too boring too watch, add `speed(0)` right before the first `fd(5)`. It will run the same, except the turtle will move much faster.

# Answer
> 7 votes
# Logo, 43 bytes

```
for[i 1 512][fd 9 lt :i/(bitand :i -:i)*90]

```

Try with interpreter at http://www.calormen.com/jslogo/#

This uses the same principle as my previous ASCII art answer and the formula on at wikipedia except I reversed the direction to match the image in the question:

> First, express n in the form `k*(2^m)` where k is an odd number. The direction of the nth turn is determined by k mod 4 i.e. the remainder left when k is divided by 4. If k mod 4 is 1 then the nth turn is ~~R~~ L; if k mod 4 is 3 then the nth turn is ~~L~~ R

`bitand :i -:i` finds the least significant bit of `i`. We divide `i` by this to shitft `i` right the required amount, giving the required odd number `k`. There is no need to distinguish between left and right turns; we just turn left by `k*90` degrees and rely on the fact that rotation is a modulo 360 operaton to perform the modulo for us.

**Output**

use `ht` to hide turtle if required.

**Output (modified)**

The following shows how the curve is a single strand.

```
bk 6 for[i 1 512][fd 6 rt :i/(bitand :i -:i)%4*45-90 fd 3 rt :i/(bitand :i -:i)%4*45-90]

```

# Answer
> 5 votes
# Underload, 196 bytes

```
()()(<svg width="99" height="147">)S(<g transform="translate):S((33,33)">)S((3,0)rotate)*a(*a(~*)*~("><path d="M0h3" stroke="#"/>)~*a(*)**:(-90)a~^~(90)a~^)*::*:**:*^S(</g>)(:*)::*:**:*^S(</svg>)S

```

I thought it might be interesting to try this challenge in a low-powered esolang; Underload does fairly well for a language with such a low number of commands.

The output is an SVG file with very heavily nested tags, and some golfing shortcuts. So far, I haven't found a browser that can display it (Firefox hangs for several minutes trying to load it, and both Firefox and Chromium give a blank screen). Most image processing programs can't load it either (making it hard to convert to another format), but I managed to load it in the image viewer Eye of Gnome (which is part of the default install on Ubuntu). So I took a screenshot of the image so that you can see it (the actual image has a transparent background, but you can't really screenshot transparent):

We need to specify the image size explicitly. Picking an appropriate orientation for the image, drawing everything at the minimum legal size, and doing the minimum number of iterations specified by the challenge, gives us an image that *just* fits into 99 pixels wide, saving a byte. It's nice when things work out like that.

The general algorithm used for drawing the image is to maintain two variables (Underload doesn't name variables, but I thought of them as *x* and *y*), both initially empty. Then we repeatedly replace (*x*, *y*) with (*x*, turn left and move forward, *y*) and (*x*, turn right and move forward, *y*). After ten iterations, both *x* and *y* hold a nine-iteration dragon curve.

There are a few micro-optimizations and Underload-specific tricks, too. In order to avoid too much messing around with the top of the stack, each loop iteration, we start by combining *x* and *y* into the function "return the string created by concatenating: *x*, a turn instruction, the function argument, a move-forward instruction, and *y*." This function only takes up one space on the stack, so we can duplicate it, call it with `-90` as an argument, swap the return value under the duplicate, and call it with `90` as an argument, to get hold of new values for *x* and *y* without ever needing to touch more than the top two elements of the stack (which are by far the most commonly accessible). This function is code-generated at runtime. The generator itself is also code-generated at runtime, in order to allow it to reuse the string `<g transform="translate` that's also used to set the origin of the image. We generate all the open tags first, and then because all the close tags are just `</g>`, we can output 1024 close tags via simply repeating the string, without worrying about matching them to the open tags. (Writing numbers efficiently in Underload is an interesting problem in its own right; `(:*)::*:**:*` is probably the most efficient way to write 1024, though, translating to "2 to the power of (1 + 2×2) × 2".

Underload doesn't have any graphics libraries, so I produce SVG using a combination of drawing lines in a fixed position, and rotating the image around a given point; instead of turning the pen, we turn the paper. The idea is that by drawing a line, rotating the entire image, drawing another line, rotating the image again, etc., we can effectively simulate turtle graphics without having to do any arithmetic or use any graphics libraries, as all the lines are drawn in the same location. Of course, that means that we have some very heavily nested rotate-the-image tags, which confuses many SVG viewers.

Styling the image would count against the byte count, so I needed to give the minimum styling needed to display the image. This turns out to be `stroke="#"`, which more or less translates as "the line needs to be some color"; this seems to be expanded to drawing it in black. (Normally you'd specify the color as, say, "#000".) The background is transparent by default. We don't specify a stroke width, but the choice picked by Eye of Gnome leaves everything visible.

Many Underload interpreters struggle with this program, e.g. the one on Try It Online crashes, because it generates some very large strings internally. The original online Underload interpreter works, though. (Interestingly, the very first interpreter was online, so the language was usable online before it was usable offline.)

Something I'm slightly uneasy about is that there only seem to be 1023 line segments here, and we'd expect 1024. It could be that one of the segments at the end isn't being drawn with this algorithm (it'd be drawn on the next iteration instead). If that's disqualifying, it may be possible to adapt the program, but it might well end up considerably longer. (It's not like this challenge is going to win the competition anyway; there are already several shorter entries.)

# Answer
> 4 votes
# LindenMASM, 51 Bytes

LindenMASM was a language I created for a challenge a while ago that will forever live in the Sandbox. It makes use of the concept of Lindenmayer systems to draw things like Dragon curves, fractal plants, Sierpinski triangles, etc.

The source code is as follows:

```
STT
AXI FX
INC 9
SET F 0
RPL X X+YF+
RPL Y -FX-Y
END

```

To set this up for `n = 6` for example:

```
STT
AXI FX
INC 6
SET F 0
RPL X X+YF+
RPL Y -FX-Y
END

```

This produces the following image via Python 3's `turtle`:

There may be a slight numbering difference for iterations, as in the Lindenmayer system the first iteration is a single line. Here's what it looks like for `n = 10`:

Just for fun, here's what it looks like with 15 generations (with an added instruction `MOV 2` to make it a bit smaller):

Once you get up to 20 generations (with `MOV 0.5`) you can't really see the lines anymore, and it takes a LOT of steps to create (pairs of `+-` and `-+` are not optimized out). Here's what you get:

<sup>*Note that the current interpreter may present graphical issues for smaller amounts of generations, i.e. possibly not drawing to the screen. Unfortunately when this interpreter was created there were no issues, a possible change in Python 3 could have caused this or it could just be my system*</sup>

# Answer
> 4 votes
# MATL, 26 bytes

```
0J1_h9:"tPJ*h]hYsXG15Y01ZG

```

If different scales in the two axes are accepted, the code can be reduced to 19 bytes:

```
0J1_h9:"tPJ*h]hYsXG

```

The figures below correspond to the equal-scale (26-byte) version.

The code above produces the 9-th (0-based) iteration, that is, the tenth image in the challenge:

For other values change the `9` in the code, or replace it by `i` to take the number as user input. For example, the result for `13` is:

### Explanation

This uses a loop to gradually build an array of the *steps* followed by the curve in the complex plane. For example, the first two steps are `1j` (up) and `-1` (left).

In each iteration, the array of steps so far is copied. The copy of the array is *reversed*, *multiplied* by `1j` (to rotate 90 degrees), and *concatenated* to the original.

After the loop, a *cumulative sum* of the steps gives the actual points, which are then plotted in the complex plane.

```
0                          % Push 0
 J1_h                      % Push array [1j, -1]. This defines the first two steps
     9:                    % Push [1, 2, ..., 9]
       "                   % For each
        t                  %   Duplicate the array of steps so far
         P                 %   Reverse
          J*               %   Multiply by 1j
            h              %   Concatenate horizontally to previous steps
             ]             % End
              h            % Concatenate with the initial 0
               Ys          % Cumulative sum
                 XG        % Plot. Complex numbers are plotted with real and imag as x and y
                   15Y0    % Push string 'equal'
                       1ZG % Set equal scale in the two axes

```

# Answer
> 3 votes
# Mathematica 86 bytes

```
{1,-1}
r=Reverse;Graphics@Line@Nest[Join[l=Last@#;h=#-l&/@#,r[r@#%&/@h]]&,{{0,0},%},9]

```

How it works: `{1,-1}` Outputs `{1,-1}`. It basically "pushes it to the stack". This value can be recalled with `%`. `r=Reverse` basically just renames the Reverse function because I use it twice in the code. The `Graphics@Line@` just takes a list of points and draws a line connecting them. The real meat of the problem happens in this code segment: `Nest[Join[l=Last@#;h=#-l&/@#,r[r@#%&/@h]]&,{{0,0},%},9]`. Lemme tell you - that segment is complicated as f\******ck. Here's what `Nest` does: `Nest[f,x,9]`outputs the result of calling `f[f[f[f[f[f[f[f[f[x]]]]]]]]]`.

In my code, this first argument `f` is: `Join[l=Last@#;h=#-l&/@#,r[r@#%&/@h]]&`, the second argument `x` is `{{0,0},%}` (which evaluates to `{{0,0},{1,-1}}`), and the third argument is `n`, which is just 9 (which will just apply the first argument to the second argument 9 times).

The most complex part of all is this first argument: `Join[l=Last@#;h=#-l&/@#,r[r@#%&/@h]]&`, which is a giant mess of almost pure syntactic sugar. I was *really* abusing mathematica's syntactic sugar for this one. That line of code represents mathematica's version of an anonymous function, except to shorten things I actually defined two separate anonymous functions within that anonymous function. Yep, that's legal, folks. Let's break it down.

`Join` takes two arguments. The first is `l=Last@#;h=#-l&/@#`, and the second is `r[r@#%&/@h]`.

**The first argument of Join:** Inside the "main" anonymous function, `#` is a list of all the points at the current iteration in the curve. So `l=Last@#;` means "Take the point in the list of points you recieved as input, and assign that point to the variable `l`. The next segment, `h=#-l&/@#`, is a little more complex. It means "You have a function. This function takes a point as input, subtracts `l` from it, and returns the result. Now, apply that function to every element in the list of points you received as input to generate a list of shifted points, and assign that new list to the variable `h`.

**The second argument of Join:** `r[r@#%&/@h]` has literally the most complex syntax I've ever written. I can't believe any code segment could contain something like `@#%&/@` \- it looks like I'm cursing like a cartoon character in the middle of a program! But it's possible to break it down. Remember - `r[x]` takes a list of points and returns that list in reverse order. `r@#%&` is an anonymous function that reverses it's input, then multiplies it by the value storied in `%` (which is `{1,-1}`), and returns the result. Basically it rotates it's input 90 degrees, but in code as short as I could possibly write. Then `r@#%&/@h` means "Output a new list that is every point in `h` rotated 90 degrees."

So overall, `Join[l=Last@#;h=#-l&/@#,r[r@#*%&/@h]]&` is a function that takes a list of points as an input, and adds on that same list of points rotated 90 degrees to get the next iteration of the curve. This is repeated 9 times to get the dragon curve. Then it's the resulting list of points is drawn to the screen as a line. And the output:

# Answer
> 3 votes
# Python 2, 43 bytes

This answer is 43 bytes not including the import statement and it's largely based on Level River St's Logo answer and their use of `i/(i&-i)` in their code. Try it online at trinket.io

```
from turtle import*
for i in range(1,513):fd(9);rt(90*i/(i&-i))

```

Here is a picture of the output.

# Answer
> 3 votes
# Mathematica, ~~56~~ 55 bytes

```
Graphics@Line@AnglePath[Pi/2JacobiSymbol[-1,Range@512]]

```

Explanation: OEIS A034947

Just for fun, here is a colored version of the 19th iteration.

# Answer
> 2 votes
# HTML + JavaScript, 182

```
<canvas id=C></canvas><script>c=C.getContext("2d")
C.width=C.height=400
s=n=9
x=y=200
for(i=d=0;i<=1<<n;d+=++i/(i&-i))
c.lineTo(x,y),
d&1?y+=d&2?s:-s:x+=d&2?-s:s
c.stroke()</script>
```

# Answer
> 2 votes
## Mathematica, 63 bytes

Using `AnglePath`

```
Graphics@Line@AnglePath[Pi/2Nest[Join[#,{1},-Reverse@#]&,{},9]]

```

# Answer
> 0 votes
# Haskell + diagrams, 179 bytes

```
import Diagrams.Prelude
import Diagrams.Backend.SVG
d 1=hrule 1<>vrule 1
d n=d(n-1)<>d(n-1)#reverseTrail#rotateBy(1/4)
main=renderSVG"d"(mkWidth 99)$strokeT(d 9::Trail V2 Double)

```

Output is a 99 pixels wide svg file with transparent background (an image 9 pixels wide would have a stroke too thick to recoqnize anything). Here it is rescaled and composed over a white background:

# Answer
> 0 votes
# tosh, 518 bytes

tosh is Scratch, but with text instead of blocks. At 518 bytes, this answer is probably even worse than Java.

This answer uses the same logic as @Theo's Python answer, but with strings of "L" and "R" instead of numbers, as Scratch's (and thus tosh's) list capabilities are awful.

You can run it as a Scratch project here. (tosh compiles to Scratch projects)

```
when flag clicked
set path to "R"
go to x: -50 y: 100
point in direction 90
pen down
set pen size to 2
clear
repeat 9
    set path copy to path
    set path to join (path) "R"
    set i to length of path copy
    repeat length of path copy
        if letter i of path copy = "R" then
            set path to join (path) "L"
        else
            set path to join (path) "R"
        end
        change i by -1
    end
end
set i to 0
repeat length of path
    change i by 1
    if letter i of path = "R" then
         turn cw 90 degrees
    else
         turn ccw 90 degrees
    end
    move 7 steps
end

```

## Explanation:

```
when flag clicked
set path to "R"
go to x: -50 y: 100
point in direction 90
pen down
set pen size to 2
clear

```

This first part makes the program run when the green flag is clicked (`when flag clicked`), sets the path variable to "R", and gets the sprite and stage in the proper state to be ready to draw.

```
repeat 9
    set path copy to path
    set path to join (path) "R"
    set i to length of path copy
    repeat length of path copy
        if letter i of path copy = "R" then
            set path to join (path) "L"
        else
            set path to join (path) "R"
        end
        change i by -1
    end
end

```

Now we get to the path generation code. It uses the same logic as @Theo's Python answer, except with strings of "R" and "L" instead of numbers, and we use nested loops instead of list comprehensions.

```
set i to 0
repeat length of path
    change i by 1
    if letter i of path = "R" then
         turn cw 90 degrees
    else
         turn ccw 90 degrees
    end
    move 7 steps
end

```

Finally, we draw the path by going through each letter of the path variable and turning left or right depending on the letter.

---
Tags: code-golf, graphical-output, fractal
---


# Question
Title: Prime containment numbers (golf edition)
This is sequence A054261.

The \\$n\\$th prime containment number is the lowest number which contains the first \\$n\\$ prime numbers as substrings. For example, the number \\$235\\$ is the lowest number which contains the first 3 primes as substrings, making it the 3rd prime containment number.

It is trivial to figure out that the first four prime containment numbers are \\$2\\$, \\$23\\$, \\$235\\$ and \\$2357\\$, but then it gets more interesting. Since the next prime is 11, the next prime containment number is not \\$235711\\$, but it is \\$112357\\$ since it's defined as the smallest number with the property.

However, the real challenge comes when you go beyond 11. The next prime containment number is \\$113257\\$. Note that in this number, the substrings `11` and `13` are overlapping. The number `3` is also overlapping with the number `13`.

It is easy to prove that this sequence is increasing, since the next number needs to fulfill all criteria of the number before it, and have one more substring. However, the sequence is not strictly increasing, as is shown by the results for `n=10` and `n=11`.

## Input

A single integer `n>0` (I suppose you could also have it 0-indexed, then making `n>=0`)

## Output

Either the `n`th prime containment number, or a list containing the first `n` prime containment numbers.

The numbers I have found so far are:

```
 1 =>             2
 2 =>            23
 3 =>           235
 4 =>          2357
 5 =>        112357
 6 =>        113257
 7 =>       1131725
 8 =>     113171925
 9 =>    1131719235
10 =>  113171923295
11 =>  113171923295
12 => 1131719237295

```

Note that `n = 10` and `n = 11` are the same number, since \\$113171923295\\$ is the lowest number which contains all numbers \\$\[2, 3, 5, 7, 11, 13, 17, 19, 23, 29\]\\$, but it also contains \\$31\\$.

Since this is marked code golf, get golfing! Brute force solutions are allowed, but your code has to work for any input in theory (meaning that you can't just concatenate the first n primes). Happy golfing!

# Answer
> 11 votes
# 05AB1E, 8 bytes

```
∞.ΔIÅpåP

```

Try it online!

**Explanation**

```
           # from
∞          # a list of infinite positive integers
 .Δ        # find the first which satisfies the condition:
       P   # all
   IÅp     # of the first <input> prime numbers
      å    # are contained in the number

```

# Answer
> 5 votes
# Jelly, 11 bytes

```
³ÆN€ẇ€µẠ$1#

```

Try it online!

Simple brute force. Not completely sure how `#`'s arity works, so there may be some room for improvement.

### How it works

```
³ÆN€ẇ€µẠ$1#    Main link. Input: Index n.
         1#    Find the first natural number N that satisfies:
³ÆN€             First n primes...
    ẇ€           ...are substrings of N
      µẠ$        All of them are true

```

# Answer
> 5 votes
# JavaScript (ES6),  ~~105 ... 92~~  91 bytes

```
n=>(k=1,g=(s,d=k++)=>n?k%d--?g(s,d):g(d?s:s+`-!/${n--,k}/.test(n)`):eval(s+';)++n'))`for(;`

```

Try it online!

### How?

We recursively build a concatenation of conditions based on the first \\$n\\$ primes:

```
"-!/2/.test(n)-!/3/.test(n)-!/5/.test(n)-!/7/.test(n)-!/11/.test(n)..."

```

We then look for the smallest \\$n\\$ such that all conditions evaluate to *false*:

```
eval('for(;' + <conditions> + ';)++n')

```

### Commented

```
n => (                             // main function taking n
  k = 1,                           // k = current prime candidate, initialized to 1
  g = (s,                          // g = recursive function taking the code string s
          d = k++) =>              //     and the divisor d
    n ?                            // if n is not equal to 0:
      k % d-- ?                    //   if d is not a divisor of k:
        g(s, d)                    //     recursive call to test the next divisor
      :                            //   else:
        g(                         //     recursive call with s updated and d undefined:
          d ?                      //       if d is not equal to 0 (i.e. k is composite):
            s                      //         leave s unchanged
          :                        //       else (k is prime):
            s +                    //         decrement n and add to s
            `-!/${n--,k}/.test(n)` //         the next condition based on the prime k
                                   //       the lack of 2nd argument triggers 'd = k++'
        )                          //     end of recursive call
    :                              // else (n = 0):
      eval(s + ';)++n')            //   complete and evaluate the code string
)`for(;`                           // initial call to g with s = [ "for(;" ]

```

# Answer
> 5 votes
# Java 8, 143 bytes

```
n->{int r=1,f=1,c,i,j,k;for(;f>0;r++)for(i=2,f=c=n;c>0;c-=j>1?1+0*(f-=(r+"").contains(j+"")?1:0):0)for(j=i++,k=2;k<j;)j=j%k++<1?0:j;return~-r;}

```

Try it online.
NOTES:

1. Times out above `n=7`.
2. Given enough time and resources it only works up to a maximum of `n=9` due to the size limit of `int` (maximum of `2,147,483,647`).
    * With +4 bytes changing the `int` to a `long`, the maximum is increased to an output below `9,223,372,036,854,775,807` (about `n=20` I think?)
    * By using `java.math.BigInteger` the maximum can be increased to any size (in theory), but it will be around +200 bytes at least due to the verbosity of `java.math.BigInteger`'s methods..

**Explanation:**

```
n->{                   // Method with integer as both parameter and return-type
  int r=1,             //  Result-integer, starting at 1
      f=1,             //  Flag-integer, starting at 1 as well
      c,               //  Counter-integer, starting uninitialized
      i,j,k;           //  Index integers
  for(;f>0;            //  Loop as long as the flag is not 0 yet
      r++)             //    After every iteration, increase the result by 1
    for(i=2,           //   Reset `i` to 2
        f=c=n;         //   Reset both `f` and `c` to the input `n`
        c>0;           //   Inner loop as long as the counter is not 0 yet
        c-=            //     After every iteration, decrease the counter by:
           j>1?        //      If `j` is a prime:
            1          //       Decrease the counter by 1
            +0*(f-=    //       And also decrease the flag by:
                   (r+"").contains(j+"")?
                       //        If the result `r` contains the prime `j` as substring
                    1  //         Decrease the flag by 1
                   :   //        Else:
                    0) //         Leave the flag the same
           :           //      Else:
            0)         //       Leave the counter the same
      for(j=i++,       //    Set `j` to the current `i`,
                       //    (and increase `i` by 1 afterwards with `i++`)
          k=2;         //    Set `k` to 2 (the first prime)
          k<j;)        //    Inner loop as long as `k` is smaller than `j`
        j=j%k++<1?     //     If `j` is divisible by `k`
           0           //      Set `j` to 0
          :            //     Else:
           j;          //      Leave `j` the same
                       //    (If `j` is unchanged after this inner-most loop,
                       //     it means `j` is a prime)
  return~-r;}          //  Return `r-1` as result

```

# Answer
> 4 votes
# Ruby, 58 bytes

```
->n,i=1{i+=1until Prime.take(n).all?{|x|/#{x}/=~"#{i}"};i}

```

Try it online!

Brute-force, works up to 7 on TIO.

# Answer
> 4 votes
# Pyth, 14 bytes

Extremely, *extremely* slow, times out for \\$n\>5\\$ on TIO.

```
f@I`M.fP_ZQ1y`

```

Try it online!

```
f@I`M.fP_ZQ1y`     Full program. Q is the input.
f                  Find the first positive integer that fulfils the condition.
 @I`M.fP_ZQ1y`     Filtering condition, uses T to refer to the number being tested.
     .f   Q1       Starting at 1, find the first Q positive integers (.f...Q1) that
       P_Z         Are prime.
   `M              Convert all of those primes to strings.
  I                Check whether the result is invariant (i.e. doesn't change) when...
 @          y`     Intersecting this list with the powerset of T as a string.

```

---

# Pyth, 15 bytes

Slightly faster but 1 byte longer.

```
f.A/L`T`M.fP_ZQ

```

Try it online!

```
f.A/L`T`M.fP_ZQ     Full program. Q is the input.
f                   Find the first positive integer that fulfils the condition.
 .A/L`T`M.fP_ZQ     Filtering condition, uses T to refer to the number being tested.
         .f   Q     Starting at 1, find the first Q positive integers (.f...Q) that
           P_Z      Are prime.
       `M           Convert all of those primes to strings.
 .A/L               And make sure that they all (.A) occur in (/L)...
     `T             The string representation of T.

```

# Answer
> 3 votes
# Jelly, 14 bytes

```
³RÆNṾ€ẇ€ṾȦ
Ç1#

```

Try it online!

# Answer
> 3 votes
# Perl 6, ~~63~~ 59 bytes

*-4 bytes thanks to nwellnhof*

```
{+(1...->\a{!grep {a~~!/$^b/},(grep &is-prime,2..*)[^$_]})}

```

Try it online!

A brute force solutions that times out on TIO for numbers above 5, but I'm pretty sure it works correctly. Finds the first positive number that contains the first `n` primes. Here's a solution that doesn't time out for `n=6`.

### Explanation:

```
{                                                             } # Anonymous code block
 first                                                    2..*  # Find the first number
       ->\a{                                            }       # Where:
            !grep     # None of
                                                   [^$_]  # The first n
                              (grep &is-prime,2..*)       # primes
                  {a~~!/$^b/},   # Are not in the current number

```

# Answer
> 3 votes
# Charcoal, 42 bytes

```
≔¹ηＷ‹ＬυＩθ«≦⊕η¿¬Φυ¬﹪ηκ⊞υη»≔¹ηＷΦυ¬№ＩηＩκ≦⊕ηＩη

```

Try it online! Link is to verbose version of code. Explanation:

```
≔¹ηＷ‹ＬυＩθ«≦⊕η¿¬Φυ¬﹪ηκ⊞υη»

```

Build up the first `n` prime numbers by trial division of all the integers by all of the previously found prime numbers.

```
≔¹ηＷΦυ¬№ＩηＩκ≦⊕η

```

Loop through all integers until we find one which contains all the primes as substrings.

```
Ｉη

```

Cast the result to string and implicitly print.

The program's speed can be doubled at a cost of a byte by replacing the last `≦⊕η` with `≦⁺²η` but it's still too slow to calculate `n>6`.

# Answer
> 2 votes
# SAS, 149 bytes

```
data p;input n;z:i=1;a=0;v+1;do while(a<n);i+1;do j=2 to i while(mod(i,j));end;if j=i then do;a+1;if find(cat(v),cat(i))=0 then goto z;end;end;cards;

```

Input is entered following the `cards;` statement, like so:

```
data p;input n;z:i=1;a=0;v+1;do while(a<n);i+1;do j=2 to i while(mod(i,j));end;if j=i then do;a+1;if find(cat(v),cat(i))=0 then goto z;end;end;cards;
1
2
3
4
5
6
7

```

Outputs a dataset `p`, with the result `v`, with an output row for each input value. Should technically work for all the given test-cases (the max integer with full precision in SAS is 9,007,199,254,740,992), but I gave up after letting it think for 5 minutes on n=8.

Explanation:

```
data p;
input n; /* Read a line of input */

z: /* Jump label (not proud of this) */
    i=1; /* i is the current value which we are checking for primality */
    a=0; /* a is the number of primes we've found so far */
    v+1; /* v is the final output value which we'll look for substrings in */

    do while(a<n); /* Loop until we find the Nth prime */
        i+1;
        do j=2 to i while(mod(i,j));end; /* Prime sieve: If mod(i,j) != 0 for all j = 2 to i, then i is prime. This could be faster by only looping to sqrt(i), but would take more bytes */
        if j=i then do; /* If i is prime (ie, we made it to the end of the prime sieve)... */
            a+1;
            if find(cat(v),cat(i))=0 then goto z; /* If i does not appear as a substring of v, then start all over again with the next v */
        end;
    end;

/* Input values, separated by newlines */
cards;
1
2
3
4
5
6
7

```

# Answer
> 2 votes
# Python 2, 131 bytes

```
f=lambda n,x=2:x*all(i in`x`for i in g(n,2))or f(n,x+1)
def g(n,x):p=all(x%i for i in range(2,x));return[0]*n and[`x`]*p+g(n-p,x+1)

```

Try it online!

`f` is the function.

# Answer
> 2 votes
# Python 2, 91 bytes

```
n=input();l=[]
P=k=1
while~-all(`x`in`k`for x in(l+[l])[:n]):P*=k*k;k+=1;l+=P%k*[k]
print k

```

Try it online!

# Answer
> 1 votes
# Japt, ~~20~~ 18 bytes

Far from my finest work, I was just happy to get it working after the day I've had. I'm sure I'll end up tapping away at it down the boozer later!

```
_õ fj ¯U e!øZs}aUÄ

```

Try it \- takes 13 seconds to run for an input of `7`, throws a wobbly after that (the updated version craps out at `5` for me, but that might just be my phone).

# Answer
> 1 votes
# Haskell, 102 bytes

```
import Data.List
f n|x<-[2..n*n]=[a|a<-[2..],all(`isInfixOf`show a).take n$show<$>x\\((*)<$>x<*>x)]!!0

```

Try it online!

## Explanation / Ungolfed

Since we already have `Data.List` imported we might as well use it: Instead of the good old `take n[p|p<-[2..],all((>0).mod p)[2..p-1]]` we can use another way of generating all primes we need. Namely, we generate a sufficient amount of composites and use these together with `(\\)`:

```
[2..n*n] \\ ( (*) <$> [2..n*n] <*> [2..n*n] )

```

Using `n*n` suffices because \\$\pi(n) \< \frac{n^2}{\log(n^2)}\\$. The rest is just a simple list comprehension:

```
[ a | a <- [2..], all (`isInfixOf` show a) . take n $ enoughPrimes ] !!0

```

---
Tags: code-golf, math, primes, integer
---


title: The Random Quine

text:
# Question
Title: The Random Quine
Write a program that is capable of randomly generating itself.

It must do this based on the *tokens* used in its source code. If your program's source code is composed of 50 unique tokens and is 60 tokens long, then the program should output 60 tokens where each token is randomly chosen from one of the 50 unique tokens.

For example, this program would have a one in 50^60 chance to reproduce itself.

**What is a token?** That depends on the language. For example, identifiers (`foo_bar`), keywords (`while`), and numbers (`42`) would count as tokens in most languages. Whitespace would not count in most languages.

**Additional rules:**

* Output may only contain tokens found in the programs source code, separated by the appropriate delimiter
* Output must be the same length as the program's source code, counted by tokens
* Only one programming language may be used
* Source code must have at least 3 unique tokens
* Exclude comments from the source code
* Program should only have a one in U^L chance to reproduce itself

**Scoring:** The program that has the best chance to reproduce itself, wins.

# Answer
## Python 2, 3^-3 = 0.037

`exec` abuse is quite handy for reducing the token count. Now updated to not read the source file!

```
exec '' """
s = '''{a}
s = {b}
s = s.format(a='"'*3, b="'"*3+s+"'"*3)
import random
tokens = ['exec', "''", s]
print random.choice(tokens), random.choice(tokens), random.choice(tokens),
{a}'''
s = s.format(a='"'*3, b="'"*3+s+"'"*3)
import random
tokens = ['exec', "''", s]
print random.choice(tokens), random.choice(tokens), random.choice(tokens),
"""

```

The extra `''` between `exec` and the giant triple-quoted string is just to pad the token count to the required minimum of 3. It gets merged into the second string due to implicit string literal concatenation.

Original, opening-the-source-file version:

```
exec '''
# String literals are one token!
import random
import tokenize

with open(__file__) as f:
    tokens = [x[1] for x in tokenize.generate_tokens(f.readline)][:-1]

''' '''
# Splitting the string into two strings pads the token count to the minimum of 3.

print random.choice(tokens), random.choice(tokens), random.choice(tokens),
'''

```

Strictly speaking, the Python grammar places an ENDMARKER token at the end of the source file, and we can't produce a source file with ENDMARKERs randomly strewn about. We pretend it doesn't exist.
> 12 votes

# Answer
## Javascript, 102 tokens, 33 unique, 7.73×10-154

Note, this is a true quine. It doesn't read the file or use `eval` or `Function.toString`

```
meta = "meta = ; out = '' ; tokens = meta . split ( '\\u0020' ) ; tokens . push ( '\"' + meta + '\"' ) ; length = tokens . length ; tmp = length ; unique = { } ; while ( tmp -- ) unique [ tokens [ tmp ] ] = unique ; unique = Object . keys ( unique ) ; tmp = unique . length ; while ( length -- ) out += tokens [ ~~ ( Math . random ( ) * tmp ) ] + '\\u0020' ; console . log ( out )";
out = '';
tokens = meta.split('\u0020');
tokens.push('"' + meta + '"');
//console.log(tokens);
length = tokens.length;
tmp = length;
unique = { };
while(tmp--) unique[tokens[tmp]] = unique;
unique = Object.keys(unique);
//console.log(unique);
tmp = unique.length;
while(length--)
    out += unique[~~(Math.random() * tmp)] + '\u0020';
console.log(out)

```
> 5 votes

# Answer
# Python: P(generating program in 1 trial) = 3.0317 * 10^-123

34 unique tokens, 80 total tokens. Note that there is a space at the end of each line.

```
import tokenize , random
tokens = [ x [ 1 ] for x in tokenize . generate_tokens ( open ( __file__ , 'r' ) . readline ) ] [ : -1 ]
s = ''
for x in tokens : s += random . choice ( list ( set ( tokens ) ) ) ; s += [ ' ' , '' ] [ s [ -1 ] == '\n' ]
print s

```

Sample output:

```
' ' random len set 'r' , for ( list , import ] ] tokens : random [ for '\n' import readline readline 'r' tokens [ len 'r' import '' choice '' '' for in ( readline ( = open readline , list 1 list s += for s 1 , '' : 1 += list len - __file__ ; open __file__ print . - ] 'r' for import [ print . ,

; . [ [ print print __file__ generate_tokens ] ; open ] , readline

```

Thanks to the other Python solution by user2357112 for reminding me to discard the last token and use `__file__` which I was previously ignorant of.
> 4 votes

# Answer
# J - 1 in 1117 = 1.978 x 10-18

```
;(?11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11){~.;:(,,,{:,{:)';(?11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11){~.;:(,,,{:,{:)'''

```

J has a bunch of handy little tools for getting these kinds of jobs done.

* First of all, *any space separated string of numbers is one token*. It means a one-dimensional array of those numbers. This is how J's lexer works. By the way, that's seventeen `11`s, if anyone is curious.
* `(,,,{:,{:)'QUINE'''` is a common quine trick in J, made to use as few tokens as possible: `{:` means *Tail*, so it appends the string to itself, and then adds two copies of the last character to the end of that. Since the last character is a single quote (J uses Pascal-style strings), the result is `QUINE'QUINE'''`.
* `;:` is a tokenizer, and breaks up an input string as though it was J code, returning a list of boxes. The length of this result is 17.
* `~.` takes all the unique elements of this array. The length of this result is 11.
* `?` is called *Roll*. For each integer in its argument, it selects a random positive number greater than or equal to zero, less than that number. So here J will generate 17 numbers from 0 to 10 inclusive.
* `{` uses the random indices to select items out of our list of unique-tokens-in-boxes.
* `;` opens all these boxes and runs the result together.

Some examples follow. The indented lines are the input prompts, and the lines flush with the left side are the interpreter's output.

```
   ;(?11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11){~.;:(,,,{:,{:)';(?11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11){~.;:(,,,{:,{:)'''
~.~.(?;;:11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11';(?11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11){~.;:(,,,{:,{:)'''(){11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11){(;:;
   ;(?11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11){~.;:(,,,{:,{:)';(?11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11){~.;:(,,,{:,{:)'''
{';(?11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11){~.;:(,,,{:,{:)''',?{:;:{:';(?11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11){~.;:(,,,{:,{:)'''11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11{:{;(;:{:,~.

```
> 3 votes

# Answer
# Postscript

This was a fun one

```
/cvx /cvx cvx /exec /exec cvx /dup /rand /mod /get /== /array /astore /realtime
/srand /repeat 6 17 54 17 /array cvx exec /astore cvx exec 54 /dup cvx /rand
cvx 17 /mod cvx /get cvx /== cvx 6 /array cvx exec /astore cvx exec cvx /realtime
cvx exec /srand cvx exec /repeat cvx exec

```

There are 17 unique tokens and 54 tokens total for approx 1 in 3.6e-67 chance.
> 2 votes

# Answer
## Whitespace, 3^-205 3^-189 3^-181 3^-132 ~= 10^-63

This is a Whitespace program that, when seeded with random characters, has a 1 in 3^132 chance of reproducing itself (3 distinct tokens, repeated 132 times). It must be seeded with at least 132 random characters when run, (Whitespace has no built-in random or date function to seed with) e.g. `some_whitespace_interpreter my_quine.ws <some_random_source >quine_output.ws`. The score would be improved if the program could be golfed any more, but this is my first "real" Whitespace program, so I'll just leave it with my meager amount of golfing.

Plain Whitespace code, or see it run: (to try it, click "edit", copy the stuff inside the \
 tags; should be 132 characters with Unix-style EOL)

```

```

Code annotated with what command is what (not technically a quine, as it won't reproduce the comments):

```
stack push_number + 0 end
stack push_number + 1   0 0 1   end
heap        store stack push_number + 1 end
stack push_number + 1   0 0 0 0 0 end
heap        store stack push_number + 1 0 end
stack push_number + 1   0 1 0 end
heap        store stack push_number + 1 0 0 0 0 0 1 1   end
flow
make_label  loop_begin
stack push_number + 1   1   end
IO
read    character stack push_number + 1 1   end
heap        retrieve    stack push_number + 1   1   end
arithmetic   modulo     heap        retrieve    IO
print char stack push_number + 1    end
arithmetic   subtract   stack duplicate
 flow
jump_if_zero        end_prog
flow
jump_to
loop_begin
flow
make_label  end_prog
flow
end_program

```

If the seed just happens to be equivalent (the characters are taken mod 3 to be converted to the tokens) to this, it will succeed:

```
CCCCACCCBCCBABBCCCCBACCCBCCCCCABBCCCCBCACCCBCBCABBCCCCBCCCCCBBAACCBACCCBBABABCCCCBBABBBCCCBBABCBBBBBBACCCCCBABCCBCACABBAACABAACCAAAA
```

It's a pretty simple program, roughly equivalent to this Ruby program:

```
i = 131
while true
    print '\t \n'[STDIN.getc.ord % 3]
    i = i - 1
    break if i < 0
end

```
> 2 votes

# Answer
## Perl, 27 tokens, P = 1.4779 x 10-34

```
@ARGV=$0;print$W[rand@W]for@W=split/(\W)/,readline

```

Last edit: use `@ARGV=$0` instead of `open*ARGV,$0` to save a token.

* 15 unique tokens
* 4 tokens appear 2 times (`=`, `/`, `@`, `$`)
* 1 token appears 4 times (`W`)

So I think that makes the probability (pow(2,2\*4) * pow(4,4))/pow(27,27), about 1.48E-34.

If the source code is in a file called `ARGV`, then you can use this 26 token solution with P =~ 2.193 x 10-31:

```
@ARGV=ARGV;print$ARGV[rand@ARGV]for@ARGV=split/(\W)/,readline

```
> 1 votes

# Answer
# Perl 6, \\$1\\$ in \\$3^3\\$ = \\$0.037037...\\$

(I know this isn't code-golf, but...)

```
q[say |roll <<~~"q[$_]".EVAL>>: 3]~~.EVAL

```

Try it online!

Much the same as the Python answer, where the first token is a string literal that is evaluated. The tokens are

```
q[say |roll <<~~"q[$_]".EVAL>>: 3]   String literal
~~                                   Smartmatch operator
.EVAL                                Function call

```

### Explanation:

```
q[say |roll <<~~"q[$_]".EVAL>>: 3]         # Push as string literal
                                  ~~       # Smartmatch by setting $_ to the string literal
                                    .EVAL  # Eval the string
            <<~~"q[$_]".EVAL>>             # From the list of tokens
       roll                   : 3          # Pick 3 times with replacement
  say |                                    # Join and print

```
> 0 votes

---
Tags: code-challenge, quine
---


title: Programming Tetris Blocks (Literally)

text:
# Question
Title: Programming Tetris Blocks (Literally)
In the game Tetris, there are 7 types of bricks or *Tetr**i**minoes*, which are mathematically known as tetr**o**minoes because they are all made with 4 square segments:

The have the names I, J, L, O, S, T, and Z, that correspond to their approximate shapes. Counting 90° rotations, there are 19 unique shapes in total:

```
I
I
I
I

IIII

 J
 J
JJ

JJJ
  J

JJ
J
J

J
JJJ

L
L
LL

  L
LLL

LL
 L
 L

LLL
L

OO
OO

 SS
SS

S
SS
 S

TTT
 T

T
TT
T

 T
TTT

 T
TT
 T

ZZ
 ZZ

 Z
ZZ
Z

```

# Challenge

Write a rectangular block of code that acts as the base segment these 19 shapes are made from. When this code is arranged into one of the shapes, a program should be formed that outputs the single uppercase letter associated with that shape. This must work for all 19 shapes.

The leading empty areas present in some of the 19 shapes are filled in entirely with spaces (). The trailing empty areas are not filled with anything (so the programs are not always exactly rectangular).

## Example

Suppose this was your code block:

```
ABC
123

```

Then either arrangement of the block into the S Tetris piece would be a program that prints `S`:

```
   ABCABC
   123123
ABCABC
123123
```

```
ABC
123
ABCABC
123123
   ABC
   123
```

(Notice that all leading empty space is filled with space characters, and that no lines have any trailing spaces.)

The same idea applies to all 6 other pieces and their respective rotations.

## Notes

* All 19 final programs are to be run in the same programming language.
* If desired, you may add a single trailing newline to *all* programs (not just some, all or none).
* Your code block may contain any characters (including spaces) that aren't line terminators.
* Output the letter to stdout (or your language's closest alternative) with an optional trailing newline.

## Scoring

The submission whose code block has the smallest area (width times height) wins. This essentially means the shortest code wins, which is why this is tagged . Tiebreaker goes to the *highest voted* answer.

The `ABC\n123` example has area 3×2 = 6.

## Snippet

Given a code block, this snippet will generate all 19 programs:

```
<script>function drawShape(X,n,v){for(var t="",e=0;e<v.length;e++)for(var l=0;l<n.length;l++){for(var r=0;r<v[e].length;r++)t+="X"===v[e][r]?n[l]:X[l];t+="\n"}return t}function go(){var X=document.getElementById("input").value;if(0!=X.length){var n=X.replace(/./g," ").split("\n");X=X.split("\n");for(var v="I (v1):|I (v2):|J (v1):|J (v2):|J (v3):|J (v4):|L (v1):|L (v2):|L (v3):|L (v4):|O:|S (v1):|S (v2):|T (v1):|T (v2):|T (v3):|T (v4):|Z (v1):|Z (v2):".split("|"),t="X\nX\nX\nX|XXXX| X\n X\nXX|XXX\n  X|XX\nX\nX|X\nXXX|X\nX\nXX|  X\nXXX|XX\n X\n X|XXX\nX|XX\nXX| XX\nXX|X\nXX\n X|XXX\n X|X\nXX\nX| X\nXXX| X\nXX\n X|XX\n XX| X\nXX\nX".split("|"),e="",l=0;l<v.length;l++)e+=v[l]+"\n\n"+drawShape(n,X,t[l].split("\n"))+"\n";e=e.substring(0,e.length-2),document.getElementById("output").value=e}}</script><style>html *{font-family: monospace;}</style>Code Block:<br><textarea id='input' rows='8' cols='64'>ABC
123</textarea><br><button type='button' onclick='go()'>Go</button><br><br>All 19 Programs:<br><textarea id='output' rows='24' cols='64'></textarea>
```

# Answer
> 16 votes
# \<\>\< (Fish) - 12 * 32 = 384

I was planning to go for a more elegant solution, but I somehow ended up with this, which is pretty brute-force:

```
c  0  g84*%\
c2*0  g84*%\
0  84*g84*%\
c  84*g84*%\
c2*84*g84*%\
0  88*g84*%\
c  88*g84*%\
?v         \
;>?v~~?vv
"L" o;  >
"S" o; >~?v
"T" o;    >
;  >~?v"L"o
;     >"J"o
?v         \
 >~?v~~?vv
"I"  o;  >
"J"  o; >
    \~~?vv
"T"  o;  >
"Z"  o; >
?v         \
 >?v"J"o;
   >?v"Z"o;
"L"o;>?!v
"J"o;   >?v
"T"o;     >
?v?v"I"o;  >
   >"L"o;
 >?v"T"o;
   >?v"O"o;
     >"S"o;

```

It's pretty simple, it checks the code in a 3x3 square for text and uses the results to see which tetrimino corresponds to the code's shape. I didn't take a lot of effort to golf it yet.

Try the code here (after using the snippet to shape it like a tetrimino)

Example of code in shape Z (v1) here

# Answer
> 15 votes
# C (gcc), ~~26x20 = 520~~ ~~25x19 = 475~~ 23x17 = 391

```
#ifndef M            //
#define M(a,b)a##b   //
#define W(z,x)M(z,x) //
char*s,*S[]={"!!!!c",//
"8M !7! M8 878","77",//
"7!!MO887","788OM!!7"//
,"N7!78","7N87!"},r[5//
],*p=r;i=7;main(){for//
(;i--;)strstr(S[i],r)//
&&putchar("ITOJLSZ"[i//
]);}                 //
#endif               //
__attribute__((      //
constructor(__LINE__)//
))W(f,__LINE__)(){s= //
"                     \
";*p++=strlen(s)+12;}//

```

I was recently informed of GNU's function attributes, and most interestingly the `constructor` attribute, which allows for a more terse implementation of what I was doing in a more roundabout way in my earlier approach to this problem.

The thrust of the idea is the same as before: Build a string and search for it in a list to identify which tetris block the code is laid out as. This is done by calling functions, each one adding a character to the string. The complication was and remains that the number of functions varies.

Defining a function with `attribute((constructor(x)))` makes it so that the function is run before `main()` is entered, with the optional `x` being the priority (lower means it is run earlier). This removes the need for function pointers, which allows us to drop a macro, some declarations, and the calling chain.

Using `__LINE__` for priority is iffy, since priority levels 0-100 are reserved. However, it does not result in errors, only warnings, and those are plentiful when golfing, so what's a few more?

It would have helped shave another column off to not use priorities at all, but the order of execution does not seem to be defined. (They are reversed in this case, but other tests are inconclusive.)

Example of L v2 here

## Older, more portable, approach

```
#ifndef M              //
#define M(a,b) a##b    //
#define W(z,x)M(z,x)   //
#define F W(f,__LINE__)//
#define A W(a,__LINE__)//
char r[5],*S[]={"####k"//
,";<<US##;",";##SU<<;",//
";;",";T<;#","<S #;# S"//
"< <;<","T;#;<"},*s,*p=//
r;i;typedef(*T)();T a17//
,a36,a55,a74;main(){for//
(a17(),a36&&a36(),a55&&//
a55(),a74&&a74();i--;) //
strstr(S[i],r)&&putchar//
("ILJOZTS"[i]);}i=7;   //
#endif                 //
F();T A=F;F(){s=       //
"                       \
";*p++=strlen(s)+12;}  //

```

One of my favourite problems I've solved on this site.

I began by figuring each block would divine its own coordinates somehow. Rows are easy with `__LINE__`, and the number of horizontally adjacent blocks could be found by using the length of a string literal, like so:

```
char*s=//char*s=//
"       ""       "
;        ;

```

Take the length of the resulting string and and divide by a proper number and you have the width. Sadly, any empty space before the block is invisible by this method. I still suspected strings would be the solution, since whitespace only has meaning outside of strings very rarely, in things like `a+++b` vs. `a+ ++b`. I briefly considered something like that, but could not come up with anything useful. Another possibility would have been to let identifiers be "glued" together where blocks met:

```
A  BA  B

```

I would not be surprised if this could still make for an interesting solution.

Despite its simplicity, it took me quite some time to find the string solution, which is based on this block fragment:

```
s=//
"  \
";//

```

If the fragment has no horizontal neighbours, the newline on the second line is escaped by the backslash, creating a string of length 2. If, however, it does have a neighbour, the backslash will instead escape the quotion mark at the start of line 2 of the next block:

```
s=//s=//
"  \"  \
";//";//

```

This will create the string " \\" " of length 5.

More crucially, this also allows for detection of empty space before the block:

```
    s=//
    "  \
    ";//

```

Again, the newline is escaped, and the whitespace of the empty block to the left is included in the resulting string " " of length 6.

In total there are seven different configurations of blocks on a row that we need to worry about, and they all make strings of unique lengths:

```
2 "  "
---
s=//
"  \
";//

5 "  \"  "
---
s=//s=//
"  \"  \
";//";//

6 "      "
---
    s=//
    "  \
    ";//

9 "  \"      "
----
    s=//s=//
    "  \"  \
    ";//";//

10 "          "
---
        s=//
        "  \
        ";//

8 "  \"  \"  "
---
s=//s=//s=//
"  \"  \"  \
";//";//";//

11 "  \"  \"  \"  "
----
s=//s=//s=//s=//
"  \"  \"  \"  \
";//";//";//";//

```

The final blocks will of course not have such short length, but the principle is the same regardless of block size. This also has the bonus that a separate mechanism for detecting width is unnecessary. By adding a character corresponding to the length of this string to a results string, each of the 19 configurations yields a unique string, that needs only be compared to a suitable list once all the blocks have been run.

Once this was sorted, the next big problem was how to "visit" each row of blocks. In C, we are very limited to what can be done outside of functions. We also need `main()` to appear, but only once. The latter is easily achieved by some `#define`s, but if we want the code of subsequent blocks to be inside of `main()`, the problem of how to know when to put the final closing curly bracket. After all, we don't know how many rows of blocks will actually be used. So we need to have `main()` static and somehow the rest to be dynamic.

If the other block-rows are to be self-contained, they need to be functions, but we need to make sure each function has a name that is unique, while also being predictable enough to be callable from `main()`. We also need a mechanism for knowing which functions are actually there to be called. Generating unique names is solved by helper macros:

```
#define M(a,b) a##b     //
#define W(z,x)M(z,x)    //
#define F W(f,__LINE__) //
#define A W(a,__LINE__) //

```

Calling `F` will create an identifier whose name begins with an f and ends with the line number. `A` does the same but with a as prefix, which is used for the second part of the solution, which is function pointers. We declare four such pointers:

```
typedef(*T)();T a17,a36,a55,a74;

```

Since these are declared as global variables, they are conveniently set to NULL. Later on, each block-row will have the following piece of code:

```
F();T A=F;F()

```

This will first declare a function, define the appropriate function pointer to point to that function (we can only define globals once, but the earlier declaration did not count as a definition, even if it did initialise to NULL), and then define the actual function. This allows `main()` to call any function pointer that is non-NULL (a17 will never be NULL):

```
a17(),a36&&a36(),a55&&a55(),a74&&a74()

```

Doing so will build the string `r`, which is then looked for in the table of strings and if found, the appropriate letter is output.

The only remaining trick is that the list of strings to match against were shortened whenever ambiguity could be avoided, or overlapping strings could be conflated.

Example of L v2 here

# Answer
> 6 votes
# x86 opcode(.com), ~~86~~ 82 bytes

Tester:

```
org 100h
macro e {
db $F6,$04,$DF,$78,$13,$75,$08,$00,$C0,$40,$83,$C6,$52,$EB,$F1,$88
db $C2,$00,$D0,$00,$D0,$46,$EB,$E8,$05,$02,$40,$73,$ED,$E8,$26,$00
db $50,$08,$43,$4D,$2C,$0C,$1C,$15,$A5,$14,$10,$13,$3F,$27,$20,$0F
db $51,$1D,$29,$49,$49,$4A,$4A,$4A,$4A,$4C,$4C,$4C,$4C,$4F,$53,$53
db $54,$54,$54,$54,$5A,$5A,$5F,$AE,$75,$FD,$8A,$55,$12,$B4,$02,$CD
db $21,$C3
}

macro n { db 82 dup $20 }

macro s { db 10 }

n
e
s
n
e
s
e
e

```

Source:

```
BOF:    ;mov bx, 100h
p:      test [si], byte $DF
        js _a ; exist
        jnz _b ; newline
_z:     add al, al
        inc ax
q:      add si, EOF-BOF
        jmp p
_b:     mov dl, al
        add al, dl
        add al, dl
        inc si
        jmp p
_a:     add ax, 4002h
        jnc q
        call y
        db 80,8,67,77,44,12,28,21,165,20,16,19,63,39,32,15,81,29,41
        db 'IIJJJJLLLLOSSTTTTZZ'
y:      pop di
        scasb
        jnz y+1
        mov dl,[di+18]
        mov ah,2
        int $21
        ret
EOF:

```

Run in win7dos where init AX=0, SI=100, BX=0 References

---
Tags: code-golf, source-layout, tetris
---


title: Tips for golfing in Mini-Flak

text:
# Question
Title: Tips for golfing in Mini-Flak
What general tips do you have for golfing in Mini-Flak? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Mini-Flak (e.g. "remove comments" is not an answer).

Please post one tip per answer.

Mini-Flak is just Brain-flak without `[]`, `<...>` or `<>` so tips for Mini-Flak are different for a large amount of problems. However the use of brackets like `[...]` are allowed.

# Answer
> 4 votes
# Zero efficiently

The `<...>` from Brain-flak is missing so it is often required that you replace it with something else.

The two following snippets do just that:

* `(...)[{}]`
* `[(...)]{}`

However when you are zeroing it is important to select these properly, because there is a lot of golfing that can be done that can't be done with Brain-Flak's zeros. For example the following Brain-Flak code:

```
({}[()]<({}())>)

```

Could be reconstituted as

```
({}[()](({}()))[{}])

```

However it is cheaper to do

```
({}[()(({}()))]{})

```

You should try to combine your negative with as many other negatives in the scope as possible.

# Answer
> 3 votes
# Use "XOR swap"-style swaps to move values around

One of the biggest issues with Mini-Flak's command set is that, having only "two" stacks (the active stack, and the stack of temporary values implied by the structure of the program), you can't move two values past each other with simple copying; if you have value *a* above *b* on the primary stack, and want *b* above *a*, at some point you'll have to have a stack element that's storing parts of *b* and *a* simultaneously.

There's a well known trick in languages like C to swap two values without using a temporary:

```
a ^= b;  /* now a = a0^b0, b = b0 */
b ^= a;  /* now a = a0^b0, b = a0 */
a ^= b;  /* now a = b0,    b = a0 */

```

The trick is that you temporarily use `a` to store a combination of `a` and `b`, so that you can use the combined value to transform `b` into `a`, and then use the value of `a` you just obtained to recover `b` from the combined value.

Less well known is that you can do the same trick with addition and subtraction:

```
a -= b;  /* now a = a0-b0, b = b0 */
b += a;  /* now a = a0-b0, b = a0 */
a = b-a; /* now a = b0,    b = a0 */

```

This version of the trick uses only operations that we have available in Brain-Flak, so we can actually write it.

When I wrote it by hand, I eventually golfed it into the following program (which uses a different sequence of additions and subtractions from the example above):

```
(({}({}))[({}[{}])])

```

Try it online!

I've also been writing a computer search program to try to optimise Mini-Flak fragments, and tested it on this problem; it confirmed that 20 bytes is the shortest possible swap of the top two stack elements, but found a different way to write the solution, which is probably a bit easier to follow (in addition to matching the algorithm given more closely):

```
([({}[({})])]({}{}))

```

Try it online!

Here's how it documented its own version of the program (stacks are written with the active end at the right, and "Working" is the Mini-Flak equivalent of the third stack):

```
                      [$b, $a]      Working: $W
(                     [$b, $a]      Working: $W, 0
([                    [$b, $a]      Working: $W, 0, 0
([(                   [$b, $a]      Working: $W, 0, 0, 0
([({}                 [$b]          Working: $W, 0, 0, $a
([({}[                [$b]          Working: $W, 0, 0, $a, 0
([({}[(               [$b]          Working: $W, 0, 0, $a, 0, 0
([({}[({}             []            Working: $W, 0, 0, $a, 0, $b
([({}[({})            [$b]          Working: $W, 0, 0, $a, $b
([({}[({})]           [$b]          Working: $W, 0, 0, $a-$b
([({}[({})])          [$b, $a-$b]   Working: $W, 0, $a-$b
([({}[({})])]         [$b, $a-$b]   Working: $W, -$a+$b
([({}[({})])](        [$b, $a-$b]   Working: $W, -$a+$b, 0
([({}[({})])]({}      [$b]          Working: $W, -$a+$b, $a-$b
([({}[({})])]({}{}    []            Working: $W, -$a+$b, $a
([({}[({})])]({}{})   [$a]          Working: $W, $b
([({}[({})])]({}{}))  [$a, $b]      Working: $W+$b

```

We start by calculating the difference `$a-$b`, removing `$a` from the stack in the process but leaving `$b` there. Then we make two copies of the difference on our working stack, with opposite signs (`$a-$b` and `$b-$a`); we can add the `$a-$b` copy to `$b` to transform it into `$a`, and the result of the push `$a` ends up adding to the `$b-$a` copy to produce `$b`, which we can push to the stack on top of the new `$a`.

The same general idea can be used to do arbitrary stack operations (e.g. copying the fourth stack element into the second position); although the programs are fairly long by the standards of most programming languages, they're not really that long by Mini-Flak standards, and the only other way such a program could be written would be to handle each possible value for the intervening stack elements individually, which would be less general and much more verbose.

---
Tags: code-golf, tips, brain-flak
---


title: What key did I press?

text:
# Question
Title: What key did I press?
The task is to write code to identify which key is pressed on the keyboard. You can assume that only one key is pressed at a time and that there is a standard US keyboard layout. That is the layout with the @ over the 2.

Your code should output a unique identifier for any key pressed. This includes PrtScn, Scroll Lock, Pause, left Shift, right Shift, left Ctrl, right Ctrl, Caps Lock, Tab, Enter, Enter on the number pad, Num Lock, Insert, Ins on the number pad, Backspace, Del, F1...F12, Esc, left Windows key, right Windows key, Alt, AltGr, application key (context menu) and so on.

Your code should carry on waiting for key presses and outputting their identity until it is killed. It should output the identifier as soon as a key is released however. It shouldn't carry out any other action from the key presses it receives and it shouldn't output anything apart from the unique identifier.

In your answer, please show what you code outputs for the following key presses: Tab, Pause, Enter, Enter on the number pad, left Windows key, right Windows key, Insert and Ins on the number pad.

If you have a very different keyboard, the challenge is still to output a different identifier for every single key on your keyboard.

# Answer
> 22 votes
## x86 machine code, DOS executable, ~~29~~* 28 bytes

```
FAE464D0E873FAE460D0E073F4D41005212192B402CD2188F2CD21EBE3

```

This is a COM executable for MS-DOS, it requires a IBM PC compatible hardware.
Particularly an 8042 PS/2 controller or more likely an emulation of it through SMM.
Long story short, it should work out of the box in any mainstream PC.

The source code is

```
BITS 16

 ;Disable the interrupts so we don't compete with the IRQ 1 (the 8042 main
 ;device IRQ) handler (the ISR n. 9 by default) for the reading of the codes.
 cli

_wait:

 ;Is 'Output buffer full (OBF)' bit set?

 in al, 64h                ;Read the 8042 status register
 shr al, 1                 ;Move bit 0 (OBF) into the carry flag

jnc _wait                  ;Keep spinning if CF = OBF not set

 ;Read the scan code S
 in al, 60h

 ;Is S a break code?

 shl al, 1                 ;Bit 7 is set if it is
jnc _wait

 ;PART 2

 ;AL = S mod 10h := y, AH = S / 10h := x
 aam 16
 add ax, 2121h             ;Make both quantities in the printable ASCII range (skip space though)

 ;Print y
 xchg dx, ax
 mov ah, 02h
 int 21h                   ;int 21/ah=02 prints the char in DL

 ;DH is still valid here, it holds x. We print it now
 mov dl, dh
 int 21h

 ;Never terminate
jmp _wait

```

I've divided the program into two parts.

The first part deals with the reading of the scancodes. Scancodes are numeric values associated with every key.
Note that these are hardware code, they don't depend on the OS or the charset. They are like an encoded pair (column, row) of the key.
Every key has a scancode, even those non-standard weird function keys found on some keyboard (e.g. the "open calc" key).
Some key has multi-byte scancode, they have prefixes designed to make the stream decodificable by just looking at the sequence of bytes.
So each key gets its unique identifier, even CTRL, SHIFT, WinKeys and so on.

Only the "break codes", sent when a key is released, are processed, the "make codes" are ignored.
The formers have the higher bit (bit 7 for a byte) set, so it's easy to recognise them.

The second part deals with the printing of a byte.
Printing is always lengthy in assembly, we have no builtins.
To keep it short, and since it was required to write *an identifier* of the key, I abandoned decimal or hex numerals in favour of a personal encoding.

A byte xy, where x is the higher nibble and y the lower is printed as two successive chars c0 and c1 defined as:

c0 = 0x21 + y
c1 = 0x21 + x

Note that the lower nibble is printed *first* (this spared me a swap).
The rationale is to map the each one of the 16 possible values of a nibble into consecutive ASCII characters from '!'.
Simply put this is a hex numeral but with

1. The nibbles swapped
2. `!"#$%&'()*+,-./01` as digit(als) instead of `0123456789abcdef`

Running it in DOSBox and pressing some random key (some of which is a special key but note that as a Windows process DOSBox can't capture all the keys) yields

Note that this program never terminates (further, it takes complete control of the PC by disabling the interrupts) as I believe was intended by the question (simply there is no killing of processes in DOS).

---

* Reduced thank to CodyGray.

# Answer
> 12 votes
# Java 7 or Higher, ~~246~~ 228 bytes

```
import java.awt.event.*;class K{public static void main(String[]a){new java.awt.Frame(){{addKeyListener(new KeyAdapter(){public void keyPressed(KeyEvent e){System.out.println(e);}});show();setFocusTraversalKeysEnabled(0<0);}};}}

```

Ungolfed:

```
import java.awt.event.*;
class K{
    static void main(String[]a){
        new java.awt.Frame(){
            {
                addKeyListener(new KeyAdapter(){
                    public void keyPressed(KeyEvent e){
                        System.out.println(e);
                    }
                });
                show();
                setFocusTraversalKeysEnabled(0<0);
            }
        };
    }
}

```

*-18 thanks to @OlivierGrégoire for `show()`, `0<0` and `import java.awt.event.*;`*

Which results in:

Even handles shift-presses for capitalized characters, the windows key, cap locks, etc... You can see it printing the 'modifiers' as well, which are 'held keys'.

```
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=27,keyText=Escape,keyChar=Escape,keyLocation=KEY_LOCATION_STANDARD,rawCode=27,primaryLevelUnicode=27,scancode=1,extendedKeyCode=0x1b] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=192,keyText=Back Quote,keyChar='`',keyLocation=KEY_LOCATION_STANDARD,rawCode=192,primaryLevelUnicode=96,scancode=41,extendedKeyCode=0xc0] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=9,keyText=Tab,keyChar=Tab,keyLocation=KEY_LOCATION_STANDARD,rawCode=9,primaryLevelUnicode=9,scancode=15,extendedKeyCode=0x9] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=20,keyText=Caps Lock,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=20,primaryLevelUnicode=0,scancode=58,extendedKeyCode=0x14] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=16,keyText=Shift,keyChar=Undefined keyChar,modifiers=Shift,extModifiers=Shift,keyLocation=KEY_LOCATION_LEFT,rawCode=16,primaryLevelUnicode=0,scancode=42,extendedKeyCode=0x10] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=17,keyText=Ctrl,keyChar=Undefined keyChar,modifiers=Ctrl,extModifiers=Ctrl,keyLocation=KEY_LOCATION_LEFT,rawCode=17,primaryLevelUnicode=0,scancode=29,extendedKeyCode=0x11] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=524,keyText=Windows,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_LEFT,rawCode=91,primaryLevelUnicode=0,scancode=91,extendedKeyCode=0x20c] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=18,keyText=Alt,keyChar=Undefined keyChar,modifiers=Alt,extModifiers=Alt,keyLocation=KEY_LOCATION_LEFT,rawCode=18,primaryLevelUnicode=0,scancode=56,extendedKeyCode=0x12] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=32,keyText=Space,keyChar=' ',keyLocation=KEY_LOCATION_STANDARD,rawCode=32,primaryLevelUnicode=32,scancode=57,extendedKeyCode=0x20] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=18,keyText=Alt,keyChar=Undefined keyChar,modifiers=Alt,extModifiers=Alt,keyLocation=KEY_LOCATION_RIGHT,rawCode=18,primaryLevelUnicode=0,scancode=56,extendedKeyCode=0x12] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=17,keyText=Ctrl,keyChar=Undefined keyChar,modifiers=Ctrl,extModifiers=Ctrl,keyLocation=KEY_LOCATION_RIGHT,rawCode=17,primaryLevelUnicode=0,scancode=29,extendedKeyCode=0x11] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=37,keyText=Left,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=37,primaryLevelUnicode=0,scancode=75,extendedKeyCode=0x25] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=16,keyText=Shift,keyChar=Undefined keyChar,modifiers=Shift,extModifiers=Shift,keyLocation=KEY_LOCATION_RIGHT,rawCode=16,primaryLevelUnicode=0,scancode=42,extendedKeyCode=0x10] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=38,keyText=Up,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=38,primaryLevelUnicode=0,scancode=72,extendedKeyCode=0x26] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=39,keyText=Right,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=39,primaryLevelUnicode=0,scancode=77,extendedKeyCode=0x27] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=96,keyText=NumPad-0,keyChar='0',keyLocation=KEY_LOCATION_NUMPAD,rawCode=96,primaryLevelUnicode=48,scancode=82,extendedKeyCode=0x60] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=110,keyText=NumPad .,keyChar='.',keyLocation=KEY_LOCATION_NUMPAD,rawCode=110,primaryLevelUnicode=46,scancode=83,extendedKeyCode=0x6e] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=10,keyText=Enter,keyChar=Enter,keyLocation=KEY_LOCATION_NUMPAD,rawCode=13,primaryLevelUnicode=13,scancode=28,extendedKeyCode=0xa] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=107,keyText=NumPad +,keyChar='+',keyLocation=KEY_LOCATION_NUMPAD,rawCode=107,primaryLevelUnicode=43,scancode=78,extendedKeyCode=0x6b] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=109,keyText=NumPad -,keyChar='-',keyLocation=KEY_LOCATION_NUMPAD,rawCode=109,primaryLevelUnicode=45,scancode=74,extendedKeyCode=0x6d] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=106,keyText=NumPad *,keyChar='*',keyLocation=KEY_LOCATION_NUMPAD,rawCode=106,primaryLevelUnicode=42,scancode=55,extendedKeyCode=0x6a] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=34,keyText=Page Down,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=34,primaryLevelUnicode=0,scancode=81,extendedKeyCode=0x22] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=33,keyText=Page Up,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=33,primaryLevelUnicode=0,scancode=73,extendedKeyCode=0x21] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=35,keyText=End,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=35,primaryLevelUnicode=0,scancode=79,extendedKeyCode=0x23] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=36,keyText=Home,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=36,primaryLevelUnicode=0,scancode=71,extendedKeyCode=0x24] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=127,keyText=Delete,keyChar=Delete,keyLocation=KEY_LOCATION_STANDARD,rawCode=46,primaryLevelUnicode=0,scancode=83,extendedKeyCode=0x7f] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=155,keyText=Insert,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=45,primaryLevelUnicode=0,scancode=82,extendedKeyCode=0x9b] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=123,keyText=F12,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=123,primaryLevelUnicode=0,scancode=88,extendedKeyCode=0x7b] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=122,keyText=F11,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=122,primaryLevelUnicode=0,scancode=87,extendedKeyCode=0x7a] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=121,keyText=F10,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=121,primaryLevelUnicode=0,scancode=68,extendedKeyCode=0x79] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=120,keyText=F9,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=120,primaryLevelUnicode=0,scancode=67,extendedKeyCode=0x78] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=119,keyText=F8,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=119,primaryLevelUnicode=0,scancode=66,extendedKeyCode=0x77] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=118,keyText=F7,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=118,primaryLevelUnicode=0,scancode=65,extendedKeyCode=0x76] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=117,keyText=F6,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=117,primaryLevelUnicode=0,scancode=64,extendedKeyCode=0x75] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=116,keyText=F5,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=116,primaryLevelUnicode=0,scancode=63,extendedKeyCode=0x74] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=115,keyText=F4,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=115,primaryLevelUnicode=0,scancode=62,extendedKeyCode=0x73] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=114,keyText=F3,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=114,primaryLevelUnicode=0,scancode=61,extendedKeyCode=0x72] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=113,keyText=F2,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=113,primaryLevelUnicode=0,scancode=60,extendedKeyCode=0x71] on frame0
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=112,keyText=F1,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=112,primaryLevelUnicode=0,scancode=59,extendedKeyCode=0x70] on frame0

```

# Answer
> 11 votes
# HTML (with Javascript), ~~46~~ 31 chars, ~~46~~ 31 bytes

~~Using this to differentiate numpad enter and return, LControl and RControl...~~ Not anymore since apsillers found a way to do it with a signle function call.

```
<body onkeyup=alert(event.code)

```

Specific outputs:

OUTPUTS THAT ARE STILL WITH THE NUMBERS ARE THOSE I CAN'T TEST ON MY LAPTOP
PLEASE WAIT FOR ME TO HAVE ACCESS TO THOSE KEYS

PrtScn -\> PrintScreen
Scroll Lock -\> ScrollLock
Pause -\> Pause
left Shift -\> ShiftLeft
right Shift -\> ShiftRight
left Ctrl -\> ContrlLeft
right Ctrl -\> ControlRight
Caps Lock -\> CapsLock
Tab -\> Tab
Enter -\> Enter
Enter on the number pad -\> NumpadEnter
Num Lock -\> NumLock
Insert -\> Insert
Ins on the number pad -\> Numpad0
Backspace -\> Backspace
Del -\> Delete
F1...F12 -\> F1 to F12
Esc -\> Escape
left Windows key -\> MetaLeft
right Windows key -\> MetaRight
Alt -\> AltLeft
AltGr -\> AltRight (kind of buggy, it detects ControlLeft and then AltRight, but it is indeed AltRight)
application key (context menu) -\> ContextMenu

EDITs :
1 byte saved on `;` after func call
18 bytes saved thanks to Lil' Bits and ETHproductions, they noticed I forgot to shorten func and var names.
32 bytes saved thanks to RogerSpielker, he noticed I was doing sparated code for no reason; and again -2 bytes : `onkeydown` -\> `onkeyup`
1 byte saved : no need for final slash
2 bytes saved thanks to CraigAyre : `with()` function
2 bytes saved thanks to ASCII-only : `key` in place of `which`
4 bytes saved, since we have text, there is no need for `'-'+` (every identifier is unique without this) 1 byte saved thanks to ASCII-only (again) : no more closing symbol `>` 15 bytes saved thanks to apsillers, as said at the top of my answer.

```
<body onkeyup=alert(event.code)
```

# Answer
> 8 votes
# Tcl/Tk, 22 characters

```
bind . <Key> {puts %K}

```

Sample run:

Notes:

* No right Windows key on my keyboard ☹ (~~clever~~ designer put the backlight switch in its place)
* The numeric pad's Insert generates different code based on NumLock's status
* The volume knob generates X.org specific codes, all other are just regular keysyms

# Answer
> 6 votes
# Bash with X.org, 21 bytes

```
xev|awk 'NR%2&&/\(k/'

```

Unfortunately, I can't test it since I'm on MacBook on Linux - no PrntScr, no numeric keyboard &all.

`xev` is a tool that outputs mouse and keyboard events under `X.org`. I pipe it to awk, filter even lines (since every key is shown when key is pressed, and then when it's released), and select only those that contain `(k` \- this string is in every line that describes pressed key.

# Answer
> 5 votes
# C and Win32, 240 224 216 205 202 194 191 bytes

```
#include<d3d.h>
#include<stdio.h>
w[9];p(x,y,a,b){printf("%X",a^b);}main(){w[1]=p;w[9]=p;CreateWindow(RegisterClass(w),0,1<<28,0,0,0,0,0,0,0,0);for(;GetMessage(w,0,16,0);)DispatchMessage(w);}

```

## Outputs

`TAB`: `F0008C00F0008`

`PAUSE`: `450012C0450012`

`ENTER`: `1C000CC01C000C`

`NUMPAD-ENTER`: `11C000CC11C000C`

`WINDOWS-LEFT`: `15B005AC15B005A`

`WINDOWS-RIGHT`: `15C005DC15C005D`

`INSERT`: `152002CC152002C`

`NUMPAD-INSERT`: `52002CC052002C`

## Explanation

```
#include <d3d.h> // shortest built-in header that includes windows.h
#include <stdio.h> // for printf

w[9]; // space for wndclass-data array

// function castable to the signature of WNDPROC
p(x,y,a,b)
{
    // key and state are encoded in the last two 4-byte arguments to wndproc
    printf("%X",a^b);
}

main(m)
{
    // set minimal window class equivalent data pointing to wndproc above
    w[1]=p;w[9]=p;

    // create the window using the class, with WS_VISIBLE flag
    CreateWindow(RegisterClass(w),0,1<<28,0,0,0,0,0,0,0,0)
    for(;GetMessage(w,0,16,0);) // filter messages 15 and lower, which fire without input
        DispatchMessage(w);
}

```

## Edits

-16 thanks to @ugoren

-8: changed `WNDCLASS` to `int` array since all 10 members are 4 bytes

-11: partial initialization of wndclass-data array, reduced to 9 elements

-3: use implicit `int` decl for wndclass-data array

-8: remove newline from output format (not required in spec and printf flushes immediately without it); move `RegisterClass` into `CreateWindow` arg, using returned `ATOM`; set wndclass name to `m` which just needs a zero-byte in it to be a valid string.

-3: reuse `w` var for `MSG` data

# Answer
> 3 votes
# Java (OpenJDK 8), 369 bytes

```
import java.awt.event.*;import javax.swing.*;class F{public static void main(String[] a){JFrame f=new JFrame();f.addKeyListener(new KeyListener(){public void keyPressed(KeyEvent e){System.out.print(e.getKeyCode()*8+e.getKeyLocation());}public void keyTyped(KeyEvent e){}public void keyReleased(KeyEvent e){}});f.setVisible(true);f.setFocusTraversalKeysEnabled(false);}}

```

This cannot be run with TIO because it uses a graphical interface, but it works on my computer.

```
Pause: 153
Enter: 81
Enter on NumPad: 84
Left Super key: 193 (After disabling the Menu shortcut for my desktop)
Right Super key: 201
Insert: 241
Insert on Numpad: 522948 (I don't have one, but that's what you get when you press 5 with Num lock off. When Num lock is on, you get 812.)

```

# Ungolfed / Explanation:

```
import java.awt.event.*; // KeyListener, KeyEvent
import javax.swing.*; // JFrame

class F implements KeyListener {

    public static void main(String[] a) {
        JFrame f=new JFrame(); // creates a new GUI frame
        f.addKeyListener(new KeyListener() {  // puts a KeyListener in the frame with the following properties:

            // Method that runs whenever a key is pressed
            public void keyPressed(KeyEvent e) {
                // getKeyCode returns an integer that uniquely identifies the key,
                // but not the location (e.g. LShift and RShift have the same key code)
                // To fix this, I scale up the key code by 8 and add the location,
                // which is always 0-4 (Standard, Left, Right, NumPad, or Unknown)
                // I could have scaled by 5 instead but I wasn't really thinking
                System.out.print(e.getKeyCode() * 8 + e.getKeyLocation());
                // If you want nicer-looking output, just change "print" to "println"
            }

            // Method that runs whenever a printable character is typed (does nothing)
            public void keyTyped(KeyEvent e){}

            // Method that runs whenever a keyboard key is released (does nothing)
            public void keyReleased(KeyEvent e){}
        });

        f.setVisible(true); // the frame will only except key presses if it is visible
        f.setFocusTraversalKeysEnabled(false); // disables "focus traversal" keys (such as Tab) from actually traversing focus
    }
}

```

# Answer
> 3 votes
# Scala 2.10+, 279 chars, 279 bytes

Now this is a scala response :) even though it feels like I'm doing Java. Anyway we can't test it on TIO.

```
import scala.swing._
import java.awt.event._
object M extends SimpleSwingApplication{def top=new MainFrame{this.peer.addKeyListener(new KeyListener(){def keyPressed(e:KeyEvent){print(e.getKeyCode+"-"+e.getKeyLocation)}
def keyReleased(e:KeyEvent){}
def keyTyped(e:KeyEvent){}})}}

```

It's sad we need to declare all inherited methods even if we don't use them :l can I remove them from byte count, since some compiler flags can permit not declaring them?

This prints (as for my html-js response) the keyPressed, "-" and then its "location".

For instance :

PrtScn -\> not verifyable
Scroll Lock -\> 145-1
Pause -\> 19-1
left Shift -\> 16-2
right Shift -\> 16-3
left Ctrl -\> 17-2
right Ctrl -\> 17-3
Caps Lock -\> 20-1
Tab -\> not verifyable
Enter -\> 10-1
Enter on the number pad -\> 10-4
Num Lock -\> 144-4
Insert -\> 96-1
Ins on the number pad -\> 96-4
Backspace -\> 8-1
Del -\> 127-1
F1...F12 -\> 112-1 to 123-1
Esc -\> 27-1
left Windows key -\> 524-2
right Windows key -\> 524-3
Alt -\> 18-2
AltGr -\> 18-3 (kind of buggy, it detects 17-2 and then 18-3, but it is indeed 18-3)
application key (context menu) -\> 525-1

Though I think it depends on the computer :/ I'm on an azerty laptop right now.

# Answer
> 3 votes
# TI-BASIC, 19 bytes

> **PROGRAM:S**

```
If Ans
Disp Ans
getKey
prgmS

```
* Enter: 105,
* Left key: 24,
* Right key: 26,
* Ins\[ert\] is a little different because it would normally take two key presses to get to, but those would be 21 followed by 23.

**Here's an illustration of the rest of the keys:**

**Explanation:**

> **PROGRAM:S** The editor displays the name at the top apart from the code; the name is "S"

```
If Ans    // If the last input isn't zero
Disp Ans  // Display the last input
getKey    // Input a key press
prgmS     // Call the same program in a recursive fashion

```

This, unfortunately, isn't possible to do in Arnold C, so I had to stick to TI-BASIC.

# Answer
> 2 votes
# PowerShell, 34 bytes

```
$Host.UI.RawUI.ReadKey().Character

```

Outputs on the same line as the input, which can be a tad confusing.

# Answer
> 1 votes
# C#, 144 + 601 = 745 bytes

Consists of two classes, I couldn't manage to successfully combine them into one class.

Main class:

```
namespace System.Windows.Forms{class P:Form{static void Main(){Application.Run(new P());}P(){new Reflection.M().U+=k=>Console.Write(k.f+k.v);}}}

```

Hook class:

```
namespace System.Reflection{using Runtime.InteropServices;public class M{public delegate void d(s s);event d u;public event d U{add{if(h<1){j=m;h=SetWindowsHookEx(13,j,Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]),0);}u+=value;}remove{u-=value;}}public struct s{public int v;public int c;public int f;}[DllImport("user32.dll")]static extern int SetWindowsHookEx(int idHook,p lpfn,IntPtr hMod,int dwThreadId);delegate int p(int c,int w,IntPtr l);p j;int h;int m(int c,int w,IntPtr l){if(c>=0&u!=null&(w==257|w==261))u.Invoke((s)Marshal.PtrToStructure(l,typeof(s)));return -1;}}}

```

Outputs:

* Tab: `137`
* Pause: `147`
* Enter: `141`
* NumPad Enter: `142`
* Left Windows: `220`
* Right Windows: `221`
* Insert: `174`
* NumPad Insert: `224`

# Answer
> 1 votes
# AutoHotkey, 26 Bytes

```
loop{
input,x,L1M
send %x%
}

```

Can't test (win-only), but the `M` option says

> M: Modified keystrokes such as Control-A through Control-Z are recognized and transcribed if they correspond to real ASCII characters.

So it should do fine.

# Answer
> 1 votes
# C (gcc) + Win32, 94 ~~95~~ ~~98~~ ~~105~~ ~~107~~ ~~110~~ bytes

```
#import"d3d.h"
j;f(){for(;;)for(j=191;j--;)GetAsyncKeyState(j)&(j<16||j>18)?printf("%d",j):0;}

```

The code captures keys even after focus is lost.

The following screenshots are recorded adding spaces between outputs (`printf("%d ",j);` +1 byte) for better readibility:

`Left-ctrl` `Left-win` `Left-alt` `Space` `Right-alt` `Right-win` `Right-menu` `Right-ctrl` `Left-shift` `Z` `X` `C` `Right-shift` `Left-shift` `1` `2` `3` `Num 1` `Num 2` `Num 3` `Left-shift` `+/= (on the main part)` `Num +` `Left-alt` `PrtScn`

The code uses `GetAsyncKeyState` to query key state without checking message queue, usually more real-time than other user-mode approaches (except DirectInput). This approach is widely used in keyloggers.

`(j<16||j>18)` filters regular Ctrl/Alt/Shift. 16/17/18 is triggered whenever left or right one is pressed, along with location-specified vkey value.

# Answer
> 1 votes
# WinApi C (gcc), 156 bytes

```
#include <d3d.h>
#define b GetStdHandle(-10)
BYTE i[20];main(){SetConsoleMode(b,0);a:ReadConsoleInput(b,i,1,i+5);*i^1||*(i+4)||printf("%X\n",i[10]);goto a;}

```

This program prints out the Windows Virtual-Key Code assciocated with each keyboard key of input. The `\n` in the `printf` format-string is optional (but makes output human-friendly) and can be dropped for a total score of **154 bytes**. An easy way to kill the program (without taskmgr) is with `CTRL + PAUSE`. If you have a keyboard with a Fn key, this program cannot pick it up since it isn't even noticed by Windows.

* Credit to MooseBoys's answer for the `#include <d3d.h>` trick and inspiration for the `BYTE` array.

The program with local variables, readability, and without compiler warnings looks like this:

```
#include <windows.h>
#include <stdio.h>

int main(void)
{
    HANDLE conIn = GetStdHandle(STD_INPUT_HANDLE);
    INPUT_RECORD ir;
    DWORD useless;

    SetConsoleMode(conIn, 0);

    for(;;)
    {
        ReadConsoleInput(conIn, &ir, 1, &useless);

        if(ir.EventType == KEY_EVENT && !ir.Event.KeyEvent.bKeyDown)
            printf("%X\n", ir.Event.KeyEvent.wVirtualKeyCode);
    }

    return 0;
}

```

---
Tags: code-golf
---