title: Church Subtraction

text:
# Question
Title: Church Subtraction
# Church Subtraction

Lambda calculus has always been a fascination of mine and the emergent behaviors of passing functions into each other is delightfully complex. Church numerals are representations of natural numbers contructed from the repeated application of a function (normally the unary addition of a constant). For example, the number zero returns x and "ignores" the input function, one is `f(x)`, two is `f(f(x))` and so on:

```
ident = lambda x: x
zero = lambda f: ident
succ = lambda n: lambda f: lambda x: f(n(f)(x))
one = succ(zero)
add1 = lambda x: x + 1
to_int = lambda f: f(add1)(0)
print(to_int(one))
>>> 1

```

From this we can easily see that addition is accomplished by applying the first function to x then applying the second function to x:

```
add = lambda m: lambda n: lambda f: lambda x: n(f)(m(f)(x))
print(to_int(add(one)(two)))
>>> 3

```

Addition is relatively easy to understand. However, to a newcomer it might be inconceivable to think of what subtraction looks like in a Church encoded number system. What could it possibly mean to un-apply a function?

# Challenge

Implement the subtraction function in a Church encoded numeral system. Where subtraction performs the monus operation and unapplies a function `n` times if the result will be greater than zero or zero otherwise. This is code-golf so shortest code wins.

# Input

Two Church numerals that have been encoded in your choice of language. The input can be positional or curried. To prove these are true Church numerals they will have to take in any function and apply them repeatedly (`add1` is given in the examples but it could be `add25`, `mult7`, or any other unary function.)

# Output

A Church numeral. It should be noted that if `m < n` then `m - n` is always the same as the identity function.

Examples:

```
minus(two)(one) = one
minus(one)(two) = zero
...

```

also acceptable:

```
minus(two, one) = one
minus(one, two) = zero

```

Credit:

This github gist for giving me a python implementation of Church Numerals.

# Answer
> 9 votes
# Haskell, 35 bytes

```
(r%s)f x=s(x:)(iterate f x)!!r(+1)0

```

Try it online!

Say that `r` and `s` are the church encodings of `m` and `n`. We want `r%s` to apply `f` `m-n` times to some initial value `x`. We first generate the infinite list

```
iterate f x = [x, f x, f (f x), f (f (f x)), ...]

```

then use `s(x:)` to prepend `n` copies of `x`, that is, shift each value `n` indices right:

```
s(x:)(iterate f x) = [x, x, x, ...,  x, f x, f (f x), f (f (f x)), ...]

```

We then compute `m` directly as `r(+1)0`, and take the `m`'th element of that list as `!!r(+1)0`. An indexing-free solution could instead do `head$r tail$...`, that is drop the first element `m` times and then take the first element, but the indexing syntax is much shorter.

Note that the classic solution doesn't work in Haskell without extensions because its strong typing can't represent the predecessor operation.

# Answer
> 3 votes
# Python 2, ~~82~~ 80 bytes

```
eval('!u:!v:v(!n:!f:!x:n(!g:!h:h(g(f)))(!u:x)(!u:u))(u)'.replace('!','lambda '))

```

Try it online!

2 bytes thx to Nick Kennedy noting an un-needed pair of parens.

Anonymous function that implements minus.

Mostly this is just compressing the definition found at the Wikipedia page; not like I truly understand the code yet. But interesting!

# Answer
> 3 votes
# Python 2, 77 bytes

```
lambda r,s:s(lambda r:lambda f:lambda x:r(lambda(_,x):(x,f(x)))((x,x))[0])(r)

```

Try it online!

We do Church decrement by tracking the previous value for each iteration and outputting that at the end. 39% of the code length is `"lambda"`'s...

# Answer
> 2 votes
# C++ (clang), 112 bytes

```
#define L(x,y)[&](auto x){return y;}
auto m=L(u,L(v,v(L(n,L(f,L(x,n(L(g,L(h,h(g(f)))))(L(u,x))(L(u,u))))))(u)));

```

Try it online!

This is by far the most incomprehensible C++ code I've ever written. That said, I think that ungolfing this code will only make it worse.

# Answer
> 2 votes
# JavaScript (Node.js), ~~87~~ ~~85~~ ~~81~~ ~~76~~ 74 bytes

```
f=>g=>h=>x=>f(([x,[g,a]])=>[g(x),a])([x,g(a=>[x=>x,a])(f(a=>[h,a])())])[0]

```

Try it online! Not going to win any awards, but I thought I'd try a different approach.

`a=>[h,a]` is a stage that applies `h`, while `a=>[x=>x,a]` is a stage that doesn't apply `h`. We apply the first function `f` times and the second function `g` times. We then apply the inverse function `([f,[g,a]])=>[g(x),a]` `f` times. This skips over the `g` second stages and performs `f-g` first stages as desired. It then remains to extract the final value.

The tuples can of course be converted to lambda functions which results in the following expression:

```
f=>g=>h=>x=>f(e=>e(x=>d=>d(g=>a=>e=>e(g(x))(a))))(e=>e(x)(g(a=>e=>e(x=>x)(a))(f(a=>e=>e(h)(a))())))(x=>a=>x)

```

# Answer
> 2 votes
# Underload, 37 bytes

```
(~(((!())~):*^(~!:(:)~*(*)*)~^^!)~^^)

```

Try it online!

The inner `(((!())~):*^(~!:(:)~*(*)*)~^^!)` is the `pred` function, implemented via pairs:

```
(               ( start pred function )!
  (
    (!())~      ( push zero below argument )!
  ):*^          ( do that twice )!

  (             ( start pair-increasing function )!
    ~!          ( remove second argument)!
    :           ( duplicate first argument )!
    (:)~*(*)*   ( increment first return value )!
  )
  ~^^           ( run pair-increasing function n times )
  !             ( remove first in returned pair )!
)

```

# Answer
> 1 votes
# , 86 bytes

```
eval(parse(t=gsub("!(.)","function(\\1)","!u!vv(!n!f!xn(!g!hh(g(f)))(!ux)(!uu))(u)")))

```

Try it online!

R port of @ChasBrown’s Python answer so be sure to upvote that one too.

# Answer
> 1 votes
# , 56 bytes

```
c=:3 :0
t=.^:y
5!:1<'t'
)
m=.2 :'c 0>.(>:u 5!:0->:v 5!:0)0'

```

Try it online!

Note: *-3 bytes off TIO count for `m=.`*

Higher order functions in J are achieved using adverbs and conjunctions. Here a church numeral is the gerund form of the adverb formed by combining the "power of" conjunction (which repeatedly applies a verb) and an integer. The following verb `c` (for "create") uses J's Atomic Representation to transform an integer into such a gerund:

```
c=:3 :0
t=.^:y
5!:1<'t'
)

```

Our "minus" operator (which is a conjunction) subtracts the right gerund church numeral from the left. It does not, however, assume any particular implementation of church numerals, including the one from our `c` verb. Instead, it relies on the general definition and turns each gerund church numeral back into an adverb by inverting it with `5!:0`, and then applying that adverb to the increment verb `>:`, and then applying *that* to 0.

It then subtracts and takes the maximum with 0, and applies `c` to get the final result: a new gerund church numeral.

# Answer
> 1 votes
# Wolfram Language (Mathematica), ~~55~~ ~~48~~ ~~47~~ 39 bytes (33 characters)

```
#2[(fx#[g#@g@f&][x&][#&])&]@#&

```

Try it online!

The  symbol is 0xF4A1, a special Mathematica code point that denotes a rightward arrow for `\[Function]`. See here for more explanations. This is what the code looks like in the Mathematica front end:

We can do it in 40 bytes / 32 characters, which may be shorter depending on the measurement scheme: `#2[n⟼f⟼x⟼n[g⟼#@g@f&][x&][#&]]@#&`

The un-golfed version is a literal translation of the classical definition of pred:

```
pred = n \[Function] f \[Function] x \[Function] n[g \[Function] h \[Function] h[g[f]]][u \[Function] x][u \[Function] u];
subtract[m_, n_] := n[pred][m]

```

which looks like this in the Mathematica front end:

This subtraction function works with the Church numerals defined with

```
c@0=#& &;c@n_=#@*c[n-1][#]&

```

(un-golfed: `c[0] = Identity &; c[n_] = Function[a, a@*c[n-1][a]]`)

so that we have

```
Table[c[n][f][x], {n, 0, 6}]
(*    {x, f[x], f[f[x]], f[f[f[x]]], f[f[f[f[x]]]], f[f[f[f[f[x]]]]], f[f[f[f[f[f[x]]]]]]}    *)

```

and

```
subtract[c[7],c[5]][f][x]
(*    f[f[x]]    *)

```

---
Tags: code-golf, functional-programming
---


# Question
Title: Print the first 128 prime numbers without using any reserved words
The obvious solution would be to just print them as a string, but is it possible to write a shorter code?

Requirements:

1. No input should be processed, and the output should be in the form of `2 3 5 7 11 13 ...` etc.
2. No reserved words in the language are used at all
3. The language should at least allow structured programming, and have reserved words (otherwise point 2 would be moot).

first I had exclusively C/C++ in mind, but extended the question while still trying to prevent cheating

# Answer
## C, 60 chars

The "no keywords" limitation doesn't matter here. I'm pretty sure that improving it, if possible, won't be done by adding keywords.

```
n=2;main(m){n<720&&main(m<2?printf("%d ",n),n:n%m?m-1:n++);}

```

Alternate version:
The output isn't as nice, but I like the `printf` abuse.

```
n=2;main(m){n<720&&main(m<2?printf("%*d",n,n):n%m?m-1:n++);}

```

The trick in both solutions is to merge two loops (implemented by recursion) into one.
`n` is the next potential prime, `m` the next potential divisor.
In each recursive call, we either increment `n` (while setting `m` to its previous value) or decrement `m`.
> 15 votes

# Answer
## Python, 108 chars

Python was not made for this challenge. Wanna `print`? That's reserved. Well, how about we use `stdout`? Well, that's gonna cost an `import`... you guessed it, reserved. Well... I'm on unix, so I can open up the file descriptor 1, which happens to be stdout. Hack!

Man, and iteration? Nothing but `eval`. No loops, of course, but we can't even define a function with `def` or `lambda`. And to add insult to injury, we can't even use list comprehension! I always look for an excuse to use things like `map(p.__mod__,...)` in code golf... comprehension is always better. Until now, that is.

```
p=1
eval(compile("p+=1;open('/dev/fd/1','w').write('%s '%p*all(map(p.__mod__,range(2,p))));"*720,'','exec'))

```

Now, you might complain that `exec` is a keyword, even though I didn't use the keyword (I didn't even `eval` an `exec`). Well, here's a 117-character solution which doesn't use `'exec'`.

```
p=2
s="eval('('+s*(p<720)+')',open('/dev/fd/1','w').write('%s '%p*all(map(p.__mod__,range(2,p)))),{'p':p+1})";eval(s)

```
> 8 votes

# Answer
# JavaScript (80 chars)

```
eval((s=Array(719)).join("s[j=++n]?j:"+s.join("s[j+=n]=")+"r+=n+' ';"),r="",n=1)

```

Run in console of your webbrowser.

Used a prime sieve, which turned out to be very condensed.
> 7 votes

# Answer
## C, 87 chars

```
d;p(n){--d<2||n%d&&p(n);}r(n){p(d=n);d<2&&printf("%d\n",n);++n<720&&r(n);}main(){r(2);}

```

(I tried to write it in a more functional style, but my inability to use `return` kind of killed that plan.)
> 5 votes

# Answer
## C, 183 chars

```
#define q j*j<k?i%p[j++]||(i++,j=0):printf("%d\n",p[j=0,k++]=i++)
#define A q;q;q;q;q;q;q;q
#define B A;A;A;A;A;A;A;A
#define C B;B;B;B;B;B;B
main(){int i=2,j=0,k=0,p[999];C;C;C;C;C;}

```

Well, here's a quick first attempt. I believe this should satisfy the requirements. I'm using simple trial division to find the primes and an unrolled loop constructed using the preprocessor to iterate it until I've found enough of them. The number of repetitions has been tweaked so that exactly 128 primes are printed.
> 4 votes

# Answer
## C, 134 chars

Here's an alternate solution that tries to avoid using words as much as possible, reserved or otherwise:

```
main(i){i<9?main(2953216):i>4097?--i&4094?i/4096%(i%4096)?main(i):
main((i/4096-1)*4097):printf("%d\n",i>>12,main((i/4096-1)*4097)):0;}

```

All it uses is `printf` and `main` with a single argument.
> 4 votes

# Answer
### *Mathematica* 50 characters

I'm not sure how to interpret "reserved words" for *Mathematica* but I want to play so I'll take it to mean doing without built-in functions to generate primes or test for primality.

```
Fold[#2Cases[#/#2,1|_Rational]&,#,#]&@Range[2,719]

```
> 4 votes

# Answer
## Haskell, 72 characters

```
main=putStrLn.unwords$take 128[show p|p<-[2..],all((>0).mod p)[2..p-1]]

```

Admittedly, avoiding keywords isn't too difficult in Haskell.
> 3 votes

# Answer
# K (ngn/k), 31 bytes

```
x,1_&&/720#'!'x:24\234925135391

```

Try it online!
> 2 votes

---
Tags: code-golf
---


# Question
Title: Bot Problem.How to solve this problem in c?
Programming problem: In BotLand, Robots can understand all words of any combination of letters and letters with leading or trailing (not both) numeric value. Given a word W (string of alphanumeric). Write a function to check if W is Bot word. Don't use library functions/ regex.

Example:

Input: BotLand
Output: Bot word

Input: BotLand77
Output: Bot word

