title: 'Plane' the numbers in any base!

text:
# Question
Title: 'Plane' the numbers in any base!
*Inspired by this Numberphile video.*

---

## What is planing?

In order to 'plane' a sequence of digits, you need to:

1. Identify the lengths of the 'runs' (adjacently repeated digits) in the sequence. Non-repeated digits count as runs of one.
2. Decrease the length of each run by one. Runs of length 1 become length 0.
3. Reconstruct the sequence, using the new lengths for the runs. Runs that are now length 0 are deleted altogether.

For example, planing the sequence \\$1, 1, 2, 3, 3, 3, 4, 4, 5, 6\\$ would give us:

1. The length of the runs is demonstrated below:

```
 1  1  2  3  3  3  4  4  5  6
|____||_||_______||____||_||_|
  2    1     3      2    1  1

```
2. Decreasing the length of the runs gives us:

```
            1  1  2  3  3  3  4  4  5  6
           |____||_||_______||____||_||_|
              2   1     3      2    1  1
becomes:      1   0     2      1    0  0

(0s removed): 1  2  1

```
3. Using these lengths to reconstruct the original sequence, e.g. the first run is now length 1, the second length 0, etc., gets us our 'planed' sequence:

```
 1  3  3  4
|_||____||_|
 1   2    1

```

Note that the planing operation can also have a strength: the above example used a strength of \\$1\\$, but a strength of \\$2\\$ would decrease the length of each run by 2, strength \\$3\\$ by 3, etc.. In cases where this would make the length of a run go negative, the length just becomes 0.

E.g. with the above example and a strength of \\$2\\$, we get:

```
Input:       1  1  2  3  3  3  4  4  5  6
            |____||_||_______||____||_||_|
Run lengths:  2    1     3      2    1  1
Lengths - 2:  0   -1     1      0   -1 -1
Rounded to 0: 0    0     1      0    0  0

Output sequence:

 3
|_|
 1

```

## Challenge

Given a limit \\$n\\$, a strength \\$s\\$ and a base \\$b\\$, output the base-10 result of having 'planed' each of the numbers from 1 to \\$n\\$ in base \\$b\\$ with the strength \\$s\\$.

The basic steps to complete this are as follows:

1. Make a list \\$x\\$ of numbers 1 to \\$n\\$, including both 1 and \\$n\\$.
2. Convert each number \\$x\\$ in the list to base \\$b\\$.
3. Treating each digit of the base-\\$b\\$ number as an item of a sequence, plane the sequence with strength \\$s\\$.
4. Reading the sequence as a set of digits (or 0, in case of an empty sequence), convert the planed sequence back from base \\$b\\$ digits to a base 10 number.
5. Output this number and repeat for all values in \\$x\\$.

## Examples

Given \\$b\\$ = 4, \\$n\\$ = 250, and \\$s\\$ = 2:

```
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,5,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,10,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

```

\\$b\\$ = 2, \\$n\\$ = 112, and \\$s\\$ = 3:

```
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,3,7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0]

```

\\$b\\$ = 12, \\$n\\$ = 1024, and \\$s\\$ = 1:

```
[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0,0,7,0,0,0,0,0,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,9,0,0,0,0,0,0,0,0,0,0,0,0,10,0,0,0,0,0,0,0,0,0,0,0,0,11,0,0,0,0,0,0,0,0,0,0,0,0,1,13,1,1,1,1,1,1,1,1,1,1,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0,0,7,0,0,0,0,0,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,9,0,0,0,0,0,0,0,0,0,0,0,0,10,0,0,0,0,0,0,0,0,0,0,0,0,11,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,2,2,26,2,2,2,2,2,2,2,2,2,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0,0,7,0,0,0,0,0,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,9,0,0,0,0,0,0,0,0,0,0,0,0,10,0,0,0,0,0,0,0,0,0,0,0,0,11,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,3,3,3,39,3,3,3,3,3,3,3,3,0,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0,0,7,0,0,0,0,0,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,9,0,0,0,0,0,0,0,0,0,0,0,0,10,0,0,0,0,0,0,0,0,0,0,0,0,11,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,4,4,4,4,52,4,4,4,4,4,4,4,0,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0,0,7,0,0,0,0,0,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,9,0,0,0,0,0,0,0,0,0,0,0,0,10,0,0,0,0,0,0,0,0,0,0,0,0,11,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,4,0,0,0,0,0,0,0,5,5,5,5,5,65,5,5,5,5,5,5,0,0,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0,0,7,0,0,0,0,0,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,9,0,0,0,0,0,0,0,0,0,0,0,0,10,0,0,0,0,0,0,0,0,0,0,0,0,11,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,6,6,6,6,6,6,78,6,6,6,6,6,0,0,0,0,0,0,0,7,0,0,0,0,0,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,9,0,0,0,0,0,0,0,0,0,0,0,0,10,0,0,0,0,0,0,0,0,0,0,0,0,11,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0]

```

## Rules

* This is , so the shortest code in bytes wins.
* Standard loopholes apply.
* I/O may be taken/given in any acceptable, valid format. Each number in the sequence should be delimited in some way by a non-numeric digit, but the precise delimiting is up to you.
* You may assume \\$b\>1\\$, \\$n\>1\\$, and \\$s\>0\\$. You may also assume reasonable upper bounds for these, depending on the capacity for number types in your language.
* If you wish, input arguments may have an offset (e.g. an input of \\$1\\$ to \\$b\\$ represents base 2), but this must be stated in your answer and should not impede the ability of your code to cover the whole range of allowed inputs.
* Output may be given as floats, ints, strings, etc., but all values must represent a numeric, base-10 value - so e.g. no `NaN`s in place of 0s.

### Test code

For reference, here is the (shoddily-written and ungolfed) code I used to generate the above examples (in console JS):

```
// called as f(length, base, strength)
const f = (l, b, s) => {
    return JSON.stringify(
        Array(l)
        .fill(0)
        .map((e, i) => i + 1)
        .map(e =>
            e.toString(b)
            .split('')
            .reduce((a, e, i, A) => (A[i - 1] && A[i - 1] === e) ?
                [...a.slice(0, -1), [a.slice(-1)[0][0], a.slice(-1)[0][1] + 1]] :
                [...a, [e, 1]], [])
            .map(e => [e[0], Math.max(0, e[1] - s)])
            .map(e => e[0].repeat(e[1]))
            .join('')
        )
        .map(e => parseInt(e, b) || 0),
        null,
        1
    )
}

```

Note that this implementation is not a complete/valid one, as it only works for \\$b \le 36\\$. As per the instructions, complete answers should be able to handle any base in theory, up to the integer limit of your language.

# Answer
> 7 votes
# Japt, 11 bytes

*How* is Japt winning this (so far) despite the need for an essentially unnecessary byte in the `,`? It's making me feel like I've done something wrong!

```
õÈìV,ÈòÎcsW

```

Try it

```
õÈìV,ÈòÎcsW     :Implicit input of integers U=n, V=b & W=s
õ               :Range [0,U]
 È              :Map
  ìV            :  Convert to base V digit array
    ,           :  Does nothing (more accurately, prevents the V from becoming the first parameter of the next function)
     È          :  Pass through the following function and convert back to decimal
      ò         :    Partition between elements where
       Î        :      The sign of their difference is truthy (not zero)
        c       :    Flat map
         sW     :      Slice off the first W elements

```

Or, to avoid that pesky comma, we can reverse the second 2 inputs and do this, where  is the last element of the array of all inputs:

```
õÈìNÌÈòÎcsV

```

Try it

# Answer
> 4 votes
# Vyxal, ~~14~~ 12 bytes

```
ɾvτƛ⁰nĠvȯf¹β

```

Try it Online!

```
ɾ            # 1...n
 vτ          # Foreach, base convert
   ƛ         # Foreach...
    ⁰        # Strength
     nĠ      # Each one grouped
       vȯ    # Trim each
         f   # Flatten
          ¹β # Convert back

```

# Answer
> 4 votes
# APL (Dyalog Extended), ~~32~~ 23 bytes (SBCS)

Full program. Prompts for \\$n\\$ then \\$s\\$, then \\$b\\$.

```
∊⎕(⊣⊥∘∊⎕↓¨⊤⊂⍨1,2≠/⊤)¨⍳⎕

```

Try it online!

prompt for \\$n\\$

generate \\$x\\$, the **i**ndices 1 through \\$n\\$

`⎕(` establish the following tacit function, then apply it using each element of \\$x\\$ as right argument, and a prompted-for \\$b\\$-value as left argument:

encode \\$x\_i\\$ in base \\$b\\$

`2≠/` pairwise difference

`1,` prepend 1, giving a mask of starting positions of runs

`⊤⊂⍨` use that to partition \\$x\_i\\$ re-encoded in base \\$b\\$

`⎕↓¨` prompt for \\$s\\$ and use that to drop the first that many elements from each run

`∘∊` enlist (flatten), then:

`⊣⊥` evaluate in base \\$b\\$

enlist (flatten)

# Answer
> 4 votes
# 05AB1E, 12 bytes

```
LIвεγIδ.$˜²β

```

Try it online!

```
L             # push range [1 .. n]
 Iв           # convert each number to base b (represented as lists of digits)
   ε          # for each list of digits:
    γ         #   group equal adjacent digits
     Iδ.$     #   remove s digits from each group
         ˜    #   flatten into a single list of digits
          ²β  #   convert back from base b

```

# Answer
> 4 votes
# , ~~107~~ 104 bytes

```
function(x,b,s)Map(function(n,l=0:n,r=rle(n%/%b^l%%b))sum(rep(r$v,t<-pmax(r$l-s,0))*b^(1:sum(t)-1)),1:x)

```

Try it online!

Goes out-of-range for the last test-case: add +7 bytes to extend the range of amenable calculations and fix this.

# Answer
> 4 votes
# Jelly, 12 bytes

```
Ḋ¡€F
b€ŒgÇ€ḅ

```

Try it online!

## How it works

```
Ḋ¡€F - Helper link. Takes a list of grouped digits D
  €  - Over each group:
 ¡   -   Do the following S times:
Ḋ    -     Dequeue; remove the first element
   F - Flatten

b€ŒgÇ€ḅ - Main link. Takes n on the left and b on the right
b€      - Convert each integer 1 to n to base b
  Œg    - Over each, group adjacent equal digits
    Ç€  - Run the helper link over each list of groups
      ḅ - Convert each back from base b

```

# Answer
> 3 votes
# JavaScript (ES6), 92 bytes

*Saved 1 byte thanks to @Shaggy*

Expects `(b)(s)(n)`.

```
b=>s=>F=n=>n?[...F(n-1),(t=0,p=g=x=>x?g(x/b|0,x%=b,x==p?k++:k=1,p=x,k>s?t=t*b+x:0):t)(n)]:[]

```

Try it online!

### Commented

```
b => s =>               // outer functions taking b and s
F = n =>                // F = inner recursive function taking n
n ?                     // if n is not equal to 0:
  [ ...F(n - 1),        //   do a recursive call to F with n - 1
    (                   //   and append the next value to the array:
      t = 0,            //     t = final value converted back from base b
      p =               //     p = previous term in the sequence
      g = x =>          //     g is a recursive function taking x
        x ?             //       if x is not equal to 0:
          g(            //         do a recursive call to g ...
            x / b | 0,  //           ... using floor(x / b)
            x %= b,     //           reduce x modulo b
            x == p ?    //           if it's equal to the previous term:
              k++       //             increment k
            :           //           else:
              k = 1,    //             reset k to 1
            p = x,      //           update the previous term p to x
            k > s ?     //           if k is greater than the strength:
              t = t * b //             update t to t * b + x
                  + x   //             (i.e. add the digit x in base b)
            :           //           else:
              0         //             do nothing
          )             //         end of recursive call
        :               //       else (x = 0):
          t             //         return t
    )(n)                //     initial call to g with x = n
  ]                     //   end of array
:                       // else (n = 0):
  []                    //   stop the main recursion

```

# Answer
> 3 votes
# K (ngn/k), 28 bytes

```
{(y/*'(1=#'?:')#z':y\)'1+!x}

```

Try it online!

Takes three arguments: `n => x`, `b => y`, and `s => z`. `s` needs to be offset by +1 (i.e. to apply a strength of `2`, pass in `3`).

* `(...)'1+!x` call the code in parenthesis on each value from `1..n`
* `y\` convert each value to base `b`, returning a list of digits
* `z':` take `s`-length rolling windows of the converted digits
* `(1=#'?:')#` filter out rolling windows containing more than one distinct digit
* `*'` take the first digit of each remaining rolling window
* `y/` convert back to original base

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

```
b€Œr_⁵Ż¤Œṙḅ

```

Try it online!

Takes three arguments in the form `n b [s]`.

*-1 byte thanks to @cairdcoinheringaahing*

## Explanation

```
b€Œr_⁵Ż¤Œṙḅ   Main dyadic link
b€            Convert each to base b (implicitly casting n to [1..n])
  Œr          Run-length encode
    _         Subtract [vectorized]
       ¤        (
     ⁵            The third argument
      Ż           Prepend a 0
       ¤        )
        Œṙ    Run-length decode
          ḅ   Convert from base b

```

# Answer
> 1 votes
# Scala, 155 bytes

```
b=>s=>1.to(_)map{y=>(0+:Seq.unfold(y){q=>Option.when(q>0)(q%b,q/b)}:\(0,0,0)){case(d,(c,p,a))=>if(d==p)(c+1,d,a)else(1,d,(a/:Seq.fill(c-s)(p))(_*b+_))}._3}

```

Try it in Scastie!

It's been a while since I wrote an answer as complex as this. Takes `(b)(s)(n)`. Explanation coming soon.

Ungolfed:

