title: Marquee sign letters

text:
# Question
Title: Marquee sign letters
Each day you put up a new word on a marquee sign with movable letters, buying just the letters you need to write it. You re-use letters you've bought for earlier words whenever possible. Given the words you want to write each day in order, output the letters you buy each day.

> **Example**
>
> ```
> Input:  ['ONE', 'TWO', 'THREE', 'SEVENTEEN']
> Output: ['ENO', 'TW', 'EHR', 'EENSV']
>
> ```
>
> **Day 1:** You start with no letters, so to write `ONE`, you buy all its letters `E`, `N`, `O`.
> **Day 2:** The next day, you want to put up `TWO` (taking down the `ONE`). You already have an `O` from `ONE`, so you buy an additional `TW`.
> **Day 3:** At this point, you have `ENOWT`. To write `THREE`, you need `EHR`. Note that you need to buy a second `E` in addition to the one you have.
> **Day 4:** To write `SEVENTEEN`, you need 4 `E`'s total of which you already have two (not three!), so you buy two more. You also have the `T` and one of the `N`'s, so you buy the remaining letters: `EENSV`.
>
> We've output letters sorted alphabetically in this example, but you may output them in any order.

**Input:** A non-empty list of non-empty strings of letters `A-Z`. You may use lowercase if you prefer. Lists of characters are fine for strings.

**Output:** Output or print the additional letters you need to buy each day. The letters for a day may be output in any order, but the days must come in the right order.

The letters from each day should be separated from other days so you can tell where a day ends. A trailing and/or leading separator is fine, both within a day or between days. Note that a day may have no letters bought, which should be reflected in the output (a space or empty line is OK, even for the last day).

**Test cases**

```
['ONE', 'TWO', 'THREE', 'SEVENTEEN']
['ENO', 'TW', 'EHR', 'EENSV']

['ONE', 'TWO', 'ONE', 'THREE']
['ENO', 'TW', '', 'EHR']

['ABC', 'AABC', 'ABBC', 'ABCC', 'AABBCC']
['ABC', 'A', 'B', 'C', '']

['SHORT', 'LOONG', 'LOOOONG', 'LOOOOOOONG', 'SHORT', 'LOOONG']
['HORST', 'GLNO', 'OO', 'OOO', '', '']

```

Here are all the inputs and outputs as separate lists:

```
[['ONE', 'TWO', 'THREE', 'SEVENTEEN'], ['ONE', 'TWO', 'ONE', 'THREE'], ['ABC', 'AABC', 'ABBC', 'ABCC', 'AABBCC'], ['SHORT', 'LOONG', 'LOOOONG', 'LOOOOOOONG', 'SHORT', 'LOOONG']]
[['ENO', 'TW', 'EHR', 'EENSV'], ['ENO', 'TW', '', 'EHR'], ['ABC', 'A', 'B', 'C', ''], ['HORST', 'GLNO', 'OO', 'OOO', '', '']]

```

And as space-separated strings (the trailing spaces in the outputs matter):

```
ONE TWO THREE SEVENTEEN
ONE TWO ONE THREE
ABC AABC ABBC ABCC AABBCC
SHORT LOONG LOOOONG LOOOOOOONG SHORT LOOONG

ENO TW EHR EENSV
ENO TW  EHR
ABC A B C
HORST GLNO OO OOO

```

**Leaderboards**

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

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

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

# Answer
## Haskell, ~~54~~ 49 bytes

```
import Data.List
g x=zipWith(\\)x$scanl(++)""$g x

```

Try it online!

We build the output list by calculating pairwise the list difference (`\\`) of the input list and the cumulative append of the output list (starting with `""`).

```
input list:                ONE       TWO       THREE        SEVENTEEN
cumulative append:         ""   +->  ONE  +->  ONETW   +->  ONETWHRE
list difference (output):  ONE -+    TW  -+    HRE    -+    SVEEN

```

With both `Data.List` and `Data.Function` in scope (e.g. by using the lambdabot environment), this can be shortened to 30 bytes:

```
fix.(.scanl(++)"").zipWith(\\)

```

Edit: -5 bytes thanks to @Sriotchilism O'Zaic.
> 10 votes

# Answer
# Python 2, ~~72~~ 68 bytes

-4 bytes thanks to Jonathan Allan.

```
p=''
for r in input():
 for x in p:r=r.replace(x,'',1)
 print r;p+=r

```

Try it online!

## Commented

```
l=input()       # the list of words to write
p=''            # p contains all letters we own
for r in l:     # for each word ...
  for x in p:   # for each letter we own ...
    r=r.replace(x,'',1)   # remove one occurence from the current word
  print r       # print the remaining word
  p+=r          # add the remaining chars to p

```
> 10 votes

# Answer
# Jelly, 7 bytes

```
,œ-@Kɗ/

```

Try it online!

Output: -separated string.
> 8 votes

# Answer
# Perl 6, ~~44~~ 40 bytes

*-4 bytes thanks to Matthew Jensen*

```
{$!=@;.map:{kxxv $!=.comb∖($⊎=$!):}}

```

Try it online!

Outputs as a list of lists of characters.

### Explanation

```
{                                  } # Anonymous codeblock
 $!=@;                               # Initialise $! to an empty list
      .map:{                      }  # Map each item in the input to
                    .comb            # The string split to characters
                                     # In a Bag
                         ∖           # Set minus
                          ($⊎=$!)    # The accumulated Bag of results
                 $!=                 # And save the result for the next item
            kxxv                 : # Then decompose the Bag into a list

```
> 7 votes

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

```
a=>a.map(h=>([...t].map(c=>h=h.replace(c,'')),t+=h,h),t='')

```

Try it online!

Quite straightforward solution. For each word `h`, remove letters we already have.

Here is an explained version of that code:

```
f = list => {
  // the string that accumulates all the letters already bought
  let accu = '';
  // for every word in the list
  return list.map( word => {
    // for every letter already bought
    [...accu]
      // remove the letter from the word
      .map(char => {
        return word = word.replace(char,'')
      });
    // add not bought letters to accumulator
    accu += word;
    // the reduced word (without already bought letters) should be added to result map
    // this represents the letters to buy today
    return word
  }, accu)
}

console.log(f(['ONE', 'TWO', 'THREE', 'SEVENTEEN']))
console.log(f(['ONE', 'TWO', 'ONE', 'THREE']))
console.log(f(['ABC', 'AABC', 'ABBC', 'ABCC', 'AABBCC']))
console.log(f(['SHORT', 'LOONG', 'LOOOONG', 'LOOOOOOONG', 'SHORT', 'LOOONG']))
```
> 7 votes

# Answer
# Haskell, 44 bytes

```
import Data.List
foldl1(\a x->a++',':(x\\a))

```

Try it online!

Output is a string like `ONE,TW,HRE,SVEEN` with commas between days.
> 7 votes

# Answer
# , 29 bytes

*-29 bytes thanks to FrownyFrog!*

```
(],a.<@#~0>.-&(1#.a.=/;))/@|.

```

Try it online!

# Original Post

## , 58 bytes

```
[:}.@>[:(],<@(/:~@({.@>@-.&(((e.<@#[){:)\));))&.>/<@a:,~|.

```

Try it online!

*Thanks to ngn for help improving the "subtract letters while respecting repetition part".*

Not a great fit for J, but an illuminating exercise.

Let's begin by constructing a helper verb `wo` ("without") that removes all chacters in one string from another, while respecting repetitions.

```
wo=.{.@>@-.&(((e. <@# [) {:)\)

```

There is a fun idea here: We make each repeated instance of a character unique, by repeating it the required number of times. Thus if our original string is `ABBA` it becomes:

```
┌─┬─┬──┬──┐
│A│B│BB│AA│
└─┴─┴──┴──┘

```

