title: Hide a Brainf*** greeting in other code

text:
# Question
Title: Hide a Brainf*** greeting in other code
The goal is to write a program (anything except explicit brainfuck) which prints Barney Stinson's best rule:

> New is always better.

when interpreted normally, but

> Legen... wait for it... dary!

When processed with a Brainfuck interpreter.

May the most popular bro win. You have 72 hours to be legendary.

# Answer
> 11 votes
## C#

So I decided to get a little more... creative with my entry. The Brainfuck code is embedded into the C# as the various operators (not in comments or in hardcoded strings), while the C# code itself operates on a similar principal to the way Brainfuck prints characters (meaning there are no hardcoded strings, and C# generates each individual character as an integer then casts it to a char when printing).

I'm sure I could have made this more elegant, but it took me long enough to finish as it is.

Everything was tested on this JavaScript Brainfuck interpreter by Cal Henderson and with Visual Studo 2012's C# compiler (targeted at .NET framework v4.0).

```
using System;

namespace Polyglot
{
    internal static class Program
    {
        private static void Main()
        {
            var a = new short[50];

            short _1 = 72;
            short _2 = 0;
            short _3 = 0;
            short _4 = 0;
            short _5 = 0;
            short _6 = 0;
            short _7 = 97;
            short _8 = 0;
            short _9 = 0;
            short _10 = 0;
            short _11 = 0;
            short _12 = 0;
            short _13 = 0;
            short _14 = 0;
            short _15 = 0;
            short _16 = 46;
            short _19 = 0;
            short _20 = 0;
            short _21 = 0;

            if( 0 >= 0 )
            {
                ++_1;
                ++_1;
                ++_1;
                ++_1;
            }

            a[ -1 < 0 ? 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 : 0 + 1 > 1 ? 0 : 0 ] = 9001;

            if( 7 < 42 )
            {
                ++_1;
                ++_1;
            }

            Console.Write( (char)_1 );

            _2 = 101;
            _1 += 1 + 1 + 1 + 1 + 1;

            _3 = 42 > 7 ? 110 + 9 : 1 + 1;

            a[ -1 < 0 ? 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 : 0 > 0 ? 0 : 0 ] = 9001;

            if( 1 < 2 )
                _4 = 32;

            Console.Write( (char)_2 );

            ++_1;
            _5 = 105;

            Console.Write( (char)_3 );

            --_1;

            _6 = 115;

            Console.Write( (char)_4 );

            ++_1;
            ++_1;
            ++_1;
            _1 += 1 + 1 + 5;

            Console.Write( (char)_5 );

            --_1;
            --_1;

            if( 42 > 41 )
            {
                ++_1;
                ++_1;
                ++_1;
            }

            a[ -1 < 0 ? 0 : 10 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 > 5 ? 0 : 0 ] = 9001;

            if( 42 < 9001 )
                Console.Write( (char)_6 );

            Console.Write( (char)_4 );
            Console.Write( (char)_7 );

            if( 12 > 11 && 11 > 10 )
            {
                _8 = 108;
                _9 = _3;
            }
            else
            {
                ++_1;
                ++_1;
                ++_1;
            }

            a[ -1 < 0 ? 1 + 1 + 1 + 1 + 1 + 1 : 1 > 2 ? 0 : 0 ] = 9001;

            if( _4 < _1 )
            {
                ++_1;
                Console.Write( (char)_8 );
            }
            else if( _4 > _19 && _2 > _20 )
            {
                ++_21;
                ++_21;
                ++_21;
                ++_21;
                ++_21;
                _21 += (short)( _21 + 36 );
            }

            a[ -7 < 9 ? 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 : 4 > 8 ? 9 : 9 ] = (short)( 12 < 10 ? -_4 : _9 );
            Console.Write( (char)_9 );

            if( _4 > _9 )
            {
                ++_1;
                ++_1;
                ++_1;
            }

            a[ -9 < 7 ? 10 - 1 - 1 - 1 - 1 : 6 > 7 ? 0 : 0 ] = _21;

            if( 1 < 0 )
                return;
            else
            {
                ++_1;
                Console.Write( (char)_7 );
            }

            _10 += 5 + 4 + 1 + 2 + 8 + 9 + 1 + 91;
            Console.Write( (char)_10 );

            if( 10 > _4 ) ++_21; else a[ -0 < 0 ? 5 + 6 + 1 + 2 + 3 + 9 : 1 > 2 ? 0 : 9 ] = 50;

            if( _21 <= _4 )
                _11 = 58 + 57;

            Console.Write( (char)_11 );

            if( _2 <= _8 )
                Console.Write( (char)_4 );
            else if( 1 >= 2 )
                return;
            else if( 42 >= _4 )
                _1 += ++_21;
            else
            {
                a[ -99 < --_1 ? --_1 - _1 : 44 > 12 ? 9 : 7 ] = (short)( _2 < _4 ? _21 : 6 );
                throw new Exception();
            }

            switch( _4 )
            {
                case 32:
                    var x = (char)( (short)( _4 + 66 ) );
                    Console.Write( x );
                    break;
                default: break;
            }

            _12 += (short)( ++_12 + ( ++_1 ) + 1 + 1 + 1 );
            Console.Write( (char)_12 );

            _13 += (short)( 39 + 38 + 39 );
            Console.Write( (char)_13 );

            if( _12 < _13 )
                Console.Write( (char)_13 );

            if( _13 >= _4 )
            {
                _14 = (short)( 500 - ( - ( 50 ) ) - ( --_1 ) - 90 - ( -4 ) - 267 );
                Console.Write( (char)_14 );
            }

            switch( _1 )
            {
                case 52:
                    _15 += (short)( ++_1 + ( ++_21 ) );
                    break;
                default:
                    _15 += (short)( 15 + ( ++_1 ) + 2 );
                    break;
            }

            Console.Write( (char)_15 );

            if( _16 <= 3521 && _21 < _4 )
                Console.WriteLine( (char)_16 );

            _16 = (short)( Int16.Parse( "54" ) % 2 );
            _20 = (short)( Int16.Parse( "99" ) / ( _1 > _4 ? 3 : 0 ) );
            _1 = (short)( 02.23 );

            if( _16 > 9 || _20 >= 52 )
                _1 += (short)( ( ++_1 ) + _21 );

            a[ -0 < 0 ? -52 - ( --_20 ) : 1 > 0 ? 1 : 2 ] = (short)( _12 < _19 ? Int16.Parse( "19" ) : 44 );
            _12 -= (short)f( --_19 / 19.467d );

            if( _12 > _14 )
                _19 += (short)( _19 + 1 + _3 + 5 );

            a[ -904 < 409 ? 4 + ( ++_4 ) + 4 : 49 > 50 ? 49 : 50 ] = (short)( 50 < 99 ? _4 + 669.2452 : 0 );

            if( 44 > ++_4 )
                a[ -9 < 6 ? 6 + ( ++_4 ) : 9 > 2 ? 44 : 8 ] = 3;
        }

        private static double f( double x )
        {
            return x < 12 ? x + 13.22 : x < 6 ? x + 90.45 : 5555;
        }
    }
}

```

This is the original Brainfuck code I wrote for this challenge:

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

```

When running the C# code through a Brainfuck interpreter, you end up with the following commands (notice the addition of the square brackets at the beginning, these are from the array declaration and don't do anything, since the cell under the memory pointer in the array will already be 0):

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

```

# Answer
> 6 votes
# Smalltalk

```
"adding adding all the time"
"1+1+1+1+1+1+1+1+1+1+1" "is not fine"
"more to come / going far"
"+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1"
"all that work for a single char"

"happy me / a loop to start"
"[>++>+++>++++>+++++<<<<-]"
"was it code or just a fart?"
"adding adding / thats not fine"
"+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1"

">>+" 'New is always better.' "shall I " print
">+.++.--.+++++++++.----------.<<----...<+++++++"
"the garbage here gives us no hint"
".>>+++++++++++.>---.++++++++"

"hurray a change to stop the pain"
".>---------.<<<<.>>"
"the author now has in his brain"
"-----------------.>>-----.+++.<<<<.>>>.>++."
"We all agree the time is here"
"<<<...<.>>--.>--------.>--.+++++++.<<<<."
"to finish this and have a beer"

```

type into a workspace and press "doIt", or send to BF. BF stolen from the other posters - thanks.

# Answer
> 4 votes
## Javascript / Brainfuck

Ungolfed version as it is not a code-golf contest :

```
var outputString='';
'+++++++@++++[>++@/+@@>@/+@+@++>++++++@/+>+@++@/+@@+++++@/>@+@+++++@/+++@+<@/<<<<-]>>>@-.>++.+@/+@@.--.>.<-@/.@<@<++...<-.@/>>>>+++++@++++.<-@/-@-.@+@/+@+@+++++@/.>-@--@/.<<<<.>>>@---.>---@/-@@-@/.@+@++.<<<@/<@.@>>>+++@/.@@>@/+@+@.<<<@/...<@.>>>--@/---.---.>--.+++++++.<<<<+.<'
  .split('/')
  .forEach(function(e) {
    var matched=e.match(/[^@]*@/g);
    if (matched) {
      var asciiCode=0;
      for(var i=0;i<matched.length;i++) {
        asciiCode=matched[i-0].length-1+10*asciiCode;
      }
      outputString+=String.fromCharCode(asciiCode);
    }
  });
  alert(outputString);

```

That was the occasion for me to learn BF and that was fun :)
The difficulty was to **never** use `,` as BF interprets it as user input and be sure that byte is 0 before using `[]` for accessing elements of arrays.
The JS encoding is pretty simple, each strings before `/` encode a character and each string length before `@` defines ASCII code in decimal. (`+++++++@++++[>++@` = `78` = `N`)

You can test Brainfuck here : http://copy.sh/brainfuck/

# Answer
> 3 votes
# Cubically (TIO) / BF (TIO)

```
+5+1/1+5+3@6:2/1+5+5+1@6+2@6:5/1+3@6:5+1/1+5+5+1@6:5+2/1+5+5+2@6:5/1+3@6:5+2/1+5+5@6:5+5+2@6:2/1+5+53[@6>:5+2/1+5+5@6>:4/1+5+5+3@6+>:5+2/1+55+2@6:5/1+3@6>:5+3/1+55@6>:2/1+551@6<<<<<-]>:5+3./1+552-@66>+.:2/1+5+51.@6--.>:5+1/1+5+5+2@6:1/1+5@6+++++.>----...>+++++++.<<+++++++++.<----.++++++++.>---.>>.<<<---.>-----.+++.>>.<<<+++.>++.>...>.<<<-----.---.>--.+++++++.>>+.

```

*(Updated 8/4/17 to account for language changes in Cubically)*

Basically this just uses as many characters from the BF program as it can in the Cubically program, then sticks the rest of the BF program on the end of it. No forced termination with `&`/`E` in the Cubically program is necessary.

# Answer
> 2 votes
## Python / BrainF\**k, 362 chars

BrainF\**k code taken from Clément Renaud's deleted answer.

**Edit** \- Initial null character no longer printed.

