title: Find Patterns in Strings

text:
# Question
Title: Find Patterns in Strings
In this challence, your task is to locate substrings with a given structure.

# Input

Your input shall be two non-empty alphanumeric strings, a *pattern* `p` and a *text* `t`. The idea is that each character of `p` represents a contiguous non-empty substring of `t` which occur next to each other, and `p` represents their concatenation. Identical characters correspond to identical substrings; for example, the pattern `aa` represents any non-empty square (a string obtained by concatenating a shorter string to itself). Thus the pattern `aa` can match the substring `byebye`, with each `a` matching `bye`.

# Output

If the text `t` contains a substring that `p` matches, then your output shall be that substring, with colons `:` inserted between the strings that correspond to characters of `p`. For example, if we have `t = byebyenow` and `p = aa`, then `bye:bye` is an acceptable output. There may be several choices for the matching substring, but you shall only output one of them.

If `t` does not contain a matching substring, your output shall be a sad face `:(`.

# Rules and Clarifications

Different characters of `p` can correspond to identical substrings, so `p = aba` can match the string `AAA`. Note that the characters must correspond to non-empty strings; in particular, if `p` is longer than `t`, the output must be `:(`.

You can write a full program or a function, and you can also change the order of the two inputs. The lowest byte count wins, and standard loopholes are disallowed.

# Test Cases

Given in the format `pattern text -> output`. Note that other acceptable outputs may exist.

```
a Not -> N
aa Not -> :(
abcd Not -> :(
aaa rerere -> re:re:re
xx ABAAAB -> A:A
MMM ABABBAABBAABBA -> ABBA:ABBA:ABBA
x33x 10100110011001 -> 10:1001:1001:10
abcacb 0a00cca0aa0cc0ca0aa0c00c0aaa0c -> c:a0aa:0c:c:0c:a0aa
abccab 0a00cca0aa0cc0ca0aa0c00c0aaa0c -> a:a:0c0:0c0:a:a
abcbcab 0a00cca0aa0cc0ca0aa0c00c0aaa0c -> :(
abcbdcab 0a00cca0aa0cc0ca0aa0c00c0aaa0c -> 00:c:ca0aa0c:c:0:ca0aa0c:00:c

```

# Answer
# Python, 207 bytes

```
import re
h=lambda x:"a"+str(ord(x))
def g(a,b):
 c,d="",set()
 for e in a:
  c+=["(?P<"+h(e)+">.+)","(?P="+h(e)+")"][e in d]
  d.add(e)
 f=re.search(c,b)
 return f and":".join(f.group(h(e))for e in a)or":("

```

Call with `g(pattern, string)`

Uses the `re` module to do most of the work.
> 6 votes

# Answer
# JavaScript (SpiderMonkey) (ES5.1), 198 bytes

**Since ES6 was released in June 2015, I post the ES5.1 version of the code together with the ES6 equivalent, but declare ES5.1 version as the main answer.**

Greedy match, so the first case returns "Not" instead of "N".

```
function(a,b){c=[o="indexOf"];r=a.split("");return(m=RegExp(r.map(function(i){return(e=c[o](i))>0?"\\"+e:(c.push(i),"(.+)")}).join("")).exec(b))?r.map(function(x){return m[c[o](x)]}).join(":"):":("}

```

Try it online!

# JavaScript (Node.js) (ES6), 141 bytes

```
a=>b=>(c=[o="indexOf"],r=[...a],m=RegExp(r.map(i=>(e=c[o](i))>0?"\\"+e:(c.push(i),"(.+)")).join``).exec(b))?r.map(x=>m[c[o](x)]).join`:`:":("

```

Try it online!

Takes the arguments in currying syntax: `f(a)(b)`

Explanation (and ungolfed):

```
function matchPattern(a, b) {                   // Main function
 var c = ["indexOf"];                           // Array used for the capturing groups
 var r = [...a];                                // Split the pattern first
 var m = RegExp(r.map(function(i) {             // Create the regex
  var e = c.indexOf(i);                         // Check if the character is found before
  if (e > 0)                                    // If so
   return "\\" + e;                             // Append the back reference to the regex
  else {                                        // If not
   c.push(i);                                   // Append the character to the array
   return "(.+)";                               // Append a capturing group to the regex
  }
 }).join("")).exec(b);                          // Execute the regex
 if (m != null)                                 // If the pattern matches the string
  return r.map(function(x) {                    // Replace each letter
   return m[c.indexOf(x)];                      // With the corresponding substring
  }).join(":");                                 // And join them with ":"
 else                                           // If there is no match
  return ":(";                                  // Return ":("
}

```
> 1 votes

# Answer
# Brachylog, 35 bytes

```
sᵗ~cᵗXlᵛ∧Xzdz≠ʰ∧Xt~ṇ{Ḷ∧":"|}ᵐ.∨":("

```

Try it online!

On not-quite-small inputs, ***very*** slow. I-haven't-actually-done-the-sixth-test-case-but-not-for-lack-of-trying slow. (Probably owing to brute-forcing every partition of every substring, starting with the largest, and then checking if it's a match.) Takes input as a list `[pattern,string]`.

### Condensed and divided explanation:

`sᵗ~cᵗX`

X is the pattern paired with a partition of a substring of the input string.

`lᵛ`

The pattern and the partition have the same number of elements.

`Xzdz≠ʰ`

No two unique `pattern char, matched substring` pairs share a pattern character. That is, no pattern character maps to multiple substrings, although multiple pattern characters may map to one substring.

`Xt~ṇ{Ḷ∧":"|}ᵐ.∨":("`

The output is the elements of the partition joined by colons, unless something couldn't be done, in which case it's `:(` instead.

### Monolithic explanation:

```
                                       The input
 ᵗ  ᵗ                                  with its last element replaced with
  ~c                                   a list which concatenates to
s                                      a substring of it
     X                                 is X,
       ᵛ                               the elements of which all have the same
      l                                length.
        ∧                              And,
         X                             X
          z                            zipped
           d                           with duplicate pairs removed
            z                          and zipped back
              ʰ                        has a first element
             ≠                         with no duplicate values.
               ∧                       Furthermore,
                 t                     the last element of
                X                      X
                  ~ṇ                   with its elements joined by newlines
                    {      }ᵐ          where each character of the joined string
                     Ḷ                 is a newline
                      ∧                and
                          |            is replaced with
                       ":"             a colon
                          |            or is passed through unchanged
                             .         is the output.
                              ∨        If doing any part of that is impossible,
                                       the output is
                               ":("    ":(".

```
> 1 votes

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


title: Probabilistic approach puzzle

text:
# Question
Title: Probabilistic approach puzzle
A few hours earlier, I got this puzzle:

> Suppose, you toss a coin n times, then what is the probability of getting m number of heads? ( where m belongs to the *set of all prime numbers*)

For instance, take n = 2, then
`SS = { HH, HT, TH, TT }`

So, output is 1/4 (for HH case)

Then, for n = 3,
`SS = { HHH, HHT, HTH, THH, HTT, THT, TTH, TTT }`

So, output is (1 + 3)/8 (for 3 H's case and 2 H's cases respectively)

**Input**: n ( an integer, 0 \<= n \<= 1000 )
**Output**: The probability (in any distinguishable form, i.e., decimal, exponential, fraction, etc)

This is a , so fewest bytes would win!

# Answer
> 9 votes
# Wolfram Language (Mathematica), 33 bytes

Uses Binomial and outputs ,really fast, fractions

```
Tr@Binomial[#,Prime@Range@#]/2^#&

```

Try it online!

The original code according to my formula was

```
Tr@Binomial[#,Prime@Range@PrimePi@#]/2^#&

```

but, as **@attinat** commented, instead of searching all Primes \< `n` we can
search the first `n` primes because every prime \> `n` returns zero binomial.
In this way we save *8 bytes*

Here is also the graph of the first 1000 cases which looks pretty cool

# Answer
> 6 votes
# Jelly, 7 bytes

```
cÆRSH⁸¡

```

**Try it online!**

### How?

```
cÆRSH⁸¡ - Link@ integer, n                   e.g. 20
 ÆR     - primes to n                             [2,3,5,7,11,13,17,19]
c       - (n) choose (vectorises)                 [190,1140,15504,77520,167960,77520,1140,20]
   S    - sum                                     340994
      ¡ - repeat...
     ⁸  - ...times: chain's left argument, n
    H   - ...action: halve
        -   (170497, 85248.5, ..., ~0.65, ~0.325) 0.3251972198486328

```

# Answer
> 4 votes
# 05AB1E, ~~10~~ 7 bytes

```
ÅPcOso/

```

Try it online!

**Explanation**

```
ÅP       # push a list of primes upto and including input
  c      # push choose(input, prime) for each prime
   O     # sum
    so   # push 2^input
      /  # divide

```

# Answer
> 4 votes
# Octave/MATLAB with Statistics Package/Toolbox, 32 bytes

```
@(n)sum(binopdf(primes(n),n,.5))

```

Try it online!

# Answer
> 2 votes
# Python 3, ~~198~~ ~~125~~ 97 bytes

```
lambda n:f(n)/2**n
f=lambda n,h=0:h>1>sum(h%i<1for i in range(2,h))if n<1else f(n-1,h+1)+f(n-1,h)

```

Try it online!

To aid in understanding, I first generate all the of the possible combinations, then I get then total heads if that is prime, then I add the total number of primes. The second function, `h` generates the result from function `f`. Bellow is the original algorithm before minimizing it.

```
def f(n,h=""):
  count = 0
  if n==0:
    hCount=h.count("h")
    for i in range(2, hCount):
      if hCount % i == 0:
        return 0
    if hCount < 2:
      return 0
    return 1
  count += f(n-1,h+"h")
  count += f(n-1,h+"t")
  return count

def h(n):
  return f(n), (2**n)

print(h(4))

```

Credits:

# Answer
> 2 votes
# Excel Formula, ~~311~~ 309 bytes

The following should be entered as an array formula (`Ctrl`+`Shift`+`Enter`):

```
=SUM(IFERROR(COMBIN(A1,SMALL(IF(MMULT(--(IF(ROW(INDIRECT("2:"&A1))>TRANSPOSE(ROW(INDIRECT("2:"&A1))),MOD(ROW(INDIRECT("2:"&A1)),(ROW(INDIRECT("2:"&A1))>TRANSPOSE(ROW(INDIRECT("2:"&A1))))*TRANSPOSE(ROW(INDIRECT("2:"&A1)))))=0),ROW(INDIRECT("2:"&A1)))=0,ROW(INDIRECT("2:"&A1))),ROW(INDIRECT("1:"&A1)))),0))/(2^A1)

```

Where `A1` is the number to test.

**Examples:**

```
A1=15
Result: 0.34997558593750
A1=25
Result: 0.341329127550125

```

**Credits**

`-2` thanks to Sophia Lechner!

# Answer
> 1 votes
# Gaia, ~~12~~ 8 bytes

```
:ṅK¦Σ@z÷

```

Try it online!

```
:		| dup input n
 ṅ		| push first n prime numbers, [2..k]
  K¦		| push n choose k (0 if k > n)
    Σ		| sum
     @z		| push 2^n
       ÷	| divide

```

# Answer
> 1 votes
# Pari/GP, 35 bytes

```
n->binomial(n)*isprime([0..n])~/2^n

```

Try it online!

# Answer
> 1 votes
# Retina, 41 bytes

```
K`
"$+"+%`^
$"H
*\Cm`^(?!(..+)\1+$)..
m`^

```

Try it online! Output is as a ratio. Explanation:

```
K`
"$+"+%`^
$"H

```

Generate all the possible coin tosses of `n` coins, but keep only the heads. (`T$"H` would keep the tails as well.)

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

```

Count how many are prime and print on a separate line.

```
m`^

```

Count how many there are altogether.

# Answer
> 1 votes
# JavaScript (ES7), 71 bytes

```
n=>(s=1,g=i=>i<n&&(s*=(n-i)/++i)*(p=d=>i%--d?p(d):d==1)(i)+g(i))``/2**n

```

Try it online!

# Answer
> 1 votes
# Jelly, 7 bytes

```
Ø.ṗ§ẒÆm

```

Try it online!

Different approach from Jonathan Allan's answer.

# Answer
> 0 votes
# Japt `-x`, 13 bytes

```
õÈj *UàX /2pU

```

Try it

---
Tags: code-golf, arithmetic, probability-theory
---


title: String Manipulation Interpreter

text:
# Question
Title: String Manipulation Interpreter
## Summary

A new string manipulation language has been made, using only the characters `$+#-!*|@>`! Your task is to implement an interpreter for it in as few bytes as possible.

## Input

A string, which is a single line of this language. This can be taken in any reasonable way (stdin, function parameter, command line argument etc.), or as a predefined variable. If the program asks for user input, accept all user input it asks for **from stdin** and nothing more, see below. You may assume it is a valid program.

## Output

Whatever the language would output, specifications below. You must output a string, in any reasonable way (stdout, function output, etc.), or a variable value. When the language outputs explicitly, this **must** go to stdout. Standard loopholes are banned.

## Language Specifications

### Processing and Syntax

The language has a very simple form of processing as it does only string manipulation: it starts with an empty string (`""`), and changes it with each term. A term is made up of one or two parts: a function (below) followed by possibly a parameter(below), which edits its behaviour. Terms are separated by pipes (`|`). You may assume it will not be an empty program, and no term will be empty. You should output the value at the end of the program.

### Functions

The language has just 6 functions, as shown below. Each function either accepts one or zero parameters.

* `+` concatenate strings (takes one string parameter, concatenates it to the current value)
* `!` reverse the character order of the current value (no parameter)
* `*` repeat the string (takes one integer parameter, repeats the current value that many times)
* `-` removes all occurrences of a value (takes one string parameter, removes all occurrences of it from the current value)
* `$` \[pseudo-\]randomly shuffles the current value (no parameter)
* `<` output the current value to `stdout` (no parameters)