Input: 1Bot2Land3
Output: Non Bot word

# Answer
# Python 3, 33 bytes

```
lambda s:1-(s[0]+s[-1]).isdigit()

```

Try it online!

-8 bytes thanks to Grimy and A _
> 3 votes

---
Tags: code-golf, code-challenge, decision-problem
---


title: Undress a string

text:
# Question
Title: Undress a string
We already now how to strip a string from its spaces.

However, as proper gentlemen/ladies, we should rather *undress* it.

---

Undressing a string is the same as stripping it, only more delicate. Instead of removing all leading and trailing spaces at once, we remove them *one by one*. We also *alternate* between leading and trailing, so as not to burn steps.

Example, starting with `" codegolf "` (five leading and trailing spaces):

```
     codegolf
    codegolf
    codegolf
   codegolf
   codegolf
  codegolf
  codegolf
 codegolf
 codegolf
codegolf
codegolf

```

---

1. First output the string unchanged. Then, output every step. Begin by removing a *leading* space (if applicable - see rule #2).
2. The input may have a different number of leading and trailing spaces. If you run out of spaces on one side, keep undressing the other until the string is bare.
3. The input may have no leading nor trailing spaces. If that's the case, output it as-is.
4. Use PPCG's default I/O methods. PPCG Default loopholes are forbidden.
5. Undefined behaviour on empty input, or input that only contains spaces, is OK.
6. You can assume that the string will only contain characters from the ASCII printable space (`0x20` to `0x7E`).

---

Examples - spaces are replaced by dots `.` for better readability:

```
4 leading spaces, 5 trailing: "....Yes, Sir!....."
....Yes, Sir!.....
...Yes, Sir!.....
...Yes, Sir!....
..Yes, Sir!....
..Yes, Sir!...
.Yes, Sir!...
.Yes, Sir!..
Yes, Sir!..
Yes, Sir!.
Yes, Sir!

6 leading, 3 trailing: "......Let's go golfing..."
......Let's go golfing...
.....Let's go golfing...
.....Let's go golfing..
....Let's go golfing..
....Let's go golfing.
...Let's go golfing.
...Let's go golfing
..Let's go golfing
.Let's go golfing
Let's go golfing

0 leading, 2 trailing: "Hello.."
Hello..
Hello.
Hello

0 leading, 0 trailing: "World"
World

21 leading, 5 trailing: ".....................a....."
.....................a.....
....................a.....
....................a....
...................a....
...................a...
..................a...
..................a..
.................a..
.................a.
................a.
................a
...............a
..............a
.............a
............a
...........a
..........a
.........a
........a
.......a
......a
.....a
....a
...a
..a
.a
a

```

A gentleman/lady is concise, so *the shortest answer in bytes wins*.

# Answer
## Retina, 26 bytes

```
{m`^ (.+)\z
$&¶$1
 $
 ¶$%`

```

Try it online! (Test suite uses periods for clarity. The footer and header convert them to and from spaces for the main code.)

### Explanation

It would be nice if we could just alternate between dropping a leading and a trailing space and printing the intermediate result each time. The problem is that currently Retina can't print conditionally, so it would even print this intermediate result if there are no leading or no trailing spaces left, generating duplicates. (Retina 1.0 will get an option that only prints the result if the string was changed by the operation, but we're not there yet...)

So instead, we're building up a single string containing all intermediate results and printing that at the end.

```
{m`^ (.+)\z
$&¶$1

```

The `{` wraps both stages of the program in a loop which repeats until the string stops changing (which means there are no leading/trailing spaces left). The stage itself matches a leading space on the final line of the string, and that final line, and then writes back the match, as well as the stuff after the space on a new line (thereby dropping the leading space in the copy).

```
 $
 ¶$%`

```

Removing the trailing space is a bit easier. If we just match the final space, we can access the stuff in front of it (on the same line) with `$%`` which is a line-aware variant of the prefix substitution `$``.
> 11 votes

# Answer
# Python 2, ~~122~~ ~~107~~ ~~103~~ ~~102~~ ~~98~~ ~~95~~ ~~93~~ ~~91~~ ~~90~~ ~~88~~ 87 bytes

```
s=input()+' '
a=0
while-a*s!=id:
 if a:id=s
 a=~a
 if'!'>s[a]:s=s[1+a:len(s)+a];print s

```

Try it online!

---

# Python 3, ~~97~~ ~~95~~ ~~93~~ 90 bytes

```
s=input()
a=p=print
p(s)
while s!=a:
 a=s
 if'!'>s:s=s[1:];p(s)
 if'!'>s[-1]:s=s[:-1];p(s)

```

Try it online!
> 11 votes

# Answer
# 05AB1E, ~~21~~ 15 bytes

```
=v¬ðQi¦=}¤ðQi¨=

```

Try it online!

**Explanation**^

```
=                 # print input
 v                # for each character in input
  ¬ðQi  }         # if the first char in the current string is a space
      ¦=          # remove it and print without popping
         ¤ðQi     # if the last char in the current string is a space
             ¨=   # remove it and print without popping

```
> 7 votes

# Answer
# Perl 6, 55 bytes

*Saved 3 bytes thanks to @nwellnhof.*

```
{($_,{$++%2??S/" "$//!!S/^" "//}...*)[^.comb*2].unique}

```

Try it online!

**Explanation**: `($_,{$++%2??S/" "$//!!S/^" "//}...*)` is a recursive infinite sequence that starts with the original string (`$_`) and the next element is given by the block called on the previous element.

The block itself gets the string in the `$_` variable. The operator `S/(regex)/(string)/` will search for the first occurence of `(regex)` in `$_`, replaces it with `(string)`, and returns the result. If there is no match, it returns the content of `$_` unchanged. We use the ternary operator `?? !!` with the condition `$++%2`, which alternates between `False` and `True` (`$` is a free variable that conserves its contents across calls to the block.)

In the worst case (all spaces on one side and 1 other character), we remove 1 space every 2 steps. So we can be sure that in 2\*(length of the string) steps, all spaces will have been removed. We take that many elements from the recursive sequence with `[^.comb*2]` and finally discard duplicates (which occur whenever a space should have been removed but it isn't there) with `.unique`. This returns the list of strings, progressively stripped of spaces.
> 7 votes

# Answer
# C (gcc), ~~89~~ 84 bytes

Recursive version is shorter ;-)

```
j;f(char*s){puts(s);*s^32||puts(++s);s[j=strlen(s)-1]<33?s[j]=0,f(s):*s^32||f(s+1);}

```

Try it online!

# C (gcc), ~~107~~ ~~102~~ ~~101~~ ~~100~~ 99 bytes

Saved 2 bytes thanks to @Jonathan Frech using spaces and ~

```
i,j,k;f(char*s){for(i=~++k,puts(s);i^k;k=s[j=strlen(s)-1]<33?s[j]=0,puts(s):0)*s^32?i=0:puts(++s);}

```

Try it online!
> 7 votes

# Answer
# JavaScript (ES6) 92

@Upvoters: have a look at the other JS answer down below that is **76** bytes long

```
(s,q,l=2,p=0)=>{for(alert(s);l--;p=!p)s[+p&&s.length-p]<'!'&&alert(s=s.slice(!p,-p||q,l=2))}

```

A loop looking for a space at front or at end. If found, remove space and output string. If no space found 2 times, stop.

```
F=
(s,q,l=2,p=0)=>{for(alert(s);l--;p=!p)s[+p&&s.length-p]<'!'&&alert(s=s.slice(!p,-p||q,l=2))}

// some trick to show dots instead of spaces, for test
alert=x=>console.log(x
  .replace(/^ +/g,z=>'.'.repeat(z.length))
  .replace(/ +$/g,z=>'.'.repeat(z.length))
)

function go() {F(I.value.replace(/\./g,' '))}

go()
```

```
<input ID=I value='....yes Sir!....'> (use dot instead of space)
<button onclick='go()'>Go</button>
```
> 6 votes

# Answer
# Perl 5, 32 bytes

*Saved 4 bytes due to @Abigail.*

```
1while s/^ /!say/e+s/ $/!say/e

```

Requires `-pl` counted as 2, invoked with `-E`.

**Sample Usage**

```
$ echo '   test   ' | perl -plE'1while s/^ /!say/e+s/ $/!say/e'
   test
  test
  test
 test
 test
test
test

```

Try it online!
> 6 votes

# Answer
# C# (.NET Core), ~~192~~ ~~183~~ ~~182~~ ~~181~~ ~~179~~ 178 bytes

<sup>-3 bytes thanks to Kevin Cruijssen</sup>

```
n=>{var o=n+"\n";for(var e=1;n.Trim()!=n;){if(1>(e^=1))if(n[0]<33)n=n.Remove(0,1);else continue;else if(n.TrimEnd()!=n)n=n.Remove(n.Length-1);else continue;o+=n+"\n";};return o;}

```

Try it online!
> 5 votes

# Answer
# Java 8, ~~150~~ ~~146~~ ~~145~~ 137 bytes

```
s->{String r=s;for(int f=0;s!=s.trim();f^=1)r+="\n"+(s=f+s.charAt(0)<33|!s.endsWith(" ")?s.substring(1):s.replaceAll(" $",""));return r;}

```

-4 bytes thanks to *@Nevay* changing `(f<1&s.charAt(0)<33)` to `f+s.charAt(0)<33`.
-1 byte by using the `!s.trim().equals(s)` trick from *@someone*'s C# .NET answer instead of `s.matches(" .*|.* ")`.
-8 bytes thanks to *@Nevay* again by changing `!s.trim().equals(s)` to `s!=s.trim()`, because `String#trim` will return "*A copy of this string with leading and trailing white space removed, or **this string if it has no leading or trailing white space***", thus the reference stays the same and `!=` can be used to check if they are the same reference, instead of `.equals` to check the same value.

**Explanation:**

Try it here (or try a more visual version here with `#` instead of spaces).

```
s->{                               // Method with String as both parameter and return-type
  String r=s;                      //  Result-String (starting at the input)
  for(int f=0;                     //  Flag-integer (starting at 0)
      s!=s.trim();                 //  Loop as long as `s` contains leading/trailing spaces
      f^=1)                        //    And XOR(1) `f` after every iteration (0->1; 1->0)
    r+="\n"                        //   Append the result with a new-line
       +(                          //    Followed by:
         s=f+                      //     If `f` is 0,
             s.charAt(0)<33        //     and `s` starts with a space
           |!s.endsWith(" ")?      //     Or doesn't end with a space
            s.substring(1)         //      Remove the first leading space
           :                       //     Else:
            s.replaceAll(" $",""));//      Remove the last trailing space
                                   //  End of loop (implicit / single-line body)
  return r;                        //  Return the result-String
}                                  // End of method

```
> 5 votes

# Answer
# Jelly, 16 bytes

```
Ḋ=⁶Ḣ$¡UµÐĿ¹Ṛƭ€QY

```

Try it online!

-2 bytes thanks to Erik the Outgolfer
-1 byte thanks to miles

# Explanation

```
Ḋ=⁶Ḣ$¡UµÐĿ¹Ṛƭ€QY  Main link
       µÐĿ        While the results are unique (collecting intermediate results), apply the last link (`µ` creates a new monadic link):
Ḋ=⁶Ḣ$¡            Remove a space from the beginning if there is one
 =⁶Ḣ$             If the first character is a space, then 1, else 0
 =                Compare each character to
  ⁶               ' '
   Ḣ              Get the first comparison
Ḋ                 Then Dequeue the string (s -> s[1:])
    ¡             That many times
     U            And reverse the string (the next time this is called, it will remove spaces from the end instead)
             €    For each string
            ƭ     Alternate between two commands:
          ¹       Identity (do nothing), and
           Ṛ      Reverse
          ¹Ṛƭ€    Correct all strings that are reversed to remove the trailing space
              Q   Remove duplicates (where there was no space to remove)
               Y  Join on newlines

```
> 4 votes

# Answer
# C, ~~91~~ 90 bytes

```
i,l;f(char*s){for(i=puts(s);i;i=(s[l=strlen(s)-1]*=s[l]>32)?i:puts(s))i=*s<33&&puts(++s);}

```

Try it online!
> 4 votes

# Answer
# Java (OpenJDK 8), ~~161 147~~ 146 bytes

```
x->{for(int l=0,r=x.length(),k=-1,u,v;((u=32-x.charAt(l)>>k)*(v=32-x.charAt(r-1)>>-1))<1;x+="\n"+x.substring(l-=k&~u|v,r+=(k=~k)&~v|u));return x;}

```

Try it online!

-1 byte thanks to *@Kevin Cruijssen*!

```
x -> {
    /*
     * l: left index (inclusive)
     * r: right index (exclusive)
     * k: side to remove from, -1:=left, 0:=right
     * u: left character   0:=space, <0:=no space (-1 if k is left side)
     * v: right character  0:=space, -1:=no space
     */
    for (int l = 0, r = x.length(), k = -1, u, v;
            ((u = 32 - x.charAt(l) >> k)
           * (v = 32 - x.charAt(r - 1) >> -1)) < 1; // loop while left or right has space(s)
            x += "\n" + x.substring(                // append newline and substring
                    l -= k & ~u | v,                // inc. left  if k is left side
                                                    //               and left has space
                                                    //            or right has no space
                    r += (k = ~k) & ~v | u));       // dec. right if k is right side
                                                    //               and right has space
                                                    //            or left has no space
    return x;
}

```
> 3 votes

# Answer
# 05AB1E, ~~25~~ 17 bytes

*-8 bytes by borrowing the no-need-for-an-end-check idea from Emigna*

```
,v2F¬ðQi¦DNiR},}R

```

Try it online!

I'm pretty sure a less straightforward approach can beat that solution easily. For now...

**Explanations:**

```
,v2F¬ðQi¦DNiR},}R           Full Programm
,                           Print the input string
 v                          For each char of the string
                               (we don't really care, we only need to loop
                                enough times to accomplish our task, since
                                we print conditionally we can loop more
                                times than necessary)
  2F...........}            Two times...
    ¬õQi                       Is 1st item a space?
        ¦D                        Remove 1st item + duplicate
          NiR}                    If on the second pass: reverse the list
              ,                   Pop & print with newline
               }               End If
                 R          Reverse the list

```
> 3 votes

# Answer
# Ruby, 63 bytes

```
->s{*x=s;(s=~/^ /&&x<<s=$';s=~/ $/&&x<<s=$`)while s=~/^ | $/;x}

