title: Bouncing in an array

text:
# Question
Title: Bouncing in an array
### Introduction

Arrays can also be seen as a field for a bouncing ball. This of course sounds very vague, so here is an example of an input:

```
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[9, 8, 7, 6, 5, 4, 3, 2, 1]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

```

The challenge is to output the **bounced arrays**. These are made from diagonal patterns which bounce at the edges of the field. This path is pointed *upwards*. The path for the first bounced array (in which the path is directly bounced off the egde), is:

```
[1, -, -, -, 5, -, -, -, 9]
[-, 8, -, 6, -, 4, -, 2, -]
[-, -, 3, -, -, -, 7, -, -]

```

From left to right, this would result in `[1, 8, 3, 6, 5, 4, 7, 2, 9]`. This is our *first* bounced array. The path for the second bounced array:

```
[-, 2, -, -, -, 6, -, -, -]
[9, -, 7, -, 5, -, 3, -, 1]
[-, -, -, 4, -, -, -, 8, -]

```

This results in `[9, 2, 7, 4, 5, 6, 3, 8, 1]`. The path for the third bounced array is:

```
[-, -, 3, -, -, -, 7, -, -]
[-, 8, -, 6, -, 4, -, 2, -]
[1, -, -, -, 5, -, -, -, 9]

```

This results in `[1, 8, 3, 6, 5, 4, 7, 2, 9]`. So the three *bounced arrays* are:

```
[1, 8, 3, 6, 5, 4, 7, 2, 9]
[9, 2, 7, 4, 5, 6, 3, 8, 1]
[1, 8, 3, 6, 5, 4, 7, 2, 9]

```

### Task

Given at least 1 array containing only non-negative integers, with all the arrays having the same length, output all the bounced arrays.

### Test cases

Test case 1:

```
Input:                       Output:
[1, 2, 3, 4, 5]              [1, 7, 3, 9, 5]
[6, 7, 8, 9, 0]              [6, 2, 8, 4, 0]

Input:                       Output:
[1, 2, 3, 4, 5]              [1, 2, 3, 4, 5]

Input:                       Output:
[0, 0, 0, 0, 0, 0, 0, 0]     [0, 9, 0, 9, 0, 9, 0, 100]
[9, 9, 9, 9, 9, 9, 9, 100]   [9, 0, 9, 0, 9, 0, 9, 0]
[0, 0, 0, 0, 0, 0, 0, 0]     [0, 9, 0, 9, 0, 9, 0, 100]

Input:                       Output:
[0, 1, 2, 3, 4, 5]           [0, 7, 14, 9, 4, 11]
[6, 7, 8, 9, 10, 11]         [6, 1, 8, 15, 10, 5]
[12, 13, 14, 15, 16, 17]     [12, 7, 2, 9, 16, 11]

Input:                       Output:
[0, 0, 0, 0, 0, 0]           [0, 2, 2, 6, 2, 6]
[1, 2, 3, 4, 5, 6]           [1, 0, 3, 2, 5, 2]
[2, 2, 2, 2, 2, 2]           [2, 2, 0, 4, 2, 4]
[9, 8, 7, 6, 5, 4]           [9, 2, 3, 0, 5, 2]

```

This is , so the submission with the least amount of bytes wins!

# Answer
## Pyth, 17 bytes

```
>lQC.e.>bkC+_PtQQ

```

Explanation:

```
                      implicit: Q=input
>                     First
  l Q                   len(Q) elements of the
  C .e                  Transpose of enumerated map lambda b,k:
       .>                 Rotate the kth element rightwards by
          b
          k               k.
       C +              Transpose of: Q concatenated to
           _ P t Q        itself reversed without first and last elements.
           Q

```

Try it here.
> 7 votes

# Answer
# JavaScript (ES6), 70

```
a=>a.map((r,k)=>r.map((e,j)=>(a[k-=d]||a[d=-d,k-=d+d]||r)[j],d=1,++k))

```

**TEST**

```
F = a=>a.map((r,k)=>r.map((e,j)=>(a[k-=d]||a[d=-d,k-=d+d]||r)[j],d=1,++k))

test = [{
  I: [
    [1, 2, 3, 4, 5],
    [6, 7, 8, 9, 0]
  ],
  O: [
    [1, 7, 3, 9, 5],
    [6, 2, 8, 4, 0]
  ]
}, {
  I: [
    [1, 2, 3, 4, 5]
  ],
  O: [
    [1, 2, 3, 4, 5]
  ]
}, {
  I: [
    [0, 0, 0, 0, 0, 0, 0, 0],
    [9, 9, 9, 9, 9, 9, 9, 100],
    [0, 0, 0, 0, 0, 0, 0, 0]
  ],
  O: [
    [0, 9, 0, 9, 0, 9, 0, 100],
    [9, 0, 9, 0, 9, 0, 9, 0],
    [0, 9, 0, 9, 0, 9, 0, 100]
  ]
}, {
  I: [
    [0, 1, 2, 3, 4, 5],
    [6, 7, 8, 9, 10, 11],
    [12, 13, 14, 15, 16, 17]
  ],
  O: [
    [0, 7, 14, 9, 4, 11],
    [6, 1, 8, 15, 10, 5],
    [12, 7, 2, 9, 16, 11]
  ]
}, {
  I: [
    [0, 0, 0, 0, 0, 0],
    [1, 2, 3, 4, 5, 6],
    [2, 2, 2, 2, 2, 2],
    [9, 8, 7, 6, 5, 4]
  ],
  O: [
    [0, 2, 2, 6, 2, 6],
    [1, 0, 3, 2, 5, 2],
    [2, 2, 0, 4, 2, 4],
    [9, 2, 3, 0, 5, 2]
  ]
}];

console.log = x => O.textContent += x + '\n';

test.forEach(t => {
  var r = F(t.I),
    ok = r.join `\n` == t.O.join `\n`
  console.log((ok ? 'OK' : 'KO') + '\nInput\n' + t.I.join `\n` + '\nOutput\n' + r.join `\n` + '\n')
})
```

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

# Answer
## CJam, ~~31~~ 30 bytes

```
q~__W%1>W<+_z,_@*<zee::m>z\,<p

```

Input and output as a list of CJam-style arrays.

Test it here.

Most definitely golfable...
> 3 votes

# Answer
# Jelly, ~~29~~ ~~25~~ 24 bytes

```
ṖḊm-³;Z
,ZL€R_€/‘ż€Çị/€€

```

*Thanks for @Sp3000 for helping me golf off 5 bytes!*

Try it online!
> 3 votes

# Answer
# Japt, ~~55~~ ~~49~~ ~~41~~ 39 bytes

Wow, that was both really tricky and insanely fun.

```
C=2*Nl -2Nw £YoY+Ul)£NgLmX%CC-X%C)gY} ·

```

Test it online!

Outputs in reverse order to the examples. This will break slightly on inputs of more than 100 arrays; hopefully this doesn't make too much difference.

```
           // Implicit: N = array of input arrays, U = first input array, J = -1, L = 100
           // Let's use the first example. 3 input arrays, each of length 9.
C=2*Nl -2  // Set variable C to 2*N.length - 2. In the example, C is 4.
Nw      }  // Reverse N and map each index Y to:
YoY+Ul)    //  Create the range [Y...U.length+Y).
           //  The first time through (Y=0), we have   [0, 1, 2, 3, 4, 5, 6, 7, 8]
£       }  //  Map each item X and index Y to:
X%C        //   Take X mod C.                          [0, 1, 2, 3, 0, 1, 2, 3, 0]
C-X%C      //   Take C - (X mod C).                    [4, 3, 2, 1, 4, 3, 2, 1, 4]
Lm         //   Take the minimum of these and 100.     [0, 1, 2, 1, 0, 1, 2, 1, 0]
Ng         //   Get the array at the resulting index.
gY         //   Get the item at index Y in this array. [1, 8, 3, 6, 5, 4, 2, 7, 9]
·          // Join the result with newlines. I guess this isn't necessary, but it helps with readability.

```

### Non-competing version, 36 bytes

```
C=J+Nl)òC±C ®óUl)£NgLmX%CC-X%C)gY} ·

```

I had implemented these two number functions prior to the challenge:

* `ò` \- same as `o`, but returns `[X..Y]` instead of `[X..Y)`
* `ó` \- same as `o`, but returns `[X..X+Y)` instead of `[X..Y)`

But due to a misplaced `0`, they were buggy and always returned empty arrays. This has now been fixed.

Test it online!
> 2 votes

# Answer
## Ruby (2.2.2p95), 124 bytes

```
->*a{b=a.length;b<2?a:b.times.map{|i|d=i>0?-1:1;c=i;a[0].length.times.map{|j|r=a[c][j];c+=d;d*=-1if c==0||c==a.length-1;r}}}

```

This could probably be a lot better. I'll figure out how later!
> 2 votes

# Answer
# Python 2, ~~107~~ ~~106~~ ~~108~~ ~~105~~ 104 bytes

(Dropped some extra parens) (Wrong starting location (ب\_ب) ) (already had a list of that length)

```
def b(a):
 r,e=len(a)-1,enumerate
 print[[a[abs((i-o-r)%(r*2or 1)-r)][i]for i,_ in e(q)]for o,q in e(a)]

```

It's legal to have the input as an argument to a function, right? This is my first time submitting my code golf answer.
> 2 votes

# Answer
## APL, 33 chars

```
{(⍳≢⍵){0⌷(⍺-⍳≢⍉⍵)⊖⍵⍪1↓¯1↓⊖⍵}¨⊂↑⍵}

```

Assume ⎕IO←0. The idea is that the bouncing movement can be obtained by simple shift upward of a matrix, if the original matrix is augmented along the first dimension with the matrix reversed with its first and last row shaved. Graphically:

```
1 - - - - - 1 - - - -
- 2 - - - 2 - 2 - - -
- - 3 - 3 - - - 3 - 3
- - - 4 - - - - - 4 -

```

from

```
1 - - - - - 1 - - - -
- 2 - - - - - 2 - - -
- - 3 - - - - - 3 - -
- - - 4 - - - - - 4 -
- - - - 3 - - - - - 3
- - - - - 2 - - - - -

```

In APL `reverse` and `upward rotate` are the same symbol: .
> 1 votes

# Answer
## Clojure, 125 bytes

Wow, this accumulated characters quite fast.

```
(fn[v](let[H(count v)r range R(r H)](for[i R](map #((v %2)%)(r(count(v 0)))(drop i(cycle(concat R(reverse(r 1(dec H))))))))))

```

Just trying to save bytes by `let`-defining frequently used values.
> 1 votes

# Answer
# Jelly\*, 15 bytes

```
JṚŒḄṖṙ’Ʋị⁸Jị"$€

```

Try it online!

<sup>* Newer version</sup>
> 0 votes

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


# Question
Title: The least weird fact about the US presidency right now
The **least** weird fact about the US presidency right now is that there have been two unrelated presidents whose last names start with T-R-U-M.

That made me think, how many US presidents share other combinations of characters? There are obviously two presidents that share the characters "BUSH", and "ROOSEVELT". But did you know there are four presidents who share the characters "BU" (Buchanan, Buren, Bush and Bush), three presidents who share "CL" (Cleveland, Cleveland and Clinton), but only one president whose name starts with an "E" (Eisenhower).

---

# Challenge:

Take a non-empty string as input, and output how many presidents have names starting at those letters. **You may assume that the string will match at least one president**.

That means, you may get inputs such as "J" (Jackson, Jefferson, Johnson and Johnson), "TA" (Taft and Taylor) and "Nixon" (Nixon). You will **not** get inputs such as "Z", "RANT" and "RUMP".

---

### Rules

* The input is on any convenient format, with optional upper or lower case.
* The output should be an integer in the range **1 ... 5**.
* Shortest code in bytes in each language wins

### Test cases

There are three strings that should return 5 (C, H, T), two strings that should return 4 (BU, J), five strings that should return 3 (A, CL, HAR, M, R). There are many strings that should return 2. Where there are parentheses, it means both AD, ADA, ADAM and ADAMS should all return 2, as well as TR, TRU and TRUM. You will not get "TRUT" as input, since that doesn't match a president.