```
b => s => n =>
//Make a range [1,n]
1.to(n) map { y => //Perform these operations on each y
  //Build a list of digits in base b (reversed)
  val toBaseB = Seq.unfold(y) { //Start with y as the quotient
    q =>                        //q is the quotient at each iteration
      //If q is still greater than 0, add another digit
      Option.when(q > 0)(
        q % b,   //The next digit is q mod b
        q / b    //The next quotient is the floor of q÷b
      )
  }
  //Plane and convert back to decimal here
  ((0 +: toBaseB) //First prepend a 0 so that the last digit of toBaseB is counted
    :\ (0, 0, 0) //First accumulator (count 0, prev item 0, sum 0)
  ) {
    //d is the current digit, p is the previous digit,
    //c is the current run length,
    //and a is the sum (partially converted to decimal)
    case (d, (c, p, a)) =>
      if (d == p)     //If the run's still going
        (c + 1, d, a) //Increase the run length
      else            //Otherwise
        (1, d,        //Set the run length to 1 and set p to the new d
          //Add the current run to the sum
          //Make a sequence of (c-s) p's
          //Convert to decimal, and add the previous sum (a) to that
          (a /: Seq.fill(c - s)(p))(_ * b + _)
        )
  }._3 //Only get the sum (planed sequence converted to decimal)
}

```

# Answer
> 1 votes
# Jelly, 14 bytes

```
RbŒgṫ⁵$Ḋ$€F$€ḅ

```

Try it online!

```
RbŒgṫ⁵$Ḋ$€F$€ḅ  Main Link; takes [n, b, s]
R               Range from 1 to n
 b              Base convert (each) into base b
  Œg            Group equal runs (vectorizes)
    (    )-$€   For each number
    ( )-$       - For each run
    ṫ⁵$           - Tail; remove the first s-1 items
       Ḋ          - Dequeue; remove the first element
          F     - Flatten
             ḅ  Convert (each) back from base b

```

# Answer
> 1 votes
# Husk, 11 bytes

```
möB⁰ṁ↓²gB⁰ḣ

```

Try it online!

```
m           # map the following function
          ḣ # across all the integers from 1 to arg3
            # the 'plane' function:
 ö          # composition of 4 commands
        B⁰  # get the digits in base arg2
       g    # group equal values
    ṁ↓²     # drop the first arg1 elements from each group, and flatten
  B⁰        # interpret as digits in base arg2

```

# Answer
> 0 votes
# Charcoal, 31 bytes

```
ＮθＮηＩＥＥＮ↨⊕ιη↨Φι∧¬‹μθ⬤…⮌…ιμθ⁼νλη

```

Try it online! Link is to verbose version of code. Takes inputs in the order `s`, `b`, `n`. Explanation:

```
ＮθＮη

```

Input `s` and `b`.

```
   Ｎ                        Input `n`
  Ｅ                         Map over implicit range
     ⊕ι                     Current index, 1-indexed
    ↨  η                    Convert to base `b`
 Ｅ                          Map over list
          ι                 Current base conversion
         Φ                  Filtered where
              μ             Current position
            ¬‹ θ            Is not less than `s`
           ∧                Logical And
                 …⮌…ιμθ     Last `s` elements
                ⬤           All satisfy
                        ν   Inner element
                       ⁼    Equal to
                         λ  Outer element
        ↨                 η Convert from base `b`
Ｉ                           Cast to string
                            Implicitly print each result on its own line

```

---
Tags: code-golf, number, sequence, base-conversion
---


# Question
Title: Number of Straight-Chain Alk*nes of given length
A straight-chain alk\*ne is defined as a sequence of carbon atoms connected by single (alkane), double (alkene), or triple bonds (alkyne), (implicit hydrogens are used.) Carbon atoms can only form 4 bonds, so no carbon atom may be forced to have more than four bonds. A straight-chain alk\*ne can be represented as a list of its carbon-carbon bonds.

These are some examples of valid straight-chain alk\*nes:

```
[]       CH4              Methane
[1]      CH3-CH3          Ethane
[2]      CH2=CH2          Ethene
[3]      CH≡CH            Ethyne
[1,1]    CH3-CH2-CH3      Propane
[1,2]    CH3-CH=CH2       Propene
[1,3]    CH3-C≡CH         Propyne
[2,1]    CH2=CH-CH3       Propene
[2,2]    CH2=C=CH2        Allene (Propadiene)
[3,1]    CH≡C-CH3         Propyne
[1,1,1]  CH3-CH2-CH2-CH3  Butane
...

```

While these are not, as at least one carbon atom would have more than 4 bonds:

```
[2,3]
[3,2]
[3,3]
...

```

Your task is to create a program/function that, given a positive integer `n`, outputs/returns the **number** of valid straight-chain alk\*nes of exactly `n` carbon atoms in length. This is OEIS A077998.

# Specifications/Clarifications

* You must handle `1` correctly by returning `1`.
* Alk\*nes like `[1,2]` and `[2,1]` are considered distinct.
* Output is the *length* of a list of all the possible alk\*nes of a given length.
* You do *not* have to handle 0 correctly.

# Test Cases:

```
1 => 1
2 => 3
3 => 6
4 => 14

```

This is code golf, so lowest *byte* count wins!

# Answer
> 7 votes
# Oasis, ~~9~~ 7 bytes

```
xcd-+3V

```

Try it online!

### Explanation

This uses the recurrence relationship in OEIS:

> a(n) = 2\*a(n-1) + a(n-2) - a(n-3)

```
x    Multiply a(n-1) by 2: gives 2*a(n-1)
c    Push a(n-2)
d    Push a(n-3)
-    Subtract: gives a(n-2) - a(n-3)
+    Add: gives 2*a(n-1) + a(n-2) - a(n-3)
3    Push 3: initial value for a(n-1)
V    Push 1, 1: initial values for a(n-2), a(n-3)

```

# Answer
> 9 votes
# MATL, 10 bytes

```
7K5vBiY^1)

```

Try it online!

### Explanation

This uses the characterization found in OEIS

> a(n) is the top left entry of the n-th power of the 3 X 3 matrix \[1, 1, 1; 1, 0, 0; 1, 0, 1\]

```
7    % Push 7
K    % Push 4
5    % Push 5
v    % Concatenate all numbers into a column vector: [7; 4; 5]
B    % Convert to binary: gives 3×3 matrix [1, 1, 1; 1, 0, 0; 1, 0, 1]
i    % Input n
Y^   % Matrix power
1)   % Take the first element of the resulting matrix, i.e. its upper-left corner.
     % Implicitly display

```

# Answer
> 6 votes
# Oasis, ~~9~~ 8 bytes

Saved a byte thanks to *Adnan*

```
xc+d-63T

```

Try it online!

**Explanation**

```
a(0) = 0
a(1) = 1
a(2) = 3
a(3) = 6

a(n) = xc+d-

x         # calculate 2*a(n-1)
 c        # calculate a(n-2)
  +       # add: 2*a(n-1) + a(n-2)
   d      # calculate a(n-3)
    -     # subtract: 2*a(n-1) + a(n-2) - a(n-3)

```

# Answer
> 4 votes
# MATL, 14 bytes

```
q3:Z^TTZ+!5<As

```

Try it online!

### Explanation

This generates the Cartesian power of `[1 2 3]` "raised" to the number of atoms minus 1, and then uses convolution to check that no two contiguous numbers in each Cartesian tuple sum more than `4`.

```
q    % Take number of atoms n implicitly
3:   % Push [1 2 3]
Z^   % Cartesian power. Gives a matrix with each (n-1)-tuple on a row
TT   % Push [1 1]
Z+   % 2D convolution. For each tuple this gives the sum of contiguous numbers
5<   % For each entry, gives true if less than 5
!    % Transpose
A    % True if all elements of each column are true. Gives a row vector
s    % Sum of true results. Implicitly display

```

# Answer
> 4 votes
# Jelly, 10 bytes

```
745DBæ*µḢḢ

```

Try it online!

Uses Luis Mendo's algorithm.

### Explanation

```
745DBæ*µḢḢ    Main link. Argument: n
745D          Get the digits of 745
    B         Convert each to binary
     æ*       Matrix power
        ḢḢ    First element of first row

```

## Jelly, 15 bytes

```
3Rṗ’µ+2\<5PµÐfL

```

Try it online!

Uses brute force.

### Explanation

```
3Rṗ’µ+2\<5PµÐfL    Main link. Argument: n
3R                 Start with [1, 2, 3]
   ’               Take the (n-1)'th
  ṗ                Cartesian power
            Ðf     Filter on:
     +2\             Sums of overlapping pairs
        <5           1 for sums < 5, 0 otherwise
          P          Product: 1 if all pairs < 5
              L    Length

```

# Answer
> 3 votes
## Mathematica, 48 bytes

```
MatrixPower[{{1,1,1},{1,0,0},{1,0,1}},#][[1,1]]&

```

As Luis Mendo pointed out, this is A006356 in the OEIS. Here are my original attempts:

```
Count[Length@Split[#,+##<5&]&/@Tuples[{1,2,3},#-1],0|1]&

```

For an input `n`, `Tuples[{1,2,3},n-1]` is the list of all `(n-1)`-tuples of elements in `{1,2,3}` representing all possible sequences of single, double, or triple bonds for `n` carbon atoms. `+##<5&` is a pure function which returns whether the sum of its arguments is less than `5`, so `Split[#,+##<5&]&` splits a list into sublists consisting of consecutive elements whose pairwise sums are less than `5`. Describing a valid alk\*ne is equivalent to this list having length `0` (in the case where `n=1`) or `1`, so I just `Count` the number of `(n-1)`-tuples where the length of that list matches `0|1`.

```
Count[Fold[If[+##>4,4,#2]&]/@Tuples[{1,2,3},#-1],Except@4]&

```

`If[+##>4,4,#2]&` returns `4` if the sum of its arguments is greater than `4` and returns the second argument otherwise. `Fold[If[+##>4,4,#2]&]` does a left `Fold` of its input with this function. So here I `Count` the number of `(n-1)`-tuples to which applying this operator doesn't give `4`. The case where `n=1` is covered since `Fold` remains unevaluated when its second argument is the empty list `{}`.

# Answer
> 3 votes
# Python, 51 bytes

```
f=lambda n:n<4and(n*n+n)/2or 2*f(n-1)+f(n-2)-f(n-3)

```

This is a straightforward implementation of the recurrence relation. Thanks to Tim Pederick for 3 bytes. The output is a float in Python 3 and an integer in Python 2.

Try it online!

# Answer
> 2 votes
# Pyth - 16 bytes

Uses brute force.

```
lf.AgL4+VTtT^S3t

```

Test Suite.

# Answer
> 2 votes
# Dyalog APL, 30 bytes

```
{⍵<3:⍵⌷1 3⋄+/∧/¨4≥2+/¨,⍳1↓⍵/3}

```

Uses brute force. Explanation (my best attempt at one, at least):

```
⍵<3:⍵⌷1 3 - if ⍵ (function arg) is 1 (case 1) or 2 (case 2), return 1 (case 1) or 3 (case 2)
⋄ - separate statements
⍵/3 - otherwise, 3 repeated ⍵ times
1↓ - without the first element
⍳ - the matrix of possible indices of a matrix of that size
,  - ravel, return a list of all the elements of the matrix
2+/¨ - sum of each contiguous pair on each element
4≥ - tests whether each element is less than or equal to 4
∧/¨ - all elements are true, applied to each item.
+/ - Sum.

```

# Answer
> 2 votes
# Ruby, 62 bytes

```
->n{c=0
(10**n/10).times{|i|"#{i}#{i*11}"=~/[3-9]/||c+=1}
c}

```

Horribly inefficient base 10 brute force approach. Could be improved to base 5 for additional bytes.

Numbers are generated where each digit represents a bond (n-1 digits.) `0` represents a bond order of 1, `2` represents a bond order of 3. Digits over 2 are invalid.

We multiply this by 11 to sum adjacent pair of digits. Again digits over 3 are invalid.

We combine the two numbers in a string and perform a regex to search for invalid digits. If none are found, we increment the counter.

**in test program**

```
f=->n{c=0
(10**n/10).times{|i|"#{i}#{i*11}"=~/[3-9]/||c+=1}
c}

p f[gets.to_i]

```

# Answer
> 2 votes
# Ruby, 51 bytes

```
->n{a=[1,1,3]
n.times{a<<2*a[-1]+a[-2]-a[-3]}
a[n]}

```

Based on the recurrence relation per OEIS A006356.

Starts with an array for elements 0,1 and 2 of the sequence which are 1 (as calculated by me, to make it work), 1 and 3 respectively.

Iteratively adds `n` more elements to the sequence, then returns element `n`. It always calculates 2 elements more than it actually needs to, but it's still linear time, which is way more efficient than my previous answer.

**in test program**

```
f=->n{a=[1,1,3]
n.times{a<<2*a[-1]+a[-2]-a[-3]}
a[n]}

p f[gets.to_i]

```

# Answer
> 2 votes
## Mathematica, ~~42~~ 40 bytes

Byte count assumes a compatible single-byte encoding like CP-1252 (the default on Windows installations).

```
±0=±1=1;±2=3;±n_:=±(n-1)2+±(n-2)-±(n-3);

```

This simply implements the recurrence given on OEIS as a unary operator.

# Answer
> 2 votes
## CJam (19 bytes)

```
{2,{__-2=+1b+}@*W=}

```

Online test suite. This is an anonymous block (function) which takes one item on the stack and leaves one on the stack. Note that the test suite includes `a(0) = 1`.

The recurrence used is based on the observation for the related OEIS sequence A006356:

> Equals the INVERT transform of (1, 2, 1, 1, 1,...) equivalent to a(n) = a(n-1) + 2\*a(n-2) + a(n-3) + a(n-4) + ... + 1. a(6) = 70 = (31 + 2\*14 + 6 + 3 + 1 + 1). - Gary W. Adamson, Apr 27 2009

but with the appropriate offset, which removes the need for the final `+ 1` as now covered by `a(0)`.

### Dissection

```
{         e# Define a block
  2,      e#   Take starting sequence [0 1] (beginning at index -1 for golfiness)
  {       e#   Loop...
    _     e#     Copy sequence so far
    _-2=+ e#     Append an extra copy of a(n-2)
    1b    e#     Sum
    +     e#     Append
  }@*     e#   ...n times
  W=      e#   Take the final value from the sequence
}

```

# Answer
> 2 votes
# Brain-Flak, 56 bytes

Uses the algorithm detailed in the first comment on the OEIS page.

Try it online!

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

```

## Explanation

The sequence can be defined as such:

```
For u(k), v(k), and w(k) such that
u(1) = v(1) = w(1) = 1
u(k+1) = u(k) + v(k) + w(k)
v(k+1) = u(k) + v(k)
w(k+1) = u(k)
u(k) is the number of straight-chain alk*nes with length k