```

Try it online!
> 3 votes

# Answer
# , ~~145~~ ~~133~~ 111 bytes

*-12 bytes thanks to @Giuseppe, by storing the result of `sub` in a new variable and testing for whether it has changed*

*-22 bytes by returning a vector of strings rather than a string with newlines*

```
function(s){L=s
while(grepl("^ | $",s)){if((x=sub("^ ","",s))!=s)L=c(L,x)
if((s=sub(" $","",x))!=x)L=c(L,s)}
L}

```

Try it online!

Explanation on a partially ungolfed version:

```
function(s){
  L=s                          # Initialise a vector with the original string
  while(grepl("^ | $",s)){     # While there are leading or trailing spaces...
    if((x=sub("^ ","",s))!=s){ # Check whether we can remove a leading space
      L=c(L,x)                 # If so, add the shortened string to the vector
    }
    if((s=sub(" $","",x))!=x){ # Check whether we can remove a trailing space
      L=c(L,x)                 # If so, add the shortened string to the vector
    }
  }
  L                            # Return the vector
}

```
> 3 votes

# Answer
# Husk, ~~23~~ 22 bytes

```
u§↑L`G`I¢e₁ȯ↔₁↔
?tI<"!

```

Thanks to Leo for -1 byte.

Try it online!

## Explanation

The function ``G`I` should really be a built-in...

```
?tI<"!  Helper function: remove initial space.
?  <"!  If less than the string "!",
 t      remove first character,
  I     else return as is.
u§↑L`G`I¢e₁ȯ↔₁↔  Main function.
         e       List containing
          ₁      the helper function
           ȯ↔₁↔  and the composition reverse-helper-reverse.
        ¢        Repeat it cyclically.
    `G`I         Cumulative reduce from left by function application
                 using input string as initial value.
 §↑L             Take first length(input) values.
u                Remove duplicates.

```
> 3 votes

# Answer
## C++, ~~196~~ ~~193~~ ~~189~~ ~~186~~ 183 bytes

-10 bytes thanks to Jonathan Frech
-3 bytes thanks to Zacharý

```
#include<iostream>
#include<string>
#define D std::cout<<s<<'\n'
#define R ~-s.size()
auto u=[](auto s){D;while(s[0]<33||s[R]<33){if(s[0]<33)s.erase(0,1),D;if(s[R]<33)s.erase(R),D;}};

```

Compilation with MSVC requires the un-activation of SDL checks
> 3 votes

# Answer
# Java (OpenJDK 8), ~~137~~ ~~125~~ ~~121~~ ~~120~~ 124 bytes

```
s->{int i=1;do System.out.println(s);while(s!=(s=s.substring(s.charAt(0)<33?i:(i=0),s.length()-(s.endsWith(" ")?i^=1:0))));}

```

Try it online!
> 3 votes

# Answer
# MATL, ~~21~~ 16 bytes

```
tnE:"t@o&)w46-?x

```

This uses dots instead of spaces for greater clarity. For spaces replace `46` by `32`.

**Try it online!**

### Explanation

```
tn      % Input (implicit). Duplicate and push length, say L
E       % Multiply by 2
:       % Push range [1 2 ... 2*L]
"       % For each k in that array
  t     %   Duplicate the string at the top of the stack
  @     %   Push k
  o     %   Parity: gives 1 or 0
  &)    %   Two-ouput indexing. Pushes the k-th entry of the string and then
        %   the rest of the string. The 1-st output is the first, the 0-th
        %   is the last (indexing is 1-based dand modular)
  w     %   Swap
  46-   %   Subtract 46, which ias ACII for '.'
  ?     %   If non-zero
    x   %     Delete sub-string that was obained by removing that entry
        %   End (implicit)
        % End (implicit)
        % Display stack (implicit)

```
> 3 votes

# Answer
# C# (.NET Core), 176 170 bytes

```
using System;s=>{Action o=()=>Console.WriteLine(s);o();Func<int>l=()=>s.Length-1;while(s!=s.Trim()){if(s[0]<33){s=s.Remove(0,1);o();}if(s[l()]<33){s=s.Remove(l());o();}}}

```

*Try it online!*

This is an alternative to @someone's answer, and just outputs the strings directly.
> 2 votes

# Answer
# JavaScript (ES6), 76 bytes

```
f=(s,r,n,l=s.length)=>s[r?--l:0]<"!"?s+`
`+f(s.slice(!r,l),!r):n?s:f(s,!r,1)

```

Outputs as a multiline string.

## Test Cases

Using dots instead of spaces, as most answers are doing.

```
f=(s,r,n,l=s.length)=>s[r?--l:0]<"!"?s+`
`+f(s.slice(!r,l),!r):n?s:f(s,!r,1)

// converting to and from dots and spaces
let dots=s=>s.replace(/^\.+|\.+$/gm,x=>" ".repeat(x.length));
let spaces=s=>s.replace(/^ +| +$/gm,x=>".".repeat(x.length));

["....Yes, Sir!.....", "......Let's go golfing...", "Hello..", "World", ".....................a....."]
.forEach(test=>O.innerHTML+=spaces( f(dots(test)) ) + "\n\n");
```

```
<pre id=O></pre>
```
> 2 votes

# Answer
## Sed, 24 bytes

```
p;:s s/ //p;s/ $//p;ts;D

```

Try It Online !
> 2 votes

# Answer
# Octave, ~~88~~ 83 bytes

*5 bytes off thanks to Stewie Griffin!*

```
x=[input('') 0];for p=mod(1:sum(x),2)if x(~p+end*p)<33,disp(x=x(2-p:end-p)),end,end

```

**Try it online!**
> 2 votes

# Answer
# x86 machine code for Linux, 60 bytes

```
e8 1f 00 00 00 31 c0 80 3f 20 75 09 47 4d 74 10
e8 0f 00 00 00 80 7c 2f ff 20 74 05 84 c0 75 e5
c3 4d eb dc 6a 04 58 50 31 db 43 89 f9 89 ea cd
80 58 6a 0a 89 e1 89 da cd 80 58 c3

```

This is a function for Linux x86. It takes as input pointer to the string in `edi` and string length in `ebp`.

Ungolfed, with some infrastructure to test (compile with FASM, run with the string as program argument; look for `undress:` label for actual function code):

```
format ELF executable
segment executable
SYS_WRITE = 4
    jmp     callUndress
; -------------------- the function itself --------------------------------
; Input:
;   edi=string
;   ebp=length
undress:
undressLoopPrint:
    call    print
undressLoop:
    xor     eax, eax    ; flag of having printed anything on this iteration
    cmp     byte [edi], ' '
    jne     startsWithoutSpace
    inc     edi
    dec     ebp
    jz      quit
    call    print
startsWithoutSpace:
    cmp     byte [edi+ebp-1], ' '
    je      endsWithSpace
    test    al, al      ; if print has been called, then we have 0x0a in eax
    jnz     undressLoop
quit:
    ret
endsWithSpace:
    dec     ebp
    jmp     undressLoopPrint
print:
    push    SYS_WRITE
    pop     eax
    push    eax
    xor     ebx, ebx
    inc     ebx ; STDOUT
    mov     ecx, edi
    mov     edx, ebp
    int     0x80
    pop     eax
    push    0x0a    ; will print newline
    mov     ecx, esp
    mov     edx, ebx ; STDOUT=1, which coincides with the length of newline
    int     0x80
    pop     eax
    ret
; --------------------- end undress ---------------------------------------
SYS_EXIT = 1
STDERR = 2
callUndress:
    pop     eax     ; argc
    cmp     eax, 2
    jne     badArgc
    pop     eax     ; argv[0]
    pop     edi
    mov     al, 0
    cld
    mov     ecx, -1
    repne   scasb
    lea     edi, [edi+ecx+1] ; argv[1]
    neg     ecx
    sub     ecx, 2
    mov     ebp, ecx     ; strlen(argv[1])
    call    undress
    xor     ebx, ebx
exit:
    mov     eax, SYS_EXIT
    int     0x80
    ud2
badArgc:
    mov     esi, eax
    mov     eax, SYS_WRITE
    mov     ebx, STDERR
    mov     ecx, badArgcMsg
    mov     edx, badArgcMsgLen
    int     0x80
    mov     ebx, esi
    neg     ebx
    jmp     exit
badArgcMsg:
    db      "Usage: undress YourString",0x0a,0
badArgcMsgLen = $-badArgcMsg
segment readable writable
string:
    db      100 dup(0)
    stringLen = $-string

