title: HyperNeutrino is back!

text:
# Question
Title: HyperNeutrino is back!
Today, *@HyperNeutrino* succeeded merging his two accounts, and finally got the reputation he lost back. Now, it's time to celebrate! Your task is to output this exact text:

```
                /\
               /  \
              /    \
             /      \
            /        \
           /          \
          /            \
         /              \
        /                \
       /                  \
      /                    \
     /                      \
    /                        \
   /                          \
  /                            \
 /                              \
/                                \
|                                |
|                                |
|  @HyperNeutrino Welcome back!  |
|                                |
|                                |
\                                /
 \                              /
  \                            /
   \                          /
    \                        /
     \                      /
      \                    /
       \                  /
        \                /
         \              /
          \            /
           \          /
            \        /
             \      /
              \    /
               \  /
                \/

```

## Rules:

* Your program *must not* take input.
* The output must be exactly as shown above.
* Trailing and leading spaces / newlines are allowed.
* Defaults Loopholes apply.
* You can provide output by any standard method.
* This is a celebration, hence the shortest code in each language wins! Have fun!

# Answer
# , 64 bytes

```
i/\
\/16ñH>GMÙXppjÄXppñ5O|³² |M3lR@HyperNeutrino Welcome back!

```

Try it online!

Hexdump:

```
00000000: 692f 5c0a 5c2f 1b31 36f1 483e 474d d958  i/\.\/.16.H>GM.X
00000010: 7070 6ac4 5870 70f1 354f 7cb3 b220 7c1b  ppj.Xpp.5O|.. |.
00000020: 4d33 6c52 4048 7970 6572 4e65 7574 7269  M3lR@HyperNeutri
00000030: 6e6f 2057 656c 636f 6d65 2062 6163 6b21  no Welcome back!

```

Explanation:

```
i                             " Insert:
 /\<cr>\/                     "   '/\<newline>\/'
         <esc>                " Return to normal mode
16ñ             ñ             " 16 times:
   H                          "   Move to the beginning of the buffer
    >G                        "   Indent every line
      M                       "   Move to the middle of the buffer (the last downward facing part)
       Ù                      "   Duplicate this line downwards
        X                     "   Delete one of the leading spaces
         pp                   "   And paste it between the slashes twice
           j                  "   Move down a line (the first upward facing part)
            Ä                 "   Duplicate this line upwards
             X                "   Delete one of the leading spaces
              pp              "   And paste it between the slashes twice
5O                            " On the five lines above us, insert:
  |³² |                       "   A bar followed by 32 spaces, followed by a bar
       <esc>                  " Return to normal mode
            M                 " Move to the middle line of the buffer
             3l               " Move 3 characters to the right
               R              " And write the following over the existing text:
@HyperNeutrino Welcome back!  "   Welcome back!

```
> 5 votes

# Answer
# 05AB1E, ~~87~~ ~~78~~ ~~81~~ 79 bytes

-9 bytes because of dictionary compression

+2 bytes because "back" isn't capitalized

-2 bytes because of "mirroring"

```
17F'/16N-úðN×«∞}'|D32ú«D”|  @HyperNeutrino‡Ý back!  |”'|D32ú«D17F'\Núð16N-×«∞}»

```

Try it online!

---

## Explanation (split into parts)

Produces the "triangle" at the top

```
17F            # for N in 0 .. 16
   '/          # push a forward slash
     16N-      # 16 - N
         ú     # put 16 - N spaces in front of the forward slash
          ð    # space character
           N×  # repeated n times
             } # end of for loop

```

Produces the two lines with vertical bars at the end.

```
'|       # push a vertical bar
  D      # duplicate
   32ú   # put 32 spaces before the vertical bar
      «  # concatenate, i.e. one line complete
       D # duplicate

```

Produces the "Welcome back" string; `”| @HyperNeutrino‡Ý back! |”`.

Most of it is interpreted as the literal characters, except for `‡Ý`, which is interpreted as `Welcome`.

Exact copy of second section: `'|D32ú«D` produces second set of vertical bar lines

Produces the "triangle" at the bottom, similar to first part

```
17F              # for N in 0 .. 16
   '\            # push backslash
     Nú          # put N spaces before backslash
       ð         # space character
        16N-     # 16 - N
            ×    # 16 - N spaces
             «   # concatenate the two strings
              ∞  # mirror
               } # end for

```

The `»` at the end joins everything by newlines and implicitly prints.
> 5 votes

# Answer
# Charcoal, 40 bytes

```
↑³↗¹⁷‖Ｍ‖Ｂ↓Ｊ³¦⁰“]‹baiE_ν﹪↓➙ZＫξη¢:Ａgλ⁸%I”

```

Try it online! Link is to verbose version of code.
> 5 votes

# Answer
# T-SQL, 222 bytes

```
DECLARE @ INT=1T:PRINT SPACE(17-@)+'/'+SPACE(2*(@-1))+'\'SET @+=1IF @<18GOTO T
PRINT REPLACE('|S|
|S|
|  @HyperNeutrino Welcome back!  |
|S|
|S|','S',SPACE(32))B:SET @-=1PRINT SPACE(17-@)+'\'+SPACE(2*(@-1))+'/'IF @>0GOTO B

```

Pretty straightforward procedural approach. Formatted:

```
DECLARE @ INT=1
T:  --count up for top cone
    PRINT SPACE(17-@) + '/' + SPACE(2*(@-1)) + '\'
    SET @+=1
IF @<18 GOTO T

--middle section, string literal with line breaks and a single replace
PRINT REPLACE('|S|
|S|
|  @HyperNeutrino Welcome back!  |
|S|
|S|','S',SPACE(32))

B:  --count back down for bottom cone
    SET @-=1
    PRINT SPACE(17-@) + '\' + SPACE(2*(@-1)) + '/'
IF @>0 GOTO B

```

Only thing probably worth explaining is that strings in T-SQL can contain line breaks inside the quotes, I take advantage of that here, instead of adding `CHAR(13)`.
> 3 votes

# Answer
# Python 2, 187 bytes

```
f,s=lambda s,n=1:'\n'.join((s%(' '*i)).center(34)for i in range(0,34,2)[::n]),'|%s|\n'
print f('/%s\\')+'\n'+s%(' '*32)*2+s%('  @HyperNeutrino Welcome back!  ')+s%(' '*32)*2+f('\\%s/',-1)

```

Try it online!
> 2 votes

# Answer
# Mathematica, 165 bytes

```
T=Table;c=Column;c[{s=c[T[""<>{"/",T[" ",2i],"\\"},{i,0,16}],Alignment->Center],g=c@T[""<>{"|",T[" ",32],"|"},2],"|  @HyperNeutrino Welcome back!  |",g,s~Rotate~Pi}]

```
> 2 votes

# Answer
# Retina, 107 bytes

```

17#¶#¶|2@HyperNeutrino Welcome back!2|¶#¶#17
#
|32|
\d+
$*
\G (?=( *))
$1/$`$`\¶
r`(?<=( *)) \G
¶$1\$'$'/

```

Try it online! Explanation: The first stage inserts the text and starts outlining the surrounding characters, which are further expanded by the next two stages. The fourth and fifth stages then generate the top and bottom diagonal lines respectively.
> 1 votes

# Answer
# PHP, 174 bytes

```
for(;$i<39;)echo($p=str_pad)($p($i>16?$i!=19?$i>21?"\\":"|":"|  @HyperNeutrino Welcome back!  ":"/",$i>16?$i>21?77-$i*2:33:$i*2+1).($i++>16?$i>22?"/":"|":"\\"),34," ",2),"
";

```

Try it online!
> 1 votes

# Answer
# ///, 306 bytes

```
/6/"\\//5/\/\///4/"#53/  52/\\%51/\/%50/\\'5-/\/'5,-|%%"3|/-/
5&/3#/1/""5#/3\\5"/3331&/\0% #/#0%#/&0% \/60%\/40" &/"&0"&1\0" #1#041&0" \1606140 &1"&0&1%\0 #1%#0#1%&0 \1%60\1%4\,,'|3@HyperNeutrino Welcome back!3|,,'\2%4- \2%6-#2%&- #2%#-&2%\- &2"&-624-" \26-42&-" #2#-"&2\-" &\"&-%\\4-% \\6-%#\&-% #\#-%&\\/

```

Try it online!
> 1 votes

# Answer
# SOGL V0.12, ~~54~~ 50 bytes

```
ā'²∫0; /ž}j"ν_‘3∙+╬³"Ξ█a⁄I⅜ģī\↕═<ν▲ΩhΕR$C¹‘4L«žj╬Æ

```

Try it Here!

Explanation:

```
ā                                push an empty array
 '²∫     }                       17 times repeat
    0;                             push 0 below the iteration
       /ž                          at [0, iteration] (1-indexed position) insert the slash (so every time it moves  everything one char right)
          j                      remove last blank line (idk why it's there)
           "ν_‘                  push "|                "
               3∙                get an array of 3 of those
                 +               append that to the diagonals mirrored
                  ╬³             mirror horizontally with 0 overlap and swapping chars
                    "..‘         push "@HyperNeutrino Welcome back!"
                        4L«ž     at [4;20] insert that in
                            j    remove last blank line (2nd byte wasted now)
                             ╬Æ  mirror vertically

```
> 1 votes

# Answer
# 05AB1E, 57 bytes

```
žvƒ'/'\N·ú«}'|žvúÂìD”|  @HyperNeutrino‡Ý back!  |”)Â¦í«.c

```

Try it online!
> 1 votes

# Answer
# Canvas, 55 bytes

```
⁷╵＼║：↕|“ ”⁷×＋║２＊：“×∔］＊YV≠²↖:tvｘZ｝@ｌ Ｊ｛ ５ｎ＼┌⟳sｃ⤢7‟；∔∔┘∔∔

```

Try it here!
> 1 votes

# Answer
# Vyxal `C`, 47 bytes

```
\/16꘍¦øṀ÷\|16꘍m:`|  @Hy∧‛NeꜝṘ⋏⇩ ÷… λǐ!  |`WḂḢRJ

```

Try it Online!
> 1 votes

# Answer
# Canvas, 40 bytes

```
⁷╵／|３＊∔╫@HyperNeutrino Welcome back!４Ａ«╋

```

Try it here!

There's already a Canvas answer here but I'd say this uses a fairly different approach.
> 0 votes

# Answer
# Deadfish~, 2245 bytes

```
{iii}ii{c}cccccc{i}iiiiic{iiii}iiiiic{{d}ii}ddc{ii}ii{c}ccccc{i}iiiiic{d}dddddcc{iiiiii}c{{d}ii}ddc{ii}ii{c}cccc{i}iiiiic{d}dddddcccc{iiiiii}c{{d}ii}ddc{ii}ii{c}ccc{i}iiiiic{d}dddddcccccc{iiiiii}c{{d}ii}ddc{ii}ii{c}cc{i}iiiiic{d}dddddcccccccc{iiiiii}c{{d}ii}ddc{ii}ii{c}c{i}iiiiic{d}ddddd{c}{iiiiii}c{{d}ii}ddc{ii}ii{c}{i}iiiiic{d}ddddd{c}cc{iiiiii}c{{d}ii}ddc{ii}iiccccccccc{i}iiiiic{d}ddddd{c}cccc{iiiiii}c{{d}ii}ddc{ii}iicccccccc{i}iiiiic{d}ddddd{c}cccccc{iiiiii}c{{d}ii}ddc{ii}iiccccccc{i}iiiiic{d}ddddd{c}cccccccc{iiiiii}c{{d}ii}ddc{ii}iicccccc{i}iiiiic{d}ddddd{cc}{iiiiii}c{{d}ii}ddc{ii}iiccccc{i}iiiiic{d}ddddd{cc}cc{iiiiii}c{{d}ii}ddc{ii}iicccc{i}iiiiic{d}ddddd{cc}cccc{iiiiii}c{{d}ii}ddc{ii}iiccc{i}iiiiic{d}ddddd{cc}cccccc{iiiiii}c{{d}ii}ddc{ii}iicc{i}iiiiic{d}ddddd{cc}cccccccc{iiiiii}c{{d}ii}ddc{ii}iic{i}iiiiic{d}ddddd{cc}{c}{iiiiii}c{{d}ii}ddc{iiii}dddc{d}ddddd{cc}{c}cc{iiiiii}c{{d}ii}ddc{{i}}{i}iiiic{{d}i}dd{cc}{c}cc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}dd{cc}{c}cc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddcc{iii}iic{i}ddc{iiiii}dc{d}ic{d}dc{i}iiic{ddd}ddddddc{ii}iiic{i}iiiiiicdcddc{d}iciiiiicic{{d}ii}ic{iiiii}iiiiic{i}iiiic{i}dddc{d}ic{i}iicddc{d}iic{{d}iii}ic{iiiiii}iiiiiicdciic{i}ddc{{d}iii}ddddcdcc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}dd{cc}{c}cc{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}dd{cc}{c}cc{{i}d}iic{{d}}{d}ddddc{{i}dd}iic{dddddd}{cc}{c}cc{i}iiiiic{dddd}iiic{ii}iic{iiiiii}c{dddddd}{cc}{c}{i}iiiiic{dddd}iiic{ii}iicc{iiiiii}c{dddddd}{cc}cccccccc{i}iiiiic{dddd}iiic{ii}iiccc{iiiiii}c{dddddd}{cc}cccccc{i}iiiiic{dddd}iiic{ii}iicccc{iiiiii}c{dddddd}{cc}cccc{i}iiiiic{dddd}iiic{ii}iiccccc{iiiiii}c{dddddd}{cc}cc{i}iiiiic{dddd}iiic{ii}iicccccc{iiiiii}c{dddddd}{cc}{i}iiiiic{dddd}iiic{ii}iiccccccc{iiiiii}c{dddddd}{c}cccccccc{i}iiiiic{dddd}iiic{ii}iicccccccc{iiiiii}c{dddddd}{c}cccccc{i}iiiiic{dddd}iiic{ii}iiccccccccc{iiiiii}c{dddddd}{c}cccc{i}iiiiic{dddd}iiic{ii}ii{c}{iiiiii}c{dddddd}{c}cc{i}iiiiic{dddd}iiic{ii}ii{c}c{iiiiii}c{dddddd}{c}{i}iiiiic{dddd}iiic{ii}ii{c}cc{iiiiii}c{dddddd}cccccccc{i}iiiiic{dddd}iiic{ii}ii{c}ccc{iiiiii}c{dddddd}cccccc{i}iiiiic{dddd}iiic{ii}ii{c}cccc{iiiiii}c{dddddd}cccc{i}iiiiic{dddd}iiic{ii}ii{c}ccccc{iiiiii}c{dddddd}cc{i}iiiiic{dddd}iiic{ii}ii{c}cccccc{iiiiii}c{dddd}dddddc

