# Question
Title: Make an ASCII bat fly around an ASCII moon
**Background**

Here is a Halloween related challenge.

As you may have seen from my last challenge I quite like what I term as ascii art animations, that is not just draw a pattern but draw a pattern that progresses. This idea came to me after I was asked a couple of years ago to liven up a (rather dull) presentation by making random ascii bats fly across the screen on Halloween. Needless to say I duly obliged (I was being paid for it) but it made me think that there is more to life than random bats. Inspired by this I would like to propose this challenge.

**Challenge**

Make a bat fly around the moon.

Here is a bat:

```
^o^

```

Here is the moon:

```
     mmm
   mmmmmmm
  mmmmmmmmm
   mmmmmmm
     mmm

```

You must show every stage of the bats flight (see output).

**Input**

None

**Output**

```
      ^o^
      mmm
    mmmmmmm
   mmmmmmmmm
    mmmmmmm
      mmm

      mmm^o^
    mmmmmmm
   mmmmmmmmm
    mmmmmmm
      mmm

      mmm
    mmmmmmm^o^
   mmmmmmmmm
    mmmmmmm
      mmm

      mmm
    mmmmmmm
   mmmmmmmmm^o^
    mmmmmmm
      mmm

      mmm
    mmmmmmm
   mmmmmmmmm
    mmmmmmm^o^
      mmm

      mmm
    mmmmmmm
   mmmmmmmmm
    mmmmmmm
      mmm^o^

      mmm
    mmmmmmm
   mmmmmmmmm
    mmmmmmm
      mmm
      ^o^

      mmm
    mmmmmmm
   mmmmmmmmm
    mmmmmmm
   ^o^mmm

      mmm
    mmmmmmm
   mmmmmmmmm
 ^o^mmmmmmm
      mmm

      mmm
    mmmmmmm
^o^mmmmmmmmm
    mmmmmmm
      mmm

      mmm
 ^o^mmmmmmm
   mmmmmmmmm
    mmmmmmm
      mmm

   ^o^mmm
    mmmmmmm
   mmmmmmmmm
    mmmmmmm
      mmm

      ^o^
      mmm
    mmmmmmm
   mmmmmmmmm
    mmmmmmm
      mmm

```

**Rules**

* No reading from external files or websites
* You may submit a full program or a function
* Extra spaces and/or newlines are fine by me
* Standard loopholes banned as usual
* The bat must finish back at the top of the moon
* Please feel free to clear the screen between frames if you wish however this is not a requirement. Output as shown above is fine
* As this is code golf, the winner will be the answer with the lowest byte count although any answer is welcome

**Sample**

Reference implementation in totally ungolfed Python 2 (620 bytes but just to prove that it can be done. May golf it later).

```
b='^o^'
m=['                     ',
'         mmm         ',
'       mmmmmmm       ',
'      mmmmmmmmm      ',
'       mmmmmmm       ',
'         mmm         ',
'                     ']
p=[(9,12),(12,15),(14,17),(15,18),(14,17),(12,15),(9,12),(6,9),(4,7),(3,6),(4,7),(6,9),(9,12)]
d=0
for z in range(7):
    x=map(str,m[z])
    c="".join(x[:p[z][0]]) + b + "".join(x[p[z][1]:])+"\n"
    print "\n".join(m[:z]) + "\n" + c+"\n".join(m[z+1:])
for z in range(6)[::-1]:
    x=map(str,m[z])
    c="".join(x[:p[z+6][0]]) + b + "".join(x[p[z+6][1]:])+"\n"
    print "\n".join(m[:z]) + "\n" + c+"\n".join(m[z+1:])

```

**Result**

Although @Jonathan obviously wins on byte count with Jelly, I am going to mark the Brainfuck answer from @Oyarsa as the accepted answer purely because I think that anyone who can actually do something like this in such a crazy language deserves +15 rep no matter how many bytes it takes. This is not because I have any problem with golfing languages. See my answer to a question regarding this on meta if you have any doubts. Many thanks and respect to all who contributed in whatever language.

# Answer
# Brainfuck, 690 Bytes

This is my first time golfing, so I'm sure there's still plenty of room for improvement

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

```

Try it online

Ungolfed some for readability:

```
-[-[-<]>>+<]>-<<+++[>+++++++<-]>>>+>>-[<-->-------]<->++++++++>+>+++++>+>+++++>+>+++++++>+>+++++>+>+++++>+>++++++++>+>+>+>>+++[<++++++>-]<+>+>-->+>+>+
Sets counters for creation of the m's and spaces
[<]>[[<+>>-[>]+[[<]>+[>]<+[<]>>>-]<<[->>+<<]>-]>-[->>>>+<<<<]>++]
Adds the first counter plus two of the character at the second counter to the end of the
current set of cells removes the first two counters on the list then repeats until
it encounters a 254
>>>[[-]<]>>>>[>]>>+>+++++++<<<<[<]
Removes some excess cells then adds a 7 after the end of the set of cells
+<+<<+[[<]++++[>++++<-]>[<+[>]>[-<+>]<[<]>>-]>[>]++++++++++[>]>>>-[<]<<[<]<]
Adds a newline every 16 characters until 7 newlines are added
<[<]>->-<<<[-]++++++<+<+++[>++++++<-]+<++++[>++++++++<-]---<-[>+<-----]++<----[>+<----]--<-[>+<---]<-[>++<-----]++++<-[>+<---]++<-[>+<-------]---<----[>+<----]<--[>+<++++++]<+++++[>+++++<-]++++++
Removes some excess cells then sets indices for the locations of bats
>[[[>]>[>]>>[-<<+>>]<<[<]<[<]>-]>[>]>[>]+++++++[>+++++++++<-]>-[->+>+>+<<<]++++[>>++++<<-]>>+<<<<[<]>[.>]>>[.>]<[<]>[-]>[-]>[-]<+[--<---[->]<]<[->+>+>+<<<]<<[[->>+<<]<]<]
Loops through the indices replacing the spaces at each index with a bat then printing
the set of cells then changing the bat back to spaces

