title: The Lehmer-Comtet sequence

text:
# Question
Title: The Lehmer-Comtet sequence
The Lehmer-Comtet sequence is a sequence such that **a(n)** is the **n**th derivative of **f(x) = xx** with respect to **x** as evaluated at **x = 1**.

# Task

Take a non-negative integer as input and output the **n**th term of the Lehmer-Comtet sequence.

This is so you should minimize the file size of your source code.

# Test Cases

OEIS 5727

Here are the first couple terms in order (copied from the OEIS)

```
1, 1, 2, 3, 8, 10, 54, -42, 944, -5112, 47160, -419760, 4297512, -47607144, 575023344, -7500202920, 105180931200, -1578296510400, 25238664189504, -428528786243904, 7700297625889920, -146004847062359040, 2913398154375730560, -61031188196889482880

```

# Answer
# Haskell, ~~77~~ 75 bytes, no differentiation builtins

```
x@(a:b)&y@(c:d)=a*c:zipWith(+)(b&y)(x&d)
s=1:s&(1:scanl(*)1[-1,-2..])
(s!!)

```

Try it online!

### How it works

We represent a function as its infinite list of Taylor series coefficients about \\$x = 1\\$:

$$ f(x) = \sum\_{n=0}^\infty \frac{f^{(n)}(1)}{n!} (x - 1)^n $$