```

Try it online!

Tio runs 3/4 of it.
> 0 votes

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


title: Universal Spooky Meme Translator

text:
# Question
Title: Universal Spooky Meme Translator
# Introduction

Turns out, aliens love memes just as much as we do. Every alien race we've encountered so far has their own version of `2spooky4me` (see the following question) and equivalent, though, with some variation. The inhabitants of planet CUTE1f can't handle a lot of spook, so their preferred spook is `1spooky2me`, while skeletor7 memers love them some spook, so they tend to use `9spooky11me`.

# Challenge

Translating memes is hard work, so you've been tasked with writing a universal meme translator to help these guys access the memenet correctly. Your program will accept a meme and a transformation to apply to the digit sequences in that meme to make it appropriate for the inhabitants of a different planet.

## Input

Your program will receive two string inputs:

1. The input meme (e.g. `2spooky4me`). Matches `[a-zA-Z0-9]+`.
2. The transformation to apply to it (e.g. `+1`, to go from `2spooky4me` to `3spooky5me`). Matches `[+\-*/^]\d+` (you must accept `+`, `-`, `*`, `/`, and `^` as operators, regardless of the native representation in your language).

## Output

Your program must return a string output (printed to standard output or equivalent) with the given transformation applied to the digit sequences in the input meme. In a weird turn of events, it also turns out that all races encountered so far prefer integral memes over fractional ones, so these transformations should perform integer arithmetic (e.g. `1spooky1me /2` should result in `0spooky0me`).

## Examples

Standard arithmetic operations apply:

```
Input:  2spooky4me +1
Output: 3spooky5me

Input:  2spooky4me -1
Output: 1spooky3me

Input:  2spooky4me *15
Output: 30spooky60me

Input:  10spooky900me /5
Output: 2spooky180me

```

Digit sequences are integral; integer truncation should occur in cases like this:

```
Input:  idontunderstandmemes3 /2
Output: idontunderstandmemes1

```

Your input may not have any digit sequences:

```
Input:  notreallyafunnymeme *100
Output: notreallyafunnymeme

```

You must support exponentiation, even if it is not a native operation in your language of choice:

```
Input:  2spooky4me ^3
Output: 8spooky64me

```

There's no limit on string length of number of digit sequences in the string:

```
Input:  some1meme2sequences3can4be5really6long7 /2
Output: some0meme1sequences1can2be2really3long3

```

## Addendum

If your language supports arbitrary-precision integers as a language feature, you must use those. If it does not, you do not need to support arbitrary-precision integers. For example, you must use `Integer` in Haskell instead of `Int` because it's available as part of the language; in `Java`, you are not required to use `BigInteger` because it's a library feature, not a language feature.

```
Input:  2000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000spooky4me /2
Output: 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000spooky2me

```

This is , so standard loopholes are forbidden, and the shortest answer in bytes wins!

# Leaderboard

The Stack Snippet at the bottom of this post generates the leaderboard from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

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

```
## Language Name, N bytes

```

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

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

```

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

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

```

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

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

```

```
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 79809; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 45941; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```

# Answer
# Jolf, ~~15~~ 14 bytes

```
ρi«\d+»dC!6+HI

```

Try it here!

## Explanation

```
ρi«\d+»dC!6+HI
ρ «\d+»         replace all digits
 i              in the input
       d        (functional replace)
         !6     eval (using jolf's custom infix eval)
           +H   the number as a string plus
             I  the second input
        C       floor the result (integer truncate)

```

---

Fun to note, I updated Jolf after this challenge, adding some RegExp builtins. This could be ~~12~~ 11 bytes:

```
ρiLRdC!6+HI

```
> 10 votes

# Answer
# Ruby, ~~50~~ ~~44~~ 43 bytes

FGITW answer. Gotta go fast!

Thanks to @Neil for saving 6 bytes.

Oh right, crossed out 44 is still 44

```
->m,t{m.gsub(/\d+/){eval$&+t.sub(?^,'**')}}

```
> 25 votes

# Answer
# Perl, ~~36~~ 34 bytes

```
s/\d+/"0|$&$^I"=~s#\^#**#r/gee

```

The source code is **30 bytes** long and it requires the switches `-pi` (**+4 bytes**). It takes the first input from STDIN, the second input as an argument to `-i`.

*Thanks to @DenisIbaev for golfing off 2 bytes!*

Test it on Ideone.
> 14 votes

# Answer
## PowerShell v2+, ~~139~~ 137 bytes

```
param($a,$b)-join($a-split"(\d+)"|%{if($_-match"\d+"){if($b[0]-ne'^'){[math]::Floor((iex $_$b))}else{"$_*"*$b.Trim('^')+1|iex}}else{$_}})

```

Ooof ... 47 bytes just to account for `^` since that's not a native operator in PowerShell. Saved 2 bytes thanks to @TessellatingHeckler.

Takes input as `$a=<word>`, `$b=<operation>`, like `.\universal-spooky-meme.ps1 2spooky4me ^3`. We `-split` `$a` on digits, enclosing that in parens so we keep the delimiters, and pipe the resultant array through a loop `|%{...}`. If the current piece is a number, we're in the first `if`. We need to check whether the first character of `$b` is `^`. If it's not, we simply concatenate our current piece and `$b` and send it to `iex` (similar to `eval`), then leave that on the pipeline. Otherwise, we need to create an exponentiation string with `"$_*"*$b.Trim('^')+1` and pipe that to `iex`, and leave that on the pipeline. For the given `2spooky4me ^3` example, this will be `2*2*2*1` and `4*4*4*1`, respectively.

Otherwise, we just leave the string as-is on the pipeline.

All of those results are gathered from the pipeline with the encapsulating parens before being `-join`ed back together into one string. That is the re-left on the pipeline, and output is implicit at program termination.

### Examples

```
PS C:\Tools\Scripts\golfing> .\universal-spooky-meme.ps1 2spooky4me ^5
32spooky1024me

PS C:\Tools\Scripts\golfing> .\universal-spooky-meme.ps1 2spooky4me /3
0spooky1me

```
> 9 votes

# Answer
## JavaScript (ES7), ~~58~~ 57 bytes

```
(s,t)=>s.replace(/\d+/g,n=>0|eval(n+t.replace('^','**')))

```

Edit: Saved 1 byte when I remembered that `replace` also works on literal strings.
> 7 votes

# Answer
# Python 2, ~~156~~ ~~89~~ ~~88~~ 87 bytes

Inspired by the other answers that use their languages' substitution function with a function handler to process the numeric parts of the long `i`nput string with the `o`perator. Unlucky for Python, the `^` must be replaced by `**`, which costs a whopping 18 bytes. The `.group(0)` call just to access the match object's string representation does not make things better...

Thanks to QPaysTaxes for spotting a spurious space and RootTwo for the unnecessary argument to `.group`!

```
import re
lambda i,o:re.sub(r'\d+',lambda p:str(eval(p.group()+o.replace('^','**'))),i)

```
> 6 votes

# Answer
# Pyth, 29

```
Jws.i:zK"\d+"3m.vs.iJ]+d;:zK1

```

This works by extracting each number from the meme, and then interleaving (`.i`) it followed by a space and wrapped in a list with the other argument. So if our number is `7` and we had `^20` we would get the list: `["^", "7 ", "20"]`. Flattening and using Pyth's `eval` (`.v`) on this always gives the operation we want. Finally these values are interleaved with the original string split on occurrences of numbers.

This could be a byte shorter if both inputs were surrounded by quote characters, or two bytes shorter if only one of them could be quoted.

Try it here or run a Test Suite
> 6 votes

# Answer
# Javascript (ES6) 99 bytes

Another example, why we hate to wait for ES7 to get compatibility

```
(a,b)=>a.match(/\d+|\D+/g).map(_=>(d=- -_)?eval(b[0]=="\^"?Math.pow(_,b.slice(1)):d+b)|0:_).join``

```

Runnable example:

```
f=(a,b)=>a.match(/\d+|\D+/g).map(_=>(d=- -_)?Math.ceil(eval(b[0]=="\^"?Math.pow(_,b.slice(1)):d+b)):_).join``

alert(f(prompt("Enter string!"), prompt("Enter operation!")));
```
> 5 votes

# Answer
# Julia, ~~71~~ ~~59~~ 54 bytes

```
/ =÷
x%y=replace(x,r"\d+",t->"big($t)"y|>parse|>eval)

```

The requirement to use `big` if available makes this a lot longer than it could be...

Try it online!
> 4 votes

# Answer
## PowerShell (v4), ~~124~~ 120 bytes

```
# New 120 byte version:
$s,$a=$args;[regex]::Replace($s,'\d+',{($(if($a-ne($a=$a.Trim('^'))){
"$args*"*$a+1}else{"$args$a"})|iex)-replace'\..*'})

# Previous 124 byte version
$s,$a=$args;[regex]::Replace($s,'\d+',{if($a[0]-eq'^'){
[math]::pow("$args",$a.Trim('^'))}else{iex "$args$a-replace'\..*'"}})

```

(the newlines are only here to avoid horizontal scrolling, they work when saved as one line).

Comments, and ungolfed version was requested:

```
$meme, $instruction = $args

# Scriptblock which processes the numbers
# to be replaced. $args is the input number.
$replacement = {

    # Generates a string of the calculation, by:
    # Removing leading ^ character, if present.
    # ^3 -> 3,      +3 -> +3
    # See if it was present, and switch code paths.
    # (Can be one combined step in the golf)
    # Switch code paths for "raise to the power of",
    # or basic arithmetic.
    $trimmedInstruction = $instruction.Trim('^')
    $tmp = if ( $instruction -ne $trimmedInstruction ) {

        # String multiplication, changes
        # function input "45" and instruction "3" into
        # "45*45*45*+1". The "3" implicitly casts to [int]
        # the +1 is there to make the trailing * not crash.
        "$args*" * $instruction + 1

    } else {
        # Cobble the basic math together as a string
        # "45" and "+10" becomes
        # "45+10"
        "$args$instruction"
    }

    # eval() the generated string (e.g. "45+10" or "45*45*45*+1")
    $tmp = Invoke-Expression $tmp      # iex

    # Use a regex golf to replace trailing .23423
    # decimals in case of division with remainder.
    # Acts as [math]::floor(), harmless on other numbers.
    $tmp -replace'\..*'
}

# A regular expression replacement which picks out all
# the numbers (\d+) and runs them through the
# replacement function. Returns a string which
# ends up on stdout
[regex]::Replace($meme, '\d+', $replacement)

```
* .Net regex library can do a replace with a scriptblock that executes on the content of the match, and PowerShell casts types strings to numbers, and `iex` is like `eval()` in other languages. It just does `"2spooky" "+3"` -\> `eval("2+3")`
* Except... it can't handle `^` operator or any other convenient exponentiation like `**`, it can only use the `[math]::Pow()` library call so there's a big block to handle that branch.
    + The updated version steals an idea from @TimmyD and does string multiplication instead - `"2*" * n` which becomes `"2*2*2*2*"` and then adds `+1` on the end to multiply by one instead of complaining about the trailing `*`.