```
t='++++++++++_+++++++|^+++++++|+[>++>+++%>++++>+++++<<<<-||]+++++++++++|*+++++++++++++@+>>+.>+||.++.|--.+++++++++.--|^--------.<<----..._<+++++|++.>|>+++++&++++++.>---.+=+++++++|.>---------.<<^<<.>>--||-----|--~-----|---.>>-----~.+++.<<<<.>|>>.*>++.<<<...<.>>--._>|--------|.>-^-.+++++++.<<<<!!!'
print ''.join((chr(93+len(x))if x else' ')for x in t.split('|'))

```

Uses a very simple trick - `|` characters were added to the BF program, and the distances between them encode the string printed in Python. The Python code is mostly ignored by BF.

---
Tags: popularity-contest, polyglot, brainfuck
---


# Question
Title: Trivial Brainf**k Substitution Interpreter
Brainf\**k is the most famous esoteric programming language and is the inspiration for hundreds of other esoteric languages. In fact, there are quite a few languages that are so heavily based off of Brainf\**k that the only difference is the characters used. Your challenge is to interpret one of these languages.

## Brainf\**k

Brainf\**k uses these commands:

```
> Move pointer to the right
< Move pointer to the left
+ Increment the memory cell under the pointer
- Decrement the memory cell under the pointer
. Output the character signified by the cell at the pointer
, Input a character and store it in the cell at the pointer
[ Jump past the matching ] if the cell under the pointer is 0
] Jump back to the matching [ if the cell under the pointer is nonzero

```

## Trivial Brainf\**k Substitution

There are lots of esolangs that are identical to Brainf\**k in that they use the same commands, just with different characters/strings signaling the commands. For example, take Ook!:

```
Brainf**k | Ook         | Command
-----------------------------------------------------
>         | Ook. Ook?   | Move the pointer to the right
<         | Ook? Ook.   | Move the pointer to the left
+         | Ook. Ook.   | Increment the memory cell under the pointer
-         | Ook! Ook!   | Decrement the memory cell under the pointer
.         | Ook! Ook.   | Output the character signified by the cell at the pointer
,         | Ook. Ook!   | Input a character and store it in the cell at the pointer
[         | Ook! Ook?   | Jump past the matching Ook? Ook! if the cell under the pointer is 0
]         | Ook? Ook!   | Jump back to the matching Ook! Ook? if the cell under the pointer is nonzero

```

Ook is exactly like Brainf\**k, except for the syntax.

`TrivialBrainfuckSubstitution` is a function defined as:

```
TrivialBrainfuckSubstitution(string1, string2, string3, string4, string5, string6, string7, string8)

```

Each string provided substitutes the corresponding Brainf\**k character - so `string1` will be a substitution for `>`, `string2` will be a substitution for `<`, so on and so forth.

For example, Ook! is equivalent to `TrivialBrainfuckSubstitution("Ook. Ook?", "Ook? Ook.", "Ook. Ook.", "Ook! Ook!", "Ook! Ook.", "Ook. Ook!", "Ook! Ook?", "Ook? Ook!")`.

Alphuck is equivalent to `TrivialBrainfuckSubstitution("a", "c", "e", "i", "j", "o", "p", "s")`.

# The challenge

Implement `TrivialBrainfuckSubstitution`.

To elaborate: Given eight strings representing the eight substitutions and a ninth string representing a program, interpret the program as a trivial Brainf\** substitution.

# Rules

* `TrivialBrainfuckSubstitution` may take function arguments or command line arguments. These are the only ways it may take the first eight arguments.
* `TrivialBrainfuckSubstitution` can take the ninth argument from standard input, a file, or a literal ninth argument.
* `TrivialBrainfuckSubstitution` must be able to take any ASCII characters as substitutions. It does not have to handle Unicode, and you can assume there are no duplicate elements provided.
* Note that the actual function in your code need not be named `TrivialBrainfuckSubstitution`. This is just the title of the function; the actual name in the code can be `f`, or `x`, or a lambda, or whatever you like.
* Your interpreter should not require any spaces between command substitutions. However, it should not break if they are present. To rephrase, it should ignore unrecognized commands, just like normal Brainf\**k.
* You may assume that all substitutions are the same length. I.e. you may assume that `AB`, `A`, and `B` are never in the same substitution set.

# Challenge-specific Brainf\**k semantics

In your newly-created Brainf\**k language:

* You do not need to be able to go left from the start of the tape. (You can choose to allow this.)
* The tape should have a minimum length of 30000. (If you want it can be longer or allocated dynamically.)
* The maximum value of the tape elements must be the maximum value for an integer in your (host) language.
* Input can be read from standard input or a file.
* An attempt to read `EOF` (End Of File) should not cause any undefined behavior. `EOF` must simply be stored as would any other character read.

# Test cases

Test case 1
Test case 2

# Winner

As with , the shortest submission wins. I won't ever accept an answer unless one is 50 bytes shorter than all others.

Also, as this challenge is somewhat more difficult than others (while certainly not the hardest), I kindly ask that you include an ungolfed version and explanation with your answer.

# Answer
> 5 votes
# APL (Dyalog), 49 bytes

Prompts for program as text, then for a list of eight PCRE patterns. Note that this allows for substitutions of differing lengths, and even mapping multiple substitutions to each BF command, at the cost of having to escape some characters. Outputs to STDERR.

```
⎕CY'dfns'
bf(⎕,'.')⎕R(,¨'><+-.,[] ')⊢⍞

```

Try it online! (runs first two test cases, as the third is faulty)

`⎕CY'dfns'`**C**op**y** the **dfns** workspace

prompt for text input (the symbol is mnemonic: a quote character in a console)

yield that (serves to separate the substitution patterns from the input)

`(``)⎕R(``)`**R**eplace:

`⎕,'.'` input (mnemonic: console) followed by PCRE for "any character"

… with:

`'><+-.,[] '` the BF symbols followed by a BF no-op space

ravel each (to make them into character vectors/strings instead of scalars)

`bf` evaluate as **BF**.

---

As of posting, this is way more than 50 bytes shorter than the other two solutions.

# Answer
> 6 votes
# Python 2, 447 bytes

```
import re,sys
def f(b,r,a,i,n,f,u,c,k):
 d,e,g,m=[0]*30000,0,0,''
 for n in re.finditer('|'.join(r'(?P<%s>%s)'%m for m in[(j,re.escape(l))for j,l in zip('rlidoswen',[r,a,i,n,f,u,c,k,'.'])]),b):
  m+=' '*g+{'r':'e+=1','l':'e-=1','i':'d[e]+=1','d':'d[e]-=1','o':'sys.stdout.write(chr(d[e])),','s':'d[e]=ord(sys.stdin.read(1))','w':'while d[e]:','e':'pass'}.get(n.lastgroup,'')+'\n';g+=n.lastgroup=='w';g-=n.lastgroup=='e'
 try:exec m
 except:d[e]=-1

```

Try it online!

The first argument `b` is the code and the arguments `r a i n f u c k` are `> < + - . , [ ]` respectively.

Well... Lemme know if I missed out on anything.

---

## Explanation

This implements a golfed tokenizer.

```
import re, sys

def trivial_brainfuck_substitution(code, r, a, i, n, f, u, c, k):  # define function with arguments
    tape, index, loop, result = [0]*30000, 0, 0, ''                # initialize tape, pointer, loop state and the final code

    for i in re.finditer(                                                    # iterate over matches of the regex...
                 '|'.join(                                                   # which is the next list joined by '|'
                     r'(?P<%s>%s)' % m for m in                              # construct a regex with a named group
                         [(j, re.escape(l)) for j, l in                      # a tuple of...
                             zip('rlidoswen', [r, a, i, n, f, u, c, k,'.'])  # the group name and the command
                         ]
                  ),
             code):                                                          # in the given code

        result += (' ' * loop +                                         # a space for the current amount of loops
                      {
                          'r': 'index += 1',                            # move to next cell
                          'l': 'index -= 1',                            # move to previous cell
                          'i': 'tape[index] += 1',                      # increment current cell
                          'd': 'tape[index] -= 1',                      # decrement current cell
                          'o': 'sys.stdout.write(chr(tape[index]))',    # output current cell's value as ASCII character
                          's': 'tape[index] = ord(sys.stdin.read(1))',  # store ASCII number of input in current cell
                          'w': 'while tape[index]:',                    # start a while loop
                          'e': 'pass'                                   # end a while loop
                      }.get(i.lastgroup, '') + '\n'                     # get respective command or an empty string for a no-op
                  )

        loop += i.lastgroup == 'w'  # increment the loop counter
        loop -= i.lastgroup == 'e'  # decrement the loop counter

    try:
        exec result       # execute the generated code as Python code
    except:               # except on a TypeError, thrown when no input is found
        tape[index] =- 1  # store -1 in current cell

```

# Answer
> 5 votes
# Python 2, ~~373~~ ~~372~~ ~~381~~ ~~380~~ 375 bytes

-1 Thanks to @StepHen

-1 Thanks to @RohanJhunjhunwala

-5 More thanks to @RohanJhunjhunwala's suggestion and cleaning up some repeated code

+9 Cause @totallyhuman made a valid point about `raw_input()` requiring a new line

```
import sys
def f(c,r,l,i,d,p,n,b,j):
 t,x,a,h,s,o,v=[0]*30000,0,0,[],0,'',[r,l,i,d,p,n,b,j," "]
 w=map(len,v)
 while a<len(c):
	for u in range(9):
	 if v[u]==c[a:w[u]+a]:break
	if s<1or u>5:
	 exec"x+=1|x-=1|t[x]+=1|t[x]-=1|o+=chr(t[x])|t[x]=ord(sys.stdin.read(1))|if t[x]and s<1:h+=[a]\nelse:s+=1|if s<1:a=h.pop()-w[6]\nelse:s-=1|".split("|")[u]
	x%=30000
	a+=w[u]
 return o

```

Try it online!

Works on the first two test cases, but it looks like the third one is messed up since it has 9 strings instead of 8, and two are the same. It also works on some other Hello World! Brainfuck programs.

---

# Explanation

