title: Finding My Favorite Times

text:
# Question
Title: Finding My Favorite Times
I really like times that follow certain patterns. In particular, I like times where all the digits are the same, or all of the digits increase arithmetically by one from left to right. Further, I viscerally hate when people put letters in my times, so all of that AM/PM nonsense is dead to me. Thus, my favorite times are:

```
0000 0123 1111 1234 2222 2345

```

For my peace of mind, I need you to write me a single program that, given the current time as input, both: **(A)** if it is ***not*** now one of my favorite times, tells me both (i) how many minutes it's been since my last favorite time as well as (ii) how many minutes from now my next favorite time will occur; and **(B)** if it ***is*** now one of my favorite times, supplies a single 'signal value'.

### Input

Your program should accept (by whatever method: function argument, `stdin`, command line argument, etc.) the current time, in any of the following formats:

* A four-digit time as a string
* An integer that can be zero-padded on the left to make a four-digit time as a string
* A sequence of four (or fewer) integers, ordered such that the first integer in the sequence is the leftmost (significant) digit in the time input (e.g., `0951` could be validly represented as `[0, 9, 5, 1]` or `[9, 5, 1]`)

+ Representing `0000` as a zero-length sequence is acceptable

In the case of a string input, it should ***only*** contain digits, no colons or other punctuation. **Inputs can be assumed to always be valid 24-hour times:** `HHMM`, where `0 <= HH <= 23` and `0 <= MM <= 59`. Disregard the possibility of a leap second.

### Output

Your program must supply (function returns, `stdout`, etc. are all fine) either **(A)** or **(B)**, as appropriate to whether or not the input value is a target time.

**For (A):**

Supply two numeric values in any sensible format, such as:

* Single-string output with a suitable delimiter
* Sequential integer/string outputs, e.g., `bash` printing two lines to `stdout`:

```
49
34

```
* Length-two ordered return values, such as a Python list, a C array, etc.: `[49, 34]`

The values can come in either order. For example, both of the following would be valid outputs for an input of `1200`:

```
49 34
34 49

```

*The order and separator must be the same for all input values, however!*

**For (B):**

Produce any otherwise unattainable result. The *same* result must be produced for all six of the target times, however. Infinite loops are excluded.

### Sample Inputs/Outputs

`YAY!!!` is used here as a demonstrative example and is not prescriptive.

```
Input      Output
------    --------
 0000      YAY!!!
 0020      20 63
 0105      65 18
 0122      82 1
 0123      YAY!!!
 0124      1 587
 0852      449 139
 1111      YAY!!!
 1113      2 81
 1200      49 34
 1234      YAY!!!
 1357      83 505
 1759      325 263
 1800      326 262
 1801      327 261
 2222      YAY!!!
 2244      22 61
 2345      YAY!!!
 2351      6 9

```

This is , so shortest code in bytes wins. Standard loopholes are disallowed.

# Answer
# Jelly, ~~34~~ ~~33~~ ~~32~~ ~~31~~ 28 bytes

*3 bytes thanks to Mr. Xcoder's `.ị` and `³` tricks.*

```
d³ḅ60;15j83,588ṁ5¤_\ṠÞAµ.ịxẠ

```

Try it online!

Some parts are exactly as in Jonathan Allan's answer, but I'm posting it as I think it is sufficiently different from it and independently written based on my Pyth answer (and shorter :D). Should also have room for improvement.

Input is an integer, output is an array of previous and next times or the empty array for special times.

### Explanation

Using example input `1200`.

* converts the time to base 100, into hours and minutes: `[12,0]`.
* `ḅ60` converts from base 60 to get total minutes: `720`.
* `;15` pairs it with 15: `[720, 15]`.
* `83,588` creates the array `[83, 588]`.
* `ṁ5` makes it length 5: `[83, 588, 83, 588, 83]`.
* `¤` combines the two above actions. Just a technicality.
* `j` joins the pair with the array: `[720, 83, 588, 83, 588, 83, 15]`.
* `_\` subtracts each array value from the first and gets intermediate results: `[720, 637, 49, -34, -622, -705, -720]`.
* `ṠÞ` *stably* sorts these by signum: `[-34, -622, -705, -720, 720, 637, 49]`.
* `A` takes the absolute values: `[34, 622, 705, 720, 720, 637, 49]`.
* `µ` starts a new monadic chain. Again, a technicality.
* `.ị` takes the last and first items: `[49, 34]`.
* `×Ạ` repeats that once if there are no zeroes, or zero times otherwise: `[49, 34]`.
> 2 votes

# Answer
# JavaScript (ES6), ~~87~~ 83 bytes

*Saved 4 bytes thanks to @l4m2*

Takes input as a string. Returns either `0` or a 2-element array.

```
t=>[i=0,83,588,83,588,83,15].every(d=>(k=t-(t/25>>2)*40)>(j=i,i+=d))|i-k&&[k-j,i-k]

```

### Test cases

```
let f =

t=>[i=0,83,588,83,588,83,15].every(d=>(k=t-(t/25>>2)*40)>(j=i,i+=d))|i-k&&[k-j,i-k]

console.log(f('0000')) // YAY!!!
console.log(f('0020')) // 20 63
console.log(f('0105')) // 65 18
console.log(f('0122')) // 82 1
console.log(f('0123')) // YAY!!!
console.log(f('0124')) // 1 587
console.log(f('0852')) // 449 139
console.log(f('1111')) // YAY!!!
console.log(f('1113')) // 2 81
console.log(f('1200')) // 49 34
console.log(f('1234')) // YAY!!!
console.log(f('1357')) // 83 505
console.log(f('1759')) // 325 263
console.log(f('1800')) // 326 262
console.log(f('1801')) // 327 261
console.log(f('2222')) // YAY!!!
console.log(f('2244')) // 22 61
console.log(f('2345')) // YAY!!!
console.log(f('2351')) // 6 9
```

### How?

We do not care about the result of the `.every()` loop. Provided that the input is valid, it will *always* be falsy. What we're really interested in is *when* we exit this loop.

We exit as soon as we find a favorite time `i` (expressed in minutes) which is greater than or equal to the reference time `k` (the input time `t` converted in minutes). We then return `0` if `i == k` or the 2 delays otherwise.
> 2 votes

# Answer
# Befunge-93, ~~88~~ ~~85~~ ~~86~~ ~~80~~ 74 bytes

```
&:"d"/58**-:"S"-:"b"6*-:"S"v
@._v#!:<\-*53:-"S":-*6"b":-<
:$#<$$\^@.._\#`0

```

Try it online!

Outputs the number of minutes since the last favourite time, followed by the number of minutes until the next favourite time (separated by the two character sequence: space, hyphen). If it is already a favourite time, then a single zero is returned.
> 2 votes

# Answer
# Jelly,  ~~33 32~~  34 bytes

~~+3~~  +2 bytes to fix up so all liked time outputs are equal.

gotta be a shorter way!

```
s2Ḍḅ60
83,588ṁ5“¡Ð‘j+\ṡ2>E¥ÞÇḢạÇa\

```

A monadic link taking a list of the four digits and returning a list containing two integers
\- if it's a liked time the result both entries will be zeros.

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

### How?

```
s2Ḍḅ60 - helper link, getMinuteOfDay: list of digits, D   e.g. [1,2,3,3]
 2     - literal two                                           2
s      - split into chunks of length                           [[1,2],[3,3]]
  Ḍ    - un-decimal (convert from base 10) (vectorises)        [12,33]
    60 - literal sixty                                         60
   ḅ   - un-base (convert from base)                           753

83,588ṁ5“¡Ð‘j+\ṡ2>E¥ÞÇḢạÇa\ - Link: list of digits        e.g. [1,2,3,3]
83,588                      - literal list of integers         [83,588]
       5                    - literal five                     5
      ṁ                     - mould like (implicit range of) [83,588,83,588,83]
        “¡Ð‘                - code-page index list             [0,15]
            j               - join                           [0,83,588,83,588,83,15]
              \             - cumulative reduce with:
             +              -   addition                     [0,83,671,754,1342,1425,1440]
                2           - literal two                      2
               ṡ            - overlapping slices of length     [[0,83],[83,671],[671,754],[754,1342],[1342,1425],[1425,1440]]
                     Ç      - last link (1) as a monad f(D)    753
                    Þ       - sort by:
                   ¥        -   last two links as a dyad:
                 >          -     greater than? (vectorises)    [0, 0] [ 0,  0] [  0,  1] [  1,   1] [   1,   1] [   1,   1]
                  E         -     equal?                          1       1         0         1           1           1
                            -                             -->  [[671,754],[0,83],[83,671],[754,1342],[1342,1425],[1425,1440]]
                      Ḣ     - head                             [671,754]
                        Ç   - last link (1) as a monad f(D)    753
                       ạ    - absolute difference (vectorises) [ 82,  1]
                          \ - cumulative reduce with:
                         a  -   AND                            [ 82,  1]
                            -   -- such that if "liked" then the [0,x] result becomes [0,0] so they are all equal

```
> 1 votes

# Answer
# C, 121 bytes

```
*p,l[]={0,83,671,754,1342,1425,1440};f(t){t=t%100+t/100*60;for(p=l;t>*p;++p);*p-t?printf("%d %d",t-p[-1],*p-t):puts("");}

```

Outputs a newline if the time is a favourite time.

Try it online!
> 1 votes

# Answer
# Pyth, ~~48~~ ~~45~~ 42 bytes

```
&*FJ.u-NY+P*3,83 588 15isMcz2 60,eK._DJ_hK

```

Try it online. Test suite.

The code takes in a time string and outputs the previous and next times as an array, or `0` if the time is special.

Interestingly, an imperative approach is also 42 bytes:

```
V+_isMcz2 60+P*3,83 588 15KZIg0=-ZNIZK)_ZB

```

### Explanation

* `cz2` splits input (`z`) into two-character pieces.
* `sM` evaluates them as integers.
* `i``60` parses the resulting two-item array as base 60.
* `,83 588` represents the array `[83, 588]`.
* `*3` triplicates that to `[83, 588, 83, 588, 83, 588]`.
* `P` removes the last `588`.
* `+``15` adds `15` to the end.
* `.u-NY` starts from the parsed number, subtracts each number in the array from it and returns the intermediate values. These are the differences from each special time.
* `J` assigns these differences to `J`.
* `*F` computes the product of the differences. This will be 0 if the time was special.
* `&` stops the evaluation here and returns 0 if the time was special.
* `._DJ` stable-sorts the differences by sign.
* `K` saves that array in `K`.
* `e` takes the last item in the array.
* `_hK` takes the first item in the array and negates it.
* `,` returns the two as an array.
> 1 votes

# Answer
# Clean, 126 bytes

```
import StdEnv
f=[1440,1425,1342,754,671,83,0]
?t#t=t rem 100+t/100*60
=(\(a,b)=(t-hd b,last a-t))(span(\a=t<a||isMember t f)f)

```

Defines the function `?`, taking `Int` and returning `(Int, Int)`.
When the argument is a favourite time, it crashes the calling program with `hd of []`.

Try it online!
> 1 votes

# Answer
# Husk, 36 bytes

```
?↑2↑0Πṙ_1†aÖ±↔Ġ-::15t*3e588 83B60†d½

```

Try it online!

Thanks to Zgarb for explaining me how ternaries work in chat. Trying to golf `↑0`, but I didn't get it to work otherwise for some reason (?). This is my first non-trivial Husk answer, and letting the aforementioned aside, I am pretty satisfied with it. The value used instead of `YAY!!!` is `[]` (but I hope that will change for golfing purposes).

### Explanation

```
?↑2↑0Πṙ_1†aÖ±↔Ġ-::15t*3e588 83B60†d½ | Input as a digit list from CLA, output to STDOUT.

                                   ½ | Split the list into two halves.
                                 †d  | Turn each half into a base-10 integer.
                              B60    | Convert from base 60.
                :                    | Append the above to ↓ ([15, 83, 588, 83, 588, 83]).
                       e588 83       | Create the two element list [588, 83].
                     *3              | Repeat three times.
                    t                | Remove the first element.
                 :15                 | Prepend a 15.
              Ġ-                     | Apply cumulative subtraction from the right.
             ↔                       | Reverse.
           Ö±                        | Stable sort by the sign (-1, 0 or 1).
         †a                          | Map absolute value.
      ṙ_1                            | Rotate one right.
?    Π                               | If the product is truthy, then:
 ↑2                                  | Take the first two elements.
   ↑0                                | Return an empty list otherwise.

```
> 1 votes

# Answer
# Kotlin, 293 bytes

```
{fun i(l:List<Int>)=l.all{it==l[0]}|| l.mapIndexed{a,b->b-a}.all{it==l[0]}
val a=(0..1439+0).map{val h=it/60
val m=it%60
listOf(h/10,h%10,m/10,m%10)}+listOf(listOf(0,0,0,0))
val s=a.indexOf(it)
if(i(it))0 to 0 else
s-a.subList(0,s).indexOfLast{i(it)}to a.subList(s,a.size).indexOfFirst{i(it)}}

```

## Beautified

```
{
    fun i(l:List<Int>)=l.all { it ==l[0] } || l.mapIndexed { a, b -> b - a }.all { it ==l[0] }
    val a = (0..1439 + 0).map {
        val h = it/60
        val m = it%60
        listOf(h/10,h%10,m/10,m%10)
    } + listOf(listOf(0,0,0,0))
    val s = a.indexOf(it)
    if (i(it)) 0 to 0 else
        s - a.subList(0, s).indexOfLast {i(it)} to a.subList(s, a.size).indexOfFirst {i(it)}
}

