# Question
Title: Implement 1-dimensional version of Multi-Take
## Background

Adám and I were once discussing a way to properly extend some features in Dyalog APL. I came up with the following extension to Take, a function that takes some front or back elements (and an analogous extension to Drop). We agreed that it was a good idea, but it was incredibly hard to come up with a piece of code that imitates the behavior.

While the original proposal operates on multi-dimensional arrays, this challenge's scope is limited to 1D arrays of numbers. Whenever I mention "array", it implies a 1D array.

## The Take function

takes two arguments. One is the array `A` (of length `L`), and the other is a single integer `N` (which can be 0, positive, or negative).

The behavior depends on the value of `N`:

* If `0 ≤ N ≤ L`,  takes first `N` elements of `A` from the start.
* If `-L ≤ N < 0`,  takes last `-N` elements of `A` from the end.
* If `N > L` or `N < -L`,  performs "overtake", appending (for positive `N`) or prepending (for negative `N`) zeros until the array's length becomes `abs(N)`.

It can be thought of applying a Boolean mask to an infinitely zero-padded version of `A`:

```
For all cases, A = [1, 2, 3, 4, 5]

For N = 3: (positive simple take)
A     :  ... 0 0 1 2 3 4 5 0 0 ...
Mask  :  ... 0 0 1 1 1 0 0 0 0 ...  # Fill 1s from the start of the array
Result:          1 2 3              # Elements at 0 mask are removed from the array

For N = -4: (negative simple take)
A     :  ... 0 0 1 2 3 4 5 0 0 ...
Mask  :  ... 0 0 0 1 1 1 1 0 0 ...  # Fill 1s from the end of the array
Result:            2 3 4 5

For N = 7: (positive overtake)
A     :  ... 0 0 1 2 3 4 5 0 0 0 ...
Mask  :  ... 0 0 1 1 1 1 1 1 1 0 ...  # The mask overflows the input array
Result:          1 2 3 4 5 0 0

For N = -8: (negative overtake)
A     :  ... 0 0 0 0 1 2 3 4 5 0 0 ...
Mask  :  ... 0 1 1 1 1 1 1 1 1 0 0 ...  # The mask is filled from the end,
                                        # overflowing through the start
Result:        0 0 0 1 2 3 4 5

```

## The proposed extension ("Multi-Take")

The extension allows `N` to be an array of integers `[N1, N2, N3, ..., Nn]`. It conceptually generates all the masks to apply to `A` using each of `Ni`, and combines all of them by logical OR. Then the mask is applied to `A` in the same sense as above, giving the resulting array (which may have some contiguous middle elements removed, or have padding in both directions).

Because the identity element for OR is 0, empty `N` gives all-zero mask, resulting in an empty array (which is equivalent to giving a single zero as `N`).

```
For all cases, A = [1, 2, 3, 4, 5]

For N = [1, -2]: (removing a contiguous region)
A        :  1 2 3 4 5
Mask (1) :  1 0 0 0 0  # Taking from start
Mask (-2):  0 0 0 1 1  # Taking from end
OR       :  1 0 0 1 1
Result   :  1     4 5  # [1, 4, 5]

For N = [8, -7]: (padding in both direction)
A        :      1 2 3 4 5
Mask (8) :  0 0 1 1 1 1 1 1 1 1  # Overtaking from start
Mask (-7):  1 1 1 1 1 1 1 0 0 0  # Overtaking from end
OR       :  1 1 1 1 1 1 1 1 1 1
Result   :  0 0 1 2 3 4 5 0 0 0  # [0, 0, 1, 2, 3, 4, 5, 0, 0, 0]

For N = [2, 4, 7]: (for multiple values of same sign, some are simply shadowed)
A        :  1 2 3 4 5
Mask (2) :  1 1 0 0 0 0 0
Mask (4) :  1 1 1 1 0 0 0
Mask (7) :  1 1 1 1 1 1 1
OR       :  1 1 1 1 1 1 1  # Same as simply N = 7 or [7]
Result   :  1 2 3 4 5 0 0  # [1, 2, 3, 4, 5, 0, 0]

For N = []: (empty N gives empty result)
A     :  1 2 3 4 5
Mask  :  (None)     # No mask to apply
OR    :  0 0 0 0 0  # Identity element of OR
Result:  (Empty)    # []

```

## Challenge

Implement the extension, i.e. a program or function that takes an array of numbers `A` and an array of take amounts `N`, and outputs the modified array using the mechanism described above.

The "array" can be any sequential container type in your language of choice.

