title: Siteswap validator

text:
# Question
Title: Siteswap validator
Siteswap is a notation for juggling patterns.

The other siteswap puzzle is great and it explains siteswap in greater detail than here. This puzzle is meant to be a bit simpler! Numberphile recently interviewed Colin Wright which helped develop the notation. The part at ~16min will be useful for this challenge. Another resource which may be useful for wrapping your hear around siteswap if you have not used it before: In your head

Below is the diagram(courtesy of wikipedia) for valid throws with 3 balls and a max height of a throw of 5. A valid siteswap ends at the same position as it started.

A valid siteswap for the case we are interested in is defined as follows: In the diagram above choose a starting node and then follow the arrows and write down the number attached to the arrow. If you end up on the same node as you started then the number you have written down is a valid siteswap, otherwise it is not valid.

### Challenge

Take a number as input and output a truthy value if it is a valid siteswap for juggling with 3 balls with a max height of 5, otherwise output a falsy value. (No multiplex throws are allowed)

### Examples

```
Input             Output
------------------------
3                  True
3333333333         True
3342               True
441                True
5                  False
225225220          False
332                False

```

# Answer
# Python 2, ~~204~~ ~~195~~ ~~188~~ ~~174~~ ~~149~~ 144 bytes

```
lambda s:any(i==reduce(lambda C,c:int('40WW75W5AA47WW07W4WW54A0WWAA70A5WAA123896W'.replace('W','A'*3)[C::11][int(c)],16),s,i)for i in range(10))

```

Try it online!
> 2 votes

---
Tags: code-golf
---


title: I am greater than you!

text:
# Question
Title: I am greater than you!
Write a function or program that given a **list** of **non negative** integers, arranges them such that they form the largest possible number.

**INPUT**

```
[50, 2, 1, 9]

```

**OUTPUT**

```
95021

```

---

**INPUT**

```
0

```

**OUTPUT**

```
0

```

---

**INPUT** (Interesting one)

```
[7, 76]

```

**OUTPUT**

```
776

```

**RULES**

* standard loopholes apply.
* Depending on your language you can use `int(32)` / `int(64)` or any other numeric datatype. *(Please append the chosen type to your answer)*
* take a **list** as Input
* you choose the behavior on empty input

**GL**

# Answer
# 05AB1E, 3 bytes

```
œJà

```

Try it online!
> 6 votes

# Answer
# Python 2, ~~85~~ ~~80~~ ~~77~~ ~~72~~ 70 bytes

```
lambda l:''.join(sorted(map(str,l),key=lambda i:i+i[-1]*max(l))[::-1])

```

Try it online!

Sorts the numbers lexicographically, but each number is padded with its last digit.

This means that 'shorter' numbers (string-wise) can be larger than 'longer' numbers:

Example:

Input: `[76, 7]`

Each number gets padded with its last digit: `['76666..','7777..']`

Sorted (descending): `['7777..',76666..']`, which gives `[7, 76]`

Joining the result gives: `776`
> 9 votes

# Answer
# Jelly, 4 bytes

```
Œ!VṀ

```

## Explanation

```
       Input: list [1, 4, 5, 21, 4]
Œ!     Generate all permutations of input list
  V    Eval those lists as Jelly code: every sublist is joined and interpreted as int
   Ṁ   Pick the highest

```

Try it online!
> 5 votes

# Answer
# Brachylog, 5 bytes

```
pᶠcᵐ⌉

```

Try it online!

### Explanation

```
pᶠ       Find all permutations of the list
  cᵐ     Concatenate each permutation into an integer
    ⌉    Take the biggest one

```
> 4 votes

# Answer
## JavaScript (ES6), 40 bytes

```
a=>a.sort((a,b)=>``+b+a-(``+a+b)).join``

```

Sorts the numbers by their ordering when concatenated, and joins the result.
> 4 votes

# Answer
# Ohm v2, 4 bytes

```
ψJì↑

```

**Explanation:**

```
ψ      All possible permutations
 J     join sublists
  ì    convert to int
   ↑   get maximum

```

Try it online!
> 4 votes

# Answer
# Japt, 8 bytes

```
ñ!îL w q

```

Test it online!

Look ma, no permutation built-in!

### Explanation

```
ñ           Sort the input as if each item
 !îL          were repeated to 100 chars. (!îL -> LîX for each item X, L = 100)
     w      Reverse.
       q    Join into a single string.
            Implicit: output result of last expression

```

Repeating each item to length 100 works because while `'7' < '76'`, `'7777...' > '7676...'`, and no number could possibly be length 100 when converted to a string.
> 3 votes

# Answer
# Actually, 11 bytes

```
;l@╨⌠εj≈⌡MM

```

Try it online!

Explanation:

```
;l@╨⌠εj≈⌡MM
;l@╨         all permutations of input
    ⌠εj≈⌡M   concatenate each permutation
          M  maximum

```
> 2 votes

# Answer
# Java (OpenJDK 8), ~~113~~ ~~220~~ 87 bytes

```
l->l.stream().map(i->""+i).sorted((i,j)->(j+i).compareTo(i+j)).reduce((i,j)->i+j).get()

```

Try it online!
> 2 votes

# Answer
# Pyth, 9 bytes

```
eSmsjkd.p

```

**Try it here!**

**or:**

```
eSsMjLk.p
jkeojkN.p

```

---

* `.p` \- Generate all the permutations.
* `msjkd` \- Map on the above with the following function that takes `d` as a variable:

+ `jkd` \- Concatenate the integers into a single string.
    + `s` \- Convert to integer.
* `S` \- Sort the input.
* `e` \- Get the last element.
> 2 votes

# Answer
# Octave / MATLAB, 65 bytes

```
@(x)max(cellfun(@(s)str2num(s(s>32)),cellstr(num2str(perms(x)))))

```

Try it online!
> 2 votes

# Answer
# Japt, ~~13~~ 7 bytes

```
á m¬ñ Ì

```

Try it here.

-6 thanks to ETHproductions.
> 2 votes

# Answer
# K (oK), 18 bytes

**Solution:**

```
,/x@>(|/#:'x)#'x:$

```

Try it online!

**Examples:**

```
> ,/x@>(|/#:'x)#'x:$50 2 1 9
"95021"
> ,/x@>(|/#:'x)#'x:$7 76
"776"

```

**Explanation:**

```
,/x@>(|/#:'x)#'x:$ / the solution
                 $ / convert to string, 50 2 1 9 -> "50","2","1","9"
               x:  / store in x
     (      )      / do this together
        #:'x       / count (#:) each (') x, "50","2","1","9" -> 2 1 1 1
      |/           / max over, 2 1 1 1 -> 2,
             #'    / take each parallel, 2#'"50","2","1","9" -> "50","22","11","99"
    >              / return sorted indices (descending), "50","22","11","99" -> 3 0 1 2
  x@               / apply these indices to x, "50","2","1","9" -> "9","50","2","1"
,/                 / flatten, "9","50","2","1" -> "95021"

```
> 2 votes

# Answer
# C#, 113 Bytes

It's not very short, but hey, it's still C# we're talking about.

```
int F(List<int>n)=>n.Max(i=>{var l=new List<int>(n);l.Remove(i);return int.Parse(""+i+(l.Count>0?""+F(l):""));});

```

Formatted:

```
int F (List<int>n) => n.Max (i =>
{
    var l = new List<int> (n);
    l.Remove (i);
    return int.Parse ("" + i + (l.Count > 0 ? "" + F (l) : ""));
});

```

It simply recursively tries all possible permutations of the input and returns the largest one.

It uses a 32 Bit integer as input and output numerical datatype.

If anybody has an idea on how to improve this solution, feel free to comment.
> 2 votes

# Answer
## Ruby, ~~48~~ ~~41~~ 36 bytes

Similar implementation to others, generates all permutations and takes the max. Shame that "permutation" needs to be spelled out in full . . .

```
f=->l{l.permutation.map(&:join).max}

```

Calling it:

```
f.call([50, 2, 1, 9])
 => "95021"

f.call([7, 76])
 => "776"

```

Or

```
f.([50, 2, 1, 9])
 => "95021"

```
> 2 votes

# Answer
# Gaia, 4 bytes

```
f$¦⌉

```

Try it online!
> 1 votes

# Answer
# Perl 5, 27 bytes

```
join"",sort{"$b$a"cmp$a.$b}

```

TIO
> 1 votes

# Answer
# J, ~~29~~ 25 bytes

