title: Goldenness of an integer

text:
# Question
Title: Goldenness of an integer
A positive integer *n* can be represented as a *rectangle with integer sides* *a*, *b* such that *n* = *a* * *b*. That is, the area represents the number. In general, *a* and *b* are not unique for a given *n*.

As is well known, a rectangle is specially pleasing to the eye (or is it the brain?) when its sides are in the *golden ratio*, *φ* = (sqrt(5)+1)/2 ≈ 1.6180339887...

Combining these two facts, the purpose of this challenge is to decompose an integer *n* into the product of two integers *a*, *b* whose ratio is as close as possible to *φ* (with the usual metric on ℝ). The fact that *φ* is irrational implies that there is a unique solution pair (*a*, *b*).

# The challenge

Given a positive integer *n*, output positive integers *a*, *b* such that *a* * *b* = *n* and the absolute difference between *a*/*b* and *φ* is minimized.

As an example, consider *n* = 12. The pairs (*a*, *b*) that satisfy *a* * *b* = *n* are: (1, 12), (2,6), (3,4), (4,3), (6,2), (12,1). The pair whose ratio is closest to *φ* is (4,3), which gives 4/3 = 1.333.

# Rules

Functions or programs are acceptable.

The *numerator* (*a*) should appear *first* in the output, and the *denominator* (*b*) *second*. Other than that, input and output formats are flexible as usual. For example, the two numbers can be output as strings with any reasonable separator, or as an array.

The code should work in theory for arbitrarily large numbers. In practice, it may be limited by memory or data-type restrictions.

It's sufficient to consider an approximate version of *φ*, as long as it is accurate up to the *third decimal* or better. That is, the absolute difference between the true *φ* and the approximate value should not exceed 0.0005. For example, 1.618 is acceptable.

When using an approximate, rational version of *φ* there's a small chance that the solution is not unique. In that case you can output any pair *a*, *b* that satisfies the minimization criterion.

Shortest code wins.

# Test cases

```
1        ->  1    1
2        ->  2    1
4        ->  2    2
12       ->  4    3
42       ->  7    6
576      ->  32   18
1234     ->  2    617
10000    ->  125  80
199999   ->  1    199999
9699690  ->  3990 2431

```

# Answer
> 6 votes
# Jelly, ~~16~~ ~~15~~ 14 bytes

*Saved 1 byte thanks to @miles.*

```
÷/ạØp
ÆDżṚ$ÇÞḢ

```

Try it online!

### Explanation

```
÷/ạØp         Helper link, calculates abs(a/b - phi). Argument: [a, b]
÷/            Reduce by division to calculate a/b.
  ạØp         Calculate abs(a/b - phi).

ÆDżṚ$ÇÞḢ      Main link. Argument: n
ÆD            Get divisors of n.
  żṚ$         Pair the items of the list with those of its reverse. The reversed
              divisors of a number is the same list as the number divided by each
              of the divisors.
     ÇÞ       Sort by the output of the helper link of each pair.
       Ḣ      Get the first element [a, b] and implicitly print.

```

# Answer
> 7 votes
# Pyth - ~~24~~ 23 bytes

There has to be a better way to find the divisors...

```
ho.a-.n3cFNfsIeTm,dcQdS

```

Test Suite.

# Answer
> 6 votes
# Matlab, 96 81 bytes

Golfed (-15bytes), props to Luis Mendo

```
function w(n);a=find(~(mod(n,1:n)));[~,c]=min(abs(a./(n./a)-1.618));[a(c) n/a(c)]

```

Original:

```
function w(n)
a=find(not(mod(n,1:n)));b=abs(a./(n./a)-1.618);c=find(not(b-min(b)));[a(c) n/a(c)]

```

This is by far not a great solution, but my first attempt at code-golf. What fun!

# Answer
> 5 votes
## Mathematica, 51 bytes

```
#&@@SortBy[{x=Divisors@#,#/x},Abs[#/#2-1.618]&]&

```

The  is Mathematica's postfix operator for transposition (displayed as a superscript `T` in Mathematica).

Mathematica has a built-in `GoldenRatio`, but 1.618 is a lot shorter, especially because the former also requires `N@`.

# Answer
> 5 votes
# 05AB1E, 21 bytes

Code:

```
ÑÂø©vy`/})5t>;-ÄWQ®sÏ

```

Uses the **CP-1252** encoding. Try it online!

# Answer
> 5 votes
# Pyth, ~~21~~ ~~20~~ 18 bytes

```
hoacFN.n3C_Bf!%QTS

```

Try it online. Test suite.

### Explanation

1. Get the inclu`S`ive range from 1 to input.
2. `f`ilter for numbers for that divide the input `!%QT`.
3. Get `[that list, that list reversed]` `_B`. The reversed divisors of a number is the same list as the number divided by each of the divisors.
4. Transpose the list to get pairs of `[numerator, denominator]`.
5. S`o`rt the pairs by the `a`bsolute difference of the ratio of the pair `cFN` and the golden ratio `.n3`.
6. Get the first (lowest) pair `h` and print.

# Answer
> 5 votes
## Javascript (ES6), 73 bytes

```
n=>{for(b=0,k=n/.809;n%++b||k>b*b*2&&(a=b););return[b=k-a*a>b*b?b:a,n/b]}

```

We look for:

* **a** = highest divisor of n for which **n / φ \> a²**
* **b** = lowest divisor of n for which **n / φ \< b²**

Then, the solution is either **\[ a, n / a \]** or **\[ b, n / b \]**. We compare **n / φ - a²** with **b² - n / φ** to find out which expression is closest to zero.

The actual formula used in the code are based on φ / 2 which can be written in a shorter way than φ with the same precision: `.809` vs `1.618`.

Therefore:

> n / φ \> a² ⇔ **n / (φ / 2) \> 2a²**

and:

> n / φ - a² \> b² - n / φ ⇔ 2n / φ - a² \> b² ⇔ **n / (φ / 2) \- a² \> b²**

### Complexity

The number of iterations heavily depends on the number of factors of n. The worst case occurs when n is prime, because we have to perform all iterations from 1 to n to find its only 2 divisors. This is what happens with 199999. On the other hand, 9699690 is 19-smooth and we quickly find two divisors on either sides of the breaking point √(n/φ) ≈ 2448.

### Test cases

```
let f =
n=>{for(b=0,k=n/.809;n%++b||k>b*b*2&&(a=b););return[b=k-a*a>b*b?b:a,n/b]}

console.log(JSON.stringify(f(12)));       // [ 3, 4 ]
console.log(JSON.stringify(f(42)));       // [ 6, 7 ]
console.log(JSON.stringify(f(576)));      // [ 18, 32 ]
console.log(JSON.stringify(f(1234)));     // [ 2, 617 ]
console.log(JSON.stringify(f(10000)));    // [ 80, 125 ]
console.log(JSON.stringify(f(199999)));   // [ 1, 199999 ]
console.log(JSON.stringify(f(9699690)));  // [ 2431, 3990 ]
```

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

```
f=
n=>{p=r=>Math.abs(r/n-n/r-1);for(r=i=n;--i;)r=n%i||p(i*i)>p(r*r)?r:i;return[r,n/r]}
;
```

```
<input type=number min=1 oninput=[a.value,b.value]=f(+this.value)><input readonly id=a><input readonly id=b>
```

Actually returns the (*a*, *b*) pair which minimises the absolute value of *a*/*b*-*b*/*a*-1, but this works for all the test cases at least, although I guess I could save 4 bytes by using the 1.618 test instead.

# Answer
> 3 votes
# Brachylog, 41 bytes

```
:1fL:2a:Lzoht
,A:B#>.*?!,.=
:3a/:$A-$|
//

```

Try it online!

### Explanation

* Main predicate:

```
:1fL           L is the list of all couples [A:B] such that A*B = Input (see Pred. 1)
    :2a        Compute the distance between all As/Bs and φ (see Pred. 2)
       :Lz     Zip those distances to L
          o    Sort the zip on the distances
           ht  Take the couple [A:B] of the first element of the sorted list

```
* Predicate 1: Output is a couple `[A:B]` such that `A*B = Input`

```
,A:B           The list [A:B]
    #>         Both A and B are strictly positive
      .        Output = [A:B]
       *?      A*B = Input
         !,    Discard other choice points
           .=  Assign a value to A and B that satisfy the constraints

```
* Predicate 2: Compute the distance between `A/B` and φ.

```
:3a            Convert A and B to floats
   /           Divide A by B
    :$A-       Subtract φ
        $|     Absolute value

```
* Predicate 3: Convert an int to a float by inverting its inverse

```
/              1/Input
 /             Output = 1/(1/Input)

```

# Answer
> 2 votes
# Haskell (Lambdabot), 86 bytes

```
f(x,y)=abs$(x/y)-1.618
q n=minimumBy((.f).compare.f)[(x,y)|x<-[1..n],y<-[1..n],x*y==n]

```

# Answer
> 2 votes
# php, 103 bytes

```
<?php for($s=$a=$argv[1];++$i<$a;)if($a%$i==0&&$s>$t=abs($i*$i/$a-1.618)){$n=$i;$s=$t;}echo"$n ".$a/$n;

```

Produces a notice (this doesn't interrupt execution) about unassigned $i so should be run in an environment that silences notices.

# Answer
> 1 votes
# Python 3, 96 bytes

Pretty simple solution. Makes use of this SO answer.

```
lambda n:min([((i,n//i),abs(1.618-i/(n//i)))for i in range(1,n+1)if n%i<1],key=lambda x:x[1])[0]

```

**Try it online**

The same solution in Python 2 is one byte longer.

```
lambda n:min([((i,n/i),abs(1.618-1.*i/(n/i)))for i in range(1,n+1)if n%i<1],key=lambda x:x[1])[0]

```

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


title: Roll the Alphabet into a Spiral

text:
# Question
Title: Roll the Alphabet into a Spiral
Write a program or function that, when given `n`, will print a spiral `n` characters long made up of the Latin alphabet `ABCDEFGHIJKLMNOPQRSTUVWXYZ` repeated as needed. This spiral should run through the alphabet only forwards.

Related to Alphabet Spiral, though the spiral runs through the alphabet forwards and backwards, and the spiral is constant.

**Test cases**

```
4   AB
    DC

40   UVWXYZ
     TGHIJA
    NSFABKB
    MREDCLC
    LQPONMD
    KJIHGFE

0

10  GHIJ
    FAB
    EDC

1000    UVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ
        TGHIJKLMNOPQRSTUVWXYZABCDEFGHIJA
        SFABCDEFGHIJKLMNOPQRSTUVWXYZABKB
        REZCDEFGHIJKLMNOPQRSTUVWXYZABCLC
        QDYBMNOPQRSTUVWXYZABCDEFGHIJCDMD
        PCXALEFGHIJKLMNOPQRSTUVWXYZKDENE
        OBWZKDEFGHIJKLMNOPQRSTUVWXALEFOF
        NAVYJCDMNOPQRSTUVWXYZABCDYBMFGPG
        MZUXIBCLCDEFGHIJKLMNOPQREZCNGHQH
        LYTWHABKBABCDEFGHIJKLMNSFADOHIRI
        KXSVGZAJAZGHIJKLMNOPQROTGBEPIJSJ
        JWRUFYZIZYFUVWXYZABCDSPUHCFQJKTK
        IVQTEXYHYXETQRSTUVWXETQVIDGRKLUL
        HUPSDWXGXWDSPUVWXYZYFURWJEHSLMVM
        GTORCVWFWVCROTGHIJAZGVSXKFITMNWN
        FSNQBUVEVUBQNSFABKBAHWTYLGJUNOXO
        ERMPATUDUTAPMREDCLCBIXUZMHKVOPYP
        DQLOZSTCTSZOLQPONMDCJYVANILWPQZQ
        CPKNYRSBSRYNKJIHGFEDKZWBOJMXQRAR
        BOJMXQRARQXMLKJIHGFELAXCPKNYRSBS
        ANILWPQZQPWVUTSRQPONMBYDQLOZSTCT
        ZMHKVOPYPONMLKJIHGFEDCZERMPATUDU
        YLGJUNOXONMLKJIHGFEDCBAFSNQBUVEV
        XKFITMNWVUTSRQPONMLKJIHGTORCVWFW
        WJEHSLMLKJIHGFEDCBAZYXWVUPSDWXGX
        VIDGRKJIHGFEDCBAZYXWVUTSRQTEXYHY
        UHCFQPONMLKJIHGFEDCBAZYXWVUFYZIZ
        TGBEDCBAZYXWVUTSRQPONMLKJIHGZAJA
        SFAZYXWVUTSRQPONMLKJIHGFEDCBABKB
        REDCBAZYXWVUTSRQPONMLKJIHGFEDCLC
        QPONMLKJIHGFEDCBAZYXWVUTSRQPONMD
                                LKJIHGFE

```

**Rules**

* Your input will be a non-negative integer `0 <= n <= 1000`, but your code should theoretically handle any non-negative integer.
* Your output format may be in any sane format, with delimiters if necessary.
* Rotations and reflections are equivalent.
* Your alphabet may be uppercase or lowercase.
* The empty spaces in your spiral may be filled in with whatever non-alphabetic nulls you see fit.
* The spiral itself may be in any shape you see fit. Rectangular spirals work best with ASCII solutions, but graphical solutions may be shorter with circular spirals.
* Leading and trailing spaces and newlines are allowed.
* This is code golf. The shortest answer in bytes (or equivalent) wins.

As always, if anything is unclear or incorrect, please let me know in the comments. Good luck and good golfing!

# Answer
> 12 votes
# Logo, ~~129~~ 87 bytes

## Graphical solution, implemented as function

This was built on Calormen.com's Logo interpreter. The `S` function takes the number of characters as a parameter and draws them in a spiral. ~~The `T` function outputs letters upright to prevent them from rotating with the spiral.~~. I decided that it looked nicer (and golfed out 42 bytes) to omit correcting the letter orientation. I also tightened up the spacing which did not change the byte count. If you were to actually roll up an alphabet, it would look more like this anyway.

### Updated Version (letters roll)

```
TO S:r
PU IF:r[REPEAT:r[LABEL CHAR((REPCOUNT-1)%26)+65
RT 99/SQRT(REPCOUNT)FD 12]]END

```

### Invocation

Invoke as follows: `S` *iterations*

### Sample output

```
S 1000

```

## Old Version (letters always upright)

~~```
TO T:l:h
RT:h
LABEL CHAR(:l%26)+65
LT:h
END
TO S:r
PU IF:r[REPEAT:r[T REPCOUNT-1 90-HEADING
RT 95/SQRT(REPCOUNT)FD 15]]END

```~~

Old output removed to save space. See it here.

# Answer
> 9 votes
## Javascript (ES6), ~~203~~ 201 bytes

```
n=>{for(a=[],i=d=k=z=0,p=526,j=1;i<n;){p+=[1,32,-1,-32][d&3];j--||(((z^=1)||k++),j=k,d++);(a[y=p>>5]=(a[y]||Array(32).fill` `))[p&31]=String.fromCharCode(65+(i++%26))}return a.map(r=>r.join``).join`
`}

```

### Demo

The demo below should be preferably run in full page.

```
let f =

n=>{for(a=[],i=d=k=z=0,p=526,j=1;i<n;){p+=[1,32,-1,-32][d&3];j--||(((z^=1)||k++),j=k,d++);(a[y=p>>5]=(a[y]||Array(32).fill` `))[p&31]=String.fromCharCode(65+(i++%26))}return a.map(r=>r.join``).join`
`}

function draw(n) {
  document.getElementById('v').innerHTML = n;
  document.getElementById('o').innerHTML = f(n);
}
draw(500);
```

```
pre {font-size:10px}
```

```
<input type="range" min="1" max="1000" oninput="draw(this.value)" style="width:500px"><span id="v"></span><pre id="o"></pre>
```

# Answer
> 8 votes
# R, 46 or 51 bytes, depending on spacing

```
s=1:scan();plot(s*sin(s),s*cos(s),pch=letters)

```

(updated version of plot: the gray spiral isn't plotted by default but I added it after to show that the letters indeed lie on a spiral.)

The spiral isn't of constant spacing, so I hope this is okay. If constant spacing is required, start with `s=(1:scan())^.5` instead, and add 5 bytes to the total. Then the output is as below (n=150):

# Answer
> 6 votes
# Python 3.5, ~~180~~ ~~157~~ ~~152~~ ~~147~~ 141 bytes

-6 due to Sherlock9

```
r=[[]]
for x in range(int(input())):
 r=len(r[-1])<len(r[0])and r or[*zip(*r[::-1]),[]];r[-1]+=[chr(x%26+65)]
print(*map(''.join,r),sep='\n')

```

-5 due to Kap.

```
R=range
def g(n):
 r=[[]]
 for x in R(n):
  if len(r[-1])==len(r[0]):r=[*zip(*r[::-1]),[]]
  r[-1]+=[chr(x%26+65)]
 print(*map(''.join,r),sep='\n')

```

### Revised Solution, python 3.x:

```
R=range
def g(n):
 r=[[]]
 for x in R(n):
  if len(r[-1])==len(r[0]):r=list(zip(*r[::-1]))+[[]]
  r[-1]+=[chr(x%26+65)]
 print(*map(''.join,r),sep='\n')

```

### Previous Solution:

```
R=range
def g(n):
 r=[]
 for x,f in zip(R(n),(j<1for i in R(n)for j in R(i//2+1))):
  if f:r=list(zip(*r[::-1]))+[[]]
  r[-1].append(chr(x%26+65))
 print(*map(''.join,r),sep='\n')

```

### Explanation

`r` is a list of lists that holds the spiral. The basic idea is that new letters are added to the bottom row of the spiral (`r[-1].append(chr(x%26+65))`). When the bottom row is filled up, the spiral is rotated 90 clockwise and a new empty row is added to the bottom (`r = list(zip(*r[::-1]))+[[]]`).

The trick is to figure out when to rotate the spiral. In the first solution, the generator `(j<1for i in R(n)for j in R(i//2+1))` produces a sequence of True/False values that tell when to rotate the spiral. In the revised solution, I changed the way `r` is initialized. Now when the length of the bottom row equals the length of the top row, the spiral needs to be rotated.

# Answer
> 5 votes
# MATL, ~~21~~ 18 bytes

```
X^Xk1YL1Y2y)wG>~*c

```

Input `0` exits with an error (which is allowed by default).

Try it online!

### Explanation

```
X^Xk   % Input n implicitly. Take square root and round up
1YL    % Square matrix of that size containing a spiral of numbers
1Y2    % Predefined literal: string "AB···YZ"
y      % Duplicate the spiral matrix onto the top
)      % Apply as an index inth the string. Gives 2D array of chars
w      % Swap: move copy of the spiral matrix to top
G>~    % Set entries that exceed the input to 0, and the rest to 1
*      % Multiply. This makes unwanted entries equal to 0
c      % Convert to char. 0 is shown as a space. Display implicitly

```

# Answer
> 5 votes
# Python 2, ~~84~~ 82 bytes

I'm using Turtle again. It's so fun! :D

```
from turtle import*
up()
for i in range(input()):write(chr(i%26+65));rt(9);fd(9+i)

```

**Try it online**

Unfortunately, Trinket.io has a horribly small canvas. I changed `9+i` to `9+i/9` and adjusted the turtle's starting point for the purpose of screen-capturing this image, so that more of the output would fit:

# Answer
> 4 votes
# Pyth, 32 bytes

```
JS@Q2ju+.t_G)Hc<*GQQ.u+NY.iJJZ]Y

```

A program that prints a rectangular lower-case ASCII spiral. Depending on the input, one row or column of leading or trailing whitespace may be present.

Try it online

**How it works**

```
JS@Q2ju+.t_G)Hc<*GQQ.u+NY.iJJZ]Y  Program. Input: Q
  @Q2                             Yield sqrt(Q)
JS                                Unary range, J=[1, 2, 3, ..., floor(sqrt(q))]
                         .iJJ     Interleave J with itself, yielding [1, 1, 2, 2, 3, 3, ...
                                  floor(sqrt(Q)), floor(sqrt(Q))]
                    .u+NY    Z    Cumulatively reduce by addition with base case 0,
                                  yielding [0, 1, 2, 4, 6, 9, 12, 16, 20...]
                *GQ               Repeat the lower-case alphabet Q times
               <   Q              Truncate to legth Q
              c                   Split the above at the indices in the above list
      u                       ]Y  Reduce the above, with base case [[]]:
          _G                       Reverse
        .t  )                      Transpose
       +     H                     Add the next arm of the spiral
     j                            Join on newlines and implicitly print

```

# Answer
> 3 votes
# TSQL, ~~386~~ ~~362~~ ~~358~~ 306 bytes

Please note that TSQL doesn't have a way to rotate text. This script is starting from A and calculating which direction the next letter should be placed. (right, down, left, left, left, up, up, right...)

The script can handle a maximum of 7744 letters.

**Golfed:**

```
DECLARE @z INT = 7744

DECLARE @ INT=2+SQRT(@z-1)DECLARE @o varchar(max)=REPLICATE(SPACE(@-1)+char(10),@-1);WITH C as(SELECT 0i,@/2a,@/2b UNION ALL SELECT i+1,a+z/2,b+z%2FROM(SELECT*,IIF(a>@/2*2-b,IIF(a<b,2,-1),IIF(a>b,-2,1))z FROM C)t WHERE i<@z-1)SELECT @o=STUFF(@o,@*a-@+b,1,char(i%26+65))FROM c OPTION(maxrecursion 0)PRINT @o

```

**Ungolfed:**

```
DECLARE @z INT = 7744

DECLARE @ INT=2+SQRT(@z-1)
DECLARE @o varchar(max)=REPLICATE(SPACE(@-1)+char(10),@-1)

;WITH C as
(
  SELECT
    0i,@/2a,@/2b
  UNION ALL
  SELECT
    i+1,a+z/2,b+z%2
    FROM
      (SELECT*,
         IIF(a>@/2*2-b,
           IIF(a<b,2,-1),
             IIF(a>b,-2,1))z FROM C)t
  WHERE
    i<@z-1
)
SELECT
  @o=STUFF(@o,@*a-@+b,1,char(i%26+65))
FROM c
OPTION(maxrecursion 0)

PRINT @o

```

**Fiddle**

# Answer
> 2 votes
# Python 2, 243 bytes

```
r=range(input())
a=[1j**int((4*i+1)**.5)for i in r]
b=[map(int,(-sum(a[:i]).real,sum(a[:i]).imag))for i in r]
c,d=zip(*b)
for i in range(min(c),max(c)+1):print''.join([i,j]in b and chr(b.index([i,j])%26+65)or' 'for j in range(min(d),max(d)+1))

```

Ideone it!

# Answer
> 0 votes
# PHP, 219 bytes

```
for($q=ceil(sqrt($a=$argn))**2,$d=1,$x=$y=$w=0;$i<$q;$i++,${yx[$w%2]}+=[-1,1][$d&1],$i%$d?:$d+=$w++&1)$e[$c[]=$x-!($a&1)][$l[]=$y]=$i<$a?chr(65+$i%26):" ";for($k=min($c);$e[$k];print join($e[+$k++])."\n")ksort($e[+$k]);

```

Try it online!

PHP , 260 Bytes

Old version

```
for($y=$x=$d=$i=0;$i<$m=ceil(sqrt($n=$argv[1]))**2;$i++){$a[$y][$x]=$i<$n?chr($i%26+65):" ";$d=$y==$x&$y<1?0:(1-$y==$x&$x>0?1:($y==$x&$y>0?2:($y==-$x&$x<0?3:$d)));$d>2?$y--:($d>1?$x--:($d>0?$y++:$x++));}ksort($a);foreach($a as$r){ksort($r);echo join($r)."\n";}

```

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


# Question
Title: Parse the comments out of my esoteric code
Earlier this week, we learned about how to format esoteric languages for commenting. Today, we're going to do the inverse of that. I need you to write a program or function that parses some well-commented esoteric code and parses the comments out, returning just the code. Using some examples from the previous challenge, here is what well-commented code looks like:

```
a                #Explanation of what 'a' does
 bc              #Bc
   d             #d
    e            #Explanation of e
     fgh         #foobar
        ij       #hello world
          k      #etc.
           l     #so on
            mn   #and
              op #so forth

```

Here is what you need to do to extract the code out. First, remove the comment character (`#`), the space before it, and everything after the comment character.

```
a
 bc
   d
    e
     fgh
        ij
          k
           l
            mn
              op

```

Then, collapse each line upwards into a single line. For example, since `b` is in the second column on line two, once we collapse it up, it will be in the second column on line *one*. Similarly, `c` will be put in the third column of line one, and `d` will be put on the fourth. Repeat this for every character, and you get this:

```
abcdefghijklmnop

```

Important note: It seems like the trivial solution is to just remove the comments, remove every space, and join every line. This is *not* a valid approach! Because the original code might have spaces in it, these will get stripped out with this approach. For example, this is a perfectly valid input:

```
hello         #Line one
              #Line two
       world! #Line three

```

And the corresponding output should be:

```
hello  world!

```

# The Challenge:

Write a program or function that takes commented code as input, and outputs or returns the code with all the comments parsed out of it. You should output the code *without* any trailing spaces, although one trailing newline is permissible. The comment character will always be `#`, and there will always be one extra space before the comments start. `#` will *not* appear in the comment section of the input. In order to keep the challenge simpler, here are some inputs you do *not* have to handle:

* You can assume that the code will not have two characters in the same column. For example, this is an input that violates this rule:

```
a  #A character in column one
bc #Characters in columns one and two

```
* You can also assume that all comment characters appear in the same column. For example, this input:

```
short       #this is a short line
      long        #This is a long line

```

violates this rule. This also means that `#` will not be in the code section.
* And lastly, you do not have to handle code sections with leading or trailing spaces. For example,

```
  Hello,          #
         World!   #

```

You may also assume that the input only contains printable ASCII characters.

# Examples:

```
Input:
hello         #Line one
              #Line two
       world! #Line three

Output:
hello  world!

Input:
E                                                   #This comment intentionally left blank
 ac                                                 #
   h s                                              #
      ecti                                          #
          on is                                     #
                one c                               #
                     haracte                        #
                            r longer                #
                                     than the       #
                                              last! #

Output:
Each section is one character longer than the last!

Input:
4          #This number is 7
 8         #
  15       #That last comment is wrong.
    16     #
      23   #
        42 #

Output:
4815162342

Input:
Hello                     #Comment 1
      world               #Comment 2
           ,              #Comment 3
             how          #Comment 4
                 are      #Comment 5
                     you? #Comment 6

Output:
Hello world, how are you?

Input:
Prepare                               #
        for...                        #
                        extra spaces! #

Output:
Prepare for...          extra spaces!

```

You may take input in whatever reasonable format you like, for example, a list of strings, a single string with newlines, a 2d list of characters, etc. The shortest answer in bytes wins!

# Answer
> 18 votes
# Jelly, ~~8~~ 7 bytes

```
»/ṣ”#ḢṖ

```

Try it online!

### How it works

```
»/ṣ”#ḢṖ  Main link. Argument: A (array of strings)

»/       Reduce the columns of A by maximum.
         Since the space is the lowest printable ASCII characters, this returns the
         non-space character (if any) of each column.
  ṣ”#    Split the result at occurrences of '#'.
     Ḣ   Head; extract the first chunk, i.e., everything before the (first) '#'.
      Ṗ  Pop; remove the trailing space.

```

# Answer
> 13 votes
# Python 2, ~~48~~ 43 bytes

```
lambda x:`map(max,*x)`[2::5].split(' #')[0]

```

*Thanks to @xnor for golfing off 5 bytes!*

Test it on Ideone.

# Answer
> 5 votes
# JavaScript (ES6), ~~97~~ ~~75~~ 60 bytes

Thanks to @Neil for helping golf off 22 bytes

```
a=>a.reduce((p,c)=>p.replace(/ /g,(m,o)=>c[o])).split` #`[0]

```

Input is an array of lines.

* `a` is array input
* `p` is previous item
* `c` is current item
* `m` is match string
* `o` is offset

# Answer
> 4 votes
# Perl, ~~35~~ ~~34~~ 32 bytes

Includes +1 for `-p`

Give input on STDIN

`eso.pl`

```
#!/usr/bin/perl -p
y/ /\0/;/.#/;$\|=$`}{$\=~y;\0;

```

Notice that there is a space after the final `;`. The code works as shown, but replace `\0` by the literal character to get the claimed score.

# Answer
> 3 votes
## Python 2, 187 bytes

```
def f(x,o=""):
 l=[i[:i.index("#")-1]for i in x]
 for n in range(len(l[0])):
  c=[x[n]for x in l]
  if sum([1for x in c if x!=" "])<1:o+=" "
  else:o+=[x for x in c if x!=" "][0]
 print o

```

I'm gonna golf this more tomorrow I have school ;)

# Answer
> 2 votes
# J, 30 bytes

```
(#~[:<./\'#'~:])@(>./&.(3&u:))

```

Takes a list of strings as input. Basically uses the same approach as Dennis in his Jelly answer.

## Commented and explained

```
ord =: 3 & u:
under =: &.
max =: >./
over =: @
maxes =: max under ord
neq =: ~:
arg =: ]
runningMin =: <./\
magic =: #~ [: runningMin ('#' neq arg)

f =: magic over maxes

```

Intermediate steps:

```
   p
Hello                     #Comment 1
      world               #Comment 2
           ,              #Comment 3
             how          #Comment 4
                 are      #Comment 5
                     you? #Comment 6
   maxes p
Hello world, how are you? #Comment 6
   magic
#~ ([: runningMin '#' neq arg)
   3 neq 4
1
   '#' neq '~'
1
   '#' neq '#'
0
   '#' neq maxes p
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1
   runningMin 5 4 2 5 9 0 _3 4 _10
5 4 2 2 2 0 _3 _3 _10
   runningMin '#' neq maxes p
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0
   0 1 0 1 1 0 # 'abcdef'
bde
   'abcdef' #~ 0 1 0 1 1 0
bde
   (maxes p) #~ runningMin '#' neq maxes p
Hello world, how are you?
   (#~ [: runningMin '#' neq arg) maxes p
Hello world, how are you?
   ((#~ [: runningMin '#' neq arg) over maxes) p
Hello world, how are you?
   (magic over maxes) p
Hello world, how are you?

```

## Test case

```
   f =: (#~[:<./\'#'~:])@(>./&.(3&u:))
   a
Hello                     #Comment 1
      world               #Comment 2
           ,              #Comment 3
             how          #Comment 4
                 are      #Comment 5
                     you? #Comment 6
   $a
6 36
   f a
Hello world, how are you?

```

# Answer
> 2 votes
# Ruby, 63 bytes

Basically a port of Dennis' Jelly answer. Takes input as an array of strings.

```
->a{l,=a
l.gsub(/./){a.map{|m|m[$`.size]||$/}.max}[/(.+) #/,1]}

```

See it on eval.in: https://eval.in/640757

# Answer
> 2 votes
## CJam, 12 bytes

*Thanks to Sp3000 for saving 2 bytes.*

```
{:.e>_'##(<}

```

An unnamed block that takes a list of strings (one for each line) and replaces it with a single string.

Try it online!

### Explanation

```
:.e>  e# Reduce the list of strings by elementwise maximum. This keeps non-spaces in
      e# favour of spaces. It'll also wreak havoc with the comments, but we'll discard
      e# those anyway.
_'##  e# Duplicate and find the index of '#'.
(<    e# Decrement that index and truncate the string to this length.

```

# Answer
> 2 votes
# Javascript (ES6), 63 bytes

```
a=>a.reduce((p,c)=>p+/(.+?)\s+#/.exec(c)[1].slice(p.length),'')

```

Takes input as an array of strings.

```
F=a=>a.reduce((p,c)=>p+/(.+?)\s+#/.exec(c)[1].slice(p.length),'')

input.oninput = update;
update();

function update() {
  try {
    output.innerHTML = F(input.value.trim().split`
`);
  } catch(e) {
    output.innerHTML = 'ERROR: INVALID INPUT';
  }
}
```

```
textarea {
  width: 100%;
  box-sizing: border-box;
  font-family: monospace;
}
```

```
<h2>Input:</h2>
<textarea id="input" rows="8">
a                #Explanation of what 'a' does
 bc              #Bc
   d             #d
    e            #Explanation of e
     fgh         #foobar
        ij       #hello world
          k      #etc.
           l     #so on
            mn   #and
              op #so forth
</textarea>
<hr />
<h2>Output:</h2>
<pre id="output">
</pre>
```

# Answer
> 1 votes
# Retina, 32 bytes

Byte count assumes ISO 8859-1 encoding.

```
Rmr` #.+|(?<=^(?<-1>.)+).+?¶( )+

```

Try it online!

# Answer
> 1 votes
## Pyke, ~~15~~ 10 bytes

```
,FSe)s\#ch

```

Try it here!

Port of the Jelly answer

```
,          -     transpose()
 FSe)      -    map(min, ^)
     s     -   sum(^)
      \#c  -  ^.split("#")
         h - ^[0]

```

# Answer
> 1 votes
# C# 157 122 Bytes

Golfed 35 bytes thanks to @milk -- though I swear I tried that earlier.

Takes input as a 2-d array of characters.

```
string f(char[][]s){int i=0;foreach(var x in s)for(i=0;x[i]!=35;i++)if(x[i]!=32)s[0][i]=x[i];return new string(s[0],0,i);}

```

157 bytes:

```
string g(char[][]s){var o=new char[s[0].Length];foreach(var x in s)for(int i=0;x[i]!=35;i++)if(x[i]!=32|o[i]<1)o[i]=x[i];return new string(o).TrimEnd('\0');}

```

# Answer
> 1 votes
# sed, 126 bytes

```
:a;N;$!ba;s,#[^\n]*\n,#,g;s,^,#,;:;/#[^ ]/{/^# /s,^# *,,;t;H;s,#.,#,g}
t;/#[^ ]/!{H;s,#.,#,g};t;g;s,\n#(.)[^\n]*,\1,g;s,...$,,

```

Requires a newline at the end of the input.
I'm sure I can golf this a little more, but I'm just happy it works for now.

# Answer
> 1 votes
# Pyth, 11 bytes

```
PhceCSMCQ\#

```

A program that takes input of a list of strings on STDIN and prints a string.

Try it online

**How it works**

```
PhceCSMCQ\#  Program. Input: Q
       CQ    Transpose Q
     SM      Sort each element of that lexicographically
    C        Transpose that
   e         Yield the last element of that, giving the program ending with ' #' and some
             parts of the comments
  c      \#  Split that on the character '#'
 h           Yield the first element of that, giving the program with a trailing space
P            All but the last element of that, removing the trailing space
             Implicitly print

```

# Answer
> 1 votes
# Perl 6, 39 bytes

```
{[Zmax](@_».comb).join.split(' #')[0]}

```

Translation of the Python solution by Dennis.
Takes input as a list of strings, and returns a string.

(try it online)

# Answer
> 0 votes
# Jelly, 27 bytes

```
żḟ€” ;€” Ḣ€
i€”#’©ḣ@"ç/ḣ®ṪṖ

```

Test it at **TryItOnline**

Uses the strictest spec - the extra space before the comment character is removed at the cost of a byte.

Input is a list of strings.

# Answer
> 0 votes
# TSQL, ~~216~~ 175 bytes

**Golfed:**

```
DECLARE @ varchar(max)=
'hello         #Line one
              #Line two
       world! #Line three'

DECLARE @i INT=1,@j INT=0WHILE @i<LEN(@)SELECT @=stuff(@,@j+1,len(x),x),@j=iif(x=char(10),0,@j+1),@i+=1FROM(SELECT ltrim(substring(@,@i,1))x)x PRINT LEFT(@,patindex('%_#%',@))

```

**Ungolfed:**

```
DECLARE @ varchar(max)=
'hello         #Line one
              #Line two
       world! #Line three'

DECLARE @i INT=1,@j INT=0
WHILE @i<LEN(@)
  SELECT @=stuff(@,@j+1,len(x),x),@j=iif(x=char(10),0,@j+1),@i+=1
  FROM(SELECT ltrim(substring(@,@i,1))x)x
PRINT LEFT(@,patindex('%_#%',@))

```

**Fiddle**

# Answer
> 0 votes
# Dyalog APL, 22 bytes

Inspiration.

```
(⎕UCS¯2↓⍳∘35↑⊢)⌈⌿∘⎕UCS

```

`(`

`⎕UCS` character representation of

`¯2↓` all but the last two of

`⍳∘35↑` up until the position of the first 35 ("#"), in that which is outside the parenthesis, taken from

that which is outside the parenthesis

`)` namely...

`⌈⌿` the columnar maximums

of

`⎕UCS` the Unicode values

TryAPL online!

# Answer
> 0 votes
## Ruby, 77 bytes

```
puts File.readlines("stack.txt").join('').gsub(/\s{1}#.*\n/,'').gsub(/\s/,'')

```

---
Tags: code-golf, string, parsing, comment
---


title: The ten hundred most common words

text:
# Question
Title: The ten hundred most common words
This question is written because "Thing Explainer" is fun to read, and gave me an idea.

Write "stuff that makes computer do things" that reads/takes a set of letters, numbers and things like this `"#%|?` and returns `True / 1` if all words are part of this set.

If all words are not part of that set, return the words that were not a part of it.

---

**This website can be considered correct in all cases.** The rules are written to follow the specs on that site.

---

# Examples:

**Truthy**:

*The code should return a truthy value if the entire text above the first horizontal line is pasted as input.*

The following lines should return a truthy value (input is separated by `###`)

```
This returns "Hello, World!"
###
tHiS rEtUrNs TrUe...
###
Thing Explainer is a book written by a man.
The man writes books with simple words.
###
This set of stuff "#!^{>7( must return true

```

**Falsey**:

In the following examples, input and output are separated by `***`. Different test cases are separated by `###`.

```
This code doesn't return "Hello, World!"
***
code
###
tHiS rEtUrN"s false...
***
s
false

```

**More detailed rules:**

* You can use this to test your code.
* Non-letters are interpreted as spaces by the code, except for words like `'wasn't'`. The words with apostrophes that returns `true` are included in the list
    + For instance: `foo123bar` should return `foo` and `bar`, since they are not part of the list, and `123` can be interpreted as spaces
* The input will only contain printable ASCII code points \[10, 32-126\].
* Words can contain mixed case letters. See second test case.
* The list of words
    + should be taken as input (STDIN, function argument or equivalent)
    + can be modified (words can be separated by newline, comma etc., and you might sort the list)
    + Note that you can not use this list (it's not identical)
* The output can be on any format you like
* The output can be upper, lower or mixed case (optional)
* There shall be no symbols in the output

---

For the record, Jonathan Allan found a strange corner case: the implementation on XKCD will actually ignore any letters after an apostrophe up to the next non-\[A-Z\]\[a-z\]\['\] - for example `find's found`, and `find'qazxswedc found'` both return nothing, whereas `find'qazx.swedc found` returns `swedc`.

You can choose if you want to return nothing for `find'qazxswedc found'`, or return `qazxswedc`. Returning `qazx, swedc` for `find'qazx.swedc` is also OK.

# Answer
> 2 votes
## PowerShell v3+, ~~105~~ 92 bytes

```
param($a,$b)$x=@();-split($b-replace"[^a-zA-Z']",' ')|%{if($_-notin$a){$x+=$_}};($x,1)[!$x]

```

Takes simple words like `$a`, and words like `$b`. Makes helper `$x`. Take each word in `$b` and get rid of any bad not letters, then check each one `|{...}`. If that word is not in `$a`, then we add it to `$x`. At the end, we choose `$x` or `1` by not `$x`. That is sent out, either `words` or `1`.

### Some words to try

```
PS C:\Tools\Scripts\golfing> ('This returns "Hello, World!"','tHiS rEtUrNs TrUe...','Thing Explainer is a book written by a man.
The man writes books with simple words.','This set of stuff "¤!^¤>7\ must return true'|%{"$_";(.\ten-hundred-most-common-words.ps1 (gc .\ten-hundred-most-common-words.txt) $_)})-join"`n###`n"
This returns "Hello, World!"
###
1
###
tHiS rEtUrNs TrUe...
###
1
###
Thing Explainer is a book written by a man.
The man writes books with simple words.
###
1
###
This set of stuff "¤!^¤>7\ must return true
###
1

PS C:\Tools\Scripts\golfing> ("This code doesn't returns Hello, World!",'tHiS rEtUrN"s false...'|%{"$_`n***`n"+(.\ten-hundred-most-common-words.ps1 (gc .\ten-hundred-most-common-words.txt) $_)})-join"`n###`n"
This code doesn't returns Hello, World!
***
code
###
tHiS rEtUrN"s false...
***
s false

```

# Answer
> 2 votes
# Python, 93 bytes

```
import re
lambda w,s:[w for w in re.sub("[^'\w]|\d|_",' ',w).split()if w.lower()not in s]or 1

```

All test cases are at **ideone**

Preprocessing of the list is to split on `|` and put it in a `set` (which I imagine is fine if pre-sorting is allowed). Input words as `w` and the set as `s`.

If that's not allowed this becomes 98 bytes with `not in s` becoming `not in set(s)`.

We could preprocess it to have all permutations of upper and lower case characters too and save 8 bytes, but I think that might be going too far (that would be a huge set).

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


title: Validate a stem-and-leaf plot

text:
# Question
Title: Validate a stem-and-leaf plot
A stem and leaf plot displays a bunch of numerical values in groups, which are determined by all but the last digit. For example, suppose we have this set of data:

```
0, 2, 12, 13, 13, 15, 16, 20, 29, 43, 49, 101

```

We could produce this stem and leaf plot:

```
0|02
1|23356
2|09
3|
4|39
5|
6|
7|
8|
9|
10|1

```

The first row's stem is 0, so its "leaves" - the digits after the `|` \- represent the values between 0 inclusive and 10 exclusive. The leaves on each stem are sorted. Stems with no leaves (like 3) still appear in the plot. The value of 101 is between 100 inclusive and 110 exclusive, so its stem is 10 (100 divided by 10).

**Your challenge** is to check whether a piece of text is a valid stem and leaf plot. A valid plot satisfies these rules:

* Has exactly one row for every stem (i.e. 10-wide group) in the range of the data (including stems in the middle of the range with no leaves)
* Has no stems outside the range
* All leaves are sorted ascending to the right
* All stems are sorted ascending down
* Has only numeric characters (besides the separator `|`)

You do not have to deal with numbers that have fractional parts. You may approve or reject extra leading zeros in the stems, but a blank stem is not allowed. There will be at least one value. You may only assume extra spaces after the leaves on each row. You may assume a leading and/or trailing newline. All characters will be printable ASCII.

Your function or program should return or output (to screen or the standard output) a truthy value for a valid plot, or a falsy value for an invalid plot. You may take input from the standard input, from a file, as one big string, as an array of strings - whatever is most convenient.

Here are some **test cases** that are valid plots (separated by blank lines):

```
2|00003457
3|35
4|799
5|3

99|3
100|0556
101|
102|
103|8

0|0

```

Here are some **test cases** that are invalid plots, with commentary to the right:

```
|0               Blank stem

5|347            Missing a stem (6) in the range
7|9

4|               Has a stem (4) outside the range
5|26
6|7

11|432           Leaves aren't sorted correctly
12|9989

5|357            Stems aren't sorted correctly
4|002
6|1

4|5              Duplicate stem
4|6
4|6
5|1

51114            No stem and leaf separator
609

1|2|03           Multiple separators
2|779|

4|8abcdefg9      Invalid characters
5|1,2,3

75 | 4 6         Invalid characters (spaces)
76 | 2 8 8 9

```

This is code golf, so the shortest code wins! Standard loopholes are disallowed.

# Answer
> 4 votes
# Perl, 47 bytes

Includes +2 for `-0p`

Give input on STDIN

`stem.pl`:

```
#!/usr/bin/perl -0p
$"="*";$_=/^((??{$_+$n++})\|@{[0..9,"
"]})+$/

```

# Answer
> 2 votes
## Pip, ~~60~~ 58 + 1 = 59 bytes

First stab at the problem, probably could use more golfing. Uses the `-r` flag to read lines of input from stdin. Truthy output is `1`, falsy output is `0` or empty string.

```
g=a+,#g&a@vNE'|NEg@v@v&$&{Y(a^'|1)a@`^\d+\|\d*$`&SNy=^y}Mg

```

Explanation and test suite pending, but in the meantime: Try it online!

# Answer
> 1 votes
# JavaScript, 189 bytes

```
(x,y=x.split`
`.map(a=>a.split`|`),z=y.map(a=>a[0]))=>!(/[^0-9|\n]|^\|/m.exec(x)||/^\d+\|\n|\|$/.exec(x)||y.some((c,i,a)=>c.length!=2||c[1]!=[...c[1]].sort().join``)||z!=z.sort((a,b)=>a-b))

```

Same length alternate solution:

```
(x,y=x.split`
`.map(a=>a.split`|`),z=y.map(a=>a[0]))=>!(/[^0-9|\n]|^\||^.*\|.*\|.*$/m.exec(x)||/^\d+\|\n|\|$/.exec(x)||y.some((c,i,a)=>c[1]!=[...c[1]].sort().join``)||z!=z.sort((a,b)=>a-b))

```

Defines an anonymous function that takes input as a multiline string.

I'm sure there's more to golf, so let me know if you see any possible improvements.

### Explanation:

The function checks for a number of bad things, and if any of those are true, it returns false (using logical ORs and a NOT)

```
(x,y=x.split("\n").map(a=>a.split`|`),          //y is input in pairs of stem and leaves
z=y.map(a=>a[0]))                               //z is stems
=>                                              //defines function
!(                                              //logical not
/[^0-9|\n]|^\|/m.exec(x)                        //checks for invalid chars and blank stems
||/^\d+\|\n|\|$/.exec(x)                        //checks for stems out of range
||y.some((c,i,a)=>c.length!=2                   //checks for multiple |s in a line
||c[1]!=[...c[1]].sort().join``))               //checks if leaves are in wrong order
||z!=z.sort((a,b)=>a-b))                        //checks for stems in wrong order

```

In the alternate solution, checking for multiple `|`s in a line is done as part of the first regex instead.

# Answer
> 1 votes
## Batch, 409 bytes

```
echo off
set/pp=||exit/b1
set t=
set i=%p:|=&set t=%
if "%t%"=="" exit/b1
for /f "delims=0123456789" %%s in ("%i%")do exit/b1
:l
set t=-
set s=%p:|=&set t=%
if "%s%"=="" exit/b1
if not "%s%"=="%i%" exit/b1
set/ai+=1
for /f "delims=0123456789" %%s in ("%t%")do exit/b1
:m
if "%t:~1,1%"=="" goto n
if %t:~0,1% gtr %t:~1,1% exit/b1
set t=%t:~1%
goto m
:n
set/pp=&&goto l
if "%t%"=="" exit/b1

```

Takes input on STDIN, but exits as soon as it sees an error.

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


title: Source code GO!

text:
# Question
Title: Source code GO!
Let's use augmented reality to hunt small creatures hidden in source-code. Write a quine program that outputs its own code source, except for 5 consecutive characters that will be modified and that will display a *PCG-mon* : `(^_^)`

The 5 consecutive characters can be positioned anywhere in the source code (from position `0` to `n-5`, `n` being the source code length). The source code must have a minimum length of 5 characters. The string `(^_^)` or any of its substring of length \>=2 must not appear in initial source code, only in output.

Example of valid submission:

* source code `my source code`, output `my (^_^)e code`

Invalid:

* source code `(^_^) copy;`, output `(^_^) (^_^)`

## Winning criteria

The shortest code in bytes wins.

# Answer
# Javascript ES6, 44 bytes

```
$=_=>`$=(\^\_\^\)${($+'').slice(5)};$()`;$()

```

Output:

```
$=(^_^)=(\^\_\^\)${($+'').slice(5)};$()`;$()

```

Still working on golfing, but it works for now.
> 13 votes

# Answer
# Vim, ~~33~~, 27 keystrokes

```
qqqqqS(<C-v>94_<C-v>94)q@q<esc>hh"qPq@q

```

Note that `<C-v>` means ctrl+v, and is byte `0x16` and `<esc>` is the escape character, and is byte `0x1B`.

This just uses a slightly modified version of my Golf you a quine for great good! answer.

Outputs:

```
(^_^)S(^V94_^V94)q@q^[hh"qPq@q

```

This is valid since `^V` is the way vim represents `<C-v>` and `^[` is the way vim represents `<esc>`.

The basic idea, is just to input the text `(^_^)` by its code points so we can avoid putting those characters in the source code. In insert mode, `<C-v>number` will insert the ASCII character of "number". However, since the challenge says:

> The string `(^_^)` or any of its substring of length \>=2 must not appear in initial source code, only in output.

This answer abuses the "substring" rule by only entering the codepoints of the `^` characters, and entering `(`, `_`, and `)` directly.

Here's a gif that lets you see this solution in action, and puts the source code and output side by side for comparison:
> 10 votes

# Answer
## CJam, ~~13~~ 11 bytes

```
"(_)"
_p'^*

```

Online interpreter *(-2 bytes thanks to @MartinEnder)*.

```
"(_)"             Push string
      _p          Duplicate and print repr with newline
        '^*       Join string with '^'

```
> 7 votes

# Answer
## CJAM, 16 15 bytes

Try it here.

```
{"^(_)"(*}_~sss

```
> 3 votes

# Answer
# Python, ~~115~~ ~~111~~ 107 bytes

```
def f():s='def f():s=%r;print s%%s.replace(s[:5],"^".join("(_)"))';print s%s.replace(s[:5],"^".join("(_)"))

```

Call `f()` and the output is:

```
def f():s='(^_^)():s=%r;print s%%s.replace(s[:5],"^".join("(_)"))';print s%s.replace(s[:5],"^".join("(_)"))

```

Inspired in part by this answer to a similar question.
> 3 votes

# Answer
# JavaScript (ES6), 91 bytes

There's already a JavaScript answer, but there's not a non-source-reading JS answer:

```
a="a=%s;co%s.log(a,uneval(a),`(${'^'}_${'^'})`)";console.log(a,uneval(a),`(${'^'}_${'^'})`)

```

This is based on my non-source-reading answer to Golf you a quine for great good!. Outputs

```
a="a=%s;co%s.log(a,uneval(a),`(${'^'}_${'^'})`)";co(^_^).log(a,uneval(a),`(${'^'}_${'^'})`)

```

This can easily be modified by moving around the second `%s` in the string. For example,

```
a="a=%s;console.log(a,uneval(a),`($%s_${'^'})`)";console.log(a,uneval(a),`(${'^'}_${'^'})`)

```

outputs

```
a="a=%s;console.log(a,uneval(a),`($%s_${'^'})`)";console.log(a,uneval(a),`($(^_^)_${'^'})`)

```
> 3 votes

# Answer
# Go (golang), 131 bytes

This challenge must have an answer in Go!

```
package main;import"fmt";func main(){a:="package main;import\"fmt\";func(%c_%[1]c)(){a:=%q;fmt.Printf(a,94,a)}";fmt.Printf(a,94,a)}

```

Try it online!
> 3 votes

# Answer
# Jelly, 22 bytes

```
“4094959441b³ỌØV”ṘVabc

```

Available at **TryItOnline**

Uses the built-in payload capable quine `“ØV”ṘV`
The `abc` on the end is just filler to be replaced
converts the integer into base 100, resulting in `[40,94,95,94,41]`
casts to characters, resulting in `(^_^)`
So the whole result is `“4094959441b³ỌØV”(^_^)`
> 2 votes

# Answer
# C# 5.0, 715 bytes

I know, this is huge. Just wanted to add a C# solution.

```
/*^()_*/using System.CodeDom;namespace System{class P{static void Main(){var b="/*^()_*/using System.CodeDom;namespace System{{class P{{static void Main(){{var b={0};var f=new string(new[]{{b[3],b[2],b[5],b[2],b[4]}});var w=new IO.StringWriter();CodeDom.Compiler.CodeDomProvider.CreateProvider(\"CSharp\").GenerateCodeFromExpression(new CodePrimitiveExpression(b),w,null);Console.WriteLine(b.Replace(\"[4]}}}}}}}}\",f),w);Console.ReadKey();}}}}}}";var f=new string(new[]{b[3],b[2],b[5],b[2],b[4]});var w=new IO.StringWriter();CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp").GenerateCodeFromExpression(new CodePrimitiveExpression(b),w,null);Console.WriteLine(b.Replace("[4]}}}}",f),w);Console.ReadKey();}}}