You can assume the elements of `A` are given in any common number type in your language of choice (or, if you're doing string I/O, represented in the most natural format for your language). Your program should be able to handle empty `A` and `A` containing zeros or duplicate elements.

You may assume `A` contains only integers even if your program accepts floating-point numbers as input.

Standard rules apply. The shortest code in bytes wins.

## Test cases

```
# These test cases all share A = 1 2 3 4 5
# Should work for any 5-element array A' = a b c d e
# giving the output's 1 2 3 4 5 substituted with a b c d e respectively,
# even if A' contains duplicates or zeros
N = (empty)
Output = (empty)
N = 3
Output = 1 2 3
N = 0
Output = (empty)
N = -4
Output = 2 3 4 5
N = 7
Output = 1 2 3 4 5 0 0
N = -8
Output = 0 0 0 1 2 3 4 5
N = 0 0 0 0 0
Output = (empty)
N = 0 4 2 3
Output = 1 2 3 4
N = -2 -1 0 -7
Output = 0 0 1 2 3 4 5
N = 0 2 -2 1 -1
Output = 1 2 4 5
N = -7 -5 -3 -1 1 3 5 7
Output = 0 0 1 2 3 4 5 0 0

-------------------------
# Noteworthy edge cases
A = 1 4 3 4 5
N = 0 2 -2
Output = 1 4 4 5

A = 1 2 0 4 5
N = 7 -8
Output = 0 0 0 1 2 0 4 5 0 0

-------------------------
# These test cases share A = (empty)
N = (empty)
Output = (empty)
N = 0 0 0 0 0
Output = (empty)
N = 3 1 4
Output = 0 0 0 0
N = -3 -1 -4
Output = 0 0 0 0
N = 3 1 -4 -1 5
Output = 0 0 0 0 0 0 0 0 0 (9 zeros)

```

# Answer
> 8 votes
# APL (Dyalog Unicode), ~~58~~ 50 bytes

```
{{2⊃{⍵[⍒⍴¨⍵]}(⍺,⍵)A⍺(⍵,⍺↓⍨≢A)}/((⌈/,⌊/)0,⍵)↑¨⊂A←⎕}

```

Try it online!

What better way to implement this than in APL itself? That being said, some of the logic is nontrivial.

Anonymous function that takes `N` as the right argument and `A` in standard input.

*-2 bytes thanks to @Bubbler*

*-1 byte thanks to @Adám*

### Explanation

Even though APL has the take function built-in, combining them requires a bit more work.

Firstly, as @Jonah noted, only the elements of `N` with the largest absolute value matter to the final result since all elements with smaller absolute value correspond to subarrays of those formed from higher absolute value. Aka, only the largest positive number and the most-negative negative number matter. We obtain those right off the bat with `(⌈/,⌊/)0,⍵`, where  is N. This produces a pair of the smallest number and the highest number in `0` appended to N. Appending `0` is important because it guarantees that the two numbers obtained are respectively non-positive and non-negative.

The convenient part is `↑¨⊂A←⎕`, where we use APL's built-in take () to obtain two arrays, one (call it `m`) counting backwards from the end, and one forwards from the start (call it `M`).

Here, it gets interesting. For non-trivial `A`, there are several cases to consider:

```
A =    1 2 3 4 5

1. M ⊆ m:
m: 0 0 1 2 3 4 5
M:     1 2 3
union: m

2. m ⊆ M:
m:         3 4 5
M:     1 2 3 4 5 0 0 0
union: M

3. Both m and M have 0s:
m: 0 0 1 2 3 4 5
M:     1 2 3 4 5 0 0 0
union: m,(the zeros of M)

4. Neither m nor M have 0s, but they overlap:
m:         3 4 5
M:     1 2 3 4
union: A

5. M and m do not overlap:
m:           4 5
M;     1 2
union: M,m

```

There are different ways to define the unions of the two arrays. For example, the union for case 3 could instead be `(the zeros of m),M`, but that is less useful for golfing due to precedence. Importantly, case 1 could analogously be defined as `m,(the zeros of M)` (same as case 3) since `M` has no zeros in case 1.

For cases 1 to 4, the union desired is the longest one out of `A`,`M`, and `m,(the zeros of M)`. For example, in the example for case 2 , `M` has length 8, which is longer than the other two possibilities: `A` has length 5, and `m,(the zeros of M)` has length 6. This holds true for all four of these cases, so all we have to do is compute all 3 possibile unions, then take the longest one.

This evidently does not hold true for case 5. `A` always has more elements than the desired union, so it would always be selected over `M,m`. This is only one conditional, so it is not particularly difficult to add in a quick check. However, `M,m` is the longest in cases 1 to 4, so we can instead take the second-longest out of `A`,`M`, `m,(the zeros of M)`, and `M,m`.

```
{{2⊃{⍵[⍒⍴¨⍵]}(⍺,⍵)A⍺(⍵,⍺↓⍨≢A)}/((⌈/,⌊/)0,⍵)↑¨⊂A←⎕}
{...}/(⌈/,⌊/)0,⍵}↑¨⊂A←⎕      ⍝ Compute m and M as discussed,
                             ⍝ then pass m as ⍺ and M as ⍵ to the following:
2⊃{⍵[⍒⍴¨⍵]} ⍝ Get the second-longest of:
 ⍺,⍵         ⍝ m,M
 A           ⍝ A
 ⍺           ⍝ M
 ⍵,⍺↓⍨≢A    ⍝ m,(the zeros of M)

```

# Answer
> 6 votes
# JavaScript (ES6),  ~~103 97~~  96 bytes

Expects `(A)(N)`.

```
a=>b=>Object.keys(g=x=>x&&g(g[x<0?a.length+x++:--x]=x),b.map(g)).sort((a,b)=>a-b).map(i=>~~a[i])

```

Try it online!

### How?

When it's called with \\$x\>0\\$, the helper function \\$g\\$ creates a key in its own underlying object for each value in the range:

$$\[x - 1, x - 2, ..., 0\]$$

When it's called with \\$x\<0\\$, it does the same thing with the range:

$$\[L + x, L + x + 1, ..., L - 1\]$$

where \\$L\\$ is the length of the input array \\$a\\$.

When it's called with \\$x=0\\$, it does nothing.

```
g = x =>               // x = input
  x &&                 // stop the recursion if x = 0
  g(                   // otherwise, do a recursive call:
    g[                 //   create a new key in g:
      x < 0 ?          //     if x is negative:
        a.length + x++ //       use a.length + x and post-increment x
      :                //     else:
        --x            //       use x, pre-decremented
    ] = x              //   the value associated to this key doesn't matter,
                       //   so we just use the argument for the next call
  )                    // end of recursive call

```

We sort all keys created by invoking \\$g(x),x\in b\\$ in ascending order and map the resulting indices to the values of \\$a\\$, forcing \\$0\\$'s when they are out of range.

```
a => b =>
  Object.keys(
    g = …,
    b.map(g)
  )
  .sort((a, b) => a - b)
  .map(i => ~~a[i])

```

# Answer
> 5 votes
# Python 3, ~~113~~ 103 bytes

```
def f(A,N):k=len(A);N+=0,;return[+(-1<i<k)and A[i]for i in sorted({*range(max(N)),*range(k+min(N),k)})]

```

Try it online!

Bit naive of an approach, but it works pretty well.

*-10 bytes thanks to @ovs*

### Explanation

We generate the sets of all indices of `m` and `M`, 0-indexed relative to the start of `A`. A simple union of these two sets combines the two masks.

```
def f(A,N):
    k=len(A);
    N+=0,; # Append 0 to ensure that the min/max functions never error
    [
        +(-1<i<len(A))and A[i] # try to get the i-th element of A
        for i in sorted({  # sort the indices to appear in proper order
            # generate the indices
            # 0-indexed starting at the first element of A
            *range(max(N)), # the set of all indices of M¸union:
            *range(k+min(N),k) # the set of all indices of m
        })
    ]

```

# Answer
> 3 votes
# Charcoal, 34 bytes

```
⊞η⁰Ｅ⁻±⌊ηＬθ0ＩΦθ∨‹κ⌈η›⁻⊕κＬθ⌊ηＥ⁻⌈ηＬθ0

```

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

```
⊞η⁰

```

Much like the other answers, a `0` is pushed to the take list, so that the maximum is at least `0` and the minimum is at most `0`.

```
Ｅ⁻±⌊ηＬθ0

```

Print `0`s for each element taken before the first.

```
ＩΦθ∨‹κ⌈η›⁻⊕κＬθ⌊η

```

Print those elements which fall in either the positive or negative range.

```
Ｅ⁻⌈ηＬθ0

```

Print `0`s for each element taken after the last.

# Answer
> 2 votes
# 05AB1E, ~~28~~ 26 bytes

```
εÝ¨yd≠iIg+<]˜êεIg‹yd*iyèë¾

```

Inputs in the order \\$N,A\\$.

Try it online or verify all test cases.

**Explanation:**

```
ε              # Map each value `y` in the (implicit) input-list `N` to:
 Ý             #  Push a list in the range [0,`y`]
  ¨            #  Remove the last value to make the range [0,`y`)
   yd≠i        #  If `y` is negative:
       Ig+     #   Add the input-length of `A` to each value
          <    #   And decrease each value by 1
]              # Close the if-statement and map
 ˜             # Flatten the list of indices
  ê            # Sort and uniquify these indices
   ε           # Map each index `y` to:
    Ig‹        #  Check if `y` is smaller than the input-length of `A`
       yd      #  Check if `y` is non-negative (>= 0)
         *i    #  If both are truthy:
           yè  #   Index `y` into the (implicit) input-list `A`
          ë    #  Else:
           ¾   #   Push a 0 instead
               # (after which the resulting list is output implicitly)

```

# Answer
> 2 votes
# Clojure, 90 bytes

```
#(for[j(sort(set(for[i %2 x(range(Math/abs i))](if(< i 0)(+(count %)i x)x))))](get % j 0))

```

Try it online!

Takes input in the order: data, indices

### Ungolfed

```
#(for [j
  (->
    ; for each i in indices generate a range from 0 to abs(i)
    (for [i %2 x (range (Math/abs i))]
      ; for negative indices add the offset = length(data) + i
      (if (< i 0) (+ (count %) i x) x))
    set ; keep unique values
    sort)] ; sort in ascending order
  ; for each j, get the jth item in data, or 0 if out of bounds
  (get % j 0))

```

---
Tags: code-golf, array, apl
---


# Question
Title: Is a statement of propositional logic always true?
The challenge is to golf a program that checks if a statement of propositional calculus/logic is a logical tautology (i.e. it is true for all possible values of the variables).

## Input

Input formulas will use `P`, `P'`, `P''` ect. as variables. They can either be true or false.

`(P and P')` means both `P` and `P'` are true.

`(P or P')` means at least one of `P` and `P'` is true.

`(P implies P')` means that if `P` is true, than `P'` must be true.

`(not P)` means that P is false.

These forms can be nested.

Example input: `(P implies ((P' or P'') and P'''))`

## Output

Output will be a truthy value if the input is a tautology, and a falsy value if it is not. (i.e True/False 1/0)

## Test Cases

`P`: False

`(P implies P)`: True

`((P implies P') implies ((P' implies P'') implies (P implies P'')))`: True

`(P implies (P or P'))`: True

`(P implies (P and P'))`: False

`(P or (not P))`: True

`and`, `or`, `not`, and `implies` are the ONLY operators.

This is . Shortest program in bytes wins.

## Clarification

The type of logic used here is Classical logic.

# Answer
> 8 votes
# Retina 0.8.2, ~~136~~ ~~124~~ 121 bytes

```
{T`()`<>
.*P.*
<$& ¶ $&>
(?=(P'*))(?=.*\1[^P']*(¶|$))\1
$.2
¶
a
<not 1>|<0 or 0>|<1 [ai]\w* 0>|<0 a\w* .>|(<[^P<>]*>)
$#1

```

Try it online! Link includes test cases. Explanation: Works by considering each variable in turn, replacing the string `f(p)` with the string `<f(1) and f(0)>` for each variable `p`. The resulting string is then evaluated according to Boolean arithmetic.

```
{`

```

Repeat the entire program until the buffer stops changing.

```
T`()`<>

```

Change the `()`s to something that doesn't need to be quoted.

```
.*P.*
<$& ¶ $&>

```

If the line still contains a variable, then duplicate it, and wrap the whole buffer in `<>`, however the two copies are still separated by a newline for now.

```
(?=(P'*))(?=.*\1[^P']*(¶|$))\1
$.2

```

Replace all copies of the last variable in the line with `1` or `0` depending on whether this is the original or duplicate line.

```
¶
a

```

Replace the newline with an `a` so that the two lines are joined together by an `< and >` operation.

```
<not 1>|<0 or 0>|<1 [ai]\w* 0>|<0 a\w* .>|(<[^P<>]*>)
$#1

```

Simplify any expressions that only contain constants. The expressions `<not 1>`, `<0 or 0>`, `<1 implies 0>`, `<1 and 0>`, `<0 and 0>`, `<0 and 1>` and `<0 and P>` (edge case) all evaluate to `0`, while any other expression that contains no sub-expressions or variables evaluates to `1`. (The original version of the code was buggy in this respect and needed a byte to fix it which I have included in the revised byte count in the header.)

# Answer
> 5 votes
# Python 3, 128 bytes

```
lambda s:eval("all("+s.replace("implies","<=").replace(*"'_")+"".join(f" for P{'_'*i} in[0,1]"for i in range(s.count("P")))+")")

```

Try it online!

The operator names in the task definition are the same as in Python (except `implies`, which is replaceable by `<=`), but there is an extra annoyance due to the necessity to replace apostrophes with something else.

To enumerate all possible values of variables, we construct a multi-level list comprehension of the form `<given expression> for P in[0,1] for P_ in[0,1]...` and evaluate whether all values are `True`.

I haven't found a short way to determine the number of distinct variables (= the number of levels), so I'm just counting all instances of `P` (which is more than necessary, and thus does the job). In principle, we could even shorten this check to `len(s)`, but this would lead to timeouts for longer expressions...

# Answer
> 3 votes
# JavaScript (ES6),  ~~129 ... 122~~  115 bytes

*Saved 1 byte thanks to @Neil*

Returns **0** or **1**.

```
f=(s,n)=>eval(s.replace(m=/\w+'*/g,s=>(m|=l=s.length,{a:"&",i:"<=",n:"!",o:"|"})[s[0]]||n>>l-1&1))?n>>m||f(s,-~n):0

```

Try it online!

### How?

We use `/\w+'*/g` to match all variables and operator names.

The operators `and`, `not` and `or` can be easily translated to `&`, `!` and `|` respectively.

Translating `implies` is a little trickier. We know that \\$A \Rightarrow B\\$ is equivalent to \\$\neg A \lor B\\$. But inserting a leading `!` would be quite difficult. Fortunately, this can also be expressed as \\$(A \operatorname{xor} 1)\lor B\\$. Given the precedence of JS operators, no parentheses are needed. So, `implies`  ~~is~~  could be translated to `^1|`.

**Edit**: Better yet, as noticed by @Neil, `implies` can also be translated to `<=`, which is 1 byte shorter.

Variables are replaced by either \\$0\\$ or \\$1\\$ depending on their size and the current value of the counter \\$n\\$.

Once everything has been replaced in the original expression, we test whether it `eval()`uates to \\$1\\$.

We keep track in \\$m\\$ of all lengths of the matched strings OR'ed together. This value is greater than or equal to the length of the longest string and *a fortiori* of the longest variable name. We use it to make sure that all possible combinations are tried at least once.

### Commented

```
f = (s, n) =>             // s = input string, n = counter
  eval(                   // evaluate as JS code:
    s.replace(            //   replace in s:
      m = /\w+'*/g,       //     all operator and variable names
      s =>                //     s = matched string
        (                 //
          m |=            //     do a bitwise OR between m and ...
            l = s.length, //       ... the length l of the matched string
          {               //     lookup object:
            a: "&",       //       "and"     -> "&"
            i: "<=",      //       "implies" -> "<="
            n: "!",       //       "not"     -> "!"
            o: "|"        //       "or"      -> "|"
          }               //
        )[s[0]] ||        //     translate the operator name according to
                          //     its first letter
        n >> l - 1 & 1    //     or replace the variable name with 0 or 1
    )                     //   end of replace()
  ) ?                     // end of eval(); if truthy:
    n >> m ||             //   stop if n is equal to 2 ** m (success)
    f(s, -~n)             //   otherwise, do a recursive call with n + 1
  :                       // else:
    0                     //   failure: return 0

```

# Answer
> 2 votes
# 05AB1E (legacy), 45 bytes

```
„€Ÿ(ì'''_:'Ø¢„<=:D'P¢ƒ1Ý'_N×“ €‡ Pÿ€†ÿ“}')J.Eb

```

Port of *@KirillL.*'s Python answer, so make sure to upvote him!

Outputs `1`/`0` respectively. If outputting `True`/`False` is allowed (even though these are both falsey in 05AB1E), the trailing `b` could be omitted.

Uses the legacy version of 05AB1E, where list `[0,1]` will be input as string with `ÿ`, whereas this would result in an error in the new version of 05AB1E.

Try it online or verify all test cases.

**Explanation:**

```
„€Ÿ(              # Push dictionary string "all("
    ì             # Prepend it in front of the (implicit) input-string
'' '_:           '# Replace all "'" with "_"
'Ø¢ „<=:         '# Replace dictionary string "implies" with "<="
D                 # Duplicate the string
 'P¢             '# Pop and count the amount of "P" in this string
    ƒ             # Loop `N` in the range [0, count]:
     1Ý           #  Push list [0,1]
     '_N×        '#  Push a string consisting of `N` amount of "_"
     “ €‡ Pÿ€†ÿ“  #  Push dictionary string " for Pÿ inÿ",
                  #  where the first `ÿ` is automatically replaced with the "_"-string
                  #  and the second the stringified "[0,1]" list
    }')          '# After the loop: push a ")"
J                 # Join all strings on the stack together
 .E               # Execute it as Python code
   b              # Then convert the "True"/"False" to 1/0 with the binary builtin
                  # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `„€Ÿ(` is `"all("`; `'Ø¢` is `"implies"`; and `“ €‡ Pÿ€†ÿ“` is `" for Pÿ inÿ"`.

# Answer
> 1 votes
# SageMath, ~~140~~ ~~134~~ 132 bytes

```
lambda p:propcalc.formula(r(*"'0",r("implies","->",r("or","|",r("and","&",r("not","~",p)))))).is_tautology()
from re import sub as r

```

Try it online!

# Answer
> 1 votes
# , ~~114~~102 bytes

```
[:*/([:;e.&' ()'({.;(<./@i.~&'rapt'{ ::''+`*`<:,'1-';'&{',~&":1-~#)@}.);.1]),/&.":"#.2#:@i.@^1#.e.&'P'

```

Try it online!

### How it works

```
2|:@#:@i.@^1#.e.&'P'

```

Count the P's in the string, 2^y, range, and base 2 it. This is a matrix with all boolean combinations for P variables. Now transforming the string to a J expression:

```
e.&' ()'

```

Bit mask if  `()` is at that position.

```
(…);.1]

```

Split the string based on the bit masks first item (which will be 1 expect in the single `P` case.) The groups start whenever the bit mask is 1, i.e. we either have the single groups ,`(`,`)` or a group that starts with that and also has a word like `(P'''`

```
{.;(…)@}.

```

Take the first character of the group unmodified, and for the rest apply:

```
'&{',~&":1-~#

```

Length - 1 as string prepended with `&{`, e.g. `3&{` for `P'''`.

```
+`*`<:,'1-';

```

The operators: or, and, implies, not. Now we have a list of things we have to pick from.

```
<./@i.~&'rapt'{ ::''

```

Search for any of `rapt` (o*r*, *a*nd, im*p*licit, no*t*) with the implicit `P` at the 5th place), reduce the word to that index, and take from the list (with an empty string if the group was only one character long.) We now have a list of valid J expressions like `(0&{ <: (2&{ + 1&{))`.

```
,/&.":"1

```

With the function on the left side and the booleans on the right side: Convert from numbers to strings with `":` (this will only change the booleans), append them to the function, and with `&.` the inverse of `":` will be called afterwards, so `(0&{ <: (2&{ + 1&{)) 0 1` will then be called and converted to the integer 1.

```
[:*/

```

Multiply-reduce the results.

# Answer
> 1 votes
# , ~~230~~ ~~197~~ 191 bytes

```
f=function(s,`[`=gsub)`if`(grepl("P",s<-sapply(0:1,`[`,pa="Q","and"["&","or"["|","not"["!","implies"["<=","P([^'])|P$"["Q\\1",s]]]]])),all(sapply("P'"["P",s],f)),all(sapply(parse(t=s),eval)))

```

Try it online!

*Edits: -39 bytes in exchange for quite a lot of warnings*

This was a lot of fun, but I must confess that I needed to look at the other answers for inspiration about how to handle 'implies'...

Works by recursively substituting each `P` (without any apostrophes) for `1` and `0`, then reducing the number of apostrophes after all the remaining `P`s and calling itself, until there are no more `P`s left, at which point it evaluates each expression.

My pattern matching & substitution is rather clunky, so I suspect that this could still be reduced quite a lot.

Commented version:

```
is_tautology=f=function(string) {
    string=                         # exchange in string:
    gsub("and","&",                 # and -> &
    gsub("or","|",                  # or -> |
    gsub("not","!",                 # not -> !
    gsub("implies","<=",            # implies -> <=
    gsub("P([^'])","Q\\1",
    gsub("P$","Q",                  # P (but not P') -> Q
    string))))))
                                    # now exchange Q for 1 or for 0:
    string=sapply(0:1,gsub,pattern="Q",string)
    if(!any(grepl("P",string))){    # if there are no more P's left:
                                    # return true if expression evaluates true
                                    # in both cases (Q->1 and Q->2)
        return(eval(parse(text=string[1]))&&eval(parse(text=string[2])))
    } else {                        # otherwise (there are still some P's):
        string=g("P'","P",string)   # remove one apostrophe from each P'
                                    # and recursively call self
                                    # with both cases (Q->1 and Q->2)
        return(f(string[1])&&f(string[2]))
    }
}

```

# Answer
> 0 votes
# Wolfram Language (Mathematica), 10 bytes

```
TautologyQ

```

Yep, there's a builtin.... Now, the OP will have to decide if the input format is acceptable (I feel that it is well within the spirit of this site's guidelines).

In terms of the variables themselves, we need to use strings of letters in place of `P`, `P'`, `P''`, and so on: we can use `P`, `Pp`, `Ppp`, and so on (as has been done in the TIO link), or `a`, `b`, `c`, `foo`, `bar`, or whatever. (Strangely, `TautologyQ` seems to be ok with a single variable containing primes, but two different such variables seems to break it.)

Logical input can be taken in two different formats. We can preserve the infix notation in the examples, such as:

```
TautologyQ[(P \[Implies] (P \[And] Pp))]

```

Or we can use prefix notation, such as:

```
TautologyQ[Implies[P, And[P, Pp]]]

```

(If the input format is completely inflexible, then one can add some processing commands like `StringReplace` followed by `ToExpression`.)

Try it online!

---
Tags: code-golf, math, decision-problem, logic
---


# Question
Title: Shortest Python 3 for sum of arithmetic progression
**Input**: from STDIN number of vertices in Graph \\$2 \leq N \leq 100\\$.

**Rules**: \[Code size\] = max (\[code length without spaces, tabs and newlines\], \[total code length divided by 4\])

**Math formulation**: In the graph of N vertices, between each pair of vertices can be 3 road states:

* there is no road
* there is a road from A to B
* there is a road from B to A

**Find the number of different graphs on given vertices.**

We can apply next formula (number of different road states in pow of pairs number): $$\huge3 ^ {\frac{n(n - 1)}{2}}$$.

# My Python 3 37 bytes solution here:

```
n = int(input())
print(3 ** ((n ** 2 - n) // 2))

```

I know that exists **34 bytes** solution. Then I started to think about 1 liner, and find next formula for sum of arithmetic progression, which use N only once: $$\frac{(2n - 1) ^ 2}{8} - \frac18$$

Unfortunately the code only increased:

```
x = 2 * int(input()) - 1
print(3 ** ((x ** 2 - 1) // 8))

```

# Answer
# Python 3, 34 bytes (not counting the newline)

Uses the conventional formula for the sum of the arithmetic progression (\\$\frac{n(n-1)}2\\$) and the trick that `n-1` = `~-n` (but with higher operator precedence). This way, one pair of parentheses can be omitted.

```
n=int(input())
print(3**(n*~-n//2))

```

Try it online!
> 4 votes

# Answer
# Python 3, 34 bytes

```
print(3**sum(range(int(input()))))

```

**Try it online!**

In Python 2 this is just `print 3**sum(range(input()))` for 28.
> 12 votes

---
Tags: tips, python
---


title: Smple way to get min & max

text:
# Question
Title: Smple way to get min & max
You will take a set of input numbers, and output the minimum and maximum of the set. You can either write two programs, with 1 program doing each function, or one combined program.

Here's an example in Perl, 50 and 42 bytes (92 total):

Max:

```
sub mx {return ( reverse sort {$a <=> $b} @_ )[0]}

```

Min:

```
sub mn {return ( sort {$a <=> $b} @_ )[0]}

```

And a single program, 96:

```
sub mxmn {return ( reverse sort {$a <=> $b} @_ )[0] if shift; return ( sort {$a <=> $b} @_ )[0]}

```

Here's some more test cases.

## Leaderboard

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

```
/* Configuration */

var QUESTION_ID = 4310; // 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 = 48934; // 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
## Perl, 28 char

This sub provides an array that contains the min in the first member and the max in the second member:

```
sub a{@_=sort@_;(shift,pop)}

```

## Perl, 34 char (27 inside the sub)

According to comments, in fact the above doesn't work for array length less than 2, here a new attempt that works even for zero length array and array that contains only numerics:

```
sub a{@_&&(sort{$a<=>$b}@_)[0,-1]}

```
> 0 votes

# Answer
Perl does have `min` and `max` subs.

```
use List::Util qw( min max );
my $min = min @values;
my $max = max @values;

```

A common module has a `minmax` function which finds both at once faster than they can be found individually (which is far more important than compactness of code).

```
use List::MoreUtils qw( minmax );
my ($min, $max) = minmax @values;

```
> 1 votes

# Answer
If it doesn't have to be Perl and you just want the simplicity of Scheme instead of just shaving off characters (I don't care about long variable names (symbols in Scheme)), here's my Scheme for this (pun intended):

Of course we could cheat and use the fonctions (min a b c d ...) and (max a b c ...).

Don't mind the long variable names, they were chosen to be descriptive:

```
(define (min . args) (extremum < args))
(define (max . args) (extremum > args))

(define-syntax extremum
  (syntax-rules ()
    [(_ op . args)
     (if (null? args)
         (error "Read The Fucking Code!")
         (reduce (lambda (a b) (if (op a b) a b))
           (car rest) (cdr rest)))]
    [else (error "Read The Fucking Code!")]))

```

But if you want less code (fold is sort of like reduce):

```
(define (min . args) (e < args)) (define (max . args) (e > args))
(define-syntax e
  (syntax-rules ()
    [(_ o . r) (fold (lambda (a b) (if (o a b) a b)) (car r) (cdr r))]))

```
> 1 votes

# Answer
If all numbers are non-negative, this works:

```
sub max{\@s[@_];$#s}

```
> 1 votes

# Answer
# Japt `-g`, 1 byte Min

```
n

```

Try it online!

---

# Japt `-g`, 2 bytes Max

```
n<

```

Try it online!

---

# Total: 3 bytes
> 1 votes

# Answer
Both programs pretty much just evaluate the input & sort it. Min takes the first item of the sorted list, and Max takes the last item of the sorted list.

# GolfScript, 4 bytes Min

```
~$0=

```

Try it online!

# GolfScript, 5 bytes Max

```
~$-1=

```

Try it online!

## Total: 9 bytes
> 1 votes

# Answer
I don't think Perl is very golfy for such a problem.

Here are two alternatives for *numerical lists only*:

---

**20 chars (inside sub)**

```
sub min{(sort{$a<=>$b}@_)[0]}
sub max{(sort{$b<=>$a}@_)[0]}

```

---

**30 chars (inside sub)**

```
sub min{$r=pop;$r=$_<$r?$_:$r for@_;$r}
sub max{$r=pop;$r=$_>$r?$_:$r for@_;$r}

```
> 0 votes

# Answer
# Io, 28 + 28 = 56

I found the magical pure-arithmetic max/min functions! (You guys definitely have a better formula than be, so feel free to mention a better one!)

# Io, 28 bytes

The max function;

```
method(x,y,(x+y+(x-y)abs)/2)

```

Try it online!

# Io, 28 bytes

Min function

```
method(x,y,(x+y-(x-y)abs)/2)

```

Try it online!

## Explanation for both programs

In order to find a purely-arithmetic max-min function, I started to think of averages. Let's take 3 and 4 as examples.

```
(3+4)/2 = 3.5

```

We can see that the distance towards both sides are equal:

```
3 - 3.5 = -0.5
4 - 3.5 = 0.5

```

We do the difference and take the absolute value, to get the distance that we need to add / subtract towards the average. `0.5` in this case.

Then, we find the average again. If we're finding the max, we add it by the distance, otherwise we subtract the value by the distance:

```
3.5 + 0.5 = 4
3.5 - 0.5 = 3

```

Our current expression is:

```
x + y   | x - y     |
----- ± | ----- - x |
  2     |   2       |

```

Actually, the rightmost x can also be y, but we chose x for the simplicity of simplification.

x + y   | x - y   2x  |
----- ± | ----- - --- |
  2     |   2      2  |

=

x + y   | x - y - 2x |
----- ± | ---------- |
  2     |     2      |

=

x + y   | x - y |
----- ± ---------
  2         2

And then, the formula becomes the current formula:

x + y ± | x - y |
-----------------
       2
```

> 0 votes

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


# Question
Title: “Hello, world!” with n distinct characters
Write a series of programs in the *same language* that print “Hello, world!” using n distinct source characters, where n is in \[1..10\] inclusive (“distinct” meaning that duplicate characters are ignored from character count). The winner is the solution with the most programs, each with distinct n. I suggest making one solution per language, which is treated like a wiki.

Further rules:

* *Case-sensitive* ('H' and 'h' are distinct characters)
* In *case-insensitive languages*, all non-string-literal characters are assumed to be *uppercase*.
* EDIT: No characters ignored by the compiler (comments)
* Output must be *exactly* “Hello, world!” (without quotes) - no variations in punctuation or case, and no newline.
* “Output” can mean either *value of the expression* or *output to stdout*.
* Esoteric programming languages are very much allowed.
* EDIT: The language must already exist (as of this question being asked).
* If anyone gets all of \[1..10\], they are the accepted winner.

Here's a polyglot example:

```
'Hello, world'

```

It scores 11 (and thus is not part of a solution) because it includes distinct characters:

```
'Helo, wrd!

```

# Answer
# DC: 2, 3, 4, 5, 6, 7, 8, 9 and 10 distinct characters

Seeing as the value of an expression is accepted as valid, this should qualify for 2 distinct characters (newlines added for legibility):

```
1111111111111111111111111111111+
1111111111111111111111111111111+
1111111111111111111111111111111+
1111111111111111111111111111111+
1111111111111111111111111111111+
11111111111111111111111111111+1+
11111111111111111111111111111+1+
1111111111111111111111111111+11+
1111111111111111111111111111+11+
11111111111111111111111111+1111+
11111111111111111111111111+1111+
1111111111111111111111111+11111+
11111111111111111111111+1111111+
11111111111111111111111+1111111+
1111111111111111111111+11111111+
1111111111111111111111+11111111+
1111111111111111111111+11111111+
111111111111111111111+111111111+
111111111111111111111+111111111+
111111111111111111111+111111111+
11111111111111111111+1111111111+
11111111111111111111+1111111111+
11111111111111111111+1111111111+
11111111111111111111+1111111111+
11111111111111111111+1111111111+
11111111111111111111+1111111111+
1111111111111111111+11111111111+
1111111111111111111+11111111111+
1111111111111111111+11111111111+
11111111111111111+1111111111111+
11111111111111111+1111111111111+
11111111111111111+1111111111111+
11111111111111111+1111111111111+
11111111111111111+1111111111111+
11111111111111111+1111111111111+
1111111111111111+11111111111111+
1111111111111111+11111111111111+
1111111111111111+11111111111111+
1111111111111111+11111111111111+
1111111111111111+11111111111111+
1111111111111111+1111111111111+
1111111111111111+1111111111111+
111111111111111111+11111111111+
1111111111111111111+1111111111+
1111111111111111111+1111111111+
1111111111111111111+1111111111+
11111111111111111111111+111111+
11111111111111111111111+111111+
11111111111111111111111+111111+
11111111111111111111111+111111+
11111111111111111111111+111111+
1111111111111111111111111+1111+
1111111111111111111111111+1111+
11111111111111111111111111+111+
111111111111111111111111111+11+
111111111111111111111111111+11+
111111111111111111111111111111+
11111111111111111111111111111+
11111111111111111111111111111+
11111111111111111111111111111+
11111111111111111111111111111+
1111111111111111111111111+
1111111111111111111111111+
11111111111111111111111+
1111111111111111111111+
1111111111111111111111+
1111111111111111111111+
111111111111111111111+
111111111111111111111+
111111111111111111111+
111111111111111111111+
111111111111111111+
111111111111111111+
111111111111111111+
1111111111111111+
1111111111111111+
111111111111111+
111111111111111+
111111111111111+
111111111111111+

```

The above is equal to `Hello, world!`, which can be seen by printing it with `P`. Note that it yields an error, as the first plus sign doesn't have two values on the stack to work with, but that doesn't change the value of the expression (as the error doesn't stop the execution). Replace the first plus sign with a space for the solution with 3 distinct characters.

4 distinct characters:

```
11dd1d+++ddd++dP+1dd+d+++dP1ddd++d+++ddPP111dddP11d+d+P1d+d+d+dd+d+P+PP1dd+++PPdd++ddd++1+PP

```

The rest:

```
2i1001000011001010110110001101100011011110010110000100000011101110110111101110010011011000110010000100001P
3i12000022021201222010112112220012020100011020212102102112221212020P
4i1020121112301230123302300200131312331302123012100201P
5i100103122130403124020421012422302411143103141P
6i2324032511514252112222553531220321252053P
7i2106632145606024426126104063251063041P

```
> 6 votes

# Answer
## Brainfuck, n=2, 3, 4, 5, 6, 7, 8

Case n=2: (new lines added for readability)

```
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.
+++++++++++++++++++++++++++++.
+++++++..
+++.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++.
+++.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++.

```

Case n=2 will be our basis.

For case n=3: we add `-` to the end of the n=2 source.

For case n=4: we add `->` to the end of the n=2 source.

For case n=5: we add `-><` to the end of the n=2 source.

For case n=6: we add `[><]` to the **beginning** of the n=2 source.

For case n=7: we add `[><-]` to the beginning of the n=2 source.

For case n=8: we add `[><,-]` to the beginning of the n=2 source.

Note: if you allow comments to be counted, add `a` anywhere for n=9 and add `ab` anywhere for n=10.
> 4 votes

# Answer
Emacs Lisp: One expression that returns "Hello, World!"

Exactly 10 distinct characters: \[s, t, r, i, n, g, ), (, \*, +\]

```
(string

(*(+(*)(    *))(+(*(
*(+(*)(*    ))(+(*)(
*))))(*(    +(*)(*)(
*)(*))(*(*(+(*)(*))(
+(*)(*))(+(*)(*)))))
))(+(*)(    *(+(+(*)
(*))(+(*    )(*))))(
*(+(*)(*    ))(+(*)(

*))(+(*)(*))(+(*)(*)
)(+(*)(*)))(*(*(+(*)
(*))(+(*
)(*))(+(*)(*)))(+(*)
(*))(+(*)(*))(+(*)(*
))))(+(*
(+(*)(*))(+(*)(*)))(
*(+(*)(*))(+(*)(*))(

+(+(*)(*
))))(*(+
(*)(*))(
+(*)(*))
(+(*)(*)
)(+(*)(*
))(+(*)(*)))(*(*(+(*
)(*))(+(*)(*))(+(*)(

*)))(+(*
)(*))(*(
+(*)(*))
(+(*)(*)
))))(+(*
(+(*)(*)
)(+(*)(*)))(*(+(*)(*
))(+(*)(*))(+(+(*)(*

))))(*(+(*)(*))(+(*)
(*))(+(*)(*))(+(*)(*
))(+(*)(    *)))(*(*
(+(*)(*)    )(+(*)(*
))(+(*)(    *)))(+(*
)(*))(*(    +(*)(*))
(+(*)(*)))))(+(+(*)(
*)(*))(*(+(*)(*))(+(

*)(*))  (+(*  )(*)))
(*(+(*  )(*)  )(+(*)
(*)))(  *(+(  *)(*))
(+(*)(  *))(  +(*)(*
))(+(*  )(*)  )(+(*)
(*)))(  *(*(  +(*)(*
))(+(*)(*))(+(*)(*))
)(+(*)(*))(*(+(*)(*)

)(+(*)(*)))))(+(*)(*
)(*(+(*)(*))(*(+(*)(
*))(+(*)    (*))))(*
(+(*)(*)    (*)(*))(
*(*(+(*)    (*))(+(*
)(*))(+(    *)(*))))
)(*)(*))(+(*(*(+(*)(
*))(+(*)(*)))(*(+(*)

(*))(+(*)(*))(+(*)(*
)))))(+(*(*(+(*)(*))
(+(*)(*)    )(+(*)(*
))))(+(*    )(*)(*))
(*(+(*)(*))(+(*)(*))
(+(*)(*)   ))(*(+(
*)(*))(+    (*)(*))
)(*(+(*)     (*))(+(

*)(*))(+
(*)(*))(
+(*)(*))
(+(*)(*)
))(*(*(+
(*)(*))(
+(*)(*))(+(*)(*)))(+
(*)(*))(*(+(*)(*))))

)(+(+(*)(*)(*))
(*(+(*)(*))(+(*)(*))
(+(*)(*)    ))(*(+(*
)(*))(+(    *)(*)))(
*(+(*)(*    ))(+(*)(
*))(+(*)    (*))(+(*
)(*))(+(*)(*)))(*(*(
+(*)(*))(+(*)(*

))(+(*)(
*)))(+(*
)(*))(*(
+(*)(*))
(+(*)(*)
))))(+(*

)(*)(*(+

(*)(*))(+(*)(*)))(*(+(*)(*))(+
(*)(*)))(*(+(*)(*))(+(*)(*))(+
(+(*)(*))))(*(+(*)(*))(+(*)(*)
)(+(*)(*))(+(*)(*))(+(*)(*)))(
*(*(+(*)(*))(+(*)(*))(+(*)(*))
)(+(*)(*))(*(+(*)(*))(+(*)(*))
)))(+(*(+(*)(*))(+(*)(*)))(*(+
(*)(*))(+(*)(*))(+(+(*)(*))))(
*(+(*)(*))(+(*)(*))(+(*)(*))(+
(*)(*))(+(*)(*)))(*(*(+(*)(*))
(+(*)(*))(+(*)(*)))(+(*)(*))(*
(+(*)(*))(+(*)(*)))))(+(+(*)(*
))(+(*)(*))(*(+(*)(*))(+(*)(*)
)(+(*)(*))(+(*)(*))(+(*)(*)))(
*(*(+(*)(*))(+(*)(*))(+(*)(*))
)(+(*)(*))(+(*)(*))(+(*)(*))))
(+(*)(*(*(+(*)(*))(+(*)(*)))(*
(+(*)(*))(+(*)(*))(+(*)(*))))))

```
> 4 votes

# Answer
## H9+

```
H
H0
H01
H012
H0123
H01234
H012345
H0123456
H01234567
H012345678

```
> 3 votes

# Answer
# Actually, 10 bytes

```
HIKLPTUVZ]

```

Try it online!

All prefixes of the program output `Hello, World!`:

```
H
HI
HIK
HIKL
HIKLP
HIKLPT
HIKLPTU
HIKLPTUV
HIKLPTUVZ
HIKLPTUVZ]

```
> 0 votes

# Answer
# *99*, 3 to 10 distinct chars

```
999 9 9
99 99999999 999 9
99
99 99999 9 999 9
99
99 99 999 999999
99
99
99 9999999 9999 999 9
99
99 99 9999999 9 999 9 999 9 999 9
99
99 99 999999 9 999999 9
99
9999
99 99999 999 999999 999 9
99
99 9999999 9999 9 999 9
99
99 99 999999 9
99
99 99 999999 999 9
99
99 99999 9999999 9
99

```

Try it online!

This is just standard *99*.

For the rest, replace the 999 with `9a99`, `9ab99`, etc.
> 0 votes

---
Tags: code-challenge, hello-world, multiple-holes
---


# Question
Title: Implement a UNIX file system and command line parser
## Description

Your task is to implement a simple UNIX command parser and file system. Your program will have to implement a file system that can be modified via commands.

The starting directory of your file system is an empty root directory `/`, with no subdirectories or files. Your program must be capable of handling the following commands:

## Commands

`cd <dirpath>` \- Change the current directory

* `<dirpath>` will be a list of directory names or "..", seperated by "/"
* e.g. `cd ../folder1/folder2` means to navigate up one directory level, then descend into `folder1`, then descend into `folder2`
* If the directory path is not valid, then the command will do nothing

`touch <filename>` \- Create a new file

* e.g. `touch me.txt` creates a file called `me.txt` in the current directory
* Filenames will only contain characters a-z and "."
    + Filenames will contain "." at least once
    + "." will never be the first or last character in a file name
* If a file already exists with the same name in the current directory, nothing happens

`mkdir <dirname>` \- Create a new directory

* e.g. `mkdir photos` creates a new `photos` directory in the current directory
* Directory names will only contan characters a-z
* If a directory already exists with the same name in the current directory, nothing happens

`rm [-r] <filename-or-dirname>` \- Remove a file or directory

* e.g. `rm hello.mp3` removes a file named `hello.mp3` in the current directory
* e.g. `rm -r documents` removes a folder named `documents` in the current directory, and all of its contents
* If `rm` tries to delete a directory without the `-r` flag, nothing will happen
    + However `rm` will delete a file even with the `-r` flag
* If the specified directory or file cannot be found, nothing happens

## Tree output

Your program will output the following tree-like representation of the current file system using spaces as indentation. For example:

```
/
  documents
    document.docx
  downloads
    zippedfile
      notavirus.exe
    coolgoats.mp3
    zippedfile.zip
  pictures
    myvacation.png

```
* ~~All directories names must end with a "/"~~ no longer necessary
* You may use any number of spaces to indent the tree (minimum 1)
* Directories must be listed before files in the same directory
* ~~Directories and files should be listed in lexographical alphabetical order~~
    + ~~The character "." lexographically comes before any alphabetical character~~
* You may output the contents of directories in any order you wish

## Challenge

Create a program that accepts a series of commands, and outputs a tree-like representation of the current file system.

**Input**

The first line of input will be an integer `N`. Following will be `N` lines, each containing a command as described above.

You may feel free to omit the number `N` from your input if it is not necessary

Slight variations are allowed (using commas to seperate commands, input as a list etc) as long as it's reasonable

**Output**

The contents of the current file system in a tree-like representation, as described above.

## Test Cases

Input 1: Simple example from earlier

```
15
mkdir documents
cd documents
touch document.docx
cd ..
mkdir downloads
cd downloads
touch coolgoats.mp3
touch zippedfile.zip
mkdir zippedfile
cd zippedfile
touch notavirus.exe
cd ../..
mkdir pictures
cd pictures
touch myvacation.png

```

Output 1:

```
/
  documents
    document.docx
  downloads
    zippedfile
      notavirus.exe
    coolgoats.mp3
    zippedfile.zip
  pictures
    myvacation.png

```

Input 2: Incorrect commands and edge cases

```
12
mkdir folder1
mkdir folder1
mkdir folder2
rm folder1
rm -r folder2
cd ..
cd ../folder1
cd folder1/folder2
touch file.txt
touch file.txt
touch file2.txt
rm -r file2.txt

```

Output 2:

```
/
  folder1
  file.txt

```

Input 3: ~~Alphabetical listing of directories and files~~ no longer necessary

```
8
mkdir b
mkdir c
mkdir a
touch c.txt
touch aa.txt
touch b.txt
touch a.txt
touch ab.txt

```

Output 3:

```
/
  a
  b
  c
  a.txt
  aa.txt
  ab.txt
  b.txt
  c.txt

```

Input 4: Partially correct cd should not be parsed (Suggested by @Arnauld)

```
4
mkdir folder1
cd folder1
cd ../folder2
touch file.txt

```

Output 4:

```
/
  folder1
    file.txt

```

Input 5: Partially correct cd should not be parsed (Suggested by @Abigail)

```
3
mkdir foo
cd bar/../foo
touch file.txt

```

Output 5:

```
/
  foo
  file.txt

```

Standard loopholes and I/O rules apply.

**This is , shortest code wins.**

**Edit:** output requirements have been relaxed a little bit

# Answer
> 7 votes
# Bash, ~~133~~ 86 bytes

```
(for i;{
$i
[[ $PWD =~ , ]]||cd ->~/e
})
tree --dirsfirst|sed '$d;s#[^0-Z.]# #g;1c /'

```

*-2 bytes thanks to @Dom Hastings (removing spaces around `||`)*

*-6 bytes thanks to @Dom Hastings (removing `eval`  before `$i` and using `#` as a sed delimiter)*

*-12 bytes thanks to @ilkkachu (combining the `sed`s).*

*-5 bytes thanks to @chepner (`=~`, `$PWD` and sed `c` command)*

Takes input where each argument is a command, e.g. `script 'mkdir A' 'cd A' 'touch B'`

Must be called from an empty directory with name containing `,`, such that this directory is the only directory containing `,` on the system.

The code itself is 85 bytes, +1 byte for specifying the directory name.

Try it online!.

**How it Works**

```
(         # start a subshell
for i;do  # for each argument
 $i          # run that command (rm [-r], touch, and mkdir
             # behave exactly as specified)
             # unfortunately cd can leave the directory, so...
 if [[ $PWD != *,* ]];then  # if we left the directory
                              # (i.e. the directory now no longer contains a comma)
    cd - > ~/e                     # cd to the directory from before the command
                                   # if this is successful, it outputs the new directory to stdout
                                   # so, redirect stdout to a file we can edit
                                   # piping to : didn't work without more bytes
                                   # It would be nice to not have to do this, but
                                   # redirecting the final `tree` output to a file included that file half the time
 fi
done
) # end subshell, returning to the initial directory (corresponding to '/')
tree --dirsfirst  # tree does most of the work for us
                  # outputs nearly the desired output, but it looks like
                  # .
                  # ├── A
                  # │   └── B.txt
                  # └── F
                  # 2 directories, 1 file

 | sed '
   $d;              # remove the last line ("2 directories, 1 file")
   s#[^0-Z.]# #g;   # replace all characters that are not digits, letters, or '.' with a space
   1c /             # replace the initial '.' with a '/'
 '

```

# Answer
> 9 votes
# Python 2, <sup>~~358~~ ... ~~280~~</sup> 277 bytes

thanks to randomdude999 for -3 bytes and a bugfix.

Input is a list of commands, where each command is represented by a 2-tuple as `(cmd, args)`. Test cases can be transformed using this Retina program.

```
K=T={}
for c,a in input():
 try:exec"T[a]=1|x=a<'.';if x or T[a]<2:del T[a[3*x:]]|T[a]=T.get(a,{'..':T})|E=T\nfor p in a.split('/'):E=E[p]\nT=E".split('|')[hash(c)%6]
 except:1
def p(t,i):
 for k in sorted(t,cmp,t.get,1):
	if'..'<k:print i+k;t[k]>1!=p(t[k],i+' ')
p({'/':K},'')

```

Try it online!

### Explanation

```
K=T={}

```

The file system is represented by a dictionary, where `K` points to the root directory, and `T` points to the current directory. Each sub-directory contains a reference to its parent directory under the key `'..'`, which allows for easy execution of `cd ..`. Files are represented by the integer `1`.

```
for c,a in input():
 try:exec"""<touch>|<rm>|<mkdir>|<cd>""".split('|')[hash(c)%4]
 except:1

```

This loop executes the commands, the right code to execute is selected using the hash of the command (see table below). The execution is wrapped in `try/except` to catch exceptions that occur in invalid `cd` and `rm` calls.

```
┌───────┬──────────────────────┬─────────────┐
│   cmd │            hash(cmd) │ hash(cmd)%6 │
├───────┼──────────────────────┼─────────────┤
│    cd │    12672076131114255 │           3 │
│ mkdir │ -4476162622565762260 │           2 │
│    rm │    14592087666131641 │           1 │
│ touch │  7353934562497703448 │           0 │
└───────┴──────────────────────┴─────────────┘

```

```
# touch
T[a]=1

```

Creates a new file called `a` in the current directory.

```
# rm
x=a<'.'
if x or T[a]<2:del T[a[3*x:]]

```

If `a` starts with `'-r'`, `x` is set to `True`. If `x` is True or we want to delete just a file (dicts are greater than integers in Python 2), the object can be deleted.

```
# mkdir
T[a]=T.get(a,{'..':T})

```

If the current directory already has an item called `a`, do nothing. Otherwise create a new subdirectory in the current directory with name `a` with a parent reference to the current directory.

```
# cd
E=T
for p in a.split('/'):E=E[p]
T=E

```

If p is equal to '..', `E['..']` points to the parent directory of `E`. Otherwise `E[p]` is the subdirectory `p` in `E`. The current directory is only updated if all steps have completed without error.

```
# Function that formats and prints the file system
# t - dictionary representing a part of the file system
# i - current indentation
def p(t,i):
 # Iterate over the keys sorted ...
 # ... on the values, where dicts (directories) ...
 # ... are larger than `1` (files) ...
 # ... and reverse
 for k in sorted(t,cmp,t.get,1):
  # if k is not 0 (a parent reference) ...
  # print the name of k ...
  # and, if k is a directory, call p recursively
  if k:print i+k;t[k]>1!=p(t[k],i+' ')

```

# Answer
> 7 votes
# JavaScript (ES6),  ~~268 265 254~~  248 bytes

Expects an array of strings. Returns a single linefeed-separated string.

```
a=>a.map(o=r=s=>([[c],s,e]=s.split` `,c>'m'?c>r?o[s]=1:o[e||+o[s]&&s]=0:c<'m'?o=s.split`/`.every(s=>o=o[s]-2?0:o[s],q=o)?o:q:o[s]=o[s]||{'..':o}))&(g=(o,i)=>[0,1].map(t=>{for(k in o)(v=o[k],t?v^1:v-2|k<S)||(S+=i+k,t||g(v,i+' '))}))(r,`
 `,S=`/`)||S

```

Try it online!

## How?

### Part 1: parse the commands and build the tree

The file tree is described by an object whose keys are the file names and whose values are:

* **0** for a deleted entry
* **1** for a file
* another object for a directory

Each directory (except the root) contains a default `..` entry pointing to the parent directory.

```
a.map(                   // main loop
  o =                    // o is the current object
  r =                    // r is the root object
  s => (                 // for each string s in a[]:
    [[c], s, e] =        //   split it into c = first character of the command,
      s.split` `,        //   s = first argument, e = second argument
    c > 'm' ?            //   if c is greater than 'm':
      c > r ?            //     if c is greater than 's':
        o[s] = 1         //       touch: create a file whose name is s
      :                  //     else:
        o[               //       rm:
          e ||           //         use e if it exists (meaning that -r was used)
          +o[s] && s     //         or use s if o[s] is a file
        ] = 0            //       mark this entry as deleted
    :                    //   else:
      c < 'm' ?          //     if c is less than 'm':
        o =              //       cd:
          s.split`/`     //         split the path
          .every(s =>    //         for each string s in the path:
            o =          //           update o:
              o[s] - 2 ? //             if o is a file or a deleted entry:
                0        //               abort
              :          //             else:
                o[s],    //               update o to o[s] (may be undefined)
            q = o        //           q = backup of o
          ) ?            //         if all entries were truthy:
            o            //           confirm the update
          :              //         else:
            q            //           restore o to q
      :                  //     else:
        o[s] = o[s] ||   //       mkdir: create a directory whose name is s,
               {'..': o} //       provided that it doesn't already exist
  )                      //
)                        // end of map()

```

### Part 2: build the output string

```
( g =                    // g is a recursive function taking:
  (o, i) =>              //   o = current object, i = indentation string
  [0, 1].map(t => {      //   for t = 0 and t = 1:
    for(k in o)          //     for each key k in o:
      (                  //
        v = o[k],        //       v = value
        t ?              //       if we are listing files:
          v ^ 1          //         abort if v is not equal to 1
        :                //       else (listing directories):
          v - 2 |        //         abort if v is a file or a deleted entry
          k < S          //         or the directory name is '..'
      ) || (             //       if the above test was falsy:
        S +=             //         append to S:
          i + k,         //           indentation + key
        t ||             //       if we are listing directories:
          g(v, i + ' ')  //         do a recursive call
      )                  //     implicit end of for()
  })                     //   end of map()
)(r, `\n `, S = `/`)     // initial call to g

```

---
Tags: code-golf, parsing
---


title: Optimal Games of Tic Tac Torus

text:
# Question
Title: Optimal Games of Tic Tac Torus
This challenge is about the game Tic Tac Toe, but it's played on a torus.

# How to play

To create the necessary game board, you start out with a regular Tic Tac Toe game board. First fold it into a cylinder by joining the left and the right edge. Then fold it into torus by joining the top and the bottom edge. Here's a simple visualization of such a game board with a few moves played (Sick Paint skills!).

The rules of Tic Tac Toe on a torus are the same as regular Tic Tac Toe. Each Player place alternating Xs and Os. The first one with 3 same symbols in a row, a column or a in a diagonal wins.

Since a torus is quite hard to visualize, we simply project the board back onto a paper. Now we can play the game as regular Tic Tac Toe. The only difference is, that you can also win with 3 same symbols in a broken diagonal. For instance Player 1 (X) wins the following board. You can see this easily by changing the view on the torus a little bit.

If your interested, you can play Tic Tac Toe on a Torus at Torus Games. There's a Windows, Mac and Android version.

# Optimal Games

In this challenge were interested in optimal games. An optimal game is a game, where both players play an optimal strategy. On a regular Tic Tac Toe board optimal games always end in a draw. Fascinatingly on a torus board always the first player wins. In fact a game on a torus board can never end in a draw (also if the players play not optimal).

The optimal strategy is really easy:

* If you can win by placing your symbol, do it.
* Otherwise if your opponent has two symbols in one row/column/điagonal, try to block him. Otherwise, do what you want.
* Otherwise do what you want.

Every optimal game consists of exactly 7 moves and these moves can be described in the following way:

1. Player 1 places a X anywhere on the board (9 choices)
2. Player 2 places an O anywhere on the board (8 choices)
3. Player 1 places a X anywhere on the board (7 choices)
4. Player 2's move may be forced (1 choice), if not, he places the O anywhere (6 choices)
5. Player 1's move is forced (1 choice)
6. Player 2 is caught in a fork (Player 1 can win in two different ways), so Player 2 has to block Player 1 in one way (2 choices)
7. Player 1 places the his last move and wins (1 choice)

There are 9\*8\*1\*6\*1\*2\*1 + 9\*8\*6\*1\*1\*2\*1 = 1728 different optimal games on our projected board. Here you can see one typical optimal game:

If we label each cell of the board with the digits `0-8`, we can describe this game by the digits `3518207`. First a X is places in the cell 3 (middle row, left column), than an O in cell 5 (middle row, right column), than a X in cell 1 (upper row, middle column), ...

Using this digit notation we automatically generated an order. Now we can sort all of the 1728 optimal games and we get the list:

```
Game 0000: 0123845
Game 0001: 0123854
Game 0002: 0124735
Game 0003: 0124753
Game 0004: 0125634
   ...
Game 0674: 3518207
   ...
Game 1000: 5167423
Game 1001: 5167432
Game 1002: 5168304
   ...
Game 1726: 8765034
Game 1727: 8765043

```

# Challenge

This list is part of your job. You will receive one number `k` between 0 and 1727 and you have to return the `k`th game in digit notation of that sorted list.

Write a function or a program, that receives the number `k` (integer) computes the correspondent game. You can read the input via STDIN, command-line argument, prompt or function argument and print the result (7 digits) in a readable format (e.g. `0123845` or `[0, 1, 2, 3, 8, 4, 5]`) or return it using an string (human readable format) or an integer (containing all digits in base 10), or in any array/list format.

The challenge type is code-golf. Therefore the shortest code wins.

# Answer
# JavaScript (ES6), 266 ~~308 317 334 341~~

A function returning a string. **Edit** Found an arithmetic solution for function M (at last!)

```
F=(n,x=[],M=(a,b,t=-a-b)=>(a-b)%3?a<3&b<3?3+t:a>5&b>5?21+t:12+t:9+t+a%3*3)=>
[for(a of z='012345678')for(b of z)for(c of z)for(d of z)
a-b&&c-a&&c-b&&(b-(y=M(a,c))?d==y:d-a&&d-b&&d-c)&&(
f=M(c,e=M(b,d)),g=M(a,e),g<f?[f,g]=[g,f]:0,r=a+b+c+d+e,x.push(r+f+g,r+g+f))]
&&x[n]

```

Very naive ~~, it can be shortened in many ways~~. It simply enumerates all the possible legal values and returns what find at place n. The M function returns the position in between two cells, that is the mandatory move to block an opposite player.

*More readable*

```
F=(n,x=[],
  M=(a,b,t=-a-b)=>(a-b)%3?
     a<3&b<3?
       3+t // first row
       :a>5&b>5?
          21+t // last row
          :12+t // middle row and diags
     :9+t+a%3*3 // columns
  )=>
  [for(a of z='012345678') // enumerate the first 4 moves
     for(b of z)
       for(c of z)
         for(d of z)
           a-b&&c-a&&c-b // avoid duplicates
           &&(b-(y=M(a,c))?d==y:d-a&&d-b&&d-c) // and check if d must block a-c or it's free
           &&(
             e=M(b,d), // forced to block b-d
             f=M(c,e),g=M(a,e),g<f?[f,g]=[g,f]:0, // f and g could be in the wrong order
             r=a+b+c+d+e, // start building a return string
             x.push(r+f+g,r+g+f) // store all values in x
  )]&&x[n] // return value at requested position

```
> 6 votes

# Answer
# APL (Dyalog Unicode), 73 bytes

```
⎕⊃z/⍨(∧/{⍵[4⍪3 2⍴5 6 1 3]∊⍨∘{3⊥3|-+/3 3⊤⍵}¨⍥↓⍵[1 3⍪3 2⍴0 4 2]},≠)¨z←,⍳7⍴9

```

Try it online!

A full program, and takes way too much time and memory to complete for any input. Also, the code includes some 18.0 features that aren't yet available on TIO. The TIO link includes a faster version using only features up to 17.1, so that the output can be checked.

### Winning or blocking position

Given two positions, extract their row and column numbers. For each dimension (row/column), if the numbers are the same, so is the result; otherwise, the result is the third number. In both cases, the result coordinates can be found with the following property:

```
n1  n2  res  -(n1+n2)%3
0   0   0    0
0   1   2    2
0   2   1    1
1   0   2    2
1   1   1    1
1   2   0    0
2   0   1    1
2   1   0    0
2   2   2    2

```

The resulting code is as simple as the following.

```
{3⊥3|-+/3 3⊤⍵}  ⍝ ⍵←two positions
        3 3⊤⍵   ⍝ Convert the numbers to base 3, each number → column
      +/        ⍝ Sum of each row
   3|-          ⍝ Negate and modulo 3
 3⊥             ⍝ Convert from base 3 to integer

```

### How the code works

```
z←,⍳7⍴9      ⍝ Create an array of 7-tuples of 0..8
z/⍨(...)¨z   ⍝ Filter the tuples by the following condition:
  ∧/{...},≠  ⍝ Check that Unique Mask (≠) is all ones AND it is an optimal TTT game:
    ⍵[...] ... ⍵[...]  ⍝ Extract certain indexes of the given tuple as matrices
    ⍥↓                 ⍝ Downrank both sides into four 2-tuples
    ∘{...}¨            ⍝ For each tuple of the right side,
      3⊥3|-+/3 3⊤⍵     ⍝ Compute the cell that completes a line in TTT
    ∊⍨                 ⍝ And check that the right side appears in
                       ⍝ the matching tuple on the left side
⎕⊃  ⍝ Take input n from stdin and pick the nth 7-tuple

-------------------
Left side idxs  ≡ ↓4⍪3 2⍴5 6 1 3 ≡ (4 4)(5 6)(1 3)(5 6)
Right side idxs ≡ ↓1 3⍪3 2⍴0 4 2 ≡ (1 3)(0 4)(2 0)(4 2)

Left  Right  Meaning
1 3   2 0    Turns 1 and 3 (by P1) are blocked by either Turn 2 or 4
4 4   1 3    Turns 2 and 4 (by P2) are blocked by Turn 5
5 6   0 4    Turn 6 blocks one of Turns 1,5 or Turns 3,5, and
             Turn 7 completes the other
5 6   4 2    ↑

```
> 4 votes

# Answer
# APL (Dyalog Extended), 72 bytes

```
g←{⍵,⍨1⌽@(∊∘⍺)¨⍵}
7↑⎕⊃∧⍋¨5 6g,¨(⊂⍳3)(∪⊢,⌽¨,⊖¨,⊢∘⌽¨)⍣≡1 3g⊂3 3⍴⊃4 6 8g⊂⍳9

```

Try it online!

Decided to post as a separate answer, because the approach is drastically different.

Inspired from orion's comment, this one generates all optimal games by transforming a single game board in various ways.

The 3x3 toroidal board is *very very* permissive on its transformations; the three-in-a-rows are preserved through reflection, rotation (e.g. cycling the top row to the bottom), and shear (e.g. cycling elements of each row 0, 1, 2 units to the right respectively). With this information, I could identify *four* seed boards that have distinct topology (using 0 to 6 to denote the seven moves made in sequence):

```
P2#4 not forced
0 1 2    0 1 2
3 6 5    3 5 6
x x 4    x x 4

P2#4 forced
0 3 2    0 3 2
1 6 5    1 5 6
x x 4    x x 4

```

Then I tried various combinations of the transformations to find a short one that generates all 1728 boards. And I noticed that even the seed boards can be generated from *one* board, by swapping the positions of 1-3 (decides whether the 4th move is forced) and 5-6 (swap a block and a win).

### How it works

```
⍝ Helper function
g←{⍵,⍨1⌽@(∊∘⍺)¨⍵}
1⌽@(∊∘⍺)¨⍵  ⍝ Cycle the positions of ⍺s in each of ⍵
⍵,⍨  ⍝ Prepend the above to ⍵

⍝ Main program
7↑⎕⊃∧⍋¨5 6g,¨(⊂⍳3)(∪⊢,⌽¨,⊖¨,⊢∘⌽¨)⍣≡1 3g⊂3 3⍴⊃4 6 8g⊂⍳9
3 3⍴⊃4 6 8g⊂⍳9  ⍝ Generate the seed board:
0 1 2
3 6 5
8 7 4
5 6g 1 3g  ⍝ Generate four seed boards from the above,
           ⍝ by swapping the numbers 1-3 and 5-6
(⊂⍳3)(...)⍣≡  ⍝ Repeat certain transformations until all are found:
  ⊢∘⌽¨  ⍝ Reverse the order of columns:
a b c   c b a
d e f → f e d
g h i   i h g
  ⊖¨,   ⍝ Join with vertical shear:
a b c   a e i
d e f → d h c
g h i   g b f
  ⌽¨,   ⍝ Join with horizontal shear:
a b c   a b c
d e f → e f d
g h i   i g h
  ∪⊢,   ⍝ Join with original and take unique results

⍋¨,¨  ⍝ Flatten each 3x3 matrix and extract where each number is
∧     ⍝ Ascending sort
⎕⊃    ⍝ Take input n and pick nth result
7↑    ⍝ Take first 7, since the last two are garbage

```
> 4 votes

# Answer
# Octave, 467 369 363 309 297 characters

**297:**

```
global t=0*(1:9)m=dec2bin([15;113;897;1170;1316;1608;2370;2216;2580])-48 a;
function g(s,p)global a t m;
if nnz(s)<8&&any((t==1)*m>2)a=[a;s];return;end;q=t==3-p;
(r=sort(~q.*(1:9)*m(:,find([3 1]*([q;t==p]*m)==6)')))||(r=find(~t));
for i=r t(i)=p;g([s i+47],3-p);t(i)=0;end;end;g('',1);f=@(n)a(n+1,:);

```

The only relevant change is that **we never check if the current player can win, only check the opponent's possibility to win the next turn**. As **the only turn the player 1 can win is turn 7**, this is the only place when the algorithm would produce game that is not optimal, but it's very easy to filter such a situation out. We simply verify each game generated if it's won by player 1 - if it was not, the move in turn 7 was incorrect, so we don't add this game to optimal games table.

(Exactly half the games generated by this rule are false *ie.* in the 7th turn the player 1 always has two possibilities to block player two, but only one will make him win instantly).

Use:

```
$ octave
octave:1>> source script.m
octave:2>> f(634)
ans = 3270148

```

The ungolfed code looks like:

```
 global t=0*(1:9);
 global m=dec2bin([15;113;897;1170;1316;1608;2370;2216;2580])-48;
 global allgames;
 allgames=[];

 function r=canbewon(by)
  global t m
  q=[t==by;t==(3-by)]*m;
  g=(find([3 1]*q==6))';
  r=sort((~(t==by).*(1:9)) * m(:,g));
 end

 function games_starting_with(s)
 global allgames t;
 if 7==numel(s) && any((t==1)*m==3) # it's 7th move and first player won
  allgames=[allgames;s];
  return;
 end;
 poss=(find(~t));                  # for now all free slots are possible
 player=1+mod(numel(s),2);
 moves = canbewon(3-player);
 if numel(moves) poss=moves; end;  # ... no, we must block the other player
 for i=poss
  t(i)=player;
  games_starting_with([s char(i+47)]);
  t(i)=0;
 end
end

games_starting_with('');
f=@(n)(allgames(n+1,:));

```
> 3 votes

---
Tags: code-golf, game, tic-tac-toe
---


title: This ain't it Chief

text:
# Question
Title: This ain't it Chief
This is mostly for the memes. I regret existing.

# Rules

* Your code has to output, by either printing or showing in stdout, the phrase `This ain't it Chief.` in that exact format.
* You can only use the characters from the phrase in either format of

+ UTF-8 (`Aa Cc Ee Ff Hh Ii Nn Tt Ss . '`)
    + or hex bytes (`41 61 20 43 63 20 45 65 20 46 66 20 48 68 20 49 69 20 4e 6e 20 54 74 20 53 73 20 2e 20 27`)
* No inputs are allowed via stdin or any form of user input.
* Use `JSFiddle`, `CodePen`, etc. to prove your code works (or a screenshot if needed?)

# Answer Formatting

```
 #Language - Code length in bytes
    some code
 #Comments, laughs, etc.

```

# Scoring

* This is code golf, so shortest code in bytes wins.

# Answer
> 2 votes
# CJam, 40 bytes

```
'T'h'i's' 'a'i'n'''t' 'i't' 'C'h'i'e'f'.

```

Try it online!

Explanation: 'T pushes a T to the stack, etc. CJam has an implicit output.

# Answer
> 2 votes
# Japt, 43 bytes

```
'.ifieiiihi'CiSitiiiSiti''iniiiaiSisiiihi'T

```

Try it

> Draco18s: As for the challenge itself, I don't think any language can work with that instruction set except by sheer coincidence

This is one such coincidence; Japt's `i` method prepends its argument to the string it's applied to.

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

A function returning the string, just for the lols.

```
'This ain''t it Chief'

```

Try it online!

> Draco18s: As for the challenge itself, I don't think any language can work with that instruction set except by sheer coincidence

This is one such coincidence; You just need to type `''` to escape a `'` character, instead of using `\'`.

# Answer
> 0 votes
# , 1.07e192 bytes

```
insert 1070535411808274876356555204541421987893453317986634005193363842599488570060956068723122679013084672793132737522449327487355527954547514152318677638703786440293483566302887576787267171423983556 A's here

```

Obligatory Lenguage (well this isn't Lenguage but you know what I mean) answer.

Try the brainfuck online!

---
Tags: code-golf, kolmogorov-complexity, restricted-source, alphabet
---


title: Generate Dennis Numbers

text:
# Question
Title: Generate Dennis Numbers
This challenge is a tribute to PPCG user Dennis for winning the robbers' part of The Programming Language Quiz.

Looking at Dennis' PPCG profile page we can see some pretty impressive stuff:

He currently has over sixty-eight *thousand* reputation, making him second in rep overall, surpassing third place by almost thirty thousand. He recently won our election for a new moderator and got a shiny new diamond next to his name. But I personally think the most interesting part about Dennis is his PPCG user ID number: 12012.

At first glance `12012` almost looks like a palindrome, a number that reads the same when reversed, but it's a little off. It can become the palindrome `21012` if we swap the positions of the first `1` and `2`, and it can become the palindrome `12021` if we swap the last `1` and `2`. Also, following the convention that leading zeroes in a number are not written, swapping the first `1` and the `0` results in `02112` or rather `2112` which is another palindrome.

Let's define a **Dennis number** as a positive integer that is not palindromic itself but can be made into a palindrome by swapping the positions of at least one pair of any two digits. The **order** of a Dennis number is the number of distinct pairs of digits that can be swapped to make a (not necessarily distinct) palindrome.

So the order of `12012` is 3 since 3 distinct pairs of its digits (`***12***012`, `120***12***`, `***1***2***0***12`) can be swapped around to produce palindromes. `12012` happens to be the smallest order 3 Dennis number.

`10` is the smallest Dennis number and has order 1 because switching around the `1` and `0` gives `01` a.k.a. `1` which is a palindrome.

The imaginary leading zeroes of a number don't count as switchable digits. For example, changing `8908` to `08908` and swapping the first two digits to get the palindrome `80908` is invalid. `8908` is not a Dennis number.

Non-Dennis numbers could be said to have order 0.

# Challenge

Write a program or function that takes in a positive integer N and prints or returns the Nth smallest Dennis number *along with its order* in some reasonable format such as `12012 3` or `(12012, 3)`.

For example, `12012` is the 774th Dennis number so if `774` is the input to your program, the output should be something like `12012 3`. (Curiously, 774 is another Dennis number.)

**The shortest code in bytes wins.**

Here is are the first 20 Dennis numbers and their orders for reference:

```
N       Dennis  Order
1       10      1
2       20      1
3       30      1
4       40      1
5       50      1
6       60      1
7       70      1
8       80      1
9       90      1
10      100     1
11      110     2
12      112     1
13      113     1
14      114     1
15      115     1
16      116     1
17      117     1
18      118     1
19      119     1
20      122     1

```

Here is the same list up to N = 1000.

# Answer
> 14 votes
# Pyth, 44 bytes

```
L/lf_ITs.e.e`sXXNkZYbN=N`b2,Je.f&!_I`ZyZQ0yJ

```

Try it online: Demonstration or Test Suite

A stupid little bug (?) in Pyth ruined a 41 byte solution.

### Explanation:

```
L/lf_ITs.e.e`sXXNkZYbN=N`b2
L                             define a function y(b), which returns:
                      =N`b       assign the string representation of b to N
        .e             N         map each (k=Index, b=Value) of N to:
          .e         N             map each (Y=Index, Z=Value) of N to:
              XXNkZbN                switch the kth and Yth value in N
            `s                       get rid of leading zeros
       s                         combine these lists
   f_IT                          filter for palindromes
  l                              length
 /                        2      and divide by 2

,Je.f&!_I`ZyZQ0yJ
   .f        Q0     find the first input() numbers Z >= 0, which satisfy
      !_I`Z            Z is not a palindrom
     &                 and
           yZ          y(Z) != 0
  e                 get the last number
 J                  and store in J
,J             yJ   print the pair [J, y(J)]

```

# Answer
> 44 votes
# CJam, 45 bytes

```
0{{)_s:C,2m*{~Ce\is_W%=},,2/:O!CCW%=|}g}ri*SO

```

Try it online!

### How it works

```
0          e# Push 0 (candidate).
{          e# Loop:
  {        e#   Loop:
    )_     e#     Increment the candidate and push a copy.
    s:C    e#     Cast to string and save in C.
    ,      e#     Get the length of C, i.e., the number of digits.
    2m*    e#     Push all pairs [i j] where 0 ≤ i,j < length(C).
    {      e#     Filter:
      ~    e#       Unwrap, pushing i and j on the stack.
      Ce\  e#       Swap the elements of C at those indices.
      is   e#       Cast to int, then to string, removing leading zeroes.
      _W%= e#       Copy, reverse and compare.
    },     e#     Keep the pairs for which = returned 1, i.e., palindromes.
    ,2/    e#     Count them and divide the count by 2 ([i j] ~ [j i]).
    :O     e#     Save the result (the order) in O.
    !      e#     Negate logically, so 0 -> 1.
    CCW%=  e#     Compare C with C reversed.
    |      e#     Compute the bitwise NOT of both Booleans.
           e#     This gives 0 iff O is 0 or C is a palindrome.
  }g       e#   Repeat the loop while the result is non-zero.
}ri*       e# Repeat the loop n times, where n is an integer read from STDIN.
           e# This leaves the last candidate (the n-th Dennis number) on the stack.
SO         e# Push a space and the order.

```

# Answer
> 7 votes
# Haskell, 174 bytes

```
import Data.List
p x=x==reverse x
x!y=sum[1|(a,b)<-zip x y,a/=b]==2
o n|x<-show n=sum[1|v<-nub$permutations x,x!v,p$snd$span(<'1')v,not$p x]
f=([(x,o x)|x<-[-10..],o x>0]!!)

```

`p` checks whether a list is a palindrome.

`x!y` is `True` iff the lists `x` and `y` (which should have the same length) differ in exactly two places. Specifically, if `x` is a permutation of `y`, `x!y` determines whether it is a "swap".

`o n` finds the Dennis-order of `n`. It filters for swaps among the permutations of `x = show n`, and then counts how many of those swaps are palindromes. The list comprehension that performs this count has an extra guard `not (p x)`, which means it will return `0` if `n` was a palindrome to begin with.

The `snd (span (<'1') v)` bit is just `dropWhile` but one byte shorter; it turns `"01221"` into `"1221"`.

`f` indexes from a list of `(i, o i)` where `o i > 0` (i.e. `i` is a Dennis number.) There would normally be an off-by-one error here, as `(!!)` counts from 0 but the problem counts from 1. I managed to remedy this by starting the search from `-10` (which turned out to be considered a Dennis number by my program!) thereby pushing all the numbers into the right spots.

`f 774` is `(12012,3)`.

# Answer
> 6 votes
## Rust, 390 bytes

```
fn d(mut i:u64)->(u64,i32){for n in 1..{let mut o=0;if n.to_string()==n.to_string().chars().rev().collect::<String>(){continue}let mut s=n.to_string().into_bytes();for a in 0..s.len(){for b in a+1..s.len(){s.swap(a,b);{let t=s.iter().skip_while(|&x|*x==48).collect::<Vec<&u8>>();if t.iter().cloned().rev().collect::<Vec<&u8>>()==t{o+=1}}s.swap(a,b);}}if o>0{i-=1;if i<1{return(n,o)}}}(0,0)}

```

The new Java? :/

Ungolfed and commented:

```
fn main() {
    let (num, order) = dennis_ungolfed(774);
    println!("{} {}", num, order);  //=> 12012 3
}

fn dennis_ungolfed(mut i: u64) -> (u64, i32) {
    for n in 1.. {
        let mut o = 0;  // the order of the Dennis number
        if n.to_string() == n.to_string().chars().rev().collect::<String>() {
            // already a palindrome
            continue
        }
        let mut s = n.to_string().into_bytes();  // so we can use swap()
        for a in 0..s.len() {  // iterate over every combination of (i, j)
            for b in a+1..s.len() {
                s.swap(a, b);
                // need to start a new block because we're borrowing s
                {
                    let t = s.iter().skip_while(|&x| *x == 48).collect::<Vec<&u8>>();
                    if t.iter().cloned().rev().collect::<Vec<&u8>>() == t { o += 1 }
                }
                s.swap(a, b);
            }
        }
        // is this a Dennis number (order at least 1)?
        if o > 0 {
            // if this is the i'th Dennis number, return
            i -= 1;
            if i == 0 { return (n, o) }
        }
    }
    (0, 0)  // grr this is necessary
}

```

# Answer
> 6 votes
# Python 2, 176

```
i=input()
n=9
c=lambda p:`p`[::-1]==`p`
while i:n+=1;x=`n`;R=range(len(x));r=[c(int(x[:s]+x[t]+x[s+1:t]+x[s]+x[t+1:]))for s in R for t in R[s+1:]];i-=any(r)^c(n)
print n,sum(r)

```

I can't imagine that my swapping code is particularly optimal, but this is the best I've been able to get. I also don't like how often I convert between string and integer...

For each number, it creates a list of a whether all of the swaps of two digits are palindromes. It decrements the counter when at least one of these values is true, and the original number is not a palindrome. Since `0+True` in python evaluates to `1` the sum of the final list works for the order of the Dennis number.

# Answer
> 5 votes
# Jelly, 33 bytes

```
ṚḌ=
=ċ0^2°;ḌÇ
DŒ!Qç@ÐfDL©Ṡ>Ñµ#Ṫ,®

```

Try it online!

### How it works

```
DŒ!Qç@ÐfDL©Ṡ>Ñµ#Ṫ,®  Main link. No arguments.

              µ      Combine the chain to the left into a link.
               #     Find; execute the chain with arguments k = 0, 1, 2, ...
                     until n values of k result in a truthy value, where n is an
                     integer read implicitly from STDIN. Return those n values.

D                      Decimal; convert k to the list of its digits in base 10.
 Œ!                    Generate all permutations of the digits.
   Q                   Unique; deduplicate the list of permutations.
      Ðf               Filter:
    ç@  D                Call the helper link on the second line with the
                         unpermuted digits (D) as left argument, and each
                         permutation as the right one.
                       Keep permutations for which ç returns a truthy value.
         L©            Compute the length (amount of kept permutations) and save
                       it in the register.
           Ṡ           Sign; yield 1 if the length is positive, and 0 otherwise.
            >Ṅ         Compare the sign with the result from the helper link on
                       the first line. This will return 1 if and only if the
                       length is positive and Ñ returns 0.
                Ṫ      Tail; extract the last value of k.
                 ,®    Pair it with the value in the register.

=ċ0^2°;ḌÇ              Helper link. Arguments: A, B (lists of digits)

=                      Compare the corresponding integers in A and B.
 ċ0                    Count the zeroes, i.e., the non-matching integers.
   ^2                  Bitwise XOR the amount with 2.
     °                 Convert to radians. This will yield 0 if exactly two
                       corresponding items of A and B are different ,and a
                       non-integral number otherwise.
      ;                Prepend the result to B.
       Ḍ               Convert the result from decimal to integer. Note that
                       leading zeroes in the argument won't alter the outcome.
        Ç              Call the helper link on the first line.

ṚḌ=                    Helper link. Argument: m (integer)

Ṛ                      Convert m to decimal and reverse the digits.
 Ḍ                     Convert back to integer.
  =                    Compare the result with m.

```

# Answer
> 3 votes
# APL, 87

```
2↓⎕{⍺(2⊃⍵+K⌊~A∧.=⌽A)X,K←+/{⍵∧.=⌽⍵}¨1↓∪,{⍕⍎Y⊣Y[⌽⍵]←⍵⊃¨⊂Y←A}¨∘.,⍨⍳⍴A←⍕X←1+3⊃⍵}⍣{=/2↑⍺}3⍴0

```

The body of the loop returns a vector of 4 numbers: 1) its left argument  read from input, 2) count of Dennis numbers so far, 3) current value of `X` — the loop counter, and 4) its order `K` computed as sum of palindromes within 1-swap permutations. It terminates when the first two elements become equal and last two are then returned as result.

# Answer
> 2 votes
# JavaScript (ES6), 229

As usual, JavaScript shines for its ineptitude for combinatorics (or, maybe it's *my* ineptitude...). Here I get all possibile swap positions finding all binary numbers of the given length and just 2 ones set.

Test running the snippet below in Firefox (as MSIE is far from EcmaScript 6 compliant and Chrome is still missing default parameters)

```
F=c=>(P=>{for(a=9;c;o&&--c)if(P(n=++a+'',o=0))for(i=1<<n.length;k=--i;[x,y,z]=q,u=n[x],v=n[y],!z&&u-v&&(m=[...n],m[x]=v,m[y]=u,P(+(m.join``))||++o))for(j=0,q=[];k&1?q.push(j):k;k>>=1)++j;})(x=>x-[...x+''].reverse().join``)||[a,o]

// TEST

function go(){ O.innerHTML=F(I.value)}

// Less Golfed
U=c=>{
  P=x=>x-[...x+''].reverse().join``; // return 0 if palindrome

  for(a = 9; // start at 9 to get the first that is known == 10
      c; // loop while counter > 0
      o && --c // decrement only if a Dennis number found
      )
  {
    o = 0; // reset order count
    ++a;
    if (P(a)) // if not palindrome
    {
      n = a+''; // convert a to string
      for(i = 1 << n.length; --i; )
      {
        j = 0;
        q = [];
        for(k = i; k; k >>= 1)
        {
          if (k & 1) q.push(j); // if bit set, add bit position to q
          ++j;
        }
        [x,y,z] = q; // position of first,second and third '1' (x,y must be present, z must be undefined)
        u = n[x], v = n[y]; // digits to swap (not valid if they are equal)
        if (!z && u - v) // fails if z>0 and if u==v or u or v are undefined
        {
          m=[...n]; // convert to array
          m[x] = v, m[y] = u; // swap digits
          m = +(m.join``); // from array to number (evenutally losing leading zeroes)
          if (!P(m)) // If palindrome ...
            ++o; // increase order count
        }
      }
    }
  }
  return [a,o];
}

//////
go()
```

```
<input id=I value=774><button onclick="go()">-></button> <span id=O></span>
```

# Answer
> 1 votes
# awk, 199

```
{for(;++i&&d<$0;d+=o>0)for(o=j=_;j++<l=length(i);)for(k=j;k++<l;o+=v!=i&&+r~s){split(t=i,c,v=s=r=_);c[j]+=c[k]-(c[k]=c[j]);for(e in c){r=r c[e];s=s||c[e]?c[e]s:s;v=t?v t%10:v;t=int(t/10)}}print--i,o}

```

## Structure

```
{
    for(;++i&&d<$0;d+=o>0)
        for(o=j=_;j++<l=length(i);)
            for(k=j;k++<l;o+=v!=i&&+r~s)
            {
                split(t=i,c,v=s=r=_);
                c[j]+=c[k]-(c[k]=c[j]);
                for(e in c)
                {
                    r=r c[e];
                    s=s||c[e]?c[e]s:s;
                    v=t?v t%10:v;
                    t=int(t/10)
                }
            }
    print--i,o
}

```

## Usage

Paste this to your console and replace the number after `echo`, if you want

```
echo 20 | awk '{for(;++i&&d<$0;d+=o>0)for(o=j=_;j++<l=length(i);)for(k=j;k++<l;o+=v!=i&&+r~s){split(t=i,c,v=s=r=_);c[j]+=c[k]-(c[k]=c[j]);for(e in c){r=r c[e];s=s||c[e]?c[e]s:s;v=t?v t%10:v;t=int(t/10)}}print--i,o}'

```

It gets slow at higher numbers ;)

## Ungolfed reusable version

```
{
    dennisFound=0

    for(i=0; dennisFound<$0; )
    {
        i++
        order=0

        for(j=0; j++<length(i); )
        {
            for(k=j; k++<length(i); )
            {
                split(i, digit, "")
                digit[j]+=digit[k]-(digit[k]=digit[j]) # swap digits

                tmp=i
                iRev=iFlip=iFlipRev=""

                for(e in digit)
                {
                    if(tmp>0)                        # assemble reversed i
                        iRev=iRev tmp%10
                    tmp = int( tmp/10 )

                    iFlip=iFlip digit[e]             # assemble flipped i

                    if(iFlipRev>0 || digit[e]>0)     # assemble reversed flipped i
                        iFlipRev=digit[e] iFlipRev   # without leading zeros
                }
                if(iRev!=i && 0+iFlip==iFlipRev) order++  # i is not a palindrome,
            }                                             # but flipped i is
        }
        if(order>0) dennisFound++
    }
    print i, order
}

```

# Answer
> 1 votes
# Ruby, 156

```
->i{s=?9
(o=0;(a=0...s.size).map{|x|a.map{|y|j=s+'';j[x],j[y]=j[y],j[x];x>y&&j[/[^0].*/]==$&.reverse&&o+=1}}
o<1||s==s.reverse||i-=1)while i>0&&s.next!;[s,o]}

```

Uses the Ruby feature where calling `"19".next!` returns `"20"` to avoid having to convert types back and forth; we just use a regex to ignore leading `0s`. Iterates over all pairs of string positions to check for palindromic switches. I originally wrote this a recursive function but it busts the stack.

Output for 774 is `["12012", 3]` (removing the quotation marks would cost 4 more bytes but I think the spec allows them).

# Answer
> 1 votes
# 05AB1E, 34 bytes

```
∞ʒÂÊ}ε©ā<2.Æε®DrèRyǝïÂQ}O‚}ʒθĀ}I<è

```

Try it online or output the first \\$n\\$ Dennis numbers.

**Explanation:**

```
∞            # Push an infinite positive list: [1,2,3,...]
 ʒ           # Filter it by:
  Â          #  Bifurcate the current number (short for Duplicate & Reverse Copy)
   Ê         #  Check that the reverse copy does NOT equal the number itself
 }ε          # After we've filtered out all palindromes: map over the remaining numbers:
   ©         #  Store it in variable `®` (without popping)
    ā        #  Push a list in the range [1, length] (without popping)
     <       #  Decrease each by 1 to make the range [0, length)
      2.Æ    #  Get all possible pairs of this list
    ε        #  Map each pair of indices to:
     ®D      #   Push the number from variable `®` twice
       r     #   Reverse the stack order from [indices,nr,nr] to [nr,nr,indices]
        è    #   Get the digits of the number at these indices
         R   #   Reverse this pair
          y  #   Push the indices we're mapping over again
           ǝ #   And insert the reversed digits back into the number at the indices
     ï       #   Cast it to an integer to remove leading 0s
      Â      #   Bifurcate it (short for Duplicate & Reverse Copy)
       Q     #   Check that the reverse copy equals the number itself,
             #   resulting in 1 if its a palindrome, and 0 if not
    }O       #  After the inner map: sum all truthy values together
      ‚      #  And pair it with the number
 }ʒ          # After the outer map: filter again:
   θ         #  Where the last value of the pair (the calculated order)
    Ā        #  Is not 0
  }I         # After the filter: push the input-integer
    <        # Decrease it by 1 (because 05AB1E uses 0-based indexing)
     è       # And get the pair at that index in the infinite list
             # (after which it is output implicitly as result)

```

# Answer
> 0 votes
# JavaScript (ES6), 151 bytes

```
f=(n,x)=>(g=a=>(a=[...+a.join``+''])+''==a.reverse(k=0))(a=[...x+''])|a.map((p,i)=>a.map((q,j)=>k+=g(b=[...a],b[i]=q,b[j]=p)))|!k||--n?f(n,-~x):[x,k/2]

```

Try it online!

# Answer
> 0 votes
# Perl 5 `-alp`, 148 bytes

```
$_=9;while(!$o||--$F[0]){$o=0;if(++$_ ne reverse){for$i(0..(@a=/./g)){map{@b=@a;@b[$i,$_]=@b[$_,$i];$o+=($t=1*join'',@b)eq reverse$t}$i..$#a}}}say$o

```

Try it online!

Output is on two lines. First line is the order; second line is the number.

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