* Except... .Net does Banker's Rounding which rounds to the nearest even number by default, and 3/2 = 2 rather than 3/2 = 1. This challenge calls for truncation, and that means `[math]::Truncate()`. Instead, I save characters by using `-replace` to trim a decimal point and anything after it.

Test cases:

```
PS D:\> .\meme.ps1 2spooky4me +1
3spooky5me

PS D:\> .\meme.ps1 2spooky4me -1
1spooky3me

PS D:\> .\meme.ps1 2spooky4me *15
30spooky60me

PS D:\> .\meme.ps1 10spooky900me /5
2spooky180me

PS D:\> .\meme.ps1 idontunderstandememes3 /2
idontunderstandememes1

PS D:\> .\meme.ps1 "idontunderstandememes3" "/2"
idontunderstandememes1

PS D:\> .\meme.ps1 "notreallyafunnymeme" "*100"
notreallyafunnymeme

PS D:\> .\meme.ps1 "2spooky4me" "^3"
8spooky64me

PS D:\> .\meme.ps1 "some1meme2sequences3can4be5really6long7" "/2"
some0meme1sequences1can2be2really3long3

PS D:\> .\meme.ps1 2000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000spooky4me /2
1E+780spooky2me

```

NB. In the last test the numbers overflow into type `[BigInteger]` automatically, but they get rendered in scientific notation. Luckily, every known race able to communicate between the stars has enough scientific development to be able to process scientific notation without problem.
> 4 votes

# Answer
## Kotlin, ~~416~~ 413 Bytes

The lack of an `eval()` in Kotlin really upped that byte count...

```
fun main(a:Array<String>){var r=Regex("\\d+");var i=a[0];var n=a[1].takeLast(a[1].length-1).toInt();when(a[1][0]){'+'->print(r.replace(i,{m->""+(m.value.toInt()+n)}));'*'->print(r.replace(i,{m->""+(m.value.toInt()*n)}));'/'->print(r.replace(i,{m->""+(m.value.toInt()/n)}));'-'->print(r.replace(i,{m->""+(m.value.toInt()-n)}));'^'->print(r.replace(i,{m->""+(Math.pow(m.value.toDouble(),n.toDouble())).toInt()}));}}

```

Try it Online!

### Ungolfed

```
fun main(a: Array<String>) {
    var r = Regex("""\d+""")
    var i = a[0]
    var n = a[1].takeLast(a[1].length - 1).toInt()
    when (a[1][0]) {
        '+' -> print(r.replace(i, { m -> "" + (m.value.toInt() + n) }))
        '*' -> print(r.replace(i, { m -> "" + (m.value.toInt() * n) }))
        '/' -> print(r.replace(i, { m -> "" + (m.value.toInt() / n) }))
        '-' -> print(r.replace(i, { m -> "" + (m.value.toInt() - n) }))
        '^' -> print(r.replace(i, { m -> "" + (Math.pow(m.value.toDouble(), n.toDouble())).toInt() }))
    }
}

```
> 4 votes

# Answer
# Lua, ~~145~~ 93 bytes

```
r=io.read;m=r()o=r()m=m:gsub("%d",function(n)return loadstring("return..."..o)(n)end)print(m)

```
> 3 votes

# Answer
## Bash + GNU coreutils, 144 Bytes

```
d=
u=$1,
for((i=0;i<${#u};i++)){ l=${u:i:1}
[[ "$l" =~ [0-9] ]]&&d=$d$l||{ [ -z $d ]||echo -n `bc<<<$d$2`&&{ [ $l != , ]&&echo -n $l; };d=; }
}

```

This looks at the alteration between digits and non-digits, that's why a random invalid input character (comma) is appended to the input string. This comma is then ignored in the output. The convention of the OP follows exactly the syntax of `bc` which is used here to do the maths.
> 3 votes

# Answer
# Zsh (builtins only), ~~167~~ 118 bytes

```
a=$1 S=(${(s: :)a//[0-9]/ })
for i (${(s: :)a//[a-z]/ })N+=($[i${2/^/**}])
((#a<58))&&<<<${(j::)N:^S}||<<<${(j::)S:^N}

```

Crack the input into a numerical array `N` and string array `S`, do operations on `N`, then zip the arrays together again (zip the arrays the other way if the leading character is a letter).

Try it Online.

<sub>~~167 bytes!~~ (longer than the bash solution! ☹ )</sub>
> 3 votes

# Answer
# Zsh, 95 bytes

Whole program. Inputs: the meme and transformation as command line arguments. Output: standard output (with a trailing newline).

```
a=$1;repeat $#a c=${a/[^0-9]*}&&(($#c))&&b+=$[$c${2/^/**}] a=${a##<->}||b+=$a[1] a=${a#?};<<<$b

```

Try it online!

A 98-byte solution with a non-optimized number/letter test:

```
a=$1;repeat $#a [[ $a = <->* ]]&&b+=$[${a%%[^0-9]*}${2/^/**}] a=${a##<->}||b+=$a[1] a=${a#?};<<<$b

```

Explanation: first here's the code with additional whitespace.

```
a=$1;
repeat $#a \
  c=${a/[^0-9]*} &&
  (($#c)) &&
  b+=$[$c${2/^/**}] a=${a##<->} ||
  b+=$a[1] a=${a#?};
<<<$b

```

The general idea is to consume the input in `$a` from left to right, one multi-digit integer or one non-digit character at a time. Accumulate the result in `$b`, which is printed out after the loop.

`repeat $#a …` repeats the following code `$#a` (initial length of the input) times. The loop body consumes at least one character as long as `$a` is non-empty and does nothing when it runs out, so this works, and it's shorter than naive approaches such as `while (($#a))` or `while [ $a ]`. In the loop body:

1. Set `c` to the initial digit sequence of `$a` (remove everything starting with the first non-digit). `${a/[^0-9]*}` is short for `${a/[^0-9]*/}` and shorter than the more intuitive `${a%%[^0-9]*}`. The assignment always succeeds, so the subsequent `&&` is just like `;` except that it doesn't terminate the `repeat` body.
2. `((#c))` tests whether `c` is non-empty, i.e. if `$a` starts with a digit.
3. If the test above, i.e. if `$a` starts with a digit, append the result of the arithmetic expression `$[…]` (an alternative form of `$((…))`) to `b`. The expression uses the digits in `$c` and the operator-and-number from `$2`. Zsh has the operators `+` `-` `*` `/` as required but exponentiation is `**` instead of `^`.
4. If the test above was false, i.e. if `$a` starts with a non-digit, append the first character of `$a` to `b` and remove the first character from `a`.
> 3 votes

# Answer
# Zsh `--extendedglob`, 39 bytes

```
<<<${1//(#m)[0-9]##/$[MATCH${2/\^/**}]}

```

Try it online!
> 3 votes

# Answer
## R, 163 bytes

As someone who's learning regular expressions and string substitution in R, this proved to be a quite difficult challenge. Especially because matching the numbers is easy but I couldn't find a way to use multiple substitutions with `gsub`. Furthermore, I don't know if `eval(parse(paste0(...` is the most efficient way to switch between operations. Maybe the `switch`-function is better suited here.

```
function(s,o){p=strsplit;y=p(gsub("\\d+","?",s),"?")[[1]];x=na.omit(as.integer(p(s,"[a-zA-Z]+")[[1]]));y[y=="?"]=floor(eval(parse(,,paste0("x",o))));cat(y,sep="")}

```

**Explanation**

```
f=function(s,o){
    p=strsplit                                    # alias for stringsplit
    y=p(gsub("\\d+","?",s),"?")[[1]]              # substitute numbers with "?" and split into vector on "?"
    x=na.omit(as.integer(p(s,"[a-zA-Z]+")[[1]]))  # split at alphabetical char, return vector with numbers to be operated on
    y[y=="?"]=floor(eval(parse(,,paste0("x",o)))) # replace inserted "?" with vector of numbers operated on
    cat(y,sep="")                                 # print concatenated vector
}

```
> 2 votes

# Answer
# Javascript (ES6), 85 Bytes

```
x=(s)=>{var a=s.split(" ");return[...a[0]].map(x=>(!isNaN(x))?eval(x+a[1]):x).join``}

console.log(x("2spookie5me +1"));

```

Ungolfed:

```
x = (s) => {
  var a = s.split(" ");
  return [...a[0]].map(x => (!isNaN(x)) ? eval(x + a[1]) : x).join ``
}
console.log(x("2spookie5me +1"));

```
> 2 votes

# Answer
# Groovy, ~~64~~ 60 Bytes

```
{a,b->a.replaceAll(/\d+/,{Eval.me(it+b.replace("^","**"))})}

```

Replaces all instances of digits with a closure that evaluates the operation on the digit portions of the word passed. If passed an exponent function, it replaces it with the proper notation. Groovy implicitly handles BigInteger/BigDecimal conversion when using `Eval.me()` because parsed strings can potentially be out of the `2^32-1` range.

## Explained

`{a,b->...}` \- Closure with two arguments.

`a.replaceAll(/\d+/,{...})` \- Search for all digit sequences in string and replace with a closure.

`{Eval.me(it+b.replace("^","**"))}` \- More specifically, a closure with each match having the operation appended to it, then evaluated as groovy code.

`.replace("^","**")` \- Replace the first instance of `^` with the groovy exponent operator `**` in the operation provided. If you want this to work with full equation strings that use exponents, use `replaceAll()` instead for a +3 byte penalty.

Fun side-note his is a valid test scenario:
`(22348952345238905290858906209862398036spooky409552me, /200*4943^8-23939+((100/203)+600)`
> 2 votes

# Answer
# 05AB1E, 18 bytes

```
ε.γd]``s„^/„m÷‡.VJ

```

Input as a pair of strings.

Try it online or verify all test cases.

**Explanation:**

```
ε                  # Map both strings in the (implicit) input-pair to:
 .γ                #  Group it into substrings by:
   d               #   Is it a non-negative number
    ]              # Close both the map and inner group-by
     `             # Pop and push both list or substrings separated to the stack
      `            # Pop and push the operator and number separated to the stack
       s           # Swap them, so the operator is at the top of the stack
        „^/„m÷‡    # Transliterate "^" to "m" and "/" to "÷"
               .V  # Evaluate the operator string as 05AB1E command
                   # (the operations are no-ops on the non-number substrings)
                 J # Join the list of substrings back together to a single string
                   # (after which it is output implicitly as result)

```

If the final test case wasn't necessary, it could have been 17 bytes (which unfortunately has floating-point precision issues for the final test case):

```
ε.γd]``s'^'m:.VïJ

```

Try it online or verify all test cases.

**Explanation:**

Mostly the same as above, except for `„^/„m÷‡` being `'^'m:` to only transform the exponent-operator and leave the division-operator as is, and the addition of `ï` to truncate the decimals after the eval.
> 2 votes

# Answer
# RProgN, 39 Bytes

```
►x='%d+'§x'%D+'''Rx'%d+'''Rg'y'=y_}R

```

## Explained

```
►x='%d+'§x'%D+'''Rx'%d+'''Rg'y'=y_}R
►                                       # Spaceless segment.
 x=                                     # Assign the top value of the stack '[+*/-]\d+'
   '$d+'§                         }R     # Replace everything in the pattern %d+ (all numbers) based on an anonymous function
         x'%D+'''R                      # Replace all Non-digits in the modifer with nothing, leaving just the second argument for the operator.
                  x'%d+'''R             # Snip all digits, separating our operator from our digits such that digit operator exists in the stack.
                           g'y'=        # Grab the function that is represented by the top of the stack (the operator in this case)
                                y       # Run it
                                 _      # Floor the result.

```

Technically invalid answer, because this language did not exist for it. However, it was not specifically designed for it, nor any particular addition. So I'm running it. Sue me.

Try it Online!
> 1 votes

# Answer
## Perl 6, 111 bytes

```
{/(\w+)\s(<[+\-*/^]>)(\d+)/&&my \b=+$2;my \o=(*+b,*-b,* *b,*div b,* **b)[index "+-*/^",$1];$0.subst(/\d+/,o):g}

```

