title: Point-free look and say sequence

text:
# Question
Title: Point-free look and say sequence
You are too make a program that take an integer as the input and outputs the first what ever that number was of the look and say sequence.

For example:

```
$ ./LAS
8
[1,11,21,1211,111221,312211,13112221,1113213211]

```

The exact way you output the list is unimportant, as long as users can distinctly see the different numbers of the sequence. Here is the catch though. **You can't use any sort of user-defined variable.**

For example:

1. No variables, including scoped variables.
2. When you have functions, they can not have a name. (Exception, if your language requires a main function or similar to work, you may have that function.)
3. When you have functions, they can not have named arguments.

Also, you may not use a library with specific capabilities relating to the look and say sequence, and you can not access the network, or provide your program with any files (although it can generate and use its own.) This is code golf, so shortest code in characters wins!

# Answer
## GolfScript (31 chars)

```
~[]\{[1\{.2$={;\)}1if\}*].n@}*;

```

Adapted from my answer to a previous look-and-say question. This one has a less onerous restriction for functional languages, which allows saving 5 chars, but because most answers to the previous question can't be adapted (it's a crazily onerous restriction for non-functional languages) I don't think it makes sense to close it as a dupe.
> 6 votes

# Answer
## Haskell 206 Chars

```
import Data.List
import Control.Applicative
import Data.Function
main= readLn >>= print .(flip take (map read $ fix (("1":). map (concat .(map ((++)<$>(show . length)<*>((:[]). head))). group))::[Integer]))

```

It works by using the group function to group them into groups of equal things. Then it uses applicatives with functions to build a function that simultaneously reads the length, and appends it to with one the elements. It uses a fix and a map to create a recursive definition (point-free.) And there ya go.
> 11 votes

# Answer
# J (42 chars)

Point-free (also called tacit) programming is natural in J.

