title: Is it a doubling sequence?

text:
# Question
Title: Is it a doubling sequence?
A doubling sequence is an array of numbers where each subsequent number is at least twice the previous number.

Given an ordered list of numbers, determine if the numbers in the list (\\$n\_{x}\\$) have the property that:

\\$n\_1 \times 2 \le n\_2\\$

\\$n\_2 \times 2 \le n\_3\ ...\\$

and so on until reaching the end of the list.

# Input

A list of two or more numbers.

# Output

Any distinct True or False value.

# Examples:

```
[10,20,30] -> False
[10,20,40] -> True
[1,2,3] -> False
[1,2,4] -> True
[1,2,10] -> True
[1,1] -> False
[10,1] -> False

```

# Answer
# , ~~27~~ 26 bytes

```
all(diff(log2(scan()))>=1)

```

Try it online!

1 byte saved by Giuseppe.
> 11 votes

# Answer
# Jelly, 4 (5?) bytes

Monadic link taking the list as input.

```
I<ṖẸ

```

If I am allowed to output 0 for Truthy and 1 for Falsy... Otherwise,

```
I<ṖẸ¬

```

You can try all test cases!

Notice that \\$x\_{i+1} \geq 2x\_i \iff x\_{i+1} - x\_i \geq x\_i\\$.

```
 <      Compare
I       the forward differences
  Ṗ     with the original list without the last item.
   Ẹ    Check if any comparison returned true
    ¬   and negate that

```

# Jelly, 6 bytes

We can instead take pairwise quotients and check directly if they satisfy the inequality with this monadic link:

```
÷Ɲ>.Ẹ¬

```

You can verify all test cases!

```
÷Ɲ      Compute the quotient for all pairs of elements in the input list.
  >.    See if the elements are greater than 0.5
    Ẹ   and take the "OR" of that list,
     ¬  finishing off with the negation of that.

```
> 10 votes

# Answer
# Japt v2.0a0, 6 bytes

```
ä÷ e§½

```

Try it

```
ä÷ e§½     :Implicit input of array
ä          :Consecutive pairs
 ÷         :  Reduced by division
   e       :All
    §½     :  Less than or equal to 0.5

```
> 8 votes

# Answer
# Haskell, 30 bytes

```
f(x:s)=any(<2)$zipWith(/)s$x:s

```

Try it online!

`True` for false and `False` for true.
> 5 votes

# Answer
# Python 3, ~~37~~ 29 bytes

-8 bytes thanks to xnor.

Fails for doubling sequences, completes otherwise.

```
f=lambda a,*b:2*a<=b[0]>f(*b)

```

Try it online!

# Python 3, 40 bytes

```
f=lambda a,*b:b==()or 2*a<=b[0]and f(*b)

```

Try it online! Test suite by Noodle9.
> 5 votes

# Answer
# JavaScript (ES6),  ~~26~~  24 bytes

*Saved 2 bytes thanks to @Grimmy*

```
a=>!a.some(n=>2*a>(a=n))

```

Try it online!
> 4 votes

# Answer
# Husk, 4 bytes

```
Λ·≤D

```

Try it online!

Returns 0 if False, a positive number if True.

```
Λ     Check if adjacent pairs of elements satisfy the predicate
 · D    by doubling the first number
  ≤     and checking if the second number is less than it

```
> 3 votes

# Answer
# Dyalog APL, 8 bytes

```
∧/2≤2÷/÷

```

Try it online!
> 3 votes

# Answer
# Octave, 18 bytes

```
@(e)istril(e<2*e')

```

Try it online!

Octave has a nice feature known as broadcasting. Here, we take broadcast less-than of the input and the input doubled, by transposing the input. This creates a matrix of ones and zeroes. Iff this matrix is lower triangular (no nonzero entries above the diagonal), the sequence is a doubling sequence.
> 3 votes

# Answer
# Octave, ~~46~~ ~~33~~ 31 bytes

```
@(n)all(2*n(1:end-1)<=n(2:end))

```

Try it online!

Thanks to Luis Mendo for `all`. Much shorter!
> 2 votes

# Answer
# Python 3, ~~57~~ \\$\cdots\\$ ~~44~~ 43 bytes

Saved a byte thanks to kaya3!!!

```
lambda l:all(b>=a*2for a,b in zip(l,l[1:]))

```

Try it online!
> 2 votes

# Answer
# PHP, ~~53~~ ~~49~~ ~~47~~ 43 bytes

```
for(;$argv[$i++]*2<=$k=$argv[$i];);echo!$k;

```

Try it online!

-4 bytes thanks to @Kaddath.
> 2 votes

# Answer
# Keg, `-rR`, ~~15~~ 13 bytes

```
1&÷{!;|":'½≤⑾

```

Try it online!

*-2 bytes thanks to @a'\_'*

## Answer History

### 15 Bytes

```
1&÷^{!;|":'2*≥⑾

```

Try it online!

I'm quite happy with this answer, and I'm quite happy with the explanation.

**Explained**

```
1&

```

First, we store the number 1 in the register. This will end up being the means by which the result is shown.

```
÷^

```

We then item split the input list and reverse it, so that things are in descending order.

```
{!;|

```

Now, we start a while loop that will run while the length of the stack - 1 is not zero.

```
":'

```

This bit of the algorithm took me a while to visualise and write... I had to resort to move playing cards around my living room floor to understand which stack shifting mechanics to use.

Lets say the input stack (after item splitting and reversal) is `[4, 2, 1]`. Right shifting the stack (`"`) gives `[1, 4, 2]`, duplicating the top gives `[1, 4, 2, 2]` and then left shifting the stack (`'`) gives `[4, 2, 2, 1]`.

We do this so that we can compare the top of the stack with the next item and preserve that second item (in other words, circumnavigate the side effects of operators consuming stack items).

```
2*≥

```

We then multiply the top item by two and see if the result is greater than or equal to the next item in the series.

The result is then augmented multiplied into the register and the while loop continues.

`-rR` prints the value of the register at the end of execution as an integer.
> 2 votes

# Answer
# Ruby, 31 bytes

```
->l{x,*l=l;l.all?{|y|x*2<=x=y}}

```

Try it online!
> 2 votes

# Answer
# 05AB1E, ~~4~~ 3 bytes

Crossed out 4 is still regular 4 ;(

```
¥›à

```

Outputs `0` for truthy and `1` for falsey.

Port of *@RGS*' first Jelly answer, so make sure to upvote him!
-1 byte thanks for *@Grimmy* for mentioning any two distinct truthy/falsey values are allowed, so I can drop the invert at the end

Try it online or verify all test cases.

**Explanation:**

```
¥    # Get the deltas (forward differences) of the (implicit) input-list
 ›   # Check for each whether it's larger than value at the same position in the (implicit)
     # input-list, which automatically ignores the trailing item of the input
  à  # Get the maximum of this, to check if any are truthy
     # (after which it is output implicitly as result)

```
> 2 votes

# Answer
# Clojure, ~~42~~ 40 bytes

```
(fn[s](every? #(<= 2%)(map /(rest s)s)))

```

Try it online!

Basically the obvious pairwise thing, with a fun way to generate consecutive pairs of a sequence.
> 2 votes

# Answer
# Lua, 54 bytes

```
for i=2,#arg do b=b or arg[i-1]*2>0+arg[i]end print(b)

```

Try it online!

`true` and `false` are swapped.
> 2 votes

# Answer
# Desmos, 41 Bytes

```
f(n)=1-l(n[2n[0...l(n)]>n])
l(n)=n.length

```

Try It Over Here
> 2 votes

# Answer
# PowerShell, 49 bytes

```
param($n)($n|?{$_-ge2*$l;$l=$_}).count-eq$n.count

```

Try it online!

Takes input `$n` then uses a `Where-Object` to pull out those elements that are `-g`reaterthanor`e`qual to `2` times the `$l`ast element. Those are left on the pipeline, and we set our `$l`ast element for the next iteration. We then take the `.count` of that collection and make sure it's `-eq`ual to the `.count` of our input array. That Boolean value is left on the pipeline and output is implicit.

---

If we don't need to worry about negative numbers, we can use the following instead, thanks to mazzy:

# PowerShell, 27 bytes

```
!($args|?{$_-lt2*$l;$l=$_})

```

Try it online!

This again takes input `$args`, and pulls out those items where they're `-l`ess`t`han `2` times the `$l`ast element (i.e., they're not "big enough" to make the doubling sequence). If there are any left, then the Boolean-not surrounding the collection results in `False`, otherwise if the collection is empty we get `True`. That's left on the pipeline and output is implicit.
> 1 votes

# Answer
# , 14 bytes

```
[:*/0.5>:2%/\]

```

Try it online!
> 1 votes

# Answer
# x86-16 machine code, 11 bytes

```
49          DEC  CX                 ; adjust to loop N-1 times
        N_LOOP:
AD          LODSW                   ; load N1 into AX
D1 E0       SHL  AX, 1              ; double AX
39 04       CMP  WORD PTR[SI], AX   ; compare to N2
7C 02       JL   DONE               ; if less, return
E2 F7       LOOP N_LOOP             ; keep looping
        DONE:
C3          RET                     ; return to caller

```

Input array at `[SI]`, length in `CX`. Returns `ZF` if `truthy`, `NZ` if `falsey`.
> 1 votes

# Answer
# GolfScript, 28 bytes

GolfScript has its clunky zip function (I need a lot of code to convert the string to a list of codepoints).

```
.1>]zip);{1/~0=\0=2*<!}%{&}*

```

Try it online!

# Explanation

```
.1>]zip                      # Zip itself with itself without the first item
       );                    # Discard the extra trailing item
         {1/~0=\0=2*<!}%     # Is the first item * 2 greater than or equal to the next item?
                        {&}* # All of them?

```

# GolfScript, 31 bytes

```
.(+{2/}%]zip);{1/{0=}%~>!}%{&}*

```

Try it online!
> 1 votes

# Answer
# Pyth, 11 bytes

```
<1hS/MP.T,t

```

Try it online!

### Explanation

```
<1hS/MP.T,tQQ  # full program, last two Q (=input) are implicit

         ,tQQ  # [Q[1:], Q]
       .T      # Transpose -> [[Q[1],Q[0]], [Q[2],Q[1]], ...,  [Q[-1]]]
      P        # all but last element (gets rid of lone Q[-1])
    /M         # Map all pairs by division
   S           # Sort quotients
  h            # first element (minimum quotient)
<1             # is 1 smaller than this?

```
> 1 votes

# Answer
# Burlesque, 15 bytes

```
raJ0{2.*>=}LO==

```

Try it online!

Finally got an answer where using `LO` is advantageous.

```
ra   # Read as array
J    # Duplicate
0    # 0 (start of loop)
{2.* # Double
 >=  # Greater than or equal to previous elem
}LO  # Loop through array performing op on each pair
     # Push to array if true
==   # Arrays are the same

```

# Burlesque, 16 bytes

Alternative (but longer) solutions using 2-grams and map-reduce

```
ra2CO{./2>=}m^r&
ra2CO{p^./2>=}al

```

Try it online!
> 1 votes

# Answer
# Wolfram Language (Mathematica), ~~25~~ 15 bytes

```
Min@Ratios@#<2&

```

Returns `True` for false and `False` for true.

-10 bytes thanks to @att

Try it online!
> 1 votes