```

## Test

```
var t:(i:List<Int>)-> Pair<Int, Int> =
{fun i(l:List<Int>)=l.all{it==l[0]}|| l.mapIndexed{a,b->b-a}.all{it==l[0]}
val a=(0..1439+0).map{val h=it/60
val m=it%60
listOf(h/10,h%10,m/10,m%10)}+listOf(listOf(0,0,0,0))
val s=a.indexOf(it)
if(i(it))0 to 0 else
s-a.subList(0,s).indexOfLast{i(it)}to a.subList(s,a.size).indexOfFirst{i(it)}}

data class Test(val input: List<Int>, val output: Pair<Int, Int>)

val TEST = listOf(
    Test(listOf(0,0,0,0), 0 to 0),
    Test(listOf(0,0,2,0), 20 to 63),
    Test(listOf(0,1,0,5), 65 to 18),
    Test(listOf(0,1,2,2), 82 to 1),
    Test(listOf(0,1,2,3), 0 to 0),
    Test(listOf(0,1,2,4), 1 to 587),
    Test(listOf(0,8,5,2), 449 to 139),
    Test(listOf(1,1,1,1), 0 to 0),
    Test(listOf(1,1,1,3), 2 to 81),
    Test(listOf(1,2,0,0), 49 to 34),
    Test(listOf(1,2,3,4), 0 to 0),
    Test(listOf(1,3,5,7), 83 to 505),
    Test(listOf(1,7,5,9), 325 to 263),
    Test(listOf(1,8,0,0), 326 to 262),
    Test(listOf(1,8,0,1), 327 to 261),
    Test(listOf(2,2,2,2), 0 to 0),
    Test(listOf(2,2,4,4), 22 to 61),
    Test(listOf(2,3,4,5), 0 to 0),
    Test(listOf(2,3,5,1), 6 to 9)
)

fun main(args: Array<String>) {
    for (t in TEST) {
        val v = t(t.input)
        if (v != t.output) {
            throw AssertionError("$t $v")
        }
    }
}

```

## TIO

TryItOnline
> 1 votes

---
Tags: code-golf, date
---


title: Balanced ternary logic

text:
# Question
Title: Balanced ternary logic
## Balanced ternary logic

Ternary is normally another name for base 3, that is to say, each digit is `0`, `1`, or `2`, and each place is worth 3 times as much as the next place.

Balanced ternary is a modification of ternary which uses digits of `-1`, `0` and `1`. This has the advantage of not needing a sign. Each place is still worth 3 times as much as the next place. The first few positive integers are therefore `[1]`, `[1, -1]`, `[1, 0]`, `[1, 1]`, `[1, -1, -1]` while the first few negative integers are `[-1]`, `[-1, 1]`, `[-1, 0]`, `[-1, -1]`, `[-1, 1, 1]`.

You have three inputs `x, y, z`. `z` is either `-1`, `0`, or `1`, while `x` and `y` can be from `-3812798742493` to `3812798742493` inclusive.

The first step is to convert `x` and `y` from decimal to balanced ternary. This should give you 27 trits (TeRnary digITS). You then have to combine the trits from `x` and `y` in pairs using a ternary operation and then convert the result back to decimal.

You can choose which values of `z` map to one of these three ternary operations each:

* `A`: Given two trits, if either is zero, then the result is zero, otherwise the result is -1 if they are different or 1 if they are the same.
* `B`: Given two trits, if either is zero, then the result is the other trit, otherwise the result is zero if they are different or the negation if they are the same.
* `C`: Given two trits, the result is zero if they are different or their value if they are the same.

Example. Suppose `x` is `29` and `y` is `15`. In balanced ternary, these become `[1, 0, 1, -1]` and `[1, -1, -1, 0]`. (The remaining 23 zero trits have been omitted for brevity.) After each of the respective operations they become `A`: `[1, 0, -1, 0]`, `B`: `[-1, -1, 0, -1]`, `C`: `[1, 0, 0, 0]`. Converted back to decimal the results are `24`, `-37` and `27` respectively. Try the following reference implementation for more examples:

```
function reference(xd, yd, zd) {
    var rd = 0;
    var p3 = 1;
    for (var i = 0; i < 27; i++) {
        var x3 = 0;
        if (xd % 3 == 1) {
            x3 = 1;
            xd--;
        } else if (xd % 3) {
            x3 = -1;
            xd++;
        }
        var y3 = 0;
        if (yd % 3 == 1) {
            y3 = 1;
            yd--;
        } else if (yd % 3) {
            y3 = -1;
            yd++;
        }
        var r3 = 0;
        if (zd < 0) { // option A
            if (x3 && y3) r3 = x3 == y3 ? 1 : -1;
        } else if (zd > 0) { // option B
            if (!x3) r3 = y3;
            else if (!y3) r3 = x3;
            else r3 = x3 == y3 ? -x3 : 0;
        } else { // option C
            r3 = x3 == y3 ? x3 : 0;
        }
        rd += r3 * p3;
        p3 *= 3;
        xd /= 3;
        yd /= 3;
    }
    return rd;
}
```

```
<div onchange=r.textContent=reference(+x.value,+y.value,+z.selectedOptions[0].value)><input type=number id=x><input type=number id=y><select id=z><option value=-1>A</option><option value=1>B</option><option value=0>C</option><select><pre id=r>
```

The reference implementation follows the steps given above but you are of course free to use any algorithm that produces the same results.

This is , so the shortest program or function that violates no standard loopholes wins!

# Answer
> 2 votes
# Clean, ~~231~~ ... 162 bytes

```
import StdEnv
$n=tl(foldr(\p[t:s]#d=sign(2*t/3^p)
=[t-d*3^p,d:s])[n][0..26])
@x y z=sum[3^p*[(a+b)/2,[1,-1,0,1,-1]!!(a+b+2),a*b]!!(z+1)\\a<- $x&b<- $y&p<-[0..26]]

```

Defines the function `@`, taking three `Int`s and giving an `Int`.
Operators map as `1 -> A, 0 -> B, -1 -> C`.

Try it online!

The function `$` folds a lambda over the digit places `[0..26]`, into a list of ternary digits. It uses the head of the list it yields to keep a current total difference from the requisite number (which is why it is tailed prior to returning), and `sign(2*t/3^p)` to determine the current digit to yield. The sign trick is equivalent to `if(abs(2*t)<3^p)0(sign t)`.

# Answer
> 1 votes
# , ~~190~~ ~~172~~ 151 bytes

```
function(a,b,z){M=t(t(expand.grid(rep(list(-1:1),27))))
P=3^(26:0)
x=M[M%*%P==a,]
y=M[M%*%P==b,]
k=sign(x+y)
switch(z+2,x*y,k*(-1)^(x+y+1),k*!x-y)%*%P}

```

Try it online!

Computes all combinations of trits and selects the right one. It'll actually throw a memory error with `27`, since `3^27` is a somewhat large number, but it would in theory work. The TIO link has only `11` trit integer support; I'm not sure at what point it times out or memory errors first, and I don't want Dennis to get mad at me for abusing TIO!

## old answer, 170 bytes

This one should work for all inputs, although with only 32-bit integers, there's the possibility of imprecision as R will automatically convert them to `double`.

```
function(a,b,z){x=y={}
for(i in 0:26){x=c((D=c(0,1,-1))[a%%3+1],x)
y=c(D[b%%3+1],y)
a=(a+1)%/%3
b=(b+1)%/%3}
k=sign(x+y)
switch(z+2,x*y,k*(-1)^(x+y+1),k*!x-y)%*%3^(26:0)}

```

Try it online!

Takes `-1` for `A`, `0` for `B`, and `1` for `C`.

Ports the approach in this answer for converting to balanced ternary, although since we're guaranteed to have no more than 27 balanced trits, it's optimized for that.

# , 160 bytes

```
function(a,b,z){s=sample
x=y=rep(0,27)
P=3^(26:0)
while(x%*%P!=a&y%*%P!=b){x=s(-1:1,27,T)
y=s(-1:1,27,T)}
k=sign(x+y)
switch(z+2,x*y,k*(-1)^(x+y+1),k*!x-y)%*%P}

```

Try it online!

This version will terminate extremely slowly. The bogosort of base conversion, this function randomly picks trits until it somehow magically (`3^-54` chance of it occurring) finds the right trits for `a` and `b`, and then does the required operation. This will basically never finish.

# Answer
> 1 votes
# Jelly, 39 bytes

```
×=
×
+ị1,-,0
A-r1¤ṗœs2ṚẎị@ȯµ€Uz0ZU⁹ŀ/ḅ3

```

A full program taking two arguments, `[x,y]`, and `z`
...where `z` is `{A:-1, B:0, C:1}`
which prints the result

**Try it online!** Note: the golfed method makes it slow - this altered version is faster (logs by 3, ceils and increments prior to each Cartesian product)

### How?

```
×=       - Link  1 (1), B: list of trits L, list of trits R
×        - L multiplied by... (vectorises):
 =       -   L equal R? (vectorises)

×        - Link -1 (2), A: list of trits L, list of trits R
×        - L multiplied by R (vectorises)

+ị1,-,0  - Link  0 (3), C: list of trits L, list of trits R
+        - L plus R (vectorises)
  1,-,0  - list of integers = [1,-1,0]
 ị       - index into (vectorises) - 1-based & modular, so index -2 is equivalent to
         -                           index 1 which holds the value 1.

A-r1¤ṗœs2ṚẎị@ȯµ€Uz0ZU⁹ŀ/ḅ3 - Main link: list of integers [X,Y], integer Z
              µ€           - for each V in [X,Y]:
A                          -   absolute value = abs(V)
    ¤                      -   nilad followed by link(s) as a nilad:
 -                         -     literal minus one
   1                       -     literal one
  r                        -     inclusive range = [-1,0,1]
     ṗ                     -   Cartesian power, e.g. if abs(V)=3: [[-1,-1,-1],[-1,-1,0],[-1,-1,1],[-1,0,-1],[-1,0,0],[-1,0,1],[-1,1,-1],[-1,1,0],[-1,1,1],[0,-1,-1],[0,-1,0],[0,-1,1],[0,0,-1],[0,0,0],[0,0,1],[0,1,-1],[0,1,0],[0,1,1],[1,-1,-1],[1,-1,0],[1,-1,1],[1,0,-1],[1,0,0],[1,0,1],[1,1,-1],[1,1,0],[1,1,1]]
                           -                   (corresponding to: [-13       ,-12      ,-11      ,-10      ,-9      ,-8      ,-7       ,-6      ,-5      ,-4       ,-3      ,-2      ,-1      ,0      ,1      ,2       ,3      ,4      ,5        ,6       ,7       ,8       ,9      ,10      ,11     ,12     ,13     ] )
        2                  -   literal two
      œs                   -   split into equal chunks           [[[-1,-1,-1],[-1,-1,0],[-1,-1,1],[-1,0,-1],[-1,0,0],[-1,0,1],[-1,1,-1],[-1,1,0],[-1,1,1],[0,-1,-1],[0,-1,0],[0,-1,1],[0,0,-1],[0,0,0]],[[0,0,1],[0,1,-1],[0,1,0],[0,1,1],[1,-1,-1],[1,-1,0],[1,-1,1],[1,0,-1],[1,0,0],[1,0,1],[1,1,-1],[1,1,0],[1,1,1]]]
         Ṛ                 -   reverse                           [[[0,0,1],[0,1,-1],[0,1,0],[0,1,1],[1,-1,-1],[1,-1,0],[1,-1,1],[1,0,-1],[1,0,0],[1,0,1],[1,1,-1],[1,1,0],[1,1,1]],[[-1,-1,-1],[-1,-1,0],[-1,-1,1],[-1,0,-1],[-1,0,0],[-1,0,1],[-1,1,-1],[-1,1,0],[-1,1,1],[0,-1,-1],[0,-1,0],[0,-1,1],[0,0,-1],[0,0,0]]]
          Ẏ                -   tighten                            [[0,0,1],[0,1,-1],[0,1,0],[0,1,1],[1,-1,-1],[1,-1,0],[1,-1,1],[1,0,-1],[1,0,0],[1,0,1],[1,1,-1],[1,1,0],[1,1,1],[-1,-1,-1],[-1,-1,0],[-1,-1,1],[-1,0,-1],[-1,0,0],[-1,0,1],[-1,1,-1],[-1,1,0],[-1,1,1],[0,-1,-1],[0,-1,0],[0,-1,1],[0,0,-1],[0,0,0]]
                           -                   (corresponding to: [1      ,2       ,3      ,4      ,5        ,6       ,7       ,8       ,9      ,10     ,11      ,12     ,13     ,-13       ,-12      ,-11      ,-10      ,-9      ,-8      ,-7       ,-6      ,-5      ,-4       ,-3      ,-2      ,-1      ,0      ] )
           ị@              -   get item at index V (1-based & modular)
             ȯ             -   logical OR with V (just handle V=0 which has an empty list)
                U          - upend (big-endian -> little-endian for each)
                  0        - literal zero           }
                 z         - transpose with filler  } - pad with MSB zeros
                   Z       - transpose              }
                    U      - upend (little-endian -> big-endian for each)
                       /   - reduce with:
                      ŀ    -   link number: (as a dyad)
                     ⁹     -     chain's right argument, Z
                         3 - literal three
                        ḅ  - convert from base