```
,@:((#,{.);.1~(1,}.~:}:))&.>^:(<`((<1)"_))

```

That's a function, to use it you write the code, a space, and the input number. For example,

```
   ,@:((#,{.);.1~(1,}.~:}:))&.>^:(<`((<1)"_)) 8
┌─┬───┬───┬───────┬───────────┬───────────┬───────────────┬───────────────────┐
│1│1 1│2 1│1 2 1 1│1 1 1 2 2 1│3 1 2 2 1 1│1 3 1 1 2 2 2 1│1 1 1 3 2 1 3 2 1 1│
└─┴───┴───┴───────┴───────────┴───────────┴───────────────┴───────────────────┘

```

Notice the pretty boxes in the output.

*Addendum*: Here are a couple of "cheats" I was too bashful to use at first, but now that I've seen other use them first...

* Here's a 36 char version with a different "calling convention": replace 8 with the number of terms you want.

```
,@:((#,{.);.1~(1,}.~:}:))&.>^:(<8)<1

```
* And if having extra zeroes in the output is OK, here's a 32 char version:

```
,@:((#,{.);.1~(1,}.~:}:))^:(<8)1

```
> 10 votes

# Answer
# Bash and coreutils, 111 73 chars

```
eval echo 1\|`yes 'tee -a o|fold -1|uniq -c|(tr -dc 0-9;echo)|'|sed $1q`:

```

`uniq -c` is doing the heavy lifting to produce the next number in the sequence. `yes`, `sed` and `eval` create the necessary number of repeats of the processing pipeline. The rest is just formatting.

Output is placed in a file called `o`.:

```
$ ./looksay.sh 8
ubuntu@ubuntu:~$ cat o
1
11
21
1211
111221
312211
13112221
1113213211
$

```
> 8 votes

# Answer
## GolfScript, 36 chars

```
~([1]\{.[0\{.2$=!{0\.}*;\)\}/](;}*]`

```

Variables are pretty rarely used in GolfScript, and this task certainly doesn't need them. Input is on stdin, output to stdout. For example, the input `8` gives the output:

```
[[1] [1 1] [2 1] [1 2 1 1] [1 1 1 2 2 1] [3 1 2 2 1 1] [1 3 1 1 2 2 2 1] [1 1 1 3 2 1 3 2 1 1]]

```

I may write a detailed explanation of this code later, but at least you can easily tell that it uses no variables by the fact that it doesn't include the variable assignment operator `:` anywhere.
> 7 votes

# Answer
# Haskell, 118 chars (80 without imports)

```
import Data.List
import Control.Monad
main=readLn>>=print.flip take(iterate(ap((++).show.length)(take 1)<=<group)"1")

```
> 6 votes

# Answer
# Mathematica, 65 chars

```
FromDigits/@NestList[Flatten@Reverse[Tally/@Split@#,3]&,{1},#-1]&

```

### Example:

```
FromDigits/@NestList[Flatten@Reverse[Tally/@Split@#,3]&,{1},#-1]&[8]

```

> {1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211}
> 4 votes

# Answer
## J, 37 characters

```
1([:,((1,2&(~:/\))(#,{.);.1]))@[&0~i.

```

Based on my answer to the Pea Pattern question. There may be some potential for shortening here. Usage is as for the other J answer:

```
   1([:,((1,2&(~:/\))(#,{.);.1]))@[&0~i. 7
1 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0
2 1 0 0 0 0 0 0
1 2 1 1 0 0 0 0
1 1 1 2 2 1 0 0
3 1 2 2 1 1 0 0
1 3 1 1 2 2 2 1

```

It also has the extra zeroes problem my pea pattern answer had.
> 3 votes

# Answer
# Perl 6: 63 53 characters

```
say (1,*.subst(/(\d)$0*/,{.chars~.[0]},:g)...*)[^get]

```

Create a lazy list of the Look and Say sequence (`1,*.subst(/(\d)$0*/,{.chars~.[0]},:g)...*`), and then get as many elements as specified by the user (`[^get]`, which is an array subscript and means `[0..(get-1)]`), and `say` them all.

The lazy list works by first taking 1, then to generate each successive number, it takes the last one it found and substitutes all the sequences of the same digit, as matched by `/(\d)$0*/`, and replaces them with {how many}+{what digit}, or `.chars~.[0]`.

The only variables in this code are `$0`, the first capture of the match, and the implicit, topical `$_` variable that bare `.method`s call, and neither of these are user-defined.
> 2 votes

# Answer
# Dyalog APL, 35 characters

`(⊢,⊂∘∊∘((≢,⊃)¨⊃⊂⍨2≢/0,⊃)∘⌽)⍣(⎕-1)⊢1`

is evaluated input. In the link I've replaced it with 8, as tryapl.org does not allow user input.

No named variables (`a←1`), no named functions (`f←{}`), no arguments (, ).

Only composition of functions:

* monadic operators—each:, reduce:`f/`, commute:`f⍨`
* dyadic operators—power:`f⍣n`, compose:`f∘g`
* forks—`(f g h)B ←→ (f B)g(h B)`; `A(f g h)B ←→ (A f B)g(A h B)`
* atops—`(f g)B ←→ f(g B)`; `A(f g)B ←→ f(A g B)`
* 4-trains (fork-atops)—`(f g h k) ←→ (f (g h k))`

Primitive functions used:

* right:`A⊢B ←→ B`
* reverse:`⌽B`
* first:`⊃B`
* concatenate:`A,B`
* not match:`A≢B`, count:`≢B`
* enclose:`⊂B`, partition:`A⊂B`
* flatten:`∊B`

In tryapl.org, if you remove the trailing `⊢1`, which is the argument to this massive composed thing, you can see a diagram of how it's parsed:

```
     ⍣
   ┌─┴─┐
 ┌─┼─┐ 7
 ⊢ , ∘
    ┌┴┐
    ∘ ⌽
 ┌──┴───┐
 ∘    ┌─┴─┐
┌┴┐   ¨ ┌─┼───┐
⊂ ∊ ┌─┘ ⊃ ⍨ ┌─┼───┐
  ┌─┼─┐ ┌─┘ 2 / ┌─┼─┐
  ≢ , ⊃ ⊂   ┌─┘ 0 , ⊃
            ≢

```
> 2 votes

# Answer
# GolfScript, ~~57~~ 43 chars

My own approach. Ended up longer than the existing one sadly =(.

```
~[1 9]{.);p[{...1<^0=?.@(\@(>.,(}do 0=]}@*;

```

Sample output for stdin of `8`:

```
[1]
[1 1]
[2 1]
[1 2 1 1]
[1 1 1 2 2 1]
[3 1 2 2 1 1]
[1 3 1 1 2 2 2 1]
[1 1 1 3 2 1 3 2 1 1]

```

Alternate version w/out the `9` sentinel, yet it's longer at 47 characters. I suspect it has more potential:

```
~[1]{.p[{...1<^.{0=?.@(\@(>1}{;,\0=0}if}do]}@*;

```
> 1 votes

# Answer
# Scala 178

```
(0 to Console.in.readLine.toInt).map(i=>Function.chain(List.fill[String=>String](i)(y=>(('0',0,"")/:(y+" ")){case((a,b,c),d)=>if(d==a)(a,b+1,c)else(d,1,c+b+a)}._3.drop(2)))("1"))

```
> 1 votes

# Answer
# Husk, 11 bytes

```
↑¡oṁ§eL←g;1

```

Try it online!

1-indexed.
> 1 votes

# Answer
## J 66 (with I/O)

```
".@(_5}&',@((#,&:":{.);.1~1&(0})&(~:_1|.]))^:(<X)":1')@{.&.stdin''

```

without IO, scores 43:

```
NB. change the 8 for the number of numbers you'd want
,@((#,&:":{.);.1~1&(0})&(~:_1|.]))^:(<8)'1'

```

Funny question to pose yourself, when is the first 9 to show up?
> 0 votes

# Answer
# Jelly, 11 10 bytes

```
1ŒrUFƊ’}¡)

```

Try it online!

Jelly doesn't have variables.

## Explanation

```
1ŒrUFƊ’}¡)
         )   For each i in 1..n:
1              Begin with 1
      ’}¡      i - 1 times
     Ɗ         (
 Œr              Run-length encode
   U             Reverse each
    F            Flatten
     Ɗ         )

```
> 0 votes

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


title: Perfect radicals

text:
# Question
Title: Perfect radicals
Given a positive integer number \\$n\\$ output its perfect radical.

# Definition

A perfect radical \\$r\\$ of a positive integer \\$n\\$ is the lowest integer root of \\$n\\$ of any index \\$i\\$:

$$r = \sqrt\[i\]{n}$$

where \\$r\\$ is an integer.

In other words \\$i\\$ is the maximum exponent such that \\$r\\$ raised to \\$i\\$ is \\$n\\$:

$$n = r^i$$

This is OEIS A052410.

# Special cases

For \\$n = 1\\$ we don't really care about the degree \\$i\\$ as we are asked to return \\$r\\$ in this challenge.

* Just take \\$r=1\\$ for \\$n=1\\$.
* Since there is an OEIS for this and it starts from 1 you don't have to handle \\$n=0\\$.

# Note

A positive integer \\$n\\$ is expressed in the form \\$100...000\\$ if we convert it to base \\$r\\$ For example the perfect radical of \\$128\\$ is \\$2\\$ which is \\$1000000\\$ in base \\$2\\$, a \\$1\\$ followed by \\$i -1\\$ \\$0\\$s.

**Input:** a positive integer. You don't not have to handle inputs not supported by your language (obviously, abusing this is a standard loophole.)

**Output:** the perfect radical of that number.

You may instead choose to take a positive integer \\$n\\$ and output the radicals of the first \\$n\\$ positive integers, or to output the infinite list of radicals.

# Test cases

This is a list of all numbers \\$n \le 10000\\$ where \\$n \ne r\\$ (expect for \\$n = 1\\$, included as an edge case, included also some cases where r==n for completeness sake ) :

```
[n, r]
[1, 1],
[2,2],
[3,3],
[4, 2],
[5,5],
[6,6],
[7,7],
[8, 2],
[9, 3],
[10,10],
[16, 2],
[25, 5],
[27, 3],
[32, 2],
[36, 6],
[49, 7],
[64, 2],
[81, 3],
[100, 10],
[121, 11],
[125, 5],
[128, 2],
[144, 12],
[169, 13],
[196, 14],
[216, 6],
[225, 15],
[243, 3],
[256, 2],
[289, 17],
[324, 18],
[343, 7],
[361, 19],
[400, 20],
[441, 21],
[484, 22],
[512, 2],
[529, 23],
[576, 24],
[625, 5],
[676, 26],
[729, 3],
[784, 28],
[841, 29],
[900, 30],
[961, 31],
[1000, 10],
[1024, 2],
[1089, 33],
[1156, 34],
[1225, 35],
[1296, 6],
[1331, 11],
[1369, 37],
[1444, 38],
[1521, 39],
[1600, 40],
[1681, 41],
[1728, 12],
[1764, 42],
[1849, 43],
[1936, 44],
[2025, 45],
[2048, 2],
[2116, 46],
[2187, 3],
[2197, 13],
[2209, 47],
[2304, 48],
[2401, 7],
[2500, 50],
[2601, 51],
[2704, 52],
[2744, 14],
[2809, 53],
[2916, 54],
[3025, 55],
[3125, 5],
[3136, 56],
[3249, 57],
[3364, 58],
[3375, 15],
[3481, 59],
[3600, 60],
[3721, 61],
[3844, 62],
[3969, 63],
[4096, 2],
[4225, 65],
[4356, 66],
[4489, 67],
[4624, 68],
[4761, 69],
[4900, 70],
[4913, 17],
[5041, 71],
[5184, 72],
[5329, 73],
[5476, 74],
[5625, 75],
[5776, 76],
[5832, 18],
[5929, 77],
[6084, 78],
[6241, 79],
[6400, 80],
[6561, 3],
[6724, 82],
[6859, 19],
[6889, 83],
[7056, 84],
[7225, 85],
[7396, 86],
[7569, 87],
[7744, 88],
[7776, 6],
[7921, 89],
[8000, 20],
[8100, 90],
[8192, 2],
[8281, 91],
[8464, 92],
[8649, 93],
[8836, 94],
[9025, 95],
[9216, 96],
[9261, 21],
[9409, 97],
[9604, 98],
[9801, 99],
[10000, 10]

```

# Rules

* Input/output can be given by any convenient method.
* You can print it to STDOUT, return it as a function result or error message/s.
* Either a full program or a function are acceptable.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

Sandbox

# Answer
> 11 votes
# , 14 bytes

```
(%+./)&.(_&q:)

```

Try it online!

```
(%+./)&.(_&q:)
      &.(_&q:) number to prime exponents
(%+./)         divide them by their GCD
      &.(_&q:) prime exponents to number

```

# Answer
> 8 votes
# Jelly, 10 bytes

```
ÆEgƒ0:@ƊÆẸ

```

Try it online!

`ÆE:g/$ÆẸ` errors given 1.

```
ÆE            Take the exponents of the input's prime factorization.
     :@Ɗ      Divide each exponent by
  gƒ0         the exponents' GCD (or 0 in the case that there are none).
        ÆẸ    Let the result be the exponents of the output's prime factorization.

```

# Answer
> 8 votes
# Brachylog, 6 bytes

```
1|~^hℕ

```

Try it online!

```
1|~^hℕ  with the implicit input n
1       input and output is 1
 |      or
  ~^    find two numbers [r, i] so that r^i = n
    h   return r
     ℕ  to limit the search space: r must be positive

```

Search tries lowest `i` first, so we get the maximum `r` for free.

# Answer
> 8 votes
# Python 3, ~~55~~ \\$\cdots\\$ ~~59~~ 57 bytes

Added 7 bytes to fix an error kindly pointed by user.
Saved 3 bytes thanks to user!!!

```
lambda n:{r**i:r for i in range(n)for r in range(n+1)}[n]

```

Try it online!

# Answer
> 7 votes
# Jelly, ~~8~~ ~~6~~ 5 bytes

```
bR§i1

```

Try it online!

Uses the fact that `n` in base `r` has the format `100...000`, meaning that the sum of the digits only equals 1 in base `r`

-1 byte (indirectly) thanks to Dominic van Essen's answer, make sure to give them an upvote

## How it works

```
bR§i1 - Main link. Takes n on the left
 R    - [1, 2, 3, ..., n]
b     - Convert n to each base 1, 2, 3, ..., n
  §   - Sum of the digits of each
   i1 - First index of 1

```

# Answer
> 7 votes
# 05AB1E, ~~~~8~~~~ ~~11~~ 8 bytes

-3 thanks to @ovs!

```
L¦BíCXkÌ

```

Try it online!

I am trying to somehow implement a log function to check whether a number matches the regex `10*`, but that is too mathematical for me...

# Wait, how?

```
L              # Push all numbers natural numbers up to input          [1, 2, 3 ... I]
 ¦             # What is that 1 doing there? Remove it!                [2, 3, 4 ... I]
  B            # Convert the input to each of the bases e.g input: 9   [1001, 100, 21...]
   í           # Reverse each string                                   [1001, 001, 12...]
    C          # Convert each from binary to decimal                   [9, 1, 4...]              (How though! Can someone explain?)
     Xk        # Get first index of 1                                  1
       Ì       # Add 2                                                 3

```

# Answer
> 7 votes
# Husk, 8 bytes

```
VȯεΣ`B¹ḣ

```

Try it online!

```
V           # index of first truthy element of
 ȯ          # applying 3 functions to
       ḣ    # 1...input
    `B¹     # convert input to this base
   Σ        # sum of digits
  ε         # is at most 1

```

# Answer
> 6 votes
# k4, ~~26~~ ~~24~~ ~~21~~ 18 bytes

-2 bytes by ignoring `n=0` case

-3 bytes by applying @caird coinheringaahing's logic

-3 bytes by simplifying/combining operations

```
{(x{+/y\:x}'!x)?1}

```

Benefits from `list ? value` returning the count of the list if the value isn't present in it, and from convenient weirdness with the `n=0` and `n=1` edge cases.

# Answer
> 5 votes
# Retina 0.8.2, 60 bytes

```
.+
$*
(?<=(?=((?=((1*)(?=\5\3+$)1)(\2*$))\4)*1$)^(..+)).*

1

```

Try it online! Link includes test cases. Explanation:

```
.+
$*

```

Convert to unary.

```
(?<=(?=...$)^(..+)).*

```

Delete the earliest suffix leaving behind the smallest prefix \\$r\\$ (captured into `\5`) such that the \\$n\\$ matches the following:

```
((?=((1*)(?=\5\3+$)1)(\2*$))\4)*1

```

Find \\$k\\$ `\3` such that \\$n-r\\$ is divisible by \\$k\\$, but also \\$n\\$ is divisible by \\$k+1\\$ `\2`. Apparently this can only be satisfied by \\$n=r(k+1)\\$, but I can't find the answer where this is proved. \\$(r-1)(k+1)\\$ is then subtracted from \\$n\\$, resulting in \\$k+1\\$. This is then repeated until \\$n\\$ is reduced to \\$1\\$, which is matched at the end.

```
1

```

Convert to decimal.

# Answer
> 5 votes
# , 47 bytes

```
n=scan();match(n,sapply(0:n,"^",1:n))%/%n-(n<2)

```

Try it online!

Struggled for ages trying to beat Giuseppe's answer, only to be totally outgolfed (seconds before posting) by Robin Ryder's comment (now an answer)...

# Answer
> 5 votes
# JavaScript (ES7), 36 bytes

Recursively looks for the highest \\$i\le n\\$ such that \\$k=n^{1/i}\\$ is an integer. Then returns this \\$k\\$.

```
f=(n,i=n)=>(k=n**(1/i))%1?f(n,i-1):k

```

Try it online!

---

# JavaScript (ES7), 37 bytes

A slightly longer version that performs more recursive calls but is not subject to rounding errors.

```
n=>(g=k=>k**i-n?g(k-1||i--|n):k)(i=n)

```

Try it online!

# Answer
> 5 votes
# , ~~37~~ 33 bytes

-4 bytes thanks to Dominic van Essen

```
match(T,!log(n<-scan(),1:n)%%1,1)

```

Try it online!

A different (and shorter) approach than the one used in Giuseppe's and Dominic van Essen's R answers.

Finds the first integer `k` such that `log(n,k)` is an integer, or returns `1` if there is no such `k` (which corresponds to the special case `n=1`).

# Answer
> 5 votes
# Python 3.8, ~~53~~ 51 bytes (thanks @user for pointing out extra spaces)

```
def r(n):
    i=n
    while(a:=n**(1/i))%1:i-=1
    return a

```

Try it online!

# Answer
> 4 votes
# , ~~49~~ 44 bytes

```
n=scan();which(outer(1:n,n:1,"^")==n,T)[1,1]

```

Try it online!

Thanks to Dominic van Essen for pointing out a bug.

```
n <- scan()				# read input
arr <- outer(0:n,1:n,"^")		# create the array of powers (0^(1:n), 1^(1:n), ... n^(1:n))
arr <- t(arr)				# transpose, so the array is ((0:n)^1, (0:n)^2, ... (0:n)^n)
ind <- which(arr==n,T)			# get 1-based array indices where arr == n. So they are a matirx of rows of [i+1,r+1] pairs, sorted in increasing order of r
ind[1,2]-1				# extract the appropriate r.

```

# Answer
> 4 votes
# Factor, 49 bytes

```
[ dup [1,b] 2dup '[ _ swap _ n^v member? ] find ]

```

Try it online!

Slow for larger inputs because it tries to evaluate a large power.

```
[
  dup [1,b] 2dup       ! ( n 1..n n 1..n )
  '[                   ! Put stack items in the `_`s in the quotation
    _(n) swap _(1..n)  !   ( elt -- n elt 1..n )
    n^v member?        !   Test if n appears in elt^(1..n)
  ] find               ! Find the first number in 1..n that satisfies the above
]

```

# Answer
> 4 votes
# 05AB1E, 6 bytes

Inspired by SunnyMoon's answer.

```
LÀ.ΔBR

```

Try it online!

```
L         # push the range [1, 2, ..., n]
 À        # rotate the 1 to the back: [2, 3, ..., n, 1]
  .Δ      # find the first integer where ...
    B     #   the input converted to that base
     R    #   reversed
          #   implicit: is equal to 1 as a number

```

---

# 05AB1E, 8 bytes

```
LÀ.Δ.n.ï

```

Try it online! There was a bug with, which has recently been fixed, but the interpreter on TIO is not up to date.

```
L         # push the range [1, 2, ..., n]
 À        # rotate the 1 to the back: [2, 3, ..., n, 1]
  .Δ      # find the first integer where ...
    .n    #   the logarithm of the input in that base
      .ï  #   is an integer

```

# Answer
> 3 votes
# C (gcc), ~~65~~ ~~60~~ 58 bytes

Saved 5 bytes thanks to Sisyphus!!!

```
p;i;r;f(n){for(r=0;r++<n;)for(p=i=1;i++<n;p*=r)n=p-n?n:r;}

```

Try it online!

# Answer
> 3 votes
# Japt `-g`, 10 bytes

I feel like I'm missing a trick here.

```
õ ï æ@¥Xrp

```

Try it

```
õ ï æ@¥Xrp     :Implicit input of integer U
õ              :Range [1,U]
  ï            :Cartesian product with itself
    æ          :Get first pair that returns true
     @         :When passed through the following function as X
      ¥        :  Test U for equality with
       Xr      :  X reduced by
         p     :    Exponentiation
               :Implicit output of first element of that pair

```

# Answer
> 3 votes
# Wolfram Language (Mathematica), 27 bytes

```
Most@*Internal`PerfectPower

```

Try it online!

-20 bytes from att

# Answer
> 3 votes
# Stax, 10 bytes

```
┌Pèó~JRå▲ï

```

Run and debug it

## Explanation

```
R{xs|E|+1=}j
R            range 1..n
 {        }j get first number i where:
  xs|E       input(x) in base i digits
      |+     summed
        1=   equals 1

```

# Answer
> 3 votes
# 05AB1E, 12 (10) bytes

```
ÓDā<Ør0š¿÷mP

```

Port of *@UnrelatedString*'s Jelly answer.

The  shouldn't be necessary, but unfortunately there is a bug in 05AB1E for `¿` with empty lists.

Try it online or verify all test cases.

**Explanation:**

```
Ó             # Get the prime exponents of the (implicit) input-integer
 D            # Duplicate this list of exponents
  ā           # Push a list in the range [1, length] (without popping the list itself)
   <          # Decrease each by one to make the range [0, length)
    Ø         # Get the n'th prime for each of these indices
     r        # Reverse the three lists on the stack
      0š      # Prepend a 0 (work-around for `¿` bug with empty lists)
        ¿     # Pop and get the greatest common divisor (gcd) of this list
         ÷    # Integer-divide all values in the list by this gcd
              # (we use integer-division due to another bug that isn't on TIO yet,
              #  as well as to get an integer output, instead of float)
          m   # Take the primes we created earlier to the power of these values
           P  # And take the product of that
              # (after which it is output implicitly)

```

# Answer
> 2 votes
# Scala, 50 bytes

Back to 50 bytes because n=0 doesn't have to be handled anymore!

```
n=>1.to(n)find(r=>1.to(n)exists(n==math.pow(r,_)))

```

Try it online!

# Answer
> 2 votes
# Charcoal, ~~19~~ 16 bytes

```
ＮθＩ⊕⌕Ｅθ⎇ιΣ↨θ⊕ιθ¹

```

Try it online! Link is to verbose version of code. Edit: Now back to a reformulation of my original answer. Works by converting `n` to each base `1..n` and finding the first 1-indexed value with a digit sum of `1`. Conveniently this automatically works for an input of `0` (the resulting list is empty, so the 1-indexed position is `0`), so the only edge case is base `1` as Charcoal cannot convert to unary, but the digit sum is always `n` in base `1` anyway. Explanation:

```
Ｎθ                  Input `n` as a number
      θ             `n`
     Ｅ              Map over implicit range
        ι           Current value
       ⎇      θ     If zero then `n` else
          ↨θ        `n` converted to base
            ⊕ι      Incremented value
         Σ          Sum of digits
    ⌕          ¹    Find first occurrence of literal `1`
   ⊕                Increment (convert to 1-indexing)
  Ｉ                 Cast to string
                    Implicitly print

```

# Answer
> 2 votes
# Octave, 33 bytes

```
@(n)[~,j]=find((t=1:n)'.^t'==n,1)

```

**Try it online!**

### How it works

```
@(n)                               % anonymous function with input n
               (t=1:n)             % let t = [1, 2, ..., n] (row vector)
                       .^          % element-wise power with broadcast...
                      '            % of t transposed...
                         t         % raised to t. Gives n×n matrix of powers
                          '==n     % test each entry for equality with n
    [~,j]=find(               ,1)  % col index of the first true entry (in linear order)

```

# Answer
> 2 votes
# Perl 5 `-p`, 34 bytes

```
++$\until grep"@F"==$\**$_,1..$_}{

```

Try it online!

# Answer
> 1 votes
# Python 3, 55 bytes

```
f=lambda n,r=1,i=1:r*(r**i==n)or f(n,r+(i>n),i>n or-~i)

```

Try it online!

My first golf in over a year! It's a bit longer than this answer, but doesn't use that nasty floating point. As many good code golf answers do, this hits the recursion limit pretty soon.

# Answer
> 1 votes
# Python 3, 74 bytes

```
lambda n,r=round:r(n**[1/i for i in range(1,n+1)if r(n**(1/i))**i==n][-1])

```

Try it online!

This solution is longer but faster than this answer

---
Tags: code-golf, math, sequence, number-theory, base-conversion
---


# Question
Title: Find the number of ways to climb a stairway
**Challenge:**

Find the number of ways to climb some stairs with n steps and with some limitations. You should be able to run the tests below on TIO https://tio.run/ **without timing out.** – 60 seconds. (Typically a fraction of a second is well within reach for most languages if a good optimizing strategy is applied).

**The input is a list of positive numbers:**

* the first number in the input is the total number of steps in the stairway
* the rest of the input is the different number of steps you are allowed to climb at once, but you're only allowed to use n steps a maximum n times if n\>1. So if 2 is allowed you're only allowed to take 2 steps a maximum of 2 times. And 3 steps maximum 3 times and so on for all n\>1. So if 1 is allowed, you can take 1 step as many times as you like.
* you should not "overstep", with a stairway of 5 steps and only 2 steps at once are allowed, there is no way to climb it (output 0)

Allowed assumptions: all input numbers are positive integers, at least 1 (0, negative and fractional numbers need no special handling). The list of allowed steps are unique numbers and ordered if it helps. Also the size of the stairs can be the last number or a separate part of the input if that's helpful to your implementation ("reorganizing" input don't need to be a part of the problem)

**Output:**

* a number which is the number of ways to climb the stairs

**Examples:**

* Input: 3,1 Output: 1 (as there is only one way when you're only allowed one step at a time)
* Input: 3,1,2 Output: 3 (since you can climb in three ways: 1+1+1 or 1+2 or 2+1)
* Input: 3,4 Output: 0 (you should always end at the top, you cannot take 4 steps since the stairs only has 3)
* Input: 4,1,2,3 Output: 7 (1+1+1+1, 1+1+2, 1+2+1, 2+1+1, 2+2, 3+1, 1+3)
* Input: 6,2 Output: 0 (since you're not allowed to take 2 steps 3 times)
* Input: 6,2,1 Output: 12 (2+2+1+1, 2+1+2+1, 2+1+1+2, 2+1+1+1+1, 1+2+2+1, 1+2+1+2, 1+2+1+1+1, 1+1+2+2, 1+1+2+1+1, 1+1+1+2+1, 1+1+1+1+2, 1+1+1+1+1+1. But 2+2+2 isn't allowed)
* Input: 99,99,1 Output: 2 (99 or 1+1+1+1+...99 times)

**More tests:**

```
2,1        → 1
10,1       → 1
3,1,2      → 3
3,4        → 0
3,2        → 0
4,1,2      → 5
4,1,2,3    → 7
6,2        → 0
6,2,1      → 12
7,1,2      → 17
5,1,2,3    → 13
15,1,2,7   → 266
39,3,2,7   → 301
99,11,3,2  → 1981

```

# Answer
# JavaScript (ES6), 71 bytes

Expects `(list)(n)`.

```
(a,t=0)=>g=n=>n>0?a.map(x=>--g[(g[x]=-~g[x])+~x|x<2&&g(n-x),x])|t:t+=!n

```

Try it online!

### Commented

```
(a, t = 0) =>           // a[] = input list, t = output
g = n =>                // g is a recursive function taking the number of steps n
  n > 0 ?               // if n is positive:
    a.map(x =>          //   for each value x in a[]:
      --g[              //     decrement g[x] afterwards
        (g[x] = -~g[x]) //       increment g[x]
        + ~x |          //       if g[x] is not equal to x + 1
        x < 2 &&        //       or x = 1:
          g(n - x),     //         do a recursive call with n - x
        x               //       actual index to update g[x]
      ]                 //     end of entry update: this is guaranteed to be 0 on
                        //     the first iteration; therefore, .map() is coerced to
                        //     0 by the the bitwise OR even if a[] is a singleton
    ) | t               //   end of map(); yield t
  :                     // else:
    t += !n             //   increment t if n = 0

```
> 5 votes

# Answer
# Charcoal, 62 bytes

```
⊞υ⟦Ｅη⟦ι⎇⊖ιιθ⟧⁰⟧ＦυＦ‹§ι¹θＦ§ι⁰⊞υ⟦ΦＥ§ι⁰Ｅμ⁻ξ∧π⁼μλ§μ¹⁺§ι¹§λ⁰⟧Ｉ№Ｅυ⊟ιθ

```

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

```
⊞υ⟦Ｅη⟦ι⎇⊖ιιθ⟧⁰⟧

```

Start a breadth-first search with a tuple of a list of steps and remaining counts (except that the count for a single step is the total number of steps) and the number of steps taken so far.

```
Ｆυ

```

Loop over every possible permutation of steps.

```
Ｆ‹§ι¹θ

```

If the total has not been reached, then...

```
Ｆ§ι⁰

```

... loop over the remaining steps, and...

```
⊞υ⟦ΦＥ§ι⁰Ｅμ⁻ξ∧π⁼μλ§μ¹⁺§ι¹§λ⁰⟧

```

... push a tuple of the list with one step removed (entirely if the count falls to zero) and the new position reached.

```
Ｉ№Ｅυ⊟ιθ

```

Count the number of times the desired total was reached exactly.
> 4 votes

# Answer
# , 171 bytes

```
function(N,S){s=S;s[s==1]=N
for(i in 1:N){m=expand.grid(rep(list(S),i))
m=t(m[rowSums(m)==N,])
if(z<-ncol(m))for(j in 1:z){R=m[,j]
t=table(factor(R,S))
F=F+all(t<=s)}}
+F}

```

Try it online!

Times out for large `N`.

This is rough for R. Looking at this recursive solution which is still wrong, but a decent start, should anyone want to pick up where I left off -- note that it requires `S` to be sorted ascending due to `split`.
> 3 votes

# Answer
# Wolfram Language (Mathematica), 119 bytes

```
If[#<1,0,Length@Flatten[Permutations/@(S=Select)[IntegerPartitions[#,All,#2],And@@(#>=#2&@@@S[Tally@#,#&@@#>1&])&],1]]&

```

Try it online!
> 2 votes

# Answer
# Wolfram Language (Mathematica), ~~74~~ ~~65~~ 63 bytes

```
Sum[UnitStep@@(--+#(#-a))Multinomial@@a,{a,FrobeniusSolve@##}]&

```

Try it online!

```
Sum[                                   ,{a,FrobeniusSolve@##}]& (* for each way to climb with the given step increments, sum *)
                         Multinomial@@a                         (* the number of rearrangements *)
    UnitStep@@(--+#(#-a))                                       (* if no quotas are surpassed *)

```

---

### 66 bytes

```
If[#>0,If[##3'~Count~i>=i>1,0,#0[#-i,##2,i]]~Sum~{i,#2},1+Sign@#]&

```

Try it online!

A recursive function. Move the outer condition into the sum to conform to the initial spec: 68 bytes.

```
If[#>0,                     (* if there are still stairs to climb, *)
  If[##3'~Count~i>=i>1,0,   (*   and we haven't used up our quota of i-steps, *)
    #0[#-i,##2,i]]          (*     check how many ways there are after an i-step, *)
   ~Sum~{i,#2},             (*   and add those up for all possible step sizes. *)
  1+Sign@#]&                (* otherwise, check if we overshot. *)

```
> 2 votes

# Answer
# Python 3, 120 bytes

```
def f(z,w,a=0,s=0,i=0):
 for x in w:b=(a or w)[:];b[i]-=1;s+=b[i]*(x-1)>=0and(f(z-x,w,b)if z>x else z==x);i+=1
 return s

```

Try it online!
> 2 votes

# Answer
# Python 3, 75 bytes

```
f=lambda n,s,p=[]:0**n+sum(f(n-d,s,p+1%d*[d])for d in s if p.count(d)<d<=n)

```

Try it online!

Based on Donat's solution.
> 2 votes

# Answer
# Java (JDK), 129 bytes

```
int f(int z,int[]...v){int s=1/~z,i=0,a[];for(int y:v[0])s-=--(a=v[v.length-1].clone())[i++]<0&y>1|y>z?0:f(z-y,v[0],a);return-s;}

```

Try it online!

Reduced from 167 to 161 with hint by ceilingcat.

Further reduced to 153, 136, 132 now.

From 132 to 129, thanks to ceilingcat.
> 2 votes

# Answer
# Scala, 123 118 115 bytes

Thanks to user x2

```
% =>b=>1 to%map{b.flatMap($=>Seq.fill(if($<2)%else $)($))combinations _ flatMap(_.permutations)count(_.sum== %)}sum

```

Input: (#steps)=\>(list). The algorithm creates the list of all allowed steps, analyzes all the permutations of the combinations of n elements (n from 1 to the number of stairs) and counts the ones that sum up to the number of steps

Try it online!
> 2 votes

# Answer
# Perl 5, 75 bytes

```
sub f($z,$w,%a){$z&&map{%b=%a;++$b{$_}>$_&$_>1|$_>$z?():f($z-$_,$w,%b)}@$w}

```

Try it online!

The function returns a list of zeros. Perl will convert it to the number of its elements, when evaluated in scalar context. This will be the result.

Evaluation in scalar context can be forced by a helper function like this:

```
sub g{+&f}

```

In my test cases this not necessary because the result is treated as a scalar value.
> 1 votes

---
Tags: code-golf, restricted-time
---


title: Quickly regrouping lists

text:
# Question
Title: Quickly regrouping lists
Grouping takes a list and splits it into new lists of equal adjacent elements. For example

```
[1,1,2,1,1] -> [[1,1],[2],[1,1]]

```

If you then take the length of these groups you get a new list of integers

```
[1,1,2,1,1] -> [2,1,2]

```

Your task is to write a program that takes a list of positive integers and find the number of times you can group and length it before the resulting list has a single element. For example the list `[1,2,3,3,2,1]` can be regrouped 4 times

```
[1,2,3,3,2,1]
[1,1,2,1,1]
[2,1,2]
[1,1,1]
[3]

```

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

# Test cases

```
[1,2,3,3,2,1] -> 4
[1,2,3,4,5,6,7] -> 2
[1,1,1,1,1,1] -> 1
[2] -> 0
[1,2,4] -> 2
[1,2,2,1,1,2] -> 4
[1,2,2,1,1,2,1,2,2] -> 5
[1] -> 0

```

# Answer
## Haskell, 49 bytes

```
import Data.List
f[_]=0
f c=1+f(length<$>group c)

```

Try it online!
> 7 votes

# Answer
## CJam, 18 bytes

```
q~_,{_e`0f=}*]:,1#

```

Try it online!
> 5 votes

# Answer
# Brachylog, 12 bytes

```
;.{ḅlᵐ}ⁱ⁾l1∧

```

Try it online!

### Explanation

```
;.{   }ⁱ⁾        Iterate Output times the following predicate on the input:
   ḅ               Group consecutive equal elements together
    lᵐ             Map length
         l1∧     The result of this iteration must have length 1

```
> 5 votes

# Answer
# Japt, 12 bytes

```
ÊÉ©1+ßUò¦ ml

```

Test it online!

### Explanation

```
 Ê É © 1+ßUò¦  ml
Ul -1&&1+ßUò!= ml    Ungolfed
                     Implicit: U = input array
Ul -1                Take U.length - 1.
     &&              If this is non-zero:
          Uò!=         Split U between non-equal elements.
               ml      Take the length of each run of equal elements.
         ß             Run the entire program again on the resulting array.
       1+              Add one to the return value.

```

Recursion is a really non-conventional approach for Japt, but it seems to be 4 bytes shorter than the next alternative...
> 3 votes

# Answer
# K (oK), ~~20~~ 19 bytes

**Solution:**

```
#2_{#:'(&~~':x)_x}\

```

Try it online!

**Examples:**

```
#2_{#:'(&~~':x)_x}\1 2 3 3 2 1
4
#2_{#:'(&~~':x)_x}\1 2 3 4 5 6 7
2
#2_{#:'(&~~':x)_x}\1 1 1 1 1 1
1
#2_{#:'(&~~':x)_x}\1#2
0
#2_{#:'(&~~':x)_x}\1 2 4
2

```

**Explanation:**

This one is pretty simple, am wondering if there is an even better approach though... Find the indices where the input differs, split at those indices and then count the length of each sub-list. Iterate until results converge to 1.

```
#2_{#:'(&~~':x)_x}\ / the solution
   {             }\ / scan over lambda until results converge
                x   / implicit input
               _    / cut at indices
       (      )     / do this together
         ~~':x      / differ... not (~) match (~) each-previous (':) x)
        &           / indices where true
    #:'             / count (#:) each (')
 2_                 / drop first two results
#                   / count result

```

**Notes:**

The following **14 byte** solution works for all **except** a single-item list:

```
#1_(-':&~~':)\

```

Try it online!
> 3 votes

# Answer
# Husk, 8 bytes

-1 byte thanks to @Zgarb!

```
←Vε¡(mLg

```

Try it online!

### Explanation

```
←Vε¡(mLg)  -- example input: [1,2,3,3,2,1]
   ¡(   )  -- repeatedly apply the function & collect results
    (  g)  -- | group: [[1],[2],[3,3],[2],[1]]
    (mL )  -- | map length: [1,1,2,1,1]
           -- : [[1,2,3,3,2,1],[1,1,2,1,1],[2,1,2],[1,1,1],[3],[1],[1],...
 V         -- index where
  ε        -- | length is <= 1: [0,0,0,0,1,1...
           -- : 5
←          -- decrement: 4

```
> 3 votes

# Answer
# , 25 23 bytes

1 byte saved thanks to streetster

1 byte saved thanks to FrownyFrog

```
2#@}.#;.1@(0,2=/\])^:a:

```

Try it online!

Initial solution:

```
_2+[:#(#;.1~1,2~:/\])^:a:

```

Try it online!

## Explanation

```
      (               )^:a: - repeat until result stops changing, store each iteration
        ;.1~                - cut the input (args swapped)
            1,2~:/\]      - where the items are no longer the same
       #                    - and take the length of the sublists
 2+[:#                      - finally subtract 2 from the number of steps

```
> 3 votes

# Answer
# C (gcc), ~~108~~ 103 bytes

```
j,k,n;f(A,l)int*A;{for(j=k=n=0;j<l;j++)n=A[j]-A[k]?A[k++]=n,A[k]=A[j],1:n+1;A=l>1?-~f(A,k,A[k++]=n):0;}

```

Try it online!

# Explanation (108 bytes version)

```
j,k,n;                // array pos, group pos, group val
f(A,l)int*A;{         // function takes array and length
 for(j=k=n=0;j<l;j++) // initialize, loop through array
  if(n++,             // increase n (*), check if group ended
  A[j]-A[k])          // group ended
   A[k++]=--n,        // advance group pos, decrease n, counteracting (*)
   A[k]=A[j],         // store new group type
   n=1;               // group is at least one long
 A=l>1?               // check if array length is larger than one
  -~f(A,k,A[k++]=n)   // fix last group length, enter recursion
  :0;}                // array length is less than two, return zero

```

Try it online!
> 2 votes

# Answer
## JavaScript (ES6), ~~67~~ ~~65~~ 63 bytes

```
f=a=>a[1]?1+f(q=j=i=[],a.map(x=>x^a[++i]?j=!q.push(++j):++j)):0

```

Oddly enough, JavaScript and Japt seem to have the same shortest algorithm for once...
> 2 votes

# Answer
# Stax, 9 bytes

```
ÆÑfá╒]`*Ä

```

Run and debug it online

The ascii representation of the same program is this.

```
{D}{|RMHgf%

```

This uses a stax feature called a generator that produces value according to transformation and filter blocks.

```
{ }            the filter for the generator
 D             tail of array; this is truthy for length >= 2
   {    gf     generator block - termination condition is when the filter fails
    |R         run-length encode into pairs [element, count]
      M        transpose matrix
       H       last element
          %    length of final generated array

```
> 2 votes

# Answer
# APL (Dyalog Unicode), ~~33~~ 24 bytes

Saved 9 bytes thanks to @Adám!

```
{1=≢⍵:0⋄1+∇2-/⍸2≠/0,⍵,0}

```

Try it online!

{
 1=≢⍵           ⍝If the length (≢) of the input (⍵) is 1
  :0            ⍝return 0, as we can't go further

⋄1+             ⍝Otherwise, add 1 to the result of the next call:
  ∇2-/⍸2≠/0,⍵,0 ⍝Next step
         0,⍵,0  ⍝ Put 0s on both sides (1 1 1 2 2 1 -> 0 1 1 1 2 2 1 0)
      2≠/       ⍝Pairwise reduce with ≠
                ⍝0 1 1 1 2 2 1 0 -> 1 0 0 1 0 1 1
                ⍝There is now a 1 wherever a run starts
      ⍸          ⍝Indices of 1s (indices where runs start)
                ⍝1 0 0 1 0 1 1 -> 1 4 6 7
   2-/          ⍝Pairwise reduce with subtraction (length of each run)
                ⍝1 4 6 7 -> 3 2 1
 ∇              ⍝Call itself with new list
}
```
</code></pre>
> 2 votes

# Answer
# Jelly, 10 bytes

```
ŒgL€$ḊÐ¿L’

```

Try it online!
> 1 votes

# Answer
# CJam, 19 bytes

```
q~{_);}{_e`0f=}w],(

```

Try it online!
> 1 votes

# Answer
# CJam, 20 bytes

```
l~{__,(}{e`z0=}w;;],

```

Try it online!
> 1 votes

# Answer
# SmileBASIC, ~~110~~ 108 bytes

```
DEF R L,J
K=LEN(L)FOR I=1TO K
N=POP(L)IF O-N THEN UNSHIFT L,0
INC L[0]O=N
NEXT
IF I<3THEN?J ELSE R L,J+1
END

```

Call function as `R list,0`; output is printed to the console.
> 1 votes

# Answer
# Python 2, 84 bytes

```
f=lambda a:len(a)>1and-~f(eval(''.join('1'+',+'[x==y]for x,y in zip(a,a[1:]))+'1,'))

```

**Try it online!**

### How?

`f` is a recursive function which, if its input, `a`, has length 2 or more (`len(a)>1`) returns `1+f(x)`* where `x` is the group lengths of `a`; while if its input is length 1 or 0 returns `False` (equal to 0 in Python) - this is because the right hand side of the `and` does not get evaluated when the left is falsey.

* `-~f(x)` is `-(-1 - f(x))` but can abut the `and` unlike `1+f(x)` or `f(x)+1`)

The group lengths are calculated by creating code which is then evaluated with `eval(...)`. The code created is something like `1,1,1+1+1,1,1+1,1,` which evaluates to a tuple like `(1,1,3,1,2,1)`.

The code is created by zipping through `a` and `a` without its head (`...for x, y in zip(a,a[1:])` making `x` and `y` each of the adjacent pairs in `a`. If the pair are equal `x==y` evaluates to `True` (1) otherwise `False` (0) - this result is used to index into the string `,+` yielding `+` and `,` respectively and each resulting character is preceded by a `1` (`'1'+...`) - the whole thing then has a final, trailing `1,` appended. For example if `a` were `[5,5,2,9,9,9]` then the `x,y` pairs would be `(5,5)(5,2)(2,9)(9,9)(9,9)` making the equalities `10011` then the characters would be `+,,++`, which with the preceding `1`s becomes `1+1,1,1+1+` and the final trailing `1,` making `1+1,1,1+1+1,` which evaluates to `(2,1,3)` as required.

Note that the trailing `,` ensures that an input with a single group is evaluated as a tuple rather than an integer (i.e. `[3,3]` -\> `1+1,` -\> `(2)` rather than `[3,3]` -\> `1+1` -\> `2`)
> 1 votes

# Answer
# Perl 6, 52 bytes

```
{+($_,*.comb(/(\d+)[" "$0»]*/).map(+*.words)...^1)}

```

Test it

## Expanded:

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

  + (              # turn the following into a Numeric (get the count)

      $_,          # seed the sequence with the input

      *.comb(      # turn into a string, and grab things that match:

        /          # regex
          ( \d+ )  # a run of digits (number)
          [
            " "    # a space
                   # (gets inserted between elements of list when stringified)

            $0     # another instance of that number
            »      # make sure it isn't in the middle of a number

          ]*       # get as many as possible
        /
      ).map(
        +*.words  # turn each into a count of numbers
      )

      ...^        # keep doing that until (and throw away last value)

      1           # it gives a value that smart-matches with 1
                  # (single element list)
  )
}

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), 32 bytes

Saved 2 bytes thanks to Martin Ender. Using CP-1252 encoding, where `±` is one byte.

```
±{_}=0;±x_:=1+±(Length/@Split@x)

```

Try it online!
> 1 votes

# Answer
# Perl 5, ~~53~~ ~~50~~ ~~49~~ 45 bytes

Includes `+3` for `-p`

Give the list of numbers as one line on STDIN

```
#!/usr/bin/perl -p
s%%$\+=1<s:\d+:$.++x($'-$&and$.=1):eg%eg}{

```

Try it online!
> 1 votes

# Answer
# Ruby, ~~54 56 55~~ 54 bytes

```
g=->l,d=0{l[1]?g[l.chunk(&:i).map{|i,j|j.size},d+1]:d}

```

Try it online!
> 1 votes

# Answer
# 05AB1E, 9 bytes

```
[Dg#γ€g]N

```

Try it online!

**Explanation**

```
[Dg#   ]     # loop until the length of the current value is 1
    γ        # split into groups of consecutive equal elements
     €g      # get length of each
        N    # push the iteration variable N

```
> 1 votes

# Answer
# Jelly, 6 bytes

```
ŒɠƬṖṖL

```

Try it online!

I assume that `Œɠ` did not exist when Dennis wrote his solution, and it wouldn't surprise me if this challenge had even inspired him to add it, but it's worth showing that this solution is possible now.
> 1 votes

# Answer
# Python 2, 85 bytes

```
from itertools import*
f=lambda a:~-len(a)and-~f([len(list(v))for k,v in groupby(a)])

```

Try it online!
> 0 votes

# Answer
# , ~~51~~ 45 bytes

```
f=function(a)"if"(sum(a|1)>1,f(rle(a)$l)+1,0)

```

Try it online!

Recursively take the length of the run length encoding and increment the counter.
> 0 votes

# Answer
# Retina 0.8.2, 31 bytes

```
,.*
$&_
}`(\b\d+)(,\1)*\b
$#2
_

```

Try it online! Link includes test cases. Explanation:

```
,.*
$&_

```

If there is a comma, we're going to make another iteration, so append a count character.

```
}`(\b\d+)(,\1)*\b
$#2

```

Replace each run with its decremented length. The above stages repeat until there are no commas left.

```
_

```

Count the number of iterations.
> 0 votes

# Answer
# Brain-Flak, 78 bytes

```
({}<>)<>({()<(<>{}<(())><>){({}[({})]<>){((<{}>))}{}((){})<>}<>{}({}<>)<>>}{})

```

Try it online!
> 0 votes

# Answer
# Pyth, 9 bytes

```
ltt.uhMr8

```

**Test suite!**
> 0 votes

# Answer
# Red, 140 bytes

```
func[b][n: 0 while[(length? b)> 1][l: copy[]parse split form b" "[any[copy s[set t string! thru any t](append l length? s)]]b: l n: n + 1]n]

```

Try it online!

I just wanted to give Red's Parse dialect another try.

Ungolfed

```
f: func [b] [
    n: 0
    while [(length? b) > 1][
        l: copy []
        parse split form b " " [
            any [copy s [set t string! thru any t]
                (append l length? s)]
        ]
        b: l
        n: n + 1
    ]
    n
]

```
> 0 votes

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


title: Black and White Rainbows

text:
# Question
Title: Black and White Rainbows
Given an image that has only black and white pixels and an (x,y) location that's a white pixel, color the white pixels based on their minimal Manhattan distance from (x,y) in a path that only involves traversing other white pixels.

The hue of the colored pixels must be proportional to their distance from (x,y), so the pixel at (x,y) will have a hue of 0° (pure red) and the pixels farthest away from (x,y) will have a hue of 360° (also red), with the other hues blending seamlessly and linearly in between. The saturation and value must both be 100%.

If a white pixel is not connected to (x,y) through other white pixels then it must remain white.

## Details

* The input will consist of the file name of the image or the raw image data, plus the x and y integers.
* The output image may be saved to a file or piped raw to stdout in any common image file format, or simply displayed.
* The x value is 0 on the leftmost pixels, and increases going right. The y value is 0 in the topmost pixels and increases going down. (x,y) will always be in the image bounds.
* Both full programs and functions are allowed.

**The shortest code in bytes wins.**

## Examples

***All these images have been downsized to save space. Click them to view at full size.***

Input image:

`(x,y) = (165,155)` and `(x,y) = (0,0)`

---

Input image and output with `(x,y) = (0,0)`:

---

Input image and output with `(x,y) = (600,350)`:

---

Input image and output with `(x,y) = (0,0)`:

---

Input image and output with `(x,y) = (0,0)`:

---

**Optional -30% bonus:** use Euclidean distance. A suggestion for your algorithm is as follows (general outline):

1. Have a start pixel.
2. Flood-fill from that pixel.
3. For every pixel reached in the flood fill,
4. Move from the start pixel to that pixel in half-unit steps, in a straight line.
5. At each step, apply `int()` to the x and y coordinates. If the pixel at these coordinates is black, stop. Otherwise, continue. (This is a line-of-sight method.)
6. Any reached pixel that borders a white pixel and/or a pixel that was previously labeled with a significantly higher distance (i.e., +10) becomes a start pixel.

In a more meta sense, this algorithm spreads out to every pixel reachable in a straight line from start/already-colored pixels, then "inches" around edges. The "significantly higher distance" bit is intended to speed up the algorithm. Honestly, it doesn't really matter *how* you implement Euclidean distance, it just has to look pretty much like this.

This is what the first example looks like with Euclidean distance, using the algorithm above:

Input image and `(x,y) = (165,155)`

---

**Many thanks to Calvin'sHobbies and trichoplax for helping write this challenge! Have fun!**

# Answer
> 34 votes
# Matlab, ~~255 245~~ 231 bytes

This expects the image name first, then `y` and then `x`.

```
I=@input;i=imread(I('','s'));[r,c]=size(i);m=zeros(r,c);m(I(''),I(''))=1;M=m;d=m;K=[1,2,1];for k=1:r*c;d(m&~M)=k;M=m;m=~~conv2(m,K'*K>1,'s');m(~i)=0;end;z=max(d(:));v=[1,1,3];imshow(ind2rgb(d,hsv(z)).*repmat(m,v)+repmat(~d&i,v),[])

```

I implemented the flood filling (or 'dijkstra for 4-neighbourhoods' if you want) roughly by first creating a mask where the seed pixel is set to 1 and with a distance accumulator (both of the size of the image) and then repeating following steps:

* convolute the mask with a 4 neighbourhood kernel (this is the very inefficient part)
* set all nonzero pixels of the mask to 1
* set all the black pixels of the image to zero
* set all values in the accumulator where the mask has changed in this step to `k`
* increase `k`
* repeat until there are no more changes in the mask (I actually do not check this condition, but just use the number of pixels in the image as an upper bound, which is usually a very bad upper bound, but this is codegolf=)

This leaves us with the manhattan distances of every pixel to the seed pixel in the distance accumulator. Then we create a new image by going throu the given range of colours and map the "first" hue to the value zero and the "last" hue to the maximal distance.

# Examples

As a bonus, here a pretty picture of how the distance gets calculated. brighter = farther away.

# Answer
> 3 votes
## Blitz 2D/3D, 3068 * 0.7 = 2147.6

This is the reference implementation for the Euclidean algorithm, golfed.

```
image=LoadImage("HueEverywhere_example1.png")
Graphics ImageWidth(image),ImageHeight(image)
image=LoadImage("HueEverywhere_example1.png")
x=0
y=0
w=ImageWidth(image)
h=ImageHeight(image)
Type start
Field x,y
Field dis#
Field nex.start
End Type
Type cell
Field x,y
Field dis#
End Type
Type oldCell
Field x,y
Field dis#
End Type
initCell.start=New start
initCell\x=x
initCell\y=y
initCell\dis=1
Dim array#(w,h)
imgBuff=ImageBuffer(image)
LockBuffer(imgBuff)
s.start=First start
colr=col(0,0,0)
colg=col(0,0,1)
colb=col(0,0,2)
newcol=colr*256*256+colg*256+colb
WritePixelFast(s\x,s\y,newcol,imgBuff)
While s<>Null
c.cell=New cell
c\x=s\x
c\y=s\y
c\dis=s\dis
While c<>Null
For dy=-1To 1
For dx=-1To 1
If dx*dy=0And dx+dy<>0
nx=c\x+dx
ny=c\y+dy
ndis#=s\dis+Sqr#((nx-s\x)*(nx-s\x)+(ny-s\y)*(ny-s\y))
If nx >= 0And nx<w And ny >= 0And ny<h
If KeyHit(1)End
pixcol=ReadPixelFast(nx,ny,imgBuff)
If pixcol<>-16777216
If array(nx,ny)=0Or ndis<array(nx,ny)
check=1
steps=Ceil(dis)*2
For k=0 To steps
r#=k*1./steps
offx#=Int(s\x+(c\x-s\x)*r)
offy#=Int(s\y+(c\y-s\y)*r)
pixcol2=ReadPixelFast(offx,offy,imgBuff)
If pixcol2=-16777216
check=0
Exit
EndIf
Next
If check
array(nx,ny)=ndis
newCell.cell=New cell
newCell\x=nx
newCell\y=ny
newCell\dis=ndis
EndIf
EndIf
EndIf
EndIf
EndIf
Next
Next
o.oldCell=New oldCell
o\x=c\x
o\y=c\y
o\dis=c\dis
Delete c
c=First cell
Wend
For o.oldCell=Each oldCell
bordersWhite=0
For dy=-1To 1
For dx=-1To 1
If dx<>0Or dy<>0
nx=o\x+dx
ny=o\y+dy
If nx>=0And nx<w And ny>=0And ny<h
pixcol=ReadPixelFast(nx,ny,imgBuff)
If (pixcol=-1And array(nx,ny)=0)Or array(nx,ny)>o\dis+9
bordersWhite=1
Exit
EndIf
EndIf
EndIf
Next
If bordersWhite Exit
Next
If bordersWhite
ns.start=New start
ns\x=o\x
ns\y=o\y
ns\dis=o\dis
s2.start=First start
While s2\nex<>Null
If ns\dis<s2\nex\dis
Exit
EndIf
s2=s2\nex
Wend
ns\nex=s2\nex
s2\nex=ns
EndIf
Delete o
Next
EndIf
s2=s
s=s\nex
Delete s2
Wend
maxDis=0
For j=0To h
For i=0To w
If array(i,j)>maxDis maxDis=array(i,j)
Next
Next
For j=0To h
For i=0To w
dis2#=array(i,j)*360./maxDis
If array(i,j) <> 0
colr=col(dis2,0,0)
colg=col(dis2,0,1)
colb=col(dis2,0,2)
newcol=colr*256*256+colg*256+colb
WritePixelFast(i,j,newcol,imgBuff)
EndIf
Next
Next
UnlockBuffer(imgBuff)
DrawImage image,0,0
Function col(ang1#,ang2#,kind)
While ang1>360
ang1=ang1-360
Wend
While ang1<0
ang1=ang1+360
Wend
While ang2>180
ang2=ang2-360
Wend
While ang2<-180
ang2=ang2+360
Wend
a3#=ang2/180.
If ang1>300
diff#=(ang1-300)/60.
r=255
g=0
b=255*(1-diff)
ElseIf ang1>240
diff#=(ang1-240)/60.
r=255*diff
g=0
b=255
ElseIf ang1>180
diff#=(ang1-180)/60.
r=0
g=255*(1-diff)
b=255
ElseIf ang1>120
diff#=(ang1-120)/60.
r=0
g=255
b=255*diff
ElseIf ang1>60
diff#=(ang1-60)/60.
r=255*(1-diff)
g=255
b=0
Else
diff#=(ang1-00)/60.
r=255
g=255*diff
b=0
EndIf
If a3>0
r2=r+a3*(255-r)
g2=g+a3*(255-g)
b2=b+a3*(255-b)
Else
r2=r+a3*r
g2=g+a3*g
b2=b+a3*b
EndIf
If r2>255
r2=255
ElseIf r2<0
r2=0
EndIf
If g2>255
g2=255
ElseIf g2<0
g2=0
EndIf
If b2>255
b2=255
ElseIf b2<0
b2=0
EndIf
If kind=0
Return r2
ElseIf kind=1
Return g2
ElseIf kind=2
Return b2
Else
Return 0
EndIf
End Function

```

Actually, I kinda hate how unreadable this is compared to the original. (Which is, incidentally, 5305 bytes.) Actually, I could lop off quite a few more bytes by using one-character variable names for everything, but this is kinda ridiculous enough already. And it's not winning any time soon. :P

# Answer
> 2 votes
## C++ / SFML : ~~1271~~ ~~1235~~ 1226 bytes

-36 bytes thanks to user202729 -9 bytes thanks to Zacharý

```
#include<SFML\Graphics.hpp>
#include<iostream>
#define V std::vector
#define P e.push_back
#define G(d,a,b,c) case d:return C(a,b,c);
#define FI(r,s)(std::find_if(e.begin(),e.end(),[&a](const T&b){return b==T{a.x+(r),a.y+(s),0};})!=e.end())
using namespace sf;using C=Color;struct T{int x,y,c;bool operator==(const T&a)const{return x==a.x&&y==a.y;}};int max(V<V<int>>&v){int m=INT_MIN;for(auto&a:v)for(auto&b:a)m=b>m?b:m;return m;}C hsv2rgb(int t){int ti=t/60%6;float f=t/60.f-ti,m=(1.f-f)*255,n=f*255;switch(ti){G(0,255,n,0)G(1,m,255,0)G(2,0,255,n)G(3,0,m,255)G(4,n,0,255)G(5,255,0,m)default:throw std::exception();}}void r(Image&a,int x,int y){auto d=a.getSize();V<V<int>>m(d.x,V<int>(d.y));int i=0,j,c=0,t;for(;i<d.y;++i)for(j=0;j<d.x;++j)m[j][i]=a.getPixel(j,i)==C::Black?-1:0;V<T>e{{x,y,1}};while(e.size()){V<T>t=std::move(e);for(auto&a:t){m[a.x][a.y]=a.c;if(a.x>0&&m[a.x-1][a.y]==0&&!FI(-1,0))P({a.x-1,a.y,a.c+1});if(a.y>0&&m[a.x][a.y-1]==0&&!FI(0,-1))P({a.x,a.y-1,a.c+1});if(a.x<m.size()-1&&m[a.x+1][a.y]==0&&!FI(1,0))P({a.x+1,a.y,a.c+1});if(a.y<m[0].size()-1&&m[a.x][a.y+1]==0&&!FI(0,1))P({a.x,a.y+1,a.c+1});}}c=max(m)-1;for(i=0,j;i<d.y;++i)for(j=0;j<d.x;++j)if(m[j][i]>0)a.setPixel(j,i,hsv2rgb(360.f*(m[j][i]-1)/c));}

```

The `sf::Image` parameter is also the output ( will be modified ). You can use it like that :

```
sf::Image img;
if (!img.loadFromFile(image_filename))
    return -1;

r(img, 0, 0);

if (!img.saveToFile(a_new_image_filename))
    return -2;

```

The first parameter is the image input ( and output ), the second and third parameters are the `x` and `y` parameter where it needs to start

# Answer
> 2 votes
# Matlab with DIPimage, 118 bytes - 30% = 82.6

```
function F(f,x,y),a=readim(f);m=a{1}>0;s=m|1;s(x,y)=0;h=gdt(s,[],m);n=~isinf(h);a(n)=lut(h(n),255*hsv(fix(max(h(n)))))

```

DIPimage has a function to compute Euclidean geodesic distance transform (`gdt`). It uses the Fast Marching algorithm, which produces a very reasonable approximation to Euclidean distances. See the docs.

DIPimage automatically displays the image

I'm using the idea from flawr's answer to create a colormap using `hsv`.

# Answer
> 1 votes
# C++, 979 969 898 859 848 bytes

```
#include<cstdio>
#include<cstdlib>
#define K 400
#define L 400
#define M (i*)malloc(sizeof(i))
#define a(C,X,Y)if(C&&b[Y][X].c){t->n=M;t=t->n;b[Y][X].d=d+1;t->n=0;t->c=X;t->d=Y;}
#define A(n,d)case n:d;break;
#define F fgetc(f)
#define W(A,B) for(A=0;A<B;A++){
struct i{int c;int d;int v;i*n;}b[L][K]={0},*h,*t;float m=0;int main(){FILE*f=fopen("d","r+b");int x,y,d=0;W(y,L)W(x,K)b[y][x].c=F<<16|F<<8|F;}}rewind(f);x=165,y=155;h=M;h->c=x;h->d=y;b[y][x].d=d;t=h;while(h){i*p=b[h->d]+h->c;if(p->v)h=h->n;else{p->v=1;x=h->c;y=h->d;d=p->d;m=d>m?d:m;a(x>0,x-1,y)a(x<K-1,x+1,y)a(y>0,x,y-1)a(y<L-1,x,y+1)}}W(y,L)W(x,K)i p=b[y][x];unsigned char n=-1,h=p.d/(m/n),R=h%43*6,Q=n*(n-(n*R>>8))>>8,t=n*(n-(n*(n-R)>>8))>>8,r,g,b;switch(h/43){A(0,n,t,0)A(1,Q,n,0)A(2,0,n,t)A(3,0,Q,n)A(4,t,0,n)A(5,n,0,Q)}d=h?r|g<<8|b<<16:p.c?-1:0;fwrite(&d,1,3,f);}}}

```
* Input: RGB data file (contained in file: d)
* Output: RGBA RGB data file (outputted in file: d)
* Example: convert -depth 8 -size "400x400" test.png d.rgb && mv -f d.rgb d && g++ -o test main.c && ./test
* NOTE: the image size and start are controlled at a source level, if this is an issue add 50 bytes or something -- I just didn't care to change it to be honest.

Not exactly a direct "ungolf" but this was a C prototype I mocked up first:

```
#include "stdio.h"
#include "stdlib.h"

struct i{
    unsigned int c;
    int d;
    int v;
}b[400][400]={0};

typedef struct q{
    int x;
    int y;
    struct q *n;
}q;
q *qu;
q *t;
float m=0;
int get_dist(int x, int y)
{
    int d = 0;

}

void flood(int x,int y,int d){
    qu=malloc(sizeof(q));
    qu->x=x;qu->y=y;b[y][x].d=d;
    t=qu;
    while(qu){
        struct i *p = &b[qu->y][qu->x];
        if(p->v){qu=qu->n; continue;}
        p->v=1;x=qu->x;y=qu->y;d=p->d;
        #define a(C,X,Y) if(C&&b[Y][X].c){t->n=malloc(sizeof(q));t=t->n;b[Y][X].d=d+1;t->n=0;t->x=X;t->y=Y;}
        a(x>0,x-1,y);
        a(x<399,x+1,y);
        a(y>0,x,y-1);
        a(y<399,x,y+1);
        m=p->d>m?p->d:m;
    }
}

unsigned int C(int h)
{
    int r=0,g=0,b=0;
    int s=255,v=255;
    unsigned char R, qq, t;

    R = h%43*6;

    qq = (v * (255 - ((s * R) >> 8))) >> 8;
    t = (v * (255 - ((s * (255 - R)) >> 8))) >> 8;

    switch (h / 43){
        case 0: r = v; g = t; break;
        case 1: r = qq; g = v; break;
        case 2: g = v; b = t; break;
        case 3: g = qq; b = v; break;
        case 4: r = t; b = v; break;
        case 5: r = v; b = qq; break;
    }

    return r|(g<<8)|(b<<16)|255<<24;
}

#define F fgetc(f)
int main()
{
    FILE *f=fopen("d", "r+b");
    for(int y=0; y<400; y++){
        for(int x=0; x<400; x++){
            b[y][x].c = (F<<24)|(F<<16)|(F<<8);
        }
    }
    rewind(f);
    flood(165,155,1);
    m/=255.f;
    for(int y=0; y<400; y++){
        for(int x=0; x<400; x++){
            struct i p = b[y][x];
            unsigned int h = C(p.d/m);
            int o = p.c?-1:255<<24;
            if(p.d)fwrite(&h,4,1,f);
            else fwrite(&o,4,1,f);
        }
    }
}

```

Many concepts remain similar, but there are certainly a myriad of tiny changes. To compile that as C you do need to use C11 (C99 will probably work but I only strictly tested in C11).
I quite enjoyed this challenge, thanks for giving me the idea to try something new :).
Edit: Golf'd a bit better.
Edit2: Merged two structs so my pixel struct and queue are the same, bit more macro abuse, and reflowed uses of 255 such that it can be defined as -1 when defining a series of unsigned chars, and lastly removed a function call.
Edit3: Reused a few more variables, operator precedence tweaks, and output converted to RGB saving the alpha channel
Edit4: I think I am done with this now, some pointer arithmetic changes and slight control flow tweaks.

# Answer
> 0 votes
# Python 3 and matplotlib, ~~251~~ 227 bytes

```
from pylab import*
def f(i,p):
 h,w,_=i.shape;o=ones((h,w))/0;q=[p+[0]]
 while q:
  x,y,d=q.pop(0)
  if w>x>=0and h>y>=0and i[y,x,0]:o[y,x]=d;i[y,x]=0;d+=1;q+=[[x-1,y,d],[x+1,y,d],[x,y-1,d],[x,y+1,d]]
 imshow(i);imshow(o,'hsv')

```

The input is an MxNx3 numpy array as returned by matplotlib's `imread()` function. The input is modified by the function so it should be copied beforehand. It displays the image automatically if matplotlib is in "interactive" mode; otherwise a call to `show()` should be added for another 7 bytes.

The output is created by first displaying the original image and then displaying the rainbow image overtop of it. Matplotlib conveniently treats inf and nan as transparent so the black and white image shows through.

---
Tags: code-golf, graphical-output, image-processing, path-finding
---


# Question
Title: Longest word using a single row of the qwerty keyboard
The three rows of the qwerty keyboard are `qwertyuiop`, `asdfghjkl` and `zxcvbnm`. Your task is to find the longest word that can be typed using only one row of the keyboard, from a given list of words.

Sample input 1

```
artist
home
gas
writer
geology
marine
twerp

```

Output

```
writer

```

(Of the given words, only `gas`, `writer` and `twerp` can be written using a single row, and `writer` is the longest)

The words may not be actual words (so don't assume the third row to be invalid). However, you can assume that there will always be exactly one answer (no more, no less).

Sample input 2

```
wrhuji
bxnzmmx
gllwssjjd
vnccbb
lrkjhgfdsa
tttttt

```

Output

```
bxnzmmx

```

Additional punctuation and whitespaces can be provided in input (as per language requirements). However, no extra output should be given. Input and output are in lower case. **Shortest code wins.**

# Answer
> 19 votes
## Python 2, 84 bytes

```
lambda l:max(l,key=lambda w:(-len({"asdfghjklzxcvbnm".find(c)/9for c in w}),len(w)))

```

Finds the `max` of the input, comparing by fewer keyboard rows spanned, then in increasing length. The keyboard row value is extracted by `"asdfghjklzxcvbnm".find(c)/9`, which takes the middle row to `0`, the bottom row to `1`, and the top row, which is excluded, to `-1`, since `find` gives `-1` for missing values.

Other attempts:

```
lambda l:max((-len({"asdfghjklzxcvbnm".find(c)/9for c in w}),len(w),w)for w in l)[2]
lambda l:max(l,key=lambda w:len(w)-1./len({"asdfghjklzxcvbnm".find(c)/9for c in w}))
lambda l:max([w for w in l if len({"asdfghjklzxcvbnm".find(c)/9for c in w})<2],key=len)

```

# Answer
> 13 votes
# Japt, ~~32~~ 30 bytes

```
;Uf_¬£DbXu)f10Ãä¥ eÃn@Yl -XlÃg

```

Test it online! Input is an array of strings.

### How it works

```
;Uf_  ¬ £  DbXu)f10Ã ä¥  eÃ n@  Yl -XlÃ g
;UfZ{Zq mX{DbXu)f10} ä== e} nXY{Yl -Xl} g

         // Implicit: U = input array of strings
;        // Reset variables A-L to various values.
         // D is set to the string "QWERTYUIOP\nASDFGHJKL\nZXCVBNM".
UfZ{   } // Take U and filter to only the items Z that return truthily to this function:
Zq       //  Split Z into chars, then
mX{    } //  map each char X by this function:
DbXu)    //   Return D.indexOf(X.toUpperCase()),
f10      //   floored to a multiple of 10.
         //  This maps each char to 0 for the top row, 10 for the middle, 20 for the bottom.
q ä==    //  Split the resulting string into chars and check each pair for equality.
e        //  Check that every item in the result is truthy. This returns true if all chars
         //  are on the same row; false otherwise.
         // Now we have only the words that are entirely on one row.
nXY{   } // Sort by passing each two args X and Y into this function:
Yl -Xl   //  Return Y.length - X.length. Sorts the longest to the front.
g        // Get the first item in the resulting array. Implicitly output.

```

# Answer
> 11 votes
# Python 2.5+ and 3, 93 bytes

Had to test how many strokes for this approach; this uses the fact that `a.strip(b)` results in empty string if `a` solely consists of characters that occur in b.

The function takes list of strings and returns a string.

```
lambda a:max(a,key=lambda x:(~all(map(x.strip,['qwertyuiop','asdfghjkl','zxcvbnm'])),len(x)))

```

# Answer
> 8 votes
## Retina, 73 bytes

```
G`^([eio-rtuwy]+|[adfghjkls]+|[bcmnvxz]+)$
1!`(.)+(?!\D+(?<-1>.)+(?(1)!))

```

Try it online!

Conclusion: Retina needs a sorting stage.

### Explanation

```
G`^([eio-rtuwy]+|[adfghjkls]+|[bcmnvxz]+)$

```

This is a grep stage: it only keeps lines which are matched by the regex. I.e. those which are formed exclusively from one of those character classes.

```
1!`(.)+(?!\D+(?<-1>.)+(?(1)!))

```

Now we just need to find the largest of the remaining strings. We do this by matching all words which are at least as long than all the words after them. The `1` is a new addition to Retina (released two days ago), which limits this match stage to considering only the first such match. And `!` instructs Retina to print the match (instead of counting it).

# Answer
> 6 votes
## Java, ~~154~~ 142 or ~~142~~ 130 bytes

Because, ya know, Java.

C#, for comparison.

146 bytes if input has to be a single string with values separated by `\n`:

```
s->java.util.Arrays.stream(s.split("\n")).filter(g->g.matches("[wetyuio-r]*|[asdfghjkl]*|[zxcvbnm]*")).max((a,b)->a.length()-b.length()).get()

```

134 bytes if I can assume input as String\[\] instead:

```
s->java.util.Arrays.stream(s).filter(g->g.matches("[wetyuio-r]*|[asdfghjkl]*|[zxcvbnm]*")).max((a,b)->a.length()-b.length()).get()

```

Slightly ungolfed:

```
UnaryOperator<String> longestQwertyStr = s ->
        java.util.Arrays.stream(s.split("\n")) // Split string input over `\n` and convert to Stream<String>
                .filter(g->g.matches("[wetyuio-r]*|[asdfghjkl]*|[zxcvbnm]*")) // Filter to Strings that only use characters from a single row
                .max((a,b)->a.length()-b.length()) // Find the max by comparing String length
                .get(); // Convert from Optional<String> to String and implicit return single statement lambda

```

Second lambda is a `Function<String[],String>`.

# Answer
> 4 votes
# Python 3, 98

Saved 5 bytes thanks to Kevin.
Saved 3 bytes thanks to PM 2Ring.
Saved 3 bytes thanks to Antti Haapala.

Brute forcing it at the moment. I filter the words down to only those contained by a single row, and then sort for max string length.

```
lambda a:max(a,key=lambda x:(any(map(set(x).__le__,['qwertyuiop','asdfghjkl','zxcvbnm'])),len(x)))

```

Test cases:

```
assert f(['asdf', 'qwe', 'qaz']) == 'asdf'
assert f('''artist
home
gas
writer
geology
marine
twerp'''.splitlines()) == 'writer'
assert f('''wrhuji
bxnzmmx
gllwssjjd
vnccbb
lrkjhgfdsa
tttttt'''.splitlines()) == 'bxnzmmx'

```

# Answer
> 4 votes
# Jelly, ~~40~~ 34 bytes

```
p“£vẈ¬ḣ“£AS°GƤg“£ḷḳƤ²ƤȤḤ»f/€fµL€Mị

```

Try it online!

### How it works

```
p“£vẈ¬ḣ“£AS°GƤg“£ḷḳƤ²ƤȤḤ»f/€fµL€Mị

 “£vẈ¬ḣ“£AS°GƤg“£ḷḳƤ²ƤȤḤ»           Use dictionary compression to yield
                                    ['quipo twyer', 'adj flash jg', 'bcmnz xv'].
p                                   Cartesian product; for all pairs of an input
                                    string and one of the rows.
                         f/€        Reduce each pair by filter, keeping only the
                                    letters in the input string that are on that
                                    particular keyboard row.
                            f       Filter the results, keeping only filtered words
                                    that occur in the input.
                             µ      Begin a new chain.
                              L€    Get the length of each kept word.
                                M   Get the index corr. to the greatest length.
                                 ị  Retrieve the word at that index.

```

# Answer
> 3 votes
## PowerShell v2+, 72 bytes

```
($args-match"^([qwertyuiop]+|[asdfghjkl]+|[zxcvbnm]+)$"|sort Length)[-1]

```

Takes input via command-line arguments as `$args`, then uses the `-match` operator with a regex to select only the words that are exclusively made up of one keyboard row. We pipe those results into `Sort-Object` that sorts by the property `Length`. We can do this since strings in PowerShell are all of the `System.String` type, which includes `.Length` as a sortable property. This sorts the strings into ascending order by length, so we take the last one with `[-1]`, leave it on the pipeline, and output is implicit.

**Example**

```
PS C:\Tools\Scripts\golfing> .\longest-word-qwerty-keyboard.ps1 asdf qwe zxc typewriter halls establishment
typewriter

```

# Answer
> 3 votes
# Pyth, ~~45~~ 35 bytes

Thanks to @FryAmThe Eggman for saving me some bytes!

```
elDf}k-LTc."`z:I¿Ç  Ì(T4²ª$8·"\`Q

```

Try it here!

Takes input as a list of words.

## Explanation

```
elDf}k-LTc."..."\`Q   # Q = list of all input words

   f              Q   # Filter input with T as lambda variable
         c."..."\`    # List of all keyboard rows
      -LT             # Remove all letters of the current input row from the current input
                      # word. Results in a list of 3 string with one being empty if
                      # the word can be typed with one row
    }k                # Check if the list contains an emtpy string
elD                   # order result list by length and take the last

```

# Answer
> 3 votes
# Ruby, 88 82 69

If I'm not allowed to take a list of strings and must take a multiline string, add +12 to the score and add `.split('\n')` right before the `.grep` call.

Thanks CatsAreFluffy for teaching me about stabby lambdas in Ruby, and further optimizations from manatwork

```
->x{x.grep(/^([o-rwetyui]+|[asdfghjkl]+|[zxcvbnm]+)$/).max_by &:size}

```

# Answer
> 3 votes
# C#, 141 / 112 / (120 bytes)

Contender for worst golfing language, for obvious reasons. Uses "my" locale with qwertz instead of qwerty but works fine otherwise.

Full program without where:

```
static void Main(string[]a){Console.WriteLine(a.OrderBy(x=>x.Length).Last(x=>Regex.IsMatch(x,"^([qwertzuiop]+|[asdfghjkl]+|[yxcvbnm]+)$")));}

```

Only output without Where:

```
Console.WriteLine(a.OrderBy(x=>x.Length).Last(x=>Regex.IsMatch(x,"^([qwertzuiop]+|[asdfghjkl]+|[yxcvbnm]+)$")));

```

Only output (original):

```
Console.WriteLine(a.Where(x=>Regex.IsMatch(x,"^([qwertzuiop]+|[asdfghjkl]+|[yxcvbnm]+)$")).OrderBy(x=>x.Length).Last());

```

# Answer
> 3 votes
## awk , ~~92~~ ~~84~~ 81 bytes

```
(/^([wetyuio-r]+|[asdfghjkl]+|[zxcvbnm]+)$/)&&length>length(a){a=$0}END{print a}

```

saved 3 bytes thanks to @Wolfgang suggestion

# Answer
> 2 votes
# `bash`, 105 bytes

And various other utilities, of course.

```
egrep -x '[wetyuio-r]+|[asdfghjkl]+|[zxcvbnm]+'|awk '{print length($0)"\t"$0;}'|sort -n|cut -f2|tail -n1

```

# Answer
> 1 votes
# MATL, 54 bytes

```
[]y"@Y:nh]2$SP"@Y:!t'asdfghjkl'mw'zxcvbnm'myy+~hhAa?@.

```

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

Input format is (first example)

```
{'artist' 'home' 'gas' 'writer' 'geology' 'marine' 'twerp'}

```

or (second example)

```
{'wrhuji' 'bxnzmmx' 'gllwssjjd' 'vnccbb' 'lrkjhgfdsa' 'tttttt'}

```

**Try it online!**

### Explanation

```
[]               % push empty array. Will be used for concatenation
y                % take input array implicitly at bottom of stack, and copy onto top
"                % for each string
  @Y:            %   push current string
  nh             %   get its length. Concatenate with array of previous lengths
]                % end for each
2$S              % sort the original copy of input array by increasing string length
P                % flip: sort by decreasing length
"                % for each string in decreasing order of length
  @Y:!           %   push that string as a column char vector
  t'asdfghjkl'm  %   duplicate. Tru for chars in 2nd row of keyboard
  w'zxcvbnm'm    %   swap. True for chars in 3rd row of keyboard
  yy+~           %   duplicate top two arrays, sum, negate: true for chars in 1st row
  hh             %   concatenate horizontally twice
  Aa             %   true if any column has all true values
  ?              %   if that's the case
    @            %     push string
    .            %     break for each loop
                 %   end if implicitly
                 % end for each
                 % display implicitly

```

# Answer
> 1 votes
# Perl, 81 bytes

`$a=$1 if/^([wetyuio-r]+|[asdfghjkl]+|[zxcvbnm]+)$/&&1<<y///c>$a=~y///c;END{say$a}`

Symbol to letter count pretty high.

# Answer
> 0 votes
# Groovy, 65 characters

```
{it.grep(~/[o-rwetyui]+|[asdfghjkl]+|[zxcvbnm]+/).max{it.size()}}

```

Sample run:

```
groovy:000> ({it.grep(~/[o-rwetyui]+|[asdfghjkl]+|[zxcvbnm]+/).max{it.size()}})(['wrhuji', 'bxnzmmx', 'gllwssjjd', 'vnccbb', 'lrkjhgfdsa', 'tttttt'])
===> bxnzmmx

```

Note that the regular expression used by `.grep()` not requires anchoring, allowing to spare the grouping too:

```
groovy:000> ['ab', 'ac', 'bc', 'abc', 'aca', 'bbc'].grep ~/[ac]+|b+/
===> [ac, aca]

```

# Answer
> 0 votes
# Japt `-h`, 18 bytes

```
;k_£D·bøXuÃä¦ dÃñÊ

```

Try it

```
;k_£D·bøXuÃä¦ dÃñÊ     :Implicit input of array
 k                     :Remove elements that return true
  _                    :When passed through the following function
   £                   :  Map each character X
;   D                  :    "QWERTYUIOP\nASDFGHJKL\nZXCVBNM"
     ·                 :    Split on newlines
      b                :    Index of first element that
       ø               :      Contains
        Xu             :      Uppercase X
          Ã            :  End map
           ä           :  Consecutive pairs of characters
            ¦          :  Reduced by checking for inequality
              e        :  Any true?
               Ã       :End filter
                ñ      :Sort by
                 Ê     :  Length
                       :Implicit output of last element

```

# Answer
> 0 votes
# K (ngn/k), 56 bytes

```
{x@*&|/&/''~^($`qwertyuiop`asdfghjkl`zxcvbnm)?\:x@:>#'x}

```

Try it online!

* `x@:>#'x` sort the input (a list of strings) by their lengths, descending, updating `x` with the result
* `($`qwertyuiop`asdfghjkl`zxcvbnm)` generate a list of strings representing which letters are present on each row of a qwerty keyboard
* `~^(...)?\:x` check whether or not each letter of each input word is present or not in each keyboard line
* `&/''` determine if all letters of each input word are present in the same keyboard line or not
* `|/` check that there is at least one keyboard line containing all the letters of each input word
* `x@*&` return the longest word in the input where the above criteria are met

# Answer
> 0 votes
# Perl 5 `-l`, 75 bytes

```
map$a[y///c]=$_,grep/^([weo-rtyui]+|[asdfghjkl]+|[zxcvbnm]+)$/,<>;say pop@a

```

Try it online!

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


title: Strobogrammatic Numbers

text:
# Question
Title: Strobogrammatic Numbers
# Strobogrammatic Numbers

---

### Definition

A number which is rotationally symmetrical, i.e., it'll appear the same when rotated by 180 deg in the plane of your screen. The following figure illustrates it better,

(source: w3resource.com)

# Task

Given a number as the input, determine if it's strobogrammatic or not.

# Examples

* Truthy

```
1
8
0
69
96
69169
1001
666999
888888
101010101

```
* Falsey

```
2
3
4
5
7
666
969
1000
88881888
969696969

```

# Rules

* The number is guaranteed to be less than a billion.
* We are considering `1` in it's roman numeral format for the sake of the challenge.
* Input can be taken as number, or an array of chars, or as string.
* Output would be a truthy/falsey value. However, you are allowed to flip the output values.
* This is a , so fewest bytes will win!

---

Sandbox link

# Answer
> 3 votes
# Node.js 11.6.0,  ~~34~~  33 bytes

Expects an array of digits. Returns *false* for strobogrammatic, or *true* otherwise.

```
n=>n.some(c=>n.pop()-c**66%79%63)

```

Try it online!

### How?

Taking the precision errors on large integers into account1, we look for a function:

$$f(x)=(x^p\bmod m\_0)\bmod m\_1$$

such that:

$$f(0)=0,\\:f(1)=1,\\:f(6)=9,\\:f(8)=8,\\:f(9)=6$$

and:

$$f(x)\>9\text{ for }x\in\\{2,3,4,5,7\\}$$

*1: These errors actually depend on the JS engine. This is guaranteed to work with Node 11.6.0.*

---

# JavaScript (ES6), 38 bytes

Expects an array of digits. Returns *false* for strobogrammatic, or *true* otherwise.

```
n=>n.some(c=>n.pop()!="01----9-86"[c])

```

Try it online!

# Answer
> 3 votes
# Perl 5 `-pa`, ~~48~~ 34 bytes

@Arnauld had a better idea in his JavaScript answer than my first one in Perl, so I stole it.

```
y/0-9/01aaaa9a86/;$_="@F"==reverse

```

Try it online!

# Answer
> 3 votes
# 05AB1E, ~~12~~ 11 bytes

```
•yΘOñ•I<èRQ

```

Try it online!

*-1 byte thanks to Razetime's suggestion*

Takes the number as a list of digits

## Explained

```
•yΘOñ•       # Push the number 1000090860
      I<     # Decrement the input list
        èR   # And get each number when rotated 180 degrees, reversing it
          Q  # Check if that equals the input

```

# Answer
> 3 votes
# Ruby `-n`, 30 bytes

```
p$_.==$_.reverse.tr'92-7','69'

```

Try it online!

# Answer
> 1 votes
# Python 3, 53 bytes

```
lambda n:["01....9.86"[int(c)]for c in n[::-1]]==[*n]

```

Try it online!

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


title: How Many Atoms?

text:
# Question
Title: How Many Atoms?
Your task is when given a chemical formula as input, output the total number of atoms in the formula.

### Input

A chemical formula in any reasonable format. Each chemical formula has the following:

* A leading coefficient, which is a number \\$N \> 1\\$.
* At least 0 groupings of elements surrounded by parentheses.
    + Groupings can have both elements and groupings inside of them.
* At least 1 element.
    + Elements match the regex `[A-Z][a-z]*`.
* Each grouping and element can have an optional subscript, which is an `_` followed by a number \\$N \> 1\\$

### Output

The total number of atoms in the formula. Rules for counting are as follows:

* A coefficient before the formula multiplies the total count that many times.
* A subscript multiples the group or atom it follows that many times.
* An element with no coefficient or subscript represents 1 atom.

### Testcases

```
In -> Out (Notes)
H_2O -> 3
CO_2 -> 3
Co_2 -> 2 (2 cobalts)
3 C_2H -> 9
EeeEeuEetUue -> 4
3 (C_21H_30O_2)_3 -> 477 (= 3 * (53) * 3)
32H -> 32
C_10H_16N_5O_13P_3 -> 47
(Ga(U(Y_2)_3)_4)_5 -> 145 (= (1 + (1 + (2 * 3)) * 4) * 5)
Ti(Ca_2(HSO_4)_2)_2 -> 29 (= 1 + (2 + (1 + 1 + 4) * 2) * 2))

```

This is , so shortest code wins!

# Answer
# JavaScript (ES6), 87 bytes

```
s=>eval(s.replace(/[A-Z][a-z]*|_|^\d+|\(/g,s=>+s?`n=${s};n*=`:s>{}?"*":"+"+(s>"0"||s)))

```

Try it online!

### How?

Matched patterns and replacements are summarized in the following table.

```
 pattern     | replacement
-------------+-------------------------------------------
 [A-Z][a-z]* | "+true"
 _           | "*"
 ^\d+        | "n=N;n*=" (where N is the matched number)
 \(          | "+("

```

For instance, `"3 (C_21H_30O_2)_3"` is turned into:

```
"n=3;n*= +(+true*21+true*30+true*2)*3"

```

This string is simply evaluated as JS code.
> 10 votes

# Answer
# Retina 0.8.2, ~~81~~ 79 bytes

```
\d+
$*
(1+) (.+)
($2)_$1
[A-Z][a-z]*(_|())
$#2$*
+1`(\((1+)\)_)1|\(1+\)_
$2$1
1

```

Try it online! Link includes test cases. Explanation:

```
\d+
$*

```

Convert the numbers to unary.

```
(1+) (.+)
($2)_$1

```

Turn any coefficient into a group.

```
[A-Z][a-z]*(_|())
$#2$*

```

Delete all elements with suffixes, but if an element did not have a suffix, then replace it with `1`.

```
+1`(\((1+)\)_)1|\(1+\)_
$2$1

```

Multiply out all of the groupings. (These have to be done one at a time to be able to collect the results correctly.)

```
1

```

Convert to decimal.
> 2 votes

# Answer
# Perl 5 `-p`, 57 bytes

```
y/_a-z/*/d;s/^\d+\K.*/*($&)/;s/\pL/+1/g;s/\(/+(/g;$_=eval

```

Try it online!
> 2 votes

# Answer
# Ruby, 88 bytes

*A port of Arnauld's answer in Ruby!*

```
p eval gsub(/_|\(/,?_=>?*,?(=>'+(').gsub(/[A-Z][a-z]*/,'+1').gsub /^\d+/,"k=#{'\&'};k*="

```

Try it online!
> 1 votes

# Answer
# 05AB1E, ~~39~~ 37 bytes

```
AмAuS„+1:'_'*:'(„+(.:.γd}ćDdi'*«}šJ.E

```

Similar approach as the other answers, except without regex. Especially the `^\d+` to `N*` therefore costs quite a few bytes (16 to be exact: `.γd}ćDdi'*«}šJ`).

Try it online or verify all test cases.

**Explanation:**

```
Aм           # Remove all lowercase letters from the (implicit) input-string
AuS„+1:      # Replace all uppercase letters with "+1"
'_'*:        # Replace all "_" with "*"
'(„+(.:     '# Replace all "(" with "+("
.γ }         # Adjacent group the string by:
  d          #  Whether it's a digit
    ć        # Extract head; pop and push the remainder-list and first item
             # separated to the stack
     D       # Duplicate this first item
      di     # Pop, and if it's a (non-negative) integer:
        '*« '#  Append "*" to it
       }     # After the if-statement:
        š    # Prepend the potentially modified first item back to the list
         J   # Join everything together again
.E           # And evaluate and execute it as Python code
             # (after which the result is output implicitly)

```

Verify all test cases without the `.E`.
> 1 votes

# Answer
# PHP, 111 bytes

```
eval('$n='.preg_replace(["/^(\d+)/","/[A-Z][a-z]*/","/_/","/\(/"],['$1;$n*=',"+1","*","+("],$argn).';');echo$n;

```

Try it online!

Just a port of Arnauld's clever trick with `eval` and some adaptations:

* in PHP it was shorter to use a list of regexes instead of using `preg_replace_callback` (what a long function name)
* the evaled string has to be valid php prefixed with `$n=` and ended by `;` (in PHP `eval` does not return the result), example with "Ti(Ca\_2(HSO\_4)\_2)\_2": `$n=+1+(+1*2+(+1+1+1*4)*2)*2;`
* output of `$n` has to be explicit

Longer than what I thought, but "c'est de bonne guerre ma bonne dame", it's our good old PHP after all
> 1 votes

# Answer
# PowerShell, 92 bytes

I think there's definitely some room for optimization here; A lot of the bytes are just there to handle the cases with the leading "\d "

```
$t=1;-split$args|%{$t*=$_-replace'\(','+('-creplace'[A-Z][a-z]*','+1'-replace'_','*'|iex};$t

```

Try it online!

# Honorary Mention, PowerShell, 99 92 bytes

This was my first solution, and I really liked it. Including it here because I think it's fun.

```
$o="'-creplace'";"'$args$o^(\d)(.*)','`$1*(`$2)$o\(','+($o[A-Z][a-z]*','+1$o`_','*'"|iex|iex

```

Try it online!
> 1 votes

# Answer
# PowerShell, ~~84~~ ~~83~~ 88 bytes

inspired by `Honorary Mentioned Solution` by Zaelin Goodman

-1 byte thanks to Zaelin Goodman

+5 bytes the `32H` test case added

```
$o="'-creplace'"
"'$args$o^\d+','`$0*($'')#$o\(','+($o[A-Z][a-z]*','+1$o`_','*'"|iex|iex

```

Try it online!

Powershell expands the formula `32H` to:

```
'32H'-creplace'^\d+','$0*($'')#'-creplace'\(','+('-creplace'[A-Z][a-z]*','+1'-creplace'_','*'

```

The first `iex` calculates this expression to:

```
32*+(+1)#+1

```

The second `iex` calculates the expression before the comment to `32`.

---

Another example. Powershell expands the formula `3 (C_21H_30O_2)_3` to:

```
'3 (C_21H_30O_2)_3'-creplace'^\d+','$0*($'')#'-creplace'\(','+('-creplace'[A-Z][a-z]*','+1'-creplace'_','*'

```

The first `iex` calculates this expression to:

```
3*+( +(+1*21+1*30+1*2)*3)# +(+1*21+1*30+1*2)*3

```

The second `iex` calculates the expression before the comment to `477`.
> 1 votes

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


title: Climb a step to a prime

text:
# Question
Title: Climb a step to a prime
The title of Numberphile's newest video, 13532385396179, is a fixed point of the following function \\$f\\$ on the positive integers:

> Let \\$n\\$ be a positive integer. Write the prime factorization in the usual way, e.g. \\$60 = 2^2 \cdot 3 \cdot 5\\$, in which the primes are written in increasing order, and exponents of 1 are omitted. Then bring exponents down to the line and omit all multiplication signs, obtaining a number \\$f(n)\\$. \[...\] for example, \\$f(60) = f(2^2 \cdot 3 \cdot 5) = 2235\\$.

(The above definition is taken from Problem 5 of Five $1,000 Problems - John H. Conway)

Note that \\$f(13532385396179) = f(13 \cdot 53^2 \cdot 3853 \cdot 96179) = 13532385396179\\$.

## Task

Take a positive composite integer \\$n\\$ as input, and output \\$f(n)\\$.

## Another example

\\$48 = 2^4 \cdot 3\\$, so \\$f (48) = 243\\$.

## Testcases

More testcases are available here.

```
   4 -> 22
   6 -> 23
   8 -> 23
  48 -> 243
  52 -> 2213
  60 -> 2235
 999 -> 3337
9999 -> 3211101

```

# Answer
> 16 votes
# Python, ~~166~~ ~~162~~ 159 bytes

You guys are much better. This is what I used! (the algorithm that solved it calls this)

```
from primefac import*
def c(n):
 x=factorint(n)
 a=''
 for i in range(len(x)):
  l=min(x.keys())
  a+=str(l)
  if x[l]>1:a+=str(x[l])
  x.pop(l)
 return int(a)

```

# Answer
> 10 votes
## Jelly, 6 bytes

```
ÆFFḟ1V

```

Try it online!

### Explanation

```
ÆF      Get prime factorisation of input as prime-exponent pairs.
  F     Flatten.
   ḟ1   Remove 1s.
     V  Effectively flattens the list into a single integer.

```

# Answer
> 9 votes
# Brachylog, 8 bytes

```
ḋoọc;1xc

```

Try it online!

### Explanation

```
Example input: 60

ḋ          Prime decomposition: [5,3,2,2]
 o         Order: [2,2,3,5]
  ọ        Occurences: [[2,2],[3,1],[5,1]]
   c       Concatenate: [2,2,3,1,5,1]
    ;1x    Execute 1s: [2,2,3,5]
       c   Concatenate: 2235

```

You can use `ℕ₂ˢ` (*select all integers greater than or equal to 2*) instead of `;1x`, which is probably more readable and more in the spirit of Brachylog.

# Answer
> 7 votes
# Mathics, 34 bytes

```
Row[Join@@FactorInteger@#/.1->""]&

```

Try it online!

-2 bytes from @sanchez

# Answer
> 4 votes
## CJam, 8 bytes

```
limF:~1-

```

Try it online!

### Explanation

```
li  e# Read input and convert to integer.
mF  e# Get prime factorisation as prime-exponent pairs.
:~  e# Flatten.
1-  e# Remove 1s.
    e# Implicitly print a flattened representation of the list.

```

# Answer
> 4 votes
# 05AB1E, 10 bytes

```
Òγʒ¬?gDië?

```

Try it online!

```
Ò          # Push list of prime factors with duplicates
 γ         # Break into chunks of consecutive elements
  ʒ        # For each
   ¬?      #   Print the first element
     gD    #   Push the length of this chunk twice
       ië  #   If not 1
         ? #     Print the length

```

# Answer
> 3 votes
# 05AB1E, ~~12~~ 11 bytes

```
Òγvy¬sgD≠×J

```

Try it online!

**Explanation**

```
Ò            # calculate prime factors with duplicates
 γ           # group consecutive equal elements
  vy         # for each group
    ¬        # get the head without popping
     sg      # push the length of the group
       D≠×   # repeat the length (length != 1) times
          J  # join

```

# Answer
> 2 votes
# Pyth, 12 bytes

```
smjk_>hddr8P

```

Try it!

### alternative, 12 bytes

```
smjk<_AdGr8P

```

Try that!

### explanation

```
smjk_>hddr8P
           PQ  # prime factorization (already in correct order) of the implicit input: [3, 3, 11, 101]
         r8    # length encode: [[2, 3], [1, 11], [1, 101]]
 m             # map over the length encoded list (lambda variable: d)
     >hdd      # take the d[0] last elements of d (so only the last for d[0]==1 and all else)
    _          # reverse that list
  jk           # join into a string
s              # conatenate the list of strings

```

# Answer
> 2 votes
# Pyth, 11 bytes

```
jksm_-d1r8P

```

Try here

# Answer
> 2 votes
# Python 2, 99 bytes

```
n=input()
r=''
p=2
while~-n:
 e=0
 while n%p<1:e+=1;n/=p
 r+=str(p)*(e>0)+str(e)*(e>1);p+=1
print r

```

**Try it online!**

If inputs are restricted to be below `2147483659`, both `str(...)` may be replaced by ``...`` saving 6 bytes (this program will be **very** slow for numbers affected anyway!).

# Answer
> 2 votes
# Ohm, 11 bytes

```
o:_]D2<?O;J

```

Try it online!

### Explanation

```
o:_]D2<?O;J
o           # Push prime factors with powers from input (Format [[prime,power],...]
 :          # For each...
  _          # Push current element
   ]         # flatten
    D        # Duplicate power
     2<? ;   # Is the power smaller than 2?
        O     # Delete top of stacks
          J  # Join

```

# Answer
> 1 votes
# PHP, 88 bytes

```
for($i=2;1<$a=&$argn;)$a%$i?$i++:$a/=$i+!++$r[$i];foreach($r as$k=>$v)echo$k,$v<2?"":$v;

```

Try it online!

# Answer
> 1 votes
# Japt, 19 bytes

```
k ó¥ ®¯1 pZlÃc fÉ q

```

Test it online!

### Explanation

```
 k ó¥  ®   ¯  1 pZlÃ c fÉ  q
Uk ó== mZ{Zs0,1 pZl} c f-1 q  // Ungolfed
                              // Implicit: U = input number
Uk                            // Break U into its prime factors.
   ó==                        // Group into runs of equal items.
       mZ{         }          // Map each item Z in this to
          Zs0,1               //   Z.slice(0, 1) (the array of the first item),
                pZl           //   with Z.length added at the end.
                              // This returns an array of prime-exponent pairs (Jelly's ÆF).
                     c        // Flatten.
                       f-1    // Filter to the items X where X - 1 is truthy (removes '1's).
                           q  // Join the resulting array into a single string.
                              // Implicit: output result of last expression

```

# Answer
> 1 votes
# , 72 bytes

```
x=rle(pracma::factors(scan()));x$l[x$l<2]='';paste0(x$v,x$l,collapse='')

```

Requires the `pracma` package, which is not installed on TIO.

# Answer
> 1 votes
# APL (Dyalog Extended), ~~15~~ 14 bytes

Saved 1 byte thanks to @Adám

```
∊⍕¨1~⍨∊⍉2⌂pco⎕

```

Try it online!

```
∊⍕¨1~⍨∊⍉2⌂pco⎕
               ⎕      ⍝ Input
          2⌂pco        ⍝ Prime factors with exponents
        ⍉             ⍝ Transpose so the 1st column is factors, 2nd is exponents
       ∊               ⍝ Flatten
    1~⍨               ⍝ Remove 1
 ⍕¨                   ⍝ Convert each to a string
∊                      ⍝ Concatenate them together

```

# Answer
> 0 votes
# C#, ~~206~~ 100 bytes

```
n=>{var r="";for(int d=1,c;++d<=n;){c=0;while(n%d<1){c++;n/=d;}r+=c>0?d+(c>1?c+"":""):"";}return r;}

```

Full/Formatted version:

```
using System;

class P
{
    static void Main()
    {
        Func<int, string> func = n =>
        {
            var r = "";
            for (int d = 1, c; ++d <= n;)
            {
                c = 0;
                while (n % d < 1)
                {
                    c++;
                    n /= d;
                }

                r += c > 0 ? d + (c > 1 ? c + "" : "") : "";
            }

            return r;
        };

        Console.WriteLine(func(4));
        Console.WriteLine(func(6));
        Console.WriteLine(func(8));
        Console.WriteLine(func(48));
        Console.WriteLine(func(52));
        Console.WriteLine(func(60));
        Console.WriteLine(func(999));
        Console.WriteLine(func(9999));

        Console.ReadLine();
    }
}

```

# Answer
> 0 votes
# Javascript - 91 bytes

```
(x,r='',i=1,n)=>{while(x>i++){for(n=0;x%i<1;n++)x/=i;r+=(n>0?i+'':'')+(n>1?n:'')}return r}

```

## Explanation

```
(x,r='',i=1,n)=>(          // input x is the number to process, r, i, n are default values only
    while(x>i++){          // iterate over i until x
        for(n=0;x%i<1;n++) // iterate over n until i is not a factor of x
            x/=i;          // factor i out of x
        r+=(n>0?i+'':'')   // append i to r if n > 0
            +(n>1?n:'')    // append n to r if n > 1
                           // i+'' prevents adding i and n before appending to r
    }
    return r               // return r by comma-operator and arrow function syntax
)

```

# Answer
> 0 votes
# Java 8, 103 chars

Pretty straightforward solution.

```
n->{String r="";int d=2,c;while(n>1){c=0;while(n%d<1){c++;n/=d;}if(c>0)r+=d;if(c>1)r+=c;d++;}return r;}

```

Ungolfed:

```
private static Function<Integer, String> f = n->{
    String result = "";
    int divisor = 2, count;
    while (n>1) {
        count = 0;
        while (n % divisor < 1) {
            count++;
            n /= divisor;
        }
        if (count > 0) result += divisor;
        if (count > 1) result += count;
        divisor++;
    }
    return result;
};

```

# Answer
> 0 votes
# Octave, 69 bytes

```
@(a)printf('%d',(f=[[~,c]=hist(b=factor(a),d=unique(b));d](:))(f~=1))

```

Try it online!

Ended up being quite long, but this will generate the desired output.

Essentially we use the histogram function to count the number of occurrences of the unique values in the prime factorisation of the input value.

* The result of the `factor()` function gives the prime factors in ascending order
* we then find `unique()` values in that array
* `hist()` returns the number of occurrences

Once we have the two arrays (one for unique factors, one for counts), we concatenate the arrays vertically (one on top of the other), and then flatten. This interleaves the factors with counts.

Finally we display the result as a string ensuring to skip any 1's in the final array. The only time 1's can appear is if the count was 1 because 1 will never be a prime factor. This elimination is done before converting to a string so it won't affect things like the number 10.

# Answer
> 0 votes
# Ruby, 45 + 7 bytes

Requires the flag `-rprime`.

```
->n{(n.prime_division.flatten-[1]).join.to_i}

```

Try it online!

# Answer
> 0 votes
# Pyth - 16 bytes

```
V{PQpNK/PQNItKpK

```

Try it

Another solution:

```
sm`d-.nm(d/PQd){PQ1

```

---
Tags: code-golf, number, arithmetic, primes
---