# Answer
# Pip `-r`, 11 bytes

```
$&2*_<=BMPg

```

Try it online!

Takes input numbers separater by newlines. (`-r` flag)

## Explanation

```
$&2*_<=BMPg  g → input
        MP   pass pairs from g to function on the left
  2*_<=B     a ≤ b? for pair (a, b)
$&           Fold with & operator

```
> 1 votes

# Answer
# Proton, 41 bytes

```
a=>all([a[x+1]/a[x]>=2for x:0..len(a)-1])

```

Try it online!

This isn't very efficient because Proton is too buggy to do this right.
> 1 votes

# Answer
# Arturo, ~~29~~ 28 bytes

```
$=>[l:0every?&'x[x>=l*2l:x]]

```

Try it
> 1 votes

# Answer
# Pyt, 6 bytes

```
↔ʁ/2≥Π

```

Try it online!

Outputs 1 if doubling array, 0 otherwise

```
↔           implicit input; flip array
 ʁ/         ʁeduce by division
   2≥       is each element greater than or equal to 2?
     Π      take product of list; implicit print

```
> 1 votes

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

```
rl1)?v1n;n0<
@:$+:<|.!:0^?)

```

Try it

* `r` reverse
* `l1)?` is the length greater than 1?
* `v` then go down
* `1n;` otherwise, output 1 (true)
* `<` go left
* `:+` double
* `$:@` duplicate NOS
* `)?` is NOS greater than TOS?
* `^<0n;` then output 0 (false)
* `0:!.|` go back to start after inverting direction
> 1 votes

# Answer
# StackCell, 16 bytes

`:[{::+}x>?.:]'Y;`

Explanation:

* `:[`: Duplicate the top element of the stack, and then consume the duplicate. If it was non-zero, perform the loop body (up until the next `]`) - else skip the loop body
* `{`: Remove the top element of the stack, and place it in the 'cell' (temporary storage which is overwritten on writes and copied on reads)
* `::+`: Create two duplicates of the top element of the stack (previously the top-but-one element), and add them together to get 2x
* `}`: Put the stored element back on the top of the stack
* `x`: Swap the top two elements of the stack
* `>`: Consume and compare the top two elements of the stack: If the top-most element is larger than the second-most element of the stack, push `1` to the stack, otherwise push `0` to the stack
* `?`: Consume the value on top of the stack, and skip the next instruction (`.`) if and only if the consumed value was 0
* `.`: Halt the program immediately (falsy output)
* `:]`: Duplicate the top value of the stack, then consume the duplicate. If it was non-zero, jump back to the instruction after the matching `[`; otherwise, continue
* `'Y`: Push the character `Y` to the stack, as a byte
* `;`: Print the top value of the stack, as a character
> 1 votes

# Answer
# Nekomata \+ `-e`, 4 bytes

```
∆$i≥

```

Attempt This Online!

```
-e      Check that
∆       the delta
   ≥    is greater than or equal to
 $i     the original list without the last item

```
> 1 votes

# Answer
# C (clang), 38 bytes

Returns 0 for doubling sequences, 1 otherwise.

```
f(*a,s){return--s?*a*2>*++a|f(a,s):0;}

```

Try it online!
> 1 votes

# Answer
# Scala, 48 bytes

Golfed version. Try it online!

```
_.sliding(2).map{case Seq(a,b)=>b/a}.exists(_<2)

```

Ungolfed version. Try it online!

```
object Main {

  def f(x: List[Double]): Boolean = {
    x.sliding(2).map { case List(a, b) => b / a }.exists(_ < 2)
  }

  def main(args: Array[String]): Unit = {
    val data = List(
      List(10.0, 20.0, 30.0),
      List(10.0, 20.0, 40.0),
      List(1.0, 2.0, 3.0),
      List(1.0, 2.0, 4.0),
      List(1.0, 2.0, 10.0),
      List(1.0, 1.0),
      List(10.0, 1.0)
    )

    println(data.map(f))
  }
}

```
> 1 votes

# Answer
# Desmos, 27 bytes

```

f(l)=\{l[2...]<2l,0\}.\max

```

Returns `0` for doubling sequences and `1` for non-doubling sequences.

Try It On Desmos!

Try It On Desmos! - Prettified
> 1 votes

# Answer
# Vyxal `G`, 3 bytes

```
¯>Ṫ

```

Try it Online!

A port of 05AB1E

## Explained

```
¯>Ṫ
¯   # deltas
 >  # greater than original input
  Ṫ # last item removed
# G flag gets biggest item.

```
> 1 votes

# Answer
# Kotlin, 50 bytes

```
{a:IntArray->(0..a.size-2).first{a[it]*2>a[it+1]}}

```

Try it online!

`Int` for false and `Nothing` for true (throws `NoSuchElementException`)
> 1 votes

# Answer
# Retina 0.8.2, 28 bytes

```
\d+
$*
((^|,(?=\3\3))(1+))+$

```

Try it online! Link includes test cases. Explanation:

```
\d+
$*

```

Convert to unary.

```
  ^|

```

On the first repeat, match at the beginning, otherwise...

```
    ,(?=\3\3)

```

... match a comma followed by a number which is at least twice as big as the previous match.

```
              (1+)

```

Capture the number so that it can be compared on the next repeat.

```
(                 )+$

```

All entries in the list need to satisfy the above conditions.
> 0 votes

# Answer
# Clojure, 89 bytes

```
(fn[x](#(cond(empty? %)true(>=(first %)(* %2 2))(recur(rest %)(first %)):else false)x 0))

```

Try it online!

The obvious (and longest) solution to the problem.
> 0 votes

# Answer
# Perl 5 `-apl -MList::Util=reduce`, 26 bytes

```
reduce{$_&&=$a<=$b/2;$b}@F

```

Try it online!
> 0 votes

# Answer
# Python 3, 52 bytes

```
lambda l:all(2*l[i]<=l[i+1]for i in range(len(l)-1))

```

Try it online!
> 0 votes

# Answer
# Zsh, 29 bytes

```
(($1*2<=$2))&&${=3+$0 ${@:2}}

```

Try it online!

```
(($1*2<=$2))&&     # return false if 2 * $1 > $2
  ${=3+$0 ${@:2}}  # recursive call:
  ${ 3+         }  # if there is a third parameter
       $0 ${@:2}   # ... substitute the program name ($0), " ", "$2 $3 $4 "...
  ${=           }  # ... then split on spaces

```

In cases like `a &&` or `b ||`, Zsh will simply return with the exit code of the previous command.
> 0 votes

# Answer
# Python 3, 52 bytes

```
lambda l:all(l[i-1]*2<=l[i]for i in range(1,len(l)))

```

Try it online!
> 0 votes

# Answer
# APL (Dyalog Extended), 18 bytes

```
∧/{(2×¯1↓⍵)≤(1↓⍵)}

```

Try it online!

Decomposition/Explanation:

```
⍵ is the input vector (test cases). Output will be 1 or 0; 1 is TRUE/truthy, 0 is FALSE/falsey.

            (1↓⍵)  - Drop the first element from the input vector (call it LASTN)
      ¯1↓⍵         - Drop the last element from the input vector, separately, and
   (2×    )        - multiply it by two (call the result DFIRSTN)
           ≤       - compare corresponding elements - Each element of LASTN should be
                     equal to or greater than the corresponding element of DFIRSTN.
  {              } - encapsulate as a dfn to apply to the input vector. This dfn will
                     return 0 for elements where the comparison is FALSE, 1 where TRUE
∧/                 - AND (Boolean conjunction) reduction of the vector. ∧/ A B C D ... is
                     equivalent to A ∧ B ∧ C ∧ D ∧ ..., and if there are any FALSE values
                     in the vector, the result will be FALSE (0)

```

The linked TIO has the test cases and a REPL; you can test your own vectors by changing the input field, one vector per line.
> 0 votes

# Answer
# C (gcc), 51 bytes

```
r;f(a,l)int*a;{for(r=--l;l--;)r=*a*2>*++a?0:r;a=r;}

```

Pretty simple. For every element of the array, check if the current element times two is greater than the next element.

Returns zero if it is not a doubling sequence and non-zero (or more specifically the length minus one) otherwise.

*-10 bytes thanks to ceilingcat!*

Try it online!
> 0 votes

# Answer
# C++ (gcc), 75 71 67 65 bytes

```
int f(int*a,int s){int r=1;for(;--s;)r*=a[s]>=2*a[s-1];return r;}

```

Try it online!
> 0 votes

# Answer
# T-SQL, 64 bytes

This can handle positive values above 0

Returns -1 for true, 0 for false

```
SELECT~min(1/~x)FROM(SELECT a/lag(2*a)over(ORDER BY i)x FROM @)y

```

**Try it online**
> 0 votes

# Answer
# Rockstar, ~~101~~ 100 bytes

```
listen to F
D's0
while F
listen to T
let R be F/T-.5
turn up R
let D be D or R
let F be T

say not D

```

Try it here (Code will need to be pasted in, with each input integer on an individual line)
> 0 votes

# Answer
# Thunno 2 `S!`, 4 bytes

```
Ṣ$ṫ<

```

Try it online! Link is to verify all test cases.

#### Explanation

```
Ṣ$ṫ<  # Implicit input
Ṣ     # Deltas of input
 $ṫ   # Input without last item
   <  # Compare the two lists
      # Check if the sum is 0
      # Implicit output

```
> 0 votes

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


title: Are the brackets fully matched?

text:
# Question
Title: Are the brackets fully matched?
You must write a program or function that takes a string of brackets and outputs whether or not that string is fully matched. Your program should print a truthy or falsy value, and IO can be in any reasonable format.

# Rules and definitions:

* For the purpose of this challenge, a "bracket" is any of these characters: `()[]{}<>`.
* A pair of brackets is considered "matched" if the opening and closing brackets are in the right order and have no characters inside of them, such as

```
()
[]{}

```

Or if every subelement inside of it is also matched.

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

```

Subelements can also be nested several layers deep.

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

```
* A string is considered "Fully matched" if and only if:

1. Every single character is a bracket,
    2. Each pair of brackets has the correct opening and closing bracket and in the right order, and
    3. Each bracket is matched.
* You may assume the input will only contain printable ASCII.

# Test IO

Here are some inputs that should return a truthy value:

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