```
> 2 votes

# Answer
# PHP, 117 bytes

I add an extra space at the start so it will take the space out and show the original without any extra code.

Kinda new to this... would the \<?php and the space at the start of the PHP file add 6 extra bytes or do I get that for free?

```
$s=" $argn";while($r!=$s){$r=$s;if($s[0]==" ")echo($s=substr($s,1))."
";if($s[-1]==" ")echo($s=substr($s,0,-1))."
";}

```

Try it online!
> 2 votes

# Answer
# Octave, 89 bytes

```
s=input('');while any(s([1,end])<33)if s(1)<33,s(1)=[],end,if s(end)<33,s(end)=[],end,end

```

Try it online!

I'll add an explanation later, when I have the time. I might be able to golf off some bytes if I change the approach completely, but I can't see how unfortunately.

The last letters here spell out: "sendsendendend". I wish there was a way to store `end` as a variable and use that, but guess what ...
> 1 votes

# Answer
# Python 2, 79 bytes

-1 byte thanks to @JonathanFrech

```
f=lambda s,i=1:[s]+(s>i*'!'and'!'>s[-1]and f(s[:-1])or'!'>s and f(s[1:],0)or[])

```

Try it online!

The test suit replaces `"."` with `" "` before calling the function and replaces `" "` back to `"."` before printing the results for clarity.
> 1 votes

# Answer
# Pyth, 28 bytes

```
QW<lrKQ6lQ=hZ?&%Z2qdhQ=tQ=PQ

```

**Try it here!** or **Verify all test cases!**

# Explanation

```
QW<lrKQ6lQ=hZ?&%Z2qdhQ=tQ=PQ   ~ Full program. Q is autoinitialized to input.

Q                              ~ Output the input.
 W<lrKQ6lQ                     ~ Loop while the condition is met.
  <                            ~ Is smaller?
   lrKQ6                       ~ The length of the original input, stripped on both sides.
        lQ                     ~ The length of the current Q.
          =hZ                  ~ Increment a variable Z, initially 0
             ?&%Z2qdhQ         ~ If Z % 2 == 1 and Q[0] == " ", then:
                      =tQ      ~ Make Q equal to Q[1:] and output, else:
                         =PQ   ~ Make Q equal to Q[:-1] and output.

```
> 1 votes

# Answer
# Bash, ~~98~~ 94 bytes

Saved 4 bytes using subshell instead of sequences (poor performances)

```
r()(s=$1;[[ $s = $b ]]||([[ $s = $a ]]||echo "$s"
b=$a a=$s;((i=!i))&&r "${s# }"||r "${s% }"))

```

First answer

```
r(){ s=$1;[[ $s = $b ]]||{ [[ $s = $a ]]||echo "$s"
b=$a a=$s;((i=!i))&&r "${s# }"||r "${s% }";};}

```

Note the `!` must be escaped in interactive mode
> 1 votes

# Answer
# C# - yet again, 125 bytes

```
while(s.Trim()!=s){if(s[0]==' '){yield return s=s.Substring(1);}if(s.Last()==' '){yield return s=s.Substring(0,s.Length-1);}}

```

Cheers!

Try it online!
> 1 votes

# Answer
# Haskell, 109 bytes

```
(b%e)
t=last
b(' ':s)=s
b l=l
e l|t l>' '=l|1>0=init l
(g%h)l=l:t((h%g$g l):[t$(h%g$h l):[[]|h l==l]|g l==l])

```

Try it online!

`b` removes leading space if there is a leading space

`e` removes trailing space if there is a trailing space

`%` switches between `b` and `e`
> 1 votes

# Answer
# Haskell, 86 bytes

```
(f#g)
r=reverse
f(' ':s)=s
f s=g s
g=r.f.r
(a#b)s=s:[x|last s<'!'||s<"!",x<-(b#a)$a s]

```

Try it online! Usage: `(f#g) " test "` yields a list of strings.

### Explanation

* Function `f` removes a leading space from a given string. If there is no leading space, it calls function `g`.
* Function `g` reverses the string, calls `f` and reverses back. This removes a trailing space if there is one, and an leading space otherwise.
* If a string has neither leading nor trailing spaces, then `f` and `g` diverge, so this needs to be checked before.
* The main function `#` is initialized with `f` as first and `g` as second argument. The third argument `s` is the input string, which is appended to the recursively computed list of results:
    + If `s` has no leading or trailing spaces, then `last s<'!'||s<"!"` is false and the list of results empty.
    + Otherwise the function given as first argument is applied to `s` and `#` is applied recursively with `f` and `g` exchanged.
> 1 votes

# Answer
# D, ~~142~~ 140 bytes

```
import std.stdio;void u(T)(s){s.writeln;while(s[0]<33||s[$-1]<33){if(s[0]<33){s=s[1..$];s.writeln;}if(s[$-1]<33){s=s[0..$-1];s.writeln;}}}

```

Try it online!

This is a port of HatsuPointerKun's C++ answer.
> 1 votes

# Answer
# Julia, 138 bytes

```
a(s)=' ' in s?s[1]==' '?(println(s);z(s[2:end])):z(s[1:end]):print(s)
z(s)=' ' in s?s[end]==' '?(println(s);a(s[1:end-1])):a(s[1:end]):print(s)

```

Not sure if there is a way to substitute another character for `end`, but if there was that would probably save some bytes.
> 1 votes

# Answer
# Jq 1.5, ~~149~~ 116 bytes

```
def G(p):if p==[]then. else sub(p[0];"")as$n|if.!=$n then.,($n|G(p|reverse))else($n|G(p[1:]))end end;G(["^ "," $"])

```

Expanded

```
def G(p):
  if p==[] then .                  # stop when no patterns remain
  else
     sub(p[0];"") as $n            # use first pattern
   | if .!=$n                      # if we removed something
     then ., ($n|G(p|reverse))     #   return result and switch patterns
     else ($n|G(p[1:]))            # otherwise remove failed pattern
     end
  end
;
G(["^ "," $"])

```

Sample Run

```
$ jq -MRr 'def G(p):if p==[]then. else sub(p[0];"")as$n|if.!=$n then.,($n|G(p|reverse))else($n|G(p[1:]))end end;G(["^ "," $"])' <<<'     codegolf     '
     codegolf
    codegolf
    codegolf
   codegolf
   codegolf
  codegolf
  codegolf
 codegolf
 codegolf
codegolf
codegolf

$ wc -c <<<'def G(p):if p==[]then. else sub(p[0];"")as$n|if.!=$n then.,($n|G(p|reverse))else($n|G(p[1:]))end end;G(["^ "," $"])'
 116

```
> 0 votes

# Answer
# Kotlin, ~~151~~ 150 bytes

```
{var v=it
var c={println(v)}
while(0<((if(v[0]<'!'){c()
v=v.substring(1)
1}else 0)+if(v.endsWith(' ')){c()
v=v.slice(0..v.length-2)
1}else 0
)){}
c()}

```

## Beautified

```
{
    var v = it
    var c={println(v)}
    while ( 0 <(
            (if (v[0] < '!') {
                c()
                v = v.substring(1)
                1
            } else 0)
                    +
                    if (v.endsWith(' ')) {
                        c()
                        v = v.slice(0..v.length-2)
                        1
                    } else 0
            )){}
    c()
}

```

## Test

```
/** Shows spaces, just helps viewing answer. */
fun println(i: String) {
    for (c in i) {
        if (c == ' ') {
            print('~')
        } else {
            print(c)
        }
    }
    print('\n')
}
var u: (String) -> Unit =
{var v=it
var c={println(v)}
while(0<((if(v[0]<'!'){c()
v=v.substring(1)
1}else 0)+if(v.endsWith(' ')){c()
v=v.slice(0..v.length-2)
1}else 0
)){}
c()}

fun main(args: Array<String>) {
    u("      Let's go golfing   ")
}

```

# Edits

-1 -\> `x == ' '` =\> `x < '!'` Jonathan French
> 0 votes

# Answer
This is not a successful contender, because it works only for len(left whitespace) between \[len(right whitespace), len(right whitespace)+1\]. Anyway, just for the fun of it:

Python 3, 56 bytes:

```
def f(a,e=0):print(a);a[e]<'!'and f(a[e+1:e or None],~e)

```
> 0 votes

# Answer
# GolfScript \- 46 bytes

```
'
'+{.(32={.1}{;.0}if\);)32={'
'+\1}{;0}if|}do

```

### Explanation

```
'\n'+    Adds endline to the argument
{.       Starts do loop and duplicates the top of the stack
(32=     Is the first character a ' '?
{.1}     It is, duplicate result and push 1
{;.0}if  It isn't, remove cut string, duplicate and push 0
\        The number (0 or 1) we pushed before sinks one position
);)      Obtains the last character of the string
32=      Is it a space?
{'\n'+\1} Add a new line, make the number we pushed before rise
          one position, and push another 1
{;0}if   Same as before
|        'Or' between the two numbers we pushed before
}do      If at least one of them was 1, repeat!

```

### Test

It works with dots by replacing 32 with 46.

```
Input: ...test..

Output:

...test..
..test..
..test.
.test.
.test
test

```
> 0 votes

# Answer
# Japt `-R`, 18 bytes

```
ÈrYg"^  $"ò}hUÊN â

```

Try it
> 0 votes

# Answer
# Stax, 16 bytes

```
ùG⌐♦ò⌡╩d♪º"╪8·`;

```

Run and debug it

### Procedure:

* Alternate replacing regexes `"^ "` and `" $"` with `""`. Do this `n` times where `n` is the length of the input.
* Remove duplicate values.
> 0 votes

# Answer
# Perl 5 `-n`, 33 bytes

```
(s/^ //&&say)|(s/ $//&&say)&&redo

```

Try it online!
> 0 votes

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


# Question
Title: Build a mob of suspiciously happy lenny faces ( ͡° ͜ʖ ͡°)
I was going through a bizarre thread on Reddit, and came across this:

( ͡°( ͡° ͜ʖ( ͡° ͜ʖ ͡°)ʖ ͡°) ͡°)

It's representing a group of people smiling somewhat suspiciously.

(In the challenge below though, spaces to the left of the right eyes were dropped somehow while I was writing the challenge. Note the spec).

---

Your goal is to create a group of smiling lenny faces `n` deep with the following rules:

1. At depth one, a full face (`( ͡° ͜ʖ ͡°)`) is shown.
2. At depth two, half faces are shown. On the left side, a little over half the face (`( ͡° ͜ʖ`) is represented. On the right however, the right side is shown, and the mouth is omitted (`ʖ ͡°)`)
3. Any deeper, and only the sides of head and eyes are shown (`( ͡°` and `͡°)`. There's a space between the eye and left side of the head, but there are, despite appearances, no spaces on the right side. The spacing is due the `͡` character which messes with things a bit.

---

Input:

* `n`, showing how many layers deep of faces to show.
* `n` will always be in the range `0 <= n <= 500`. You are not required to handle anything outside of this range.
* `n` may be offset by 1 so that 0 means one face instead of no faces. You'll need to handle -1 then though.

Output:

* A string, or character array, or anything remotely comparable (like a list of single-character strings in Python/Javascript). It can also be printed directly. Trailing white-space is fine.

You can submit a complete program, or a function.

---

Since it's difficult to see what characters are involved, here's it laid out in Python:

```
>> [ord(c) for c in '( ͡° ͜ʖ ͡°)']
[40, 32, 865, 176, 32, 860, 662, 32, 865, 176, 41]

>> [ord(c) for c in '( ͡°( ͡°( ͡° ͜ʖ( ͡° ͜ʖ ͡°)ʖ ͡°)͡°)͡°)']
[40, 32, 865, 176, 40, 32, 865, 176, 40, 32, 865, 176, 32, 860, 662, 40, 32, 865, 176, 32, 860, 662, 32, 865, 176, 41, 662, 32, 865, 176, 41, 865, 176, 41, 865, 176, 41]

```

---

Test Cases:

```
face_crowd(0)
''

face_crowd(1)
'( ͡° ͜ʖ ͡°)'

face_crowd(2)
'( ͡° ͜ʖ( ͡° ͜ʖ ͡°)ʖ ͡°)'

face_crowd(5)
'( ͡°( ͡°( ͡°( ͡° ͜ʖ( ͡° ͜ʖ ͡°)ʖ ͡°)͡°)͡°)͡°)'

face_crowd(10)
'( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡° ͜ʖ( ͡° ͜ʖ ͡°)ʖ ͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)'

face_crowd(500)
'( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡° ͜ʖ( ͡° ͜ʖ ͡°)ʖ ͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)'

```

---

Here's an extraordinarily naive recursive reference implementation (posted on my Github). I tried to keep it as plain as possible for clarity; but there's a lot of duplication

I posted it externally because I wanted to wrap it in a spoiler in case people don't want to see a reference, but that complicates copying the code. I figure it's not important to the challenge really, so it isn't a big deal if it goes down I can paste it here if it's deemed important.

---

This is code-golf, so the least number of bytes in each language wins.

# Answer
# Haskell, ~~89~~ ~~87~~ 80 bytes

*7 bytes off thanks to xnor*

```
(!!)$"":x:iterate(4#8)(7#6$x)
x="( ͡° ͜ʖ ͡°)"
(a#b)y=take a x++y++drop b x

```

Try it online!

To start we assign ( ͡° ͜ʖ ͡°) to a string `x` for convenience.

```
x="( ͡° ͜ʖ ͡°)"

```

Then we build a list of the answers and index it to find the solution. This is done by hardcoding the first two answers as the first two elements of the list and then iterating a function that adds the first 4 characters and the last 4 characters to front and back of the string across the third answer.

```
(!!)$"":x:iterate(4#8)(7#6$x)

```

We also have the special function `(#)` which adds a specified amount of ( ͡° ͜ʖ ͡°) to the front and back of a string:

```
(a#b)y=take a x++y++drop b x

```
> 15 votes

# Answer
# JavaScript (ES6), 66 bytes

```
f=n=>n?"( ͡°"+(--n>1?f(n):" ͜ʖ"+(n?f(n)+"ʖ ":" "))+"͡°)":""

```

Try it online!

Or try it with the following snippet for a better rendering.

```
f=n=>n?"( ͡°"+(--n>1?f(n):" ͜ʖ"+(n?f(n)+"ʖ ":" "))+"͡°)":""

for(n = 0; n <= 10; n++) {
  o.innerHTML += '"' + f(n) + '"\n';
}
```

```
pre { font-family:Arial }
```

```
<pre id="o"></pre>
```

### Commented

In the following code, we use the character set `"eEMN"` (eyebrow, eye, mouth and nose respectively) in order to preserve the formatting.

```
f = n =>           // f is a recursive function taking the number n of remaining
                   // faces to draw
  n ?              // if n is greater than 0:
    "( eE" + (     //   append the left cheek + a space + the left eye
      --n > 1 ?    //   decrement n; if it's still greater than 1:
        f(n)       //     append the result of a recursive call
      :            //   else (n = 0 or 1):
        "MN" + (   //     append the mouth and the nose
          n ?      //     if n = 1:
            f(n)   //       append the result of a recursive call
            + "N " //       followed by the nose + a space
          :        //     else (n = 0):
            " "    //       append a space and stop recursion
        )          //
    )              //
    + "eE)"        //   append the right eye + the right cheek
  :                // else:
                   //   the special case n = 0 is reached only if the original
    ""             //   input is 0; just return an empty string

```
> 9 votes

# Answer
# Python 3, 75 bytes

```
f=lambda i:L[:7+~2%~i]+f(i-1)+L[6+2%i:]if i>1else L*i
L='( ͡° ͜ʖ ͡°)'

```

Try it online!

-6 bytes thanks to xnor
> 8 votes

# Answer
# Excel, 85 bytes

```
=IF(A1>1,REPT("( ͡°",A1-1)&" ʖ( ͡° ͜ʖ ͡°)ʖ "&REPT("͡°)",A1-1),REPT("( ͡° ͜ʖ ͡°)",A1))

```

Naive solution for `n>1`. Second repeat required to handle `0` testcase.
> 7 votes

# Answer
# Retina 0.8.2, 56 bytes

```
.+
$*< $&$*>
 >>
 >ʖ >
<(?=<? )
< ͜ʖ
<
( ͡°
>
͡°)

```

Try it online! Explanation:

```
.+
$*< $&$*>

```

Generate the cheeks, but use `<`s and `>`s because `(`s and `)`s would need to be quoted. A space in the middle ends up between the middle man's nose and left eye.

```
 >>
 >ʖ >

```

If the man in the middle has a man on his left, give that man a nose and a space between it and his left eye.

```
<(?=<? )
< ͜ʖ

```

Add the mouth and nose to the man in the middle and the man to his right if any. We don't see the left eye of the man to his right so he doesn't need a space, and we gave the man in the middle a space on the first stage.

```
<
( ͡°

```

Fix the right cheeks and add the right eyes.

```
>
͡°)

```

Fix the left cheeks and add the left eyes.
> 5 votes

# Answer
# Inform 7, 262 bytes

```
To say x:say "[Unicode 865][Unicode 176]".
To say y:say Unicode 860.
To say z:say Unicode 662.
To say p (N - number):say "( [x][p N minus 1][x])".
To say p (N - 2):say "( [x] [y][z][p 1][z][x])".
To say p (N - 1):say "( [x] [y][z] [x])".
To say p (N - 0):say "".

```

This takes advantage of Inform 7's function overloading: the most specific overload will be run, and the function that takes a number (any integer) as its argument is less specific than the function that takes the number two (and only two) as its argument.

There are some repeated bits of text, like "( \[x\]", which could potentially be abstracted as functions of their own—but I7 is so verbose, defining a new function takes more bytes than this would save! The only places defining a new function seems to save bytes is for the non-ASCII characters, since the syntax for printing them is *even more* verbose than the syntax for function definitions.

Boilerplate to run this:

```
Foo is a room. When play begins: say p 7.

```

Replace 7 with a non-negative integer of your choice.
> 5 votes

# Answer
# C++ (gcc), 102 bytes

```
#include <string>
std::string f(int n){return n?"( ͡°"+(--n>1?f(n):" ͜ʖ"+(n?f(n)+"ʖ ":" "))+"͡°)":"";}

```

Try it online!

Shameless port of Arnauld's JavaScript solution.
> 5 votes

# Answer
# Perl 5 `-p`, 96 bytes

```
$\='( ͡° ͜ʖ ͡°)'if$_--;$\="( ͡° ͜ʖ$\ʖ ͡°)"if$_-->0;$\="( ͡°$\ ͡°)"while$_-->0}{

```

Try it online!
> 4 votes

# Answer
# Stax, 42 bytes

```
ü/┐▐Φd¬•U►^τ∩█┴êZ3↔uº'µ3ó(▀◄Ü▒iÇÆ'[∞_¥▄>A√

```

Run and debug it

I think it appears not to work in Firefox in Windows. But that's just because the FF default font for monospace is Courier, which seems not to support these fancy unicode modifiers or whatever. I think.
> 4 votes

# Answer
# Java 7, ~~133~~ ~~90~~ 89 bytes

```
String f(int n){return--n<0?"":"( ͡°"+(n>1?f(n):" ͜ʖ"+(n>0?f(n)+"ʖ ":" "))+"͡°)";}

```

Port of @Arnauld's recursive JavaScript answer, since it's shorter than my initial first attempt using a Java 8+ lambda.

Try it online.

**Explanation:**

```
String f(int n){               // Recursive method with integer parameter & String return-type
  return--n                    //  Decrease the input by 1 first
           <0?                 //  And if the input is now -1:
              ""               //   Return an empty string
             :                 //  Else:
             "( ͡°"             //   Return the left part of Lenny's face
             +(n>1?            //   And if the modified input is larger than 1:
                   f(n)        //    Append a recursive call with this now decreased input
                  :            //   Else (the input is here either 0 or 1):
                   " ͜ʖ"        //    Append Lenny's nose
                   +(n>0?      //    And if the input is larger than 0 (thus 1):
                         f(n)  //     Append a recursive call
                         +"ʖ " //     As well as the right part of its nose
                        :      //    Else (thus 0):
                         " "   //     Append a space instead
            ))+"͡°)";}          //   And also append the right part of Lenny's

```
> 3 votes

# Answer
# Python 3, 66 bytes

```
f=lambda i:i*'x'and"( ͡° ͜ʖ"[:7+~2%~i]+f(i-1)+"ʖ ͡°)"[2%i:]

```

Try it online!

The index calculation idea is borrowed from @xnor in @Jitse's solution.
> 3 votes

# Answer
# Julia 1.0, 85 bytes

```
f(n,s="( ͡° ͜ʖ ͡°)")=n<3 ? ["",s,s[1:10]s*s[10:17]][n+1] : s[1:5]f(n-1)s[12:17]

```

Try it online!
> 2 votes

# Answer
# Japt, 47 bytes (UTF-8)

```
?"( ͡°{´U>1?ß:" ͜ʖ"+(U?'ʖiß:S} ͡°)":P

```

Saved a byte thanks to Shaggy

Try it
> 2 votes

# Answer
# Python 3, 80 chars, 86 bytes

```
x='( ͡° ͜ʖ ͡°)'
n=3-1
print(x[:4]*(n-1)+x[:7]*(n!=0)+x+x[6:]*(n!=0)+x[8:]*(n-1))

```

Try it online!

To put input, change the 3 to whatever input you want, leaving the -1 alone.

If anyone knows a better way to do input that would reduce the char count let me know.

Nothing fancy going on here, just string slicing and abuse of booleans
> 2 votes

# Answer
# Canvas, 46 bytes

```
b＊5USy{↖ｑYｑ⇵≡„a¹„┬Ｈｃ＋
⁷ｍ；⁷±ｍ±└＋＋
Ｈ？３４⁸］］⁷］５７⁸｝

```

Try it here!
> 1 votes

# Answer
# Charcoal, 41 bytes

```
ＮθＰ⭆θ✂ʖ ͡°)⊗‹¹ι←⭆θ✂ʖ͜ °͡ (∧‹¹ι³

```

Try it online! The deverbosifier tries to quote the second string for some reason, but it doesn't seem to be necessary, but here's the verbose version if you want it. Explanation:

```
Ｎθ

```

Input the number of faces.

```
Ｐ⭆θ✂ʖ ͡°)⊗‹¹ι

```

Print the left sides of the faces (on our right as we see them). These consist of the string `ʖ ͡°)` repeated up to twice, and then that string without the first two characters repeated the remaining number of times.

```
←⭆θ✂ʖ͜ °͡ (∧‹¹ι³

```

Print the right sides of the faces (on our left as we see them). These consist of the (reversed) string `ʖ͜ °͡ (` repeated up to twice, and then that string without the first two characters repeated the remaining number of times.

The more observant among you will have noticed that the middle face has its nose generated twice which is why I'm printing in such a way that they overlap.
> 1 votes

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


title: Determine if 4 points form a square

text:
# Question
Title: Determine if 4 points form a square
Write a function that takes 4 points on the plane as input and returns true iff the 4 points form a square. The points will have integral coordinates with absolute values \< 1000.

You may use any reasonable representation of the 4 points as input. The points are not provided in any particular order.

Shortest code wins.

Example squares:

```
(0,0),(0,1),(1,1),(1,0)    # standard square
(0,0),(2,1),(3,-1),(1,-2)  # non-axis-aligned square
(0,0),(1,1),(0,1),(1,0)    # different order

```

Example non-squares:

```
(0,0),(0,2),(3,2),(3,0)  # rectangle
(0,0),(3,4),(8,4),(5,0)  # rhombus
(0,0),(0,0),(1,1),(0,0)  # only 2 distinct points
(0,0),(0,0),(1,0),(0,1)  # only 3 distinct points

```

You may return either true or false for the degenerate square `(0,0),(0,0),(0,0),(0,0)`

# Answer
> 13 votes
# Python ~~176~~ ~~90~~ 79 bytes

```
def S(A):c=sum(A)/4.0;return set(A)==set((A[0]-c)\*1j\*\*i+c for i in range(4))

```

Function S takes a list of complex numbers as its input (A). If we know both the centre and one corner of a square, we can reconstruct the square by rotating the corner 90,180 and 270 degrees around the centre point (c). On the complex plane rotation by 90 degrees about the origin is done by multiplying the point by *i*. If our original shape and the reconstructed square have the same points then it must have been a square.

# Answer
> 13 votes
## J, 28 ~~17~~ ~~25~~ ~~27~~

J doesn't really have functions, but here's a monadic verb that takes a vector of points from the complex plane:

```
4 8 4-:#/.~&(/:~&:|&,&(-/~))

```

Method is a mix of Michael Spencer (work solely on inter-vertex lengths; but he's currently failing my rhombus2) and Eelvex's (check the sets' sizes) works. Reading right to left:

* `-/~` compute all point differences
* `,` flatten
* `|` extract magnitude
* `/:~` sort up
* `#/.~` nub and count
* `4 8 4 -:` must have exactly 4 equidistant (at 0), 8 a bit bigger (length 1, sides), 4 bigger yet (length `sqrt 2`, diagonals)

Demonstration:

```
   NB. give the verb a name for easier use
   f =: 4 8 4-:#/.~&(/:~&:|&,&(-/~))

   NB. standard square
   f 0 0j1 1j1 1
1

   NB. non-axis-aligned square
   f 0 2j1 3j_1 1j_2
1

   NB. different order
   f 0 1j1 0j1 1
1

   NB. rectangle
   f 0 0j2 3j2 3
0

   NB. rhombus 1
   f 0 3j4 8j4 5
0

   NB. rhombus 2
   f 0 1ad_60 1ad0 1ad60
0

```

For memory's sake, my previous method (required ordered vertices, but could detect regular polygons of any order):

```
*./&(={.)&(%1&|.)&(-1&|.)

```

See history for explanation and demo. The current method could probably be expanded to other polygons, that `4 8 4` does look a lot like a binomial distribution.

# Answer
> 5 votes
# Python, 71 ~~42~~

```
lambda A: len(set(A))==4 and len(set(abs(i-j)for i in A for j in A))==3

```

Update 1) to require 4 different points (would previously give false positives for repeated points - are there others?) 2) to define a function per spec

For a square, the vector between any two points must be 0 (the same point), a side, or a diagonal. So, the set of the magnitude of these vectors must have length 3.

```
# Accepts co-ordinates as sequences of complex numbers

SQUARES=[
 (0+0j,0+1j,1+1j,1+0j),  # standard square
 (0+0j,2+1j,3-1j,1-2j),  # non-axis-aligned square
 (0+0j,1+1j,0+1j,1+0j)   # different order
]

NONSQUARES=[
 (0+0j,0+2j,3+2j,3+0j),  # rectangle
 (0+0j,3+4j,8+4j,5+0j),  # rhombus
 (0+0j,0+1j,1+1j,0+0j),   # duplicated point
 (0+0j,1+60j,1+0j,1-60j)  # rhombus 2 (J B)
]

test = "lambda A: len(set(A))==4 and len(set(abs(i-j)for i in A for j in A))==3"
assert len(test)==71

is_square=lambda A: len(set(A))==4 and len(set(abs(i-j)for i in A for j in A))==3

for A in SQUARES:
    assert is_square(A)

for A in NONSQUARES:
    assert not is_square(A)

```

# Answer
> 3 votes
**OCaml, 145 164**

```
let(%)(a,b)(c,d)=(c-a)*(c-a)+(d-b)*(d-b)
let t a b c d=a%b+a%c=b%c&&d%c+d%b=b%c&&a%b=a%c&&d%c=d%b
let q(a,b,c,d)=t a b c d||t a c d b||t a b d c

```

Run like this:

```
q ((0,0),(2,1),(3,-1),(1,-2))

```

Let's deobfuscate and explain a bit.

First we define a norm:

```
let norm (ax,ay) (bx,by) = (bx-ax)*(bx-ax)+(by-ay)*(by-ay)

```

You'll notice that there is no call to sqrt, it's not needed here.

```
let is_square_with_fixed_layout a b c d =
  (norm a b) + (norm a c) = norm b c
  && (norm d c) + (norm d b) = norm b c
  && norm a b = norm a c
  && norm d c = norm d b

```

Here a, b, c and d are points. We assume that these points are layed out like this:

```
a - b
| / |
c - d

```

If we have a square then all these conditions must hold:

* a b c is a right triangle
* b c d is a right triangle
* the smaller sides of each right triangle have the same norms

Observe that the following always holds:

```
is_square_with_fixed_layout r s t u = is_square_with_fixed_layout r t s u

```

We will use that to simplify our test function below.

Since our input is not ordered, we also have to check all permutations. Without loss of generality we can avoid permuting the first point:

```
let is_square (a,b,c,d) =
  is_square_with_fixed_layout a b c d
  || is_square_with_fixed_layout a c b d
  || is_square_with_fixed_layout a c d b
  || is_square_with_fixed_layout a b d c
  || is_square_with_fixed_layout a d b c
  || is_square_with_fixed_layout a d c b

```

After simplification:

```
let is_square (a,b,c,d) =
  is_square_with_fixed_layout a b c d
  || is_square_with_fixed_layout a c d b
  || is_square_with_fixed_layout a b d c

```

Edit: followed M.Giovannini's advice.

# Answer
> 3 votes
## Factor

An implementation in the Factor programming language:

```
USING: kernel math math.combinatorics math.vectors sequences sets ;

: square? ( seq -- ? )
    members [ length 4 = ] [
        2 [ first2 distance ] map-combinations
        { 0 } diff length 2 =
    ] bi and ;

```

And some unit tests:

```
[ t ] [
    {
        { { 0 0 } { 0 1 } { 1 1 } { 1 0 } }   ! standard square
        { { 0 0 } { 2 1 } { 3 -1 } { 1 -2 } } ! non-axis-aligned square
        { { 0 0 } { 1 1 } { 0 1 } { 1 0 } }   ! different order
        { { 0 0 } { 0 4 } { 2 2 } { -2 2 } }  ! rotated square
    } [ square? ] all?
] unit-test

[ f ] [
    {
        { { 0 0 } { 0 2 } { 3 2 } { 3 0 } }   ! rectangle
        { { 0 0 } { 3 4 } { 8 4 } { 5 0 } }   ! rhombus
        { { 0 0 } { 0 0 } { 1 1 } { 0 0 } }   ! only 2 distinct points
        { { 0 0 } { 0 0 } { 1 0 } { 0 1 } }   ! only 3 distinct points
    } [ square? ] any?
] unit-test

```

# Answer
> 3 votes
## Haskell, 100 characters

Here's how I'd write the JB's J solution in Haskell. With no attempt made to damage readability by removing nonessential characters, it's about 132 characters:

```
import Data.List
d (x,y) (x',y') = (x-x')^2 + (y-y')^2
square xs = (== [4,8,4]) . map length . group . sort $ [d x y | x<-xs, y<-xs]

```

You can scrape it down a bit to 100 by removing excess spaces and renaming some things

```
import Data.List
d(x,y)(a,b)=(x-a)^2+(y-b)^2
s l=(==[4,8,4]).map length.group.sort$[d x y|x<-l,y<-l]

```

Let's use QuickCheck to ensure that it accepts arbitrary squares, with one vertex at (x,y) and edge vector (a,b):

```
prop_square (x,y) (a,b) = square [(x,y),(x+a,y+b),(x-b,y+a),(x+a-b,y+b+a)]

```

Trying it in ghci:

```
ghci> quickCheck prop_square
*** Failed! Falsifiable (after 1 test):
(0,0)
(0,0)

```

Oh right, the empty square isn't considered a square here, so we'll revise our test:

```
prop_square (x,y) (a,b) =
   (a,b) /= (0,0) ==> square [(x,y),(x+a,y+b),(x-b,y+a),(x+a-b,y+b+a)]

```

And trying it again:

```
ghci> quickCheck prop_square
+++ OK, passed 100 tests.

```

# Answer
> 2 votes
## Python - 42 chars

Looks like its an improvement to use complex numbers for the points

```
len(set(abs(x-y)for x in A for y in A))==3

```

where A = \[(11+13j), (14+12j), (13+9j), (10+10j)\]

old answer:

```
from itertools import*
len(set((a-c)**2+(b-d)**2 for(a,b),(c,d)in combinations(A,2)))==2

```

Points are specified in any order as a list, eg

```
A = [(11, 13), (14, 12), (13, 9), (10, 10)]

```

# Answer
> 2 votes
## Python (105)

Points are represented by `(x,y)` tuples. Points can be in any order and only accepts squares. Creates a list, `s`, of pairwise (non-zero) distances between the points. There should be 12 distances in total, in two unique groups.

```
def f(p):s=filter(None,[(x-z)**2+(y-w)**2for x,y in p for z,w in p]);return len(s)==12and len(set(s))==2

```

# Answer
> 2 votes
C# -- not exactly short. Abusing LINQ. Selects distinct two-combinations of points in the input, calculates their distances, then verifies that exactly four of them are equal and that there is only one other distinct distance value. Point is a class with two double members, X and Y. Could easily be a Tuple, but meh.

```
var points = new List<Point>
             {
                 new Point( 0, 0 ),
                 new Point( 3, 4 ),
                 new Point( 8, 4 ),
                 new Point( 5, 0 )
              };
var distances = points.SelectMany(
    (value, index) => points.Skip(index + 1),
    (first, second) => new Tuple<Point, Point>(first, second)).Select(
        pointPair =>
        Math.Sqrt(Math.Pow(pointPair.Item2.X - pointPair.Item1.X, 2) +
                Math.Pow(pointPair.Item2.Y - pointPair.Item1.Y, 2)));
return
    distances.Any(
        d => distances.Where( p => p == d ).Count() == 4 &&
                distances.Where( p => p != d ).Distinct().Count() == 1 );

```

# Answer
> 2 votes
**PHP, 82 characters**

---

```
//$x=array of x coordinates
//$y=array of respective y coordinates
/* bounding box of a square is also a square - check if Xmax-Xmin equals Ymax-Ymin */
function S($x,$y){sort($x);sort($y);return ($x[3]-$x[0]==$y[3]-$y[0])?true:false};

//Or even better (81 chars):
//$a=array of points - ((x1,y1), (x2,y2), (x3,y3), (x4,y4))
function S($a){sort($a);return (bool)($a[3][0]-$a[0][0]-abs($a[2][1]-$a[3][1]))};

```

# Answer
> 2 votes
# OCaml + Batteries, 132 characters

```
let q l=match List.group(-)[?List:(x-z)*(x-z)+(y-t)*(y-t)|x,y<-List:l;z,t<-List:l;(x,y)<(z,t)?]with[[s;_;_;_];[d;_]]->2*s=d|_->false

```

(look, Ma, no spaces!) The list comprehension in `q` forms the list of squared norms for each distinct unordered pair of points. A square has four equal sides and two equal diagonals, the squared lengths of the latter being twice the squared lengths of the former. Since there aren't equilateral triangles in the integer lattice the test isn't really necessary, but I include it for completeness.

Tests:

```
q [(0,0);(0,1);(1,1);(1,0)] ;;
- : bool = true
q [(0,0);(2,1);(3,-1);(1,-2)] ;;
- : bool = true
q [(0,0);(1,1);(0,1);(1,0)] ;;
- : bool = true
q [(0,0);(0,2);(3,2);(3,0)] ;;
- : bool = false
q [(0,0);(3,4);(8,4);(5,0)] ;;
- : bool = false
q [(0,0);(0,0);(1,1);(0,0)] ;;
- : bool = false
q [(0,0);(0,0);(1,0);(0,1)] ;;
- : bool = false

```

# Answer
> 2 votes
## \- 33

Translation of the J solution by J B:

```
{4 8 4~#:'=_sqrt+/'_sqr,/x-/:\:x}

```

K suffers here from its reserved words(`_sqr` and `_sqrt`).

Testing:

```
  f:{4 8 4~#:'=_sqrt+/'_sqr,/x-/:\:x}

  f (0 0;0 1;1 1;1 0)
1

  f 4 2#0 0 1 1 0 1 1 0
1

  f 4 2#0 0 3 4 8 4 5 0
0

```

# Answer
> 2 votes
# Mathematica 65 80 69 66

Checks that the number of distinct inter-point distances (not including distance from a point to itself) is 2 and the shorter of the two is not 0.

```
h = Length@# == 2 \[And] Min@# != 0 &[Union[EuclideanDistance @@@ Subsets[#, {2}]]] &;

```

**Usage**

```
h@{{0, 0}, {0, 1}, {1, 1}, {1, 0}}       (*standard square *)
h@{{0, 0}, {2, 1}, {3, -1}, {1, -2}}     (*non-axis aligned square *)
h@{{0, 0}, {1, 1}, {0, 1}, {1, 0}}       (*a different order *)

h@{{0, 0}, {0, 2}, {3, 2}, {3, 0}}       (* rectangle *)
h@{{0, 0}, {3, 4}, {8, 4}, {5, 0}}       (* rhombus   *)
h@{{0, 0}, {0, 0}, {1, 1}, {0, 0}}       (* only 2 distinct points *)
h@{{0, 0}, {0, 1}, {1, 1}, {0, 1}}       (* only 3 distinct points *)

```

> True
> True
> True
> False
> False
> False
> False

N.B.: `\[And]` is a single character in Mathematica.

# Answer
> 2 votes
# Jelly, 8 bytes

```
_Æm×ıḟƊṆ

```

Try it online!

Takes a list of complex numbers as a command line argument. Prints `1` or `0`.

```
_Æm        Subtract mean of points from each point (i.e. center on 0)
   ×ıḟƊ    Rotate 90°, then compute set difference with original.
       Ṇ   Logical negation: if empty (i.e. sets are equal) then 1 else 0.

```

This seems like an enjoyable challenge to revive!

# Answer
> 1 votes
## PHP, ~~161~~ 158 characters

```
function S($a){for($b=4;--$b;)for($c=$b;$c--;){$e=$a[$c][0]-$a[$b][0];$f=$a[$c][1]-$a[$b][1];$d[$g++]=$e*$e+$f*$f;}sort($d);return$d[0]==$d[3]&&$d[4]==$d[5];}

```

Proof (1x1): http://codepad.viper-7.com/ZlBpOB

This is based off of eBuisness's JavaScript answer.

# Answer
> 1 votes
## Haskell (212)

```
import Data.List;j=any f.permutations where f x=(all g(t x)&&s(map m(t x)));t x=zip3 x(drop 1$z x)(drop 2$z x);g(a,b,c)=l a c==sqrt 2*l a b;m(a,b,_)=l a b;s(x:y)=all(==x)y;l(m,n)(o,p)=sqrt$(o-m)^2+(n-p)^2;z=cycle

```

Naive first attempt. Checks the following two conditions for all permutations of the input list of points (where a given permutation represents, say, a clockwise ordering of the points):

* all angles are 90 degrees
* all sides are the same length

Deobfuscated code and tests

```
j' = any satisfyBothConditions . permutations
          --f
    where satisfyBothConditions xs = all angleIs90 (transform xs) &&
                                     same (map findLength' (transform xs))
          --t
          transform xs = zip3 xs (drop 1 $ cycle xs) (drop 2 $ cycle xs)
          --g
          angleIs90 (a,b,c) = findLength a c == sqrt 2 * findLength a b
          --m
          findLength' (a,b,_) = findLength a b
          --s
          same (x:xs) = all (== x) xs
          --l
          findLength (x1,y1) (x2,y2) = sqrt $ (x2 - x1)^2 + (y2 - y1)^2

main = do print $ "These should be true"
          print $ j [(0,0),(0,1),(1,1),(1,0)]
          print $ j [(0,0),(2,1),(3,-1),(1,-2)]
          print $ j [(0,0),(1,1),(0,1),(1,0)]
          print $ "These should not"
          print $ j [(0,0),(0,2),(3,2),(3,0)]
          print $ j [(0,0),(3,4),(8,4),(5,0)]
          print $ "also testing j' just in case"
          print $ j' [(0,0),(0,1),(1,1),(1,0)]
          print $ j' [(0,0),(2,1),(3,-1),(1,-2)]
          print $ j' [(0,0),(1,1),(0,1),(1,0)]
          print $ j' [(0,0),(0,2),(3,2),(3,0)]
          print $ j' [(0,0),(3,4),(8,4),(5,0)]

```

# Answer
> 1 votes
Clojure, 159 chars.

```
user=> (def squares
         [[[0,0] [0,1] [1,1]  [1,0]]   ; standard square
         [[0,0] [2,1] [3,-1] [1,-2]]  ; non-axis-aligned square
         [[0,0] [1,1] [0,1]  [1,0]]]) ; different order
#'user/squares
user=> (def non-squares
         [[[0,0] [0,2] [3,2] [3,0]]    ; rectangle
          [[0,0] [3,4] [8,4] [5,0]]])  ; rhombus
#'user/non-squares
user=> (defn norm
         [x y]
         (reduce + (map (comp #(* % %) -) x y)))
#'user/norm
user=> (defn square?
         [[a b c d]]
         (let [[x y z] (sort (map #(norm a %) [b c d]))]
           (and (= x y) (= z (* 2 x)))))
#'user/square?
user=> (every? square? squares)
true
user=> (not-any? square? non-squares)
true

```

Edit: To also explain a little bit.

* First define a norm which basically gives the distance between two given points.
* Then calculate the distance of the first point to the other three points.
* Sort the three distances. (This allows any order of the points.)
* The two shortest distances must be equal to be a square.
* The third (longest) distance must be equal to the square root of the sum of the squares of the short distances by the theorem of Pythagoras.

(Note: the square rooting is not needed and hence in the code saved above.)

# Answer
> 1 votes
# JavaScript 144 characters

Mathematically equal to J Bs answer. It generates the 6 lengths and assert that the 2 greatest are equal and that the 4 smallest are equal. Input must be an array of arrays.

```
function F(a){d=[];g=0;for(b=4;--b;)for(c=b;c--;d[g++]=(e*e+f*f)/1e6)e=a[c][0]-a[b][0],f=a[c][1]-a[b][1];d.sort();return d[0]==d[3]&&d[4]==d[5]} //Compact function
testcases=[
[[0,0],[1,1],[1,0],[0,1]],
[[0,0],[999,999],[999,0],[0,999]],
[[0,0],[2,1],[3,-1],[1,-2]],
[[0,0],[0,2],[3,2],[3,0]],
[[0,0],[3,4],[8,4],[5,0]],
[[0,0],[0,0],[1,1],[0,0]],
[[0,0],[0,0],[1,0],[0,1]]
]
for(v=0;v<7;v++){
    document.write(F(testcases[v])+"<br>")
}

function G(a){ //Readable version
    d=[]
    g=0
    for(b=4;--b;){
        for(c=b;c--;){
            e=a[c][0]-a[b][0]
            f=a[c][1]-a[b][1]
            d[g++]=(e*e+f*f)/1e6 //The division tricks the sort algorithm to sort correctly by default method.
        }
    }
    d.sort()
    return (d[0]==d[3]&&d[4]==d[5])
}

```

# Answer
> 1 votes
## Scala (146 characters)

```
def s(l:List[List[Int]]){var r=Set(0.0);l map(a=>l map(b=>r+=(math.pow((b.head-a.head),2)+math.pow((b.last-a.last),2))));print(((r-0.0).size)==2)}

```

# Answer
> 1 votes
### C#, 107 characters

```
return p.Distinct().Count()==4&&
(from a in p from b in p select (a-b).LengthSquared).Distinct().Count()==3;

```

Where points is List of Vector3D containing the points.

Computes all distances squared between all points, and if there are exactly three distinct types (must be 0, some value a, and 2\*a) and 4 distinct points then the points form a square.

# Answer
> 1 votes
## JavaScript 1.8, 112 characters

Update: saved 2 characters by folding the array comprehensions together.

```
function i(s)(p=[],[(e=x-a,f=y-b,d=e*e+f*f,p[d]=~~p[d]+1)for each([a,b]in s)for each([x,y]in s)],/8,+4/.test(p))

```

Another reimplementation of J B's answer. Exploits JavaScript 1.7/1.8 features (expression closures, array comprehensions, destructuring assignment). Also abuses `~~` (double bitwise not operator) to coerce `undefined` to numeric, with array-to-string coercion and a regexp to check that the length counts are `[4, 8, 4]` (it assumes that exactly 4 points are passed). The abuse of the comma operator is an old obfuscated C trick.

Tests:

```
function assert(cond, x) { if (!cond) throw ["Assertion failure", x]; }

let text = "function i(s)(p=[],[(e=x-a,f=y-b,d=e*e+f*f,p[d]=~~p[d]+1)for each([a,b]in s)for each([x,y]in s)],/8,+4/.test(p))"
assert(text.length == 112);
assert(let (source = i.toSource()) (eval(text), source == i.toSource()));

// Example squares:
assert(i([[0,0],[0,1],[1,1],[1,0]]))    // standard square
assert(i([[0,0],[2,1],[3,-1],[1,-2]]))  // non-axis-aligned square
assert(i([[0,0],[1,1],[0,1],[1,0]]))    // different order

// Example non-squares:
assert(!i([[0,0],[0,2],[3,2],[3,0]]))  // rectangle
assert(!i([[0,0],[3,4],[8,4],[5,0]]))  // rhombus
assert(!i([[0,0],[0,0],[1,1],[0,0]]))  // only 2 distinct points
assert(!i([[0,0],[0,0],[1,0],[0,1]]))  // only 3 distinct points

// Degenerate square:
assert(!i([[0,0],[0,0],[0,0],[0,0]]))   // we reject this case

```

# Answer
> 1 votes
## GoRuby - 66 characters

```
f=->a{z=12;a.pe(2).m{|k,l|(k-l).a}.so.go{|k|k}.a{|k,l|l.sz==z-=4}}

```

expanded:

```
f=->a{z=12;a.permutation(2).map{|k,l|(k-l).abs}.sort.group_by{|k|k}.all?{|k,l|l.size==(z-=4)}}

```

Same algorithm as J B's answer.

Test like:

```
p f[[Complex(0,0), Complex(0,1), Complex(1,1), Complex(1,0)]]

```

Outputs `true` for true and blank for false

# Answer
> 1 votes
**Python 97 (without complex points)**

```
def t(p):return len(set(p))-1==len(set([pow(pow(a-c,2)+pow(b-d,2),.5)for a,b in p for c,d in p]))

```

This will take lists of point tuples in \[(x,y),(x,y),(x,y),(x,y)\] in any order, and can handle duplicates, or the wrong number of points. It does NOT require complex points like the other python answers.

You can test it like this:

```
S1 = [(0,0),(1,0),(1,1),(0,1)]   # standard square
S2 = [(0,0),(2,1),(3,-1),(1,-2)] # non-axis-aligned square
S3 = [(0,0),(1,1),(0,1),(1,0)]   # different order
S4 = [(0,0),(2,2),(0,2),(2,0)]   #
S5 = [(0,0),(2,2),(0,2),(2,0),(0,0)] #Redundant points

B1 = [(0,0),(0,2),(3,2),(3,0)]  # rectangle
B2 = [(0,0),(3,4),(8,4),(5,0)]  # rhombus
B3 = [(0,0),(0,0),(1,1),(0,0)]  # only 2 distinct points
B4 = [(0,0),(0,0),(1,0),(0,1)]  # only 3 distinct points
B5 = [(1,1),(2,2),(3,3),(4,4)]  # Points on the same line
B6 = [(0,0),(2,2),(0,2)]        # Not enough points

def tests(f):
    assert(f(S1) == True)
    assert(f(S2) == True)
    assert(f(S3) == True)
    assert(f(S4) == True)
    assert(f(S5) == True)

    assert(f(B1) == False)
    assert(f(B2) == False)
    assert(f(B3) == False)
    assert(f(B4) == False)
    assert(f(B5) == False)
    assert(f(B6) == False)

def t(p):return len(set(p))-1==len(set([pow(pow(a-c,2)+pow(b-d,2),.5)for a,b in p for c,d in p]))

tests(t)

```

This will take a little explaining, but the overall idea is that there are only three distances between the points in a square (Side, Diagonal, Zero(point compared to itself)):

```
def t(p):return len(set(p))-1==len(set([pow(pow(a-c,2)+pow(b-d,2),.5)for a,b in p for c,d in p]))

```
* for a list p of tuples (x,y)
* Remove duplicates using set(p) and then test the length
* Get every combination of points (a,b in p for c,d in p)
* Get list of the distance from every point to every other point
* Use set to check there are only three unique distances -- Zero (point compared to itself) -- Side length -- Diagonal length

To save code characters I am:

* using a 1 char function name
* using a 1 line function definition
* Instead of checking the number of unique points is 4, I check that it is -1 the different point lengths (saves ==3==)
* use list and tuple unpacking to get a,b in p for c,d in p, instead of using a\[0\],a\[1\]
* uses pow(x,.5) instead of including math to get sqrt(x)
* not putting spaces after the )
* not putting a leading zero on the float

I fear someone can find a test case that breaks this. So please do and Ill correct. For instance the fact I just check for three distances, instead of doing an abs() and checking for side length and hypotenuse, seems like an error.

First time I've tried code golf. Be kind if I've broken any house rules.

# Answer
> 1 votes
# Python, 66

Improving paperhorse's answer from 76 to 66:

```
def U(A):c=sum(A)/4;d=A[0]-c;return{d+c,c-d,d*1j+c,c-d*1j}==set(A)

```

# Answer
> 1 votes
# Python 2, 49 bytes

```
lambda l:all(1j*z+(1-1j)*sum(l)/4in l for z in l)

```

Try it online!

Takes a list of four complex numbers as input. Rotates each point 90 degrees around the average, and checks that each resulting point is in the original list.

Same length (though shorter in Python 3 using `{*l}`).

```
lambda l:{1j*z+(1-1j)*sum(l)/4for z in l}==set(l)

```

Try it online!

# Answer
> 1 votes
# Wolfram Language (Mathematica), ~~32~~ 31 bytes

```
Tr[#^2]==Tr[#^3]==0&[#-Mean@#]&

```

Try it online!

Takes a list of points represented by complex numbers, calculates the second and third central moment, and checks that both are zero.

Un-golfed:

```
S[p_] := Total[(p - Mean[p])^2] == Total[(p - Mean[p])^3] == 0

```

or

```
S[p_] := CentralMoment[p, 2] == CentralMoment[p, 3] == 0

```

# proof

This criterion works on the entire complex plane, not just on the Gaussian integers.

1. First, we note that the central moments do not change when the points are translated together. For a set of points

```
P = Table[c + x[i] + I*y[i], {i, 4}]

```

the central moments are all independent of `c` (that's why they are called *central*):

```
{FreeQ[FullSimplify[CentralMoment[P, 2]], c], FreeQ[FullSimplify[CentralMoment[P, 3]], c]}
(*    {True, True}    *)

```
2. Second, the central moments have a simple dependence on overall complex scaling (scaling and rotation) of the set of points:

```
P = Table[f * (x[i] + I*y[i]), {i, 4}];
FullSimplify[CentralMoment[P, 2]]
(*    f^2 * (...)    *)
FullSimplify[CentralMoment[P, 3]]
(*    f^3 * (...)    *)

```

This means that if a central moment is zero, then scaling and/or rotating the set of points will keep the central moment equal to zero.
3. Third, let's prove the criterion for a list of points where the first two points are fixed:

```
P = {0, 1, x[3] + I*y[3], x[4] + I*y[4]};

```

Under what conditions are the real and imaginary parts of the second and third central moments zero?

```
C2 = CentralMoment[P, 2] // ReIm // ComplexExpand // FullSimplify;
C3 = CentralMoment[P, 3] // ReIm // ComplexExpand // FullSimplify;
Solve[Thread[Join[C2, C3] == 0], {x[3], y[3], x[4], y[4]}, Reals] // FullSimplify
(*    {{x[3] -> 0, y[3] -> -1, x[4] -> 1, y[4] -> -1},
       {x[3] -> 0, y[3] -> 1, x[4] -> 1, y[4] -> 1},
       {x[3] -> 1/2, y[3] -> -1/2, x[4] -> 1/2, y[4] -> 1/2},
       {x[3] -> 1/2, y[3] -> 1/2, x[4] -> 1/2, y[4] -> -1/2},
       {x[3] -> 1, y[3] -> -1, x[4] -> 0, y[4] -> -1},
       {x[3] -> 1, y[3] -> 1, x[4] -> 0, y[4] -> 1}}    *)

```

All of these six solutions represent squares:  Therefore, the only way that a list of points of the form `{0, 1, x[3] + I*y[3], x[4] + I*y[4]}` can have zero second and third central moments is when the four points form a square.

Due to the translation, rotation, and scaling properties demonstrated in points 1 and 2, this means that any time the second and third central moments are zero, we have a square in some translation/rotation/scaling state. ∎

# generalization

The k-th central moment of a regular n-gon is zero if k is not divisible by n. Enough of these conditions must be combined to make up a sufficient criterion for detecting n-gons. For the case n=4 it was enough to detect zeros in k=2 and k=3; for detecting, e.g., hexagons (n=6) it may be necessary to check k=2,3,4,5 for zeros. I haven't proved the following, but suspect that it will detect any regular n-gon:

```
isregularngon[p_List] :=
  And @@ Table[PossibleZeroQ[CentralMoment[p, k]], {k, 2, Length[p] - 1}]

```

The code challenge is essentially this code specialized for length-4 lists.

# Answer
> 0 votes
## J, <sup>31 29 27</sup> 26

```
3=[:#[:~.[:,([:+/*:@-)"1/~

```

checks if the 8 smallest distances between the points are the same. checks if there are exactly three kinds of distances between the points (zero, side length and diagonal length).

```
f 4 2 $ 0 0 2 1 3 _1 1 _2
1
f 4 2 $ 0 0 0 2 3 2 3 0
0

```

`4 2 $` is a way of writing an array in J.

# Answer
> 0 votes
## Smalltalk for 106 characters

```
s:=Set new.
p permutationsDo:[:e|s add:((e first - e second) dotProduct:(e first - e third))].
s size = 2

```

where p is a collection of points, e.g.

```
p := { 0@0. 2@1. 3@ -1. 1@ -2}. "twisted square"

```

I think the math is sound...

# Answer
> 0 votes
## Mathematica, 123 characters (but you can do better):

```
Flatten[Table[x-y,{x,a},{y,a}],1]
Sort[DeleteDuplicates[Abs[Flatten[Table[c.d,{c,%},{d,%}]]]]]
%[[1]]==0&&%[[3]]/%[[2]]==2

```

Where 'a' is the input in Mathematica list form, eg: `a={{0,0},{3,4},{8,4},{5,0}}`

The key is to look at the *dot* products between all the vectors and note that they must have exactly three values: 0, x, and 2\*x for some value of x. The dot product checks both perpendicularity AND length in one swell foop.

I know there are Mathematica shortcuts that can make this shorter, but I don't know what they are.

# Answer
> 0 votes
Haskell, "wc -c" reports 110 characters. Does not check that the input has 4 elements.

```
import Data.List
k [a,b]=2*a==b
k _=0<1
h ((a,b):t)=map (\(c,d)->(a-c)^2+(b-d)^2) t++h t
h _=[]
j=k.nub.sort.h

```

I tested on

```
test1 = [(0,0),(3,4),(-4,3),(-1,7)] -- j test1 is True
test2 = [(0,0),(3,4),(-3,4),(0,8)]  -- j test2 is False

```

# Answer
> 0 votes
**Smalltalk** Squeak 4.x flavour, **91** char in the form of a block:

```
[:p||b|b:=Bag new.p do:[:x|p do:[:y|b add:(x dist:y)]].b valuesAndCounts asSet={4. 8}asSet]

```

Test it with:

```
{
"Example squares:"
    {0@ 0. 0@ 1. 1@ 1. 1@ 0}. " standard square"
    {0@ 0. 2@ 1. 3@ -1. 1@ -2}.  " non-axis-aligned square"
    {0@ 0. 1@ 1. 0@ 1. 1@ 0}. " different order"
"Example non-squares:"
    {0@ 0. 0@ 2. 3@ 2. 3@ 0}.  " rectangle"
    {0@ 0. 3@ 4. 8@ 4. 5@ 0}.  " rhombus"
    {0@ 0. 0@ 0. 1@ 1. 0@ 0}.  " only 2 distinct points"
    {0@ 0. 0@ 0. 1@ 0. 0@ 1}.   " only 3 distinct points"
}
collect:
[:p||b|b:=Bag new.p do:[:x|p do:[:y|b add:(x dist:y)]].b valuesAndCounts asSet={4. 8}asSet].

```

It's a variant of #(4 8 4)

* Bag is collecting the pairs ( interdistance -\> number\_of\_occurences )
* valuesAndCounts send the bag contents (a Dictionary)
* asSet apply to the values in the dictionary (number\_of\_occurences)

A degenerated (0,0)\*4 is not considered as a valid square.

# Answer
> 0 votes
## Python, 67 chars, complex and distance-based, and no false positives ...

```
S=lambda A:len(set(A))-1==len(set([abs(K-J)for K in A for J in A]))

```

(I hope;-).

The sqrt in abs() may cause some roundoff problems, but probably not - abs((K-J)\**2) is more reliable but compresses domain as numbers can approach to within a few digits of double precision limits.

Combines Jagu's answer (len(set(Points))-1==len(set(distances)) - brilliant IMNSHO - which drops to 85 as outer pow(...,.5) calls are unnecessary, and (...)\**2 is shorter anyway) and user932's (lambda instead of def).

Neither as elegant, nor as short, as paperhorse's rotation as modified by WolframH.

I had a solution that put only the squares of the side and diagonal lengths in the set L and tested "len(L)==2 and max(set(L))/2 in L" but it never went much below 90 chars.

Tests (all should print True):

```
print S([(0+1j),(1+0j),(0+0j),(1+1j)])
print S([(0+0j),(2+1j),(3-1j),(1-2j)])
print S([(0+0j),(1+1j),(0+1j),(1+0j)])
print S([(1000+1j),(-1+1000j),(1-1000j),(-1000-1j)])

print not S([(0+1j),(0-1j),(0+0j),(0+1j)])
print not S([(999+1j),(-1+1000j),(1-1000j),(-1000-1j)])
print not S([(0+1j),(1+0j),(0+0j),(0-1j)])
print not S([(0+0j),(0+2j),(3+2j),(3+0j)])
print not S([(0+0j),(3+4j),(8+4j),(5+0j)])
print not S([(0+0j),(0+0j),(1+1j),(0+0j)])
print not S([(0+0j),(0+0j),(1+0j),(0+1j)])

```

# Answer
> 0 votes
# C (gcc), ~~159~~ 141 bytes

```
g;f(a,e)_Complex*a,e;{e=(*a+a[1]+a[2]+a[3])/4;for(g=0;a[g]-=e,g<4&cabs(a[g])==cabs(*a)&!fmod(carg(a[g++])-carg(*a),atan(1)););return g>4;}

```

-18 thanks to @G.Sliepen.

Try it online!

After subtracting the center point, checks that the absolute values of each complex number are equal, and that all the arguments are equal modulo π/2.

# Answer
> 0 votes
# Stax, 14 bytes

```
┐cÜ╦┤╖ó#┬├{%ì↔

```

Run and debug it

* Calculate the square of the distance between each pair of points. This yields 6 numbers.
* "Reduce" the 6-array by dividing each element by the array's gcd.
* The shape is a square iff the product of the reduced array is 4.

```
2S{M{:sJF+m square of the distance between each pair of points
:_          "reduce"; divide each by the gcd of the array
:*4=        does the product of the array equal 4?

```

Run this one

# Answer
> 0 votes
Its not exactly shortest, but I dont think anyone proposed this strategy.

Scala, 152

```
def f(p:Seq[(Double,Double)])={p.map(b=>{math.sqrt(math.pow((p.map(_._1).sum/p.size)-b._1,2)+math.pow((p.map(_._2).sum/p.size)-b._2,2))}).toSet.size==1}

```

Basically we calculate average of all points across each axis to find presumably center of the square, and then validate that center has same distance from all points.

Properly formatted solution:

```
type Point = (Double, Double)
def isSquare(points: Seq[Point]): Boolean = {
  //finds center point along an axis
  def avg(axis: Seq[Double]): Double = {
    axis.sum / axis.size
  }

  //finds distance between 2 points
  def distance(a: Point, b: Point): Double = {
    val x = a._1 - b._1
    val y = a._2 - b._2
    math.sqrt((x * x) + (y * y))
  }

  //point in the center of square
  val center = (
    avg(points.map(_._1)),
    avg(points.map(_._2)))

  //find a set of distances from center to all points
  //and make sure only one is in the set
  points.map(distance(center, _)).toSet.size == 1
}

```

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


title: Tips for golfing in Smalltalk

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

> Smalltalk is a purely object-oriented language created by Alan Kay. The two links are GNU Smalltalk and a general Smalltalk page respectively. You do not have to pay attention on this "spoiler".

# Answer
## Use the `;` operator to refer to the previous object

There is a convenient shorthand in Smalltalk used to refer to the previous object. Say we want to add 3 items to the set x.

```
x:=Set new
x add:5.x add:7.x add:'foo'

```

However, we can save a few bytes by using the ; operator:

```
x:=Set new
x add:5;add:7;add:'foo'

```
> 7 votes

---
Tags: code-golf, tips
---


title: Auto BATCH golfer

text:
# Question
Title: Auto BATCH golfer
I love BATCH, despite its shocking lack of functional commands, despite even due to its lack of non-integer support. Why? Because this works:

```
SET var=SET
%var% i=0

```

This would evaluate to:

```
SET var=SET
SET i=0

```

Fantastic, isn't it? I've used this technique in a BATCH program before, because it saves bytes!

Your challenge, should you accept it, would be to "golf" BATCH programs in this way. You are to decrease the byte size of an input BATCH program by including `SET` statements that would evaluate to portions of the program, and in no other way modify the program. (This disallows, say, renaming a variable name to something shorter. Keep in mind that BATCH, asides from variables, is case insensitive.) Your score is calculated as thus:

```
score = # of characters in your program + 5*(net result bytes in test cases below)

```

I reserve the right to add more test cases, so as to discourage working to optimize the program for the test cases.

For the sake of this challenge, your `SET` statements cannot contain control characters (`|`, `<`, `>`, `%`) or linebreaks. You may not modify the code other than to move pieces of code inside a set statement. (That is, you may not remove unnecessary whitespace, replace `EQU` with `==`, etc.) We will assume that the lines end with `\n`.

## Test cases

Each test case is in a separate code block, and each test case is self-contained, meaning you should golf only assuming what's given within it. (I.e., if you `SET d=SET` in one program, that statement will not be automatically given to any other program). Each example result can be found after each test case. There is a line between test cases.

```
@ECHO OFF
SET increment=10
:loop
IF %increment% EQU 0 GOTO end
ECHO %increment%
SET /A %increment%-=1
GOTO loop
:end
EXIT
```

---

```
@ECHO OFF
SET /p INPUT=Enter input here:
SET R=%1
ECHO Last char of input here: %R:~-1%
```

---

```
@ECHO OFF
SET increment=10
:e
GOTO f
ECHO f
:f
GOTO g
ECHO g
:g
GOTO h
ECHO h
:h
GOTO i
ECHO i
:i
GOTO j
ECHO j
:j
IF 3==4 ( ECHO 4 ) ELSE ( ECHO 5 )
IF 5==3 ( GOTO l ) ELSE ( GOTO k )
:k
ECHO Done.
ECHO BATCH OUT!!
EXIT
:l
GOTO g
```

---

```
ECHO Hello, Hello, Hello, hello, hello, Hello, Hello!, hello, ello!, Lello.
```

---

Example outputs:

```
@ECHO OFF
SET increment=10
:loop
IF %increment% EQU 0 GOTO end
ECHO %increment%
SET /A %increment%-=1
GOTO loop
:end
EXIT
```
(0 bytes saved)
```
@ECHO OFF
SET %i%= input here:
SET /p INPUT=Enter%i%
SET R=%1
ECHO Last char of %i%%R:~-1%
```
(3 bytes gained)
```
@ECHO OFF
SET increment=10
SET g=GOTO
SET e=ECHO
:e
%g%f
%e%f
:f
%g%g
%e%g
:g
%g%h
%e%h
:h
%g%i
%e%i
:i
%g%j
%e%j
:j
IF 3==4 ( %e%4 ) ELSE ( %e%5 )
IF 5==3 ( %g%l ) ELSE ( %g%k )
:k
%e%Done.
%e%BATCH OUT!!
EXIT
:l
%g%g
```
(10 chars saved)
```
SET %h%=ello,
ECHO H%h% H%h% H%h% h%h% h%h% H%h% Hello!, h%h% ello!, Lello.
```
(1 character saved)

# Answer
# Java 8, Java 10, ~~3884~~ 799/795 program + 484 output = ~~4368~~ 1283/1279 total

There are two limitations of this code:

* It assumes that variables from A to Z are free. (uppercase)
* It assumes that there are no more than 27 substitutions.
* Oh, and because Scanner doesn't quite cut it, empty input dumps out stacktrace.

But hey - there is a pro!

* Outputs best code. Always.

The code manages to perform better than examples provided by challenge author.

This golfed version has been made by Kevin.

## Java 8

```
c->{List<String>S=new Stack();HashMap<String,Integer>h=new HashMap(),s=new HashMap();int v=65,l=c.length(),b,e;do{for(b=0,l=c.length(),s.clear();b!=l;b++)for(e=b;++e<=l;)S.add(c.substring(b,e));S.removeIf(t->t.length()<5|t.matches(".*[\n|<%>].*"));S.forEach(t->h.merge(t,1,Integer::sum));S.clear();h.entrySet().removeIf(t->t.getValue()==1);String Y=c;int L=l;char V=(char)v;h.forEach((k,x)->{String i=Y,t;for(int j,I,q;i.contains(k);i=t+"%"+V+"%"+i.substring(j+k.length(),i.length())){for(I=-1,t=i.substring(q=0,j=i.indexOf(k));(I=t.indexOf("%",++I))>=0;q++);if(q%2>0)return;}i="SET "+V+"="+k+"\n"+i;if(i.length()<L)s.put(i,L-i.length());});h.clear();v++;c=s.isEmpty()?c:s.entrySet().stream().max((x,y)->x.getValue()>y.getValue()?1:-1).get().getKey();}while(l>c.length());return c;}

```

**Try it online!**

## Java 10

```
c->{var S=new Stack<String>();HashMap<String,Integer>h=new HashMap(),s=new HashMap();int v=65,l=c.length(),b,e;do{for(b=0,l=c.length(),s.clear();b!=l;b++)for(e=b;++e<=l;)S.add(c.substring(b,e));S.removeIf(t->t.length()<5|t.matches(".*[\n|<%>].*"));S.forEach(t->h.merge(t,1,(x,y)->x+y));S.clear();h.entrySet().removeIf(t->t.getValue()==1);var Y=c;int L=l;var V=(char)v;h.forEach((k,x)->{String i=Y,t;for(int j,I,q;i.contains(k);i=t+"%"+V+"%"+i.substring(j+k.length(),i.length())){for(I=-1,t=i.substring(q=0,j=i.indexOf(k));(I=t.indexOf("%",++I))>=0;q++);if(q%2>0)return;}i="SET "+V+"="+k+"\n"+i;if(i.length()<L)s.put(i,L-i.length());});h.clear();v++;c=s.isEmpty()?c:s.entrySet().stream().max((x,y)->x.getValue()>y.getValue()?1:-1).get().getKey();}while(l>c.length());return c;}

```

**Try it online!**.

# Original version

It's not golfed at all, I just wanted to have some fun, not to suffer. If you, dear reader, would like to golf this answer, please do it.

```
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Predicate;

public class Main {
	List<String> substrings = new ArrayList<String>();
	HashMap<String, Integer> hm = new HashMap<String, Integer>();
	HashMap<String, Integer> scores = new HashMap<String, Integer>();

	private int v1 = 65;

	public static String rfos(String inputString, String stringToReplace,
	        String stringToReplaceWith) {

	    int length = stringToReplace.length();
	    int inputLength = inputString.length();

	    int startingIndexofTheStringToReplace = inputString.indexOf(stringToReplace);

	    if(count(inputString.substring(0, startingIndexofTheStringToReplace), "%") % 2 == 1)
	    	return null;

	    String finalString = inputString.substring(0, startingIndexofTheStringToReplace) + stringToReplaceWith
	            + inputString.substring(startingIndexofTheStringToReplace + length, inputLength);

	    return finalString;

	}

	public static int count(String text, String find) {
        int index = 0, count = 0, length = find.length();
        while( (index = text.indexOf(find, index)) != -1 ) {
                index += length; count++;
        }
        return count;
	}

	private String process(String program) {
		int begin = 0, end, il = program.length();

		scores.clear();

		while(begin != program.length()) {
			for(end = begin + 1; end < program.length() + 1; end++)
				substrings.add(program.substring(begin, end));
			begin++;
		}

		substrings.removeIf(new Predicate<String>() {
			@Override
			public boolean test(String arg0) {
				return arg0.length() <= 4 || arg0.contains("\n")
						|| arg0.contains("|")
						|| arg0.contains("<")
						|| arg0.contains("%")
						|| arg0.contains(">");
			}
		});

		substrings.forEach(new Consumer<String>() {

			@Override
			public void accept(String t) {
				if(hm.containsKey(t)) {
					hm.replace(t, hm.get(t) + 1);
				} else {
					hm.put(t, 1);
				}
			}

		});

		substrings.clear();

		hm.entrySet().removeIf(new Predicate<Map.Entry<String, Integer>>() {

			@Override
			public boolean test(Map.Entry<String, Integer> t) {
				return t.getValue() == 1;
			}

		});

		hm.forEach(new BiConsumer<String, Integer>() {

			@Override
			public void accept(String arg0, Integer arg1) {
				String iteration = program;
				boolean between = false;
				while(iteration.contains(arg0)) {
					iteration = rfos(iteration, arg0, "%" + Character.toString((char) v1) + "%");
					if(iteration == null)
						return;
				}
				iteration = "SET " + Character.toString((char) v1) + "=" + arg0 + "\n" + iteration;
				if(iteration.length() < program.length())
					scores.put(iteration, program.length() - iteration.length());
			}

		});

		hm.clear();
		v1++;

		if(scores.isEmpty())
			return program;
		else
			return scores.entrySet().stream().max((entry1, entry2) -> entry1.getValue() > entry2.getValue() ? 1 : -1).get().getKey();
	}

	public static void main(String[] args) {
		Main processor = new Main();
		int genid = 0, before = 0, after = 0;
		String currentCode = new Scanner(System.in).useDelimiter("\\Z").next();

		System.out.println("Calculating first generation...");

		do {
			String cc = processor.process(currentCode);
			before = currentCode.length();
			after = cc.length();

			currentCode = cc;

			if(before > after) {
				System.out.println("Generation " + genid++);
				System.out.println(before + " -> " + after);
				System.out.println("***\n" + cc + "\n***");
			} else {
				System.out.println("Generation FAIL " + genid++);
				System.out.println(before + " -> " + after);
				System.out.println("***\n" + cc + "\n***");
			}
		} while(before > after);

	}

}

```

Example output:

```
SET B=GOTO
SET A=ECHO
@%A%OFF
SET increment=10
:e
%B%f
%A%f
:f
%B%g
%A%g
:g
%B%h
%A%h
:h
%B%i
%A%i
:i
%B%j
%A%j
:j
IF 3==4 ( %A%4 ) ELSE ( %A%5 )
IF 5==3 ( %B%l ) ELSE ( %B%k )
:k
%A%Done.
%A%BATCH OUT!!
EXIT
:l
%B%g

```

**Try it online!**
> 6 votes

---
Tags: string, metagolf
---