title: How many peaks in my mountain range?

text:
# Question
Title: How many peaks in my mountain range?
A list of positive integers can be visualized as a quantized mountain range where each list entry represents the height of one vertical section of the mountains.

For example, the list

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

```

can become the range

```
      x
    x x
   xxxxx   xxx   x
 xxxxxxxx xxxxxx x
xxxxxxxxxxxxxxxxxx

```

(Less poetic people might call this a bar chart, but I digress.)

The question in this challenge is: **How many peaks are in the mountain range of some arbitrary list?** Essentially, how many local maxima are in the list?

A peak is defined as a contiguous section of one or more columns of the mountain range that are all equal in height, where the columns immediately to the left and the right are lower in height.

It's easy to visually tell that the example has four peaks at these parenthesized locations:

```
1, 2, 2, 3, (4), 3, (5), 3, 2, 1, 2, (3, 3, 3), 2, 2, 1, (3)

```

Note how the `(3, 3, 3)` plateau section counts as a peak because it is a contiguous set of columns equal in height, higher than its neighboring columns.

The last `(3)` counts as a peak as well because, for the purposes of this challenge, **we'll define the left neighbor of the leftmost column and the right neighbor of the rightmost column to both be height zero.**

This means that a list with only one value, for example `1, 1, 1`, can be interpreted as `0, 1, 1, 1, 0`, and thus has one peak, not none: `0, (1, 1, 1), 0`.

The only list with zero peaks is the empty list.

# Challenge

Write a function or program that takes in an arbitrary list of positive integers and prints or returns the number of peaks in the corresponding mountain range.

**The shortest code in bytes wins.** Tiebreaker is earlier post.

# Test Cases

```
Input List -> Output Peak Count

```

```
[empty list] -> 0
1, 1, 1 -> 1
1, 2, 2, 3, 4, 3, 5, 3, 2, 1, 2, 3, 3, 3, 2, 2, 1, 3 -> 4
1 -> 1
1, 1 -> 1
2, 2, 2, 2, 2 -> 1
90 -> 1
2, 1, 2 -> 2
5, 2, 5, 2, 5 -> 3
2, 5, 2, 5, 2, 5, 2 -> 3
1, 2, 3, 4 -> 1
1, 2, 3, 4, 1, 2 -> 2
1, 3, 5, 3, 1 -> 1
7, 4, 2, 1, 2, 3, 7 -> 2
7, 4, 2, 1, 2, 1, 2, 3, 7 -> 3
1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2 -> 10
1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1 -> 10
2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2 -> 10
1, 3, 3, 3, 1, 3, 3, 1, 3, 1, 3, 3, 3, 3, 1 -> 4
12, 1, 2, 1, 2, 3, 3, 3, 2, 4, 4, 4, 1, 5, 5, 4, 7, 9 -> 6
87, 356, 37673, 3676, 386, 909, 909, 909, 909, 454, 909, 909 -> 3
87, 356, 37673, 3676, 386, 909, 909, 909, 909, 454, 909, 908, 909 -> 4

```

# Answer
# Pyth, 18 bytes

```
su_>VGtG2eMr++ZQZ8

```

Based on @PeterTaylor's repeated greater than solution, but with a twist.

`++ZQZ`: Add zeros on both sides.

`eMr ... 8`: Remove repeats.

`u ... 2 ...`: Apply the following twice:

`>VGTG`: Map each pair of numbers to whether they are in decreasing order.

`_`: And reverse.

A 1 in the output corresponds to a `1, 0` in prior step, which corresponds to `a < b > c` in the input due to the reversal.

`s`: Sum (and print)
> 2 votes

# Answer
## CJam (32 26 24 21 bytes)

```
0q~0]e`1f=2ew::>2,/,(

```

Expected input is space-separated numbers.

Online demo ; full test suite (expected output is a `1` per test case).

Thanks to Martin for informing me that the current version of CJam improves one of the operators used, saving 2 chars; and for a further 3-char saving.

### Dissection

Two phases: deduplicate, then identify local maxima in each set of three.