```

And here are some outputs that should return a falsy value:

```
(               Has no closing ')'
}{              Wrong order
(<)>            Each pair contains only half of a matched element
(()()foobar)    Contains invalid characters
[({}<>)>        The last bracket should be ']' instead of '>'
(((()))         Has 4 opening brackets, but only 3 closing brackets.

```

As usual, this is code-golf, so standard loopholes apply, and shortest answer in bytes wins.

# Answer
# 05AB1E, 19 bytes

Input is given in *quotes*. Code:

```
"[](){}<>"2÷)"":g2Q

```

Well crap, a *lot* of bugs and unimplemented features were found. Explanation:

```
"[](){}<>"           # Push this string
          2÷         # Split into pieces of two
            )        # Wrap it into an array (which should not be needed)
             ""      # Push an empty string
               :     # Infinite replacement

```

This is actually a tricky part. What this looks like in pseudocode is:

```
input().replace(['[]', '()', '{}', '<>'], "")

```

This is covered by this part from the 05AB1E code:

```
if type(b) is list:
    temp_string = temp_string_2 = str(a)
    while True:
        for R in b:
            temp_string = temp_string.replace(R, c)
        if temp_string == temp_string_2:
            break
        else:
            temp_string_2 = temp_string
    stack.append(temp_string)

```

As you can see, this is **infinite replacement** (done until the string doesn't change anymore). So, I don't have to worry about setting the replacement into a loop, since this is already builtin. After that:

```
                g    # Take the length of the final string
                 2Q  # Check if equal with 2 (which are the quotes at the end)

```

Uses **CP-1252** encoding. Try it online! (slightly modified because the above version is deprecated).
> 17 votes

# Answer
# Brain-Flak, ~~1101, 1085~~, 981 bytes

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

```

Try it online!

This is 980 bytes of source code, and `+1` for the `-a` flag allowing ASCII input (but decimal output)

This is an answer I've been wanting to write for a *very very* long time. At least 6 months. I waited to post this because I knew that answering this challenge would be extra hard in brain-flak. But it's worth it for one very important reason: The source code itself is a truthy input, which is the entire point of this language itself.

And as I wrote about here, this question was what inspired me to write brain-flak.

> Shortly after I wrote Are the brackets fully matched?, it made me wonder how much information you can store with only matched brackets. One thing that stood out to me, was that even though you only have 4 "atoms" of sorts:
>
> ```
> (){}[]<>
>
> ```
>
> you really have 8 units of information to convey, since each of these bracket types can be empty, or have other brackets in between, which are fundamentally different pieces of information. So, I decided to write a language that only allowed for matched brackets, and where empty brackets convey something different than brackets with other brackets inside of them.

This answer took roughly two hours to write. I'll admit it's pretty poorly golfed, mostly because a lot of the code is repeated for each bracket type. But I'm mostly amazed that I was able to write an answer at all, especially given that Brain-Flak is

> A minimalist esolang designed to be painful to use

I'm going to attempt to golf it down later, but I wanted to get this out there anyway.

I have a detailed explanation, but it's about 6 thousand characters long, so I think it would not be wise to paste the entire thing into this answer. You can read through it here if you want. I'll add a shorter explanation here.

The basic idea, is that we repeat the following steps for every character on the stack:

* We check each character to see if it matches any bracket. If it is an opening bracket, we push a number onto the other stack according to the following mapping:

```
( = 1
< = 2
[ = 3
{ = 4

```
* Then we check to see if it matches any closing bracket. If it does, we push the equivalent number onto the alternate stack, just like for opening brackets. *Then*, we check if the top two numbers are equal. If they are, the both get popped and the program continues as normal. If they are not, we clear both stacks (to stop the looping) and push a one onto the alternate stack. This is essentially a "break" statement.
* After checking the 8 bracket types, we push the value of this run through the loop. Since we zero out most of it, the only snippets that have any value are the conditionals when we compare against brackets. So if any bracket is matched, the whole loop has a value of 1. If none of them did, the whole loop has a value of 0. In this case, we will clear both stacks and push a 0 onto the alternate stack. Again, this is like a "break" statement.

After this main loop is running, the rest is fairly simple. We are on the (empty) main stack, and the alternate stack is empty (if the brackets were matched) or non-empty if they were not. So we run this:

```
#Toggle to the alternate stack
<>

#Push this stack-height onto main-stack
([]<>)

#Logical not
({}<(())>){((<{}{}>))}{}

```

This will push a 0 or a 1 onto the main-stack, and when the program ends it is implicitly printed.

---

* *Thanks to @WheatWizard for coming up with a good stack-clean "equals" and "logical not" snippet, and for regularly updating the github wiki with useful examples.*
* *Thanks to @ASCII-only for writing an online integer metagolfer which helped immensely in writing this program*

---

*revisions*

* *Removed some push pop redundancy*
* *Changed my zero counter logic*
> 40 votes

# Answer
# Brain-Flak, ~~204~~ ~~196~~ 190 bytes

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

```

Try it online!

-8 bytes thanks to Wheat Wizard. -6 bytes thanks to Jo King.

### Explanation

This program stores the character codes of all current unclosed brackets on the second stack. The bracket pairs `<>`, `[]`, and `{}` each have character codes that differ by exactly 2, so there is no need to check for them specifically. The pair `()` only differs by 1, so we check for `(` specifically, and effectively decrement that byte (actually increment every other byte) before continuing.

```
# While there are bytes left to process
{

 # Move byte to second stack
 ({}<>)<>

 # Push 40, 0, 40, 60, 91, 123: (, then null, then all four opening brackets
 ((((()()()()()){})(({}){})())({}(({})((({}){})(<()>))))())

 ((

   # For each opening bracket type:
   {

    # Evaluate as zero
    <

     # Compute difference between bracket type and input byte
     ({}<>[({})])

    >

    # Evaluate loop iteration as -1 if equal, 0 otherwise
    [()]{()(<{}>)}{}<>

   }

   # Remove the 0 that was inserted to terminate that loop
   {}

   # Add 1 to result
   ()

   # Evaluate rest of this expression as zero
   <

    # Determine whether the byte is open parenthesis
    ({}<>[({})])

    # If not:
    {

     # Add 1 to byte and break if
     (<{}({}())>)

    }{}

    # Return to main stack
    <>

   >

 # Push result twice (0 if matched an opening bracket, 1 otherwise)
 ))

 # If byte was not an opening bracket:
 {

  # Push zero to break out of if
  (<

    # Push (open bracket + 2 - byte) below that zero
    ({}{}<>[{}]{}<>)

  >)

 }{}

 # If byte was neither an opening bracket nor the appropriate closing bracket:
 {

  # Clear alternate stack and stay there to break out of main loop early
  <>{{}}

 }{}

# End of main loop
}

# If a prefix was invalid, the top of the other stack is the same nonzero value
# that made us break out in the first place. If the string was a valid prefix,
# the other stack contains every unclosed bracket.  If the string is balanced,
# there are none of these. Thus, the other stack is empty if the
# brackets are balanced, and has a nonzero value on top otherwise.

# Push 1 on other stack if empty, and 0 on current stack otherwise
<>((){[()]<>})

```
> 30 votes

# Answer
## JavaScript (ES6), ~~52~~ 50 bytes

```
f=s=>(t=s.replace(/\(\)|\[]|{}|<>/,''))==s?!s:f(t)

```

Repeatedly remove brackets until the result is the same as the original, then return false unless the string is now empty.

Edit: Saved 2 bytes thanks to @edc65.
> 16 votes

# Answer
## Python, 67 bytes

```
lambda s:eval("s"+".replace('%s','')"*4%([],(),{},'<>')*len(s))==''

```

Generates and evals an expression that looks like

```
s.replace('[]','').replace('()','').replace('{}','').replace('<>','').replace('[]','').replace('()','').replace('{}','').replace('<>','')

```

and checks if the result is empty.

Sp3000 saved 8 bytes by pointing out that `[],(),{}` can be subbed in without quotes because they're Python objects, and that two parens were unneeded.
> 14 votes

# Answer
# Retina, 20 bytes

```
+`\(\)|\[]|{}|<>

^$

```

Try it online
> 11 votes

# Answer
## CJam, ~~25~~ ~~24~~ ~~23~~ 21 bytes

*Thanks to Sp3000 for saving 2 bytes.*
*Thanks to jimmy23013 for saving 2 bytes.*

```
q_,{()<>}a`$2/*{/s}/!

```

Test suite.

Works essentially the same as the other answers: we repeatedly remove `()`, `[]`, `<>` and `{}` from the string and check if we end up with the empty string. To avoid having to check when we're done, we remove the pairs `N` times where `N` is the length of the string, which is always sufficient (since each iteration will remove at least two characters, unless we're done). I'm glad to see that this doesn't beat Retina. :) (Although Pyth or Jelly might...)

There's one fun golfing trick here: to get the string `()<>[]{}` we use the following:

```
{()<>}a`$

```

The, `{()<>}` is just a block (i.e. a function), which contains the other brackets as code. With `a` we wrap the block in an array. The ``` stringifies that array, which gives `"[{()<>}]"`. Finally, we sort the string with `$`, which rearranges the brackets to `()<>[]{}`.
> 11 votes

# Answer
# Yacc, 119 bytes

Does not use regex/replace.

```
%%input:r;r:%empty|'['r']'r|'{'r'}'r|'('r')'r|'<'r'>'r;%%yylex(){return getchar();}main(){return yyparse();}yyerror(){}

```

## Ungolfed

```
%%                              # Grammar in BNF
input:
  r;
r:
  %empty
| '['r']'r
| '{'r'}'r
| '('r')'r
| '<'r'>'r;
%%                              # Minimal parser invocation and lexer
yylex(){return getchar();}
main(){return yyparse();}
yyerror(){}

```

## Compilation

```
yacc -o bracket.c bracket.y
cc -o bracket bracket.c

```

## Usage

```
~/ % echo -n "<()[]>" | ./bracket
~/ %
~/ % echo -n "{" | ./bracket
~/ 1 %                                                                         :(

```
> 8 votes

# Answer
## Pyth, ~~31~~ ~~25~~ 24 bytes

Golfed down to 25 bytes thanks to FryAmTheEggMan Removed 1 byte

```
VQ=:Q"<>|\[]|{}|\(\)"k;!

```

Try it here: Test suite !

I'm still a Pyth newbie, any help is appreciated.

## Explanation

```
VQ                         For N in range(0, len(z)), with Q being the evaluated input.
                           Optimal solution would be to use range(0, len(z)/2) instead, but it add two bytes.
  =:Q"<>|\[]|{}|\(\)"k     assign Q without {}, [], <> nor () (regex replacement) to Q
                      ;    End of For loop
                       !   Logical NOT of Q's length (Q is the input, but has gone several times through y, and Q is implicit).
                           This last operation returns True if len(Q) is 0 (which means all brackets were matched), False otherwise

```

BTW, congrats to the other Pyth answer (which is currently 20 bytes)
> 7 votes

# Answer
# Pyth, 20 bytes

```
!uuscNTc"[](){}<>"2G

```

Try it online: Test Suite

Repeatedly removes occurrences of `[]`, `()`, `<>` and `{}` by splitting and re-merging. Checks if the resulting string is empty or not.
> 6 votes

# Answer
# Javascript ES6, 54 bytes

```
f=_=>_.match(x=/\(\)|\[]|{}|<>/)?f(_.replace(x,'')):!_

```

Uses a recursive replace implementation. Simple enough.
> 5 votes

# Answer
# Brain-Flak, 204 bytes

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

```

Try it online!

Not quite as short as Nitroden's answer, but uses a very different approach. This one runs through the input repeatedly, removing neighbouring matching pairs of brackets each time until there are none left. At that point if there is anything left on the stack, then the string was not fully matched.

### Explanation:

```
(())  Push 1 to simulate the check at the start of the loop
{  While check
	{}           Pop check
	{({}<>)<>}<> Reverse input
	({           Loop over input
		< Don't push the values of these calculations
		(<(({})<>)>)  Create a copy of the top of the input and push to the other stack
		(((((
		((([(())()()()]){}){}){}())
		(()))
		(((())()){}()){})
		){})          Push the differences in values of the end brackets
		(({<(({}<>{}[()]))>(){[()](<{}>)}{}<>}{}))  If the copy is the same as any of these, push the difference between the other bracket twice
		<>{}<>  Pop copy
		{  If this character is a start bracket
			{}({}[({})]<>({}))  Check if the next character is the end bracket
			{(<>)(<>)}{}          If not, push a 0 to each stack as buffer
			{}       Pop the top of the input stack, either the start bracket if they matched or the buffer 0
			(<>)     Push 0 to other stack to end check
		}{}>
		{}   Pop the top of the other stack
		         If the character was not an end bracket, pop the copy of check, which is 0
		         If it was, but didn't match the next character, pop the buffer 0
		         If the brackets matched, pop the end bracket and add it to the loop total
	<>}	Repeat with the rest of the input
	<>)	Push the loop total
		If any brackets were matched, the loop total is non zero
}{}
((){<>[()]}) If there is anything left on the stack, push 0 to the other stack, otherwise push 1

```
> 5 votes

# Answer
# Regex (PCRE flavor), ~~41~~ 37 bytes

```
^((<(?1)>|{(?1)}|\[(?1)]|\((?1)\))*)$

```

Just a standard solution with recursive regex.

*Thanks jimmy23013 for shaving off 4 bytes*
> 4 votes

# Answer
# Perl, ~~34~~ 33 bytes

Includes +2 for `-lp`

Run with input on STDIN:

```
./brackets.pl <<< "{<>()}"

```

`brackets.pl`:

```
#!/usr/bin/perl -lp
s/\(\)|\[]|<>|{}//&&redo;$_=!$_

```

Finds the first bracket pair without anything between them and removes it as long as there are any. Then checks if the final string is empty.
> 4 votes

# Answer
## Brainfuck, 132 bytes

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

```

Formatted:

```
+>,
[
  [<-> >+>[-]<<-]
  <
  [
    not matching closing bracket
    >+>[<+<+>> >+<-]
    +++++[>--------<-]
    >
    [
      not open paren
      <<+>
      ++++[>-----<-]>
      [
        not open angle bracket
        <+++++[>------<-]>-
        [
          not open square bracket
          <++++[>--------<-]>
          [
            not open brace
            ,>
          ]
        ]
      ]
    ]
    <
  ]
  ,
]
<<[>]
>.

```

Expects input without a trailing newline. Prints `\x00` for false and `\x01` for true.

Try it online.

Approach: Maintain a stack starting with `\x01`, and push the corresponding closing bracket whenever an opening bracket is encountered. Before checking whether the current character is an opening bracket, first check whether it's equal to the closing bracket at the top of the stack, and if so pop it. If it's neither the proper closing bracket nor an opening bracket, consume the rest of the input while moving the pointer to the right. At the end, check whether the pointer is next to the initial `\x01`.
> 4 votes

# Answer
# Java 7, ~~156~~ 151 bytes

```
class A{public static void main(String[]a){for(int i=0;i<-1>>>1;++i,a[0]=a[0].replaceAll("<>|\\[]|\\(\\)|\\{}",""));System.out.print(a[0].isEmpty());}}

```

I'm not expecting this to win any awards but I didn't see a Java answer yet. Additionally, I like to lurk around PPCG and I would enjoy being able to vote/comment on other answers.

Input is given as program parameters. This follows the same format as many other answers here in that it preforms a regex replacement in a loop. Originally I had it loop N times where N is the length of the original string but looping to `Integer.MAX_VALUE` is shorter :\]. This should be ok because `Integer.MAX_VALUE` is the maximum length of a `String` in Java so there's an implicit assumption that the length of input is something that is handle-able by Java. The runtime is pretty bad (took about 20 minutes on my lappytop) on account of the loop but I didn't see any restriction on that.
> 3 votes

# Answer
# Haskell, 151 bytes

```
infix 1#
'(':x#y=x#')':y
'<':x#y=x#'>':y
'[':x#y=x#']':y
'{':x#y=x#'}':y
')':x#')':y=x#y
'>':x#'>':y=x#y
']':x#']':y=x#y
'}':x#'}':y=x#y
""#""=1
_#_=0

```

Try it online!
> 3 votes

# Answer
# C, ~~121~~ ~~122~~ 114 bytes

Shaved of 8 bytes thanks to @xsot!

```
a[99],i,k;main(c){for(;read(0,&c,!k);c%7&2?k|=a[i--]^c/9:(a[++i]=c/9))k|=!strchr("()[]{}<>",c);putchar(48+!k*!i);}

```

Uses a stack.
> 2 votes

# Answer
## Grime v0.1, 34 bytes

```
M=\(M\)|\[M\]|\{M\}|\<M\>|MM|_
e`M

```

Prints `1` for a match and `0` for no match. Try it online!

## Explanation

Grime is my 2D pattern-matching language designed for this challenge; it can also be used to match 1D strings. This is my first answer with it. I did modify Grime today, but only to change the character of one syntax element (``` instead of `,`), so it doesn't affect my score.

```
M=                         Define pattern called M that matches:
\(M\)|\[M\]|\{M\}|\<M\>      a smaller M inside matched brackets,
|MM                          or two smaller Ms concatenated,
|_                           or the empty pattern.
e`M                        Match the entire input against M.

```
> 2 votes

# Answer
## PowerShell v2+, ~~63~~ 62 bytes

```
param($a)for(;$a-ne$b){$a=($b=$a)-replace"\[\]|\(\)|<>|{}"}!$a

```

Can't quite catch JavaScript, but is currently edging out the other non-esolangs.

Similar approach as other answers: a simple loop that continues so long as we can remove one of `[]`, `()`, or `<>` (with several extraneous characters because we need to escape the regex specials). We use `$b` as a helper along the way to remember what our previous loop's `$a` was set as. An uninitialized variable is `$null`, so the first time the loop is encountered, `$a` is obviously not equal to `$null`.

At the end of the loop, `$a` is either empty or not, and the Boolean-not of that string is either `True` or `False`.

### Example

```
PS C:\Tools\Scripts\golfing> .\are-the-brackets-fully-matched.ps1 "[({})]"
True

PS C:\Tools\Scripts\golfing> .\are-the-brackets-fully-matched.ps1 "[({])}"
False

```
> 2 votes

# Answer
# Reng v.3.3, 137 bytes, noncompeting

Try it here!

```
aií0#zl2,q!~1ø
:"]"eq!v:"}"eq!v:">"eq!v:")"eq!v)1z+#z
ve¤[2-2<       <       <     +1<
>]?v$$$zÀ0#z >ðq!vlqv¤l2%[1Ø
   \$2+)1z+#z/   ~n1/

```

There's a bit more golfing to be done, but at least it works. I added a command `ð` to keep track of stacks after this challenge in order for this to be remotely possible/easily. I'll explain this in a bit, but it generally keeps track of all strings iterated over and looks for repeats; if there is a repeat, then the string is irreducible. Otherwise, the string will be reduced to the empty string/stack, and will output `1`. Otherwise, no output will be produced.
> 2 votes

# Answer
### Python 2.7, 96 bytes

```
def r(s):i=max(map(s.find,['()','[]','{}','<>']));return not len(s)if i<0 else r(s[:i]+s[i+2:])

```
> 2 votes

# Answer
# R, 298

```
function(.){s=strsplit;u=paste0;.=s(.,"")[[1]];p=s("><)(}{][","")[[1]];.[!.%in%p]="§";for(i in 1:4*2){.[.==p[i]]=sprintf("S('%s',{",p[i]);.[.==p[i-1]]=sprintf("},'%s');",p[i])};S=function(H,B,T)if(H!=T)stop();r=try(eval(parse(,,u(.,collapse=""))),1);if(inherits(r,"try-error"))FALSE else TRUE}

```

The approach here is to convert the sequence into R code, and then try to parse and evaluate it. If that gives an error, then return `FALSE`.

But there is a minor problem ... R's rules for brackets are different, so `<` and `>` are not brackets at all, and the other types have rules of their own. This is solved by a revolutionary approach -- a squeaking function, whose only function is to signal an error if its head and tail squeak in different ways.

For example, `[]` is transformed into `S('[', {}, ']')`, where S is defined as ...

```
S=function(H,B,T)if(H!=T)stop()

```

Because the head squeak and tail squeak match, no error is thrown.

A few other examples (the left part is a sequence of brackets and right part is its transformation into valid R code that can be evaluated):

```
[}     -->  S('[', {}, '}')     # squeaks an error
[()]   -->  S('[', {S('(',{},'(')}, "[")
({[]}) -->  S('(',{S('{',{S('[',{},'[');},'{');},'(');

```

Some other sequences of brackets will result in parse errors:

```
[[)    -->   S('[',{S('[',{},'(');

```

So the remaining part just catches the errors and returns FALSE if there are any, and TRUE if there are none.

The human-readble code:

```
 sqk <- function(.){
   s=strsplit;u=paste0
   .=s(.,"")[[1]]            # break the argument up into 1-character pieces
   p=s("><)(}{][","")[[1]]   # vector of brackets
   .[!.%in%p]="§"            # replace anything besides brackets by § (--> error)
   for(i in 1:4*2){
     .[.==p[i]]=sprintf("S('%s',{",p[i])    # '<' -->   S('<',{     ... etc
     .[.==p[i-1]]=sprintf("},'%s');",p[i])  # '>' -->   },'<');     ... etc
   }
   S=function(H,B,T)if(H!=T)stop()          # define the working horse
   r=try(eval(parse(,,u(.,collapse=""))),1) # evaluate the sequence
   if(inherits(r,"try-error"))FALSE else TRUE   # any errors?
   }

```

Applying it on sample cases:

```
truthy<-readLines(textConnection("()
[](){}<>
(((())))
({[<>]})
[{()<>()}[]]
[([]{})<{[()<()>]}()>{}]"))
falsy<-readLines(textConnection("(
}
(<2)>
(()()foobar)
[({}<>)>
(((()))"))
> sapply(truthy,sqk)
                      ()                 [](){}<>                 (((())))
                    TRUE                     TRUE                     TRUE
                ({[<>]})             [{()<>()}[]] [([]{})<{[()<()>]}()>{}]
                    TRUE                     TRUE                     TRUE
> sapply(falsy,sqk)
           (            }        (<2)> (()()foobar)     [({}<>)>      (((()))
       FALSE        FALSE        FALSE        FALSE        FALSE        FALSE

```
> 2 votes

# Answer
# Julia, 51 bytes

```
~z=z==(n=replace(z,r"\(\)|\[]|{}|<>",""))?z=="":~n

```

The least insane of several options. Unsurprisingly, leveraging the power of regex is the shortest path to string matching, but this really only applies if the pattern to match is regular. Trying to do PCRE recursive patterns ends up ballooning the size of the code, either by seeing if the whole string is the match or by anchoring the ends and then creating a construct to specify the inner body for regex recursion. Neither of which are pretty or conducive to code golf.

## Explanation:

```
~z=                            # Define ~z to be the following:
    z==(                       # If z is equal to
        n=replace(z,           # z with the replacement of
            r"\(\)|\[]|{}|<>", # adjacent matching brackets ((),[],{}, or <>)
            ""                 # with empty strings
        )                      # (which is assigned to n)
    )?z==""                    # whether z is an empty string
    :~n                        # else ~ applied to the substituted string

```

The function repeatedly removes adjacent pairs of parentheses from its only argument, and returns true if it can derive an empty string this way.
> 2 votes

# Answer
# Lua (92 bytes)

The older Lua answer is everything but golfing code. There's my proposal instead:

```
function x(s)m=""return s:gsub("%b<>",m):gsub("%b[]",m):gsub("%b{}",m):gsub("%b()",m)==m end

```
> 2 votes

# Answer
# Stax, ~~11~~ 10 bytes

```
é:råvm∟&1Γ

```

Run and debug it

Got lucky, as stax has a literal constant in it with matched pairs of brackets.
> 2 votes

# Answer
# Curry, ~~64~~ 56 bytes

*Tested to work in both PAKCS and KiCS2*

```
f(x:a++y:b)|elem[x,y]["{}","<>","[]","()"]=f a*f b
f""=1

```

Try it on Smap!

Try it online!

This returns `1` if string is balanced and nothing otherwise.

## Explanation

Our definition of `f` then matches the empty string as balanced for a base case:

```
f""=1

```

Then we have the main logic:

```
f(x:a++y:b)|[x,y]=:=anyOf["{}","<>","[]","()"]=f a*f b

```

Here `*` is used like a logical and. Since the only value we can get back is `1`, this always gives back `1` when it finds results. But when it doesn't this doesn't give any result.

With that this pattern matches strings with a pair of matching brackets so that they divide the input into two balanced strings.
> 2 votes

# Answer
# C, 258 bytes

```
#define E else if(a==
#define D(v) {if (b[--p]!=v)z=1;}
#define F b[p++]=
main(a, v) char* v[]; {char b[99],p=0,z=0;for(;*v[1];v[1]++) {a=*v[1];if(a=='(')F 0;E '[')F 1;E '{')F 2;E '<')F 3;E '>')D(3)E '}')D(2)E ']')D(1)E ')')D(0)else z=1;}puts(z|p?"0":"1");}

```

## Degolfed, macro-substituted, commented

<pre><code>
int main(int a, char* v[]) {
//           ^ this variable is used as a general purpose int variable and not as its intended purpose (argc)

    char b[99], // create a 99 byte array for storing bracket types
        p = 0, // pointer within the array
        z = 0; // error flag

    // loop through every byte of input (argv[1])
    for(;*v[1];v[1]++) {
        a=*v[1];// a is the current byte

        if(a=='(') b[p++] = 0; // record bracket type
        else if(a== '[') b[p++] = 1;
        else if(a== '{') b[p++] = 2;
        else if(a== '<') b[p++] = 3;
        else if(a== '>') {
            if (b[--p] != 3) z = 1; // error: bracket type mismatch
        } else if(a== '}') {
            if (b[--p] != 2) z = 1;
        } else if(a== ']') {
            if (b[--p] != 1) z = 1;
        }else if(a== ')') {
            if (b[--p] != 0)z = 1;
        }else z = 1; // error: invalid character
    }

    // if either z or p is not 0 print a '0', otherwise print a '1'
    // if p is not zero that means not all brackets were closed
    // if z is not zero that indicates an erro
    puts(z|p ? "0":"1");
}

```
</code></pre>
> 2 votes

# Answer
# Kotlin, ~~100~~ ~~89~~ 86 bytes

-11 bytes: Use `any` instead of `firstOrNull`
-3 bytes: Use `chunked` instead of `split` (thanks to @leo848)

```
fun f(s:String):Boolean="()<>[]{}".chunked(2).any{it in s&&f(s.replace(it,""))}||s==""

```

Try it online!
> 2 votes

# Answer
# Python 2, 80 bytes

```
def m(s,i=0):exec's=s.replace("[({<])}>"[i%4::4],"");i+=1;'*4*len(s);return"">=s

```
> 1 votes

# Answer
# sed, 39 36 bytes (34 for code, 2 for -r)

```
:a
s/\(\)|\[]|<>|\{}//;ta
/./c0
c1

```

Try it online!

sed version of what appears to be the standard approach. Requires extended regular expressions (`sed -r`)

Saved 3 bytes thanks to Cows quack
> 1 votes

# Answer
# 05AB1E, 9 bytes

```
žu2ôõ:g2Q

```

Input is given in quotes.

Try it online!

Explanation:

```
žu          # Push "()<>[]{}"
  2ô        # Split into pieces of size 2
    õ       # Push empty string
            # Implicit input
      :     # Infinite replacement
       g2Q  # Is length equal to 2?
            # Implicit print

```
> 1 votes

# Answer
# K (ngn/k), ~~32~~ 29 bytes

-3 bytes thanks to @coltim

```
~#{x{""/y\x}/4 2#"()[]{}<>"}/

```

Try it online!

`{` `}` a function with argument `x`

`4 2#"()[]{}<>"` split to 4 strings of length 2: `("()";"[]";"{}";"<>")`

`x{`..`}/` starting with `x`, go through the list of pairs and apply the function in `{` `}` with the previous result as `x` and the current pair as `y`

`{""/y\x}` split `x` on occurrences of `y` and join with `""` \- effectively remove all occurrences of `y`

`#` length

`~` is 0? (logical not)
> 1 votes

# Answer
## Unix TMG, 83 bytes

Another compiler-compiler solution (in addition to Yacc).

```
p:s parse((any(!<<>>)|={<1>}));s:b s/d;d:;b:<[>x<]>|<{>x<}>|<(>x<)>|<<>x<>>;x:s|();

```

Unlike Yacc, it works by recursive-descent parsing. It outputs "1" on success, nothing – otherwise.

Expanded:

```
p: s parse((any(!<<>>)|={<1>}));
s: b s/d;d:;
b: <[>x<]>|<{>x<}>|<(>x<)>|<<>x<>>;
x: s|();

```
> 1 votes

# Answer
# Stax, <sup>~~19~~</sup> 12 bytes

```
æöT┴S○♂èα ôG

```

Run and debug it

Link is to unpacked code.

-7 using a brackets builtin.

## Explanation

```
c%{Vb2/{z:rF}*!
c%              get the input's length
  {         }*  execute this block that many times:
   Vb           take the brackets
     2/         groups of 2
       {   F    for each:
        z:r     replace the brackets with nothing
              ! logical not

```
> 1 votes

# Answer
# Husk, ~~23~~ 18 bytes

*Edit -5 bytes thanks to Leo*

```
¬ω`Ḟ`σøC2"()[]{}<>

```

Try it online!

**How?**

```
¬ωλ◄Lmλσ⁰ø²)C2"()[]{}<>
¬                     # logical NOT of (note NOT of a non-empty string is 0):
 ωλ                   # result of repeating the following operation
                      # until it reaches a periodic (in this case fixed) resut:
   `Ḟ                 # fold over
         C2           # each pair x from
           "()[]{}<>  # the string "()[]{}<>",
                      # with starting value equal to the (implicit) input,
                      # and using the function:
      `σø             # substitute x to null in the last value

```
> 1 votes

# Answer
# JavaScript (Node.js), 97 bytes

Solution without regex, so it can't really compete in terms of shortness.

```
s=>[...s].every(c=>(i="([{<)]}>".indexOf(c))<0?0:i<5?a+=i:a%10-i+4==0?a=""+(a/10|0):0,a="")&&a<1

```

Try it online!

---

This solution uses a string as if it were a stack.
We push by concatenating 1, 2, 3 or 4 for `([{<` respectively, we check the last value by using modulo 10, and pop it by dividing by 10 if there is a match between the last opening bracket seen and the current closing bracket (an opening bracket is kept forever in the stack if it's not matched).
If there is any closing bracket that doesn't match or if there is any unauthorized character at all, the entire result will be falsed.
The unprintable `SOH` character is used as padding to never have a `0` in the stack (OP guaranteed that no unprintable character would be in the input). It's necessary to avoid confusing the empty stack `""` with a stack potentially full of zeroes, in the condition below.
The `a<1` is to check that all the necessary closing brackets have been encountered (which is equivalent to checking if the stack has been successfully emptied at the end).
> 1 votes

# Answer
## Clojure, 153 bytes

Longer than even C and Brainfuck answers :o

```
(defn f[[s & r]](if s(let[[a b](split-at(.indexOf(reductions + 1(for[c r](get(zipmap[s({\(\)\[\]\{\}\<\>}s)][1 -1])c 0)))0)r)](and(not=()a)(f(butlast a))(f b))))1)

```

Doesn't use regex, instead uses the first character to determine what the closing tag is and finds the first index where that bracket is balanced (cumulative sum is zero). Then iteratively checks that what is within brackets and after brackets are valid.

Gotta see if there is a better approach...
> 0 votes

# Answer
# Japt v2.0a0 `-!`, 16 bytes

```
e/\[]|<>|\(\)|{}

```

Try it
> 0 votes

# Answer
# Lua, 295 bytes

```
f = false g = string.gsub t=table s={}b=io.read()for c in b:gmatch('.')do if c:find("[%[<{%(]")then s[#s + 1] = g(g(g(g(c,"<",">"),"{","}"),"%[","]"),"%(",")")elseif c:find("[%]>}%)]")then if t.remove(s)~=c then print(f)return end else print(f)return end end if#s>0 then print(f)else print(1)end

```

## Ungolfed Version

```
f = false
g = string.gsub
t=table
s={} --Define a stack of opening brackets
b=io.read() --get the input
for c in b:gmatch('.') do   --for every character
    if c:find("[%[<{%(]") then
        s[#s + 1] = g(g(g(g(c,"<",">"),"{","}"),"%[","]"),"%(",")") --if the current character is an opening bracket, push the closing bracket onto the stack
    elseif c:find("[%]>}%)]") then
        if t.remove(s)~=c then
            print(f) --if the character is a closing bracket, pop the closing bracket off the stack and test if they match, if not print false
            return
        end
    else
        print(f) --if the character is not a bracket print false
        return
    end
end
if #s>0 then
    print(f) --if there are still brackets on the stack print false
else
    print(1) --print 1 there are no brackets on the stack
end

```

Try it online!
> 0 votes

# Answer
# Pascal (FPC), ~~137~~ 126 bytes

```
var s,t:string;i:word;begin read(s);repeat t:=s;for i:=1to 4do Delete(s,pos('([{<'[i]+')]}>'[i],s),2)until s=t;write(s='')end.

```

Try it online!
> 0 votes

# Answer
# Haskell, 138 Bytes

`f x=let g z x=case x of{[]->z;a:b->if a==z!!0then g(tail z)b else g(case a of{'('->')';'['->']';'{'->'}';'<'->'>';_->' '}:z)b}in" "==g" "x`

de-golfed:

```
f x=                                                                      --define a function f
  let g z x=case x of{                                                    --define a function which takes two parameters: z (the remaining input) x (the characters that need to be matched)
    []->z;                                                                --handle end of input
    a:b->if a==z!!0                                                       --if the input matches the characters that need to be matched
      then g (tail z) b                                                   --calls itself for the remaining input
      else g (case a of{'('->')';'['->']';'{'->'}';'<'->'>';_->' '} : z) b--otherwise adds the character to the list of ones that need to be matched
  }
  in g " " x == " "                                                       --runs the matching function

```
> 0 votes

# Answer
# , 104 bytes

```
f=function(x,y=x)`if`(nchar(x),{for(e in c("{}","[]","()","<>"))y=gsub(e,"",y,f=T)
`if`(y==x,F,f(y))},T)

```

Try it online!

Shorter, but sadly *much* more boring and uninventive than the previous R answer, which I feel more-deserves appreciation... please upvote it instead!
> 0 votes

# Answer
# Vyxal, 15 bytes

```
λkḂ2ẇk<J(no);Ẋ¬

```

Try it Online!

```
λ           ;Ẋ  # While result changes
        (  )    # For each of
 kḂ2ẇk<J        # Pairs of brackets
         no     # Remove it
              ¬ # If something remains, it's unbalanced.

```
> 0 votes

# Answer
## PHP5.4 (84 chars)

Given *$argv\[1\]* as a command line argument, it doesn't take a regex to print `0` or `1` :

```
for($s=$argv[1];"$s"!=$s=str_replace(['()','[]','{}','<>'],'',$s););echo$s===''?1:0;

```

The same process is **87 chars** long using a function :

```
function f($s){for(;"$s"!=$s=str_replace(['()','[]','{}','<>'],'',$s););return$s==='';}

```

Try it Online \- Usage :

```
var_dump(f('[([]{})<{[()<()>]}()>{}]')); // bool(true)
var_dump(f('0(()())')); // bool(false)

```

**Info** : Only the array declaration break the PHP4 compatibility.
> 0 votes

# Answer
# Lexurgy, 38 bytes

While the input changed last iteration, replace pairs of adjacent brackets with an empty string.

```
a propagate:
{\(\),\[\],\{\},\<\>}=>*

```
> 0 votes

# Answer
# Haskell, 59 bytes

```
null.foldr(%)""
c%(a:b)|elem(c,a)$zip"([{<"")]}>"=b
c%s=c:s

```

Try it online!
> 0 votes

# Answer
# Rust, 95 bytes

Straightforward recursive solution based on the replacement approach.

```
fn f(s:String)->bool{s==""||"(),<>,{},[]".split(",").any(|c|s.contains(c)&&f(s.replace(c,"")))}

```

Try it online!
> 0 votes

---
Tags: code-golf, string, balanced-string, decision-problem
---


# Question
Title: Enumerate all palindromic numbers (in decimal) between 0 and n
Given a non-negative integer n, enumerate all palindromic numbers (in decimal) between 0 and n (inclusive range). A palindromic number remains the same when its digits are reversed.

The first palindromic numbers (in base 10) are given here:

> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, 212, 222, 232, 242, 252, 262, 272, 282, 292, 303, 313, 323, 333, 343, 353, 363, 373, 383, 393, 404, 414, 424, 434, 444, 454, 464, 474, 484, 494, 505, 515, ...

This is a code golf with the prize going to fewest characters. The palindromic numbers should be output one per line to stdout. The program should read n from the commandline or stdin.

# Answer
> 7 votes
## Golfscript, 15 chars

```
~),{.`-1%~=},n*

```

# Answer
> 10 votes
## Perl 5.10, 29 (or 39) characters

```
say for grep$_==reverse,0..<>

```

Needs the `say` feature enabled. 29 chars if you consider that to be free, otherwise 39 to add `use 5.010;`. Argument on STDIN.

## Perl, 35 characters

```
#!perl -l
print for grep $_==reverse,0..<>

```

using the old perlgolf convention that `#!perl` is not counted but any flags following it are.

## Perl, 36 characters

```
print$_,$/for grep $_==reverse,0..<>

```

If none of the others qualify.

# Answer
> 9 votes
## Befunge 320 313 303 characters

(including significant newlines and whitespace)

```
 &:#v_v#  #                  :-1<
v91:<         v          <
0     >0.@    >\25**\1-:#^_v
pv   p09+1g09<^_           >$+     v
:>:25*%\25*/:| ^:p18:+1g18\<
 :          > >90g 1-:90p  | >  ^
>|           $^     <      >-|  ^  #<
 @           > 0 81p^        >:.25*,^
            ^                      <

```

I wonder if I could make this smaller by rerouting the paths...

Edit: redid the top part to avoid an extra line.

# Answer
> 8 votes
## Perl 5.10 - 27 characters

`map{say if$_==reverse}0..<>`

Reads the argument from stdin.

# Answer
> 7 votes
## Ruby 1.9, 39 characters

```
puts (?0..gets).select{|i|i==i.reverse}

```

Input (must not be terminated with a newline) via stdin. Example invocation:

```
echo -n 500 | ruby1.9 palinenum.rb

```

40 characters for a version which uses commandline args:

```
puts (?0..$*[0]).select{|i|i==i.reverse}

```

# Answer
> 6 votes
## , 20 characters

```
(#~(-:|.)@":"0)>:i.n

```

# Answer
> 5 votes
## Python, 57 51 chars

```
for i in range(input()):
 if`i`==`i`[::-1]:print i

```

Usage:

```
echo 500 | python palindromic.py

```

# Answer
> 5 votes
**Perl \> 5.10 : 25 characters**

```
map$_==reverse&&say,0..<>

```

# Answer
> 4 votes
### APL (~~25~~ 17)

```
↑t/⍨t≡∘⌽¨t←⍕¨0,⍳⎕

```

# Answer
> 3 votes
## Javascript ~~122~~ ~~108~~ 107 chars...

I'm sure this can be golfed more - I'm new to this!

```
n=prompt(o=[]);for(i=0;i<=n;i++)if(i+''==(i+'').split("").reverse().join(""))o.push(i);alert(o.join("\n"));

```

### or

```
n=prompt(o=[]);i=-1;while(i++<n)if(i+''==(i+'').split("").reverse().join(""))o.push(i);alert(o.join("\n"));

```

# Answer
> 3 votes
## Haskell 66 characters

```
main=do n<-readLn;mapM_ putStrLn[s|s<-map show[0..n],s==reverse s]

```

# Answer
> 3 votes
## Perl - 43 chars

```
for$i(0..<>){if($i==reverse$i){print$i,$/}}

```

This is my first attempt at code golf, so I'm pretty sure a Perl pro could golf it down.

# Answer
> 3 votes
**Mathematica 61**

```
Column@Select[0~Range~Input[],#==Reverse@#&@IntegerDigits@#&]

```

# Answer
> 3 votes
# Brachylog

## With the I/O format stated in the question, 8 bytes

```
≥ℕA↔A≜ẉ⊥

```

Try it online!

## With modern PPCG I/O rules, 4 bytes

```
≥ℕ.↔

```

Try it online!

This is a function that generates all the outputs, not a full program like the previous example, and so doesn't comply with the spec as written, but I thought I'd show how the program would look like if the question had been written to modern I/O standards (which permit the use of functions, and output via generators).

# Explanation

```
≥ℕ.↔
 ℕ    Generate natural numbers
≥     less than or equal to the input
  .   but output only the ones
   ↔  that would produce the same output if reversed

```

For the full program version, we create a temporary variable `A` to hold the output, explicitly labelize it (this is done implicitly for the main predicate of a program), and use the well-known `ẉ⊥` technique for outputting a generator's elements to standard output.

# Answer
> 2 votes
## PHP, ~~64~~ 58 bytes

```
for($i=0;$i<=$argv[1];print$i==strrev($i)?$i.'\n':'',$i++)

```

Changed `$_GET['n']` to `$argv[1]` for command line input.

# Answer
> 2 votes
## **PHP, 59 55 53 chars**

```
for($i=0;$i++<$argv[1];)if($i==strrev($i))echo"$i\n";

```

Usage

```
php palindromic.php 500

```

Edit : thanks Thomas

# Answer
> 2 votes
### Scala 59

```
(0 to readInt)filter(x=>""+x==(""+x).reverse)mkString("\n")

```

# Answer
> 2 votes
## C, 98 characters

```
n,i,j,t;main(){for(scanf("%d",&n);i<=n;i-j?1:printf("%d ",i),i++)for(t=i,j=0;t;t/=10)j=j*10+t%10;}

```

# Answer
> 2 votes
# k (23 chars)

```
{i@&{&/i=|i:$x}'i:!1+x}

```

# Answer
> 2 votes
# Befunge, 97 (grid size 37x4=148)

```
#v&#:< ,*25-$#1._.@
:>:::01-\0v >-!#^_$1-
*\25*/:!#v_::1>\#* #*25*#\/#$:_$\25*%
   `-10:\<+_v#

```

Have a better Befunge answer to this question. This is Befunge-93 specifically; I could probably make it even more compact with Befunge-98. I'll include that in a future edit.

Since you can't operate on strings in Befunge, the best I could do was compute the digit-reverse of each number (which I'm surprised I was able to manage without `p` and `g`) and compare it to the original number. The digit-reverse takes up most of the code (basically the entire third and fourth lines).

Note that the program, as it stands now, prints the numbers backwards from the input down to 0. If this is a big deal, let me know. (The challenge only says to enumerate them, not specifically in increasing order.)

# Answer
> 2 votes
# 05AB1E, 5 bytes

```
ƒNÂQ–

```

Explanation:

```
ƒ      # For N in range(0, input() + 1)
 N     #   Push N
  Â    #   Bifurcate (pushes N and N[::-1])
   Q   #   Check for equality
    –  #   If true, pop and print N

```

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

# Answer
> 2 votes
# Jelly, 5 bytes

```
ŻŒḂƇY

```

Try it online!

# Answer
> 2 votes
# Perl 5, 24 bytes

```
map$_-reverse||say,0..<>

```

Try it online!

# Answer
> 1 votes
# Python

```
n=raw_input('')
for a in range(0,int(n)+1):
    r=str(a)
    if str(a)==r[::-1]:
        print r

```

# Answer
> 1 votes
# Groovy, 83

```
System.in.eachLine{(0..it.toInteger()).each{if("$it"=="$it".reverse())println(it)}}

```

# Answer
> 1 votes
## Q (33)

```
{if[x="I"$(|:) -3!x;:x]} each til

```

Probably a neater way to do this but anyway, sample usage (you enter n+1 to get to n):

```
q){if[x="I"$(|:) -3!x;:x]} each til  10
0 1 2 3 4 5 6 7 8 9

```

Suggestion by tmartin, gets it down to 29:

```
({$[x="I"$(|:) -3!x;x;]}')(!)

```

Same usage.

# Answer
> 1 votes
# Q (34 chars)

Pass n rather than n+1 as an argument for this Q solution.

```
{i(&)({all i=(|)i:($)x}')i:(!)1+x}

```

# Answer
> 1 votes
# Q,32

```
{a(&)a~'((|:)')a:((-3!)')(!)1+x}

```

# Answer
> 1 votes
## Python, 106 characters

```
import sys as a
print(type(a.argv[1]))
for x in range(int(a.argv[1])+1):
 x=str(x)
 if x==x[::-1]:print(x)

```

usage:

```
python a.py 500

```

# Answer
> 1 votes
# C# (217 214 191 chars)

Golfed version:

```
using System;using System.Linq;class P{static void Main(){int n=int.Parse(Console.ReadLine());do{var t=(n+"").ToArray();Array.Reverse(t);Console.Write(n+""==new string(t)?n+"\n":"");}while(n-->0);Console.ReadLine();}}

```

Readable:

```
using System;
using System.Linq;
class P
{
    static void Main()
    {
        int n = int.Parse(Console.ReadLine());
        do
        {
            var t = (n + "").ToArray();
            Array.Reverse(t);
            Console.Write(n + "" == new string(t) ? n + "\n" : "");
        } while (n-->0);

        Console.ReadLine();
    }
}

```

This prints out palindromes in descending order making use of the n--\>0 operator. (as n goes to 0).

\*Edited version replaces do...while with while, saving 3 chars, but now you must input with n+1.

```
using System;using System.Linq;class P{static void Main(){int n=int.Parse(Console.ReadLine());while(n-->0){var t=(n+"").ToArray();Array.Reverse(t);Console.Write(n+""==new string(t)?n+"\n":"");}Console.ReadLine();}}

```

\*edited: found a better way to reverse string without converting to array:

```
using System;using System.Linq;class P{static void Main(){int n=int.Parse(Console.ReadLine());while(n-->0)Console.Write(n+""==string.Join("",(""+n).Reverse())?n+"\n":"");Console.ReadLine();}}

```

Readable:

```
using System;
using System.Linq;
class P
{
    static void Main()
    {
        int n = int.Parse(Console.ReadLine());
        while (n-->0)
            Console.Write(n + "" == string.Join("", ("" + n).Reverse()) ? n + "\n" : "");
        Console.ReadLine();
    }
}

```

# Answer
> 1 votes
# PHP 53

Can 53 be any lower? Four different options:

```
for($i=$argv[1];$i-->0;)echo$i==strrev($i)?"$i\n":"";
for($i=$argv[1];$i-->0;)if($i==strrev($i))echo"$i\n";
while(($i=$argv[1]--)>0)echo$i==strrev($i)?"$i\n":"";
while(($i=$argv[1]--)>0)if($i==strrev($i))echo"$i\n";

```

If you want to get funky...

**PHP 47**

```
while(($i=$argv[1]--)>0)if($i==strrev($i))`$i`;

```

You have to ignore the error text. The palindrome numbers are still output to the command line, however.

# Answer
> 1 votes
# Burlesque, 13

```
rz{J<-==}f[p^

```

Burlesque has some useful commands for golfing, in this case \<- reverses anything you put before it.

```
          rz             creates a range from 0 to input
            {            start of filtering (discards any element not returning 1) the created range
              J <- ==    duplicates element, reverses duplicate, compare
            }f[          end filtering, now we're left with a block of palindromic integer which
            p^           takes care of, and outputs the numbers as desired.

```

Try it here The linked example has 1000 as input, change it to see more or fewer palindromic numbers.

# Answer
> 1 votes
# Pyth, 11

```
VhQIq`N_`NN

```

Example:

```
$ pyth -c 'VhQIq`N_`NN' <<< 200
0
1
2
3
4
5
6
7
8
9
11
22
33
44
55
66
77
88
99
101
111
121
131
141
151
161
171
181
191

```

# Answer
> 1 votes
# C++, 145 143

```
#include<iostream>
int i,j,n,r;int main(){std::cin>>n;for(;i<=n;i++){j=i;while(j!=0){r=r*10;r=r+j%10;j=j/10;}if(i==r)std::cout<<i<<' ';r=0;}}

```

**Alternative \[143 too\]:**

```
#include<stdio.h>
int i,j,n,r;int main(){scanf("%d",&n);for(;i<=n;i++){j=i;while(j!=0){r=r*10;r=r+j%10;j=j/10;}if(i==r)printf("%d ", i);r=0;}}

```

# Answer
> 1 votes
**Python** (54)

```
print filter(lambda i:`i`==`i`[::-1],range(input()+1))

```

# Answer
> 1 votes
# Gogh, 17 bytes

This answer is non-competing, as the language was created after the challenge was posted.

```
G{÷÷sR=¦?}m0%{Ƥ}m

```

Usage:

```
$ ./gogh i 'G{÷÷sR=¦?}m0%{Ƥ}m' <input>

```

---

### Explanation

```
        “ Implicit input.                                      ”
G       “ Push an inclusive list.                              ”
{       “ Open a code block.                                   ”
 ÷÷     “ Push two copies of the TOS.                          ”
 sR=    “ Check if the integer is palindromic.                 ”
 ¦?     “ If n is palindromic, yield n. If not, yield 0.       ”
}m      “ Close the code block and map it to the TOS.          ”
0%      “ Remove non-palindromic integers (denoted by zeroes). ”
{       “ Open a code block.                                   ”
 Ƥ      “ Print.                                               ”
}m      “ Close the code block and map it to the TOS.          ”
        “ Implicit output.                                     ”

```

# Answer
> 1 votes
# Zsh, <sup>~~34~~</sup> 33 bytes

```
eval \>{0..$1}';ls `ls|rev`;rm *'

```

Try it online!

* `{0..$1}` \- repeat the string with this part substituted with the numbers from `0` to the input
* `eval`uate that
    + `>` \- create the file with that number
    + `ls` \- list all the files in the current directory
    + `|rev` \- reverse that
    + `ls `ls|rev`` \- print the intersection of the files in the current directory and the output of `ls|rev` (i.e. filter palindromes)
    + `rm *` \- remove all files

# Answer
> 1 votes
# Husk, 6 bytes

```
#S=↔Θḣ

```

Try it online!

'Enumerates' palindromic numbers (so, outputs how many there are). To list all of them, use `fS=↔Θḣ` for the same number of bytes.

```
#        # number of elements that
 S=      # are equal to themselves after
   ↔     # reversing their digits,
    Θḣ   # among 0 followed by 1..input.

```

# Answer
> 1 votes
# Vyxal, `j`, ~~5~~ 3 bytes

```
'Ḃ=

```

Try it Online!

Pretty simple answer really.

## Explained

```
'Ḃ=
'     # Filter by:
 Ḇ=   #     Bifuricate the argument passed and check if the two results are equal
      # The `j` flag joins on newlines

```

# Answer
> 1 votes
# Stax, 6 bytes

```
ô°hånⁿ

```

Run and debug it

-1 byte from Weijun Zhou's answer.

# Answer
> 1 votes
# Javascript (ES6), ~~84~~ ~~81~~ 74 bytes

`u=(n,c=n+1)=>c?u(n,--c).concat(`${c}`.split``.reverse().join``==c?c:[]):[]`

u is function.

~~There's got to be a better way to golf the loop. Php is annoying but at least it has builtins...~~

~~Rewrote the whole thing, recursive now. Is there something else for array.concat that pushes nothing?~~

Why did I have a random argument that did nothing?

# Answer
> 1 votes
# Thunno 2, 4 bytes

```
ĖæḲ=

```

Try it online!

#### Explanation

```
ĖæḲ=  # Implicit input
Ė     # Push [0..input]
 æ    # Filter by:
  Ḳ   #  Bifurcate it
   =  #  Are they equal?
      # Implicit output

```

# Answer
> 1 votes
# Raku, ~~29~~ 27 bytes

```
.flip-$_||.say for 0..slurp

```

Try it online!

# Answer
> 0 votes
## T-SQL, 72

```
DECLARE @@ INT=X,@ INT=0#:IF @=REVERSE(@)PRINT @ SET @+=1IF @<=@@ GOTO #

```

Replace "X" with the input number. This code runs in SQL Server 2008 R2.

# Answer
> 0 votes
## Pyke, 6 bytes

```
S#`D_q

```

Explanation:

```
S      - range(1, input()+1)
 #     - filter where True
  `D_q -  str(num) == str(num)[::-1]

```

Try it here!

# Answer
> 0 votes
# Visual Basic for Applications, 66 bytes

Callable from the immediate window.

```
Sub u(b)
For i=0To b
If StrReverse(i)=i Then Debug.?i
Next
End Sub

```

# Answer
> 0 votes
# Stax, 7 characters

```
çi/i∩≈f

```

Run and debug online!

## Explanation

Uses the unpacked version to explain.

```
^rfcEcr=
^r          [0..n]
  f         Print each element that matches the predicate on individual line
   cE       Array of decimal digits
     cr=    Equals its reverse

```

# Answer
> 0 votes
# Javascript, 98 bytes

```
n=>new Array(n+1).fill().map((a,b)=>b).filter(a=>[...''+a].reverse().join``==''+a&&(a<=n)).join` `

```

# Answer
> 0 votes
# PowerShell, 67 bytes

```
0..$args[0]|%{$x=[string]$_;if($x-eq(-join$x[-1..-$x.length])){$x}}

```

Try it online!

# Answer
> 0 votes
# Haskell, 45 bytes

```
f n=filter(\x->show x==(reverse.show)x)[0..n]

```

Try it online!

Input is an `Int`, output is a `[Int]`

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


title: Determine Uilta Pitch Accent

text:
# Question
Title: Determine Uilta Pitch Accent
Uilta is a minority tungusic language spoken in the far east of Russia.

A neat thing about Uilta is that it has pitch accent which can be predicted by a computer program. In this challenge we are going to take Uilta a word and determine where the accent peak is.

Let me explain how this can be done.

## Phonemes

The first thing needed is to split the input into phonemes. Phonemes are the smallest unit of language and they consist of vowels and consonants.

We will be using XSAMPA for this challenge so a vowel in Uilta is any of the following characters:

```
iu@oEOa

```

A consonant is any of the following characters:

```
mnJNptkbdgsx4ljw

```

Additionally the digraphs `tS` and `dZ` count as single consonants. Every input will have a unique decomposition into phonemes. So you don't have to worry about handling bad input.

Here are some example words split into phonemes:

```
na4i -> n a 4 i
mOO -> m O O
tuN@ndZi -> t u N @ n dZ i
ilaa -> i l a a
patala -> p a t a l a
xamdatta -> x a m d a t t a
@@kt@ -> @ @ k t @
isaaptu -> i s a a p t u
dZakpu -> dZ a k p u
bitSix@ -> b i tS i x @
xaiwaddaa -> x a i w a d d a a

```

## Syllables

Each word in Uilta can be broken into syllables. Syllables give the rhythm of the word. Syllables in Uilta match the regex `C?VV?C?`, where `C` matches any consonant and `V` matches any vowel.

There is one further restriction: Only the first syllable may begin with a vowel.

Every input will have a unique decomposition into valid syllables.

Here are some example words split into syllables:

```
na4i -> na.4i
mOO -> mOO
tuN@ndZi -> tu.N@n.dZi
ilaa -> i.laa
patala -> pa.ta.la
xamdatta -> xam.dat.ta
@@kt@ -> @@k.t@
isaaptu -> i.saap.tu
dZakpu -> dZak.pu
bitSix@ -> bi.tSi.x@
xaiwaddaa -> xai.wad.daa

```

## Morae

Each syllable is made up of 1-3 smaller units called "morae". The first mora is all of the syllable up to and including the first vowel, this forms the primary mora. Every other letter in the syllable is its own mora, these are secondary morae.

Every input will have a unique decomposition into **at least two** valid morae.

Here are some example words split into syllables with `.` and morae with :

```
na4i -> na.4i
mOO -> mO O
tuN@ndZi -> tu.N@ n.dZi
ilaa -> i.la a
patala -> pa.ta.la
xamdatta -> xa m.da t.ta
@@kt@ -> @ @ k.t@
isaaptu -> i.sa a p.tu
dZakpu -> dZa k.pu
bitSix@ -> bi.tSi.x@
xaiwaddaa -> xa i.wa d.da a

```

## Pitch accent

Once you've split the word up into morae you can determine where the accent peak is.

The process is as follows:

* Check the second to last mora. If it's a primary mora then it's the accent peak. If it's not ...
* Check the mora preceding it. If it's a primary mora then it's the accent peak. If it's not ...
* The mora preceding it is the accent peak. (It must be a primary mora)

```
na4i -> na
mOO -> mO
tuN@ndZi -> N@
ilaa -> la
patala -> ta
xamdatta -> da
@@kt@ -> @
isaaptu -> sa
dZakpu -> dZa
bitSix@ -> tSi
xaiwaddaa -> da

```

## Task

Given a valid Uilta word output its accent peak mora. Input will always be valid as described above.

This is so your goal is to minimize the size of your source code as measured in bytes.

---

If you want to read more about the Uilta language the following is an excellent resource and was invaluable for creating this challenge:

*Grammatical Outline of Uilta* (Revised)

# Answer
> 8 votes
# Retina 0.8.2, ~~102~~ ~~77~~ ~~39~~ 38 bytes

```
.*((^|[^iu@oEOaSZ]S?Z?)[iu@oEOa]).+
$1

```

Try it online! Link includes test cases. Explanation: Now heavily inspired by @WheatWizard's Haskell answer, simply matches the last nonterminal vowel with its immediately preceding consonant or at the beginning of the string. Edit: Saved 1 byte thanks to @OlivierGrégoire.

# Answer
> 5 votes
# Haskell, ~~154~~ ~~108~~ 103 bytes

*5 bytes saved thangks to Unrelated String*

```
v=(`elem`"iu@oEOa")
g"S"="tS"
g"Z"="dZ"
g x=x
m(x:y:z)|v x>v y=g[y]++[x]|1>0=m$y:z
m x=x

```

```
m.tail.reverse

```

Try it online!

# Explanation

This is overall pretty simple. The first thing we do is `reverse` the input. We do this because the pitch accent is easier to describe relative to the end of a word than the beginning. From there we use `tail` to remove the final character. If this is a primary mora we've broken it up and the solution is now the final primary mora. If it wasn't well now we removed the final mora, and the solution is the new final primary mora.

So we are looking for the final primary mora. That's a vowel followed by a non-vowel. So `m` does just that, it trims until it finds a vowel followed by a consonatn and returns them reversed. We use a small bit of extra logic to handle `tS` and `dZ`: If the non-vowel was `S` or `Z`, we replace it with `tS` or `dZ` respectively otherwise we leave it alone.

And that's it, it gives us the accent peak.

# Answer
> 2 votes
# Haskell + hgl, 78 bytes

```
v=kB$fe"iu@oEOa"

```

```
rv<gj<gP(h_*>l2p(p<v)(nA v*>hds++pM""en++(ʃ>/wR"St Zd")))<rv

```

# Explanation

This works a lot like my haskell answer.

First we setup `v` which is a parser which accepts any vowel. With that the first step in our function is to reverse the input with `rv`. We do this since we want to do things relative to the end of the list rather than the front of the list.

From here we have the actual parser.

```
h_*>l2p(p<v)(nA v*>hds++pM""en++(ʃ>/wR"St Zd"))

```

The actual parser just finds all primary morae except ones that end the list First it does `h_` which parses one or more characters then we parse a primary mora.

Since `h_` never parses 0 characters this breaks up any primary mora that would be at the end of the list.

The part that parses a primary mora is a little bit more complex

```
l2p(p<v)(nA v*>hds++pM""en++(ʃ>/wR"St Zd"))

```

But it can be broken down into further parts, first it parses a vowel `p<v` which parses a single vowel as a string. Then it parses a non-vowel, it does this with a negative look-ahead to check it's not a vowel `nA v`. Then it parses either, any one character `hds`, the end of the string `pM""en` or one of the digraphs `ʃ>/wR"St Zd"`. It can do both the first and last option at the same time, but since the digraphs are placed last they will have higher priority in the final result.

Once we have that parser we can run it. We run it with `gP` to get all results as a list. We use `gj` to get the last result, which do to the way we've done things will be the mora closest to the end of the string. This is also where the digraphs get higher priority than single characters, they will always appear later in the list.

Finally we reverse the given mora back to the correct order.

## Relfection

There were some pretty painful things here. When I first started I immediately realized there were some very important functions missing. I added them to the repo, although they are not present above.

I won't go into much detail but they would have saved 3 bytes overall:

```
v=xay"iu@oEOa"

```

```
rv<gj<gP(h_*>l2p(p<v)(nA v*>hds++pM""en++asy["St","Zd"]))<rv

```

However there are still some things that could be improved:

* `pM""en` is so painful. It's just an extremely expensive way to say the end of the list. `en` should in theory do that, but it returns a `()` instead and we need it to be an empty list. A version of `en` that returns an empty list would be useful.
* We really shouldn't have to do `gj<<gP`, there should be a built in way to get the highest / lowest priority parse, and only that.

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), 193 bytes

```
s=>System.Text.RegularExpressions.Regex.Match(s,$"^((?<P>{C}?{V}){V}?{C}?)((?<P>{C}{V}){V}?{C}?)*?({C}{V})?$").Groups["P"].Captures[^1].Value;string T="iu@oEOa",C=$"([^{T}][SZ]?)",V=$"([{T}])";

```

Try it online!

```
^((?<P>{C}?{V}){V}?{C}?)((?<P>{C}{V}){V}?{C}?)*?({C}{V})?$

```

This regex does all of the work. C and V stand for consonants and vowels respectively.

```
((?<P>{C}?{V}){V}?{C}?)

```

The first part matches the first syllable, and captures its primary mora in capturing group `P`.

```
((?<P>{C}{V}){V}?{C}?)*?

```

This part matches the next syllables, again capturing their primary mora in capturing group `P`. Note the lazy quantifier at the end.

```
({C}{V})?

```

This matches a single-mora syllable at the very end, if any.

We can then take the final mora captured within `P`, since it is guranteed to be primary, and also guranteed to not be the final mora (since that would either be captured within the last part, or it would be non-primary).

# Answer
> 1 votes
# Python 2, 113 Bytes

```
lambda s,v='iu@oEOa':(['dt'[i<'T'][:i in'SZ']+i+j for i,j in zip(s[:-1],s[1:-1])if(i in v)<(j in v)][-1:]or s)[0]

```

Try it online!

Heavily inspired by Wheat Wizard's Haskell answer.

### Approach

* Split the word into two-letter chunks, excluding the last letter
* Find all chunks of the form CV (consonant then vowel)
    + If no such chunk exists, return the first letter of the word
    + Return the last such chunk

# Answer
> 1 votes
# 05AB1E, 34 bytes

```
¨.γ"tSdZ"så_N*}ü2¬нšʒžM'@«slåJ}θJÔ

```

Inspired by *@WheatWizard♦*'s Haskell answer.

Try it online or verify all test cases.

**Explanation:**

```
¨             # Remove the final character of the (implicit) input-string
.γ            # Adjacent group by:
        s     #  Check if the current character
         å_   #  is NOT in
  "dtSZ"      #  string "dtSZ"
           N* #  Multiply it by the index, so everything else is in its own group
 }ü2          # After the group-by: get all overlapping pairs of this list
    ¬нš       # For the edge case of a leading vowel:
    ¬         #  Get the first pair (without popping the list)
     н        #  Pop and get its first character
      š       #  Prepend it to the list
ʒ             # Filter this list of pairs (plus the single leading item) by:
 žM           #  Push the vowels "aeiou"
   '@«       '#  Append a "@"
      s       #  Swap so the current pair is at the top of the stack
       l      #  Convert all letters to lowercase
        å     #  Check if its in the vowels string
         J    #  Join these checks together
              #  (truthy: "1"/"01"; falsey: "0"/"00"/"10"/"11")
}θ            # After the filter: pop and keep the last valid item
  J           # Join this pair back together to a string
   Ô          # For the edge case of "tt" or "dd":
   Ô          #  Connected uniquify
              # (after which the result is output implicitly)

```

# Answer
> 1 votes
# Vyxal, 45 bytes

```
Ṫλ&›`dtSZ`$c¬¥*;Ḋ2l:hhp'ɽkv\@J$vcṅ⌊1=;tfṅĠvhṅ

```

Try it Online!

Port of 05AB1E.

# Answer
> 0 votes
# Python3, 650 bytes:

```
lambda x:[*s(T(x),1)][0]
T=lambda x,c=[]:c if''==x else T(x[len((t:=[(a,b)for a,b in[('C','tS'),('C','dZ')]+[('C',i)for i in'mnJNptkbdgsx4ljw']+[('V',i)for i in'iu@oEOa']if x[:len(b)]==b][0])[1]):],c+[t])
P=lambda x:''.join(i[1]for i in x)
def M(w):
 w=[i for j in w for i in j]
 for i in[-2,-3,-4]:
  if w[i][0]:return w[i][1]
def s(t,l,c=[]):
 if[]==t:yield M([[(1,P(i[:I[0]+1])),*[(0,P([j]))for j in i[I[0]+1:]]]if(I:=[x for x,(a,_)in enumerate(i)if'V'==a])else i for i in c]);return
 for i in'CVVC CVV CVC CV VVC VV VC V'.split():
  if len(t)>=len(i)and(i[0]!='V'or l)and all(a==k for(a,b),k in zip(t,i)):yield from s(t[len(i):],0,c+[t[:len(i)]])

```

Try it online!

# Answer
> 0 votes
# Charcoal, 39 bytes

```
≔…θ⌈⌕Ａ⁺00⭆…θ⊖Ｌθ№iu@oEOaι01η✂η±⁺²№SZ§η±²

```

Try it online! Link is to verbose version of code. Alternative formulation, also 39 bytes:

```
≔✂θ⁰±⌕⪫00⭆Φ⮌θκ№iu@oEOaι10¹η✂η±⁺²№SZ§⮌η¹

```

Try it online! Link is to verbose version of code. Explanation: Ports of @WheatWizard's Haskell answer.

```
≔…θ⌈⌕Ａ⁺00⭆…θ⊖Ｌθ№iu@oEOaι01η

```

Except for the last letter, map each letter to whether it is a vowel or not, prefix `00` to the result, find the last index of `01`, and truncate the input string at that point, which thanks to the `00` prefix will be just after the desired primary mora, although the second `0` does double duty by allowing an initial vowel to be detected as a primary mora.

```
≔✂θ⁰±⌕⪫00⭆Φ⮌θκ№iu@oEOaι10¹η

```

Reverse the string except for the last letter, map each letter to whether it is a vowel or not, wrap the result in `00`, find the index of `10`, and remove that many characters from the end of the input string. The leading `0` adjusts the find index to be the number of characters to remove while the trailing `0` allows an initial vowel to match as a primary mora.

```
✂η±⁺²№SZ§η±²
✂η±⁺²№SZ§⮌η¹

```

Output the last two characters of the remaining string, unless the second last character is `S` or `Z`, in which case output the last three.

# Answer
> 0 votes
# Java (JDK), 59 bytes

```
s->s.replaceAll(".*((^|[^iu@oEOaSZ]S?Z?)[iu@oEOa]).+","$1")

```

Try it online!

## Credits

# Answer
> 0 votes
# Raku, 49 bytes

Port of Olivier Grégoire’s Java answer.

```
{S:g/.*((^|<-[iu@oEOaSZ]>S?Z?)<[iu@oEOa]>).+/$0/}

```

Try it online!

---
Tags: code-golf, parsing, natural-language
---