title: Code Romanization

text:
# Question
Title: Code Romanization
The challenge is to make any Roman numerals valid code in your chosen language.

They should **not** appear inside of strings or anything similar, but work just like any other tokens, literals such as (Arabic) numbers, characters or strings; or variable/method/function identifiers, etc.

For instance, in Java, the following would have to compile and run just as if `i` was initialized to `42`:

```
int i = XLII;

```

The actual parsing of the numerals is secondary, so you can use a library if you want to, but this is a popularity contest, so creativity is encouraged.

You cannot use any language that actually uses roman numerals, if there is such a thing.

Good luck.

# Answer
# C

There are only so many Roman numerals, since 4000 and higher have no standard notation, and the preprocessor is a wonderful decompression tool, especially if you have no problems with the fact that the code has undefined behaviour.

```
enum{_
#define a_
#define d_
#define g_
#define j_
#define a(x)c(x)b
#define b(x)c(x)a
#define c(x)x,
#define d(x)f(x)e
#define e(x)f(x)d
#define f(x)m(a(x)(x##I)(x##II)(x##III)(x##IV)(x##V)(x##VI)(x##VII)(x##VIII)(x##IX))
#define g(x)i(x)h
#define h(x)i(x)g
#define i(x)m(d(x)(x##X)(x##XX)(x##XXX)(x##XL)(x##L)(x##LX)(x##LXX)(x##LXXX)(x##XC))
#define j(x)l(x)k
#define k(x)l(x)j
#define l(x)m(g(x)(x##C)(x##CC)(x##CCC)(x##CD)(x##D)(x##DC)(x##DCC)(x##DCCC)(x##CM))
#define m(x)n(x)
#define n(...)__VA_ARGS__##_
m(j()(M)(MM)(MMM))
};

```

This defines all Roman numerals from `I` to `MMMCMXCIX` as enumeration constants, plus `_` (which can be replaced by anything you like) as zero.
> 40 votes

# Answer
## Ruby

```
def Object.const_missing(const)
  i = const.to_s
  if i =~ /^[IVXLCDM]+$/
    #http://codegolf.stackexchange.com/questions/16254/convert-arbitrary-roman-numeral-input-to-integer-output
    %w[IV,4 IX,9 XL,40 XC,90 CD,400 CM,900 I,1 V,5 X,10 L,50 C,100 D,500 M,1000].map{|s|k,v=s.split ?,;i.gsub!(k,?++v)}
    eval(i)
  else
    super
  end
end

```

Any (uppercase) Roman numerals will now be parsed like their decimal equivalents. The only issue is that they're still assignable: you can do `X = 9`, but not `10 = 9`. I don't think there's a way to fix that.
> 16 votes

# Answer
# JavaScript (ES6)

Use `Proxy` to catch roman numerals.

Testable in Firefox (latest) on JSFiddle.
Not testable in Chrome (with Traceur) since `Proxy` implementation is broken.

```
// Convert roman numeral to integer.
// Borrowed from http://codegolf.stackexchange.com/a/20702/10920
var toDecimal = (s) => {
  var n = 0;
  var X = {
    M: 1e3, CM: 900, D: 500, CD: 400, C: 100, XC: 90,
    L: 50,  XL: 40,  X: 10,  IX: 9,   V: 5,   IV: 4,  I: 1
  };

  s.replace(/[MDLV]|C[MD]?|X[CL]?|I[XV]?/g, (d) => n += X[d]);
  return n;
};

// Whether a string is a valid roman numeral.
var isRoman = (s) => s.match(/^[MDCLXVI]+$/);

// Profixy global environment to catch roman numerals.
// Since it uses `this`, global definitions are still accessible.
var romanEnv = new Proxy(this, {
  get: (target, name) => isRoman(name) ? toDecimal(name) : target[name],
  set: (target, name, value) => isRoman(name) ? undefined : (target[name] = value),
  has: (target, name) => isRoman(name) || name in target,
  hasOwn: (target, name) => name in target
});

```

Usage:

```
with (romanEnv) {
  var i = MIV + XLVIII;
  console.log(i); // 1052
}

```
> 12 votes

# Answer
# C & C++ (Updated Answer)

As observed in a comment, my original solution had two problems:

1. Optional parameters are only available in C99 and later standards of the language family.
2. Trailing comma in enum definition is also specific to C99 and later.

Since I wanted my code to be as generic as possible to work on older platforms, I decided to take another stab at it. It is longer than it was before, but it works on compilers and preprocessors set to C89/C90 compatibility mode. All macros are passed an appropriate number of arguments in the source code, though sometimes those macros "expand" into nothing.

Visual C++ 2013 (aka version 12) emits warnings about missing parameters, but neither mcpp (an open source preprocessor that claims high compliance with the standard) nor gcc 4.8.1 (with -std=iso9899:1990 -pedantic-errors switches) emit warnings or errors for those macro invocations with an effectively empty argument list.

After reviewing the relevant standard (ANSI/ISO 9899-1990, 6.8.3, Macro Replacement), I think there is sufficient ambiguity that this should not be considered non-standard. "The number of arguments in an invocation of a function-like macro shall agree with the number of parameters in the macro definition...". It does not seem to preclude an empty argument list as long as the needed parentheses (and commas in the case of multiple parameters) are in place to invoke the macro