~~\[:\>./-.&' '&.":"1@(A.~i.@!@#)~~

```
[:>./,&.":/"1@(A.~i.@!@#)

```
* ~~`-.&' '&.":"1` smashes a list of numbers together to produce a single number. `-.` is "set minus" and `":` is format, so `":` turns, eg, the list `7 76` into the single string (aka list of chars) into `'7 76'`, and `-.&' '` removes the spaces from that string. Since `":` was applied using Under `&.` the inverse is automatically applied at the end, turning the single string-now-without-spaces back into a number.~~
* `,&.":/"1` smashes a list of numbers together to produce a single number.
* `(A.~i.@!@#)` all permutations of the list
* `>./` maximum of

Try it online!
> 1 votes

# Answer
# bash, 96 bytes

```
f(){ local l g p=$1;shift&&{ for i;{ (($i$p>$p$i))&&l+=\ $i||g+=\ $i;};echo $(f $l)$p$(f $g);};}

```

Try It Online
> 1 votes

# Answer
# Python 2, ~~90~~ ~~86~~ 80 bytes

```
lambda l:max("".join(map(str,x))for x in permutations(l))
from itertools import*

```

Try it online!

*-4 bytes thanks to FlipTack*

*-6 bytes thanks to i cri everytim*

I believe this can be golfed a ton, but I don't really know how. Stupid type conversions added a ton of bytes.
> 1 votes

# Answer
# Groovy, 41 bytes

```
{it.permutations().max{it.join()}.join()}

```

---

If commands were 3 bytes in groovy instead of a full word I halve the size lol:

```
{it.p().max{it.j()}.j()}

```
> 1 votes

# Answer
# MATLAB/Octave, ~~65~~ 62 bytes

```
@(n)max(str2num(sprintf([repmat('%d',size(n)) 10],perms(n)')))

```

Try it online!

Anonymous function which takes an array as an input, and spits out an integer representing the largest number that can be made.

Permutations are found, then the result is formatted to a 2D array where each line contains only the digits from the values in a given permutation in order. This is done by `sprintf` with enough `%d` markers to absorb the whole permutation. The result is then converted back to an array of integers where each line becomes its own value. The maximum from this array is returned.

---

* Save 3 bytes using `size(n)` instead of `1,numel(n)` in the `repmat()` call

Note: This was developed completely independently from the other Octave answer.
> 1 votes

# Answer
# Mathematica, 57 bytes

```
Max[FromDigits[Join@@IntegerDigits/@#]&/@Permutations@#]&

```

Try it online!
> 0 votes

# Answer
# Matlab, 135 53 bytes

New Solution:

```
a=input('')
b=sprintf('%d', a)
c=sort(b,'descend')

```

Explanation: It takes a user matrix input, then separates it into digits, and finally orders those digits from greatest to least.

Old Solution:

```
a=input('');
b=sprintf('%d',a) - '0';
c=[];b=sort(b,'descend');
for i=1:size(b,2)
 c(i)=b(i);
end
for y=1:size(c,2)
 e(y)=num2str(c(y))
end

```

Explanation: First it takes a user input, then separates all of the numbers into individual digits. The %d in sprintf essentially converts the numbers in the string, which is necessary for sorting into each digit (afaik). I tried simply doing num2str(a) but that leaves a space between each number. From there, it is just a matter of sorting and arranging the numbers with proper formatting. The actual code has a lower byte count because it has no semi-colons and everything on one line.
> 0 votes

---
Tags: code-golf, math, number, array
---


title: Demolish a string!

text:
# Question
Title: Demolish a string!
# Challenge

Given a string input, output the demolished version of it.

# The Process

```
P
r      Pr       r
o       o       o
g       g       g
r       r       r      rogr         r
a  ->   a  ->   a  ->     a  ->     a  ->           ->           ->           ->           ->
m       m       m         m         m
m       m       m         m         m         mmar         m
i       i       i         i         i         i            i           mi           m
n       n       n         n        gn        gn           gn           gn           gni         mgni
g       g      Pg        Pg      roPg      roPg         roPgmar      roPgmar      roPgmar      roPgmar

```
1. Place the string vertically.
2. Select a random integer between `1` and `(height of the column of characters) - 1` and a random direction (left or right).
3. Rotate that number of characters in that direction (if those spaces are unoccupied go to step 4; if not, go back to step 2).
4. Let those characters fall due to gravity.
5. Repeat until the height of the column of characters is at most `1` larger than the height of the columns next to it (i.e. it becomes impossible to further demolish ("steps 2-4") the column).
6. If there is another column of characters that is more than `1` character taller than one or more of its surrounding columns (i.e. demolish-able), repeatedly demolish that column until it is no longer demolish-able. If there are multiple demolish-able columns, completely demolish the tallest column (if there are multiple tallest columns, completely demolish the leftmost one).
7. Repeat until all columns are no longer demolish-able.

If there are space characters in the input, demolish those first, all at once.

```
C
o

d
e  ->     oC  ->         ->  ...
       de
G        G          G
o        o          o
l        l          l
f        f        defoC

```

## Rules

* Standard loopholes are forbidden.
* Trailing and leading newlines are allowed.
* Your program may either print or return a string/equivalent.
* The output must be non-deterministic (unless the input is not demolish-able).

This is , so the submissions with the smallest byte counts in their languages win!

# Answer
> 5 votes
# Python 2, ~~622~~ ~~595~~ ~~573~~ ~~552~~ ~~542~~ ~~534~~ ~~527~~ ~~520~~ 515 bytes

```
from random import*
s=input()
r=range
R=choice
Z=len
L=h=Z(s)
a=[[]for _ in'  '*-~h]
S=s[::-1].split()
X=-1,1
for w in S[1:]:
 for i in r(Z(w)):a[h-~i*R(X)]+=w[i]
a[h]+=S[0]
while L:
 H=[map(Z,a[c-1:c+2])+[c]for c in r(1,h-~h)];D=L=[(min(n,m)-C,i)for n,C,m,i in H if~-C>min(n,m)]
 while D:
	_,c=min(L);n,C,m=map(Z,a[c-1:c+2]);D=X[n+2>C:1+(C-1>m)]
	if D:
	 d=R(D);l=R(r(1,C-[0,m,n][d]));w,a[c]=a[c][-l:],a[c][:-l]
	 for i in r(l):a[c-~i*d]+=w[i]
for l in zip(*[l+[' ']*max(H)[1]for l in a if l])[::-1]:print`l`[2::5]

```

Try it online!

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


title: Sequence of integer square roots

text:
# Question
Title: Sequence of integer square roots
Let's define a sequence of integer square roots. First, a(1) = 1. Then, a(n) is the smallest positive integer **not seen before** such that

```
sqrt(a(n) + sqrt(a(n-1) + sqrt(... + sqrt(a(1)))))

```

is an integer. Some examples:

a(2) is 3 because it's the smallest integer such that `sqrt(a(2) + sqrt(a(1))) = sqrt(a(2) + 1)` is integer, and 3 hasn't occured in the sequence before.

a(3) is 2 because it's the smallest integer such that `sqrt(a(3) + sqrt(a(2) + sqrt(a(1)))) = sqrt(a(3) + 2)` is integer, and 2 hasn't occured in the sequence before.

a(4) is 7 because `sqrt(a(4) + 2)` is integer. We couldn't have a(4) = 2 because 2 already occured in our sequence.

Write a program or function that given a parameter *n* returns a sequence of numbers a(1) to a(n).

The sequence starts 1,3,2,7,6,13,5, ....

Source of this sequence is from this Math.SE question.

---

A plot of the first 1000 elements in the sequence:

# Answer
# Python 2, 80 bytes

```
s=[]
exec'x=q=1\nwhile(x in s)+q%1:x+=1;q=(v+x)**.5\nv=q;s+=x,;'*input()
print s

```

Try it online!
> 4 votes

# Answer
# Python 2, 87 bytes

```
t,=s=1,
for n in~-input()*s:
 while(n in s)+(t+n)**.5%1:n+=1
 s+=n,;t=(t+n)**.5
print s

```

Try it online!

-3 thanks to Mr. Xcoder.
-5 thanks to ovs.
> 3 votes

# Answer
# Haskell, ~~103~~ 87 bytes

Horribly inefficient, but does not rely on floating point arithmetic. Here `a(x) = sqrt(f(x)+a(x-1))` is a helper sequence, that simplifies the computation.

```
a 0=0
a x=[k|k<-[1..],m<-[k^2-a(x-1)],m>0,notElem m$f<$>[1..x-1]]!!0
f x=(a x)^2-a(x-1)

```

Try it online!
> 3 votes

# Answer
# MATL, ~~30~~ 27 bytes

```
lXHiq:"`@ymH@+X^1\+}8MXHx@h

```

Try it online! Or see a graphical display (takes a while; times out for inputs exceeding approximately `60`).

### Explanation

```
l          % Push 1. This is the array that holds the sequence, initialized to
           % a single term. Will be extended with subsequent terms
XH         % Copy into clipboard H, which holds the latest result of the
           % "accumulated" square root
iq:"       % Input n. Do the following n-1 times
  `        %   Do...while
    @      %     Push interaton index k, starting at 1. This is the candidate
           %     to being the next term of the sequence
    y      %     Push copy of array of terms found so far
    m      %     Ismbmer? True if k is in the array
    H      %     Push accumulated root
    @+     %     Add k
    X^     %     Square root
    1\     %     Modulo 1. This gives 0 if k gives an integer square root
    +      %     Add. Gives nonzero if k is in the array or doesn't give an
           %     integer square root; that is, if k is invalid.
           %   The body of the do...while loop ends here. If the top of the
           %   stack is nonzero a new iteration will be run. If it is zero that
           %   means that the current k is a new term of the sequence
  }        %   Finally: this is executed after the last iteration, right before
           %   the loop is exited
    8M     %     Push latest result of the square root
    XH     %     Copy in clipboard K
    x      %     Delete
    @      %     Push current k
    h      %     Append to the array
           % End do...while (implicit)
           % Display (implicit)

```
> 3 votes

# Answer
# Mathematica, 104 bytes

```
(s=f={i=1};Do[t=1;While[!IntegerQ[d=Sqrt[t+s[[i]]]]||!f~FreeQ~t,t++];f~(A=AppendTo)~t;s~A~d;i++,#-1];f)&

```

Try it online!

The sequence of the square roots is also very interesting...
and outputs a similar pattern

> 1,2,2,3,3,4,3,5,3,6,4,4,5,4,6,5,5,6,6,7,4,7,5,7,6,8,4,8,5,8,6,9,5,9,6,10,5,10,6,11,5,11,6,12,6,13,6,14,7,7,8,7,9,7,10,7,11,7,12,7,13,7,14,8,8,9,8,10...

also here are the differences of the main sequence
> 3 votes

# Answer
# Python 2, ~~117~~ ~~115~~ ~~112~~ ~~102~~ ~~99~~ 87 bytes

```
t,=r=1,;exec"x=1\nwhile(t+x)**.5%1or x in r:x+=1\nr+=x,;t=(t+x)**.5;"*~-input();print r

```

Try it online!

Used the `t=(t+x)**.5` logic from Erik's answer
> 2 votes

# Answer
# , ~~138~~ ~~105~~ 99 bytes

```
function(n){for(i in 1:n){j=1
while(Reduce(function(x,y)(y+x)^.5,g<-c(T,j))%%1|j%in%T)j=j+1
T=g}
T}

```

Try it online!

*-33 bytes using Tfeld's clever `sqrt()%%1` trick in the while loop*

*-6 bytes using T instead of F*

### original answer, 138 bytes:

```
function(n,l={}){g=function(L)Reduce(function(x,y)(y+x)^.5,L,0)
for(i in 1:n){T=1
while(g(c(l,T))!=g(c(l,T))%/%1|T%in%l)T=T+1
l=c(l,T)}
l}

```

Try it online!
> 2 votes

# Answer
# JavaScript (ES7), ~~89~~ ~~82~~ ~~77~~ 76 bytes

```
i=>(g=k=>(s=(++n+k)**.5)%1||u[n]?g(k):i--?[u[n]=n,...g(s,n=0)]:[])(n=0,u=[])

```

### Demo

```
let f =

i=>(g=k=>(s=(++n+k)**.5)%1||u[n]?g(k):i--?[u[n]=n,...g(s,n=0)]:[])(n=0,u=[])

console.log(JSON.stringify(f(10)))
```

### Formatted and commented

```
i => (                             // given i = number of terms to compute
  u = [],                          // u = array of encountered values
  g = p =>                         // g = recursive function taking p = previous square root
    (s = (++n + p) ** .5) % 1      // increment n; if n + p is not a perfect square,
    || u[n] ?                      // or n was already used:
      g(p)                         //   do a recursive call with p unchanged
    :                              // else:
      i-- ?                        //   if there are other terms to compute:
        [u[n] = n, ...g(s, n = 0)] //     append n, set u[n] and call g() with p = s, n = 0
      :                            //   else:
        []                         //     stop recursion
  )(n = 0)                         // initial call to g() with n = p = 0

```
> 2 votes

# Answer
# Husk, 21 bytes

```
!¡oḟȯΛ±sFo√+Som:`-N;1

```

Try it online!

### How?

```
!¡oḟȯΛ±sFo√+Som:`-N;1    Function that generates a list of prefixes of the sequence and indexes into it
                   ;1    The literal list [1]
 ¡                       Iterate the following function, collecting values in a list
  oḟȯΛ±sFo√+Som:`-N        This function takes a prefix of the sequence, l, and returns the next prefix.
                `-N      Get all the natural numbers that are not in l.
            Som:         Append l in front each of these numbers, generates all possible prefixes.
    ȯΛ±sFo√+               This predicate tests if sqrt(a(n) + sqrt(a(n-1) + sqrt(... + sqrt(a(1))))) is an integer.
        F                Fold from the left
         o√+             the composition of square root and plus
       s                 Convert to string
    ȯΛ±                  Are all the characters digits, (no '.')
  oḟ                     Find the first list in the list of possible prefixes that satisfies the above predicate
!                        Index into the list

```
> 2 votes

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


title: Tips for golfing in Wierd

text:
# Question
Title: Tips for golfing in Wierd
What tips do you have for golfing in Wierd? Tips for golfing other languages don't seem to help one golf Wierd programs so I'm looking for ideas that can be applied to code golf problems that are specific to Weird - especially if it helps me reduce the size of this answer at "Hello, World!"

# Answer
**Don't forget about self modifying code**

As Dennis showed in https://codegolf.stackexchange.com/a/142785/24812 a loop can be much shorter than a linear program and that there are clever ways to exit the loop. The spec makes it clear that a 90 degree angle allows you to choose one of two different directions at runtime. Dennis showed that you could modify the program at runtime - with amazing results.
> 1 votes

---
Tags: code-golf, tips
---


title: Boo! A Halloween Code Golf Challenge

text:
# Question
Title: Boo! A Halloween Code Golf Challenge
Write a program that takes an input string of length 2 or more characters and adds the string  `~BOO!~`  (that string has a leading and ending space) in a *uniformly random* spot in the string that is not on either end.

---

**Disallowed sample inputs**: `2` or  (an empty input)

**Disallowed sample outputs**: `Hello ~BOO!~`  or  `~BOO!~ Hello` for the input `Hello`

**Sample input**: `Hello, World!`

**Sample outputs**: `Hel ~BOO!~ lo, World!` or `Hello, Worl ~BOO!~ d!`

---

This is code golf, fellas. Standard rules apply. Shortest code in bytes wins.

---

Congratulations to **Dennis** for having the shortest, spookiest program! Happy Halloween!

# Answer
# Pyth, ~~19~~ 18 bytes

```
j" ~BOO!~ "cz]OtUz

```

*Thanks to @Jakube for golfing off 1 byte!*

Try it online.

### How it works

```
                    (implicit) Store the input in z.
                Uz  Compute [0, ... len(z)-1].
               t    Remove the first element.
              O     Select an integer, pseudo-randomly.
             ]      Wrap it in an array.
           cz       Split the input string at that point.
j" ~BOO!~ "         Join the split string, using " ~BOO!~ " as separator.

```
> 6 votes

# Answer
# GML, 91 bytes

```
s=get_string("","")
show_message(string_insert(" ~BOO!~ ",s,irandom(string_length(s)-2)+1);

```

Simple enough - get a string, insert the substring into it, output the string. Done.
> 4 votes

# Answer
# Python 3, 60 bytes

```
s=input();n=1+hash(s)%(len(s)-1);print(s[:n],'~BOO!~',s[n:])

```

Note:

The modulo of `hash()` will be uniformly distributed over the length of the string. If you think that's bending the rules, note that because of python's hash randomization, this is *actually* random: repeated executions with the same input will give different results.
> 3 votes

# Answer
# CJam, 20 bytes

```
l_,(mr)/(" ~BOO!~ "@

```

Try it online

Explanation:

```
l       Get input.
_,      Calculate length.
(       Decrement, since the number of possible positions is 1 less than length.
mr      Generate random number between 0 and length-2
)       Increment, giving random number between 1 and length-1.
/       Split. Note that this splits repeatedly, but this will not do any harm.
        We will only really use the first split.
(       Peel off the first fragment after the split.
" ~BOO!~ "
        Push the magic string.
@       Rotate the list with the remaining fragments to the top.

```
> 2 votes

# Answer
## Pip, 19 bytes

Takes input from the command-line. If the input has spaces or other special characters, it will need to be placed in quotes.

```
a^@1RR#aJ" ~BOO!~ "

```

Explanation:

```
a                    Command-line arg
 ^@                  Split at index...
   1RR#a             ...random integer >= 1 and < length(a) (Python randrange)
        J" ~BOO!~ "  Join on that string and autoprint

```
> 2 votes

# Answer
## Python 3, 79 bytes

```
from random import*;s=input();n=randint(1,len(s)-1);print(s[:n],'~BOO!~',s[n:])

```

Try it online

Pretty self-explanatory - read a string, pick a random integer between 1 and the length of the string, and print the string with `' ~BOO!~ '` inserted.
> 1 votes

# Answer
# C#, 125 bytes

```
using System;class X{static void Main(string[]a){Console.Write(a[0].Insert(new Random().Next(a[0].Length-2)+1," ~BOO!~ "));}}

```

Expanded:

```
using System;
class X
{
    static void Main(string[] a)
    {
        Console.Write(a[0].Insert(new Random().Next(a[0].Length - 2) + 1, " ~BOO!~ "));
    }
}

```

This solution assumes that the string is passed in as the first command-line parameter. This is not usual for C# (stdin is more normal), so I’ve also included a solution that uses normal stdin:

# C#, 139 bytes

```
using System;class X{static void Main(){var x=Console.In.ReadToEnd();Console.Write(x.Insert(new Random().Next(x.Length-2)+1," ~BOO!~ "));}}

```

Expanded:

```
using System;
class X
{
    static void Main()
    {
        var x = Console.In.ReadToEnd();
        Console.Write(x.Insert(new Random().Next(x.Length - 2) + 1, " ~BOO!~ "));
    }
}

```
> 1 votes

# Answer
# Julia, 70 bytes

```
print((s=readline())[1:(r=rand(2:length(s)-2))]," ~BOO!~ ",s[r+1:end])

```

Ungolfed:

```
# Read a line from STDIN
s = readline()

# Define a random integer within the bounds of s
r = rand(2:length(s)-2)

# Print to STDOUT with boo in there somewhere
print(s[1:r], " ~BOO!~ ", s[r+1:end])

```
> 1 votes

# Answer
## APL, 27 bytes

```
{(-⌽' ~BOO!~ ',⍵⌽⍨⊢)?¯1+⍴⍵}

```

APL doesn't have an insert function, so we rotate the string instead.

```
{                          }    ⍝ Monadic function:
                     ?¯1+⍴⍵     ⍝ Place to insert string, let's say it's X
 (                  )           ⍝ Monadic train:
               ⍵⌽⍨⊢            ⍝ Rotate input by X (⊢) to the left
    ' ~BOO!~ ',                 ⍝ Concatenate ' ~BOO!~ '
  -                             ⍝ -X
   ⌽                            ⍝ Rotate that by X to the right

```

**Example input on TryAPL**
> 1 votes

# Answer
# Lua, 75 bytes

```
s=io.read()m=math.random(2,#s/2);return s:sub(1,m).." ~BOO!~ "..s:sub(m,#s)

```
> 1 votes

# Answer
# Perl, 35 bytes

34 bytes code + 1 byte command line

```
$-=rand y///c-2;s/..{$-}\K/~BOO!~/

```

Usage:

```
perl -p entry.pl

```
> 1 votes

# Answer
# MATLAB, 69 bytes

```
i=input('');a=randi(nnz(i)-1,1);disp([i(1:a) ' ~Boo!~ ' i(a+1:end)]);

```

Inserting a string mid string at a given index in MATLAB is costly in terms of bytes. If there was a simple way to do it, I could save a fair amount by moving to an anonymous function, but I can't find one. Ah well.

Basically it gets a random number between 1 and the length of the string minus 1. Then it displays everything up to and including that index, followed by the `~Boo!~`, and then everything after the index to the end.

---

It also works with **Octave**, so you can try it out online here.
> 0 votes

# Answer
# Ruby, 46 bytes

```
$><<gets.insert(rand(1..$_.size-2),' ~BOO!~ ')

```
> 0 votes

# Answer
# Vitsy, 19 Bytes

Note that `z` and `Z` were edited today, but not for this challenge.

```
I1-R1+\i" ~OOB~ "zZ
I1-                   Get the length of the input, minus 1
   R                  Push a random number from 0 to the top item of the stack.
    1+                Add one to it - this is now a random number from 1 to input
                      length - 1.
      \i              Get that many items of input.
        " ~OOB~ "     Push ' ~BOO~ ' to the stack.
                 z    Get the rest of the input.
                  Z   Output it all.

```
> 0 votes

# Answer
# Bash/GNU, 61 bytes

```
echo $1|sed "s/.\{`shuf -i1-$((${#1}-1)) -n1`\}/\0 ~BOO!~ /"

```

Takes input string as argument
> 0 votes

# Answer
# JavaScript, 79

```
r=Math.random()*((x=prompt()).length-1)+1;x.substr(0,r)+" ~BOO!~ "+x.substr(r);

```

It's for the browser console; have fun just popping that in.
> 0 votes

# Answer
# Chaîne, 23 bytes

```
{il1-R1+`} ~BOO!~ {<$/}

```
> 0 votes

# Answer
# Java 8, ~~158~~ 154 bytes

```
interface M{static void main(String[]a){int i=a[0].length()-2;System.out.println(a[0].substring(0,i=1+(i*=Math.random()))+" ~BOO!~ "+a[0].substring(i));}}

```

Try it here.

EDIT: Only now reading program instead of the default function/program in the challenge description.. So added the bordercode with interface and main method.

If a function would be allowed it would be (**~~99~~ 95 bytes**)

```
s->{int i=s.length()-2;return s.substring(0,i=1+(i*=Math.random()))+" ~BOO!~ "+s.substring(i);}

```

Try it here.

**Explanation:**

```
s->{                        // Method with String as both parameter and return-type
  int i=s.length()-2;       //  The length of the input - 2
  return s.substring(0,i=1  //  Return the first part of the input from index 0 to 1
    +(i*=Math.random()))    //    + a random integer between 0 and length-2
   +" ~BOO!~ "              //   appended with the literal " ~BOO!~ "
   +s.substring(i);         //   appended with the rest of the input-String
}                           // End of method

```
> 0 votes

# Answer
# TeaScript, 30 bytes

```
xh(j=N(xn-1)+1)+' ~BOO!~ '+xS(j)

```

Very straight forward.
> -1 votes

# Answer
## CJam, 19 bytes

```
q_,mr)/(" ~BOO!~ "@

```
> -1 votes

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


title: What's that number in Shortlex?

text:
# Question
Title: What's that number in Shortlex?
Most computers store integers in binary, but output them in decimal. However, decimal is just one representation, we just happen to find it convenient.

This challenge is to write some code to output an integer value in ***shortlex decimal***.

What's that?
http://en.wikipedia.org/wiki/Shortlex\_order

Shortlex takes the length of the sequence of digits as the primary signifier of value. The sequence, starting from an empty string representing zero, is...

```
ε,0,1,...,8,9,00,01,...98,99,000,001,...,998,999,0000,...

```

(Think of Excel columns, but using only the decimal digits.)

Write a program or function that accepts an integer and returns a string corresponding to the shortlex-decimal representation of that integer as described above.

Test values:

0 → "" (Empty string)
1 → "0"
10 → "9"
11 → "00"
42 → "31"
100 → "89"
800 → "689"
1060 → "949"
10270 → "9159"
100501 → "89390"

# Answer
# JavaScript (ES6) 42 ~~74~~

```
n=>(n-~(n+'').replace(/./g,8)+'').slice(1)

```

**Test in FireFox console**

```
;[0,1,10,11,42,100,800,1060,10270,100501]
.forEach(x => console.log(x +" -> '" + S(x) + "'"))

```

*Output*

```
0 -> ''
1 -> '0'
10 -> '9'
11 -> '00'
42 -> '31'
100 -> '89'
800 -> '689'
1060 -> '949'
10270 -> '9159'
100501 -> '89390'

```

**How did I think of this?**

Given a fixed number of digits, the output sequence is simply ascending, so there is a fixed delta between input and output. Have a look:

```
  1..10 -> 0..9 (delta -1)
 11..110 -> 00..99 (delta -11)
111..1110 -> 000..999 (delta -111) mmm there's a pattern here...

```

But the leading 0s are difficult to manage, so I have a standard trick, add a first digit and work modulo (that is, cut the first digit in output). Then -1-\> +9, -11 -\> +89, -111 -\> +889 and so on.
Last step: I don't care what the first digit is, so there is no need to check if the iinput number is \< or \> than 111... (honestly I found this by trial and error)

**Test**

```
var F=
n=>(n-~(n+'').replace(/./g,8)+'').slice(1)

function update()
{
  var i=+I.value
  O.textContent = F(i)
}

update()
```

```
<input id=I value=99 type=number oninput='update()'><pre id=O></pre>
```
> 34 votes

# Answer
# Marbelous ~~177~~ ~~173~~ 170

```
@0@6000000@5
}0&0&0&0&0
>0@6&3
\\--\/&2
@0/\@4\/&1!!
@4@1..@2@5@3
IIIIIIIIIIII
FF&1FF&2FF&3
@1OO@2OO@3OO
:I
}1..}10001F7
=9&1++..&1&0
&0}0&1&0{1{1
{>\/{0//
:O
}0
+Z
+C
{0

```

It works for only for values under 256 since Marbelous is an 8 bit language.

## How it works

Marbelous is a 2D language with values represented by 8 bit marbles that fall down one cell on each tick unless some device prevents them from falling down. This Marbelous program consists of 3 boards; let's start with the easiest one:

```
:O
}0
+Z
+C
{0

```

`:O` is the name of the board (to be precise, O is the name and : tells the interpreted that this line is a name. By giving boards a name, other boards can call on them `}0` is an input device, this can be seen as an argument of this function. This cell will get replaced by an input marble (value) when the function gets called. `+Z` adds 35 to any marble that passes over it and lets it fall through. `+C` does the same but only adds 12. `{0` is an output cell, when a marble reaches this cell, the function will exit and return the value in this output device.

So all together, this board takes one value and then adds 47 to it. For us this means it turns any single digit number into the ascii code of the digit -1 (this will of course also work for 10).

```
:I
}1 .. }1 00 01 F7
=9 &1 ++ .. &1 &0
&0 }0 &1 &0 {1 {1
{> \/ {0 //

```

This board is looking a bit more complicated. You should be able to identify `:I` as the name of the board and have spotted some input and output devices. You'll notice that we have two different input devices, `}0` and `}1`. This means this function takes 2 inputs. You'll also notice that there are two instances of the `}1` device. Upon calling the function, both of these cells will contain the same value. The `}0` input device is directly above a `\/` device, this acts as a trashcan and removes any marble that falls upon it immediately.

Let's have a look at what happens to one of the marbles put into the board by the `}1` input devices:

```
}1
=9 &1
&0
{>

```

It will fall down on the first tick and hit the `=9` device. This compares the value oif the marble to 9 and lets the marble fall through if the statement `=9` evaluates to through. The marble gets pushed to the right if not. `&0`and `&1` are synchronizers. They hold on to marbles that fall onto them until all other `&n`synchronizers are filled as well. As you can expect, this will conditionally trigger different behaviour on some other part of the board.

```
}1 00 01 F7
++ .. &1 &0
&1 &0 {1 {1
{0 //

```

If I tell you that `++` is an incrementor, you should already be able to tell what the different synchronizers will be filled with. The left `&1` will contain the input value `}1` \+ 1, the `&0` next to it will contain 0 (`00` is a language literal, represented in hexadecimal). The second `&1` will contain the value 1 and the right `&0` gets filled with an `F7`, which subtracts 9 from a value since addition in Marbelous is modulo 256.

`//` is a deflector device, which pushes any marble to the left instead of letting it fall down.

Putting this all together gives you this: if the marble in `}1` is 9, the `&0` synchronizers get filled. This will cause the value 0 to fall into the `{0` output and `F7` (or -9) into the `{1` output. If `}1` is not 9, `{0` will be filled with `}1` \+ 1 and `{0` will contain 1. There is also a `{>` device, this is a special output that outputs a marble next to a board in stead of underneath it. This will get filled with `}1` if it equals 9.

```
@0 @6 00 00 00 @5
}0 &0 &0 &0 &0
>0 @6 &3
\\ -- \/ &2
@0 /\ @4 \/ &1 !!
@4 @1 .. @2 @5 @3
II II II II II II
FF &1 FF &2 FF &3
@1 OO @2 OO @3 OO

```

Okay, now for the big one. This board does not have an explicit name, since it is the main board of the file. Its implicit name is `Mb`. You should be able to recognize some cells. There is an input device, some language literals (`00` and `FF`). There are some synchronizers and there's a deflector. lets step through this piece by piece.

```
@0 @6
}0 &0
>0 @6
\\ --
@0 /\ @4

```

So the input value (the command line input since this is the main board) starts at the second cell from the top where `}0` is located. It will fall down and reach the `>0` device, which is another comparison device. any marble larger than 0 falls through, any other marble gets pushed to the right. (since Marbelous variables are unsigned, only exactly 0 will get pushed to the right). This zero value marble will then hit the `@6` device. This is a portal and transports the marble to another corresponding portal, in this case right above it. The 0 marble will then reach the `&0` synchronizer and trigger some things elsewhere.

If the marble is not 0, it falls down, gets deflected to the right by `\\` hits `--` which decrements it by one and then falls onto `/\`, a cloner. This device takes a marble and outputs one copy of it to the right and one to the left. The left one will be taken upwards to the other `@0` where the marble will go through the same sequence again. The left one will be taken elsewhere. This gives us a loop, which decrements the command line input once per loop and triggers some behaviour on every loop until it reaches 0. It then triggers some other behaviour.

Let's have a look at what happens with the marble pushed into `@4` on each loop.

```
@4 @1 .. @2 @5 @3
II II II II II II
FF &1 FF &2 FF &3
@1 OO @2 OO @3 OO

```

There are 3 language literals here (`FF`), which will immediately fall into portals. These portals will take them to three of the `II` devices. `II` refers to the board `:I` we defined further down the file. Since `:I` has 2 distinct input devices, it's representation on another board must be 2 cells wide. Since we have 6 cells containing `II`, we cam tell we have 3 instances of this function on the board.

The `FF` (or 256 or -1 if you will) marbles will sit in the input cells of the `:I` function waiting untill there are enough input marble sto start the function (one more that is). That's where the `@4` portal comes in. A copy of the decremented command line input falls through there on each loop. This will trigger the leftmost `:I` board. Initialy with the values 256 (or -1) and whatever the command line input was -1. The left marble will be put into the `}0` devices of the `:I` board and the right one into the `}1`. If you recall what this board did, you'll be able to tell what result this has. It will output an incremented version of the right input on the left output (and it turns a 9 into a 0, not 10) and outputs either 1 or -9 on the right.

The incremented value will be taken right back to the right input cell by a portal, and the value on the right falls into a synchronizer. If a synchronizer is already holding a marble, the two marbles will collide. Colliding marbles get added together modulo 256. So the values in the synchroizers will do the folowing: They start out empty, then turn to 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, and then to 1 again (since 247 gets added modulo 256).

You also might remember that a marble gets output to the right when the input value loops back to 0. Since the `:I` boards are right next to each other, thsi will trigger the board to the right once. This will fill the three synchronizers with values that are one higher than they should be to be a shortlex representation of the command line input, by the time this has looped down to 0.

You might also remember that the `:O` function turns a value into the ascii value of the digit that represents the value -1. The output of these `OO` cells will then fall off the board, which prints their corresponding ascii chars to STDOUT.

```
00 00 00 @5
&0 &0 &0
&3
\/ &2
   \/ &1 !!
      @5

```

So what happens when the command line input marble reaches 0 and fills that `&0` synchronizers? well, a few 0 value marbles fall down and trigger the three synchronizers that are holding the digits (+ 1) of the shortlex number at the bottom of the board. `&3` gets triggered first, since it contain the most significant digit, then comes `&2` followed by `&1`. This marble then gets teleported to the other `@5` device before eventually hitting the `!!` cell, which terminates the board.
> 13 votes

# Answer
# CJam, ~~14~~ 11 bytes

```
l40f-Ab)s1>

```

Try it online.

### How it works

This approach is heavily based on edc65's answer (with his explicit permission):

```
" Read a line L from STDIN. ";

l

" edc65's answer now forms an integer N by replacing each digit in L by an 8 and computes
  L - ~N = L + N + 1. Instead of adding L and N, we subtract 40 from each char code of L.
  Since the char code of the digit `D` is `D + 48`, this basically adds 8 to each digit.  ";

40f-

" Turn the resulting array into an integer by considering its elements a base 10 number.
  This is implemented as A ↦ A[-1] + 10 * A[-2] + 100 * A[-3] + ⋅⋅⋅, so it won't choke
  on digits greater than the base.                                                        ";

Ab

" Increment the integer on the stack to complete the calculation of L + N + 1.            ";

)

" Push the integers string representation and discard its first character.                ";

s1>

```

### Example run

```
$ for i in 0 1 10 11 42 100 800 1060 10270 100501
> do echo $i: $(cjam <(echo 'l40f-Ab)s1>') <<< $i)
> done
0:
1: 0
10: 9
11: 00
42: 31
100: 89
800: 689
1060: 949
10270: 9159
100501: 89390

```
> 12 votes

# Answer
# Python 2 (38)  (43)

```
f=lambda n:n*'_'and f(~-n/10)+`~-n%10`

```

No character substitution, just arithmetic.

**Ungolfed:**

```
def f(n):
    if n==0: return ''
    else: return f((n-1)//10) + str((n-1)%10)

```

I don't have a good reason why the recursion works, I just fit this pattern to the list of values. If you changed each `n-1` to `n`, you'd get the regular digit representation.

For golfing, I use `~-n` to compute `n-1` with higher precedence than `/10` or `%10`, saving on parens. The `n*'_'` is just to produce the empty string when `n=0` and any other string otherwise. The `'_'` can be any string for this purpose.
> 6 votes

# Answer
# Ruby, ~~70~~ ~~68~~ ~~66~~ ~~64~~ 57 bytes

```
f=->n{i=-1;n-=10**i while n>=10**i+=1;i<1?'':"%0#{i}d"%n}

```

Defines a function to be called like `f[42]`. Here is the rough breakdown of the algorithm:

* Treat `0` separately.
* Subtract powers of 10 until the next power of 10 doesn't fit into the number any more.
* Turn the number into a string padded with zeroes on the left.

Credits for the idea of using a format string go to Falko!

---

Alternatively, using edc65's approach:

```
f=->n{"#{n-~n.to_s.tr('^.',?8).to_i}"[1..-1]}

```

That's **45 bytes** and I'm only including it, because I'm not beating him with it. ;)
> 4 votes

# Answer
# Haskell, 67 bytes

```
n('9':x)='0':n x
n(c:x)=succ c:x
n""="0"
f x=reverse$iterate n""!!x

```

this solution basically adds 1 the given number of times, in shortlex notation.

usage:

```
>f 9
"8"
>f 100
"89"

```
> 3 votes

# Answer
# CJam, 16 bytes

```
li_)9*,{`1>}%_&=

```

Try it online. Requires at least O(n) time and memory, so leave 100501 to the offline interpreter...

### How it works

The basic idea behind this approach is to compute at least N shortlex decimals in their natural order and discard all but the Nth. Not very efficient, but short.

```
li                " Read an integer N from STDIN.                                   ";
  _)9*            " Push M := (N + 1) * 9.                                          ";
      ,           " Push A := [ 0 1 ... M - 1 ].                                    ";
       {   }%     " For each I ∊ A:                                                 ";
       {`1>}%     " Push its string representation and discard the first character. ";
             _&   " Remove duplicates from the resulting array.                     ";
               =  " Retrieve the Nth element.                                       ";

```

### Example run

```
$ for i in 0 1 10 11 42 100 800 1060 10270 100501
> do echo $i: $(cjam <(echo 'li_)9*,{`1>}%_&=') <<< $i)
> done
0:
1: 0
10: 9
11: 00
42: 31
100: 89
800: 689
1060: 949
10270: 9159
100501: 89390

```
> 3 votes

# Answer
# Bash+coreutils, 27 bytes

Port of @edc65's clever answer, with @Dennis's improvements:

```
cut -b2-<<<$[$1-~${1//?/8}]

```

### Output:

```
$ for n in 0 1 10 11 42 100 110 111 800 1060 1110 1111 10270 100501; do echo "./shortlex.sh $n = \"$(./shortlex.sh $n)\""; done
./shortlex.sh 0 = ""
./shortlex.sh 1 = "0"
./shortlex.sh 10 = "9"
./shortlex.sh 11 = "00"
./shortlex.sh 42 = "31"
./shortlex.sh 100 = "89"
./shortlex.sh 110 = "99"
./shortlex.sh 111 = "000"
./shortlex.sh 800 = "689"
./shortlex.sh 1060 = "949"
./shortlex.sh 1110 = "999"
./shortlex.sh 1111 = "0000"
./shortlex.sh 10270 = "9159"
./shortlex.sh 100501 = "89390"
$

```

---

*Previous answer:*

# Bash+coreutils, 71 54 bytes

Here's a slightly different way to do it:

```
jot -w%x $1$1|tr 0-9a a0-9|grep -P ^\\d+$|sed $1!d 2>-

```
* `jot` outputs increasing hexadecimal integers
* `tr` converts this to (0,1,...,8,9,b,...f,0a,00,01,...,99,9b,...,ff,0aa,...,000,...)
* `grep` simply filters all lines containing digits to give (0,1,...,8,9,00,...,99,000....)
* `sed` deletes all but the nth line
* STDERR is redirected to a throwaway file '-' so that we simply get the empty string when 0 is passed in (`sed` counts line numbers starting at 1, so errors if 0 is passed)
* Because we are filtering numbers out with `grep`, we need to generate more base 11 integers with `seq`/`dc` than the input number. Repeating the digits of n is more than sufficient.

Note that once the shortlex number is printed, `seq` continues generating numbers up to `$1$1`, which slow especially for larger input numbers - O(n²), I think. We can speed up by having the `seq` quit immediately after printing at the cost of 7 bytes:

```
jot -w%x $1$1|tr 0-9a a0-9|grep -P ^\\d+$|sed -n $1{p\;q} 2>-

```

There is no speed requirement in the question, so I'm going with the shorter version for my main answer.
> 3 votes

# Answer
# Python 2 - ~~84, 70~~ 66

```
n=input()
i=0
while n>=10**i:n-=10**i;i+=1
print"%%0%dd"%i%n*(i>0)

```

**Alternative approach (same length):**

```
n=input()
k=len(`9*(n+1)/10`)
print"%%0%dd"%k%(n-int('1'*k))*(n>0)

```
> 2 votes

# Answer
# Python 3, 107 characters

This didn't end up winning but I thought it was clever:

```
def G():yield'';yield from(r+c for r in G()for c in'0123456789')
S=lambda n:list(zip(range(n+1),G()))[n][1]

```

I define a generator for the entire sequence in 64 characters. Unfortunately, I have to go through some contortions to get the nth element of the generator... if only I could do `S=lambda n:G()[n]`.
> 2 votes

# Answer
# Pyth, 12

Another port of @edc65's answer, who is the clear winner (IMO):

```
t`+hQv*l`Q\8

```

### Test package (Thanks to @DigitalTrauama):

```
$ for n in 0 1 10 11 42 100 110 111 800 1060 1110 1111 10270 100501; do echo "shortlex.pyth $n = \"$(pyth programs/shortlex.pyth <<< $n)\""; done
shortlex.pyth 0 = ""
shortlex.pyth 1 = "0"
shortlex.pyth 10 = "9"
shortlex.pyth 11 = "00"
shortlex.pyth 42 = "31"
shortlex.pyth 100 = "89"
shortlex.pyth 110 = "99"
shortlex.pyth 111 = "000"
shortlex.pyth 800 = "689"
shortlex.pyth 1060 = "949"
shortlex.pyth 1110 = "999"
shortlex.pyth 1111 = "0000"
shortlex.pyth 10270 = "9159"
shortlex.pyth 100501 = "89390"

```

### Explanation:

```
Q = eval(input())             Implicit.
t`                            All but the first digit of
  +hQ                         Q+1 +
   v                          eval(
    *l`Q                      len(repr(Q)) *
     \8                       "8"

```
> 2 votes

# Answer
# Java 8, 60 bytes

```
n->(n-~new Long((n+"").replaceAll(".","8"))+"").substring(1)

```

Port of @edc65's amazing JavaScript (ES6) answer, since I doubt it can be done shorter in an arithmetic way in Java.

Try it here.
> 1 votes

# Answer
# Haskell, 57 bytes

```
((g=<<[0..])!!)
g 0=[""]
g n=[c:s|c<-['0'..'9'],s<-g$n-1]

```

Try it online!

Constructs an infinite list of shortlex numbers and indexes into it for the answer. `g n` constructs the nth "generation" of numbers by prepending the next digit in front of each of the numbers in the previous generation.
> 1 votes

# Answer
# 05AB1E, 7 bytes

Uses *edc65's* replace by 8 trick

```
8sg×+>¦

```

Try it online!

**Explanation**

```
8          # push 8
 sg×       # repeat it len(input) times
    +      # add to input
     >     # increment
      ¦    # discard the first digit

```
> 0 votes

# Answer
# Jelly, 5 bytes

```
ḃ⁵ịØD

```

Try it online!

I'm very new to Jelly, so if you can improve this, please comment!

Explanation:

```
ḃ⁵ịØD   Main link.
ḃ       Convert to bijective base ...
 ⁵      10.
  ị     Each number (1 - 10) is converted to the character at its index in the string...
   ØD   “0123456789” (digits)

```

(According to r.e.s.'s comment above, the problem is equivalent to convert the number to bijective base 10)
> 0 votes

# Answer
# Excel, 37 bytes

Using @edc65's approach:

```
=REPLACE(REPT(8,LEN(A1))+A1+1,1,1,"")

```
> 0 votes

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


title: Detect the Zeroless Numbers

text:
# Question
Title: Detect the Zeroless Numbers
Zeroless numbers are numbers that do not contain **0** as one of their decimal digits.

Given an integer **K**, return the **K**th zeroless number. **K** will be non-negative if you choose **0**-indexing, or positive if you choose **1**-indexing instead. Note that this is OEIS A052382.

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

## Test cases

1-indexed:

```
1 -> 1
2 -> 2
9 -> 9
10 -> 11
16 -> 17
100 -> 121

```

0-indexed:

```
0 -> 1
1 -> 2
8 -> 9
9 -> 11
15 -> 17
99 -> 121

```

# Answer
# Jelly, 3 bytes

```
ḃ9Ḍ

```

Try it online!

### How it works

```
ḃ9Ḍ  Main link. Argument: n (1-based index)

ḃ9   Convert n to bijective base 9.
  Ḍ  Convert the result from base 10 to integer.

```
> 28 votes

# Answer
# Python 2, 35 bytes

```
f=lambda n:n and~-n%9+1+f(~-n/9)*10

```

Try it online!

One indexed.
> 13 votes

# Answer
# Python 2, 50 bytes

```
n=input()
i=0
while n:i+=1;n-=1-('0'in`i`)
print i

```

Try it online!
> 5 votes

# Answer
# Actually, 10 bytes

```
⌠$'0@cY⌡╓N

```

Try it online!

Explanation:

```
⌠$'0@cY⌡╓N
⌠      ⌡╓N  nth number (starting with i=0) where
 $            string representation of i
  '0@cY       does not contain 0

```
> 5 votes

# Answer
# Haskell, 31 bytes

```
(filter(all(>'0').show)[0..]!!)

```

Try it online!

---

**32 bytes**

```
(l!!)
l=(+).(10*)<$>0:l<*>[1..9]

```

Try it online! One-indexed.

---

**33 bytes**

```
(l!!)
l=0:[10*a+b|a<-l,b<-[1..9]]

```

Try it online!

---

**34 bytes**

```
(l!!)
l=0:do a<-l;take 9[10*a+1..]

```

Try it online!

---

**37 bytes**

```
f 0=0
f n=mod(n-1)9+1+10*f(div(n-1)9)

```

Try it online!
> 5 votes

# Answer
## Perl 5, 20 bytes

**19 bytes code + 1 for `-p`.**

Uses 1-indexing.

```
0while$_-=++$\!~0}{

```

Try it online!
> 5 votes

# Answer
# Javascript (ES7), 23 Bytes

```
f=n=>n&&n--%9+10*f(n/9)

```

Explanation:

```
f=n=>                  //=> syntax
     n&&n--%9          //only with 0 0s
             +10*f(n/9)//^^

```
> 5 votes

# Answer
# Python 2, 50 bytes

```
n=input();v=0
while n:v+=1;n-=min(`v`)>'0'
print v

```

Try it online!
> 4 votes

# Answer
# PowerShell, 40 bytes

```
param($a)(1..(2*$a)|?{$_-notmatch0})[$a]

```

Try it online!

Take input `$a`, then construct a range from `1` to `2*$a`. Pull out those elements that regex do `-notmatch` `0`, and then take the `$a`th one thereof. Output is implicit.
> 4 votes

# Answer
# Haskell, 31 bytes

This is zero-indexed

```
(filter(all(>'0').show)[1..]!!)

```

Try it online!
> 4 votes

# Answer
# MATL, ~~16~~ ~~13~~ 14 bytes

*-2 bytes thanks to Luis Mendo*

```
E:!tV48-!XA)G)

```

Try it online!

Explanation:

```
(implicit input)
E                   % double
 :                  % 1:top of stack (so [1, 2, ..., 2n])
  !t                % transpose and dup
    V               % cast to chars
     48-            % subtract 48 (maps numbers to digits)
        !           % transpose
         XA         % Check each column if All are true (nonzero)
           )        % index into array (so we are left with zeroless numbers)
            G)      % paste input and index; TOS is the nth element.