A third `A` would become `AAA` and so on. This is accomplished by the phrase `((e. <@# [) {:)\`, which takes each prefix `\`, looks at the final element `{:` of it, and constructs a mask of all elements in that prefix that match `e.` that final element, and then filters and boxes just those elements `<@#`.

With our inputs both "unique-ified" we can now safely use normal set minus `-.` while still respecting repetition.

We then open each result and take only the first element to "undo" our repetitions: `{.@>`

Plugging this helper verb in, our overall solution (which simply inlines it) becomes:

```
[: }.@> [: (] , <@(/:~@wo ;))&.>/ <@a: ,~ |.

```

Essentially, all we do here is setup our problem as a single reduction. We start be reversing the input `|.` and appending to it `,~` an ace `a:`, or empty box, which will be the initial value of our final result, like so:

```
┌─────────┬─────┬───┬───┬──┐
│SEVENTEEN│THREE│TWO│ONE│┌┐│
│         │     │   │   ││││
│         │     │   │   │└┘│
└─────────┴─────┴───┴───┴──┘

```

We stick the following verb between each element to effect the reduction:

```
(] , <@(/:~@wo ;))/

```

This says: take the right input `]` (ie, our result) and append to it `,` the left input (this is `ONE` on the first iteration, `TWO` on the 2nd, etc) without `wo` the raze of `;` the right input (ie, without any previous letters so far used), but before appending sort it `/:~` and box it again `<@`.

At the end of all this we'll have the result we want, a list of boxes, but all inside one big additional box, and still with the empty box at the front. Thus we open to remove the outer box and kill the first element: `}.@>`.
> 5 votes

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

```
a=>a.map(b=s=>[...s].filter(c=>x==(x=x.replace(c))?b+=c:0,x=b+0))

```

Try it online!

### Commented

\\$b\\$ is a string holding all available letters (and also some invalid characters, but this is irrelevant to the algorithm). For each new word, we create a copy of \\$b\\$ in \\$x\\$. Each letter \\$c\\$ of a word is either *used* by removing it from \\$x\\$ or *bought* by appending it to \\$b\\$. Only bought letters are returned.

```
a =>                      // a[] = input
  a.map(b =               // initialize b to the callback function of this map()
                          // it will be coerced to a string that does not contain
                          // any letter in uppercase
    s =>                  // for each entry s in a[]:
    [...s].filter(c =>    //   for each character c in s:
      x == (              //     check whether x is changed when
        x = x.replace(c)  //     c is replaced with 'undefined'
      ) ?                 //     if so:
        b += c            //       append c to b and keep c
      :                   //     else:
        0,                //       discard c
      x = b + 0           //     coerce b to a string and save it in x
    )                     //   end of filter()
  )                       // end of map()

```
> 4 votes

# Answer
# C++ (gcc), ~~177~~ 170 bytes

-5 bytes thanks to @anatolyg's tip, -2 bytes to small things I noticed.

```
#import<random>
#define v std::vector<std::string>
v a(v p){std::vector<int>o(91),b;int j=-1;for(auto i:p){b=o;p[++j]="";for(int c:i)--b[c]<0?p[j]+=c,++o[c]:0;}return p;}

```

Explanation

`#import<random>` adds both `<string>` and `<vector>` for half the bytes.

First creates a 91-element vector of 0s (only indices 65-90 are used to store letter occurences), and another vector of the same type but not set to a value. Iterates through each element of the input (the days): gets the currently owned letters, gets the letters that are needed for the day, overrides the input at the index with the needed amount and updates the owned letters. Returns the overridden input.

Try it online!
> 4 votes

# Answer
# Python 2, ~~102~~ 100 bytes

```
from collections import*
c=Counter
l=c()
for x in map(c,input()):y=x-l;l+=y;print list(y.elements())

```

Try it online!

<sub>-2 bytes, thanks to Embodiment of Ignorance</sub>
> 2 votes

# Answer
# Japt, ~~15~~ 14 bytes

```
£Q®X=rZPPÃQ±XX

```

Try it

```
£Q®X=rZPPÃQ±XX     :Implicit input of array
£                  :Map each X
 Q®                :  Map each Z in Q (initially a quotation mark)
   X=              :    Reassign to X
     rZ            :    Replace Z with
       P           :    The empty string
        P          :    With the default global flag disabled
         Ã         :  End map
          Q±X      :  Append X to Q
             X     :  Return X

```
> 2 votes

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

```
a=>{var b="";for(dynamic i=0,e,f;i<a.Count;b+=a[i++]=f)foreach(var c in((e,f)=(b.ToList(),"")).f+a[i])f+=e.Remove(c)?"":c;}

```

Try it online!

Anonymous function that outputs by modifying an input array.

```
// a: input array of strings
a=>{
  // b: cumulative letters
  var b="";
  for(
    // i: loop index of string
    // e: copy of cumulative letters for manipulation
    // f: characters missing from current string
    dynamic i=0,e,f;
    // iterate over each string in a
    i<a.Count;
    // add missing letters of the day to
    // cumulative missing letters and
    // update array for output
    b+=a[i++]=f
  )
    // iterate current string with character c
    foreach(var c in
      // tuplized variable assignment
      // e=b.ToList()
      //   set e to a copy of the cumulative letters
      // f=""
      //   initially there are no letters needed for the day
      ((e,f)=
      (b.ToList(),"")).f+a[i]
    )
      // conditionally add c to missing letters for the day
      f+=e.Remove(c)?"":c;
}

```
> 2 votes

# Answer
# R, ~~119 112 106~~ 103 bytes

-7 bytes from aliasing the two longer function names and now taking user input from `scan()`
-6 bytes to only call `strsplit()` once at the beginning
-3 bytes to get rid of the aliasing again and assign two variables in one call

(Also edited the byte count which was erroneously low earlier)

```
a=scan(,'');b=a=strsplit(a,'');for(i in 2:length(a))b[[i]]=vecsets::vsetdiff(a[[i]],unlist(b[1:i-1]));b

```

This is my very first PPCG submission of any kind! So I have no idea what I'm doing both in terms of golfing and in terms of posting etiquette. The output is a list of vectors which may or may not meet the terms of the challenge. :-P

As for the code itself, it takes user input via `scan()` and compares each new day's letters to the cumulatively owned letters, as in other solutions. If there are shorter alternatives to `unlist` and `strsplit` for converting strings into vectors of individual characters that would be cool to know. I also used the `vsetdiff` function in Carl Withoft's `vecsets` package to get the set difference of the letters needed for the next day and the current letters owned.
> 2 votes

# Answer
# PowerShell, 71 bytes

```
$args|%{$w=$_;$p|% t*y|%{$w=$w-replace"^(.*?)$_(.*)",'$1$2'};$w;$p+=$w}

```

Try it online!

Takes input words `$args` and iterates over them. Each iteration we set the current word `$w`, then loop over our `$p`ool of already-purchased letters. Each inner loop, we perform a regex `-replace` on our current `$w`ord, so that we're replacing just the first instance of the letter from our `$p`ool. Once we've gone through all letters in the pool, we output what's remaining `$w` (i.e., what we need to purchase), and then tack those letters onto our pool `$p+=$w` for the next word.
> 2 votes

# Answer
# 05AB1E, 11 bytes

*-6 thanks to Kevin Cruijssen*

```
ćsvDysSõ.;»

```

Try it online!
> 1 votes

# Answer
# Red, 75 bytes

```
func[b][a: copy""foreach w b[foreach c a[replace w c""]print w append a w]]

```

Try it online!
> 1 votes

# Answer
# Excel VBA, 127 bytes

```
Function z(w)
z=""
For Each x In w.Cells
v=x.value
For y=1To Len(z)
v=Replace(v,Mid(z,y,1),"",1,1)
Next
z=z&v
Next
End Function

```

Takes input in the form of an excel range.
> 1 votes

# Answer
# C (gcc), 118 bytes

```
m(a,r,q,u)char**a,*r,*q,*u;{for(;*a;a++,memcpy(r,q,255))for(memcpy(q,r,255),u=*a;*u;u++)*u=r[*u]-->0?32:(q[*u]++,*u);}

```

Try it online!

As a little bonus it takes the stock in `r` at the start as an array. Outputs the input null-terminated null-terminated-string list `a` with all pre-owned letters replaced with spaces.
> 1 votes

# Answer
# Swift 4.2/Xcode 10.2, ~~244~~ ~~242~~ ~~239~~ 238 bytes

```
a.reduce(([Character:Int](),[String]())){c,l in let b=l.reduce(into:[Character:Int]()){$0[$1,default:0]+=1}.map{($0,max(0,$1-(c.0[$0] ?? 0)))};return(c.0.merging(b){$0+$1},c.1+[b.map{String(Array(repeating:$0.0,count:$0.1))}.joined()])}.1

```

Try it online!

The letters are not arranged in alphabetical order, it is not forbidden by the rules.
> 1 votes

# Answer
# K (ngn/k), ~~36~~ 33 bytes

```
*+(){(a;x,a:&0|-/#''='(y;x@:1))}\

```

Try it online!
> 1 votes

# Answer
# Scala, 68 bytes

```
(c:Seq[String])=>c./:(Seq(""))((a,n)=>a:+n.diff(a./:("")(_+_))).tail

```

Try it online!

/: is short-hand for foldLeft operator, a is aggregation, ultimately returns the result we want, n is next element

## Un-golfed

```
def NewLettersPerDay(c: Seq[String]): Seq[String] = {
    c.foldLeft(Seq(""))((agg, next) => {
      val existingLetters = agg.reduce(_+_)
      val newDayLetters = next.diff(existingLetters)
      agg :+ newDayLetters
    }).tail
}

```
> 1 votes

# Answer
# PHP, 87 bytes

```
for(;$w=$argv[++$i];print' ')for($b=$a;$l=$w[$$i++];)$b[$l]?$b[$l]--:++$a[$l]&&print$l;

```

Try it online!
> 1 votes

# Answer
# Charcoal, 18 bytes

```
ＥθΦι¬⊙…θκ‹№…ιμλ№νλ

```

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

```
 θ                  Input array
Ｅ                   Map over strings
   ι                Current string
  Φ                 Map over characters
       θ            Input array
      …             Truncated to length
        κ           Outer index
    ¬               Logical Not
     ⊙              Any element exists where
          №         Count of
              λ     Current letter in
            ι       Outermost word
           …        Truncated to
             μ      Current letter index
         ‹          Is less than
               №    Count of
                 λ  Current letter in
                ν   Innermost word
                    Implicitly print each day's bought letters on their own line

```
> 0 votes

# Answer
## PHP, UTF-8 aware (253 bytes)

```
<?php $p=[];for($i=1;$i<$argc;$i++){$a=$p;$b=[];for($j=0;$j<mb_strlen($s=$argv[$i]);$j++){$k=1;if(isset($a[$c=mb_substr($s,$j,1)]))if($a[$c]){$k=0;$a[$c]--;}if($k){echo $c;if(isset($b[$c]))$b[$c]+=$k;else $b[$c]=$k;}}$p=array_merge($p,$b);echo PHP_EOL;}

```
> 0 votes

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

```
a=>{var b="";for(int i=0;;b+=a[i++])foreach(var z in b)if(a[i].Contains(z))a[i]=a[i].Remove(a[i].IndexOf(z),1);}

```

Try it online!
> 0 votes

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

```
for$i(@h){s/$i//}push@h,/./g

```

Try it online!
> 0 votes

# Answer
# Ruby, 52 bytes

```
->l{r="";l.map{|x|r.chars{|c|x[c]&&x[c]=''};r+=x;x}}

```

Try it online!
> 0 votes

# Answer
# Stax, 7 bytes

```
é█üa%┐┤

```

Run and debug it

Output is newline separated.
> 0 votes

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


title: Unlock your Lock

text:
# Question
Title: Unlock your Lock
You have locked your bike with a combination lock of 3 digits. Now you want to go for a ride and need to unlock it with the help of following program.

## Input

### 1st parameter

The digit combination of your lock in *locked* state. It must be different from the 2nd parameter (=the combination of *unlocked* state). (Or else your bike could be stolen!)

Range 000..999. Leading zeros must not be omitted.

### 2nd parameter

The digit combination of your lock in *unlocked* state. This value is your goal.

Range 000..999. Leading zeros must not be omitted.

## Output

A list of each state of the combination lock after each "rotation" including the initial state (which is always the 1st parameter) and the last step (which is always the 2nd paramater).

## Algorithm

You start "rotating" the first digit one by one until you reach the correct digit in *unlocked* state. But, because you are in knowledge of the whole unlock-code, **you rotate the digit in the direction in which you need the smallest amount of rotations to reach the digit in *unlocked* state**. In case of a tie you can choose whatever direction you prefer.

When you have reached the correct first digit, you start the same procedure with the 2nd and then with the 3rd.

The order of digits is to understand as a circle:

`... 9 0 1 2 3 4 5 6 7 8 9 0 1 2 ...`

This means, that the smallest amount of rotations from 1 to 9 is not

`1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9` = 8

but

`1 -> 0 -> 9` = 2.

## Notes

## Examples

### Example 1, correct

```
Input: 999 001

Output:
999
099
009
000
001

```

### Example 2, correct

```
Input: 000 292

Output:
000
100
200
290
291
292

```

### Example 3, wrong output

```
Input: 999 121

Wrong output:
999
899 // Wrong because wrong rotation direction.
799
699
...

Correct output:
999
099
199
109
119
129
120
121

```

### Example 4, wrong input

```
Input: 1 212 // Wrong because no leading zeros.

```

This is the shortest answer wins.

# Answer
> 12 votes
# Python 2, ~~113~~ ~~107~~ ~~105~~ ~~99~~ 95 bytes

```
a,b=input()
i=0
print a
for x in a:
 while x-b[i]:a[i]=x=(x+(x-b[i])%10/5*2-1)%10;print a
 i+=1

```

Try it online!

Takes input as lists of integers

---

Saved:

* -6 bytes, thanks to Joel
* -4 bytes, thanks to Jitse

# Answer
> 6 votes
# Jelly, 15 bytes

```
_æ%5ḣT$ṂṠ⁸_%⁵ðƬ

```

A dyadic Link accepting the start-code on the left and the target-code on the right as lists of integers (in \\$\[0,9\]\\$, lengths equal but otherwise arbitrary) which yields a list of lists of the codes from start-code to target-code.

**Try it online!**

### How?

```
_æ%5ḣT$ṂṠ⁸_%⁵ðƬ - Link: list of integers, s; list of integers, t
              Ƭ - collect up values until a fixed point is reached applying:
             ð  -   the dyadic chain:  (i.e. f(x, t) where x starts off as s)
_               -     subtract (t from x) (vectorises) - i.e. [ta-xa, tb-xb, tc-xc]
   5            -     literal five
 æ%             -     symmetric modulo (vectorises) - i.e. [[-4..5][ta-xa], [-4..5][tb-xb], [-4..5][tc-xc]]
      $         -     last two links as a monad:
     T          -       truthy indices  - e.g. [0,-4,1]->[2,3]
    ḣ           -       head to index (vectorises)       [[0,-4],[0,-4,1]]
       Ṃ        -     minimum                            [0,-4]
        Ṡ       -     sign (vectorises)                  [0,-1]
         ⁸      -     chain's left argument (x)
          _     -     subtract (vectorises) - i.e. move the single spindle one in the chosen direction
            ⁵   -     literal ten
           %    -     modulo (since 9+1=10 not 0)

```

# Answer
> 4 votes
# JavaScript (ES6),  ~~73 72~~  70 bytes

*Saved 2 bytes thanks to @tsh*

Takes input as 2 arrays of digits in curried syntax `(a)(b)`. Returns a string.

```
a=>g=b=>b.some(x=>d=x-(a[++i]%=10),i=-1)?a+`
`+g(b,a[i]+=d/5<5/d||9):b

```

Try it online!

### Commented

```
a =>                  // a[] = initial combination
g = b =>              // b[] = target combination
  b.some(x =>         // for each digit x in b[]:
    d =               //   compute the difference d:
      x -             //     between x
      (a[++i] %= 10), //     and the corresponding digit in a[]
                      //     we apply a mod 10, because it may have exceed 9
                      //     during the previous iteration
    i = -1            //   start with i = -1
  ) ?                 // end of some(); if it's truthy:
    a + `\n` +        //   append a[] followed by a line feed
    g(                //   followed by the result of a recursive call:
      b,              //     pass b[] unchanged
      a[i] +=         //     add either 1 or 9 to a[i]:
        d / 5 < 5 / d //       add 1 if d / 5 < 5 / d
        || 9          //       otherwise, add 9
    )                 //   end of recursive call
  :                   // else:
    b                 //   stop recursion and return b[]

```

# Answer
> 2 votes
# Jelly, 25 bytes

```
_æ%5+⁹⁹rḊ€%⁵J;Ɱ"$ẎṄḢ}⁺¦¥ƒ

```

Try it online!

Full program.

# Answer
> 2 votes
# Python 2, ~~101~~ 97 bytes

```
a,c=input()
print a
for i in 0,1,2:
 while a[i]!=c[i]:a[i]=(a[i]+(a[i]-c[i])%10/5*2-1)%10;print a

```

Try it online!

3 bytes thx to Joel.

Takes input as lists of ints.

# Answer
> 1 votes
# PHP, 114 bytes

```
for([,$a,$b]=$argv;$i<3;($x=$a[$i]-$b[$i])?(print$a._).$a[$i]=($y=$a[$i]+(5/$x>$x/5?-1:1))<0?9:$y%10:++$i);echo$b;

```

Try it online!

My solution probably sucks, but that is the best I can think of for now!

# Answer
> 1 votes
# Jelly, 30 bytes

```
_ż+¥⁵AÞḢṠxAƊ×€ʋ"JṬ€$$Ẏ;@W}+\%⁵

```

Try it online!

A dyadic link taking as its left argument the unlock code and its right the current locked state, both as lists of integers.

This feels far too long!

# Answer
> 1 votes
# Charcoal, 48 bytes

```
θ≔ＥθＩιθＦ³«≔⁻﹪⁺⁻Ｉ§ηι§θι⁵χ⁵ζＦ↔ζ«§≔θι﹪⁺§θι÷ζ↔ζχ⸿⪫θω

```

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

```
θ

```

Print the initial position.

```
≔ＥθＩιθ

```

Change the initial position string into an array of numeric digits for calculation purposes.

```
Ｆ³«

```

Loop over each digit in turn.

```
≔⁻﹪⁺⁻Ｉ§ηι§θι⁵χ⁵ζ

```

Calculate the number of rotations needed to unlock that digit. This is a number from `-5` to `4` where `-5` means 5 downward rotations and `4` means 4 upward rotations.

```
Ｆ↔ζ«

```

Loop over each rotation.

```
§≔θι﹪⁺§θι÷ζ↔ζχ

```

Update the digit according to the sign of the rotation.

```
⸿⪫θω

```

Output the digits as a string on a new line.

# Answer
> 1 votes
# T-SQL 2008, 170 bytes

I added some linebreaks to make it readable

```
DECLARE @1 char(3)='123',@2 char(3)='956'

DECLARE @r int,@s int,@ int=0
g:SET @+=1
h:SELECT @r=substring(@1,@,1)+9,@s=@r-substring(@2+'1',@,1)
IF @s=9GOTO g
PRINT @1
SET @1=stuff(@1,@,1,(@r+@s/5%2*2)%10)
IF @<4GOTO h

```

**Try it online**

# Answer
> 0 votes
# C# (Visual C# Interactive Compiler), 101 bytes

```
a=>b=>{for(int i=0;i<3;i++)for(;a[i]!=b[i];a[i]+=(a[i]-b[i]+10)%10<5?9:1,a[i]%=10)Print(a);Print(a);}

```

Try it online!

# Answer
> 0 votes
# , 36 bytes

```
10|[+/\@,#:@4 2 1#~[:>&|/`]}10|-,:-~

