title: Worn-tile Scrabble

text:
# Question
Title: Worn-tile Scrabble
## Problem

You're stuck in a cabin in the middle of the woods, with only an old scrabble set to entertain yourselves. Upon inspection you see that the scrabble letters are so worn, that only the points for each letter are visible.

Nonetheless you decide to play a game. You pull seven letters from the bag and place them on your tray, your challenge is to determine what those letters could be.

So generally, given a list of points convert it into any possible string or list of letters.

---

## Scrabble Tiles and Distributions

* 2 blank tiles (scoring 0 points)
* 1 point: E ×12, A ×9, I ×9, O ×8, N ×6, R ×6, T ×6, L ×4, S ×4, U ×4
* 2 points: D ×4, G ×3
* 3 points: B ×2, C ×2, M ×2, P ×2
* 4 points: F ×2, H ×2, V ×2, W ×2, Y ×2
* 5 points: K ×1
* 8 points: J ×1, X ×1
* 10 points: Q ×1, Z ×1

So if you have a list of points `[10,10,8,5,1,1,1]` then `"QZJKEEE"` would be valid but `"QQJKEEE"` would not be valid (since there is only 1 Q tile in the bag)

---

## Problem Specific Rules

* You may assume all inputs are valid and that there will always be 7 tiles (i.e it wont be a list of seven 10 point tiles and won't be 9 tiles)
* You can assume no tiles have been previously pulled from the bag (so the distribution is the standard distribution of english tiles as defined above)
* You do not have to generate a valid word, only a valid string of letters.
* The order of your string is irrelevant as long as for each tile there is a corresponding letter.
* Points are based on the standard english scrabble tile points as defined above.
* You may output in upper or lower case, for a blank tile you may output either a space character or an underscore '\_'
* Your answer may output as any reasonable representation of the tiles such as a List, String, Array or Sequence

---

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code (i.e. TIO).
* Also, adding an explanation for your answer is highly recommended.

---

## Test Cases

Obviously since you can output any possible value it's difficult to define strict test cases.

Some cases with a *possible valid* return value:

```
[10,0,10,5,8,8,0] -> "Q ZKJX "
[1,1,1,1,1,1,1] -> "EEEEEEE"
[1,2,3,4,5,8,0] -> "NDBHKJ "
[2,2,2,2,2,2,2] -> "DGDGDGD"

```

Some cases with an *invalid* return value:

```
[10,0,10,5,8,8,0] -> "Q QKJX "  - Too many Qs
[1,1,1,1,1,1,1] -> "EEEEEE "  - Space is 0 points not 1
[1,2,3,4,5,8,0] -> "NDBH" - Too short
[1,2,3,4,5,8,0] -> "NDBHKJ  I" - Too long
[1,2,3,4,5,8,0] -> "ÉDBHKJ1" - Contains none scrabble characters
[2,2,2,2,2,2,2] -> "GDGDGDG" - Contains too many Gs (case for invalid cycling)

```

# Answer
> 8 votes
# JavaScript (ES6), 72 bytes

*A shorter variant suggested by @supercat*

```
a=>a.map(o=n=>'?ED?BWQ?_EG?CFZ?_EDJMH?K?EGXPV'[n*9.4+(o[n]=7-~o[n])&31])

```

Try it online!

---

# JavaScript (ES6),  ~~137 ... 84 78 77~~  76 bytes

*Saved 10 bytes by using Neil's cycling method*

Returns a list of tiles. Uses `_` for blank tiles.

```
a=>a.map(o=n=>"____FHVWGDGD_K__BCMPEEEE_ZQ__XJ"[n*20%44%32+(o[n]=-~o[n])%4])

```

Try it online!

### How?

For each number of points, we cycle through a group of exactly 4 tiles, starting with the *second* tile of each group (this is important for `G` vs `D`):

```
 points | group | max. sequence
--------+-------+---------------
    0   | ____  | __
    1   | EEEE  | EEEEEEE
    2   | GDGD  | DGDGDGD
    3   | BCMP  | CMPBCMP
    4   | FHVW  | HVWFHVW
    5   | _K__  | K         \
    8   | _XJ_  | XJ         }--- these letters may only appear once each
   10   | _ZQ_  | ZQ        /

```

All these groups are stored as a single string of 31 characters:

```
____FHVWGDGD_K__BCMPEEEE_ZQ__XJ
^   ^   ^   ^   ^   ^   ^   ^
0   4   8  12  16  20  24  28

```

*NB*: We don't need to store the final `"_"` in `"_XJ_"`, as it will never be accessed anyway.

The number of points \\$n\\$ is converted to the correct index \\$i\_n\\$ into this string with:

$$i\_n=((20\times n)\bmod 44)\bmod 32$$

```
  n | *20 | mod 44 | mod 32 | group
----+-----+--------+--------+-------
  0 |   0 |    0   |    0   | ____
  1 |  20 |   20   |   20   | EEEE
  2 |  40 |   40   |    8   | GDGD
  3 |  60 |   16   |   16   | BCMP
  4 |  80 |   36   |    4   | FHVW
  5 | 100 |   12   |   12   | _K__
  8 | 160 |   28   |   28   | _XJ_
 10 | 200 |   24   |   24   | _ZQ_

```

The current position in each group is stored in the object \\$o\\$.

# Answer
> 7 votes
# Charcoal, 33 bytes

```
⭆θ§§⪪”＆↖“Ｖh_z↶∕¡⌈∨₂χ¹‖◨⌊″”¶ι№…θκι

```

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

```
 θ                  Input array
⭆                   Map over elements and join
     ”...”          Literal string " \nE\nDG\nBCMP\nFHVW\nK\n\n\nJX\n\nQZ"
    ⪪     ¶         Split on newlines
   §       ι        Indexed by current element
  §                 Cyclically indexed by
            №…θκι   Number of times current element has already appeared
                    Implcitly print

```

# Answer
> 5 votes
# Jelly,  ~~31 30 27~~  26 bytes

```
“ñẒẎYñ(“Nut¦hß’ṃØA;€⁶ɓṢĖœị

```

A monadic Link accepting a list of integers which yields a list of characters.
\- a mishmash of my previous, below, and my improvement of Nick Kennedy's

**Try it online!**

The output is not given in the same order as the input (this is allowed).

Using 2 of my own additions to the language in an answer does not happen often! ( and `ɓ` here).

### How?

```
“...“...’ṃØA;€⁶ɓṢĖœị - Link: list of integers, V     e.g. [10,1,0,3,2,1,10]
“...“...’            - list of base 250 integers          [28089224382041, 77611203526272]
          ØA         - 'ABC...XYZ'
         ṃ           - base decompress (vectorises)       ["EDMFKZZJZQ", "NGPYKZZXZZ"]
            ;€       - for €ach: concatenate:
              ⁶      -   a space                          ["EDMFKZZJZQ ", "NGPYKZZXZZ "]
               ɓ     - start a new dyadic chain with swapped arguments - i.e. f(V,that)
                Ṣ    - sort                               [0,1,1,2,3,10,10]
                 Ė   - enumerate                          [[1,0],[2,1],[3,1],[4,2],[5,3],[6,10],[7,10]]
                  œị - multi-dimensional index into       " NEGMZQ"
                       (1-based and modular)

```

---

previous @ 30

```
“²rṛʂṂø5=Ɓṇ^N¥Y»⁾tky;⁶s2ɓṢĖUœị

```

A monadic Link accepting a list of integers which yields a list of characters.

Try it online!

This one's output is also mixed-case (this is allowed).

### How?

```
“...»⁾tky;⁶s2ɓṢĖUœị - Link: list of integers, V          e.g. [10,1,0,3,2,1,10]
“...»               - compression of dictionary entries:
                    -   "end", "GMP", "fyttes", "adj", and "xci" and the string "qz"
                    -                                         "endGMPfyttesadjxciqz"
        y           - translate with:
     ⁾tk            -   ['t', 'k']                            "endGMPfykkesadjxciqz"
         ;⁶s2ɓṢĖUœị - ...
                    - ...then like the above method (except U reverses each pair of indices)
                                                              " neGMzq"

```

# Answer
> 4 votes
# Pyth - ~~92~~ ~~86~~ ~~83~~ ~~81~~ ~~80~~ ~~75~~ ~~60~~ ~~52~~ ~~49~~ ~~42~~ 36 bytes

Loops through input, popping off the available letters. I just have one of each letter that together give 7 for that point category. Now using packed string encoding.

```
K[M*L7c."B_êº çÑOÒ
7âCkÑ"\Lm.)@K

K                       Assign to K
 [M                     Map list(for popping). Uses a quirk of M to splat each first
  *L7                   Map repeating each string by 7
   c      \L            Split on occurrences of 'L'
    ."..."              Packed string encoding of the needed letters
m              (Q)      Map on input (input is taken implicitly)
 .)                     Pop. This returns the first element after removing it
  @K                    Index into K
   (d)                  The loop variable is given implicitly

```

Btw, this is the original letter string before encoding: `"_ E DG BCMP FHVW K JX QZ"`.

Try it online.

# Answer
> 3 votes
# 05AB1E, ~~70~~ ~~52~~ ~~39~~ ~~38~~ ~~29~~ ~~26~~ 25 bytes

```
{ε.•3Oû}α›ηö‡.ÝŽ{•2ôÁyèNè?

```

-18 bytes thanks to *@ExpiredData*.
-13 bytes by using the same extend to size 7 from *@Maltysen*'s Pyth answer.
-9 bytes by creating a port of *@JonathanAllan*'s Jelly answer, so make sure to upvote him!
-3 bytes thanks to *@Emigna*.

Results in a list of characters, and uses lowercase letters and a space for blanks.

Try it online or verify some more test cases.

**Explanation:**

```
{                      # Sort the (implicit) input-list
 ε                     # Map each character `y` in this list to:
  .•3Oû}α›ηö‡.ÝŽ{•     #  Push compressed string "endgmpfykkzzzzjxzzqz "
                  2ô   #  Split into parts of size 2
                    Á  #  Rotate it once towards the left so the space is leading
  yè                   #  Use integer `y` to index into the string-pairs
    Nè                 #  Then get the `N`'th character of the string-pair (with automatic
                       #   wraparound), where `N` is the index of the loop

```

See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*) to understand why `.•3Oû}α›ηö‡.ÝŽ{•` is `"endgmpfykkzzzzjxzzqz "`.

---

**Previous 38 bytes answer:**

```
.•Mñ&Àû«ì{₆v*Å+µ-•#ðšε7∍}IvDyèн©?ε®õ.;

```

Try it online or verify some more test cases.

**Explanation:**

```
.•Mñ&Àû«ì{₆v*Å+µ-•    # Push compressed string "e dg bcmp fhvw k   jx  qz"
                  #   # Split on spaces: ["e","dg","bcmp","fhvw","k","","","jx","","qz"]
                   ðš # Prepend a space to this list
 ε7∍}                 # Extend each string to size 7:
                      #  ["       ","eeeeeee","dgdgdgd","bcmpbcm","fhvwfhv","kkkkkkk","","","jxjxjxj","","qzqzqzq"]
     Iv               # Loop `y` over the input-list:
       Dyè            #  Get the `y`'th string from a copy of the list
          н           #  Get it's first character
           ©?         #  Store it in the register, and print it without trailing newline
        ε             #  Then map each string in the list to:
         ®õ.;         #   Remove the first occurrence of the character from the register

```

See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*) to understand why `.•Mñ&Àû«ì{₆v*Å+µ-•` is `"e dg bcmp fhvw k jx qz"`.

# Answer
> 3 votes
# Perl 5, 71 bytes

```
@a=(__,'E'x7,DDDDGGG,BBCCMMP,FFHHVVW,K,1,1,JX,1,QZ);say chop$a[$_]for<>

```

Try it online!

# Answer
> 2 votes
# C (gcc), 110 bytes

```
_[]={0,7,14,21,0,0,22,0,24};f(char*s){for(;*s+1;s++)*s=*s?*s-1?"DDDDGGGBBCCMMPFFHHVVWKJXQZ"[_[*s-2]++]:69:32;}

```

Try it online!

Uses the `_` array as an index into the static string `"DDDDGGGBBCCMMPFFHHVVWKJXQZ"` dynamically with exceptions for 0 and 1.

Argument is a `-1`-terminated array of scores which is transformed in-place into a `-1`-terminated string.

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), ~~104~~ 90 bytes

```
a=>a.OrderBy(x=>x).Select((x,i)=>(x="_ E DG BCMP FHVW K   JX  QZ".Split()[x])[i%x.Length])

```

Try it online!

# Answer
> 1 votes
# Python 3, ~~178~~ ~~142~~ ~~135~~ ~~127~~ ~~112~~ 117 bytes

```
def f(l):
 d=list(map(list,"  _EEEEEEE_DDDDGGG_BBCCMMP_FFHHVVW_K___JX__QZ".split('_')))
 return[d[i].pop()for i in l]

```

Try it online!

*-1 byte thanks to cdlane*

*correct thanks to mathmandan*

# Answer
> 1 votes
# Jelly, ~~34~~ 32 bytes

```
“¿RÇĊƈ⁸⁾%ỵṆþœsṀṂ’ṃØAṣ”A;⁶ẋ€7⁸ịḢ€

```