```

# Answer
> 0 votes
# Jelly, 47 bytes

```
×=
×
N0⁼?ȯȧ?"
ḃ3%3’
0Çḅ3$$⁼¥1#ḢÇṚµ€z0Z⁹+2¤ŀ/Ṛḅ3

```

Try it online!

Full program.

`-1` = `C`, `0` = `A`, `1` = `B`

Argument 1: `[x, y]`
Argument 3: `z`

---
Tags: code-golf, integer, base-conversion
---


title: Have I had lunch yet?

text:
# Question
Title: Have I had lunch yet?
You love lunch. However, you are on a diet and want to make sure you don't accidentally eat lunch twice in one day. So you need to make a program to help you make sure.

However, one complication is that you eat lunch on a very weird schedule. The time you eat lunch at is **MONTH:DAY PM** (you can use UTC or localized time zone). That's right, if the day is **July 14**, you eat lunch at **7:14 PM**.

For your program, you need to use the current date and time (don't take input), and output a consistent truthy value if you have already eaten lunch for the day (or it is lunch time now), or a consistent falsy value if you haven't.

**Examples:** (Time you run program =\> output)

* May 4th 11:35 AM =\> false (you will eat lunch at 5:04 PM)
* June 3rd 5:45 PM =\> false (you will eat lunch at 6:03 PM)
* July 28th 8:30 PM =\> true (you ate lunch at 7:28 PM)
* December 15th 3:25 PM =\> true (you ate lunch at 12:15 PM)
* February 29th 2:29 PM =\> true (it is exactly lunch time)
* October 12th 12:00 AM =\> false (day just started)

**Reference:**

How a 12 hour clock works

# Answer
> 7 votes
# Swift 3, 310 bytes

```
import Foundation;var n=String(describing:Date());var k=n.startIndex;print(Int(n[n.index(k,offsetBy:5)...n.index(k,offsetBy:6)])!*60+Int(n[n.index(k,offsetBy:8)...n.index(k,offsetBy:9)])!+720<=Int(n[n.index(k,offsetBy:11)...n.index(k,offsetBy:12)])!*60+Int(n[n.index(k,offsetBy:14)...n.index(k,offsetBy:15)])!)

```

Check it out!

This prints `true` and `false`, for truthy and falsy respectively.

> **NOTE**: This only works until the year 9999, at 11:59:59 PM, because it uses Strings to compare the dates.

# Answer
> 3 votes
# 05AB1E, ~~15~~ 18 bytes

```
žežb‚žf12+ža‚т*+`‹

```

Try it online!

### Explanation

```
žežb‚žf12+ža‚т*+`‹
že                 # Push current day
  žb               # Push current minute
    ‚              # Wrap to array
     žf12+         # Push current month and add 12 to it
       ža          # Push current hour
         ‚         # Wrap these two to array as well
          т*       # Multiply each element in the second array by 100
            +      # Add both arrays together
             `     # Flatten the resulting array to stack
              ‹    # Is the first item smaller than the second one?

```

# Answer
> 2 votes
# Octave, 61 bytes

```
diff(str2num([(d=datestr(now,'mmddHHMM'))(1:4);d(5:8)]))>1200

```

Try it online!

### Explanation:

First the functions:

* `now()` returns the time on a decimal format. The parentheses are optional.
* `datestr` converts a decimal number to a string on the format given in its second argument
* `str2num` converts a string to a number
* `diff` takes the difference between two numbers

### Breakdown:

We take this from the middle:

```
diff(str2num([(d=datestr(now,'mmddHHMM'))(1:4);d(5:8)]))>1200

```

**`datestr(now,'mmddHHMM')`**: First we take the current time `now` as input to `datestr` and specifies the format `mmddHHMM`. The letters mean: `mm = month`, `dd = day`, `HH = hour`, `MM = minutes` and `AM` specifies that the hours should be on a 12-hour format. No separators are included, to keep it as short as possible. It outputs `d = 07142117` on the time of writing this explanation. I'll refer to that part as `x` from now.

**`[(d=x)(1:4);d(5:8)]`**: Stores the string above, as `d`, then creates an array with two elements, the first four characters, then the 5-9 characters. This gives:

```
ans =
0714
2122

```

Where the numbers are stored as strings, not numbers. We'll call the result above for `y` below.

**`str2num(y)`** converts the array of characters to numbers, where each row turns into one number. This gives `[714; 2122]`. We'll call the result for `z`.

**`diff(z)>1200`** takes the difference between the two numbers and checks if the current time is 1200 higher than the current date. This accounts for AM/PM. This gives us the desired result.

# Answer
> 2 votes
# Pyth, ~~22~~ ~~21~~ 20 bytes

```
<0+g.d7.d5-.d6+12.d4

```

*-1 byte thanks to @Mr.Xcoder*

Try this!

## old approach, ~~22~~ 20 bytes

```
<+`+12.d4.d5+`.d6.d7

```

Try it!

## explanation

```
<0+g.d7.d5-.d6+12.d4
              +12.d4   # Add 12 to the current month to make it PM
          -.d6         # subtract that from the current hour: negative it is too early,
                       # positive when it is past this hour, zero when its the same hour
   g.d7.d5             # Is the minute greater or equal than the day? True=1; False=0
  +                    # Add this to the hour result,
                       # so that 0 can turn positive if minutes are true
<0                     # Is the result larger than 0 ?

```

# Answer
> 2 votes
# Haskell, 135 129 bytes

```
import Data.Time
x(ZonedTime(LocalTime d(TimeOfDay h m _))_)|(_,x,y)<-toGregorian d=return(mod x 12<h-12&&y<m)
y=getZonedTime>>=x

```

this unpacking is quite annoying, maybe string handling is better suited

//edit: pattern guards safe 5 bytes

# Answer
> 2 votes
# C#, 174 bytes

```
using System;public class Program{public static void Main(){Console.WriteLine(DateTime.Now>DateTime.Today.AddHours(DateTime.Today.Month+12).AddMinutes(DateTime.Today.Day));}}

```

Try it online!

# Answer
> 2 votes
# **PHP and other languages with these common functions: about 28 to 29 bytes:**

```
echo eval(date('Gi-1199>md'));

```

or alternatively

```
<?=eval(date('Gi-1199>md'))?>

```

both of which will print.

possibly with `?1:0` depending on representation. Possibly bytes cut if a language is used that has implicit echo, or no final ';'.

Why would one get the values into variables and all the rest, when it's not needed :)
`date()` leaves anything as literals that isn't defined, so for example, `7 May 2017 17:22:43` passes the expression `1722 - 1200 >= 507` to eval(). Byte saved by changing it to the equivalent `1722 - 1199 > 507`.

Who says eval is dead? ;-)

# Answer
> 2 votes
# Mathematica, ~~65~~ ~~64~~ 62 bytes

### 3 Programs

```
p=Date[][[#]]&;{60,1}.#&/@(p[4;;5]>=p[2;;3]+{12+p@2~Mod~12,0})

```

```
{60,1}.#&/@(#[[4;;5]]>=#[[2;;3]]+{12+#[[2]]~Mod~12,0})&@Date[]

```

```
{60,1}.#&/@(#[4;;5]>=#[2;;3]+{12+#@2~Mod~12,0})&[Date[][[#]]&]

```

These are each one byte less if  counts as a single byte in Mathematica.

### Explanations

1. `Date[]` returns a list in the form `{y,m,d,h,m,s}`. So `Date[][[4;;5]]` are the hours and minutes of the current time.
2. `p=Date[][[#]]&;` makes `p` a function that takes in the indices we want and gives us those parts of the date.
3. `{60,1}.#&` is an anonymous function that takes the dot product of `{60,1}` and the input to get a way to compare times. It's one byte shorter than `TimeObject`.
4. `p@2` is equivalent to `p[2]`, the number of the month.
5. `+{12+p@2~Mod~12,0}` adds `{12,0}` to the month and date when we're not in December, and adds `{0,0}` otherwise. (Thanks, michi7x7!)
6. `>=` is the comparison operator, but we can't compare {hours, minutes} to {adjusted month, date} entrywise...
7. `/@` maps `{60,1}.#&` to both sides of the inequality in parentheses, so we can compare times correctly.
8. For the programs that start with `{60,1}.#&`, they use `#` to represent the input to a big anonymous function, and `&` to signify the end.
9. `@Date[]` Applies the big function on its line (which extracts parts of a list) to the date list itself.
10. `[Date[][[#]]&]` Applies the big function on its line to another anonymous function, one which extracts parts of the date list.

### Bonus

As an aside, if we ate lunch between 1AM and 12:59PM, then we could save 25 bytes with just `{60,1}.#&[Date[][[#]]]&/@(4;;5>=2;;3)`.

You can test all of these out by pasting the code into the Wolfram Cloud sandbox and clicking Gear-\>Evaluate Cell or hitting Shift+Enter or Numpad Enter.

# Answer
> 2 votes
## Java, 81 bytes

```
n->new Date().after(new Date(){{setHours(getMonth()+13);setMinutes(getDate());}})

```

Try it online!

Ungolfed:

```
n -> new Date().after(new Date() { //new Date() returns current date
    { //instance initialization
        setHours(getMonth() + 13); //month + 12 hours for PM + 1 because months are 0 indexed
        setMinutes(getDate()());
    }
})

```

# Answer
> 1 votes
# q, 31 bytes

```
x>12:+"T"$(-3!x:.z.P)5 6 13 8 9

```

Example:

```
q).z.P
2017.07.16D19:35:26.654099000
q)x>12:+"T"$(-3!x:.z.P)5 6 13 8 9
1b

```

Interpreter is available here

Old version

```
{x:.z.p;x>"T"$":"sv"0"^2$/:string 12 0+`mm`dd$\:x}`

```

# Answer
> 1 votes
# Python 3, 104 bytes

```
from datetime import*
n=datetime.now();print(n>=n.replace(hour=[0,n.month+12][n.month<12],minute=n.day))

```

Try it online!

All datetime tests. I replaced Feb 29th with Feb 28th because the invalid date wasn't working.

# Answer
> 1 votes
# Python 2.7, 130 bytes

```
from datetime import*
a=str(datetime.now()).split()
print int(''.join(a[0].split('-')[1:]))+1200<int(''.join(a[1].split(':')[:2]))

```

Try it online

Note: There may be a problem with the sign. Please excuse that because I follow IST and it's quite confusing because it's 2:28am here now. Do correct the sign if you feel it is wrong.

# Answer
> 1 votes
## JavaScript (ES6), 75 bytes

```
f=
(d=new Date)=>(d.getHours()-d.getMonth()-13||d.getMinutes()-d.getDate())>=0
```

```
<input type=button value=Lunch? onclick=o.textContent=f()><tt id=o>
```

Those long function names...

# Answer
> 1 votes
# JavaScript, 75 bytes

```
t=new Date,t.setHours(13+t.getMonth()),t.setMinutes(t.getDate()),new Date>t

```

Which is equivalent to the following code:

```
function didEat()
  const d = new Date()
  d.setHours(12 /* PM */ + d.getMonth() + 1)
  d.setMinutes(d.getDate())
  return new Date > d
}
didEat()

```

# Answer
> 1 votes
# , 92 bytes

```
library(lubridate)
d=Sys.Date()
cat(Sys.time()>ymd_hm(paste0(d,'-',month(d)+12,'-',day(d))))

```

Try it online!

```
                                   month(d)+12,'-',day(d)    # get month and day and paste into a string, adding 12 hours for pm
                      paste0(d,'-',                      )   # add current date to beginning
               ymd_hm(                                    )  # turn whole thing into a date-time object
cat(Sys.time()>                                            ) # compare with current date-time and print

```

# Answer
> 1 votes
## Perl, 45 chars

```
sub c{@a=gmtime;$a[2]-12>$a[4]&&$a[1]>=$a[3]}

```

If I have to provide a method, it will be 45 for `sub c{...}`. If I have to print `say ()||0` even makes it 47. I will add that in if it's a requirement.

# Answer
> 1 votes
# Excel, ~~52~~ ~~50~~ 49 bytes

```
=TIME(MONTH(NOW())+12,DAY(NOW()),0)<=MOD(NOW(),1)

```

Input is this formula in any cell.
Output is either `TRUE` or `FALSE`.

Excel's built-in date handling helps a lot.
The `TIME` function returns the day's lunch time as a time value which, if converted to a date, would use `Jan 0, 1900`. We compare it against `NOW - TODAY` so we get the current time with a date value of `0` or `Jan 0, 1900`.

Saved 2 bytes thanks to Wernisch
Saved 1 byte thanks to Adam

# Answer
> 0 votes
# Excel VBA, 55 Bytes

Anonymous VBE immediate window function that takes no input and outputs a Boolean value representing whether I've had lunch to the VBE immediate window

```
n=Now:?TimeValue(n)>TimeValue(Month(n)&":"&Day(n)&"PM")

```

# Answer
> 0 votes
# JavaScript, 62 chars

```
f=
_=>[,m,d,H,M]=(new Date).toISOString().split(/\D/),+m+12+d<=H+M

```

Test code below:

```
console.log(( // May 4, 5:03 PM, false (1 minute before lunch)
  [,m,d,H,M]=(new Date("2017-05-04T17:03Z")).toISOString().split(/\D/),+m+12+d<=H+M
));

console.log(( // May 4, 5:04 PM, true (exact time)
  [,m,d,H,M]=(new Date("2017-05-04T17:04Z")).toISOString().split(/\D/),+m+12+d<=H+M
));