```

Try it online!

Will add explanation tomorrow.

# Answer
> 0 votes
# MATLAB, ~~100~~ 89 bytes

A different approach (using implicit expansion to create a subtraction matrix) reduces 11 bytes:

```
function f(a,b);c = mod(a-b+5,10)-5;a,mod(a-cumsum(repelem(eye(3).*sign(c),abs(c),1)),10)

```

\[Original 100 byte solution\]

```
function f(a,b);c=mod(a-b+5,10)-5;a,for n=1:3;for r=1:abs(c(n));a(n)=mod(a(n)-sign(c(n)),10),end;end

```

Both called by passing the inputs as 3-element arrays, e.g. `f([9 1 1], [2 3 2])`

# Answer
> 0 votes
# Java (JDK), 139 bytes

```
a->b->{for(int i;;a[i]+=(a[i]-b[i]+10)%10<5?9:1,a[i]%=10){System.out.println(""+a[i=0]+a[1]+a[2]);for(;i<3&&a[i]==b[i];i++);if(i>2)break;}}

```

Try it online!

Same algorithm as everyone, rolled differently because Java's `System.out.println` is pretty expensive!

# Answer
> 0 votes
# C (clang), 125 bytes

```
t,*d;f(*a,*b){for(t=d=a;t?printf("%d%d%d\n",*a,a[1],a[2]):d++,t=*d-b[d-a],d-a<3;*d=(*d+=!~*d*10)%10)t?*d+=(t+10)/5&1?1:-1:0;}

```

Try it online!

# Answer
> 0 votes
# Kotlin, 162 bytes

```
{s:Array<Int>,e:Array<Int>->var i=0
o@while(i<3){println(""+s[0]+s[1]+s[2])
while(s[i]==e[i]){if(i>1)break@o
i++}
s[i]=(s[i]+if((e[i]-s[i]+10)%10>5)9 else 1)%10}}

```

Try it online!

---
Tags: code-golf, path-finding
---


title: Significant Whitespace

text:
# Question
Title: Significant Whitespace
We define **whitespace** to be any of the three characters, tab (0x09), newline (0x0A) or space (0x20).

For this challenge, you're to write two programs or functions in the same programming language, which perform the following tasks:

1. Count the whitespace characters in a given string. For instance, the input

```
  123 -_-   abc
def

```

would return 7 (provided there is no trailing newline).
2. Split a given string at consecutive runs of whitespace. If the string starts or ends with whitespace, no empty strings should be returned at the ends. For instance, the same input

```
  123 -_-   abc
def

```

would return `["123", "-_-", "abc", "def"]`.

In either case you may take input via STDIN, command-line argument or function argument a return the result or print it STDOUT. For the second program, if you choose to print to STDOUT, please print each string on its own line, without surrounding quotes.

For both programs you may assume that the input contains only printable ASCII (0x20 to 0x7E) and whitespace.

*Now here is the catch:*

* If all whitespace is removed from both programs/functions, the resulting strings have to be identical. That is, your two submissions may *only* differ in the number and placement of whitespace characters.
* Neither program/function may contain any string or regex literals (character literals are fine, provided your language has a designated character type).
* Neither program/function may contain any comments.
* You must not read the program's source code, directly or indirectly.

This is code golf. Your score is the sum of the sizes of both solutions (in bytes). Lowest score wins.

## Leaderboards

The following Stack Snippet generates both a regular leaderboard and an overview of winners by language. So even if your language of choice doesn't let you win the entire challenge, why not try to snatch a spot on the second list? I'd be very interested to see how people tackle this challenge in a variety of languages!

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

```
# Language Name, N bytes

```

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

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

```

You may also include the individual counts before the total count, e.g.

```
# Python 2, 35 + 41 = 76 bytes

```

The last number that is not struck through will be used by the snippet.

```
<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script><script>site = 'meta.codegolf',postID = 5314,isAnswer = true,QUESTION_ID = 42253;jQuery(function(){var u='https://api.stackexchange.com/2.2/';if(isAnswer)u+='answers/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJeRCD';else u+='questions/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJO6t)';jQuery.get(u,function(b){function d(s){return jQuery('<textarea>').html(s).text()};function r(l){return new RegExp('<pre class="snippet-code-'+l+'\\b[^>]*><code>([\\s\\S]*?)<\\/code><\/pre>')};b=b.items[0].body;var j=r('js').exec(b),c=r('css').exec(b),h=r('html').exec(b);if(c!==null)jQuery('head').append(jQuery('<style>').text(d(c[1])));if (h!==null)jQuery('body').append(d(h[1]));if(j!==null)jQuery('body').append(jQuery('<script>').text(d(j[1])))})})</script>
```

# Answer
# Pyth, 16 + 15 = 31 bytes

Try it here.

Counter:

```
L@,cb)sm!cd)b1 0

```

Splitter:

```
L@,cb)sm!cd)b10

```

These each define a function, `y`, which takes a string input to solve the desired task.

Thanks to @FryAmTheEggman for the idea of using Pyth's feature of modular indexing into lists to shave a character.

Test cases:

```
L@,cb)sm!cd)b1 0y++"abc def"b"gh ij k"
L@,cb)sm!cd)b10y++"abc def"b"gh ij k"

```

Explanation:

```
L                  define a function, y, which takes one input, b.
 @                 Index into
  ,                2-tuple of
   cb)             b.split()                          (solution to splitter)
   s               sum over                           (solution to counter)
    m              map, with input d, to
     !cd)          logical negation of d.split()      (empty list is falsy)
     b             over b.
                   Index is either:
   10
   1
                   Indexing is modulo the length of the list in Pyth.
 0                 In one case, a 0 with a leading space is outside the function.
                   Leading space suppresses print, so the 0 is invisible.

```
> 16 votes

# Answer
# Python, 54 + 56 = 110 bytes

Counter:

```
m=lambda x:sum(y.isspace()for y in x)
+1
0<9or x.split()

```

Splitter:

```
m=lambda x:sum(y.isspace()for y in x)+10<9or x.split()

```

For the counter, we use the fact that Python is okay with having just an expression on a line. It's necessary to split up `+1` and `0<9or x.split()` to stop a `NameError` from being thrown, as `0<9` being `True` prevents `x.split()` from being evaluated due to short circuiting.

For the splitter, since the number of whitespace is always nonnegative, `sum(y.isspace()for y in x)+10<9` is always `False` and the splitting function comes into play.

---

## Alternative 1, 59 + 60 = 119 bytes

Counter:

```
m=lambda x:[x.split(),sum(y.isspace()for y in x)][min([1])]

```

Splitter:

```
m=lambda x:[x.split(),sum(y.isspace()for y in x)][m in([1])]

```

The results of both counting and splitting are stored in a two-element list. The list is indexed by either `min([1])`, returning the minimum of the one-element list containing `1`, or `m in([1])`, which returns `False` (equivalent to `0`) as `m` is not contained in `[1]`.

---

## Alternative 2, 67 + 69 = 136 bytes

Counter:

```
ted=1;s=lambda x:[x.split(),sum(y.isspace()for y in x)][not s or ted]

```

Splitter:

```
ted=1;s=lambda x:[x.split(),sum(y.isspace()for y in x)][not sorted]

```

Like above, the results of both counting and splitting are stored in a two-element list. `sorted` is a built-in function which is a truthy value, so `not sorted` returns `False` (equivalent to `0`). For `not s or ted`, since `s` is a function and also truthy, `not s` is `False` and `ted = 1` is returned.

---

## Alternative 3, 59 + 60 = 119 bytes

Counter:

```
def f(s):a=s.split();a1=len(s)-len((s*0).join(a));return a1

```

Splitter:

```
def f(s):a=s.split();a1=len(s)-len((s*0).join(a));return a
1

```

This is a function where splitter's result is stored in the variable `a`, and counter's result is stored in the variable `a1`. Like before, Python is fine with having just an expression on a line, in this case `1`. Splitting up `a1` determines what to return from the function.
> 54 votes

# Answer
# Java 8, 239 + 240 = 479

**Count the whitespace** (returns Integer)

```
Object f(String s){String r=new String(new char[]{92,'s'}),e=new String();int intx=0;intx=1;return intx>0?s.chars().filter(c->c==9|c==10|c==32).count():java.util.Arrays.stream(s.split(r)).map(t->t.replaceAll(r,e)).filter(t->t.length()>0);}

```

**Split on the whitespace** (returns Stream\<String\>)

```
Object f(String s){String r=new String(new char[]{92,'s'}),e=new String();int intx=0;int x=1;return intx>0?s.chars().filter(c->c==9|c==10|c==32).count():java.util.Arrays.stream(s.split(r)).map(t->t.replaceAll(r,e)).filter(t->t.length()>0);}

```

Explanation:

```
Object f(String s){
    String r=new String(new char[]{92,'s'}),e=new String();  // init regex'es

    int intx=0;     // critical variable

    intx=1;         // change intx to 1
              OR
    int x=1;        // new, unused variable

    return intx>0 ? // test variable to decide what to do
      s.chars().filter(c->c==9|c==10|c==32).count() :
      java.util.Arrays.stream(s.split(r)).map(t->t.replaceAll(r,e)).filter(t->t.length()>0);
}

```
> 16 votes

# Answer
## Whitespace, 75 + 153 = 228

Spaces, tabs and newlines substituted by STL, respectively, and folded for legibility. Convert to a proper Whitespace file with `tr -d \\n | sed 'y/STL/ \t\n/'`.

**Counter**

```
SSSLLSSLSSSTSSSSSLSLSSLSTLTSTTTSLSLTSSLTSSTLTTLSSSTLTSSSLSLLLSSSLS
LLSLLTLST

```

**Splitter**

```
SSSTLSSSLTTSLSSTLSSSLSLSTLTSTTTSLSSLSLTSLSSSTSSSSTLTSSTLTTTTLSSSTL
SLSTTSLSLSLLSSTTLSSSTSTSLSSSTLTTTLTSTSLTLSSSSSTLSSSLTTSLSSTSLLSLTL
LSSSLTLSSLSLTLLSSLLLL

```
> 14 votes

# Answer
# Marbelous, 103 + 92 = 195

**Counter:**

```
@0      @200@1@3
]]&1]]3W
  \\!!?001
        &0  >W@1
>W    @2/\  /\@3+A
00&0      &1
          Dp
@0//

```

**Splitter:**

```
@0  @200@1    @3
]]&1]]  3W    \\
  !!    ?001&0
>W@1>W@2
/\  /\@3+A00&0
          &1Dp@0
//

```

Test these programs here. Cylindrical Boards, Include Libraries, and spaces for blank cells must all be checked.

Input and Output are through STDIN/STDOUT.

### Explanation

**Counter:**

The blue path receives input. If the character is a whitespace character (ascii value less than 0x21), the black path is taken, which synchronizes with the purple path.

The purple path simply increments a marble stored in the `&1` synchronizer each time the black path is taken.

Once there is no more input, the red path is taken, printing the number of whitespace characters and exiting.

**Splitter:**

The program begins with the blue path, which loops until a non-whitespace character is found.

Once a non-whitespace character is retrieved, the black path is taken, which prints out this character and moves execution to the green path, which loops and prints until a whitespace-character is received. Execution then continues to the purple path, which contains `3W`, or a three-way splitter.

The left branch moves execution to the blue path (and whitespace is discarded until a non-whitespace character is found).

The middle branch sets the copy of the input to 0 with `?0` (generate a random number between `0` and `0`), and adds 10 (`0x0A` = newline), which is then outputted.

The right path is discarded.
> 13 votes

# Answer
# CJam, 26 + 27 = 53 ~~59 61 73 77~~ bytes

**Counter**

```
'!q_,\SN9c++SerS%:Qs,-QN*?

```

**Splitter**

```
' !q_,\SN9c++SerS%:Qs,-QN*?

```

**How it works**

The idea is simple, calculate both number of whitespaces and split the string on consecutive runs of whitespaces. Then choose one of them based on the following fact that `' !` means `not of space character` which is falsy, while `'!` is the `!` character, which is truthy.

Expanded code:

```
'! / ' !                              "Get truthy or falsy value";
        q_                            "Read the input, make a copy";
          ,\                          "Take the length of the copy and swap";
            SN9c++                    "Get a string comprised of all Whitespaces";
                  Ser                 "Replace any occurrence of any character of"
                                      "the above string with space";
                     S%               "Split on one or more runs of space";
                       :Qs,           "Store this in Q, flatten to a string and take length";
                           -          "Subtract from total length to get count";
                            QN*       "Put the splitted array on stack and join newline";
                               ?      "Base on the truthy or falsy value, pick one to print";

```