```

The output is:

```
/*^()_*/using System.CodeDom;namespace System{class P{static void Main(){var b="/*^()_*/using System.CodeDom;namespace System{{class P{{static void Main(){{var b={0};var f=new string(new[]{{b[3],b[2],b[5],b[2],b[4]}});var w=new IO.StringWriter();CodeDom.Compiler.CodeDomProvider.CreateProvider(\"CSharp\").GenerateCodeFromExpression(new CodePrimitiveExpression(b),w,null);Console.WriteLine(b.Replace(\"[4]}}}}}}}}\",f),w);Console.ReadKey();}}}}}}";var f=new string(new[]{b[3],b[2],b[5],b[2],b[4]});var w=new IO.StringWriter();CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp").GenerateCodeFromExpression(new CodePrimitiveExpression(b),w,null);Console.WriteLine(b.Replace("(^_^)}}",f),w);Console.ReadKey();}}}

```

Available at Ideone.com
> 2 votes

# Answer
# Bash, 178 bytes

```
Q='#(8_8)
printf "Q=\47"
echo -n "$Q"|sed -r "s~(_|\()8~\1^~g"
echo -e "\x27"
tail<<<"$Q" -n4'
printf "Q=\47"
echo -n "$Q"|sed -r "s~(_|\()8~\1^~g"
echo -e "\x27"
tail<<<"$Q" -n4

```

Pfff, I am not good at quines :/ Any suggestion to golf it more is more than welcome! :-)
> 1 votes

# Answer
# MATL, 14 bytes

```
')_`_*i't&Dwqh

```

Produces the output `')_`_*i'(^_^)h`.

Try it online!

### Explanation

```
')_`_*i'  % Push this string
t&D       % Duplicate and get string representation (i.e. enclose with quotes)
w         % Swap
q         % Subtract 1. Transforms ')_`_*i' into the code points of '(^_^)h'
h         % Concatenate. Automatically casts code points to chars. Implicitly display

```
> 1 votes

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


title: Flexagonal flexagation

text:
# Question
Title: Flexagonal flexagation
Being programmers, watching us flex aren't very interesting. Today we change that! In this challenge you will lex and flex hexaflexagons.

# About

For a video introduction, watch viharts video(s) on flexagons

A flexagon is a shape that you can flex to reveal faces other than the top and bottom one; we are making a hexahexaflexagon, which has 6 faces. See the image below on how to fold a hexahexaflexagon out of a strip of paper.

`A` shows both sides of the strip. The two white triangles are glued together. This is how you would flex it:

Below is a diagram of possible states and their relationships:

The colored circles represent the 6 triangles with the same number from the first image. Each of the circes have two colors- the bottom most represent the back face (what you would see if you where to flip your flexagon around), which you don't have to consider in this challenge.
The gray circles in the background represent how you can flex your flexagon in any given state: there are 4 different ways to flex it, we call these `Left`, `Right`, `Up` and `Down`. You don't actually flex in these directions, the important bit is that some are opposite to each other.
If you are in the center you can use `Left` and `Right` to go to the other center ones. To get out of the center you use `Up` and `Down`. If you aren't in the center you cannot use `Left` or `Right`.

```
Left/Down = clockwise
Right/Up  = anti-clockwise

```

# Challenge

Create a function or program that take as input what should be on the 18 front faces and the 18 back faces of a flexagon, a sequence of left, right, up and down flexes, and return the 8 visible faces after the flexes.

Elaborate example computation:

```
flex "hexaflexaperplexia"
     "flexagationdevices"
     [Right, Right, Left]

Divide a strip of paper into 18 triangles:
1/2\3/1\2/3\1/2\3/1\2/3\1/2\3/1\2/3   Front
4/4\5/5\6/6\4/4\5/5\6/6\4/4\5/5\6/6   Back

Write "hexaflexaperplexia" on the front of the paper strip:
1/2\3/1\2/3\1/2\3/1\2/3\1/2\3/1\2/3

hexaflexaperplexia
123123123123123123
h  a  e  p  p  x     Face 1, Initially the front face
 e  f  x  e  l  i    Face 2, Initially the back face
  x  l  a  r  e  a   Face 3, Initially hidden

Write "flexagationdevices" on the back of the paperstrip:
4/4\5/5\6/6\4/4\5/5\6/6\4/4\5/5\6/6

flexagationdevices
445566445566445566
fl    at    ev       Face 4, up from 3
  ex    io    ic     Face 5, up from 2
    ag    nd    es   Face 6, up from 1

Flex it [Right, Right, Left]
  The initial visible face is 1: "haeppx"
  flexing Right ..
  The current visible face is 2: "efxeli"
  flexing Right ..
  The current visible face is 3: "xlarea"
  flexing Left ..
  The current visible face is 2: "efxeli"
  flexed [Right, Right, Left]!

outputting "efxeli"

```

Example implementation: http://jdoodle.com/a/18A

# Input and expected output:

```
> hexaflexaperplexia flexagationdevices RRL
= efxeli

> loremipsumdolorsit hexaflexamexicania RUU
= riuort

> abcdefghijklmnopqr stuvwxyz1234567890 UL
= I can't flex that way :(

> abcdefghijklmnopqr stuvwxyz1234567890 RRRRLLUDDUUUULDD
= uv1278

```

# Rules

* You may take input and return output in any reasonable way
* If the input is impossible, you should indicate so in some way that is distinct from regular output
* Standard loopholes apply
* This is `Codegolf`. Shortest code in bytes win.

# Answer
> 2 votes
# Haskell (Lambdabot), ~~270~~ 234 bytes

```
(!)=((map(snd<$>).groupBy((.fst).(==).fst).sortOn fst).).zip.cycle
o n(a,b)|n>1||b<1=(mod(a+[-1,1,0,0]!!n)3,mod(b+[0,0,-1,1]!!n)3)
(x&y)d|(g,h)<-foldl(flip(.))id(o<$>d)(0,0)=([0,1,2]!x++[3,3,4,4,5,5]!y)!!([0,5,1,1,4,2,2,3,0]!!(3*g+h))

```

Usage:

```
> (&) "hexaflexaperplexia" "flexagationdevices" [1,3]
"exioic"

```

\[0,1,2,3\] = \[left,right,up,down\]
Thanks to @Damien for a lot of bytes!

---
Tags: code-golf, math, geometry, data-structures, repeated-transformation
---


title: Create a T9 keyboard

text:
# Question
Title: Create a T9 keyboard
This question asks for a T9 dictionary matching functionality which is a very interesting problem. But T9 has another way of typing and that is typing character-by-character. You would NOT need a dictionary to implement this keyboard.

Here is key-map of a T9 keyboard if you forgot:

```
+-------+-------+-------+
|   1   |   2   |   3   |
|  .?!  |  ABC  |  DEF  |
+-------+-------+-------+
|   4   |   5   |   6   |
|  GHI  |  JKL  |  MNO  |
+-------+-------+-------+
|   7   |   8   |   9   |
| PQRS  |  TUV  |  WXYZ |
+-------+-------+-------+
|   *   |   0   |   #   |
|   ←   | SPACE |   →   |
+-------+-------+-------+

```

### How T9 works

To type a character with T9, you need to press number key representing that character `n` times. `n` is order of that character written on that key. Numbers are the last character you can type for each key. For example, to type `B` I press `2` two times, or to type `5` I press `5` four times. To finish typing this character I press `#`. `*` is simply backspace. In our version of keyboard there is no capitalization.

### Input and output examples:

```
8#99999#055#33#999#22#666#2#777#3# → T9 KEYBOARD

```

Explanation:

* `8` selects `T` and `#` moves to next character
* `99999` select last character of **`9`** key which is `9` and `#` moves to next charachter
* `0` inserts a space
* `33` selects second character of **`3`** key which is `K` and `#` moves to next character
* And so on...

### Rules

Your function or program should accept a string representing T9 keypresses. Output is the resulting text from those keypresses, as outlined above.

This is basic code golf, so the winner is shortest in bytes, and standard rules/loopholes apply.

# Answer
# CJam, ~~109~~ 94 bytes (2nd bonus)

A very naive and long solution

```
q'#/);{__'*-:A-,_g{){;}*A_}*;'0/{_,g{)~".?~1"a'[,65>292994 5b{/(X):X+\s}%+1:Xm>=\,=}*}%S*1/~}%

```

This is a full program, although a function will be of the same length.

The input goes into STDIN

Example:

```
8#99999#055#33#999#***22#666#2#777#3#

```

Output:

```
T9 BOARD

```

Try it online here
> 5 votes

# Answer
# JavaScript ES6, ~~220-10=210~~ 178 bytes

As a part of Helka's CMC, I've outgolfed my first challenge.

```
n=>(g=n=>n==(k=n.replace(/.\*/,""))?n:g(k))(n.match(/(\d)\1*|\*/g).map(e=>e<"0"?e:(a=" |.?!|ABC|DEF|GHI|JKL|MNO|PQRS|TUV|WXYZ".split`|`[+e[0]]+e[0])[~-e.length%a.length]).join``)

```

Sample outputs:

```
> f=n=>(g=n=>n==(k=n.replace(/.\*/,""))?n:g(k))(n.match(/(\d)\1*|\*/g).map(e=>e<"0"?e:(a=" |.?!|ABC|DEF|GHI|JKL|MNO|PQRS|TUV|WXYZ".split`|`[+e[0]]+e[0])[~-e.length%a.length]).join``)
[Function]
> f("8#99999#055#33#999#***22#666#2#777#3#")
'T9 BOARD'
> f("8#44#33#0#999#*77#88#444#222#55#0#22#777#666#9#66#0#333#666#99#0#5#88#6#7#7777#0#666#888#33#777#0#8#44#33#0#555#2#99#*9999#999#0#3#666#4#111#")
'THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG!'
> f("8#99999#055#33#999#***22#666#2#777#3#")
'T9 BOARD'

```

## Explanation

```
(g=n=>n==(k=n.replace(/.\*/,""))?n:g(k))

```

This implements recursive replacement, replacing all characters followed by `*` until there are no `*`s left.

```
n.match(/(\d)\1*|\*/g)

```

This matches all runs of consecutive digits, or `*`s.

```
a=" |.?!|ABC|DEF|GHI|JKL|MNO|PQRS|TUV|WXYZ".split`|`[+e[0]]+e[0]

```

This creates the desired dictionary, obtaining the encoded part from the large string, then appending the desired digit to it.

```
a[~-e.length%a.length]

```

This gets the character, modulo `a`'s length.

```
.join``

```

This prepares the string for processing and removal of `*`s.
> 3 votes

# Answer
## AWK 211 bytes (with the bonuses)

```
{split(".?!1-ABC2-DEF3-GHI4-JKL5-MNO6-PQRS7-TUV8-WXYZ9- 0",k,"-");split($0"#",a,"");while(1+(b=a[++i])){if(b==p)++c;else{for(g in k)if(p==substr(k[g],l=length(k[g])))printf(substr(k[g],1+((c-1)%l),1));c=1;p=b}}}

```

This is a full program which read the input from stdin. It would be more efficient to not resplit the keyboard for each line, but it would make the script longer.

Also if the "0" key was anything else than 0, the script would be 4 bytes shorter, but that's part of the game :o)
> 1 votes

# Answer
# ~~Python, ~~167~~ ~~157~~ 151 bytes~~

(doesn't support '\*')

Nothing special. I use regex to convert the input to a list, then i loop the entries. I use the first character and length of each entry to search it in a lookup list:

```
def f(i):
  import re
  t9 = [" 0",".?!1","ABC2","DEF3","GHI4","JKL5","MNO6","PQRS7","TUV9","WXYZ9"]
  i = re.findall(r'[1-9]+|0+',i)
  answer = []
  for j in i:
    answer = answer + [t9[int(j[0])][len(j)-1]]
  return ''.join(answer)

```

After some golfing it looks like this:

```
import re;m=lambda i:"".join([" 0,.?!1,ABC2,DEF3,GHI4,JKL5,MNO6,PQRS7,TUV9,WXYZ9".split(",")[int(j[0])][len(j)-1] for j in re.findall(r'[1-9]+|0+',i)])

```

No bonuses (yet). I don't know how I would implement the first bonus in regex. The second bonus would add a lot of bytes as the lookup elements are not the same size. Don't really understand the third bonus.
> 1 votes

# Answer
# Perl 5: 106 (104 code + 2 flags)

Modified to handle deletes.

```
#!perl -lp
s/((\d)\2*)#?|./chr$2*5+length$1/ge;y//d 0-3.?!1 ABC2 DEF3 GHI4 JKL5 MNO6 P-S7TUV8 W-Z9/c;1while s/.?d//

```

Usage:

```
perl t9.pl <<<'8#99999#055#33#999#22#666#2#777#3#'
perl t9.pl <<<'899999055339992266627773'

```

# Perl 5: 88 (86 code + 2 flags)

Old version without star-delete.

```
#!perl -lp
s/(\d)(\1*)#?/chr$1*5+length$2/ge;y// 0-3.?!1 ABC2 DEF3 GHI4 JKL5 MNO6 P-S7TUV8 W-Z9/c

```
> 1 votes

# Answer
# Ruby 254, 248, 229 bytes

Golfed:

```
n=->(t){r,m,b=[]," _.?!1_ABC2_DEF3_GHI4_JKL5_MNO6_PQRS7_TUV8_WXYZ9_*_0_#".split("_"),nil;t.scan(/((.)\2*)/){|l,_|(!(l=~/\#/)?(l=~/\*/?(r.pop l.size):(l=="00"?r<<(b ? "0 ":" 0"):(c=m[l[0].to_i];r<<c[l.size%c.size-1]))):b=l)};r*""}

```

Ungolfed:

```
def t9totext(t)
  bonq = nil
  numpad = [" ",".?!1","ABC2","DEF3","GHI4","JKL5","MNO6","PQRS7","TUV8","WXYZ9","*","0","#"]

  r = []
  t.scan(/((.)\2*)/) do |l, _|
    if !(l =~ /\#/)
      if l =~ /\*/
        r.pop(l.size)
      elsif l == "00"
        r << (bonq ? "0 " : " 0")
      else
        c = numpad[l[0].to_i]
        r << c[l.size % c.size - 1]
      end
    else
      bonq = l
    end
  end
  r.join
end

```

All these specs should succeed:

```
  it "outputs the correct word" do
    expect(n.call('8#99999#055#33#999#22#666#2#777#3#1')).to eq("T9 KEYBOARD.")
    expect(n.call('4433555#55566609666666677755533*3111')).to eq("HELLO WORLD!")
    expect(n.call('7##222#222**7#222#4')).to eq('PPCG')
    expect(n.call('00#0#00')).to eq(' 0 0 ')
  end

```

The `0 0` answer looks a bit like a hacky solution. Will look into it when I've got the time.
> 1 votes

# Answer
# C (245 bytes)

```
#define M "8#44#33#0#999#*77#88#444#222#55#0#22#777#666#9#66#0#333#666#99#0#5#88#6#7#7777#0#666#888#33#777#0#8#44#33#0#555#2#99#*9999#999#0#3#666#4#111#"

#include<stdio.h>
char K[][4]={" ",".?!","ABC","DEF","GHI","JKL","MNO","PQRS","TUV","WXYZ"},I[]=M;int
i,j,k,r;main(){for(;I[i];++i){if(I[i]=='#')I[j++]=K[k][--r],r=k=0;else
if(I[i]=='*')j?--j:0;else if(!r++)k=I[i]-'0';}I[j]=0;printf("%s\n",I);}

```

## Output

```
THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG!

```

## Explanation

The byte count does not include the input string given in the first `#define`.

I use a two-dimensional array as the lookup table for what character to print. The program reads in characters delimited by `'#'`.

For each group, the input number determines the first-dimension array index, and the number of repetitions of the input number determines the second-dimension array index. The `'*'` moves back the index of the array for the output string so as to overwrite the previous letter.

So the input string `44#` (1 repetition of `'4'`) is translated to lookup table `K[4][1]`, which is the character `H`.

---

## Ungolfed Version

```
#define INPUT "8#44#33#0#999#*77#88#444#222#55#0#22#777#666#9#66#0#333#666#99#0#5#88#6#7#7777#0#666#888#33#777#0#8#44#33#0#555#2#99#*9999#999#0#3#666#4#"

#include<stdio.h>

static const char keyboard[10][4] = {" ", ".?!", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"};

int main(void)
{
  char input[] = INPUT;
  char output[256];
  int i, j;
  int key = 0;
  int reps = 0;

  for (i = j = 0; input[i] != '\0'; ++i) {
    switch (input[i]) {
    case '#':
      output[j] = keyboard[key][reps - 1];
      ++j;
      reps = key = 0;
      break;
    case '*':
      if (j > 0) --j;
      break;
    default:
      if (reps == 0)  {
        key = (int)input[i] - '0';
      }
      ++reps;
      break;
    }
  }

  output[j] = '\0';
  printf("%s\n", output);

  return(0);
}

```
> 1 votes

# Answer
# PHP, 183-10=173 bytes

All versions take input from command line argument; call with `php -r '<code>' <string>`.

*Note*: All versions throw a warning if input starts with `*`.
Prepend `$o=[];` to the code to remove that flaw.

```
preg_match_all("%(\d)\1*|\*%",$argv[1],$m);foreach($m[0]as$w)if("*"==$w)array_pop($o);else$o[]="- 0   .?!1 ABC2 DEF3 GHI4 JKL5 MNO6 PQRS7TUV8 WXYZ9"[$w[0]*5+strlen($w)];echo join($o);

```
* does not need hash tags
* fails if a key is pressed too often

**210-10-??=??? bytes**

```
$a=[" 0",".?!1",ABC2,DEF3,GHI4,JKL5,MNO6,PQRS7,TUV8,WXYZ9];preg_match_all("%(\d)\1*|\*%",$argv[1],$m);foreach($m[0]as$w)if("*"==$w)array_pop($o);else$o[]=$a[$w[0]][strlen($w)%strlen($a[$w[0]])-1];echo join($o);

```
* does not need hash tags
* rotates if a key is pressed too often

**181 bytes, no bonus**

```
preg_match_all("%\d+#|\*%",$argv[1],$m);foreach($m[0]as$w)if("*"==$w)array_pop($o);else$o[]=" 0   .?!1 ABC2 DEF3 GHI4 JKL5 MNO6 PQRS7TUV8 WXYZ9"[$w[0]*5+strlen($w)-2];echo join($o);

```

---

**breakdown**

The "no hash tags" versions split the string to (streak of equal numbers) and (asterisk) and forget everything else. The no-bonus version takes (streak of numbers followed by `#`) and (asterisk).

Then loop through the matches: If a '\*' is found, remove the last element of the result array.

The difference between the versions is in the `else` part:

* no bonus version: offset map string to (key\*5), then add (keystrokes=word length-1)-1, add character from that position to result.
* simple no-tag version: almost the same, but: (keystrokes=word length); added a character to the map string to get rid of the other `-1`.
* rotating version: take item (key) from map array, add character (keystrokes%item length-1) from that item to result.
> 0 votes

# Answer
# JavaScript, 147 bytes

Conor´s answer fixed with the regex from my PHP answer and golfed down.

```
t=i=>i.match(/(\d)\1*|\*/g).map(w=>(" 0~.?!1~ABC2~DEF3~GHI4~JKL5~MNO6~PQRS7~TUV8~WXYZ9".split`~`[w[0]]||"*")[w.length-1]).join``.replace(/.\*/g,"")

```

**breakdown**

```
t=i=>i
    .match(/(\d)\1*|\*/g)   // split input to streaks of equal numbers and single `*`
    .map(w=>                // replace each item with ...
                            // .. take string depending on the digit
        (" 0~.?!1~ABC2~DEF3~GHI4~JKL5~MNO6~PQRS7~TUV8~WXYZ9".split`~`[w[0]]
        ||"*")              // .. ("*" for not a digit)
        [w.length-1]        // -> the (item length)th character of that string
    )
    .join``                 // join without delimiter
    .replace(/.\*/g,"")     // and recursively remove every (letter,asterisk) combination

```

**rotating version, 158 bytes**

added `s=` to remember the string and `%s.length` to rotate.

```
t=i=>i.match(/(\d)\1*|\*/g).map(w=>(s=" 0~.?!1~ABC2~DEF3~GHI4~JKL5~MNO6~PQRS7~TUV8~WXYZ9".split`~`[w[0]]||"*")[w.length%s.length-1]).join``.replace(/.\*/g,"")

```
> 0 votes

---
Tags: code-golf, keyboard
---


# Question
Title: How does math work in Anastasiya's world?
# Background:

Standard operation math like basic addition and multiplication in the real world work like these:

```
12 + 123 = 135

```

and

```
12 * 123 = 1476

```

*That's not interesting and boring!* Many schools are already interpreting this as practice, practice, practice of formal algorithms. That implies a pretty rigid and boring mathematical diet and is not what is intended in this challenge. Get ready to play some fun on our beloved site.

Consider the process of adding two positive integer numbers, then adding again all the digits of its result. Repeating with the addition until only a single digit is obtained. For example:

1. The result of `12 + 123` is 135.
2. Adding all the digits of 135 we obtain `1 + 3 + 5 = 9`.

The number of steps required to obtain a single digit value 9 in this repeated addition is 2.

As with the previous process of the addition, the multiplication of two positive integer numbers follows the same process. Multiply all the digits of its result and then repeating this process until only a single digit remains. Take the above example:

1. The result of `12 * 123` is 1476.
2. Multiply all the digits of 1476 we obtain `1 * 4 * 7 * 6 = 168`.
3. Multiply again all the digits of 168 we obtain `1 * 6 * 8 = 48`.
4. Multiply again all the digits of 48 we obtain `4 * 8 = 32`.
5. Multiply once again all the digits of 32 we obtain `3 * 2 = 6`.

The number of steps required to obtain a single digit value 6 this repeated multiplication is 5.

For this challenge's sake and avoiding any misuse of math notations, I introduce these two dummy notations: `(+)` and `(*)`, **but you may use any notation you like**, which work like the followings:

1. The operation of repeated addition process to obtain a single value is `12 (+) 123 = 9`.
2. The operation of repeated multiplication process to obtain a single value is `12 (*) 123 = 6`.

# Challenge:

The challenge is to write either a program or a function which can perform **both of operations** as explained in the background section: `(+)` and `(*)`.

# Input:

The inputs of the program or the function are two positive integers and one operation either `(+)` and `(*)`. **The format of the input is an arbitrary choice of the programmer**. You may format the input, for example, `a (+) b` or `F(a, (+), b)` or any format you wish.

# Output:

The output of the program or the function must contain the result of operation and the number of steps required with freestyle format as you wish.

Test Cases (ignore the input and output format):

```
    81 (+) 31       -->   (4 ; 2)
    351 (+) 14568   -->   (6 ; 3)
    21 (*) 111      -->   (8 ; 3)
    136 (*) 2356    -->   (0 ; 2)

```

# General rules:

* This is , so the shortest answer in bytes wins the challenge.
Don't let esolangs discourage you from posting an answer with regular languages. Enjoy this challenge by providing an answer as short as possible with your programming language. If you post a clever answer and a clear explanation, your answer will be appreciated (hence the upvotes) regardless of the programming language you use.
* Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/ method with the proper parameters, full programs, etc. The choice is yours.
* If possible, your program can properly handle large numbers. If not, that will just be fine.

---

***Let the game begin!!***

# Answer
# Dyalog APL, ~~33~~ ~~32~~ ~~30~~ 29 bytes

This extends APL to include the prefix notation `+/A n₁ n₂` and `×/A n₁ n₂`. (In fact, you can use any operation to the left of the `/A`.) Returns a list of {result, repetition count}.

```
A←{(⊃,≢)⍺⍺{∪⍵,⍨⍺⍺⍎¨⍕⊃⍵}⍣≡⍺⍺⍵}

```

> `A←{` define a higher-order function in terms of left-hand function `⍺⍺`, and right-hand argument
>
> > `(⊃,≢)` the first element of, followed by the count of
> >
> > `⍺⍺{` the supplied function (`+/` for sum or `×/` for product) fed to the higher-order function
> >
> > > the unique elements of
> > >
> > > `⍵,⍨` the argument appended to
> > >
> > > `⍺⍺` the fed function applied to
> > >
> > > `⍎¨` the evaluation of each character of
> > >
> > > the character representation of
> > >
> > > `⊃⍵` the first element of the argument
> >
> > `}⍣≡` applied repeatedly until the result is identical to the argument, beginning with
> >
> > `⍺⍺⍵` the originally fed function (`+/` or `×/`) applied to the original argument
>
> `}` \[end of higher-order function definition\]

TryAPL online! ( has been emulated with `e` for security reasons.)

Thanks to @ngn for saving a byte.

---

# 0 bytes (in jest)

Dyalog APL actually already has full support for Anastasiyan math; instead of `(+)` and `(×)`, it uses `+{n←0⋄n,⍺⍺{n+←1⋄⍺⍺/⍎¨⍕⍵}⍣=⍵⍺⍺⍨⍺}` and `×{n←0⋄n,⍺⍺{n+←1⋄⍺⍺/⍎¨⍕⍵}⍣=⍵⍺⍺⍨⍺}`.

Try `81 +{(⊃,≢)⍺⍺{∪⍵,⍨⍺⍺e¨⍕⊃⍵}⍣≡⍺⍺/⍺⍵} 31` and `21 ×{n←0⋄n,⍺⍺{n+←1⋄⍺⍺/e¨⍕⍵}⍣=⍵⍺⍺⍨⍺} 111`.
> 12 votes

# Answer
## Haskell, 108 bytes

```
f=map(read.pure).show
g h=(\x->(h.f$last x,length x+1)).takeWhile(>10).iterate(h.f)
(a#b)o=g(foldr1 o)$o a b

```

Defines the function `#` which first takes `a` and `b` and then the operator `o`. Fun fact: this works with any operator (actually, any function) you want!
> 10 votes

# Answer
## Pyke, 16 bytes

```
RE`DltImbRoKr)oh

```

Try it here!

```
RE               - evaluate the input as Pyke code
                 -  (`B` is product and `s` is sum, the second line is a tuple)
  `              - i = str(^)
    ltI      )   - if len(i) != 1:
       mb        -   map(i, int)
         R       -   get the `B` or `s` from input
          oK     -   o++
            r    -   goto_start()
              oh - o++ + 1

```

Takes multiply as `B` and add as `s`. The two numerical inputs are separated by commas.
> 8 votes

# Answer
# JavaScript (ES6), 59

Recursive function, the input format is tailored to simplify the recursive call:

* operator : '+' or '\*'
* operands : array of two values

```
f=(o,v,s=1,t=eval(v.join(o)))=>t>9?f(o,[...t+''],s+1):[t,s]

```

**Test**

```
f=(o,v,s=1,t=eval(v.join(o)))=>t>9?f(o,[...t+''],s+1):[t,s]

;[
  [81,'+',31,     /* -> */ 4, 2]
, [351,'+',14568, /* -> */ 6, 3]
, [21,'*',111,    /* -> */ 8, 3]
, [136,'*',2356,  /* -> */ 0, 2]
].forEach(t=>{
  var [a,o,b,k1,k2] = t,
      [r,s]=f(o,[a,b]);
  console.log(k1==r && k2==s ? 'OK':'KO',a,o,b,'->',r,s)
})

```
> 8 votes

# Answer
# Python 2, 60 bytes

```
f=lambda s,c=0:s[1:]and f(min(s).join(`eval(s)`),c+1)or(s,c)

```

Input is a string like `81+31`, output is a tuple of a singleton string and a counter (e.g., `('4', 2)`.

Test it on Ideone.
> 8 votes

# Answer
# R, ~~175~~ ~~167~~ ~~164~~ ~~140~~ ~~134~~ ~~127~~ ~~126~~ 119 bytes

```
function(G,S,D){i=1;O=switch(S,"+"=sum,prod);x=O(G,D);while(x>9){i=i+1;x=O(strtoi(strsplit(paste(x),"")[[1]]))};c(x,i)}

```

**Ungolfed :**

```
f=function(G,S,D) #The function takes : the left operand, the operation symbol (between quote marks)
                  #and then the right operand
i=1               #That's the counter

O=switch(S,"+"=sum,prod)     #`O` takes the value `sum` if `S` matches `+`, `prod`
                             #(which is the next agument) if not.

x=O(G,D)                     #Does the first operation

while(nchar(x)>1)                 #While the number of character of the result
                                  #of the operation is not of length 1, i.e., an integer :

    i=i+1                                    #Increase the counter
    x=O(strtoi(strsplit(paste(x),"")[[1]]))  #Apply the operation `O` to the first operation and
                                             #the eventual subsequent ones

c(x,i)                                 #Outputs the result and the counter

```

~~`ifelse` is back ! *Yeah !*~~
*Nop*

**Usage :**

```
Special addition
> f(31,"+",81)
[1] 4 2

Special multiplication
> f(136,"*",2356)
[1] 0 2

```

Thanks a lot to **@plannapus** for golfing out *24* bytes !
*-7* bytes thanks to a good idea from **@Vlo** !
> 7 votes

# Answer
## Pyth, 16

```
eJ.uvjhQ`N.vQ)lJ

```

Takes input like `"+ 123 12"` for addition, and `"* 123 12"` for multiplication. Outputs like `result<linefeed>steps`.

Try it here, or run a Test Suite, but note that this relies on eval, so only the addition variant will work in the online interpreter. Multiplication works correctly with the offline interpreter.

This uses the cumulative reduction function to create a list of intermediate results, so for `"+ 351 14568"` we get `[14919, 24, 6]`. This works because single digit numbers are a fixed point of the Anastasiya addition and multiplication. Then we just get the last element of the array as well as the length of the array.

This will work for arbitrarily large numbers, at least until you run out of memory.
> 7 votes

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

```
Dj⁹VµÐĿḊĖṪ

```

Input is a pair of numbers and either `+` or `×`.

Try it online! or verify all test cases.

### How it works

```
Dj⁹VµÐĿḊĖṪ  Main link. Left argument: [x, y] (integers). Right argument: + or ×

    µÐĿ     Repeatedly execute the chain to the left, initially with argument
            [x, y], then with the previous return value. Stop when the results are
            no longer unique, and return the array of all intermediate results.
D           Decimal; convert the integers [x, y] or the return value z to base 10.
 j⁹         Join, separating by the link's right argument, i.e., '+' or '×'.
   V        Evaluate the result. This casts the previous return value to string,
            so, e.g., [8, 1, '+', 3, 1] becomes "81+31" before evaluation.
       Ḋ    Dequeue; discard the first intermediate result, i.e., [x, y].
        Ė   Enumerate; prefix each integer in the array with its 1-based index.
         Ṫ  Tail; extract the last index-value pair.

```
> 7 votes

# Answer
# ARM Machine Code, 48 bytes

Hex dump:

```
b570 2a00 bf0c 1840 4348 2101 230a e00c 3101 0015 fbb0 f6f3 fb06 0413 2a00 bf0c 192d 4365 0030 d1f5 0028 280a d2f0 bd70

```

This function doesn't depend any system calls or library functions. This is Thumb-2 code, which is a variable-length instruction encoding (2 or 4 bytes) for 32-bit ARM. Thus, the maximum value it can process is 2^32-1. 2 bytes could be dropped if it didn't conform to the AAPCS (**46 bytes**), since we wouldn't have to stack registers at the beginning.

Ungolfed assembly (GNU syntax):

```
.syntax unified
.text
.global anastasiya
.thumb_func
anastasiya:
    @Input:
    @r0 - First number
    @r1 - Second number
    @r2 - 0 for add, 1 for multiply
    @Output:
    @r0 - Resultant value
    @r1 - Number of steps
    push {r4,r5,r6,lr}
    cmp r2,#0
    ite eq @if r2==0
    addeq r0,r0,r1 @r0+=r1
    mulne r0,r0,r1 @else r0*=r1
    movs r1,#1 @r1 is the number of steps
    movs r3,#10
    b endloop
    loop:
        adds r1,r1,#1 @Increment number of steps
        movs r5,r2 @r5=1 if multiply, 0 if add
        parseDigits:
            udiv r6,r0,r3 @r6=r0/r3
            mls r4,r6,r3,r0 @r4=r0 - r6*r3
            @Last two operations were r4=r0%r3 (r3==10)
            cmp r2,#0
            ite eq @if r2==0
            addeq r5,r5,r4 @r5+=r4
            mulne r5,r5,r4 @else r5*=r4
            movs r0,r6 @r0=r6 (Set r0 to r0/10)
            bne parseDigits @while (r0!=0)
        @Now our new total is in r5
        movs r0,r5 @Put it in r0
    endloop:
        cmp r0,#10
        bhs loop @while (r0 >=10)
    pop {r4,r5,r6,pc} @Return

```

Testing script in C:

```
#include <stdio.h>
unsigned long long anastasiya(unsigned,unsigned,unsigned);

int main(void) {
    unsigned x,y,op;
    printf("Enter first operand, second operand, and 0 for addition or 1 for multiplication.\n");
    scanf("%u%u%u",&x,&y,&op);
    unsigned long long res = anastasiya(x,y,op);
    printf("Result = %u, steps = %u\n",(unsigned)res ,(unsigned)(res >> 32));
}

```
> 7 votes

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

```
[¼¹iOëP}Dg#S]¾‚

```

**Explanation**

```
[       Dg# ]    # loop until number is single digit
 ¼               # increase counter
  ¹iO            # if operation is addition, sum list
     ëP}         # else take product of list
           S     # split into a list of digits
             ¾‚  # pair final number with counter and output

```

Operator is 1 for addition, 0 for multiplication.

Try it online
> 6 votes

# Answer
# Jelly, 17 bytes

```
+×⁵?µDSP⁵?$ÐĿµL;Ṫ

```

Try it online!

Given arguments like `x y 1`, this computes the Anastasiya sum `x (+) y`.

Given arguments like `x y 0`, this computes the Anastasiya product `x (*) y`.

Output is given as `[number of steps, result]`.
> 4 votes

# Answer
# Octave, 85 bytes ~~MATLAB, 123, 114, 105, 94 bytes~~

Decided to translate this to Octace, to take advantage of the direct indexing, and incrementing capabilitites. Takes the input on the form: `f(a,operator)`, where `a = [number1, number2]`, and `operator==1` gives the product, and `operator==2` gives the sum.

```
function[x,i]=f(a,o)
g={@prod,@sum}{o};x=g(a);i=1;while(x=g(num2str(x)-48))>9;i++;end

```

Explanations:

`g={@prod,@sum}{o}` : Chooses the appropriate function, product or sum and assigns it to `g`

`x=g(a)` takes the sum or product of the inputs

`i=1; ... i++` : Incrementer to count the number of steps

```
while(x=g(num2str(x)-48))>9;
          num2str(x)-48)     % turns a number 123 into an array [1 2 3].
        g(num2str(x)-48))    % Takes the sum or product of the array
      x=g(num2str(x)-48))    % Assign that value to the variable x
      x=g(num2str(x)-48))>9  % Checks if x > 9, continue looping if yes