```

The program starts at `1` and repeatedly applies this recurrence to calculate `u(k)`

### Annotated Code (actual annotation to come)

```
# Setup: decrement the input by one and push three 1's to the stack under it
({}[()]<(((())))>)

# Calculation:
{                          }           # While the input is not zero (main loop)
 ({}[()]                  )            # Pop the counter decrement it by one and push it
        <                >             # Before the counter gets pushed back to the stack...
         {            }                # Loop while the top of the stack is not zero (subloop)
          (        )                   # Push...
           {}                          # The top of the stack (popped)...
             <>                        # to the other stack...
               ({})                    # plus the top of the other stack (peeked)
                    <>                 # Switch back to the first stack.
                       <>              # Switch to the other stack
                            {}         # Pop the input (now zero)
                              (      ) # Push...
                               {}      # The top of the stack (u(k))...
                                 <>    # to the other stack...
                                   {}  # plus the top of the other stack (zero).

```

### Visualization of the stacks

In one iteration of the main loop this is what happens (note that the zeros may or may not be present but it does not matter either way):

```
Start of main loop iteration/subloop first iteration:
A    B

u
v
w
0    0
^

After first subloop iteration:
A    B

v
w    u
0    0
^

After second subloop iteration:
A    B

    u+v
w    u
0    0
^

After third subloop iteration (top of stack is zero so subloop terminates):

A    B

   u+v+w
    u+v
     u
0    0
^

End of main loop iteration:
A    B

   u+v+w
    u+v
     u
0    0
     ^

```

The state of the stacks is now the same as it was at the start of the loop except that the current stack now has the next values for `u`, `v`, and `w` on it.

# Answer
> 2 votes
## Perl 6, 48

```
{my @a=1,0,0;@a=reverse [\+] @a for 1..$_;@a[0]}

```

Originally

```
sub f {$_>2??2*f($_-1)+f($_-2)-f($_-3)!!(1,1,3)[$_]}

```

but I forgot I needed the `sub f` so the iterative solution wins out.

# Answer
> 1 votes
# Dyalog APL, 29 bytes

```
{⍵<4:⍵⌷1 3 6⋄+/2 1 ¯1×∇¨⍵-⍳3}

```

Works by using the recursive definition of the integer sequence OEIS A006356.

# Answer
> 1 votes
# Python with Numpy, 62 bytes

I had to try it, but it seems pure Python and recursion is shorter than numpy and the explicit, matrix-based calculation on the OEIS page.

```
from numpy import*
lambda n:(mat('1 1 1;1 0 0;1 0 1')**n)[0,0]

```

# Answer
> 1 votes
# R, ~~61~~ ~~58~~ ~~55~~ ~~51~~ 50 bytes

Takes input from stdin, uses matrix exponentiation to determine exact result.

```
el(expm::`%^%`(matrix(!-3:5%in%2^(0:2),3),scan()))

```

If you prefer a recursive solution, here's a straightforward implementation of the recurrence relation listed in OEIS, for **55 bytes**.

```
f=function(n)`if`(n<4,(n*n+n)/2,2*f(n-1)+f(n-2)-f(n-3))

```

# Answer
> 1 votes
# Excel, 123 bytes

Implements the formula from OEIS:

```
=4*(SIN(4*PI()/7)^2*(1+2*COS(2*PI()/7))^A1+SIN(8*PI()/7)^2*(1+2*COS(4*PI()/7))^A1+SIN(2*PI()/7)^2*(1+2*COS(8*PI()/7))^A1)/7

```

As always, input in `A1`, formula in any other cell.

Dug up old Trig identities to see if could be helpful. Now my head hurts.

# Answer
> 0 votes
## Lithp, 79 bytes

```
#N:(((if(< N 4)((/(+ N(* N N))2))((-(+(* 2(f(- N 1)))(f(- N 2)))(f(- N 3)))))))

```

Implements recursive integer sequence listed in OEIS.

Readable implementation and test suite.

```
% alkaline.lithp
% run with: ./run.js alkaline.lithp
(
    (def f #N : ((
        (if (< N 4) (
            (/ (+ N (* N N)) 2)
        ) (else (
            (- (+ (* 2 (f (- N 1))) (f (- N 2))) (f (- N 3)))
        )))
    )))

    % Test cases 1 to 4
    (import lists)
    (each (seq 1 4) #I :: ((print (f I))))
)

