title: An expanding array

text:
# Question
Title: An expanding array
Given two positive integers **p** and **q**, your task is to return the array **A** created by applying the following algorithm:

1. Start with **A = \[p, q\]** and **d = 2**
2. For each pair **(x, y)** of contiguous numbers in **A** whose sum is divisible by **d**, insert **(x + y) / d** between **x** and **y**.
3. If at least one matching pair was found, increment **d** and go on with step #2. Otherwise, stop and return **A**.

## Example

Below is the detail of the process for **p = 1** and **q = 21**.

```
  1  21             | Iteration #1: we start with d = 2 and A = [1, 21]
   \/               |               1 + 21  is divisible by 2 -> we insert 11
 22/2=11            |
                    |
  1  11 21          | Iteration #2: d = 3, A = [1, 11, 21]
   \/               |               1 + 11  is divisible by 3 -> we insert 4
 12/3=4             |
                    |
  1 4 11  21        | Iteration #3: d = 4, A = [1, 4, 11, 21]
        \/          |               11 + 21 is divisible by 4 -> we insert 8
      32/4=8        |
                    |
  1    4    11 8 21 | Iteration #4: d = 5, A = [1, 4, 11, 8, 21]
    \/   \/         |               1 + 4   is divisible by 5 -> we insert 1
  5/5=1 15/5=3      |               4 + 11  is divisible by 5 -> we insert 3
                    |
  1 1 4 3 11 8 21   | Iteration #5: d = 6, A = [1, 1, 4, 3, 11, 8, 21]
                    |               no sum of two contiguous numbers is divisible by 6
                    |               -> we stop here

```

Hence the expected output: **\[1, 1, 4, 3, 11, 8, 21\]**

## Clarifications and rules

* Input and output can be handled in any reasonable format. The integers **p** and **q** are guaranteed to be greater than 0. If that helps, you may assume **q ≥ p**.
* The 2nd step of the algorithm should ***not*** be recursively applied to elements that have just been inserted at the same iteration. For instance, **A = \[1, 1\]** and **d = 2** should lead to **\[1, 1, 1\]** (not an infinite list of 1's).
* This is , so the shortest answer in bytes wins!

## Test cases

```
  p |   q | Output
----+-----+-------------------------------------------------------------------------------
  1 |   1 | [1,1,1]
  1 |   2 | [1,2]
  1 |   3 | [1,1,2,3]
  2 |   6 | [2,1,2,1,4,1,2,6]
  3 |  13 | [3,1,8,1,3,1,7,1,2,1,5,1,3,2,13]
  9 |   9 | [9,6,9,6,9]
 60 |  68 | [60,13,1,4,31,2,3,5,2,19,64,7,13,1,2,5,2,27,44,3,4,8,2,1,12,1,5,3,28,2,4,16,1,
    |     |  2,12,1,2,1,10,1,6,68]
144 | 336 | [144,68,3,4,8,1,12,1,4,2,28,13,128,44,17,92,240,58,108,5,17,1,2,5,3,28,3,1,11,
    |     |  60,3,6,2,42,2,4,26,192,54,132,7,1,15,1,3,1,18,1,4,2,30,3,1,12,1,9,78,46,336]

```

If you'd like to test your code on a slightly bigger test case, **here** is the expected output for:

* **p = 12096** (26\*33\*7)
* **q = 24192** (27\*33\*7)

# Answer
> 6 votes
# 05AB1E, ~~28~~ ~~19~~ 18 bytes

```
[Ðü+NÌ/‚ζ˜ʒ.ï}DŠQ#

```

Try it online!

---

~~eh, can definitely be improved hardcore. still working to refactor.~~

~~Probably as good as I'm getting it.~~

***-1 thanks to, who else but, Emigna! For pointing out swap worked better than the registers.***

---

```
[                   // Infinite loop.
 Ð                  // Triplicate [p, ..., q]
  U                 // Pop 1 of 3 copies into register X.
   ü+               // Pairwise addition.
     NÌ/            // Divide by current iteration + 2 (which is d).
        ‚           // Group original [p, ..., q] with pairwise additives.
         ζ˜         // Transpose together and flatten.
           ʒ.ï}     // Filter out non-integer entities (includes the space added by zip).
               DXQ  // Dupe result, see if equal to original.
                  # // If new array is original array, nothing happened, quit & return.

```

---

Debug dump for `[p,q] = [1,3]`:

```
Full program: [ÐUü+NÌ/‚ζ˜ʒ.ï}DXQ#
current >> [  ||  stack: []
ÐUü+NÌ/‚ζ˜ʒ.ï}DXQ#
Full program: ÐUü+NÌ/‚ζ˜ʒ.ï}DXQ#
current >> Ð  ||  stack: []
current >> U  ||  stack: [[1, 3], [1, 3], [1, 3]]
current >> ü  ||  stack: [[1, 3], [1, 3]]
Full program: +
current >> +  ||  stack: [1, 3]
stack > [4]
current >> N  ||  stack: [[1, 3], [4]]
current >> Ì  ||  stack: [[1, 3], [4], 0]
current >> /  ||  stack: [[1, 3], [4], 2]
current >> ‚  ||  stack: [[1, 3], [2.0]]
current >> ζ  ||  stack: [[[1, 3], [2.0]]]
current >> ˜  ||  stack: [[[1, 2.0], [3, ' ']]]
current >> ʒ  ||  stack: [[1, 2.0, 3, ' ']]
Filter: .ï
Full program: .ï
current >> .  ||  stack: [1]
stack > [1]
Full program: .ï
current >> .  ||  stack: [2.0]
stack > [1]
Full program: .ï
current >> .  ||  stack: [3]
stack > [1]
Full program: .ï
current >> .  ||  stack: [' ']
invalid literal for int() with base 10: ' '
stack > []
current >> D  ||  stack: [[1, 2.0, 3]]
current >> X  ||  stack: [[1, 2.0, 3], [1, 2.0, 3]]
current >> Q  ||  stack: [[1, 2.0, 3], [1, 2.0, 3], [1, 3]]
current >> #  ||  stack: [[1, 2.0, 3], 0]
stack > [[1, 2.0, 3]]
Full program: ÐUü+NÌ/‚ζ˜ʒ.ï}DXQ#
current >> Ð  ||  stack: [[1, 2.0, 3]]
current >> U  ||  stack: [[1, 2.0, 3], [1, 2.0, 3], [1, 2.0, 3]]
current >> ü  ||  stack: [[1, 2.0, 3], [1, 2.0, 3]]
Full program: +
current >> +  ||  stack: [1, 2.0]
stack > [3.0]
Full program: +
current >> +  ||  stack: [3.0, 2.0, 3]
stack > [3.0, 5.0]
current >> N  ||  stack: [[1, 2.0, 3], [3.0, 5.0]]
current >> Ì  ||  stack: [[1, 2.0, 3], [3.0, 5.0], 1]
current >> /  ||  stack: [[1, 2.0, 3], [3.0, 5.0], 3]
current >> ‚  ||  stack: [[1, 2.0, 3], [1.0, 1.6666666666666667]]
current >> ζ  ||  stack: [[[1, 2.0, 3], [1.0, 1.6666666666666667]]]
current >> ˜  ||  stack: [[[1, 1.0], [2.0, 1.6666666666666667], [3, ' ']]]
current >> ʒ  ||  stack: [[1, 1.0, 2.0, 1.6666666666666667, 3, ' ']]
Filter: .ï
Full program: .ï
current >> .  ||  stack: [1]
stack > [1]
Full program: .ï
current >> .  ||  stack: [1.0]
stack > [1]
Full program: .ï
current >> .  ||  stack: [2.0]
stack > [1]
Full program: .ï
current >> .  ||  stack: [1.6666666666666667]
stack > [0]
Full program: .ï
current >> .  ||  stack: [3]
stack > [1]
Full program: .ï
current >> .  ||  stack: [' ']
invalid literal for int() with base 10: ' '
stack > []
current >> D  ||  stack: [[1, 1.0, 2.0, 3]]
current >> X  ||  stack: [[1, 1.0, 2.0, 3], [1, 1.0, 2.0, 3]]
current >> Q  ||  stack: [[1, 1.0, 2.0, 3], [1, 1.0, 2.0, 3], [1, 2.0, 3]]
current >> #  ||  stack: [[1, 1.0, 2.0, 3], 0]
stack > [[1, 1.0, 2.0, 3]]
Full program: ÐUü+NÌ/‚ζ˜ʒ.ï}DXQ#
current >> Ð  ||  stack: [[1, 1.0, 2.0, 3]]
current >> U  ||  stack: [[1, 1.0, 2.0, 3], [1, 1.0, 2.0, 3], [1, 1.0, 2.0, 3]]
current >> ü  ||  stack: [[1, 1.0, 2.0, 3], [1, 1.0, 2.0, 3]]
Full program: +
current >> +  ||  stack: [1, 1.0]
stack > [2.0]
Full program: +
current >> +  ||  stack: [2.0, 1.0, 2.0]
stack > [2.0, 3.0]
Full program: +
current >> +  ||  stack: [2.0, 3.0, 2.0, 3]
stack > [2.0, 3.0, 5.0]
current >> N  ||  stack: [[1, 1.0, 2.0, 3], [2.0, 3.0, 5.0]]
current >> Ì  ||  stack: [[1, 1.0, 2.0, 3], [2.0, 3.0, 5.0], 2]
current >> /  ||  stack: [[1, 1.0, 2.0, 3], [2.0, 3.0, 5.0], 4]
current >> ‚  ||  stack: [[1, 1.0, 2.0, 3], [0.5, 0.75, 1.25]]
current >> ζ  ||  stack: [[[1, 1.0, 2.0, 3], [0.5, 0.75, 1.25]]]
current >> ˜  ||  stack: [[[1, 0.5], [1.0, 0.75], [2.0, 1.25], [3, ' ']]]
current >> ʒ  ||  stack: [[1, 0.5, 1.0, 0.75, 2.0, 1.25, 3, ' ']]
Filter: .ï
Full program: .ï
current >> .  ||  stack: [1]
stack > [1]
Full program: .ï
current >> .  ||  stack: [0.5]
stack > [0]
Full program: .ï
current >> .  ||  stack: [1.0]
stack > [1]
Full program: .ï
current >> .  ||  stack: [0.75]
stack > [0]
Full program: .ï
current >> .  ||  stack: [2.0]
stack > [1]
Full program: .ï
current >> .  ||  stack: [1.25]
stack > [0]
Full program: .ï
current >> .  ||  stack: [3]
stack > [1]
Full program: .ï
current >> .  ||  stack: [' ']
invalid literal for int() with base 10: ' '
stack > []
current >> D  ||  stack: [[1, 1.0, 2.0, 3]]
current >> X  ||  stack: [[1, 1.0, 2.0, 3], [1, 1.0, 2.0, 3]]
current >> Q  ||  stack: [[1, 1.0, 2.0, 3], [1, 1.0, 2.0, 3], [1, 1.0, 2.0, 3]]
current >> #  ||  stack: [[1, 1.0, 2.0, 3], 1]
[1, 1.0, 2.0, 3]
stack > [[1, 1.0, 2.0, 3]]

```

Try it online with debug!

# Answer
> 8 votes
# Mathematica, ~~72~~ ~~64~~ ~~59~~ 58 bytes

```
(d=2;#//.x_:>Riffle[x,(x+{##2,}&@@x)/d++]~Cases~_Integer)&

```

Try it online!

### How it works

We take the input as a list `{p,q}`. The iteration step is reformulated as:

1. Insert `(a+b)/d` between *every* two elements `a` and `b`: `(x+{##2,}&@@x)` computes the sequence of `a+b`'s, with an `a+Null` at the end. We divide by `d`, and `Riffle` inserts each `(a+b)/d` between `a` and `b`. Increment `d`.
2. Pick out the `Integer` elements of the resulting list. (This gets rid of the `Null` introduced by `{##2,}`, too.)

This is repeated until the result doesn't change (which can only happen because we removed all the new elements, because none of them were integers).

*-8 bytes thanks to @MartinEnder from using `//.` instead of `FixedPoint` (and from taking input as a list).*

*-6 more because `ListConvolve` actually isn't that great*

# Answer
> 4 votes
# Ruby, 80 bytes

```
->a,d=2{*b=a[0];a.each_cons 2{|x,y|z=x+y;b+=z%d>0?[y]:[z/d,y]};b==a ?a:f[b,d+1]}

```

Try it online!

Recursive function `f` taking input as the array `[p, q]`.

# Answer
> 4 votes
## Haskell, ~~85~~ 81 bytes

```
(a:b:c)#d=a:[div(a+b)d|mod(a+b)d<1]++(b:c)#d
l#d=l
l%d|l==l#d=l|e<-d+1=l#d%e
(%2)

```

Try it online!

The input is taken as a list, e.g. `[1,2]`.

Edit: -4 bytes thanks to @Laikoni.

# Answer
> 3 votes
# Python 2, ~~112~~ ~~110~~ ~~108~~ ~~105~~ 103 bytes

-2 bytes thanks to Jonathan Frech
-5 bytes thanks to Erik the Outgolfer

```
y=input()
x=d=1
while x!=y:
 d+=1;x=y;y=x[:1]
 for a,b in zip(x,x[1:]):c=a+b;y+=[c/d,b][c%d>0:]
print x

```

Try it online!

# Answer
> 3 votes
# Python 2, 98 bytes

```
f=lambda A,B=0,d=2:A*(A==B)or f(sum([[(l+r)/d,r][(l+r)%d>0:]for l,r in zip(A,A[1:])],A[:1]),A,d+1)

```

Invoke as `f([p,q])`. Try it online!

Jonathan Allan saved 12 bytes. Thanks~!

## Explanation

`f` is a recursive function: `f(A, B, d)` evalutes to `f(next_A, A, d+1)`, unless `A == B`, in which case it returns `A`. (This is handled by `A*(A==B)or …`: if A ≠ B, `A*(A==B)` is the empty list, which is false-y, so the  part is evaluated; if A = B then `A*(A==B)` is `A`, which is non-empty and thus truthy, and it gets returned.)

`next_A` is computed as:

```
sum([[(l+r)/d,r][(l+r)%d>0:]for l,r in zip(A,A[1:])],A[:1])

```

This is best explained by example. When e.g. `d = 5` and `A = [1, 4, 11, 8, 21]`:

```
  sum([[(l+r)/d,r][(l+r)%d>0:]for l,r in zip(A,A[1:])],A[:1])
= sum([[(1+4)/d, 4], [(4+11)/d, 11], [8], [21]], [1])
= [1] + [1, 4] + [3, 11] + [8] + [21]
= [1, 1, 4, 3, 11, 8, 21]

```

# Answer
> 2 votes
# Python 2, 111 bytes

```
A=input()
m=d=1
while m:
 m=o=0;d+=1
 while A[o+1:]:
	o+=1;s=A[o-1]+A[o]
	if s%d<1:A[o:o]=s/d,;m=1;o+=1
print A

```

Try it online!

-8 thanks to Rod.
-2 thanks to Lynn.

# Answer
> 2 votes
# Husk, 22 bytes

```
→UG`λf£NΣẊṠeo/⁰+:.)⁰tN

