# Question
Title: Take a ride on the Reading, If you pass Go, collect $200
### Monopoly Board

For this code-golf challenge we will be building the board game Monopoly.

### Rules:

* Take no input.
* Output a 11x11 board where each ASCII character forming the board is the first letter of each space of the U.S. version of the Monopoly board.
* The characters must be separated by spaces.
* `Go` should start in the bottom right.

The exact string to produce is

```
F K C I I B A V W M G
N                   P
T                   N
C                   C
S                   P
P                   S
V                   C
S                   P
E                   L
S                   B
J C V C O R I B C M G

```

Note that from bottom right to bottom left the squares are as follows:

```
G --> Go
M --> Mediterranean Avenue
C --> Community Chest
B --> Baltic Avenue
I --> Income Tax
...
J --> Jail

```

**Edit** Wow! you guys sure liked this one! :)

# Answer
## Retina, 74 bytes

```

FKCIIBAVWMGN_PT_NC_CS_PP_SV_CS_PE_LS_BJCVCORIBCMG
S_`(._.)
_
9$*
\B

1

```

The third to last and last lines should contain a single space.

Try it online!

### Explanation

```

FKCIIBAVWMGN_PT_NC_CS_PP_SV_CS_PE_LS_BJCVCORIBCMG

```

This replaces the (empty) input with the string on the second line.

```
S_`(._.)

```

This is split stage, which splits the string around matches of the regex `(._.)` (that is, any three characters with a `_` in the middle). The reason we put the whole regex in a group is that split stages also return the results of capturing groups. E.g. splitting `abcd` around `bc` gives `[a, d]`, but splitting it around `b(c)` gives `[a, c, d]`. This way we get all the `._.` parts on separate lines but also the 11-character parts at the beginning and end. We use the `_` option to omit empty results between the individual `._.` matches. The result would be this:

```
FKCIIBAVWMG
N_P
T_N
C_C
S_P
P_S
V_C
S_P
E_L
S_B
JCVCORIBCMG

```

Next we process the underscores:

```
_
9$*

```

This replaces each underscore with nine `1`s. The reason we use `1`s here instead of spaces immediately is that it makes it easier to insert the padding spaces next.

```
\B

```

Remember that there's a space on the second line. This inserts a space in every position that *isn't* a word boundary, i.e. everywhere except at the beginning and end of the lines.

```
1

```

And finally, we replace all those `1`s with spaces as well.
> 36 votes

# Answer
# Jelly, 44 bytes

```
“£ċ9NɲT⁴MỵƇñdMỊḞ*µ7Sʂɓ¢Ż}ạ¥ċwÞ’ḃ23ṣ4ịØAz⁶ṙ1G

```

Try it online!

### Idea

If we remove every second column and transpose rows with columns, we get the following board.

```
FNTCSPVSESJ
K         C
C         V
I         C
I         O
B         R
A         I
V         B
W         C
M         M
GPNCPSCPLBG

```

Now, we can rotate each column one unit to the right, moving all remaining spaces to the right.

```
JFNTCSPVSES
KC
CV
IC
IO
BR
AI
VB
WC
MM
GGPNCPSCPLB

```

Then, we remove the remaining spaces and replace linefeeds with the letter **D**.

```
JFNTCSPVSESDCKDVCDCIDOIDRBDIADBVDCWDMMDGGPNCPSCPLB

```

Now, we replace each letter with its 1-based index in the alphabet.

```
10  6 14 20  3 19 16 22 19  5 19  4  3 11  4 22  3  4  3  9  4 15  9  4 18
 2  4  9  1  4  2 22  4  3 23  4 13 13  4  7  7 16 14  3 16 19  3 16 12  2

```

Then, we convert this digit array from bijective base **23** to integer.

```
54580410997367796180315467139871590480817875551696951051609467717521

```

Now, we convert this integer to bijective base **250**.

```
  2 232  57  78 163  84 132  77 228 144  27 100  77 176 195
 42   9  55  83 167 155   1 210 125 211   4 232 119  20

```

Finally, we use these digits to index into Jelly's code page.

```
£ċ9NɲT⁴MỵƇñdMỊḞ*µ7Sʂɓ¢Ż}ạ¥ċwÞ

```

This is the encoded data we'll include in the program (**29 bytes**). To produce the desired output, we just have to reverse the steps above.

### Code

```
“£ċ9NɲT⁴MỵƇñdMỊḞ*µ7Sʂɓ¢Ż}ạ¥ċwÞ’ḃ23ṣ4ịØAz⁶ṙ1G  Main link. No arguments.

“£ċ9NɲT⁴MỵƇñdMỊḞ*µ7Sʂɓ¢Ż}ạ¥ċwÞ’               Convert the string from bijective
                                              base 250 (using the indices in
                                              Jelly's code page) to integer.
                               ḃ23            Convert that integer to bijective
                                              base 23.
                                  ṣ4          Split the resulting array at
                                              occurrences of 4.
                                    ịØA       Replace the remaining digits in the
                                              resulting 2D array with the
                                              corresponding uppercase letters.
                                       z⁶     Zip/transpose rows and columns,
                                              padding shorter rows with spaces.
                                         ṙ1   Rotate the rows one unit down.
                                           G  Grid; join rows by spaces, columns
                                              by linefeeds.

```
> 25 votes

# Answer
# 05AB1E, ~~48~~ 47 bytes

Thanks to *Emigna* for saving a byte!

```
•(K·;“…¬È¦z"9äuŸé;TÞîÕs‡ÓÐV9XÒt\<•33B¾9ð×:S11ô»

```

**Explanation:**

First some compression. `•(K·;“…¬È¦z"9äuŸé;TÞîÕs‡ÓÐV9XÒt\<•` is a compressed version of the following number:

```
120860198958186421497710412212513392855208073968557051584380118734764403017

```

After that, this is converted to **base 33**, which results into the following string:

```
FKCIIBAVWMGN0PT0NC0CS0PP0SV0CS0PE0LS0BJCVCORIBCMG

```

The zeroes are replaced by **9 spaces**, using the following code `¾9ð×:`. After that, we `S`plit the string into characters and slice them into pieces of **11** elements (done with `11ô`). We get the following 2-dimensional array:

```
[['F', 'K', 'C', 'I', 'I', 'B', 'A', 'V', 'W', 'M', 'G'],
 ['N', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'P'],
 ['T', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'N'],
 ['C', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'C'],
 ['S', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'P'],
 ['P', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'S'],
 ['V', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'C'],
 ['S', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'P'],
 ['E', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'L'],
 ['S', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'B'],
 ['J', 'C', 'V', 'C', 'O', 'R', 'I', 'B', 'C', 'M', 'G']]

```

We *gridify* this array with `»` and output it implicitly.

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

# Answer
## Python 2, 89 bytes

```
l='%s '*11+'\n'
print(l+'%s%20s\n'*9+l)%tuple("FKCIIBAVWMGNPTNCCSPPSVCSPELSBJCVCORIBCMG")

```

Creates the template

```
? ? ? ? ? ? ? ? ? ? ?
?                   ?
?                   ?
?                   ?
?                   ?
?                   ?
?                   ?
?                   ?
?                   ?
?                   ?
? ? ? ? ? ? ? ? ? ? ?

```

to substitute in letters via string formatting. The template uses two types of lines:

* The outer line `l` of 11 copies of letter-plus-space, then a newline. It's also used for the first and last line. It has a trailing space.
* The inner line of a character, then a character preceded by 19 characters of padding spaces, then a newline. It's copied 9 times for the center lines.

Python 3.5 can save a byte with tuple unpacking `(*'...',)`.
> 12 votes

# Answer
## PowerShell v2+, ~~131~~ ~~123~~ ~~114~~ ~~110~~ 99 bytes

```
'F K C I I B A V W M G
N0P
T0N
C0C
S0P
P0S
V0C
S0P
E0L
S0B
J C V C O R I B C M G'-replace0,(" "*19)

```

This is just a literal string with newlines placed on the pipeline, with a little `-replace` at the end to turn the `0` into `19` spaces. The first and last lines are just verbatim. With only 10 spaces and little repetition otherwise, there wasn't enough room to golf them. This string is left on the pipeline, and output via implicit `Write-Output` happens at program completion.

```
PS C:\Tools\Scripts\golfing> .\take-a-ride-on-reading.ps1
F K C I I B A V W M G
N                   P
T                   N
C                   C
S                   P
P                   S
V                   C
S                   P
E                   L
S                   B
J C V C O R I B C M G

```
> 9 votes

# Answer
# Javascript ES6 REPL, ~~105~~ ~~102~~ 101 bytes

Not much interesting happening here. Paste in the console to see the desired results

Saved 3 bytes thanks to @Arnauld
Saved 1 more byte thanks to @Neil

```
`FKCIIBAVWMG
N P
T N
C C
S P
P S
V C
S P
E L
S B
JCVCORIBCMG`.replace(/.( ?)/g,`$& `+`$1`.repeat(17))

```

```
a.innerHTML =

`FKCIIBAVWMG
N P
T N
C C
S P
P S
V C
S P
E L
S B
JCVCORIBCMG`.replace(/.( ?)/g,`$& `+`$1`.repeat(17))
```

```
<pre id=a>
```
> 9 votes

# Answer
# ///, ~~100~~ 98 bytes

```
/s/    //p/ssss   //q/pC
SpP
//!/ C /F K!I I B A V W M G
NpP
TpN
CqPpS
VqEpL
SpB
J!V!O R I B!M G

```

Try it online!

For some mysterious reason, there seem to be trailing spaces after the `G`s. Without them, my code would have been 96 bytes.

Thanks to 42545 (ETHproductions) and 56258 (daHugLenny) for reducing 1 byte each!
> 7 votes

# Answer
# Turtlèd, 72 bytes

```
"K C I I B A V W M G">"GPNCPSCPLBG">"G M C B I R O C V C J">"JSESVPSCTNF

```

Try it online

`>` rotates turtle, `"foo"` writes strings on grid. last `"` was elidable
> 6 votes

# Answer
# , ~~75, 62~~, 59 bytes

```
iFKCIIBAVWMG
NPTNCCSPPSVCSPELSB
JCVCORIBCMG-ò9á lli
òÍ./&

```

Try it online!

Since this codel contains non-ASCII characters, here is a hexdump:

```
0000000: 6946 4b43 4949 4241 5657 4d47 0a4e 5054  iFKCIIBAVWMG.NPT
0000010: 4e43 4353 5050 5356 4353 5045 4c53 420a  NCCSPPSVCSPELSB.
0000020: 4a43 5643 4f52 4942 434d 471b 2df2 39e1  JCVCORIBCMG.-.9.
0000030: 206c 6c69 0af2 cd2e 2f26 20               lli..../&

```

Explanation. First, we enter the following text:

```
FKCIIBAVWMG
NPTNCCSPPSVCSPELSB
JCVCORIBCMG

```

Then, we `<esc>` back to normal mode. At this point, the cursor is on the third line on the last `G`. Conveniently, there is a command to put us on the first column of the line right above the cursor. That command is `-`. Then, once we end up on the second line (on the `N`), we run the following loop:

```
ò9á lli
ò

```

Explanation:

```
ò           " Recursively:
 9á         "   Append 9 spaces
    ll      "   Move to the right twice. This will fail on the last time because there isn't a space to move into
      i     "   Enter a newline
ò           " End

```

Now, the buffer looks like this:

```
FKCIIBAVWMG
N         P
T         N
C         C
S         P
P         S
V         C
S         P
E         L
S         B
JCVCORIBCMG

```

