title: Hopping numbers

text:
# Question
Title: Hopping numbers
# TASK

print integers n, where `12 <= n <= 123456789`, and all pairs of consecutive digits in n have the same positive difference between them (e.g. 2468 but not 2469).

# NO INPUT.

# Output:

```
12
13
14
15
16
17
18
19
23
24
25
26
27
28
29
34
35
36
37
38
39
45
46
47
48
49
56
57
58
59
67
68
69
78
79
89
123
135
147
159
234
246
258
345
357
369
456
468
567
579
678
789
1234
1357
2345
2468
3456
3579
4567
5678
6789
12345
13579
23456
34567
45678
56789
123456
234567
345678
456789
1234567
2345678
3456789
12345678
23456789
123456789

```

# Rules

1. Standard loopholes apply.
2. no input

*shortest code wins.*

***Credits*** anarchy golf

# Answer
> 11 votes
# Jelly, ~~12~~ 11 bytes

```
9œcḊẎIE$ÐfY

```

Try it online!

### How it works

```
9œcḊẎIE$ÐfY  Main link. No arguments.

9            Set the argument and return value to 9.
   Ḋ         Dequeue; yield [2, ..., 9].
 œc          Take all k-combinations of [1, ..., 9], for each k in [2, ..., 9].
    Ẏ        Concatenate the arrays of k-combinations.
        Ðf   Filter the result by the link to the left.
     IE$         Compute the increments (I) of the combination / digit list and
                 tests if all are equal (E).
          Y  Join the results, separating by linefeeds.

```

# Answer
> 7 votes
# Python 2, 81 bytes

```
k=71
exec"k+=1;r=range(k/8%9+1,10,k%8+1)\nif r[k/72:]:print`r`[1:k/24+2:3]\n"*576

```

Try it online!

My solution from anarchy golf. The idea is to iterate over all possible triples of length, start value, and step, which gives sorted outputs. The triple is encoded as a value `r` from `72` to `647`, and the components are extracted as `k/72`, `k/8%9`, and `k%8`. Starting `k` high enough avoids single-digit numbers from being output.

xsot saved two bytes off this by replacing the `range` with a hardcoded string of digits `'123456789'`.

This was written under the constraint of a two second runtime limit. A slower strategy that filters numbers rather than generating these may be shorter.

# Answer
> 6 votes
# C, ~~166~~ 152 Bytes

```
p,l,d,i=11;main(){for(char s[10];i<=1e9;){sprintf(s,"%d",++i);p=0;for(l=strlen(s);--l>0;){d=s[l]-s[l-1];if(!p)p=d;if(p^d|d<1)break;p=d;}if(!l)puts(s);}}

```

6 bytes saved thanks to @KevinCruijssen!

8 bytes saved thanks to @JonathanFrech!

Try it online

The fully formatted version of the above code can be seen below.

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

int main( void )
{
int prev_diff, diff, len;
int num = 11;
char str[10];

while(num<123456789)
    {
    prev_diff = 0;
    sprintf(str,"%d",++num);
    len = strlen(str)-1;
    for( ; len > 0; len-- )
        {
        diff = str[len] - str[len-1];
        if( prev_diff == 0 )
            {
            prev_diff = diff;
            }
        if( prev_diff != diff || diff < 1 )
            {
            break;
            }
        prev_diff = diff;
        }
    if ( len == 0 )
        {
        puts(str);
        }
    }
}

```

# Answer
> 5 votes
# Jelly, ~~14~~, 13 bytes

```
DIµEȧ>0Ȧ
Ç77#

```

Try it online!

One byte saved thanks to @MrXcoder!

This is extremely inefficient, so it'll time out on TIO, but if it ever finishes, it will produce the correct output. You can try it with smaller numbers here: Try it online!

Explanation:

```
            # Helper link:
            #
D           # The Digits of 'n'
 I          # The increments (deltas, differences) between digits
  µ         # Give that array as an argument to the rest of this link:
   E        # Are all elements equal?
    ȧ       #   AND
     >0     # Are all elements greater then 0?
       Ȧ    # And is there at least one element?
            # (in the differences, so that numbers < 10 are false)
            #
            # Main link:
            #
 77#        # Return the first 77 'n's for which
Ç           #   The helper link is truthy

