title: Print My Block Schedule

text:
# Question
Title: Print My Block Schedule
My high school, and many others implement a type of schedule called a Rotating Block Schedule. This is a way for people to have 8 classes, but on have 6 periods in a school day.

There are four days in a block schedule that repeat over and over, and have nothing to do with the actual days of the week. Each are assigned a number `[1-4]`.

The way the schedule works is that you list all your morning classes, periods `1-4`: `[1, 2, 3, 4]`. This is your schedule for the first day, or Day 1. The rest of the days just rotate the list: `[2, 3, 4, 1]` , `[3, 4, 1, 2]`, `[4, 1, 2, 3]`.

However, the last period in the morning is "dropped" and you don't see that teacher that day. Hence the days are: `[1, 2, 3]`, `[2, 3, 4]`, `[3, 4, 1]`, `[4, 1, 2]`.

The afternoon is the same, except that it uses periods `5-8` instead: `[5, 6, 7]`, `[6, 7, 8]`, `[7, 8, 5]`, `[8, 5, 6]`.

## Your task

All this rotating is hard to keep track of, so you have to write a program to print out my schedule given what day it is as input. Your code has to place Homeroom and Lunch in the correct spots. Here is the **exact** output your code needs to have for inputs `1-4`:

```
Homeroom    Homeroom    Homeroom    Homeroom
Period 1    Period 2    Period 3    Period 4
Period 2    Period 3    Period 4    Period 1
Period 3    Period 4    Period 1    Period 2
Lunch       Lunch       Lunch       Lunch
Period 5    Period 6    Period 7    Period 8
Period 6    Period 7    Period 8    Period 5
Period 7    Period 8    Period 5    Period 6

```

# But Wait - One more thing!

Sometimes, on the first day of school, or on other special days, my school has a "Day 0". This just means that I will have *all* my classes that day along with homeroom and lunch. Your code will have to deal with Day 0's. Here is the output for a Day 0:

```
Homeroom
Period 1
Period 2
Period 3
Period 4
Lunch
Period 5
Period 6
Period 7
Period 8

```

This is so shortest code in **bytes** wins!

# Answer
> 3 votes
## Snowman 1.0.2, 190 bytes

```
}vg10sB*:#NdE*!1*"Homeroom
"sP0vn3nR:|%+#nA4NmO'"Period "sP'!#nAtSsP"
"sP|%;ae|"Lunch
"sP5*|ae;:"Homeroom
"sP0vn4nR*#:`"Period "sP`NiNtSsP"
"sP;aE"Lunch
"sP#:`"Period "sP`5nAtSsP"
"sP;aE;#bI

```

That leftmost column actually looks pretty nice, doesn't it?

...

... who am I kidding, I'd rather program in PHP than this.

"Readable" version:

```
}vg10sB*   // store day # in permavar
// big if statement coming up, depending on whether the input (n) is 0 or not

// THE FOLLOWING BLOCK IS FOR N != 0
:

#NdE*      // decrement number (because we like 0-based indeces) and re-store
!1*        // store the number 1 in permavar ! for later
"Homeroom
"sP        // print "Homeroom"
0vn3nR     // generate [0 1 2]
// for each element in this array...
:
    |%            // shuffle around some variables so we have room
    +#nA          // add day number (in permavar +)
    4NmO          // modulo by 4
    '"Period "sP  // print "Period "
    '!#nAtSsP     // add whatever is in permavar ! and print
    "
"sP               // print a newline
    |%            // return variables to their original state
;ae
// this is a rare occasion in which we use "ae" instead of "aE"
// we use non-consume mode here because we need the block again
// since we've used a permavar ! to determine what to add to the period number,
//   we can set the permavar to 4 more than it used to be and run the same
//   exact block
|"Lunch
"sP        // print "Lunch"
5*         // store the number 5 in permavar !, as described above
|ae        // run the same block over the same array again

;

// THE FOLLOWING BLOCK IS FOR N == 0

:

// after much frustration, I have determined that the easiest way to go about
//   this is to simply code the "day 0" separately
// yes, snowman is *that* bad
"Homeroom
"sP           // you know the drill
// for each number in [0 1 2 3]
0vn4nR*#:
    `"Period "sP
    `NiNtSsP  // increment and print
    "
"sP
;aE
"Lunch
"sP           // same stuff from here
// only interesting thing is we saved the range from before with *#, so we can
//   get it back easily
#:`"Period "sP`5nAtSsP"
"sP;aE

;

#bI

```

Thoughts and musings:

* Firstly, I definitely need to implement a prettier way of printing newlines. Because strings with newlines in an indented block are super ugly.
* I like my trick with `ae`—you rarely see the `ae` operator without the `E` capitalized in real Snowman code. (You also rarely see Snowman code that's not written by me, but that's besides the point.)

For the uninitiated, Snowman has two ways to call operators. "Consume" mode, and "non-consume" mode. "Consume" mode will call the operator with the variables requested and then discard the variables. Non-consume mode will call the operator and still leave the variables intact.

Which is usually not what you want with `ae` (array-each), because the block you're calling on each element will stay there and get in your way, using up a precious one of the eight variables.

However, this is a rare situation in which `ae` *is* actually what we want (see the comments in the code for further explanation).
* I'm really, really starting to think that Snowman needs more than two modes, other than just "consume" and "do-not-consume." For example, with `aa` (basically array indexing), you only get two ways to call it:

```
["foo" 0] -> ["f"]
["foo" 0] -> ["foo" 0 "f"]

```

(Snowman doesn't use a stack/array structure, but that's simply being used for clarity here.)

It's pretty common that you want `["foo" "f"]` (i.e. consume the index variable, but not the original one). It's a super convoluted process to get rid of that annoying `0` if you use "do-not-consume" mode.

A similar thing happens when you call "array-each" in "do-not-consume" mode, as is done here. The array and the block stick around, *even **during** the execution of said block*. Which is... really, really weird.

Then again, the design goal of Snowman is to be as confusing as possible, so I'm not sure whether this is a problem at all.

# Answer
> 2 votes
# CJam, ~~65~~ 55 bytes

```
ri_5,m<0-_W<\?_4f+]"HomeroomLunch"8/.{N@{"Period "\N}%}

```

Try it online in the CJam interpreter.

# Answer
> 1 votes
# Python 3, ~~193~~ ~~192~~ ~~182~~ ~~168~~ 165 bytes

```
u=int(input())
print('Homeroom')
r=['Period '+i for i in("123567234678341785412856"[(u-1)*6:u*6]if u else"12345678")]
r.insert(len(r)//2,'Lunch')
for i in r:print(i)

```

Just a quick solution.

# Python 2, 161 bytes

```
u=int(input())
print'Homeroom'
r=['Period '+i for i in("123567234678341785412856"[(u-1)*6:6*u]if u else"12345678")]
r.insert(len(r)//2,'Lunch')
print'\n'.join(r)

```

# Answer
> 0 votes
# Pyth, 51 bytes

```
"Homeroom"j"Lunch
"c2jb+L"Period "+J?QP.<S4tQS4+L4J

```

---
Tags: code-golf, sequence
---


title: Also want my cake

text:
# Question
Title: Also want my cake
## Introduction

Today is my birthday,

Yes my parents spend a lot time at home during the cold December **holidays** as many **others**.

So I also want my cake.

But I have a problem: I just sent the invitations today so I'm not sure how many friends will come. Also I don't want to order a big cake because I have been on a diet since last year and don't want to keep temptation leftovers in the fridge.

## Challenge

Write a full program to output the cake design so my baker prepares just *enough* cake for everyone.

Input Integer `1 <= n <= 999`. Worst case I eat my cake **alone**.

* Each slice will have a unique label number `1 .. n` sequenced left to right, then top to bottom.
* Write in the middle line and align center the best way you can.
* Slice size is a square of 3x3 (this is why upper limit is 999).
* `*` indicate where to cut each slice.

## Output

n = 1 =\> Side = RoundUP(sqrt(1)) = 1

```
*****
*   *
* 1 *
*   *
*****

```

n = 3 =\> Side = RoundUP(sqrt(3)) = 2

```
*********
*   *   *
* 1 * 2 *
*   *   *
*********
*   *
* 3 *
*   *
*****

```

n = 5 =\> Side = RoundUP(sqrt(5)) = 3

```
*************
*   *   *   *
* 1 * 2 * 3 *
*   *   *   *
*************
*   *   *
* 4 * 5 *
*   *   *
*********

```

n = 10 =\> Side = RoundUP(sqrt(10)) = 4

```
*****************
*   *   *   *   *
* 1 * 2 * 3 * 4 *
*   *   *   *   *
*****************
*   *   *   *   *
* 5 * 6 * 7 * 8 *
*   *   *   *   *
*****************
*   *   *
* 9 * 10*
*   *   *
*********

```

## Winning

Shortest code in bytes wins.

# Answer
> 1 votes
# Python 2, ~~241~~ ~~239~~ 237 bytes

```
i=input()
s=int(round(i**.5+.5))
q="*"*5;p="*   *"
v=lambda x,y:"\x1b[%d;%dH".join(["",q,p,"*{}*",p,q])%tuple(i for j in zip(range(x*4+1,x*4+6),[y*4+5]*5)for i in j)
print"".join([v(j/s,j%s).format(`j+1`.center(3," "))for j in range(i)])

```

Lots of ANSI goodness...

Defines a function for drawing a box at a position on the screen.

Then calls it with the relevant positions that are in the cake.

Finally adds the numbers using `str.format()` and `str.center`

NOTE: If your terminal isn't big enough to display everything at once, it will get 'cropped' and you won't be able to see anything past the last row.

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


title: Where did you COME FROM?

text:
# Question
Title: Where did you COME FROM?
INTERCAL is a wonderful language, but it is not always easy to understand other people's code. This is particularly the case if they use the COME FROM statement.

# Challenge definition

1. Write a **program** or **function** which take the source code of an INTERCAL program as a text/data stream. If you write a function it is recommended that you also provide a program to call the function, but it will not count towards your score.
2. The function output will be a text/data stream of the jumps that program makes, according to the following instructions. The output *does not* need to be printed, but it does need to be a single text, not an array of strings (for example).
3. Each line of output will consist of the statement which will be COME FROM and the line number of its COME FROM statement, separated by a `->`. An example:

```
(310)   DO .4 <- .3 -> 55

```
4. You can trim these lines of source code, but it is not necessary to.
5. The test cases will only consist of noncomputed labels (i.e., integer labels).
6. The output must be sorted by the source code order of the statements which will be COME FROM, not their label, nor the order of the COME FROM statements or their labels.
7. It is possible for multiple statements to COME FROM the same label. In such cases the COME FROM line numbers must be sorted, and separated by commas.
8. It is possible for a statement to COME FROM itself.
9. A COME FROM statement may be prefixed with a NOT statement. In such cases the line number must be wrapped in square brackets.
10. The words COME FROM can appear in a comment and must be ignored. You do not need to fully parse the file: if they are followed by a label (a number in parentheses) then you can assume it is a real statement.

# Scoring

Entrants will be scored by the **character length** of their program or function.

# Test cases

These test cases all come from the calvinmetcalf/intercal Github repo. Although any useful application will safely accept any input, for the purposes of this challenge you need only account for these five test cases.

**rot13.i**

```
(10) PLEASE DON'T GIVE UP -> 87
(33) DON'T GIVE UP -> 92

```

**primes.i**

```
(15)    DO (13) NEXT -> 26
(16)    DO .12 <- .1 -> 6
(23)    DO (21) NEXT -> 3

```

**unlambda.i**

```
(7202)  DO RETRIEVE .203+,202 -> 75
(4202)  DO ,202SUB.201.202#7 <- ,201SUB.201.202#7 -> 108
(6202)  DO ,201SUB.201.202#7 <- ,202SUB.201.202#7 -> 117
(4203)  DO READ OUT ,201SUB.201.202#7 -> 133
(4302)  DO .302 <- .2 -> 181
(5410)  DO ,400SUB#124 <- #4 $ #17 -> 293
(3410)  PLEASE (4410) NEXT -> 288
(5402)  DO (412) NEXT -> 328
(4412)  PLEASE (3412) NEXT -> 334
(3423)  DO FORGET #2 -> 375
(4404)  DO RETRIEVE .311+.312 -> 411
(5404)  PLEASE DO (414) NEXT -> 430
(4434)  DO FORGET #1 -> 441
(3454)  DO (103) NEXT -> 451
(5502)  DO .512 <- .312 -> 520
(8503)  PLEASE RETRIEVE .311+.312 -> 621
(7503)  DO (302) NEXT -> 515
(3622)  DO (302) NEXT -> 514
(603)   PLEASE FORGET #2 -> 622

```

**pass.i**

```
(10)    DO  NOTHING -> 5, 11
(20)    PLEASE  (100) NEXT -> 6
(30)    PLEASE  (200) NEXT -> 12
(103)   DO  (104) NEXT -> 27
(104)   DO  (105) NEXT -> 19
(1) DO  (2) NEXT -> 36
(2) DO  (105) NEXT -> 194
(202)   DO NOT  .2 <- #2 AGAIN -> [196]
(203)   DO  (204) NEXT -> 167
(204)   DO  (205) NEXT -> 159

```

**continuation.i**

```
(8201)  DO NOTHING -> 165, 271
(8202)  PLEASE NOTE Fork threads, one dormant, one alive -> 53, 58
(8211)  DO COME FROM (8211) -> 60
(8216)  DO NOTHING -> 71
(8215)  DO NOTHING -> 68
(8217)  DO COME FROM (8217) AGAIN -> 118
(8299)  DO COME FROM (8299) AGAIN -> 141
(8274)  DO (8273) NEXT ONCE -> 158
(8259)  PLEASE DO NOTHING -> 166
(8276)  DO COME FROM (8276) AGAIN -> 199
(8278)  PLEASE DO COME FROM (8278) AGAIN -> 237

```

# Answer
> 2 votes
# JavaScript, 232 bytes

```
function c(d){for(var l,o,f,c,p=/^.(\d+).+?$/gm,a=/(T\s+)?C.{7}M .(\d+)/g,r='';l=p.exec(d);)for(f=0;o=a.exec(d);)o[2]==l[1]&&(c=d.slice(0,o.index).split('\n').length,r+=f++?', ':'\n'+l[0]+' -> ',r+=o[1]?'['+c+']':c);return r.trim()}

```

To be called with

```
var data = require( 'fs' ).readFileSync( process.argv[2] ).toString();
console.log( c( data ) );

```

Explanation

```
function c(d){
    for(
        // Initialise variables
        var l,o,f,c,p=/^.(\d+).+?$/gm,a=/(T\s+)?C.{7}M .(\d+)/g,r='';
        // Find lines beginning with a label
        l=p.exec(d);)
            for(
                // Reset a have-we-output-this-line flag
                f=0;
                // Find CALL FROM statements
                o=a.exec(d);)
                    // Filter to CALL FROM statements which have the current line
                    o[2]==l[1]&&(
                        // Calculate the line number of this CALL FROM statement
                        c=d.slice(0,o.index).split('\n').length,
                        // Concat the output for this line
                        r+=f++?', ':'\n'+l[0]+' -> ',r+=o[1]?'['+c+']':c);
    // Trim an initial new line
    return r.trim()}

```

---
Tags: code-golf, parsing
---


title: Recursive ASCII Spirals

text:
# Question
Title: Recursive ASCII Spirals
> This competition is over. Thanks for the interesting non-esolang entries, and congrats to Jakuje for his winning JavaScript submission.

In the great tradition of ASCII Art Challenges on this site, here's another one. Given an input, draw a spiral.

```
&>----v
||>--v|
|||>v||
|||@|||
||^-<||
|^---<|
^-----<

```

Simple, yeah? Heh, heh, heh ... Yeah...

(Inspired by the ASCII Dragons Curve post, and Optimizer's ASCII Art of the Day posts)

### Input

Input will be in the form of a series of parameters, taken from the usual STDIN/function argument/etc., whatever your language equivalent, comprised of four parts. These parts can be four separate arguments, a quadruple, an array of size 4, etc. For simplicity and consistency throughout the challenge, I will represent the input as a single word.

* An integer `2 ≤ x ≤ 20` that specifies the size of the spiral in terms of "squares" with each printed character representing one "square" in size. Theoretically this could be enormous in scope, but given that we're drawing ASCII art, a safe upper limit on this will be 20 so that it fits somewhat decently on screen.
* A single letter of `d u r` or `l`, indicating the initial movement from the starting "square" (down, up, right, left).
* An optional `c`, indicating "counter-clockwise." If the `c` is omitted, assume clockwise rotation for the spiral.
* A final integer `1 ≤ y ≤ 10` that specifies how many times to recurse the spiral drawing, using the finish "square" of the previous spiral as the starting "square" of the new one. I'm picking an upper limit of 10 because I want the drawing to finish at some point.
* A few example inputs: `20lc5` `13d2` `2rc1`

Of interest, do note that odd values for the size input will result in the `@` always being the exact center of a spiral, but even values may have the starting "square" offset in any of the four diagonal directions, dependent upon the direction of initial travel. This can result in some ... interesting ... patterns. See the two even examples below.

Input that doesn't follow the input specification (e.g., `11q#s`) is undefined and I fully expect the program to barf appropriately. :)

### Output

Output is an ASCII printable output via language-equivalent STDOUT, with the following specifications:

* The starting "square" (of each recursion) must be marked with an at-sign `@`.
* The final "square" must be marked with an ampersand `&`. In the case of multiple recursions, only the very final "square" should be marked `&`.
* Corners of the spiral path need to "point" in the direction of travel, using `< > v ^`.
* Vertical travel need to be drawn by pipes `|`.
* Horizontal travel needs to be drawn with dashes `-`.
* "Squares" that are overwritten by later recursions should display the most-recent direction of travel. This will result in "newer" recursions seeming to be layered on top of the "older" recursions. See the `4rc3` example below.
* A final trailing newline is OK, leading spaces could be a must and so are allowed, but trailing spaces are not allowed.
* I won't dock you if you use escape sequences to draw the ASCII art going to STDOUT, but I will be silently disappointed in you. (You'll still be eligible for the bounty if you use them)

### Examples

`2d4` = diameter of 2, starts by going down, clockwise, 4 recursions

```
&@@@@
^<<<<

```

In this example, the drawing starts in the upper-right `@`, goes down one, left one, up one. At this point, we've finished the `2d` portion, and so start the 2nd recursion, so we have another `@`, down one, left one, up one; then the 3rd recursion; then the 4th and finally our `&`.

`4rc3` = diameter of 4, starts by going right, counter-clockwise, 3 recursions

```
&--<
v-<|
|@^|<
>--^|
 |@^|<
 >--^|
  |@^|
  >--^

```

In this example, the drawing starts in the bottom `@`, goes right one, up one, spirals around, until it reaches the middle `@` and finishes the `4rc` portion. This then repeats two more times to get the full 3 recursions requested. Note that `4rc1` would be just the upper-left 4x4 block of this example.

`7u1` = diameter of 7, starts by going up, clockwise, 1 recursion (note the is the same as the intro)

```
&>----v
||>--v|
|||>v||
|||@|||
||^-<||
|^---<|
^-----<

```

### Winning & Restrictions

This is Code Golf, so smallest answer in bytes wins. Submissions should be in the usual form of program/function/CJam Code Block/etc. Standard Loophole Restrictions Apply. Professional driver on closed course. If irritation persists, discontinue use and consult your doctor.

# Answer
# Javascript, ~~578~~, ~~575~~, ~~553~~, ~~478~~, 377 Bytes

After the beaten Lua I switched to some more compact language and moved competition to Javascript:

```
s=function(w,d,c,r){d="dlur".indexOf(d)
j=i=G=H=I=J=w*r;o=[];for(x=0;x<J*2;x++){o[x]=[]
for(y=0;y<J*2;)o[x][y++]=' '}for(;r--;){a=d;m=l=z=1;o[i][j]="@"
for(k=w*w-1;k--;){G=G<i?G:i;H=H>i?H:i;I=I<j?I:j;J=J>j?J:j
o[i+=(1-a)%2][j+=a?a-2:0]=l++==m?(a+=c=="c"?3:1,m+=z=!z,l=1,"v<^>"[a%=4]):k?"|-"[a%2]:"&"}}for(i=G;i<=H;)console.log(o[i++].slice(I,J+1).join("").replace(/\s+$/g,''))}

```

Algorithm is the same, but written in more more compact language so I managed to beat the evil Lisp :)

*Edit: Some structural changes were needed to reach under Lisp again and to eliminate trailing whitespaces. But we are here again.*

*Edit2: Some abstractions taken into account to get under 500. Hope it will be enough :)*

*Edit3: Thanks @Timwi, the code is another 100 chars slimmer. I didn't update the explanation yet.*

Tests (online version, tested in Chrome):