is represented by \\$\[f(1), f'(1), f''(1), ...\]\\$.

The `&` operator multiplies two such functions using the product rule. This lets us recursively define the function \\$s(x) = x^x\\$ in terms of itself using the differential equation

$$ s(1) = 1, \\ s'(x) = s(x) \cdot (1 + \ln x), $$

where

$$ \ln x = \sum\_{n=1}^\infty \frac{(-1)^{n-1}(n - 1)!}{n!}(x - 1)^n. $$
> 13 votes

# Answer
# Mathematica, 19 bytes

```
D[x^x,{x,#-1}]/.x->1&

```

*-18 bytes from @Not a tree*
> 7 votes

# Answer
# Octave with Symbolic Package, ~~36~~ 32 bytes

```
syms x
@(n)subs(diff(x^x,n),x,1)

```

The code defines an anonymous function which outputs a symbolic variable with the result.

**Try it online!**
> 5 votes

# Answer
# Haskell, 57 bytes

```
f 0=1
f n=f(n-1)-foldl(\a k->f(k-1)/(1-n/k)-a*k)0[1..n-1]

```

Try it online!

No built-ins for differentiating or algebra. Outputs floats.
> 5 votes

# Answer
# Python with SymPy, ~~77~~ ~~75~~ ~~58~~ 57 bytes

*1 byte saved thanks to @notjagan*

*17 bytes saved thanks to @AndersKaseorg*

```
from sympy import*
lambda n:diff('x^x','x',n).subs('x',1)

```
> 4 votes

# Answer
# SageMath, ~~33~~ 32 bytes

```
lambda n:diff(x^x,x,n).subs(x=1)

```

Try it on SageMathCell
> 3 votes

# Answer
# Python 3, 150 bytes

```
lambda n:0**n or sum(L(n-1,r)for r in range(n))
L=lambda n,r:0<=r<=n and(0**n or n*L(n-2,r-1)+L(~-n,r-1)+(r-~-n)*L(~-n,r)if r else n<2or-~-n*L(n-1,0))

```

Try it online!

Exponential runtime complexity. Uses the formula given in the OEIS page.
> 2 votes

# Answer
# Python3+mpmath 52 bytes

```
from mpmath import*
lambda n:diff(lambda x:x**x,1,n)

```

-3 bytes, Thanks @Zachary T
> 1 votes

# Answer
# Python 3, ~~288~~ 261 bytes

Differentiation without differentiation built-in.

```
p=lambda a,n:lambda v:v and p(a*n,n-1)or a
l=lambda v:v and p(1,-1)
e=lambda v:v and m(e,a(p(1,0),l))or 1
a=lambda f,g:lambda v:v and a(f(1),g(1))or f(0)+g(0)
m=lambda f,g:lambda v:v and a(m(f(1),g),m(g(1),f))or f(0)*g(0)
L=lambda n,f=e:n and L(n-1,f(1))or f(0)

```

Try it online!

## How it works

Each of the first five lines define functions and their derivatives and their results when evaluated at `1`. Their derivatives are also functions.

* `p` is power i.e. `a*x^n`
* `l` is logarithm i.e. `ln(x)`
* `e` is exponential i.e. `exp(x)`
* `a` is addition i.e. `f(x)+g(x)`
* `m` is multiplication i.e. `f(x)*g(x)`

Usage: for example, `exp(ln(x)+3x^2)` would be represented as `e(l()+p(3,2))`. Let `x=e(l()+p(3,2))`. To find its derivative, call `x(1)`. To find its result when evaluated at `1`, call `x(0)`.

Bonus: symbolic differentiation
> 1 votes

# Answer
# Pari/GP, 32 bytes

```
n->n!*Vec((y=1+x+O(x^n++))^y)[n]

```

Try it online!
> 0 votes

---
Tags: code-golf, sequence, integer, calculus
---


title: Quine over network

text:
# Question
Title: Quine over network
## Write a program, that sends its own source code over network.

Network example is TCP/UDP or web socket. Ethernet, Bluetooth, Wi-Fi and internet over USB are allowed.

No need to write receiver program. You can use any encoding protocol, but decoder will be realizable.

# Rules

* Network **is not** a stdout, screen, USB, UART, GPIO or same.
* The program must be at least 1 byte long.
* No input or accessing source from file system.
* No extra software to send stdout to network like **ssh**.
* This is , shortest code wins.

# Answer
# Java 8, 662 bytes

```
import java.io.*;import java.util.*;interface M{static void main(String[]a)throws Exception{String s="import java.io.*;import java.util.*;interface M{static void main(String[]a)throws Exception{String s=%c%s%1$c,x=s=s.format(s,34,s);for(List l=Arrays.asList(x.split(%1$c%1$c));!x.equals(s);s=s.join(%1$c%1$c,l));ObjectOutputStream o=new ObjectOutputStream(new java.net.Socket(%1$clocalhost%1$c,0).getOutputStream());o.writeObject(s);o.flush();}}",x=s=s.format(s,34,s);for(List l=Arrays.asList(x.split(""));!x.equals(s);s=s.join("",l));ObjectOutputStream o=new ObjectOutputStream(new java.net.Socket("localhost",0).getOutputStream());o.writeObject(s);o.flush();}}

```

Creating a in Java is verbose as F... \>.\>

**Explanation:**

'Try it' here. (Will result in `java.net.SocketException: Permission denied`.)

```
import java.io.*;              // Required import for ObjectOutputStream
import java.util.*;            // Required import for List and Arrays
interface M{                   // Class
  static void main(String[]a)  //  Required main-method
      throws Exception{        //  required throws for the Stream and Socket
    String s="import java.io.*;import java.util.*;interface M{static void main(String[]a)throws Exception{String s=%c%s%1$c,x=s=s.format(s,34,s);for(List l=Arrays.asList(x.split(%1$c%1$c));!x.equals(s);s=s.join(%1$c%1$c,l));ObjectOutputStream o=new ObjectOutputStream(new java.net.Socket(%1$clocalhost%1$c,0).getOutputStream());o.writeObject(s);o.flush();System.out.println(s);}}",
                               //   Quine-String
     x=s=s.format(s,34,s);for(List l=Arrays.asList(x.split(""));!x.equals(s);s=s.join("",l));
                               //   Quine-magic
    ObjectOutputStream o=new ObjectOutputStream(new java.net.Socket("localhost",0).getOutputStream());
                               //   Output stream to http://localhost:0000/
    o.writeObject(s);          //   Write to the output stream
    o.flush();                 //   And send it
  }                            //  End of main-method
}                              // End of class

```
* The String `s` contains the unformatted source code.
* `%s` is used to input this String into itself with the `s.format(...)`.
* `%c`, `%1$c` and the `34` are used to format the double-quotes.
* `s.format(s,34,s)` puts it all together

Slightly modified with `print` to prove it's a quine:
Try it here.
> 3 votes

---
Tags: code-golf, quine, networking
---


title: A Dog on a Chain

text:
# Question
Title: A Dog on a Chain
I'm looking out of my attic window into my neighbor's yard. They have a dog chained to a post in the center of the yard. The dog runs around the yard but is always on the end of its chain, so it ends up leaving a track in the dirt. Normally this track would be perfectly circular, but my neighbors have some other poles in their yard that the dog's chain gets caught on. Each time the dogs chain hits a pole the dog begins rotating about the new pole with whatever length of chain is left as its radius. Since the poles, the dog and the chain all have zero width (my neighbors are mathematicians) the chain can wind around a pole indefinitely without the radius of the circle shortening. The dog can also pass through the chain (just not its collar) if the chain is in its path. After observing this oddity for a while I decide I will write some code to simulate my neighbor's dog. The code will take the locations of a center pole, to which the dog is chained, the locations of the other poles in my neighbors yard, the length of the chain, and the starting location of the dog, and will output a diagram indicating the path where the dog has worn down the grass. You may assume that any combination of the following are constant (and thus not take them as input):

* Location of the pole to which the dog is chained
* Length of the chain
* Starting location of the dog

The sun is rising, so the space on the floor of my attic illuminated by the window is shrinking, giving me less and less space to write my code. Please try to minimize the byte count of your code so that I have space to draft it on my attic floor.

## Test cases

Here I assume that the dog starts 3 units south from the to which pole it is chained (the red dot), located at `0,0`. I have indicated where the poles are with dots for clarity, you do not need to include them in your output.

`Poles at 1,2 -1,2`

`Poles at 0,.5`

`Poles at 0,1 1,1 -2,1 -1,-.5`

`Poles at 0,1 1,1`

# Answer
## Python 3 using matplotlib, 457 bytes

```
from cmath import*
from matplotlib import pyplot as g,patches as i
def x(p):
 p+=[0];d=180/pi;a=2;h=g.gca();h.set_xlim(-5,5);h.set_ylim(-5,5)
 while a:
  a-=1;c=0;y=3;z=-pi/2
  while 1:
   s=[n for n in p if abs(n-c)<=y and n!=c]
   if not s:h.add_patch(i.Arc((c.real,c.imag),y*2,y*2));break
   n=[max,min][a](s,key=lambda n:(z-phase(n-c))%(2*pi));l,r=polar(n-c);h.add_patch(i.Arc((c.real,c.imag),y*2,y*2,[z,r][a]*d,0,[r-z,z-r][a]*d));y-=l;z=r;c=n
 g.show()

```

Because your neighbors are mathematicians I've assumed that your neighbor's garden occupies the complex domain and any coordinates of objects in the garden are therefore complex numbers. To use this function, you should therefore pass it a list of complex numbers signifying the locations of the poles in your neighbor's garden. The default coordinate system representation has been chosen, where to the right are positive real numbers and upwards are positive imaginary numbers. This means the examples become:

```
x([2j+1,2j-1])
x([.5j])
x([1j,1+1j,-2+1j,-1-.5j])
x([1j,1+1j])

```

Furthermore, the program assumes the following things: the leash is tied to the point 0, the leash is 3 units long, and the plot area is 10 by 10 centered around 0. For these parameters, the results match up exactly with the examples, and this is how the result looks like (for the final example):

The algorithm is quite simple, only requiring one conditional to differentiate the clockwise and the counterclockwise search. The state of the algorithm is defined by the current rotation point and the orientation/remaining length of the leash when it hit the current rotation point. It works as follows:

* Filter out points from the collision set that are further away from the current rotation point than the remaining leash length, as well as the current rotation point.
* If this set is empty, draw a circle with the radius of the remaining belt length around this point as the end of this arm has been reached.
* Determine the point where the phase difference between the difference vector and the leash orientation is minimal/maximal. This is the next point the leash will hit in the clockwise/counterclockwise direction respectively.
* Draw the arc based on these vectors, take the leash length, subtract the magnitude of the distance and set the leash orientation to the orientation of the difference vector. Update the rotation point and continue from the start.

This algorithm is then performed first in the clockwise direction, after which the state is reset and it is executed in the counterclockwise direction. The simplicity of the algorithm means that about half of the program bytecount is spent on the drawing functions. If the drawing routines were stripped out it would remove 218 bytes from the program size.

The following is an ungolfed version that also contains debug code, which also displays points and leash collisions:

```
from cmath import pi, rect, polar, phase
from matplotlib import pyplot, patches
def x_ungolfed(points):
    degrees = 180/pi # conversions

    # add the center point to the collision points
    points.append(0.0)

    # configure plot area
    axes=pyplot.gca()
    axes.set_xlim(-5,5)
    axes.set_ylim(-5,5)

    # plot the points
    x, y =zip(*((p.real, p.imag) for p in points))
    axes.scatter(x, y, 50, "b")

    # first iteration is clockwise, second counterclockwise
    clockwise = 2
    while clockwise:
        clockwise -= 1

        # initial conditions
        center = 0 + 0j;
        leash_size = 3
        leash_angle = -pi / 2

        # initial leash plot
        leash_start = rect(leash_size, leash_angle)
        axes.plot([center.real, leash_start.real], [center.imag, leash_start.imag], "r")

        # search loop
        while 1:
            # find possible collission candidates
            candidates = [n for n in points if abs(n - center) <= leash_size and n != center]
            # if we reached the end, draw a circle
            if not candidates:
                axes.add_patch(patches.Arc(
                    (center.real, center.imag),
                    leash_size*2, leash_size*2
                ))
                break
            # find the actual collision by comparing the phase difference of the leash angle vs the difference between the candidate and the current node
            new = (min if clockwise else max)(candidates, key=lambda n: (leash_angle - phase(n - center)) % (2 * pi))

            # convert the difference to polar coordinates
            distance, new_angle = polar(new - center)
            # draw the arc
            if clockwise:
                axes.add_patch(patches.Arc(
                    (center.real, center.imag),
                    leash_size * 2, leash_size * 2,
                    new_angle * degrees,
                    0,
                    (leash_angle-new_angle) * degrees
                ))
            else:
                axes.add_patch(patches.Arc(
                    (center.real, center.imag),
                    leash_size * 2, leash_size * 2,
                    leash_angle * degrees,
                    0,
                    (new_angle - leash_angle) * degrees
                ))
            # draw intermediate lines
            edge = rect(leash_size, new_angle) + center
            axes.plot([center.real, edge.real], [center.imag, edge.imag], "g")

            # perform updates: decrease remaining leash size, set new leash angle, move rotation center to the collision
            leash_size -= distance
            leash_angle = new_angle
            center = new

    # show the graph
    pyplot.show()

```

The output it produces looks like this:
> 11 votes

# Answer
# Processing 3, 815 ~~833~~ ~~835~~ ~~876~~ ~~879~~ bytes

*Saved two bytes thanks to @ZacharyT by removing unnecessary parentheses*

```
void settings(){size(600,600);}int i,w,x,n;float l,d,t,a,f,g,m,R,U;float[][]N,T;float[]S,p;void s(float[][]t){N=new float[t.length+1][2];N[0][0]=N[0][1]=i=0;for(float[]q:t)N[++i]=q;translate(w=300,w);noFill();pushMatrix();f(N,0,-w,w,1,0);popMatrix();f(N,0,-w,w,0,0);}float p(float a,float b){for(a+=PI*4;a>b;)a-=PI*2;return a;}void f(float[][]P,float x,float y,float L,int c,int I){l=2*PI;d=i=0;S=null;for(;i<P.length;i++){float[]p=P[i];g=atan2(y,x);m=atan2(p[1],p[0]);if(p(f=(c*2-1)*(g-m),0)<l&(t=dist(0,0,p[0],p[1]))<=L&I!=i){l=p(f,0);S=new float[]{g,m};d=t;n=i;}}if(S==null)ellipse(0,0,2*(L-d),2*(L-d));else{arc(0,0,L*2,L*2,p(S[c],S[1-c]),S[1-c]);R=cos(a=S[1]);U=sin(a);translate(d*R,d*U);T=new float[P.length][2];for(int i=0;i<T.length;T[i][1]=P[i][1]-d*U,i++)T[i][0]=P[i][0]-d*R;f(T,(L-d)*R,(L-d)*U,L-d,c,n);}}

```

Run this program like so:

```
void setup() {
    s(new float[][]{{0,100},{100,100},{-200,100},{-100,-50}});
}

```

(the function `s` takes in a `float[][]`). This is essentially testcase #3, but multiplied by 100 to fit the window.

Several things to note:

* the program does NOT draw poles
* the images appear flipped upside-down because in Processing's coordinate system, the positive y-axis goes down
* because Processing uses floats, the calculations are not very accurate, so you might see this in the images. I have asked the OP if these floating-point error matter.
* the size of the window is 600 pixels by 600 pixels
* very small input coordinates will bork the program because the stack `pushMatrix()` and `popMatrix()` operate on can only hold 32 matrices.
* the dog starts at (0, -300) and the chain starts at 300 pixels long
* the images below have been minified for convenience

Sample output for the above testcase.

If you want to see the prettified output, add this line right after the `translate(w,w);` in function `s`.

```
background(-1);scale(1,-1);fill(255,0,0);ellipse(0,0,25,25);fill(0);for(float[]q:N)ellipse(q[0],q[1],25,25);

```

And this gives us this result:

# Ungolfed `f()` and explanation

(contains debug code as well)

```
void f(float[][]points, float x, float y, float len, int c, int pindex) {
    print(asd+++")");
    float closest = 2*PI;
    float d=0,t;
    float[]stuff = null;
    int index = 0;
    for(int i=0;i<points.length;i++) {
        if(pindex != i) {
            float[]p = points[i];
            float originAngle = atan2(y, x);
            float tempAngle = atan2(p[1], p[0]);
            //println(x,y,p[0],p[1]);
            float diff = c<1?tempAngle-originAngle:originAngle-tempAngle;
            println("@\t"+i+"; x=\t"+x+"; y=\t"+y+"; tx=\t"+p[0]+"; ty=\t",p[1], diff, originAngle, tempAngle);
            if(p(diff) < closest && (t=dist(0,0,p[0],p[1])) < len) {
                println("+1");
                closest = p(diff);
                stuff = new float[]{originAngle, tempAngle};
                d=t;
                index = i;
            }
        }
    }
    if(stuff == null) {
        ellipse(0,0,2*(len-d),2*(len-d));
        println("mayday");
    } else {
        println("d angles",d,p(stuff[c],stuff[1-c],c), stuff[1-c]);
        //println(points[0]);
        arc(0, 0, len*2, len*2, p(stuff[c],stuff[1-c],c), stuff[1-c]);
        float angle = stuff[1];
        translate(d*cos(angle), d*sin(angle));
        println("Translated", d*cos(angle), d*sin(angle));
        println("angle",angle);
        float[][]temp=new float[points.length][2];
        for(int i=0;i<temp.length;i++){
            temp[i][0]=points[i][0]-d*cos(angle);
            temp[i][1]=points[i][1]-d*sin(angle);
            println(temp[i]);
        }
        println(d*sin(angle));
        pushMatrix();
        println();
        f(temp, (len-d)*cos(angle), (len-d)*sin(angle), (len-d), c, index);
        popMatrix();
        //f(temp, (len-d)*cos(angle), (len-d)*sin(angle), (len-d), 0, index);
    }
}

```

To put it shortly, the program sends two "seekers", one goes anti-clockwise and the other clockwise. Each of these seekers finds the closest pole and draws an arc to it if the chain is long enough, other wise it draws a circle. Once it draws an arc, it sends another seeker to that pole and the process continues. `f()` contains the process of each seeker. A more detailed explanation will come as soon as I golf this more.
> 7 votes

# Answer
## LOGO, ~~305~~ ~~298~~ ~~297~~ 293 bytes

Try the code on FMSLogo.

Define a function `draw` (golfed as `d`) that, given input as a list of pole coordinate (for example `draw [[0 100] [100 100] [-200 100] [-100 -50][0 0]]`, will draw on screen the result.

Requirements:

1. Initial rope length = 300 pixels. (as 3 pixels is too small)
2. `[0 0]` must be included in pole list. If debug code (draw poles) is turned on, then `[0 0]` must be the last item.
3. The dog start at coordinate `x=0, y=-300` (as in the problem description)

Possible optimizations:

1. -1 byte if exceptional case (the dog run into a pole) is not required to be mathematically correct by replacing `>=` with `>`

---

Golfed code:

```
to f
op(if ?=pos 360 modulo :m*(180+heading-towards ?)360)
end
to x :m[:1 300]
home
forever[make 2 filter[:1>=u ?](sort :p[(u ?)<u ?2])invoke[pd
arc -:m*f :1
pu
if 360=f[stop]make 1 :1-u ?
lt :m*f
setpos ?]reduce[if f<invoke[f]?2[?][?2]]:2]
end
to d :p
copydef "u "distance
foreach[1 -1]"x
end

```

---

Ungolfed code (`;` starts an inline comment (used for explanation), and `:` starts a variable name):

```
to f
    op ifelse ? = pos 360 modulo :m*(180 + heading - towards ?) 360
end

to x
    home
    foreach :poles [pu setpos ? pd circle 5] ; debug code
    make "length 300 ; initial length of rope
    forever [
        make "tmp filter [:length >= distance ?] ; floating point error makes > and >= similar,  ~
            ; but >= is correct mathematically ~
            (sort :poles [(distance ?) < distance ?2])
         ; the last = longest element will be rotated
        invoke [
            pd
            arc -:m*f :length
            pu
            if 360=f [stop]
            make "length :length - distance ?
            lt :m*f
            setpos ?
        ] reduce [
            if f < invoke[f]?2 [?] [?2]
        ] :tmp ; apply to use ? instead of :pos
    ]
end

to draw :poles
    foreach [1 -1] [[m]
        x
    ]
end

```
> 5 votes

# Answer
# Python 2 + PIL, 310 bytes

```
from PIL import Image
from cmath import*
I,_,X,P=Image.new('1',(300,300),'white'),abs,polar,input()
def r(s):
 a,C,l=0,0,3
 while _(a)<99:
  c=C+l*exp(1j*a);I.load()[c.real*30+150,150-c.imag*30]=0
  for p in P+[0]:
   N,E=X(C-c);n,e=X(C-p)
   if n<=N and _(E-e)<.1:l-=_(p-C);C=p
  a+=s
r(.01)
r(-.01)
I.show()

```

The script reads the list of points from stdin as a list of complex numbers.

```
printf '[complex(0,0.5)]' | python2 snippet.py

```

```
printf '[complex(0,1), complex(1,1)]' | python2 snippet.py

```
> 1 votes

---
Tags: code-golf, math, graphical-output, geometry
---


title: Increasing Goldbach partitions

text:
# Question
Title: Increasing Goldbach partitions
The Goldbach conjecture states that:

> every even number that is greater than 2 is the sum of two primes.

We will consider a Goldbach partition of a number **n** to be a pair of two primes adding to **n**. We are concerned with numbers is *of increasing Goldbach partition*. We measure the size of a number's Goldbach partitions by the size of the smallest prime in all of that number's partitions. A number is of increasing partition if this size is greater than the size of all smaller even numbers.

# Task

Given an even integer **n \> 2**, determine if **n** is of increasing Goldbach partition, and output two unique values, one if it is and one if it is not.

This is , so you should aim to minimize the number of bytes in your source code.

OEIS A025018

# Answer
> 5 votes
# Jelly, 12 bytes

```
ÆRðfạṂ
Ç€M⁼W

```

Try it online!

### How it works

```
Ç€M⁼W   Main link. Argument: n

Ç€      Map the helper link over [1, ..., n].
  M     Get all indices of the maximum.
    W   Wrap; yield [n].
   ⁼    Test the results to both sides for equality.

ÆRðfạṂ  Helper link. Argument: k

ÆR      Prime range; get all primes in R := [1, ..., k].
  ð     Begin a dyadic chain with arguments R and k.
    ạ   Absolute difference; yield k-p for each p in R.
   f    Filter; keep the q in R such that q = k-p for some p in R.
     Ṃ  Take the minimum.
        This yields 0 if the array is empty.

```

# Answer
> 4 votes
# PHP, 154 bytes

```
for(;$n++<$a=$argn;$i-1?:$p[]=$n)for($i=$n;--$i&&$n%$i;);foreach($p as$x)foreach($p as$y)if(!$r[$z=$x+$y]){$r[$z]=$x;$l[]=$z<$a?$x:0;};echo$r[$a]>max($l);

```

Try it online!

Expanded

```
for(;$n++<$a=$argn;$i-1?:$p[]=$n) # loop through all integers till input if is prime add to array
  for($i=$n;--$i&&$n%$i;);
foreach($p as$x) #loop through prime array
  foreach($p as$y) #loop through prime array
    if(!$r[$z=$x+$y]){
      $r[$z]=$x; # add only one time lower value for a sum of $x+$y
      $l[]=$z<$a?$x:0;}; # add lower value if sum is lower then input
echo$r[$a]>max($l); # Output 1 if lower value for sum of input is greater then all lower values of all numbers under input

```

Try it online! Check for all numbers till 1000

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

Uses a similar logic as Jörg's PHP answer.

```
(n,P=[...Array(n).keys()].filter(n=>(p=n=>n%--x?p(n):x==1)(x=n)))=>P.map(p=>P.map(q=>a[q+=p]=a[q]||(m=q<n&&p>m?p:m,p)),a=[m=0])&&a[n]>m

```

### Demo

```
let f =

(n,P=[...Array(n).keys()].filter(n=>(p=n=>n%--x?p(n):x==1)(x=n)))=>P.map(p=>P.map(q=>a[q+=p]=a[q]||(m=q<n&&p>m?p:m,p)),a=[m=0])&&a[n]>m

console.log(
  JSON.stringify(
    [...Array(310).keys()].filter(n => f(n))
  )
)
```

# Answer
> 2 votes
# Python 3: 156 151 142 138 136 128 bytes

```
r=range
m=lambda n:min(x for x in r(2,n+1)if all(o%i for o in[x,n-x]for i in r(2,o)))
f=lambda n:m(n)>max(map(m,r(2,n,2)))or n<5

```

(thanks to OP)

(thanks to @Rod)(again)(and again)

# Answer
> 1 votes
# Python 3: 204 196 bytes

Bytes saved thanks to: Olm Man

```
from itertools import*
m=lambda g:min([x for x in product([n for n in range(2,g)if all(n%i for i in range(2,n))],repeat=2)if sum(x)==g][0])
i=lambda g:1if all(m(g)>m(x)for x in range(4,g,2))else 0

```

Try it online!

---
Tags: code-golf, number-theory, decision-problem, primes
---


# Question
Title: Calculate the middle number of a row of the pascal triangle
Write a function that calculates a row of the pascal triangle and returns the middle number, if there are 2 it should return their sum.

Example:

`5`

would return

`20`

Example 2:

`4`

would return

`6`

**EDIT:**

To be clear:

a) if the number inputted is odd then find then return the middle number of a row on the pascal triangle.

b) if the number inputted is even then find the two middle numbers of the row on the pascal triangle and sum the 2 numbers.