```

Removed two newlines, a space, and placed both input numbers in a vector instead of separate arguments. This saved 9 bytes, thanks to pajonk! Removed `k=@(x)...` to save another 11 bytes thanks to beaker =) Finally, translated the whole thing to Octave to save another 9 bytes...
> 4 votes

# Answer
# Java, ~~164~~ ~~159~~ 146 bytes

```
int[]p(int t,int m,String[]d){int r=m;for(String i:d){int x=Integer.decode(i);r=m<1?r+x:r*x;}return r>9?p(++t,m,(r+"").split("")):new int[]{r,t};}

```

First argument is just the counter, always 0

Second argument is method, 0 for ADD and 1 for MULTIPLY.

Third argument is an array of Strings, which contains the values to add/multiply.

# Ungolfed

```
public static int[] p(int t, int m, String[] d) {
    int r = m;
    for (String i : d) {
        int x = Integer.decode(i);
        r = m < 1 ? r + x : r * x;
    }
    return (r + "").length() > 1 ? p(++t, m, (r + "").split("")) : new int[]{r, t};
}

```

thanks to @Kevin Cruijssen for cutting a few bytes.

thanks to @milk for shaving 5 bytes.

# Test Program

```
public static final int ADD = 0;
public static final int MULTIPLY = 1;