Try it online!

I hadn’t seen there was a shorter Jelly answer when I wrote this, and this uses a different approach so I thought was worth posting as well.

Thanks to @JonathanAllan for saving 2 bytes!

# Answer
> 0 votes
# PHP, 101 bytes

```
$b=[_,E,DG,BCMP,FHVW,K,8=>JX,0,QZ];foreach($argv as$t){echo$c=($d=$b[$t])[0];$b[$t]=substr($d,1).$c;}

```

As a standalone program, input via command line:

```
$ php s.php 10 0 10 5 8 8 0
"Q_ZKJX_"

```

Try it online!

### Or 112 bytes as a function

```
function($a){$b=[_,E,DG,BCMP,FHVW,K,8=>JX,0,QZ];foreach($a as$t)$b[$t]=substr($d=$b[$t],1).$c[]=$d[0];return$c;}

```

Try it online!

**Output**

```
[10,0,10,5,8,8,0]   "Q_ZKJX_"
[1,1,1,1,1,1,1]     "EEEEEEE"
[1,2,3,4,5,8,0]     "EDBFKJ_"
[2,2,2,2,2,2,2]     "DGDGDGD"

```

# Answer
> 0 votes
# Python 2, 102 bytes (or maybe 95?)

(Also fine for Python 3.)

```
lambda a:''.join([r*7for r in'_ E DG BCMP FHVW K * * JX * QZ'.split()][x][:a.count(x)]for x in set(a))

```

Try it online!

I don't think the following would be acceptable:

```
lambda a:[[r*7for r in'_ E DG BCMP FHVW K * * JX * QZ'.split()][x][:a.count(x)]for x in set(a)]

```

This second version would give output like `['__', 'JX', 'QZ', 'K']`. So the letters would be correct, but they would be collected by point value. (If this were acceptable, it would save 7 bytes.)

# Answer
> 0 votes
# Ruby, ~~77~~ 76 bytes

```
->a{r=%w{_ E DG BCMP FHVW K . . JX . QZ};a.map{|i|(r[i]<<r[i][0]).slice! 0}}

```

Try it online!

# Answer
> 0 votes
# Perl 6, 63 bytes

```
*>>.&{(<_ E DG BCMP FHVW K _ _ JX _ QZ>[$_]x 7).comb[%.{$_}++]}

```

Try it online!

```
<_ E DG BCMP FHVW K _ _ JX _ QZ> # array indexed on tile value
(<...>[$_] x 7)     # pull letters for this value, repeat 7 times to catch E
          %         # anonymous stateful hash
           .{$_}    # element for this tile value
                ++  # post increment value to move position
       .comb[...]   # characters to array, pull this incrementing index

```

So essentially it keeps a lookup of offsets for each tile value and increments them as needed, using the offset to pull a character from the available set.

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


title: Prime Powers of Primes

text:
# Question
Title: Prime Powers of Primes
For the purpose of this challenge, a Prime Power of a Prime (PPP) is defined as a number that can be defined as a prime number to the power of a prime number. For example, 9 is a PPP because it can be represented as 3^2. 81 on the other hand is not a PPP because it can only be represented as 3^4, and 4 is not prime. The first few PPPs are: 4, 8, 9, 25, 27, 32, 49, 121, 125, 128, 169, 243, 289, 343... This is OEIS sequence A053810

## Your Task:

Write a program or function that for an input integer n returns/outputs the nth PPP, either 1-indexed or 0-indexed, whichever you prefer.

## Input:

An integer between 0 and 1,000, received through any reasonable method.

## Output:

The PPP at the index indicated by the input.

## Test Cases:

These are 1-indexed, and so, if your program takes 0-indexed input, the same output should be arrived at for the stated input - 1.

```
3  -> 9
6  -> 32
9  -> 125

```

## Scoring:

This ,lowest score in bytes wins!

# Answer
# 05AB1E (legacy),  ~~9~~  7 bytes

*Saved 2 bytes thank to @KevinCruijssen*

```
µNÓ0Kp»

```

Try it online!

```
µ           # while counter_variable != input:
 N          #   push iteration counter                       e.g. 125
  Ó         #   get prime exponents                          -> [0, 0, 3]
   0K       #   filter out zeros                             -> [3]
     p      #   is prime?                                    -> [1]
      »     #   join with newlines: we use » instead of J
            #   so that [0,1] is not interpreted as truthy   -> 1
            #   implicit: if 1, increment counter_variable

```
> 8 votes

# Answer
# Haskell, ~~95~~ ~~85~~ 80 bytes

*-10 bytes thanks to @Lynn*
*-5 bytes thanks to @WillNess*

0-based

```
(!!)[x|x<-[2..],p<-[[i|i<-[2..x],all((>)2.gcd i)[2..i-1]]],or[y^e==x|e<-p,y<-p]]

```

Try it online!

**Explanation**

```
(!!)                    -- point-free expression, partially evaluate index-access operator
[x|x<-[2..]             -- consider all integers x>=2
,p<-                    -- let p be the list of all primes <=x
[[                      -- list of a list so p ends up as a list
i|i<-[2..x],            -- consider all i<=x to be potentially prime
all((>)2.gcd i)[2..i-1] -- if the gcd of i with all smaller integers is
                        -- smaller than 2 then this i is actually prime
 ]],or                  -- if any of the following list entries is true
[y^e==x|                -- the condition y^e==x holds for x with ...
e<-p,y<-p]              -- y and e being prime, i.e. x is a PPP,
]                       -- then add this x to the output sequence / list

```
> 5 votes

# Answer
# Husk, 10 bytes

```
!fȯṗ§*ELpN

```

Try it online!

## Explanation

```
!fȯṗ§*ELpN  Implicit input.
 f       N  Filter the natural numbers by this function:
  ȯṗ§*ELp    Argument is a number, say 27.
        p    Prime factors: [3,3,3]
       L     Length: 3
      E      Are all elements equal: 1
    §*       Multiply last two: 3
  ȯṗ         Is it prime? Yes, so 27 is kept.
!           Index into remaining numbers with input.

```
> 5 votes

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

1 byte thanks to Dennis.

```
ÆN€*þ`FṢị@

```

Try it online!
> 4 votes

# Answer
# Actually, 14 bytes

Based on Mr. Xcoder's Pyth solution. Golfing suggestions welcome. Try it online!

```
;ur♂P;∙⌠iⁿ⌡MSE

```

**Ungolfing**

```
                Implicit input n
;ur             Duplicate and push [0..n]
   ♂P           Push the 0th to nth primes
     ;∙         Push Cartesian square of the primes
       ⌠iⁿ⌡M    Reduce each list in the Cartesian square by exponentiation
            SE  Sort the list and get the nth index (0-indexed)