The nth row is using zero-based indicies. For numbers other than zero, this is the row which has its second number as the number inputted into the function.

# Answer
# Ohm, 6 bytes

```
½⌠Ddac

```

Try it online!

If the number is even it is you calculate (n n/2) if it is odd (n+1 (n+1)/2)

```
         Inplicit input
½        Half
 ⌠       Ceil
  D      Duplicate on stack
   d     x2
    a    Swap on stack
     c   Binomial

```
> 5 votes

# Answer
# 05AB1E, ~~7~~ 5 bytes

Saved 2 bytes using the duplicate/swap technique from FrodCube's Ohm answer

```
;îxsc

```

Try it online!
> 2 votes

# Answer
# Python 2, ~~88~~ ~~81~~ ~~80~~ ~~79~~ ~~74~~ 72 bytes

Thanks to @JonathanAllen

```
import math
f=math.factorial
n=input()
print(n%2+1)*f(n)/f(n/2)/f(n-n/2)

```

Try it online!
> 1 votes

# Answer
# Jelly, 5 bytes

```
HĊµḤc

```

A monadic link, taking a (0-indexed) row and returning the middle number or the sum of the two middle numbers - equivalently the middle number of the row beneath).

Try it online!, or see the first 20 values in the test suite.

### How?

```
HĊµḤc - Link: number v
H     - halve = v/2
 Ċ    - ceiling, i.e. (v + isOdd?(v)) / 2
  µ   - monadic chain separation, call that k
   Ḥ  - double k (this is n: v if v was even, or v+1 if v was odd)
    c - that choose k = nCk, the required result

```
> 1 votes

# Answer
# , 35 bytes

```
function(n)(1+n%%2)*choose(n,n%/%2)

```

An anonymous function.

Since odd rows need to be doubled, `n%%2+1` is 2 when `n` is odd and `1` when `n`n is even. Then, I multiply by the appropriate binomial coefficient.

Try it online!
> 1 votes

# Answer
# Python 2, ~~40~~ 38 bytes

```
f=lambda n:n<1or(-n|1)*2*f(n-2)/(-n/2)

```

Try it online!
> 1 votes

# Answer
# Jelly, 8 bytes

```
c:2$×Ḃ‘$

```

Try it online!
> 0 votes

# Answer
# Dyalog APL, 12 bytes

```
{k!2×k←⌈⍵÷2}

```

or

```
(⊢!2∘×)∘⌈÷∘2

```

Try it online!

**How?**

`⍵÷2` \- divide by 2

\- ceiling

`k←` \- assign to `k`

\- double

`k!` \- binomial with `k`
> 0 votes

---
Tags: code-golf
---


title: Buzzby Berkeley Robot Hokey Pokey

text:
# Question
Title: Buzzby Berkeley Robot Hokey Pokey
## Buzzby Berkeley Robot Hokey Pokey

### Task

Write a program or function to produce an ASCII art animation depicting a line of robots dancing to the lyrics of the Hokey Pokey (or Cokey, if you prefer) in the style of a Busby Berkeley number!

### Example Output

### Input

Accepts three arguments (assumed to be valid):

**N** = number of robots in the line (Min=6)

**B** = duration of one "beat" in milliseconds (Min=10)

**D** = delay in ms between successive robots (Min=0)

(In the example output above: N=8, B=380, C=75)

### Specifications