Now we use a compressed regex to replace each character with that character and a space. That's the `Í./&` part. This translates to the following vim regex:

```
:%s/./& /g

```

Which means:

```
:%          " On any line
  s/        " Substitute
    ./      " Any character with
      & /   " That same character and a space
         g  " Allow for multiple substitutions on the same line

```
> 5 votes

# Answer
# R, 149 146 bytes

Not so impressive but also not sure how this would be golfed. Exploiting `paste` somehow is my first guess. Compare to raw text of 241 bytes.

```
x=strsplit("NTCSPVSESPNCPSCPLB","")[[1]];cat("F K C I I B A V W M G\n");for(i in 1:9)cat(x[i],rep("",18),x[i+9],"\n");cat("J C V C O R I B C M G")

```

R-fiddle
> 4 votes

# Answer
## Perl, 90 bytes

Pretty boring approach, can't think of a better way to reduce... Requires `-E` at no extra cost. Outputs an additional space at the end of every line. -2 bytes thanks to @Dada!

```
say"FKCIIBAVWMG
NZP
TZN
CZC
SZP
PZS
VZC
SZP
EZL
SZB
JCVCORIBCMG"=~s/Z/$"x9/ger=~s/./$& /gr

```

### Usage

```
perl -E 'say"FKCIIBAVWMG
NZP
TZN
CZC
SZP
PZS
VZC
SZP
EZL
SZB
JCVCORIBCMG"=~s/Z/$"x9/ger=~s/./$& /gr'

```
> 4 votes

# Answer
## Python 2, 108 bytes

Slightly different than the other python answer, using no replaces, only string joins.

```
print'\n'.join(map(' '.join,['FKCIIBAVWMG']+map((' '*9).join,zip('NTCSPVSES','PNCPSCPLB'))+['JCVCORIBCMG']))

```
> 4 votes

# Answer
# Jolf, 72 bytes

```
Ζ0ρ,ahtht"111"'.d?=H♣Q♣+."FKCIIBAVWMGNPTNCCSPPSVCSPELSBJCVCORIBCMG"wΖhζ♣

```

Replace all  with `\x05`, or try it here!

```
Ζ0ρ,ahtht"111"'.d?=H♣Q♣+."..."wΖhζ♣
Ζ0                                   ζ = 0
   ,ahtht"111"                       a box of width&height 11, with borders "1"
  ρ           '.d                    replace each char in that string with...
                 ?=H♣                 is it a space?
                     Q♣                if so, return two spaces.
                                      otherwise
                        ."..."         get the Nth member of this string
                              wΖhζ      where N = (++ζ) - 1
                       +          ♣      and add a space to the end

```

This gives the desired string.
> 4 votes

# Answer
# Java 7, ~~177~~ ~~165~~ ~~142~~ 131 bytes

```
String c(){return"FKCIIBAVWMG\nN_P\nT_N\nC_C\nS_P\nP_S\nV_C\nS_P\nE_L\nS_B\nJCVCORIBCGM".replace("_","         ").replace(""," ");}

```

-15 bytes thanks to *@BassdropCumberwubwubwub*.
-11 bytes thanks to *@Numberknot*.

**Ungolfed & test code:**

Try it here.

```
class M{
  static String c(){
    return "FKCIIBAVWMG\nN_P\nT_N\nC_C\nS_P\nP_S\nV_C\nS_P\nE_L\nS_B\nJCVCORIBCGM"
      .replace("_","         ").replace(""," ");
  }

  public static void main(String[] a){
    System.out.print(c());
  }
}

```

**Output:**

```
F K C I I B A V W M G
N                   P
T                   N
C                   C
S                   P
P                   S
V                   C
S                   P
E                   L
S                   B
J C V C O R I B C M G

```
> 3 votes

# Answer
# Perl, ~~115~~ 112 bytes

```
print FKCIIBAVWMG=~s/(.)/\1 /gr.NPTNCCSPPSVCSPELSB=~s/(.)(.)/"\n$1".$"x19 .$2/gre."\nJCVCORIBCMG"=~s/(.)/\1 /gr;

```

Produces the following output:

```
F K C I I B A V W M G
N                   P
T                   N
C                   C
S                   P
P                   S
V                   C
S                   P
E                   L
S                   B
J C V C O R I B C M G

```