```

I wanted to use the fact that by adding a newline to the beginning, each stage can be read in both directions to get two different stages, but I couldn't find a good way to do so without generating the full six and a half stages at once.
> 9 votes

# Answer
# 05AB1E, ~~69~~ ~~62~~ 60 bytes

Saved 2 bytes thanks to *Adnan*.

```
3ð×…^o^)U13FNV0379730vð5y>;ï-y_+×N(Y-12%_Xè'my×NY-12%_y&XèJ,

```

Try it online!

**Explanation**

`3ð×…^o^)U` stores the list `[" ","^o^"]` in **X** for later use.

`13FNV` loops over the 13 stages *\[0 .. 12\]* and stores the current iteration index in **Y**.

`0379730v` loops over the rows of each stage,
where **N** is the row index and **y** is the current number of *m's*.

We start by adding `floor(5/(y+1))-(y==0)` spaces to each row with `ð5y>;ï-y_+×`.

We then determine if there should be a bat or 3 spaces before the *m's*.
If `(-N-Y)%12 == 0` is true we add a bat, else 3 spaces.
This expression (`N(Y-12%_Xè`) will place bats in stages `0,6-12`.

Then we place **y** *m's* with `'my×`.

Now we determine if there should be a bat or 3 spaces after the *m's*.
The code `NY-12%_y&Xè` will place a bat if `((N-Y)%12 == 0) and y!=0` is true, else 3 spaces.
This will place the bats on stages `1-5`.

Finally we join the whole row into a string and print with a newline: `J,`.
> 23 votes

# Answer
## JavaScript (ES6), ~~109~~ ~~144~~ ~~140~~ 138 bytes

```
f=(k=13,b=y=>(y-k)%12?'   ':'^o^')=>k--?[0,3,7,9,7,3,0].map((n,y)=>' '.repeat(5-n/2+!n)+b(y)+'m'.repeat(n)+b(n?-y:.1)).join`
`+`
`+f(k):''

console.log(f());
```

### Animated version

```
f=(k,b=y=>(y-k)%12?'   ':'^o^')=>[0,3,7,9,7,3,0].map((n,y)=>' '.repeat(5-n/2+!n)+b(-y)+'m'.repeat(n)+b(n?y:.1)).join`
`

var k =0;
setInterval(function() { o.innerHTML = f(k++) }, 150);
```

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

# Answer
## HTML+JS, ~~153~~ 149 bytes

```
n=setInterval(_=>o.innerText=`zzd
zc3e
 b7f
a9g
 l7h
zk3i
zzj`.replace(/\S/g,c=>parseInt(c,36)-n%12-10?`m`.repeat(c)||`   `:`^o^`,n++),1e3)
```

```
<pre id=o>
```

Edit: Saved a bunch of bytes thanks to @RickHitchcock. The boring version that just returns the 13 multiline strings in an array is ~~132~~ 131 bytes:

```
_=>[...Array(13)].map((_,n)=>`zza
zl3b
 k7c
j9d
 i7e
zh3f
zzg`.replace(/\S/g,c=>parseInt(c,36)-n%12-10?`m`.repeat(c)||`   `:`^o^`))

```
> 15 votes

# Answer
# Jelly, ~~76 69~~ 58 bytes

```
⁾ mṁ11ż“æ¤¿¬®µ‘ŒḄ¤Œṙs⁴Y
_4¢ḣ;“^o^”;¢ṫ⁸¤
“½œ0CSbp\I7'ð½‘Ç€Y

```

**TryItOnline**

### How?

```
⁾ mṁ11ż“æ¤¿¬®µ‘ŒḄ¤Œṙs⁴Y - Link 1, make a moon (niladic)
⁾ m                     - literal " m"
   ṁ                    - reshape like
    11                  - 11 (interpreted as range(11)) -> " m m m m m "
                 ¤      - nilad followed by links as a nilad
       “æ¤¿¬®µ‘         - code page indexes [22,3,11,7,8,9]
               ŒḄ       - bounce -> [22,3,11,7,8,9,8,7,11,3,22]
      ż                 - zip -> [[22,' '],[3,'m'],[11,' '],...]
                  Œṙ    - run length decode -> "                      mmm           mmmmmmm        mmmmmmmmm        mmmmmmm           mmm                      "
                    s   - split into chunks of length
                     ⁴  - l6
                      Y - join with line feeds

_4¢ḣ;“^o^”;¢ṫ⁸¤ - Link 2, a moon with a bat placed: endIndex
_4              - subtract 4 (startIndex)
  ¢              - call last link (1) as a nilad
   ḣ            - ḣead to startIndex
    ;           - concatenate
     “^o^”      - literal "^o^"
          ;     - concatenate
              ¤ - nilad followed by links as a nilad
           ¢    - call last link (1) as a nilad
            ṫ⁸  - tail from endIndex

“½œ0CSbp\I7'ð½‘Ç€Y - Main link (niladic)
“½œ0CSbp\I7'ð½‘    - code page indexes [10,30,48,67,83,98,112,92,73,55,39,24,10]
                   -    indices to the right of each bat in a constructed moon
               Ç€  - call last link (2) as a monad for each
                 Y - join on line feeds

```
> 14 votes

# Answer
# Python 2, ~~146 144~~ 138 bytes

-2 bytes thanks to @Willem (use the variable `c` rather than looping through a `map`)

```
m='\n'.join(int(a)*' '+int(b)*'m'+3*' 'for a,b in zip('6643466','0379730'))
for b in" -;L[hrbQ@2' ":c=ord(b)-23;print(m[:c-3]+'^o^'+m[c:])

```

**repl.it**

`'6643466'` is the number of spaces before the moon (with 6 on the empty first and last lines, since the bat will go there).

`'0379730'` is the number of `'m'`s in the moon on each line.

The `zip` unpacks these characters into `a` and `b` and makes the moon in the sky, `m`, with 3 trailing spaces on each line.

The last line then traverses the positions of the bat within the moon, and is effectively:

```
for c in(9,22,36,53,68,81,91,75,58,41,27,16,9):print(m[:c-3]+'^o^'+m[c:])

```

but the tuple of positions is encoded as the ordinals of printable characters, with an added 23 (since 9 is not printable). This comes out as `" -;L[hrbQ@2' "`, and `c=ord(b)-23` is used to extract the values.
> 12 votes

# Answer
# Autovim, ~~85~~ 81 bytes

No animation, probably still golfable... Still, not bad for the new kid on the block! (autovim)

```
ñ9am␛ÿP2xÿP4xyjGpđp2o
%ce 15
®q=8j$p
®z=6␍"_d3hP
ñğyG12PğÿPC^o^␛v^y6@q==o␛6@z==O

```

To run it:

```
autovim run ascii-bat.autovim -ni

```

## Explanation

In short, we draw the moon, copy and paste it 12 times, and use two macros: one to append the bat on the first 7 moons, the other to prepend the last 6.

```
" Draw the moon
ñ                                 " Normal mode
 9am␛                            " Write 9 `m`
      ÿP                          " Duplicate the line
        2x                        " Delete two characters
          ÿP                      " Duplicate the line
            4x                    " Delete 4 characters
              yj                  " Yank two lines
                Gp                " Paste at the end of the file
                  đp              " inverts the current line with the previous
                    2o            " Add two line breaks

%ce 15                            " Center our moon

" Macros
®q=8j$p                           " Macro `q` jumps 8 lines, and pastes
                                  "   at the end
®z=6␍"_d3hP                      " Macro `z` jumps 6 lines and replaces
                                  "   the previous 3 characters by the default

" Draw all 12 moons and add the bats
                                  "   register's content
ñ                                 " Run in normal mode
 ğyG                              " Copy the moon we just drew
    12P                           " Duplicate the moon 12 times
       ğÿP                        " Duplicate the top line (gets 3 centered `m`)
          C^o^␛                  " Change the mmm by a bat
                v^y               " Copy the bat we just drew
                   6@q            " Add the first 6 bats
                      ==          " Center the bat
                        o␛       " Add a line under the bat
                           6@z    " Add the 6 last bats
                              ==  " Align the last bat in the center
                                O " Add a line over the last moon

```
> 7 votes

# Answer
## Python 2, 112 bytes

```
b=['   ','^o^']
for k in range(91):r=k%7;print(b[k/7+r==12]*(r%6>0)+(r*(6-r)*8/5-5)*'m'+b[k/7%12==r]).center(15)

```

Print the picture. Each line has three parts

* A potential bat on the left
* Some number of `m`'s for the moon
* A potential bat on the right

These parts are concatenated and centered in a box of size 15 for spacing. To avoid the bats shifting the center, a missing bat is three spaces, the same length. For bats on top of or below the moon, the left bar slot is omitted and the right slot is occupied.

There are 91 lines: a 7-line picture for each of 13 pictures. These are counted up via divmod: As `k` counts from `0` to `91`, `(k/7, k%7)` goes

```
(0, 0)
(0, 1)
(0, 2)
(0, 3)
(0, 4)
(0, 5)
(0, 6)
(1, 0)
(1, 1)
 ....
(12, 5)
(12, 6)

```

Taking the first value `k/7` to be the picture and the second value `r=k%7` as the row number within the picture, this counts up first by picture, then by row number within each picture, both 0-indexed.

The number of `m`'s in the moon changes with row number `r=k%7` as `[0,3,7,9,7,3,0]`. Rather than indexing into this, a formula was shorter. A convenient degree of freedom is that the `0`'s can be any negative value, as this still gives the empty string when multiplied by `m`. Fiddling with a parabola and floor-dividing gave a formula `r*(6-r)*8/5-5`.

Now, we look at selecting whether to draw a bat or empty space on either side. The array `b=[' ','^o^']` contains the options.

The bat in row 0 on in picture 0 (on top), in row 1 in picture 1 (on the right), on to in row 6 in picture 6 (on top). So, it's easy to check whether it appears as the row and picture number as being equal, `k/7==r`. But we also need picture 12 to look like picture 0, so we take the picture number modulo 12 first.

On the left it's similar. The bat appears on the left in rows `r=5,4,3,2,1` in pictures `7,8,9,10,11`. So, we check whether the row and picture number sum to 12. We also make sure to draw nothing rather than three spaces on rows `0` and `6` -- the right bat slot will draw the bat, and we must not mess up its centering.
> 7 votes

# Answer
## PHP, 167 bytes

I made a small program in PHP:

```
<?php foreach([0,3,7,9,7,3,0]as$l)$b.=str_pad(str_repeat('=',$l),15," ",2)."\n";foreach([6,25,43,60,75,89,102,83,65,48,33,19,6]as$x)echo substr_replace($b,'^o^',$x,3);

```

Here is a more verbose version:

```
// width of the moon
$moonsizes = [0,3,7,9,7,3,0];
// position where to place the bat
$positions = [6,25,43,60,75,89,102,83,65,48,33,19,6];
// prepare base moon painting
foreach($moonsizes as $size){
    $basepainting .= str_pad(str_repeat('=',$size),15," ",STR_PAD_BOTH)."\n";
}
// loop frames and place bat
foreach($positions as $position) {
    echo substr_replace($basepainting,'^o^',$position,3);
}

```

This is my first codegolf, if you have any suggestion i'm happy to hear :)
> 7 votes

# Answer
# Python 2, ~~299~~ ~~300~~ ~~290~~ 270 bytes

Golfed down to 270 having gained a bit more golfing experience.

Reference implementation golfed down by ~~321~~ ~~320~~ 330 bytes. Not pretty or elegant. Just uses brute force string and list slicing. Was fun to get the byte count down though but I think the approach was completely wrong to start with for a serious competitor.

I don't expect this answer to be taken seriously so please no downvotes. I did say in the question that I would try to golf the reference implementation and this is exactly that. Just posted for fun.

```
c,e,n=' ','m','\n';f,g=c*9+e*3+c*9,c*7+e*7+c*7;h=9,12;i=12,15;j=6,9;k=13,17;l=4,7;m=c*21,f,g,c*6+e*9+c*6,g,f,c*21;p=h,i,k,(15,18),k,i,h,j,l,(3,6),l,j,h;w=0
for z in map(int,'0123456543210'):print n.join(m[:z])+n+m[z][:p[w][0]]+'^o^'+m[z][p[w][1]:]+n+n.join(m[z+1:]);w+=1

```

Try it online!
> 6 votes

# Answer
## C#, ~~615~~ ~~582~~ 337 bytes

This is my first (still far too readable) attempt at one of these, so I'll gladly welcome any suggestions to shave off a few hundred bytes! Top of my list right now is a shorter way to create the moon array.

```
void M(){string[]m={"","      mmm","    mmmmmmm","   mmmmmmmmm","    mmmmmmm","      mmm",""};var b="^o^";for(int x=0;x<13;x++){var a=(string[])m.Clone();int n=x>6?12-x:x;int[] j={0,1,3,6};a[n]=!a[n].Contains("m")?"      "+b:x<=n?a[n]+b:new string(' ',j[Math.Abs(9-x)])+b+a[n].Replace(" ","");foreach(var c in a){Console.WriteLine(c);}}}

```

Ungolfed (includes loop!)

```
class Program {
    public static string[] moon = new string[] { "               ", "      mmm      ", "    mmmmmmm    ", "   mmmmmmmmm   ", "    mmmmmmm    ", "      mmm      ", "               " };

    public static string bat = "^o^";

    static void Main(string[] args) {
        while (true) {
            Fly();
        }
    }

    static void Fly() {
        int times = (moon.Length * 2) - 1;
        for (int x = 0; x < times; x++) {
            string[] temp = (string[])moon.Clone(); //create a new array to maintain the original

            int index = x >= moon.Length ? times - x - 1 : x;

            if (!temp[index].Contains("m")) {
                temp[index] = new string(' ', 6) + bat + new string(' ', 6);
            } else if (x <= index) {
                int lastM = temp[index].LastIndexOf('m') + 1;
                temp[index] = temp[index].Insert(lastM, bat);
            } else {
                int firstM = temp[index].IndexOf('m');
                char[] src = temp[index].ToCharArray();
                int i = firstM - bat.Length;
                src[i] = bat[0];
                src[i + 1] = bat[1];
                src[i + 2] = bat[2];

                temp[index] = new string(src);
            }

            for (int y = 0; y < temp.Length; y++) {
                Console.WriteLine(temp[y]);
            }
            Thread.Sleep(100);
            Console.Clear();
        }
    }
}

```

Edit:

Took out 21 bytes by removing trailing spaces in the array declaration. Instead of a grid 15 characters wide, each row is only wide enough for the bat to fit. Removed another 12 for the unnecessary string\[\]args in `Main()` declaration.

Edit 2:

Rewrote most of the logic, taking out 245 bytes! Includes suggested changes from the comments. Thanks!

From the comments, turned this into a function `M()` instead of the previous `Main()` method - so now, this needs to be called externally.
> 6 votes

# Answer
## Ruby, ~~164~~ 156 bytes

```
puts Zlib.inflate Base64.decode64 "eNqlkrUVAAEMQvtMcZP9DfLYvzo3qhNSxQ2GVRC1ad29ar1JXaoHbul16Yig+p6BCKqtFBFU+1IE1famoHrX/jZBvN8e8f5tiE94Ib4SBREwNKH5BNJy2QM="

```

Very simple program. Can be worked on more. Please leave tips in the comments.
> 3 votes

# Answer
# ///, 205 bytes

```
/*/\/\///B/^o^*9/
*M/mmm*N/MM*O/   *0/OO*n/

*1/O Nm0
*2/NM0
*3/0M9*4/1O2*7/13n*5/34/0B9570MB0
473O NmBO
O2731ONMBO
75O NmBO
3n510MB0n
5130B9n51OBM9n5 BNm0
3n31B273 BNm0
O27OBM9470B90M0O
410MO

```

Try it online!

Only if I didn't need tons of trailing spaces...
> 2 votes

# Answer
# Mumps, 223 Bytes

This is using InterSystems Cache Mumps -- it allows braces around loops which make it handy for nested loops in a single line.

```
S X="09121415141209060403040609",R="097679",L="037973",S=-14 F Y=1:1:13 S S=S+2 F C=1:1:7 S F=$E(X,Y*2-1,Y*2),(M,T)="",$P(T," ",21)="" F A=1:1:$E(L,C){S M=M_"m"} S $E(T,$E(R,C))=M S:C=$S(Y<8:Y,1:Y-S) $E(T,F,F+2)="^o^" W T,!

```

Could probably be golfed more, and I may play with that when I have more time. Add another 9 bytes, and it'll be animated \[\[ due to the addition of the 'H 1 W # ' --\> that halts for a second and clears the screen:

```
S X="09121415141209060403040609",R="097679",L="037973",S=-14 F Y=1:1:13 S S=S+2 H 1 W # F C=1:1:7 S F=$E(X,Y*2-1,Y*2),(M,T)="",$P(T," ",21)="" F A=1:1:$E(L,C){S M=M_"m"} S $E(T,$E(R,C))=M S:C=$S(Y<8:Y,1:Y-S) $E(T,F,F+2)="^o^" W T,!

```

Here's an ungolfed / explained version (of the animation version), with the correct 'do' statements and dot loops:

```
 S X="09121415141209060403040609"
 S R="097679",L="037973",S=-14              ; Initialize Variablex
 F Y=1:1:13 D                               ; Set up our main loop of 13 cels
 . S S=S+2                                  ; set up secondary counter, for start char.
 . H 1                                      ; halt for 1 second
 . W #                                      ; clear screen
 . F C=1:1:7 D                              ; set up our per-line loop
 . . S F=$E(X,Y*2-1,Y*2)                    ; set F to 2-digit "start of bat"
 . . S (M,T)=""                             ; set our "builder" lines to empty strings
 . . S $P(T," ",21)=""                      ; then reset our main 'line string' to 21 spaces.
 . . F A=1:1:$E(L,C){S M=M_"m"}             ; make our 'moon' text.
 . . S $E(T,$E(R,C))=M                      ; and insert our 'moon' into the empty line
 . . S:C=$S(Y<8:Y,1:Y-S) $E(T,F,F+2)="^o^"  ; find the start character for our 'bat' and insert.
 . . W T,!                                  ; and write the line and a CR/LF.

```

I tried to do the "compress then Base-64 encode" jazz just to see what would happen, but the encoded string ended up a little longer than the program itself! That, and Cache's system calls for the compression and base64 encoding are quite long... for example, here's the system call to decode base64: *$System.Encryption.Base64Decode(STRING)*

That method would 'bloat' the program to over 300 characters, I think...
> 2 votes

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


title: Image Smoothie!

text:
# Question
Title: Image Smoothie!
Input into your program a black and white image. (png, jpg, etc)

Convert the image to a 2D matrix of pixels, where each index is the grayscale value of the image.

Take each index of the matrix and average the 8 pixels around it. Then replace that index with the average.

For example if you had:

```
120 80  60
20  10  30
40  100 05

```

If you were finding the average for 10, the result would be `56.875`, which is `(120,80,60,30,05,100,40,20)/8`.

Round to up to the nearest integer (57) and replace the index. The result of this iteration would be

```
120 80  60
20  57  30
40  100 05

```

If you are finding the average for a pixel on an edge then only take values that are valid. In the example above if you were finding the average for `20` You would only consider `120, 80, 57, 100, and 40` which is `79.4` rounded to `80`.

You may start at any index of the graph but it must be in order. For example you could do

```
[0][0], [0][1], ... [0][n], then [1][0], [1][1],... [1][n]

```

Once the averaging is complete, convert the matrix back into a new image.

Display the new image as the output of the program. (Or save it and add it in your solution). The result of your code should be a blurry looking image but much smoother than the original.

Example Input
Example Output

Example Input two
Example Output two

Please provide your code and start and end image results.

**Q/A**
*1Q. If one of the 8 neighbors has already been changed, should the average be calculated based on this new value, or based on the original values? That is, does the order of calculation affect the end result?*

1A Yes, You should change each index with new values from any potential indices done before. That is why you need to go left-right, top-bottom etc. In order.

*2Q. Could you clarify what is meant by "must be in order"? Does this mean that only raster order/reading order is acceptable? Or does it mean that the order must be the same each time the code is run? Would a spiral be valid? Or a shuffled order that is always the same?*

2A. You should go left to right, right to left, top to bottom, or bottom to top. I.E. Do all of the 0th row, do all of the 1st row,... do all of the nth row

# Answer
# J, ~~90~~ 82 bytes

```
[:((=i.@$){"0 1],"+3 3((+/>.@%#)@(_-.~(<<<4){,);._3)_,.~_,._,~_,])&.>/(#<@-#\)@,,<

```

This iterates over pixels from left-to-right, then top-to-bottom.

You can see the progression of values here.

```
   |. ((=i.@$){"0 1],"+3 3((+/>.@%#)@(_-.~(<<<4){,);._3)_,.~_,._,~_,])&.>/\. ((#<@-#\)@,,<) 120 80 60 , 20 10 30 ,: 40 100 5
┌──────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬────────┬────────┐
│120  80 60│37  80 60│37  32 60│37  32 24│37  32 24│37  32 24│37  32 24│37  32 24│37 32 24│37 32 24│
│ 20  10 30│20  10 30│20  10 30│20  10 30│44  10 30│44  39 30│44  39 40│44  39 40│44 39 40│44 39 40│
│ 40 100  5│40 100  5│40 100  5│40 100  5│40 100  5│40 100  5│40 100  5│61 100  5│61 38  5│61 38 39│
└──────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴────────┴────────┘

```

The output for the first sample image is (converting from an array of pixels to a bmp)
> 5 votes

# Answer
# PHP, 321 bytes

```
$i=imagecreatefromjpeg($f="96512.jpg");list($w,$h)=getimagesize($f);for($y=$h;$y--;)for($x=$w;$x--;$s=$n=0){for($a=-2;$a++<1;)for($b=-2;$b++<1;)if(false!==($d=imagecolorat($i,$x+$a,$y+$b))){$n++;$s+=imagecolorsforindex($i,$d)[red];}imagesetpixel($i,$x,$y,imagecolorallocate($i,$r=ceil($s/$n),$r,$r));}imagejpeg($i,"b$f");

```

does the blurring from bottom to top, from right to left.

-2 bytes for a gif or png; could save even more with a shorter file name
and -6 if rounding down was allowed. pity that image processing functions have so long names.
but I´m fine. pretty byte count.
> 4 votes

# Answer
# PHP, 70 bytes

```
imagefilter($i=imagecreatefromjpeg($f="i.jpg"),10,0);imagejpeg($i,$f);

```

Overwrites the original image file. Run with `-r`.
-2 bytes if you use a gif or png.

---

I thought PHP might have a built-in for this, and indeed:
`10` stands for `IMG_FILTER_SMOOTH`; and `0` is the weight parameter.

See the GD library source code: This calls `gdImageSmooth` which calls `gdImageConvolution` with the requested matrix. I am not sure what it does at the edges; but overall it does the smoothing from top to bottom, from left to right.
> 2 votes

# Answer
## Racket 346 bytes

```
(let((s1 sub1)(a1 add1)(lr list-ref)(ln length))(define(g r c)(if(or(> r(s1(ln l)))(> c(s1(ln(lr l 0))))(< r 0)(< c 0))
#f(lr(lr l r)c)))(define(ng r c)(define h'(-1 0 1))(define k(filter(λ(x)x)(for*/list((i h)(j h)#:unless(= 0 i j))
(g (+ r i)(+ c j)))))(round(/(apply + k)(ln k))))(for/list((i(ln l)))(for/list((j(length (lr l 0))))(ng i j))))

```

Ungolfed (comments follow ';'):

```
(define (f l)
  (define (get r c)                       ; to get value at a row,col
    (if (or (> r (sub1 (length l)))
            (> c (sub1 (length (list-ref l 0))))
            (< r 0)
            (< c 0))                      ; if row/col number is invalid
        #f (list-ref (list-ref l r) c)))  ; return false else return value
  (define (neighbors r c)                 ; finds average of neighboring values
    (define h '(-1 0 1))
    (define k (filter                     ; filter out false from list
               (lambda(x) x)
               (for*/list ((i h)(j h) #:unless (= 0 i j))
                 (get (+ r i) (+ c j)))))
    (round(/(apply + k)(length k))))      ; find average of values (sum/length of list)
  (for/list ((i (length l)))              ; create a list of lists of average values
    (for/list ((j (length (list-ref l 0))))
      (neighbors i j))
    ))

```

Testing:

```
(f (list
    '(120 80 60)
    '(20 10 30)
    '(40 100 5)))

```

Output:

```
'((37 48 40) (70 57 51) (43 21 47))

```
> 1 votes

# Answer
## Ruby 2.3.1, 338 bytes

```
->w{d,k=16843008,ChunkyPNG::Canvas.from_file(w);(0..k.height-1).each do |y|;(0..k.width-1).each do |x|;t,i,a=0,0,[[x-1,y-1],[x,y-1],[x+1,y-1],[x-1,y],[x+1,y],[x,y+1],[x,y+1],[x+1,y+1]];a.each do |c|; next unless k.include_xy?(c[0],c[1]);t=t+k.[](c[0],c[1]);i=i+1;end;n=t/i;while(n%d)>0 do;n=n+1;end;k.[]=(x,y,n-1);end;end;k.save("w")}

```
* Uses oily\_png/chunky\_png for image handling.
* Goes left to right, top to bottom doing the averaging.
* Since chunky uses integer color values, I'm doing a really, really slow up rounding method to get averaged color values to an actual grayscale value.

Example output(that took a very, very long time):

# Ungolfed, slightly modded, and commented

```
require 'oily_png'
l = -> img {
  time_begin = Time.new
  d = 16843008
  k = ChunkyPNG::Canvas.from_file(img)
  # go line by line, pixel by pixel
  (0..k.height-1).each do |y|
    (0..k.width-1).each do |x|
      total, i = 0, 0
      p "Starting color is #{curr} or #{curr.to_s(16)}"
      # set the coords around the pixel we want
      around = [[x-1,y-1], [x, y-1], [x+1, y-1], [x-1,y], [x+1, y], [x,y+1], [x, y+1], [x+1, y+1]]
      # grab the 8 colors around the current pixel
      around.each do |coords|
        # ignore values that are not in bounds
        next unless k.include_xy?(coords[0], coords[1])
        # get a total to average later
        total = total + k.[](coords[0], coords[1])
        # increment
        i = i+1
      end
      # get the average value for the new color
      new_color = total/i
      # since new color will likely not be a grayscale value,
      # round up to the nearest grayscale value.
      # This is unfortunately really slow.
      while (new_color%d) > 0 do
        new_color = new_color+1
      end
      p "New color is now #{new_color-1} or #{(new_color-1).to_s(16)}"
      # set the color and
      # remove one from the color value to get full alpha instead of none.
      k.[]=(x, y, new_color-1)
    end
  end
  # save the complete image
  k.save("#{Time.new}.png")
}
l.($*[0])

```

Could certainly do things a bit more efficiently, unfortunately I'm not quite how to. There's got to be a more clever way of handling the coordinate management for the 8 surrounding locations.
> 1 votes

---
Tags: code-golf, image-processing, matrix
---


title: The 3x3 Hexa Prime Square Puzzle

text:
# Question
Title: The 3x3 Hexa Prime Square Puzzle
# The 3x3 Hexa Prime Square Puzzle

### Introduction

We consider 3x3 squares of hexadecimal digits (from `0` to `F`) such as:

```
2 E 3    1 F 3
8 1 5    7 2 7
D D 5    B B 9

```

We define a **3x3 Hexa Prime Square** (**HPS3**) as such a square for which all hexadecimal numbers read from left to right and from top to bottom are odd primes (i.e. primes greater than 2).

This is true for the left square and false for the right square:

```
2 E 3 --> 0x2E3 = 739       1 F 3 --> 0x1F3 = 499
8 1 5 --> 0x815 = 2069      7 2 7 --> 0x727 = 1831
D D 5 --> 0xDD5 = 3541      B B 9 --> 0xBB9 = 3001
| | |                       | | |
| | +---> 0x355 = 853       | | +---> 0x379 = 889 = 7 x 127
| +-----> 0xE1D = 3613      | +-----> 0xF2B = 3883 = 11 x 353
+-------> 0x28D = 653       +-------> 0x17B = 379

```

### Goal

Given a list of 9 hexadecimal digits, your goal is to find an arrangement that forms a HPS3.

**Example:**

```
Input: 123558DDE
Possible output: 2E3815DD5 (a flattened representation of the above left example)

```

### Input / Output

Input and output formats are flexible. The only requirement is that output digits are ordered from left to right and from top to bottom. Below are some possible options:

```
"2E3815DD5"
[ 0x2, 0xE, 0x3, 0x8, 0x1, 0x5, 0xD, 0xD, 0x5 ]
[ "2", "E", "3", "8", "1", "5", "D", "D", "5" ]
[
  [ 0x2, 0xE, 0x3 ],
  [ 0x8, 0x1, 0x5 ],
  [ 0xD, 0xD, 0x5 ]
]
[ "2E3", "815", "DD5" ]
etc.

```

Using the same format for both input and output is not required.

### Rules

* This is code-golf, so the shortest answer in bytes wins. Standard loopholes are forbidden.
* Your algorithm must be deterministic
* You can't just bogosort the array until it's valid, even in a deterministic way (by using a constant random seed).
* You *may* list all possible solutions for a given input, but this is neither required nor subject to a bonus.
* You're not required to support inputs that do not admit any solution. (It's perfectly fine if your code is looping forever or crashing in that case.)