```
5: C, H, T
4: BU, J,
3: A, CL, HAR, M, R
2: AD (ADAMS), BUS (BUSH), CLE (CLEVELAND), F, G, HARR (HARRISON), JO (JOHNSON), P, RO (ROOSEVELT), TA, TR (TRUM), W
1: Every other valid string

```

### Alphabetical list of surnames

```
Adams, Adams, Arthur, Buchanan, Buren, Bush, Bush, Carter, Cleveland, Cleveland, Clinton, Coolidge, Eisenhower, Fillmore, Ford, Garfield, Grant, Harding, Harrison, Harrison, Hayes, Hoover, Jackson, Jefferson, Johnson, Johnson, Kennedy, Lincoln, Madison, McKinley, Monroe, Nixon, Obama, Pierce, Polk, Reagan, Roosevelt, Roosevelt, Taft, Taylor, Truman, Trump, Tyler, Washington, Wilson
-------- Same list (obviously) -----------
'Adams', 'Adams', 'Arthur', 'Buchanan', 'Buren', 'Bush', 'Bush', 'Carter', 'Cleveland', 'Cleveland', 'Clinton', 'Coolidge', 'Eisenhower', 'Fillmore', 'Ford', 'Garfield', 'Grant', 'Harding', 'Harrison', 'Harrison', 'Hayes', 'Hoover', 'Jackson', 'Jefferson', 'Johnson', 'Johnson', 'Kennedy', 'Lincoln', 'Madison', 'McKinley', 'Monroe', 'Nixon', 'Obama', 'Pierce', 'Polk', 'Reagan', 'Roosevelt', 'Roosevelt', 'Taft', 'Taylor', 'Truman', 'Trump', 'Tyler', 'Washington', 'Wilson'

```

# Answer
# Python 2, ~~179~~ ~~175~~ 173 bytes

```
lambda s:sum(any(s==X[:len(s)]for X in x.split())for x in[A,B,'A CL HAR M R '+B,'ADAMS BUSH CLEVELAND F G HARRISON JOHNSON P ROOSEVELT TA TRUM W M',s])
A='C H T';B='BU J '+A

```

Try it online!
> 5 votes

# Answer
# Python 3, ~~141~~ ~~140~~ ~~111~~ ~~106~~ 97 bytes

Input is in title case, 114 bytes with lowercase input.

-5 bytes thanks to Value Ink.

```
lambda n:(f"AdamsBushCleveFGHarriJohnsPRooseTaTrumW{0:31}AClHarMR{0:36}BuJCHT".rfind(n[:5]))/39+2

```

Try it online!
> 5 votes

# Answer
# JavaScript (ES6), ~~109~~ ~~105~~ 102 bytes

Expects the input string in title case.

```
s=>-~"CHT4BuHaJ3AClHarMR2AdamsBushCleveFGHarriJohnsPRooseTaTrumW1".match(s.slice(0,5)+'.*?(\\d)|1')[1]

```

Try it online!

### How?

We use a lookup string holding prefixes between 1 and 5 characters, along with digits describing the corresponding number of occurrences:

```
"CHT4BuHaJ3AClHarMR2AdamsBushCleveFGHarriJohnsPRooseTaTrumW1"
 {5-}{4---}{3------}{2-------------------------------------}

```

We use the following regular expression on this string and apply `-~` on the second entry returned by `.match()`:

```
                                     /**PREFIX**.*?(\d)|1/
                                      \____/\_/\__/\/
                                        |    |  |  |
the 5 first characters of the input ----+    |  |  |
the shortest possible string (lazy match) ---+  |  |
a digit (captured) -----------------------------+  |
fallback: look for '1' instead (last character) ---+

```

*Examples:*

* `"C"``['CHT4', '4']``-~'4' = 5`
* `"Har"``['HarMR2', '2']``-~'2' = 3`
* `"Lincoln"``['1', undefined]``-~undefined = 1`
> 4 votes

# Answer
# , 156 bytes

```
function(k)max(which(mapply(grepl,z<-paste('',k),c(z,' ADAMS BUSH CLEVELAND F G HARRISON JOHNSON P ROOSEVELT TA TRUM W',' A CL HAR M R',' BU J',' C H T'))))

```

Try it online!

Inspired by @TFeld Python 2 solution
> 3 votes

# Answer
# Ruby, ~~132 100~~ 92 bytes

```
->s{1+"AdamsBushCleveFGHarriJohnsPRooseTaTrumWAClHarMMRBuBuJJCCHHTT".scan(/#{s[0,5]}/).size}

```

Try it online!
> 0 votes

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


title: Is the Matrix Positive-Definite?

text:
# Question
Title: Is the Matrix Positive-Definite?
## Introduction

Today we're gonna take care of the bane of first-year linear algebra students: matrix definiteness! Apparently this doesn't yet have a challenge so here we go:

## Input

* A \\$n\times n\\$ symmetric Matrix \\$A\\$ in any convenient format (you may also of course only take the upper or the lower part of the matrix)
* Optionally: the size of the matrix \\$n\\$

## What to do?

The challenge is simple: Given a real-valued matrix \\$n\times n\\$ Matrix decide whether it is positive definite by outputting a truthy value if so and a falsey value if not.

You may assume your built-ins to actually work precisely and thus don't have to account for numerical issues which could lead to the wrong behaviour if the strategy / code "provably" should yield the correct result.

## Who wins?

This is , so the shortest code in bytes (per-language) wins!

---

## What is a positive-definite Matrix anyways?

There are apparently 6 equivalent formulations of when a symmetric matrix is positive-definite. I shall reproduce the three easier ones and reference you to Wikipedia for the more complex ones.

* If \\$\forall v\in\mathbb R^n\setminus \\{0\\}: v^T Av\>0\\$ then \\$A\\$ is positive-definite.
This can be re-formulated as:
If for every non-zero vector \\$v\\$ the (standard) dot product of \\$v\\$ and \\$Av\\$ is positive then \\$A\\$ is positive-definite.
* Let \\$\lambda\_i\quad i\in\\{1,\ldots,n\\}\\$ be the eigenvalues of \\$A\\$, if now \\$\forall i\in\\{1,\ldots,n\\}:\lambda\_i\>0\\$ (that is all eigenvalues are positive) then \\$A\\$ is positive-definite.
If you don't know what eigenvalues are I suggest you use your favourite search engine to find out, because the explanation (and the needed computation strategies) is too long to be contained in this post.
* If the Cholesky-Decomposition of \\$A\\$ exists, i.e. there exists a lower-triangular matrix \\$L\\$ such that \\$LL^T=A\\$ then \\$A\\$ is positive-definite. Note that this is equivalent to early-returning "false" if at any point the computation of the root during the algorithm fails due to a negative argument.

## Examples

### For truthy output

\begin{pmatrix}1&0&0\\0&1&0\\0&0&1\end{pmatrix}

\begin{pmatrix}1&0&0&0\\0&2&0&0\\0&0&3&0\\0&0&0&4\end{pmatrix}

\begin{pmatrix}5&2&-1\\2&1&-1\\\-1&-1&3\end{pmatrix}

\begin{pmatrix}1&-2&2\\\-2&5&0\\2&0&30\end{pmatrix}

\begin{pmatrix}7.15&2.45\\2.45&9.37\end{pmatrix}

### For falsey output

(at least one eigenvalue is 0 / positive semi-definite) \begin{pmatrix}3&-2&2\\\-2&4&0\\2&0&2\end{pmatrix}

(eigenvalues have different signs / indefinite) \begin{pmatrix}1&0&0\\0&-1&0\\0&0&1\end{pmatrix}

(all eigenvalues smaller than 0 / negative definite) \begin{pmatrix}-1&0&0\\0&-1&0\\0&0&-1\end{pmatrix}

(all eigenvalues smaller than 0 / negative definite) \begin{pmatrix}-2&3&0\\3&-5&0\\0&0&-1\end{pmatrix}

(all eigenvalues smaller than 0 / negative definite) \begin{pmatrix}-7.15&-2.45\\\-2.45&-9.37\end{pmatrix}

(three positive, one negative eigenvalue / indefinite) \begin{pmatrix}7.15&2.45&1.23&3.5\\2.45&9.37&2.71&3.14\\1.23&2.71&0&6.2\\3.5&3.14&6.2&0.56\end{pmatrix}

# Answer
# C, 108 bytes

*-1 byte thanks to Logern*
*-3 bytes thanks to ceilingcat*

```
f(M,n,i)double**M;{for(i=n*n;i--;)M[i/n][i%n]-=M[n][i%n]*M[i/n][n]/M[n][n];return M[n][n]>0&(!n||f(M,n-1));}

```

Try it online!

