title: Seven Slash Display

text:
# Question
Title: Seven Slash Display
Write a program that takes in a non-empty string of the digits 0 through 9 and prints how they would be shown on a seven-segment display using slashes (`/`, `\`).

These are the precise digit shapes:

```
/\
\ \
 \/

 \
  \

/\
 /
 \/

/\
 /\
  /

 \
\/\

/
\/\
  /

/
\/\
 \/

/\
  \

/\
\/\
 \/

/\
\/\
  /

```

When one digit occurs after another, they are chained diagonally up and to the right, with a diagonal space in between. So, for example, `203` would become this:

```
    /\
     /\
  /\  /
  \ \
/\ \/
 /
 \/

```

Note that the `1` character takes up the same amount of space as the others. The two lines of the `1` are on the right side of the display, not the left.

So `159114` would become this:

```
           \
          \/\
         \
          \
       \
        \
    /\
    \/\
  /   /
  \/\
 \  /
  \

```

There may be any amount and combination of leading/trailing newlines or spaces in the output as long as the digits are in the correct position with respect to one another.

So for `159114`, this would also be valid:

```

          \
         \/\
        \
         \
      \
       \
   /\
   \/\
 /   /
 \/\
\  /
 \

```

Take input from stdin or the command line, or write a function that takes in a string. Print the result to stdout or you can return it as a string if you write a function.

Any non-empty string of the digits 0 through 9 should work, including single digits strings (e.g. `8`) and strings with leading zeros (e.g. in `007`, the zeros *do* need to be printed).

**The shortest code in bytes wins.**

# Answer
# CJam, ~~77~~ ~~71~~ ~~70~~ ~~69~~ ~~63~~ 62 bytes

```
r_,5*_Sa*a*\{~"÷ÐëúÜ¾¿ðÿþ"=i2bS"\/"4*W<+.*3/..e>2fm>2m>}/Wf%N*

```

All characters are printable, so copy and paste should work just fine.

Try it online in the CJam interpreter.

### Idea

We start by examining the number of digits **n** in the input and pushing a square of spaces big enough to cover the output. In the implementation, this square will be encoded as a two-dimensional array of one-character strings.

A square of length **2n+1** would be just right (i.e., no surrounding whitespace) for a straightforward implementation, but we'll use one of length **5n** to save a couple of bytes. Thankfully, surrounding whitespace is allowed.

If we reverse the lines of the seven slash representation of **8**, we obtain the following:

```
 \/
\/\
/\

```

The representation of all digits can be encoded as an 8-bit integer, where the ith bit is **0** iff the ith character should get replaced with a space. For the digits **0** to **9**, the resulting integers are

```
247 208 235 250 220 190 191 240 255 254

```

which correspond to the following ISO-8559-1 characters:

```
÷ÐëúÜ¾¿ðÿþ

```

For each digit in the input, after selecting the corresponding 8-bit integer, we repeat the ith character of the representation of **8** exactly **ai** times, where **ai** is the ith bit of the integer. This pushes an array of strings of either one or zero characters. By dividing this array into chunks of length 3, we obtain an array where each element corresponds to a line of the representation.

Now, we compute the vectorized maximum of the strings that represent the square and the strings that represent the digit. The strings `/` and `\` are bigger than the string , so they will replace the spaces in the square. The empty string, however, is smaller than the string , so empty strings in the digit representation will preserve the spaces in the square.

We now rotate the rows and columns by two units to place the following digit representation in the proper part of the square and repeat the process for the remaining digits in the input.

Finally, we reverse each row and insert a linefeed between the individual rows.

### Code

```
r_,      e# Read a token from STDIN and push the length of a copy.
5*_      e# Multiply the length by 5 and push a copy.
Sa*      e# Repeat the array [" "] that many times.
a*       e# Repeat the array [[" " ... " "]] that many times.
\{       e# For each character C in the input:
  ~      e#   Push eval(C), i.e., the digit the character represents.

  "÷ÐëúÜ¾¿ðÿþ"

         e#   Push the encodings of all 10 seven slash representations.

  =      e#   Select the proper one.
  i2b    e#   Push the resulting characters code point in base 2, i.e., its bits.
  S      e#   Push " ".
  "\/"4* e#   Push "\/\/\/\/".
  +W<    e#   Concatenate and eliminate the last character.
  .*     e#   Vectorized repetition.

         e#   For the digit 5, e.g., we have [1 0 1 1 1 1 1 0] and  " \/\/\/\" on
         e#   the stack, so .* yields [" " "" "/" "\" "/" "\" "/" ""].

  3/     e#   Divide the representation into chunks of length 3, i.e., its lines.
  ..e>   e#   Compute the twofold vectorized maximum, as explained above.
  2fm>   e#   Rotate each line to characters to the right.
  2m>    e#   Rotate the lines two units down.
}/
Wf%      e# Reverse each line.
N*       e# Place linefeeds between them.

```

The last rotations would mess up the output if the square's side length was smaller than **2n+3**. Since **5n ≥ 2n+3** for all positive integers **n**, the square is big enough to prevent this.
> 9 votes

# Answer
# Python 3, ~~189~~ ~~183~~ 174 bytes

```
s="a%sa"%input()
while s[1:]:b,a,c,d,e,f,g=[c*(ord(n)>>int(s[~(n>"Ͱ")],16)&1)or" "for c,n in zip("\/"*4,"ΟϭŅͭͱͼϻ")];S=len(s)*"  ";print(S+a+b,c+d+"\n"+S+e+f+g);*s,_=s

```

The compression looks okay to me, but I'm having trouble coming up with a good way of ditching the seven variables...

Thankfully the spec is fairly relaxed on whitespace rules, because there's a lot of leading/trailing whitespace.

**Expanded:**

```
s="a%sa"%input()
while s[1:]:
  b,a,c,d,e,f,g=[c*(ord(n)>>int(s[~(n>"Ͱ")],16)&1)or" "
                 for c,n in zip("\/"*4,"ΟϭŅͭͱͼϻ")]
  S=len(s)*"  "
  print(S+a+b,c+d+"\n"+S+e+f+g)
  *s,_=s

```

## Explanation

The segment positions represented by the variables are:

```
    ab               /\
    efg               /\
  ab cd            /\  /
  efg              \ \
ab cd            /\ \/
efg               /
 cd               \/

```

Each segment is encoded by a single 2-byte Unicode character. For example, `ϻ` encodes `g`'s segment like so:

```
bin(ord("ϻ")) = bin(1019) = "0b1111111011"
                               ^^^^^^^^^^
                               9876543210

```

Indeed, `2` is the only digit to not use the bottom-right segment of a seven-segment display.
> 25 votes

# Answer
# C, 1098 345 323 319 bytes

First Second Third attempt. Finally decided to ditch the screen buffer to save a few bytes. This program takes a parameter of digits and prints the digits in 7-segment format.

First time participant. Just for fun. Be gentle.

```
a[]={100489,2056,98569,67849,2440,67969,100737,2057,100745,67977},i,j,k,n,m;char*c=" /\\";
#define f(q,r) for(q=0;q<(r);q++)
#define P(w) putchar(w)
#define Q(d,i,j) P(c[a[v[1][d]-48]>>(i*3+j)*2&3])
main(w,char**v){f(i,n=strlen(v[1]))f(k,(m=n-i-1)?2:3){f(j,m*2)P(32);f(w,3)Q(m,k,w);if(!k&&i)f(w,2)Q(m+1,2,w+1);P(10);}}

```

Expanded, warning free:

```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int a[]={100489,2056,98569,67849,2440,67969,100737,2057,100745,67977};
char *c=" /\\";
#define f(q,r) for(q=0;q<(r);q++)
#define P(w) putchar(w)
#define Q(d,i,j) P(c[a[v[1][d]-48]>>(i*3+j)*2&3])
int main(int w, char **v)
{
    int i,j,k,n,m;
    f(i,n=strlen(v[1])) {
        m=n-i-1;
        f(k,m?2:3) {
            f(j,m*2) P(32);
            f(w,3) Q(m,k,w);
            if (!k&&i) f(w,2) Q(m+1,2,w+1);
            P(10);
        }
    }
}

```
> 19 votes

# Answer
# JavaScript, ~~192~~ ~~178~~ ~~167~~ 162 bytes

```
f=x=>{n=b="\n";for(k in x)for(i=0;i<8;)b+=("î\xA0Öô¸|~àþü".charCodeAt(x[k])>>i++&1?i%2?"/":"\\":" ")+(i%3?"":n+"  ".repeat(k));return b.split(n).reverse().join(n)}

```

Usage: `f("1337");` will return

```
      /\
        \
    /\
     /\
  /\  /
   /\
 \  /
  \

```

It uses features of ES6 and may have some implementation dependent behavior due to omission of semicolons and parentheses and such, but it works in Firefox.

**Expanded:**

```
f=x=>
{
    n = b = "\n";

    for (k in x)
        for (i=0; i<8;)
            b += ("î\xA0Öô¸|~àþü".charCodeAt(x[k]) >> i++ & 1? i%2? "/" : "\\" : " ") + (i%3? "" : n+"  ".repeat(k));

    return b.split(n).reverse().join(n)
}

```

**Explanation:**

`l` is an array containing 10 single byte characters which correspond to the shape of each digit. For example, the digit 0 is represented by the character `î`:

```
/\        11
\ \  -->  101  --> 11 101 110 = î
 \/       011

```

The input characters are used as keys to the array holding their shape representing counterparts, which get read bit by bit.
> 14 votes

# Answer
## Perl - 103 Bytes

```
#!perl -n
print$i+$%2?U^(u,$i--%2?v9:z)[$i<4+$%2&vec$_,4*$-3-$i,1]:$/.!($i=$--)
while$+=2*y/0-9/wPkz\\>?p~/

```

The above contains 6 unprintable characters (the source can be downloaded at **Ideone**), and is equivalent to the following:

```
#!perl -n
print$i+$^F%2?U^(u,$i--%2?v9:z)[$i<4+$^F%2&vec$_,4*$^F-3-$i,1]:$/.!($i=$^F--)
while$^F+=2*y/0-9/wPkz\\>?p\177~/

```

Each `^F` may be replaced by a literal character 6 (ACK), and `\177` replaced by character 127 (DEL).

The shebang is counted as 1, the second newline is uncessary. Input is taken from stdin.

---

**Sample Usage**

```
$ echo 0123 | perl seven-slash.pl

      /\
       /\
    /\  /
     /
   \ \/
    \
/\
\ \
 \/

$ echo 456789 | perl seven-slash.pl

          /\
          \/\
        /\  /
        \/\
      /\ \/
        \
    /
    \/\
  /  \/
  \/\
 \  /
\/\

```

---

**Explanation**

Output is generated one byte at a time. Each character is transliterated, and this is then interpreted as a bit array using `vec`. The bits are stored in the following way:

```
   /\           56
   \/\          234
 /\ \/   ->   56 01
 \/\          234
  \/           01

```

Output alternates between 3 and 5 slashes, so that bits `56` spills over into `01` of the next digit. Bit `7` is not used.
> 10 votes

# Answer
# C#, 360 355 331 bytes

Hi there, first attempt at code-golf. Hope this doesn't score too badly for a C#-entry.

```
string p(string n){var l=new string[n.Length*2+1];var i=l.Length-1;for(;i>0;){var x=@"/\\ \\/ \  \  /\ / \//\ /\ / \\/\  / \/\ // \/\\//\  \  /\\/\\//\\/\ /".Substring((n[0]-48)*7,7);for(var j=i-3;j>=0;){l[j--]+="  ";}l[i--]+=" "+x[5]+x[6];l[i--]+=""+x[2]+x[3]+x[4];l[i]+=""+x[0]+x[1];n=n.Remove(0, 1);}return string.Join("\n",l);}

```

Usage: `p("159114");` will return

```
          \
         \/\
        \
         \
      \
       \
   /\
   \/\
 /   /
 \/\
\  /
 \

```

**Expanded:**

```
string p(string n)
    {
        var l = new string[n.Length * 2 + 1];
        var i = l.Length - 1;
        for (; i > 0; )
        {
            var x = @"/\\ \\/ \  \  /\ / \//\ /\ / \\/\  / \/\ // \/\\//\  \  /\\/\\//\\/\ /".Substring((n[0] - 48) * 7, 7);

            for (var j = i - 3; j >= 0; )
            {
                l[j--] += "  ";
            }
            l[i--] += " " + x[5] + x[6];
            l[i--] += "" + x[2] + x[3] + x[4];
            l[i] += "" + x[0] + x[1];

            n = n.Remove(0, 1);
        }

        return string.Join("\n", l);
    }

```
> 8 votes

# Answer
## python 2, ~~317~~ ~~298~~ ~~278~~ 273.15

```
def f(s):
    r=range;n=len(s)*2;l=[[' ']*-~n for x in r(-~n)]
    for x in r(0,n,2):
        for i,[d,y,c]in enumerate(zip('0112012','1021012',r'\\\\///')):l[n-2-x+int(y)][x+int(d)]=[' ',c][('%7s'%(bin(ord('}(7/jO_,\x7fo'[map(int,s)[x/2]])))[2:])[i]=='1']
    for x in l:print''.join(x)

```

I considered 4-spaces as tabs while counting.
Uncompressed and readable:

```
def f(s):
    r=['1111101','0101000','0110111','0101111','1101010','1001111','1011111','0101100','1111111','1101111']
    ''.join(map(lambda x:chr(eval('0b'+x)),r))
    n=len(s)*2
    l=[[' ']*(n+1) for x in xrange(n+1)]
    shifts=[(0,1,'\\'),(1,0,'\\'),(1,2,'\\'),(2,1,'\\'),(0,0,'/'),(1,1,'/'),(2,2,'/')]
    for x in xrange(0,n,2):
        y=n-2-x
        for i,[dx,dy,c] in enumerate(shifts):
            l[y+dy][x+dx]=c if r[map(int,s)[x/2]][i]=='1' else ' '
    return '\n'.join(''.join(x) for x in l)

```
> 4 votes

# Answer
# KDB(Q), ~~172~~ 136 bytes

```
{d:(9#1 2 0 2)*/:-9#'0b vs'427 136 403 409 184 313 315 392 443 441;
 -1" /\\"{m+(c,/:y),c:(count[m:0 0,x,\:0 0]-3)#0}/[3 3#/:d"J"$'(),x];}

```

# Explanation

1) Create `d` map with all the digits' shapes.

2) Pad the matrix with extra zeros and add them together. i.e. "01"

```
0           0 0 0 2 0
0           0 0 0 0 2
1 2 0 0 0 + 0 0 0 0 0
2 0 2 0 0   0
0 2 1 0 0   0

```

3) Use the index to map `" /\"` and print with `-1`.

# Test

```
q){d:(9#1 2 0 2)*/:-9#'0b vs'427 136 403 409 184 313 315 392 443 441;-1" /\\"{m+(c,/:y),c:(count[m:0 0,x,\:0 0]-3)#0}/[3 3#/:d"J"$'(),x];}"0123456789"
                  /\
                  \/\
                /\  /
                \/\
              /\ \/
                \
            /
            \/\
          /  \/
          \/\
         \  /
        \/\
      /\
       /\
    /\  /
     /
   \ \/
    \
/\
\ \
 \/

```

I'm sure this can be shorter!!

Thanks @h.j.k.
> 3 votes

# Answer
# Pip, 122 + 1 = 123 bytes

Uses the `-n` flag. Takes input via command-line argument.

```
l:$.(J"\/ "@^(A_TB3M"⮐䫶ヷ㄃䓳ⴷⴥㅕ⬿⭑")@_.2<>2Ma)z:2*#ap:sXz+2RLz+2Fi,5Fj,z{c:[4-ii]//2+j(pc@0c@1):(lij)}RVp

```

The characters in the UTF-8 string have the following code points: `11152, 19190, 12535, 12547, 17651, 11575, 11557, 12629, 11071, 11089`.

Slightly ungolfed:

```
t:[120022001 222022202 122012021 122012201 220012202 120212201 120212001 122022202 120012001 120012201]
l:$.({J"\/ "@^t@a.2<>2}Ma)
z:2*#a+2
p:sXzRLz
Fi,5
 Fj,2*#a {
  x:i//2+j
  y:(4-i)//2+j
  p@y@x:l@i@j
 }
P RVp

```

The basic strategy is to find each number's constituent characters and then skew them appropriately. For example, for `8`, we want this (spaces represented by dots):

```
/.
\\
/.
\\
/.

```

which will turn into this:

```
 .
/\.
\/\.
 \/

```

The nice feature of this strategy is that multiple pre-skewed numbers can simply be concatenated side by side.

Now, we can encode `/.\\/.\\/.` in base 3 as `1200120012`. Then we can convert this to decimal and treat it as a UTF-8 code point.

The expression `J"\/ "@^(A_TB3M"⮐䫶ヷ㄃䓳ⴷⴥㅕ⬿⭑")@_.2<>2Ma` gets the pre-skewed data by the following process:

```
                            Ma   Map this lambda function to each character in input:
        (A_TB3M"...")            Create list of the code points of each character in UTF-8
                                   string, converted to base 3
                     @_          Index into that list using the input character
                       .2        Concatenate 2 to the end of the base-3 value (all of the
                                   pre-skewed number grids end in 2, i.e. space)
       ^                         Split the number into a list of its digits
 "\/ "@                          Index into this string with those digits, giving a list
                                   of slashes & spaces
J                                Join the list together into a string
                         <>2     Group string two characters at a time

```

Once we have concatenated these strings side-by-side using `$.`, we then create a grid of spaces (2\**n*+2 square), loop through the pre-skewed grid, and replace the corresponding spaces in the post-skewed grid with the appropriate characters. To see it happening, one can modify the code to print each stage and pause for user input:

The grid is actually built upside down, because that seemed to make the math easier.

I'm sure there's better algorithms to use. But I wanted to come up with my own idea rather than copying somebody else's.

More on Pip
> 2 votes

# Answer
## Brainfuck - 719 bytes

For historical context only, credits to Daniel B Cristofani. I'm not exactly sure when this was created, but it is available from the Internet Archive as early as May 9th, 2003.

The output for `9` is different than in the problem description.

```
>>>>+>+++>+++>>>>>+++[
  >,+>++++[>++++<-]>[<<[-[->]]>[<]>-]<<[
    >+>+>>+>+[<<<<]<+>>[+<]<[>]>+[[>>>]>>+[<<<<]>-]+<+>>>-[
      <<+[>]>>+<<<+<+<--------[
        <<-<<+[>]>+<<-<<-[
          <<<+<-[>>]<-<-<<<-<----[
            <<<->>>>+<-[
              <<<+[>]>+<<+<-<-[
                <<+<-<+[>>]<+<<<<+<-[
                  <<-[>]>>-<<<-<-<-[
                    <<<+<-[>>]<+<<<+<+<-[
                      <<<<+[>]<-<<-[
                        <<+[>]>>-<<<<-<-[
                          >>>>>+<-<<<+<-[
                            >>+<<-[
                              <<-<-[>]>+<<-<-<-[
                                <<+<+[>]<+<+<-[
                                  >>-<-<-[
                                    <<-[>]<+<++++[<-------->-]++<[
                                      <<+[>]>>-<-<<<<-[
                                        <<-<<->>>>-[
                                          <<<<+[>]>+<<<<-[
                                            <<+<<-[>>]<+<<<<<-[
                                              >>>>-<<<-<-
  ]]]]]]]]]]]]]]]]]]]]]]>[>[[[<<<<]>+>>[>>>>>]<-]<]>>>+>>>>>>>+>]<
]<[-]<<<<<<<++<+++<+++[
  [>]>>>>>>++++++++[<<++++>++++++>-]<-<<[-[<+>>.<-]]<<<<[
    -[-[>+<-]>]>>>>>[.[>]]<<[<+>-]>>>[<<++[<+>--]>>-]
    <<[->+<[<++>-]]<<<[<+>-]<<<<
  ]>>+>>>--[<+>---]<.>>[[-]<<]<
]
[Enter a number using ()-./0123456789abcdef and space, and hit return.
Daniel B Cristofani (cristofdathevanetdotcom)
http://www.hevanet.com/cristofd/brainfuck/]

```
> 2 votes

# Answer
# Perl, 270 bytes

I really shouldn't have wasted my time on this.

```
$e="\\";$g=" ";$_=reverse<>;$l=length;push@a,(119,18,107,91,30,93,125,19,127,95)[$1]while/(.)/g;for($i=0;$i<=$l;$i++){$j=2*($l-$i);$b=$a[$i];$c=$i&&$a[$i-1];print" "x$j,$b&1?"/":$g,$b&2?$e:$g,$g,$c&32?$e:$g,$c&64?"/":$g,"
"," "x$j,$b&4?$e:$g,$b&8?"/":$g,$b&16?$e:$g,"
"}

```
> 1 votes

# Answer
# JavaScript (*ES6*), 191 ~~206~~

Run snippet in Firefox to test.

```
F=m=>(
  a='    \\/  /\\/\\ /  /\\  \\\\ \\'.match(/.../g),
  o=f='',r=' ',
  [for(d of m)(
    n=1e3+'¯B\x91ÿ$ê\x86A\x87ë'.charCodeAt(d)+'', // here there are 3 valid characters tha the evil stackoverflow editor just erase off, so I had to put them as hex escape
    o='\n'+f+' '+a[n[2]]+'\n'+r+a[n[1]]+o,
    r=f+a[n[3]],
    f+='  ')],
  r+o
)

//TEST

go=_=>O.innerHTML =(v=I.value)+'\n'+F(v)

go()
```

```
<input id=I value='0123456789'><button onclick='go()'>-></button>
<pre id=O></pre>
```
> 1 votes

# Answer
# JavaScript (Node.js),  ~~149~~  146 bytes

Contains a few unprintable characters which are escaped in the code below.

```
s=>(g=([d,...s],p='',q=p)=>d?g(s,p+q,88)+(p+=q?`10 65
${p}234
`:865).replace(/\d/g,n=>'\\/ '[Buffer("w\x11k;\x1d>~\x13\x7f?")[n>4?s[0]:d]>>n&1?n&1:2]):s)(0+s)

```

Try it online!

### How?

This recursively builds the following pattern (here with 4 digits):

```
88888810 65
888888234
888810 65
8888234
8810 65
88234
10 65
234
865

```

Where:

* \\$8\\$ is a padding character
* other even digits are replaced with either `\` or a space
* odd digits are replaced with either `/` or a space

Leading to:

```
______/\ \/
______\/\
____/\ \/
____\/\
__/\ \/
__\/\
/\ \/
\/\
_\/

```
> 1 votes

# Answer
# Java 8, 341 bytes

```
n->{int i=n.length*2,j=i+1,k=0,t;String l[]=new String[j],x;for(;j-->0;l[j]="");for(;i>0;l[i--]+=" "+x.substring(5,7),l[i--]+=x.substring(2,5),l[i]+=x.substring(0,2))for(x="/~~ ~~/ ~  ~  /~ / ~//~ /~ / ~~/~  / ~/~ // ~/~~//~  ~  /~~/~~//~~/~ /".replace('~','\\').substring(t=(n[k++]-48)*7,t+7),j=i-2;j-->0;)l[j]+="  ";return"".join("\n",l);}

```

Port of *@Shion*'s C# .NET answer, so make sure to upvote him as well!

Try it online.

**Explanation:**

```
n->{                       // Method with character-array parameter and String return-type
  int i=n.length*2,        //  Two times the length of the input array
      j=i+1,               //  Index integer, starting at `i+1`
      k=0,t;               //  Temp integers
  String l[]=new String[j],//  String-array for the rows, default filled with `null`
         x;                //  Temp-String
  for(;j-->0;l[j]="");     //  Replace all `null` with empty Strings
  for(;i>0                 //  Loop `i` downwards in the range [`n.length*2`, 0)
      ;                    //   After every iteration:
       l[i--]+=            //    Append the row at index `i` with:
                           //    (and decrease `i` by 1 afterwards with `i--`)
         " "               //     A space
         +x.substring(5,7),//     And the 6th and 7th characters of temp-String `x`
       l[i--]+=            //    Append the row at index `i` with:
                           //    (and decrease `i` by 1 afterwards with `i--`)
         x.substring(2,5), //     The 3rd, 4th and 5th characters of temp-String `x`
       l[i]+=              //    Append the row at index `i` with:
         x.substring(0,2)) //     The 1st and 2nd characters of the temp-String `x`
    for(x="/~~ ~~/ ~  ~  /~ / ~//~ /~ / ~~/~  / ~/~ // ~/~~//~  ~  /~~/~~//~~/~ /".replace('~','\\')
                           //   String containing all digit-parts
          .substring(t=(n[k++]-48)*7,t+7),
                           //   and take the substring of 7 characters at index
                           //   `n[k]` as integer multiplied by 7
        j=i-2;j-->0;)      //   Inner loop `j` in the range (`i`-2, 0]
      l[j]+="  ";          //    And append the rows at index `j` with two spaces
  return"".join("\n",l);}  //  Return the rows delimited with new-lines

```
> 0 votes

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


title: Hash bomb filtrate

text:
# Question
Title: Hash bomb filtrate
Pipe a short stream to the following Java program run with accompanying command line options, such that it prints `true`.

```
class Code implements java.io.Serializable {
    private static final long serialVersionUID = 0L;
    private static long count;
    @Override public int hashCode() {
        ++count;
        return super.hashCode();
    }
    public static void main(String[] args) throws Throwable {
        new java.io.ObjectInputStream(System.in).readObject();
        System.err.println(count != (int)count);
    }
}

java '-Djdk.serialFilter=maxarray=100000;maxdepth=16;maxrefs=500;Code;java.util.HashSet;java.util.Map$Entry;!*' Code

```

**Rules**

* Shortest stream in bytes wins.
* The program above must print `true`.
* No fiddling with the command line - no aliasing, no running a weird shell, no putting nonsense in classpath, etc. (It does require the quotes. The `Map$Entry` bit is indeed weird.)
* In case of issue, run on Oracle JDK13 current update at time of posting.
* Tie breaker: size of stream in bytes when compressed with `gzip --best` (on my machine, if that's variable).

Probably post the source code to generate the stream, rather than some bytes.

# Answer
1087 bytes 1065 bytes

Apparently the JDK's maxdepth limit is kinda broken...

```
static Object payload() throws Exception {
  int layers = 30;
  int width = 2;
  int codes = 7;
  int extra = 8;

  List<Set<Object>> sets = new ArrayList<>();
  sets.add(new HashSet<>());

  for (int i = 1; i < layers; i++) {
    Set<Object> s = new HashSet<>();
    sets.add(s);
    for (int j = i - 1; j >= i - width - 1 && j >= 0; j--) {
      sets.get(j).add(s);
    }
  }

  for (int i = 0; i < codes; i++) {
    sets.get(sets.size() - 1).add(new Code());
  }

  // special HashSet at the root to circumvent maxdepth limitation. By including a couple deeply
  // nested HashSets here, they will be replaced by references when they're used inside `sets`.
  // Using a LinkedHashSet to guarantee order of serialization.
  LinkedHashSet<Object> linkedRoot = new LinkedHashSet<>();
  linkedRoot.add(sets.get(28));
  linkedRoot.add(sets.get(14));
  linkedRoot.add(sets.get(0));

  // shaving off some more bytes by storing multiple copies of the same set at the top level
  for (int i = 0; i < extra; i ++) {
    sets.get(0).add("foo" + i);
    linkedRoot.add(sets.get(0));
    sets.get(0).remove("foo" + i);
  }

  // transplant the contents of the LinkedHashSet into the HashSet
  Set<Object> root = new HashSet<>();
  Field mapField = HashSet.class.getDeclaredField("map");
  mapField.setAccessible(true);
  mapField.set(root, mapField.get(linkedRoot));
  return root;
}

```

Base64-encoded data:

```
rO0ABXNyABFqYXZhLnV0aWwuSGFzaFNldLpEhZWWuLc0AwAAeHB3DAAAABA/QAAAAAAAC3NxAH4AAHcMAAAAED9AAAAAAAABc3EAfgAAdwwAAAAQP0AAAAAAAAdzcgAEQ29kZQAAAAAAAAAAAgAAeHBzcQB+AARzcQB+AARzcQB+AARzcQB+AARzcQB+AARzcQB+AAR4eHNxAH4AAHcMAAAAED9AAAAAAAADc3EAfgAAdwwAAAAQP0AAAAAAAANzcQB+AAB3DAAAABA/QAAAAAAAA3NxAH4AAHcMAAAAED9AAAAAAAADc3EAfgAAdwwAAAAQP0AAAAAAAANzcQB+AAB3DAAAABA/QAAAAAAAA3NxAH4AAHcMAAAAED9AAAAAAAADc3EAfgAAdwwAAAAQP0AAAAAAAANzcQB+AAB3DAAAABA/QAAAAAAAA3NxAH4AAHcMAAAAED9AAAAAAAADc3EAfgAAdwwAAAAQP0AAAAAAAANzcQB+AAB3DAAAABA/QAAAAAAAA3NxAH4AAHcMAAAAED9AAAAAAAADc3EAfgAAdwwAAAAQP0AAAAAAAAJxAH4AAnEAfgADeHEAfgACcQB+AAN4cQB+ABlxAH4AAnhxAH4AGHEAfgAZeHEAfgAXcQB+ABh4cQB+ABZxAH4AF3hxAH4AFXEAfgAWeHEAfgAUcQB+ABV4cQB+ABNxAH4AFHhxAH4AEnEAfgATeHEAfgARcQB+ABJ4cQB+ABBxAH4AEXhxAH4AD3EAfgAQeHEAfgAOcQB+AA94c3EAfgAAdwwAAAAQP0AAAAAAAANzcQB+AAB3DAAAABA/QAAAAAAAA3NxAH4AAHcMAAAAED9AAAAAAAADc3EAfgAAdwwAAAAQP0AAAAAAAANzcQB+AAB3DAAAABA/QAAAAAAAA3NxAH4AAHcMAAAAED9AAAAAAAADc3EAfgAAdwwAAAAQP0AAAAAAAANzcQB+AAB3DAAAABA/QAAAAAAAA3NxAH4AAHcMAAAAED9AAAAAAAADc3EAfgAAdwwAAAAQP0AAAAAAAANzcQB+AAB3DAAAABA/QAAAAAAAA3NxAH4AAHcMAAAAED9AAAAAAAADc3EAfgAAdwwAAAAQP0AAAAAAAANzcQB+AAB3DAAAABA/QAAAAAAAA3EAfgAMcQB+AA1xAH4ADnhxAH4ADHEAfgANeHEAfgAncQB+AAx4cQB+ACZxAH4AJ3hxAH4AJXEAfgAmeHEAfgAkcQB+ACV4cQB+ACNxAH4AJHhxAH4AInEAfgAjeHEAfgAhcQB+ACJ4cQB+ACBxAH4AIXhxAH4AH3EAfgAgeHEAfgAecQB+AB94cQB+AB1xAH4AHnhxAH4AHHEAfgAdeHEAfgAacQB+ABpxAH4AGnEAfgAacQB+ABpxAH4AGnEAfgAacQB+ABp4

```
> 4 votes

# Answer
This one’s 1207 bytes and performs 3910245742 hashes.

```
private fun veryHashySet(): Set<Any> {
  val codes = listOf(Code(), Code())
  val sets = mutableListOf<Set<Any>>()

  for (i in 0 until 16) {
    val limit = if (i == 15) 3 else 2
    for (j in 0 until limit) {
      val set = HashSet<Any>()
      for (k in 0 until 4) {
        when {
          k < sets.size -> set.add(sets[sets.size - 1 - k])
          k < codes.size -> set.add(codes[k])
        }
      }
      sets += set
    }
  }

  return sets.last()
}

```

Data:

```
aced0005737200116a6176612e7574696c2e48617368536574ba44859596b8b7340300007870770c000000103f400000000000047371007e0000770c000000103f400000000000047371007e0000770c000000103f400000000000047371007e0000770c000000103f400000000000047371007e0000770c000000103f400000000000047371007e0000770c000000103f400000000000047371007e0000770c000000103f400000000000047371007e0000770c000000103f400000000000047371007e0000770c000000103f400000000000047371007e0000770c000000103f400000000000047371007e0000770c000000103f400000000000047371007e0000770c000000103f400000000000047371007e0000770c000000103f400000000000027371007e0000770c000000103f4000000000000273720004436f6465000000000000000002000078707371007e000f787371007e0000770c000000103f4000000000000271007e000e71007e0010787871007e000e7371007e0000770c000000103f4000000000000371007e000d71007e000e71007e00127871007e00127871007e000d71007e001371007e0012787371007e0000770c000000103f4000000000000471007e000c71007e000b7371007e0000770c000000103f4000000000000471007e000c71007e000b71007e00137371007e0000770c000000103f4000000000000471007e000c71007e000d71007e000b71007e0013787871007e00167871007e001571007e00167871007e001471007e00157371007e0000770c000000103f4000000000000471007e000a71007e001471007e001571007e0016787871007e000a7371007e0000770c000000103f4000000000000471007e000971007e000a71007e001471007e00177871007e0017787371007e0000770c000000103f4000000000000471007e000871007e000971007e001871007e0017787371007e0000770c000000103f4000000000000471007e000871007e000971007e001871007e0019787371007e0000770c000000103f4000000000000471007e000871007e001871007e001971007e001a787871007e001a7371007e0000770c000000103f4000000000000471007e000771007e001971007e001a71007e001b7871007e001b787371007e0000770c000000103f4000000000000471007e000671007e00077371007e0000770c000000103f4000000000000471007e000671007e000771007e001c71007e001b7871007e001c7871007e001e71007e001c787371007e0000770c000000103f4000000000000471007e000571007e001d71007e001e7371007e0000770c000000103f4000000000000471007e000671007e000571007e001d71007e001e787871007e00207371007e0000770c000000103f4000000000000471007e000571007e001d71007e001f71007e0020787871007e001f71007e002071007e00217871007e00047371007e0000770c000000103f4000000000000471007e000371007e000471007e001f71007e00217871007e0021787371007e0000770c000000103f4000000000000471007e000271007e000371007e000471007e0022787371007e0000770c000000103f4000000000000471007e000271007e000371007e002371007e00227871007e002278

```
> 2 votes

---
Tags: code-challenge, java, programming-puzzle
---


title: String permutations

text:
# Question
Title: String permutations
Print the biggest-size subset of strings in the input that are all permutations of each other. If there are ties, any one will do. If no strings are permutations of each other (for example, only one string was given or the strings contain distinct characters), this is just one of the strings. If no strings were passed in , do not output anything or output an empty list.

Test cases:

```
Input => Output
["ABCDE", "EDBCA", "XYZ", "ZYX", "ZXY"] => ["XYZ", "ZYX", "ZXY"]
["A"] => ["A"]

```

# Answer
# 05AB1E, 6 bytes

```
.¡{}éθ

```

Try it online!

```
.¡ }      # group the input strings by:
  {       #  sort (all permutations of each other will be identical when sorted)
    é     # sort the groups by length
     θ    # output the last (longest) group

```
> 3 votes

# Answer
# T-SQL, 267 bytes

SQL queries was totally made to solve this type of question

```
SELECT top 1WITH TIES x FROM(SELECT(SELECT a FROM(SELECT
top 999substring(x,number+1,1)a,*FROM
@,spt_values WHERE type='P'and number<len(x)ORDER BY a)c
WHERE x=t.x for xml path(''),type).value('.','char(9)')v,x FROM @ t)z
ORDER BY-count(*)over(PARTITION BY v),-len(x)

```

**Try it online**
> 2 votes

# Answer
# Japt `-h`, ~~6~~ 5 bytes

```
üñ ñl

```

Try it

```
üñ ñl     :Implicit input of array
ü         :Sort & group by
 ñ        :  Sorted strings
   ñ      :Sort by
    l     :  Length
          :Implicit output of last element

```
> 1 votes

# Answer
# Perl 6, 36 bytes

```
{max .classify(~*.comb.sort){*}||''}

```

Try it online!

Output an empty string for an empty input. If we could output something else, for example `-Inf`, then this could be:

# Perl 6, 31 bytes

```
*.classify(~*.comb.sort){*}.max

```

Try it online!
> 1 votes

# Answer
# Python 2, ~~79~~ 77 bytes

```
lambda A,S=sorted:A and max([[y for y in A if S(x)==S(y)]for x in A],key=len)

```

Try it online!

2 bytes thx to wilkben.

The `A and...` is only required to deal with the empty input.
> 1 votes

# Answer
# , 19 bytes

```
0({>\:#&>)/:~&></.]

```

Try it online!

*-2 bytes thanks to FrownyFrog*

Similar approach to Grimmy's answer.
> 1 votes

# Answer
# Clojure, 54 bytes

```
#(some val(sort-by(comp count val)>(group-by sort %)))

```

Returns `nil` for empty input.

Try it online!
> 0 votes

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


title: Shift the digits

text:
# Question
Title: Shift the digits
Here, **x** (supplied as input) and **n** (the result of your computation) are both positive integers. `n * x = n shifted`. Find n.

Here's an example of shifting:

```
123456789 -> 912345678
abcdefghi -> iabcdefgh (letters = any 0~9 digit)
123       -> 312

```

Shifting only happens *once* to the **right**. Shifting left, e.g.

```
123456789 -> 234567891

```

is *not* a valid shifting.

## Rules

* Preceding zeros count after shifting. If the number is `10` and is multiplied by `0.1` (`0.1` isn't a valid input), the result is `1`, which isn't equal to `01` (`10` after shifting).
* If your number only has one digit, the shifted result is your number:

```
1 -> 1
4 -> 4
9 -> 9

```
* Given enough time and resources, your program/function should work for any **x** input, but you only have to support **x** in the range `[1,9]` without timing out on Try It Online.

## Test cases

For more test cases, this is OEIS A092697.

1 -> 1 (1 * 1 = 1 shifted.)

9 -> 10112359550561797752808988764044943820224719
(In this test case, x = 9 and n = 10112359550561797752808988764044943820224719.
n shifted = n * x =              91011235955056179775280898876404494382022471)

6 -> 1016949152542372881355932203389830508474576271186440677966
```
</code></pre>

# Answer
> 0 votes
# 05AB1E (legacy), 12 bytes

```
T*<•GIs•°s÷*

```

Try it online!

```
T*             - Multiply input by 10
  <            - subtract 1
   •GIs•°      - 10**1045044
         s÷    - Integer divide
           *   - Multiply by input again

```

Port of xnor's answer

# Answer
> 7 votes
# Python 2, 31 bytes

```
lambda x:10**1045044/(10*x-1)*x

```

Try it online!

Produces enormous million-digit numbers. Uses the formula from the OEIS page, `x*(10^m-1)/(10*x-1)`. But, instead of using the smallest possible `m` for the given `x`, we hardcode `m=1045044`, which works for each `x` from `1` to `9`. (I'm assuming only these `x` need to be supported, because bigger ones are impossible.)

We need an `m` that's divisible by the order of `10` modulo `10*x-1`. So, to get one that works for all `x`, we take the least common multiple (LCM) of the orders, giving `m=1045044`.

```
x order
-----
1 1
2 18
3 28
4 6
5 42
6 58
7 22
8 13
9 44

```

We save a few bytes by doing `10^m/(10*x-1)` instead of `(10^m-1)/(10*x-1)`, since Python 2's floor division cuts off the remainder and gives the same result, as long we move the `*x` after the division.

Despite how the massive the results are, TIO can in fact compute them for every `x` from `1` to `9` without timing out. Validating the rotating property of an output string-wise takes longer, but if you set `validate=True` in the TIO link and the limit to a single `x`, this also completes before timing out. I've also validated all the results on my machine.

# Answer
> 3 votes
# JavaScript (Node.js),  ~~54 48~~  44 bytes

*Saved 4 bytes thanks to @xnor*

Takes input as a BigInt. Based on the formula given in A092697.

```
f=(x,m=t=10n)=>~-m%(q=t*x-1n)?f(x,m*t):m/q*x

```

Try it online!

---

# JavaScript (Node.js),  ~~165 153~~  151 bytes

Takes input as a BigInt and performs a recursive search.

```
f=(x,n='',i=-1)=>+n[[d,...a]=[...x*BigInt(n)+''],s=a.join``+d,0]&&n==s?o=n:n.slice(0,i++)==s.slice(-i,-1)&i<60&&([...2**29+'4'].some(k=>f(x,k+n,i)))&&o

```

Try it online!

---

**NB:** Both solutions assume \\$1\le x\le9\\$.

# Answer
> 3 votes
# Wolfram Language (Mathematica), 42 bytes

```
#(10^MultiplicativeOrder[10,a=10#-1]-1)/a&

```

Try it online!

**xnor's method n-shifted my bytes...**

# Wolfram Language (Mathematica), 24 bytes

```
#(10^1045044-1)/(10#-1)&

```

Try it online!

# Answer
> 3 votes
# Jelly, 13 bytes

```
⁵×’⁵*“ÐṂ+’¤:×

```

**Try it online!** (The 1045044 digits do not fit within TIO's output)

An implementation of xnor's LCM method.

`⁵×’⁵*58!$¤:×` works in theory for 12, but there's no chance of calculating results with \\$58!\\$ digits within 60s using Jelly.

```
⁵×’⁵*“ÐṂ+’¤:× - Link: integer,    x
⁵             - 10                10
 ×            - multiply          10x
  ’           - decrement         10x-1
          ¤   - nilad followed by link(s) as a nilad:
   ⁵          -   10              10
     “ÐṂ+’    -   1045044         1045044
    *         -   exponentiate    10^1045044
           :  - integer division  10^1045044//(10x-1)
            × - multiply          10^1045044//(10x-1)*x

```

---
Tags: code-golf, arithmetic, integer, restricted-time
---


# Question
Title: Determine max speed horse can run without passing or slowing
# Story

There is a woman, named Sarah, whom likes smooth horse rides. She's going to go for a ride down a path too thin to pass any other horses she may come across - and so that her ride can be as smooth as possible she does not want to have to change speed though she would prefer to get to her destination as fast as possible.

# Situational Definition

There is a random number of horses traveling at a random speed which are at a random point between the start and end of the path when the Sarah departs. You must calculate the fastest speed at which she can travel without reaching another of the horses have having to slow her speed.

All horses on this path will slow to the speed of the horse in front of it if it reaches that horses position. It's a popular trail, and there is always at least 1 horse.

Example "starting" point graphic:

Example "half way" graphic:

# Primary Success Criteria

Each post must have a code golf answer - in which you try to solve the problem in as few characters as possible.

I'm open to changes on these policies but I thought it would be interesting if I were allowed to have the following **special rules**: (If they are deemed unfair or flawed I'll certainly reconsider)

* Line endings are assumed to be '\n' not '\r\n' and are only counted as 1 character. This may allow slightly more readable code in some languages.
* To encourage answering in languages that would not usually be "winners" in code golf I'd like to institute a point modification system:
    + Code golf languages have their character count multiplied by 1.25. (I will consider any language in which at least 80% of it's operators or keywords are 1 or 2 characters to be a code golf language.)
    + Answers using compiled strictly typed languages (C, Java, etc) can have their character count multiplied by 0.85 (Because usually it requires more characters to code things in those languages.) Languages like Javascript that may be "compiled" by something like V8 do not count and are loosely typed.

(These may be modifiers may be altered or changed slightly if they are unfair or need improvement)

**Implementation technical details** You are not required to post surrounding code that is not specific to this problem and is required by your language for your code to execute. For example, in java your code would need a "class" and a main function to execute; however, you can simply provide code as if it were within the "main" function. Any import statements for standard libraries that are required for your code to run should be provided in a code block below your main code, and these will not count towards your character count. You shouldn't use any libraries someone who can compile or execute that language wouldn't have out of the box.

**Code Scope** Your code should work assuming that variables "d" and "h" (or a closest variant in your language if for some reason those are not acceptable) are present in your scope.

"d" is a number with decimal precision (ex. double/float) representing the distance to the destination from 0. "h" is an array or list of some structure that can support two values "p" and "s" which are also decimals.

**Testing code** You should provide a some lines for testing in a code block below your answer code block that assigns d to a random value between or equal to 200 and 1000, and "h" to a list of length between or equal to 10 and 40 in which each list item stores a value for position between 0 and the value of d, and speed is between or equal to 5 and 10. (Not Sarah's horse is the worlds fastest horse and can travel as fast as is optimal, even if that speed greatly exceeds 10)

**Results** Your answer should store the speed Sarah should travel in a variable capable of storing decimal values such that it could be used in lines below your code for any purpose including answer checking, logging to a console, or outputting in the programs UI. This variable should be named "o" if possible which is short for "optimal speed".

To recap your answer should:

1. Have a code block which outputs the speed assuming "d" and "h" are present in the scope.
2. Have a code block below which assigns "d" and "h" to appropriate values for distance and a list of horses.
3. Output the correct value for "o" which is the speed to travel. (Again if these variable names are not acceptable in your language please just note why and what variable names you used in place of the ones provided)

The answer with the shortest character count wins.

## Example situation:

"d" is 250, and "h" has one item with "p" of 50 and speed of "20". In this simple case Sarah can travel at 250/((250-50)/20)=25. So "o" should be 25 in this case.

You should be-able to handle cases in which there are numerous horses slowing after reaching the horse(s) in front of them.

## Secondary Objective

If your answer is written in JavaScript and works with the data provided or you provide an additional conforming JavaScript answer in the same post, I will execute your code in something like this in a web page I will later create in the latest version of the chrome browser:

```
var horse = (pos, speed) => ({pos: pos, speed: speed})
var rhorse = (d) => horse(rand(d), rand(5)+1)

var rand = (i) => Math.random()*i
var irand = (i) => Math.round(Math.random()*i)

var answers = []

answers.push(function(d, h){
    //YOUR CODE
})

function checkAnswer(ans, d, h){
    // Code that which is proven to answer the question reliably
}
var speeds = []
for (var a = 0; a < answers.length; a++) {
    var totalTime = 0
    for (var i = 0; i < 1000; i++) {
        var d = rand(800)+200
        var numhorses = irand(30)+10
        var h = []

        for (var i = 0; i < numhorses; i++)
            horses.push(rhorse(d))

        var start = performance.now()

        answers[a]()

        totalTime += performance.now()-start

        if (!checkAnswer(ans)
    }
    var time = (totalTime/1000)
    speeds.push({time: time, answer: a})
    console.log("Answer " + a + " completed with an average speed of " + time)
}

//Todo: sort by time

console.log(speeds)

```

And then the times I got for each answer will be posted. This does **not** determine the **winner** or the question I will mark as the "answer". It is merely another metric that is being measured. (And if you have interest in trying to out-perform other code examples you can compete that way as well). As mentioned you may provide a second code blog to be used to for the performance comparison.

# Example answer (That would fail)

" **62 Characters**

```
someHorse = h[0]
o = (d-someHorse.p)/someHorse.s
o = d/o

```

**Test code:**

```
var horse = (p, s) => ({p: p, s: s})
var rhorse = (d) => horse(rand(d), rand(5)+1)

var rand = (i) => Math.random()*i
var irand = (i) => Math.round(Math.random()*i)
var d = rand(800)+200
var numhorses = irand(30)+10
var h = []

for (var i = 0; i < numhorses; i++)
    horses.push(rhorse(d))

```

"

You can just note you'll use my test code here if you're code is written in javascript.

# Results:

1. ppperry (By the way, where is he?)- 31 characters

# Disclaimer

This is my first code golf question. I'm willing to fix flaws, please go easy with me.

This question was very strongly inspired by: https://code.google.com/codejam/contest/8294486/dashboard

# Answer
> 6 votes
# APL (Dyalog Classic), ~~10~~ 9 bytes

```
⌊/s÷1-p÷d

```

Taking `s`, `p` and `d` as per the specs, respectively horse speeds, positions and the total distance to be travelled.

Explanation:

```
      p÷d  ⍝ Divide each horse position by the total distance
    1-     ⍝ and do 1 minus that.
  s÷       ⍝ Divide each speed s by each element in the list.
⌊/         ⍝ Finally go over the list accumulating the minimum.

```

You can try it online!

Previous 10 byte solution:

```
d÷⌈/s÷⍨d-p

```

Explanation:

```
       d-p ⍝ Find the distance each horse still has to travel
    s÷⍨    ⍝ and divide it by each horse's speed.
  ⌈/       ⍝ Now go over the list, accumulating the maximum.
d÷         ⍝ Finally divide the distance by that time.

```

You can try it online!

Thanks to @Grimmy for spotting a (now corrected) problem with my original answer and for saving me 1 byte.

# Answer
> 3 votes
# Python 3, 31 bytes

```
o=d/max((d-x.p)/x.s for x in h)

```

This challenge is actually much simpler than it seems. In order to avoid running in to other horses, you have to arrive at the end after whichever horse (not counting Sarah's) arrives at the end last. To go fastest, it is thus best to arrive at exactly the same time as that horse does.

Testing code:

```
import random
d=random.uniform(200, 1000)
h=[]
class Horse:__slots__=("p", "s")
for _ in range(random.randint(10, 40)):
    h.append(Horse())
    h[-1].p = random.uniform(0, d)
    h[-1].s = random.uniform(5, 10)

```

# Answer
> 2 votes
# 05AB1E, 5 bytes

```
/1α/ß

```

Try it online!

# Answer
> 0 votes
# Pyth, 16 bytes * 1.25 = 20 bytes

```
=ZcdeS.ec-dhbebH

```

Most of this is dedicated to preserving the input format.

Used `H` instead of `h` because `h` isn't a variable in Pyth

While I could've taken that o isn't a variable as an excuse to use `J` or `K` and save a byte, in the end I decided to use `Z` (zerO) because it's what I would've had to do if `o` was available.

Try it online!

---
Tags: code-golf
---


# Question
Title: Greater than less than greater than something fishy
Given a length N string of less-than and greater-than signs (`<`, `>`), insert the integers 0 through N at the start and end and in between each pair of signs such that all the inequalities are satisfied. Output the resulting string. If there are multiple valid outputs, output any one (and just one) of them.

For example

```
<<><><<

```

has 7 characters so all the numbers from 0 to 7 inclusive must be inserted. A valid output is

```
2<3<4>1<5>0<6<7

```

because all the inequalities taken one at a time

```
2<3
3<4
4>1
1<5
5>0
0<6
6<7

```

are true.

If desired, the output may have spaces surrounding the signs, e.g. `2 < 3 < 4 > 1 < 5 > 0 < 6 < 7`.

**The shortest code in bytes wins.**

## Test Cases

The first line after an empty line is the input and the next line(s) are each valid output examples.

```
[empty string]
0

<
0<1

>
1>0

<<
0<1<2

<>
1<2>0

><
1>0<2
2>0<1

>>
2>1>0

<<<
0<1<2<3

><>
1>0<3>2

>><
3>2>0<1
3>1>0<2
2>1>0<3

>>>
3>2>1>0

>>><<<
3>2>1>0<4<5<6
6>3>1>0<2<4<5
4>2>1>0<3<5<6
4>3>1>0<2<5<6

<<><><<
2<3<4>1<5>0<6<7

>><><>>
7>6>0<5>1<4>3>2

<<<<<<<<<<<<<<
0<1<2<3<4<5<6<7<8<9<10<11<12<13<14

>><<<<><>><><<
6>5>4<7<8<9<10>3<11>2>1<12>0<13<14
14>5>4<7<8<9<10>3<11>2>1<12>0<13<6

```

# Answer
> 32 votes
# Retina, 20 bytes

Byte count assumes ISO 8859-1 encoding.

```

$.'
S`>
%O#`\d+
¶
>
```

Try it online! (The first line enables a linefeed-separated test-suite.)

### Explanation

A simple way to find a valid permutation is to start by inserting the numbers from `0` to `N` in order, and then to reverse the numbers surrounding each substring of `>`s. Take `<><<>>><<` as an example:

```
0<1>2<3<4>5>6>7<8<9
  ---   -------      these sections are wrong, so we reverse them
0<2>1<3<7>6>5>4<8<9

```

Both of those tasks are fairly simple in Retina, even though all we can really work with are strings. We can save an additional byte by inserting the numbers from `N` down to `0` and reversing the sections surrounding `<` instead, but the principle is the same.

**Stage 1: Substitution**

```

$.'
```

We start by inserting the length of `$'` (the suffix, i.e. everything *after* the match) into every possible position in the input. This inserts the numbers from `N` down to `0`.

**Stage 2: Split**

```
S`>

```

We split the input around `>` into separate lines, so each line is either an individual number or a list of numbers joined with `<`.

**Stage 3: Sort**

```
%O#`\d+

```

Within each line (`%`) we sort (`O`) the numbers (`\d#`) by their numerical value (`#`). Since we inserted the number in reverse numerical order, this reverses them.

**Stage 4: Substitution**

```
¶
>

```

We turn the linefeeds into `>` again to join everything back into a single line. That's it.

As a side note, I've been meaning to add a way to apply `%` to other delimiters than linefeeds. Had I already done that, this submission would have been *14* bytes, because then the last three stages would have been reduced to a single one:

```
%'>O#`\d+

```

# Answer
> 27 votes
# \>\<\>, ~~46~~ ~~43~~ 35 + 4 for `-s=` = 39 bytes

```
0&l?!v:3%?\&:n1+$o!
+nf0.>&n; >l&:@

```

This is an implementation of xnor's algorithm in \>\<\>.

It takes the input string on the stack (`-s` flag with the standard interpreter).

You can try it out on the online interpreter.

# Answer
> 25 votes
## \>\<\>, 26 + 4 = 30 bytes

```
l22pirv
1+$2po>:3%::2g:n$-

```

Try it online! +4 bytes for the `-s=` flag - if just `-s` is okay (it would mean that the flag would need to be dropped entirely for empty input), then that would be +3 instead.

Assumes that STDIN input is empty so that `i` produces -1 (which it does on EOF). The program errors out trying to print this -1 as a char.

Uses the max-of-nums-so-far-for-`>`, min-of-nums-so-far-for-`<` approach.

```
[Setup]
l22p         Place (length of stack) = (length of input) into position (2, 2) of
             the codebox. Codebox values are initialised to 0, so (0, 2) will
             contain the other value we need.
i            Push -1 due to EOF so that we error out later
r            Reverse the stack
v            Move down to the next line
>            Change IP direction to rightward

[Loop]
:3%          Take code point of '<' or '>' mod 3, giving 0 or 2 respectively
             (call this value c)
:            Duplicate
:2g          Fetch the value v at (c, 2)
:n           Output it as a number
$-1+         Calculate v-c+1 to update v
$2p          Place the updated value into (c, 2)
o            Output the '<' or '>' as a char (or error out here outputting -1)

```

A program which exits cleanly and does not make the assumption about STDIN is 4 extra bytes:

```
l22p0rv
p:?!;o>:3%::2g:n$-1+$2

```

# Answer
> 16 votes
# CJam, 16 bytes

```
l_,),.\'</Wf%'<*

```

Try it online!

A port of my Retina answer.

### Explanation

```
l    e# Read input.
_,   e# Duplicate, get length N.
),   e# Get range [0 1 2 ... N].
.\   e# Riffle input string into this range.
'</  e# Split around '<'.
Wf%  e# Reverse each chunk.
'<*  e# Join with '<'.

```

# Answer
> 11 votes
# Perl, 29 bytes

Includes +2 for `-lp`

Run with input on STDIN, e.g.

```
order.pl <<< "<<><><<"

```

Output:

```
0<1<7>2<6>3<4<5

```

`order.pl`:

```
#!/usr/bin/perl -lp
s%%/\G</?$a++:y///c-$b++%eg

```

## Explanation

Have two counters, max starting with the string length, min starting with 0. Then at each boundary (including start and end of string) if it is just before a `<` put the minimum there and increase by 1, otherwise put the maximum there and decrease by 1 (at the end of the string it doesn't matter which counter you take since they are both the same)

# Answer
> 10 votes
# Python 2, ~~163~~ 137 bytes

```
from random import*
def f(v):l=len(v)+1;N=''.join(sum(zip(sample(map(str,range(l)),l),v+' '),()));return N if eval(N)or len(v)<1else f(v)

```

Shuffles the numbers until the statement evals to `True`.

Try it.

# Answer
> 10 votes
## Python 2, 67 bytes

```
f=lambda s,i=0:s and`i+len(s)*(s>'=')`+s[0]+f(s[1:],i+(s<'>'))or`i`

```

A recursive function. Satisfies each operator in turn by putting the smallest unused value `x` for `x<` and greatest for `x>`. The smallest unused value is stored in `i` and updated, and the largest unused value is inferred from `i` and the remaining length.

# Answer
> 8 votes
# APL, 33 bytes

```
⍞←(S,⊂''),.,⍨-1-⍋⍋+\0,1-2×'>'=S←⍞

```

`⍋⍋` is unusually useful.

### Explanation

```
⍞←(S,⊂''),.,⍨-1-⍋⍋+\0,1-2×'>'=S←⍞
                                   ⍞ read a string from stdin      '<<><><<'
                                 S←   store it in variable S
                             '>'=     test each character for eq.   0 0 1 0 1 0 0
                         1-2×         1-2×0 = 1, 1-2×1 = ¯1         1 1 ¯1 1 ¯1 1 1
                                      (thus, 1 if < else ¯1)
                       0,             concatenate 0 to the vector   0 1 1 ¯1 1 ¯1 1 1
                     +\               calculate its running sum     0 1 2 1 2 1 2 3
                   ⍋                 create a vector of indices    1 2 4 6 3 5 7 8
                                      that sort the vector in
                                      ascending order
                 ⍋                   do it again: the compound ⍋⍋ 1 2 5 3 6 4 7 8
                                      maps a vector V to another
                                      vector V', one permutation of
                                      the set of the indices of V,
                                      such that
                                            V > V  => V' > V'.
                                             i   j     i    j
                                      due to this property, V and V'
                                      get sorted in the same way:
                                          ⍋V = ⍋V' = ⍋⍋⍋V.
              -1-                     decrement by one              0 1 4 2 5 3 6 7
      ⊂''                            void character vector         ⊂''
    S,                                concatenate input string     '<<><><<' ⊂''
   (     ),.,⍨                       first concatenate each        0 '<' 1 '<' 4 '>' 2 \
                                     element of the result vector  '<' 5 '>' 3 '<' 6 '<' \
                                     with the cordisponding        7 ⊂''
                                     element in the input string,
                                     then concatenate each result
⍞←                                  write to stdout

```

# Answer
> 7 votes
## JavaScript (ES6), ~~74~~ 56 bytes

```
s=>s.replace(/./g,c=>(c<'>'?j++:l--)+c,j=0,l=s.length)+j

```

Starts with the set of numbers `0...N`. At each stage simply takes the greatest (`l`) or least (`j`) of the remaining numbers; the next number must by definition be less than or greater than that. Edit: Saved a massive 18 bytes thanks to @Arnauld.

# Answer
> 6 votes
# Pyth - 19 bytes

Hooray for comparison chaining!

```
!QZhv#ms.idQ.p`Mhl

```

Doesn't work online cuz of eval safety.

# Answer
> 4 votes
# 2sable, 20 bytes

```
gUvy'<Qi¾¼ëXD<U}y}XJ

```

**Explanation**

```
gU                     # store input length in variable X
  v              }     # for each char in input
   y'<Qi               # if current char is "<"
        ¾¼             # push counter (initialized as 0), increase counter
          ëXD<U}       # else, push X and decrease value in variable X
                y      # push current char
                  XJ   # push the final number and join the stack

```

Try it online!

For **N\<10** this could have been 14 bytes:

```
ÎvyN>}J'<¡í'<ý

```

# Answer
> 4 votes
# C#, ~~102~~ 99 bytes

```
string f(string s){int i=0,j=s.Length;var r="";foreach(var c in s)r=r+(c<61?i++:j--)+c;return r+i;}

```

Ungolfed:

```
string f(string s)
{
    int i = 0, j = s.Length;    // Used to track the lowest and highest unused number.
    var r = "";                 // Start with the empty string.

    foreach (var c in s)        // For each character in the input string:
        r = r +                 // Append to the result:
            (c < 61             // If the current character is '<':
                ? i++           // Insert the lowest unused number,
                : j--)          // otherwise, insert the highest unused number.
            + c;                // And append the current character.

    return r + i;               // Return the result with the last unused number appended.
}

```

# Answer
> 4 votes
# Jelly, ~~27 14~~ 12 bytes

Port of @Martin Enders CJam solution
-2 bytes thanks to @Dennis

```
żJ0;µFṣ”<Uj”<

```

Test it at **TryItOnline**

How?

```
żJ0;Fṣ”<Uj”< - main link takes an argument, the string, e.g. ><>
 J           - range(length(input)), e.g. [1,2,3]
  0          - literal 0
   ;         - concatenate, e.g. [0,1,2,3]
ż            - zip with input, e.g. [[0],">1","<2",">3"]
    F        - flatten, list, e.g. "0>1<2>3"
      ”<  ”< - the character '<'
     ṣ       - split, e.g. ["0>1","2>3"]
        U    - upend (reverse) (implicit vectorization), e.g. ["1>0","3>2"]
         j   - join, e.g. "1>0<3>2"

```

Previous method was interesting mathematically, but not so golfy...

```
=”>U
LR!×ÇĖP€S‘
L‘ḶŒ!ị@ÇðżF

```

This uses the factorial base system to find an index of the permutations of \[0,N\] that will satisfy the equation.

# Answer
> 4 votes
# Java 8, ~~126~~ 125 bytes

```
s->{int t=s.replaceAll("<","").length(),y=t-1;String r=t+++"";for(char c:s.toCharArray())r+=(c+"")+(c<61?t++:y--);return r;};

```

I don't think this even works hehe

# Ungolfed test program

```
public static void main(String[] args) {
    Function<String, String> function = s -> {
        int t = s.replaceAll("<", "").length(), y = t - 1;
        String r = t++ + "";
        for (char c : s.toCharArray()) {
            r += (c + "") + (c < 61 ? t++ : y--);
        }
        return r;
    };

    System.out.println(function.apply("<<><><<"));
    System.out.println(function.apply(">>><<<"));
    System.out.println(function.apply(">>>"));
    System.out.println(function.apply("<<<"));
    System.out.println(function.apply(">><><>>"));
}

```

# Answer
> 4 votes
## **Clojure, ~~152~~ ~~132~~ 126 bytes**

```
(defn f[s](loop[l 0 h(count s)[c & r]s a""](if c(case c\<(recur(inc l)h r(str a l c))(recur l(dec h)r(str a h c)))(str a l))))

```

Saved a fair number of bytes by eliminating as much whitespace as I could. I realized whitespace isn't necessary to separate a parenthesis from another character.

Basically a Clojure port of @Scepheo's answer. Works identically.

Those `recur` calls are killer! ~~I suppose I could have used atoms to clean it up.~~ The `swap!` calls required to use atoms added to the count :/

Thanks to @amalloy for saving me a few bytes.

Ungolfed:

```
(defn comp-chain [chain-str]
  (loop [l 0 ; Lowest number
         h (count chain-str) ; Highest number
         [c & cr] chain-str ; Deconstruct the remaining list
         a ""] ; Accumulator
    (if c ; If there's any <>'s left
      (if (= c \<) ; If current char is a <...
        (recur (inc l) h cr (str a l c)) ; Add l to a, and inc l
        (recur l (dec h) cr (str a h c))) ; Add h to a, and dec h
      (str a l)))) ; Add on the remaining lowest number, and return

```

# Answer
> 3 votes
## Haskell, 162 bytes

```
import Data.List
(a:b)%(c:d)=show c++a:b%d
_%[x]=show x
f l=map(l%).filter(l#)$permutations[0..length l]
(e:f)#(x:y:z)=(e!x)y&&f#(y:z)
_#_=0<1
'>'!x=(>)x
_!x=(<)x

```

This is friggin' long.

# Answer
> 3 votes
# Perl (107 + 1 for -p) 108

```
for$c(split''){$s.=$i++.$c;}
for$b(split'<',$s.$i){$h[$j]=join'>',reverse split'>',$b;$j++;}
$_=join'<',@h;

```

Algorithm stolen from Martin Ender♦'s answer

# Answer
> 3 votes
# 05AB1E, ~~13~~ 12 bytes

```
õª€N'<¡íJ'<ý

```

Port of *@MartinEnder*'s CJam answer, so make sure to upvote him as well!
-1 byte thanks to *@Grimmy*.

Try it online or verify all test cases.

**Explanation:**

```
õª            # Append an empty string to the (implicit) input-string as list,
              # which also converts the input-string to a list of characters
              #  i.e. "><>" → [">","<",">",""]
  €N          # Insert the 0-based index before each character in this list
              #  → [0,">",1,"<",2,">",3,""]
    '<¡      '# Split this list on "<"
              #  → [[0,">",1,],[2,">",3,""]]
       í      # Reverse the items of each inner list
              #  → [[1,">",0],["",3,">",2]]
        J     # Join each inner list into a string
              #  → ["1>0","3>2"]
         '<ý '# And join this list of strings with "<" delimiter
              #  → "1>0<3>2"
              # (after which the resulting string is output implicitly as result)

```

# Answer
> 2 votes
# Python 2, ~~176~~ 172 bytes

It's not very short compared to the others, but I'm happy that I solved it so quickly.

```
from itertools import*
def f(s):
 for p in permutations(range(len(s)+1)):
    n=list(s);p=list(p);t=[p.pop()]+list(chain(*zip(n,p)));r="".join(map(str,t))
    if eval(r):return r

```

**Try it online**

Ungolfed:

```
from itertools import*
def f(s):
    n=list(s);R=range(len(s)+1)
    for p in permutations(R):
        p=list(p)
        r=[p.pop()]
        t=n+p
        t[::2]=n
        t[1::2]=p
        r="".join(map(str,r+t))
        if eval(r):return r

```

**Try it online**

# Answer
> 2 votes
## Ruby, 135 bytes

```
g=gets
puts g.nil?? 0:[*0..s=g.size].permutation.map{|a|a.zip(g.chars)*""if s.times.map{|i|eval"%s"*3%[a[i],g[i],a[i+1]]}.all?}.compact

```

Note: Time complexity is large (O(n!)).

# Answer
> 1 votes
# PHP , 190 Bytes

random shuffle till a valid solution exists

```
$x=range(0,$l=strlen($q=$argv[1]));while(!$b){$b=1;$t="";shuffle($x);for($i=0;$i<$l;){$t.=$x[$i].$q[$i];if(($q[$i]==">"&$x[$i]<$x[$i+1])|($q[$i]=="<"&$x[$i]>$x[1+$i++]))$b=0;}}echo$t.$x[$i];

```

381 Bytes get all solutions and pick one

```
<?php $d=range(0,strlen($q=$argv[1]));echo $q."\n";$e=[];function f($t=""){global$e,$d,$q;foreach($d as$z){preg_match_all("#\d+#",$t,$y);if(in_array($z,$y[0]))continue;$p=preg_match_all("#[<>]#",$t);$g="";if(preg_match("#\d+$#",$t,$x)){if(($q[$p]==">"&$x[0]<$z)|($q[$p]=="<"&$x[0]>$z))continue;$g=$q[$p];}strlen($q)==$p+1|!$q?$e[]=$t.$g.$z:f($t.$g.$z);}}f();echo$e[array_rand($e)];

```

# Answer
> 1 votes
# Javascript (node.js), 94 bytes

**Try it online**

```
s=>[[0],...s].reduce((x,v,i)=>v>'<'?[...x.map(v=>v+1),0]:[...x,i]).reduce((x,v,i)=>x+s[i-1]+v)

```

Ungolfed:

```
s =>
  [[0],...s].reduce((x, v, i) =>
    v > '<' ?
      [...x.map(v => v + 1), 0] :
      [...x, i])
    .reduce((x, v, i) => x + s[i-1] + v)

```

# Answer
> 0 votes
# Burlesque, 38 bytes

```
sarzPp{J'>=={PPl_}{PPg_j}x/iePp}]mPP?+

```

Try it online!

Using xnor's algorithm

```
sarz                      # Generate range [0,N_comp]
Pp                        # Push this into state stack
{
 J'>==                    # Non destructive test if is ">"
 {PPl_}{PPg_j}x/ie        # If it is, take the head of the range
                          # Else take the tail
 Pp                       # Push the remainder back to the state stack
}]m                       # Apply to each character and map result to string
PP                        # Take the remaining element from state stack
?+                        # Append it to the string

```

# Burlesque, 61 bytes

```
)'.2co)PIsarzr@{2CO}m[jbcz[{**FL(&&)[+}^m:e!{~]3co{x/}^mgn}m[

```

Try it online!

A method using actually evaluating permutations of ints, longer partially due to trying to format the final answer sensibly.

```
)'.     # Add a "." before each character (.> is comparison in Burlesque)
2co)PI  # Split into comparison operators
sarzr@  # Create all permutations of [0,N_comp]
{2CO}m[ # Create ngrams of length 2 ({abc} -> {ab bc}
jbcz[   # Zip with the operators
{
 **FL   # Merge to form an operation of the form {a b .> b c .<}
 (&&)[+ # Append a bitwise and
}^m     # Apply to each element
:e!     # Filter for those which when evaluated produce true
{
 ~]     # Drop last element (&&)
 3co    # Split into chunks of three
 {x/}^m # Cycle and push each block
 gn     # Delete duplicate consecutive elements
}m[     # Apply to each group

```

# Answer
> 0 votes
# Haskell, 95 bytes

```
s=show
('<':y)!(a:b)=s a++'<':y!b
(x:y)!z=s(last z)++x:y!init z
_!(y:_)=s y
f x=x![0..length x]

```

Try it online!

# Answer
> 0 votes
# PHP, ~~165~~ ~~156~~ 110 bytes

```
$o=[$j=$i=$s=$m=0];for(;$i<strlen($n=$argn);)$o[]=$n[$i++]=='<'?++$m:--$s;for(;$j<=$i;)echo$o[$j]-$s,$n[$j++];

```

Try it online!

## Ungolfed

```
<?php

$min=0;
$max=0;
$current=0;

$order = [0];

for ($i=0;$i<strlen($argn);$i++){
    $compare=$argn[$i];
    if ($compare=='<') {
        $max++;
        $current=$max;
    } else {
        $min--;
        $current=$min;
    }
    $order[] = $current;
}

for ($i=0;$i<=strlen($argn);$i++){
    echo ($order[$i]-$min);
    if ($i<strlen($argn)) echo $argn[$i];
}

```

# Answer
> 0 votes
# Excel (Ver. 1911), 199 Bytes

Using iterative calculation (max iterations set to 1024)

```
B2 'Input
B3 =IF(B3=4^5,1,B3+1)
B4 =B3-1
C2 =SEQUENCE(LEN(B2))
D2 =ROW(C2#:C1)-1
E2 =IF(B4,IF(C2#=B4,IF(F2#=">",@SORT(G2#,,-1),G2),E2#),-C2#)
F2 =MID(B2,C2#,1)
G2 =FILTER(D2#,NOT(MMULT(N(D2#=TRANSPOSE(E2#)),C2#/C2#)))
H2 =CONCAT(E2#:F2#,G2) ' Output

```

### Explanation

```
B2 'Input
B3 =IF(B3=4^5,1,B3+1) ' Keeps track of iteration number
B4 =B3-1 ' 0 index the iteration counter
C2 =SEQUENCE(LEN(B2)) ' Generate sequence to index input string
D2 =ROW(C2#:C1)-1 ' Create sequence [0..N]
E2 =IF(B4,IF(C2#=B4,IF(F2#=">",@SORT(G2#,,-1),G2),E2#),-C2#)
      ' On each iteration check if the current char is ">" pull the largest unused number,
      ' else pull the smallest
F2 =MID(B2,C2#,1) ' Break the input string into separate rows
G2 =FILTER(D2#,NOT(MMULT(N(D2#=TRANSPOSE(E2#)),C2#/C2#))) ' Set of unused numbers
H2 =CONCAT(E2#:F2#,G2) ' Concatenate numbers, gt/lt signs, and last unused number

```

### Test Sample

---
Tags: code-golf, math, arithmetic, permutations, integer
---


# Question
Title: Render a version of the BBC Micro owl logo
Can you render out a version of the BBC Micro Owl logo as per above from code?

Rules:

* You can use any programming language you like.
* Output can be text or graphic.
* Circles don't have to overlap.

Winner:

* The answer with the most upvotes wins.

Kudos for anyone that attempts this in BBC basic.

You can read about the BBC Micro here

# Answer
> 31 votes
# BBC BASIC

I tried using trig functions to draw proper circles, but that was painfully slow. Came up with this instead:

```
10 MODE 1
20 GCOL 0,1 : VDU 19,1,3,0,0,0
30 FOR Y%=0 TO 20
40 READ N% : P%=65536
50 FOR X%=0 TO 16
60 IF (N% AND P%)=0 THEN GOTO 160
70 X0% = X%*32+384 : Y0% = 872-Y%*32
80 FOR DX%=-16 TO 16 STEP 8
90 FOR DY%=-8 TO 8 STEP 8
100 PLOT 69,X0%+DX%,Y0%+DY%
110 NEXT DY% : NEXT DX%
120 FOR DX%=-8 TO 8 STEP 8
130 FOR DY%=-16 TO 16 STEP 32
140 PLOT 69,X0%+DX%,Y0%+DY%
150 NEXT DY% : NEXT DX%
160 P%=P%/2
170 NEXT : NEXT
1000 DATA 87381,33410,69905,10280
1010 DATA 69649,33410,82181,40968
1020 DATA 87377,43520,87297,43520
1030 DATA 21761,10880,5441,2720
1040 DATA 1361,552,1093,43682,1

```

Here's the output:

# Answer
> 10 votes
### GolfScript

```
"!C-DD[5v`>U8G`J2zX['b#L*\\q>FQp "{32-}%96base 2base{"   *"2/=}%18/{""*1>17/~n@n}/

```

The code prints an ascii art version of the logo (run here).

```
* * * * * * * * *
 *     * *     *
*   *   *   *   *
   * *     * *
*   *       *   *
 *     * *     *
* *     *     * *
 * *         *
* * * * * * *   *
 * * * *
* * * * *       *
 * * * *
  * * * *       *
   * * * *
    * * * *     *
     * * * *
      * * * *   *
       *   * *
      *   *   * *
 * * * * * *   *
                *

```

# Answer
> 7 votes
# Mathematica

Nothing but grunt work.

```
w = 20; h = 25; r = .7; r2 = .2; t = Table; d = Disk;
owl = Graphics[{Polygon[{{0, 0}, {w, 0}, {w, h}, {0, h}}],
   ColorData[57, 4],
   t[d[{k, 22}, r], {k, 2, 19, 2}],
   t[d[{18, k}, r], {k, 2, 21, 2}],
   t[d[{k, #}, r], {k, #2}] & @@@ {{21, {3, 9, 10, 11, 17}}, {20, {2,
       6, 10, 14, 18}},
     {19, {5, 6, 7, 13, 14, 15}}, {18, {6, 9, 11, 14}}, {17, {10,
       17}, {16, {16}}, {15, {15}}, {14, {8, 10, 12, 14}},
      {13, {9}}, {12, {9}}}},
   t[d[{# - k, k}, r], #2] & @@@ {{20, {k, 18, 3, -1}}, {19, {k, 16,
       6, -1}}, {18, {k, 16, 5, -1}}, {17, {k, 14, 7, -1}}, {16, {k,
       14, 6, -1}}, {14, {k, 11, 5, -1}}, {14, {k, 12, 5, -1}}},
   t[d[{k, 4}, r], {k, {8, 12}}],
   t[d[{k, 3}, r], {k, 3, 13, 2}],
   d[{8, 13}, r],
   Black, d[{10, 21}, r2], d[{8, 13}, r2], d[{9, 12}, r2],
   t[d[{19 - k, k}, r2], {k, 16, 6, -1}],
   t[d[{17 - k, k}, r2], {k, 14, 7, -1}],
   t[d[{15 - k, k}, r2], {k, 12, 6, -1}],
   t[d[{k, 19}, r2], {k, {6, 14}}]}, ImageSize -> 220]

```

# Answer
> 7 votes
### R

```
image(t(matrix(as.integer(sapply(c(1397760,567810,1070336,141954,1381696,133794,
                                   1054036,559786,1332560,557218,1052756,131114,
                                   1380368,139272,1064964,557058,1398101),
                                   intToBits)[1:21,]),nr=21)),ax=F)

```

Results in:

Basically the idea is to take the base-2 representation of the 17 numbers (1397760, 567810, 1070336, 141954, 1381696, 133794, 1054036, 559786, 1332560, 557218, 1052756, 131114, 1380368, 139272, 1064964, 557058 and 1398101), make it into a 21x17 matrix of 1 and 0s and plot the matrix as is.

# Answer
> 7 votes
# Pov-Ray

```
background{color<.14,.01,.01>}
camera{orthographic location z*-2 up y*24 right x*20}
#macro s(X,Y)sphere{<X,Y,0>,1.07,2.6}#end
#declare b=array[17]{1397760,567810,1070336,141954,1381696,133794,1054036,
559786,1332560,557218,1052756,131114,1380368,139272,1064964,557058,1398101}
blob{threshold 0.9 #for(j,0,16,1)#declare V=b[j];#for(i,0,28,1)
#if(mod(V,2))s(j-8,i-10)#end #declare V=floor(V/2);#end #end
pigment{color<1,1,.8>}finish{ambient 1}}

```

'compile' with `povray +Ibbc.pov -Obbc.png +A0.1 +R9 -W240 -H285`

# Answer
> 6 votes
## Bash

Since you didn't specify no external resources...

```
curl -s http://codegolf.stackexchange.com/questions/19214/render-a-version-of-the-bbc-micro-owl-logo | grep '* * *' | sed -n '/code>\*/,/<pre>/p' | sed '$d' | sed 's/<pre><code>//'

```

Howard - stole your Ascii art, thanks.

**Or** after I uploaded it here -

```
curl -s http://textuploader.com/1ojd | sed -n '/<code/,/<\/code>/p' | sed 's/<[^>]\+>//g'

```

# Answer
> 6 votes
# BBC Basic, random colours, golfed!

149 characters. I'm not that big on golfing (I prefer the code challenges) but I liked the ridiculousness of golfing in BBC basic. BBC emulator at http://www.bbcbasic.co.uk/. Runs in screen mode 6 at the command line.

FORK=6TO185S=K MOD9=5VDU-32\*(K MOD18=15),17,128+RND(6)\*(ASCMID$("?OSUuLEMSS^H?=A\_W",K/6,1)/2^(K MOD6)AND1),32,17,128,32,-13\*S,-10\*S:NEXT

Explanation (ungolfed version)

No IF statements, because the rest of the line would only be executed if the IF was true (so to ensure the NEXT was reached I would have to do a program with line numbers.) Therefore I made a lot of use of ASC(null character)=0 to control output. Also, I had to cut off the pixel at the bottom right corner to fit the whole command line on the screen after printing (and that saved 2 characters.

I love how BBC basic can recognise an identifier after FOR, even with no white space. FORE, FORD, FORK, FORM, FORS, FORT :-)

```
 FOR K=6 TO 185

     REM Set S to true(-1) if K mod 9 = 5, otherwise set S to false(0)

     S = K MOD 9=5

     REM If K mod 18 = 15, send asc(space)=32 to the VDU controller,otherwise send 0.
     REM This causes staggering every 2 lines.

     VDU-32*(K MOD18=15)

     REM Vdu 17 for colour. foreground colours start at 0, background colours at 128.
     REM Rnd(6) to choose a bright color. Multiply by the horrible expression.
     REM The horrible expression evaluates to 1 if the pixel is to be printed, 0 if not.
     REM Picture data is stored in base 64 in the string.
     REM MID$ extracts the characters in order.
     REM The FOR loop starts at K=6 so that this will work properly.
     REM Extracted character SHR ((K mod 6)) AND 1 to decide to
     REM colour pixel or not. BBC basic does not have SHR operator.
     REM so we divide by 2^(K mod 6) instead.

     VDU 17,128+RND(6)*
      (ASC(MID$( "?OSUuLEMSS^H?=A_<A^tC|dGxEMh>W" ,K/6,1))/2^(K MOD 6)AND 1)

     REM Print a space in the new background colour

     VDU 32

     REM Change background colour back to black

     VDU 17,128

     REM Print another space

     VDU 32

     REM If S is true (-1) print a carriage return and linefeed. otherwise two 0's

     VDU -13*S,-10*S

 NEXT

```

# Answer
> 4 votes
## C

ASCII output.

```
x[]={256,191,424,104,376,60,316,30,286,15,287,15,383,67,403,153,325,102,341,153,511};i=20;mai
n(){for(;i>=0;i--){i&1&&putchar(32);while(x[i]){putchar(x[i]&1?42:32);x[i]>>=1;putchar(32);}pu
tchar(10);}}

```

Code output:

```
* * * * * * * * *
 *     * *     *
*   *   *   *   *
   * *     * *
*   *       *   *
 *     * *     *
* *     *     * *
 * *         *
* * * * * * *   *
 * * * *
* * * * *       *
 * * * *
  * * * *       *
   * * * *
    * * * *     *
     * * * *
      * * * *   *
       *   * *
      *   *   * *
 * * * * * *   *
                *

```

# Answer
> 4 votes
# JavaScript - 326 307 285 characters (ASCII)

```
a=[1716886015,1133746501,253693823,1010572830,3215485048,0];s="";with(Math)
for(y=0;44>y;y++,s+="\n")for(x=0;90>x;x++,s+="#8*+=:-. "[min(floor(d),8)])
for(j=d=0;22>j;j++)for(i=0;9>i;i++)1==((8==i?j+1:a[floor(j/4)]>>i+j%4*8)&1)
&&(d+=50/pow(pow(x-10*(i+j%2/2)-4,2)+pow(2*y-4*j-4,2),1.5));s;

```

Probably not the shortest code. I tried to be as close as possible to the original logo, using only ASCII.

To execute : copy paste to javascript console (eg: chrome or firefox). Note : the script might take a little time to run so if nothing come just after pressing enter, be a little patient.

# Answer
> 4 votes
# CoffeeScript

Code isn't golfed. It uses some metaballs-ish algorithm to simulate "stickyness" of the circles. ASCII owl was shamelessly stolen from other answers :)

```
canvas = document.createElement 'canvas'
canvas.style.backgroundColor = '#240202'
canvas.style.transform = 'scale(0.5) translate(-480px,-570px)'
W = canvas.width = 960
H = canvas.height = 1140
D = 50
R = D / 2
ctx = canvas.getContext '2d'
imageData = ctx.getImageData 0, 0, W, H
data = imageData.data
owl = '''

\ * * * * * * * * *
\  *     * *     *
\ *   *   *   *   *
\    * *     * *
\ *   *       *   *
\  *     * *     *
\ * *     *     * *
\  * *         *
\ * * * * * * *   *
\  * * * *
\ * * * * *       *
\  * * * *
\   * * * *       *
\    * * * *
\     * * * *     *
\      * * * *
\       * * * *   *
\        *   * *
\       *   *   * *
\  * * * * * *   *
\                 *
'''.split '\n'

insideDot = (x, y) ->
  w = 0
  for du in [-1..1] then for dv in [-1..1]
    u = x // D + du
    v = y // D + dv
    continue unless owl[v]?[u] is '*'
    dx = x - (u * D + R)
    dy = y - (v * D + R)
    d = dx * dx + dy * dy
    w += 1 / (d * d)
    return yes if w > 0.0000008
  no

for y in [0...H] then for x in [0...W] when insideDot x, y
  i = (y * W + x) * 4
  data[i] = data[i+1] = data[i+3] = 255
  data[i+2] = 214

ctx.putImageData imageData, 0, 0
document.body.appendChild canvas

```

Watch it destroy the coffeescript.org documentation (hit Run):

# Answer
> 3 votes
**BBC Basic+GXR**

Very late to this but: the 'bbcmicrobot' account on twitter which runs progs\<280 chars or so added the Acorn GXR ROM, allowing drawing circles and ellipses. I thought, what could I draw with a couple of circles? And this came to me. It's based in part on the answer by @Level River Street, tho I've used abbreviated basic commands, used bit testing instead of SHR and changed the bit representation:

```
2MO.2:P."HOW TO DRAW AN OWL":MOV.200,700:PL.&91,120,0:MOV.250,450:PL.0,-200,0:PL.&C1,155,250:V.29,640;130;
5F.G=0TO188:Z=(G MOD18)>8:X=G MOD9*2-Z:Y=G DIV18*2-Z
6IFASC(MID$("@|WhFMxeG|tC^|A_|A?]HSNSEuLUMS?G",(G+6)DIV6,1))AND2^(G MOD6) MOV.X*36,Y*36:PL.&99,24,0
8N.G

```

My original tweet is here

# Answer
> 2 votes
**PHP**

Building upon the ascii art versions of the logo submitted previously and using this as the array to render a graphical version using the GD library.

```
$circleWidth = 34;
$circleHeight = 34;
$movement = 24;
$canvasWidth = 480;
$canvasHeight = 570;
$image = imagecreatetruecolor($canvasWidth, $canvasHeight);
$backgroundColour = imagecolorallocate($image, 36, 2, 2);
ImageFillToBorder($image, 0, 0, $backgroundColour, $backgroundColour);
$circleColour = imagecolorallocate($image, 255, 255, 214);
$coordinates ='
* * * * * * * * *
 *     * *     *
*   *   *   *   *
   * *     * *
*   *       *   *
 *     * *     *
* *     *     * *
 * *         *
* * * * * * *   *
 * * * *
* * * * *       *
 * * * *
  * * * *       *
   * * * *
    * * * *     *
     * * * *
      * * * *   *
       *   * *
      *   *   * *
 * * * * * *   *
                * ';
$coordinates = str_split($coordinates);
$coordinateX = $movement;
$coordinatY = $movement;
$i=1;
foreach ($coordinates as $coordinate) {
    if ($i < 19) {
        if ($coordinate == '*') {
            ImageFilledEllipse($image, $coordinateX, $coordinatY, $circleWidth, $circleHeight, $circleColour);
        }
        $coordinateX = $coordinateX + $movement;
        $i++;
    } else {
        $i=1;
        $coordinateX = $movement;
        $coordinatY = $coordinatY + $movement;
    }
}
header("Content-type: image/png");
imagepng($image);
imagedestroy($image);

```

Results in:

---
Tags: popularity-contest, graphical-output
---