### Test cases

```
Input       Possible output
---------------------------
123558dde   2e3815dd5
1155578ab   a7b851551
03bddffff   ffd0dfb3f
35899beff   8f99e3bf5
15899bbdf   581bb9fd9
14667799f   6f1469779
13378bcdd   78d1cd33b
24577bbdd   7274bd5db
1118bbddd   11b18dbdd
223556cdd   623c25dd5
12557899a   8a5295971
113579bbd   5b3db7191

```

# Answer
# 05AB1E, ~~23~~ 21 bytes

Uses CP-1252 encoding.

```
œJvy3ôD€SøJìHDps2›*P—

```

Too slow for TIO.

**Explanation**

```
œJ                     # all permutations of input as strings
  v                    # for each permutation
                       # EXAMPLE: 2E3815DD5
   y3ô                 # split in pieces of 3
                       # EXAMPLE: ['2E3','815','DD5']
      D                # duplicate
                       # EXAMPLE: ['2E3','815','DD5'], ['2E3','815','DD5']
       €SøJ            # zip the copy to swap rows and columns
                       # EXAMPLE: ['2E3','815','DD5'], ['28D','E1D','355']
           ì           # attach them to the same list
                       # EXAMPLE: ['2E3','815','DD5','28D','E1D','355']
            H          # convert from base 16 to base 10
                       # EXAMPLE: [739, 2069, 3541, 653, 3613, 853]
             D         # duplicate
                       # EXAMPLE: [739, 2069, 3541, 653, 3613, 853],[739, 2069, 3541, 653, 3613, 853]
              p        # check first copy for primality
                       # EXAMPLE: [739, 2069, 3541, 653, 3613, 853],[1,1,1,1,1,1]
               s2›     # check that each in second copy is larger than 2
                       # EXAMPLE: [1,1,1,1,1,1],[1,1,1,1,1,1]
                  *    # pairwise multiplication
                       # EXAMPLE: [1,1,1,1,1,1]
                   P   # product (1 if all were primes larger than 2, else 0)
                       # EXAMPLE: 1
                    —  # if 1, print y
                       # EXAMPLE: 2E3815DD5

```
> 6 votes

# Answer
# Python 2, ~~212~~ ~~206~~ ~~197~~ 194 bytes

Requires input enclosed in quotes, like `"123558dde"`

```
from itertools import*
k,p,P=3,4,[]
while k<5e3:P+=[k][:p%k];p*=k;k+=1
print[s for s in map(''.join,permutations(input()))if all(int(s[3*i:][:3],16)in P and int(s[i::3],16)in P for i in(0,1,2))]

```

Saving 9 and 3 bytes thanks to Jonathan Allan

Found new prime filter from xnor (modified the square away, since we dont want 2 as prime here), old prime filter is from Bob
> 5 votes

# Answer
# Jelly, ~~34~~ 30 bytes

```
i@€ØH’
s3µ;ZÇ€ḅ⁴µ>2aÆPẠ
Œ!ÇÐfḢ

```

