title: Cycles on the torus

text:
# Question
Title: Cycles on the torus
# Challenge

This challenge will have you write a program that takes in two integers `n` and `m` and outputs the number non-intersecting loops on the `n` by `m` torus made by starting at `(0,0)` and only taking steps up and to the right. You can think of torus as the grid with wraparound both at the top and the bottom and on the sides.

This is so fewest bytes wins.

# Example

For example, if the input is `n=m=5`, one valid walk is

```
(0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (2,3) -> (2,4) ->
(2,0) -> (3,0) -> (4,0) -> (4,1) -> (4,2) -> (4,3) ->
(0,3) -> (1,3) -> (1,4) ->
(1,0) -> (1,1) -> (2,1) -> (3,1) -> (3,2) -> (3,3) -> (3,4) -> (4,4) ->
(0,4) -> (0,0)

```

as shown in the graphic.

Some example input/outputs

```
f(1,1) = 2 (up or right)
f(1,2) = 2 (up or right-right)
f(2,2) = 4 (up-up, up-right-up-right, right-right, right-up-right-up)
f(2,3) = 7
f(3,3) = 22
f(2,4) = 13
f(3,4) = 66
f(4,4) = 258

```

# Answer
> 4 votes
# Jelly, 28 bytes

```
ạƝ§=1Ȧ
²‘p/’ŒPÇƇḢÐṂ%⁸QƑƇṪÐṂL

```

A monadic Link accepting a list, `[m,n]`, which yields the count.