```

# Answer
> 0 votes
# MMIX, 44 bytes (11 instrs)

If passed 0, returns \\$A077998(2^{64})\\$ (if the computer doesn't break down).

Works mod \\$2^{64}\\$.

(jxd)

```
00000000: e3010001 e3020001 e3030003 27000001  ẉ¢¡¢ẉ£¡¢ẉ¤¡¤'¡¡¢
00000010: 28ff0302 26ffff01 c1010200 c1020300  (”¤£&””¢Ḋ¢£¡Ḋ£¤¡
00000020: c103ff00 5b00ffb5 f8020000           Ḋ¤”¡[¡”Ọẏ£¡¡

```

Disassembly and explanation:

```
alkns   SET   $1,1          // a(0)
        SET   $2,1          // a(1)
        SET   $3,3          // a(2)
0H      SUBU  $0,$0,1       // loop: n--
        2ADDU $255,$3,$2    // a' = 2a + a`
        SUBU  $255,$255,$1  // - a``
        SET   $1,$2         // a`` = a`
        SET   $2,$3         // a` = a
        SET   $3,$255       // a = a'
        PBNZ  $0,0B         // if(n) goto loop
        POP   2,0           // return a

```

---
Tags: code-golf, combinatorics, chemistry
---


# Question
Title: Write a hello world GUI program that closes itself after three seconds
Please read the rules, **and the bold areas as well**.

Write a program in any language, so long as it has GUI support for a window system (cannot be text-consoles, etc., and must be a GUI/toolkit/window).

The program must say hello world in any manner (splash image, menu bar, status bar, title, video, message box, other widget stuff, etc.), **so long as a GUI-compliant window appears and shows this text for three seconds**. The person who can code this in the least amount of code used, counted in bytes, will take the cake.

# Answer
# Unix shell, 31 characters

```
xmessage -timeout 3 hello world

```

This program requires the xmessage(1) utility from X.Org. It uses the traditional black-and-white X Athena Widgets (Xaw).
> 29 votes

# Answer
# Shell and gedit - 27 characters

```
timeout 3 gedit Hello World

```

>

If Hello World needs to be displayed as a single string, then its **28** characters:

```
timeout 3 gedit Hello\ World

```

`timeout` utility runs a command for the duration specified. It ensures that gedit runs for 3 seconds, assuming minimal startup time.

Any editor can be used in place of `gedit`. If a shorter named editor is used like `gvim`, the length can be reduced by 1 or more characters.

Using an editor initially thought of by user80551.
> 24 votes

# Answer
# Applescript, 45 bytes:

Not often Applescript is one of the shorter answers:

```
display alert "hello world" giving up after 3

```

Paste into the Applescript Editor and run, or run using `osascript` at the command line:

```
osascript -e 'display alert "hello world" giving up after 3'

```
> 20 votes

# Answer
# HTML+Javascript, 73 60 characters

```
<script>setTimeout("open('','_self','');close()",3e3)</script>Hello world

```

This works in Chrome, but may not be portable to other browsers.

Suggestions from the comments take this further:

```
<body onload=open('',name=setTimeout(close,3e3))>Hello world

```
> 17 votes

# Answer
## shell script, 31

Not sure whether it qualifies. Requires `notify-send`. Works at least on Ubuntu 12.04.

```
notify-send -t 3000 Hello world

```
> 16 votes

# Answer
## shell + gedit / geany, 34

```
gedit Hello\ World&sleep 3;kill $!

```

This assumes that gedit pops up instantly since the 3 seconds are counted from the start of issuing the command. Could be smaller if there's a GUI text editor shorter than `gedit`.

`geany` works too for the same number of chars, just `s/gedit/geany/g`

EDIT: Using `timeout` is shorter. https://codegolf.stackexchange.com/a/28477/8766

EDIT2: Can anyone confirm if this works with `kate` ?

---

## meld , 32

If exactly `Hello World` is not required, then `meld` can be used.

```
meld Hello World&sleep 3;kill $!

```
> 12 votes

# Answer
## VBScript, 58

```
WScript.CreateObject("WScript.Shell").Popup"Hello world",3

```
> 7 votes

# Answer
## Python (pygame), 87

```
import pygame.display as d,time
d.set_mode()
d.set_caption('Hello world')
time.sleep(3)

```
> 6 votes

# Answer
## Tcl - 32 bytes

I noticed that some of these submissions, like the shell or javascript ones, allow you to type the code into the console. If that's the case I can shorten it to:

```
wm ti . hello\ world;af 3000 exi

```

Must be typed into the console **after** running wish. Meaning, run `wish` without arguments which will give you a REPL console and then type the code above. This makes use of the fact that tcl can be lenient and autocomplete command/function names but only in interactive mode. So that `af` actually exectues the `after` command and `exi` executes `exit`. I wanted to use `ex` but my system has the `ex` editor installed.

---

## Original submission - 36 bytes

```
wm ti . hello\ world;after 3000 exit

```

Run using `wish` instead of `tclsh`.
> 6 votes

# Answer
## ~~52~~ 51 chars with Mathematica

(Hope it counts as a GUI-compliant.)

```
NotebookClose/@{CreateDialog@"Hello world",Pause@3}

```
> 5 votes

# Answer
# Java, 136 bytes

```
class F{public static void main(String[]a)throws Exception{new java.awt.Frame("Hello World").show();Thread.sleep(3000);System.exit(0);}}

```

Displays the message `Hello World` as the title of a frame. After `3` seconds, the program closes.

Looks like this:

Drag it bigger:

---

Expanded code (ie readable):

```
class F {

    public static void main(String[] a) throws Exception {
        new java.awt.Frame("Hello World").show();
        Thread.sleep(3000);
        System.exit(0);
    }

}

```
> 4 votes

# Answer
## R, 44

```
x11(ti="Hello World");Sys.sleep(3);dev.off()

```
> 4 votes

# Answer
## PowerShell - 63 52

```
(new-object -c wscript.shell).popup('Hello World',3)

```
> 4 votes

# Answer
# GTK+, ~~47~~ 45

```
zenity --info --text=Hello\ World --timeout=3

```

---

Old version (score 47):

```
zenity --info --title="Hello World" --timeout=3

```

For some reason, zenity display a text which can be translated as *All update are done*.
> 4 votes

# Answer
# Visual FoxPro - 23 characters

```
WAIT"hello world"TIME 3

```

This abuses the fact that VFP allows to not to put a space between the string to be printed (which I just discovered) and that it allows to shorten every keyword to up to its first 4 characters.

Ungolfed version:

```
WAIT "hello world" TIMEOUT 3

```
> 4 votes

# Answer
## Batch (24)

```
msg/time:3 * hello world

```

Tested on Windows 7, but should work on any NT-based version of Windows, assuming you have MSG.EXE in your System32 folder.

EDIT: Apparently MSG.EXE is not available by default on home versions of Windows. On Windows 7, for example, this is only available in the Ultimate or Business editions. However, you can copy the file over to your System32 folder and get it to work. (You must also copy over the appropriate MSG.EXE.MUI file to get proper error messages, but my "script" works without them.)

You have to install software for most of these other responses to work, too, so I don't think that should be a disqualifier.
> 4 votes

# Answer
## C, 151 characters

```
#include<allegro.h>
main(){textout_ex(screen,font,"Hello World",0,0,7,set_gfx_mode('SAFE',8,8,install_timer(),
allegro_init()));rest(3e3);}END_OF_MAIN()

```

Not the smallest answer. I like it though.
> 3 votes

# Answer
# C# 101 151

This will for sure not be the shortest answer (since there are already other good answers being way shorter) but codegolf.SE needs a lot more C# contributions in my opinion!

```
using t=System.Threading;class P{static void Main(){using(t.Tasks.Task.Run(()=>System.Windows.MessageBox.Show("hello world"))){t.Thread.Sleep(3000);}}}

```

# C# 121

An alternative based on Bob's answer, but with WPF instead of WinForms:

```
class P{static void Main(){new System.Windows.Window(){Title="hello world"}.Show();System.Threading.Thread.Sleep(3000);}}

```

Saves 3 characters thanks to the shorter namespace ...
> 3 votes

# Answer
## bash + ImageMagick (36 bytes)

```
timeout 3 display label:Hello\ world

```

Tested on Ubuntu 14.04 LTS and on Fedora 20.

Nicer-looking, but 10 bytes larger:

```
timeout 3 display -size 800 label:Hello\ world

```
> 3 votes

# Answer
## CMD / Batch - 33 Bytes

I believe the window that the Windows CMD terminal runs in counts as GUI compliant.

```
start "Hello world" cmd /csleep 3

```

If you don't have the `sleep` command on your system - then you can use `timeout` which comes default in Windows 7. For two more bytes.

```
start "Hello world" cmd /ctimeout 3

```

Starts a new CMD window with the title "Hello World" (**NOT** displayed in the terminal itself, but as the title of the GUI window that the terminal runs in), this window will close as soon as all parsed commands have executed - so after `sleep 3` or `timeout 3` has completed.

The window looks like this -

Note; `start` runs the given commands in a new window - not the window that you are running the above commands from.
> 3 votes

# Answer
# Autohotkey, 22 Bytes

```
msgbox,,hello world,,3

```

Ahk's msgbox is pretty powerful and has a built-in timeout option.
> 3 votes

# Answer
# Red, 49 bytes

```
view[text"hello world"rate 0:0:3 on-time[unview]]

```
> 3 votes

# Answer
## APL (40)

```
X.Close⊣⎕DL 3⊣'X'⎕WC'Form' 'Hello World'

```
> 2 votes

# Answer
## Lua + LÖVE, 67 bytes

```
l=love l.window.setTitle"hello world"l.timer.sleep(3)l.event.quit()

```
> 2 votes

# Answer
## Perl 5, 47

Using Perl/Tk:

```
perl -MTk -e'alarm 3;tkinit-title,"Hello World!";MainLoop'
#     123    45678901234567890123456789012345678901234567

```
> 2 votes

# Answer
# Perl on Windows (56)

```
use Win32;fork?kill+sleep+3,$$:Win32'MsgBox"Hello World"

```
> 2 votes

# Answer
# Processing, 77

```
int x=millis();void draw(){text("Hello world",0,9);if(millis()>x+3e3)exit();}

```

Screenshot:

**Edit 1:** Y position of the text can be 9 instead of 10, like noted by @ace.

**Edit 2:** 3000 can be represented as 3e3 to shave one character off, also noted by @ace
> 2 votes

# Answer
# QML - 98 bytes

Here's the code. Works on all supported platforms (including Android and iOS):

```
import QtQuick 1.0;Text{text:"Hello world";Timer{interval:3000;onTriggered:Qt.quit();running:1>0}}

```
> 2 votes

# Answer
# Rebol View (r3gui), 49

```
view/no-wait[title"hello world"]wait 3 unview/all

```

Ungolfed:

```
view/no-wait [title "hello world"]
wait 3
unview/all

```
> 2 votes

# Answer
# PowerShell, 72 49

```
saps -pa notepad "Hello World"|%{sleep 3;kill $_}

```

Thanks to @joey for continued golfing
> 2 votes

# Answer
### Python with turtle module (69 66 bytes)

```
import turtle as t,time
t.title("Hello World")
t.fd(1)
time.sleep(3)

```

Note that if you run this in an interactive console, you don't need the `t.fd(9)` line. However, for some reason when running this non-interactively, the title doesn't change unless you run the extra line.

### Edit (66 bytes)

```
import turtle as t
t.title("Hello World")
t.ontimer(t.fd(1),3000)

```
> 2 votes

# Answer
# PureBasic, 91 chars

Okay, it's not the shortest, it will never win, but I still gotta support my favourite BASIC dialect :-)

```
OpenWindow(0,9,9,99,99,"")
TextGadget(0,0,0,99,99,"Hello World")
Delay(3000)
CloseWindow(0)

```
> 2 votes

# Answer
# Java, 153 bytes

```
interface a{static void main(String[]A){new Thread(()->javax.swing.JOptionPane.showMessageDialog("Hello world")).start();Thread.sleep(3000);throw null;}}

```

Points to `null` three seconds after popping up a quite ugly window with the text "Hello world" on it.
> 2 votes

# Answer
# SmileBASIC, 23 bytes

```
DIALOG"hello world",,,3

```
> 2 votes

# Answer
# APL (Dyalog APL), 36 bytes

```
⎕EX(⎕DL 3)⊢⎕A⎕WC'Form' 'hello world'

```

`⎕A` uppercase **A**lphabet (the only legal name which can be written with two characters)

`⎕WC`**W**indow **C**reate (and return name of)

`'Form' 'hello world'` a GUI form with appropriate caption

yield the form's name while ignoring the result of

`(⎕DL 3)`**D**e**l**aying 3 seconds (the ignored result is the elapsed time)

`⎕EX`**Ex**punge the form (thus making it disappear)

This only works on Windows.
> 2 votes

# Answer
# C (MSVC) + Windows API, ~~130~~ 119

-11 thanks to @EasyasPi

```
#include<windows.h>
main(){GetProcAddress(LoadLibrary("user32.dll"),"MessageBoxTimeoutA")(0,"Hello World",0,0,0,3000);}

```

Never thought the Windows API could get this short! Many thanks to this Stack Overflow answer for documenting the undocumented `MessageBoxTimeoutA` function.
> 2 votes

# Answer
# Cobra - 180

```
use System.Windows.Forms
use System.Threading
class M
    def main
        Thread(ref .w).start
        Thread.sleep(3000)
        Environment.exit(0)
    def w
        MessageBox.show("hello world")

```
> 1 votes

# Answer
# Python 3, ~~83~~ 72 bytes

```
from tkinter import*
f=Tk()
f.wm_title("Hello World")
f.after(3000,exit)

```

Save bytes by using `tkinter`.

The old method added a `Label` to the frame. This method sets the title of the frame to `Hello World`. `f.after(3000,exit)` runs `exit()` after `3000` milliseconds have passed.
> 1 votes

# Answer
# Ruby \[with Shoes\] (44 chars)

```
Shoes.app{para "Hello world";every(3){exit}}

```
> 1 votes

# Answer
# C# 124

Far from the shortest :(

```
class P{static void Main(){new System.Windows.Forms.Form(){Text="Hello World"}.Show();System.Threading.Thread.Sleep(3000);}}

```
> 1 votes

# Answer
# Bash with `xterm`, 34

Uses the title of an `xterm` window to display "Hello World". Does close after 3 seconds.

```
xterm -T Hello\ World -e sleep\ 3

```

If displaying `Hello_World` (without a space) is allowed, you can save one char (`xterm -T Hello_World -e sleep\ 3`).
> 1 votes

# Answer
# Legacy C/Xt/Motif (240)

Super old-school entry!

Link with `-lXm -lXt -lX11`, order matters.

Also curious if this works on other \*nix platforms, because the XFlush is me subverting what I'm supposed to do (enter the application loop) in order that I don't have to install a timer to shut down after 3 seconds (and consume more characters).

```
#include <Xm/XmAll.h>
int main(int n,char **v){XtAppContext c;Widget t=XtVaAppInitialize(&c,"h",NULL,0,&n,v,NULL,NULL);XtVaSetValues(t,XmNtitle,"Hello World",XmNminWidth,300,NULL);XtRealizeWidget(t);XFlush(XtDisplay(t));sleep(3);return 0;}

```
> 1 votes

# Answer
## TCL, 52 bytes

```
label .l -text Hello\ World
pack .l
after 3000 exit

```
> 1 votes

# Answer
# JavaScript (51)

Some old JavaScript methods that still exist because they existed in Netscape 2. `document.write` replaces the page with a string. `setTimeout` calls a function after given time (in miliseconds). `close` closes the window. Doesn't work in Firefox JS console, but it works when imported with `<script>` or in other browsers' JavaScript consoles.

```
document.write("Hello world")
setTimeout(close,3e3)

```
> 1 votes

# Answer
# Factor, 128 bytes

```
[ f T{ world-attributes { title "" } } clone "Hello world" <label> >>gadgets open-window* 3 seconds sleep close-window ] with-ui

```
> 1 votes

# Answer
# 05AB1E \+ `Message` permission, 39 bytes

```
'‚«™’ÿ.¬•"ÄÖ/€º:3 * Ÿ™ ‚ï"’.E

```

---

```
'‚«™’...’.E  # trimmed program
         .E  # evaluate...
    ’...’    # "ÿ.shell\"msg/time:3 * hello world\""...
             # (implicit) with ÿ replaced by...
'‚«          # "system"...
   ™         # in title case...
         .E  # as Elixir code

====================

System.shell"..."  # trimmed program
System.shell       # execute shell command...
            "..."  # literal

====================

msg/time:3 * ...  # trimmed program
msg               # show message...
             ...  # literal...
   /time:         # that closes after...
         3        # literal...
   /time:         # seconds...
           *      # to all users

```
> 1 votes

# Answer
# Ruby - 136 bytes

Using FXRuby :

```
require'fox16';include Fox;a=FXApp.new;timeout=a.addTimeout(3000)do|s|a.exit;end;a.create;FXMessageBox.error(a,MBOX_OK,'','Hello World')

```
> 0 votes

# Answer
## Javascript (ECMAScript) + jQuery

**65 Script + 23 Html = 88 Characters**

*Html*

```
<div id='a'>Hello World

```

*Script*

```
e=$('#a'),d='dialog',x=e[d]();setTimeout(B=n=>{x.remove()},3000)

```

*All-in-one* (105 Characters)

`<div id='a'>Hello World<script>e=$('#a'),d='dialog',x=e[d]();setTimeout(B=n=>{x.remove()},3000)</script>`

Fiddle

```
 <div id="a">Hello World
 <script>
   e=$("#a"),
   d='dialog',
   x=e[d]();
   setTimeout(B=n=>{x.remove()},3000)
 </script>

```
> 0 votes

# Answer
## VB.NET Winforms, 167

```
Private Sub Form2_Shown(sender As Object, e As System.EventArgs) Handles Me.Shown
    Me.Text = "hello world"
    System.Threading.Thread.Sleep(3000)
    End
End Sub

```

based on ace suggestion the new code is

**NOW 100 Characters**

```
 Sub f() Handles Me.Shown
Me.Text = "hello world"
System.Threading.Thread.Sleep(3000)
End
End Sub

```
> 0 votes

# Answer
# Linux Shell, 54

```
echo "hello world">f;firefox f;sleep 3;killall firefox

```
> 0 votes

# Answer
## HTML/JavaScript (81)

```
<body onload="setTimeout(function(){document.body.innerHTML=''},3e3)">Hello World

```
> 0 votes

# Answer
# Tcl/Tk, 15+11=26

```
after 3000 exit

```

If I name the file "Hello world.tcl", I will automatically get the "Hello world" text as the window's title:
> 0 votes

# Answer
# Vala + `gtk+-3.0`, 144 bytes

```
void main(string[]a){Gtk.init(ref a);var w=new Gtk.Window();w.title="hello world";w.show();Timeout.add(3000,()=>{Process.exit(0);});Gtk.main();}

```

First Vala program, first GTK program.

The title is `hello world`, but the default window size causes it to clip on my window manager.

```
void main(string[] args)
{
    // Initialize GTK
    Gtk.init(ref args);
    // Create a new window
    var win = new Gtk.Window();
    // Set the title
    win.title = "hello world";
    // Set the window to show
    win.show();
    // Set a timeout to exit the program after 3 seconds
    Timeout.add(3000, () => { Process.exit(0); });
    // Enter the main GTK loop to show the window
    Gtk.main();
}

```
> 0 votes

---
Tags: code-golf, graphical-output, hello-world
---


title: Straight Chain Alk*nes without Order

text:
# Question
Title: Straight Chain Alk*nes without Order
This is much like my earlier challenge, except, this time, order *doesn't* matter.

A straight-chain alk\*ne is defined as a sequence of carbon atoms connected by single (alkane), double (alkene), or triple bonds (alkyne), (implicit hydrogens are used.) Carbon atoms can only form 4 bonds, so no carbon atom may be forced to have more than four bonds. A straight-chain alk\*ne can be represented as a list of its carbon-carbon bonds.

These are some examples of valid (not necessarily distinct) straight-chain alk\*nes:

```
[]       CH4              Methane
[1]      CH3-CH3          Ethane
[2]      CH2=CH2          Ethene
[3]      CH≡CH            Ethyne
[1,1]    CH3-CH2-CH3      Propane
[1,2]    CH3-CH=CH2       Propene
[1,3]    CH3-C≡CH         Propyne
[2,1]    CH2=CH-CH3       Propene
[2,2]    CH2=C=CH2        Allene (Propadiene)
[3,1]    CH≡C-CH3         Propyne
[1,1,1]  CH3-CH2-CH2-CH3  Butane
...

```

While these are not, as at least one carbon atom would have more than 4 bonds:

```
[2,3]
[3,2]
[3,3]
...

```

Two straight-chain alk\*nes, `p` and `q` are considered equivalent if `p` is `q` reversed, or `p` is `q`.

```
[1] = [1]
[1,2] = [2,1]
[1,3] = [3,1]
[1,1,2] = [2,1,1]
[1,2,2] = [2,2,1]

```

Your task is to create a program/function that, given a positive integer `n`, outputs/returns the **number** of valid straight-chain alk\*nes of exactly `n` carbon atoms in length.

# Specifications/Clarifications

* You must handle `1` correctly by returning `1`.
* Alk\*nes like `[1,2]` and `[2,1]` are *NOT* considered distinct.
* Output is the *length* of a list of all the possible alk\*nes of a given length.
* You do *not* have to handle `0` correctly.

# Test Cases:

```
1 => 1
2 => 3
3 => 4
4 => 10
5 => 18
6 => 42

```

This is code golf, so the lowest byte count wins!

# Answer
# JavaScript (ES6), 107 bytes

```
A=n=>n>9?2*A(n-1)+3*A(n-2)+3*A(n-7)+A(n-8)-5*A(n-3)-A(n-4)-2*A(n-6)-A(n-9):[0,1,3,4,10,18,42,84,192,409][n]

```

Recursive solution, using the recurrence relation that was pointed out in the comments of the question. Execution time rises much quicker than the input (complexity of `O(9^N)` if I'm not mistaken), so be careful with values higher than 20.
> 2 votes

# Answer
# MMIX, ~~108~~ 92 bytes (~~27~~ 23 instrs)

Works mod \\$2^{63}\\$, because it uses the two-part recurrence instead of the one-part, due to the two-part recurrence being much easier to compute.

(jxd)

```
00000000: e3010001 e3020001 e3030003 e3040001  ẉ¢¡¢ẉ£¡¢ẉ¤¡¤ẉ¥¡¢
00000010: e3050003 e3060006 67050002 67060005  ẉ¦¡¤ẉ©¡©g¦¡£g©¡¦
00000020: 27000001 28ff0302 26ffff01 c1010200  '¡¡¢(”¤£&””¢Ḋ¢£¡
00000030: c1020300 c103ff00 28ff0605 26ffff04  Ḋ£¤¡Ḋ¤”¡(”©¦&””¥
00000040: 66040005 66050006 660600ff 5b00fff5  f¥¡¦f¦¡©f©¡”[¡”ṫ
00000050: 22000104 3f000001 f8010000           "¡¢¥?¡¡¢ẏ¢¡¡

```

Disassembly and explanation:

```
alkns   SET   $1,1          // a(0)
        SET   $2,1          // a(1)
        SET   $3,3          // a(2)
        SET   $4,1          // b(0)/b(1)
        SET   $5,3          // b(2)
        SET   $6,6          // b(4)
        CSOD  $5,$0,2       // b(3), use if n is odd
        CSOD  $6,$0,5       // b(5), use if n is odd
0H      SUBU  $0,$0,1       // loop: n--
        2ADDU $255,$3,$2    // a(n+1) = 2a(n) + a(n-1)
        SUBU  $255,$255,$1  // - a(n-2)
        SET   $1,$2         // and shift
        SET   $2,$3         // values of a
        SET   $3,$255       // down
        2ADDU $255,$6,$5    // b(n+2) = 2b(n) + b(n-2)
        SUBU  $255,$255,$4  // - b(n-4)
        CSOD  $4,$0,$5      // shift values of b down
        CSOD  $5,$0,$6      // if n is odd
        CSOD  $6,$0,$255    // (happens once if n started at 2 or 3)
        PBNZ  $0,0B         // if(n) goto loop
        ADDU  $0,$1,$4      // r(n) = (a(n) + b(n))
        SRU   $0,$0,1       // ÷ 2
        POP   1,0           // return r(n)

```
> 1 votes

---
Tags: code-golf, combinatorics, chemistry
---


title: Number Lockers!

text:
# Question
Title: Number Lockers!
Given a positive integer \< 100 (from 1 to 99, including 1 and 99), output that many lockers.

A locker is defined as the following:

```
+----+
|    |
|    |
|    |
| nn |
+----+

```

where `nn` is the locker number, in base 10. If there is 1-digit number, it is expressed with a 0 in front of it. For example, locker number 2 displays the number `02`.

Lockers can be stacked, but only up to 2 high:

```
+----+
|    |
|    |
|    |
| on |
+----+
|    |
|    |
|    |
| en |
+----+

```

`on` denotes an odd number, `en` an even number. Lockers can also be put next to each other.

```
+----+----+
|    |    |
|    |    |
|    |    |
| 01 | 03 |
+----+----+----+
|    |    |    |
|    |    |    |
|    |    |    |
| 02 | 04 | 05 |
+----+----+----+

```

Notice that locker number 5 is an odd-numbered locker that is on the bottom. This is because when you have odd-numbered input, the last locker should be placed on the floor (because a hovering locker costs too much). The above example therefore is the expected output for n=5. n=0 should return an nothing.

**Rules:** Standard methods of input/output. Input in any convenient format, output as a string. Standard loopholes apply.

**Test cases:**

```
Input
Output
---------------------
1

+----+
|    |
|    |
|    |
| 01 |
+----+
--------------------- (newlines optional in case 1)
4
+----+----+
|    |    |
|    |    |
|    |    |
| 01 | 03 |
+----+----+
|    |    |
|    |    |
|    |    |
| 02 | 04 |
+----+----+
---------------------
5
+----+----+
|    |    |
|    |    |
|    |    |
| 01 | 03 |
+----+----+----+
|    |    |    |
|    |    |    |
|    |    |    |
| 02 | 04 | 05 |
+----+----+----+
---------------------
16
+----+----+----+----+----+----+----+----+
|    |    |    |    |    |    |    |    |
|    |    |    |    |    |    |    |    |
|    |    |    |    |    |    |    |    |
| 01 | 03 | 05 | 07 | 09 | 11 | 13 | 15 |
+----+----+----+----+----+----+----+----+
|    |    |    |    |    |    |    |    |
|    |    |    |    |    |    |    |    |
|    |    |    |    |    |    |    |    |
| 02 | 04 | 06 | 08 | 10 | 12 | 14 | 16 |
+----+----+----+----+----+----+----+----+

```

This is , so shortest code wins!

# Answer
# Pyth, 66 bytes

```
A.[Y2m+.rKXJr6j" | "++km.[\02`kdkjkUT;" -|+"+*3]KJ_.T_McSQ2js[GHhH

```

Test suite.
> 7 votes

# Answer
# Python 2, ~~201~~ ~~191~~ ~~185~~ ~~175~~ ~~171~~ ~~166~~ ~~164~~ 163 bytes

```
n=input()
for j in 0,1:c=n/2+n%2*j;m='+----'*c+'+\n';print['\n',m+('|    '*c+'|\n')*3+''.join('| %02d '%-~i for i in range(j,n-n%2,2)+n%2*j*[~-n])+'|\n'+m*j][c>0],

```

Try it Online!
> 6 votes

# Answer
# PHP, 191 Bytes

```
for(;a&$k="01112344453"[$i++];print"$l\n")for($l="",$b="+||"[$k%3],$n=0;$n++<$a=$argn;)$l.=$i<6&$n%2&$n!=$a|$i>5&($n%2<1|$n==$a)?($l?"":"$b").["----+","    |",sprintf(" %02d |",$n)][$k%3]:"";

```

Try it online!

# PHP, 235 Bytes

```
for(;$i++<$a=$argn;)$r[$i==$a|1-$i&1][]=($p=str_pad)($i,2,0,0);for(;$j<6;)$l[]=($a<2&$j<3?"":[$p("+",$c=($j<3?floor:ceil)($a/2)*5+1,"----+"),$p("|",$c,"    |"),"| ".join(" | ",$r[$j/3])." |"])[$j++%3]."\n";echo strtr("01112344453",$l);

```

Case 1 with optional newlines

Try it online!

Expanded

```
for(;$i++<$a=$argn;)
  $r[$i==$a|1-$i&1][]=($p=str_pad)($i,2,0,0); # make an 2D array 0:odd values 1:even values and last value
for(;$j<6;) # create 6 strings for each different line
  $l[]=($a<2&$j<3 # if last value =1 and line number under 3
    ?"" # make an empty string empty [] as alternative
    :[$p("+",$c=($j<3 # else make the 0 or 3 line and store the count for next line
      ?floor # if line number =0 count=floor ($a/2)  multiply 5 and add 1
      :ceil)($a/2)*5+1,"----+") # else count= ceil($a/2) multiply 5 and add 1
    ,$p("|",$c,"    |") # make lines 1 and 4
    ,"| ".join(" | ",$r[$j/3])." |"])[$j++%3]."\n"; #make lines 2 odd values and 5 even values and last value
echo strtr("01112344453",$l); # Output after replace the digits with the 6 strings

```

# PHP, 300 Bytes

```
for(;$i++<$a=$argn;)$r[$i==$a||!($i%2)][]=($p=str_pad)($i,2,0,0);echo strtr("01112344453",($a>1?[$p("+",$c=($a/2^0)*5+1,"----+")."\n",$p("|",$c,"    |")."\n","| ".join(" | ",$r[0])." |\n"]:["","",""])+[3=>$p("+",$c=ceil($a/2)*5+1,"----+")."\n",$p("|",$c,"    |")."\n","| ".join(" | ",$r[1])." |\n"]);

```

replace `["","",""]` with `["\n","\n","\n"]` if you want newlines for case `1`

Try it online!
> 4 votes

# Answer
# Ruby, ~~256~~ ~~239~~ ~~201~~ ~~191~~ 183 bytes

```
n=gets.to_i;a=n/2;z=a+n%2;t=a*2;q="+----+";r=->x{q*x+?\n+("|    |"*x+?\n)*3+"| n |"*x+?\n};u=r[a]+r[z]+q*z;n.times{|i|j=2*i+1;u[?n]="%02d"%(i<a ?j:i>=t ?j-t:j-t+1)};puts u.squeeze'+|'

```

This is awfully long. I'll work on golfing it more.
> 2 votes

# Answer
# C (gcc), ~~426~~ ~~335~~ ~~300~~ ~~294~~ ~~282~~ ~~252~~ ~~249~~ ~~246~~ ~~244~~ 237 bytes

This really needs to be golfed down

```
#define L puts("")
#define P(s)printf(&s[i>1]
#define F(x)for(i=0;i++<x;)P(
#define O(x,y)F(x)"+----+"));for(j=0;L,j++<3;)F(x)"|    |"));j=y;F(x)"| %02d |")
e,i,j;f(n){e=n/2+n%2;O(n/2,-1),j+=2);L;O(e,0),j+=i^e?2:2-n%2);L;F(e)"+----+"));}

```

Try it online!
> 2 votes

# Answer
## Batch, 305 bytes

```
@echo off
set/a"n=%1&-2
if %1 gtr 1 call:l %n% 1
call:l %1 2
echo %s: =-%
exit/b
:l
set s=+
set "t=|
for /l %%i in (%2,2,%n%)do call:c %%i
if %1 gtr %n% call:c %1
for %%s in ("%s: =-%" "%s:+=|%" "%s:+=|%" "%s:+=|%" "%t%")do echo %%~s
exit/b
:c
set s=%s%    +
set i=0%1
set "t=%t% %i:~-2% |

```

`+----+` and `| |` are both similar to `+ +` in that they can be generated via a single substitution, and it turns out to be slightly shorter than generating them separately (the extra quoting needed for `|`s doesn't help).
> 1 votes

# Answer
# Pyth - ~~97~~ ~~74~~ ~~86~~ ~~80~~ 75 bytes

```
V3K+:?&NtQ2 1Q2?NQYIlK+*+\+*\-4lK\+IqN2BFTU4+sm?qT3.F"| {:02d} "d+\|*\ 4K\|

```

Try it here
> 1 votes

# Answer
# JavaScript ES6, 224 bytes

```
n=>(r=(s,k)=>s.repeat(k),s="",[0,1].map(i=>(c=(n/2+n%2*i)|0,c&&(s+="+"+r(l="----+",c)+`
|`+r(r("    |",c)+`
|`,3),[...Array(c).keys()].map(j=>s+=` ${(h=2*j+(i+!(i&j>c-2&n%2)))>9?h:"0"+h} |`),s+=`
`+(i?`+${r(l,c)}
`:"")))),s)

```

Used some ideas from math junkie's Python answer

## Test Snippet

```
f=
n=>(r=(s,k)=>s.repeat(k),s="",[0,1].map(i=>(c=(n/2+n%2*i)|0,c&&(s+="+"+r(l="----+",c)+`
|`+r(r("    |",c)+`
|`,3),[...Array(c).keys()].map(j=>s+=` ${(h=2*j+(i+!(i&j>c-2&n%2)))>9?h:"0"+h} |`),s+=`
`+(i?`+${r(l,c)}
`:"")))),s)

O.innerHTML=f(I.value);
```

```
<input id="I" value="5" type="number" min="0" max="99" oninput="O.innerHTML=f(this.value)">
<pre id="O"></pre>
```

## Cleaned up

```
n => {
    r=(s,k)=>s.repeat(k);
    s="";
    [0,1].map(i => {
        c = (n/2 + n%2 * i)|0;
        if (c) {
            s += "+" + r(l="----+", c) + "\n|" + r(r("    |",c) + "\n|", 3);
            [...Array(c).keys()].map(j => {
                s += ` ${(h = 2*j + (i + !(i & j>c-2 & n%2))) > 9 ? h:"0"+h} |`;
            });
            s += "\n" + (i ? `+${r(l,c)}\n` : "");
        }
    });
    return s;
};

```
> 1 votes

# Answer
# Charcoal, 37 bytes

```
ＮθＦ…·¹θ«Ｆ⁵¿﹪ι²¿⁼ιθ→↗↓Ｂ⁶±⁶↗→→0Ｐ←⮌Ｉι←←↙

```

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

```
Ｎθ

```

Input the number of lockers into `q`.

```
Ｆ…·¹θ«

```

Loop over the lockers from `1` to `q` inclusive.

```
Ｆ⁵¿﹪ι²¿⁼ιθ→↗↓

```

Calculate the direction to the next locker, and repeat that 5 times (golfier than using jump movements).

```
Ｂ⁶±⁶

```

Draw the locker, starting at the bottom left corner. (The bottom right corner also takes 4 bytes while the top right corner takes 5. The top left corner only takes 3 bytes but then the locker number would take longer to draw.)

```
↗→→0

```

Draw the leading zero of the locker number, if necessary.

```
Ｐ←⮌Ｉι

```

Draw the locker number reversed and right-to-left, effectively right justifying it.

```
←←↙

```

Move back to the bottom left corner ready to calculate the direction to the next locker.

Edit: Later versions of Charcoal support this 32-byte solution:

```
Ｆ⪪…·¹Ｎ²«Ｆ⮌ι«↗→→0Ｐ←⮌Ｉκ↖↖↖↑ＵＲ⁶»Ｍ⁵χ

```

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

```
Ｆ⪪…·¹Ｎ²«

```

Take the numbers from `1` to the input number inclusive pairwise. (If the input number is odd the last array will only have one element.)

```
Ｆ⮌ι«

```

Loop over each pair in reverse order.

```
↗→→0

```

Draw the leading zero of the locker number, if necessary.

```
Ｐ←⮌Ｉι

```

Draw the locker number reversed and right-to-left, effectively right justifying it.

```
↖↖↖↑ＵＲ⁶

```

Move to the top left of the locker and draw it. This is also the bottom left of the next locker, so we're ready to draw the second locker of the pair if applicable.

```
»Ｍ⁵χ

```

Move to the next pair of lockers. (This should be before the inner loop for a saving of 1 byte but Charcoal generates incorrect output for an input of 1 for some reason.)
> 0 votes

# Answer
# Vyxal, 127 bytes

```
½⌊:\+4-*\++,3(:\|4꘍*\|+,)?ɾ'∷n⁰≠∧;ƛS:₃[0p]`| `pð+;ṅ\|+,?½⌈:\+4-*\++,3(:\|4꘍*\|+,)?ɾ'₂n⁰=n∷∧∨;ƛS:₃[0p]`| `pð+;ṅ\|+,?½⌈:\+4-*\++,

```

Try it Online!

This is horrible.
> 0 votes

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


title: Smooth as Teflon

text:
# Question
Title: Smooth as Teflon
Literally! April 6th is National Teflon Day, which is celebrated with Teflon-coated pans (what we will be making). So, given a positive integer `n`, create a Teflon pan. The "pan" section of the pan is an octagon with each of its sides consisting of `n` characters, which will vary depending on which side it is **except for the sides using the character `{` or `}`. Those sides will have a character length of one always.** If `n` is 1:

```
  _
 / \
{   }
 \_/

```

As you can see, each side consists of one character (either `{`, `}`, `/`, `\`, or `_`). If `n` is 2:

```
   __
  /  \
 /    \
{      }
 \    /
  \__/

```

The handle will be created with `n+3` `=`'s and end with a zero (`0`).

---

If `n` is one:

```
  _
 / \
{   }====0
 \_/

```

`n` is 2:

```
   __
  /  \
 /    \
{      }=====0
 \    /
  \__/

```

`n` is 3:

```
    ___
   /   \
  /     \
 /       \
{         }======0
 \       /
  \     /
   \___/

```

If `n` is 4:

```
     ____
    /    \
   /      \
  /        \
 /          \
{            }=======0
 \          /
  \        /
   \      /
    \____/

```

**Rules and Criterion**

* No loopholes allowed
* Handle comes out the right hand side (the side made of the `}` character)
* Input is a positive integer
* If the side does not consist of either `{` or `}` (not the left or right side), they will consist of `n` respective characters:

```
            _
           / \
Left side {   } Right side
           \_/

```
* Since this is , shortest code wins!

# Answer
> 9 votes
# Charcoal,  ~~41~~   ~~38~~   ~~36~~   ~~30~~  28 bytes

*Thanks to @Emigna for helping to save two bytes, thanks to @ASCII-only for saving six bytes, and thanks to @Neil for saving another two bytes!*

```
Ｎη↙η↑←×_η↖η↗{↗η×_η↓↘η}×=⁺³η0

```

Try it online!

**Explanation:**

```
Ｎη                 // Take the size of the pan as input.
↙η                 // Draw a line of η '\'s going down to the left.
↑←×_η              // Move one step up and print η underscores to the left.
↖η↗{↗η             // Print a line of η '\'s going up to the left.
                   // Then move one step north-east and print '{'.
                   // Then print a line of η '/'s going up to the right.
×_η↓               // Print '_' η times and move one step down.
↘η}                // Draw a line of η '\'s going down to the right, then print '}'.
×=⁺³η              // Print '=' η+3 times.
0                  // Print '0'

```

# Answer
> 7 votes
## JavaScript (ES6), 171 bytes

```
f=
n=>(r=s=>s[0][0].repeat(n-1)+s)`  `+r`_
`+r` `.replace(/ /g," $'/$' $`$`$`\\\n")+`{`+r` `+r` `+r` }`+r`====0`+r` `.replace(/ /g,"\n $`\\$` $'$'$'/").replace(/ +\/$/,r`_/`)
```

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

The whole ~~pizza~~ pan is very repetitious so the r function (designed as a tagged template literal) repeats the first character of its input n times. This handles the top and middle and lines of the pan. The rest is repeated by replacing a string of blanks; the `$`` and `$'` subsitutions automatically correspond to increasing and decreasing numbers of blanks thus positioning the `/` and `\` appropriately. Finally the `_`s are filled in on the last line as it's subtly different from the second line in that respect.

# Answer
> 7 votes
## JavaScript + HTML, 575 bytes (451 bytes only JS) 376 bytes (482 bytes only JS)

```
y=document,y.y=y.getElementById,a=(b,c)=>{w="";for(z=0;z<b;z++)w+=c;return w},d=_=>{n=Number(y.y("n").value);s="";u=" ";j="<br>",m="\\",o="/";for(i=-2;i<=2*n;i++)-2==i?s+=a(n+1,u)+a(n,"_")+j:i<n-1?s+=a(n-i-1,u)+o+a(2*(i+1)+n,u)+m+j:i==n-1?s+="{"+a(3*n,u)+"}"+a(n+3,"=")+"0"+j:i+1==2*n?s+=a(n,u)+m+a(n,"_")+o:i+1<2*n&&(s+=a(i-n+1,u)+m+a(5*n-2*i-2,u)+o+j);y.y("p").innerHTML=s};
```

```
<input type="number" id='n'><button onclick='d()'>Do</button><p id='p' style='font-family:monospace;'></p>
```

Not a complicated approach: several string concatenations using conditions for the five different parts of the pan: the uppermost, lowermost and middle lines and the upper and lower halves.

I shortened as much as I could, but it was the limit with this method.

EDIT: it wasn't - additionally golfed by @programmer5000

# Answer
> 4 votes
# Python 3, 196 bytes

```
n=int(input())
p=print
s=' '
def m(i,f,b,c=s):p(s*(n-i)+f+c*(n+2*i)+b)
p(s*n+s+'_'*n)
for i in range(n):m(i,*'/\\')
p('{'+s*n*3+'}'+'='*(n+3)+'0')
for i in range(n-1,0,-1):m(i,*'\\/')
m(0,*'\\/_')

```

I used a few variables to shorten the code, but it's mostly straightforward. Here's a longer, more readable version:

```
n = int(input())

def middle_part(i, first_slash, second_slash, middle_char=' '):
    print(' ' * (n-i) + first_slash + middle_char * (n + 2*i) + second_slash)

print(' ' * (n+1) + '_' * n)

for i in range(n):
    middle_part(i, '/', '\\')

print('{' + ' ' * n*3 + '}' + '=' * (n+3) + '0')

for i in range(n-1, 0, -1):
    middle_part(i, '\\', '/')

middle_part(0, '\\', '/', middle_char='_')

```

**Edit:** changed to read n from stdin, 181 → 196 bytes

# Answer
> 4 votes
# PHP, 174 bytes

```
echo($p=str_pad)("",-$i=-1-$n=$argn),$p(_,$n,_);for(;$i++<$n;)echo$p("
",1+$a=abs($i)),$i?$p("\/"[$i<0],1+$n*3-$a*2,"_ "[$i<$n])."\/"[$i>0]:$p("{",$n*3).$p("} ",5+$n,"="). 0;

```

Takes input from STDIN; run with `-nR` or test it online.

**breakdown**

```
// first line
echo($p=str_pad)("",-$i=-1-$n=$argn),$p(_,$n,_);
// loop $i from -$n to $n
for(;$i++<$n;)echo
    $p("\n",1+$a=abs($i)),                  // 1. left padding
$i?                     // if not middle line:
    $p("\/"[$i<0],1+$n*3-$a*2,"_ "[$i<$n])  // 2. left edge and inner padding
    ."\/"[$i>0]                             // 3. right edge
:                       // else:
    $p("{",$n*3)                            // 2. left edge and inner padding
    .$p(" }",5+$n,"=")                      // 3. right edge
    . 0                                     // 4. knob
;

```

# Answer
> 3 votes
# Python 2.7, ~~194~~ ~~195~~ ~~191~~ ~~187~~ 185 bytes

```
n=input();s=' ';a='\\';z='/'
def m(f,b,i,c=s):print(n-i)*s+f+c*(n+2*i)+b
m(s,s,0,'_')
for i in range(n):m(z,a,i)
print'{'+s*n*3+'}'+'='*(n+3)+'0';exec"m(a,z,i);i-=1;"*(n-1);m(a,z,0,'_')

```

Try it online!

Open to edit suggestions to make it smaller. :)

Edit 1: +1 byte - Credits to ElPedro for pointing out an error in the code, which made it 1 byte longer.

Edit 2: -4 bytes - Credits to piyush-ravi for removing unneccesary arguments.

Edit 3: -4 bytes - How did I not see that? :P

Edit 4: -2 bytes - Replacing '\n' with ';'

# Answer
> 3 votes
# Python 2, ~~180~~ 178 bytes

```
s,i=' ',input();R=range(i)
print'\n'.join([s+s*i+'_'*i]+[s*(i-a)+'/'+s*(i+a*2)+'\\'for a in R]+['{'+s*i*3+'}'+'='*(i+3)+'0']+[s*(i-c)+'\\'+'_ '[c>0]*(i+c*2)+'/'for c in R[::-1]])

```

Try it online!

# Answer
> 2 votes
# PowerShell, 165 bytes

```
param($n)($a=' '*$n)+" "+($b='_'*$n);$n..1|%{' '*$_+"/"+' '*($n+2*$i++)+"\"};"{$($a*3)}$('='*($n+3))0";if($n-1){1..($n-1)|%{' '*$_+"\"+' '*($n+2*--$i)+"/"}};"$a\$b/"

```

Try it online!

Takes input `$n`, sets `$a` to a bunch of spaces, `$b` to a bunch of underscores, and string concatenates that with a space. That's left on the pipeline.

Loops from `$n` down to `1`. If `$n=1`, this will only execute once. Each iteration we do a string concatenation of spaces, a `/`, more spaces with counter `$i`, and a `\`. Those are all left on the pipeline.

Then comes the middle part with the handle, which *coincidentally* has `$a*3` spaces in the middle, and `$n+3` `=` signs, then a `0`. That's left on the pipeline.

If `$n` is bigger than `1`, then `$n-1` is truthy so we enter the conditional, where we loop the other direction to form the bottom of the pan. If `$n=1`, then we don't need this portion due to how the lines work. Those are all left on the pipeline. We finish off with the spaces and underlines with the `$a\$b/` bottom of the pan.

All those strings from the pipeline are sent via implicit `Write-Output` that prints them with newlines in between elements.

# Answer
> 2 votes
# JavaScript + HTML - 346 bytes

**JavaScript - 314 bytes, HTML - 32 bytes**

```
function o(a){a=parseInt(a),String.prototype.r=String.prototype.repeat;c=console.log,d=" ".r(a),e="_".r(a);c(" "+d+e);for(f=a-1,g=a;f>=0;f--,g+=2)c(" ".r(f+1)+"/"+" ".r(g)+"\\");c("{ }=0".replace(" "," ".r(3*a)).replace("=","=".r(a)));for(f=0,g=3*a;f<a-1;f++,g-=2)c(" ".r(f+1)+"\\"+" ".r(g-2)+"/");c(d+"\\"+e+"/")}
```

```
<input id=n onkeyup=o(n.value)>
```

# Un-golfed

```
function o(sides) {

  String.prototype.r = String.prototype.repeat;
  var middle = '{ }=0',
  log = console.log,
  ss = ' '.r(sides),
  u = '_'.r(sides),
  sides = parseInt(sides);

  // top
  log(' ' + ss + u);

  // top mid
  for (var i = sides - 1, j = sides; i >= 0; i--, j += 2) {
    log(' '.r(i + 1) + '/' + ' '.r(j) + '\\');
  }

  // mid
  log('{ }=0'.replace(' ', ' '.r(sides * 3)).replace('=', '='.r(sides)));

  // bottom mid
  for (var i = 0, j = sides * 3; i < sides - 1; i++, j -= 2) {
    log(' '.r(i + 1) + '\\' + ' '.r(j - 2) + '/');
  }

  // bottom
  log(ss + '\\' + u + '/');

}
```

```
<input id="n" onkeyup="o(n.value)">
```

# Answer
> 0 votes
# C, 249 bytes

```
o(c,a){for(;a--;)putchar(c);}s;p(n){o(32,n+1);o(95,n);o(10,1);for(s=0;s<n;s++)o(32,n-s),o(47,1),o(32,n+s*2),o(92,1),o(10,1);o(123,1);o(32,n*3);o(125,1);o(61,3+n);o(48,1);o(10,1);for(s=n-1;s>-1;s--)o(32,n-s),o(92,1),o(s?32:95,n+s*2),o(47,1),o(10,1);}

```

Try it online

# Answer
> 0 votes
# Vyxal, 69 bytes

```
›\_?*꘍,(nε\/꘍₴nd⁰+\\꘍,)\{₴3*\}꘍₴3+\=*0+,(n›\\꘍₴nε‹d+n›⁰=` _`$i$*₴\/,)

```

Try it Online!

Unfortunate bytecount...

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


title: Pizza, Pizza, Deep Dish Pizza!

text:
# Question
Title: Pizza, Pizza, Deep Dish Pizza!
April 5th is National Deep DIsh Pizza Day, the theme of this challenge. Given a positive integer `n` (`n` is greater than 0), create an ASCII deep dish pizza. Actual deep dish pizza shown:

As you can see, there is a layer of crust on the bottom and surrounding the rest of the pizza.

**How to make the pizza**

The crust is made of two layers. The first layer will be `n` tall and `n*3` long. Length is the number of characters (including spaces) in the highest line. So given `n` is 1, the first layer would look like this:

```
\_/  1 character tall
 3 characters long

```

If `n` is two:

```
\    /   2 characters tall
 \__/
  6 characters long

```

Now for the second layer of the crust. It will go *outside* the first, inner crust so therefore, it will be `n+2` characters tall and `(n*3)+6)` characters long. Given `n` is one:

```
\       /  3 characters tall
 \     /
  \___/
   9 characters long (3 underscores, 3 slashes on either side)

```

If `n` is two:

```
\          / 4 characters high
 \        /
  \      /
   \____/
    12 characters long

```

You would then match up the two highest pairs of `\/` with each other for the inner and outer crust. In `n` is 1:

```
\ \   / /
 \ \_/ /
  \___/

```

If done correctly, it would look like a V without the tops with a one character difference between each layer. Speaking of tops, the crust will be joined together by a pair of `/\`, separated by a line of underscores `(n*3)+2` long to complete the crust and pizza.

**Examples**

If `n` is 1:

```
/\_____/\
\ \   / /
 \ \_/ /
  \___/

```

`n` is 2:

```
/\________/\
\ \      / /
 \ \    / /
  \ \__/ /
   \____/

```

`n` is 3:

```
/\___________/\
\ \         / /
 \ \       / /
  \ \     / /
   \ \___/ /
    \_____/

```

**Winning Criterion**

This is , so the shortest code in bytes wins!

# Answer
> 2 votes
# Charcoal, 35 bytes

```
Ｎθ←_←×_θ↖θ↖²Ｍ→/Ｐ×_⁺²×²θ↘θ↘¹\×_θ‖ＢＯθ

```

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

```
Ｎθ

```

Input the size of the pizza.

```
←_←×_θ

```

Print part of the outer crust base.

```
↖θ↖²

```

Print the outer crust left side.

```
Ｍ→/Ｐ×_⁺²×²θ

```

Print part of the top crust.

```
↘θ↘¹\

```

Print the inner crust left side.

```
×_θ

```

Print part of the inner crust base.

```
‖ＢＯθ

```

Reflect to complete the pizza.

Note that modern additions to Charcoal shrink the size down to 31 bytes:

```
Ｎθ←×_⊕θ↖θ↖²Ｍ→/Ｐ×_⊗⊕θ↘⊕θ\×_θ‖ＢＯθ

```

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

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

```
f=
n=>"/\\"+(r=s=>s[0][0].repeat(n-1)+s)`_`+r`_`+r`___/\\
`+r` `.replace(/ /g,"$`\\ \\$`   $'$'$'/ /\n")+r` \\ \\`+r`_/ /
`+r`  \\`+r`___/`
```

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

The whole pizza is very repetitious so the `r` function (designed as a tagged template literal) repeats the first character of its input `n` times. This handles the top and bottom two lines of the pizza. The middle is repeated by replacing a string of blanks; the `$`` and `$'` subsitutions automatically correspond to increasing and decreasing numbers of blanks thus positioning the `\ \` and `/ /` appropriately.

# Answer
> 2 votes
# JavaScript (ES6), 205 bytes

---

This is my first post!

Add a `f=` at the beginning and invoke like `f(arg)`.

```
n=>{a=[];w=" ";u="_";t=`/\\${u.repeat(n*3+2)}/\\
`;for(i=0;i<n+1;i++){c=i==n?u:w;a.push(`${w.repeat(i)}\\ \\${c.repeat((n+1-i*2)+n+(n-1))}/ /
`)};return [t,...a,`${w.repeat(i)}\\${u.repeat(n+2)}/`].join``}

```

**Note:** *All line breaks are necessary!*

---

```
f=n=>{a=[];w=" ";u="_";t=`/\\${u.repeat(n*3+2)}/\\
`;for(i=0;i<n+1;i++){c=i==n?u:w;a.push(`${w.repeat(i)}\\ \\${c.repeat((n+1-i*2)+n+(n-1))}/ /
`)};return [t,...a,`${w.repeat(i)}\\${u.repeat(n+2)}/`].join``}

document.querySelector("#elem").innerHTML = f(+prompt("Enter a Number"));
```

```
<pre id="elem">
```

---

## Explanation

The code first declares an Array `a`. It then declares `w` and `u` having the value of whitespace and underscore respectively. Then, it declares a String variable to hold the value of the crust (which can be computed by `/\+(n*3+2 underscores)+/\`, as mentioned in the Challenge). After that, with a `for` loop and a `Template Literal`, the middle of the pizza is created (with each layer having `i` whitespaces at the starting and `(n+1-i*2)+n+(n-1)` whitespaces between `\ \` and `/ /`, where `i` represents the index of `for` loop). At the last, the bottom most part of the pizza is created (`(i whitespaces)+\+(n+2 underscores)+/`). All parts are joined together and output(ted).

---

If for some reason the snippet does not display the ASCII art correctly, have a look here.

Happy Deep Dish Pizza Day to everyone!

---

# Answer
> 2 votes
## Python 2, ~~153~~ 151 bytes

Try it online

```
n=input()
a=' '*n
b='_'*n
print'/\\__'+b*3+'/\\'
i=0
exec"print' '*i+'\ \\\\'+' '*(3*n-2*i)+'/ /';i+=1;"*n
print a+'\ \\'+b+'/ /'
print a+' \\_'+b+'_/'

```

-2 bytes by substituting repeated values with variables thanks to @KoishoreRoy

# Answer
> 2 votes
## MATLAB, 333 bytes

(Lazy-ish attempt)

```
function t(n);p=@(q)fprintf(q);s=@(x)p(' ');r=@()p('/ /');l=@()p('\\ \\');f=@()p('/');b=@()p('\\');u=@(x)p('_');h=@()p('/\\');e=@()p('\n');h();arrayfun(u,1:3*n+2);h();e();for i=1:n;arrayfun(s,1:i-1);l();arrayfun(s,1:3*n-2*(i-1));r();e();end;arrayfun(s,1:n);l();arrayfun(u,1:n);r();e();arrayfun(s,1:n+1);b();arrayfun(u,1:n+2);f();e();

```

### Formatted:

```
function d(n)
p=@(q)fprintf(q);
s=@(x)p(' ');
r=@()p('/ /');
l=@()p('\\ \\');
f=@()p('/');
b=@()p('\\');
u=@(x)p('_');
h=@()p('/\\');
e=@()p('\n');
h();arrayfun(u,1:3*n+2);h();e();
for i=1:n
arrayfun(s,1:i-1); l(); arrayfun(s,1:3*n-2*(i-1)); r();e();
end
arrayfun(s,1:n); l(); arrayfun(u,1:n); r();e();
arrayfun(s,1:n+1); b(); arrayfun(u,1:n+2); f();e();

```

Basic idea is I have function handles to print everything, and then I just pretty much brute-force it. The one for loop is for the `n` layers between the very top and the bottom of the inside layer. The repetition of  (spaces) and `_` is done using `arrayfun`, with array inputs. Will try to think of more interesting ways to do this if I get more time later.

# Answer
> 2 votes
# Charcoal, ~~54~~ 52 bytes

```
Ａ⁺Ｎ²β↖Ｍ↓↙¹Ｍ→↘βＭ↑×_β↗βＭ←↖¹Ｍ↓↙βＭ↑←×_⁺β±²↖βＭ↘Ｍ→×_⁺×β³±⁴

```

Explanation:

```
Ａ⁺Ｎ²β       Assign input + 2 to the variable β
↖             Move up and left one, printing a \
Ｍ↓           Move pointer down one
↙¹            Move down and left one, printing a /
Ｍ→           Move pointer right one
↘β            Move down and right β times
Ｍ↑           Move pointer up
×_β           Write underscores β times
↗β            Move up and right β times
Ｍ←           Move pointer right one
↖¹           Move up and left one
Ｍ↓           Move pointer down one
↙β           Move down and right β times
Ｍ↑           Move up one
←             Set direction to left
×_⁺β±²        Write underscores β - 2 times
↖β            Move up and left β times
Ｍ↘           Move down and right one
Ｍ→           Move right one
×_⁺×β³±⁴      Write underscores (β * 3) - 4 times

```

My previous answer was in Retina, a language I haven't posted an answer to before. Now, you have an answer in Charcoal, which I haven't posted an answer to before.

Try it online!

# Answer
> 2 votes
# PHP, ~~209 200 137~~ 135 bytes

finally beating JS :)

```
echo($f=str_pad)("/\\",1+3*$x=$n=1+$argn,_),"/\\
";for(;$n;)echo$f("\\ \\",2*$n+$x," _"[!--$n]),"/ /
",$p.=" ";echo$f("\\",2+$x,_),"/";

```

Takes input from STDIN; run with `-nR` or order a family pizza.

**breakdown**

```
// print top
echo($f=str_pad)("/\\",1+3*$x=$n=1+$argn,_),"/\\\n";
// loop N+1 times
for(;$n;)
    // print current line and left padding for next line
    echo$f("\\ \\",2*$n+$x," _"[!--$n]),"/ /\n",$p.=" ";
// print bottom
echo$f("\\",2+$x,_),"/";

```

# Answer
> 1 votes
## Batch, 200 bytes

```
@set l=@for /l %%i in (1,1,%1)do @call
@set t=
@set s=
%l%set s=___%%s%%
@echo /\_%s%_/\
%l%echo %%t%%\ \%%s:_= %%/ /&call set t= %%t%%&call set s=%%s:~2%%
@echo %t%\ \%s%/ /
@echo %t% \_%s%_/

```

`t` contains the left indent while `s` contains the inside; its `_`s are subsituted with spaces on the middle rows. `l` just exists to avoid some repetition.

# Answer
> 1 votes
# Vyxal, 59 bytes

```
k/₴3*⇧\_*k/+,›(n`\ \\`꘍₴nεd+n⁰=` _`$i*₴`/ /`,)›\\꘍₴⇧\_*\/+,

```

Try it Online!

# Answer
> 0 votes
# , 57 bytes

```
i\ \´ / /ÙãxX2r_>>Ù>>lxxE2r_ÀñHãyêP>GÄXã2é ñHÄÒ_R/\$h.

```

Try it online!

Since, (as usual) this contains lots of nasty non-ASCII characters and unprintables, here is a hexdump:

```
00000000: 695c 205c b420 2f20 2f1b d9e3 7858 3272  i\ \. / /...xX2r
00000010: 5f3e 3ed9 3e3e 6c78 7845 3272 5fc0 adf1  _>>.>>lxxE2r_...
00000020: 48e3 79ea 503e 47c4 58e3 32e9 20f1 48c4  H.y.P>G.X.2. .H.
00000030: d25f 522f 5c1b 2468 2e                   ._R/\.$h.

```

I'll post a more detailed explanation soon, but here is a high level overview:

```
i\ \´ / /ÙãxX2r_>>Ù>>lxxE2r_
"Create
"\ \    / /
" \ \__/ /
"  \____/
"This can probably be compressed a lot more

ÀñHãyêP>GÄXã2é ñ
"*arg1 times*, expand the pizza slice

HÄÒ_R/\$h.
"Add the crust

```

# Answer
> 0 votes
# C (clang), ~~211~~ 215 bytes

```
i,l;f(n){l=n*3+6;char u[l];for(i=0;i<l;)u[i++]='_';u[l-1]=i=0;printf("/\\%.*s/\\\n",l-4,u);for(;i<n;i++)printf("%*s\\ \\%*.s/ /\n",i,"",n*3-(2*i),"");printf("%*.s\\ \\%.*s/ /\n%*.s\\%.*s/\n",i,"",n,u,i+1,"",n+2,u);}

```

Try it online!

## Pretty Code:

```
i,l;
f(n) {
    l = n*3+6;
    char u[l];

    // Initialize u[] with a full line of underscores,
    for (i=0;i<l;)
        u[i++] = '_';

    // Make sure the string ends in a valid way
    u[l] = i = 0;

    /* Print the crust 'top'
     * l-4 dashes are needed because '/\/\'
     * %.*s notation to pad (l-4) bytes of the underscore string
     */
    printf("/\\%.*s/\\\n", l-4,u);

    /* Print n rows of just 'walls' \ \  / /
     * each row has i=0++ leading spaces,
     * and each row has n*3-(2i) center spaces
     */
    for(; i<n; i++)
        printf("%*s\\ \\%*.s/ /\n", i,"", n*3-(2*i), "");

    /* Print i spaces, '\ \', n underlines, '/ /'
     * then i+1 spaces, '\', n+2 underlines, and '/'
     */
    printf("%*.s\\ \\%.*s/ /\n%*.s\\%.*s/\n",i,"",n,u,i+1,"",n+2,u);
}

```

## Edits:

* removed s\[l\] and associated by switching from %.*s notation to %*.s
* added function wrapper for compliance & try it online

# Answer
> 0 votes
## CJam, 74 Bytes

*Way* too long. I'm going to try another approach.

```
"/\\"ri:M3*:A2+'_*1$NL{"\ \\"AS*"/ /"3$S+A((:A;N\}M*4$A'_*4$N4$S'\A2+'_*'/

```

Builds the string line-by line. Nothing too crazy.

# Answer
> 0 votes
## CJam, 89 bytes

Well, this is actually longer than my other solution at the moment, but I think it's more golfable:

```
ri{:T)_S*a*ee_{~'\t}%TS*aTU+*'_f+@{~'/t}%W%++z}:K~2S*f{\+}T1:U+K..e>"/\\"'_T3*(*1$++a\+N*

```

Stack trace:

```
"2" ; r
2 ; i
2 {:T)_S*a*ee_{~'\t}%TS*aTU+*'_f+@{~'/t}%W%++z} ; {}
2 {:T)_S*a*ee_{~'\t}%TS*aTU+*'_f+@{~'/t}%W%++z} ; :K
2 ; ~
2 ; :T
3 ; )
3 3 ; _
3 3 " " ; S
3 "   " ; *
3 ["   "] ; a
["   " "   " "   "] *
[[0 "   "] [1 "   "] [2 "   "]] ; ee
[[0 "   "] [1 "   "] [2 "   "]] [[0 "   "] [1 "   "] [2 "   "]] ; _
[[0 "   "] [1 "   "] [2 "   "]] ["\  " " \ " "  \\"] ; {~'\t}%
[[0 "   "] [1 "   "] [2 "   "]] ["\  " " \ " "  \\"] 2 ; T
[[0 "   "] [1 "   "] [2 "   "]] ["\  " " \ " "  \\"] 2 " " ; S
[[0 "   "] [1 "   "] [2 "   "]] ["\  " " \ " "  \\"] "  " ; *
[[0 "   "] [1 "   "] [2 "   "]] ["\  " " \ " "  \\"] ["  "] ; a
[[0 "   "] [1 "   "] [2 "   "]] ["\  " " \ " "  \\"] ["  "] 2 ; T
[[0 "   "] [1 "   "] [2 "   "]] ["\  " " \ " "  \\"] ["  "] 2 0 ; U
[[0 "   "] [1 "   "] [2 "   "]] ["\  " " \ " "  \\"] ["  "] 2 ; +
[[0 "   "] [1 "   "] [2 "   "]] ["\  " " \ " "  \\"] ["  " "  "] ; *
[[0 "   "] [1 "   "] [2 "   "]] ["\  " " \ " "  \\"] ["  " "  "] '_ ; '_
[[0 "   "] [1 "   "] [2 "   "]] ["\  " " \ " "  \\"] ["  _" "  _"] ; f+
["\  " " \ " "  \\"] ["  _" "  _"] [[0 "   "] [1 "   "] [2 "   "]] ; @
["\  " " \ " "  \\"] ["  _" "  _"] ["/  " " / " "  /"] ; {~'/t}%
["\  " " \ " "  \\"] ["  _" "  _"] ["  /" " / " "/  "] ; W%
["\  " " \ " "  \\" "  _" "  _" "  /" " / " "/  "] ; ++
["\      /" " \    / " "  \__/  "] ; z
["\      /" " \    / " "  \__/  "] "  " ; 2S*
["  \      /" "   \    / " "    \__/  "] ; f{\+}
["  \      /" "   \    / " "    \__/  "] 2 ; T
["  \      /" "   \    / " "    \__/  "] 2 1 ; 1
["  \      /" "   \    / " "    \__/  "] 2 1 ; :U
["  \      /" "   \    / " "    \__/  "] 3 ; +
["  \      /" "   \    / " "    \__/  "] ["\          /" " \        / " "  \      /  " "   \____/   "] ; K
["\ \      / /" " \ \    / / " "  \ \__/ /  " "   \____/   "] ; ..e>
["\ \      / /" " \ \    / / " "  \ \__/ /  " "   \____/   "] "/\\" ; "/\\"
["\ \      / /" " \ \    / / " "  \ \__/ /  " "   \____/   "] "/\\" '_ ; '_
["\ \      / /" " \ \    / / " "  \ \__/ /  " "   \____/   "] "/\\" '_ 3 ; T
["\ \      / /" " \ \    / / " "  \ \__/ /  " "   \____/   "] "/\\" '_ 9 ; 3*
["\ \      / /" " \ \    / / " "  \ \__/ /  " "   \____/   "] "/\\" '_ 8 ; (
["\ \      / /" " \ \    / / " "  \ \__/ /  " "   \____/   "] "/\\" "________" ; *
["\ \      / /" " \ \    / / " "  \ \__/ /  " "   \____/   "] "/\\" "________" "/\\" ; 1$
["\ \      / /" " \ \    / / " "  \ \__/ /  " "   \____/   "] "/\________/\\" ; ++
["\ \      / /" " \ \    / / " "  \ \__/ /  " "   \____/   "] ["/\________/\\"] ; a
["/\________/\\" "\ \      / /" " \ \    / / " "  \ \__/ /  " "   \____/   "] ; \+
"/\________/\
\ \      / /
 \ \    / /
  \ \__/ /
   \____/   " ; N*
; [implicit output]

```

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


title: Happy Bacon Day!

text:
# Question
Title: Happy Bacon Day!
Today is Bacon Day which is probably why the name of the hat for participating today is "Mmmm Bacon". What better way to celebrate bacon day with fun filled 2d matrices made out of bacon! A 1 by 1 bacon strip is represented by this:

```
-----
)===)
(===(
)===)
-----

```

You goal here is given two coordinates in a tuple, (`x`, `y`), where `x` and `y` are nonzero positive integers, you are to create the bacon and return in some format (list, array, string).

**Input and Output:**

```
Input: (2, 1)

Output:
----------
)===))===)
(===((===(
)===))===)
----------

Input: (1, 2)

Output:

-----
)===)
(===(
)===)
-----
)===)
(===(
)===)
-----

Input: (2, 2)

----------
)===))===)
(===((===(
)===))===)
----------
)===))===)
(===((===(
)===))===)
----------