```
----| 2d4 |---
s.js:9 &@@@@
s.js:9 ^<<<<
ss.html:7 ----| 4rc3 |---
s.js:9 &--<
s.js:9 v-<|
s.js:9 |@^|<
s.js:9 >--^|
s.js:9  |@^|<
s.js:9  >--^|
s.js:9   |@^|
s.js:9   >--^
ss.html:9 ----| 7u1 |---
s.js:9 &>----v
s.js:9 ||>--v|
s.js:9 |||>v||
s.js:9 |||@|||
s.js:9 ||^-<||
s.js:9 |^---<|
s.js:9 ^-----<
ss.html:11 ----| 8r3 |---
s.js:9       >------v
s.js:9       |>----v|
s.js:9       ||>--v||
s.js:9       |||@v|||
s.js:9    >------v|||
s.js:9    |>----v|<||
s.js:9    ||>--v||-<|
s.js:9    |||@v|||--<
s.js:9 >------v|||
s.js:9 |>----v|<||
s.js:9 ||>--v||-<|
s.js:9 |||@v|||--<
s.js:9 ||^-<|||
s.js:9 |^---<||
s.js:9 ^-----<|
s.js:9 &------<
ss.html:13 ----| 8rc3 |---
s.js:9 &------<
s.js:9 v-----<|
s.js:9 |v---<||
s.js:9 ||v-<|||
s.js:9 |||@^|||--<
s.js:9 ||>--^||-<|
s.js:9 |>----^|<||
s.js:9 >------^|||
s.js:9    |||@^|||--<
s.js:9    ||>--^||-<|
s.js:9    |>----^|<||
s.js:9    >------^|||
s.js:9       |||@^|||
s.js:9       ||>--^||
s.js:9       |>----^|
s.js:9       >------^

```

And to be fair, there is fair explanation:

```
s = function(w, d, c, r) {
    // width, direction, "c" as counter-clockwise and number of repetition
    // transfer direction to internal numerical representation
    d=d=="d"?0:d=="u"?2:d=="l"?1:3;
    // output strings
    x="v<^>"
    y="|-"
    // this is size of our canvas. Could be smaller, but this is shorter
    M = w * r * 2;
    // fill canvas with spaces to have something to build upon
    o = [];
    for (i = 0; i < M; i++) {
        o[i] = [];
        for (j = 0; j < M; j++)
            o[i][j] = ' '
    }
    // i,j is starting position
    // G,H,I,J are current boundaries (maximum and minimum values of i and j during the time)
    j = i = G = H = I = J = M / 2
    for (q = 0; q < r; q++) { // number of repeats
        a = d; // reset original direction
        // m is the expected length of side
        // l counts the of current side length
        m = l = 1;
        z = 0; // counts occurrences of the length
        o[i][j] = "@" // write initial character
        for (k = w * w; k > 1; k--) { // cycle over the whole spiral
            // update boundaries
            G = G < i ? G : i;
            H = H > i ? H : i;
            I = I < j ? I : j;
            J = J > j ? J : j;
            // move to the next position according to direction
            i+=a<3?1-a:0;
            j+=a>0?a-2:0
            if (k == 2) // we reached the end
                o[i][j] = "&"
            else if (l == m) {
                // we reached the corner so we need to count next direction
                a=(c=="c"?a+3:a+1)%4;
                // and write according sign
                o[i][j]=x[a]
                // first occurrence of this length
                if (z == 0)
                    z = 1; // wait for finish of the other
                else {
                    m++; // increase length of side
                    z = 0 // wait again for the first one
                }
                l = 1 // start the side counter over
            } else {
                l++ // another part of this side
                // according side character
                o[i][j] = y[a%2]
            }
        }
    }
    // blow it all out
    for (i = G; i <= H; i++)
        console.log(o[i].slice(I, J + 1).join("").replace(/\s+$/g, ''))
}

```
> 6 votes

# Answer
# Common Lisp, ~~649~~ ~~617~~ ~~605~~ ~~586~~ ~~576~~ ~~565~~ ~~554~~ ~~527~~ 518

```
(lambda(r v z c &aux(m 0)s(c(if c 1 -1))o p(x 0)i(y 0)j u)(#8=dotimes(_ z)(#7=setf p(aref"ruld"v)i(1-(abs(- p 2)))j(- 1(abs(1- p)))s'@)(#8#($(1- r))#5=(#7#m(min m x)o(cons`(,x,y,s)o)s(aref"-|-|"p)x(+ x i)y(+ y j))#2=(#7#s(*(- c)j)j(* i c)i s p(mod(+ p c)4)s(aref">^<v"p)u(#8#(_(1+ $))#5#))#2#))(#7#s'& u #5#o(#4=stable-sort(#4#o'< :key'car)'> :key'cadr)y(cadar o)x m)(dolist(k o)(do()((>=(cadr k)y))(#7#y(1- y)x m)(terpri))(do()((<=(car k)x))#9=(incf x)(princ" "))(and(=(cadr k)y)(=(car k)x)#9#(princ(caddr k)))))