public static void main(String[] args) {
    System.out.println(Arrays.toString(p(0, ADD, new String[]{"12", "123"}))); //9
    System.out.println(Arrays.toString(p(0, MULTIPLY, new String[]{"12", "123"}))); //6
}

public static int[] p(int t, int m, String[] d) {
    int r = m;
    for (String i : d) {
        int x = Integer.decode(i);
        r = m < 1 ? r + x : r * x;
    }
    return (r + "").length() > 1 ? p(++t, m, (r + "").split("")) : new int[]{r, t};
}

```
> 4 votes

# Answer
# R, ~~130~~ 124 chars

A somewhat different approach from @Frédéric's:

```
f=function(a,f,b){b=c(a,b);n=1;while((m<-nchar(d<-switch(f,'(+)'=sum,prod)(b)))>1){b=d%%10^(1:m)%/%10^(1:m-1);n=n+1};c(d,n)}

```

Indented, with newlines:

```
f=function(a,f,b){
    b=c(a,b) # Take both numbers
    n=1 #Counter
    while((m<-nchar(d<-switch(f,'(+)'=sum,prod)(b)))>1){
#My own special digit splitter! (d is the result and m is the nb of char of d)
        b=d%%10^(1:m)%/%10^(1:m-1)
        n=n+1
    }
    c(d,n) #Print results
    }

