# Question
Title: N-movers: How much of the infinite board can I reach?
# Single moves

The board is an infinite 2 dimensional square grid, like a limitless chess board. A piece with value N (an ***N-mover***) can move to any square that is a distance of exactly the square root of N from its current square (Euclidean distance measured centre to centre).

For example:

* A 1-mover can move to any square that is horizontally or vertically adjacent
* A 2-mover can move to any square that is diagonally adjacent
* A 5-mover moves like a chess knight

Note that not all N-movers can move. A 3-mover can never leave its current square because none of the squares on the board are a distance of exactly root 3 from the current square.

# Multiple moves

If allowed to move repeatedly, some pieces can reach any square on the board. For example, a 1-mover and a 5-mover can both do this. A 2-mover can only move diagonally and can only reach half of the squares. A piece that cannot move, like a 3-mover, cannot reach any of the squares *(the starting square is not counted as "reached" if no movement occurs)*.

The images show which squares can be reached. More details on hover. Click for larger image.

* Squares reachable in 1 or more moves are marked in black
* Squares reachable in exactly 1 move are shown by red pieces
*(apart from the 3-mover, which cannot move)*

What proportion of the board can a given N-mover reach?

# Input

* A positive integer N

# Output

* The proportion of the board that an N-mover can reach
* This is a number from 0 to 1 (both inclusive)
* For this challenge, output as a fraction in lowest terms, like 1/4, is allowed

So for input `10`, both `1/2` and `0.5` are acceptable outputs. Output as separate numerator and denominator is also acceptable, to be inclusive of languages that support neither floats nor fractions. For example, `1 2` or `[1, 2]`.

For the integer outputs (0 and 1), any of the following are acceptable formats:

* For 0: `0`, `0.0`, `0/1`, `0 1`, `[0, 1]`
* for 1: `1`, `1.0`, `1/1`, `1 1`, `[1, 1]`

# Scoring

This is code golf. The score is the length of the code in bytes. For each language, the shortest code wins.

# Test cases

In the format `input : output as fraction : output as decimal`

```
  1 : 1     : 1
  2 : 1/2   : 0.5
  3 : 0     : 0
  4 : 1/4   : 0.25
  5 : 1     : 1
  6 : 0     : 0
  7 : 0     : 0
  8 : 1/8   : 0.125
  9 : 1/9   : 0.1111111111111111111111111111
 10 : 1/2   : 0.5
 13 : 1     : 1
 16 : 1/16  : 0.0625
 18 : 1/18  : 0.05555555555555555555555555556
 20 : 1/4   : 0.25
 25 : 1     : 1
 26 : 1/2   : 0.5
 64 : 1/64  : 0.015625
 65 : 1     : 1
 72 : 1/72  : 0.01388888888888888888888888889
 73 : 1     : 1
 74 : 1/2   : 0.5
 80 : 1/16  : 0.0625
 81 : 1/81  : 0.01234567901234567901234567901
 82 : 1/2   : 0.5
144 : 1/144 : 0.006944444444444444444444444444
145 : 1     : 1
146 : 1/2   : 0.5
148 : 1/4   : 0.25
153 : 1/9   : 0.1111111111111111111111111111
160 : 1/32  : 0.03125
161 : 0     : 0
162 : 1/162 : 0.006172839506172839506172839506
163 : 0     : 0
164 : 1/4   : 0.25
241 : 1     : 1
242 : 1/242 : 0.004132231404958677685950413223
244 : 1/4   : 0.25
245 : 1/49  : 0.02040816326530612244897959184
260 : 1/4   : 0.25
261 : 1/9   : 0.1111111111111111111111111111
288 : 1/288 : 0.003472222222222222222222222222
290 : 1/2   : 0.5
292 : 1/4   : 0.25
293 : 1     : 1
324 : 1/324 : 0.003086419753086419753086419753
325 : 1     : 1
326 : 0     : 0
360 : 1/72  : 0.01388888888888888888888888889
361 : 1/361 : 0.002770083102493074792243767313
362 : 1/2   : 0.5
369 : 1/9   : 0.1111111111111111111111111111
370 : 1/2   : 0.5
449 : 1     : 1
450 : 1/18  : 0.05555555555555555555555555556
488 : 1/8   : 0.125
489 : 0     : 0
490 : 1/98  : 0.01020408163265306122448979592
520 : 1/8   : 0.125
521 : 1     : 1
522 : 1/18  : 0.05555555555555555555555555556
544 : 1/32  : 0.03125
548 : 1/4   : 0.25
549 : 1/9   : 0.1111111111111111111111111111
584 : 1/8   : 0.125
585 : 1/9   : 0.1111111111111111111111111111
586 : 1/2   : 0.5
592 : 1/16  : 0.0625
593 : 1     : 1
596 : 1/4   : 0.25
605 : 1/121 : 0.008264462809917355371900826446
610 : 1/2   : 0.5
611 : 0     : 0
612 : 1/36  : 0.02777777777777777777777777778
613 : 1     : 1
624 : 0     : 0
625 : 1     : 1

```

# Answer
# JavaScript (Node.js), ~~144~~ ~~138~~ ~~125~~ ~~74~~ ~~73~~ 70 bytes

```
f=(x,n=2,c=0)=>x%n?x-!c?f(x,n+1)/(n%4>2?n/=~c&1:n%4)**c:1:f(x/n,n,c+1)

```

Try it online!

**-4 byte thanks @Arnauld!**

### Original approach, 125 bytes

```
a=>(F=(x,n=2)=>n*n>x?[x,0]:x%n?F(x,n+1):[n,...F(x/n,n)])(a).map(y=>r-y?(z*=[,1,.5,p%2?0:1/r][r%4]**p,r=y,p=1):p++,z=r=p=1)&&z

```

Try it online!

Inspired by the video Pi hiding in prime regularities by 3Blue1Brown.

For each prime factor \\$p^n\\$ in the factorization of the number, calculate \\$f(p^n)\\$:

* If \\$n\\$ is odd and \\$p\equiv 3\text{ (mod 4)}\\$ \- \\$f(p^n)=0\\$. Because there is no place to go.
* If \\$n\\$ is even and \\$p\equiv 3\text{ (mod 4)}\\$ \- \\$f(p^n)=\frac{1}{p^n}\\$.
* If \\$p=2\\$ \- \\$f(2^n)=\frac{1}{2^n}\\$.
* If \\$p\equiv 1\text{ (mod 4)}\\$ \- \\$f(p^n)=1\\$.