```

Takes a 2-element list, returns list of integers and floats. Try it online!

## Explanation

```
→UG`λf£NΣẊṠeo/⁰+:.)⁰tN  Input is a list L.
  G                 tN  Cumulative reduce over the list [2,3,4..
                   ⁰    with initial value L
   `λ             )     using flipped version of this function:
     f£NΣẊṠeo/⁰+:.       Arguments are a list, say K=[1,3,3], and a number, say d=4.
                :.       Prepend 0.5: [0.5,1,2,3]
         Ẋ               For each adjacent pair,
               +         take their sum,
            o/⁰          divide by d,
          Ṡe             and pair it with the right number in the pair: [[0.375,1],[1.0,3],[1.5,3]]
        Σ                Concatenate: [0.375,1,1.0,3,1.5,3]
     f£N                 Remove non-integers: [1,1.0,3,3]
                        Now we have an infinite list of L threaded through 2,3,4.. using the expansion operation.
 U                      Take longest prefix of unique elements,
→                       then last element of that.

```

# Answer
> 1 votes
# Perl 5, 92 + 1 (`-a`) = 93 bytes

```
do{$c=0;@n=shift@F;$.++;push@n,($t=$_+$n[-1])%$.?$_:($c=$t/$.,$_)for@F;@F=@n}while$c;say"@F"

```

Try it online!

# Answer
> 1 votes
# JavaScript (ES6), ~~89~~ ~~87~~ 82 bytes

*Thanks @Arnauld for -2 bytes and for helping save 5 more bytes.*

```
f=(a,d=2,r)=>a.map(v=>b.push(v,...(v+=a[++i])%d<1?[r=v/d]:[]),b=i=[])|r?f(b,d+1):a

```

Takes input as an array: `f([p,q])`.

## Test Cases

```
f=(a,d=2,r)=>a.map(v=>b.push(v,...(v+=a[++i])%d<1?[r=v/d]:[]),b=i=[])|r?f(b,d+1):a