---

Input is from STDIN and output is to STDOUT

Try it online here
> 12 votes

# Answer
# Mathematica, 44 + 43 = 87 ~~97~~ bytes

I thought I'd add another language to the mix.

Counter:

```
StringCount[#,Whitespace]+0 1StringSpli t@#&

```

Splitter:

```
String Count[#,Whitespace]+01StringSplit@#&

```

This makes use of Mathematica's feature that space separation is the same as multiplication. And that multiplying something with 0 is always 0, and adding 0 to something is always idempotent.

For the counter, we first count the whitespace, and the we add `0*1*StringSpli*t@#`. `StringSpli` and `t` aren't defined, but Mathematica uses symbolic computation, so it just treats those as an unknown variable and function. The `1*` is idempotent (just as `0+`), the `0*` turns it into a zero. It is necessary to separate the `StringSplit` into two variables, because `0` times a list is treated as a scalar-vector multiplication which results in a vector (list) of zeroes.

For the splitter, I'm using the fact that `Count` also exists but doesn't look into strings. It tries to count all sub*expressions* matching the pattern, but `Whitespace` is a pattern that only applies to string contents. So `Count` will always return `0`, which makes the `String` vanish. The multiplication of the split array by `01 = 1` is again idempotent.
> 11 votes

# Answer
# Ruby, ~~107~~ 91 bytes

**Splitter (46 bytes)**

```
p
p=gets(p).split
puts p||$_.size-pp.join.size

```

**Counter (45 bytes)**

```
pp=gets(p).split
puts p||$_.size-pp.join.size

```

`p` is a predefined method that, with no arguments, just returns `nil`. We use this in several ways. In the splitter, the initial `p` does nothing. `gets(p)` reads in everything from standard input, since the delimiter is null. We call the built-in split method on that, and assign the result to `p`, so now when it's not given arguments it'll be parsed as a variable. `puts p||...` short-circuits and prints each element of the `p` variable to its own line.

In the counter, we delete the first newline so that the split array is assigned to `pp` instead. Since we haven't assigned to `p`, it's still the nil-returning method so the second part of the `||` gets evaluated and passed to `puts`. `$_` is a magic variable containing the result of `gets`, so the total amount of whitespace is the size of that minus the non-whitespace characters, which are what `pp` contains. I feel like there should be a shorter way of doing the counting, but I can't find one, and at any rate using the split array in the counter is fun.
> 10 votes

# Answer
# Python, 169

It's almost too easy to do this in Python!

Counter:

```
def x(s):
 def y(s):
  return sum(map(str.isspace,s))
  return s.split()
 return y(s)

```

Splitter:

```
def x(s):
 def y(s):
  return sum(map(str.isspace,s))
 return s.split()
 return y(s)

```

They differ in only one space, and I'm not doing any trickery like splitting a number or a variable name in half :)
> 7 votes

# Answer
# C, 138+136 = 274

In each case, the code is a program that accepts exactly one command-line argument and prints the result to stdout. `\t` should be replaced with a tab character. If you want to pass an argument containing tabs and newlines, it's your job to figure out how ;).

**Counting**

```
#define strtok strpbrk
h=' \t\n';main(c,v,n)char**v;{for(n=- -c-1;v[n]=strtok(1[v],&h);n[v]++)v[!n]=0,puts(*v),c++;n*='d%';printf(&n,c-2);}

```

**Splitting**

```
#define strtokstrpbrk
h=' \t\n';main(c,v,n)char**v;{for(n=--c-1;v[n]=strtok(1[v],&h);n[v]++)v[!n]=0,puts(*v),c++;n*='d%';printf(&n,c-2);}

```
> 6 votes

# Answer
# JavaScript, 95 + 96 = 191 bytes

Counter:

```
c=(a,v)=>{v
v=a=a.split(RegExp(String.fromCharCode(92,115)));return v?a.length-1:a.filter(j=>j)}

```

Splitter:

```
s=(a,v)=>{vv=a=a.split(RegExp(String.fromCharCode(92,115)));return v?a.length-1:a.filter(j=>!!j)}

```

Ungolfed:

```
s=(a,v)=>{

    v  // this `v` is ignored, or combined with the next line to make `vv`

    // split array and store it in `a` and `v` (or alternatively `vv`)
    v = a = a.split(RegExp(String.fromCharCode(92,115)));

    return v?
            a.length-1        // return number of whitespace chars
            :
            a.filter(j=>j)    // return array without empty strings
    }

```

The `RegExp(String.fromCharCode(92,115)` line creates the whitespace-matching regex `/\s/` without regex or string literals.

In each program, we use the variable `v` or `vv`. We store the split array into that variable (`v` or `vv`), and then branch our behavior on the value of `v` (meanwhile, `vv` is ignored). In the counter, `v` has a truthy value; in the splitter it has a falsy value (because `vv` got the value instead).

---

# Alternate: JavaScript, 250 bytes

I have another solution that isn't winning any prizes for brevity, but I thought it was an interesting challenge to abuse JavaScript's automatic semicolon insertion behavior.

Counter:

```
c=a=>{a=a.split(RegExp(String.fromCharCode(92,115)));x:for(i=2;i--;)for(o=i?a.length-1:a.filter(j=>j);1;){break x}return o}

```

Splitter:

```
s=a=>{a=a.split(RegExp(String.fromCharCode(92,115)));x:for(i=2;i--;)for(o=i?a.length-1:a.filter(j=>j);1;){break
x}return o}

```

Ungolfed counter:

```
s=a=>{
    a = a.split(
            RegExp(String.fromCharCode(92,115))   // split input on whitespace regex /\s/
        );
    x:                             // x is a label for the outer loop
    for(i=2;i--;)                  // run this outer loop twice
        for(o=i?                   // if this is the first outer loop pass,
               a.length-1          //    set `o` to number of whitespaces
               :                   // else, on second outer loop pass,
               a.filter(j=>j);     //    set `o` to split input (w/o empty strings)
            1;                     // 1 is truthy; run inner loop forever
            ) {
                break x;           // break out of outer loop
            }
    return o;                      // return `o`
}

```

The splitter is exactly the same, except for the line:

```
break x;

```

is now

```
break
x;

```

JavaScript's automatic semicolon insertion normally does not terminate multi-line statements early if they can be understood without a line break, but it does not tolerate line breaks after `return`, `continue` or `break`. Therefore, the line is read simply as `break`, which breaks out of the inner loop only, instead of breaking out of the outer loop. The "second-pass" behavior `o = a.filter(j=>j)` is then executed (versus being skipped in the counter), because the outer loop is given a second pass.
> 6 votes

# Answer
# Python, ~~228~~ ~~198~~ ~~182~~ ~~166~~ ~~146~~ 145 bytes

Counter (**72 bytes**):

```
ior1=0
w=lambda i:i.split()if ior1 else sum(ord(c)in(9,10,32)for c in i)

```

Splitter (**73 bytes**):

```
ior1=0
w=lambda i:i.split()if i or 1else sum(ord(c)in(9,10,32)for c in i)

```

`ior1` is a falsey variable, but `i or 1` is truthy. That's the main trick.
> 5 votes

# Answer
## Befunge 98, 61 + 59 = 120

**Counter:**

```
~:'!-0`#v_ >$1+#@ #. #
 @#,#$ #<_v#`0-!':~ # .#
  ,#$ #+55<v

```

**Splitter:**

```
~:'!-0`#v_ >$1+#@ #.#
 @#, #$#<_v#`0-!':~ #.#
  , #$#+55<v

```
> 5 votes

# Answer
# Bash, 75 + 79 = 154 bytes

This relies on bash being able to continue execution even if some lines or parts of a line of the script are malformed (in some circumstances). Whitespace is used to deactivate escapes for some close brackets, and to break a pipe by putting it on a new line.

Splitter:

```
echo $((`echo $1|wc -w`+${#1}-$(\)\)\)
for a in $1;do echo $a;done|wc -c)))

```

Counter:

```
echo $((`echo $1|wc -w`+${#1}-$(\ )\ )\ )
for a in $1;do echo $a;done
|wc -c)))

```

Input is via commandline argument, output is via stdout.

Because this relies on bash error behaviour, the user is expected to ignore stderr.

Example run (showing input with a newline and multiple contiguous spaces):

```
# bash counter.sh "abc def
gh   ij k" 2>/dev/null
6
# bash splitter.sh "abc def
gh   ij k" 2>/dev/null
abc
def
gh
ij
k

```
> 4 votes

# Answer
# Ruby, ~~114 + 116~~ 107 + 109 = 216 bytes

This can't compete with the ruby solution by histocrat, but I thought it would be worth putting up anyway.

I used `$z` for `nil` and `nil.to_s` for `String.new`

The extra whitespace character that I add to the end of the input is to force the last word to be added to the array (`r`) - a word is only added to the end of the array when a whitespace character follows a non-whitespace character. The alternative was adding another `r<<w if w` after the `each_byte` block.

## Counting

```
->s{r=[]
n=-1
w=$z
(s+9.chr).each_byte{|b|if b<33
r<<w if w
w=$z
n+=1
else
w=w.to_s+b.chr
end}
$zorr ?r:n}

```

## Splitting

```
->s{r=[]
n=-1
w=$z
(s+9.chr).each_byte{|b|if b<33
r<<w if w
w=$z
n+=1
else
w=w.to_s+b.chr
end}
$z or r ?r:n}

```
> 4 votes

# Answer
# Haskell, ~~53 + 55 = 108~~ 36 + 38 = 74 bytes

**Counter**

```
f=do
 pure(length.filter(<'!'))words

```

**Splitter**

```
f=do
 pure(length.filter(<'!'))
 words

```

This solution makes use of the fact that in Haskell functions are an instance of the Monad type class and thus can be used as monadic actions in do-notation.

In the first case the resulting function of the do-block is the first argument of `pure` (which is essentially `const` for the function type), making the counter the final result and the splitter being discarded.

In the second case `pure` is only applied to a single argument, making it a function that returns another function (the counter). However, the result is never used and thus discarded. The final result is the second line of the do-block, the splitter.
> 3 votes

# Answer
# Java 8, 187 + 188 = 375

First of all, I'd like to say that this answer is heavily based on @Ypnypn's. I basically replaced some parts with shorter ones (including the whitespace-dependent part, which IMO is the most important in this challenge), but the functional code is mostly the same.

**Count the whitespace**, 187 (returns `int`):

```
Object f(String s){String r=new String(new char[]{92,115});int a=0;return a--+a>0?s.chars().filter(c->c>8&c<11|c==32).count():java.util.Arrays.stream(s.split(r)).filter(t->t.length()>0);}

```

**Split on the whitespace**, 188 (returns `Stream<String>`):

```
Object f(String s){String r=new String(new char[]{92,115});int a=0;return a- -+a>0?s.chars().filter(c->c>8&c<11|c==32).count():java.util.Arrays.stream(s.split(r)).filter(t->t.length()>0);}

```
> 2 votes

# Answer
# J, 48 + 49 = 97 char

Two functions taking and returning a single argument. Used the crappiest way that I could think of to beat the same-but-whitespace rule, so there are probably characters to be saved by finding a more clever route around that.

```
(aa[aa=.+/@a=.a:-.~(e.u:)&9 10 32 :(<;._1~1,}.))      NB. count
(a a[aa=.+/@a=.a:-.~(e.u:)&9 10 32 :(<;._1~1,}.))     NB. split