As for the trailing comma problem, that is resolved by adding an extra identifier to the enumeration (in my case, MMMM which seems as reasonable as anything for the identifier to follow 3999 even if it doesn't obey the accepted rules of Roman numeral sequencing exactly).

A slightly cleaner solution would involve moving the enum and supporting macros to a separate header file as was implied in a comment elsewhere, and using undef of the macro names immediately after they were used so as to avoid polluting the namespace. Better macro names should undoubtedly be chosen as well, but this is adequate for the task at hand.

My updated solution, followed by my original solution:

```
#define _0(i,v,x)
#define _1(i,v,x) i
#define _2(i,v,x) i##i
#define _3(i,v,x) i##i##i
#define _4(i,v,x) i##v
#define _5(i,v,x) v
#define _6(i,v,x) v##i
#define _7(i,v,x) v##i##i
#define _8(i,v,x) v##i##i##i
#define _9(i,v,x) i##x

#define k(p,s) p##s,
#define j(p,s) k(p,s)
#define i(p) j(p,_0(I,V,X)) j(p,_1(I,V,X)) j(p,_2(I,V,X)) j(p,_3(I,V,X)) j(p,_4(I,V,X)) j(p,_5(I,V,X)) j(p,_6(I,V,X)) j(p,_7(I,V,X)) j(p,_8(I,V,X)) j(p,_9(I,V,X))
#define h(p,s) i(p##s)
#define g(p,s) h(p,s)
#define f(p) g(p,_0(X,L,C)) g(p,_1(X,L,C)) g(p,_2(X,L,C)) g(p,_3(X,L,C)) g(p,_4(X,L,C)) g(p,_5(X,L,C)) g(p,_6(X,L,C)) g(p,_7(X,L,C)) g(p,_8(X,L,C)) g(p,_9(X,L,C))
#define e(p,s) f(p##s)
#define d(p,s) e(p,s)
#define c(p) d(p,_0(C,D,M)) d(p,_1(C,D,M)) d(p,_2(C,D,M)) d(p,_3(C,D,M)) d(p,_4(C,D,M)) d(p,_5(C,D,M)) d(p,_6(C,D,M)) d(p,_7(C,D,M)) d(p,_8(C,D,M)) d(p,_9(C,D,M))
#define b(p) c(p)
#define a() b(_0(M,N,O)) b(_1(M,N,O)) b(_2(M,N,O)) b(_3(M,N,O))

enum { _ a() MMMM };

#include <stdio.h>

int main(int argc, char** argv)
{
    printf("%d", MMMCMXCIX * MMMCMXCIX);
    return 0;
}

```

The original answer (which received the first six upvotes, so if no one ever upvotes this again, you shouldn't think my updated solution got the upvotes):

In the same spirit as an earlier answer, but done in a way that *should* be portable using only defined behavior (though different environments don't always agree on some aspects of the preprocessor). Treats some parameters as optional, ignores others, it should work on preprocessors that don't support the `__VA_ARGS__` macro, including C++, it uses indirect macros to ensure parameters are expanded before token pasting, and finally it is shorter and I think easier to read (though it is still tricky and probably not *easy* to read, just easier):

```
#define g(_,__) _, _##I, _##II, _##III, _##IV, _##V, _##VI, _##VII, _##VIII, _##IX,
#define f(_,__) g(_,)
#define e(_,__) f(_,) f(_##X,) f(_##XX,) f(_##XXX,) f(_##XL,) f(_##L,) f(_##LX,) f(_##LXX,) f(_##LXXX,) f(_##XC,)
#define d(_,__) e(_,)
#define c(_,__) d(_,) d(_##C,) d(_##CC,) d(_##CCC,) d(_##CD,) d(_##D,) d(_##DC,) d(_##DCC,) d(_##DCCC,) d(_##CM,)
#define b(_,__) c(_,)
#define a       b(,) b(M,) b(MM,) b(MMM,)
enum { _ a };

```
> 12 votes

# Answer
# Common Lisp

The following is a rather lengthy explanation of how I made a macro that you can use like this:

```
(roman-progn
  (+ XIV XXVIII))

```

When a macro is called in Common Lisp, it basically acts like a function, only that the arguments are received *before* they are evaluated. Actually, since in Common Lisp code is just data, what we receive is a (nested) list representing an unparsed syntax tree that we can do whatever we want with, and it's done in compile-time.

### Helper functions

The first step of the plan is to take this tree and scan it for anything that looks like Roman Numerals. This being Lisp and all, let's try to do it somewhat functionally: We need a function that will do a deep traversal of a tree and return every object for which a provided function `searchp` returns true. This one is even (semi) tail-recursive.

```
(defun deep-find-all (searchp tree &optional found)
  (if (null tree)
    found
    (let* ((item (car tree))
           (new-found (if (consp item)
                        (deep-find-all searchp item found)
                        (if (funcall searchp item)
                          (cons item found)
                          found))))

      (deep-find-all searchp (cdr tree) new-found))))

```

Then some code for parsing the roman numerals, courtesy of Rosetta Code:

```
(defun mapcn (chars nums string)
  (loop as char across string as i = (position char chars) collect (and i (nth i nums))))

(defun parse-roman (R)
  (loop with nums = (mapcn "IVXLCDM" '(1 5 10 50 100 500 1000) R)
        as (A B) on nums if A sum (if (and B (< A B)) (- A) A)))

```

### The actual macro

We take the syntax tree (`body`), search it with our deep-find-all procedure and somehow make the roman numerals that we find, available.

```
(defmacro roman-progn (&body body)
  (let* ((symbols (deep-find-all (lambda (sym)
                                   (and
                                     (symbolp sym)
                                     (loop for c across (string sym)
                                           always (find c "IVXLCDM")))) body))
         (parsed-romans (mapcar (lambda (sym)
                                  (list sym (parse-roman (string sym)))) symbols)))

    (if parsed-romans
      `(let (,@parsed-romans)
         ,@body)
      `(progn
         ,@body))))

```

So, what is `1 + 2 + 3 + (4 * (5 + 6)) + 7` ?

```
(roman-progn
  (+ I II III (* IV (+ V VI)) VII))
=> 57

```

And to see what actually happened when the macro was invoked:

```
(macroexpand-1 +)
=> (LET ((VII 7) (VI 6) (V 5) (IV 4) (III 3) (II 2) (I 1))
   (+ I II III (* IV (+ V VI)) VII))

```
> 9 votes

# Answer
# Lua

```
setmetatable(_G, {
    __index = function(_, k)
        if k:match"^[IVXLCDM]*$" then
            local n = 0
            for _, v in ipairs{{IV = 4}, {IX = 9}, {I = 1}, {V = 5}, {XL = 40}, {X = 10}, {XC = 900}, {CD = 400}, {CM = 900}, {C = 100}, {D = 500}, {M = 1000}} do
                local p, q = next(v)
                local r
                k, r = k:gsub(p, "")
                n = n + r * q
            end
            return n
        end
    end
})

```

Simply a fallback \__index for the global table. The actual conversion using gsub turned out much prettier than I imagined it to be.
> 7 votes

# Answer
# Smalltalk (Smalltalk/X) (87/101 chars)

of course we could easily modify the parser's tokenizer (as it is part of the class library, and as such open for modification, and always present), but a challenge is to affect only evaluations in a given context, so that the rest of the system works as usual.

### Version 1:

define a number of variables in the evaluation namespace. So this will affect interactive doIts (aka evals):

```
(1 to:3999) do:[:n |
    Workspace workspaceVariables at:(n romanPrintString asUppercase) put:n]

```

then I can do (in a doIt, but not in compiled code):

```
   |a b|
   a := MMXIV.
   b := V.
   a + b

```

-\> 2019

Notice: the 101 chars includes whitespace; actually it can be done with 87 chars.
Also notice, when define in the global Smalltalk namespace, I'd see those constants also in compiled code.

### Version 2:

Use a methodWrapper hook, which allows for any existing code to be wrapped without recompiling. The following wraps the Parser's tokenizer to look for a roman identifier to be scanned and makes it an integer. The tricky part is to dynamically detect if the calling context is from the roman empire or not. This is done using a query signal (which is technically a proceedable exception):

define the query:

```
InRomanScope := QuerySignal new defaultAnswer:false.

```

So we can ask at any time ("InRomanScope query") to get false by default.

Then wrap the scanner's checkIdentifier method:

```
MessageTracer
    wrapMethod:(Scanner compiledMethodAt:#checkForKeyword:)
    onEntry:nil
    onExit:[:ctx :ret |
        InRomanScope query ifTrue:[
            |scanner string token n|

            scanner := ctx receiver.
            string := ctx argAt:1.
            (n := Integer readFromRomanString:string onError:nil) notNil
            ifTrue:[
                scanner "/ hack; there is no setter for those two
                    instVarNamed:'tokenType' put:#Integer;
                    instVarNamed:'tokenValue' put:n.
                true
            ] ifFalse:[
                ret
            ].
        ] ifFalse:[
            ret
        ]
    ].

```

Now the scanner works as usual, unless we are in the roman empire:

```
InRomanScope answer:true do:[
    (Parser evaluate:'MMDXXV') printCR.
].

```

-\> 2525

we can even compile code:

```
Compiler
    compile:'
        inTheYear2525
            ^ MMDXXV
    '
    forClass:Integer.

```

nice try; but this fails with a syntax error (which is exactly what we want). However, in the roman empire, we CAN compile:

```
InRomanScope answer:true do:[

    Compiler
        compile:'
            inTheYear2525
                ^ MMDXXV
        '
        forClass:Integer.
]

```

and now, we can ask any integer (sending that message) from inside and outside of Rome:

```
(1000 factorial) inTheYear2525

```

-\> 2525
> 5 votes

# Answer
# Postscript

I tried to follow the C one but I didn't understand it. So I did it this way:

```
/strcat{
    2 copy length exch length add string % 1 2 3
    3 2 roll % 2 3 1
    2 copy 0 exch putinterval % 2 3 1
    2 copy length % 2 3 1 3 n(1)
    5 4 roll putinterval % 3 1
    pop
}def
/S{
    dup length string cvs
} def
[
/u {/ /I /II /III /IV /V /VI /VII /VIII /IX}
/t {/ /X /XX /XXX /XL /L /LX /LXX /LXXX /XC}
/h {/ /C /CC /CCC /CD /D /DC /DCC /DCCC /CM}
/m {/ /M /MM /MMM /MMMM}
>>begin
[0
[
[m]{ % M*
    S
    [h]{ % M* H*
        S
        [t]{ % M* H* T*
            S
            [u]{ % M* H* T* U*
                S
                4 copy
                strcat strcat strcat % M* H* T* U* M*H*T*U*
                5 1 roll % M*H*T*U* M* H* T* U*
                pop % (M*H*T*U*)* M* H* T*
            }forall
            pop % (M*H*T*U*)** M* H*
        }forall
        pop % (M*H*T*U*)*** M*
    }forall
    pop % (M*H*T*U*)****
}forall
]
{exch dup 1 add}forall pop>>end begin

```

Postscript doesn't have `enum` but we can construct a dictionary with sequential integer values and fold them into an array. This reduces the problem to generating all the strings in sequence, which is done by concatenating in 4 nested loops. So it generates all the strings, then interleaves each string with an increasing counter value, resulting in a long series of *\<string\> \<int\>* pairs on the stack which are wrapped in `<<`...`>>` to produce a dictionary object.

The program constructs and installs a dictionary mapping all names for the roman numerals to their corresponding value. So mentioning the names in source text invokes the automatic name-lookup and yields the integer value on the stack.

```
II IV MC pstack

```

prints

```
2
4
600

```
> 5 votes

# Answer
## D

using D's compile time function evaluation

```
import std.algorithm;
string numerals(){
    auto s = cartesianProduct(["","I","II","III","IV","V","VI","VII","VIII","IX"],
                              ["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"],
                              ["","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"],
                              ["","M","MM","MMM"]);
    s.popFront();//skip first
    char[] result="enum ";
    int i=1;
    foreach(p;s){
        result~=p[3]~p[2]~p[1]~p[0]~"="~i++~",";
    }
    result[$-1]=';';//replace last , with a ;
    return result.idup;
}
mixin(numerals());

```
> 5 votes

# Answer
# J - 78 char

This only goes up to MMMCMXCIX = 3999, as with the other solutions.

```
(}.,;L:1{M`CDM`XLC`IVX('';&;:(_1,~3#.inv]){' ',[)&.>841,3#79bc5yuukh)=:}.i.4e3

```

Breaking it down (recall J is usually read from right to left, unless superseded by parentheses):

* `M`CDM`XLC`IVX` \- Four boxes of letters. We're going to use numeric arrays into index into these letters and build up subwords of Roman numerals.
* `841,3#79bc5yuukh` \- This is the numeric data, tightly encoded.\*
* `(_1,~3#.inv])` \- This will decode the above data, by expanding in ternary and appending -1.
* `('';&;:(...){' ',[)&.>` \- Pairing up the numbers on the left with the boxes on the right (`&.>`), decode the arrays of numbers and use them to index into the letters. We treat 0 as space by prepending a space character to the letter lists. This procedure builds lists of words like `I II III IV V VI VII VIII IX` and `M MM MMM`.
* `{` \- Take the Cartesian product of these four boxes full of words. Now we have a 4D array of all the Roman numerals.
* `}.,;L:1` \- Run all that into a single 1D list of Roman numerals, and remove the empty string at the front because it would create an error. (`L:` is a rare sight in J golf! Usually there are not this many levels of boxing involved.)
* `}.i.4e3` \- The integers from 0 to 4000, *excluding* the endpoints.
* Finally, we put everything together with a global assignment `=:`. J allows you to have a boxed list of names on the LHS, as a form of computed multiple assignment, so this works out fine.

Now the J namespace is full of variables representing Roman numerals.

```
   XCIX
99
   MMCDLXXVIII
2478
   V * LXIII   NB. 5*63
315
   #4!:1]0     NB. How many variables are now defined in the J namespace?
3999

```

* I need the number 2933774030998 to later be read in base 3. It so happens that I can express it in base 79 using digits no greater than 30, which is good because J can only understand digits up to 35 (0-9 and then a-z). This saves 3 characters over decimal.
> 5 votes

# Answer
Haskell, using meta-programming in Template Haskell and roman-numerals:

```
{-# LANGUAGE TemplateHaskell #-}
import Data.Char (toLower)
import Language.Haskell.TH
import Text.Numeral.Roman

$( mapM (\n -> funD (mkName . map toLower . toRoman $ n)
                    [ clause [] (normalB [| n |]) []]) $ [1..1000 :: Int] )

main = print xlii

```

Haskell reserves identifiers starting with upper case letters for constructors, so I used lower-case.
> 4 votes

# Answer
## Python

The Idea is simple as the other answers. But Just to be neat and not to pollute the global namespace, a context manager is used. This also imposes the restriction, that you need to declare before hand, the extent of Roman numerical you are planning to use.

**Note** Just to keep it simple, and not to reinvent the wheel, I have utilized the Roman python package

**Implementation**

```
class Roman(object):
    memo = [0]
    def __init__(self, hi):
        import rome
        if hi <= len(RomanNumericals.memo):
            self.romans = Roman.memo[0:hi]
        else:
            Roman.memo += [str(rome.Roman(i))
                    for i in range(len(Roman.memo),
                            hi+1)]
            self.romans = Roman.memo
    def __enter__(self):
        from copy import copy
        self.saved_globals = copy(globals())
        globals().update((v,k) for k,v in enumerate(self.romans[1:], 1))
    def __exit__(self,*args ):
        globals().clear()
        globals().update(self.saved_globals)

```

**Demo**

```
with Roman(5):
    with Roman(10):
        print X
    print V
    print X

10
5

Traceback (most recent call last):
  File "<pyshell#311>", line 5, in <module>
    print X
NameError: name 'X' is not defined

```
> 3 votes

# Answer
# Rebol

```
Rebol []

roman-dialect: func [
    {Dialect which allows Roman numerals as numbers (integer!)}
    block [block!]
    /local word w m1 m2 when-in-rome rule word-rule block-rule
  ][
    when-in-rome: does [
        if roman? w: to-string word [change/part m1 roman-to-integer w m2]
    ]

    word-rule:  [m1: copy word word! m2: (when-in-rome)]
    block-rule: [m1: any-block! (parse m1/1 rule)]
    rule:       [any [block-rule | word-rule | skip]]

    parse block rule
    do block
]

; couple of helper functions used in above parse rules

roman-to-integer: func [roman /local r eval] [
    r: [IV 4 IX 9 XL 40 XC 90 CD 400 CM 900 I 1 V 5 X 10 L 50 C 100 D 500 M 1000]
    eval: join "0" copy roman
    foreach [k v] r [replace/all eval k join " + " v]
    do replace/all to-block eval '+ '+
]

roman?: func [s /local roman-chars] [
    roman-char: charset "IVXLCDM"
    parse/case s [some roman-char]
]

```

### Example

```
roman-dialect [
    m: X + V
    print m
    print M + m  ; doesn't confuse the variable m with Roman Numeral M
    if now/year = MMXIV [print "Yes it is 2014"]
    for n I V I [
        print [rejoin [n "+" X "="] n + X]
    ]
]

```

Output:

> 15
>
> 1015
>
> Yes it is 2014
>
> 1+10= 11
>
> 2+10= 12
>
> 3+10= 13
>
> 4+10= 14
>
> 5+10= 15

Disclaimer: I'm sure there are other (and probably better!) ways of doing this in Rebol as well.

PS. My `roman-to-integer` function is a transliteration of *histocrat*'s nice Ruby algorithm for converting Roman Numeral string into a number. Returned with thanks! +1
> 3 votes

# Answer
**Python**

This is possibly the simplest solution using Python:

```
ns = [1000,900,500,400,100,90,50,40,10,9,5,4,1]
ls = 'M CM D CD C XC L XL X IX V IV I'.split()
for N in range(1, 4000):
    r=''
    p=N
    for n,l in zip(ns,ls):
        while p>=n:
            r+=l
            p-=n
    exec('%s=%d'%(r,N))

i, j = XIX, MCXIV
print i, j

```
> 3 votes

# Answer
# APL (Dyalog APL), 77 bytes

Prompts for Roman numeral maximum length and defines all variables.

```
t←'IVXLCDM',⊂⍬
{⍎⍕⍵'←',+/2(⊣×¯1*<)/0,⍨(∊1 5∘×¨10*⍳4)[t⍳⍵]}¨,/t[⍉8⊥⍣¯1⍳¯1+8*⎕]

```

`t←`*t* gets

`'IVXLCDM',` Roman chars followed by

an enclosed

empty list

`t[``]` index *t* with…

the transposed (to get the right order)

`8⊥⍣¯1` appropriate width base-eight representation of

the first *n* indices, where *n* is

`¯1+` one less than

`8*⎕` eight to the power of numeric input

`,/` flatten rows (each representation)

`{` apply the following anonymous function on each representation…

`(``)[t⍳⍵]` corresponding to the positions of the argument's items in *t*, select from…

the enlisted

`1 5∘×¨` one and five times each of

`10*` ten to the power of

`⍳4` zero through three

`0,⍨` append zero

`2(…)/` on each length-two sliding window, apply the following anonymous function train…

`⊣×` the left argument times

`¯1*` negative one to the power of

`<` whether the left argument is less than the right argument

`+/` sum

`⍵'←',` prepend the argument (the Roman numeral) and an assignment arrow

format (to flatten and convert the number to text)

execute that (makes the assignment outside the anonymous function)

Try it online! (using max-length 5)
> 3 votes

# Answer
# PHP

There a several rules for valid roman numbers

1. Write the greatest value befor the lower values
2. Subtract only `[I,X,C]` before the next 2 greater values
3. Subtract double `[I,X,C]` before the next 2 greater values
4. Subtract double `[I,X,C]` before the greater values
5. Combine 4+5

Online Version

## Step 1 Create the rules

```
{"M":1000,"IM":999,"IIM":998,"XM":990,"XXM":980,"CM":900,"CCM":800,"D":500,"ID":499,"IID":498,"XD":490,"XXD":480,"CD":400,"C":100,"IC":99,"IIC":98,"XC":90,"XXC":80,"L":50,"IL":49,"IIL":48,"XL":40,"X":10,"IX":9,"IIX":8,"V":5,"IV":4,"I":1}

```

is the JSON output for all valid roman numbers

```
$rule_sub_all=$rule_add=$rule_sub_simple=["M"=>1000,"D"=>500,"C"=>100,"L"=>50,"X"=>10,"V"=>5,"I"=>1];
foreach(["I","X","C"]as$roman_letter){
    $rule_sub_simple[$roman_letter.array_search($value=$rule_add[$roman_letter]*5,$rule_add)]=$value-$rule_add[$roman_letter];
    $rule_sub_simple[$roman_letter.array_search($value=$rule_add[$roman_letter]*10,$rule_add)]=$value-$rule_add[$roman_letter];
}
$rule_sub_lower_one=$rule_sub_double=$rule_sub_simple;
foreach(["I","X","C"]as$roman_letter){
    $rule_sub_double[$roman_letter.$roman_letter.array_search($value=$rule_add[$roman_letter]*10,$rule_add)]=$value-2*$rule_add[$roman_letter];

foreach($rule_add as$key=>$value){
    if($value>$rule_add[$roman_letter])$rule_sub_all[$roman_letter.$key]=$value-$rule_add[$roman_letter];
    if($value>5*$rule_add[$roman_letter])$rule_sub_all[$roman_letter.$roman_letter.$key]=$value-2*$rule_add[$roman_letter];
    if($value>10*$rule_add[$roman_letter])$rule_sub_lower_one[$roman_letter.$key]=$value-$rule_add[$roman_letter];
    }
}
arsort($rule_sub_all);
arsort($rule_sub_lower_one);
arsort($rule_sub_double);
arsort($rule_sub_simple);

```

## Step 2 Make lists for all rules till 3999

```
$array_sub_lower_one=$array_sub_double=$array_sub_all=$array_add=$array_sub_simple=[];
for($i=1;$i<4000;$i++){
    $number_sub_all=$number_add=$number_sub_simple=$number_sub_double=$number_sub_lower_one=$i;
    $roman_letter_sub_all=$roman_letter_add=$roman_letter_sub_simple=$roman_letter_sub_double=$roman_letter_sub_lower_one="";
    foreach($rule_sub_all as$key=>$value){
        $roman_letter_sub_all.=str_repeat($key,$d=$number_sub_all/$value^0);$number_sub_all-=$value*$d;
        if(in_array($value,$rule_sub_lower_one)){
        $roman_letter_sub_lower_one.=str_repeat($key,$d=$number_sub_lower_one/$value^0);$number_sub_lower_one-=$value*$d;}
        if(in_array($value,$rule_add)){
        $roman_letter_add.=str_repeat($key,$d=$number_add/$value^0);$number_add-=$value*$d;}
        if(in_array($value,$rule_sub_simple)){
        $roman_letter_sub_simple.=str_repeat($key,$d=$number_sub_simple/$value^0);$number_sub_simple-=$value*$d;}
        if(in_array($value,$rule_sub_double)){
        $roman_letter_sub_double.=str_repeat($key,$d=$number_sub_double/$value^0);$number_sub_double-=$value*$d;}
     }
    $array_sub_lower_one[$roman_letter_sub_lower_one]=$i;
    $array_sub_all[$roman_letter_sub_all]=$i;
    $array_add[$roman_letter_add]=$i;
    $array_sub_simple[$roman_letter_sub_simple]=$i;
    $array_sub_double[$roman_letter_sub_double]=$i;
}

```

## Step 3 Create constants

Combine all lists and define constants

```
foreach(array_merge($array_add,$array_sub_simple,$array_sub_lower_one,$array_sub_double,$array_sub_all)as$key=>$value){ define($key,$value); }

```

## Output

In the example mutiply two valid versions of the number 8

```
echo IIX *  VIII;

```
> 2 votes

# Answer
# Lua

```
local g={}
setmetatable(_G,g)
local romans = {I = 1,
                V = 5,
                X = 10,
                L = 50,
                C = 100,
                D = 500,
                M = 1000}
local larger = {    -- Precalced, for faster computing.
                I = "VXLCDM",
                V = "XLCDM",
                X = "LCDM",
                L = "CDM",
                C = "DM",
                D = "M",
                M = " " -- A space will never be found, and it prevents the pattern matcher from erroring.
}
local storedRomans = {}
function g:__index(key)
    if storedRomans[key] then
        return storedRomans[key]
    end
    if key:match"^[IVXLCDM]+$" then
        local n = 0
        local i = 1
        for s in key:gmatch"." do
            local N = romans[s]
            if key:find('['..larger[s]..']',i) then
                n = n - N
            else
                n = n + N
            end
            i = i + 1
        end
        storedRomans[key] = n
        return n
    end
end

```

This effects the metatable of the global table, giving it a new index function. When a global variable which only contains roman numerals is asked for, eg `XVII`, it parses it.

Easy to test;

```
print(XVII) -- 42
print(VI)   -- 6
print(III)  -- 3
print(MMM)  -- 3000

```

Try it online!
> 1 votes

# Answer
# Excel VBA, <sub>~~204~~</sub> 183 bytes

A subroutine which takes no input, and when run, creates `Enum R`, which contains all of the Roman Numeral values. These values may be used directly, without referencing the Enum.

Requires programmatic access to the VBE Project module.

Enum hold values from 1 to 3999.

<sub>*Note:* Terminal `"`s on lines 7, 8, and 13 are included for syntax highlighting only, and do not contribute to the bytecount</sub>

```
Global c
Sub a(s)
c.AddFromString s
End Sub
Sub b
Set c=ThisWorkbook.VBProject.VBComponents.Add(1).CodeModule
a"Enum R"
a"I=1"
For n=2To 3999
[A1]=n
a[Roman(A1)]
Next
a"End Enum"
End Sub

```

## Ungolfed and Explained

```
Global C As CodeModule                                              '' dim object to hold module to be added

Private Sub pWriteLine(ByRef s As String)                           '' define a helper sub that writes a single
    C.AddFromString s                                               ''   line containing string `s` to global
End Sub                                                             ''   codemodule `c`

Public Sub InitializeRomanNumerals()
    Set C = ThisWorkbook.VBProject.VBComponents.Add(1).CodeModule   '' Create Module
    Call pWriteLine("Public Enum RomanNumeral")                     '' Write Enum Header
    Call pWriteLine("I = 1")                                        '' Write First line, and set value to 1
    For n = 2 To 3999                                               '' iter from 2 to 3999
        [A1] = n                                                    '' push value to A1
        Call pWriteLine([Roman(A1)])                                '' write a line containing roman numeral value of A1,
                                                                    ''  enum value will auto increment to be 1 over
                                                                    ''  that of the line above
    Next n                                                          ''
    Call pWriteLine("End Enum")                                     '' Write Enum Footer
End Sub

```
> 1 votes

# Answer
# JavaScript, 167 bytes

```
f=n=>n<4e3?"M1000CM900D500CD400C100XC90L50XL40X10IX9V5IV4I1".replace(/(\D+)(\d+)/g,(_,r,d)=>r.repeat(n/d,n%=d)):`(${f(n/1e3)})`+f(n%1e3)
for(i=0;i<4e3;i++)this[f(i)]=i

```

The Decimal to Roman function comes from this answer (thanks Neil !)

Then it will add all of them to the root object (`this`). Very optimized, and definitively a good practice I know !

Just paste it to the browser's console to try it out !
> 1 votes

---
Tags: popularity-contest, roman-numerals, parsing, syntax
---


title: Multiplying numbers

text:
# Question
Title: Multiplying numbers
Your task, is simply to multiply 2 integers given in input, separated by a ",". The catch is, you cannot use the multiplication operator "\*", even if it is being used differently, or any loops whatsoever

This is code-golf, so shortest code wins!

Test cases: *i dont know if you even need it! lol*

1,0 -\> 0

5,6 -\> 30

3920,549 -\> 2152080

# Answer
# 05AB1E, 6 bytes

```
',¡`иO

```

Try it online or verify all test cases.

Would be 2 bytes without the restricted input-format:

```
иO

```

Try it online or verify all test cases.

**Explanation:**

```
',¡    '# Split the (implicit) input-string on ","
   `    # Pop and push both values separated to the stack
    и   # Repeat the first value the second value amount of times as list
     O  # Sum that list
        # (after which the result is output implicitly)

```
> 0 votes

# Answer
# Python 3, 32 bytes

```
lambda x,y:eval("x"+chr(42)+"y")

```

Try it online!
> 0 votes

---
Tags: code-golf, code-challenge
---


title: Create a rotating quine

text:
# Question
Title: Create a rotating quine
A rotation of a string is made by splitting a string into two pieces and reversing their order, for example `"world!Hello, "` is a rotation of `"Hello, world!"`. It is possible to create programs that can be rotated to form a different, but still valid program. Consider this example in python:

```
print ")import sys; sys.stdout.write("

```

It can be rotated to form

```
import sys; sys.stdout.write("print ")

```

Which is itself a valid python program.

Your challenge is to write a program that outputs a rotation of itself, which when run will output the original program. Bonus points to any entry with a cycle length greater than two!

This is code golf, the exact scoring will be: (length of code)/(cycle length - 1).

EDIT: We have a winner (unless someone else is able to beat a score of 4)! I'd still be very interested to see any other solutions, whether they're contenders or not.

# Answer
> 22 votes
# APL (158 characters, score = 4)

```
'''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0

```

I'm using Dyalog APL here. The number of cycles can be increased by one by adding  (0 followed by a space) to the end of the expression and to the end of the string (before `'''`). The cycle length is `(# 0's) + 1`, and the length of the expression is `150 + 4*(cycle length))`. Assuming we continue adding zeros forever, the score is `Limit[(150 + 4*n)/(n - 1), n -> Infinity] = 4`, where `n` is the cycle length.

Here's an example with cycle length=6:

```
      '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0
 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0

      0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0
 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0

      0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0
 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0

      0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0
 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0

      0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0
 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1

      0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1
'''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 0 0 0 0

```

### 192 characters, score = 2

```
'''{2≠⍴⍺:¯3⌽(2×1+⍴⍺)⍴(1+⍴⍺)⍴⍺ ⋄ a←⊃2⌷⍺ ⋄ ⍵=0:¯2⌽(2×1+⍴a)⍴(1+⍴a)⍴a⋄(-4+⌊10⍟⊃⍺)⌽(2×1+⍴a)⍴(1+⍴a)⍴a}01'''{2≠⍴⍺:¯3⌽(2×1+⍴⍺)⍴(1+⍴⍺)⍴⍺⋄a←⊃2⌷⍺⋄⍵=0:¯2⌽(2×1+⍴a)⍴(1+⍴a)⍴a⋄(-4+⌊10⍟⊃⍺)⌽(2×1+⍴a)⍴(1+⍴a)⍴a}01

```

Depending on the implementation, one point of failure could be when the integer prefixed to the string is too large. Theoretically, though, we can add a cycle by adding two characters - a `1` at the end of the string (before `'''`) and a `1` at the end of the entire line.

### 200 characters, score = 1

```
'''{a←{2=⍴⍵:⊃2⌷⍵⋄⍵}⍺⋄(⍺{⍵=9:⍬⋄⍕1+{2=⍴⍵:10×⊃⍵⋄0}⍺}⍵),(¯2⌽(2×1+⍴a)⍴(1+⍴a)⍴a),⍺{⍵=9:(⍕9),⍕⊃⍺⋄⍕⌊⍵÷10}⍵}'''{a←{2=⍴⍵:⊃2⌷⍵⋄⍵}⍺⋄(⍺{⍵=9:⍬⋄⍕1+{2=⍴⍵:10×⊃⍵⋄0}⍺}⍵),(¯2⌽(2×1+⍴a)⍴(1+⍴a)⍴a),⍺{⍵=9:(⍕9),⍕⊃⍺⋄⍕⌊⍵÷10}⍵}91

```

My APL implementation doesn't have unlimited precision integers by default, so the integer is converted to a float when it becomes too large, causing the output to be wrong. So this one is the most finicky, but theoretically (either by hand or with a different APL interpreter), it should have a score of 1. Just add a `1` to the end of the expression, and you get another cycle.

## Overview (with a shorter quine)

I'm going to give an overview of the first version, because I think it's probably the easiest to comprehend. Before tackling that version, however, we're going to consider a simple quine in APL:

```
1⌽22⍴11⍴'''1⌽22⍴11⍴'''

```

I've found that one of the best ways to understand some APL expressions is to look at the output throughout the cascade of operators/functions. All operators and functions in APL are right-associative and have the same precedence, so here is is, from right to left:

* `'''1⌽22⍴11⍴'''`: This is just a string literal (a list of characters). `''` is the APL way of escaping single quote marks. Output: `'1⌽22⍴11⍴'`.
* `11⍴'''1⌽22⍴11⍴'''`: Here, we reshape () the string to be of length `11`. Because the string's length is under 11, it is repeated (i.e., `5⍴'abc'` would yield `'abcab'`). Output: `'1⌽22⍴11⍴''`. So we now have two quotation marks at the end - we're getting somewhere!
* `22⍴11⍴'''1⌽22⍴11⍴'''`: Similarly, we now reshape our previous output to be of length `22`. Output: `'1⌽22⍴11⍴'''1⌽22⍴11⍴''`. We're almost there - we just need to move the first single quote to the end.
* `1⌽22⍴11⍴'''1⌽22⍴11⍴'''`: Here, we rotate () the list of characters by `1`. This moves the first character of the string to the end. As another example, `2⌽'abcdef'` returns `'cdefab'`. Output: `1⌽22⍴11⍴'''1⌽22⍴11⍴'''`.

## The rotating quine

That short quine is the main basis for our rotating quine. Now, with that in mind, let's take a look at our quine:

```
'''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0

```

`{ ... }` defines an unnamed function, which is where we'll be doing the work. Note that functions in APL take a right argument, denoted by , and an optional left argument, denoted by  (think infix). We want to feed this function both our quine string and something to aid us in creating an arbitrary number of cycles. To make things easier on ourselves (and anyone wanting to add cycles), we make the quine string the left argument. The right argument, then, is where we put our list of cycles. 2 or more items separated by a space creates a list, so in this example, we have 2-element list consisting of a `1` and a `0`.

We can see that the function looks similar to the quine from before. We have the same `...⌽...⍴...⍴...` form from before. So that's good - we at least understand that much! Let's delve deeper into the ellipses, starting with everything after the last : `⊃,/(~^/¨⍺=0)/⍺`.

* As you can see by looking at the example above, we prefix the string with the 0's from the right-hand side, adding one with each iteration; but we don't care about those right now. We just want the string!
* First, consider what's in the parentheses. (They group like in most other languages, by the way.)
    + `⍺=0` returns a list, in this case, with the same shape as , where each element in  is replaced by a `1` if it is equal to `0`, and a `0` otherwise. This is performed recursively; so if we have a list of a list of a list of characters, the individual characters will be tested against 0, and you will get back a list of a list of a list of binary values.
    + So if  consists of just our string, we get back a list of 0's. Otherwise, our left argument has some 0's prefixed to it (e.g., `0 0 0 'quinestring'`), so it is a list consisting of 0's and another list, our string. Then our output looks like `1 1 1 <sub-list of zeros>`.
    + `^/¨⍺=0`: We apply the derived function `^/`, which reduces (`/`) using the logical AND (`^`) function, to each (`¨`) element of `⍺=0`. This is to flatten the sub-list of zeros so that we can consider the quine string to be one binary value. Considering the previous example, the output would be `1 1 1 0`.
    + `~`: We binary NOT each of the values from before (e.g., returning `0 0 0 1`).
* `(~^/¨⍺=0)/⍺`: For each element in , we replicate (`/`) it the number of times given by the corresponding element in the left argument. This eliminates all of the 0's, leaving us only with our quine string.
* `⊃,/` is some necessary paperwork to ensure that we get back a flattened list of characters, by reducing the result with the concatenation function (`,`). If the input is already a flattened list (i.e., the left argument to our main function is only the string), we get a 1-element list containing that list. In the other case, when we have a list consisting of a sub-list for the string, we get the same thing back (a list with a sub-list). We then unpack this (), giving us only the first element of the list (i.e., the sub-list of characters). This might seem unnecessary, but otherwise we would then be trying to reshape a 1-element list!

Next, we look at the length given for the first reshape, within the parentheses:

* `⍺,⍵`: We concatenate the right argument to the first argument
* `⊃,/⍺,⍵`: Same as before - flatten the list.
* `+/0=⊃,/⍺,⍵`: Add up the number of zeros in the list by reducing (`/`) using the addition (`+`) function.
* `2×+/0=⊃,/⍺,⍵`: Multiply that number by two.
* `z←2×+/0=⊃,/⍺,⍵`: Assign () the result to a variable, `z`. To recap, `z` is now twice the number of zeros found in both the left and right arguments.
* `77+z←2×+/0=⊃,/⍺,⍵`: We then add `77`, for the characters in the quine string, ignoring everything after the space following `1`. Like in the initial quine example, we add 1 to the length of the string to get another single quote.
* The output of this reshape, in this example, is: `'{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 ''`

The argument to the reshape that follows is simple and mirrors the short quine (2 times the length for the first reshape). Our output now is:

```
'{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 '''{(((3+z)×^/⍵)-5+2×+/+/¨⍺=0)⌽(2×77+z)⍴(77+z←2×+/0=⊃,/⍺,⍵)⍴⊃,/(~^/¨⍺=0)/⍺}1 0 ''

```

Now for the final step, where we calculate how much to rotate the output string:

* As you can see by looking at the previous output, we want to rotate it back (a negative amount) to bring the 2 final quotes to the beginning. Because we want a `0` (and another space) to move to the beginning as well, we want to rotate it an additional 3 characters back.
* `+/+/¨⍺=0`: Add up the number of zeros in the *left* argument. The first (from the right) `+/¨` sums each element's count (i.e., a sublist or just an integer), and the second `+/` gives us the sum of that resulting list.
* `5+2×+/+/¨⍺=0`: Multiply by two (to rotate the spaces as well), and add 5 (the result we came up with before).
* Now, we subtract the previous value from the left argument to `-` to handle the case when we hit the end of our cycle:
    + `(3+z)×^/⍵`: AND all of the elements in the right argument together to see if we've reached our end (`1`), and multiply that by `3+z`.

And we're done!

# Answer
> 13 votes
## GolfScript, 10046 / 9999 ≈ 1.0047 (asymptotic score 1)

OK, I'm going to try and beat D C's APL entry with this:

```
{\''+.,{(;\'.~1'}{'1'9999*@'.~']puts:puts}if}.~

```

The code above is *not* the actual quine — I felt that posting a 10kB one-liner would not be a very good idea. Rather, running the code above once produces the actual 10046-char GolfScript program, which, when iterated as specified in the question, generates 9999 rotations of itself and, finally, itself again.

The length of the cycle (and the program) can be adjusted by changing the constant `9999`. For brevity and convenience, I'll show what the iterated output looks like if the constant is reduced to `9`:

```
111111111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~
11111111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~1
1111111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~11
111111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~111
11111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~1111
1111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~11111
111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~111111
11{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~1111111
1{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~11111111
{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~111111111
111111111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~
11111111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~1
1111111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~11
111111{\''+.,{(;\'.~1'}{'1'9*@'.~']puts:puts}if}.~111
etc.

```

As the constant `9999` is increased, the ratio of the program length and cycle length (minus one) tends to one. I'm pretty sure that *this* solution can't be beaten, at least not asymptotically. ;-)

### How does it work?

GolfScript is a pretty easy language to write quines in, since basically any number literal acts as a quine: for example, the GolfScript program `12345` outputs — you guessed it — `12345`. Also, concatenating multiple quines typically produces a quine. Thus, I could use a simple number like `11111...111` as the repetitive part of my cyclic quine.

However, to get the quine to actually cycle, we need to carry and execute a non-trivial "payload". The simplest GolfScript quine I could think of that can do that is the following:

```
{PAYLOAD'.~'}.~

```

So my plan was to prefix a quine like that with a repetitive numeric constant, and use a payload that chops one digit off the number and moves it to the end of the program. If the program detects that there *is* no numeric constant in front of it (in which case the value below it on the stack will be an empty string, assuming there no input), it will instead prepend a fixed-length numeric constant in front of itself.

There's one additional wrinkle, though — when "wrapping around", the payload must also suppress the output of the number *after* itself. Normally, when a GolfScript program ends, all values on the stack are automatically printed, which would be a problem here.

However, there turns out to be an (AFAIK) undocumented way to avoid that: the interpreter actually calls the predefined function `puts` to do the printing, so redefining that function as a no-op suppresses the automatic output. Of course, this also means that we must first call `puts` ourselves to print the part of the stack we *want* printed.

The final code looks pretty messy (even for GolfScript), but at least it works. I suspect there may be some clever ways I haven't yet thought of to shave a few chars off the payload, but for this version I was mainly just focusing on the asymptotic score.

# Answer
> 10 votes
# Alice, 94 bytes, score --\> 1

```
<pp&a0Ra*880R9Z640R8Z5e0R7*a70R6Z060R5Z9e0R4Z4R20R3*79Y3Zea0eZ1R51!Z73

```

Unfortunately, I had to fix a bug in the interpreter to make this work, so this doesn't work on TIO.

## Explanation

This is a straightforward extension of my solution to Rotation-safe quine. Since that solution is a proper, payload-capable quine for *every* rotation of the source code, we can simply shift the source by one character before printing to cycle through all possible rotations. So this solution has byte count = cycle length.

The code we're writing into the grid to do so is

```
@o&~,.^'h%?t"

```

The only difference to the other quine is that we pull up the 94th character to the top of the stack, before printing everything.

We can arbitrarily increase the byte count and cycle length by adding no-ops anywhere in the program, which lets the score tend arbitrarily close to 1.

# Answer
> 0 votes
# Python 3.8 (pre-release), 127 bytes, asymptotic score = 1

```
000000000
for i in 1,0:exec(s:="i or print(end=-~-len(str(n))%10*'0'+f'\\nfor i in 1,0:exec(s:=%r);n={n//10 or 10**9}'%s)");n=1

```

Try it online!

## How it works :

We run the for loop twice.

* The first time we initialize the variable `n` to a power of 10 and
* The second time we print our quine dividing `n` by 10 and prepending a `0` in front of the code.

When `n` is equals to `1`, we set `n` to the initial power of 10 an we remove the prepending `0`

By adjusting the number of `0` in the original program, modifying `len(str(n))%10` by `len(str(n))%< x >` and `n//10 or 10**9` by `n//10 or 10**< x-1 >`, with x -\> infinity, the asymptotic score is 1

---
Tags: code-challenge, quine, source-layout
---


title: Flatten the Array!

text:
# Question
Title: Flatten the Array!
In this challenge, your task is to create a program which takes in a nested array and returns a single-dimensional flattened array. For Example `[10,20,[30,[40]],50]` should output `[10,20,30,40,50]`.

---

**Input**

The input will be a nested array (eg. `[10,20,[[[10]]]]`). It will contain only Integers (both negative and positive), Strings and Arrays. You can take the input as function argument, STDIN or whatever suits your language. You can assume that the input array won't have an empty array.

---

**Output**

The output will be a flatted single-dimensional array with the same elements of same type as in the nested array and in the SAME order.

---

**Test Cases**

```
[10,20,30] -> [10,20,30]
[[10]] -> [10]
[["Hi"],[[10]]] -> ["Hi",10]
[[[20],["Hi"],"Hi",20]] -> [20,"Hi","Hi",20]
[[["[]"],"[]"]] -> ["[]","[]"]

```

---

Feel free to ask for any clarification by using comments. This is , so the shortest code in bytes wins!

**Note:** *If your language contains a built-in for this, then you must NOT use it.*

---

**Edit**

Please also include a link to a website where your code can be executed.

# Answer
> 42 votes
# K, 3 bytes

```
,//

```

This is a fairly common idiom. "Join over converge".

try it here with oK.

How it works:

Join (`,`) fuses together atoms or lists to produce a list. Over (`/`) takes a verb (in this case join) and applies it between each element of a list, left to right. Thus, the compound `,/` will flatten all the top level elements of the list. The symbol `/` actually has different meanings depending on the valence (number of arguments) of the verb with which it is compounded. When we provide `,/` as the verb, the final `/` acts as "converge"- it repeatedly applies `,/` to the input until it stops changing. Some other languages call a feature like this a "fixed point combinator". By repeatedly fusing bottom level lists, you will eventually arrive at a single flat list, and none of the operations will perturb the order of elements. This seems to solve the problem.

# Answer
> 39 votes
# JavaScript (ES6), 35 bytes

Inspired by @user81655's answer:

```
f=a=>a.map?[].concat(...a.map(f)):a

```

# Answer
> 19 votes
## Mathematica, ~~16~~ 14 bytes

```
{##&@@#&//@#}&

```

An unnamed function which takes and returns a list, e.g.:

```
{##&@@#&//@#}& @ {{{20}, {"Hi"}, "Hi", 20}}
(* {20, "Hi", "Hi", 20} *)

```

### Explanation

Syntactic sugar party!

To understand how this works, note that every expression in Mathematica is either an atom (e.g. numbers, strings, symbols) or a compound expression of the form `f[a, b, c, ...]`, where `f`, `a`, `b`, `c` are themselves arbitrary expressions. Here, `f` is called the *head* of the expression. Everything else on top of that is just syntactic sugar. E.g. `{a, b, c}` is just `List[a, b, c]`.

We start with `//@` which maps a functions over *all* levels of a list. For instance:

```
f //@ {{{20}, {"Hi"}, "Hi", 20}}
(* f[{f[{f[{f[20]}], f[{f["Hi"]}], f["Hi"], f[20]}]}] *)

```

Note that this maps `f` over atoms as well as compound expressions. What we're now looking for is a way to get rid of the list heads and keep everything else.

The `Apply` function is normally used to feed the elements of a list as separate arguments to a function, but its actual definition is more general and simply replaces the head of an expression. E.g. `Apply[g, f[a, b]]` gives `g[a, b]`.

Now there's a special "head" called `Sequence` that simply vanishes. E.g. `{a, Sequence[b, c], d}` just evaluates to `{a, b, c, d}`. The idea for flattening the list is to replace the heads of all inner lists with `Sequence` so that they get splatted into their surrounding list. So what we want is to `Apply` the head `Sequence` to the lists. Conveniently if we `Apply` something to an atom, it just leaves the atom unchanged, so we don't have to distinguish between types of expressions at all.

Finally, there's one small issue: `f` is also applied to the outermost level, so that it also removes the outermost `List`, which we don't want. The shortest way to counter that is simply to wrap the result in a list again, such that the surrounding `Sequence` can safely vanish.

Note that there's neither `Apply` nor `Sequence` in the code. `@@` is an operator form of `Apply` and `##&` is a standard golfing trick to shorten the long built-in name `Sequence`. So ungolfing everything a bit, we get something like:

```
flatten[list_] := { MapAll[Apply[Sequence], list] }

```

For more details on how and why the `##&` works, see the section on "Sequences of arguments" in my answer for the Mathematica tips.

# Answer
> 13 votes
## Python 2, 43 bytes

```
f=lambda l:[l]*(l*0!=[])or sum(map(f,l),[])

```

On a list, recurses on the elements and concatenates the results. On a string or number, encases in a singleton list.

Unfortunately, Python 2's ordering for types `int < list < string` sandwiches `list` between the others, requiring two inequalities to check. So, instead, `l*0` is checked against the empty list `[]`, otherwise giving `0` or `""`.

# Answer
> 10 votes
# Ruby, ~~43~~ ~~42~~ 34 bytes

Recursive solution. Now with exception handling! (might as well credit @akostadinov for inspiring the change though)

```
f=->a{a.map(&f).inject:+rescue[a]}

```

IDEOne link

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

```
f=a=>[].concat(...a.map(v=>v.pop?f(v):v))
```

```
<textarea id="input" rows="6" cols="40">[[[20],["Hi"],"Hi",20]]</textarea><br /><button onclick="result.textContent=JSON.stringify(f(eval(input.value)))">Go</button><pre id="result"></pre>
```

# Answer
> 8 votes
# Perl 6, 24 bytes

```
{gather {$_».&{.take}}}

```

### Explanation:

```
{ # has $_ as an implicit parameter

  gather {

    $_\ # the parameter from the outer block
    »\  # for each single value in the structure
    .&( # call the following block as if it was a method
      { # this block has its own $_ for a parameter
        .take # call the .take method implicitly on $_
      }
    )
  }
}

```

### Test:

```
#! /usr/bin/env perl6

use v6.c;
use Test;

my &flatten = {gather {$_».&{.take}}}

my @tests = (
  [10,20,30], [10,20,30],
  [[10,],], [10,],
  [["Hi",],[[10,],],], ["Hi",10],
  [[["[]",],"[]"],], ["[]","[]"],
);

plan @tests / 2;

for @tests -> $input, $expected {
  # is-deeply cares about the exact type of its inputs
  # so we have to coerce the Seq into an Array
  is-deeply flatten($input).Array, $expected, $input.perl;
}

```

```
1..4
ok 1 - $[10, 20, 30]
ok 2 - $[[10],]
ok 3 - $[["Hi"], [[10],]]
ok 4 - $[[["[]"], "[]"],]

```

# Answer
> 7 votes
## Haskell, 43 bytes

```
data D a=L a|N[D a]
f(L x)=[x]
f(N l)=f=<<l

```

Haskell has neither nested lists with different depths of the sublists nor mixed types for the list elements. For nesting I define a custom data type `D` which is either a leaf `L` that holds some element or a node `N` which is a list of `D`s. For the mixed elements I use the predefined data type `Either` which combines two types into one, here `Either String Integer`. The new type `D` and the flatten function `f` are fully polymorphic in the type of the leaf elements, so I don't have to take extra care of anything regarding `Either`.

Usage example: `f (N[N[L(Right 20)], N[L(Left "Hi")], L(Left "Hi") , L(Right 20)])` -\> `[Right 20,Left "Hi",Left "Hi",Right 20]`.

# Answer
> 6 votes
## JavaScript (Firefox 30-57), 43 bytes

```
f=a=>a.map?[for(b of a)for(c of f(b))c]:[a]

```

Just because I could even avoid using `concat`.

# Answer
> 6 votes
# Pyth, ~~7~~ ~~6~~ 5 bytes

```
us+]Y

```

Try it online: Demonstration or Test Suite

But of course, there is also a build-in function, that handles the task in just 2 bytes: `.n` (Test Suite)

# Answer
> 5 votes
# Perl, ~~34~~ 29 bytes

Functions.

If needs to flatten to list like `my @a = f(@a)`, 29 bytes:

```
sub f{map{ref()?f(@$_):$_}@_}

```

Test it on Ideone

If needs to flatten to array ref like `my $a = f($a)`, 34 bytes:

```
sub f{[map{ref()?@{f(@$_)}:$_}@_]}

```

Test it on Ideone.

# Perl 5.22.0+, 27 bytes

Thanks to hobbs.

If needs to flatten to list like `my @a = f(@a)`, 27 bytes:

```
sub f{map{ref?f(@$_):$_}@_}

```

Test it on JDoodle

If needs to flatten to array ref like `my $a = f($a)`, 32 bytes:

```
sub f{[map{ref?@{f(@$_)}:$_}@_]}

```

Test it on JDoodle.

# Answer
> 5 votes
## Julia, 29 bytes

```
f(x,y=vcat(x...))=x==y?x:f(y)

```

This is recursive splatting into a concatenate function until a reaching a fix point. Example

```
julia> f([1,[2,[3,[4,[5,[6]]]]]])
6-element Array{Int64,1}:
 1
 2
 3
 4
 5
 6

```

# Answer
> 4 votes
# Attache, 14 bytes

```
{Reap[Sow@>_]}

```

Try it online!

Fortunately, Attache has a "vectorization" operator, which applies a function at the atoms of a list. In this case, all we need to do is to set up a reaper with `Reap` and `Sow` all atoms of the input `_` with `@>`. I think it's quite elegant.

## Alternatives

**15 bytes:** `Fixpoint{`'^^_}`

**16 bytes:** `Fixpoint!&Concat`

**17 bytes:** `{q:=[]q&Push@>_q}`

**17 bytes:** `Fixpoint[&Concat]`

# Answer
> 3 votes
## Retina, 30 bytes

```
1>`("(\\.|[^"])+")|[][]
$1
$
]

```

Try it online! (The first line is only used to run multiple test cases at once.)

Retina has no concept of arrays, string literals or numbers, so I decided to go with a "common" input format of `[...,...]` style arrays and `"`-delimited strings, where `\` can be used inside the strings to escape any character (in particular `"` and `\` itself).

The program itself simply matches either a full string or a square bracket, and replaces them with `$1` which keeps strings and removes square brackets. The limit `1>` skips the first match so that we don't remove the leading `[`. However, this does remove the trailing `]`, so we add it back in in a separate stage.

# Answer
> 3 votes
## Pyke, 11 bytes

```
.F~]+=])K~]

```

Try it here!

Explanation:

```
.F~]+=])    - Deep for loop
  ~]        -    contents of `]` ([] by default)
    +       -  ^+i
     =]     - `]` = ^
        K~] - Output value
        K   - Remove the output from the for loop
         ~] - Return the contents of `]`