Unfortunately `EVAL` is disabled by default. Also, you have to use `div` for integer division.
> 1 votes

---
Tags: code-golf, string, math, subsequence
---


title: Increasing permutation trees

text:
# Question
Title: Increasing permutation trees
For this challenge a "binary tree" is a rooted tree where each node has 0 children (leaf) or 2. The children of a node are unordered, meaning that while you might *draw* the tree with left and right children there isn't a distinction between them and mirroring the tree or a sub-tree does not produce a new tree.

In this challenge you will be given an integer \\$n\\$ and you will be asked to determine the number of binary trees with each node labeled from \\$1\\$ to \\$2n+1\\$ such that no child node is less than its parent.

For example the following tree with 7 nodes is valid:

```
     1
 2    7
3  4
  5 6

```

but the following tree is not:

```
     1
 2    7
6  4
  5 3

```

Since `3` is a child of `4`.

# Task

Given \\$n\\$ calculate the number of binary trees labeled from \\$1\\$ to \\$2n+1\\$ such that no child node is less than its parent.

This is so the goal is to minimize the size of your source code as measured in bytes.

# Test cases

I've calculated the first 11 solutions on my own:

```
1, 1, 4, 34, 496, 11056, 349504, 14873104, 819786496, 56814228736, 4835447317504

```

and the OEIS has more terms at: A002105

# Answer
# Python NumPy, 72 bytes

```
lambda n:(mat(tril(cumsum(r_[1:n+3]),1),"O")**n)[0,0]
from numpy import*
```

Attempt This Online!

Same as below but as a function (no outer loop):

# Python NumPy, 85 bytes

```
from numpy import*
a=1,
for s,in r_:print((mat(tril(a,1),"O")**s).A1[0]);a+=a[s]+s+2,
```

Attempt This Online!

Uses the production matrix approach from the OEIS page. Preamble doctors `print` to cut short the infinite loop (otherwise ato swallows the output). Uses this trick to set up the infinite loop.
> 6 votes

# Answer
# Python 3.8 (pre-release), ~~85~~ 80 bytes

```
def f(n,s=1,*a):
 for _ in"__"*~-n:a=s,*[s:=s+x for x in a[::-1]]
 print(s>>~-n)

```

Try it online! Link includes test cases. Explanation: Based on the relation `A002105(n) = A000111(2n-1)/2ⁿ⁻¹`, calculates A000111 using @dingledooper's approach to Count alternating permutations. Edit: Saved 5 bytes with help from @pexger.
> 5 votes

# Answer
# SageMath, ~~44~~ ~~42~~ 36 bytes

```
lambda n:2*(-2)**n*polylog(1-2*n,-1)

```

Try it online!

*Saved ~~2~~ 8 bytes thanks to alephalpha!!!*

Uses a port of the Mathematica code by Vladimir Reshetnikov on the OEIS A002105 page.
> 4 votes

# Answer
# BQN, 23 bytesSBCS

Based on Peter Luschny's Sage function on OEIS.

```
1⊑(0∾2×+`∘⌽⍟2)⍟⊑∘⥊÷2××˜

```

Run online!
> 3 votes

# Answer
# Charcoal, 31 bytes

```
Ｎθ⊞υ¹Ｆ⊖⊗θ≔⊞Ｏ⮌ＥυΣ…υ⊕λ⁰υＩ÷§υ⁰Ｘ²⊖θ

```

Try it online! Link is to verbose version of code. Explanation: Combining two formulas on A110501 gives A002105 in terms of A000111, which we did a couple of days ago: `A002105(n) = A000111(2n-1)/2ⁿ⁻¹`.

```
Ｎθ

```

Input `n`.

```
⊞υ¹Ｆ⊖⊗θ≔⊞Ｏ⮌ＥυΣ…υ⊕λ⁰υ

```

Calculate `A000111(2n-1)`. See my answer to Count alternating permutations.

```
Ｉ÷§υ⁰Ｘ²⊖θ