```

Line 4 probably needs more explanations:

```
switch(f,'(+)'=sum,prod) #pick which operator to use
switch(f,'(+)'=sum,prod)(b) # apply it to b
d<-switch(f,'(+)'=sum,prod)(b) #Saves the result in d
nchar(d<-switch(f,'(+)'=sum,prod)(b))#Measures the number of character of d
m<-nchar(d<-switch(f,'(+)'=sum,prod)(b)) #Saves it in m
(m<-nchar(d<-switch(f,'(+)'=sum,prod)(b)))>1 #Checks if it is more than 1

```

Test cases:

```
> f(12,"(+)",123)
[1] 9 2
> f(12,"(*)",123)
[1] 6 5
> f(351,"(+)",14568)
[1] 6 3

```
> 4 votes

# Answer
# Python, ~~160~~ ~~146~~ 129 bytes

```
def r(s):
 n=str(eval(s));c=0
 while n[1:]:exec("n=str(reduce(lambda a,b:a%sb,map(int,list(n))))"%"*+"["+"in s]);c+=1
 return n,c

```

Will post an explanation soon.

Input is in the form `12+12` or `5*35` (with normal `+` and `*` signs), and assumes that those are the only two operators.

It can handle number inputs as large as your computer's memory allows.

I'm almost certainly confident that this can be further.

**EDIT:** *~~16~~ 31 bytes saved thanks to @Copper.*
> 3 votes

# Answer
# R, 110 bytes

Using @plannapus' splitter.

`function(A,F,B){r=Reduce;x=r(F,A,B);y=1;while(x>9){m=nchar(x);x=r(F,x%%10^(1:m)%/%10^(1:m-1));y=y+1};cat(x,y)}`

```
f=function(A,F,B){
  r=Reduce                                  # Shortcut for Reduce
  x=r(F,A,B)                                # A operator B
  y=1                                       # Initiate counter
  while(x>9)                                # If number of digits > 2, or number > 9
  {m=nchar(x)                               # Count number of digits
    x=r(F,x%%10^(1:m)%/%10^(1:m-1))         # @plannapus's splitter, then feed into the A operator B operator C, etc while condition true
    y=y+1}                                  # Increment counter
  cat(x,y)}                                 # Print

