title: Custom Number Base Converter

text:
# Question
Title: Custom Number Base Converter
The powers that be want to be able to quickly convert any number they have into their own number base using any format they would like.

**Input**

Your program must accept 3 parameters.

1. Number: The string number to be converted
2. InputFormat: the base string the number is currently in
3. OutputFormat: the base string that the number is to be converted to.

**Output**

Your program must convert the `Number` from the old number base `InputFormat` to the new number base `OutputFormat`

**Examples**

```
("1","0123456789","9876543210") = "8"
("985724","9876543210","0123456789ABCDEF") = "37C3"
("FF","0123456789ABCDEF","0123456789") = "255"
("FF","0123456789ABCDEF","01234567") = "377"
("18457184548971248772157", "0123456789","Aa0Bb1Cc2Dd3Ee4Ff5Gg6Hh7Ii8Jj9Kk,Ll.Mm[Nn]Oo@Pp#Qq}Rr{Ss-Tt+Uu=Vv_Ww!Xx%Yy*Zz") = ",sekYFg_fdXb"

```

***Additional***

The new base 77 test is not required props if it works though

1. if your in a language where you have to convert to a number first and are locked within 32Bit you can skip it.
2. as it's an additional test.

All examples were generated by PHP 7.2 with the bcmath extension using the following code (vars mins but code formatted). there will probably be a shorter way this is just the way I came up with for the system I needed to do this with would be nice to see if anyone could come up with a shorter version though.

PHP 7.2 (bcmath - extension) 614 bytes

```
<?php
function f($a, $b, $c)
{
    $d= str_split($b,1);
    $e= str_split($c,1);
    $f= str_split($a,1);
    $g=strlen($b);
    $h=strlen($c);
    $k=strlen($a);
    $r='';
    if ($c== '0123456789')
    {
        $r=0;
        for ($i = 1;$i <= $k; $i++)
            $retval = bcadd($retval, bcmul(array_search($f[$i-1], $d),bcpow($g,$k-$i)));
        return $r;
    }
    if ($b!= '0123456789')
        $l=f($a, $b, '0123456789');
    else
        $l= $a;
    if ($l<strlen($c))
        return $e[$l];
    while($l!= '0')
    {
        $r= $e[bcmod($l,$h)].$r;
        $l= bcdiv($l,$h,0);
    }
    return $r;
}

```

Try it Online

**Scoring**

This is code golf; shortest code wins. Standard loopholes apply.

# Answer
> 13 votes
# MATL, 2 bytes

```
Za

```

Try it online!
All test cases.

For the Za lord!

# Answer
> 8 votes
# , 124 bytes

```
function(n,s,t,T=L(t),N=(match(!n,!s)-1)%*%L(s)^(L(n):1-1))intToUtf8((!t)[N%/%T^rev(0:log(N,T))%%T+1])
"!"=utf8ToInt
L=nchar

```

Try it online!

Ugh, this was a doozy. I use the typical base conversion tricks for R, but string manipulations in R are still messy!

# Answer
> 7 votes
# APL (Dyalog Unicode), 22 bytes

Anonymous infix lambda. Takes `InputFormat` as left argument and `OutputFormat` as right argument, and prompts for `Number` from stdin. Assumes `⎕IO` (**I**ndex **O**rigin) to be `0`, which is default on many systems.

```
{⍵[(≢⍵)⊥⍣¯1⊢(≢⍺)⊥⍺⍳⎕]}

```

Try it online!

`{``}` "dfn";  is left argument,  is right argument
<sup>(mnemonic: left and right ends of the Greek alphabet)</sup>

`⍵[``]` index the output format with the following:

prompt for input

`⍺⍳`**ɩ**ndices of those characters in the input format

`(``)⊥` evaluate as being in the following base:

`≢⍺` the length of the input format

yield that (separates `¯1` from `(≢⍺)`)

`(``)⊥⍣¯1` convert to the following base:

`≢⍺` the length of the output format

# Answer
> 7 votes
# Japt, ~~5~~ 3 bytes

```
nVW

```

Try it

---

## Explanation

```
         :Implicit input of U=Number, V=InputFormat & W=OutputFormat
 nVW     :Convert U from base V to base W

```

# Answer
> 7 votes
## C (gcc), 79 + 46 = 125 bytes

```
char*O;l,n;g(n){n/l&&g(n/l);write(1,O+n%l,1);}

```

This must be compiled with the

```
-Df(s,i,o)=for(n=l=0;n=n*strlen(i)+index(i,s[l])-i,s[++l];);l=strlen(O=o);g(n)

```