### Values

These are the values that may be passed to functions, represented by regex that would match them:

* `@[^|]*` a string literal, including any character other than pipes. It may be empty.
* `#[0-9]+` an integer literal
* `>` the next line of `stdin`. If used with `*`, convert to integer.

## Test Cases

```
╔════════════════════════╤═════════════╤══════════════╗
║code                    │input        │output        ║
╟────────────────────────┼─────────────┼──────────────╢
║+>|!|+@hello|*>         │13           │31hello31hello║
║                        │2            │              ║
╟────────────────────────┼─────────────┼──────────────╢
║+>|+@abcdefg|$          │hello        │hcloeebafdlg  ║
╟────────────────────────┼─────────────┼──────────────╢
║+@how areyou|-@o|->     │w            │h areyu       ║
╟────────────────────────┼─────────────┼──────────────╢
║+@out|<|*#3             │             │out           ║
║                        │             │outoutout     ║
╟────────────────────────┼─────────────┼──────────────╢
║+>                      │what ever 345│what ever 345 ║
╟────────────────────────┼─────────────┼──────────────╢
║+@$pe<i@l|<|-@$pe<i@l|+>│A|$o $pe<!@| │$pe<i@l       ║
║                        │             │A|$o $pe<!@|  ║
╟────────────────────────┼─────────────┼──────────────╢
║<|+>|!|<                │input text   |              ║
║                        │             │txet tupni    ║
║                        │             │txet tupni    ║
╟────────────────────────┼─────────────┼──────────────╢
║+@>#                    │             |>#            ║
╚════════════════════════╧═════════════╧══════════════╝

```

Note that test case 2 is random, so any permutation of the characters in it is valid. Also, the outputs in the table are seperated by newlines, but your program doesn't have to do the same. The last value in each case the the final output.

## Example (Un-golfed) python interpreter

Try it online! IMO better if you run it through IDLE or whatever you use. (I golfed it down to 424 bytes after, but I'm sure you lot can do better).

# Answer
# Ruby `-palF\|`, ~~146~~ 142 bytes

```
r='';$F.map{|i|x=i[1]!=?>?i[2..-1]:gets.chomp;eval %w[r.reverse! r*=x.to_i 0 $><<r r=r.chars.shuffle*'' r.gsub!x,'' r+=x][i[0].ord*5%11]};$_=r

```

Try it online!

Port of Chas Brown's Python answer. Does not print newlines after output.

As usual, Ruby 2.6 version will be 2 bytes shorter with endless range indexing (`i[2..]`).
> 3 votes

# Answer
# , ~~287~~ ~~286~~ ~~273~~ 269 bytes

```
function(C,x='',`[`=gsub,`!`=intToUtf8,`?`=utf8ToInt){for(k in el(strsplit(C,'\\|'))){B=eval(parse(t='^.'['','(?<=.)>$'['readLines(,1)','[@#](.+)'['"\\1"',k],,T]]));x=switch((?substr(k,1,1))%%13-2,strrep(x,B),paste0(x,B),,B['',x,f=T],!rev(?x),print(x),,!sample(?x))};x}

```

Try it online!

* -1 thanks to @Kirill L.
* -4 thanks to @Giuseppe

Unrolled code and explanation :

```
function(C){                                      # C is the string manipulation expression
  x = ''                                          # initialize x = ''
  tokens = el(strsplit(C,'\\|'))                  # split C by pipe '|'
  for(k in tokens){                               # for each token k
    arg2 = k
    arg2 = gsub('[@#](.+)','"\\1"',k)             # replace @X or #X with "X" (in quotes)
    arg2 = gsub('(?<=.)>$','"readLines(,1)"',
                 arg2,perl=T)                     # replace > with readLines(,1)
    arg2 = gsub('^.','',arg2)                     # remove the first character
    B = eval(parse(t=arg2))                       # evaluate the string : this will be our
                                                  # second argument B
    A = substr(k,1,1)                             # take the first character :
                                                  # i.e. the main command (+,-,! etc)
    x = switch(A,                                 # switch on the main command, execute the
            '+'=paste0(x,B),                      # corresponding expression and
            '!'=intToUtf8(rev(utf8ToInt(x))),     # store the result into x
            '*'=strrep(x,B),                      # Note: in the actual code we switch on
            '-'=B['',x,f=T],                      # the utf8 value MOD 13-2 of the command
            '$'=intToUtf8(sample(utf8ToInt(x))),
            '<'=print(x)
        )
    }
    x                                             # return x (and print it implicitly)
}

```
> 6 votes

# Answer
# Python 2, ~~215~~ ~~219~~ ~~209~~ 208 bytes

```
from random import*
I=raw_input;o=''
for t in I().split('|'):p=t[1:]=='>'and I()or t[2:];exec"o=o[::-1] o*=int(p) 0 print(o) o=''.join(sample(o,len(o))) o=o.replace(p,'') o+=p".split()[ord(t[0])*5%11]
print o

```

Try it online!

-4 because `raw_input` is required.

9 bytes thanks to Embodiment of Ignorance; 1 byte from Ascii-only.
> 3 votes

# Answer
# C# (Visual C# Interactive Compiler), 305 bytes

```
a=>{string s="",d,g;foreach(var c in a.Split('|')){g=$"{c,2}";d=g[1]==62?ReadLine():g.Substring(2);var z=c[0]%14;s=z<1?string.Concat(Enumerable.Repeat(s,int.Parse(d))):z<2?s+d:z<4?s.Replace(d,""):z<5?s:z<6?string.Concat(s.Reverse()):string.Concat(s.OrderBy(_=>Guid.NewGuid()));Write(z==4?s:"");}return s;}

```

Try it online!
> 2 votes

# Answer
## Javascript, ~~292~~ 267 bytes

```
f=(p)=>{c='';p.split`|`.map(l=>{v=l.substr(2);v=l[1]=='#'?parseInt(v):l[1]=='>'?prompt():v;c={'+':_=>c+v,'-':_=>c.split(v).join``,'*':_=>c.repeat(v),'$':_=>[...c].sort(_=>.5-Math.random()).join``,'!':_=>[...c].reverse().join``,'<':_=>alert(c)||c}[l[0]]();});return c}

```

JSFiddle
> 1 votes

# Answer
# Perl 5 `-MList::Util=shuffle -pF/\|/`, ~~220~~ ~~217~~ ~~210~~ 183 bytes

```
map{$,=s/..//r;$\=reverse$\if/^!/;$,ne""||chomp($,=<>),$\=~s/\Q$,//g if/^-/;say$\if/^</;$\=join"",shuffle$\=~/./g if/^\$/;$\.=$,eq""?<>=~s/\n//r:$,if/^\+/;$\x=$,eq""?<>:$,if/^\*/}@F}{

```

Try it online!
> 1 votes

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


title: Display "Happy Easter!"

text:
# Question
Title: Display "Happy Easter!"
Your task is to print the following ASCII Art:

```
 _     _                            _______                           _
| |   | |                          (_______)          _              | |
| |__ | | ____ ____  ____  _   _    _____   ____  ___| |_  ____  ____| |
|  __)| |/ _  |  _ \|  _ \| | | |  |  ___) / _  |/___)  _)/ _  )/ ___)_|
| |   | ( ( | | | | | | | | |_| |  | |____( ( | |___ | |_( (/ /| |    _
|_|   |_|\_||_| ||_/| ||_/ \__  |  |_______)_||_(___/ \___)____)_|   |_|
              |_|   |_|   (____/

```

Remember, this is , so the code with the smallest amount of bytes wins. Good luck.

# Answer
# Bubblegum, 130 bytes

```
0000000: 758f b579 0530 18c4 7a4f a1d2 7fe5 8102  u..y.0..zO......
0000010: 5ae4 760f 5de8 91ee b3cc 8400 f523 2c3c  Z.v.]........#,<
0000020: 4656 0850 3f60 5b86 5fe4 8290 15a2 84a0  FV.P?`[._.......
0000030: 5a61 4d0b b64f 2b35 c476 eb1e 844e c841  ZaM..O+5.v...N.A
0000040: 08c8 731d 1a02 ead0 1547 1d70 beba 9fd6  ..s......G.p....
0000050: 31bf 5fdb 6c72 1d7b 1051 ed8a a884 7c76  1._.lr.{.Q....|v
0000060: 0fa7 db91 1503 c43c 9b18 124f cdb3 4220  .......<...O..B
0000070: 9631 716b a71c 3bd6 ed8b 0b62 7ebd 55cf  .1qk..;....b~.U.
0000080: 7a07                                     z.

```

Try it online.

Compressed using `zopfli --deflate --i10000`.
> 10 votes

# Answer
# JavaScript (ES6), ~~377~~ ~~373~~ ~~360~~ ~~359~~ 345 bytes

*Thanks to @Neil for a one byte savings, and to @edc65 for another 14!*

Figured I'd give it a shot. Compresses common repeating patterns in the text.

`_____` (5 underscores) is stored as `_5`

(5 spaces) is stored as `5`

`| | | | |` (5 of the `|` pattern) is stored as `~5`

```
console.log(` _ 5_ 28_7 27_
|~ 2~2 26(_7) 10_ 13~2
|~_2~2 _4 _4 2_4 2_ 3_ 4_5 3_4 2_3|~_ 2_4 2_4|~
| 2_2)|~/ _ ~ 2_ \\| 2_ \\|~3 ~ 2_3) / _ ~/_3) 2_)/ _ 2)/ _3)_|
|~ 2~ ( (~9_|~ ~2_4( (~2_3~2_( (/ /|~ 4_
|_| 2~_|\\_|2_|~|_/|~|_/ \\_2 ~ ~_7)_|2_(_3/ \\_3)_4)_| 2~_|
 13~_| 2~_| 3(_4/`.replace(/(.)(\d+)/g,(_,a,b)=>a.repeat(b)).replace(/~/g,' |'))

```
> 10 votes

# Answer
# BinaryFuck, ~~565~~ 378 bytes

This basically stores the characters used in the array, then navigates through the array, printing them accordingly. Currently quite long, will shorten it up.

```
1000010000000000000000110011110001010010000011011111010010110001011011000000010010111011001111011110010010010000010000010000000000000010000010000000000010000010000000000011011011011011011011011011001111010010000000000110001010000000000000000010000000000011011111010010001010001001001001010010001010000000000000000000000000000010001001001001010000000000000000000000000000000011011011011100010100011100100100100100010100011100100100100100100100100100100100100100100100100100100100100100100100100100100100100010100100100100100100100011100100100100100100100100100100100100100100100100100100100100100100100100100100100010100011100010010010010100011011011011011100010100011100010100100100011100010100011100010100100100100100100100100100100100100100100100100100100100100100100100100100100011011100010010010100100100100100100100010100011011100100100100100100100100100100010100011100100100100100100100100100100100100100100011100010100011100010010010010010100011011011011011100010100011100010010100100011100011100010100011100010100010100100100100011100010100100100100011100100010100100100100011100100010100011100100100010100011100100100100010100100100100100011100100100010100100100100011100100010100100100011011100010100011100010010100011100100010100100100100011100100010100100100100011011100010100011100010010010010010100011011011011011100010100100010100100010100011011011100010100011100011011100010010010100010100011100100011100010100100010100011100010010010100011011011011100010100100010100011100010010010100011011011011100010100011100010100011100010100011100010100100011100010100100010100100100010100011011100011011011100010010010100010100011100100011100011011100010010010010100100100010100011011100100010100010100011011011011011100010010010100010100011100100010010100011011011011011100010010010100010100100100010100011100011011100010010010010010100011011011011011100010100011100010100100100011100010100011011100010010100011011100010010100011100010100011100010100011100010100011100010100011100010100011100010100011100010100011100010100011100010010100011011100010100011100010100100011100010100011100010010100100100100011011011100010010100011011100010010100011100010100011100010010100100100011100011100010100011100010010100011011011100010010100011011100011100010010010100011011011100010010100010100011100010100100100100010100011100010010010010100011011011011011100010010100011011100010100100100011100010010100011011100010010010010100011011100011011100100010010100011011100010100011100100010010100011011011011100010010100010100011100100010010100011011011011100010010010100010010010100011011100100011100100011100010100100011100010010100100100100100100100010100011100011011100100010010100011011011100010010010100100100011011011011100010010010100010010010100011011100100100010100011100100100100010100011100011011100010100100100011100010010100011011100010010010010010100011011011011100100100100100100100100100100100100100100011100010010100011011100010100100100011100010010100011011100010100100100011011100010010010100100100100011011011011100

```

Here is the ungolfed code:

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

```

EDIT: by rearranging the order of the characters in the cells, I saved 186 bytes!
> 8 votes

# Answer
## JavaScript (ES6), 380 bytes

For completeness this is my effort to use a different compression method, although as it turns out it's not as efficient as run length encoding. Each digit specifies that the last N already generated characters are repeated. Subsequent digits can repeat already repeated characters, e.g. `| 23` turns into `| | |`. I only wish I could compress a run of three characters.

```
f=(s=` _  26  2479__23   2499_
| 2  6  2379(__23)   25_  237|2
| |__ |2 __25  __2  _ 4   ___2   __2  ___| |_  ___6_| |
|  __)| |/ _  |  _ \\6| 24 |  ___) / _  |/___)  _)/ _  )/ ___)_|
| 2  | (2 |248 |_| 23|__2( 2| |___ |2_( (/ /| 2   _
|_|   |_|\\_||_| ||_/6 \\__  |3__23)_||_(___/ \\___)_5|   |_|
  237|_|6   (__2/`,r=s.replace(/(.*?)(\d)/,(_,p,n)=>p+p.slice(-n)))=>r==s?r:f(r)

o.textContent = f()
```

```
<pre id=o></pre>
```
> 6 votes

# Answer
# C, 517 427 407 bytes

* saved few bytes, thanks to @ceilingcat

```
c,i;main(m){for(char*s=" _ 4_ 999_6 998_ 1\n|B 2|B 997(_6) 9_ 94|B \n| |_1C _3 _3 1_3 1_ 2_ 3_4 2_3 1_2|B_ 1_3 1_3|B \n| 1_1)|B/ _ 1\\| 1_ \\| 1_E 1| 1_2) / _ 1|/_2) 1_)/ _ 1)/ _2)_| \n|B 2| ( (J_|B 1|B_3( (C_2C_( (/ /|B 3_ 1\n|_| 2|_|\\_||_|B1_/|B1_/ \\_1 1| 1|_6)_|1_(_2/ \\_2)_3)_| 2|_| \n 94|_| 2|_| 2(_3/\n";*s;s++)for(i=isdigit(*s)?c=m,*s-48:isalpha(*s)?c=0,*s-65:(c=*s,1);i--;)printf(c?m=c,&c:" |");}

```

**Ungolfed** Try Online

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

char m = 0;

void g(char c, int i)
{
    while(i--) c ? m=putchar(c) : printf(" |");
}

void p(char* s)
{
    while(*s)
        isdigit(*s) // golfed if-else-if
        ? g(m,*s-48)
        : isalpha(*s)
          ? g(0,*s-65)
          : g(*s,1)
        ,
        s++;
}

int main()
{
    p(" _ 4_ 999_6 998_ 1\n|B 2|B 997(_6) 9_ 94|B \n| |_1C _3 _3 1_3 1_ 2_ 3_4 2_3 1_2|B_ 1_3 1_3|B \n| 1_1)|B/ _ 1\\| 1_ \\| 1_E 1| 1_2) / _ 1|/_2) 1_)/ _ 1)/ _2)_| \n|B 2| ( (J_|B 1|B_3( (C_2C_( (/ /|B 3_ 1\n|_| 2|_|\\_||_|B1_/|B1_/ \\_1 1| 1|_6)_|1_(_2/ \\_2)_3)_| 2|_| \n 94|_| 2|_| 2(_3/\n");
    return 0;
}

```
> 6 votes

# Answer
# Perl 5, 286 bytes

`perl -M5.01 happy.pl`, where `happy.pl` is:

```
$_='u5u28 7_27u
~~x~~25 (7_)10u7x~~
~p_ ~~4_ 4_x4_x_3u4 5_3 4_x3_~px4_x4_~~
~u_)~|/ux~u \~u \4~ ~ 3_) /ux|/3_)x_)/ux)/ 3_)_|
~~x~( ( 8~p~~ ~|4-( ( ~p__ ~p( (/ /~~3u
p~xp|\_|p~|p/~|p/ \__x~ p6_)_|p(3_/ \3_)4_)_~xp|
14 p~xp~x(4_/';s/u/ _/g;s/\d+(.)/$1x$&/ge;s/x/  /g;s/~/| /g;s/p/|_/g;say

```

Thanks to Dom Hastings (in a comment hereon) for an idea that saved me two bytes and led to another idea of mine that saved four more.
> 5 votes

# Answer
# , 72 chars / 209 bytes

```
`Эć훼쎧漤詼媰਀㻆僚픈耊Ⓢኍ⋱쬝ᇑ덆䖇䂊՛樥첾㨭쯠ཁ톇:덱螟醮䖉⥊覂削ꇉ漈涹႘챘ඕ꼳⁒᭷Ừ䒕鶀놜㆝〢ﱱꎀ쎴䋈㗂䅉Ⴄቀ쳵菨ⶩ∉툲耀

```

`Try it here (Firefox only).`

Well, at least the char count is great, but we can't use the custom code page. It's just an LZString-decompression. I'm also working on another solution - more on that later.
> 5 votes

# Answer
## JavaScript, 297 bytes

```
console.log(` 29 288999002889 3
19 18899 500_)82891
1__ 1 0_ 02022 290_2 02012020_1
|3_)162|3 \\|3 \\1 19|90) 62|/0)3)62)60)_|
19 |55 1 1 1 1 71910_(5 10 1_(56/193
7|4\\_|717/176\\_2|9|00_)_|7(06\\0)0_)_|4
8 44950_/`.replace(/\d/g,n=>`___,| |,_  ,  _,   |_|, (,/ ,|_,          ,  `.split`,`[n]))

```

Simple encoding of the ten most (as far as I can tell) common substrings. They are not in order because of overlaps; my encoder (below) needs to see e.g. `'_ '` and `' _'` before `' '`.

```
(s,a,t=s)=>a.map((t,i)=>s=s.split(t).join(i))&&[s,(b=>{b=new Map;for(i=0;i<s.length;i++)for(j=0;j<i;j++)b.set(s.slice(j,i),s.length-s.split(s.slice(j,i)).join().length-i+j-1);return[for(x of b)if(x[1]>0&&!/\d/.test(x[0]))x].sort(([a,b],[c,d])=>b-d)})(),t.length-(s+' '+a).length]

```

This takes a string and an array of substrings to encode and returns a) the encoded string b) the list of potential next savings c) the number of bytes saved so far.
> 5 votes