```

**Rules:**

* As you can see with the second test case, if multiple pieces of bacon are stacked together, only one `-----` separates with each piece of bacon above and/or below it. That means stacking bacon like this is invalid:

```
-----
)===)
(===(
)===)
-----
-----
)===)
(===(
)===)
-----

```
* Standard loopholes are forbidden
* The code must work for the above test cases and the following: `(4, 4)`, `(1, 6)`, `(5, 1)`, `(2, 3)`, `(3, 2)`
* Provide an interpreter where the above test cases can be tested

**Winning Criteria:**

Shortest code wins! Happy Bacon Day to everyone!

# Answer
> 12 votes
# , ~~28, 26~~, 24 bytes

```
Ài)³=)Y4PÒ-G.MÓ)/(
kÀäG

```

Try it online!

Explanation:

```
Ài                      " Arg 1 times insert:
  )³=)                  " ')===)'
      <esc>             " Escape back to normal mode
           Y            " Yank this line
            4P          " Paste four times
              Ò-        " Replace this line with '-'
                G.      " Repeat on the last line
                  M     " Move to the middle line
                   Ó)/( " Replace ')' with '('
k                       " Move up (to the second line)
 À                      " Arg 2 times
  äG                    " Duplicate everything up to the last line

```

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

This one was actually quite genius :)

```
":→Str0:Input :For(M,0,4Y:For(N,1,X:")===)
If not(fPart(M/4:"-----
If .5=fPart(M/4:"(===(
Str0+Ans→Str0:End:Ans+":→Str0:End

```

# Answer
> 7 votes
# Python 2.7, 74 bytes

I'm sure this could be golfed some more, but this is what I came up with (Python's string multiplication feature sure comes in handy):

```
a,b=input();f="-"*5*a;d=")===)"*a;print'\n'.join([f,d,"(===("*a,d,''])*b+f

```

Try it here!

Ungolfed with explanation:

```
a,b = input()                                       # Take input from the user as a tuple
f = "-"*5 * a                                       # f is the delimiter between bacons
d = ")===)" * a                                     # 2nd and 4th lines of bacon
print '\n'.join([f, d, "(===("*a, d, ''])*b + f     # Join everything together!

```

# Answer
> 5 votes
# Mathematica, 74 bytes

```
Array[b["-----",b=")===)","(===("][[#~Mod~4]]&,{4#2+1,#}]~Riffle~"\n"<>""&

```

Unnamed function taking two positive integer arguments and returning a string-with-newlines. A standard Mathematica approach: build a 2d array of strings using a (mod 4) chooser to cycle the strings in the vertical direction, then collapse them to a single string.

# Answer
> 4 votes
## Batch, 168 bytes

```
@set s=
@for /l %%i in (1,1,%1)do @call set s=%%s%%-___-
@set t=%s:_==%
@echo %s:_=-%
@for /l %%i in (1,1,%2)do @echo %t:-=)%&echo %t:-=(%&echo %t:-=)%&echo %s:_=-%

```

Rather unfortunately I can't write `@echo %s:==-%` otherwise that would eliminate the necessity for the second variable.

# Answer
> 4 votes
# 05AB1E, ~~32~~ 30 bytes

Saved 2 bytes thanks to *Adnan*.

```
'-5×…)==ûÐ')'(:s)vy¹×})I.D¬)˜»

```

Try it online!

**Explanation**

```
'-5×                            # push "-----"
    …)==ûÐ                      # push 3 copies of ")===)"
          ')'(:s                # replace ")" with "(" in the 2nd copy
                )               # wrap in list
                 vy¹×})         # repeat each list entry input-1 times
                       I.D      # repeat list input-2 times
                          ¬     # push the first element of the list ("-----")
                           )˜   # wrap in list and flatten
                             »  # join by newline

