title: Print a cube net of the specified size

text:
# Question
Title: Print a cube net of the specified size
## Challenge

Given a size s, print a cube net of that size made of hash symbols (`#`) and spaces ().

Examples:

```
1:
  #
# # #
  #
  #

2:
    # #
    # #
# # # # # #
# # # # # #
    # #
    # #
    # #
    # #

3:
      # # #
      # # #
      # # #
# # # # # # # # #
# # # # # # # # #
# # # # # # # # #
      # # #
      # # #
      # # #
      # # #
      # # #
      # # #

```

The net can actually be any valid cube net that can fold into a cube, for example these:

```
    # #
    # #
# # # # # # # #
# # # # # # # #
    # #
    # #

    # # # #
    # # # #
    # #
    # #
    # #
    # #
# # # #
# # # #

```

## Rules

* The resulting net must be geometrically valid (foldable into a cube)
* Standard loopholes forbidden
* Read the rules carefully
* This is , shortest answer wins, but will not be selected

# Answer
> 24 votes
## Python 2, 47 bytes

```
n=input()
for c in 1,4,1:exec"print'# '*c*n;"*n

```

Try it online!

Prints this net, chosen for being left-justified:

```
# #
# #
# # # # # # # #
# # # # # # # #
# #
# #

```

The lines have `n` or `4*n` copies of `'# '`. For each of `1,4,1`, we print `n` times that many copies, done `n` times for `n` lines. Having an `exec` loop inside a `for` loop seems wasteful, but I didn't see better.

Alternatives I tested:

```
lambda n:('# '*n*3+'\n')*n+('  '*n+'# '*n+'\n')*3*n

lambda n:('# '*n*3+'\n')*n+(' '*4*n+'# '*n*3+'\n')*n

def f(n):
 for c in[3]*n+[1]*3*n:print('# '*c*n).center(6*n)

def f(n):
 for c in[4]*n+[0]*n:print' '*c*n+'# '*n*3

def f(n):
 for c in[1]*n+[4]*n+[1]*n:print'# '*c*n

def f(n):
 c=1;exec("print'# '*c*n;"*n+"c^=5;"*n)*3

def f(n):
 for i in range(3*n):print'# '*[1,4,1][i/n]*n

def f(n):
 for c in 1,4,1:print('# '*c*n+'\n')*n,

def f(n):
 for c in 1,4,1:exec"print'# '*c*n;"*n

```

(The `def` functions can all be one shorter as a program.)

# Answer
> 8 votes
# Octave, ~~58~~ ~~44~~ ~~42~~ 32 bytes

```
@(n)[z=repmat('# ',n);z,z,z,z;z]

```

partly inspired by @xnor 's python answer.

```
z=repmat('# ',n);

```

creates a squre pattern of '# ' for input 2 results the following pattern:

```
# #
# #

y=[z,z,z,z];

```

four `z` s are concatenated horizontally:

```
# # # # # # # #
# # # # # # # #

[z;y;z]

```

`z` and `y` and `z` are concatenated vertically

Try It Online!

```
# #
# #
# # # # # # # #
# # # # # # # #
# #
# #

```

Previous answer:

```
@(n){h(1:n,1:2:n*6)=1;h(1:n*4,n*2+1:2:4*n)=1;' #'(h+1)}{3}

```

Try It Online!

Generates a T shaped one

```
# # # # # # # # #
# # # # # # # # #
# # # # # # # # #
      # # #
      # # #
      # # #
      # # #
      # # #
      # # #
      # # #
      # # #
      # # #

```

# Answer
> 6 votes
# Mathematica, ~~77~~ ~~60~~ 52 bytes

*Thanks to Martin Ender for golfing 8 bytes away!*

```
{±s_:=s~Table~#;b=±{a=±"# ","
"},±{a,a,a,a,"
"}}<>b&

```

Unnamed function taking a positive integer argument `#` and returning a string with newlines (including a trailing newline); each line has a trailing space as well. First we define `±` to be a function that repeats its input `#` times; then `a` is defined as `±"# "` (this `#` is a character, not the input!), and from that `b` is defined to be the set of `#` short lines, while `±{a,a,a,a}<>n` is the set of `#` long lines. (In both cases, there is a literal linefeed between matching quotes.) The final `<>b` concatenates the resulting list of strings with second copy of the set of short lines. Example output when `#=2` (xnor's answer taught me that this orientation is golfier):

```
# #
# #
# # # # # # # #
# # # # # # # #
# #
# #

```

Previous version of this implementation:

```
""<>(±s_:=s&~Array~#;{b=±{a=±"# ",n="\n"},±{a,a,a,a}<>n,b})&

```

Original submission:

```
""<>If[(m=n~Mod~t)==0,"\n",If[n<t#||#<m<=2#,"# ","  "]]~Table~{n,4(t=3#+1)#}&

```

Builds a string out of `4*(3#+1)` pieces, each of which is either `"# "`, `" "`, or `"\n"`; simply calculates which pieces to use based on the index `n`. Example output when `#=2`:

```
# # # # # #
# # # # # #
    # #
    # #
    # #
    # #
    # #
    # #

```

# Answer
> 5 votes
## JavaScript (ES6), 59 bytes

```
f=
n=>`141`.replace(/./g,m=>`${`# `.repeat(n*m)}\n`.repeat(n))
```

```
<input type=number oninput=o.textContent=f(this.value)><pre id=o>
```

Output includes a trailing space at the end of each line and a trailing newline.

# Answer
> 5 votes
# Ruby, 36 bytes

```
f=->n{puts (t=[s="# "*n]*n)+[s*4]*n+t}

```

Usage:

```
f=->n{puts (t=[s="# "*n]*n)+[s*4]*n+t}
f[3]
# # #
# # #
# # #
# # # # # # # # # # # #
# # # # # # # # # # # #
# # # # # # # # # # # #
# # #
# # #
# # #

```

# Ruby, 38 bytes

This shape is longer in Ruby but I expect there are some languages where it is shorter.

```
->n{puts [s="# "*n*3]*n+[" "*n*4+s]*n}

```

Usage:

```
g=->n{puts [s="# "*n*3]*n+[" "*n*4+s]*n}
g[3]
# # # # # # # # #
# # # # # # # # #
# # # # # # # # #
            # # # # # # # # #
            # # # # # # # # #
            # # # # # # # # #

```

Both answers can be shorter if it is permitted to return (preferably) an array of strings or (less preferably) a single string instead of printing.

# Answer
> 4 votes
# JavaScript (ES6), 71

```
n=>((z='# '[R='repeat'](n))[R](3)+`
`)[R](n)+('  '[R](n)+z+`
`)[R](n*3)

```

**Test**

```
f=
n=>((z='# '[R='repeat'](n))[R](3)+`
`)[R](n)+('  '[R](n)+z+`
`)[R](n*3)

function update() {
  O.textContent=f(I.value)
}

update()
```

```
<input id=I type=number value=3 oninput='update()'><pre id=O></pre>
```

# Answer
> 4 votes
# , ~~24~~ ~~23~~ ~~20~~ ~~18~~ 20 bytes

```
Ài# ddÀpLyGïp3PGïp

```

With all the hidden characters shown

```
Ài# ^[ddÀp^VLyGïp3PGoïp

```

`^[` is `0x1b` (escape character literal) and `^V` is `0x16` (`C-v`)

Try it online!

I had to increase bytecount because the `Ä` command was being buggy in this new V pull

Outputs in this format:

```
#
# # # #
#

```

with a leading newline

Hexdump:

```
00000000: c069 2320 1b64 64c0 7016 4c79 47ef 7033  .i# .dd.p.LyG.p3
00000010: 5047 ef70                                PG.p

```

## Explanation

```
Ài# ^[              " Argument times insert "# "
ddÀp                " Argument times duplicate line

```

Now that one face of the net has been completed, we have to create the net

```
^VLy                " Copy the face
Gïp                 " Paste it at the end of buffer
3P                  " Paste 3 times (these form the line)
Gïp                 " Paste at end of buffer again

```

---

Alternate solution if we don't output the spaces:

### ~~21~~ ~~20~~ ~~18~~ ~~16~~ 18 bytes

```
Àé#ddÀpLyGïp3pGïp

```

(for the same reason as the top solution, this TIO link is modified)

Try it online!

# Answer
> 4 votes
# Jelly, ~~20~~ 19 bytes

```
”#xẋ³Wẋ³K€Y
141DÇ€Y

```

Try it online!

*-1 thanks to 44874 (steenbergh).*

I CAN'T OUTGOLF MUDDYFISH HELP!

Is this golfable??? ~~20~~ 19 bytes just seems like **too much**, seeing Link 1.

Explanation:

```
”#xẋ³Wẋ³K€Y Helper link. Arguments: z
”#          Character #.
            y (implicit)
  x         Repeat each element of y x times.
    ³       1st command-line argument.
   ẋ        Repeat x y times.
     W      Wrap z.
       ³    1st command-line argument.
      ẋ     Repeat x y times.
        K   Join z on spaces.
         €  Map this link on x.
          Y Join z on newlines.

141DÇ€Y Main link. Arguments: 0
141     Integer 141.
   D    Convert z to base 10.
    Ç   The above link as a monad.
     €  Map this link on x.
      Y Join z on newlines.

```

# Answer
> 4 votes
# Scala, 56 bytes

```
(n:Int)=>Seq(1,4,1)map("# "*_*n+"\n")map(_*n)mkString ""

```

# Answer
> 4 votes
# Java 8, 99 bytes

```
l->{for(int i=-1,j;++i<3*l;)for(j=-1,k=(i/l==2)?4*l:l;++j<k;)System.out.print("# "+j>k-2?"\n":"");}

```

# Answer
> 4 votes
# , 14 bytes (non-competing)

```
Ài# 5Ù4JjòÀÄk

```

Try it online!

```
00000000: c069 2320 1b35 d934 4a6a f2c0 c46b       .i# .5.4Jj...k

```

For whatever reason, this challenge uncovered numerous bugs. Now that they're all fixed, this version is unfortunately non-competing, but it's nice to see what a V answer to this challenge should look like when it doesn't have to add tons of bytes to keep up with my sloppy coding.

Explanation:

```
À                   " Arg 1 times:
 i# <esc>           "   Insert the string "# "
         5Ù         " Make 5 copies of this line, and put the cursor on the second copy
           4J       " Join four of these lines together
             j      " Move down to the last line
              ò     " Recursively:
               ÀÄ   "   Make Arg 1 copies of this line
                 k  "   And move up a line

```

# Answer
> 3 votes
# Charcoal, 20 bytes

```
ＮλＧ↑λ←×⁶λ↓λ# ＤＭ×⁴λ←

```

The code ends with a space. Try it online!

### Explanation

Charcoal is a language specializing in ASCII art. It is also incomplete, buggy, and under-documented. Suffice it to say, this took a fair amount of trial and error before it did what it was supposed to.

* `Ｎλ` inputs a number into `λ`.
* is the polygon command, which we'll use here to draw a rectangle. `↑λ←×⁶λ↓λ` specifies the border of the polygon: upward `λ` steps, leftward 6 times `λ` steps, and downward `λ` steps. (That's three `λ` by `λ` blocks side-by-side.) The bottom edge of the rectangle is inferred. The polygon is then filled with the string `#` .
* dumps the current canvas to stdout, resulting in something like this:

```
 # # # # # # # # #
 # # # # # # # # #
 # # # # # # # # #

```
* After the  command, the cursor is at the bottom left corner of the canvas. `Ｍ×⁴λ←` moves it leftward by 4 times `λ` steps (equivalent to two `λ` by `λ` blocks).
* outputs a space there, extending the canvas leftward by the correct amount.
* At the end of the program, the canvas is (again) sent to stdout:

```
             # # # # # # # # #
             # # # # # # # # #
             # # # # # # # # #

```

Put 'em together and you've got a cube net.

# Answer
> 2 votes
# Python 2, ~~68~~ ~~71~~ 65 bytes

-6 with thanks to @sagiksp

```
def f(i,c=1):
 print(' '*i*4,'')[c>i]+'# '*i*3
 if i*2>c:f(i,c+1)

```

Try it online!

In the absence of finding a way to beat @xnor I'll post my recursive function simply as an alternative approach. For f(5) prints

```
                    # # # # # # # # # # # # # # #
                    # # # # # # # # # # # # # # #
                    # # # # # # # # # # # # # # #
                    # # # # # # # # # # # # # # #
                    # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # #
# # # # # # # # # # # # # # #
# # # # # # # # # # # # # # #
# # # # # # # # # # # # # # #
# # # # # # # # # # # # # # #

```

This pattern was chosen simply because it can be split into two parts unlike all of the others.

# Answer
> 2 votes
# Bash / Unix utilities, ~~72~~ ~~69~~ ~~68~~ 66 bytes

```
b()(yes `dc<<<2o4d$n^$1^3/p`|tr 01 ' #'|head -$n);n=$1;b 1;b 4;b 1

```

Try it online!

This works by using the fact that \[4^k / 3\], when written in base 2, is 10101010...01, with k 1's. (The square brackets here denote the floor function.)

# Answer
> 2 votes
# Pyke, 16 bytes

```
uAD,sXF**"#

```

Try it here!

Equivalent to

```
1 4 1]3AD,sXF**"#

```

Because of unprintables

This uses a couple of tricks to lower the byte-count:

* It uses some unprintables to represent the list `[1, 4, 1]`
* `XF` automatically dumps the output to the stack
* The string `"#`  at the end gets swapped with the last `*`, meaning that the closing `"` is not required. This happens implicitly when the last token is a string.

```
u                -      [1, 4, 1]
     AD          -     apply(*, ^, input)
       ,         -    zip(^)
        s        -   sum(^)
          F**"#  -  for i in ^:
           *     -    ^ * input
            *    -   ^ * v
             "#  -    "# "
         X       - splat(^)

```