```

### Or 7 bytes after a bugfix

```
M?+]K~]

```

Try it here!

Explanation:

```
M?+]    - Deep map
 ?+]    -  `]` = `]`+i
    K~] - Output value
    K   - Remove the output from the for loop
     ~] - Return the contents of `]`

```

### Or even 2 bytes if printing to stdout is allowed (This might come under built-ins)

```
M
<newline required>

```

Try it here!

This deeply applies the `print_newline` function to every non-sequence item in the input and recurses for sequence items.

# Answer
> 3 votes
# Java (v8) 390 276 bytes

```
public static Object[] f(final Object[]a) {
    List<Object>r=new ArrayList<>();boolean t=false;int n=0;
    for(final Object p:a)
        if(t=p instanceof Object[]){for(final Object q:(Object[])p) r.add(q);}
        else r.add(p);
    return(t)?f(r.toArray()):r.toArray();
}

```

Just for completeness and all that. :) Can't say Java's code-efficient.

# Answer
> 2 votes
## Python, 57 bytes

```
f=lambda a:sum([list==type(x)and f(x)or[x]for x in a],[])

```

Try it online: Python 2, Python 3

Thanks to Kevin Lau for the `list==type(x)` trick.

# Answer
> 2 votes
# Ruby

there is builtin `flatten` method.

You can run here: http://www.tutorialspoint.com/execute\_ruby\_online.php

One 43 bytes, but thought to share:

```
f=->a{a.inject([]){|r,e|r+(f[e]rescue[e])}}