flag. (Yes, this is incredibly sketchy, which is why I'm keeping my old answer below.) This defines a macro `f` that outputs the answer to STDOUT.

Try it online!

## C (gcc), ~~133~~ 131 bytes

```
char*O;l;g(n){n/l&&g(n/l);write(1,O+n%l,1);}f(s,i,o,n)char*s,*i,*o;{for(n=0,l=strlen(O=o);n=n*strlen(i)+index(i,*s)-i,*++s;);g(n);}

```

Try it online!

This defines a function `f` that outputs the answer to STDOUT.

```
char*O;           // declare variable to store output charset
l;                // will be set to length of O
g(n){             // helper function to print the result
  n/l&&g(n/l);    // recursively calls itself if there are more digits
  write(1,        // output to stdout...
   O+n%l,1);      // the byte at (n mod output base) in O
}
f(s,i,o,n)        // main function
char*s,*i,*o;{    // declare string inputs
for(n=0,          // initialize n to 0
l=strlen(O=o);    // assign output charset so we don't have to pass it to g
n=n*strlen(i)     // repeatedly multiply n by input base...
+index(i,*s)-i,   // ... add the index of the digit in input charset...
*++s;);           // and move to the next digit until there's none left
g(n);             // call the helper function on the resulting integer
}

```

# Answer
> 6 votes
# 05AB1E, 5 bytes

```
ÅβIÅв

```

Try it online!

This does *not* work in the legacy version of 05AB1E. It only works on the new version, the Elixir rewrite.

### How it works

```
ÅβIÅв – Full program.
Åβ    – Convert from custom base to decimal.
  I   – Push the third input.
   Åв – Convert from decimal to custom base.

```

# Answer
> 4 votes
# MATL, 5 bytes

sundar found the real builtin to do this! Go upvote that answer instead of my dumb one :-(

```
ZAwYA

```

Try it online!

```
          % implicit input N, the number, and S, the digits of the Source base
ZA        % base2dec, convert string N using S as digits into a base 10 integer
w         % swap stack elements, with implicit input T, the digits of the Target base
YA        % dec2base, reverse the ZA operation with digits coming from T instead.

```

# Answer
> 4 votes
# Charcoal, 5 bytes

```
⍘⍘ＳＳＳ

```

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

```
  Ｓ     Input the "number"
   Ｓ    Input the input format
 ⍘      Convert to number using that format
    Ｓ   Input the output format
⍘       Convert to string using that format
        Implicitly print

```

The `BaseString` function automatically converts between number and string depending on the type of the first parameter.

# Answer
> 3 votes
# Python 2, ~~132~~ ~~129~~ ~~122~~ 121 bytes

```
lambda n,a,b:g(sum(len(a)**i*a.find(j)for i,j in enumerate(n[::-1])),b)
g=lambda n,c:c[n:n+1]or g(n/len(c),c)+c[n%len(c)]

```

Try it online!

An anonymous function (thanks, Erik the Outgolfer!) which converts the original number to a base 10 integer, then passes the integer and the new base string to function g(), which recursively converts to the new base. Now passes length of the OutputFormat as a parameter to g().

Updated g() for a lower bytecount. (thanks, Dennis!)

Replaced index() with find(). (thanks, Mr. Xcoder!)

## Ungolfed Explanation:

```
def f(n, a, b):
    # reverse the string to that the least significant place is leftmost
    # Ex: 985724 -> 427589
    n = n[::-1]
    # get the value of each place, which is its index in the InputFormat, times the base to the power of the place
    # Ex: 427589, 9876543210 -> 5*10^0, 7*10^1, 2*10^2, 4*10^3, 1*10^4, 0*10^5 -> [5,70,200,4000,10000,0]
    n = [a.find(j)*len(a)**i for i,j in enumerate(n)]
    # add all of the values together to bet the value in base 10
    # Ex: (5 + 70 + 200 + 4000 + 10000 + 0) = 14275
    n = sum(n)

    # call the convert to base function
    return g(n, b)

def g(n, c):
    # string slice, which will return an empty string if n:n+1 is not in range
    # an empty string is falsey
    if c[n:n+1]:
        return c[n:n+1]
    else:
        # get current least significant digit
        rem = c[n%len(c)]
        # get the rest of the integer
        div = n/len(c)

        # get the converted string for the rest of the integer, append the calculated least significant digit
        return g(div,c)+rem

```

# Answer
> 3 votes
# VBA, 182 bytes

A declared subroutine which takes input, `n`, in the language `y` and projects that into language `z`.

```
Sub f(n,y,z)
l=Len(n)
For i=-l To-1
v=v+(InStr(1,y,Mid(n,-i,1))-1)*Len(y)^(l+i)
Next
l=Len(z)
While v
v=v-1
d=v Mod l+1
v=v\l
If d<0Then v=v+1:d=d-l
o=Mid(z,d+1,1)&o
Wend
n=o
End Sub

```

# Answer
> 2 votes
# Jelly, 11 bytes

```
iⱮ’ḅL{ṃ⁵ṙ1¤

```

Try it online!

Argument order: InputFormat, Number, OutputFormat. **Be sure to quote the arguments with proper escaping!**

# Answer
> 2 votes
# Pyth, 21 bytes

```
s@LeQjimx@Q1dhQl@Q1le

```

Test suite

Explanation:
```
s@LeQjimx@Q1dhQl@Q1le  | Code
s@LeQjimx@Q1dhQl@Q1leQ |  with implicit variables
       m               | Map the function
        x   d          |   index of d in
         @Q1           |    the second string in the input
             hQ        |  over the first string in the input
      i                | Convert the resulting list to int from base
               l@Q1    |  length of the second string in the input
     j                 | Convert the int into a list in base
                   leQ |  length of the last string in the input
 @LeQ                  | Turn each number in the list into the character from the numbers index in the last string in the input
s                      | Concatenate the strings in to one string
                       | Implicit print

```

# Answer
> 2 votes
# Haskell, 119 bytes

```
n!f=init.((foldl((+).(l f*))0[i|c<-n,(i,d)<-zip[0..]f,d==c],0)#)
(0,d)#b=[b!!d]
(r,d)#b=r`divMod`l b#b++[b!!d]
l=length

```

Try it online!

# Answer
> 2 votes
# JavaScript (ES6), ~~90~~ 86 bytes

Takes input as `(input_format)(output_format)(number)`.

```
s=>d=>g=([c,...n],k=0)=>c?g(n,k*s.length+s.search(c)):k?g(n,k/(l=d.length)|0)+d[k%l]:n

```

Try it online!

# Answer
> 2 votes
# Perl 6, ~~100~~ 97 bytes

```
{$^c.comb[(":"~$^b.chars~[$^a.comb>>.&{index $b,$_}].perl).EVAL.polymod($c.chars xx*)].join.flip}

```

Try it online!

Anonymous code block that takes 3 strings in order, input, input format and output format, then returns a string

### Explanation:

```
{  # Anonymous code block
  $^c.comb[  # Split the output format into characters
           (":"~$^b.chars~[$^a.comb>>.&{index $b,$_}].perl) # The radix syntax in a string e.g ":3[1,2,3]"
           .EVAL  # Eval'ed to produce the base 10 version
           .polymod($c.chars xx*)  # Converted to a list in the output base (reversed)
          ] # Convert the list into indexes of the output format
           .join  # Join the characters to a string
           .flip  # And unreversed
}

```

# Answer
> 1 votes
# Python 2, ~~97~~ 95 bytes

Thanks to Chas Brown for -2 bytes.

```
n,s,t=input()
k=0;w='';x=len(t)
for d in n:k=len(s)*k+s.find(d)
while k:w=t[k%x]+w;k/=x
print w

```

Try it online!

# Answer
> 1 votes
# C (gcc), 130 129 bytes

```
v;c(r,i,s,t)char*r,*i,*t;{for(r[1]=v=0;*i;v=v*strlen(s)+index(s,*i++)-s);for(s=strlen(t),i=1;*r=t[v%s],v/=s;memmove(r+1,r,++i));}

```

Try it online!

-1 byte using `index` instead of `strchr`.

This is a simple iterative approach, reusing some variables (and thereby abusing `sizeof(int) == sizeof(char *)` on TIO) to save bytes.

Input:

* `i` input number
* `s` source base characters
* `t` target base characters

Output:

* `r` result number (pointer to a buffer)

### Explanation:

```
v;                                        // value of number
c(r,i,s,t)char*r,*i,*t;{
    for(r[1]=v=0;                         // initialize value and second
                                          // character of output to 0
        *i;                               // loop while not at the end of
                                          // input string
         v=v*strlen(s)+index(s,*i++)-s);  // multiply value with source base
                                          // and add the value of the current
                                          // digit (position in the base string)
    for(s=strlen(t),i=1;                  // initialize s to the length of the
                                          // target base string, length of
                                          // result to 1
        *r=t[v%s],v/=s;                   // add character for current digit
                                          // (value modulo target base) and
                                          // divide value by target base until
                                          // 0 is reached
        memmove(r+1,r,++i));              // move result string one place to
                                          // the right
}

```

# Answer
> 1 votes
# Java 10, 131 bytes

A lambda taking the parameters in order as strings and returning a string.

```
(i,f,o)->{int n=0,b=o.length();var r="";for(var c:i.split(r))n=n*f.length()+f.indexOf(c);for(;n>0;n/=b)r=o.charAt(n%b)+r;return r;}

```

Try It Online

## Ungolfed

```
(i, f, o) -> {
    int n = 0, b = o.length();
    var r = "";
    for (var c : i.split(r))
        n = n * f.length() + f.indexOf(c);
    for (; n > 0; n /= b)
        r = o.charAt(n % b) + r;
    return r;
}

```

---
Tags: code-golf, math, number, arithmetic, base-conversion
---


title: What do I need to destroy the world?

text:
# Question
Title: What do I need to destroy the world?
The gravitational binding energy of a planet is the amount of energy required to separate every tiny piece of it so that no piece will orbit or collide with another piece. For a uniform sphere, Wikipedia gives this formula:

$$E = \frac{3GM^2}{5R}$$

Where G is the gravitational constant (6.672e-11 m3•kg-1•s-2), M is mass, and R is the radius.

I *could* make this challenge about merely calculating this in Joules (kg•m2•s-2), but… that would be *boring*. And besides, not everyone understands Joules.

So instead, let's convert it into the following units:

* Kilotons of TNT (4.184 trillion Joules, shorthand `kilotons`)
* Hiroshima nuclear weapons (62.76 trillion Joules, shorthand `nukes`)
* Hostess™ Twinkies (560,000 Joules, shorthand `twinkies`)
* Kilowatt-hours (exactly 3.6 million Joules, shorthand `kWh`)
* Kilograms of mass-energy (1 kg mass-energy = 299,792,4582 Joules, shorthand `kg`)

So, take in the following input:

* mass in kilograms
* radius in meters
* one of six distinct inputs representing the unit to use

And output the binding energy in the specified units. Append the shorthand unit to the end of the output.

# Rules

* The shorthand for Joules is `J`.
* Arbitrary whitespace is allowed, as long as it doesn't split the shorthand unit or the number.
* Scientific notation is allowed, in whatever format your language uses.
* You only need 4 significant figures. Floating points are *highly* recommended.
* Blah blah shortest answer in bytes.

# Test Cases

Generated with this spreadsheet.

```
Mass (kg)   Radius (m)  J           kilotons    nukes       twinkies    kWh         kg
3.302E+23   2440000     1.789E+30   4.275E+17   2.850E+16   3.194E+24   4.969E+23   1.990E+13
4.869E+24   6052000     1.568E+32   3.748E+19   2.499E+18   2.800E+26   4.356E+25   1.745E+15
5.974E+24   6371000     2.242E+32   5.360E+19   3.573E+18   4.004E+26   6.229E+25   2.495E+15
6.419E+23   3390000     4.866E+30   1.163E+18   7.753E+16   8.689E+24   1.352E+24   5.414E+13
1.899E+27   69911000    2.065E+36   4.935E+23   3.290E+22   3.687E+30   5.736E+29   2.298E+19
5.685E+26   58232000    2.222E+35   5.310E+22   3.540E+21   3.968E+29   6.172E+28   2.472E+18
8.683E+25   25360000    1.190E+34   2.845E+21   1.896E+20   2.125E+28   3.306E+27   1.324E+17
1.024E+26   24620000    1.705E+34   4.075E+21   2.717E+20   3.045E+28   4.736E+27   1.897E+17
1.311E+22   1186000     5.801E+27   1.387E+15   9.244E+13   1.036E+22   1.611E+21   6.455E+10
1.989E+30   696300000   2.274E+41   5.436E+28   3.624E+27   4.062E+35   6.318E+34   2.531E+24
7.350E+22   1737000     1.245E+29   2.976E+16   1.984E+15   2.223E+23   3.458E+22   1.385E+12

```

---

Inspired by Powering the Death Star with Twinkies by Scott Manley.

# Answer
> 6 votes
# 05AB1E, ~~56~~ 54 bytes

Takes input as `unit, radius, mass`

```
6n56•G*•x619+•Oć•4°z)•1¡‡•S°*"Wwigu"I1èkè*2498T>°P/*¹J

```

Try it online!

Saved 2 bytes thanks to *Erik the outgolfer* (base 255 encode `4184` and `6276`).

# Answer
> 17 votes
# JavaScript (ES6), 78 bytes

Takes input as 3 distinct variables `(mass, radius, unit)`.

```
(m,r,u)=>m*m/r/[8987e9,56,6276e6,,4184e5,1e-4,360][parseInt(u,30)%7]/2498e11+u

```

### Test cases

The following snippet runs all test cases in the provided spreadsheet.

```
let f=

(m,r,u)=>m*m/r/[8987e9,56,6276e6,,4184e5,1e-4,360][parseInt(u,30)%7]/2498e11+u

console.log(
  [
    '3.302e+23 2440000   1.789e+30 4.275e+17 2.850e+16 3.194e+24 4.969e+23 1.990e+13',
    '4.869e+24 6052000   1.568e+32 3.748e+19 2.499e+18 2.800e+26 4.356e+25 1.745e+15',
    '5.974e+24 6371000   2.242e+32 5.360e+19 3.573e+18 4.004e+26 6.229e+25 2.495e+15',
    '6.419e+23 3390000   4.866e+30 1.163e+18 7.753e+16 8.689e+24 1.352e+24 5.414e+13',
    '1.899e+27 69911000  2.065e+36 4.935e+23 3.290e+22 3.687e+30 5.736e+29 2.298e+19',
    '5.685e+26 58232000  2.222e+35 5.310e+22 3.540e+21 3.968e+29 6.172e+28 2.472e+18',
    '8.683e+25 25360000  1.190e+34 2.845e+21 1.896e+20 2.125e+28 3.306e+27 1.324e+17',
    '1.024e+26 24620000  1.705e+34 4.075e+21 2.717e+20 3.045e+28 4.736e+27 1.897e+17',
    '1.311e+22 1186000   5.801e+27 1.387e+15 9.244e+13 1.036e+22 1.611e+21 6.455e+10',
    '1.989e+30 696300000 2.274e+41 5.436e+28 3.624e+27 4.062e+35 6.318e+34 2.531e+24',
    '7.350e+22 1737000   1.245e+29 2.976e+16 1.984e+15 2.223e+23 3.458e+22 1.385e+12'
  ]
  .map((l, n) => {
    [m, r, ...res] = l.match(/\S+/g).map(Number);

    return 'Test case #' + -~n + ' -> ' + (
      ['J', 'kilotons', 'nukes', 'twinkies', 'kWh', 'kg']
      .every((u, i) => +(+f(m, r, u).split(u).join``).toExponential(3) === +res[i])
      ? 'OK' : 'FAIL'
    )
  })
)
```

### How?

This is quite similar to @ColeraSu's C answer, with a JS-friendly hash function that works on the whole unit string.

```
Unit       | Parsed as (*) | Base-30 -> Dec. | mod 7
-----------+---------------+-----------------+------
"J"        | "j"           | 19              | 5        (*):
"kilotons" | "kilotons"    | 451052545318    | 4          Because we're parsing as Base-30,
"nukes"    | "n"           | 23              | 2          characters [u-z] (and anything
"twinkies" | "t"           | 29              | 1          after them) are simply ignored.
"kWh"      | "k"           | 20              | 6
"kg"       | "kg"          | 616             | 0

```

# Answer
> 7 votes
# Jelly, 78 bytes

```
²×⁽LÐ÷ȷ14÷⁴÷5÷⁵ị“¤Fðẏẏż“?A⁺ẏẏż“¬ŀż“8Ƙż“¡uþ³⁾ẉṿÆ“¡’¤;⁵ị“ÞṠlT“¡ṁæ-“;ØḲ“ȧ¹“ṫD“}»¤

```

Try it online!

Stuff to do with strings isn't really Jelly's type of challenge...

-7 bytes thanks to user202729 (thanks for helping me not get beaten by JavaScript :D)

# Answer
> 6 votes
# C, 113 bytes

Hash the second character, using the trailing `'\0'` of `"J"`. Inline array in C is used.

Note we need to multiply the second `M` last, or it will overflow to `inf`.

```
f(m,r,c)float m,r;char*c;{printf("%e%s",m/r/(float[]){1e-4,360,6276e6,8987e9,56,4184e5}[c[1]%36%7]/2498e11*m,c);}

```

Try it online!

# Answer
> 4 votes
# APL (Dyalog Unicode), ~~153 71~~ 69 bytes

```
op←{⍺,⍨40032E¯15÷÷/8987E13 36E5 6276E10 56E4 4184E9 1['gWuw '⍳⊃1↓⍺]⍵⍺⍺⍵}

```

Try it online!

Thanks to @Adám for absolutely crushing my old answer into this one. Thanks to @ngn for 2 bytes.

This 'function' is actually an operator called `op`. All the values for the measurement units were transformed to scientific notation.

### How it works:

```
{⍺,⍨40032E¯15÷÷/8987E13 36E5 6276E10 56E4 4184E9 1['gWuw '⍳⊃1↓⍺]⍵⍺⍺⍵}
                                                             1↓⍺         ⍝ take the measurement unit without the first letter (because it is ambiguous)
                                                            ⊃            ⍝ picks the first element returned by
                                                           ⍳             ⍝ Dyadic ⍳ota, which finds the index of
                                                  'gWuw '                ⍝ each of these characters
                                                 [             ]         ⍝ square brackets indicate the index
               8987E13 36E5 6276E10 56E4 4184E9 1                        ⍝ of the element of this vector (1-indexed) which will be used as the divisor for
            ÷/                                                  ⍵⍺⍺⍵     ⍝ dividing by the left operand (⍺⍺) and the right argument squared.
    40032E¯15÷                                                           ⍝ then divide this number by the result
 ⍺,⍨                                                                     ⍝ and append the measurement unit

```

# Answer
> 3 votes
# Python 3, ~~112~~ ~~106~~ ~~108~~ 101 Bytes

```
lambda m,r,u:str(40032e-19*m*m/r/{'':1e-4,'i':4184e5,'u':6276e6,'w':56,'W':360,'g':8987e9}[u[1:2]])+u

```

Pretty straight forward. Uses Python's `e` notation. Uses a dict that distinguishes unit based on the second letter and divides by the corrosponding value. `u[1:2]` is basically `u[1]`, expect it returns `''` instead of an error (which I only learned now). Then applies the formula with a few simplifications.

edit: down to 106 thanks to totallyhuman, back to 108 because of new nukes value and down to 101 thanks to Colera Su.

Try it online!

# Answer
> 3 votes
# Excel (Office 365), ~~106~~ ~~101~~ 97 bytes

Assuming cell `A1` is the mass, `A2` is the radius, and `B1` is the unit, written as the shorthand for the output.

```
=40032E-19*A1^2/(A2*SWITCH(MID(B1,2,1),"u",6276E6,"w",56,"W",360,"g",89876E8,"i",4184E5,1E-4))&B1

```

# Excel, 130 bytes

Old-fashioned Excel doesn't have the `SWITCH` function, so you have

```
=40032E-15*A1^2/(A2*IF(B1="J",1,IF(B1="nukes",6276E10,IF(B1="twinkies",56E4,IF(B1="kWh",36E5,IF(B1="kg",299792E3^2,4184E9))))))&B1

```

# Answer
> 1 votes
# Ruby , ~~83~~ 82 bytes

```
->m,r,u{"#{40032E-18*m*m/r/[36E2,56,8987E9,1E-3,4184E6,6276E7][u.sum*3%71%6]} "+u}

```

Uses a custom hash to index a LUT for the units (`i * k mod m` formula). The numbers were found using brute-force.

# Answer
> 0 votes
# Excel, 94 bytes

Takes Mass from `A1`, Radius from `B1`, Unit in `C1`. Look up on `2*Code(Unit) + Length(Unit) modulo 11`.

```
=4.0032E-15*A1^2/B1/CHOOSE(MOD(2*CODE(C1)+LEN(C1),11),,4184E5,,,6276E6,1E-4,89876E8,360,56)

```

# Answer
> 0 votes
# Jelly,  ~~59~~  54 bytes

*Saved 5 bytes thanks to @ChartZBelatedly*

I just wanted to try another weird method to convert the units. But the rest of the code is probably badly golfed.

```
⁵OẒḄ%9ị56,4184ȷ5,8987ȷ9,360,0,6276ȷ6,ȷ-4
²÷÷2498ȷ11÷¢⁵

```

Try it online!

### How?

We build a 'signature' of a unit string out of the primality of its ASCII codes. We interpret it as a binary value and apply a modulo to get the final index in the lookup table.

```
⁵OẒḄ%9ị[...]    - helper link to convert the unit to a hardcoded constant
⁵               - the 3rd input        e.g. "kilotons"
 O              - to ASCII codes       --> [107, 105, 108, 111, 116, 111, 110, 115]
  Ẓ             - is prime?            --> [1, 0, 0, 0, 0, 0, 0, 0]
   Ḅ            - binary -> decimal    --> 128
    %9          - modulo 9             --> 2
      ị[...]    - get value from table --> 418400000

²÷÷2498ȷ11÷¢⁵   - main link taking the mass, the radius and the unit
²               - square the mass
 ÷              - divide by the radius
  ÷2498ȷ11      - divide by 2498e11
          ÷¢    - divide by the unit constant, invoking the helper link as a nilad
            ⁵   - append the unit

```

The helper link gives the following indices for each unit:

```
unit     | ASCII codes                     | is prime?       | bin -> dec | mod 9
---------+---------------------------------+-----------------+------------+------
J        | 74                              | 0               |      0     |   0
kilotons | 107,105,108,111,116,111,110,115 | 1,0,0,0,0,0,0,0 |    128     |   2
nukes    | 110,117,107,101,115             | 0,0,1,1,0       |      6     |   6
twinkies | 116,119,105,110,107,105,101,115 | 0,0,0,0,1,0,1,0 |     10     |   1
kWh      | 107,87,104                      | 1,0,0           |      4     |   4
kg       | 107,103                         | 1,1             |      3     |   3

```

---
Tags: code-golf, physics
---


# Question
Title: Test if a string is parenthesly balanced
We call a ***parens group*** the open paren `(`, its matching close paren `)` and everything inside them.

A parens group or string is called ***parenthesly balanced*** if it contains either nothing or only 2 parenthesly balanced parens groups.

For example:

```
The string   "(()())()"      is parenthesly balanced
              (    )()       Because it contains exactly 2 parenthesly balanced parens groups
               ()()          The left one is parenthesly balanced because it contains 2 parenthesly balanced parens groups (balanced because they are empty). The right one is parenthesly balanced because it contains nothing.

```

Likewise:

```
The string   "(()(()))()"    is not parenthesly balanced
              (      )()     Because it contains a parens group that is not parenthesly balanced: the left one
               ()(  )        The left one is not balanced because it contains a parens group that is not balanced: the right one
                  ()         The right one is not balanced because it only contains one balanced group.

```

So, a parenthesly balanced string or parens group should either:

* Contain nothing at all.
* Or contain only and exactly 2 parenthesly balanced parens groups. It should contain nothing else.

### Task:

Your task is to write a function or program that checks if a given string is a parenthesly balanced one or not.

### Input:

Input will be a string or list of characters or something similar. You can assume that the string will only consist of the characters `'('` and `')'`. You can also assume that each open paren `(` will have its matching close paren `)`, so don't worry about strings like `"((("` or `")("` or `"(())("`...

**Note:** As mentioned by @DigitalTrauma in his comment bellow, it's ok to subtitute the `()` combo by other characters (such as `<>`, `[]`, ...), if it's causing additional work like escaping in some languages

### Output:

Anything to signal whether the string is parenthesly balanced or not (true or false, 1 or 0, ...). Please include in your answer what your function/program is expected to yield.

### Examples:

```
""                                        => True
"()()"                                    => True
"()(()())"                                => True
"(()(()(()())))(()())"                    => True
"(((((((()())())())())())())())()"        => True
"()"                                      => False
"()()()"                                  => False
"(())()"                                  => False
"()(()(())())"                            => False
"(()())(((((()())()))())())"              => False
"()(()()()())"                            => False
"()(()(()())()())"                        => False

```

The last two examples really made a difference!

Best of luck!

# Answer
> 8 votes
# Japt v2, 20 bytes

```
V="()"V¥iU1 eViV²1 V

```

Test it online!

Everyone misunderstood the challenge at first and though that each pair of parentheses had to contain an *even* number of sub-pairs, when in fact the challenge actually asks for *0 or 2* sub-pairs. So here's my revised answer, using the same technique as before.

We can still solve the challenge with recursive replacement. The thing is, instead of just removing all occurrences of `()()`, we need to make sure that there's nothing else in the same wrapper besides the `()()` (in other words, no `()()()()` or anything like that). We can do this by recursively replacing `(()())` with `()`.

The new problem is that the input itself does not have one pair of outer parentheses (as that would make it not a parenthesly balanced string), forcing us to wrap it in an extra pair to fully reduce it. Finally, the end result for balanced strings is now `()` instead of the empty string, so we check for equality rather than just taking logical NOT of the output.

# Answer
> 7 votes
# sed 4.2.2, 30

```
:
s/(()())/()/
t
/^()()$\|^$/q1

```

Try it online.

This returns a shell exit code of 1 for True and 0 for False.

```
:               # label
s/(()())/()/    # replace "(()())" with "()"
t               # jump back to label if above replacement matched
/^()()$\|^$/q1  # exit code 1 if remaining buffer is exactly "()()" or empty
                # otherwise exit with code 0

```

# Answer
> 7 votes
# Perl 5 -lp, ~~24~~ 22 bytes

```
$_=/^((<(?1)?>){2})?$/

```

Try it online! Link includes test cases. Edit: Saved 2 bytes thanks to @JoKing. Explanation: Just a recursive regex. The outer capturing group represents a balanced string as a `<` followed by an optional balanced string followed by a `>`, twice. Note that most of the other answers are able to use `()`s but this costs an extra two bytes:

```
$_=/^((\((?1)?\)){2})?$/

```

Try it online! Link includes test cases.

# Answer
> 6 votes
# Brachylog, 28 bytes

```
Ẹ|~c["(",A,")(",B,")"]∧A;B↰ᵐ

```

Try it online!

# Explanation

```
                                    --  The string perfectly balanced iff
Ẹ                                   --      the string is empty
 |                                  --  or
  ~c["(",A,")(",B,")"]              --      the string can be written id the format of "($A)($B)"
                      ∧             --          where
                       A;B ᵐ        --          both A and B
                          ↰         --          are perfectly balanced

```

# Answer
> 5 votes
# , ~~21~~, 20 bytes

```
é(Á)òÓ(“()()…)òø^()$

```

Try it online! or Verify all test cases!

```
é(                      " Insert '(' at the beginning of the line
  Á)                    " Append ')' at the end
    ò         ò         " Recursively...
     Ó                  "   Remove...
      (                 "     '('
       “    …           "     (Limit the part that is removed to this section of the match)
        ()()            "     '()()'
             )          "     ')'
                        " (effectively, this replaces '(()())' with '()', but it's one byte shorter than the straightforward approach
               ø        " Count...
                ^()$    "   Lines containing exactly '()' and nothing more

```

Hexdump:

```
00000000: e928 c129 f2d3 2893 2829 2829 8529 f2f8  .(.)..(.()().)..
00000010: 5e28 2924                                ^()$

```

# Answer
> 5 votes
# 6502 machine code routine, 48 bytes

```
A0 00 84 FD A2 00 B1 FB F0 0E C8 C9 29 18 F0 06 8A 48 E6 FD 90 EE B0 0A E0 01
90 06 E0 02 38 D0 01 18 A5 FD F0 09 C6 FD 68 AA E8 B0 F5 90 D7 60

```

Expects a pointer to a string in `$fb`/`$fc` which is expected to only contain `(` and `)`. Clears C (Carry) flag if the string is "paranthesely balanced", sets it otherwise (which is a typical idiom on the 6502, set carry "on error"). Does nothing sensible on invalid input.

Although the algorithm is recursive, it doesn't call itself (which would need more bytes **and** make the code position dependent) but instead maintains a recursion depth itself and uses "simple" branching.

### Commented disassembly

```
; function to determine a string is "paranthesly balanced"
;
; input:
;   $fb/$fc: address of the string
; output:
;   C flag set if not balanced
; clobbers:
;   $fd:     recursion depth
;   A,X,Y

 .isparbal:
A0 00       LDY #$00            ; string index
84 FD       STY $FD             ; and recursion depth
 .isparbal_r:
A2 00       LDX #$00            ; set counter for parantheses pairs
 .next:
B1 FB       LDA ($FB),Y         ; load next character
F0 0E       BEQ .done           ; end of string -> to final checks
C8          INY                 ; increment string index
C9 29       CMP #$29            ; compare with ')'
18          CLC                 ; and reset carry
F0 06       BEQ .cont           ; if ')' do checks and unwind stack
8A          TXA                 ; save counter ...
48          PHA                 ; ... on stack
E6 FD       INC $FD             ; increment recursion depth
90 EE       BCC .isparbal_r     ; and recurse
 .cont:
B0 0A       BCS .unwind         ; on previous error, unwind directly
 .done:
E0 01       CPX #$01            ; less than one parantheses pair
90 06       BCC .unwind         ; -> ok and unwind
E0 02       CPX #$02            ; test for 2 parantheses pairs
38          SEC                 ; set error flag
D0 01       BNE .unwind         ; if not 2 -> is error and unwind
18          CLC                 ; clear error flag
 .unwind:
A5 FD       LDA $FD             ; check recursion depth
F0 09       BEQ .exit           ; 0 -> we're done
C6 FD       DEC $FD             ; otherwise decrement
68          PLA                 ; get "pair counter" ...
AA          TAX                 ; ... from stack
E8          INX                 ; and increment
B0 F5       BCS .unwind         ; continue unwinding on error
90 D7       BCC .next           ; otherwise continue reading string
 .exit:
60          RTS

```

---

### Example C64 assembler program using the routine:

**Online demo**

**Code in ca65 syntax:**

```
.import isparbal   ; link with routine above

.segment "BHDR" ; BASIC header
                .word   $0801           ; load address
                .word   $080b           ; pointer next BASIC line
                .word   2018            ; line number
                .byte   $9e             ; BASIC token "SYS"
                .byte   "2061",$0,$0,$0 ; 2061 ($080d) and terminating 0 bytes

.bss
linebuf:        .res    256

.data
prompt:         .byte   "> ", $0
truestr:        .byte   "true", $0
falsestr:       .byte   "false", $0

.code
inputloop:
                lda     #<prompt        ; display prompt
                ldy     #>prompt
                jsr     $ab1e

                lda     #<linebuf       ; read string into buffer
                ldy     #>linebuf
                ldx     #0              ; effectively 256
                jsr     readline

                lda     #<linebuf       ; address of string to $fb/fc
                sta     $fb
                lda     #>linebuf
                sta     $fc
                jsr     isparbal        ; call function

                bcs     isfalse
                lda     #<truestr
                ldy     #>truestr
                bne     printresult
isfalse:        lda     #<falsestr
                ldy     #>falsestr
printresult:    jmp     $ab1e           ; output true/false and exit

; read a line of input from keyboard, terminate it with 0
; expects pointer to input buffer in A/Y, buffer length in X
.proc readline
                dex
                stx     $fb
                sta     $fc
                sty     $fd
                ldy     #$0
                sty     $cc             ; enable cursor blinking
                sty     $fe             ; temporary for loop variable
getkey:         jsr     $f142           ; get character from keyboard
                beq     getkey
                sta     $2              ; save to temporary
                and     #$7f
                cmp     #$20            ; check for control character
                bcs     checkout        ; no -> check buffer size
                cmp     #$d             ; was it enter/return?
                beq     prepout         ; -> normal flow
                cmp     #$14            ; was it backspace/delete?
                bne     getkey          ; if not, get next char
                lda     $fe             ; check current index
                beq     getkey          ; zero -> backspace not possible
                bne     prepout         ; skip checking buffer size for bs
checkout:       lda     $fe             ; buffer index
                cmp     $fb             ; check against buffer size
                beq     getkey          ; if it would overflow, loop again
prepout:        sei                     ; no interrupts
                ldy     $d3             ; get current screen column
                lda     ($d1),y         ; and clear
                and     #$7f            ;   cursor in
                sta     ($d1),y         ;   current row
output:         lda     $2              ; load character
                jsr     $e716           ;   and output
                ldx     $cf             ; check cursor phase
                beq     store           ; invisible -> to store
                ldy     $d3             ; get current screen column
                lda     ($d1),y         ; and show
                ora     #$80            ;   cursor in
                sta     ($d1),y         ;   current row
                lda     $2              ; load character
store:          cli                     ; enable interrupts
                cmp     #$14            ; was it backspace/delete?
                beq     backspace       ; to backspace handling code
                cmp     #$d             ; was it enter/return?
                beq     done            ; then we're done.
                ldy     $fe             ; load buffer index
                sta     ($fc),y         ; store character in buffer
                iny                     ; advance buffer index
                sty     $fe
                bne     getkey          ; not zero -> ok
done:           lda     #$0             ; terminate string in buffer with zero
                ldy     $fe             ; get buffer index
                sta     ($fc),y         ; store terminator in buffer
                sei                     ; no interrupts
                ldy     $d3             ; get current screen column
                lda     ($d1),y         ; and clear
                and     #$7f            ;   cursor in
                sta     ($d1),y         ;   current row
                inc     $cc             ; disable cursor blinking
                cli                     ; enable interrupts
                rts                     ; return
backspace:      dec     $fe             ; decrement buffer index
                bcs     getkey          ; and get next key
.endproc

```

# Answer
> 4 votes
# C (gcc), 113 bytes

```
p(a,r,e,n)char*a;{if(*a-40)return 1;for(r=1,e=0;e<2;r&=e++||*a==40)for(r*=n=p(++a);n+=*a++-40?~0:1;);r=r&&*a-40;}

```

Try it online!

# Explanation

```
p(a,r,e,n)char*a;{   // function and variable declaration
 if(*a-40)return 1;  // string does not start with '(', thus is empty
 for(r=1,e=0;e<2;    // r: return value, e: group id (look for exactly two groups)
 r&=e++||*a==40)     // after the first group, a second shall follow
  for(r*=n=p(++a);   // check that the group is itself balanced
  n+=*a++-40?~0:1;); // skip group
 r=r&&*a-40;}        // additionally, after those two groups there shall follow none

```

Try it online!

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

Takes input as an array of characters. Returns **false** for parenthesly balanced, **true** for not parenthesly balanced.

```
a=>[...a,k=0].some(c=>c<')'?!(a[k]=-~a[k++]):a[k]=~5>>a[k--]&1)

```

Try it online!

### Commented

```
a =>                     // a[] = input array of characters; we are going to reuse it to
  [                      // store the number of parenthesis groups at each depth
    ...a,                // append all characters
    k = 0                // initialize k = current depth to 0 and append a value that will
  ]                      // be treated as a final closing parenthesis for the root level
  .some(c =>             // for each character c in this array:
    c < ')' ?            //   if c is an opening parenthesis:
      !(                 //     increment the number of groups at the current depth
        a[k] = -~a[k++]  //     increment the depth
      )                  //     yield false
    :                    //   else:
      a[k] = ~5          //     make sure that the current depth contains either 0 or 2
             >> a[k--]   //     groups, by shifting the 1-complement of 5 (101 in binary)
             & 1         //     and testing the least significant bit
                         //     it resets the number of groups to 0 if the bit is not set
                         //     otherwise, it forces some() to return true
                         //     decrement the depth
  )                      // end of some()

```

---

# Recursive, 54 bytes

Using recursive replacements (like in ETHproductions' Japt answer) is however significantly shorter.

Takes input as a string. Returns **1** for parenthesly balanced, **0** for not parenthesly balanced.

```
f=s=>s==(s=s.split`(()())`.join`()`)?!s|s=='()()':f(s)

```

Try it online!

---

# Recursive, 46 bytes

This one throws a recursion error for not parenthesly balanced:

```
f=s=>!s|s=='()()'||f(s.split`(()())`.join`()`)

```

Try it online!

# Answer
> 3 votes
# Haskell, ~~82~~ 59 bytes

```
all(`elem`[0,2]).foldl(#)[0]
b#'('=0:b
(x:y:z)#_=y+1:z++[x]

```

Try it online!

I assume it can be golfed much further since it's my first time golfing in haskell, so any tricks or comments are more than welcome.

**EDIT -** Thanks @nimi for saving **23 bytes** (more than 28% of the original submission :)

# Answer
> 3 votes
# MATL, ~~26~~ 25 bytes

```
oo~`tnw52B5LZttnb<]XB10X-

```

Try it online!

Thanks to @ETHProductions' answer for the "replace (()()) with ()" idea, and @JungHwan Min's question comment for the idea of seeing the brackets as binary digits.

Output is an empty array for truthy, a positive number for falsey - which I think is allowed by OP's comment: "Could be categories. i.e. truthy values to signal truthiness and falsy values to signal otherwise." If it's not, we can add `n` at the end for +1 byte, to have 0 as truthy output and 1 as falsey output.

### With comments:

```
o         % Convert the parantheses to their ASCII codes
          %  40 for '(', 41 for ')'
o         % Parity - 1 for odd, 0 for even
~         % Not - change 0 to 1 and vice versa, so '(' is now 1 and ')' 0
          % Input char array is now a binary array B
`         % Do-while loop
  tn          % Get the length of the array
  w           % Bring the array B back on top
  52B         % Push the binary value of 52 on stack
              %  [1 1 0 1 0 0] (equivalent to '(()())')
  5L          % Push the constant [1 0] for '()'
  Zt          % Replace the sequence [1 1 0 1 0 0] in array B
              %  with [1 0]
  tn          % Get the length of the array after replacement
  b<          % Has it decreased? If so, continue loop
  ]       % end loop
          % Final value for balanced input will be
          %  either [1 0 1 0] for the remaining outer '()()'
          %  or an empty array [] for empty '' input
XB        % Convert the final binary array back to decimal
10X-      % Set difference, remove 10 from that result
          % Result is [] empty array for balanced input, otherwise
          %  some decimal number ≠ 10 for unbalanced input

```

# Answer
> 3 votes
# C# (.NET Core), 78 71 bytes

```
f=s=>{var r=s.Replace("(()())","()");return r==s?s==""|s=="()()":f(r);}

```

Try it online!

# Answer
> 3 votes
# Perl 6,  ~~43 41~~  37 bytes

```
{my rule f{\([<&f>**2]?\)};?/^<&f>**2$|^$/}

```

Test it

```
{(my$f)=/\([<$f>**2]?\)/;?/^[<$f>**2]?$/}

```

Test it

```
{$!=/\([<$!>**2]?\)/;?/^[<$!>**2]?$/}

```

Test it

## Expanded:

```
{  # bare block lambda with implicit parameter $_

  $! = # store regex into $! (no need to declare it)
  /
    \(

      [
        <$!> ** 2 # recurse into regex twice
      ]?          # optionally

    \)
  /;

  ?      # boolify (causes it to be run against $_)

    /
      ^         # beginning of string

      <$!> ** 2 # match using regex twice

      $         # end of string

    |           # or

      ^ $       # empty string
    /
}

```

# Answer
> 3 votes
# , 71 bytes

```
f=function(s,r=sub('(()())','()',s,f=T))'if'(r==s,s==''|s=='()()',f(r))

```

Try it online!

* porting of recursive Japt solution of @ETHproductions
* -2 bytes thanks to @JayCe

---

Another - longer - solution but interesting for the different approach

# , 85 bytes

```
g=gsub;!sum(eval(parse(t=g('\\)\\(',')-(',g('\\)','-1)',g('\\(','(2+',scan(,'')))))))

```

Try it online!

**Explanation :**

Take the input string and replaces :

```
'('  with '(2+'
')'  with '-1)'
')(' with ')-('

```

then evaluates the resulting expression. If it's equal to zero is balanced, otherwise is not. The use of `sum` is only necessary to handle the empty string case, because its evaluation returns `NULL`.

e.g.

```
()(()()) => (2+-1)-(2+(2+-1)-(2+-1)-1) = 0
(()())   => (2+(2+-1)-(2+-1)-1)        = 1

```

# Answer
> 2 votes
# Wolfram Language (Mathematica), 65 bytes

```
#=={}||{1,1}==(#//.{a___,"(",i:1...,")",b___}/;1!=+i<3:>{a,1,b})&

```

Try it online!

# Answer
> 2 votes
# 05AB1E, ~~18~~ ~~16~~ 13 bytes

```
…(ÿ)…(()∞„()©:®Q

```

Port of *@ETHproductions*'s Japt answer to fix the test case `()(()()(()())(()()))`.
-2 bytes thanks to *@Adnan*.

Based on this comment of OP I now use `()` as truthy value, and anything else as falsey. If both values need to be consistent instead of just one, it would be the old 16-bytes answer instead (`…(ÿ)…(()∞„()©:®Q`), returning `0` for truthy and `1` for falsey test cases.

Try it online or verify all test cases.

**Explanation**

```
…(ÿ)             # Take the input (implicitly) and surround it with "(" and ")"
            :    # Infinite replacement of:
    …(()∞        #  "(()())"    ("(()" mirrored)
         „()     #  with "()"
                 # After the infinite replacement: return the result
                 # ("()" for truthy; falsey otherwise)

```

---

(Old 18-bytes answer which failed for test case `()(()()(()())(()()))`..):

```
ΔD„()∞©6∍å_i®õ.:]Ā

```

Try it online or verify all test cases.

# Answer
> 2 votes
# APL (Dyalog Classic), 27 bytes

```
3>≢'<<><>>'⎕r'<>'⍣≡1⌽'><',⎕

```

Try it online!

# Answer
> 2 votes
# Prolog, 46 bytes

```
a-->p,p.
a-->[].
p-->[l],a,[r].
f(X):-a(X,[]).

```

Try it online! or Verify all test cases!

Uses lists of `l` and `r` as input, e.g. `"()()"` is tested as `f([l,r,l,r]).`.

The first three lines are the grammar of valid strings in Prolog's Definite Clause Grammar syntax. `a(A,B).` returns `true` when `A` is a list which follows the grammar and `B` is empty. Thus the main function `f` takes some `X` and checks whether `a(X,[])` holds.

# Answer
> 2 votes
# Python 2, ~~73~~ 71 bytes

```
f=lambda s,P='(()())':P in s and f(s.replace(P,'()'))or s in['()()','']

```

Try it online!

# Answer
> 1 votes
# Java 10, ~~99~~ ~~96~~ ~~95~~ 83 bytes

```
s->{s="("+s+")";for(var p="";!p.equals(s);s=s.replace("(()())","()"))p=s;return s;}

```

Port of my 05AB1E answer (so also returns `()` as truthy and anything else as falsey).

Try it online.

**Explanation:**

```
s->{                 // Method with String as both parameter and return-type
  s="("+s+")";       //  Surround the input-String between "(" and ")"
  for(var p="";      //  Previous-String, starting empty
      !p.equals(s)   //  Loop as long as the previous and current Strings differ
      ;              //    After every iteration:
       s=s.replace("(()())","()"))
                     //     Replace all "(()())" with "()"
    p=s;             //   Set the previous String with the current
  return s;}         //  Return the modified input-String
                     //  (if it's now "()" it's truthy; falsey otherwise)

```

`return s;` can be `return"()".equals(s);` if an actual boolean result was required.

# Answer
> 1 votes
# Python2, ~~95~~ 94 bytes

```
f=lambda i:g(eval("(%s)"%i.replace(")","),")))
g=lambda i:len(i)in(0,2)and all(g(j)for j in i)

```

Try it online!

f() transforms the string into a nested tuple, which it passes to g().

g() recursively navigates the tuple and returns False if any element doesn't have exactly 0 or 2 children.

Saved one byte by using string formatting.

# Answer
> 1 votes
## brainfuck, 50 bytes

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

```

Formatted:

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

```

Expects a string of `(` and `)` without a trailing newline, and outputs `\x01` for true and `\x00` for false. (For legibility, you can e.g. add 48 `+`s before the final `.` to make it print `1` and `0` instead.)

Try it online

This maintains a stack with the number of groups at each depth, distinguishing characters by parity and checking whether the number of groups is in {0, 2} after each close parenthesis; if the condition is not met, consumes the rest of the input and sets a flag; then checks the condition again at the end of the program.

If we are allowed to terminate the input stream with an odd character, we can omit the final check `<[--[>->]]` to save 10 bytes. (If `\n` weren't inconveniently even, I might have proposed this variant as the main answer.)

(We could also save some bytes by changing the output format to `\x00` for true and non-`\x00` for false, which seems to be allowed (maybe accidentally) by the problem statement as written, but anyway it wouldn't be very interesting, and I prefer not to make that change.)

# Answer
> 1 votes
# Stax, ~~13~~ 11 bytes

```
₧aaS▐îî»Å·╢

```

Run and debug it

I saved two bytes when I realized the inputs can coincidentally be implicitly evalled as array literals. By removing the double quotes, the input is simplified.

The general idea is to eval the input as an array literal, and recursively map the elements to check parethesly balance. If the final assertion ever fails, then there will be a subsequent pop on an empty stack. In stax, popping with empty stacks immediately terminates the program.

Unpacked, ungolfed, and commented, it looks like this.

```
        input is implicitly treated as array literals
L       wrap entire input stack in an array
G       jump to the trailing '}', and come back when done
}       terminate the program, the rest is a recursive call target
{Gm     map array on top of the stack by using the recursive call target
%       get the length of the mapped array
02\#    is the length one of [0, 2]?
|c      assert value is truthy, pop if not

```

Run this one

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


title: Map of Islands (and a river)

text:
# Question
Title: Map of Islands (and a river)
# Introduction

For many centuries, there has been a certain river that has never been mapped. The Guild of Cartographers want to produce a map of the river, however, they have never managed to succeed -- for some reason, all the cartographers they have sent to map the river have been eaten by wild animals in the area. A different approach is required.

# Input Description

The area is a rectangular grid of cells of length `m` and width `n`. The cell in the bottom left would be `0,0`, and the cell in the top right would be `m-1,n-1`. `m` and `n` are provided in the input as a tuple `m,n`.

By using long distance geographical sounding techniques the location of islands around the river have been identified. The size of the islands (i.e. how many cells the island occupies) have also been identified but the shape has not. We supply this information in a tuple `s,x,y` where `s` is the size of the island, and `x` and `y` are the x and y positions of one particular cell of that island. Each tuple in the input is space separated, so here is an example input:

```
7,7 2,0,0 2,3,1 2,6,1 2,4,3 2,2,4 8,0,6 1,2,6 3,4,6

```

To illustrate more clearly, here are is the input on a graph:

```
 y 6|8 1 3
   5|
   4|  2
   3|    2
   2|
   1|   2  2
   0|2
     =======
     0123456
     x

```

# Output Description

Output a map using ASCII characters to represent parts of the area. Each cell will either be `#` (land) or `.` (water). The map should follow these rules:

1. **Definition.** An island is a orthogonally contiguous group of land cells that is bounded entirely by river cells and/or the border of the area.
2. **Definition.** A river is an orthogonally contiguous group of water cells that is bounded entirely by land cells and/or the border of the area, **and** does not contain "lakes" (2x2 areas of water cells).
3. **Rule**. The map shall contain exactly one river.
4. **Rule**. Each numbered cell in the input shall be part of an island containing exactly `s` cells.
5. **Rule**. Every island in the map shall contain exactly one of the numbered cells in the input.
6. **Rule**. There exists a single unique map for every input.

Here is the output of the example input:

```
#.#.##.
#....#.
#.##...
##..##.
###....
...##.#
##....#

```

Here is another input and output.

Input:

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

```

Output:

```
#.#.#
#.#.#
.....
###.#
.....

```

# Answer
> 10 votes
# C + PicoSAT, ~~2345~~ ~~995~~ 952 bytes

```
#include<picosat.h>
#define f(i,a)for(i=a;i;i--)
#define g(a)picosat_add(E,a)
#define b calloc(z+1,sizeof z)
#define e(a,q)if(a)A[q]^A[p]?l[q]++||(j[++k]=q):s[q]||(i[q]=p,u(q));
z,F,v,k,n,h,p,q,r,C,*x,*A,*i,*l,*s,*j,*m;u(p){s[m[++n]=p]=1;e(p%F-1,p-1)e(p%F,p+1)e(p>F,p-F)e(p<=F*v-F,p+F)}t(){f(q,k)l[j[q]]=0;f(q,n)s[m[q]]=0;k=n=0;i[p]=-1;u(p);}main(){void*E=picosat_init();if(scanf("%d,%d",&F,&v)-2)abort();z=F*v;for(x=b;scanf("%d,%d,%d",&r,&p,&q)==3;g(p),g(0))x[p=F-p+q*F]=r;f(p,F*v-F)if(p%F)g(p),g(p+1),g(p+F),g(p+F+1),g(0);for(A=b,i=b,l=b,s=b,j=b,m=b;!C;){picosat_sat(E,C=h=-1);f(p,F*v)A[p]=picosat_deref(E,p)>0,i[p]=0;f(p,F*v)if(x[p])if(i[q=p]){for(g(-q);i[q]+1;)q=i[q],g(-q);g(C=0);}else if(t(),r=n-x[p]){f(q,r<0?k:n)g(r<0?j[q]:-m[q]);g(C=0);}f(p,F*v)if(!i[p])if(t(),A[p]){g(-++z);f(q,k)g(j[q]);g(C=0);f(q,n)g(-m[q]),g(z),g(0);}else{C&=h++;f(q,k)g(-j[q]);g(++z);g(++z);g(0);f(q,F*v)g(s[q]-z),g(q),g(0);}}f(p,F*v)putchar(A[p]?35:46),p%F-1||puts("");}

```

Try it online!

(Warning: this TIO link is a 30 kilobyte URL that contains a minified copy of PicoSAT 965, so you might not be able to load it in some browsers, but it loads in at least Firefox and Chrome.)

### How it works

We initialize the SAT solver with a variable for each cell (land or water), and only the following constraints:

1. Every numbered cell is land.
2. Every 2×2 rectangle has at least one land.

The rest of the constraints are difficult to encode directly into SAT, so instead we run the solver to get a model, run a sequence of depth-first searches to find the connected regions of this model, and add additional constraints as follows:

3. For every numbered cell in a land region that’s too big, add a constraint that there should be at least one water cell among the current land cells in that region.
4. For every numbered cell in a land region that’s too small, add a constraint that there should be at least one land cell among the current water cells bordering that region.
5. For every numbered cell in the same land region as another numbered cell, add a constraint that there should be at least one water cell along the path of current land cells between them (found by walking the parent pointers left over from the depth-first search).
6. For every land region including no numbered cells, add constraints that either
    * all of those current land cells should be water, or
    * at least one of the current water cells bordering that region should be land.
7. For every water region, add constraints that either
    * all of those current water cells should be land, or
    * every cell other than those current water cells should be land, or
    * at least one of the current land cells bordering that region should be water.

Taking advantage of the incremental interface to the PicoSAT library, we can immediately rerun the solver including the added constraints, preserving all the previous inferences made by the solver. PicoSAT gives us a new model, and we continue iterating the above steps until the solution is valid.

This is remarkably effective; it solves 15×15 and 20×20 instances in a tiny fraction of a second.

(Thanks to Lopsy for suggesting this idea of interactively constraining connected regions in an incremental SAT solver, a while back.)

### Some larger test cases from puzzle-nurikabe.com

A random page of 15×15 hard puzzles (5057541, 5122197, 5383030, 6275294, 6646970, 6944232):

```
15,15 1,5,1 3,9,1 5,4,2 1,6,2 2,11,2 2,2,3 3,9,3 2,4,4 1,10,4 5,12,4 3,1,5 1,3,5 3,8,5 1,13,5 5,5,6 1,12,6 1,2,8 2,9,8 1,1,9 2,6,9 6,11,9 3,13,9 5,2,10 2,4,10 4,10,10 1,5,11 2,12,11 2,3,12 2,8,12 5,10,12 1,5,13 1,9,13 1,6,14 1,8,14
15,15 4,2,0 2,5,0 1,3,1 2,14,2 1,3,3 2,11,3 1,13,3 1,5,4 11,7,4 1,9,4 1,4,5 1,8,5 2,10,5 12,14,5 3,5,6 1,4,7 2,10,7 3,9,8 4,0,9 1,4,9 1,6,9 3,10,9 1,5,10 1,7,10 8,9,10 1,1,11 10,3,11 2,11,11 6,0,12 1,11,13 2,9,14 1,12,14
15,15 2,2,0 8,10,0 2,3,1 2,14,2 2,3,3 3,5,3 3,9,3 2,11,3 5,13,3 6,0,4 3,7,4 3,3,5 2,11,5 2,6,6 1,8,6 1,4,7 2,10,7 1,6,8 2,8,8 5,3,9 2,11,9 2,7,10 7,14,10 2,1,11 4,3,11 2,5,11 1,9,11 2,11,11 2,0,12 4,6,13 1,11,13 3,4,14 1,12,14
15,15 2,0,0 2,4,0 3,6,1 2,10,1 1,13,1 2,5,2 2,12,2 3,0,3 2,2,3 4,7,3 2,9,3 1,14,3 1,4,4 1,8,4 2,12,5 4,2,6 3,4,6 1,14,6 7,7,7 1,10,8 2,12,8 3,2,9 2,14,9 2,0,10 2,6,10 1,10,10 2,5,11 4,7,11 2,12,11 1,14,11 3,2,12 3,9,12 1,1,13 2,4,13 3,8,13 2,10,14 5,14,14
15,15 1,3,0 1,14,0 3,7,1 3,10,1 2,13,1 3,1,2 4,5,2 2,12,3 3,3,4 1,8,4 1,1,5 3,5,5 1,9,5 5,13,5 3,3,6 1,8,6 2,2,7 2,12,7 1,6,8 1,8,8 2,11,8 2,1,9 4,5,9 2,9,9 2,13,9 2,6,10 4,11,10 1,2,11 3,9,12 2,13,12 3,1,13 2,4,13 3,7,13 1,0,14
15,15 2,8,0 2,4,1 2,7,1 1,10,1 6,4,3 1,1,4 12,5,4 3,11,4 5,13,4 3,10,5 3,0,6 1,6,6 2,8,6 4,13,7 2,3,8 1,6,8 3,8,8 2,14,8 2,4,9 5,1,10 4,3,10 1,9,10 6,13,10 3,8,11 1,10,11 3,4,13 2,7,13 3,10,13 1,6,14 1,14,14

```

A random page of 20×20 normal puzzles (536628, 3757659):

```
20,20 1,0,0 3,2,0 2,6,0 1,13,0 3,9,1 3,15,1 2,7,2 3,13,2 3,0,3 2,3,3 3,18,3 3,5,4 2,9,4 2,11,4 2,16,4 1,0,5 2,7,5 1,10,5 1,19,5 3,2,6 1,11,6 2,17,6 2,0,7 3,4,7 5,6,7 2,9,7 4,13,7 3,15,7 1,3,8 1,10,8 1,14,9 2,18,9 3,1,10 2,4,10 1,8,10 1,10,10 3,12,10 3,16,10 1,9,11 1,17,11 2,19,11 2,0,12 2,2,12 1,4,12 4,6,12 2,13,12 2,15,12 1,14,13 2,17,13 1,3,14 2,5,14 4,7,14 2,15,14 3,0,15 1,2,15 2,13,15 3,18,15 3,7,16 7,10,16 1,17,16 2,0,17 2,3,17 2,5,17 3,11,17 3,15,17 1,0,19 1,2,19 1,4,19 2,6,19 5,8,19 1,11,19 1,13,19 3,15,19 2,18,19
20,20 1,0,0 1,4,0 5,8,0 1,17,0 1,19,0 2,17,2 3,6,3 2,10,3 2,12,3 4,14,3 6,0,4 3,4,4 4,7,4 1,11,4 1,18,4 1,6,5 3,12,5 4,15,5 4,4,6 2,16,6 2,19,6 6,0,7 3,10,7 2,12,8 2,17,8 3,3,9 2,5,9 4,8,9 2,10,9 3,0,10 1,2,10 5,14,10 2,16,10 2,19,10 7,7,11 3,12,12 2,17,12 2,2,13 4,4,13 3,6,13 4,14,13 3,0,14 1,3,14 1,5,14 3,16,14 1,2,15 1,9,15 2,11,15 5,13,15 3,19,15 1,4,16 3,6,16 1,3,17 1,12,17 1,14,17 1,16,17 6,0,19 2,2,19 3,5,19 2,7,19 5,9,19 1,11,19 2,13,19 1,15,19 4,17,19

```

# Answer
> 3 votes
# GLPK/GNU MathProg, ~~1286~~ ~~1227~~ ~~1086~~ ~~998~~ 947 bytes

The main idea is to encode the "contiguous islands" constraint by introducing a preserved flow variable that has a pre-specified source at the hint location. The decision variable `is_island` then plays the role of placeable sinks. By minimizing the total sum of this flow, the islands are forced to remain connected in the optimum. The other constraints rather directly implement the various rules. What puzzles me that I still seem to need `island_fields_have_at_least_one_neighbor`.

Performance of this formulation is not great, though. By directly eating all the complexity with a large amount of constraints, the solver takes close to 15 seconds for the 15 x 15 example.

## Code (golfed)

```
param M;param N;param P;set X:=0..N-1;set Y:=0..M-1;set Z:=0..P-1;set V:=X cross Y;set E:=setof{(p,q)in V,(r,s)in V:((abs(p-r)=1)&&(q=s))||((p=r)&&(abs(q-s)=1))}(p,q,r,s);param I{X,Y,Z},default 0;param t{z in Z}:=sum{x in X,y in Y}I[x,y,z];var u{X,Y},binary;var v{X,Y,Z},integer;var w{E,Z}>=0;minimize o:sum{(p,q,r,s)in E,z in Z}w[p,q,r,s,z];a{(x,y)in V,z in Z}:I[x,y,z]+sum{(p,q,r,s)in E:x=r&&y=s}w[p,q,x,y,z]-sum{(p,q,r,s)in E:x=p&&y=q}w[x,y,r,s,z]=v[x,y,z];b{(x,y)in V,z in Z}:v[x,y,z]*99>=I[x,y,z];c{(x,y)in V}:u[x,y]+sum{z in Z}v[x,y,z]=1;d{z in Z}:sum{(x,y)in V}v[x,y,z]=t[z];e{(x,y)in V:x>0&&y>0}:3>=u[x,y]+u[x-1,y-1]+u[x-1,y]+u[x,y-1];f{(x,y)in V}:sum{(p,q,r,s)in E:x=r&&y=s}u[p,q]>=u[x,y];g{(x,y)in V,z in Z:t[z]>1}:sum{(p,q,r,s)in E:x=r&&y=s}v[p,q,z]>=v[x,y,z];h{(x,y)in V,z in Z}:sum{(p,q,r,s)in E,oz in Z:x=p&&y=q&&z!=oz}v[r,s,oz]<=4*P*(1-v[x,y,z]);solve;for{y in M-1..0 by -1}{for{x in X}printf if u[x,y]=1 then"."else"#";printf"\n";}

```

## Code (ungolfed)

```
# SETS
param M > 0, integer; # height
param N > 0, integer; # width
param P > 0, integer; # no. of islands

set X := 0..N-1;  # set of x coords
set Y := 0..M-1;  # set of y coords
set Z := 0..P-1;  # set of I

set V := X cross Y;
set E within V cross V := setof{
  (sx, sy) in V, (tx, ty) in V :

  ((abs(sx - tx) = 1) and (sy = ty)) or
  ((sx = tx) and (abs(sy - ty) = 1))
}
  (sx, sy, tx, ty);

# PARAMETERS
param I{x in X, y in Y, z in Z}, integer, default 0;
param island_area{z in Z} := sum{x in X, y in Y} I[x, y, z];

# VARIABLES
var is_river{x in X, y in Y}, binary;
var is_island{x in X, y in Y, z in Z}, binary;
var flow{(sx, sy, tx, ty) in E, z in Z} >= 0;

# OBJECTIVE
minimize obj: sum{(sx, sy, tx, ty) in E, z in Z} flow[sx, sy, tx, ty, z];

# CONSTRAINTS
s.t. I_are_connected{(x, y) in V, z in Z}:

    I[x, y, z]
  - is_island[x, y, z]
  + sum{(sx, sy, tx, ty) in E: x = tx and y = ty} flow[sx, sy, x, y, z]
  - sum{(sx, sy, tx, ty) in E: x = sx and y = sy} flow[x, y, tx, ty, z]
  = 0;

s.t. island_contains_hint_location{(x, y) in V, z in Z}:

    is_island[x, y, z] >= if I[x, y, z] > 0 then 1 else 0;

s.t. each_square_is_river_or_island{(x, y) in V}:

    is_river[x, y] + sum{z in Z} is_island[x, y, z] = 1;

s.t. I_match_hint_area{z in Z}:

    sum{(x, y) in V} is_island[x, y, z] = island_area[z];

s.t. river_has_no_lakes{(x,y) in V: x > 0 and y > 0}:

  3 >= is_river[x, y] + is_river[x - 1, y - 1]
     + is_river[x - 1, y] + is_river[x, y - 1];

s.t. river_squares_have_at_least_one_neighbor{(x, y) in V}:

    sum{(sx, sy, tx, ty) in E: x = tx and y = ty} is_river[sx, sy]
 >= is_river[x, y];

s.t. island_fields_have_at_least_one_neighbor{(x, y) in V, z in Z: island_area[z] > 1}:

    sum{(sx, sy, tx, ty) in E: x = tx and y = ty} is_island[sx, sy, z]
 >= is_island[x, y, z];

s.t. I_are_separated_by_water{(x, y) in V, z in Z}:

    sum{(sx, sy, tx, ty) in E, oz in Z: x = sx and y = sy and z != oz}
        is_island[tx, ty, oz]
 <= 4 * P * (1 - is_island[x, y, z]);

solve;

for{y in M-1..0 by -1}
{
    for {x in X}
    {
        printf "%s", if is_river[x, y] = 1 then "." else "#";
    }
    printf "\n";
}

```

## Problem data

### 5 x 5

```
data;
param M := 5;
param N := 5;
param P := 5;
param I:=
# x,y,z,area
  0,1,0,3
  4,1,1,1
  0,4,2,2
  2,4,3,2
  4,4,4,2;
end;

```

### 7 x 7

```
data;
param M := 7;
param N := 7;
param P := 8;
param I:=
# x,y,z,area
  0,0,0,2
  3,1,1,2
  6,1,2,2
  4,3,3,2
  2,4,4,2
  0,6,5,8
  2,6,6,1
  4,6,7,3;
end;

```

### 15 x 15

```
data;
param M := 15;
param N := 15;
param P := 34;
param I:=
# x,y,   z,area
5,  1,   0, 1
9,  1,   1, 3
4,  2,   2, 5
6,  2,   3, 1
11, 2,   4, 2
2,  3,   5, 2
9,  3,   6, 3
4,  4,   7, 2
10, 4,   8, 1
12, 4,   9, 5
1,  5,  10, 3
3,  5,  11, 1
8,  5,  12, 3
13, 5,  13, 1
5,  6,  14, 5
12, 6,  15, 1
2,  8,  16, 1
9,  8,  17, 2
1,  9,  18, 1
6,  9,  19, 2
11, 9,  20, 6
13, 9,  21, 3
2,  10, 22, 5
4,  10, 23, 2
10, 10, 24, 4
5,  11, 25, 1
12, 11, 26, 2
3,  12, 27, 2
8,  12, 28, 2
10, 12, 29, 5
5,  13, 30, 1
9,  13, 31, 1
6,  14, 32, 1
8,  14  33, 1;
end;

```

## Usage

Have `glpsol` installed, model as one file (e.g. `river.mod`), input data in separate file(s) (e.g. `7x7.mod`). Then:

```
glpsol -m river.mod -d 7x7.mod

```

This plus some patience will print the solution in the specified output format (together with "some" diagnostic output).

# Answer
> 3 votes
# Python 3, 1295 bytes

This is a python only solution. It uses no libraries and loads the board through standard input. Further explanation to come. This is my first attempt at such a large golf. There is a link to the commented and none-golfed code at the bottom.

```
L,S,O,R,F=len,set,None,range,frozenset
U,N,J,D,I=S.update,F.union,F.isdisjoint,F.difference,F.intersection
def r(n,a,c):
 U(c,P)
 if L(I(N(Q[n],C[n]),a))<2:return 1
 w=D(P,N(a,[n]));e=S();u=S([next(iter(w))])
 while u:n=I(Q[u.pop()],w);U(u,D(n,e));U(e,n)
 return L(e)==L(w)
def T(a,o,i,c,k):
 s,p,m=a
 for _ in o:
  t=s,p,N(m,[_]);e=D(o,[_])
  if t[2] in c:o=e;continue
  c.add(t[2]);n=D(Q[_],m);U(k,n)
  if not J(i,n)or not r(_,N(m,i),k):o=e
  elif s==L(t[2]):yield t
  else:yield from T(t,N(e,n),i,c,k)
s,*p=input().split()
X,Y=eval(s)
A=[]
l=1,-1,0,0
P=F((x,y)for y in R(Y)for x in R(X))
exec("Q%sl,l[::-1]%s;C%s(1,1,-1,-1),l[:2]*2%s"%(('={(x,y):F((x+i,y+j)for i,j in zip(',')if X>x+i>-1<y+j<Y)for x,y in P}')*2))
for a in p:a,x,y=eval(a);k=x,y;A+=[(a,k,F([k]))]
A.sort(reverse=1)
k=F(a[1]for a in A)
p=[O]*L([a for a in A if a[0]!=1])
g,h=p[:],p[:]
i=0
while 1:
 if g[i]is O:h[i]=S();f=O;g[i]=T(A[i],Q[A[i][1]],D(N(k,*p[:i]),[A[i][1]]),S(),h[i])
 try:p[i]=g[i].send(f)[2]
 except:
  f=I(N(k,*p[:i]),h[i]);g[i]=p[i]=O;i-=1
  while J(p[i],f):g[i]=p[i]=O;i-=1
 else:
  i+=1
  if i==L(p):
   z=N(k,*p)
   if not any(J(z,F(zip([x,x+1]*2,[y,y,y+1,y+1])))for x in R(X-1)for y in R(Y-1)):break
   for c in h:U(c,z)
b=[X*['.']for i in R(Y)]
for x,y in z:b[y][x]='#'
for l in b[::-1]:print(''.join(l))

```

Try it online!

Un-golfed code here.

---
Tags: code-golf, graph-theory
---


title: Print the Nth non-palindromic number

text:
# Question
Title: Print the Nth non-palindromic number
A palindromic number (in case you don't know) is a number which reads the same backwards and forwards (example, 11). The first 15 non-palindromic numbers are: `10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26`. This is A029742. I constantly need these numbers, but my sticky note pad is very small, so your code must be as short as possible.

## Rules

* Each submission must be a full program or function (e.g. in C, you can't just define a function without headers, but you can define a function WITH necessary headers ).
* If it is possible, provide a link to a site where your program can be tested.
* Your program must not write anything to `STDERR`.
* You can take input as an argument or from `STDIN` (or the closest alternative in your language).
* Programs are scored according to *bytes*. The usual character set is UTF-8, if you are using another please specify.
* Standard loopholes are forbidden.

## Test Cases

```
1
==> 10

-----

5
==> 15

-----

12
==> 23

```

## Scoring

This is , so least bytes wins.

## Submissions

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
# Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

## Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

```
/* Configuration */

var QUESTION_ID = 79251; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 53406; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/<a/.test(lang)) lang = jQuery(lang).text();

    languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang > b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
```

```
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<div id="language-list">
  <h2>Winners by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
```

# Answer
# Pyth, 7 bytes

```
e.f!_I`

```

Test suite

**Explanation:**

```
e.f!_I`
e.f!_I`ZQ    Implicit variable introduction.
 .f     Q    Find the first Q numbers whether the following is truthy,
             starting at 1, where Q is the input.
      `Z     Convert the number to a string.
     _I      Check if it's the same when reversed.
    !        Logical not.
 e           Return the last element of the list.

```
> 9 votes

# Answer
## Haskell, 38 bytes

```
([x|x<-[1..],(/=)<*>reverse$show x]!!)

```

Uses 0-based index. `([x|x<-[1..],(/=)<*>reverse$show x]!!) 11` -\> `23`.

The test whether to keep a number `(/=)<*>reverse$show x` translates to `(show x) /= (reverse (show x))`, i.e check if the string representation of the number does not equal the reverse of the string representation.
> 5 votes

# Answer
# Brachylog, ~~14~~ 11 bytes

```
;0{<≜.↔¬}ⁱ⁽

```

-3 bytes tanks to Fatalize

## Explanation

```
; {      }ⁱ⁽        --  Find the nth number
 0                  --      (starting with 0)
   <                --      which is bigger then the previous one
    ≜               --      make explicit (otherwise it fucks up)
      .             --      which is the output
       ↔            --      and if reversed
        ¬           --      is not the output

```

Try it online!
> 4 votes

# Answer
# Jelly, 9 bytes

1 bytes thanks to @Sp3000.

```
ṚḌ_
0Ç³#Ṫ

```

Try it online!

Test suite.

## Explanation

```
DUḌ_   Helper link. Check if x is not palindrome.

D      Convert to decimal.
 U     Reverse.
  Ḍ    Convert back to integer.
   _   Subtract x from the result above.
       For 23, this will yield 32-23 = 9.
       Only yield 0 (falsy) if x is palindrome.
       If x is not a palindrome,
       it will return a truthy number.

0Ç³#Ṫ  Main link.

0      Start from 0.
   #   Find the first         numbers:
  ³                   <input>
 Ç         where the above link returns a truthy number.
    Ṫ  Yield the last of the matches.

```
> 3 votes

# Answer
# 05AB1E, 8 bytes

Code:

```
µNÂÂQ>i¼

```

Uses **CP-1252** encoding. Try it online!.
> 3 votes

# Answer
# Clojure, 62 bytes

```
#(nth(for[i(range):when(not=(seq(str i))(reverse(str i)))]i)%)

```

0-indexed. Generate lazily infinite range of non-palindromic numbers using list comprehension and take `i`th one. See it online: https://ideone.com/54wXI3
> 3 votes

# Answer
## PowerShell v2+, 65 bytes

```
for(;$j-lt$args[0]){if(++$i-ne-join"$i"["$i".length..0]){$j++}}$i

```

Loops through numbers from `0` (implicit value for uninitialized `$i`) until we find input `$args[0]` many matches, then outputs the last one. Note that we don't initialize the loop, so `$j=0` is implicit.

Each iteration, we pre-increment `$i`, and check if it's not-equal to `$i` reversed. If so, that means we've found a non-palindrome, so increment `$j`. The loop then continues as many times as necessary.

### Examples

```
PS C:\Tools\Scripts\golfing> .\print-nth-palindromic-number.ps1 100
120

PS C:\Tools\Scripts\golfing> .\print-nth-palindromic-number.ps1 5
15

PS C:\Tools\Scripts\golfing> .\print-nth-palindromic-number.ps1 55
70

PS C:\Tools\Scripts\golfing> .\print-nth-palindromic-number.ps1 212
245

```
> 2 votes

# Answer
# Python 2, 60 bytes

```
f=lambda n,i=0,j=1:j>n and i-1or f(n,i+1,j+(`i`!=`i`[::-1]))

```

A one-indexed function that takes input of `n` via argument and returns the `n`th non-palindromic number.

**How it works**

This is an exhaustive recursive search, which consecutively tests integers `i` in the range `[1,∞)` until `n` non-palindromic numbers have been found; since `i` is pre-incremented, `i-1` is then returned. Testing whether a number is palindromic is performed by converting to a string, reversing, and then checking whether the original and reversed strings are equal.

The code is logically equivalent to:

```
def f(n,test=0,count=1):
    if count>n:
        return test
    elif str(test)!=reversed(str(test)):
        return f(n,test+1,count+1)
    else:
        return f(n,test+1,count)

```

which itself is essentially:

```
def f(n):
    test=0
    count=1
    while count<=n:
        if str(test)!=reversed(str(test)):
            count+=1
        test+=1
    return test-1

```

Try it on Ideone
> 2 votes

# Answer
## Clojure, 62 bytes

```
#(nth(filter(fn[i](not=(seq i)(reverse i)))(map str(range)))%)

```

A quite different approach than the other answer, but equal length.
> 2 votes

# Answer
# Forth (gforth), 103 99 bytes

```
: f 9 swap 0 do begin 1+ dup 0 over begin 10 /mod >r swap 10 * + r> ?dup 0= until = 0= until loop ;

```

Try it online!

### Explanation

Loop n times, each iteration finds the next non-palindromic number by incrementing a counter by 1 until the number doesn't equal itself reversed

### Ungolfed Code

Normally I wouldn't "ungolf" the code, but since this code is somewhat messy I figured it would help

```
: reverse ( s -- s )
    0 swap
    begin
        10 /mod
        >r swap
        10 * +
        r> ?dup 0=
    until
;

: f ( s -- s )
    9 swap 0
    0
    do
        begin
            1+ dup dup
            reverse =
        0= until
    loop
;

```

### Code Explanation

```
: f                \ start a new word definition
  9                \ start at 9, since all positive ints < 10 are palindromic
  swap 0           \ set up loop parameters from 0 to n-1
  do               \ start a counted loop
    begin          \ start an indefinite loop
      1+ dup       \ increment counter and place a copy on the stack
      ( Reverse )
      0 over       \ add 0 to the stack (as a buffer) and copy the top counter above it
      begin        \ start another indefinite loop
        10 /mod    \ get the quotient and remainder of dividing the number by 10
        >r         \ store the quotient on the return stack
        swap 10 *  \ multiply the current buffer by 10
        +          \ add the remainder to the buffer
        r>         \ grab the quotient from the return stack
        ?dup       \ duplicate if not equal to 0
        0=         \ check if equal to 0
      until        \ end inner indefinite loop if quotient is 0
      ( End Reverse )
      = 0=         \ check if counter =/= reverse-counter
    until          \ end the outer indefinite loop if counter =/= reverse-counter
  loop             \ end the counted loop
;                  \ end the word definition

```
> 2 votes

# Answer
# , ~~133~~ ~~117~~ ~~93~~ 76 bytes

-16 bytes thanks to JayCe. -41 bytes thanks to Giuseppe.

```
x=scan();while({F=F+any((D=T%/%10^(1:nchar(T)-1)%%10)!=rev(D));F<=x})T=T+1;T

```

Try it online!
> 2 votes

# Answer
# Perl 6, 29 bytes

```
{grep({$_!= .flip},^Inf)[$_]}

```

( uses 0 based index )

```
{         # The $_ is implied above
  grep(   # V
    { $_ != $_.flip }, # only the non-palindromic elements of
    ^Inf               # an Infinite list ( 0,1,2,3 ...^ Inf )
  )[ $_ ]              # grab the value at the given index
}

```

### Usage:

```
my &non-palindrome = {grep({$_!= .flip},^Inf)[$_]}

say non-palindrome 1  - 1; # 10
say non-palindrome 5  - 1; # 15
say non-palindrome 12 - 1; # 23

# this also works:
say non-palindrome 0..20;
# (10 12 13 14 15 16 17 18 19 20 21 23 24 25 26 27 28 29 30 31 32)

```
> 1 votes

# Answer
## Actually, 17 bytes

```
;τR9+;`$;R=Y`M@░E

```

Try it online!

Values are 1-indexed. This could be easily changed to 0-indexed by replacing the first `R` with `r`. But, `R` is what I initially typed, so that's what I'm going with.

The nonpalindromic numbers satisfy `a(n) ≈ n + 10`, so `2n+9` is a sufficient upper bound.

Explanation:

```
;τR9+;`$;R=Y`M@░E
;τ9+R;             push n, range(1,(2*n)+10)
      `$;R=Y`M@░   take values that are not palindromic
                E  take nth element

```
> 1 votes

# Answer
## JavaScript (ES6), 54 bytes

Uses 1-based indexing. Only works up until the 7624th number.

```
d=(i,a=0)=>i?d(i-=++a!=[...''+a].reverse().join``,a):a

```

### Usage

```
d=(i,a=0)=>i?d(i-=++a!=[...''+a].reverse().join``,a):a
d(1)
10
d(123)
146
d(7624)
7800
d(7625)
// Uncaught RangeError: Maximum call stack size exceeded

```

---

## JavaScript (ES6), 59 bytes

Doesn't use recursion and so can handle much larger inputs.

```
i=>eval("for(a=9;i-=++a!=[...`${a}`].reverse().join``;);a")

```

### Usage

```
(i=>eval("for(a=9;i-=++a!=[...`${a}`].reverse().join``;);a"))(1)
10
(i=>eval("for(a=9;i-=++a!=[...`${a}`].reverse().join``;);a"))(7625)
7801
(i=>eval("for(a=9;i-=++a!=[...`${a}`].reverse().join``;);a"))(123456)
124579

```
> 1 votes

# Answer
# Java 8, ~~117~~ ~~95~~ 94 bytes

```
n->{int r=10;for(;n-->0;)if((++r+"").contains(new StringBuffer(r+"").reverse()))r++;return r;}

```

0-indexed

**Explanation:**

Try it here.

```
n->{             // Method with integer as both parameter and return-type
  int r=10;      //  Result-integer, starting at 10
  for(;n-->0;)   //  Loop an amount of times equal to the input
    if((++r+"")  //   First raise `r` by 1, and then check if `r`
               .contains(new StringBuffer(r+"").reverse()))
                 //   is the same as `r` reversed (and thus a palindrome)
      r++;       //    And if it is: raise `r` by 1 again
  return r;}     //  Return result-integer

```
> 1 votes

# Answer
# Ruby, 54 bytes

This function is 1-indexed and is partially based on Dom Hastings's Javascript answer. I think there's a way to golf this better, especially with that last ternary condition. Also, this function currently returns a string, which may need to be edited later. Any golfing suggestions are welcome.

```
f=->x,y=?9{x<1?y:(y.next!.reverse!=y)?f[x-1,y]:f[x,y]}

```

**Ungolfed:**

```
def f(x, y="9")
 if x<1
  return y
 else
  y = y.next
  if y.reverse != y
   return f(x-1, y)
  else
   return f(x, y)
  end
 end
end

```
> 1 votes

# Answer
## Javascript (using external library) (97 bytes)

```
n=>_.Sequence(n,i=>{i=_.From(i+"");if(!i.Reverse().SequenceEqual(i)){return i.Write("")}}).Last()

```

Link to lib: https://github.com/mvegh1/Enumerable

Code explanation: Library has static method called Sequence, where first param defines how many elements the sequence will guarantee to create, and the 2nd parameter is a predicate accepting the current iteration value, "i". The predicate converts the integer to a string, which gets converted to a char array by calling \_.From. The char array is compared against the reversal of the char array, and if they are not equal the char array is joined back into a string and returned. Otherwise, nothing is returned (i.e the result is undefined, which the library will always ignore). Finally, the last element of the sequence, i.e the Nth element is returned
> 1 votes

# Answer
## C++ (GCC), 148 bytes

It's 1-based and the algorithm is really naive

```
#import <iostream>
using namespace std;int n,i=1;string s;main(){cin>>n;while(s=to_string(i+1),(n+=equal(begin(s),end(s),s.rbegin()))-i++);cout<<i;}

```
> 1 votes

# Answer
## C, 84 bytes

Function `f(n)` takes integer `n` and returns `n-th` non-palindromic number (1 based).

```
g(n,r){return n?g(n/10,r*10+n%10):r;}s;f(n){for(s=9;n--;g(++s,0)==s&&s++);return s;}

```

Test it on Ideone!

It's fairly trivial code, thus there is probably space for improvement.
> 1 votes

# Answer
# APL NARS 35 chars

```
r←v a;c
r←c←0
A:r+←1⋄c+←r≠⍎⌽⍕r⋄→A×⍳c<a

```

it is the function v; "⍎⌽⍕"r traslate number r in string, reverse that string, traslate from string to number. Test and help functions:

```
  ⍝ return the one string for the basic types ('Char', 'Int', 'Float', 'Complex or Quaternion or Oction')
  ⍝ or one string for composite types ('Tensor 3' 'Tensor 4' etc 'Matrix', 'List', 'String')
  ⍝ follow the example in: https://codegolf.stackexchange.com/a/39745
  type←{v←⍴⍴⍵⋄v>2:'Tensor ',⍕v⋄v=2:'Matrix'⋄(v=1)∧''≡0↑⍵:'String'⋄''≡0↑⍵:'Char'⋄v=1:'List'⋄⍵≢+⍵:'Complex or Quaternion or Oction'⋄⍵=⌈⍵:'Int'⋄'Float'}
  h←{'Int'≢type ⍵:¯1⋄(⍵<1)∨⍵>2e5:¯1⋄v ⍵}
  h 1
10
  h 1.32
¯1
  h 7878
8057
  h¨3 5 12
13 15 23
  h 6 7 8
¯1
  h '123'
¯1
  h '1'
¯1
  h 1.0
10
  h 1.0003
¯1
  h ¯2
¯1
  h 0
¯1
  h 200000
201200
  h 200001
¯1

```
> 1 votes

# Answer
# Japt, ~~14~~ ... ~~9~~ 7 bytes

0-indexed.

```
È¦sw}iU

```

Try it

```
È¦sw}iU     :Implicit input of integer U
È           :Function taking an integer X as an argument
 ¦          :  Test for inequality with
  s         :  Convert to string
   w        :  Reverse
    }       :End function
     iU     :Get the Uth integer that returns true