```
import sys
def TrivialBrainfuckSubstitution(code, greater, less, plus, minus, period, comma, leftbracket, rightbracket):
    tape, index, slot, loopindex, skip, output = [0]*8**5, 0, 0, [], 0, ''                  # Set up variables for the tape, tape index, code index, list of loop indices we're in, skipping indicator, and output string
    values = [greater, less, plus, minus, period, comma, leftbracket, rightbracket," "]     # Create a list of all possible values to find in the code
    lengths = map(len, values)                                          # Create a list with the lengths of all of the elements in value
    while slot < len(code):                                             # While we havent reached the end of the string
        for u in range(9):                                              # For each value in the value list
            if value[u] == code[slot:lengths[u] + slot]:break           # If the u-th element of values is equal to the same length chuck of the code from the current index
        if skip < 1 or u > 5:                                           # If we're not skipping operations or if we found a leftbracket or rightbracket
            if u == 0:                                                  # If the option was a greater
                index += 1                                              # Increment the tape counter
            elif u == 1:                                                # Else if it was a less
                index -= 1                                              # Decrement the tape counter
            elif u == 2:                                                # Else if it was a plus
                tape[index] += 1                                        # Increment the current tape cell
            elif u == 3:                                                # Else if it was a minus
                tape[index] -= 1                                        # Decrement the current tape cell
            elif u == 4:                                                # Else if it was a period
                output += chr(tape[index])                              # Append the character value of the current tape cell to the output string
            elif u == 5:                                                # Else if it was a comma
                tape[index] = ord(sys.stdin.read(1))                    # Store only a single character of input into the tape cell
            elif u == 6:                                                # Else if it was a leftbracket
                if tape[index] and skip < 1:                            # If the current cell is non-zero and we aren't currently skipping over a loop
                    loopindex += [index]                                # Append the current index to the loopindex list
                else:                                                   # Else we're trying to skip to the end of a loop
                    skip += 1                                           # Increment the skip counter (a count of the number of rightbrackets we need to skip to continue executing)
            elif u == 7:                                                # Else if it was a rightbracket
                if skip < 1:                                            # If we're executing code normally
                    slot = loopindex.pop() - lengths[6]                 # Move to the index we stored when we hit the leftbracket, but push forward enough so we hit it with the next character
                                                                        # Simultaneously remove the last value from the loopindex list since we just used it
                else:                                                   # Else we're trying to move past some loop
                    skip -= 1                                           # Decrement the skip counter since we found another rightbracket
        index = index % 30000                                           # Map the index back to 0-29999
        slot += lengths[u]                                              # Move past the current operator
 return output                                                          # Return the output string we generated

```

I took a different approach than totallyhuman did, so that I didn't need to import and modules. It does however use the same trick with passing strings to `exec` to have it do all the work. Effectively, at the start of each loop, it looks at the current index and sees if the text that follows can be matched to any of the operators that were given. If it can't, then the counter will end at an index associated with a non-valid character in this language.

The hardest part for me was getting a refined way of matching loop starts and ends. I eventually settled on a counter that gets incremented every time it sees a loop start operator, and decrements every time it sees a loop end. So in order to have the now parsed option executed, we have to be not skipping over code (indicated by a skip counter of 0) or it's the loop start or loop end characters (or a bad character, but nothing happens with that, so it's okay).

That counter index is then used to take the index-th slot of an array of strings that is created by splitting that massive string you see at all of the `|`s. That line of code is then executed by `exec` which will do a handful of checks and variable mutations. At the end of the loop we skip past the operator we just found and keep going. Finally, return the output string we've been adding onto this entire time.

On of the key pieces to this was how skipping back to loops was handled. Every time a loop was started, it appended its index to the back of a list, and every time a loop ended, it set the code index to the last value of that list (minus the length of the loop end operator so that when it was pushed "past" the loop end operator we would be at the loop start operator again).

# Answer
> 1 votes
# PHP, ~~275 222 234 238 239 235 233 236 230 229 224~~ 223 bytes

```
for($p=_.strtr($argv[9],array_flip(array_slice($argv,$m=1,8)));~$c=$p[$i+=$c<7];eval(['$m++','$m--','$$m++','$$m--','echo chr($$m)','$$m=ord(fgetc(STDIN))'][$c].';'))for($n=$d=[6=>!$$m,-1][$c];$n;)$n+=[6=>1,-1][$p[$i+=$d]];

```

Takes dictionary from arguments 1..8, code from argument 9, input from STDIN.

The tape has 2^64 cells and starts almost in the middle, but does not wrap.
Insert `,$m=($m+3e4)%3e4` after `eval(...)` for a wrapping 30K tape.
<sup>(or replace `'$m--'` with `'$m+=29999'` and insert `,$m%=3e4` after `eval(...)` \- that´s 3 bytes shorter)</sup>

Requires PHP 5.5 or later. Run with `-nr` or try it online.

**breakdown**

```
for(
# translate code to 0..7, init $m (memory pointer)
    $p=_.strtr($argv[9],array_flip(array_slice($argv,$m=1,8)));
# loop through code
    ~$c=$p[
    # 1. previous instruction was not 7: increment $i (instruction pointer)
        $i+=$c<7
    ];
    # 3. instructions 0..5: eval
    eval(['$m++','$m--','$$m++','$$m--','echo chr($$m)','$$m=ord(fgetc(STDIN))'][$c].';')
)
    # 2. instructions 6,7:
        for(
        # init $n: instruction 6 and cell is 0: 1, instruction 7: -1, else: 0 or NULL
            $n=$d=[6=>!$$m,-1][$c];
        # loop while $n (bracket count) is truthy
            $n;
        )
            # 2. if bracket, increment / decrement bracket count
            $n+=[6=>1,-1][$p[
            # 1. increment / decrement IP
                $i+=$d
            ]];

```

# Answer
> 1 votes
# CJam, 183 bytes

```
q:Iea):C;:O];{O{_,C<=}#_)O0=,(e&)C>:C}g]:C,{_C=6-We>"M+:M M(\:M;a+aL+:L "S/=~}/];0a3e4*{TC="(+ 1m> ))+ )(+ _W=co );I0ae|(\:I;i+ _W={L{1=T=}=0=:T;}| _W={L{0=T=}=1=:T;}& "S/=~T):TC,<}g;

```

183 bytes of pure, sweet CJam.

This first 8 command-line arguments are the commands, the 9th is the code.

Try it online!

### Ungolfed and commented

```
e# Variables:
e# I  Input
e# C  Code
e# O  Command aliases
e# L  Loop open-close index pairs ([] by default, not set up here)
e# T  Instruction pointer (0 by defualt, not set)

q:I   e# Read the input and store it in I.
ea    e# Read the command-line args.
):C;  e# Remove the last, store it in C, and delete.
:O    e# Store the rest in O.
];    e# And clear everything off the stack.

e# Now we translate the code into numbers for each command:
e# -1 no-op
e# 0  >
e# 1  <
e# 2  +
e# 3  -
e# 4  .
e# 5  ,
e# 6  [
e# 7  ]

{          e# Do:
 O{_,C<=}#  e# Find the index of the alias such that C starts with (or -1 if C doesn't start with a valid command)
 _          e# Copy it
 )          e# Increment it
 O0=,(      e# Get the alias length-1
 e&)        e# Logical AND and increment the result
 C>         e# Slice that many characters from the beginning of C
 :C         e# Store the newly sliced code back into C
}g         e# While (C is not empty)
]:C        e# Save the resulting list of commands back into C

e# Next, we find the pairs of matching loops

,{                         e# For i in C
 _C=                        e# Copy i and push C[i]
 6-We>                      e# max(-1, i-6)
 "M+:M M(\:M;a+aL+:L "S/=~  e# Split this string on spaces, and eval result[max(-1, i-6)]
                            e# For 0 ([), push the index to M (M is a temporarily used list)
                            e# For 1 (]), pop and index from M, pair it with the current index, and add that pair to L
                            e# For -1, do nothing
}/                         e# End for
];                         e# Clear the stack

e# The final step is to interpret

0a3e4*  e# Create a tape containing 30000 0's
{       e# Do
 TC=     e# Get the current instruction

 e# This string contains the commands, space separated, so they can be easily evaled
 "(+ 1m> ))+ )(+ _W=co );I0ae|(\:I;i+ _W={L{1=T=}=0=:T;}| _W={L{0=T=}=1=:T;}& "
 S/=~    e# Split by spaces, get result[command], and eval
 T):T    e# Increment the instruction pointer
 C,<     e# Check if it's less than the length of the C
}g      e# While TOS is truthy
;       e# Delete the tape so it doesn't get implicitly printed

```

---
Tags: code-golf, interpreter, brainfuck, substitution
---


title: Build a Semi-Zigzag

text:
# Question
Title: Build a Semi-Zigzag
You will be given a positive integer `N` as input. Your task is to build a Semi-Zigzag, of `N` sides, each of length `N`. Since it is relatively hard to clearly describe the task, here are some examples:

* `N = 1`:

```
O

```
* `N = 2`:

```
O
 O O

```
* `N = 3`:

```
O       O
 O     O
  O O O

```
* `N = 4`:

```
O           O O O O
 O         O
  O       O
   O O O O

```
* `N = 5`:

```
O               O O O O O
 O             O         O
  O           O           O
   O         O             O
    O O O O O               O

```
* `N = 6`:

```
O                   O O O O O O
 O                 O           O
  O               O             O
   O             O               O
    O           O                 O
     O O O O O O                   O O O O O O

```
* `N = 7`:

```
O                       O O O O O O O                       O
 O                     O             O                     O
  O                   O               O                   O
   O                 O                 O                 O
    O               O                   O               O
     O             O                     O             O
      O O O O O O O                       O O O O O O O

```
* A larger test case with `N = 9`

As you can see, a Semi-Zigzag is made of alternating diagonal and horizontal lines, and it always begins with a top-left to bottom right diagonal line. Take note that the characters on the horizontal lines are separated by a space.

# Rules

* You may choose any non-whitespace *character* instead of `O`, it may even be inconsistent.
* You may output / return the result as a String or as a list of Strings, each representing one *line*.
* You may have a trailing or leading newline.
* **Default Loopholes** apply.
* You can take input and provide output by **any standard mean**.
* If possible, please add a testing link to your submission. I will upvote any answer that shows golfing efforts and has an explanation.
* This is , so the shortest code in bytes ***in every language*** wins!

# Answer
> 10 votes
# Charcoal, 24 bytes

```
ＦＮ«↶§7117ι×⁺#× ﹪ι²⁻Ｉθ¹»#

```

Try it online!

-5 thanks to Neil.

AST:

```
Program
├Ｆ: For
│├Ｎ: Input number
│└Program
│ ├↶: Pivot Left
│ │└§: At index
│ │ ├'7117': String '7117'
│ │ └ι: Identifier ι
│ └Print
│  └×: Product
│   ├⁺: Sum
│   │├'#': String '#'
│   │└×: Product
│   │ ├' ': String ' '
│   │ └﹪: Modulo
│   │  ├ι: Identifier ι
│   │  └2: Number 2
│   └⁻: Difference
│    ├Ｉ: Cast
│    │└θ: Identifier θ
│    └1: Number 1
└Print
 └'#': String '#'

```

# Answer
> 7 votes
# Python 2, ~~157~~ 153 bytes

```
n=input()
o,s=q='O '
def p(k,t=q*n+s*(4*n-6)):print(t*n)[k*~-n:][:n*3/2*~-n+1]
p(2)
for i in range(n-2):p(0,i*s+s+o+s*(4*n-7-2*i)+o+s*(2*n+i-2))
n>1>p(5)

```

Try it online!

* `n*3/2*~-n+1` is the width of each line: ⌊3n/2⌋ · (n−1) + 1 characters.
* The string `q*n+s*(4*n-6)` represents the top and bottom rows. If we repeat it and slice `[2*(n-1):]` we get the top row; if we slice `[5*(n-1):]` we get the bottom row. Hence the definition of `p` and the calls to `p(2)` and `p(5)`. But since we need the repetition and line-length slicing for all other lines anyway, we reuse `p` in the loop.
* The `i*s+s+o+…` is just a boring expression for the middle rows.
* `n>1>p(5)` will short-circuit if `n≯1`, causing `p(5)` to not get evaluated. Hence, it’s shorthand for `if n>1:p(5)`.