```
> 4 votes

# Answer
# Mathematica, 48 bytes

```
Sort[Join@@Array[(p=Prime)@#^p@#2&,{#,#}]][[#]]&

```

Try it online!

but Martin Ender had a better idea and saved 6 bytes

# Mathematica, 42 bytes

```
Sort[Power@@@Prime@Range@#~Tuples~2][[#]]&

```

Try it online!
> 4 votes

# Answer
# Python 2, ~~163~~ ~~157~~ ~~137~~ 136 bytes

* Saved six bytes by using `input()` rather than defining a function.
* Saved four bytes thanks to Felipe Nardi Batista; merging two loops.
* Saved sixteen bytes thanks to ASCII-only.
* Saved a byte thanks to ArBo.

```
p=input();r=i=0;e=lambda p:all(p%d for d in range(2,p))
while~-i<p:
 r+=1
 for x in range(r*r):y=x%r;x/=r;i+=x**y==r>e(x)>0<e(y)
print r

```

Try it online!
> 4 votes

# Answer
# \+ numbers, 57 bytes

```
function(n,x=numbers::Primes(2*n))sort(outer(x,x,"^"))[n]

```

Try it online!

`outer` is such a handy function.

Fairly certain this will always work. Will make a formal argument when I have the time.
> 4 votes

# Answer
# APL (Dyalog Extended), 15 bytes

```
{⍵⌷∧∊∘.*⍨¯2⍭⍳⍵}

```

Try it online!

**Explanation**

```
{⍵⌷∧∊∘.*⍨¯2⍭⍳⍵}

              ⍵   Right argument. Our input.
{              }  Wraps the function in dfn syntax which allows us to use ⍵.
             ⍳     Range [1..⍵].
          ¯2⍭     Get the n-th prime for each n in the range.
      ∘.*⍨        Get the prime powers of each prime.
     ∊            Flatten the list.
    ∧             In Extended, this is monadic sort ascending.
 ⍵⌷               Get the input-th index of the list of prime powers of primes.

```
> 3 votes

# Answer
# Pyth, 15 bytes

```
e.f/^FR^fP_TSZ2

```

**Try it here!** or **Verify more test cases.**

## Explanation

```
e.f/^FR^fP_TSZ2  - Full program. Q means input.

 .f              - First Q inputs with truthy results. Uses the variable Z.
        fP_TSZ   - Filter the range [1, Z] for primes.
       ^      2  - Cartesian square. Basically the Cartesian product with itself.
    ^FR          - Reduce each list by exponentiation.
  /              - Count the occurrences of Z in ^.
e                - Last element.

```
> 2 votes

# Answer
# Javascript 137 133 bytes

```
P=n=>{for(p=[i=2];j=++i<n*9;j^i&&p.push(i))
for(;j*j<=i;)j=i%++j?j:i
x=[]
for(i of p)
for(j of p)
x[i**j]=1
return Object.keys(x)[n]}

console.log(P(1000))
console.log(P(800))
console.log(P(9))
console.log(P(5))
```

\**normal algorithem(100ms result) P =n =\> {

```
  for(p=[i=2];f=++i<=n*10;!f||p.push(i))
    for(j=0;f&&(x=p[j++])*x<=i;)
      f=i%x
  x=[]
  T=0
  for(i of p)
  for(j of p)
  {
    l= i**j
    if(++T>n &&x.length<l )
    break
    x[l] = 1
  }
  return Object.keys(x)[n]
}

```
> 2 votes

# Answer
# Perl 6, 50 bytes

```
{(sort [X**] (^7028,^24)>>.grep(&is-prime))[$_-1]}

```

Try it online!

```
  (^7028,^24)            # create 2 ranges from 0
     >>.grep(&is-prime)  # grep for primes in both
 [X**] ...               # calc each exponential pair (2^2, 2^3, 2^5...)
(sort ... )[$_-1]        # sort and get value at index n-1

```

The reasons for the 24 and 7028 are that the largest value (n=1000) is 49378729, which is 7027^2, and the largest prime power of 2 which fits under that is 23. So covering 2..7027 ^ 2..23 includes all the items in the first 1000 (and a lot of spares).
> 2 votes

# Answer
# Pyth - 13 bytes

```
e.f&P_lPZ!t{P

```

Test Suite.
> 1 votes

# Answer
# Java 8, 211 bytes

```
import java.util.*;n->{List l=new Stack();for(int a=2,b;a<132;a++)for(b=2;b<132;b++)if(p(a)*p(b)>0)l.add(Math.pow(a,b));Collections.sort(l);return l.get(n);}int p(int n){for(int i=2;i<n;n=n%i++<1?0:n);return n;}

```

Very inefficient method.. It basically calculates all PPP's from 22 through ~~999999~~ 132132 and stores it in a List, then sorts that List, and then gets the `n`'th item from that List.

EDIT: Instead of using 999999 which results in a List of 28,225 items, I now use 132132 which results in a List of just 1,024 items. This improves the performance quite a bit, and is perfectly acceptable since the challenge states we should support an input from index 0 through 1,000. (Changing `1e3` to `132` doesn't affect the byte-count, though.)

**Explanation:**

Try it here.

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

n->{                          // Method with integer as parameter and Object as return-type
  List l=new Stack();         //  List to store the PPPs in
  for(int a=2,b;a<132;a++)    //  Loop (1) from 2 to 1,000 (exclusive)
    for(b=2;b<132;b++)        //   Inner loop (2) from 2 to 1,000 (exclusive)
      if(p(a)*p(b)>0)         //    If both `a` and `b` are primes:
        l.add(Math.pow(a,b)); //     Add the power of those two to the List
                              //   End of loop (2) (implicit / single-line body)
                              //  End of loop (1) (implicit / single-line body)
  Collections.sort(l);        //  Sort the filled List
  return l.get(n);            //  Return the `n`'th item of the sorted List of PPPs
}                             // End of method

int p(int n){                 // Separated method with integer as parameter and return-type
  for(int i=2;                //  Index integer (starting at 2)
      i<n;                    //  Loop from 2 to `n` (exclusive)
    n=n%i++<1?                //   If `n` is divisible by `i`:
       0                      //    Change `n` to 0
      :                       //   Else:
       n                      //    Leave `n` the same
  );                          //  End of loop
  return n;                   //  Return `n` (which is now 0 if it wasn't a prime)
}                             // End of separated method

```
> 1 votes

# Answer
# PARI/GP, 48 bytes

```
f(n)=[x|x<-[1..4^n],isprime(isprimepower(x))][n]

```

If you do not count the `f(n)=` part, that is 43 bytes.

---

Another approach without the set notation which does not check so many unnecessary cases:

```
f(n)=c=0;i=1;while(c<n,i++;isprime(isprimepower(i))&&c++);i

```
> 1 votes

# Answer
# J, 21 bytes

```
{[:/:~@,[:^/~p:@i.@>:

```

Zero-indexed anonymous function.

Try it online!

Trying to get back into the swing of things but I seem to have forgotten all tricks to make good monadic chains.

### Short explanation

Constructs a table of prime powers from the 0th prime to the prime at the index of the input plus 1 (to account for 0). Flattens this list and sorts it and then indexes into it. I realize now that this might give incorrect results for some values since the table might not be large enough -- in that case I'd edit in a hardcoded value like 1e4 which should suffice. I can't prove it one way or the other (it passes for the test cases given), so do let me know if this is an issue.

### Also 21 bytes

```
3 :'y{/:~,^/~p:i.>:y'

```
> 0 votes

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


title: Source permutation

text:
# Question
Title: Source permutation
A permutation of a set \\$S = \\{s\_1, s\_2, \dotsc, s\_n\\}\\$ is a bijective function \\$\pi: S \to S\\$. For example, if \\$S = \\{1,2,3,4\\}\\$ then the function \\$\pi: x \mapsto 1 + (x + 1 \mod 4)\\$ is a permutation:

$$ \pi(1) = 3,\quad \pi(2) = 4,\quad \pi(3) = 1,\quad \pi(4) = 2 $$

We can also have permutations on infinite sets, let's take \\$\mathbb{N}\\$ as an example: The function \\$\pi: x \mapsto x-1 + 2\cdot(x \mod 2)\\$ is a permutation, swapping the odd and even integers in blocks of two. The first elements are as follows:

$$ 2,1,4,3,6,5,8,7,10,9,12,11,14,13,16,15,\dotsc $$

## Challenge

Your task for this challenge is to write a function/program implementing any1 permutation on the positive natural numbers. The score of your solution is the sum of codepoints after mapping them with the implemented permutation.

## Example

Suppose we take the above permutation implemented with Python:

```
def pi(x):
    return x - 1 + 2*(x % 2)

```

Try it online!

The character `d` has codepoint \\$100\\$, \\$\texttt{pi}(100) = 99\\$. If we do this for every character, we get:

$$ 99,102,101,31,111,106,39,119,42,57,9,31,31,31,31,113,102,115,118,113,109,31,119,31,46,31,50,31,44,31,49,41,39,119,31,38,31,49,42 $$

The sum of all these mapped characters is \\$2463\\$, this would be the score for that function.

## Rules

You will implement a permutation \\$\pi\\$ either as a function or program

* given an natural number \\$x\\$, return/output \\$\pi(x)\\$
* for the purpose of this challenge \\$\mathbb{N}\\$ does **not** contain \\$0\\$
* the permutation must non-trivially permute an infinite subset of \\$\mathbb{N}\\$
* your function/program is not allowed to read its own source

## Scoring

The score is given by the sum of all codepoints (zero bytes may not be part of the source code) under that permutation (the codepoints depend on your language2, you're free to use SBCS, UTF-8 etc. as long as your language supports it).

The submission with the lowest score wins, ties are broken by earliest submission.

---

1. Except for permutations which only permute a finite subset of \\$\mathbb{N}\\$, meaning that the set \\$\\{ x | \pi(x) \neq x \\}\\$ must be infinite.
2. If it improves your score, you can for example use a UTF-8 encoded Jelly submission instead of the usual SBCS.

# Answer
> 6 votes
# Jelly, score  ~~288 250 212~~  199

-38 thanks to Erik the Outgolfer!

```
C-*+

```

Swaps even with odd.

The score is \\$67+45+44+43=199\\$ \- see self-scoring here.

**Try it online!**

# Answer
> 5 votes
# JavaScript (ES6), Score =  ~~276~~  268

```
$=>(--$^40)+!0

```

Try it online!

# Answer
> 4 votes
# Perl 6, Score: 201

```
*-!0+^40+!0

```

Try it online!

Port of Arnauld's answer. This benefits from xor (`+^`) having the same precedence as `-` and `+`, and the use of a Whatever lambda to reduce overall characters. Other than that, I couldn't find a way of representing it differently that got a better score.

# Perl 6, Score ~~804~~ 702

```
{{(++$∉ords(q[!$%()+-2?[]_doqrsx{}∉])??++$+22-$++%2-$++%2!!++$)xx$_}()[-!$+$_]}

```

Try it online!

The first quine-y type answer here, and I think it scores pretty well.

This produces the sequence \\$23,22,25,24...\\$ from the question body with the range \\$1,2,3,4...21\\$ inserted at the indexes of the unique sorted codepoints of the code. For example, the 30th through 35th elements of the sequence are \\$50, 53, 52, 1, 55, 54\\$ since the 33rd codepoint is `!` and that's the lowest codepoint in my code.

# Answer
> 4 votes
# Python 2 score: ~~742~~ ~~698~~ 694 points

```
lambda a:a^96or~~96

```

Try it online!

-44 points thanks to Ørjan Johansen; -4 points thx to xnor.

# Answer
> 2 votes
# Retina 0.8.2, 6 bytes, score 260

```
T`O`RO

```

Try it online! Link includes self-scoring footer. Simply swaps digits `1` and `9` and `3` and `7` in the decimal representations, so that numbers that contain no digits coprime to `10` are unaffected.

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), 22 bytes, Score ~~247~~ 245

```
A=>A>65?A-1+A%2*2:66-A

```

Try it online!

Simple, if less than 66, return 66 minus input, else use the formula in the question that swaps even and odd numbers.

# Answer
> 2 votes
# TI-BASIC, 9 bytes, score ~~1088~~ ~~1051~~ 1000

```
Ans-cos(π2fPart(2⁻¹Ans

```

Swaps even with odd. Even maps to `Ans-1` and odd maps to `Ans+1`.

TI-BASIC is tokenized, so this program will have the following hex-values:

```
Ans   -    cos(  π    2    fPart(  2   ⁻¹  Ans
72    71   C4    AC   32   BA      32  0C  72

```

Thus the score is: \\$113+114+195+171+49+185+49+11+113=1000\\$

**Output test program:**

```
For(I,1,10
I
Ans-cos(π2fPart(2⁻¹Ans
Disp Ans
Pause
End

```

Which outputs:

```
2
1
4
3
6
5
8
7
10
9

```

---

**Notes:**

* TI-BASIC's token values can be found here.
* `Pause` is used in the output program to better see the permutation, as the calculator only has 8 lines. Press **\[ENTER\]** to view the next permutation.

# Answer
> 1 votes
# Charcoal, 13 bytes, score 681

```
⁻⁺²³²ι⊗﹪⊖ι²³³

```

Try it online! Link is to self-scoring version with header to map over an array of byte codes. (Charcoal has a custom code page so I've manually inserted the correct byte codes in the input.) Works by reversing ranges of 233 numbers, so that 117, 350, 583 ... are unchanged. Explanation:

```
     ι          Value
 ⁺              Plus
  ²³²           Literal 232
⁻               Minus
         ι      Value
        ⊖       Decremented
       ﹪        Modulo
          ²³³   Literal 233
      ⊗         Doubled

```

# Answer
> 1 votes
# Haskell, score 985

```
(\((.),(-))->(.)*200+mod(-39+(-))200+1).(\(*)->divMod((*)-1)200)

```

Try it online!

# Answer
> 1 votes
# 05AB1E, score: 488 in 05AB1E's code page

```
È·<-

```

Swaps odd and even like the example function.

Will try to improve the score from here.

Try it online with input in the range `[1, 100]` or Try it online with the codepoints.

**Explanation:**

```
È     # Check if the (implicit) input is even (1 if truthy; 0 if falsey)
 ·    # Double (2 if truthy; 0 if falsey)
  <   # Decrease by 1 (1 if truthy; -1 if falsey)
   -  # Subtract it from the (implicit) input (and output implicitly)

```

# Answer
> 0 votes
# Brainfuck, 47 bytes, score 2988

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

```

Try it online!

I used the permutation given in the introduction. Since this is bijection you can use it as a simple symmetric cipher similar to ROT13 or Atbash. My solution works on unbounded cells. However, by restricting yourself to 8-bit cells, you could save 2 points by replacing `[-]` with `[+]`.

---
Tags: code-challenge, sequence, integer, permutations, self-referential
---


title: To string or not to string

text:
# Question
Title: To string or not to string
Given an input string, output at random the unique combinations with repetition of the characters in the input string, from length 1 up to the length of the input string, with an equal chance of each one occurring.

Example: given the input `abcd` (or any combination thereof of the four characters `a`,`b`,`c`,`d`) , there is an equal chance of outputting:

```
a b c d aa ab ac ad ba bb bc bd ca cb cc cd da db dc dd aaa aab aac aad aba abb abc abd aca acb acc acd ada adb adc add baa bab bac bad bba bbb bbc bbd bca bcb bcc bcd bda bdb bdc bdd caa cab cac cad cba cbb cbc cbd cca ccb ccc ccd cda cdb cdc cdd daa dab dac dad dba dbb dbc dbd dca dcb dcc dcd dda ddb ddc ddd aaaa aaab aaac aaad aaba aabb aabc aabd aaca aacb aacc aacd aada aadb aadc aadd abaa abab abac abad abba abbb abbc abbd abca abcb abcc abcd abda abdb abdc abdd acaa acab acac acad acba acbb acbc acbd acca accb accc accd acda acdb acdc acdd adaa adab adac adad adba adbb adbc adbd adca adcb adcc adcd adda addb addc addd baaa baab baac baad baba babb babc babd baca bacb bacc bacd bada badb badc badd bbaa bbab bbac bbad bbba bbbb bbbc bbbd bbca bbcb bbcc bbcd bbda bbdb bbdc bbdd bcaa bcab bcac bcad bcba bcbb bcbc bcbd bcca bccb bccc bccd bcda bcdb bcdc bcdd bdaa bdab bdac bdad bdba bdbb bdbc bdbd bdca bdcb bdcc bdcd bdda bddb bddc bddd caaa caab caac caad caba cabb cabc cabd caca cacb cacc cacd cada cadb cadc cadd cbaa cbab cbac cbad cbba cbbb cbbc cbbd cbca cbcb cbcc cbcd cbda cbdb cbdc cbdd ccaa ccab ccac ccad ccba ccbb ccbc ccbd ccca cccb cccc cccd ccda ccdb ccdc ccdd cdaa cdab cdac cdad cdba cdbb cdbc cdbd cdca cdcb cdcc cdcd cdda cddb cddc cddd daaa daab daac daad daba dabb dabc dabd daca dacb dacc dacd dada dadb dadc dadd dbaa dbab dbac dbad dbba dbbb dbbc dbbd dbca dbcb dbcc dbcd dbda dbdb dbdc dbdd dcaa dcab dcac dcad dcba dcbb dcbc dcbd dcca dccb dccc dccd dcda dcdb dcdc dcdd ddaa ddab ddac ddad ddba ddbb ddbc ddbd ddca ddcb ddcc ddcd ddda dddb dddc dddd

```

Example: given the input `efgh` (or any combination thereof of the four characters `e`,`f`,`g`,`h`), there is an equal chance of outputting:

```
e f g h ee ef eg eh fe ff fg fh ge gf gg gh he hf hg hh eee eef eeg eeh efe eff efg efh ege egf egg egh ehe ehf ehg ehh fee fef feg feh ffe fff ffg ffh fge fgf fgg fgh fhe fhf fhg fhh gee gef geg geh gfe gff gfg gfh gge ggf ggg ggh ghe ghf ghg ghh hee hef heg heh hfe hff hfg hfh hge hgf hgg hgh hhe hhf hhg hhh eeee eeef eeeg eeeh eefe eeff eefg eefh eege eegf eegg eegh eehe eehf eehg eehh efee efef efeg efeh effe efff effg effh efge efgf efgg efgh efhe efhf efhg efhh egee egef egeg egeh egfe egff egfg egfh egge eggf eggg eggh eghe eghf eghg eghh ehee ehef eheg eheh ehfe ehff ehfg ehfh ehge ehgf ehgg ehgh ehhe ehhf ehhg ehhh feee feef feeg feeh fefe feff fefg fefh fege fegf fegg fegh fehe fehf fehg fehh ffee ffef ffeg ffeh fffe ffff fffg fffh ffge ffgf ffgg ffgh ffhe ffhf ffhg ffhh fgee fgef fgeg fgeh fgfe fgff fgfg fgfh fgge fggf fggg fggh fghe fghf fghg fghh fhee fhef fheg fheh fhfe fhff fhfg fhfh fhge fhgf fhgg fhgh fhhe fhhf fhhg fhhh geee geef geeg geeh gefe geff gefg gefh gege gegf gegg gegh gehe gehf gehg gehh gfee gfef gfeg gfeh gffe gfff gffg gffh gfge gfgf gfgg gfgh gfhe gfhf gfhg gfhh ggee ggef ggeg ggeh ggfe ggff ggfg ggfh ggge gggf gggg gggh gghe gghf gghg gghh ghee ghef gheg gheh ghfe ghff ghfg ghfh ghge ghgf ghgg ghgh ghhe ghhf ghhg ghhh heee heef heeg heeh hefe heff hefg hefh hege hegf hegg hegh hehe hehf hehg hehh hfee hfef hfeg hfeh hffe hfff hffg hffh hfge hfgf hfgg hfgh hfhe hfhf hfhg hfhh hgee hgef hgeg hgeh hgfe hgff hgfg hgfh hgge hggf hggg hggh hghe hghf hghg hghh hhee hhef hheg hheh hhfe hhff hhfg hhfh hhge hhgf hhgg hhgh hhhe hhhf hhhg hhhh

```

Example: given the input `ijkl` (or any combination thereof of the four characters `i`,`j`,`k`,`l`), there is an equal chance of outputting:

```
i j k l ii ij ik il ji jj jk jl ki kj kk kl li lj lk ll iii iij iik iil iji ijj ijk ijl iki ikj ikk ikl ili ilj ilk ill jii jij jik jil jji jjj jjk jjl jki jkj jkk jkl jli jlj jlk jll kii kij kik kil kji kjj kjk kjl kki kkj kkk kkl kli klj klk kll lii lij lik lil lji ljj ljk ljl lki lkj lkk lkl lli llj llk lll iiii iiij iiik iiil iiji iijj iijk iijl iiki iikj iikk iikl iili iilj iilk iill ijii ijij ijik ijil ijji ijjj ijjk ijjl ijki ijkj ijkk ijkl ijli ijlj ijlk ijll ikii ikij ikik ikil ikji ikjj ikjk ikjl ikki ikkj ikkk ikkl ikli iklj iklk ikll ilii ilij ilik ilil ilji iljj iljk iljl ilki ilkj ilkk ilkl illi illj illk illl jiii jiij jiik jiil jiji jijj jijk jijl jiki jikj jikk jikl jili jilj jilk jill jjii jjij jjik jjil jjji jjjj jjjk jjjl jjki jjkj jjkk jjkl jjli jjlj jjlk jjll jkii jkij jkik jkil jkji jkjj jkjk jkjl jkki jkkj jkkk jkkl jkli jklj jklk jkll jlii jlij jlik jlil jlji jljj jljk jljl jlki jlkj jlkk jlkl jlli jllj jllk jlll kiii kiij kiik kiil kiji kijj kijk kijl kiki kikj kikk kikl kili kilj kilk kill kjii kjij kjik kjil kjji kjjj kjjk kjjl kjki kjkj kjkk kjkl kjli kjlj kjlk kjll kkii kkij kkik kkil kkji kkjj kkjk kkjl kkki kkkj kkkk kkkl kkli kklj kklk kkll klii klij klik klil klji kljj kljk kljl klki klkj klkk klkl klli kllj kllk klll liii liij liik liil liji lijj lijk lijl liki likj likk likl lili lilj lilk lill ljii ljij ljik ljil ljji ljjj ljjk ljjl ljki ljkj ljkk ljkl ljli ljlj ljlk ljll lkii lkij lkik lkil lkji lkjj lkjk lkjl lkki lkkj lkkk lkkl lkli lklj lklk lkll llii llij llik llil llji lljj lljk lljl llki llkj llkk llkl llli lllj lllk llll

```

This by definition also means that every indiviual character within the string too has equal probability. All characters in the input are distinct.

# Answer
> 6 votes
# Jelly,  ~~10~~  5 bytes

```
ṗJẎQX

```

A monadic Link accepting a list of characters which yields a list of characters.

**Try it online!**

### How?

```
ṗJẎQX - Link list of characters    e.g.  aabc
 J    - range of length                  [1,2,3,4]
ṗ     - Cartesian power (vectorises)     [[a,a,b,c],[aa,aa,ab,ac,aa,aa,ab,ac,ba,ba,bb,bc,ca,ca,cb,cc],[aaa,aaa,aab,aac,aaa,aaa,aab,aac,aba,aba,abb,abc,aca,aca,acb,acc,aaa,aaa,aab,aac,aaa,aaa,aab,aac,aba,aba,abb,abc,aca,aca,acb,acc,baa,baa,bab,bac,baa,baa,bab,bac,bba,bba,bbb,bbc,bca,bca,bcb,bcc,caa,caa,cab,cac,caa,caa,cab,cac,cba,cba,cbb,cbc,cca,cca,ccb,ccc],[aaaa,aaaa,aaab,aaac,aaaa,aaaa,aaab,aaac,aaba,aaba,aabb,aabc,aaca,aaca,aacb,aacc,aaaa,aaaa,aaab,aaac,aaaa,aaaa,aaab,aaac,aaba,aaba,aabb,aabc,aaca,aaca,aacb,aacc,abaa,abaa,abab,abac,abaa,abaa,abab,abac,abba,abba,abbb,abbc,abca,abca,abcb,abcc,acaa,acaa,acab,acac,acaa,acaa,acab,acac,acba,acba,acbb,acbc,acca,acca,accb,accc,aaaa,aaaa,aaab,aaac,aaaa,aaaa,aaab,aaac,aaba,aaba,aabb,aabc,aaca,aaca,aacb,aacc,aaaa,aaaa,aaab,aaac,aaaa,aaaa,aaab,aaac,aaba,aaba,aabb,aabc,aaca,aaca,aacb,aacc,abaa,abaa,abab,abac,abaa,abaa,abab,abac,abba,abba,abbb,abbc,abca,abca,abcb,abcc,acaa,acaa,acab,acac,acaa,acaa,acab,acac,acba,acba,acbb,acbc,acca,acca,accb,accc,baaa,baaa,baab,baac,baaa,baaa,baab,baac,baba,baba,babb,babc,baca,baca,bacb,bacc,baaa,baaa,baab,baac,baaa,baaa,baab,baac,baba,baba,babb,babc,baca,baca,bacb,bacc,bbaa,bbaa,bbab,bbac,bbaa,bbaa,bbab,bbac,bbba,bbba,bbbb,bbbc,bbca,bbca,bbcb,bbcc,bcaa,bcaa,bcab,bcac,bcaa,bcaa,bcab,bcac,bcba,bcba,bcbb,bcbc,bcca,bcca,bccb,bccc,caaa,caaa,caab,caac,caaa,caaa,caab,caac,caba,caba,cabb,cabc,caca,caca,cacb,cacc,caaa,caaa,caab,caac,caaa,caaa,caab,caac,caba,caba,cabb,cabc,caca,caca,cacb,cacc,cbaa,cbaa,cbab,cbac,cbaa,cbaa,cbab,cbac,cbba,cbba,cbbb,cbbc,cbca,cbca,cbcb,cbcc,ccaa,ccaa,ccab,ccac,ccaa,ccaa,ccab,ccac,ccba,ccba,ccbb,ccbc,ccca,ccca,cccb,cccc]
  Ẏ   - tighten                          [a,a,b,c,aa,aa,ab,ac,aa,aa,ab,ac,ba,ba,bb,bc,ca,ca,cb,cc,aaa,aaa,aab,aac,aaa,aaa,aab,aac,aba,aba,abb,abc,aca,aca,acb,acc,aaa,aaa,aab,aac,aaa,aaa,aab,aac,aba,aba,abb,abc,aca,aca,acb,acc,baa,baa,bab,bac,baa,baa,bab,bac,bba,bba,bbb,bbc,bca,bca,bcb,bcc,caa,caa,cab,cac,caa,caa,cab,cac,cba,cba,cbb,cbc,cca,cca,ccb,ccc,aaaa,aaaa,aaab,aaac,aaaa,aaaa,aaab,aaac,aaba,aaba,aabb,aabc,aaca,aaca,aacb,aacc,aaaa,aaaa,aaab,aaac,aaaa,aaaa,aaab,aaac,aaba,aaba,aabb,aabc,aaca,aaca,aacb,aacc,abaa,abaa,abab,abac,abaa,abaa,abab,abac,abba,abba,abbb,abbc,abca,abca,abcb,abcc,acaa,acaa,acab,acac,acaa,acaa,acab,acac,acba,acba,acbb,acbc,acca,acca,accb,accc,aaaa,aaaa,aaab,aaac,aaaa,aaaa,aaab,aaac,aaba,aaba,aabb,aabc,aaca,aaca,aacb,aacc,aaaa,aaaa,aaab,aaac,aaaa,aaaa,aaab,aaac,aaba,aaba,aabb,aabc,aaca,aaca,aacb,aacc,abaa,abaa,abab,abac,abaa,abaa,abab,abac,abba,abba,abbb,abbc,abca,abca,abcb,abcc,acaa,acaa,acab,acac,acaa,acaa,acab,acac,acba,acba,acbb,acbc,acca,acca,accb,accc,baaa,baaa,baab,baac,baaa,baaa,baab,baac,baba,baba,babb,babc,baca,baca,bacb,bacc,baaa,baaa,baab,baac,baaa,baaa,baab,baac,baba,baba,babb,babc,baca,baca,bacb,bacc,bbaa,bbaa,bbab,bbac,bbaa,bbaa,bbab,bbac,bbba,bbba,bbbb,bbbc,bbca,bbca,bbcb,bbcc,bcaa,bcaa,bcab,bcac,bcaa,bcaa,bcab,bcac,bcba,bcba,bcbb,bcbc,bcca,bcca,bccb,bccc,caaa,caaa,caab,caac,caaa,caaa,caab,caac,caba,caba,cabb,cabc,caca,caca,cacb,cacc,caaa,caaa,caab,caac,caaa,caaa,caab,caac,caba,caba,cabb,cabc,caca,caca,cacb,cacc,cbaa,cbaa,cbab,cbac,cbaa,cbaa,cbab,cbac,cbba,cbba,cbbb,cbbc,cbca,cbca,cbcb,cbcc,ccaa,ccaa,ccab,ccac,ccaa,ccaa,ccab,ccac,ccba,ccba,ccbb,ccbc,ccca,ccca,cccb,cccc]
   Q  - de-duplicate                     [a,b,c,aa,ab,ac,ba,bb,bc,ca,cb,cc,aaa,aab,aac,aba,abb,abc,aca,acb,acc,baa,bab,bac,bba,bbb,bbc,bca,bcb,bcc,caa,cab,cac,cba,cbb,cbc,cca,ccb,ccc,aaaa,aaab,aaac,aaba,aabb,aabc,aaca,aacb,aacc,abaa,abab,abac,abba,abbb,abbc,abca,abcb,abcc,acaa,acab,acac,acba,acbb,acbc,acca,accb,accc,baaa,baab,baac,baba,babb,babc,baca,bacb,bacc,bbaa,bbab,bbac,bbba,bbbb,bbbc,bbca,bbcb,bbcc,bcaa,bcab,bcac,bcba,bcbb,bcbc,bcca,bccb,bccc,caaa,caab,caac,caba,cabb,cabc,caca,cacb,cacc,cbaa,cbab,cbac,cbba,cbbb,cbbc,cbca,cbcb,cbcc,ccaa,ccab,ccac,ccba,ccbb,ccbc,ccca,cccb,cccc]
    X - uniform random choice

```

# Answer
> 6 votes
# 05AB1E, 6 bytes

```
ā€ã˜ÙΩ

```

Try it online!

**Explanation**

```
ā       # push [1 ... len(input)]
 €ã     # apply repeated cartesian product on each and input
   ˜    # flatten
    Ù   # remove duplicates
     Ω  # pick random string

```

# Answer
> 4 votes
# Perl 6, ~~35 33~~ 28 bytes

*-2 bytes thanks to nwellnhof*

```
{[~] roll .rand+1,$_}o*.comb

```

Try it online!

This challenge keeps changing a lot.

### Explanation:

```
{                   }o*.comb  # Anonymous code block turning input into chars
                  $_          # From the input
          .rand+1,              # Take a random number from 1 to length of list
     roll                       # Of characters
 [~]                          # And join them into a string

```

# Answer
> 3 votes
# Brachylog, 8 bytes

```
⊇ᶠbṛ;?ṛw

```

Try it online!

Prints output directly instead of constraining the output variable, because for some reason this actually fails without the `w` at the end. Originally this used  and the `∈&` backtracking hack I used to implement bogosort, but I realized that it would be far saner to just use `b` instead.

```
       w    Print
      ṛ     a random one of
     ?      the input
    ;       or
   ṛ        a random element of
 ᶠ          every
⊇           sublist of
            the input
  b         except the first one (which would be the input).

```

# Answer
> 2 votes
# Python 2, ~~111~~ 121 bytes

```
lambda s:choice(g(list(set(s)),len(s)))
from random import *
g=lambda s,n:s+(n>1and[c+k for k in g(s,n-1)for c in s]or[])

```

Try it online!

Takes any iterable (list, set, string, etc.) of either distinct characters or non-distinct characters as input. Outputs a non-empty string with the required distribution.

`g` is a recursive function to generate a list of compliant strings.

# Answer
> 2 votes
# , ~~72~~ 64 bytes

-8 bytes thanks to Giuseppe.

```
S=sample;S(t<-unique(s<-scan(,"")),S(n<-seq(s),p=length(t)^n),T)

```

Try it online!

Input and output are vectors of characters. All possible outputs have equal probability.

Explanation (ungolfed version):

```
s<-scan(,"")                         # takes input as vector of characters
n<-length(s)
t<-unique(s)
sample(t,                           # sample uniformly at random from the list of unique characters
       sample(n,p=length(t)^(1:n)), # with length k in 1..n chosen randomly such that P[k] is proportional to length(t)^k
       T)                           # the sampling is with replacement

```

# Answer
> 1 votes
# Wolfram Language (Mathematica), 41 bytes

```
""<>#&@*RandomChoice@*Subsets@*Characters

```

Try it online!

# Answer
> 1 votes
## Java 131 bytes

```
void k(String a){a.chars().forEach(v->{int z=(int)(Math.random()*(a.length()+1));if(z<a.length())System.out.print(a.charAt(z));});}

```

# Answer
> 1 votes
# Pyth - 7 bytes

```
Os^LQSl

O                         Random choice
 s                        Collapse list
  ^L                      Map cartesian power
   Q                      Input
   S                      1-indexed range
    l                     Length
     (Q implicit)         Input

```

Try it online.

Try it online without random pick to see all possible options.

# Answer
> 1 votes
# Haskell, ~~143~~ 126 bytes

-7 bytes thanks to @Laiconi, additional improvement (which I need to fully understand first) in the comments

```
import Control.Monad
import System.Random
f a|c<-concat[replicateM x a|x<-[1..length a]]=randomRIO(0,length c-1)>>=print.(c!!)

```

Try it online!

---

Original

# Answer
> 0 votes
# C (gcc), ~~68~~ 65 bytes

```
f(s,i)char*s;{for(;i<strlen(s);i++)rand()&1?putc(s[i],stdout):0;}

```

Try it online!

# Answer
> 0 votes
# T-SQL, 222 bytes

This creates all combinations of each unique character with recursive sql, then picks a random row from the distinct combinations.

```
DECLARE @ varchar(max)='T-SQL';

WITH C as(SELECT DISTINCT substring(@,number+1,1)x
FROM spt_values
WHERE'P'=type and len(@)>number),D
as(SELECT x y
FROM c UNION ALL
SELECT y+x
FROM C JOIN D
ON len(y)<len(@))SELECT top 1*FROM D
GROUP BY y
ORDER BY newid()

```

Note the online version will always give the same result unlike MS-SQL Studio Management. This is because newid() always returns the same value in the online testing. This should work in Studio Management.

**Try it online** ungolfed version

# Answer
> 0 votes
# Charcoal, 34 bytes

```
≔Φθ⁼κ⌕θιη≔⊕‽ΣＥθＸＬη⊕κζＷζ«§ηζ≔÷⊖ζＬηζ

```

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

```
≔Φθ⁼κ⌕θιη

```

Extract the unique characters of the input. Let's call the number of unique characters `n`.

```
≔⊕‽ΣＥθＸＬη⊕κζ

```

Calculate the number of combinations for each possible length and take the sum. Then, pick a random number between 1 and this number (inclusive). This ensures that all combinations are equally likely (within the accuracy of the random number generator).

```
Ｗζ«§ηζ≔÷⊖ζＬηζ

```

Convert the number into bijective base `n`, using the unique characters as the digits.

# Answer
> 0 votes
# MATLAB / Octave, 110 bytes

Choose a random permutation of a subset of the input letters (with repetitions), whose random length is based on the probability of generating a word with that length.

```
@(a)a(randi(numel(a),[find(cumsum(numel(a).^[1:numel(a)])>=randi(sum(numel(a).^[1:numel(a)])),1,'first'),1]));

```

Try it online!

# Answer
> 0 votes
# , 27 bytes

```
[:(?@#{])@;[:,@{&.>#\<@#"{<

```

Try it online!

## standard formatting

```
[: (?@# { ])@; [: ,@{&.> #\ <@#"1 _ <

```

## explanation

Eg, for the string 'abc' we first use `#\<@#"{<` to create:

```
┌─────┬─────────┬─────────────┐
│┌───┐│┌───┬───┐│┌───┬───┬───┐│
││abc│││abc│abc│││abc│abc│abc││
│└───┘│└───┴───┘│└───┴───┴───┘│
└─────┴─────────┴─────────────┘

```

We then take the cartesian product of each of these `{`, flatten the results, and finally remove the outer boxing `;`.

`(?@#{])@` takes a random result from that list.

# Answer
> 0 votes
# Python 2, 124 bytes

```
lambda s:g(list(set(s)),len(s))
from random import*
g=lambda s,n:choice(s)+(random()*~-len(s)**(n)>~-len(s)and g(s,n-1)or'')

```

Try it online!

A different approach: instead of first constructing a list of all compliant strings and choosing one at random, this approach randomly decides to continue extending the string or stopping.

This again has to deal with the exacting input requirements, at a cost of 31 bytes; but the function of interest `g` takes a list `s` of characters to be used, and an integer `n` which is the maximum length of the returned string.

As an example, consider the set of characters \['a','b'\] and suppose we want to generate random strings of length 1, 2, or 3.

Then if we randomly choose 'a' as the starting character, the possible strings which could be returned are:

```
a
 aa
  aaa
  aab
 ab
  aba
  abb

```

shown above in 'tree' form, which is a total of `1 + 2 + 2*2 = 2^0 + 2^1 + 2^2 = 7` strings. So if we generate a string `a`; then `1/7` of the time we should stop and return `'a'`, and `6/7` of the time we should add further to the string - then the distribution will be uniform in the way desired.

More generally, if `n` is maximum length of the string and `x` is the number of characters in the set, then the number of strings starting with some given character is going to be:

$$h(n)=\sum\_{i=0}^{n-1} x^i$$ $$h(n)=1+x+x^2+x^3...+x^{n-1}$$

For `x>1` (guaranteed by OP's rule 'at least two distinct...'), we have:

$$h(n)(x-1)=(1+x+x^2+x^3...+x^{n-1})(x-1)=x^n-1$$ $$h(n)=\frac{x^n-1}{x-1}$$

So to decide whether we should continue extending our string, let `p` be a random number in `[0,1)`; then we should recurse only if any of these equivalent statements are true:

$$p\>\frac{1}{h(n)}$$ $$p\>\frac{x-1}{x^n-1}$$ $$p(x^n-1)\>x-1$$

of which `g` is the golfed implementation.

# Answer
> 0 votes
# C# (Visual C# Interactive Compiler), 126 bytes

```
a=>{var s=new Random();int d=a.Length;return Enumerable.Range(1,s.Next(1,d)).Select(x=>a.Distinct().ToList()[s.Next(0,d-1)]);}

```

Try it online!

# Answer
> 0 votes
# Forth (gforth), 68 bytes

```
include random.fs
: f dup random 1+ 0 do 2dup random + 1 type loop ;

```

Try it online!

### Explanation

* Get a random number between 1 and string-length
* Loop that many times
* For each iteration
    + Get a random number between 0 and string length - 1
    + Add that to string starting address and output the character at that address

### Code Explanation

```
include random.fs          \ include the library file needed to generate random numbers
: f                        \ start a new word definition
  dup                      \ duplicate the string-length
  random 1+                \ get the length of the new string, make sure it starts from 1
  0 do                     \ start a loop of that length
    2dup                   \ duplicate the starting address and string length
    random +               \ get a number from 0 to string-length and add it to the address
    1 type                 \ output the character at that address
  loop                     \ end the loop
;                          \ end the word definition

```

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


title: Match Roman Numerals

text:
# Question
Title: Match Roman Numerals
### Challenge

Given some input string, return a truthy value if it represents a correct roman numeral between 1 (=`I`) and 3999 (=`MMMCMXCIX`), and a falsey value otherwise.

### Details

* The input is a non-empty string that only comprises the characters `IVXLCDM`.
* The roman numerals (that we use here in this challenge) are defined as follows:

We use only following symbols:

```
Symbol  I   V   X   L   C   D    M
Value   1   5  10  50 100 500 1000

```

To define which strings are actually valid roman numerals, it is probably easiest to provide the rule of conversation: To write a decimal number `a3 a2 a1 a0` (where each `ai` represents one digit. So for example to represent `792` we have `a3=0, a2=7, a1=9, a0=2`.) as a roman numeral, we decompose it into the power of tens. The different powers of ten can be written as follows:

```
      1-9: I, II, III, IV, V, VI, VII, VIII, IX
    10-90: X, XX, XXX, XL, L, LX, LXX, LXXX, XC
  100-900: C, CC, CCC, CD, D, DC, DCC, DCCC, CM
1000-3000: M, MM, MMM

```

Beginning at the left side with the most significant digit of the, we can convert the number that each digit represents separately and concatenate them. So for the example from above this would look like so:

```
Digit        a3    a2   a1   a0
Decimal       0     7    9    2
Roman             DCC   XC   II

```

Therefore the roman numeral for `792` is `DCCXCII`. Here is a full list of all roman numerals that are relevant for this challenge: OEIS a006968.txt

### Examples

**Truthy**

```
MCCXXXIV (1234)
CMLXXXVIII (988)
DXIV (514)
CI (101)

```

**Falsey**

```
MMIXVIII
IVX
IXV
MMMM
XXXVX
IVI
VIV

```

# Answer
> 17 votes
# Verbose, 1362 bytes

```
GET A ROMAN NUMERAL TYPED IN BY THE CURRENT PERSON USING THIS PROGRAM AND PUT IT ONTO THE TOP OF THE PROGRAM STACK
PUT THE NUMBER MMMM ONTO THE TOP OF THE PROGRAM STACK
MOVE THE FIRST ELEMENT OF THE PROGRAM STACK TO THE SECOND ELEMENT'S PLACE AND THE SECOND ELEMENT OF THE STACK TO THE FIRST ELEMENT'S PLACE
DIVIDE THE FIRST ELEMENT OF THE PROGRAM STACK BY THE SECOND ELEMENT OF THE PROGRAM STACK AND PUT THE RESULT ONTO THE TOP OF THE PROGRAM STACK
PUT THE NUMBER V ONTO THE TOP OF THE PROGRAM STACK
GET THE FIRST ELEMENT OF THE PROGRAM STACK AND THE SECOND ELEMENT OF THE PROGRAM STACK AND IF THE SECOND ELEMENT OF THE PROGRAM STACK IS NOT ZERO JUMP TO THE INSTRUCTION THAT IS THE CURRENT INSTRUCTION NUMBER AND THE FIRST ELEMENT ADDED TOGETHER'S RESULT
PUT THE NUMBER I ONTO THE TOP OF THE PROGRAM STACK
GET THE TOP ELEMENT OF THE STACK AND OUTPUT IT FOR THE CURRENT PERSON USING THIS PROGRAM TO SEE
PUT THE NUMBER III ONTO THE TOP OF THE PROGRAM STACK
GET THE FIRST ELEMENT OF THE PROGRAM STACK AND THE SECOND ELEMENT OF THE PROGRAM STACK AND IF THE SECOND ELEMENT OF THE PROGRAM STACK IS NOT ZERO JUMP TO THE INSTRUCTION THAT IS THE CURRENT INSTRUCTION NUMBER AND THE FIRST ELEMENT ADDED TOGETHER'S RESULT
PUT THE NUMBER NULLA ONTO THE TOP OF THE PROGRAM STACK
GET THE TOP ELEMENT OF THE STACK AND OUTPUT IT FOR THE CURRENT PERSON USING THIS PROGRAM TO SEE

```

Outputs `I` for valid roman numerals in the range `I-MMMCMXCIX` and `NULLA` (0) or informs user input is not a valid roman numeral otherwise.

# Answer
> 9 votes
## C# (Visual C# Interactive Compiler), ~~79~~ 109 bytes

This seems like a Regex challenge, I'm sure a shorter solution can be found...

```
s=>System.Text.RegularExpressions.Regex.IsMatch(s,"^M{0,3}(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$")

```

Try it online!

# Answer
> 8 votes
# Wolfram Language (Mathematica), 35 bytes

```
Check[FromRomanNumeral@#<3999,1<0]&

```

Try it online!

*5 bytes saved, thanks to @attinat*

the limitation `[1,3999]` unfortunateley costs 7 bytes...
here is the code for any roman number

# Wolfram Language (Mathematica), 28 bytes

```
Check[FromRomanNumeral@#,F]&

```

Try it online!

the above code works for any number, not just \[1,3999\]

# Answer
> 8 votes
# Java 8, 70 bytes

```
s->s.matches("M{0,3}(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})")

```

Port of *@Innat3*'s C# answer, so make sure to upvote him!

Try it online.

**Explanation:**

```
s->                // Method with String parameter and boolean return-type
  s.matches("...") //  Check if the string matches the regex fully
                   //  (which implicitly adds a leading "^" and trailing "$")

M{0,3}             // No, 1, 2, or 3 adjacent "M"
(     |        )   // Followed by either:
 C[MD]             //  A "C" with an "M" or "D" after it
      |            // or:
       D?          //  An optional "D"
         C{0,3}    //  Followed by no, 1, 2, or 3 adjacent "C"
(     |        )   // Followed by either:
 X[CL]             //  An "X" with a "C" or "L" after it
      |            // or:
       L?          //  An optional "L"
         X{0,3}    //  Followed by no, 1, 2, or 3 adjacent "X"
(     |        )   // Followed by either:
 I[XV]             //  An "I" with an "X" or "V" after it
      |            // or:
       V?          //  An optional "V"
         I{0,3}    //  Followed by no, 1, 2, or 3 adjacent "I"

```

# Answer
> 8 votes
# CP-1610 assembly (Intellivision),  ~~52 ... 48~~  47 DECLEs1 = 59 bytes

Let's try this on a system that predates Perl by a good 7 years. :-)

Takes a pointer to a null-terminated string in **R4**. Sets the **Zero** flag if the input is a valid Roman numeral, or clears it otherwise.

```
                ROMW    10              ; use 10-bit ROM width
                ORG     $4800           ; map this program at $4800

                ;; ------------------------------------------------------------- ;;
                ;;  test code                                                    ;;
                ;; ------------------------------------------------------------- ;;
4800            EIS                     ; enable interrupts

4801            SDBD                    ; R5 = pointer into test case index
4802            MVII    #ndx,     R5
4805            MVII    #$214,    R3    ; R3 = backtab pointer
4807            MVII    #11,      R0    ; R0 = number of test cases

4809  loop      SDBD                    ; R4 = pointer to next test case
480A            MVI@    R5,       R4
480B            PSHR    R0              ; save R0, R3, R5 onto the stack
480C            PSHR    R3
480D            PSHR    R5
480E            CALL    isRoman         ; invoke our routine
4811            PULR    R5              ; restore R5 and R3
4812            PULR    R3

4813            MVII    #$1A7,    R0    ; use a white 'T' by default
4815            BEQ     disp

4817            MVII    #$137,    R0    ; or a white 'F' is the Z flag was cleared

4819  disp      MVO@    R0,       R3    ; draw it
481A            INCR    R3              ; increment the backtab pointer

481B            PULR    R0              ; restore R0
481C            DECR    R0              ; and advance to the next test case, if any
481D            BNEQ    loop

481F            DECR    R7              ; loop forever

                ;; ------------------------------------------------------------- ;;
                ;;  test cases                                                   ;;
                ;; ------------------------------------------------------------- ;;
4820  ndx       BIDECLE test0, test1, test2, test3
4828            BIDECLE test4, test5, test6, test7, test8, test9, test10

                ; truthy
4836  test0     STRING  "MCCXXXIV", 0
483F  test1     STRING  "CMLXXXVIII", 0
484A  test2     STRING  "DXIV", 0
484F  test3     STRING  "CI", 0

                ; falsy
4852  test4     STRING  "MMIXVIII", 0
485B  test5     STRING  "IVX", 0
485F  test6     STRING  "IXV", 0
4863  test7     STRING  "MMMM", 0
4868  test8     STRING  "XXXVX", 0
486E  test9     STRING  "IVI", 0
4872  test10    STRING  "VIV", 0

                ;; ------------------------------------------------------------- ;;
                ;;  routine                                                      ;;
                ;; ------------------------------------------------------------- ;;
      isRoman   PROC

4876            PSHR    R5              ; push the return address

4877            MOVR    R7,       R2    ; R2 = dummy 1st suffix
4878            MOVR    R2,       R5    ; R5 = pointer into table
4879            ADDI    #@tbl-$+1,R5

487B  @loop     MVI@    R5,       R1    ; R1 = main digit (M, C, X, I)
487C            MVI@    R5,       R3    ; R3 = prefix or 2nd suffix (-, D, L, V)

487D            MVI@    R4,       R0    ; R0 = next digit

487E            CMPR    R0,       R3    ; if this is the prefix ...
487F            BNEQ    @main

4881            COMR    R2              ; ... disable the suffixes
4882            COMR    R3              ; by setting them to invalid values
4883            MVI@    R4,       R0    ; and read R0 again

4884  @main     CMPR    R0,       R1    ; if R0 is not equal to the main digit,
4885            BNEQ    @back           ; assume that this part is over

4887            MVI@    R4,       R0    ; R0 = next digit
4888            CMPR    R0,       R1    ; if this is a 2nd occurrence
4889            BNEQ    @suffix         ; of the main digit ...

488B            CMP@    R4,       R1    ; ... it may be followed by a 3rd occurrence
488C            BNEQ    @back

488E            MOVR    R2,       R0    ; if so, force the test below to succeed

488F  @suffix   CMPR    R0,       R2    ; otherwise, it may be either the 1st suffix
4890            BEQ     @next
4892            CMPR    R0,       R3    ; or the 2nd suffix (these tests always fail
4893            BEQ     @next           ; if the suffixes were disabled above)

4895  @back     DECR    R4              ; the last digit either belongs to the next
                                        ; iteration or is invalid

4896  @next     MOVR    R1,       R2    ; use the current main digit
                                        ; as the next 1st suffix

4897            SUBI    #'I',     R1    ; was it the last iteration? ...
4899            BNEQ    @loop

489B            CMP@    R4,       R1    ; ... yes: make sure that we've also reached
                                        ; the end of the input

489C            PULR    R7              ; return

489D  @tbl      DECLE   'M', '-'        ; table format: main digit, 2nd suffix
489F            DECLE   'C', 'D'
48A1            DECLE   'X', 'L'
48A3            DECLE   'I', 'V'

                ENDP

```

### How?

The regular expression can be rewritten as 4 groups with the same structure, provided that `#` is any invalid character that is guaranteed not be present in the input string.

```
                 +-------+---> main digit
                 |       |
(M[##]|#?M{0,3})(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})
                   ||  |
                   |+--+-----> prefix or second suffix
                   |
                   +---------> first suffix

```

The *first suffix* of the group \\$N\\$ is the *main digit* of the group \\$N-1\\$. Therefore, we can store the patterns with the pair \\$(\text{main\_digit}, \text{second\_suffix})\\$ alone.

Our routine attempts to parse the input string character by character according to these patterns and eventually checks whether the end of the string is reached.

### Output

*screenshot of jzIntv*

---

*1. A CP-1610 opcode is encoded with a 10-bit value, known as a 'DECLE'. This routine is 47 DECLEs long, starting at $4876 and ending at $48A4 (included).*

# Answer
> 5 votes
# , ~~74~~ ~~71~~ 56 bytes

Thanks to @RobinRyder, @Giuseppe, & @MickyT for their suggestions how to use grep effectively with R's built in `as.roman`.

```
sub("^M(.+)","\\1",scan(,""))%in%paste(as.roman(1:2999))

```

Try it online!

# Answer
> 4 votes
# Wolfram Language (Mathematica), 32 bytes

```
RomanNumeral@Range@3999~Count~#&

```

Try it online!

# Answer
> 2 votes
# Jelly,  ~~48 47 46~~  44 bytes

-1 thanks to Nick Kennedy

```
5Żo7;“ÆæC‘ð“IVXLCDM”ṃ@3Ƥm2”MẋⱮ3¤ṭŻ€ṚŒpF€ḟ€0ċ

```

A monadic Link accepting a non-empty list of characters consisting only of `IVXLCDM` which yields either `1` (when it's a valid Roman numeral between \\$1\\$ and \\$3999\\$) or `0` (if not).

**Try it online!** Or see the test-suite.

### How?

```
5Żo7;“ÆæC‘ð“IVXLCDM”ṃ@3Ƥm2”MẋⱮ3¤ṭŻ€ṚŒpF€ḟ€0ċ  - Main Link: list of characters S

5Żo7;“ÆæC‘  - chain 1: f(S) -> X
5Ż          - zero range of five = [0,1,2,3,4,5]
  o7        - OR seven             [7,1,2,3,4,5]
     “ÆæC‘  - list of code-page indices        [13,22,67]
    ;       - concatenate          [7,1,2,3,4,5,13,22,67]

          ð - start a new dyadic chain...

“IVXLCDM”ṃ@3Ƥm2”MẋⱮ3¤ṭŻ€ṚŒpF€ḟ€0ċ - chain 2: f(X,S) -> isValid
“IVXLCDM”                         - list of characters, IVXLCDM
           3Ƥ                     - for infixes of length three:
                                  - (i.e. IVX VXL XLC LCD CDM)
         ṃ@                       -   base decompression with swapped arguments
                                  -   (i.e. use characters as base-3 digits of X's values)
                                  -   (e.g. IVX -> VI I V IX II IV III VII VIII)
             m2                   - modulo two slice (results for IVX XLC and CDM only)
                    ¤             - nilad followed by link(s) as a nilad:
               ”M                 -   character 'M'
                  Ɱ3              -   map across [1,2,3] with:
                 ẋ                -     repeat -> M MM MMM
                     ṭ            - tack
                      Ż€          - prepend a zero to each
                        Ṛ         - reverse
                                  -   -- now we have the table:
                                  -    0 M MM MMM
                                  -    0 DC C D CM CC CD CCC DCC DCCC
                                  -    0 LX X L XC XX XL XXX LXX LXXX
                                  -    0 VI I V IX II IV III VII VIII
                         Œp       - Cartesian product   [[0,0,0,0],...,["M","CM",0,"IV"],...]
                           F€     - flatten €ach  [[0,0,0,0],...,['M','C','M',0,'I','V'],...]
                             ḟ€0  - filter out the zeros from €ach       ["",...,"MCMIV",...]
                                ċ - count occurrences of S

```

# Answer
> 1 votes
# Perl 5 (`-p`), 57 bytes

```
$_=/^M*(C[MD]|D?C*)(X[CL]|L?X*)(I[XV]|V?I*)$/&!/(.)\1{3}/

```

TIO

* uses almost the same regular expression except `{0,3}` quantifier was changed by `*`
* `&!/(.)\1{3}/` to ensure the same character can't occur 4 times in a row.
* can't be golfed with `-/(.)\1{3}/` because would give`-1` for `IIIIVI` for example

# Answer
> 1 votes
# 05AB1E, ~~61~~ ~~9~~ 8 bytes

```
ŽF¯L.XIå

```

Whopping \\$\color{green}{\textrm{-52 bytes}}\\$ thanks to *@Adnan*, because apparently 05AB1E's Roman Number builtin wasn't documented, haha.. xD

Try it online or verify all test cases.

**Explanation:**

```
ŽF¯       # Push comressed integer 3999
   L      # Create a list in the range [1,3999]
    .X    # Convert each integer in this list to a roman number string
      Iå  # Check if the input is in this list
          # (and output the result implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `ŽF¯` is `3999`.

---

**Original 61 bytes answer:**

```
•1∞Γ'иÛnuÞ\₂…•Ž8вв€SÐ)v.•6#&‘нδ•u3ôNèyè}'M3L×)Rεõš}`3Fâ}€˜JIå

```

Try it online or verify all test cases.

**Explanation:**

```
•1∞Γ'иÛnuÞ\₂…•             '# Push compressed integer 397940501547566186191992778
              Ž8в           # Push compressed integer 2112
                 в          # Convert the integer to Base-2112 as list:
                            #  [1,11,111,12,2,21,211,2111,10]
€S                          # Convert each number to a list of digits
  Ð                         # Triplicate this list
   )                        # And wrap it into a list of lists (of lists)
    v                       # Loop `y` over each these three lists:
     .•6#&‘нδ•              #  Push compressed string "xivcxlmcd"
              u             #  Uppercased
               3ô           #  And split into parts of size 3: ["XIV","CXL","MCD"]
     Nè                     #  Use the loop index to get the current part
       yè                   #  And index the list of lists of digits into this string
    }'M                    '# After the loop: push "M"
       3L                   # Push list [1,2,3]
         ×                  # Repeat the "M" that many times: ["M","MM","MMM"]
          )                 # Wrap all lists on the stack into a list:
                            # [[["I"],["I","I"],["I","I","I"],["I","V"],["V"],["V","I"],["V","I","I"],["V","I","I","I"],["I","X"]],[["X"],["X","X"],["X","X","X"],["X","L"],["L"],["L","X"],["L","X","X"],["L","X","X","X"],["X","C"]],[["C"],["C","C"],["C","C","C"],["C","D"],["D"],["D","C"],["D","C","C"],["D","C","C","C"],["C","M"]],["M","MM","MMM"]]
           R                # Reverse this list
            εõš}            # Prepend an empty string "" before each inner list
                `           # Push the four lists onto the stack
                 3F         # Loop 3 times:
                   â        #  Take the cartesian product of the two top lists
                    }€˜     # After the loop: flatten each inner list
                       J    # Join each inner list together to a single string
                        Iå  # And check if the input is in this list
                            # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (sections *How to compress strings not part of the dictionary?*, *How to compress large integers?*, and *How to compress integer lists?*) to understand why:

* `•1∞Γ'иÛnuÞ\₂…•` is `397940501547566186191992778`
* `Ž8в` is `2112`
* `•1∞Γ'иÛnuÞ\₂…•Ž8вв` is `[1,11,111,12,2,21,211,2111,10]`
* `.•6#&‘нδ•` is `"xivcxlmcd"`

# Answer
> 1 votes
# Python 2, 81 bytes

```
import re
re.compile('M{,3}(D?C{,3}|C[DM])(L?X{,3}|X[LC])(V?I{,3}|I[VX])$').match

```

Try it online!

Let's look at the last part of the regex, which matching the Roman numerals up to 9 (including the empty string)

```
V?I{,3}|I[VX]

```

This has two alternatives separated by `|`:

* `V?I{,3}`: An optional `V` followed by up to 3 `I`'s. This matches the empty string `I`,`II`,`III`, `V`, `VI`,`VII`,`VIII`.
* `I[VX]`: An `I` followed by a `V` or `X`. This matches `IV` and `IX`.

The same things with `X,L,C` matching the tens, with `C,D,M` matches the hundreds, and finally `^M{,3}` allows up to 3 `M`'s (thousands) at the start.

I tried generating the template for each trio of characters rather than writing it 3 times, but this was a lot longer.

# Answer
> 1 votes
# Retina, ~~56~~ 51 bytes

```
(.)\1{3}
0
^M*(C[MD]|D?C*)(X[CL]|L?X*)(I[XV]|V?I*)$

```

Port of *@NahuelFouilleul*'s Perl 5 answer, so make sure to upvote him!

Try it online or verify all test cases.

**Explanation:**

```
(.)\1{3}        # If four adjacent characters can be found which are the same
0               # Replace it with a 0

^...$           # Then check if the string matches the following fully:
 M*             #  No or any amount of adjacent "M"
 (     |    )   #  Followed by either:
  C[MD]         #   A "C" with an "M" or "D" after it
       |        #  or:
        D?      #   An optional "D"
          C*    #   Followed by no or any amount of adjacent "C"
 (     |    )   #  Followed by either:
  X[CL]         #   An "X" with a "C" or "L" after it
       |        #  or:
        L?      #   An optional "L"
          X*    #   Followed by no or any amount of adjacent "X"
 (     |    )   #  Followed by either:
  I[XV]         #   An "I" with an "X" or "V" after it
       |        #  or:
        V?      #   An optional "V"
          I*    #   Followed by no or any amount of adjacent "I"

```

# Answer
> 0 votes
# Python 3, ~~116~~ ~~113~~ ~~109~~ ~~107~~ ~~105~~ 106 bytes

```
import re
lambda n:re.match(r'(M{,3}(C(M|CC?|D)?|DC{,3}))(X(C|XX?|L)?|(LX{,3}))?(I(X|II?|V)?|VI{,3})?$',n)

```

Try it online!

*-1 byte thanks to ShadowRanger*

# Answer
> 0 votes
# perl -MRegexp::Common -pe, 34 bytes

```
$_=/^$RE{num}{roman}$/&!/(.)\1{3}/

```

The `&!/(.)\1{3}/` part is necessary, because `Regexp::Common` allows four (but not five) of the same characters in a row. That way, it matches roman numbers used on clock faces, where `IIII` is often used for 4.

# Answer
> 0 votes
# Ruby, (`-n`) 56 bytes

```
p~/^M{,3}(D?C{,3}|CM|CD)(L?X{,3}|XC|XL)(V?I{,3}|IV|IX)$/

```

Try it online!

Outputs 0 (truthy) or nil (falsy).

---
Tags: code-golf, string, number, decision-problem, roman-numerals
---


title: Please release me!

text:
# Question
Title: Please release me!
As code-golfers, we're not used to releasing (*surely*). We're gonna need a few tools to help us do that.

Of course, to help marketing a new release, we need a nice and shiny Release Version. Who doesn't get excited when they hear about version 3.0.0?

### Task

Your task will be to write a program/routine/... to increment a version number.

You need to increment the version number and reset the "less important" ones (i.e. patch version).

You get two arguments: the current version (ex "1.0.3") as a string, and an index to know which one to update (0 or 1-indexed).

Example, 0-indexed:

```
next-version("1.0.3", 0) # 2.0.0
next-version("1.2.3.4.5", 2) # 1.2.4.0.0
next-version("10.0", 0) # 11.0
next-version("3", 0) # 4
next-version("1", 7) # ERROR
next-version("01", 0) # ERROR

```

The version is a string, each part is a number, separated with a dot. There can be no leading, no trailing or no consecutive dots (and nothing outside of numbers/dots). There is no limit to the size of the version string.

`^[1-9]\d*(\.[1-9]\d*)*$`

The error case (last two examples) is undefined behavior. What happens in case of wrong inputs is of no relevance to this challenge.

As usual, standard loopholes are forbidden. You're allowed to print or return the string.

# Answer
# Japt, ~~16~~ 11 bytes

```
¡V«´V+ÂX}'.

```

Test it online! Input number is 1-indexed.

Based on my JavaScript answer. This takes advantage of one of Japt's most helpful features: splitting one string on another before mapping each item, then joining on that string again after mapping.

### Ungolfed and explanation

```
¡  V«  ´ V+Â X}'.
Um@V&&!--V+~~X}'.
                   Implicit: U = input string, V = input number
Um@           }'.  Split U at periods, then map each item X by this function:
   V&&               If V is 0, return V.
      !--V+~~X       Otherwise, decrement V and return X + !V (increments X iff V was 1).
               '.  Re-join the result with periods.
                   Implicit: output last expression

```
> 11 votes

# Answer
# JavaScript (ES6), ~~44~~ ~~42~~ ~~40~~ 37 bytes

*Saved 3 bytes thanks to @Neil*

```
x=>i=>x.replace(/\d+/g,n=>i&&+n+!--i)

```

Input number is 1-indexed.

### Test snippet

```
f = x=>i=>x.replace(/\d+/g,n=>i&&+n+!--i)

console.log(f("1.0.3")(1))
console.log(f("1.2.3.4.5")(3))
console.log(f("10.0")(1))
console.log(f("1")(8))
```
> 10 votes

# Answer
# Vim ~~20~~ 25 bytes

I unfortunately realized that it didn't handle the case of updating the last number, so I had to add bytes. This is 1-indexed.

```
DJA.0@"t.qq2wcw0@qq@qx

```

TryItOnline

Unprintables:

```
DJA.^[0@"t.^Aqq2wcw0^[@qq@qx

```

This takes the arguments in reverse order, as separate lines:

```
3
1.2.3.4.5

```

Explanation:

```
DJ                           # Delete the input argument, and join lines
  A.^[0                      # Add a period to the end
       @"t.                  # Move to the "Copy register"th period
           ^A                # Increment the number under the cursor
             qq       @qq@q  # Until an error
               2w            # Move the cursor forward to the next number
                 cw0^[       # Change the number to 0
                           x # Delete the last '.'

```
> 10 votes

# Answer
# , ~~13~~, 12 bytes

```
Àñf.ñò2wcw0

```

Try it online!

This is 0-indexed.

There is a `ctrl-a` (ASCII 0x01) in there, so here is a readable version:

```
Àñf.ñ<C-a>ò2wcw0

```

Explanation:

```
À                   " 'arg1' times
 ñ  ñ               " Repeat the following:
  f.                "   Move to the next '.' character
     <C-a>          " Increment the next number
          ò         " Recursively:
           2w       "   Move two words forward
              cw    "   Change this word
                0   "   to a '0'

```
> 10 votes

# Answer
# Perl, ~~40~~ ~~37~~ 34 + 1 = 35 bytes

-2 bytes thanks to @Dada. -3 bytes thanks to an idea I got from reading @ETHproductions's Japt code.

Run with the `-p` flag.

```
$a=<>;s/\d+/$a--<0?0:$&+!($a+1)/ge

```

Try it online!

### Breakdown of the code

```
-p          #Wraps the program in a while(<>){ ... print$_} statement.
            #Input is read into the $_ variable
$a=<>;s/\d+/$a--<0?0:$&+!($a+1)/ge
$a=<>;                              #Reads the version update into $a
      s/   /                   /ge  #Substitution regex:
                                g   #Repeats the substitution after first match
                                 e  #Interprets replacement as Perl code
       \d+                          #Matches 1 or more digits, and stores match in $&
                  ? :               #Ternary operation
            $a--<0                  #Checks if $a is negative and then decrements $a
                  ?0                #If negative, we've passed our match; print 0 instead
                    :$&+!($a+1)     #Otherwise, we're either printing $& + 0 (if $a was positive) or $& + 1 (if $a was 0).
#Since substitution implicitly modifies $_, and -p prints $_, it prints our answer

```
> 7 votes

# Answer
# C# ~~116~~ 104 Bytes

```
using System.Linq;(v,i)=>string.Join(".",v.Split('.').Select(int.Parse).Select((x,n)=>n==i?x+1:n>i?0:x));

```

## Explanation

```
using System.Linq;(v,i)=>   //Anonymous function and mandatory using
    string.Join(".",                    //Recreate the version string with the new values
        v.Split('.')                    //Get individual pieces
            .Select(int.Parse)          //Convert to integers
                .Select(
                    (x,n)=>             //Lambda with x being the part of the version and n being the index in the collection
                        n==i
                            ?x+1        //If n is the index to update increment x
                            :n>i        //Else if n is greater than index to update
                                ?0      //Set to zero
                                :x));   //Otherwise return x

```

Try it here
> 6 votes

# Answer
# Python 2, 84 Bytes

I feel like this could really be shorter.. Might need a way to have a non-enumerate option.

```
lambda s,n:'.'.join(str([-~int(x)*(i==n),x][i<n])for i,x in enumerate(s.split('.')))

```

If we were able to take the version as a list of strings, there's a 75-byte solution:

```
g=lambda s,n:(str(-~int(s[0]))+'.0'*~-len(s))*(n<1)or s[0]+'.'+g(s[1:],n-1)

```

Furthermore, if both the input and output were lists of numbers, there's a 64-byte solution:

```
g=lambda s,n:([-~s[0]]+[0]*~-len(s))*(n<1)or [s[0]]+g(s[1:],n-1)

```
> 5 votes

# Answer
# Jelly, ~~19~~ 17 bytes

```
ṣ”.V€‘⁹¦µJ’<⁹×j”.

```

1-indexed.

**TryItOnline!**

### How?

```
ṣ”.V€‘⁹¦µJ’<⁹×j”. - Main link: currentVersion, theIndex
ṣ”.               - ṣplit left (currentVersion) at occurences of '.'
   V€             - eVal €ach (creates a list of integers)
      ⁹           - right argument (theIndex)
       ¦          - apply to given index(es)
     ‘            -    increment
        µ         - monadic chain separation (call the above result z)
         J        - range(length(z))  i.e. ([1,2,3,...,length])
          ’       - decrement         i.e. ([0,1,2,...,length-1])
            ⁹     - right argument (theIndex)
           <      - less than?        i.e. ([1,1,...,(1 at theIndex),0...,0,0,0]
             ×    - multiply by z (vectortises) - zeros out all of z after theIndex
              j”. - join with '.'

```
> 5 votes

# Answer
# **MATLAB, 85 bytes**

```
function f(s,j);a=split(s,'.');a(j)=string(double(a(j))+1);a(j+1:end)='0';join(a,'.')

```

One based, and first attempt at golf!
> 5 votes

# Answer
# Perl 6, 67 bytes, 0-indexed

```
->$v,$i {$v.split('.').map({++$>$i??($++??0!!$_+1)!!$_}).join: '.'}

```

Explanation:

```
->$v,$i {$v.split('.').map({++$>$i??($++??0!!$_+1)!!$_}).join: '.'}
->$v,$i {                                                         } # function taking version/index to increment
         $v.split('.')                                              # split by dot
                      .map({                          })            # for each version number
                            ++$>$i??                                # if an anonymous variable ($), incremented,
                                                                    #  is greater than $i (index to increment)
                                    ($++??       )                  # if it's not the first time we've been over $i
                                                                    # (using another anonymous value, which gets default-init'd to 0)
                                          0                         # then 0 (reset lower version numbers)
                                           !!$_+1                   # otherwise, increment the number at $i
                                                  !!$_              # otherwise return the number part
                                                        .join: '.'  # join with a dot

```
> 4 votes

# Answer
# V ~~14~~ 20 bytes

Again, I had to add code for the corner case of incrementing the final digit. (1-indexed)

```
DJA.0@"t.ò2wcw0òx

```

TryItOnline

Unprintables:

```
DJA.^[0@"t.^Aò2wcw0^[òx

```

This takes the arguments in reverse order, as separate lines:

```
3
1.2.3.4.5

```
> 4 votes

# Answer
## Batch, 119 bytes

```
@set s=%1
@set i=%2
@set t=
@for %%i in (%s:.=,%)do @set/an=!!i*(%%i+!(i-=!!i))&call set t=%%t%%.%%n%%
@echo %t:~1%

```

1-indexed.
> 4 votes

# Answer
# PowerShell 3+, ~~75~~ 74 bytes

```
($args[0]-split'\.'|%{$m=!$b;$b=$b-or$args[1]-eq$i++;(+$b+$_)*$m})-join'.'

```

### Ungolfed

```
(
    $args[0] -split '\.' |
        ForEach-Object -Process {
            $m= -not $b
            $b = $b -or ($args[1] -eq $i++)
            (([int]$b) + $_) * $m
        }
) -join '.'

```

### Explanation

Parameters are accepted using the `$args` array.

1. Split the version string on `.`, then for each element:
    1. `$m` is set to be `-not $b`. On first run, `$b` will be undefined which will be coalesced to `$false`, so `$m` will start as `$true`. `$m` is intended to be a multiplier that's always `0` or `1` and it will be used later. `$m` must be evaluated here because we want it to be based on the last iteration's `$b` value.
    2. `$b` is set to itself `-or` the result of comparing an iterator `$i` with `$args[1]` (the index parameter). This means `$b` will be set to `$true` here once we're on the element that is to be incremented. Additionally, it will be `$true` in every subsequent iteration because the conditional is `-or`'d with its current value.
    3. `$b` is converted to a number using unary `+` (`$false` =\> `0`, `$true` =\> `1`), then added to the current version element `$_` which is a `[string]`, but PowerShell always tries to coalesce the argument on the right to the type on the left, so arithmetic will be performed, not string concatenation. Then this value will be multiplied by `$m`, which is still `[bool]` but will be implicitly coalesced.
2. Re-join the resulting array with `.`.

So, the first iteration where `$b` becomes `$true`, `$b` would have been `$false` when `$m` was evaluated, making `$m` equal `$true`, which will keep the multiplier at `1`.

During that run `$b` becomes `$true` and is added to the version element (as `1`), thereby incrementing it, and since the multiplier is still `1`, that will be the end result.

So on the next iteration, `$b` will already be `$true`, making `$m` equal `$false`, which will make the multiplier `0`. Since `$b` will forever be `$true` now, the multiplier will always be `0`, so every element returned will be `0` too.
> 3 votes

# Answer
# PHP, 81 bytes

awfully long. At least: the Elephpant still beats the Python.

```
foreach(explode(".",$argv[1])as$i=>$v)echo"."[!$i],($i<=$n=$argv[2])*$v+($i==$n);

```

loops through first argument split by dots: `"."[!$i]` is empty for the first and a dot for every other element; `($i<=$n)` and `($i==$n)` are implicitly cast to integer `0` or `1` for integer arithmetics.
> 3 votes

# Answer
# R, ~~100~~ ~~95~~ ~~92~~ 86 bytes

Unusually for R, this uses 0-indexing. Anonymous function with two arguments (a string and an integer). Likely can be golfed down a tad.

```
function(v,i)cat((x=scan(t=el(strsplit(v,"\\."))))+c(rep(0,i),1,-x[-(0:i+1)]),sep=".")

```
> 2 votes

# Answer
# 05AB1E, 22 bytes

```
'.¡vy²N‹i0*}²NQi>})'.ý

```

Try it online!

I don't know how to do if-else in 05AB1E, so this is longer than it should be.
> 2 votes

# Answer
# Coffee-script: 77 67 Bytes

```
f=(p,i)->((z<i&&v||z==i&&~~v+1||0)for v,z in p.split '.').join '.'

```

Woot! Time for cake and coffee for the beta release.

Thanks to @ven and @Cyoce I shaved 10 Bytes!
> 2 votes

# Answer
# Python 3, ~~89~~ 86 bytes

```
lambda v,c:'.'.join((str((int(x)+1)*(i==c)),x)[i<c]for i,x in enumerate(v.split('.')))

```

very naive way of getting things done

Edit: rewritten the conditional by referring to @kade
> 2 votes

# Answer
# JavaScript (ES6), ~~57~~ 55 bytes

```
(s,x)=>s.split`.`.map((j,i)=>i==x?+j+1:i>x?0:j).join`.`

```

Examples:

```
n=(s,x)=>s.split`.`.map((j,i)=>i==x?+j+1:i>x?0:j).join`.`

console.log(n('1.0.3', 0))
console.log(n('1.2.3.4.5', 2))
console.log(n('10.0', 0))
console.log(n('3', 0))
console.log(n('1', 7))
```

Not the best JS implementation but it's fairly simple and follows the logic you'd expect.
> 2 votes

# Answer
# LiveScript, ~~53~~ 52 bytes

```
->(for e,i in it/\.
 [+e+1;0;e][(i>&1)+2*(i<&1)])*\.

```

-1 byte thanks to @ASCII-only!

Old Explanation:

```
(a,b)->x=a/\.;x[b]++;(x[to b] ++ [0]*(x.length-1-b))*\.
(a,b)->                                                 # a function taking a and b (version and index)
       x=a/\.;                                          # split a on dot, store in x
              x[b]++;                                   # increment at the given index
                     (x[to b]                           # slice be from 0 to the index
                              ++                        # concat (both spaces are necessary so it's not interpreted as an increment operator
                                 [0]*(x.length-1-b))    # with enough zeros to fill the array back to its original size (x's size)
                                                    *\. # join on dot

```

Another self-answer... Not that anyone golfes in LiveScript anyway. :P

I was working on another version:

```
(a,b)->(a/\.=>..[b]++;..[b to *]=0)*\.

```

But `*` is too overloaded to be recognized in a splicing index, thus `=0` will try to access `0[0]`. So you need to write something like `..[b to ..length- b]=[0]*(..length-1-b)` and it's longer in the end.
> 1 votes

# Answer
## Powershell, ~~80~~ ~~100~~ ~~95~~ 92 Bytes

Saved 5 bytes by using a const for the `-1..if`

Saved 3 bytes by using `!$b` instead of `$b-eq0`

```
filter x($a,$b){[int[]]$y=$a.Split('.');-1..((-$b,-1)[!$b])|%{$y[$_]=0};$y[$b]++;$y-join'.'}

```

Explanation:

```
filter x($a,$b){
    [int[]]$y=$a.Split('.') #Split input into integer array
    $y[$b]++ #Increment 'major' version no. ($b) by one
    -1..((-$b,-1)[!$b])|%{$y[$_]=0} #Set all trailing numbers to 0, now also checks for $b=0 cases.
    $y-join'.' #Join back into '.' seperated Array
}

```

Test Cases:

```
x "1.0.3" 0
x "1.2.3.4.5" 2
x "10.0" 0
x "1" 7
2.0.0
1.2.4.0.0
11.0
Index was outside the bounds of the array.

```
> 1 votes

# Answer
**Objective-C 531 Bytes**

```
#import<Foundation/Foundation.h>
int main(int argc,const char *argv[]){@autoreleasepool{NSString *s=[NSString stringWithUTF8String:argv[1]];NSInteger n=strtol(argv[2],NULL,0);NSArray *c=[s componentsSeparatedByString:@"."];if(c.count<=n)NSLog(@"ERROR");else{int i=0;NSMutableString *v=[[NSMutableString alloc]init];for(;i<n;++i)[v appendFormat:@"%@.",[c objectAtIndex:i]];[v appendFormat:@"%li", strtol(((NSString *)[c objectAtIndex:i++]).UTF8String,NULL,0)+1l];for(;i<c.count;++i)[v appendString:@".0"];NSLog(@"%@",v);}}return 0;}

```

compile:

```
clang -fobjc-arc -Os main.m -o main

```

usage:

```
./main 1.2.3 1

```
> 1 votes

# Answer
# Javascript ES6: 60 bytes

```
n.split(".").map((n,r)=>{return r>i?n=0:n}).join("."),n[i]++}

```
> 1 votes

# Answer
# R, 75 bytes

```
f=function(a,b){n=scan(t=a,se=".");m=-n;m[b]=1;m[1:b-1]=0;cat(n+m,sep=".")}

```

Indexing is 1-based. You can play with it online here.
> 1 votes

# Answer
# APL (Dyalog), 31 bytes

Requires `⎕IO←0` (**I**ndex **O**rigin 0), which is default on many systems. Full program body; prompts for text input (version) and then numeric input (index).

```
' '⎕R'.'⍕⎕(⊢∘≢↑↑,1+⊃)⊃⌽'.'⎕VFI⍞

```

Try it online!

prompt for text input

`'.'⎕VFI`**V**erify and **F**ix **I**nput using period as field separator (fields' validities, fields' values)

reverse (to put the values in front)

pick the first (the values)

`⎕(`...`)` apply the following tacit function to that, using evaluated input as left argument:

To explain the non-tacit equivalents of each function application we will now use  to indicate the left argument (the index) and  to indicate the right argument (the list of individual numbers of the originally inputted current version number).

equivalent to `(⍺⊃⍵)` use  to pick an element from

`1+` add one to that

`↑,` equivalent to `(⍺↑⍵),` prepend  numbers taken from

`⊢∘≢↑` equivalent to `(⍺⊢∘≢⍵)↑` equivalent to `(≢⍵)↑` take as many numbers from that as there are elements in , padding with zeros if necessary

format (stringify with one space between each number)

`' '⎕R'.'` PCRE **R**eplace spaces with periods
> 1 votes

# Answer
# Java 8, 130 bytes

```
s->n->{String r="",a[]=s.split("\\.");for(int l=a.length,i=-1;++i<l;)r+=(i>n?0:new Long(a[i])+(i<n?0:1))+(i<l-1?".":"");return r;}

```

**Explanation:**

Try it here.

```
s->n->{                 // Method with String and Integer parameters and String return-type
  String r="",          //  Result-String
  a[]=s.split("\\.");   //  String-array split by the dots
  for(int l=a.length,   //  Length of the array
      i=-1;++i<l;)      //  Loop from 0 to `l` (exclusive)
    r+=                 //   Append the result-String with:
       (i>n?            //    If index `i` is beyond input `n`:
        0               //     Append a zero
       :                //    Else:
        new Long(a[i])  //     Convert the current String to a number
        +(i<n?          //     If index `i` is before input `n`
           0            //      Leave the number the same by adding 0
          :             //     Else:
           1))          //      Add 1 to raise the version at index `n`
       +(i<l-1?         //    If we've haven't reached the last iteration yet:
          "."           //     Append a dot
         :              //    Else:
          ""            //     Append nothing
   );                   //  End of loop
   return r;            //  Return the result-String
}                       // End of method

```
> 1 votes

# Answer
# Haskell, ~~136~~ 129 bytes

```
import Data.List.Split
import Data.List
f s n|(x,z:y)<-splitAt n(splitOn "."s)=intercalate "."(x++[show$read z+1]++map(\_->"0")y)

```

Try it online!

---

Original
> 1 votes

# Answer
# Pyth - 21 bytes

```
j\.++<Kcz\.Qhs@KQmZ>K

```

Test Suite
> 0 votes

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


title: MacGyver's Second Toolbox

text:
# Question
Title: MacGyver's Second Toolbox
In this question each answer will get a "toolbox" that can be used to construct a program/function. The toolbox will consist of two things:

* a list of programming languages
* a list of valid characters

You must write a valid program/function in one of the languages provided using only the characters in the toolbox. Your program/function should output the number of answers already present on this question.

Once you have written and posted an answer the language and characters you have used will be removed from the toolbox and 1 new language and 8 new characters will be randomly added to be used as the toolbox for the next answer.

## Rules

* Each answer will:

+ Output the number of valid answers coming before it
    + Contain a subset of the characters provided in the toolbox for that answer. (repeats are allowed)
    + Be in one of the languages from the provided toolbox
* The next toolbox will determined by this python program. To generate the next toolbox put in the remaining languages and characters along with the *post id* of the last answer.
* The language list here is all the languages available on try it online at the time of this post. The characters have char codes 0-127.
* You may write either a full program or a function as your answer. Since REPLs are different languages they will not be allowed. (use the TIO version of every language)
* If a language uses a special encoding the characters should be interpreted as *bytes* (decoded from ASCII and padded with a zero).
* The starting toolbox will be randomized from this questions post id (128464), there will be 7 languages to start and I will add the characters `echoprint0` and ascii 0-31 for free to get people started.
* You may not answer twice in a row

## Scoring

Each time a person answers they will get a number of points for their answer. The goal is to get as many points as possible. For an answer in language X you will get as many turns as language X has gone unused in the toolbox. For example the first person to answer will get 1 point because the language was just added to the toolbox. There will not necessarily be an end and I will not be accepting any answers.

## Sporting

This is a competition, but I encourage you to put fun above winning while still staying competitive (if I could make the winning criteria "fun had" I would). Some things that are not fun:

* Intentionally using characters you don't need to stunt future answers.
* Attempting to game the post id system to make future tool boxes harder to use.
* Attempting to game the post id system to make future tool boxes easier to use.

I can't prevent any one from doing these things, but I will be downvoting any answers I suspect are doing this.

On a more positive note, here are some things that are good sporting and encouraged:

* Coordinating with other users in chat.
* Saving characters for harder or more restrictive languages

> This is a second iteration of a challenge found here. It improves a number of problems with the first one. Here is a meta discussing these questions.

# Answer
> 9 votes
# This is impossible

Going through all of the languages in the langbox:

1. The tcl programming language consists of words separated by spaces. The space character is not in the toolbox, so no valid programs can be written.
2. Str programs by default transform input. In order for them to do anything when given no input, the `;` character is required, which is not in the toolbox.
3. The only means for a program in scheme-chez to do anything is by calling a function using parentheses. All scheme-chez programs therefore need the `(` character, which is not in the toolbox
4. Brain-Flak programs need balanced brackets. The only bracket character in the toolbox is `)`, so no programs containing balanced brackets are possible.
5. Similar to scheme, maxima programs require parentheses to do anything.
6. Java programs require the `{` or `->` character sequences to declare a function (and all full programs need at least one function), none of which are in the toolbox.
7. Condit programs require the word `when`, which contains the "e" character, which is not in the toolbox.

Proofs of impossibility are allowed as answers

# Answer
> 4 votes
# 2. Oasis

```
n!

```

Try it online!

Next toolbox

# Answer
> 3 votes
# 1. Bash, outputs 0

```
echo	0

```

Try it online!

The code contains a literal tab.

Next toolbox

---
Tags: restricted-source, answer-chaining
---