Multiply all those function values, there we are.

### Update

Thanks to the effort of contributors from Math.SE, the algorithm is now backed by a proof
> 19 votes

# Answer
# Clean, ~~189~~ ~~185~~ ~~172~~ 171 bytes

```
import StdEnv
$n#r=[~n..n]
#p=[[x,y]\\x<-r,y<-r|x^2+y^2==n]
=sum[1.0\\_<-iter n(\q=removeDup[k\\[a,b]<-[[0,0]:p],[u,v]<-q,k<-[[a+u,b+v]]|all(\e=n>=e&&e>0)k])p]/toReal(n^2)

```

Try it online!

Finds every position reachable in the `n`-side-length square cornered on the origin in the first quadrant, then divides by `n^2` to get the portion of all cells reachable.

This works because:

* The entire reachable plane can be considered as overlapping copies of this `n`-side-length square, each cornered on a reachable point from the origin as if it were the origin.
* All movements come in groups of four with signs `++ +- -+ --`, allowing the overlapping tiling to be extended through the other three quadrants by mirroring and rotation.
> 11 votes

# Answer
# Mathematica, 80 bytes

```
d[n_]:=If[#=={},0,1/Det@LatticeReduce@#]&@Select[Tuples[Range[-n,n],2],#.#==n&];

```

This code is mostly reliant on a mathematical theorem. The basic idea is that the code asks for the density of a lattice given some generating set.

More precisely, we are given some collection of vectors - namely, those whose length squared is N - and asked to compute the density of the set of possible sums of these vectors, compared to all integer vectors. The math at play is that we can always find two vectors (and their opposite) that "generate" (i.e. whose sums are) the same set as the original collection. LatticeReduce does exactly that.

If you have just two vectors, you can imagine drawing an identical parallelogram centered at each reachable point, but whose edge lengths are the given vectors, such that the plane is completely tiled by these parallelograms. (Imagine, for instance, a lattice of "diamond" shapes for n=2). The area of each parallelogram is the determinant of the two generating vectors. The desired proportion of the plane is the reciprocal of this area, since each parallelogram has just one reachable point in it.

The code is a fairly straightforward implementation: Generate the vectors, use LatticeReduce, take the determinant, then take the reciprocal. (It can probably be better golfed, though)
> 10 votes

# Answer
# Retina 0.8.2, ~~126~~ 82 bytes

```
.+
$*
+`^(1(1111)+)(?<!^\3+(11+))(\1)*$
1$#4$*
^(?!((^1|11\2)+)\1?$)1+
0
11+
1/$.&

```

Try it online! Link includes test cases. Explanation:

```
.+
$*

```

Convert to unary.

```
+`^(1(1111)+)(?<!^\3+(11+))(\1)*$
1$#4$*

```

Repeatedly divide by prime factors of the form `4k+1`.

```
^(?!((^1|11\2)+)\1?$)1+
0

```

If the result is neither a square nor twice a square then the result is zero.

```
11+
1/$.&

```

Compute the reciprocal as a decimal fraction.
> 5 votes

# Answer
# Regex (ECMAScript, reciprocal out), ~~256~~ ~~163~~ ~~157~~ ~~94~~ ~~83~~ 82 bytes

*-93 bytes thanks to Neil*
*-6 bytes thanks again to Neil*
*-63 bytes by doing division without capturing the divisor*
*-11 bytes thanks to Grimmy's simultaneous optional-division-by-constant and square root*
*-1 byte by moving the end-match condition and return value capture into the loop as a second alternative, thanks to Grimmy*

This uses the same mathematics as Shieru Asakoto's JavaScript answer.

The input is in unary. Since a pure regex can only return as output a substring from the input (i.e. a natural number less than or equal to the input), or "no match", this regex returns the reciprocal of the proportion of the board that an N-mover can reach. Since the reciprocal of 0 is infinity, it returns "no match" in that case.

**SPOILER WARNING**: For the square root, this regex uses a variant of the generalized multiplication algorithm, which is non-obvious and could be a rewarding puzzle to work out on your own. For more information, see an explanation for this form of the algorithm in Find a Rocco number.

This regex first goes into loop identifying all prime factors \\$p\\$ such that \\$p\equiv 1\text{ (mod 4)}\\$, and divides the input number by each one as many times as it can. Let \\$m\\$ be the end result of this. Then, it indirectly tests to see if the prime factorization of \\$m\\$ (and therefore also the input number) includes any primes \\$\equiv 3\text{ (mod 4)}\\$ raised to an odd power, by testing to see if \\$m\\$ or \\$m/2\\$ is a perfect square. If not, then \\$m\\$ did include such a prime raised to an odd power, and the regex returns "no match"; otherwise, it returns \\$m\\$.