```

Output

```
> f(136,"*",2356)
0 2
> f(31,"+",81)
4 2
> f(2,"+",3)
5 1
> (function(A,F,B){r=Reduce;x=r(F,A,B);y=1;while(x>9){m=nchar(x);x=r(F,x%%10^(1:m)%/%10^(1:m-1));y=y+1};cat(x,y)})(21,"*",111)
8 3

```

edit: I can't count.
> 3 votes

# Answer
# Clojure 126 bytes

```
(defn f [o a b] (loop [n (o a b) c 1] (if (< n 10) [n c] (recur (reduce #(o %1 %2) (map #(- (int %) 48) (str n))) (inc c)))))

```

Function is called like so:

```
(f + 81 31)

```

Here is the code ungolfed:

```
(defn f [o a b]
  (loop [n (o a b) c 1]
    (if (< n 10)
      [n c]
      (recur (reduce #(o %1 %2)
                     (map #(- (int %) 48) (str n)))
             (inc c)))))

(def test-cases [[+ 81 31]
                 [+ 351 14568]
                 [* 21 111]
                 [* 136 2356]])

(map #(apply f %) test-cases)
;;=> ([4 2] [6 3] [8 3] [0 2])

```

Bear in mind that Clojure is still new to me, so this is likely not the best solution. The challenge was fun all the same. Additionally, the code ran with very large numbers without any difficulty.
> 3 votes

# Answer
## Haskell, ~~76~~ 70 bytes

```
 (x#y)f=until(<[10])(\[s,i]->[foldr(f.read.pure)0$show s,i+1])[f x y,1]

```

Returns a two element list with the result and number of steps. Works for arbitrary large numbers. Usage example: `(351#14568)(+)` -\> `[6,3]`.

Edit: Thanks to @BlackCap for 6 bytes.
> 2 votes

# Answer
# Perl 6 53 bytes

```
{$/=(&^b($^a,$^c),{[[&b]] .comb}...10>*);$/[*-1],+$/}

```

Since `( 12, &[+], 123 )` is acceptable for the input, I can get it down to 53 bytes.
( `&[+]` is short for `&infix:<+>` which is a "reverence" to the numeric infix addition operator )

If the second argument had to be a string `(+)` it would be 87 bytes

```
{my&b=::("&infix:<$^b.substr(1,1)>");$/=(b($^a,$^c),{[[&b]] .comb}...10>*);$/[*-1],+$/}

```

## Explanation:

```
# bare block lambda with 3 parameters declared using placeholder syntax
{
  # store list into ｢$/｣
  # ( used ｢$/｣ so that I don't have to declare a variable )
  $/ = (

    # declare second placeholder parameter, and call it
    &^b(
      # with the first and third placeholder parameters
      $^a, $^c
    ),

    # bare block lambda with implicit parameter ｢$_｣
    {
      # list reduce using the second parameter from outer block
      [[&b]]

      # a list of the digits of ｢$_｣ (implicit method call)
      .comb
    }

    # keep doing that until
    ...

    # it produces something smaller than 10
    # ( Whatever lambda )
    10 > *
  );

  # returns

  # final result ( last value from list )
  $/[ * - 1 ],
  # and count of values in list
  +$/
}

```

## Test:

```
#! /usr/bin/env perl6
use v6.c;
use Test;

my &anastasiya-math = {$/=(&^b($^a,$^c),{[[&b]] .comb}...10>*);$/[*-1],+$/}

my @test = (
  (  81, &[+], 31    ) => (4, 2),
  ( 351, &[+], 14568 ) => (6, 3),
  (  21, &[*], 111   ) => (8, 3),
  ( 136, &[*], 2356  ) => (0, 2),
);

plan +@test;

for @test -> $_ ( :key(@input), :value(@expected) ) {
  cmp-ok anastasiya-math(|@input), &[»==«], @expected;
}

```

## Normal Usage:

```
# override built-in Bag operator ｢(+)｣ in current lexical scope
my &infix:<(+)> = &anastasiya-math.assuming: *, &[+], *;

# add a new operator
my &infix:<(*)> = &anastasiya-math.assuming: *, &[*], *;

say 12 (+) 123; # (9 2)
say 12 (*) 123; # (6 5)

```
> 2 votes

# Answer
# Python 2, ~~107~~ 97 bytes

```
g=lambda x,o,i=1:x<10and[x,i]or g(eval(o.join(`x`)),o,i+1)
lambda a,o,b:g(eval('%s'*3%(a,o,b)),o)

```

An anonymous function that takes input via argument of a first operand `a`, an operator `o` (`'+'` or `'*'`) and a second operand `b`, and returns a list of the form `[result, steps]`.

**How it works**

The anonymous function creates a string by concatenating the operands with the operator between them, and then evaluates it; this is the first step described in the question. Then, this value and the operator are passed to the recursive function `g`. Here, a counter `i`, which is incremented for every recursive call, is used. If the input is less than `10`, a single digit must have been reached, so this and `i` are returned. If not, the input is converted to a string and each character in this string is joined with the operator, giving the desired calculation, which is then evaluated and passed to the function recursively.

Try it on Ideone
> 2 votes

# Answer
# Groovy, 102 bytes

```
def p,e,r;p={t,m,d->e=d*.toInteger();r=m<1?e.sum():e.inject{a,b->a*b};r>9?p(++t,m,""+r as List):[r,t]}

```

### Degolfed

```
def p,e,r
p = { t, m, d ->
    e = d*.toInteger()
    r = (
            m<1
                ? e.sum()
                : e.inject { a, b -> a * b }
        )
    r > 9
        ? p(++t, m, "" + r as List)
        : [r,t]
}

```

### Explanation

Based on @Sean Bean 's excellent solution for Java.

* `p`: The closure (function, lambda, whatever) that implements the solution
* `t`: The current call depth (number of iterations), `p` should always be invoked with `t=1`
* `m`: The operation to perform, `0` for "add", `1` for "multiply"
* `d`: The list of operands, each operand is a String object
* `e`: The elements of `d`, each converted to an Integer
* `r`: The sum or product of `e`, depending on the operation `m`
* result statement, starting with `r > 9`:
    + If multi-digit (`r > 9`), reinvoke, incrementing depth `t` and converting `r` to a list of digit strings (and return result).
    + If single-digit, return `r` and `t` as a list.

### Test Program

```
final ADD = 0
final MULTIPLY = 1
println p(1, ADD, ["12", "123"]) //9, 2
println p(1, MULTIPLY, ["12", "123"]) //6, 5
println p(1, ADD, ["2", "3"]) //5, 1

```

### Results

```
[9, 2]
[6, 5]
[5, 1]

```
> 2 votes

# Answer
# R, 91 bytes

Using @Vlo's code, which makes use of @plannapus's splitter, and some ideas I generated while golfing @Frédéric's answer, this is the shortest R answer yet. (An unusually large number of R answers here today...)

```
function(A,F,B){x=F(A,B);while(x>9){m=nchar(x);x=F(x%%10^(1:m)%/%10^(1:m-1));T=T+1};c(x,T)}

```

Crucially, this requires that the input for the operator be either `sum` for (+) or `prod` for (\*). Under the rules of the challenge, this seems to be okay.

With indentation:

```
function(A,F,B){
  x=F(A,B);
  while(x>9){
    m=nchar(x);
    x=F(x%%10^(1:m)%/%10^(1:m-1));
    T=T+1
  };
  c(x,T)
}

```

Main differences from @Vlo's answer are:

1. Instead of using `Reduce`, we rely on the input argument being a function, and just call it explicitly. (Yay for functions being first-class objects!)
2. Instead of initializing a new variable as our counter, we abuse R's builtins and use `T`, which evaluates to `TRUE` (aka `1`), but since it's not a reserved variable we can modify it. Thus `T+T` is `2`. So we use that as our counter.
3. Instead of `cat`ing the output, we just return it as a vector with `c`. As well as saving two bytes, the fact that the output is forced into a vector ensures that `T` is of class `numeric`. If we use `cat`, and `T` hasn't been incremented, then we get erroneous output like `1 TRUE`.
> 2 votes

# Answer
# Java 7, ~~203~~ ~~195~~ 192 bytes

```
int c=1;String c(long a,long b,int o){return p(((o<1?a+b:a*b)+"",o)+","+c;}long p(String n,int o){long x=o,q;for(String s:n.split("")){q=new Long(s);x=o<1?x+q:x*q}c++;return x<10?x:p(x+"",o);}

```

It uses `long` (maximum value of 2<sup>63</sup>-1). If it would use `int` instead (maximum value of 2<sup>31</sup>-1) it would only be 1 byte less (**191 bytes**):

```
int c=1;String c(int a,int b,int o){return p(((o<1?a+b:a*b)+"",o)+","+c;}int p(String n,int o){int x=o,q;for(String s:n.split("")){q=new Integer(s);x=o<1?x+q:x*q}c++;return x<10?x:p(x+"",o);}

```

It can most likely be golfed a bit more. Having to print the steps as well as the answer for both operators takes some bytes, though..
Uses 0 (for `(+)`) and 1 (for `(*)`).

**Ungolfed & test code:**

Try it here.

```
class Main{
  static int c = 1;
  static String c(long a, long b, int o){
    return p((o < 1 ? a+b : a*b) + "", o) + "," + c;
  }

  static long p(String n, int o){
    long x = o,
         q;
    for(String s : n.split("")){
      q = new Long(s);
      x = o < 1
           ? x + q
           : x * q;
    }
    c++;
    return x < 10
            ? x
            : p(x+"", o);
  }

  public static void main(String[] a){
    System.out.println(c(81, 31, true));
    c = 1;
    System.out.println(c(351, 14568, true));
    c = 1;
    System.out.println(c(21, 111, false));
    c = 1;
    System.out.println(c(136, 2356, false));
  }
}

```

**Output:**

```
4,2
6,3
8,3
0,2

```
> 1 votes

# Answer
## Mathematica, ~~105~~ 94 bytes

*Code.*

```
{x,y}=(c=0;f//.a_:>(c++;t=o@@IntegerDigits@a);{t,c})&/.{{f->#1+#2,o->Plus},{f->#1#2,o->Times}}

```

*Usage.*

```
x[81, 31]
(* {4, 2} *)

x[351, 14568]
(* {6, 3} *)

y[21, 111]
(* {8, 3} *)

y[136, 2356]
(* {0, 2} *)

```

*Explanation.*

The two functions `x` (for (+)) and `y` (for (\*)) are created at the same time by replacing the parameters `f` and `o` in

```
(c = 0;
 f //. a_ :> (c++; t = o@@ IntegerDigits@a);
 {t, c}
)&

```

with their appropriate values. For `x`, `f` becomes `#1 + #2` and `o` becomes `Plus`; for `y`, they respectively become `#1 #2` and `Times`. Rewriting the function `x` for the last part of the explanation:

```
x = (
  c = 0;
  #1 + #2 //. a_ :> (c++; t = Plus@@IntegerDigits@a);
  {t, c}
) &;

(* The symbol //. stands for ReplaceRepeated.
   The rule a_ :> (c++; t = Plus@@IntegerDigits@a) is applied until the result no longer
changed. Specifically, the rule increments the counter of 1 at each step (this is c++),
then takes the sum of the digits of the previous result (this is Plus@@IntegerDigits@a).
The rule stops to apply when the variable t is less than 10. We return the final result and
the number of steps with {t, c}. *)

```
> 1 votes

# Answer
# Ruby, 55 bytes

Recursive call. Used to be very different from @edc65's JavaScript answer but as I optimized it eventually became a direct port developed almost independently from their answer, minus one final optimization involving checking the eval'ed result instead of the length of the list of operands being passed in, which allowed me to surpass their byte count.

Input is a string representing the operator, and an array containing the operands.

Try it online.

```
f=->o,x,i=1{y=eval x*o;y>9?f[o,y.to_s.chars,i+1]:[y,i]}

```
> 1 votes

# Answer
# Perl, 38 bytes

Includes +2 for `-ap`

Run with the input on STDIN and spaces around the operator:

```
amath.pl <<< "12 + 123"
amath.pl <<< "12 * 123"

```

The output is digit and steps separated by `+A`

`amath.pl`:

```
#!/usr/bin/perl -ap
1while++$\,$_=eval."+A",s/\B/$F[1]/g

```

If outputting the steps in unary is ok this 35 byte version works better:

```
#!/usr/bin/perl -lap
1while$\.=1,$_=eval,s/\B/$F[1]/g

```
> 1 votes

---
Tags: code-golf, math, repeated-transformation
---