# Answer
> 6 votes
# Mathematica, ~~126~~ ~~125~~ ~~121~~ ~~112~~ ~~104~~ ~~89~~ 86 bytes

```
(m=" "&~Array~{#,#^2-#+1};Do[m[[1[i,#,-i][[j~Mod~4]],j#-#+i+1-j]]="X",{j,#},{i,#}];m)&

```
* `#` is the input number for an anonymous function (ended by the final `&`).
* `m=" "&~Array~{#,#^2-#+1};` makes a matrix of space characters of the right size by filling an array of given dimensions `#,#^2-#+1` with the outputs of the constant anonymous function "output a space" `" "&`.
* `Do[foo,{j,#},{i,#}]` is a pair of nested do loops, where `j` ranges from `1` to `#` and inside of that `i` ranges from `1` to `#`.
* `m[[1[i,#,-i][[j~Mod~4]],j#-#+i+1-j]]="X"` sets the the corresponding part of the matrix to be the character `X` based on `j` and `i`. The `-i` uses negative indexing to save bytes from `#-i+1`. (I forgot to write `Mod[j,4]` as `j~Mod~4` in the original version of this code.) Jenny\_mathy pointed out that we can use the modular residue to index into the list directly (rather than using `Switch`) to save 9 bytes, and JungHwan Min pointed out that we didn't need to use `ReplacePart` since we can set a part of an array and that `1[i,#,-i][[j~Mod~4]]` uses the odd behavior and generality of `[[foo]]` to save bytes over `{1,i,#,-i}[[j~Mod~4+1]]`
* Since meta established that a list of characters is a string (as JungHwan Min pointed out) we don't need to map any function across the rows of the matrix of characters since it's already a list of "string"s.

You can test this out in the Wolfram Cloud sandbox by pasting code like the following and hitting Shift+Enter or the numpad Enter:

```
(m=" "&~Array~{#,#^2-#+1};Do[m[[1[i,#,-i][[j~Mod~4]],j#-#+i+1-j]]="X",{j,#},{i,#}];m)&@9//MatrixForm

```

# Answer
> 4 votes
# Mathematica, 179 bytes

```
Rotate[(c=Column)@(t=Table)[{c@(a=Array)[" "~t~#<>(v="o")&,z,0],c@t[t[" ",z-1]<>v,z-1],c@a[t[" ",z-2-#]<>v&,z-1,0],c@t[v,z-Boole[!#~Mod~4<1]-1]}[[i~Mod~4+1]],{i,0,(z=#)-1}],Pi/2]&

```

edit for @JungHwanMin

# Answer
> 4 votes
## C++, ~~321~~ 234 bytes

-87 bytes thanks to Zacharý

```
#include<vector>
#include<string>
auto z(int n){std::vector<std::string>l;l.resize(n,std::string(n*n+n/2*(n-1),32));l[0][0]=79;int i=0,j,o=0;for(;i<n;++i)for(j=1;j<n;++j)l[i%4?i%4-1?i%4-2?0:n-j-1:n-1:j][i*n+j-i+(o+=i%2)]=79;return l;}

```

Returns a vector of strings

# Answer
> 4 votes
# 05AB1E, ~~21~~ ~~20~~ 19 bytes

### Code

Uses the new canvas mode:

```
Fx<)Nè'ONÉúR3212NèΛ

```

Uses the **05AB1E** encoding. Try it online!

### Explanation:

```
F                      # For N in range(0, input)
 x<)                   #   Push the array [input, 2 × input - 1]
    Nè                 #   Retrieve the Nth element
      'ONÉúR           #   Push "O" if N is odd, else "O "
            3212Nè     #   Retrieve the Nth element of 3212
                  Λ    #   Write to canvas

```

For input **6**, this gives the following arguments (in the same order) for the canvas:

```
[<num>, <fill>, <patt>]
[6,     'O',     3]
[11,    'O ',    2]
[6,     'O',     1]
[11,    'O ',    2]
[6,     'O',     3]
[11,    'O ',    2]

```

To explain what the canvas does, we pick the first set of arguments from the list above.

The number **6** determines the *length* of the string that will be written into the canvas. The filler is used to write on the canvas, which in this case is `O`. It cyclically runs through the filler string. The direction of the string is determined by the final argument, the direction. The directions are:

```
7  0  1
 \ | /
6- X -2
 / | \
5  4  3

```

This means that the **3** sets the direction to *south-east*, which can also be tried online.

# Answer
> 2 votes
# SOGL V0.12, 36 bytes

```
╝.H∫2\?.╝}F2%?№@.┌Ο};1w⁄Hh1ž}.4%1>?№

```

Try it Here!

The basic idea is to for each number of the input range choose either adding a diagonal or the horizontal dotted part, in which case it will turn the array around for easier adding on. Explanation:

```
╝                                     get a diagonal from the bottom-left corner with the length of the input - the starting canvas
 .H∫                        }         for each number in the range [1,inp-1] do, pushing counter
    2\?  }                              if it divides by 2, then
       .╝                                 create another diagonal of the input
          F2%                           push counter % 2
             ?     }                    if that [is not 0]
              №                           reverse the current canvas upside down
               @.┌Ο                       get an alternation of spaces and dashes with the dash amount of the input length
                    ;                   get the canvas on top of the stack
                     1w⁄                get its 1st element length
                        H               decrease it
                         h              swap the bottom 2 items - the canvas is now at the bottom and the current addition ontop
                          1             push 1
                           ž            at 1-indexed coordinates [canvasWidth-1, 1] in the canvas insert the current part made by the Ifs
                             .4%1>?   if input%4 > 1
                                   №    reverse the array vertically

```

If the input of 1 wasn't allowed, then `ο.∫2%?.╝}F2\?№@.┌Ο};1w⁄Hh1ž}.4%1>?№` would work too. If random numbers floating around were allowed `.∫2%?.╝}F2\?№@.┌Ο};1w⁄Hh1ž}.4%1>?№` would work too. If I were not lazy and implemented , `}F2%?` could be replaced with  for -4 bytes

# Answer
> 2 votes
# Python 3, ~~228 226 224 215 197~~ 195 bytes

***-11 bytes Thanks to @Mr. Xcoder***

-2 bytes Thanks to @Mr. Xcoder

```
def f(n,s=range):
 x=y=t=c=0;z=[]
 for i in s(n*n-n+2):c+=i%(n-(2<=n))<1;z+=[[x,y]];t=max(t,x);x+=2-c%2;y+=[-1,1][c%4<3]*(c%2)
 return'\n'.join(''.join(' O'[[k,j]in z]for k in s(t))for j in s(n))

```

Try it online!

## Explanation and less-golfed code:

```
def f(n):
 x=y=t=c=0;z=[]                       #initialize everything
 for i in range(n*n-n+2):             #loop n*n-n+2 times which is the numberr of 'o's expected
    c+=i%[~-n,n]<n-1                  #if one cycle has been completed, increase c by 1, if n>1.
    z+=[[x,y]]                        #add [x,y] to z(record the positions of 'o')
    t=max(t,x)                        #trap maximum value of x-coordinate(to be used later while calculatng whole string)
    r=[[2,0],[1,1],[2,0],[1,-1]][c%4] #r gives direction for x and y to move, adjust it as per c i.e. cycles
    x+=r[0];y+=r[1]                   #yield newer values of x and y
 return '\n'.join(''.join(' o'[[k,j]in z]for k in range(t))for j in range(n)) #place space or 'o' accordingly as per the recorded posititons in z

```

# Answer
> 2 votes
# Mathematica, ~~106~~ 87 bytes

```
SparseArray[j=i=1;k=#-1;Array[{j+=Im@i;k∣#&&(i*=I);j,#+1}->"o"&,l=k#+1,0],{#,l}," "]&

```

Returns a `SparseArray` object of `String`s. To visualize the output, you can append `Grid@`. Throws an error for case `1`, but it's safe to ignore.

### Explanation

```
j=i=1

```

Set `i` and `j` to 1.

```
k=#-1

```

Set `k` to input - 1.

```
l=k#+1

```

Set `l` to `k*input + 1`

```
Array[ ..., l= ...,0]

```

Iterate `l` times, starting from `0`, incrementing by `1` each time...

---

```
j+=Im@i

```

Add the imaginary component of `i` to `j`...

```
k∣#&&(i*=I)

```

If the current iteration is divisible by `k`, multiply `i` by the imaginary unit...

```
{... j,#+1}->"o"

```

Create a `Rule` object that changes element at position `{j, current iteration + 1}` to `"o"`

---

```
SparseArray[ ...,{#,l}," "]

```

Create a `SparseArray` object using the generated `Rule` objects, with dimension `{input, l}`, using `" "` as blank.

Try it on Wolfram Sandbox!

# Answer
> 1 votes
# Haskell, 197 bytes

```
a n c=take(2*n)$cycle$c:" "
r i n x y=take(div(3*n)2*(n-1)+1)$(' '<$[1..i])++(cycle$"O "++(a(2*n-i-3)y)++"O "++(a(n+i-2)x))
z n=take n$(r 0 n 'O' ' '):[r i n ' ' ' '|i<-[1..n-2]]++[r(n-1)n ' ' 'O']

```

Try it online!

*Thanks to @Lynn : fixed the spaces between `O`s on horizontal segments of the zigzag, but it costed a lot of bytes!*

Some explanations:

* `r` is a row of the output: it has the `0 y y y y y 0 x x x 0 y ...` format, the number of `x`and `y` depending on the row and the initial `n`
* for the top row, `x='0'`and `y=' '`
* for the middle rows, `x=' '`and `y=' '`
* for the bottom row, `x=' '`and `y='0'`
* `take(div(3*n)2*(n-1)+1)` cuts an infinite row at the right place
* every output has one top row and one bottom row except when `n=1`: `take n` handles this case.

# Answer
> 1 votes
# Python 2, ~~155~~ ~~151~~ ~~146~~ 137 bytes

```
m=input()
n=m-1
r=range(n+2)
for L in zip(*[' '*i+'O'+n*' 'for i in(r+[n,m]*~-n+r[-2::-1]+([m,0]*n)[:-1])*m][:1+3*m/2*n]):print''.join(L)

```

Try it online!

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


title: Secret Message Part 1, Elements

text:
# Question
Title: Secret Message Part 1, Elements
You and your friend want to send each other secret messages. However, because you are conspiracy theorists and think that the government has a quantum computer that can crack any standard encryption. Therefore, you are inventing one of your own. The first step of this is as follows: taking an input string, you check if all the letters can be represented by the symbols for the elements of the periodic table (case insensitive). If they can be, you replace each section with the name of the element the symbol represents. If all letters cannot be replaced in this way, you simply use the original string.

## Your Task:

You are to write a program or function that encodes a message, as outlined previously. Remember that if your program fetches data from an outside source, the size of the outside source must be added to the byte count (this loophole). The elements and symbols used are here:

```
H   Hydrogen
He  Helium
Li  Lithium
Be  Beryllium
B   Boron
C   Carbon
N   Nitrogen
O   Oxygen
F   Fluorine
Ne  Neon
Na  Sodium
Mg  Magnesium
Al  Aluminum
Si  Silicon
P   Phosphorus
S   Sulfur
Cl  Chlorine
Ar  Argon
K   Potassium
Ca  Calcium
Sc  Scandium
Ti  Titanium
V   Vanadium
Cr  Chromium
Mn  Manganese
Fe  Iron
Co  Cobalt
Ni  Nickel
Cu  Copper
Zn  Zinc
Ga  Gallium
Ge  Germanium
As  Arsenic
Se  Selenium
Br  Bromine
Kr  Krypton
Rb  Rubidium
Sr  Strontium
Y   Yttrium
Zr  Zirconium
Nb  Niobium
Mo  Molybdenum
Tc  Technetium
Ru  Ruthenium
Rh  Rhodium
Pd  Palladium
Ag  Silver
Cd  Cadmium
In  Indium
Sn  Tin
Sb  Antimony
Te  Tellurium
I   Iodine
Xe  Xenon
Cs  Cesium
Ba  Barium
La  Lanthanum
Ce  Cerium
Pr  Praseodymium
Nd  Neodymium
Pm  Promethium
Sm  Samarium
Eu  Europium
Gd  Gadolinium
Tb  Terbium
Dy  Dysprosium
Ho  Holmium
Er  Erbium
Tm  Thulium
Yb  Ytterbium
Lu  Lutetium
Hf  Hafnium
Ta  Tantalum
W   Tungsten
Re  Rhenium
Os  Osmium
Ir  Iridium
Pt  Platinum
Au  Gold
Hg  Mercury
Tl  Thallium
Pb  Lead
Bi  Bismuth
Po  Polonium
At  Astatine
Rn  Radon
Fr  Francium
Ra  Radium
Ac  Actinium
Th  Thorium
Pa  Protactinium
U   Uranium
Np  Neptunium
Pu  Plutonium
Am  Americium
Cm  Curium
Bk  Berkelium
Cf  Californium
Es  Einsteinium
Fm  Fermium
Md  Mendelevium
No  Nobelium
Lr  Lawrencium
Rf  Rutherfordium
Db  Dubnium
Sg  Seaborgium
Bh  Bohrium
Hs  Hassium
Mt  Meitnerium
Ds  Darmstadtium
Rg  Roentgenium
Cn  Copernicium
Nh  Nihonium
Fl  Flerovium
Mc  Moscovium
Lv  Livermorium
Ts  Tennessine
Og  Oganesson

```

## Input:

A string to be encoded. You may take this in all caps or lowercase if you wish, as long as you specify that requirement in your answer.

## Output:

The string, encoded as outlined previously if possible.

## Examples:

```
Hi!                --> HydrogenIodine!
This is an example --> This is an example
Neon               --> NeonOxygenNitrogen
Snip               --> SulfurNitrogenIodinePhosphorus OR TinIodinePhosphorus
Nag                --> NitrogenSilver

```

## Scoring:

This is , shortest code in bytes wins!

# Answer
# Mathematica, 404 (239) bytes

```
S="";l=ToLowerCase;e=ElementData;Unprotect[e];a="Abbreviation";n="Name";e[113,a]="Nh";e["Nh",n]="Nihonium";e[115,a]="Mc";e["Mc",n]="Moscovium";e[117,a]="Ts";e["Ts",n]="Tennessine";e[118,a]="Og";e["Og",n]="Oganesson";r=StringReplace;A=Reverse@SortBy[Table[e[j,a],{j,118}],StringLength];If[StringFreeQ[r[l@S,Table[l@A[[j]]->"",{j,118}]],Alphabet[]],r[l@S,Table[l@A[[j]]->Capitalize@e[A[[j]],n],{j,118}]],S]

```

Using Mathematica's built-in database to fetch element names and their abbreviation. Input can be mixed lower and upper case and is stored in the variable `S`. The output is the expression's result, it is not explicitly printed.

The at this time fully working code takes up 404 bytes, as Mathematica's built-in chemical database is a bit behind. `ElementData[118, "Name"]` returns `ununoctium` instead of `oganesson` (the super-heavy elements where only recently properly named, ununoctium was a placeholder name for element 118).
To update `ElementData`, I unprotect it and fix the values for elements Nihonium (113), Moscovium (115), Tennessine (118) and Oganesson (118).

If Mathematica's database were up to date, I would only require 239 bytes.

```
S="";l=ToLowerCase;e=ElementData;r=StringReplace;A=Reverse@SortBy[Table[e[j,"Abbreviation"],{j,118}],StringLength];If[StringFreeQ[r[l@S,Table[l@A[[j]]->"",{j,118}]],Alphabet[]],r[l@S,Table[l@A[[j]]->Capitalize@e[A[[j]],"Name"],{j,118}]],S]

```
> 2 votes

# Answer
## JavaScript (ES6), ~~881~~ 871 bytes

Takes the input string in all caps.

```
s=>(o={},'HEelLIithBEeryllMGagnesCAalcTIitanVanadCRhromGAallGEermanSEelenRBubidSRtrontYttrZRirconTCechnetRUuthenRHhodPDalladCDadmTEellurBAarCEerPRraseodymNDeodymPMromethSMamarEUuropGDadolinTBerbDYysprosERrbTMhulLUutetREhenIRridTLhallFRrancRAadACctinTHhorPArotactinUranAMmericCMurESinsteinFMermMDendelevLRawrencRFutherfordDBubnSGeaborgMTeitnerDSarmstadtRGoentgenFLlerovMCoscovLVivermorHydrogenBoronCarbonNitrogenOxygenFluorineNEeonALluminumPhosphorusSulfurCLhlorineARrgonMNanganeseZNincASrsenicBRromineKRryptonMOolybdenumIodineXEenonLAanthanumTAantalumPTlatinumATstatineRNadonTSennessineOGganessonNAsodiumKpotassiumFEironAGsilverWtungstenAUgoldHGmercury'.split(/([A-Z]+|[a-z]+)/).map((r,i,a)=>i%4-3?0:o[e=a[i-2]]=i>339?r[0].toUpperCase()+r.slice(1):e[0]+r+(i<235?'ium':'')),g=([c,...s],r)=>c?c<'A'|c>'Z'?g(s,r+c):o[c]&&g(s,r+o[c])||o[c+=s.shift()]&&g(s,r+o[c]):r)(s,'')||s

```

### Extended test cases

Because this challenge is also a variant of the exact cover set problem, I've added the following test cases:

* "NA" → "Sodium"
* "NAG" → "N" + "AG" → "NitrogenSilver"
* "NAP" → "NA" + "P" → "SodiumPhosphorus"

```
let f =

s=>(o={},'HEelLIithBEeryllMGagnesCAalcTIitanVanadCRhromGAallGEermanSEelenRBubidSRtrontYttrZRirconTCechnetRUuthenRHhodPDalladCDadmTEellurBAarCEerPRraseodymNDeodymPMromethSMamarEUuropGDadolinTBerbDYysprosERrbTMhulLUutetREhenIRridTLhallFRrancRAadACctinTHhorPArotactinUranAMmericCMurESinsteinFMermMDendelevLRawrencRFutherfordDBubnSGeaborgMTeitnerDSarmstadtRGoentgenFLlerovMCoscovLVivermorHydrogenBoronCarbonNitrogenOxygenFluorineNEeonALluminumPhosphorusSulfurCLhlorineARrgonMNanganeseZNincASrsenicBRromineKRryptonMOolybdenumIodineXEenonLAanthanumTAantalumPTlatinumATstatineRNadonTSennessineOGganessonNAsodiumKpotassiumFEironAGsilverWtungstenAUgoldHGmercury'.split(/([A-Z]+|[a-z]+)/).map((r,i,a)=>i%4-3?0:o[e=a[i-2]]=i>339?r[0].toUpperCase()+r.slice(1):e[0]+r+(i<235?'ium':'')),g=([c,...s],r)=>c?c<'A'|c>'Z'?g(s,r+c):o[c]&&g(s,r+o[c])||o[c+=s.shift()]&&g(s,r+o[c]):r)(s,'')||s

console.log(f('HI!'))
console.log(f('THIS IS AN EXAMPLE'))
console.log(f('NEON'))
console.log(f('SNIP'))
console.log(f('NA'))
console.log(f('NAG'))
console.log(f('NAP'))
```

### How?

**Preliminary optimization**

We ignore the following 26 elements entirely, because they can safely be replaced with two symbols of one character among `BCFHIKNOPSUVWY`:

```
Bh, Bi, Bk, Cf, Cn, Co, Cs, Cu, Hf, Ho, Hs, In, Nb,
Nh, Ni, No, Np, Os, Pb, Po, Pu, Sb, Sc, Si, Sn, Yb

```

**Encoding and decoding the elements**

We use an interlaced list of element symbols in upper case and element names in lower case. Symbols are always stored as-is, while names are shortened according to the following rules:

1. If the first letter of the name matches the first letter of the symbol, we omit it.
2. If the element passes rule #1 and its name ends in "ium", we omit this suffix.

Examples:

* Ag / Silver: "AGsilver"
* K / Potassium: "Kpotassium"
* Zn / Zinc: "ZNinc"
* He / Helium: "HEel"

The 58 elements that trigger both rules are stored at the beginning of the list, followed by the 27 elements that trigger rule #1 only, followed by the 7 elements that do not trigger any rule.

We decode this list to populate the lookup table ***o***, where the keys are the symbols and the values are the decoded element names:

```
"HEelLIith[...]HGmercury"       // encoded list
.split(/([A-Z]+|[a-z]+)/)       // split it by character case, which gives:
                                // [ '', 'HE', '', 'el', '', 'LI', '', 'ith', etc. ]
.map((r, i, a) =>               // for each item 'r' at position 'i' in this array 'a':
  i % 4 - 3 ?                   //   if we're not currently pointing to an element name:
    0                           //     do nothing
  :                             //   else:
    o[e = a[i - 2]] =           //     save o[e], where e = element symbol
      i > 339 ?                 //     if symbol/name first letters do not match:
        r[0].toUpperCase() +    //       we need to capitalize the first letter of the name
        r.slice(1)              //       and keep the rest unchanged
      :                         //     else:
        e[0] +                  //       we use the first letter of the symbol,
        r +                     //       followed by the name,
        (i < 235 ? 'ium' : '')  //       followed by the 'ium' suffix when appropriate
)                               // end of map()

```

**Covering the input string**

We try to replace all upper-case letters in the input string with element symbols, using the recursive function ***g()*** which eventually returns a replacement string or *undefined* if no exact cover is found:

```
g = ([c,                                  // c = next character
         ...s],                           // s = array of remaining characters
                r) =>                     // r = replacement string
  c ?                                     // if there's still at least one character:
    c < 'A' | c > 'Z' ?                   //   if it's not an upper-case letter:
      g(s, r + c)                         //     just append it to 'r'
    :                                     //   else:
      o[c] && g(s, r + o[c]) ||           //     try to find a symbol matching 'c'
      o[c += s.shift()] && g(s, r + o[c]) //     or a symbol matching 'c' + the next char.
  :                                       // else:
    r                                     //   success: return 'r'

```
> 6 votes

# Answer
# Javascript, ~~1487~~ ~~1351~~ ~~1246~~ ~~1170~~ ~~1243~~ 1245 bytes

*saved 234 bytes thanks to @musicman523*

*saved 174 bytes thanks to @ovs*

*saved 7 bytes thanks to @Shaggy*

*added 75 bytes to make it work for 2 letter elements*

```
b=>~((o=0,d=Array.from([...b].map((u,i,a)=>(h=e=>("he0Hel2h0Hydrogen1li0Lith2be0Beryll2b0Boron1c0Carbon1n0Nitrogen1o0Oxygen1f0Fluorine1ne0Neon1na0Sod2mg0Magnes2al0Aluminum1p0Phosphorus1s0Sulfur1cl0Chlorine1ar0Argon1k0Potass2ca0Calc2ti0Titan2v0Vanad2cr0Chrom2mn0Manganese1fe0Iron1ni0Nickel1cu0Copper1zn0Zinc1ga0Gall2ge0German2as0Arsenic1se0Selen2br0Bromine1kr0Krypton1rb0Rubid2sr0Stront2y0Yttr2zr0Zircon2nb0Niob2mo0Molybdenum1tc0Technet2ru0Ruthen2rh0Rhod2pd0Pallad2ag0Silver1cd0Cadm2in0Ind2te0Tellur2i0Iodine1xe0Xenon1cs0Ces2ba0Bar2la0Lanthanum1ce0Cer2pr0Praseodym2nd0Neodym2pm0Prometh2sm0Samar2eu0Europ2gd0Gadolin2tb0Terb2dy0Dyspros2ho0Holm2er0Erb2tm0Thul2lu0Lutet2hf0Hafn2ta0Tantalum1w0Tungsten1re0Rhen2ir0Irid2pt0Platinum1au0Gold1hg0Mercury1tl0Thall2at0Astatine1rn0Radon1fr0Franc2ra0Rad2ac0Actin2th0Thor2pa0Protactin2u0Uran2np0Neptun2pu0Pluton2am0Americ2cm0Cur2bk0Berkel2cf0Californ2es0Einstein2fm0Ferm2md0Mendelev2no0Nobel2lr0Lawrenc2rf0Rutherford2db0Dubn2sg0Seaborg2bh0Bohr2hs0Hass2mt0Meitner2ds0Darmstadt2rg0Roentgen2nh0Nihon2fl0Flerov2mc0Moscov2lv0Livermor2ts0Tennessine1og0Oganesson".replace(/2/g,'ium1').split(1).map(a=>a.split(0)).find(a=>a[0]==e)||[,0])[1],o?(o=0,''):((p=a[i+1])&&(o=1,h(u+p))||(o=0,h(u)))))).join``).search(0))?b:d

```

(Slightly more) readable version:

```
b=>~((o=0,d=Array.from([...b].map((u,i,a)=>(h=e=>(
"he0Hel2h0Hydrogen1li0Lith2be0Beryll2b0Boron1c0Carbon1n0Nitrogen1o0Oxygen1f0Flu
orine1ne0Neon1na0Sod2mg0Magnes2al0Aluminum1p0Phosphorus1s0Sulfur1cl0Chlorine1ar0
Argon1k0Potass2ca0Calc2ti0Titan2v0Vanad2cr0Chrom2mn0Manganese1fe0Iron1ni0Nickel1
cu0Copper1zn0Zinc1ga0Gall2ge0German2as0Arsenic1se0Selen2br0Bromine1kr0Krypton1rb
0Rubid2sr0Stront2y0Yttr2zr0Zircon2nb0Niob2mo0Molybdenum1tc0Technet2ru0Ruthen2rh0
Rhod2pd0Pallad2ag0Silver1cd0Cadm2in0Ind2te0Tellur2i0Iodine1xe0Xenon1cs0Ces2ba0Ba
r2la0Lanthanum1ce0Cer2pr0Praseodym2nd0Neodym2pm0Prometh2sm0Samar2eu0Europ2gd0Gad
olin2tb0Terb2dy0Dyspros2ho0Holm2er0Erb2tm0Thul2lu0Lutet2hf0Hafn2ta0Tantalum1w0Tu
ngsten1re0Rhen2ir0Irid2pt0Platinum1au0Gold1hg0Mercury1tl0Thall2at0Astatine1rn0Ra
don1fr0Franc2ra0Rad2ac0Actin2th0Thor2pa0Protactin2u0Uran2np0Neptun2pu0Pluton2am0
Americ2cm0Cur2bk0Berkel2cf0Californ2es0Einstein2fm0Ferm2md0Mendelev2no0Nobel2lr0
Lawrenc2rf0Rutherford2db0Dubn2sg0Seaborg2bh0Bohr2hs0Hass2mt0Meitner2ds0Darmstadt
2rg0Roentgen2nh0Nihon2fl0Flerov2mc0Moscov2lv0Livermor2ts0Tennessine1og0Oganesson
".replace(/2/g,'ium1').split(1).map(a=>a.split(0)).find(a=>a[0]==e)||[,0])[1],o?
(o=0,''):((p=a[i+1])&&(o=1,h(u+p))||(o=0,h(u)))))).join``).search(0))?b:d

```
> 2 votes

---
Tags: code-golf, string, kolmogorov-complexity, encryption
---


title: Champernowne up to me

text:
# Question
Title: Champernowne up to me
Inspired by this question.

Champernowne's constant is an infinite decimal number that consists of "0." followed by all natural numbers concatenated together. It begins like so: `0.123456781011121314151617181920212223242526272829303132333435363738394041424344454647484950`, etc. The digits of Chamernowne's constant are sequence A033307 in the OEIS.

## Your Task:

Write a program or function that, when given an integer as input, outputs/returns Champernowne's constant up to the first occurance of the input. For example, if the input is `13`, you should output `0.12345678910111213`. If you wish, for inputs greater than 0, you may drop the leading "0." in your output.

## Input:

An integer, or a string containing only numbers.

## Output:

Champernowne's constant up to the first occurance of the input.

## Test Cases:

```
0   -> 0
1   -> 0.1 OR 1
14  -> 0.1234567891011121314 OR 1234567891011121314
91  -> 0.1234567891 OR 1234567891
12  -> 0.12 OR 12
101 -> 0.123456789101 OR 123456789101

```

## Scoring:

This is , lowest score in bytes wins!

# Answer
# 05AB1E, 6 bytes

### Code

```
LJ¹¡н«

```

Uses the **05AB1E** encoding. Try it online!

### Explanation

```
L         # Create the range [1, 2, ..., input]
 J        # Join into a single string
  ¹¡      # Split at occurences of the input
    н     # Take the first element
     «    # Append the input to the first element and implicitly output

```
> 2 votes

# Answer
# Python 3, ~~70~~ ~~63~~ 61 bytes

*A bunch of bytes removed thanks to @Rod, and some more thanks to @WheatWizard*

```
lambda x:''.join(map(str,range(1,x))).split(str(x))[0]+str(x)

```

Try it online!
> 2 votes

# Answer
# MATL, ~~20~~ ~~15~~ 14 bytes

```
U:VXzG&Yb1X)Gh

```

Takes the input as a string. Try it online!

### Explanation

```
U      % Implicitly input a string. Convert to number
:      % Range from 1 to that
V      % Convert to string. Includes spaces as separators
Xz     % Remove spaces
G      % Push input again
&Yb    % Split at that. Gives a cell array
1X)    % Get contents of the first cell
G      % Push input again
h      % Concatenate horizontally. Implicitly display

```
> 1 votes

# Answer
# Haskell, ~~82~~ ~~73~~ 55 bytes

```
x!b|or$zipWith(==)x b=x
x!(a:b)=a:x!b
(!(show=<<[1..]))

```

Try it online!

## Explanation

First we define `!`. `x!b` truncates `b` to the first appearance of `x`. It does this by checking if `b` starts with `x` (`or$zipWith(==)x b`) returning `x` if it does and moving one down the string otherwise. Then we define our main function. Our main function is a point-free function that takes the constant (`show=<<[1..]`) and truncates it to the first appearance of `x`. This takes `x` as a string.
> 1 votes

# Answer
# Pyth, ~~11~~ 8 bytes

```
+hcjkSQ`

```

Try it online! or run a Test Suite.

Simply creates the constant (`jkSQ`) and then prints the constant up to the input (`c ... ``) followed by the input (`+ ...`).
> 1 votes

# Answer
# Mathematica, 111 bytes

```
(m=Min@SequencePosition[s=Flatten[IntegerDigits/@Range[0,#]],t=IntegerDigits@#];FromDigits@Join[s[[;;m-1]],t])&

```
> 1 votes

---
Tags: code-golf, number, kolmogorov-complexity
---


title: Efficient Robot Movement

text:
# Question
Title: Efficient Robot Movement
> Disclaimer: The story told within this question is entirely fictional, and invented solely for the purpose of providing an intro.

My boss has gotten a new toy robot, and he wants me to help program it. He wants to be able to enter simple arrow instructions to get it to move. These instructions are: ^ (for move forward) \< (for turn left), and \> (for turn right). However, now that I've programmed the robot, he wants additional functionality. He wants me to transform any sequence of arrows he inputs, so that rather than having the robot take the path indicated, it moves to the desired location, indicated by the place it would end up if it had taken the inputted path, as efficiently as possible. I appeal to you, the members of PP&CG, to help me with this task.

## Your Task:

Write a program or function to convert a string made up of arrows into a string that will get to the location indicated by the input as quickly as possible. Turning takes exactly as long as moving backwards or forwards.

## Input:

A string of arrows, as indicated above. If you wish, different characters may be substituted for the arrows, but be sure to include the fact that you do so in your answer. All test cases use the arrows normally.

## Output:

A string of arrows (or your equivalent characters), that take the robot to the desired destination as efficiently as possible.

## Test Cases:

Note that the solutions offered are only possibilities, and that other solutions may be valid.

```
>^<<^^>^^    -> ^^<^
^^^^>^^^^    -> ^^^^>^^^^
>>>^^^^^^    -> <^^^^^^
>^>^>^>^     -> (empty string)
^<^^<^^<^^^^ -> >^^>^

```

## Scoring:

The robot's memory is limited, so your program must have the lowest byte count possible.

# Answer
> 10 votes
# Retina, ~~103~~ ~~74~~ 71 bytes

```
<
>>>
+`(>(\^*>){3})\^
^$1
+`\^(>\^*>)\^
$1
>>(\^*)>(\^+)
<$2<$1
<?>*$

```

Try it online! Link includes test cases. Explanation:

```
<
>>>

```

Turn left turns into triple right turns.

```
+`(>(\^*>){3})\^
^$1

```

Reduce all turns modulo 4.

```
+`\^(>\^*>)\^
$1

```

Cancel out movements in opposite directions.