Performs Gaussian elimination and checks whether all diagonal elements are positive (Sylvester's criterion). Argument `n` is the size of the matrix minus one.
> 10 votes

# Answer
# MATLAB/Octave, ~~19~~ ~~17~~ 12 bytes

```
@(A)eig(A)>0

```

Try it online!

The function eig provides the eigenvalues in ascending order, so if the first eigenvalue is greater than zero, the other ones are too.
> 9 votes

# Answer
# Jelly, ~~11~~ 10 bytes

```
ṖṖ€$ƬÆḊṂ>0

```

Uses Sylvester's criterion.

Try it online!

### How it works

```
ṖṖ€$ƬÆḊṂ>0  Main link. Argument: M (matrix)

   $Ƭ       Do the following until a fixed point is encountered.
Ṗ             Pop; remove the last row of the matrix.
 Ṗ€           Pop each; remove the last entry of each row.
     ÆḊ     Take the determinants of the resulting minors.
       Ṃ    Take the minimum.
        >0  Test if the least determinant is positive, i.e., if all determinants are.

```
> 7 votes

# Answer
# , 29 bytes

```
function(m)all(eigen(m)$va>0)

```

Try it online!

---

Alternative using cholesky :

# , ~~34~~ 33 bytes

```
function(m)is.array(try(chol(m)))

```

Try it online!

-1 byte thanks to @Giuseppe
> 6 votes

# Answer
# Haskell, 56 bytes

```
f((x:y):z)=x>0&&f[zipWith(-)v$map(u/x*)y|u:v<-z]
f[]=1>0

```

Try it online!

Basically a port of nwellnhof's answer. Performs gaussian elimination and checks whether the elements on the main diagonal are positive.

~~Fails the first falsey output because of rounding errors, but it would theoretically work with infinite precision.~~ Thanks to Curtis Bechtel's suggestion, now the outputs are all correct.
> 6 votes

# Answer
# Wolfram Language (Mathematica), 20 bytes

```
0<Min@Eigenvalues@#&

```

Try it online!
> 4 votes

# Answer
# MATL, 4 bytes

```
Yv0>

```

Try it online!

I've noticed that for the `[3 -2 2; -2 4 0; 2 0 2]` test case, MATL calculates the `0` eigenvalue with a very small inaccuracy, computing something as low as about \\$10^{-18}\\$. This therefore fails the first falsy test case due to precision issues. Thanks to Luis Mendo for pointing out that a non-empty array is truthy iff all its entries differ from 0, saving 1 byte.
> 3 votes

# Answer
# Mathematica, ~~29~~ 28 bytes

```
AllTrue[Eigenvalues@#,#>0&]&

```

Definition 2.
> 2 votes

# Answer
# MATL, 6 bytes

It is possible to do it using even less bytes, @Mr. Xcoder managed to find a 5 byte MATL answer!

```
YvX<0>

```

**Explanation**

```
Yv     compute eigenvalues
  X<   take the minimum
    0> check whether it is greather than zero

```

Try it online!
> 2 votes

# Answer
# Julia 1.0, 28 bytes

```
using LinearAlgebra
isposdef

```

Try it online!

---

# Julia 0.6, 8 bytes

```
isposdef

```

Try it online!
> 2 votes

# Answer
## Maple, 33 bytes

(i.e. my 2 cents)

```
with(LinearAlgebra):
IsDefinite(A)

```
> 1 votes

# Answer
# JavaScript (ES6),  ~~99 95~~  88 bytes

Same method as nwellnhof's answer. Returns \\$0\\$ or \\$1\\$.

```
f=(m,n=0,R=m[n])=>R?f(m,n+1)&R[m.map((r,y)=>y<n&&R.map((v,x)=>r[x]-=v*r[n]/R[n])),n]>0:1

```

Try it online!
> 0 votes

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


title: Quadratic residues are so much fun!

text:
# Question
Title: Quadratic residues are so much fun!
## Definitions

### Quadratic residues

An integer \\$r\\$ is called a quadratic residue modulo \\$n\\$ if there exists an integer \\$x\\$ such that:

$$x^2\equiv r \pmod n$$

The set of quadratic residues modulo \\$n\\$ can be simply computed by looking at the results of \\$x^2 \bmod n\\$ for \\$0 \le x \le \lfloor n/2\rfloor\\$.

### The challenge sequence

We define \\$a\_n\\$ as the minimum number of occurrences of the same value \\$(r\_0-r\_1+n) \bmod n\\$ for all pairs \\$(r\_0,r\_1)\\$ of quadratic residues modulo \\$n\\$.

The first 30 terms are:

$$1, 2, 1, 1, 1, 2, 2, 1, 1, 2, 3, 1, 3, 4, 1, 1, 4, 2, 5, 1, 2, 6, 6, 1, 2, 6, 2, 2, 7, 2$$

This is A316975 (submitted by myself).

## Example: \\$n=10\\$

The quadratic residues modulo \\$10\\$ are \\$0\\$, \\$1\\$, \\$4\\$, \\$5\\$, \\$6\\$ and \\$9\\$.

For each pair \\$(r\_0,r\_1)\\$ of these quadratic residues, we compute \\$(r\_0-r\_1+10) \bmod 10\\$, which leads to the following table (where \\$r\_0\\$ is on the left and \\$r\_1\\$ is on the top):

$$\begin{array}{c|cccccc} & 0 & 1 & 4 & 5 & 6 & 9\\ \hline 0 & 0 & 9 & 6 & 5 & 4 & 1\\ 1 & 1 & 0 & \color{blue}7 & 6 & 5 & \color{green}2\\ 4 & 4 & \color{magenta}3 & 0 & 9 & \color{red}8 & 5\\ 5 & 5 & 4 & 1 & 0 & 9 & 6\\ 6 & 6 & 5 & \color{green}2 & 1 & 0 & \color{blue}7\\ 9 & 9 & \color{red}8 & 5 & 4 & \color{magenta}3 & 0 \end{array}$$

The minimum number of occurrences of the same value in the above table is \\$2\\$ (for \\$\color{green}2\\$, \\$\color{magenta}3\\$, \\$\color{blue}7\\$ and \\$\color{red}8\\$). Therefore \\$a\_{10}=2\\$.

## Your task

* You may either:

+ take an integer \\$n\\$ and print or return \\$a\_n\\$ (either 0-indexed or 1-indexed)
    + take an integer \\$n\\$ and print or return the \\$n\\$ first terms of the sequence
    + take no input and print the sequence forever
* Your code must be able to process any of the 50 first values of the sequence in less than 1 minute.
* Given enough time and memory, your code must theoretically work for any positive integer supported by your language.
* This is .

# Answer
# MATL, 14 bytes

```
:UG\u&-G\8#uX<

```

Try it online! Or verify the first 30 values.

### Explanation

```
:      % Implicit input. Range
U      % Square, element-wise
G      % Push input again
\      % Modulo, element-wise
u      % Unique elements
&-     % Table of pair-wise differences
G      % Push input
\      % Modulo, element-wise
8#u    % Number of occurrences of each element
X<     % Minimum. Implicit display

```
> 5 votes

# Answer
# Japt `-g`, ~~22~~ 20 bytes

Spent too long figuring out what the challenge was actually about, ran out of time for further golfing :\

Outputs the `n`th term in the sequence. Starts struggling when input `>900`.

```
õ_²uUÃâ ïÍmuU
£è¥XÃn

```

Try it or check results for 0-50

---

## Explanation

```
                  :Implicit input of integer U
õ                 :Range [1,U]
 _                :Map
  ²               :  Square
   uU             :  Modulo U
     Ã            :End map
      â           :Deduplicate
        ï         :Cartesian product of the resulting array with itself
         Í        :Reduce each pair by subtraction
          m       :Map
           uU     :  Absolute value of modulo U
\n                :Reassign to U
£                 :Map each X
 è                :  Count the elements in U that are
  ¥X              :   Equal to X
    Ã             :End map
     n            :Sort
                  :Implicitly output the first element in the array

```
> 4 votes

# Answer
# Jelly,  ~~13~~  10 bytes

-1 thanks to Dennis (forcing dyadic interpretation with a leading `ð`)
-2 more also thanks to Dennis (since the pairs may be de-duplicated we can avoid an `R` and a `2`)

```
ðp²%QI%ĠẈṂ

```

A monadic link accepting a positive integer which yields a non-negative integer.

**Try it online!** Or see the first 50 terms.

### How?

```
ðp²%QI%ĠẈṂ - Link: integer, n                   e.g. 6
ð          - start a new dyadic chain - i.e. f(Left=n, Right=n)
 p         - Cartesian product of (implicit ranges)  [[1,1],[1,2],[1,3],[1,4],[1,5],[1,6],[2,1],[2,2],[2,3],[2,4],[2,5],[2,6],[3,1],[3,2],[3,3],[3,4],[3,5],[3,6],[4,1],[4,2],[4,3],[4,4],[4,5],[4,6],[5,1],[5,2],[5,3],[5,4],[5,5],[5,6],[6,1],[6,2],[6,3],[6,4],[6,5],[6,6]]
  ²        - square (vectorises)                     [[1,1],[1,4],[1,9],[1,16],[1,25],[1,36],[4,1],[4,4],[4,9],[4,16],[4,25],[4,36],[9,1],[9,4],[9,9],[9,16],[9,25],[9,36],[16,1],[16,4],[16,9],[16,16],[16,25],[16,36],[25,1],[25,4],[25,9],[25,16],[25,25],[25,36],[36,1],[36,4],[36,9],[36,16],[36,25],[36,36]]
   %       - modulo (by Right) (vectorises)          [[1,1],[1,4],[1,3],[1,4],[1,1],[1,0],[4,1],[4,4],[4,3],[4,4],[4,1],[4,0],[3,1],[3,4],[3,3],[3,4],[3,1],[3,0],[4,1],[4,4],[4,3],[4,4],[4,1],[4,0],[1,1],[1,4],[1,3],[1,4],[1,1],[1,0],[0,1],[0,4],[0,3],[0,4],[0,1],[0,0]]
    Q      - de-duplicate                            [[1,1],[1,4],[1,3],[1,0],[4,1],[4,4],[4,3],[4,0],[3,1],[3,4],[3,3],[3,0],[0,1],[0,4],[0,3],[0,0]]
     I     - incremental differences (vectorises)    [0,3,2,-1,-3,0,-1,-4,-2,1,0,-3,1,4,3,0]
      %    - modulo (by Right) (vectorises)          [0,3,2,5,3,0,5,2,4,1,0,3,1,4,3,0]
       Ġ   - group indices by value                  [[1,6,11,16],[10,13],[3,8],[2,5,12,15],[9,14],[4,7]]
        Ẉ  - length of each                          [3,2,2,4,2,2]
         Ṃ - minimum                                 2

```
> 4 votes

# Answer
# 05AB1E, ~~22~~ ~~20~~ ~~15~~ 13 bytes

```
LnI%êãÆI%D.m¢

```

-2 bytes thanks to *@Mr. Xcoder*.

Try it online or verify the first 99 test cases (in about 3 seconds). (NOTE: The Python legacy version is used on TIO instead of the new Elixir rewrite. It's about 10x faster, but requires a trailing `¬` (head) because `.m` returns a list instead of a single item, which I've added to the footer.)

**Explanation:**

```
L       # Create a list in the range [1, (implicit) input]
 n      # Square each
  I%    # And then modulo each with the input
    ê   # Sort and uniquify the result (faster than just uniquify apparently)
 ã      # Create pairs (cartesian product with itself)
  Æ     # Get the differences between each pair
   I%   # And then modulo each with the input
D.m     # Take the least frequent number (numbers in the legacy version)
   ¢    # Take the count it (or all the numbers in the legacy version, which are all the same)
        # (and output it implicitly)

```
> 3 votes

# Answer
# C (gcc), ~~202~~ ~~200~~ ~~190~~ ~~188~~ ~~187~~ 186 bytes

* Saved ~~two~~ ~~twelve~~ ~~fourteen~~ fifteen bytes thanks to ceilingcat.
* Saved a byte.

```
Q(u,a){int*d,*r,A[u],t,i[a=u],*c=i,k;for(;a--;k||(*c++=a*a%u))for(k=a[A]=0,r=i;r<c;)k+=a*a%u==*r++;for(r=c;i-r--;)for(d=i;d<c;++A[(u+*r-*d++)%u]);for(t=*A;++a<u;t=k&&k<t?k:t)k=A[a];u=t;}

```

Try it online!
> 3 votes

# Answer
# Python 2, 97 bytes

```
def f(n):r={i*i%n for i in range(n)};r=[(s-t)%n for s in r for t in r];return min(map(r.count,r))

```

Try it online!
> 1 votes

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

```
{&/#:'=,/x!r-\:r:?x!i*i:!x}

```

Try it online!

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

`!x` integers from `0` to `x-1`

`i:` assign to `i`

`x!` mod `x`

`?` unique

`r:` assign to `r`

`-\:` subtract from each left

`r-\:r` matrix of all differences

`x!` mod `x`

`,/` concatenate the rows of the matrix

`=` group, returns a dictionary from unique values to lists of occurrence indices

`#:'` length of each value in the dictionary

`&/` minimum
> 1 votes

# Answer
# Wolfram Language (Mathematica), 64 bytes

```
Min[Last/@Tally@Mod[Tuples[Union@Mod[Range@#^2,#],2].{1,-1},#]]&

```

Try it online!
> 1 votes

# Answer
# Ruby, 88 bytes

```
->n{(z=(w=(0..n).map{|x|x*x%n}|[]).product(w).map{|a,b|(a-b)%n}).map{|c|z.count(c)}.min}

```

Try it online!
> 1 votes

# Answer
# APL (Dyalog Unicode), ~~28~~ 24 bytes

```
{⌊/⊢∘≢⌸∊⍵|∘.-⍨∪⍵|×⍨⍳⍵+1}

```

Try it online!

Prefix direct function. Uses `⎕IO←0`.

Thanks to Cows quack for 4 bytes!

### How:

```
{⌊/⊢∘≢⌸∊⍵|∘.-⍨∪⍵|×⍨⍳⍵+1} ⍝ Dfn, argument ⍵

                   ⍳⍵+1 ⍝ Range [0..⍵]
                 ×⍨     ⍝ Squared
               ⍵|       ⍝ Modulo ⍵
              ∪         ⍝ Unique
          ∘.-⍨          ⍝ Pairwise subtraction table
       ∊⍵|              ⍝ Modulo ⍵, flattened
      ⌸                 ⍝ Key; groups indices (in its ⍵) of values (in its ⍺).
   ⊢∘≢                  ⍝ Tally (≢) the indices. This returns the number of occurrences of each element.
 ⌊/                      ⍝ Floor reduction; returns the smallest number.

```
> 1 votes

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


title: Regular Expression to find a pangram

text:
# Question
Title: Regular Expression to find a pangram
Awhile back I encountered a simple programming puzzle to determine whether a string was a pangram, or a perfect pangram. (Although it's worth noting that this particular challenge gave a different meaning than the standard definition of a "perfect pangram," to mean any sentence where every letter appears *n* times for some positive *n*). And it was a fun challenge. But recently it got me wondering whether it would be possible to solve this challenge purely with regular expressions. If it is, I expect it will be a pretty gnarly regex. But I'm not even sure it is possible.

Still, if anyone is able to do it, it would be the folks here at Code Golf. So here's the challenge:

Write a regular expression which can determine whether or not a given string is a pangram. You can assume that all non-alpha characters have already been stripped out (or don't, if you really want to challenge yourself), and that everything has been transformed into lowercase.

Bonus challenge: write another regular expression to determine whether the given string is a "perfect pangram" by the definition given above.

Examples of an ordinary pangram:

> thequickbrownfoxjumpsoverthelazydog

Example of perfect pangrams:

> abcdefghijklmnopqrstuvwxyz
>
> jocknymphswaqfdrugvexblitz
>
> squdgykilpjobzarfnthcwmvexhmfjordwaltzcinqbuskpyxveg

I'm not really sure if this is even possible just with regex alone. If you find that it is, kudos!

# Answer
Assuming you're using a flavor of regex that include look-aheads, detecting a pangram is straightforward, but tedious. Using Python syntax:

`r"(?=.*a)(?=.*b)(?=.*c)(?=.*d)(?=.*e)(?=.*f)(?=.*g)(?=.*h)(?=.*i)(?=.*j)(?=.*k)(?=.*l)(?=.*m)(?=.*n)(?=.*o)(?=.*p)(?=.*q)(?=.*r)(?=.*s)(?=.*t)(?=.*u)(?=.*v)(?=.*w)(?=.*x)(?=.*y)(?=.*z).*"`

https://regex101.com/r/Z7NjEQ/2

The `(?=.*a)` block tests if what follows after that point matches `.*a`; another way to say that is, is this expression followed by any characters and then an `a`, or just, does this include an `a`? Then repeat that check for every letter of the alphabet.

Without lookaheads, it's still possible, but even more tedious, because you have to account for every possible ordering of the alphabet. If you were limited to the letters `abc`, here's what it might look like:

`r".*(a.*b.*c|a.*c.*b|b.*a.*c|b.*c.*a|c.*a.*b|c.*b.*a).*"`

https://regex101.com/r/OnXQe7/1/

This checks for an `a`, any set of characters, a `b`, any set of characters, then a `c`, OR an `a`, any set of characters, a `c`, any set of characters, then a `b`, OR...you get the idea.

You could use the same approach to check for the standard meaning of perfect pangram (every character exactly once), but not the modified version used here.
> 5 votes

# Answer
**Regexp: 45 43 20 19 18 bytes**

```
(?!.*(.).*\1).{26}

```

Assuming the input is \[a-z\] (lowercase, only alphabets a to z, spaces etc removed)

A byte saved, thanks to Neil
> 1 votes

---
Tags: regular-expression
---


title: Crop ASCII Art Challenge

text:
# Question
Title: Crop ASCII Art Challenge
ASCII art is fun. Modern text editors are very good at manipulating text. Are modern programming languages up to the task?

One common task in ASCII art manipulation is to crop text to a rectangle between two characters. This is the task you must implement in this challenge.

## Details

Your program will take 3 inputs:

* the first is the 'start' character of the block - marking the top-left corner
* the second is the 'end' character of the block - marking the bottom-right corner
* the third is some form of multiline text, either a string, or list of strings, or filename, or whatever

The result will be multiline text (again, in any of the above formats) cropped to the rectangle between the given inputs. Note that the first two inputs may not be unique.

## Edge cases

Boxes must always have volume at least 2. Thus these:

```
()     (
       )

```

*are* boxes but these:

```
)(     )      (
       (     )

```

are not (with start=`(` and end=`)`).

The input will only contain one box. Thus the start and end characters must only occur once, unless they are the same character in which case they must occur exactly twice.

Additionally each line in the input must be at least as long as the distance from the start of a line to the right edge of the box in the input.

Your program does not need to handle invalid inputs; they may result in undefined behavior.

## Rules

Typical code-golf rules apply. Shortest code wins.

## Examples

Sunny-day: `start: ( end: ) input:`

```
This is some text
. (but this text
  is in a box  ).
So only it is important.

```

Output:

```
(but this text
is in a box  )

```

Note the stripping of horizontal space as well. ASCII art crops are 2d.

Rainy-day: `start: ( end: ) input:`

```
This is some text (
But is that even  )
really a box?

```

Output:

```
(
)

```

Same start/end: `start: / end: / input:`

```
Oh, I get how this could be useful
 /----------------------------\
 | All this text is in a box! |
 \----------------------------/

```

Output:

```
/----------------------------\
| All this text is in a box! |
\----------------------------/

```

Invalid input: `start: ( end: ) input:`

```
Boxes are rectangular ( so this has
0 volume ) which is illegal.

```

Invalid input 2: `start: ( end: ) input:`

```
(The lines must already be square
so this line that is too short
relative to this end, is illegal)

```

# Answer
> 15 votes
# Vim, ~~16~~, 12 bytes/keystrokes

```
#<C-v>Nj*yggVGp

```

Try it online! in the V interpreter

> Modern text editors are very good at manipulating text. Are modern programming languages up to the task?

I bet *old* text editors are even better! :D

Even though it doesn't necessarily have to, this answer does work with both of the given "invalid" inputs, outputting

```
 rectangular (
) which is ill

```

and

```
(The lines must already be square
so this line that is too short
relative to this end, is illegal)

```

Explanation:

```
#               " Move backward to the previous occurrence of the word (or in this case, character) under the cursor
 <C-v>          " Start a visual block selection
      N         " Go to the next occurrence of the last searched term (guaranteed to be line 1)
       j        " Move down a line
        *       " Move forward to the next occurrence of the character under the cursor
         y      " Yank (copy) the whole visually selected block
          gg    " Go to line 1
            VG  " Select every line
              p " And paste what we last copied over it, deleting the whole buffer and replacing it with the block

```

# Answer
> 6 votes
# Jelly, 13 bytes

```
=€SŒṪr/,þ/Zœị

```

A dyadic link accepting a list of start and end characters on the left and a list of lines (as lists of characters) on the right which yields a list of lines (as lists of characters).

**Try it online!** (full program - if inputs are valid Python they will require Python-string-quoting.)

### How?

```
=€SŒṪr/,þ/Zœị - Link: [start, stop], lines
 €            - for each (of [start, stop]):
=             -   equals? (vectorises across the lines)
  S           - sum (vectorises)
   ŒṪ         - multi-dimensional truthy (i.e. non-zero) indices
      /       - reduce by:
     r        -   inclusive range (vectorises)
         /    - reduce by:
        þ     -    outer product with:
       ,      -       pair
          Z   - transpose
           œị - multi-dimensional index-into (the lines)

```

As an example, with left = `['a', 'b']` and right (as a list of lists of characters - the lines):

```
--------
--a+++--
--++++--
--+++b--
--------

```

`=€` yields a list of two lists of lists (the first performs `'a'=`, the second `'b'=`):

```
00000000         00000000
00100000         00000000
00000000    ,    00000000
00000000         00000100
00000000         00000000

```

summing this yields a single list of lists (summing element-wise):

```
00000000
00100000
00000000
00000100
00000000

```

`ŒṪ` then gives us the (1-indexed) multi-dimensional indices of the non-zeros, `[[2,3],[4,6]]` \- i.e. `[[top,left],[bottom,right]]`.

`r/` then performs `[2,3]r[4,6]` which, since `r` vectorises, is like `[2r4, 3r6]`, evaluating to `[[2,3,4],[3,4,5,6]]` \- i.e. `[rows,columns]`.

`,þ/` then performs `[2,3,4],þ[3,4,5,6]` where `þ` is an outer-poduct instruction and `,` is pair. This yields all the `[row,column]` values by column, in this case:

```
[[[2,3],[3,3],[4,3]],
 [[2,4],[3,4],[4,4]],
 [[2,5],[3,5],[4,5]],
 [[2,6],[3,6],[4,6]]]

```

We want these by row, so `Z` is used to transpose this to:

```
[[[2,3],[2,4],[2,5],[2,6]],
 [[3,3],[3,4],[3,5],[3,6]],
 [[4,3],[4,4],[4,5],[4,6]]]

```

Finally `œị` indexes back into the input lines:

```
a+++
++++
+++b

```

It's worth noting that when both bounding characters are the same `=€` identifies both twice but `SŒṪ` ends up doing the right thing, since `2` is truthy, e.g. with `['a','a']`:

```
--------         00000000   00000000        00000000
--a+++--         00100000   00100000        00200000
--++++--  =€ ->  00000000 , 00000000  S ->  00000000  ŒṪ ->  [[2,3],[4,6]]
--+++a--         00000100   00000100        00000020
--------         00000000   00000000        00000000

```

# Answer
> 5 votes
# APL (Dyalog), ~~38~~ 30 bytes

*4 bytes saved thanks to @EriktheOutgolfer*

```
(1-⍨w-⍨⊃⍸⎕=s)↑(w←∊⊃⌽⍸⎕=s)↑s←↑⎕

```

Try it online!

# Answer
> 3 votes
# Jelly, 14 bytes

```
œẹⱮẎQr/Ṛṭþ/œị⁸

```

Try it online!

# Answer
> 3 votes
# Python 2, 130 bytes

```
def f(s,e,t):
 a=[(i,l.find(c))for i,l in enumerate(t)for c in s+e if c in l];r,c,R,C=a[0]+a[-1]
 for l in t[r:R+1]:print l[c:C+1]

```

Try it online!

# Answer
> 2 votes
# Canvas, 37 bytes

```
｛³⁴⁰；ｘ≡‽┐
Ｘ⁸）Ｊ╵⁶；┤ω┤⁵Ｘ⁶⁸⁰Ｋ├；┐┤└∔┘┘∔；＠

```

Try it here!

36 bytes for getting the coordinates of the characters (and converting them to x,y,w,h because that's what  takes) and 1 byte for getting the subsection.. There must be a better approach

# Answer
> 2 votes
# JavaScript (ES6), 98 bytes

Takes input as two integers and an array of strings. Returns an array of strings.

```
(x,y,a,X=Y=0)=>a.filter(s=>!Y&&(Y=-~s.indexOf(y,X?X-1:X=-~s.indexOf(x)),X)).map(s=>s.slice(X-1,Y))

```

Try it online!

### Commented

```
( x,                          // x = start character
  y,                          // y = end character
  a,                          // a[] = array of strings
  X =                         // X = position of x, plus 1
  Y = 0                       // Y = position of y, plus 1
) =>                          //
  a.filter(s =>               // for each string s in a[]:
    !Y &&                     //   reject this string if Y is non-zero
    (                         //   otherwise, use the 2nd condition:
      Y = -~s.indexOf(        //     update Y:
        y,                    //       by looking for y in s
        X ?                   //       if X is non-zero:
          X - 1               //         start the search at X - 1
        :                     //       else:
          X = -~s.indexOf(x)  //         update X and start the search at X
      ),                      //     end of Y update
      X                       //     keep this string if X is non-zero
    )                         //   end of 2nd condition
  )                           // end of filter()
  .map(s =>                   // for each remaining string s:
    s.slice(X - 1, Y)         //   remove left and right characters outside the box
  )                           // end of map()

```

# Answer
> 2 votes
# Java 10, 204 bytes

```
(s,e,a)->{int b=-1,i=0;for(;i<a.length;i++)a[i]=(b=b<0?a[i].indexOf(s):b)<0|a[i].length()<b?"":a[i].substring(b);for(b=-1;i-->0;)a[i]=(b=b<0?a[i].indexOf(e):b)<0|a[i].length()<b?"":a[i].substring(0,b+1);}

```

Modifies the input-array instead of returning a new one to save bytes. This does mean that removed lines become `""` instead, though. If this is not allowed I will change it.

Try it online.

**Explanation:**

```
(s,e,a)->{                 // Method with 2 Strings & String-array parameters and no return
  int b=-1,                //  Boundaries-integer, starting at -1
  i=0;for(;i<a.length;i++) //  Loop `i` in the range [0, amountOfLines)
    a[i]=                  //   Change the `i`th line in the array to:
      (b=b<0?              //    If `b` is -1:
          a[i].indexOf(s)  //     Set `b` to the index of `s` in the current line
                           //     (which is still -1 if it's not found)
         :                 //    Else (starting index already found)
          b                //     Leave `b` unchanged
      )<0                  //    Then, if `b` is -1,
         |a[i].length()<b? //    or the current line-length is too short:
       ""                  //     Remove the current line
      :                    //    Else:
       a[i].substring(b);  //     Shorten the line by removing every character before `b`
  for(b=-1;                //  Reset `b` to -1
      i-->0;)              //  Loop `i` in the range (amountOfLines, 0]
    a[i]=                  //  Change the `i`th line in the array to:
       (b=b<0?a[i].indexOf(e):b)<0|a[i].length()<b?"":
                           //   Similar as above (with end `e` instead of start `s`),
         a[i].substring(0,b+1);}
                           //   except we remove every character after `b` this time

```

**For example:**

With the inputs `start = "("`, `end = ")"` and `lines =`

```
["This is some text",
 ". (but this text",
 "  is in a box  ).",
 "So only it is important."]

```

the first loop will crop it at the top and left, changing it to this:

```
["",
 "(but this text",
 "is in a box  ).",
 " only it is important."]

```

the second loop will crop it at the bottom and right, changing it to this:

```
["",
 "(but this text",
 "is in a box  )",
 ""]

```

# Answer
> 1 votes
# Retina 0.8.2, 110 bytes

```
^((.)¶.)(.*¶)+(.*\2)
$1¶$4
^(.)(¶.¶\1)
$2
}s`(?<=^.¶.+)¶.
¶
s`^¶(.)¶(.*\1).*
$2
+m`^((.)+).¶((?<-2>.)+)$
$1¶$3

```

Try it online! Explanation:

```
^((.)¶.)(.*¶)+(.*\2)
$1¶$4

```

Delete the input lines preceding the first line of the box.

```
^(.)(¶.¶\1)
$2

```

If the start character is in the left column of the input, delete it.

```
}s`(?<=^.¶.+)¶.
¶

```

If the start character hasn't been deleted yet, shift all the input columns left by one and repeat from the beginning.

```
s`^¶(.)¶(.*\1).*
$2

```

Delete the end character and everything in the input after the end character.

```
+m`^((.)+).¶((?<-2>.)+)$
$1¶$3

```

Truncate all the lines to the length of the next line. This works by counting all but one character on each line, then attempting to match up to that many characters on the next line; if this succeeds then the second line was shorter, so the last character is deleted and the loop repeats.

# Answer
> 0 votes
# C (gcc), 237 bytes

```
f(c,r,o,p)char*p,*c;{char*_=strchr(p,r),*a,b;*_=0;a=strrchr(p,10);a=(a?a:p);*_=r;r=_-a;p=a;_=strrchr(p,o);*_=0;a=strrchr(p,10);a=(a?a:p);*_=o;o=_-a+1;_[1]=0;for(_=p;_;_=strchr(_+1,10)){b=_[o];_[o]=0;strcat(c,_+r);strcat(c,"\n");_[o]=b;}}

```

Try it online!

I'm 99% sure this can be shortened using some kind of helper function to find horizontal index of and pointer to a character, as it is repeated twice. Alas I couldn't find a short enough way to do it, I may try again later if I find the time.

### Description

```
f(c,r,o,p)char*p,*c;{
    char*_=strchr(p,r),*a,b;         // find opening char (and declare vars)
    *_=0;a=strrchr(p,10);            // find \n before it
    a=(a?a:p);                       // deal with single line inputs
    *_=r;r=_-a;                      // save left margin width in r
    p=a;                             // crop everything before opening line

    _=strchr(p,o);                   // find closing char
    *_=0;a=strrchr(p,10);            // find \n before it
    a=(a?a:p);                       // deal with single line inputs
    *_=o;o=_-a+1;                    // save width in o
    _[1]=0;                          // crop everything after closing char
    for(_=p;_;_=strchr(_+1,10)){       // for each line
        b=_[o];_[o]=0;
        strcat(c,_+r);
        strcat(c,"\n");
        _[o]=b;
    }
}

```

# Answer
> 0 votes
# Stax, 15 bytes

```
╛↨½╝v∞░W╧)╗Ö≈☼k

```

Run and debug it

It takes the set of box delimiter characters (1 or 2) on the first line of input. The rest of the lines are the input body.

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

```
            first line of input is the delimiter characters
dL          discard the first line of input and listify the rest into an array
{           begin block for iteration
  Mr        rotate matrix 90 degrees
  {         begin block for while loop
    ch      copy first row of block
    y|&C    if it insersects with the first line of input, break iteration
    D       drop the first line
  W         do-while loop until break
}4*         execute block 4 times
m           display result lines

```

Run this one

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


# Question
Title: Let's play some Reaper - Closed for Submissions
**NOTE**: The winner of this competition is Jack!!!. No more submissions will be accepted.

Here is the chat room for this challenge. This is my first one so I'm open to suggestions!

Reaper is a game concept developed by the Art of Problem Solving which involves patience and greed. After modifying the game to fit a KOTH style contest (Thanks to @NathanMerrill and @dzaima for your suggestions and improvements), here is the challenge.

The game works as the following: we have a value known as the Reap that multiplies by a given constant every tick. After each tick, each bot has the option of "reaping", which means adding the current value of Reap to one's score, and reducing Reap down to 1.

However, there's a fixed number of ticks that a bot must wait in between "reaps", and a fixed number of points necessary to win the game.

Simple enough? Here are your inputs:

# I/O

You are to write a function in Python 3 that takes 3 inputs. The first is `self`, used for referencing class objects (shown later). The second is the `Reap`, the current value of the Reap that you would earn if you were to "reap". The third is `prevReap`, a list of the bots that reaped during the previous tick.

Other objects you can access in your function:

```
self.obj: An object for your use to store information between ticks.
self.mult: The multiplier that Reap is multiplied by each tick
self.win: The score you need to win
self.points: Your current set of points
self.waittime: The amount of ticks that you must wait between reaps during the game
self.time: The number of ticks since your last reap
self.lenBots: The number of bots (including you) in the game.
self.getRandom(): Use to produce a random number between 0 and 1.

```

You **MUST** not edit any of the contents of these objects, except for `self.obj`.

You must output `1` to reap, and anything else (or nothing) to not reap. Note that if you reap when you haven't waited enough ticks, I'll ignore the fact that you have chosen to reap.

# Rules

The parameters I will be using are `winning_score=10000`, `multiplier=1.6-(1.2/(1+sqrt(x)))`, `waittime = floor(1.5*x)` where `x` is the number of bots in the KOTH.

* The game ends when a player (or multiple) reach the winning score.
* When multiple bots ask to reap at once, priority is given to the bots who have waited longer(in case of ties, the bots that have waited the max time all are allowed to reap and gain the points in the Reap)
* Your bot must take no more than 100 ms on average across 5 ticks.
* If you want to import libraries, ask! I'll try to add any libraries that I can run on my desktop version of Python (math is already imported: feel free to use it)
* All of the standard loopholes for KoTHs, such as duplicate bots, 1-up bots, etc, are similarly banned.
* Any bots that use any sort of randomness must use the `getRandom` function I've provided.

You can find the controller in the TIO link below. To use it, add the name of your function to `BotList` as a string, and then add the function to the code. Modify `multiplier` to change what the Reap is multiplied by each tick, modify `winning_score` to change what score is necessary to end the game, and modify `waittime` to change the number of ticks to wait between reaps.

For your convenience, here are some sample (and rather silly) bots. Submitting bots similar to these will not be permitted. However, they demonstrate how the controller works.

```
def Greedybot(self,Reap, prevReap):
    return 1
def Randombot(self,Reap, prevReap):
    if self.obj == None:
        self.obj=[]
    self.obj.append(prevReap)
    if self.getRandom()>0.5:
        return 1

```

For those interested, here is the Controller with the 15 submissions built into it: Try it Online

**FINAL RESULTS**

WOO THEY ARE FINALLY HERE! Check the TIO Link above to see what code I used to generate the final standings. The results are not terribly interesting. Over the 1000 runs I did with different random seeds, the results were

```
1000 wins - Jack
0 wins - everyone else

```

Congratulations to the Bounty winner Jack!! (aka @Renzeee)

# Answer
> 9 votes
## Sniper

A bot fueled by spite. Keeps track of opponent's cooldowns and scores. Attempts to keep others from winning. Pretty much never actually wins, but makes the game frustrating to play for others.

**EDIT:**

* If reaping would cause it to win, reap.
* If no one is \>= 70% of the winning score:

+ If everyone else is on their cooldown, wait until the last possible moment to reap.
    + If anyone else would win by reaping the current value, and they are active now or would be active next turn, reap.
    + ~~If at least half of the other users are on their cooldown, attempt to reap.~~ *This makes it difficult to target specific opponents, and so was removed.*
    + Otherwise, reap 25% of the time (essentially to guarantee that this bot does reap SOMETIMES, just in case something weird happens, like everyone is waiting several turns).
* **If someone IS \>= 70% of the winning score:**

**+ If Sniper can win a tiebreaker, and next round would be above the average Reap value for the highest scoring opponent, reap**+ **If highest scoring opponent will leave their cooldown next turn, reap.**

```
def Sniper(self, Reap, prevReap):
    # initialize opponents array
    if not hasattr(self.obj, "opponents"):
        self.obj.opponents = {}

    # initialize previous Reap value
    if not hasattr(self.obj, "lastReap"):
        self.obj.lastReap = 0

    # increment all stored wait times to see who will be "active" this turn
    for opponent in self.obj.opponents:
        self.obj.opponents[opponent]["time"] += 1

    # update opponents array
    for opponent in prevReap:
        # don't track yourself, since you're not an opponent
        if opponent != "Sniper":
            # initialize opponent
            if opponent not in self.obj.opponents:
                self.obj.opponents[opponent] = {"time": 0, "points": 0, "num_reaps": 0, "avg": 0}
            self.obj.opponents[opponent]["time"] = 0
            self.obj.opponents[opponent]["points"] += self.obj.lastReap
            self.obj.opponents[opponent]["num_reaps"] += 1
            self.obj.opponents[opponent]["avg"] = self.obj.opponents[opponent]["points"] / self.obj.opponents[opponent]["num_reaps"]

    # done "assigning" points for last round, update lastReap
    self.obj.lastReap = Reap

    # get current 1st place(s) (excluding yourself)
    winner = "" if len(self.obj.opponents) == 0 else max(self.obj.opponents, key=lambda opponent:self.obj.opponents[opponent]["points"])

    # you are ready now
    if self.time >= self.waittime:
        # current Reap is sufficient for you to win
        if self.points + Reap >= self.win:
            return 1

        if (
                # a 1st place exists
                winner != ''
                # if current 1st place is close to winning
                and self.obj.opponents[winner]["points"] / self.win >= .7
        ):
            if (
                    # next round's Reap value will be above opponent's average Reap
                    (Reap * self.mult >= self.obj.opponents[winner]["avg"])
                    # we have been waiting at least as long as our opponent (tiebreaker)
                    and self.time >= self.obj.opponents[winner]["time"]
            ):
                return 1

                # current 1st place opponent will be active next round
            if self.obj.opponents[winner]["time"] + 1 >= self.waittime:
                return 1

        else:
            if (
                    # everyone is waiting for their cooldown
                    all(values["time"] < self.waittime for key, values in self.obj.opponents.items())
                    # and we're tracking ALL opponents
                    and len(self.obj.opponents) == self.lenBots - 1
                    # at least one person will be ready next turn
                    and any(values["time"] + 1 >= self.waittime for key, values in self.obj.opponents.items())
            ):
                return 1

            if (
                    # opponent will be active next round
                    any( (values["time"] + 1 >= self.waittime)
                         # current Reap value would allow opponent to win
                         and (values["points"] + Reap >= self.win) for key, values in self.obj.opponents.items())
            ):
                return 1

            if (
                    # a 1st place exists
                    winner != ''
                    # current 1st place opponent will be active next round
                    and (self.obj.opponents[winner]["time"] + 1 >= self.waittime)
                    # next round's Reap value will be above their average Reap
                    and (Reap * self.mult >= self.obj.opponents[winner]["avg"])

            ):
                return 1

            # # at least half of opponents are waiting for their cooldown
            # if sum(values["time"] < self.waittime for key, values in self.obj.opponents.items()) >= (self.lenBots - 1) / 2:
            #     return 1

            # 25% of the time
            if self.getRandom() <= .25:
                return 1

    # default return: do not snipe
    return 0

```

## Bored

Just for fun, this bot was brought along by a friend and doesn't actually want to be here. They roll a d16 until they get a number in 1-9, then they attempt to reap anytime a number contains the chosen digit. (Going to look for a d10 would disrupt the game, which is rude, and 0 is just too easy!)

```
def Bored(self, Reap, prevReap):
    # if this is the first round, determine your fav number
    if not hasattr(self.obj, "fav_int"):
        r = 0

        while r == 0:
            # 4 bits are required to code 1-9 (0b1001)
            for i in range(0, 4):
                # flip a coin. Puts a 1 in this bit place 50% of the time
                if self.getRandom() >= .50:
                    r += 2**i
            # if your random bit assigning has produced a number outside the range 1-9, try again
            if not (0 < r < 10):
                r = 0

        self.obj.fav_int = r

    # you are ready now
    if self.time >= self.waittime:
        # current Reap is sufficient for you to win
        if self.points + Reap >= self.win:
            return 1
        # do you like this value?
        if str(self.obj.fav_int) in str(Reap):
            return 1
        # do you like your wait time?
        if self.time % int(self.obj.fav_int) == 0:
            return 1

    # default return: do not reap
    return 0

```

# Answer
> 9 votes
# Indecisive Twitchy Mess

```
def mess(self, Reap, prevReap):
    if not hasattr(self.obj, "start"):
            self.obj.start = False
    if self.time < self.waittime:
        return 0
    if self.points + Reap >= self.win:
            return 1
    if Reap >= self.waittime / (self.lenBots + 2):
        self.obj.start = True
    if self.obj.start:
        return 1 if self.getRandom() > 0.2 else 0
    return 1 if self.getRandom() > 0.8 else 0

```

This bot does the usual checks first(Can I reap, can I win?) and then looks for a target value before it reaps. However, it's indecisive, so after it reaches the target, it wonders how much longer it can wait and doesn't reap immediately. In addition, it's twitchy, so it might accidentally "hit the button" and reap before the target.

### **Fun fact:** This is basically how I play reaper as a human.

# Answer
> 7 votes
# Jack

This is a simple bot with 4 rules:

* Don't reap when it doesn't do anything
* Always reap when reaping lets us win
* Also reap when there has not been reaped for 3 ticks
* Otherwise do nothing

I have optimized the 3 ticks versus the current existing bots (Sniper, grim\_reaper, Every50, mess, BetterRandom, Averager, some more).

```
def Jack(self, Reap, prevReap):
    if self.time < self.waittime:
        return 0
    if self.win - self.points < Reap:
        return 1
    if self.mult ** 3 <= Reap:
        return 1
    return 0

```

I have tried to stay with my old solution (5 ticks) but also reap if you haven't reap for longer than X ticks, and then reap after fewer ticks have been passed during non-reaping (i.e. 5, if waited longer than self.waittime + 5, also reap if not been reaped for 4 ticks). But this didn't improve just always reaping after 4 ticks instead of 5.

# Answer
> 5 votes
# Every 50

This bots will reap every time the `Reap` amount is above 50.

**Why 50?**

If I make the assumption there will be 25 bots in play, it means the `multiplier = 1.6-(1.2/(1+sqrt(25))) = 1.4` and the `waittime = floor(1.5*25) = 37`. Since the `Reap` starts at `1`, it will go up like this:

```
Round: 1  2    3     4      5      6      7      8       9       10      11      12      13      14      15       16       17       18       19       20       etc.
Reap:  1  1.4  1.96  2.744  ~3.84  ~5.39  ~7.53  ~10.54  ~14.76  ~20.66  ~28.92  ~40.50  ~56.69  ~79.37  ~111.12  ~155.57  ~217.79  ~304.91  ~426.88  ~597.63  etc.

```

As you can see, it reaches above 50 after 13 ticks. Since the `Reap` will reset to 1 every time a bot reaps, and the `waittime` for a bot that reaps is 37, the likelihood a bot reaps sooner than later is pretty high, especially with bots similar to the example `GreedyBot`, which will reap as soon as their `waittime` is available again. At first I wanted to do 200 which is the 17th tick, somewhat in the middle of the 37 waiting time ticks, but with the assumption there are 25 bots in play there is a pretty high chance someone else snatches the `Reap` before me. So I lowered it to 50. It's still a nice rounded number, but especially because it's the 13th tick (with 25 bots), and 13 and 'reaping' also fit a bit in that same 'evil' genre.

**Code:**

The code is laughable trivial..

```
def Every50(self, Reap, prevReap):
  return int(Reap > 50)

```

**Notes:**

This bot is pretty bad with low amount of bots in play. For now I will leave it, and I might make a better bot actually calculating the best time to `Reap`. With an extremely low amount of bots in play the `waittime` is much lower as well of course, so even `GreedyBot` might win quite easily from this bot if the `waittime` is low enough.

Hopefully more people will add a lot more bots. ;p

# Answer
> 5 votes
## Averager

```
def Averager(self,Reap,prevReap):
    returner = 0
    if not hasattr(self.obj,"last"):
        self.obj.last = Reap
        self.obj.total = 0
        self.obj.count = 0
        returner = 1
    else:
        if len(prevReap) > 0:
            self.obj.total += self.obj.last
            self.obj.count += 1
        self.obj.last = Reap
    if self.obj.count > 0 and Reap > self.obj.total / self.obj.count:
        returner = 1
    return returner

```

This bot tries to reap any time the current Reap value is above the average Reaped value.

# Answer
> 3 votes
# Grim Reaper

This bot keeps a running average of the values of all the previous reaps as well as the time each bot has been waiting. It reaps when it has been waiting longer than 3/4 of the other bots and the reap is at least 3/4 the size of the average reap seen so far. The goal is to grab a lot of reasonably sized, low risk reaps.

```
def grim_reaper(self, Reap, prevReap):
    if self.obj == None:
        self.obj = {}
        self.obj["reaps"] = []
        self.obj["prev"] = 1
        self.obj["players"] = {i:0 for i in range(math.ceil(self.waittime / 1.5))}
    if Reap == 1 and len(prevReap) > 0:
        self.obj["reaps"].append(self.obj["prev"])
        for player in prevReap:
            self.obj["players"][player] = 0

    retvalue = 0
    if (len(self.obj["reaps"]) > 0
         and Reap > sum(self.obj["reaps"]) / len(self.obj["reaps"]) * 3. / 4.
         and sum([self.time >= i for i in self.obj["players"].values()]) >= len(self.obj["players"].values()) * 3 / 4):
        retvalue = 1

    for player in self.obj["players"]:
        self.obj["players"][player] += 1
    self.obj["prev"] = Reap
    return retvalue

```

Edit: Fixed some embarrassing syntax errors.

Try it Online

# Answer
> 3 votes
# BetterRandom

```
def BetterRandom(self,reap,prevReap):
    return self.getRandom()>(reap/self.mult**self.waittime)**-0.810192835

```

The bot is based on the assumption that the chance to reap should be proportional to the reap size because a point is a point, no matter when it's gotten. There is always a very small chance to reap, this keeps the behavior exploitable. First I thought it would be directly proportional and assumed the proportionality constant to be around `1/mult^waittime` (the maximum reap assuming at least one bot plays greedy) after running some simulations I found that this was indeed the optimal constant. But the bot was still outperformed by Random so I concluded the relation wasn't directly proportional and added a constant to calculate what the relation was. After some simulations I found that against my test set of bots `-1.5` was optimal. This actually corresponds to an inversely proportional relationship between the reap chance and `reap*sqrt(reap)` which is surprising. So I suspect this is highly depended on the specific bots so a version of this bot that calculates k while playing would be better. (But I don't know if you are allowed to use data from previous rounds).

EDIT: I made program to find the kind of proportionality automatically. On the test set `["myBot("+str(k)+")","Randombot","Greedybot","Every50","Jack","grim_reaper","Averager","mess"]` I found the new value.

# Answer
> 3 votes
# Target

```
def target(self,Reap,prevReap):
    if not hasattr(self.obj, "target_time"):
        self.obj.target_time = -1
        self.obj.targeting = False
        self.obj.target = None
    if self.obj.target_time >= 0:
        self.obj.target_time += 1

    if self.time < self.waittime:
            return 0
    if self.points + Reap >= self.win:
        return 1
    if len(prevReap) > 0:
        if not self.obj.targeting:
            self.obj.target_time = 0
            self.obj.target = prevReap[int(self.getRandom() * len(prevReap))]
            self.obj.targeting = True
    if self.waittime <= self.obj.target_time + 1:
        self.obj.targeting = False
        self.obj.target = None
        self.obj.target_time = -1
        return 1
    return 0

```

My chances of winning with mess are almost none now, so time to mess up all the other bots in as many ways as possible! :)

This bot functions similar to sniper. Whenever someone reaps, it picks a random target from whoever reaped. Then, it simply waits until that target almost can reap again and snipes it. However, it doesn't change focus - once you've been chosen and locked on, you can't escape :)

# Answer
> 2 votes
Ongoing: My project to extend T4T to every open KOTH.

# Tit for Tat

```
def t4t(self, r, p):
    if(not hasattr(self.obj,"last")): self.obj.last = self.win
    if(p):
        self.obj.last = r
        return 0

    # The usual checks
    if self.time < self.waittime:
        return 0
    if self.points + r >= self.win:
        return 1

    if(r >= self.obj.last):
        return 1

```

# Tit for *n* Tats

```
def t4nt(self, r, p):
    n = 5 # Subject to change
    if(not hasattr(self.obj,"last")): self.obj.last = [self.win]*n

    if(p):
        self.obj.last.append(r)
        self.obj.last.pop(0)
        return 0

    # The usual checks
    if(self.time < self.waittime):
        return 0
    if(self.points + r >= self.win):
        return 1

    if(r >= self.obj.last[0]):
        return 1

```

---

# Kevin

Just to keep you on your toes.

```
def kevin(just, a, joke):
    return 0

```

# Answer
> 2 votes
# EveryN

I guess it's time for my second bot right before the deadline.

This bot will:

* Skip when it's still in its waiting time for the last Reap
* Reap when it can win
* Reap when no one reaped for at least `n` rounds, where `n` is calculated with `n = 3 + ceil(self.waittime / self.lenBots)`

Code:

```
def every_n(self, Reap, prevReap):
    # Initialize obj fields
    if not hasattr(self.obj, "roundsWithoutReaps"):
        self.obj.roundsWithoutReaps = 0

    # Increase the roundsWithoutReaps if no bots reaped last round
    if len(prevReap) < 1:
        self.obj.roundsWithoutReaps += 1
    else
        self.obj.roundsWithoutReaps = 0

    # Skip if you're still in your waiting time
    if self.time < self.waittime:
        return 0
    # Reap if you can win
    if self.win - self.points < Reap:
        return 1

    # i.e. 25 bots: 3 + ceil(37 / 25) = 5
    n = 3 + math.ceil(self.waittime / self.lenBots)

    # Only reap when no bots have reaped for at least `n` rounds
    if self.obj.roundsWithoutReaps >= n:
        self.obj.roundsWithoutReaps = 0
        return 1

    return 0

```

I don't program in Python very often, so if you see any mistakes let me know.

# Answer
> 1 votes
# Average Joe

I got inspired by *Averager* and created a bot which calculates on average how many turns it takes before someone reaps and tries to reap one turn prior to that.

```
def average_joe(self, Reap, prevReap):

    if not hasattr(self.obj, "average_turns"):
        self.obj.turns_since_reap = 1
        self.obj.total_turns = 0
        self.obj.total_reaps = 0
        return 1

    if len(prevReap) > 0:
        self.obj.total_turns = self.obj.total_turns + self.obj.turns_since_reap
        self.obj.total_reaps += 1
        self.obj.turns_since_reap = 0
    else:
        self.obj.turns_since_reap += 1

    # Don't reap if you are in cooldown
    if self.time < self.waittime:
        return 0

    # Reap if you are going to win
    if self.win - self.points < Reap:
        return 1

    # Reap if it is one turn before average
    average_turns = self.obj.total_turns / self.obj.total_reaps

    if average_turns - 1 >= self.obj.turns_since_reap:
        return 1
    else:
        return 0

```

# Answer
> 1 votes
# HardCoded

Yes, it is.

```
def HardCo(self,reap,prevReap):
    return reap > 2

```

Instead of averaging on the past reaps, use a pre-calculated average on a typical run. It's not going to get better with time anyway.

---
Tags: king-of-the-hill
---


title: Print rotation-safe numbers

text:
# Question
Title: Print rotation-safe numbers
## Background

You are working for some board-game manufacturer and need to produce wooden tiles with the numbers from 0 to *n* engraved on them for some game. However, without further ado, some tiles would become indistinguishable, e.g., `6` and `9`. To avoid this, you have to equip numbers that can be confused with others (and only those) with a disambiguating dot, e.g., you would have tiles like `9.` or `6089.`.

Unfortunately, you need to use some old, yet programmable wood-engraving device for this, whose interface is so broken that you have to encode every character of the program by hand in an unspeakably tedious process. Fortunately the device understands every existing programming language. Thus you are looking for the shortest program that prints such tiles.

## Actual task

Write the shortest program that:

* Takes a positive integer *n* as input. How the input is read is up to you.
* Prints each of the numbers from 0 to *n* (0 and *n* included) exactly once in an order of your choice, separated by a single whitespace character (including newline). The numbers are to be printed without leading zeros.
* Appends a dot (.) to every number that turns into another, valid number upon rotation by π (180 °), even if that number is larger than *n.* Your typeface’s 0 and 8 are rotation-symmetric and the 9 is a rotated 6. The 2 and 5 are distinct upon rotation; the 1 is not rotation-symmetric. Numbers with leading zeros are not valid.

## Examples

Each of the following numbers has to be printed exactly this way:

* `2`
* `4`
* `5`
* `6.`
* `8`
* `9.`
* `16`
* `60`
* `66.`
* `68.`
* `69`
* `906`
* `909.`
* `8088.`
* `9806.`
* `9886`
* `9889.`

# Answer
## Pyth \- 34 ~~38~~

```
VhQJ`N+J*\.&nJX_J`69`96&eN!-J"0689

```

I must give thanks to @Sp3000 for helping me remove 4 bytes. I originally had an additional check `&@JK` which made sure there was a 6 or 9 in the number, but after perusing the answers before posting, I read his answer and noticed that my identical translation and reversal already took care of that.

Also thanks to @isaacg for pointing out that strings are iterables, and you can use set operations on them. Also for making the current code ;)

Explanation:

```
                                    : (implicit) Q=eval(input())
VhQ                                 : for N in range(Q+1):
   J`N                              : J=str(N)
      +J*\.                         : J + "." * ...
           &nJX_J`69`96             : J!=translate(reversed(J),"69","96") and...
                       &eN          : N%10 and...
                          !-J"0689  : not(setwise_difference(J, "0689"))

```
> 5 votes

# Answer
# CJam, ~~46~~ ~~44~~ ~~43~~ 42 bytes

```
l~),{_A%g1$s_6890s-!\_69s_W%erW%=!&&'.*N}/

```

I think there's some room for improvement.

Test it here.

## Explanation

```
l~),{_A%g1$s_6890s-!\_69s_W%erW%=!&&'.*N}/
l~                                         "Read an eval input.";
  ),                                       "Get range from 0 to n.";
    {                                   }/ "For each...";
     _                                     "Get a copy of the integer.";
      A%g                                  "Ends with digit other than 0?";
         1$s_                              "Get another copy, convert to string, get a copy.";
             0689s-!                       "Contains rotation-safe digits?";
                    \                      "Swap with other copy.";
                     _                     "Get another copy.";
                      69s_W%er             "Swap 6 and 9.";
                              W%           "Reverse.";
                                =!         "Is different from original?";
                                  &&       "AND all three conditions.";
                                    '.*    "If true, push a period (else, an empty string).";
                                       N   "Push a newline.";

```
> 10 votes

# Answer
# CJam, ~~46 45 43~~ 42 bytes

```
ri){Is___69`96`erW%=!\6809`-!&IA%g&'.*N}fI

```

I think it can be golfed a little more.

Takes `n` from STDIN.

Try it online here
> 8 votes

# Answer
## APL 66

```
∊' ',¨{a←⌽'0.....9.86'[⎕D⍳b←⍕⍵]⋄'.'∊a:b⋄('0'=⊃a)∨⍵=⍎a:b⋄b,'.'}¨0,⍳

```

***Explanation:***

```
¨0,⍳           applies the function to each number 0-n
a←⌽'0.....9.86'[⎕D⍳b←⍕⍵] inverts 6s and 9s, leaving 8s and 0s, and replacing other numbers with dots. Reverses vector after substitution.
'.'∊a          if there is a dot in the number....
('0'=⊃a)       .. or if the number starts with 0...
⍵=⍎a           or if the (inverted) number is the same as original
:b             then print the original number
b,'.'          else print a dot in the end
∊' ',¨        Finally to give the result in the asked format i add a single space after each result and join them all

```

Try it on tryapl.org

*Note that in the online interpreter the ⍎ function doesn't work so i had to substitute it with 2⊃⎕VFI which does the same in this case, executes and returns the number, given a string.*
> 5 votes

# Answer
# Perl 5, 53 bytes

```
say$_,"."x(!/[1-57]|0$/&&reverse!=y/96/69/r)for 0..<>

```

Online demo.

Uses the Perl 5.10+ `say` feature, so needs to be run with `perl -M5.010` (or `perl -E`) to enable it. (See this meta thread.) Reads input from stdin, prints to stdout.
> 4 votes

# Answer
# C#, ~~343~~ 309 characters

*Way* too long, but anyway:

```
namespace System.Linq{class C{static void Main(){int n=int.Parse(Console.ReadLine());for(int i=0;i<=n;i++){var b=i+"";var c=b.Replace("6","9");Console.Write(b+(b.All(x=>x=='0'|x=='8'|x=='6'|x=='9')&!b.EndsWith("0")&!(b.Count(x=>x=='6')==b.Count(x=>x=='9')&new String(c.Reverse().ToArray())==c)?". ":" "));}}}}

```

How does it work? To add a period to the number, it must match the following requirements:

* Consists only of `0`, `8`, `6` and `9`.
* Does not end with a zero.
* Is not the same number when you rotate it:
    + If a number has an equal amount of `6`s and `9`s, and
    + if `c` = the number with all `6`s replaces with `9`s,
    + and reversed `c` == `c`,
    + then: the rotated number is the same as the number itself.

The numbers are separated by a space.

Code with indentation:

```
namespace System.Linq
{
    class C
    {
        static void Main()
        {
            int n = int.Parse(Console.ReadLine());
            for (int i = 0; i <= n; i++)
            {
                var b = i + "";
                var c = b.Replace("6", "9");
                Console.Write(b +
                    (b.All(x => x == '0' | x == '8' | x == '6' | x == '9') &
                    !b.EndsWith("0") &
                    !(b.Count(x => x == '6') == b.Count(x => x == '9') &
                    new String(c.Reverse().ToArray()) == c) ? ". " : " "));
            }
        }
    }
}

```
> 4 votes

# Answer
# Python 2, ~~130~~ ~~116~~ 113 bytes

```
def f(n):S=`n`;n and f(n-1);print S+"."*all([n%10,set(S)<=set("0689"),(u""+S[::-1]).translate({54:57,57:54})!=S])

```

Defines a function `f` which prints the numbers to STDOUT, in ascending order.

This time I thought I'd take a leaf out of @feersum's book with `.translate` :)

Expanded:

```
def f(n):
 S=`n`
 n and f(n-1)                                      # Recurse if not 0
 print S+"."*all([n%10,                            # Not divisible by 10
                  set(S)<=set("0689"),             # Consists of 0689
                  (u""+S[::-1]).translate
                  ({54:57,57:54})!=S])             # When rotated is not itself

```

---

Previous solution:

```
def f(n):S=`n`;print S+"."*all([n%10,set(S)<=set("0689"),eval("S[::-1]"+".replace('%s','%s')"*3%tuple("6a96a9"))!=S]);n and f(n-1)

```

Thanks to @xnor for showing me the `.replace` trick some time ago.
> 4 votes

# Answer
# M (MUMPS) - ~~72~~ 70

```
R n F i=0:1:n W !,i S r=$TR($RE(i),69,96) W:r=+r*r'=i*'$TR(i,0689) "."

```

Most built-in commands and functions in M have abbreviated versions. I've used the full names below.

`READ n` \- Read a string from the keyboard and store it in `n`.

`FOR i=0:1:n` \- Loop from zero to `n`, incrementing `i` by 1 each time. (The remainder of the line constitutes the body of the loop.)

`WRITE !,i` \- Print a newline followed by the value of `i`.

`SET r=$TRANSLATE($REVERSE(i),69,96))` \- Reverse `i`, replace nines with sixes and sixes with nines, and store that in `r`.

`WRITE:r=+r*r'=i*'$TRANSLATE(i,0689) "."`

* `:` \- Denotes a postconditional expression, so the `WRITE` command is only executed if `r=+r*r'=i*'$TRANSLATE(i,0689)` evaluates to a truthy value.
* `r=+r` \- Check that `r` doesn't have a leading zero. The unary `+` operator converts a string to a number, which strips leading zeroes if there are any.
* `*` \- Multiplication operator. M has no order of operations; all binary operators are evaluated in the order they appear from left to right.
* `r'=i` \- Check that `i` isn't the same as it's flipped version `r`.
* `'$TRANSLATE(i,0689)` \- Remove all zeros, sixes, eights, and nines from `i`, and check that there's nothing left. (`'` is the logical negation operator.)
* `"."` \- Finally the argument to the `WRITE` command (a literal string).

**Edit:** Made it a little shorter by abusing the multiplication operator. Previous version:

```
R n F i=0:1:n W !,i S r=$TR($RE(i),69,96) I '$TR(i,0689),i'=r,r=+r W "."

```
> 4 votes

# Answer
# APL, 53 characters

`∊{⍵,'. '↓⍨∨/(3≡⊃i)(5∊i),⍵≡'9608x'[i←⌽'6908'⍳⍵]}∘⍕¨0,⍳`

```
0,⍳N        numbers 0..N
{...}∘⍕¨    format each number as a string and do the thing in curly braces
                inside the braces ⍵ is the current string
'6908'⍳⍵    encode '6' as 1, '9' as 2, '0' as 3, '8' as 4, and all others as 5
⌽           reverse
'9608x'[A]  use each element of A as an index in '9608x':
                effectively: swap '9'←→'6', preserve '08', mask other digits
⍵≡          does it match the original string?
                this is the first boolean condition, two more to come
5∊i         did we have a digit other than '0689'?
3≡⊃i        is the first of i (that is, the last of ⍵) a '0' (encoded as 3)?
∨/          disjunction ("or") over the three conditions, returns 0 or 1
'. '↓⍨      drop 0 or 1 elements from the beginning of the string '. '
⍵,          prepend ⍵
∊           flatten the results to obtain a single output string

```
> 3 votes

# Answer
# C# 205 ~~209~~

C# doesn't have to be so long...
more or less, a port of my JavaScript answer

```
class P{static void Main(string[]a){for(int n=int.Parse(a[0]);n>=0;--n){string p="",u=n+p;int e=n%10;foreach(var d in u)p=(d<56?d!=54?d>48?e=0:0:9:120-d-d)+p;System.Console.WriteLine(e!=0&p!=u?u+".":u);}}}

```

**Ungolfed**

```
class P
{
    static void Main(string[] a)
    {
        for (int n = int.Parse(a[0]); n >= 0; --n)
        {
            string p = "", u = n + p;
            int e = n % 10;
            foreach (var d in u) p = (d < 56 ? d != 54 ? d > 48 ? e = 0 : 0 : 9 : 120 - d - d) + p;
            System.Console.WriteLine(e != 0 & p != u ? u + "." : u);
        }
    }
}

```
> 3 votes

# Answer
# JavaScript (ES6) 101 ~~104 106 109~~

A function with n as argument, output via console.log
**Edit** using %10 to test for leading 0
**Edit 2** `for` reorganization, I don't need array comprehension after all
**Edit 3** modified (again) the check for leading 0

```
F=n=>{
   for(;e=~n;console.log(e*l&&p-n?n+'.':n),--n)
     for(d of(p='')+n)p=(l=d<8?d-6?-d?e=0:0:9:24-d-d)+p
}

```

**Ungolfed** and easier to test

```
F=n=>
{
  o = '';
  for( ; ~n; --n) // loop on n decreasing to 0 (~n is 0 when n==-1)
  {
    e = ~n; // init to a nonzero value, zero will mark 'invalid digit'
    p = ''; // build rotated number in p
    for(d of '' + n)
    {
      // l is the current digit, on exit will be the first digit of p
      l = d < 8 ?
            d != 6 ?
              d != 0 ?
                e = 0 // invalid char found, no matter what
                : 0
              : 9 // 6 become 9
            : 24 - d - d; // calc 8 => 8, 9 => 6
      p = l + p;
    }
    // e==0 if invalid char, l==0 if leading 0
    o += ' ' + ( e * l && p-n ? n+'.' : n);
  }
  console.log(o);
}

F(100)

```

*Output*

```
100 99. 98. 97 96 95 94 93 92 91 90 89. 88 87 86. 85 84 83 82 81 80 79 78 77 76 75 74 73 72 71 70 69 68. 67 66. 65 64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9. 8 7 6. 5 4 3 2 1 0

```
> 2 votes

# Answer
# Ruby, 81

```
?0.upto(*$*){|x|puts x.reverse.tr('69','96')!=x&&x=~/^[0689]+$/&&/0$/!~x ?x+?.:x}

```

Input is taken from the command line.

Generates a list of `String`s from `0` to `n`. It loops trough them and prints them. It appends a dot if all conditions are satisfied:

* reversing the number and replacing the `6`s with `9`s doesn't yield the original
* the number only consists of the digits `0`, `6`, `8` and `9`
* the number doesn't end with `0`
> 2 votes

# Answer
# sed, 467

Longer than C#...

I pretty much completed this when @edc65 pointed out that answers need to process numbers 0-n and not just n. Adding the sed code to increment 0-n adds a LOT more code, as this task is ill-suited to arithmetic-less sed.

```
:l
/^[0689]*$/{
h
s/$/:/
:x
s/([0-9]):(.*)/:\2\1/
tx
s/://
y/69/96/
G
/^([0-9]+)\n\1/be
s/^[^0].*/&./
:e
s/.*\n//
}
p
s/\.//
s/[0-9]/<&/g
s/0//g;s/1/_/g;s/2/__/g;s/3/___/g;s/4/____/g;s/5/_____/g
s/6/______/g;s/7/_______/g;s/8/________/g;s/9/_________/g
:t
s/_</<__________/
tt
s/<//g
s/_//
:b
s/__________/</g
s/<([0-9]*)$/<0\1/
s/_________/9/;s/________/8/;s/_______/7/;s/______/6/
s/_____/5/;s/____/4/;s/___/3/;s/__/2/;s/_/1/
s/</_/g
tb
s/^$/0/
/^0$/by
bl
:y
c\
0
p

```

As per the OP, ordering doesn't matter, so we work downwards from n to 0.

### Output:

```
$ sed -rnf rotproof.sed <<< 100 | grep "\."
99.
98.
89.
86.
68.
66.
9.
6.
$

```
> 2 votes

# Answer
# bc, 158

After doing this purely in sed using all string and regex operations with no native arithmetic, I was curious to see how this would look the other way around, i.e. all arithmetic and logic operations and no string/regex:

```
for(i=read();i+1;r=0){p=1
for(x=i;x;x/=A){d=x%A
if(x==i&&!d)p=0
if(d==6||d==9)d=F-d else if(d%8)p=0
r=r*A+d}
if(r==i)p=0
print i--
if(p)print "."
print "\n"}

```

Output is sorted in descending order.

### Output:

```
$ bc rotproof.bc <<< 100 | grep "\."
99.
98.
89.
86.
68.
66.
9.
6.
$

```
> 2 votes

# Answer
# Bash + coreutils, 105

```
for((i=0;i<=$1;i++));{
[ ${i//[0689]/} ]||[ $i = `rev<<<$i|tr 69 96` ]||((!${i: -1}))||d=.
echo $i$d
d=
}

```

### Test:

```
$ ./rotproof.sh 100 | grep "\."
6.
9.
66.
68.
86.
89.
98.
99.
$

```
> 1 votes

# Answer
# Python - 152

```
for i in range(input()+1):print`i`+("."*all([j in"0689"for j in`i`])and`i`[-1]!="0"and`i`!=`i`.replace("9","x").replace("6","9").replace("x","6")[::-1])

```
> 1 votes

# Answer
## AWK: 120

```
{a[a[6]=9]=6;a[8]=8;for(j=a[0]=0;j<=$0;++j){r="";for(i=j;i;i=int(i/10))r=r a[i%10];print(j~/[^0689]|0$/||j==r)?j:j"."}}

```

Read the n value from stdin.

Test:

> C:\AWK\>gawk -f revnum.awk|grep \\.
> 100
> ^Z
> 6.
> 9.
> 66.
> 68.
> 86.
> 89.
> 98.
> 99.
> 1 votes

# Answer
# Rebol - 195

```
for n 0 do input 1[b: copy a: form n d: c: 0 parse reverse a[any[m:"6"(change m"9"++ c)|"9"(change m"6"++ c)|"0"|"8"| skip(++ d)]]print rejoin [b either all[d = 0 c > 0 a != b a/1 != #"0"]"."{}]]

```

Ungolfed + some annotations:

```
for n 0 do input 1 [
    b: copy a: form n
    d: c: 0

    ; reverse number and rotate "6" & "9"
    ; and do some counts (c when "6" or "9" and d when != "0689")
    parse reverse a [
        any [
            m:
              "6" (change m "9" ++ c)
            | "9" (change m "6" ++ c)
            | "0"
            | "8"
            | skip (++ d)
        ]
    ]

    print rejoin [
        b either all [
            d = 0               ; only has 0689 digits
            c > 0               ; must have at least one "6" or "9"
            a != b              ; not same when reversed
            a/1 != #"0"         ; does not "end" with zero
        ]
        "." {}                  ; if ALL then print "." else blank {}
    ]
]

```
> 1 votes

# Answer
# JavaScript - 168 129 119 113 111 108

```
F=n=>{for(;~n;n--){r='';for(c of""+n)r=(c-6?c-9?c:6:9)+r;console.log(r-n&&!/[1-57]/.test(r)&&n%10?n+".":n)}}

```

> 4 5 6. 8 9. 16 60 66. 68. 69 906 909. 6090 9806. 9886 9889.

Or readable version:

```
F=n=>{for(;~n;n--){
    r='';for(c of ""+n)r=(c-6?c-9?c:6:9)+r; // rotate
    console.log( // output, new-line is added
        // original number, and
        // append dot only if number is different than its rotated version and no un-rotatable digit is present and there is no zero at the end
        r-n && !/[1-57]/.test(r) && n%10
           ?n+".":n
    )}}

```

I am not very happy with the regex, any ideas?

**Edit**: Learned neat trick with `~` and `for (... of ...)` from @edc65
**Edit2**: Reorganized conditions
**Edit3**: applied suggestions by @edc65
> 1 votes

# Answer
# 05AB1E, ~~38~~ ~~37~~ ~~30~~ 29 bytes

```
ÝεÐSUT%ĀiŽR!XåPiÐ69Â‡RÊi'.«]»

```

Try it online.

**Explanation:**

```
Ý                # Inclusive 0-based range: [0, (implicit) input]
 ε               # Map each integer to:
  Ð              #  Triplicate the current integer
  SU             #  Convert it to a list of digits, and pop and store it in variable `X`
    T%Āi         #  If the current integer contains no trailing zeros
    ŽR!XåPi      #  And if the current integer only consists of the digits [0689]
    Ð69Â‡RÊi     #  And if the current integer is not the same when its 6s and 9s
                 #  are swapped and then the total is reversed
             '.« #   Concat a '.'
                 #  Implicit else: use the top of the stack (the duplicate current integer)
]                # Close all three ifs and the map
 »               # Join the resulting list by newlines (and output implicitly)

```

Additional explanation for some parts:

```
T%Āi       # Check if the integer contains no trailing zeros:
T          #  Push 10 (T is a builtin for 10)
 %         #  Modulo
  Ā        #  Trutified: 0 remains 0 (falsey), everything else becomes 1 (truthy)
           #   i.e. 12 % 10 → 2 → 1 (truthy)
           #   i.e. 68 % 10 → 8 → 1 (truthy)
           #   i.e. 70 % 10 → 0 → 0 (falsey) (70 remains as is)
           #   i.e. 609 % 10 → 9 → 1 (truthy)
           #   i.e. 808 % 10 → 8 → 1 (truthy)

ŽR!XåPi    # Check if the integer only consists of the digits 0, 6, 8 and/or 9:
ŽR!        #  Push 6890 (Ž is a builtin for 2-char compressed integers, where R! is 6890)
   X       #  Push variable `X` (the list of digits)
    å      #  Check for each of these digits if they're in "6890"
     P     #  Take the product of that list
           #   i.e. [1,2] → [0,0] → 0 (falsey) (12 remains as is)
           #   i.e. [6,8] → [1,1] → 1 (truthy)
           #   i.e. [6,0,9] → [1,1,1] → 1 (truthy)
           #   i.e. [8,0,8] → [1,1,1] → 1 (truthy)

Ð69Â‡RÊi   # Check if the integer with 6s and 9s swapped and then reversed isn't unchanged:
Ð          #  Triplicate the integer
 69        #  Push 69
   Â       #  Bifurcate (short for Duplicate & Reverse)
    ‡      #  Transliterate (in `a` replace all characters `b` with characters `c`)
     R     #  Reverse
      Ê    #  Check for inequality
           #   i.e. 68 → "68" → "98" → "89" → 68 != "89" → 1 (truthy) (68 becomes "68.")
           #   i.e. 609 → "609" → "906" → "609" → 609 != "609" → 0 (falsey) (609 remains as is)
           #   i.e. 808 → "808" → "808" → "808" → 808 != "808" → 0 (falsey) (808 remains as is)

```
> 1 votes

# Answer
# Perl - 84

```
for(0..$ARGV[0]){s/6/x/g;s/9/6/g;s/x/9/g;printf"$_%s\n",$_=~/^[0689]+[689]$/?".":""}

```
> 0 votes

# Answer
# Powershell, ~~111~~ 102 bytes

```
param($s)$s+'.'*!($s-match'[1-57]|0$|'+-join$(switch -r($s[($s.Length-1)..0]){'0|8'{$_}'6'{9}'9'{6}}))

```

Explained test script:

```
$f = {

param($s)           # input string
$l=$s.Length        # length of the string
$c=$s[($l-1)..0]    # chars of the string in the reversed order
$d=switch -r($c){   # do switch with regex cases for each char
    '0|8'{$_}       # returns the current char if it equal to 8 or 0
    '6'{9}          # returns 9 if the current char is 6
    '9'{6}          # returns 6 if the current char is 9
}                   # returns array of new chars (contains 0,6,8,9 only)
$s+'.'*!(            # returns s. Add '.' if not...
    $s-match'[1-57]|0$|'+-join$d
                    # $s contains chars 1,2,3,4,5,7 or
                    # ends with 0 or
                    # equal to string of $d
)

}

@(
    ,('2'    ,'2'   )
    ,('4'    ,'4'   )
    ,('5'    ,'5'   )
    ,('6.'   ,'6'   )
    ,('7'    ,'7'   )
    ,('9.'   ,'9'   )
    ,('16'   ,'16'  )
    ,('60'   ,'60'  )
    ,('66.'  ,'66'  )
    ,('68.'  ,'68'  )
    ,('69'   ,'69'  )
    ,('906'  ,'906' )
    ,('909.' ,'909' )
    ,('8088.','8088')
    ,('9806.','9806')
    ,('9886' ,'9886')
    ,('9889.','9889')
) | % {
    $e,$s = $_
    $r = &$f $s
    "$($r-in$e): $r"
}

```

Output:

```
True: 2
True: 4
True: 5
True: 6.
True: 7
True: 9.
True: 16
True: 60
True: 66.
True: 68.
True: 69
True: 906
True: 909.
True: 8088.
True: 9806.
True: 9886
True: 9889.

```
> 0 votes

# Answer
# Stax, 27 bytes

```
Ç▒≈♣▌╬"÷╜─B↓«âpø←╚S☼ì>♫è;&╛

```

Run and debug it

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

```
0p      print 0 with no line break
F       for each [1 .. n] execute the rest of the program, where n is the input
  zP    print a newline
  q     peek and print the iterating variable without newline
  A%!C  modulo 10, and cancel iteration if zero (this cancels for multiples of 10)
  _$cc  convert iterating value to string and duplicate it twice on the stack
  7R6-$ construct the string "123457"
  |&C   if the character intersection is truthy, cancel the iteration
  r     reverse string
  69$:t map 6 and 9 characters to each other
  =C    if this rotated string is equal to the original, cancel iteration
        print "." with no newline
        (this comment precedes the instruction because it's an unterminated literal)
  ".

```

Run this one
> 0 votes

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