# Answer
> 2 votes
## PHP, 64 62 bytes

Saved 2 bytes thanks to Christoph.

```
while($a="282"[$i++/$s=$argv[1]]*$s)echo str_pad("
",$a,"# ");

```

Prints a net like this:

```
# #
# #
# # # # # # # #
# # # # # # # #
# #
# #

```

(with a leading newline)

# Answer
> 1 votes
## Batch, 111 bytes

```
@set s=
@set i=@for /l %%i in (1,1,%1)do @
%i%call set s=%%s%% #
%i%echo%s%
%i%echo%s%%s%%s%%s%
%i%echo%s%

```

# Answer
> 1 votes
## QBIC, ~~52~~ ~~67~~ 40 bytes

Complete re-write:

```
:[a*3|G=G+@#`][a*2|G=G+@ `][a|?G][a|?_fG

```

This now uses this pattern:

```
###--
--###

```

Where the `-`are filled with spaces.

```
:        Read 'a' from the command line        > Assume 3
[a*3|    Create 3 segments times 'a' filling   > 3*3 = 9
G=G+@#`] Define A$ to be '#' and add this to G > G = "#########"
[a*2|    Create 2 segments times 'a' spacer
G=G+@ `] Define B$ to be ' ' and add this to G > G = "#########       "
[a|      FOR d == 1; d <= a; d++
?G]      Display G$:
            "#########       "
            "#########       "
            "#########       "
[a|      FOR e == 1; e <= a; e++
?_fG     Display G$ in reverse (_f...|):
            "      #########"
            "      #########"
            "      #########"
         (For loop and function call to Flip impicitly closed by QBIC)

```

# Answer
> 1 votes
# Pushy, ~~32~~ ~~29~~ 28 bytes

Prints the cube net left-justified. This was hard to golf...

```
&V:`# `;{:";N^:4:";T'.;TD^:"

```

**Try it online!**

# Answer
> 1 votes
# Retina, 39 37 bytes

This is my first time using Retina, I'm still trying to understand how to do things.

```
.+
$*#
#
#
\`#
$_¶
G`.
)*%`^
$_$_$_

```

(with two trailing spaces after the 4th and 5th lines)

Thanks to Martin Ender for golfing 2 bytes!

Try it online!

# Answer
> 1 votes
# Pip, ~~28~~ ~~17~~ 16 bytes

15 bytes of code, +1 for `-n` flag.

```
"# "Xa*_RLaM141

```

Takes the size as a command-line argument. Try it online!

### Explanation

```
                 a is 1st cmdline arg
       _         Build a lambda function
     a*          (a) times argument
"# "X            Repeat string "# " that many times
        RLa      Wrap in a list and repeat list (a) times
           M141  Map that function to the characters of 141
                 Autoprint (-n flag separating list items with newlines)

```

The following isn't exactly how the data gets modified, but it gives the basic idea (for `a=2`):

```
141

[1;4;1]

[2;8;2]

["# # ";"# # # # # # # # ";"# # "]

[["# # ";"# # "];["# # # # # # # # ";"# # # # # # # # "];["# # ";"# # "]]

# #
# #
# # # # # # # #
# # # # # # # #
# #
# #

```

# Answer
> 0 votes
# 05AB1E, 13 bytes

```
D141S×S*„# ×»

```

Try it online!

**Explanation**

Example input `n=2`

```
D              # duplicate input
               # STACK: 2, 2
 141S          # push the list [1,4,1]
               # STACK: 2, 2, [1,4,1]
     ×         # repeat each item in the list input_no times
               # STACK: 2, [11, 44, 11]
      S        # split into list of digits
               # STACK: 2, [1, 1, 4, 4, 1, 1]
       *       # multiply each digit with input
               # STACK: [2, 2, 8, 8, 2, 2]
        „# ×   # repeat the string "# " for each item in the list
               # STACK: ['# # ','# # ','# # # # # # # # ','# # # # # # # # ','# # ','# # ']
            »  # join by newlines
               # OUTPUT: # #
                         # #
                         # # # # # # # #
                         # # # # # # # #
                         # #
                         # #

```

# Answer
> 0 votes
# SmileBASIC, ~~57~~ 50 bytes

```
INPUT S
E$=("#"*S*3+CHR$(10))*S?E$SCROLL-S*2,-1?E$

```

Explained:

```
INPUT SIZE
PART$=("#"*SIZE*3+CHR$(10))*S 'generate half of the pattern
PRINT PART$ 'print half the pattern
SCROLL SIZE*-2,-1 'scroll the text 2 squares right (and 1 character down)
PRINT PART$ 'print half the pattern again

```

After the first PRINT (size=2, @ is the cursor position):

```
######
######

@

```

After the SCROLL:

```
    ######
    ######
@

```

After the second PRINT:

```
    ######
    ######
######
######
@

```

# Answer
> 0 votes
## C#, 152 bytes

```
n=>{var m="";foreach(int c in new[]{1,4,1})for(int i=0,j;i++<n;){for(j=0;j++<c;)m+=new System.Text.StringBuilder().Insert(0,"# ",n);m+="\n";}return m;};

```

# Answer
> 0 votes
# Common Lisp, ~~83~~ ~~81~~ 79 bytes

```
(lambda(x)(format t"~v@{~v@{# ~}~:*~%~}~v@{~vt~0@*~v{# ~}~%~}"x(* x 3)(* x 2)))

```

Usage:

`(funcall #'(lambda(x)(format t"~v@{~v@{# ~}~:*~%~}~v@{~vt~0@*~v{# ~}~%~}"x(* x 3)(* x 2)))2)`

Output:

```
# # # # # #
# # # # # #
    # #
    # #
    # #
    # #
    # #
    # #

```

### How does it work?

```
in format there is control string (inside "") and arguments after it
certain commands in string can use arguments (for example ~a displays argument)
~v{~} - takes argument and does commends inside {~} number of times
                                      (number is given by argument)
       we can write text in loop body - it'll get displayed. Even if
       in loop body there are none commends to use arguments loop itself
       will consume one argument (it doesn't matter what it'll be -
       it doesn't seem to affect output)
~% - newline
~n* - jump n arguments forward (relative)
~n:* - jump n arguments backwards (relative)
~n@* - jump to argument n (global, counting from 0)

~v@{~v{# ~}~%~1@*~} <--- we make x rowns, 3x columns of string "# ".
                         ~1@* is used during looping, it also means we end on argument 1.
                         (second argument: (* x 3))
~v@{~vt~0@*~v{# ~}~%~} <--- we now make 3x rows, x columns of "(spaces)# "
                         ~vt - is used to move to accurate column.
                         Here it takes argument (* x 2) - this is
                         minimal number of columns to display. It uses
                         space as default character for missing characters
                         (when string inside <~> is shorter than min
                         number of columns). I use it to make (* x 2) spaces,
                         by giving it no text.
      ~0@* <--- after making spaces we have no new arguments, we go back to
                argument number zero - it is used to determine number of columns in our block

```

Ideas for improvement are welcomed.

---
Tags: code-golf, string, ascii-art, kolmogorov-complexity, geometry
---


title: Your Memory's Leaking

text:
# Question
Title: Your Memory's Leaking
Your task is to write a program that:

* Runs indefinitely
* Produces no output
* Consumes an unbounded amount of memory

## Specifications

* You must list the implementation used for your program. This is relevant because some implementations might preform optimizations while others do not. For example, the LISP code `(defun f () (f)) (f)` may or may not consume infinite memory depending on whether the implementation optimizes tail recursion.
* Obviously, your program may terminate from running out of memory.

## Examples

BF:

```
+[>+]

```

Python:

```
l = []
while True:
    l.append(1)

```

JavaScript:

```
l = [];
while (true)
    l.push(1);

```