```
> 1 votes

# Answer
# Husk, 6 bytes

Yay for  :)

```
!fS≠↔N

```

Try it online!

### Explanation

```
 f   N  -- filter the naturals by:
  S≠    --   is it not equal to..
    ↔   --   ..itself reversed
!       -- index into that list

```
> 1 votes

# Answer
# Perl 5, 33 + 1 (`-p`) = 34 bytes

```
map{1until++$\!=reverse$\}1..$_}{

```

Try it online!
> 1 votes

# Answer
# C# 7, 89 bytes

```
n=>{int i=9;for(;n-->0;)if(Enumerable.SequenceEqual(++i+"",(""+i).Reverse()))i++;return i;}

```

1 indexed Try on Repl.It

```
n=>
  int i = 9;                                  | Start at 9. Iterate exactly n times. Assume n >= 1
  for(;n-->0;)                                | Iterate n times
  if(EnumerableSequenceEqual(                 | Compare two sequences
  ++i+"",(""+i).Reverse())                    | Generate the forward and backward strings, which behave like char sequences for Linq
  i++                                         | If the sequences are equal, the number is a palindrome. Increment i to skip
  return i;                                   | Return the number after the for loop exits

```

I don't think this uses any language features from c# 7, but I put there since that's what I tested against
> 1 votes

# Answer
## TCC, 11 bytes

```
?>!~<>;i;'T

```

Try it online!

```
            | Printing is implicit
?>          | Find n-th number for which the following is "T":
  !~        | If not equal...
    <>;     | reverse. No value specified, so input is assumed.
       i;   | Input, since double semicolons are ignored
         'T | ... print string "T"

```
> -2 votes

---
Tags: code-golf, number, sequence, palindrome
---