*(I should be able to use an nfind to just fetch the first match, `1#` in place of `ÐfḢ`, for less bytes and more speed, but I'm seeing errors when I try. EDIT: wrote some changes to possibly implement this in Jelly.)*

Brute force search of all permutations, filtered for the criteria, returning first match.
Way too slow for TtyItOnline. Local output examples:

```
C:\Jelly\jelly-master>python jelly -fu test.txt "123558DDE"
28DE1D355
C:\Jelly\jelly-master>python jelly -fu test.txt "1155578AB"
11B8A5557

```

### How?

```
i@€ØH’ - Link 1, convert from hexadecimal string to integer list: string
   ØH  - yield hexadecimal characters, "0123456789ABCDEF"
i@€    - index of €ach character of s in hex chars
     ’ - decrement (vectorises) (from 1 based jelly index to place value)

s3µ;ZÇ€ḅ⁴µ>2aÆPẠ - Link 2, check if a flattened square is "all prime": string
s3               - split into threes (rows)
  µ              - monadic chain separation
   ;             - concatenate with
    Z            - transpose (columns)
     Ç€          - call last link (1) as a monad for €ach string in the list
                       -> list of integer lists
       ḅ⁴        - convert from base 16 (vectorises) -> list of decimals
         µ       - monadic chain separation
          >2     - greater than 2
            a    - and
             ÆP  - isPrime? -> list of 1s and 0s
               Ạ - all truthy?

Œ!ÇÐfḢ  - Main link: string
Œ!      - all permutations of the string
   Ðf   - filter keeping entries that evaluate to truthily for
  Ç     - last link (3) as a monad
     Ḣ  - head - return first entry

```
> 3 votes

# Answer
# Pyth, ~~23~~ 21 bytes

```
f*F}R-Pd2iR16sCBc3T.p

```

Times out online, but finishes in 1.5 minutes on my laptop. Takes input in quotes.

### Explanation

```
f*F}R-Pd2iR16sCBc3T.p
                   .pQ     permutations of input (implicit Q)
f                 T        filter each T:
                c3             divide into rows
              CB               make pair (rows, columns)
             s                 join those lists
         iR16                  interpret items as hex
   }R                          check if each number d is in
      Pd                           its prime factors
     -  2                          with twos removed
 *F                            product (also known as all)
                           implicitly print matches

```
> 3 votes

# Answer
# J, 49 bytes

```
[:(#~([:*/@(2&<*1&p:)@(,&dfh|:)_3]\])"{)i.@!@#A.]

```

Brute-force search that tests all permutations and outputs all permutations that satisfy the conditions for the puzzle.

The performance is good enough to compute each test case in about 3 seconds.

## Usage

```
   f =: [:(#~([:*/@(2&<*1&p:)@(,&dfh|:)_3]\])"{)i.@!@#A.]
   f '123558dde'
28de1d355
28de1d355
28de1d355
28de1d355
2e3815dd5
2e3815dd5
2e3815dd5
2e3815dd5
   timex 'f ''123558dde'''
3.68822

```

## Explanation

```
[:(#~([:*/@(2&<*1&p:)@(,&dfh|:)_3]\])"{)i.@!@#A.]  Input: string S
                                             #     Length of S
                                           !@      Factorial
                                        i.@        Range [0, len(S)!)
                                                ]  Get S
                                              A.   Find the permutations of S by index
[:(                                    )           Operate on the permutations
     (                              )"{              For each permutation P
                                   ]                   Get P
                               _3]\                    Get sublists of size 3
      [:              (       )                        Operate on the sublists
                            |:                           Transpose
                        &dfh                             Convert both the transpose and
                                                         initial from hex to decimal
                       ,                                 Join them
           (        )                                  Operate on the decimals
                1&p:                                     Test each for primality
            2&<                                          Test each if greater than 2
               *                                         Multiply them (AND)
        */@                                            Reduce using multiplication
   #~                                                Filter the permutations by those
                                                     values and return

```
> 2 votes

# Answer
# Mathematica, 115 bytes

```
#<>""&@@Select[Permutations@#,And@@(PrimeQ@#&&#>2&)/@(FromDigits[#<>"",16]&/@#~Join~Transpose@#)&[#~Partition~3]&]&

```

The input must be a list of characters (e.g. `{"1", "2", "3", "5", "5", "8", "D", "D", "E"}`)
> 2 votes

# Answer
# Ruby, 146 bytes

Anonymous function takes an array of nine integers, returns one solution as an array of nine integers. Relies on helper function `g` and a `require`.

```
require'prime'
g=->x,y,z{(2<s=x<<8|y<<4|z)&&s.prime?}
->r{r.permutation{|i|a=1
3.times{|j|a&&=g[*i[j*3,3]]&&g[i[j],i[j+3],i[j+6]]}
a&&(return i)}}

```

This **140-byte** version prints all possible solutions, with the integers as decimals (not sure if that's allowed.)

```
require'prime'
g=->x,y,z{(2<s=x<<8|y<<4|z)&&s.prime?}
->r{r.permutation{|i|a=1
3.times{|j|a&&=g[*i[j*3,3]]&&g[i[j],i[j+3],i[j+6]]}
a&&p(i)}}

```

**Ungolfed in test program**

```
require'prime'
g=->x,y,z{(2<s=x<<8|y<<4|z)&&   #combine 3 input values, check if >2
  s.prime?}                     #and check if prime
h=->r{
  r.permutation{|i|             #iterate over all permutations
    a=1                         #a=truthy
    3.times{|j|
      a&&=g[*i[j*3,3]]&&        #check rows (3 consecutive integers)
          g[i[j],i[j+3],i[j+6]] #and columns
    }
    a&&(return i)               #if a still truthy, return solution.
  }
}

#test cases: uncomment to run. solutions do not always match example solution from OP.
a=10;b=11;c=12;d=13;e=14;f=15
#p h[[1,2,3,5,5,8,d,d,e]]   #2e3815dd5
#p h[[1,1,5,5,5,7,8,a,b]]   #a7b851551
#p h[[0,3,b,d,d,f,f,f,f]]   #ffd0dfb3f
#p h[[3,5,8,9,9,b,e,f,f]]   #8f99e3bf5
#p h[[1,5,8,9,9,b,b,d,f]]   #581bb9fd9
#p h[[1,4,6,6,7,7,9,9,f]]   #6f1469779
#p h[[1,3,3,7,8,b,c,d,d]]   #78d1cd33b
#p h[[2,4,5,7,7,b,b,d,d]]   #7274bd5db
#p h[[1,1,1,8,b,b,d,d,d]]   #11b18dbdd
#p h[[2,2,3,5,5,6,c,d,d]]   #623c25dd5
#p h[[1,2,5,5,7,8,9,9,a]]   #8a5295971
#p h[[1,1,3,5,7,9,b,b,d]]   #5b3db7191

```
> 1 votes

# Answer
# Groovy, 134 Bytes

Finds all possible solutions and returns them as an array, returns `[]` if there isn't a solution.

```
{it.toList().permutations().collect{it.collate(3).every{x=Integer.parseInt(it.join(),16);(2..x**0.5).every{x%it>0};}?it.join():0}-[0]}

```

Example input: `123558dde`
Output:

```
[8235d5e1d, 2dd851e35, 815e352dd, 2e3d5518d, d2d3e5581, 853de5d21, 2dd3558e1, 2dd3e5581, 2e355d18d, 2518dd3e5, dd52e3185, e1d5d5283, 823ed1d55, 28d3e515d, 28d15de35, e351258dd, e5dd21853, 851d2d3e5, ed515d283, 2dd3e5185, 85de35d21, 5d1ed5823, 8dd355e21, d2d3e5815, d2d3e5851, 251e358dd, 2dde35851, 8235d5ed1, 2dde35815, e3585dd21, d2d8153e5, 85d5d12e3, 21dd85e35, d8521de35, 21d85d3e5, e1d5d5823, e35581d2d, 3e52dd581, dd52e3851, dd52e3815, 3e5281dd5, 8dd1253e5, 3e5815d2d, 3e55d128d, ed515d823, de5853d21, e218dd355, d8d1253e5, d8d251e35, d8d5512e3, 2dde35581, 3e52dd851, 5d1ed5283, e21dd5853, 3e5d2185d, 2513e58dd, 2dd3e5815, 2dd3e5851, e1d823d55, 3e52dd815, 581d2de35, e3515d28d, 2e318dd55, ed1823d55, dd52813e5, dd52e3581, 2e3515d8d, 28d3e55d1, 82355de1d, 82355ded1, 2dde35185, 3e5d8d125, 85d21de35, 281dd53e5, d21d85e35, d21e35d85, 2dd8e1355, 28d5d1e35, 85d15d2e3, 2813e5dd5, 3e5d2d185, 5d1e5d283, 3e5d2d581, e1dd55823, 3558e12dd, d55283e1d, 15dde5283, 5d128d3e5, 5518dd2e3, e5d28315d, 5d5823ed1, d2d1853e5, 823d55e1d, de521d853, d81d552e3, 5d5823e1d, 21ded5853, 823e1dd55, 3e52dd185, 5812dde35, d85e35d21, 3e585d21d, 8512dd3e5, 3e5251d8d, d2d8513e5, e1dd55283, 2e3d81d55, 853ed5d21, 2835d1ed5, 15d2e3d85, 5d1e3528d, 15dde5823, e35851d2d, 55d283e1d, 2e3551d8d, 8dd3e5125, 85d3e5d21, 8152e3dd5, 28de1d355, e1d55d823, 8dd3e5251, 5158dd2e3, e3521dd85, e1d35528d, 2e35d185d, 21de5d853, 823d55ed1, 5813e52dd, 8153e5d2d, e1d55d283, 21de3585d, d85d21e35, 5152e3d8d, 8513e5d2d, dd5e21853, 3552dd8e1, d552e318d, e5d2835d1, 2835d1e5d, 2835d1de5, 5d1e5d823, 8dde35125, 5d52e3d81, 3e5821dd5, 28d5d13e5, e35d21d85, dd51852e3, d2d185e35, 8dde35251, 8dd2513e5, e35d2d185, 2835d5e1d, 1852e3dd5, d85d213e5, 515d8d2e3, dd53e5821, d5518d2e3, 8dd5512e3, 283d55ed1, e5d5d1823, 28d355ed1, 3e58152dd, d812e3d55, e5d85321d, d8515d2e3, d2d581e35, 3e5581d2d, 85d21d3e5, 283d55e1d, dd53e5281, 851dd52e3, e35dd5821, 3e51258dd, dd58512e3, 28d355e1d, d8d2513e5, 125e358dd, e35dd5281, e35d2d851, d8d2e3515, e35d2d815, d21853ed5, d8d2e3551, 1852dd3e5, d21853e5d, 85dd213e5, d21853de5, 5d1283e5d, 823ed155d, 5d1283de5, ed521d853, 283e1dd55, d8d355e21, d8de35251, 5d1283ed5, e35d2d581, 3e528d15d, d55283ed1, 8512dde35, 3e5851d2d, 823ed15d5, 15d28de35, 15d3e528d, 2835d5ed1, 5d12e385d, 5d185d2e3, 5d5283e1d, 55d2e3d81, d2185de35, d55e1d283, ed582315d, 2dd8513e5, 853e5d21d, e352dd581, 851e352dd, 2dd5813e5, e352dd815, 853d21e5d, e352dd851, dd5821e35, ed155d283, 3e5d8d251, d8de35125, 2e3d8d551, 3e528d5d1, e5d21d853, dd5853e21, 853d21ed5, 85de3521d, e352518dd, 2e3d8d515, 125d8de35, e352dd185, 853d21de5, 8e13552dd, 1258dde35, 581e352dd, e21d8d355, ed155d823, e21853dd5, e3528d5d1, d2d851e35, 5512e38dd, 125d8d3e5, 2e3815dd5, 2513e5d8d, 21dde5853, 355d2d8e1, d55ed1283, 815dd52e3, 283ed1d55, 8152dd3e5, 281e35dd5, 28355de1d, 355e1d28d, ed182355d, 853dd5e21, e3528d15d, ed18235d5, 15d85d2e3, e351852dd, d55e1d823, 8e12dd355, 28355ded1, 2dd815e35, 581d2d3e5, d55ed1823, 15d283ed5, 821dd53e5, 2e35d518d, 5d5283ed1, 15d283e5d, 15d283de5, e1d28355d, e5d5d1283, 251d8d3e5, e1d2835d5, dd5281e35, ed15d5823, 21de35d85, dd58152e3, 2dd1853e5, 1258dd3e5, 5d5e1d283, 1253e58dd, 3e5d8521d, 18d2e3d55, e358152dd, 5512e3d8d, e35251d8d, 853ed521d, 3e5dd5281, 5813e5d2d, ed15d5283, 18d55d2e3, 281dd5e35, 8dde21355, 1852dde35, 3e585dd21, d85e3521d, 581e35d2d, ed1283d55, d812e35d5, 2e35518dd, 5d128de35, 8153e52dd, ed55d1823, e5d82315d, e35d85d21, d812e355d, d853e521d, 8dd2e3551, 2e3581dd5, 15de5d823, 8dd2e3515, 185e35d2d, 125e35d8d, 581dd52e3, 5d5e1d823, 5812e3dd5, 5152e38dd, 3558e1d2d, 85d3e521d, 5d1d852e3, 823de55d1, 2e3d8155d, d213e585d, ed55d1283, 2e3dd5581, 2e3dd5815, 15d823ed5, 2e3dd5851, d552e3d81, 55de1d823, e5d8235d1, 21d853de5, de528315d, d21e3585d, 2e3d815d5, 21d853e5d, ed58235d1, 2e3dd5185, 21d853ed5, de52835d1, 15d823e5d, e1d28d355, 355ed128d, 5812dd3e5, 815d2d3e5, 15d823de5, 823de515d, 55de1d283, ed5853d21, 2dd8153e5, 2e3d855d1, 185dd52e3, 8e1355d2d, 2e3d55d81, d2d3558e1, d8521d3e5, e5d15d823, ed52835d1, 35528de1d, dd5e35281, 3e58dd251, 5d5ed1283, dd58213e5, e355d128d, 3e58dd125, 3e5125d8d, 8213e5dd5, 355e218dd, 2e3d8515d, 35528ded1, e5d15d283, 853e21dd5, 8dd125e35, 15ded5823, e358dd251, 2e315dd85, 851d2de35, 551d8d2e3, d2d5813e5, ed528315d, 2e3185dd5, 185d2de35, 8152dde35, e35d2185d, 15de3528d, e358dd125, 251e35d8d, 5d5ed1823, 821dd5e35, 251d8de35, 8512e3dd5, 5d1823de5, d2d815e35, 3e51852dd, 5d1823e5d, 82315dde5, 3e5dd5821, 82315de5d, 5d518d2e3, 1853e5d2d, 8dd251e35, ed128355d, e1d8235d5, 82315ded5, d21ed5853, 823ed515d, 2e38dd551, ed135528d, 2e38dd515, 5d1823ed5, 2e318d55d, 15de5d283, e1d82355d, ed1d55823, 2e3851dd5, d8d5152e3, 283de515d, 823ed55d1, 3e55812dd, dd5e35821, 15ded5283, e21355d8d, 21d85de35, 8dd5152e3, e35125d8d, e355812dd, 5d52e318d, 8e1d2d355, d8155d2e3, 3e5d21d85, 21d3e5d85, ed12835d5, de585321d, d2185d3e5, 85dd21e35, 2e318d5d5, d213e5d85, 2e385d5d1, 55d823ed1, 15d2e385d, 3e521dd85, 283de55d1, ed1d55283, d8de21355, de5d21853, 55d823e1d, d852e315d, 355d8de21, d852e35d1, 8513e52dd, 185d2d3e5, 853e5dd21, 21d3e585d, 2dd581e35, de582315d, 823e5d15d, de515d283, 185e352dd, 28de3515d, 3e5d2d815, d21de5853, 283ed155d, 3e5d2d851, 55d283ed1, 3558dde21, 283ed15d5, d815d52e3, 28de355d1, 851e35d2d, de515d823, 5d1de5823, 55dd812e3, 283e5d15d, dd55812e3, 823e5d5d1, 15dd852e3, d2de35185, 1253e5d8d, 2e35d5d81, 1853e52dd, 2e35158dd, 21dd853e5, e35185d2d, 283e5d5d1, 18dd552e3, e35281dd5, 5d13e528d, e1d283d55, 2e385d15d, 28315de5d, 85d2e35d1, 28315dde5, 2dd185e35, e3585d21d, 283ed55d1, 5d1de5283, 28315ded5, d55823ed1, 5d12e3d85, e5d853d21, e35d8d125, e358512dd, d55823e1d, 815e35d2d, e35d8d251, 18d5d52e3, 28ded1355, e3521d85d, 283ed515d, 821e35dd5, d2d3e5185, 85321de5d, d2de35815, e35d8521d, d55d812e3, e213558dd, e35815d2d, d855d12e3, 15d28d3e5, d21e5d853, 85d2e315d, 3e58512dd, d2de35851, ed128d355, 28d15d3e5, 3e52518dd, 18d2e355d, de55d1823, d2de35581, 85321ded5, d2d8e1355, d853e5d21, 18d2e35d5, 2e35d1d85, 85321dde5, 3e5185d2d, 853de521d, 355e21d8d, 5d5d812e3, 55ded1823, de55d1283, 8235d1ed5, e35821dd5, 2518dde35, 8235d1de5, 8235d1e5d, 3e521d85d, d8d125e35, 2e315d85d, ed5d21853, 55ded1283, 815d2de35, 283e1d55d, 823e1d55d, 2e355dd81, 3e5d85d21, d8d3e5125, 3e515d28d, d21d853e5, 283e1d5d5, ed585321d, 823e1d5d5, 55d2e318d, d8d3e5251, 55d18d2e3, de58235d1]

```

Example input: `222222222` Output: `[]`

If anyone wants me to comment it out, holler at a brother.
> 0 votes

---
Tags: code-golf, primes, hexadecimal
---


title: Generate a random digit!

text:
# Question
Title: Generate a random digit!
Your task is to generate a random digit following these steps:

First, generate 10 random digits to make a binary number, 50% 0, and 50% 1:

```
010011001

```

If it is all zeros, generate a new one.

Convert this to decimal:

```
153

```

For each digit, write that amount of alternating 0s and 1s (first digit = 1s, second digit = 0s, third digit = 1s, etc.):

```
100000111

```

Convert this to decimal:

```
263

```

Take the middle digit (If there is an even number of digits, take the left middle)

```
6

```

Remember, this is , so the code with the smallest number of bytes wins.

# Answer
> 2 votes
# Pyth, ~~23~~ 22 bytes

*1 byte thanks to @Jakube (swap `r` operands).*

```
ehc2`ir9,R=!ZjOS1023T2

```

Try it online.

> First, generate 10 random digits to make a binary number, 50% 0, and 50% 1.
> If it is all zeros, generate a new one.
> Convert this to decimal.

Generate a number between 1 and 1023. `OS1023` in Pyth. Then get its digits: `j``T`.

> For each digit, write that amount of alternating 0s and 1s (first digit = 1s, second digit = 0s, third digit = 1s, etc.).

Pair each digit with an alternating `True` or `False`: `,R=!Z`. The alternating booleans come from `=!Z`, or `Z = not Z` where `Z` starts as 0. Then run-length decode: `r``9`.

> Convert this to decimal.

Parse integer as binary: `i``2`.

> Take the middle digit (If there is an even number of digits, take the left middle).

Take the string representation: ```. Split it in two, with the possible middle character going to the left: `c2`. Take the first half's last character: `eh`.

# Answer
> 2 votes
# Perl, ~~62~~ ~~61~~ ~~55~~ 53 bytes

Get the digit distribution through a lookup table. Implementing the original algorithm is about 15 bytes longer.

```
perl -E 'say-(map+(--$n)x$_,unpack"W*","\x90leJZaEC_")[rand 1023]'

```

Just the code:

```
say-(map+(--$n)x$_,unpack"W*","\x90leJZaEC_")[rand 1023]

```

Works as shown,, but replace `\x90` by the literal byte to get the claimed score

# Answer
> 2 votes
# 05AB1E, 19 bytes

```
To<L.RvTNèy×}JC2ä¬¤

```

Try it online!

**Explanation**

`153` used as example

```
To<L                  # [1 ... 2^10-1]
                      # STACK: [1 ... 1023]
    .R                # take random number from range
                      # STACK: 153
      v     }         # for each digit
       TNè            # use the digits index in the number to index into 10
          y×          # repeat the number that many times
                      # STACK: 1,00000,111
             J        # join to string
                      # STACK: 100000111
              C       # convert to decimal
                      # STACK: 263
               2ä     # split in 2
                      # STACK: [26,3]
                 ¬¤   # take the last digits of the first part
                      # OUTPUT: 6

```

# Answer
> 0 votes
# Jelly 17 bytes

```
⁵Ḷx“ḶƇleJZaEC_‘µX

```

**TryItOnline!**

### How?

The distribution of the first step are \[1,1023\] with equal likelihood.
Applying the transformation instructed for each of those numbers produces a distribution of:
`{0: 178, 1: 144, 2: 108, 3: 101, 4: 74, 5: 90, 6: 97, 7: 69, 8: 67, 9: 95}`

```
⁵Ḷx“ḶƇleJZaEC_‘µX - Main link: (niladic)
⁵                 - literal 10
 Ḷ                - range -> [0,1,2,3,4,5,6,7,8,9]
   “ḶƇleJZaEC_‘   - code page indexes -> [178,144,108,101,74,90,97,69,67,95]
  x               - repeat - > [178 zeros, 144 ones, 108 twos, ...]
               µ  - monadic chain separation
                X - pick a random element

```

---
Tags: code-golf, random
---


title: C# is the Main problem

text:
# Question
Title: C# is the Main problem
This programming puzzle is inspired by another question which has been asked here yesterday but which was deleted by the author...

**The challenge:**

Create an executable binary (Windows .EXE or Linux binary) using Visual C# (or your favorite C# IDE) which prints the following text to the standard output:

```
Main() is the main method of C# programs!

```

... without using the 4 consecutive letters M-A-I-N appearing in any source file!

Notes:

* If your source code contains the text `remainder` (for example) it contains the 4 consecutive letters M-A-I-N, however if it contains `mxain` the 4 letters would not be consecutive any more so `mxain` would be allowed.
* You are not allowed to run any programs but the C# IDE nor change the settings of the C# IDE to run other programs (but the ones it would normally run such as the C# compiler).

Otherwise you could simply say: "I write a Pascal program using the C# IDE and invoke the Pascal compiler in the 'pre-build' steps of my C# project".

This would be too simple.
* Users of an IDE that can be extending using "plug-ins" (or similar) or that have built-in binary file editors (hex-editors) would have a **too** large advantage over users of other C# IDEs.

Therefore these featrues should also not be used.
* Using the other non-ASCII-Editors (such as the dialog window editor) is explicitly allowed!
* The user asking the original question proposed using the backslash in function names just like this: `static void M\u0061in()` Because this answer has already been read by other users it will not be accepted any more!
* A user asked if it would be allowed to simply type in an .EXE file into the source code editor and to save the file as ".exe" instead of ".cs". Answer: I doub't that this is possible because both valid Windows and Linux binaries contain NUL bytes. However if you find a valid binary that can be created this way you have a valid solution.

The name of this site is "Programming Puzzles **&** Code Golf" - this is a "Programming Puzzle", not "Code Golf": The challenge is to find a working solution before all other users, not to find a solution shorter than all other solutions.

Therefore the **first post describing a working solution wins**!

Good luck!

By the way: I have a solution working under Visual C# Express 2010.

# Answer
# C# Interactive Window

Open the C# Interactive Window (View \> Other Windows \> C# Interactive in Visual Studio 2015). I suppose not all IDEs will have this.

This approach executes C# in the Interactive Window in order to create a C# exe that prints the desired string without the author ever writing `main`. As a bonus, the exe's IL also does not contain `main`.

Run the following code in the Interactive Window

```
using System.Reflection;
using System.Reflection.Emit;
var appMeow = (dynamic)System.Type.GetType("System.AppDom" + "ain").GetProperty("CurrentDom" + "ain", BindingFlags.GetProperty | BindingFlags.Static | BindingFlags.Public).GetValue(null);
var asmName = new AssemblyName("MEOW");
var asmBuilder = appMeow.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndSave);
var module = asmBuilder.DefineDynamicModule("MEOW", "MEOW.exe");
var typeBuilder = module.DefineType("Meow", TypeAttributes.Public);
var entryPoint = typeBuilder.DefineMethod("EntryPoint", MethodAttributes.Static | MethodAttributes.Public);
var il = entryPoint.GetILGenerator();
il.Emit(OpCodes.Ldstr, "Meow() is the meow method of C# programs!");
il.Emit(OpCodes.Ldstr, "eow");
il.Emit(OpCodes.Ldstr, "ain");
il.EmitCall(OpCodes.Call, typeof(string).GetMethod("Replace", new[] { typeof(string), typeof(string) }), null);
il.EmitCall(OpCodes.Call, typeof(Console).GetMethod("Write", new[] { typeof(string) }), null);
il.Emit(OpCodes.Ret);
var type = typeBuilder.CreateType();
asmBuilder.SetEntryPoint(type.GetMethods()[0]);
asmBuilder.Save("MEOW.exe");

```

Use `Environmnent.CurrentDirectory` to see where the exe was created. Run it to observe the desired output.

Resulting IL:
> 6 votes

# Answer
# WPF Application

1. Create a new WPF application.
2. Replace all instances of `Main` with `Meow`
3. Rename `MainWindow.xaml` to `MeowWindow.xaml`. This will automatically rename `MainWindow.xaml.cs` to `MeowWindow.xaml.cs`.

4. In project properties, change the Output type to `Console Application` so the console is created.
5. Add console write for the desired output string in your `MeowWindow` constructor
6. Ctrl+Shift+F to confirm there's no `main` anywhere in the source directory.
7. F5 / compile and run.

### How it works

For WPF applications, Visual Studio generates `obj\Debug\App.g.cs` which contains the `Main` method. The generated `Main` creates an instance of your WPF app and starts it.
> 3 votes

# Answer
## Just as a reference

My idea was similar to "milk"'s second idea:

Find a way to let the IDE execute code and write an executable to the disk.

I explicitly mentioned Windows and Linux binaries because I thought about writing the binary .EXE file using `System.IO.File.WriteAllBytes()` so it would not neccessarily be a .NET EXE file.

My problem was that VS Express 2010 seems not to have an interactive console so I had to find a replacement for that - I found the following:

Create a DLL project with a dialog window and a custom control; compile the project and add the custom control to the dialog window. The dialog window editor will then call the code of the custom control - and in this code you may write the .EXE file to the disk...
> 0 votes

# Answer
I had to break the rules because I used vim with csc...

```
class C {
    static void \u004d\u0061\u0069\u006e(){
        Syste\u006d.Co\u006esole.Write("\u004d\u0061\u0069\u006e() is the \u006d\u0061\u0069\u006e \u006dethod of C# progra\u006ds!");
    }
}

```
> -5 votes

---
Tags: restricted-source, programming-puzzle, c#
---


title: Can you outgolf me? (Robbers section)

text:
# Question
Title: Can you outgolf me? (Robbers section)
# Robbers section

The cops section can be found here.

### Challenge

Your task is to outgolf the submissions of the cops *in the same language* and *the same version* (for example, **Python 3.5****Python 3.4**, so that is not allowed). A submission is outgolfed when the length in bytes is shorter than the original submission. **You only need to golf off at least 1 byte** in order to crack a submission. E.g. if the task was to perform **2 × *n***, and the submission was the following:

```
print(2*input())

```

You could outgolf the cop by doing the following:

```
print 2*input()

```

Or even this (since lambda's are allowed):

```
lambda x:2*x

```

Post this with the following header:

```
##{language name}, <s>{prev byte count}</s> {byte count}, {cop's submission + link}

```

For example:

> ## Python 2, ~~16~~ 12 bytes, Adnan (+ link to submission)
>
> ```
> lambda x:2*x
>
> ```
>
> Computes A005843, (offset = 0).

In that case, you have **cracked** the submission.

### Scoring

The person with who cracked the most submissions is the winner.

### Rules

* The crack submission must be in the same language as the cop submission.
* The same input should result into the same output (so a(2) = 4 should remain 4).
* For languages such as Python, you can import libraries that are standard included within the language. (So, no numpy/sympy etc.)
* Input and output are both in decimal (base 10).

---

> **Note**
>
> This challenge is finished. The winner of the *Robbers* section is **feersum**. The final scores for the CnR are shown below:
>
> * **feersum**: **16** cracks
> * **Dennis**: **12** cracks
> * **Leaky Nun**: **6** cracks
> * **Lynn**: **4** cracks
> * **miles**: **3** cracks
> * **Martin Ender**: **2** cracks
> * **Emigna**: **2** cracks
> * **jimmy23013**: **1** crack
> * **Sp3000**: **1** crack
> * **randomra**: **1** crack
> * **alephalpha**: **1** crack
> * **nimi**: **1** crack
> * **Destructible Watermelon**: **1** crack
> * **Dom Hastings**: **1** crack

# Answer
> 9 votes
## Cheddar, ~~7~~ 6 bytes, Downgoat

```
(<<)&1

```

This seems to work, but it's always possible that I don't understand the language correctly.

# Answer
> 14 votes
# Jelly, ~~5~~ 4 bytes, George V. Williams

```
RÆḊḞ

```

Try it here.

A hidden feature!

If I remembered correctly, `ÆḊ`(A) = sqrt(det(AAT)) is n! times the n dimensional Lebesgue measure of a simplex formed by n input point and the origin in m dimensional space. When n=1 it degenerate to the Euclidean distance. Not that weird after all...

# Answer
> 12 votes
## Hexagony, ~~91~~ 33 bytes, Blue

```
1""?{\>{+/</+'+./_'..@'~&/!}'+=($

```

Unfolded:

```
    1 " " ?
   { \ > { +
  / < / + ' +
 . / _ ' . . @
  ' ~ & / ! }
   ' + = ( $
    . . . .

```

Try it online!

Still looks somewhat golfable but I figured I'd post it before FryAmTheEggman beats me to it. ;)

### Explanation

Here are some colour-coded execution paths:

However, these are unnecessarily convoluted due to golfing. Here is the exact same code with a saner layout:

That's better. And finally, here is a memory diagram, where the red arrow indicates the initial position and orientation of the memory pointer (MP):

The gist is that I'm iteratively computing Fibonacci numbers on the three edges labelled **f(i)**, **f(i+1)** and **f(i+2)** while keeping track of the iterator on the edges **A**, **B** and **C**. While doing so the roles of these edges are swapped out cyclically after each iteration. Let's see how this happens...

The code starts on the grey path which does some initial setup. Note that **f(i)** already has its correct initial value of `0`.

```
1   Set edge f(i+1) to 1.
""  Move the MP to edge A.
?   Read input n into edge A.
)   Increment n.

```

Now the green path is the main loop. `_` and `>` are just mirrors.

```
(     Decrement n.
<     If the result is zero or less, continue on the red path, otherwise
      perform another iteration of the main loop.
{     Move the MP to edge f(i+2).
+     Add edges f(i) and f(i+1) into this edge, computing the next Fibonacci number.
'     Move the MP to the edge opposite A.
~     Multiply by -1 to ensure that it's non-positive (the edge may have a positive
      value after a few iterations).
&     Copy the current value of n from A.
'     Move back and to the right again.
+     Copy n by adding it to zero. Since we know that the other adjacent edge
      is always zero, we no longer need to use ~&.
'+'+  Repeat the process twice, moving n all the way from A to B.
=     Reverse the orientation of the MP so that it points at f(i) which now
      becomes f(i+2) for the next iteration.

```

This way, the MP moves around the inner triplet of edges, computing successive Fibonacci numbers until `n` reaches zero. Then finally the red path is executed:

```
{}    Move the MP to f(i).
!     Print it.
@     Terminate the program.

```

---

Diagrams generated with Timwi's HexagonyColorer and EsotericIDE.

# Answer
> 7 votes
# Haskell, ~~5~~ 4 bytes, xnor

```
(^)1

```

Simple currying.

# Answer
> 7 votes
## Stack Cats, ~~14~~ 13 bytes, feersum

```
^]T{_+:}_

```

with the `-nm` flags for +4 bytes. Try it online!

Okay, that loop was nuts. I tried several approaches, such as brute forcing over a reduced alphabet and brute forcing `3x+2` or `5x+4` and trying to extend it, but I never expected the solution to *actually* contain a loop.

The best way to see how this works is to add a `D` flag for debugging (so run with `-nmD`) and turn debug on for the above TIO link. A `{}` loop remembers the top of stack at the beginning of the loop, and exits when the top of stack is that value again. The interior of the loop does some fun subtracting and cycling of the top three elements of the stack, which is how the loop gets to run for so many iterations.

# Answer
> 6 votes
# Sesos, ~~14~~ 11 bytes, Leaky Nun

Computes **n2**. Try it here.

Hex dump:

```
0000000: 16c0f7 959d9b 26e83e ce3d                         ......&.>.=

```

From assembly:

```
set numin
set numout
get
jmp
  jmp, sub 1, fwd 1, add 1, fwd 1, add 2, rwd 2, jnz
  fwd 2, sub 1
  rwd 1, sub 1
  jmp, sub 1, rwd 1, add 1, fwd 1, jnz
  rwd 1
jnz
fwd 2
put

```

# Answer
> 6 votes
## Woefully, ~~776~~ 759 bytes, Destructible Watermelon

```
| |||||||| | |
|| |||||| |
||| |||| |
|||| || |
||||| || |
|||| |||| |
||| |||||| |
|| |||||||| |
| |||||||||| |
|| |||||||| |
||| ||||||| |
||||||||||| |
||||||||||| |
||||||||||| |
||||||||||| |
|||||||||| |
||||||||| |
||||||||| |
||||||||| |
||||||||| |
|||||||||| |
||||||||||| |
|||||||||||| |
||||||||||| |
|||||||||| |
||||||||| |
|||||||| |
||||||| |
|||||| |
||||| |
|||| |
||| |
|| |
| |
| |
| |
|| |
|| |
|| |
|| |
|| |
| |
| |
| |
|| |
||| |
|||| |
||||| |
|||||| |
||||||| |
|||||| |
||||||| |
|||||||| |
||||||||| |
|||||||||| |
||||||||||| |
|||||||||||| |
||||||||||| |
|||||||||| |
||||||||| |
|||||||| |
||||||| |
|||||| |
||||| |
|||| |
||| |
|| |
| |
| |
| |
| |
|| |
| |
|| |
||| |
||| |
|||| |
||| |
|| |
| |
| |
| |
|| |
|| |
|| |
|| |

```

I tried to read the source code for this language but it was too confusing. For one thing, `ip[1]` is a line number while `ip[0]` is the column number, while the `cp` coordinates are used the other way around. Yet, sometimes the value of `cp` is assigned to `ip`. I gave up on trying to understand what the program is doing and found a way to encode the identical sequence of instructions using fewer bars.

# Answer
> 5 votes
# Brachylog, ~~27~~ 21 bytes, Fatalize

```
yrb:1a:+a:[1]c*.
:2/.

```

Try it online!

# Answer
> 5 votes
# J, ~~17~~ 12 bytes, miles

```
+/@(]!2*-)i:

```

Pretty much the same as the original just more golfed. :)

`i:` having `+1` range compared to `i.` is useful (and weird). If you use `i.` here `n=0` will be incorrect but luckily `i:` solves that.

Try it online here.

# Answer
> 5 votes
# M, ~~10~~ 6 bytes, Dennis

```
R×\³¡Ṫ

```

Given *n*, it computes the *nth*-level factorial of *n*. This was a fun exercise!

The code is capable of running as Jelly so you can Try it online.

## Explanation

```
R×\³¡Ṫ  Input: n
R       Create the range [1, 2, ..., n]
   ³¡   Repeat n times starting with that range
 ×\       Find the cumulative products
     Ṫ  Get the last value in the list
        Return implicitly

```

# Answer
> 5 votes
# Snowman, ~~50~~ 44 bytes, Doorknob

```
((}#2nMNdE0nR1`wRaC2aGaZ::nM;aF;aM:`nS;aF*))

```

Try it online!

# Answer
> 5 votes
## Haskell, ~~15~~ 14 bytes, xnor

```
until odd succ

```

I spent a fruitless couple of hours learning to decipher "pointless" syntax... `until` I found this instead.

Or for a less mellifluous 13 bytes, `until odd(+1)`.

# Answer
> 4 votes
## Python 2, ~~43~~ 40, xsot

```
g=lambda n:n<2or-~sum(map(g,range(n)))/3

```

# Answer
> 4 votes
# Pyke, ~~11~~ 9 bytes, muddyfish

```
hVoeX*oe+

```

Try it here!

### How it works

```
          Implicit input: n (accumulator), n (iterations)
h         Increment the number of iterations.
 V        Do the following n + 1 times.
  o         Iterator. Pushes its value (initially 0) and increments it.
   e        Perform integer division by 2.
            This pushes 0 the first time, then 1, then 2, etc.
    X       Square the result.
     *      Multiply the accumulator and the result.
      oe    As before.
        +   Add the result to the accumulator.
            This sets the accumulator to a(0) = 0 in the first iteration and
            applies the recursive formula in all subsequent ones.

```

# Answer
> 4 votes
## 05AB1E, ~~7~~ 4, Emigna

```
LnOx

```

> From the formula for the sum of squares of positive integers 1^2 + 2^2 + 3^2 + ... + n^2 = n(n+1)(2\*n+1)/6, if we multiply both sides by 2 we get Sum\_{k=0..n} 2\*k^2 = n(n+1)(2\*n+1)/3, which is an alternative formula for this sequence. - Mike Warburton (mikewarb(AT)gmail.com), Sep 08 2007

# Answer
> 4 votes
## Jelly, ~~22~~ 21 bytes, Dennis

```
_²×c×Ḥc¥@÷⁸÷’{S
‘µR+ç

```

I spent several hours reading Jelly source code for the last one, so I might as well put this "skill" to use. I hope @Dennis will share with us his mathematical discoveries allowing a shorter formula (assuming there is something and not only weird Jelly tricks!).

# Answer
> 4 votes
# J, ~~20~~ 19 bytes, miles

```
[:+/2^~+/@(!|.)\@i.

```

This computes the product as a sum of squared Fibonacci numbers, which are calculated as a sum of binomial coefficients.

Thankfully, @miles himself posted the code to generate Fibonacci numbers in this comment.

# Answer
> 4 votes
# *Acc!!*, ~~526~~ 525 bytes, DLosc

```
N
Count x while _%60-46 {
(_+_%60*5-288)*10+N
}
_/60
Count i while _/27^i {
_+27^i*(_/27^i*26-18)
}
_*3+93
Count i while _/27^i/27%3 {
_-i%2*2+1
Count j while _/3^(3*j+2-i%2)%3 {
_+3^(1+i%2)
Count k while _/3^(3*k+1+i%2)%3-1 {
_+3^(3*k+1+i%2)*26
}
}
}
Count i while _/27^i/3 {
_-_/27^i/3%27*27^i*3+_/3^(3*i+1+_%3)%3*3
}
_/3
Count i while _/100^i {
_*10-(_%100^i)*9
}
Count i while _/100^i/10 {
_+_/100^i/10%10
Count j while i+1-j {
_+(_%10-_/100^(j+1)%10)*(100^(j+1)-1)
}
}
_/100
Count j while _/100^j {
Write _/100^j%10+48
}

```

I have no idea how this works, but I was able to spot a tiny improvement.

```
24c24
< _+_/100^i*100^i*9
---
> _*10-(_%100^i)*9

```

# Answer
> 4 votes
## Haskell, 10 bytes, xnor

```
gcd=<<(2^)

```

Usage example: `map ( gcd=<<(2^) ) [1..17]` -\> `[1,2,1,4,1,2,1,8,1,2,1,4,1,2,1,16,1]`.

How it works: From the oeis page we see that `a(n) = gcd(2^n, n)` or written in Haskell syntax: `a n = gcd (2^n) n`. Functions with the pattern `f x = g (h x) x` can be turned to point-free via the function `=<<`: `f = g =<< h`, hence `gcd=<<(2^)` which translates back to `gcd (2^x) x`.

# Answer
> 3 votes
# Sesos, ~~14~~ 9 bytes, Leaky Nun

Computes **n mod 16**. Try it here.

Hex:

```
0000000: 17f84a 750e4a 7d9d0f                              ..Ju.J}..

```

Assembly:

```
set numin
set numout
set mask
get
jmp, sub 1, fwd 1, add 16, rwd 1, jnz
fwd 1
jmp, sub 16, fwd 1, add 1, rwd 1, jnz
fwd 1
put

```

# Answer
> 3 votes
# Python, ~~39~~ 17 bytes, Destructible Watermelon

```
lambda n:n*-~n>>1

```

# Answer
> 3 votes
# 05AB1E, ~~9~~ 4 bytes, Emigna

```
>n4÷

```

Try it online!

Computes this function instead:

# Answer
> 3 votes
## Hexagony, ~~7~~ 6 bytes, Adnan

```
?!/$(@

```

Unfolded:

```
 ? !
/ $ (
 @ .

```

Try it online!

Same idea, slightly different layout.

# Answer
> 3 votes
## MATL, ~~11~~ 10 bytes, Luis Mendo

```
YftdAwg_p*

```

Instead of doing -1^length(array) it converts the elements to Boolean values (which are always 1), negates them, and takes the product of the elements.

# Answer
> 3 votes
# Jelly, ~~11~~ 10, Dennis

```
Ḥ’_Rc’*@RP

```

Vectorized version of same approach.

Try it online!

# Answer
> 3 votes
# 05AB1E, ~~10~~ 8 bytes, Adnan

```
µNÂÂQ>i¼

```

Try it online.

# Answer
> 3 votes
# Jelly, ~~9~~ 8 bytes, Dennis

```
œċr0$L€Ḅ

```

Sorry! I wasn't able to find your intended solution.

This relies on the fact that `C(n+k-1, k)` is the number of ways to choose `k` values from `n` with replacement.

Note: This is inefficient since it generates the possible sets in order to count them, so try to avoid using large values of *n* online.

Try it online or Verify up to *n*.

I later found another 8 byte version that is efficient enough to compute *n* = 1000. This computes the values using the binomial coefficient and avoids generating the lists.

```
Ḷ+c’Ṛ;1Ḅ

```

Try it online or Verify up to *n*.

## Explanation

```
œċr0$L€Ḅ  Input: n
  r0$     Create a range [n, n-1, ..., 0]
œċ        Create all combinations with replacement for
          (n, n), (n, n-1), ..., (n, 0)
     L€   Find the length of each
       Ḅ  Convert it from binary to decimal and return

Ḷ+c’Ṛ;1Ḅ  Input: n
Ḷ         Creates the range [0, 1, ..., n-1]
 +        Add n to each in that range
   ’      Get n-1
  c       Compute the binomial coefficients between each
    Ṛ     Reverse the values
     ;1   Append 1 to it
       Ḅ  Convert it from binary to decimal and return

```

# Answer
> 3 votes
# Brachylog, ~~11~~ 10 bytes, Fatalize

```
yb:AcLrLc.

```

Try it online!

## Explanation

Brachylog is a Prolog-derived languages, whose greatest ability is to prove things.

Here, we prove these statements:

```
yb:AcLrLc.
yb:AcL       Inclusive range from 1 to input, concatenated with A, gives L
     LrL     L reversed is still L
       Lc.   L concatenated is output

```

# Answer
> 3 votes
## M, ~~9~~ 8 bytes, Dennis

```
Ḥrc’ḊḄḤ‘

```

# Answer
> 3 votes
## QBasic, ~~30~~ 29 bytes, DLosc

```
INPUT n:?(n MOD 2)*(n+.5)+n/2

```

# Answer
> 3 votes
## Pip, ~~24~~ 22 bytes, DLosc

```
Y5T#y>aY(A_My)JkyA(ya)

```

# Answer
> 3 votes
## J, ~~12~~ 11 bytes, miles

```
##.>:@I.@#:

```

`+/` for summing an array behaves poorly with regards to vectorization, so I tried to use base 1 instead. `#` happened to work for a 1-byte verb that results in 1 when called on a scalar.

# Answer
> 2 votes
## Python 3.5, ~~38~~ 36 bytes, R. Kap

```
G=lambda n:+(n<1)or(2*n-1)**2*G(n-1)

```

Even if you don't accept `True` as 1, this is good enough.

# Answer
> 2 votes
# J, ~~9~~ 7 bytes, Leaky Nun

```
2&o.t.]

```

This is a monadic verb; it computes the **y**th term of the Taylor series of the *cosine* function (`2&o.`).

### Example run

```
   f =: 2&o.t.]
   f each 0 1 2 3 4 5 6 7
┌─┬─┬──┬─┬─┬─┬──┬─┐
│1│0│_1│0│1│0│_1│0│
└─┴─┴──┴─┴─┴─┴──┴─┘

```

# Answer
> 2 votes
# J, ~~10~~ 9 bytes, Leaky Nun

```
-:*1-~3*]

```

Just shifted the operators around.

# Answer
> 2 votes
# Java, ~~53~~ 51 bytes, JollyJoker

```
int f(int n){return n<2?3-3*n:n<3?2:f(n-2)+f(n-3);}

```

Combines the first two *if* statements into `3-3*n` for *n* less than 2.

# Answer
> 2 votes
## Retina, ~~28~~ 27 bytes, Martin Ender

```
.+
$*
((^.?|\3)(^|\1)){99}$

```

Where it says `{99}` I wanted to use `+`, but that mysteriously causes the match to fail.

The regex matches strings which have a length that is a sum of a prefix of the Fibonacci numbers. The main group matches lengths starting with 1, 2, 3, ..., which skips one of the initial 1s, so I tried to improve it by getting it to match length 1 twice at the beginning, so that it was not necessary to have a special case.

# Answer
> 2 votes
## 05AB1E, ~~13~~ 12 bytes, Adnan

```
µ•vÉ•DNìÙ{Q½

```

Try it online

# Answer
> 2 votes
## Python 3, ~~77~~ 40 bytes, Joe

```
g=lambda n,c=1:+(n==0 or n>0<g(n-c,c+1))

```

# Answer
> 2 votes
# MarioLANG, ~~87~~ 86 bytes, Business Cat

Don't know how I did it, but here it is I think

```
;
)-)+(< >>(
-)===" ""====
>>+([!)( >-(
"====#[(("==+[
!-) - <!!![)<<)
#======###====:

```

# Answer
> 2 votes
## CoffeeScript, ~~83~~ 50 bytes, DerpfacePython

```
s=(n)->0|r<0||Array(0|(n/9)+2).join ((n-1)%9+1)+''

```

Tested via http://coffeescript.org/.

# Answer
> 2 votes
# Python, ~~69~~ 32 bytes, HiggsBot

```
f=lambda n:0**n or(4*n-2)*f(n-1)

```

Test it on Ideone.

*Two bytes saved by @xnor. Thanks!* Two more could be saved by returning `True` instead of `1`.

# Answer
> 2 votes
## 05AB1E, ~~7~~ 6 bytes, Adnan

```
!¹L!/O

```

or

```
!žr<*ï

```

Note that both of these return 1 for 0, but so did the cop program.

# Answer
> 2 votes
# *Acc!!*, ~~522~~ 514 bytes, DLosc

```
N
Count x while _%60-46 {
(_+_%60*5-288)*10+N
}
_/60*2
Count i while _/27^i {
_+(_/27^i*26-18)*27^i
}
_*3+93
Count i while _/27^i/27%3 {
_-i%2*2+1
Count j while _/3^(3*j+2-i%2)%3 {
_+3+i%2*6
Count k while _/3^(3*k+1+i%2)%3-1 {
_+27^k*3^(i%2)*78
}
}
}
Count i while _/27^i/3 {
_-_/27^i/3%27*27^i*3+_/3^(3*i+1+_%3)%3*3
}
_/3
Count i while _/100^i {
_*10-_%100^i*9
}
Count i while _/100^i/10 {
_+_/100^i/10%10
Count j while i+2-j {
_+(_%10-_/100^j%10)*(100^j-1)
}
}
_/100
Count j while _/100^j {
Write _/100^j%10+48
}

```

Not so tiny improvement this time, but I still have no idea what I'm doing.

```
28,29c28,29
< Count j while i+1-j {
< _+(_%10-_/100^(j+1)%10)*(100^(j+1)-1)
---
> Count j while i+2-j {
> _+(_%10-_/100^j%10)*(100^j-1)

```

Since `(100^j-1)` is zero when **j = 0**, we can loop over the range **\[0, ..., i + 2)** instead of looping over **\[0, ..., i + 1)** and incrementing **j**. This saves eight bytes.

# Answer
> 2 votes
# Python, ~~46~~ 45 bytes, Sp3000

```
f=lambda n,k=1:n and-~f(n-(k+(k&-k)&k>0),k+1)

```

Test it on Ideone.

# Answer
> 2 votes
# Excel, ~~16~~ 12 bytes, Anastasiya-Romanova 秀

```
=FACT(n)*2^n

```

I don't actually have Excel, but from what I read online, this should work.

# Answer
> 2 votes
## M, ~~18~~ 17 bytes, Dennis

Tragically, Dennis has missed a trivial modification this time. Only the first line is different.

```
Ḥrc
‘Ḥc0r$×Ç:‘+\S

```

# Answer
> 2 votes
# *Acc!!*, ~~512~~ 511 bytes, DLosc

```
N
Count x while _%60-46 {
(_+_%60*5-288)*10+N
}
_/30
Count i while _/27^i {
_+(_/27^i*26-18)*27^i
}
_*3+93
Count i while _/27^i/27%3 {
_-i%2*2+1
Count j while _/3^(3*j+2-i%2)%3 {
_+3+i%2*6
Count k while _/3^(3*k+1+i%2)%3-1 {
_+3^(3*k+i%2)*78
}
}
}
Count i while _/27^i/3 {
_-_/27^i/3%27*27^i*3+_/3^(3*i+1+_%3)%3*3
}
_/3
Count i while _/100^i {
_*10-_%100^i*9
}
Count i while _/100^i/10 {
_+_/100^i/10%10
Count j while i+2-j {
_+(_%10-_/100^j%10)*(100^j-1)
}
}
_/100
Count j while _/100^j {
Write _/100^j%10+48
}

```

This is the improvement.

```
15c15
< _+27^k*3^(i%2)*78
---
> _+3^(3*k+i%2)*78

```

# Answer
> 2 votes
## J, ~~18~~ 13 bytes, miles

```
(2&-%-.-*:)t.

```

I checked the ~~shortest~~ most popular J answer for Fibonacci numbers: a generating function. Unsurprisingly, the same approach is also good for Lucas numbers.

# Answer
> 1 votes
## JavaScript(ES6), ~~77~~ 76, user81655

```
n=>eval("for(i=0;n;n-=!a)[...s=a=++i+''].map(d=>a-=Math.pow(d,s.length));i")

```

Just a 1-byte peephole golf.

# Answer
> 1 votes
# Actually, ~~28~~ 11 bytes, Mego

```
19,`;τ(+`nX

```

Try it online!

### How it works

This uses the recursive definition from A048696: **a(0) = 1, a(1) = 9, a(n) = 2a(n-1) + a(n-2)**.

```
19           Push 1 and 9 on the stack.
  ,          Read n from STDIN and push it on the stack.
   `    `n   Do the following n times:
    ;          Push a copy of the topmost integer.
     τ         Multiply it by 2.
      (        Rotate the bottom-most integer on top of the stack.
       +       Add the two topmost integers.
             Each iteration turns the stack [a(k-2) a(k-1)] into [a(k-1) a(k)].
             After n iterations, we are left with [a(n) a(n+1)].
          X  Discard a(n+1) from the stack.

```

# Answer
> 1 votes
# *Acc!!*, ~~523~~ 521 bytes, DLosc

```
N
Count x while _%60-46 {
(_+_%60*5-288)*10+N
}
_/60
Count i while _/27^i {
_+27^i*(_/27^i*26-18)
}
_*3+93
Count i while _/27^i/27%3 {
_-i%2*2+1
Count j while _/3^(3*j+2-i%2)%3 {
_+3+i%2*6
Count k while _/3^(3*k+1+i%2)%3-1 {
_+3^(3*k+1+i%2)*26
}
}
}
Count i while _/27^i/3 {
_-_/27^i/3%27*27^i*3+_/3^(3*i+1+_%3)%3*3
}
_/3
Count i while _/100^i {
_*10-_%100^i*9
}
Count i while _/100^i/10 {
_+_/100^i/10%10
Count j while i+1-j {
_+(_%10-_/100^(j+1)%10)*(100^(j+1)-1)
}
}
_/100
Count j while _/100^j {
Write _/100^j%10+48
}

```

I have no idea how this works, but I was able to spot a tiny improvement.

```
13c13
< _+3^(1+i%2)
---
> _+3+i%2*6

```

---
Tags: code-golf, number, sequence, cops-and-robbers
---


title: Balanced triplet brackets

text:
# Question
Title: Balanced triplet brackets
A "triplet bracket" (that I made up for this challenge) is one of the following:

```
(...+...)
[...:...]
{...|...}
<...-...>

```

A balanced triplet bracket string (BTBS for short) is either an empty string, two BTBSes concatenated, or one of the above triplet brackets with each `...` replaced with a BTBS.

Your task is to write a program or function that checks whether a string that consists of only `(+)[:]{|}<->` is balanced. Shortest code wins.

## Examples

Your program should return truthy for the following strings:

```
(+)(+)(+)
[[[:]:]:(+(+))]{<->|<(+)->[:]}(+)
<<<<<<<<<<<<->->->->->->->->->->->->
{|(+[:<-{|(+[:<->])}>])}
[[[:]:[:]]:[[:]:[:]]]
{[:](+)|<->{|}}[(+)<->:{|}(+)]

```

Your program should return falsy for the following strings:

```
:[
<|>
(+(+)
[:][:](+[[:]):]
{|{|{|(+{|{|{|}}}}}+)}[:]{|}
{{||}}
<<->-<->-<->>
[(+):((+)+)+(+(+))]
<<<<<->->->->->->

```

# Answer
> 1 votes
# Japt, 25 bytes

```
!Ue"%(%+%)|%[:]|\{%|}|<->

```

**Test it online!**

`e` on strings is a recursive-replace function. The second parameter defaults to the empty string, which means this recursively removes matches of the Japt regex `"%(%+%)|%[:]|\{%|}|<->"` (in regular terms, `/\(\+\)|\[:]|{\|}|<->/`). This returns an empty string for balanced triplet strings and a non-empty string for non-balanced, so the correct return value is the logical NOT of this.

# Answer
> 14 votes
## JavaScript (ES6), ~~77~~ ~~58~~ ~~57~~ 56 bytes

```
f=s=>s==(s=s.replace(/\(\+\)|\[:]|{\|}|<->/,''))?!s:f(s)

```

### Test cases

```
f=s=>s==(s=s.replace(/\(\+\)|\[:]|{\|}|<->/,''))?!s:f(s)

console.log("Testing truthy values");
console.log(f("(+)(+)(+)"));
console.log(f("[[[:]:]:(+(+))]{<->|<(+)->[:]}(+)"));
console.log(f("<<<<<<<<<<<<->->->->->->->->->->->->"));
console.log(f("{|(+[:<-{|(+[:<->])}>])}"));
console.log(f("[[[:]:[:]]:[[:]:[:]]]"));
console.log(f("{[:](+)|<->{|}}[(+)<->:{|}(+)]"));

console.log("Testing falsy values");
console.log(f(":["));
console.log(f("<|>"));
console.log(f("(+(+)"));
console.log(f("[:][:](+[[:]):]"));
console.log(f("{|{|{|(+{|{|{|}}}}}+)}[:]{|}"));
console.log(f("{{||}}"));
console.log(f("<<->-<->-<->>"));
console.log(f("[(+):((+)+)+(+(+))]"));
console.log(f("<<<<<->->->->->->"));
```

# Answer
> 5 votes
# sed, ~~28~~ 27 bytes

```
:
s#(+)\|\[:]\|{|}\|<->##
t

```

*sed* doesn't have a concept of truthy/falsy, so I'm considering an empty string truthy and a non-empty string falsy. This checks out if we consider the conditional `/^$/`.

*Thanks to @Neil for golfing off 1 byte!*

Try it online!

# Answer
> 4 votes
## Python, 77 bytes

```
lambda s:eval("s"+".replace('%s','')"*4%('(+)','[:]','{|}','<->')*len(s))==''

```

Uses Arnauld's replacement idea. Generates and evaluates a long string like

```
s.replace('(+)','').replace('[:]','').replace('{|}','').replace('<->','').replace('(+)','').replace('[:]','').replace('{|}','').replace('<->','')

```

to cycle between replacing all the bracket types. Then, checks if the result is the empty string.

# Answer
> 3 votes
# Mathematica, 55 bytes

```
StringDelete["(+)"|"[:]"|"{|}"|"<->"]~FixedPoint~#==""&

```

Anonymous function. Takes a string as input and returns `True` or `False` as output. Uses the standard method for doing this.

# Answer
> 2 votes
## Grime, 39 bytes

```
e`\(_\+_\)|\[_\:_\]|\{_\|_\}|\<_\-_\>v*

```

Try it online! Sadly, the TIO version runs out of memory on most of the test cases.

## Explanation

Nothing too fancy here. `_` is shorthand for the entire pattern, and `v*` is the same as `*`, but with lower precedence.

```
e`                                       Match entire input against this pattern:
  \(_\+_\)                               '(', match of _, '+', match of _, ')'
          |                              or
           \[_\:_\]|\{_\|_\}|\<_\-_\>    same for the other bracket types
                                     v*  repeated 0-∞ times

```

# Answer
> 2 votes
# J, 48 bytes

```
a:=([:delstring&.>/'(+)';'[:]';'{|}';'<->';])^:_

```

Similar to the others, this is also based on Arnauld's method.

## Usage

```
   f =: a:=([:delstring&.>/'(+)';'[:]';'{|}';'<->';])^:_
   f '(+)(+)(+)'
1
   f '[[[:]:]:(+(+))]{<->|<(+)->[:]}(+)'
1
   f '<<<<<<<<<<<<->->->->->->->->->->->->'
1
   f '<|>'
0
   f '[:][:](+[[:]):]'
0
   f '{|{|{|(+{|{|{|}}}}}+)}[:]{|}'
0

```

## Explanation

```
a:=([:delstring&.>/'(+)';'[:]';'{|}';'<->';])^:_  Input: string S
   (                                        )^:_  Repeat until convergence
                                         ]          Get S
                 '(+)';'[:]';'{|}';'<->';           Append to ['(+)', '[:]', '{|}', '<->']
    [:delstring&.>/                                 Reduce right-to-left by deleting
                                                    occurrences of each string on the
                                                    left from the right
                                                    Return the final string as the new S
a:=                                               Test if the final value of S is empty

```

# Answer
> 1 votes
## Pip, 26 bytes

```
L#aaR:"(+)[:]{|}<->"<>3x!a

```

Try it online!

Loops len(a) times, replacing all occurrences of empty triplet brackets (`"(+)[:]{|}<->"<>3`, where `<>` is the "group" operator, =\> `["(+)"; "[:]"; "{|}"; "<->"]`) with empty string (`x`). This many iterations is overkill, but it will always be more than enough to completely reduce all properly formed triplet brackets to nothing. After the loop completes, outputs `!a`: `0` if `a` is truthy (still has some characters), `1` if `a` is falsey (empty).

# Answer
> 0 votes
# Scala, 96 bytes

```
def&(s:String):Any={val t=s.replaceAll(raw"\(\+\)|\[:]|\{\|}|<->","")
if(t==s)t.size<1 else&(t)}

```

This is basically the same idea as the other answers, but with some scala boilerplate.

### without stealing ideas from others (188 bytes):

```
import scala.util.parsing.combinator._
val a = new RegexParsers{def r:Parser[_]="("~r~"+"~r~")"|"["~r~":"~r~"]"|"{"~r~"|"~r~"}"|"<"~r~"-"~r~">"|""
def!(s:String)= !parseAll(r,s).isEmpty}!_

```

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


title: Output the ALONED numbers

text:
# Question
Title: Output the ALONED numbers
Consider the natural sequence up-to 6 *(disregard 1)*:

```
2,3,4,5,6

```

We start scanning from the left (in this case from 2), search for a number divisible by 2 (here 4) and then remove both the numbers from the list (here 2 & 4), such that the list reduces to:

```
3,5,6

```

We continue the same process, here leftmost is 3, so we search for number divisible by 3. 6 is surely that number and thus 3 and 6 are removed,

```
5

```

Now, no further such searches can be made Thus, this becomes the list of ALONED numbers for n=6.

**OBJECTIVE**

1. Given a number n greater than 1, print all the corresponding aloned numbers.

**INPUT**

```
2
6
15
20
22

```

**OUTPUT**

```
2
5
8,9,11,12,13,15
11,12,13,15,17,19,20
12,13,15,17,19,20,21

```

**YET ANOTHER WORKED OUT EXAMPLE**

*For n= 22*

```
=>2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22
=>3,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22 (remove 2 & 4)
=>5,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22 (remove 3 & 6)
=>7,8,9,11,12,13,14,15,16,17,18,19,20,21,22 (remove 5 & 10)
=>8,9,11,12,13,15,16,17,18,19,20,21,22 (remove 7 & 14)
=>9,11,12,13,15,17,18,19,20,21,22 (remove 8 & 16)
=>11,12,13,15,17,19,20,21,22 (remove 9 & 18)
=>12,13,15,17,19,20,21 (remove 11 & 22) (OUTPUT)

```

***This is , so the shortest code in bytes wins.***

# Answer
# 05AB1E, ~~22~~ ~~17~~ ~~15~~ 14 bytes

```
L¦¹F¬·©¹›_i¦®K

```

Try it online!

**Explanation**

```
L¦               # push the list [2..input]
  ¹F             # input nr of times do:
          i      # if
    ¬·©          # the first element in the list * 2
       ¹›_       # is less than or equal to input
                 # then
           ¦     # remove first element of list
            ®K   # and remove it's multiple

```
> 5 votes

# Answer
## Python 2, ~~90~~ ~~79~~ 73 bytes

<sup>*-6 bytes thanks to xnor*</sup>

```
L=range(2,input()+1)
while L[0]*2<=L[-1]:L.remove(L[0]*2);L=L[1:]
print L

```

Takes the input number on stdin. Ideone it!

### Explanation

We construct the initial list from the input number and store it in `L`. Next, loop while the last number is greater than or equal to 2 times the first number and remove 2 times the first number from the list. This will always be the next number divisible by `L[0]`. `L=L[1:]` takes off the first number as well. When the condition is no longer true, no further removals can be made, and the list is printed.
> 6 votes

# Answer
## Python, 61 bytes

```
lambda n:[i+1for i in range(n/2,n)if-~i&~i&4**n/3>>(-~i&i<1)]

```

It's a bit easier to understand this less golfed code:

```
lambda n:[i for i in range(n/2+1,n+1)if((i&-i)**.5%1>0)^(i&~-i>0)]

```

This uses a direct characterization of aloned numbers:

> A number `i` is *aloned* if, when decomposed as `i = a * 2^b` with `b` odd, either
>
> * `a>1` and `b` is even, or
> * `a==1` and `b` is odd
>
> The aloned numbers for `n` are all aloned numbers `i` in the interval `n/2 + 1 <= i <= n`.

Why does this hold? When doing the process for `n`, say we remove an odd number `a` in the lower half (`1` to `n/2`). Then, `2*a` is removed no matter where in the list it is. So, `4*a` remains (if it existed). But if it's in the lower half, the deletion process will get to it and remove both `4*a` and `8*a`. So, we see that an upper-half number gets removed if it's of form `2*a`, `8*a` ... with odd `c`, but stays if it has form `a`, `4*a`, `8*a`, ...

The exception is for `a=1`, which does not start in the list and so is not removed. As a result, the removal chain starts with `a=2`, and the rule for powers of 2 is flipped.

```
lambda n:[i for i in range(n/2+1,n+1)if((i&-i)**.5%1>0)^(i&~-i>0)]

```

In the code above, `(i&-i)**.5%1>0` checks whether `i` lacks the form `i = a * 2^b` with `b` odd, by the bit-trick to extract the greatest power-of-two factor, `2^b = i&-i`, then checking if the result is not a perfect square. Then, `i&~-i>0` is another bit trick to check if `i` is not a perfect power of 2. These conditions are then xor'ed.

There's some more improvements here

```
lambda n:[i+1for i in range(n/2,n)if-~i&~i&4**n/3>>(-~i&i<1)]

```

First, we shift the range 1 index down to to shorten to `range(n/2,n)` from `range(n/2+1,n+1)`, compensating by replacing all `i` with `i+1` (or `~-i`).

Whether a power of 2 is number is a power of `4` (2^`b` with `b` even) can be checked by and-ing with `2**c/3` for some large `c`. This is because `2**c/3` has binary representation `10101...101` with ones in the even-positioned bits. Using `c=2*n` suffices. To negate result when `i` is a power of 2, we halve this number is that case, putting `1`'s in the odd positions instead.
> 5 votes

# Answer
# Groovy, ~~65~~ 58 Bytes

Algorithm idea from DSLoc, who noticed you need only to remove the doubles.

```
{n->a=(2..n);(2..(n/2)).each{if(it in a){a-=[it,it*2]}};a}

```

Here's a breakdown:

```
{
    n->
    a=(2..n);             // Store [2,...,n].
    (2..(n/2)).each {     // From 2 to half of n.
        if(it in a){      // If it's there...
            a-=[it,it*2]  // Remove it and its double, store in a.
        }
    };
    a                     // Return a.
}

```
> 4 votes

# Answer
# Perl, ~~53~~ ~~49~~ ~~45~~ 44 bytes

Includes +1 for `-n`

Give input number on STDIN:

```
perl -M5.010 aloned.pl <<< 22

```

`aloned.pl`:

```
#!/usr/bin/perl -n
@F[$F[$_*2]/2,$_*2,1]=0,$_&&say for@F=0..$_

```

Directly checking the possible numbers is longer:

```
map{/$/;$_/=4until$_%4;$_%2^$_<3&&say$`}$_/2+1..$_

```

This checks all numbers in the upper half range. Keep numbers that have an even number of 2 as prime factors except if the number is a power of 2 then odd (because 1 is left out of the original series). This method should however work well for other languages.
> 4 votes

# Answer
## Haskell, ~~71~~ ~~69~~ ~~62~~ 56 bytes

```
g(a:b)|s<-filter(/=2*a)b=[a|s==b]++g s
g x=x
q n=g[2..n]

```

Usage example: `q 22` -\> `[12,13,15,17,19,20,21]`.

If there's a multiple of the first number `a`, then it's `2*a`. Keep `a` if `2*a` is not in the list and append a recursive call with `a` and `2*a` removed from the list.
> 3 votes

# Answer
# MATL, 18 bytes

*Borrowed the "multiply by 2" idea from @Emigna's 05AB1E answer*.

```
q:Qt"t1)tEhym?6MX-

```

Try it online!

### Explanation

```
q:Q        % Input n implicitly. Push [2 3 ... n]
t"         % Duplicate. For each: repeat n-1 times
  t1)      %   Duplicate. Get first element from current array, say k
  tEh      %   Append twice that value: gives array [k 2*k]
  y        %   Push another copy of current array
  m?       %   If both k and 2*k are members of the array
    6M     %     Push [k 2*k] again
     X-    %     Set difference: remove from current array
           %   End if implicitly
           % End for each implicitly
           % Display implicitly

```
> 3 votes

# Answer
# Pyth - 19 bytes

Will *definitely* be refactoring.

```
u?Kf!%ThGtG-tGhKGtS

```

Test Suite.
> 2 votes

# Answer
## Ruby, 124

Comparing scores to other answers, this is obviously the wrong approach:

```
->n{a={};b=[*2..n].each{|k|a[k]=7}
b.map{|i|g=b.select{|x|a[i]&&a[x]&&x%i<1}
a[g[0]]=a[g[1]]=!g[1]}
a.select{|k,v|v&k}.keys}

```

The somewhat clever bit here is `a[g[0]]=a[g[1]]=!g[1]` which sets the hash's values to true/false as necessary.
> 2 votes

# Answer
# PHP, 98 Bytes

```
foreach($r=range(2,$argv[1])as$v)$a=&$r[$v-2]&&$b=&$r[$v*2-2]?$b=$a="":(!$a?:print$x?",$a":$x=$a);

```

8 Bytes save by @Titus Thank You

If a trailing comma is allowed then it can be shorten 9 Bytes `(!$a?:print"$a,");` instead of `(!$a?:print$x?",$a":$x=$a);`
> 2 votes

# Answer
## Javascript, 149 bytes

```
function a(n){o=Array.from(Array((n+1)).keys());o.shift();o.shift();for(i=1;i<o.length;i++){if(o[i]%o[0]==0){o.splice(i,1);o.shift();i=0;}}return o;}

```

Here's a working example. All the HTML and the wrapper() function is just so it's actually interactive.

```
<!DOCTYPE html>
<html lang="en">
  <head>
<meta charset="UTF-8">
<title>Aloned</title>
<script>
  function wrapper(){document.getElementById("o").innerHTML = a(parseInt(document.getElementById("i").value));}
  function a(n){o=Array.from(Array((n+1)).keys());o.shift();o.shift();for(i=1;i<o.length;i++){if(o[i]%o[0]==0){o.splice(i,1);o.shift();i=0;}}return o;}
</script>
  </head>
  <body>
<p>Enter an integer:</p>
<p><input type="text" id="i" value="5" /></p>
<p><input type="button" value="Alone It!" onclick="wrapper()" /></p>
<div id="o"></div>
  </body>
</html>
```

This ungolfed code snippet has some comments and lets you interactively see the steps for any given input.

```
<!DOCTYPE html>
<html lang="en">
  <head>
<meta charset="UTF-8">
<title>Aloned</title>
<script>
  function wrapper()
  {
    document.getElementById("o").innerHTML = aloned(parseInt(document.getElementById("i").value));
  }
  function aloned(n)
  {
    // From nils peterson's comment on benmcdonald's answer
    // http://stackoverflow.com/questions/3895478
    // Creates an array from 0 to n.
    o=Array.from(Array((n+1)).keys());

    // Remove 0 and 1 from the start of the array.
    o.shift();
    o.shift();

    // s and t are just used to display the output each iteration.
    var s = String(o);

    // Go through every item in the array (except the first).
    for(i = 1; i < o.length; i++)
    {
      // Check for an item evenly divisible by the first item.
      if (o[i]%o[0]==0)
      {
        var t=" (remove "+o[0]+" and "+o[i]+")";

        // Splice removes the current item, shift removes the first item.
        o.splice(i,1);
        o.shift();

        // Reset the array, so we're looping from the beginning again.
        i=0;

        s = s + "<br />" + String(o) + t;
      }
    }
    return s + " (OUTPUT)";
  }
</script>
  </head>
  <body>
<p>Enter an integer:</p>
<p><input type="text" id="i" value="5" /></p>
<p><input type="button" value="Alone It!" onclick="wrapper()" /></p>
<div id="o"></div>
  </body>
</html>
```
> 1 votes

# Answer
## Racket 191 bytes

```
(let loop((fl(range 2(add1 n)))(fg #f))(define i(first fl))(for((j(rest fl))
#:when(= 0(modulo j i))#:final(= 0(modulo j i)))
(set! fl(remove*(list i j)fl))(set! fg #t))(if fg(loop fl #f)fl))

```

Ungolfed (comments after ';'):

```
(define (f n)
  (let loop ((fl (range 2 (add1 n)))  ; create a full list of numbers
             (fg #f))                 ; flag to show if main list is modified
    (define i (first fl))
    (for ((j (rest fl)) #:when (= 0 (modulo j i))  ; test divisibility
                        #:final (= 0 (modulo j i)))
      (set! fl (remove* (list i j) fl))  ; remove these from main list
      (set! fg #t))
    (if fg (loop fl #f)              ; if main list modified, check again,
        fl)))                         ; else print modified list.

```

Testing:

```
(f 2)
(f 6)
(f 15)
(f 20)
(f 22)

```

Output:

```
'(2)
'(5)
'(8 9 11 12 13 15)
'(11 12 13 15 17 19 20)
'(12 13 15 17 19 20 21)

```
> 1 votes

# Answer
# JavaScript (ES6), 92 bytes

```
f=(n,R=[...Array(n-1)].map((_,i)=>i+2),[i,...r]=R)=>~r.indexOf(i*=2)?f(n,r.filter(x=>x-i)):R

```

I thought I had posted this yesterday, but obviously not...

Here's another version:

```
f=(n,R=[...Array(n-1)].map((_,i)=>i+2),[i,...r]=R,q=r.filter(x=>x-i*2))=>q+""!=r+""?f(n,q):R

```
> 1 votes

# Answer
# Java 7, 210 bytes

```
import java.util.*;List c(int n){List<Integer>l=new ArrayList();int i=1;for(;i++<n;l.add(i));for(i=1;i++<n;)for(int x:l)if(i!=x&x%i<1&l.indexOf(i)>=0){l.remove((Integer)i);l.remove((Integer)x);break;}return l;}

```

Can definitely be golfed some more by using a different approach, probably by using an array with some tricks. Due to the cast, break, typed-list and if-checks it is a bit longer than expected, but it works.

**Ungolfed & test code:**

Try it here.

```
import java.util.*;
class M{
  static List c(int n){
    List<Integer> l = new ArrayList();
    int i = 1;
    for(; i++ < n; l.add(i));
    for(i = 1; i++ < n;){
      for(int x : l){
        if(i != x & x%i < 1 & l.indexOf(i) >= 0){
          l.remove((Integer)i);
          l.remove((Integer)x);
          break;
        }
      }
    }
    return l;
  }

  public static void main(String[] a){
    System.out.println(Arrays.toString(c(2).toArray()));
    System.out.println(Arrays.toString(c(6).toArray()));
    System.out.println(Arrays.toString(c(15).toArray()));
    System.out.println(Arrays.toString(c(20).toArray()));
    System.out.println(Arrays.toString(c(22).toArray()));
  }
}

```

**Output:**

```
[2]
[5]
[8, 9, 11, 12, 13, 15]
[11, 12, 13, 15, 17, 19, 20]
[12, 13, 15, 17, 19, 20, 21]

```
> 1 votes

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