1. **N** robots are shown in a row upon a stage.
2. One line of text from "the verse" is shown at a time beneath the stage (centred to within 1 character, and enclosed in quotation marks.)
3. The robots perform the actions for each line as it is shown until the verse has been repeated 5 times.
4. An action is performed by depicting a robot using a set of ASCII characters and waiting a specified duration before performing the next action. The duration of an action is measured in "beats". The duration of 1 beat is a number of milliseconds, **B**.
5. The first robot starts performing the actions for each line of verse immediately when the line's text is displayed.
6. Each subsequent robot delays starting its actions until a specific time (**D**) after the robot to its right (your left!) begins its actions.
7. Robots' depictions vary by the ASCII characters which represent a robot's "antenna", of which there are 5 possible types, distributed randomly every time the program is run.
8. Each type of antenna must be used by at least one robot, but the same type must not appear on any robots separated by fewer than 3 other robots. The amounts of any two types of antennae may differ by no more than 1 (e.g. 1xType\_4 and 3xType\_5's is illegal since 3-1\>1 )

### Verse and Actions

The whole verse is repeated 5 times, 1 line at a time...

```
Line  Text                            Action/Beats,
----  -----------------------------   ------------------------------------
1     You put your ? in               ??/4
2     You take your ? out             AA/4
3     You put your ? in               ??/4
4     And you shake it all about      AA/1, ??/1, AA/1, ??/1
5     You do the Hokey Pokey and...
      ...you turn yourself around     AA/1, H[1-7]/1
6     That's what it's all about!     AA/4, ZZ/4

```

For each repetition (R) of the verse, substitute ? and ??...

```
R   ?=           ??=
--  -----------  ---
1.  right foot   RF
2.  left foot    LF
3.  right hand   RH
4.  left hand    LH
5.  whole self   WS

```

### Actions and ASCII patterns

Each labelled action is represented by 5 lines of 8 ASCII symbols.
The representation of each action is as follows...

```
1 |   12     12        12    12        12     12      12
2 |  ['']   ['']      ['']  ['']      ['']   ['']   \[*-]
3 | └[__]┘ └[__]┘    └[__]┘┌[__]┘    └[__]┐ ┌[__]┐   [__]\
4 |   ||     /<        >\    <\        />    /  \     /|
5 |--------------------------------------------------------
  |\__AA__/\__RF__/\__LF__/\__RH__/\__LH__/\__WS__/\__ZZ__/

1 |   12     12_     34_      34      _34     _12     12
2 |  ['']    [" ]    [ _]    [__]    [_ ]    [ "]    ['']
3 | >[__]<   [_<]    [<.]   <[..]>   [.>]    [>_]   <[__]>
4 |   ||      |\      ||      /|      ||      |\      ||
5 |--------------------------------------------------------
  |\__H1__/\__H2__/\__H3__/\__H4__/\__H5__/\__H6__/\__H7__/

```

In row 1, replace "1-4" with corresponding symbol for each antenna type...

```
1 | 1234 1234 1234 1234 1234
  | \/\/ |┌┐| )||( |||| ┐/\┌ <-- Symbols 1-4 for...
  | 1    2    3    4    5    <-- ...antenna types 1-5

```

### Output

The entire scene must be rendered at least once immediately whenever the content of the scene changes in any way. (I.e. assuming the delay between robots' actions is \> 0, the output may be rendered no less than **N** times per action.)

Ideally, for an animation the console or equivalent output area is cleared before each update is rendered. To provide for languages unable to clear the console, output may also be rendered in a continuous stream, subject to the same requirement described above.

### Scoring

Winners are the shortest programs in each language, as well as the shortest overall.

**Exception 1** Because clearing the console each render is preferable though not required, bytes used exclusively for this luxurious purpose do not count towards the total bytes. This includes commands to clear the console, and padding output with blank lines to scroll the console contents out of view.

**Exception 2** CSS or effectively similar means used exclusively for the purpose of styling the output beyond the minimum requirements do not count towards the total bytes. E.g. `*{color:blue;text-align:center;}` counts as only 32-10=**22 bytes** since `color:blue;` doesn't serve to satisfy any specification, whereas centred text is specified.

### Meta

Inspired by (showing my age) the TRS-80 Dancing Demon, Android Nim, and of course Busby Berkeley (and no, I'm not **that** old).

# Answer
> 13 votes
Ladies and Gentlemen, please welcome our lovely

# Full Frontend-Stack Dance Group, 1,320 ~~1,378~~ ~~1,425~~ ~~1,495~~ bytes

JavaScript: **1,195 bytes** | CSS: **103 bytes** | HTML: **22 bytes**

---

This is a cute challenge. It also has lots of special cases. Oh boy, so many special cases. And those antennas …

It will run forever and restart after all actions (`left foot`, `right foot` etc.) are completed.

You can try it on jsFiddle or by using the code snippet thingy below:

```
t=setTimeout
c=l=a=i=0
_=(x,y,z)=>{if(!i)for(;++i<=x;q=~~(Math.random()*10))s.append(document.createElement('pre'))
for(i=l=0,c=a+1;i<33;)(i=>{t($=>{if(4==i){c=0
l=1}if(8==i){c=a+1
l=0}if(12==i|14==i){c=0
l=2}if(13==i|15==i)c=a+1
if(16==i){c=0
l=3}if(16<i&24>i)c=i-10
if(24==i){c=0
l=4}if(28==i)c=6
if(31<i){a=++a%5
_(x,y,z)}for(j=0;j<x;)(j=>{t($=>s.childNodes[j][h]=(-1<[1,3,8,9].indexOf(c)?'  ':2==c||4==c?'    ' :'   ')+(11==c||12==c?'_':'')+['\\/\\/','|┌┐|',')||(','||||','┐/\\┌'][(q+j)%4].substring($=8<c&12>c?2:0,$+2)+(8==c||9==c?'_':'')+'\n'+[`  ['']
 └[__]┘
   ||`,` ['']
└[__]┘
  /<`,`   ['']
  └[__]┘
    >\\`,` ['']
┌[__]┘
  <\\`,`   ['']
  └[__]┐
    />`,`  ['']
 ┌[__]┐
  /  \\`,` \\[*-]
  [__]\\
   <\\`,`  ['']
 >[__]<
   ||`,`  [" ]
  [_<]
   |\\`,`  [ _]
  [<.]
   ||`,`  [__]
 <[..]>
   /|`,`  [_ ]
  [.>]
   ||`,`  [ "]
  [>_]
   |\\`,`  ['']
 <[__]>
   ||`][c]+'\n-------',j*z)})(j++)
p[h='innerText']='"'+["You put your $ in","You take your $ out","And you shake it all about","You do the Hokey Pokey and you turn yourself around","That's what it's all about!"][l].replace('$',['right foot','left foot','right hand','left hand','whole self'][a])+'"'},i*y)})(i++)}

// let's dance (not included in the byte count – as if it would make any difference)
_(8, 400, 50)
```

```
*{text-align:center}x pre{display:inline-block;width:55px;text-align:left}pre{line-height:16px;margin:0
```

```
<x id=s></x><pre id=p>
```

---

Tested in Chrome and Firefox on macOS, Windows 10 and Ubuntu

---

**Edits**

* *Saved* **70 bytes** by removing the extra container to hold the antennas. Thanks to Bumpy. Also found some more whitespaces, removed the now unnecessary caching of `createElement` and removed the long access to `.firstChild`.
* *Saved* **47 bytes** – just realized that I actually don't need to call `getElementById`. This also makes the caching of `document` unnecessary.
* *Saved* **4 bytes** by replacing `||` and `&&` with bitwise `&` and `|`. Thanks to TheLethalCoder.
* *Saved* **54 bytes** by simplifying lots of small things and by optimizing the CSS.

# Answer
> 5 votes
## C#, 1188 1376 1382 bytes after exceptions

Compacted:

```
namespace System.Threading{using S=String;void H(int n,int b,int d){Console.CursorVisible=false;int t,u=0,v=5,w,x,y,z;S[]i=",That's what it's all about!,,You do the Hokey Pokey and you turn yourself around,And you shake it all about,,You take? out,You put? in".Split(',');i[0]=i[1];i[2]=i[3];i[5]=i[7];for(b=b<d*n?0:b-d*n;v-->0;)for(w=32;w-->0;Thread.Sleep(b))for(t=u,z=0;z++<n;Thread.Sleep(d)){S s="",r=i[w/4].Replace("?"," your "+(v<1?"whole self":(v%2<1?"right ":"left ")+(v/3<1?"hand":"foot")));u="88880000765432109090999900009999"[w];u=u>56?9+v:u-48;for(y=4;y-->0;s+="\n")for(x=0;x<n;x++)s+=S.Format(@"{0}{0}   |\   {0}   /|   {0}   |\   {0}   /|{4} /  \{4}  />{4}<\{4}{4}>\{4}/<{4} └{1}┘  >{1}<   [_<]{4}[<.]   <[..]>   [.>]{4}[>_]   <{1}>   {1}\  ┌{1}┐   └{1}┐┌{1}┘{4}└{1}┘└{1}┘   {2}  {2}   ["" ]{4}[ _]{4}{1}{4}[_ ]{4}[ ""]   {2}  \[*-]   {2}   {2}{2}{4}{2}{2}  {3}{3}  12_{4} 34_{4}  34{4}  _34{4} _12  {3}{3}{3} {3} 12{4} {3} 12{4}", "   ||   ","[__]"," [''] ","   12   ","    ").Substring(y*14+(x<z?u:t)<<3,8).Replace("12",@"\/|┌)|||┐/".Substring(x%5*2,2)).Replace("34",@"\/┐||(||\┌".Substring(x%5*2,2));Console.Clear();Console.Write(s+new S('-',n*8)+"\n"+new S(' ',n*4-r.Length/2)+r);}}}

```

Slightly nicer formatting and wrapped in an executable program:

```
namespace System.Threading{
    using S=String;

    //** Not counted towards score: execution wrapper
    class P{
        static void Main(S[]a){
            new P().H(int.Parse(a[0]),int.Parse(a[1]),int.Parse(a[2]));
        }
    //** End not counted towards score

        void H(int n,int b,int d){
            Console.CursorVisible=false;  // Not counted under exception 2
            int t,u=0,v=5,w,x,y,z;
            S[]i=",That's what it's all about!,,You do the Hokey Pokey and you turn yourself around,And you shake it all about,,You take? out,You put? in".Split(',');
            i[0]=i[1];
            i[2]=i[3];
            i[5]=i[7];
            for(b=b<d*n?0:b-d*n;v-->0;)
                for(w=32;w-->0;Thread.Sleep(b))
                    for(t=u,z=0;z++<n;Thread.Sleep(d)){
                        S s="",r=i[w/4].Replace("?"," your "+(v<1?"whole self":(v%2<1?"right ":"left ")+(v/3<1?"hand":"foot")));
                        u="88880000765432109090999900009999"[w];
                        u=u>56?9+v:u-48;
                        for(y=4;y-->0;s+="\n")
                            for(x=0;x<n;x++)
                                s+=S.Format(@"{0}{0}   |\   {0}   /|   {0}   |\   {0}   /|{4} /  \{4}  />{4}<\{4}{4}>\{4}/<{4} └{1}┘  >{1}<   [_<]{4}[<.]   <[..]>   [.>]{4}[>_]   <{1}>   {1}\  ┌{1}┐   └{1}┐┌{1}┘{4}└{1}┘└{1}┘   {2}  {2}   ["" ]{4}[ _]{4}{1}{4}[_ ]{4}[ ""]   {2}  \[*-]   {2}   {2}{2}{4}{2}{2}  {3}{3}  12_{4} 34_{4}  34{4}  _34{4} _12  {3}{3}{3} {3} 12{4} {3} 12{4}", "   ||   ","[__]"," [''] ","   12   ","    ").Substring(y*14+(x<z?u:t)<<3,8).Replace("12",@"\/|┌)|||┐/".Substring(x%5*2,2)).Replace("34",@"\/┐||(||\┌".Substring(x%5*2,2));
                        Console.Clear(); // Not counted under exception 1
                        Console.Write(s+new S('-',n*8)+"\n"+new S(' ',n*4-r.Length/2)+r);
                    }
        }
    } // Not counted towards score: end class
}

```

### Try it online!

1. Visit this link: tutorialspoint.com
2. In the **Default Term** tab at the bottom of the screen, type:
`mono main.exe 8 400 40`

### Edit 1

Replaced `string.Format(i,j)` with `i.Replace("?",j)` saving 6 bytes overall.

### Edit 2

Complete revamp with suggestions from the comments.

# Answer
> 0 votes
## JavaScript, 948 bytes

Probably poor form to answer your own question, but anyway...

Tried all sorts of ways to compress the text, but most ended up longer than the original with the key+algorithm included. I'm certain there's still a more optimal way to compress it all down, but I have to draw the line somewhere.

Interestingly, the search yielded one or two ideas for some other challenges which I might refine and post later.

```
<pre id=O/>

f=(N,B,D)=>{Q=c=>(K={},k='~',[...c].map(v=>v<k?K[k=v]='':K[k]+=K[v]||v),K[k])
x=``,A=`//,||,)||(,,/`.split(',').sort(new Date)
r=new Array(N).fill(0),t=i=v=0,n=`\n`,T=setTimeout
C=_=>(w=Q(`ouhand t t's ake Y y all abtokey righlefwhole fooself ,${v+1},,1yr ${x[v*2]+x[v*2+1]}puintt,,Ashi,do the HPaturn yrarnd,,7,8,90123,Twi!,,6,`).split(',')[i++])<'A'?(r.map((_,m)=>T((a,b)=>R(r[N-a]=b),m*D,m,w)),i>22?(v++,i=0):0,v<3?T(C,B*(i<7||i>21?4:1)):0):C(t=w),R=_=>{for(o='',m=4;m--;o+=n){for(w=N;w--;)o+=Q(`┌┐└┘\\/||/${A[w%5]}   [__] [''] ||] _ __ _  [*-][" ][ _][_ ][ "] ┐ ┐><[_<] [<.]<[..]>[.>] [>_]<> /<></>/ //`).substr(r[w]*8+(3-m)*112,8)}
O.innerHTML=o+'-'.repeat(N*8)+' '.repeat(((N*8)-t.length)/2)+t}
C()}

```

(**NB:** Contains some characters in the range 1-31 whose representations are a bit odd when posted here)

Watch the full psychedelic dance cycle on CodePen!

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


title: Generate a box based on user input

text:
# Question
Title: Generate a box based on user input
NOTE: This question is different than Draw an ASCII Rectangle because the user has to input only 1 number to generate a box, unlike the other question, where the user has to input the x and y size of the box.

Your task is to create a box based upon user input. Let's say I inputted 2. The box generated would look like:

```
--
--

```

As in, two by two long. Or, if I entered 7:

```
-------
|     |
|     |
|     |
|     |
|     |
-------

```

So, seven by seven.

Notice the box generated above has 5 bars up and seven hyphens across. The hyphen directly above or below the bars does count as one vertical iteration.

One more example. I enter 5. The box generated:

```
-----
|   |
|   |
|   |
-----

```

You can use any programming language you wish. The task is to be able to generate a box using the *least* possible amount of bytes.

Current leaderboard:

\[1\] dzaima in SOGL, 17 bytes

\[2\] Adam in APL, 27 bytes

\[3\] HyperNeutrino in Python, 51 bytes

# Answer
# SOGL V0.12, ~~21~~ 17 bytes

```
1.⁰{1.┐∙ž}:┐┌ŗH╬8

```

Try it Here!

Explanation:

```
1.⁰                push 1, input and wrap in an array
   {     }         for each item in that array do
    1                push 1
     .┐∙             get an array of input amount of items of "|"
        ž            at coordinates [currentArrayItem; 1] place those bars
          :        duplicate it
           ┐┌ŗ     replace "|" with "-"
              H    rotate anti-clockwise
               ╬8  place the 2nd array over the 1st

```
> 1 votes

# Answer
# APL (Dyalog), 27 bytes

```
'-'⍪'-'⍪⍨'|','|',⍨''⍴⍨2⍴-∘2

```

Try it online!

`-∘2` subtract two

`2⍴`**r**eshape into length 2

`''⍴⍨` use that as height and width to **r**eshape an empty string (padding with spaces)

`'|',⍨` put stiles on the right

`'|',` put stiles on the left

`'-'⍪⍨` put dashes below

`'-'⍪` put dashes on top
> 0 votes

# Answer
# JavaScript (ES6), ~~61~~ 60 bytes

```
n=>`${h="-"[r="repeat"](n)}
${`|${" "[r](n-=2)}|
`[r](n)}`+h

```
> 0 votes

# Answer
# Python, 51 bytes

```
lambda x:'-'*x+'\n'+('|'+' '*(x-2)+'|\n')*(x-2)+'-'*x

```

I tested this on my laptop and then manually wrote this answer on mobile so please tell me if this doesn't work.
> 0 votes

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


title: 12 hour time conversion

text:
# Question
Title: 12 hour time conversion
# Challenge

Convert and print out a time in a 12-hour format. `HH:MM AM/PM`

### Examples

Input:

* `'Fri Jun 30 2017 21:14:20 GMT-0700 (PDT)'`
* `'Fri Jun 30 2017 00:10:23 GMT-0700 (PDT)'`
* `'Fri Jun 30 2017 12:10:23 GMT-0700 (PDT)'`
* `'Sat Jun 31 2018 8:06:20 GMT-0700 (PDT)'`
* `'Fri Jul 01 2017 01:14:20 GMT-0700 (PDT)'`
* `'Sat Apr 10 2020 09:06:20 GMT-0700 (PDT)'`

Ouput:

* `9:14 PM`
* `12:10 AM`
* `12:10 PM`
* `08:06 AM`
* `1:14 AM`
* `09:06 AM`

### Fine Points

* A zero before a one digit number **is okay**, no zero is also allowed. The following examples are **both allowed**:

+ `9:06 AM`
    + `09:06 AM`
* All tested years will be after `999` (each year will be **exactly** `4` digits)

# Rules

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

```
d=>new Date(d).toLocaleString(0,{hour:n='numeric',minute:n,hour12:1})

```

```
f=
d=>new Date(d).toLocaleString(0,{hour:n='numeric',minute:n,hour12:1})
console.log(
  f('Fri Jun 30 2017 21:14:20 GMT-0700 (PDT)'),
  f('Fri Jun 30 2017 00:10:23 GMT-0700 (PDT)'),
  f('Fri Jun 30 2017 12:10:23 GMT-0700 (PDT)'),
  f('Sat Jun 31 2018 8:06:20 GMT-0700 (PDT)'),
  f('Fri Jul 01 2017 01:14:20 GMT-0700 (PDT)'),
  f('Sat Apr 10 2020 09:06:20 GMT-0700 (PDT)'),
)
```

---

# JavaScript (ES6), ~~58~~ 55 bytes

Assumes you are in the United States.

```
d=>new Date(d).toLocaleTimeString().replace(/:.. /,' ')

```

```
f=
d=>new Date(d).toLocaleTimeString().replace(/:.. /,' ')
console.log(
  f('Fri Jun 30 2017 21:14:20 GMT-0700 (PDT)'),
  f('Fri Jun 30 2017 00:10:23 GMT-0700 (PDT)'),
  f('Fri Jun 30 2017 12:10:23 GMT-0700 (PDT)'),
  f('Sat Jun 31 2018 8:06:20 GMT-0700 (PDT)'),
  f('Fri Jul 01 2017 01:14:20 GMT-0700 (PDT)'),
  f('Sat Apr 10 2020 09:06:20 GMT-0700 (PDT)')
)
```

---

# JavaScript (ES6), ~~81~~ 78 bytes

Answer before outputting a leading 0 in single-digit hours was made optional and test cases without leading 0s were added.

```
d=>([m,s]=d.slice(16).split`:`,`0${m%12||12}:${s} ${m<12?'A':'P'}M`.slice(-8))

```

```
f=
d=>([m,s]=d.slice(16).split`:`,`0${m%12||12}:${s} ${m<12?'A':'P'}M`.slice(-8))
console.log(
  f('Fri Jun 30 2017 21:14:20 GMT-0700 (PDT)'),
  f('Sat Jun 31 2018 08:06:20 GMT-0700 (PDT)'),
  f('Fri Jul 01 2017 01:14:20 GMT-0700 (PDT)'),
  f('Sat Apr 10 2020 09:06:20 GMT-0700 (PDT)')
)
```

# Answer
> 6 votes
# Python 2, 66 bytes

```
lambda s:`int(s[15:18])%12`+s[18:21]+'  APMM'[int(s[15:18])>11::2]

```

Try it online!

# Answer
> 5 votes
# sh + coreutils, 22 bytes

```
date +%I:%M\ %p -d"$1"

```

(If seconds are allowed, then `date +%r -d"$1"` suffices.)

# Answer
> 4 votes
## JavaScript (ES6), 77 bytes

Assumes that the year has 4 digits.

```
s=>`${([,,,h,m]=s.match(/\d./g),x=h%12||12)>9?x:'0'+x}:${m} ${'AP'[h/12|0]}M`

```

### Test cases

```
let f =

s=>`${([,,,h,m]=s.match(/\d./g),x=h%12||12)>9?x:'0'+x}:${m} ${'AP'[h/12|0]}M`

console.log(f('Fri Jun 30 2017 21:14:20 GMT-0700 (PDT)')) // 09:14 PM
console.log(f('Fri Jun 30 2017 00:10:23 GMT-0700 (PDT)')) // 12:10 AM
console.log(f('Fri Jun 30 2017 12:10:23 GMT-0700 (PDT)')) // 12:10 PM
console.log(f('Sat Jun 31 2018 08:06:20 GMT-0700 (PDT)')) // 08:06 AM
console.log(f('Fri Jul 01 2017 01:14:20 GMT-0700 (PDT)')) // 01:14 AM
console.log(f('Sat Apr 10 2020 09:06:20 GMT-0700 (PDT)')) // 09:06 AM
```

# Answer
> 2 votes
# Japt, 15 bytes

```
ÐU¯24)s8 r.³+SS

```

Try it online!

12 bytes if we can assume that the time will be given in the computer's local time:

```
ÐU s8 r.³+SS

```

Try it online!

### Mathy approach, 40 bytes

```
tG5 r"^.."_<C?+Z+B:°TnZ)%CÄÃ+" {"AP"gT}M

```

Test it online!

# Answer
> 1 votes
# , 36 bytes

```
16x3wC AMÇ^0ü^1[0-2]/12WrP
ç^ä:/é0

```

Try it online!

Hexdump:

```
00000000: 3136 7833 7743 2041 4d1b c75e 30fc 5e31  16x3wC AM..^0.^1
00000010: 5b30 2d32 5d2f 3132 1857 7250 0ae7 5ee4  [0-2]/12.WrP..^.
00000020: 3a2f e930                                :/.0

```

# Answer
> 1 votes
# PHP, 45 bytes

Answer improved thanks to manatwork

```
<?=(new DateTime($argv[1]))->format('h:i A');

```

First attempt:

```
<? $d=new DateTime($argv[1]);echo$d->format('h:i A');

```

Example usage through php CLI:

```
php d.php "Sat Apr 10 2020 09:06:20 GMT-0700 (PDT)"

```

This is my first golf try.

# Answer
> 1 votes
# Jelly, 43 bytes

```
Ḳ5ịṣ”:Ṗṁ3µV’%12‘Dµ1¦µV>11ị⁾PAµ3¦“0: M”żFṫ-7

```

Try it online!

This is *superfluously too long*! That is, Jelly sucks at time manipulation.

EDIT: I'm even outgolfed by PHP!

# Answer
> 0 votes
# Go, 103 bytes

```
func f(s*string){t,_:=time.Parse("Mon Jan 02 2006 15:04:05 MST-0700 (MST)",*s)
*s=t.Format("03:04 PM")}

```

Test here: https://play.golang.org/p/P1zRWGske-

# Answer
> 0 votes
# MATL, 9 bytes

```
5:24)16XO

```

Try it at MATL online! Or verify all test cases.

### Explanation

```
5:24    % Push array [5 6 ... 24]
)       % Implicit input. Get characters at those positions. This
        % removes the first four characters with the day of the week