console.log(( // May 4, 5:05 PM, true (1 minute after)
  [,m,d,H,M]=(new Date("2017-05-04T17:05Z")).toISOString().split(/\D/),+m+12+d<=H+M
));
```

# Answer
> 0 votes
# Ruby, 64+7 = 71 bytes

Requires the `-rtime` flag because for some reason `Time::parse` is like, the only function requires it out of the entire `Time` module.

```
p Time.parse("#{t=Time.now}"[/.+-(..)-(..) /]+[$1,$2]*?:+'pm')<t

```

Try it online! (it also prints out the current time)

# Answer
> 0 votes
## Julia 0.6.0 99 bytes

`a=split(string(Dates.today()),"-");(Dates.hour(now())<parse(a[2]))&&Dates.minute(now())<parse(a[3])`

Julia has built in function to use the clock/calendar of the computer. My computer is running on ubuntu 16.04 and already with 12 hour clock, so I can't say if what I did works with other machine using different clock, but seems to works on my machine.

# Answer
> 0 votes
# Matlab, 241 bytes

```
dt=datestr(now,'mm/dd');
dt(2)
dt(4:5)
CrctLchTm=[' ' dt(2) ':' dt(4:5) ' PM']
CrntTm=datestr(now,'HH:MM PM')
CrntTm(7)=='A'
if ans==1
    Lch='false'
else
    CrctLchTm=str2num([CrctLchTm(2) CrctLchTm(4:5)])
    CrntTm=str2num([CrntTm(2) CrntTm(4:5)])
    CrntTm<CrctLchTm
    if ans==1
        Lch='false'
    else
        Lch='true'
    end
end

```

Explanation: First, I obtain the date as a string. Then, I isolate the month and day. Since the problem states that it is always interpreted as PM, then I automatically write false if the time is in AM. If the current time is in PM, then I continue on and just compare the numbers of the time.

Note: I've formatted it slightly differently here for readability.

# Answer
> 0 votes
# JavaScript ES6, 70 Bytes

```
_=>(h=x=>new Date().toJSON().substr(x,5).replace(/\D/,0))(5)+12e3<h(11)

```

Maybe not that right on some milliseconds...

---
Tags: code-golf, date
---


# Question
Title: Is this a valid game of Five Up (Dominoes)?
A set of dominoes consists of tiles with two numbers on them such that every combination of integers from 0 to N are represented. Examples below refer to N=6 out of convenience, but N=9 and N=12 are also common. The orientation of the tiles does not matter (they are usually printed with dots rather than digits), so `[1-6]` and `[6-1]` refer to the same tile, of which there is only one in a set.

Most games played with dominoes involve players taking turns adding dominoes to a line of those already played onto the table, such that one of the numbers on the new domino is placed adjacent to the same number at one end of the line on the table. Thus, you might add a `[2-5]` to either end of an existing line of `[2-3][3-3][3-5]`, producing `[5-2][2-3][3-3][3-5]` or `[2-3][3-3][3-5][5-2]`.

Many such games require "doubles", dominoes with two of the same number on them, to be placed perpendicular to the other dominoes connected to them. Aside from scoring which we are unconcerned with here, this has no effect except when...

Many of those games then allow the "line" to fork at some or all doubles. Five Up is such a game where the line can fork into 3 new lines at each double, so all four sides of a double might have a matching domino attached.

Here is an example layout of dominoes from a "double 6" set in a game of Five Up (where A|B or A-B is a single domino):

```
     4
     -
     0

3|0 0|0 0|2

     0
     -
     1

4|1 1|1 1|6
                3
     1          -
     -          6
     5
                6
6|5 5|5 5|0 0|6 - 6|2 2|1
                6
     5
     -          6
     4          -
                4

```

Your task is to take an list of dominoes in the order in which they were added to the table, and determine whether or not this order represents a legal game of Five Up.

You can write a whole program that takes input from stdin, or a function that takes input as one or more parameters.

Canonical input would be a list or array of two-tuples of integers. A list of lists, array of arrays, vector of tuples, etc are all valid forms in which to take input, as would be a string representing any of the above, or multiple strings. The input will only contain pairs of non-negative integers, valid dominoes.

Output should be a truthy or falsey value, for valid and invalid games respectively.

Your code should accept arbitrarily large domino numbers, within the capabilities of the maximum integer values of your language.

Examples:

* `0-6` is valid, as is any other single domino
* `0-6 6-0` is not valid, there is only one `0-6` domino in a set
* `6-6 6-5 5-3 3-0` is valid, a simple linear arrangement
* `6-6 6-5 3-0 5-3` is not valid, there is no `3` or `0` in play for the third domino to connect to prior to the `5-3` being played
* `1-1 1-2 1-3 1-4 1-5 1-6` is not valid, all four open `1` ends are used up leaving nowhere to connect the `1-6`
* `1-1 1-2 1-3 1-4 1-5 3-6 1-6` is valid, the 3-6 connects to the 1-3, then the 1-6 can connect to the 3-6
* `5-5 5-4 5-0 0-6 6-6 6-4 6-2 2-1 6-3 5-1 1-1 1-6 4-1 1-0 0-0 2-0 3-0 0-4` is valid, the above illustrated example
* `12-12 12-1 3-12 3-1 1-2 3-3` is valid, uses larger dominoes, and has an ambiguous placement

NOTE: The function required here is not a perfect check for valid Five Up games. We are ignoring here the rules about which domino gets played first, which would require more information about the variant of the game and number of players, and would disqualify a significant minority of inputs.

# Answer
# Haskell, ~~188~~ ~~174~~ 168 bytes

```
f(p:r)=[p]!r$p?p
(s!(p:r))o|b<-[p,reverse p]=or[(q:s)!r$q%o|q<-b,elem(q!!0)o,all(`notElem`s)b]
(s!_)o=1<3
p@[x,y]?r=[c|x==y,c<-p]++r
p@[x,y]%(a:r)|a/=x=a:p%r|z<-y:r=p?z

```

Try it online! Usage example: `f [[6,6],[6,5],[5,3],[3,0]]` yields `True`.

### Ungolfed:

```
f :: [[Int]] -> Bool
f (p:r) = check [p] (double p p) r

check :: [[Int]] -> [Int] -> [[Int]] -> Bool
check seen open [] = True
check seen open ([x,y]:r) =
	  notElem [x,y] seen
   && notElem [y,x] seen
   && (elem x open && check ([x,y]:seen) (update [x,y] open) r
   ||  elem y open && check ([y,x]:seen) (update [y,x] open) r)

double :: [Int] -> [Int] -> [Int]
double [x,y] rest =
    if x==y
    then [x,y] ++ rest
    else rest

update :: [Int] -> [Int] -> [Int]
update [x,y] (a:rest) =
    if x==a
    then double [x,y] (y:rest)
    else a : update [x,y] rest

```

Try it online!
> 1 votes

# Answer
# , 224 bytes

```
function(L,x=c(),y=c()){o=T
z=length
if(z(L)){p=sort(L[1:2])
w=rep(p,2-(p[2]>p[1]))
x=rbind(p,x)
if(z(y)){m=match(p,y,0)
v=which.max(m)
if(m[v]>0){y=y[-m[v]]
w=w[-v]}}
y=c(y,w)
L=L[-1:-2]
o=o&f(L,x,y)&!sum(duplicated(x))}
o}

```

Try it online!

The code receives the pieces as an ordered list and returns TRUE or FALSE according to the specs. The function recursively scans every piece, adds the piece to an index to verify the absence of duplicates, and keeps track of the available insertion points to check that the piece can effectively be added to the stack. The handling of piece connections (e.g. attaching a 1-2 by the 1 or by the 2) is done in a greedy fashion, so it is not entirely impossible that some weird configurations may blow up.
> 0 votes

---
Tags: code-golf, decision-problem, dominoes
---


title: How many shuffles

text:
# Question
Title: How many shuffles
A riffle shuffle is a type of shuffle where the deck is split into two partitions and the partitions are then spliced back together to create a new shuffled deck.

The cards are spliced together in such a way that cards maintain their relative order *within the partition they are a member of*. For example, if card **A** is before card **B** in the deck and cards **A** and **B** are in the same partition, card **A** must be before card **B** in the final result, even if the number of cards between them has increased. If **A** and **B** are in different partitions, they can be in any order, regardless of their starting order, in the final result.

Each riffle shuffle can then be viewed as a permutation of the original deck of cards. For example the permutation

```
1,2,3 -> 1,3,2

```

is a riffle shuffle. If you split the deck like so

```
1, 2 | 3

```

we see that every card in `1,3,2` has the same relative order to every other card in it's partition. `2` is still after `1`.

On the other hand the following permutation is *not* a riffle shuffle.

```
1,2,3 -> 3,2,1

```

We can see this because for all the two (non-trivial) partitions

```
1, 2 | 3
1 | 2, 3

```

there is a pair of cards that do not maintain their relative orderings. In the first partition `1` and `2` change their ordering, while in the second partition `2` and `3` change their ordering.

However we do see that `3, 2, 1` can be made by composing two riffle shuffles,

```
1, 3, 2 + 2, 3, 1 = 3, 2, 1

```

In fact a pretty simple fact to be proven is that *any* permutation can be made my combining some number of riffle shuffle permutations.

# Task

Your task is to make a program or function that takes a permutation (of size **N**) as input and outputs the smallest number of riffle shuffle permutations (of size **N**) that can be combined to form the input permutation. You do not need to output the riffle shuffles themselves just how many there are.

This is so answers will be scored in bytes with fewer bytes being better.

You may output either 1 or 0 for an identity permutation.

# Test Cases

```
1,3,2 -> 1
3,2,1 -> 2
3,1,2,4 -> 1
2,3,4,1 -> 1
4,3,2,1 -> 2

```

# Answer
> 2 votes
# Python 3, 255 bytes

Checks all possible riffles up to the length of the list (maximum number required), so it is very slow for larger input. Could also probably be golfed quite a bit.

```
lambda x:f(range(1,len(x)+1),x)
f=lambda x,y,i=0:x==y and i or i<len(x)and min(f(q,y,i+1)for a in range(1,len(x))for q in g(x[:a],x[a:]))or i
g=lambda x,y:(x or y)and[[v]+q for v in x[:1]for q in g(x[1:],y)]+[[v]+q for v in y[:1]for q in g(x,y[1:])]or[[]]

```

Try it online!

# Answer
> 2 votes
# Clean, ~~206~~ ... 185 bytes

```
import StdEnv
f=flatten
$a b#[c:d]=b
|a>[]#[u:v]=a
=[a++b,b++a:f[[[u,c:e],[c,u:e]]\\e<- $v d]]=[b]
@l#i=length l
=hd[n\\n<-[0..],e<-iter n(f o map(uncurry$o splitAt(i/2)))[[1..i]]|l==e]

```

Try it online!

Generates every possible outcome of shuffling `n` times, and checks if the list is a member.
While this is a horribly inefficient way to solve the problem, this code is *particularly slow* due to its use of list comprehensions instead of composition, which heavily limits any elementary graph reduction, and results in a spectacular showcase of Clean's garbage collector.

**Ungolfed:**

```
import StdEnv
shuffle [] l
    = [l]
shuffle [a: b] [c: d]
    = [[a: b]++[c: d], [c: d]++[a: b]: flatten [
        [[a, c: e], [c, a: e]]
        \\ e <- shuffle b d
        ]]
numReq l
    = until cond ((+)1) 0
where
    cond n
        = let
            mapper
                = map (uncurry shuffle o splitAt (length l/2))
            options
                = iter n (removeDup o flatten o mapper) [[1..length l]]
        in isMember l options

```

Try it online!

---
Tags: code-golf, combinatorics, card-games, abstract-algebra
---


title: Integer Division Loops

text:
# Question
Title: Integer Division Loops
## Challenge

Given any positive integer supported by your language:

1. Take the input and divide it into two halves. For all divisions in this program, if the input is odd, round one half up and one half down (ex: `7 -> 3,4`, not `7 -> 3.5,3.5`).
2. Divide either number in half, then take the larger of these two new halves and add it back to the number that wasn’t split. Ex: `3,4 -> (1,2),4 -> 1,6` or `3,4 -> 3,(2,2) -> 5,2`.
3. Repeat step 2 until you reach a set you have seen before. Ex: `5 -> 3,2 -> (1,2),2 -> 1,4 -> 1,(2,2) -> 3,2`. Since we’ve seen `3,2` before, we may stop repeating. You may completely exhaust a stack in the process of doing this. Ex: `5 -> 3,2 -> (1,2),2 -> 1,4 -> (0,1),4 -> 0,5`.
4. Output each pair in the loop (i.e. the above without the intermediate steps, from the first appearance of a pair until the second, but not including the second). Ex: `3,2 -> 1,4`. If the input is included, don’t output a `0` with it - `5 -> 3,2 -> 1,4`, not `0,5 -> 3,2 -> 1,4`.
5. Repeat steps 1-4 by splitting the pairs differently.

## I/O

Input is a positive integer larger than `1` and smaller than either the maximum integer supported by your language or the maximum integer that won’t crash the computer, whichever is smaller.

Output is the loops from above in any format you want (string, list, array, etc.). Trailing white space is allowed.

Do not output the same loop twice, nor different versions of the same loop. Ex: `2 -> 1,1` and `1,1 -> 2` are both valid loops, but they describe the same loop, beginning at different points on the loop. Likewise, two loops that are identical but go in the reverse order should not be outputted. Ex: `3 -> 1,2 -> 2,1` and `3 -> 2,1 -> 1,2` are the same loop, but they go in the opposite direction from each other.

You may use any delimiter to differentiate between the pairs, between each number in the pairs, and between each loop, provided that they are three distinct chars or strings. Above, I divided the numbers using commas, the pairs using `->`’s, and the loops using boring instructions. In my examples below, I will use parentheses around each pair, commas between each number within a pair, and new lines between each loop.

## Examples

Credit to @WheatWizard’s code for fixing up my examples list. As I said in an earlier draft, I was sure I was missing a few since I was doing it by hand, but boy was I missing some.

Input: `2`
Output: `(2)(1,1)`

Input: `3`
Output:

```
(3)(1,2)
(1,2)(2,1)
(3)(1,2)(2,1)