The first and last rows of output have a trailing space. The code makes use of regex replacements and the fact that if objects are not defined, they are interpreted as strings (e.g. FKCIIBAVWMG is treated as "FKCIIBAVWMG". Couldn't take the quotes out of the last row because of the preceeding newline, which I couldn't finagle anywhere else.

Edit 1: Saved 3 bytes by replacing `" "` with `$"`, removing the outer parentheses and inserting a space after print, and removing the parentheses around `$"x19` and adding a space afterwards (so the `.` wouldn't be interpreted as a decimal)
> 3 votes

# Answer
# Befunge, 120 bytes

```
<v"FKCIIBAVWMG NPTNCCSPPSVCSPELSB $JCVCORIBCMG "
:<,*48 ,_v#-*48<
>1-:#v_\,>$52*, :48*-!#v_,54*
^,*84<         ^p19*88$<

```

First line has the string to be printed in reverse (it looks like it's not, but the code is going backwards on that line). Second line prints the top and bottom rows. Third line and the left side of the fourth line print the middle rows, and the small chunk on the bottom right does an interesting thing: it moves the cursor back to the second row to print out the last line, but after finishing it, it quits.

As you can see on the first line, the strings are separated by spaces to distinguish between the first, middle, and last rows. The spaces can be anything else, and if I used ASCII characters 0-9, I could've easily saved 4 bytes. The $ you see is just a garbage character that has to be there and could be replaced with anything but a space.
> 3 votes

# Answer
# Ruby, 92

Full program, prints to stdout using `$> <<`

```
40.times{|i|$><<"FKCIIBAVWMGNPTNCCSPPSVCSPELSBJCVCORIBCMG"[i]+(i%29>9?[$/,' '*19][i%2]:' ')}

```

There are 40 total letters to plot. Letters 10 to 28 alternate between being followed by a newline or `' '*19`. The earlier and later letters are separated by single spaces.
> 3 votes

# Answer
# J, ~~77~~ 73 bytes

```
' FKCIIBAVWMGNPTNCCSPPSVCSPELSBJCVCORIBCMG'{~_22}.\,0,.(*+/\),0=*/~5-|i:5

```

Note that 43 bytes, over half the total, are used just for the string `' FKCIIBAVWMGNPTNCCSPPSVCSPELSBJCVCORIBCMG'`.

## Explanation

First, make a list

```
   |i:5
5 4 3 2 1 0 1 2 3 4 5
   5-|i:5
0 1 2 3 4 5 4 3 2 1 0

```

Then make its times table

```
   */~5-|i:5
0 0  0  0  0  0  0  0  0 0 0
0 1  2  3  4  5  4  3  2 1 0
0 2  4  6  8 10  8  6  4 2 0
0 3  6  9 12 15 12  9  6 3 0
0 4  8 12 16 20 16 12  8 4 0
0 5 10 15 20 25 20 15 10 5 0
0 4  8 12 16 20 16 12  8 4 0
0 3  6  9 12 15 12  9  6 3 0
0 2  4  6  8 10  8  6  4 2 0
0 1  2  3  4  5  4  3  2 1 0
0 0  0  0  0  0  0  0  0 0 0

```

Then test for equality with zero

```
   0=*/~5-|i:5
1 1 1 1 1 1 1 1 1 1 1
1 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 1
1 1 1 1 1 1 1 1 1 1 1

```

Flatten it, find the cumulative sums, and multiply elementwise

```
   ,0=*/~5-|i:5
1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1
   +/\,0=*/~5-|i:5
1 2 3 4 5 6 7 8 9 10 11 12 12 12 12 12 12 12 12 12 12 13 14 14 14 14 14 14 14 14 14 14 15 16 16 16 16 16 16 16 16 16 16 17 18 18 18 18 18 18 18 18 18 18 19 20 20 20 20 20 20 20 20 20 20 21 22 22 22 22 22 22 22 22 22 22 23 24 24 24 24 24 24 24 24 24 24 25 26 26 26 26 26 26 26 26 26 26 27 28 28 28 28 28 28 28 28 28 28 29 30 31 32 33 34 35 36 37 38 39 40
   (*+/\),0=*/~5-|i:5
1 2 3 4 5 6 7 8 9 10 11 12 0 0 0 0 0 0 0 0 0 13 14 0 0 0 0 0 0 0 0 0 15 16 0 0 0 0 0 0 0 0 0 17 18 0 0 0 0 0 0 0 0 0 19 20 0 0 0 0 0 0 0 0 0 21 22 0 0 0 0 0 0 0 0 0 23 24 0 0 0 0 0 0 0 0 0 25 26 0 0 0 0 0 0 0 0 0 27 28 0 0 0 0 0 0 0 0 0 29 30 31 32 33 34 35 36 37 38 39 40

```

Then join with zeros, split it into sublists of length 22, drop the head of each sublist, and use the values as indices in the string `' FKCIIBAVWMGNPTNCCSPPSVCSPELSBJCVCORIBCMG'`

```
   ' FKCIIBAVWMGNPTNCCSPPSVCSPELSBJCVCORIBCMG'{~_22}.\,0,.(*+/\),0=*/~5-|i:5
F K C I I B A V W M G
N                   P
T                   N
C                   C
S                   P
P                   S
V                   C
S                   P
E                   L
S                   B
J C V C O R I B C M G

```
> 3 votes

# Answer
# Actually, 74 bytes

```
"%s"9⌐α' j;"%s%20s"9α'
j(k'
j"FKCIIBAVWMGNPTNCCSPPSVCSPELSBJCVCORIBCMG"#@%

```

Try it online!

This program works off of the same basic principle as xnor's Python 2 answer.

Explanation (newlines replaced with `\n` for clarity):

```
"%s"9⌐α' j                                       ' '.join(["%s"]*11)
;                                                duplicate
"%s%20s"9α'\nj                                   '\n'.join(["%s%20s"]*9)
(                                                move bottom of stack to top
k'\nj                                            '\n'.join(stack)
"FKCIIBAVWMGNPTNCCSPPSVCSPELSBJCVCORIBCMG"#@%                    %tuple(longstring)

```
> 3 votes

# Answer
# Charcoal, 66 bytes

```
Ｂ²¹¦¹¹F K C I I B A V W M GPNCPSCPLBG M C B I R O C V C JSESVPSCTN

```

Try it online!

`Box(21, 11, 'F K C I I B A V W M GPNCPSCPLBG M C B I R O C V C JSESVPSCTN')`.

Noncompeting, 36 bytes
> 3 votes

# Answer
# C#6, ~~192~~ 190 Bytes

```
using System.Linq;
string f()=>string.Join("\n","FKCIIBAVWMG~N!P~T!N~C!C~S!P~P!S~V!C~S!P~E!L~S!B~JCVCORIBCMG".Replace("!","         ").Split('~').Select(s=>string.Join(" ",s.Select(c=>c))));

```

Without trailing space; without trailing newline.

A straightforward solution. Start with the literal string. `Replace` `!` by 9 spaces. Then `Split` into 11 strings by `~`, and further to `char`s (inner `Select`). Append a space to each character, then `Join` back to 11 strings. Finally another `Join` by newline character.
> 3 votes

# Answer
# Python 2, 116 Bytes

Pretty straightforward, for whatever reason even though string replacing is so verbose it was the best thing I could come up with. Possibly using `re` might be shorter.

```
print' '.join('FKCIIBAVWMG!N@P!T@N!C@C!S@P!P@S!V@C!S@P!E@L!S@B!JCVCORIBCMG').replace(' ! ','\n').replace('@',' '*17)

```
> 2 votes

# Answer
## Batch, 171 bytes

```
@echo F K C I I B A V W M G
@set s=NPTNCCSPPSVCSPELSB
:l
@echo %s:~0,1%                   %s:~1,1%
@set s=%s:~2%
@if not "%s%"=="" goto l
@echo J C V C O R I B C M G

```
> 2 votes

# Answer
# C, ~~171~~ 156 Bytes

```
i,j;char*b="FKCIIBAVWMGNPTNCCSPPSVCSPELSBJCVCORIBCMG ";f(){for(i=1;*b;j=i%21==0?putchar(*b++),puts(""),i++,*b++:i<21||i>210?i&1?*b++:32:32,putchar(j),i++);}

```

Outputs a trailing newline character as well... Could probably be golfed down a bit more.
> 2 votes

# Answer
# GameMaker Language, 148 bytes

I know it's pretty basic, but I don't think this can be beat in GML...

```
a="                   "return"F K C I I B A V W M G #N"+a+"P#T"+a+"N#C"+a+"C#S"+a+"P#P"+a+"S#V"+a+"C#S"+a+"P#E"+a+"L#S"+a+"B#J C V C O R I B C M G "

```
> 2 votes

# Answer
## Pip, 64 bytes

63 bytes of code, +1 for `-S` flag.

```
.*"NTCSPVSES".sX19.^"PNCPSCPLB"PE^"FKCIIBAVWMG"AE^"JCVCORIBCMG"

```

Try it online!

### Explanation

Operators used:

* `.` (binary) concatenates (operates item-wise on lists).
* `X` (binary) string-multiplies. (`s` is a variable preinitialized to `" "`.)
* `^` (unary) splits a string into a list of characters.
* `.*` is another way to split a string into characters. It consists of unary `.`, which is a no-op on strings, paired with the `*` meta-operator, which maps a unary operator to each item in its (iterable) operand. Using `.*"..."` lets us save a byte over `(^"...")`--the parentheses would be required because `.` is higher precedence than `^`.
* `PE` prepends an element to a list. `AE` appends an element to a list.

With that background, here's the code step by step:

```
.*"NTCSPVSES"

['N 'T 'C 'S 'P 'V 'S 'E 'S]

.sX19

["N                   "
 "T                   "
 "C                   "
 "S                   "
 "P                   "
 "V                   "
 "S                   "
 "E                   "
 "S                   "]

.^"PNCPSCPLB"

["N                   P"
 "T                   N"
 "C                   C"
 "S                   P"
 "P                   S"
 "V                   C"
 "S                   P"
 "E                   L"
 "S                   B"]

PE^"FKCIIBAVWMG"

[['F 'K 'C 'I 'I 'B 'A 'V 'W 'M 'G]
 "N                   P"
 "T                   N"
 "C                   C"
 "S                   P"
 "P                   S"
 "V                   C"
 "S                   P"
 "E                   L"
 "S                   B"]

AE^"JCVCORIBCMG"

[['F 'K 'C 'I 'I 'B 'A 'V 'W 'M 'G]
 "N                   P"
 "T                   N"
 "C                   C"
 "S                   P"
 "P                   S"
 "V                   C"
 "S                   P"
 "E                   L"
 "S                   B"
 ['J 'C 'V 'C 'O 'R 'I 'B 'C 'M 'G]]

```

When this result is autoprinted, the `-S` flag joins the sublists on spaces and the main list on newlines, giving the desired output.
> 2 votes

# Answer
# Perl 5, 92 86 bytes

* saved 6 bytes thanks to Dada

```
$a="%s "x11;printf"$a
"."%s%20s
"x9 .$a,FKCIIBAVWMGNPTNCCSPPSVCSPELSBJCVCORIBCMG=~/./g

```

Uses `sprintf`, padding and the string repeat operator `x`.
> 2 votes

# Answer
## Haskell, ~~128~~ ~~125~~ 114 bytes

```
mapM(putStrLn.((:" ")=<<))$"FKCIIBAVWMG":zipWith(\a b->a:"         "++[b])"NTCSPVSES""PNCPSCPLB"++["JCVCORIBCMG"]

```

Try it here

* `((:" ")=<<)` is `concatMap (\a -> [a,' '])` \- pads by adding a space behind every letter in its input
> 1 votes

# Answer
# Powershell, 95 bytes

*Inspired by @AdmBorkBork's answer.*

```
'FKCIIBAVWMG
N0P
T0N
C0C
S0P
P0S
V0C
S0P
E0L
S0B
JCVCORIBCMG'-replace0,(' '*9)-replace'.','$0 '

```

## Explanation

The first replacing operator makes the rectangle `11x11`.

```
FKCIIBAVWMG
N         P
T         N
C         C
S         P
P         S
V         C
S         P
E         L
S         B
JCVCORIBCMG

```

The second replacing operator inserts a space after each character. The result has trailing spaces.

```
F K C I I B A V W M G
N                   P
T                   N
C                   C
S                   P
P                   S
V                   C
S                   P
E                   L
S                   B
J C V C O R I B C M G

```
> 1 votes

---
Tags: code-golf, string, ascii-art, kolmogorov-complexity, board-game
---


title: Generate an RSA key pair

text:
# Question
Title: Generate an RSA key pair
Given a positive integer \\$N \>= 4\\$, output an RSA key pair (both the private and the public key) whose key length is \\$N\\$ bits.

The RSA key generation algorithm is as follows:

1. Choose an \\$N\\$-bit semiprime \\$n\\$. Let the prime factors of \\$n\\$ be \\$p\\$ and \\$q\\$.
2. Compute \\$\lambda(n) = LCM(p-1, q-1)\\$.
3. Choose an integer \\$e\\$ such that \\$1 \< e \< \lambda(n)\\$ and \\$GCD(e, \lambda(n)) = 1\\$.
4. Compute \\$d \equiv e^{−1} \pmod {\lambda(n)}\\$.

The public key is composed of \\$n\\$ and \\$e\\$. The private key is \\$d\\$.

## Rules

* You may assume that there exists at least one semiprime \\$n\\$ with bit length \\$N\\$.
* Output may be in any consistent and unambiguous format.
* \\$e\\$ and \\$n\\$ must be chosen from discrete uniform distributions.
* You may assume that \\$N\\$ is less than or equal to the maximum number of bits for integers representable in your language, if your language has such a restriction.

# Answer
> 2 votes
# JavaScript (ES7), 190 bytes

Returns `[n,e,d]`.

```
f=N=>(R=Math.random,g=d=>d&&p%--d?g(d):d)(p=g(p=n=R()*2**N|0))<2&n>1&(L=(q=n/p-1)*--p/(G=(a,b)=>b?G(b,a%b):a)(p,q))>2?(g=_=>G(L,e=R()*(L-2)+2|0)<2?(h=d=>d*e%L<2?[n,e,d]:h(-~d))():g())():f(N)

```

Try it online!

Because of the limited size of the call stack, this may fail for \\$N\>13\\$.

### Commented

```
f = N =>
  (
    R = Math.random,
    // helper function returning the highest divisor of p
    g = d => d && p % --d ? g(d) : d
  )(
    // choose n and compute its highest divisor p
    p = g(p = n = R() * 2 ** N | 0)
  )
  // make sure that p is prime
  < 2 &
  // and that n is greater than 1
  n > 1 &
  // compute L = λ(n) = LCM(p - 1, q - 1) = (p - 1) * (q - 1) / GCD(p - 1, q - 1),
  // using the helper function G that returns GCD(a, b)
  (L = (q = n / p - 1) * --p / (G = (a, b) => b ? G(b, a % b) : a)(p, q))
  // make sure that L > 2
  > 2 ?
    // helper function to choose e such that GCD(e, L) = 1
    (g = _ => G(L, e = R() * (L - 2) + 2 | 0) < 2 ?
      // helper function to compute d such that d * e mod L = 1
      (h = d => d * e % L < 2 ? [n, e, d] : h(-~d))()
    :
      g()
    )()
  :
    f(N)

```

# Answer
> 1 votes
# Jelly, ~~30~~ ~~29~~ ~~27~~ 26 bytes

```
2*µrHÆfL2=ƲƇXṄÆcµgÐṂ`ḊXṄæi

```

Try it online!

### Explanation

```
2*µrHÆfL2=ƲƇXṄÆcµgÐṂ`ḊXṄæi    Main link. Arg: N
2*                            Compute 2^N
  µ                           Begin a new chain. Arg: 2^N
    H                         Compute 2^N/2
   r                          Get all N-bit numbers (plus 2^N)
          Ʋ                     Group the following. Arg: num
     Æf                         Prime factors of num
       L                        Number of prime factors of num
        2=                      See if it is 2
           Ƈ                  Filter by the above block
                              This gets N-bit semiprimes
            X                 Choose n at random
             Ṅ                Print n
              Æc              Compute λ(n)
                µ             Begin a new chain. Arg: λ(n)
                 gÐṂ`         Find all 1≤x≤λ(n) with minimal GCD(x,λ(n))
                     Ḋ        Remove the 1 from the candidates
                              This gets candidates for e
                      X       Choose e at random
                       Ṅ      Print e
                        æi    Compute d = e⁻¹ mod λ(n)

```

# Answer
> 0 votes
# Axiom, 230 bytes

```
b(x)==(1+floor log_2 x)::INT
P(n)==nextPrime(2^(n-1)::NNI+randnum(2^(n-1)::NNI))
R(n)==(n<4=>-1;k:=n quo 2;repeat(p:=P(k+1);q:=P(k);b(p*q)=n=>break);l:=lcm(p-1,q-1);repeat(e:=2+randnum(l-2);gcd(e,l)=1=>break);[p*q,e,invmod(e,l)])

```

b in b(x) would find the bit len of x; randnum(x) with x one positive integer would be one function that return one pseudorandom number in the range 0..(x-1); P in P(n) would find one pseudorandom prime in range 2^(n-1)..(2^n-1) \[lenght of that range 2^n-1-2^(n-1)=2^(n-1)-1\]; R in R(n) would find \[n,e,d\] as the exercise says.

```
(15) -> a:=R 23
   Compiling function P with type Integer -> Integer
   Compiling function b with type Integer -> Integer
   Compiling function R with type PositiveInteger -> Any
   Compiling function G1452 with type Integer -> Boolean
   (15)  [4272647,824717,1001213]
                                                       Type: List Integer
(16) -> b %.1
   Compiling function b with type PositiveInteger -> Integer
   (16)  23
                                                    Type: PositiveInteger
(17) -> factor a.1
   (17)  1061 4027
                                                   Type: Factored Integer
(18) -> (a.2*a.3) rem lcm(1061-1,4027-1)
   (18)  1
                                                    Type: PositiveInteger
(19) -> a:=R 23
   (19)  [5215391,932257,1728433]
                                                       Type: List Integer
(20) -> R 2048
   (20)
   [23213251353270373502637714718370965847258432024211176383232570158843901982_
     8374419721867989228927344460592814980635585372922578037879152449312504744_
     2861913195543965318695967745717301811727824635815211233105475881576100225_
     3632803572317998112861757923774382346449223053928741441134006614228292016_
     5273067128098814936149948557863692935433292700177694639931896886174791595_
     2591510100576556786861493463332533151814120157258896598771272703168867259_
     1059421044639753552393378020089166512073314575563837723165164503239565057_
     8157637522454347226109931834702697646569048737623886830735628816778282907_
     16962402277453801137600520400279
     ,
    26277208914513047097872541919539499189114183243456446871374032261842172481_
     1782225662860226419702820497403134660912654534465780004169047137965180193_
     9424240720814436784731953475388628791624586090011147747029161125853374433_
     7624317473301390727052150821160711361987569549572011227572161234939947570_
     1006480714726838475136080877420539301562592505847293621815149245444744497_
     0146019787431225138564647562282720244978299356752301570039442420559831909_
     1396109771341727891989553783027544302642531934746013600522012136408967482_
     8591443211475273074214579546316395151724707332850441864609728119186620471_
     5116079141878558542286273118499
     ,
    37945816199160687259342706646596754136573392197139994836682676167798393778_
     9533248999943052484273349085225287510658624414105052824140785833431676303_
     9819497567439525931938766580464486131713424225091467044692614132161523472_
     3141843691744552674894778838275993887411876266402821208140118598964705638_
     4930606996298811686240430389336754369834390870340241699155004906972042503_
     8705910893788941005489353671521480377818624793497995264157466810522707258_
     4139749164641845206614670777070059395273813452365545085917304619784119668_
     4846093245280478965642073804885084960796597065443090998925258186802193768_
     8791746419960588307023018400019]
                                                       Type: List Integer

```

---
Tags: code-golf, random, cryptography
---


title: Number of FIFO cache misses

text:
# Question
Title: Number of FIFO cache misses
This challenge is really simple (and a precursor to a more difficult one!).

Given an array of resource accesses (simply denoted by nonnegative integers) and a parameter `n`, return the number of cache misses it would have assuming our cache has capacity `n` and uses a first-in-first-out (FIFO) ejection scheme when it is full.

Example:

```
4, [0, 1, 2, 3, 0, 1, 2, 3, 4, 0, 0, 1, 2, 3]
0 = not in cache (miss), insert, cache is now [0]
1 = not in cache (miss), insert, cache is now [0, 1]
2 = not in cache (miss), insert, cache is now [0, 1, 2]
3 = not in cache (miss), insert, cache is now [0, 1, 2, 3]
0 = in cache (hit), cache unchanged
1 = in cache (hit), cache unchanged
2 = in cache (hit), cache unchanged
3 = in cache (hit), cache unchanged
4 = not in cache (miss), insert and eject oldest, cache is now [1, 2, 3, 4]
0 = not in cache (miss), insert and eject oldest, cache is now [2, 3, 4, 0]
0 = in cache (hit), cache unchanged
1 = not in cache (miss), insert and eject oldest, cache is now [3, 4, 0, 1]
2 = not in cache (miss), insert and eject oldest, cache is now [4, 0, 1, 2]
3 = not in cache (miss), insert and eject oldest, cache is now [0, 1, 2, 3]

```

So in this example there were 9 misses. Maybe a code example helps explain it better. In Python:

```
def num_misses(n, arr):
    misses = 0
    cache = []
    for access in arr:
        if access not in cache:
            misses += 1
            cache.append(access)
            if len(cache) > n:
                cache.pop(0)
    return misses

```

Some further testcases (which contains a hint towards the next challenge - notice anything curious?):

```
0, [] -> 0
0, [1, 2, 3, 4, 1, 2, 3, 4] -> 8
2, [0, 0, 0, 0, 0, 0, 0] -> 1
3, [3, 2, 1, 0, 3, 2, 4, 3, 2, 1, 0, 4] -> 9
4, [3, 2, 1, 0, 3, 2, 4, 3, 2, 1, 0, 4] -> 10

```

Shortest code in bytes wins.

# Answer
> 11 votes
# JavaScript (ES6), 55 bytes

### Method #1: the cache overwrites the input

Takes input in currying syntax `(cache_size)(list)`.

```
n=>a=>a.map(x=>a[a.indexOf(x,k>n&&k-n)<k||k++]=x,k=0)|k

```

Try it online!

### How?

We overwrite the input array **a\[ \]** with the cache, using a separate pointer **k** initialized to **0**.

We use `a.indexOf(x, k > n && k - n) < k` to test whether **x** is in the cache.

The cache can't grow faster than the original array is walked through, so each value is guaranteed to be found, either within or beyond the cache window (i.e. `indexOf()` will never return **-1**).

A value is in the cache if it is found at an index between **max(0, k - n)** and **k - 1** (both bounds included), in which case we do **a\[true\] = x**. This only affects a property of the underlying object behind **a\[ \]** but does not alter the *array* **a\[ \]**. Otherwise, we do **a\[k++\] = x**.

### Example

Below are the different steps for the input `[1, 1, 2, 3, 3, 2, 1, 4]` with a cache size of **2**:

* bold borders: **map()** pointer
* brackets: cache pointer **k**
* orange: current cache window
* yellow: expired cache values

---

# JavaScript (ES6), 57 bytes

### Method #2: the cache is appended at the end of the input

Takes input in currying syntax `(cache_size)(list)`.

```
n=>a=>a.map(x=>n*~a.indexOf(~x,-n)||a.push(~x)&k++,k=0)|k

```

Try it online!

### How?

Because the input array **a\[ \]** is guaranteed to contain non-negative integers, we can safely append the cache at the end of **a\[ \]** by using the one-complement **~x** of each value **x**.

We use `n * ~a.indexOf(~x, -n)` to test whether **~x** is found among the last **n** values. Whenever this test fails, we append **~x** to **a\[ \]** and increment the number of misses **k**.

### Example

Below are the different steps for the same example as above, using this method. Because cache values are simply appended at the end of the array, there is no explicit cache pointer.

# Answer
> 10 votes
# Haskell, 50 bytes

```
f n=length.foldl(\r x->[x|all(/=x)$take n r]++r)[]

```

Try it online!

Based on Lynn's method of storing the whole cache history and taking its length. Unary output would be a bit shorter:

**Haskell, 47 bytes**

```
n?l=1<$foldl(\r x->[x|all(/=x)$take n r]++r)[]l

```

Try it online!

# Answer
> 9 votes
# Python 2, 58 bytes

```
lambda n,a:len(reduce(lambda c,i:[i][i in c[:n]:]+c,a,[]))

```

Try it online!

Thanks to ovs for 3 bytes, and xnor for 3 more.

# Answer
> 7 votes
# , ~~69~~ ~~64~~ 62 bytes

```
function(n,A,K={}){for(i in A)K=c(i[!i%in%K[0:n]],K);sum(K|1)}

```

Try it online!

Thanks to JayCe for suggesting some improvements, and DigEmAll for another couple!

# Answer
> 5 votes
# 05AB1E, ~~17~~ 16 bytes

```
)svDyå_i¼y¸ìI£]¾

```

Try it online!

**Explanation**

```
)                   # wrap the stack in a list
 sv                 # for each item y in input list
   D                # duplicate current list
    yå_i            # if y is not contained in the current list
        ¼           # increment counter
         y¸ì        # prepend y to the current list
            I£      # keep the first input elements
              ]¾    # end loop and push counter