C (I'm not sure if this works):

```
#include <stdio.h>
int main() {
    while (1)
        malloc(1);
}

```

---

This is , so the shortest valid solution (in bytes) wins.

# Answer
> 1 votes
# Jelly, 2 bytes

```
‘ß

```

Increments and calls itself recursively. As the integer gets bigger, more memory is required to store it.

You can Try it online!, but it's not much to look at.

# Answer
> 0 votes
# Python 3, 16 bytes

```
i=9
while i:i*=9

```

As `int`s in Python3 are only limited by the memory, this will run until there is no more memory available.

# Answer
> 0 votes
## Ruby, 15 bytes

```
i=[];loop{i<<0}

```

# Answer
> 0 votes
# Befunge-98, 1 byte

```
'

```

Fills the stack with strings containing `'`

# Answer
> 0 votes
# Java (OpenJDK 9), 75 bytes

```
interface G{static void main(String[]a){a=new String[1];for(;;)a[0]+=' ';}}

```

Try it online!

# Answer
> 0 votes
# Vim, 13 bytes

```
qqaa<esc>"Ax@qq@q

```

This defines a macro, `q` that appends the letter `a` to the register `A` and then calls itself. This results in an infinite loop of making register `A` bigger and bigger, only limited by memory.

# Answer
> 0 votes
# Brain-Flak, 8 bytes

```
(()){()}

```

Try it online!

# Answer
> 0 votes
# Bash, 17 bytes

```
for((;;)){ a+=a;}

```

Try it online!

---
Tags: code-golf
---


# Question
Title: Convert between Lambda Calculus Notations
The lambda calculus is a system of functional programming. Lambda calculus consists of variables, abstractions, and applications.

A variable is simply a name denoting a function parameter. It is a single letter. An abstraction is a "function literal" of sorts, it consists of a backslash `\` followed by a variable name, and then an expression, which is the function body. For example, the function `\x.x` is a function which takes an argument `x` and returns `x`, a.k.a. the identity function. Abstractions can also return other abstractions. For example, `\x.\y.x` is a function which takes an argument `x` and returns a new function that returns `x`.

There is also application. In application, you remove the header on the first value and substitute all instances of the function's argument with the value it is applied to. For example, to apply `\x.xx` to `\y.y`, substitute all `x`'s with `\y.y`'s, yielding `(\y.y)(\y.y)` (Parenthesis may need to be added for clarification.) Applications are denoted in an expression by writing the two values next to each other, where the first is the function to apply and the second is the argument to apply to. For example, you can write `xy` to apply x to y. However, you may need parenthesis (for example in `a(bcd)` or `y(\x.xx)`.

The first lambda calculus notation is the one I just described.

```
\f.(\x.xx)(\x.f(xx))

```

The second lambda calculus notation does not need parenthesis. It matches the following grammar:

```
<expression> ::= <variable> || <abstraction> || <application>
<abstraction> ::= "\" <variable> <expression>
<application> ::= "`" <expression> <expression>

```

Here, a `<variable>` can be any uppercase or lowercase letter. This is an example of an expression in the second notation:

```
\f`\x`xx\x`f`xx

```

Your task is to write a program that takes a lambda calculus expression in the first notation and outputs it rewritten in the second notation.

## Specifications

* Every variable name is 1 letter.
* Abstractions in the first notation go as far as possible, and application goes left to right: `d(abc) -> `d``abc`.
* You do not have to deal with free/bound variables and scoping.

## Test Cases

```
\a.a                                  -> \aa
(\x.xx)(\x.xx)                        -> `\x`xx\x`xx
\x.\y.\z.xz(yz)                       -> \x\y\z``xz`yz
(\S.\K.SKK)(\x.\y.\z.xz(yz))(\p.\q.p) -> ``\S\K``SKK\x\y\z``xz`yz\p\qp

```

# Answer
> 3 votes
## Haskell, ~~211 197~~ 186 bytes

(Saved 10 bytes by using `interact` as suggested by @Challenger5, and one more by not having a final newline.)

```
m(')':r)=([],r)
m s|(a,u)<-e s,(b,v)<-m u=(a:b,v)
f s|(a,r)<-m s=(tail(a>>"`"):a>>=id,r)
e('\\':v:_:s)|(a,r)<-f s=('\\':v:a,')':r)
e('(':s)=f s
e(v:s)=([v],s)
main=interact$fst.f.(++")")

```

Initially I had a function to perform the whole transformation, but now that is inlined into the `main` function which makes it a complete program. Dealing with a complete program instead of using a function `String -> String` at the interpreter also avoids the need to type and read double backslashes. The other functions follow the (simplified) pure functional parsing pattern of returning a parsing result and the unparsed rest of the string. `f` parses a list of expressions (possibly a multiple application) . It uses a helper function `m` that also parses a list of expressions and has a list of parses as result. `e` handles the remaining cases: lambdas, parenthesized expressions, and variables. Instead of generating a parsing tree, we directly generate the desired output.

Try it online!

Using `interact` ruined clean I/O behaviour. If you don't use the TIO link but run it at the command line of your computer, you have to make sure that there is no trailing whitespace, it would be treated like a variable. You can do something like `echo -n '\f.(\x.xx)\x.f(xx)' | ./prog`. Alternatively, you could replace the last line by the previous version `main=getLine>>=putStrLn.fst.f.(++")")`.

---
Tags: code-golf, string, lambda-calculus
---


title: From Rgb to Cmyk

text:
# Question
Title: From Rgb to Cmyk
Given 3 bytes or RGB as input, calculate the nearest CMYK values, and output them.

* create either a function with parameters and return value or a program that operates on stdin/stdout
* use the color profile of your choice, but provide a reference
* input may be either separate numeric values in range \[0;255\] or a 6 digit hex string
* output should be separate numeric values ranging either \[0;1\] or \[0;100\]
* standard code golf: no loopholes, shortest code wins
* extravagant ideas are welcome

sample data:

```
input             output
108,174,106       [0.3793103448275862, 0.0, 0.3908045977011494, 0.3176470588235294]
0,0,0             0,0,0,1
170,255,238       33,0,7,0
0x0088ff          1,0.4667,0,0
[250,235,215]     [0,6,14,1.96]
#123456           .7907,.3953,0,.6627

```
* Uncalibrated mapping is fine and probably the easiest
* No input validation required; floats are allowed (ranging from 0 to 255), but may also be rounded
* Output format should be either clearly commented or obvious; i.e.:
    1. CMYK in that order
    2. does not matter if percentage \[0;100\] or pure numbers \[0;1\]
* Testing should include the trivial example \[0,0,0\].

This site has the most digits of online tools that I could find. Does anyone know a tool that gives more than 4 digits?

# Answer
# Dyalog APL, ~~16~~ 15 bytes

```
1-⊢(÷,255÷⍨⊢)⌈/

```

1 minus `1-`
***X*** divided by `÷` ***Y***, followed by `,` 255 dividing `255÷⍨` ***Y*** , where
***X*** is itself  (i.e. the list of RGB values), and
***Y*** is the max `/⌈` (of the RGB values).

$$ \begin{cases} J = max(R,G,B)\\ C = 1-\frac{R}{J}\\ M = 1-\frac{G}{J}\\ Y = 1-\frac{B}{J}\\ K = 1-\frac{J}{255}\\ \end{cases} $$

TryAPL!

**Credits:**
∘ -1 byte by ngn.
> 8 votes

# Answer
# C#, ~~88~~ ~~86~~ ~~85~~ 84 bytes

```
(r,g,b)=>{float[]a={r,g,b,1};var j=a.Max();a[3]=j*j/255;return a.Select(x=>1-x/j);};

```

output for `108,174,106`:

```
0.3793104
0
0.3908046
0.3176471

```

Since OP allows function I submitted only the lambda. You can find a running demo on .NetFiddle. I am not a golfer, I post for fun. Also, it is my first answer \o/. Feel free to comment any improvement :)

Kudos to Leaky Nun for the formula.

caveat: it doesn´t work for \[0,0,0\] (thank you Titus)
> 8 votes

# Answer
# Python, 46 bytes

```
lambda*c:[1-i/max(c)for i in c]+[1-max(c)/255]

```

Requires input to be floats in Python 2, fairly sure it doesn't in 3.
> 4 votes

# Answer
## JavaScript (ES6), ~~58~~ 51 bytes

```
a=>[...a.map(e=>1-e/m||1,m=Math.max(...a)),1-m/255]

```

Accepts an array `[R, G, B]` (add 7 bytes for separate parameters) and returns an array `[C, M, Y, K]` using the uncalibrated colour mapping.
> 3 votes

# Answer
## Mathematica, ~~36~~ ~~28~~ 33 bytes

```
List@@ColorConvert[{##}/255,"CMYK"]&

```

~~After liberalization of I/O formats, golfed further: `List@@#~ColorConvert~"CMYK"&`~~

Anonymous function, that does what is asked.

The old function takes three arguments from 0 to 255 (anything beyond this range will be automatically clipped to this range) and returns an array of "CMYK" values between `0.` and `1.`

Example (for old function):

```
List @@ ColorConvert[{##}/255, "CMYK"] &[108, 174, 106]

```

> ```
> {0.37931, 0., 0.390805, 0.320313}
>
> ```

Since arrays are allowed as input, **33 bytes:**

```
List@@ColorConvert[#/255,"CMYK"]&

```

*Of course* the *built-in* function handles `{0, 0, 0}` properly and returns `{0, 0, 0, 1}`.
> 3 votes

# Answer
# Pyth, ~~24~~ ~~21~~ ~~18~~ ~~24~~ 21 bytes

Life is a round trip, indeed.

```
~~=cR255Q+mc--1dK-1JeSQJQK~~
~~=cR255Q+mc-JeSQdJQ-1J~~
~~+mc-JeSQdJQ-1cJ255~~
~~+mc-JeSQd+J^T_15Q-1cJ255~~
+m-1?JeSQcdJ1Q-1cJ255

```

Test suite.

Sample input: `108,174,106`

Sample output: `[0.3793103448275862, 0.0, 0.3908045977011494, 0.3176470588235294]`

Sample input: `0,0,0`

Sample output: `[0, 0, 0, 1.0]`

Formula used:

$$ \begin{cases} J = max(R,G,B)\\ C = 1-\frac{R}{J}\\ M = 1-\frac{G}{J}\\ Y = 1-\frac{B}{J}\\ K = 1-\frac{J}{255}\\ \end{cases} $$

Old formula: https://i.stack.imgur.com/ZtPD6.gif

Old formula: https://i.stack.imgur.com/Nqi9F.gif
> 2 votes

# Answer
# Bash + ImageMagick, 69 bytes

```
convert "xc:$1[1x1]" -colorspace cmyk txt:-|grep -o '([^)]*)'|head -1

```

Example:

```
$ ./rgb2cmyk.sh "#6CAE6A"
(38%,0%,39%,32%)

$ ./rgb2cmyk.sh "#000000"
(0%,0%,0%,100%)

$ ./rgb2cmyk.sh "#AAFFEE"
(33%,0%,7%,0%)

$ ./rgb2cmyk.sh "#0088ff"
(100%,47%,0%,0%)

$ ./rgb2cmyk.sh "#FAEBD7"
(0%,6%,14%,2%)

$ ./rgb2cmyk.sh "#123456"
(79%,40%,0%,66%)

```
> 2 votes

# Answer
# SmileBASIC, ~~73~~ 72 bytes

```
INPUT R,G,B
J=MAX(R,G,B)IF!J THEN?0,0,0,1 ELSE?1-R/J,1-G/J,1-B/J,1-J/255

```

Could be much shorter.
> 2 votes

# Answer
## Lithp, 114 bytes

```
#R,G,B::((var J(max R G B))(if(!= 0 J)((list(- 1(/ R J))(- 1(/ G J))(- 1(/ B J))(- 1(/ J 255))))((list 0 0 0 1))))

```

Try it online!

* Saved 6 bytes (forgot that `max` takes any number of arguments)

I'm not quite sure this is right. The first two results with the sample data are correct, but the rest are not (see the Try it online.)

Uses the implementation described nicely as follows:

$$ \begin{cases} J = max(R,G,B)\\ C = 1-\frac{R}{J}\\ M = 1-\frac{G}{J}\\ Y = 1-\frac{B}{J}\\ K = 1-\frac{J}{255}\\ \end{cases} $$
> 2 votes

# Answer
# PHP 7, ~~123~~ ~~110~~ 105 bytes

**Input as RGB color `100 240 75`**

```
$j=max($h=$argv);echo strtr(@(1-$h[1]/$j).",".@(1-$h[2]/$j).",".@(1-$h[3]/$j).",".(1-$j/255),["NAN"=>0]);

```

Outputs CMYK values as decimal in `0...1` range.

Saved lots of bytes thanks to Titus.

Sample usage:

```
php -r '$j=max($h=$argv...' 100 240 75
0.58333333333333,0,0.6875,0.058823529411765

php -r '$j=max($h=$argv...' 255 255 255
0,0,0,0

php -r '$j=max($h=$argv...' 0 255 0
1,0,1,0

php -r '$j=max($h=$argv...' 0 0 0
0,0,0,1

```

Test online

---

**Input as HEX color `#123456`, 202 bytes**

```
$h=str_split(substr($argv[1],-6),2);$j=max($r=hexdec($h[0]),$g=hexdec($h[1]),$b=hexdec($h[2]));echo z($r,$j),",",z($g,$j),",",z($b,$j),",",1-$j/255;function z($c,$y){return is_nan(@($c/$y))?0:1-$c/$y;}

```

54 bytes for function to prevent division by zero, probably golfable or removable.

Gets as input RGB color as HEX `#123456` and outputs CMYK as decimal in `0...1` range.

Sample usage:

```
php -r '$h=str_split...' '#000000'
0,0,0,1

php -r '$h=str_split...' '#ffffff'
0,0,0,0

php -r '$h=str_split...' '#123456'
0.7906976744186,0.3953488372093,0,0.66274509803922

php -r '$h=str_split...' '#ffff00'
0,0,1,0

```
> 1 votes

# Answer
# PHP, not competing

I was just too tempted to post my own.

**RGB input, 74 bytes**

```
for(;$i++<4;)echo$i<4?($j=max($argv))?1-$argv[$i]/$j:0:1-$j/255,","[$i>3];

```

or 68 bytes with a trailing comma in the output: remove `[$i>3]`.

Run with `php -r '<code>' <red-value> <green-value> <blue-value>`.

**HEX input, 100 bytes**

```
foreach($a=array_map(hexdec,str_split($argv[1],2))as$c)echo($j=max($a))?1-$c/$j:0,",";echo 1-$j/255;

```

Run with `php -nr '<code>' RRGGBB`.

That approach would take 75 bytes for RGB input:
replace `foreach($a=array_map...as$c)` with `foreach($a=$argv as$c)if($i++)`.
> 1 votes

# Answer
# C, 155 bytes

```
#define C(x) 1-x/(j>0?j:1)
#define F float
i=0;F j;f(F r,F g,F b){j=(r>g?r:g)>b?(r>g?r:g):b;for(;i++<4;)printf("%f\n",i>1?i>2?i>3?1-j/255:C(b):C(g):C(r));}

```

I'm trying to figure out how it's possible golf more.

## Usage:

```
#define C(x) 1-x/(j>0?j:1)
#define F float
i=0;F j;f(F r,F g,F b){j=(r>g?r:g)>b?(r>g?r:g):b;for(;i++<4;)printf("%f\n",i>1?i>2?i>3?1-j/255:C(b):C(g):C(r));}
main(){
    f(108,174,106);
}

```

### Output:

```
0.379310
0.000000
0.390805
0.317647

```
> 0 votes

# Answer
## Hoon, 110 bytes

```
=>
rs
|*
a/*
=+
[s=(cury sub .1) j=(roll a max)]
(welp (turn a |*(* (s (min .1 (div +< j))))) (s (div j .255)))

```

Use the single precision floating-point library. Create a new generic function that takes `a`. Set `s` to `sub` curried with `.1` for later, and `j` to folding over `a` with `max`.

Map over `a` by dividing each element with `j`, finding the minimum of that and 1 to normalize NaN, then subtract 1 with `s`. Add `1-j/255` to the end of that list.

```
> =f =>
  rs
  |*
  a/*
  =+
  [s=(cury sub .1) j=(roll a max)]
  (welp (turn a |*(* (s (min .1 (div +< j))))) (s (div j .255)))
> (f (limo ~[.108 .174 .106]))
[i=.3.7931037e-1 t=[i=.0 t=[i=.3.908046e-1 .3.1764704e-1]]]
> (f (limo ~[.0 .0 .0]))
[i=.0 t=[i=.0 t=[i=.0 .1]]]

```
> 0 votes

---
Tags: code-golf, conversion, color
---


title: ASCII Art "Flight Simulator"

text:
# Question
Title: ASCII Art "Flight Simulator"
**EDIT**

It appears that there has been some confusion following my typo in the original post which used a lowercase o to define the plane and then an uppercase later. Unfortunately this bug did not get picked up in the Sandbox. Since many members have written answers with both and since the typo was my fault I will allow either uppercase or lowercase o in the definition of the plane. I have added a new rule for this.

**Background**

I like ascii art animations as I tend to call them so here is another one. I don't think this is too difficult to implement so will hopefully get some short and interesting answers.

**To all fellow community members**

If you improve on your answer please modify your byte count as

**~~old byte count~~ new byte count**

so we can see your progress. Thanks!

**Challenge**

Here is an ascii plane

```
--O--

```

Here is an ascii runway

```
____|     |____

```

The plane starts at 5 newlines above the runway. To prevent any clashes between metric and imperial systems and make this a truly international challenge I won't mention meters or feet. Example:

```
        --O--

____|     |____

```

The Plane must land exactly in the middle of the runway as shown below:

```
____|--O--|____

```

**Input**

The initial horizontal position of the plane is defined by an integer input which is used to reference the tip of the left wing i.e. it is between 0 and 10 inclusive.

**Output**

Each stage of the planes flight must be shown. Example below (input=10):

```
          --O--

____|     |____

         --O--

____|     |____

        --O--

____|     |____

       --O--

____|     |____

      --O--
____|     |____

____|--O--|____

```

To keep things simple, we are ignoring the laws of perspective. The runway stays the same size as you get closer.

**Rules**

* **Update** The middle of the plane can be either an uppercase or lowercase o but whichever is chosen must be consistent throughout the code. If your language does not support the characters above feel free to use alternative ascii only characters.
* The plane descends 1 line per frame.
* The plane can only move 1 space to the left or right each time it descends one line. It does not have to move on each line of descent. As long as it finishes on the runway it is up to you when it moves right or left. You're the pilot!
* No error handling required. You may assume that the input will always be a valid integer from 0-10 inclusive.
* Output must consist of only the characters shown above (if your language does not support them the see edited first rule) and must be the same size i.e. must start 6 lines high by 15 characters wide. The height can decrease as it progresses as in the example above.
* Program or function is fine but must produce an output as shown above.
* Leading/trailing spaces/newlines are fine by me.
* Please feel free to clear the screen between output frames if you wish. This is **not** a requirement.
* Standard loopholes prohibited as usual (although I don't think there are many that would help with this kind of challenge).
* This is code golf so shortest answer is obviously the winner and will probably get most votes but may not necessarily be accepted as the best answer if some really interesting solution comes along in some unexpected language, even if it is longer. Feel free to post anything that meets the rules as long as it works.

Ungolfed reference implementation in Python 2 available at Try it online! so you can see how it looks for different input values.

# Answer
# TI-BASIC, 61 bytes

```
Input A
A
For(B,1,5
ClrHome
Output(5,1,"----/     /----
Output(B,Ans,"--O--
Ans+6-median({5,7,Ans
End

```
> 4 votes

# Answer
# TI-BASIC, 62 bytes

```
:Input A
:A
:For(N,3,8
:ClrHome
:Output(8,1,"----I     I----
:Output(N,Ans,"--O--
:Ans+(Ans<6)-(Ans>6
:End

```

Note that TI-BASIC does not support _ or | and therefore I replaced with a capital I and -. This should not effect byte count.
> 8 votes

# Answer
## Python 2, 107 bytes

```
n=input();h=5
while h:print' '*n+'--O--'+'\n'*h+'____|     |____\n';n-=cmp(n,5);h-=1
print'____|--O--|____'

```

Try it online

Simply hardcodes the last line for the landing plane. It can likely be golfed by re-using parts from before or being integrated into the loop.
> 6 votes

# Answer
## Perl, 94 bytes

93 bytes of code + `-p` flag.

```
$\="____|     |____
";$p="--O--";for$i(-5..-1){print$"x$_.$p.$/x-$i;$_+=5<=>$_}$\=~s/ +/$p/}{

```

Try it online!
> 5 votes

# Answer
# JavaScript (ES6), 108 bytes

```
f=(a,b=5)=>b?" ".repeat(a)+`--O--${`
`.repeat(b)}____|     |____

`+f(a<5?a+1:a-1,b-1):"____|--O--|____"

```

## Test it

```
f=
(a,b=5)=>b?" ".repeat(a)+`--O--${`
`.repeat(b)}____|     |____

`+f(a<5?a+1:a-1,b-1):"____|--O--|____"
```

```
<input type=number min=0 max=10 oninput=o.textContent=f(+this.value)><pre id=o>
```

## Usage

Just call `f` with the index of the plane.

```
f(2)

```

## Output

```
  --O--

____|     |____

   --O--

____|     |____

    --O--

____|     |____

     --O--

____|     |____

    --O--
____|     |____

____|--O--|____

```
> 3 votes

# Answer
## Scala, ~~224~~ 181 bytes

**EDIT**: I had no idea you could do `"string"*n` to repeat it n times! Scala continues to blow my mind. Missing the `if(t>0)` instead of `if(t==0)` was a rookie mistake. Thanks for the tips, Suma!

---

```
def?(x:Int,t:Int=5):Unit={var(p,o)=("--o--","")
o=s"____|${if(t>0)" "*5 else p}|____\n"
for(i<-0 to t)o=if(i!=0&&i==t)" "*x+p+o else "\n"+o
println(o)
if(t>0)?(x-(x-4).signum,t-1)}

```

---

Original remarks:

I figured a recursive solution would be fun to try. I'm relatively new to Scala, so I'm certain this is far from optimal.
> 3 votes

# Answer
## Batch, 230 bytes

```
@echo off
set/ax=10-%1
set s=          --O--
for /l %%i in (0,1,4)do call:l %%i
echo ____^|--O--^|____
exit/b
:l
call echo %%s:~%x%%%
for /l %%j in (%1,1,3)do echo(
echo ____^|     ^|____
echo(
set/a"x-=x-5>>3,x+=5-x>>3

```

`x` is the number of spaces to remove from the beginning of the string `s`, so I subtract the parameter from 10. The last line is the nearest Batch has to `x-=sgn(x-5)`.
> 2 votes

# Answer
# Perl 6, ~~97~~ ~~90~~ 81 bytes

```
{say "{"{" "x 15}\n"x 5}____|     |____"~|("\0"x$^h+$_*(17-$h/5)~"--O--") for ^6}

```

Contrary to what it looks like, it outputs the \*lower-case version of the plane (`--o--`), as allowed by the updated task description.

Try it online!

### How it works

Bitwise string operators FTW!

```
{                                                  # Lambda accepting horizontal index $h.
    say                                            # Print the following:
        "{ "{ " " x 15 }\n" x 5 }____|     |____"  # The 15x6 background string,
        ~|                                         # bitwise-OR'd against:
        (
            "\0"                                   # The NULL-byte,
            x $^h + $_*(17 - $h/5)                 # repeated by the plane's offset,
            ~ "--O--"                              # followed by an OR mask for the plane.
        )
    for ^6                                         # Do this for all $_ from 0 to 5.
}

```

It works because bitwise string operators use the codepoint values of the characters at a given position in two strings, to calculate a new character at that position in the output string.
In this case:

```
space  OR  O   =  o
space  OR  -   =  -
any    OR  \0  =  any

```

For an uppercase-`O` plane, we could have used `~^` (string bitwise XOR), with a plane mask of `\r\ro\r\r` (+4 bytes for backslashes):

```
space  XOR   o  =  O
space  XOR  \r  =  -
any    XOR  \0  =  any

```

The formula for the plane's offset, `h + v*(17 - h/5)`, was simplified from:

```
  v*16         # rows to the vertical current position
+ h            # columns to the horizontal starting position
+ (5 - h)*v/5  # linearly interpolated delta between horizontal start and goal

```
> 2 votes

# Answer
# sed, 181 bytes + 2 for `-nr` flags

```
s/10/X/
:A
s/^/ /;y/0123456789X/-0123456789/;/[0-9]/bA;s/ -/P\n\n\n\n\n____|P|____/
:B
h;s/P([\n|])/--O--\1/;s/P/     /;s/^ *_/_/;p;/^_/q;x;s/\n//
/^ {5}$/bB;/ {6}/s/  //;s/^/ /;bB

```

## Ungolfed

```
# Add leading spaces
s/10/X/
:A
    s/^/ /
    y/0123456789X/-0123456789/
/[0-9]/bA

s/ -/P\n\n\n\n\n____|P|____/

:B
    # Place plane in appropriate spot
    h
    s/P([\n|])/--O--\1/
    s/P/     /
    s/^ *_/_/
    p
    /^_/q
    x

    # Movement
    s/\n//
    /^ {5}$/bB
    # move left one extra, since we'll move right next line
    / {6}/s/  //
    s/^/ /
bB

```

Usage: `$ echo 2 | sed -nrf flightsim.sed`
> 2 votes

# Answer
# Retina, 86 83 bytes

```
.+
$* --O--¶¶¶¶¶¶____|     |____
{*`$
¶
2D`¶
 ( {5})
$1
}`^ {0,4}-
 $&
 +
--O--
G`_

```

Try it online!

There is probably some sort of compression I could have used on the runway and the empty space over it, but anything I tried came up more expensive than plaintext (in Retina ¶ is a newline, so you can see the initial state in plaintext on the second line).
> 2 votes

# Answer
## Scala, 177, 163, 159 137 bytes

```
def p(x:Int,t:Int=5,a:String="\n"):String=a+(if(t>0)
" "*x+"--O--"+"\n"*t+"____|     |____\n"+p(x-(x-4).signum,t-1)else"____|--O--|____")

```

Based on another answer, with significant reductions.
> 2 votes

# Answer
# Python 2, 160 bytes

```
i,s,p,l,r,c,x=input(),' ','--O--','____|','|____',0,4
while x>=0:print'\n'.join([s*i+p]+[s*15]*x+[l+s*5+r])+'\n';c+=1;x-=1;i=((i,i-1)[i>5],i+1)[i<5]
print l+p+r

```

Try it online!

Here is the reference implementation golfed down to 160 from 384. Still a way to go I think. Just posted for fun and to encourage a better Python answer.
> 1 votes

# Answer
# Befunge-93, ~~136~~ 130 bytes

```
&5>00p10p55+v
:::00g>:1-\v>:"____|     |_"
>:1-\v^\+55_$"--O--"10g
^\*84_$>:#,_10g::5v>:#,_@
<_v#!:-1g00+`\5\-`<^"____|--O--|____"

```

Try it online!

**Explanation**

```
&                          Read the plane position.
 5                         Initialise the plane height.
  >                        Begin the main loop.

   00p                     Save the current height.
      10p                  Save the current position.
         55+:              Push two linefeed characters.

         "____|     |_"    Push most of the characters for the airport string.
:::                        Duplicate the last character three times to finish it off.

   00g>:1-\v               Retrieve the current height, and then push
      ^\+55_$                that many copies of the linefeed character.

             "--O--"       Push the characters for the plane.

>:1-\v              10g    Retrieve the current position, and then push
^\*84_$                      that many copies of the space character.

       >:#,_               Output everything on the stack in reverse.

            10g::          Retrieve the current position and make two copies to work with.
                 5v        If it's greater than 5
                -`<          then subtract 1.
           +`\5\           If it's less than 5 then add 1.

        g00                Retrieve the current height.
      -1                   Subtract 1.
 _v#!:                     If it's not zero, repeat the main loop.

^"____|--O--|____"         Otherwise push the characters for the landed plane.
>:#,_@                     Output the string and exit.

```
> 1 votes

# Answer
# Ruby, 94 bytes

```
->a{5.times{|i|puts" "*a+"--O--#{?\n*(5-i)}____|     |____

";a+=5<=>a};puts"____|--O--|____"}

```

Prints the plane's position followed by newlines and then the airport. Then it moves the plane by 1, -1, or 0, depending on its position relative to 5.

After looping the above 5 times, it prints the plane in the airport.
> 1 votes

# Answer
# 8th, ~~177~~ 172 bytes

```
: f 5 >r 5 repeat over " " swap s:* . "--O--" . ' cr r> times "____|     |____\n\n" . over 5 n:cmp rot swap n:- swap n:1- dup >r while "____|--O--|____\n" . 2drop r> drop ;

```

The word `f` expects an integer between 0 and 10.

**Usage**

```
4 f

```

**Explanation**

```
: f \ n --
  5 >r     \ Push vertical distance from airport to r-stack
  5 repeat
    \ Print plane
    over " " swap s:* . "--O--" .
    \ Print airport
    ' cr r> times "____|     |____\n\n" .
    \ Now on the stack we have:
    \ distanceFromLeftSide distanceFromAirport
    over      \ Put distance from left side on TOS
    5 n:cmp   \ Compare left distance and 5. Return
              \ -1 if a<b, 0 if a=b and 1 if a>b
    rot       \ Put distance from left side on TOS
    swap n:-  \ Compute new distance from left side
    swap n:1- \ Decrement distance from airport
    dup >r    \ Push new airport-distance on the r-stack
  while
  "____|--O--|____\n" .  \ Print final step
  2drop r> drop          \ Empty s-stack and r-stack
;

```
> 1 votes

# Answer
## QBIC, ~~93~~ ~~91~~ 84 bytes

```
:{X=space$(a)+@--O--`┘a=a-sgn(a-5)~t>-1|?X[t|?]t=t-1?@____|`+@     `+_fB|\_xB+A+_fB

```

*Dropped some bytes by replacing the declaration of X$; optimised the FOR loop that prints the distance above-ground. Explanation below is for the old version, but it basically works the same.*

For testing (and aesthetics) I had a slightly different version, at 103 bytes:

```
:{_z.5|_CX=Y[a|X=X+@ `]X=X+@--O--`
a=a-sgn(a-5)
~u>0|?X';`[u|?]u=u-1?@____|`+@     `+_fC|\_xC+_tB+_fC

```

These are functionally identical. The second one has the addition that the screen gets cleared between frames and that it halts for 0.5 seconds between frames.

# Sample output

Note that I've added two newlines between frames. The most golfed code above does not add empty lines between frames, the cooler one clears the screen.

```
Command line: 10

          --O--

____|     |____

         --O--

____|     |____

        --O--

____|     |____

       --O--

____|     |____

      --O--
____|     |____

____|--O--|____

```

# Explanation

Since I feel this touches upon many things I really like about QBIC, and gives a good insight in how some of its functions work under the hood, I've gone a bit overboard on the explanation. Note that QBIC is, at its core, an QBasic interpreter for Codegolf. QBIC code goes in - QBasic code comes out (and is subsequently executed).

```
:{      get the starting offset (called 'a') from the command line, and start a DO-loop

----  cool code only  ----
_z.5|_C At the start of a DO-loop, pause for half a second and clear the screen
---- resume golf-mode ----

---- #1 - The tip of the left wing is anywhere between 0 and 10 positions to the right.
----       Create the plane with the spacing in X$
X=Y          Clear X$
[a|          For each point in the current offset
X=X+@ `]     Add a space to X$
    - Every capital letter in QBIC references that letter+$, a variable of type String
    - @ and ` start and end a string literal, in this case a literal space.
    - ] ends one language construct (an IF, DO or FOR). Here, it's NEXT
X=X+@--O--`  Create the actual plane
    - @ and `once again create a string literal. Every literal that is created in this
      way is assigned its own capital letter. This is our second literal, so the body of
      our plane is stored in B$ (A$ contains the space, remember?)

---- #2 Adjust the offset for the next iteration
a=a-sgn(a-5) The clever bit: We have an offset X in the range 0 - 10, and 5 attempts to
             get this to be == 5. X - 5 is either positive (X = 6 - 10), negative
             (X = 0 - 4) or 0 (X=5). sgn() returns the sign of that subtraction
             as a 1, -1 or 0 resp. We then sub the sign from 'a', moving it closer to 5.

---- #3 Draw the plane, the empty airspace and the landing strip
~u>0|     Are we there yet?
    - ~ is the IF statement in QBIC
    - It processes everything until the | as one true/false expression
    - All the lower-case letters are (or better, could be) references to numeric
      variables. Since QBasic does not need to post-fix those, they double as 'natural'
      language: ignored by QBIC and  passed as literal code to the QBasic beneath.
    - The lower-case letters q-z are kinda special: at the start of QBIC, these
      are set to 1 - 10. We haven't modified 'u' yet, so in the first DO-loop, u=5

?X';`     If we're still air-borne, print X$ (our plane, incl. spacers)
    - ? denotes PRINT, as it does in QBasic.
    - ' is a code literal in QBIC: everything until the ` is not parsed, but
      passed on to QBasic.
    - In this case, we want a literal ; to appear after PRINT X$. This suppresses
      QBasic's normal line-break after PRINT. This needs to be a code literal
      because it is the command to read a String var from the command Line in QBIC.
[u|?]     FOR EACH meter above the ground, print a newline
u=u-1     Descent 1 meter
?@____|`  Print the LHS of the landing strip
+@     `  plus 5 spaces
+_fC|     plus the LHS reversed.
\         ELSE - touchdown!
_x        Terminate the program (effectively escape the infinite DO-loop)
    - the _x command has an interesting property: ULX, or Upper/Lowercase Extensibility.
      Writing this command with an uppercase _X does something similar, yet different.
      The _x command terminates, and prints everything found between _x and | before
      quitting. Uppercase _X does not look for |, but only prints something if it is
      followed by a character in the ranges a-z and A-Z - it prints the contents of
      that variable.
C+B+_fC   But before we quit, print C$ (the LHS of the landing strip) and the plane,
          and the LHS flipped.

---- #4 QBIC has left the building
- Did I say _x looks for a | ? Well, that gets added implicitly by QBIC at the end of
  the program, or when one ( ']' ) or all ( '}' ) opened language constructs are closed.
- Also, all still opened language constructs are automatically closed at EOF.
- Had we stored anything in Z$, that would also be printed at this time.

```
> 1 votes

# Answer
# Mathematica, 111 bytes

```
If[#<1,"____|--O--|____"," "~Table~#2<>"--O--"<>"
"~Table~#<>"____|     |____

"<>#0[#-1,#2+#2~Order~5]]&[5,#]&

```

Anonymous function. Takes a number as input and returns a string as output. Could probably be golfed further.
> 1 votes

# Answer
# SmileBASIC, ~~109~~ 105 bytes

```
G$="_"*4INPUT X
FOR I=0TO 4?" "*X;"--O--";CHR$(10)*(4-I)?G$;"|     |";G$X=X-SGN(X-5)?NEXT?G$;"|--O--|";G$

```
> 1 votes

# Answer
# PHP 7, 139 bytes

still awfully long

```
for($x=$argv[1],$d=6;$d--;$x+=5<=>$x)for($i=$p=-1;$i++<$d;print"$s
")for($s=$i<$d?" ":"____|     |____
";!$i&++$p<5;)$s[$x+$p]="--O--"[$p];

```

takes input from command line argument; run with `-r`.

**breakdown**

```
for($x=$argv[1],                        // take input
    $y=6;$y--;                          // loop height from 5 to 0
    $x+=5<=>$x)                             // post increment/decrement horizontal position
    for($i=$p=-1;$i++<$y;                   // loop $i from 0 to height
        print"$s\n")                            // 3. print
        for($s=$i<$y?" ":"____|     |____\n";   // 1. template=empty or runway+newline
            !$i&++$p<5;)$s[$x+$p]="--O--"[$p];  // 2. if $i=0, paint plane

```
> 1 votes

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


# Question
Title: RegEx-golf: match all contents in a string
Your task is to write a RegEx that matches everything inside strings.

A string is defined as everything surrounded by (but not including) two unescaped `"`.

A `"` can be escaped by `\`, which can also be escaped again.

# Testcases

```
string:  ab\c"defg\\\"hi"jkl"mn\\\\"opqrst""
matches:      ^^^^^^^^^^     ^^^^^^        ^ (the empty string)

```

# Scoring

Shortest solution wins.

# Specs

* Please specify the flavour used.
* The input will have balanced `"`.
* There will be no `\` that immediately precedes a string-beginning-delimiter. For example, you would not need to handle `abc\"def"`

# Answer
# PCRE, 21 20 15 19 bytes

```
(.|^)"\K(\\.|[^"])*

```

Try it here.

This matches a character (or the beginning of the input) before the beginning double quote and then reset the match, to make sure the double quote isn't shared with another match.

# PCRE, 25 23 bytes

Thanks to Martin Büttner for golfing off 2 bytes.

```
(\\.|[^"])*+(?!"(?R)|$)

```

Try it here.

### Explanation

```
(
    \\.|[^"]     # An escaped character, or a character that isn't a double quote
)*+              # Possessive zero-or-more quantifier, which means backtracking
                 # could not happen after first match is found. That means if \\.
                 # matched, it would never switch to [^"], because it is always a
                 # match if it just stopped after the \\. without backtracking.
(?!"(?R)|$)      # Make sure it is not followed by a double quote and another
                 # match, or the end of the input.

```

Note that the possessive quantifier (`*+`) made sure the negative lookahead always begins after a whole string, or a whole segment of non-string.

There are 4 cases:

* The match begins anywhere outside of a string. `\\.` would never match a double quote according to the clarification. It could only end just before the next double quote which begins a string, or the end of input. Both cases fails the negative lookahead.
* The match begins at the beginning of a string. `(\\.|[^"])*+` would match a complete string. The next character must be a double quote, and couldn't be the end of input. After the double quote it is outside of the string, so it couldn't be another match. So it passes the negative lookahead.
* The match begins at the end of a string. It matches an empty string in the same way as the previous case. But it doesn't matter according to the clarification.
* The match begins in the middle of a string. Impossible because matches don't overlap.
> 3 votes

# Answer
# JavaScript, 24 bytes

`"([^"\\]*(?:\\.[^"\\]*)*)"`

Group 1 is the contents of the string.
> 0 votes

# Answer
# JavaScript, ~~21~~ ~~15~~ ~~13~~ 12 bytes

`"((\\?.)*?)"`

String contents are in group 1.

```
"   #start of string
(    #capturing group
 (
  \\?. #match character or escaped character
 )*?  #match as few as possible
)
"   #end of string

```
> 0 votes

---
Tags: code-golf, string, regular-expression, syntax
---


title: Linear Regression on a String

text:
# Question
Title: Linear Regression on a String
This challenge is a little tricky, but rather simple, given a string `s`:

```
meta.codegolf.stackexchange.com

```

Use the position of the character in the string as an `x` coordinate and the ascii value as a `y` coordinate. For the above string, the resultant set of coordinates would be:

```
0, 109
1, 101
2, 116
3, 97
4, 46
5, 99
6, 111
7, 100
8, 101
9, 103
10,111
11,108
12,102
13,46
14,115
15,116
16,97
17,99
18,107
19,101
20,120
21,99
22,104
23,97
24,110
25,103
26,101
27,46
28,99
29,111
30,109

```

---

Next, you must calculate both the slope and the y-intercept of the set you've garnered using Linear Regression, here's the set above plotted:

Which results in a best fit line of (0-indexed):

```
y = 0.014516129032258x + 99.266129032258

```

Here's the ***1-indexed*** best-fit line:

```
y = 0.014516129032258x + 99.251612903226

```

---

So your program would return:

```
f("meta.codegolf.stackexchange.com") = [0.014516129032258, 99.266129032258]

```

Or (Any other sensible format):

```
f("meta.codegolf.stackexchange.com") = "0.014516129032258x + 99.266129032258"

```

Or (Any other sensible format):

```
f("meta.codegolf.stackexchange.com") = "0.014516129032258\n99.266129032258"

```

Or (Any other sensible format):

```
f("meta.codegolf.stackexchange.com") = "0.014516129032258 99.266129032258"

```

Just explain why it is returning in that format if it isn't obvious.

---

Some clarifying rules:

```
- Strings are 0-indexed or 1 indexed both are acceptable.
- Output may be on new lines, as a tuple, as an array or any other format.
- Precision of the output is arbitrary but should be enough to verify validity (min 5).

```

This is lowest byte-count wins.

# Answer
# MATL, 8 bytes

```
n:G3$1ZQ

```

1-based string indexing is used.

Try it online!

### Explanation

```
n:     % Input string implicitly. Push [1 2 ... n] where n is string length.
       % These are the x values
G      % Push the input string. A string is an array of chars, which is
       % equivalent to an array of ASCII codes. These are the y values
3$     % The next function will use 3 inputs
1      % Push 1
ZQ     % Fit polynomial of degree 1 to those x, y data. The result is an
       % array with the polynomial coefficients. Implicitly display

```
> 2 votes

# Answer
# Octave, ~~29~~ ~~26~~ ~~24~~ 20 bytes

```
@(s)s/[!!s;1:nnz(s)]

```

Try it Online!

We have the model

```
y= intercept *x^0 + slope * x
 = intercept * 1  + slope * x

```

Here `y` is the ASCII value of string `s`

To find parameters intercept and slope we can form the following equation:

```
s = [intercept slope] * [1 X]

```

so

```
[intercept slope] = s/[1 x]

```

`!!s` converts a string to a vector of ones with the same length as the string.
The vector of ones is used for estimation of the intercept.
`1:nnz(s)` is range of values from 1 to number of elements of the string used as `x`.

Previous answer

```
@(s)ols(s'+0,[!!s;1:nnz(s)]')

```

For test paste the following code into Octave Online

```
(@(s)ols(s'+0,[!!s;1:nnz(s)]'))('meta.codegolf.stackexchange.com')

```

A function that accepts a string as input and applies ordinary least squares estimation of model `y = x*b + e`

The first argument of ols is `y` that for it we transpose the string `s` and add with number 0 to get its ASCII code.
> 7 votes

# Answer
# TI-Basic, 51 (+ 141) bytes

Strings are 1-based in TI-Basic.

```
Input Str1
seq(I,I,1,length(Str1->L1
32+seq(inString(Str2,sub(Str1,I,1)),I,1,length(Str1->L2
LinReg(ax+b)

```

Like the other example, this outputs the equation of the best fit line, in terms of X. Also, in Str2 you need to have this string, which is 141 bytes in TI-Basic:

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

The reason this cannot be a part of the program is because two characters in TI-Basic cannot be automatically added to a string. One is the `STO->` arrow, but this is not a problem because it is not a part of ASCII. The other is the string literal (`"`), which can be stringified only by typing into a `Y=` equation and using `Equ>String(`.
> 6 votes

# Answer
## R, 46 45 bytes

```
x=1:nchar(y<-scan(,""));lm(utf8ToInt(y)~x)$co

```

Reads input from stdin and for the given test case returns (one-indexed):

```
(Intercept)           x
99.25161290  0.01451613

```
> 6 votes

# Answer
# Python, ~~82~~ 80 bytes

<sub>-2 bytes thanks to @Mego</sub>

Using `scipy`:

```
import scipy
lambda s:scipy.stats.linregress(range(len(s)),list(map(ord,s)))[:2]

```
> 5 votes

# Answer
# Mathematica, 31 bytes

```
Fit[ToCharacterCode@#,{1,x},x]&

```

Unnamed function taking a string as input and returning the actual equation of the best-fit line in question. For example, `f=Fit[ToCharacterCode@#,{1,x},x]&; f["meta.codegolf.stackexchange.com"]` returns `99.2516 + 0.0145161 x`.

`ToCharacterCode` converts an ASCII string to a list of the corresponding ASCII values; indeed, it defaults to UTF-8 more generally. (Kinda sad, in this context, that one function name comprises over 48% of the code length....) And `Fit[...,{1,x},x]` is the built-in for computing linear regression.
> 4 votes

# Answer
# Node.js, 84 bytes

Using `regression`:

```
s=>require('regression')('linear',s.split``.map((c,i)=>[i,c.charCodeAt()])).equation

```

## Demo

```
// polyfill, since this is clearly not Node.js
function require(module) {
  return window[module];
}
// test
["meta.codegolf.stackexchange.com"].forEach(function test(string) {
  console.log(string);
  console.log(this(string));
},
// submission
s=>require('regression')('linear',s.split``.map((c,i)=>[i,c.charCodeAt()])).equation
);
```

```
<script src="https://cdn.rawgit.com/Tom-Alexander/regression-js/master/src/regression.js"></script>
```
> 4 votes

# Answer
## Sage, 76 bytes

```
var('m','c')
y(x)=m*x+c
f=lambda x:find_fit(zip(range(len(x)),map(ord,x)),y)

```

Hardly any golfing, probably longer than a golfed Python answer, but yeah...
> 3 votes

# Answer
# , 11 bytes

```
3&u:%.1,.#\

```

This uses one-based indexing.

Try it online!

## Explanation

```
3&u:%.1,.#\  Input: string S
         #\  Get the length of each prefix of S
             Forms the range [1, 2, ..., len(S)]
      1,.    Pair each with 1
3&u:         Get the ASCII value of each char in S
    %.       Matrix divide

```
> 2 votes

# Answer
# JavaScript, ~~151~~ 148 bytes

```
s=>([a,b,c,d,e]=[].map.call(s,c=>c.charCodeAt()).reduce(([a,b,c,d,e],y,x)=>[a+1,b+x,c+x*x,d+y,e+x*y],[0,0,0,0,0]),[k=(e*a-b*d)/(c*a-b*b),(d-k*b)/a])

```

More readable:

```
function f(s) {
  var [n, sx, sx2, sy, sxy] = [].map.call(s, c => c.charCodeAt(0))
    .reduce(([n, sx, sx2, sy, sxy], y, x) => [
      n + 1,
      sx + x,
      sx2 + x * x,
      sy + y,
      sxy + x * y
    ], [0, 0, 0, 0, 0]);
  var k = (sxy * n - sx * sy) / (sx2 * n - sx * sx);
  return [k, (sy - k * sx) / n];
}

$(() => $('#run').on('click', () => console.log(f($('#input').val()))));
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="input" style="width: 100%">meta.codegolf.stackexchange.com</textarea>
<button id="run">Run</button>
```
> 2 votes

# Answer
# Haskell, ~~154~~ 142 bytes

```
import Statistics.LinearRegression
import Data.Vector
g x=linearRegression(generate(Prelude.length x)i)$i.fromEnum<$>fromList x
i=fromIntegral

```

It is far too long for my likings because of the imports and long function names, but well. I couldn't think of any other Golfing method left, although I'm not expert on the area of golfing imports.

Stripped 12 bytes by replacing `ord` and the import of `Data.Char` by fromEnum thanks to nimi.
> 2 votes

# Answer
# Javascript (ES6), 112 bytes

```
s=>[m=(a=b=c=d=0,([...s].map((u,x)=>{a+=n=x,b+=y=u.charCodeAt(),c+=x*x,d+=x*y}),++n)*d-a*b)/(n*c-a*a),b/n-m*a/n]

```

```
F=s=>[m=(a=b=c=d=0,([...s].map((u,x)=>{a+=n=x,b+=y=u.charCodeAt(),c+=x*x,d+=x*y}),++n)*d-a*b)/(n*c-a*a),b/n-m*a/n]

const update = () => {
  console.clear();
  console.log(F(input.value));
};
input.oninput = update;
update();
```

```
#input {
  width: 100%;
  box-sizing: border-box;
}
```

```
<input id="input" type="text" value="meta.codegolf.stackexchange.com" length=99/>
<div id="output"></div>
```
> 2 votes

# Answer
# SAS Macro Language, 180 bytes

Uses 1-based indexing. The solution gets to be pretty wordy when the output is only the slope and intercept.

```
%macro t(a);data w;%do i=1 %to %length(&a);x=&i;y=%sysfunc(rank(%substr(&a,&i,1)));output;%end;run;proc reg outtest=m;model y=x/noprint;run;proc print data=m;var x intercept;%mend;

```
> 1 votes

# Answer
## Clojure, 160 bytes

No built-ins, uses the iterative algorithm described at Perceptron article. Might not converge on other inputs, in that case lower the learning rate `2e-4` and maybe increase the iteration count `1e5`. Not sure if the non-iterative algorithm would have been shorter to implement.

```
#(nth(iterate(fn[p](let[A apply e(for[x(range(count %))](-(int(get % x))(*(p 1)x)(p 0)))](mapv(fn[p e](+(* e 2e-4)p))p[(A + e)(A +(map *(range)e))])))[0 0])1e5)

```

Example:

```
(def f #( ... ))
(f "meta.codegolf.stackexchange.com")

[99.26612903225386 0.014516129032464659]

```
> 1 votes

# Answer
## Maple, 65 bytes

```
Statistics:-LinearFit(b*x+a,[$(1..length(s))],convert(s,bytes),x)

```

Usage:

```
s := "meta.codegolf.stackexchange.com";
Statistics:-LinearFit(b*x+a,[$(1..length(s))],convert(s,bytes),x);

```

Returns:

```
99.2516129032259+0.0145161290322573*x

```

Notes: This uses the Fit command to fit a polynomial of the form a\*x + b to the data. The ASCII values for the string are found by converting to bytes.
> 1 votes

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


title: Print 0-255 in grey code

text:
# Question
Title: Print 0-255 in grey code
Gray Code is a number system where only 1 bit of the number changes from one number to the next number. Print the 8 bit Gray Code values of 0 to 255.

Shortest Code wins!

Start of output:

```
 0 00000000
 1 00000001
 2 00000011
 3 00000010
 4 00000110
 5 00000111
 6 00000101
 7 00000100
 ...

```

You only have to print the Gray Code in binary. The decimal numbers in the example are just for reference.

# Answer
> 2 votes
# Ruby, 48 33 Bytes

15 Bytes saved thanks to G B

```
256.times{|i|puts "%08b"%(i^i/2)}

```

# Answer
> 1 votes
# C, 89 bytes

(Note: Leading Zeros Omitted from output)

```
q;main(a){a--;for(q=a^(a>>1);q;)printf("%c%i",8207,q%2),q/=2;puts("");a<256?main(a+2):0;}

```

---

I use a very neat trick in this one:

> It converts a decimal to gray code (base 10), then convert that to binary which will print the grey number in *reverse order*. But before each time I output the mirrored grey number, I print U+200F or char(8207) which is a Right-To-Left marker character which causes output to be mirrored (and on the right side of my screen). Mirroring my backwards grey number outputs, thus making them forward, proper grey numbers (At least to human eyes, to the computer they are still backwards).

Notice the numbers are different in the LTR output, they are mirrored grey numbers.

(Note: Leading Zeros Omitted from output)

# Answer
> 0 votes
# Jelly, 10 bytes

```
⁹ḶH+^ḶBḊ€Y

```

Try it online!

# Answer
> 0 votes
# PHP, ~~43~~ 40 bytes

unpadded

```
for(;$i<256;$i++)printf("%b\n",$i^$i/2);

```

+2 bytes for padded: replace `%b` with `%08b`.

Thanks @user63956 for reminding me of printf.

# Answer
> 0 votes
# Python, 53 bytes

`for i in range(256): print(bin(i^(i>1))[2:].zfill(8))`

---
Tags: code-golf
---


# Question
Title: Traverse all numbers with only one bit flip per step
You can count 0, 1, 2, 3, 4. But to get from 3 to 4 you have to change 3 bits at once. Given a number of bits, how can you go through all numbers once, but change at each step only 1! bit.

Here is an example for 3 bits:

```
000 100 110 010 011 111 101 001

```

so the output is:

```
0 1 3 2 6 7 5 4

```

## Rules:

* given a number of bits n, return a list of 2^n unique numbers
* between to consecutive numbers only one bit is different
* the shorter the code the better

# Answer
Python 3:

```
for i in range(2**n):i^i//2

```

(Doh. Overlooked that this solutions is already known. Would delete it if stackexchange allowed it)
> 5 votes

# Answer
## GolfScript, 13 chars

```
~2\?,{.2/^}%`

```

For example, the input `3` produces the output `[0 1 3 2 6 7 5 4]`.

Here's a de-golfed version with comments:

```
~              # evaluate the input, turning it from a string into a number
2 \ ?          # raise 2 to the power given by the input...
,              # ...and turn it into a list containing the numbers from 0 to 2^n-1
{ . 2 / ^ } %  # xor each number in the list with itself divided by 2
`              # un-eval the list into a string for output

```

It's perhaps interesting to note that there are no particular "golfing tricks" involved — this *is* basically the most obvious and straightforward way to solve this task in GolfScript.
> 2 votes

# Answer
## C++, 188 bytes

```
#include <cstdlib>
#include <iostream>
#define y if(b)f(b-1)
int x=0;
void f(int b){y;std::cout<<(x^=1<<b)<<' ';y;}
int main(int,char**v){int b=std::atoi(v[1]);std::cout<<x<<' ';y;}

```

Specify the number of bits on the command line and it will print a list of space separated integers.
> 1 votes

# Answer
# F# (32)

```
[for i in 0..(1<<<n)-1->i^^^i/2]

```

If explicit output is not required, this will do the job (45 chars):

```
for i in 0..(1<<<n)-1 do printf"%i "(i^^^i/2)

```

Disclaimer: Very similar to the answer I provided here, just simplified to fit the output specified here.
> 0 votes

# Answer
# Jelly, 6 bytes

```
2*Ḷ^H$

```

Try it online!

### How it works

```
2*Ḷ^H$  Main link. Argument: n

2*      Yield 2ⁿ.
  Ḷ     Unlength; yield [0, ..., 2ⁿ].
     $  Combine the two links to the left into a chain.
   ^H       XOR each k in the range with k/2.

```
> 0 votes

---
Tags: code-golf, number
---


title: Lost in translation

text:
# Question
Title: Lost in translation
*This is a if you are not familiar with the format click the tag to go to the wiki. There will not be a robbers' thread for this question.*

# Cops

Your task as Cops is to select two sequences from the Online Encyclopedia of Integer Sequences and write a program that takes the nth element of one sequence as input and outputs the nth element of the second sequence. You then make an answer including the code and omitting the sequences selected. Robbers will attempt to find the sequences you selected and if one manages to find the sequences you had in mind or some other sequences for which your program you must mark your answer as **Cracked**. If a robber informs you with a crack that you believe is not valid you may present a proof that it is not a crack. Otherwise you must mark it so.

As per the usual answers that have been uncracked for 7 days are eligible to be marked safe. A Cop may mark their answer as safe by revealing the sequences that they had in mind. Once safe an answer may no longer be cracked.

The goal is to minimize the byte count of your program while remaining uncracked.

## Example

The following Python code translates the nth element of A000290 (the square numbers) into A000217 (the triangular numbers):

```
lambda x:sum(range(0,int(x**.5+1)))

```

# Stipulations and Requirements

* If you choose a sequence that has not been proven to be finite you must output all terms that might exist not just the ones listed on the OEIS page
* As an exception to the previous rule languages without infinite precision integers do not have to output or input numbers outside of their range.
* The size of your input sequence must not have been proven to be smaller than the output sequence.
* Your input sequence must not have any repeat elements (otherwise the task is pretty much impossible)
* The OEIS includes an index on their page (the first number after the "OFFSET" header) by default this is your offset for n (n equals the index for the first element on the sequence) if you choose another index you must indicate so in your answer.
* If you choose a offset different from the one listed on the OEIS you must still map all elements in your input sequence to the corresponding element in your output sequence.
* If your program receives an input that is not in the input sequence it may do whatever it wishes (undefined behavior). However it is probably in your best interest for it to still output an integer.
* It is unsportsmanlike to intentionally make your code difficult to run, be it by making it time consuming to execute or through non-free language selection. While I will enforce the latter I cannot objectively enforce the former. However I implore you, for the sake of fun, not to attempt the former as it makes the challenge specifically more difficult for those with weaker computers.

# Robbers

Your task as Robbers is to select uncracked, unsafe answers and find the sequences they map between. If you find solution a solution that works (not necessarily the Cops' intended solution) comment the sequences on the appropriate answer.

Robbers should not worry to much about verifying that two particular sequences are a solution, one should post a solution if it matches all of the entries on OEIS. If that is not the sequence that a cop had in mind the cop may offer a proof that it is incorrect or mark it as cracked if they cannot find one.

# Answer
> 6 votes
# Jelly, 14 bytes (Cracked by @Wolfram)

```
+66%444µ111<µ¡

```

Try it online!

It should be fairly obvious what this does. In fact, for the benefit of the non-Jelly users, I'll even give an explanation:

## Explanation

```
+66%444µ111<µ¡
       µ    µ¡  Run the transformation
+66%444           "add 66, then modulo 444"
        111<    once if 111 is less than the input, zero times otherwise

```

The question is, why does it do this?

## Crack

The sequences in question were A201647 and A201647. They're finite, and differ only in the last 2 elements:

* 3, 5, 7, 9, 11, 15, 21, 165, 693
* 3, 5, 7, 9, 11, 15, 21, 231, 315

Thus, if the input is low, I leave it the same, and I simply fit a function to the transformation of the last two.

# Answer
> 3 votes
# Jelly, 7 bytes (Cracked by @JonathanAllan)

```
ÆFḅÆdÆẸ

```

Try it online!

### What it does

```
ÆFḅÆdÆẸ  Main link. Argument: n

ÆF       Factor n into prime-exponent pairs.
   Æd    Compute σ, the number of divisors of n.
  ḅ      Convert each pair from base σ to integer.
     ÆẸ  Yield the integer whose prime signature (infinite sequence of all prime
         exponents, including zeroes, in order) is equal to the result.

```

# Answer
> 2 votes
# Processing, 184 bytes, SAFE!

```
int x(int y){int b=TRIANGLES-MITER;for(int i=OVERLAY/BURN;i>#fffffe;b*=(int)pow(y,(MOVE-HAND+0.)/(int)sqrt(red(color(-1<<16))/(int)log(color(0)*color(-1)))),i-=QUAD/DARKEST);return b;}

```

A function that takes in an int and returns an int. As long as the input number is in `int`'s range, the program should work fine.

This isn't slow, just unreadable. Good luck!

---

I am surprised this submission has lasted this long. Oh well, at least it's the first safe submission :)

### A000578 to A000290

In other words: the cubes to the squares.

### Explanation

While answering No strings (or numbers) attached, I discovered a list of Processing constants that represent ints. For example, `CORNER` has a value of `0`. The full list can be found here. To find the value of a constant, you can just `print` it.

Using this, I decided to swap certain numbers with combinations of these constants to obfuscate it. So, here's what you get when you substitute the constants with their respective int values.

```
int x(int y){int b=9-8;for(int i=512/8192;i>#fffffe;b*=(int)pow(y,(13-12+0.)/(int)sqrt(red(color(-1<<16))/(int)log(color(0)*color(-1)))),i-=16/16);return b;}

```

Even now, the full clear code isn't revealed. The colours are remaining. In Processing, colour variables have int values, for example white (`#ffffff`) is `-1`, `#fffffe` is `-2`, `#fffffd` is `-3`, and so on. This can be found by `print`ing the colour. So let's simplify the colours.

```
int x(int y){int b=9-8;for(int i=512/8192;i>-2;b*=(int)pow(y,(13-12+0.)/(int)sqrt(red(color(-1<<16))/(int)log(-16777216*-1))),i-=16/16);return b;}

```

We're about halfway there :) To understand the values, we need to simplify the numerical expressions.

```
int x(int y){int b=1;for(int i=0;i>-2;b*=(int)pow(y,(1.)/(int)sqrt(red(color(-65536))/(int)log(16777216))),i-=1);return b;}

```

Much clearer! Now let's simplify the logarithm.

```
int x(int y){int b=1;for(int i=0;i>-2;b*=(int)pow(y,(1.)/(int)sqrt(red(color(-65536))/(int)16.6...)),i-=1);return b;}

int x(int y){int b=1;for(int i=0;i>-2;b*=(int)pow(y,(1.)/(int)sqrt(red(color(-65536))/16)),i-=1);return b;}

```

Almost over! Now we have to figure out this `(int)sqrt(red(color(-65536))/16))` mouthful. `color(-65536)` is red, so `rgb(255, 0, 0)`. Now the `red()` function returns the value of the red component in the argument (which is a colour). So how much red is there in red? The answer is `255`. With that we get

```
(int)sqrt(255/16))
(int)sqrt(15)
(int)3.8...
3

```

Substituting this in the program results in:

```
int x(int y){int b=1;for(int i=0;i>-2;b*=(int)pow(y,(1.)/3),i-=1);return b;}

```

Yay, it's done!

```
int x(int y){                        // y is the cube
  int b=1;                           // variable that holds the final result
  for(int i=0;                       // for-loop that
          i>-2;                      // loops twice
          b*=(int)pow(y,(1.)/3),     // multiply b by the cube root of y
          i-=1);                     // decrement the looping variable
  return b;                          // finally return b
}

```

To sum it up, this returns the square (done by multiplying twice in the for-loop) of the cube root of the input number.

# Answer
> 2 votes
# Python 3, 256 bytes (**Cracked!**)

```
from math import*
def p(i,m):
 r=0;d=floor(log(i))
 for y in range(d):r+=(pow(16,d-y-1)%(8*y+m))/(8*y+m)
 o=-1;y=d
 while r!=o:o=r;r+=pow(16,d-y-1)/(8*y+m);y+=1
 return r
def q(n):r=4*p(n,1)-2*p(n,4)-p(n,5)-p(n,6);return floor((1-(-r%1)if r<0 else r%1)*16)

```

Try it online!

Sorry if this code looks horrendous, I think this is my first Python golf. The casting in Python makes it easier to code.

# Answer
> 0 votes
# Mathematica (or whatever) — Cracked!

```
f[x_] := Quotient[ 366403414911466530559405368378193383110620062 -
    755296348522256690003418238667147075159564695 x +
    525778437135781349270885523650096958873079916 x^2 -
    156594194215500250033652167655133583167162556 x^3 +
    20861131421245483787723229627506507062999392 x^4 -
    1181515772235154077024719095229309394979146 x^5 +
    29382627265060088525632055454760915985604 x^6 -
    308672970015057482559939241399297150364 x^7 +
    1087516675449597417990589334580403666 x^8 -
    312989984559486345089577524231879 x^9,
  265451130886621254401938908479744271974400 ]

```

I know Mathematica is non-free software, but this function is trivial to port to whatever favorite language you want to run it in. It literally computes the value of the given degree-9 polynomial evaluated at the input integer, then takes the integer quotient of that value and the 42-digit number on the last line. For example, `f[100]` evaluates to `-3024847237`.

---
Tags: code-golf, sequence, cops-and-robbers
---


title: Output the alphabet using the alphabet

text:
# Question
Title: Output the alphabet using the alphabet
The title is pretty self-explanatory, isn't it?

Your task is to output the alphabet (the string `"abcdefghijklmnopqrstuvwxyz"`) to STDOUT, using each and every letter of the alphabet in your program once and only once.

Oh, and for a bit of extra fun?

The letters "g", "o", "l" and "f" must be in order (just for the code to be a bit more code-y).

Rules:

* Only standard letters of the alphabet from ASCII count as letters (`ë != e`).
* Both uppercase and lowercase characters count as letters (if you have `E`, you are not allowed to have `e`).
* You are allowed to use comments, but every character in the comment is equal to 2 bytes.
* Your final score will be the byte-count of your program, subtracted by 26.

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

# Answer
# 05AB1E, ~~27~~ 26 - 26 = 0 bytes

Thanks to Katenkyo for saving 1 byte :). Code:

```
golfAqbcdehijkmnprstuvwxyz

```

Try it online!.
> 10 votes

# Answer
# Brainfuck, 67 - 26 + 26 (comment) = ~~41~~ 67 bytes

```
golfabcdehijkmnpqrstuvwxyz++++++++[>++++++++++++>+++<<-]>>++[-<+.>]

```

Try it online!
> 5 votes

# Answer
## Batch, 36 + 13 + 9 - 26 = 32 bytes

```
:g
@echo ab%0pqrstuvwxyz
:lfdijkmn

```

Requires that the batch file itself be named `cdefghijklmno`. Scored as 36 (size of file `cdefghijklmno`) + 13 (size of filename `cdefghijklmno`) + 9 (commented letters) - 26.

Edit: Saved 29 bytes even under my scoring scheme thanks to @ΈρικΚωνσταντόπουλος.
> 3 votes

# Answer
# Jolf, 27 - 26 = 1 byte

```
goΔaplfbcdehijkmnqrstuvwxyz

```

`o` assigns `Δ` to `apl`, which `a`lerts `pl`, which is the lowercase alphabet. I take it that "in order" does not mean "adjacent to". You can see that `f` follows `l` which follows `o` which follows `g`. Try it out here!
> 3 votes

# Answer
# CJam, 29 - 26 = 3 bytes

```
"golfabcdehijkmnpqrstuvwxyz"$

```

Try it online!
> 2 votes

# Answer
# Pyke, 29 - 26 = 3 bytes

```
"golfabcdehijkmnpqrstuvwxyz"S

```
> 2 votes

# Answer
# MATL, 29-26 = 3 bytes

```
'abcdehijkmnpqrstuvwxyzgolf'S

```

Try it Online!
> 2 votes

# Answer
# J, 36 - 26 = 10 bytes

```
'golfabcdehjkmnpqrstvwxyz']u:97+i.26

```

Not a comment, just a string that's discarded. `u:` converts numbers to ASCII chars, and `97+i.26` is a range from 0..25 with vectorized addition over 97, the char code of `a`. Here's an alternative (albeit longer) solution using `a.`:

```
'golfbcdehjkmnpqrstvwxyz']a.{~97+i.26

```
> 2 votes

# Answer
## dc, 111 - 26 = 85 bytes

```
[gol][P]s@[abcdef]1 1=@103 1 1=@[hijk]1 1=@108 1 1=@[mn]1 1=@111
1 1=@112 1 1=@[qr]1 1=@115 1 1=@[tuvwxyz]1 1=@

```

**Run:** dc -f alphabet\_letters.dc

**Output:**

```
abcdefghijklmnopqrstuvwxyz

```

I use `1 1=@` as a trick to simulate `l@x`, that executes the print command `P` stored in register `@`. This is one example of a language that entailed a non-trivial solution for this task.
> 2 votes

# Answer
# Jelly, 29 - 26 = 3 bytes

```
“golfabcdehijkmnpqrstuvwxyz”Ṣ

```

Try it online!
> 1 votes

# Answer
# Actually, 29 - 26 = 3 bytes

```
"golfabcdehijkmnpqrstuvwxyz"S

```

Try it online!
> 1 votes

# Answer
# Ruby, ~~57~~ ~~37~~ 47 - 26 = 21 bytes

I'm ashamed it took me that many tries to arrive at this super obvious solution.

```
"gol";$><<"abcdef\147hijk\154mnp\157qrstuvwxyz"

```

See it on ideone: http://ideone.com/FAtiy3
> 1 votes

# Answer
# SmileBASIC, ~~68~~ 61 bytes -26 = 35

```
_=97@V?CHR$(_);
_=_+1GOSUB"@"+KEY(3)[2]*(_<123)@ADLIJFMNPQTWXZ

```

Explained:

```
_=97 'set variable _ to 97 (ascii value of "a")
@V 'label
 ?CHR$(_) 'convert _ to a character and print
 _=_+1 'add 1 to _
GOSUB"@"+KEY(3)[2]*(_<123) 'jump to @V (KEY(3) is "SAVE") if _ is less than 123 (ascii code for z +1)
@ADLIJFMNPQTWXZ 'create a label with the unused letters

```
> 0 votes

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


title: Remainder When N divided by 2^M

text:
# Question
Title: Remainder When N divided by 2^M
Write the shortest code to find the remainder when an input number N is divided by 2^M. You cannot use /,\* and % operator.

```
Input Specification
Number of test cases followed by a pair of integers on each line.

Sample Input
1
150 6

Sample Output
22

Limits
1<T<1000
1<N<2^31
1<B<31

Time Limit
1 Sec

```

# Answer
> 2 votes
## Golfscript - 16 chars

```
~]1>2/{~2\?(&n}/

```

For a single pair or numbers this would sufficient

```
~2\?(&

```

By the way, the `/` does not stand for division here :)

# Answer
> 3 votes
```
scanf("%d", &T);
while(T--){
   scanf("%d,%d", &N,&M);
   printf("%d",N&~(~0 << M));
}

```

# Answer
> 3 votes
Uh, guys, in pretty much any language, it would be

```
N & (1 << M  - 1)

```

# Answer
> 1 votes
# Java

With whitespace to make readable:

```
long F(long M, long N) {
  M = 2<<M;
  while(N>=M) N-=M;
  return N;
}

```

# Answer
> 1 votes
## Perl, 31

```
<>;/ /,say($`&~(-1<<$'))while<>

```

Perl 5.10 or later, run with `perl -E '<code here>'`

# Answer
> 0 votes
# J, ~~15~~ ~~12~~ 9 bytes

6 bytes thanks to @miles.

```
#.@#:~#&2

```

## Previous 12-byte version

```
#.@({.~-)~#:

```

### Usage

```
>> f =: #.@({.~-)~#:
>> 6 f 150
<< 22

```

Where `>>` is STDIN and `<<` is STDOUT.

### Explanation

`#:` converts `n` to base 2.

`({.~-)~` then takes the last `m` digits from it

`#.` converts it back to base 2.

## Previous 15-byte version:

```
2#.(0-[){.[:#:]

```

### Usage

```
>> f =: 2#.(0-[){.[:#:]
>> 6 f 150
<< 22

```

Where `>>` is STDIN and `<<` is STDOUT.

### Explanation

`[:#:]` converts `n` to base 2.

`(0-[){.` then takes the last `m` digits from it

`2#.` converts it back to base 2.

# Answer
> 0 votes
# Racket (scheme) 29 bytes

Kinda cheating because racket doesn't even have the % operator:

```
(λ(n m)(modulo n(expt 2 m)))

```

# Answer
> 0 votes
# SmileBASIC, 36 characters

```
INPUT N,M?N AND(1<<M)-1

```

There's basically only one solution to this...

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


title: A day at the beach

text:
# Question
Title: A day at the beach
Inspired by this challenge

---

## Goal:

The goal is to draw waves crashing onto a beach.

## Input:

You will be given 3 integers (in whatever format you want) as input.
The first integer will be the length of the drawing The second integer will be the index of the sandbar, where the waves start to crest (at least 3 spaces from beach)
The third integer will be the spacing between waves (at least 3, can be greater than length of drawing, in which case you only draw one wave)

## Output:

The output will be a box of characters which shows the waves crashing into the beach. The drawing should end when the first wave has completed crashing into the beach.

At first, the wave is shown as a swell (`_-_`).
As the wave passes the sandbar, it starts to crest (`/c_`).
Finally, the wave crashes into the beach (`/c.` =\> `_-_` =\> `___` =\> `__.` ).

## Examples:

Input: 14 4 6

Output:

```
-___________..
_-__________..
__-_________..
___-________..
___/c_______..
____/c______..
-____/c_____..
_-____/c____..
__-____/c___..
___-____/c__..
___/c____/c_..
____/c____/c..
-____/c____-_.
_-____/c_____.
__-____/c___..

```

Input: 10, 2, 11

Output:

```
-_______..
_-______..
_/c_____..
__/c____..
___/c___..
____/c__..
_____/c_..
______/c..
_______-_.
_________.
________..

```

Input: 6 0 3

```
c___..
/c__..
_/c_..
c_/c..
/c_-_.
_/c__.
c_/c..

```

## Rules:

Standard Loopholes apply

This is so shortest code wins

# Answer
## JavaScript (ES6), ~~250~~ 243 bytes

This code is assuming code page #1252 and is using the `·` character (0xB7). Takes input as 3 distinct parameters `(a,b,c)`.

```
(a,b,c,R=n=>'_'.repeat(n-2),s=(x=b?'-':'c')+R(a-1)+'··')=>(g=j=>s+`
`+((F=`__·$,_-_·,/c··,-__,^${C=R(b>2?b:2)}__-,/c_,^c_,^_${S=R(c)},_··,___·,_-_·,_-_,${C}/c_,_/c,/c,${x+S}`.split`,`).map((r,i)=>s=i&8?s:s.replace(RegExp(r,'g'),F[i+8])),j--?g(j):''))(a)

```

### How it works

This code starts with a string such as `-______··` and applies successive regular expressions on each iteration to animate the waves.

For instance `-__` is replaced with `_-_`.

At first, it looked like a reasonable idea. However, the fact that the string may start with a `c` (like it does in the 3rd test case) makes things significantly more complicated.

### Test cases

```
f =

(a,b,c,R=n=>'_'.repeat(n-2),s=(x=b?'-':'c')+R(a-1)+'··')=>(g=j=>s+`
`+((F=`__·$,_-_·,/c··,-__,^${C=R(b>2?b:2)}__-,/c_,^c_,^_${S=R(c)},_··,___·,_-_·,_-_,${C}/c_,_/c,/c,${x+S}`.split`,`).map((r,i)=>s=i&8?s:s.replace(RegExp(r,'g'),F[i+8])),j--?g(j):''))(a)

console.log(f(14, 4, 6))
console.log(f(10, 2, 11))
console.log(f(6, 0, 3))
```
> 5 votes

# Answer
## Batch, ~~273~~ 243 bytes

```
@echo off
set f=for /l %%i in (0,1,%1)do call
set s=set b=
%s%..
%f% %s%_%%b%%
%f%:c %%i %2 %3
exit/b
:c
set/aw=%1%%%3
if %w%==0 %s%__-%b:~3%
if %w%==%2 %s%%b:_-=/c%
%s%_%b:~0,-4%%b:~-3%
%s%%b:__. =_.. %
%s%%b:/.=-_%
echo %b:~3%

```

Note: Trailing space on line 4. If only the two beach characters were different, I could save 3 bytes and actually beat JavaScript!
> 2 votes

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


# Question
Title: Fizz Buzz.. Crackle Pop! (Generalized Fizz Buzz)
We've all heard of the ol' Fizz Buzz problem, but what happens when you try to apply it with more factors? Fizz Buzz Crackle Pop!

# The Challenge

Write a **full program** that takes an *integer* input **n**, then n tuples containing an integer and a string, then another integer (\>1) k, as such:

```
 n int1 str1 int2 str2 (...) intn strn k

```

You can take this line from either command line or STDIN.

Then, for all integers 1 to k, if it is divisible by any of *int1*, *int2*...*intn*, output all corresponding *str*s in the input order, followed by a newline. If it isn't, then just output the integer, followed by a newline.

For example, with input

```
3 2 Fizz 3 Buzz 5 Crackle 10

```

we get

```
1
Fizz
Buzz
Fizz
Crackle
FizzBuzz
7
Fizz
Buzz
FizzCrackle

```

But with input (notice the order change)

```
3 3 Buzz 2 Fizz 5 Crackle 10

```

we get

```
1
Fizz
Buzz
Fizz
Crackle
BuzzFizz
7
Fizz
Buzz
FizzCrackle

```

Optional trailing newline is acceptable.

Shortest code in bytes wins.

# Edits:

Obviously I've missed out a lot, sorry.

* Inputs from console and STDIN, anything else gets +5 bytes (:c) anywhere
* Full programs please.
* Assume non-empty strings for strs
* No guarantees for uniqueness of ints

Sample C++ program (limited at 20 because I'm lazy):

```
#include <iostream>
#include <string>
using namespace std;

int main() {
  string names[20];
  int mods[20], n, max;
  cin >> max >> n;
  for (int i=0; i<n; i++) {
    cin >> mods[i] >> names[i];
  }
  for (int i=1; i<=max; i++) {
    bool found = false;

    for (int j=0; j<n; j++) {
      if (i % mods[j] == 0) {
        found = true;
        cout << names[j];
      }
    }
    if (!found)
     cout << i;
    cout << endl;
  }

  return 0;
}

```

# Answer
# 05AB1E, 28 bytes

```
#¦¤U¨2ôøVXLvY`sysÖÏJDg1‹iy},

```

Try it online!

**Or with a different input format:**

# 05AB1E, 16 bytes

```
Lv²y³ÖÏJDg1‹iy},

```

Try it online!
> 3 votes

# Answer
## JavaScript (ES6), 90 bytes

Generates a leading newline.

```
f=(a,i=a.pop())=>i?f(a,i-1)+`
`+(a.map((_,j)=>++j>a[0]|i%a[j*2-1]?'':a[j*2]).join``||i):''

```

### Test

```
f=(a,i=a.pop())=>i?f(a,i-1)+`
`+(a.map((_,j)=>++j>a[0]|i%a[j*2-1]?'':a[j*2]).join``||i):''

console.log(f([3, 2, 'Fizz', 3, 'Buzz', 5, 'Crackle', 10]))
console.log(f([3, 3, 'Buzz', 2, 'Fizz', 5, 'Crackle', 10]))
```
> 4 votes

# Answer
# Python 2, 98 bytes

```
lambda b:[''.join(''if x%b[1+i*2]else b[2+i*2]for i in range(b[0]))or`x`for x in range(1,b[-1]+1)]

```

Try it online!
> 2 votes

# Answer
# C++, 194 bytes

```
#include <iostream>
#define p std::cout<<
int main(int c,char**a){c=2*atoi(a[1])+2;int x,f,i,n=atoi(a[c]);for(x=1;x<=n;x++){f=0;for(i=2;i<c;i+=2)if(x%atoi(a[i])<1)f=1,p a[i+1];if(!f)p x;p'\n';}}

```

Ungolfed:

```
#include <iostream>

int main(int c, char **a) {
    c = 2 * atoi(a[1]) + 2;
    int x, f, i, n = atoi(a[c]);
    for (x = 1; x <= n; x++) {
        f = 0;
        for (i = 2; i < c; i += 2)
            if (x % atoi(a[i]) < 1) f = 1, std::cout << a[i+1];
        if (!f) std::cout << x;
        std::cout << '\n';
    }
}

```
> 1 votes

# Answer
# PHP, 99 bytes

Based on primo´s FizzBuzz answer: `õ` is chr(245), a bit inverted newline.

```
for(;$i++<($a=$argv)[$z=$argc-1];){for($k=$s="";$z>$k+=2;)$s.=[$a[$k+1]][$i%$a[$k]];echo$s?:$i,~õ;}

```

ignores the first argument; run with `-nr`.
> 1 votes

# Answer
# JavaScript (ES6), ~~105~~ 97 bytes

```
g=(m,k,i=1)=>i<-~k?([...m.keys()].filter(j=>i%j<1).map(j=>m.get(j)).join``||i)+"\n"+g(m,k,i+1):""

```

Takes in a map of pairs **m** (integer, string) and an integer **k**. Comes with a trailing newline.

Here's a non-recursive version (105 bytes), but doesn't yield a trailing newline.

```
m=>k=>[...Array(k).keys()].map(x=>[...m.keys()].filter(j=>-~x%j<1).map(j=>m.get(j)).join``||x+1).join`\n`

```

Try it online!
> 0 votes

# Answer
# Java, 331 bytes

Because Java.

```
import java.util.*;class A{A(int c,String x){i=c;v=x;}int i;String v;void x(String[]x){ArrayList<A>l=new ArrayList();int n=0;for(;++n<x.length-1;)l.add(new A(Integer.valueOf(x[n++]),x[n]));n=Integer.valueOf(x[n]);for(int i=1;i++<n;){String o="";boolean y=1>0;for(A a:l)if(i%a.i==0){y=1<0;o+=a.v;}if(y)o+=i;System.out.println(o);}}}

```

This is the full class required for this. However, in order to run it, you must call the method `x` on an existing instance of `A`. For the sake of testing, I have provided a command-line runnable class below, which is partially ungolfed.

```
import java.util.*;
class A{
A(int c,String x){i=c;v=x;}
int i;
String v;
void x(String[]x){
ArrayList<A>l=new ArrayList();
int n=0;
for(;++n<x.length-1;)
l.add(new A(Integer.valueOf(x[n++]),x[n]));
n=Integer.valueOf(x[n]);
for(int i=1;i++<n;){
String o="";
boolean y=1>0;
for(A a:l)if(i%a.i==0){y=1<0;o+=a.v;}
if(y)o+=i;
System.out.println(o);
}
}
public static void main(String[] args) {
new A(0,"").x(args);
}
}

```
> 0 votes

# Answer
# stacked, 85 bytes

```
args rev...2*nsgroup rev 2 chunk@s~>{!s[1#]map s[0#n|]map keep''join:[n]\¬if out}map

```

Try it online! Alternatively, 86 bytes:

```
args behead...@k sgroup 2 chunk@s k~>{!s[1#]map s[0#n|]map keep''join:[n]\¬if out}map

```
> 0 votes

# Answer
# dc, 121 bytes

```
?dstsw?[rdlt:Y:Rlt1-dst0<q]dsqx?sb1sm[ln;Y;RnlP1+sP]ss[lmn]sF[1sn0sP[lnd;Ylmr%0=s1+dsnlw!<g]dsgxlP0=Flm1+dsm10Plb!<i]dsix

```

Takes input on 3 separate lines, the first line containing the integer `n`, the second housing the `int str` tuples with the strings enclosed in square brackets (`[]`), and the third line consists of the integer `k`. For example, `3 2 Fizz 3 Buzz 5 Crackle 10` could be input as:

```
3
3 [Buzz] 2 [Fizz] 5 [Crackle]
10

```

Try it online!

### Or taking input in a different order:

# dc, 118 bytes

```
?dstsw[dlt:Y:Rlt1-dst0<q]dsqxsb1sm[ln;Y;RnlP1+sP]ss[lmn]sF[1sn0sP[lnd;Ylmr%0=s1+dsnlw!<g]dsgxlP0=Flm1+dsm10Plb!<i]dsix

```

This takes input in a different order, but on a single line in the format

```
k [str1] int1 [str2] int2 (...) [strn] intn n

```

For example, `3 2 Fizz 3 Buzz 5 Crackle 10` would be input as:

```
10 [Buzz] 3 [Fizz] 2 [Crackle] 5 3

```

Try it online!
> 0 votes

---
Tags: code-golf, fizzbuzz
---


title: Closest Woodall Prime

text:
# Question
Title: Closest Woodall Prime
A Woodall Prime is a prime which can be calculated, given a positive integer `n`, with `n * 2^n - 1`.

Your task is to, given a integer `k`, generate a Woodall Prime with `k` digits. If no such Woodall Prime exists, you must generate a Woodall Prime with the closest amount of digits. If two primes exist with the same digit count difference, you may use either.

You may assume that there exists no two Woodall Primes with the same amount of digits.

There is no time complexity limit, and you must be able to handle at least the first ten Woodall Primes (you can see them in the OEIS link at the start of the question)

You may write a full program or a function, and you may print or return the output.

### Examples:

```
1 -> 7
4 -> 383
0 -> 7
-100 -> 7
7 -> 383 or 32212254719 (you may pick either of these)
8 -> 32212254719

```

As this is , that shortest code wins!

(there are only nine Woodall Primes on the linked OEIS sequence, so you might want to look at this for more Woodall Primes: https://oeis.org/A002234)

# Answer
# Brachylog, ~~28~~ 26 bytes

```
:K≜+ℕ~lṗ.+₁~×[İ,J]h:2^₍J≜∧

```

Try it online!

This is too slow for TIO for inputs bigger than 4.

### Explanation

```
:K                             The list [Input, K]
  ≜                            Assign a value to K (0, then 1, then -1, then 2, etc.)
   +ℕ                          Input + K >= 0
     ~l .                      Output is a number of length (Input + K)
       ṗ.                      Output must be a prime number
         +₁                    Output + 1...
           ~×[İ,J]             ... = İ × J, İ being an integer...
                  h:2^₍J       ... and J = 2^İ
                         ≜∧    Check that it is possible to find a value for İ that satisfies
                                 all of those constraints. If not, go back to the beginning
                                 and try another value for K through backtracking.

```

We use a common trick in Brachylog for "find the closest X to Y": labeling a completely free variable (which we do when we use  on the list `[Input, K]` will label it with this pattern: `0, 1, -1, 2, -2, 3, ...`. Therefore, when backtracking if the value `Input + K` doesn't work as the number of digits, the next choice we will try will be the next possible closest choice.
> 4 votes

# Answer
# Mathematica, 72 bytes

```
Nearest@<|Thread[w->IntegerLength[w=# 2^#-1&~Array~999~Select~PrimeQ]]|>

```

Pure function taking an integer as input and returning the set of Woodall primes whose lengths are closest to the input. For example, applying this function to `6` results in `{383}`, while applying it to `7` yields `}{383,32212254719}`.

`w=# 2^#-1&~Array~999~Select~PrimeQ` constructs a list of the first 15 Woodall primes, by testing all numbers of the form n\*2^n-1 with n up to 999. `<|Thread[w->IntegerLength[w]]|>` creates an association taking the number of digits of each of these Woodall primes to the primes themselves. Then `Nearest` picks out the Woodall primes whose numbers-of-digits are closest to the input.
> 1 votes

# Answer
# Perl 6,  ~~71~~  68 bytes

```
->\k{({$/ if is-prime $/=2**++$*++$-1}...*.chars>k).min:{abs k-.chars}}

```

Try it

```
{({$/ if is-prime $/=2**++$*++$-1}...*.comb>$^k).min:{abs $k-.comb}}

```

Try it

## Expanded:

```
{         # bare block lambda with parameter ｢$k｣
  (  # sequence of possible candidates

    {
      $/         # use the Woodall number
      if         # but only if
      is-prime(  # this is prime

        $/ =     # store the Woodall number in $/

         2 **    # 2 to the power of
         ++$     # n           ( preincrement of anon state variable )
         *       # times
         ++$     # n           ( preincrement of anon state variable )
         -1      # -1

      )
    }

    ...          # keep generating Woodall primes until:

    *.comb > $^k  # it has more digits than ｢$k｣ (declare ｢$k｣ as a parameter)

  ).min: { abs $k - .comb } # find the nearest one
}

```
> 0 votes

---
Tags: code-golf, sequence, primes
---


# Question
Title: Shortest program to throw NullPointerException in Java
I find `NullPointerException` to be interesting since there are no explicit pointers in Java. Here is a program that throws such an exception.

```
class c {
  public static void main(String[]s) {
    throw new NullPointerException();
  }
}

```

What is the shortest Java program that throws `NullPointerException`?

# Answer
## 62 Bytes (17 byte statement)

-2 bytes thanks to @PeterTaylor.

```
class C{public static void main(String[]s){s=null;s.clone();}}

```

Without knowing about the `throw` trick, this is the first thing that occurred to me. Using the main class's type is the shortest one available, and casting `null` is shorter than declaring `C c=null;`. `notify` is also the shortest method on an object that doesn't throw an exception.
> 4 votes

# Answer
# Java 8 - ~~56~~ 53 bytes (11 byte snippet)

```
interface P{static void main(String[]a){throw null;}}

```

**ideone**

From the documentation:

> ### Class NullPointerException
>
> ...
> Thrown when an application attempts to use null in a case where an object is required. These include:
> ...
>
> * Throwing null as if it were a Throwable value.
> 7 votes

---
Tags: code-golf, java
---