```

*All tests still pass. The ungolfed function was also updated to reflect the changes, as were comments. I finally got rid of `remove-duplicates` in order to shorten the code, but now I don't know where to find more bytes. Well done Jakuje.*

## Examples

```
(funcall *fun* 8 #\r 3 nil)

      >------v
      |>----v|
      ||>--v||
      |||@v|||
   >------v|||
   |>----v|<||
   ||>--v||-<|
   |||@v|||--<
>------v|||
|>----v|<||
||>--v||-<|
|||@v|||--<
||^-<|||
|^---<||
^-----<|
&------<

(funcall *fun* 8 #\r 3 t) ;; counter-clockwise

&------<
v-----<|
|v---<||
||v-<|||
|||@^|||--<
||>--^||-<|
|>----^|<||
>------^|||
   |||@^|||--<
   ||>--^||-<|
   |>----^|<||
   >------^|||
      |||@^|||
      ||>--^||
      |>----^|
      >------^

(funcall *fun* 7 #\u 1 nil)

&>----v
||>--v|
|||>v||
|||@|||
||^-<||
|^---<|
^-----<

(funcall *fun* 2 #\d 4 nil)

&@@@@
^<<<<

```

See also `20lc10` (pastebin).

## Ungolfed

There is no recursion involved here, just a basic *Turtle graphics* approach with loops:

1. Draw the spirals in memory by storing `(x y char)` triples in a stack.
2. Stable-sort elements according to `y` and `x`
3. Iterate over that list while avoiding duplicates (previous traces) and print from top-left to bottom-right.

```
(lambda
    (r v z c
     &aux
       (m 0)       ; minimal x
       s           ; symbol to print (a character)
       (c          ; 1 if clockwise, -1 otherwise
        (if c
            1
            -1))
       o           ; stack of (x y char) traces
       p           ; position of s in ">^<v"
       i           ; move direction of x
       j           ; move direction of y
       (x 0)       ; position in x
       (y 0)       ; position in y
       u           ; auxiliary variable
       )
  ;; repeat for each recursive step
  (dotimes (_ z)
    ;; initialize spiral parameters
    (setf s '@            ; start spiral with @
          p (position v"ruld") ; initialize p according to input V

          ;; Set initial direction in I and J.
          i (1-(abs(- p 2))) ; i(0..3) = ( 1, 0, -1, 0 )
          j (- 1(abs(1- p))) ; j(0..3) = ( 0, 1, 0, -1 )

    ;; Iterate with increasing diameter $. For each iteration, draw a
    ;; "L"-shape that extends previous shape. Here is roughly what
    ;; happens at each step:
    ;;
    ;;   3334
    ;;   3124
    ;;   3224
    ;;   4444
    ;;
    (dotimes($(1- r))

      ;;
      ;; Assign the form to the reader variable #1# in order to
      ;; copy-paste later. This is like declaring a local function,
      ;; but shorter: push trace into list O and move forward.
      ;;
      #1=(setf m (min m x)
               o (cons `(,x ,y ,s) o)
               s (aref "-|-|" p)
               x (+ x i)
               y (+ y j))

      ;;
      ;; Helper function #2#: rotate and draw a line of length $.
      ;;

      #2=(setf u (* (- c) j) ; rotation as a vectorial
               j (* i c)     ; product of (i j 0) with (0 0 c).
               u i           ; At first I used PSETF, but now I reuse
                             ; the existing SETF with an auxiliary
                             ; variable U to shorten the code and get
                             ; rid of PROGN. That's also why I affect
                             ; the result of DOTIMES to U (no need
                             ; for two forms and a PROGN, just SETF).

               p (mod(+ p c)4)   ; ">^<v" is sorted counter-clockwise, which
               s (aref ">^<v" p) ; means that adding P and C (modulo 4) gives
                                 ; the next symbol after rotation.

               ;; trace a line by repeatedly invoking code snippet #1#
               u (dotimes(_(1+ $)) #1#))
      ;;
      ;; Rotate and draw a second line, hence drawing a "L"-shape.
      ;;
      #2#))

  ;; Finally, draw the final symbol &
  (setf s '&)
  #1#

  (setf o

        ;; From inside-out:
        ;;
        ;; - stable sort O according to X
        ;;   (from lowest (left) to highest (right))
        ;;
        ;; - stable sort the result according to Y
        ;;   (from highest (top) to lowest (bottom))
        ;;
        (stable-sort (stable-sort o '< :key 'car) '> :key 'cadr)

        ;; initialize Y with the first Y in O, which is also the
        ;; minimum of all Y.
        y (cadar o)

        ;; initialize X with the minimum of all X
        x m)

  ;; For each trace in O
  (dolist (k o)

    ;; Add as many lines as needed to advance Y to current trace's Y.
    (do ()
      ((<= y (cadr k)))
      (setf y (1- y)
            x m)
      (terpri))

    ;; Add as many spaces as needed to advance X to current trace's X.
    (do () ((>= x (car k))) (incf x) (princ " "))

    ;; Then, print current trace's character and increment X.
    ;; This happens only when we have a "new" trace, not another
    ;; trace at the same point (which was being overwritten).
    (and(=(car k)x)(=(cadr k)y)(incf x)(princ(caddr k)))

```
> 7 votes

# Answer
# Lua 5.2, 740 Bytes

```
s=io.read W=io.write Z=math.max A=math.min
D="d"U="u"L="l"R="r"function n()G=A(G,i)H=Z(H,i)I=A(I,j)J=Z(J,j)i=(a==D and i+1 or a==U and i-1 or i)j=(a==R and j+1 or a==L and j-1 or j)end
w=s"*n"d=s(1)c=s(1)r=(c=="c")and s"*n"or c
c=c=="c"M=w*(r+1)o={}for i=1,M do o[i]={}for j=1,M do o[i][j]=" "end end
i=M/2 j=i G=i H=i I=i J=i
for q=1,r do a=d m=1 l=1 z=0
o[i][j]="@"for k=3,w^2 do
n()if l==m then
a=c and(a==D and R or a==U and L or a==L and D or a==R and U)or(a==D and L or a==U and R or a==L and U or a==R and D)o[i][j]=(a==D and"v"or a==U and"^"or a==L and"<"or a==R and">")
if z==0 then z=1 else m=m+1;z=0 end
l=1
else
l=l+1
o[i][j]=(a==D or a==U)and"|"or"-"end end
n()o[i][j]="&"end
for i=G,H do for j=I,J do
W(o[i][j])end W("\n")end

```

I though that it would be fun to try to implement some algorithm to beat Lisp, but Lua is probably not the best option. I spend too much time on it, over-engineered some parts to end with this uggly one, but working solution. Probably I will try different language later to beat Lisp since there is some 90 characters that I can't take away from this algorithm.

Testing outputs:

```
jakuje@E6430:/tmp$ echo "2d4" | lua s.lua
&@@@@
^<<<<
jakuje@E6430:/tmp$ echo "4rc3" | lua s.lua
&--<
v-<|
|@^|<
>--^|
 |@^|<
 >--^|
  |@^|
  >--^
jakuje@E6430:/tmp$ echo "7u1" | lua s.lua
&>----v
||>--v|
|||>v||
|||@|||
||^-<||
|^---<|
^-----<

```
> 4 votes

# Answer
# PHP, 524 bytes

I arrived late at this party. My PHP solution is neither the smallest, nor the smartest. It just works.

```
$a=$argv;
$b=[['|','^',0,-1],['-','>',1,0],['|',v,0,1],['-','<',-1,$x=$y=$o=$p=$q=$r=0]];
for($t=$a[4];$t;$t--){$d=strpos(urdl,$a[2]);$c=$b[$d];$m[$y][$x]='@';
for($s=0;++$s<$a[1];){for($k=3;--$k;){for($i=$s;--$i;)
$m[$y+=$c[3]][$x+=$c[2]]=$c[0];$x+=$c[2];$y+=$c[3];$c=$b[$d=($d+($a[3]==c?3:1))%4];
$m[$y][$x]=$c[1];}$o=min($x,$o);$p=max($p,$x);$q=min($y,$q);$r=max($r,$y);}
for($i=$s;--$i;)$m[$y+=$c[3]][$x+=$c[2]]=$c[0];$m[$y][$x]='&';}
for($y=$q;$y<=$r;$y++){$l='';for($x=$o;$x<=$p;$x++)$l.=$m[$y][$x]?:' ';
echo rtrim($l)."\n";}

```

How to run it:

```
$ php -d error_reporting=0 recursive-ascii-spirals.php 4 r c 3
&--<
v-<|
|@^|<
>--^|
 |@^|<
 >--^|
  |@^|
  >--^
$ php -d error_reporting=0 recursive-ascii-spirals.php 7 u '' 1
&>----v
||>--v|
|||>v||
|||@|||
||^-<||
|^---<|
^-----<

```

The detailed version with tests, explanation and other goodies can be found on github.
> 2 votes

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


title: I haven't seen that number before!

text:
# Question
Title: I haven't seen that number before!
Write a program that goes through a string of non-whitespace characters (you may assume that they are digits `0` to `9`, but nothing in the way they are to be processed depends on this) and adds spaces according to the following rules.

1. Let the current token be the empty string, and the previously emitted tokens be an empty set.
2. Iterate through the characters of the string. For each character, first append the character to the current token. Then if the current token is not already in the set of previously emitted tokens, add the current token to that set and let the new current token be the empty string.
3. If when you reach the end of the string the current token is empty, output the previously emitted tokens in order of emission, separated by a space character. Otherwise output the original string verbatim.

**Input**

The input to the STDIN should be a sequence of digits.

**Output**

The program should print the result as specified in step 3.

**Samples**

*Sample inputs*

```
2015
10101010
4815162342
101010101010
3455121372425
123456789101112131415
314159265358979323846264338327950288419716939937

```

*Sample outputs*

```
2 0 1 5
10101010
4 8 1 5 16 2 3 42
1 0 10 101 01 010
3 4 5 51 2 1 37 24 25
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
3 1 4 15 9 2 6 5 35 8 97 93 23 84 62 64 33 83 27 95 0 28 841 971 69 39 937

```

---

This is code golf, so standard CG rules apply. Shortest program in bytes wins.

(Please request any clarifications in the comments. I'm still new to this. Thanks!)

# Answer
# Pyth, 22 bytes

```
 faW!}=+kTYY~kdz?tkzsY

```

Leading space is important.
> 9 votes

# Answer
# Retina, ~~68~~ 61 bytes

```
+`\b(\w+?)(?<!\b\1 .*)(\w+)$
$1 $2
(?=.* (.+)$(?<=\b\1 .+))
<empty>

```

`<empty>` is an empty line. Note the trailing space on line 3. You can run the above code from a single file with the `-s` flag.

## Explanation

```
+`\b(\w+?)(?<!\b\1 .*)(\w+)$
$1 $2

```

This first step implements rules 1 to 6. It is a regex substitution which is applied repeatedly until the string stops changing (that's what the `+` is for). In each step we add a single space into the string from left to right (following the rules of the challenge). The regex matches the shortest string of digits which hasn't appeared in the already processed part of the string. We ensure that we're looking at a prefix of the remaining string with the word boundary `\b` and checking that we can reach the end of the string without passing spaces with `(\w+)$`. The latter also ensures that we only perform one replacement per step.

```
(?=.* (.+)$(?<=\b\1 .+))
<empty>

```

This matches any space (which is at the end of the regex), provided that the last segment of the string is the same as any other segment in the string, and replaces them with the empty string. That is, we undo the first step if it resulted in an invalid final segment, implementing rule 7.
> 13 votes

# Answer
## Pyth, ~~24~~ 23 bytes

```
VzI!}=+kNYaY~k"";?kzjdY

```

Try it out here.

```
VzI!}=+kNYaY~k"";?kzjdY    Implicit: z=input(), k='', Y=[], d=' '
Vz              ;          For N in z:
     =+kN                    Append N to k
  I!}    Y                   Is the above not in Y?
          aY k               Append k to Y
            ~k""             After append, reset k to ''
                 ?k        Is k truthy (i.e. not '')
                   z       Print original input
                    jdY    Otherwise print Y joined on spaces

```

Thanks to @FryAmTheEggman for saving a byte :o)
> 11 votes

# Answer
# Python 3, 92 bytes

```
i,n,*o=input(),""
for c in i:n+=c;o,n=[o+[n],o,"",n][n in o::2]
print([" ".join(o),i][n>""])

```

Basically a heavily golfed version of @Willem's solution.
> 7 votes

# Answer
## Python 3, ~~100~~ 99 bytes

```
o=[];n="";i=input()
for c in i:
 n+=c
 if not n in o:o.append(n);n=""
print(i if n else" ".join(o))

```
> 6 votes

# Answer
# Brachylog, 91 bytes

```
:_:_{h:0<|bhN,?hh:NrcH,?hB(l1,-1=A;BbA),?rhL:I(mH:Ar:[L]c:1&;:[H]:\"~w \"w,L:[H]c:_:Ar:1&)}

```

This made me realize that there's a lot of things about the syntax I need to change...

### Explanation

```
:_:_              § Creates a list [Input,[],[]]
{...}             § Define a new predicate between the brackets and call it with the previous list as input
h:0<              § If the head of the input is negative, stop
|                 § Else
bhN,              § Second element of Input is called N
?hh:NrcH,         § N concatenated with the first element of Input is H
?hB(l1,-1=A;BbA), § Remaining digits A are either -1 if there's only one digit left or all the digits but the head otherwise
?rhL:I            § List of used integers is called L
(
   mH:Ar:[L]c:1&  § If H is already in L, call the predicate with input [A,H,L]
   ;              § Else
   :[H]:\"~w \"w, § Print H followed by a space
   L:[H]c:_:Ar:1& § Call the predicate with input [A,[],M] where M is L with H appended to it
)

```
> 5 votes

# Answer
# CJam, 26 bytes

```
LLq{+_a2$&{a+L}|}/:X+X!S**

```

Test it here.

## Explanation

```
L        e# Push an empty array to keep track if the previous segments.
L        e# Push an empty array to build the current segment.
q{       e# For each character in the input...
  +      e#   Add it to the current segment.
  _a2$&  e#   Duplicate and check if it's already in the segment list.
  {      e#   If not...
    a+L  e#     Add it to the list and push a new empty array for the next segment.
  }|
}/
:X+      e# Store the trailing segment in X and add it's *characters* to the list.
         e# For valid splittings, this trailing segment will be empty, so that the
         e# list remains unchanged.
X!       e# Push X again and take the logical NOT.
S*       e# Get that many spaces, i.e. 1 for valid segments and 0 otherwise.
*        e# Join the list with this string between elements.

```
> 4 votes

# Answer
# JavaScript (ES6), 109

My output format is not exactly the same of the output samples in the questioin (there is a leading space). I don't see that as a flaw, as the output format is not specified (just *The program should print the number after the number...*)

Test running the snippet below in a EcmaScript 6 compliant browser. Developed with Firefox, tested and running on the latest Chrome.

```
/* Test: redirect console.log */ console.log=x=>O.innerHTML+=x+'\n';

F=s=>{for(z=s,b=l=o=' ';s[+l];)~o.search(b+(n=s.slice(0,++l)+b))||(s=s.slice(l),o+=n,l=0);console.log(s?z:o)}

/* Test cases */
test = [
  '2015',
,'10101010'
,'4815162342'
,'101010101010'
,'3455121372425'
,'123456789101112131415'
,'11312123133'
,'314159265358979323846264338327950288419716939937']

test.forEach(t=>{console.log('\n'+t);F(t)})
```

```
<pre id=O></pre>
```
> 3 votes

# Answer
# GNU sed, 83 77 73 71 bytes

(Score one extra because we require `-r` flag)

```
h
s/./&_/
:
/(\b[^ ]+).*\b\1_/{
s/_(.)/\1_/
t
g
}
s/_(.)/ \1_/
t
s/_//

```

The inner loop tests for a repeated sequence and appends characters as needed until a unique number appears after the separator `_`. The outer loop moves `_` along.

Expanded, annotated version:

```
#!/bin/sed -rf

# Stash original in hold space
h

# Add separator
s/./&_/

:
# If current candidate is a duplicate, ...
/(\b[^ ]+).*\b\1_/{
#  ...then attempt to lengthen it ...
s/_(.)/\1_/
# ... and repeat if we succeeded, ...
t
# ... otherwise, restore original string
g
}
# Insert a space, and move our separator along
s/_(.)/ \1_/
t

# Remove the separator if we still have it
s/_//

```
> 2 votes

# Answer
# Ruby, 57 + 1 = 58 bytes

```
s=''
l={}
$_.chars{|c|l[s<<c]||=s=''}
l[s]||$_=l.keys*' '

```

Uses the command line flag `-p` (or `pl` if your input has a trailing newline). Exploits several traits of Ruby Hash dictionaries: you can safely mutate the string you used to define a key without it changing the key (which doesn't work for other mutable types), `.keys` returns the keys in the order they were inserted, and the `[]||=` operator provides a terse way of branching on whether a given key is already there.
> 1 votes

# Answer
# Haskell, 105 bytes

`f` does it.

```
e""s""=unwords s
e t s""=concat s++t
e t s(c:r)|t&c`elem`s=e(t&c)s r|0<1=e""(s&(t&c))r
a&b=a++[b]
f=e""[]

```
> 1 votes

# Answer
# PHP - 148 bytes

Cool challenge, lots of fun!

```
$x=fgets(STDIN);$w=array();$k='';$l='';for($i=0;$i<strlen($x);$i++){$k.=$x[$i];if(!isset($w[$k])){$l.=$k.' ';$w[$k]=1;$k='';}}echo strlen($k)?$x:$l;

```
> 1 votes

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


# Question
Title: Reconstruct a Text Rectangle from Diagonal Strips
This challenge is inspired by a SO question about traversing a matrix by enumerating all its diagonal strips.

Instead of a matrix, consider a block of text:

```
ABCD
EFGH
IJKL

```

Traversing this block's SW-NE diagonals from left to right, starting from the top left corner and ending in the bottom right, results in the following output:

```
A
EB
IFC
JGD
KH
L

```

## Challenge

Write a program or a function that execute the reverse of the process described above. That is, given a set SW-NE diagonal strips, output the block of text that produced it.

## Input and Output

Both input and output can be represented as strings with newlines, or arrays/lists of strings.

Trailing newlines are optional.

The input will consist of at least one printable character and can be assumed to be correct (there will not be inconsistent row lengths).

The output block will always have a number of columns greater than or equal to the number of rows.

## Test Cases

Input:

```
A

```

Output:

```
A

```

Input:

```
.
LI
PO.
PV.
CE
G

```

Output:

```
.I..
LOVE
PPCG

```

Input:

```
M
DA
AIT
LAR
SGI
/OX
/N
/

```

Output:

```
MATRIX
DIAGON
ALS///

```

# Answer
# CJam, ~~23~~ 20 bytes

```
{_z,,Nf*W%\.+zW%sN%}

```

Try it here.
> 5 votes

# Answer
## Python 2, 84

```
L=[]
for w in input():
 i=0;L+=[''][:len(w)-len(L)]
 for c in w:i-=1;L[i]+=c
print L

```

Input and output are lists of strings.

```
input: ['A','EB','IFC','JGD','KH','L']
output: ['ABCD', 'EFGH', 'IJKL']

```

The list of lines `L` to output is built up as we read the input. Each new character is appended to a line, starting from the last line `i=-1` and progressing towards the front.

Whenever the new line to add is too long for the list, a new empty line is appended: `L+=[''][:len(w)-len(L)]`. I'm hoping for a way to shorten this part.
> 3 votes

# Answer
# Python 2, ~~165~~ ~~162~~ ~~169~~ 163 bytes

```
import sys
j=map(list,[e.strip() for e in sys.stdin.readlines()])
r=max(1,len(j)-2)
while j:
 s=''
 for b in range(r):s+=j[b].pop()
 j=[e for e in j if e]
 print s

```

Reads all lines from input, then turns them into a list of lists. Loops while that list has elements. In each iteration, it pops the last element from the number of inner lists equal to the number of columns in the output. The list is then cleaned and the line printed.

Examples:

```
$ python rectangle.py << EOF
> A
> EB
> IFC
> JGD
> KH
> L
> EOF
ABCD
EFGH
IJKL
$ python rectangle.py << EOF
> .
> LI
> PO.
> PV.
> CE
> G
> EOF
.I..
LOVE
PPCG
$ python rectangle.py << EOF
> M
> DA
> AIT
> LAR
> SGI
> /OX
> /N
> /
> EOF
MATRIX
DIAGON
ALS///

```

Thanks to w0lf for saving 6 bytes.

# PYG, 139 bytes

```
j=M(L,[e.strip() for e in sys.stdin.readlines()])
r=Mx(1,len(j)-2)
while j:
 s=''
 for b in R(r):s+=j[b].pop()
 j=[e for e in j if e]
 P(s)

```
> 1 votes

# Answer
# Python, ~~332~~ 325 bytes

Because Python.

```
n=[]
v=[]
x=y=-1
l=0
s=""
while 1:
 k=raw_input()
 if len(k)<1:break
 n.append(k)
while 1:
 if l>len(n):break
 y+=1
 try:
    x+=1;k=n[y][x]
    if[x,y]not in v:s+=k;v.append([x,y])
    else:raise
 except:
    try:
     x-=1;k=n[y][x]
     if[x,y]not in v:s+=k;v.append([x,y])
    except:s+="\n";x=-1;y=l;l+=1
print s[:s.rstrip("\n").rfind("\n")]

```
> 0 votes

---
Tags: code-golf
---


# Question
Title: Primes, as efficiently inefficient as possible
Write a program that tests if a number `n` is prime by checking that none of the integers between `2` and `n-1` (inclusive) divide `n` (you must use *this* algorithm!). The input to STDIN should be an integer `n` (strictly) greater than 1. The output to STDOUT should be `prime` if `n` is prime and `not prime` if `n` is not prime.

Even though you are intentionally writing an inefficient program, this is still code golf, fellas. Standard CG rules apply. Shortest code in bytes wins.

# Answer
# CJam, 25 bytes

```
li_,2>f%:*!"not "*"prime"

```

Try it online

Explanation:

```
li    Get input and convert to integer.
_,    Create range [0 ... n-1].
2>    Slice off first two elements, to get [2 ... n-1].
f%    Apply modulo with all range members to input.
:*    Calculate product of the results. This will be 0 if one of the modulo
      results was 0, non-zero if the input is prime.
!     Negate. We now have 0 for primes, 1 for non-primes.
"not "*
      Push "not " 0/1 times based on value.
"prime"
      Push "prime".

```
> 2 votes

# Answer
# Pyth - ~~25~~ 23 bytes

Heavily golfable, uses filter.

```
+?f!%QTr2Q"not "k"prime

```

Test Suite.
> 1 votes

# Answer
# Pyth, 22 bytes

```
+*}0%LQr2Q"not ""prime

```

Try it online.
> 1 votes

# Answer
# Python 2, 59

```
i=input()
print"not "*any(i%n<1for n in range(2,i))+"prime"

```

Thanks Alex! One day I will remember.
> 1 votes

# Answer
# Python 2, way too many bytes (95, to be exact)

```
n=input();x=0
for i in range(2,n):
 if n%i==0:x+=1;print'not prime';break
if x==0:print'prime'

```

Heavily golfable for sure.
> 0 votes

# Answer
# R, 59 bytes

```
n=scan();cat(if(n>2&sum(!n%%2:(n-1)))"not ","prime",sep="")

```

Ungolfed:

```
# Read n from STDIN
n <- scan()

# Test primality and write to STDOUT
if (n > 2 & sum(!(n %% 2:(n-1)))
    cat("not prime")
else
    cat("prime")

```
> 0 votes

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


title: Generate the Stack Overflow logo

text:
# Question
Title: Generate the Stack Overflow logo
**The challenge is to generate an image similar to the StackOverflow logo:**

**The output must contain:**

* Image size 64\*64 or greater
* A gray |\__| shaped base
* A curved segmented stack coming up from the base. The segments will fade from gray to orange, and make a ~90 degree right turn. The number of segments should be between 5 and 7, with 6 being preferred.

Note: For ascii displays that lack color, use a '0' character to represent gray, and '9' for orange. '1' to '8' would represent the shades in-between.

**Restrictions:**

* You must *generate* the image. Loading images or storing them in the code/binary is not allowed.

**Additional rules/information:**

* The image is not required to be identical to the logo, however it must be recognizable as it.
* The method of display is up to you. Saving it to an image file or displaying on the screen are both acceptable.

**Judging/winning criteria:**

* Accuracy of the image is the primary condition
* Elegance of generation is the secondary condition

# Answer
> 61 votes
# Mathematica

```
Graphics[{
   Gray, Rectangle[{0, 0}, {78, 50}],
   White, Rectangle[{9, 9}, {69, 50}]}
  ~Join~
  Table[{
    Blend[{Gray, Orange}, x/5],
    Rotate[
     Translate[
      Rectangle[{16, 16}, {61, 25}],
      {0.25x^3 + 0.6x^2 - 0.4x, -0.53x^3 + 3.26x^2 + 12x}],
     -0.05x^2 - 0.04x]},
   {x, 0, 5}]]

```

I decided to prettify my answer after realizing this isn't code golf. Whoops!

Screenshot:

In related news, I also created what I think the Stack Overflow logo might look like in... ***THE FUTURE***:

Here's the code if anyone wants to play around with it (sorry for the mess):

```
Graphics3D[{EdgeForm[],
   Opacity[1],
   RGBColor[0.2, 0.2, 0.2], Cuboid[{0, 0, 0}, {78, 4, 50}],
   Cuboid[{0, 4, 0}, {4, 45, 50}],
    Cuboid[{74, 4, 0}, {78, 45, 50}],
   Opacity[1]}
  ~Join~
  Fold[Join, {},
   Table[{Hue[0.15 - i/5/12, i/3, 1],
     Translate[
      Rotate[
       Scale[Cuboid[{16, 16, 16}, {61, 25, 25}], {1, .3, .3}],
       (-.05 ((i*2 - 1.5)*1.25)^2 - .04 ((i*2)*1.2)), {0.3,
        0.8, -1}, {(16 + 61)/2, (16 + 25)/2, (16 + 25)/2}],
      {-((i*2)^2 - (i*2)*4)/2, (i*2)^2*3/2, 0}]},
    {i, 0, 4.5, 0.05}]], Lighting -> "Neutral", Axes -> False,
 Background -> White, Boxed -> False]

```

# Answer
> 23 votes
## Javascript (650)

I wrote a quine that reads the characters in the function, and replaces non-space characters with a number from 0-9.

```
(function a(){
l=[
                   1,
                    1,
            11,      1,
             11,     1,
               11,    1,
       11,      11,   1,
         11,      11,
           11,
   11,       1111,
     1111,
0,       11111111, 0,
0, 11,             0,
0,   111111111111, 0,
0,                 0,
0, 11111111111111, 0,
0,                 0,
000000000000000000000]

b=a.toString().split("[")[1].split("]")[0].split(""),i=-1
document.getElementById("output").innerHTML=
b.map(function(c){
++i
if(c==" "||c=="\n")return c
if(c!=0)c=9-Math.floor((i/b.length)*10)
if(b[i-1]=="0")c=0
return"<span class='c"+c+"'>"+c+"</span>"
}).join("")
})()

```

This outputs this ASCII art:

```
                   99
                    88
            888      88
             777     77
               766    66
       666      666   66
         555      555
           555
   444       44444
     44444
00       333333333 00
00 333             00
00   2222222222222 00
00                 00
00 111111111111111 00
00                 00
000000000000000000000

```

which can be colored with a css stylesheet if you like

```
  span{
    font-weight: bold;
  }
  .c0, .c1{
    color: #222;
  }
  .c2{
    color: #765;
  }
  .c3{
    color: #976;
  }
  .c4{
    color: #A64;
  }
  .c6, .c5{
    color: #D51;
  }
  .c8, .c9, .c7{
    color: #F60;
  }

```

You can see it in action on jsBin.

Here is a screenshot, in case the link dies:

# Answer
> 22 votes
## SVG (347 characters)

Based on Sir\_Lagsalot's version, with strokes instead of fills. Besides shaving off a few chars, the code is simpler and the output looks better scaled up.

```
<svg width="66" height="85" xmlns="http://www.w3.org/2000/svg">
<g stroke-width="7" fill="none">
<path stroke="gray" d="m4,50v31h49V50M12,69h33"/>
<path stroke="#a86" d="m12,57 33,3"/>
<path stroke="#b95" d="m14,42 32,9"/>
<path stroke="#c82" d="m22,24 27,19"/>
<path stroke="#e80" d="m37,9 18,27"/>
<path stroke="#f71" d="m58,1 4,32"/>
</g></svg>

```

Link to SVG image.

Rendered to PNG (at natural size and scaled up x2 and x3):

**Edit:** Finally got around to fixing the off-by-one error that caused the sides of the box not to line up. Also tweaked the line thickness and end point placement a bit, and added explicit width and height to avoid the bottom and right edges being cropped too tight. It now looks a *lot* closer to the official logo.

# Answer
> 18 votes
## Haskell w/Gloss

```
import Graphics.Gloss

picture = translate 0 (-50) $ pictures [stack, base 150 60 20]

stack = translate 0 30 $ pictures [item n | n <- [0..5]]

item n = bend 200 (-10*n) $ color (fade grey orange (n/5)) box
  where box = rectangleSolid 110 20

base width height thickness = color grey $ pictures [left, right, bottom]
  where bottom = rectangleSolid width thickness
        left = translate (width / 2) (height / 2) side
        right = translate (-width / 2) (height / 2) side

        side = rectangleSolid thickness (height + thickness)

bend radius angle = translate radius 0 . rotate angle . translate (-radius) 0

fade from to alpha = mixColors (1-alpha) alpha from to

grey = greyN 0.5

```

Paste the code here to see it in action, or add the following line to compile it (requires Gloss).

```
main = display (InWindow "Stack Overflow" (512, 512) (10, 10)) white picture

```

# Answer
> 15 votes
## SVG (333 characters)

I've created a SVG image that generates a 67x68 version of the logo in 333 characters:

```
<svg xmlns="http://www.w3.org/2000/svg">
<path fill="grey" d="m0,53v34h53V53h-5v29H5V53M9,69h33v6H11v-6"/>
<path fill="#a86" d="m12,56 31,3-1,6-31-3"/>
<path fill="#b95" d="m15,41 31,9-2,6-31-8"/>
<path fill="#c82" d="m22,25 28,17-3,5-28-17"/>
<path fill="#e80" d="m38,8 19,27-5,4-19-27"/>
<path fill="#f71" d="m62,0 5,32-6,1-5-32"/>
</svg>

```

Link for small SVG image
Link for large SVG image

# Answer
> 13 votes
## LaTeX

Using the TikZ and PGF packages.

```
\documentclass{minimal}
\usepackage{tikz}
\pagestyle{empty}
\begin{document}
\xdefinecolor{col1}{RGB}{167, 149, 116}
\xdefinecolor{col2}{RGB}{189, 153, 87}
\xdefinecolor{col3}{RGB}{211, 157, 57}
\xdefinecolor{col4}{RGB}{233, 161, 28}
\xdefinecolor{col5}{RGB}{255, 165, 0}
\begin{tikzpicture}
\draw[gray, fill=gray] (-1,0.5) -- (-1,0) -- (0,0) -- (0,0.5) -- (-0.1,0.5) -- (-0.1,0.1) -- (-0.9,0.1) -- (-0.9,0.5) -- (-1,0.5);
\draw[gray, fill=gray] (-0.8,0.3) rectangle(-0.2,0.2);
\draw[col1, fill=col1, xshift=0.3pt, yshift=3pt,  rotate around={-15:(0.2,0.2)}] (-0.8,0.3) rectangle(-0.2,0.2);
\draw[col2, fill=col2, xshift=0.5pt, yshift=6pt,  rotate around={-30:(0.2,0.2)}] (-0.8,0.3) rectangle(-0.2,0.2);
\draw[col3, fill=col3, xshift=0.8pt, yshift=9pt,  rotate around={-45:(0.2,0.2)}] (-0.8,0.3) rectangle(-0.2,0.2);
\draw[col4, fill=col4, xshift=1.3pt, yshift=12pt, rotate around={-60:(0.2,0.2)}] (-0.8,0.3) rectangle(-0.2,0.2);
\draw[col5, fill=col5, xshift=2.1pt, yshift=14pt, rotate around={-75:(0.2,0.2)}] (-0.8,0.3) rectangle(-0.2,0.2);
\end{tikzpicture}
\end{document}

```

# Answer
> 9 votes
# CSS+JavaScript (HTML div based)

```
* { padding: 0; margin: 0; }

div { position: absolute; width: 100px; height: 20px; background-color: red; }
.s { background-color: gray; }
#d0,#d2 { width: 20px; height: 70px; }
#d0 { left: 20px; top: 160px; }
#d1 { left: 20px; top: 230px; width: 160px; }
#d2 { left: 160px; top: 160px; }

.e { -moz-transform-origin: 200% center; -ms-transform-origin: 200% center; -o-transform-origin: 200% center; -webkit-transform-origin: 200% center; transform-origin: 200% center; }

```

```
$(document).ready(function() {
    for (var i = 0; i < 9; i++)
        $('body').append($('<div/>').attr('id', 'd' + i).attr('class', i < 3 ? 's' : 'e'))

    $('.e').each(function(i) {
        $(this).css({
            left: (50 - i * 3) + 'px',
            top: '200px',
            backgroundColor: '#' + (i + 10).toString(16) + 'a' + (10 - i * 2).toString(16),
            '-moz-transform': 'rotate(' + (i * 15) + 'deg)',
            '-ms-transform': 'rotate(' + (i * 15) + 'deg)',
            '-o-transform': 'rotate(' + (i * 15) + 'deg)',
            '-webkit-transform': 'rotate(' + (i * 15) + 'deg)',
            transform: 'rotate(' + (i * 15) + 'deg)'
        });
    });
});

```

Sample run: http://jsfiddle.net/ryzBx/

Sample rendering (Firefox 14):

# Answer
> 8 votes
## Javascript (a lot of 814 characters)

```
window.onload = function() {
                var canvas = document.getElementById("cgCanvas");
                var context = canvas.getContext("2d");
                context.moveTo(60,140);
                context.lineTo(60,190);
                context.moveTo(57.5,190);
                context.lineTo(137.5,190);
                context.moveTo(135,140);
                context.lineTo(135,190);
                context.lineWidth = 5;
                context.strokeStyle = "rgb(94,94,94)";
                context.stroke();
                for(i=0;i<6;i++) {
                    context.beginPath();
                    var b=1;
                    var a=1;
                    if(i==5) {
                        a=3;
                        b=1.3;
                    }
                    else if(i==4)
                        a==2;
                    x=94+i*9;
                    y=94-i*5;
                    z=95-i*19;
                    context.moveTo(122.5+i*i,180-i*15);
                    context.lineTo(72.5+i*i+i*i*b,180-i*15-i*i*i+i*i*a);
                    context.lineWidth = 8;
                    context.strokeStyle = 'rgb('+ x +','+ y +','+ z +')';
                    context.stroke();
                }
            };

```

It ain't pretty but looks a bit like the SO logo. Test fiddle here - http://jsfiddle.net/elssar/jcYtg/2/

# Answer
> 7 votes
## C#/GDI+

I was surprised when I noticed there's no C# answer here. So here's one. This is not an ingenious way of drawing the logo, and is not a short solution either. But gets the required output.

You can check my blog post out to download the full working solution → http://guganeshan.com/blog/stackoverflow-logo-using-csharp-and-gdi.html

```
public class SOLogo
{
    private float _rotateValue;
    private float _xValueForTransformation;
    private float _yValueForTransformation;

    int _containerWidth;
    int _containerHeight;
    float _lineThickness;
    int _paddingWithinContainer;
    int _elementStartY;

    public SOLogo(float rotateValue, float xValueForTransformation, float yValueForTransformation)
    {
        // Values used to position and rotate the overflowing elements.
        _rotateValue = rotateValue;
        _xValueForTransformation  = xValueForTransformation;
        _yValueForTransformation = yValueForTransformation;
    }

    public void DrawLogo(Graphics g, int startX, int startY)
    {
        // Backup the current smoothing mode to apply later.
        var SmoothingMoodBackup = g.SmoothingMode;
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

        // Values for the container box.
        _containerWidth = 94;
        _containerHeight = 61;
        _lineThickness = 11f;
        _paddingWithinContainer = 15;

        // Y value of the position where the 1st overflowing element starts.
        _elementStartY = 0;

        // Starting point of the 'container' - Top point of the line on the left-> |_|
        Point pointContainerLineStart = new Point(startX, startY);

        Point pointContainer1stLineEnd = new Point(pointContainerLineStart.X, pointContainerLineStart.Y); // Start with the previous
        pointContainer1stLineEnd.Offset(0, _containerHeight); // Offset "Y"

        Point pointContainer2ndLineEnd = new Point(pointContainer1stLineEnd.X, pointContainer1stLineEnd.Y); // Start with the previous
        pointContainer2ndLineEnd.Offset(_containerWidth, 0); // Offset "X"

        Point pointContainer3rdLineEnd = new Point(pointContainer2ndLineEnd.X, pointContainer2ndLineEnd.Y); // Start with the previous
        pointContainer3rdLineEnd.Offset(0, 0 - _containerHeight); // Offset "Y" (negative)

        GraphicsPath pathOfBox = new GraphicsPath();
        pathOfBox.AddLine(pointContainerLineStart, pointContainer1stLineEnd); // Left line. Top to bottom
        pathOfBox.AddLine(pointContainer1stLineEnd, pointContainer2ndLineEnd); // Bottom line. Left to right
        pathOfBox.AddLine(pointContainer2ndLineEnd, pointContainer3rdLineEnd); // Right line. Bottom to top

        Pen thickPen = new Pen(Brushes.Gray, _lineThickness);
        Color elementColor = Color.FromKnownColor(KnownColor.Gray);

        // Draw the 'container'
        g.DrawPath(thickPen, pathOfBox);

        // Increase the size of the pen to draw the elements inside the container
        thickPen.Width = _lineThickness += 3;
        // "Y" - position of the 1st element
        _elementStartY = startY + 38;

        // The following section draws the overflowing elements

        Point pointElement1Left = new Point(startX + _paddingWithinContainer, _elementStartY);
        Point pointElement1Right = new Point((startX + _containerWidth) - _paddingWithinContainer, _elementStartY);

        // Six colors of the overflowing elements
        var colors = new Color[] {
            Color.Gray,                 Color.FromArgb(-6911615),   Color.FromArgb(-4417693),
            Color.FromArgb(-2848227),   Color.FromArgb(-554957),    Color.FromArgb(-688847)
        };

        for (int x = 0; x < 6; x++)
        {
            thickPen.Color = colors[x];
            pointElement1Left = new Point(startX + _paddingWithinContainer, _elementStartY);
            pointElement1Right = new Point((startX + _containerWidth) - _paddingWithinContainer, _elementStartY);
            g.DrawLine(thickPen, pointElement1Left, pointElement1Right);
            g.RotateTransform(_rotateValue);
            g.TranslateTransform(_xValueForTransformation, _yValueForTransformation);
        }

        pathOfBox.Dispose();
        thickPen.Dispose();

        // Restore the smoothing mood that was backed up before we started this method.
        g.SmoothingMode = SmoothingMoodBackup;
    }
}

```

# Answer
> 7 votes
I know I'm **super** late to the game here, but I was surprised no one did a CSS version of this. This is definitely not a competitive answer when it comes to character count (1,195) but the final product is pretty accurate.

Written in Safari (9.0) and tested in Chrome (45.0.2454.93) and Firefox (40.0.3).

```
body {
    padding: 100px 40px;
}
.base {
    width: 60px;
    height: 40px;
    border: 8px solid #818286;
    border-top: none;
}
.container {
    bottom: 28px;
    left: 6px;
    position: relative;
}
.line {
    width: 48px;
    height: 10px;
    position: relative;
}
.line:nth-child(1n) {
    background: #ff7a15;
    bottom: 23px;
    left: 45px;
    transform: rotate(80deg)
}
.line:nth-child(2n) {
    background: #ff8907;
    bottom: 25px;
    left: 25px;
    transform: rotate(55deg)
}
.line:nth-child(3n) {
    background: #d48c28;
    bottom: 19px;
    left: 10px;
    transform: rotate(30deg)
}
.line:nth-child(4n) {
    background: #c19653;
    bottom: 12px;
    left: 3px;
    transform: rotate(16deg)
}
.line:nth-child(5n) {
    background: #a78b6e;
    bottom: 5px;
    left: 0;
    transform: rotate(5deg);
}
.line:nth-child(6n) {
    background: #818286;
    bottom: 0;
    left: 0;
    transform: rotate(0deg);
}
```

```
<div class="base">
    <div class="container">
        <div class="line"></div>
        <div class="line"></div>
        <div class="line"></div>
        <div class="line"></div>
        <div class="line"></div>
        <div class="line"></div>
    </div>
</div>
```

# Answer
> 5 votes
## JavaScript + jQuery & SVG - 250

```
$('body').html('<svg><g stroke-width="6" fill="none"$grey" d="m3,51v31h47V53M10,70h33"/$#a86" d="m10,57 33,3"/$#b95" d="m13,42 31,9"/$#c82" d="m20,25 28,17"/$#e80" d="m34,9 19,27"/$#f71" d="m56,1 4,32"/></g></svg>'.replace(/\$/g, '><path stroke="'))

```

I took Ilmari Karonen's SVG and used JavaScript to replace `$`s with `><path stroke="` effectively shortening it even with the overhead of JavaScript.

# Answer
> 4 votes
# PHP w/ GD

```
<?php
$img = imagecreatetruecolor(67,68);
$white = imagecolorallocate($img,0xff,0xff,0xff);
$grey = imagecolorallocate($img,0x80,0x81,0x85);
$orng1 = imagecolorallocate($img,0xa6,0x8a,0x6e);
$orng2 = imagecolorallocate($img,0xc0,0x95,0x53);
$orng3 = imagecolorallocate($img,0xd3,0x8b,0x28);
$orng4 = imagecolorallocate($img,0xfd,0x88,0x08);
$orng5 = imagecolorallocate($img,0xfe,0x7a,0x15);
imagefilledrectangle($img,0,0,67,68,$white);

//container
imagefilledrectangle($img,7,41,10,65,$grey);
imagefilledrectangle($img,10,61,44,65,$grey);
imagefilledrectangle($img,41,61,44,41,$grey);

// stack levels
imagefilledrectangle($img,14,52,37,56,$grey); //1st level
imagefilledpolygon($img,array(14,42,14,47,37,49,37,44),4,$orng1);
imagefilledpolygon($img,array(16,32,15,36,37,42,38,38),4,$orng2);
imagefilledpolygon($img,array(22,21,20,24,39,35,41,32),4,$orng3);
imagefilledpolygon($img,array(33,10,31,12,43,30,45,28),4,$orng4);
imagefilledpolygon($img,array(45,5,48,5,51,27,48,27),4,$orng5);
header("Content-type: image/png");
imagepng($img);
?>

```

Example:

# Answer
> 4 votes
## R

Not the prettiest solution but it returns the requested output.

```
library(grid)
my.palette <- colorRampPalette(c("grey57","orange"))(6)
png("StackOverflow_Logo.png", width=300, height=300)
pushViewport(viewport(x=0.5, y=0.5, w=unit(100, "points"), h=unit(100, "points")))
grid.polygon(x=unit(c(10, 0, 0, 100, 100, 90, 90, 10),"points"),
             y=unit(c(50, 50, 0, 0, 50, 50, 10, 10),"points"),
             default.units="points", gp=gpar(col = "grey57", fill="grey57"))
grid.rect(vp=viewport(x=0.5, y=0.3, w=unit(70, "points"), h=unit(10, "points")),
          gp=gpar(col = "grey57", fill="grey57"))

grid.rect(vp=viewport(x=0.52, y=0.52, w=unit(70, "points"), h=unit(10, "points"), angle=-10),
          gp=gpar(col = my.palette[2], fill=my.palette[2]))

grid.rect(vp=viewport(x=0.58, y=0.78, w=unit(70, "points"), h=unit(10, "points"), angle=-20),
          gp=gpar(col = my.palette[3], fill=my.palette[3]))

grid.rect(vp=viewport(x=0.70, y=1.05, w=unit(70, "points"), h=unit(10, "points"), angle=-35),
          gp=gpar(col = my.palette[4], fill=my.palette[4]))

grid.rect(vp=viewport(x=0.90, y=1.25, w=unit(70, "points"), h=unit(10, "points"), angle=-55),
          gp=gpar(col = my.palette[5], fill=my.palette[5]))

grid.rect(vp=viewport(x=1.15, y=1.38, w=unit(70, "points"), h=unit(10, "points"), angle=-70),
          gp=gpar(col = my.palette[6], fill=my.palette[6]))
dev.off()

```

# Answer
> 2 votes
## Scala

```
object LogoCanvas extends javax.swing.JPanel {

  import java.awt._

    def viereck (g: Graphics, points: scala.List[(Int, Int)]) = {
      val polygon = new Polygon ()
      points.foreach (p => polygon.addPoint (10 * p._1, 400 - 10 * p._2))
      g.fillPolygon (polygon)
    }

  override def paint (g: Graphics) = {
    g.setColor (Color.GRAY);
    // ablage
    viereck (g, scala.List ((2, 1), (2, 11), (3, 11), (3, 1)))
    viereck (g, scala.List ((2, 1), (2, 2), (23, 2), (23, 1)))
    viereck (g, scala.List ((23, 1), (23, 11), (24, 11), (24, 1)))
    // blaetter flach
    viereck (g, scala.List ((5, 5), (5, 6), (21, 6), (21, 5)))
    viereck (g, scala.List ((5, 9), (5, 10), (21, 10), (21, 9)))
    // blaetter schraeg
    g.setColor (Color.LIGHT_GRAY);
    viereck (g, scala.List ((7, 22), (8, 23), (21, 13), (21, 12)))
    viereck (g, scala.List ((12, 28), (13, 29), (22, 15), (21, 14)))
    // blaetter steil
    g.setColor (Color.ORANGE);
    viereck (g, scala.List ((18, 34), (19, 34), (23, 17), (22, 16)))
    viereck (g, scala.List ((24, 36), (25, 36), (25, 17), (24, 17)))
  }

  import javax.swing._

  def main (args: Array [String]) : Unit = {
    val jf = new JFrame ("Stackoverflow!")
    jf.setSize (350, 520)
    jf.setLocationRelativeTo (null)
    jf.setBackground (Color.BLACK)
    jf.add (LogoCanvas)
    jf.setDefaultCloseOperation (WindowConstants.EXIT_ON_CLOSE)
    jf.setVisible (true)
  }
}

```

# Answer
> 1 votes
# JavaScript

```
var c=document.getElementById('c'),x=c.getContext('2d'),i=0
c.width=c.height=140
x.scale(5,5)
x.fillStyle="#999"
x.fillRect(3,26,14,2)
x.fillRect(1,18,2,10)
x.fillRect(17,18,2,10)
for(;i<6;){x.fillStyle="#"+"999a96b95c94d93f90".substr(i*3,3)
x.save()
x.translate(i*i/2,22-i*6)
x.rotate(i++/5)
x.fillRect(5,0,10,2)
x.restore()}
```

```
<canvas id="c"></canvas>
```

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


# Question
Title: Can you help Tony Stark become an Ironman?
Tony Stark is, as we know *Ironman* (that super awesome guy in metal suit and loads of weapons). However, without the metal suit, he can't claim that title. Tony Stark, having a great ego, wants to finish Norseman, which is considered to be the hardest triathlon in the world (for distances equivalent to those of an Ironman race), to prove that he's a mean machine, even when he leaves the iron at home.

Tony has a predefined schedule / time plan for each part of the competition.
That means for every location in the race (i.e. distance from start), there's an expected time he should arrive there based on the schedule.

He also has a watch that tells the time spent and the total distance covered.

Your task is: **Given those two values as input, tell Tony how much he is ahead of, or behind schedule.** The input will be a time on the format `hh:mm:ss` (or (optional) `h:mm:ss` if it's been less than 10 hours) and a decimal number telling how far he has come (in km).

The distances for each of the three disciplines are:

```
Swim: 3.8 km
Bike: 180 km
Run: 42 km
Total distance: 225.8 km   // Input will never exceed 225.8

```

The estimated times for each part (i.e. the schedule):

```
Swim: 1:20:00
Transition 1: 0:12:00
Bike: 7:10:00
Transition 2: 0:05:00
Run: 4:50:00
Total: 13:37:00

```

Both distances, and the estimated times are given before the race, and can therefore be hardcoded. The transition zone is just a place where he changes clothes and equipment, so he's not moving during transition.

Input can be comma-separated, a string, two separate arguments or whatever is most convenient in your language. He want the output on the format `+/-mm:ss`, not hours (assume he's never more than one hour too slow or too fast. If he's in transition, you can assume he just got there.

**Examples and explanations (apologies for the length of it):**

```
Input: 04:32:20 93.8
Output: +34:40 / 34:40

```

At 93.8 km, he has finished the swim, been through transition and has finished half of the bike leg. According to the schedule, this should have taken him: `1:20:00 + 0:12:00 + (0.5 * (07:10:00)) = 5:07:00`. If he has used `4:32:20`, then he's `34:40` ahead of schedule.

---

```
Input: 1:20:00 3.8
Output: +00:00 / +0:00 / 00:00 / 0:00 / -00:00 / -0:00

```

Assuming the distance is `3.8`, you can assume he has just got into the first transition zone. The estimated time here was `1:20:00`, so for the input above, he's on time.

---

If the time is `1:25:00`, then he's 5 minutes behind schedule, thus:

```
Input: 1:25:00 3.8
Output: -05:00 / -5:00

```

---

Another example, explained in detail:

```
Input: 10:33:46 198.14

```

So, a distance of 198.14 km has been covered. That means he has finished the swim (3.8), the bike leg (180 km) and 14.34 km of the running, and he has been through both transitions. According to the schedule, he should have started the run after: `1:20:00 + 0:12:00 + 07:10:00 + 0:05:00 = 8:47:00`. 42 km of running should take 4:50:00, thus 14.34 km should take: `4:50:00 * (14.34 / 42) = 1:39:01`. So, according to the plan, 198.14 km should take: `8:47:00 + 1:39:01 = 10:26:01`. He has used `10:33:46`, which is `07:45` more than planned.

```
Output: -07:45 / -7:45

```

---

The plus sign is optional, but there has to be a minus sign if he's behind schedule.

The output should have exactly the same format as the examples above, but trailing spaces, newlines etc. are OK.

This is code golf, so the shortest code in bytes win.

# Answer
> 2 votes
# CJam, 91

```
r~[0_80 3.8_92 43dI183.8 527 290d42]4/{1$a<},W=(@\-\~/@*+60*r':/:i60b-i_gs);\60b2Te[':*)Amd

```

Try it online. Note: it takes the distance first.

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


title: Literally code golf

text:
# Question
Title: Literally code golf
In modern day standards *Golfing* translates to playing a game of *golf*, while *golf* itself translates to a car manufactured by Volkswagen.
So instead of the usual *golfing of code*, you will today be *coding a golf*.

## Challenge

Write a program (A) in language **A** which will output the source code of another program (B) of language **B**, which in it's turn will output `Vroom vrooom!` when executed.

## Rules

* The source code of program A is formatted into a nice ASCII car (not necessarily a volkswagen).
* Program A must be executable in the format you posted it in.
* Language A is ***NOT*** the same language as language B.
* The output of program B may or may not end with a new line.
* Program A takes no input.
* In non-obvious languages (esoteric) please explain program A.
* You must start your answer with `# Language A, Language B` eg. `# Brainfuck, Python`.
* Valid languages must have either an English Wikipedia article, an esolangs article or a Rosetta Code article at the time this challenge was posted.
* Be creative :-)

## Scoring

This is a popularity contest. Whichever answer has the most upvotes by Oct 4, will be declared the winner.

## Example

# Brainfuck, Python 2

```
                   ++++++++++[>+++>
                ++++    ++>+++    ++++
              +++<        <<        -]>>>
     ++++++++++++.        ++        .------
   ---.+++++.++++++.<<++.++.>++++++++++++++
 ++++++++++++.>--.---..--.<<--.>>+++++++++.
 ----.---...--.----------------------------
  ---------------------------------------
     \--o--/                    \--o--/
      \-_./                      \+_./

```

This outputs the following code, which can be executed in Python 2;

```
print "Vroom vrooom!"

```

# Answer
> 41 votes
## evil, JavaScript (ES6)

```
                                        aeMeeeDDDeDDDwHwwwwwwDaeeaeae;.
                                  .eu@wa04QMMM4WHHWWM#404HGV#0B4aeee0HeHa
                               .ewD&M%e       aG##a       aa a@Q%Bwaaeeuu4.
                           .uwuwW&u          e&M&e        H  wB0B&uGMVBGuuGu
                          wuu@M0Bu           wW@4Be      ueu=w#H00%V%QG@W%eGa
               ...aa+aeeweWWaee#G&G%V@B@G0@B&00V0V0%4VB4%BQGeewwB%BwwwV0%HMwae
           eaeee&BQM%M@4B%Mu%4G@BMwaeeaeeaawwaeeeuuuuwaaaeewwwuueee&QBeweaeMQ4e
      ,w#QawaHBH4Veaaaawueueeawaaeeeeuuwue&%#eeaeewaaawueewaeaeawueaQBBeeeHVewe.
    .eeuu0waaeQMQ%0Waaaawaeaeeee+u<+<=<===->::w~<+<=~-:<><uuwaeeaee&@B&&uuwawaa.
   aaaaaweaaQ#@4%@4#Veuuu~><uuw<-ewaaeueeaweeeeueweaeewaaaee-weH#V#%BBQ@0ueeawea
   aeewuuu#QB4B4B&0W%QVeuweeeaeM4M%&0W&MG@M0QV%VB0M%W0M&#QQeae4%#G#Q%4#4Q#Vwu>uuw
  wQWGuuwMHWVVuue<e%eQ4M4#@0BBWVHVVQ#4HG4%B%#&H@M#BMM0G0MVW0WQ44uwue.eueHGG#waHBe
  e&H0ueeV%Heu0wu,GQu0BGWQVH40MM4@0H0BQMMHWW%weueeaawuuuuwuu#@4Hu@&w+MVw@4M%ueeB
   %B0V&QW%MaVee>uwH%BW%4aeeeeueeuweaeeeeBMBGM&%H0QG&44#Mwe&#%VaWeeee~&Qw#V%G&wu.
   eaeDD&WQ&eGu,.&&0H%04ewaeeaDeB%#HG&#H#BQQ#&#@0Vuw0HBMaD4H#G#eWDee%DaD.Ww
         .u%.ue.4aaa.@Mw                                    ,w&wDwwDwwue@a
           eeHueMwa@Ge                                       .uV&.eeDw.4u
            "ee00V0e'                                          "a@HB4wP

```

For the evil program, I used a similar method as I did for this answer. In summary, I generated an optimally short program (limited to these four commands) that produced the desired JS, before mixing it with ignored characters to make a Volkswagen golf.

It prints out the following JS program, which in turn prints out `Vroom vrooom!` to the console:

```
       c=console
      o  =   x=>c
.log(x+"om!");O=o
Q="Vroom\x20vroo";
  (O)       (Q)

```

# Answer
> 19 votes
# Common Lisp, BASIC (and Python)

I took inspiration from some nice ASCII cars. Mine is a pickup truck seen from behind:

```
         (if'(
      (-----------------)
    _(  _______________  )_
   (_( (               ) )_)
     ( (_______________) )
     (                   )
   (=======================)
   (( MY OTHER CAR        ))
   (( IS A CDR            ))
   (-----------------------)
    (  )               (  )
    (__)               (__))
(lambda()(format t"~&PRINT ~S~%""Vroom vroom!")))

```

# Answer
> 12 votes
# CJam, C++

My car is a 1988 Pontiac Trans Am. (I tried my best. :P)

```
                                 "#"e####===========_
                            "inclu"+               e#\
                          "de "   +           "<iostream>"+e#+--.____    __..
             N+N+"using"+" namespace "+"std;"+Ne#---" """""       """""  __'
      +N+"int "                                                    +"main()"+
 N+"{"+N+" "4*+"c"   +"out << \"Vr"+e#====================.--""  ""--.=======:
e#      [w] : /        \ : |========================|    : /        \ :  [w] :
"oom"+" vro"+            "oom!\";"+e#===============|    :|          |:   _-"
 N+"}"+e#___: \        / :_|=======================/_____: \        / :__-"
  e#--------'  ""____""  `-------------------------------'  ""____""

```

You can test this here.

## CJam

```
"#include <iostream>"N+N+"using namespace std;"+N+N+"int main()"N+"{"+N+" "4*+"cout << \"Vroom vrooom!\";"+N+"}"+

```

And you can test that, here.

## C++

```
#include <iostream>

using namespace std;

int main()
{
    cout << "Vroom vrooom!";
}

```

# Answer
> 11 votes
## BrainFuck, Golf Script, Glee, JQ, Lasso, Lang5 & many more

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

```

Output

> "Vroom vrooom!"

Which will be valid syntax for these language which will ouptut "Vroom vroom!"

Golf Script

Glee

J

JQ

Lasso

Lang5

m4

Ml/I

Salmon

TPP & many more

This list came from Rosetta code's Hello World Program

# Answer
> 6 votes
# Java, Python

```
    public final class
Car{public static void main
(String    ...a    ){System
//CCCCC    CCCC    CCCCCCCC//
.out.println("print(\"Vroom"+
" vroom!\")");}}//HDBSKJBGIWE
      /////         /////
       ///           ///

```

(Sorry, the car's really bad)

---
Tags: popularity-contest
---