;[[1,1],[1,2],[1,3],[2,6],[3,13],[9,9],[60,68],[144,336],[12096,24192]]
.forEach(test=>O.innerText+=JSON.stringify(test)+" -> "+JSON.stringify(f(test))+"\n")
```

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

# Answer
> 1 votes
# Retina, 111 bytes

```
\d+
$*1;
^
11@
{+`(1+); (1+);
$1; $1$2 $2;
(?<=(?=(1+)).*) (\1)+
 a$#2$*1;
 1+

.*a
1$&
)`a

1+@

1+
$.&
;

```

Try it online!

Takes the input as space separated numbers. Quite naively follows the given algorithm, with the only notable technique being to use a marker symbol, `a`, to note when any of the numbers had been kept. This is used to work with Retina's somewhat limited looping capabilities, which only allows you to loop until a set of stages makes no overall change to the input to those stages.

### Explanation:

This will use the same example as in the question.

```
\d+
$*1;

```

We change the input array of numbers into a semicolon separated unary array, so we'd have:

```
1; 111111111111111111111;

^
11@

```

Put `d` into our code at the beginning, giving us:

```
11@1; 111111111111111111111;

{+`(1+); (1+);
$1; $1$2 $2;

```

This is slightly more complicated. `{` starts a group of stages that will be executed until they reach a fixed point. Then, `+` indicates that this stage itself should be executed until a fixed point. This stage adds each pair of adjacent numbers but inserts them without the additional semicolon. Now we'd have:

```
11@1; 1111111111111111111111 111111111111111111111;

(?<=(?=(1+)).*) (\1)+
 a$#2$*1;

```

The other tricky stage, this one accumulates our divisor in the first capture group, and replaces any number in our list without a trailing semicolon with that number divided by `d`. We also add a leading `a` to these numbers, to indicate that something was kept, along with the `;` to indicate it should be permanently part of the array. Now we'd have:

```
11@1; a11111111111; 111111111111111111111;

```

```
 1+

```

This deletes numbers that were not divisible by `d` nor in the array before this round. This makes no changes in our example.

```
.*a
1&$

```

This greedily matches from the beginning of the string to the last letter `a` in the input. This means there can be at most one match. If we made any changes, we add one to `d`, otherwise leaving it the same so we can exit the loop.

```
111@1; a11111111111; 111111111111111111111;

```

```
)`a

```

The `)` closes the loop started by `{` (don't question it!) and otherwise this stage just removes the markers we put down earlier. Since this is the end of the loop, we would repeat the above stages many times, however I'm just going to continue as though I had forgotten the loop, since it makes the example more continuous.

```
111@1; 11111111111; 111111111111111111111;

```

```
1+@

```

This stage removes from our output:

```
1; 11111111111; 111111111111111111111;

1+
$.&

```

This stage replaces the unary numbers with decimal numbers:

```
1; 11; 21;

```

```
;

```

The final stage gets rid of the semicolons:

```
1 11 21

```

Obviously, skipping out on the loop makes us have an incorrect result here, but hopefully that isn't too confusing.

# Answer
> 1 votes
# Röda, 90 bytes

```
f a,d=2{A=[a()|slide 2|[_,(_1+_)/d]if[(_1+_2)%d=0]else[_1]]+a[-1]f A,d=d+1 if[a!=A]else A}

```

Try it online!

# Answer
> 1 votes
# Java 8, 180 bytes

```
import java.util.*;p->q->{List<Integer>r=new Stack();r.add(p);r.add(q);for(int d=1,f=d,i;f==d++;)for(i=1;i<r.size();i++)if((q=r.get(i)+r.get(i-1))%d<1)r.add(i++,q/(f=d));return r;}

```

**Explanation:**

Try it here.

```
import java.util.*;           // Required import for List and Stack

p->q->{                       // Method with two integer parameters and List return-type
  List<Integer>r=new Stack(); //  Result-list
  r.add(p);r.add(q);          //  Add the two input-integers to the List
  for(int d=1,                //  Divisible integer (starting at 1)
          f=d,                //  Temp integer (starting at `d` / also 1)
          i;                  //  Index-integer
      f==d++;)                //  Loop (1) as long as `f` and `d` are equal
                              //  (and raise `d` by 1 so it starts at 2 inside the loop)
    for(i=1;                  //   Reset index-integer to 1
        i<r.size();i++)       //   Inner loop (2) over the List
      if((q=r.get(i)+r.get(i-1))
                              //    If the current + previous items (stored in `q`)
         %d<1)                //    are divisible by `d`:
        r.add(i++,q/(f=d));   //     Insert `q` divided by `d` to the List at index `i`
                              //     (and raise `i` by 1 and set `f` to `d` in the process)
                              //   End of inner loop (2) (implicit / single-line body)
                              //  End of loop (1) (implicit / single-line body)
  return r;                   //  Return the result-List
}                             // End of method

```

# Answer
> 1 votes
**C#, 280 bytes**

```
using System.Linq;class A{static void Main(string[] p){var l=new System.Collections.Generic.List<int>(p.Select(int.Parse));int r,d=2,c;do{c=0;for(int i=1;i<l.Count;++i){if((r=l[i-1]+l[i])%d==0){l.Insert(i++,r/d);++c;}}++d;}while(c>0);l.ForEach(v=>System.Console.Write((v+" ")));}}

```

First attempt at code golf, which is the whole program. Test It

**Attempt 2, 159 bytes**

Taking away the scaffolding, since the task is to provide a function that can take a pair of numbers (an array works) and returns an array. Given that a Func\<int\[\],int\[\]\> *F* can be used to satisfy the requirements, just define *F*:

```
F=v=>{var l=new List<int>(v);int i,r,d=2,c;do{c=0;for(i=1;i<l.Count;++i){if((r=l[i-1]+l[i])%d==0){l.Insert(i++,r/d);++c;}}++d;}while(c>0);return l.ToArray();};

```

Test Full Program Here

This could be smaller if a generic List is considered a valid output (drop the .ToArray() to save 10 bytes).

If the input can also be modified, then passing in a List\<int\> instead of an array removes the need to initialize the output (comes out at 126 bytes).

Taking this a step further, there doesn't really need to be a return value in this case. Using an Action instead removes the 9 bytes used by the return statement.

# Answer
> 1 votes
# Jelly, 19 bytes

```
®‘©‘÷@+2\⁸żFfṀR$µÐL

```

Try it online!

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


title: Wait, but what's e^N?

text:
# Question
Title: Wait, but what's e^N?
**Objective:**

The objective is to calculate e^N for some real or imaginary N (e.g. 2, -3i, 0.7, 2.5i, but not 3+2i). This is code golf, so, shortest code (in bytes) wins.

So, for example:

1. N = 3, e^N = 20.0855392
2. N = -2i, e^N = -0.416146837 - 0.9092974268i

The letter `i` shouldn't be capitalized (since in math it is lowercase)

If your language supports raising numbers to complex numbers, you can't use that. You may use built-in real exponentiation.

For any answer where b (in a + bi) is negative, it is OK to have both the plus and minus sign (e.g. 2 + -3i), since that is understood to be (2 - 3i)

**Bonus (-15 bytes):** Solve this for N is a any complex number (e.g. 5 + 7i). If you are going for the bonus, you can assume that both components will always be given (even for the standard objective)

# Answer
# Mathematica, ~~23~~ 20 bytes - 15 = 5

```
E^#(Cos@#2+Sin@#2I)&

```

This is an anonymous function taking two arguments (real and imaginary component). You should supply floats unless you want exact result (with square roots and exponentials). So you can use this like

```
E^#(Cos@#2+Sin@#2I)&[3.0,-2.0]

```

Note that `I` is Mathematica's imaginary unit, but I'm not actually using any complex arithmetic. Also note, that Mathematica will actually print the result using a (double-struck) *lowercase* `i` as required. See the screenshot in belisarius's comment.
> 5 votes

# Answer
# CJam, 22 - 15 = 7

```
l~_mc\ms@me:X*\X*'+@'i

```

Try it online here

Takes input in the form of `a b` where `a` is the real component and `b` is the complex.

For ex. `2i` is

```
0 2

```

gives

```
-0.4161468365471424+0.9092974268256817i

```
> 6 votes

# Answer
# 80386 Assembly (41 bytes - 15 = 26)

```
8B 4C 24 04 8B 54 24 08 D9 EA DC 09 D9 C0 D9 FC DC E9 D9 C9 D9 F0 D9 E8 DE C1 D9 FD DD 02 D9 FB D8 CA DD 19 D8 C9 DD 1A C3

```

Floating point math in assembly is a pain..

This is a function (cdecl calling convention) that calculates `e^(a+bi)` via the relation `e^(a+bi)=e^a cos b + e^a sin b * i`. (It accepts two `double *` parameters, a and b in that order, and outputs the real part into the `a` pointer, and the imaginary part into the `b` pointer).

The function prototype in C would be:

```
void __attribute__((cdecl)) exp_complex(double *a, double *b);

```

About half (20, to be exact) of the 41 bytes were spent calculating `e^a`; another 8 were spent getting the function arguments into registers.

The above bytecode was written by hand, from the following assembly (NASM-style, commented):

```
; get pointers into ecx, edx
mov ecx, [esp+4] ; 8B 4C 24 04
mov edx, [esp+8] ; 8B 54 24 08

; log(2,e)
fldl2e           ; D9 EA
; a log(2,e)
fmul qword [ecx] ; DC 09
; duplicate
fld st0          ; D9 C0
; get integer part
frndint          ; D9 FC
; get fractional part
fsub st1, st0    ; DC E9
; put fractional part on top
fxch st1         ; D9 C9
; 2^(fract(a log(2,e))) - 1
f2xm1            ; D9 F0
; 2^(fract(a log(2,e)))
fld1             ; D9 E8
faddp st1        ; DE C1
; 2^(fract(a log(2,e))) * 2^(int(a log(2,e)))
; = e^a
fscale           ; D9 FD

; push b
fld qword [edx]  ; DD 02
; sin and cos
fsincos          ; D9 FB
; e^a cos b
fmul st2         ; D8 CA
; output as real part
fstp qword [ecx] ; DD 19
; e^a sin b
fmul st1         ; D8 C9
; output as imaginary part
fstp qword [edx] ; DD 1A

; exit
ret              ; C3

```

To try this in C (gcc, linux, intel processor):

```
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>

int main(){
    // bytecode from earlier
    char code[] = {
        0x8B, 0x4C, 0x24, 0x04, 0x8B, 0x54, 0x24, 0x08,
        0xD9, 0xEA, 0xDC, 0x09, 0xD9, 0xC0, 0xD9, 0xFC,
        0xDC, 0xE9, 0xD9, 0xC9, 0xD9, 0xF0, 0xD9, 0xE8,
        0xDE, 0xC1, 0xD9, 0xFD, 0xDD, 0x02, 0xD9, 0xFB,
        0xD8, 0xCA, 0xDD, 0x19, 0xD8, 0xC9, 0xDD, 0x1A,
        0xC3,
    };
    // allocate executable memory to a function pointer called 'exp_complex'
    void __attribute__( (__cdecl__) ) (*exp_complex)(double *,double *) = mmap(0,sizeof code,PROT_WRITE|PROT_EXEC,MAP_ANON|MAP_PRIVATE,-1,0);
    memcpy(exp_complex, code, sizeof code);

    // test inputs
    double a = 42.24, b = -2.7182818;

    printf("%.07g + %.07g i\n", a, b);

    // call bytecode as a c function
    exp_complex(&a, &b);

    printf("%.07g + %.07g i\n", a, b);

    // release allocated memory
    munmap(exp_complex, sizeof code);

    return 0;
}

```
> 6 votes

# Answer
## ES6, ~~63~~ ~~56~~ 55 bytes - 15 = 40

```
(a,b)=>(m=Math,e=m.exp(a),e*m.cos(b)+`+${e*m.sin(b)}i`)

```

---

This is a function that accepts a number in the form `a + bi` with `a` and `b` as the function arguments.

It uses Euler's formula `e^ix=cosx+isinx`.
> 3 votes

# Answer
## TI-BASIC (NSpire) 13 (28 bytes-15)

```
f(r,j):=^r*(sin(j)i+cos(j

```

The  is `e`. This computes `e^z` for `z=r+i*j`. `i` is an undefined variable. This defines a function f which accepts two parameters: the real part and the imaginary part.
> 3 votes

# Answer
# Haskell 30 raw, 15 with bonus:

```
e a b=map(*exp a)[cos b,sin b]

```

load it up into the GHCi, then try out the function:

```
Ok, modules loaded: Main.
*Main> e 3 0
[20.085536923187668,0.0]
*Main> e 0 (-2)
[-0.4161468365471424,-0.9092974268256817]

```

Also, humans can understand why this works :)

I hope the GHCi is a code golf legal way of bringing Haskell in. Also note that a human must infer that the second field is the complex one. \[edit1\]
> 2 votes

# Answer
# CJam, 33 bytes

```
l_"i"&{);d_mc\ms_0<!'+*\'i}{dme}?

```

Test it here.

This supports only purely real or purely imaginary input.
> 1 votes

# Answer
# BBC BASIC - 44 bytes (with tokenisation) - 15 = 29

Put this after the END statement. Arguments are the same as

```
a+bi = (a,b)

```

### Code

```
DEFFNf(a,b)e=EXPa:=STR$(e*COSb)+"+"+STR$(e*SINb)+"i"

```

### Usage

```
imaginary$ = FNf(1,1)
PRINT imaginary$
END
DEFFNf(a,b)e=EXPa:=STR$(e*COSb)+"+"+STR$(e*SINb)+"i"

```

Where the output is:

```
1.46869394+2.28735529i

```
> 1 votes

# Answer
# APL (Dyalog Extended), ~~20~~ 16 - 15 = 1 byte (SBCS)

```
'+i',⍨¨*⍤⊣×2 1○⊢

```

`'+i',⍨¨` append "+" and "i" to the ends of
`*`*e* to the power of
the left argument (the real part)
`×` times
`2 1○` the cosine and sine of
the right argument (the imaginary part)

TryAPL online!
> 1 votes

# Answer
# Python, (94 - 15) = 79 bytes

```
from math import *
import cmath
n=input()
print `e**(n[0])*(cos(n[1])+1j*sin(n[1]))`[1:-2]+'i'

```

Pretty straightforward implementation. Since python uses "j" instead of "i" for imaginary numbers, replacing the characters in the final string eats up quite a few (12) bytes. This can definitely still be golfed.

Takes input in the form of `[a,b]` for a + bi.
> 1 votes

# Answer
# C (gcc), ~~51~~ 47 bytes - 15 = 32

```
#define f(x)(cos((x)*1i)-1i*sin(1i*(x)))*exp(x)

```

Try it online!
> 0 votes

---
Tags: code-golf, math, arithmetic, complex-numbers
---


# Question
Title: Shortest way to generate 12 repeated characters in JavaScript
```
'---------'
'-'.repeat(9) // longer!

'------------'
(x='----')+x+x
'-'.repeat(12) // same length

```

Is there any cleverer way of generating strings of 12 repeated characters in JavaScript?

# Answer
Unfortunately, after what seems an eternity of searching documentation, I can't seem find any solution that will work with the 12-character constraint and generate for any given character given. However, there are a few neat tricks one can do to save some bytes for specific cases:

* `1e*L*-1+''` will give a string, filled with `9`s, of *L* length.
* `''.padEnd(*L*)` will give a string, filled with spaces, of *L* length. It's only useful when *L* \> 10, otherwise it's too long. This one can be immediately chained with a function.
* `*N*/9+''` will give a string, starting with `0.` then followed by a bunch of `*N*`s. This does not work when *N* \< 1 or *N* \> 8, and the result obviously does not contain the same characters the whole way, but pretty close and pretty short.
* `Array(*L*)+''` will give a string, filled with commas, of length *L* \- 1.
> 3 votes

---
Tags: tips, javascript
---


title: Which switches are on?

text:
# Question
Title: Which switches are on?
# Introduction

You are sitting with your coworker, having lunch, and bragging to him/her about the latest and supposedly greatest project you've been working on. Getting sick and tired of your constant showcase of egoism, he/she gives you a challenge just so you'll shut up. Being the egoistic and happy-go-lucky person you are, you of course accept (because you *must* accept each and every challenge). The **challenge**, as he/she explains it is, given an **input** of a block of text containing 1 or more of each character in `!@#$^&*`, **output** in any reasonable format the coordinates of the switch(es) that is/are "on".

According to your coworker, a switch is a `$`, and a switch is classified as "on" if and only if it satisfies at least 1 of the following criteria:

1. It is surrounded by all `^`. So...

```
^^^
^$^
^^^

```

results in an "on" switch.
2. It is surrounded by all `&`. So...

```
&&&
&$&
&&&

```

results in an "on" switch.
3. It is completely covered on at *least* two sides with `*`. For instance,

```
***
&$&
***

```

results in an "on" switch, but

```
&*&
&$&
&*&

```

does not, since the switch is not *completely covered* on any two sides by `*`s.
4. There is at least 1 `!` and/or 1 `@` in any of the corners around it. This does *not* count if either of these are *not* in a corner. So...

```
!&&
^$@
@&!

```

results in an "on" switch, since there is at least 1 `!` and/or `@` in at least 1 of the corners (in the above case, there are 2 valid `!`s and 1 valid `@` in 3 corners). And...

```
&!&
^$@
^!&

```

does *not*, although there are 2 `!`s and 1 `@`, since none of them are in *any* of the corners.
5. 1 or more `#` are *not* on *any* sides around the switch, unless at least 1 `&` surrounds the switch. In other words, if there is at least 1 `#` present on a side, it overrides all other rules, unless there is also a `&` present. Therefore:

```
#&*
*$*
!**

```

results in an "on" switch, although a `#` exists, since there is an `&` around the switch, and it follows at least 1 of the above rules. However, if the exclamation point were not present like so:

```
#&*
*$*
***

```

The switch would be off, since it does not follow at least one of the above rules. Therefore, even though a switch may be surrounded by a `#` and a `&`, it would still be off unless it follows one or more of these rules. Also, there must *always* be a \>=1:1 ratio between `&`s and `#`s for the switch to be valid. For instance,

```
#&!
*$*
**#

```

would still be an invalid switch, although it follows 1 of these rules, since there are 2 `#`s, but only 1 `&`, and therefore not a \>=1:1 ratio between `&`s and `#`s. To make this valid, you must add 1 or more additional `&`s to any edge in order balance the number of `#`s and `&`s out, possibly like so:

```
#&!
*$&
&*#

3:2 ratio between &s and #s

```

Finally...

```
#^^
^$*
@^!

```

results in an "off" switch, although it follows 1 or more of the above rules, since it contains *at least* 1 `#` around it, and no `&`s to outbalance it.
6. The valid switches will *only* be *inside* an input, and therefore, each valid `$` must be surrounded *completely* by any 8 of the valid characters. For instance, if the entire input were to be:

```
*$*
!$!
!!!

```

the top `$` is definitely *not* a valid switch since the switch is on an edge, and therefore the switch is not completely surrounded by 8 valid characters. In this instance, the switch should not even be considered. However, the switch in the middle is completely valid, and as a matter of fact is "on", since it meets at least one of the above requirements.

To demonstrate, consider this block of characters:

```
!@#^^$#!@
!@#$$*$&@
@$^!$!@&&

```

which we can label for coordinates like so, calling the vertical axis `y` and the horizontal axis `x`:

```
y

3 !@#^^$#!@
2 !@#$$*$&@
1 @$^!$!@&&

  123456789 x

```

The coordinates must *always* be returned in an `(x,y)` format, similar to a two-dimensional coordinate grid. Now, which switches are on? Well, let's first find them all. We can already see that there is 1 in the very top row, and another in the very bottom. However, those are automatically no-ops, since they are not completely surrounded by 8 characters.

Next comes the one in row 2. Specifically, this one:

```
#^^
#$$
^!$

```

We can see that there are 3 `$` signs in this, but we just want to focus on the one in the middle, and, as you can probably see, it is already invalid, since it has 2 `#`s around it with no `&`s to balance them out. Additionally, this does not even follow any of the rules, so even if it was a valid switch, it would be "off" anyways.

Next comes another one in row 2:

```
^^$
$$*
!$!

```

Again, only focus on the switch in the middle. This switch is "on", since it has *at least* 1 `!` in *at least* 1 corner. The coordinates of this one are `(5,2)`.

Moving on, we finally move onto the last switch. This one is also in the second row and appears like so:

```
$#!
*$&
!@&

```

and, as you can probably see, this one is also a valid switch, although there is a `#` surrounding it, since there are 2 other `&`s to outbalance the `#`. In addition to that, it also has at least 1 `!` in at least 1 of the corners, and therefore not only is the switch valid, but it's also "on". The coordinates of this switch are `(7,2)`.

We have finally reached the end, and have found 2 "on" switches in that entire block on text. Their coordinates are `(5,2)` and `(7,2)`, which is our final answer, and what the output should be. However, this input was very simple. Inputs can get *a lot* bigger, as there is not limit on how big the block of text can get. For instance, the input could even be a randomized `200x200` block of text.

# Contraints

* Standard Loopholes are prohibited.
* There can't *possibly* be a built-in for this, but just in case there is (looking at you Mathematica), the use of built-ins that directly solve this are prohibited.

# Test Cases:

Given in the format `string input -> [array output]`:

```
@#$$&^!&!#
@*&!!^$&^@
$!#*$@#@$!   ->  [[7,3],[9,2]]
*@^#*$@&*#

#^&!$!&$@@#&^^&*&*&&
!^#*#@&^#^*$&!$!*^$$
#^#*#$@$@*&^*#^!^@&* -> [[19,3],[15,3],[8,2]]
#$@$!#@$$^!#!@^@^^*#

@!@!^&*@*@
*$*^$!*&#$
@$^*@!&&&#
**$#@$@@#!  -> [[2,8],[5,8],[6,6],[9,3]]
##*&*#!^&^
$&^!#$&^&@
^^!#*#@#$*
$@@&#@^!!&
#@&#!$$^@$

!!@##!$^#!&!@$##$*$#
$^*^^&^!$&^!^^@^&!#!
@*#&@#&*$!&^&*!@*&** -> [[9,4],[9,3]]
^!!#&#&&&#*^#!^!^@!$
&$$^*$^$!#*&$&$#^^&$

```

More coming soon

# Additional Notes

* You can assume that the input will always be in the form of a complete block (i.e. a rectangle or square)
* There will *never* be any other character in the input than those in `!@#$^&*`.

Remember, this is a so the shortest code wins!

# Answer
## JavaScript (ES6), ~~363~~ ~~339~~ ~~312~~ ~~309~~ 298 bytes

This is a function taking the input as a string and returning a list of coordinates. It's split into 2 main parts: a transformation of switches into a pair of coordinates and its surrounding characters, and a 'is it on' check based on the rules of the challenge on the surrounding characters.

```
a=>[...a].map((z,p,m)=>(y-=z==B,z)=='$'&&(r=m[p-n-2]+m[p-n]+m[p+n]+m[p+n+2]+m[p-n-1]+m[p-1]+m[p+1]+m[p+n+1],r=r[L]<9?r:'')[T]`&`[L]>=r[T]`#`[L]&&(/(\^|&){8}|\*{4}(.\*\*.|\*..\*)/.exec(r)||/!|@/.exec(r.substr(0,4)))&&[1+(p-(w-y))%n,y],y=w=a[T='split'](B='\n')[L='length'],n=a.search(B)).filter(e=>e)

```
> 2 votes

# Answer
# Haskell, 304 bytes

```
import Data.List
s!c=sum[1|a<-s,a==c]
f t|Just w<-elemIndex '\n't,h<-t!'\n'=[c|c<-mapM(\a->[2..a-1])[w,h],s<-[(\[x,y]->t!!((h-y-1)*(w+1)+x))<$>mapM(\a->[a-2..a])c],s!!4=='$',foldr1(-)((s!)<$>"#&")<1,or$("@!"/="@!"\\map(s!!)[0,2..8]):zipWith(\c i->all(==c)$(s!!)<$>[0..8]\\(4:i))"^&**"[[],[],[1,7],[3,5]]]

```

This defines the function `f` which performs the given task.
> 2 votes

# Answer
# Python 2, ~~299~~ ~~297~~ ~~279~~ ~~275~~ ~~261~~ 259 bytes

```
m=input()
R=range
h=len(m)
for y in R(h-2):
 for x in R(len(m[0])-2):
	a=''.join(m[y+o][x:x+3]for o in R(3))
	if(a.count('&')>=a.count('#'))*(a[:4]+a[5:]in('^'*8,'&'*8)or'*'*6in(a[:3]+a[6:],a[::3]+a[2::3])or'!'in a[::2]or'@'in a[::2])*a[4]=='$':print x+2,h+~y

```

Try it online!

Takes input as a list of strings

Prints the output as a pair of x,y coordinates on each line
> 2 votes

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


title: Guess how to pronounce German words

text:
# Question
Title: Guess how to pronounce German words
# Introduction

Unlike English, German is considered to have quite a phonemic writing system. That means that the correspondence between spelling and pronunciation is close. Given any word you aren't familiar with, you would still know how to pronounce it because of the spelling system. This means a computer should be able to do it too right?

# Challenge

Write a program or function that takes as input a string representing a German word, and prints or returns its pronunciation in the International Phonetic Alphabet (IPA).

I am of course **not going to make you learn German or the full IPA**. This one Wikipedia section provides almost all the German to IPA rules you need, and I've coded an ungolfed C# reference implementation.

Also provided in that link is a list of 400 common German words and their IPA pronunciation (needed for validation). Taking an example from that list, if the input is `solltest`, the correct output is `ˈzɔltəst`.

The reference implementation adds two helpful rules not mentioned in the Wikipedia section: It assumes word stress is on first syllable (very likely in German), and uses a better heuristic for determining when the letter "e" represents the schwa sound /ə/. It also implements special processing for prefixes, but that didn't improve results as much as I thought it would.

# Details

To be considered a valid entry, your program must meet the following requirements:

* Your IPA output must be an exact match for at least 300 of the 400 words in the reference word list (the reference implementation gets 333 correct)
* Your program must make a guess for any plausibly German word. So we have a technical requirement, this will mean that for any input that matches the regex `[a-zA-ZäÄöÖüÜ][a-zäöüß]*` and has at least one vowel (aeiouyäöü), you must produce non-whitespace-only output and not error out.
* The program must be deterministic (always produce the same output given the same input)
* Otherwise, standard loopholes are forbidden (especially the one about fetching off-site resources)

Miscellaneous things you are allowed to do:

* Have leading and trailing whitespace in your output if you must
* Use any pre-existing character encoding in the output (I can't imagine anything other than Unicode working well, but if you can, congrats)
* Assume the input is in some normalized form like Unicode normalization forms NFD, NFC, etc. For example, is ä written as a single character or a base character + a combining character?
* Use standard input and output methods

# Scoring & IPA Characters

Scoring is in bytes. Be warned that the German characters and the IPA characters are 2 bytes in UTF-8. Also, the IPA character U+0327 COMBINING INVERTED BREVE BELOW ( ̯) is a Unicode combining character and is a 2 byte UTF-8 character on its own. That means something like ɐ̯ would count as 4 bytes in UTF-8. For the curious, this symbol means the vowel does not form the syllable nucleus (the previous one does instead).

Also, beware of these IPA characters that in some fonts look like other ASCII characters: ɡ, ɪ, ʏ, ː (marks a long vowel), ˈ (marks which syllable has the stress in a multisyllable word).

# How the reference word list was created

*This section is extra info not needed for the challenge.*

The word list was grabbed from this Wiktionary word frequency list, removing repeats because of casing difference and two words that didn't have German entries in the English Wiktionary (oh & hey). The IPA was from looking at both the English and German Wiktionaries. Where multiple pronunciations were offered, I chose the more formal and standard one. If this wasn't clear, I chose the one that most fit the general rules.

I also had to standardize how the letter "r" is pronounced. It is heavily dependent on the region how this letter pronounced, and Wiktionary was not at all consistent in which one it chose. I felt it tended towards the following: "r" is pronounced /ɐ̯/ when followed by a long vowel and a vowel does not follow, otherwise, it is ʁ. So, I changed all of them to follow that rule, except for the ver- and er- prefixes that were quite consistently /(f)ɛɐ̯/. Similarly, I standardized "eu" as /ɔʏ̯/.

# Answer
# PHP, 3311 2988 2916 2845 2759 2671 2667 2509 2484 bytes, passing 301/400

> `<?$f=fopen(__FILE__,r);fseek($f,__COMPILER_HALT_OFFSET__);eval(strtr(stream_get_contents($f),[F=>'=>',M=>'==','&'=>'&&',H=>'function ',A_=>'array',G=>'if',4=>'for','|'=>'||','~'=>'))','%'=>str,7=>'=$',8=>'[]',9=>'!$','@'=>'count(','#'=>';$',5=>'return ',3=>':(']));__halt_compiler();define(J,[ieh,ah,aa,Ah,eh,ee,ie,ih,oh,oo,Oh,uh,Uh,au,eu,Au,ei,ai,ey,ay,a,e,i,o,u,A,O,U,y])#b7e=8;Hv($a){5in_A_($a,J);}Hn($a){5!v($a);}Hpronounce($w){global$b,$e#w=%tr(%tolower(%tr($w,[ßF1,ÄF2,äF2,ÖF0,öF0,ÜF6,üF6]~,[1FS,2FA,0FO,6FU])#W=8#L7w;while($L)4each(A__merge([tzsch,dsch,tsch,zsch,sch,chs,ch,ck,dt,ng,nk,pf,ph,qu,ss,th,tz,b,c,d,f,g,h,j,k,l,m,n,p,r,s,S,t,v,w,x,z],J)as$c){$l=%len($c);G(sub%($L,0,$l)M$c){$W87c#L=sub%($L,$l);break;}}$s=8#l=@$W);4($o7t7i=0#i<$l#i++){$c7W[$i]#p7i?$W[$i-1]:0#n7iM$l-1?0:$W[$i+1];G(9n|!(n($c)&$cM$n&n($W[$i+2]~)$s[$o]87c;G($p&((9n&v($c)&n($p~|(n($n)&v($W[$i+2]~~$s[++$o]=8;}$s[@$s)-1]|A__pop($s);4each($s as$z){$b87t#t+=@$z)#e87t;}$o=[sieFziQ,duFduQ,'die'FdiQ,derFdeQT,zuFtsuQ,wirFviQT,mirFmiQT,denFdeQn,dassFdas,erFeQT,soFzoQ,warFvaQT,fürFfyQT,jaFjaQ,wieFviQ,dirFdiQT,nurFnuQT,demFdeQm,ihnFiQn,auchFaUBx,ihrFiQT,daFdaQ,schonFʃoQn,wennFvEn,malFmaQl,gutFguQt,nachFnaQx,willFvIl,mussFmUs,habFhaQp,vorFfoQT,ihmFmiQm,tunFtuQn][$w]?:'';G($o)goto x#P7B7S7V7Z=0;@$s)>1&$o=[verFfET,daFda,geFgC][join($s[0])]#o&$P=1&A__shGt($s);(($P|@$s)M2)&$o.=W)|(@$s)>2&$d=1&$h=(int)@$s)/2)#w=A__merge(...$s);4each($w as$l){G(0<$S--)continue#n7w[$B+1]#p7w[$B-1]#f=''#Z+=in_A_($B,$b)#f7lMd&9n?t3$lMb&(9n|$nMt)?p3$lMg&(9n|$nMt)?((9n&$pMi)?K:k)3$lMc?(($nMA|$nMe|$nMi)?ts:k)3$lMch?(($pMa|$pMo|$pMu)?x:K)3$lMchs|$lMx?ks3$lMck?k3$lMdsch?dZ3$lMdt|$lMth?t3$lMph|$lMv?f39f&$lMg?g3$lMh?(v($n)?h:'')3$lMng?N3$lMnk?Nk3$lMqu?kv3$lMr?((!v($n)&9nMt)?T:R)3$lMsch?S3$lMss|$lMS?s3$lMtsch|$lMtzsch|$lMzsch?tS3$lMtz|$lMz?ts3$lMw?v3$lMs?(9p&($nMp|$nMt~?S3v($n)?z:s):$f~~~~~~~~~~)#U=0;G(v($l~{G(%len($l)>1)($f=[auFaUB,euFcYB,eiFaIB][$l])|$U=1;else{G(n($n)&((9w[$B+2]&$n!=n)|v($w[$B+2]~)$U=1;G($lMe){$U=9n?:$U;G(9w[$B+2]){G($nMr)($f=A)&$U=9S=1;G($nMm|$nMl)$f=C;}}elseG($nMch)$U=0;G(in_A_($B,$e~$U=0;}$f=($U|9Z)&9f?($l[0]MO?D3$l[0]MU?y3$l[0]MA?E:$l[0]~).Q39f?($lMe?((9n|(9w[$B+2]&($nMn|$nMs~)?C:E)3$lMA?E3$lMi?I3$lMo?c3$lMu?U3($lMU|$lMy)?Y:$l~~~:$f)#V++;}$f7f?:$l;G($d&$ZM$h)$f.=W#o.7f#B++;}G(%pos($o,W)M=false&$V>1)$o=W.$o;4(#j++<%len($o);)G($o[$j]M$o[$j+1])$o=sub%($o,0,$j).sub%($o,$j+1);x:5%tr($o,[SFʃ,ZFʒ,KFç,gFɡ,NFŋ,QF'ː',WFˈ,TFɐ̯,BF'̯',RFʁ,AFɐ,EFɛ,OFœ,IFɪ,YFʏ,UFʊ,cFɔ,CFə,DFø]);}`

Defines `pronounce(string $word)`.

Usage:

```
assert(
    pronounce('darüber') == "daˈʁyːbɐ"
);

```

One note: 3 prefixes and 33 words are hard-coded, and some of the code is mildly optimized towards the testing list.

Testing code is here, though it does depend on this file.

To test:

```
php test.php all

```

Powered by the tears of ternary statements.

**EDIT 7**: Squeezed off ~170 bytes by writing a preprocessor into the program. As a consequence, the actual program (everything after `__halt_compiler();`) is kinda hard to read. If you want the unprocessed program, switch `eval` with `print` in the third statement.
> 10 votes

---
Tags: code-golf, string, parsing, natural-language
---


title: Decode Baby-talk!

text:
# Question
Title: Decode Baby-talk!
When babies open their mouths, they're not just spewing gibberish. They're actually talking in a highly advanced, adult-proof cipher...

# The Baby-talk Cipher

When a baby talks, it could look something like `gogooa gagooook aagaaoooy` Each single-space separated section represents a character (so the example above represents 3 characters).

To decipher a section, we must count number of As and Os it contains. However, we only count those which are adjacent to another vowel. For example, the A in 'gag' would not count, but both the A and O in 'gaog' would.

Counting the example above would look like this:

```
Section    | Num Os | Num As

gogooa     | 2      | 1
gagooook   | 4      | 0
aagaaoooy  | 3      | 4

```

We then use these values to convert the input into plaintext on a Polybius square. This is a 5x5 representation of the English alphabet, omitting 'J' (please note that, in baby-talk, 0-counting rules apply to the table):

```
  0 1 2 3 4
0 A B C D E
1 F G H I K
2 L M N O P
3 Q R S T U
4 V W X Y Z

```

Using the number of Os as the column, and number of As as the row, we find which character each section represents:

```
Section    | Num Os | Num As | Character

gogooa     | 2      | 1      | (2,1) -> H
gagooook   | 4      | 0      | (4,0) -> E
aagaaoooy  | 3      | 4      | (3,4) -> Y

```

Which tells us that the baby was just saying "HEY".

**Notes**:
\- If a section representing a character has more than 4 As or Os, ignore the extras, because 4 is the maximum value on the table. \- For this task, Y is not a vowel - only A, E, I, O and U.

# The Challenge

Your task is to create a *full* program which takes one input, a word in baby-speak, and prints it in plaintext.

* Your program must be able to take input in uppercase, lowercase, and a mix of both.
* The input will only contain ASCII alphabet letters (A-Z and a-z), with single spaces to seperate the baby words.
* The output text can be in any case.
* You should the take the input from `STDIN` and print the plaintext on `STDOUT`. If your language does not have these, use the nearest equivalent.
* This is , so the shortest code in bytes wins - but any solution is welcome.

# Test Cases

```
'GLOOG KAKAAOOO ARGOOO OOOOOGUGUU' -> CODE
'oaka pooopaa gaau augu' -> GOLF
'Aoao U oOOAoa oaoAoo aoAoAOa' -> NAPPY
'GUG gAGaA gOougOou' -> ALE
'OOaGOG GoGOOoGoU gAA bLAA GOUGoOUgAIGAI' -> HELLO

```

# Answer
# 05AB1E, 46 bytes

```
lð¡vyžNvyð:}ð¡D€g1›ÏJ©'a¢4‚W5*®'o¢4‚Ws\+A'j-è?

```

Try it online!

**Explanation in steps**

1. split on spaces to form words
2. replace konsonants in words with spaces
3. split words on spaces to form groups of vowels
4. remove vowel groups with a length shorter than 2
5. get min of count(a) and 4, multiply by 5
6. get min of count(o) and 4
7. add counts
8. get letter at that index of alphabet (excluding "j")
> 6 votes

# Answer
# Perl, 82 bytes

Includes +1 for `-a`

Give input on STDIN:

```
perl -M5.010 baby.pl <<< "OOaGOG GoGOOoGoU gAA bLAA GOUGoOUgAIGAI"

```

`baby.pl`:

```
#!/usr/bin/perl -a
say map{$A=$O=$_=uc;y/AEIOU/@/c;s/(\B.|.\B)/$$1+=$$1<4/eg;(A..I,K..Z)[5*$A+$O]}@F

```

This assumes a recent enough perl version where `-a` implies `-n`. If your perl is too old you will need to add an explicit `-n` option.

It also assumes babies can't say general ASCII strings that start with digits like `1 this will not work`
> 9 votes

# Answer
# JavaScript (ES6), 145 bytes

```
alert(prompt().replace(/\S+ ?/g,x=>(g=r=>(q=(x.match(/[aeiou]{2,}/gi)+"").split(r).length-1)>4?4:q,(g(/a/i)*5+g(/o/i)+10)*20/19|0).toString(36)))

```

Replaces each word (and the following space) with its corresponding letter.

`s.split` `.map().join``` is 3 bytes longer:

```
alert(prompt().split` `.map(x=>(g=r=>(q=(x.match(/[aeiou]{2,}/gi)+"").split(r).length-1)>4?4:q,(g(/a/i)*5+g(/o/i)+10)*20/19|0).toString(36)).join``)

```
> 6 votes

# Answer
# brainfuck, 656 bytes

```
+[[>>>,[>++++[<-------->-]]<]<<[>]<-[+[<+>>+<-]----[>>+<<----]>>+[<[-<]<[>]>>-]-<[[-]>+<]>[[-[->]<<+>]<->>>]<<<[>>>+<<<-]<<-]>>>>>[[<+>>+<-]----[>-<----]>--[----<]<[>]>[----<]<[>]>[------<]<[>]>[------<]<[>]><+>[[-]<->]>>]<<<[>->]<[<]>[>[<<<<<+>>>>>>+<-]<<<<]<[-]>>>>[<[>[>+<-]<-]>[-]->[<+>-]>>]<<<[-<----[>-<----]>[>+>+<<-]+>[<->[-]<]<[<]>[[<<<]<+>>>>[>>>]<<<-]>+>--------------[<->[-]]<[-<<<<[<<<]>+>>[>>>]>]<<<<]<[<+<+>>-]>++++[<<[->]>[<]>-]+<<[[-]++++<[-]>>]>[<]<<[>+<-]>>+>->[>+>+<<-]<++++[>>[-<]<[>]<-]>>[[-]++++>[-]]<<<[>]<->>>>[<+>-]<[<<<+>>>-]<<<<[>+++++<-]>[>+>+<<-]<++++++++[>>[-<]<[>]<-]>>[[-]>+<]----[>+<----]>++.[-]+>>>,[<++++[>--------<-]]>]

```

This was a pretty good way to kill a couple of hours.

Requires a brainfuck interpreter that uses 8-bit wrapping cells, allows you to go left from cell 0 and returns 0 if `,` is used when stdin is empty. In my experience, these are the most common settings.

This program does not consider Y a vowel, but if OP wants it to it's an easy fix.

It seems like writing this would be a daunting task but if you have some familiarity with the language there's nothing surprising or new in the code. Standard brainfuck tactics: Read the input but make sure you leave a couple of empty cells between each byte, use those empty cells to store data about the input, use the data you stored to decide how to transform it and spit something out at the end. In this case it was get the input, set it all to uppercase, figure out which cells are vowels, throw that information away after using it to determine which cells are *next to* vowels, set everything that isn't next to a vowel to some value that will never be relevant so they're not in the way later, and you're basically done. From there you just have to count your `A`s and `O`s, multiply `A`s by 5 and add the number of `O`s, special case anything above 8 to avoid J and output. I did choose to handle this one word at a time, rather than taking the whole input at once, so I had to set up the part of the code that reads stdin to break at 0 or 32, but that's not too big of a problem (just wrap the subtraction by 32 in a conditional so it doesn't happen if the value is already 0, then correct for any `<` or `>` instructions you missed later).

I don't know how helpful it will be because I wrote it mostly to keep my thoughts straight rather than as a real explanation, but here's the code with my comments and its original indentation:

```
+[[>>>,[>++++[<-------->-]]<]get an entire word of input
                            each character lowered by 32
                            two empty cells between characters
                            stops when reaching a space or null byte

any lowercase letters have become uppercase; anything with a value below 65 used
to be an uppercase character; fix it

<<[>]<-[+                for each character until hitting 1:
  [<+>>+<-]              make a backup
  subtract 64 from the character but stop if it hits 0
  ----[>>+<<----]>>+     generate the number 64
  [                      64 times:
    <[                     if the character is not 0:
      -                    subtract 1
      <                    go to a guaranteed 0 cell to break the loop
    ]

    we're either on the character or to the left of it; sync up
    <[>]

  >>-]
  -<[[-]>+<]>            logical NOT of character

  [                      if logical NOT returns true:
    [-[->]<<+>]<-          add 32 to backup of character
  >>>]

  <<<[>>>+<<<-]          move copy over to make room
<<-]
  >>>>>[                 for each character:
  [<+>>+<-]              make copies
  ----[>-<----]>--       check if it's A
  [----<]<[>]>           check if it's E
  [----<]<[>]>           check if it's I
  [------<]<[>]>         check if it's O
  [------<]<[>]>         check if it's U

  IF YOU NEED TO ADD Y; THIS IS THE PLACE

  <+>[[-]<->]            logical NOT to complete vowel check
>>]

<<<[                if the last char is a vowel; prevent a side effect
  >->
]

<[<]>[                 for each character:
  >[                     if it's a vowel:
    <<<<<+>>>>>>+<-          leave a flag to the left and right to show that a
  ]                          vowel is adjacent
<<<<]

<[-]>                  clean up a side effect left behind if first char is vowel

>>>[                   for each char:
  <[                     if it's adjacent to a vowel:
    >[>+<-]<-              move it to the side
  ]
  >[-]-                otherwise; destroy it
  >[<+>-]              move backup over if it exists (subtracting 1)
>>]

all characters without a vowel beside them have been set to 255
all characters with a vowel beside them are set to itself minus 1

notable charaters are: 'A' minus 1 = 64
                       'O' minus 1 = 78

<<<[                 for each character:
  -<----[>-<----]      subtract 64
  >[>+>+<<-]           make a copy
  +>[<->[-]<]<[<]>     logical NOT

  [[<<<]<+>>>>[>>>]<<<-] if NOT returns true; record an A

  >+>--------------  subtract 14 from backup

  [<->[-]]<          logical NOT
  [-<<<<[<<<]>+>>[>>>]>] if NOT returns true; record an O
<<<<]

<[<+<+>>-]           make a backup of A count
>++++[<<[->]>[<]>-]  subtract 4 but don't go below 0
+<<[                   if the char was greater than 3:
  [-]++++<[-]>>          put 4 there
]
>[<]                  resynchronise
<<[>+<-]              if there were fewer than 4 As put the number back

same thing but for the O count

>>+>->[>+>+<<-]       make a backup of O count
<++++[>>[-<]<[>]<-]   subtract 4 but don't go below 0
>>[                     if the char was greater than 3:
  [-]++++>[-]             put 4 there
]
<<<[>]                resynchronise
<->>>>[<+>-]          if there were fewer than 4 Os put the number back

<[<<<+>>>-]<<<<[>+++++<-] A*5 plus B = index of character to output

>[>+>+<<-]            make a backup
<++++++++[>>[-<]<[>]<-] subtract 8 but don't go below 0
>>[[-]>+<]            if the result is nonzero it is late enough in the alphabet
                      that it must be increased by 1 to exclude J as a possible
                      output
----[>+<----]>++      add 65 to make it a letter
.[-]+>>>,             output and get new input
[<++++[>--------<-]]> sub 32 if not 0
]

```
> 6 votes

# Answer
# Perl, 159 +1 = 160 bytes

+1 byte for -n flag. Whitespace is not part of the code and is only provided for readability.

```
for(split$",lc){
    $b=0;
    @a=sort/([ao](?=[aeiou])|(?<=[aeiou])[ao])/g;
    $b++until$b>$#a||$a[$b]eq o;
    $c=($d=$#a-$b+1)>4?4:$d;
    $b=$b>4?4:$b;
    print+(a..i,k..z)[5*$b+$c];
}

```

The code splits the input by spaces and converts each baby word to lowercase before proceeding. The regex finds all a or o vowels that are followed by another vowel, or are preceeded by a vowel, and sorts them, a's at the start, o's at the end, then finds the index of the first 'o'. If the remaining number of matches (aka, the number of 'a's) is greater than 4, then we care about 4 a's, and if there are more than 4 o's, we care about 4 o's. Then it pulls the appropriate letter out of the matrix and prints it, then moves onto the next baby word.
> 5 votes

# Answer
## Brainfuck, 283 bytes

```
,[[<[>-[>>>-<<<----[----[>+<------[>-<------[<[-]>>>>[-]->>[-]<<<<<-]]]]]>[>>>>+
<<<<-]>>+<[>[>+<-]>>[>+<-]<<<-]<,<<[>>>+<<<-]>]>+[<+>[-<<]>[[-]+++++[<++++++>-]<
+<]>>>]<]>>[-]>+>>+[[-]>[<+>-[<+>-[<+>-[<+>[-]]]]]<<<]>->[>+<-[[>+<-]>>+>]>[+>--
--[->]]]+[-<+]>>+++++++++++++[>+++++<-]>.,]

```

Formatted:

```
,
[
  [
    <
    [
      >-
      [
        not a
        >>>-<<<
        ----
        [
          not e
          ----
          [
            not i
            >+<
            ------
            [
              not o
              >-<
              ------
              [
                consonant
                <[-]>
                >>>[-]->>[-]<<<<<-
              ]
            ]
          ]
        ]
      ]
      >[>>>>+<<<<-]> >+<
      [
        prev was vowel
        >[>+<-]>>[>+<-]<<<-
      ]
      <,<<[>>>+<<<-]
      >
    ]
    >+
    [
      <+>[-<<]
      >[[-]+++++[<++++++>-]<+<]
      >>>
    ]
    <
  ]
  >>[-]>+>>+
  [
    [-]
    >[<+>-[<+>-[<+>-[<+>[-]]]]]<
    <<
  ]
  >->
  [
    >+<-
    [
      [>+<-]
      >>+>
    ]
    >
    [
      +>----[->]
    ]
  ]
  +[-<+]
  >>+++++++++++++[>+++++<-]
  >.,
]

```

This works with or without a trailing newline in the input.

Try it online.

Each character is processed mod 32 (with control flow such that the code implementing the mod operation only occurs once in the program). This enables case insensitivity, as well as collapsing the space character and EOF into a single case. A trailing newline is treated the same as `J`, which doesn't affect the output.

Sketch of memory layout:

`0 x C c y a A b B`

where `c` is the input character, `C` is the char mod 32, `x` is whether it is a vowel, `y` is whether the previous char was a vowel, `A` and `B` are the counts of valid (next to vowels) `a` and `o` chars respectively, and `a` and `b` are their respective buffers that get copied or cleared depending on whether there is an adjacent vowel.

When a space or EOF is reached, some juggling is done to reduce counts greater than 4 and to skip the letter `J`, and then the decoded character is printed.
> 4 votes

# Answer
# PHP, 163 bytes

```
<?php for(;$c=preg_replace('/(?<![AEIOU]).(?![AEIOU])/','',strtoupper($argv[++$i]));$j=min($d[79],4)+5*min($d[65],4),print range(A,Z)[$j+($j>8)])$d=count_chars($c);

```

More readable version:

```
<?php
for (
    ;
    $c = preg_replace(
        '/(?<![AEIOU]).(?![AEIOU])/',
        '',
        strtoupper($argv[++$i])
    );
    $j = min($d[79], 4) + 5 * min($d[65], 4),
    print range(A, Z)[$j + ($j > 8)]
)
    $d = count_chars($c);

```

Tests:

```
$ php babytalk.php GLOOG KAKAAOOO ARGOOO OOOOOGUGUU
CODE
$ php babytalk.php oaka pooopaa gaau augu
GOLF
$ php babytalk.php Aoao U oOOAoa oaoAoo aoAoAOa
NAPPY
$ php babytalk.php GUG gAGaA gOougOou
ALE
$ php babytalk.php OOaGOG GoGOOoGoU gAA bLAA GOUGoOUgAIGAI
HELLO

```
> 3 votes

# Answer
# Java 8, ~~272~~ ~~266~~ ~~251~~ 249 bytes

```
interface M{static void main(String[]i){String z="(?=[AEIOU])|(?<=[AEIOU])";for(String s:i[0].split(" ")){int a=s.split("(?i)A"+z+"A",-1).length-1,o=s.split("(?i)O"+z+"O",-1).length-1,t=(a>4?4:a)*5+(o>4?4:o);System.out.printf("%c",t>9?t+66:t+65);}}}

```

-6 bytes thanks to *@Joba*.
-1 byte converting from Java 7 to 8, and ~~14~~ 16 additional bytes saved by changing the print-part.

**Explanation:**

Try it here.

```
interface M{                   // Class:
  static void main(String[]i){ //  Main method:
    String z="(?=[AEIOU])|(?<=[AEIOU])";
                               //   Regex-part for look-ahead or look-behind of vowels
    for(String s:i[0].split(" ")){
                               //    Loop over the program-arguments
      int a=s.split("(?i)A"+z+"A",-1).length-1,
                               //     The amount of A's with adjacent vowels
          o=s.split("(?i)O"+z+"O",-1).length-1,
                               //     The amount of O's with adjacent vowels
          t=(a>4?4:a)          //     If `a` is larger than 4, just take 4, else take `a`
            *5                 //     Multiply it by 5
            +(o>4?4:o);        //     And add 4 if `o` is larger than 4, else take `o`
       System.out.printf("%c", //     Print a character:
        t>9?                   //      If `t` is larger than 9 (index of J)
         t+66                  //       Take character unicode (skipping J)
        :                      //      Else:
         t+65);                //       Take character unicode (prior to J)
    }                          //   End of loop
  }                            //  End of main-method
}                              // End of program

```
> 3 votes

# Answer
# Python 3, ~~163~~ ~~162~~ ~~157~~ 146 bytes

```
import re
for W in input().upper().split():S=''.join(re.findall("[AEIOU]{2,}",W)).count;I=min(S('A'),4)*5+min(S('O'),4);print(end=chr(65+I+(I>9)))

```

Uses regex to find all string of vowels larger than 2, counts As and Os with maximum of 4, and then prints.
> 2 votes

# Answer
## APL, 60

```
{⎕A[a+9<a←5⊥+/¨'ao'∊⍨¨⊂⍵/⍨0(,∨,⍨)2∧/⍵∊'aeiou']}¨' '(≠⊂⊢)819⌶

```

Note that ⎕IO←0 and ⎕ML←3

Example:

```
fn←{⎕A[a+9<a←5⊥+/¨'ao'∊⍨¨⊂⍵/⍨0(,∨,⍨)2∧/⍵∊'aeiou']}¨' '(≠⊂⊢)819⌶
fn 'Aoao U oOOAoa oaoAoo aoAoAOa'
NAPPY

```

Works in Dyalog 15.0, since it's the version in which 819⌶ was introduced to lowercase a string.
> 2 votes

# Answer
# Pyth, 64 bytes

Can probably be golfed further. Try it here !

```
L?<b5b4DebK+ds:rbZ"[aeiou]{2,}"1J+*/K\a5y/K\oR@G?<J9JhJu+GeHcQd"

```
> 1 votes

# Answer
## R, 261 bytes

I think I spent way too much time just to get this working and I believe this is an unnecessarily complicated solution, although it works. Takes input from stdin, it's important that the string is enclosed in quotes.

```
x=el(strsplit(toupper(scan(,""))," "))
cat(apply(sapply(c("A","O"),function(y)sapply(sapply(regmatches(x,gregexpr("[AEIOU]{2,}",x,)),paste,collapse=""),function(s)min(sum(el(strsplit(s,""))%in%y),4)))+1,1,function(z)t(matrix(LETTERS[-10],5))[z[1],z[2]]),sep="")

```

The use of four nested `apply`-family could theoretically be reduced to only two by making use of `mapply` instead. But because inputs to `mapply` will not be of the same length, the shorter one is recycled which complicates things and I couldn't figure out a working solution.

If anyone is interested I'll add an ungolfed explanation later.

Try all the test cases on R-fiddle

Please note that this version takes input as a function argument instead from stdin because `scan` doesn't work on R-fiddle. Furthermore, added a newline to make it easier to read.
> 1 votes

# Answer
## Kotlin, ~~221~~ 209 bytes

Now *much* more ugly and slow, all in the name of **11 bytes**

```
readLine()!!.toLowerCase().split(" ").map{fun
c(c:Char)=Regex("([aeiou]{2,})").findAll(it).fold(0){a,b->a+b.value.count{it==c}}.let{if(it>4)4 else it}
(('A'..'I')+('K'..'Z'))[c('a')*5+c('o')]}.forEach(::print)

```

Save it to a file (ex. `BabyTalk.kts`) to run as a script. Or, the above code can be prepended with `fun main(z:Array<String>)=` and compiled normally for a cost of 26 more bytes.

Try it online!

Indented:

```
readLine()!!
    .toLowerCase()
    .split(" ")
    .map {
        fun c(c: Char) =
            Regex("([aeiou]{2,})")
                .findAll(it)
                .fold(0) {
                    a, b ->
                    a + b.value.count { it == c }
                }
                .let { if (it > 4) 4 else it }
        (('A'..'I') + ('K'..'Z'))[c('a') * 5 + c('o')]
    }
    .forEach(::print)

```
> 0 votes

# Answer
# Python 3, 262 bytes

```
import re;f,b,v,n,r,l,t,g,a,o=re.findall,input().lower(),'aeiou',list(range(26)),'[aeiou]','abcdefghiklmnopqrstuvwxyz','',len,'a','o';del n[9],
for w in b.split():
 O,A=g(f(o+r,w))+g(f(r+o,w)),g(f(a+r,w))+g(f(r+a,w))
 if O>4:O=4
 if A>4:A=4
 t+=l[A*5+O]
print(t)

```

Less Golfed (The comments are the variables in the shortened code):

```
import re
findAll = re.findall #f
babyTalk = input('Baby Talk: ').lower() #b
vowels = 'aeiou' #v
numbers = list(range(26)) #n
del numbers[9]
letters = 'abcdefghiklmnopqrstuvwxyz' #l
finalText = '' #t
length = len #g
regex = '[aeiou]' #r
o = 'o' #o
a = 'a' #a
for word in babyTalk.split(): #w in b
 Os = len(findAll('o[aeiou]', word)) + len(findAll('[aeiou]o', word)) #O
 As = len(findAll('a[aeiou]', word)) + len(findAll('[aeiou]a', word)) #A
 if Os > 4: Os = 4
 if As > 4: As = 4
 print(As, Os)
 finalText += letters[As*5+Os]
 print(finalText)

```

Try it online!
> 0 votes

# Answer
# PHP, ~~124 129 121 120~~ 125 bytes

```
for(;$s=$argv[++$i];print chr((8<$O+=5*$A)+$O+65))for($k=$A=$O=0;$c=_&$s[$k++];$p=$c)$$c+=$$c<4&!trim($p.$s[$k]&__,AEIOU)[1];

```

Takes input from command line arguments. Run with `-nr` or try it online.

**breakdown**

```
for(;$s=$argv[++$i];            # loop $s through arguments
    print chr((8<$O+=5*$A)+$O+65)   # 3. map A and O counts to letter, print
)
    for($k=$A=$O=0;                 # 1. reset A and O counters
        $c=$s[$k++]&_;              # 2. loop $c through characters:
        $p=$c)                          # 2. remember current character as previous
        $$c+=                           # 1. increment counter for $c, if ...
            $$c<4&                          # it is < 4 and ...
            !trim($p.$s[$k]&__,AEIOU)[1];   # ... previous or next char is vowel

```
> 0 votes

# Answer
# , 109 bytes

```
echo{&(u:97+i.26)(+8<[)5#.4<.'AO'+/@e."1 0/~(;@#~1<#@>)@(</.~0+/\@,}.~:&(e.&'AEOUI')}:);._1' ',toupper 1!:1]3

```

Try it online!
> 0 votes

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


title: The prime ant

text:
# Question
Title: The prime ant
The "prime ant" is an obstinate animal that navigates the integers and divides them until there are only primes left!

---

Initially, we have an infinite array A containing all the integers \>= 2 : `[2,3,4,5,6,.. ]`

Let `p` be the position of the ant on the array. Initially, `p = 0` (array is 0-indexed)

Each turn, the ant will move as follows:

* if `A[p]` is prime, the ant moves to the next position : `p ← p+1`
* else, if `A[p]` is a composite number, let `q` be its smaller divisor \> 1. We divide `A[p]` by `q`, and we add `q` to `A[p-1]`. The ant moves to the previous position: `p ← p-1`

Here are the first moves for the ant:

```
 2  3  4  5  6  7  8  9  ...
 ^
 2  3  4  5  6  7  8  9  ...
    ^
 2  3  4  5  6  7  8  9  ...
       ^
 2  5  2  5  6  7  8  9  ...
    ^
 2  5  2  5  6  7  8  9  ...
       ^
 2  5  2  5  6  7  8  9  ...
          ^
 2  5  2  5  6  7  8  9  ...
             ^
 2  5  2  7  3  7  8  9  ...
          ^

```

Your program should output the ant's position after `n` moves. (you can assume `n <= 10000`)

Test cases:

```
0 => 0
10 => 6
47 => 9
4734 => 274
10000 => 512

```

**Edit.** you can also use 1-indexed lists, it's acceptable to display the results 1, 7, 10, 275, 513 for the above test case.

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

# Answer
# Alice, 45 bytes

```
/o
\i@/.&wqh!]k.&[&w;;?c]dt.n$k&;[.?~:![?+!kq

```

Try it online!

Mostly straightforward implementation.

Looping `n` times in Alice is typically done by pushing a return address `n-1` times, then returning at the end of each iteration with `k`. The last time through the loop, the `k` instruction has nowhere to return to, and execution proceeds forward.

This program uses the same `k` instruction to stop early when the number is prime. As a result, the final iteration will always move the ant left. To compensate for this bug, we do `n+1` iterations on a 1-indexed array, which gives exactly the result we want (and gives the case `n=0` for free).
> 10 votes

# Answer
# Octave, ~~109 103 101~~ 94 bytes

```
function i=a(n)i=1;for l=z=2:n+1
if nnz(q=factor(z(i)))>1
z(i--)/=p=q(1);z(i--)+=p;end
i++;end

```

Try it online!

This code will output the position in 1-indexing, so outputs for test cases are:

```
0 => 1
10 => 7
47 => 10
4734 => 275
10000 => 513

```

---

This version uses some Octave optimisations so isn't compatible with MATLAB. The code below is a MATLAB compatible version.

---

# MATLAB, ~~130 123 118~~ 117 bytes

```
function i=a(n)
z=2:n+1;i=1;for l=z
q=factor(z(i));if nnz(q)>1
z(i)=z(i)/q(1);i=i-1;z(i)=z(i)+q(1);else
i=i+1;end
end

```

Uses 1-indexing as with the Octave version. I've tested it against all test cases in MATLAB. As an example the output at 100000 is 3675 (one-indexing).

An commented version of the above code:

```
function i=a(n)
    z=2:n+1;                %Create our field of numbers
    i=1;                    %Start of at index of 1 (MATLAB uses 1-indexing)
    for l=1:n               %For the required number of iterations
        q=factor(z(i));     %Calculate the prime factors of the current element
        if nnz(q)>1         %If there are more than one, then not prime
            z(i)=z(i)/q(1); %So divide current by the minimum
            i=i-1;          %Move back a step
            z(i)=z(i)+q(1); %And add on the minimum to the previous.
        else
            i=i+1;          %Otherwise we move to the next step
        end
    end

```

---

As a matter of interest, this is the ants positions vs number of iterations for the first 10000 values of n.

Seems likely that the Ant will probably tend to infinity, but who knows, looks can be deceiving.

---

* MATLAB: Saved 6 bytes with `for` instead of `while` and removing brackets from `if` \- Thanks @Giuseppe
* MATLAB: Save 2 bytes - Thanks @Sanchises
* Octave: Save 10 bytes by using Octave `\=` and `+=` operations - Thanks @Giuseppe
* Octave: Save 2 bytes with `i++` and `i--` \- Thanks @LuisMendo
* Octave: Save 7 bytes - Thanks @Sanchises
> 7 votes

# Answer
# Python 2, 120 bytes

```
p=0
A=range(2,input()+2)
for _ in A:
 for q in range(2,A[p]):
	if A[p]%q<1:A[p]/=q;p-=1;A[p]+=q;break
 else:p+=1
print p

```

Try it online!

Ah, the rare `for``else` loop! The `else` clause only executes if the `for` body is *not* exited via `break`. In our case, this means we checked all `q`s and found none of them to divide `p`.
> 7 votes

# Answer
# JavaScript (ES6), 91 bytes

```
f=(n,a=[p=0])=>n--?f(n,a,(P=n=>++x<n?n%x?P(n):a[a[p]/=x,--p]+=x:p++)(a[p]=a[p]||p+2,x=1)):p

```

### Demo

*NB: You may have to increase the default stack size of your engine to have it pass all test cases.*

Try it online!
> 6 votes

# Answer
# Haskell, ~~108~~ ~~106~~ 94 bytes

```
([0]#[2..]!!)
(a:b)#(p:q)=length b:([b#(a+d:div p d:q)|d<-[2..p-1],mod p d<1]++[(p:a:b)#q])!!0

```

Try it online! Example usage: `([0]#[2..]!!) 10` yields `6` (0-indexed).

The function `#` operates on two list, the reversed front of the array `[p-1, p-2, ..., 1]` and the infinite rest of the array `[p, p+1, p+2, ...]`. It constructs an infinite list of positions, from which the `n`th position is returned given an input `n`.

The pattern `((a:b)#(p:q))` binds `p` to the value of the current position of the ant and `a` to the value a the previous position. `b` is the prefix of the array from position 1 to `p-2` and `q` the infinite rest starting from position `p+1`.

We construct a list of recursive calls in the following way: We look at each divisor `d` of `p` (which is larger than one and smaller than `p`) in ascending order and add `b#(a+d:div p d:q)` for each of them, that is the current value `p` is divided by `d` and the ant moves one step to the left where `d` is added to `a`. Then we append `(p:a:b)#q` to the end of this list, which indicates the ant moving one step to the right.

We then take the first of those recursive calls from the list and prepend the current position, which coincides with the length of the prefix list `b`. Because the divisors are in ascending order, picking the first from the list of recursive calls ensures we use the smallest one. Additionally, because `(p:a:b)#q` is added to the end of the list, it is only selected if there are no divisors and `p` is thus prime.

*Edits:*
-2 bytes by switching the list of functions from descending to ascending order.
-12 bytes thanks to Zgarb's idea to index into an infinite list instead handling a counter, and by switching to 0-indexing.
> 6 votes

# Answer
# TI-BASIC, ~~108~~ ~~103~~ ~~102~~ 98 bytes

Input and output are stored in `Ans`. Output is 1-indexed.

```
Ans→N
seq(X,X,2,9³→A
1→P
For(I,1,N
1→X:∟A(P→V
For(F,2,√(V
If X and not(fPart(V/F:Then
DelVar XV/F→∟A(P
P-1→P
F+∟A(P→∟A(P
End
End
P+X→P
End

```
> 5 votes

# Answer
# MATL, 41 bytes

```
:Q1y"XHyw)Zp?5MQ}1MtYf1)/H(8MyfHq=*+9M]]&

```

Output is 1-based. The program times out for the last test case in the online interpreter.

**Try it online!**

### Explanation

The program applies the procedure as described in the challenge. To do so, it makes unusually heavy use of MATL's manual and automatic clipboards.

The smallest divisor is obtained as the first entry in the prime factor decomposition.

The "divide" update is done by overwriting the corresponding entry of array *A*. The "add" update is done by element-wise adding to *A* an array that contains zeros except at the desired position.

```
:Q        % Implicitly input n. Push array [2 3 ... n+1]. This is the initial array A.
          % It contains all required positions. Some values will be overwritten
1         % Push 1. This is the initial value for p
y         % Duplicate from below
"         % For each loop. This executes the following n times.
          %   STACK (contents whosn bottom to top): A, p
  XH      %   Copy p into clipboard H
  y       %   Duplicate from below. STACK: A, p, A
  w       %   Swap. STACK: A, A, p
  )       %   Reference indexing. STACK: A, A[p]
  Zp      %   Isprime. STACK: A, false/true
  ?       %   If true (that is, if A[p] is prime)
    5M    %     Push p from automatic clipboard. STACK: A, p
    Q     %     Add 1. STACK: A, p+1
  }       %   Else (that is, if A[p] is not prime)
    1M    %     Push A[p] from automatic clipboard. STACK: A, A[p]
    t     %     Duplicate. STACK: A, A[p], A[p]
    Yf    %     Prime factors, with repetitions. STACK: A, A[p], prime factors of A[p]
    1)    %     Get first element, d. STACK: A, A[p], d
    /     %     Divide. STACK: A, A[p]/d
    H     %     Push p from clipboard H. STACK: A, A[p]/d, p
    (     %     Assignment indexing: write value. STACK: A with A[p] updated
    8M    %     Push d from automatic clipboard.
    y     %     Duplicate from below. STACK: A with A[p] updated, d, A with A[p] updated
    f     %     Find: push indices of nonzero entries.
          %     STACK: A with A[p] updated, d, [1 2 ... n]
    Hq    %     Push p from clipboard H, subtract 1.
          %     STACK: A with A[p] updated, d, [1 2 ... n], p-1
    =     %     Test for equality, element-wise.
          %     STACK: A with A[p] updated, d, [0 ... 0 1 0 ... 0]
    *     %     Multiply, element-wise. STACK: A with A[p] updated, [0 ... 0 d 0 ... 0]
    +     %     Add, element-wise. STACK: A with A[p-1] and A[p] updated
    9M    %     Push p-1 from automatic clipboard.
          %     STACK: A with A[p-1] and A[p] updated, p-1
  ]       %   End if. The stack contains the updated array and index
]         % End for each. Process the next iteration
&         % Specify that the following implicit display function should display only
          % the top of the stack. Implicitly display

```
> 5 votes

# Answer
# PARI/GP, 87 bytes

```
f(n)=A=[2..9^5];p=1;for(i=1,n,q=factor(A[p])[1,1];if(A[p]-q,A[p]/=q;p--;A[p]+=q,p++));p

```

Pretty self-explanatory (not so golf-ish). If you do not count the `f(n)=` part, that is 82 bytes. You can also start by `n->` (85 bytes).

It is a 1-indexed language.

---

**Edit:** The modification `illustrate(n,m)=A=[2..m+1];p=1;for(i=1,n,for(j=1,m,printf("%5s",if(j==p,Str(">",A[j],"<"),Str(A[j]," "))));print();q=factor(A[p])[1,1];if(A[p]!=q,A[p]/=q;p--;A[p]+=q,p++))` will print an illustration of the ant's walk (given a wide enough terminal). For example `illustrate(150,25)` will give the first 150 steps on 25 columns, like this:

```
  >2<   3    4    5    6    7    8    9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2   >3<   4    5    6    7    8    9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    3   >4<   5    6    7    8    9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2   >5<   2    5    6    7    8    9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5   >2<   5    6    7    8    9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    2   >5<   6    7    8    9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    2    5   >6<   7    8    9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    2   >7<   3    7    8    9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    2    7   >3<   7    8    9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    2    7    3   >7<   8    9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    2    7    3    7   >8<   9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    2    7    3   >9<   4    9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    2    7   >6<   3    4    9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    2   >9<   3    3    4    9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5   >5<   3    3    3    4    9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5   >3<   3    3    4    9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    3   >3<   3    4    9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    3    3   >3<   4    9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    3    3    3   >4<   9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    3    3   >5<   2    9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    3    3    5   >2<   9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    3    3    5    2   >9<  10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    3    3    5   >5<   3   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    3    3    5    5   >3<  10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    3    3    5    5    3  >10<  11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    3    3    5    5   >5<   5   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    3    3    5    5    5   >5<  11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    3    3    5    5    5    5  >11<  12   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    3    3    5    5    5    5   11  >12<  13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    3    3    5    5    5    5  >13<   6   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    3    3    5    5    5    5   13   >6<  13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    3    3    5    5    5    5  >15<   3   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    3    3    5    5    5   >8<   5    3   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    3    3    5    5   >7<   4    5    3   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    3    3    5    5    7   >4<   5    3   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    3    3    5    5   >9<   2    5    3   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    3    3    5   >8<   3    2    5    3   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    3    3   >7<   4    3    2    5    3   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    3    3    7   >4<   3    2    5    3   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    3    3   >9<   2    3    2    5    3   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    3   >6<   3    2    3    2    5    3   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5   >5<   3    3    2    3    2    5    3   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    5   >3<   3    2    3    2    5    3   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3   >3<   2    3    2    5    3   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3   >2<   3    2    5    3   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2   >3<   2    5    3   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3   >2<   5    3   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    2   >5<   3   13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    2    5   >3<  13   14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    2    5    3  >13<  14   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    2    5    3   13  >14<  15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    2    5    3  >15<   7   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    2    5   >6<   5    7   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    2   >7<   3    5    7   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    2    7   >3<   5    7   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    2    7    3   >5<   7   15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    2    7    3    5   >7<  15   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    2    7    3    5    7  >15<  16   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    2    7    3    5  >10<   5   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    2    7    3   >7<   5    5   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    2    7    3    7   >5<   5   16   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    2    7    3    7    5   >5<  16   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    2    7    3    7    5    5  >16<  17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    2    7    3    7    5   >7<   8   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    2    7    3    7    5    7   >8<  17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    2    7    3    7    5   >9<   4   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    2    7    3    7   >8<   3    4   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    2    7    3   >9<   4    3    4   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    2    7   >6<   3    4    3    4   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    2   >9<   3    3    4    3    4   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3   >5<   3    3    3    4    3    4   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5   >3<   3    3    4    3    4   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3   >3<   3    4    3    4   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3   >3<   4    3    4   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    3   >4<   3    4   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3   >5<   2    3    4   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5   >2<   3    4   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2   >3<   4   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    3   >4<  17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2   >5<   2   17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    5   >2<  17   18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    5    2  >17<  18   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    5    2   17  >18<  19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    5    2  >19<   9   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    5    2   19   >9<  19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    5    2  >22<   3   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    5   >4<  11    3   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2   >7<   2   11    3   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7   >2<  11    3   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    2  >11<   3   19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    2   11   >3<  19   20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    2   11    3  >19<  20   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    2   11    3   19  >20<  21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    2   11    3  >21<  10   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    2   11   >6<   7   10   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    2  >13<   3    7   10   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    2   13   >3<   7   10   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    2   13    3   >7<  10   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    2   13    3    7  >10<  21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    2   13    3   >9<   5   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    2   13   >6<   3    5   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    2  >15<   3    3    5   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7   >5<   5    3    3    5   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5   >5<   3    3    5   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    5   >3<   3    5   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    5    3   >3<   5   21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    5    3    3   >5<  21   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    5    3    3    5  >21<  22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    5    3    3   >8<   7   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    5    3   >5<   4    7   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    5    3    5   >4<   7   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    5    3   >7<   2    7   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    5    3    7   >2<   7   22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    5    3    7    2   >7<  22   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    5    3    7    2    7  >22<  23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    5    3    7    2   >9<  11   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    5    3    7   >5<   3   11   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    5    3    7    5   >3<  11   23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    5    3    7    5    3  >11<  23   24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    5    3    7    5    3   11  >23<  24   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    5    3    7    5    3   11   23  >24<  25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    5    3    7    5    3   11  >25<  12   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    5    3    7    5    3  >16<   5   12   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    5    3    7    5   >5<   8    5   12   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    5    3    7    5    5   >8<   5   12   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    5    3    7    5   >7<   4    5   12   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    5    3    7    5    7   >4<   5   12   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    5    3    7    5   >9<   2    5   12   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    5    3    7   >8<   3    2    5   12   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    5    3   >9<   4    3    2    5   12   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    5   >6<   3    4    3    2    5   12   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5   >7<   3    3    4    3    2    5   12   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    7   >3<   3    4    3    2    5   12   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    7    3   >3<   4    3    2    5   12   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    7    3    3   >4<   3    2    5   12   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    7    3   >5<   2    3    2    5   12   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    7    3    5   >2<   3    2    5   12   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    7    3    5    2   >3<   2    5   12   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    7    3    5    2    3   >2<   5   12   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    7    3    5    2    3    2   >5<  12   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    7    3    5    2    3    2    5  >12<  25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    7    3    5    2    3    2   >7<   6   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    7    3    5    2    3    2    7   >6<  25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    7    3    5    2    3    2   >9<   3   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    7    3    5    2    3   >5<   3    3   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    7    3    5    2    3    5   >3<   3   25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    7    3    5    2    3    5    3   >3<  25   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    7    3    5    2    3    5    3    3  >25<  26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    7    3    5    2    3    5    3   >8<   5   26
   2    5    5    5    3    3    2    3    5    3    3    5    2    7    5    7    3    5    2    3    5   >5<   4    5   26

```
> 3 votes

# Answer
# Pyth - 44 bytes

Straightforward procedural implementation.

```
K}2hhQVQJ@KZIP_J=hZ).?=GhPJ XKZ/JG=tZ XZKG;Z

```

Test Suite.
> 2 votes

# Answer
# Python 3, ~~158~~ ~~149~~ 133 bytes

This is a straightforward procedural implementation with one or two quirks to make sure the code works for all test cases. I use `[*range(2,n+9)]` to ensure that A is large enough (except for `n<3`, `n+9` is more than enough). The `else` clause divides the old `A[p]` by `d`, decrements `p`, and then adds `d` to the new `A[p]`, which is definitely bad coding practice. Otherwise, pretty straightforward. Golfing suggestions welcome!

**Edit:** -9 bytes without `sympy` thanks to Halvard Hummel. -14 bytes from Felipe Nardi Batista, -6 bytes from some cues from Jonathan Frech's Python 2 answer

```
p,_,*A=range(int(input())+2)
for _ in A:
 m=A[p];d=min(k for k in range(2,m+1)if m%k<1);p+=1
 if d<m:A[p-1]//=d;p-=2;A[p]+=d
print(p)

```

Try it online!
> 2 votes

# Answer
# Python 2, ~~142~~ 127 bytes

```
T=range(2,input()+2);p=0
for _ in T:
 m=T[p];d=min(k for k in range(2,m+1)if m%k<1);p+=1
 if d<m:T[p-1]/=d;p-=2;T[p]+=d
print p

```

Try it online!
> 2 votes

# Answer
# Mathematica, ~~118~~ 103 bytes

```
(s=Range[2,5^6];t=1;Do[If[PrimeQ@s[[t]],t++,s[[t]]/=(k=#2&@@ Divisors@s[[t]]);s[[t-1]]+=k;t--],#];t-1)&

```

Try it online!

*Martin Ender saved 15 bytes*
> 2 votes

# Answer
# PHP, 102+1 bytes

```
for($a=range(2,$argn);$argn--;$d<$a[+$p]?$a[$p--]/=$d+!$a[$p]+=$d:$p++)for($d=1;$a[+$p]%++$d;);echo$p;

```

Run as pipe with `-R` or try it online.

Empty output for input `0`; insert `+` after `echo` for a literal `0`

or use this 1-indexed version (103+1 bytes):

```
for($a=range($p=1,$argn);$argn--;$d<$a[$p]?$a[$p--]/=$d+!$a[$p]+=$d:$p++)for($d=1;$a[$p]%++$d;);echo$p;

```
> 2 votes

# Answer
# C (gcc), ~~152~~ 148 bytes

### Minified

```
int f(int n){int*A=malloc(++n*4),p=0,i,q;for(i=0;i<n;i++)A[i]=i+2;for(i=1;i<n;i++){for(q=2;A[p]%q;q++);if(A[p++]>q){A[--p]/=q;A[--p]+=q;}}return p;}

```

### Formated with some comments

```
int f(int n) {
  int *A = malloc(++n * 4), p = 0, i, q;
  // Initialize array A
  for (i = 0; i < n; i++)
    A[i] = i + 2;
  // Do n step (remember n was incremented)
  for (i = 1; i < n; i++) {
    // Find smallest divisor
    for (q = 2; A[p] % q; q++)
      ;
    if (A[p++] > q) {
      A[--p] /= q;
      A[--p] += q;
    }
  }
  return p;
}

```

### Main function for testing

```
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv) {
  if (argc != 2)
    return 2;
  int n = atoi(argv[1]);
  int p = f(n);
  printf("%d => %d\n", n, p);
  return 0;
}

```

### For showing each step

1. Declare display() inside f()

```
int f(int n) {
  int *A = malloc(++n * 4), p = 0, i, q;
  void display(void) {
    for (int i=0; i < p; i++) {
      printf(" %d", A[i]);
    }
    printf(" \033[1;31m%d\033[m", A[p]);
    if (p+1 < n)
      printf(" %d", A[p+1]);
    printf("\n");
  }
  ...

```
2. Call display()

```
  A[i] = i + 2;
display();

```
3. Call display()

```
  }
  display();
}

```
> 2 votes

# Answer
# , 123 bytes

A straightforward implementation. It is provided as a function, which takes the number of moves as input and returns the position p.

It loops over the sequence and moves the pointer forth and back according to the rules. The output is 0-based.

A note: in order to find the smallest prime factor of a number x, it computes the modulus of x relative to all integers from 0 to x. It then extracts the numbers with modulus equal to 0, which are always \[0,1,...,x\]. If the third such number is not x, then it is the smallest prime factor of x.

```
p=function(l){w=0:l;v=w+1;j=1;for(i in w){y=v[j];x=w[!y%%w][3]
if(x%in%c(NA,y))j=j+1
else{v[j]=y/x;j=j-1;v[j]=v[j]+x}}
j-2}

```

Try it online!
> 2 votes

# Answer
## Clojure, 185 bytes

```
#(loop[[n p][(vec(range 2 1e3))0]i %](if(= i 0)p(recur(if-let[q(first(for[i(range 2(n p)):when(=(mod(n p)i)0)]i))][(assoc n p(/(n p)q)(dec p)(+(n(dec p))q))(dec p)][n(inc p)])(dec i))))

```

Ouch, editing a "state" is not ideal in Clojure. You'll need to increase the exponent for larger inputs.
> 1 votes

# Answer
# Java 8, ~~138~~ 135 bytes

```
n->{int a[]=new int[++n],s=0,p=0,j=0;for(;j<n;a[j++]=j+1);for(;++s<n;p++)for(j=1;++j<a[p];)if(a[p]%j<1){a[p--]/=j;a[p--]+=j;}return p;}

```

**Explanation:**

Try it here.

```
n->{                     // Method with integer as both parameter and return-type
  int a[]=new int[++n],  //  Integer-array with a length of `n+1`
      s=0,               //  Steps-counter (starting at 0)
      p=0,               //  Current position (starting at 0)
      j=0;               //  Index integer (starting at 0)
  for(;j<n;              //  Loop (1) from 0 to the input (inclusive due to `++n` above)
    a[j++]=j+1           //   And fill the array with 2 through `n+2`
  );                     //  End of loop (1)
  for(;++s<n;            //  Loop (2) `n` amount of steps:
      p++)               //    And after every iteration: increase position `p` by 1
    for(j=1;             //   Reset `j` to 1
        ++j<a[p];)       //   Inner loop (3) from 2 to `a[p]` (the current item)
      if(a[p]%j<1){      //    If the current item is divisible by `j`:
        a[p--]/=j;       //     Divide the current item by `j`
        a[p--]+=j;}      //     And increase the previous item by `j`
                         //     And set position `p` two steps back (with both `p--`)
                         //   End of inner loop (3) (implicit / single-line body)
                         //  End of loop (2) (implicit / single-line body)
  return p;              //  Return the resulting position `p`
}                        // End of method

```
> 1 votes

# Answer
# Clojure, ~~198~~ ~~193~~ 191 bytes

This needs to be severely golfed...

```
#(loop[i(vec(range 2(+ % 9)))c 0 p 0](if(= % c)p(let[d(dec p)u(i p)f(some(fn[n](if(=(mod u n)0)n))(range 2(inc u)))e(= u f)](recur(if e i(assoc i d(+(i d)f)p(/ u f)))(inc c)(if e(inc p)d)))))

```

**Golf 1**: Saved 5 bytes by changing `(first(filter ...))` to `(some ...)`

**Golf 2**: Saved 2 bytes by changing `(zero? ...)` to `(= ... 0)`

---

## Usage:

```
(#(...) 10000) => 512

```

## Ungolfed code:

```
(defn prime-ant [n]
  (loop [counter 0
         pos 0
         items (vec (range 2 (+ n 9)))]
    (if (= n counter) pos
      (let [cur-item (nth items pos)
            prime-factor
            (some #(if (zero? (mod cur-item %)) %)
              (range 2 (inc cur-item)))
            equals? (= cur-item prime-factor)]
        (recur
          (inc counter)
          (if equals? (inc pos) (dec pos))
          (if equals? items
            (assoc items
              (dec pos) (+ (items (dec pos)) prime-factor)
              pos (/ cur-item prime-factor))))))))

```
> 1 votes

---
Tags: code-golf, sequence, primes
---