```
>>(\^*)>(\^+)
<$2<$1

```

Turn a triple right turn back into a left turn. This also handles the case of `>>^>^` which needs to become `<^<^`.

```
<?>*$

```

Delete unnecessary trailing turns.

# Answer
> 6 votes
# Mathematica, 135 bytes

```
{a="^"~Table~Ramp@#&;a@#,s=If[#2>0,">","<"],a@Abs@#2,If[#<0,s,""],a@-#}<>""&@@ReIm[j=0;i=1;Switch[#,">",i*=I,"<",i/=I,"^",j+=i]&/@#;j]&

```

Takes a `List` of strings as input.

### Explanation

```
j=0;i=1

```

Set `j` to 0, and set `i` to 1.

```
/@#

```

For each character in input...

```
Switch[#,">",i*=I,"<",i/=I,"^",j+=i]

```

If the character is `>`, multiply `i` by the imaginary unit. If the character is `>`, divide `i` by the imaginary unit. If the character is `^`, add `i` to `j`.

```
ReIm[ ... ;j]

```

Take the real and imaginary parts of `j`. This gives the Cartesian coordinate of the robot.

```
... &@@

```

Apply the following to this result:

---

```
a="^"~Table~Ramp@#&;

```

Set `a` to a function that generates a string with `(input)` or `0` character `^`s, whichever is larger.

```
{ ... }

```

A `List` consisting of...

```
a@#

```

`a` applied to the first input (real part of `j`)

```
s=If[#2>0,">","<"]

```

If the second input (imaginary part of `j`) is larger than `0`, `>`. Otherwise, `<`. Set `s` to the resulting character.

```
a@Abs@#2

```

`a` applied to the absolute value of the second input.

```
If[#<0,s,""]

```

If the first input is less than 0, `s`. Otherwise, empty string.

```
a@-#

```

Apply `a` to the input times negative one.

```
... <>""

```

Join the strings.

# Answer
> 2 votes
## Mathematica 119 Bytes

JungHwan's final position to path code was shorter than mine, so using that. I think there is probably an even shorter way to do this...

I use the built-in `AnglePath` function to decide the final position. I also define the symbols L, F, and R for "\<", "^" and "\>", to save a few quote characters.

```
L={0,Pi/2};R=-L;F={1,0};{a="F"~Table~Ramp@#&;a@#,s=If[#2>0,"L","R"],a@Abs@#2,If[#<0,s,""],a@-#}<>""&@@Last@AnglePath@#&

```

Usage:

```
%@{R,F,L,L,F,F,R,F,F}

```

Output:

```
FFLF

```

# Answer
> 2 votes
# Ruby, 130 bytes

```
->s{w,d=0,1;s.bytes{|b|b>93?w+=d:d*=1i*(b<=>61)};r,c=w.rect;[w=(d=">><"[c<=>0])+?^*c.abs,?^*r.abs+w,w+d+?^*r.abs][r<=>0].chomp ?>}

```

### How it works

```
->s{
    # We start from (0,0i), direction is +1
    w,d=0,1

    s.bytes{|b|
        # If it's ASCII 94, go one step forward,
        # else multiply direction by +i or -i
        b>93?w+=d:d*=1i*(b<=>61)
    }

    # Get the rectangular representation of the result
    r,c=w.rect

    # Now, create 2 strings of "^" (call them x and y) for horizontal and vertical moves
    # And a single ">" or "<" (call it d) for the direction change
    # If x>0, output x+d+y
    # If x==0, output d+y
    # If x>0, output d+y+d+x
    [w=(d=">><"[c<=>0])+?^*c.abs,?^*r.abs+w,w+d+?^*r.abs][r<=>0]

    #If y==0 we get an extra ">" sometimes
    .chomp ?>
}

```

Try it online!

# Answer
> 2 votes
# J, 90 bytes

## solution