```

Input: `4`
Output:

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

```

Input: `5`

Output:

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

```

Input: `6`

Output:

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

```

Input: `7`

Output:

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

```

## Scoring

This is , so the lowest byte count wins.

---

This is my first challenge here, so any feedback would be greatly appreciated. Link to sandbox here.

Fun fact: I was bored one day and playing with random little pieces of pencil lead in this manner and eventually noticed that I could keep going in these types of loops. For some reason my first reaction was “hey, this would be a great challenge for code golf.”

# Answer
# Clean, ~~267~~ ... 167 bytes

```
import StdEnv
f s l|any((==)s)l=[dropWhile((<>)s)l]#[h,t:_]=s
|1>h*t=f[max h t]l=f[h/2,(h+1)/2+t](l++[s])++(f[(t+1)/2+h,t/2](l++[s]))
@n=removeDup(f[n/2,(n+1)/2][[n]])

```

Try it online!

**Ungolfed:**

```
loops num
    = removeDup (half (divide num) [[num]])
where
    divide num
        = [num/2, (num+1)/2]
    half [_, 0] list
        = list
    half [0, _] list
        = list
    half [a, b] list
        | isMember [a, b] list
            = [dropWhile ((<>) [a, b]) list]
        # [u, v: _]
            = divide a
        # [x, y: _]
            = divide b
        = (half [u, v+b] (list ++ [a, b])) ++ (half [a+y, x] (list ++ [a, b]))

```
> 2 votes

# Answer
# Haskell, ~~227~~ 203 bytes

*17 bytes saved thanks to Οurous*

```
(%)=div
u x|odd x=x%2+1|1>0=x%2
[0,b]!l=[b]!l
[b,0]!l=[b]!l
t!l|elem t l=[dropWhile(/=t)l]
t@[a,b]!l|q<-l++[t]=[a%2,u a+b]!q++[u b+a,b%2]!q
f x|q<-[x%2,u x]![[x]]=[a|(a,b)<-zip q[0..],notElem a$take b q]

```

Try it online!
> 2 votes

---
Tags: code-golf, math, number, division
---


title: Factor-poor numbers

text:
# Question
Title: Factor-poor numbers
If a positive integer \\$N \> 2\\$ has (strictly) less prime factors (without counting multiplicities) than its successor and its predecessor, we will call it a *factor-poor number*.

In other words, \\$\omega(N) \< \omega(N - 1)\\$ and \\$\omega(N) \< \omega(N + 1)\\$, where \\$\omega(N)\\$ is the number of unique prime factors of \\$N\\$.

# Task

You can choose among the following I / O formats:

* Take an integer \\$N\\$ and output the \\$N^{\text{th}}\\$ factor-poor number. In case you choose this one, \\$N\\$ can either be 0 or 1 indexed.
* Take a positive integer \\$N\\$ and output the first \\$N\\$ factor-poor numbers.
* Print the sequence indefinitely.

---

You can take input and provide output through any standard method, in any programming language, while taking note that these loopholes are forbidden by default. This is code golf, so the shortest submission that abides to the rules wins.

I won't include separate test cases, because the methods of competing are different, but you can refer to the first 100 terms of this sequence, which is OEIS A101934:

```
11, 13, 19, 23, 25, 27, 29, 37, 41, 43, 47, 49, 53, 59, 61, 64, 67, 71, 73, 79, 81, 83, 89, 97, 101, 103, 107, 109, 113, 121, 125, 131, 137, 139, 149, 151, 155, 157, 163, 167, 169, 173, 179, 181, 191, 193, 197, 199, 211, 221, 223, 227, 229, 233, 239, 241, 243, 251, 259, 263, 265, 269, 271, 277, 281, 283, 289, 293, 307, 309, 311, 313, 317, 331, 337, 341, 343, 347, 349, 353, 359, 361, 365, 367, 371, 373, 379, 383, 389, 397, 401, 407, 409, 419, 421, 431, 433, 439, 441, 443

```

As an example, \\$25\\$ occurs in this sequence because \\$\omega(25) = 1\\$ (5), \\$\omega(26) = 2\\$ (2 and 13) and \\$\omega(24) = 2\\$ (2 and 3), so \\$\omega(25) \< \omega(24)\\$ and \\$\omega(25) \< \omega(26)\\$.

# Answer
# Brachylog, 21 bytes

```
⟨+₁≡-₁⟩{ḋdl}ᵐ⌋>~↰₂?ẉ⊥

```

Try it online!

Prints infinitely.

### Explanation

```
⟨+₁≡-₁⟩                  Fork: The output of the fork is [Input + 1, Input -1]
       {   }ᵐ            Map:
        ḋdl                (predicate 2) the output is the length of the prime decomposition
                           of the input with no duplicates
             ⌋           Take the minimum result of that map
              >          This minimum is bigger than…
               ~↰₂?      …the output of predicate 2 with Input as input
                  ?ẉ     Write Input followed by a new line if that's the case
                    ⊥    False: backtrack and try another value for Input

```
> 7 votes

# Answer
# Python 2, ~~123~~ 119 bytes

```
q=lambda n:sum(n%i<all(i%j for j in range(2,i))for i in range(2,n+1))
i=2
while 1:
 i+=1
 if q(i-1)>q(i)<q(i+1):print i

```

Try it online!
> 5 votes

# Answer
# Jelly, ~~13~~ 12 bytes

```
Cr~ÆvÐṂN⁼Wø#

```

Prints the first **n** factor-poor numbers.

Try it online!

### How it works

```
Cr~ÆvÐṂN⁼Wø#  Main link. No arguments.

          ø   Wrap the links to the left into a chain and begin a new chain.
           #  Read an integer n from STDIN and call the chain to the left with
              arguments k = 0, 1, 2, ... until n of them return a truthy value.
              Return those n values of k as an array.
C                 Complement; yield -k+1.
  ~               Bitwise NOT; yield -k-1.
 r                Range; yield [-k+1, -k, -k-1].
     ÐṂ           Yield those elements of [-k+1, -k, -k-1] for which the link to
                  the left returns the minimal value.
   Æv                 Count the number of unique prime factors.
                      Note that, for a negative argument, Æv counts -1 as well, and
                      0 is counted as a/the factor of 0. Negating the the arguments
                      eliminates the edge case 1 (no factors), which would be a
                      false positive otherwise.
                  For a factor-poor number, this yields [-k].
       N          Take the negatives of the resulting integers.
         W        Wrap; yield [k].
        ⁼         Test the results to both sides for equality.

```
> 5 votes

# Answer
# MATL, ~~26~~ ~~24~~ 22 bytes

```
`T@3:q+YFg!sdZSd0>?@QD

```

Prints the sequence indefinitely.

Try it online!

### Explanation

```
`         % Do...while loop
  T       %   Push true. Will be used as loop condition
  @       %   Push (1-based) iteration index, k
  3:q     %   Push [1 2 3] minus 1, that is, [0 1 2]
  +       %   Add, element-wise. Gives [k k+1 k+2]
  YF      %   Exponents of prime-factor decomposition. Gives a 3-row matrix
  g       %   Convert to logical: non-zero numbers become 1
  !s      %   Transpose, sum of each column. Gives a row vector of 3 elements,
          %   which are the number of unique prime factors of k, k+1 and k+2
  d       %   Consecutive differences. Gives a row vector of 2 elements
  ZS      %   Sign: replaces each number by -1, 0 or 1
  d       %   Consecutive difference. Gives a single number
  0>      %   Is it positive?
  ?       %   If so
    @Q    %     Push k+1
    D     %     Display
          %   End (implicit)
          % End (implicit). The stack contains true, which (is consumed and)
          % causes an infinite loop

```
> 4 votes

# Answer
# Husk, 22 bytes

```
f(ΠtSM<←ṙ1mȯLup§…←→)tN

```

Prints the sequence indefinitely, try it online or view the first **N**!

Alternatively `§oΛ>←t` could be used instead of `ΠtSM<←`.

### Explanation

```
f(                  )tN  -- filter the tail of the naturals ([2,3…]) by:
  ΠtSM<←ṙ1m(Lup)§…←→     -- | takes a number as argument, example 11
                §…       -- | range of..
                  ←      -- | | the argument decremented (10)
                   →     -- | | to the argument incremented (12)
                         -- | : [10,11,12]
          m(   )         -- | map the following (example on 12) ..
              p          -- | | prime factors: [2,2,3]
             u           -- | | deduplicate: [2,3]
            L            -- | | length: 2
                         -- | : [2,1,2]
        ṙ1               -- | rotate by 1: [1,2,2]
    SM<                  -- | map the function (< X) over the list where X is ..
       ←                 -- | | the first element (1)
                         -- | : [0,1,1]
   t                     -- | tail: [1,1]
  Π                      -- | product: 1
                         -- : [11,13,19,23,25,27,29…

```
> 3 votes

# Answer
# Pyth, 14 bytes

```
.f!-.ml{Pb}tZh

```

**Try it here!**

It was initially a suggestion on Dopapp's answer, but they told me to post it separately.

### How it works?

```
.f!-.ml{Pb}tZh | Full program. Takes input from STDIN, outputs the first N to STDOUT.

.f             | (var: Z) Output the first N values which satisfy the predicate.
          }tZh | Creates the list [Z - 1, Z, Z + 1].
    .m         | (var: b) Take the elements with minimal function value.
        Pb     | Prime factors of b.
      l{       | Deduplicate, get length.
               | For a factor-poor number, this yields itself wrapped in a singleton.
   -           | Remove Z from that.
  !            | Logical negation.

```
> 3 votes

# Answer
# Haskell, ~~105~~ 86 bytes

*Thanks to @Wheat Wizard, @Bruce Forte, and @Laikoni for saving 19 bytes.*

`[n|n<-[2..],d n<d(n-1),d n<d(n+1)]
d x=[1|n<-[1..x],x`rem`n<1,all((>0).rem n)[2..n-1]]`
> 3 votes

# Answer
# Octave,  ~~87~~   ~~83~~  79 bytes

*Thanks to @Cows quack for saving a byte and thanks to @Luis Mendo for saving ~~three~~ six bytes!*

```
f=@(n)nnz(unique(factor(n)));n=9;while++n if[f(n-1) f(n+1)]>f(n)disp(n);end;end

```

Prints the sequence indefinitely.

Try it online!

**73 bytes with leading `n =` before each value:**

```
f=@(n)nnz(unique(factor(n)));n=9;while++n if[f(n-1) f(n+1)]>f(n)n end;end

```

Try it online!
> 2 votes

# Answer
# 05AB1E, ~~14~~ 13 bytes

Outputs the nth factor-poor number (1-indexed)

```
µ3LN+Íf€gÀć›P

```

Try it online!

**Explanation**

```
µ                 # loop over N (1,2,3, ...) until counter equals input
 3L               # push the range [1,2,3]
   N+             # add current N
     Í            # subtract 2
      f           # get unique prime factors of each
       €g         # get length of each factor list
         À        # rotate left
          ć       # extract the head
           ›      # check if the remaining elements are strictly greater
            P     # product
                  # if 1, increment counter
                  # implicitly output final N

```
> 2 votes

# Answer
# Pyth, 30 25 bytes

```
#=hTI&>l{PhTKl{PT>l{PtTKT

```

This is my first *real* Pyth golf, so any comments are very appreciated.

A big thanks to Xcoder!

Explanation

```
#                         | Loop until error
 =hT                      | Add one to T (initially 10)
    I&                    | If both...
      >l{PhTKl{PT         | The number of unique prime factors of T+1 is greater than that of T (store in K)
                 >l{PtTK  | And the number of unique prime factors of T-1 is greater than K (from before)
                        T | Then implicitly print T

```

TIO.
> 1 votes

# Answer
# JavaScript (ES6), 94 bytes

Returns the Nth factor-poor number, 0-indexed.

```
f=(i,n=9)=>(P=(n,i=k=1)=>++k>n?0:n%k?P(n,1):i+P(n/k--,0))(n)>P(++n)&P(n)<P(n+1)&&!i--?n:f(i,n)

```

Try it online!

### How?

We first define the **P()** function which returns the number of unique prime factors of a given integer.

```
P = (                   // P = recursive function taking:
  n,                    //   n = input number to test
  i =                   //   i = flag to increment the number of prime factors
  k = 1                 //   k = current divisor
) =>                    //
  ++k > n ?             // increment k; if k is greater than n:
    0                   //   stop recursion
  :                     // else:
    n % k ?             //   if k is not a divisor of n:
      P(n, 1)           //     do a recursive call with n unchanged and i = 1
    :                   //   else:
      i +               //     add i and
      P(n / k--, 0)     //     do a recursive call with n / k and i = 0; decrement k

```

The wrapping code now reads as:

```
f = (                   // given:
  i,                    //   i = input index
  n = 9                 //   n = counter
) =>                    //
  P(n) > P(++n) &       // increment n; if P(n - 1) is greater than P(n)
  P(n) < P(n + 1) &&    // and P(n) is less than P(n + 1)
  !i-- ?                // and we have reached the correct index:
    n                   //   return n
  :                     // else:
    f(i, n)             //   go on with the next value

```
> 1 votes

# Answer
# Japt, ~~29~~ ~~27~~ 26 bytes

Not entirely happy with this but at least it's better than my first attempt which was over 40 bytes!

Outputs the `N`th number in the sequence, 1-indexed.

```
È=Jõ_+X k â ÊÃé)e>Xo)«´U}a

```

Try it

---

## Explanation

Implicit input of integer `U`.

```
È                       }a