```

We define the verb `a` to have two different actions, depending on whether it's used with one argument or with two. With one argument, it is `(e.u:)&9 10 32`, which checks if each character is whitespace or not. With two arguments, it is `a:-.~(<;._1~1,}.)`, which takes a boolean vector on the right and cuts the left argument at those positions, throwing out any empty cuts with `a:-.~`.

Then, we define `aa` to be number of True values in the result of `a`, which only makes sense with one argument. Finally, we use `aa` or `a a` depending on whether we want to count or split the whitespace of the string. `aa` works as expected.

The reason `a a` works is because when J sees `(f g)y`, it considers `(f g)` a hook and evaluates it like `y f (g y)`. In this case, `f` is the dyadic `a` above which does the cutting, and `g` is `a[aa`, which calculates the sum from `aa`, throws it out, and calculates (monadic) `a` again.

At the REPL:

```
   (aa[aa=.+/@a=.a:-.~e.&(u:9 10 32) :(<;._1~1,}.))   '  123',TAB,'-_-   abc',LF,'def'
7
   (a a[aa=.+/@a=.a:-.~e.&(u:9 10 32) :(<;._1~1,}.))  '  123',TAB,'-_-   abc',LF,'def'
+---+---+---+---+
|123|-_-|abc|def|
+---+---+---+---+

```
> 2 votes

# Answer
# Bash, 54 + 50 = 104 bytes

### Counter

```
a=$IFS
IFS=
cat()(tr -cd $a|wc -c)
printf %s \\n$1|cat

```

### Splitter

```
a=$IFSIFS=ca
t()(tr-cd$a|wc-c)
printf %s\\n $1|cat

```
> 2 votes

# Answer
## Perl, 37 + 38 = 75

**Counter**:

```
sub f{($_)=@_;(y/   - //,[split])[0.1]}

```

**Splitter**:

```
sub f{($_)=@_;(y/   - //,[split])[0 .1]}

```
> 1 votes

# Answer
# Perl 6, 31 + 32 = 63 bytes

### Counter

```
{?^1??.words!!+grep 33>*,.ords}

```

Try it online!

`?^1` is parsed like `?^ 1` which applies the Boolean negation operator to 1, resulting in `False`.

### Splitter

```
{? ^1??.words!!+grep 33>*,.ords}

```

Try it online!

`? ^1` converts the range 0..0 to Bool, resulting in `True`.
> 1 votes

# Answer
# Python 2, 98

**Splitting (49)**

Returns the tokens in a list.

```
f=lambda s:[sum(map(str.isspace,s))]and s.split()

```

**Counting (49)**

Returns a list of length one containing the number of space characters. It will most likely cause a runtime error, but the function `f` can be used after executing the code.

```
f=lambda s:[sum(map(str.isspace,s))]
ands.split()

```
> 0 votes

# Answer
# C (gcc), 88 + 89 = 177 bytes

## Splitter

```
i,n,x,c;f(char*s){x=n=i=0;for(x+++n;c=*s++;c*x&&putchar(c))i=c<33?n++,c=i*10,0:1;x=n-1;}

```

Splitter

## Counter

```
i,n,x,c;f(char*s){x=n=i=0;for(x+ ++n;c=*s++;c*x&&putchar(c))i=c<33?n++,c=i*10,0:1;x=n-1;}

```

Counter

## Rundown

Takes input as a function argument. The counting function returns the number of whitespace. The splitting function uses STDOUT for its output (but incidentally returns number of whitespace minus one as well).

```
i,                      Flag signalling whether we are inside a word.
n,                      Number of whitespace encountered.
x,                      Flag signalling whether or not we should output the words.
c;                      Current character.
f(char*s){              Take input string as an argument.
x=n=i=0;for(            Initialise everything and start loop.
x+++n;                  SPLITTER ONLY: Interpreted as x++ +n, meaning x is set to 1 and n stays 0.
x+ ++n;                 COUNTER ONLY: Inverse of the above. Sets n to 1, and x stays 0.
c=*s++;                 Sets c to current char and increment string pointer, end loop if end of string.
c*x&&putchar(c))        Only output c if x is 1 and c is non-zero, which only happens if we left a word.
i=c<33?                 Since input contains only printable ASCII or whitespace, anything below 33 is whitespace.
       n++,             ...if that is the case, increment the whitespace counter (n)
           c=i*10,      ...and set c to newline (10), but only if we just left a word (if i is 1)
                  0:    ...and set i to 0.
                    1;  If not a whitespace, set i to 1, signalling we are inside a word.
x=n-1;}                 Implicitly returns n-1, which is the number of whitespaces if we are in the counter function.

```
> 0 votes

# Answer
# Zsh, 35+35=70 bytes

> * Neither program/function may contain any string or regex literals

I am unsure whether `[^$IFS]` qualifies, since it is used in pattern matching. Here is a 45+45 solution in the case it is banned.

---

Split:

```
:<<<${#1//[^$IFS]}
:
<<<${(F)${=1}}

```

Count:

```
:
<<<${#1//[^$IFS]}
:<<<${(F)${=1}}

```

The `:` builtin is equivilent to `true`, we use it as something between a comment and /dev/null (since comments are disallowed) by piping the unwanted expansion to it.

Zsh has a builtin for splitting on whitespace, that being `${=var}`. This makes it hard to do any kind of logical combination other than just executing both and discarding the one we don't want.

Try it online!
> 0 votes

---
Tags: code-golf, string, restricted-source, source-layout, whitespace
---


title: Output the Arecibo Message

text:
# Question
Title: Output the Arecibo Message
> The Arecibo message is a 1974 interstellar radio message carrying basic information about humanity and Earth sent to globular star cluster M13 in the hope that extraterrestrial intelligence might receive and decipher it... The message consisted of 1,679 binary digits, approximately 210 bytes...
>
> The number 1,679 was chosen because it is a semiprime (the product of two prime numbers), to be arranged rectangularly as 73 rows by 23 columns. The alternative arrangement, 23 rows by 73 columns, produces an unintelligible set of characters (as do all other X/Y formats).
>
> *This is the message with color added to highlight its separate parts. The actual binary transmission carried no color information.*

Source: Wikipedia

---

Your task is to output the Arecibo Message in the exact 23x73 arrangement shown in the image. Any of these output formats is acceptable:

* Text, using one character for ones and another for zeros (using the usual rules for row separation)
* A 2D array of two distinct values
* A 23x73 image with two distinct colors
* Aan uninterrupted stream of 1679 items of two distinct values (i.e. any of the above formats, but flat.)
* A 1679-bit integer. Indicate bit and byte order (endianness) in your solution.

For your convenience, here is a copy-pastable version (also an example output in text format):

```
00000010101010000000000
00101000001010000000100
10001000100010010110010
10101010101010100100100
00000000000000000000000
00000000000011000000000
00000000001101000000000
00000000001101000000000
00000000010101000000000
00000000011111000000000
00000000000000000000000
11000011100011000011000
10000000000000110010000
11010001100011000011010
11111011111011111011111
00000000000000000000000
00010000000000000000010
00000000000000000000000
00001000000000000000001
11111000000000000011111
00000000000000000000000
11000011000011100011000
10000000100000000010000
11010000110001110011010
11111011111011111011111
00000000000000000000000
00010000001100000000010
00000000001100000000000
00001000001100000000001
11111000001100000011111
00000000001100000000000
00100000000100000000100
00010000001100000001000
00001100001100000010000
00000011000100001100000
00000000001100110000000
00000011000100001100000
00001100001100000010000
00010000001000000001000
00100000001100000000100
01000000001100000000100
01000000000100000001000
00100000001000000010000
00010000000000001100000
00001100000000110000000
00100011101011000000000
00100000001000000000000
00100000111110000000000
00100001011101001011011
00000010011100100111111
10111000011100000110111
00000000010100000111011
00100000010100000111111
00100000010100000110000
00100000110110000000000
00000000000000000000000
00111000001000000000000
00111010100010101010101
00111000000000101010100
00000000000000101000000
00000000111110000000000
00000011111111100000000
00001110000000111000000
00011000000000001100000
00110100000000010110000
01100110000000110011000
01000101000001010001000
01000100100010010001000
00000100010100010000000
00000100001000010000000
00000100000000010000000
00000001001010000000000
01111001111101001111000

```

If your language, for some reason, has a builtin for the Arecibo Message, you may not use that builtin.

Good Luck!

UPDATE: I accepted the 05AB1E answer since it was the first one to be shorter than the original message. Don't let that dissuade you from new solutions.

UPDATE 2019-09-09: Accepted answer moved to a new 05AB1E answer, as it obsoletes the previous 05AB1E answer. Same point goes as previous update; new solutions still welcome.

# Answer
# 05AB1E, 182 bytes

```
•sv¯ö¨₁ÿ.ÛïžôΔ¨γ_Ígv…=Bм„Ð.(Ü¦i´…ε±G½0^/₃öRÛž¼¤"āêL!ˆ6‘GāÜ‡ðв₁÷Ã7€₂δ¬‚Cć¨g¾†@÷[_-68¯a∍iG*6ÆîÆ;>éjζãÎÂ+ºžnî¼ć'(ÝÞΔ‹∞Ã‰Ý¹Õ5λ₆*a|§oÄmôæ¨;Â—:hž¥ð¢ocË'¨%¡4Ćáß©ìća;FÁ?iˆèεƒʒ•Ž6–FD4‰`3ÊD?i-

```

Try it online! (uses `1` for 0 and `0` for 1, as allowed by the question).

Try it online! (5 bytes longer, `0` for 0 and `1` for 1, added newlines for readability).

Most of the code is a base-255 integer constant N, the rest is an Asymmetric Numeral System decoder, using hardcoded probabilities of 75% / 25% (the actual frequency of 0 is 76.35%, which is so close to 75% that it would only save 1.2 bits in the payload, while the nice and round 75% lets us save several bytes in the decoder).

```
Ž6–F                  # repeat the following 1679 times:
    D                 #  duplicate N
     4‰`              #  divmod 4: pushes N / 4, N % 4 on the stack
        3Ê            #  is N % 4 != 3 ? (boolean 1 or 0)
          D?          #  print a copy
            i-        #  if it's 1, subtract: N = N - (N / 4)
                      #  (otherwise, N = N / 4, since that's the top of the stack)

```

Here's the ANS encoder that generated the constant: Try it online!

```
Î                          # start from N = 0
 Rv         ]              # for each bit in the reversed input:
   4*                      #  N *= 4
     yi                    #  if the bit is 1:
       3+                  #   N += 3
         ë                 #  else:
          3÷               #   N /= 3 (integer division)
             ₅B'•.ø        # compress N as base-255

```
> 3 votes

# Answer
# 05AB1E, ~~215~~ ~~210~~ 200 bytes

Saved 15 bytes thanks to *Magic Octopus Urn*

```
•cOž¤4é57ñΛ\Ö₃BαöĀíL½₅üBdoÙRθLγ¨G×Tćú$G(˜ƒ¦!€R»SDrµCnJ†d∊ζ·<8‡T@|‹ï=BζćósxG\ÙÎ$¿o₁5/ÔŸÇBûXé-”a::Ž]°∊y;ζ]MÜβ‘иL”β{üÃÇíäc€÷›ÎU=}¨иaŸdY`»¾ÚUβ:ô©¦β†₅DGŠβ3Jêθ,äá!ícqšVÖ›lÈΣ¯pε €êÊƒDpÙ/¬Žλ8:ãÿ3=€.Þć•3BY¾4×:

```

Try it online! or with Additional formatting

Base-255 encoded trinary string with occurrences of `0000` replaced by `2`.
> 13 votes

# Answer
# Java, ~~688 678 590 379~~ 361 bytes

Returns a string.

```
n->new java.math.BigInteger("in95mzupnpa2r0khpoepyql6ioqyn413avucdtfay6indx4wh9dehe3sn18klobtf4z9g9q17umqmwpegr2khb5eqinn7azl4jpfp2a8eui0xfrx5qwrou6gd65jh4ge3ls14k5lu7qrvmg6942ms29u5rb8fa6yrdhfoh5zoi9bdi7uh5ig0u0ff9kounth8sh357x7qox4m3oqviqsbrvakonbka4ahp21bgzi5v1akzzuqoncszhpabbru9q1uo2g11zr73iuyiqr5ikr69zn7cdv7e1lhd6ese9",36).toString(3).replace("2","0000")

```

-10 bytes by returning the raw stream (old answer)
-88 bytes by using base 10 numerics (thanks @ceilingcat!)
-211 bytes (I knew it could be golfed!) by using a base-36 encoded BigInteger (thanks @JollyJoker!)
-18 bytes by using a different encoded integer (thanks again @JollyJoker)
Try it online!
Explanation:

```
n->new java.math.BigInteger("base36 string",36) // Decode the base-36 integer.
   .toString(3)                                 // Re-encode as ternary
   .replace("2","0000")                         // Replace 2 with "0000"
                                                // Implicit return

```
> 11 votes

# Answer
# Jelly, 213 bytes

```
“H²ɓ¶Ṡḷ€ẹ]ƒf*ḳḢ&ƁṇOḥ{ḄṫwỊ+oLạʋß¢H9¢¹÷ỴɗÇ⁶ƲƙæḊẋ3³=1!VƇƁ'D⁺3Ỵɱ©⁵%fȯez#ƈjƒżṆo.ZF⁶ċṢ⁶ọṛb9Ȯƒd?ƁUĠt4ẇ,ḞġƒµƭfʠƁP§÷øȤŻPɲẋ(¢ß¢(⁽3¶ṙėɗy@ṁYȮL~e⁷ƤĊ§nỊṅµṠ°@7ẠB>Ġ⁻İ}uy¡½:esOpḢt}qS©HÞṬĖṛṇḣ9÷;ESḢ,Ẉ^ṙpƲ©tṃwçnẒṆ¡⁻Jıƒị£-&Ɱ*ẋʂżoȯÑḢɼ’

```

Try it online!

I played around with Huffman coding, but the improvements in data size were outweighed by the extra code. As such, this is simply a base-250 encoded version of the desired output. Output consists of an integer that when decoded as bijective base 2 will yield the 1D list of 1s and 2s. Thanks @Emigna for pointing out the change in rules.

Try it online - with further decoding to demonstrate output!

If a more conventional binary encoding is preferred, here is one that encodes an integer representation of the inverted binary message. The most significant bit of the integer represents the beginning of the message.
> 9 votes

# Answer
# Brainfuck, ~~2360~~ ~~2008~~ ~~1938~~ 1902 bytes

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

```

Try it online!

My idea was to first generate a simple solution consisting of setting up an ASCII 0 followed only by `+-.` instructions to produce the output. Repeating sections can then be shortened using loops.

Choosing the optimal set of non-overlapping sections for looping basically comes down to solving a maximum-weight independent set problem. Currently, I just use a greedy algorithm which takes the section that can be optimized the most and then removes all conflicting sections. This is then repeated until no sections are left.

Using a more sophisticated algorithm one can surely achieve better results.
> 9 votes

# Answer
# Piet, 1763 codels

Outputs a stream of 0s and 1s (no line breaks).

Codel size 1:

Codel size 4, for easier viewing:

## Explanation

* First, push a sentinel value of -1 onto the stack.
* Then push the Arecibo message, in reverse order (because it's a stack), using run-length encoding.
* Finally, alternate between two loops, one printing zeroes and the other printing ones.
    + The loop counter is the current stack value, decremented until it hits zero, at which point it is discarded and we switch to the other loop.
    + Between the zeroes-loop and the ones-loop, check for the sentinel value, exiting if it is found.

## Notes

The program follows a spiral path, clockwise from top left into the centre. The scattered black blocks that roughly follow the diagonals are the flow control. Here's the trace from NPiet.

I've been working on this since the day this challenge went up, but it took a little bit of time to get the message "written" into the picture! I wrote the final loops and the sentinel value first, and then built up the message from the centre outwards. (Since Piet always starts execution from the top left, I expected to have to shuffle and rotate the image around to avoid excess whitespace, but it fit perfectly!)

Fun fact: Run-length encoding in Piet doesn't (by itself) save any space. It takes *n* codels of one colour to push the value *n* onto the stack, or *n* codels of different colours to push that many 1s onto the stack. So it's the same number of codels either way. But the bigger numbers that RLE gives you mean you can use arithmetic tricks (e.g. instead of pushing 9, you can push 3, duplicate, and multiply) to reduce the number of codels, and funny-shaped blocks to fill in available whitespace.

I wasn't sure about how to count score for Piet entries. I found some that seem to count *all* codels, and others that explicitly only count those actively used. I just counted them all; ignoring white codels (even those that the program never moves through) seems akin to ignoring whitespace in a more typical programming language.

Oh, and I've just now (two hours after posting) realised that I wasted the last bit of time working on this. I wanted to trim off the almost-completely-white last row and column, so I shuffled things around... including the black flow-control blocks. But the edges of the image work the same as black! If I'd just remembered that, I wouldn't have needed to spend so much time puzzling over the intricacies of DPs and CCs...
> 8 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~366~~ ~~332~~ ~~329~~ 319 bytes

```
int i;foreach(var g in"*ЀʂЄ࢈ҲપԤ␀␀␀؀ȀȀȀ؀␀␀సؘࠀƐഘؚ྾ߟ␀␀Ā␀␀ྀ␀␀రܘࠈഌΚ྾ߟ␀␀ă␀ྃ␀ȁăÃ1`ƀ1`ÃĂȃЃЁȂĀ`ÀƀȺ؀Ȃ␀ȏЀȗɛ'Ŀஇ7;ȅ?ȅ0ȍЀ␀␀΂␀ΨՕ΀Ŕ␀ŀЀ?܀àǀƀ`̀°٠Ƙѐʈш҈EB@Ѐޟɸ")Write(Convert.ToString(g,2).PadLeft(12-i++%2,'0'));

```

Replace all instances of  with `\0` to test.

Try it online!

# C# (Visual C# Interactive Compiler), 305 bytes, 210 chars

```
_=>"*ЀʂЄ࢈ҲપԤ␀␀␀؀ȀȀȀ؀␀␀సؘࠀƐഘؚ྾ߟ␀␀Ā␀␀ྀ␀␀రܘࠈഌΚ྾ߟ␀␀ă␀ྃ␀ȁăÃ1`ƀ1`ÃĂȃЃЁȂĀ`ÀƀȺ؀Ȃ␀ȏЀȗɛ'Ŀஇ7;ȅ?ȅ0ȍЀ␀␀΂␀ΨՕ΀Ŕ␀ŀЀ?܀àǀƀ`̀°٠Ƙѐʈш҈EB@Ѐޟɸ".Select((g,i)=>Convert.ToString(g,2).PadLeft(12-i%2,'0'))

```

Same with above, replace with  with `\0` to test. Output as `IEnumerable<string>`.

Try it online!(Courtesy of Jo King)
> 4 votes

# Answer
# \[Python 2\], 345 bytes

```
s=''
for c in")pG/K(K*j$h%kk$ppjGE&I6S6S5[5eCv~vw0x&z$wgqcde$e=G4G?G4eG0e:vv~w*G,gn$wy$uuuuG=G)I,G.I2G(I-eG(I)e-I0G+G+G(G)I*G*vI)G-w'I2y0w'I,vI)G*G)G+G(G*I+W+I+W,G*G(G*G*G*G/I,I+I,iq.G*G1G(e/g$c%sG)m%md~$M(},K(cO)K(eO)K(I)G(aE$M(G1c$hpoI,pG3K1e3eU/M*M,I.I*S,Q(y*y'hG(ng&j$j$G+hW/g'G/G,G1k.d$e$mN":c=ord(c)-35;s+=[bin(c-35)[2:],'0'*c][c<35]
print s

```

I encoded the length of strings of 0s as a byte starting at chr(31). Then I encoded the remaining 10101 as binary numbers starting at chr(70) up to chr(126). Binary strings that didn't fit were split up into smaller chunks.

Edit: Reduced to 326 bytes. Thanks Jo King

Edit: Fixed a bug in the code generator program

Edit: Final Edit
> 3 votes

# Answer
# Bubblegum, ~~275~~ 236 bytes

```
00000000: e006 8e00 e45d 0018 6988 6507 a228 f86f  .....]..i.e..(.o
00000010: f042 c62f d4d7 b99e 38bc 56c4 52e8 2630  .B./....8.V.R.&0
00000020: 8aaa 7252 d47d 5ef4 c96a 511f 6842 423f  ..rR.}^..jQ.hBB?
00000030: 4532 ca9f 22d3 1633 e0c4 665a d5dc 4e68  E2.."..3..fZ..Nh
00000040: 7b09 76ae 3c7e f9d4 fa4a 05e0 4163 c580  {.v.<~...J..Ac..
00000050: c585 a383 2396 4ca9 1f48 a4b9 744e 37c8  ....#.L..H..tN7.
00000060: 68c5 af23 645d 59a7 542a e6d1 23b9 3aba  h..#d]Y.T*..#.:.
00000070: f0e6 2738 dfd5 b0a3 c6a3 60bf c5b6 5ae6  ..'8......`...Z.
00000080: 7893 30a8 ae04 edf9 298b b777 4d56 285b  x.0.....)..wMV([
00000090: cb74 07cc 7a7b a399 3dc7 c6e7 b693 e715  .t..z{..=.......
000000a0: d908 876e 001f 7408 3c6a 5fcd 37cb 02c4  ...n..t.<j_.7...
000000b0: 93de 33c2 a11e 5bac cd12 d99a fac3 e0fa  ..3...[.........
000000c0: 5268 94f7 d640 0f73 cede f79d 821f 39d1  Rh...@.s......9.
000000d0: dc49 ff06 6962 6c31 dc29 a077 01c3 7690  .I..ibl1.).w..v.
000000e0: 85ef bbec 31d7 5c7f f9fc 8c00            ....1.\.....

```

Try it online!
> 2 votes

# Answer
# Node.js, 333 bytes

Returns a binary string of 1,679 characters.

```
_=>Buffer(")SI)=.);1K?>>>2333A3,93/I3>3)g33)AEAAI)5JQZJTddda3)*3*33+3,e)*e3)//0/1+)1C/7Cgggg3395)9)A3IY)h*IH),39+)995*)AA-)59Y)*O3Z,)//*)91**)A*-)Y+1)I11+)I1)/)5)Y*0?)+)I)-0Y)1@;_*7<gaE/a)Q7[*9HM+IY16I33)a1)*^.><I+S3.38I)*hY)7)a)Y)A,9*A5Y/A:9=9K:1I-=9)19I)9*329)GH<").map(x=>s+=(x-51&&x-41).toString(2).padStart(x-51?6:12,0),s='')&&s

```

Try it online! (with formatted output)

---

# JavaScript (ES8), 413 bytes

Returns a binary string of 1,679 characters.

```
_=>atob('AsKoAFBQEiIlwpVVUk!!ABwo!DQ!Gg!V!Aw7g!!GHGHCi!yGjHChsK+w7vDr8K!!Q!Q!!g!/DgAHDs!AGGHDhiAgCGhjwprDu8Ovwr4!ABAw4AQAcK!MKDAD8GB8OAD!QCAQQMBAYYEAMQwABwpgAMQwBwoYEBAgEEBgEQDAIwoAgIMKAwoDCgMKABgDDgDAEdcKACAgAEHwAIXTCtgTDpMO+w6HDgcK4AsKDwrIFB8OkCgwINg!!A4IAB1FVTDoArCo!U!/CgAB/w4ADwoDDoAwAYDQBYMOMBmEUFEIkSMKARR!woQgAQB!MKUAHnDtA'.split`!`.join`AA`).replace(/[\s\S]/g,c=>c.charCodeAt().toString(2).padStart(8,0))

```

Try it online! (with formatted output)
> 2 votes

# Answer
# Perl 6, 368 bytes

```
.say for :36('FJXOE0PDDNF5Y5EHGB8M9SWMXQOXIKIT9F6ZKWWDEACHCBGXL1N2H60CN0CJ4EMKF7D6MODSKYJVNR4SFTDR6NSM421LQ67B6MWF0G5BQATFOJJJBQ0UFQM64T0MWSQN41C4S5D1QR5KJM2L9UTYMMKUBBQWY45YCMRGO8ZRGTQH7LXMZBUASLCTKX30IH0AYKYEPHO8HFHX8GAY5WM38YOSUX0HABYSH2PPBLRDRZIN5ANAQ3V8PLOZ6EHC0UI95EVJVYD1820T6J14HGX85NWFQET2NWOMSNUT0JW4LHMY90X094TEE9KXJXSNN6YPERFQW').base(2).substr(1).comb(23)

```

Try it online!

The long string is the message as a single base-36 number (with a single prefixed 1 bit to preserve the leading zeroes) which is then converted back to binary and printed 23 bits at a time.
> 2 votes

# Answer
# Wolfram Language (Mathematica), 383 bytes

```
StringPartition[Uncompress@"1:eJylVNsRwjAM44s92KBaBTZgAUZhZXqtHUuOWrgjfSRRHFlO4tyer/vjfb1clq0gHirZLRjby986hppcT5p+L3BmgJ3t4Ul4GsNyG++7YbaXLh0ZTPhXa4Sn+X/s9Qfk3Hx2cOaSIuNYaVu5laschvgzSqAjHeZBhilKgKBDEhw0upJRg+HOK4MyNC29sfbc3RV0VPDqeLiRTsG1ulExq1IitpunOa7asnYM9siDZ6eidUCkEzBOUbCkGIig4aTyUGBYWAX6W6aXIWGGI/HlhmsqzSU0QTZjkMVpaX5sBsm1OGKVg1qdjKP0EdyqZBRLhukn8DLBQav6kccgz8OKfgBzjj6Z",23]

```

Try it online!
> 2 votes

# Answer
# bash + GNU tools, 351 bytes

```
base64 -d<<<H4sIAPnNrVwCA6WUCRLDIAwDv8T+/3NNG4wvkTBTcisGSyA8xrcxj9Ds02F+Z7yuf3hnPyz0vYEGz+FG3IKBs+x3oL2PSh0TM/PnaGamft9nPUCew3uCp5RBWdRKGz+qNJn8qRKkkNaTBgeVIFXWOdi8VCaIeUnsfHo6TXpaFa3H5olf6J5MuIHLoEi0uKcRFCvEXG4xseglKzZg7kpYJSLMA3M7wXKR+/L2WiK0kvg+TDASLp6Co1KEVIlVmFzhCktRhBBDdSZYU1xKHrmDUllcWpNR/YNW2QNcHtF0rSySb0MXk/SDUgEwG5gfLvQDxuEdDo8GAAA=|gunzip

```

TIO
> 2 votes

# Answer
# MathGolf, ~~223~~ 220 bytes

```
'06*"x·<×J× Ç×►B×ê\"@$↕!◙è0♥f░×→0×♠p└☺α?×└•×◙×P♣p¬è:×►∟××××←♦♠♣≥â☻┘A☺▄αp⌂r☻[║►×>◘×♦♦└:☻↑`×♥@@@@►►@♦↑ ☻♀◘☻♦☻☻├×å↑×╠×Ç!♠ 0♀◘↑◘☻♦◘×♠α♥â▼ÇA×└×◘` ×××▀≈}═14♦►►π0♀××°×α•×►×××☻×◘××└≈}_├↑♪↓×─0♫♥×××|××*××♪×Ç♠×└×××× ⌐¬╩↕◄○((×T☺"$à+

```

Try it online!

## Explanation

```
'0                push single character "0"
  6*              repeat 6 times
    "..."         push the magic string
         $        convert to ordinal
          à       convert to binary string
           +      pop a, b : push(a+b) (add the 6 zeroes)
                  below is the footer
            L/    divide into groups of 23 characters
              n   join array with newlines into string

```
> 2 votes

# Answer
# Python 3, 331 bytes

```
exit(''.join(bin(i)[3:]for i in b'`UP@JB`IDQKJjjd`@@@@@L@@Ah@@CP@@J`@@_@@@@@LNLLP@FPtXpu}}}|@@@@`@@`@@@A@@A~@@~@@@CCCcDA@DMCGM____@@@@HF@H@L@@PX@_`pO`A`@HA@HHF@`LLB@FHX@@s@@Xa`CC@`HD@``L@b@XAD@PDDA@PD@C@F@X@ck@A@P@BCx@DKi[@gI\x7f\\NC\\@TGY@hOrAPXDFp@@@@@\\D@@zbjipAU@@B`@Gp@@\x7fx@G@\\@X@LAh@lFXCLHhJHQHdPBJH@DHP@H@`@Dh@OOix')[1:])

```

Try it online!
> 2 votes

# Answer
# Perl 5, 460 bytes

```
printf"%023b",oct"0x$_"for qw/15400 141404 4444b2 555524 0 600 1a00 1a00 2a00 3e00 0 61c618 400190 68c61a 7df7df 0 80002 0 40001 7c001f 0 618718 404010 68639a 7df7df 0 81802 1800 41801 7c181f 1800 100804 81808 61810 18860 1980 18860 61810 81008 101804 201804 200808 101010 80060 60180 11d600 101000 107c00 10ba5b 1393f 5c3837 283b 10283f 102830 106c00 0 1c1000 1d4555 1c0154 140 7c00 1ff00 701c0 c0060 1a00b0 330198 228288 224488 22880 21080 20080 9400 3cfa78/

```

Try it online!
> 1 votes

# Answer
# Python 2, 336 bytes

```
print bin(int('gVQAKCgJERLKqqkgAAAAAMAABoAADQAAKgAAfAAAAAMOMMQAGQ0Yw19998AAAAgAAgAAABAAB+AA+AAADDDjEBAENDHNffffAAAAIGAIAMAAQYAfgwPgBgAIBAIIGAgMMCAGIYAAzAAYhgDDAgIEAggMAiAYBEAQEEBAQEADAGAYAjrABAQACD4AELpbAnJ/cODcAUHZAoPyBQYEGwAAAAAcEAA6iqpwBVAACgAHwAA/4AHAcAYAMBoAsGYDMIoKIRIkQCKIAEIQAIAgAEoAPPp4'.decode('base64').encode('hex'),16))[3:]

```

Try it online!

Prints a string of bytes
> 1 votes

# Answer
# Zsh (+coreutils), 320 ~~577~~ bytes

It runs on my Mac, but try it online doesn't work because TIO doesn't have `basenc` :(
It's a one-line program, I've added newlines here for readability. Data compressed to z85 encoding (similar to Ascii85).

```
basenc -d --z85<<<'0&M8}p.B@#L#QZE00001Fb*2U02+?qq#={[000069asT6g8.)4ZwEwH00
0Mg1onA4aoh}/0Q{6?7?7Abap8T<N!#M/0000:ZZ{J%0d$no1{.{L01Yzs5hjUju{Cb/00eC!f:[
8q1oX#k5eUKnfBigKaB[#)FcD1?fA=JG2NyzwD&LsiWGLW<&LA29Gr+T=<o=q3huiZS05#83BRN)
l3zmwk01TOWF4#ep&0YP[gY.1d24nhWll]9LmgYDLaoqEc0f^Fe]ZR$Y'|basenc --base2msbf
 -w0|cut -c-1679

```

**Encoding steps** <sub>
. Convert Arecibo message to a digestible format → `bitstr.8`
. Convert `bitstr.8` into binary, using script `demo16.sh`\**`bits.16.again`
. Convert binary to z85`basenc --z85 bits.16.again >``bits.85`
. Use the z85-encoded string in `bits.85` for a much shorter code golf!</sub>

**Decoding steps** -- i.e. what the main script does <sub>
. `basenc -d --z85<<<` decodes the z85 string to binary
. `|basenc --base2msbf -w0` decodes binary to Ascii `1`s and `0`s
. `|cut -c-1679` trims extra data</sub>

---

#### Original 577-byte solution

try it online!!

```
S=fxxxxibxxdxxfyzzzyx1yxxxxxxxxyyywl2ij1xxhj1xxhixxxhi5iw2d3c2d2cxl2bxc2az2c2d2ax4x4x4x5wcxpxwdxp15m5w2d2d3c2cxfxhxc1xxc2c2y1xx4x4x4x5wc1f2ixj2kd1e2j15e2f5j2kb1h1hyc1f2gzd2d2fzaf2c1d2ej2b2gf2c1d2ed2d2f1dc1f1hzb1g2hya1h2hya1i1gzb1g1g1dc1l2ed2h2gbz2xx2ibzd1lbzb5jb1dx2xyx1x2fy2yy6x3d3e2a3ixxd2x2b1fxxd6b1fxxd2db1e2a2jwb3e1lb2xxzxxxxx1b3ixxxynxxeh5jf9hd3g3fc2k2eb2a1ix2da2b2g2b2cazxxdxzzazyzyzzezxz1ge1d1d1ge1i1ggyxxia3y4xy3z
for X in ${(s::)S};{case $X in
[a-w])V=$[##$X-96];printf 0%.s {1..$V};;[1-9])V=$[##$X-48];printf 1%.s {1..$V};;[x-z])V=$[##$X-119];printf $[10**$V];;esac}

```

Used custom encoding logic. The string `S` is 421 characters, could possibly be compressed a bit more. Letters `a-w` represent repeated `0`s. Numbers `1-9` represent repeated `1`s. Letters `x y z` represent `10 100 1000` respectively.

*Maybe I should have tried byte-pair encoding or Ascii85 --\> Done. ✅*
> 1 votes

# Answer
# Bash, ~~702~~ 697 bytes

```
xxd -r -p<<X|xz -dc
fd377a585a000004e6d6b4460200210116000000742fe5a3e006d7010c5d
0018698865079cf6752c9e9a501a87a798b4844f9fcfdaaf87733b9d8239
48c816d860a938767f6cb81299f3e8a638effe3068c0e096a8949c81d706
7dff3ec44e5df185b3a48e5b5857724386e8c37cfbd5c856b12614ee78ec
c41df4db3aea71fd3a8fa474905609f78eb3fd66e246557965e4ab6dfd67
efbd9202f542ded9cf98a6401ee2d23afb2f544bd2442c6f428fd612397c
f2c6ec50847ddccc5832185e487712e5a7676b97058d7e485d5a3536166a
44ab3c689c93073cdda73b5306a83c4cd268e79db238bfa2d08ac912a578
75020bc7828342d5a62ce367aff7fd89290336128d119fa4272da2b2a79f
5973c71935af054f2d91c1bd3ea4847a3502d6dc8c975114dacf8a4de600
622d80986dbb0cd00001a802d80d00001b16e2a7b1c467fb020000000004
595a
X

```

Try it online!
> 0 votes

# Answer
# Ruby, 362 bytes

```
puts"5r0afnfm8wyke8tfy1pwt7xnuaxyh3wodfp7bhsdufyw0xbdp1pumrz2xir652tuc0ss9oec8yad9vefivd66j126wybhefgk2lv38uqqiur11u26q275jk3h2ucithd59awpaenqpqi1pszh52179zw0ddqtbrvo6kyrrgv8c34pqrp83j8estjp63v29t4hqp9yg2hhzjlq1e9zqx6gh20n9lsttimz3nbq060ritrphxaru7quwmv3oujhd9xjddpbacq4bnpf270znhgto59yn0980itylf95pxw9x7rvkvi7mfql1sx46puo8rg4dq0".to_i(36).to_s(2).rjust(1679,?0)

```

Integer written in base 36. There's surely a more efficient way to compress the integer, e.g. with `zlib` or `base64`.

Try it online!
> 0 votes

# Answer
# \[C++ (VC++)(but tested with gcc as well)\], 585 bytes

```
#define l(x,y)for(int x=0;x<y;x++)
void f(){const char*a="02A800505012Y595Y240U180YD0Y1A0Y540YF80V61C618800321A3186BEFBEF80X10Y40W20YFC001F0X1861C620200868639AFBEFBE0W40C0100180Z83003F0607C00C001008041030101860400C430Z19800310C018604040804101804403008802020808080800600C030047580080800107C002174B604E4FEE1C1B80283B20507E40A0C08360U3820Z751554E00AA0Z140ZF80Z7FC00380E00C0060340160CC06611414422448804510Z8420010040Z940079F4F0";int x=1679;l(i,365){int d=a[i],c=0;d-=(d>47&d<58)?48:((d>64&d<71)?55:0);if(d>70&d<91)c=91-d,d=a[i-1];for(c;c>=0;c--)l(j,4){if(x--)cout<<(int)((d&(8>>j))>0);}}}

```

Try it online!

ungolfed Version (lacks the break after the 1679th element though and goes until the 1680th):

```
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
    const char arecibo[]="02A800505012Y595Y240U180YD0Y1A0Y540YF80V61C618800321A3186BEFBEF80X10Y40W20YFC001F0X1861C620200868639AFBEFBE0W40C0100180Z83003F0607C00C001008041030101860400C430Z19800310C018604040804101804403008802020808080800600C030047580080800107C002174B604E4FEE1C1B80283B20507E40A0C08360U3820Z751554E00AA0Z140ZF80Z7FC00380E00C0060340160CC06611414422448804510Z8420010040Z940079F4F0";
    int i = 0,j;
    while (i<sizeof(arecibo)-1)
    {
        char digit = arecibo[i];
        int count=0;
        if (digit >= '0' & digit <= '9')
        {
            digit -= '0';
        }
        else if (digit>='A'& digit<='F')
        {
            digit -=  'A'-10;
        }
        else if (digit > 'F'&digit<='Z')
        {
            //digit does not contain any valid hex digit in this case
            count = 'Z' - digit+1; //digit = Z means repeat 2 more times...
            digit = arecibo[i - 1];
        }
        for (count; count >= 0; count--)
        {
            for (j = 0; j<4; j++)
            {
                cout << (int)(((digit)&(8 >> j))>0);
            }
        }
        i++;
    }
    return 0;
}

```

as an Explanation: i concatenated the 73 lines of sample output given to one long line. i encoded them in hexadecimal where the bit order is msbfirst (using this program https://github.com/Marc-Bender/longBinaryStreamToHex/releases/download/addedErrorCode-4/longBinaryStreamToHex.exe) i shortened the Output of that by about 70 hexadecimal Digits by using the letters 'G'-'Z' as a sign to repeat the last Digit for a certain amount of times (Z = 2more times, Y = 3more times …) the rest should be relatively self explainatory for Code-Golfers. abusing the preprocessor to shorten loops, abusing the `,` Operator and the like.

Output Format is uninterrupted stream of 1679 0/1-values.
> 0 votes

# Answer
# Perl 6, 348 bytes

```
{"000000"~:36<5r0afnfm8wyke8tfy1pwt7xnuaxyh3wodfp7bhsdufyw0xbdp1pumrz2xir652tuc0ss9oec8yad9vefivd66j126wybhefgk2lv38uqqiur11u26q275jk3h2ucithd59awpaenqpqi1pszh52179zw0ddqtbrvo6kyrrgv8c34pqrp83j8estjp63v29t4hqp9yg2hhzjlq1e9zqx6gh20n9lsttimz3nbq060ritrphxaru7quwmv3oujhd9xjddpbacq4bnpf270znhgto59yn0980itylf95pxw9x7rvkvi7mfql1sx46puo8rg4dq0>.base(2)}

```

Based on Benjamin Urquhart's Java solution.

Uses a straight stream of 0 and 1 characters. The link below has some code to prettify the output.

Try it online!
> 0 votes

# Answer
# Tcl, 366 bytes

```
binary scan [binary decode base64 QBUACgpIRKSpqkoCAAAAgAEAsAAAWAAAKgAAHwAAAGA4hhEATFiMYX3f9wEAAAgAIAAAAAQA8AOADwAAGIZjBAQQFsZZ3/d9AAAAAgMIgAEAwQD8YOADMAAIECAIDAgYBgIwwgCAGQCMMIBhICAQIAgYIAIMEAEEBAEBAQFgAAMMIK4BEBAACD4AhC5tICd/h4MdQMFNoOAnUDAQbAAAAAAcBACuqCoHUAUAKADwAQD+A8ABBzAABiyABjNghigoQiQSAaIIACEEgAACACkAni8P] b* z
puts [join [regexp -all -inline .{23} $z] \n]

```

Try it online!
> 0 votes

# Answer
# C++ (with Gnu multi-precision library), 359 bytes

This outputs the string as one line. It uses '1' for 0, and '0' for 1 :/

It simply reads the embedded string as base 62, and prints it as base 2.

Use `g++ -g arecibo.cpp -lgmp -lgmpxx` to compile and link

```
#include<gmpxx.h>
main(){mpz_out_str(stdout,2,class_mpz("vuXXKBYAu1hPsJPbFSf49akyFd0bjJbMIV3upYndU8kYFPsXcpRUK6c9qnzLfORxkxGL7ZfoSwgSxFbCrydjHL603QcxexopAzoYAcAyEiENJJU2vQA2zM8NDbeY6nHgL8rfFoPJaclwxx6TeKeOEknEQHzp7C4la3o8xijBQLOVweFZ1CI9dXy2VQhgnuwF5FeW5mQ909pRMxhn6G3RJ1QEtkS7oGMZYHM03fh4fj391IoYLGVv3iUVuTrV2ghz9CUa9hfGYrdhGoVE2w1inYalYl",62).get_mpz_t());}

```
> 0 votes

# Answer
# Perl 6, 276 bytes

```
:122[q{3tD!gLF['u#.K>'uCG8cvJZ[on1Z<D!	`Fhqq-_V'"qQn+n0h\:b,vXjo&1TMFaW;wvX;eUS
(ueelNSu,y93\kjGI&?UU/38 :ndi4Y5cyC+ME\g7LWaS;QLjtD^L+aVd(XW%gy\8'Eqk-+f72S5J?(r5!m^5px T[Z'3&jd0lZ'/x%#(}.ords].base(2)~~S/.//.say

```

Try it online!

Outputs as a series of 1679 0s and 1s. You can have it on different lines by adding `.comb(23)>>` before the `say`.

### Explanation:

```
:122["...".ords]                     # Convert the string from base 122
                .base(2)             # To base 2
                        ~~S/.//      # Remove the leading 1
                               .say  # And print

```

I can probably save bytes by using the output as a 1679 bit integer instead, or reversing the bit representation.
> 0 votes

# Answer
# C++ (gcc), 748 bytes

```
#define l(X,Y)if(z[i]==#X[0])z.replace(i,1,#Y);
void f(){std::string z = {"ab1eeedala1ebeeheal1mmma1fa1g1eeeeeeea1a1alddhgdbcdgdacedgdacedgdeeedgdndgddhgqiafbcag1dbfa1blceafafbcegcinnnlddhgmddegddhgb1ddelcidbnlddhgqqiafag1hedeblcebcaf1acegcinnnlddhgmhcdegdacdagb1bfda1lcibfhcildacdaga1d1d1almhcheagbqch1blhcmbqgdacachghcmbqgbqch1blmh1d1aga1hfd1aledcd1aledeheaga1heheblmdbqgbcdchga1af1efdga1hedbla1bndala1b1f1ea1fflh1aia1acccl1f1bibff1ldeebf1fla1h1ebfccla1h1ebfbla1bffdalddhgaibedblaieemeeeeelaideeeealdh1ehldcidalhcccidlbihf1hlafdafbgacedefblfachfacagemebeemagema1ma1magbememhgbeb1b1hgbedehghea1edalfcacieacca0"};for(int i=0;i<1751;i++){l(q,cb)l(n,fi)l(m,ae)l(i,c1)l(h,ba)l(g,0l)l(f,0c)l(e,01)l(d,bb)l(c,11)l(b,aa)l(a,00)l(l,\n)printf("%c",z[i]);}}

```

Try it online!

By replacing the most used substring with a new character until it's not worth it anymore
> 0 votes

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


# Question
Title: Create a square of increasing size by replicating the initial code
Your assignment is to write a program of **even length**, that prints an ASCII-art square (described below), that increases its side length by **1** unit each time the original source code is pasted in the middle of the current code.

It is quite hard for me to define this task very well, so I'll give you an example:

* Let's say your initial code was `CODE` and that it printed:

```
0

```
* Then, insert `CODE` in the middle: your code becomes `COCODEDE` and it should print:

```
00
00

```
* Re-insert `CODE` in the middle: your code becomes `COCOCODEDEDE` and should print:

```
000
000
000

```
* And so on. Your answer should theoretically work after any number of iterations, but I understand if, due to language performance limitations, it cannot run reasonably over a certain threshold.

Some rules:

* You can use any **printable ASCII** (32-127) as the character to use for your square. Your choice needs to be constant (You should use the same character for each iteration).
* The initial output square must have side-length **1**.
* An ascii-art square is defined as a string with **N** lines (separated by **N-1** linefeeds / newlines), and with each line containing **N** copies of the chosen character.
* Your output isn't allowed to contain any extraneous whitespace, other than a trailing newline.
* You can use the defaults for input and output (programs or functions are allowed, but snippets are not).
* The *middle* of your code is defined as the point where the source code can be split in two parts such that the two are equal.
* Your answers will be scored by the length of **your original program**, in bytes. The lowest byte count wins. In case there's a tie, the answer that was submitted earlier wins.
* You can use this program to apply the insertions without having to do that by hand.

# Answer
# Pyth, 2 bytes

```

5

```

Try it online! Also Try it doubled, tripled!

### How does that work?

`\n` is the command that prints its argument with a trailing newline, while **returning it** simultaneously. So, each time you make an insertion, you turn the integer literal **5** into a number containing **N** copies of **5** concatenated, and the leading newlines basically make sure it's printed the appropriate number of times, thus keeping it square.
> 41 votes

# Answer
## JavaScript (ES6), ~~42~~ ~~32~~ 30 bytes

```
s=[this.s]+0;  console.log(s);

```

Second iteration:

```
s=[this.s]+0;  s=[this.s]+0;  console.log(s);console.log(s);

```

This works by appending a `0` to `s` each time the first half of the code is run, and printing `s` itself each time the second half is run. Takes advantage of four quirks of JavaScript:

1. The current environment can be referred to with `this`. This allows us to do `this.s` in place of `s`.
2. When accessing a property that has not been defined on an object, instead of throwing an error, JavaScript returns `undefined`.
3. An array plus a number returns a string. `[1,2,3] + 4 === "1,2,34"`
4. When stringifying an array, `undefined` is converted to the empty string, which means that `[undefined] + 0 === "0"`.

Put together, this means that we can express the first half (generating a string of zeroes) in just 13 bytes. If using `alert` instead of `console.log` is allowed, we can save 4 more bytes by shortening the second half.
> 26 votes

# Answer
# 05AB1E, 2 bytes

```
5=

```

Try it online!

Port of my Pyth answer.
> 18 votes

# Answer
# Python 2, ~~42~~ ~~38~~ 28 bytes

```
id='%s@'%id  ;print id[22:];

```

Try it online!. You can also try the 2nd and 3rd iterations
> 17 votes

# Answer
# Python 2, 22 bytes

```
i=0;i+=1; i
print'*'*i

```

Try it online!

Doubled:

```
i=0;i+=1; ii=0;i+=1; i
print'*'*i
print'*'*i

```

Note that the second half starts with a newline character.
> 14 votes

# Answer
# C (gcc), ~~170~~ ~~168~~ ~~96~~ ~~80~~ ~~72~~ 70 bytes

Much shorter version. Still wish I could find a solution without the preprocessor.

```
i;main(n){for(;i++<n;)printf
#if 0

#endif
(" %*c",n=__LINE__/4, 10);}

```

Try it online!

Old 168 byte version:

```
#ifndef A
#define A p(c){putchar(c);}j,n;main(i){for(
#else
#define A n++,
#endif
A

#ifndef B
#define B i=++n;i--;p(10))for(j=n;j--;)p(64);}
#else
#define B
#endif
B

```

Try it online!
> 9 votes

# Answer
# Python 2, 30 bytes

```
False+=1      ;print'*'*False;

```

Try it online!, 2nd and 3rd iteration

This makes use of the fact that bools in Python are basically ints and the names `False` and `True` were reassignable in Python 2.

# Python 1, 32 bytes

```
exit=exit+'*'  ;print exit[30:];

```

Try it online!, 2nd and 3rd iteration

In Python 1 the builtin strings `exit` and `quit` existed to inform the user of the interactive shell how to exit it. The default value is `"Use Ctrl-D (i.e. EOF) to exit."`.
> 8 votes

# Answer
# Charcoal, 6 bytes

```
⊞υωＬυ⸿

```

Try it online! Explanation:

```
  ω     Predefined empty string (any variable would do here)
 υ      Predefined initially empty list
⊞       Push

```

`υ` ends up with a length of the number of repetitions.

```
    υ   List
   Ｌ    Length
        Implicitly print as a row of `-`s
     ⸿  Move to start of next line

```
> 6 votes

# Answer
# Haskell, 68 bytes

```
let s@(z:n)="0\n"in case lines<$>[]of(h:t):_->(h:h:t)>>(z:h++n);_->s

```

Try it online once, twice or thrice.

Because of Haskell's laziness an expression like the one above counts as a function which takes no arguments, as per this Meta question.
> 6 votes

# Answer
# Ruby, 18 bytes

```
$/=?x+$/;  puts$/;

```

Try it online! Doubled! Tripled!
> 5 votes

# Answer
# brainfuck, ~~44~~ 34 bytes

crossed out 44 is still regular 44 ;(

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

```

Try it online!

Try it doubled, tripled. Look, no padding!

Prints squares of `U`. It splits right down the middle of the 10 `+`s.
> 5 votes

# Answer
# Brain-Flak, 74 bytes

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

```

Try it online!

Try it doubled and tripled.

### Explanation

```
(((((()()()){}){}){}){}) # push 48 ("0") onto first stack
((()()()()()<>){})       # push 10 (\n) onto second stack
<>([]){({}[()]<          # a number of times equal to the height of the first stack:
  (({})<>)<>             #   copy the top of the first stack to the second stack
>)}{}<>                  # cleanup and return to second stack

```

The break point is in the middle of the `<>` in the "push 10" section. Breaking this up will leave a 5 on the third stack until we reach the corresponding second half, at which point pushing 10 will resume right where it left off.

While it is possible to push a printable ASCII value (space) in 22 bytes, this would make the central `<>` be executed after pushing `5`. By adding two more bytes, I was able to move the `<>` so that all of the progress toward pushing `10` was on the third stack. As a bonus, this also made the resulting square more aesthetically pleasing.
> 5 votes

# Answer
# tinylisp, 112 bytes

```
(load library) (d N((q((x)(i x(inc x)1)))(v(h(t(t(h(t(q())))))))))(join(repeat-val(string(repeat-val 42 N))N)nl)

```

Try it online! Also doubled and fivefold.

The "build a string in the first half, print it in the second half" approach that a lot of languages are taking won't work in tinylisp, since there are no mutable variables. Instead, we do some serious code nesting.

When a second copy of the code is inserted, it is placed inside the `(q())`, which wraps it in a list. Then `(h(t(t(h(t(...))))))` drills into that list to the part after `(d N`. `(v(...))` evaluates it; then we pass it to the unnamed function `(q((x)(i x(inc x)1)))`, which increments the resulting value if it's a number and returns 1 if it's the empty list. The final result in the outermost nested version of the code is assigned to `N`. In essence, we've set up a weird sort of recursion that counts the number of nesting levels.

The second half of the code then creates a string of `N` asterisks, then a list of `N` such strings, then joins the list on newlines. The result is displayed with a trailing newline.
> 4 votes

# Answer
# , 44 bytes

```
F=F+1;T=TRUE*TRUE+12;
write(strrep(1,F),"");

```

Try it online!

Prints with a trailing newline. The `T=TRUE*TRUE+12` is just to pad the length.

Try it doubled and Try it tripled.
> 3 votes

# Answer
# SNOBOL4 (CSNOBOL4), ~~130~~ 68 bytes

Now with no comments! See the edit history for an explanation of the old algorithm.

```
	X =X + 1
	A =ARRAY(X,DUPL(1,X));
I	I =I + 1
	OUTPUT =A<I>	:S(I)
END

```

Try it online!

Try it doubled and tripled

Explanation:

```
	X =X + 1		;* increment X
	A =ARRAY(X,DUPL(1,X));	;* create an x-length array with 1 repeated x times for each element
I	I =I + 1		;* for i < x
	OUTPUT =A<I>	:S(I)	;* output a[i]
END

```

Because an `END` label is required and anything after the first `END` label is ignored, we get two advantages for this challenge:

* operations in the first half of the program are repeated `X` times for the `X` repetitions
* there will (to the interpreter) only exist one copy of the second half, *including labels*.

This suggests that we use the repetition for the first half, and then we can use a more "conventional" labeling approach to repeat the output `X` times.

The first half is

```
	X =X + 1
	A =ARRAY(X,DUPL(1,X));
```

which, when repeated, increments `X` the appropriate number of times, and creates an `ARRAY` `A` with indices from `1` to `X` and where each element of `A` is the string `1` repeated `X` times.

Then no matter how many times the program is repeated, the interpreter only sees:

```
I	I =I + 1
	OUTPUT =A<I>	:S(I)
END

```

which is a typical SNOBOL program that prints out the elements of `A` one at a time until the index goes out of bounds, then terminates the program.

`;` is an optional line terminator usually reserved for one-line `EVAL` or `CODE` statements that quite neatly brings the byte count to 68 and marks the halfway point, allowing the code to be appended there.
> 3 votes

# Answer
# Julia 0.6, 29 bytes

All my ideas were longer than adapting xnor's clever python solution.

```
i=0;i+=1;    i
println("0"^i)

```

Becomes

```
i=0;i+=1;    ii=0;i+=1;    i
println("0"^i)
println("0"^i)

```

Try it online!
> 3 votes

# Answer
# shortC, ~~56~~ 44 bytes

-12 bytes: wait duh I'm using shortC why not use some shortened C stuff

```
s[];A
strcat(s,"@");//
Js);/*filling space*/

```

I would've used standard C, but that requires a `}` at the end which messes with replication. shortC inserts it at EOF implicitly.
> 3 votes

# Answer
# Perl 5, 25 bytes

**24 bytes code + 1 for `-p`.**

Appreciate that you might not want to allow commandline flags, please let me know if this is not valid.

```
$@=0 x++$n;;$_="$@
"x$n;

```

Try it online!
> 2 votes

# Answer
# Zsh, 10 bytes

```
s+=0
<<<$s

```

**Try a full test suite online!**

...yeah, this is a bit better. Append to string N times, then print N times. Turns out `<<<foo<<<foo` works just fine.

---

### Zsh, 64 bytes

Character used:  (space).

```
f(){printf '%*s\n' $1}
:<<'E'

E
repeat $[i=LINENO/3];f $i
exit

```

**Try a full test suite online!**

The midpoint is between the second `E` and the newline following it. A heredoc will end when there is an `E` on a line by itself, which happens right in the middle of the code.
> 1 votes

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