```

# Answer
> 5 votes
## Haskell, ~~61~~ 58 bytes

```
n!a|let(a:b)#c|elem a c=b#c|1<2=1+b#take n(a:c);_#_=0=a#[]

```

Try it online!

```
n!a|      =a#[]     -- take input 'n' and a list 'a'
                    -- and call # with the initial list and an empty cache
 let                -- bind function '#':
  (a:b)#c           -- if there's at least one element 'a' left in the list
     |elem a c=b#c  --  and it's in the cache, go on with the same cache
                    --  and the remainder of the list
     |1<2=          -- else (i.e. cache miss)
          1+        --  add one to the recursive call of
       b#           --  the remainder of the list and
       take n(a:c)  --  the first n elements of 'a' prepended to the cach
 _#_=0              -- if there's no element in the list, return 0

```

Edit: -3 bytes thanks to @Lynn.

# Answer
> 5 votes
# Kotlin, ~~82~~ 69 bytes

```
{a,n->a.fold(List(0){0}){c,v->if(v!in c.takeLast(n))c+v else c}.size}

```

Takes input as an `IntArray`, **not** the typical `List<Int>` (which shouldn't be a problem.) This uses the approach of "build a cache history and count its length".

Try it online!

## Explanation

```
{ a, n ->                         // lambda where a is accesses and n is cache size
    a.fold(List(0){0}) { c, v ->  // fold on empty list
        if(v !in c.takeLast(n))   // if resource is not in last n cache inserts
            c + v                 // insert to cache list
        else
            c                     // return cache as is
    }.size                        // length of cache list is number of inserts
}

```

### Creating an empty list

Kotlin does not have collection literals, but it does have some functions to create new collections.

The proper way to create an empty `List<Int>` is simply:

```
List<Int>()

```

but it is shorter if we abuse the size and initializer args to do this:

```
List(0){0}
List(0)       // List of size 0
       { 0 }  // with generator returning 0

```

Because the generator lambda returns 0, Kotlin infers the type of this list as `List<Int>`, and the size of 0 means this list is empty.

# Answer
> 4 votes
# Pyth,  ~~16 15 18 14~~  13 bytes

Saved 1 byte thanks to isaacg.

```
luaW-H>QGGHEY

```

Test suite!

This challenge is very well suited to Pyth's `u` structure.

### How it works

```
luaW-H>QGGHEY     Full program. Q = the cache length, E = the list.
 u         E      Reduce E with G = current value and H = corresponding element
            Y     With starting value Y, which is preinitialised to [] (empty list).
   W              Conditional application. If...
    -H            ... Filtering H on absence of...
      >QG         ... The last Q elements of G...
                  ... Yields a truthy value (that is, H is not in G[-Q:]), then...
  a      GH       ... Append H to G.
                  ... Otherwise, return G unchanged (do not append H at all).
l                  Get the length of the result.

```

# Answer
> 4 votes
# Java 8, 96 bytes

A curried lambda taking a cache size (`int`) and access list (mutable `java.util.List<Integer>`) and returning an `int`.

```
s->a->{int w=0,m=0,i;for(int r:a)m+=(i=a.indexOf(r))<w&i<s?0:s<1?1:1+0*a.set(w++%s,r);return m;}

```

Try It Online

## Ungolfed

This uses the first (up to) `s` slots in the input list for the cache.

```
s ->
    a -> {
        int
            w = 0,
            m = 0,
            i
        ;
        for (int r : a)
            m +=
                (i = a.indexOf(r)) < w & i < s ?
                    0
                    s < 1 ?
                        1
                        : 1 + 0*a.set(w++ % s, r)
            ;
        return m;
    }

```

## Acknowledgments

* bugfix thanks to *nimi*

# Answer
> 4 votes
# Perl 6, 48 bytes

```
{my@c;$_∈@c.tail($^n)||push @c,$_ for @^o;+@c}

```

Test it

```
{  # bare block with placeholder params $n,@o

  my @c; # cache

      $_ ∈ @c.tail($^n) # is the current value in the last bit of the cache
    ||
      push @c, $_       # if not add it to the cache

  for                   # do this for all of

    @^o;                # the input array

  +@c                   # numify the cache (the count)
}