```
t=.{&' ><'@*
g=.'^'#~|
(t,g@{.,t@-@(*/),g@{:`g@{:,t@{.,g@|@{.@.(0<:{:))@+.@(+/)@(=&1*j.**/\)

```

## explanation

there's a neat trick using complex numbers (multiplying by *i* is a 90 degree left rotation, and *-i* gives you a right one).

so we take our input as complex numbers: a 1 represents "walk forward" and *i* / *-i* represent left and right turns.

the final position is calculated effortlessly with this representation. Note this is the first (rightmost) part of my final expression above:

```
(+/)@(=&1*j.**/\)

```

That short line above is what solves the problem. Everything else is just figuring out how to format the answer, and could surely be golfed down significantly more.

To understand the short line above, note that `*/\` (the scan of partial products) gives you list of *the positions you are facing* at each index in the input: *i* is north, 1 and -1 are east and west, and *-i* is south. But since we start facing north, we have to multiply all of those by *i* which, in J, is represented by `j.` (chew on that sentence for a moment).

We only actually "move" when the original input is 1, so we then multiply that result elementwise by the boolean array which is 1 where the original input is 1 and 0 otherwise: `=&1*`. The result of *that* multiplication is an array of "directional steps". Our final position is simply the sum of those steps: `+/`

## testing

Unfortunately I can't get this working in TIO for some reason, but pasting the following into J console will verify that it works:

```
t=.{&' ><'@*
g=.'^'#~|
f=.(t,g@{.,t@-@(*/),g@{:`g@{:,t@{.,g@|@{.@.(0<:{:))@+.@(+/)@(=&1*j.**/\)

NB. test cases
NB. format input as complex numbers
convert=. {&0j1 0j_1 1@:('<>^'&i.)

s=. '^<^^<^^<^^^^'  NB. >^^>^
echo f convert s
s=. '>^<<^^>^^'     NB. ^^<^
echo f convert s
s=. '^^^^>^^^^'     NB. ^^^^>^^^^
echo f convert s
s=. '>>>^^^^^^'     NB. <^^^^^^
echo f convert s
s=. '>^>^>^>^'      NB. empty string
echo f convert s

```

# Answer
> 1 votes
# C# (.NET Core), 349 bytes

```
n=>{int a=0,b=0,x=0,y=1,t=0,j=0,k=0,w,e,r;var p="";foreach(var c in n){if(c==62){t=x;x=y;y=-t;}if(c<61){t=x;x=-y;y=t;}if(c>63){a+=x;b+=y;}}while(a!=j|b!=k){w=0;e=a-j;r=b-k;if(r>=e&r>=-e){w=b-k;k+=w;}else if(r<=e&r<=-e){p+=">>";w=k-b;k-=w;}else if(r>=e&r<=-e){p+="<";w=j-a;j-=w;}else if(r<=e&r>=-e){p+=">";w=a-j;j+=w;}p+=new string('^',w);}return p;}

```

Try it online!

Takes a string as an input and outputs the shortest path that the input would take.

---

**Ungolfed & Commented**

```
n =>
{
    // First, calculate the route that the robot is going to take, represented by xy
    int a = 0, b = 0; // The current coordinates (a=x, b=y)
    int x = 0, y = 1; // The movement vector
    int t = 0; // A temp variable
    var p = ""; // The path we are going to return
    // Calculate the path the robot is going to take by input
    foreach (var c in n)
    {
        if (c == '>') { t = x; x = y; y = -t; } // Turn movement vector right
        if (c == '<') { t = x; x = -y; y = t; } //                      left
        if (c == '^') { a += x; b += y; }       // Move forward
    }
    int j = 0, k = 0; // The new movement coordinates (j=x,k=y)
    // While the target position is not reached, move the robot
    while (a != j | b != k)
    {
        int w = 0; // The forward variable, counting how many times we have to go forward
        int e = a - j, r = b - k; // The target position minus the current position (e=x,r=y)
        if (r >= e & r >= -e) { w = b - k; k += w; } // Up
        else if (r <= e & r <= -e) { p += ">>"; w = k - b; k -= w; } // Down
        else if (r >= e & r <= -e) { p += "<"; w = j - a; j -= w; } // Left
        else if (r <= e & r >= -e) { p += ">"; w = a - j; j += w; } // Right
        p += new string('^', w);
    }
    // Return the final path
    return p;
}

```

# Answer
> 1 votes
# JavaScript (Node.js), 187 bytes

```
s=>{x=y=t=0;r=x=>"^".repeat(x<0?-x:x);for(c of s){t-=b=c<">"||-(c<"^");if(!b)[z=>++y,z=>++x,z=>--y,z=>--x][t&3]()}t=x<0?"<":">";return (y>0?r(y):"")+(x?t+r(x):"")+(y<0?(x?t:t+t)+r(y):"")}

```

Try it online!

Golfed version with whitespace

**-14 bytes** by @Neil

---

### Ungolfed:

```
s=>{
  // convert turns to up/down/left/right movements to final destination
  let directions = [
    z=>++y, // up
    z=>++x, // right
    z=>--y, // down
    z=>--x  // left
  ];
  let x = y = direction = 0;
  for(c of s){
    let relativeDirection = "<^>".indexOf(c)-1; // relative turn offset: -1 = left, 1 = right
    direction += relativeDirection;
    if(direction<0){direction+=4} // make sure direction%4 > 0
    if(c==="^"){directions[direction%4]()} // do the movement if going forwards
  }
  // convert destination back to turns
  // the most efficient output has up before left/right before down
  let absoluteRepeat = num => "^".repeat(Math.abs(num));
  let turn = x<0 ? "<" : ">";
  let outp = "";
  if (y>0) { outp += absoluteRepeat(y) } // handle up before left/right
  if (x) { outp+=turn+absoluteRepeat(x) } // handle left/right
  if (y<0) { outp += (outp?turn:turn+turn)+absoluteRepeat(y)) } // handle down (including w/o left/right)
  return outp;
}

```

# Answer
> 1 votes
# Python 2, ~~174~~ ~~169~~ 165 bytes

Edit 1: -5 bytes by allowing the direction to be outside the range 0-3, and removing whitespace.

Edit 2: -4 bytes by changing input to (1, 2, 3) instead of (\<, ^, \>) since the OP allowed it, as well as changing my coordinate system to allow me to reduce my distance calculation.

```
n,d=[0,0],0
for c in input():exec'd-=1 n[d%2]+=(-1)**(d/2%2) d+=1'.split()[ord(c)-49]
print'2'*n[0]+'13'[n[1]>0]*any(n)+'2'*abs(n[1])+'13'[n[1]>0]*(n[0]<0)+'2'*-n[0]

```

Try it online!

Determines final coordinates via the dictionary's values being executed, then just prints the direct path to the end goal.

# Answer
> 0 votes
# Perl 5, 185 + 1 (-p) = 186 bytes

```
/</?$d--:/>/?$d++:/\^/?$m[$d%4]++:0for/./g;$y=$m[0]-$m[2];$x=$m[1]-$m[3];$q='^'x abs$x;$_=A.$q.B.('^'x-$y);$x<0?y/AB/</:$x?y/AB/>/:0;$_=('^'x$y).($x<0?'<':$x>0?'>':'').$q if$y>0;y/AB//d

```

Try it online!

# Answer
> 0 votes
**JavaScript (document.getElementById() kind), 343 chars**

```
function b(s){s=s.split('');c=[0,0];r=0;p='';w='<';e='>';n='^';for(i in s){r+=s[i]==e?.5:s[i]==w?-.5:0;r=r>1?-.5:r<-.5?1:r;c[1-Math.ceil(Math.abs(r%1))]+=s[i]==n?r>0?1:-1:0;}x=c[0];y=c[1];j=x<0?-x:x;k=y<0?-y:y;f=function(a){p+=a==j?x<0?w:x>0?e:'':j>k?y<0?w:y>0?e:'':y>0?e+e:'';for(i=0;i<a;i++){p+=n}};if(j>k){f(j);f(k)}else{f(k);f(j)}alert(p)}

```

expanded:

```
function b(s){

s = s.split('');
c = [0, 0];
r = 0;
p = '';
w = '<';
e = '>';
n = '^';

for(i in s){

    r += s[i] == e ? .5 : s[i] == w ? -.5 : 0;
    r = r > 1 ? -.5 : r < -.5 ? 1 : r;

    c[1 - Math.ceil( Math.abs( r%1 ) )] += s[i] == n ? r > 0 ? 1 : -1 : 0;

}

x = c[0];
y = c[1];
j = x < 0 ? -x : x;
k = y < 0 ? -y : y;

f = function(a){

    p += a == j ? x < 0 ? w : x > 0 ? e : '' : j > k ? y < 0 ? w : y > 0 ? e : '' : y > 0 ? e+e : '';

    for( i = 0; i < a; i++){
        p += n
    }

};

if( j>k ){

    f(j);
    f(k)

} else {

    f(k);
    f(j)

}

alert(p)

```

}

Usage:

```
b('^<^^<^^<^^^^')

```

alerts: `>^^>^`

A robot with reverse would have been useful.

---
Tags: code-golf, string, optimized-output
---


title: Floor Planning!

text:
# Question
Title: Floor Planning!
> Disclaimer: The story told within this question is entirely fictional, and invented solely for the purpose of providing an intro.

I have a friend who is an architect, and, after explaining the concept of code-golf and this site to him, he said that I should code something actually useful for a change. I asked him what he would consider useful, and, being an architect, he replied that he would enjoy having a floor planner that gave him all possible arrangements for rooms of certain sizes within a house of a certain size. I thought I would prove that code-golf wasn't useless after all, and give him this program in the smallest number of bytes possible.

## Your Task:

Write a program or function that, when given an array D containing the dimensions of the entire house, and a second array R containing the dimensions of the interior rooms, output as ASCII art, all possible configurations of the rooms inside the house.

All rooms and the exterior walls of the house should be formed as standard ASCII boxes, using the | symbol for vertical walls, the - symbol as horizontal walls, and the + symbol for corners. For example, a house with the dimensions \[4,4\] will look like:

```
+----+
|    |
|    |
|    |
|    |
+----+

```

As you can see, corners do not count as part of a set of dimensions. The number of - or | characters forming a side should equal the number given in the dimensions. Rooms may share walls, or share walls with the house. A room may not contain smaller rooms within itself.

For example, the configuration

```
+--+---+-+
|  |   | |
|  |   | |
+--+---+ |
|        |
|        |
+--------+

```

is valid for D=\[5,8\], and R=\[\[2,2\],\[2,3\]\].

## Input:

Two arrays, one of which contains two integers, the dimensions for the house, and the other of which contains a series of arrays containing the dimensions for rooms.

## Output:

Either an array of all possible houses as strings, or a string containing all possible houses, delimited in some consistent way. Note that rotations of the exact same configuration should only be counted once.

## Test Cases:

```
D     R                   ->   Output

[4,3] [[2,1],[4,1]]       -> +-+-+ +-+-+ +-+-+  Note that though there is an option to switch which side the [2,1] room and the [4,1] room are on, doing so would merely be rotating the house by 180 degrees, and therefore these possibilities do not count.
                             | | | +-+ | | | |
                             +-+ | | | | | | |
                             | | | | | | +-+ |
                             | | | +-+ | | | |
                             +-+-+ +-+-+ +-+-+

[4,7] [[3,1],[4,2],[2,2]  -> +----+--+ +----+--+ +----+--+ +----+--+  There are some more possiblities I didn't feel like adding, but it's the same four again, just with the [4,2] and the [2,2] room switched.
                             |    |  | |    |  | |    |  | |    |  |
                             |    |  | |    |  | |    |  | |    |  |
                             +---++--+ +--+-+-++ +-+--++-+ ++---+--+
                             |   |   | |  |   || | |   | | ||   |  |
                             +---+---+ +--+---++ +-+---+-+ ++---+--+

```

## Scoring:

This is , lowest score in bytes wins!

# Answer
# Python 2, ~~625~~ ~~607~~ ~~602~~ ~~563~~ 551 bytes

1. -5 bytes thanks to Mr.Xcoder.
2. -12 bytes when avoiding deep-copying.
3. -39 bytes with some list simplifications.

```
r,z=range,len
L,C=D;p,q,v,w=['+'],['|'],'*',' '
H=[p+['-']*C+p]
P=[[e[:]for e in H+[q+[w]*C+q]*L+H]]
def g(M,x,y,N):
 m=[e[:]for e in M]
 try:
  for i in r(z(N)):
   for j in r(z(N[0])):
	if v==N[i][j]and w!=M[x+i][y+j]:return[]
	m[x+i][y+j]=m[x+i][y+j]in[w,v,N[i][j]]and N[i][j]or'+'
 except:return[]
 return m
for l,c in R:
 H=[p+['-']*c+p]
 P=[g(U,x,y,[e[:]for e in H+[q+[v]*c+q]*l+H])for U in P for x in r(L+2)for y in r(C+2)]
F=[]
for m in P:
 if[e[::-1]for e in m[::-1]]not in F:F+=[m]
for m in F:
 print
 for e in m:print''.join(e).replace(v,w)

```

Try it online!

**Some explanations** It is a greedy approach:

1. Find all positions where the first room can be allocated
2. Find all possible positions where the next room can be allocated from the remaining free space of the house, and so on for the other rooms.
3. If the last room was successfully allocated the code output the configuration if it is not a 180°-rotation of a previous configuration.
> 2 votes

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


title: Fill in the path

text:
# Question
Title: Fill in the path
Write a program that fills in the paths of a grid of characters (ASCII 20-7E) according to the following rules.

The path is governed by eight directional characters: `-`, `|`, `/`, `\`, `&`, `@`, `%`, and `*`, as specified in the table below. The direction of the path will change when it reaches one of the eight above characters. Note that the direction the pointer is moving will always be on a line, forming an angle to the x-axis with radian measure `kπ/4` for integer `k`.

```
-       Move right
|       Move down
/       Move up/right
\       Move down/right
&       Move left
@       Move up
%       Move down/left
*       Move up/left

```

The program starts at the top left of the grid, which is either `-`, `\`, or `|` and the pointer will move in the direction specified.

The objective of the program is to draw the path that the program takes by filling in whitespace according to the direction that the program is traveling. Any whitespace the pointer encounters is filled in, but if the pointer encounters a character not described above, the character is ignored (or put on the stack, if you choose to implement in the bonus).

The program ends when the pointer reaches the edge of the initial "box" the grid was in without hitting another directional character. This initial box does not contain any blank lines on the perimeter of the grid.

It should be noted that a specific point on the grid may change between the beginning and end of the program. For example, if the initial grid is `- &`, then by the time the pointer reaches `&`, the grid will be `--&`. Then the pointer will move one to the left, encounter `-`, and move to the right. It will not encounter an empty space, as the original grid suggests.

One of the things that might happen with this program is the appearance of infinite loops. Trivially, `-&` would be an infinite loop if the program were allowed to run indefinitely.\` To counter this, your program must terminate within a reasonable amount of time.

The input to the program is a set of characters with a `-`, `\`, or `|` as the first character in the first line. There cannot be any trailing or leading newlines.

*Sample input*

```
-    h     %
|  &(   &f   |
 #
      r @  )
5

```

*Sample output*

```
-----h-----%
|&&&(&&&&f%  |
|#      @%
|     r @  )
5

```

---

**Bonus**

If your program prints the non-directional characters the pointer encounters separated from the modified grid by a newline, multiply your byte count by 0.9.

---

This is code golf, so standard rules apply. Shortest code in bytes wins.

# Answer
# Python 2, 347\*.9 = 312.3 bytes

```
def R(I):
 i=x=y=F=V=0;h=len(I);w=max([len(j)for j in I]);I,m,n,E,e,C=[[k for k in j.ljust(w)]for j in I],-1,"","-|/\\&@%*","10011m11m00mm1mm",""
 while 0<=x<w!=0<=y<h!=len(I)**4>i:
	if I[y][x]==" ":I[y][x]=C
	c=I[y][x]
	if c in E:H=2*E.index(c);exec"F,V="+e[H]+","+e[H+1];C=c
	elif c!=" ":n+=c
	x+=F;y+=V;i+=1
 for i in I:print"".join(i)
 print n

```

Try it online!

To comply with standard rules, a function is defined. The function's input is a list of strings representing the input (see the tio.run footer). Non-directional characters are printed, program terminates after a lot of steps (to halt on inputs like `-&`).
> 1 votes

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


title: Superior Highly Composite Numbers

text:
# Question
Title: Superior Highly Composite Numbers
A superior highly composite number is an integer where the ratio of its count of divisors to some power of the number is as high as possible. Expressing this as a formula:

Let d(n) be the number of divisors of n, including the number itself. For a given integer n, if there exists a number e such that d(n)/n^e is greater than or equal to d(k)/k^e for every integer k, then n is a highly composite number.

For more, see Superior highly composite number at Wikipedia, or A002201 at OEIS.

Here are the initial values:

```
2, 6, 12, 60, 120, 360, 2520, 5040, 55440, 720720, 1441440, 4324320, 21621600, 367567200, 6983776800, 13967553600, 321253732800, 2248776129600, 65214507758400, 195643523275200, 6064949221531200

```

Your challenge is to take an index n, and output the nth number in this sequence.

You may use 0 or 1 indexing, and you may make a program which is only correct up to the limits of your language's data type(s), as long as it can handle the first 10 values at a minimum.

This is code golf. Standard loopholes apply.

# Answer
> 3 votes
# Mathematica, 277 bytes

```
(A=AppendTo;p[f_]:=Module[{p=f[[1]],k=f[[2]]},N[Log[(k+2)/(k+1)]/Log[p]]];m=#;f={{2,1},{3,0}};o=1;l={2};x=Table[p[f[[i]]],{i,o+1}];For[n=2,n<=m,n++,i=Position[x,Max[x]][[1,1]];A[l,f[[i,1]]];f[[i,2]]++;If[i>o,o++;A[f,{Prime[i+1],0}];A[x,p[f[[-1]]]]];x[[i]]=p[f[[i]]]];Times@@l)&

```

input

> \[21\]

output

> 6064949221531200

input

> \[50\]

output

> 247899128073275948560051200231228551175691632580942972608000

---
Tags: code-golf, math, sequence
---