16      % Push 16
XO      % Convert to date string format 16, which is 'HH:MM PM'
        % Implicitly display

```

# Answer
> 0 votes
# 05AB1E, 39 bytes

```
#4è':¡¨`sD11›„APès<12%>0ìR2£R)Á… :M‚øJJ

```

Try it online!

# Answer
> 0 votes
# PHP, 42 bytes

```
<?=date_create($argv[1])->format('h:i A');

```

Try it online!

# Answer
> 0 votes
# C#, 145 bytes

```
namespace System.Linq{s=>{var d=DateTime.Parse(string.Join(" ",s.Split(' ').Skip(1).Take(4)));return d.ToString("h:mm ")+(d.Hour>11?"PM":"AM");}}

```

Full/Formatted version:

```
namespace System.Linq
{
    class P
    {
        static void Main()
        {
            Func<string, string> f = s =>
            {
                var d = DateTime.Parse(string.Join(" ", s.Split(' ').Skip(1).Take(4)));

                return d.ToString("h:mm ") + (d.Hour > 11 ? "PM" : "AM");
            };

            Console.WriteLine(f("Fri Jun 30 2017 21:14:20 GMT-0700 (PDT)"));
            Console.WriteLine(f("Fri Jun 30 2017 00:10:23 GMT-0700 (PDT)"));
            Console.WriteLine(f("Fri Jun 30 2017 12:10:23 GMT-0700 (PDT)"));
            Console.WriteLine(f("Fri Jul 01 2017 01:14:20 GMT-0700 (PDT)"));
            Console.WriteLine(f("Sat Apr 10 2020 09:06:20 GMT-0700 (PDT)"));

            Console.ReadLine();
        }
    }
}

```

# Answer
> 0 votes
# ,,,, 41 bytes

```
::18⊢3⊣⇆15⊢3⊣i11>"  APMM"⇆⊢2⟛↔15⊢3⊣i12%s#

```

## Explanation

WIP

---
Tags: code-golf
---


title: Draw an ASCII Rectangle

text:
# Question
Title: Draw an ASCII Rectangle
Given two integers as input in an array, draw a rectangle, using the first integer as width and second as height.

Or, if your language supports it, the two integers can be given as separate inputs.

Assume the width and height will never be less than 3, and they will always be given.

Example Outputs:

**\[3, 3\]**

```
|-|
| |
|-|

```

**\[5, 8\]**

```
|---|
|   |
|   |
|   |
|   |
|   |
|   |
|---|

```

**\[10, 3\]**

```
|--------|
|        |
|--------|

```

This is code-golf, so the answer with the lowest amount of bytes wins.

# Answer
# Jolf, 6 bytes

```
,ajJ'|

```

Try it here! My box builtin finally came in handy! :D

```
,ajJ'|
,a       draw a box
  j      with width (input 1)
   J     and height (input 2)
    '    with options
     |    - corner
          - the rest are defaults

```
> 6 votes

# Answer
# Jelly, 14 bytes

```
,þ%,ỊḄị“-|| ”Y

```

Try it online! or verify all test cases.

### How it works

```
,þ%,ỊḄị“-|| ”Y  Main link. Left argument: w. Right argument: h

,þ              Pair table; yield a 2D array of all pairs [i, j] such that
                1 ≤ i ≤ w and 1 ≤ j ≤ h.
   ,            Pair; yield [w, h].
  %             Take the remainder of the element-wise division of each [i, j]
                by [w, h]. This replaces the highest coordinates with zeroes.
    Ị           Insignificant; map 0 and 1 to 1, all other coordinates to 0.
     Ḅ          Unbinary; convert each pair from base 2 to integer.
                  [0, 0] -> 0 (area)
                  [0, 1] -> 1 (top or bottom edge)
                  [1, 0] -> 2 (left or right edge)
                  [1, 1] -> 3 (vertex)
       “-|| ”   Yield that string. Indices are 1-based and modular in Jelly, so the
                indices of the characters in this string are 1, 2, 3, and 0.
      ị         At-index; replace the integers by the correspoding characters.
             Y  Join, separating by linefeeds.

```
> 10 votes

# Answer
# Matlab, ~~69~~ ~~65~~ 56 bytes

Thanks @WeeingIfFirst and @LuisMendo for some bytes=)

```
function z=f(a,b);z(b,a)=' ';z([1,b],:)=45;z(:,[1,a])='|'

```

This is really simple in Matlab: First make a matrix of the desired size, then index the first and last row to insert the `-`, and do the same with the first and last column to insert `|`.

For example `f(4,3)` returns

```
|--|
|  |
|--|

```
> 9 votes

# Answer
# PHP, 74 Bytes

```
for(;$i<$n=$argv[2];)echo str_pad("|",$argv[1]-1,"- "[$i++&&$n-$i])."|\n";

```
> 8 votes

# Answer
## JavaScript (ES6), 63 bytes

```
f=
(w,h,g=c=>`|${c[0].repeat(w-2)}|
`)=>g`-`+g` `.repeat(h-2)+g`-`
;
```

```
<div oninput=o.textContent=f(w.value,h.value)><input id=w type=number min=3 value=3><input id=h type=number min=3 value=3><pre id=o>
```
> 8 votes

# Answer
## Haskell, ~~62~~ 55 bytes

```
f[a,b]n=a:(b<$[3..n])++[a]
g i=unlines.f[f"|-"i,f"| "i]

```

Usage example:

```
*Main> putStr $ g 10 3
|--------|
|        |
|--------|

```

The helper function `f` takes a two element list `[a,b]` and a number `n` and returns a list of one `a` followed by `n-2` `b`s followed by one `a`. We can use `f` thrice: to build the top/bottom line: `f "|-" i`, a middle line: `f "| " i` and from those two the whole rectangle: `f [<top>,<middle>] j` (note: `j` doesn't appear as a parameter in `g i` because of partial application).

Edit: @dianne saved some bytes by combining two `Char` arguments into one `String` of length 2. Thanks a lot!
> 8 votes

# Answer
# Python 2, ~~61~~ 58 bytes

-3 bytes thanks to @flornquake (remove unnecessary parentheses; use `h` as counter)

```
def f(w,h):exec"print'|'+'- '[1<h<%d]*(w-2)+'|';h-=1;"%h*h

```

Test cases are at **ideone**
> 8 votes

# Answer
# Vimscript, ~~93~~ ~~83~~ ~~75~~ ~~74~~ ~~73~~ ~~66~~ ~~64~~ 63 bytes

# Code

```
fu A(...)
exe "norm ".a:1."i|\ehv0lr-YpPgvr dd".a:2."p2dd"
endf

```

## Example

```
:call A(3,3)