```

# Answer
> 4 votes
# C, 91 89 bytes

```
i;f(w,h){w=w*5+1;for(i=0;i<w*4*h+w;++i)putchar(i%w<w-1?i/w%4?i%w%5%4?61:40+i/w%2:45:10);}

```

# Answer
> 4 votes
# 05AB1E, 25 bytes

Code:

```
…)==û×Ð¬'(:s)¬g'-×=¸«»²F=

```

Explanation:

```
…)==û                         # Push the string ")===)"
     ×                        # String multiply by the first input
      Ð                       # Triplicate the string
       ¬                      # Take the first character, which is a ')' and push
        '(:                   # Replace by '('
           s                  # Swap the top two elements
            )                 # Wrap everything into an array
             ¬g               # Get the length of the first element in the array
               '-×            # And repeat the character '-' that many times
                  =           # Print it without popping
                   ¸«         # Append the string of dashes to the array
                     »        # Join by newlines
                      ²F      # Second input times do...
                        =     #   Print the top of the stack without popping

```

Uses the **CP-1252** encoding. Try it online!

# Answer
> 3 votes
## JavaScript, ~~132~~ ~~129~~ 121 bytes

*-8 bytes thanks to @user2428118*

~~```
(x,y)=>{a=b=["-----",")===)","(===(",")===)","-----"];for(i=0;++i<y;){b=[...b,...a.slice(1)]}return b.map(v=>v.repeat(x)).join(`
`)}