(implicit output)

```
> 4 votes

# Answer
# Jelly, 5 bytes

```
DȦ$#Ṫ

```

-2 bytes thanks to Dennis

# Explanation

```
DȦ$#Ṫ  Main link; takes input from STDIN
   #   nfind; get first n matches starting from 0
  $    Get numbers that are zeroless:
D      Digits
 Ȧ     Are all truthy
    Ṫ  Tail; get last element

```

Try it online!
> 3 votes

# Answer
# 05AB1E, 5 bytes

```
µNSĀP

```

Try it online!

**Explanation**

```
µ       # loop over N until input matches are found
 NS     # split N into list of digits
   Ā    # check if trueish (not zero)
    P   # product

```

or with Dennis's base conversion trick

# 05AB1E, 3 bytes

```
9.h

```

Try it online!
> 3 votes

# Answer
# 6502 machine code (C64), 124 bytes

```
00 C0 20 FD AE 20 6B A9 A2 05 A9 00 85 FB 85 FC 85 FD A0 10 06 FB 06 14 26 15
90 02 E6 FB A5 FB C9 09 90 04 E9 09 85 FB 26 FC 26 FD 88 D0 E5 A5 FB 95 61 CA
A5 FD 85 15 A5 FC 85 14 D0 CC A5 15 D0 C8 E8 86 FE B5 61 D0 1E A9 09 95 61 86
9E CA B4 61 F0 11 D6 61 D0 0D E4 FE D0 04 E6 FE B0 05 95 61 CA 10 EB A6 9E E8
E0 06 D0 D9 18 A6 FE B5 61 69 30 20 D2 FF E8 E0 06 D0 F4 60