```

## Explanation

```
fun A(...)    " a function with unspecified params (a:1 and a:2)
exe           " exe(cute) command - to use the parameters we must concatenate :(
norm          " run in (norm) al mode
#i|           " insert # vertical bars
\e            " return (`\<Esc>`) to normal mode
hv0l          " move left, enter visual mode, go to the beginning of the line,  move right (selects inner `|`s)
r-            " (r)eplace the visual selection by `-`s
YpP           " (Y) ank the resulting line, and paste them twice
gv            " re-select the previous visual selection
r<Space>      " replace by spaces
dd            " Cut the line
#p            " Paste # times (all inner rows)
2dd           " Remove extra lines

```

Note that it is not using `norm!` so it might interfere with vim custom mappings!
> 7 votes

# Answer
# 05AB1E, ~~23~~ ~~22~~ 20 bytes

Input taken as height, then width.

```
F„ -N_N¹<Q~è²Í×'|.ø,

```

**Explanation**

```
F                          # height number of times do
    N_                     # current row == first row
          ~                # OR
      N¹<Q                 # current row == last row
 „ -       è               # use this to index into " -"
            ²Í×            # repeat this char width-2 times
               '|          # push a pipe
                 .ø        # surround the repeated string with the pipe
                   ,       # print with newline

```

Try it online!

Saved 2 bytes thanks to Adnan
> 5 votes

# Answer
# MATL, 19 bytes

```
'|-| '2:"iqWQB]E!+)

```

Try it online!

### Explanation

The approach is similar to that used in this other answer. The code builds a numerical array of the form

```
3 2 2 2 3
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
3 2 2 2 3

```

and then its values are used as (1-based, modular) indices into the string `'|-| '` to produce the desired result.

```
'|-| '                % Push this string
      2:"     ]       % Do this twice
         i            % Take input
          q           % Subtract 1
           W          % 2 raised to that
            Q         % Add 1
             B        % Convert to binary
               E      % Multiply by 2
                !     % Transpose
                 +    % Add with broadcast
                  )   % Index (modular, 1-based) into the string

```
> 5 votes

# Answer
# C, 73 bytes

```
i;f(w,h){for(i=++w*h;i--;)putchar(i%w?~-i%w%~-~-w?i/w%~-h?32:45:124:10);}

```
> 5 votes

# Answer
## Common Lisp, 104 bytes

Golfed:

```
(defun a(w h)(flet((f(c)(format t"|~v@{~A~:*~}|~%"(- w 2)c)))(f"-")(loop repeat(- h 2)do(f" "))(f"-")))

```

Ungolfed:

```
(defun a (w h)
  (flet ((f (c) (format t "|~v@{~A~:*~}|~%" (- w 2) c)))
    (f "-")
    (loop repeat (- h 2) do
     (f " "))
    (f "-")))

```
> 4 votes

# Answer
# Python 2, 56 bytes

```
w,h=input()
for c in'-%*c'%(h-1,45):print'|'+c*(w-2)+'|'