```

Divide by `2ⁿ⁻¹`.
> 3 votes

# Answer
# Wolfram Language (Mathematica), 21 bytes

```
EulerE[2#-1,0](-2)^#&

```

Try it online!

This is basically the Mathematica code by Vladimir Reshetnikov on OEIS, but golfed down.
> 3 votes

# Answer
# Python 2, 99 bytes

```
D=[1]
i=0
while 1:exec"D[::-1]=D\nfor k in range(i):D[k+1]+=D[k]\n"*2;D+=0,;print(D[i]<<i)/-~i;i+=1
```

Attempt This Online!

-14 bytes thanks to @ovs

Based on Peter Luschny's program on the OEIS page.

Full program which prints the sequence infinitely.

`exec"..."*2` performs two cumulative sums on `D`, first backwards, then forwards.

A backwards cumulative sum is equivalent to:

```
D.reverse()
D.normal_cumulative_sum()
D.unreverse()

```

Since "unreverse" is the same as reverse, the overall sequence of operations becomes:

```
D.reverse()
D.normal_cumulative_sum()
D.reverse()
D.normal_cumulative_sum()

```

and this can be extracted into a snippet of code which we just call twice.

`D[::-1]=D` is a horrible way of reversing `D` in-place, which is two bytes shorter than `D.reverse()`. Unlike the more obvious `D=D[::-1]`, it doesn't reassign `D` (it mutates it in-place), which means it can be done in a function without having to use the `global` keyword.
> 2 votes

# Answer
# PARI/GP, 27 bytes

```
n->(-2)^n*eulerpol(2*n-1)%x
```

Attempt This Online!

Based on the Mathematica code by Vladimir Reshetnikov on OEIS.
> 2 votes

# Answer
# Python, 125 bytes

```
C=lambda n,k:n==k or C(n-1,k)*n//(n-k)
def f(n):
    s=i=0
    while(i<n)*n:j=n-i-1;s+=f(i)*f(j)*C(2*n,2*i+1);i+=1
    return s//2or 1
```

Attempt This Online!
> 2 votes

# Answer
# Python, ~~58~~ 56 bytes

-2 jezza\_99

```
lambda n:2*(-2)**n*polylog(1-2*n,-1)
from mpmath import*

```

Attempt This Online!

Ported from code by Vladimir Reshetnikov from the OEIS page (A002105)
> 2 votes

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

```
f=(n,s=0,l=1)=>n?s*f(n-=.5,s-1,l+1)+l*f(n,s+1,l):!s

```

Try it online!

This program output `true` for `n=0`. 1 more byte is required to convert it into `1`.

```
f=(
  n,    // nodes: `2*n` is number of nodes remaining
  s=0,  // slots: how many nodes with 1 child currently
  l=1   // leaves: how many leaf nodes currently
)=>
  n? // is all nodes placed on the tree?
    s*f(n-=.5,s-1,l+1)+ // chose a non-leaf node, place it as an child
    l*f(n,s+1,l):       // chose a leaf node, place it as an child
  !s // make sure all non-leaf nodes have 2 children

```
> 2 votes

# Answer
# JavaScript (ES6),  ~~66~~  65 bytes

Returns the \\$n\\$-th term, 0-indexed.

Uses @Neil's method.

```
n=>(g=a=>i<2*n?g([s,...a.map(_=>s+=a[--j],j=i++)]):s>>n)([i=s=1])

```

Try it online!
> 1 votes

# Answer
# Factor \+ `math.extras`, ~~54~~ 51 bytes

```
[| n | n 2^ 4 n ^ 1 - * n 2 * bernoulli abs * n / ]

```

Try it online!

Uses the following formula from the title of OEIS A002105:

$$\large\frac{2^n\times(2^{2n}-1)\times|\text{bernoulli}(2n)|}{n}$$

-3 bytes from peeking at @Noodle9's SageMath answer which combines \\$2^{2n}\\$ into \\$4^n\\$.
> 0 votes

# Answer
# , ~~55~~ 51 bytes

```
\(n){for(i in 2:(2*n))T=rev(diffinv(T));T[1]/2^n*2}
```

Attempt This Online!

Uses the `A002105(n) = A000111(2n-1)/2ⁿ⁻¹` trick found by @Neil, and my answer to Count alternating permutations (calculating A000111).
> 0 votes

---
Tags: code-golf, combinatorics, permutations, graph-theory, binary-tree
---


title: Average-ignorant sets of integers

text:
# Question
Title: Average-ignorant sets of integers
Recently a friend of mine posed the following:

> What subset of the integers satisfies the condition if distinct a and b are in the subset, their average is not in the subset? I know the set of non-0 squares satisfies the condition, but I wonder if there exists a more... dense set that satisfies the condition.

(It turns out my friend was wrong about "the set of non-0 squares satisfies the condition", just ignore that.)

Now, I thought I could turn this into a coding challenge.

The goal of this challenge is to submit a function \\$f: \mathbb{N} \to \\{\top, \bot\\}\\$ which takes in a positive integer and returns a boolean satisfying the conditions in the "Rules" section.

Your score is the length of your program in bytes. Program \\$A\\$ is better than program \\$B\\$ if \\$A\\$ is shorter than \\$B\\$.

# Rules

* For any distinct \\$a, b\\$ so that \\$f(a)\\$ is true, \\$f(b)\\$ is true and \\$a+b\\$ is even, then \\$f(\frac{a+b}{2})\\$ is false.
* Let \\$e: \mathbb{N} \to \mathbb{N}\\$ be defined as \\$e(x) = \text{the } x^{\text{th}} \text{ number so that } f(x) \text{ is true}\\$. Then, there exists some \\$m\\$ so that \\$e(n) \< n^2\\$ for all \\$n \geq m\\$.
* The set \\$\\{a: f(a) \text{ is true}\\}\\$ is infinite, i.e. you can't make \\$f\\$ hold for only finitely many values.

# Leaderboard

1. allxy \- 4 bytes (Jelly)
2. Neil \- 6 bytes (Charcoal)
3. m90 \- 10 bytes (x86 32-bit machine code)
4. m90 \- 12 bytes (Re:direction)
5. Dominic van Essen \- 15 bytes (BQN)
6. knomologs \- 20 bytes (МК-52/МК-61)
7. alephalpha \- 22 bytes (PARI/GP)
8. chunes \- 23 bytes (Factor + `math.unicode`) (tied with #8)
9. G B \- 23 bytes (Ruby) (tied with #7)
10. Neil \- 26 bytes (Retina 0.8.2)
11. Arnauld \- 28 bytes (JavaScript ES6)
12. loopy walt \- 31 bytes (Python 2)
13. loopy walt \- 33 bytes (Python)
14. solid.py \- 50 bytes (Python 3.6)
15. friddo \- 68 bytes (Python 3.8)
16. Kevin Cruijssen \- 110 bytes (Whitespace)

# Answer
A simple greedy approach gives the set `[1, 2, 4, 5, 10, 11, 13, 14...]`. This is probably optimal.

It can be constructed by:

* Start with the set `[1]`
* Forever:
    + Take the maximum value of the set, double it, and subtract 1
    + Add that to each value of the set
    + Append that to the current set

Here's an example program to do this.

After a bit of digging on OEIS, we find that the sequence we're looking for is A003278.

A more convenient way of constructing this set is to use one of the definitions on said OEIS page - Try it Online!

This one takes the infinite list of nonnegative integers, converts each to binary and from ternary, and increments them.

This definition is really easy to implement as a check. We simply check that (n-1) in ternary contains no twos.

The sequence plus or minus any constant has the same properties so we can check if n in ternary contains no twos. Thanks to Jonathan Allan for this insight, saving a byte on both versions.

Finally:

# Vyxal, 5 bytes

```
3τ2<A

```

Try it Online!

```
3τ    # Convert to base 3
    A # Are all elements
  2<  # Less than 2?

```

Jelly has a convenient builtin for this which saves a byte:

# Jelly, 4 bytes

```
b3ỊȦ

```

Try it online!

```
b3   # Convert to base 3
   Ȧ # Are all elements
  Ị  # Less than two?

```
> 15 votes

# Answer
# Python 2, 27 bytes

```
f=lambda n:n>n%3/2>-f(n/3)

```

Try it online!

Swaps True and False.

### Python 2, 29 bytes (@xnor)

```
f=lambda n:n<1or n%3<2*f(n/3)

```

Try it online!

Thanks to @Jonathan Allan for convincing me that @xnor's switching to A005836 (without its first element) is actually perfectly good.

### Python 2, 31 bytes (@KevinCruijssen)

```
f=lambda n:n<2or n%3>0<f(n/3+1)
```

Attempt This Online!

Improved logic is inspired by @alephalpha's PARI/GP answer. Could save another two bytes by allowing any nonzero value for True.

### Python, 33 bytes

```
f=lambda n:n<2or n%3and f(n//3+1)
```

Attempt This Online!

Uses the base 3 characterisation at OEIS. Returns 0 and True.
> 4 votes

# Answer
# Charcoal, ~~7~~ 6 bytes

```
›²⌈↨Ｎ³

```

Try it online! Link is to verbose version of code. Outputs `-` if the input is a member of A005836, nothing if not. Explanation: Another port of @allxy's solution.

```
 ²      Literal integer `2`
›       Is greater than
  ⌈     Maximum of
    Ｎ   Input number
   ↨    Converted to base
     ³  Literal integer `3`
        Implicitly print

```

Previous 7-byte version:

```
›2⌈⍘⊖Ｎ³

```

Try it online! Link is to verbose version of code. Outputs `-` if the input is a member of A003278, nothing if not. Explanation:

```
 2      Literal characater `2`
›       Is greater than
  ⌈     Maximum of
     Ｎ  Input integer
    ⊖   Decremented
   ⍘    Converted to base
      ³ Literal integer `3`
        Implicitly print

```

String base conversion is used because array base conversion returns an empty array for an input of `1` (decremented) which has no maximum.

A003278 is infinitesimally denser than A005836 because it effectively includes an extra element at the beginning, so given any finite integer, the number of terms in A003278 less than that integer is always at least as many as the number of terms in A005836 less than that integer, but I don't know whether A003278 always beats all other possible subsets in this way.
> 3 votes

# Answer
# Regex (or Retina), 9 bytes

```
^[0268]*$

```

Try it online!

For any two different numbers composed of 0, 2, 6, 8 in decimal, at any digit position where they differ, their average has 1, 3, 4, 5, or 7, and thus does not satisfy the condition.

This condition includes asymptotically \\$ 4^{log\_{10}n} = n^{log\_{10}4} \approx n^{0.602}\\$ of the first \\$n\\$ numbers.
> 3 votes

# Answer
# JavaScript (ES6), 25 bytes

A port of loopy walt's answer.

24 bytes if we can return zero / non-zero.

```
f=n=>n<2||n%3&&f(-~(n/3))

```

Try it online!
> 2 votes

# Answer
# PARI/GP, 22 bytes

```
f(n)=n<2||f(n\3+1)*n%3
```

Attempt This Online!

A port of loopy walt's Python answer.
> 2 votes

# Answer
# Электроника МК-52/МК-61, 20 bytes

```
X→П0 3 - Fx≥0 18 П→X0 3 ÷ K{x} Fx≠0 19 FBx K[x] 1 + X→П0 БП 01 1 С/П

```

or, in bytecode:

```
40 03 11 59 18 60 03 13 35 57 19 0F 34 01 10 40 51 01 01 50

```

Port of loopyWalt's Python answer.

The MK-52 and MK-61 were the most advanced Soviet programmable calculators to use keystroke programming (later models, like the MK-85 and MK-90, had a form of BASIC). Despite looking more like macros than "real" programs, the language is actually Turing-complete. Each instruction occupies 1 byte in memory. Code-golfing was in fact very popular with these calculators in the 80s, because one had to fit the program in 104 bytes – however, even quite complex games were written with this limitation.

Online emulator here. Turn on the calculator (switch labeled Вкл), paste the above bytecode into the text area on the right and click "Ввести в память" ("Write to memory"). Input number into calculator and press В/О, then С/П to run program. Outputs 1 for true and 0 for false (not exactly quickly though...)
> 2 votes

# Answer
# Re:direction, 12 bytes

```
+++>
v +>
 <

```

Try it online!

Outputs by exit code, 0 for False and 1 (by queue underflow) for True. (This is a bit dubious; it matches the usual convention for numbers in general, but is the opposite of the convention normally used for exit codes.)

The condition used is that the number consists only of 0s and 2s in ternary, which is another variation that also works. This program goes into an infinite loop on 0, which thankfully does not need to be handled.

The following notation will be used for the contents of the queue: a number means that many s, and `|` means one . If the input number is N, the initial queue is `N|`.

The possibilities are as shown:
> 2 votes

# Answer
# Python 3.8 (pre-release), 68 bytes

```
lambda n,s={1}:any(n in(s:=s|{a+max(s)*2-1for a in s})for _ in[0]*n)

```

Try it online!

By no means the shortest solution, but a fun one!
Builds up the set using the method described by @allxy's Jelly answer and checks if n is in it.
> 1 votes

# Answer
# Retina 0.8.2, 26 bytes

```
.+
$*
+`^1?(1*)\1\1$
$1
^$

```

Try it online! Link includes test cases. Outputs `1` if the input is a member of A005836, `0` if not. Explanation:

```
.+
$*

```

Convert to unary.

```
+`

```

Repeat as many times as possible...

```
^1?(1*)\1\1$
$1

```

... integer divide by `3`, but only if the remainder is not `2`.

```
^$

```

Test to see whether it was possible to reach `0`.
> 1 votes

# Answer
# Factor \+ `math.unicode`, 23 bytes

```
[ 1 - 3 >base "10"⊂ ]

```

Try it online!

Based on @allxy's Vyxal/Jelly answers. Subtract 1 from the input, convert it to base 3, but instead of checking whether each digit is less than two, check whether the result is a subset of `"10"` since that's shorter in Factor.
> 1 votes

# Answer
# Ruby, 23 bytes

```
->n{(n-1).to_s(3)!~/2/}

```

Try it online!
> 1 votes

# Answer
# Whitespace, 110 bytes

```
[S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input][N
S S N
_Create_Label_FUNC][S N
S _Duplicate_input][S S S T S N
_Push_2][T  S S T   _Subtract][N
T   T   T   N
_If_negative_Jump_to_Label_TRUTHY][S N
S _Duplicate_input][S S S T T   N
_Push_3][T  S T T   _Modulo][S S S N
_Push_0][S N
T   _Swap_top_two][T    S S T   _Subtract][N
T   T   S N
_If_negative_Jump_to_label_CONTINUE][N
N
N
_Exit_Program][N
S S S N
_Create_Label_CONTINUE][S S S T T   N
_Push_3][T  S T S _Integer_divide][S S S T  N
_Push_1][T  S S S _Add][N
S N
N
_Jump_to_Label_FUNC][N
S S T   N
_Create_Label_TRUTHY][S S S T   N
_Push_1][T  N
S T _Print_1_as_number]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Port of *@loopyWalt*'s Python answer.

Whitespace doesn't have any booleans, but this will output `1` for truthy and nothing for falsey (could also output `0` for falsey at the cost of 8 additional bytes).

**Try it online** (with raw spaces, tabs and new-lines only).

### Explanation in pseudo-code:

```
Integer n = STDIN as number
FUNC:
  If(n-2 is negative):
    Jump to TRUTHY
  If(0-(n%3-1) is negative):
    Jump to CONTINUE
  Exit program (falsey result)

CONTINUE:
  n = n//3+1
  Jump to FUNC

TRUTHY:
  Print 1 as number to STDOUT
  (implicitly stop the program with an error stating 'no exit is defined')

```
> 1 votes

# Answer
# BQN, ~~15~~ ~~14~~ 13 bytes

*Edit: -1 byte thanks to Razetime*

```
⌊´2-3|⊢⌊∘÷3⋆↕

```

Try it at BQN online REPL

```
             ↕      # range from 0...input-1
           3⋆       # get 3 to the power of those
        ⌊∘÷         # now use these to divide & floor (=integer division)
       ⊢            # the input
     3|             # get each one modulo 3
   2-               # subtract it from 2
 ⌊´                 # and find the minimum

```

The final  ~~`2>·⌈´`~~  `⌊´2-` part seems a bit clunky to me (although now improved a bit): I'd want to be able to do something like `¬2∊` (NOT is `2` a member of), but unfortunately this returns an array which doesn't seem to work as a boolean.
> 1 votes

# Answer
# x86 32-bit machine code, 10 bytes

```
48 25 AA AA AA AA 0F 94 C0 C3

```

Try it online!

Uses the `regparm(1)` calling convention – argument in EAX, result in AL.

This implements a slightly different criterion from the one most other answers use: n-1 consists of only 0s and 1s in base *4*. This still works, and barely satisfies the \\$e(n) \< n^2\\$ condition; removing the subtraction of 1 would make it fail that condition.

This modified criterion is simple to implement, by checking whether the odd-position bits in n-1 are all zero.

In assembly:

```
f:
    dec eax
    and eax, 0xAAAAAAAA
    setz al
    ret

```
> 1 votes

---
Tags: code-golf, number, number-theory, open-ended-function
---


title: Run the Nth characters to get N

text:
# Question
Title: Run the Nth characters to get N
Write the shortest program possible such that when you combine the first character and every Nth character after it into a new program, the output is N. This must work for N = 1, 2, ..., 16.

Another way to say it is, if you *remove* all the characters from your program *except for* the first one and every Nth one after that, the output of the remaining code should be N.

# Example

If your code was

```
ABCDEFGHIJKLMNOP

```

N = 1 results in `ABCDEFGHIJKLMNOP`. Running this should output 1.
N = 2 results in `ACEGIKMO`. Running this should output 2.
N = 3 results in `ADGJMP`. Running this should output 3.
N = 4 results in `AEIM`. Running this should output 4.
N = 5 results in `AFKP`. Running this should output 5.
N = 6 results in `AGM`. Running this should output 6.
N = 7 results in `AHO`. Running this should output 7.
N = 8 results in `AI`. Running this should output 8.
N = 9 results in `AJ`. Running this should output 9.
N = 10 results in `AK`. Running this should output 10.
N = 11 results in `AL`. Running this should output 11.
N = 12 results in `AM`. Running this should output 12.
N = 13 results in `AN`. Running this should output 13.
N = 14 results in `AO`. Running this should output 14.
N = 15 results in `AP`. Running this should output 15.
N = 16 results in `A`. Running this should output 16.

# Details

* All characters are allowed, ASCII and non-ASCII. (Newlines and unprintable ASCII are allowed as well. Note that carriage return and line feed count as distinct characters.)
* Your score is the length *in characters* of your unaltered program (15 in example). The lowest score wins.
* A score below 16 is clearly impossible because then at least two of the altered programs would be identical.
* Output may be to a file or stdout or anything else reasonable. However, the output of the 16 different programs must all go to the same place (e.g. it's not ok if `AO` goes to stdout but `A` goes to a file). There is no input.
* The output must be in decimal, not hex. The actual output should only contain the 1 or 2 characters that make up the number from 1 to 16, nothing else. (Things like Matlab's `ans =`  are ok.)
* Your program does not have to work for N = 17 or above.

# Answer
> 14 votes
## APL, 49

```
⌊⊃⍟○7⍟⍟1|/2111118 9⍝×-1 ×○3×4_5_×   1_   _⍝_⍝ __2

```

**Altered programs**

```
1  ⌊⊃⍟○7⍟⍟1|/2111118 9⍝×-1 ×○3×4_5_×   1_   _⍝_⍝ __2
2  ⌊⍟7⍟|21189×1×345× 1  ⍝⍝_2
3  ⌊○⍟/119-××5 1 ⍝ 2
4  ⌊7|18××4×1 ⍝2
5  ⌊⍟21×○5
6  ⌊⍟19×51⍝2
7  ⌊11-4 ⍝
8  ⌊|8×× 2
9  ⌊/9×1
10 ⌊2×5
11 ⌊11 ⍝
12 ⌊1×12
13 ⌊13
14 ⌊14⍝
15 ⌊15
16 ⌊8×2

```

**Explaination**

I'll start from the bottom as it would make explaining easier

There are two language feature of APL to keep in mind. One, APL has no operator precedence, statements are always evaluated right to left. Two, many APL functions behave quite differently depending if it is given one argument on its right (monadic) or two arguments on its left *and* right (dyadic).

Monadic  is round down (floor function), Dyadic `×` is obviously multiplication,  comments out rest of the line
This should make these obvious:

```
16 ⌊8×2
15 ⌊15
14 ⌊14⍝
13 ⌊13
12 ⌊1×12
11 ⌊11 ⍝
10 ⌊2×5

```

**9: `⌊/9×1`**
`/` is Reduce. Basically it takes the function of the left and the array on the right, insert the function between every pair of elements of the array and evaluate. (This is called "fold" in some languages)
Here, the right argument is a scalar so `/` does nothing.

**8: `⌊|8×× 2`**
Monadic `×` is the signum function and monadic `|` is the absolute value function So, `× 2` evaluates to `1` and `|8×1` is of course `8`

**7: `⌊11-4 ⍝`** should be obvious

**6: `⌊⍟19×51⍝2`**
Monadic  is natural log
So, `⍟19×51` evaluates to `ln(19×51) = 6.87626...`, and  rounds it down to `6`

**5: `⌊⍟21×○5`**
Monadic  multiplies its argument by π
`⍟21×○5` is `ln(21×5π) = 5.79869...`

**4: `⌊7|18××4×1 ⍝2`**
Dyadic `|` is the mod function
`×4×1` evaluates to `1`, and `7|18×1` is `18 mod 7 = 4`

**3: `⌊○⍟/119-××5 1 ⍝ 2`**
Space-separated values is an array. Note that in APL, when most scalar functions are give array arguments, it is an implicit map.
Dyadic  is log
So `××5 1`, is signum of signum on 5 and 1, which gives `1 1`, `119-1 1` is `¯118 ¯118` (`¯` is just the minus sign. APL has to distinguish between negative numbers and subtraction), and `⍟/¯118 ¯118` is log-118(-118) = 1

**2: `⌊⍟7⍟|21189×1×345× 1 ⍝⍝_2`**
You can work it out yourself

**1: `⌊⊃⍟○7⍟⍟1|/2111118 9⍝×-1 ×○3×4_5_× 1_ _⍝_⍝ __2`**
This one consist of a more complicated use of `/`. If `n` is a number, `F` is a function, and `A` is an array, then `nF/A` takes each group of `n` consecutive entries of `A` and apply `F/`. For example, `2×/1 2 3` takes each pair of consecutive entries (which are `1 2` and `2 3`) and apply `×/` to each group to give `2 6`
So, `1|/2111118 9` just returns `2111118 9` (as it applies `|/` to scalars). Then, `⍟○7⍟⍟` applies ln, then log7 to those numbers, then multiplies them by π and ln again. The numbers that come out the other side are `1.46424... 0.23972...`
Here,  is just used to select the first element of an array.

# Answer
> 22 votes
# Python - ~~1201~~ 1137 (generator: ~~241~~ 218) - Long live the hashes!

**Strategy:**

I tried to start every line with as many hashes as the desired output `n`. Then all other versions will skip this line completely.

The main difficulty, however, was to append the correct number of hashes so that the next run will hit the beginning of the next line exactly. Furthermore, interferences with other versions might occur, e.g. version 16 jumping right into the `print` command of line 5 and so on. So this was a lot of trial and error combined with a helper script for rapid testing.

**Statistics:**

* Characters: ~~1201~~ 1137
* Hashes: ~~1066~~ 1002 (88.1 %)
* Non-hashes: 135 (11.9 %)

**Code:**

```
#
print 1#####
#p#r#i#n#t# #2######################
##p##r##i##n##t## ##3###
###p###r###i###n###t### ###4
####p####r####i####n####t#### ####5#########
#####p#####r#####i#####n#####t##### #####6##########
######p######r######i######n######t###### ######7###########
#######p#######r#######i#######n#######t####### #######8###
########p########r########i########n########t######## ########9##
#########p#########r#########i#########n#########t######### #########1#########0##
##########p##########r##########i##########n##########t########## ##########1##########1##
###########p###########r###########i###########n###########t########### ###########1###########2##
############p############r############i############n############t############ ############1############3##
#############p#############r#############i#############n#############t############# #############1#############4##
##############p##############r##############i##############n##############t############## ##############1##############5##
###############p###############r###############i###############n###############t############### ###############1###############6

```

**Test script:**

```
with open('printn.py', 'r') as f:
    c = f.read()

for n in range(1, 17):
    print "n =", n, "yields",
    exec c[::n]

```

**Output:**

```
n = 1 yields 1
n = 2 yields 2
n = 3 yields 3
n = 4 yields 4
n = 5 yields 5
n = 6 yields 6
n = 7 yields 7
n = 8 yields 8
n = 9 yields 9
n = 10 yields 10
n = 11 yields 11
n = 12 yields 12
n = 13 yields 13
n = 14 yields 14
n = 15 yields 15
n = 16 yields 16

```

---

**Update: A generating script!**

I thought about my solution and that there must be a pattern to generate it algorithmically. So here we go:

```
lines = ['#']
for i in range(1, 17):
    lines.append(('#' * (i - 1)).join('\nprint ' + `i`))
    fail = True
    while fail:
        while ''.join(lines)[::i].find('print ' + `i`) < 0:
            lines[i] = '#' + lines[i]
        fail = False
        for n in range(1, 17):
            try:
                exec ''.join(lines)[::n]
            except:
                lines[i] = '#' + lines[i]
                fail = True
                break
print ''.join(lines)

```

It builds the program line by line:

1. Start with a hash.
2. Append a new line `i` with the `print i` command and `i - 1` hashes in between each two neighboring characters.
3. While the "i-version" (every i-th character) of the current program does not contain the command `print i` (due to misalignment) or any `n`-version with `n in range(1, 17)` throws an exception, add another hash to the previous line.

It actually returned a shorter program than I found manually this morning. (So I updated my solution above.) Furthermore, I'm pretty sure there is no shorter implementation following this pattern. But you never know!

**Golfed version - ~~241~~ 218:**

```
h='#';L=[h];I=range(1,17);J=''.join
for i in I:
 p='print '+`i`;L+=[(h*(i-1)).join('\n'+p)]
 while 1:
  while J(L)[::i].find(p)<0:L[i]=h+L[i]
  try:
   for n in I:exec J(L)[::n]
   break
  except:L[i]=h+L[i]
print J(L)

```

Note that there might be a shorter generator, e.g. by hard-coding the required number of succeeding hashes for each line. But this one computes them itself and could be used for any N \> 16.

# Answer
> 22 votes
# Befunge 93 - Five million seven-hundred sixty-five thousand and seven-hundred and seventy six characters

I demand to be taken seriously...

```
v                                                                               &(720 720 - 80) X SPACE
""""""""""""""""                                                                &(720 720 - 80) X SPACE
1234567890123456                                                                &(720 720 - 80) X SPACE
"""""""""1111111                                                                &(720 720 - 80) X SPACE
,,,,,,,,,"""""""                                                                &(720 720 - 80) X SPACE
@@@@@@@@@,,,,,,,                                                                &(720 720 - 80) X SPACE
         ,,,,,,,                                                                &(720 720 - 80) X SPACE
         @@@@@@@                                                                &(720 720 - 80) X SPACE

```

3 reasons why. 1st reason: a befunge script is always 80x25, so no matter what, there had to be **something** that got reduced on the lines with code. 2nd reason: why that something is about 5.5 million spaces is because 720 720 is the smallest common multiple of 1 to 16... Means there will be no wrap around mess when we're skipping characters. 3rd reason: wow, this is pretty absurd.

# Answer
> 16 votes
# 209 characters (Various languages)

I just tried to keep things simple and avoid putting anything in positions with a lot of prime factors. The advantage is an ability to run in many scripting languages. It should work in any language that is not deliberately perverse and has the following features:

* Integer literals
* Basic arithmetic operators +, - (subtraction and negation), \*, /
* Prints the evaluation of a bare expression
* Has a single character that begins a line comment

For example,

## Python 2 command-line interpreter (though not from a file):

```
+                1 #            4 /   23      #    #   5            #            9   #            7   6 *         #    # -        5     2   *  -        ##  2        6   #2                     *   2       6   4

```

## MATLAB (simply replace '#' with '%'):

```
                 1 %            4 /   23      %    %   5            %            9   %            7   6 *         %    % -        5     2   *  -        %%  2        6   %2                     *   2       6   4

```

N.B. There should be 17 spaces preceding the first '1'. You guys know a lot of languages, so please help me list more that it could run in ( :

### EDIT: Added unary + at position 0 for Python to avoid the line being indented.

# Answer
> 9 votes
# CJam, 89 bytes

```
GiiAHH(5A5(7ii)ii;(;(-i((i(-i)i)ii)i()i((i(i(iiii(iii(iiiii(iiiii(i-i(iiiiiii(ii(ii(-ii-

```

This approach doesn't use any kind of comments.

`i` casts to integer, so it is a noop here. It could be replaced by whitespace, but the letters seem more readable to me...

Try it online by executing the following *Code*:

```
G,{)
"GiiAHH(5A5(7ii)ii;(;(-i((i(-i)i)ii)i()i((i(i(iiiii(iii(iiiii(iiiii(i-i(iiiiiii(ii(ii(-ii-"
%_~}%N*

```

### Example run

```
$ cat nth-char.cjam
G,{)"GiiAHH(5A5(7ii)ii;(;(-i((i(-i)i)ii)i()i((i(i(i
iii(iii(iiiii(iiiii(i-i(iiiiiii(ii(ii(-ii-"%_~}%N*N
$ cjam nth-char.cjam
GiiAHH(5A5(7ii)ii;(;(-i((i(-i)i)ii)i()i((i(i(i
iii(iii(iiiii(iiiii(i-i(iiiiiii(ii(ii(-ii-
1
GiH(A(i)i((i((iii)(i(((
i(i(ii(ii(-(iii(ii(i-
2
GA(5ii(-(-ii(((iii(i(i(iii(((i
3
GHAii((ii(((iii(i-iii(-
4
GH(i(iii(i(i(i(ii-
5
G(i((i((i(((i((
6
G5)-ii(iii(i(
7
GAi(i(iiiii-
8
G5(-(i(ii(
9
G((i((((i
10
G7ii(i(i-
11
Gi((i(i(
12
Gi((ii(
13
G)i(i((
14
Giii(i
15
Giiiii
16

```

# Answer
> 7 votes
# GolfScript, 61 bytes

```
1})_#;#;;00123358_(_};}_}_}} _}_(__6
_})4_)_+)__(__}__;_}___6

```

This takes advantage of comments (`#`) and the undocumented "super-comments" (everything following an unmatched `}` it is silently ignored).

`_` is a noop. It could be replaced by whitespace, but the underscores seem more readable to me...

Try it online.

# Example run

```
$ cat nth-char.gs
16,{)"1})_#;#;;00123358_(_};}_}_}} _}_(__6
_})4_)_+)__(__}__;_}___6"\%.~}%n*
$ golfscript nth-char.gs
1})_#;#;;00123358_(_};}_}_}} _}_(__6
_})4_)_+)__(__}__;_}___6
1
1)##;0238(}}}} }(_
}4)+_(__;}_6
2
1_#025(;}}}_
)))(};_6
3
1#;28}} (
4+(_}6
4
1;05}_}64)__6
5
1#2(}}
)(;6
6
1;3; 6)_}
7
1;8}(4(}
8
10(}
);
9
10}}4_6
10
11}_+_
11
12}
(6
12
13})_
13
13 )}
14
15})6
15
18((
16

```

# Answer
> 5 votes
# Zsh, 249 bytes

```
b
y
e

2y
y
yyyy
e
bye 1
e e
e
e

9

1

1

11

1

13

4

5

6

b

b

b
y
y
y

e

6

8

1

0

b

b

y

e

e

7b

y

e

1

5

2

b
b
yy

e

3
4
```

Verify all slices online!

Every sliced program is of the form:

```
[...junk]
bye N
[junk...]

```

For example, for \\$ N = 8 \\$:

```
b2y1e
 11
6

bye 8

y

 e
2
be4

```

Attempt This Online!

The only code that matters is the `bye 8`, which exits the program with the exit code of 8.

The rest of the junk is just ignored by zsh, because it's all invalid commands. (Everything after the first valid `bye` also doesn't matter, because it never gets executed).

---

To optimise this answer, we want to interleave the programs `bye 1`, `b y e 2`, `b y e 3`, etc., so that:

* every program starts at an offset that is a multiple of its corresponding value of \\$ N \\$
* none of the programs "overlap", putting different characters in the same place, which will break the code
* the total length is minimised (of course)

This problem boils down to searching over the permutations of \\$ \[1, 16\] \\$, and then inserting each program in the chosen order at the first valid offset in the output code.

I tried various strategies to solve these constraints, including some obvious orderings picked by hand, and a greedy breadth-first search, but the most successful was a crude "Monte Carlo" method:

1. shuffle the range into a particular order
2. arrange the programs in that order
3. if this solution was shorter than the previous iteration, then save it as the current shortest possibility
4. repeat ad nauseam

Here's my optimiser code, in Python:

```
import re, random, time

def valid(code, n):
    match = pattern.search(''.join(code))
    return match and match[1] == str(n)

pattern = re.compile(r"^\s*bye\s+(\d+)\s*$", re.MULTILINE)

# for repeatability
seed = int(time.time() * 1e6)
print(f"{seed=}")
random.seed(seed)

ns = list(range(1, 17))

# it's pretty much guaranteed we'll find a solution shorter than this fake one
result = "dummy" * 100

while True:
    code = ["\n"] * 1000
    random.shuffle(ns)
    used = set()
    for n in ns:
        used.add(n)
        out = code.copy()
        insert = f"bye {n}"
        offset = 0
        out[offset:offset + len(insert) * n:n] = insert
        while not all(valid(out[::i], i) for i in used):
            offset += n
            if offset >= 250:
                # too long
                break
            out = code.copy()
            out[offset:offset + len(insert) * n:n] = insert
        # hack to propogate break
        else:
            code = out
            continue
        break
    else:
        candidate = "".join(code).rstrip("\n")
        if len(candidate) < len(result):
            result = candidate
            print("------")
            print("length:", len(result))
            print(result)
```

Attempt This Online! (but due to ATO's timeout and non-streaming nature, this is probably better run on your actual computer)

---
Tags: code-golf, source-layout
---


title: Fill the rectangle

text:
# Question
Title: Fill the rectangle
## Challenge

In this challenge, you have to fill an \\$M\\$ x \\$N\\$ rectangle grid with the most \\$A\\$ x \\$B\\$ rectangle pieces possible.

Requirements:

* The sizes of the \\$M\\$ x \\$N\\$ rectangle grid is always bigger than the sizes of the \\$A\\$ x \\$B\\$ rectangle pieces. In other words, \\$min(M, N) ≥ max(A, B)\\$
* You can freely rotate the \\$A\\$ x \\$B\\$ rectangle pieces.
* Those \\$A\\$ x \\$B\\$ rectangle pieces can touch each other on the edge, but it cannot overlap each other.
* Those \\$A\\$ x \\$B\\$ rectangle pieces, or part of it, cannot be outside of the \\$M\\$ x \\$N\\$ rectangle grid.
* You don't have to fill the whole \\$M\\$ x \\$N\\$ rectangle grid, because sometimes that is impossible.

## Example

Given a \\$5\\$ x \\$5\\$ rectangle grid (or square) like below:

And you have to fill it with \\$2\\$ x \\$2\\$ rectangle (or square) pieces. The best you can do is \\$4\\$, like below:

## Input/Output

Input can be taken in any resonable format, containing the size of the \\$M\\$ x \\$N\\$ rectangle grid and the \\$A\\$ x \\$B\\$ rectangle pieces.

Output can also be taken in any resonable format, containing the most number of pieces possible.

Example Input/Output:

```
Input         -> Output
[5, 5] [2, 2] -> 4
[5, 6] [2, 3] -> 5
[3, 5] [1, 2] -> 7
[4, 6] [1, 2] -> 12
[10, 10] [1, 4] -> 24

```

This is , so shortest answer (in bytes) wins!

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

Expects `(m,n,[a,b])` with all values passed as BigInts.

```
(m,n,a,M,g=(p,y,i)=>q=i--&&p>>y*~m|g(p,~-y,i))=>(h=(k,N,x,y)=>{for(y=n;--y;)for(x=m;x--;)a.map((v,i)=>k&g(2n**v-1n<<x,y,a[i^1])?M>N?0:M=N:h(k|q,N+1))})(g(1n<<m,n,++n)|~-q,0)|M

```

Try it online!

### How?

This is a (slow) brute-force search over a single BigInt bitmask representing the entire board with left and bottom borders.

For instance, a \\$2\times3\\$ board is initialized to \\$2343\\$, which is \\$100100100111\\$ in binary. Once re-arranged in 2D, this gives:

$$\begin{matrix}1&0&0\\1&0&0\\1&0&0\\1&1&1\end{matrix}$$

We use the helper function \\$g\\$ to create the bitmask \\$q\\$ of a rectangle:

```
g = (          // g is a recursive function taking:
  p,           //   p = row pattern
  y,           //   y = starting row
  i            //   i = remaining number of rows
) =>           //
q =            // save the final result in q
  i-- &&       // decrement i; stop if it was 0
  p            // insert the pattern
  >> y * ~m |  // shifted to the left by y * (m+1) positions
               // (we actually do a shift to the right by
               // y * (-m-1), which doesn't work as expected
               // with Numbers but works fine with BigInts)
  g(p, ~-y, i) // do a recursive call with y - 1

```

We use `g(1n << m, n, ++n) | ~-q` to initialize the board: the call to \\$g\\$ creates the left border and the bitwise OR with \\$q-1\\$ appends the bottom border.

We use \\$g\\$ again to create the smaller rectangles of size \\$A\times B\\$ and \\$B\times A\\$. We test collisions with bitwise ANDs and add them to the board with bitwise ORs.
> 4 votes

# Answer
# Charcoal, ~~95~~ 92 bytes

```
ＮθＮη≔Ｅ²Ｎζ⊞υ×⊖Ｘ²θ÷⊖Ｘ²×η⊕θ⊖Ｘ²⊕θＦ×η⊕θＦ×Ｘ²ιＥＸ²⟦ζ⮌ζ⟧×⊖⊟κ÷⊖Ｘ⊟κ⊕θ⊖Ｘ²⊕θＦυＦ⁼κ＆λκ⊞υ⁻λκＵＭυΣ⍘ι²Ｉ÷⁻⌈υ⌊υΠζ

```

Try it online! Link is to verbose version of code. Explanation: Brute-force breadth-first search, so very slow.

```
ＮθＮη

```

Input the dimensions of the grid to be filled.

```
≔Ｅ²Ｎζ

```

Input the dimensions of the rectangle.

```
⊞υ×⊖Ｘ²θ÷⊖Ｘ²×η⊕θ⊖Ｘ²⊕θ

```

Start a breadth-first search with a bitmask representing an empty grid.

```
Ｆ×η⊕θ

```

Loop over all the possible top left corners of the rectangle, and some impossible ones too.

```
Ｆ×Ｘ²ιＥＸ²⟦ζ⮌ζ⟧×⊖⊟κ÷⊖Ｘ⊟κ⊕θ⊖Ｘ²⊕θ

```

Calculate and loop over the bitmasks for both orientations of the rectangle at this position.

```
Ｆυ

```

Loop over the grid layouts found so far.

```
Ｆ⁼κ＆λκ

```

If the rectangle can be placed at this position...

```
⊞υ⁻λκ

```

... then add a new layout with the updated grid.

```
ＵＭυΣ⍘ι²

```

Calculate the number of squares left on each grid.

```
Ｉ÷⁻⌈υ⌊υΠζ

```

Divide the difference between the maximum (i.e. the original area of the grid) and minimum by the area of the rectangle.
> 3 votes

# Answer
# Python3, 460 bytes:

```
R=range
S=lambda x,y:[(X,Y)for X in R(x)for Y in R(y)]
def L(m,X,Y,w,h):
 m=eval(str(m))
 for x,y in S(X,Y):
  if 0==m[y][x]and Y-y>=h and X-x>=w:
   for j,k in S(h,w):
    if m[y+j][x+k]:return
    m[y+j][x+k]=1
   return m
def f(a,b):
 m=[[0 for _ in R(a[0])]for _ in R(a[1])]
 q,s,l=[(m,0)],[],[]
 while q:
  m,c=q.pop(0);l+=[c]
  if(t:=L(m,*a,*b))and t not in s:q+=[(t,c+1)];s+=[t]
  if(t:=L(m,*a,*b[::-1]))and t not in s:q+=[(t,c+1)];s+=[t]
 return max(l)

```

Try it online!
> 3 votes

# Answer
# Jelly, 22 bytes

```
Rṡ"p/⁺€ɗⱮṚƬ}ẎŒPẎQƑ$ƇṪL

```

A dyadic Link that accepts the large rectangle dimensions, `[M, N]`, on the left and the small rectangle dimensions, `[A, B]`, on the right and yields the maximal count.

**Try it online!** Too slow to complete on TIO for any other test case.

### How?

Dumb brute-force...
Creates all possible sub-rectangles where each one is a list of the cell coordinates it covers in the \\$M\\$ by \\$N\\$ rectangle. Then filters the collection of every possible set of distinct sub-rectangles keeping only those with no overlap (repeated coordinate) and outputs the length of (one of) the longest one(s).

```
Rṡ"p/⁺€ɗⱮṚƬ}ẎŒPẎQƑ$ƇṪL - Link: [M, N]; [A, B]
R                      - range -> [[1..M], [1..N]]
           }           - use right argument, [A, B], with:
          Ƭ            -   collect up until no change applying:
         Ṛ             -     reverse
                           -> [[A, B], [B, A]] ...or [[A, B]] if A==B
        Ɱ              - map - i.e. for [i,j] in those apply:
       ɗ               -   last three links as a dyad - f([[1..M], [1..N]], [i,j]):
  "                    -     zip with - i.e. [f(l=[1..M], r=i), f(l=[1..N], r=j)]:
 ṡ                     -       all sublists of l of length r
    /                  -     reduce by:
   p                   -       Cartesian product
      €                -     for each:
     ⁺                 -       repeat (reduce by Cartesian product)
            Ẏ          - tighten -> all possible A by B or B by A sub-rectangles
                                    as 1-indexed coordinates
             ŒP        - powerset (Note: elements cardinality is non-decreasing)
                   Ƈ   - filter keep those for which:
                  $    -   last two links as a monad:
               Ẏ       -     tighten
                 Ƒ     -     is invariant under?:
                Q      -       deduplicate (i.e. we keep those with no overlap)
                    Ṫ  - tail (the/one way to maximise small rectangles)
                     L - length

```
> 2 votes

---
Tags: code-golf
---


title: Scribble Pad for Nerds

text:
# Question
Title: Scribble Pad for Nerds
aka. implement an easier version of 05ab1e's canvas element.

# Description

The canvas element is used to draw ASCII lines on the screen.
The (easier version of the) canvas element takes a list of integers and returns a multi-line string (or a list of strings). The integers map to the following directions:

```
7   0   1
  ↖ ↑ ↗
6 ← X → 2
  ↙ ↓ ↘
5   4   3

0: upwards
1: top-right
2: right
3: bottom-right
4: downwards
5: bottom-left
6: left
7: top-left

```

If given eg. `[6, 4, 2]`, it outputs this:

```
###
#
###

```
1. Start with one hash already drawn (`X`)
2. Draw two hashes towards the left (direction `6`)
3. Draw two hashes downwards (direction `4`)
4. Draw two hashes towards the right (direction `2`)

# Rules

* Default Loopholes apply
* Multiple integers or a list of integers will be given as the input
* Output must be a string, a list of strings, or a matrix of characters (like a binary matrix)
* You will not receive directions with intersecting lines
* You can replace `#` with any other constant character, but you'll always have to draw **2** hashes per direction and **start** with a hash
* Excess whitespace is allowed
* The shortest code, as this is , wins

# Examples

In: [1, 5, 3, 7, 5, 1, 7, 3]
Out:
#   #
 # #
  #
 # #
#   #

In: [2, 2, 2, 2, 4, 4, 7, 7]
Out:
#########
     #  #
      # #
       ##
        #

In: [1, 2, 3, 6, 6, 2, 4, 2, 2, 4, 2, 6, 4, 2, 1, 3, 2, 6, 7, 5, 6, 6, 4, 0, 6, 4, 0, 6, 0, 6, 2, 0, 2]
Out:
  ###
 #   #
# #####
    #
  #######
  #     #
###     ### #
  #     #  # #
  #########   ###
    # #
    # #

```
</code></pre>

# Answer
> 13 votes
# Vyxal, 4 bytes

```
×3ø^

```

Try it Online!

# 05AB1E, 3 bytes

```
3$Λ

```

Try it online!

# Answer
> 11 votes
# Charcoal, 9 bytes

```
ＦＡ✳ι##‖↘#

```

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

```
ＦＡ

```

Loop over the directions.

```
✳ι##

```

Print two `#`s in that direction.

```
‖↘

```

Reflect to switch from Charcoal to 05AB1E coordinates. This is because Charcoal's coordinate system has `0` as right and `2` as up etc.

```
#

```

Print the final `#`.

Boring built-in version:

```
ＧＨ✳✳⁻²Ａ³#

```

Try it online! ~~Link is to verbose version of code~~ Unfortunately the version of Charcoal on TIO has a bug in its deverbosifier meaning that it parses `Directions()` as `Direction(s)`. I could use a capital `S`... or you could just Attempt This Online! Link is to verbose version of code. Note that the `PolygonHollow` line drawing code takes the lengths of the lines rather than the number of additional `#`s to draw.

# Answer
> 9 votes
# Jelly,  ~~25~~  22 bytes

<sup>Saved three bytes using the allowance of excess whitespace (this also fixed a bug that meant an input with only left and/or right movements would have printed incorrectly since no space or newline characters were being introduced in such cases).</sup>

```
ı2½*Nx2ŻÆiNṠ+\+L$ŒṬo⁶Y

```

A full program that accepts the list of instructions and prints the result using `1` as the character.

**Try it online!**

### How?

Jelly has no canvas drawing built-ins, so instead this builds a matrix of zeros and ones, with ones at visited locations and prints it with spaces in place of zeros joined with newline characters.

```
ı2½*Nx2ŻÆiNṠ+\+L$ŒṬo⁶Y - Main Link: list of integers from [0,7]:
ı2                     - 2i (twice the square root of -1)
  ½                    - square root
    N                  - negate the input (vectorises)
   *                   - exponentiate (vectorises)
     x2                - repeat each element twice
       Ż               - prefix with a zero
        Æi             - convert each to [real, imaginary] parts
          N            - negate (vectorises)
           Ṡ           - sign (vectorises)
             \         - cumulative reduce by:
            +          -   addition (vectorises)
                $      - last two links as a monad:
               L       -   length
              +        -   add (vectorises)
                 ŒṬ    - matrix with 1s at the indicated [row, column]s
                   o⁶  - logical OR with space character
                     Y - join with newline characters
                       - implicit, smashing print

```

Note: `ı2` is a hack - `ı` should work but there are floating-point errors - for example, `ı½*-2` gives `2.220446049250313e-16-1j` rather than `0-1j`.

# Answer
> 9 votes
# Ruby, 106 bytes

```
->d{m=2*x=y=d.size*2;c=[]
[-5,*d].map{|k|2.times{(c[y+=k==6?0:k%7<=>2]||=[0]*m)[x+=k<1?0:4<=>k]=1}};c-[p]}

```

Try it online! Returns a binary matrix (1 for `#`, 0 for ). A semicolon replaced for a newline for readability's sake (and the same byte count). Produces a lot of leading/trailing spaces in each row (most of the time).

I'm sure there's some more bytes to be shaved but I can't currently see what they are.

## Direction to coordinate formula

I'm not sure if this is the shortest, but I imagine this approach is shorter than an approach by complex exponentiation. For a given direction \\$k\\$, we want to produce the delta directions \\$dx\\$ and \\$dy\\$ to "nudge" our central coordinate along. We can see that, through some formula manipulation, we can do just that:

\begin{array} {|c|c|} \hline k & dx & dy & k\<1 & 4\Leftrightarrow k& & k=6 & k\bmod7 & k\bmod7\Leftrightarrow2 \\ \hline 0 & 0 & -1 & T & 1 & \mathbf{0} & F & 0 & -1 & \mathbf{-1} \\ \hline 1 & 1 & -1 & F & 1 & \mathbf{1} & F & 1 & -1 & \mathbf{-1} \\ \hline 2 & 1 & 0 & F & 1 & \mathbf{1} & F & 2 & 0 & \mathbf{0} \\ \hline 3 & 1 & 1 & F & 1 & \mathbf{1} & F & 3 & 1 & \mathbf{1} \\ \hline 4 & 0 & 1 & F & 0 & \mathbf{0} & F & 4 & 1 & \mathbf{1} \\ \hline 5 & -1 & 1 & F & -1 & \mathbf{-1} & F & 5 & 1 & \mathbf{1} \\ \hline 6 & -1 & 0 & F & -1 & \mathbf{-1} & T & 6 & 1 & \mathbf{0} \\ \hline 7 & -1 & -1 & F & -1 & \mathbf{-1} & F & 0 & -1 & \mathbf{-1} \\ \hline -5 & & & T & 1 & \mathbf{0} & F & 2 & 0 & \mathbf{0} \\ \hline \end{array}

Bolded cells above indicate taking the previous expression, but instead choosing zero if the previous condition holds. In code, we update our coordinates as thus:

```
x += k < 1  ? 0 : 4 <=> k
y += k == 6 ? 0 : k % 7 <=> 2

```

Important to note is that \\$-5\\$, as well as any other number \\$c\<1\\$ for which \\$c\equiv 2\mod 7\\$, produces a 0 in both coordinates, and is useful as a placeholder to mean "no action", and hence a useful initialization instruction.

## Commented code

```
-> d {
  # x and y are initially set to d.size * 2, guaranteeing us sufficient room
  # so that our calculations will not step outside of bounds.
  # m is our minimum width for padding purposes for such a bound, and extends
  # the distance from 0 to x or y in each direction, that is, 2x or 2y
  m = 2 * x = y = d.size * 2
  c = []
  # to account for the initial cell, we prepend -5 to the input (see above table)
  [-5, *d].map { |k|
    # since each line is two characters long, we update each cell individually
    2.times {
      # update y, as per above
      y += k == 6 ? 0 : k % 7 <=> 2
      # get the current row, defaulting to an appropriate row of 0s
      row = c[y] ||= [0] * m
      # update x, as per above
      x += k < 1 ? 0 : 4 <=> k
      # update (x,y) in the output array
      row[x] = 1
    }
  }
  # remove all nil rows from the output array
  c - [p]
}

```

# Answer
> 7 votes
# BQN, ~~79~~ ~~77~~ ~~71~~ ~~67~~ ~~58~~ ~~53~~ 51 bytes

*Saved 5 bytes thanks to att*

```
' '+(¬⊸-↑↑⟜1)∘⋈˜∘¬⟜-∘≠{(∨⌽)´-}4(⊢×○×-)2/8|-⟜2⊸⋈¨

```

Try it at BQN online

### Explanation

New approach!

```
8|-⟜2⊸⋈¨

```

Turn each number in the initial list of directions into a list containing two numbers, the first number shifted two directions counterclockwise (i.e. minus 2, mod 8). These will become the y and x deltas, respectively.

```
2/

```

Repeat each direction twice.

```
4(⊢×○×-)

```

Turn the directions into deltas. We want to implement the following function:

* 0 or 4 -\> 0
* 1, 2, or 3 -\> 1
* 5, 6, or 7 -\> -1

We almost get the desired result if we subtract the input from 4 and take the sign. The only problem is that 0 becomes 1, which we can fix by multiplying by the sign of the input: `sign(4-x) * sign(x)`, in C-like pseudocode. In BQN, `×○×` is a dyadic function that takes the sign of each argument and multiplies them; `(⊢×○×-)` is a dyadic train that passes its right argument and the difference of its arguments to `×○×`; and so if we give it `4` as its left argument and a direction number as its right argument, it will return the desired delta. Since all of the functions used here are pervasive, we can apply them to a list of lists of numbers and get a list of lists of results.

```
(¬⊸-↑↑⟜1)∘⋈˜∘¬⟜-∘≠

```

Call the length of the original list \\$N\\$. (The length of the list of deltas is \\$2N\\$ because we repeated each move twice.) Construct a \\$4N+1\\$ by \\$4N+1\\$ array that is filled with 0s but with a 1 in the exact center.

```
{(∨⌽)´-}

```

Negate each delta and right-fold the list of deltas using the following procedure: Start with the \\$4N+1\\$ array constructed above. At each step, rotate the partial result by the current delta, and then logical OR with another copy of the \\$4N+1\\$ array. The result is a \\$4N+1\\$ by \\$4N+1\\$ array of 0s and 1s.

```
' '+

```

Add a space character, converting the 0s to spaces and the 1s to `!`s.

# Answer
> 3 votes
# Perl 5 \+ `-pl043F`, 63 bytes

```
$_=". "x@F.s/./(<#{DA,A,,B,BD,{B,,A}DD}>)[$&]x2/ger;s/\w/.[$&/g
```

Try it online!

## Explanation

The solution utilises ANSI escape sequences to move the cursor to the required position based on the input commands. First `$_` is reset to `@F` (a list containing each character of the input, which, when interpreted as a scalar, returns the length of the list) repetitions of `\f`  (form-feed followed by space) to move the cursor to a position to allow enough space for the output (hopefully...), concatenated with the original input `s///`ubstituting each digit (`.`) with its index into the `glob` list (`<#{DA,A,,B,BD,{B,,A}DD}>`). This results in a string like: `#A#A#BDD#BDD#B#B#DDA#DDA#BDD#BDD#A#A#DDA#DDA#B#B#` where the letters correspond to the ANSI escape sequence to move either left, up or down. These letters are then replaced with the correct ANSI escape sequences in the final `s///`ubstitution.

Bonus "cat" drawing.

# Answer
> 1 votes
# (gcc): ~~218~~ 210 bytes

**Edit**: Thanks to ceilingcat for shortening the code to *210 bytes*.

```
p=297,C[800]={[297]=3},d,j=800;f(D,n){d^D?:(C[p+=n]=C[p+=n]=3);}main(c,v)char**v;{for(;d=*v[--c]-48,c;f(0,-40))f(7,-41),f(6,-1),f(5,39),f(4,40),f(3,41),f(2,1),f(1,-39);for(;j--;j%40?:puts(""))putchar(C[j]+32);}

```

Try it online (with explanation)

**Explanation**:

```

// Thanks to ceilingcat for shortening the code to 210 bytes

// 'C[800]' is the 2D canvas ('C[20][40]') flattened out to 1D and contains the
// offset of the ASCII character code from 32 (e.g. '#' character code is 35
// but would be stored as 3). This is because initializing an array with any
// other value than 0 is not cheap (space-wise) and in this case it's better to
// just add 32 whenever needed.
// 'p' should point to the middle of the canvas (might be wrong :P).
p=297,C[800]={[297]=3},d,j=800;
// This moves the cursor and draws 2 '#'s in the specified direction 'D'.
f(D,n){d^D?:(C[p+=n]=C[p+=n]=3);}
main(c,v)char**v;{
        // Converts command line arguments to an 'int' and draws on the canvas.
        for(;d=*v[--c]-48,c;f(0,-40))f(7,-41),f(6,-1),f(5,39),f(4,40),f(3,41),f(2,1),f(1,-39);
        // Print the canvas.
        for(;j--;j%40?:puts(""))putchar(C[j]+32);
}

```

# Answer
> 1 votes
# Python 3, 125 bytes

```
from turtle import*
mode("logo")
def f(l,w=write):
 reset();ht();pu();w("#")
 for d in l:seth(d*45);fd(9);w("#");fd(9);w("#")

```

---
Tags: code-golf, ascii-art, array, binary-matrix
---


title: Curry tips for Haskell programmers

text:
# Question
Title: Curry tips for Haskell programmers
Curry is the Language of the Month this month and some users are starting to get into it, so let's get some together.

Haskell and Curry are similar in a lot of ways and a lot of tips for Haskell work well in Curry and vice versa. So I'd like in this question to gather tips for in Curry, that would be useful to someone who has read up on our Haskell tips extensively.

This would cover cool things you can do in Curry that you can't do in Haskell, as well as tips for getting around the cool things you *can't* do in Curry that you might be used to from Haskell.

Please post only one tip per answer.

# Answer
> 11 votes
# Use `++` in patterns

In Haskell we are used to handling lists with `:` as our pattern. Curry1 can do this but it can also use `++` in patterns. This can be used to pattern match longer prefixes for strings, e.g. this Haskell pattern:

```
f('a':'b':'c':x) = ...

```

works in Curry, but can be shorter as:

```
f("abc"++x)=...

```

However it can also match much more exotic things.

```
f(x++"abc"++y)=...

```

This pattern matches all strings that have `abc` as a substring somewhere. This can't even be written as a pattern in Haskell and requires a guard at the minimum.

```
f(a++[b])=...

```

This pattern matches lists ending with the element `b`. It's the sort of pattern that Haskell programmers can attest would certainly be useful for many things.

This can be combined with other tricks to get *even more powerful* patterns, for example:

```
f(a++a)=...

```

This matches strings which are made up two copies of the same string concatenated.

`++` patterns aren't just a way to write certain patterns more efficiently. They allow us to represent much more complex patterns on lists than were even possible before.

---

1: `++` can be used as a pattern in PAKCS, KiCS, and MCC Curry, but does not work in Sloth, so this tip is not applicable there.

# Answer
> 4 votes
# Use `?` as or-patterns

In languages like Mathematica or Rust or Python 3.10, there are some kind of "or-patterns", usually written in the form `a|b`, that could match either `a` or `b`. Haskell doesn't have such thing. But in Curry, you can write `a?b`.

For example, instead of

```
f a=someExpr a
f b=someExpr b

```

You can write:

```
f c@(a?b)=someExpr c

```

Unlike other languages, `?` isn't a special symbol for patterns. It is just a built-in function that returns either of the two values. Using `a?b` in patterns is just another example of functional patterns, just like `a++b` in Wheat Wizard's answer.

---
Tags: code-golf, tips, functional-programming, haskell
---