title: Is it a pleasing number?

text:
# Question
Title: Is it a pleasing number?
A pleasing number (according to this definition) is a number that can be passed through the following process (let's use `41802000` as an example):

* Separate the trailing identical numbers (`41802000 => [41802, 000]`)
* Sort the first half of the digits and take the maximum (`[41802, 000] => [8, 000]`)
* Take the length of the final element. Call the resultant elements *A* and *B* (`[8, 000] => A=8, B=3`)
* Is NB = A for any integer `N`? (`True` in this example; 23 = 8)

If the input results in `True` from the following process, it is considered pleasing.

Your task is to take an integer `x`, and output whether `x` is a pleasing number. You can output any two distinct values for truthy and falsey, but please state what you're using in your answer. `x` is guaranteed to have at least two distinct digits (e.g. `111` is an invalid input). As with most challenges, you may take `x` as a string, or a list of digits.

This is a so shortest code in *bytes* wins.

## Test cases

```
          Input          Output
       41802000               1
            100               1
      123456788               0
      451111111               0
234543454545444               0
             12               1
       41902000               0
          92599               1

```

# Answer
# APL (Dyalog), 36 bytes

```
{(⊢≡⌊)(⌈/⍎¨⍵/⍨~o)*÷≢⍵/⍨o←⌽⌊\1,2=/⌽⍵}

```

Try it online!

**How?**

*Almost a poem.*

`⌽⍵` \- reverse the input once,

`1,2=/` \- get the differences list.

`⌊\` \- keep only the first group of ones,

\- and flip it over to complete.

---

`o←` \- assign to `o`,

`~o` \- switch ones and zero(s),

`⍵/⍨` \- filter the input with it,

`⍎¨` \- turn the result into list of each digit,

* `⌈/` \- and get the maximum. (that's A)

---

`⍵/⍨o` \- filter the input with `o` unalt(ered),

\- and take the length, that would be B.

`÷` \- get one divided by this result,

`*` \- and take A to that power thee.

---

`⊢≡⌊` \- integer?
> 10 votes

# Answer
# 05AB1E, 11 bytes

```
γRćgUZXzm.ï

```

Try it online!

## Explanation

```
γRćgUZXzm.ï ~ Full program.

γ           ~ Split into runs of digits.
 R          ~ Reverse.
  ć         ~ Push a[1:], a[0] to the stack.
   g        ~ Length (of a[0]).
    U       ~ Assign this to the integer variable X.
     ZX     ~ Get the maximum, without popping, and push X.
       zm   ~ A<sup>1/B</sup>.
         .ï ~ Is it an integer?

```

Emigna saved 1 byte.

Relies on the fact that if **A** is a positive integer **N** raised to the power of **B**, then **N=A1/B**, hence it must be an integer.
> 9 votes

# Answer
# Haskell, ~~85~~ ~~75~~ ~~72~~ 71 bytes

***Edit**: -10 bytes by taking a list of digits instead of a string. Thanks to WhatToDo for pointing out that this is allowed. -3 bytes thanks to Ourous' solution in Clean. -1 byte thanks to user28667.*

```
f s|(b,a)<-span(==last s)$reverse s=or[n^length b==maximum a|n<-[1..9]]

```

Try it online! Takes input as a list of digits. Example usage: `f [4,1,8,0,2,0,0,0]` yields `True`.

### Explanation:

Given an input `s=[4,1,8,0,2,0,0,0]`, we `reverse` the list and separate the leading elements with `span(==last s)`: `([0,0,0],[2,0,8,1,4])`. The pattern matching on `(b,a)` yields `b=[0,0,0]` and `a=[2,0,8,1,4]`.

The list comprehension `or[n^length b==maximum a|n<-[1..a]]` checks whether any integer `n` in the range from `1` to `9` satisfies `n^length b==maximum a`, that is `n^3=8`.
> 9 votes

# Answer
# Haskell, ~~104~~ 89 bytes

@Laikoni found a shorter solution, but this is the best I could do. Thanks @Laikoni for letting me know that we can also accept lists of digits as input.

```
import Data.List
(g.length.last<*>maximum.concat.init).group
g b a=any(==a)$(^b)<$>[1..a]

```

### Explanation:

Try it online!
> 6 votes

# Answer
# Jelly, 11 bytes

```
ŒgµṪL9*€fṀL

```

Takes input as a list of digits.

Try it online!

### How it works

```
ŒgµṪL9*€fṀL  Main link. Argument: D (digit array)

Œg           Group runs of digits, yielding a run array R.
  µ          Begin a new chain with argument D.
   Ṫ         Tail; remove and yield the last element of D.
    L        Take the length. Let's call it b.
     9*€     Compute [1**b, ..., 9**b].
         Ṁ   Take the maximum run in R, yileding [a, ..., a].
        f    Filter, yielding either [a] (if a = n**b for some n) or [].
          L  Take the length.

```
> 5 votes

# Answer
# , 80 bytes

```
function(x)any((0:(m=max((d=rle(rev(utf8ToInt(c(x,''))-48)))$v[-1])))^d$l[1]==m)

```

Try it online!

Uses `utf8ToInt - 48` to split the number into digits. This throws a warning from the conversion to a string.

Using rle get the count of the trailing digits and the max value of the first digits. Return true if the any of the range 0 to max value to the power of trailing count equals max value.

I think there are further golfing opportunities, but that can wait until tomorrow.
> 5 votes

# Answer
# R, 66 bytes

This answer is more or less a medley of MickyT and NofP's answers, and on their request, here it is:

```
function(x,R=rle(rev(utf8ToInt(x)-48)))!max(R$v[-1])^(1/R$l[1])%%1

```

It takes x as a string.

```
> f=function(x,R=rle(rev(utf8ToInt(x)-48)))!max(R$v[-1])^(1/R$l[1])%%1
> f("41802000")
[1] TRUE
> f("100")
[1] TRUE
> f("123456788")
[1] FALSE
> f("451111111")
[1] FALSE
> f("234543454545444")
[1] FALSE
> f("12")
[1] TRUE
> f("41902000")
[1] FALSE

```
> 5 votes

# Answer
# JavaScript (ES7), 66 bytes

Takes input as either a string or an array of characters. Returns a boolean.

```
f=([c,...s],m)=>s.some(n=>n-c)?f(s,c<m?m:c):!(m**(1/-~s.length)%1)

```

### Test cases

```
f=([c,...s],m)=>s.some(n=>n-c)?f(s,c<m?m:c):!(m**(1/-~s.length)%1)

console.log(f(       '41802000')) // 1
console.log(f(            '100')) // 1
console.log(f(      '123456788')) // 0
console.log(f(      '451111111')) // 0
console.log(f('234543454545444')) // 0
console.log(f(             '12')) // 1
```
> 4 votes

# Answer
# Clean, ~~130~~ ~~128~~ ~~118~~ 93 bytes

```
import StdEnv
@l#(b,a)=span((==)(last l))(reverse l)
=or[n^length b==last(sort a)\\n<-[0..9]]

```

Defines the function `@`, taking a list of integer digits.

Try it online!
> 4 votes

# Answer
# Python 2, ~~95~~ 78 bytes

* Saved seventeen bytes thanks to Rod.

```
def f(s,i=~0):
	while s[i]==s[~0]:i-=1
	return int(max(s[:-~i]))**(1./~i)%1==0

```

Try it online!
> 4 votes

# Answer
# C (gcc), ~~144~~ ~~126~~ 117 bytes

```
j,k,m;f(char*N){N+=j=strlen(N);k=~j;for(j=-1;m=N[j--]==N[j];);for(;k++<j;)m=fmax(N[k],m);j=!fmod(pow(m-48,1./~j),1);}

```

Try it online!
> 3 votes

# Answer
# , 93 bytes

```
function(x){n=nchar(x)
d=x%/%10^(n:1-1)%%10
i=max(which(d!=d[n]))
max(d[1:i])^(1/(n-i))%%1>0}

```

Try it online!

The code takes an integer as input and returns FALSE if the number is pleasing, and TRUE otherwise.
> 3 votes

# Answer
# Python 3, ~~88~~ 85 bytes

```
def f(n):p=n.rstrip(n[-1]);a=int(max(p));b=len(n)-len(p);return round(a**(1/b))**b==a

```

### Ungolfed:

```
def is_pleasing_number( n ):
    prefix = n.rstrip(n[-1])
    a = int(max(prefix))
    b = len(n) - len(prefix)
    return round(a ** (1 / b)) ** b == a

```
* The input argument is expected to be a digit string
* The output is either `True` or `False`.
* Similar to yet developed independently of Halvard’s answer but uses floating point arithmetic in a way that doesn't suffer from rounding errors until `a ** (1 / b)` is off by at least 0.5 from b√a which requires a value above 253 (or whatever floating point radix and mantissa length Python happens to use, see `sys.float_info`).
* Can be modified trivially to still work with arbitrary number bases between 2 and 36.
> 3 votes

# Answer
# Kotlin, 106 bytes

```
fun String.p()=split(Regex("(?=(.)\\1*$)")).let{Math.pow((it[0].max()?:'0')-'0'+.0,1.0/(it.size-1))}%1==.0

```

Output: true/false

Try it online!
> 2 votes

# Answer
# Japt, ~~26~~ 18 bytes

```
ó¶
o l
ñ o n qV v1

```

Try it online!

---

Takes input as a string, returns `1` for pleasing numbers, `0` otherwise.

Short explanation:

```
ó¶

```

Take the first input and split it by values where `(x,y) => x===y` is true. For example `'41802000'` to `['4','1','8','0','2','000']`.

```
o l

```

Take the array from the first step, remove the last element and get its length, yielding **B**.

```
ñ o n qV v1

```

Find the largest element in the remaining array, yielding **A**, take it to the power `1/B` and then return if the result is divisible by one.

---

First time working with Japt, very open to any recommendations.
Shaved off 8 bytes thanks to ETHproductions.
> 2 votes

# Answer
# Ruby, 64 bytes

```
->a{!([a[/(\d)\1*$/].size,$`.chars.max]*?x!~/x1$|^2x[49]|^3x8/)}

```

Input as a string, returns true if:

* B==1 (no need to check A)
* A==4 and B==2
* A==9 and B==2
* A==8 and B==3

Try it online!
> 1 votes

# Answer
# Perl 6, 55 bytes

```
{m/(\d+?)((\d)$0*)$/;so any(^10)**$1.comb==$0.comb.max}

```

Try it online!

After the evaluation of the initial regex--which can only succeed if the input is a positive integer--`$0` contains the initial part of the number, and `$1` contains the trailing repeated digits.

The `comb` method without arguments, applied to a string, returns a list of the characters, which in numeric context evaluates to the length of the list. So `$0.comb.max` is the largest of the digits in the prefix, and `$1.comb` is the length of the suffix.

We then check whether `any(^10)` (ie, the or-junction of the numbers from 0-9), when raised to the power of the length of the suffix, is equal to the largest digit in the prefix. The `so` forces boolean evaluation of the resulting junction, which would otherwise be just fine on its own as a truthy value, but the challenge calls for just two distinct values to be returned.
> 1 votes

# Answer
# C# (.NET Core), 132 bytes

```
n=>{int A=0,B=1,s=1,i=n.Length-1;for(;i-->0;)if(n[i]==n[i+1]&s>0)B++;else{A=n[i]>A?n[i]:A;s=0;}return System.Math.Pow(A,1d/B)%1==0;}

```

Try it online!

### Acknowledgements

-12 bytes thanks to @KevinCruijssen

### DeGolfed

```
n=>{
    int A=0, // maximum digit
        B=1, // count of trailing identical numbers
        s=1, // 1 if dealing with trailing numbers, 0 otherwise
        i=n.Length-1;

    for(; i-- > 0;)
        if(n[i] == n[i+1] & s > 0)
            B++;
        else
        {
            A = n[i] > A? n[i] : A;
            s = 0;
        }

    return Math.Pow(A, 1d/B) % 1 == 0;
}

```
> 1 votes

# Answer
# Add++, 21 bytes

```
L,BGubLV@¦+bMG1$/^1%!

```

Try it online!

It's been 3 and a half months, I hope I'm not ninja'ing anyone.
> 1 votes

# Answer
## Clojure, 168 bytes

```
(fn[x](let[y(reverse(vec x))z(count(take-while #(= %(first y))y))a(apply max(map #(-(int %)48)(drop z y)))b(Math/pow a(/ 1 z))](<(Math/abs(- b(Math/round b)))0.00001)))

```

Try it online!
> 0 votes

# Answer
# Charcoal, 33 bytes

```
≔ＥＳιθ⊞υ⊟θＷ⁼§υ⁰§θ±¹⊞υ⊟θ¬﹪ＸＩ⌈θ∕¹Ｌυ¹

```

Try it online! Link is to verbose version of code. Outputs a `-` for pleasing numbers. Explanation:

```
≔ＥＳιθ

```

Split the input `q` into characters.

```
⊞υ⊟θ

```

Remove the last character from `q` and push it to `u` (predefined to an empty list).

```
Ｗ⁼§υ⁰§θ±¹⊞υ⊟θ

```

Repeatly pop and push while the last character of `q` is the first character of `u`.

```
¬﹪ＸＩ⌈θ∕¹Ｌυ¹

```

Take the maximum digit of `q` and raise it to the power of the reciprocal of the length of `u`, then check whether the result is an integer.
> 0 votes

# Answer
# Python 2, ~~91~~ 85 bytes

```
s=`input()`;d=0
p=s.rstrip(s[-1])
exec"`d**(len(s)-len(p))`==max(p)>exit(1);d+=1;"*10

```

Try it online!
> 0 votes

# Answer
# Perl 5, 73 + 1 (`-p`) = 74 bytes

```
s/(.)\1*$//;$/=length$&;$_=(sort/./g)[-1];$q=$"++**$/while$q<$a;$_=$q==$a

```

Try it online!
> 0 votes

# Answer
# Java 8, 125 bytes

```
a->{int A=0,B=1,f=1,i=a.length-1;for(;i-->0;)if(a[i]==a[i+1]&f>0)B++;else{A=a[i]>A?a[i]:A;f=0;}return Math.pow(A,1d/B)%1==0;}

```

Port of *@Ayb4btu*'s C# .NET answer.

Try it online.

**Explanation:**

```
a->{                       // Method with digit-array parameter and boolean return-type
  int A=0,                 //  Maximum digit `A` as specified in the challenge description
      B=1,                 //  `B` as specified in the challenge description
      f=1,                 //  Flag-integer, starting at 1
      i=a.length-1;        //  Index integer `i`
  for(;i-->0;)             //  Loop `i` backwards over the digits (excluding the last)
    if(a[i]==a[i+1]        //   If the current and next digits are the same,
       &f>0)               //   and the flag is still 1
      B++;                 //    Increase `B` by 1
    else{                  //   Else:
      A=a[i]>A?            //    If the current digit is larger than `A`
         a[i]              //     Replace `A` with the current digit
        :                  //    Else:
         A;                //     Leave `A` the same
      f=0;}                //    Set the flag-integer to 0
  return Math.pow(A,1d/B)  //  Return if `A` ^ (1/`B`)
    %1==0;}                //  is an exact integer

```
> 0 votes

# Answer
# Pip, ~~32~~ ~~22~~ 21 bytes

```
'.N(#a-#Ya<|a@v)RTMXy

```

Uses `1` for *falsey* and `0` for *truthy*, saving a byte. Try it online!
> 0 votes

# Answer
## Pyth, 29 bytes

```
JezWqezJ=Pz=hZ)K@sh.MsZzZqKsK

```

**Test suite**

Python 3 translation:
```
Z=0
z=input()
J=z[-1]
while z[-1]==J:
    z=z[:-1]
    Z+=1
K=max(map(int,z))**(1/Z)
print(K==int(K))

```
> 0 votes

---
Tags: code-golf, math, decision-problem
---


title: Reverse Range Successors

text:
# Question
Title: Reverse Range Successors
Given a positive integer `n`, do the following (and output every stage):

1. start with a list containing `n` copies of `n`.
2. do the following `n` times:
3. at the `i`th step, gradually decrement the `i`th entry of the list until it reaches `i`

So, for example, if the given `n` is `4`, then you start with `[4,4,4,4]`, and then at the first step you have `[3,4,4,4]`, `[2,4,4,4]`, `[1,4,4,4]`. At the second step, you have `[1,3,4,4]`, `[1,2,4,4]`. At the third step you have `[1,2,3,4]`. Nothing is done on the fourth step.

So your output is `[[4,4,4,4],[3,4,4,4],[2,4,4,4],[1,4,4,4],[1,3,4,4],[1,2,4,4],[1,2,3,4]]`.

---

Any reasonable input/output format is permitted.

---

Standard loopholes apply. This is : the answer with the smallest byte-count wins.

---

Python implementation for checking purposes.

# Answer
# Jelly, 9 bytes

```
r€⁸Œp»\QṚ

```

**Try it online!**

### How?

```
r€⁸Œp»\QṚ - Link: integer, N    e.g. 4
 €        - for €ach of implicit range of N (i.e. for i in [1,2,3,...N])
  ⁸       -   with the chain's left argument, N on the right:
r         -     inclusive range (for i<=N this yields [i, i+1, ..., N]
          - ...leaving us with a list of lists like the post-fixes of [1,2,3,....,N]
          -                     e.g. [[1,2,3,4],[2,3,4],[3,4],[4]]
   Œp     - Cartesian product* of these N lists
          -                     e.g. [[1,2,3,4],[1,2,4,4],[1,3,3,4],[1,3,4,4],[1,4,3,4],[1,4,4,4],[2,2,3,4],[2,2,4,4],[2,3,3,4],[2,3,4,4],[2,4,3,4],[2,4,4,4],[3,2,3,4],[3,2,4,4],[3,3,3,4],[3,3,4,4],[3,4,3,4],[3,4,4,4],[4,2,3,4],[4,2,4,4],[4,3,3,4],[4,3,4,4],[4,4,3,4],[4,4,4,4]]
      \   - cumulative reduce with:
     »    -   maximum (vectorises)
          -                     e.g. [[1,2,3,4],[1,2,4,4],[1,3,4,4],[1,3,4,4],[1,4,4,4],[1,4,4,4],[2,4,4,4],[2,4,4,4],[2,4,4,4],[2,4,4,4],[2,4,4,4],[2,4,4,4],[3,4,4,4],[3,4,4,4],[3,4,4,4],[3,4,4,4],[3,4,4,4],[3,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]]
       Q  - de-duplicate        e.g. [[1,2,3,4],[1,2,4,4],[1,3,4,4],[1,4,4,4],[2,4,4,4],[3,4,4,4],[4,4,4,4]]
        Ṛ - reverse             e.g. [[4,4,4,4],[3,4,4,4],[2,4,4,4],[1,4,4,4],[1,3,4,4],[1,2,4,4],[1,2,3,4]]

```

* It may be easier to see what's going on with the Cartesian product used above with a different input:

```
the Cartesian product of [[0,1,2],[3,4],[5]]
is [[0,3,5],[0,4,5],[1,3,5],[1,4,5],[2,3,5],[2,4,5]]

```
> 6 votes

# Answer
# , ~~83~~ ~~82~~ 74 bytes

```
N=rep(n<-scan(),n);while({print(N);any(K<-N>1:n)})N[x]=N[x<-which(K)[1]]-1

```

Try it online!

Instead of a double for-loop, a `while` loop is sufficient here: we find the first index where the list is greater than the index, and decrement there.

`K` has `TRUE` wherever `N[i]>i`, `which(K)` returns the true indices, and we take the first with `[1]`.
> 5 votes

# Answer
# Jelly, 12 bytes

```
R‘®¦<³S©$Ð¿Ṛ

```

Try it online!
> 3 votes

# Answer
# JavaScript (ES6), 75 bytes

```
f=(n,a=Array(n).fill(n))=>[[...a],...a.some(v=>v>++j,j=0)?f(a[j-1]--,a):[]]

```

Try it online!
> 2 votes

# Answer
# APL+WIN, 54 bytes

Prompts for screen input of integer

```
((⍴m)⍴n)-+⍀m←0⍪(-0,+\⌽⍳n-1)⊖((+/+/m),n)↑m←⊖(⍳n)∘.>⍳n←⎕

```

Outputs a matrix with each row representing the result of each step e.g. for 4:

```
4 4 4 4
3 4 4 4
2 4 4 4
1 4 4 4
1 3 4 4
1 2 4 4
1 2 3 4

```
> 2 votes

# Answer
# Java (OpenJDK 8), 135 bytes

```
a->{int r[]=new int[a],i=0;java.util.Arrays x=null;x.fill(r,a);for(r[0]++;i<a;r[i++]++)for(;--r[i]>i;System.out.print(x.toString(r)));}

```

Try it online!

**Explanation:**

```
int r[]=new int[a],i=0;    //Initialize array and loop counter
java.util.Arrays x=null;    //reduces the number of of “Arrays” needed from 3 to 1
x.fill(r,a);    //Sets each value in array length n to int n
for(r[0]++;i<a;r[i++]++)    //Increment everything!
  for(;--r[i]>i;    //If decremented array element is larger than element number:
     System.out.print(x.toString(r)));}    //Print the array

```

**Credit:**

-8 bytes thanks to Jonathan Frech!

-16 bytes thanks to Kevin Cruijssen!

-1 byte thanks to Okx!
> 2 votes

# Answer
# Haskell, ~~69 67 65~~ 63 bytes

Recursive definition:

```
f 0=[[]]
f a=map(:(a<$[2..a]))[a,a-1..2]++[1:map(+1)x|x<-f$a-1]

```

Thanks to Laikoni for 2 bytes!
> 2 votes

# Answer
# Jelly, 11 bytes

```
x`’Jḟḣ1Ʋ¦ÐĿ

```

Try it online!

### How it works

```
x`’Jḟḣ1Ʋ¦ÐĿ  Main link. Argument: n

x`           Repeat self; yield an array of n copies of n.
         ÐĿ  While the results are unique, repeatedly call the link to the left.
             Return the array of all unique results, including the initial value.
  ’     ¦      Decrement the return value at all indices specified by the chain
               in between.
       Ʋ         Combine the four links to the left into a monadic chain.
   J               Indices; yield [1, ..., n].
    ḟ              Filterfalse; remove all indices that belong to the return value.
     ḣ1            Head 1; truncate the result to length 1.

```
> 2 votes

# Answer
# Python 3, 91 bytes

```
n=int(input())
x=[n]*n;print(x)
for i in range(n):
    for j in[0]*(n-i-1):x[i]-=1;print(x)

```

Try it online!
> 2 votes

# Answer
## PHP, 153 Bytes

Try it online!

**Code**

```
function f($n){
$a=array_fill(0,$n,$n);$r=json_encode($a)."\n";$p=0;while($p<$n)
{if($a[$p]!=$p+1){$a[$p]--;$r.=json_encode($a)."\n";}else{$p++;}}echo$r;}

```

*Gonna try to lower the bytes, or finish the recursive function*

**Explanation**

```
function f($n){
  $a=array_fill(0,$n,$n);          #start with $nlength array filled with $n
  $r=json_encode($a)."\n";         #pushed to the string to output
  $p=0;                            #first position
  while($p<$n){                    #on position $n ($n-1) we do nothing
    if($a[$p]!=$p+1){              #comparing the position+1 to the value
     $a[$p]--;                     #it gets decreased by 1
     $r.= json_encode($a)."\n";    #and pushed
   } else {
     $p++;                       #when position+1 = the value,
   }                               #position is changed ++
  }
   echo $r;
  }

```
> 2 votes

# Answer
# Python 2, ~~80~~ 76 bytes

```
i=input();l=[i]*i;print l
for x in range(i):
 while l[x]>x+1:l[x]-=1;print l

```

Try it online!

Bit wasteful having two `print` statements but I can't think of a better way at the moment.
> 1 votes

# Answer
# Python 2, 70 bytes

-2 bytes thanks to @LeakyNun
-2 bytes thanks to @JonathanFrech

```
i=I=input()
l=[I]*I
exec"exec'print l;l[-i]-=1;'*max(~-i,2);i-=1;"*~-I

```

Try it online!
> 1 votes

# Answer
# Java (JDK 10), 112 bytes

```
n->{var s="";for(int i=1,k=n,j;i<=n;k=--k>i?k:n-++i+i)for(j=0;j++<n;)s+=(j<i?j:j>i?n:k)+(j<n?",":";");return s;}

```

Try it online!
> 1 votes

# Answer
# , ~~17~~ 15 bytes

```
+/\@,(#=)@i.&.-

```

Try it online!

## Explanation

```
+/\@,(#=)@i.&.-  Input: n
              -  Negate n
          i.     Reverse of range [0, n)
       =           Identity matrix of order n
      #            Copy each row by the reverse range
              -  Negate
    ,            Prepend n
+/\              Cumulative sum of rows

```
> 1 votes

# Answer
# Retina, 49 bytes

```
.+
*
_
$`_,$=
.{*\`_+,(_+)
$.1
0`(\b(_+),\2)_
$1

```

Try it online! Explanation:

```
.+
*

```

Convert the input to unary.

```
_
$`_,$=

```

Create a list of n copies of `i,n` where `i` is the index of the copy.

```
.

```

Don't print anything (when the loop finishes).

```
{

```

Loop until the pattern does not change.

```
*\`_+,(_+)
$.1

```

Temporarily delete the `i`s and convert the `n`s to decimal and output.

```
0`(\b(_+),\2)_
$1

```

Take the first list entry whose value exceeds its index and decrement it.
> 1 votes

# Answer
# Python 3, ~~70~~ ~~67~~ 65 bytes

```
def f(n):
 k=0;a=[n]*n
 while k<n-1:print(a);k+=a[k]==k+1;a[k]-=1

```

Try it online!

* (67) Converting to function: -3 bytes
* (65) Removing unneeded parentheses: -2 bytes

**Ungolfed version:**

```
def f(n):
    k = 0
    a = [n] * n             # create n-item list with all n's
    while k < n - 1:        # iterate through columns 0..n-1
        print(a)            # print whole list
        if a[k] == k + 1:   # move to the next column when current item reaches k+1
            k += 1
        a[k] -= 1           # decrement current item

```
> 1 votes

# Answer
# C (clang), ~~131~~ 141 bytes

```
i,j,k,m[99];p(){for(k=0;m[k];printf("%d ",m[k++]));puts("");}f(n){for(j=k=m[n]=0;k<n;m[k++]=n);p();for(;j<n;j++)for(i=1;i++<n-j;m[j]--,p());}

```

Try it online!

This will work for all `n` upto 99. TIO truncates output. It can support arbitrarily larger `n` by changing size of array `m` as memory permits.

---

Following is limited to n=1..9 but is significantly shorter

# C (clang), ~~89~~ 92 bytes

```
i,j;char m[12];f(n){j=!puts(memset(m,n+48,n));for(;j<n;j++)for(i=1;i++<n-j;m[j]--,puts(m));}

```

Try it online!

Updated: Modified to avoid dependence on static initialization
> 0 votes

# Answer
# K (ngn/k), ~~34~~ 32 bytes

```
{{x[y]-:1;x}\(,x#x),,/(|!x)#'!x}

```

Try it online!
> 0 votes

# Answer
## Clojure, 132 bytes

```
#(loop[R[(vec(repeat % %))]j(- % 2)i 0](if(> i j)R(recur(conj R(update(last R)i dec))(if(= i j)(- % 2)(dec j))(if(= i j)(inc i)i))))

```

I was hoping this to be shorter...

Less stateful but longer at **141** bytes:

```
#(apply map list(for[i(range %)](concat(repeat(nth(cons 0(reductions +(reverse(range %))))i)%)(range % i -1)(if(>(dec %)i)(repeat(inc i))))))

```
> 0 votes

# Answer
# Python 3, 101 bytes

```
def f(n):
 p=print;m=[n for_ in range(n)];p(m)
 for i in range(n):
    while m[i]>1+i:m[i]-=1;p(m)

```

I could probably golf more with the print, but I'm away from my computer and am not entirely sure of python 2's rules on setting a variable to print. I'll update later when I get to a computer or if someone clarifies in the comments.
> 0 votes

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


title: Code Johnny Code, Code!

text:
# Question
Title: Code Johnny Code, Code!
Rock-and-roll founding father Chuck Berry sadly passed away today.

Consider the chorus of his famous song "Johnny B. Goode":

```
Go, go
Go Johnny go, go
Go Johnny go, go
Go Johnny go, go
Go Johnny go, go
Johnny B. Goode

```

<sup>(There are other ways it has been punctuated but the above will serve for the purposes of the challenge.) </sup>

# Challenge

Given a nonempty, lowercase string of letters a-z, output the chorus of "Johnny B. Goode" with all the instances of `Go` or `go` replaced with the input string, capitalized in the same way.

A trailing newline may optionally follow. Nothing else in the chorus should change.

> **For example**, if the input is `code` the output must be exactly
>
> ```
> Code, code
> Code Johnny code, code
> Code Johnny code, code
> Code Johnny code, code
> Code Johnny code, code
> Johnny B. Codeode
>
> ```
>
> optionally followed by a newline.

Note that the capitalization of all words matches the original chorus, and (despite lack of rhythm) the `Go` in `Goode` is replaced as well as the individual words `Go` and `go`.

**The shortest code in bytes wins.**

# Test Cases

```
"input"
output

"go"
Go, go
Go Johnny go, go
Go Johnny go, go
Go Johnny go, go
Go Johnny go, go
Johnny B. Goode

"code"
Code, code
Code Johnny code, code
Code Johnny code, code
Code Johnny code, code
Code Johnny code, code
Johnny B. Codeode

"a"
A, a
A Johnny a, a
A Johnny a, a
A Johnny a, a
A Johnny a, a
Johnny B. Aode

"johnny"
Johnny, johnny
Johnny Johnny johnny, johnny
Johnny Johnny johnny, johnny
Johnny Johnny johnny, johnny
Johnny Johnny johnny, johnny
Johnny B. Johnnyode

"fantastic"
Fantastic, fantastic
Fantastic Johnny fantastic, fantastic
Fantastic Johnny fantastic, fantastic
Fantastic Johnny fantastic, fantastic
Fantastic Johnny fantastic, fantastic
Johnny B. Fantasticode

```

# Answer
> 88 votes
# Go, 123 bytes

*Go Johnny, **Go**!*

Try it online!

```
import."strings"
func(s string)string{t,e:=Title(s),", "+s+"\n";return t+e+Repeat(t+" Johnny "+s+e,4)+"Johnny B. "+t+"ode"}

```

# Answer
> 14 votes
# VIM, ~~54~~ 49 Keystrokes (saved 1 keystroke from Kritixi Lithos)

```
yw~hC<Ctrl-R>", <Ctrl-R>0<Enter>Johnny B. <Ctrl-R>"ode<Esc>}O<Ctrl-R>", Johnny <Ctrl-R>0, <Ctrl-R>0<Esc>3.

```

---

Start with the word on a line on a file with the cursor at the first character, then this will replace it all with the text Explanation

1. Copy the word into a register, then change the first letter to be capitalized and save that to a register.
2. Write the first line using the registers to fill in the replacements and last lines
3. Write the second line using the registers to fill in the replacements
4. Repeat the middle line 3 times

Try it online! (Thanks DJMcMayhem!)

# Answer
> 11 votes
# 05AB1E, 37 bytes

```
™„, ¹J¹Ð™”ÿºÇ ÿ, ÿ”4.D¹™”ºÇ B. ÿode”»

```

Try it online!

**Explanation**

```
™„, ¹J                                # concatenate title-cased input with ", " and input
     ¹Ð™                              # push input, input, title-cased input
        ”ÿºÇ ÿ, ÿ”                    # push the string "ÿ Johnny ÿ, ÿ" with "ÿ" replaced
                                      # by title-cased input, input, input
                  4.D                 # push 3 copies of that string
                     ¹™               # push title-cased input
                       ”ºÇ B. ÿode”   # push the string "Johnny B. ÿode" with "ÿ" replaced
                                      # by title-case input
                                   »  # join the strings by newlines

```

# Answer
> 10 votes
# Pure Bash, ~~69~~ 76 bytes

```
M=aaaa;echo -e ${1^}, $1 ${M//a/\\n${1^} Johnny $1, $1}\\nJohnny B. ${1^}ode

```

Try it online!

# Answer
> 6 votes
# , ~~41~~, 38 bytes

```
ÄJé,Ùäwa johnny 5ÄGdwwcWB.W~Aode.Î~

```

Try it online!

The perfect challenge for V!

Explanation:

```
ä$                              " Duplicate the input ('go' --> 'gogo', and cursor is on the first 'o')
  a, <esc>                      " Append ', '
                                " Now the buffer holds 'go, go'
          Ù                     " Duplicate this line
           äw                   " Duplicate this word (Buffer: 'gogo, go')
             a Johnny <esc>     " Append ' Johnny ' (Buffer: 'go Johnny go, go')
                           5Ä   " Make 5 copies of this line
G                               " Go to the very last line in the buffer
 dw                             " Delete a word
   w                            " Move forward one word (past 'Johnny')
    cW                          " Change this WORD (including the comma), to
      B.<esc>                   "   'B.'
             W                  " Move forward a WORD
              ~                 " Toggle the case of the character under the cursor
               Aode.<esc>       " Apppend 'ode.'
                         ÎvU    " Capitalize the first letter of each line

```

# Answer
> 6 votes
## Batch, 207 bytes

```
@set s= %1
@for %%l in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)do @call set s=%%s: %%l=%%l%%
@set j="%s% Johnny %1, %1"
@for %%l in ("%s%, %1" %j% %j% %j% %j% "Johnny B. %s%ode")do @echo %%~l

```

# Answer
> 6 votes
# JavaScript (ES6), ~~104~~ ~~101~~ 99 bytes

```
(i,u=i[0].toUpperCase()+i.slice(1),x=`, ${i}
${u} Johnny `+i)=>u+x+x+x+x+`, ${i}
Johnny B. ${u}ode`

```

Previous version:

```
(i,u=i[0].toUpperCase()+i.slice(1))=>u+`, ${i}
${u} Johnny ${i}`.repeat(4)+`, ${i}
Johnny B. ${u}ode`

```

---

**How it works:**

* It's an anonymous function that takes the input as the parameter `i`
* Defines a variable `u` as the input `i` with the first letter capitalized (Note that this assumes input is nonempty, which is OK)
* Just directly construct the string to be returned from those two variables.
* Repeating the string `"go, \nGo Johnny go"` four times instead of repeating `"Go Johnny go, go"` saves one byte.

---

**Edit 1:** Forgot to golf out the semicolon, haha!! Also miscounted the bytes, it was originally 102, not 104. Thanks apsillers.

**Edit 2:** Instead of `.repeat(4)`, by putting that string in a variable `x` and doing `x+x+x+x` allows saving two bytes.

---

### Test snippet

```
let f = (i,u=i[0].toUpperCase()+i.slice(1),x=`, ${i}
${u} Johnny `+i)=>u+x+x+x+x+`, ${i}
Johnny B. ${u}ode`;
```

```
<input id=I type="text" size=70 value="code"><button onclick="console.log(f(I.value))">Run</button>
```

# Answer
> 6 votes
# JavaScript, 98

```
s=>[S=s[0].toUpperCase()+s.slice(1),[,,,].fill(` ${s}
${S} Johnny `+s)]+`, ${s}
Johnny B. ${S}ode`

```

Abuses array-to-string serialization to create commas. Builds an array of the form:

```
["Go",
 " go\nGo Johnny go", (repeated...)]

```

And concatenates it to the string of the form `", go\nJohnny B. Goode"`:

```
["Go",
 " go\nGo Johnny go",
 " go\nGo Johnny go",
 " go\nGo Johnny go",
 " go\nGo Johnny go"] + ", go\nJohnny B. Goode"

```

# Answer
> 5 votes
# Pyth - 52 bytes

```
j", "_ArBQ3V4s[H" Johnny "G", "G;%"Johnny B. %sode"H

```

Test Suite.

# Answer
> 5 votes
# C, ~~156~~ 151 bytes

```
i,a,b;B(char*s){a=*s++;printf("%c%s, %c%s\n",b=a-32,s,a,s);for(;++i%4;)printf("%c%s Johnny %c%s, %c%s\n",b,s,a,s,a,s);printf("Johnny B. %c%sode",b,s);}

```

# Answer
> 5 votes
## Python 3, 88 bytes

```
lambda x:("{0}, {1}\n"+4*"{0} Johnny {1}, {1}\n"+"Johnny B. {0}ode").format(x.title(),x)

```

A simple format string, with positional arguments.

# Answer
> 4 votes
# Python, 94 bytes

```
lambda s:("|, #\n"+"| Johnny #, #\n"*4+"Johnny B. |ode").replace("|",s.title()).replace("#",s)

```

# Answer
> 4 votes
## Retina, 65 bytes

Byte count assumes ISO 8859-1 encoding.

```
^
$',
:T01`l`L
:`,
 Johnny$',
:`$
¶$`
(\S+) (\S+ ).+$
$2B. $1ode

```

Try it online!

# Answer
> 4 votes
# Jelly, 41 bytes

```
5“ Johnny “, “¶”ẋj¹Ḋṙ7ỴŒu1¦€Y“B. ”⁸Œt“ode

```

Try it online!

# Answer
> 4 votes
# C#, ~~219~~ ~~211~~ ~~212~~ ~~146~~ 122 Bytes

Implemented multiple suggestions from comments with additional optimization This is the Endresult:

```
a=>{string x=(char)(a[0]^32)+a.Remove(0,1),n=a+"\n",c=", ",r=n+x+" Johnny "+a+c;return x+c+r+r+r+r+n+$"Johnny B. {x}ode";}

```

Try it online!

Explantation:

```
a=>//Input parameter Explanation assumes "go" was passed
{
string x = (char)(a[0] ^ 32) + a.Remove(0, 1)// Input with first letter Uppercase "go"->"Go"
,
n = a + "\n",                               //"go" followed by newline
c = ", "                                    //Hard to believe: Comma followed by space
,
r = n + x + " Johnny " + a + c             //"go" follwed by newline followed by "Go Johnny go, "
;
return x + c + r + r + r + r + n + $"Johnny B. {x}ode"; };//return in the right order                              //Johnny B. Goode

```

Output for testcases:

```
Go, go
Go Johnny go, go
Go Johnny go, go
Go Johnny go, go
Go Johnny go, go
Johnny B. Goode

Code, code
Code Johnny code, code
Code Johnny code, code
Code Johnny code, code
Code Johnny code, code
Johnny B. Codeode

A, a
A Johnny a, a
A Johnny a, a
A Johnny a, a
A Johnny a, a
Johnny B. Aode

Johnny, johnny
Johnny Johnny johnny, johnny
Johnny Johnny johnny, johnny
Johnny Johnny johnny, johnny
Johnny Johnny johnny, johnny
Johnny B. Johnnyode

Fantastic, fantastic
Fantastic Johnny fantastic, fantastic
Fantastic Johnny fantastic, fantastic
Fantastic Johnny fantastic, fantastic
Fantastic Johnny fantastic, fantastic
Johnny B. Fantasticode

```

Edit: Thanks to weston for suggesting using a function

# Answer
> 3 votes
# PHP, 86 Bytes

```
echo strtr("1, 0\n2222Johnny B. 1ode",[$l=$argn,$u=ucfirst($l),"$u Johnny $l, $l\n"]);

```

# Answer
> 3 votes
# MATLAB/Octave, ~~133~~ 111 bytes

```
@(a)regexprep(['1, 2' 10 repmat(['1 32, 2' 10],1,4) '3B. 1ode'],{'1','2','3'},{[a(1)-32 a(2:end)],a,'Johnny '})

```

It's a start. Can hopefully be reduced further.

Basically it's an anonymous function which takes a string input and then uses regex to create the required output.

```
@(a)                                                    %Anonymous Function
    regexprep(                                          %Regex Replace
        ['1, 2' 10                                      %First line is: Code, code
            repmat(['1 32, 2' 10],1,4)                  %Then four lines of: Code Johnny code, code
                               '3B. 1ode'],             %Final line: Johnny B. Codeode
         {'1','2','3'},                                 %1,2,3 are our replace strings in the lines above
         {[a(1)-32 a(2:end)],a,'Johnny '}               %We replace with '(I)nput', 'input' and 'Johnny ' respectively.
    )

```

An example:

```
@(a)regexprep(['1, 2' 10 repmat(['1 32, 2' 10],1,4) '3B. 1ode'],{'1','2','3'},{[a(1)-32 a(2:end)],a,'Johnny '});
ans('hi')
ans =

Hi, hi
Hi Johnny hi, hi
Hi Johnny hi, hi
Hi Johnny hi, hi
Hi Johnny hi, hi
Johnny B. Hiode

```

~~You can *sort of* Try it online!. The code doesn't quite work with Octave as all the upper case letters become `${upper($0)}`, whereas in MATLAB this is converted to the actual upper case letter.~~

Given the input is guaranteed to only be `a-z` (lowercase alphabet), I can save 22 bytes by using a simple subtraction of 32 to convert the first letter in the string to capital, rather than using regex with the `upper()` function.

As a result, the code now works with Octave as well, so you can now Try it online!

# Answer
> 3 votes
# Ruby, ~~89~~ ~~88~~ ~~86~~ 79 bytes

My first golf submission :

```
->x{"^, *
#{"^ Johnny *, *
"*4}Johnny B. ^ode".gsub(?^,x.capitalize).gsub ?*,x}

```

Thanks a lot to @manatwork for his awesome comment : 7 bytes less!

# Answer
> 3 votes
# Java 8, ~~151~~ ~~147~~ ~~146~~ 130 bytes

```
s->{String x=(char)(s.charAt(0)^32)+s.substring(1),n=s+"\n",r=n+x+" Johnny "+s+", ";return x+", "+r+r+r+r+n+"Johnny B. "+x+"ode";}

```

**Explanation:**

Try it here.

```
s->{                               // Method with String as both parameter and return-type
  String x=                        //  Temp String with:
           (char)(s.charAt(0)^32)  //   The first letter capitalized
    +s.substring(1),               //   + the rest of the String
         n=s+"\n",                 //  Temp String with input + new-line
         c=", ",                   //  Temp String with ", "
         r=n+x+" Johnny "+s+c;     //  Temp String with "input\nInput Johnny input, "
  return x+c+r+r+r+r+n+"Johnny B. "+x+"ode";
                                   //  Return output by putting together the temp Strings
}                                  // End of method

```

# Answer
> 3 votes
# Nova, 105 bytes

```
a(String s)=>"#{s.capitalize()+", #s\n"+"#s.capitalize() Johnny #s, #s\n"*4}Johnny B. #s.capitalize()ode"

```

Because Nova (http://nova-lang.org) is extremely early beta (and buggy), there are some obvious handicaps that are in place here keeping it from using even less bytes.

For example, could have saved capitalized function call (which is called 3 times) in a local variable like this:

```
a(String s)=>"#{(let c=s.capitalize())+", #s\n"+"#c Johnny #s, #s\n"*4}Johnny B. #{c}ode"

```

which would have taken the byte count down to **89 bytes**. The reason this doesn't work now can be blamed on the argument evaluation order in the C language, because Nova is compiled to C. (The argument evaluation order will be fixed in a future update)

Even more, I could have introduced a "title" property in the String class (and I will after doing this lol) to reduce the count from the capitalization function call:

```
a(String s)=>"#{(let c=s.title)+", #s\n"+"#c Johnny #s, #s\n"*4}Johnny B. #{c}ode"

```

and that would free up 7 bytes to a new total of **82 bytes**.

Furthermore (and further off), once lambda variable type inference is added, this would be valid:

```
s=>"#{(let c=s.title)+", #s\n"+"#c Johnny #s, #s\n"*4}Johnny B. #{c}ode"

```

The count could be brought down to **72 bytes**.

By the way, this is my first code golf, so I probably have missed even more optimizations that could have been made. And this being a **non-golf centric**, **general purpose** language, I think it's pretty impressive.

The first 105 byte code works in the current Nova Beta v0.3.8 build available on http://nova-lang.org

```
class Test {
    static a(String s)=>"#{s.capitalize()+", #s\n"+"#s.capitalize() Johnny #s, #s\n"*4}Johnny B. #s.capitalize()ode"

    public static main(String[] args) {
        Console.log(a("expl"))
    }
}

```

outputs:

```
Expl, expl
Expl Johnny expl, expl
Expl Johnny expl, expl
Expl Johnny expl, expl
Expl Johnny expl, expl
Johnny B. Explode

```

Thank you for listening to my shameless advertisement for the general purpose language Nova (found at http://nova-lang.org ...get it now!!)

# Answer
> 3 votes
# Brainfuck, 352 bytes

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

```

Try it online!

1. Get the input.
2. Save special characters for later.
3. Write the first part.
4. Save "Johnny" for later
5. Print "Go Johnny go, go" four times
6. Write The last part

I always like challenges in Brainfuck so it was fun. It can probably be golfed more but golfing Brainfuck is kind of long.

# Answer
> 2 votes
# Stacked, 64 bytes

```
:@n tc@N('%N, %n
'!'%N Johnny %n, %n
'!4*'Johnny B. 'N'ode'!)sum

```

Try it online!

# Answer
> 2 votes
# Excel VBA, <sub>~~137~~ ~~121~~ ~~112~~ ~~89~~ ~~87~~</sub> 84 Bytes

Anonymous VBE immediate window function that takes input of type `Variant/String` from cell `[A1]` and outputs by printing the the VBE immediate window

```
c=[Proper(A1)]:s=vbCr+c+[" Johnny "&A1&", "&A1]:?c", "[A1]s;s;s;s:?"Johnny B. "c"ode

```

-16 Bytes for converting to Immediate window function

-9 Bytes for using `[PROPER(A1)]`

-23 Bytes for dropping `For ...` loop and abusing the `?` statement

-2 Bytes for replacing `" Johnny "&[A1]&", "&[A1]` with `[" Johnny "&A1&", "&A1]`

-3 Bytes for using `+` over  `&` for String concatenation and leaving the terminal string unclosed

## Example Case

```
[A1]="an"          ''  <- Setting [A1] (may be done manually)
                   '' (Below) Anonymous VBE function
c=[Proper(A1)]:s=vbCr+c+[" Johnny "&A1&", "&A1]:?c", "[A1]s;s;s;s:?"Johnny B. "c"ode"
 An, an            ''  <- output
 An Johnny an, an
 An Johnny an, an
 An Johnny an, an
 An Johnny an, an
 Johnny B. Anode

```

# Answer
> 2 votes
## C#, ~~159~~ ~~130~~ 128 bytes

---

**Golfed**

```
i=>string.Format("{0},{1}????\n{2} B. {0}ode".Replace("?","\n{0} {2}{1},{1}"),(i[0]+"").ToUpper()+i.Substring(1)," "+i,"Johnny");

```

---

**Ungolfed**

```
i => string.Format( "{0},{1}????\n{2} B. {0}ode"
    .Replace( "?", "\n{0} {2}{1},{1}" ),

    ( i[ 0 ] + "" ).ToUpper() + i.Substring( 1 ), // {0}
    " " + i,                                      // {1}
    "Johnny" );                                   // {2}

```

---

**Ungolfed readable**

```
i => string.Format( @"{0},{1}
    ????
    {2} B. {0}ode"

    // Replaces the '?' for the string format that contains the
    // repetition of "___ Johnny ___, ___".
    .Replace( "?", "\n{0} {2}{1},{1}" ),

    // {0} - Converts the first letter to upper,
    //       then joins to the rest of the string minus the first letter
    ( i[ 0 ] + "" ).ToUpper() + i.Substring( 1 ),
    // {1} - The input padded with a space, to save some bytes
    " " + i,
    // {2} - The name used as parameter, to save some bytes
    "Johnny" );

```

---

**Full code**

```
using System;

namespace Namespace {
    class Program {
        static void Main( string[] args ) {
            Func<string, string> func = i =>
                string.Format( "{0},{1}????\n{2} B. {0}ode"
                    .Replace( "?", "\n{0} {2}{1},{1}" ),

                    ( i[ 0 ] + "" ).ToUpper() + i.Substring( 1 ),
                    " " + i,
                    "Johnny" );

            int index = 1;

            // Cycle through the args, skipping the first ( it's the path to the .exe )

            while( index < args.Length ) {
                Console.WriteLine( func( args[index++] ) );
            }

            Console.ReadLine();
        }
    }
}

```

---

**Releases**

* **v1.2** \- `- 2 bytes` \- Swapped `(i)=>` for `i=>`, thanks to TheLetalCoder comment.
* **v1.1** \- `-29 bytes` \- Thanks to Sir Bitesalot last update, who remembered me I could edit the string before format.
* **v1.0** \- `159 bytes` \- Initial solution.

---

**Notes**

The title has a link to a page with the code and the test cases. Just hit ***Go*** and the result will be printed below the code.

# Answer
> 2 votes
# **Javascript - ~~72~~ 106 bytes**

~~**Edit: Oops!! I didn't pay attention to the capitalization rules! It'll be longer after a while**~~

**Edit 2: Should be following the rules now!**

Could probably be golfed more

```
c=>(`G,g
`+`G Johnnyg,g
`.repeat(4)+`Johnny B.Gode`).replace(/g/g,' '+c.toLowerCase()).replace(/G/g,' '+c)

```

Used as:

```
c=>(`G,g
`+`G Johnnyg,g
`.repeat(4)+`Johnny B.Gode`).replace(/g/g,' '+c.toLowerCase()).replace(/G/g,' '+c)
alert(f("Code"));
alert(f("Go"));

```

# Answer
> 1 votes
# CJam, 50 bytes

```
r:L(eu\+:M',SLN[MS"Johnny ":OL',SLN]4*O"B. "M"ode"

```

Try it online!

Explanation:

```
r:L(eu\+:M',SLN[MS"Johnny ":OL',SLN]4*O"B. "M"ode" e# Accepts an input token.
r:L                                                e# Gets input token and stores it in L.
   (eu\+:M                                         e# Converts token to uppercase-first and stores it in M.
          ',S                                      e# Appears as ", ".
             L                                     e# Input token.
              N                                    e# Newline.
               [                                   e# Opens array.
                M                                  e# Modified token.
                 S                                 e# Space.
                  "Johnny ":O                      e# Pushes "Johnny " and stores it in O.
                             L                     e# Input token.
                              ',SLN                e# The same {',SLN} as before.
                                   ]4*             e# Closes array and repeats it 4 times.
                                      O            e# "Johnny ".
                                       "B. "       e# "B. ".
                                            M      e# Modified token.
                                             "ode" e# "ode".

```

# Answer
> 1 votes
# Pyke, 43 bytes

```
l5j", "Qs3
Qld"Johnny "iQs3:D4i"B. ode"+Tj:

```

Try it online!

Constructs and prints the first line then inserts `Johnny go` before the comma and duplicates that 4 times. Finally constructs the last part.

# Answer
> 1 votes
# Java 6, ~~258~~ 242 bytes

```
enum j{;public static void main(String[]a){char[]b=a[0].toCharArray();b[0]^=32;System.out.printf("%1$s, %2$s\n%1$s %3$s%2$s, %2$s\n%1$s %3$s%2$s, %2$s\n%1$s %3$s%2$s, %2$s\n%1$s %3$s%2$s, %2$s\n%3$sB. %1$sode",new String(b),a[0],"Johnny ");}}

```

Longest part of it is the format for printf. There are problems with input different than string from `a` to `z`(yes I know I don't need to support anything else).

Ungolfed with comments:

```
enum j {
    ;

    public static void main(String[] a) {
        char[] b = a[0].toCharArray();              // Copy of the input string
        b[0]^=32;                                   // First character of copy to uppercase
        System.out.printf(
                "%1$s, %2$s\n%1$s %3$s%2$s, %2$s\n%1$s %3$s%2$s, %2$s\n%1$s %3$s%2$s, %2$s\n%1$s %3$s%2$s, %2$s\n%3$sB. %1$sode", // Format string
                new String(b),  // Capitalized string
                a[0],           // Original input string
                "Johnny ");     // "Johnny "
    }
}

```

EDIT: Golfed 16 bytes thanks to weston

# Answer
> 1 votes
# Kotlin, ~~112~~, 99 Bytes

```
fun g(s:String)=s.capitalize().let{"$it, $s\n${"$it Johnny $s, $s\n".repeat(4)}Johnny B. ${it}ode"}

```

Ungolfed:

```
fun g(s: String) = s
        .capitalize()
        .let {
            "$it, $s\n${"$it Johnny $s, $s\n".repeat(4)}Johnny B. ${it}ode"
        }

```

# Answer
> 1 votes
# Python, 258 bytes

```
from jinja2 import Template
def f(go):
    t = Template("""{{ Go }}, {{ go }}
{{ Go }} Johnny {{ go }}, {{ go }}
{{ Go }} Johnny {{ go }}, {{ go }}
{{ Go }} Johnny {{ go }}, {{ go }}
{{ Go }} Johnny {{ go }}, {{ go }}
Johnny B. {{ Go }}ode""")
    return t.render(Go=go.title(), go=go)

```

# Answer
> 1 votes
# Japt, ~~62~~ 53 bytes

```
[1S]+U+R+`1 20, 0
`²²+`2B. 1o¸` d0U1Ug u +UÅ2"Johnny

```

Try it online!

---

62-byte solution using a substantially different technique:

*Saved 3 bytes thanks to ETHproductions*

```
W=Ug u +UÅ)+", {U}
"+`{W} Johnny {U}, {U}
`²²+`Johnny B. {W}o¸

```

Try it online!

# Answer
> 1 votes
# Bash, 72 bytes

(modified version of R. Kapp's answer):

```
M=hnny;echo -e ${1^}, $1 ${M//?/\\n${1^} Jo$M $1, $1}\\nJo$M B. ${1^}ode

```

Try it online!

# Answer
> 1 votes
# Mathematica, 83 bytes

```
{a=ToTitleCase@#,b=", ",#,{"
",a," Johnny ",#,b,#}~Table~4,"
Johnny B. ",a}<>"ode"&

```

Anonymous function. Takes a string as input and returns a string as output. Could probably be golfed further.

# Answer
> 1 votes
# Swift, 151 144 bytes

```
import Foundation
func b(a:String){let u=a.capitalized;print(u+", "+a);for _ in 0..<4{print(u+" Johnny "+a+", "+a)};print("Johnny B. "+u+"ode")}

```

Previous Version:

```
import Foundation
func b(s:String){let u=s.capitalized;print("\(u), \(s)");for _ in 0..<4{print("\(u) Johnny \(s), \(s)")};print("Johnny B. \(u)ode");}

```

Ungolfed:

```
import Foundation
func beGoode(inputString: String) {
        let capitalizedString = inputString.capitalized
        print("\(capitalizedString), \(inputString)")
        for _ in 0..<4 {
            print("\(capitalizedString) Johnny \(inputString), \(inputString)")
        }
        print("Johnny B. \(capitalizedString)ode")
    }

```

Example:

```
b(s: "code")

Code, code
Code Johnny code, code
Code Johnny code, code
Code Johnny code, code
Code Johnny code, code
Johnny B. Codeode

```

**Edit:** Golfed down 6 bytes by using string concatenation instead of interpolation. Down 1 byte more by removing final semi-colon.

# Answer
> 1 votes
# PHP, ~~84~~ 83 bytes

Good Bye, Chuck!

```
<?=strtr(str_pad("1, 0",41,"
1 2 0, 0")."2 B. 1ode",[$argn,ucfirst($argn),Johnny]);

```

or

```
<?=strtr(str_pad("1,0",32,"
1 20,0")."2 B. 1ode",[" $argn",ucfirst($argn),Johnny]);

```

Run with `echo '<input>' | php -nF <filename>` or try them online.

# Answer
> 0 votes
## Q, 97 bytes

```
{u:(upper x[0]),1_x;u,", ",x,"\n",((,/)4#enlist u," Johnny ",x,", ",x,"\n"),"Johnny B. ",u,"ode"}

```

Assuming input "go".

1. Defines uppercase input as variable u.
2. Merges u with input x to generate first line, "Go, go".
3. Copies body, "Go Johnny go, go", four times.
4. Merges with final line, "Johnny B. Goode".

# Answer
> 0 votes
# Common Lisp, 107 bytes

```
(apply'format t"~:(~A~), ~a~%~4@{~:(~A~) Johnny ~a, ~a ~%~}Johnny G. ~:(~A~)ode"(fill(make-list 15)(read)))

```

Try it online!

# Answer
> 0 votes
# Japt, 52 bytes

```
[V=UhUg u)',SUR[VSW="Johnny "U',SUR]¬²²W`B. {V}o¸`]¬

```

Try it

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

```
n;f(char*s){for(n=6;n--;)printf(n?n^5?"%c%s Johnny %s, %s\n":"%c%s, %s\n":"Johnny B. %c%sode",*s-32,s+1,s,s);}

```

Try it online!

# Answer
> 0 votes
# Excel, 103 bytes

-8 bytes saved by using `#` and `~` instead of `Go` and `go`

```
=SUBSTITUTE(SUBSTITUTE("#, ~
"&REPT("# Johnny ~, ~
",4)&"Johnny B. #ode","#",PROPER(A1)),"~",LOWER(A1))

```

# Answer
> 0 votes
## Pyth, ~~69~~ 67 bytes

```
.F++"{0}, {1}\n"*"{0} {2} {1}, {1}\n"4"{2} B. {0}ode"[rz4rz0"Johnny

```

Try it here!

Python 3 translation:
```
z=input()
print(("{0}, {1}\n"+"{0} {2} {1}, {1}\n"*4+"{2} B. {0}ode").format(z.capitalize(),z.lower(),"Johnny"))

```

# Answer
> 0 votes
# SOGL V0.12, 38 bytes

```
,1Ƨ, Ο,@+"9:█ŗ‘⁽:A+⁴+:³a,⁽"B. ŗode”+⁰⁽

```

Try it Here!

# Answer
> 0 votes
# Stax, 34 bytes

```
₧:hç╟╫9↓Σl(Ü°╤`╨+B╥¢└ÇI╩4╢YP-├Γ■fl

```

Run and debug it

Unpacked, ungolfed, and commnted, it looks like this.

```
:.X         title case input and store in x register        e.g. "Code"
., +        concat ", "                                     e.g. "Code, "
y+Q         concat input and print without popping          e.g. "Code, code"
x`?*u)U"`+  concat " Johnny " to x                          e.g. "Code, code" "Code Johnny "
sv+         swap top of stack, lowercase, concat            e.g. "Code Johnny code, code"
QQQQ        print 4 times without popping                   e.g. "Code Johnny code, code"
j1@p        split, print the second word without newline    e.g. "Johnny"
" B. `xode  output string template with x register embedded e.g. " B. Codeode"

```

Run this one

# Answer
> 0 votes
# Jstx, 52 bytes

```
₧&Eu◄, :;4♦/u♂ Johnny♀:◄, :;► :;41u☼◘~ΘåÆëë╟┌°;♫☺åΘ:

```

Try it online!

Explanation

```
₧&          # Push literal 100
E           # Push the second stack value the absolute value of the first stack value times.
u           # Push the first stack value transformed to Title Case.
◄,          # Push literal ,
:           # Push the sum of the second and first stack values.
;           # Push the difference of the second and first stack values.
4           # Print the first stack value, then a newline.
♦           # Push literal 4
/           # Enter an iteration block over the first stack value.
u           # Push the first stack value transformed to Title Case.
♂ Johnny♀   # Push literal  Johnny
:           # Push the sum of the second and first stack values.
◄,          # Push literal ,
:           # Push the sum of the second and first stack values.
;           # Push the difference of the second and first stack values.
►           # Push literal
:           # Push the sum of the second and first stack values.
;           # Push the difference of the second and first stack values.
4           # Print the first stack value, then a newline.
1           # End an iteration block.
u           # Push the first stack value transformed to Title Case.
☼◘~ΘåÆëë╟┌° # Push literal Johnny B.
;           # Push the difference of the second and first stack values.
♫☺åΘ        # Push literal ode
:           # Push the sum of the second and first stack values.

```

# Answer
> 0 votes
## Python 2, 156 bytes

```
#coding:UTF-8
import sys;a="þ, ÿ"+("\nþ Johnny ÿ, ÿ"*4)+"\nJohnny B. þode";print a.replace("þ",sys.argv[1].title()).replace("ÿ",sys.argv[1].lower())

```

De-golfed:

```
#coding:UTF-8
import sys
a = "þ, ÿ" + ("\nþ Johnny ÿ, ÿ" * 4) + "\nJohnny B. þode"
b = a.replace("þ", sys.argv[1].title())
c = b.replace("ÿ", sys.argv[1].lower())
print c

```

Works as long as input doesn't contain the character *ÿ*, but passes all test cases.

Bytes counted by this byte counter.

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


title: Tower building challenge

text:
# Question
Title: Tower building challenge
I have recently thought of a wonderful relatively old mobile game, called Tower Bloxx. Alhough I'm not really old myself, but it reminded me of childhood and school :)

So this my challenge is a kind of a *reference* to that good game!

<sup>I have (hopefully) looked into any tower question on PPCG and this won't be a dupe. </sup>

---

## Definition

Given `N` \- number of blocks, build a tower of N blocks with the following pattern. The horizontal coordinate is changed with every block.

In order to avoid misinterpretations, here's the "table" of correlations between the n-th block and its horizontal coordinate.

There're no random things there, the coordinate for each block is strictly defined.

These horizontal coordinates are all listed relative to the first block and they are in fact just for readability of the following test cases.

```
N    X (coord)
------
1    0
2    2
3   -2
4    0
5   -2
6    2
7    goto N=1

```

On top of the last block, you must smash a roof.

---

## Input

Positive integer (`N`).

## Output:

`N` blocks stacked on top of each other and the roof. Each block is horizontally moved compared to the first block (to either -2, 0, or 2 points), as described in the table.

The block structure:

```
  *********
  * ----- *
  * |   | *
  * |   | *
  * ----- *
  *********

```

Once they are stacked together, the top of the lower block intersects with the bottom of the higher block:

```
    *********
    * ----- *
    * |   | *
    * |   | *
    * ----- *
  ***********
  * ----- *
  * |   | *
  * |   | *
  * ----- *
  *********

```

The roof that should be stacked on top of the last, n-th block is:

```
      *
     ***
    ** **
   **   **

```

The block with the roof atop looks like this:

```
      *
     ***
    ** **
   **   **
  *********
  * ----- *
  * |   | *
  * |   | *
  * ----- *
  *********

```

## Test cases below.

Input: `1`. Output:

```
      *
     ***
    ** **
   **   **
  *********
  * ----- *
  * |   | *
  * |   | *
  * ----- *
  *********

```

---

Input: `2`. Output:

```
        *
       ***
      ** **
     **   **
    *********
    * ----- *
    * |   | *
    * |   | *
    * ----- *
  ***********
  * ----- *
  * |   | *
  * |   | *
  * ----- *
  *********

```

---

Input: `3`. Output:

```
    *
   ***
  ** **
 **   **
*********
* ----- *
* |   | *
* |   | *
* ----- *
*************
    * ----- *
    * |   | *
    * |   | *
    * ----- *
  ***********
  * ----- *
  * |   | *
  * |   | *
  * ----- *
  *********

```

---

Input: `4`. Output:

```
      *
     ***
    ** **
   **   **
  *********
  * ----- *
  * |   | *
  * |   | *
  * ----- *
***********
* ----- *
* |   | *
* |   | *
* ----- *
*************
    * ----- *
    * |   | *
    * |   | *
    * ----- *
  ***********
  * ----- *
  * |   | *
  * |   | *
  * ----- *
  *********

```

---

Input: `10`. Output:

```
      *
     ***
    ** **
   **   **
  *********
  * ----- *
  * |   | *
  * |   | *
  * ----- *
***********
* ----- *
* |   | *
* |   | *
* ----- *
*************
    * ----- *
    * |   | *
    * |   | *
    * ----- *
  ***********
  * ----- *
  * |   | *
  * |   | *
  * ----- *
  ***********
    * ----- *
    * |   | *
    * |   | *
    * ----- *
*************
* ----- *
* |   | *
* |   | *
* ----- *
***********
  * ----- *
  * |   | *
  * |   | *
  * ----- *
***********
* ----- *
* |   | *
* |   | *
* ----- *
*************
    * ----- *
    * |   | *
    * |   | *
    * ----- *
  ***********
  * ----- *
  * |   | *
  * |   | *
  * ----- *
  *********

```

## Scoring

Code golf, shortest wins!

---

Trailing invisible stuff is allowed.

# Answer
# Charcoal, 48 bytes

```
ＦＮ«Ｍ×Ｘ±¹ιＩ§224ι←Ｂ⁹±⁶*↗↗↑↓²→⁵↖↑²←⁵↖»ＧＨ<⁵*Ｍ⁷←ＧＨ<⁴*

```

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

```
ＦＮ«

```

Draw `N` Blox.

```
Ｍ×Ｘ±¹ιＩ§224ι←

```

Adjust the horizontal position before drawing each Blox.

```
Ｂ⁹±⁶*

```

Draw the outer wall of the Blox.

```
↗↗↑↓²→⁵↖↑²←⁵↖»

```

Draw the inner wall of the Blox.

```
ＧＨ<⁵*Ｍ⁷←ＧＨ<⁴*

```

Raise the roof.
> 2 votes

# Answer
# JavaScript (ES6), 206 bytes

*Saved 2 bytes thanks to @kamoroso94*

```
f=(n,k=0)=>n--?f(n,k+1)+`${n?`
`:23456}0110`.replace(/./g,c=>' '.repeat('240204'[k%6])+'* ----- ,* |   | ,    ,   **,  ** *, **   *,********'.split`,`[c]+`*
`)+(k%6<2?'  ':'')+'*'.repeat(k?k%3<2?11:13:9):''

```

Try it online!
> 1 votes

# Answer
# SOGL V0.12, 53 bytes

```
ø.∫"│“3─wι«@*ο"²¹EiΕbK⁷‘╬$.F=?"¦○⌠Q°‘5nΓ;+}┼JGKh╬8;++

```

Try it Here!
> 0 votes

# Answer
# Python 2, 258 bytes

```
n=input()
l=[[4,2,4,0,2,0][(n-i)%6]for i in[0]+range(n)+[n-1]]
for i,v in enumerate(l[:-1]):s=v*' ';a,b=s+'* ----- *',s+'* |   | *';x,y=sorted([l[i+1],v]);print'\n'.join(([a,b,b,a]if i else[s+'    *',s+'   ***',s+'  ** **',s+' **   **'])+[' '*x+'*'*(9+y-x)])

```

Try it online!
> 0 votes

# Answer
# JavaScript (Node.js), 238 bytes

```
n=>{for(l=n>2&&2,s=i="";i<n;l=A)
s=(y=(p=" "[r="repeat"](A="240204"[i++%6]-(n<3)*2))+`* ----- *
`)+(x=p+`* |   | *
`)+x+y+" "[r](l>A?A:l)+"*"[r](9+Math.abs(A-l))+`
`+s
return p+`    *
${p}   ***
${p}  ** **
${p} **   **
${p}*********
`+s}

```

Try it online!
> 0 votes

---
Tags: code-golf, ascii-art
---


title: Reserved JavaScript

text:
# Question
Title: Reserved JavaScript
As of ECMAScript 2015, JavaScript has 33 reserved keywords, such as `break`, `const` and `new`, as well as 10 future reserved keywords, such as `let` and `await`.

Your task is to chain together the largest number of consecutive1 distinct reserved keywords2 while writing functional JavaScript code3.

1. Consecutive reserved keywords - reserved keywords that are separated only by whitespace and/or parentheses and/or curly braces.
2. Reserved keywords - any reserved or future reserved keywords as of ECMAScript 2015. Reserved keywords from older standards are excluded, a full list of allowed keywords is given below.
3. Functional code - your code should run (state your runtime, if necessary), eventually halt, and not throw any runtime errors.

If your code needs a specific runtime, the used reserved keywords must not be no-ops in the given environment.

## List of reserved keywords

```
await
break
case
catch
class
const
continue
debugger
default
delete
do
else
enum
export
extends
finally
for
function
if
implements
import
in
instanceof
interface
let
new
package
private
protected
public
return
static
super
switch
this
throw
try
typeof
var
void
while
with
yield
```

## Scoring & examples

Your score will be equal to the largest number of consecutive distinct reserved keywords.
In the case of equal scores, shortest source code in bytes wins. Commented sections and strings don't count towards reserved keywords, but count towards byte count.

```
// score: 3
if (true) 0; else throw function() {}
             ^------------------^
// score: 2
let foo = typeof typeof void typeof void 0;
                             ^---------^
// score: 0
/* typeof default debugger */

// score: 0, doesn't halt or debugger is no-op, depending on the environment
debugger;

```

Standard loopholes apply.

# Answer
# 43 words, 603 bytes

Uhm, is this a loophole? I have no idea how the hell this is legal JS, but it works and it uses every single keyword.

```
new (class await
{
    break(){}
    case(){}
    catch(){}
    const(){}
    continue(){}
    debugger(){}
    default(){}
    delete(){}
    do(){}
    else(){}
    enum(){}
    export(){}
    extends(){}
    finally(){}
    for(){}
    function(){}
    if(){}
    implements(){}
    import(){}
    in(){}
    instanceof(){}
    interface(){}
    let(){}
    package(){}
    private(){}
    protected(){}
    public(){}
    return(){}
    static(){}
    super(){}
    switch(){}
    this(){}
    throw(){}
    try(){}
    typeof(){}
    var(){}
    void(){}
    while(){}
    with(){}
    yield(){}
})

```
> 58 votes

# Answer
# 37 words

```
if (void this) {
  do {
    with (protected)
      for (public in private)
        typeof static instanceof new (function implements() {
          var let
          try {
            throw (class extends {} {})
          } catch (package) {
            yield
          } finally {
            debugger
          }
          return
        })()
    continue
    break
  } while (interface)
} else {
  switch (delete await) { default : 42 }
}

```

Keywords not used:

* `case` requires `:`
* `const` requires `=`
* `export` requires strict mode
* `import` requires strict mode
* `super` requires `constructor`
> 57 votes

# Answer
# 43 words, ~~302~~ 299 bytes

```
switch(void function(){for(const interface in public)do with(package)try{break}catch(private){if(typeof
this)throw yield static instanceof new class extends await{case(){return}super(){debugger}import(){}export(){}enum(){}}
else continue}finally{delete let}while(protected)var implements}){default:}

```
> 35 votes

# Answer
# ~~21~~ ~~24~~ 26 words, 185 bytes

*+~~1~~ 2 words thanks to Arnauld, and +1 to 12Me21!*

```
void(function(){do{with({})if(typeof true in this)throw{}instanceof new(class extends{}{})
else return delete{}
try{break}finally{yield}
continue
}while(false)})()
switch({}){case{}:{}}

```

Assuming I understood the challenge, this scores 24 words. The words without parentheses, brackets, and whitespace:

```
void function do with if typeof true in this throw instanceof new class extends else return delete try break finally yield continue while false switch case

```

### 24 words, 177 bytes

Without "true" and "false", which are apparently not keywords according to the question.

```
void(function(){do{with({})if(typeof{}in this)throw{}instanceof new(class extends{}{})
else return{}
try{break}finally{yield}
continue
}while(delete{})})()
switch({}){case{}:{}}

```

Words:

```
void function do with if typeof in this throw instanceof new class extends else return try break finally yield continue while delete switch case

```
> 10 votes

# Answer
# ~~38~~ 39

```
class await {}
class g extends await {
 constructor() {
  super()
 }
}
switch ({}) {
 case function(){
  for (let in public)
  do with(package){
   try{break}catch(private){
   if(typeof this)
    throw static instanceof new (class extends await {})
   else{continue}}finally{debugger}
  }while(void protected)
  var implements
  return
  yield delete interface
  const a=0
 }:
}

```

words from "super" to "const"

Golfed version:

```
class e{}class g extends e{constructor(){super()}}switch({}){case
function(){for(let in public)do with(package)try{break}catch(private){if(typeof
this)throw static instanceof new(class extends await{})
else{continue}}finally{debugger}while(void protected)
var implements
return
yield delete interface
const a=0}:}

```
> 7 votes

# Answer
# 21 words

(not sure about `let` and `await`)

```
var await=String, let=String;
switch (await) {
    case void typeof new await instanceof let in (function()
{do{try{return this
if((class extends{}{})){}else{break}}finally{(delete {})}}while(false)})():break;
}

```
> 4 votes

# Answer
# ~~14~~ ~~15~~ 16 Words with no brackets or newline

```
!function(){if(0);else do throw yield new public in void typeof this instanceof class await extends function async(){}{};while(0)}

```

Thank Bergi for +1
> 4 votes

# Answer
# 43 words, 300 bytes

```
with(this)try{let protected}catch(package){if(delete yield)for(const interface in typeof public)do{throw implements instanceof private}while(static)else debugger}finally{switch(void new class extends function(){return}{export(){var await}import(){break}super(){continue}enum(){}case(){}}){default:0}}

```

More readably:

```
with(this)
    try {
        let protected
    } catch(package){
        if(delete yield)
            for(const interface in typeof public)
                do {
                    throw implements instanceof private
                } while(static)
        else
            debugger
    } finally {
        switch(
          void new class extends function(){return} {
              export(){var await}
              import(){break}
              super(){continue}
              enum(){}
              case(){}
          }
        ){
            default:0
        }
    }

```

I had to use the "reserved word as method name" to deal with

* `case` (since I had already used `default` with my `swtich`),
* `export` and `import` (since module-mode is always strict, which disqualifies `with`)
* `super` (since it must be followed by a property access or placed in a `constructor` function), and
* `enum` (which can never be used at all, being a reserved word with no grammatically-valid use)
> 3 votes

# Answer
# 28 Words without brackets, 234 Bytes

Putting identifier names as method definition names was too obvious (for me at least), so I was looking for the longest consecutive distinct sequence of reserved words and whitespace in a code snippet.

I hope dead code after a `return` doesn't count as a loophole, but the code is still runnable if the used identifiers are declared.

```
function*_(){implements:{
let private
var public
return yield typeof static
delete protected
throw new interface in package
break implements
debugger
void this instanceof class await extends function async(){}{}
do
continue
while(0)}}

```

This exploits the fact that some of the future reserved keywords are only considered invalid in ES5.1's strict mode (apparently because engines didn't bother to block all of ES3's future reserved words so there was too much code using them out there on the web).

Similarly, the `async` and `await` tokens introduced in ES8 are only considered keywords in strict mode.
> 2 votes

---
Tags: code-challenge, javascript
---


title: Yet another "draw a box" Question

text:
# Question
Title: Yet another "draw a box" Question
The following problem is a common interview question, thus dull answers are discouraged. Go short or creative, best if both:

*Create the following pattern*

```
###########
##       ##
# #     # #
#  #   #  #
#   # #   #
#    #    #
#   # #   #
#  #   #  #
# #     # #
##       ##
###########

```

In case you cry "dupe", I see your point but this is a slight variation and I hope it differs enough to be greenlit.

# Answer
# Charcoal, 9 bytes

```
Ｐ¬↙×⁶#‖Ｏ¬

```

Try it online!
> 4 votes

# Answer
# Canvas, 14 bytes

```
６#×：＼ω↷１１╋１１╋┼

```

Try it here!

uses an older version of Canvas as in the latest one I undid a thing I undid with a logical reason..
> 2 votes

# Answer
# , 92 bytes

```
write(c(" ","#")[1+!!`[<-`(`[<-`(diag(11)+diag(11)[11:1,],c(1,11),,1),,c(1,11),1)],1,11,,"")

```

Try it online!

That is...a lot of `1`s.
> 2 votes

# Answer
# C (gcc), ~~129~~ 122 bytes

```
*s;f(j,k){for(j=puts(s="###########")-2;--j;)printf("#%*c%*c%*c\n",k-(k==5),k-5?35:32,10-k-k,35,k=j>5?10-j:j,35);puts(s);}

```

Try it online!
> 1 votes

# Answer
# Python 2, 100 bytes

```
for i in range(11):s=[" "]*11 if 0<i<10 else ["#"]*11;s[0]=s[10]=s[0+i]=s[10-i]="#";print ''.join(s)

```

Try it online!

**Explanation** :

```
for i in range(11):
  s=[" "]*11 if 0<i<10 else ["#"]*11;    #Ternary Expression to set cap lists
  s[0]=s[10]=s[0+i]=s[10-i]="#";    #Set '#'s in the right spots
  print ''.join(s)    #Convert to string and print

```
> 1 votes

---
Tags: code-golf, ascii-art, kolmogorov-complexity
---


title: Create an unlimited counterstring

text:
# Question
Title: Create an unlimited counterstring
A counterstring is some sort of self-describing test data that is used in software testing. Not sure it was actually invented by James Bach, but I know it from there.

The idea is as follows: the test data contains many asterisk (`*`). The number in front of the asterisk tells you how long the test data is at that point. If you need to know a position in the test data that is not an asterisk, find the last asterisk, look at the number before and add the number of digits that follow.

The sequence starts like this:

```
2*4*6*8*11*14*17*20*23*
             ^

```

As you can see, the marked asterisk is at position 14.

If a file happens to be truncated as follows

```
[...]2045*20

```

then you can derive that there is a limit of 2047 characters somewhere (2045 where the asterisk is plus 2 for `2` and `0`).

It's your task to create the shortest (this is ) program that outputs (std::out or file or whatever) an arbitrary long test string of that format. The length in characters is given as argument. The program shall support up to 2 GB test data (input value 2147483647 characters).

"Dangerous" positions in the 2 GB file:

```
8*11*
98*102*
998*1003*
9998*10004*
99998*100005*
999995*1000003*
9999995*10000004*
99999995*100000005*
999999995*1000000006*

```

This should answer @Leaky Nun's question if there is a decision to make between 995\*999\* and 995\*1000\* or similar: no.

The end of the 2 GB file with input value 2147483647 is:

```
2147483640*2147483

```

# Answer
# Pyth, ~~25~~ ~~17~~ ~~15~~ 14 bytes

```
<uu++GlN\*k)Qk

```

Try it online.

Length is taken via STDIN.
> 4 votes

# Answer
## Haskell, ~~60~~ 58 bytes

As a function we get:

```
f=length.show
iterate(\n->1+n+(f$n+1+f n))2>>=(++"*").show

```

### Full program, ~~72~~ 70 bytes

This outputs an infinite counterstring to STDOUT:

```
f=length.show
main=putStr$iterate(\n->1+n+(f$n+1+f n))2>>=(++"*").show

```

Inputting the length requires 20 additional bytes:

```
main=interact(\j->take(read j)$iterate(\n->1+n+(f$n+1+f n))2>>=(++"*").show)

```

This works up to your approximately your RAM size, since Haskell defaults numeric integral types to `Integer`.
> 4 votes

# Answer
# Python 3, ~~126~~ ~~114~~ 99 bytes

```
def f(x,s=''):
 i=t=2
 while len(s)<x:i+=len(str(t+i))-len(str(t));s+=str(t)+'*';t+=i
 print(s[:x])

```

A function that takes input via argument of the character count at which to truncate the string, and prints to STDOUT.

**How it works**

The difference between the numbers in the string is initially 2. Every time an order of magnitude is passed, this difference is increased by 1; this can be achieved by taking the difference between the number of digits of the current number and the number of digits of the current number added to the difference, which is 1 only when required. The function simply loops while the length of the string is less than the input, appends to the string and updates the difference and number as required, and then truncates before printing.

Try it on Ideone

**Infinite output version, 69 bytes**

```
s=i=2
while 1:i+=len(str(s+i))-len(str(s));print(end=str(s)+'*');s+=i

```
> 2 votes

# Answer
# Python 2, ~~74~~ ~~72~~ ~~66~~ ~~64~~ 61 Bytes

```
f=lambda n,i=2:"%d*"%i+f(n,len(`i+2`)-~i)[:n-2]if i<n*2else""

```

Takes an integer n and outputs a counterstring of length n.

### program version, 69 Bytes:

```
s,n,i="",input(),2
while i<2*n:s+="%d*"%i;i+=len(`i+2`)+1
print s[:n]

```

Takes an integer n from stdin and prints a counterstring of length n.

### Shorter, but only almost working, alternative version:

```
n,i=input(),2
while i<2*n:print("%d*"%i)[:n-i],;i+=len(str(i+2))+1

```
> 2 votes

# Answer
## PowerShell v5, 97 bytes

```
param($n)$l=1;for($i=0;$i-lt$n){$i+="$i*".length;if("$i".Length-gt$l){$i++;$l++};ac .\o "$i*" -n}

```

Takes input as a command-line argument `$n`, sets helper `$l` which we use to keep track of our integer length. Then, we loop from `0` up to `$n`. Each iteration, we increment `$i` by the `.length` of the string formed from `$i` and an asterisk. Then, if the `.length` of `$i` changed (e.g., we moved from 2 digits to 3 digits), we increment both the helper `$l`ength variable and `$i` (to account for the additional digit). We then use the `add-content` command to append `"$i*"` to file `.\o` in the current directory, with `-n`oNewLine.

### NB

* Requires v5, since the `-noNewLine` parameter was finally added in that version.
* PowerShell will automatically up-convert from `[int]` to `[double]` (no, I don't know why it doesn't go to `[long]`), so this will properly handle input up to and greater than `2147483648`, without problem. Theoretically, it will handle input somewhere up to around `1.79769313486232E+308` (max value of `[double]`) before complaining, but I expect the disk to fill up before that happens. ;-)
* Due to the loop conditional checking, this will output to the file a *minimum* of the input length. For example, for input `10` this will output `2*4*6*8*11*`, since `11` is the first `$i` value greater than the input.

---

### PowerShell v2+, also 97 bytes (non-competing)

```
param($n)$l=1;-join(&{for($i=0;$i-lt$n){$i+="$i*".length;if("$i".Length-gt$l){$i++;$l++};"$i*"}})

```

Instead of sending to a file, this encapsulates the loop iterations and then `-join`s them together into a string. This allows it to work for versions earlier than v5. However, since .NET defines a `[string]` with a constructor like `String(char c,Int32 length)`, this version does *not* satisfy the max input requirement, since the output string will overflow and barf.

Also, you may not want to have a ~2GB string floating around in your pipeline. Just sayin'.
> 1 votes

# Answer
# R, 92 bytes

```
    N=nchar;f=function(n){z=0;y="";while(z<n){z=z+N(z+N(z)+1)+1;y=paste0(y,z,"*")};strtrim(y,n)}

```

Example output:

> f(103) \[1\] "2\*4\*6\*8\*11\*14\*17\*20\*23\*26\*29\*32\*35\*38\*41\*44\*47\*50\*53\*56\*59\*62\*65\*68\*71\*74\*77\*80\*83\*86\*89\*92\*95\*98\*102\*1"
> 1 votes

# Answer
# Jelly, ~~22~~ ~~19~~ 18 bytes

```
2µṾL+®‘¹©=¡=µ³#j”*

```

Try it online!

Find the first `n` numbers in the string then join the list with an asterisk. This will always be longer than `n` which was allowed by OP in the comments.

The program selectively updates the register with the current number in the sequence in the `#` loop with `¹©=¡`. I was hoping this could be shorter, by putting `©` after the second `µ` for example, but unfortunately that doesn't work and I couldn't figure out any thing shorter.
> 1 votes

---
Tags: code-golf, counting
---


title: ASCII Maya Numbers

text:
# Question
Title: ASCII Maya Numbers
Write a program or function which, given a positive integer as input, outputs the representation of that integer in Maya numerals.

# Maya numerals

Maya numerals is a vigesimal system (base 20) using only 3 symbols :

* `< >` for *Zero* (The correct symbol is some sort of shell that can't easily be represented using ASCII).
* `.` for *One*
* `----` for *Five*

Numbers are written vertically in powers of 20, and numbers between 0 and 19 are written as stacks of *fives* and *ones*. You shall refer to the Wikipedia article for more details.

As an example, here are the numbers between 0 and 25, separated by commas:

```
                                                                                .    ..  ...  ....
                                                        .    ..  ...  .... ---- ---- ---- ---- ----  .    .    .    .    .    .
                               .    ..  ...  .... ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
<  >, .  , .. ,... ,....,----,----,----,----,----,----,----,----,----,----,----,----,----,----,----,<  >, .  , .. ,... ,....,----

```

# Inputs

* Inputs always are positive integers between 0 and 2147483647 (2^31 - 1).
* You may take the input from STDIN, as a command line argument, function parameter or anything similar.

# Outputs

* Each line is at most 4 characters long. `< >` and `----` should always be printed as given here (4 characters long each).
* Ones(`.`) must be centered on the line. If there are 1 or 3 `.`, since perfect horizontal alignment is impossible, it does not matter whether they are one column to the left or one column to the right or the center.
* There must be exactly one empty line between different powers of 20, regardless of the height of the stacks in the power of 20s. For example, the correct output for 25 and 30 are :

```
        .
 .
       ----
----   ----

```
* No leading or trailing lines allowed.
* Outputs must be printed exactly like they are in the examples given.

### Test cases

* Each individual number between 0 and 25 given as example above.
* Input: `42`

Output:

```
 ..

 ..

```
* Input: `8000`

Output:

```
 .

<  >

<  >

<  >

```
* Input: `8080`

Output:

```
 .

<  >

....

<  >

```
* input: `123456789`

Output:

```
 .

...
----
----
----

 .
----
----

 ..
----
----

 .

....
----
----
----

....
----

```
* Input: `31415`

Output:

```
...

...
----
----
----

----
----

----
----
----

```
* Input: `2147483647`

Output:

```
 .

...
----
----

 .
----
----

 .

----
----
----

....
----

 ..

 ..
----

```

# Scoring

This is , so the shortest code in bytes wins.

# Answer
# Pyth, 41 bytes

```
j+bbm|jb_m.[\ 4kc:*d\.*5\.*4\-4"<  >"jQ20

```

Try it online: Demonstration

### Explanation:

```
                                     jQ20   convert input to base 20
    m                                       map each value d to:
                  *d\.                         string of d points
                 :    *5\.*4\-                 replace 5 points by 4 -s
                c             4                split into groups of 4
         m.[\ 4k                               center each group
        _                                      invert order
      jb                                       join by newlines
     |                         "<  >"          or if 0 use "<  >"
j+bb                                        join by double newlines

```
> 3 votes

# Answer
# Perl, ~~125~~ 117 bytes

```
$-=<>;{$_=($-%20?(""," .
"," ..
","...
","....
")[$-%5]."----
"x($-/5&3):"<  >
").$_;($-/=20)&&($_=$/.$_,redo)}print

```

Thanks to Dom Hastings for helping me save 8 bytes.
> 5 votes

# Answer
# Mathematica ~~185 182 171~~ 153

With 18 bytes saved thanks to Arcinde's suggestion to use anonymous functions,

```
c=Column;c[If[#>0,{q,r}=#~QuotientRemainder~5;c@{{""," ."," .."," ...","...."}[[r+1]],c@{{""},{d="----"},{d,d},{d,d,d}}[[q+1]]},"< >"]&/@#~IntegerDigits~20]&

```

**Example**

```
c[If[# > 0, {q, r} = #~QuotientRemainder~5; c@{{"", " .", " ..", " ...", "...."}[[r + 1]], c@{{""}, {d = "----"}, {d, d}, {d, d, d}}[[q + 1]]}, "< >"] & /@ #~IntegerDigits~20] &[31415]

```

---

**Checking**

The decimal number, 31415, expressed in base 20. Mathematica employs lower case for this.

```
BaseForm[31415, 20]

```

---

The decimal digits corresponding to the above base 20 number.

```
IntegerDigits[31415,20]

```

> {3, 18, 10, 15}

---

**Another example**

```
IntegerDigits[2147483607, 20]

```

> {1, 13, 11, 1, 15, 9, 0, 7}

```
c[If[# > 0, {q, r} = #~QuotientRemainder~5;c@{{"", " .", " ..", " ...","...."}[[r + 1]], c@{{""}, {d = "----"}, {d, d}, {d, d, d}}[[q + 1]]},"< >"] & /@ #~IntegerDigits~20] &[2147483607]

```
> 4 votes

# Answer
# JavaScript ES6, 143 bytes

Loads of bytes added because need to `console.log`, could save another 23 bytes without it.

```
n=>console.log((d=(x,s='',l=1,j=x/l|0)=>s+(j>19?d(x,s,l*20)+`

`:'')+((j=j%20)?(' '+`.`.repeat(j%5)).slice(-4)+`
----`.repeat(j/5):'<  >'))(n))

```
> 4 votes

# Answer
## JavaScript (ES6), 157 bytes

The newlines are significant and are counted as 1 byte each. Since printing to STDOUT is required, `console.log` cost me a few bytes there.

```
f=i=>console.log([...i.toString(20)].map(j=>(!(j=parseInt(j,20))||j%5?[`<  >`,` .`,` ..`,`...`,`....`][j%5]+`
`:'')+`----
`.repeat(j/5)).join`
`.slice(0,-1))

```

### Demo

For demonstration purposes I'll write an ES5 version so it works in all browsers:

```
// Snippet stuff
console.log = function(x) {
  O.innerHTML = x;
}
document.getElementById('I').addEventListener('change', function() {
  f(this.valueAsNumber);
}, false);

// Actual function
f = function(i) {
  console.log(i.toString(20).split('').map(function(j) {
    return (! (j = parseInt(j, 20)) || j % 5 ? ['<  >', ' .', ' ..', '...', '....'][j % 5] + '\n' : '') + '----\n'.repeat(j / 5);
  }).join('\n').slice(0,-1));
}
```

```
<input type=number min=0 max=2147483647 value=0 id=I>

<pre><output id=O></output></pre>
```
> 3 votes

# Answer
# CJam, ~~82~~ 76 bytes

```
li{_K%[""" .
"" ..
""...
""....
"]1$5%='-4*N+2$5/3&*+"<  >
"?N+L+:L;K/}h;L);

```

My first CJam program, basically just a transliteration of my Perl answer to CJam.

Try online

Multi-line with comments:

```
li            # read input
{             # start of do-while loop
  _K%         # check if this base-20 digit is a zero
    [""" .
    "" ..
    ""...
    ""....
    "]1$5%=   # push dots for 1s onto stack
    '-4*N+2$5/3&*+    # push lines for 5s onto stack

    "<  >
    "         # push zero on stack
  ?           # ternary if test (for digit equals zero)
  N+L+:L;     # pre-concatenate string with output plus newline
  K/          # divide by 20
}h            # end of do while loop
;L);          # push output string on stack, chop off trailing newline

```
> 2 votes

# Answer
# Python 2.x, 142 bytes:

```
def m(n):
 h=[[""," "*(2-n%5/2)+"."*(n%5)+"\n"][n%5!=0]+"----\n"*(n%20/5),"<  >\n"][n%20==0]
 n/=20
 if n>0:
  h=m(n)+"\n\n"+h
 return h[:-1]

```

Example:

```
>>> print m(2012)
----

<  >

 ..
----
----
>>>

```

Edit: trailing line...
> 2 votes

# Answer
## PHP, 220 bytes

Same approach as my JavaScript answer. PHP has built-in functions for everything.

Takes 1 input from the command line (i.e. STDIN), as seen with `$argv[1]`:

```
<?=rtrim(implode("\n",array_map(function($j){return(!($j=base_convert($j,20,10))||$j%5?['<  >', ' .', ' ..', '...', '....'][$j%5]."\n":'').str_repeat("----\n",$j/5);},str_split(base_convert($argv[1],10,20)))));

```
> 1 votes

# Answer
## C - 149

```
f(v){v/20&&(f(v/20),puts("\n"));if(v%=20)for(v%5&&printf("%3s%s","...."+4-v%5,v/5?"\n":""),v/=5;v--;v&&puts(""))printf("----");else printf("<  >");}

```

Uses recursion to print most significant numbers first. Then either prints zero or prints all dots with one *clever* `printf` and all fives in a loop. I am not sure if I can avoid using if-else here.

The downside of clever printf is that 1 and 3 are not aligned to each other:

Result for 23 is:

```
  .

...

```

## ~~119~~ incorrect solution - trailing newline

```
f(v){v/20&&(f(v/20),puts(""));if(v%=20)for(v%5&&printf("%3s\n","...."+4-v%5),v/=5;v--;)puts("----");else puts("<  >");}

```
> 1 votes

# Answer
# PHP, ~~202~~ 192 bytes

```
function m($n){return(($c=($n-($r=$n%20))/20)?m($c)."\n":"").
($r?(($q=$r%5)?substr(" .   .. ... ....",$q*4-4,4)."\n":"").
str_repeat("----\n",($r-$q)/5):"<  >\n");}
echo rtrim(m($argv[1]),"\n");

```

It gets the input from the first command line argument.

The complete source code, with comments and tests, is available on github.
> 1 votes

# Answer
# Python 2, 114 bytes

This answer is based on Jakube's Pyth answer and Locoluis's Python 2 answer.

```
def f(n):d,m=divmod(n%20,5);h=[" "*(2-m/2)+"."*m+"\n----"*d,"<  >"][n%20<1];n/=20;return(f(n)+"\n\n"if n else"")+h

```
> 1 votes

# Answer
# Jelly, ~~50~~ ~~49~~ 47 bytes

```
b5µṪ”.x⁶;$L<3Ɗ¡ṭ⁾--;UW¤ẋ$Ẏ$L¡Ṛø“<  >”WµẸ?
b20Ç€

```

Try it online!

`...` is now left aligned thanks to user202729's point.

When you trick yourself into thinking `< >` is a palindrome...
> 0 votes

---
Tags: code-golf, number, base-conversion
---