```

flornquake saved one byte.
> 4 votes

# Answer
# Mathematica, ~~67~~ 64 bytes

*Thanks to lastresort and TuukkaX for reminding me that golfers should be sneaky and saving 3 bytes!*

Straightforward implementation. Returns an array of strings.

```
Table[Which[j<2||j==#,"|",i<2||i==#2,"-",0<1," "],{i,#2},{j,#}]&

```
> 3 votes

# Answer
# Turtlèd, 40 bytes

Interpreter is ~~slightly~~ no longer buggèd

```
?;,u[*'|u]'|?@-[*:l'|l[|,l]d@ ],ur[|'-r]

```

## Explanation

```
?                            - input integer into register
 ;                           - move down by the contents of register
  ,                          - write the char variable, default *
   u                         - move up
    [*   ]                   - while current cell is not *
      '|                     - write |
        u                    - move up
          '|                 - write | again
            ?                - input other integer into register
             @-              - set char variable to -
               [*             ] - while current char is not *
                 :l'|l          - move right by amount in register, move left, write |, move left again
                      [|,l]     - while current cell is not |, write char variable, move left
                           d@   - move down, set char variable to space (this means all but first iteration of loop writes space)
                               ,ur   -write char variable, move up, right
                                  [|   ] -while current char is not |
                                    '-r - write -, move right

```
> 3 votes

# Answer
# Python 3, ~~104~~ 95 bytes

( feedback from @mbomb007 : -9 bytes)

```
def d(x,y):return'\n'.join(('|'+('-'*(x-2)if n<1or n==~-y else' '*(x-2))+'|')for n in range(y))

```

(my first code golf, appreciate feedback)
> 3 votes

# Answer
# Ruby, ~~59~~ ~~54~~ 52 bytes

Oh, that's a lot simpler :)

```
->x,y{y.times{|i|puts"|#{(-~i%y<2??-:' ')*(x-2)}|"}}

```

Test run at ideone
> 2 votes

# Answer
# PHP, 82 bytes

```
list(,$w,$h)=$argv;for($p=$h--*$w;$p;)echo$p--%$w?$p%$w?$p/$w%$h?" ":"-":"|
":"|";

```

indexing a static string including the newline

```
list(,$w,$h)=$argv;         // import arguments
for($p=$h--*++$w;$p;)       // loop $p through all positions counting backwards
    // decrease $h and increase $w to avoid parens in ternary conditions
    echo" -|\n"[
        $p--%$w             // not (last+1 column -> 3 -> "\n")
        ?   $p%$w%($w-2)    // not (first or last row -> 2 -> "|")
            ?+!($p/$w%$h)   // 0 -> space for not (first or last row -> 1 -> "-")
            :2
        :3
    ];

```
> 2 votes

# Answer
## Batch, 128 bytes

```
@set s=
@for /l %%i in (3,1,%1)do @call set s=-%%s%%
@echo ^|%s%^|
@for /l %%i in (3,1,%2)do @echo ^|%s:-= %^|
@echo ^|%s%^|

```

Takes width and height as command-line parameters.
> 2 votes

# Answer
# Haxe, ~~112~~ 106 bytes

```
function R(w,h){for(l in 0...h){var s="";for(i in 0...w)s+=i<1||i==w-1?'|':l<1||l==h-1?'-':' ';trace(s);}}

```

## Testcases

```
R(5, 8)
|---|
|   |
|   |
|   |
|   |
|   |
|   |
|---|

R(10, 3)
|---------|
|         |
|---------|

```
> 2 votes

# Answer
# Java 135 bytes

```
public String rect(int x, int y){
String o="";
for(int i=-1;++i<y;){
o+="|";
for(int j=2;++j<x)
if(i<1||i==y-1)
o+="-";
else
o+=" ";
o+="|\n";
}
return o;
}

```

Golfed:

```
String r(int x,int y){String o="";for(int i=-1;++i<y;){o+="|";for(int j=2;++j<x;)if(i<1||i==y-1)o+="-";else o+=" ";o+="|\n";}return o;}

```
> 2 votes

# Answer
# Lua, 120 93 bytes

Saved quite a few bytes by removing stupid over complexities.

```
function(w,h)function g(s)return'|'..s:rep(w-2)..'|\n'end b=g'-'print(b..g' ':rep(h-2)..b)end

```

Ungolfed:

```
function(w,h)                           -- Define Anonymous Function
    function g(s)                       -- Define 'Row Creation' function. We use this twice, so it's less bytes to function it.
        return'|'..s:rep(w-2)..'|\n'    -- Sides, Surrounding the chosen filler character (' ' or '-'), followed by a newline
    end
    b=g'-'                              -- Assign the top and bottom rows to the g of '-', which gives '|---------|', or similar.
    print(b..g' ':rep(h-2)..b)          -- top, g of ' ', repeated height - 2 times, bottom. Print.
end

```

Try it on Repl.it
> 2 votes

# Answer
## PowerShell v3+, 55 bytes

```
param($a,$b)1..$b|%{"|$((' ','-')[$_-in1,$b]*($a-2))|"}

```

Takes input `$a` and `$b`. Loops from `1` to `$b`. Each iteration, we construct a single string. The middle is selected from an array of two single-length strings, then string-multiplied by `$a-2`, while it's surrounded by pipes. The resulting strings are left on the pipeline, and output via implicit `Write-Output` happens on program completion, with default newline separator.

Alternatively, also at 55 bytes

```
param($a,$b)1..$b|%{"|$((''+' -'[$_-in1,$b])*($a-2))|"}

```

This one came about because I was trying to golf the array selection in the middle by using a string instead. However, since `[char]` times `[int]` isn't defined, we lose out on the savings by needing to cast as a string with parens and `''+`.

Both versions require v3 or newer for the `-in` operator.

### Examples

```
PS C:\Tools\Scripts\golfing> .\draw-an-ascii-rectangle.ps1 10 3
|--------|
|        |
|--------|

PS C:\Tools\Scripts\golfing> .\draw-an-ascii-rectangle.ps1 7 6
|-----|
|     |
|     |
|     |
|     |
|-----|

```
> 2 votes

# Answer
# Perl, 48 bytes

Includes +1 for `-n`

Give sizes as 2 lines on STDIN

```
perl -nE 'say"|".$_ x($`-2)."|"for"-",($")x(<>-1-/$/),"-"'
3
8
^D

```

Just the code:

```
say"|".$_ x($`-2)."|"for"-",($")x(<>-1-/$/),"-"

```
> 2 votes

# Answer
## bash, sed and coreutils, 95 89 bytes

You can define a function like this

```
f(){ n=$[$1-2];yes \ |sed $[$2*n]q|tr -d \\n|fold -w$n|sed 's/^\|$/|/g;1!{$!b};s/ /-/g';}

```

Or in a more readable format:

```
f() {
  n=$(($1-2))

  # The next couple of lines create a rectangle of spaces
  # matching the desired size
  yes ' '          |
  head -n$(($2*n)) |
  tr -d '\n'       |
  fold -w$n        |

  # Add the pipes and dashes
  sed '
    s/^\|$/|/g   # Replace first and last character by a pipe
    1! {$!b }    # Do nothing if not on first or last line
    s/ /-/g      # Add the dashes
  '
  echo
}

```

You can now say `f 4 3`:

```
|--|
|  |
|--|

```

If you care about trailing new-line, add an echo at the end of function.
> 1 votes

# Answer
# Python 2, 67 bytes

```
def f(a,b):c="|"+"-"*(a-2)+"|\n";print c+c.replace("-"," ")*(b-2)+c

```

**Examples**

```
f(3,3)

|-|
| |
|-|

f(5,8)

|---|
|   |
|   |
|   |
|   |
|   |
|   |
|---|

f(10,3)

|--------|
|        |
|--------|

```
> 1 votes

# Answer
# MATL, ~~21~~ 17 bytes

```
Z"45ILJhY('|'5MZ(

```

This is a slightly different approach than the one of the MATL-God.

```
Z"                   Make a matrix of spaces of the given size
  45ILJhY(           Fill first and last row with '-' (code 45)
          '|'5MZ(    Fill first and last column with '|' (using the automatic clipboard entry 5M to get ILJh back)

```

Thanks @LuisMendo for all the help!

Try it Online!
> 1 votes

# Answer
# PHP 4.1, 76 bytes

```
<?$R=str_repeat;echo$l="|{$R('-',$w=$W-2)}|
",$R("|{$R(' ',$w)}|
",$H-2),$l;

```

This assumes you have the default `php.ini` settings for this version, including `short_open_tag` and `register_globals` enabled.

This requires access through a web server (e.g.: Apache), passing the values over session/cookie/POST/GET variables.
The key `W` controls the width and the key `H` controls the height.
For example: `http://localhost/file.php?W=3&H=5`
> 1 votes

# Answer
# Python 3, 74 chars

```
p="|"
def r(w,h):m=w-2;b=p+"-"*m+p;return b+"\n"+(p+m*" "+p+"\n")*(h-2)+b

```
> 1 votes

# Answer
# Python (70 bytes)

```
def r(w,h): print '\n'.join(['|'+('-' if i%(h-1)==0 else ' ')*(w-2)+'|' for i in range(h)])

```

Edit: lambda function for a few less bytes (thanks @DJMcMayhem)

```
r=lambda w,h:'\n'.join(['|'+('-'if i%(h-1)==0 else' ')*(w-2)+'|'for i in range(h)])

```

Edit#2: `if` notation is greedy

```
r=lambda w,h:'\n'.join(['|'+(0<i<h-1 and' 'or'-')*(w-2)+'|'for i in range(h)])

```

Edit#3: -8 bytes with list trick

```
r=lambda w,h:'\n'.join(['|'+'- '[0<i<h-1]*(w-2)+'|'for i in range(h)])

```
> 1 votes

# Answer
# C#, 102 93 bytes

*Saved 9 bytes thanks to milk \- completely forgot to concatenate strings. The compare trick is pretty cool too.*

```
w=>h=>{var s="";for(int i=0;i<h;)s+="|"+new String(1>i++%(h-1)?'-':' ',w-2)+"|\n";return s;};

```

**Try it online!**

Full source, including test cases:

```
using System;

namespace DrawASCIIRectangle
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<int,Func<int,string>> d= w=>h=>{var s="";for(int i=0;i<h;)s+="|"+new String(1>i++%(h-1)?'-':' ',w-2)+"|\n";return s;};
            Console.WriteLine(d(3)(3));
            Console.WriteLine(d(5)(8));
            Console.WriteLine(d(10)(3));
        }
    }
}

```
> 1 votes

# Answer
# Swift(2.2) 190 bytes

```
let v = {(c:String,n:Int) -> String in var s = "";for _ in 1...n {s += c};return s;};_ = {var s = "|"+v("-",$0-2)+"|\n" + v("|"+v(" ",$0-2)+"|\n",$1-2) + "|"+v("-",$0-2)+"|";print(s);}(10,5)

```

I think Swift 3 could golf this a lot more but I don't feel like downloading Swift 3.
> 1 votes

# Answer
**C 87 bytes**

```
f(b,a,c,k){for(;c<a*b;++c)printf("%s",(k=c%b)==b-1?"|":!k?"\n|":c<b||c>a*b-b?"-":" ");}

```

this is the main for some test...

```
main()
{f(3,3,0,0); f(5,8,0,0); f(10,3,0,0);
 return 0;
}

|-|
| |
|-|
|---|
|   |
|   |
|   |
|   |
|   |
|   |
|---|
|--------|
|        |
|--------|

```
> 1 votes

# Answer
## F#, 131 bytes

```
let d x y=
 let q = String.replicate (x-2)
 [for r in [1..y] do printfn "%s%s%s" "|" (if r=y||r=1 then(q "-")else(q " ")) "|"]

```
> 1 votes

# Answer
# Pyth, 22 bytes

```
VJE.[Q*-Q2?}N,0tJ\-d\|

```

A program that takes input of the width, followed by the height, on STDIN and prints the result.

Try it online

**How it works**

```
VJE.[Q*-Q2?}N,0tJ\-d\|  Program. Inputs: Q, E
 JE                     Assign E to J
V                       For N in [0, 1, 2, ..., J-1]:
             ,0tJ        Yield [0, J-1]
           }N            N is in that list
          ?              If that:
                 \-       Yield "-"
                         Else:
                   d      Yield " "
      *-Q2               Repeat that Q-2 times
   .[Q              \|   Evenly pad that with "|" on both sides to length Q
                         Implicitly print

```
> 0 votes

# Answer
## Actually, 35 bytes

```
¬'|@α(¬;)' *╗`╜o'|o`Mi('-*"|%s|"%;)

```

Try it online!

Explanation:

```
¬'|@α(¬;)' *╗`╜o'|o`Mi('-*"|%s|"%;)
¬                                    height - 2
 '|@α                                ["|" for _ in range(height-2)]
     (¬;)                            width - 2, duplicate, move to bottom of stack
         ' *                         " "*(width-2)
            ╗                        save to register 0
             `╜o'|o`M                for each "|" in list of "|"s:
              ╜o                       append (width-2) spaces
                '|o                    append a second "|"
                     i               flatten list
                      (              bring copy of (width-2) back to top
                       '-*           "-"*(width-2)
                          "|%s|"%    surround with "|"s
                                 ;)  dupe, move copy to bottom of stack
                                     (implicitly print stack contents, one element per line)

```
> 0 votes

# Answer
# Python 3, 68 bytes

```
def f(a,b):
 c='|'+'-'*(a-2)+'|\n';print(c+c.replace(*'- ')*(b-2)+c)

```
> 0 votes

# Answer
## Racket 108 bytes

```
(λ(w h)(for((j h))(display #\|)(for((i(- w 2)))(display(if(or(= j 0)(= j(- h 1)))#\-" ")))(displayln #\|)))

```

Ungolfed:

```
(define f
  (λ (w h)
    (for ((j h))
      (display #\|)
      (for ((i (- w 2)))
        (display (if (or
                      (= j 0)
                      (= j (- h 1)))
                     #\-
                     " ")))
      (displayln #\|))))

```

Testing:

```
(f 5 3)

```

Output:

```
|---|
|   |
|---|

```
> 0 votes

# Answer
# APL (Dyalog Unicode), 25 bytes

```
'|','|',⍨'-'⍪'-'⍪⍨''⍴⍨-∘2

```

Try it online!

`-∘2` subtract two

`''⍴⍨` use that as height and width to **r**eshape an empty string (padding with spaces)

`'-'⍪⍨` put dashes below

`'-'⍪` put dashes on top

`'|',⍨` put stiles on the right

`'|',` put stiles on the left
> 0 votes

# Answer
# Python, 105 bytes

```
[a,b]=input().split()
def d(e):print("|"+e*(int(a)-2)+"|")
d("-")
for f in range(2,int(b)):d(" ")
d("-")

```

Try it online
> 0 votes

# Answer
# tcl, 99

```
puts [set M |[string repe - [incr w -2]]|]
incr w
time {puts |[format %$w\s |]} [incr h -2]
puts $M

```

# demo
> 0 votes

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


# Question
Title: Compute the inverse of an integer modulo 100000000003
The task is the following. Given an integer `x` (such that `x` modulo `100000000003` is not equal to `0`) presented to your code in any way you find convenient, output another integer `y < 100000000003` so that `(x * y) mod 100000000003 = 1`.

You code must take less than 30 minutes to run on a standard desktop machine for *any* input `x` such that `|x| < 2^40`.

**Test cases**

Input: 400000001. Output: 65991902837

Input: 4000000001. Output: 68181818185

Input: 2. Output: 50000000002

Input: 50000000002. Output: 2.

Input: 1000000. Output: 33333300001

**Restrictions**

You may not use any libraries or builtin functions that perform modulo arithmetic (or this inverse operation). This means you can't even do `a % b` without implementing `%` yourself. You can use all other non-modulo arithmetic builtin functions however.

**Similar question**

This is similar to this question although hopefully different enough to still be of interest.

# Answer
# Pyth, 24 bytes

```
L-b*/bJ+3^T11Jy*uy^GT11Q

```

Test suite

This uses the fact that a^(p-2) mod p = a^-1 mod p.

First, I manually reimplement modulus, for the specific case of mod 100000000003. I use the formula `a mod b = a - (a/b)*b`, where `/` is floored division. I generate the modulus with `10^11 + 3`, using the code `+3^T11`, then save it in `J`, then use this and the above formula to calculate b mod 100000000003 with `-b*/bJ+3^T11J`. This function is defined as `y` with `L`.

Next, I start with the input, then take it to the tenth power and reduce mod 100000000003, and repeat this 11 times. `y^GT` is the code executed in each step, and `uy^GT11Q` runs it 11 times starting with the input.

Now I have `Q^(10^11) mod 10^11 + 3`, and I want `Q^(10^11 + 1) mod 10^11 + 3`, so I multiply by the input with `*`, reduce it mod 100000000003 with `y` one last time, and output.
> 16 votes

# Answer
# Haskell, 118 113 105 101 bytes

Inspired from this solution.

*-12 from Ørjan Johansen*

```
p=10^11+3
k b=((p-2)?b)b 1
r x=x-div x p*p
(e?b)s a|e==0=a|1<2=(div e 2?b$r$s*s)$last$a:[r$a*s|odd e]

```

Try it online!

# Haskell, 48 bytes

A rewrite of this solution. While fast enough for the test vector, this solution is too slow for other inputs.

```
s x=until(\t->t-t`div`x*x==0)(+(10^11+3))1`div`x

```

Try it online!
> 9 votes

# Answer
# Brachylog, 22 bytes

```
∧10^₁₁+₃;İ≜N&;.×-₁~×N∧

```

Try it online!

This took about 10 minutes for `1000000` with a slightly different (and longer) version of the code which was exactly two times faster (checked only positive values of `İ` instead of both positive and negatives). Therefore this should take about 20 minutes to complete for that input.

### Explanation

We simply describe that `Input × Output - 1 = 100000000003 × an integer`, and let constraint arithmetic find `Output` for us.

```
∧10^₁₁+₃                   100000000003
        ;İ≜N               N = [100000000003, an integer (0, then 1, then -1, then 2, etc.)]
            &;.×           Input × Output…
                -₁         … - 1…
                  ~×N∧     … = the product of the elements of N

```

We technically do not need the explicit labeling , however if we do not use it,  will not check the case `N = [100000000003,1]` (because it's often useless), meaning that this will be very slow for input `2` for example because it will need to find the second smallest integer instead of the first.
> 6 votes

# Answer
# Python, ~~53~~ ~~51~~ ~~49~~ ~~58~~ ~~53~~ 49 bytes

-2 bytes thanks to orlp
-2 bytes thanks to officialaimm
-4 bytes thanks to Felipe Nardi Batist
-3 bytes thanks to isaacg
-1 byte thanks to Ørjan Johansen
-2 bytes thanks to Federico Poloni

```
x=input()
t=1
while t-t/x*x:t+=3+10**11
print t/x

```

Try it Online!

It took me ~30 minutes to figure this one out. My solution is to start with the first number that will mod to 1. This number is 1. If its divisible by x, then y is that number divided by x. If not, add 10000000003 to this number to find the second number which mod 1000000003 will equal 1 and repeat.
> 6 votes

# Answer
## JavaScript (ES6), ~~153~~ ~~143~~ 141 bytes

Inspired by this answer from math.stackexchange.com.

A recursive function based on the Euclidean algorithm.

```
f=(n,d=(F=Math.floor,m=1e11+3,a=1,c=n,b=F(m/n),k=m-b*n,n>1))=>k>1&d?(e=F(c/k),a+=e*b,c-=e*k,f(n,c>1&&(e=F(k/c),k-=e*c,b+=e*a,1))):a+d*(m-a-b)

```

Modulo is implemented by computing:

```
quotient = Math.floor(a / b);
remainder = a - b * quotient;

```

Because the quotient is also needed, doing it that way does actually make some sense.

### Test cases

```
let f =

f=(n,d=(F=Math.floor,m=1e11+3,a=1,c=n,b=F(m/n),k=m-b*n,n>1))=>k>1&d?(e=F(c/k),a+=e*b,c-=e*k,f(n,c>1&&(e=F(k/c),k-=e*c,b+=e*a,1))):a+d*(m-a-b)

console.log(f(2))
console.log(f(50000000002))
console.log(f(1000000))
```
> 5 votes

# Answer
# C++11 (GCC/Clang, Linux), ~~104~~ 102 bytes

```
using T=__int128_t;T m=1e11+3;T f(T a,T r=1,T n=m-2){return n?f(a*a-a*a/m*m,n&1?r*a-r*a/m*m:r,n/2):r;}

```

https://ideone.com/gp41rW

Ungolfed, based on Euler's theorem and binary exponentation.

```
using T=__int128_t;
T m=1e11+3;
T f(T a,T r=1,T n=m-2){
    if(n){
        if(n & 1){
            return f(a * a - a * a / m * m, r * a - r * a / m * m, n / 2);
        }
        return f(a * a - a * a / m * m, r, n / 2);
    }
    return r;
}

```
> 5 votes

# Answer
# Mathematica, 49 bytes

```
x/.FindInstance[x#==k(10^11+3)+1,{x,k},Integers]&

```
> 4 votes

# Answer
# PHP, 71 bytes

```
for(;($r=bcdiv(bcadd(bcmul(++$i,1e11+3),1),$argn,9))!=$o=$r^0;);echo$o;

```

Testcases
> 2 votes

# Answer
# Ruby, 58 bytes

Uses isaacg's application of Fermat's little theorem for now while I finish timing the brute-force solution.

```
->n,x=10**11+3{i=n;11.times{i**=10;i-=i/x*x};i*=n;i-i/x*x}

```

Current brute force version, which is 47 bytes but ~~might be~~ *is* too slow:

```
->n,x=10**11+3{(1..x).find{|i|i*=n;i-i/x*x==1}}

```

Try it online!
> 1 votes

---
Tags: code-golf, math, abstract-algebra, restricted-time
---


title: Carrots. So. Many. Carrots

text:
# Question
Title: Carrots. So. Many. Carrots
> Damn, that's a lot of carrots.

## The Inspiration

## The Task

You must create a program, that, in as many languages as possible, replaces every instance of `^` with a *markdown formatted link* (meaning that if I was to post it in an answer, it would automatically read it as an image and place the image instead of the words) of *this* upward facing carrot.

### How to Use Said Formatting:

First, anywhere in the file, put in the link like so (this is what I did for this question):

```
[1]: https://i.stack.imgur.com/mecHl.png
```

And then, wherever you want it:

```
[![][1]][1]
```

## Rules

* Standard Loopholes apply.
* Input will be through STDIN or equivalent.
* Output will be through STDOUT or equivalent.
* Your code must be a fully operating program in all languages that you use.
* The URL that you use for your carrot does *not* have to be the one in this answer. This was just an example. You may use *any* URL, provided that SE's Markdown shows this specific carrot with it.
* This is a challenge, so the answer with the greatest amount of ~~carrots~~ languages wins!
    + In the case of a tie, the shortest code size of the entries with the largest number of languages wins.

**EDIT:**

* Also, do NOT use trivial derivatives of languages! This means using a substitution language (Brainfuck vs. ShadyAsFuck) and different language versions (Python 2 vs. Python 3).

> There's a lot trivial esolangs to fit... (including 9001 BF variants)

Don't be that guy.

Note: Yes, this program will be slightly trivial in languages with regex support. However, the competition is to see how many languages the competitors can use.

# Answer
# Python, Befunge 98, Lisp, and Javascript - ~~829~~ 827 +2 (-x flag in python) =  ~~831~~  829 bytes

```
"^\
";/*";
""""(defun q (string part replacement &key (test #'char=))(with-output-to-string (out) (loop with part-length = (length part) for old-pos = 0 then (+ pos part-length) for pos = (search part string :start2 old-pos :test test) do (write-string string out :start old-pos :end (or pos (length string))) when pos do (write-string replacement out) while pos)))(princ "[1]:http://tinyurl.com/qczsjtl
")(ignore-errors (loop (princ (q (read-line) "^" "[![][1]][1]"))))""";import sys;i=sys.stdin.read();print '[1]:http://tinyurl.com/qczsjtl\n'+i.replace('^','[![][1]][1]');"""" """
1;'''
;#<v"[1]:http://tinyurl.com/qczsjtl"$$$
;X v,<
;X >:|XXXXX>v
;vXXX>a,#
;>#@~>:10g-|>,#
;^ XXXXXXXX>$"]1[]]1[][![">:# ,# _#
;X */alert("[1]:http://tinyurl.com/qczsjtl\n"+prompt().split("^").join("[![][1]][1]"));/*
;>^"'''#*/

```

Requires the `-x` command line flag when run with python. the `X`s can be replaced with any character. The end-of-line number signs (and the number sign at the beginning of the first line that starts with a semicolon) are present to avoid befunge trying to execute the invalid instruction `;` (which starts a comment in lisp). There is no trailing space on any of the lines.

Saved two bytes by replacing `55+` with `a` to print a newline.
> 5 votes

# Answer
## Minkolang 0.10, Befunge-93, \>\<\>; 3 2D languages, 321 bytes

```
v[1]: https://i.stack.imgur.com/mecHl.png
v[![][1]][1]
>\$$>~:1+!#v_:"^"-#v_1>:34*`#v_v
//  ^             ,<0        <    >:0g,1+v
v#   ,,:*52<          ^+1  ,g1:<@_^#`*85:<1
>!v#(od"^"=,34*&34*[i1+1qO]!O$I)lO58*[i1+0qO].
  >i:0(?v:"^"-?v1>:34*)?vv
  ^           o<0       < > :0go1+v
  oo:*52<        ^+1og1: <^;?)*85:<1

```

Interpreters: Minkolang, Befunge-93, \>\<\>.

I'll go into detail on each component if anyone wants, but what's important is that all of them read the first and second lines of the codebox and output the characters at the appropriate times. Also, I decide between Befunge and Minkolang/\>\<\> by the use of `\`, which swaps the top two values of the stack in the first and is a mirror in the other two. To separate Minkolang and \>\<\>, I use `!v#`. `!` is an unconditional trampoline in both languages, but `#` is an omni-directional mirror in \>\<\> and a no-op in Minkolang. From then on, each language executes code in its own component.
> 18 votes

# Answer
# Carrot, ~~60~~ 58 bytes

```
#^A^S"[![][1]][1]"^[1]: https://i.stack.imgur.com/mecHl.png

```

I know it is only one language at the moment but I thought we can't really have a challenge about carrots that isn't answered in Carrot.

*Saved 2 bytes thanks to @KritixiLithos.*

Explanation:

```
#                                          // Set the stack to the input
^                                          // Change to operations mode
A^                                         // Convert to array mode by splitting on ^
S"[![][1]][1]"                             // Convert to string mode by joining on
                                           // the literal string supplied
^[1]: https://i.stack.imgur.com/mecHl.png   // Switch back to stack mode and
                                           // append the string literal

```
> 5 votes

---
Tags: code-challenge, string, polyglot
---


title: Cyclic Polyglot Challenge (Cops)

text:
# Question
Title: Cyclic Polyglot Challenge (Cops)
# Cyclic Polyglot Challenge

*This is the cops thread. You can find the robbers thread here.*

## Cyclic Polyglot

A N-element cyclic polyglot is a complete program that can be run in N different languages. In each language, when the program is run with no input (possibly subject to this exception), it should print the name of a language to STDOUT. Specifically, if the program is run in the Kth language, it should print the name of the (K+1)th language. If the program is run in the Nth language (that is, the final language in an N-element cycle), it should print the name of the first language.

An example might be useful.

```
a = [[ v = 7, puts('Befunge') ]]
__END__
= print("Ruby")
-->*+:292*++,,@
--3    9
--7    *
--^,:-5<

```

Running this program with Lua prints the string "Ruby". Running this program in Ruby prints the string "Befunge". Running this program in Befunge prints the string "Lua", completing the cycle. This program constitutes a 3-cycle consisting of Lua, Ruby, and Befunge.

The same language cannot appear twice in a cycle, and different versions of the same language (such as Python 2 and Python 3) cannot appear in the same cycle as one another.

## Cops

Your challenge is to write an N-cyclic polyglot, where N is at least 2. Then, you must add, replace, and delete some number of characters to the program to produce an M-cyclic polyglot, where M is strictly greater than N. You should then post the shorter, N-cyclic polyglot (and the languages it runs in), as well as the number of characters you changed to produce the longer polyglot. Your score is N, the number of languages in your shorter cycle.

The robbers will try to identify your longer cycle. If, after seven days, no one has successfully cracked your solution, you should edit your answer declaring that it is safe. You should also post your longer M-cyclic polyglot at this time.

## Robbers

Given a cop's N-cyclic polyglot and the number of characters they added to produce a larger polyglot cycle, your goal is to produce that larger cycle. If you can produce a longer cycle by adding, deleting, or replacing as many characters as the cop did *or fewer characters*, you have cracked the cop's polyglot. Your score is the length of the new cycle you've created. Your new polyglot need not be the same as or even similar to the cop's secret polyglot; it only needs to be larger than their existing one.

Your solution may also be cracked. If another robber comes along and produces a cycle strictly longer than yours, starting from the same cop's polyglot, they have stolen your points.

## Valid Programming Languages

Since this challenge indirectly involves guessing programming languages used by other participant's, the definition of a programming language for the purposes of this challenge will be a little more strict than the usual definition. A programming language used in this challenge must satisfy all of the following conditions.

## Final Notes

* The code you write should be a standalone program in every language that it is intended to run in. Functions or code snippets are not allowed.
* Your program will be given no input through STDIN. Likewise, your program should print nothing to STDERR.
* A cop's score is the number of languages in the cycle of the polyglot they posted. The cop should post the languages that the posted polyglot runs correctly in, as well as the number of characters they added to produce a longer polyglot. They are *not* responsible for posting the languages the longer, hidden polyglot runs in until their answer is safe.
* A robber's score is the number of languages the modified polyglot runs in. As with the cop, the robber should post the list of languages the polyglot runs correctly in.
* The number of characters changed should be computed in Levenshtein distance.

# Answer
# C (gcc), 126 bytes

`M=N+1`

`Levenshtein(polyglot(M),polyglot(N))` is **36** bytes

```
#include<stdio.h>
#define print(a) main(){int z[1];if(sizeof(0,z)==4)printf("C(gcc)");else printf("Perl5");}
print("C++(gcc)")

```

Try it online!
> 1 votes

---
Tags: cops-and-robbers, polyglot
---


title: Cyclic Polyglot Challenge (Robbers)

text:
# Question
Title: Cyclic Polyglot Challenge (Robbers)
# Cyclic Polyglot Challenge

*This is the robbers thread. You can find the cops thread here.*

## Cyclic Polyglot

A N-element cyclic polyglot is a complete program that can be run in N different languages. In each language, when the program is run with no input (possibly subject to this exception), it should print the name of a language to STDOUT. Specifically, if the program is run in the Kth language, it should print the name of the (K+1)th language. If the program is run in the Nth language (that is, the final language in an N-element cycle), it should print the name of the first language.

An example might be useful.

```
a = [[ v = 7, puts('Befunge') ]]
__END__
= print("Ruby")
-->*+:292*++,,@
--3    9
--7    *
--^,:-5<

```

Running this program with Lua prints the string "Ruby". Running this program in Ruby prints the string "Befunge". Running this program in Befunge prints the string "Lua", completing the cycle. This program constitutes a 3-cycle consisting of Lua, Ruby, and Befunge.

The same language cannot appear twice in a cycle, and different versions of the same language (such as Python 2 and Python 3) cannot appear in the same cycle as one another.

## Cops

Your challenge is to write an N-cyclic polyglot, where N is at least 2. Then, you must add, replace, and delete some number of characters to the program to produce an M-cyclic polyglot, where M is strictly greater than N. You should then post the shorter, N-cyclic polyglot (and the languages it runs in), as well as the number of characters you changed to produce the longer polyglot. Your score is N, the number of languages in your shorter cycle.

The robbers will try to identify your longer cycle. If, after seven days, no one has successfully cracked your solution, you should edit your answer declaring that it is safe. You should also post your longer M-cyclic polyglot at this time.

## Robbers

Given a cop's N-cyclic polyglot and the number of characters they added to produce a larger polyglot cycle, your goal is to produce that larger cycle. If you can produce a longer cycle by adding, deleting, or replacing as many characters as the cop did *or fewer characters*, you have cracked the cop's polyglot. Your score is the length of the new cycle you've created. Your new polyglot need not be the same as or even similar to the cop's secret polyglot; it only needs to be larger than their existing one.

Your solution may also be cracked. If another robber comes along and produces a cycle strictly longer than yours, starting from the same cop's polyglot, they have stolen your points.

## Valid Programming Languages

Since this challenge indirectly involves guessing programming languages used by other participant's, the definition of a programming language for the purposes of this challenge will be a little more strict than the usual definition. A programming language used in this challenge must satisfy all of the following conditions.

## Final Notes

* The code you write should be a standalone program in every language that it is intended to run in. Functions or code snippets are not allowed.
* Your program will be given no input through STDIN. Likewise, your program should print nothing to STDERR.
* A cop's score is the number of languages in the cycle of the polyglot they posted. The cop should post the languages that the posted polyglot runs correctly in, as well as the number of characters they added to produce a longer polyglot. They are *not* responsible for posting the languages the longer, hidden polyglot runs in until their answer is safe.
* A robber's score is the number of languages the modified polyglot runs in. As with the cop, the robber should post the list of languages the polyglot runs correctly in.
* The number of characters changed should be computed in Levenshtein distance.

# Answer
# mdahmoune, added Ruby, Levenshtein = 10

```
#include<stdio.h>
#define print(a) main(){int z[1];if(sizeof(0,z)==4)printf("C(gcc)");else printf("Perl5");}
print($=?"Ruby":"C++(gcc)")

```

Cycle is `C -> Perl5 -> Ruby -> C++ -> C`

I don't really know what I did (and I really don't know why it's valid in C and C++), I just ripped it off this answer.

C (gcc): Try it online!

Perl5: Try it online!

Ruby: Try it online!

C++ (gcc): Try it online!
> 2 votes

---
Tags: cops-and-robbers, polyglot
---