```

Return the first integer `X` that returns true when passed through the following function.

```
=Jõ             )

```

Assign the array `[-1,0,1]` to `X`.

```
 _+X      Ã

```

Pass each element of that array through a function which firstly adds the current value of `X`.

```
k â Ê

```

Get the length (`Ê`) of the unique (`â`) prime factors (`k`) of the result.

```
é

```

Rotate the resulting array one to the right.

```
e>Xo)

```

Pop (`o`) the last element from `X` and check if all remaining elements are greater than it.

```
«´U

```

If so, decrement `U` and check if it is equal to 0.
> 1 votes

# Answer
# Python 3, 97 bytes

```
n,g=9,lambda m,k=2,p=1:m//k and(m%k<p%k)+g(m,k+1,p*k*k)
while 1:n+=1;g(n-1)>g(n)<g(n+1)!=print(n)

```

In theory, this prints the sequence indefinitely. In practice, `g` eventually exceeds the recursion limit.

Try it online!
> 1 votes

# Answer
# C (gcc), 126 bytes

```
j,t;o(n){for(j=t=0;j++<n;)if(n%j<1)for(t--;j>1>n%j;)n/=j;t=~t;}
m(J){for(J=3;;J++)if(o(J-1)>o(J)&o(J)<o(J+1))printf("%d,",J);}

```

Try it online!
> 1 votes

# Answer
# APL NARS, 124 bytes, 62 chars

```
{(⍵>1E4)∨⍵≤0:¯1⋄x←9+⍳10×⍵⋄⍵↑(∊{v←⍴∘∪∘π¨⍵+2-⍳3⋄2=+/v>2⌷v}¨x)/x}

```

It should return answer until 1E4, then return -1 error; it suppose 9..10xargument has enought right numbers; test:

```
  z←{(⍵>1E4)∨⍵≤0:¯1⋄x←9+⍳10×⍵⋄⍵↑(∊{v←⍴∘∪∘π¨⍵+2-⍳3⋄2=+/v>2⌷v}¨x)/x}
  z 0
¯1
  z 1
11
  z 20
11 13 19 23 25 27 29 37 41 43 47 49 53 59 61 64 67 71 73 79

```
> 0 votes

# Answer
# Clean, ~~130~~ ~~123~~ 117 bytes

```
import StdEnv
?n=[1\\q<-[p\\p<-[2..n]|and[gcd p i<2\\i<-[2..p-1]]]|n rem q<1]
f=[n\\n<-[3..]| ?n<min(?(n-1))(?(n+1))]

```

Equates to an infinite number of terms of the sequence. Since it's all nested comprehensions, it can't take advantage of graph reduction very well and so is quite slow, even for such a bad algorithm.

Try it online!
> 0 votes

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


title: Disentangle doubly linked data

text:
# Question
Title: Disentangle doubly linked data
A doubly linked list is a data structure in which each node has a `value` as well as "links" to both the `previous` and next `nodes` in the list. For example, consider the following nodes with values 12, 99, and 37:

Here, the nodes with values **12** and **99** point to their respective `next` nodes, with values **99** and **37**. The node with value **37** has no `next` pointer because it's the last node in the list. Likewise, the nodes with values **99** and **37** point to their respective `previous` nodes, **12** and **99**, but **12** has no `previous` pointer because it's the first node in the list.

## The setup

In practice, a node's "links" are implemented as pointers to the previous and next node's locations in memory. For our purposes, the "memory" will be an array of nodes and a node's location will be its index in the array. A node can be thought of as a 3-tuple of the form `( prev value next )`. The above example, then, might look like this:

But it might look like this, instead:

Starting at any node, you can follow `previous` links (shown as the origins of the red arrows) to get to the nodes that precede it and `next` links (green arrows) to find subsequent nodes in order to get all of the nodes' values in order: `[12, 99, 37]`.

The first diagram above could be represented in an array as `[[null, 12, 1], [0, 99, 2], [1, 37, null]]`. The second, then, would be `[[2, 99, 1], [0, 37, null], [null, 12, 0]]`.

## The challenge

> Write a program that takes as input an array of nodes and the index of a node and returns, in list order, the values of the nodes in the same doubly linked list.

### A complication

The "memory" won't always contain the nodes of just one list. It might contain several lists:

The above array contains three doubly linked lists, color-coded for your convenience:

1. The nodes at indexes `7`, `10`, `1`, `4`, `3`, `12` (showing only `next` links to reduce clutter; click to enlarge):

Given this array and any of these indexes, your program should return, in order, the values `[0, 1, 1, 2, 3, 5, 8]`.
2. The node at index `9`:

Given the index `9`, your program should return `[99]`.
3. The nodes at indexes `11`, `8`, `0`, `6`, `2`:

Given one of these indexes, it should return `[2, 3, 5, 7, 11]`.

## Rules

### Input

Your program will receive as input:

1. A list of nodes (3-tuples as described above), where 1 ≤ ≤ 1,000, in any convenient format, e.g. an array of arrays, a "flat" array of integers with length 3, etc.

The 3-tuples' elements may be in any order: `( prev value next )`, `( next prev value )`, etc. For each node, `prev` and `next` will be `null` (or another convenient value, e.g. `-1`), indicating the first or last node in a doubly linked list, or a valid index of the list, either 0- or 1-based as is convenient. `value` will be a signed 32-bit integer or the largest integer type your language supports, whichever is smaller.
2. The index of a node in the list (1). The indicated node may be the first node in a doubly linked list, the last node, a middle node, or even the only node.

The input list (1) **may contain pathological data** (e.g. cycles, nodes pointed to by multiple other nodes, etc.), but the input index (2) will always point to a node from which a single, well-formed output can be deduced.

### Output

Your program should output the values of the nodes of the doubly linked list of which the node at index is a member, in list order. Output can be in any convenient format, but its data must include only the node `value`s.

### Winning

This is . Shortest answer in bytes wins. Standard loopholes apply.

## Test cases

Below, each test case is of the form:

```
X)
prev value next, prev value next, ...
index
value value value ...

```

...where `X` is a letter to identify the test case, the second line is the input list, the third line is the 0-based input index, and the fourth line is the output.

```
A) null 12 1, 0 99 2, 1 37 null
   1
   12 99 37

B) 2 99 1, 0 37 null, null 12 0
   1
   12 99 37

C) 8 5 6, 10 1 4, 6 11 null, 4 3 12, 1 2 3, 12 8 null, 0 7 2, null 0 10, 11 3 0, null 99 null, 7 1 1, null 2 8, 3 5 5
   4
   0 1 1 2 3 5 8

D) 8 5 6, 10 1 4, 6 11 null, 4 3 12, 1 2 3, 12 8 null, 0 7 2, null 0 10, 11 3 0, null 99 null, 7 1 1, null 2 8, 3 5 5
   0
   2 3 5 7 11

E) 8 5 6, 10 1 4, 6 11 null, 4 3 12, 1 2 3, 12 8 null, 0 7 2, null 0 10, 11 3 0, null 99 null, 7 1 1, null 2 8, 3 5 5
   9
   99

F) 13 80 18, 18 71 null, 5 10 19, 12 1 8, 19 21 null, 31 6 2, 17 5 26, 26 0 30, 3 -1 25, null 1 23, 27 6 17, 14 1 24, 28 -1 3, null 80 0, 20 4 11, 33 6 29, 24 9 33, 10 7 6, 0 67 1, 2 15 4, 32 1 14, null 1 31, 29 3 null, 9 -1 28, 11 5 16, 8 1 null, 6 3 7, null 8 10, 23 1 12, 15 5 22, 7 9 null, 21 3 5, null 3 20, 16 2 15
   18
   80 80 67 71

G) 13 80 18, 18 71 null, 5 10 19, 12 1 8, 19 21 null, 31 6 2, 17 5 26, 26 0 30, 3 -1 25, null 1 23, 27 6 17, 14 1 24, 28 -1 3, null 80 0, 20 4 11, 33 6 29, 24 9 33, 10 7 6, 0 67 1, 2 15 4, 32 1 14, null 1 31, 29 3 null, 9 -1 28, 11 5 16, 8 1 null, 6 3 7, null 8 10, 23 1 12, 15 5 22, 7 9 null, 21 3 5, null 3 20, 16 2 15
   8
   1 -1 1 -1 1 -1 1

H) 13 80 18, 18 71 null, 5 10 19, 12 1 8, 19 21 null, 31 6 2, 17 5 26, 26 0 30, 3 -1 25, null 1 23, 27 6 17, 14 1 24, 28 -1 3, null 80 0, 20 4 11, 33 6 29, 24 9 33, 10 7 6, 0 67 1, 2 15 4, 32 1 14, null 1 31, 29 3 null, 9 -1 28, 11 5 16, 8 1 null, 6 3 7, null 8 10, 23 1 12, 15 5 22, 7 9 null, 21 3 5, null 3 20, 16 2 15
   4
   1 3 6 10 15 21

I) 13 80 18, 18 71 null, 5 10 19, 12 1 8, 19 21 null, 31 6 2, 17 5 26, 26 0 30, 3 -1 25, null 1 23, 27 6 17, 14 1 24, 28 -1 3, null 80 0, 20 4 11, 33 6 29, 24 9 33, 10 7 6, 0 67 1, 2 15 4, 32 1 14, null 1 31, 29 3 null, 9 -1 28, 11 5 16, 8 1 null, 6 3 7, null 8 10, 23 1 12, 15 5 22, 7 9 null, 21 3 5, null 3 20, 16 2 15
   14
   3 1 4 1 5 9 2 6 5 3

J) 13 80 18, 18 71 null, 5 10 19, 12 1 8, 19 21 null, 31 6 2, 17 5 26, 26 0 30, 3 -1 25, null 1 23, 27 6 17, 14 1 24, 28 -1 3, null 80 0, 20 4 11, 33 6 29, 24 9 33, 10 7 6, 0 67 1, 2 15 4, 32 1 14, null 1 31, 29 3 null, 9 -1 28, 11 5 16, 8 1 null, 6 3 7, null 8 10, 23 1 12, 15 5 22, 7 9 null, 21 3 5, null 3 20, 16 2 15
   17
   8 6 7 5 3 0 9

K) 4 11 0, null 22 3, null 33 3, 1 44 4, 3 55 null, 7 66 7, 6 77 6
   3
   22 44 55

L) null -123 null
   0
   -123

```

# Answer
> 1 votes
# 05AB1E, 25 bytes

```
è[¬D0‹#Isè]\[`sˆD0‹#Isè]¯

```

Try it online!

## Explanation

```
è[¬D0‹#Isè]\[`sˆD0‹#Isè]¯   # Arguments n, a
è                           # Get element at index n in a
 [¬D0‹#Isè]                 # Find the first element in the list
 [                          # While true, do
  ¬                         #   Head (get index of previous element)
   D0‹#                     #   Break if lower than 0
       Isè                  #   Get the element at that index
          ]                 # End loop
           \                # Delete top element of stack
            [`sˆD0‹#Isè]    # Iterate through list
            [               # While true, do
             `sˆ            #   Add value to global array and keep next index on stack
                D0‹#Isè     #   Same as above
                       ]    # End loop
                        ¯   # Push global array

```

# Answer
> 3 votes
# Haskell, ~~79~~ ~~65~~ ~~59~~ 55 bytes

**-6** bytes thanks to Brute Force.

```
x#i|let-1!d=[];i!d=i:x!!i!!d!d=[x!!i!!1|i<-last(i!0)!2]

```

Defines function `#` that accepts a list of lists of integers, where `null` is represented as `-1`, and returns list of node values.

Try it online!

## Explanation

```
let-1!d=[];i!d=i:x!!i!!d!d

```

Define function `!` that iterates through the nodes starting at node `i` and returns a list visited indexes. It accepts the second argument `d` that specifies which index of the "tuple" use as the index of the next node (`d==2` to iterate forwards, `d==0` to iterate backwards).

```
(i!0)

```

Iterate backwards starting from the given index and return visited indexes.

```
last(i!0)

```

Take last visited index, which is the beginning of the list.

```
last(i!0)!2

```

Iterate from the beginning of the list.

```
[x!!i!!1|i<-last(i!0)!2]

```

Replace each visited index with the value of the node.

# Answer
> 3 votes
# Python 2, 60 bytes

```
l,n=input()
while~n:m=n;n=l[n][0]
while~m:p,v,m=l[m];print v

```

Try it online!

This is pretty much Chas Brown's answer, minus these golfs:

* I reuse n, saving an assignment
* I store the last valid n in m, allowing me to
* place the print after the assignment in line 3, saving me the final print
* I use only ~n instead of -~n, because negative values are just as truthy as positive ones, saving me 2 characters.

# Answer
> 2 votes
# Clean, ~~94~~ ~~90~~ 88 bytes

```
import StdEnv
$l[_,u,v]|v<0=[u]=[u: $l(l!!v)]
?l= $l o until((>)0o hd)((!!)l o hd)o(!!)l

```

Try it online!

# Answer
> 2 votes
# MATL, 39 bytes

```
XHx`HwI3$)t]x6Mt`Hwl3$)tbhwt]x4L)Hw2I$)

```

Try it online!

Almost a direct port of my Octave answer, but this version finds the end first, and then works it way back, rather than the other way round, which saved one byte.

```
XHx           % Store array in H.
`HwI3$)t]     % Work to the end of the array
x6Mt          % Delete the end of array delimiter, and push the array end index twice
`Hwl3$)    t] % Work to the beginning of the array
       tbhw   % Append all indices found.
Hw2I$)        % Index into original array.

```