```

**Online demo**

**Usage:** `sys49152,[n]`, e.g. `sys49152,100`. `n` is **1**-indexed.

Valid values are in the range \[1,63999\].

### Explanation:

The common approach to save bytes is to do it iteratively / recursively checking for decimal `0` digits -- this doesn't save bytes on the C64 because there's not even a division instruction available -- just converting to base 9 and adjusting the digits gives a shorter result (still with the need to hand-code a long binary division). Here's the commented disassembly:

```
         00 C0       .WORD $C000        ; load address
.C:c000  20 FD AE    JSR $AEFD          ; consume comma
.C:c003  20 6B A9    JSR $A96B          ; read 16bit number
.C:c006  A2 05       LDX #$05           ; index of last digit in result
.C:c008   .divide:
.C:c008  A9 00       LDA #$00           ; initialize some variables
.C:c00a  85 FB       STA $FB            ; to zero ...
.C:c00c  85 FC       STA $FC
.C:c00e  85 FD       STA $FD
.C:c010  A0 10       LDY #$10           ; repeat 16 times for division
.C:c012   .div_loop:
.C:c012  06 FB       ASL $FB            ; shift remainder left
.C:c014  06 14       ASL $14            ; shift dividend ...
.C:c016  26 15       ROL $15            ; ... left
.C:c018  90 02       BCC .div_nobit     ; highest bit set?
.C:c01a  E6 FB       INC $FB            ; then add one to remainder
.C:c01c   .div_nobit:
.C:c01c  A5 FB       LDA $FB            ; compare remainder ...
.C:c01e  C9 09       CMP #$09           ; ... to 9 (divisor)
.C:c020  90 04       BCC .div_nosub     ; if greater or equal 9 (divisor)
.C:c022  E9 09       SBC #$09           ; subtract 9 from remainder
.C:c024  85 FB       STA $FB
.C:c026   .div_nosub:
.C:c026  26 FC       ROL $FC            ; shift quotient left, shifting in
.C:c028  26 FD       ROL $FD            ; carry if remainder was >= 9
.C:c02a  88          DEY                ; loop counting
.C:c02b  D0 E5       BNE .div_loop      ; and repeat
.C:c02d  A5 FB       LDA $FB            ; load remainder
.C:c02f  95 61       STA $61,X          ; store in current output digit
.C:c031  CA          DEX                ; decrement digit index
.C:c032  A5 FD       LDA $FD            ; copy quotient ...
.C:c034  85 15       STA $15
.C:c036  A5 FC       LDA $FC            ; ... to dividend
.C:c038  85 14       STA $14
.C:c03a  D0 CC       BNE .divide        ; if not zero yet
.C:c03c  A5 15       LDA $15
.C:c03e  D0 C8       BNE .divide        ; repeat division by 9
.C:c040  E8          INX
.C:c041  86 FE       STX $FE            ; remember index of first digit
.C:c043   .adjust_loop:
.C:c043  B5 61       LDA $61,X          ; load digit
.C:c045  D0 1E       BNE .nonine        ; if it's zero, must be changed to 9
.C:c047  A9 09       LDA #$09
.C:c049  95 61       STA $61,X
.C:c04b  86 9E       STX $9E            ; save current index and go back
.C:c04d  CA          DEX
.C:c04e   .sub_loop:
.C:c04e  B4 61       LDY $61,X          ; examine previous digit
.C:c050  F0 11       BEQ .sub_done      ; zero? nothing more to subtract
.C:c052  D6 61       DEC $61,X          ; decrement previous digit
.C:c054  D0 0D       BNE .sub_done      ; not zero -> done
.C:c056  E4 FE       CPX $FE            ; are we at the first digit?
.C:c058  D0 04       BNE .sub_next      ; no: go on
.C:c05a  E6 FE       INC $FE            ; first digit now zero, so increment
.C:c05c  B0 05       BCS .sub_done      ; and done with subtraction
.C:c05e   .sub_next:
.C:c05e  95 61       STA $61,X          ; store 9 to this digit
.C:c060  CA          DEX                ; and go to previous
.C:c061  10 EB       BPL .sub_loop      ; repeat
.C:c063   .sub_done:
.C:c063  A6 9E       LDX $9E            ; load saved digit index
.C:c065   .nonine:
.C:c065  E8          INX
.C:c066  E0 06       CPX #$06           ; reached last digit?
.C:c068  D0 D9       BNE .adjust_loop   ; no -> repeat
.C:c06a  18          CLC
.C:c06b  A6 FE       LDX $FE            ; start output at first digit
.C:c06d   .out_loop:
.C:c06d  B5 61       LDA $61,X          ; load digit
.C:c06f  69 30       ADC #$30           ; add character code `0`
.C:c071  20 D2 FF    JSR $FFD2          ; output character
.C:c074  E8          INX                ; next
.C:c075  E0 06       CPX #$06           ; last digit done?
.C:c077  D0 F4       BNE .out_loop      ; if not, repeat
.C:c079  60          RTS

