title: Move to the printable ASCII front

text:
# Question
Title: Move to the printable ASCII front
### Background

The move-to-front transform (MTF) is a data encoding algorithm designed to improve the performance of entropy encoding techniques.

In the bzip2 compression algorithm, it is applied after the Burrows–Wheeler transform (as seen in Burrows, Wheeler and Back), with the objective of turning groups of repeated characters into small, easily compressible non-negative integers.

### Definition

For the purpose of this challenge, we'll define the printable ASCII version of the MTF as follows:

Given an input string **s**, take an empty array **r**, the string **d** of all printable ASCII characters (0x20 to 0x7E) and repeat the following for each character **c** of **s**:

1. Append the index of **c** in **d** to **r**.
2. Move **c** to the front of **d**, i.e., remove **c** from **d** and prepend it to the remainder.

Finally, we take the elements of **r** as indexes in the *original* **d** and fetch the corresponding characters.

### Step-by-step example

```
INPUT: "CODEGOLF"

0. s = "CODEGOLF"
   d = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
   r = []
1. s = "ODEGOLF"
   d = "C !\"#$%&'()*+,-./0123456789:;<=>?@ABDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
   r = [35]
2. s = "DEGOLF"
   d = "OC !\"#$%&'()*+,-./0123456789:;<=>?@ABDEFGHIJKLMNPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
   r = [35 47]
3. s = "EGOLF"
   d = "DOC !\"#$%&'()*+,-./0123456789:;<=>?@ABEFGHIJKLMNPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
   r = [35 47 37]
4. s = "GOLF"
   d = "EDOC !\"#$%&'()*+,-./0123456789:;<=>?@ABFGHIJKLMNPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
   r = [35 47 37 38]
5. s = "OLF"
   d = "GEDOC !\"#$%&'()*+,-./0123456789:;<=>?@ABFHIJKLMNPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
   r = [35 47 37 38 40]
6. s = "LF"
   d = "OGEDC !\"#$%&'()*+,-./0123456789:;<=>?@ABFHIJKLMNPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
   r = [35 47 37 38 40 3]
7. s = "F"
   d = "LOGEDC !\"#$%&'()*+,-./0123456789:;<=>?@ABFHIJKMNPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
   r = [35 47 37 38 40 3 45]
8. s = ""
   d = "FLOGEDC !\"#$%&'()*+,-./0123456789:;<=>?@ABHIJKMNPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
   r = [35 47 37 38 40 3 45 41]

OUTPUT: "COEFH#MI"

```

### Task

Write a program or function that implements the printable ASCII MTF (as defined above).

### Test cases

```
Input:  Programming Puzzles & Code Golf
Output: Prpi"do lp%((uz rnu&3!P/o&$U$(p

Input:  NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN BATMAN!
Output: Na! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !!"DDUP"%'

Input:  Two more questions and I have bzip2 in less than 100 bytes!
Output: Twp#o"si$sv#uvq(u$(l#o#W!r%w+$pz,xF%#,"x(. #0--'$GG ".z(**:

```

### Additional rules

* You cannot use any built-in operator that computes the MTF of a string.
* Your code may print a trailing newline if you choose STDOUT for output.
* Your code has to work for any input of 1000 or less printable ASCII characters (0x20 to 0x7E).
* Standard code golf rules apply. The shortest submission in bytes wins.

# Answer
# CJam, 20

```
'¡,q{_C#c' ,C+@|}fC;

```

Try it online

**Explanation:**

```
'¡,      make a string of characters with codes from 0 to 160 (a modified "d")
         could have been to 126 but stackexchange doesn't like the DEL character
q        read the input (s)
{…}fC    for each character C in s
  _      duplicate the d string
  C#     find the index of C in d
  c      convert to character (this is the result)
  ' ,    make a string of characters from 0 to 31
  C+     append C to the string
  @      bring d to the top
  |      set union, preserving order; effectively, C is moved to position 32
         this is the updated d string
;        pop the last d

```
> 6 votes

# Answer
# Ostrich, ~~46~~ 45 chars

Don't have a version number in the header because this is actually just the latest commit. I added the `O` (ascii code to string) operator after releasing the latest version (but still before this challenge was posted).

```
{a95,{32+O}%:d3@{:x\.3@?3@\+\x-x\+}/;{d=}%s*}

```

Explanation:

```
a             this is the "r" array (a is short for [], empty array)
95,{32+O}%:d  this is the "d" array
3@{...}/      for each character in the input (as an "argument")...
  :x            store in variable x (stack is now [r d c])
  \.3@?         find index in d     (stack is now [r d idx])
  3@\+          append index to r   (stack is now [d modified_r])
  \x-           remove char from d, and then...
  x\+           prepend char to d   (stack is now [modified_r modified_d])
;             throw away modified_d
{d=}%         map r to indices of (original) d
s*            join (s is short for ``, empty string)

```
> 6 votes

# Answer
# SWI-Prolog, ~~239~~ ~~197~~ 189 bytes

```
a(S):-l([126],X),a(S,X,[],R),b(R,X).
a([A|T],X,S,R):-nth0(I,X,A,Z),(a(T,[A|Z],[I|S],R);R=[I|S]).
b([A|T],X):-(b(T,X);!),nth0(A,X,E),put(E).
l([B|R],Z):-A is B-1,X=[A,B|R],(A=32,Z=X;l(X,Z)).

```

Example: `a(`Two more questions and I have bzip2 in less than 100 bytes!`).` outputs:

```
Twp#o"si$sv#uvq(u$(l#o#W!r%w+$pz,xF%#,"x(. #0--'$GG ".z(**:

```

(and `true .` after it, obviously)

**Note:** your SWI-Prolog version has to be one of the newer ones in which the backquote ``` represents codes strings. Code strings used to be represented with double-quotes `"` in older versions.
> 3 votes

# Answer
# Python 3, 88

```
*d,=range(127)
for c in input():y=d.index(ord(c));d[:32]+=d.pop(y),;print(chr(y),end='')

```

Using some ideas from my CJam solution.
-4 bytes belong to Sp3000 :)
> 3 votes

# Answer
# Python 2, ~~137~~ ~~110~~ 104

Wasn't hard to implement, but *maybe* still golfable?

**Try it here**

```
e=d=map(chr,range(32,127))
r=""
for c in raw_input():n=e.index(c);r+=d[n];e=[e[n]]+e[:n]+e[n+1:]
print r

```
> 2 votes

# Answer
# Stax, <sup>~~18 15 14~~</sup> 13 bytes

```
ä╦@╥◄/J[;&πi⌡

```

Run and debug it

-3 bytes using a map, and a simpler algorithm.

-1 byte borrowing from Kevin Cruijssen's answer.

-1 byte by simplifying a stack operation.
> 2 votes

# Answer
# Perl 5, 96 bytes

```
sub{$d=$o=join'',map chr,32..126;join'',map{$d=~s/\Q$_//;$d=$_.$d;substr$o,length$`,1}pop=~/./g}