# Answer
> 1 votes
# Python 2, ~~81~~ 77 bytes

```
a,n=input()
u=a[n][0]
while-~u:u,v,w=a[u]
while-~w:print v;u,v,w=a[w]
print v

```

Try it online!

EDIT: Thx to Mr. Xcoder for 4 bytes...

Takes a list of tuples \[u,v,w\] where u and w are -1 to represent the beginning/end of the linked list segment.

# Answer
> 1 votes
## PHP, 132 bytes

```
<?list(,$x,$y)=$argv;parse_str($x);while(($q=$x[$y*3+1])>=0)$y=$q;do{$n[]=$x[$y*3+2];$y=$x[$y*3];}while($x[$y*3]);echo join(' ',$n);

```

Try it online!

Input is taken as a querystring `x[]=-1&x[]=1&x[]=1...` (all nodes in a flat array), in the order of `next`, `prev`, then `value` for each node with -1 used for ending nodes.

# Answer
> 1 votes
# Octave, ~~81~~ ~~78~~ 76 bytes

```
function o=f(a,n)while q=a(n,1)o=a(n=q,2);end
while n=a(n,3)o=[o a(n,2)];end

```

Try it online!

Rather straightforward version. Explanation is left as an exercise to the reader. A much more *fun* version is presented below:

# Octave, ~~142~~ ~~99~~ 92 bytes

```
@(a,n)[(p=@(b,c,z){q=a(z,2),@()[b(b,c,a(z,c)),q]}{2-~a(z,c)}())(p,1,n),p(p,3,n)(end-1:-1:1)]

```

Try it online!

Yo, I heard you liked anonymous functions...

Takes a `nx3` array, with the first column the predecessor, second column the value, and third value the successor nodes. All the node indices are 1-based, which is the default in Octave.

```
% Create an anonymous function, taking an array a and first node n
@(a,n)
% Returns an array containing the predecessor and sucessor nodes
      [                                                                     ,                     ]
% Defines an recursive anonymous function (by supplying itself to the local namespace)
% which looks at the first column (c=1) or last column (c=3) of the input array to get the next nodes
       (p=@(p,c,z)                                                   )(p,1,n)
% Create a cell array, either containing the end node,
                    {q=a(z,2),
% ...or an array with all next  next nodes and the current node
% (note the use of an anonymous function taking no parameters to defer array access, in case of the last node)
                              @()[p(p,c,a(z,c)),q]}
% depending whether the next node number is nonzero (followed by () to execute the deferred array access)
                                                    {2-~a(z,c)}()
% Do the same with c=3, reverse (function p builds the array right-to-left) and drop the current node to prevent a duplicate.
                                                                             p(p,3,n)(end-1:-1:1)

```

# Answer
> 1 votes
# Kotlin, 85 bytes

```
{g,S->generateSequence(generateSequence(S){g[it][0]}.last()){g[it][2]}.map{g[it][1]}}

```

## Beautified

```
{g,S->
    generateSequence(generateSequence(S){g[it][0]}.last()){ g[it][2]}.map { g[it][1] }
}

```

## Test

```
typealias Node=Triple<Int?,Int?,Int?>
data class Test(val input: List<Node>, val start:Int, val result: List<Int>)
val TEST = listOf<Test>(
Test(
listOf(Node(null, 12, 1), Node(0, 99, 2), Node(1, 37, null)),
1,
listOf(12, 99, 37)
),
Test(listOf(
Node(2, 99, 1), Node(0, 37, null), Node(null, 12, 0)),
1,
listOf(12, 99, 37)
),
Test(
listOf(Node(8, 5, 6), Node(10, 1, 4), Node(6, 11, null), Node(4, 3, 12), Node(1, 2, 3), Node(12, 8, null), Node(0, 7, 2), Node(null, 0, 10), Node(11, 3, 0), Node(null, 99, null), Node(7, 1, 1), Node(null, 2, 8), Node(3, 5, 5)),
4,
listOf(0, 1, 1, 2, 3, 5, 8)
),
Test(
listOf(Node(8, 5, 6), Node(10, 1, 4), Node(6, 11, null), Node(4, 3, 12), Node(1, 2, 3), Node(12, 8, null), Node(0, 7, 2), Node(null, 0, 10), Node(11, 3, 0), Node(null, 99, null), Node(7, 1, 1), Node(null, 2, 8), Node(3, 5, 5)),
0,
listOf(2, 3, 5, 7, 11)
),
Test(
listOf(Node(8, 5, 6), Node(10, 1, 4), Node(6, 11, null), Node(4, 3, 12), Node(1, 2, 3), Node(12, 8, null), Node(0, 7, 2), Node(null, 0, 10), Node(11, 3, 0), Node(null, 99, null), Node(7, 1, 1), Node(null, 2, 8), Node(3, 5, 5)),
9,
listOf(99)
),
Test(
listOf(Node(13, 80, 18), Node(18, 71, null), Node(5, 10, 19), Node(12, 1, 8), Node(19, 21, null), Node(31, 6, 2), Node(17, 5, 26), Node(26, 0, 30), Node(3, -1, 25), Node(null, 1, 23), Node(27, 6, 17), Node(14, 1, 24), Node(28, -1, 3), Node(null, 80, 0), Node(20, 4, 11), Node(33, 6, 29), Node(24, 9, 33), Node(10, 7, 6), Node(0, 67, 1), Node(2, 15, 4), Node(32, 1, 14), Node(null, 1, 31), Node(29, 3, null), Node(9, -1, 28), Node(11, 5, 16), Node(8, 1, null), Node(6, 3, 7), Node(null, 8, 10), Node(23, 1, 12), Node(15, 5, 22), Node(7, 9, null), Node(21, 3, 5), Node(null, 3, 20), Node(16, 2, 15)),
18,
listOf(80, 80, 67, 71)
),
Test(
listOf(Node(13, 80, 18), Node(18, 71, null), Node(5, 10, 19), Node(12, 1, 8), Node(19, 21, null), Node(31, 6, 2), Node(17, 5, 26), Node(26, 0, 30), Node(3, -1, 25), Node(null, 1, 23), Node(27, 6, 17), Node(14, 1, 24), Node(28, -1, 3), Node(null, 80, 0), Node(20, 4, 11), Node(33, 6, 29), Node(24, 9, 33), Node(10, 7, 6), Node(0, 67, 1), Node(2, 15, 4), Node(32, 1, 14), Node(null, 1, 31), Node(29, 3, null), Node(9, -1, 28), Node(11, 5, 16), Node(8, 1, null), Node(6, 3, 7), Node(null, 8, 10), Node(23, 1, 12), Node(15, 5, 22), Node(7, 9, null), Node(21, 3, 5), Node(null, 3, 20), Node(16, 2, 15)),
8,
listOf(1, -1, 1, -1, 1, -1, 1)
),
Test(
listOf(Node(13, 80, 18), Node(18, 71, null), Node(5, 10, 19), Node(12, 1, 8), Node(19, 21, null), Node(31, 6, 2), Node(17, 5, 26), Node(26, 0, 30), Node(3, -1, 25), Node(null, 1, 23), Node(27, 6, 17), Node(14, 1, 24), Node(28, -1, 3), Node(null, 80, 0), Node(20, 4, 11), Node(33, 6, 29), Node(24, 9, 33), Node(10, 7, 6), Node(0, 67, 1), Node(2, 15, 4), Node(32, 1, 14), Node(null, 1, 31), Node(29, 3, null), Node(9, -1, 28), Node(11, 5, 16), Node(8, 1, null), Node(6, 3, 7), Node(null, 8, 10), Node(23, 1, 12), Node(15, 5, 22), Node(7, 9, null), Node(21, 3, 5), Node(null, 3, 20), Node(16, 2, 15)),
4,
listOf(1, 3, 6, 10, 15, 21)
),
Test(
listOf(Node(13, 80, 18), Node(18, 71, null), Node(5, 10, 19), Node(12, 1, 8), Node(19, 21, null), Node(31, 6, 2), Node(17, 5, 26), Node(26, 0, 30), Node(3, -1, 25), Node(null, 1, 23), Node(27, 6, 17), Node(14, 1, 24), Node(28, -1, 3), Node(null, 80, 0), Node(20, 4, 11), Node(33, 6, 29), Node(24, 9, 33), Node(10, 7, 6), Node(0, 67, 1), Node(2, 15, 4), Node(32, 1, 14), Node(null, 1, 31), Node(29, 3, null), Node(9, -1, 28), Node(11, 5, 16), Node(8, 1, null), Node(6, 3, 7), Node(null, 8, 10), Node(23, 1, 12), Node(15, 5, 22), Node(7, 9, null), Node(21, 3, 5), Node(null, 3, 20), Node(16, 2, 15)),
14,
listOf(3, 1, 4, 1, 5, 9, 2, 6, 5, 3)
),
Test(
listOf(Node(13, 80, 18), Node(18, 71, null), Node(5, 10, 19), Node(12, 1, 8), Node(19, 21, null), Node(31, 6, 2), Node(17, 5, 26), Node(26, 0, 30), Node(3, -1, 25), Node(null, 1, 23), Node(27, 6, 17), Node(14, 1, 24), Node(28, -1, 3), Node(null, 80, 0), Node(20, 4, 11), Node(33, 6, 29), Node(24, 9, 33), Node(10, 7, 6), Node(0, 67, 1), Node(2, 15, 4), Node(32, 1, 14), Node(null, 1, 31), Node(29, 3, null), Node(9, -1, 28), Node(11, 5, 16), Node(8, 1, null), Node(6, 3, 7), Node(null, 8, 10), Node(23, 1, 12), Node(15, 5, 22), Node(7, 9, null), Node(21, 3, 5), Node(null, 3, 20), Node(16, 2, 15)),
17,
listOf(8, 6, 7, 5, 3, 0, 9)
),
Test(
listOf(Node(4, 11, 0), Node(null, 22, 3), Node(null, 33, 3), Node(1, 44, 4), Node(3, 55, null), Node(7, 66, 7), Node(6, 77, 6)),
3,
listOf(22, 44, 55)
),
Test(
listOf(Node(null, -123, null)),
0,
listOf(-123)
)
)

var f:(List<List<Int?>>,Int)-> Sequence<Int?> =
{g,S->generateSequence(generateSequence(S){g[it][0]}.last()){g[it][2]}.map{g[it][1]}}

fun main(args: Array<String>) {
    for ((input, start, result) in TEST) {
        val out = f(input.map { it.toList() }, start).toList()
        if (out != result) {
            throw AssertionError("$input $start $result $out")
        }
    }
}

```

## TIO

TryItOnline

# Answer
> 0 votes
# JavaScript ES6, ~~70~~ 63 Bytes

```
(x,i,a)=>(h=_=>i&&h(a(x[i].v),i=x[i].n))(x.map(_=>i=x[i].p||i))

```

Test case:

```
F([undefined,{p:0,v:12,n:2},{p:1,v:99,n:3},{p:2,v:37,n:0}],1,alert)

```

---
Tags: code-golf, data-structures
---


title: Is it a Pascal Prime?

text:
# Question
Title: Is it a Pascal Prime?
It is well known that odd primes will appear in Pascal's triangle exactly twice. However, not all numbers that appear exactly twice in Pascal's triangle are prime. We'll call these numbers Pascal primes.

Pascal primes are composite numbers that appear exactly twice in Pascal's triangle. The first few Pascal primes are

```
4, 8, 9, 12, 14, 16, 18, ...

```

Your challenge is to take a positive integer **n** as input and output true or false, depending on if **n** is a Pascal prime or not. This is code-golf, so the shortest program wins!

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

```
CompositeQ@#&&Binomial~Array~{#-1,#}~FreeQ~#&

```

Try it online!

Every composite number **n** appears exactly twice on row **n** and cannot appear afterwards. So the condition for Pascal primes is that they don't appear at all within the first **n-1** rows.

As far as I can tell, this is shorter than checking that it appears exactly twice within the first **n** rows and being able to use `!PrimeQ` instead.

# Answer
> 4 votes
# Jelly, ~~11~~ ~~10~~ 9 bytes

Thanks to:

* Martin Ender for -1 byte! (another approach, use  (+1) avoid using `n2` (-2), so -1 overall.
* Jonathan Allan for bug fix.
* Dennis for another -1 byte.

```
Ḷc€ḶFċ=ÆP

```

Try it online!

Alternative approach, by Jonathan Allan. (flawed)

```
----------- Explanation -----------
Ḷ            Lowered range. [0, 1, ..., n-1]
 c€Ḷ           `c`ombination `€`ach with `Ḷ`owered range [0...n-1]
    F        Flatten.
     ċ       Count the number of occurences of (n) in the list.
       ÆP    Returns 1 if (n) is a prime, 0 otherwise.
      =      Check equality.

```

Explanation for the last line:

* As pointed out by Martin Ender, "`n` appears twice in the Pascal triangle" is equivalent to "`n` doesn't appear in the first `n-1` rows".
* We want to return `true` if the number is not a prime (that is, `ÆP == 0`) and the count `c` is zero. From that we can deduce that `ÆP == c`.
It can be proven that if they are equal, then they are equal to 0, because:
    + `ÆP` return a boolean value, which can only be 0 or 1.
    + If it returns 1, then `n` is a prime, therefore it cannot appear in the first `n-1` lines (that is, `c == 0`)

# Answer
> 4 votes
# Python 2, 93 bytes

```
def f(n):l=[1];exec"(n in l)>=any(n%k<1for k in range(2,n))>q;l=map(sum,zip([0]+l,l+[0]));"*n

```

Try it online!

This is a named function **f**, which outputs via exit code, **0** for Pascal Primes, **1** otherwise.

### How this works?

```
def f(n):l=[1];                       # Define a function f (arg. n) and a list l = [1].
exec"..."*n                           # Execute n times.
(n in l)                              # Boolean: "n is in l?" is greater than...
   >=any(n%k<1for k in range(2,n))    # the boolean: "Is n composite?"?
            >q;                       # If the boolean comparison returns a falsy
                                      # result, then continue on without any difference.
                                      # Otherwise, evaluate the other part of the
                                      # inequality, thus performing "is greater than q".
                                      # Since we have no variable "q", this terminates
                                      # with exit code 1, throwing a "NameError".
l=map(sum,zip([0]+l,l+[0]));          # Generate the next row in Pascal's triangle,
                                      # By zipping l prepended with a 0 with l appended
                                      # with a 0 and mapping sum over the result.

```

This basically checks whether **n** occurs in the first **n - 1** rows of Pascal's triangle or if it is prime, and throws an error if any of these two conditions are met.

Saved 1 byte thanks to ovs.

# Answer
> 4 votes
# APL (Dyalog), ~~44~~ ~~34~~ ~~24~~ 19 bytes

*5 bytes saved thanks to @Cowsquack*

```
(~0∊⊢|⍨2↓⍳)⍱⊢∊⍳∘.!⍳

```

Try it online!

**How?**

We make sure that **neither does**

\- range `0` .. `n-1`,

`⍳∘.!` \- upon cartesian binomial with self

`⊢∊` \- contain `n`,

\- **nor does**

`⊢|⍨` \- `n` modulo each item of

`2↓⍳` \- range `2` .. `n-1`

`~0∊` \- not contain `0` (a.k.a non-divisible)

# Answer
> 4 votes
# Haskell, ~~86~~ 84 bytes

```
p=[]:[zipWith(+)(1:x)x++[1]|x<-p]
f n=all((>0).rem n)[2..n-1]==any(elem n)(take n p)

```

Try it online!

### Explanation

The function `p` recursively defines a degenerate Pascal's triangle:

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

```

As we can see (in this solution `1` is somewhat special) every number `n` appears exactly twice in the `n+1`th row and all elements of the subsequent rows only get bigger, thus we only need to check if `n` is somewhere up to the `n`th row to see if an element is disqualified:

```
any(elem n)(take(n-1)p)

```

Now we have `True` for all elements that appear more than twice (except `1`), so all we need is to have a faulty `isPrime` function that returns `True` for `1`:

```
all((>0).rem n)[2..n-1]

```

# Answer
> 2 votes
# JavaScript (Node.js), ~~103~~ 101 bytes

```
n=>(r=x=>[...Array(n).keys(F=n=>n>0?n*F(n-1):1)].every(x))(i=>r(j=>F(i)/F(j)/F(i-j)-n))>r(i=>i<2|n%i)

```

Try it online!

# Answer
> 2 votes
# Ruby, <sub>~~97~~</sub> 95 bytes

```
->n{c=!r=[1,1]
(2...n).map{|i|c|=1>n%i
[n]&r=[0,*r,0].each_cons(2).map{|a,b|a+b}}&[[n]]==[]&&c}

```

Try it online!

Scraped a couple bytes off.

# Answer
> 2 votes
# , 55 bytes

```
function(n)sum(!n%%1:n)>2&!n%in%outer(1:n-1,1:n,choose)

```

Try it online!

`sum(!n%%1:n)>2` is the composite test and `outer(1:n-1,1:n,choose)` computes rows `0` to `n-1` of Pascal's triangle, so we make sure `n` does not appear there.

# Answer
> 2 votes
# 05AB1E, 10 bytes

```
ÝDδcI¢IpÌQ

```

Try it online!

**Explanation**

```
Ý            # push range [0 ... input]
 D           # duplicate
  δc         # double vectorized command binomial
    I¢       # count occurrences of input
      Ip     # check input for primality
        Ì    # add 2
         Q   # compare for equality

```

Checks that `n` occurs exactly twice in the first **n+1** rows of pascals triangle and isn't prime.
The comparison works as there are no primes that can occur 3 times in the triangle.

# Answer
> 1 votes
# Haskell, 90 bytes

```
f n=2==sum[1|i<-[0..n],j<-[0..i],p[j+1..i]`div`p[1..i-j]==n,mod(p[1..n-1]^2)n<1]
p=product

```

Try it online!

# Answer
> 1 votes
# Pyth, 10 bytes

```
qP_Q/s.cRU

```

**Try it online!** or check the **Test suite.**

# Answer
> 1 votes
# JavaScript (Node.js), ~~79~~ ~~133~~ ~~130~~  128 bytes

```
f=(n,a=[1])=>n<a.length||[...'0'.repeat(n)].filter((x,i)=>n%i<1).length>1&&a.indexOf(n)<0&&f(n,[...a.map((x,i)=>x+a[i-1]||1),1])

```

Try it online!

evil prime checker +50 bytes :(

# Answer
> 0 votes
# Python 2, ~~105~~ 104 bytes

thanks to user202729 for -1 byte

```
a=q=[1];n=input();r=n<4;p=1
for i in range(2,n):q=a+map(sum,zip(q[1:],q))+a;r+=n in q;p*=n%i
print p+r<1

```

Try it online!

---
Tags: code-golf, math, number, decision-problem, primes
---


title: Compute the Optimal Square Matrix

text:
# Question
Title: Compute the Optimal Square Matrix
The **optimal matrix** (for the rather narrow scope of this challenge) is obtained by "zipping" the elements from the corresponding rows and columns of a square matrix and getting the maximum of each pair.

For instance, given the following matrix:

```
4 5 6
1 7 2
7 3 0

```

You can combine it with its transpose to get: `[[[4,5,6],[4,1,7]],[[1,7,2],[5,7,3]],[[7,3,0],[6,2,0]]]`. If you zip each pair of lists, you obtain the following: `[[(4,4),(5,1),(6,7)],[(1,5),(7,7),(2,3)],[(7,6),(3,2),(0,0)]]`. The last step is to get the maximum of each pair to get the optimal matrix:

```
4 5 7
5 7 3
7 3 0

```

Your task is to output the optimal matrix of a square matrix given as input. The matrix will only contain integers. I/O can be done in any reasonable format. The shortest code in bytes (either in UTF-8 or in the language's custom encoding) wins!

### Tests

```
[[172,29],[29,0]] -> [[172,29],[29,0]]
[[4,5,6],[1,7,2],[7,3,0]] -> [[4,5,7],[5,7,3],[7,3,0]]
[[1,2,3],[1,2,3],[1,2,3]] -> [[1,2,3],[2,2,3],[3,3,3]]
[[4,5,-6],[0,8,-12],[-2,2,4]] -> [[4,5,-2],[5,8,2],[-2,2,4]]

```

# Answer
> 7 votes
# Jelly, 2 bytes

```
»Z

```

Try it online!

### How it works

```
»Z  Main link. Argument: M (integer matrix)

 Z  Zip the rows of M, transposing rows and columns.
»   Take the maxima of all corresponding integers.

```

# Answer
> 5 votes
# Husk, ~~5~~ 4 bytes

Whoop, never got to use  before (or ):

```
S‡▲T

```

Try it online!

### Explanation

```
S  T -- apply the function to itself and itself transposed
 ‡▲  -- bi-vectorized maximum

```

# Answer
> 5 votes
# Haskell, 40 bytes

```
z(z max)<*>foldr(z(:))e
e=[]:e
z=zipWith

```

Try it online!

I would ungolf this as:

```
import Data.List
f m = zipWith (zipWith max) m (transpose m)

```

...which is so much more elegant.

# Answer
> 4 votes
# Octave, 13 bytes

```
@(A)max(A,A')

```

Try it online!

# Answer
> 4 votes
# MATL, 6 bytes

```
t!2$X>

```

Try it online!

**Explanation:**

```
t        % Duplicate the input.
!        % Transpose the duplicate.
2$X>     % Elementwise maximum of the two matrices.

```

# Answer
> 3 votes
# APL (Dyalog Unicode), 3 bytes

Anonymous tacit prefix function.

```
⊢⌈⍉

```

Try it online!

argument

ceiling'd with

transposed argument

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

```
m=>m.map((r,y)=>r.map((v,x)=>v>(k=m[x][y])?v:k))

```

### Test cases

```
let f =

m=>m.map((r,y)=>r.map((v,x)=>v>(k=m[x][y])?v:k))

console.log(JSON.stringify(f([[172,29],[29,0]]            ))) // -> [[172,29],[29,0]]
console.log(JSON.stringify(f([[4,5,6],[1,7,2],[7,3,0]]    ))) // -> [[4,5,7],[5,7,3],[7,3,0]]
console.log(JSON.stringify(f([[1,2,3],[1,2,3],[1,2,3]]    ))) // -> [[1,2,3],[2,2,3],[3,3,3]]
console.log(JSON.stringify(f([[4,5,-6],[0,8,-12],[-2,2,4]]))) // -> [[4,5,-2],[5,8,2],[-2,2,4]]
```

# Answer
> 2 votes
# Japt, ~~12~~ ~~10~~ 8 bytes

Look, Ma, no transposing or zipping!

```
£XËwUgEY

```

Try it

# Answer
> 2 votes
# , 4 bytes

Tacit prefix function.

```
>.|:

```

Try it online!

`>.` ceiling \[of the argument\] with

`|:` the transposed argument

# Answer
> 1 votes
# , 23 bytes

```
function(A)pmax(A,t(A))

```

Try it online!

This is equivalent to most other answers. However, R has two distinct `max` functions for the two common scenarios:

> `max` and `min` return the maximum or minimum of all the values present in their arguments, as integer if all are logical or integer, as double if all are numeric, and character otherwise.
>
> `pmax` and `pmin` take one or more vectors (or matrices) as arguments and return a single vector giving the ‘parallel’ maxima (or minima) of the vectors. The first element of the result is the maximum (minimum) of the first elements of all the arguments, the second element of the result is the maximum (minimum) of the second elements of all the arguments and so on. Shorter inputs (of non-zero length) are recycled if necessary.

# Answer
> 1 votes
# CJam, 8 bytes

```
{_z..e>}

```

Anonymous block (function) that takes the input from the stack and replaces it by the output.

**Try it online!** Or **verify all test cases**.

### Explanation

```
{      }    e# Define block
 _          e# Duplicate
  z         e# Zip
   .        e# Apply next operator to the two arrays, item by item
            e# (that is, to rows of the two matrices)
    .       e# Apply next operator to the two arrays, item by item
            e# (that is, to numbers of the two rows)
     e>     e# Maximum of two numbers

```

# Answer
> 1 votes
# C (gcc), ~~79~~ 77 bytes

* Saved two bytes thanks to Steadybox; only taking in one matrix dimension parameter as all matrices in this challenge are square.

```
j,i;f(A,n)int*A;{for(j=0;j<n*n;j++)printf("%d,",A[A[j]>A[i=j/n+j%n*n]?j:i]);}

```

Try it online!

Takes a flat integer array `A` and the matrix dimension `n` (as the matrix has to be square) as input. Outputs a flat integer array string representation to stdout.

# Answer
> 1 votes
# Clean, 58 bytes

```
import StdEnv,StdLib
@l=zipWith(zipWith max)(transpose l)l

```

I don't think this needs an explanation.

Try it online!

# Answer
> 1 votes
# Wolfram Language (Mathematica), 23 bytes

A port of my Pari/GP answer.

```
(#+#+Abs[#-#])/2&

```

is `\[Transpose]`.

Try it online!

# Answer
> 1 votes
# Julia 0.6, 13 bytes

`max.` applies the function `max` elementwise to it's arugments.

```
a->max.(a,a')

```

Try it online!

# Answer
> 0 votes
# Python 2, 45 bytes

```
lambda k:[map(max,*c)for c in zip(k,zip(*k))]

```

Try it online!

Thanks to totallyhuman for a few bytes saved.

# Answer
> 0 votes
# 05AB1E, 7 bytes

```
ø‚øεøεà

```

Try it online!

**Explanation**

```
ø         # transpose input matrix
 ‚        # pair with original matrix
  ø       # zip together
   ε      # apply on each sublist ([[row],[transposed row]])
    ø     # zip
     ε    # apply on each sublist (pair of elements)
      à   # extract greatest element

```

# Answer
> 0 votes
# Jelly, 7 bytes

```
żZZṀ€$€

```

Try it online!

# Answer
> 0 votes
# Mathematica, 30 bytes

*-8 bytes thanks to Jonathan Frech.*

```
Map@Max/@t/@t@{#,t@#}&
t=#&

```

Try it online!

# Answer
> 0 votes
# Pari/GP, 21 bytes

```
m->(m+m~+abs(m-m~))/2

```

Try it online!

---
Tags: code-golf, array, integer, matrix
---