# Answer
# Python 2, 159 bytes

This source contains non-printable characters, so it is presented as a hexdump that can be decoded with `xxd -r`.

```
00000000: efbb bf70 7269 6e74 2278 017d 8fb5 7540  ...print"x.}..u@
00000010: 3114 c5fa 3f85 4abb f240 012d a2dd 432f  1...?.J..@.-..C/
00000020: 4cba c732 1302 20ff e0c0 dfc8 1501 e33f  L..2.. ........?
00000030: 580e 9b77 e40b d115 2911 aa23 1c33 05a7  X..w....)..#.3..
00000040: cf54 6ae4 74c7 7310 baa3 8310 c86d 8c27  .Tj.t.s......m.'
00000050: 04ea 6656 9c79 9bfb a5fb 6cdd f6fe b5c5  ..fV.y....l.....
00000060: a2ef 3182 4875 56a4 123d 770f 2702 902b  ..1.HuV..=w.'..+
00000070: 03b2 5bcb 28cf 985b 8520 876d b974 a6dc  ..[.(..[. .m.t..
00000080: be28 20bb f842 f6ee a57a 1e01 c1a2 733e  .( ..B...z....s>
00000090: 222e 6465 636f 6465 2827 7a69 7027 29    ".decode('zip')

```
> 2 votes

# Answer
# Racket, 367 364 bytes

```
(require file/gunzip net/base64)((λ(o)(gunzip-through-ports(open-input-bytes(base64-decode #"H4sIAOhN/lYAA31QwQ3EMAj7dwqezYuFInkRhj+MoWor9UBCmGBDMBhN8cMg+9dhR1hkovhhZwutO/FhSadQzqJQDdXkjsOYfa5Hkm4QEsp0ZeYkEdmeKK8i91GHazesgoyJEdfXzvR4O1ooOLY7oA8QunnfhDdCCSE2oogBV7QN7RhzI3bwYPWUUDXRj9fVpj439h/OlCKU1gEAAA=="))o)(displayln(get-output-string o)))(open-output-bytes))

```

### Ungolfed

```
(require file/gunzip net/base64)
((λ (o)
   (gunzip-through-ports
    (open-input-bytes
     (base64-decode
      #"H4sIAOhN/lYAA31QwQ3EMAj7dwqezYuFInkRhj+MoWor9UBCmGBDMBhN8cMg+9dhR1hkovhhZwutO/FhSadQzqJQDdXkjsOYfa5Hkm4QEsp0ZeYkEdmeKK8i91GHazesgoyJEdfXzvR4O1ooOLY7oA8QunnfhDdCCSE2oogBV7QN7RhzI3bwYPWUUDXRj9fVpj439h/OlCKU1gEAAA=="))
    o)
   (displayln (get-output-string o)))
 (open-output-bytes))

```

Based off a similar challenge I answered.
> 2 votes

# Answer
# ///, ~~282~~ 279 bytes

Improvement: I noticed that there are too many `//` in the replacement commands, so I decided to compress them also (to `m`), which saved me 3 bytes.

```
/m/\/\///l/ _mk/|amj/b_mi/\\\m/h/|cmg/ddmf/ccme/bbmd/aamc/ |mb/__ma/  /ldlgggdejgggal
hafggga(ej)ga_gdah
hbf e eaea_alde_a eajh_aeaeh
kb)hilak_ \\k_ \\|fcakj) ila|ij)a_)ila)i j)_|
hac ( (ffffc_hahe( (fjf_( (i ihd_
|_kc_|\\_||_h|_ih|_i \\bak|ej)_||_(ji \\j)e)_kc_|
gda|_kc_k (ei

```

Repeatly compress the most frequent substring.

### Thirteenth generation, 282 bytes

```
/l/ _//k/|a//j/b_//i/\\\///h/|c//g/dd//f/cc//e/bb//d/aa//c/ |//b/__//a/  /ldlgggdejgggal
hafggga(ej)ga_gdah
hbf e eaea_alde_a eajh_aeaeh
kb)hilak_ \\k_ \\|fcakj) ila|ij)a_)ila)i j)_|
hac ( (ffffc_hahe( (fjf_( (i ihd_
|_kc_|\\_||_h|_ih|_i \\bak|ej)_||_(ji \\j)e)_kc_|
gda|_kc_k (ei

```

Try it online!

### First generation, 486 bytes

No compression. Escaped the `/` and the `\`.

```
 _     _                            _______                           _