```

One 45 bytes that is more efficient than the previous and the other ruby answer:

```
f=->a{a.map{|e|Array===e ?f[e]:[e]}.inject:+}

```

here's benchmark:

```
require 'benchmark'
n=10^9
arr=[[[20],[[[[[[[[123]]]]]]]],"ads",[[[[[[[4]]]]]]],5,[[[[[[[[[[6]]]]]]]]]],7,8,[[[[[[[[[[9]]]]]]]]]],[[[[[[[[[[0]]]]]]]]]],[[[[[[[[[[[["Hi"]]]]]]]]]]]],[[[[[["Hi"]]]]]],[[[[[20]]]]]]]
Benchmark.bm do |x|
  x.report { f=->a{a.map(&f).inject:+rescue[a]}; f[arr] }
  x.report { f=->a{a.map{|e|e!=[*e]?[e]:f[e]}.inject:+}; f[arr] }
  x.report { f=->a{a.inject([]){|r,e|r+(f[e]rescue[e])}}; f[arr] }
  x.report { f=->a{a.map{|e|Array===e ?f[e]:[e]}.inject:+}; f[arr] }
end

```

result:

```
       user     system      total        real
   0.010000   0.000000   0.010000 (  0.000432)
   0.000000   0.000000   0.000000 (  0.000303)
   0.000000   0.000000   0.000000 (  0.000486)
   0.000000   0.000000   0.000000 (  0.000228)