```
> 3 votes

# Answer
# Pyth,  ~~9~~  8 bytes

```
e.f*FjZT

```

**Verify all the test cases.**

## Explanation

```
e.f*FjZT   ~ Full program.

 .f        ~ Collect the first Q matches. Uses a variable Z.
     jZT   ~ Decimal digits of Z.
   *F      ~ Product. Can be replaced by .A (all) - Basically checks if all are ≥ 1.
e          ~ End. Get the last element.

```
> 2 votes

# Answer
# QBIC, 32 bytes

```
[:|p=p+1≈instr(!p$,@0`)|p=p+1}?p

```

## Explanation

```
[:|     FOR a = 1 to <input>
p=p+1   increase p (starts as 0) by 1
≈       WHILE
 instr  the index in
 (!p$     the string-cast of p
 ,@0`)|   of the string '0' is non-zero
 p=p+1    skip this number in the zero-less sequence
}       WEND, NEXT
?p      PRINT p

```
> 2 votes

# Answer
# Mathematica, 55 bytes

```
(s=t=1;While[s<=#,If[DigitCount[t++,10,0]<1,s++]];t-1)&

```

Try it online!
> 2 votes

# Answer
# Perl 6, 24 bytes

```
{(grep {!/0/},^∞)[$_]}

```

Try it online!

0-indexed.
> 2 votes

# Answer
# Python 2, ~~50~~ 49 bytes

*1 byte off thanks to @Mr.Xcoder*

```
lambda n:[k for k in range(2*n)if('0'in`k`)<1][n]

```

0-based.

Try it online!
> 1 votes

# Answer
# C, 70 bytes

```
i,j,k;f(n){for(i=0;n--;n+=!k)for(k=j=++i;j;j/=10)k=j%10?k:0;return i;}

```

1-indexed

Try it online!

# C (gcc), 65 bytes

```
i,j,k;f(n){for(i=0;n--;n+=!k)for(k=j=++i;j;j/=10)k=j%10?k:0;n=i;}

```

1-indexed

Try it online!
> 1 votes

# Answer
## JavaScript (ES6), ~~28~~ 27 bytes

```
f=n=>n&&--n%9+1+10*f(n/9|0)
```

```
<input type=number min=1 oninput=o.textContent=f(this.value)><pre id=o>
```

Edit: Saved 1 byte by switching to a numeric result (effectively porting @xnor's Python answer).
> 1 votes

# Answer
# Excel VBA, 57 Bytes

Anonymous VBE immediate window function that takes input, `n` from range `[A1]` and outputs the `n`th `0`-indexed zeroless number to the VBE immediate window.

```
For i=1To[A1]:j=j+1:While InStr(1,j,0):j=j+1:Wend:Next:?j

```
> 1 votes

# Answer
# AWK, 39 bytes

```
{for(;c<$1;)c=index(++i,0)?c:c+1;$0=i}1

```

Since this is `AWK` `1`-indexing seemed appropriate.

Try it online!
> 1 votes

# Answer
# Java 8, 45 bytes

```
int c(int n){return n>0?--n%9+1+c(n/9)*10:0;}

```

1-indexed

Port of *@xnor*'s Python 2 answer.

**Explanation:**

Try it here.

```
int c(int n){  // Method with integer as both parameter and return-type
  return n>0?  //  If `n` is larger than 0:
    --n%9      //   Return `(n-1)%9
    +1         //    + 1
    +c(n/9)    //    + recursive call with `(n-1)/9`
     *10       //      multiplied by 10
   :           //  Else:
    0;         //   Return 0
}              // End of method

```
> 1 votes

# Answer
# C# (.NET Core), ~~68~~ 63 bytes

-8 bytes thanks to @raznagul.

```
k=>{int i=0;for(;k>0;)if(!(++i+"").Contains("0"))k--;return i;}

```

Try it online!

---

Don't really want to use this, since it's just a C# port of an existing answer.

**C# (.NET Core), 45 bytes**

```
int c(int n){return n>0?--n%9+1+c(n/9)*10:0;}

```

Try it online!
> 1 votes

# Answer
# Jq 1.5, 76 bytes

```
[.,0]|until(.[0]<1;.[1]+=1|if"\(.[1])"|contains("0")then. else.[0]-=1end)[1]

```

Expanded

```
  [.,0]                           # initial state (n, v)
| until(.[0]<1;                   # until we've found n'th number
     .[1]+=1                      #   increment v
   | if "\(.[1])"|contains("0")   #   if v contains 0
     then .                       #   leave state alone
     else .[0]-=1                 #   otherwise decrement n
     end
  )[1]                            # return n'th number found

```

Try it online!
> 1 votes

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


title: Repeat the Nth elements

text:
# Question
Title: Repeat the Nth elements
We haven't had a question for a while (5 days to be precise), so let's go for one.

Given a string `s` and a positive integer `n`, take every `n`th element of `s`, repeat it `n` times, and put it back into `s`.

For example, if `n = 3` and `s = "Hello, World!"`, every third character is `Hl r!`. You then repeat each character `n` times to produce `HHHlll rrr!!!`. You then replace the original letters with the repeated versions to produce the final product of `HHHellllo, Worrrld!!!`

You are to accomplish this task in the shortest code possible in your language!

# Rules

* This is a so the shortest code in bytes wins
* `n` is guaranteed to be smaller than the length of `s` and greater than 0
* The first character of `s` is where the `n`th characters are taken from, and is always repeated `n` times
* `s` will only consist of printable ASCII (code points `0x20 (space)` to `0x7E (~)`)

# Test cases

```
s, n => output

"Hello, World!", 3 => "HHHellllo,   Worrrld!!!"
"Code golf", 1 => "Code golf"
"abcdefghijklm", 10 => "aaaaaaaaaabcdefghijkkkkkkkkkklm"
"tesTing", 6 => "ttttttesTingggggg"
"very very very long string for you to really make sure that your program works", 4 => "vvvvery    veryyyy verrrry loooong sssstrinnnng foooor yoooou toooo reaaaally    makeeee surrrre thhhhat yyyyour    proggggram    workkkks"

```

# Answer
# Jelly, 3 bytes

```
Ḣs×

```

Input is taken as **s, n**.

Try it online!

### How it works

```
Ḣs×  Main link. Argument: s, n

Ḣ    Head; yield s.
     This pops the list, leaving [n] as the main link's argument.
 s   Split s into chunks of length n.
  ×  Multiply each chunk by [n], repeating its first element n times.

```
> 10 votes

# Answer
# Jelly,  ~~6~~  5 bytes

-1 byte thanks to leaky Nun (use Python's string multiplication.)

```
×Jm¥¦

```

A full program, accepting two command line arguments, the string and the number, and printing the result.

**Try it online!**

### How?

```
×Jm¥¦ - Main link: list of characters, s; number, n   e.g. ['g','o','l','f','e','r'], 2
    ¦ - sparse application:
   ¥  - ...to indices: last two links as a dyad:
 J    -      range of length of s                          [1,2,3,4,5,6]
  m   -      modulo slicing by n (every nth entry)         [1,3,5]
×    - ...action: multiply  ["gg",'o',"ll",'f',"ee",'r']
      - implicit print                                 >>> ggollfeer

```
> 8 votes

# Answer
# JavaScript (ES6), 46 bytes

Takes input in currying syntax `(s)(n)`.

```
s=>n=>s.replace(/./g,(c,i)=>c.repeat(i%n?1:n))

```

### Test cases

```
let f =

s=>n=>s.replace(/./g,(c,i)=>c.repeat(i%n?1:n))

console.log(f("Hello, World!")(3))
console.log(f("Code golf")(1))
console.log(f("abcdefghijklm")(10))
console.log(f("tesTing")(6))
console.log(f("very very very long string for you to really make sure that your program works")(4))
```
> 5 votes

# Answer
# C# (.NET Core), ~~84~~ 82 bytes

```
n=>m=>{var s="";for(int i=0;i<n.Length;)s+=new string(n[i],i++%m<1?m:1);return s;}

```

Try it online!
> 4 votes

# Answer
# 05AB1E, ~~8~~ 7 bytes

-1 byte thanks to @Emigna

```
ôʒć²×ì?

```

Try it online!

### Explanation

```
ôʒć²×ì?    Arguments s, n  ("Hello, World!", 3)
ô          Split s into pieces of n  (["Hel", "lo,", ...])
 ʒ         Filter (used as foreach)
  ć          Extract head  ("Hel" -> "el", "H" ...)
   ²×ì       Repeat n times and prepend  ("el", "H" -> "HHHel" ...)
      ?      Print without newline

```
> 4 votes

# Answer
# Proton, 44 bytes

```
s=>n=>"".join(s[i]*(i%n?1:n)for i:0..len(s))

```

Try it online!
> 3 votes

# Answer
# Python 2, 54 53 bytes

**Edit:** Saved 1 byte thanks to @Rod

```
f=lambda x,n,i=0:x[i:]and[1,n][i%n<1]*x[i]+f(x,n,i+1)

```

Try it online!
> 3 votes

# Answer
## Alice, 25 bytes

```
/
KI /!Iw?&.?t&O?&wWOI.h%

```

Try it online!

### Explanation

```
/         Switch to Ordinal.
I         Read first line of input (i.e. n).
/         Switch to Cardinal.
!         Convert input to its integer value and store it on the tape.
I         Read first character from input string.
w         Push current IP address onto the return address stack. This
          effectively marks the beginning of the main loop.

  ?         Retrieve n.
  &.        Duplicate current character n times (once more than we need,
            but who cares about a clean stack...).
  ?t        Retrieve n and decrement.
  &O        Output n-1 copies of the current character.
  ?         Retrieve n.
  &w        Push the current IP address onto the return address stack n
            times. This marks the beginning of a loop that is executed n
            times.

    W         Discard one copy of the return address from the stack,
              effectively decrementing the loop counter.
    O         Output the last character. On the first iteration, this is
              the final copy of the repeated character, otherwise it's just
              the single character we read on the last iteration.
    I         Read a character for the next iteration.
    .h%       Compute c % (c+1) on that character, which is a no-op for
              for valid characters, but terminates the program at EOF when
              c becomes -1.

K         Jump to the address on top of the return address stack. As long
          as there are still copies of the address from the inner loop, we
          perform another iteration of that, otherwise we jump back to the
          beginning of the outer loop.

```
> 3 votes

# Answer
# , ~~82~~ ~~76~~ 75 bytes

```
function(s,n)cat(rep(S<-el(strsplit(s,'')),c(n,rep(1,n-1))+!seq(S)),sep='')

```

Try it online!

A function; takes a string `s` and an integer `n`, and prints the repeated version to stdout.

Explanation:

```
function(s,n){
 S <- el(strsplit(s,""))                  # characters
 r     <- c(n,rep(1,n-1))                 # [n, 1, 1,...,1], length n
 repeats <- r+!seq(S)                     # extends R to length of S
 cat(rep(S, repeats), sep="")             # print out
}

```

# , 55 bytes

```
function(S,n)cat(rep(S,c(n,rep(1,n-1))+!seq(S)),sep="")

```

Try it online!

Same algorithm as above, but with `S` taken as a list of individual characters.
> 3 votes

# Answer
# PowerShell, 51 bytes

```
param($a,$n)-join($a|%{($_,("$_"*$n))[!($i++%$n)]})

```

Try it online!

Takes input as a `char`-array `$a` and the number `$n`. Loops through `$a` and each iteration either outputs the current letter `$_` or the current letter multiplied by `$n`, based on an index into a pseudo-ternary. The index chooses between the two based off of incrementing `$i` and then modulo `$n`. Those letters are then `-join`ed back together and the string is left on the pipeline; output is implicit.
> 2 votes

# Answer
# Python 3, ~~53~~ 52 bytes

```
f=lambda x,n,i=0:x[i:]and n**(i%n<1)*x[i]+f(x,n,i+1)

```

Try it online!
> 2 votes

# Answer
# Japt, 8 bytes

```
ËùDV*EvV

```

Test it online!

### Explanation

```
 Ë    ùDV*EvV
UmDE{DùDV*EvV}   Ungolfed
                 Implicit: U = s, V = n
UmDE{        }   Replace each char D and (0-)index E in U by this function:
          EvV      Take 1 if the index is divisible by V; 0 otherwise.
        V*         Multiply this by V. This gives V for every Vth index; 0 for others.
     DùD           Pad D with itself to this length. This gives V copies of D for every
                   Vth index; 1 copy of D for others.
                 Implicit: output last expression

```

I have to credit the idea to use `ù` to @Shaggy's answer here. I don't know that I ever would have thought of it myself...
> 2 votes

# Answer
# J, 17 bytes

```
(#@]$[,1#~<:@[)#]

```
* `(...) # ]` everything in parens creates the string for J's built in "copy" verb. So, eg, if the left argument is 3, it creates the string `3 1 1` repeated as needed to equal the number of characters in the right arg `]`, which contains the string. Which is to say, `#` solves the problem directly, assuming we can give it the correct left argument: `4` should be `4 1 1 1` repeated, and so on.
* Examining `#@]$[,1#~<:@[`, we see it uses J's shape verb `$` in the middle -- that's the main verb of this phrase...
* To the left of `$` is `#@]`, meaning the length `#` of the right arg `]`.
* To the right of `$` is `[,1#~<:@[`, a 5 verb train. The first train executed is...
* `1#~<:@[`, which means 1 copied `#~` (passive form of copy) one less than `<:` the left arg `[`. This result is passed to the final fork:
* `[, ...` meaning take the left arg, and append the result we just calculated, which is a string of `1`s.

Try it online!
> 2 votes

# Answer
# Perl 5, ~~37~~, 29 +1 (-p) bytes

-8 bytes thanks to Tom's comment.

```
$n=<>;s/./"@-"%$n?$&:$&x$n/ge

```

Try It Online
> 2 votes

# Answer
# Java 8, ~~100~~ 76 bytes

```
s->n->{int i,k=0;for(char c:s)for(i=k++%n<1?n:1;i-->0;)System.out.print(c);}

```

-24 bytes thanks to *@OliverGrégoire*.

**Explanation:**

Try it here.

```
s->n->{                    // Method with char-array and int parameters and no return-type
  int i,k=0;               //  Index-integers
  for(char c:s)            //  Loop (1) over the characters of the input array
    for(i=k++%n<1?         //   If `k` is divisible by the input `n`:
         n                 //    Change `i` to `n`
        :                  //   Else:
         1;                //    Change `i` to 1
        i-->0;)            //   Inner loop (2) from `i` down to 0
      System.out.print(c); //    And print the current character that many times
                           //   End of inner loop (2) (implicit / single-line body)
                           //  End of loop (1) (implicit / single-line body)
}                          // End of method

```
> 2 votes

# Answer
# C# (.NET Core), 61 + 18 = 79 bytes

```
using System.Linq;
n=>m=>string.Concat(n.Select((c,i)=>new string(c,i%m<1?m:1)))

```

Try it online!
> 2 votes

# Answer
# 6502 machine code routine, 50 bytes

```
A0 01 84 97 88 84 9E 84 9F B1 FB F0 20 A4 9F 91 FD C6 97 D0 10 A6 FF CA F0
05 C8 91 FD D0 F8 84 9F A5 FF 85 97 E6 9E A4 9E E6 9F D0 DC A4 9F 91 FD 60

```

This is a position-independent subroutine expecting a pointer to the input string (0-terminated aka C-string) in `$fb`/`$fc`, a pointer to the output buffer in `$fd`/`$fe` and the count (`n`) in `$ff`. It uses simple indexing, so it's limited to a maximum output length of 255 characters (+ 0 byte) due to the 8bit architecture.

**Explanation (commented disassembly):**

```
 .rep:
A0 01       LDY #$01            ; init counter to next repetition sequence
84 97       STY $97
88          DEY                 ; init read and write index
84 9E       STY $9E             ; (read)
84 9F       STY $9F             ; (write)
 .rep_loop:
B1 FB       LDA ($FB),Y         ; read next character
F0 20       BEQ .rep_done       ; 0 -> finished
A4 9F       LDY $9F             ; load write index
91 FD       STA ($FD),Y         ; write next character
C6 97       DEC $97             ; decrement counter to nex rep. seq.
D0 10       BNE .rep_next       ; not reached yet -> next iteration
A6 FF       LDX $FF             ; load repetition counter
 .rep_seqloop:
CA          DEX                 ; and decrement
F0 05       BEQ .rep_seqdone    ; if 0, no more repetitions
C8          INY                 ; increment write index
91 FD       STA ($FD),Y         ; write character
D0 F8       BNE .rep_seqloop    ; and repeat for this sequence
 .rep_seqdone:
84 9F       STY $9F             ; store back write index
A5 FF       LDA $FF             ; re-init counter to next ...
85 97       STA $97             ; ... repetition sequence
 .rep_next:
E6 9E       INC $9E             ; increment read index
A4 9E       LDY $9E             ; load read index
E6 9F       INC $9F             ; increment write index
D0 DC       BNE .rep_loop       ; jump back (main loop)
 .rep_done:
A4 9F       LDY $9F             ; load write index
91 FD       STA ($FD),Y         ; and write terminating0-byte there
60          RTS                 ; done.

```

**Example C64 machine code program using it**:

This is a program in ca65-style assembler for the C64 using this routine (imported as `rep`):

```
REP_IN          = $fb
REP_IN_L        = $fb
REP_IN_H        = $fc

REP_OUT         = $fd
REP_OUT_L       = $fd
REP_OUT_H       = $fe

REP_N           = $ff

.import         rep

.segment "LDADDR"
                .word   $c000

.code
                jsr     $aefd           ; consume comma
                jsr     $ad9e           ; evaluate expression
                sta     REP_IN_L        ; store string length
                jsr     $b6a3           ; free string
                ldy     #$00            ; loop over string
readloop:       cpy     REP_IN_L        ; end of string?
                beq     termstr         ; then jump to 0-terminate string
                lda     ($22),y         ; read next character
                sta     in,y            ; store in input buffer
                iny                     ; next
                bne     readloop
termstr:        lda     #$00            ; load 0 byte
                sta     in,y            ; store in input buffer

                jsr     $b79b           ; read 8bit unsigned int
                stx     REP_N           ; store in `n`
                lda     #<in            ; (
                sta     REP_IN_L        ;   store pointer to
                lda     #>in            ;   to input string
                sta     REP_IN_H        ; )
                lda     #<out           ; (
                sta     REP_OUT_L       ;   store pointer to
                lda     #>out           ;   output buffer
                sta     REP_OUT_H       ; )
                jsr     rep             ; call function

                ldy     #$00            ; output result
outloop:        lda     out,y
                beq     done
                jsr     $ffd2
                iny
                bne     outloop
done:           rts

.bss
in:             .res    $100
out:            .res    $100

```

**Online demo**

**Usage:** `sys49152,"[s]",[n]`, e.g. `sys49152,"Hello, World!",3`

**Important:** If the program was load from disk (like in the online demo), issue a `new` command first! This is necessary because loading a machine program trashes some C64 BASIC pointers.
> 2 votes

# Answer
# Haskell, ~~51~~ 46 bytes

Thanks @Laikoni for saving me 5 bytes!

```
n&s=do(m,c)<-zip[0..]s;c<$[0..(n-1)*0^mod m n]

```

Try it online!

### Explanation/Ungolfed

The operator `c <$ [a..b]` replaces each element of the list `[a,a+1...b]` by `c` \- so it's just a golfed `replicate`:

```
do(m,c)<-zip[0..]s;                                  -- with all (m,c) in the enumerated ([(0,a),(1,b)..]) input string, replace with
                   replicate (1 + (n-1)*0^mod m n) c -- either n or 1 times the character c (note that the list begins with 0, that's where the 1+ comes from)

```
> 2 votes

# Answer
# MATL, ~~10~~ 7 bytes

*-3 bytes thanks to Luis Mendo!*

```
tq:ghY"

```

Try it online!

Takes input as `n` and then `S` as a string/char array.

```
    % (implicit input)
    % stack: n
t   % duplicate
    % stack: n n
q   % decrement
    % stack: n n-1
:   % range
    % stack: n [1 2 ... n-1]
g   % convert to logical (nonzero->1, zero->0)
    % stack: n [1 1 ... 1]
h   % horizontal concatenate
    % stack: [n 1 1 ... 1]
Y"  % run-length decoding, taking the string as first input and recycling
    % the lengths [n 1 1 ... 1] as needed
    % (implicit output as string)

```
> 2 votes

# Answer
# Python 2, 57 bytes

```
lambda s,n:''.join(c*[1,n][i%n<1]for i,c in enumerate(s))

```

Try it online!
> 1 votes

# Answer
# Charcoal, 14 bytes

```
Ｎθ⪫ＥＳ⎇﹪κθι×ιθω

```

Try it online! Link is to verbose version of code. Takes input in the order `n`, `s`.
> 1 votes

# Answer
# , 13 bytes

```
"aDJòylÀpÀll

```

Try it online!

This is a really dumb workaround. `òlhÀälÀlÀ<M-->l` should work, but I can't for the life of me understand why, especially since manually doing `lhÀälÀlÀ<M-->l` repeated a bunch of times *does* work.

Hexdump:

```
00000000: 1822 6144 4af2 796c c070 c06c 6c         ."aDJ.yl.p.ll

```

Explanation:

```
<C-x>               " Decrement the number
       D            " Delete that number...
     "a             "   Into register 'a'
        J           " Remove the blank line
         ò          " Recursively...
          yl        "   Yank the letter under the cursor
            Àp      "   And paste it 'a' times
              Àl    "   Move 'a' times to the right ('l' for right)
                l   "   Move to the right one more time
                    " (implicit) end the loop

```
> 1 votes

# Answer
# Pyth, 12 bytes

```
s*Vzm^Q!d%Uz

```

Try it here.
> 1 votes

# Answer
# Mathematica, 71 bytes

```
""<>s[[i]]~t~If[i~Mod~#2==1,#2,1]~(t=Table)~{i,Tr[1^(s=Characters@#)]}&

```

Try it online!

saved -2 bytes by listening to user202729
> 1 votes

# Answer
# Python 3, 58 bytes

Working on golfing it down.

I know there are already other Python answers, but I thought I'd post this one too seeing as it scores pretty well compared to the others, despite being a full function and not a lambda.

Takes input as function parameters, and prints to `STDOUT`.

```
def f(s,n,i=0):
 for c in s:print(end=[c,c*n][i%n<1]);i+=1

```

Try it online!

For one byte less (57), I coded a lambda, however similar answers have already been posted by other users:

```
lambda s,n:''.join([c,c*n][i%n<1]for i,c in enumerate(s))

```
> 1 votes

# Answer
# Brain-Flak (BrainHack), 122 + 3 (`-A`) = 125 bytes

I am sure this is too long, but I spent quite a while looking and couldn't find any improvements.

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

```

Try it online!
> 1 votes

# Answer
# 05AB1E, ~~12~~ 11 bytes

```
vX‚RNIÖèy×?

```

Try it online!

**Explanation**

```
v             # for each letter in the input string
       è      # index into
 X‚           # the list [input_int,1]
   R          # reversed
    NIÖ       # with letter_index % input_int == 0
        y×    # repeat the current letter this many times
          ?   # print

```
> 1 votes

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

**Solution:**

```
{,/(1|y*~y!!#x)#'x}

```

Try it online!

**Examples:**

```
> {,/(1|y*~y!!#x)#'x}["Hello, World!";3]
"HHHellllo,   Worrrld!!!"
> {,/(1|y*~y!!#x)#'x}["Code golf";1]
"Code golf"
> {,/(1|y*~y!!#x)#'x}["abcdefghijklm";10]
"aaaaaaaaaabcdefghijkkkkkkkkkklm"

```

**Explanation:**

```
{,/(1|y*~y!!#x)#'x} / the solution
{                 } / lambda function with x and y as implicit parameters
   (          )     / do everything in brackets together
            #x      / count x, #"Hello, World!" -> 13
           !        / til, !13 -> 0 1 2 3 4 5 6 7 8 9 10 11 12
         y!         / y modulo, 3!0 1 2 3 4 5 6 7 8 9 10 11 12 -> 0 1 2 0 1 2 0 1 2 0 1 2 0
        ~           / not, ~0 1 2 0 1 2 0 1 2 0 1 2 0 -> 1 0 0 1 0 0 1 0 0 1 0 0 1
      y*            / multiply by y, 3*1 0 0 1 0 0 1 0 0 1 0 0 1 -> 3 0 0 3 0 0 3 0 0 3 0 0 3
    1|              / min of 1 and, 1|3 0 0 3 0 0 3 0 0 3 0 0 3 -> 3 1 1 3 1 1 3 1 1 3 1 1 3
                #'x / take each parallel, 1 2 3#'"abc" -> "a", "bb", "ccc"
 ,/                 / flatten the list, "a", "bb", "ccc" -> "abbccc"

```

**Notes:**

* -4 bytes with different approach
> 1 votes

# Answer
# Excel VBA, 71 Bytes

Anonymous VBE immediate window function that take input from range `[A1:B1]` and outputs to the VBE immediate window.

```
For i=1To[Len(A1)]:[C1]=i:?[Rept(Mid(A1,C1,1),B1^(Mod(C1,B1)=1))];:Next

```
> 1 votes

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


title: Counting in bijective base 62

text:
# Question
Title: Counting in bijective base 62
The task is to generate all the strings from 'a' to '999' including upper case characters like so:

```
'a', 'b', 'c' ... 'y', 'z', 'A', 'B', 'C' ... 'Y', 'Z', '0', '1', 2' ...
'8', '9', 'aa', 'ab', 'ac' ... 'az', 'aA', 'aB' ... 'aZ', 'a0' ... 'a9', 'ba'

```

and so on (filling in the gaps), optionally starting with the empty string.

**Input:**

* The amount of consecutive characters the program has to print up to.

**Output:**

* An array containing each string *OR* one string per line

**Clarifications:**

* The order doesn't matter, you can print uppercase or lowercase letters first if you want.
* The output can return any type of enumerable, doesn't have to be an array specifically, although I doubt printing all the combinations won't be the easiest way to go.
* An input of `3` would print all the string from `'a'` (or `''`) to `'999'`‚ an input of `5` up to `'99999'` and so on.

# Answer
> 13 votes
# Jelly, 7 bytes

```
ØWṖṗR;/

```

This is a monadic link that accepts an integer as input and returns an array of strings.

Try it online!

### How it works

```
ØWṖṗR;/  Main link. Argument: n

ØW       Yield 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_'.
  Ṗ      Remove the last element (underscore).
    R    Range; yield [1, ..., n].
   ṗ     Cartesian product. For each k in the range, this yields the arrays of all
         strings of alphanumeric characters.
     ;/  Concatenate the arrays of strings of each length.

```

# Answer
> 8 votes
## Haskell, 65 bytes

```
a#b=[a..b]
k n=mapM id.('a'#'z'++'A'#'Z'++'0'#'9'<$)=<<(1#)<$>1#n

```

Usage example: `k 3` -\> `["a","b","c",....,"997","998","999"]`.

How it works

```
a#b = [a..b]        -- helper function that builds a list from a to b

        (1#n)<$>    -- map the function (1#), i.e. "build the list from 1 up to"
                1#n -- on the list from 1 to n

                    -- now we have [[1],[1,2],[1,2,3]]

              =<<   -- map over this list (and combine results in a single list)
  (        <$)      -- a function that makes length of input copies of
 'a'#'z'++ ... '9'  -- all characters we need

                    -- now we have [["a..9"],["a..9","a..9"],["a..9","a..9","a..9"]]

mapM id.            -- and make the cartesian product of each sublist

```

# Answer
> 6 votes
## Python, 86 bytes

```
f=lambda n:n*[1]and[x+chr(y)for x in['']+f(n-1)for y in range(128)if chr(y).isalnum()]

```

Outputs a list of non-empty strings. Recursively prepends each alphanumeric character to each output for `n-1` and empty string.

# Answer
> 5 votes
# 05AB1E, ~~9~~ 8 bytes

Code:

```
ƒžj¨Nã€,

```

Explanation:

```
ƒ          # For N in range(0, input + 1), do:
 žj        #   Push predefined literal [a-zA-Z0-9_]
   ¨       #   Remove the last character (the underscore)
    N      #   Push N
     ã     #   Take the Cartesian product, with N repetitions.
      €,   #   For each element in the array, print with a newline

```

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

# Answer
> 5 votes
## JavaScript (Firefox 30-57), 108 bytes

```
f=n=>n?[for(s of['',...f(n-1)])for(c of(t='abcdefghijklmnopqrstuvwxyz')+t.toUpperCase()+'0123456789')s+c]:[]

```

Saved 3 bytes by using toUpperCase. Computing the 62 characters takes me an extra 10 bytes.

# Answer
> 4 votes
# Cinnamon Gum, 15 bytes

```
0000000: 689b b718 05be a345 9c4b c283 d077 de    h......E.K...w.

```

Not short enough, despite this being the exact kind of challenge Cinnamon Gum was made for :(

Compressed by converting from bijective base 96 to base 256. Try it online. Inputs greater than 2 will cause problems on TIO.

## Explanation

This decompresses to the regex `[a-zA-Z0-9]{1,%s}`. The `h` mode then substitutes the input in to `%s` and outputs all strings matching the regex.

# Answer
> 4 votes
# Python 2.7, ~~136~~ 134 bytes

*Thanks to Maltysen and NonlinearFruit for saving 2 bytes*

```
from itertools import*;from string import*;f=lambda n:[''.join(a) for i in range(1,n+1) for a in product(ascii_letters+digits,repeat=i)]

```

Takes `ascii_letters` and `digits` from the string module and uses the Cartesian Product as `product` from itertools to compute all the combinations.

# Output

```
out = f(3)

print out[:10]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

print out[100:110]
['aM', 'aN', 'aO', 'aP', 'aQ', 'aR', 'aS', 'aT', 'aU', 'aV']

print out[-10:]
['990', '991', '992', '993', '994', '995', '996', '997', '998', '999']

```

# Answer
> 4 votes
# Ruby, 82 bytes

Constructs cartesian products of the character set up to the given length. The character set is generated by grabbing all characters between `0` and `z` and filtering out non-word characters and also `_`.

```
->n{a=(?0..?z).grep(/\w/)-[?_];r=[]
n.times{|i|r+=a.product(*[a]*i).map &:join};r}

```

# Answer
> 3 votes
# Pyth - ~~13~~ 12 bytes

*1 bytes saved thanks to @Jakube.*

```
sm^s+rBG1UTh

```

Try it online here.

```
s                    Add up the lists of different lengths
 m          (Q)      Map implicitly over input
  ^     h(d)         Cartesian product of string to implicit lambda var + 1
   s                 Add up list
    ++               Concat up three things
     G               Alphabet
     rG1             Uppercase alphabet
     UT              All digits

```

# Answer
> 3 votes
# Python 2, ~~106~~ 97 bytes

```
from string import*
f=lambda n,r=['']:n and r+f(n-1,[x+y for x in r for y in letters+digits])or r

```

Try it on Ideone.

# Answer
> 2 votes
# MATL, 12 bytes

```
:"3Y24Y2h@Z^

```

This takes a number as input.

**Try it online!**

### Explanation

```
:       % Implicitly take input, say N. Generate range [1 2... N]
"       % For each number in that range
  3Y2   %   Predefined literal: string with all letters, uppercase and lowercase
  4Y2   %   Predefined literal: string with all digits
  h     %   Concatenate horizontally
  @     %   Push number of characters corresponding to current iteration
  Z^    %   Cartesian power. Each result is a row
        % End for each. Implicitly display

```

# Answer
> 1 votes
# , 21 chars / 27 bytes

```
ⒶïⓜᵖɱĬ⟦ᶛ+ᶐ+⩤9⨝],⧺_)ė)

```

`Try it here (Firefox only).`

Nope. Nope. Nope.

# Explanation

```
ⒶïⓜᵖɱĬ⟦ᶛ+ᶐ+⩤9⨝],⧺_)ė) // implicit:
Ⓐïⓜ                    // [...Array(input)].map(($,_)=>...)
    ᵖ                   // push to stack:
     ɱĬ⟦ᶛ+ᶐ+⩤9⨝],⧺_)   // list of n-digit numbers in [a-zA-Z0-9]-ary
                     ė) // formatted into a matrix (no spaces)
                        // implicit stack output, newline-separated

```

# Answer
> 1 votes
# Perl, 113 bytes + whitespace

```
@r="";
for (1..shift) {
  @r = sub {
    map { $c=$_; map $c.$_, @{$_[1]} } @{$_[0]}
  }->(\@r, [0..9, "a".."z", "A".."Z"])
}
map say($_), @r

```

Use "perl -E" on the above, with an argument that's a number. I could probably decently have not counted the last "map say" in the chars count.

# Answer
> 1 votes
## APL, 38 37 bytes

```
{⊃{⍵,,⍺∘.,⍵}/⍵⍴⊂,¨⎕a,⎕d,⍨⎕ucs 96+⍳26}

```

# Answer
> 1 votes
# J, 50 bytes

```
62&(('0123456789',~(,toupper)u:97+i.26){~#~#:i.@^)

```

Half of the bytes, 25 to be exact, are spent generating the letters and digits needed.

# Answer
> 0 votes
# Bash + GNU utilities, 90

```
printf -vs %$1s
eval printf '%s\\n' ${s// /{=,{a..z\},{A..Z\},{0..9\}\}}|sed s/^=*//\;/=/d

```

Input as a command-line parameter. Output is a whitespace-separated list.

Works for inputs upt and including 3. Run out of memory with 4 - the `eval printf` takes an the entire set of 63n elements of the bash expansion.

# Answer
> 0 votes
# Bash + GNU utils, 66

Different (and I think slightly novel) approach to my other answer:

```
dc -e"64 $1^[d2 48^r-P1-d0<m]dsmx"|base64 -w8|sed s_^/*__\;/[+/]/d

```
* `dc` counts down from 248-1 to 248-64n and `P`rints each resulting number as a bytestream (i.e. base 256). If the input is between 1 and 4 inclusive, this is guaranteed to be exactly 6 bytes per number.
* `base64` converts this to base64 output and thus 8 bytes per base64 digit, one per line.
* `sed` strips off leading `/` (base64 digit 63), and then removes any lines containing `+` or `/` (base64 digits 62 and 63). This leaves the required sequence.

# Answer
> 0 votes
# , 73 bytes

```
y='';x=c(letters,LETTERS,0:9);for(i in 1:scan())cat(y<-outer(y,x,paste0))

```

`y` starts off as empty string, `x` as the base case `'a','b','c',...,'8','9'`. `outer` takes each of its input arguments, and applies the function `paste0` to each combination of elements in `y` and `x` which concatenates the strings. `y` saves the result, `cat` prints it, and it iterates through STDIN number of times of doing this.

Try it online!

# Answer
> 0 votes
# Jq 1.5, 97 bytes

```
range(.)as$n|[[range(97;123),range(65;91),range(48;58)]|implode/""|combinations($n+1)]|map(add)[]

```

Expanded

```
  range(.) as $n           # for each n-digit sequence
| [
      [                    # build array of ordinals for
        range(97;123),     #   a-z
        range(65;91),      #   A-Z
        range(48;58)       #   0-9
      ]
    | implode/""           # make into array of strings
    | combinations($n+1)   # generate array of n-element combinations
  ]
| map(add)[]               # convert to sequence of strings

```

Try it online!

---
Tags: code-golf, string, number, array
---