| |   | |                          (_______)          _              | |
| |__ | | ____ ____  ____  _   _    _____   ____  ___| |_  ____  ____| |
|  __)| |\/ _  |  _ \\|  _ \\| | | |  |  ___) \/ _  |\/___)  _)\/ _  )\/ ___)_|
| |   | ( ( | | | | | | | | |_| |  | |____( ( | |___ | |_( (\/ \/| |    _
|_|   |_|\\_||_| ||_\/| ||_\/ \\__  |  |_______)_||_(___\/ \\___)____)_|   |_|
              |_|   |_|   (____\/

```

Try it online!

### Second generation, 402 bytes

Compressed two spaces to `a`. The `/a/ /` means "replace all occurrences of `a` to two spaces".

```
/a/  / _aa _aaaaaaaaaaaaaa_______aaaaaaaaaaaaa _
| |a | |aaaaaaaaaaaaa(_______)aaaaa_aaaaaaa| |
| |__ | | ____ ____a____a_a _aa_____a ____a___| |_a____a____| |
|a__)| |\/ _a|a_ \\|a_ \\| | | |a|a___) \/ _a|\/___)a_)\/ _a)\/ ___)_|
| |a | ( ( | | | | | | | | |_| |a| |____( ( | |___ | |_( (\/ \/| |aa_
|_|a |_|\\_||_| ||_\/| ||_\/ \\__a|a|_______)_||_(___\/ \\___)____)_|a |_|
aaaaaaa|_|a |_|a (____\/

```

Try it online!

### Third generation, 369 bytes

Compressed `__` to `b`. The `/b/__/` at the beginning means "replace all occurrences of `b` to `__`".

```
/b/__//a/  / _aa _aaaaaaaaaaaaaabbb_aaaaaaaaaaaaa _
| |a | |aaaaaaaaaaaaa(bbb_)aaaaa_aaaaaaa| |
| |b | | bb bbabba_a _aabb_a bbab_| |_abbabb| |
|ab)| |\/ _a|a_ \\|a_ \\| | | |a|ab_) \/ _a|\/b_)a_)\/ _a)\/ b_)_|
| |a | ( ( | | | | | | | | |_| |a| |bb( ( | |b_ | |_( (\/ \/| |aa_
|_|a |_|\\_||_| ||_\/| ||_\/ \\ba|a|bbb_)_||_(b_\/ \\b_)bb)_|a |_|
aaaaaaa|_|a |_|a (bb\/

```

Try it online!

### Fourth generation, 339 bytes

Compressed  `|` to `c`. The `/c/ |/` at the beginning means "replace all occurrences of `c` to  `|`".

```
/c/ |//b/__//a/  / _aa _aaaaaaaaaaaaaabbb_aaaaaaaaaaaaa _
|caccaaaaaaaaaaaaa(bbb_)aaaaa_aaaaaaa|c
|cbcc bb bbabba_a _aabb_a bbab_|c_abbabb|c
|ab)|c\/ _a|a_ \\|a_ \\|ccca|ab_) \/ _a|\/b_)a_)\/ _a)\/ b_)_|
|cac ( (ccccccccc_|ca|cbb( (ccb_cc_( (\/ \/|caa_
|_|ac_|\\_||_|c|_\/|c|_\/ \\ba|a|bbb_)_||_(b_\/ \\b_)bb)_|ac_|
aaaaaaa|_|ac_|a (bb\/

```

Try it online!

### The rest of the compression rules

So, the list of compression rules:

* Compress two spaces to `a`.
* Compress `__` to `b`.
* Compress  `|` to `c`.
* Compress `aa` to `d`.
* Compress `bb` to `e`.
* Compress `cc` to `f`.
* Compress `dd` to `g`.
* Compress `|c` to `h`.
* Compress `\/` to `i`. Both the `\` and the `/` in the rules are further escaped.
* Compress `b_` to `j`.
* Compress `|a` to `k`.
* Compress  `_` to `l`.
* Compress `//` to `m`.

As you can see, there are overlapping compression rules. For example, `g` encodes `dd` which encodes `aaaa` which encodes 8 spaces.
> 2 votes

# Answer
# Python 2, ~~343~~ ~~328~~ 316 bytes

This solution uses no decompression functions or other imports.

```
o=""
for i in range(250):j=ord(")*I*yyQZyyI*(!+9!+yyA,Z-q*y9!+(!+2)!!B)B1B1*9*AJ9B1:!+*1B1B!+(+12-!+/)*1+1*).+1*).!!!+1+1:-)/)*1+/:-1*-/)*1-/):-*+(!+9!,),)!!!!!!!!+*!+1!+B,),)!+:)!+*,),/)/!+A*(+*+9+*+.*3*!3*/!3*/).21+1+Z-*3*,:/).:-B-*+9+*+(y9+*+9+*+9,B/(".replace("!","+)")[i])-40;o+="\n _|()\/"[j&7]*(j/8+1)
print o

```

Readable version:

```
DATA=(")*I*yyQZyyI*("
"!+9!+yyA,Z-q*y9!+("
"!+2)!!B)B1B1*9*AJ9B1:!+*1B1B!+("
"+12-!+/)*1+1*).+1*).!!!+1+1:-)/)*1+/:-1*-/)*1-/):-*+("
"!+9!,),)!!!!!!!!+*!+1!+B,),)!+:)!+*,),/)/!+A*("
"+*+9+*+.*3*!3*/!3*/).21+1+Z-*3*,:/).:-B-*+9+*+("
"y9+*+9+*+9,B/(").replace("!","+)")
SIZE=250
o=""
for i in range(SIZE):
 j=ord(DATA[i])-40
 o+="\n _|()\/"[j&7]*(j/8+1)
print o

```

Uses a version of run length encoding with 3 bits for a symbol from the set "\n \_|()/". The remainder of the byte is the length, but I have limited the length to 10 and manipulated it so that the results are printable characters that are valid in a python string without any escaping.

Replacing the string corresponding with "| " with a single character in the encoded data saves a few more bytes.

I removed the trailing spaces on lines 1 and 5, which may be bending the rules a bit, but seems practical.

This program generates the packed data:

```
message="""
 _     _                            _______                           _
| |   | |                          (_______)          _              | |
| |__ | | ____ ____  ____  _   _    _____   ____  ___| |_  ____  ____| |
|  __)| |/ _  |  _ \|  _ \| | | |  |  ___) / _  |/___)  _)/ _  )/ ___)_|
| |   | ( ( | | | | | | | | |_| |  | |____( ( | |___ | |_( (/ /| |    _
|_|   |_|\_||_| ||_/| ||_/ \__  |  |_______)_||_(___/ \___)____)_|   |_|
              |_|   |_|   (____/"""[1:]
size=len(message)
symbols="\n _|()\/"
i=0
encoded=""
while i<size:
    count=0
    while count<10 and i+count+1<size and message[i+count+1]==message[i]:
        count+=1
    n = symbols.find(message[i]) | count<<3
    encoded+=chr(n+40)
    i+=count+1
encoded_lines = encoded.replace("+)","!").split(chr(40))
for line in encoded_lines:
    print line+chr(40)
print len(encoded)

```
> 2 votes

# Answer
## Your Mom (non-competing), 331 bytes

Decode the string and decompress it using the Jelly compressor

```
'IF8KfCgpL1z/AQAAAQAAAAAAAAAAAAAAAAAAEREREAAAAAAAAAAAAAAAAAAQIwMAAwMAAAAAAAAAAAAAAAAAQREREVAAAAAAAQAAAAAAAAAwMjAxEDAwEREBERABERABAAEAABEREAAREQAREwMQAREQARETAyMAEVMDYBADABBzABBzAwMDADABEVBgEANhEVABVgEAVgERUTIwMAAwQEAwMDAwMDAwMDEwMAMDERFAQDAxEQMDFARgYwMAABAjEwADE3EzEwMxYwMxYHEQAwAxERERUTMUERYHERUREVEwADEyAAAAAAAAADEwADEwAEERFg=='`

```
> 2 votes

# Answer
# Python 3, 263 bytes

Initial pass using builtins.

```
from base64 import*
from zlib import*
print(decompress(a85decode(b"Gas1Y_%\"=:#lAfQT$<1I,'acT5E):N/+l.oQs`98(esP<+T'c!7p'"
b";rpgIeCXZQ&]8Z,D1U/2<LjGq-FIBH)'D@dH'FCjS[&_Wa(Y9N^<LMJiMJrGNuf@S=?GWT(W34:oA%hQ<"
b"thh3pT#pD4$L]LSa%IG!R,BiQaoor91d>uo0VEQs4+2O[m4o")).decode())

```

some extra quotes and linebreaks added to avoid horizontal scroll for display purposes only (not counted in score)
> 1 votes

# Answer
# Python 3, 377 bytes

```
from re import*;i=0
r=r'2_.7_./ .|2.| .4_.\\. _._d|.( (.3_). _ .2|_. |2 ._| |.a| |./ _2 .|3 |_. 4_2 . | |.\n'
e='an5n28 t27jf3b26 (t)10n14bfub pcp2n3n4 5_3c3g_2c4gar u)q|erjorjo|bhr k e|/k2n)e)sk_|f3 qlbbbb |g2bplb3_b_ls/q|4ja|mo_iqi/qisou2h|t)_i(3_sokp)ma14 |m3 (p/'
for j in r.split('.'):e=sub(chr(117-i),j,e);i+=1
print(sub('(\d+)(.)',lambda x:int(x.group(1))*x.group(2),e))

```

similar to the javascript answer, used RLE plus a bunch of replacements for common substrings.

Think I went a bit over the top with the replacing stuff, probably didn't help that much but oh well.
> 1 votes

# Answer
# JavaScript (ES6), 354 bytes

Another attempt. Not as efficient as run length, unfortunately.

```
i=0,console.log(`1c1bt96zfx1!1n4ikabr1w5!1n4iut4kyue!krgqthnkpkem8!43tb4j2urme!8hwrsagny80!69dfowb7hvk!2xj89rpvcb2!23l14ken5i1!1xzn6ns7j78!1tzyivgb4h2!1yy885vts00!12du7km7f51!1lvpcyzgbfq!17nicizf8og0!1246xqebgb9!1n4j181hywz!`.replace(/\w+!/g,v=>parseInt(v,36).toString(4).replace(/./g,w=>"_ |"[w]||`
()

)/\\\\)//))/)/)
((((((//
\\//\\)(/\\))
(/`[i++])))

```

Stores a bunch of base-36 numbers in the first string, delimited by a `!` separator. Then replaces the numbers (along with the `!`) with the numbers' base-4 representations. Replaces all the 0's, 1's, and 2's in the base-4 number with `_`, , and `|` respectively, and all the 3's are replaced with the elements in the second string sequentially.
> 1 votes

# Answer
# CJam, 229

```
"3WPPEFXvN'vlFBse/cTD>.x:Na,Y&NJH^tZ%xL(NkYzo0Rq%BeV&Zl1T^2y69,W/QC4pL`nv<Jo$'Cq.'m2-3H#9teHi&<uyO>f V)D\E y'*]oGq*ODjQLyoS*GyM7;\Z.n6B;J@OyEaE!4'E5p5MOl^#[,ZtA;`jy,gTP^\;;i<A6^:k1%"' fm91b31b"}*+{~'NHIF\JLM
OGQK)(P/RST|_- \""f=~

```

No funky characters and no built-in compression :)

Try it online
> 1 votes

# Answer
# Ruby, ~~271~~ ~~262~~ 248 bytes

```
require'zlib'
require'base64'
puts Zlib.inflate Base64.decode64'eJx1UMENxDAI+zMFz+bFQpG8CMMX46DeVWpQrJjYhGDp6e7Cj3VBaz0p/CvKbrWBLkStYHAcEH8uafqhUKE6rjoFTWS+BxWdZD9ShHrDakosju6oe7sq8h04hZLPHgX0AdLwODOBG8VOy0a2MRFC31CPOTOiggPrq6LKyW6vqU1+Zhx2A7NMZ9I'

```

Try it here
> 1 votes

# Answer
# Lua, 353 bytes

Program:

```
a=(" _ 5_ 28_7 27_\n|~ 2~2 26(_7) 10_ 13~2\n|~_2~2 _4 _4 2_4 2_ 3_ 4_5 3_4 2_3|~_ 2_4 2_4|~\n| 2_2)|~/ _ ~ 2_ \\| 2_ \\|~3 ~ 2_3) / _ ~/_3) 2_)/ _ 2)/ _3)_|\n|~ 2~ ( (~9_|~ ~2_4( (~2_3~2_( (/ /|~ 4_\n|_| 2~_|\\_|2_|~|_/|~|_/ \\_2 ~ ~_7)_|2_(_3/ \\_3)_4)_| 2~_|\n 13~_| 2~_| 3(_4/"):gsub("(.)(%d+)",function(a,b)return a:rep(b)end):gsub("~"," |")print(a)

```

Thanks to @jrich for compression.
> 1 votes

# Answer
# Vim, ~~374~~ ~~365~~ ~~326~~ ~~319~~ ~~313~~ 311 keystrokes

9 keystrokes thanks to @Dr Green Eggs and Ham DJ.

```
:im @ ___<CR>
:im % _|<CR>
a _## _<esc>28a <esc>yl7a_<esc>27pa_ <CR>
|!#!!<esc>26pa(<esc>7a_<esc>a)<esc>10pa_<esc>14pa|!<CR>
|!__!!<esc>3a @_<esc>bi <esc>A#_# _##@__# @_#@|!_#@_#@%!<CR>
|#__)|!/ _ !#_ \|#_ \<esc>4a| <esc>a!#@) / _ !/@)#_)/ _#)/ @)%<CR>
|!#! ( (<esc>9a!<esc>a%! !!@_( (!!@!!_( (/ /|!##_ <CR>
|%#!%\%|_<esc>2a|!|_/<esc>a \__ ! !<esc>7a_<esc>a)%|_(@/ \@)@_)%#!%<CR>
<esc>14pa|%#!%# (@_/<esc>
:%s/!/ |/g<CR>
:%s/#/  /g<CR>

```

Probably can be golfed further by using `:nn`?
> 1 votes

# Answer
# HTML, 482 481 475 bytes

```
<pre> _     _                            _______                           _
| |   | |                          (_______)          _              | |
| |__ | | ____ ____  ____  _   _    _____   ____  ___| |_  ____  ____| |
|  __)| |/ _  |  _ \|  _ \| | | |  |  ___) / _  |/___)  _)/ _  )/ ___)_|
| |   | ( ( | | | | | | | | |_| |  | |____( ( | |___ | |_( (/ /| |    _
|_|   |_|\_||_| ||_/| ||_/ \__  |  |_______)_||_(___/ \___)____)_|   |_|
              |_|   |_|   (____/
```
> 1 votes

# Answer
# Javascript (ES6) ~~464~~ 352 bytes

```
00000000  63 6f 6e 73 6f 6c 65 2e  6c 6f 67 28 60 08 09 28  |console.log(`..(|
00000010  09 c3 a0 39 c3 98 09 08  0f 0c 08 0c 18 0c 08 0c  |...9............|
00000020  c3 90 0a 39 0e 50 09 70  0c 08 0c 0f 0c 08 0c 11  |...9.P.p........|
00000030  08 0c 08 0c 08 21 08 21  10 21 10 09 18 09 20 29  |.....!.!.!.... )|
00000040  18 21 10 19 0c 08 0c 09  10 21 10 21 0c 08 0c 0f  |.!.......!.!....|
00000050  0c 10 11 0e 0c 08 0c 0a  08 09 10 0c 10 09 08 0c  |................|
00000060  10 09 08 0c 08 0c 08 0c  08 0c 10 0c 10 19 0e 08  |................|
00000070  0a 08 09 10 0c 0a 19 0e  10 09 0e 0a 08 09 10 0e  |................|
00000080  0a 08 19 0e 09 0c 0f 0c  08 0c 18 0c 08 0a 08 0a  |................|
00000090  08 0c 08 0c 08 0c 08 0c  08 0c 08 0c 08 0c 08 0c  |................|
000000a0  08 0c 09 0c 08 0c 10 0c  08 0c 21 0a 08 0a 08 0c  |..........!.....|
000000b0  08 0c 19 08 0c 08 0c 09  0a 08 0a 08 0a 0c 08 0c  |................|
000000c0  20 09 08 0f 0c 09 0c 18  0c 09 0c 09 14 09 0c 08  | ...............|
000000d0  14 09 0a 0c 08 14 09 0a  08 11 10 0c 10 0c 39 0e  |..............9.|
000000e0  09 14 09 0a 19 0a 08 19  0e 21 0e 09 0c 18 0c 09  |.........!......|
000000f0  0c 0f 70 0c 09 0c 18 0c  09 0c 18 0a 21 60 2e 73  |..p.........!`.s|
00000100  70 6c 69 74 28 22 22 29  2e 6d 61 70 28 61 3d 3e  |plit("").map(a=>|
00000110  61 2e 63 68 61 72 43 6f  64 65 41 74 28 29 29 2e  |a.charCodeAt()).|
00000120  6d 61 70 28 61 3d 3e 41  72 72 61 79 28 28 61 3e  |map(a=>Array((a>|
00000130  3e 33 29 2b 31 29 2e 6a  6f 69 6e 28 22 20 5f 2f  |>3)+1).join(" _/|
00000140  5c 5c 7c 28 29 5c 6e 22  2e 73 70 6c 69 74 28 22  |\\|()\n".split("|
00000150  22 29 5b 61 26 37 5d 29  29 2e 6a 6f 69 6e 28 22  |")[a&7])).join("|
00000160  22 29 29                                          |"))|

```

Try it here!
> 1 votes

# Answer
# 05AB1E, 171 bytes

```
"_ |0/)(
\"•1æÆ&¢ÙDÿœƒ˜¶f
¹∍[saÎΛÞÀθ¶\‚e–8(¬šôon&{wαλµ.cRŽ1ºWèíÄʒΣ ι.ì¨Gt‰?WиΛÆ—©UãšW#тÊ÷´¥b™¢,V§¯l€éàøjòÐø¬ëäÇ kĀT¬Àн4p«ªÒdαñáyÛÆ¦‚@ø‘Ñ‚иu₅₂Qp>øî÷^‡иÓ7¯ÓÇŠ@ÄéS•9вèJ0…   :

```

Try it online.

**Explanation:**

```
"_ |0/)(
\"            "# Push string "_ |0/)(\n\"
  •1æÆ&¢ÙDÿœƒ˜¶f
  ¹∍[saÎΛÞÀθ¶\‚e–8(¬šôon&{wαλµ.cRŽ1ºWèíÄʒΣ ι.ì¨Gt‰?WиΛÆ—©UãšW#тÊ÷´¥b™¢,V§¯l€éàøjòÐø¬ëäÇ kĀT¬Àн4p«ªÒdαñáyÛÆ¦‚@ø‘Ñ‚иu₅₂Qp>øî÷^‡иÓ7¯ÓÇŠ@ÄéS•
               # Push compressed integer 1097503083536947704653792841425892054204805659502021445044262296065039856679486956980779201344195600186307613120325421519873972685660197036332437042797892085831181080642513349371962439499848029872306826792254102689695782393365417312419084231420872539225014767457254170199022042856591776594745757160095950475758150232076499909206475280246564765470414367938
   9в          # Converted to Base-8 as list: [1,0,3,1,1,0,3,3,3,3,3,3,3,3,3,1,0,0,0,0,0,0,0,3,3,3,3,3,3,3,3,3,0,7,2,1,2,3,2,1,2,3,3,3,3,3,3,3,3,1,1,6,0,0,0,0,0,0,0,5,3,3,3,1,0,3,3,3,3,1,1,2,1,2,7,2,1,2,0,0,1,2,1,2,1,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0,1,1,0,3,0,3,1,0,0,0,0,0,3,0,0,0,0,1,1,0,0,0,2,1,2,0,1,1,0,0,0,0,1,1,0,0,0,0,2,1,2,7,2,1,1,0,0,5,2,1,2,4,1,0,1,1,2,1,1,0,1,8,2,1,1,0,1,8,2,1,2,1,2,1,2,1,1,2,1,1,0,0,0,5,1,4,1,0,1,1,2,4,0,0,0,5,1,1,0,5,4,1,0,1,1,5,4,1,0,0,0,5,0,2,7,2,1,2,3,2,1,6,1,6,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,0,2,1,2,1,1,2,1,2,0,0,0,0,6,1,6,1,2,1,2,0,0,0,1,2,1,2,0,6,1,6,4,1,4,2,1,2,3,1,0,7,2,0,2,3,2,0,2,8,0,2,2,0,2,1,2,2,0,4,2,1,2,2,0,4,1,8,0,0,1,1,2,1,1,2,0,0,0,0,0,0,0,5,0,2,2,0,6,0,0,0,4,1,8,0,0,0,5,0,0,0,0,5,0,2,3,2,0,2,7,3,3,3,3,1,1,2,0,2,3,2,0,2,3,6,0,0,0,0,4]
     è         # Index each into the string
      J        # Join all characters together to a single string
       0…   :  # Replace all "0" with "   " (3 spaces)
               # (and output the string implicitly as result)

```

See this 05AB1E tip of mine (section *How to compress large integers?* and *How to compress integer lists?*) to understand how the compressed integer and Base-8 list work.
> 1 votes

# Answer
# C (gcc), ~~280~~ 279 bytes

```
f(i){for(char*A=" _|/\\()\n",*s="H@@H.@#IA-@AWP@PP-@M#IF$@H'@BzBJABBIIHIAHIAH@H@@IIA@II@IQPAHIAHIQPW@IVPCAP@AT@AT#P@BHIFCAPKIFH^H@^HINzBB@BEE(BJBBPPIIEEBJIPPihCSP@@AWQ@PQLRQPJSPJCLAP@J#INRiIY`IqIINB@Jz'@JB@JB@MIY";i=*s>63?:*s++;s++)for(;i--&31;)printf("%c%c",A[*s&7],A[*s/8&7]);}

```

Try it online!

## Rundown

We define an alphabet of 8 symbols, `" _|/\\()\n"`, and compress the data by packing two symbols per byte according to its index in the alphabet, with the first symbol in bits 0..2, and the second in 3..5. Bit 6 is set to bring the resulting byte into printable ASCII territory. A simple RLE is then run on the compressed string. If a symbol in the string occurs more than twice in a row, it is stored as a character pair, with the first containing the run-length plus 32 (bit 5 set) and the second the symbol itself.

```
f(i){                                               i is run-length; not actually passed to f()
    for(                                            Loop over compressed string.
        char*A=" _|/\\()\n",                        Alphabet
        *s="...";                                   Compressed string.
        i=*s>63?:*s++;                             If char is outside symbol range, use as run-length and skip to next. Stop on EOS.
        s++)                                        Advance to next char.
            for(;i--&31;)                           Repeat symbol pair per run-length.
                printf("%c%c",A[*s&7],A[*s/8&7]);   Extract symbols from character and print.
}

```

Try it online!
> 1 votes

# Answer
# Javascript ES6, 314 bytes

Contains unprintable bytes. Uses some black JS magic to run. If `console.log()` is needed for this answer to be valid, the byte count will be 327.

```
[...`Ãm°Ûm¶Ûm¶Ûm¶Û\`��m¶Ûm¶Ûm¶Ûm�ç�±Çm¶Ûm¶Ûm¶Ûh���¶Ûm°Ûm¶Ûm�<â�8à�À�°�l6Ãm��m��\`�Äl����Ç��§��Ça�ØfqÇ��À�����»
°Ú¬� ó�Øé¦8ã�8ã� ã±Ä�&�â�Ç�4Y�vØnAÛ�X$�HG��\`lv �� ���0��
�Ø�öÛm¶Ûb�Ø�¶���`].map(a=>'0'.repeat(8-(z=a.charCodeAt().toString(2)).length)+z).join``.replace(/.{1,3}/g,a=>`_|/\\()
`[parseInt(a,2)]).slice(0,-2)

```

This was a huge pain to get right, and I couldn't manage to get rid of the `.slice(0,-2)` :(
Will edit in an explanation tomorrow when I'm less tired.

Replaced every single byte with the corresponding hex value in order for the code snippet to be able to run

```
f=_=>
[...`\xc3\x6d\xb0\xdb\x6d\xb6\xdb\x6d\xb6\xdb\x6d\xb6\xdb\x60\x00\x00\x6d\xb6\xdb\x6d\xb6\xdb\x6d\xb6\xdb\x6d\x86\xe7\x1d\xb1\xc7\x6d\xb6\xdb\x6d\xb6\xdb\x6d\xb6\xdb\x68\x00\x00\x0b\xb6\xdb\x6d\xb0\xdb\x6d\xb6\xdb\x6d\x8e\x3c\xe2\x06\x38\xe0\x00\xc0\x01\xb0\x00\x6c\x36\xc3\x6d\x80\x00\x6d\x80\x03\x60\x01\xc4\x6c\x00\x1b\x00\x01\xc7\x9d\x80\xa7\x15\x86\xc7\x61\x99\xd8\x66\x71\xc7\x1d\x8e\xc0\x0b\x96\x1b\x14\x00\xbb\x0a\xb0\xda\xac\x00\xa0\xf3\x8e\xd8\xe9\xa6\x38\xe3\x8e\x38\xe3\x8e\x20\xe3\xb1\xc4\x00\x26\x98\xe2\x00\xc7\x11\x34\x59\x1c\x76\xd8\x6e\x41\xdb\x10\x58\x24\x1c\x48\x47\x12\x16\x60\x6c\x76\x20\x00\x00\xa0\x91\x00\x0b\x30\x05\x00\x0a\x0e\xd8\x83\xf6\xdb\x6d\xb6\xdb\x62\x0e\xd8\x83\xb6\x80\x00\x80`].map(a=>'0'.repeat(8-(z=a.charCodeAt().toString(2)).length)+z).join``.replace(/.{1,3}/g,a=>`_|/\\()
`[parseInt(a,2)]).slice(0,-2)

a.innerHTML=f()
```

```
<pre id=a>
```
> 0 votes

# Answer
# JavaScript, ~~294~~ 292 bytes

```
_='_&3,,& *.,,&_ 7+&+,,-(*.)&&& _,-+7+__1 . .-.3&_& ._&.-*+_-.-.+7|3_)+2_43 b|3 \\+14-*) 2_4/*)3)2_-)2*)_|7+&| 51111 6+-+.51*1_52/+& _ 7|0\\_|6+6/+62\\__44*.)_|6(*2\\*).)07,40&(./,&&&&0_|&6|&- .*_*___1 ++| |3-_4-|- 2/ 5( (6|_7\n';for(Y in $='7652-43+1*.&0,')with(_.split($[Y]))_=join(pop());_

```

This... is literally just encoding of the art... with this...

If `console.log()` is required, then byte count is ~~307~~305 bytes.

294-\>292, -2B for encoding `\n` to `7`.
> 0 votes

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


title: Christmas Cracker Mystery Calculator

text:
# Question
Title: Christmas Cracker Mystery Calculator
The presents have been opened. The mince-pies have been eaten. The Star Wars have been watched. The Christmas Season is beginning to wind down. By now you may well have pulled a few Christmas Crackers. If you're lucky, instead of the usual useless plastic toys, you may have won a **Mystery Calculator** with which you can *amaze your friends and relatives*.

This trick consists of 6 cards each with a 4x8 grid of numbers printed on it. Each card contains a different subset of the integers `[1,63]`. The magician will ask you to pick a number from one card and keep that number secret. The magician will then ask which cards have that number. With that knowledge, the magician will *magically* be able to determine and disclose the original number guessed.

---

Output the full set of 6 Mystery Calculator cards exactly as follows:

```
 1  3  5  7  9 11 13 15
17 19 21 23 25 27 29 31
33 35 37 39 41 43 45 47
49 51 53 55 57 59 61 63
 - - - - - - - - - - -
 2  3  6  7 10 11 14 15
18 19 22 23 26 27 30 31
34 35 38 39 42 43 46 47
50 51 54 55 58 59 62 63
 - - - - - - - - - - -
 4  5  6  7 12 13 14 15
20 21 22 23 28 29 30 31
36 37 38 39 44 45 46 47
52 53 54 55 60 61 62 63
 - - - - - - - - - - -
 8  9 10 11 12 13 14 15
24 25 26 27 28 29 30 31
40 41 42 43 44 45 46 47
56 57 58 59 60 61 62 63
 - - - - - - - - - - -
16 17 18 19 20 21 22 23
24 25 26 27 28 29 30 31
48 49 50 51 52 53 54 55
56 57 58 59 60 61 62 63
 - - - - - - - - - - -
32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47
48 49 50 51 52 53 54 55
56 57 58 59 60 61 62 63

```

Output may or may not contain one final trailing newline. There must be no trailing whitespace. Each card is separated by 11 `-` perforations.

* md5sum with final newline: `7aa2d9339b810ec62a2b90c5e11d6f4a`
* md5sum without final newline: `e9abe4e32dca3e8fbfdaa4886fc5efd2`

For those of you of more of a windows orientation, I will also allow `CRLF` style line endings. In that case, the md5s are:

* md5sum with final newline: `e4f16ff9752eee2cedb5f97c7b5aec6d`
* md5sum without final newline: `78c560eed3b83513e3080117ab5dc5fa`

# Answer
# Python 2, ~~99~~ ~~96~~ ~~93~~ 91 bytes

```
k=1
while 1:print('%2d '*7+'%2d\n')*4%tuple(n for n in range(64)if k&n),11/(k<32)*' -';k*=2

```

Exits with an error, which is allowed by default.

Try it online! or verify the MD5 hash.

### How it works

After initializing **k** as **1**, we enter an infinite loop that executes the following code.

```
print('%2d '*7+'%2d\n')*4%tuple(n for n in range(64)if k&n),11/(k<32)*' -';k*=2

```

`tuple(n for n in range(64)if k&n)` creates a tuple of all non-negative integers below **64** that have there **j**th bit set, where **j** is the iteration count of the loop, i.e., **2j = k**.

`('%2d '*7+'%2d\n')*4` first creates the format string `'%2d %2d %2d %2d %2d %2d %2d \n'`, then repeats it four times. This is a template for each card, which pads each integer in the tuple to two characters (prepending spaces), separates each group of **8** integers by spaces, and the groups themselves by linefeeds.

Now, Python 2's `print` statement is a curious beast. It takes several expressions, separated by commata, and prints them one by one. It evaluates the first expression, prints it, evaluates the next expressions, prints it, etc. until no more expressions are left. Unless the last expression is followed by a comma, it appends a linefeed to it. Also, it prepends a space to all expressions, unless they are printed at the beginning of a line.

In each iteration, we first print the result of applying the format string to the tuple. We're at the beginning of a line, so no space is prepended.

Then, we (attempt to) print the result of `11/(k<32)*' -'`. If **k \< 32**, this expressions evaluates to `' - - - - - - - - - - -'`. Again, we're at the beginning of a line, so no space is prepended. There is no comma after this expression, so `print` appends a linefeed. However, in the sixth iteration, **k = 25 = 32**, so trying to evaluate `11/(k<32)*' -'` raises an uncaught *ZeroDivisionError*. This breaks out of the loop and ends the program immediately.
> 10 votes

# Answer
# C (gcc), 105 bytes

```
o;main(i){for(;i<384;i++%64||puts(" - - - - - - - - - - -"))i&1<<i/64&&printf("%2d%c",i%64,++o%8?32:10);}

```
> 7 votes

# Answer
# Jelly, ~~27~~ 26 bytes

```
Ts8GW
⁾ -ẋ11W
63RBUz0Ñ€j¢Y

```

Try it online! or verify the MD5 hash.

### How it works

```
63RBUz0Ñ€j¢Y  Main link. No arguments.

63R           Range 63; yield [1, ..., 63].
   B          Binary; convert each integer to base 2.
    U         Upend; reverse the binary representations.
     z0       Zip with filler 0; transpose rows and columns, filling gaps in
              the (non-rectangular) matrix with zeroes.
       Ñ€     Map the first helper link over the new rows.
          ¢   Yield the return value of the second helper link.
         j    Join the left result, separating by the right result.
           Y  Join the results, separating by line feeds.

Ts8G          First helper link. Argument: A (array of 1's and 0's)
T             Truth; get all indices of 1's.
 s8           Split the indices into chunks of length 8.
   G          Grid; convert the 2D array into a string, separating row items
              by spaces, rows by linefeeds, and left-padding each integer
              with spaces to equal lengths.
    W         Wrap the generated string in an array.

⁾ -ẋ11W       Second helper link. No arguments.

⁾ -           Yield " -".
   ẋ11        Repeat the string 11 times.
      W       Wrap the generated string in an array.

```
> 5 votes

# Answer
# Python 2, 132 bytes

```
for c in range(6):s=" ".join("%2d"%n for n in range(64)if n&1<<c);print"\n".join([s[24*i:24*i+23]for i in range(4)]+[" -"*11]*(c<5))

```

Splitting sequences is annoying in Python.

Try it online.
> 5 votes

# Answer
# Pip, ~~49~~ ~~48~~ 44 bytes

43 bytes of code, +1 for `-S` flag.

```
Fi,6{IiP" -"X11P(sX2-#_._M2**iBA_FI,64)<>8}

```

Try it online!

### Explanation

```
                                             s is space (preinitialized)
Fi,6{                                     }  For i in range(6):
     Ii                                      If i is nonzero (i.e. all except 1st loop):
       P" -"X11                              Print hyphens
                                 FI,64       Range(64), filtered on this function:
                          2**iBA_              2**i bitwise AND with argument (is nonzero)
                         M                   To each remaining number, map this function:
                   2-#_                        2-len(argument)
                 sX                            ^ that many spaces
                       ._                      prepended to argument
                (                     )<>8   Group list into length-8 sublists
               P                             Print (-S flag joins on space then newline)

```
> 5 votes

# Answer
# Ruby, 90 bytes

```
1.upto(383){|i|print (j=i%64)<1?' -'*11+$/:"%2d%s"%[j,j+1&15>>i/256>0?' ':$/]*(j>>i/64&1)}

```

**Ungolfed**

Fairly straightforward. The only thing that may require additional explanation is when to follow a number with a newline rather than a space. This happens when `j+1%16==0` in the first four cards and `j+1%8`==0 in the last two. Hence the expression `15>>i/64/4` or equivalently `15>>i/256`is ANDed with `j` to determine whether space or newline is required.

```
1.upto(383){|i|                              #Count starting at 1 instead of 0 to supress - -  before 1st card
  print (j=i%64)<1?                          #j=number to consider for card. If 0,
    ' -'*11+$/:                              #print - - -... else print
     "%2d%s"%[j,j+1&15>>i/256>0?' ':$/]*     #j formatted to 2 spaces followed by a space (or if j+1 divisible by 16 or 8 depending on card, a newline.)
     (j>>i/64&1)                             #only print appropriate numbers for this card, i.e. when this expression evaluates to 1
}

```
> 4 votes

# Answer
## JavaScript (ES6), 150 bytes

```
f=
_=>[1,2,4,8,16,32].map(m=>[...Array(64)].map((_,i)=>` ${i}`.slice(-2)).filter(i=>i&m).join` `.replace(/(.{23}) /g,`$1
`)).join(`
${` -`.repeat(11)}
`)
;document.write(`<pre>`+f())
```
> 3 votes

# Answer
# Perl 6,  ~~194 116~~  86 bytes

```
put join "\n{' -'x 11}\n",map {join "\n",.[^32].rotor(8)».fmt('%2s')},(1,3...63),(2,{|($_ X+1,4)}...*),(4,{|($_ X+1,2,3,8)}...*),(8,{|((1...7,16)X+$_)}...*),(16,{|((1...15,32)X+$_)}...*),32..63

```

Try it

```
for 1..383 {print !($/=$_%64)??"{' -'x 11}\n"!!$/+>($_/64)%2??$/.fmt('%2d')~(($/+1)+&(15+>($_/256))??' '!!"\n")!!''}

```

Try it

```
for 1..383 {$_%64||put ' -'x 11;$_+&(1+<($_/64))&&printf "%2d%c",$_%64,++$/%8??32!!10}

```

Try it

(check the *Debug* sections for the MD5 results)
The last two were inspired/transcribed from the Ruby and C implementations
> 2 votes

# Answer
# 05AB1E, 71 bytes

```
63L©DÉÏ®À2ô®ÉÏ®ÀÀÀ4ô®ÉÏ®Á8ô®ÈÏ63®Á16ô®ÈÏ63D32sŸ)˜32ôvy8ôvy.B}„ -11×})¨»

```

Try it online!

This approach, don't try it. Will likely delete this out of shame to be honest. Matrix manipulation is not my strong suit so I tried to brute force generate all 6 sequences and then pump them together sloppily.
> 2 votes

# Answer
## Batch, 249 bytes

```
@echo off
set s=
for %%i in (1 2 4 8 16 32)do for /l %%j in (0,1,63)do call:c %%i %%j
exit/b
:c
if %2==0 if %1 gtr 1 echo  - - - - - - - - - - -
set/an=%1^&%2
if %n%==0 exit/b
set n=  %2
set s=%s%%n:~-3%
if not "%s:~23%"=="" echo%s%&set s=

```

Outputs a trailing CRLF.
> 1 votes

# Answer
## JavaScript (ES6), ~~103~~ 102 bytes

```
f=(k=1,n=z=0)=>n>>6?k>>5?'':' -'.repeat(11)+`
`+f(k*2):(n&k?(n>9?'':' ')+n+`
 `[++z&7&&1]:'')+f(k,++n)

```

*MD5: 7AA2D9339B810EC62A2B90C5E11D6F4A*

### Test

```
f=(k=1,n=z=0)=>n>>6?k>>5?'':' -'.repeat(11)+`
`+f(k*2):(n&k?(n>9?'':' ')+n+`
 `[++z&7&&1]:'')+f(k,++n)

console.log(f())
```
> 1 votes

# Answer
# bash / Unix utilities, ~~125~~ 124 bytes

```
b='- - - - ';for ((x=1;x<33;x*=2));{ for n in {0..63};{ ((x&n))&&printf \ %2d $n;};echo $b$b$b;}|fold -w24|sed -e\$d -es/.//

```

*Edit: Removed an unnecessary ^ from the regex at the end; the regex will always match at the beginning of the line anyway.*
> 1 votes

# Answer
# PHP, 102 bytes

```
for(;$c<6;$n%32||$c+=print str_pad("
",25," -"),$n%2**$c||$b+=1<<$c)printf("
"[$n++%8]."%3d",++$b%64);

```

prints a leading but no trailing newline, and one leading space in each line. Run with `-nr` or try it online.

For PHP\<5.6, replace `2**$c` with `(1<<$c)`. PHP 5.5 could use `&~1<<$c?:` instead of `%2**$c||`.
For PHP\<5.5, replace `"\n"[$n++%8]` with `($n++%8?"":"\n")`.

---

Dashes are one character off due to the leading space; append a space to the first `str_pad` parameter (insert a space before the second code line) to fix.

Removing the leading space instead requires some fiddling and three additional bytes: `printf("%c%2d",$n++%8?32:10,++$b%64);` and `23` instead of `25`.

Turning the leading newline into a trailing one would cost another three bytes:

```
for(;$c<6;$n%32||$c+=print str_pad("",22," -")."
",$n%2**$c||$b+=1<<$c)printf("%2d%c",++$b%64,++$n%8?32:10);

```

---

# PHP, 109 bytes

```
for($c=1;~$c&64;$n%32||$c<<=print str_pad("",22," -")."
",$n%$c||$b+=$c)printf("%2d%c",++$b%64,++$n%8?32:10);

```

matches all specs and works with all PHP versions.
> 1 votes

# Answer
# Python 2, 89 bytes

```
i=0;exec"print('%2d '*7+'%2d\\n')*4%tuple(j for j in range(64)if j&2**i)+' -'*11;i+=1;"*6

```

Try it online!

Explanation:

```
# initialize outer counter variable
i=0
           # generate a formatting string for a single row of numbers
           # %2d will left pad an integer with spaces, up to string length 2
           # the \\n is so that exec will interpret it as a character rather than a literal line break
           '%2d '*7+'%2d\\n'
          # create a formatting string of 4 lines of 8 numbers
          (.................)*4
                               # format the string with a generated tuple of numbers that have a 1 in the current bit slot
                               # (or more literally, bitwise j AND 2^i is not zero)
                               %tuple(j for j in range(64)if j&2**i)
                                                                    # add the perforation break
                                                                    +' -'*11
     # print the generated string, then increment the counter
     print..................................................................;i+=1
# execute the following statements 6 times
exec"............................................................................."*6

```
> 1 votes

# Answer
# 05AB1E, 29 bytes

```
63L2вíƶ0ζε0K8ô§2j»}„ -11×¶.øý

```

Port from *@Emigna*'s 05AB1E answer here, after which I added additional code to print it according to the requirements in this challenge.

Try it online or verify md5sum.

**Explanation:**

```
63L          # Create a list in the range [1,63]
   2в        # Convert each number to binary as lists of 0s and 1s
     í       # Reverse each binary list
      ƶ      # Multiply each binary digit by its 1-based index [1,length] (so [1,63])
       0ζ    # Zip/transpose; swapping rows/columns, with "0" as filler
ε            # Map each inner list to:
 0K          #  Remove all 0s
   8ô        #  Split it into (four) lists of size 8
     §       #  Cast each integer to string (bug, shouldn't be necessary..)
      2j     #  And pad leading spaces to make each string size 2
        »    #  Join the inner lists by spaces, and then all strings by newlines
}„ -         # After the map: push string " -"
    11×      # Repeated 11 times to " - - - - - - - - - - -"
       ¶.ø   # Surround it with newlines: "\n - - - - - - - - - - -\n"
          ý  # And join the mapped strings with this delimiter-string
             # (after which the result is output implicitly)

```
> 1 votes

# Answer
# JavaScript, 234 bytes.

```
for(a=[[],[],[],[],[],[]],i=1;i<64;i++)for(j=0;j<6;j++)i&2**j?a[j].push(i<10?" "+i:i):0;for(j=0;j<6;j++){for(s=[],i=0;i<4;)s.push(a[j].slice(i*8,++i*8).join(" "));b=s.join(n="\n");a[j]=b.substr(0,b.length)};a.join(n+" -".repeat(11)+n)

```

I will write explanation later.

If `console.log` is required, the byte count would be 247 bytes.
> 0 votes

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


title: Different number, same weight

text:
# Question
Title: Different number, same weight
# Background

The Hamming weight of an integer is the number of ones in its binary representation. For this challenge, integers are represented with 32 bits, and they are unsigned.

# Challenge

Given an integer between 0 and 2^32-1 (non-inclusive), output a *different* integer within the same range, and also with the same Hamming weight.

# Examples

```
Input (Decimal) | Input (Binary) | Hamming weight | Possible output (Decimal)
       46       |   0b0010 1110  |       4        |      15
       12       |   0b0000 1100  |       2        |      3
        1       |   0b0000 0001  |       1        |      2
        3       |   0b0000 0011  |       2        |      6
      2^31      |   0b1000....0  |       1        |      1
      2^31+2    |   0b1000...10  |       2        |      3
      2^32-5    |   0b1111..011  |       31       |      2^31-1
      2^32-2    |   0b1111....0  |       31       |      2^31-1
        0       |   0b0000 0000  |       0        | None (This case need not be handled)
      2^32-1    |   0b1111....1  |       32       | None (This case need not be handled)

```

# Scoring

This is , so the solution in the fewest bytes in each language wins.

# Answer
# x86-64 assembly, ~~5~~ 4 bytes

```
   0:   97                      xchg   %eax,%edi
   1:   d1 c0                   rol    %eax
   3:   c3                      retq

```

A function using the C calling convention that bitwise rotates its argument left by 1 bit.
> 29 votes

# Answer
# Python, 20 bytes

```
lambda x:x*2%~-2**32

```

Bitwise rotation left by 1 bit.
> 8 votes

# Answer
# Jelly, ~~10~~ 8 bytes

```
‘&~^^N&$

```

Swaps the least significant set and unset bit.

Try it online!

### How it works

```
‘&~^^N&$  Main link. Argument: n

‘         Increment; yield n+1, toggling all trailing set bits and the rightmost
          unset bit.
  ~       Bitwise NOT; yield ~n, toggling ALL bits of n.
 &        Bitwise AND; yield (n+1)&~n, keeping the only bit that differs in n+1 and
          ~n, i.e., the rightmost unset bit.
   ^      Perform bitwise XOR with n, toggling the rightmost unset bit.
       $  Combine the two links to the left into a monadic chain.
     N        Negate; yield -n. Since ~n = -(n+1) in 2's complement, -n = ~n+1.
      &       Take the bitwise AND of n and -n. Since -n = ~n + 1 and n = ~~n, the
              same reasoning that applied for (n+1)&~n applies to -n&n; it yields
              the rightmost unset bit of ~n, i.e., the rightmost set bit of n.
    ^      XOR the result to the left with the result to the right, toggling the
           rightmost set bit of the left one.

```
> 6 votes

# Answer
# MATL, 9 bytes

```
32&B1YSXB

```

Circularly shifts the 32-digit binary representation one step to the right.

Try it online!
> 6 votes

# Answer
## JavaScript (ES6), ~~35~~ 31 bytes

Looks for the first bit transition (0 → 1 or 1 → 0) and inverts it.

```
f=(n,k=3)=>(n&k)%k?n^k:f(n,k*2)

```

### Demo

```
f=(n,k=3)=>(n&k)%k?n^k:f(n,k*2)

;[ 46, 12, 255, 2**32-2 ]
.map(n => {
  r = f(n);
  console.log((n >>> 0), '=', (n >>> 0).toString(2), '-->', (r >>> 0), '=', (r >>> 0).toString(2));
})
```

## Bit rotation, 14 bytes

Much shorter but less fun.

```
n=>n>>>31|n<<1

```

### Demo

```
let f =

n=>n>>>31|n<<1

;[ 46, 12, 255, 2**32-2 ]
.map(n => {
  r = f(n);
  console.log((n >>> 0), '=', (n >>> 0).toString(2), '-->', (r >>> 0), '=', (r >>> 0).toString(2));
})
```
> 5 votes

# Answer
# Brain-Flak, 78 bytes

```
(([()()])[[]()]){((){}<({({})({}())}{})>)}{}([(({}(({}){})())<>)]){({}())<>}{}

```

Try it online!

Returns 2n if n \< 2^31, and 2n+1-2^32 otherwise. Unfortunately, because Brain-Flak doesn't have any fast way to determine the sign of a number, the program times out on TIO if the input differs from 2^31 by more than about 500000.

### Explanation

First, push -2^32 onto the stack:

```
(([()()])[[]()])                               push (initial value) -2 and (iterator) -5
                {((){}<                >)}     do 5 times:
                       ({({})({}())}{})        replace the current (negative) value with the negation of its square
                                            {}   pop the (now zero) iterator

```

Then, compute the desired output:

```
      (({}){})                        replace n by 2n on left stack
   ({}        ())                     push 2n+1-2^32 on left stack
  (              <>)                  push again on right stack
([                  ])                push its negation on right stack
                      {({}())<>}      add 1 to the top value of each stack until one of them reaches zero
                                {}    pop this zero, and implicitly print the number below it on the stack

```
> 4 votes

# Answer
# dc, 10

```
?2~z31^*+p

```

Try it online.

This is an arithmetic implementation of a 32bit right-rotate:

```
?           # input
 2~         # divmod by 2 - quotient pushed first, then the remainder
   z        # z pushes the size of the stack which will be 2 (quotient and remainder) ...
    31^     #  ... and take that 2 to the 31st power
       *    # multiply the remainder by 2^31
        +   # add
         p  # output

```
> 3 votes

# Answer
# APL, 12 bytes

```
(2⊥32⍴1)|2×⊢

```

**How?**

```
           ⊢  ⍝ monadic argument
         2×   ⍝ shift left (×2)
(2⊥32⍴1)|     ⍝ modulo 2^32 - 1

```
> 3 votes

# Answer
# Java 8, ~~117~~ ~~17~~ 29 bytes

```
n->n*2%~-(long)Math.pow(2,32)

```

+12 bytes by changing `int` to `long`, because `int`'s max size is `2³¹-1`

~~100~~ 89 bytes saved by creating a port of *@AndersKaseorg*'s amazing Python answer.

Try it here.

Outputs:

```
46 (101110):                                     92 (1011100)
12 (1100):                                       24 (11000)
1 (1):                                           2 (10)
3 (11):                                          6 (110)
10000 (10011100010000):                          20000 (100111000100000)
987654 (11110001001000000110):                   1975308 (111100010010000001100)
2147483648 (10000000000000000000000000000000):   1 (1)
4294967294 (11111111111111111111111111111110):   4294967293 (11111111111111111111111111111101)

```

**Old answer (~~117~~ 118 bytes):**

```
n->{long r=0;for(;!n.toBinaryString(++r).replace("0","").equals(n.toBinaryString(n).replace("0",""))|r==n;);return r;}

```

+1 byte by changing `int` to `long`, because `int`'s max size is `2³¹-1`

Try it here.

Outputs:

```
46 (101110):                                     15 (1111)
12 (1100):                                       3 (11)
1 (1):                                           2 (10)
3 (11):                                          5 (101)
10000 (10011100010000):                          31 (11111)
987654 (11110001001000000110):                   255 (11111111)
2147483648 (10000000000000000000000000000000):   1 (1)

```
> 3 votes

# Answer
## Mathematica, 29 bytes

```
Mod@##+Quotient@##&[2#,2^32]&

```

Try it at the Wolfram sandbox

Rotates left arithmetically: first multiply by 2, which possibly shifts the number out of range, then cut off the out-of-range digit with `Mod[...,2^32]` and add it back on the right with `+Quotient[...,2^32]`.

(Mathematica does have a single builtin that gives the modulus and the quotient in one go, but it's `QuotientRemainder`, which is a bit of a golfing handicap…)
> 2 votes

# Answer
# 05AB1E, 5 bytes

```
·žJ<%

```

Try it online!

**Explanation**

Uses the trick to rotate the binary representation left by 1 bit from Anders Kaseorg's python answer.

```
·       # input * 2
    %   # modulus
 žJ<    # 2^32-1

```
> 1 votes

# Answer
## R, ~~42~~ 63 bytes

```
function(x){s=x;while(s==x){sample(binaryLogic::as.binary(x))}}

```

Shuffles the bits around randomly, but checks to make sure it didn't return the same number by chance.
> 1 votes

# Answer
# Whitespace, ~~81~~ 80 bytes

(1 byte saved thanks to @Ørjan Johansen reminding me dup is shorter than push 0)

```

```

Try it online!

Basically implements a cyclic right bitshift using integer arithmetic. Pushing a large constant is expensive in Whitespace so we save some bytes by pushing 2^8 and squaring it twice. (Saves 1 byte over (2^16)^2 and 10 bytes over pushing 2^32 directly.)

## Explanation

```
sssn  ; push 0
sns   ; dup
tntt  ; getnum from stdio
ttt   ; retrieve n from heap and put it on the stack
sns   ; dup
ssstsn ; push 2
tstt  ; mod - check if divisible by 2 (i.e. even)
ntsn  ; jez "even"
ssstssssssssn ; push 2^8
sns   ; dup
tssn  ; mul - square it to get 2^16
sns   ; dup
tssn  ; mul - square it to get 2^32
tsss  ; add 2^32 so MSB ends up set after the divide
nssn  ; even:
ssstsn ; push 2
tsts  ; divide by 2, aka shift right
tnst  ; putnum - display result

```
> 1 votes

# Answer
# Python 2.7, 89 bytes

Full Program:

```
from random import*;a=list(bin(input())[2:].zfill(32));shuffle(a);print int(''.join(a),2)

```

Try it online!

Suggestions welcome! :)
> 0 votes

# Answer
# Pari/GP, 15 bytes

```
n->2*n%(2^32-1)

```

Try it online!
> 0 votes

# Answer
# Japt, 5 bytes

```
Ñ%3pH

```

Bitwise rotation, like most answers here.

Try it
> 0 votes

# Answer
# Perl 5 `-p`, 39 bytes

```
$_=sprintf'0b%b',$_;$_=oct$_.int s/10//

```

Try it online!
> 0 votes

# Answer
# C++ (gcc), ~~45~~ 39 bytes

*-6 bytes thanx to ceilingcat*

```
auto h(unsigned x){return x%2<<31|x/2;}

```

Try it online!
> 0 votes

# Answer
# Python 3, 45 bytes

```
lambda i:int(f'{i:32b}'[1:]+f'{i:32b}'[:1],2)

```

Try it online!
> 0 votes

---
Tags: code-golf, number, bitwise
---


title: Alphabetical Justice Warrior

text:
# Question
Title: Alphabetical Justice Warrior
### Introduction:

Aaron is a young game developer. He recently joined the development team of a game where the players select their character from a predefined set, aka "heroes". Unfortunately, the names of the existing heroes are not evenly distributed throughout the alphabet. For example, there are 6 heroes that have a name starting with C, but only 5 starting with A or B. Since the game will continue to add new heroes, and Aaron has a saying in how to name those, he is determined to try "smoothening" the distribution of hero names.

Of course, he cannot simply mathematically generate names as gap fillers, because those suggestions would be unpronounceable and thus rejected right away. Therefore, instead of calculating a name, Aaron opted to go with "just" a helper for his creative process that helps him to focus on the right things to do:

He will calculate the "distance" between each two names following each other in alphabetical order, and then print the top ten biggest gaps between two names. This way Aaron can try to focus on finding a name that comes in between those two, so he'll eventually create a smoother equidistant descend throughout the alphabet as the list of heroes continues to grow.

### The Challenge

For a given list of names, generate the entries' keys that consist of only the uppercase form of the letters `[A-Za-z]`. Calculate a distance between each two alphabetically adjacent keys.

The first key is additionally compared to the first possible key `"A"`, the last to the last possible key `"ZZZZZZZZZZZZ"`.

Print the **top ten (or all if there are less)** biggest gaps in descending order with both names as given by the input and a measurement for the size of the gap. The "given name" of the borders is an empty string.

### Input data

The list of names. Conditions as follows:

Entries:

* The entries are guaranteed to only contain printable ASCII characters (sorry `Björn NUL LF`)
* The characters may have any case (`"Tim"`, to be treated same as `"TIM"`)
* The entries have different lengths (`"Anna", "Jon"`)
* The entries are guaranteed to **not** contain commas, so you can use that as safe delimiter for your outputs
* The entries **do** contain other characters such as spaces or dots, which do not change the key as stated above (`"Mr. T"`, to be treated same as `"MRT"`)
* The entries **are** guaranteed to give keys within 1 to 12 (inclusive) letters (entries won't be `""` or `"-.-.-. -.--.-"` or `"Gandalf the White"`)
* The entries explicitly **may** contain single quotes `'` and double quotes `"`, in case this is important for escaping

List:

* The entries **are not** guaranteed to come in any particular order (e. g. `"Eve", "Dr. Best", "Dracula"`, keys sorted `"DRACULA", "DRBEST", "EVE"`)
* The list is guaranteed to have at least one entry
* The list is guaranteed to have only entries with distinct keys
* The list will not (and must not!) contain any entries that will give the keys `"A"` or `"ZZZZZZZZZZZZ"`

### Example

This was done in Excel. I limited the maximum length of 7 letters though for practical reasons (see notes), but the point should be clear.

```
List: ["Tim", "Mr. T", "Anna", "Jon", "Eve", "Dr. Best", "Timo", "Dracula"]
Keys: ["TIM", "MRT", "ANNA", "JON", "EVE", "DRBEST", "TIMO", "DRACULA"]
Ordered: ["ANNA", "DRACULA", "DRBEST", "EVE", "JON", "MRT", "TIM", "TIMO"]
Values: [595765044, 1808568406, 1809137970, 2255435604, 4096878669, 5305375503, 7884458676, 7884753921]
Distances: [1212803362, 569564, 446297634, 1841443065, 1208496834, 2579083173, 295245]
Distance from "ANNA" to "A": 208344555
Distance from "TIMO" to "ZZZZZZZ": 2575894526

Output (padding added for clarity, see "Rules #4"):
[    Mr. T,      Tim, 2579083173 ]
[     Timo,         , 2575894526 ]
[      Eve,      Jon, 1841443065 ]
[     Anna,  Dracula, 1212803362 ]
[      Jon,    Mr. T, 1208496834 ]
[ Dr. Best,      Eve,  446297634 ]
[         ,     Anna,  208344555 ]
[  Dracula, Dr. Best,     569564 ]
[      Tim,     Timo,     295245 ]

```

Interpretation: Aaron should focus on finding a name in the middle between "Mr. T" and "Tim". Welcome **Pyrion**, splitting `2579083173` into `1261829394 + 1317253779`, while sounding absolutely badass! This is not part of the challenge however, only the top ten pairs and their distance should be output.

### Rules

* *Ex falso sequitur quodlibet.* If the input data does not conform to the rules set above, the program may do whatever, including crashing.
* You are free to chose your method of measurement for the distance, but it has to ensure the following: `AAA` and `AAC` are further apart than `AAA` and `AAB`. `AAA` is closer to `AAB` than to `ABA`. `AA` comes after `A` (so basically: all possible names are ordered lexicographically). This means the distance in the output could differ per answer, but the order of the pairs are strict.
* Range and precision of the gaps is arbitrary, as long as you have a non-zero distance between `"AAAAA AAAAA AA"` and `"AAAAA AAAAA AB"`.
* The output has to contain the names as given (not the keys) and the distance. The precise formatting is up to you, as long as it's clear what belongs together. `Name1,Name2,Distance` is a safe bet.
* As mentioned earlier, if there are more than ten results, only output the top ten.
* The borders of `"A"` and `"ZZZZZZZZZZZZ"` are empty strings in the output.

### Winner

* Code golf, shortest code by bytes wins.

### Notes

* The example above was done in Excel and uses a base 27 number system. It was limited to 7 letters, because for 12, the upper bound would be `27^13 - 1 = 4,052,555,153,018,976,266` which exceeds Excel's internal number range. If you were to add a test-link for your code which times out for 12 letter keys, feel free to use a smaller value so your program can be verified in the test-link.
* I am aware that the "measurement of the gap size" may vary depending on the algorithm. Some might not even have "one number" to sum it up. Try your best to find something conveying that finding a name between `"Mr. T"` and `"Tim"` helps a lot more than between `"Mr. T"` and `"Jon"` on our road to more equidistant names.
* This is my first posting here, feel free to comment if I need to add or clarify something. I've been looking at other content and hope I did everything right.
* The problem is derived from an actual problem I had to solve lately and I thought it might be a fun one to post it here.

# Answer
# Perl 6, 136 bytes

```
{$!=$;$/=1;(|.sort(&h),'').map({~$!,~($!=$_),-$/+($/=(sort('A'..'Z'x 12)....&h||'Z'x 12))}).sort(-*[2])[lazy ^10]}
my&h={S:g/<:!L>//.uc}

```

Try it online!

This is an anonymous code block that takes a list of strings and returns a list of lists. This uses a brute forcey method which takes *far* too long to attempt 12 letter names, so here is a link to a version with only 3 letter names.

### Explanation:

```
my&h={              }  # Helper function.
      S:g/<:!L>//      # This removes non-alpha characters
                 .uc   # Convert to uppercase

{              # Actual code block
  $!=$;        # Initialise the "first" element as an empty string
  $/=1;        # With value 1
  (|.sort(&h)  # Sort the input by the helper function
   ,'')        # And add the last string as an empty string
  .map({       # Map each value to
    ~$!,          # The previous name
    ~($!=$_),     # The current name
    -$/           # The negative of the previous value
       +($/=(     # Plus the new value, which is:
             sort('A'..'Z'x 12)     # From the lexographically sorted list of names
             ...                    # Get the sublist up to
                .&h                 # The current name
                   ||'Z'x 12        # Or the last name if the current is empty
        ))   # And get the length of the list
   }).sort(      # Sort each list
     *[2]        # By the third element
   )[lazy ^10]   # And get the first 10 or less items

```
> 4 votes

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


title: The easy way to code-golf ascii art!

text:
# Question
Title: The easy way to code-golf ascii art!
# Task:

> There are a lot of answers on this site that are arranged into ascii art, like this one. Usually the arrangement is done manually, but wouldn't a program help with that? :)

Your program will take 3 inputs:

* The code, as one single line
* The number of lines in the pattern (can be omitted if not necessary)
* The pattern itself, as `*`s or another char

# Rules:

* You have to write a program (not a function) that reads from stdin
* The text is placed left-to-right per line
* If there is not enough text to fill the pattern, put `.`s in the remaining spaces
* If there is too much text to fill the pattern, print it out after the output
* , so the shortest code, in bytes wins

# Sample Runs:

**Input (Exact Fit test)**:

```
qwertyuiopasdfghjklzxcvbnm
4
***** * ***
*   * * *
*   * * *
***** * ***

```

**Output**:

```
qwert y uio
p   a s d
f   g h j
klzxc v bnm

```

**Input (Extra characters test)**:

```
qwertyuiopasdfghjklzxcvbnm12345
4
***** * ***
*   * * *
*   * * *
***** * ***

```

**Output**:

```
qwert y uio
p   a s d
f   g h j
klzxc v bnm
12345

```

**Input (Insufficient Characters test)**:

```
qwertyuiopasdfg
4
***** * ***
*   * * *
*   * * *
***** * ***

```

**Output**:

```
qwert y uio
p   a s d
f   g . .
..... . ...

```

# Answer
> 5 votes
### GolfScript, 30 characters

```
n/(\(;n*'*'/{@.!'.'*+([]+@+}*\

```

Run online.

*Examples:*

```
> qwertyuiopasdfghjklzxcvbnm
> 4
> ***** * ***
> *   * * *
> *   * * *
> ***** * ***

qwert y uio
p   a s d
f   g h j
klzxc v bnm

> qwertyuiopasdfghjklzxcvbnm
> 1
> ***** * ***

qwert y uio
pasdfghjklzxcvbnm

> qwerty
> 2
> ***** * ***
> *   * * *

qwert y ...
.   . . .

```

# Answer
> 10 votes
# Perl 6: ~~60 characters~~ *EDIT*: 38 points (see bottom)

```
  #C#O     D#E#G#O       #L#
#F    #.#S#       T#A#C#K
  get\     .subst(       "*"
,{    shift       BEGIN [
  get\     .comb,\       "."
xx    * ]},       :g)\ .\
  say\     xx get\       ()\
#E    #X#C#       H#A#N#G
  #E#.     #C#O#M#       #!#

```

If you don't appreciate my terrible art skills, here's the golf:

```
get.subst("*",{shift BEGIN [get.comb,"."xx*]},:g).say xx get

```

This one does weird things with evaluation times.

First, the `BEGIN` keyword forces `[get.comb, "." xx *]` to be evaluated first, putting into an array the list of characters that make up "the code", followed by an infinite amount of `"."`s.

Next, the `get` at the end is evaluated, getting the number of lines of the ASCII art template. The `xx` operator repeats the first part of the program this many times. This makes more sense when you realize that `code() xx count()` is basically sugar for `code() for 1..count()`: `count()` should be evaluated first.

Finally, the `get` in the beginning of the program gets a line of the ASCII art template and substitutes every `"*"` with a value shifted off of the beginning of the array we made before everything else (`{shift BEGIN …}`).

## EDIT:

Golfed down to 37 characters, plus one for the command line switch:

```
perl6 -pe's:g[\*]=shift BEGIN [get.comb,"."xx*]'

```

This is the same concept as the original, the `-p` switch iterating over each line (after the `BEGIN` has read in "the code"), and substituting all `*`s with the next letter from "the code" before printing it. The input format for this shouldn't include the number of lines of the format.

# Answer
> 6 votes
## Ruby 2.0, ~~53~~ 52 characters

```
c=gets.chop
$><<gets($n).gsub(?*){c.slice!(0)||?.}+c

```

As per the spec, doesn't use the 'number of lines' paramater.

Example run:

```
qwertyuiopasd
***** * ***
*   * * *
*   * * *
***** * ***

```

Output:

```
qwert y uio
p   a s d
.   . . .
..... . ...

```

# Answer
> 2 votes
# PowerShell, ~~63~~ ~~86~~ ~~83~~ 82 bytes

*+20 bytes thanks @Veskah*

```
param($s,$p)-join($p|% *ht($s|% Le*)'*'|% t*y|%{if($_-eq42){$_=$s[$i++]}"$_."[0]})

```

Try it online!

Less golfed:

```
param($string,$pattern)

$chars = $pattern |
    % PadRight ($string|% Length) '*' |
    % toCharArray |
    % {
        if($_-eq42){$_=$string[$i++]}    # $_ can become $null
        "$_."[0]                         # $_ or '.' if $_ is $null
    }
-join($chars)

```

# Answer
> 2 votes
# Japt, 18 bytes

```
sVè-)iVr-@t°J1 ª'.

```

Try it

# Answer
> 2 votes
# T-SQL, 142 bytes

> @h is the input text
>
> @ is the pattern

```
DECLARE @h varchar(max)='qwertyuiopasdfg'
DECLARE @ varchar(max)='
***** * ***
*   * * *
*   * * *
***** * ***'

WHILE @ like'%*'SELECT @=left(@,charindex('*',@)-1)+left(@h+'.',1)+stuff(@,1,charindex('*',@),''),@h=substring(@h,2,999)PRINT
concat(@,'
'+@h)

```

**Try it online**

# Answer
> 2 votes
# Perl 5 `-plF`, 51 bytes

```
$_=join'',<>;s/\*/@F?shift@F:'.'/ge;$\=$/.join'',@F

```

Try it online!

# Answer
> 1 votes
# JavaScript - 199

```
text="qwertyuiopasdfghjklzxcvbnm";
pattern="***** * ***\n*   * * *\n*   * * *\n***** * ***";

function p(a,c){z=c.length,y=a.length,x=0;for(i=z;i-->0;)if(c[i]=="*")x+=1;if(x-y>0)for(i=x-y;i-->0;)a+=".";for(;i++<x;)c=c.replace(new RegExp("[*]"),a[i]);console.log(c);console.log(a.substring(x))}

p(text,pattern);

```

Outputs extra characters in text input if not used in pattern, uses padded "." if there's not enough.

EDIT: modified to be a function accepting text and pattern

# Answer
> 1 votes
# JavaScript (ES6) -~~96~~ 87

```
r=(c,p)=>{c=0+c;console.log(p.replace(/\*/g,t=>(c=c.substr(1),c[0]||'.'))+c.substr(1))}

```

Note: As suggested by the OP, I am using a function. But if its required to have a program, here's a **93 chars solution**.

```
c=0+(x=prompt)();p=x();console.log(p.replace(/\*/g,t=>(c=c.substr(1),c[0]||'.'))+c.substr(1))

```

EDIT1: Major change, I don't know why I didn't realize this for the first time :P Saved 40 chars.

---

**Usage**:

```
// r(code, pattern)
r("qwertyuiopasdfghjklzxcvbnm", "***** * ***\n*   * * *\n*   * * *\n***** * ***\n** ** **)

```

---

**Test Input**: (without unneeded optional number as per spec)

```
qwertyuiopasdfghjklzxcvbnm
***** * ***
*   * * *
*   * * *
***** * ***
** ** **

```

**Output**:

```
qwert y uio
p   a s d
f   g h j
klzxc v bnm
.. .. ..      // not much text was there to fill *s - replaced with dots as per spec

```

---

**Ungolfed Code**:

```
function run(code, pattern){
  code = "0" + code;  // prepend a zero; useful for the substring operation ahead

  pattern = pattern.replace(/\*/g, function(){  // replace the dots
    // by removing the first letter of code
    // and replacing dot with the first-letter of leftover code
    // and if it isn't there (code finished)
    // return a dot

    code = code.substr(1);
    return c[0] || '.';
  });
  }

  // after this operation; code contains the last letter of the org. code

  console.log(  p +  // the pattern has now code
                "\n" +   // and a newline
                c.substr(1) // if there is more than one letter of code left; display it
             );
}

```

---

It would be very nice to hear of any suggestions from users :)

# Answer
> 1 votes
# C, 98, 91 characters

Here a pretty straight-forward C solution in under 100 characters. This doesn't use the line count input. (Else a second unneeded gets() would be needed).

```
char b[999],*s;c;main(){gets(s=b);while(~(c=getchar()))putchar(c^42?c:*s?*s++:46);puts(s);}

```

ungolfed:

```
char b[999],*s;c;
main(){
    gets(s=b);
    while(~(c=getchar()))
        putchar(c^42?c:*s?*s++:46);
    puts(s);
}

```

# Answer
> 1 votes
## Python 2.7, ~~165~~ ~~155~~ ~~150~~ ~~138~~ 119 characters

Okay, pretty much but I guess it's the tiniest way to do it with Python.

```
import sys
r=raw_input
l=list(r())
w=sys.stdout.write
for c in"\n".join([r()for _ in[1]*input()]):w(c=='*'and(l and l.pop(0)or'.')or c)
w("".join(l))

```

**Edit:** new functional 1.0.1 version with even less bytes used:

**Edit2:** `map(r,['']*input())` instead of `[r()for _ in[1]*input()]` and removed unused import

**Edit3:** `'>'*input()` instead of `['']*input()` saving one character and adding prompt character for pattern :)

```
r=raw_input
l=list(r())
print''.join(map(lambda c:c=='*'and(l and l.pop(0)or'.')or c,"\n".join(map(r,'>'*input())))+l)

```

# Answer
> 1 votes
# Perl, 70 characters

```
@_=split'',<>=~s/\n//r;<>;print/\*/?shift@_||'.':$_ for map{split''}<>

```

Or, without boundary check, 56 characters

```
@_=split'',<>;<>;print/\*/?shift@_:$_ for map{split''}<>

```

Note, this code is not using second line as in spec, and can be shortened by three characters `<>;`

# Answer
> 1 votes
# Bash, ~~166 156 111~~ 106

Reads from standard input, doesn't take a line count. First line of input is the code you want to put into ascii art, all subsequent lines are the ascii art, consisting of the `@` character. **Input has a maximum length of 999 chars, and is not permitted to contain forward slashes**. (I chose not to use `*` or `#` because they have special meanings in Bash).

```
read -n999 -d/ i p
while [[ $p =~ @ && -n $i ]];do
p="${p/@/${i:0:1}}"
i=${i:1}
done
tr @ .<<<"$p"
echo $i

```

**WARNING:** This program uses a file called `p`. After executing the program, delete `p` \- it will confuse the program the second time you run it.

Most of the work here is done by

```
p="${p/@/${i:0:1}}"
i=${i:1}

```

The first line substitutes the first `@` in the art with the first character of the code. The second line removes the first character of the code.

If there is not enough code to fill the shape, a newline is printed after the main ascii art output by `echo $i`.

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

```
var n=ReadLine();int k=0;foreach(var z in In.ReadToEnd())Write(z>33?(n+new string('.',999))[k++]:z);Write(n.Substring(k));

```

Try it online!

# Answer
> 0 votes
# 05AB1E, ~~18~~ ~~17~~ 15 bytes

```
s0¢.$«0¹S.;0'.:

```

Takes the code as first input, pattern as second (with `0` instead of `#`).

Try it online or verify all test cases.

**~~18~~ 15 bytes alternative by taking the inputs in reversed order:**

```
0¢.$¹ì0IS.;0'.:

```

Try it online.

**Explanation:**

```
s                # Swap with implicit inputs, so the stack order is now: [code, pattern]
 0¢              # Count the amount of "0" in the pattern
   .$            # Remove that many leading characters from the code
     «           # Append it to the (implicit) pattern input
      0¹S.;      # Replace every "0" one by one with the characters of the first code input
           0'.: '# Then replace any remaining "0" with "."
                 # (after which the result is output implicitly as result)

```

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