```
0q~0]      e# Put the input in an array wrapped in [0 ... 0]
e`1f=      e# Use run-length encoding to deduplicate
2ew::>     e# Map [a b c ...] to [(a>b) (b>c) ...]
2,/        e# Split on [0 1], which since we've deduplicated occurs when (a<b) (b>c)
,(         e# Count the parts and decrement to give the number of [0 1]s

```
> 10 votes

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

```
m=>m.map(n=>{h=n<p?h&&!++r:n>p||h;p=n},r=h=p=0)|r+h

```

## Explanation

Takes an array of numbers

```
m=>
  m.map(n=>{       // for each number n in the mountain range
      h=
        n<p?       // if the number is less than the previous number:
          h&&      // if the previous number was greater than the number before it
          !++r     // increment the number of peaks and set h to 0
        :n>p||h;   // if the number is greater than the previous number, set h to 1
      p=n          // set p to the current number
    },
    r=             // r = number of peaks
    h=             // h = 1 if the previous number was higher than the one before it
    p=0            // p = previous number
  )|r+h            // return the output (+ 1 if the last number was higher)

```

## Test

```
var solution = m=>m.map(n=>{h=n<p?h&&!++r:n>p||h;p=n},r=h=p=0)|r+h
```

```
Mountain Range (space-separated) = <input type="text" id="input" value="87 356 37673 3676 386 909 909 909 909 454 909 908 909" />
<button onclick="result.textContent=solution(input.value.split(' ').map(n=>+n))">Go</button>
<pre id="result"></pre>
```
> 7 votes

# Answer
## Pyth, ~~25~~ 23 bytes

```
L._M-M.:b2s<R0y-y+Z+QZZ

```

Explanation:

```
L              y = lambda b:
  ._M -M .:          signs of subsets
           b          of b
           2          of length 2. That is, signs of differences.

s <R              number of elements less than
     0              0 in
     y -            y of ... with zeroes removed
         y +          y of
             Z        the input with zeroes tacked on both sides
             + Q Z
       Z

```
> 5 votes

# Answer
# Julia, 66

```
x->(y=diff([0;x;0]);y=y[y.!=0];sum((y[1:end-1].>0)&(y[2:end].<0)))

```

Pad, differentiate: `y=diff([0;x;0])`.
Ignore the plateaus: `y=y[y.!=0]`.
Count `+` to `-` zero crossings: `sum((y[1:end-1].>0)&(y[2:end].<0))`.
> 4 votes

# Answer
# Mathematica, 42 36 33 32 bytes

Thanks to Martin Büttner for saving 1 byte.

```
Tr@PeakDetect[#&@@@Split@#,0,0]&

```

`PeakDetect` just does almost everything!

Test cases:

```
Total@PeakDetect[#&@@@Split@#,0,0]&@{12,1,2,1,2,3,3,3,2,4,4,4,1,5,5,4,7,9}
(* 6 *)
Total@PeakDetect[#&@@@Split@#,0,0]&@{87,356,37673,3676,386,909,909,909,909,454,909,908,909}
(* 4 *)

```
> 3 votes

# Answer
# MATLAB, ~~29~~ 27 bytes

```
@(a)nnz(findpeaks([0 a 0]))

```

Anonymous function which finds the peaks in the data and counts how many there are. 0 is prepended and appended to the data to ensure peaks at the very edges are detected as per the question.

This will also work with **Octave**. You can try online here. Simply paste the above code into the command line, and then run it with `ans([1,2,1,3,4,5,6,1])` (or whatever other input).

---

As the numbers are always +ve, we can assume they are greater than zero, so can save 2 bytes by using `nnz` instead of `numel`.
> 3 votes

# Answer
# Python 3, 75 bytes

```
def m(t):
 a=p=d=0
 for n in t+[0]:a+=(n<p)&d;d=((n==p)&d)+(n>p);p=n
 return a

```

This is my first codegolf so there may be some places to cut down on it, especially the `d=((n==p)&d)+(n>p)` part. However it works on all the test cases
> 3 votes

# Answer
# CJam, ~~27~~ 26 bytes

```
A0q~0A]e`1f=3ew{~@e>>}%1e=

```

Uses the run length coding to remove duplicates. After that we check for every triplet if the middle one is the largest number.

Try it here! Passes Peter Taylor's test suite.
> 2 votes

# Answer
# Mathematica, ~~55~~ ~~39~~ ~~36~~ 35 bytes

```
Length@FindPeaks[#&@@@Split@#,0,0]&

```

Now works on all of the test cases!
> 2 votes

# Answer
## Retina, ~~33~~ 31 bytes

*Thanks to Neil for saving 2 bytes.*

```
\b(1+)(?<!\1,\1)(,\1)*\b(?!,\1)

```

Try it online!

Takes input as a comma-separated, unary list.
> 2 votes

# Answer
# MATL, 22 bytes

```
0ih0hdZS49+c'21*?0'XXn

```

Uses current version of the language/compiler.

### Example

```
>> matl
 > 0ih0hdZS49+c'21*?0'XXn
 >
> [1, 2, 2, 3, 4, 3, 5, 3, 2, 1, 2, 3, 3, 3, 2, 2, 1, 3]
4

```

### Explanation

```
0ih0h           % input array. Append and prepend 0
dZS             % sign of difference between consecutive elements. Gives -1, 0, 1
49+c            % convert to a string of '0','1','2'
'21*?0'XX       % use (lazy) regular expression to detect peaks: '20' or '210' or '2110'...
n               % number of matches. Implicity print

```
> 2 votes

# Answer
## JavaScript ES6, ~~96~~ 94 bytes

```
t=>(a=t.filter((x,i)=>x!=t[i-1])).filter((x,i)=>(x>(b=a[i-1])||!b)&&(x>(c=a[i+1])||!c)).length

```

Principle: collapse plateaus into single peaks, find the picks which are defined as being higher than both next and previous elements.

Takes input as an array.

Demo:

```
f=t=>
(a=t.filter((x,i)=>x!=t[i-1]))    //collapse every plateau into the pick
    .filter((x,i)=>
       (x>(b=a[i-1])||!b)&&(x>(c=a[i+1])||!c)    //leave only those values which are greater than the succeeding and preceding ones
    ).length

document.write(
  f([])+"<br>"+
  f([1, 1, 1])+"<br>"+
  f([1, 2, 2, 3, 4, 3, 5, 3, 2, 1, 2, 3, 3, 3, 2, 2, 1, 3])+"<br>"+
  f([1])+"<br>"+
  f([1, 1])+"<br>"+
  f([2, 2, 2, 2, 2])+"<br>"+
  f([90])+"<br>"+
  f([2, 1, 2])+"<br>"+
  f([5, 2, 5, 2, 5])+"<br>"+
  f([2, 5, 2, 5, 2, 5, 2])+"<br>"+
  f([1, 2, 3, 4])+"<br>"+
  f([1, 2, 3, 4, 1, 2])+"<br>"+
  f([1, 3, 5, 3, 1])+"<br>"+
  f([7, 4, 2, 1, 2, 3, 7])+"<br>"+
  f([7, 4, 2, 1, 2, 1, 2, 3, 7])+"<br>"+
  f([1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2])+"<br>"+
  f([1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1])+"<br>"+
  f([2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2])+"<br>"+
  f([1, 3, 3, 3, 1, 3, 3, 1, 3, 1, 3, 3, 3, 3, 1])+"<br>"+
  f([12, 1, 2, 1, 2, 3, 3, 3, 2, 4, 4, 4, 1, 5, 5, 4, 7, 9])+"<br>"+
  f([87, 356, 37673, 3676, 386, 909, 909, 909, 909, 454, 909, 909])+"<br>"+
  f([87, 356, 37673, 3676, 386, 909, 909, 909, 909, 454, 909, 908, 909])
)
```
> 1 votes

# Answer
# MATL, 23

Since we need to use stack based esolangs to be competitive, I reimplemented my **Julia** solution in MATL.

```
0i0hhdtg)t5L)0>w6L)0<*s

```

Push `0`, input, `0`, concatenate twice. `0i0hh` =\> `x = [0, input(''), 0]`

Differentiate. `d` =\> `x = diff(x)`

Duplicate `t`, convert one to boolean and use it to index the other. `tg)` =\> `x=x(x!=0)`

Duplicate again. `t`

First: `[1,G])0>` =\> `y1 = x(1:end-1)>0`

Exchange. `w`

Second: `[2,0])0<` =\> `y2 = x(2:end)<0`

Logic and, count the truthy values. `*s` =\> `sum(y1 & y2)`
> 1 votes

# Answer
## ES6, ~~50~~ 48 bytes

```
m=>m.map(h=>{f=h>p?c+=!f:f&&h==p;p=h},p=c=f=0)|c

```

Saved 2 bytes thanks to @user81655.

Ungolfed:

```
function peaks(mountains) {
    var previous = 0;
    var count = 0;
    var plateau = false;
    for (var height of mountains) {
        if (height > previous) {
            if (!plateau) count++;
            plateau = true;
        } else if (height != previous) {
            plateau = false;
        }
    }
    return count;
}

```
> 1 votes

# Answer
# Japt, 19 bytes

That was easier than I thought, but the beginning is slightly wasteful due to a bug.

```
Uu0;Up0 ä< ä> f_} l

```

Try it online!

### How it works

```
Uu0;Up0 ä< ä> f_} l  // Implicit: U = input
Uu0;Up0              // Add 0 to the beginning and end of U. If this isn't done, the algorithm fails on peaks at the end.
        ä<           // Compare each pair of items, returning true if the first is less than the second, false otherwise.
                     // This leaves us with a list e.g. [true, false, false, true, false].
           ä>        // Repeat the above process, but with greater-than instead of less-than.
                     // JS compares true as greater than false, so this returns a list filled with false, with true wherever there is a peak.
              f_} l  // Filter out the falsy items and return the length.

```

### Non-competing version, 15 bytes

```
Uu0 p0 ä< ä> è_

```

Earlier today, I added the `è` function, which is like `f` but returns the number of matches rather than the matches themselves. I also fixed a bug where `Array.u` would return the length of the array rather than the array itself.

Try it online!
> 1 votes

# Answer
# Jelly, 27 bytes

```
ṡ2EÐḟFs2ḣ€1S€ṡ3M€Fċ2
0;⁸;0Ç

```

Try it online!
> 1 votes

# Answer
# 05AB1E, 9 bytes

```
Ô0.ø¥0‹ÔO

```

Try it online!

**Explanation:**

```
Ô0.ø¥0‹ÔO      Full program
Ô              Uniquify (= remove plateaus)
 0.ø           Surround with zeros
    ¥          Push deltas
     0‹        Test each element if lower than 0
               --- we now have a list with 0's (= going uphill) and
                   1's (going downhill). Since we removed plateaus, all
                   we have to do now is to count the number of ramps
                   going downhill
       Ô       Uniquify (reduce ramps to length 1)
        O      Total sum of the list

```
> 1 votes

# Answer
# Japt, 14 bytes

```
iT òÎmÎä> ò> l

```

Try it (includes all test cases)

Accommodating the empty array cost 2 bytes.

```
iT òÎmÎä> ò> l     :Implicit input of array
iT                 :Prepend 0
   ò               :Partition between elements where
    Î              :  The sign of their difference is truthy (not 0)
     m             :Map
      Î            :  First element
       ä>          :Consecutive pairs reduced by >
          ò>       :Partition after elements that are greater than the next
             l     :Length

```
> 1 votes

# Answer
# Husk, 11 bytes

```
#←gẊo±>m←gΘ

```

Try it online!

```
#←gẊo±>m←gΘ
#               # how many truthy elements in list of
 ←              # first element of each sublist of
  g             # grouped identical elements of
   Ẋ            # apply to each pair in list
    o±>         # sign of greater than (1 if greater than, 0 otherwise)
       m←       # make list from first element of each sublist of
         g      # grouped identical elements of
          Θ     # input prepended with zero

```
> 1 votes

# Answer
## GolfScript, 35

```
~0+0\{.@=!},+:a,2-,{a\>3<.$2=?1=},,

```

Test online

Basically removes duplicates, adds a 0 to both ends, and checks how many triples have a maximum in the center.
> 0 votes

# Answer
# Java 8, 141 bytes

```
l->{int r=0,i=1,t;for(l.add(0,0),l.add(0);i<l.size()-1;r+=t>l.get(i-1)&t>l.get(++i)?1:0)for(;(t=l.get(i))==l.get(i+1);)l.remove(i);return r;}

```

Can probably be golfed by using a different approach, or an array as input instead of List.

**Explanation:**

Try it here.

```
l->{                     // Method with ArrayList<Integer> parameter and int return-type
  int r=0,               //  Result-integer
      i=1,               //  Index-integer
      t;                 //  Temp integer
  for(l.add(0,0),        //  Add a 0 at the start of the list
      l.add(0);          //  Add a 0 at the end of the list
      i<l.size()-1;      //  Loop (1) from index 1 through length-1 (0-indexed)
      r+=                //    After every iteration, raise the result-integer by:
         t>l.get(i-1)    //     If the current item is larger than the previous
         &t>l.get(++i)?  //     and larger than the next:
          1              //      Increase `r` by 1
         :               //     Else:
          0)             //      `r` remains the same
    for(;(t=l.get(i))==l.get(i+1);
                         //   Inner loop (2) as long as there are two adjacent equal items
      l.remove(i)        //    And remove one of those two equal integers
    );                   //   End of inner loop (2)
                         //  End of loop (1) (implicit / single-line body)
  return r;              //  Return the result-integer
}                        // End of method

```
> 0 votes

# Answer
# Python 3, 68 bytes

```
f=lambda a,*b,p=0:(p<a>[*b,0][0])+(len(b)and f(*b,p=[p,a][a!=b[0]]))

```

Try it online!
> 0 votes

# Answer
# \>\<\> (Fish), 59 bytes

```
0i:0(?v:@)$!
v&01~~/
l
1
-
?
\?v  >^&+\
& \:?^v
\n;   \&1/

```

Try it online! \- Animated Version

## Explanation

**Green:** Read the input, push 1 if the value is less than the previous, 0 if it's more. Add a 0 and a 1 to the ends of the stack. Set the register to 0.

**Blue:** While the stack is not empty, check for a 0 followed by a 1. If so increment the register. In all other cases just pop a value.

**Yellow:** Print the result when the stack is empty.
> 0 votes

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


title: Is this substring list ambiguous?

text:
# Question
Title: Is this substring list ambiguous?
Given a set of substrings, such as `[ca, ar, car, rd]`, it's possible to create infinitely many strings by concatting them together. Some examples of this for the given substrings could be:

```
ca
caar
card
rdca
carrd
rdrd
...

```

One interesting property of this set of substrings is that any string can only be constructed in one way using them; there is no string where it's ambiguous which combination was used. As a counterexample, take the set `[foo, bar, obar, fo, baz]`. The string `foobar` could either be `foo + bar` or `fo + obar`.

**Task:**

Given a set of substrings, which will not contain duplicates, determine if the above property holds; that is, if for any concatenated ordering of any number of the substrings, it is unambiguously possible to determine the original order of the substrings that it was constructed out of.

In place of substrings you may use lists, with any reasonable data type in place of characters. You may also restrict the characters used in the substrings within reason, such as only using lowercase letters. Your chosen representation of the substrings must be able to represent at least a dozen "characters".

You may produce output using any of the following:

* A truthy/falsy value, with truthy representing either ambiguous or unambiguous (your choice)
* Two consistent values representing ambiguous and unambiguous
* One consistent value representing either ambiguous or unambiguous, and any other value representing the other

**Test cases:**

```
[ca, ar, car, rd]           unambiguous
[foo, bar, obar, fo, baz]   ambiguous
[a, b, c]                   unambiguous
[a, ab]                     unambiguous
[ab, bc, c]                 unambiguous
[b, ab, ba]                 ambiguous
[b, ab, ba, aa]             ambiguous
[a, aa]                     ambiguous
[abc, bcd, cda, dab, abcd]  ambiguous
[nn, no, on, oo]            unambiguous
[atombomb, at, omb]         ambiguous
[abc, dx, yz, ab, cd, xyz]  ambiguous
[xxx, xxxxx]                ambiguous
[a, ax, xx]                 unambiguous
[baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac, w, wb, acx, xba, aacy, ybaa, aaacz, zbaaa, aaaacd, d]  ambiguous

```

(Thanks to @Arnauld, @CursorCoercer, and @loopywalt for the last three test cases)

**Scoring:**

This is , so shortest answer (in bytes, per language) wins.

# Answer
> 8 votes
# JavaScript (ES6), 110 bytes

Returns *false* for unambiguous or *true* for ambiguous.

```
f=(a,p='',q=p)=>p>q?f(a,q,p):p&&p==q||q.match(p)&&!p[a.map(s=>n*=s.length,n=1)|n]&&a.some(s=>s!=q&&f(a,p+s,q))

```

Try it online!

### Commented

```
f = (              // f is a recursive function taking:
  a,               //   a[] = list of substrings
  p = '',          //   p = first string, initially empty
  q = p            //   q = second string, initially empty
) =>               //
p > q ?            // if p is lexicographically greater than q:
  f(a, q, p)       //   swap p and q
:                  // else:
  p && p == q ||   //   stop as successful if p is non empty and p = q
  q.match(p) &&    //   stop as failed if p cannot be found in q
  !p[              //   stop as failed if p is too long:
    a.map(s =>     //     for the upper bound, we use the product n
      n *=         //     of all substring lengths
        s.length,  //     (e.g. for two substrings whose lengths x and y
      n = 1        //     are co-prime, we may need to build strings of
    ) | n          //     length x * y to get a match)
  ] &&             //
  a.some(s =>      //   for each substring s in a[]:
    s != q &&      //     provided that s is not equal to q,
    f(a, p + s, q) //     do a recursive call where s is appended to p
  )                //   end of some()

```

### 98 bytes, much slower

```
f=(a,p='',q=p)=>p>q?f(a,q,p):p&&p==q||!p[a.map(s=>n*=s.length,n=1)|n]&&a.some(s=>s!=q&&f(a,p+s,q))

```

Try it online!

# Answer
> 8 votes
# Python, 104 bytes

```
f=lambda l,x=set():l>l-(y:={a[len(b):]for a in l|x for b in[l,l|x][{a}<l]if b+"~">a>b})or y-x and f(l,y)

```

Attempt This Online! Takes a set of strings (ASCII characters \< "~"); returns the empty set for unambiguous and True for ambiguous.

#### How?

Alongside the set of given "syllables" we keep a set of "tips" which are generated by building two words from the syllables such that one is a prefix of the other (and they do not start with the same syllable). The tip is the longer word with the prefix removed.

At each iteration we try generating new tips by finding syllables which are prefixed by or do prefix a previously found tip. The new tip will be the difference. If no new tips are found output unambiguous, if a syllable was created as a new tip output ambiguous, otherwise rinse and repeat.

# Answer
> 7 votes
# Python 3,  ~~140 133~~  129 bytes

This is my golf of Ajax 1234's method (it was 197 at the time) - go upvote that answer!

-7 Thanks to ovs (use `for j,k in q` loop in place of `while q` loop to remove the need for `j,k=q.pop()`.)

-4 Thanks to Sʨɠɠan (function rather than full-program.)

```
def f(a):
 d={};q=[(i,[i])for i in a]
 for j,k in q:q+=[(j+i,k+[i])for i in a if''.join(a)[:1-len(j+i):k in d.setdefault(j,[k])]]

```

A function that accepts a list of strings and identifies ambiguity by success/failure:

* Errors when ambiguous (raises a ValueError "slice step cannot be zero") or
* Succeeding when unambiguous (returns `None`).

**Try it online!** Or see the test-suite.

# Answer
> 5 votes
# Python3, 277 bytes:

```
def F(a):
 q,s=[(j,k)for j in a for k in a if j!=k and j[:len(k)]==k],[]
 for j,k in q:
  if j==k:return 0
  j,k=sorted([j,k],key=len)
  if k[len(j):]in s:continue
  for i in a:
   if all(J==K for J,K in zip(i[:len(k)-len(j)],k[len(j):])):q+=[(j+i,k)];s+=[k[len(j):]]
 return 1

```

Try it online!

# Answer
> 4 votes
# Charcoal, 34 bytes

```
ＷＳ⊞υι¹≔⮌υθＦθＦυ¿№θ⁺ικ⎚¿‹ＬιＬ⪫υω⊞θ⁺ικ

```

Try it online! Link is to verbose version of code. Takes input as a list of newline-terminated strings and outputs a Charcoal boolean, i.e. `1` for unambiguous, nothing for ambiguous. Explanation: Originally another port of @Ajax1234's answer, but since heavily simplified (see my comment on his answer), but it still seems to work, so...

```
ＷＳ⊞υι

```

Input the substrings.

```
¹

```

Assume they are unambiguous.

```
≔⮌υθＦθ

```

Start a breadth-first search with a clone of the list of substrings.

```
Ｆυ¿№θ⁺ικ⎚

```

Loop over all of the substrings and if an ambiguous concatenation is found then clear the canvas.

```
¿‹ＬιＬ⪫υω⊞θ⁺ικ

```

Otherwise if the current string is not too long then add the concatenation to the search.

# Answer
> 3 votes
# Python 3, 219 bytes

```
lambda x:any(t!=s and t==s[:len(t)]and c(s,t,x) for s in x for t in x)
def c(m,n,e,t=[]):d=m[len(n):];return d not in t and(d in e or any(s==d[:len(s)]and c(m,n+s,e,t+[d])or d==s[:len(d)]and c(n+s,m,e,t+[d])for s in e))

```

Try it online!

Takes a list of strings as input, returns False for unambiguous and True for ambiguous

# Answer
> 3 votes
# 05AB1E, ~~14~~ 8 bytes

```
ā€ãJ˜DÙQ

```

-6 bytes by checking if the flattened list contains only unique strings (taken from *@lyxal*'s Vyxal answer)

Outputs `0` if ambiguous and `1` if unambiguous.

Try it online or verify all test cases with \\$\leq4\\$ items.

**Explanation:**

```
ā         # Push a list in the range [1, (implicit) input-length]
 €        # Map over each integer:
  ã       #  Get the value'th cartesian power of the (implicit) input-list
   J      # Join each inner-most lists together to a string
    ˜     # Flatten the list of lists of strings
     DÙQ  # Verify the list doesn't contain any duplicated strings:
     D    #  Duplicate this list
      Ù   #  Uniquify the copy
       Q  #  Check if the two lists are still the same
          # (after which the result is output implicitly)

```

# Answer
> 2 votes
# Vyxal `r`, ~~11~~ ~~8~~ 7 bytes

```
żvÞẊfÞu

```

Try it Online!

Two can play at the porting game, Kevin! -3 bytes by using cartesian products (taken from *@KevinCruijssen*'s 05AB1E answer). And another -1 by using the `r` flag to get rid of a `$` that was needed for some weird reason (bug, probably).

Outputs `1` for unambiguous, `0` for ambiguous.

## Explained

```
żvÞẊfÞu
ż        # The range [1, len(input)]
 vÞẊ     # nth cartesian power of the input for each number in that range
    fÞu  # are all the items unique?

```

# Answer
> 0 votes
# T-SQL, 156 bytes

Returns 1 when ambiguous, 0 when unambiguous

```
WITH C(z,y)AS(SELECT*,*FROM @
UNION ALL SELECT','+z+','+x+',',+x
FROM C,@ D WHERE z not
like'%,'+x+',%')SELECT
top 1~(-1/sum(1))FROM
C GROUP BY y ORDER BY 1

```

**Try it online**

---
Tags: code-golf, decision-problem, set-partitions
---


title: Is this string a square?

text:
# Question
Title: Is this string a square?
A string is considered to be square if the following conditions are met:

* Each line has the same number of characters
* The number of characters on each line is equal to the number of lines.

Your task is to write a program or function which determines whether or not a given input string is a square.

You may require input to be delimited by your choice of LF, CR, or CRLF.

The newline character(s) are not considered part of the line's length.

You may require there to be or to not be a trailing newline in input, which doesn't count as an additional line.

Input is a string or 1D char array; it is not a list of strings.

You may assume input is non-empty and only contains printable ASCII, including spaces.

You must output a truthy value for square strings and a falsy one for other strings.

## Truthy test cases:

```
foo
bar
baz

```

```
.

```

```
.s.
.ss
.s.
(s represents space)

```

```
ss
ss
(s represents space)

```

```
aaaaa
aaaaa
aaaaa
aaaaa
aaaaa

```

## Falsy test cases:

```
..
.

```

```
.

```

```

.

```

```
....

....

```

```
4444
333
22

```

```
333
333

```

```
abc.def.ghi

```

Note extra blank lines in some of the falsy cases.

This is - fewest bytes wins!

# Answer
# Brachylog (2), 3 bytes

```
ṇẹṁ

```

Try it online!

Full program. Outputs `true.` for truthy, `false.` for falsey.

## Explanation

```
ṇẹṁ
ṇ     Split {standard input} into lines
 ẹ    Split {each line} into basic elements {in this case, characters}
  ṁ   Assert that the result is square

```

I was a bit sceptical about the usefulness of the  builtin when it was added, but I can't really deny that it's helpful here…

# Brachylog (2), 7 bytes

```
ṇẹ.\l~l

```

Try it online!

Non-builtin solution. ~~*Still* beats all the other entries, as of the time of writing.~~ EDIT: Not quite, the equal-length Jelly entry got in while I was writing this, and beats it via the timestamp tiebreak.

## Explanation

```
ṇẹ.\l~l
ṇ         Split {standard input} into lines
 ẹ        Split {each line} into basic elements {in this case, characters}
   \l     Assert that the result is rectangular, and the number of columns
  .  ~l     is equal to the number of rows

```
> 22 votes

# Answer
# Python 2, 52 bytes

```
x=input().split('\n')
print{len(x)}==set(map(len,x))

```

Try it online! or Try all test cases
> 23 votes

# Answer
# JavaScript (ES6), ~~46~~ 45 bytes

```
s=>!(s=s.split`
`).some(x=>x.length-s.length)

```

---

## Explanation

1. Split the string to an array on newlines.
2. Loop over the array.
3. Subtract the length of the array from the length of each line.
4. If a non-zero (i.e., truthy) value is returned for any line, the string is not square.
5. Negate the result of the loop to get `true` for square and `false` for not.

---

## Try it

```
f=
s=>!(s=s.split`
`).some(x=>x.length-s.length)
oninput=_=>o.innerText=f(i.value)
o.innerText=f(i.value=`foo
bar
baz`)
```

```
<textarea id=i></textarea><pre id=o>
```
> 16 votes

# Answer
# Jelly, ~~7~~ 5 bytes

```
Ỵ¬⁼Z$

```

Try it online!

Thanks to FryAmTheEggman for -2
> 11 votes

# Answer
# 05AB1E, ~~10~~ 8 bytes

```
¶¡€gDgQP

```

Try it online!

***-2 thanks to Riley, this is basically his answer .\_.***

```
Code       # Explanation                  | Truthy Example          | Falsy Example
-----------#------------------------------+-------------------------+--------------
¶¡         # Split on newlines            | [['aaa','aaa','aaa']]   | [['aa']]
  €g       # Get length of each           | [[3,3,3]]               | [[2]]
    D      # Dupe                         | [[3,3,3],[3,3,3]]       | [[2],[2]]
     g     # Get length                   | [[3,3,3],3]             | [[2],1]
      Q    # Check equality               | [[1,1,1]]               | [[0]]
       P   # Take product                 | 1                       | 0

```
> 10 votes

# Answer
# Japt, 9 bytes

```
=Ur.Q)¥Uy

```

Test it online!

### Explanation

```
 =Ur.Q)¥ Uy
U=Ur.Q)==Uy
             // Implicit: U = input string, Q = quotation mark
U=    )      // Set U to
  Ur.Q       //   U with each non-newline (/./g) replaced with a quotation mark.
       ==Uy  // Return U == U transposed. U is padded to a rectangle with spaces before
             // transposing; if U was not a rectangle before, or the sides are not of
             // equal length, the result will not be the same as U.
             // Implicit: output result of last expression

```

---

Using some features implemented shortly after this challenge was posted, this can be 6 bytes:

```
r.Q
¥y

```

Test it online!

### Explanation

```
       // Implicit: U = input string
r.Q    // Replace each non-newline (/./g) in U with a quotation mark.
       // Newline: set U to the result.
¥      // Return U ==
 y     //   U transposed.
       // Implicit: output result of last expression

```
> 9 votes

# Answer
# Jelly, 7 bytes

```
ỴµL;L€E

```

Try it online!

## Explanation

```
Ỵµ       Split the input on newline and use as input in the second link
  L      Get the number of list items
   ;     And append to that
    L€   A list with the legth of each list item
      E  Check to see if all items are equal.

```
> 9 votes

# Answer
## Haskell, ~~38~~ 34 bytes

```
l=length
(all=<<(.l).(==).l).lines

```

Try it online!

Pointfree version of `f s = all ((==length (lines s)).length) (lines s)`, i.e split the input into lines and check if the length of each line is equal to the number of lines.

Edit: Thanks to @xnor for 4 bytes.
> 9 votes

# Answer
## Husk, 6 bytes

```
S≡T'a¶

```

Takes a string and prints either `1` or `0`. Try it online! The first line iterates over the test cases; remove it if you want to test on a single value.

## Explanation

Husk is a new functional golfing language created by myself and Leo. It's missing a lot of features and development is ongoing. Its main feature is a rigid type system that allows us to overload higher order functions.

On a high level, the program works like this:

```
S≡T'a¶  Define a function:
     ¶  split on newlines,
  T'a   transpose and pad to rectangle using character 'a',
 ≡      check if this has the same shape as
S       the split input.

```

The function  actually checks if two arrays have the same shape and the same distribution of truthy elements. In Husk, all characters except the null byte are truthy, and that won't occur in our inputs. Also, `S` is the **S-combinator**, a function that takes as inputs two functions, here  and `T'a`, and returns a new function that maps `x` to `≡(x)(T'a x)`. The result of `S` is composed with , and that function is applied to the input implicitly.

How does Husk know that it should apply `S` to the next function, but  should be composed with the function on its left? Simple: it just tries every interpretation and picks the one where the types make sense. This is explained in more detail in the Husk documentation.
> 9 votes

# Answer
# Retina, ~~33~~ 31 bytes

```
.
.
^(.(.)*)(?<-2>¶\1)*$(?(2).)

```

Try it online! Explanation: The first stage simply changes all printable ASCII into the same character to make it easier to match. (It could be done without, but this is code golf, not code challenge.) The second stage then matches at least one character on the first line. However, for each additional character on the first line, it then optionally matches a newline followed by a copy of the first line. The final part of the expression causes the match to fail if there are more columns than rows.
> 7 votes

# Answer
# Pure bash (no utilities), 55

```
mapfile -t a
for l in ${a[@]};{
((c+=${#l}^${#a[@]}))
}

```
* `mapfile` reads the input into array `a`
* then the number of elements of the array is XORed with each line length, and the sum taken. For a perfect square, each XOR result (and thus the sum) will be 0. For anything else, the result will be \>0.

The opposite sense of this is returned as a shell return code (examine with `echo $?`) - perfect square is 1, anything else is 0.

Try it online (truthy).

Try it online (falsy).

---

### Previous answer using eval-escape-expansion hell, 78:

```
mapfile -t a
echo $[0$(eval eval echo +\\$\{#a[{0..$[${#a[@]}-1]}]}^${#a[@]})]

```

Try it online (truthy).

Try it online (falsy).
> 6 votes

# Answer
# Perl 6, 27 bytes

```
{.lines==all .lines».comb}

```

Tests whether the number of lines in the input string is equal to the number of characters on each line.
> 5 votes

# Answer
# Jelly, 4 bytes

```
Ỵ¬zƑ

```

Try it online!

Input via command-line argument. The input must be given with no trailing newline (otherwise the program sees a blank line at the end, which isn't the same length as the others); this I/O format is explicitly allowed by the question.

So far, the shortest answer that doesn't use an "is a square" builtin. (There's an existing 5-byte Jelly answer that works on similar principles, but is wrong, incorrectly considering `"aa\na"` to be square – this answer is not only shorter, it also fixes that issue.)

## Explanation

```
Ỵ¬zƑ
Ỵ      split {the input} on newlines
 ¬     replace every truthy character (i.e. all of them) with 0
   Ƒ   does that remain unchanged, after
  z      a ragged transpose that pads to a rectangle using {the input}?

```

There are two main cases:

* The string is not even a rectangle. In this case, the "transpose and pad to rectangle" builtin `z` will pad the string to a rectangle, but uses copies of the user input as the padding, which are not zeroes (even if the input uses the character `'0'`, this compares unequal to the integer `0`). So there's no way the ragged transpose can leave the split-and-zeroed version of the input unchanged.
* The string is a rectangle. In this case, the ragged transpose won't apply any padding, but will produce a rectangle of zeroes with the number of rows and columns swapped from the transpose input. The only way the input and output can match is therefore if the number of rows equals the number of columns, i.e. the input is a square. (If the input *is* a square, the transpose will leave it unchanged because, as every element is a zero, all the elements will be the same and thus it doesn't matter that the transpose swaps some of them.)
> 5 votes

# Answer
## Pyth, 7 bytes

```
CImL1.z

```

Try it here

Requires no trailing newline. Replaces the input with a 2D array of 1s where a 1 represents any character in the original input. Then we check whether that array is unchanged after transposing it (replacing columns with rows). Only a square will return true in such a situation.
> 4 votes

# Answer
# Java (OpenJDK 8), ~~96~~ ~~91~~ ~~90~~ 87 bytes

*-5 bytes thanks to @KevinCruijssen*
*-1 byte thanks to @TheLethalCoder*
*-2 bytes thanks to @OlivierGrégoire*

```
a->java.util.Arrays.stream(a.split("\n")).allMatch(x->x.length()==a.split("\n").length)

```

Try it online!
> 4 votes

# Answer
# MATL, ~~14~~ 12 bytes

```
10H&XXot&n=h

```

The input string is defined using string concatenation (`[...]`) and with the code point `10` to represent LF. For example, `['aaa' 10 'bb']` is interpreted in MATL as string `'aaa'` concatenated with the character with code point `10` concatenated with string `'bb'`.

The output is a non-empty numeric vector, which is truthy if and only if all its entries are non-zero.

**Try it online!**

### Explanation

Consider input `['4444' 10 '333' 10 '22']`.

```
10H   % Push 10 (code point of LF). Push 2
      % STACK: 10, 2
&XX   % Regexp with three arguments. First argument is implicit input (string);
      % second is 2, which indicates that we want to split the input; third is
      % 10, which is the character to split on. The result is a cell array of
      % matched strings
      % STACK: {'4444', '333', '22'}
o     % Concatenate into a numeric 2D array of code points, right-padding with
      % zeros if needed
      % STACK: [52 52 52 52; 51 51 51 0; 50 50 0 0]
t&n   % Duplicate. Push number of rows and number of columns
      % STACK: [52 52 52 52; 51 51 51 0; 50 50 0 0], 3, 4
=     % Are they equal?
      % STACK: [52 52 52 52; 51 51 51 0; 50 50 0 0], 0
h     % Concatenate into a row vector (in column-major order). Implicit display
      % STACK: [52 51 50 52 51 50 52 51 0 52 0 0 0]

```
> 3 votes

# Answer
# 05AB1E, 7 bytes

```
|€gDgQP

```

Try it online!
> 3 votes

# Answer
# , 57 bytes

```
function(s)all(nchar(n<-strsplit(s,'
')[[1]])==length(n))

```

An anonymous function; Splits on newlines, computes the length of each line, and checks if all are the same as the number of lines.

Try it online!
> 3 votes

# Answer
# Ruby, 50 bytes

```
s=$<.read.split $/,-1;p [s.size]==s.map(&:size)|[]

```

Try it online!

## Explanation

1. Split input into array on newline.
2. Assert that an array containing only the size of this array is equal to an array containing all uniq (set union with empty array) sizes of all elements in this array.
> 3 votes

# Answer
# R, 35 bytes

```
all(nchar(x<-scan(,""))==length(x))

```

Takes input from stdin. Checks that the number of characters in each line is equal to the total number of lines. Returns `TRUE` or `FALSE` as appropriate.
> 3 votes

# Answer
# JavaScript (ES6), 48 bytes

```
s=>(a=s.split`
`,a.every(l=>l.length==a.length))

```
> 2 votes

# Answer
## CJam, 11 bytes

```
qN/:,_,f=:*

```

Try it online!
> 2 votes

# Answer
# Pyth, ~~12~~ 10 bytes

```
!fnl.zlT.z

```

Saved 2 bytes thanks to @FryAmTheEggman.

Try it online

### Explanation

```
!fnl.zlT.z
 f     T.z     Filter lines of the input
  nl.zl        whose length is not the number of lines
!              and return whether there are no such lines.

```
> 2 votes

# Answer
# OCaml, 56 bytes

```
let f t=List.(for_all(fun l->String.length l=length t)t)

```

Try it online!
> 2 votes

# Answer
# QBIC, 43 bytes

```
{_?~_lA||h=h+1┘g=g+_lA|~g%_lA||_Xp]\_xg/h=h

```

Me, I'm happy with how short a QBasic derivative got to go on this challenge.

## Explanation:

```
{_?       DO infinitely: ask the user for input, store as A$
~    |    IF
 _lA|       The length of A$   (implicitly <> 0)
h=h+1     Add 1 to our line counter
┘         (syntactic linebreak)
g=g+_lA|  Add the length of this line to the running total of line lengths
~      |  IF
 g%_lA|     The length of the running total modulo the length of the last string
            yields anything but 0, there is a discrepancy between earlier line
            lengths and this one.
_Xp]      THEN QUIT, printing 0, end IF
\         ELSE (refers to the LEN(A$), user didn't input anything.
_xg/h=h   QUIT (the inf. loop) printing -1 if the root of the chars is the row count
            or 0 if not.

```
> 2 votes

# Answer
# Pyth, 7 bytes

```
qCC.z.z

```

Demonstration

Transpose the input with truncation twice, then check if the result is the same as the original.
> 2 votes

# Answer
# Perl 5, 31 bytes

29 bytes of code + `-p0` flags.

```
/.*/;$_=/^(.{@{+}}
){@{+}}\z/

```

Try it online!

**Explanations:**
`/.*/` matches the first line, and thus makes `@+` contain the length of the first line. Then the regex checks whether the string contains `@+` lines of length `@+`.
> 2 votes

# Answer
# MacOS Bash, 34

```
rs -EH|awk '{print $1}'|uniq|wc -l

```

`rs` is part of the default MacOS image. This will also work on Linux if `rs` is installed; it is on TIO.

* `rs -EH` lists the length of each line, along with the number of lines
* `awk` strips out extraneous info
* `uniq` outputs one line if the line lengths and number of lines are all the same, but more otherwise
* `wc -l` outputs `1` if the input is square or a greater number otherwise.

Try it online: Truthy, Falsey.
> 2 votes

# Answer
# AWK, 49 bytes

```
{s=length($0)}L{x+=L!=s}{L=s}END{print x?0:L==NR}

```

Try it online!

Could also have used a `BEGIN` block to set `FS=""` but that would be the same byte-count. For some reason using the `-F""` argument never seems to work.
> 2 votes

# Answer
# Stax, 9 bytes

```
éΘ┌«■/ÉW(

```

Run and debug online!

Turns out that due to way pairwise difference is calculated, I don't need to worry about the equivalence of `k` and `x-k` here. Saving 5 bytes.

Uses the unpacked version to explain.

```
Lc{%mc%+:u
L             Collect rows in a list
 c{%m         List of length of each row
     c%+      Append number of rows to the list
        :u    All elements in the list are equal

```
> 2 votes

# Answer
# PowerShell, 48 bytes

```
($a=$args-split'
'|%{$_.Length}).Count-eq($a|gu)

```

Test script:

```
$f = {

($a=$args-split'
'|%{$_.Length}).Count-eq($a|gu)

}

@(

,($true,@"
foo
bar
baz
"@)

,($true,@"
.
"@)

,($true,@"
. .
.
. .
"@)

,($true,@"

"@)

,($true,@"
aaaaa
aaaaa
aaaaa
aaaaa
aaaaa
"@)

,($false,@"
..
.
"@)

,($false,@"
.

"@)

,($false,@"

.
"@)

,($false,@"
....

....
"@)

,($false,@"
4444
333
22
"@)

,($false,@"
333
333
"@)

,($false,@"
abc.def.ghi
"@)

) | % {
    $expected,$s = $_
    $result = &$f $s
    "$($result-eq$expected): $result"
}

```

Output:

```
True: True
True: True
True: True
True: True
True: True
True: False
True: False
True: False
True: False
True: False
True: False
True: False

```

Explanation:

* `$args-split"``n"|%{$_.Length}` creates an array of length of each line.
* `$a.Count` counts elements of the array
* `$a|gu` apply Get-Unique to the array. The result is one integer element if all lines has same length.
* `$a.Count-eq($a|gu)` compares `Count` of element with result of the Get-Unique. It's `true` if all lines has same length and this length equals to `Count`.
> 2 votes

# Answer
# Pip, 11 bytes

```
Y0MMa^ny=Zy

```

Takes a multiline string (with no trailing newline) as a command-line argument. Try It Online!

### Explanation

```
Y0MMa^ny=Zy
    a        Command-line argument
     ^n      Split on newlines
  MM         To each character of each line, map:
 0           0
             This results in a nested list of 0's, one for each character
Y            Yank it into the y variable
       y=    That nested list equals
         Zy  Its transpose

```

For example, with inputs `"abc\ndefg"` and `"ab\ncd"`:

```
    a^n      ["abc";"defg"]       ["ab";"cd"]
Y0MM         [[0;0;0];[0;0;0;0]]  [[0;0];[0;0]]
         Zy  [[0;0];[0;0];[0;0]]  [[0;0];[0;0]]
       y=    0                    1

```
> 2 votes

# Answer
# Vyxal, 5 bytes

```
¶o²⁋=

```

Try it Online!

```
¶o²⁋=
¶o    # Remove all newlines
  ²   # Format as a square
   ⁋  # Join by newlines
    = # Equal to the input?

```
> 2 votes

# Answer
# Regex (.NET), 55 bytes

```
^.((.))*(?<-1>
.(?=(?<-2>.)*(?(2).)
)(?<2>.)*)*$(?(1).)

```

Try it on regex101

Neil said in his Retina answer, "It could be done without, but this is code golf, not code challenge." Well, here's a pure regex answer that *needs* to do it that way (without substitutions done beforehand to lighten the load).

The last line must end with exactly one newline. To remove this restriction would result in worse golf.

In this explanation,  indicates a raw newline in the regex:

```
^                    # Anchor to start of string
.                    # Skip one character, due to the fact that when we count
                     # the number of rows, matching it up with our capture count,
                     # the first row won't becounted.
((.))*               # Add the remaining length of this line to the capture count
                     # of both \1 and \2.
(?<-1>               # If there is at least one capture on the \1 stack, do the
                     # following:
    ¶                # Advance to the next line (thus proving that the entire
                     # previous line was processed)
    .                # Advance by one character (because we already did the same
                     # on the first line)
    (?=              # Lookahead - allows the same part of the string to be
                     # matched in multiple ways.
        (?<-2>.)*    # For each capture remaining on the \2 stack, advance one
                     # character. Will stop short if it reaches the end of the
                     # line before the \2 stack is emptied.
        (?(2).)¶     # Assert that if the \2 stack is not empty, there is at
                     # least one more character remaining in this line, but also
                     # assert that this is the end of the line - effectively
                     # asserting that the \2 stack is empty and we're at the end
                     # of the line.
    )
    (?<2>.)*         # Having already proved that this line is of equal length to
                     # the previous, transfer its length back into the capture
                     # count of group \2.
)*                   # Iterate the above as many times as possible, minimum zero.
$                    # Assert that we've reached the end of the string, or a
                     # newline after which it is the end of the string.
(?(1).)              # Effectively assert that the \1 stack is empty, as it is
                     # impossible to match one more non-newline character after
                     # reaching the end of the string.

```

# Regex (Perl / PCRE2), ~~69~~ 64 bytes

```
^(?=((?|
()|.(?=.*
(\2?+.)))+)+
\2$)((?=^|.+(\4?+
.+)).)+\4$|^.$

```

Try it online! \- Perl
Try it on regex101 \- PCRE2

A trailing newline on the last line is optional. Squares with or without it will both match. (In the 69 byte version, the trailing newline was mandatory.)

In PCRE, acceptance of a trailing newline can be disabled with a flag: Try it on regex101
But in Perl, the only way to do this is to replace `$` with `\z` (+1 byte): Try it online!

The regex does not work in PCRE1 (the older and no longer maintained version of PCRE) due to a PCRE1 bug in which `\2`, a nested backreference, is not reverted to its earlier value when backtracking, causing it to have false positives on shapes that have an equal number of lines as characters in their first line, but whose remaining lines monotonically increase (or stay the same) in length.

In this explanation,  indicates a raw newline in the regex:

```
^                          # Anchor to start of string
(?=                        # Lookahead - allows the same part of the string to
                           # be matched in multiple ways.
    # Assert this is a rectangle (all lines have an equal number of characters)
    # with at least 2 lines. A trailing newline on the last line is optional.
    (
        (?|                # Branch Reset Group - allows the same group numbers
                           # to be captured in different parts of the regex.
            # This alternative is to be taken when the inner loop has reached
            # the end of a line, finishing this iteration of the outer loop.
            ¶
            ()             # \2 = empty, in preparation for the next iteration
                           #      of the outer loop
        |
            # This alternative is to be taken while still processing the line.
            .              # Go forward one character.
            (?=            # Lookahead - match what's inside, then jump back to
                           # this position upon exiting it.
                .*¶        # Skip to the next line
                (          # \2 = the following:
                    \2?+   # Match previous value of \2 if set
                    .      # Match one extra character in this line
                )
            )
        )+                 # Iterate the above as many times as possible
    )+                     # Iterate the above as many times as possible
    ¶                      # Match a newline. Note that the regex engine will
                           # be forced to backtrack, because it will have
                           # already matched this newline inside the loop, and
                           # erased the contents of \2. Backtracking allows it
                           # to undo this, restoring the contents of \2 and
                           # allowing us to match the newline and \2 here.
    \2$                    # Assert that the last line is not longer than the
                           # penultimate line, by asserting that the string
                           # ends after the \2 that was captured. Note that "$"
                           # will match whether this is the end of the string,
                           # or a newline followed by the end of the string.
                           # "\z" only matches at the exact end of the string,
                           # but we don't need to use it.
)
# Assert the number of characters in the first line equals the number of lines
(
    (?=                    # Lookahead
        ^                  # On the leftmost character, match nothing else.
    |                      # On all subsequent characters, do the following:
        .+                 # Skip to the end of this line
        (                  # \4 = the following:
            \4?+           # Match previous value of \4 if set
            ¶.+            # Match a newline, followed by one more entire line,
                           # which we assert is at least one character long.
        )
    )
    .                      # Go forward one character.
)+                         # Iterate the above as many times as possible
\4$                        # Assert that the string ends after \4.

|^.$                       # Or, match a 1×1 square, which the above code can't
                           # do. Again, a trailing newline is optional due to
                           # the behavior of "$".

```
> 2 votes

# Answer
# Scala, ~~42~~ 39 bytes

Fairly compact, yet easily understandable

Saved 3 bytes thanks to @Steffan.

39 bytes solution using Java 8 Try it online!

```
s=>s.lines.forall(_.size==s.lines.size)

```

42 bytes solution using Java 11 or newer Try it online!

```
s=>s.lines.allMatch(_.size==s.lines.count)

```
> 2 votes

# Answer
# Julia 1.0, 42 bytes

```
!x=(y=split(x,"
");~=length;all(~y.==.~y))

```

Try it online!

This function splits the string over newlines and checks if the number of lines is equal to the length of each line. Since `length` must be called twice (vectorized and non-vectorized), it is renamed as `~` (Thanks amelies!).
> 2 votes

# Answer
# Cheddar, 39 bytes

```
@.split("
").all((i,j,k)->i.len==k.len)

```

Try it online!
> 1 votes

# Answer
## Clojure, 58 bytes

```
#(let[s(re-seq #"[^\n]+"%)c count](apply =(c s)(map c s)))

```

Requires a trailing newline, looking forward to seeing something more magical.
> 1 votes

# Answer
# APL (Dyalog), 17 bytes

Requires `⎕ML←3` which is default on many systems. Uses CR.

```
↓∘⎕FMT≡⎕TC[2]∘≠⊂⊢

```

Try it online!

`↓∘⎕FMT` \[is the\] split-into-lines **F**or**m**a**t**ted-into-a-square argument

identical to

`⎕TC[2]∘≠` the into-groups-of-non-newline\*-characters

partitioned

argument?

* the second element of the list of **T**erminal **C**ontrol characters.

---

In version 16.0, one can write `↓∘⎕FMT≡⎕TC[3]∘≠⊆⊢` with `⎕ML←1`.
> 1 votes

# Answer
## PowerShell, 64 bytes

The same (split, line lengths, number of lines) approach as other non-golf language answers, but there's no nice map() equivalent, so it's an array of line lengths with the number of lines tagged onto the end, then that array is grouped. Squares come out like `3,3,3,3 -> 1 group, all line lengths and line count were equal` and non-squares come out like `3,2,1 -> 3 groups`, something was unequal in the square:

```
$f={@(@(($L="$args"-split"`n")|% le*)+$L.Count|group).Count-eq1}

```

Requires newline Linux-style endings, no trailing newline. e.g.

```
$Ttests = @(@'
foo
bar
baz
'@,
'.',
@'
aaaaa
aaaaa
aaaaa
aaaaa
aaaaa
'@
)
$Ttests = $Ttests | foreach {$_ -replace "`r"}

$Ttests | % { & $f $_ }

```

(And you can do similar for the false tests, but I won't put it here as there's more of them). The couple of `@` symbols are required for when the input is the single `'.'` otherwise splitting it doesn't make an array of one string it just makes one string, and then the array concatenation doesn't output `1,1` it outputs `2`.

I hoped it might be shorter to replace all the characters with 'a', and then brute force from 1 to Input Length all the squares 'a' and see if any matched the input. Once I got past param() and .Length and -join and -replace it ends up much longer at 81 bytes:

```
$f={param($s)!!(1..$s.Length|?{,('a'*$_)*$_-join"`n"-eq($s-replace"[^`n]",'a')})}

```
> 1 votes

# Answer
## Grime, 11 bytes

```
e`.|_./+/.+

```

Prints `1` for squares and `0` for non-squares. Try it online!

## Explanation

A detailed explanation can be found on the Grime tutorial page, which happens to contain this exact program as an example.

```
e`.|_./+/.+
e`            Match entire input against pattern:
  .           A single character
   |          OR
    _         a recursive match of this pattern
     ./+      with one column of characters on its right
        /     and below that
         .+   one row of characters.

```
> 1 votes

# Answer
# C#, 73 bytes

```
using System.Linq;s=>s.Split('\n').All(l=>l.Length==s.Split('\n').Length)

```

Explanation:

```
using System.Linq;    //Import Linq
s=>                   //Take input
s.Split('\n')         //Split the input stirng by line feeds
.All(l=>              //Make sure All lines in the array return true for:
l.Length              //The length of the line
==                    //Equaling
s.Split('\n').Length) //The length of the array split again by line feeds

```
> 1 votes

# Answer
# Dart - 54 chars

```
q(s)=>!(s=s.split('\n')).any((x)=>x.length!=s.length);

```

(Expects input separated by newlines and not terminated by one)

Try it online
> 1 votes

# Answer
# Clojure, 42 chars

```
#(every?(fn[x](=(count %)x))(map count %))

```
> 1 votes

# Answer
# \>\<\>, 76 bytes

This should work, next step is trying to golf it more!

```
0v      0   <
 >i:0)?!va=?^1+
:0)?v1n;\~l:   >
    >r:@=?!vr1-^
        ;n0<

```

Try it online! Or more more fun, try some examples using this animated interpreter.

```
printf "aaa\naas\naaa" | fish _square.fish --tick 0.1 --play

```

## Explanation

The idea is roughly as follows.

1. Fill the stack with the number of characters on each line.
2. Push the length of the stack, corresponding to the number of lines (*n*).
3. Do *n* times:
    * Check if bottom two elements are equal.
    * Remove deepest element.

### Examples

For

```
aaa
aaa
aaa

```

we get `[3, 3, 3, 3]` after the first two steps and we can see that all three length 2 subsequences are equal. However, for

```
aaa
aa
a

```

we get `[3, 2, 1, 3]` and not all sequences are equal. For the last falsy case

```
`abc.def.ghi`

```

we get `[11, 1]` so there is only subpair we can check, but it is unequal so we return falsy.
> 1 votes

# Answer
# Charcoal, 20 bytes

```
Ａ⁺№θ¶¹αＦ⪪θ¶Ａ×α⁼αＬιαα

```

Try it online! Prints `-` repeated by the side length as truthy, nothing as falsy.
> 1 votes

# Answer
# Add++, 45 bytes

```
D,g,@,bU10C€=sVcG1+V10CAtbU€bLB]db=$bM*G=

```

Try it online!

## How it works

Boy this was a long one (not even counting the footer)

```
D,g,@,		; Declare a monadic function 'g'
		; Example argument:    		 ['foo\nbar\nbaz']
	bU	; Unpack;		 STACK = ['f' 'o' 'o' '\n' 'b' 'a' 'r' '\n' 'b' 'a' 'z']
	10C€=s	; Count newlines;	 STACK = ['f' 'o' 'o' '\n' 'b' 'a' 'r' '\n' 'b' 'a' 'z' 2]
	VcG	; Keep last value;	 STACK = [2]
	1+V	; Increment and save;	 STACK = []			; STORE = 3
	10CAt	; Split arg on newlines; STACK = [['foo' 'bar' 'baz']]
	bU€bLB]	; Length of €ach;	 STACK = [[3 3 3]]
	db=	; Are they all equal?	 STACK = [[3 3 3] 1]
	$bM	; Max value;		 STACK = [1 3]
	*	; Logical AND;		 STACK = [3]
	G=	; Equals STORE?		 STACK = [1]

```

Try it online!
> 1 votes

# Answer
# PHP, 65 bytes

```
while(~$c=$argv[1][$p++])$w+=":"^$c||$w=!$$w+=!!++$h;echo$$h==$h;

```

expects linux style line endings (`\n`) and a trailing newline; prints `1` for truthy, nothing for falsy.
Run with `php -nr '<code>' '<input>'` or try it online.

---

Btw: The naive approach takes 82 bytes:

```
<?=count($a=explode("
",$argv[1]))==min($m=array_map(strlen,$a))&min($m)==max($m);

```

expects linebreaks as on compile system and no trailing newline; prints `1` or `0`.
Run with `php -nR '<code>' '<input>'`.
> 1 votes

# Answer
**Python 3, 79 bytes**

```
lambda a:len(set([len(list(i))for i in a.split('\n')]+[len(a.split('\n'))]))==1

```
> 1 votes

# Answer
# Swift 3, 134 bytes

```
import Foundation;func r(s:String)->Bool{let i=s.components(separatedBy:"\n");return i.filter{$0.characters.count != i.count}.isEmpty}

```

Try it online!
> 1 votes

# Answer
# Wren, ~~76~~ 61 bytes

```
Fn.new{|a|a.split("\n").all{|x|x.count==a.split("\n").count}}

```

Try it online!

## Old answer

The algorithm is essentially just copied from a 05AB1E answer.

```
Fn.new{|a|
var b=a.split("\n").map{|i|i.count}
return b.all{|i|i==b.count}
}

```

Try it online!
> 1 votes

# Answer
# Red, 73 bytes

```
func[s][all collect[foreach b a: split s lf[keep(length? b)= length? a]]]

```

Try it online!

`{abcd
efg}` represents true multiline string and not a list of strings, hence I need `split s lf`
> 1 votes

# Answer
# SnakeEx, 38 bytes

```
h:{c<B>1}{c<L>1}{e<>}{e<R>}
c:.+$
e:.$

```

A match is truthy; no match is falsey. **Try it here**

---

The previous 50-byte SnakeEx submission was copied from the original solution to the detect-square-inputs problem in the 2D pattern-matching language challenge. Here's the thing: that problem says, "*Match the entire input* if it is a square block of characters." But for this problem, we merely need to match *something* if the input is a square block of characters. That enables us to use a different approach, saving bytes.

Instead of matching the whole square, we match its bottom row and rightmost column and assert that they are the same length. (It's important to pick the rightmost column, since that will fail if we have jagged input.)

* `c:.+$` Define `c` to match some number of characters and then the edge of the grid
* `e:.$` Define `e` to match the character it's currently on and then the edge of the grid
* `{c<B>1}` Turn backwards (i.e. toward the left side), match `c`, and put that match in group 1
* `{c<L>1}` Turn left (i.e. toward the top), match `c`, and put that match in group 1 (thereby requiring both matches to be the same length)
* `{e<>}` Match `e` in the default direction (toward the right side)
* `{e<R>}` Turn right (i.e. toward the bottom) and match `e`

The two `c` calls make sure the height and width are the same; the two `e` calls make sure our starting point is the bottom right corner.
> 1 votes

# Answer
# Google Sheets, 47

Closing parens/quotes already discounted.

Input: `A1`

`A2` to `A3`:

```
=ArrayFormula(LEN(SPLIT(A1,"
")))
=A2=COUNTIF(2:2,A2)

```
> 1 votes

# Answer
# 05AB1E, 7 bytes

```
.B¤g∍»Q

```

Try it online or verify all test cases.

**Explanation:**

```
.B       # Box the (implicit) multi-line input-string, splitting on newlines,
         # and appended spaces to make all rows the same length
  ¤      # Push the last string (without popping the list)
   g     # † Pop and push its length
    ∍    # Extend/shorten the list up to this length
     »   # Join it by newlines
      Q  # Check if it's equal to the (implicit) input
         # (after which the result is output implicitly)

```

† This is only necessary if the last line of the input is a number. Builtin  will extend/shorten it to the number size if a number is given as argument, but will use the length to extend/shorten if a string is given. E.g. `"ab" "abcdefg" ∍` will extend the `"ab"` to `length("abcdefg")=7`, resulting in `"abababa"`, but unfortunately `"123" "12" ∍` will extend the `"123"` to `"123123123123"` instead of shortening it to `length("12")=2` to `"12"`.
So for all given test cases `.B¤∍»Q` would have sufficed, but unfortunately it'll fail for something like `123\nabc\n7.3`.
> 1 votes

# Answer
# BQN, 15 bytes

```
>∘⊔'
'⊸(≠×1+`=)

```

Anonymous tacit function. Takes a multiline string that must include a trailing newline. Try it at BQN online!

Outputs via error for falsey and no error for truthy. If that's not acceptable, here's a 19-byte version that returns 0 for falsey and 1 for truthy:

```
≡·>⎊0·⊔'
'⊸(≠×1+`=)

```

### Explanation

```
>∘⊔'¶'⊸(≠×1+`=)
       (      )   Call this function with the multiline string as right argument
   '¶'⊸           and a newline character as left argument:
             =      For each character in the string, 1 if it is newline, 0 otherwise
           +`       Cumulative sum of that array
          1         starting at 1
         ×          For each of those values, multiply by the corresponding value in:
        ≠           For each character in the string, 0 if it is newline, 1 otherwise
                  This transforms the first line into 1s, the second line into 2s, etc.,
                  and newlines into 0s
  ⊔               Group the indices of this list according to their values in the list
>∘                Attempt to convert that list of lists to a rectangular array

```
* If not all lines in the input are the same length, the groups will have different lengths, and the conversion to an array will fail.
* If the input is rectangular but not square, the newlines group will have a different length from the other groups, and the conversion will fail.
* If the input is an N by N square, there will be a group representing N newlines and N groups representing N characters each, which will be successfully converted into an N+1 by N array.
> 1 votes

# Answer
# APL, 10 or 8 bytes

```
(≢=(⌈/≢¨))

```

Input is an array of strings.

Explained:

```
(       ) fork (could be removed if assigned to a variable)
 ≢        amount of strings
  =       equals
   (⌈/ )  the maximum
     ≢¨   of each of the string's lengths

```
> 1 votes

# Answer
# Julia 1.0, ~~44~~ 41 bytes

```
!s=(l=count(==('
'),s)+1)l==length(s)-l+1

```

Try it online!
> 1 votes

# Answer
# SnakeEx, 50 bytes

This is BMac's solution to the problem for the 2D regex language design challenge.

```
m:{v<R>1}{h<>1}
v:${c<L>A1}+$
h:${c<R>A1}+$
c:$.+$

```

**Try it online**
> 0 votes

# Answer
# J, 12 bytes

```
(*./=#)#;._2

```

Input requires trailing LF or CR.

Explanation:

* `;._2` split into intervals and discard trailing atom
* `#` count each group
* `(*./=#)` is a fork which returns 0 (false) or 1 (true) if the LCM of the count of each group is equal to the count-of-counts

Tests

```
(*./=#)#;._2 'abc', LF, 'def', LF, 'ghi', LF   NB. 1 for well-formed input
(*./=#)#;._2 'abc', LF, 'def', LF, 'ghi'       NB. 0 because no trailing LF

```
> 0 votes

# Answer
# Burlesque, 7 bytes

```
ln)L[sm

```

Try it online!

Requires a trailing newline after the input. Technically the trailing newline is only needed if the input ends on a newline (as `ln` ignores one trailing newline), and it doesn't make a difference whether it's there or not otherwise, but stating it as a blanket requirement is probably preferable. Returns 1 for square inputs and 0 otherwise.

Explanation:

```
ln       # Split input string into lines
  )      # Map each line...
   L[    # ...to its length
     sm  # Are all line lengths the same?

```
> 0 votes

# Answer
# Factor \+ `math.matrices`, 28 bytes

```
[ "\n"split square-matrix? ]

```

Try it online!
> 0 votes

# Answer
# Zsh, 40 bytes

```
set -- "${(@f)1}"
for l;(($#l==$#))||bye

```

Try it online!

---

Using modern rules, we can save **1 byte** by swapping truthy and falsy:

# Zsh, 39 bytes

```
set -- "${(@f)1}"
for l;(($#l-$#))&&bye

```

Try it online!

```
set -- "${(@f)1}"    # (f) splits into lines, (@) and "" are needed to preserve empty lines
for l                # for each line:
   (($#l-$#))&&bye   # - if the line length differs from the number of lines, exit 0.
                     # otherwise, ((0)) from the last loop iteration has an exit code of 1,
                     # so we exit 1.

```
> 0 votes

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


title: The world ends in ed

text:
# Question
Title: The world ends in ed
Taken straight from the ACM Winter Programming Contest 2013. You are a person who likes to take things literally. Therefore, for you, the end of The World is ed; the last letters of "The" and "World" concatenated.

Make a program which takes a sentence, and output the last letter of each word in that sentence in as little space as possible (fewest bytes). Words are separated with anything but letters from the alphabet (65 - 90, 97 - 122 on the ASCII table.) That means underscores, tildes, graves, curly braces, etc. are separators. There can be more than one seperator between each word.

`asdf jkl;__zxcv~< vbnm,.qwer| |uiop` -\> `flvmrp`
`pigs, eat dogs; eat Bob: eat pigs` -\> `ststbts`
`looc si siht ,gnitirw esreveR` -\> `citwR`
`99_bottles_of_beer_on_the_wall` -\> `sfrnel`

# Answer
> 17 votes
## Perl 5, 18 bytes

```
s/\pL*(\pL)|./$1/g

```

Requires a `-p` command line switch. The named property `L` matches only letter characters `A-Za-z`. There are several hundred such named properties, but when dealing with ASCII text, very few of them are interesting. Besides `\pL`, the only other one of any real note is `\pP`, which matches punctuation.

Try it online!

---

**Perl 5, 17 bytes**

*A one byte improvement by Dom Hastings*

```
print/\pL*(\pL)/g

```

Requires `-n` (and `-l` to support multiple inputs).

Try it online!

---

**Sample usage**

```
$ more in.dat
asdf jkl;__zxcv~< vbnm,.qwer| |uiop
pigs, eat dogs; eat Bob: eat pigs
looc si siht ,gnitirw esreveR
99_bottles_of_beer_on_the_wall

$ perl -p ends-in-ed.pl < in.dat
flvmrp
ststbts
citwR
sfrnel

```

# Answer
> 23 votes
# ed, 35 characters

```
s/[a-zA-Z]*\([a-zA-Z]\)\|./\1/g
p
Q

```

So, the world ends in ed. As I like to be too literal, I decided to write to write the solution with ed - and apparently it is actually a programming language. It's surprisingly short, even considering many shorter solutions already exist in this thread. It would be nicer if I could use something other than `[a-zA-Z]`, but considering ed isn't a programming language, it's actually good enough.

First, I would like to say this only parses the last line in file. It would be possible to parse more, just type `,` at beginning of two first lines (this specified "everything" range, as opposed to standard last line range), but that would increase code size to 37 characters.

Now for explanations. The first line does exactly what Perl solution does (except without support for Unicode characters). I haven't copied the Perl solution, I just invented something similar by coincidence.

The second line prints last line, so you could see the output. The third line forces quit - I have to do it, otherwise `ed` would print `?` to remind you that you haven't saved the file.

Now for how to execute it. Well, it's very simple. Just run `ed` with the file containing test case, while piping my program, like that.

```
ed -s testcase < program

```

`-s` is silent. This prevents `ed` from outputing ugly file size at beginning. After all, I use it as a script, not editor, so I don't need metadata. If I wouldn't do that, ed would show file size that I couldn't prevent otherwise.

# Answer
> 6 votes
## Javascript, 49

```
alert(prompt().replace(/.(?=[a-z])|[^a-z]/gi,''))

```

It uses a regular expression to remove all characters that come before a letter, as well as all non-letter characters. Then we're left with the last letter of each word.

Thanks to tomsmeding for a nice improvement.

# Answer
> 6 votes
# C, 78

Golfed:

```
main(int c,char**s){for(;c=*s[1]++;)isalpha(c)&&!isalpha(*s[1])?putchar(c):0;}

```

With whitespace:

```
main(int c,char**s)
{
  for(;c=*s[1]++;)
    isalpha(c)&&!isalpha(*s[1])?putchar(c):0;
}

```

Output:

# Answer
> 5 votes
## GNU Sed, 40 38 37

```
s/[a-z]\b/&\n/g; s/[^\n]*\(.\)\n/\1/g

```

### Testing

```
cat << EOF > data.txt
asdf jkl;__zxcv~< vbnm,.qwer| |uiop
pigs, eat dogs; eat Bob: eat pigs
looc si siht ,gnitirw esreveR
EOF

```

Run sed:

```
sed 's/[A-Za-z]\b/&\n/gi; s/[^\n]*\(.\)\n/\1/g' data.txt

```

Output:

```
flvmrp
ststbts
citwR

```

### Explanation

The first substitution replaces all word boundaries, that are preceded by the desired match group, with a new-line. This makes it easy to remove all extraneous characters in the second substitution.

### Edit

* Use case-insensitive flag (-2), thanks **manatwork**.
* Don't count whitespace (-1).

# Answer
> 3 votes
## Grep and Paste, 36 34 28

```
> echo 'asdf jkl;__zxcv~< vbnm,.qwer| |uiop' | grep -io '[a-z]\b' | tr -d \\n
flvmrp

> echo 'pigs, eat dogs; eat Bob: eat pigs'   | grep -io '[a-z]\b' | tr -d \\n
ststbts

echo 'looc si siht ,gnitirw esreveR'         | grep -io '[a-z]\b' | tr -d \\n
citwR

```

If a final new-line is needed, replace `tr -d \\n` with `paste -sd ''`.

### Edit

* Use case-insensitive grep (-2), thanks **manatwork**.
* Use `tr` instead of `paste` (-4), thanks **manatwork**.
* Don't count whitespace around pipe (-2).

# Answer
> 3 votes
## sed, 37 chars

Equal length to Thor's answer, but, I think, simpler.

```
s/[a-z]*\([a-z]\)/\1/ig;s/[^a-z]*//ig

```

The logic is quite trivial - replace letter sequences with their last letter, then delete all non-letters.

# Answer
> 3 votes
## Mathematica, 39

```
""<>StringCases[#,(__~~x_)?LetterQ:>x]&

```

Test:

```
""<>StringCases[#,(__~~x_)?LetterQ:>x]& /@
 {"asdf jkl;__zxcv~< vbnm,.qwer| |uiop",
  "pigs, eat dogs; eat Bob: eat pigs",
  "looc si siht ,gnitirw esreveR",
  "99_bottles_of_beer_on_the_wall"}

```

> ```
> {"flvmrp", "ststbts", "citwR", "sfrnel"}
>
> ```

# Answer
> 3 votes
# Zsh (builtins only), 40

```
for j (${=@//[^a-zA-Z]/ });printf $j[-1]

```

Try it Online...

# Answer
> 3 votes
# Nibbles, 4.5 bytes (9 nibbles)

```
.%~$\$a/\

```

```
.%~$\$a/\       # 9 nibble program
.%~$\$a/\$$     # with implicit variables added:
 $~             # split
   $            # the input
    \           # by whether the character class
     $          # of each element
      a         # is alphabetic;
.               # now, map over this
        \       # reversing
         $      # each group
       /        # and folding across these
          $     # returning the first (left-hand) argument
                # (in other words, return the first character of each group)

```

# Answer
> 2 votes
## Mathematica ~~62~~ ~~57~~ 52

```
Row@StringTake[StringCases[#,LetterCharacter..],-1]&

```

Testing

```
l = {"asdf jkl;__zxcv~<vbnm,.qwer| |uiop",
     "pigs,eat dogs;eat Bob:eat pigs",
     "looc si siht,gnitirw esreveR"}

Row@StringTake[StringCases[#,LetterCharacter..],-1]&/@ l
(*{flvmrp,ststbts,citwR}*)

```

# Answer
> 2 votes
# K, 49

```
{last'f@&"b"$#:'f:"|"\:@[x;&~x in,/.Q`a`A;:;"|"]}

```

.

```
k){last'f@&"b"$#:'f:"|"\:@[x;&~x in,/.Q`a`A;:;"|"]}"asdf jkl;__zxcv~< vbnm,.qwer| |uiop"
"flvmrp"
k){last'f@&"b"$#:'f:"|"\:@[x;&~x in,/.Q`a`A;:;"|"]}"pigs, eat dogs; eat Bob: eat pigs"
"ststbts"
k){last'f@&"b"$#:'f:"|"\:@[x;&~x in,/.Q`a`A;:;"|"]}"looc si siht ,gnitirw esreveR"
"citwR"

```

# Answer
> 2 votes
## Scala, 59 (or 43)

Assuming the string in already in `s`:

```
s.split("[^a-zA-Z]+").map(_.last).mkString

```

If you need to read from a prompt and print rather than using the REPL output, convert `s` to `readLine` and wrap in `println()` for 59.

# Answer
> 2 votes
## x86: 54 bytes

Assume a cdecl routine with the signature `void world_end(char *input, char *output)`:

```
60 8b 74 24 24 8b 7c 24 28 33 d2 8a 0e 8a c1 24
df 3c 41 72 08 3c 5a 77 04 8a d1 eb 09 84 d2 74
05 88 17 47 33 d2 46 84 c9 75 e0 84 d2 74 03 88
17 47 88 0f 61 c3

```

# Answer
> 2 votes
## Xi, 32

```
println$ @{=>.-1}<>input re"\W+"

```

Xi is a language still in its beta phase, but it seems to work well with code golf so I figured I might as well show yet another short and functional solution (and advertise the language a little :-)).

# Answer
> 2 votes
# Python, 76 chars

`import re;print "".join(re.findall("([a-zA-Z])(?=$|[^a-zA-Z])",raw_input()))`

# Answer
> 2 votes
# Python3, 59 chars

```
import re;print(re.sub('.(?=[a-z])|[^a-z]','',input(),0,2))

```

Correctly deals with capital letters and underscores. The 2 is to pass `re.sub` the `re.IGNORECASE` flag without having to use `re.I`.

# Answer
> 2 votes
# Japt v2.0a0 `-P`, ~~16~~ ~~9~~ 6 bytes

```
q\L mÌ

```

Try it or run all test cases

```
q\L mÌ     :Implicit input of string U
q          :Split on
 \L        :  Regex /[^a-z]/gi
    m      :Map
     Ì     :  Last character
           :Implicitly join & output

```

# Answer
> 2 votes
# Haskell, ~~62~~ 60 bytes

```
f s=last<$>words[last$' ':[c|'@'<c,c<'{','`'<c||c<'[']|c<-s]

```

Try it online! Thanks to Wheat Wizard for a version without the import, saving two bytes!

---

### Haskell, 62 bytes

```
import Data.Char
f s=last<$>words[last$' ':[c|isAlpha c]|c<-s]

```

Try it online!

Given an input string `s`, `[last$' ':[c|isAlpha c]|c<-s]` converts all non-alphabetic characters to spaces. `words` splits the resulting string on white space and `last<$>` takes the last character of each of the resulting strings.

# Answer
> 2 votes
# Pyth, ~~27~~ 19 bytes

```
seMc:z"[^A-Za-z]+"d

```

Test suite

##### Explanation:

```
seMc:z"[^A-Za-z]+"d | Full code
--------------------+---------------------------------------------
    :z"[^A-Za-z]+"d | In the input, replace non-letters with space
   c                | Split on spaces
 eM                 | Replace each word with its last letter
s                   | Concatenate each letter

```

# Answer
> 2 votes
# R, 126

My R solution

```
function(x){cat(paste(unlist(sapply(strsplit(unlist(strsplit(gsub("
[^[:alpha:]]"," ",x)," ")),""),tail,1)),collapse=""),"\n")}

```

# Answer
> 2 votes
# Pip, 8 bytes

```
DQ*a@+XA

```

Verify all test cases: Try it online!

### Explanation

```
      XA  Built-in regex variable: `[A-Za-z]`
     +    Apply regex + quantifier: `[A-Za-z]+`
   a@     Find all matches in the input
DQ*       Dequeue the last character from each match
          Concatenate together and autoprint (implicit)

```

# Answer
> 1 votes
## Mathematica ~~71~~ ~~47~~ ~~45~~ 61

Back to the drawing board, after @belisarius found an error in the code.

```
StringCases[#, RegularExpression["[A-Za-z](?![A-Za-z])"]] <> "" &

```

Testing

```
l = {"asdf jkl;__zxcv~<vbnm,.qwer| |uiop", "asdf jkl__zxcv~<vbnm,.qwer| |uiop",
"pigs,eat dogs;eat Bob:eat pigs", "looc si siht,gnitirw esreveR"};

StringCases[#, RegularExpression["[A-Za-z](?![A-Za-z])"]] <> "" & /@ l

```

> {"flvmrp", "flvmrp", "ststbts", "citwR"}

# Answer
> 1 votes
# Python 2, 88 80 75 69 68

```
s=p=''
for c in raw_input()+' ':a=c.isalpha();s+=p[a:];p=c*a
print s

```

Input: `435_ASDC__uio;|d re;fG o55677jkl..f`

Output: `CodeGolf`

---

This solution can be shortened to **67** characters if you allow the output to include backspace characters (ASCII code 8) at the beginning. The output will be visually identical.

```
s=p='<BS>'
for c in raw_input()+p:a=c.isalpha();s+=p[a:];p=c*a
print s

```

Same input, (visually) same output. `<BS>` is meant to be the backspace character.

# Answer
> 1 votes
# Python 3.x, 64 bytes

```
import re;print(''.join(a[-1] for a in re.split('\W+',input())))

```

# Answer
> 1 votes
# **Lua, 42**

```
print(((...):gsub('.-(.)%f[%A]%A*','%1')))

```

Usage example: `lua script.lua "asdf jkl;__zxcv~< vbnm,.qwer| |uiop"`

# Answer
> 1 votes
## VBA, 147 161

```
Sub a(s)
For n=0 To 255:m=Chr(n):s=Replace(s,IIf(m Like"[A-Za-z]","",m)," "):Next
For Each r In Split(s," "):t=t & Right(r,1):Next
MsgBox t
End Sub

```

# Answer
> 1 votes
**Smalltalk**, Squeak/Pharo flavour
**122** char with traditional formatting for this method added to String:

```
endOfWords
    ^(self subStrings: (CharacterSet allCharacters select: #isLetter) complement) collect: #last as: String

```

**62** chars in Pharo 1.4, with regex and weird formatting

```
endOfWords^''join:(self regex:'[a-zA-Z]+'matchesCollect:#last)

```

# Answer
> 1 votes
# J: 60 characters (or 38 characters for a less correct version)

```
(#~e.&(,26&{.&(}.&a.)"0(97 65))){:&>;:]`(' '"_)@.(e.&'_:')"0

```

If we're willing let the program break whenever there are words ending in a colon or an underscore, then we can simplify this to 38 characters.

```
(#~e.&(,26&{.&(}.&a.)"0(97 65))){:&>;:

```

Sample run:

```
    (#~e.&(,26&{.&(}.&a.)"0(97 65))){:&>;:]`(' '"_)@.(e.&'_:')"0'asdf jkl;__zxcv~< vbnm,.qwer| |uiop'
flvmrp
    (#~e.&(,26&{.&(}.&a.)"0(97 65))){:&>;:]`(' '"_)@.(e.&'_:')"0'pigs, eat dogs; eat Bob: eat pigs'
ststbts
    (#~e.&(,26&{.&(}.&a.)"0(97 65))){:&>;:]`(' '"_)@.(e.&'_:')"0'99_bottles_of_beer_on_the_wall'
sfrnel

```

# Answer
> 1 votes
# **C#**

Method, **105** bytes: (assumes usings for System, System.Text.RegularExpressions and System.Linq)

```
string R(string i){return string.Concat(Regex.Split(i,"[^a-zA-Z]").Where(x=>x!="").Select(n=>n.Last()));}

```

Program, **211** bytes:

```
using System;using System.Text.RegularExpressions;using System.Linq;class A{static void Main(){Console.WriteLine(string.Concat(Regex.Split(Console.ReadLine(),"[^a-zA-Z]").Where(x=>x!="").Select(n=>n.Last())));}}

```

# Answer
> 1 votes
It's in **PHP**. **197** bytes :( I'm beginner

```
$l=$_GET['line'];
$l=preg_replace('/(\W|_)+/',' ',$l);
$s=explode(' ',$l);
foreach($s as $d){
$a=substr($d,-1,1);
$o=ORD($a);
if(($o>=97 && $o<=122) || ($o>=65 && $o<=90)){
echo $a;
  }
}

```

**EDITED** Now it's **171 bytes**

```
<?$l=$_GET['l'];$l=preg_replace('/(\W|_)+/',' ',$l);$s=explode(' ',$l);foreach($s as $d){$a=substr($d,-1,1);$o=ORD($a);if(($o>=97&&$o<=122)||($o>=65&&$o<=90)){echo$a;}}

```

# Answer
> 1 votes
***K 30***

```
q)k)f:{x@&-1=-':(1_x," ")in,/.Q`a`A}
q)f "asdf jkl;__zxcv~< vbnm,.qwer| |uiop"
"flvmrp"
q)f "pigs, eat dogs; eat Bob: eat pigs"
"ststbts"
q)f "looc si siht ,gnitirw esreveR"
"citwR"
q)f "99_bottles_of_beer_on_the_wall"
"sfrnel"

```

# Answer
> 1 votes
# Ruby 2.0, 25 (+1) chars

```
gsub(/(\w+)\W*/){$1[-1]}

```

Must be run with the `-p` switch:

```
 $ ruby -p ed.rb <<< "asdf jkl;__zxcv~< vbnm,.qwer| |uiop"
flvmrp

```

# Answer
> 1 votes
# JavaScript, 37 bytes

```
t=>t.match(/[a-z](?![a-z])/ig).join``

```

# Answer
> 1 votes
# SNOBOL4 (CSNOBOL4), 117 bytes

```
	L =&UCASE &LCASE
	N =INPUT
B	N SPAN(L) . X BREAK(L) REM . N	:F(O)
	X RPOS(1) LEN(1) . X
	O =O X	:(B)
O	OUTPUT =O
END

```

Try it online!

```
	L =&UCASE &LCASE			;*upper and lowercase letters
	N =INPUT				;*read input
B	N SPAN(L) . X BREAK(L) REM . N	:F(O)	;*while match success, set X to first run of L characters, split on non-L characters, and set N to remainder
	X RPOS(1) LEN(1) . X			;*set X to the last character of X
	O =O X	:(B)				;*append X to O, goto B
O	OUTPUT =O				;*output O
END

```

I feel like there's a way to directly set `X` to the end of the `SPAN(L)` but I haven't figured it out yet.

# Answer
> 1 votes
# 05AB1E, 17 bytes

```
Sžosåγ€g£ʒDáQ}€θJ

```

Try it online!

# Answer
> 1 votes
# Retina, 20 bytes

```
i`.(?=[a-z])|[^a-z]

```

**Try it online**

This program is compatible with version 0.8.2

# Answer
> 1 votes
# Haskell, 76 bytes

```
import Data.Char
u=isAlpha
f(a:i@(b:_))|u b=f i|u a=a:f i|1>0=f i
f(a:b)=[a]

```

Try it online!

# Answer
> 1 votes
# Vim, 26 bytes:

```
:s/\v\S*(\a)\A*( |$)/\1/g<CR>

```

Try it online!

# Answer
> 1 votes
# Retina, 16 bytes

```
Li, -1|""`[a-z]+

```

Try it online!

### Explanation

```
Li, -1|""`[a-z]+
L         [a-z]+        List all the sequences of letters in the input
 i                      case insensitive
  ,                     Keep all the results
    -1                  but only the last character for each of them
      |""               Use the empty string as separator

```

# Answer
> 1 votes
# Java 8, 43 bytes

```
s->s.replaceAll("(?i).(?=[a-z])|[^a-z]","")

```

Port of *@mbomb007*'s Retina answer.

**Explanation:**

Try it online.

```
s->  // Method with String as both parameter and return-type
  s.replaceAll("(?i).(?=[a-z])|[^a-z]","")
     //  Remove every match of this regex, and return as result

```

Additional explanation for the regex:

```
"(?i).(?=[a-z])|[^a-z]"  // Main regex to match
 (?i)                    //  Case insensitive
     .                   //   Any character
      (?=[a-z])          //   Followed by a letter (as positive look-ahead)
               |[^a-z]   //   or a non-letter

""                       // Replace it with: nothing

```

# Answer
> 1 votes
# PHP, 52 bytes

The narrow word characeter definition quite of narrows the number of approaches.
I wonder if anything else can compete with regex here.

Try them online.

---

```
<?=preg_filter("/.*?([a-z])[^a-z]+/i","$1",$argn._);

```

This requires PHP 7.1 for the negative string index. Run as pipe with `-nF`.

---

Another solution, **53 bytes** (requires PHP 7.1)

```
foreach(preg_split("/[^a-z]/i",$argn)as$s)echo$s[-1];

```

Run as pipe with `-nR`.

---

The shortest non-regex solution I could find so far takes **60 bytes**:

```
while(~$c=$argn[$i++])$b=ctype_alpha($c)?$c:!print$b;echo$b;

```

Run as pipe with `-nR`.

# Answer
> 1 votes
# Gema, 12 characters

```
<L1>\X=$0
?=

```

Sample run:

```
bash-4.4$ gema '<L1>\X=$0;?=' <<< 'asdf jkl;__zxcv~< vbnm,.qwer| |uiop'
flvmrp

```

# Answer
> 1 votes
# Add++, 81 bytes

```
D,u,@@,o
D,l,@,V91 65r123 97r+bU€CJGe
D,T,@~,
L~,€lB]ABcB*"."dV€uJG$tbU€TBZVcGbUJ

```

Try it online!

# Answer
> 1 votes
# GAWK, ~~49~~ 46 bytes

```
BEGIN{RS="[^A-z]"}{printf substr($0,length$0)}

```

Try it online!

# Answer
> 1 votes
# Julia 0.6, 46 bytes

```
f(s)=string(matchall(r"[a-z](?![a-z])"i,s)...)

```

Try it online!

Simple Julia with Standard regex. The `r""` constructor creates a `Regex` class. Notice how the `i` letter after the last `"` makes the expression case insensitive.

# Answer
> 1 votes
# Jelly, 12 bytes

```
e€ØẠ¬œpµLƇṪ€

```

Try it online!

```
e€ØẠ¬œpµLƇṪ€ - Main link. Takes a string S on the left
  ØẠ         - Yield "ABC...XYZabc...xyz"
 €           - For each character in S:
e            -   Is it in the alphabet?
    ¬        - Logical NOT
               This yields a list, L, with 1s at non-alphabet characters
     œp      - Partition S at truthy indices of L, without keeping the borders
       µ     - Begin a new chain with the partitioned list, P, as the argument
         Ƈ   - Keep those with a truthy:
        L    -   Length
           € - Over each:
          Ṫ  -   Yield the last character

```

# Answer
> 1 votes
# Husk, 10 bytes

```
m→fo√←ġo¬√

```

Try it online!

since there's no conditional spliting function, `group-by` is used. Golflangs with regex are really strong here.

## Explanation

```
m→fo√←ġo¬√
      ġo¬√ group on nonalphabets
  fo√←     filter out nonalphabets
m→         map to last character

```

# Answer
> 1 votes
# sed (-E), 29 bytes

```
s/[a-zA-Z]*([a-zA-Z])|./\1/gp

```

Try it Online!

Beats other `sed` answers by 8 bytes. Port of the excellent `ed` solution.

# Answer
> 1 votes
# JavaScript, ~~36~~ 37 bytes

```
s=>s.match(/[A-z](?![a-z])/ig).join``

```

# Answer
> 1 votes
# Vyxal `s`, 6 bytes

*Thanks to lyxal for reminding me not to be a sussy baka*

```
øWǍƛ[t

```

Try it Online!

Explanation:

```
øW      # Group words together
  Ǎ     # Remove non-alphabet characters
   ƛ    # For each remaining string:
    [   #   If it is not empty:
     t  #     Tail

```

# Answer
> 1 votes
# Python 3,  ~~51~~  50 bytes

```
lambda s:re.sub("([a-zA-Z])*|.","\\1",s)
import re

```

Try it online!

## How it works:

* `([a-zA-Z])*` will match a whole word capturing every single char in group 1 (one at a time).
* if no words are found, `.` match the char to discard it
* `re.sub(<pattern>,"\\1",s)` substitute every occurence of our pattern by the content of capturing group 1 (the last char of the word since it only captures one char at a time)

# Answer
> 1 votes
# 05AB1E, 7 bytes

```
áмS¡€θJ

```

Try it online or verify all test cases.

**Explanation:**

```
á       # Only keep all letters of the (implicit) input-string
 м      # Remove all those letters from the (implicit) input-string
  S     # Convert it to a list of characters
   ¡    # Split the (implicit) input-string by those characters,
        # so only empty strings and strings consisting of letters are left in the list
    €θ  # Only keep the last character of each string
      J # Join it together to a single string
        # (which is output implicitly as result)

```

# Answer
> 1 votes
# Go, 134 bytes

```
import."regexp"
func f(s string)(o string){for _,e:=range MustCompile(`[A-Za-z]+`).FindAllString(s,-1){o+=string(e[len(e)-1])}
return}

```

Attempt This Online!

# Answer
> 1 votes
# PowerShell Core, 36 bytes

```
-join($args-split'[^a-z]'|%{$_[-1]})

```

Try it online!

1. Case insensitive split on non alphabetical characters
2. Get the last character of each word
3. Join them in a string

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