```

Try it online!

Ungolfed with some explanation:

```
sub{
  $d=$o=join'',map chr,32..126;  #init strings d and o to chars between 0x32-0x7e
  join('',                       #join array of chars to string
    map {                        #map array of input chars
      $d=~s/\Q$_//;              #pick out current input char from d, \Q to avoid
                                 #...special regexp meaning of some chars
      $d=$_.$d;                  #prepend current input char to d
      substr$o,length$`,1        #map to char in original dict o at position of
                                 #...current input char in d
    }
    pop=~/./g                    #array of input chars
  )                              #return joined chars
}

```

The `\Q` isn't needed for the given test cases since they don't contain `.` (period) or other chars with special meaning in regular expressions. If they did, `\Q` is needed.
> 2 votes

# Answer
# Pyth, 24 bytes

```
JK>95CM127s@LKxL~J+d-Jdz

```

Demonstration. Test Harness.

The first bit. `JK>95CM127` sets up the necessary list and saves it to `J` and `K`. `~J+d-Jd` performs the list updating, while `xL ... z` maps the input characters to their positions in the list. Finally, `s@LK` converts those indexes to characters in the original list.
> 1 votes

# Answer
# Haskell, 120 bytes

```
e#s=[b|(b,a)<-zip[0..]s,a==e]!!0
a=[' '..'~']
f=snd.foldl(\(d,r)e->(e:take(e#d)d++tail(drop(e#d)d),r++[a!!(e#d)]))(a,[])

```

Usage example: `f "CODEGOLF"` -\> `"COEFH#MI"`

How it works: `#` is an index function that returns the position of `e` in `s` (can't use Haskell's native `elemIndex` because of an expensive `import`). The main function `f` follows a fold pattern where it updates the position string `d` and result string `r` as it walks through the input string.
> 1 votes

# Answer
# 05AB1E, 16 bytes

```
žQDUIεXskXyìÙU}è

```

Output as a list of characters.

Try it online or verify all test cases.

**Explanation:**

```
žQ           # Push the printable ASCII constant string
  DU         # Duplicate it, and pop and store this copy in variable `X`
    Iε       # Map over the characters of the input:
      Xsk    #  Get the index of the current character in `X`
      Xyì    #  Then prepend the current character to `X`
         Ù   #  Uniquify the characters in this new string
          U  #  Pop and store it as new `X`
     }è      # After the map: index the mapped integers into the printable ASCII string
             # (after which the resulting character list is output implicitly)

```
> 1 votes

---
Tags: code-golf, string, compression, encoding
---


title: Illustrate the square of a binomial

text:
# Question
Title: Illustrate the square of a binomial
Given (by any means) two different natural numbers (of any reasonable size), output (by any means) the square of their sum as in the examples below:

Given 4 and 3, output:

```
12 12 12 12  9  9  9
12 12 12 12  9  9  9
12 12 12 12  9  9  9
16 16 16 16 12 12 12
16 16 16 16 12 12 12
16 16 16 16 12 12 12
16 16 16 16 12 12 12

```

Given 1 and 3, output:

```
3 9 9 9
3 9 9 9
3 9 9 9
1 3 3 3

```

Whitespace may vary within reason but the columns must be left-aligned, right-aligned, or (pseudo-)centered.

A trailing newline is fine, but standard loopholes are not.

This is so include a header like `# LanguageName, 123` in your answer, where the number is chars (bytes for languages that are not text-based). Packing code to large Unicode chars is not allowed.

---

**Bonus:** -3 if your code outputs just one square when one of the numbers is 0; e.g. given 0 and 3, output:

```
9 9 9
9 9 9
9 9 9

```

# Answer
> 14 votes
## J, 9 bytes - 3 = 6

```
#~@|.*/#~

```

Inspired by @NBZ's APL answer, golfed down by @randomra. This defines a verb that takes in an array of numbers. It's used as follows:

```
   (#~@|.*/#~) 4 3
12 12 12 12  9  9  9
12 12 12 12  9  9  9
12 12 12 12  9  9  9
16 16 16 16 12 12 12
16 16 16 16 12 12 12
16 16 16 16 12 12 12
16 16 16 16 12 12 12

```

I also claim the 3-byte bonus, since an input of 0 produces sub-matrices of size zero:

```
   (#~@|.*/#~) 4 0
16 16 16 16
16 16 16 16
16 16 16 16
16 16 16 16
   (#~@|.*/#~) 0 3
9 9 9
9 9 9
9 9 9

```

## Explanation

J has a definite edge in this challenge. In addition to eating array manipulation problems for breakfast, it prints 2D matrices in the correct format by default.

```
       #~  Replicate each number n in input n times
#~@|.      The same for reversed input
     */    Compute their multiplication table

```

# Answer
> 10 votes
# Octave, 45 bytes - 3 = 42

```
s=@(m,n)[a=ones(n,1)*n;b=ones(m,1)*m].*[b;a]'

```

### Explanation

This constructs two vectors (let's assume `m = 4` and `n = 3`):

`ones(n, 1)` constructs an array of ones of size `n x 1`, so multiplying the ones by `n` we get:

```
ones(n, 1) * n => [3 3 3]' (where ' is transpose... n x 1 is a column vector)

a = [3 3 3  4 4 4 4]'   %// a is a column vector
b = [4 4 4 4  3 3 3]    %// b is a row vector

```

Then the vectors are multiplied in an element-wise fashion, with automatic broadcast expansion so that the 7-element vectors produce a 7x7-element matrix:

```
    [3] .* [4 4 4 4 3 3 3]
    [3]
    [3]
    [4]
    [4]
    [4]
    [4]

```

For example, multiplication of the first row of `a` by `b` gives:

```
    [3] .* [4 4 4 4 3 3 3] = [12 12 12 12  9  9  9]

```

And similarly for the remaining rows of `a`.

### Output:

```
>> s(4,3)
ans =

   12   12   12   12    9    9    9
   12   12   12   12    9    9    9
   12   12   12   12    9    9    9
   16   16   16   16   12   12   12
   16   16   16   16   12   12   12
   16   16   16   16   12   12   12
   16   16   16   16   12   12   12

>> s(3,0)
ans =

   9   9   9
   9   9   9
   9   9   9

```

You can try it here on ideone

# Answer
> 10 votes
# Dyalog APL, 10-3 = 7

Inspired\* by this answer where the arguments are replicated and then used in a multiplication table:

```
⊖∘.×⍨(/⍨⎕)

```

Issues a prompt (`⎕:`) and evaluates any expression entered then. (For security reasons, this doesn't work on TryAPL but it does work on NGN/APL.)
`/⍨` Replicates its argument itself times (`/⍨4 3` ⇔ `3 3 3 4 4 4 4`)
`∘.×⍨` Creates a multiplication table.
Flips upside down.

This happens to work on any length input (input is indented 6 spaces, output is at left margin):

```
      ⊖∘.×⍨(/⍨⎕)
⎕:
      ⍬      ⍝ Empty list (the square of nothing)
      ⊖∘.×⍨(/⍨⎕)
⎕:
      0      ⍝ 0² = 0
      ⊖∘.×⍨(/⍨⎕)
⎕:
      0 1      ⍝ (0+1)² = 1²
1
      ⊖∘.×⍨(/⍨⎕)
⎕:
      2 3      ⍝ (2+3)² = 2² + 3²
6 6 9 9 9
6 6 9 9 9
6 6 9 9 9
4 4 6 6 6
4 4 6 6 6
      ⊖∘.×⍨(/⍨⎕)
⎕:
      1 2 3      ⍝ (1+2+3)² = 1² + 2(1×2) + 2(1×3) + 2² + 2(2×3) + 3²
3 6 6 9 9 9
3 6 6 9 9 9
3 6 6 9 9 9
2 4 4 6 6 6
2 4 4 6 6 6
1 2 2 3 3 3
      ⊖∘.×⍨(/⍨⎕)
⎕:
      ⍳4    ⍝ Integers 1 through 4
4 8 8 12 12 12 16 16 16 16
4 8 8 12 12 12 16 16 16 16
4 8 8 12 12 12 16 16 16 16
4 8 8 12 12 12 16 16 16 16
3 6 6  9  9  9 12 12 12 12
3 6 6  9  9  9 12 12 12 12
3 6 6  9  9  9 12 12 12 12
2 4 4  6  6  6  8  8  8  8
2 4 4  6  6  6  8  8  8  8
1 2 2  3  3  3  4  4  4  4

```

---

\*Originally, I had a different solution in mind: Each rectangle is created separately by creating a multiplication table for each combination of the two arguments. Then the four squares are mended together vertically and horizontally. It looks like this:

```
,/⍪⌿⊖∘.(,⍴×)⍨⎕

```

Prompt, as above.
`,⍴×<` Combine (`,`) the args and use that to shape () a rectangle filled with their product (`×`).
`∘.(`…`)⍨` Create a table where each cell is whatever is specified in `(`…`)`
Flip vertically.
`⍪⌿` Combine cells vertically.
`,/` Combine cells horizontally.

# Answer
> 7 votes
# R, 31 - 3 = 28

```
rev(b<-rep(a<-scan(),a))%*%t(b)

```

Explanation:

```
           a<-scan()            # take numeric input and store as vector a
    b<-rep(         ,a)         # repeat each numeric input by itself and store as vector b
rev(                   )        # the reverse of vector b
                        %*%     # matrix multiplication
                           t(b) # the transposed of vector b

```

This also works for more than two numbers. For example, the output for (5,3,2) looks like this:

```
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]   10   10   10   10   10    6    6    6    4     4
 [2,]   10   10   10   10   10    6    6    6    4     4
 [3,]   15   15   15   15   15    9    9    9    6     6
 [4,]   15   15   15   15   15    9    9    9    6     6
 [5,]   15   15   15   15   15    9    9    9    6     6
 [6,]   25   25   25   25   25   15   15   15   10    10
 [7,]   25   25   25   25   25   15   15   15   10    10
 [8,]   25   25   25   25   25   15   15   15   10    10
 [9,]   25   25   25   25   25   15   15   15   10    10
[10,]   25   25   25   25   25   15   15   15   10    10

```

# Answer
> 5 votes
# Haskell, ~~153~~ 125 bytes - 3 = 122

```
(#)=replicate
d=length.show
y%x=unlines$(>>= \n->(1+d(x*x+y*y)-d n)#' '++show n)<$>x#(y#(x*y)++x#(x*x))++y#(y#(y*y)++x#(x*y))

```

Half of the code is for output formatting. It works for arbitrary large integers. Example output:

```
> putStrLn $ 4 % 3
12 12 12 12  9  9  9
12 12 12 12  9  9  9
12 12 12 12  9  9  9
16 16 16 16 12 12 12
16 16 16 16 12 12 12
16 16 16 16 12 12 12
16 16 16 16 12 12 12

> putStrLn $ 6 % 0
36 36 36 36 36 36
36 36 36 36 36 36
36 36 36 36 36 36
36 36 36 36 36 36
36 36 36 36 36 36
36 36 36 36 36 36

```

Sometimes there's an additional whitespace between the numbers, because I'm calculating the space needed based on `x*x+y*y` instead of `max (x*x) (y*y)`, e.g.

```
> putStrLn $ 2 % 3
  6  6  9  9  9
  6  6  9  9  9
  6  6  9  9  9
  4  4  6  6  6
  4  4  6  6  6

```

But it's at most one whitespace.

# Answer
> 4 votes
# CJam, 27 bytes - 3 = 24

```
q:L~_]ze~_ff{*sL,2*Se[}W%N*

```

Takes input as a CJam style array. It uses a bit more spacing than necessary, but I think it's "within reason", and it's always properly right aligned.

Test it here.

## Explanation

```
q:L    e# Read the input and store it in L.
~_     e# Evaluate the input, pushing [A B] onto the stack and duplicate it.
]z     e# Wrap both in an array and transpose it to get [[A A] [B B]].
e~     e# Run-length decode, getting A copies of A and B copies of B.
_ff{   e# Double map over each pair of entries in this new array...
  *s   e#   Multiply the two values.
  L,2* e#   Push twice the length of the input string.
  Se[  e#   Pad the result to this width with spaces (from the left).
}
W%     e# Reverse the resulting matrix to get the correct orientation.
N*     e# Join the rows with linefeed characters.

```

# Answer
> 4 votes
# Mathematica 56-3 = 53

*Update*: I added a second method, of precisely the same code size, that uses a named function. It employs an `Array` rather than a `Table` but follows the same logic. (See below.)

**Method 1**

This makes a table of products, the factors of which depend on the row, column values. The pair of numbers is entered as a list of integers. Anonymous functions such as the following, are most useful if they are used only once in a program. Otherwise it makes more sense to use a named function.

```
Grid@Table[If[r>#2,#,#2]If[c>#,#2,#],{r,#+#2},{c,#+#2}]&

```

Each factor is an If-then statement:

* `If[r>#2,#,#2]` means, "If the row number is greater than the second input, use the first input as the factor, otherwise use the second input.
* `If[c>#,#2,#]` means, "If the column number is greater than the first input, use the second input as the factor, otherwise use the first input.

---

Example 1

```
 Grid@Table[If[r>#2,#,#2]If[c>#,#2,#],{r,#+#2},{c,#+#2}]&@@{5,3}

```

---

Example 2

```
Grid@Table[If[r>#2,#,#2]If[c>#,#2,#],{r,#+#2},{c,#+#2}]&@@{0,3}

```

---

**Method 2** (Also 56-3 = 53)

This works similarly to Method 1. But it requires less code when called. And the cells are addressable, unlike cells in a table. This method is better to use if the function will be used more than once.

```
a_~f~b_:=Grid@Array[If[#>a,a,b]If[#2>a,b,a]&,{a+b,a+b}]

```

The examples from above are produced by the following:

Ex 1:

```
f[4,3]

```

Ex 2:

```
f[0,3]

```

# Answer
> 4 votes
# C function (using glibc), 122 bytes - 3 = 119

Mostly straightforward implementation with 2 loops. I expect there are some golfing opportunities I have missed here:

```
f(n,m,x,y){for(x=0;x<n+m;x+=puts(""))for(y=0;y<n+m;y++)printf(" %*d",snprintf(0,0,"%d",n>m?n*n:m*m),(x<m?m:n)*(y<n?n:m));}

```

Inputs are passed in the first two parameters of the function, the other two are dummies. Columns are right-aligned.

Note glibc `puts()` always seems to return the number of bytes written including implicit trailing newline, which is what we need here. No guarantees this will work with any other libc.

In a full program:

```
f(n,m,x,y){for(x=0;x<n+m;x+=puts(""))for(y=0;y<n+m;y++)printf(" %*d",snprintf(0,0,"%d",n>m?n*n:m*m),(x<m?m:n)*(y<n?n:m));}

int main (int argc, char **argv) {
    if (argc == 3) {
        f(atoi(argv[1]),atoi(argv[2]));
    }
}

```

Compile as `gcc sqrbin.c -o sqrbin` (or `make sqrbin`). Warnings may safely be ignored.

### Example output:

```
$ ./sqrbin 4 3
 12 12 12 12  9  9  9
 12 12 12 12  9  9  9
 12 12 12 12  9  9  9
 16 16 16 16 12 12 12
 16 16 16 16 12 12 12
 16 16 16 16 12 12 12
 16 16 16 16 12 12 12
$ ./sqrbin 4 0
 16 16 16 16
 16 16 16 16
 16 16 16 16
 16 16 16 16
$

```

# Answer
> 4 votes
# Octave, 34 - 3 = 31

```
@(a)rot90(b=repelems(a,[1,2;a]))*b

```

**Examples:**

```
octave:1> f = @(a)rot90(b=repelems(a,[1,2;a]))*b;
octave:2> f([4,3])
ans =

   12   12   12   12    9    9    9
   12   12   12   12    9    9    9
   12   12   12   12    9    9    9
   16   16   16   16   12   12   12
   16   16   16   16   12   12   12
   16   16   16   16   12   12   12
   16   16   16   16   12   12   12

octave:3> f([0,3])
ans =

   9   9   9
   9   9   9
   9   9   9

```

# Answer
> 2 votes
# Python 2, 176 bytes - 3 = 173

```
def g(m,n):
 y,x,z,l,f='y','x','z','l','%'+str(len(str(max(m*m,n*n))))+'s'
 d={y:m*n,x:n*n,z:m*m,l:'\n'}
 for i in map(lambda x:d[x],(y*m+x*n+l)*n+(z*m+y*n+l)*m): print f % i,

```

This uses Python string functions to create a character grid, then replaces the characters with integers and prints formatted output.

# Answer
> 2 votes
# Ruby, (133 - 3) = 130 bytes

```
s=1
a=ARGV.map{|e|s*=(e=e.to_i);[e]*e}.flatten
s=s.to_s.size
a.reverse.each{|i|a.each{|j|print (i*j).to_s.rjust(s).ljust(s+3)};puts}

```

## for 4,3

```
12   12   12   12    9    9    9
12   12   12   12    9    9    9
12   12   12   12    9    9    9
16   16   16   16   12   12   12
16   16   16   16   12   12   12
16   16   16   16   12   12   12
16   16   16   16   12   12   12

```

## for 1,3

```
3   9   9   9
3   9   9   9
3   9   9   9
1   3   3   3

```

## for 0,3

```
9   9   9
9   9   9
9   9   9

```

# Answer
> 1 votes
# Blocks, ~~52~~ ~~62~~ ~~82~~ ~~87~~ 51 bytes

```
::`+`1|U;{`*`1}|A;`+`1,0+`1={`1^2}|;0+`,`1+`={`^2}|

```

Ungolfed:

```
::
  ` + `1                    | Expand;
  {` * `1}                  | SetAll;
  ` + `1, 0 + `1 = {`1 ^ 2} | Set;
  0 + `, `1 + `  = {` ^ 2}  | Set

```

Try it

# Answer
> 1 votes
# C, (125 - 3) bytes

```
i,j,a;main(b,s){for(sscanf(gets(s),"%d %d",&a,&b);j<a+b;)printf(++i>a+b?i=!++j,"\n":"%*d",strlen(s)*2,(i<a?a:b)*(j<b?b:a));}

```

Input is taken as two space-separated integers on the same line. Each cell is padded with spaces to twice length of the input string.

# Answer
> 1 votes
# Matlab, 58 − 3 = 55

Using an anonymous function:

```
@(a,b)flipud(blkdiag(a^2*ones(a)-a*b,b^2*ones(b)-a*b)+a*b)

```

Example:

```
>> @(a,b)flipud(blkdiag(a^2*ones(a)-a*b,b^2*ones(b)-a*b)+a*b)
ans =
    @(a,b)flipud(blkdiag(a^2*ones(a)-a*b,b^2*ones(b)-a*b)+a*b)
>> ans(4,3)
ans =
    12    12    12    12     9     9     9
    12    12    12    12     9     9     9
    12    12    12    12     9     9     9
    16    16    16    16    12    12    12
    16    16    16    16    12    12    12
    16    16    16    16    12    12    12
    16    16    16    16    12    12    12

>> @(a,b)flipud(blkdiag(a^2*ones(a)-a*b,b^2*ones(b)-a*b)+a*b)
ans =
    @(a,b)flipud(blkdiag(a^2*ones(a)-a*b,b^2*ones(b)-a*b)+a*b)
>> ans(0,3)
ans =
     9     9     9
     9     9     9
     9     9     9

```

### (Old solution) 59 − 3 = 56

Using an anonymous function:

```
@(a,b)[b*a*ones(b,a) b^2*ones(b);a^2*ones(a) a*b*ones(a,b)]

```

# Answer
> 1 votes
# Pyth, 39 − 3 = 36

Pyth doesn't have built-in matrix formatting, which greatly increases the size, as one has to manually pad the output numbers. Here's what I came up with.

```
JAQL*b]jdm.[`d\ l`eS^R2Jsm*d]*bdJj+yHyG

```

Try it online.

# Answer
> 1 votes
# Jelly, \\$6 - 3 = 3\\$ bytes

```
x`×þU$

```

Try it online!

A port of the APL and J answers. Takes input as `[a, b]`

## How it works

```
x`×þU$ - Main link. Takes a pair `[a, b]` on the left
 `     - Using [a, b] as both arguments:
x      -   Repeat a a times and b b times
     $ - To this repeated array:
    U  -   Reverse the array
  ×þ   -   Generate a multiplication table

```

---
Tags: code-golf, math, arithmetic, array, grid
---


title: Which Ninjutsu am I casting?

text:
# Question
Title: Which Ninjutsu am I casting?
In the MMORPG Final Fantasy XIV, the Ninja class has the ability to use combinations of up to three handsigns (Ten, Chi and Jin) to perform a variety of ninjutsu skills.

The skill you cast depends on the last sign used, and using two or more of the same sign makes the ninjutsu skill fail and puts a little bunny on your head.

## Challenge

Your job is to take up to three handsigns as input, and output the name of the ninjutsu skill this combination does. Of course, since this is , the goal is to make your code as short as possible!

## Input

The program should take between 1 and 3 handsigns as input via STDIN or function arguments. You can use any kind of input format you prefer.

Example inputs:

```
TCJ
Ten Chi Jin
["T", "C", "J"]
["Ten", "Chi", "Jin"]

```

## Output

The program should output the name (in title case) of the ninjutsu skill you get from the handsigns sent to it via input. Here's a table of each combination and their resulting skill.

Mudra table:

```
| Handsigns                     | Ninjutsu Skill |
|-------------------------------|----------------|
| Any one                       | Fuma Shuriken  |
| Any one + Ten                 | Katon          |
| Any one + Chi                 | Raiton         |
| Any one + Jin                 | Hyoton         |
| Any two + Ten                 | Huton          |
| Any two + Chi                 | Doton          |
| Any two + Jin                 | Suiton         |
| Contains two of the same sign | Bunny          |

```

Bunny takes precedence over any other ninjutsu.

## Examples

```
TCJ                -> Suiton
J                  -> Fuma Shuriken
['Ten', 'Chi']     -> Raiton
"Jin" "Jin" "Ten"  -> Bunny

```

## Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
# Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
var QUESTION_ID=218805;
var OVERRIDE_USER=45220;
var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}}
```

```
body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table>
```

# Answer
> 4 votes
# 05AB1E, ~~54~~ ~~52~~ 51 bytes

-3 bytes thanks to Kevin Cruijssen!

Takes a string of first letters of the handsigns. A list of integers could probably save a byte.

```
ÙÊi'åƒë.•!˜Œ¾Ë₂Γ∍Ÿ¾µÓ•#…ton«ι.•E‹ØÁó+±Æ•¸šÁIgèI3öè}™

```

Try it online! or Try all possible cases!

**Commented**:

```
Ù                    # deduplicate the input
 Ê                   # is this different from the input?
  i                  # if this is the case
   'åƒ              '# push compressed string "bunny"

ë                    # else:
 .•!...Ó•            # push compressed string "rai do hyo sui ka hu"
         #           # split on spaces
          …ton«      # append "ton" to each word
               ι     # rearrange the words into two lists
                     # [["raiton", "hyoton", "katon"], ["doton", "suiton", "huton"]]
.•E...Æ•             # push compressed string "fuma shuriken"
        ¸            # wrap into a list
         š           # prepend to the other list
          Á          # rotate this list right
                     # [["doton", "suiton", "huton"], ["fuma shuriken"], ["raiton", "hyoton", "katon"]]
           Ig        # take the length of the input
             è       # index into the list of lists
              I      # push the input again
               3ö    # convert from base 3
                 è   # modularly index into the list

}™                   # after the if/else: titlecase each word

```

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

*A shorter version suggested by @tsh*

Expects `[1,2,3]` for `"TCJ"`.

```
(a,b,c)=>a^b&&a^c&&b^c?',Hu,Do,Sui,Hyo,Rai,Ka'.split`,`[c||7-b]+'ton':b?'Bunny':'Fuma Shuriken'

```

Try it online!

---

# JavaScript (ES6), 99 bytes

Expects `"012"` for `"TCJ"`.

```
s=>/(.).?\1/.test([,b,c]=s)?'Bunny':b?'Hu,Do,Sui,Hyo,Rai,Ka'.split`,`[c||5-b]+'ton':'Fuma Shuriken'

```

Try it online!

### Commented

```
s =>                         // s = input string
  /(.).?\1/                  // regex to detect a duplicate character
  .test([, b, c] = s)        // apply it to s; at the same time, load the 2nd
                             // and 3rd characters into b and c respectively
  ?                          // if there's a duplicate:
    'Bunny'                  //   return 'Bunny'
  :                          // else:
    b ?                      //   if the 2nd character is defined:
      'Hu,Do,Sui,Hyo,Rai,Ka' //     lookup string of prefixes
      .split`,`              //     split it
      [c || 5 - b]           //     use c if it's defined, or 5 - b otherwise
      + 'ton'                //     append the suffix
    :                        //   else:
      'Fuma Shuriken'        //     return 'Fuma Shuriken'

```

# Answer
> 6 votes
# , ~~153~~ ~~149~~ ~~144~~ 139 bytes

*Edit: -5 bytes thanks to Giuseppe*

```
function(x)`if`(any(table(x)>1),'Bunny',`if`((l=sum(x|1))-1,a[l*3-6+x[l]],'Fuma Shuriken'));a=paste0(scan(,''),'ton')
Ka
Rai
Hyo
Hu
Do
Sui

```

Try it online!

Input is `1` for 'Ten', `2` for 'Chi', `3` for 'Jin'.

**Ungolfed:**

a=paste0(scan(,''),'ton')       # scan(,'') reads the subsequent strings until it finds an empty one,
Ka                              # paste0 joins them each together with 'ton'.
Rai
Hyo
Hu
Do
Sui

function(x){
 if(any(table(x)>1))'Bunny'     # if there are any duplicates: 'Bunny'
 else{                          # otherwise
  l=length(x)                   # define l=length of x (the R golfy way: sum(x|1) because 'length' is 6 letters)
  if(l-1)a[l*3-6+tail(x,1)]     # if it isn't length 1, output the relevant element from the vector 'a' of ninjutsu names
  else'Fuma Shuriken'           # otherwise (it's length 1): 'Fuma Shuriken'.
 }
}
```
</code></pre>

# Answer
> 6 votes
# x86-16 machine code, IBM PC DOS, ~~102~~ 101 bytes

```
00000000: b409 ba38 0149 742d ba46 0151 51ac 8bfe  ...8.It-.F.QQ...
00000010: f2ae 59e0 f759 741d 49ac 7402 0403 2c30  ..Y..Yt.I.t...,0
00000020: 8ad0 b024 b116 bf4b 01f2 aefe ca75 fa8b  ...$...K.....u..
00000030: d7cd 2103 d1cd 21c3 4675 6d61 2053 6875  ..!...!.Fuma Shu
00000040: 7269 6b65 6e24 4275 6e6e 7924 4b61 2452  riken$Bunny$Ka$R
00000050: 6169 2448 796f 2448 7524 446f 2453 7569  ai$Hyo$Hu$Do$Sui
00000060: 2474 6f6e 24                             $ton$

```

**Listing:**

```
B4 09       MOV  AH, 9                  ; DOS display $-terminated string syscall

                                        ; STEP 1 - check if input is only 1 char
BA 0138     MOV  DX, OFFSET FAM         ;  default output is Fama
49          DEC  CX                     ;  is only 1 char?
74 2D       JZ   DONE                   ;  if so, output is Fama

                                        ; STEP 2 - check if input has duplicate chars
BA 0147     MOV  DX, OFFSET BUN         ;  next default output is Bunny
51          PUSH CX                     ;  save original input length
        DUP_LOOP:
51          PUSH CX                     ;  save loop position
AC          LODSB                       ;  load next char into AL
8B FE       MOV  DI, SI                 ;  start search at current char
F2 AE       REPNZ SCASB                 ;   and search for AL
59          POP  CX                     ;  restore loop position
E0 F7       LOOPNZ DUP_LOOP             ;  end loop if there was a match
59          POP  CX                     ;  restore original length
74 1D       JZ   DONE                   ;  had a dup? output is Bunny

                                        ; STEP 3 - use last char to get correct name
49          DEC  CX                     ;  ZF if two chars, NZ if three chars
AC          LODSB                       ;  load last char into AL
74 02       JZ   FIND_NAME              ;  is three chars?
04 03       ADD  AL, 3                  ;  if so, offset array index by 3
        FIND_NAME:
2C 30       SUB  AL, '0'                ;  ASCII convert input
8A D0       MOV  DL, AL                 ;  set number of delimiters to find
B0 24       MOV  AL, '$'                ;  set delimiter char to find ('$')
B1 16       MOV  CL, 22                 ;  length of name array
BF 014C     MOV  DI, OFFSET NAM-1       ;  pointer to name array
        SCAN_LOOP:
F2 AE       REPNZ SCASB                 ;  search until delimiter found
FE CA       DEC  DL                     ;  decrement counter
75 FA       JNZ  SCAN_LOOP              ;  loop until end of counter
8B D7       MOV  DX, DI                 ;  move found pointer to DX
CD 21       INT  21H                    ;  write name prefix to STDOUT
03 D1       ADD  DX, CX                 ;  advance to start of suffix string

        DONE:                           ; STEP 4 - display string at DX
CD 21       INT  21H                    ;  write output string to STDOUT
C3          RET                         ;  return to caller

                                        ; Strings and Things
    FAM     DB  'Fuma Shuriken$'        ;  if one char
    BUN     DB  'Bunny$'                ;  if duplicate chars
    NAM     DB  'Ka$','Rai$','Hyo$'     ;  name prefix array
            DB  'Hu$','Do$','Sui$'      ;   delimited by $
    TON     DB  'ton$'                  ;  name suffix

```

Callable function, input as string at `[SI]`, length in `CX` where `Ten` = `1`, `Chi` = `2` or `Jin` = `3`. Output to DOS STDOUT.

Test program output:

# Answer
> 5 votes
# Haskell, ~~116~~ 109 bytes

*saved 7 bytes thanks to @ovs, and obscure things in the stdlib (why is `word` but not `split` in Prelude?)*

```
n[_]="Fuma Shuriken" -- matches a list of one element
n(a:b)|a`elem`b="Bunny" -- matches a list starting with a where a is in b `| `(cond)` =` is a guard that checks cond
n[a,b]=words"Ka Rai Hyo Ho Do Sui"!!b++"ton" -- !! is indexing, ++ is appending
n[a,b,c]=n[b+3,c+3] -- don't mistake n[] as indexing, it's calling n with a list.
-- b+3 so it will still catch duplicates where b=c

```

Highly readable (IMO), and highly not PHP (sorry PHP). This makes excessive use of pattern matching. It takes input as a list of Ten=0, Chi=1, Jin=2. Trailing whitespace and comments (starting with --) are not counted.

ideone it!

# Answer
> 4 votes
# PHP, ~~139~~ ~~133~~ 128 bytes

```
fn($s)=>($l=strlen($s))>1?max(count_chars($s))>1?Bunny:[T=>[Ka,Hu],C=>[Rai,'Do'],J=>[Hyo,Sui]][$s[-1]][$l%2].ton:'Fuma Shuriken'

```

Try it online!

### Explanation

```
fn( $s ) =>
    ( $l = strlen( $s ) ) > 1 ?             // is input longer than one char?
        max( count_chars( $s ) ) > 1 ?      // has more than 1 of any single char?
            'Bunny'                         // if so, contains dupes so... Bunny it is
        :                                   // else, no dupes
            [
                'T' => [ 'Ka',  'Hu'  ],    // two dimensional associative
                'C' => [ 'Rai', 'Do'  ],    //   array containing handsign
                'J' => [ 'Hyo,  'Sui' ]     //   and length as indexes
            ]
            [ $s[-1] ]                      // access array by last letter and
            [ $l % 2 ]                      //   length mod 2 (2 == 0, 3 == 1)
            . 'ton'                         //   and append "ton"
    :                                       // finally...
    'Fuma Shuriken'                         // input length was only one char

```

And combining some ideas from Cray's golfier answer, and taking input as `1, 2, 3`, gets it down to **111** bytes (Cray's is still shorter though):

### PHP, 111 bytes

```
fn($s)=>$s[1]?max(count_chars($s))>1?Bunny:[0,[Hu,Ka],['Do',Rai],[Sui,Hyo]][$s[-1]][!$s[2]].ton:'Fuma Shuriken'

```

Try it online!

# Answer
> 4 votes
# PHP, 106 bytes

Inspired by 640KB's answer. Expects input as `123`

```
fn($s)=>$s[1]?max(count_chars($s))>1?Bunny:[Ka,Hu,Rai,'Do',Hyo,Sui][$s[-1]*2-!$s[2]-1].ton:'Fuma Shuriken'

```

Try it online!

### Explanation

```
fn($s)=>
  $s[1]?                          // check if 2nd char of input is present
    max(count_chars($s))>1?       // count chars, check if any are present more than once
      'Bunny'                     // input has duplicates
    :                             // input does not have duplicates
      [Ka,Hu,Rai,'Do',Hyo,Sui]    // array of possible results
      [$s[-1]*2-!$s[2]-1]         // find correct index of result
                                  // takes last char of input, multiplied by 2,
                                  // minus boolean value based on input length
                                  // finally adjust index by -1
      .'ton'                      // and add suffix
  :
  'Fuma Shuriken'                 // input length was 1

```

# Answer
> 3 votes
# , <sup>84</sup> 79 bytes

```
('Bunny';'Fuma Shuriken';,&'ton'&.>Ka`Rai`Hy`Hu`Do`Sui){~({:+1 1 4{~#)@}.*]-:~.

```

Try it online!

Takes 1, 2, 3 as inputs, mapping to T, C, J, respectively.

* `('Bunny';'Fuma Shuriken';,&'ton'&.>Ka`Rai`Hy`Hu`Do`Sui)` creates the word list and was the least satisfactory part of the golf, despite some effort. It produces:

```
┌─────┬─────────────┬─────┬──────┬─────┬─────┬─────┬──────┐
│Bunny│Fuma Shuriken│Katon│Raiton│Hyton│Huton│Doton│Suiton│
└─────┴─────────────┴─────┴──────┴─────┴─────┴─────┴──────┘

```
* `{~` From that, select the following index:
* `(...)@}.` First remove the first element and...
* `{:+1 1 4{~#` Take the last element `{:` of what remains (crucially, this will be 0 for the empty list, i.e., one element inputs) and add to it 1, 1, or 4, depending on if the length is 0, 1, or 2.
* `*]-:~.` Multiply that result by 1 if the unique of the input `~.` matches the input `]-:`, and 0 otherwise. This ensures inputs with duplicates always have 0 index and return bunny.

# Answer
> 2 votes
# Charcoal, 65 bytes

```
¿⊙θ⊖№θιBunny¿⊖Ｌθ⁺§⪪§⪪”↶/⊟≡⧴№K5Ｇ⁰⁺jＭ✂⎚Σ”χＬθ ℅§θ±¹ton¦Fuma Shuriken

```

Try it online! Link is to verbose version of code. Takes input as a string of initials. Explanation:

```
¿⊙θ⊖№θιBunny

```

If any of the characters appear more than once then print "Bunny".

```
¿⊖Ｌθ⁺§⪪§⪪”↶/⊟≡⧴№K5Ｇ⁰⁺jＭ✂⎚Σ”χＬθ ℅§θ±¹ton

```

If the length is more than one then look up the appropriate prefix from either "Ka Rai Hyo" or "Hu Do Sui" (depending on the length) split on spaces and indexed by the ordinal of the last character, concatenated with "ton".

```
¦Fuma Shuriken

```

But if the length is 1 then just print "Fuma Shuriken".

# Answer
> 2 votes
# Lua (LuaJIT), ~~170~~ 167 bytes

```
r={'Rai','Hyo','Sui','Ka','Hu','Do'}t={'Fuma Shuriken',CT=4,JT=4,JC=1,TC=1,CJ=2,TJ=2,CJT=5,JCT=5,JTC=6,TJC=6,CTJ=3,TCJ=3}print(t[#i]or t[i]and r[t[i]]..'ton'or'Bunny')

```

Try it online!

# Answer
> 2 votes
# PowerShell, ~~214~~ ~~208~~ ~~207~~ ~~205~~ ~~203~~ ~~201~~ ~~188~~ ~~186~~ ~~180~~ 177 bytes

```
$s=$args[0];if($s[1]){if($s|% t*y|group|% c*|?{$_-ne1}){'Bunny'}else{@{'T'=('Ka','Hu');'C'=('Rai','Do');'J'=('Hyo','Sui')}["$($s[-1])"][$s.length%2]+'ton'}}else{'Fuma Shuriken'}

```

Try it online!

Thanks @640KB for the forkable PHP answer.

Cheers folks, help me to reduce the size!

(Please manually pass the argument, for test I have passed "CT", it worked and others worked too ;-)

Last -3 bytes thanks to @mazzy

# Answer
> 2 votes
# Perl 5, 120 bytes

```
/(.).?\1/ and$_="Bunny";s/^.$/Fuma Shuriken/;s/..J/Suiton/;s/..C/Doton/;s/..T/Huton/;s/.J/Hyoton/;s/.C/Raiton/;s/.T/Katon/

```

It's everybody's favorite thing: a bunch of regular expressions sitting in a row. Run with `perl -lapE '<the above code>'`

First, we deal with the bunny case, by checking if any character appears twice and simply replace the string with "Bunny" in that case. Next, we check if there's exactly one character and replace with "Fuma Shuriken". Beyond that, we simply brute force the remaining options with regular expressions. Finally, if the resulting string does not end in n or y (i.e. it's not "Bunny" or "Fuma Shuriken"), then we add "ton" to the end.

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


title: Inverting lists of lists of indices

text:
# Question
Title: Inverting lists of lists of indices
*Inspired by this StackOverflow post.*

# Introduction

Bob's job is to create spreadsheets and organize them. The way he organizes them is known to very few except for Bob, but he creates a list of each of the spreadsheets that fall under the same group. There's a bunch of data in the spreadsheet he creates, but there's only one piece of data that we're looking at right now: The number of days between the day he started this job and the day he made the spreadsheet. The first day he created two spreadsheets, noted them both as `0` and sorted them in to their proper locations.

Now, his boss is asking for a review of what kinds of spreadsheet happened each day, and it's your job to write some code that will figure that out for Bob; he has far too many spreadsheets to do it by hand.

## Input

Bob's info that he gives you comes in the form of a (0-or-1 indexed) jagged array where each datum is of the form `x = a[i][j]`. `a` is what I'm calling the jagged array itself, `i` is the type of spreadsheet, and `x` is the date the array was created. `j` is unimportant.

## The task

Given a jagged array of spreadsheet creation days organized by their type, return a jagged array of spreadsheet types organized by spreadsheet creation day.

## Examples

Bob isn't going to just leave you with this abstract data. He's given me a subset of some of his spreadsheets to help you out with figuring out what everything is supposed to be.

Example input (0-indexed):

```
a = [
[3,2,5,0], # Bob doesn't necessarily sort his lists
[1,3],
[2,1,0,4],
[4,5,3],
[6,6]
]

```

Example output (with commentary, which of course is not required):

```
output = [
[0,2] # On day 0, Bob made one type 0 and one type 2 spreadsheet
[1,2] # On day 1, Bob made one type 1 and one type 2 spreadsheet
[0,2] # On day 2, Bob made one type 0 and one type 2 spreadsheet
[0,1,3] # On day 3, Bob made one type 0, one type 1, and one type 3 spreadsheet
[2,3] # On day 4, Bob made one type 2 and one type 3 spreadsheet
[0,3] # On day 5, Bob made one type 0 and one type 3 spreadsheet
[4,4] # On day 6, Bob made two type 4 spreadsheets
]

```

Note that Bob doesn't always make two spreadsheets every day, and so the output may be jagged as well. But he always makes at least one spreadsheet every day, so the output will never need to contain empty arrays - although if your output has empty arrays at the end, you don't need to remove them.

More test cases:

```
[[3,5,6,2],[0,0,0],[1,0,3,4]] -> [[1,1,1,2],[2],[0],[0,2],[2],[0],[0]]
[[-1]] -> Undefined behavior, as all input numbers will be non-negative integers.
[[0],[0],[],[0]] -> [[0,1,3]]

```

The output's inner lists do not need to be sorted.

As always, no standard loopholes, and of course shortest code wins.

*(As this is my first question, please let me know of anything I can do to improve it.)*

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

```
FṀ⁸ċþµJ€x"

```

Input and output are 1-based.

Try it online! or verify all test cases (0-based for easy comparison).
> 5 votes

# Answer
# Pyth, 13 bytes

```
eMM.ghkSs,RVU

         ,RV      vectorized right map of pair, over:
            UQ      [0, …, len(input) - 1] and
              Q     input
                  (this replaces each date with a [date, type] pair)
        s         concatenate
       S          sort
   .ghk           group by first element (date)
eMM               last element (type) of each sublist

```

Try it online
> 5 votes

# Answer
# Pyth, 14 bytes

```
ms.e*]k/bdQS{s

```

Test suite.
> 4 votes

# Answer
# Brachylog, 28 bytes

```
:1f.
cdo:Im:?:2f.
t:.m:Im~h?

```

### Explanation

* Main predicate, Input (`?`) = a list of lists

```
:1f.              Find all valid outputs of predicate 1 with ? as input

```
* Predicate 1:

```
c                 Concatenate the list of lists into a single list
 do               Remove duplicates and sort
   :Im            Take the Ith element of that sorted list
      :?:2f.      Find all valid outputs of predicate 2 with [Element:?] as input

```
* Predicate 2:

```
t:.m              Take the (Output)th element of the list of lists
    :Im           Take the Ith element of that list
       ~h?        This element is the element of the input [Element:List of lists]

```
> 4 votes

# Answer
# Lua, 114 bytes

```
r={}for i,t in ipairs(...)do for _,v in ipairs(t)do if r[v] then r[v][#r[v]+1]=i else r[v]={i}end end end return r

```

Ideone it!

Inspired by Dennis' answer in Python 2.
> 3 votes

# Answer
## JavaScript (ES6), 58 bytes

```
a=>a.map((b,i)=>b.map(j=>(r[j]=r[j]||[]).push(i)),r=[])&&r

```
> 3 votes

# Answer
## CJam (30 29 bytes)

```
Mq~{W):W;{:X)Me]_X=W+X\t}/}/`

```

Online demo

Curiously it's shorter to hack around with `W` than to use `ee`, mainly because I want the index to end up in a variable anyway. `e]` saved two bytes over first finding the maximum element `m` and initialising an array of `m+1` empty arrays.

Thanks to Martin for a one-byte saving by storing a value in `X` instead of juggling it around the stack.

NB If trailing empty arrays are permitted, there's alternative 29-byte approach by instead initialising the array of as many empty days as there are spreadsheets:

```
q~_e_,Ma*\{W):W;{_2$=W+t}/}/`

```
> 3 votes

# Answer
## CJam, 20 bytes

*Thanks to Peter Taylor for letting me base this code on his solution and saving 3 bytes.*

```
{ee::f{S*\+S/}:~:.+}

```

An unnamed block which expects the input on top of the stack and replaces it with the output.

Test it here.

### Explanation

```
ee    e# Enumerate the input. E.g. if the input is
      e#   [[3 5 6 2] [0 0 0] [1 0 3 4]]
      e# this gives:
      e#   [[0 [3 5 6 2]] [1 [0 0 0]] [2 [1 0 3 4]]]
::f{  e# The exact details of how this works are a bit tricky, but in effect
      e# this calls the subsequent block once for every spreadsheet and
      e# its correspond index, so the first time we'll have 0 and 3 on the
      e# stack, the next time 0 5, and at the last iteration 2 and 4.
      e# Note that this is a map operation, so we'll end up with an array
      e# on the stack.
  S*  e#   So the stack holds [... index date] now. We start by creating
      e#   a string of 'date' spaces, so "   " on the first iteration.
  \+  e#   We swap this with the index and append the index.
  S/  e#   Now we split this thing on spaces, which gives us 'date' empty
      e#   lists and a list containing the index, e.g. [[] [] [] [0]].
}
:~    e# This flattens the first level of the result, so that we get a list
      e# of all those lists we just created. This is simply one list for
      e# every spreadsheet with its type in the last element.
:.+   e# Finally we fold pairwise concatenation over this list. All the
      e# empty lists won't affect the result so we'll just end up with all
      e# the types in lists for the correct date.

```
> 3 votes

# Answer
# Python 2, 82 bytes

```
r=[];i=0
for t in input():
 for v in t:r+=[()]*-(~v+len(r));r[v]+=i,
 i+=1
print r

```

Test it on Ideone.
> 2 votes

# Answer
## Mathematica, 35 bytes

```
Table[#&@@@#~Position~i,{i,Max@#}]&

```

An unnamed function which accepts and returns a ragged list. Uses 1-based indices.

Thankfully `Max` automatically flattens all its inputs, so this gets us the last day index even though the input is a ragged list. We then simply compute a list of `#&@@@#~Position~i` for all day indices `i`. This expression itself finds the position of `i` inside the ragged list (return as an array of indices at successive depths), so the values we want are the first values of each of those lists. `#&@@@` is a standard golfing trick to retrieve the first element from every sublist, by applying `#&` to each of those sublists, which is an unnamed function that returns its first argument.

Alternatively, we can define a unary operator for the same byte-count (assuming an ISO 8859-1 encoded source file):

```
±n_:=#&@@@n~Position~#&~Array~Max@n

```
> 2 votes

# Answer
# Java, 314 bytes

```
int[][]f(int[][]n){int w=0;Map<Integer,List<Integer>>m=new TreeMap<>();for(int i=0;i<n.length;i++)for(Integer x:n[i]){if(m.get(x)==null)m.put(x,new ArrayList<>());m.get(x).add(i);w=x>w?x:w;}int[][]z=new int[w+1][];for(int i=0,j;i<w+1;i++){z[i]=new int[m.get(i).size()];j=0;for(int x:m.get(i))z[i][j++]=x;}return z;

```

**Detailed**

```
public static Integer[][] f(Integer[][]n)
{
    int w=0;
    Map<Integer,List<Integer>>m=new TreeMap<>();

    for(int i=0;i<n.length;i++)
    {
        for(Integer x : n[i])
        {
            if(m.get(x)==null) m.put(x,new ArrayList<Integer>());
            m.get(x).add(i);
            w=x>w?x:w;
        }
    }

    Integer[][]z=new Integer[w+1][];
    for(int i=0,j; i<w+1; i++)
    {
        z[i]=new Integer[m.get(i).size()];
        j=0;for(Integer x : m.get(i))z[i][j++]=x;
    }

    return z;
}

```
> 2 votes

# Answer
# Jelly, 9 bytes

```
œẹⱮFṀ$Ḣ€€

```

Try it online!

Input and output is 1-indexed, the Footer converts from 0-indexing to 1-indexing and back for I/O purposes.

## How it works

```

œẹⱮFṀ$Ḣ€€ - Main link. Takes a 2D array, **a**, on the left
     $    - To **a**:
   F      -   Flatten
    Ṁ     -   Maximum
  Ɱ       - Over each number **i** in [1, 2, ..., max(flat(**a**))]:
œẹ        -   Get the multidimensional indices of **i** in **a**
              This returns [x, y] for each occurrence of **i** in **a**
              where **x** is the index of the array in **a** in which **i** is in
              and **y** is the index of **i** in that array. For example

              [[1,2,3],[4,5,6],[7,8,9]] œẹ 7 = [[3,1]]

              as 7 is in the 3rd subarray at index 1 (using 1 indexing)

      Ḣ€€ - Extract the **x** values only and return them

```
> 2 votes

# Answer
# Perl 5, 48 bytes

A subroutine:

```
{for$i(0..@_){map{push@{$b[$_]},$i}@{$_[$i]}}@b}

```

See it in action like this:

```
perl -e'print "@$_$/" for sub{for$i(0..@_){map{push@{$b[$_]},$i}@{$_[$i]}}@b}->([3,2,5,0],[1,3],[2,1,0,4],[4,5,3],[6,6])'

```
> 0 votes

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


title: Java Asterisk Rectangle

text:
# Question
Title: Java Asterisk Rectangle
For my CS class, my instructor has given us the assignment of creating a rectangle made of asterisks with diagonal lines drawn through it in Java.

He also told us to write it in as few bytes as possible. I've gotten it down to 190 bytes, but I need to find a few to simplify this code even more to decrease bytes. Can anyone help me with this?

This code is functional:

```
interface d{static void main(String[]a){for(int z=0,w=new Byte(a[0]),h=new Byte(a[1]);z<h*w;){int y=z/w,x=z++%w;System.out.print((x>w-2)?"*\n":(y%(h-1)*x*((y-x)%3)==0)?"*":" ");}}}

```

Input is `10 10`.

Output:

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

```

# Answer
Logically, there should be an asterisk (`*`) every time `i == j` and `i+j==w-1`(for diagonals), `i == 0` and `j == 0` (for top line and left side) and `j == w-1` and `i==h-1` (for right side and bottom line).

```
class d {
    public static void main(String[] a) {
        for(int i=0,w=new Byte(a[0]),h=new Byte(a[1]);i<h;i++) {
            for(int j=0;j<w;j++) {
                System.out.print(i==0 || j==0 || i==h-1 || i+j==w-1 || j==w-1 || i==j ? "*":" ");
            }
            System.out.println();
        }
    }
}

```
> 1 votes

# Answer
The code you provided could be reduced by doing this:

* replace `*` with `42` and `" "` by `' '` (taking advantage of the charcode for `*`)
* move `((y - x) % 3)` to the beginning of the things to be multiplied and remove the surrounding parenthesis
* remove surrounding parenthesis from `(x > w - 2)` and from `((y - x) % 3 * y % (h - 1) * x == 0)`

The resulting code would be:

```
interface r{static void main(String[]a){for(int z=0,w=new Byte(a[0]),h=new Byte(a[1]);z<h*w;){int y=z/w,x=z++%w;System.out.print(x>w-2?"*\n":(y-x)%3*y%(h-1)*x==0?42:' ');}}}

```

Note: the last line is missing in the example output of the question! The output of the sample code is different.
> 1 votes

# Answer
~~178~~ 174 chars

```
interface T{static void main(String[]a){for(int w=new Byte(a[0]),h=new Byte(a[1]),j,i=0;i<h;i++)for(j=0;j<w;System.out.print((i-j)%3*i*j!=0&i<h-1&++j<w?" ":j<w?"*":"*\n"));}}

```

Try it online!

Readable:

```
interface T{
    static void main(String[]a){
        for(int w=new Byte(a[0]),h=new Byte(a[1]),j,i=0;i<h;i++)
            for(j=0;j<w;System.out.print(
                    (i-j)%3*i*j!=0&i<h-1&++j<w?" ":j<w?"*":"*\n"));
    }
}

```

---

Output for field: `30 10`:

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

```
> 1 votes

# Answer
I don't actually have Java on my computer so I can't test this but I think it should work for 174 bytes and almost definitely could be golfed more

```
class d{static void main(String[]a){for(int i=0,w=new Byte(a[0]),h=new Byte(a[1]);i<h;i++)for(int j=0;j<w;j++)System.out.print(j==w-1?"*\n":i%h-1==0||!j||i+j%2==0?"*":" ");}}

```

Whitespace added for clarity:

```
class d {
    static void string main(String[] a) {
        for(int i=0,w=new Byte(a[0]),h=new Byte(a[1]);i<h;i++)
            for(int j=0;j<w;j++)
                System.out.print(j==w-1 ? "*\n" : i % h-1 == 0 || !j || i+j % 2 == 0 ? "*":" ");
    }
}

```

print `*\n` for the last char in each line, `*` for all of the first and last lines and the first column, and `*` for any time that the sum of the row and column is even, otherwise prints
> 0 votes

---
Tags: tips, java
---


# Question
Title: Count unrooted, unlabeled binary trees of n nodes
An **unrooted binary tree** is an unrooted tree (a graph that has single connected component and contains no cycles) where each vertex has exactly one or three neighbors. It is used in bioinformatics to show evolutionary relationships between species.

If such a tree has \\$n\\$ internal nodes, it necessarily has \\$n+2\\$ leaves. Therefore it always has an even number of vertices.

## Challenge

Given a positive integer \\$n\\$, compute the number of distinct unrooted, unlabeled binary trees having \\$2n\\$ vertices. This is OEIS A000672. You may take \\$2n\\$ as input instead, and in that case, you may assume the input is always even.

The shortest code in bytes wins.

## Illustration

```
n=1 (2 nodes, 1 possible)

O-O

n=2 (4 nodes, 1 possible)

O
 \
  O-O
 /
O

n=3 (6 nodes, 1 possible)

O     O
 \   /
  O-O
 /   \
O     O

n=4 (8 nodes, 1 possible)

O     O
 \   /
  O-O
 /   \
O     O-O
     /
    O

n=5 (10 nodes, 2 possible)

                  C
                   \
A     B       C     O-C
 \   /         \   /
  O-O     A     O-O
 /   \   /     /   \
A     O-O     C     O-C
     /   \         /
    B     A       C

n=6 (12 nodes, 2 possible)
(branching from A)  (branching from B or C)
    O                    O
   /                      \
O-O     O            O     O-O
   \   /              \   /
    O-O     O          O-O     O
   /   \   /          /   \   /
  O     O-O          O     O-O
       /   \              /   \
      O     O            O     O

```

## Test cases

The values for first 20 terms (for \\$n=1\dots 20\\$) are as follows:

```
1, 1, 1, 1, 2, 2, 4, 6, 11, 18,
37, 66, 135, 265, 552, 1132, 2410, 5098, 11020, 23846

```

# Answer
# JavaScript (ES6), 265 bytes

This code actually builds all possible trees and filters out isomorphic results. This is quite slow for \\$n\>9\\$ but \\$a(10)=18\\$ was checked locally.

```
n=>(K=A=>A.map(a=>[...a].sort()).sort(),g=(A,k)=>k>n-3?g[K(A)]||(N--,P=(p,a)=>a.map((v,i)=>P([...p,v],a.filter(_=>i--)))+a?1:g[K(A.map(a=>a.map(v=>~p[v])))]=1)(i=[],A.map(_=>--i)):A.map((a,i)=>a.some((v,j)=>~v?0:a[g([...A,[i,v,v]],a[j]=-~k),j]=v)))([[N=-1,N,N]])|~N

```

Try it online!

## How?

### Tree representation

Only internal nodes are stored explicitly as triplets \\$\[n\_0,n\_1,n\_2\]\\$ where each value is either the 0-indexed ID of another internal node, or \\$-1\\$ for a leaf.

The final list of triplets can be normalized with the helper function \\$K\\$ which first sorts each triplet and then the entire list:

```
K = A => A.map(a => [...a].sort()).sort()

```

### Main algorithm

The main recursive function \\$g\\$ builds all possible trees with \\$n-1\\$ internal nodes1. We start with an arbitrary root node \\$\[-1,-1,-1\]\\$ and attach each new internal node to the first available slot in one of the previous nodes.

For the first iteration, there's only one possible option:

$$\big\[\[-1,-1,-1\]\big\] \rightarrow \big\[\[1,-1,-1\],\[0,-1,-1\]\big\]$$

The underlying object of \\$g\\$ is also used to store all normalized trees that were already found.

Whenever a new tree is generated, we use the helper function \\$P\\$ to generate all permutations of the vertex identifiers. This allows us to store in \\$g\\$ all normalized trees that are isomorphic to the one we've found.

---

*1: For obscure golfing reasons, the code actually generates at least 2 internal nodes. This is inconsistent for \\$n\<3\\$ but leads to only one possible tree anyway, which is the expected result.*
> 13 votes

# Answer
# JavaScript (ES6), 267 bytes

A slightly longer but *much* faster version that implements the formula described in A000672, which itself is based on A001190.

```
n=>n<5||-(b=n=>(B=(n,g=i=>i<n/2&&B(i)*B(n-i)+g(i+1))=>v=n%1?0:n<2?n:g(1)+B(n/2)*-~v/2)(n+1))(n)+b(--n/2)+2*b(n)-2*(C=(n,r)=>!r||C(n,--r)*(r-n)/~r)(1+b(--n/3),3)-(S=(c,b,i=1)=>i>b?0:c(i)+S(c,b,i+1))(i=>C(b(i),2)*b(n-2*i),~-n/2)+S(i=>b(i)*S(j=>b(j)*b(n-j),--n/2,i),n/3)

```

Try it online!

Please follow this link for a formatted version of the code.
> 7 votes

---
Tags: code-golf, math, sequence, combinatorics, binary-tree
---


title: Bring out the inner llama of a sentence

text:
# Question
Title: Bring out the inner llama of a sentence
Your objective is to take input like

```
Pie is good.  I just ate a bunch of pies early this morning.  Actually, it was closer to the afternoon.  Mornings are good.

```

and create an array of the indexes of the string where the letters that make up the word "Llama" appear (one of each in order). For example, let me show the letters pointed at with carets to show the indexes:

```
Pie is good.  I just ate a bunch of pies early this morning.  Actually, it was closer to the afternoon.  Mornings are good.
                                            ^                      ^        ^                            ^        ^

```

So the array would look like:

```
[44, 67, 76, 105, 114]

```

(If your application uses a indexing that's not 0-based, the numbers will look different. That's fine.)

If the text has no llama, then the array should be empty, nil, null, or undefined.

Any code language is accepted. This is a contest, so the least characters win!

# Answer
> 11 votes
# CJam - 33

```
lel"llama"{1$#)_T+:T\@>}/;]___|=*

```

It gets the 1-based indexes (2 more bytes for 0-based)

Explanation:

`l` reads a line from the input (replace with `q` for whole input)
`el` converts to lowercase
`"llama"{...}/` executes the block for each "llama" letter
`1$` copies the current string
`#` finds the index of the letter
`)_` increments and duplicates
`T+:T` adds T (initially 0), updates T and leaves it on the stack
`\@` swaps items around, now we have current-T, index, string
`>` slices the string starting at the index
`;` pops the remaining string
`]` gathers the indexes in an array
At this point we have all the 1-based indexes; iff any letter was not found, the array will have duplicates.
`___` makes 3 more copies of the array
`|` (with 2 array copies) removes duplicates
`=` compares, resulting in 0 if there were duplicates or 1 if not
`*` multiplies the array 0 or 1 times accordingly

# Answer
> 12 votes
# Perl, 52 bytes

The solution is provided as function that takes the string as argument and returns a list of positions.

* One-based positions, case-sensitive search, without newlines: **52 bytes**

```
sub l{pop=~/(l).*?(l).*?(a).*?(m).*?(a)/;@+[1..$#+]}

```

The case-sensitive search returns an empty array in the example of the question, because after matching the first three letters the lowercase letter `m` is missing in the input text.
* Support of newlines: + 1 byte = **53 bytes**

```
sub l{pop=~/(l).*?(l).*?(a).*?(m).*?(a)/s;@+[1..$#+]}

```

The text can now span several lines.
* Case-insensitive search: + 1 byte = **54 bytes**

```
sub l{pop=~/(l).*?(l).*?(a).*?(m).*?(a)/si;@+[1..$#+]}

```

Now the example in the question reports a list of index positions, they are one-based numbers:

```
[45 68 77 106 115]

```
* Zero-based positions: + 9 bytes = **63 bytes**

```
sub l{pop=~/(l).*?(l).*?(a).*?(m).*?(a)/si;map{$_-1}@+[1..$#+]}

```

Result for the example in the question:

```
[44 67 76 105 114]

```

**Ungolfed:**

The latter variant includes more or less the other variants.

```
sub l {
    # pop() gets the last argument
    pop() =~ /(l).*?(l).*?(a).*?(m).*?(a)/si;
    # the letters inbetween are matched against ".*?",
    # the non-greedy variant of ".*". Thus ".*?"
    # matches only as few as possible characters.
    # The modifier /i controls the case-sensitivity
    # and means ignore case. Without the case matters.
    # Modifier /s treats the string as single line,
    # even if it contains newlines.
    map { $_-1 }   # subtract 1 for zero-based positions
        @+[1..$#+]
    # Array @+ contains the end-positions of the last
    # submatches, and of the whole match in the first position.
    # Therefore the first value is sliced away.
    # @+ is available since Perl 5.6.
}

# test
my @result = l(<<"END_STR");
Pie is good.  I just ate a bunch of pies early this morning.  Actually, it was closer to the afternoon.  Mornings are good.
END_STR
print "[@result]\n";

```

# Answer
> 12 votes
# sed, 299+1

Yes, sed can find a llama. No, sed can't do math. This is the longest answer so far, at 299+1 characters, because I had to teach sed to count.

This answer requires a sed with extended regular expressions (`sed -E` or `sed -r`). I used OpenBSD sed(1). Input is one string per line. (Therefore, the string may not contain a newline.) Output is a line of numbers, or nothing.

Usage (+1 character for `-r`):

```
$ echo 'All arms on all shoulders may ache.' | sed -rf llama.sed
1 2 12 26 30

```

Source code (299 characters):

```
s/%/z/g
s/(.*)[Aa]/\1%/
s/(.*)[Mm](.*%)/\1%\2/
s/(.*)[Aa]((.*%){2})/\1%\2/
s/(.*)[Ll]((.*%){3})/\1%\2/
s/(.*)[Ll]((.*%){4})/\1%\2/
/(.*%){5}/!d
s/[^%]/z/g
:w
s/(z*)%/\10 z\1/
s/z*$//
s/z0/1/
s/z1/2/
s/z2/3/
s/z3/4/
s/z4/5/
s/z5/6/
s/z6/7/
s/z7/8/
s/z8/9/
s/([0-9]z*)z9/z\10/g
s/(z*)z9/1\10/
/[%z]/bw

```

The program first replaces the llama with five `%`. (All `%` in this program are literal.) The first command `s/%/z/g` changes any `%` to `z` in the input line. The next five commands find the llama, so *All arms on all shoulders may ache.* becomes *A%% arms on %ll shoulders %ay %che.* Because each `.*` is greedy, I always finds the llama on the right: *llama llama* would become *llama %%%%%*. If I can't get five `%`, then `/(.*%){5}/!d` deletes the input line and skips the next commands.

`s/[^%]/z/g` changes every character but `%` to `z`. Then I enter a loop. `s/(z*)%/\10 z\1/` changes the first `%` to `0`, copies zero or more `z` from left to right, and adds one more `z` to right. This is so the number of `z` will equal the index. For example, `zz%zzz%...` becomes `zz0 zzzzzzzz%...` because the first `%` was at index 2, and the next `%` is at index 8. `s/z*$//` removes extra `z` from the end of the string.

The next eleven commands count `z` by removing each `z` and counting up from `0`. It counts like `zzz0`, `zz1`, `z2`, `3`. Also, `1zzzz9` becomes `z1zzz0` (later `23`), or `zzzz9` becomes `1zzz0` (later `13`). This loop continues until there are no more `%` or `z`.

# Answer
> 9 votes
## Fortran - ~~154~~ 148

Fortran sucks at golfing, but just to prove that parsing strings can be done in a math-based language, I did it:

```
function f result(r);integer::r(5),j=1;do i=1,len(s);if(s(i:i)==a(j:j).or.s(i:i)==b(j:j)) then;r(j)=i;j=j+1;endif;enddo;if(any(r==0))r=0;endfunction

```

I saved a few characters by eliminating the not-required `f` at the end of `endfunction` and used `if(any(r==0))` instead of `if(.not.all(r>0))`.

This requires:

1. `s` to be the string with text
2. `a` to be the lower-case test (i.e., `llama`)
3. `b` to be the upper-case test (i.e., `LLAMA`)

The full, un-golfed program is

```
program find_llama
   character(len=123) :: s = "Pie is good.  I just ate a bunch of pies early this morning.  Actually, it was closer to the afternoon.  Mornings are good."
   character(len=5) :: a="llama",b="LLAMA"

   print *,f()
 contains
   function f result(r)
     integer::r(5),j=1
     do i=1,len(s)
        if(s(i:i)==a(j:j).or.s(i:i)==b(j:j)) then
           r(j)=i
           j=j+1
        endif
     enddo
     if(any(r==0)) r=0
   end function
end program find_llama

```

# Answer
> 8 votes
# Ruby, ~~56~~ ~~65~~ 63

**Edit**: +9 characters so that it is case-insensitive.

Defines a function (lambda, technically) `f`.

```
f=->s{i=0;'LLAMA'.chars.map{|c|i=s.upcase.index(c,i+1)||break}}

```

Returns `nil` if there is no llama. If it has to be `[]` (empty array), then just add `||[]` before the last `}` for a total of **4 extra** characters.

Readable version:

```
innerLlama = -> str{
    index = 0;
    str.downcase!
    arr = 'llama'.each_char.map{|char|
        index = str.index(char, index + 1)
        break unless index
    }
    # uncomment this line for empty array on failure
    #arr || []
}

```

# Answer
> 7 votes
## C# - 119

Takes string, outputs array. Null if no llama in string.

```
int[]a(string s){var i=0;var o="llama".Select((x,y)=>i=s.IndexOf(x,y>0?i+1:0));return o.All(x=>x>=0)?o.ToArray():null;}

```

# Answer
> 6 votes
# C - 53

Compile with:

```
gcc -D L=\"llama\" -D W=\"Lie\ is\ good.\ \ I\ just\ ate\ a\ bunch\ of\ pies\ early\ this\ morning.\ \ Actually,\ it\ was\ closer\ to\ the\ afternoon.\ \ Mornings\ are\ good.\"

```

I tested this compile command with cygwin's gcc. Other environments might handle spaces, and other special characters differently.

The 0-based result is stored into array `r`. Its contents are undefined if there is no llama in the string.

* Case-sensitive (53)

`i,m,r[5];main(){for(;W[i];i++)W[i]==L[m]?r[m++]=i:i;}`
* Case-insensitive (58)

`i,m,r[5];main(){for(;W[i];i++)(W[i]|96)==L[m]?r[m++]=i:i;}`

# Answer
> 4 votes
# Python, 100

I am the worst golfer ever. :P

Thanks to @xnor for shaving off 6 bytes.

```
g,n,o='llama',0,[]
for i in s:
 if g:exec("o+=[n];g=g[1:];"*(i.lower()==g[0])+"n+=1")
o*=len(o)>4

```

`o` contains the array after.

**EDIT**: Fixed.

**EDIT 2**: `len(g)` to `g`, `o==5` to `o>4` as per @xnor's suggestions.

**EDIT 3**: @WolframH fixed it.

# Answer
> 3 votes
## Python 71

Assumes input in `s`. Output in `o`.

```
F=s.lower().find
o=F('l'),
for c in'lama':o+=F(c,o[-1]+1),
o*=min(o)>=0

```

**Edit:** Changed from lists to tuples to save 2 bytes.

# Answer
> 3 votes
# JavaScript (ECMAScript 6) - 68 Characters

```
(/((((.*l).*l).*a).*m).*a/.exec(s)||[]).map(x=>x.length-1).reverse()

```

Assumes that the string to test is in the variable `s`. If you want to turn it into a function then prepend `f=s=>` (for an additional 5 characters).

**Outputs:**

```
[]

```

**Case Insensitive - 69 Characters**

```
(/((((.*l).*l).*a).*m).*a/i.exec(s)||[]).map(x=>x.length-1).reverse()

```

**Outputs:**

```
[68, 80, 93, 105, 114]

```

**Case Insensitive & First Match - 74 Characters**

```
(/((((.*?l).*?l).*?a).*?m).*?a/i.exec(s)||[]).map(x=>x.length-1).reverse()

```

**Outputs:**

```
[44, 67, 76, 105, 114]

```

# Answer
> 2 votes
# Python 100

```
import re
x=input()
print[re.search(r"l.*?(l).*?(a).*?(m).*?(a)",x,re.I).start(i) for i in range(5)]

```

Sample:

```
in  = Pie is good.  I just ate a bunch of pies early this morning.  Actually, it was closer to the afternoon.  Mornings are good.
out = [44, 67, 76, 105, 114]
in[out] = ['l', 'l', 'a', 'M', 'a']

```

# Answer
> 2 votes
## Haskell, 111

```
import Data.Char
l i(a:as)t@(b:bs)|a==b=i:l(i+1)as bs|True=l(i+1)as t
l _ _ _=[]
r s=l 0(map toUpper s)"LLAMA"

```

Ungolfed:

```
import Data.Char

llama :: Int -> String -> String -> [Int]
llama i (a:as) t@(b:bs)
  | a==b      = i : llama (i+1) as bs
  | otherwise = llama (i+1) as t
llama _ _ _ = []

runme :: String -> [Int]
runme s = llama 0 (map toUpper s) "LLAMA"

```

Example:

```
*Main> r "Pie is good.  I just ate a bunch of pies early this morning.  Actually, it was closer to the afternoon.  Mornings are good."
[44,67,76,105,114]

```

# Answer
> 2 votes
## Matlab, 61 ~~96~~

Searches the string and replaces everything up to each match with gibberish before searching for next character. Will leave `s` undefined if an the word does not occur.

```
t='llama';for q=1:5;s(q)=min(regexpi(z,t(q))),z(1:s(q))=0;end

```

Note that the charcount could be reduced if case sensitivity is allowed.

**Previous versions**

```
 try;t='llama';for q=1:length(t);s(q)=find(lower(z)==t(q),1);z(1:s(q))=ones(1,s(q));end;catch;end

```

Searches the string and replaces everything up to each match with gibberish before searching for next character. Error handling (try-catch-end) could maybe be dropped, then the program would crash (but s would be undefined as required) if llama not found.

Implementation:

```
>> z='Pie is good.  I just ate a bunch of pies early this morning.  Actually, it was closer to the afternoon.  Mornings are good.';
>> try;t='llama';for q=1:length(t);s(q)=find(lower(z)==t(q),1);z(1:s(q))=ones(1,s(q));end;catch;end
>> s
s =

    45    68    77   106   115

```

Without error handling:

```
t='llama';for q=1:length(t);s(q)=find(lower(z)==t(q),1);z(1:s(q))=ones(1,s(q));end

```

# Answer
> 2 votes
**Language Java**

```
 final int[] wordIndexInSentence(String sentence, String word)
  {
    final int[] returnArr = new int[word.length()];
    int fromIndex = 0;
    word = word.toUpperCase();
    sentence = sentence.toUpperCase();
    for (int i = 0; i < word.length(); i++)
    {
      final char c = word.charAt(i);
      returnArr[i] = sentence.indexOf(c, fromIndex);
      fromIndex = returnArr[i] > 0 ? returnArr[i] + 1 : fromIndex;
    }
    return returnArr;
  }

```

# Answer
> 2 votes
# Rebol, 97

```
f: func[s][a: copy[]foreach n"llama"[if none? s: find s n[return[]]append a index? s s: next s]a]

```

Usage example in Rebol console:

```
>> f "Pie is good.  I just ate a bunch of pies early this morning.  Actually, it was closer to the afternoon.  Mornings are good."
== [45 68 77 106 115]

>> f "nearly llami"
== []

>> f "Llama"
== [1 2 3 4 5]

>> f reverse "llama"
== []

```

Rebol uses 1-based indexing. Returns empty list `[]` if no llama sequence found (case insensitive).

Ungolfed:

```
f: func [s] [
    a: copy []
    foreach n "llama" [
        if none? s: find s n [return []]
        append a index? s
        s: next s
    ]
    a
]

```

# Answer
> 2 votes
# OpenEuphoria, 147128

I have two examples. First, the shortest:

```
object t=and_bits(gets(0),#DF),L="LLAMA",i=0,X={}for j=1 to 5 do
i=find(L[j],t,i+1)X&=i
end for
if find(0,X) then X={} end if?X

```

I can get it down to 126 characters if I use "or" instead of "and" like the C version does up above. However, this also matches the string `''!-!` as `llama`. Uncommon, but still a possible error.

```
object t=or_bits(gets(0),96),L="llama",i=0,X={}for j=1 to 5 do
i=find(L[j],t,i+1)X&=i
end for
if find(0,X) then X={} end if?X

```

And then the version using regular expressions:

```
include std/regex.e
include std/sequence.e
include std/utils.e
object X=regex:find(new("(?i)(l).*?(l).*?(a).*?(m).*?(a)"),gets(0))
? iff(atom(X),{},vslice(X[2..6],2))

```

Both take input from STDIN and post to STDOUT.

EDIT: Shorter regex example:

```
include std/regex.e
include std/sequence.e
object X=regex:find(new("(?i)(l).*?(l).*?(a).*?(m).*?(a)"),gets(0))
if atom(X)then?{}else?vslice(X[2..6],2)end if

```

# Answer
> 2 votes
# Python (70)

```
r=[];c=-1
for x in'llama':c=s.lower().find(x,c+1);r+=[c]
r*=1-(-1in r)

```

We search of each character in `'llama'` in turn, starting after the location of the previously-found character. If no character is found, `c` becomes the default value of `-1`, in which case the last line turns `r` into the empty list.

Edit: Found out that `str.find(s,...)` can be invoked as `s.find(...)`, saving 4 characters.

# Answer
> 2 votes
# Powershell - ~~121~~ 85

I'm still practicing with Powershell, expect this could be improved

$s contains the string, result is in array $a

Original version

```
$a=@();$w="llama";$n=$c=0;foreach ($i in $s.tochararray()) {if ($i -eq $w[$n]) {$a+=$c;$n+=1} $c+=1};$a*=$a.length -gt 4

```

Ungolfed

```
$a=@()
$w="llama"
$n=$c=0
foreach ($i in $s.tochararray()) {
 if ($i -eq $w[$n]) {
  $a+=$c
  $n+=1
 } $c+=1
}
$a*=$a.length -gt 4

```

New version, with massive thanks to @goric

```
$a=@();$n=$c=0;[char[]]$s|%{if($_-eq"llama"[$n]){$a+=$c;$n++}$c++};$a*=$a.length-gt4

```

# Answer
> 2 votes
# Jelly, 16 bytes

```
ŒlẹⱮ“ṫɠ»Ż>ƇḢ¥@\Ḋ

```

Try it online!

## How it works

```
ŒlẹⱮ“ṫɠ»Ż>ƇḢ¥@\Ḋ - Main link. Takes a string on the left
Œl               - Lowercase
    “ṫɠ»         - Compressed string: "llama"
   Ɱ             - For each character in "llama":
  ẹ              -   Find the indexes of that character in the input
        Ż        - Prepend 0
            ¥    - Last 2 links as a dyad f(x, y):
         >Ƈ      -   Keep elements of x greater than y
           Ḣ     -   Take the first element
             @\  - Reduce the list by the f(y, x)
               Ḋ - Dequeue

```

# Answer
> 1 votes
# PHP

no PHP answer yet? I think a language heavily string-oriented can beat at least a math-based one

```
function x($s){$i=$j=0;$r=str_split('llama');$s=strtolower($s);while($i<strlen($s)){if($s[$i]==$r[$j]){$r[$j]=$i;$j++;if($j>4)return$r;}$i++;}return[];}

```

152 against fortran 154, job done :P

ungolfed

```
function x($s){
    $i=$j=0;$r=str_split('llama');
    $s=strtolower($s);
    while($i<strlen($s)){
        if ($s[$i]==$r[$j]){
            $r[$j]=$i;
            $j++;
            if($j>4)
                return $r;
        }
        $i++;
    }
    return[];
}

```

if the caller always passes a lowercase string, it lowers to 137

# Answer
> 1 votes
# JavaScript, 122 115

```
function(s,b){z=[];for(i=0;i<5;i++){z.push(b=s.toLowerCase().indexOf("llama"[i],++b))};return z.indexOf(-1)<0?z:[]}

```

Defines a function that takes a string as its only argument (second arg is a cheap `var`) and returns either an empty array or a 5-element array.

Drops to 108 if I take the input on a single char variable (`s`) and leave the output in another (`b`):

```
var b=((z="llama".split('').map(function(a){return (b=s.toLowerCase().indexOf(a,++b))})).indexOf(-1)<0?z:[])

```

Edit: Swapped out map for for loop.

# Answer
> 1 votes
# APL, 47

```
+\↑⊃{a s←⍵⋄~⍺∊s:⍬⍬⋄a,←n←s⍳⍺⋄a(n↓s)}/'amall',⊂⍬⍞

```

Not the shortest code, but quite warped, in an APL way.

**Explanation**

`'amall',⊂⍬⍞` Make an array of 6 elements: the letters 'amall' and a subarray of 2 elements, themselves subarrays: the empty array and a line of characters read from input.

`{...}/...` Reduce (right-fold) the 6-element array using the provided function.

`a s←⍵` Decompose the right argument into the array of indices and the remaining substring (initially the empty array and the full string.)

`~⍺∊s:⍬⍬` If the substring does not contain the next letter  stop the computation and return the empty array.

`a,←n←s⍳⍺` Otherwise, find its position, call it n, and append it to the array of indices.

`a(n↓s)` Make and return an array of 2 elements: the extended array of indices and the remaining substring.

`+\↑⊃...` Unpack the output of the folding, take the first element (the array of indices) and scan it with addition, to turn relative offsets into absolute ones.

**Examples**

```
      +\↑⊃{a s←⍵⋄~⍺∊s:⍬⍬⋄a,←n←s⍳⍺⋄a(n↓s)}/'amall',⊂⍬⍞
All cats meow aloud.
2 3 6 10 15

```

```
      +\↑⊃{a s←⍵⋄~⍺∊s:⍬⍬⋄a,←n←s⍳⍺⋄a(n↓s)}/'amall',⊂⍬⍞
Some cats purr instead.

```

# Answer
> 1 votes
# Julia, 76

Another regex example using Julia language.

```
f(s)=(m=match(r"(?i)(l).*?(l).*?(a).*?(m).*?(a)",s);m==nothing?m:m.offsets)

```

# Answer
> 0 votes
# ARM Thumb-2 machine code, 42 bytes

Machine code (little endian hexdump):

```
2500 a208 f812 3b01 b15b 5d44 b144 3501
42a3 d003 f084 0420 42a3 d1f6 c120 e7f1
2100 4770 6c6c 6d61 0061

```

Commented assembly:

```
        .syntax unified
        .arch armv6t2
        .thumb
        .globl llama
        .thumb_func
        // Input:
        //    r0: null terminated string
        //    r1: output uint32_t array, must be 4 byte aligned
        // Output:
        //    if it matches, the ONE-INDEXED offsets are stored in r1
        //    otherwise, r1 is set to NULL. (Elements are still
        //    modified).
llama:
        // index
        movs    r5, #0
        // lookup table
        adr     r2, .LLAMA
        // loop through "llama"
.Llama:
        // Read byte from llama string, increment
        ldrb    r3, [r2], #1
        // end at null terminator
        cbz     r3, .LlAmA
.LLama:
        // r4 = str[r5]
        ldrb    r4, [r0, r5]
        // if we reach the null terminator, we don't have a match.
        cbz     r4, .LlaMa
        // increment r5 (this is what makes it one indexed)
        adds    r5, #1
        // check for a direct match
        cmp     r3, r4
        beq     .LLAma
        // flip the case by xoring 1<<5
        eor     r4, r4, #0b00100000
        // test the case when flipped
        cmp     r3, r4
        bne     .LLama
.LLAma:
        // *r1++ = index
        stm     r1!, {r5}
        // loop indefinitely (trip condition is the first cbz)
        b       .Llama
.LlaMa:
        // If we don't have a match, set r1 to NULL.
        movs    r1, #0
.LlAmA:
        // Otherwise, return.
        bx      lr
.LLAMA:
        .asciz  "llama"

```

---
Tags: code-golf, subsequence
---


# Question
Title: ASCII clock with dot & comma time markers
### Introduction

Imagine that line of chars is in fact two rows. **Upper row - dots - represents hours** (24 hour system), while **lower - commas - represents minutes**. One character can represent hour, minute or **both** \- whenever it's possible.

At first probably you'd have to convert minutes since midnight to *hours and minutes*.

The result is the string showing current time in "dot format". The dot count (**apostrophe counts here as a dot and will be called so!**) is the hour count since midnight and comma count is minutes count. I'll show a few examples to make it clear.

* (Remark) hh:mm - `result`
* (Only hours) 05:00 - `'''''`
* (Only minutes) 00:08 - `,,,,,,,,`
* (hours \< minutes) 03:07 - `;;;,,,,`
* (hours \> minutes) 08:02 - `;;''''''`
* (hours = minutes) 07:07 - `;;;;;;;`
* (the start of the day) 00:00 -  (*empty result*)

Notice that *"both" character* can be used max 23 times - for 23:xx, where xx is 23 or more.

### Symbols

If character **have to** (see rule 5.) be escaped in your language, you could changed it to one of alternatives. If said alternatives aren't enough, you may use other symbols - but keep it reasonable. I just don't want escaping to be a barrier.

* `;` (semicolon) - marker for both hours and minutes (alt: `:`)
* `'` (apostrophe) - marker for hours (alt: `'``°`)
* `,` (comma) - marker for minutes (alt: `.`)

### Additional rules

1. The code with the least amount of bytes wins!
2. You have to use *both symbol* whenever it's possible. For 02:04 the result can't be `'',,,,`, nor `;',,,`. It have to be `;;,,`
3. Input - can be script/app parameter, user input (like readline) or variable inside code
3.1. If the variable inside code is used, then its lenght have to be the longest possible. It's `1439` (23:59), so it would look like `t=1439`
4. The common part which is symbolized by *"both" character* (12 in 12:05, 3 in 03:10) must be placed on the beginning of the string
5. Symbols can be replaced to alternatives only if they would have to be escaped in your code.
6. Input is given in minutes after **00:00**. You can assume that this is a non-negative integer.

### Test cases

```
Input: 300
Output: '''''

Input: 8
Output: ,,,,,,,,

Input: 187
Output: ;;;,,,,

Input: 482
Output: ;;''''''

Input: 427
Output: ;;;;;;;

Input: 0
Output:  (empty)

```

# Answer
# Pyth, 19 bytes

```
:.iF*V.DQ60J"',"J\;

```

Test suite

```
:.iF*V.DQ60J"',"J\;
      .DQ60            Divmod the input by 60, giving [hours, minutes].
           J"',"       Set J equal to the string "',".
    *V                 Perform vectorized multiplication, giving H "'" and M ','.
 .iF                   Interleave the two lists into a single string.
:               J\;    Perform a substitution, replacing J with ';'.

```
> 10 votes

# Answer
## CJam, ~~22~~ ~~20~~ 19 bytes

Takes input from STDIN:

```
ri60md]',`.*:.{;K+}

```

Test it here.

### Explanation

```
ri     e# Read input and convert to integer.
60md   e# Divmod 60, pushes hours H and minutes M on the stack.
]      e# Wrap in an array.
',`    e# Push the string representation of the comma character which is "',".
.*     e# Repeat apostrophe H times and comma M times.
:.{    e# Apply this block between every pair of characters. This will only applied to
       e# first N characters where N = min(hours,minutes). The others will remain
       e# untouched. So we want the block to turn that pair into a semicolon...
  ;    e#   Discard the comma.
  K+   e#   Add 20 to the apostrophe to turn it into a semicolon.
}

```

It was really lucky how well things worked together here, in particular the assignment of hours to `'` and minutes to `,` such that the order of hours and minutes on the stack matched up with the string representation of the character.

This is the only 3-byte block I've found so far. There were tons of 4-character solutions though:

```
{;;';}
{';\?}
{^'0+}
{^'F-}
{-'@+}
{-'6-}
...

```
> 8 votes

# Answer
# GNU Sed, 37

Score includes +1 for `-E` option to sed.

I wasn't particularly impressed with the golfiness of my bash answer, so I thought I'd try with sed for the fun.

Input is in unary, as per this meta-answer.

```
y/1/,/          # Convert unary 1's to commas (minutes)
s/,{60}/'/g     # divmod by 60.  "'" are hours
:               # unnamed label
s/(.*)',/;\1/   # replace an apostrophe and comma with a semicolon
t               # jump back to unnamed label until no more replacements

```

Try it online
> 6 votes

# Answer
## Python 2, 56 bytes

```
def g(t):d=t%60-t/60;print(t/60*";")[:t%60]+","*d+"'"*-d

```

A function that prints (one char shorter than `t=input();`).

The method is similar to Loovjo's. The number of `,` is the different between minutes and hours, with an implicit minimim of 0. For `'`, it's the negation. For `;`, computes the `min` implicitly by taking as many `;` as hours, then truncating to the number of minutes.

It saves chars to save `d`, but not the number of hours and minutes here. The analogue with lambda was two chars longer (58), so the variable assignments are worth it.

```
lambda t:(t%60*";")[:t/60]+","*(t%60-t/60)+"'"*(t/60-t%60)

```

Processing the input directly didn't save chars either (58):

```
h,m=divmod(input(),60);d=m-h;print(";"*m)[:h]+","*d+"'"*-d

```

Another strategy with slicing, much longer (64):

```
def g(t):m=t%60;h=t/60;return(";"*m)[:h]+(","*m)[h:]+("'"*h)[m:]

```
> 6 votes

# Answer
# Pure Bash (no external utilities), 103

```
p()(printf -vt %$2s;printf "${t// /$1}")
p \; $[h=$1/60,m=$1%60,m>h?c=m-h,h:m]
p , $c
p \' $[m<h?h-m:0]

```

Thanks to @F.Hauri for saving 2 bytes.
> 3 votes

# Answer
# Retina, 24

Trivial port of my sed answer.

Input is in unary, as per this meta-answer.

```
1
,
,{60}
'
+`(.*)',
;$1

```

Try it online.
> 3 votes

# Answer
# C, 119 bytes

```
#define p(a,b) while(a--)putchar(b);
main(h,m,n){scanf("%d",&m);h=m/60;m%=60;n=h<m?h:m;h-=n;m-=n;p(n,59)p(h,39)p(m,44)}

```

Detailed

```
// macro: print b, a times
#define p(a,b) while(a--)putchar(b)

int main(void)
{
    int h,m,n;
    scanf("%d",&m);  // read input

    h=m/60;m%=60;    // get hours:minutes
    n=h<m?h:m;       // get common count
    h-=n;m-=n;       // get remaining hours:minutes

    p(n,59);        // print common
    p(h,39);        // print remaining hours
    p(m,44);        // print remaining minutes

    return 0;
}

```
> 3 votes

# Answer
# Haskell, ~~68~~ 66 Bytes

```
g(h,m)=id=<<zipWith replicate[min h m,h-m,m-h]";',"
g.(`divMod`60)

```

Usage example:

```
(g.(`divMod`60)) 482

```

The clever bit here is that `replicate` will return the empty string if the length given is negative or zero so I can apply it to both differences and only the positive one will show up. The first part is easy, since the number of semicolons is just the minimum of the two. Then `zipWith` applies the function to the corresponding items.

EDIT: Realized I was using the wrong char for minutes

EDIT 2: Saved 2 bytes thanks to @Laikoni
> 3 votes

# Answer
# JavaScript (ES6) 69

```
m=>";".repeat((h=m/60|0)>(m%=60)?m:h)+",'"[h>m|0].repeat(h>m?h-m:m-h)

```
> 2 votes

# Answer
# Powershell, ~~99~~ 85 bytes

`param($n)";"*(($m=$n%60),($h=$n/60))[($b=$m-gt$h)]+"'"*(($h-$m)*!$b)+","*(($m-$h)*$b)`

Using Loovjo's method, this is my powershell implementation.

ungolfed

```
param($n)
# set the number of minutes and hours, and a boolean which one is bigger
# and also output the correct number of ;s
";"*(($m=$n%60),($h=$n/60))[($b=$m-gt$h)]+
# add the difference between h and m as 's but only if h > m
"'"*(($h-$m)*!$b)+
# add the difference between m and h as ,s but only if m > h
","*(($m-$h)*$b)

```

Saved 14 bytes thanks to AdmBorkBork
> 2 votes

# Answer
# Python 3, 98 bytes

```
d=int(input());m=d%60;h=int((d-m)/60)
if m>=h:print(";"*h+","*(m-h))
else:print(";"*(m)+"'"*(h-m))

```

Probably not the best answer, but it was a lot of fun!
> 1 votes

# Answer
# Python 2, 61 bytes

```
t=input();m,h=t%60,t/60
print";"*min(h,m)+","*(m-h)+"'"*(h-m)

```

Explaination:

```
t=input();              # Read input
          m,  t%60,     # Do a divmod, h = div, m = mod
            h=     t/60

print";"*min(h,m)+                    # Print the minimum of the h and m, but in ";"s
                  ","*(m-h)+          # Print (m-h) ","s (if m-h is negative, print nothing)
                            "'"*(h-m) # Print (h-m) "'"s (if h-m is negative, print nothing)

```
> 1 votes

# Answer
# PHP, 81 bytes

I went for the variable input as it is shorter than reading from `STDIN` or taking command line arguments.

```
for($_=1439;$i<max($h=0|$_/60,$m=$_%60);++$i)echo$i<$h?$i<min($h,$m)?';':"'":",";

```
> 1 votes

# Answer
# JavaScript (ES6), ~~77~~ 71 bytes

```
x=>';'[r='repeat'](y=Math.min(h=x/60|0,m=x%60))+"'"[r](h-y)+','[r](m-y)

```
> 1 votes

# Answer
# Perl 6, ~~103~~ ~~101~~ ~~98~~ ~~97~~ 69 bytes

```
$_=get;say ";"x min($!=($_-$_%60)/60,$_=$_%60)~"'"x $!-$_~","x $_-$!;

```

~~Outputs several arrays, but fuck it,~~ enjoy. As usual, any golfing oppertunities are appericated.

Edit: -2 bytes: got brave and removed some casts.

Edit2: -3 bytes by removing the arrays.

Edit3: -1 byte to print in right format, using "lambdas" and removing parantheses.

Edit4: (sorry guys) abusing that hours - minutes should return 0 and the opposite. Removed if statements. Then removing brackets, then realising i didnt need the lambda at all. -28 bytes :)

Woah im getting better at this.
> 1 votes

# Answer
# C, 141 bytes

```
main(h,m){scanf("%d",&m);h=(m/60)%24;m%=60;while(h||m){if(h&&m){printf(";");h--;m--;}else if(h&&!m){printf("'");h--;}else{printf(",");m--;}}}

```
> 0 votes

# Answer
# Ruby, 50 characters

```
->t{(?;*h=t/60)[0,m=t%60]+",',"[0<=>m-=h]*m.abs}

```

Thanks to:

* G B for
    + reminding me that I can't take more characters from a string than it has (-1 character)
    + reorganizing my calculation (-1 character)

Waited so long to use `Numeric.divmod`, just to realize that its horribly long.

Sample run:

```
2.1.5 :001 > puts ->t{(?;*h=t/60)[0,m=t%60]+",',"[0<=>m-=h]*m.abs}[252]
;;;;,,,,,,,,

```
> 0 votes

# Answer
# Gema, 119 characters

```
<D>=@set{h;@div{$0;60}}@set{m;@mod{$0;60}}@repeat{@cmpn{$h;$m;$h;$h;$m};\;}@repeat{@sub{$h;$m};'}@repeat{@sub{$m;$h};,}

```

Sample run:

```
bash-4.3$ gema '<D>=@set{h;@div{$0;60}}@set{m;@mod{$0;60}}@repeat{@cmpn{$h;$m;$h;$h;$m};\;}@repeat{@sub{$h;$m};`}@repeat{@sub{$m;$h};,}' <<< '252'
;;;;,,,,,,,,

```
> 0 votes

# Answer
## Matlab: 89 bytes

```
i=input('');m=mod(i,60);h=(i-m)/60;[repmat(';',1,min(h,m)),repmat(39+5*(m>h),1,abs(h-m))]

```

Test:

```
310
ans =
;;;;;,,,,,

```
> 0 votes

# Answer
# SmileBASIC, 59 bytes

```
INPUT M
H%=M/60M=M-H%*60?";"*MIN(H%,M);",'"[M<H%]*ABS(H%-M)

```

Explained:

```
INPUT MINUTES 'input
HOURS=MINUTES DIV 60 'separate the hours and minutes
MINUTES=MINUTES MOD 60
PRINT ";"*MIN(HOURS,MINUTES); 'print ;s for all positions with both
PRINT ",'"[MINUTES<HOURS]*ABS(HOURS-MINUTES) 'print extra ' or ,

```

It looks pretty terrible, since the bottom part of `;` is not even the same as `,` in SmileBASIC's font
> 0 votes

# Answer
# PHP, 81 bytes

some more solutions:

```
echo($r=str_repeat)(";",min($h=$argn/60,$m=$argn%60)),$r(",`"[$h>$m],abs($h-$m));
// or
echo($p=str_pad)($p("",min($h=$argn/60,$m=$argn%60),";"),max($h,$m),",`"[$h>$m]);

```

Run with `echo <time> | php -R '<code>'`.

```
<?=($r=str_repeat)(";",min($h=($_=1439)/60,$m=$_%60)),$r(",`"[$h>$m],abs($h-$m));
// or
<?=($r=str_repeat)(";",min($h=.1/6*$_=1439,$m=$_%60)),$r(",`"[$h>$m],abs($h-$m));
// or
<?=str_pad(str_pad("",min($h=($_=1439)/60,$m=$_%60),";"),max($h,$m),",`"[$h>$m]);

```

Replace `1439` with input, save to file, run.
> 0 votes

# Answer
# Java 8, ~~101~~ ~~99~~ 86 bytes

```
n->{String r="";for(int m=n%60,h=n/60;h>0|m>0;r+=h--*m-->0?";":h<0?",":"'");return r;}

```

**Explanation:**

Try it here.

```
n->{                      // Method with integer parameter and String return-type
  String r="";            //  Result-String (starting empty)
  for(int m=n%60,h=n/60;  //   Get the minutes and hours from the input integer
      h>0|m>0;            //   Loop as long as either the hours or minutes is above 0
    r+=                   //   Append the result-String with:
       h--*m-->0?         //    If both hours and minutes are above 0
                          //    (and decrease both after this check):
        ";"               //     Use ";"
       :h<0?              //    Else-if only minutes is above 0 (hours is below 0)
        ","               //     Use ","
       :                  //    Else:
        "'"               //     Use "'"
  );                      //  End loop
  return r;               //  Return the result
}                         // End of method

```
> 0 votes

# Answer
# 05AB1E, 25 bytes

```
60‰vy„'.Nè×}‚.BøJ„'.';:ðK

```

Try it online!

`60‰vy„'.Nè×}` can definitely be shortened, I just couldn't figure it out, and doubt I'll be able to shave off 7 bytes to win with this approach unless there's a vectored version of `×`.

---

Example (With input equal to 63):

```
60‰                       # Divmod by 60.
                          # STACK: [[1,3]]
   vy      }              # For each element (probably don't need the loop)...
                          # STACK: []
     „'.Nè×               # Push n apostrophe's for hours, periods for minutes.
                          # STACK: ["'","..."]
            ‚             # Group a and b.
                          # STACK: [["'","..."]]
             .B           # Boxify.
                          # STACK: [["'  ","..."]]
               ø          # Zip it (Transpose).
                          # STACK: [["'."," ."," ."]
                J         # Join stack.
                          # STACK: ["'. . ."]
                 „'.';:   # Replace runs of "'." with ";".
                          # STACK: ["; . ."]
                       ðK # Remove all spaces.
                          # OUTPUT: ;..

```

---

`D60÷''×s60%'.×‚.BøJ„'.';:ðK` was my original version, but that's even MORE costly than divmod.

`60‰WDµ';ˆ¼}-¬0Qi'.ë''}Z×¯ìJ` yet another method I tried...
> 0 votes

# Answer
# dc, 95 bytes

```
[60~sdsp39sj]sd[60~spsd44sj]se?ddd60~<d60~!<e[59Plp1-spld1-dsd0<y]syld0<y[ljPlp1-dsp0<y]sylp0<y

```

Try it online!
> 0 votes

# Answer
# ///, 49 bytes

```
/x/1111111111//xxxxxx/o//oo1/o1o//o1/;//o/'//1/,/

```

Try it online!

The first two substitutions, `/x/1111111111//xxxxxx/o/`, replace sequences of 60 `1`s with an `o`.

`/oo1/o1o/` interweaves the `1`s into the `o`s, which are next to each other. Ex. `oooooo1111111111 -> o1o1o1o1o1o11111` This pairs each o, which is one hour, with one 1, which is minute. This also pushes the `1`s to the left, so whichever one is greater is left at the right.

`o1/;/` replaces each pair with a ;

`/o/'/ /1/1/` and this converts the leftovers to `:`s or `'`s
> 0 votes

# Answer
# Jelly, 13 bytes

```
d60Ø½ẋ"Sị“',;

```

Try it online!

## Explanation

```
d60Ø½ẋ"Sị“',;   Main monadic link
d60             Divmod by 60
      "         Zipmap
   Ø½             [1, 2]
                  with that
     ẋ            using the “repeat n times” operator
       S        Sum
        ị       Index into
         “',;   "',;"

```
> 0 votes

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