```~~ ~~```
(x,y)=>eval('a=b=["-----",")===)","(===(",")===)","-----"];for(i=0;++i<y;)b=[...b,...a.slice(1)];b.map(v=>v.repeat(x)).join`\n`')

```~~
```
(x,y)=>eval('a=b=[c="-----",d=")===)","(===(",d,c];for(i=0;++i<y;)b=[...b,...a.slice(1)];b.map(v=>v.repeat(x)).join`\n`')

```

This can quite probably be golfed more. If you have a suggestion, please leave it in the comments.

# Answer
> 3 votes
# Python 2, 70 bytes

```
def f(w,h):n=4*h+1;exec"n-=1;print'-)()-===-===-===-)()'[n%4::4]*w;"*n

```

*Thanks to @xnor for saving 4 bytes!*

Try it online!

# Answer
> 3 votes
## Python 2, 59 bytes

```
w,h=input()
for a in'-()('*h+'-':print(a+3*'=-'[a>')']+a)*w

```

Generates each line as `a+b*3+a` from the initial character `a` and the center character `b` (which is calculated from `a`). The `a`'s cycle through `'-()('`, whereas `b` is `'-'` when `a` is `'-'`, and `'='` otherwise.

---

**67 bytes:**

```
w,h=input()
for a,b in['--']+zip(')()-','===-')*h:print(a+b*3+a)*w