```

# Answer
> 4 votes
# Mathematica, 79 bytes

```
Select[Range@123456789,Min[s=Union@Differences@IntegerDigits@#]>0&&Tr[1^s]==1&]

```

Try it online! with a lower number because it is very slow

here is another approach that constructs all the numbers in 1sec

# Mathematica, 123 bytes

```
Union[FromDigits/@(F=Flatten)[Table[Partition[#,i,1],{i,2,9}]&/@Select[F[Table[Range[j,9,k],{j,9},{k,9}],1],Tr[1^#]>1&],2]]

```

Try it online! all numbers in a sec

# Answer
> 4 votes
# 05AB1E, 23 bytes

```
•7=›ζ•FNS¥DËs0›PN11›&&–

```

Try it online!

---

Replace `•7=›ζ•` with 7000 to have it finish on TIO, or just hit the "terminate" button before it times out, resulting in the numbers printed up until that point.

# Answer
> 4 votes
# Husk, ~~14~~ 13 bytes

```
ÖifȯεuẊ≠Ṗ…"19

```

Prints newline-separated numbers to STDOUT. Try it online!

-1 byte due to inspiration from H.PWiz.

## Explanation

```
ÖifȯεuẊ≠Ṗ…"19
         …"19  The string "19" rangified: "123456789"
        Ṗ      Powerset: ["","1","2","12","3",...,"123456789"]
  fȯ           Filter by function: (input is sublist, say "2469")
      Ẋ≠        Consecutive codepoint differences: [2,2,3]
     u          Remove duplicates: [2,3]
    ε           Is it a one-element list? No, so "2469" is dropped.
Öi             Sort the result by integer value, implicitly print separated by newlines.

```

# Answer
> 4 votes
# Wolfram Language (Mathematica), 76 bytes

```
Differences@IntegerDigits@#~MatchQ~{a_?Positive..}&&Print@#&~Array~123456789

```

Try it online!

# Answer
> 3 votes
# APL (Dyalog), ~~37~~ 28 bytes

```
⍪x/⍨{1=≢∪2-/⍎¨⍕⍵}¨x←11+⍳1E9

```

Try it online! (with shorter range, due to time-out)

**How?**

`x←11+⍳123456789` \- `11, 12... 1e9` into `x`

`¨` \- for each

`⍎¨⍕⍵` \- break into digits

`2-/` \- get differences list

\- get unique elements

`1=≢` \- length == 1?

`x/⍨` \- use this as a mask on the range created

\- and columnify

# Answer
> 3 votes
# Husk, 14 bytes

```
ÖifoEẊ≠ftṖ…"19

```

Try it online!

# Answer
> 3 votes
# Java 8, ~~169~~ ~~168~~ 145 bytes

```
v->{byte[]a;for(int i=9,d,l;++i<1e9;System.out.print(l<1?i+"\n":""))for(a=(i+"").getBytes(),d=0,l=a.length;--l>0&&d*(d^(d=a[l]-a[l-1]))<1&d>0;);}

```

Port of *@Jacobinski* C answer (after I golfed it a bit).
-23 bytes thanks to *@Nevay*.

**Explanation:**

Try it here. (It's a bit too slow near the end, so doesn't print the final number on TIO. It prints the final number locally in about 20 seconds, though.)

```
v->{                         // Method with empty unused parameter and no return-type
  byte[]a;                   //  Byte-array
  for(int i=9,               //  Index integer, starting at 9
          d,                 //  Difference-integer
          l;                 //  Length integer
      ++i<1e9;               //  Loop (1) from 10 to 1,000,000,000 (exclusive)
      System.out.print(      //    After every iteration: print:
        l<1?                 //     If `l` is 0:
         i+"\n"              //      The current integer + a new-line
        :                    //     Else:
         ""))                //      Nothing
    for(a=(i+"").getBytes(), //   Convert the current item as String to a byte-array
        d=0,                 //   Reset the previous integer to 0
        l=a.length;          //   Set `l` to the length of the byte-array
        --l>0                //   Inner loop (2) from `l-1` down to 0 (exclusive)
        &&d*(d^(d=a[l]-a[l-1]))<1
                             //    As long as the previous difference is either 0
                             //    or the current diff is not equal to the previous diff
        &d>0;                //    and the current diff is larger than 0
    );                       //   End of inner loop (2)
                             //  End of loop (1) (implicit / single-line body)
}                            // End of method

```

# Answer
> 3 votes
# Batch, ~~210~~ 200 bytes

No optimizations, so very slow - takes about 25 seconds until 12345, so for the complete output you'd have to wait about 3 days.

```
@set z=@set/a
%z%c=12
:a
@echo %c%
:c
%z%c+=1&if %c%==123456790 exit/b
%z%n=c
%z%d=n%%10-n/10%%10
@if %d% leq 0 goto c
:d
%z%n=n/10
@if %n% leq 9 goto a
%z%e=n%%10-n/10%%10
@if %e%==%d% goto d
@goto c

```

# Answer
> 2 votes
# Python 2, ~~103~~ ~~97~~ 95 bytes

*-2 bytes thanks to @JonathanFrech*

```
n=11
while n<1e9:
 n+=1;Q=`n`[1:]
 if`n`<Q>1==len({int(a)-int(b)for a,b in zip(`n`,Q)}):print n

```

Try it online!

# Answer
> 2 votes
# 05AB1E, 14 bytes

```
TžhŸʒS¥D0›PsË&

```

Try it online!

# Answer
> 2 votes
## JavaScript (Firefox 30-57), 105 bytes

```
document.write(`<pre>`+(

_=>[for(x of s=`123456789`)for(y of s)for(z of s)if(x*z<10-y)s.replace(/./g,c=>c<y|(c-y)%z|c-y>x*z?``:c)]

)().join`\n`+`</pre>`);
```

Loops over lengths from 2 to 10 (x is the index of the last character and therefore 1 less than the length), starting digits from 1 to 9 and step from 1 to 9, then filters on the end digit being less than 10 and if so generates the result by filtering out digits from the digit string.

# Answer
> 2 votes
# Python 2, ~~76~~ 75 bytes

```
n=9
while n<2e8:
 n+=1
 if`n`in`range(n%10,0,~n%100%11-11)`[-2::-3]:print n

```

Takes about 3 minutes locally.

Try it online! (modified to print all numbers but the last)

# Answer
> 1 votes
# MATL, ~~17~~ 16 bytes

```
1e9:"@Vdu0>TX=?@

```

**Try it online!** with `1e9` replaced by `1e3` so that it doesn't time out in the online compiler.

# Answer
> 1 votes
# Pyth, 21 bytes

Port of Dennis' clever approach.

```
jjLkf!t{.+Tsm.cS9dtS9

```

Try it here!

# Pyth, 23 bytes

```
j.f&!tl{K.+jZT*F>R0K77T

```

This times out on the online interpreter, but works if given enough time and memory.

Try it online with a lower number.

# Answer
> 1 votes
# C (gcc), 106 bytes

```
main(i,j,k,l){for(i=1;i<9;i++)for(j=8;j;j--)for(k=0;k<j/i;puts(""))for(l=0*k++;l<=i;)putchar(57-j+k*l++);}

```

Try it online!

The ungolfed (prettified) version:

```
int main() {
  int length, start_with, max_step, step, nth;
  for (length = 2; length <= 9; length++) {
    for (start_with = 1; start_with < 9; start_with++) {
      max_step = (9 - start_with) / (length - 1);
      for (step = 1; step <= max_step; step++) {
        for (nth = 0; nth < length; nth++) {
          putchar('0' + start_with + step * nth);
        }
        puts("");
      }
    }
  }
  return 0;
}

```

# Answer
> 1 votes
# JavaScript (ES6), 121 bytes

Not nearly as short as Neil's answer, but I thought it was still worth posting.

Works by building a powerset of `'123456789'` where all non-matching entries are truncated and prefixed with `0`, sorting the results in numerical order and keeping only the 77 relevant ones.

```
_=>[...'123456789'].reduce((a,x)=>[...a,...a.map(y=>y[1]-y[0]+(y.slice(-1)-x)?'0':y+x)],['']).sort((a,b)=>a-b).slice(-77)

```

### Demo

```
let f =

_=>[...'123456789'].reduce((a,x)=>[...a,...a.map(y=>y[1]-y[0]+(y.slice(-1)-x)?'0':y+x)],['']).sort((a,b)=>a-b).slice(-77)

console.log(f().join` `)
```

# Answer
> 1 votes
# JavaScript (ES6), ~~109~~ 104 bytes

Works by generating all possible numbers: loops through each increment from 8 to 1 (variable `i`), loops through each starting digit from 8 to 1 (variable `j`), loops through each digit between `j` and `10-i` (variable `k`) and generates a string `t` by appending `k` to the current `t`. At each step `t` is added to the output array.

```
(o=[],i=9)=>{while(--i){j=9;while(k=--j){t=""+k;while(k<10-i)o.push(t+=k+=i)}}return o.sort((a,b)=>a-b)}

```

Try it online!

```
f=

(o=[],i=9)=>{while(--i){j=9;while(k=--j){t=""+k;while(k<10-i)o.push(t+=k+=i)}}return o.sort((a,b)=>a-b)}

;
console.log(f().join("\n"))
```

# Answer
> 1 votes
# Wolfram Language (Mathematica), 71 bytes

```
Flatten@Array[If[(x=#2+#3 #)<10,FromDigits@Range[#2,x,#3],{}]&,{8,8,8}]

```

Try it online!

Lightning fast due to constructing rather than selecting the output.

# Answer
> 0 votes
# PHP, ~~85~~ 84 bytes

```
for(;++$d<9||++$a<9*$d=1;sort($r))for($x=$y=$a+1;10>$y+=$d;)$r[]=$x.=$y;print_r($r);

```

try it online.

sorting cost 17 bytes. This version prints the results ordered differently:

```
while(++$d<9||++$a<9*$d=1)for($x=$y=$a+1;10>$y+=$d;)echo"
",$x.=$y;

```

# Answer
> 0 votes
## JavaScript (ES6), 145 bytes

A straight-forward approach with little magic.

```
Array(123456790).fill().map((x,i)=>(''+i).split('')).map((a,i,d) => {d=a[1]-a[0];d>0&a.every((n,j)=>j<1||n-a[j-1]==d)?console.log(a.join('')):0})
```

Running the snippet will consume a lot of memory...

# Answer
> 0 votes
# Java (OpenJDK 8), ~~228~~ ~~174~~ ~~170~~ 163 bytes

```
o->{int i=11,x,y,z,l;for(;i++<1e9;){char[]w=(""+i).toCharArray();for(x=w[1]-w[0],y=1,z=0;y<w.length;z+=l>0&l==x?0:1)l=w[y]-w[y++-1];if(z<1)System.out.println(i);}}

```

Try it online!

---
Tags: code-golf, number, sequence, kolmogorov-complexity
---


title: Coding Around The Clock

text:
# Question
Title: Coding Around The Clock
Write a single line program two or more characters long that contains no line terminators and takes no input. For example, your program might be:

```
MyProgram

```

When your program is arranged into the shapes a clock's hands make at 12, 3, 6, and 9 o'clock, it needs to output the corresponding hour number. No other times need be supported.

Specifically:

* When your program is arranged like clock hands at 12 o'clock ()

```
m
a
r
g
o
r
P
y
M

```

running it should output `12`.
* When your program is arranged like clock hands at 3 o'clock ()

```
m
a
r
g
o
r
P
y
MyProgram

```

running it should output `3`.
* When your program is arranged like clock hands at 6 o'clock ()

```
m
a
r
g
o
r
P
y
M
y
P
r
o
g
r
a
m

```

running it should output `6`.
* When your program is arranged like clock hands at 9 o'clock ()

```
........m
........a
........r
........g
........o
........r
........P
........y
margorPyM

```

running it should output `9`.

# Notes

* The first character in your program is always placed at the center of the clock. (Note how there is only one `M` in the 6 o'clock example.)
* Any one non-newline character may be used to indent the program for the 9 o'clock arrangement. In the examples `.` is used, but space or `/` or `#` would be just as valid.
* For the 3 o'clock arrangement, no characters should be in the empty upper right region. (i.e. keep it empty, don't fill it with spaces.)
* The initial program arrangement (`MyProgram` as is) does not need to do anything. Only the 12, 3, 6, and 9 o'clock arrangements need to have correct, well-defined output.
* Code that only works as a function or REPL command is not allowed. Each of the four arrangements should be ready to run as full programs as is.

**The shortest program in bytes wins.** e.g. `MyProgram` has a length of 9 bytes.

# Answer
> 38 votes
# GolfScript, ~~11~~ 10 bytes

```
21;;3#9];6

```

Uses `#` as padding character.

## 12 o'clock

```
6
;
]
9
#
3
;
;
1
2

```

Try it online!

### How it works.

* `6` is pushed on the stack, `;` discards it.
* `]` wraps the stack in an array (does not affect output).
* `9` and `3` are pushed on the stack, `;` and `;` discard them.
* Finally, `1` and `2` are pushed on the stack, and implicitly printed without separation.

## 3 o'clock

```
6
;
]
9
#
3
;
;
1
21;;3#9];6

```

Try it online!

### How it works

* `6` is pushed on the stack, `;` discards it.
* `]` wraps the stack in an array (does not affect output).
* `9` and `3` are pushed on the stack, `;` and `;` discard them.
* `1` and `21` are pushed on the stack, `;;` discards them.
* `3` is pushed on the stack.
* `#` begins a comment until the end of the line.

## 6 o'clock

```
6
;
]
9
#
3
;
;
1
2
1
;
;
3
#
9
]
;
6

```

Try it online!

### How it works

* `6` is pushed on the stack, `;` discards it.
* `]` wraps the stack in an array (does not affect output).
* `9` and `3` are pushed on the stack, `;` and `;` discard them.
* `1`, `2` and `1` are pushed on the stack.
* `;` and `;` discard the last `1` and `2`.
* `3` and `9` are pushed on the stack.
* `]` and `;` wrap the stack in an array and discard it, clearing the stack.
* `6` is pushed on the stack.

## 9 o'clock

```
#########6
#########;
#########]
#########9
##########
#########3
#########;
#########;
#########1
6;]9#3;;12

```

Try it online!

### How it works

* All lines but the last are comments.
* `6` is pushed on the stack, `;` discards it.
* `]` wraps the stack in an array (does not affect output).
* `9` is pushed on the stack.
* `#` begins a comment until the end of the line.

# Answer
> 25 votes
## \>\<\>, 20 bytes

```
X   n-+g+aa0g+9a2c!v

```

There's unprintables in there, namely:

* After the `X` is `\x06\t`
* After the `c` is `\x03`

The same part of source code is run each time, using `g` on two parts of the source code to determine what to subtract from 12.

```
v                         Make IP move downwards
 !\x03                    Jump over the \x03
      c                   Push 12
       2a9+g              Get the char at position (2, 19), i.e. the \t for
                          3 o'clock, the \x03 for 9 o'clock, 0 otherwise
            0aa+g         Get the char at position (0, 20), i.e. first char on
                          the line after the X, \x06 for 6 o'clock
                 +        Add
                  -       Subtract from the 12
                   n      Output as number
                    \t    Unrecognised instruction - errors out

```

12 o'clock | 3 o'clock | 6 o'clock | 9 o'clock (looks misaligned due to the tab)

# Answer
> 1 votes
## ROOP, 54 bytes

```
OW    3#H V  1#1  H#6  WO#H V>V1#OW V>V9#OW   2#OW   1

```

Uses `<` as padding character.

12 o'clock | 3 o'clock | 6 o'clock | 9 o'clock

## 12 o'clock

The `1` and the `2` that are near the top fall for 3 cycles. When they reach the `W` operator, the operator places the number in `O`, which represents the output.

The `1` in this part

```
1

V

H

```

fell for 2 cycles, the `V` operator moves it below and at the next cycle activates the `H` operator that ends the program.

## 3 o'clock

`O` are also objects that move and fall. Since the code now has a line with more than one character, all other lines are filled with empty spaces. All `O` moves to the right and fall, causing the `W` operators to have no place to send the `1` and `2`.

The only `O` that does not move is the one that is trapped in the center. The `3` above falls for 4 cycles to the `W`.

Then the numbers that fall are filling the 4 spaces between the `W` and`3`. When it is filled, another number can pass over all of them and reach the `H` operator that ends the program.

## 6 o'clock

```
1

H
#
6

W
O

```

Very similar to the 12, the `6` falls to the `W` and the `1` to the `H`. This occurs in 2 cycles, ending the program before the 12 case occurs.

## 9 o'clock

```
<9
<V
<>
<V
<
<W
<O
<#
<1
<V
<>
<V
<
<H

```

(I show a single column of `<` because the others do nothing).

The `V` picks up the `9` and moves it to the pipe below, which deflects the object to the left. The pipe `<` moves the object down and the next one to the right. The `V` operator put the `9` in the space below and then it is sent to the output.

The `1` makes equal movements and reaches the `H`, which ends the program. As the pipes move objects in the same cycle, all this takes a single cycle.

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


title: The Most Useless Program EVER!

text:
# Question
Title: The Most Useless Program EVER!
Inspired by The Most Useless Machine Ever.

Write the shortest program that does the following:

* create a graphical window, then immediately close the window and exit the program.
* do this in some visually apparent manner. Like the "arm" that pushes the switch in the machine, the program must use some visual method in the GUI to close itself.
* this visual method must be what causes the program to close; you cannot just show it as something on the side (though there may be other things off to the side)

Note:

* The program does not have to be visible long enough for the visible activity to be seen by a human as long as the activity is the cause of the closing.
* The window must be a GUI (must display a graphical window that contains the visible exit method).
* The visual method needs to be something the user could do if it wasn't done automatically. Explain what needs to be changed in the code for the user to be able to do this (Thanks to Iszi).
* The program must close if there is no interference from the user, but if the user interferes, then it does not need to close automatically.
* Please include an explanation of what it is that causes the program to close.

Example: a window containing a button which is programmatically clicked, running a short snippet of code that closes the program.

# Answer
> 8 votes
# TI-Basic, 3 bytes

```
DispGraph:1

hex: 31 3E DF

```

**Explanation**

`DispGraph` Displays the graph (a graphical window)

`:1` Simulates a press of `1` (by storing `1` to `Ans` at the last step of a program), which takes the calculator back to the home screen. A user could do the same thing.

# Answer
> 10 votes
# Ruby with Shoes, 110

```
Shoes.app{button('Close'){exit}
p=para
t=Time.now
animate{u=(t-Time.now).to_i+10
exit if u<0
p.text=' '*u+?<}}

```

Makes a little arrow that pushes a "Close" button. (Pushing the close button manually also closes the window.)

# Answer
> 9 votes
## Windows Batch, 4 bytes

Save the following program to a `.bat` file in your user folder (C:\Users\username):

```
Exit

```

When executed from the **Start, Run** prompt, a new window opens, types the command `Exit` and executes it.

# Answer
> 4 votes
### JavaScript: ~~133~~ 117

(You need to allow popups in your web browser for this to work)

Code-golfed:

```
(function(){w=window.open(),d=999,i=setInterval(function(){w.resizeTo(d-=9,d),d<0&&(clearInterval(i),w.close())})})()

```

Source: http://jsfiddle.net/gt2t8/2/

# Answer
> 4 votes
## Golf-Basic 84, ~~5~~ 4

```
g`:1

```

Display the graph, simluate a press of 1, closing the graph and returning home.

# Answer
> 2 votes
## x86 / Win32 assembly (~~337~~ ~~310~~ 271 bytes)

```
.586
.model flat
option casemap:none
include kernel32.inc
include windows.inc
include user32.inc
i textequ <invoke>
.code
s:i CreateThread,0,0,$+46,0,0,0
i MessageBox,0,$,$,0
i ExitProcess,0
i Sleep,999
i FindWindow,0,$
i PostMessage,eax,256,13,0
ret
END s

```

Assembles with MASM32 (`ml /c /coff /Gz /I<include path> test.asm` / `link /SUBSYSTEM:WINDOWS /LIBPATH:<library path> test.obj kernel32.lib user32.lib`).

It creates a MessageBox with an *"OK"* button, and a thread that simulates a carriage return press from the user after 999 ms.

The `$` is substituted with the address of the beginning of the `code` section by the assembler/linker. The first instruction is a `push byte 0` (implicitly, since it's generated by the `invoke`), which is encoded as `6A 00`, which equals the null-terminated string `"j"`. I take advantage of this when calling `MessageBox` and `FindWindow`.

# Answer
> 1 votes
# Bash with X Window System, 10 chars

```
xterm -e :

```

Open an xterm window, run the bash no-op `:`, after which the xterm window closes.

If you want to see the useless window for a second, you can change the `:` to `sleep 1`:

```
xterm -e sleep 1

```

# Answer
> 1 votes
# Tcl/Tk, 131

```
grid [button .b -command exit]
event generate .b <Button-1> -warp 1 -x 5 -y 5
event generate .b <ButtonRelease-1> -warp 1 -x 5 -y 5

```
~~Tcl/Tk, 136
```
grid [button .b -command exit]
event generate .b <ButtonPress-1> -warp 1 -x 5 -y 5
event generate .b <ButtonRelease-1> -warp 1 -x 5 -y 5

```~~

It needs to be ran on an interactive shell, line by line and user can not move the mouse between.

1. Application starts

2. Button whose behaviour is to close the app is added to the app window

3. Generate an event that presses down the mouse on the button — Altough the cursor is not visible in the screenshot it is over the button; it is visible the buttonhas been pressed because it now sunken in, and before it was embossed out.

4. Finally generate an event that releases the mouse button up.

a. Image before really sending it (before pressing Enter)

b. After Enter the interactive shell and the app windows just disappeared.

**Note to tcl'ers:** Tried to do the same directly on the window's X Close button using:

```
event generate . <ButtonPress-1> -warp 1 -x 175 -y -10
event generate . <ButtonRelease-1> -warp 1 -x 175 -y -10

```

but I was not successful.

# Answer
> 0 votes
## Bash - echo (50 bytes)

**Not golfed, 54 bytes:**

```
s=sleep;echo -n \>\\;$s 1;echo -ne "\b\b >/";$s 1;echo

```

**Golfed, 50 bytes**

I can't exactly display the golf version here because the backspace characters actually backspace. For the golf version, change both of the "^H" to single backspace (^H) characters:

```
s=sleep;echo -n \>\\;$s 1;echo -n ^H^H \>/;$s 1;echo

```

**Notes:**

* The activity is visible for 2 seconds.
* It doesn't use a window manager or anything of that sort, but I count the ASCII art as a "gui". If you are running the command in a terminal window, which is now the usual case, the activity is displayed in that window. It does not open up a new window.
* The user can close the program sooner than the automatic close by hitting "CTRL-C" within 2 seconds of starting the program. Users who are more comfortable using their GUI can put their cursor on the little "X" in the corner of the terminal window, quickly, and "click" it.
* The program closes after 2 seconds if there is no interference from the user. The user can only cause it to close sooner.
* What causes the program to close is the completion of the final "echo".

---
Tags: code-golf
---


title: How compute WPA key?

text:
# Question
Title: How compute WPA key?
WPA2, the actual encryption standard that secures all modern wifi networks, has been **cracked**... This challenge has nothing to do with the way that the WPA2 was cracked, however is is about computing the 64-digit hexadecimal key that corresponds to a given WPA-PSK pass-phrase.

A wireless network with WPA-PSK encryption requires a pass-phrase to be entered to get access to the network. Most wireless drivers accept the pass-phrase as a string of at most 63 characters, and internally convert the pass-phrase to a 256-bit key. However, some systems also allow the key to be entered directly in the form of 64 hexadecimal digits. So the challenge is to calculate the 64-digit hexadecimal key that corresponds to a given pass-phrase.

The hexadecimal key is computed from the pass-phrase and the network **SSID** (an SSID is a unique ID that consists of 32 characters).

**Details of the calculation**

For WPA-PSK encryption, the binary key is derived from the pass-phrase according to the following formula: `Key = PBKDF2(pass-phrase, SSID, 4096, 256)`

The function `PBKDF2` is a standardized method to derive a key from a pass-phrase. It is specified in RFC2898 with a clear explanation on how to compute it. The function needs an underlying pseudo-random function. In the case of WPA, the underlying function is `HMAC-SHA1`.

`SHA1` is a function that computes a 160-bit hash from an arbitrary amount of input data. It is clearly explained in RFC3174. `HMAC` is a standardized method to turn a cryptographic hash function into a keyed message authentication function. It is specified in RFC2104.

To summarize, the key derivation process involves iterating a `HMAC-SHA1` function 4096 times, and then doing that again to produce more key bits.

**Inputs**

* SSID a string of at most 32 characters (e.g. `stackexchange`)
* pass-phrase a string of at most 63 characters (e.g. `<ra(<@2tAc<$`)

**Output** any reasonable output of the 64 hexadecimal digits

* e.g. `24343f69e98d3c08236a6db407584227cf2d1222b050e48f0cf25dee6563cd55`
* it is the result of the previous inputs

This is , so please make your program as short as possible!

# Answer
> 5 votes
# C# (.NET Core) lambda expression, 88 82 81 bytes

Takes input as byte arrays (curried, see comments), returns key as byte array.

```
p=>s=>new System.Security.Cryptography.Rfc2898DeriveBytes(p,s,4096).GetBytes(32);

```

Try it online!

# Answer
> 4 votes
# Java, ~~192~~ 88 + 36 = 124 bytes

36 bytes for `import de.rtner.security.auth.spi.*;`

`a` is the SSID taken as a byte array, `b` is the password taken as a string. Outputs byte array. Requires PBKDF2.

```
a->b->new PBKDF2Engine(new PBKDF2Parameters("HmacSHA1","UTF-8",a,4096)).deriveKey(b,32);

```

### Old answer:

Takes SSID as char array and password as byte array. Outputs byte array.

```
a->b->{try{return javax.crypto.SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(new javax.crypto.spec.PBEKeySpec(a,b,4096,256)).getEncoded();}catch(Exception e){return null;}}

```

Try it online!

---
Tags: code-golf
---


title: Fill the steps (randomly)!

text:
# Question
Title: Fill the steps (randomly)!
**This is Hole-9 from *The Autumn Tournament* of APL CodeGolf. I am the original author of the problem there, and thus allowed to re-post it here.**

---

Given a simple (rectangular, non-jagged) Boolean array (of one or more dimensions) return a list of thusly shaped arrays where the first array is identical to the input and the last is all-true. All intermediary steps must have one more truth than its neighbor to the left (but otherwise be identical). For each step, the bit that is changed must be pseudo-randomly chosen (and you may take a seed if necessary).

### Examples

`[0]` gives `[[0],[1]]`

`[[0]]` gives `[[[0]],[[1]]]`

`[[[1,1,1],[1,1,1],[1,1,1]],[[1,1,1],[1,1,1],[1,1,1]],[[1,1,1],[1,1,1],[1,1,1]]]` gives `[[[[1,1,1],[1,1,1],[1,1,1]],[[1,1,1],[1,1,1],[1,1,1]],[[1,1,1],[1,1,1],[1,1,1]]]]`

The following examples' results may of course vary due to randomness; these are just examples of valid output:

`[0,1,0,0]` gives `[[0,1,0,0],[1,1,0,0],[1,1,0,1],[1,1,1,1]]`

`[[0,1,0],[0,0,1]]` gives `[[[0,1,0],[0,0,1]],[[1,1,0],[0,0,1]],[[1,1,0],[0,1,1]],[[1,1,1],[0,1,1]],[[1,1,1],[1,1,1]]]`

`[[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0]]` gives `[[[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,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[1,1,1,1,1,1,1,1],[0,1,1,1,1,1,1,1],[1,1,1,0,1,1,1,1],[1,1,1,1,1,0,1,1],[1,1,1,1,1,1,1,1],[1,1,1,0,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1]],[[1,1,1,1,1,1,1,1],[0,1,1,1,1,1,1,1],[1,1,1,0,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,0,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1]],[[1,1,1,1,1,1,1,1],[0,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,0,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1]],[[1,1,1,1,1,1,1,1],[0,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1]],[[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1]]]`

# Answer
> 3 votes
# Jelly, 12 bytes

```
F¬0TX$¦ÐĿ¬ṁ€

```

Try it online!

### How it works

```
F¬0TX$¦ÐĿ¬ṁ€  Main link. Argument: A (array)

F             Flatten A.
 ¬            Negate all Booleans in the result.
       DĿ     Repeatedly call the link to the left until the results are no longer
              unique. Yield the array of all unique results.
      ¦         Sparse application:
   TX$            Pseudo-randomly select an index of a 1.
  0               Replace the element at that index with 0.
         ¬    Once again negate all Booleans.
          ṁ€  Shape each flat array in the result like A.

```

# Answer
> 2 votes
# Python 2, 197 bytes

```
import random,copy
A=[input()]
while"0"in`A[-1]`:
 A+=copy.deepcopy(A[-1]),
 while~0:
	j="A[-1]"
	while[]<eval(j):j+="[%s]"%random.randint(0,~-len(eval(j)))
	if eval(j)<1:exec"%s=1"%j;break
print A

```

Try it online!

# Answer
> 1 votes
## Wolfram Language (Mathematica), 61 bytes

```
FoldList[ReplacePart[#,#2->1]&,#,RandomSample@Position[#,0]]&

```

Try it online!

### Explanation

```
Position[#,0]

```

Find all positions of `0`s in the nested array.

```
RandomSample@...

```

Shuffle the list of positions.

```
FoldList[...&,#,...]

```

Fold the function on the left over the shuffled list of positions, using the input as the starting value, and collect all steps of the fold operation in the result.

```
ReplacePart[#,#2->1]

```

Set the value at the given position to `1`.

# Answer
> 1 votes
# , ~~93~~ ~~82~~ 74 bytes

```
function(a)Reduce(function(x,y){x[y]=T;x},sample(as.list(which(!a))),a,,T)

```

Try it online!

Takes an R `logical` `array` and returns a `list` of `logical` `array`s.

The nasty `sample(as.list(which(!a)))` is to prevent an edge case in `sample`. When `a` contains exactly one `FALSE` value at index `i`, `sample` returns a random permutation of `1:i` rather than a random sample of size `1` containing only the value `i`, so I used `as.list` to prevent `which(!a)` from being `numeric`.

The R documentation for `sample` is mildly apologetic about this behavior:

> If `x` has length 1, is numeric (in the sense of `is.numeric`) and `x >= 1`, sampling via sample takes place from 1:x. ***Note* that this convenience feature may lead to undesired behaviour when x is of varying length in calls such as `sample(x)`.**

# Answer
> 1 votes
# Perl 5, 78 + 1 (`-p`) = 79 bytes

```
while(@a=/0/g){$o.="$_,";for$i(0..rand@a){/0/g}substr$_,-1+pos,1,1}$_="[$o$_]"

```

Try it online!

Array? What array? It's just a long string.

# Answer
> 0 votes
# Jelly, 19 bytes

```
F¬TṬ€$$o€$ṁ€µX$ÐĿṖṖ

```

Try it online!

Probably could be shorter

# Explanation

```
F¬TṬ€$$o€$ṁ€µX$ÐĿṖṖ  Main Link
               ÐĿ    While results are unique:
F                    Flatten the array
     $$              3 links will form a monad
 ¬                   Logical NOT on each element
  T                  Find indices of 1s (0s in the original)
    €                For each 0 in the original
   Ṭ                 Make an array of all 0s containing one 1 there
         $           2 links will form a monad
        €            For each of the mask arrays
       o             Vectorizing logical OR it with the original (flat) array
           €         For each of these subarrays
          ṁ          Reshape it to the original array's shape
            µ        Start a new monadic chain, using the list of possible next steps as the argument
              $      2 links will form a monad
             X       Pick a random element
                 ṖṖ  Remove the last two elements (0 and '' which are selected by X when the list is empty)

```

# Answer
> 0 votes
# Python 2, ~~134~~ ~~132~~ 129 bytes

```
from random import*
a=input()
print a;l=list(`a`)
while'0'in l:l[choice([i for i,c in enumerate(l)if'0'==c])]='1';print''.join(l)

```

Try it online!

---
Tags: code-golf, sequence, array, random, apl
---


# Question
Title: Take first letter of each word, leave spaces and punctuation
Shrink each word in a string of group of strings to single letters delineated by spaces or punctuation.

### Example

```
I'm a little teapot,  short and stout. Here is my handle, here is my spout. When I get all steamed up - hear me shout!   Tip me over and pour me out.

```

becomes

```
I' a l t, s a s. H i m h, h i m s. W I g a s u - h m s! T m o a p m o.

```

Edit - if there are multiple spaces, preserve only one space. All punctuation should be preserved, I missed the apostrophe. Yes this is code golf :-).

# Answer
# CJam, 13 bytes

```
r{(\'A,f&Sr}h

```

Works if I can consider only the common punctuation characters, and the output can have trailing spaces. (Thanks to Dennis.)

This question needs much more clarification...

# CJam, 17 16 bytes

```
r{(\eu_elf&Sr}h&

```

Try it online.

### Explanation

```
r          e# Read one word from input.
{          e# While it is not EOF:
    (\     e# Extract the first character.
    eu     e# Convert the rest to uppercase.
    _el    e# And lowercase.
    f&     e# Delete characters in the first string if not in the second string.
    S      e# Append a space.
    r      e# Read the next word.
}h
&          e# Discard the last space by intersecting with empty string.

```
> 5 votes

# Answer
# Pyth, 14 bytes

```
jdm+hd-rtd0Gcz

```

Try it online: Demonstration

### Explanation:

```
                 implicit: z = input string
            cz   split z by spaces
  m              map each word d to:
    hd              first letter of d
   +                +
       rtd0         (lowercase of d[1:]
      -    G         but remove all chars of "abc...xyz")
jd               join resulting list by spaces and print

```
> 4 votes

# Answer
# Python 3.4, ~~94~~ ~~92~~ ~~82~~ 77 bytes

```
print(*[w[0]+''.join(c[c.isalpha():]for c in w[1:])for w in input().split()])

```

I'm new to code golfing but I thought I'd give it a try! This one's not a winner, but it was fun.

This just splits the string, taking the first character of each word along with any punctuation in the rest of the word.

\*edited with changes by FryAmTheEggman, DLosc
> 2 votes

# Answer
# Jelly, 14 bytes

```
Ḣ;ḟØB$
Ḳ¬ÐfÇ€K

```

Try it online!

Solution done with *Mr. Xcoder* and *caird coinheringaahing* in Jelly Hypertraining chat room.

Alternative 14 bytes: Try it online!
> 2 votes

# Answer
# sed (39 chars)

Just a couple of regular expressions:

```
sed 's+\<\(.\)[A-Za-z]*+\1+g;s+  *+ +g'

```
> 1 votes

# Answer
# Javascript (*ES6*) 72 68 bytes

```
f=x=>x.split(/\s+/).map(x=>x.replace(/^(.)|[a-z]/gi,'$1')).join(' ')
```

```
<input id="input" value="I'm a little teapot,  short and stout. Here is my handle, here is my spout. When I get all steamed up - hear me shout!   Tip me over and pour me out. " />
<button onclick="output.innerHTML=f(input.value)">Run</button>
<br /><pre id="output"></pre>
```

**Commented:**

```
f=x=>
    x.split(/\s+/). // split input string by 1 or more spaces
    map(x=> // map function to resulting array
        x.replace(/^(.)|[a-z]/gi, '$1') // capture group to get the first character
                                        // replace all other letters with empty string
    ).
    join(' ') // join array with single spaces

```
> 1 votes

# Answer
## PowerShell, 56 bytes

```
%{($_-split' '|%{$_[0]+($_-replace'[a-z]','')})-join' '}

```
> 1 votes

# Answer
# Lua - 126 characters

Lua isn't much of a code golfing language, but I gave it a shot:

```
a=''for b in string.gmatch( c, '%S+%s?' )do d=(b:match('%w')or''):sub(1,1)e=b:match('[^%s%w]')or''a=a..d..e..' 'end print( a )

```

This assumes that `c` is the string.

Here it is cleaned up for readability:

```
local string = [[I'm a little teapot,  short and stout. Here is my handle, here is my
spout. When I get all steamed up - hear me shout!   Tip me over and pour me out.]]

local final = ''
for word in string.gmatch( string, '%S+%s?' ) do
    local first = ( word:match( '%w' ) or '' ):sub( 1, 1 )
    local second = word:match( '[^%s%w]' ) or ''
    final = final .. first .. second .. ' '
end
print( final )

```

You can test it here (copy and paste it. For the first on you also have to do `c = "I'm a little ...`.) For some reason the online demo of Lua won't let you input variables using `io.read`...
> 1 votes

# Answer
## C99 - ~~170~~ 169 bytes

```
main(_,a)char**a;{for(char*b=a[1],*c=b,*e,*d;*c++=*b;){for(e=b;*++b&&*b-32;);for(*b=0,d=strpbrk(e,"!',-."),d&&d-e?*c++=*d:0;b[1]==32;++b);++b;*c++=32;*c=0;}puts(a[1]);}

```

Ungolfed:

```
main(int argc, char**a) {
    char*b=a[1],*c=b,*e,*d;
    while(*c++=*b){
        for(e=b;*++b&&*b-32;); //scan for first space or end of word
        *b=0; //mark end of word
        for(;b[1]==32;++b); //skip following spaces
        d=strpbrk(e,"!',-."); //find punctuation
        if(d&&d-e) //append punctuation if any, and it's not the word itself
            *c++=*d;
        *c++=32; //append space
        b++;
    }
    *c=0; //mark end of line
    puts(a[1]);
}

```

Usage:

```
gcc -std=c99 test.c -o test
./test "I'm a little teapot,  short and stout. Here is my handle, here is my spout. When I get all steamed up - hear me shout!   Tip me over and pour me out."

```

Output:

```
I' a l t, s a s. H i m h, h i m s. W I g a s u - h m s! T m o a p m o.

```
> 1 votes

# Answer
# Java 8, 87 bytes

```
s->{for(String x:s.split(" +"))System.out.print(x.replaceAll("^(.)|[a-z]+","$1")+" ");}

```

**Explanation:**

Try it here.

```
s->{                                  // Method with String parameter and no return-type
  for(String x:s.split(" +"))         //  Split the input on one or multiple spaces
                                      //  And loop over the substrings
    System.out.print(                 //   Print:
      x.replaceAll("^(.)|[a-z]+","$1")//    Regex to get the first letter + all non-letters
      +" ");                          //    + a space delimiter
                                      //  End of loop (implicit / single-line body)
}                                     // End of method

```

**Regex explanation:**

```
x.replaceAll("^(.)|[a-z]+","$1")
x.replaceAll("           ","  ") # Replace the match of String1 with String2, in String `x`
             "           "       # Regex to match:
              ^(.)               #  The first character of String `x`
                  |[a-z]+        #  Or any one or multiple lowercase letters
                           "  "  # Replace with:
                            $1   #  The match of the capture group (the first character)

```

So it basically removes all lowercase letters of a String, except the very first one.
> 1 votes

# Answer
# Perl 5, 34 bytes

**33 bytes code + 1 for `-p`.**

```
s!\S\K\S+| \K +!$&=~s/\w| //gr!ge

```

Try it online!
> 1 votes

# Answer
# R, ~~46~~ 45 bytes

```
cat(gsub("^\\w\\W*\\K\\w*","",scan(,""),T,T))

```

This reads a line from STDIN and prints to STDOUT. It uses a regular expression to remove all characters after the first letter followed by any amount of punctuation.

Ungolfed + explanation:

```
# Read a string from STDIN and convert it to a character vector,
# splitting at spaces

input <- scan(what = "")

# Replace stuff with nothing using a regex.
# ^ start position anchor
# \w single "word" character
# \W* any amount of non-word (i.e. punctuation) characters
# \K move the match position forward
# \w* any number of word characters

replaced <- gsub("^\\w\\W*\\K\\w*", "", input, ignore.case = TRUE, perl = TRUE)

# Print the vector elements to STDOUT, separated by a space

cat(replaced, sep = " ")

```

Example:

```
> cat(gsub("^\\w\\W*\\K\\w*","",scan(,""),T,T))
1: I'm a little teapot,  short and stout. Here is my handle, here is my spout. When I get all steamed up - hear me shout!   Tip me over and pour me out.

I' a l t, s a s. H i m h, h i m s. W I g a s u - h m s! T m o a p m o.

```
> 0 votes

# Answer
# 05AB1E, 13 bytes

```
#õKεćsDáмJ}ðý

```

Try it online!

**Explanation:**

```
#õKεćsDáмJ}ðý  Full program
#              Split on spaces
 õK            Remove empty strings from the list
   ε           For each...
    ć             push a[1:], a[0]
     s            Swap
      D           Duplicate
       á          Push only letters of a
        м         pop a,b => push a.remove(all elements of b)
         J        Join
          }    End for each
           ðý  Join with spaces

```
> 0 votes

# Answer
**VBA (Excel), ~~141~~ 133 Bytes**

Using VBA Immediate Window, \[A1\] as Inputted Strings.

~~```
z=" "&[A1]:for a=2 to len(z):c=mid(z,a,1):[A2]=[A2]&IIF(mid(z,a-1,1)=" ",c,IIF(asc(lcase(c))>96 and asc(lcase(c))<123,"",c)):next:?[TRIM(A2)]

```~~
```
z=" "&[a1]:for a=2 to len(z):c=mid(z,a,1):e=asc(lcase(c)):[a2]=[a2]&iif(mid(z,a-1,1)=" ",c,IIF((e>96)*(e<123),"",c)):next:?[TRIM(A2)]

```
> 0 votes

# Answer
# Perl 6, 15 bytes

```
s:g/(\w)\w+/$0/

```

Try it online!
> -1 votes

---
Tags: code-golf, string
---


title: Generate random LTL Formulae

text:
# Question
Title: Generate random LTL Formulae
An LTL Formula l is defined by the following grammar (where \<x\> describes the non-terminal symbol x):

```
<l> ::= <b> | F <l> | G <l> | X <l> | (<l> U <l>) | (<l> W <l>) | (<l> R <l>)
            | (<l> & <l>) | (<l> \| <l>) | !<l>
<b> ::= BVar | True | False | (<i> < <i>) | (<i> <= <i>) | (<i> > <i>) | (<i> >= <i>)
             | (<i> = <i>) | (<i> != <i>)
<i> ::= IVar | -128 | -127 | ... | 127 | (<i> + <i>) | (<i> - <i>)
             | (<i> * <i>) | (<i> / <i>)

```

(I escaped a pipe to denote boolean or. You should not print that backslash in your output)

BVar and IVar represent variables of boolean and integral types respectively. Each must be one of four possible single character variable names, and there may by no overlap between BVar and IVar. For instance, you may choose a,b,c,d for BVar and w,x,y,z for IVar

Note that all binary operators must have parentheses around them and that no other parentheses are allowed.

Your task is to write a function that takes one input encoding the maximal nesting depth of an LTL formula and prints a random formula limited by that depth (but not necessarily exactly that depth). The distribution does not have to be uniformly random, but each possible formula has to have a non-zero chance of being generated.

You may use ≤, ≥, and ≠ instead of \<=, \>=, and !=.

You may add or remove whitespace as you see fit. Even no whitespace at all is allowed.

Examples:

```
f(0) -> True
f(0) -> d
f(1) -> (a&b)
f(1) -> Fd
f(1) -> (x<y)
f(3) -> (G(x!=y)|Fb)
f(3) -> (x<(w+(y+z)))

```

Standard loopholes are forbidden.

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

# Answer
## Perl 5, 251 bytes

**249 bytes code + 2 for `-pa`.**

```
$d=I;sub a{map"($d$_$d)",@_}@I=(w..z,-128..127,a qw{+ - * /});@L=(@B=(a..d,True,False,a qw{< <= > >= = !=}),B,FL,GL,XL,"!".($d=L),a qw{U W R & |});$_=$L[rand@L];0while s/L|B|I/@{$&}[rand@{$&}]/e;$;=$_;s/[^()]//g;0while s/\)\(//g;$_=y/(//>"@F"?redo:$

```

Try it online!
> 4 votes

# Answer
# Python 3, ~~298~~ ~~293~~ ~~283~~ 279 bytes

```
def f(n,t=1):s,*X=c([[(c(V[t>1]),)],[('%s',0),(c('FGX!')+'%s',1)]][t&1]+[(f"(%s{c('<U+≤W->R*≥&/=|+≠'[t::3])}%s)",*[2-(t&1)]*2)]);return n and s%tuple(f(n-1,x)for x in X)or c(V[t>1])
from random import*
c=choice
V=['True','False',*'abcd'],[*map(str,range(-128,128)),*'wxyz']

```

Try it online!
> 2 votes

# Answer
# Java 8, ~~456~~ ~~423~~ ~~419~~ ~~407~~ 403 bytes

```
n->{int r=R(9);return r>4?(r<8?"FGX!".charAt(r-5):"")+b(n):"("+b(n)+"UWR&|".charAt(r)+b(n)+")";};int R(int i){return i*=Math.random();}String b(int n){int r=R(9);return r>7?"abcd".charAt(r%4)+"":r>6?"True":r>5?"False":n>0?"("+i(n)+"<≤>≥=≠".charAt(r)+i(n)+")":b(n);}String i(int n){int r=R(n>0?256:261);return(r-=128)>131?"wxyz".charAt(r+2&3)+"":r>127?"("+i(--n)+"+-*/".charAt(r-128)+i(n)+")":r+"";}

```

-8 bytes thanks to *@ceilingcat*.

Try it online.

NOTE: Due to the rule "*The distribution does not have to be uniformly random*", I've been able to golf some parts by using modulo-4 on the input or random integer for the characters `"abcd"` or `"wxyz"`, and change `Math.random()*10` to `Math.random()*9` and change the ternary a bit. Personally I prefer to have the randomness equally divided for each method, which is **~~456~~ ~~441~~ 404 bytes** instead (and is explained below):

```
n->{int r=R(10);return r>4?(r<9?"FGX!".charAt(r-5):"")+b(n):"("+b(n)+"UWR&|".charAt(r)+b(n)+")";}int R(int i){return i*=Math.random();}String b(int n){int r=R(9);return r>7?"abcd".charAt(R(4))+"":r>6?"True":r>5?"False":n>0?"("+i(n)+"<≤>≥=≠".charAt(r)+i(n)+")":b(n);}String i(int n){int r=R(n>0?256:261);return(r-=128)>131?"wxyz".charAt(R(4))+"":r>127?"("+i(--n)+"+-*/".charAt(r-128)+i(n)+")":r+"";}

```

Try it online.

**Explanation:**

```
n->{                     // Method with integer parameter and String return-type
  int r=R(10);           //  Random integer [0,9]
  return r>4?            //  Is it [5,9]:
    (r<9?                //   Is it [5,8]:
      "FGX!".charAt(r-5) //    Return a leading character
     :                   //   Else (it's 9):
      "")                //    Return nothing
    +b(n)                //   + call to method `b(n)`
   :                     //  Else (it's [0-4]):
    "("                  //   Return opening parenthesis
    +b(n)                //   + call to method `b(n)`
    +"UWR&|".charAt(r)   //   + middle character
    +b(n)                //   + another call to method `b(n)`
    +")";                //   + closing parenthesis
}                        // End of method

int R(int i){            // Method `R(i)` with integer as both parameter and return-type
  return i*=Math.random();
                         //  Return a random integer in the range [0,i)
}                        // Else of method `R(i)`

String b(int n){         // Method `b(n)` with integer parameter and String return-type
  int r=R(9);            //  Random integer [0,8]
  return r>7?            //  Is it 8:
     "abcd".charAt(R(4))+""
                         //   Return random from "abcd"
   :r>6?                 //  Else-if it's 7:
    "True"               //   Return literal "True"
   :r>5?                 //  Else-if it's 6:
    "False"              //   Return literal "False"
   :n>0?                 //  Else-if it's [0-5] AND the input is larger than 0:
    "("                  //   Return opening parenthesis
    +i(n)                //   + call to method `i(n)`
    +"<≤>≥=≠".charAt(r)  //   + middle character
    +i(n)                //   + another call to method `i(n)`
    +")"                 //   + closing parenthesis
   :                     //  Else (it's [0-5] and the input is 0):
    b(n);                //   Call itself again, hoping for random [6-8]
}                        // End of method `b(n)`

String i(int n){         // Method `i(n)` with integer parameter and String return-type
  int r=R(n>0?256:261);return(r-=128)
                         //  Random integer in range [-128,128]
                         //  OR [-128,132] if the input is larger than 0
  >131?                  //  If it is 132:
     "wxyz".charAt(R(4))+""
                         //   Return random from "wxyz"
   :r>127?               //  Else-if it's [128,131]:
    "("                  //   Return opening parenthesis
    +i(--n)              //   + call to `i(n-1)`
    +"+-*/".charAt(r-128)//   + middle character
    +i(n)                //   + another call to `i(n-1)`
    +")"                 //   + closing parenthesis
   :                     //  Else:
    r+"";                //   Return the random integer [-128,127]
}                        // End of method `i(n)`

```
> 1 votes

---
Tags: code-golf, random, generation, logic
---


title: Where can the knight be in N moves?

text:
# Question
Title: Where can the knight be in N moves?
**This is Hole-3 from *The Autumn Tournament* of APL CodeGolf. I am the original author of the problem there, and thus allowed to re-post it here.**

---

Given:

1. a number of turns (please state if no movements is 0, otherwise we'll assume it is called 1) and
2. a list of one or more starting positions (in any form, e.g. 0 or 1 indexed coordinates or 64 consecutive numbers/characters or A1–H8 – state which), on an 8-by-8 chessboard,

return (in any order) the list of unique positions (in the same format as the input) that knight(s) can be at after the given number of turns.

* Each knight must move with every turn, but you do not have to worry about multiple knights occupying the same square.
* A knight can only move to the positions marked with X relative to its current position, marked with ♞:

### Examples (1-indexed coordinates)

`1` move from `[[1,1]]`: `[[2,3],[3,2]]`

`2` moves from `[[1,1]]`: `[[1,1],[1,3],[1,5],[2,4],[3,1],[3,5],[4,2],[4,4],[5,1],[5,3]]`

`1` move from `[[1,1],[5,7]]`: `[[2,3],[3,2],[3,6],[3,8],[4,5],[6,5],[7,6],[7,8]]`

`2` moves from `[[1,1],[5,7]]`: `[[1,1],[1,3],[1,5],[1,7],[2,4],[2,6],[2,8],[3,1],[3,3],[3,5],[3,7],[4,2],[4,4],[4,6],[4,8],[5,1],[5,3],[5,5],[5,7],[6,4],[6,6],[6,8],[7,3],[7,7],[8,4],[8,6],[8,8]]`

`0` moves from `[[3,4]]`: `[[3,4]]`

# Answer
> 12 votes
# Wolfram Language (Mathematica), 45 bytes

Because the other solution is incorrect (see Martin's comment below), so I decide to post my solution:

```
8~KnightTourGraph~8~AdjacencyList~#&~Nest~##&

```

Try it online!

Ultimate infix notation...

Takes 2 input, the first one is a list of numbers in range `[1,64]` describe the starting positions of the knight, the second one is the number of steps.

This solution relies on the extreme convenience of Mathematica builtin functions:

* `AdjacencyList` may takes a list of vertices on its right side, and return a list of vertices adjacent to any of those, **already removed duplicates and sorted**.
* `KnightTourGraph` is a builtin. Not surprise.
* `Nest` takes arguments in order `Nest[f, expr, n]`, which we can splat the `##` over its right side as `Nest[f, ##]`.
* And finally, Mathematica parse `a~b~c~d~e` as `(a~b~c)~d~e`, so no square bracket is necessary. Without infix notation and flatten `##`, it would be `Nest[AdjacencyList[KnightTourGraph[8, 8], #] &, #, #2]&`.

# Answer
> 8 votes
# JavaScript (ES7), 99 bytes

Input/output format: squares indices in **\[0 ... 63\]**.

```
f=(a,n)=>n--?f([...Array(64).keys()].filter(p=>!a.every(P=>(p%8-P%8)**2^((p>>3)-(P>>3))**2^5)),n):a

```

### Test cases

This snippet includes two helper functions to translate from and to the format provided by the OP.

```
f=(a,n)=>n--?f([...Array(64).keys()].filter(p=>!a.every(P=>(p%8-P%8)**2^((p>>3)-(P>>3))**2^5)),n):a

c2s = a => a.map(c => (c[0] - 1) * 8 + c[1] - 1)
s2c = a => JSON.stringify(a.map(s => [(s >> 3) + 1, s % 8 + 1]))

console.log(s2c(f(c2s([[1,1]]), 1)))
console.log(s2c(f(c2s([[1,1]]), 2)))
console.log(s2c(f(c2s([[1,1],[5,7]]), 1)))
console.log(s2c(f(c2s([[1,1],[5,7]]), 2)))
console.log(s2c(f(c2s([[3,4]]), 0)))
```

### How?

A move from **(x,y)** to **(X,Y)** is a valid knight move if we have either:

* **|x-X| = 1** and **|y-Y| = 2**, or
* **|x-X| = 2** and **|y-Y| = 1**

By squaring instead of using absolute values, this can be expressed as:

* **(x-X)² = 1** and **(y-Y)² = 4**, or
* **(x-X)² = 4** and **(y-Y)² = 1**

Because **1** and **4** are the only perfect squares that give **5** when XOR'd together, we have a valid knight move if:

**(x-X)² XOR (y-Y)² XOR 5 = 0**

We apply this formula to each square **p = 8y + x** on the board and each knight square **P = 8Y + X** to deduce the new possible knight target squares, and recursively repeat this process **n** times.

# Answer
> 5 votes
# Retina, ~~147~~ 102 bytes

```
.$
$*
¶
 ¶
{s`((?<=N(....|.{11}|.{13})?.{7})|(?=.{8}(....|.{11}|.{13})?N))\S(?=.*	)
n
Ts`	Nn`_:N`.*¶

```

Try it online! Takes input as an 8x8 board of `:`s with the knights marked with `N`s, with a digit for the number of turns on the next line (it makes no sense to have more than 9 turns, but if you insist I can support it for an extra byte). Note that the output contains additional white space. Edit: Saved 45 bytes thanks to @MartinEnder. Explanation: The first stage converts the number of turns to unary, but using tab characters, so that they don't get matched later by accident, while the second stage adds some spaces to the right of the board to stop the regexes from wrapping across the edge. The third stage replaces all `N`s and `:`s that are a knight's move away from an `N` with an `n` while the fourth stage deletes any remaining `N`s, changes the `n`s to `N`s, and subtracts 1 from the move count. This repeats until the move count is zero.

# Answer
> 5 votes
# Octave , 69 bytes

```
function a=f(a,n,b=~a)for k=1:n;a=b&imdilate(a,de2bi(")0#0)"-31));end

```

Online Demo!

The input/output is the configuration of the board at start/end as a binary 8\*8 matrix.

Explanation:

For `n` steps repeat morphological dilation of the board with the following mask:

```
01010
10001
00100
10001
01010

```

# Answer
> 4 votes
# Jelly, 29 bytes

```
+þ1,2Œ!×þ1,-p`¤¤Ẏ¤Ẏ⁼%8$$ÐfQµ¡

```

Try it online!

0-indexed coordinates. Almost certain this is suboptimal.

-1 byte thanks to user202729

# Explanation

```
+þ1,2Œ!×þ1,-p`¤¤Ẏ¤Ẏ⁼%8$$ÐfQµ¡  Main Link
+þ                             Addition Table (all pairs using + as combining function) with
  1,2Œ!×þ1,-p`¤¤Ẏ¤             All knight moves:
  1,2                          [1, 2]
     Œ!                        All permutations ([1, 2], [2, 1])
       ×þ                      Product Table (all pairs using × as combining function) with
         1,-p`¤                [1, 1], [1, -1], [-1, 1], [-1, -1]
         1,-                   [1, -1]
            p`                 Cartestian Product with itself
               ¤               All knight moves (in a nested array) as a nilad
                Ẏ¤             Tighten (flatten once); all knight moves in a (semi-)flat array
                        Ðf     Keep elements where
                   ⁼%8$$       The element equals itself modulo 8 (discard all elements out of the range)
                          Q    Remove Duplicates
                           µ   Start new monadic chain (essentially, terminates previous chain)
                            ¡  Repeat n times; n is implicitly the second input (right argument)

```

# Answer
> 3 votes
# 05AB1E, ~~27~~ 25 bytes

Thanks to *Emigna* for saving 2 bytes!

Uses 1-indexed coordinates.

### Code:

```
F•eĆ•SÍü‚Dí«δ+€`Ùʒ{`9‹*0›

```

Uses the **05AB1E** encoding. Try it online!

### Explanation:

```
F                          # Do the following <input_1> times..
 •eĆ•SÍ                    #   Push [-1, -2, 1, 2, -1]
       ü‚                  #   Pairwise pairing: [[-1, -2], [-2, 1], [1, 2], [2, -1]]
         D                 #   Duplicate the array
          í                #   Reverse each element
           «               #   Concatenate to the previous array

```

This gives us the following array:

```
[[-1, -2], [-2, 1], [1, 2], [2, -1], [-2, -1], [1, -2], [2, 1], [-1, 2]]

```

Which are the deltas of the moves of the knight.

```
            δ+             #   Addition vectorized on both sides
              €`           #   Flatten each element
                Ù          #   Uniquify
                 ʒ         #   Keep elements which..
                  {`9‹     #     Has a maximum element smaller than 9
                      *0›  #     And a minimum element larger than 0

```

# Answer
> 2 votes
# Java (OpenJDK 8), 124 bytes

```
(m,p)->{for(;m-->0;)for(long a=p,i=p=0,j;i<64;i++)for(j=64;j-->0;)p|=(p=i%8-j%8)*p+(p=i/8-j/8)*p==5?(a>>i&1)<<j:0;return p;}

```

Try it online!

## Input / Output format

The input/output is represented as bits in a `long` (64 bits): set bits mean a horse is present, unset bits mean no horse. Example:

```
// [[0, 0]]
0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000001L

```

## Explanations

```
(m, p) -> {                          // Lambda. No currying because m and p are modified
 for(;m-->0;)                        // For each move
  for(long a=p,i=p=0,j;i<64;i++)     // Declare variables, move p to a, create a new p and loop on bits of a.
   for(j=64;j-->0;)                  // Loop on bits of p.
    p |=                             // Assign to p a value.
     (p=i%8-j%8)*p+(p=i/8-j/8)*p==5  // If i -> j is a valid horse move, see Arnauld's JavaScript answer for full explanations
      ? (a>>i&1)<<j                  // Assign the presence of the horse (i-th bit of a) to the resulting board (j-th bit of p).
      : 0;                           // Else it's not a valid horse move
 return p;
}

```

## Credits

* 19 bytes saved thanks to Nevay!
* Reused the `(X-x)²+(Y-y)²==5` trick from Arnauld's JavaScript answer
* 1 more byte saved thanks to Nevay in the new algorithm!
* 7 more bytes saved thanks to Nevay again by switching from `int[]` to 64-bits `long`.

# Answer
> 2 votes
# Jelly, ~~29~~ 28 bytes

```
8Rp`
“¦Ʋƈ2’D_2ṡ2+€µẎ
ÇƓ¡f1£Q

```

Try it online!

Number of turns is through STDIN, and squares is an argument.

~~This ties @HyperNeutrino's Jelly solution, but with a different approach.~~

Now beating @HyperNeutrino by 1 whole byte!

Any suggestions to knock off some bytes are wanted!

## Link 1 (The chessboard)

```
8Rp`
8R   = The list [1,2,3,4,5,6,7,8]
  p` = cartesian multiplied with itself (this results in the chessboard)

```

## Link 2 (Move generation)

```
“¦Ʋƈ2’D_2ṡ2+€µẎ
“¦Ʋƈ2’          = the number 103414301
      D         = converted into a list of digits
       _2       = subtract two from each element
         ṡ2     = overlapping pairs
           +€   = add to the list of squares
             µ  = Make sure the next part isn't treated as a right argument
              Ẏ = Tighten the list (Reducing the depth by one)

```

## Link 3 (square checking)

```
ÇƓ¡f1£Q
ÇƓ¡     = Repeat link #2 the requested amount of times
   f1£  = Remove everything not a member of link #1 (not on the chess board)
      Q = Make sure squares don't appear more than once

```

# Answer
> 1 votes
# Husk, 18 bytes

```
u!¡ṁö`fΠR2ḣ8=5ṁ□z-

```

Uses 1-based indexing of squares and steps. Try it online!

## Explanation

```
u!¡ṁö`fΠR2ḣ8=5ṁ□z-  Implicit inputs, say P=[[1,1],[5,7]] and n=2
  ¡                 Iterate on P:
   ṁö               Map the following function, then concatenate:
                     Argument is a pair, say p=[5,7].
          ḣ8         The range [1,2,..,8]
       ΠR2           Repeat twice, take cartesian product: [[1,1],[1,2],..,[8,8]]
     `f              Filter with this predicate:
                      Argument is a pair, say q=[3,8].
                z-    Zip p and q with difference: [-2,1]
              ṁ□      Sum of squares: 5
            =5        Is it 5? Yes, so [3,8] is kept.
 !                  Take n'th step of the iteration.
u                   Remove duplicates, implicitly print.

```

# Answer
> 1 votes
# **Python 3, 105 bytes**

```
p=lambda g,i:i and list(set(p([x+y for x in g for y in[6,10,15,17,-6,-10,-15,-17]if 0<=x+y<64],i-1)))or g

```

Have to use a named lambda for the recursion. Not sure if that's disqualifying. Pass in starting positions as 0-indexed square number list. 0 counts as no moves.

# Answer
> 1 votes
# , ~~145~~ ~~183~~ 134 bytes

This is the result of Giuseppe's excellent golfing of my initial not-too-golfy algo (see comment below)

```
function(x,n){x=x%/%8*24+x%%8
t=c(49,47,26,22)
t=c(t,-t)
for(i in 1:n)x=intersect(v<-outer(1:8,0:7*24,"+"),outer(x,t,"+"))
match(x,v)}

```

Try it online!

Input and output are 1...64 based. Takes a vector of position using the 1...64 notation. Maps it to a 1:576 notation, that is a super-board made of nine boards. In this notation, at each iteration, each knight should be able to move by +/- 22,26,47,49 Return future positions back in the 1...64 notation, excluding those that fall off the central board. The TIO example displays the result using an 8x8 matrix.

---
Tags: code-golf, chess, board-game
---


# Question
Title: Output the simplified Goodstein sequence
A number is in base-b simplified Goodstein form if it is written as

```
b + b + ... + b + c,   0 < c ≤ b

```

The simplified Goodstein sequence of a number starts with writing the number in base-1 simplified Goodstein form, then replacing all 1's with 2's and subtracting 1. Rewrite the result in base-2 simplified Goodstein form, then replace all 2's with 3's and subtract 1, etc. until you reach 0.

Your program is to take a positive integer input and output/print its Goodstein sequence and terminate. Your program should handle numbers less than 100, though it may not terminate in a reasonable amount of time.

For example, given 3 as the input, your program should output (the right side is just explanation)

```
1 + 1 + 1                | 3 = 1 + 1 + 1
2 + 2 + 1                | Change 1's to 2's, then subtract 1. (2 + 2 + 2 - 1 = 2 + 2 + 1)
3 + 3                    | 3 + 3 + 1 - 1 = 3 + 3
4 + 3                    | 4 + 4 - 1 = 4 + 3
5 + 2                    | 5 + 3 - 1 = 5 + 2
6 + 1                    | 6 + 2 - 1 = 6 + 1
7                        | 7 + 1 - 1 = 7
7                        | 8 - 1 = 7
6                        | Numbers are now lower than the base, so just keep subtracting 1.
5                        |
4                        |
3                        |
2                        |
1                        |
0                        | End

```

Spacing doesn't matter.

---

## Winning criterion:

This is . Shortest code wins.

# Answer
> 2 votes
# 05AB1E, 19 bytes

```
Å1[D'+ý,N>D>:`Ž<)0K

```

Could also be rearranged as `>Å1[ND>:`Ž<)0KD'+ý,`

Try it online!

**Explanation**

```
Å1                    # push a list of 1's the length of the input
  [                   # start a loop
   D                  # duplicate the current list
    '+ý,              # join on "+" and print
        N>D>:         # replace <current_iteration>+1 with <current_iteration>+2
             `        # flatten the list to the stack
              Ž       # break loop if the stack is empty
               <      # decrement the top number
                )     # wrap the stack in a list
                 0K   # remove zeroes

```

# Answer
> 10 votes
# Python 2, 77 74 bytes

-3 bytes thanks to Lynn

```
n=input();b=1
while n:print"+".join(n/b*[`b`]+[`n%b`][:n%b]);n+=n/b-1;b+=1

```

Try it online!

Easily runs up to n = 100 (though the output is too long for tio fully show).

# Answer
> 3 votes
# Pyth, 29 bytes

```
WQ=hZj\++*]Z/QZ<]J%QZJ=+Qt/QZ

```

**Try it here!**

# Answer
> 2 votes
# Mathematica, 123 bytes

```
(s=1~Table~#;i=1;While[s!={},Print@StringRiffle[ToString/@s,"+"];s=s/.i->i+1;s=Join[Most@s,{Last@s}-1]~DeleteCases~0;i++])&

```

Try it online!

# Answer
> 1 votes
# Python 3, 155 bytes

```
n=int(input());l=[1]*(n+1);i=0
while l:
    l=[t+1 if t==i else t for t in l];l[-1]-=1;l=l[:-1] if l[-1]==0 else l;print("+".join(list(map(str,l))));i+=1

```

This can be reformatted into

```
n = int(input())
l = [0]*(n+1)
i = 0
while l:
    l = [t+1 if t==i else t for t in l]
    if l[-1] == 0:
        l = l[:-1]
    print("+".join(list(map(str,l))))
    i += 1

```

# Answer
> 1 votes
# Javascript ES6, 121 chars

```
for(q=1,s=Array(+prompt()).fill(1).join`+`;s!=0;s=s.split(q).join(++q).replace(/\d+$/,x=>x-1).replace(/\+0$/,''))alert(s)

```

```
alert=s=>document.write(s+'\n')
document.write("<pre>")

for(q=1,s=Array(+prompt()).fill(1).join`+`;s!=0;s=s.split(q).join(++q).replace(/\d+$/,x=>x-1).replace(/\+0$/,''))alert(s)
```

# Answer
> 1 votes
# Perl 5, 71 bytes

```
$,='+';for(@a=(++$")x<>;@a;--$a[-1]||pop@a){say@a;$_+=$_==$"for@a;$"++}

```

Try it online!

---
Tags: code-golf, math, sequence
---


title: Triangular Numbers

text:
# Question
Title: Triangular Numbers
*(no, not those ones)*

## The Challenge

You'll be given two inputs. The first is a positive integer `n > 0`, which is used to output an `n x n` right triangle of the numbers `1, 2, 3, ... n`. This triangle starts in a corner and increases horizontally and vertically by one and diagonally by two. See examples below for clarification. Keep one space between columns and keep all numbers right-aligned in their particular columns. (This is after all).

The second input, `x`, is one of four distinct single ASCII characters of your choice that determines the triangle's starting corner (and hence orientation). For example, you could use `1,2,3,4` or `a,b,c,d` or `#,*,!,)`, etc. Please specify in your answer how the orientation works.

For clarification in this challenge, I will use `1,2,3,4` which will correspond to `1` for the upper-left, `2` for the upper-right, and so on clockwise.

## The Examples

For example, for `n = 5`, `x = 1` output the following:

```
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5

```

For input `n = 11`, `x = 1` output the following (note the extra spaces so the single digits are right-aligned):

```
 1  2  3  4  5  6  7  8  9 10 11
 2  3  4  5  6  7  8  9 10 11
 3  4  5  6  7  8  9 10 11
 4  5  6  7  8  9 10 11
 5  6  7  8  9 10 11
 6  7  8  9 10 11
 7  8  9 10 11
 8  9 10 11
 9 10 11
10 11
11

```

With input `n=6` and `x=2` output:

```
6 5 4 3 2 1
  6 5 4 3 2
    6 5 4 3
      6 5 4
        6 5
          6

```

With input `n = 3` and `x = 4`, output:

```
3
2 3
1 2 3

```

With input `n = 1` and any `x`, output:

```
1

```

## The Rules

* Leading/trailing newlines or other whitespace are optional, provided that the numbers line up appropriately. (For example, trailing whitespace to make a square output is acceptable).
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Output can be to the console, saved as an image, returned as a list of strings, etc. Any convenient and allowed format.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
> 3 votes
# Jelly, 13 bytes

```
Rṫ`z⁶ṚH}¡U⁹¡G

```

Try it online!

Left argument: `n`
Right argument: `x` (`0` = top-left, `1` = top-right, `2` = bottom-left, `3` = bottom-right)

# Answer
> 2 votes
# APL (Dyalog), 29 bytes

```
{' '@(=∘0)⌽∘⍉⍣⍺⊢↑⌽(⍳+⍵-⊢)¨⍳⍵}

```

Try it online!

**How?**

`¨⍳⍵` \- for each `i` in range of `n`

`(⍳+⍵-⊢)` \- produce range of `i` with vectorized addition of `n - i`

`↑⌽` \- reverse and flatten

`⌽∘⍉` \- rotate right

`⍣⍺⊢` \- `x` times

`' '@(=∘0)` \- remove zeros

# Answer
> 1 votes
# MATL, 18 bytes

```
:&YhiX!VZ{' 0'2:YX

```

First input is `n`. Second input is `x`, which can be:

* `0`: top left
* `1`: bottom left
* `2`: bottom right
* `3`: top right

(Or it can be any other integer, which is interpreted modulo 4).

Try it at **MATL Online!**

# Answer
> 1 votes
# JavaScript 130 128 154 142 138 135 133 bytes

\*fixed padding issues

```
A=(n,x)=>(j=>{for(;n--;s=x<3?S+`
`+s:s+S+`
`)
for(S=O,i=j;i;S=i-->n^~-x%3?X+S:S+X)
X=(i>n?i+O:O).padStart(j.length+1)})(n+=s=O="")||s

console.log(A(6,1))
console.log(A(6,2))
console.log(A(6,3))
console.log(A(6,4))

console.log(A(12,1))
console.log(A(12,2))
console.log(A(12,3))
console.log(A(12,4))

/* 154 solution
A=(n,x)=>{s=""
for(j=n;n--;s=x<3?S+`
`+s:s+S+`
`)
for(S="",i=j;i;S=i-->n?~-x%3?S+X:X+S:~-x%3?X+S:S+X)
X=(i>n?i+"":"").padStart((j+"").length+1)
return s
}

142 solution
A=(n,x)=>{s=""
for(j=n;n--;s=x<3?S+`
`+s:s+S+`
`)
for(S="",i=j;i;S=i-->n ^ ~-x%3?X+S:S+X)
X=(i>n?i+"":"").padStart((j+"").length+1)
return s
}

138 solution
A=(n,x)=>{s=""
for(j=n+" ";n--;s=x<3?S+`
`+s:s+S+`
`)
for(S="",i=+j;i;S=i-->n^~-x%3?X+S:S+X)
X=(i>n?i+"":"").padStart(j.length)
return s
}

135 solution
A=(n,x)=>{for(j=n+=s=O="";n--;s=x<3?S+`
`+s:s+S+`
`)
for(S=O,i=j;i;S=i-->n^~-x%3?X+S:S+X)
X=(i>n?i+O:O).padStart(j.length+1)
return s
}
*/
```

# Answer
> 0 votes
# Python 2, ~~124~~ 120 bytes

```
n,x=input()
r=range(n)
for l in zip(*[(r+[n]+['']*i)[-n:]for i in r][::1-x%4/2*2])[::1-x/3*2]:print' %%%ds'%len(`n`)*n%l

```

Try it online! or Try all test cases

`(r+[n]+['']*i)[-n:]` will add some empty strings to the number list, and chop to the right size, `zip` with `[::1-x%4/2*2]` and `[::1-x/3*2]` will make the rotation, and `%%%ds'%len(`n`)*n` will generate a string for fomating (like `' %3s %3s %3s'...`) to be used on each numbers+empty string list

# Answer
> 0 votes
# Mathematica, 89 bytes

```
(R=Reverse;Grid[{#&,R/@#&,R[R/@#]&,R@#&}[[#2]]@PadRight@Array[Range[#,s]&,s=#]/. 0->""])&

```

here is another solution that works in TIO

# Mathematica, 122 bytes

```
(R=Reverse;StringRiffle[""<>ToString/@#&/@({#&,R/@#&,R[R/@#]&,R@#&}[[#2]]@PadRight@Array[#~Range~s&,s=#]/. 0->" "),"\n"])&

```

Try it online!

# Answer
> 0 votes
# Charcoal, 39 bytes

```
Ｎτ≔ＥτＥτ◧×‹⁺ιλτＩ⊕⁺ιλＬθσＦＮ≔⮌ＥσＥσ§μλσＥσ⪫ι

```

Try it online! Note: Trailing space. Link is to verbose version of code. Second value is number of *anticlockwise* rotations so 0 is upper left, 1 lower left, 2 lower right, 3 upper right. Explanation:

```
Ｎτ                                      Assign the first input as an integer
   ＥτＥτ                                 Map in two dimensions
               ⊕⁺ιλ                     Sum of zero-indexed coordinates plus 1
              Ｉ                         Cast to string
         ‹⁺ιλτ                          Is this the upper left triangle?
        ×                               Repeat the string once if so
       ◧           Ｌθ                   Pad to length of first input
  ≔                  σ                  Assign to variable
                          ＥσＥσ§μλ       Transpose the array
                         ⮌              Reflect the array, giving a rotation
                        ≔        σ      Reassign to variable
                       Ｎ                Second input as an integer
                      Ｆ                 Repeat that many times
                                  Ｅσ    Map over array
                                    ⪫ι  Join with spaces and implicitly print

```

# Answer
> 0 votes
---

## Javascript (ES6), ~~241~~ ~~222~~ 214 bytes

```
let f =

    (n,x)=>(L=x=>(''+x).length,M=b=>x&b?(c,i,a)=>a[n-1-i]:c=>c,Array(n).fill(b=' ').map((c,i)=>b.repeat(L(n)-L(++i))+i).map((c,i,a)=>a.map((v,j)=>j>i?b.repeat(L(n)):v)).map(M(1)).map(c=>c.map(M(2))).map(c=>c.join(b)))

function printTriangle() {  // display array of strings returned by f
    o.innerText = f(
       +Length.value, // number
       Rotate.value[0] // ASCII char
    ).join('\n');
}
```

```
Length: <input type="text" value="11" id="Length"><br>
Rotate: <input type="text" value="0" id="Rotate"> 0,1,2,3<br>
<button type="button" onclick="printTriangle()">
  OK
</button>
<br>
<pre id="o"></pre>
```

### Less Golfed

```
(n,x)=>(
    L= x=> (''+x).length,                // strlen(x)
    M= b=> x&b ? (c,i,a)=>a[n-1-i] : c=>c, // reverse or identity map
    Array(n).fill(b=' ')
   .map((c,i)=>b.repeat(L(n)-L(++i))+i)  // a complete line of numbers
   .map((c,i,a)=>a.map((v,j)=>j>i?b.repeat(L(n)):v)) // to 2-d array
                                         // with spaces for blank numbers
   .map(M(1))                            // flip vertically?
   .map(c=>c.map(M(2)))                  // flip horizontally?
   .map(c=>c.join(b))                    // convert lines to strings
)

```

### Note on orientation.

The second parameter is a character from {'0', '1', '2', '3'} and automatically type converted to a number by the `&` operator. If bit 0 (lsb) of the number is set, lines are flipped vertically. If bit 1 (nlsb) is set, columns are flipped horizontally. Other decimal digit characters can be used with predictable results.

### Trailing Spaces

Blank entries in the output string have been replaced with spaces, which means lines have trailing spaces in orientations '0' and '1'.

# Answer
> 0 votes
# Lua, 250 bytes

```
function f(w,m)d=""for y=1,w do for x=1,w do d=string.format("%s%"..tostring(w):len().."s ",d,m<2 and(y+x-1<=w and x+y-1 or"")or(m<3 and(x>=y and w-x+y or"")or(m<4 and(y+x-1>=w and w+w-x-y+1 or"")or(y>=x and w-y+x or""))))end;d=d.."\n"end;print(d)end

```

Takes parameters \[w\]idth and \[m\]ode using 1,2,3,4 for modes as described in the example.

# Answer
> 0 votes
# 05AB1E (61 bytes)

```
F¹N-LN+¹N-LN+Rõ¸N∍s«N>LN¹<--N>LN¹<--Rõ¸¹<N-∍s«)²èvy¹gyg-ú}ðý,

```

Try it online

---
Tags: code-golf, ascii-art, number
---


title: Invert a Quine!

text:
# Question
Title: Invert a Quine!
We all know what a quine is. An *inverted* quine is a non-empty program that prints the inverse of its source code without reading its source code, and consists solely of printable-ASCII characters (space through `~`).

Here, “inverse of the source code” means the following: the output of your program must contain each printable ASCII character **(m − c)** times, where **c** is the number of times said character occurs in your code, and **m** is the maximum number of times any character is repeated in your code.

(In other words: **your code** \+ **your output** = permutation of **m** times all of printable-ASCII.)

For example, if your program is `12345`, then **m = 1**, and you should output any permutation of this string:

```
 !"#$%&'()*+,-./06789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

```

If your program is `AAB`, then **m = 2**, and you should output any permutation of:

```
  !!""##$$%%&&''(())**++,,--..//00112233445566778899::;;<<==>>??@@BCCDDEEFFGHHIIJJKKLLMMNNOOPPQQRRSSTTUUVVWWXXYYZZ[[\\]]^^__``aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~

```

Note how there are two missing `A`s, and one missing `B`.

Although a program that contains all the printable ASCII characters and outputs nothing is a valid inverse quine (satisfying **m = 1**), such an answer would not be very competitive, given its length.

You are to write a program that is an inverted quine, as described in the above paragraph. As this is , the shortest program in bytes will win. Good luck!

# Answer
> 7 votes
# Brain-Flak, ~~221~~ 207 bytes

Includes +1 for `-A`

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

```

Try it online!

```
# Push 206 (the number of times to duplicate the output)
(((((((()()()()){}){}()){}){})()){}{})

# For 0 to 206
{({}[()]<

    # Push 32 on this stack and 18, 28 and 29 to the other
    # 18, 28 and 29 are the distances between the sets of braces
    ((((((()()()()){}){}){})<>[()()()])[()])((((()()()){})){}{})<>

    # For 0 to 8
    ((()()()()){}){({}[()]<

        # Push TOS, TOS + 1
        (({})())

    # end For 0 to 8
    >)}{}

    # Push TOS + 2
    # skips '(' and ')'
    ({}()())

    # For each value on the off stack (18, 28, 28)
    <>{

        # For 0 to that number
        {({}<>[()]<

            # Push TOS, TOS + 1
            (({})())

        # End for 0 to that number
        ><>)}{}

        # Push TOS + 1, TOS + 3 (skips this set of braces)
        <>(({}())()())<>

    # End for each value on the off stack (18, 28, 28)
    }<>

 # End for 0 to 206
 >)}{}

```

# Answer
> 6 votes
## CJam, 17 bytes

```
{s95c+'|,32>\-}_~

```

Try it online!

Prints

```
 !"#$%&()*./014678:;<=?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^`abdefghijklmnopqrtuvwxyz

```

### Explanation

The goal was to modify the standard quine

```
{"_~"}_~

```

such that no character is repeated in the program. The reason for this is that CJam has a set different operator which we can use to remove characters from the printable ASCII range, but it doesn't take number of occurrences into account. Implementing that by hand would probably be longer, so I needed to make sure that every character appears only once and we don't have to worry about occurrences.

```
{      e# Quine framework. Executes the block while leaving another copy of the
       e# block on the stack.
  s    e#   Stringify the block, giving us "{s95c+'|,32>\-}".
  95c  e#   Convert 95 to a character, which gives us '_' without repeating
       e#   it in the source code.
  +    e#   Append it to the string. We don't need to worry about '~', we'll just
       e#   leave it out of the printable ASCII range to begin with.
  '|,  e#   Get a character range from the null byte up to '{'. This omits "|}~",
       e#   but those are in the program anyway, it doesn't matter.
  32>  e#   Discard the unprintable characters.
  \-   e#   Subtract the source string from the printable ASCII range.
}_~

```

# Answer
> 3 votes
# Python 3, 83 bytes

```
print(~2/8,6>9)#!"$%&'*+14:;<=?@ABCDEGHIJKLMNOPQRSTUVWXYZ[\]^_`bcdfghjkmoquvwxyz{|}

```

Try it online!

Prints `-0.375 False`.

# Answer
> 2 votes
# 05AB1E, ~~95~~ ~~61~~ 60 bytes (not 58 b/c I dislike that one)

```
A?9L<J, !"'#$%&()*+-./:;=>@BCDEFGHIKMNOPQRSTUVWXYZ[\]^_`{|}~

```

Try it online!

Old answer invalidated by "only-ASCII characters", a lot of commands aren't valid here.

It prints `abcdefghijklmnopqrstuvwxyz012345678` one time as there are no duplicated characters.

---

# Version with `BCDEFGHIKMNOPQRSTUVWXYZ` removed:

*Work in progress... I think ~60 bytes is as low as you get without non-ASCII characters in 05AB1E..*

# 05AB1E, 58 bytes

```
T5+FA'uK?Au"ADLJFKST"SK?9L<5KJ?} !#$%&()*>-./:;=@[]^_`{|~\

```

Try it online!

Prints the output x12 due to the repeated characters:

```
['""', '55', '???', 'AAA', 'FF', 'JJ', 'KKKK', 'LL', 'SS', 'TT', 'uu']

```

It also doesn't terminate quite correctly, working on that now...

---

Invalid old answers (due to non-ASCII characters) have been removed, see edit history.

# Answer
> 0 votes
# Java 8, ~~106~~ ~~99~~ 190 bytes

```
class i {/*{}!"#$%&'()+,-.0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`bdefghjkmnopqrtuvwxyz|~!"#$%&'()+,-.0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`claibdefghjkmnopqrtuvwxyz|~*/}

```

# Answer
> 0 votes
# Javascript (ES6), ~~103~~ 101 bytes

```
_=>` !"#$%&'()*+,-.0123456789:;<?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^abcdefghijklmnopqrstuvwxyz{|}~`//_=>\\

```

**Old solution (103 bytes using `alert`)**

```
alert;;alert`\ \!"#$%&'()*+,-./0123456789:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_bcdfghijkmnopqsuvwxyz{|}~`

```

**Old (invalid) solution (96 bytes)**

```
alert()// !"#$%&'*+,-.0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`bcdfghijkmnopqsuvwxyz{|}~

```

---
Tags: code-golf, restricted-source, quine
---