```

# Answer
> 3 votes
# Wolfram Language (Mathematica), ~~60~~ 59 bytes

```
Tr[k={};n=#;k~Take~UpTo@n~FreeQ~#&&k~PrependTo~#&/@#2;1^k]&

```

Try it online!

### Using pattern-matching, 60 bytes

```
Length[#2//.{p___,a_,q___,a_,r___}/;Tr[1^{q}]<#:>{p,a,q,r}]&

```

I really like this one better, but it's 1 byte longer...

Try it online!

# Answer
> 2 votes
# Japt, 16 bytes

```
;£A¯V øX ªAiXÃAl

```

Try it

---

## Explanation

```
                     :Implicit input of array U and integer V
 £                   :Map over each X in U
; A                  :  Initially the empty array
   ¯V                :  Slice to the Vth element
      øX             :  Contains X?
         ª           :  Logical OR
          AiX        :  Prepend X to A
             Ã       :End map
              Al     :Length of A

```

# Answer
> 1 votes
# Ruby, ~~43~~ 40 bytes

```
->s,a,*r{a.count{|*x|r!=r=(r|x).pop(s)}}

```

Try it online!

Thanks histocrat for shaving 3 bytes.

# Answer
> 1 votes
# K4, ~~42~~ 40 bytes

**Solution:**

```
{*1+/1_{r,,(y;x#z,y)r:~z in y:*|y}[x]\y}

```

**Examples:**

```
q)k)f:{*1+/1_{r,,(y;x#z,y)r:~z in y:*|y}[x]\y}
q)f[0;1 2 3 4 1 2 3 4]
8
q)f[2;0 0 0 0 0 0 0]
1
q)f[3;3 2 1 0 3 2 4 3 2 1 0 4]
9
q)f[4;3 2 1 0 3 2 4 3 2 1 0 4]
10

```

**Explanation:**

For the inner function, y is the cache, z is the request and x is the cache size.

```
{*1+/1_{r,,(y;x#z,y)r:~z in y:*|y}[x]\y} / the solution
{                                      } / lambda taking 2 args
       {                         }       / lambda taking 3 args
                                  [x]\y  / iterate over lambda with each y
                              *|y        / last (reverse, first) y
                            y:           / assign to y
                       z in              / is z in y?
                      ~                  / not
                    r:                   / assign result to r (true=1,false=0)
           ( ;     )                     / 2-element list
                z,y                      / join request to cache
              x#                         / take x from cache (limit size)
            y                            / (else) return cache unchanged
          ,                              / enlist this result
        r,                               / join with r
     1_                                  / drop the first result
  1+/                                    / sum up (starting from 1)
 *                                       / take the first result

```

**Notes:**

There is probably a nicer way to do all of this, but this is the first way that came to mind.

The function can be ran like this for **36 bytes**:

```
q)k)*1+/1_{r,,(y;x#z,y)r:~z in y:*|y}[4]\3 2 1 0 3 2 4 3 2 1 0 4
10

```

Alternative - using a global variable to store state (not very K-like), **42 bytes**:

```
{m::0;(){$[z in y;y;[m+:1;x#z,y]]}[x]\y;m}

```

# Answer
> 1 votes
# C (gcc), ~~112 110~~ 108 bytes

```
f(x,y,z)int*y;{int*i=y+z,b[x],m=0;for(wmemset(b,z=-1,x);i-y;y++)wmemchr(b,*y,x)?:++m*x?b[z=++z%x]=*y:0;x=m;}

```

Try it online!

Slightly less golfed

```
f(x,y,z)int*y;{
 int*i=y+z,b[x],m=0;
 for(wmemset(b,z=-1,x);i-y;y++)
  wmemchr(b,*y,x)?:
   ++m*
   x?
    b[z=++z%x]=*y
   :
    0;
 x=m;
}

```

# Answer
> 1 votes
# Brain-Flak, 172 bytes

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

```

Try it online!

```
# Initialize cache with n -1s (represented as 1s)
(([{}]<>)<{({}(()))}{}>)<>

# For each number in input
([]){{}

    # Keep n on third stack
    <>((({})<

        # For last n cache entries, compute difference between entry and new value
        {({}()<<>(({})<({}<>({}<>))>)<>>)}{}

    >)<

        # Get negation of current entry and...
        <>(({})([{}]<>

            {

                # Count cache hits (total will be 1 or 0)
                <>(){[()](<{}>)}{}

                # while moving entries back to right stack
                <><({}()<<>({}<>)>)>

            }{}

        ))

        # If cache hit, don't add to cache
        {(<{}{}>)}{}

    >)

<>([])}{}

# Compute cache history length minus cache size (to account for the initial -1s)
<>({}[]<>)

```

# Answer
> 1 votes
# Jelly, 18 bytes

```
Ṗɼṛ;ɼe®Uḣ⁴¤C$¡€ṛLɼ

```

Try it online!

Takes the list as the first argument and cache capacity as second argument.

```
Ṗɼṛ;ɼe®Uḣ⁴¤C$¡€ṛLɼ
 ɼ                 Apply to the register:
Ṗ                  Pop. This initializes the register to the empty list.
  ṛ                Right argument. Yields the list of addresses.
              €    For each element in the list
             ¡     If{
     e                 the element is in
          ¤            nilad{
      ®                      the register
       U                     reversed
        ḣ                    first...
         ⁴                   (cache depth) number of elements
                             }
           C           Complement. 1 <-> 0. Easier to type this than "not".
            $          Combines everything up to `e` into a monad
                      }
                    Then{
    ɼ                    Apply to the register and store the result
   ;                     Append the element
                        }
                ṛ   Right argument:
                  ɼ Apply to the register:
                 L  Length

```

# Answer
> 0 votes
# C (gcc), 156 bytes

```
s,n,m,i,j;f(x,_)int*_;{int c[x];n=m=0;for(i=0;i<x;++i)c[i]=-1;for(i=s=0;_[i]>=0;++i,s=0){for(j=0;j<x;++j)s|=(c[j]==_[i]);if(!s){c[n++]=_[i];m++;n%=x;}}x=m;}

```

Try it online!

Description:

```
s,n,m,i,j;                       // Variable declaration
f(x,_)int*_;{                    // F takes X (the cache size) and _ (-1-terminated data)
    int c[x];                    // declare the cache
    n=m=0;                       // next queue insert pos = 0, misses = 0
    for(i=0;i<x;++i)c[i]=-1;     // initialize the cache to -1 (invalid data)
    for(i=s=0;_[i]>=0;++i,s=0){  // for each datum in _ (resetting s to 0 each time)
        for(j=0;j<x;++j)         // for each datum in cache
            s|=(c[j]==_[i]);     // set s if item found
        if(!s){                  // if no item found
            c[n++]=_[i];         // add it to the cache at position n
            m++;                 // add a mis
            n%=x;                // move to next n position (with n++)
        }} x=m;}                 // 'return' m by assigning to first argument

```

# Answer
> 0 votes
# JavaScript (Node.js), 44 bytes

```
n=>a=>a.map(y=t=>y[t]+n>p||(y[t]=++p),p=0)|p

```

Try it online!

# Answer
> 0 votes
# Jelly, 17 bytes

```
Ṗœ|Ṛḣ⁴$Ṛʋ\-;⁸e"ċ0

```

Try it online!

Full program.

Argument 1: stack (Python 3 `list` of `int`egers)
Argument 2: `n` (Python 3 `int`eger)

# Answer
> 0 votes
# Rust, 129 bytes

```
|l:&[_],s|if s>0{let(mut c,mut m)=(vec![-1;s],0);for n in l.iter(){if!c.contains(n){c.remove(0);c.push(*n);m+=1;}}m}else{l.len()}

```

Try it online!

## Ungolfed

```
|l: &[isize], s: usize| {
    if s > 0 {
        let mut c = vec![-1; s];
        let mut m = 0;
        for n in l.iter() {
            if !c.contains(n) {
                c.remove(0);
                c.push(*n);
                m += 1;
            }
        }
        m
    } else {
        l.len()
    }
}

```

# Answer
> 0 votes
# Stax, 15 bytes

```
Ç═╛¢s▲▬╓í±°☻÷hi

```

Run and debug it

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


title: Prime factors buddies

text:
# Question
Title: Prime factors buddies
Given an integer `N > 1`, output all other numbers which prime decompositions have the same digits as the prime decomposition of `N`.

For example, if `N = 117`, then the output must be `[279, 939, 993, 3313, 3331]`, because

```
117 = 3 × 3 × 13

```

therefore, the available digits are `1`, `3`, `3` and `3` and we have

```
279  = 3 × 3 × 31
939  = 3 × 313
993  = 3 × 331
3313 = 3313
3331 = 3331

```

Those are the only other possible numbers, because other combination of these digits yield non-prime integers, which can't be the result of prime factorization.

If `N` is any of `117`, `279`, `939`, `993`, `3313` or `3331`, then the output will contain the five other numbers: they are prime factors buddies.

You cannot use leading zeroes to get primes, e.g. for `N = 107`, its only buddy is `701` (`017` is not considered).

### Input and Outputs

* The input and output buddies must be taken and returned in the decimal base.
* `N` will always be strictly greater than `1`.
* The output can be formatted rather freely, as long as it only contains the buddies and separators/list syntactic elements.
* The ordering of the output is unimportant.
* You may take the input through `STDIN`, as a function argument or anything similar.
* You may print the output to `STDOUT`, return it from a function, or anything similar.

### Test cases

Your program should solve any of the test cases below in **less than a minute**.

```
N        Buddies
2        []
4        []
8        []
15       [53]
16       []
23       [6]
42       [74, 146, 161]
126      [222, 438, 483, 674, 746, 851, 1466, 1631, 1679]
204      [364,548,692,762,782,852,868,1268,1626,2474,2654,2921,2951,3266,3446,3791,4274,4742,5426,5462,6233,6434,6542,7037,8561,14426,14642,15491,15833,22547]

```

### Scoring

This is , so the shortest answer in bytes wins.

# Answer
> 4 votes
# Jelly, 14 bytes

```
ÆfVṢṚḌ
ÇÇ€=ÇTḟ

```

Execution time could be halved with `DF` instead of `V`, but it still completes the combined test cases in under thirty seconds.

Try it online! or verify all test cases.

### How it works

```
ÆfVṢṚḌ   Helper link. Argument: k (integer)

Æf       Decompose k into an array of primes with product k.
  V      Eval. Eval casts a 1D array to string first, so this computes the integer
         that results of concatenating all primes in the factorization.
   Ṣ     Sort. Sort casts a number to the array of its decimal digits.
    Ṛ    Reverse. This yields the decimal digits in descending order.
     Ḍ   Undecimal; convert the digit array from base 10 to integer.

ÇÇ€=ÇTḟ  Main link. Argument: n (integer)

Ç        Call the helper link with argument n.
         This yields an upper bound (u) for all prime factorization buddies since
         the product of a list of integers cannot exceed the concatenated integers.
 Ç€      Apply the helper link to each k in [1, ..., u].
    Ç    Call the helper link (again) with argument n.
   =     Compare each result to the left with the result to the right.
     T   Truth; yield all 1-based indices of elements of [1, ..., u] (which match
         the corresponding integers) for which = returned 1.
      ḟ  Filter; remove n from the indices.

```

# Answer
> 16 votes
## PowerShell v3+, 450 bytes

```
param($n)function f{param($a)for($i=2;$a-gt1){if(!($a%$i)){$i;$a/=$i}else{$i++}}}
$y=($x=@((f $n)-split'(.)'-ne''|sort))|?{$_-eq(f $_)}
$a,$b=$x
$a=,$a
while($b){$z,$b=$b;$a=$a+($a+$y|%{$c="$_";0..$c.Length|%{-join($c[0..$_]+$z+$c[++$_..$c.Length])};"$z$c";"$c$z"})|select -u}
$x=-join($x|sort -des)
$l=@();$a|?{$_-eq(f $_)}|%{$j=$_;for($i=0;$i-le$x;$i+=$j){if(0-notin($l|%{$i%$_})){if(-join((f $i)-split'(.)'|sort -des)-eq$x){$i}}}$l+=$j}|?{$_-ne$n}

```

***Finally!***

PowerShell doesn't have any built-ins for primality checking, factorization, or permutations, so this is completely rolled by hand. I worked through a *bunch* of optimization tricks to try and reduce the time complexity down to something that will fit in the challenge restrictions, and I'm happy to say that I finally succeeded --

```
PS C:\Tools\Scripts\golfing> Measure-Command {.\prime-factors-buddies.ps1 204}

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 27
Milliseconds      : 114
Ticks             : 271149810
TotalDays         : 0.000313830798611111
TotalHours        : 0.00753193916666667
TotalMinutes      : 0.45191635
TotalSeconds      : 27.114981
TotalMilliseconds : 27114.981

```

### Explanation

There's a lot going on here, so I'll try to break it down.

The first line takes input `$n` and defines a `function`, `f`. This function uses accumulative trial division to come up with a list of the prime factors. It's pretty speedy for small inputs, but obviously bogs down if the input is large. Thankfully all the test cases are small, so this is sufficient.

The next line gets the `f`actors of `$n`, `-split`s them on every digit ignoring any empty results (this is needed due to how PowerShell does regex matching and how it moves the pointer through the input and is kinda annoying for golfing purposes), then `sort`s the results in ascending order. We store that array of digits into `$x`, and use that as the input to a `|?{...}` filter to pull out only those that are themselves prime. Those prime digits are stored into `$y` for use later.

We then split `$x` into two components. The first (i.e., smallest) digit is stored into `$a`, while the rest are passed into `$b`. If `$x` only has one digit, then `$b` will be empty/null. We then need to re-cast `$a` as an array, so we use the comma operator quick-like to do so.

Next, we need to construct all possible permutations of the digits. This is necessary so our division tests later skip a *bunch* of numbers and make things faster overall.

So long as there's element left in `$b`, we peel off the first digit into `$z` and leave the remaining in `$b`. Then, we need to accumulate into `$a` the result of some string slicing and dicing. We take `$a+$y` as array concatenation, and for each element we construct a new string `$c`, then loop through `$c`'s `.length` and insert `$z` into every position, including prepending `$z$c` and appending `$c$z`, then `select`ing only the `-u`nique elements. That's again array-concatenated with `$a` and re-stored back into `$a`. Yes, this does wind up having goofy things happen, like you can get `3333` for input `117`, which isn't actually a permutation, but this is much shorter than attempting to explicitly filter them out, ensures that we get every permutation, and is only very marginally slower.

So, now `$a` has an array of all possible (and then some) permutations of the factor's digits. We need to re-set `$x` to be our upper-bound of possible results by `|sort`ing the digits in `-des`cending order and `-join`ing them back together. Obviously, no output value can be larger than this number.

We set our helper array `$l` to be an array of values that we've previously seen. Next, we're pulling out every value from `$a` (i.e., those permutations) that are prime, and enter a loop that is the biggest time sink of the whole program...

Every iteration, we're looping from `0` to our upper bound `$x`, incrementing by the current element `$j`. So long as the `$i` value we're considering is *not* a multiple of a previous value (that's the `0-notin($l|%{$i%$_})` section), it's a potential candidate for output. If we take the `f`actors of `$i`, `sort` them, and they `-eq`ual `$x`, then add the value to the pipeline. At the end of the loop, we add our current element `$j` into our `$l` array for use next time, as we've already considered all those values.

Finally, we tack on `|?{$_-ne$n}` to pull out those that are not the input element. They're all left on the pipeline and output is implicit.

### Examples

```
PS C:\Tools\Scripts\golfing> 2,4,8,15,16,23,42,117,126,204|%{"$_ --> "+(.\prime-factors-buddies $_)}
2 -->
4 -->
8 -->
15 --> 53
16 -->
23 --> 6
42 --> 74 146 161
117 --> 279 939 993 3313 3331
126 --> 222 438 674 746 1466 483 851 1679 1631
204 --> 782 2921 3266 6233 3791 15833 2951 7037 364 868 8561 15491 22547 852 762 1626 692 548 1268 2654 3446 2474 5462 4742 5426 4274 14426 6542 6434 14642

```

# Answer
> 8 votes
## CJam, ~~26~~ 23 bytes

```
{_mfs$:XW%i){mfs$X=},^}

```

Try it online

### Explanation

Concatenating two numbers always gives a bigger result than multiplying them. So the largest number we possibly need to consider is the largest number we can form from the digits of the input's prime factorisation, which is just all digits sorted in descending order. For the given numbers this upper bound is easily small enough that we can exhaustively check every number in range for whether it's a prime factor buddy:

```
_mf    e# Duplicate input N and get a list of its prime factors.
s$     e# Convert the list to a (flattened) string and sort it.
:X     e# Store this in X for later.
W%     e# Reverse it. This is now a string repesentation of the largest
       e# possible output M.
i)     e# Convert to integer and increment.
{      e# Get a list of all integers i in [0 1 ... M] for which the following
       e# block gives a truthy result.
  mf   e#   Get list of prime factors of i.
  s$   e#   Get a sorted list of the digits appearing in the factorisation.
  X=   e#   Check for equality with X.
},
^      e# Symmetric set difference: removes N from the output list.

```

# Answer
> 6 votes
# 05AB1E, 17 bytes

Code:

```
ÒJ{©RƒNÒJ{®QN¹Ê*–

```

Explanation:

```
Ò                  # Get the factorization with duplicates, e.g. [3, 3, 13]
 J                 # Join the array, e.g. 3313
  {©               # Sort and store in ©, e.g. 1333
    R              # Reverse the number, e.g. 3331. This is the upperbound for the range
     ƒ             # For N in range(0, a + 1), do...
      NÒ           # Push the factorization with duplicates for N
        J          # Join the array
         {         # Sort the string
          ®Q       # Check if equal to the string saved in ©
            N¹Ê    # Check if not equal to the input
               *   # Multiply, acts as a logical AND
                –  # If 1, print N

```

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

# Answer
> 4 votes
## Pyth, 17

```
LSjkPb-fqyTyQSs_y

```

Test suite.

Uses the same observation as from Martin's post.

### Expansion:

```
LSjkPb        ##  Define a function y(b) to get the sorted string of digits
              ##  of the prime factors of b
    Pb        ##  prime factors
  jk          ##  join to a string with no separator
 S            ##  Sort

-fqyTyQSs_yQQ ##  Auto-fill variables
         _yQ  ##  get reversed value of y(input)
       Ss     ##  convert that string to a list [1 ... y(input)]
 fqyTyQ       ##  keep numbers T from the list that satisfy y(T)==y(input)
-           Q ##  remove the input from the result

```

# Answer
> 3 votes
## JavaScript (ES6), ~~163~~ 158 bytes

***Edit**: It has been clarified that a prime such as 23 should return \[6\] rather an empty result set. Saved 5 bytes by removing a now useless rule that was -- on purpose -- preventing that from happening.*

The last test case is commented so that this snippet runs fast enough, although it should complete in less than one minute just as well.

```
let f =

n=>[...Array(+(l=(p=n=>{for(i=2,m=n,s='';i<=m;n%i?i++:(s+=i,n/=i));return s.split``.sort().reverse().join``})(n))+1)].map((_,i)=>i).filter(i=>i&&i-n&&p(i)==l)

console.log(JSON.stringify(f(2)));
console.log(JSON.stringify(f(4)));
console.log(JSON.stringify(f(8)));
console.log(JSON.stringify(f(15)));
console.log(JSON.stringify(f(16)));
console.log(JSON.stringify(f(23)));
console.log(JSON.stringify(f(42)));
console.log(JSON.stringify(f(126)));
//console.log(JSON.stringify(f(204)));
```

# Answer
> 2 votes
# Powershell, 147 bytes (CodeGolf version)

```
param($n)filter d{-join($(for($i=2;$_-ge$i*$i){if($_%$i){$i++}else{"$i"
$_/=$i}}if($_-1){"$_"})|% t*y|sort -d)}2..($s=$n|d)|?{$_-$n-and$s-eq($_|d)}

```

Note: The script solve last test cases less than 3 minutes on my local notebook. See "performance" solution below.

Less golfed test script:

```
$g = {

param($n)
filter d{                       # in the filter, Powershell automatically declares the parameter as $_
    -join($(                    # this function returns a string with all digits of all prime divisors in descending order
        for($i=2;$_-ge$i*$i){   # find all prime divisors
            if($_%$i){
                $i++
            }else{
                "$i"            # push a divisor to a pipe as a string
                $_/=$i
            }
        }
        if($_-1){
            "$_"                # push a last divisor to pipe if it is not 1
        }
    )|% t*y|sort -d)            # t*y is a shortcut to toCharArray method. It's very slow.
}
2..($s=$n|d)|?{                 # for each number from 2 to number with all digits of all prime divisors in descending order
    $_-$n-and$s-eq($_|d)        # leave only those who have the 'all digits of all prime divisors in descending order' are the same
}

}

@(
    ,(2   ,'')
    ,(4   ,'')
    ,(6   ,23)
    ,(8   ,'')
    ,(15  ,53)
    ,(16  ,'')
    ,(23  ,6)
    ,(42  ,74, 146, 161)
    ,(107 ,701)
    ,(117 ,279, 939, 993, 3313, 3331)
    ,(126 ,222, 438, 483, 674, 746, 851, 1466, 1631, 1679)
    ,(204 ,364,548,692,762,782,852,868,1268,1626,2474,2654,2921,2951,3266,3446,3791,4274,4742,5426,5462,6233,6434,6542,7037,8561,14426,14642,15491,15833,22547)
) | % {
    $n,$expected = $_

    $sw = Measure-Command {
        $result = &$g $n
    }

    $equals=$false-notin(($result|%{$_-in$expected})+($expected|?{$_-is[int]}|%{$_-in$result}))
    "$sw : $equals : $n ---> $result"
}

```

Output:

```
00:00:00.0346911 : True : 2 --->
00:00:00.0662627 : True : 4 --->
00:00:00.1164648 : True : 6 ---> 23
00:00:00.6376735 : True : 8 --->
00:00:00.1591527 : True : 15 ---> 53
00:00:03.8886378 : True : 16 --->
00:00:00.0441986 : True : 23 ---> 6
00:00:01.1316642 : True : 42 ---> 74 146 161
00:00:01.0393848 : True : 107 ---> 701
00:00:05.2977238 : True : 117 ---> 279 939 993 3313 3331
00:00:12.1244363 : True : 126 ---> 222 438 483 674 746 851 1466 1631 1679
00:02:50.1292786 : True : 204 ---> 364 548 692 762 782 852 868 1268 1626 2474 2654 2921 2951 3266 3446 3791 4274 4742 5426 5462 6233 6434 6542 7037 8561 14426 14642 15491 15833 22547

```

---

# Powershell, 215 bytes ("Performance" version)

```
param($n)$p=@{}
filter d{$k=$_*($_-le3e3)
($p.$k=-join($(for($i=2;!$p.$_-and$_-ge$i*$i){if($_%$i){$i++}else{"$i"
$_/=$i}}if($_-1){($p.$_,"$_")[!$p.$_]})-split'(.)'-ne''|sort -d))}2..($s=$n|d)|?{$_-$n-and$s-eq($_|d)}

```

Note: I believe the performance requirements are in conflict with the GodeGolf principle. But since there was a rule `Your program should solve any of the test cases below in less than a minute`, I made two changes to satisfy the rule:

* `-split'(.)'-ne''` instead the short code `|% t*y`;
* a hashtable for cashing strings.

Each change reduces evaluation time by half. Please do not think that I have used all the features to improve performance. Just those were enough to satisfy the rule.

Less golfed test script:

```
$g = {

param($n)
$p=@{}                          # hashtable for 'all digits of all prime divisors in descending order'
filter d{                       # this function returns a string with all digits of all prime divisors in descending order
    $k=$_*($_-le3e3)            # hashtable key: a large hashtable is not effective, therefore a key for numbers great then 3000 is 0
                                # and string '-le3e3' funny
    ($p.$k=-join($(             # store the value to hashtable
        for($i=2;!$p.$_-and$_-ge$i*$i){
            if($_%$i){$i++}else{"$i";$_/=$i}
        }
        if($_-1){
            ($p.$_,"$_")[!$p.$_] # get a string with 'all digits of all prime divisors in descending order' from hashtable if it found
        }
    )-split'(.)'-ne''|sort -d)) # split each digit. The "-split'(.)-ne''" code is faster then '|% t*y' but longer.
}
2..($s=$n|d)|?{                 # for each number from 2 to number with all digits of all prime divisors in descending order
    $_-$n-and$s-eq($_|d)        # leave only those who have the 'all digits of all prime divisors in descending order' are the same
}

}

@(
    ,(2   ,'')
    ,(4   ,'')
    ,(6   ,23)
    ,(8   ,'')
    ,(15  ,53)
    ,(16  ,'')
    ,(23  ,6)
    ,(42  ,74, 146, 161)
    ,(107 ,701)
    ,(117 ,279, 939, 993, 3313, 3331)
    ,(126 ,222, 438, 483, 674, 746, 851, 1466, 1631, 1679)
    ,(204 ,364,548,692,762,782,852,868,1268,1626,2474,2654,2921,2951,3266,3446,3791,4274,4742,5426,5462,6233,6434,6542,7037,8561,14426,14642,15491,15833,22547)
) | % {
    $n,$expected = $_

    $sw = Measure-Command {
        $result = &$g $n
    }

    $equals=$false-notin(($result|%{$_-in$expected})+($expected|?{$_-is[int]}|%{$_-in$result}))
    "$sw : $equals : $n ---> $result"
}

```

Output:

```
00:00:00.0183237 : True : 2 --->
00:00:00.0058198 : True : 4 --->
00:00:00.0181185 : True : 6 ---> 23
00:00:00.4389282 : True : 8 --->
00:00:00.0132624 : True : 15 ---> 53
00:00:04.4952714 : True : 16 --->
00:00:00.0128230 : True : 23 ---> 6
00:00:01.4112716 : True : 42 ---> 74 146 161
00:00:01.3676701 : True : 107 ---> 701
00:00:07.1192912 : True : 117 ---> 279 939 993 3313 3331
00:00:07.6578543 : True : 126 ---> 222 438 483 674 746 851 1466 1631 1679
00:00:50.5501853 : True : 204 ---> 364 548 692 762 782 852 868 1268 1626 2474 2654 2921 2951 3266 3446 3791 4274 4742 5426 5462 6233 6434 6542 7037 8561 14426 14642 15491 15833 22547

```

# Answer
> 1 votes
# PHP 486 bytes

could probably be shorter with an algorithm that´s not so by the book.
(but I like the current byte count)

```
function p($n){for($i=1;$i++<$n;)if($n%$i<1&&($n-$i?p($i)==$i:!$r))for($x=$n;$x%$i<1;$x/=$i)$r.=$i;return $r;}function e($s){if(!$n=strlen($s))yield$s;else foreach(e(substr($s,1))as$p)for($i=$n;$i--;)yield substr($p,0,$i).$s[0].substr($p,$i);}foreach(e(p($n=$argv[1]))as$p)for($m=1<<strlen($p)-1;$m--;){$q="";foreach(str_split($p)as$i=>$c)$q.=$c.($m>>$i&1?"*":"");foreach(split("\*",$q)as$x)if(0===strpos($x,48)|p($x)!=$x)continue 2;eval("\$r[$q]=$q;");}unset($r[$n]);echo join(",",$r);

```

**breakdown**

```
// find and concatenate prime factors
function p($n)
{
    for($i=1;$i++<$n;)  // loop $i from 2 to $n
        if($n%$i<1      // if $n/$i has no remainder
            &&($n-$i    // and ...
                ?p($i)==$i  // $n!=$i: $i is a prime
                :!$r        // $n==$i: result so far is empty ($n is prime)
            )
        )
            for($x=$n;      // set $x to $n
                $x%$i<1;    // while $x/$i has no remainder
                $x/=$i)     // 2. divide $x by $i
                $r.=$i;     // 1. append $i to result
    return $r;
}

// create all permutations of digits
function e($s)
{
    if(!$n=strlen($s))yield$s;else  // if $s is empty, yield it, else:
    foreach(e(substr($s,1))as$p)    // for all permutations of the number w/o first digit
        for($i=$n;$i--;)            // run $i through all positions around the other digits
            // insert removed digit at that position and yield
            yield substr($p,0,$i).$s[0].substr($p,$i);
}

// for each permutation
foreach(e(p($n=$argv[1]))as$p)
    // create all products from these digits: binary loop through between the digits
    for($m=1<<strlen($p)-1;$m--;)
    {
        // and insert "*" for set bits
        $q="";
        foreach(str_split($p)as$i=>$c)$q.=$c.($m>>$i&1?"*":"");
        // test all numbers in the expression
        foreach(split("\*",$q)as$x)
            if(
                0===strpos($x,48)   // if number has a leading zero
                |p($x)!=$x          // or is not prime
            )continue 2; // try next $m
        // evaluate expression and add to results (use key to avoid array_unique)
        eval("\$r[$q]=$q;");
    }

// remove input from results
unset($r[$n]);

// output
#sort($r);
echo join(",",$r);

```

# Answer
> 1 votes
# Actually, 27 bytes

This uses the same algorithm that Martin, Adnan, FryAmTheEggman, and Dennis have been using. Golfing suggestions welcome. Try it online!

```
`w"i$n"£MΣSR≈`╗╜ƒ;╝R`╜ƒ╛=`░

```

**Ungolfing**

```
          Implicit input n.
`...`╗    Define a function and store it in register 0. Call the function f(x).
  w         Get the prime factorization of x.
  "..."£M   Begin another function and map over the [prime, exponent] lists of w.
    i         Flatten the list. Stack: prime, exponent.
    $n        Push str(prime) to the stack, exponent times.
               The purpose of this function is to get w's prime factors to multiplicity.
  Σ         sum() the result of the map.
             On a list of strings, this has the same effect as "".join()
  SR≈       Sort that string, reverse it and convert to int.
╜ƒ        Now push the function stored in register 0 and call it immediately.
           This gives the upper bound for any possible prime factor buddy.
;╝        Duplicate this upper bound and save a copy to register 1.
R         Push the range [0..u]
`...`░    Filter the range for values where the following function returns a truthy.
           Variable k.
  ╜ƒ        Push the function in register 0 and call it on k.
  ╛=        Check if f(k) == f(n).
          Implicit return every value that is a prime factor buddy with n, including n.

```

# Answer
> 1 votes
# Japt, 18 bytes

```
k ¬ñ
Ôn õ f@¥Xk ¬ñ

```

Try it

---
Tags: code-golf, number, primes, permutations, factoring
---


title: Worded Calculator

text:
# Question
Title: Worded Calculator
A simplistic version of English numeral calculator

### Task

Write a program that takes a string as input and outputs the result of the expression.

### Rules

The input string will be worded and not numeral.

There will be no parentheses.

Order of calculation will be divide,multiply,subtract then add.

For same operations, the calculations must be done from left to right.

All input numbers will be integers from -999 to 999 (both inclusive)

Output will be an integer of any range.

Division will always be perfectly divisible and zero will never be a denominator.

Restriction of case for input is optional. You don't have to check for the validity of the input.

### Number Format

```
0 to 20 -> zero,one,two...nineteen,twenty
21 to 99 -> twenty one,twenty two.....ninety eight,ninety nine
100 to 999 -> one hundred, one hundred one, one hundred two...one hundred ten....two hundred fifty....nine hundred ninety eight,nine hundred ninety nine

```

For negative numbers: Add `minus` to its positive equivalent

### Operation Format

```
Addition: one plus two
Subtraction: one minus two
Multiplication: one time two #Note that for one on the left of multiplication, it is one time and not times.
                two times one hundred
Division: forty divided by two

```

### Examples:

```
o/p <- input

20     four times five
35     twenty plus fifteen
70     fifty plus five times four
-90    minus one time ninety
25     twenty one minus minus four
45     ninety divided by two
700    one time seven hundred
555    one hundred eleven times two plus three hundred thirty three
99     one hundred plus minus one
45     forty five plus two hundred times zero
 4     four
-3     three minus three minus three

```

**This is code-golf so shortest code wins**

# Answer
# JavaScript (ES6), ~~257~~ ~~252~~ ~~249~~ 235 bytes

*Saved 3 bytes thanks to @Shaggy*

```
s=>eval(s.split` `.map(w=>(i='zeonwohrr44fx3n5t54nn3leel8tou7fn7n98etetwthfofisiseeinihuplmitidiby'.match(/../g).findIndex(x=>~(w+w.length+w).search(x)))>28?n+' '+'+-*/ '[n='',i-29]:(n=+n+(i<28?i<20?i:i*10-180:n*99),''),n='').join``+n)

```

Try it online!

## How?

Once the input string has been split into words, each word \\$W\\$ of length \\$L\\$ is converted to an index \\$i\\$ by looking for the first 2-character key substring that can be found in \\$W+L+W\\$.

### Numbers

```
 index | word              | word + length + word         | key substring
-------+-------------------+------------------------------+---------------
    0  | "zero"            | "zero4zero"                  | "ze"
    1  | "one"             | "one3one"                    | "on"
    2  | "two"             | "two3two"                    | "wo"
    3  | "three"           | "three5three"                | "hr"
    4  | "four"            | "four4four"                  | "r4"
    5  | "five"            | "five4five"                  | "4f"
    6  | "six"             | "six3six"                    | "x3"
    7  | "seven"           | "seven5seven"                | "n5"
    8  | "eight"           | "eight5eight"                | "t5"
    9  | "nine"            | "nine4nine"                  | "4n"
   10  | "ten"             | "ten3ten"                    | "n3"
   11  | "eleven"          | "eleven6eleven"              | "le"
   12  | "twelve"          | "twelve6twelve"              | "el"
   13  | "thirteen"        | "thirteen8thirteen"          | "8t"
   14  | "fourteen"        | "fourteen8fourteen"          | "ou"
   15  | "fifteen"         | "fifteen7fifteen"            | "7f"
   16  | "sixteen"         | "sixteen7sixteen"            | "n7"
   17  | "seventeen"       | "seventeen9seventeen"        | "n9"
   18  | "eighteen"        | "eighteen8eighteen"          | "8e"
   19  | "nineteen"        | "nineteen8nineteen"          | "te"
   20  | "twenty"          | "twenty6twenty"              | "tw"
   21  | "thirty"          | "thirty6thirty"              | "th"
   22  | "forty"           | "forty5forty"                | "fo"
   23  | "fifty"           | "fifty5fifty"                | "fi"
   24  | "sixty"           | "sixty5sixty"                | "si"
   25  | "seventy"         | "seventy7seventy"            | "se"
   26  | "eighty"          | "eighty6eighty"              | "ei"
   27  | "ninety"          | "ninety6ninety"              | "ni"
   28  | "hundred"         | "hundred7hundred"            | "hu"

```

### Operators

```
 index | word              | word + length + word         | key substring
-------+-------------------+------------------------------+---------------
   29  | "plus"            | "plus4plus"                  | "pl"
   30  | "minus"           | "minus5minus"                | "mi"
   31  | "times" or "time" | "times5times" or "time4time" | "ti"
   32  | "divided"         | "divided7divided"            | "di"
   33  | "by"              | "by2by"                      | "by"

```

### Interpretation

The current number is stored in \\$n\\$, which is initialized to an empty string. Given the index \\$i\\$ of the next word, the following logic applies:

```
i > 28 ?                  // if the word is an operator:
  n +                     //   append n (which is either an empty string or a number)
  ' ' +                   //   append a space
  '+-*/ '[n = '', i - 29] //   reset n to an empty string and append the operator
                          //   the useless keyword 'by' is translated into a harmless space
: (                       // else:
    n =                   //   update n:
      +n + (              //     force the coercion of the current value of n to a number
        i < 28 ?          //     if the word is not 'hundred':
          i < 20 ?        //       if the value of the word is less than 'twenty':
            i             //         add i
          :               //       else:
            i * 10 - 180  //         add i * 10 - 180 (e.g. 'fifty' -> 23 * 10 - 180 = 50)
        :                 //     else:
          n * 99          //       multiply n by 100 by adding 99 * n to itself
      ),                  //
    ''                    //   remove this word from the original string
  )                       //

```
> 18 votes

# Answer
# Perl 6, ~~170 139 129 128 124~~ 122 bytes

*-13 bytes thanks to nwellnhof!*

```
{S:g/(<:N>+)+%\s/({'+'X$0})/.EVAL}o{S:g/" ҈"/00/}o{TR"ŉ؊⟠"*/൰ "}o*.words>>.&{chr first *.uniname.comb(.uc),1..*}

```

Try it online!

`unival` to the rescue again! This is (currently) even beating golfing languages like `05AB1E`!

### Explanation:

```
*.words     # Split by word boundaries (in this case spaces)
       >>.{                            }  # Map each word to
           chr first             ,1..*    # The first character where:
                     *.uniname      # The unicode name of that character
                                    # e.g. DIGIT FIVE
                      .comb(.uc)    # Contains the uppercase of the word
{             }o  # Pass this list to another function
                  # That converts the list to a string
 TR"ŉ؊⟠"*/൰ "    #"# And parse out the garbage characters that were wrong
                  # INVISIBLE TIMES => "*"
                  # LOZENGE DIVIDED BY HORIZONTAL RULE => "/"
                  # ARABIC-INDIC PER TEN THOUSAND SIGN => "൰" (value ten)
                  # LATIN SMALL LETTER N PRECEDED BY APOSTROPHE => " "
{S:g/" ҈"/00/}o   # Replace the character for "hundred" with 00

{                                }o   # And finally combine with
 S:g/(<:N>+)+%\s/   # Substitute each number-like character separated by spaces
                /({'+'X$0})/   # With the numbers prefixed by '+'s, in brackets
               # This works because Perl 6 supports numeric unicode literals, like
               # ፳ => 20, ፴ => 30, ፺ => 90, etc.
                            .EVAL   # And finally evaluate the whole expression

```
> 11 votes

# Answer
# Python 2, ~~333~~ ~~...~~ ~~284~~ ~~277~~ 275 bytes

```
lambda s:eval(''.join((list('+-/*')+[`N(w,0)*100+N(w,2)`])['pmdt'.find(w)]for w in re.split(' *(?:(p|m)|(t|d)i|by).*? ',s)if w))
N=lambda x,y:sum(10*(w[-3:]in'lveen')+'zeontwthfofisiseeiniteel'.find(w[:2])/2*10**('y'in w)for w in x.rpartition('hundred')[y].split())
import re

```

Try it online!
> 7 votes

# Answer
# Wolfram Language ~~95 94~~ 82 bytes

```
Interpreter["SemanticExpression"][#~StringReplace~{"me "->"mes ","plus m"->"m"}]&

```

`#` represents the input for the pure function.

If necessary,`StringReplace` replaces "time " with times ", "plus minus" with "minus" (through `"me "->"mes "`,`"plus m"->"m`", respectively). The shortened replacement forms, suggested by `lirtosiast`, saved 12 bytes.

`Interpreter["SemanticExpression"]` does all the rest.
> 5 votes

# Answer
# 05AB1E, ~~166~~ ~~147~~ ~~141~~ ~~139~~ 135 bytes

```
„byK“¡×€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š—¿áÓÁÏ“#vyN:}'tK'…§¦'+T«:'°¡„ *т«©:.•1×j›o!ĆÖ•3ôŽ9oS:'y®¨:©“‰´Øè„Æ€ººß“'tK#UX¡εð¡õK2ôJ.EO}®áX"+-**/"S:Sðì.ιJ.E

```

Way too long.. Will try to golf it down from here.

-4 bytes thanks to *@Emigna*.
-2 bytes thanks to *@JoKing*.

Try it online or verify all test cases.

**Explanation:**

```
„byK                 # Remove "by" from the (implicit) input-string
“¡×€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š—¿áÓÁÏ“
                     # Push string "zero one two three four five six seven eight nine ten eleven twelve"
 #                   # Split by spaces
  v   }              # Loop over each of these items:
   yN:               #  Replace the item with its 0-indexed index
'tK                 '# Remove all "t"
'…§¦                '# Push string "teen", and remove the first character: "een"
    '+              '# Push string "+"
      T«             # Append 10: "+10"
        :            # Replace all "een" with "+10"
'°¡                 '# Push string "hundred"
   „ *               # Push string " *"
      т«             # Append 100: " *100"
        ©            # Store it in the register (without popping)
         :           # Replace all "hundred" with " *100"
.•4º»Ÿć'Rþн•        '# Push string "wenhirforfif"
            3ô       # Split the string into parts of size 3: ["wen","hir","for","fif"]
              Ž9o    # Push integer 2345
                 S   # Split to digits: [2,3,4,5]
                  :  # Replace each
'y                  '# Push string "y"
  ®                  # Push the " *100" from the register
   ¨                 # Remove the last character: " *10"
    :                # Replace all "y" with " *10"
©                    # Save the current string in the register (without popping)
 “‰´Øè„Æ€ººß“        # Push string "plus minus times time divided"
             'tK    '# Remove all "t": "plus minus imes ime divided"
                #    # Split by spaces: ["plus","minus","imes","ime","divided"]
                 U   # Pop and save it in variable `X`
                  X  # And push variable `X` back again
                   ¡ # Split the string by those operator-strings
ε          }         # Map each substring to:
 ð¡                  #  Split by spaces (NOTE: cannot be `#`; if the string contains no
                     #   spaces, `#` remains string, whereas `ð¡` wraps it in a list)
   õK                #  Remove empty strings from the list
     2ô              #  Split the list into parts of two
       J             #  Join each pair together
        .E           #  Evaluate each as a Python `eval` expression
          O          #  Sum them
®                    # Put the string from the register to the stack again
 á                   # Remove everything except for letters
  X                  # Push variable `X`: ["plus","minus","imes","ime","divided"]
   "+-**/"           # Push string "+-**/"
          S          # Split to characters: ["+","-","*","*","/"]
           :         # Replace each
S                    # Split the string of operators to loose characters
 ðì                  # Prepend a space before each
   .ι                # Interweave all sums with these operator-characters
     J               # Join everything together to a single string
.E                   # Evaluate each as a Python `eval` expression (and output implicitly)

```

See this 05AB1E tip of mine (sections *How to use the dictionary?*, *How to compress strings not part of the dictionary?*, and *How to compress large integers?*) to understand how `“¡×€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š—¿áÓÁÏ“`, `'…§`, `'°¡`, `.•4º»Ÿć'Rþн•`, `Ž9o`, and `“‰´Øè„Æ€ººß“` work.

**Step by step example:**

* **Input:** `two hundred twenty two divided by two times minus fifty seven plus three hundred eighteen minus minus ten`
* Step 1: Remove "by": `two hundred twenty two divided two times minus fifty seven plus three hundred eighteen minus minus ten`
* Step 2: Convert "zero" through "twelve" with the correct number: `2 hundred twenty 2 divided 2 times minus fifty 7 plus 3 hundred 8een minus minus 10`
* Step 3: Remove all "t": `2 hundred weny 2 divided 2 imes minus fify 7 plus 3 hundred 8een minus minus 10`
* Step 4: Replace all "een" with "+10": `2 hundred weny 2 divided 2 imes minus fify 7 plus 3 hundred 8+10 minus minus 10`
* Step 5: Replace all "hundred" with " \*100": `2 *100 weny 2 divided 2 imes minus fify 7 plus 3 *100 8+10 minus minus 10`
* Step 6: Replace all \["wen","hir","for","fif"\] with the correct digit: `2 *100 2y 2 divided 2 imes minus 5y 7 plus 3 *100 8+10 minus minus 10`
* Step 7: Replace all "y" with " \*10": `2 *100 2 *10 2 divided 2 imes minus 5 *10 7 plus 3 *100 8+10 minus minus 10`
* Step 8: Split by \["plus","minus","ime","imes","divided"\]: `["2 *100 2 *10 2 "," 2 "," "," 5 *10 7 "," 3 *100 8+10 "," "," 10"]`
* Step 9: Split each on spaces: `[["2","","*100","2","*10","2",""],["","","2",""],["",""],["","5","*10","7",""],["","3","","*100","8+10",""],["",""],["","10"]]`
* Step 10: Remove empty items: `[["2","*100","2","*10","2"],["2"],[],["5","*10","7"],["3","*100","8+10"],[],["10"]]`
* Step 11: Split into parts of size 2 and join: `[["2*100","2*10","2"],["2"],"",["5*10","7"],["3*100","8+10"],"",["10"]]`
* Step 12: Python `eval` each: `[[200,20,2],[2],"",[50,7],[300,18],"",[10]]`
* Step 13: Sum each: `[222,2,"",57,318,"",10]`
* Step 14: Re-push the string from the register, and remove everything except letters: `dividedimesminusplusminusminus`
* Step 15: Replace "plus","minus","imes","ime","divided" with the operator characters, and prepend them with a space: `[" /"," *"," -"," +"," -"," -"]`
* Step 16: Interweave and join both together: `222 /2 * -57 +318 - -10`
* **Output:** Python `eval` the string, and output implicitly: `-5999.0`
> 3 votes

# Answer
# sfk, ~~572~~ ~~449~~ 423 bytes

This could all be one line, but for the purposes of reading it I used newlines instead of spaces.

```
xed -i
_plus_+_
_minus_-_
_times[ortext]time_*_
_divided?by_/_
+xed
"_[white][2 chars of a-z][chars of a-z]ty_[parts 1,2]0_"
"_[white][2 chars of a-z][chars of a-z]een_[part1]1[part2]_"
_ten_10_
_lev_11_
_twe_12_
+xed
_ze_0_
_on_1_
_tw_2_
_th_3_
_fo_4_
_fi_5_
_si_6_
_se_7_
_ei_8_
_ni_9_
+xed
_0[white][keep][digit]__
"_[chars of e-z ]__"
+xed
"_?dd[keep][2 digits]_[part1]_"
_?dd[keep][digit]_[part1]0_
_dd_00_
+calc #text

```

Try it online!
> 2 votes

---
Tags: code-golf
---