```

Generates each line from its outer character `a` and center character `b` as `a+b*3+a`, then prints `w` copies of this. These cycle via a `zip`.

# Answer
> 2 votes
## Lua, 132 bytes

```
a="-----"b=")===)"c="(===("w,z=io.read(),io.read()function g(f)return f:rep(w).."\n"end print((g(a)..g(b)..g(c)..g(b)):rep(z)..g(a))

```

Long, literal string attempt. Try it here.

# Answer
> 2 votes
# JavaScript (ES6), 78

```
(x,y,r=s=>`${s}`.repeat(x)+`
`,a=r`)===)`,c=r`-----`)=>c+r(a+r`(===(`+a+c,x=y)

```

**Test**

```
F=
(x,y,r=s=>`${s}`.repeat(x)+`
`,a=r`)===)`,c=r`-----`)=>c+r(a+r`(===(`+a+c,x=y)

function update() {
  var x=+X.value,y=+Y.value
  O.textContent=F(x,y)
}

update()
```

```
X<input type=number id=X value=1 min=1 oninput='update()'>
Y<input type=number id=Y value=1 min=1 oninput='update()'>
<pre id=O></pre>
```

# Answer
> 2 votes
# Vyxal, 35 bytes

```
(5⁰*¤-,`)===)`⁰*:,`(===(`⁰*,,)5*¤-,

```

Try it Online!

Uses magic :P

# Answer
> 1 votes
# GameMaker Language, ~~160~~ ~~139~~ ~~148 bytes~~ 133 bytes

```
x=argument0 y=argument1*4for(m=0;m<=y;m++){for(n=0;n<x;n++){a=")===)"if !m mod 4a="-----"else if n mod 2a="(===("r+=a}r+="#"}return r

```

# Answer
> 1 votes
# Jelly, 26 bytes

```
4“\ḊƭVṠ’bị“-=()”s5ẋ€ḷẋµ1ịṭ

```

This is a dyadic link (function) that returns a 2D array.

Try it online!

### How it works

```
4“\ḊƭVṠ’bị“-=()”s5ẋ€ḷẋµ1ịṭ  Main link. Left argument: w. Right argument: h

4                           Set the return value to 4.
 “\ḊƭVṠ’b                   Yield 366323084456 and convert it to base 4.
                            This yields [1,1,1,1,1,0,2,2,2,0,3,2,2,2,3,0,2,2,2,0].
         ị“-=()”            Index into that string, using modular 1-based indexing.
                s5          Split the result into chunks of length 5.
                  ẋ€ḷ       Repeat the characters of each chunk w times.
                     ẋ      Repeat the array of chunks h times.
                      µ     Begin a new, monadic chain. Argument: M (bacon matrix)
                       1ị   Retrieve the first line.
                         ṭ  Tack; append it to M.

```

# Answer
> 0 votes
# C, ~~159~~ ~~158~~ 153 bytes

```
p(s,n){printf(s,--n?p(s,n):0);}i,j;b(n,m){p("-----",n);for(j=3;j--;){p("\n",1);for(i=n;i--;)p(j%2?"(===(":")===)",1);}p("\n",1);--m?b(n,m):p("-----",n);}

```

Call with:

```
int main()
{
    b(2,3);
}

```

# Answer
> 0 votes
# Tcl, 91 bytes

```
time {time {append h -----
append l )===)
append p (===(} $m
puts "$h
$l
$p
$l"} $n
puts $h

```

Try it online!

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

```
x=>y=>{int i=0,h=4*y+1,j;var s=new string[h];for(;i<h;++i)if(i%4<1)s[i]=new string('-',x*5);else{var c=i%2>0?')':'(';for(j=0;j++<x;)s[i]+=c+"==="+c;}return s;};

```

Formatted version:

```
x => y =>
{
    int i = 0, h = 4 * y + 1, j;

    var s = new string[h];

    for (; i < h; ++i)
        if (i % 4 < 1)
            s[i] = new string('-', x * 5);
        else
        {
            var c = i % 2 > 0 ? ')' : '(';

            for (j = 0; j++ < x; )
                s[i] += c + "===" + c;
        }

    return s;
};

```

Try it online! (for some reason this link gives an error but works anyway)

# Answer
> 0 votes
## Dart, ~~125~~ 117 bytes

```
(x,y){var t='-'*5*x,i=0;return()sync*{yield t;for(;i<y*4;i++)yield i%4>2?t:i%2>0?'(===('*x:')===)'*x;}().join('\n');}

```

Try it here!

# Answer
> 0 votes
# Dyalog APL, 55 bytes

This is my first time using Dyalog APL, so I'm sure this isn't the best approach.

```
 {(⊂'-----'),[1]⍉⍺(4×⍵)⍴')===)' '(===(' ')===)' '-----'}

```

Explanation: This is a quite simple approach, for a bacon grid of N×M, I make an N×(4M) matrix of the following four strings, repeating:

```
')===)'
'(===('
')===)'
'-----'

```

Then I concatenate the string `-----` to the beginning.

Here's a quick explanation of the code:

```
')===)' '(===(' ')===)' '-----'  ⍝ An array of the four strings

⍺ (4×⍵) ⍴                        ⍝ reshape (⍴) the array to a matrix with the dimensions
                                 ⍝ ⍺ by (4×⍵) (⍺ is the 1st argument and ⍵ is the second)

⍉                               ⍝ transpose the matrix

,[1]                             ⍝ concatenate to beginning of the matrix...

(⊂'-----')                       ⍝ ...the string '-----' embedded in its own matrix (⊂)

```

# Answer
> 0 votes
# PowerShell, 64 bytes

```
param($x,$y)-split'----- )===) (===( )===) -----'*$y|gu|%{$_*$x}

```

Try it online!

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