**TIO-jt1qe1v9** ...although there is little point, it's way too inefficient.
(I can't even run `[2,3]` locally with 16GB ram)!

### How?

Brute force - creates coordinates of a tiled version big enough then filters the power-set of these points to those paths with neighbours only increasing by one in a single direction, then filters to those starting at a minimal coordinate (i.e. the origin) and, at the same time, removes this start coordinate from each. Then uses modulo arithmetic to wrap back to a torus and filters out any containing duplicate coordinates (i.e. those containing intersections) and, finally, filters to those with minimal ending coordinates (i.e. ending back at the origin) and yields the result's length.

```
ạƝ§=1Ȧ - Link 1: all neighbours differ by 1 in exactly one direction
 Ɲ     - for neighbours:
ạ      -   absolute difference
  §    - sum each
   =1  - equal to one (vectorises)
     Ȧ - any and all? (falsey if empty or contains a falsey value when flattened)

²‘p/’ŒPÇƇḢÐṂ%⁸QƑƇṪÐṂL - Main Link: list of integers, [m,n]
²                     - square (vectorises) -> [m*m, n*n]
 ‘                    - increment (vectorises) -> [m*m+1, n*n+1]
   /                  - reduce with:
  p                   -   Cartesian product
    ’                 - decrement (vectorises) -> all the coordinates of an m*m by n*n grid
                      -                           including [0, 0] and [m*m, n*n]
     ŒP               - power-set -> all paths going either up OR right at each step, but not
                      -              necessarily by only 1, and
                      -              necessarily both up and right (e.g. [...[1,3],[5,7],[6,2],...])
        Ƈ             - filter keep those for which:
       Ç              -   call last Link (1) as a monad
                      -              ...now all remaining paths do only go in steps
                      -              of one up or one right
          ÐṂ          - filter keep those minimal under:
         Ḣ            -   head - removes the 1st coordinate from each and yields them for the filter
                      -          ...so only those which started at [0,0] but without it
            %⁸        - modulo by the left argument ([m,n]) (vectorises)
                Ƈ     - filter keep those for which:
               Ƒ      -   is invariant when:
              Q       -     de-duplicated
                      -          ...so no repetitions of torus coordinates (and we already removed
                      -          the first [0,0] which must be present exactly twice)
                  ÐṂ  - filter keep those minimal under:
                 Ṫ    -   tail
                      -          ...so only those which ended at [0,0]
                    L - length

```

# Answer
> 12 votes
# Python 2, 87 bytes

```
f=lambda m,n,z=0,l=[]:z==0if z in l else sum(f(m,n,(z+d)%m%(n*1j),l+[z])for d in(1,1j))

```

Try it online!

The interesting thing here is using a complex number `z` to store the coordinate of the current position. We can move up by adding `1` and move right by adding `1j`. To my surprise, modulo works on complex numbers in a way that lets us handle the wrapping for each dimension separately: doing `%m` acts on the real part, and `%(n*1j)` acts on the imaginary part.

# Answer
> 7 votes
# JavaScript (ES6), 67 bytes

This shorter version is derived from a Python 3.8 alternate version found by @xnor. However, this works only for \\$m\times n\<32\\$ in JS.

Takes input as `(m)(n)`.

```
m=>n=>(g=(k,l)=>l>>k&1?!k:g((k+m)%(m*n),l|=1<<k)+g(k-~k%m-k%m,l))``

```

Try it online!

To have it work for any input, we could use BigInts for **73 bytes**:

```
m=>n=>(g=(k,l=k)=>l&(b=1n<<k)?!k:g((k+m)%(m*n),l|=b)+g(k-~k%m-k%m,l))(0n)

```

Try it online!

---

# JavaScript (ES6),  ~~76 73~~  72 bytes

Takes input as `(m)(n)`.

```
m=>n=>(g=(x,y)=>g[x+=y*m]?!x:g(-~x%m,y,g[x]=1)+g(x%m,-~y%n)+--g[x])(0,0)

```

Try it online!

### Commented

```
m => n => (         // m = width; n = height
  g = (             // g is a recursive function taking:
        x, y        //   the current coordinates (x, y) on the torus
      ) =>          //
    g[              // the surrounding object of g is also used for storage
      x += y * m    // turn x into a key for the current coordinates
    ] ?             // if this cell was already visited:
      !x            //   return 1 if we're back to (0, 0), or 0 otherwise
    :               // else:
      g(            //   first recursive call:
        -~x % m,    //     move to the right
        y,          //     leave y unchanged
        g[x] = 1    //     mark the current cell as visited by setting the flag g[x]
      ) +           //   add the result of
      g(            //   a second recursive call:
        x % m,      //     restore x in [0...m-1]
        -~y % n     //     move up
      ) +           //
      --g[x]        //   clear the flag on the current cell
)(0, 0)             // initial call to g with (x, y) = (0, 0)

```

# Answer
> 3 votes
## Haskell, ~~88~~ 80 bytes

```
n#m|let(x!y)a|elem(x,y)a=0^(x+y)|b<-(x,y):a=(mod(x+1)n!y)b+(x!mod(y+1)m)b=0!0$[]

```

Try it online!

Simple brute force: try all up/right combinations, dropping those which intersect (we keep all positions we've visited in list `a`) and counting those which eventually hit positition `(0,0)` again.

The base case of the recursion is when we visit a position a second time (`elem(x,y)a`). The result is `0^0` = `1` when the position is `(0,0)` and counts towards the numbers of loops or `0` (`0^x`, with `x` non-zero) otherwise and doesn't increase the number of loops.

Edit: -8 bytes thanks to @xnor.

# Answer
> 2 votes
# Jelly, 44 bytes

```
×ƝṪ2*Ḥ_2Rḃ€2ċⱮØ½%³¬ẠƲƇịØ.Ṛ,Ø.¤ZÄZ%€ʋ€³ŒQẠ$€S

```

Try it online!

Works for 4,4, but has complexity \\$O({2^m}^n)\\$ so won’t scale that well.

This works by finding all possible routes of up to \\$mn\\$ length, filtering out those that don’t end at 0,0, and then excluding those that pass the same point twice.

# Answer
> 1 votes
# Java 8, 120 bytes

```
n->m->g(n,m,0,0);int g(int n,int m,int k,int l){return(l>>k)%2>0?k<1?1:0:g(n,m,(k+m)%(m*n),l|=1<<k)+g(n,m,k-~k%m-k%m,l);}

```

Port of *@Arnauld*'s JavaScript answer, and also only works for inputs where \\$n\*m\<32\\$.

Try it online.

# Answer
> 1 votes
# Jelly, ~~54~~ 39 bytes

```
ḣ2æ.2ị³¤+4
‘Ç;¥¦%³Ç=4ƊÑÇị$?
çⱮØ½S
’Ñ0xÇ

```

Try it online!

I’ve posted this as a separate answer to my other Jelly one because it’s a completely different method. This is closer in principle to @Arnauld’s answer. It uses a recursive function that works through every possible path until it reaches a point it’s already got to, and then returns the result of a check whether it’s back to the start. I suspect a few more bytes could be shaved off. Now changed to using slice operator. It works well for up to 5x5. The recursion depth should be at most m x n.

# Answer
> 1 votes
## CJam (50 chars)

```
q~]:M:!a{9Yb2/\f{_W=@.+M.%a+_)a#g"WAR"=~}}:R~e_We=

```

Online demo. This is a program which takes two inputs from stdin.

Finally we have an answer to the question

> War, huh, what is it good for?

---

### Dissection

```
q~]:M        e# Parse input, collect in array, store in M (for moduli)
:!a          e# Zero and wrap in array for starting position (0, 0)
{            e# Define recursive block R
  9Yb2/      e#   Push [[1 0][0 1]], an array of movements
  \f{        e#   For each of those movements, with the current path,
    _W=@.+   e#     Add the movement to the last position in the path
    M.%      e#     Apply the wrapping
    a+       e#     Add to one copy of the path
    _)a#     e#     And find its index in another copy
    g"WAR"=~ e#     Switch on the sign of the index:
             e#       If the sign is -1, position not found, make a recursive call
             e#       If the sign is 0, found at start, push -1 to the stack
             e#       If the sign is 1, we have a self-intersection. We push 10 to
             e#       the stack for no other reason than to make the bad joke above
  }
}:R
~            e# Execute R
e_We=        e# Count the -1s which we pushed as sentinels

```

---
Tags: code-golf, combinatorics, grid, topology
---


# Question
Title: Compare four integers, return word based on maximum
This function should take four integer inputs (`a`,`b`,`c`,`d`) and return a binary word based on which values equal the maximum of the four.

The return value will be between `1` and `0xF`.

For example:

`a = 6, b = 77, c = 1, d = 4`

returns `2` (binary `0010`; only 2nd-least significant bit is set corresponding to `b` being sole max value)

`a = 4, b = 5, c = 10, d = 10`

returns `0xC` (binary `1100`; 3rd- and 4th-least significant bits set corresponding to `c` and `d` equaling max value)

`a = 1, b = 1, c = 1, d = 1`

returns `0xF` (binary `1111`; all four bits set because all values equal the max)

Here is a simple implementation:

```
int getWord(int a, int b, int c, int d)
{
    int max = a;
    int word = 1;
    if (b > max)
    {
        max = b;
        word = 2;
    }
    else if (b == max)
    {
        word |= 2;
    }
    if (c > max)
    {
        max = c;
        word = 4;
    }
    else if (c == max)
    {
        word |= 4;
    }
    if (d > max)
    {
        word = 8;
    }
    else if (d == max)
    {
        word |= 8;
    }
    return word;
}

```

return value can be string of 0's and 1's, bool / bit vector, or integer

# Answer
> 9 votes
# Jelly, 2 bytes

Takes input as `[d,c,b,a]`. Returns a list of Booleans.

```
Ṁ=

```

Try it online!

**M**aximum

`=` equal to (implies the other argument is the original argument; vectorises)

# Answer
> 5 votes
# , 17 bytes

```
max(a<-scan())==a

```

Try it online!

Returns a vector of booleans. Since this output has been confirmed, this is preferable over numerical output, as that one is almost twice longer:

### , 33 bytes

```
sum(2^which(max(a<-scan())==a)/2)

```

Try it online!

# Answer
> 4 votes
# APL (Dyalog Unicode), 4 bytesSBCS

Anonymous tacit prefix function. Takes `[a,b,c,d]` as argument. Returns a bit-Boolean array.\*

```
⌈/=⌽

```

Try it online!

`⌈/` Does the maximum of the argument

`=` equal (vectorises)

the reverse of the argument?

* Note that APL stores arrays of Booleans using one bit per value, so this does indeed return a 4-bit word, despite the display form being `0 0 1 0`.

# Answer
> 3 votes
# Haskell, ~~20~~ 18 bytes

*2 bytes saved thanks to proud haskeller*

```
map=<<(==).maximum

```

Try it online!

# Answer
> 2 votes
# 05AB1E, ~~3~~ 2 bytes

```
ZQ

```

Input as a list of `[d,c,b,a]`, output as a list of boolean.

Try it online or verify all test cases.

**Explanation:**

```
Z    # Take the maximum of the implicit input-list
 Q   # Check for each in the (implicit) input-list if it equals this value
     # (and output implicitly as result)

```

# Answer
> 2 votes
# Perl 6, 12 bytes

```
{$_ X==.max}

```

Try it online!

Anonymous code block that takes a list of integers and returns a list of booleans. If we need to return as a number, it's +4 bytes to wrap the inside of the code block with `2:[...]`.

### Explanation:

```
{          }  # Anonymous code block
 $_           # With the input
    X==       # Which values are equal
       .max   # To the maximum element

```

# Answer
> 2 votes
# Japt, 5

```
m¶Urw

```

Try it!

-4 bytes thanks to @Oliver!
-2 bytes thanks to @Shaggy!

Input is a 4-element array in the following format:

```
[d, c, b, a]

```

Output is an array of bits.

# Answer
> 2 votes
# x86 machine code (MMX/SSE1), 26 bytes (4x int16\_t)

# x86 machine code (SSE4.1), 28 bytes (4x int32\_t or uint32\_t)

# x86 machine code (SSE2), 24 bytes (4x float32) or 27B to cvt int32

(The last version that converts int32 to float isn't perfectly accurate for large integers that round to the same float. With float input, rounding is the caller's problem and this function works correctly if there are no NaNs, identifying floats that compare == to the max. The integer versions work for all inputs, treating them as signed 2's complement.)

All of these work in 16/32/64-bit mode with the same machine code.

A stack-args calling convention would make it possible to loop over the args twice (finding max and then comparing), possibly giving us a smaller implementation, but I haven't tried that approach.

x86 SIMD has vector-\>integer bitmap as a single instruction (`pmovmskb` or `movmskps` or pd), so it was natural for this even though MMX/SSE instructions are at least 3 bytes long. SSSE3 and later instructions are longer than SSE2, and MMX/SSE1 instructions are the shortest. Different versions of `pmax*` (packed-integer vertical max) were introduced at different times, with SSE1 (for mmx regs) and SSE2 (for xmm regs) only having signed word (16-bit) and unsigned byte.

(`pshufw` and `pmaxsw` on MMX registers are new with Katmai Pentium III, so really they require SSE1, not just the MMX CPU feature bit.)

This is callable from C as `unsigned max4_mmx(__m64)` with the i386 System V ABI, which passes an `__m64` arg in `mm0`. (Not x86-64 System V, which passes `__m64` in `xmm0`!)

```
   line         code bytes
    num  addr
     1                         global max4_mmx
     2                             ;; Input 4x int16_t in mm0
     3                             ;; output: bitmap in EAX
     4                             ;; clobbers: mm1, mm2
     5                         max4_mmx:
     6 00000000 0F70C8B1           pshufw    mm1, mm0, 0b10110001   ; swap adjacent pairs
     7 00000004 0FEEC8             pmaxsw    mm1, mm0
     8
     9 00000007 0F70D14E           pshufw    mm2, mm1, 0b01001110   ; swap high/low halves
    10 0000000B 0FEECA             pmaxsw    mm1, mm2
    11
    12 0000000E 0F75C8             pcmpeqw   mm1, mm0               ; 0 / -1
    13 00000011 0F63C9             packsswb  mm1, mm1               ; squish word elements to bytes, preserving sign bit
    14
    15 00000014 0FD7C1             pmovmskb  eax, mm1          ; extract the high bit of each byte
    16 00000017 240F               and       al, 0x0F          ; zero out the 2nd copy of the bitmap in the high nibble
    17 00000019 C3                 ret

size = 0x1A = 26 bytes

```

If there was a `pmovmskw`, what would have saved the `packsswb` and the `and` (3+2 bytes). We don't need `and eax, 0x0f` because `pmovmskb` on an MMX register already zeros the upper bytes. MMX registers are only 8 bytes wide, so 8-bit AL covers all the possible non-zero bits.

**If we knew our inputs were non-negative, we could `packsswb mm1, mm0`** to produce non-negative signed bytes in the upper 4 bytes of `mm1`, avoiding the need for `and` after `pmovmskb`. **Thus 24 bytes.**

x86 pack with signed saturation treats the input and output as signed, so it always preserves the sign bit. (https://www.felixcloutier.com/x86/packsswb:packssdw). Fun fact: x86 pack with unsigned saturation still treats the *input* as signed. This might be why `PACKUSDW` wasn't introduced until SSE4.1, while the other 3 combinations of size and signedness existed since MMX/SSE2.

---

Or with 32-bit integers in an XMM register (and `pshufd` instead of `pshufw`), every instruction would need one more prefix byte, except for `movmskps` replacing the pack/and. But `pmaxsd` / `pmaxud` need an extra extra byte...

**callable from C as `unsigned max4_sse4(__m128i);`** with x86-64 System V, or MSVC vectorcall (`-Gv`), both of which pass `__m128i`/`__m128d`/`__m128` args in XMM regs starting with `xmm0`.

```
    20                         global max4_sse4
    21                             ;; Input 4x int32_t in xmm0
    22                             ;; output: bitmap in EAX
    23                             ;; clobbers: xmm1, xmm2
    24                         max4_sse4:
    25 00000020 660F70C8B1         pshufd    xmm1, xmm0, 0b10110001   ; swap adjacent pairs
    26 00000025 660F383DC8         pmaxsd    xmm1, xmm0
    27
    28 0000002A 660F70D14E         pshufd    xmm2, xmm1, 0b01001110   ; swap high/low halves
    29 0000002F 660F383DCA         pmaxsd    xmm1, xmm2
    30
    31 00000034 660F76C8           pcmpeqd   xmm1, xmm0               ; 0 / -1
    32
    33 00000038 0F50C1             movmskps  eax, xmm1          ; extract the high bit of each dword
    34 0000003B C3                 ret

size = 0x3C - 0x20 = 28 bytes

```

Or if we accept input as `float`, we can use SSE1 instructions. The `float` format can represent a wide range of integer values...

Or if you think that's bending the rules too far, start with a 3-byte `0F 5B C0 cvtdq2ps xmm0, xmm0` to convert, making a 27-byte function that works for all integers that are exactly representable as IEEE binary32 `float`, and many combinations of inputs where some of the inputs get rounded to a multiple of 2, 4, 8, or whatever during conversion. (So it's 1 byte smaller than the SSE4.1 version, and works on any x86-64 with just SSE2.)

If any of the float inputs are NaN, note that `maxps a,b` exactly implements `(a<b) ? a : b`, keeping the element from the 2nd operand on unordered. So it might be possible for this to return with a non-zero bitmap even if the input contains some NaN, depending on where they are.

**`unsigned max4_sse2(__m128);`**

```
    37                         global max4_sse2
    38                             ;; Input 4x float32 in xmm0
    39                             ;; output: bitmap in EAX
    40                             ;; clobbers: xmm1, xmm2
    41                         max4_sse2:
    42                         ;    cvtdq2ps  xmm0, xmm0
    43 00000040 660F70C8B1         pshufd    xmm1, xmm0, 0b10110001   ; swap adjacent pairs
    44 00000045 0F5FC8             maxps     xmm1, xmm0
    45
    46 00000048 660F70D14E         pshufd    xmm2, xmm1, 0b01001110   ; swap high/low halves
    47 0000004D 0F5FCA             maxps     xmm1, xmm2
    48
    49 00000050 0FC2C800           cmpeqps   xmm1, xmm0               ; 0 / -1
    50
    51 00000054 0F50C1             movmskps  eax, xmm1          ; extract the high bit of each dword
    52 00000057 C3                 ret

size = 0x58 - 0x40 = 24 bytes

```

copy-and-shuffle with `pshufd` is still our best bet: `shufps dst,src,imm8` reads the input for the low half of `dst` *from* `dst`. And we need a non-destructive copy-and-shuffle both times, so 3-byte `movhlps` and `unpckhps`/pd are both out. If we were narrowing to a scalar max, we could use those, but it costs another instruction to broadcast before compare if we don't have the max in all elements already.

---

Related: SSE4.1 `phminposuw` can find the position and value of the minimum `uint16_t` in an XMM register. I don't think it's a win to subtract from 65535 to use it for max, but see an SO answer about using it for max of bytes or signed integers.

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

Takes input as `([d,c,b,a])`. Returns 4 Boolean values.

```
a=>a.map(x=>x==Math.max(...a))

```

Try it online!

# Answer
> 1 votes
# Java (JDK), 78 bytes

```
a->{int m=a[0],w=1,p=1;for(int t:a){w=t<m?w:p|(t>m?(m=t)^m:w);p*=2;}return w;}

```

Try it online!

* Takes the input as an array of `[a,b,c,d]`.

# Answer
> 1 votes
Here's a JS version that outputs as binary

update: Shorter with join, and without the lookup:

# JavaScript (Node.js), 42 bytes

```
a=>a.map(x=>+(x==Math.max(...a))).join('')

```

Try it online!

Previous, with lookup, 49 bytes

```
a=>a.map(x=>[0,1][+(x==Math.max(...a))]).join('')

```

Try it online!

Previous, with reduce, 52 bytes:

```
a=>a.reduce((y,x)=>y+[0,1][+(x==Math.max(...a))],'')

```

Try it online!

```
fa=>a.map(x=>+(x==Math.max(...a))).join('')
console.log(f([ 4, 1,77, 6])) // 0010
console.log(f([10,10, 5, 4])) // 1100
console.log(f([ 1, 1, 1, 1])) // 1111
```

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

```
n=>n.Select(a=>a==n.Max())

```

Try it online!

Takes input in format `[d,c,b,a]`. All the others down below take input as `[a,b,c,d]`

# C# (Visual C# Interactive Compiler), 35 bytes

```
n=>n.Select((a,b)=>n[3-b]==n.Max())

```

Returns an `IEnumerable<bool>`.

Try it online!

# C# (Visual C# Interactive Compiler), 39 bytes

```
n=>n.Select((a,b)=>n[3-b]==n.Max()?1:0)

```

Returns an `IEnumerable<int>`, which represent bits.

Try it online!

# C# (Visual C# Interactive Compiler), 49 bytes

```
n=>{for(int i=4;i-->0;Write(n[i]==n.Max()?1:0));}

```

Prints a binary string to STDOUT.

Try it online!

# Answer
> 1 votes
# Python 3.8 (pre-release), 67 bytes

Lambda function that takes in 4 integers, bit shifts the boolean result of their comparison to the maximum value with some help from Python 3.8's new assignment operator, and returns the bitwise OR of the results

```
lambda a,b,c,d:((m:=max(a,b,c,d))==d)<<3|(m==c)<<2|(m==b)<<2|(a==m)

```

Try it online!

# Answer
> 1 votes
# Ruby, ~~34~~ 22 bytes

Takes input as an array `[d, c, b, a]` and returns an array of 1s and 0s.

```
->r{r.map{|e|e/r.max}}

```

Try it online!

# Answer
> 1 votes
## Python 3, ~~59 bytes~~ 66 bytes

```
def f(l):
 n=max(a)
 for i in 0,1,2,3:a[i]=a[i]==n
 return a[::-1]

```

Try it online!

Takes input as `[a,b,c,d]` and outputs a list of booleans.

Edited to be a proper function, then saved 2 bytes by removing brackets around the conditional.

# Answer
> 1 votes
# 1. Python 3.5, 90 bytes

Takes sequence of numbers as parameters. Returns "binary" string

```
import sys;v=[*map(int,sys.argv[1:])];m=max(v);s=""
for e in v:s=str(int(e==m))+s
print(s)

```

example:

```
$ ./script.py 6 77 1 4 77
10010

```

## Explanation

```
import sys
# convert list of string parameters to list of integers
v=[*map(int,sys.argv[1:])]
# get max
m=max(v)
# init outstring
s=""
# walk through list
for e in v:
    # prepend to outstring: int(True)=>1, int(False)=>0
    s=str(int(e==m))+s
# print out result
print(s)

```

# Answer
> 0 votes
# C# (Visual C# Interactive Compiler), 51 bytes

```
x=>{for(int m=x.Max(),i=4;i-->0;)x[i]=x[i]==m?1:0;}

```

Try it online!

Above is an anonymous function that outputs by modifying an argument. Output is an array of 1's and 0's.

Below is a recursive function that outputs an integer.

# C# (Visual C# Interactive Compiler), 60 bytes

```
int f(int[]x,int i=3)=>i<0?0:2*f(x,i-1)|(x[i]==x.Max()?1:0);

```

Try it online!

Both functions take input as a 4-element array.

```
[d, c, b, a]

```

# Answer
> 0 votes
# PHP, 54 bytes

```
while($i<4)$argv[++$i]<max($argv)||$r+=1<<$i-1;echo$r;

```

or

```
while($i<4)$argv[++$i]<max($argv)||$r+=1<<$i;echo$r/2;

```

take input from command line arguments. Run with `-nr` or try them online.

# Answer
> 0 votes
# Python 2, 35 bytes

```
lambda i:[int(x==max(i))for x in i]

```

Try it online!

Takes input in the format \[d,c,b,a\] as with the accepted answer from Adám so I guess it is OK.

Alternative for 41 if it's not...

# Python 2, 41 bytes

```
lambda i:[int(x==max(i))for x in i][::-1]

```

Try it online!

# Answer
> 0 votes
# Python 3, 42 bytes

```
f=lambda a:list(map(lambda x:x==max(a),a))

```

Simply returns a list of whether the element is the max for each element in the input. -2 bytes if you don't count the `f=` assignment.

Try it online!

# Answer
> 0 votes
## Batch, 92 bytes

```
@set m=%1
@set f=@for %%i in (%*)do @
%f%set/a"m=m+(m-=%%i)*(m>>31)
%f%cmd/cset/a!(m-%%i)

```

Takes arguments as command-line parameters in reverse order. Works by arithmetically calculating the maximum of the parameters by reducing over them and adding on only positive differences from the running maximum, then mapping over each parameter again this time comparing it to the maximum. Conveniently `cmd/cset/a` doesn't output a newline, so the results are automatically concatenated together. The `%f%` simply saves 5 bytes on what would be a repeated construct.

---
Tags: code-golf, bitwise
---


title: Tips for golfing in Raku

text:
# Question
Title: Tips for golfing in Raku
What general tips do you have for golfing in Raku? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Raku (e.g. "remove comments" is not an answer). Please post one tip per answer.

# Answer
Avoid `sub` literals. In many cases, you can simply use `{}` for code blocks. For example, don't write the following code.

```
sub ($a){$a*2}

```

Instead, use blocks syntax. This also lets you to use `$_`, `@_`, and `%_` placeholder variables, if you only need a single variable. If you need more, you can use `$^a`, `$^b` variables, and so on.

```
{$_*2}

```

Also, in certain rare cases, it's possible to use whatever code (especially when you have simple expressions). The `*` replaces the placeholder argument.

```
* *2

```
> 9 votes

# Answer
Raku has a really bizarre feature where it allows *all* Unicode characters in categories **Nd**, **Nl**, and **No** to be used as rational number literals. Some of these are shorter than writing their numeric values out in ASCII:

* `¼` (2 bytes) is shorter than `.25` or `1/4` (3 bytes).
* `¾` (2 bytes) is shorter than `.75` or `3/4` (3 bytes).
* (3 bytes) is shorter than `1/16` (4 bytes).
* (4 bytes) is shorter than `11/12` (5 bytes).
* (4 bytes) is shorter than `216e3` (5 bytes).
* (4 bytes) is shorter than `432e3` (5 bytes).
> 9 votes

# Answer
Learn the functions to read the input. Raku has many interesting functions that can easily read the input from ARGV, or STDIN (if nothing was specified on ARGV), which can shorten your code if used correctly. If you call them as filehandle methods, you can force them to work on particular filehandle (useful if you for example read from `STDIN`, but you have to read arguments on ARGV).

# `get`

This function gets a single line, and automatically chomps it, so you don't have to. This is useful if you need to read just a one line.

# `lines`

This function gets all lines from the file or STDIN. It's a lazy list, so if you use it with `for`, it will only read what you need. For example.

```
say "<$_>"for lines

```

# `slurp`

This will read the entire file or STDIN, and will return the result as a single string.
> 8 votes

# Answer
**Warning**: Wall of text approaching. It's a lot of small tricks I gathered over time.

# Write your solutions as anonymous blocks

This was mentioned already but I'd like to reiterate it. In TIO, you can write `my $f =` into the header, the block into the code proper, and start the footer with a `;`. This seems to be by far the shortest way to get the job done (since you don't need to care about reading any input, it's given to you in the arguments).

Another nice way is using the `-n` or the `-p` switch, but I didn't find a way to make it work in TIO.

# Use the colon syntax for passing arguments

That is, instead of `thing.method(foo,bar)`, you can do `thing.method:foo,bar` and save 1 character. Unfortunately, you can't call another method on the result for obvious reasons, so it makes sense to use only for the last method in a block.

# Use `$_` as much as you can

Sometimes it's better to take a single list argument than several separate arguments because of this. When accessing `$_`, you may call methods on it just by starting with a dot: e. g. `.sort` is equal to `$_.sort`.

However, bear in mind that each block gets its own `$_`, so the parameters of the outer block won't propagate into the inner ones. If you need to access the parameters of the main function from an inner block, ...

# Use the `^` variables if you can't use `$_`

Insert a `^` between the sigil and the variable name, like this: `$^a`. These work only inside a block. The compiler first counts how many of these you have in the block, sorts them lexicographically, and then assigns the first argument to the first one, the second to the second one and so on. The `^` needs to be used only in the first occurrence of the variable. So `{$^a - $^b}` takes 2 scalars and subtracts them. The only thing that matters is the alphabetical order, so `{-$^b + $^a}` does the same thing.

If you ever feel like using the pointy block syntax (like `->$a,$b {$a.map:{$_+$b}}`), you're far better off writing bogus statement at the start of the block using the `^` for each argument you're not going to use in the main block (like `{$^b;$^a.map:{$_+$b}}`) (Note that better way to golf this is `{$^a.map(*+$^b)}`. I just wanted to show off the concept.)

# Read through the operator docs carefully

The operators are very powerful and often they're the shortest way to get things done. Especially the meta-operators (operators that take operators as an argument) `[]`, `[\]`, `X`, `<<`/`>>` and `Z` are worth of your attention. Don't forget that a meta-op can take another meta-op as an argument (like a `XZ%%` I managed to use here). You can use `>>` for a method call too, which can be a lot cheaper than a map (`@list>>.method` instead of `@list.map(*.method)`, but beware, *they're not same!*). And, finally, before you use a binary `<< >>`, bear in mind that `Z` will often do the same thing in much fewer characters.

If you heap a lot of meta-ops onto each other, you can specify precedence using square brackets `[]`. That will save you when you pile up so many operators that it confuses the compiler. (That doesn't happen very often.)

Finally, if you need to coerce things to Bool, Int or Str, don't use the methods `.Bool`, `.Int` and `.Str`, but rather the operators `?`, `+` and `~`. Or even better, just put them into an arithmetic expression to force them into Int and so on. The shortest way to get the length of a list is `+@list`. If you want to calculate 2 to the power of the length of a list, just say `2**@list` and it will do The Right Thing.

# Use the free state variables `$`, `@` and `%`

In each block, every occurence of `$` (or `@` or `%`) refers to a shiny new scalar (or array, or hash) state variable (a variable whose value persists across calls to the block). If you need a state variable that needs to be referenced *only once* in the source code, these three are your big friends. (Most often the `$`.) For instance, in the Reverse Math Cycles challenge, it could be used to choose the operators cyclically from an array, which was indexed by `$++%6`.

# Use the sub forms of `map`, `grep` et al.

That means: do rather `map {my block},list` than `list.map({my block})`. Even if you manage to use `list.map:{my block}`, these two approaches come out at the same number of bytes. And often, you would need to parenthesize the list when calling a method, but not when calling a sub. So the sub approach comes out always better or at least the same as the method one.

The only exception here is when the object which is to be `map`ped, `grep`ped and so on, is in `$_`. Then `.map:{}` obviously beats `map {},$_`.

# Use junctions (`&` and `|`) instead of `&&` and `||`.

Obviously, they are 1 byte shorter. On the other hand, they must be collapsed by being forced into a boolean context. This can be always done with a `?`. Here you should be aware of a meta-op `!`*`op`* which forces bool context, uses *`op`* and negates the result.

If you have a list and you want to turn it into a junction, don't use `[&]` and `[|]`. Instead use `.any` and `.all`. There is also `.none` which cannot be so easily mimicked by the junction ops.
> 5 votes

# Answer
# Reduce the space used for variables

There's a few parts to this.

### Remove whitespace

Variables declared using `my` can usually be declared without the space between `my` and the variable name. `my @a` is equivalent to `my@a`.

### Use sigil-less variables

You can declare variables using a backslash to remove the sigil before the variable name, like so:

```
my \a=1;

```

(unfortunately you can't remove the space :( )

This is useful as you can then refer to them as just the bare variable name later.

```
 a=5;
 a.say

```

Basically this saves bytes if you use the variable more than once elsewhere in your code. The downside is that the variable needs to be initialised.

### Use `$!` and `$/`

These pre-declared variables are usually used for exceptions and regex matches respectively, but don't need to be defined using `my`.

```
$!=1;
$/=5;

```

Especially useful is using `$/` as an array and using the shortcuts `$` followed by a number to access that element of the `$/` array;

```
$/=100..200;
say $5;  #105
say $99; #199

```
> 5 votes

# Answer
## Use `...` instead of `first`

Typically, if you want to find the first number that matches some condition `&f`, you can represent it like:

```
first &f,1..*

```

However, instead you can use the `...` operator:

```
+(1...&f)

```

If you have to start from `0`, you can have `-1` afterwards instead of `+`.

If you want the index of the first element in a list `@a` that has condition `&f`, normally you do:

```
first &f,@a,:k

```

Instead:

```
(@a...&f)-1

```

(or vice-versa if you want 0 indexed). In the same way, you can get all the elements up to the first one that passes the condition.

Downsides to this is that the list *has* to pass the condition at some point, otherwise the `...` operator will try to extrapolate off the end of the list, and most likely throw an error. You also can't use Whatever code in the left hand side, since it would be interpreted as part of the sequence.
> 3 votes

---
Tags: code-golf, tips
---


# Question
Title: A poly-moly-holy quine. (Well, it's not, but the title's cool.)
This is an answer chaining puzzle, where each answer must add on to the last.

The \\$n\\$th submission must output its own source code in the \\$n\\$th language and the \\$n−1\\$ languages before it.

A language can be either a dialect or a major version of a language, so Python version 2.121 is only counted as version 2 and Common Lisp and Clojure are considered different languages. This excludes compiler flags.

You can post 2 answers in a row, but have to use different languages.

The winner of this puzzle is the person to submit the second-to-last quine if there have been no new quines for a week. The aim of this puzzle is to go on as long as it can, so if you want the green tick, you'll have to respect that.

Have fun.

# Answer
> 6 votes
# \>\<\>, 187 bytes

```
var s=1
<0?"":"var s=1{0}<0?{1}{1}:{1}{3}{1};Write(s,(char)10,(char)34,(char)39,s)//.1+d*fao;!?l{1}var s=1{1}ar*3dr{2}";Write(s,(char)10,(char)34,(char)39,s)//.1+d*fao;!?l"var s=1"ar*3dr'

```

Try it online!

Try C# Online

Let's add a 2D language, why not?

# Answer
> 4 votes
# C# (Visual C# Interactive Compiler), 63 bytes

```
var s="var s={0}{1}{0};Write(s,(char)34,s)";Write(s,(char)34,s)

```

Just to start it off.

Try it online!

---
Tags: quine, polyglot, answer-chaining
---


title: The Highest Dice

text:
# Question
Title: The Highest Dice
## Challenge:

Here we have the first 100 items of a sequence:

```
6,5,4,3,2,1,66,65,64,63,62,61,56,55,54,53,52,51,46,45,44,43,42,41,36,35,34,33,32,31,26,25,24,23,22,21,16,15,14,13,12,11,666,665,664,663,662,661,656,655,654,653,652,651,646,645,644,643,642,641,636,635,634,633,632,631,626,625,624,623,622,621,616,615,614,613,612,611,566,565,564,563,562,561,556,555,554,553,552,551,546,545,544,543,542,541,536,535,534,533,...

```

How is this sequence formed? We first have the number in the range `[6, 1]` (all possible values of a single die from highest to lowest). We then have the numbers `[66..61, 56..51, 46..41, 36..31, 26..21, 16..11]` (all possible concatted values of two dice from highest to lowest). Etc.
This is related to the OEIS sequence A057436: *Contains digits 1 through 6 only*, but with all the numbers with equal amount of digits sorted backwards in the sequence.

The challenge is to choose one of these three options for your function/program with the sequence above:

1. Take an input \\$n\\$ and output the \\$n\\$'th value of this sequence, where it can be either 0-indexed or 1-indexed.
2. Take an input \\$n\\$ and output the first \\$n\\$ or \\$n+1\\$ values of this sequence.
3. Output the values from the sequence indefinitely.

Of course, any reasonable output format can be used. Could be as strings/integers/decimals/etc.; could be as an (infinite) list/array/stream/etc.; could be output with space/comma/newline/other delimiter to STDOUT; etc. etc. **Please state what I/O and option you're using in your answer!**

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code (i.e. TIO).
* Also, adding an explanation for your answer is highly recommended.

**Here some larger test cases if you choose option 1:**

```
n         0-indexed output    1-indexed output

500       5624                5625
750       4526                4531
1000      3432                3433
9329      11111               11112
9330      666666              11111
9331      666665              666666
10000     663632              663633
100000    6131232             6131233

```

# Answer
# Jelly, 5 bytes

```
ḃ6ạ7V

```

Try it online!

1-indexed nth value.
> 2 votes

# Answer
# Perl 6, ~~24~~ 23 bytes

*-1 byte thanks to nwellnhof*

```
{.put;.[]X~(6...1)}...*

```

Try it online!

Outputs the sequence infinitely separated by spaces/newlines. Or, for a few more bytes we can have a lazy infinite list we can index into instead.

# Perl 6, 27 bytes

```
{flat {@=.[]X~(6...1)}...*}

```

Try it online!

### Explanation:

```
{                         }    # Anonymous code block
 flat                          # Return the flattened
                      ...*       # Infinite sequence
      {              }             # Defined as
         .[]                       # The previous element arrayified
            X~                     # Each concatenated with
              (6...1)              # All of 6 to 1
       @=                          # Arrayified

```
> 12 votes

# Answer
# Python 2, ~~39~~ ~~38~~ 34 bytes

```
f=lambda n:n and-n%6+1+f(~-n/6)*10

```

Try it online!

Outputs 1-indexed number
> 6 votes

# Answer
# Bash, 31 bytes

```
f()(x+={6..1};eval echo $x;f);f

```

TIO

update from comments, the n'th value 1-indexed, +GNU tools + perl, 64 bytes, 7 bytes saved thanks to @manatwork

```
dc<<<6o$1p|perl -pe 's/(.)0/($1-1).6/e?redo:s/0//'|tr 1-6 654321

```

64 bytes
> 6 votes

# Answer
# , 43 bytes

```
p='';repeat cat(p<-sapply(p,paste0,6:1),'')

```

Try it online!

Prints the sequence indefinitely

* -9 thanks to @Kirill L.
> 6 votes

# Answer
# MATL, 11 bytes

```
`6:P!V@Z^DT

```

Outputs the values indefinitely.

Try it online!

### Explanation

```
`      % Do...while
  6:   %   Push [1 2 3 4 5 6]
  P    %   Flip: gives [6 5 4 3 2 1]
  !    %   Transpose: turns the row vector into a column vector
  V    %   Convert the number in each row to the corresponding char
  @    %   Push current iteration index, starting from 1
  Z^   %   Cartesian power. Gives a matrix where each row is a Cartesian tuple
  D    %   Display immediately
  T    %   Push true. This is used as loop condition, to give an infinite loop
       % End (implicit)

```
> 5 votes

# Answer
# JavaScript (ES6), 26 bytes

Returns the \\$n\\$th term, 1-indexed.

```
f=n=>n--&&[f(n/6|0)]+6-n%6

```

Try it online!
> 5 votes

# Answer
# Haskell, ~~38~~ 34 bytes

An infinite list of numbers:

```
d=[6,5..1]
l=d++[10*m+n|m<-l,n<-d]

```

Try it online!

Two earlier solutions that give infinite lists of strings, each using 38 bytes:

```
[1..]>>=sequence.(`replicate`"654321")

```

Try it online!

```
do n<-[1..];mapM id$[1..n]>>["654321"]

```

Try it online!
> 5 votes

# Answer
# Haskell, 28 bytes

```
l=(+).(10*)<$>0:l<*>[6,5..1]

```

Try it online!

Produces an infinite list of numbers `l`. Using `<$>` and `<*>` cuts a byte off:

**29 bytes**

```
l=[10*n+d|n<-0:l,d<-[6,5..1]]

```

Try it online!

The approach is similar to the Haskell Output All String answer fixed input string "654321", and skipping the empty string output by changing where it's prepended.

**30 bytes**

```
l=[n++[d]|n<-"":l,d<-"654321"]

```

Try it online!
> 5 votes

# Answer
# 05AB1E, 10 bytes

Outputs the sequence indefinitely.

```
¸[6LRâJD»,

```

Try it online!

**Explanation**

```
¸           # initialize the stack with a list containing the empty string
 [          # loop
  6L        # push [1 ... 6]
    R       # reverse
     â      # cartesian product
      J     # join each inner list
       D    # duplicate (saving a copy for next iteration)
        »,  # join on newline and print

```
> 4 votes

# Answer
# Perl 5, ~~40~~ 37 bytes

-3bytes thanks to @Xcali

```
map{say}<"$_">while s//{6,5,4,3,2,1}/

```

37 bytes

40 bytes
> 4 votes

# Answer
# Java (JDK), 48 bytes

```
String f(int n){return n-->0?f(n/6)+(6-n%6):"";}

```

Try it online!

This returns the 1-indexed nth element.

Recursion seems to beat the iterative lambda.

---

### Iterative version, 49 bytes

```
n->{var r="";for(;n-->0;n/=6)r=6-n%6+r;return r;}

```

Try it online!
> 3 votes

# Answer
# C# (.NET Core), 38 bytes

```
int f(int n)=>n-->0?f(n/6)*10+6-n%6:0;

```

Try it online!

Outputs the n-th value (1-based).
> 3 votes

# Answer
# Brachylog, ~~13~~ 11 bytes

*Thanks to Fatalize for 2 bytes*

```
6~d{⟧₁∋}ᵐẉ⊥

```

Outputs indefinitely. Try it online!

Here's a 14-byte version that outputs the first \\$n\\$ values: Try it online!

### Explanation

```
6~d           Start with a number, all of whose digits are 6's
              Brachylog considers these in the order 6, 66, 666, 6666...
   {   }ᵐ     Map this predicate to each of those digits:
    ⟧₁         1-based reverse range: [6,5,4,3,2,1]
      ∋        The output digit must be a number in that range
              Brachylog considers possible outputs in this order: 6, 5, 4, 3, 2, 1, 66, 65...
         ẉ    Write a possible output with newline
          ⊥   Force the predicate to fail and backtrack to the next possibility

```
> 3 votes

# Answer
# Japt, 14 bytes

There's gotta be a shorter solution using function methods and/or Cartesian product but (for now?) the best I can manage is a port of Arnauld's JS solution so be sure to upvote him too.

```
©ß´Uz6)s+6-Uu6

```

Try it or test terms `0-1000`
> 2 votes

# Answer
# Wolfram Language (Mathematica), ~~88~~ 78 bytes

```
(l=d=c=7-Range@6;While[Length@c<#,d=Flatten[(10#+l)&/@d];c=c~Join~d;];c[[#]])&

```

Try it online!

saved 4 + 6 bytes thanks to @IanMiller

List is 1 indexed, outputs the n'th number.
> 2 votes

# Answer
# Mathematica, 56 bytes

```
Flatten[FromDigits/@Tuples[7-Range@6,#]&/@Range@#][[#]]&

```

Requires excessive amounts of memory to actually run as it creates all numbers in the sequence which have length equal to or less than the input (i.e. it creates \\$\frac{6}{5}(6^n-1)\\$ terms) then takes the required value from the list. For practice use replace the second last # with a specific value for the length you want to use it on.
> 2 votes

# Answer
# Pip `-l`, 16 bytes

```
x:YP6-,6W1PxCP:y

```

Outputs the sequence indefinitely. Try it online!

### Explanation

The `-l` flag means that lists are printed with each item on its own line; if an item is itself a list, its elements are concatenated with no separator. E.g. the list `[1 [2 3] [4 [5 6]]]` would be printed as

```
1
23
456

```

With that cleared up:

```
x:YP6-,6W1PxCP:y
      ,6          Range(6): [0 1 2 3 4 5]
    6-            Subtract each element from 6: [6 5 4 3 2 1]
  YP              Yank that value into the y variable, and also print it
x:                Assign that value also to x
        W1        While 1 (infinite loop):
           xCP:    Assign to x the cartesian product of x with
               y   the list [6 5 4 3 2 1]
          P        Print it

```

After the first loop iteration, `x` looks like `[[6;6];[6;5];[6;4];...;[1;1]]`; after the second iteration, `[[[6;6];6];[[6;6];5];[[6;6];4];...;[[1;1];1]]`; and so on. We don't need to worry about flattening the sublists, because `-l` effectively does it for us.
> 1 votes

# Answer
# Charcoal, 18 bytes

```
ＮθＷθ«←Ｉ⊕﹪±θ⁶≔÷⊖θ⁶θ

```

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

```
Ｎθ

```

Input `n`

```
Ｗθ«

```

Repeat until `n` is zero.

```
←Ｉ⊕﹪±θ⁶

```

Reduce `-n` modulo `6`, then increment the result and output from right to left.

```
≔÷⊖θ⁶θ

```

Decrement `n` and integer divide it by `6`.
> 1 votes

# Answer
# Retina 0.8.2, 36 bytes

```
.+
$*_
+`(_*)\1{5}(_+)
$1$.2
T`7-1`d

```

Try it online! Link includes test cases. 1-indexed. Explanation:

```
.+
$*_

```

Convert to unary. (Retina 1 would save 2 bytes here.)

```
+`(_*)\1{5}(_+)
$1$.2

```

Convert to bijective base 6 by repeated divmod. Note that the use of `+` means that the extracted digit is always a number from 1 to 6 instead of 0 to 5 for regular base 6 conversion. (`(_{6})*` is faster but costs bytes extracting the quotient.)

```
T`7-1`d

```

Transpose the digits so that the 6s come first and the 1s last. (There are no 7s or 0s but this allows me to use the `d` shortcut.
> 1 votes

# Answer
# Cubix, 22 bytes

This will output the sequence indefinitely. The general idea is that it has a base number which 6 - 1 is added to. For each add the result is output multiplied by 10, which is pushed to the bottom of the stack to be used later in the sequence. The base is then popped and the next base started.

```
..w.06+ONo*w;|uW!(pq;;

```

Try it online!

```
    . .
    w .
0 6 + O N o * w
; | u W ! ( p q
    ; ;
    . .

```

Watch It Run
> 1 votes

# Answer
# C# (.NET Core), infinite printing, ~~181 180~~ 88 bytes.

~~```
string[] s=new string[]{" "},t;int i,j,k,l=1;while(true){j=l;t=new string[l=6*j];for(i=6;i>0;i--)for(k=(6-i)*j;k<l;)t[k]=i+s[k++%j];
for(k=0;k<l;)System.Console.Write(t[k++]);s=t;}

```
Sadly it freezes repl.it instead of outputting properly in the infinite version as written (I believe it to be an error in repl.it, as it does not output as the program loops like it should), so anyone hoping to test needs a computer. If you add a read at the front of the loop it works in repl.it as well.
Outputs to the console, obviously.
~~

~~On any finite system the code will most likely eventually crash with an out of memory error.~~

Reworked the code to use @dana 's lambda.

```
int f(int n)=>n-->0?f(n/6)*10+6-n%6:0;for(int i=0;++i>0;)System.Console.Write(f(i)+" ");

```

Try it online!
> 1 votes

# Answer
# Forth (gforth), 63 bytes

```
: f recursive dup 6 < if 6 - abs 1 .r else 6 /mod 1- f f then ;

```

Try it online!

0-indexed outputs nth value

### Explanation

If N is less than 6, output the absolute value of N - 6. Otherwise, get the quotient and remainder of dividing N by 6. Call the function recursively on the quotient, then call it on the remainder.

### Code Explanation

```
: f                 \ start a new word definition
  recursive         \ declare that this word is recursive so we can call it from itself
  dup 6 <           \ check if n is less than 6
  if                \ if it is:
    6 - abs 1 .r    \ subtract 6, get the absolute value, then print with no appended space
  else              \ else if it's greater than 6:
    6 /mod          \ get the quotient and remainder of dividing n by 6
    1-              \ subtract 1 from the quotient (because we're 0-indexed)
    f               \ call f on the result
    f               \ call f on the remainder (shortcut to format and print, it's always < 6)
  then              \ end the if/else
;                   \ end the word definition

```
> 1 votes

# Answer
# APL(NARS), 27 chars, 54 bytes

```
{0>⍵-←1:0⋄(6-6∣⍵)+10×∇⌊⍵÷6}

```

traslate the solution by dana https://codegolf.stackexchange.com/a/179980 in APL... test:

```
  f←{0>⍵-←1:0⋄(6-6∣⍵)+10×∇⌊⍵÷6}
  f 500
5625
  f¨750 1000 9329 9331 10000 100000
4531 3433 11112 666666 663633 6131233
  f¨⍳9
6 5 4 3 2 1 66 65 64

```
> 1 votes

# Answer
# C#, print from start to n, ??? bytes

Credit to @dana for the lambda expression.

```
int f(int n)=>n-->0?f(n/6)*10+6-n%6:0;for(int i=0;i<int.Parse(a[0]);)System.Console.Write(f(++i)+" ");

```

Operation: Run with command line 0th argument equal to the integer you want to count to. (It should be noted that `a[0]` is a reference to the otherwise unmentioned command line args array, and I don't know how to count it.)
> 0 votes

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


title: Who is the tallest?

text:
# Question
Title: Who is the tallest?
N children, with no two sharing their exact size, are lined up in some order. Each can only compare heights with their immediate neighbours. When the teacher shouts "raise hands if you are the tallest", they do so if they are taller than both their neighbours, and they do so simultaneously. If only one raises their hand, he wins. If more than one raise their hands, they are all eliminated from the row (preserving the order of the rest of the children) and they repeat the process.

Write a program, which takes an array of distinct integers (you can assume they are strictly positive) and outputs the winner of this game. This is code-golf, so the shortest code wins.

Examples (with intermediate stages shown):

**5** 3 **9** 8 7 → 3 **8** 7 → 8

1 2 **9** 4 → 9

**9** 3 **8** 7 4 **12** 5 → 3 **7** 4 **5** → 3 **4** → 4

---

Current leaders:

1. Jelly: 17 bytes \[by Dennis♦\]
2. MATL: 20 bytes \[by Luis Mendo\]
3. APL: 28 bytes \[voidhawk\]
4. k: 40 bytes \[by Paul Kerrigan\]

There's also a battle of Pythons going on. Still waiting for more golfing languages to show up.

I currently accepted Dennis♦'s answer - if there are new winners, I'll update the selection.

# Answer
> 4 votes
# Jelly, 17 bytes

```
j@N»3\=x@ḟ@ḢṖ?µ¬¿

```

Input is a comma-separated string of integers.

Try it online!

*Credits go to @Xanderhall, @Sherlock, and @ErikGolfer for laying the groundwork.*

### How it works

```
j@N»3\=x@ḟ@ḢṖ?µ¬¿ Main link: Argument: A (integer or list of integers)

               ¬¿ While the logical NOT of A (0 for a positive integer, a non-empty
                  array for a non-empty array) is truthy:
              µ     Execute the chain of links to the left.
  N                   Negative; multiply all integers in A by -1.
j@                    Join -A, separating by A. This prepends and appends a
                      negative to A and appends more integers that will be ignored.
   »3\                Compute the maxima of all overlapping slices of length 3.
      =               Compare the maxima with the elements of A, yielding 1 or 0.
       x@             Repeat the elements of A, 1 or 0 times.
                      This ignores Booleans without a counterpart in A.
            Ṗ?        If the popped result is truthy, i.e., if it has at least two
                      elements:
         ḟ@             Filter/remove those elements from A.
                      Else:
           Ḣ            Head; extract the (only) element of the return value.

```

# Answer
> 10 votes
# JavaScript (ES6), ~~78~~ ~~76~~ 72 bytes

*Thanks to @edc65 for -4 bytes*

```
f=a=>a.map((c,i)=>(p>c|c<a[i+1]?q:r).push(p=c),p=q=[],r=[])&&r[1]?f(q):r

```

Takes in an array of integers and outputs an array containing only the winner.

### Test snippet

```
f=a=>a.map((c,i)=>(p>c|c<a[i+1]?q:r).push(p=c),p=q=[],r=[])&&r[1]?f(q):r

g=a=>a?console.log("Input:",`[${a}]`,"Output:",f(a.map(Number))+""):console.error("Invalid input")

g([5,3,9,8,7])
g([1,2,9,4])
g([9,3,8,7,4,12,5])
```

```
<input id=I value="9 1 8 2 7 3 6 4 5"><button onclick="g(I.value.match(/\d+/g))">Run</button>
```

Here are a few other attempts, using `.filter` and array comprhensions:

```
f=a=>(q=a.filter((c,i)=>p>(p=c)|c<a[i+1]||0*r.push(c),p=r=[]))&&r[1]?f(q):r
f=a=>(r=a.filter((c,i)=>p<(p=c)&c>~~a[i+1]||0*r.push(c),p=q=[]))[1]?f(q):r
f=a=>[for(c of(i=p=q=[],r=[],a))(p>c|c<a[++i]?q:r).push(p=c)]&&r[1]?f(q):r
f=a=>(q=[for(c of(i=p=r=[],a))if(p>(p=c)|c<a[++i]||0*r.push(c))c])&&r[1]?f(q):r

```

Or a double for-loop, horribly long:

```
a=>eval("for(r=[,1];r[1]&&(p=i=q=[],r=[]);a=q)for(c of a)(p>c|c<a[++i]?q:r).push(p=c));r")

```

### Explanation

The way this works is pretty simple: it builds an array of those who are relatively taller (`r`) and an array of those that aren't (`q`), then returns `r` if it only has one item; if not, it runs itself on `q` and returns the result of that.

# Answer
> 8 votes
# MATL, 20 bytes

```
`tTYadZSd0<~&)nq}x2M

```

Input is a column vector, using `;` as separator.

Try it online! Or verify all test cases.

### Explanation

This is a direct implementation of the procedure described in the challenge. A `do`...`while` loop keeps removing elements until only one has been removed; and that one is the output.

The elements to be removed are detected by taking differences, signum, then differences again. Those that give a negative value are the ones to be removed.

```
`        % Do...while
  t      %   Duplicate. Takes input (implicit) the first time
  TYa    %   Append and prepend a zero
  d      %   Consecutive differences
  ZS     %   Signum
  d      %   Consecutive differences
  0<~    %   Logical mask of non-negative values: these should be kept
  &)     %   Split array into two: those that should kept, then those removed
  nq     %   Size minus 1. This is used as loop condition. The loop will exit
         %   if this is 0, that is, if only one element was removed
}        % Finally (i.e. execute at the end of the loop)
  x      %   Delete array of remaining elements
  2M     %   Push last element that was removed
         % End (implicit)
         % Display (implicit)

```

# Answer
> 4 votes
# Python3, ~~265~~ ~~260~~ ~~248~~ ~~243~~ ~~203~~ ~~121~~ ~~117~~ ~~112~~ 111 bytes

```
def T(I):
 b=[0];q=[];J=b+I+b
 for i,x in enumerate(I):[q,b][J[i]<x>J[i+2]]+=x,
 return len(b)<3and b[1]or T(q)

```

Thank you @ZacharyT, @orion, and @mathmandan for saving ~~5~~ ~~45~~ a lot of bytes!

# Answer
> 2 votes
## Mathematica, 107 108 bytes

```
(For[x=y=#,Length@y>1,x=DeleteCases[x,#|##&@@y],y=Intersection[Max@@@x~Split~Less,#&@@@Split[x,#>#2&]]];y)&

```

**Explanation**

First, set `x` and `y` equal to the input `List`. The loop continues until `Length@y==1`. `x~Split~Less` is the list of lists of consecutive, increasing elements, `Split[x,#>#2&]` is the list of lists of consecutive, decreasing elements. Taking the `Max` of all of the lists in the former gives the list of children taller than the child to their right (along with the right-most child). Taking the first argument (`#&`) of all of the lists in the latter gives the list of children taller than the child to their left (along with the left-most child). The intersection of these two will be the list of children who raised their hand. Set this equal to `y`. `x=DeleteCases[x,#|##&@@y]` removes from `x` any elements matching an element of `y` (`#|##&` is equivalent to `Alternatives`). Once the loop terminates, return `y`. If the output must be an integer (rather than a list containing a single integer), return `#&@@y` (+4 bytes).

Thanks to Martin Ender for saving 2 bytes and making me comply with the rules. Open to suggestions.

# Answer
> 2 votes
## Haskell, 85 bytes

```
import Data.List
f x=(#)=<<(x\\)$[b|a:b:c:_<-tails$0:x++[0],b<a||b<c]
[s]#_=s
_#i=f i

```

Usage example: `f [9,3,8,7,4,12,5]` -\> `4`.

How it works:

```
f x =                            -- main function with parameter x
         [b|                  ]  -- make a list of all b
            a:b:c:_              -- where b is the second element of all lists with
                                 -- at least 3 elements
             <- tails $ 0:x++[0] -- drawn from the tails of x with a 0 pre- and
                                 -- appended (tails [1,2,3] -> [1,2,3],[2,3],[3],[])
               ,b<a||b<c         -- and b is not greater than its neighbors
   (#)=<<(x\\)                   -- feed the list difference of x and that list
                                 -- and the list itself to the function #

[s]#_s                           -- if the list difference is a singleton list,
                                 -- return the element
_#i=f i                          -- else start over with the list of b's

```

A variant, also 85 bytes:

```
import Data.List
f x|n<-[b|a:b:c:_<-tails$0:x++[0],b<a||b<c]=last$f n:[s|[s]<-[x\\n]]

```

Bind the list of `b` (see above) to n and return the element `s` if `x\\n` is a singleton list and `f n` otherwise.

# Answer
> 1 votes
## Python 2, ~~100~~ 98 bytes

```
def f(A):
 t=[0];l=[];a=b=0
 for c in A+[0]:[l,t][a<b>c]+=[b];a,b=b,c
 return t[-2]and f(l)or t[1]

```

Uses the short-circuiting return as in Yodle's answer (by Zachary T)

# Answer
> 1 votes
# Perl 6, 111 bytes

```
{(@_,{(($/=(0,|@$_,0).rotor(3=>-2).classify({+so .[1]>.[0,2].all})){1}>1??$/{0}!!$/{1})».[1]}...*==1)[*-1][0]}

```

## Expanded:

```
{  # bare block lambda with implicit parameter list ｢@_｣

  (                                    # generate a sequence
    @_,                                # starting with the input

    {   # code block used to get the next value in the sequence
        # which has implicit parameter ｢$_｣

        (
          (

            $/ =   # store in ｢$/｣ for later use

            ( 0, |@$_, 0 )             # the input with 0s before and after
            .rotor( 3 => -2 )          # take 3 at a time, back up 2, repeat
            .classify({
              +                        # Numify the following:
              so                       # simplify the following Junction
              .[1] > .[ 0, 2 ].all     # is the middle larger than its neighbors
            })

          ){1}                         # look at the values where it is true
          > 1                          # is there more than 1?

        ??                             # if so
          $/{ 0 }                      # look at the false ones instead

        !!                             # otherwise
          $/{ 1 }                      # look at the true ones

      )».[1]                           # undo the transformation from ｢.rotor｣
    }

    ...                                # keep doing that until

    * == 1                             # there is only one value
  )\
  [ * - 1 ]                            # the last value of the sequence
  [ 0 ]                                # make it a singular value ( not a list )

}

```

# Answer
> 0 votes
# Mathematica, 101 bytes

```
If[Equal@@(a=Position[Max/@Partition[#,3,1,{2,2},0]-#,0]),#[[Last@a]],#0@Fold[Drop@##&,#,Reverse@a]]&

```

Unnamed recursive function taking a list of numbers as input, and returning a list with a single number (the winner) as output.

The core of the algorithm is `Max/@Partition[#,3,1,{2,2},0]`, which computes the array of (the-max-of-me-and-my-neighbors)s from the input list. `a=Position[...-#,0]` then subtracts the original list and returns where the 0s are; these are the hand-raising children.

`If[Equal@@a, #[[Last@a]], #0@Fold[Drop@##&,#,Reverse@a]]&` branches depending on whether all the elements of `a` are equal or not (in this case, they will be only if `a` is a singleton); if so, then this child is the winner and we output her number; if not, then we recursively call this function on the list with all elements at positions in `a` removed.

# Answer
> 0 votes
# Python 2, 99 Bytes

```
def f(l):k=[x[0]for x in zip(l,[0]+l,l[1:]+[0])if(max(x),)>x];return(len(k)+2>len(l))*max(l)or f(k)

```

# Answer
> 0 votes
# PHP, 131 bytes

```
$r=$a=$argv;for(;$r[1];$a=array_values(array_diff($a,$r))){$r=[];foreach($a as$i=>$x)if($x>$a[$i-1]&$x>$a[$i+1])$r[]=$x;}echo$r[0];

```

Takes numbers from command line arguments. Fails if filename starts with a positive number.

**breakdown**

```
// import (and init $r[1])
$r=$a=$argv;
// while more than 1 raised hand, remove them from data
for(;$r[1];$a=array_values(array_diff($a,$r)))
{
    // reset hands
    $r=[];
    // raise hands
    foreach($a as$i=>$x)
        if($x>$a[$i-1]&$x>$a[$i+1])$r[]=$x;
}
// output
echo$r[0];

```

# Answer
> 0 votes
# k, 40 bytes

```
{$[1=+/B:(|>':|x)&>':x;x@&B;.z.s x@&~B]}

```

Explanation:
$ is an if-else.
The condition is whether 1 is the sum of B, which is defined as the minimum of two lists generated by checking if x is greater than the prior and post-positions (Pipe is reverse).
If this is true we return x where B is true.
Otherwise we recurse without the true positions.

# Answer
> 0 votes
# Scala 129 bytes

## Golfed

```
def x(a:List[Int]):Int={val (y,n)=(0+:a:+0).sliding(3).toList.partition(l=>l.max==l(1));if(y.length>1)x(n.map(_(1)))else y(0)(1)}

```

## Ungolfed

```
def whoIsTallest(a: List[Int]): Int = {
  val (handUp, handDown) = (0 +: a :+ 0).sliding(3).toList.partition {
    case x :: y :: z :: Nil => y > x && y > z
  }
  if (handUp.length > 1)
    whoIsTallest(handDown.map(_(1)))
  else
    handUp.head(1)
}

```

By padding the list left and right with 0's, can then group in sets of 3 and partition the list for those where the hand is up, the left and right most elements compare to 0 on the outside so get the correct number (assuming nobodys height is negative!)

# Answer
> 0 votes
# C++14, 182 bytes

```
#define P .push_back(c[i]);
int f(auto c){decltype(c)t,s;int i=0;(c[0]>c[1]?t:s)P for(;++i<c.size()-1;)(c[i-1]<c[i]&&c[i]>c[i+1]?t:s)P(c[i-1]<c[i]?t:s)P return t.size()<2?t[0]:f(s);}

```

Learned that the ternary operator can be used with C++ objects. Requires the input to be a random access container with `push_back`, like `vector`, `deque` and `list`.

Creates two containers `t` and `s` of the same type and appends the local tallest to `t` and the rest to `s`. If there is only 1 element in `t` return that one, otherwise recursive call itself with `s`.

Ungolfed:

```
int f(auto c){
  decltype(c)t,s;
  int i=0;
  (c[0]>c[1] ? t : s).push_back(c[i]);
  for(;++i<c.size()-1;)
    (c[i-1]<c[i]&&c[i]>c[i+1] ? t : s).push_back(c[i]);
  (c[i-1]<c[i] ? t : s).push_back(c[i]);
  return t.size()<2 ? t[0] : f(s);
}

```

# Answer
> 0 votes
**R, 83 bytes**

Two different versions:

This one takes a vector N:

```
while(T){Z=diff(sign(diff(c(0,N,0))))<0;if(sum(Z)>1)N=N[!Z]else{print(N[Z]);break}}

```

This one creates a function F defined recursively:

```
F=function(N){Z=diff(sign(diff(c(0,N,0))))<0;if(sum(Z)>1)F(N[!Z])else return(N[Z])}

```

# Answer
> 0 votes
# APL (Dyalog Unicode), 28 bytesSBCS

```
{1=≢⍸s←⍵=3⌈/∊0⍵0:s/⍵⋄∇⍵/⍨~s}

```

Try it online!

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


title: Sort a list of Numbers as letters

text:
# Question
Title: Sort a list of Numbers as letters
So, you have a random list (random meaning it doesn't matter what order it is in) of numbers with a length of `n`, where n is a positive integer smaller than 1000 and larger than 1.

The random list must contain every number from `0 to (n - 1)`. Eg: \[0, 3, 2, 5, 1, 4\] (where n is 6).

**Note: If there is more than one digit you do not translate like English - 11 is not "eleven", it is "one one".**

Your task is to sort these numbers, but there are some difference to normal sorting:

1. You **have** to sort them as if they were the numbers expressed as words, in alphabetical order, but you cannot replace the numbers with letters \[1\]
2. At any given time, the list must contain exactly the same numbers in the exact quantities as the original list, you cannot add or remove any

**Test Cases**

```
n = 6
[0, 3, 2, 5, 1, 4] = [5, 4, 1, 3, 2, 0] (sorted like this but not this - ["five", "four", "one", "three", "two", "zero"])
n = 8
[0, 3, 7, 2, 5, 1, 6, 4] = [5, 4, 1, 7, 6, 3, 2, 0] (sorted like this but not this - ["five", "four", "one", "seven", "six", "three", "two", "zero"])

```

This is `code-golf`, so the smallest answer in **bytes** wins.

\[1\]: You may create another list to do the sorting, but the original list must have the same contents at all times

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

```
#~SortBy~IntegerName&

```

there is also a message that shouldn't be there

Try it online!

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


title: How many steps did I walk?

text:
# Question
Title: How many steps did I walk?
A simple pedometer can be modeled by a pendulum with two switches on opposite sides—one at x=0 and one at x=***l***. When the pendulum contacts the far switch, the ambulator can be assumed to have taken half a step. When it contacts the near switch, the step is completed.

Given a list of integers representing positions of the pendulum, determine the number of full steps recorded on the pedometer.

### Input

* An integer ***l***\>0, the length of the track.
* A list of integers representing the positions of the pedometer's pendulum at each time.

### Output

The number of full steps measured. A step is taken when the pendulum contacts the far switch (x\>=l) and then the near switch (x\<=0).

### Test cases

```
8, [8, 3, 0, 1, 0, 2, 2, 9, 4, 7]
1

```

The pendulum immediately makes contact with the far switch at x=8 at t=0. Then it touches the near switch at t=2 and t=4, completing one step. After that, it touches the far switch again at x=9 at t=8, but it never touches the near switch again.

```
1, [1, 5, -1, -4, -1, 1, -2, 8, 0, -4]
3

15, [10, -7, -13, 19, 0, 22, 8, 9, -6, 21, -14, 12, -5, -12, 5, -3, 5, -15, 0, 2, 11, -11, 12, 5, 16, 14, 27, -5, 13, 0, -7, -2, 11, -8, 27, 15, -10, -10, 4, 21, 29, 21, 2, 5, -7, 15, -7, -14, 13, 27]
7

7, [5, 4, 0]
0

7, [5, 8, 6, 1, 2]
0

```

# Answer
## CJam, ~~27~~ 24 bytes

```
l~:Xfe<0fe>_[XT]:Y--Y/,(

```

Input format is the list of pendulum positions followed by `l` on a single line.

Test it here.

### Explanation

```
l~     e# Read and evaluate input.
:X     e# Store track length in X.
fe<    e# Clamp each position to X from above.
0f>    e# Clamp each position to 0 from below.
_      e# Duplicate.
[XT]   e# Push the array [X 0].
:Y     e# Store it in Y.
-      e# Set subtraction from the clamped input list. This gives all the
       e# intermediate values.
-      e# Another set subtraction. Remove intermediate values from input list.
Y/     e# Split remaining list around occurrences of ...X 0...
,(     e# Count them and decrement. This is the number of times the pendulum
       e# moved from X to 0.

```
> 4 votes

# Answer
# MATL, 22 bytes

```
>~2G0>~-XzY'nw1)0<-H/k

```

This uses current version (14.0.0) of the language/compiler.

Inputs are in the same order and format as in the challenge, separated by a newline.

**Try it online!**

### Explanation

```
>~     % take the two inputs implicitly. Generate an array that contains true
       % where the second input (array of positions) is >= the first input (l)
2G     % push second input (positions) again
0      % push a 0
>~     % true where the second input (array of positions) is <= 0
-      % subtract: array of 1, -1 or 0
Xz     % discard the 0 values
Y'     % run-length encoding: push values and number of repetitions
n      % length of the latter array: number of half-steps, perhaps plus 1
w1)    % swap. Get first element
0<     % true if that element is -1. We need to discard one half-step then
-      % subtract
H/k    % divide by 2 and round down

```
> 2 votes

# Answer
# Javascript ES6 57 bytes

```
(t,a)=>a.map(a=>a<t?a>0?'':0:1).join``.split`10`.length-1

```

Thanks @NotThatCharles for -4
> 1 votes

# Answer
# Perl, 28 bytes

Includes +1 for `-p`

Run with the input as one long line of space separated integers on STDIN, the first number is the length:

```
perl -p steps.pl <<< "8 8 3 0 1 0 2 2 9 4 7"

```

`steps.pl`:

```
s; ;$'>=$_..$'<1;eg;$_=y;E;

```

Uses the perl flip-flop operator and counts the number of times it returns to false
> 1 votes

# Answer
# Pyth, 18 bytes

```
/.:@J,Q0m@S+Jd1E2J

```

Test suite

Explanation:

```
/.:@J,Q0m@S+Jd1E2J
                      Implicit: Q is the length of the track.
    J,Q0              Set J to [Q, 0]
        m      E      Map over the list
           +Jd        Add the current element to J
          S           Sort
         @    1       Take the middle element.
                      This is the current element,
                      clamped above by Q and below by 0.
   @J                 Filter for presence in J.
 .:             2     Form 2 element substrings
/                J    Count occurrences of J.

```
> 1 votes

# Answer
# Ruby, 42

```
->i,a{r=!0
a.count{|v|r^r=v>=i||r&&v>0}/2}

```

`r` starts as `false`. We toggle `r` at each end of the track, and add it to our count. Then, halve the count (rounding down) to get the number of steps.
> 0 votes

# Answer
# Python 3, 82

Saved 2 bytes thanks to DSM.

Not super golfed yet.

```
def f(x,s):
 c=l=0
 for a in s:
  if a>=x:l=x
  elif a<1:c+=l==x;l*=l!=x
 return c

```

Test cases:

```
assert f(8, [8, 3, 0, 1, 0, 2, 2, 9, 4, 7]) == 1
assert f(1, [1, 5, -1, -4, -1, 1, -2, 8, 0, -4]) == 3
assert f(15, [10, -7, -13, 19, 0, 22, 8, 9, -6, 21, -14, 12, -5, -12, 5, -3, 5, -15, 0, 2, 11, -11, 12, 5, 16, 14, 27, -5, 13, 0, -7, -2, 11, -8, 27, 15, -10, -10, 4, 21, 29, 21, 2, 5, -7, 15, -7, -14, 13, 27]) == 7

```
> 0 votes

# Answer
# Retina, 34

```
-1*

^(1*)((?>.*?\1.*? \D))*.*
$#2

```

Try it online! or try it with decimal input.

Takes input in unary, negative unary numbers are treated as `-111...` and zero is the empty string. Counts the number of times that the first number appears followed by a zero. Uses an atomic group to guarantee that the matches are minimal (sadly atomic groups are non-capturing so it has to be wrapped in another group...).
> 0 votes

# Answer
## Clojure, 64 bytes

```
#(count(re-seq #"10"(apply str(for[i %2](condp > i 1 0 %""1)))))

```

Maps values less-than-or-equal of zero to `0`, larger-than-or-equal of length to `1` and others to an empty string `""`. This is then concatenated to a string and occurrences of `"10"` are counted.
> 0 votes

# Answer
# APL (Dyalog Unicode), 17 bytesSBCS

Also known as "how much can I abuse iota-underbar?"

```
≢∘∪0~⍨(⍸≤)⍸(⍸0≥⊢)

```

Try it online!
> 0 votes

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


title: Black Hole challenge from codewars

text:
# Question
Title: Black Hole challenge from codewars
I came across this challenge from codewars. I wish to know how to solve this problem. The problem description is given below.

Its elements are in range\[1..n^2\]. The matrix is filled by rings, from the outwards the innermost. Each ring is filled with numbers in the following way:

1. The first number is written in the top left corner;
2. The second number is written in the top right corner;
3. The third number is written in the bottom right corner;
4. The fourth number is written in the bottom left corner;
5. Each next number is written next to the number written 4 steps before it, until the ring is filled.

The matrix is constructed when all numbers are written.\`\`\` Given the size of the hole, return the number written at (`a, b`) - you may use any consistent indexing, but please specify if (`a, b`) is anything other than 0-indexed and row-major.

# Example

For `n = 4, a = 1, b = 1`, the output should be `13`.

The hole looks like this:

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

The element at (1, 1) is 13

```

### Test cases

(`a, b`) is 0-indexed and row-major here.

```
n   a   b   result
1   0   0    1
2   0   0    1
3   0   0    1
4   0   0    1
2   0   1    2
3   0   1    5
3   1   1    9
4   1   1   13
4   2   1   16
5   2   3   22

```

# Answer
> 10 votes
# Python 2, ~~120~~ ~~119~~ 90 bytes

```
def f(n,a,b):n-=1;A,B,C=min((a,b,1),(n-b,a,2),(n-a,n-b,3),(b,n-a,4));return(n-A)*4*A+4*B+C

```

Try it online!

---

# Python 3, 87 bytes

```
def f(n,a,b):A,B=min((a,b+1/4),(n+~b,a+.5),(n+~a,n-b-1/4),(b,n-a));return(n+~A)*4*A+B*4

```

Try it online!

Returns a float

<sub>-3 bytes, thanks to Arnauld</sub>

---

### Explanation:

This takes advantage of the fact that there is some symmetry to the matrix.

The matrix can be split into four quarters, which are equal when rotated (+ an offset of 1-3).

The first part `A,B,C=...` finds out which quarter the current coordinates are in, by finding the smallest coordinates, relative to each quarter:

(green: `(a,b)`, yellow: `(n-b,a)`, red: `(n-a,n-b)`, blue: `(b,n-a)`)

The coordinate pair is then converted to a value:

`(0,0) = 1`, `(0,1) = 5`, and so on; each coordinate is `4` larger than the previous.

`sum((n-(i*2))*4for i in range(A))` skips the rows above, `+(B-A)*4` moves along the row, and `+C` adds the offset.

`sum((n-(i*2))*4for i in range(A))+(B-A)*4+C` is shortened to `(n-A)*4*A+4*B+C`

# Answer
> 2 votes
# 05AB1E (legacy), ~~36~~ ~~31~~ ~~28~~ 25 bytes

```
<αìRDÀsā)ø{н`Š4*ŠD¹<α4**O

```

Port of *@TFeld*'s Python answer, so make sure to upvote him!
-3 bytes thanks to *@Emigna*.

Inputs are \\$n\\$ and \\$\[a,b\]\\$.

Uses the legacy version instead of the new 05AB1E version, because there seems to be a bug with the sorting (`{`) of multidimensional lists.

Try it online or verify all test cases.

**Explanation:**

```
<          # Decrease the (implicit) input `n` by 1
 α         # Take the absolute difference with the (implicit) input-list
           #  (we now have `[n-1-a, n-1-b]`)
  ì        # Prepend the input (we now have `[n-1-a, n-1-b, a, b]`)
   R       # Reverse the list (we now have `[b, a, n-1-b, n-1-a]`)
DÀ         # Duplicate this list, and rotate it once towards the left
    s      # Swap these two lists
ā          # Push a list in the range [1, length_list] without popping the list: [1,2,3,4]
     )     # Wrap all three lists into a list (we now have
           #  `[[a, n-1-b, n-1-a, b], [b, a, n-1-b, n-1-a], [1, 2, 3, 4]]`)
      ø    # Zip/transpose; swapping rows/columns (we now have
           #  `[[a, b, 1], [n-1-b, a, 2], [n-1-a, n-1-b, 3], [b, n-1-a, 4]]`)
       {н  # Get the minimum by sorting the lists and getting the first inner list
           # (since the minimum builtins in 05AB1E flatten multidimensional lists
           #  and give a single integer)
`          # Push all three values to the stack: `A`, `B`, and `C`
Š          # Triple-swap once, so the order is now `C`, `A`, `B`
 4*        # Multiply `B` by 4
Š          # Triple-swap again to `B*4`, `C`, `A`
 D         # Duplicate `A`
  ¹<α      # Take the absolute difference with `n-1` (so basically `n-1-A`)
     4*    # Multiply that by 4
       *   # Multiply it with the duplicated `A`
O          # Sum all values on the stack (`B*4 + C + (n-1-A)*4*A`)
           # (and output the result implicitly)

```

# Answer
> 1 votes
# Jelly, 28 bytes

```
³_1ị’;1×4
’0;_ⱮpƝẎAµżJṂFµæ.Ç

```

Try it online!

Based on @TFeld’s python answer so be sure to upvote that one too.

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

```
(w,y,x)=>[x+(Y=w+~y)*y,y+(w+=~x)*x,w+Y*y,Y+w*x][k=x<y?x>Y?2:3:x<Y?0:x>y?1:Y-y&&2]*4-~k

```

Try it online!

# Answer
> 1 votes
# Jelly, 20 bytes

```
ZUẎTḢṬ_Ʋṁ
+þ`ṠÇƬSœị@

```

A dyadic Link accepting `n` on the left and `[a,b]` (1-indexed) on the right.

**Try it online!**

### How?

```
ZUẎTḢṬ_Ʋṁ - Link 1, next matrix (rotated): current matrix
Z         - transpose          }
 U        - reverse each row   } -> rotate clockwise 1/4
  Ẏ       - tighten into a flat list of values
       Ʋ  - last four links as a monad:
   T      -   truthy indices -- e.g. [0,0,1,0,1,1,0] -> [3,5,6]
    Ḣ     -   head (empty list yields 0)             ->  3
     Ṭ    -   un-truth (0 yields an empty list)      -> [0,0,1]
      _   - subtract (vectorises)                    -> [0,0,0,0,1,1,0]
        ṁ - mould to shape of the current matrix again

+þ`ṠÇƬSœị@ - Main Link: integer, n; list of integers [a,b]
  `         - using left (n) as both arguments:
 þ          -   table of (implicit range of integer arguments)
+           -     addition
   Ṡ        - sign -- now we have an n by n matrix of ones
     Ƭ      - collect up (a list of matrices) while results are different with:
    Ç       -   last Link (1) as a monad
      ¬     - logical NOT (replace the 1s with 0s and vice-versa)
       S    - sum (vectorises)
          @ - with swapped arguments:
        œị  -   multidimensional index into

```

# Answer
> 0 votes
# Rust - 340 bytes

```
fn f(n:usize,x:usize,y:usize)->usize{let (mut r,d)=(0,(n-1)&1);for l in ((1+d)..=n).step_by(2) {let (mut i,m,mx,mut z)=(0,l/2,n/2,0);loop {z=4*i+n*n-l*l;let u=[mx+m-i-d,mx-m,mx+m-d,mx-m+i];if (x,y)==(u[0],u[1]){r=z+4}if (x,y)==(u[2],u[0]){r=z+3}if (x,y)==(u[3],u[2]){r=z+2}if (x,y)==(u[1],u[3]){r=z+1}i+=1;if i>=l-1{break};}}r}

```

still got some work to do, but it basically draws the whole spiral, centered on a point in the middle, and saves the value at requested point x,y.

ungolf spiral draw at play.rust-lang.org

---
Tags: code-golf, matrix
---


title: Pólya urn flip and roll

text:
# Question
Title: Pólya urn flip and roll
# Problem statement

Pólya is playing about with his urn again and he wants you to help him calculate some probabilities.

In this urn experiment Pólya has an urn which initially contains 1 red and 1 blue bead.

For every iteration, he reaches in and retrieves a bead, then inspects the colour and places the bead back in the urn.

He then flips a fair coin, if the coin lands heads he will insert a fair 6 sided die roll amount of the same coloured bead into the urn, if it lands tails he will remove half the number of the same colored bead from the urn (Using integer division - so if the number of beads of the selected colour is odd he will remove `(c-1)/2` where c is the number of beads of that colour)

**Given an integer n ≥ 0 and a decimal r \> 0, give the probability to 2 decimal places that the ratio between the colours of beads after n iterations is greater than or equal to r in the shortest number of bytes.**

# An example set of iterations:

Let (x, y) define the urn such that it contains x red beads and y blue beads.

```
Iteration    Urn       Ratio
0            (1,1)     1
1            (5,1)     5        //Red bead retrieved, coin flip heads, die roll 4
2            (5,1)     5        //Blue bead retrieved, coin flip tails
3            (3,1)     3        //Red bead retrieved, coin flip tails
4            (3,4)     1.333... //Blue bead retrieved, coin flip heads, die roll 3

```

As can be seen the Ratio r is always ≥ 1 (so it's the greater of red or blue divided by the lesser)

# Test cases:

Let F(n, r) define application of the function for n iterations and a ratio of r

```
F(0,5) = 0.00
F(1,2) = 0.50
F(1,3) = 0.42
F(5,5) = 0.28
F(10,4) = 0.31
F(40,6.25) = 0.14

```

This is code golf, so the shortest solution in bytes wins.

# Answer
> 6 votes
# JavaScript (ES7),  ~~145 ... 129 124~~  123 bytes

Takes input as `(r)(n)`. This is a naive solution that actually performs the entire simulation.

```
r=>g=(n,B=s=0,R=0,h=d=>++d<7?h(d,[0,d].map(b=>g(n,B/-~!!b,R/-~!b)&g(n,B+b,R+d-b))):s/24**-~n)=>n--?h``:s+=~B<=r*~R|~R<=r*~B

```

Try it online!

Too slow for the last 2 test cases.

### Commented

```
r =>                    // r = target ratio
g = (                   // g is a recursive function taking:
  n,                    //   n = number of iterations
  B =                   //   B = number of blue beads, minus 1
  s = 0,                //   s = number of times the target ratio was reached
  R = 0,                //   R = number of red beads, minus 1
  h = d =>              //   h = recursive function taking d = 6-sided die value
    ++d < 7 ?           // increment d; if d is less than or equal to 6:
      h(                //   do a recursive call to h:
        d,              //     using the new value of d
        [0, d].map(b => //     for b = 0 and b = d:
          g(            //       do a first recursive call to g:
            n,          //         leave n unchanged
            B / -~!!b,  //         divide B by 2 if b is not equal to 0
            R / -~!b    //         divide R by 2 if b is equal to 0
          ) & g(        //       do a second recursive call to g:
            n,          //         leave n unchanged
            B + b,      //         add b blue beads
            R + d - b   //         add d - b red beads
          )             //       end of recursive calls to g
        )               //     end of map()
      )                 //   end of recursive call to h
    :                   // else (d > 6):
      s / 24 ** -~n     //   stop recursion and return s / (24 ** (n + 1))
) =>                    // body of g:
  n-- ?                 //   decrement n; if n was not equal to 0:
    h``                 //     invoke h with d = [''] (coerced to 0)
  :                     //   else:
    s +=                //     increment s if:
      ~B <= r * ~R |    //       either (-B-1) <= r*(-R-1), i.e. (B+1)/(R+1) >= r
      ~R <= r * ~B      //       or     (-R-1) <= r*(-B-1), i.e. (R+1)/(B+1) >= r

```

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

```
Length@Select[#2/#&@@@(r=Nest[Sort/@Flatten[Table[{{k,0}+#,⌈#/{1,2}⌉},{k,6}]&/@Join[#,Reverse/@#],2]&,{{1,1}},x]),#>=y&]/Length@r

```

By using `N[F,2]`,the output should print 2 decimal digits but TIO prints more...

Try it online!

---
Tags: code-golf, probability-theory
---


title: Generate the Rummy Sequence

text:
# Question
Title: Generate the Rummy Sequence
Your task is to take an input `n` and output element `n` of the Rummy Sequence, a sequence which I made (looking on OEIS will not help you).

# Definition

Each element of the Rummy Sequence is a set of truthy or falsey values. Ex.: `[true, false]`.

The steps to producing a member of the Rummy Sequence are quite simple:

1. Start out with the first index, `[]` (this is element 0).
2. Set the leftmost falsey to truthy. If there are no falseys to change, then increase the length of the list by 1 and set all members of the new list to falsey.
3. Repeat step 2 until reaching element `n`.

# Example

Let's define our function as `rummy(int n)` (stuff in `{}` is a step taken to get to the answer):

```
>>> rummy(5)
{[]}
{[false]}
{[true]}
{[false, false]}
{[true, false]}
[true, true]

```

# Rules

* Standard loopholes apply.
* Must work for inputs 0 through your language's upper numerical bound.
* You may output in any way you see fit, provided that it is clear that the output is a set of truthy/falseys.

# Trivia

I call this the "Rummy Sequence" because, starting at index 2, it defines the sets you would need to lay down in each round of Progressive Rummy, where falsey is a book and truthy is a run.

# Test Cases

```
>>> rummy(0)
[]

>>> rummy(1)
[false]

>>> rummy(6)
[false, false, false]

>>> rummy(20)
[true, true, true, true, true]

>>> rummy(1000)
[true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false]

```

# Answer
# JavaScript ES6, ~~94~~ ~~92~~ ~~72~~ ~~70~~ ~~66~~ 64 bytes

*Saved 6 bytes thanks to Neil!*

```
n=>[...Array(a=Math.sqrt(8*n+1)-1>>1)].map((_,l)=>l<n-a*(a+1)/2)

```

I don't think this can be golfed more. At least with the equations.

## Explanation

They are two main equations (`n` is input):

```
(Math.sqrt(8*n+1)-1)/2

```

This will give the total size the output array will need to be. In my program I used `>>1` instead of `(...)/2` these are the same as the first bit in binary has a value of 2. Shifting it will result in in `floor(.../2)`

---

```
n-a*(a+1)/2

```

This is the amount of `true`s there will be. `a` is the result of the previous expression.

---

This is what the syntax does:

```
[...Array(n)]

```

This code generates an array with range `[0, n)` in this answer `n` is the first equation.

---

`.map((_,l)=>l<n)` this will loop through the above range, `l` is the variable containing the current item in the range. If the item is less than the amount of trues they are (determined by second equation), then it will return `true`, else `false`.
> 10 votes

# Answer
## Python, 51 bytes

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

```

Outputs a list of 1's and 0's.
> 6 votes

# Answer
# Jelly, ~~13~~ 11 bytes

```
Ḷṗ2SÞ⁸ị1,0x

```

The code does not work in the latest version of Jelly before the challenge was posted, but it did work in this version, which predates the challenge.

Indices are 1-based. Try it online! (takes a few seconds) or verify multiple inputs at once.

### How it works

```
Ḷṗ2SÞ⁸ị1,0x  Main link. Argument: n (integer)

Ḷ            Unlength; yield [0, ..., n - 1].
 ṗ2          Take the second Cartesian power, i.e., generate the array of all
             pairs of elements of [0, ..., n - 1].
   SÞ        Sort the pairs by their sum. The sort is stable, so ties are broken
             by lexicographical order.
     ⁸ị      Retrieve the pair at index n.
       1,0x  Map [a, b] to a copies of 1 and b copies of 0.

```
> 5 votes

# Answer
# Pyth, 8 bytes

```
_@{y/RQy

```

Try it online: Demonstration or Test Suite

This is exponentially slow.

### Explanation:

```
_@{y/RQyQQ    implicit Qs at the end, (Q = input)
       yQ     2*Q
    /RQ       divide each number in [0, 1, ..., 2*Q-1] by Q
              this results in a list of Q zeros and Q ones
   y          take all subsets
  {           remove duplicates
 @       Q    take the Qth element
_             print it reversed

```
> 5 votes

# Answer
## 05AB1E, 27 bytes

```
8*>t<;ïÐ>*;¹s-ïD1s×Š-0s×JSï

```

Will see if I can golf it some more and add an explanation in the morning.

Try it online
> 4 votes

# Answer
# Java, ~~117~~ 110 bytes

```
enum B{T,F};B[]r(int n){int i=0,c=0,j=0;while(n>=i)i+=++c;B[]a=new B[c-1];for(;j<n-i+c;)a[j++]=B.T;return a;}

```

created my own boolean type, which allowed me to save 7bytes
> 4 votes

# Answer
# Python 2, ~~69~~ 63 bytes

```
a=b=0
exec'a,b=[a-1,b+1,0][a<1:][:2];'*input()
print[1]*b+[0]*a

```

Test it on Ideone.
> 2 votes

# Answer
## Python 2, 61 bytes

```
j=(2*input()+.25)**.5-.5
print[i/j<j%1for i in range(int(j))]

```

Solves for *n = j·(j+1)/2*. Input is taken from stdin.

**Sample Usage**

```
$ echo 20 | python rummy-seq.py
[True, True, True, True, True]

$ echo 50 | python rummy-seq.py
[True, True, True, True, True, False, False, False, False]

```

Demo.
> 2 votes

# Answer
# APL (Dyalog Extended), 21 bytesSBCS

```
{⍵⌷↑,/(↓0 1↓⍳≥\⍳)¨⍳⍵}

```

Try it online!
> 0 votes

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