```

# Answer
> 2 votes
# Perl, ~~39~~ 34 + 1 (`-p` flag) 35 bytes

Oneliner. Inspired by Martin Büttner.

```
#!perl -p
s/("(\\.|[^"])+"|]$|^\[)|[][]/$1/g

```

Test it on Ideone.

# Answer
> 2 votes
## Clojure, 68 bytes

```
(def f #(if(some vector? %)(f(mapcat(fn[z](if(vector? z)z[z]))%))%))

```

`mapcat` first applies function to each element and then concats results. So every time it concats one 'nesting level' is lost. Concat does not work on not sequences so elements have to be wrapped into vector if they're not vector.

You can try it here: http://www.tryclj.com

```
(f [[[20],["Hi"],"Hi",20]])
(f [[["[]"],"[]"]])

```

# Answer
> 2 votes
# ANSI C, 193 bytes

```
#define b break;
#define c case
#define p putch(_);
char f;main(_){switch(_){c 1:putch(91);b c 34:f^=1;p b c 91:f&&p b c 93:f&&p b c 10:c 13:putch(93);return;default:p}_=getch();main(_);}

```

:-/, any suggestions? Btw, I did try to find an online source to compile this but the WL is strict for this code to compile. It will work for VS and gcc otherwise.

# Answer
> 2 votes
# JavaScript 20 bytes

```
a=>(a+[]).split(',')

```

The array + array is equal to array.toString

# Answer
> 2 votes
# Haskell \+ free, 7 bytes

In order to represent a ragged list in Haskell we use a free monad of lists. Luckily for us provided with the free monad is `retract`, which does a lot of different things, but when given the particular type here it flattens the free monad of lists down to a single list.

```
retract

```

Try it online!

But we can also make our own solution using other tools, like `foldFree`:

# 11 bytes

```
foldFree id

```

Try it online!

However `foldFree` basically is just a more general version of `retract`, and we can do it without it:

# 21 bytes

```
iter(>>=id).fmap(:[])

```

Try it online!

If we want to use *none* of the functions provided by free just the definition of the monad and prelude functions we can do:

# 29 bytes

```
f(Pure a)=[a]
f(Free a)=a>>=f

```

Try it online!

# Answer
> 1 votes
# Racket, 63 bytes

```
(define(f l)(apply append(map(λ(x)(if(list? x)(f x)`(,x)))l)))

```

# Answer
> 1 votes
# JavaScript, 17 Bytes

```
a=>eval(`[${a}]`)

```

Finally, JavaScript's type conversions can be put to some good use! Please note that this will actually output an array, but string conversion (putting it into HTML) causes it to become a comma separated list.

If comma separated lists are acceptable output, then the following is valid:

# 7 Bytes

```
a=>""+a

```

NOTE: Snippet is broken for some reason

```
var subject =
  a=>eval(`[${a}]`)
```

```
<input oninput="try {output.innerHTML = subject(this.value)} catch(e) {output.innerHTML='Invaild Input'}" />
<div id="output"></div>
```

# Answer
> 1 votes
## Java 8 165 chars

```
import java.util.*;<T>T[]f(T[]a){List<T>l=new ArrayList<>();for(T e:a)if(e instanceof Object[])Collections.addAll(l,f((T[])e));else l.add(e);return(T[])l.toArray();}

```

Ungolfed into a class:

```
public class Q80096 {

    public static <T> T[] flatten(T[] array) {
        List<T> flattenedList = new ArrayList<>();
        for (T element : array)
            if (element instanceof Object[])
                 Collections.addAll(flattenedList, flatten((T[]) element));
            else
                flattenedList.add(element);
        return (T[]) flattenedList.toArray();
    }
}

```

This answer is based on Jeremy Harton's approach. I used it changed it in some places and created a more golf-like version.

# Answer
> 1 votes
# PHP, 73 Bytes

```
<?array_walk_recursive($_GET,function($i)use(&$r){$r[]=$i;});print_r($r);

```

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), 66 bytes

```
T[]f<T>(T[]a)=>a.SelectMany(x=>x is T[]y?f(y):new[]{x}).ToArray();

```

Try it online!

Recursive function that takes an `object[]` as input. Yes, there is a type parameter, so you *could* pass an array of any type... But it only works correctly if all nested arrays are of the same type. That is a requirement that I have added :)

It would be more flexible to get this to work with an input of type `IList` or `Array`.

# Answer
> 1 votes
# Elixir, 74 bytes

```
def d(l)do l|>Stream.flat_map(fn x->if is_list(x)do d(x)else[x]end end)end

```

First Elixir answer, so can probably be golfed a bit.

Try it online.

**Explanation:**

```
def d(l)do l|>            # Recursive method taking a list as input:
  Stream.flat_map(fn x->  #  Map over each item `x` of the input-list:
    if is_list(x)do       #   If `x` is a list itself:
      d(x)                #    Do a recursive call with `x`
    else                  #   Else:
      [x]                 #    Simply leave `x` unchanged
    end                   #   End of the if-else statements
  end)                    #  End of the map
end                       # End of the recursive method

```

Of course, if builtins were allowed, this could have been **25 bytes** instead:

```
fn(l)->List.flatten(l)end

```

Try it online.

# Answer
> 1 votes
# Jelly, 4 bytes

```
;/ÐL

```

Try it online!

## Explanation

```
;/   | Reduce by concatenation
  ÐL | Loop until no further changes

```

Built-in `F` would be one byte if allowed.

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

```
#~Level~{-1}&

```

Try it online!

Un-golfed: `F[x_] := Level[x, {-1}]`

picks out the elements of the structure at the last level of its tree form. I'm not sure this counts as "avoiding the builtin" (which would be `Flatten`).

# Answer
> 1 votes
# Brachylog, 6 bytes

```
ċ↰ᵐc|g

```

Try it online!

```
ċ         The input is a list,
    |     and the output is
   c      the concatenation of
 ↰ᵐ       the results of this predicate on the list's elements.
    |     If the input is not a list, then it
     g    wrapped in a list is the output.

```

# Answer
> 1 votes
# Nial, 27 bytes

```
DOWN[simple,pass,pass,link]

```

Try it online!

strangely interesting in nial since it doesn't have fixpoint.

# Answer
> 0 votes
# Lua, 123 bytes

```
function f(a)o,t={},function(s)for _,v in next,s do if type(v)=="table"then t(v)else o[#o+1]=v end end end t(a)return o end

```

I'm sure this is not the best answer, but I thought I'd post it since nobody has given a Lua solution yet. Suggestions welcome!

Try it online!

# Answer
> 0 votes
# PowerShell, 35 bytes

```
filter f{if($_.Rank){$_|f}else{$_}}

```

Try it online!

Rank \- Returns the number of dimensions in the array. Rank = `0` if an object is not array.

# Answer
> 0 votes
# 05AB1E, 13 bytes

```
ΔvyD1«Āië`}})

```

Try it online or verify all test cases

Not the easiest challenge in 05AB1E, since the merge builtin for lists is also used for strings, so reducing by concatenation like most other golfing languages are using isn't possible. Also, flattening one level down with `€``  will also flatten down strings to a list of characters (and push them in reversed order), otherwise `Δí€``  would have been a 4 byter:
Try it online or see the incorrect output of all test cases.

```
Δ          # Loop until the result no longer changes:
           # (which will use the implicit input-list in the first iteration)
 vy        #  Foreach over the items:
   D       #   Duplicate the current item
    1«     #   Append a "1" to each inner-most string/integer
      Ā    #   Truthify each inner-most string
           #   (we use the appended "1" so every string/integer - even "", "00",
           #   0, 000, etc. - becomes truthy)
       i   #   If this is truthy (will be falsey for lists of truthy values):
           #    (use the duplicated item as is)
       ë   #   Else (it's a list instead):
        `  #    Pop the list, and push all its items to the stack
       }   #   Close the if-statement
 }         #  After the foreach-loop:
  )        #  Wrap all values on the stack into a list
           # (after which the resulting flattened list is output implicitly)

```

With builtins, we could of course have used the single byte flatten builtin `˜`:
Try it online or verify all test cases.

Interesting enough, the incorrect result of the 4-byter could have been 1 byte as well with the flattened characters builtin `S`:
Try it online or see all test cases.

---
Tags: code-golf, array, ragged-list
---


title: Ninjas and Monkeys and Bears, Oh My!

text:
# Question
Title: Ninjas and Monkeys and Bears, Oh My!
*This challenge is NinjaBearMonkey's prize for winning my Block Building Bot Flocks! challenge with the Black Knight submission. Congratulations NinjaBearMonkey!*

The challenge here is fairly simple, but has a variety of possible approaches. The story goes that in the world of Isometric Illusions, there are 6 different types of creatures:

1. Ninjas, abbreviated `N`
2. Bears, abbreviated `B`
3. Monkeys, abbreviated `M`
4. NinjaBears, abbreviated `NB`
5. BearMonkeys, abbreviated `BM`
6. NinjaBearMonkeys, abbreviated `NBM`

<sup>(NinjaBearMonkey is, of course, the last, most powerful type.)</sup>

Your task is to take a census of these creatures when they are lined up side-by-side, i.e. when their abbreviation strings are concatenated. The caveat is that you need to make sure not to over-count the parts of some creatures as separate creatures that happen to look similar. The creatures will line up such that:

* Any instance of `NBM` is 1 NinjaBearMonkey and 0 other creatures.
* Any instance of `NB` not followed by `M` is 1 NinjaBear and 0 other creatures.
* Any instance of `BM` not preceded by `N` is 1 BearMonkey and 0 other creatures.
* Otherwise, instances of `N`, `B`, and `M` are single Ninjas, Bears, and Monkeys respectively.

The line is read from left to right.

So, for example, in the line of creatures `NBMMBNBNBM`, there are 0 Ninjas, 1 Bear, 1 Monkey, 1 NinjaBear, 0 BearMonkeys, and 2 NinjaBearMonkeys.

# Challenge

Write a program or function that takes in a string of the characters `N`, `B`, and `M`, and prints or returns how many of each of the 6 types of creatures are present in it.

The output should have the form

```
#N #B #M #NB #BM #NBM

```

with the respective creature count replacing each `#` sign. All 6 counts must be shown, separated by spaces, even when they are 0. However, they may be in any order (e.g. `#NBM` could come first).

Also:

* The input string will only contain the characters `N`, `B`, and `M`.
* If the empty string is input, then all the counts are 0.
* The output may optionally contain a single leading and/or trailing space, and/or a single trailing newline.

**The shortest submission in bytes wins.**

# Examples

Input: `NB`
Output: `0N 0B 0M 1NB 0BM 0NBM`

Input: `NBM`
Output: `0N 0B 0M 0NB 0BM 1NBM`

Input: `NBMMBNBNBM` (example from above)
Output: `0N 1B 1M 1NB 0BM 2NBM`

Input: `MBNNBBMNBM`
Output: `1N 1B 1M 1NB 1BM 1NBM`

Input: `NNNMNBMMBMMBMMMNBMNNMNNNBNNNBNBBNBNMMNBBNBMMBBMBMBBBNNMBMBMMNNNNNMMBMMBM`
Output: `17N 6B 14M 5NB 8BM 3NBM`

# Answer
# Pyth, 22 bytes

```
 f|pd+/zTT=:zTd_.:"NBM

```

Quite hackish way to save 1 byte, thanks to @Jakube.

---

# Pyth, 23 bytes

```
FN_.:"NBM")pd+/zNN=:zNd

```

Demonstration.

Prints in reverse order, with a trailing space and no trailing newline.

`.:"NBM")` is all the substrings, `_` puts them in the right order, `/zN` counts occurences, and `=:zNd` in-place substitutes each occurence of the string in question with a space.

```
FN_.:"NBM")pd+/zNN=:zNd
FN                         for N in                            :
  _                                 reversed(                 )
   .:     )                                  substrings(     )
     "NBM"                                              "NBM"
           pd              print, with a space at the end,
              /zN          z.count(N)
             +   N                    + N
                  =:zNd    replace N by ' ' in z.

```
> 20 votes

# Answer
# JavaScript ES6, 86 bytes

```
f=s=>'NBM BM NB M B N'.replace(/\S+/g,e=>(i=0,s=s.replace(RegExp(e,'g'),_=>++i))&&i+e)

```

(I just had to answer this.) It goes through each substring of `NBM`, starting with the longer ones, which take higher priority. It searches for each occurrence of that particular string and removes it (in this case replacing it with the current count so it won't be matched again). It finally replaces each substring with the count + the string.

This Stack Snippet is written in the ES5 equivalent of the above code to make it easier to test from any browser. It is also slightly ungolfed code. The UI updates with every keystroke.

```
f=function(s){
  return'NBM BM NB M B N'.replace(/\S+/g,function(e){
    i=0
    s=s.replace(RegExp(e,'g'),function(){
      return++i
    })
    return i+e
  })
}

run=function(){document.getElementById('output').innerHTML=f(document.getElementById('input').value)};document.getElementById('input').onkeyup=run;run()
```

```
<input type="text" id="input" value="NBMMBNBNBM" /><br /><samp id="output"></samp>
```
> 23 votes

# Answer
## Python 2, 78

```
n=input()
for x in"NBM BM NB M B N".split():n=`n`.split(x);print`len(n)-1`+x,

```

A variant of Vioz-'s answer. Fun with Python 2 string representations!

Counts occurrences of the substring indirectly by splitting on it, counting the parts, and subtracting 1. Instead of replacing the substrings by a filler symbol, replaces the string by the list that `split` produced. Then, when we take its string representation, the parts are separated by spaces and commas.
> 17 votes

# Answer
# Ruby, ~~166~~ ~~80~~ ~~72~~ 68 characters

```
f=->s{%w(NBM BM NB M B N).map{|t|c=0;s.gsub!(t){c+=1};c.to_s+t}*' '}

```

Explanation:

* The counting is done in reverse. This is because the longer ninjas and bears and monkeys take precedence over the shorter ones.
* For `NBM`, `BM`, and `NB`, the sequences are `gsub!`'d out of the original string with a block to count how many of these sequences exist (yes, the function modifies its argument).

+ However, they can't be replaced with nothing, since otherwise `BNBMM` would be counted as `NBM` and `BM` instead of `B`, `NBM`, and `M` (because when the `NBM` would be removed, it would put the `B` and `M` together and there wouldn't be a way to distinguish it). Originally I returned a single character string (`.gsub!('NBM'){c+=1;?|}`), but I realized I could just return the result of the `+=` (which is a number, so it can't be any of `N` `B` `M`).
* ~~For `M`, `B`, and `N`, I can just `count` how many of them there are in the string (no need to remove them via `gsub!`).~~ Now it's a loop (don't know why I didn't think of that in the first place), so these are done the same way.

---

Similar solution in **Ostrich, ~~54~~ 51 chars**:

```
:s;`NBM BM NB M B N`" /{:t0:n;s\{;n):n}X:s;nt+}%" *

```

Unfortunately not a valid solution, as there is a bug in the current Ostrich version (that is now fixed, but after this challenge was posted).
> 14 votes

# Answer
# Java, ~~166~~ 162

```
void f(String a){String[]q="NBM-NB-BM-N-B-M".split("-");for(int i=0,c;i<6;System.out.print(c+q[i++]+" "))for(c=0;a.contains(q[i]);c++)a=a.replaceFirst(q[i],".");}

```

And with a few line breaks:

```
void f(String a){
    String[]q="NBM-NB-BM-N-B-M".split("-");
    for(int i=0,c;i<6;System.out.print(c+q[i++]+" "))
        for(c=0;a.contains(q[i]);c++)
            a=a.replaceFirst(q[i],".");
}

```

It works pretty simply. Just loop over the tokens, replacing them with dots and counting as long as the input contains some. Counts the big ones first, so the little ones don't mess it up.

I originally tried replacing all at once and counting the difference in length, but it took a few more characters that way :(
> 14 votes

# Answer
# CJam, ~~36~~ ~~32~~ 31 bytes

```
l[ZYX]"NBM"few:+{A/_,(A+S@`}fA;

```

*Thanks to @Optimizer for golfing off 1 byte.*

Try it online in the CJam interpreter.

### How it works

```
l                                e# Read a line L from STDIN.
 [ZYX]"NBM"                      e# Push [3 2 1] and "NBM".
           few                   e# Chop "NBM" into slices of length 3 to 1.
              :+                 e# Concatenate the resulting arrays of slices.
                {          }fA   e# For each slice A:
                 A/              e#   Split L at occurrences of A.
                   _,(           e#   Push the numbers of resulting chunks minus 1.
                      A+         e#   Append A.
                        S        e#   Push a space.
                         @`      e#   Push a string representation of the split L.
                              ;  e# Discard L.

```
> 11 votes

# Answer
# Taxi, 6284 bytes

```
Go to Post Office:W 1 L 1 R 1 L.Pickup a passenger going to Chop Suey.Go to Chop Suey:N 1 R 1 L 4 R 1 L.[A]Switch to plan N if no one is waiting.Pickup a passenger going to Cyclone.N is waiting at Writer's Depot.Go to Zoom Zoom:N 1 L 3 R.Go to Writer's Depot:W.Pickup a passenger going to Crime Lab.Go to Cyclone:N.Pickup a passenger going to Cyclone.Go to Cyclone:N 1 R 1 R 1 R.Pickup a passenger going to Cyclone.Pickup a passenger going to Cyclone.Go to Cyclone:N 1 R 1 R 1 R.Pickup a passenger going to Tom's Trims.Pickup a passenger going to Tom's Trims.Go to Tom's Trims:S 1 L 2 R 1 L.Go to Cyclone:S 1 R 1 L 2 R.Pickup a passenger going to Crime Lab.Pickup a passenger going to Tom's Trims.Go to Tom's Trims:S 1 L 2 R 1 L.Go to Crime Lab:S 1 L 1 L.Switch to plan F if no one is waiting.Pickup a passenger going to Auctioneer School.Go to Rob's Rest:S 1 R 1 L 1 L 1 R 1 R.Switch to plan D if no one is waiting.Go to Bird's Bench:S.Switch to plan B if no one is waiting.Go to Rob's Rest:N.Pickup a passenger going to KonKat's.Go to Bird's Bench:S.Pickup a passenger going to KonKat's.Go to KonKat's:N 1 R 1 L 2 R 1 R 2 R.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:N 1 L 2 L 1 L.Go to Auctioneer School:S.Pickup a passenger going to Rob's Rest.Go to Rob's Rest:N 2 L 1 R.Go to Cyclone:S 1 L 1 L 2 L.Switch to plan C.[B]Go to Auctioneer School:N 1 R 1 R.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:N.Go to Cyclone:N 1 L.[C]Pickup a passenger going to Riverview Bridge.Go to Riverview Bridge:N 2 R.Go to Chop Suey:E 2 R.Switch to plan A.[D]Go to Bird's Bench:S.Switch to plan E if no one is waiting.Pickup a passenger going to Sunny Skies Park.[E]Go to Auctioneer School:N 1 R 1 R.Pickup a passenger going to Rob's Rest.Go to Rob's Rest:N 2 L 1 R.Go to Sunny Skies Park:S 1 L 1 L.Go to Cyclone:N 1 L.Switch to plan C.[F]B is waiting at Writer's Depot.Go to Writer's Depot:S 1 R 1 L 2 L.Pickup a passenger going to Crime Lab.Go to Cyclone:N.Pickup a passenger going to Cyclone.Go to Cyclone:N 1 R 1 R 1 R.Pickup a passenger going to Crime Lab.Go to Crime Lab:S 1 L 2 R 2 L.Switch to plan J if no one is waiting.Pickup a passenger going to Auctioneer School.Go to Bird's Bench:S 1 R 1 L 1 L 1 R 1 L.Switch to plan I if no one is waiting.Go to Rob's Rest:N.Switch to plan G if no one is waiting.Pickup a passenger going to KonKat's.[G]Go to Bird's Bench:S.Pickup a passenger going to KonKat's.Go to KonKat's:N 1 R 1 L 2 R 1 R 2 R.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:N 1 L 2 L 1 L.Go to Auctioneer School:S.[H]Pickup a passenger going to Bird's Bench.Go to Bird's Bench:N 2 L 1 L.Go to Cyclone:N 1 R 1 L 2 L.Switch to plan C.[I]Go to Auctioneer School:N 1 R 1 R.Switch to plan H.[J]Go to Bird's Bench:S 1 R 1 L 1 L 1 R 1 L.Switch to plan L if no one is waiting.Go to Rob's Rest:N.Switch to plan K if no one is waiting.Pickup a passenger going to KonKat's.[K]Go to Bird's Bench:S.Pickup a passenger going to KonKat's.[L]Go to Cyclone:N 1 R 1 L 2 L.Pickup a passenger going to KonKat's.Go to KonKat's:N 2 R 2 R.Pickup a passenger going to Sunny Skies Park.Go to Rob's Rest:S 4 R 1 L 1 L 1 R 1 R.Switch to plan M if no one is waiting.Pickup a passenger going to Sunny Skies Park.[M]Go to Sunny Skies Park:S 1 L 1 L.Go to Chop Suey:N 1 R 1 R 3 R.Switch to plan A.[N]Go to Rob's Rest:N 1 L 3 L 1 L 2 R 1 R.Switch to plan O if no one is waiting.Pickup a passenger going to KonKat's.[O]Go to Bird's Bench:S.Switch to plan P if no one is waiting.Pickup a passenger going to KonKat's.[P]Go to KonKat's:N 1 R 1 L 2 R 1 R 2 R.Switch to plan Q if no one is waiting.Pickup a passenger going to Sunny Skies Park.[Q]Go to Sunny Skies Park:N 1 L 2 L 1 L.N is waiting at Writer's Depot.B is waiting at Writer's Depot.M is waiting at Writer's Depot.NB is waiting at Writer's Depot.BM is waiting at Writer's Depot.NBM is waiting at Writer's Depot.Go to Writer's Depot:N 1 L.Pickup a passenger going to Joyless Park.Pickup a passenger going to Joyless Park.Pickup a passenger going to Joyless Park.Go to Joyless Park:N 3 R 2 R 2 L.Go to Writer's Depot:W 1 R 2 L 2 L.Pickup a passenger going to Joyless Park.Pickup a passenger going to Joyless Park.Pickup a passenger going to Joyless Park.Go to Joyless Park:N 3 R 2 R 2 L.[R]Switch to plan Y if no one is waiting.Pickup a passenger going to Cyclone.0 is waiting at Starchild Numerology.Go to Starchild Numerology:W 1 L 2 R 1 L 1 L 2 L.Pickup a passenger going to Addition Alley.Go to Cyclone:W 1 R 4 L.[S]Pickup a passenger going to Auctioneer School.Go to Zoom Zoom:N.Go to Auctioneer School:W 2 L.Go to Sunny Skies Park:N.Switch to plan V if no one is waiting.Pickup a passenger going to Cyclone.Go to Cyclone:N 1 L.Pickup a passenger going to Crime Lab.Pickup a passenger going to Crime Lab.Go to Crime Lab:S 1 L 2 R 2 L.Switch to plan T if no one is waiting.Pickup a passenger going to Tom's Trims.Go to Tom's Trims:N 1 L 1 L.1 is waiting at Starchild Numerology.Go to Starchild Numerology:S 1 R 1 L 1 L 2 L.Pickup a passenger going to Addition Alley.Go to Addition Alley:W 1 R 3 R 1 R 1 R.Pickup a passenger going to Addition Alley.Go to Cyclone:N 1 L 1 L.Pickup a passenger going to Riverview Bridge.Go to Riverview Bridge:N 2 R.Go to Auctioneer School:W 2 L 1 L.Switch to plan U.[T]Go to Cyclone:N 4 L 2 L.Pickup a passenger going to Narrow Path Park.Go to Narrow Path Park:N 2 R 1 L 1 R.Go to Auctioneer School:W 1 L 1 R 2 L 1 L.[U]Pickup a passenger going to Cyclone.Go to Cyclone:N 4 L.Switch to plan S.[V]Go to Addition Alley:N 1 R 1 R 1 R.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:N 1 R 1 R.Pickup a passenger going to Post Office.Go to Cyclone:N 1 L 1 L 2 R.Pickup a passenger going to Post Office." " is waiting at Writer's Depot.Go to Writer's Depot:S.Pickup a passenger going to Post Office.Go to Post Office:N 1 R 2 R 1 L.Go to Auctioneer School:S 1 R 1 L 1 L.Pickup a passenger going to Tom's Trims.Go to Narrow Path Park:N 3 R 1 R 1 L 1 R.[W]Switch to plan X if no one is waiting.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:W 1 L 1 R 2 L 1 L.Go to Zoom Zoom:N 1 R.Go to Narrow Path Park:W 1 L 1 L 1 R.Switch to plan W.[X]Go to Tom's Trims:E 1 R 4 R 1 L.Go to Joyless Park:N 1 R 1 L 3 R.Switch to plan R.[Y]

```

Try it online!

This ain't winning me any Code Golf competitions, but this was a nice reminder for me not to write any more complex programs in Taxi. *(Sooo many special cases, and sooo much gas management...)*

A more commented version can be found here, if you dare.
> 10 votes

# Answer
# R, ~~153~~ ~~134~~ 118

This got longer really quickly, but hopefully I'll be able to shave a few. Input is STDIN and output to STDOUT.

**Edit** Change of tack. Got rid of the split string and counting parts. Now I replace the parts with a string one shorter than the part. The difference between the string lengths is collected for output.

```
N=nchar;i=scan(,'');for(s in scan(,'',t='NBM BM NB M B N'))cat(paste0(N(i)-N(i<-gsub(s,strtrim('  ',N(s)-1),i)),s),'')

```

Explanation

```
N=nchar;
i=scan(,'');                     # Get input from STDIN
for(s in scan(,'',t='NBM BM NB M B N'))  # Loop through patterns
  cat(                           # output
    paste0(                      # Paste together
      N(i) -                     # length of i minus
      N(i<-gsub(                 # length of i with substitution of
        s,                       # s
        strtrim('  ',N(s)-1)     # with a space string 1 shorter than s
        ,i)                      # in i
      ),
      s)                         # split string
  ,'')

```

Test run

```
> N=nchar;i=scan(,'');for(s in scan(,'',t='NBM BM NB M B N'))cat(paste0(N(i)-N(i<-gsub(s,strtrim('  ',N(s)-1),i)),s),'')
1: NNNMNBMMBMMBMMMNBMNNMNNNBNNNBNBBNBNMMNBBNBMMBBMBMBBBNNMBMBMMNNNNNMMBMMBM
2:
Read 1 item
Read 6 items
3NBM 8BM 5NB 14M 6B 17N
> N=nchar;i=scan(,'');for(s in scan(,'',t='NBM BM NB M B N'))cat(paste0(N(i)-N(i<-gsub(s,strtrim('  ',N(s)-1),i)),s),'')
1: NBMMBNBNBM
2:
Read 1 item
Read 6 items
2NBM 0BM 1NB 1M 1B 0N
>

```
> 7 votes

# Answer
# Pyth, 19 bytes

```
jd+Ltl=zc`zd_.:"NBM

```

This is a mixture of @isaacg's Pyth solution and @xnor's incredible Python trick.

Try it online: Demonstration or Test harness

### Explanation

```
jd+Ltl=zc`zd_.:"NBM   implicit: z = input string
             .:"NBM   generate all substrings of "NBM"
            _         invert the order
  +L                  add left to each d in ^ the following:
         `z             convert z to a string
        c  d            split at d
      =z                assign the resulting list to z
    tl                  length - 1
jd                    join by spaces and implicit print

```
> 7 votes

# Answer
# Julia, ~~106~~ 97 bytes

```
b->for s=split("NBM BM NB M B N") print(length(matchall(Regex(s),b)),s," ");b=replace(b,s,".")end

```

This creates an unnamed function that takes a string as input and prints the result to STDOUT with a single trailing space and no trailing newline. To call it, give it a name, e.g. `f=b->...`.

Ungolfed + explanation:

```
function f(b)
    # Loop over the creatures, biggest first
    for s = split("NBM BM NB M B N")

        # Get the number of creatures as the count of regex matches
        n = length(matchall(Regex(s), b))

        # Print the number, creature, and a space
        print(n, s, " ")

        # Remove the creature from captivity, replacing with .
        b = replace(b, s, ".")
    end
end

```

Examples:

```
julia> f("NBMMBNBNBM")
2NBM 0BM 1NB 1M 1B 0N

julia> f("NNNMNBMMBMMBMMMNBMNNMNNNBNNNBNBBNBNMMNBBNBMMBBMBMBBBNNMBMBMMNNNNNMMBMMBM")
3NBM 8BM 5NB 14M 6B 17N

```
> 6 votes

# Answer
# SAS, 144 142 139 129

```
data;i="&sysparm";do z='NBM','NB','BM','N','B','M';a=count(i,z,'t');i=prxchange(cats('s/',z,'/x/'),-1,i);put a+(-1)z@;end;

```

Usage (7 bytes added for sysparm):

```
$ sas -stdio -sysparm NNNMNBMMBMMBMMMNBMNNMNNNBNNNBNBBNBNMMNBBNBMMBBMBMBBBNNMBMBMMNNNNNMMBMMBM << _S
data;i="&sysparm";do z='NBM','NB','BM','N','B','M';a=count(i,z,'t');i=prxchange(cats('s/',z,'/x/'),-1,i);put a+(-1)z@;end;
_S

```

or

```
%macro f(i);i="&i";do z='NBM','NB','BM','N','B','M';a=count(i,z,'t');i=prxchange(cats('s/',z,'/x/'),-1,i);put a+(-1)z@;end;%mend;

```

Usage:

```
data;%f(NNNMNBMMBMMBMMMNBMNNMNNNBNNNBNBBNBNMMNBBNBMMBBMBMBBBNNMBMBMMNNNNNMMBMMBM)

```

Result:

```
3NBM 5NB 8BM 17N 6B 14M

```
> 4 votes

# Answer
# Python 2, ~~93~~ ~~88~~ ~~89~~ 84 Bytes

Taking the straightforward approach.

```
def f(n):
 for x in"NBM BM NB M B N".split():print`n.count(x)`+x,;n=n.replace(x,"+")

```

Call like so:

```
f("NBMMBNBNBM")

```

Output is like so:

```
2NBM 0BM 1NB 1M 1B 0N

```
> 4 votes

# Answer
# PHP4.1, 92 bytes

Not the shortest one, but what else would you expect from PHP?

To use it, set a key on a COOKIE, POST, GET, SESSION...

```
<?foreach(split(o,NBMoNBoBMoMoBoN)as$a){echo count($T=split($a,$S))-1,"$a ";$S=join('',$T);}

```

The apporach is basic:

* Split the string into the names of the creatures
* Count how many elements there are
* Subtract 1 (an empty string would give an array with 1 element)
* Output the count and the creature name
* Join it all together, using an empty string (which will reduce the string and remove the last creature)

Easy, right?
> 3 votes

# Answer
# Perl, 46

```
#!perl -p
$_="NBM BM NB M B N"=~s/\w+/~~s!$&!x!g.$&/ger

```
> 3 votes

# Answer
# JavaScript, ~~108~~ 116 bytes

Just a straight forward approach, nothing fancy

```
o="";r=/NBM|NB|BM|[NMB]/g;g={};for(k in d=(r+prompt()).match(r))g[d[k]]=~-g[d[k]];for(k in g)o+=~g[k]+k+" ";alert(o);

```
> 2 votes

# Answer
# C, 205 186 184 bytes

A little different approach based on state machine. where `t` is the state.

```
a[7],t,i;c(char*s){do{i=0;t=*s==78?i=t,1:*s-66?*s-77?t:t-4?t-2?i=t,3:5:6:t-1?i=t,2:4;i=*s?i:t;a[i]++;}while(*s++);printf("%dN %dB %dM %dNB %dBM %dNBM",a[1],a[2],a[3],a[4],a[5],a[6]);}

```

Expanded

```
int a[7],t,i;

void c(char *s)
{
    do {
        i = 0;
        if (*s == 'N') {
            i=t; t=1;
        }
        if (*s == 'B') {
            if (t==1) {
                t=4;
            } else {
                i=t;
                t=2;
            }
        }
        if (*s == 'M') {
            if (t==4) {
                t=6;
            } else if (t==2) {
                t=5;
            } else {
                i=t;
                t=3;
            }
        }
        if (!*s)
            i = t;
        a[i]++;
    } while (*s++);
    printf("%dN %dB %dM %dNB %dBM %dNBM",a[1],a[2],a[3],a[4],a[5],a[6]);
}

```

Test function

```
#include <stdio.h>
#include <stdlib.h>

/*
 * 0 : nothing
 * 1 : N
 * 2 : B
 * 3 : M
 * 4 : NB
 * 5 : BM
 * 6 : NBM
 */
#include "nbm-func.c"

int main(int argc, char **argv)
{
    c(argv[1]);
}

```
> 1 votes

# Answer
# SpecBAS - 164

```
1 INPUT s$
2 FOR EACH a$ IN ["NBM","BM","NB","M","B","N"]
3 LET n=0
4 IF POS(a$,s$)>0 THEN INC n: LET s$=REPLACE$(s$,a$,"-"): GO TO 4: END IF
5 PRINT n;a$;" ";
6 NEXT a$

```

Uses the same approach as a lot of others. Line 4 keeps looping over the string (from largest first), replaces it if found.

SpecBAS has some nice touches over original ZX/Sinclair BASIC (looping through lists, finding characters) which I'm still finding out.
> 1 votes

# Answer
# C, 146

```
f(char*s)
{
  char*p,*q="NBM\0NB\0BM\0N\0B\0M",i=0,a=2;
  for(;i<6;q+=a+2,a=i++<2)
  {
    int n=0;
    for(;p=strstr(s,q);++n)*p=p[a>1]=p[a]=1;
    printf("%d%s ",n,q);
  }
}

// Main function, just for testing
main(c,a)char**a;{
  f(a[1]);
}

```
> 1 votes

# Answer
# Haskell - 177 bytes (without imports)

```
n s=c$map(\x->(show$length$filter(==x)(words$c$zipWith(:)s([f(a:[b])|(a,b)<-zip s(tail s)]++[" "])))++x++" ")l
f"NB"=""
f"BM"=""
f p=" "
l=["N","B","M","NB","BM","NBM"]
c=concat

```

(Sorry for the internet necromancy here.)

The Haskell Platform doesn't have string search without imports, and I wanted to show off and exploit the fact that the searched strings are all substrings of one (without repetitions), so that grouping characters can be done by identifying pairs that are allowed to follow each other, which is what `f` does here.

I still need the full list `l` in the end to check for equality and display exactly as required, but would not, had the challenge only been to report the number of occurrences of the possible `words` in any order.
> 1 votes

# Answer
# Vyxal, 18 bytes

```
`NBM`KṘ(n/₅‹n+¨…_∑

```

Try it Online!

```
`NBM`              # 'NBM'
     K             # Substrings
      Ṙ(           # Iterate over
        n/         # Split current string by current substring of NBM
          ₅‹       # Duplicate and decrement length
            np¨…_  # Prepend current substring of NBM and output with a trailing space
                 ∑ # Concatenate for next iteration

```
> 1 votes

# Answer
# Husk, 27 bytes

```
;zS`+ös←Lx₁GoΣ`x⁰₁
↔ÖLQ"NBM

```

Try it online!

uses the splitting technique from the Vyxal answer.

# Husk, 28 bytes

```
m§+osL←k€₁Ẋ`-U¡Ṡ-(→n₁ḣ
Q"NBM

```

Try it online!

Funny set intersection based idea.
> 1 votes

# Answer
# Japt `-S`, 18 bytes

Outputs in reverse order.

```
"NBM"ã ÔËiUèDU=rDS

```

Try it (footer reverses the output)

```
"NBM"ã ÔËiUèDU=rDS     :Implicit input of string U
"NBM"ã                 :Substrings of "NBM"
       Ô               :Reverse
        Ë              :Map each D
         i             :  Prepend
          UèD          :    Count of D in U
             U=        :    Reassign to U*
               rD      :      Replace D with
                 S     :      Space
                       :Implicit output joined with spaces

```

\*This is done within the second argument of the `è` method but as that only expects 1 argument, it's result is ignored within the mapping & prepending.
> 1 votes

# Answer
# Excel, ~~149~~ 145 bytes

<sup>Saved 4 bytes by realizing I can directly use `LEN(a)` after I rewrote the function from my first - never submitted - draft.</sup>

```
=LET(a,SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"NBM",1),"BM",2),"NB",3),LEN(a)-LEN(SUBSTITUTE(a,{"N","B","M",3,2,1},))&{"N","B","M","NB","BM","NBM"})

```

Start by replacing NBM with 1 then BM with 2 and NB with 3. Now we have a string that is as many characters long as they are creatures. One by one, we check the difference between that string's length and it's length with one of the creatures removed. Output is an array of cells.
> 1 votes

# Answer
# Bash - 101

```
I=$1
for p in NBM BM NB M B N;{ c=;while [[ $I =~ $p ]];do I=${I/$p/ };c+=1;done;echo -n ${#c}$p\ ;}

```

Pass the string as the first argument.

```
bash nmb.sh MBNNBBMNBM

```

Explained a bit:

```
# We have to save the input into a variable since we modify it.
I=$1

# For each pattern (p) in order of precedence
for p in NBM BM NB M B N;do
    # Reset c to an empty string
    c=

    # Regexp search for pattern in string
    while [[ $I =~ $p ]];do
        # Replace first occurance of pattern with a space
        I=${I/$p/ }
        # Append to string c. the 1 is not special it could be any other
        # single character
        c+=1
    done

    # -n Suppress's newlines while echoing
    # ${#c} is the length on the string c
    # Use a backslash escape to put a space in the string.
    # Not using quotes in the golfed version saves a byte.
    echo -n "${#c}$p\ "
done

```
> 0 votes

# Answer
# rs, 275 bytes

```
(NBM)|(NB)|(BM)|(N)|(B)|(M)/a\1bc\2de\3fg\4hi\5jk\6l
[A-Z]+/_
#
+(#.*?)a_b/A\1
+(#.*?)c_d/B\1
+(#.*?)e_f/C\1
+(#.*?)g_h/D\1
+(#.*?)i_j/E\1
+(#.*?)k_l/F\1
#.*/
#
#(A*)/(^^\1)NBM #
#(B*)/(^^\1)NB #
#(C*)/(^^\1)BM #
#(D*)/(^^\1)N #
#(E*)/(^^\1)B #
#(F*)/(^^\1)M #
\(\^\^\)/0
 #/

```

Live demo and tests.

The workings are simple but a little odd:

```
(NBM)|(NB)|(BM)|(N)|(B)|(M)/a\1bc\2de\3fg\4hi\5jk\6l

```

This creatively uses groups to turn input like:

```
NBMBM

```

into

```
aNBMbcdeBMfghijkl

```

The next line:

```
[A-Z]+/_

```

This replaces the sequences of capital letters with underscores.

```
#

```

This simply inserts a pound sign at the beginning of the line.

```
+(#.*?)a_b/A\1
+(#.*?)c_d/B\1
+(#.*?)e_f/C\1
+(#.*?)g_h/D\1
+(#.*?)i_j/E\1
+(#.*?)k_l/F\1
#.*/

```

*This* is the beginning cool part. It basically takes the sequences of lowercase letters and underscores, converts them into capital letters, groups them together, and places them before the pound that was inserted. The purpose of the pound is to manage the sequences that have already been processed.

```
#

```

The pound is re-inserted at the beginning of the line.

```
#(A*)/(^^\1)NBM #
#(B*)/(^^\1)NB #
#(C*)/(^^\1)BM #
#(D*)/(^^\1)N #
#(E*)/(^^\1)B #
#(F*)/(^^\1)M #
\(\^\^\)/0
 #/

```

The capital letters are replaced by their text equivalents with the associated counts. Because of a bug in rs (I didn't want to risk fixing it and getting disqualified), the empty sequences are converted into `(^^)`, which is replaced by a 0 in the second-to-last line. The very last line simply removes the pound.
> 0 votes

# Answer
# KDB(Q), 76 bytes

```
{" "sv string[-1+count@'enlist[x]{y vs" "sv x}\l],'l:" "vs"NBM NB BM N B M"}

```

# Explanation

```
                                                   l:" "vs"NBM NB BM N B M"     / substrings
                        enlist[x]{y vs" "sv x}\l                                / replace previous substring with space and cut
              -1+count@'                                                        / counter occurrence
       string[                                  ],'                             / string the count and join to substrings
{" "sv                                                                     }    / concatenate with space, put in lambda

```

# Test

```
q){" "sv string[-1+count@'enlist[x]{y vs" "sv x}\l],'l:" "vs"NBM NB BM N B M"}"NNNMNBMMBMMBMMMNBMNNMNNNBNNNBNBBNBNMMNBBNBMMBBMBMBBBNNMBMBMMNNNNNMMBMMBM"
"3NBM 5NB 8BM 17N 6B 14M"
q){" "sv string[-1+count@'enlist[x]{y vs" "sv x}\l],'l:" "vs"NBM NB BM N B M"}""
"0NBM 0NB 0BM 0N 0B 0M"

```
> 0 votes

# Answer
# Haskell, 244 bytes

```
import Data.List
s="NBM"
[]#_=[[]]
a#[]=[]:a#s
l@(a:r)#(b:m)
 |a==b=let(x:y)=r#m in((a:x):y)
 |True=[]:l#m
c?t=length$filter(==t)c
p=["N","B","M","NB","BM","NBM"]
main=getLine>>= \l->putStrLn.intercalate " "$map(\t->show((l#[])?t)++t)p

```
> 0 votes

# Answer
# Stax, 18 bytes

```
â╥)3╨‼!∩╢←◘♀←N╟Ijƒ

```

Run and debug it
> 0 votes

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