(It's now a bit more complicated than that. Due to a golf optimization in the reciprocal-output version, it tests not only \\$m\\$ and \\$m/2\\$ for being a square, but also the intermediate result before the division of each \\$p\\$, if the first test fails. This doesn't change the end result, because if the first perfect square test failed, at least one odd power of a prime \\$\equiv 3\text{ (mod 4)}\\$ will still be present in the number at every step, and it can't be a square.)

```
^(?=((?=(x+)(?!(\2+)(\2\3)+$)((\2{4})+$))\5|((xx?)(\8*))(?=(\7*)\9+$)\7*$\10)+$)\1

```

Try it online!
Try it online! (just the test cases)

```
^
(?=
    (                          # Capture return value, which will just be the value
                               # matched by the last iteration of this loop.
    # Divide tail by every one of its prime factors that's ≡1 mod 4, as many times as
    # possible.
        (?=
            (x+)               # \2 = quotient
            (?!(\2+)(\2\3)+$)  # Assert divisor is prime
            ((\2{4})+$)        # Assert divisor ≡1 mod 4; \5 = tool to make tail = \2
        )\5                    # tail = \2
    |
    # When the above alternative has been done as many times as possible:
    # Test if tail or tail/2 is a perfect square. If this test fails, the regex engine
    # will backtrack into the division loop above, and run the same perfect square
    # test on every previous number (effectively "multiplying" it by each previous P
    # in reverse, one at a time). This will not cause a failure of the test to change
    # into a success, however, because the odd power of a prime ≡3 mod 4 will see be
    # present in the number at every step. Allowing this backtracking to happen is a
    # golf optimization, and it does make the regex slower.
    # Failure of this perfect square test results in returning "no match" and indicates
    # a return value of zero.
        (                      # \7 = \8 * sqrt(tail / \8)
            (xx?)              # \8 = control whether to take sqrt(tail)
                               #                         or 2*sqrt(tail/2)
            (\8*)              # \9 = \7 - \8
        )
        (?=
            (\7*)\9+$          # Iff \8 * (\7 / \8)^2 == our number, then the first match
                               # here must result in \10==0
        )
        \7*$\10                # Test for divisibility by \7 and for \10==0
                               # simultaneously
    )+
    $                          # Require that the last iteration of the above loop was
                               # the perfect square test. Since the first alternative,
                               # the division, always leaves >=1 in tail, this guarantees
                               # that the last step is a successful perfect square test,
                               # or else the result will be "no match".
)
\1                             # Return value (which is a reciprocal)

```

## Regex (ECMAScript+`(?*)`, reciprocal output), ~~207~~ ~~138~~ ~~132~~ bytes

Obsoleted by doing division without capturing the divisor (i.e. is now identical to the above).

## Regex (ECMAScript 2018, reciprocal output), ~~212~~ ~~140~~ ~~134~~ bytes

Obsoleted by doing division without capturing the divisor (i.e. is now identical to the above).

# Regex (ECMAScript, fraction output), 80 bytes

In this version, the numerator is returned in `\10` (zero if unset/NPCG) and the denominator in `\7`.

Unlike the reciprocal output version:

* An input of zero is not correctly dealt with (it returns "no match" just like that version, but unlike it, that does not correspond to an output value of zero).
* If the perfect square test fails, it does not backtrack into the division loop, so this version is more efficient in execution time.

The big downside of an output specification like this is that it isn't contained in the program itself.

```
((?=(x+)(?!(\2+)(\2\3)+$)((\2{4})+$))\5)*((((x)x?)(\9*))(?=(\8*)\11+$)\8*$\12|x)

```

Try it online!
Try it online! (just the test cases)

```
# No need to anchor, since we return a match for all inputs in the domain.
# Divide tail by every one of its prime factors that's ≡1 mod 4
(
    (?=
        (x+)               # \2 = quotient
        (?!(\2+)(\2\3)+$)  # Assert divisor is prime
        ((\2{4})+$)        # Assert divisor ≡1 mod 4; \5 = tool to make tail = \2
    )\5                    # tail = \2
)*
# Test if tail or tail/2 is a perfect square. If this test succeeds, return tail as
# the denominator and 1 as the numerator.
(                          # \7 = denominator output
    (                      # \8 = \9 * sqrt(tail / \9)
        ((x)x?)            # \9 = control whether to take sqrt(tail) or 2*sqrt(tail/2);
                           # \10 = numerator output (NPCG to represent zero)
        (\9*)              # \11 = \8 - \9
    )
    (?=
        (\8*)\11+$         # Iff \9 * (\8 / \9)^2 == our number, then the first match
                           # here must result in \12==0
    )
    \8*$\12                # Test for divisibility by \8 and for \12==0
                           # simultaneously
|
# Failure of the perfect square test results in returning 0/1 as the answer, so here
# we return a denominator of 1.
    x
)

```
> 5 votes

# Answer
# 05AB1E, ~~27~~ ~~26~~ 25 bytes

```
ÓεNØ©<iozë®4%D≠iyÈ®ymz*]P

```

Port of *@ShieruAsakoto*'s JavaScript answer, so make sure to upvote him as well!

Try it online or verify all test cases.

**Explanation:**

```
Ó                   # Get all prime exponent's of the (implicit) input's prime factorization
                    #  i.e. 6 → [1,1]      (6 → 2**1 * 3**1)
                    #  i.e. 18 → [1,2]     (18 → 2**1 * 3**2)
                    #  i.e. 20 → [2,0,1]   (20 → 2**2 * 3**0 * 5**1)
                    #  i.e. 25 → [0,0,2]   (25 → 2**0 * 3**0 * 5**2)
 ε                  # Map each value `n` to:
  NØ                #  Get the prime `p` at the map-index
                    #   i.e. map-index=0,1,2,3,4,5 → 2,3,5,7,11,13
    ©               #  Store it in the register (without popping)
     <i             #  If `p` is exactly 2:
       oz           #   Calculate 1/(2**`n`)
                    #    i.e. `n`=0,1,2 → 1,0.5,0.25
      ë             #  Else:
       ®4%          #   Calculate `p` modulo-4
                    #    i.e. `p`=3,5,7,11,13 → 3,1,3,3,1
          D         #   Duplicate the result (the 1 if the following check is falsey)
           ≠i       #   If `p` modulo-4 is NOT 1 (in which case it is 3):
             yÈ     #    Check if `n` is even (1 if truthy; 0 if falsey)
                    #     i.e. `n`=0,1,2,3,4 → 1,0,1,0,1
             ®ymz   #    Calculate 1/(`p`**`n`)
                    #     i.e. `p`=3 & `n`=2 → 0.1111111111111111 (1/9)
                    #     i.e. `p`=7 & `n`=1 → 0.14285714285714285 (1/7)
              *     #    Multiply both with each other
                    #     i.e. 1 * 0.1111111111111111 → 0.1111111111111111
                    #     i.e. 0 * 0.14285714285714285 → 0
 ]                  # Close both if-statements and the map
                    #  i.e. [1,1] → [0.5,0.0]
                    #  i.e. [1,2] → [0.5,0.1111111111111111]
                    #  i.e. [2,0,1] → [0.25,1.0,1]
                    #  i.e. [0,0,2] → [1.0,1.0,1]
  P                 # Take the product of all mapped values
                    #  i.e. [0.5,0.0] → 0.0
                    #  i.e. [0.5,0.1111111111111111] → 0.05555555555555555
                    #  i.e. [0.25,1.0,1] → 0.25
                    #  i.e. [1.0,1.0,1] → 1.0
                    # (and output implicitly as result)

```
> 4 votes

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

```
ÆFµ%4,2CḄ:3+2Ịị,*/ʋ÷*/)P

```

A monadic link using the prime factor route.

**Try it online!**

### How?

```
ÆFµ%4,2CḄ:3+2Ịị,*/ʋ÷*/)P - Link: integer, n               e.g. 11250
ÆF                       - prime factor, exponent pairs        [[2,1], [3,2], [5,4]]
  µ                   )  - for each pair [F,E]:
    4,2                  -   literal list [4,2]
   %                     -   modulo (vectorises)                [2,1]  [3,0]  [1,0]
       C                 -   complement (1-x)                  [-1,0] [-2,1]  [0,1]
        Ḅ                -   from base 2                         -2     -3      1
         :3              -   integer divide by three             -1     -1      0
           +2            -   add two (call this v)                1      1      3
                  ʋ      -   last four links as a dyad, f(v, [F,E])
             Ị           -     insignificant? (abs(x)<=1 ? 1 : 0)   1      1      0
                */       -     reduce by exponentiation (i.e. F^E)  2      9     625
               ,         -     pair v with that                   [1,2]  [1,9]  [3,625]
              ị          -     left (Ị) index into right (that)     1      1     625
                    */   -   reduce by exponentiation (i.e. F^E)    2      9     625
                   ÷     -   divide                                1/2    1/9  625/625
                       P - product                                 1/18 = 0.05555555555555555

```

---

Previous 25 was:

```
ŒRp`²S⁼ɗƇ⁸+€`Ẏ;Ɗ%³QƊÐLL÷²

```

Full program brute forcer~~; possibly~~ longer code ~~than the prime factor route (I might attempt that later).~~

Try it online!

Starts by creating single moves as coordinates then repeatedly moves from all reached locations accumulating the results, taking modulo `n` of each coordinate (to restrict to an `n` by `n` quadrant) and keeping those which are distinct until a fixed point is reached; then finally divides the count by `n^2`
> 4 votes

# Answer
# APL (Dyalog Extended), 21 bytes

This program uses the prime factor route. I am indebted to Adám, dzaima, H.PWiz, J.Sallé, and ngn. The APL Orchard is a great place to learn APL and they are always willing to help

```
(×/÷,3≠4|*∘≢⌸)⍭*1≠4|⍭

```

Try it online!

**Ungolfing**

Part 2 of this code is the same as in the Dyalog Unicode version below, and so in this explanation, I will focus on `⍭*1≠4|⍭`

```
⍭*1≠4|⍭

      ⍭  Gives us a list of the prime factors of our input.
           Example for 45: 3 3 5
  1≠4|   Checks if each prime is of the form 4k+1.
⍭*       Takes each prime to the power of 1 or 0,
           turning all the 4k+1 primes into 1s.
           Example for 45: 3 3 1

```

---

# APL (Dyalog Unicode), ~~41~~ ~~40~~ ~~36~~ 35 bytes<sup>SBCS</sup>

This program uses the prime factor route. Learned a few tricks while writing this and I am deeply indebted to Adám, dzaima, H.PWiz, J.Sallé, and ngn. The APL Orchard is a great place to learn APL and they are always willing to help (or this post never would have got off the ground :)

Edit: -1 byte from ngn. -2 bytes from Adám and -2 more from ngn. -1 byte from ngn.

```
{(×/÷,3≠4|*∘≢⌸)p*1≠4|p←¯2÷/∪∧\⍵∨⍳⍵}

```

Try it online!

**Ungolfing**

This is a program in two parts:

```
p*1≠4|p←¯2÷/∪∧\⍵∨⍳⍵  Part 1

      p←             We can define variables mid-dfn (a function in {} brackets).
               ⍵∨⍳⍵  We take the GCD of our input
                       with every member of range(1, input).
            ∪∧\      This returns all the unique LCMs of every prefix
                       of our list of GCDs.
                       Example for 31500: 1 2 6 12 60 420 1260 6300 31500
        ¯2÷/         We divide pairwise (and in reverse)
                       by using a filter window of negative two (¯2).
                       Example for 31500: 2 3 2 5 7 3 5 5
  1≠4|p              Check if the primes are 1 modulo 4 or not
p*                   And take each prime to the power of the result (1 or 0),
                       turning the 4k+3 primes into 1s
                       and leaving any 2s and 4k+3 primes.
                       Example for 31500: 2 3 2 1 7 3 1 1

(×/÷,3≠4|*∘≢⌸)  Part 2

(            )  We apply all this to the filtered array of primes.
         *∘≢⌸   This takes all of our primes to their exponents
                  (the number of times those primes appear in the factorization).
                  Example for 31500: 4 9 1 7
     3≠4|       Then we take each prime modulo 4 and check if not equal to 3.
                  We will only get a falsey if any 4k+3 primes, as an even number of
                  4k+3 primes multiplied together will result in some 4m+1.
                  Example for 31500: 1 1 1 0
   ÷,           We append the results of the above condition check
                  to the reciprocals of the primes in p.
                  Example for 31500: (1/2) (1/3) (1/2) 1 (1/7) (1/3) 1 1 1 1 1 0
 ×/             We multiply it all together, resulting in a positive fraction or 0
                  depending on our condition check.
                  Example for 31500: 0
                We return the results of all our checks implicitly.

```
> 4 votes

---
Tags: code-golf, grid, chess, board-game
---


title: Reverse indentation

text:
# Question
Title: Reverse indentation
I've heard that your code can run faster if you indent it in reverse, so that the compiler can process it like a tree design pattern from the very top of the "branches" down. This helps because gravity will speed up the time it takes for your code to be compiled, and the data structure efficiency is improved. Here's an example, in Java scripting:

```
            function fib(n) {
        var a = 1, b = 1;
        while (--n > 0) {
    var tmp = a;
    a = b;
    b += tmp;
    if (a === Infinity) {
return "Error!";
    }
        }
        return a;
            }

```

But for some reason Notepad doesn't have a setting to do this automatically, so I need a program to do it for me.

# Description

Submissions must take a code snippet as input, reverse the indentation, and output the resulting code.

This is done by the following procedure:

* Split the code up into lines. Each line will start with zero or more spaces (there will be no tabs).
* Find all unique indentation levels in the code. For example, for the above example, this would be

```
0
4
8
12

```
* Reverse the order of this list of indentation levels, and map the reversed list to the original list. This is hard to explain in words, but for the example, it would look like

```
0  — 12
4  — 8
8  — 4
12 — 0

```
* Apply this mapping to the original code. In the example, a line with 0-space-indentation would become indented by 12 spaces, 4 spaces would become 8 spaces, etc.

# Input / Output

The input and output can be provided however you would like (STDIN/STDOUT, function parameter/return value, etc.); if your language does not support multiline input (or you just don't want to), you can use the `|` character to separate lines instead.

The input will consist of only printable ASCII + newlines, and it will not contain empty lines.

# Test cases

Input:

```
function fib(n) {
    var a = 1, b = 1;
        while (--n > 0) {
            var tmp = a;
            a = b;
            b += tmp;
            if (a === Infinity) {
                return "Error!";
            }
        }
    return a;
}

```

Output: the example code above.

Input:

```
a
  b
  c
d
   e
        f
  g
   h

```

Output:

```
        a
   b
   c
        d
  e
f
   g
  h

```

Input:

```
1
 2
  3
 2
1

```

Output:

```
  1
 2
3
 2
  1

```

Input:

```
  foo

```

Output:

```
  foo

```

# Answer
# CJam, ~~43 39 36~~ 35 bytes

```
qN/_{_Sm0=#}%___&$_W%er]z{~S*@+>N}%

```

~~This looks toooo long. I am sure I am not *Optimizing* enough!~~

How it works:

Basic idea is to split the input on newline, calculate the number of leading spaces in each line, sort and get unique numbers, copy that array and reverse the copy, transliterate the original in-order numbers with this two arrays and then finally form the final string using this information.

The lengthiest part is to figure out how many leading spaces are there in each line as CJam does not have an easy way of doing it.

Code expansion:

```
qN/_                                      "Split the string on newline and take copy";
    {_Sm0=#}%                             "Map this code block on the copy";
     _Sm                                  "Copy the string and remove spaces from the copy";
        0=                                "Get first non space character";
          #                               "Gets its index in original string";
             ___                          "Get 3 copies of the above array";
                &$_W%                     "Get unique elements, sort, copy and reverse";
                     er                   "Transliterate unique sorted elements with";
                                          "the unique reverse sorted in the copy";
                       ]z                 "Get array of [row,
                                          " original number of leading spaces,
                                          " required number of leading spaces]";
                         {~S*@+>N}%       "For each above combination";
                          ~S*             " unwrap and get leading space string";
                             @+           " prepend to the row";
                               >          " remove original spaces";
                                N         " put newline";

```

And in the spirit of the question. A real expansion of the code:

```
                                          qN/_                                      "Split the string on newline and take copy";
                                {_Sm0=#}%                             "Map this code block on the copy";
                               _Sm                                  "Copy the string and remove spaces from the copy";
                             0=                                "Get first non space character";
                          #                               "Gets its index in original string";
                         ___                          "Get 3 copies of the above array";
                       &$_W%                     "Get unique elements, sort, copy and reverse";
                     er                   "Transliterate unique sorted elements with";
"the unique reverse sorted in the copy";
                ]z                 "Get array of [row,
" original number of leading spaces,
" required number of leading spaces]";
             {~S*@+>N}%       "For each above combination";
          ~S*             " unwrap and get leading space string";
        @+           " prepend to the row";
     >          " remove original spaces";
    N         " put newline";

```

7 bytes saved thanks to Martin and 1 byte thanks to Dennis

Try it online here
> 10 votes

# Answer
# Python 2 - ~~137~~ 131 bytes

```
i=raw_input().split('|')
f=lambda s:len(s)-len(s.lstrip())
d=sorted(set(map(f,i)))
for l in i:print' '*d[~d.index(f(l))]+l.lstrip()

```

Takes input with `|` instead of `\n`.

**Explanation**

The first three lines are fairly straightforward. Make a list of all the lines in the input, define a function that tells you how much leading whitespace a string has, and make a sorted list of values that function spits out for each line of input.

The last line is way more fun.

```
                                 l               # string with the line
                               f(l)              # amount of leading whitespace
                       d.index(f(l))             # where it is in list of whitespace amounts
                      ~d.index(f(l))             # bitwise NOT (~n == -(n+1))
                    d[~d.index(f(l))]            # index into the list (negative = from end)
           print' '*d[~d.index(f(l))]            # print that many spaces...
           print' '*d[~d.index(f(l))]+l.lstrip() # plus everything after leading whitespace
for l in i:print' '*d[~d.index(f(l))]+l.lstrip() # do the above for every line

```
> 14 votes

# Answer
# JavaScript, ES6, ~~113 103~~ 101 bytes

~~I am pretty sure this can be golfed at least a little further, but here goes.~~

Never would have thought that there will be a 101 bytes JS solution, beating Python!

```
f=a=>(b=c=[...Set(a.match(r=/^ */gm).sort())],c.map((x,i)=>b[x]=c.slice(~i)[0]),a.replace(r,x=>b[x]))

```

This creates a method named `f` which can be called with the input string. If you are in a latest Firefox, you have template strings and you can call the method like

```
f(`a
  b
  c
d
   e
        f
  g
   h`)

```

Otherwise, you can also call it like

```
f("a\n\
  b\n\
  c\n\
d\n\
   e\n\
        f\n\
  g\n\
   h")

```

or, try the snippet below:

```
g=_=>O.textContent=f(D.value)

f=a=>(b=c=[...Set(a.match(r=/^ */gm).sort())],c.map((x,i)=>b[x]=c.slice(~i)[0]),a.replace(r,x=>b[x]))
```

```
<textarea id=D></textarea><button id=B onclick=g()>Inverse!</button>
<pre id=O></pre>
```
> 7 votes

# Answer
# Ruby, 63 bytes

```
->s{l=s.scan(r=/^ */).uniq.sort;s.gsub r,l.zip(l.reverse).to_h}

```

This defines an unnamed function which takes and returns a string. You can call it by appending `["string here"]` or by assigning it to a variable, and then calling that variable.

How it works: `s.scan(r=/^ */)` gives a list of all leading spaces and stores that regex in `r` for later use. `uniq` eliminates duplicates. `sort`... sorts.

Now skip to the end, `l.zip(l.reverse)` gives an array of pairs we want to substitute. `to_h` turns that into a hash, interpreting the pairs as key-value pairs.

Now `s.gsub` replaced all matches of the regex (all leading spaces) by using that hash as a look up table to find the replacement.
> 5 votes

# Answer
## Pyth 39

```
L-/bd/rb6dJcz\|KS{mydJFNJ+*d@_KxKyN>NyN

```

Try it online.

Uses the `|` delimiter option.
> 3 votes

# Answer
# Japt `-R`, 27 bytes

```
·
mâ\S
Vâ n
Ëx2 iSpWg~WbVgE

```

Try it online!

### Unpacked & How it works

```
Input: U = multiline string

qR    Split by newline and implicit assign to U

mâ\S
m     Map over U...
 â\S    .search(/\S/); first index of non-whitespace char
      Implicit assign to V (V = array of indentations)

Vâ n  Take unique elements of V, sort, and implicit assign to W

mDEF{Dx2 iSpWg~WbVgE
mDEF{                 Map over U...
     Dx2                Trim left
         iSp            Indent by this many spaces...
                 VgE      Find the current indentation stored in V
               Wb         Find its index on W
            Wg~           Take the opposite element on W

-R    Join with newline

```

### How it *really* works

```
                 Input: U = multiline string

                 qR    Split by newline and implicit assign to U

                 mâ\S
                 m     Map over U...
               â\S    .search(/\S/); first index of non-whitespace char
         Implicit assign to V (V = array of indentations)

                 Vâ n  Take unique elements of V, sort, and implicit assign to W

                 mDEF{Dx2 iSpWg~WbVgE
                 mDEF{                 Map over U...
            Dx2                Trim left
      iSp            Indent by this many spaces...
VgE      Find the current indentation stored in V
 Wb         Find its index on W
     Wg~           Take the opposite element on W

                 -R    Join with newline

```
> 2 votes

# Answer
# Haskell, 116

```
import Data.List
f s|l<-map(span(==' '))$lines s=unlines[k++b|(a,b)<-l,(k,r)<-reverse>>=zip$sort$nub$map fst l,r==a]

```
> 1 votes

# Answer
# Scala, ~~176~~171

```
def g(n:String)={val a=n.split('|').map(a=>a.prefixLength(' '==)->a)
(""/:a){case(s,(l,p))=>val b=a.unzip._1.distinct.sorted
s+" "*b.reverse(b.indexOf(l))+p.drop(l)+'\n'}}

```

It will add an extra newline at the end. If I did not have to preserve spaces at the end of the line, I can get it to 167:

```
def t(n:String)={val a=n.split('|').map(a=>a.prefixLength(' '==)->a.trim)
(""/:a){(s,l)=>val b=a.unzip._1.distinct.sorted
s+" "*b.reverse(b.indexOf(l._1))+l._2+'\n'}}

```

Ungolfed:

```
      def reverseIndent(inString: String): String = {
    val lines = inString.split('\n')
    val linesByPrefixLength = lines.map { line =>
  line.prefixLength(char => char == ' ') -> line
    }
    val distinctSortedPrefixLengths = linesByPrefixLength.map(_._1).distinct.sorted
    val reversedPrefixes = distinctSortedPrefixLengths.reverse
    linesByPrefixLength.foldLeft("") { case (string, (prefixLength, line)) =>
  val newPrefixLength = reversedPrefixes(distinctSortedPrefixLengths.indexOf(prefixLength))
  val nextLinePrefix = " " * newPrefixLength
  string + nextLinePrefix + line.substring(prefixLength) + '\n'
    }
      }

```
> 1 votes

# Answer
# PowerShell, 112 bytes

```
$x=@($args|sls '(?m)^ *'-a|% m*|% v*|sort -u)
[regex]::Replace($args,'(?m)^ *',{$x[-1-$x.IndexOf($args.Value)]})

```

Try it online!

Less golfed:

```
$xIdents=@($args|select-string '(?m)^ *'-AllMatches|% matches|% value|sort -unique) # get a sorted set of indentations
[regex]::Replace($args,'(?m)^ *',{$xIdents[-1-$xIdents.IndexOf($args.Value)]})    # replace each indentation with opposite one

```
> 1 votes

# Answer
## JavaScript, 351

```
var i=0;var a=$("#i").html().split("\n");var b=[];for(;i<a.length;i++){j=a[i].match(/\s*/)[0];if(b.indexOf(j)<0){b.push(j);}}b.sort(function(a,b){return a - b;});var c=b.slice().reverse();var d="";for(i=0;i<a.length;i++){d+=a[i].replace(/\s*/,c[b.indexOf(a[i].match(/\s*/)[0])])+"\n";j=a[i].search(/\S/);if(b.indexOf(j)<0){b.push(j);}}$("#i").html(d);

```

Ungolfed version:

```
var i = 0;
var a = $("#i").html().split("\n");
var b = [];
for (; i < a.length; i++) {
  j = a[i].match(/\s*/)[0];
  if (b.indexOf(j) < 0) {
    b.push(j);
  }
}
b.sort(function(a, b) {
  return a - b;
});
var c = b.slice().reverse();
var d = "";
for (i = 0; i < a.length; i++) {
  d += a[i].replace(/\s*/, c[b.indexOf(a[i].match(/\s*/)[0])]) + "\n";
  j = a[i].search(/\S/);
  if (b.indexOf(j) < 0) {
    b.push(j);
  }
}
$("#i").html(d);

```

### Testing

```
var i=0;var a=$("#i").html().split("\n");var b=[];for(;i<a.length;i++){j=a[i].match(/\s*/)[0];if(b.indexOf(j)<0){b.push(j);}}b.sort(function(a,b){return a - b;});var c=b.slice().reverse();var d="";for(i=0;i<a.length;i++){d+=a[i].replace(/\s*/,c[b.indexOf(a[i].match(/\s*/)[0])])+"\n";j=a[i].search(/\S/);if(b.indexOf(j)<0){b.push(j);}}$("#i").html(d);
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre><code id="i">
function fib(n) {
    var a = 1, b = 1;
        while (--n > 0) {
            var tmp = a;
            a = b;
            b += tmp;
            if (a === Infinity) {
                return "Error!";
            }
        }
    return a;
}
</code></pre>
```

```
var i=0;var a=$("#i").html().split("\n");var b=[];for(;i<a.length;i++){j=a[i].match(/\s*/)[0];if(b.indexOf(j)<0){b.push(j);}}b.sort(function(a,b){return a - b;});var c=b.slice().reverse();var d="";for(i=0;i<a.length;i++){d+=a[i].replace(/\s*/,c[b.indexOf(a[i].match(/\s*/)[0])])+"\n";j=a[i].search(/\S/);if(b.indexOf(j)<0){b.push(j);}}$("#i").html(d);
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre><code id="i">
a
  b
  c
d
   e
        f
  g
   h
</code></pre>
```

```
var i=0;var a=$("#i").html().split("\n");var b=[];for(;i<a.length;i++){j=a[i].match(/\s*/)[0];if(b.indexOf(j)<0){b.push(j);}}b.sort(function(a,b){return a - b;});var c=b.slice().reverse();var d="";for(i=0;i<a.length;i++){d+=a[i].replace(/\s*/,c[b.indexOf(a[i].match(/\s*/)[0])])+"\n";j=a[i].search(/\S/);if(b.indexOf(j)<0){b.push(j);}}$("#i").html(d);
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre><code id="i">
1
 2
  3
 2
1
</code></pre>
```

```
var i=0;var a=$("#i").html().split("\n");var b=[];for(;i<a.length;i++){j=a[i].match(/\s*/)[0];if(b.indexOf(j)<0){b.push(j);}}b.sort(function(a,b){return a - b;});var c=b.slice().reverse();var d="";for(i=0;i<a.length;i++){d+=a[i].replace(/\s*/,c[b.indexOf(a[i].match(/\s*/)[0])])+"\n";j=a[i].search(/\S/);if(b.indexOf(j)<0){b.push(j);}}$("#i").html(d);
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre><code id="i">
  foo
</code></pre>
```
> 0 votes

# Answer
## PHP - 173 bytes

The unoptimized code should be stored in the `$v` variable:

```
<?php $f='preg_replace';$f($p='#^ *#me','$i[]='.$s='strlen("$0")',$v);$a=$b=array_unique($i);sort($a);rsort($b);echo$f($p,'str_repeat(" ",array_combine($a,$b)['.$s.'])',$v);

```

Here is the ungolfed and commented version:

```
<?php
// Get the level of indentation for each line
$preg_replace = 'preg_replace';
$pattern = '#^ *#me';
$strlen = 'strlen("$0")';
$preg_replace($pattern, '$indentationLevelsOldList[] = '. $strlen, $value);

// Create an array associating the old level of indentation with the new expected one
$sortedArray = array_unique($indentationLevelsOldList);
$reverseSortedArray = $sortedArray;

sort($sortedArray);
rsort($reverseSortedArray);

$indentationLevelsNewList = array_combine($sortedArray, $reverseSortedArray);

// Print the correctly indented code
echo $preg_replace($pattern, 'str_repeat(" ", $indentationLevelsNewList['. $strlen .'])', $value);

```

I've probably never written something so dirty. I'm ashamed.
> 0 votes

# Answer
# Perl 5, 112

111 + 1 for `-n` (`-E` is free)

```
@{$.[$.]}=/( *)(.*)/;++$_{$1}}{map$_{$_[$#_-$_]}=$_[$_],0..(@_=sort keys%_);say$_{$.[$_][0]}.$.[$_][1]for 0..$.

```

I'm sure it can be done in fewer strokes, but I don't see how at the moment.
> 0 votes

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


title: Pointer jumping

text:
# Question
Title: Pointer jumping
Suppose we have an array \\$\texttt{ps}\\$ of length \\$n\\$ with pointers pointing to some location in the array: The process of "*pointer jumping*" will set every pointer to the location the pointer it points to points to.

For the purpose of this challenge a pointer is the (zero-based) index of an element of the array, this implies that every element in the array will be greater or equal to \\$0\\$ and less than \\$n\\$. Using this notation the process can be formulated as follows:

```
for i = 0..(n-1) {
  ps[i] = ps[ps[i]]
}

```

This means (for this challenge) that the pointers are updated in-place in sequential order (ie. lower indices first).

## Example

Let's work through an example, \\$\texttt{ps = \[2,1,4,1,3,2\]}\\$:

$$ \texttt{i = 0}: \text{the element at position }\texttt{ps\[0\] = 2}\text{ points to }\texttt{4} \\ \to \texttt{ps = \[4,1,4,1,3,2\]} \\ \texttt{i = 1}: \text{the element at position }\texttt{ps\[1\] = 1}\text{ points to }\texttt{1} \\ \to \texttt{ps = \[4,1,4,1,3,2\]} \\ \texttt{i = 2}: \text{the element at position }\texttt{ps\[2\] = 4}\text{ points to }\texttt{3} \\ \to \texttt{ps = \[4,1,3,1,3,2\]} \\ \texttt{i = 3}: \text{the element at position }\texttt{ps\[3\] = 1}\text{ points to }\texttt{1} \\ \to \texttt{ps = \[4,1,3,1,3,2\]} \\ \texttt{i = 4}: \text{the element at position }\texttt{ps\[4\] = 3}\text{ points to }\texttt{1} \\ \to \texttt{ps = \[4,1,3,1,1,2\]} \\ \texttt{i = 5}: \text{the element at position }\texttt{ps\[5\] = 2}\text{ points to }\texttt{3} \\ \to \texttt{ps = \[4,1,3,1,1,3\]} $$

So after **one iteration** of "*pointer jumping*" we get the array \\$\texttt{\[4,1,3,1,1,3\]}\\$.

## Challenge

Given an array with indices output the array obtained by iterating the above described pointer jumping until the array does not change anymore.

## Rules

Your program/function will take and return/output the same type, a list/vector/array etc. which

* is guaranteed to be non-empty and
* is guaranteed to only contain entries \\$0 \leq p \< n\\$.

**Variants:** You may choose

* to use 1-based indexing or
* use actual pointers,

however you should mention this in your submission.

## Test cases

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

```

# Answer
> 8 votes
# JavaScript, 36 bytes

Modifies the original input array.

```
a=>a.map(_=>a.map((x,y)=>a[y]=a[x]))

```

Try it online

# Answer
> 6 votes
# Python 2, 53 bytes

```
def f(l):L=len(l);i=0;exec'l[i]=l[l[i]];i=-~i%L;'*L*L

```

Try it online!

-6 thanks to HyperNeutrino.

Alters `l` to the result in place.

# Answer
> 6 votes
## Haskell, 56 bytes

```
foldr(\_->([]#))=<<id
x#a@(b:c)=(x++[(x++a)!!b])#c
x#_=x

```

Haskell and in-place updates are a bad match.

Try it online!

# Answer
> 5 votes
# C++14 (gcc), 61 bytes

As unnamed generic lambda. Requires sequential containers like `std::vector`.

```
[](auto&c){auto d=c;do{d=c;for(auto&x:c)x=c[x];}while(d!=c);}

```

Try it online!

# Answer
> 5 votes
## Swift, ~~68~~ 53 bytes

```
{a in for _ in a{var i=0;a.forEach{a[i]=a[$0];i+=1}}}

```

Try it online!

-15 thanks to BMO

# Answer
> 4 votes
# JavaScript (ES6), 41 bytes

```
f=a=>a+''==a.map((x,i)=>a[i]=a[x])?a:f(a)

```

Try it online!

# Answer
> 4 votes
# Japt, ~~15~~ ~~13~~ 7 bytes

Modifies the original input array.

```
££hYXgU

```

Try it (additional bytes are to write the modified input to the console)

```
££hYXgU
£           :Map
 £          :  Map each X at index Y
  hY        :    Replace the element at index Y
    XgU     :    With the element at index X

```

# Answer
> 4 votes
# 05AB1E (legacy), 8 bytes

```
ΔDvDyèNǝ

```

Try it online!

**Explanation**

```
Δ          # apply until the top of the stack stops changing
 D         # duplicate current list
  v        # for each (element y, index N) in the list
   Dyè     # get the element at index y
      Nǝ   # and insert it at index N

```

# 05AB1E, 14 bytes

```
[D©vDyèNǝ}D®Q#

```

Try it online!

# Answer
> 4 votes
# Java 8, ~~105~~ 54 bytes

```
a->{for(int l=a.length,i=0;i<l*l;)a[i%l]=a[a[i++%l]];}

```

Modifies the input-array instead of returning a new one to save bytes.

-51 bytes by just modifying the array \\$length^2\\$ times, instead of until it no longer changes.

Try it online.

**Explanation:**

```
a->{                // Method with integer-array parameter and no return-type
  int l=a.length,   //  Length of the input-array
  i=0;i<l*l;)       //  Loop `i` in the range [0, length squared):
    a[i%l]=         //   Set the (`i` modulo-length)'th item in the array to:
      a[            //    The `p`'th value of the input-array,
        a[i++%l]];} //    where `p` is the (`i` modulo-length)'th value of the array

```

# Answer
> 3 votes
# Japt, 17 bytes

```

®
£hYUgX
eV ?U:ß

```

Try all test cases

This feels like it should be shorter, but unfortunately my initial thought of `UmgU` doesn't work because each `g` accesses the original `U` rather than modifying it at each step. Preserving different components appropriately cost a handful of bytes as well.

Explanation:

```
           #Blank line preserves input in U long enough for the next line

®          #Copy U into V to preserve its original value

£hY        #Modify U in-place by replacing each element X with...
   UgX     #The value from the current U at the index X

eV ?U      #If the modified U is identical to the copy V, output it
     :ß    #Otherwise start again with the modified U as the new input

```

# Answer
> 3 votes
# C (clang), 32-bit, ~~49~~ 44 bytes

```
i;f(**p,n){for(i=0;i<n*n;)p[i++%n]=*p[i%n];}

```

Try it online!

Uses pointers.

**~~50~~ 45 bytes** with integers:

```
i;f(*p,n){for(i=0;i<n*n;)p[i++%n]=p[p[i%n]];}

```

Try it online!

# Answer
> 2 votes
# Ruby, ~~37~~ 34 bytes

```
->a{a.size.times{a.map!{|x|a[x]}}}

```

Try it online!

Returns by modifying the input array in-place.

# Answer
> 2 votes
# , ~~60~~ 58 bytes

-2 bytes thanks to @digEmAll for reading the rules.

```
function(x,n=sum(x|1)){for(i in rep(1:n,n))x[i]=x[x[i]];x}

```

Try it online!

1-indexed.

`n` is the length of the input array.

`rep(1:n,n)` replicates `1:n` `n` times (e.g. `n=3 => 1,2,3,1,2,3,1,2,3`)

Loop through the array `n` times. Steady state will be acheived by then for sure, in fact by the end of the n-1st time through I think. The proof is left to the reader.

# Answer
> 2 votes
# Clojure, 136 bytes

```
(defn j[a](let[f(fn[a](loop[i 0 a a](if(= i(count a))a(recur(inc i)(assoc a i(a(a i)))))))](loop[p nil a a](if(= p a)a(recur a(f a))))))

```

Try it online!

# Answer
> 2 votes
# Red, 63 bytes

```
func[b][loop(l: length? b)* l[repeat i l[b/:i: b/(1 + b/:i)]]b]

```

Try it online!

Modifies the array in place

# Answer
> 2 votes
# Common Lisp, ~~59~~ 58 bytes

```
(lambda(a)(dolist(j a)(map-into a(lambda(x)(elt a x))a))a)

```

Try it online!

# Answer
> 2 votes
# Clean, 80 bytes

```
import StdEnv

```

#

```
limit o iterate\b=foldl(\l i=updateAt i(l!!(l!!i))l)b(indexList b)

```

Try it online!

# Answer
> 1 votes
# Perl 5, ~~35~~ ~~34~~ 26 bytes

using the fact that convergence is reach at most for the size number of iterations

```
$_=$F[$_]for@F x@F;$_="@F"

```

26 bytes

```
$_=$F[$_]for@F;/@F/ or$_="@F",redo

```

34 bytes

```
$_=$F[$_]for@F;$_="@F",redo if!/@F/

```

35 bytes

# Answer
> 1 votes
# Clojure, 88 bytes

```
#(reduce(fn[x i](assoc x i(get x(get x i))))%(flatten(repeat(count %)(range(count %)))))

```

Try it online!

# Answer
> 1 votes
# Charcoal, 16 bytes

```
ＦθＦＬθ§≔θκ§θ§θκＩθ

```

Try it online! Link is to verbose version of code. Sadly all the usual mapping functions only operate on a copy of the array with the result being that they just permute the elements rather than jumping them, so the code has to do everything manually. Explanation:

```
Ｆθ

```

Repeat the inner loop once for each element. This just ensures that the result stabilises.

```
ＦＬθ

```

Loop over the array indices.

```
§≔θκ§θ§θκ

```

Get the array element at the current index, use that to index into the array, and replace the current element with that value.

```
Ｉθ

```

Cast the elements to string and implicitly print each on their own line.

# Answer
> 1 votes
# F#, ~~74~~ 73 bytes

```
fun(c:'a[])->let l=c.Length in(for i in 0..l*l do c.[i%l]<-c.[c.[i%l]]);c

```

Nothing special. Uses the modulus idea seen in other answers.

# Answer
> 1 votes
## K, 27 Bytes

```
{{@[x;y;:;x x y]}/[x;!#x]}/

```
* `{..}/` applies lambda {..} over arg (until convergence)
* inside outer lambda:

+ `{..}/[x;y]` applies lambda iteratively over x (updated at each iteration) and an item of y (y is a list of values, and uses an item at each iteration). In this case arg y is `!#x`(til count x, that is, indexes of the array)
    + `@[x;y;:;x x y]` amend array x (at index y assign x\[x\[y\]\])

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

Requires `⎕IO←0`

```
{m⊣{m[⍵]←m[m[⍵]]}¨⍳≢m←⍵}⍣≡

```

Try it online!

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