title: Produce an unexpected word

text:
# Question
Title: Produce an unexpected word
The goal is to write program that will produce a word **unexpectedly** (program doesn't look like it is going to produce a word).

Example (JavaScript):

```
alert(([0][1]+"").slice(4,8))

```

> alerts "fine" - jsfiddle.

Explanations:

> 1. `[0][1]` returns undefined, because there only one element in array `[0]`
> 2. Adding empty string converts `undefined` to string "undefined"
> 3. `slice(4,8)` outputs fifth to eight characters of `undefined`

---

This is **underhanded popularity contest**.

# Answer
> 100 votes
# Python2.x

```
import re
try: re.compile("[")
except re.error, e: print e.message.split()[0]

```

try it

# Answer
> 102 votes
# CJam

```
"":iXf&YbBB*b:c

```

Prints *Pneumonoultramicroscopicsilicovolcanoconiosis*.

Try it online. (Permalink works in Chrome. You have to copy and paste the code in some browsers.)

To understand how it works, click here to run this:

```
"":i5f%5b5I*b' f+~

```

### I still don't get it!

* > The first code block is actually 970 bytes long, since there are 318 zero-width characters (U+200B and 0+200C) between the two double quotes. Even with a monospaced font, these characters are completely invisible.
* > `X`, `Y` and `B` are variables initialized to 1, 2 and 11.
* > `:iXf&` casts each character to an integer (8203 or 8204) and computes the parity. This way, U+200B becomes 1 and U+200C becomes 0.
* > `Yb` converts the array of integers from above to an integer by considering it a base 2 number.
* > `BB*b` converts that integer into an array of its digits as a base 121 number.
* > The sad smiley `:c` casts each digit to its corresponding ASCII character.
* > The second code block is actually 6543 bytes long. It follows the same idea, but it uses the characters U+200B to U+200F, base 5 numbers and string evaluation.

# Answer
> 42 votes
# Python

I don't expect any upvote (but pwease don't downvote this either - unless the net votes are above 0!), because of course I claim *NO MERIT WHATSOEVER* on this answer, but in my opinion, the award would go hands down to **Tim Peters** for this Python code...

```
import this

```

(If you've never heard about it, try it here :) )

# Answer
> 32 votes
Ok - here'we go:

**Javascript:**

```
new Function("".split("").map(function(v){return String.fromCharCode(v.length)}).join(''))();

```

Evaluate it in your console...

> It can't be that easy. Try to find it yourself.

# Answer
> 27 votes
# C - ioccc feeling

```
#define\
    __(a,b) b##a
    __(in(O){,ma)
    __(at*f=&O;,flo)
    #define\
    _ __(ntf("%f",*f);,pri)
    __(ng,lo)__(ng $;O=, lo)
        __(NE__;$=,__LI)
        O*4*2699*14449
        *__(1ll,1765069);O=~--O;_-_-
        _-_-_-_-_-_-__(ts(&$);},pu)

```

**output (using gcc 4.7.2):**

> -nan-nan-nan-nan-nan-nan-nan-nan BATMAN

# C - WinApi

leave it to the professionals

```
#include <Windows.h>

CONST CCHAR *ParseStringOutputHandler(HANDLE hOut)
{
    /*
    * Prototype for SEH support function.
    */
    CONSOLE_SCREEN_BUFFER_INFO SBInfo;
    COORD crdSBInfoCoord;
    COORD crdMaxWinSize;
    COORD crdSize;
    WORD wMagicNum = 0x40;
    WORD wAttr = 0x14;
    INT8 i;
    static CCHAR szParseArray[9];
    /*
    *       This file contains the definitions and prototypes for the compiler-
    *       dependent intrinsics, support functions and keywords which implement
    *       the structured exception handling extensions.
    */
    crdSBInfoCoord.X = _WIN32_WINNT_NT4 >> 8;
    crdSBInfoCoord.Y = SUBVERSION_MASK / 28;
    crdMaxWinSize.X = EXCEPTION_EXECUTE_HANDLER | 0x2;
    crdMaxWinSize.Y = (_WIN32_IE>>010) + 3;
    crdSize.X = _WIN32_IE_IE20 >> 0x8;
    crdSize.Y = 0x15;
    SBInfo.dwCursorPosition = crdSBInfoCoord;
    SBInfo.dwMaximumWindowSize = crdMaxWinSize;
    SBInfo.dwSize = crdSize;
    SBInfo.wAttributes = wAttr;
    /*
    * Currently, all MS C compilers for Win32 platforms default to 8 byte
    * alignment.
    */
    for (i = 1; i <= 8; ++i){
        switch (i){
        case STRICT:         szParseArray[i-1] = SBInfo.dwCursorPosition.X;     break;
        case DM_COPY:        szParseArray[i-1] = SBInfo.dwCursorPosition.Y;     break;
        case DC_PAPERSIZE:   szParseArray[i-1] = SBInfo.dwMaximumWindowSize.X;  break;
        case _CRT_PACKING/2: szParseArray[i-1] = SBInfo.dwMaximumWindowSize.Y;  break;
        case 0x5:            szParseArray[i-1] = SBInfo.dwSize.X;               break;
        case DC_BINS:        szParseArray[i-1] = SBInfo.dwSize.Y;               break;
        case (_WIN32_WINNT>>8)|(_WIN32_WINNT&1):
        case 010:            szParseArray[i-1] = SBInfo.wAttributes;
        }
        szParseArray[i-1] |= wMagicNum;
        if (i > 7){
            szParseArray[sizeof(szParseArray)-1] |= wMagicNum;
        }
    }
    szParseArray[8] = NULL; // set WINVER based on _WIN32_WINNT
    return szParseArray;
}

```

**output:**

> DICKBUTT

# Answer
> 22 votes
## CJam

This is my first practice with **CJam**:

```
77c79c_78c7(8+6*3+c"K"["MICHAEL" "JACKSON"]:Ls4=Ls6=@'R'E\

```

I'm sure I could do it better with more practice but it was fun.

It prints out

> MOONWALKER

You can check it out here.

# Answer
> 19 votes
# C

*Works only on a little-endian machine*

How to make a simple multiplication ?

```
int main(void) {
    //this is an easy multiplication example
    int a = 37897 * 210;

    //print the result
    printf("%s",&a);
    return 0;
}

```

outputs `boy`

> 37897\*210 = 7958370 (0x796f62)
> `boy` ASCII representation is 62-6f-79 (0x796f62 on little-endian)
> printf with `%s` print the string, not the integer.

**\>\> Try it here**

# Answer
> 18 votes
# Javascript

**Round 2:**

**Improved Solution:**

```
try{Joe}catch(е){alert(е.message.replace(/de?/g,''))}

```

*53 characters*

**Old Solution:** Prints the same but in more short `char` length:

```
try{Joe}catch(е){console.log(е.message.replace(/de|d/g,''))}

```

*60 characters*

**Round 1:**

*I am going to Joe's place, he is sick, even computer says that:*

```
try {
    x = Joe;
} catch (err) {
    msg = err.message.split(" ");
    console.log(msg[0] + " " + msg[1] + " " + msg[2] + " " + msg[3].substring(2, 6));
}

```

*162 characters.*

```
try{x=Joe}catch(e){m=e.message.split(" ");console.log(m[0]+" "+m[1]+" "+m[2]+" "+m[3].substring(2,6))};

```

*103 characters.*

*"Joe is not fine"*

# Answer
> 14 votes
# dc

`dc` can be used with pretty obscure expressions. Here is an example, nearly asking you a question! (second line):

```
dc -e '[<!][P[ ]P]sr[|]30 4+[p]5[ ]500d+300dZ73 16d6-r[PnPnPnPP]sa[sz-=r2;h*7+++[know ]lax]sb
    vv:ha7 d0 [you] sp[eak?]                                                             lbx'

```

> Output: `I know 1337 5p34|<!`

Edit: splitting original answer into three different ones (`bash` and haskell proposals in separate posts)

# Answer
> 14 votes
# C, C++

Here's an oldie that could easily be adapted to other programming languages:

```
#include <stdio.h>

int main() {
    int i = 0x6F56DF77;
    printf("%8X", (i << 1) + 1);
}

```

> The trick is using the numbers \>9 in hexadecimal (or higher) number systems. This one print's `DEADBEEF`, but there can be many variations. AFAIK Mac OS used to mark released memory in certain debug builds as dead beef.

Try it!

# Answer
> 13 votes
## Common Lisp

No attempts to hide *how* this one works.

```
(let ((*print-base* 36))
  (print #x1A92721254086478787CE5D7))

```

> SPANISHINQUISITION

# Answer
> 12 votes
# sed

Of course with `sed` one is waiting for a string output. But if you do not already know this one, I think it can be considered as… unexpected:

```
sed 's/ //g;s/h.*yo//;s/od.*//;y/euHodityn,/ -aegmoptt/;s/ //;e'
    <<< 'Hey, have you done it today?'

```

I can't write the answer correctly in a “spoiler” block, so you'll have to try it yourself :)

(Hint: works best on Debian/Ubuntu. Don't loose your time on Mac.)

**Edit:** I discovered that I *could* use code in spoiler blocks, so output is now hidden below.

> ```
>          (__)
>          (oo)
>    /------/
>   / |    ||
>  *  /---/\
>     ~~   ~~
> ...."Have you mooed today?"...
> ```

# Answer
> 10 votes
# CJam

```
PT/

```

Try it at http://cjam.aditsu.net/

Also, for fun:

```
"HAL":)

```

# Answer
> 8 votes
# PowerShell

Can it be multiple words? If so, allow this to blow your freakin' mind.

```
function recurse() {
    $r = 72,29,7,0,3,-79,87,-8,3,-6,-8
    $s = ""
    $t = {
        $a,$b = $r
        $d+=$args[0]+$a
        $s+=[char]$d
        if ($b -ne $null) {
            return recurse $d $b $s
        }
        return $s
    }
    function recurse() {
        $r = $args[1]
        $s = $args[2]
        . $t
    }
    . $t
}
recurse 0

```

> Returns "Hello world" in a very complicated way

# Answer
> 8 votes
# **Ruby**

```
def handle(switch)
  case switch
  when 'a',
    print(switch << 'a')
  when 'n',
    print(switch.sub!('b','n'))
  when 'q',
    print(switch.gsub('b','q'))
  when 'b',
    nil
  else
    print('s!')
  end
end

handle('b')

```

Demo

# Answer
> 7 votes
# Perl

```
print pack qq;
\1108;
,hex for qw;
2e5d66e 4b88fad 4560770 3aedf79;

```

Prints a friendly message for a special day!

> Outputs `Happy Birthday!!` (Was given to a programmer friend who hates Perl.)
>
> The white space and semicolon as the delimiting characters are meant to deceive.
>
> **qq;\1108;** (equivalent to "H8")
> The semicolons are the delimiters for the double quote method. \110 is the octal code for H, followed by a plain 8, giving us the packing code "H8", meaning 8 hex digits
>
> **hex**
> Converts a hex string to an integer. No parameter means it runs on $\_ (default variable)
>
> **for qw;2e5d66e 4b88fad 4560770 3aedf79;**
> The semicolons are the delimiters for the quoted list method. `for` indicates to run the entire block on the left once per each hex string.
>
> "Unobfuscated", the script is:
> `print pack("H8", hex($_)) for (2e5d66e 4b88fad 4560770 3aedf79);`
>
> Each of those hex values, when de-hexed into an 8 digit number, and then packed into a 4 characters, will print 4 of the letters of **Happy Birthday!!**

**Run it here**

# Answer
> 7 votes
*The goal is to write program that will produce a word unexpected*

I didn't read past that. I have a serious issue with reading long passages (and error messages).

I decided to create a simple program that alerts "5". Unfortunately, I can't seem to get it to work.

```
(function () {
    "use strict";

    function logError(e) {
        // I have a serious issue with reading long error messages
        // I'll just print the first word of the error and figure out what it means
         console.log(e.message.split(" ")[0]);
    }
    // Useful assert method for debugging
    function assert(value, message) {
        if (value === false) {
            throw new Error(message);
        }
    }

    // Sets a varaible "a" to 5 and alerts it
    try {
        // Try it the old fashioned way
        a = 5;
        alert(a);
    } catch (e) {
        logError(e);

        // In some legacy browsers, that might now work
        // because alert requires a string
        try {
            // create objA which has a method "word", which always returns a word, or a string
            var objA = {
                word: function () {
                    return new String(5);
                }
            };
            // Make sure it is a string
            assert(typeof objA.word() === "string", "word didn't return a string");
            alert(objA.word());
        } catch (e) {
            logError(e);
            // Some browsers, such as chrome, just won't work
            // It's time to be evil and force them to work!
            try {
                eval("a = 5" +
                    "alert(a)");
            } catch (e) {
                logError(e);
            }
        }
    }
})();

```

Tested in the google chrome console. It produces (literally) *a word unexpected*.

http://jsfiddle.net/prankol57/Af4sH/ (For the jsfiddle, you must open your console, there won't be any html output)

# Answer
> 6 votes
# Javascript

> alerts "hello"

```
var $$ = String.fromCharCode;this[(+{}+[])[-~[]]+(![]+[])[-~-~[]]+([][+[]]+[])[-~-~-~[]]+(!![]+[])[-~[]]+(!![]+[])[+[]]]($$((((((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))*((+!+[])+(-~+[])))))+(((+!+[])+(-~+[]))*((+!+[])+(-~+[]))))+$$((((((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))*((+!+[])+(-~+[])))))+(-~+[]))+$$((((((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))*((+!+[])+(-~+[])))))+(((((+!+[])+(-~+[]))*((+!+[])+(-~+[])))*((+!+[])+(-~+[])))))+$$((((((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))*((+!+[])+(-~+[])))))+(((((+!+[])+(-~+[]))*((+!+[])+(-~+[])))*((+!+[])+(-~+[])))))+$$(((((((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))+((!+![])^((+!+[])+(-~+[]))))*(((+!+[])+(-~+[]))*((+!+[])+(-~+[])))))+(((((+!+[])+(-~+[]))*((+!+[])+(-~+[])))*((+!+[])+(-~+[])))))+(((!+![])^((+!+[])+(-~+[]))))));

```

*caveat: one variable declaration.(no time for changing `String.fromCharCode` to symbols)*

more readable code (solution is derived from this code (it's mine BTW))

### Ref:

1. http://sla.ckers.org/forum/read.php?24,33349,33405
2. http://patriciopalladino.com/blog/2012/08/09/non-alphanumeric-javascript.html (inspired for accessing `alert` from symbols)

# Answer
> 5 votes
# Ruby

```
display(STDOUT) unless case class Do
self
end when method(:print).to_proc
end

```

I've used this trick in an earlier underhanded contest, but I thought I'd dress up the output a bit differently.

Demo

First person to explain where the word

> Domain

comes from wins a no-prize.

# Answer
> 5 votes
# JavaScript, 10 characters

`alert(1/0)`

Test it on http://jsfiddle.net/cC52Z/!

## Output

> Infinity

## Explanation

> Instead of disallowing division by zero, JavaScript makes it always return Infinity (division of a negative by zero produces -Infinity).

# Answer
> 5 votes
## Emacs Lisp for version 22.1.1 (that comes on osx)

Run this right on the command line

`emacs -q --batch --eval "(progn (execute-kbd-macro \"\C-[xinfo\C-m\C-[xfun\C-i\C-m\C-u49\C-n\") (search-forward (string(+ ? ? (*)? )(+(/ ? (+(*)(*)(*))) ? ? ? (*(+(*)(*))(+(*)(*))))))(print (buffer-substring-no-properties (+(*)(*)(*)(point)) (progn (forward-word(*)) (point)))))"`

Output: **"woman"**

# Answer
> 5 votes
## Python

Inspired by @Roberto's answer.

```
try: exec('from __future__ import braces')
except Exception as e: print(e.msg)

```

> Another Python easter egg; it prints: `not a chance`

# Answer
> 5 votes
## TI-BASIC

```
:

```

(Either type the colon on an empty screen, or make an empty program or one containing just colons.)

Prints "Done"

# Answer
> 5 votes
# Homespring

(Empty program)

### Output

> In Homespring, the null program is not a quine.

### Why?

> Homespring prints this message when interpreting a empty program to prevent cheating at code golf challenges

# Answer
> 4 votes
# GolfScript

```
0:b;"#{STDIN.inspect}"${b{..}{.}if 78={6-.1:b;}{}if;}%

```

Outputs:

```
HOST

```

Try it out here.

How it works:

> `"#{STDIN.inspect}"` returns `"#<IO:<STDIN>>"`. `$` sorts it into `"#:<<>>DIINOST"`. The rest of the program loops through the string, dropping chars until it finds an `N`. Then, it changes the `N` to a `H` and keeps the rest of the chars.

# Answer
> 4 votes
## Perl

```
#!perl
eval('(*16,z<=:3??0<x06161xBBQ$8t'^((
'0'x27)^((((((('h'x6).'A'.'b'x5).'a'.
'h'x2).'A'.'h'x5).'A'.'H'x3).'f'x2))))

```

> **Output:** Mohammad Anini 3:)

# Answer
> 3 votes
# Julia

```
(repr(typeof(""))*repr(typeof(' '))*repr(typeof(1//1)))[6:7:27]

```

Another option:

```
print(print())

```

# Answer
> 3 votes
# T-SQL

```
declare @S char(3)  -- Declare a string variable that holds three characters
set @S = 1000       -- Implicitly convert the value 1000 to string
select ascii(@S)    -- Get the ASCII code value of the leftmost character

```

Outputs

> The Answer to the Ultimate Question of Life, the Universe, and Everything

SQL Fiddle

# Answer
> 3 votes
## JavaScript

```
for (var i in this) {
  if(parseInt(i[0]+i[2],16)==174) {
    this[i](i[0]+i[1]+i[2]);
    break;
  }
}

```

Not the cleverest. But, I sure do like what it has to say!

Tested in Chrome.

# Answer
> 3 votes
# Bash

```
<<< echo echo echo

```

or

```
`echo echo echo`

```

> Both commands output `echo`, of course.

# Answer
> 3 votes
# Java

This code is a bit long, outputs word:

> SEVERE

```
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Text
{
    public static void main( String args[] )
    {
        makeSureWeCantOutputText();
        unexpected();
    }

    private static void unexpected()
    {
        try
        {
            //this does nothing
            long x = 1;
            for( int i = 1; i / i == 1; i++ )
            {
                x++;
            }
        }
        catch( Exception ex )
        {
            Logger.getLogger( Text.class.getName()).log( Level.SEVERE, "");
        }
    }

    private static void makeSureWeCantOutputText()
    {
        try
        {
            //OutputStream class that outputs to nowhere
            PrintStream stream = new PrintStream( new OutputStream()
            {

                @Override
                public void write( int b ) throws IOException
                {
                }

            } );

            //replace System.out field with OutputStream that does nothing
            Field field = System.class.getDeclaredField( "out" );
            field.setAccessible( true );

            Field modifiersField = Field.class.getDeclaredField( "modifiers" );
            modifiersField.setAccessible( true );
            modifiersField.setInt( field, field.getModifiers() & ~Modifier.FINAL );

            field.set( null, stream );
        }
        catch( Exception e )
        {
            //we don't want to outpout anything if it fails
        }
    }
}

```

Explanation:

> When exception is thrown we use Logger. Logger with Level.SEVERE Logger uses System.err instead of System.out. i / i throws exception when i reaches 0 (it starts from 1 and increases, then integer overflows to Integer.MIN\_VALUE and is increased to 0).

# Answer
> 3 votes
# Ruby

```
#!/usr/bin/ruby
a = self.methods.map{|x|x.to_s}
b = a.count
p a[b/2-8]+a[b-6]

```

Outputs:

```
"freeze!"

```

# Answer
> 3 votes
# Ruby

Bit late to the party, but couldn't help but notice that no-one had done something like this:

```
puts 65791925216734442002988169043447582627179158156970580.to_s(36)

```

Demo

# Answer
> 2 votes
# JavaScript

```
function rgbToHex(rgb) {
  var r = rgb[0].toString(16);
  var g = rgb[1].toString(16);
  var b = rgb[2].toString(16);
  return '#' + r + g + b;
}

alert(rgbToHex([176,0,11]));

```

# Answer
> 2 votes
## JavaScript

Test it on your browser's console

```
x = Math.random() > 0.5 ? 2 : 0;
alert(document.getElementsByClassName('question-hyperlink')[0].text.substr(13 - x,13 + x))

```

# Answer
> 2 votes
# J

This is what happens if you're bored.

```
'Nqbs a `u{c vac'({&a.@-@(t@[-+:@t=:a.&i.@]))'Kill a good man'

```

Output:

> `Have a nice day`.

Why?

> It calculates `-y - x - x` where `x` is the left string and `y`is the right string.

# Answer
> 2 votes
**IBM Enterprise COBOL**

```
   ID DIVISION.
   PROGRAM-ID. ERRMSG.
   ENVIRONMENT DIVISION.
   DATA DIVISION.
   WORKING-STORAGE SECTION.
   01  A PIC 9 VALUE ZERO.
   PROCEDURE DIVISION.
       ADD 1 TO A
       GOBACK
       .

```

Here's a short program. It obviously does nothing but add one to the field A.

However, toss it into the compiler, and... http://www-01.ibm.com/support/docview.wss?uid=swg21156178

> You can generate a complete listing of compiler diagnostic messages with their \>message numbers, severities, and text by compiling a program that has program-name ERRMSG.
>
> You can code just the PROGRAM-ID paragraph, as shown below, and omit the rest \>of the program.

The key is to have `errmsg` as the `PROGRAM-ID`. No other code is required. The code in my example is just to convince that it is a real program which produces no output.

This is the example IBM show in the link:

```
Identification Division.
Program-ID. ErrMsg.

```

Indeed, this is enough:

```
Program-ID. ErrMsg.

```

Or this:

```
Program-ID. ErrMsg.
The quick brown fox jumped over the
lazy dog, or any other text you like.

```

This is an example of the output: http://www-01.ibm.com/support/docview.wss?uid=swg21156178&aid=1

When the compiler gets to errmsg. (note the full-stop/period, which doesn't have to be immediately after errmsg, but must exist after it somewhere in the source) it knows what is needed, reads to the end of the source and then produces the listing, including the description of the format and information contained in the error messages, and all the messages themselves.

As a curiosity, you can try this:

```
Program-ID. ErrMsg

```

This time no full-stop/period is encountered before the end of the source is reached, and a (very) minor compiler bug is revealed, as the compiler continues reading, and abends (ends abnormally, crashes) with an S001 Reason Code 5 and

```
IEC020I GET ISSUED AFTER END-OF-FILE

```

No IBM Mainframe COBOL has ever separately documented its error messages in an actual manual.

# Answer
> 2 votes
# Mathematica

```
ToString[#&@;;]~StringTake~{16,20}

```

Prints "Dummy". But I seriously do not understand why `#&@;;` does..what it does.

# Answer
> 1 votes
## Javascript - 19 chars

This one is inspired by Gary Bernadt's 'wat' talk: Video Link

```
([]+{}).substr(1,6)

```

Unexpected because `Array []` \+ `Object {}` should not output an Object.

> "object"

Another solution suggested by bebe

```
(0+{}).slice(2,8)

```

> "object"

# Answer
> 1 votes
## Mathematica

```
SeedRandom[377]; FromCharacterCode@RandomInteger[{98, 123}, 5]

```

> outputs `proof`

```
BaseForm[272580165883129, 29]

```

> outputs `impossible`

You can try the second one online in Mathics. Type in the code and press `Shift`-`Enter`. The first one is implementation specific, thus it won't work in Mathics, but it does work in *all* recent versions of Mathematica.

# Answer
> 1 votes
# Perl

```
open IN, "<".$0;
while (<IN>) {
        chomp;
        (m/(^|[^\)])w.i.e/ && (s/^.(.).(.)(.).*/$1$3$2$2/ && print $_)) || m/(^|[^\)])...se/ && (s/^..(.).*/$1/ && print $_."\n");
}
close IN;

```

> Opens it's own script file and prints out some of the characters.

# Answer
> 1 votes
## C++

```
#include <iostream>
#include <limits.h>
#include <math.h>
using namespace std;
typedef unsigned long long ULL;
#define C(x) cout<<(ULL)(x)<<endl
int main ()
{
    ULL b=UINT_MAX;
    ULL d=LLONG_MAX;

    ULL f=(ULL)(d/b);
    size_t n = (log(f)/log(10))+1;
    char *w=new char[n];
    char x;
    for(size_t i=0; i<n; i++)
    {
        x = (char)((f%10)+'@');
        f=(ULL)(f/10);
        w[n-i-1]=((n-i)<4)?x:0;
    }
    cout<<w<<endl;
    return 0;
}

```

Produces the word "BAD".

# Answer
> 1 votes
# Extended BrainFuck

```
>~~ufp~<.[-.<]

```

> outputs "poet"

# Answer
> 1 votes
## Burlesque

```
blsq ) 4593109656 128B!
"hello"
blsq ) vvSh29.-4.+
"size"

```

**Explanation**

`128B!` is just base 128.

`vvSh29.-4.+` produces an error, converts the error to a string and then slices.

# Answer
> 1 votes
# Mouse-2002

```
' '  + 20 + b + a + !'
' '  + 13 + i + z + !'
' '  + 4  + i + z + !'
' '  + 23 + i + z + !'
' '  + 15 + i + z + !'
' '  + 4  + i + z + !'
' '  + 2  + i + z + !'
' '  + 19 + i + z + !'
' '  + 4  + i + z + !'
' '  + 3  + i + z + !'
'  '   +  s  -  !'
'  '   +  n n + n n + + c + -  !'

$

```

Output:

> `Unexpected.`

Explanation:

> uses ascii charcodes. the letters refer to addresses, which are integers in the range `0-25`.

# Answer
> 0 votes
# PHP, 59 or 31 chars

Does it have to be a real word? If not, this will work:

```
echo preg_replace('/[0-9]+/',"",substr(md5(time()),0,25));

```

or even this if numbers are okay:

```
echo substr(md5(time()),0,25);

```

Set a range

```
echo substr(md5(time()),0,rand(1,50));

```

# Answer
> 0 votes
# Haskell

Classic:

```
let 1+1="Hello World!" in 1 + 1

```

> Outputs `Hello World!`. No kidding.

---
Tags: popularity-contest, underhanded
---


title: The middle-square method

text:
# Question
Title: The middle-square method
### Introduction

The *middle-square* method is used for the generation of pseudorandom numbers. However, this is not a good method in practice, since its period is usually very short and has some severe weaknesses. How does this work? Let's take an example:

For the seed, we pick `123456`:

```
Seed     123456

```

The seed squared (seed × seed), is equal to:

```
Seed²  15241383936

```

We started with a **6-digit** number. That means that the seed squared should deliver a **12-digit** number. If this is not the case, leading zeroes are added to compensate:

```
Seed²  015241383936

```

We then take the middle part of the number, with **the same size** as the seed:

```
Seed²  015241383936
          ^^^^^^

```

This is then our **new seed**: `241383`. We repeat the same process as shown above. We get the following:

```
0:     123456
    015241383936
       |    |
1:     241383
    058265752689
       |    |
2:     265752
    070624125504
       |    |
3:     624125
    389532015625
       |    |
4:     532015
    283039960225
       |    |
5:     039960
    001596801600
       |    |
6:     596801

```

And this keeps on in a while... Now we know what the middle-square method is, let's get to the challenge:

---

### The Task

Every seed **has** a *period*. The period of a *n*-digit seed cannot be longer than 8n. For example, the seed `82`. This would give the following sequence:

```
82 > 72 > 18 > 32 > 02 > 00 > 00 > 00 > 00 > 00
|____|____|____|____|____|____|____|____|____|___...
0    1    2    3    4    5    6    7    8    9

```

You can see that the period is equal to **5**, before containing the same digit again. Your task is, **when given a seed greater than 0 containing no leading zeroes, output the period of the seed**. So, in this case, you need to output `5`.

Another example is: `24`, which gives the following:

```
24 > 57 > 24
|____|____|___...
0    1    2

```

As you can see, not all sequences end in `0`. This cycle has a period of *1*.

---

### Test cases

```
Input   >   Output
24      >   1
82      >   5
123456  >   146
8989    >   68
789987  >   226

```

The pastebins with the sequences for 123456, 8989, 789987

This is , so the submission with the least amount of bytes wins!

**You can assume that the input will never have an uneven number of digits.**

# Answer
# Jelly, ~~26~~ ~~24~~ 18 bytes

```
³DL⁵*
²:¢½¤%¢µÐĿL’

```

Try it online!

### How it works

```
³DL⁵*         Helper link. No arguments.

³             Yield the original input.
 D            Convert from integer to base 10.
  L           Get l, the length of the decimal representation.
   ⁵*         Compute 10 ** l.

²:¢½¤%¢µÐĿL’  Main link. Input: n (integer)

²             Square n.
  ¢½¤         Call the helper link and take the square root of the result.
 :            Integer division; divide the left result by the right one.
      ¢       Call the helper link.
     %        Take the left result modulo the right one.
       µ      Convert the previous chain into a link, and begin a new chain.
        ÐĿ    Repeat the previous chain until the results are no longer unique,
              updating n in each iteration. Collect the intermediate results.
          L   Get the length of the list of results.
           ’  Decrement.

```
> 3 votes

# Answer
### Pure bash, ~~162 131 116 113~~ 107

Saved 3 bytes by using `$c`...

Thanks @Dennis for help me to save 6 more bytes.

`---- begin middleSquare ----`

```
for((b=$1;i[c=10#$b]<2;)){ a=${#b}
printf -v b %0$[a*2]d $[c*c]
b=${b:a/2:a};((i[10#$b]++))
};echo ${#i[@]}

```

`---- end middleSquare ----`

```
for testCase in 24 82 123456 8989 789987 111111;do
    printf "%12s: " $testCase
    bash middleSquare $testCase
  done
          24: 2
          82: 5
      123456: 146
        8989: 68
      789987: 226
      111111: 374

```

### Square formated, 131

`---- begin middleSquare ----`

```
for((b=$1;i[
10#$b]<2;1))
do a="${#b}"
printf -v b\
 %0$[a*2]d \
$[10#$b**2];
b=${b:a/2:a}
((i[10#$b]++
));done;ech\
o ${#i[@]:0}

```

`---- end middleSquare ----`

```
for testCase in 24 82 123456 8989 789987 111111;do
    printf "%12s: %9d\n" $testCase $(
        bash middleSquare $testCase)
  done
          24:         2
          82:         5
      123456:       146
        8989:        68
      789987:       226
      111111:       374

```

### Old but with fancy output, 162

`---- begin middleSquare ----`

```
for((b=$1;i[10#$b
]<2;1))do a=${#b}
printf -v b %0$[a
*2]d  $[10#$b**2]
b=${b:a/2:a};((i[
10#$b]++));print\
f "%9d %s\n" ${#\
i[@]} $b;done;ec\
ho -- ${#i[@]} --

```

`---- end middleSquare ----`

```
bash middleSquare 24
        1 57
        2 24
        2 57
-- 2 --

for testCase in 24 82 123456 8989 789987 111111
    do while read f v f
        do r=$v;done < <(
        bash middleSquare $testCase)
    printf "%12s: %11d\n" $testCase $r
  done
          24:           2
          82:           5
      123456:         146
        8989:          68
      789987:         226
      111111:         374

```
> 5 votes

# Answer
# Python ~~3~~ 2, ~~139~~ ~~114~~ 97 bytes

Thanks to Seeq for golfing off 25 bytes and thanks to Dennis for golfing off 17 bytes! Code:

```
s=`input()`;u=[];l=len(s)/2
while not s in u:u+=[s];s=`int(s)**2`.zfill(l*4)[l:3*l]
print~-len(u)

```

Can definitely be golfed further. This was also the code used to make the test cases :P.
> 3 votes

# Answer
## JavaScript (ES7), 82 bytes

```
f=(n,p={},m=-1,l=n.length)=>p[n]?m:f(`${n*n+100**l}`.substr(l/2+1,l,p[n]=1),p,++m)

```

Accepts input in the form of a string, e.g. "82", and returns an integer. Simple tail recursive technique to check each seed in turn against a hash of seeds that have already been seen. I add 100\**l to the square to ensure a consistent length.
> 3 votes

# Answer
# MATL, 33 ~~35~~ ~~40~~ bytes

```
`t0)2^10GVnXK2/^/k10K^\vtun@>]n2-

```

**Try it online!**

```
`           % do...while
  t         %   duplicate. Take input implicitly on first iteration
  0)        %   pick last value of array
  2^        %   square
  10        %   push 10
  GVn       %   number of digits of input
  XK        %   copy that to clipboard K
  2/        %   divide by 2
  ^         %   power
  /k        %   divide and floor. This removes rightmost digits from the square value
  10K^      %   10 ^ number of digits of input
  \         %   modulo. This takes the central part of the squared number
  v         %   concatenate this new number to array of previous numbers
  tun@>     %   does the number of unique values exceed the iteration index?
]           % if so: next iteration. Else: exit loop
n2-         % desired result is the amount of numbers minus 2. Implicitly display

```
> 2 votes

# Answer
# Pyth, 21 bytes

```
tl.us_<>_`^N2/lz2lzsz

```

Try it online: Demonstration or Test Suite

edit: Found the edge case `1000`, which didn't worked with my previous code. Fixed it for 1 byte.

### Explanation:

```
tl.us_<>_`^N2/lz2lzsz   implicit: z = input string
  .u               sz   apply the following instructions to N, starting with N = int(z),
                        until it runs into a loop:
          ^N2              square it
         `                 convert it to a string
        _                  reverse order
       >     /lz2          remove the first len(z)/2
      <          lz        remove everything but the first len(z)
     _                     reverse order
    s                      convert to int
  .u                   returns the list of all intermediate values
 l                     compute the length of this list
t                      minus 1

```
> 2 votes

# Answer
# Oracle SQL 11.2, 184 bytes

```
WITH v(v,p,n)AS(SELECT:1,'0',-1 FROM DUAL UNION ALL SELECT SUBSTR(LPAD(POWER(v,2),LENGTH(v)*2,0),LENGTH(v)/2+1,LENGTH(v)),v,n+1 FROM v)CYCLE v SET c TO 1 DEFAULT 0 SELECT MAX(n)FROM v;

```

Un-golfed

```
WITH v(v,p,n) AS
(
  SELECT :1,'0',-1 FROM DUAL
  UNION ALL
  SELECT SUBSTR(LPAD(POWER(v,2),LENGTH(v)*2,0), LENGTH(v)/2+1, LENGTH(v)),v,n+1 FROM v
)
CYCLE v SET c TO 1 DEFAULT 0
SELECT MAX(n) FROM v;

```

It uses the build in cycle detection to stop the recursivity.
> 2 votes

# Answer
# Julia, 64 bytes

```
f(n,A=[],p=10^endof(dec(n)))=n∈A?-1:f(n^2÷√p%p,[A...n],p)+1

```

Try it with Coding Ground.
> 2 votes

# Answer
# Mathematica, 80 bytes

```
(a=10^⌊Log10@#+1⌋;Length@NestWhileList[⌊#^2/a^.5⌋~Mod~a&,#,Unequal,All]-2)&

```
> 1 votes

# Answer
# CJam, 37 bytes

```
q{__,W*:D;~_*sD2/<D>]___|=:A;~A}g],((

```

Ran into an annoying stack-order issue that I can't immediately see how to resolve. It's also incredibly slow.

How it works: Each iteration pushes the new value on top of the stack, then we wrap the stack into an array, and see if it's the same as its union with itself (to see if it has any duplicate elements). When it has duplicate elements, stop, and see how many elements are in the stack.
> 1 votes

# Answer
# Python 2, 82 bytes

```
def f(n,A=[],l=0):l=l or len(`n`)/2;return-(n in A)or-~f(n*n/10**l%100**l,A+[n],l)

```

Try it on Ideone.
> 1 votes

# Answer
## Python, 124 bytes

```
def f(s,p=-1,n=0,m=[]):
 x=len(str(s))*2
 while n not in m:m+=[s];y=str(s*s).zfill(x);n=int(y[x/4:x*3/4]);p+=1;s=n
 return p

```
> 1 votes

# Answer
## VBSCRIPT, 131 bytes

```
s=inputbox(c):l=len(s):do:t=t&","&s:s=space(l*2-len(s*s))&s*s:s=mid(s,l/2+1,l):i=i+1:loop until instr(t,","&s)>0:msgbox i-1

```

Best I could do with vbscript, first time poster so go easy on me!
> 1 votes

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


title: Radiation softened quine

text:
# Question
Title: Radiation softened quine
It's simple: Make a proper quine where if you remove any character, it's still a quine.

The difference between this and a radiation hardened quine is that if your program is `AB`, in a radiation hardened quine `A` would output `AB`, but here, `A` would output `A`.

Code golf, all standard rules, standard loopholes apply, no cheating.

# Answer
> 25 votes
# \>\<\> (Fish), 145 107 bytes

This answer uses \>\<\>'s jumping instruction to fix the problem.

```
!<0078*+00~..>0[!."r43a*+8a+&{ee+00&1-:&(?.~~ol?!;4b*0.0f<>0['r3d*159*+&}7a*00&1-:&(?.~~ol?!;68a*+0.0+*a58

```

This quine actually contains two different quine generators. It starts with some jumping logic and by default uses the left quine. If a character is removed from the jumping logic or from the left quine, the program jumps to the right quine.

You can try it here

# Explanation

The code can be dissected into a few parts:

```
A: !<0078*+00~..>0[!.
B:              >0[!."r43a*+8a+&{ee+00&1-:&(?.~~ol?!;4b*0.
C:                                                    .0f<
D:                                                        >0['r3d*159*+&}7a*00&1-:&(?.~~ol?!;68a*+0.
E:                                                                                .0+*a58

```

Explanation of the different parts:

* A: Jumps to the right of C. If any character is deleted from from A, this jumps to the left of D or the right of E, triggering the second quine. If any character is deleted from B or C, the code is shifted 1 character to the left, causing this to jump to the left of D.
* C: This code jumps to the left of B.
* B: Quine #1
* D: Quine #2
* E: Jumps to the left of D

# Explanation of the quine (with #1 as example):

Once the instruction pointer reaches either of the quines, you're certain that that quine is completely intact.

```
>0[!.                                       //Fix the instruction pointer's direction and empty the stack (The '!.' is a leftover from codepart A)
     "r43a*+                                //Start reading all of the code and add the '"' character to the stack
            8a+&                            //Because the quine started reading at the 19th character instead of the first, the stack has to move 18 characters.
                                            //This part saves the number 18 to the register.
                {ee+00&1-:&(?.              //Move the stack one to the left, decrease the stack by 1. If the stack is not empty yet, jump back to the start of this section.
                              ~~              //Clean the temporary variables from the stack. It should now contain the whole quine.
                                ol?!;4b*0.  //Print the first character from the stack. As long as the stack isn't empty, jump back to the start of this section.

```

# Answer
> 37 votes
# Lenguage, 4.54×10761 bytes

It has this number of null characters:

> 453997365974271498471447945720930600149036031871190716908688344432973027776681259141680552038829875159204621651993092104775733418288411812715164994750890484868305218411129600012389568016974351721147925344946382782884546247102886167837964612372737300786173159265347137401863281368021545169383664534228503236761742285358985343373496184959796553930661837467682191561275123057706776367104142995491262443697167483190110516522677811931124842961701222425076750211774387637740969301686178545299089832300154448308384461700726890067468872402133010536518468336342175124002115991866466700174974019423711837589532744970385003356612639263433822126850314801275940879069069974437167102618471264140597777702065896715558989678487253830854848740247786166790545462769498303055791292

Seeing how the criterion in this challenge conflicts with the definition of a "proper quine", seriously, I think an Unary variant is going to win.

Expanded Brainfuck code:

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

```

If one character is removed from the Lenguage program, the last character becomes a `<`, which causes the program to print exactly one less character.

---
Tags: code-golf, quine, radiation-hardening
---


title: When will I have a binary car?

text:
# Question
Title: When will I have a binary car?
I noticed that my car's odometer was at 101101 when I got to work today. Which is a cool number because it's binary (and a palindrome, but that's not important). Now, I want to know when the next time I'll have a binary odometer reading. I can't read the odometer while I'm driving, because that would be dangerous, so it'll have to be binary either when I get to work or get home.

There's really bad traffic on the way to and from my office, so I have to take a different route each day.

For the purposes of this challenge, a day is a round trip and starts with my commute to work.

You'll need to take the initial reading of the odometer and a 10 element sequence representing the amount of miles each way. This sequence should be repeated until you get to a binary odometer reading. You should then output the number of days it takes until we get to a binary reading.

Both the milage for the route and the odometer reading will be positive integers. The count of days will either be `x` or `x.5`, so your output of the day count needs to support floating point for half days. If the day count is an integer, you don't need to output the `.0`. The odometer will always eventually reach a binary state.

Any form of input/output is acceptable and standard loopholes are disallowed.

Test cases:

```
101101, [27, 27, 27, 27, 27, 27, 27, 27, 27, 27] == 165.0
1, [13, 25, 3, 4, 10, 8, 92, 3, 3, 100] == 22.5
2, [2, 3, 1, 2, 7, 6, 10, 92, 3, 7] == 2.0

```

# Answer
> 3 votes
# Jelly, ~~22~~ ~~17~~ 16 bytes

```
RịS+³DṀ=1
Ṡç1#SH

```

Try it online!

### How it works

```
Ṡç1#SH     Main link. Left input: n (initial reading). Right input: A (distances)

Ṡ          Compute the sign of n. Since n is positive, this returns 1.
 ç         Apply the helper link to 1, 2, 3, ... until...
  1#         one match is found. Return the match in an array.
    S      Compute the sum of the array. This yields the match.
     H     Halve the result.

RịS+³DṀ=1  Helper link. Left argument: k (integer). Right argument: A (distances)

R          Range; yield [1, ..., k].
 ị         Retrieve the elements of A at those indices.
           Indexing in modular in Jelly.
  S        Compute the sum of the retrieved distances.
   +³      Add n (left input) to the sum.
     D     Convert the sum to base 10.
      Ṁ    Get the maximum digit.
       =1  Compare it with 1.

```

# Answer
> 6 votes
# Javascript, ~~68~~ ~~63~~ ~~61~~ ~~60~~ 52 bytes

5 bytes off thanks @ETHproductions. ~~2~~ ~~3~~ 11!! bytes off thanks @NotthatCharles.

```
f=(i,a,m=0)=>/[^01]/.test(i+=a[m++%10])?f(i,a,m):m/2

```

Test here.

# Answer
> 5 votes
# MATL, ~~29~~ ~~26~~ 25 bytes

```
`tvyyYs+V50<!A~]xx1Mf1)2/

```

Input format is

```
[27; 27; 27; 27; 27; 27; 27; 27; 27; 27]
101101

```

*EDIT (June 10, 2016): The following link replaces `v` by `&v` (**26 bytes**) to adapt to changes in the language*

**Try it online!**

```
`              ]           % do---while loop. Exit loop when top of stack is falsy
 t                         % duplicate. Takes first input (array) first time
  v                        % concat vertically (doubles length of array)
   yy                      % copy top two. Takes second input (todasy's value) first time
     Ys                    % cumulative sum of (repeated) miles each way
       +                   % add to today's value
        V                  % convert each number to a string
         50<!A             % true for strings than only contain '01 ' (ASCII less than 50)
              ~            % negate. This is the loop condition
                xx         % delete stack contents
                  1M       % push again array that tells which strings only contain '01 '
                    f1)    % pick index of first true entry
                       2/  % divide by 2

```

# Answer
> 3 votes
## Lua, 108 Bytes

First time using the repeat..until loop in a codegolf!

```
function f(o,t)i=0repeat i,o=i+1,(o+t[i%#t+1]).."."o=o:sub(1,o:find("%.")-1)until tonumber(o,2)print(i/2)end

```

### Ungolfed

```
function f(o,t)               -- o can either be a number or a string, t is a table
                              -- call it like f(2,{27,14,5...})
  i=0                         -- initialise the travel count
  repeat                      -- proceed like a do..while in C
    i,o=i+1,(o+t[i%#t+1]).."."-- increment i, and add t[i] to the odometer
    o=o:sub(1,o:find("%.")-1) -- remove the decimal part of the odometer
  until tonumber(o,2)         -- tries to convert o from binary to decimal
                              -- return nil (and repeat the loop) if it can't
  print(i/2)                  -- print i/2 which is the number of days for i travels
end

```

After the first loop, `o` will have a decimal part because of `tonumber`, I had to remove it... And to add it for the first case, that's why I concatenate it with a `"."`.

# Answer
> 3 votes
## PowerShell, ~~84~~ ~~73~~ ~~67~~ ~~59~~ 57 bytes

```
param($a,$b)do{$a+=$b[$i++%10]}until(!+($a-replace1))$i/2

```

Takes input `$a` and `$b`, expecting `$b` to be an explicit array of mileages (e.g., `.\binary-car.ps1 1 @(13,25,3,4,10,8,92,3,3,100)`). We then enter a `do`/`until` loop. Each iteration, we increment `$a` with the mileage in `$b` at position `$i++ % 10` so that we continually loop through the array. This will start at zero since for the first loop the `$i` is not initialized, and so evaluates to `$null`, which equates to `0` in this context, and it's only *after* that evaluation that the `++` occurs.

Then, the `until` statement checks if our number is only `0` and `1` by first `-replace`ing all `1` with nothing, casting that back as an integer with `+`, and then taking the Boolean-not with `!`. If it evaluates true, we'll finish the loop, output `$i / 2`, and terminate the program.

**Explanation for the loop conditional --** In PowerShell, any non-zero integer is `$true`, and any non-empty string is also `$true`. For example, `231145` (an integer) will change to `"2345"` (a string) after the `-replace`, which will integer-cast as `2345` (an integer), the `!` of which is `$false`. However, `101101` (an integer) will change to `"00"` (a string) which will cast as `0` (an integer), the `!` of which is `$true`. If we didn't have the `+`, the `"00"` will `!` to `$false` since it's a non-empty string.

Edit - Saved 11 bytes by swapping equality-on-length for strictly-zero
Edit 2 -- Saved another 6 bytes by realizing that `$b.count` will always be `10` ...
Edit 3 -- Saved another 8 bytes by using do/until instead of for
Edit 4 -- If the object being `-replace`d is an integer value, don't need quotes, saving another 2 bytes

# Answer
> 3 votes
# Java, 112 ~~miles~~ bytes

```
float c(int r,int[]d){float y=0;for(int i=0;;i%=d.length){y+=.5;r+=d[i++];if((""+r).matches("[01]+"))return y;}}

```

# Answer
> 3 votes
# 05AB1E, 31 bytes

Code:

```
0IE\[²vs>sy+D§'aT«-""Qi\2/?}Ž}Ž

```

~~Somehow, the code doesn't stop running (and I can't figure out why)~~. Apparently I forgot that there are three loops going on instead of 2. So it would still get into an infinite loop...

Try it online!

# Answer
> 2 votes
# Ruby, 58

Nothing special. Just a cycle...

```
->s,a,i=0{a.cycle{|e|i+=0.5;break i if/[2-9]/!~'%d'%s+=e}}

```

# Answer
> 1 votes
# Pyth, ~~36~~ ~~32~~ 30 bytes

```
Jvz.V0=J+J@QbI<ssM{`J2KbB;chK2

```

Try it here!

### Explanation

```
Jvz.V0=J+J@QbI<ssM{`J2KbB;chK2  # Q = input sequence

Jvz                             # assign starting value to J
   .V0                          # Start an infinite loop iterating over b starting at 0
      =J                        # Set J to
        +J                      # the sum of J
          @Qb                   # and the value at Q[b % len(q)]
             I                  # if
              <      2          # lower than 2
                  {`J           # Remove duplicate digits from J
               ssM              # Map the remaning digits back to integers and sum them
                      KbB       # if the above evals to true, save b to K and leave the loop
                         ;      # End loop body
                           hK   # Increment K because we missed one loop increment
                          c  2  # and divide it by 2 to get the days

```

# Answer
> 1 votes
# Mathematica, 92 bytes

```
(y=1;x=#+#2[[1]];While[!StringMatchQ[ToString@x,{"0","1"}..],x+=#2[[y++~Mod~10+1]]];N@y/2)&

```

Yep. Input is the odometer and a list of times. Output is the day count.

# Answer
> 1 votes
# PHP, ~~102~~ 98

```
function f($i,$s){while(1)foreach($s as$v){$d+=.5;$i+=$v;if(preg_match('/^[01]+$/',$i))return$d;}}

```

Ungolfed Version

```
function f($i,$s) {
    $d = 0;
    while(true) {
        foreach($s as $v) {
            $d += 0.5;
            $i+=$v;
            if(preg_match('/^[0|1]+$/', $i)) {
                return $d;
            }
        }
    }
}

```

PHP Notices can be removed of extra cost of 4 characters `$d = 0;` in golfed version.

Example

```
$i = 101101;
$s = [27, 27, 27, 27, 27, 27, 27, 27, 27, 27];
f($i,$s);

```

# Answer
> 0 votes
# C Sharp, 180.

Dear lord C# is long.

```
using System.Text.RegularExpressions;class a{double c(int a,int[]b){var d=0.5;a+=b[0];var i=1;while(!Regex.IsMatch(a.ToString(),"^[01]+$")){a+=b[i];i+=1;i=i%10;d+=0.5;}return d;}}

```

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


title: Draw a timeline

text:
# Question
Title: Draw a timeline
Given an input of a list of integers representing dates, output an ASCII art timeline like the following:

```
<----------------------------->
  A     B  C           D    E

```

The above timeline is the output for input `[1990, 1996, 1999, 2011, 2016]`. Note several things about the timeline:

* The first line of output is a less than sign (`<`), a number of dashes equal to `dateOfLastEvent - dateOfFirstEvent + 3` (because one must be added to include the last date, and then two more for padding), and then a greater than sign (`>`).
* In the second line of output, each event is placed at position `dateOfEvent -
dateOfFirstEvent + 2` (assuming zero-indexing). Hence, the first event is placed at position `2`, two characters to the right of the `<`, and the last event is similarly two characters to the left of the `>`.
* Each event is represented by a letter. Event 1 is `A`, event 2 is `B`, etc. There will never be more than 26 events. You may use lowercase letters if you would like.
* There is no trailing whitespace. The only extra whitespace allowed is a trailing newline at the end of the program.

Furthermore,

* The events are not necessarily given in order. Dates are still labelled according to their position in the array, though. For example, an input of `[2, 3, 1, 5, 4]` must output

```
<------->
  CABED

```
* You may be given one or more events as input. For example, an input of `[12345]` must output

```
<--->
  A

```
* You may assume that the input will never contain duplicate dates.

Input may be given as either an array/list of integers/strings or a single string separated by any non-numerical character. The allowable range of dates that will be provided as input is `1 ≤ x ≤ 32767`.

Since this is , the shortest code in bytes will win.

Test cases:

```
32767 32715 32716 32750 32730 32729 32722 32766 32740 32762
<------------------------------------------------------->
  BC     G      FE         I         D           J   HA
2015 2014
<---->
  BA
1990 1996 1999 2011 2016
<----------------------------->
  A     B  C           D    E
2 3 1 5 4
<------->
  CABED
12345
<--->
  A

```

# Answer
## Pyth, ~~37~~ ~~36~~ ~~35~~ 34 bytes

```
:*dlp++\<*\-+3-eJSQhJ">
"mhh-dhJQG

```

Explanation: (for this the newline will be replaced by `\n` for simplicity)

```
:*dlp++\<*\-+3-eJSQhJ">\n"mhh-dhJQG

                                    - autoassign Q = eval(input())
                                    - G = "abcdefghijklmnopqrstuvwxyz"

    p++\<*\-+3-eJSQhJ">\n"          -    print out the first line

            +3-eJSQhJ               -        Get the number of dashes
                 SQ                 -            sorted(Q)
                J                   -           autoassign J = ^
               e                    -          ^[-1]
              -                     -         ^-V
                   hJ               -          J[0]
            +3                      -        ^+3

         *\-                        -       ^*"-"
      +\<                           -      "<"+^
     +               ">\n"          -     ^+"-->\n"
    p                               -    print(^)

 *dl                                -  work out the number of spaces to print
   l                                -   len(^)
 *d                                 -  ^*" "
:                                 G - For i in V: ^[i] = G[i]
                          mhh-dhJQ  -  Work out the positions of the characters
                          m      Q  -  [V for d in Q]
                               hJ   -     J[0]
                             -d     -    d-^
                           hh       -   ^+2

```

Try it here!
> 5 votes

# Answer
## PowerShell, ~~120~~ 108 bytes

```
param($a)$n,$m=($a|sort)[0,-1];"<$('-'*($b=$m-$n+3))>";$o=,' '*$b;$i=97;$a|%{$o[$_-$n+2]=[char]$i++};-join$o

```

Takes input `$a` then sets `$n` and `$m` to the minimal and maximal values, respectively. We output the timeline with the next section, by executing a code block `$(...)` inside the string to generate the appropriate number of `-` characters. We then generate an array of the same length containing only spaces, and set our output character to `$i`.

Then, we loop through the input `$a` with `|%{...}`. Each loop we set the appropriate `$o` value. Finally, we `-join` `$o` together to form a string. Since that is left on the pipeline, output is implicit.

Edited to remove the `.TrimEnd()` command, as the last character of `$o` is always guaranteed to be a letter.

### Example

```
PS C:\Tools\Scripts\golfing> .\draw-a-timeline.ps1 2015,2014,2000
<------------------>
  c             ba

```
> 5 votes

# Answer
# C - 294 287 220 191 184 178 174 bytes

After staring out with a somewhat insane code I at least have gotten it down a bit ...

***Note:*** *First loop has the requirement that the execution of the binary gives 0 as result from `atoi()` on `argv[0]`. If not, this would result in the binary (name) being included as an event. Examples that invalidates:*

```
$ 42/program 1 2 3
# 42/program gives 42 from argv[0], fail.

$ 1program 3 2 9
# 1program gives 1 from argv[0], fail.

$ 842 3 2 9
# 842 gives 842 from argv[0], fail.

```

*Not sure if this is a valid requirement.*

```
char y[32769];n,m;main(i,a)char**a;{for(;n=atoi(a[--i]);y[n>m?m=n:n]=64+i);for(;!y[++i];);printf("<");for(n=i;i<=m;i+=printf("-"))!y[i]?y[i]=' ':0;printf("-->\n  %s\n",y+n);}

```

Run:

```
./cabed 32767 32715 32716 32750 32730 32729 32722 32766 32740 32762
<------------------------------------------------------->
  BC     G      FE         I         D           J   HA

./cabed 2 1 3 5 4
<------->
  BACED

./cabed 2016
<--->
  A

./cabed 130 155 133 142 139 149 148 121 124 127 136
<------------------------------------->
  H  I  J  A  C  K  E  D     GF     B

```

Ungolfed:

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

char y[32769]; /* Zero filled as it is in global scope. */
int n, m;

int main(i, a)
    char**a;
{
    /* Loop argv and set y[argv[i] as int] = Letter, (Event name).
     * Set m = Max value and thus last data element in y. */
    for ( ; n = atoi(a[--i]); y[n > m ? m = n : n] = 64 + i)
        ;

    /* i = 0. Find first element in y that has a value. (Min value.) */
    for (; !y[++i]; )
        ;

    printf("<");

    /* Save min value / y-index where data starts to n.
     * Print dashes until y-index = max
     * Build rest of event string by filling in spaces where no letters.*/
    for (n = i; i <= m; i += printf("-"))
        !y[i] ? y[i] = ' ' : 0;

    printf("-->\n  %s\n", y + n);

    return 0;
}

```
> 4 votes

# Answer
# MATL, 40 ~~41~~ bytes

```
0lY2in:)GtX<-I+(t~32w(ctn45lbX"60hP62hcw

```

**Try it online!**

```
0          % array initiallized to 0
lY2        % string 'ABC...Z'
in:)       % input array. Take as many letters as its length
GtX<-I+    % push input again. Duplicate, subtract minimum and add 3
(          % assign selected letter to those positions. Rest entries are 0
t~32w(     % replace 0 by 32 (space)
c          % convert to char
tn45lbX"   % duplicate, get length. Generate array of 45 ('-') repeated that many times
60hP62h    % prepend 60 ('<'), postpend 62 ('>')
c          % convert to char
w          % swap. Implicit display

```
> 3 votes

# Answer
# Ruby, 83 characters

```
->a{n,m=a.minmax
s=' '*(d=m-n+3)
l=?@
a.map{|i|s[i-n+2]=l.next!}
puts ?<+?-*d+?>,s}

```

Sample run:

```
irb(main):001:0> ->a{n,m=a.minmax;s=' '*(d=m-n+3);l=?@;a.map{|i|s[i-n+2]=l.next!};puts ?<+?-*d+?>,s}[[32767,32715,32716,32750,32730,32729,32722,32766,32740,32762]]
<------------------------------------------------------->
  BC     G      FE         I         D           J   HA

```
> 2 votes

# Answer
# JavaScript (ES6), 124

```
l=>(l.map(v=>r[v-Math.min(...l)]=(++i).toString(36),r=[],i=9),`<-${'-'.repeat(r.length)}->
  `+[...r].map(x=>x||' ').join``)

```

**TEST**

```
F=
l=>(l.map(v=>r[v-Math.min(...l)]=(++i).toString(36),r=[],i=9),`<-${'-'.repeat(r.length)}->
  `+[...r].map(x=>x||' ').join``)

console.log=x=>O.textContent+=x+'\n'

test= [[32767,32715,32716,32750,32730,32729,32722,32766,32740,32762],
[2015,2014],[1990,1996,1999,2011,2016],[2,3,1,5,4],[12345]]

test.forEach(x=>console.log(x+'\n'+F(x)+'\n'))
```

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

# Answer
# PHP, ~~129~~ ~~126~~ ~~125~~ ~~121~~ ~~117~~ 115 bytes

Uses ISO 8859-1 encoding.

```
$l=min([$h=max($z=$argv)]+$z)-3;echo~str_pad(Ã,$h-$l,Ò).~ÒÁõ;for(;$l<$h;)echo chr((array_search(++$l,$z)-1^32)+65);

```

Run like this (`-d` added for aesthetics only):

```
php -r '$l=min([$h=max($z=$argv)]+$z)-3;echo~str_pad(Ã,$h-$l,Ò).~ÒÁõ;for(;$l<$h;)echo chr((array_search(++$l,$z)-1^32)+65);' 1990 1996 1999 2016 2011 2>/dev/null;echo

```

Ungolfed version:

```
// Get the highest input value.
$h = max($z = $argv);

// Get the lowest value, setting the first argument (script name) to the highest
// so it is ignored.
$l = min([$h] + $z);

// Output the first line.
echo "<".str_repeat("-",$h - $l + 3).">\n  ";

// Iterate from $l to $h.
for(;$l <= $h;)
    // Find the index of the current iteration. If found, convert the numeric
    // index to a char. If not found, print a space.
    echo ($s = array_search($l++, $z)) ? chr($s+64) : " ";

```
* Saved 3 bytes by printing leading spaces from the loop and changing `<=` to `<`.
* Saved a byte by using `str_pad` instead of `str_repeat`.
* Saved 4 bytes by using bitwise logic to convert 0 (`false`) to 32, and everything above 0 to 97 onwards. Then convert that number to char.
* Saved 4 bytes by using negated extended ASCII to yield `<`, `-`, `>` and newline
* Saved 2 bytes by negating string after padding instead of before
> 2 votes

# Answer
# Perl, 109 bytes

*includes +1 for `-p`*

```
$l=A;s/\d+/$h{$&}=$l++/ge;($a,$z)=(sort keys%h)[0,-1];$o.=$h{$_}//$"for$a..$z;$_='<'.'-'x($z-$a+3).">$/  $o"

```

Expects input on stdin: space separated numbers. Example:

```
$ echo 2016 2012 2013 | perl -p file.pl
<------->
  BC  A

```

Somewhat readable:

```
$l=A;                                   # Intialize $l with the letter A
s/\d+/$h{$&}=$l++/ge;                   # construct %h hash with number->letter
($a,$z) = (sort keys %h)[0,-1];         # grab min/max numbers
$o .= $h{$_} // $" for $a..$z;          # construct 2nd line: letter or space
$_= '<' . '-' x ($z-$a+3) . ">$/  $o"   # construct 1st line, merge both lines to $_ output

```
> 1 votes

# Answer
## Python 2, ~~173~~ ~~172~~ 182 bytes

since Python is missing yet, here is my first post:

```
import sys
d=dict([(int(v),chr(65+i))for(i,v)in enumerate(sys.argv[1:])])
k=sorted(d.keys())
f=k[0]
s=k[-1]-f+3
o=list(" "*s)
for i in k:o[i-f+2]=d[i]
print "<"+"-"*s+">\n"+"".join(o)

```

the original looks following:

```
import sys

dates = dict([(int(v), chr(65+i)) for (i,v) in enumerate(sys.argv[1:])])
keys = sorted(dates.keys())
first = keys[0]
out_size = keys[-1] - first + 3
out = list(" " * out_size)
for date in keys: out[date - first + 2] = dates[date]
print "<" + "-" * out_size + ">\n" + "".join(out)

```
> 1 votes

# Answer
# Groovy, ~~106~~ 99 characters

```
{n=it.min()
o=[l="A"]
it.each{o[it-n]=l++}
"<${"-"*(it.max()-n+3)}>\n  "+o.collect{it?:" "}.join()}

```

Sample run:

```
groovy:000> print(({n=it.min();o=[l="A"];it.each{o[it-n]=l++};"<${"-"*(it.max()-n+3)}>\n  "+o.collect{it?:" "}.join()})([32767,32715,32716,32750,32730,32729,32722,32766,32740,32762]))
<------------------------------------------------------->
  BC     G      FE         I         D           J   HA

```
> 0 votes

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


title: Frame this nice ASCII-Art

text:
# Question
Title: Frame this nice ASCII-Art
# Introduction

I think everyone agrees that nice pictures have to have a nice frame. But most challenges on this site about ASCII-Art just want the raw picture and don't care about it's preservation.
Wouldn't it be nice if we had a program that takes some ASCII-Art and surrounds it with a nice frame?

# The Challenge

Write a program that takes some ASCII-Art as input and outputs it surrounded by a nice frame.

**Example:**

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

```

becomes

```
╔═══════╗
║ ***** ║
║  ***  ║
║   *   ║
║  ***  ║
║ ***** ║
╚═══════╝

```
* You have to use the exact same characters for the frame as in the example: `═ ║ ╔ ╗ ╚ ╝`
* The top and the bottom of the frame get inserted before the first and after the last line of the input.
* The left and rights parts of the frame have to have exact one space padding to the widest line of the input.
* There may be no leading or trailing whitespaces in the output. Only a trailing newline is allowed.
* You may assume that the input has no unnecessary leading whitespaces.
* You may assume that the input has no trailing whitespaces on any line.
* You don't have to handle empty input.
* The input will only contain printable ASCII-characters and newlines.

# Rules

**Happy Coding!**

*Using some great ASCII-Art, that was produced in any challenge on this site, as input to your program and showing it with a nice frame is highly encouraged!*

# Answer
> 6 votes
## CJam, 45 chars / 52 bytes

```
qN/_z,)[_)'═*N]2*C,3%'╔f+.\4/@@f{Se]'║S@2$N}*

```

Trying to avoid those expensive 3-byte chars was... interesting.

Try it online

### Explanation

```
qN/                   Split input by newline
_z,                   Zip and get length L, i.e. length of longest line
)                     Increment -> L+1
[_)'═*N]              Make two-element array of "═"*(L+2) and newline
2*                    Double the array, giving ["═"*(L+2) "\n" "═"*(L+2) "\n"]

C,                    range(12), i.e. [0 1 2 ... 11]
3%                    Every third element, i.e. [0 3 6 9]
'╔f+                  Add "╔" to each, giving "╔╗╚╝"
.\                    Vectorised swap with the previous array, giving
                      ["╔" "═"*(L+2) "╗" "\n" "╚" "═"*(L+2) "╝" "\n"]
4/                    Split into chunks of length 4

@@                    Move split input and L+1 to top
f{...}                Map with L+1 as extra parameter...
  Se]                   Pad line to length L+1, with spaces
  '║S                   Put "║" and space before it
  2$N                   Put "║" and newline after it

*                     Join, putting the formatted lines between the top and bottom rows

```

# Answer
> 16 votes
## Haskell, 139 bytes

```
q=length
g x|l<-lines x,m<-maximum$q<$>l,s<-[-1..m]>>"═"='╔':s++"╗\n"++(l>>= \z->"║ "++z++([q z..m]>>" ")++"║\n")++'╚':s++"╝"

```

As an example I'm framing snowman "12333321".

```
*Main> putStrLn $ g " _===_\n (O.O)\n/(] [)\\\n ( : )"
╔═════════╗
║  _===_  ║
║  (O.O)  ║
║ /(] [)\ ║
║  ( : )  ║
╚═════════╝

```

How it works:

```
bind
  l: input split into lines
  m: maximum line length
  s: m+2 times ═

build top line
prepend left frame to each line, pad with spaces, append right frame
build bottom line.

```

# Answer
> 9 votes
## JavaScript (ES6), 138 bytes

This is 138 bytes in the IBM866 encoding, which at time of writing is still supported in Firefox, but 152 in UTF-8.

```
s=>`╔${t='═'.repeat(w=2+Math.max(...(a=s.split`
`).map(s=>s.length)))}╗
${a.map(s=>('║ '+s+' '.repeat(w)).slice(0,w+1)).join`║
`}║
╚${t}╝`

```

# Answer
> 6 votes
# Bash, 173 171 150 148  147 bytes, 157 136 134 133 characters

```
q(){((n=${#2}>n?${#2}:n));};mapfile -tc1 -C q v;for((p=++n+1;p;--p));do z+=═;done;echo ╔$z╗;printf "║ %-${n}s║\n" "${v[@]}";echo ╚$z╝

```

### *Multiline:*

```
q() {
    (( n = ${#2} > n ? ${#2} : n))
}
mapfile -tc1 -C q v

for((p=++n+1;p;--p))
do
    z+=═
done

echo ╔$z╗
printf "║ %-${n}s║\n" "${v[@]}"
echo ╚$z╝

```

### Example execution:

```
bash -c 'q(){((n=${#2}>n?${#2}:n));};mapfile -tc1 -C q v;for((p=++n+1;p;--p));do z+=═;done;echo ╔$z╗;printf "║ %-${n}s║\n" "${v[@]}";echo ╚$z╝'< bear.txt

```

Sample run from script:

```
$ cat bear2.txt
     (()__(()
     /       \
    ( /    \  \
     \ o o    /
     (_()_)__/ \
    / _,==.____ \
   (   |--|      )
   /\_.|__|'-.__/\_
  / (        /     \
  \  \      (      /
   )  '._____)    /
(((____.--(((____/mrf
$ ./frame< bear2.txt
╔═══════════════════════╗
║      (()__(()         ║
║      /       \        ║
║     ( /    \  \       ║
║      \ o o    /       ║
║      (_()_)__/ \      ║
║     / _,==.____ \     ║
║    (   |--|      )    ║
║    /\_.|__|'-.__/\_   ║
║   / (        /     \  ║
║   \  \      (      /  ║
║    )  '._____)    /   ║
║ (((____.--(((____/mrf ║
╚═══════════════════════╝

```

# Answer
> 5 votes
# AWK, ~~159~~ 141 bytes

```
{a[NR,1]=x=length(a[NR]=$0)
m=m<x?x:m}END{for(;i++<m+2;)t=t"═"
for(print"╔"t"╗";j++<NR;)printf"║ %-"m"s ║\n",a[j]
print"╚"t"╝"}

```

Try it online!

Apparently `awk` can print Unicode if you can figure out how to get it in the code. Thanks, @ceilingcat, for pointing out that my code could be rearranged to save 18 bytes.

# Answer
> 5 votes
# Perl, 111 characters

(score includes +5 for the interpreter flags)

```
#!/usr/bin/perl -n0 -aF\n
$n=(sort{$b<=>$a}map length,@F)[0];$l="═"x$n;
print"╔═$l═╗\n",(map{sprintf"║ %-${n}s ║\n",$_}@F),"╚═$l═╝";

```

First, we find the longest line length `$n`, by numerically sorting the lengths of all lines.

We set `$l` to be the header/footer bar to be `$n` repetitions of the horizontal frame character.

Then we print each line formatted to left-align in a field of width `$n`, sandwiched in between the frame characters.

### Result:

```
╔═══════════╗
║   |\_/|   ║
║  / @ @ \  ║
║ ( > * < ) ║
║  `>>x<<'  ║
║  /  O  \  ║
╚═══════════╝

```

# Answer
> 4 votes
## Pyth, 44 chars (58 bytes)

```
++\╔K*JhheSlR.z\═\╗jbm+\║+.[+;d;J\║.z++\╚K\╝

```

Explanation

```
++\╔K*JhheSlR.z\═\╗                          - print out the first line
           lR.z                              -        map(len, all_input())
          S                                  -       sorted(^)
         e                                   -      ^[-1]
       hh                                    -     ^+2
      J                                      -    autoassign J = ^
     *         \═                            -   ^*"═"
    K                                        -  autoassign K = ^
++\╔             \╗                          - imp_print("╔"+^+"╗")

                   jbm+\║+.[+;d;J\║.z        - print out the middle
                   jb                        - "\n".join(V)
                     m             .z        -  [V for d in all_input()]
                      +\║+       \║          -   "║"+V+"║"
                          .[   ;J            -    pad(V, " ", J)
                            +;d              -     " "+d

                                     ++\╚K\╝ - print out the end
                                     ++\╚K\╝ - imp_print("╚"+K+"╝")

```

Try it here.

# Answer
> 4 votes
# PHP 5.3, 209 bytes

This only works using the encoding OEM 860. It is an Extended ASCII superset, used in Portuguese DOS versions. Since I'm Portuguese (and I used to love doing these "frames" in Pascal) and this is a standard encoding, I went ahead with this:

```
<?foreach($W=explode('
',$argv[1])as$v)$M=max($M,strlen($v)+2);printf("É%'Í{$M}s»
º%1\${$M}sº
%2\$s
º%1\${$M}sº
È%1\$'Í{$M}s¼",'',join('
',array_map(function($v)use($M){return str_pad(" $v ",$M);},$W)));

```

Here's the base64:

```
PD9mb3JlYWNoKCRXPWV4cGxvZGUoJwonLCRhcmd2WzFdKWFzJHYpJE09bWF4KCRNLHN0cmxlbigkdikrMik7cHJpbnRmKCLilZQlJ+KVkHskTX1z4pWXCuKVkSUxXCR7JE19c+KVkQolMlwkcwrilZElMVwkeyRNfXPilZEK4pWaJTFcJCfilZB7JE19c+KVnSIsJycsam9pbignCicsYXJyYXlfbWFwKGZ1bmN0aW9uKCR2KXVzZSgkTSl7cmV0dXJuIHN0cl9wYWQoIiAkdiAiLCRNKTt9LCRXKSkpOw==

```

This answer was based on my answer on: https://codegolf.stackexchange.com/a/57883/14732 (the heavy lifting was all made there, just had to twitch a bit).

# Answer
> 2 votes
# Python 3, 119 Bytes

```
def f(x):
 n='\n';s="║ ";e=" ║";h=(x.find(n)+2)*"═";return"╔"+h+"╗"+n+s+x.replace(n,e+n+s)+e+n+"╚"+h+"╝"

```

~~126 bytes~~

~~```
import sys
o=["║ %s ║\n"%j[:-1] for j in sys.stdin]
h="═"*(len(o[0])-3)
print("╔"+h+"╗\n"+"".join(o)+"╚"+h+"╝")

```~~

Input:

```
hello
there
  !

```

Output:

```
╔═══════╗
║ hello ║
║ there ║
║   !   ║
╚═══════╝

```

# Answer
> 2 votes
# Python 2, 115 Bytes

```
def f(i):w='═'*(i.find('\n')+2);return'╔%s╗\n║ %s ║\n╚%s╝'%(w,' ║\n║ '.join(i.split('\n')),w)

```

Looks shorter than 115 here, but working file includes 3-byte UTF-8 BOM mark signature, bumping it up to 115 bytes. If you were to run it in Python 3 you wouldn't need the BOM and it'd get down to 112 bytes.

# Answer
> 1 votes
# C, 290 bytes

Golfed function `B`, with dependencies; takes input as null-terminated char\*

```
#define l(s) strlen(s)
p(char*s,int n){while(n--)printf(s);}
B(char*s){char*t=strtok(s,"\n");int x=l(t),z=1;while(t=strtok(0,"\n"))z++,x=l(t)>x?l(t):x;p("╔",1);p("=",x+2);p("╗\n",1);while(z--)printf("║ %s", s),p(" ",x-l(s)),p(" ║\n",1),s+=l(s)+1;p("╚",1);p("=",x+2);p("╝\n",1);}

```

Somewhat-ungolfed function in full program

```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 1024

// GOLF-BEGIN =>
#define l(s) strlen(s)
// since multibyte chars don't fit in char: use char* instead
void p (char*s,int n){ while(n--)printf(s); }
void B (char *s){
    char *t = strtok(s,"\n");
    int x=l(t), z=1;
    while(t=strtok(0,"\n"))z++,x=l(t)>x?l(t):x;
    // x is l(longest line), z is #lines
    p("╔",1);p("=",x+2);p("╗\n",1);
    while(z--)printf("║ %s", s),p(" ",x-l(s)),p(" ║\n",1),s+=l(s)+1;
    p("╚",1);p("=",x+2);p("╝\n",1);
}
// <= GOLF-END

int main(int argc, char **argv) {
    char buffer[MAX];
    memset(buffer, 0, MAX);
    FILE *f = fopen(argv[1], "rb");
    fread(buffer, 1, MAX, f);
    B(buffer);
    return 0;
}

```

input

```
     _.,----,._
   .:'        `:.
 .'              `.
.'                `.
:                  :
`    .'`':'`'`/    '
 `.   \  |   /   ,'
   \   \ |  /   /
    `\_..,,.._/'
     {`'-,_`'-}
     {`'-,_`'-}
     {`'-,_`'-}
      `YXXXXY'
        ~^^~

```

output

```
╔======================╗
║      _.,----,._      ║
║    .:'        `:.    ║
║  .'              `.  ║
║ .'                `. ║
║ :                  : ║
║ `    .'`':'`'`/    ' ║
║  `.   \  |   /   ,'  ║
║    \   \ |  /   /    ║
║     `\_..,,.._/'     ║
║      {`'-,_`'-}      ║
║      {`'-,_`'-}      ║
║      {`'-,_`'-}      ║
║       `YXXXXY'       ║
║         ~^^~         ║
╚======================╝

```

C golfing tips appreciated!

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


title: Output the current time in ascii art

text:
# Question
Title: Output the current time in ascii art
# Challenge

Your task is to output the time (in 12 hour time) in ascii art.

All characters that will be used are as follows:

```
  ___    __   ___    ____    _  _     _____     __    ______
 / _ \  /_ | |__ \  |___ \  | || |   | ____|   / /   |____  |
| | | |  | |    ) |   __) | | || |_  | |__    / /_       / /
| | | |  | |   / /   |__ <  |__   _| |___ \  | '_ \     / /
| |_| |  | |  / /_   ___) |    | |    ___) | | (_) |   / /
 \___/   |_| |____| |____/     |_|   |____/   \___/   /_/

   ___     ___
  / _ \   / _ \                                _
 | (_) | | (_) |   __ _ _ __    _ __ _ __     (_)
  > _ <   \__, |  / _` | '  \  | '_ \ '  \     _
 | (_) |    / /   \__,_|_|_|_| | .__/_|_|_|   (_)
  \___/    /_/                 |_|

```

(For each number/symbol individually, consult this gist).

You will receive input in an array of the form:

* `[hours, minutes, 'am/pm']`. For example, `[4, 57, 'am']`, with single quotes only used for am/pm
* or `"hours-minutes-am/pm"`. For example, `"4-56-am"`
* or `[hours, 'minutes', 'am/pm']` for languages that cannot handle leading zeroes on numbers. For example, `[4, '07', 'am']`

You may use either input method.

Output will be in the form `1 2 : 5 9 am`, where there is one initial space, two spaces between each number (in the gist, each number already has one space on each side), one space between : (colon) and the neighbouring numbers, and one space between the last number and `am/pm`, with an optional leading and/or trailing newline. All spaces are between the right-most point of the symbol on the left and the left-most point of the symbol on the right.

Implicit output is allowed.

Lowest byte size wins.

The `am/pm` are to be aligned such that the bottom of the `p` in `pm` is aligned with the bottom of the rest of the output, that is, the undercore denoting the top of `am/pm` starts on the third line down (not counting a leading newline).

The colon is to be aligned such that it's first character (an underscore) starts on the second line down (not counting a leading newline).

For `minutes < 10`, output the minutes with a leading `0` (you should receive this in the input). For example, `[8, 04, 'pm']` -\> `8 : 0 4 pm`.

You must not fetch the data for the numbers from a library or external resource. All data must be contained within the program.

For example, for the input `[12, 47, 'am']`, the output would be as follows:

```
  __    ___          _  _      ______
 /_ |  |__ \    _   | || |    |____  |
  | |     ) |  (_)  | || |_       / /   __ _ _ __
  | |    / /    _   |__   _|     / /   / _` | '  \
  | |   / /_   (_)     | |      / /    \__,_|_|_|_|
  |_|  |____|          |_|     /_/

```

(If you see any edge cases that you can't decide what to do with, please post in comments and I will add them to examples).

---

# Answer
# Perl, ~~592~~ ~~579~~ ~~540~~ ~~522~~ 510 bytes

Under a sector!

```
($L,$C,$b)=unpack"W/aW/aB*",q!12346677889999 _|/\)(
'<,>.` PP¨
¨@T @ôäð˜SÀ§€fÌU`à¨Àäð'€GÖf`3 X½`fÍ5 s Î|½`gËÖ— $¡))õ™˜À8Sô BÁªx~O àÔýåËþÏÃÆ~O‡ŸY¬Àf s
½`À*õŸ/X8|½`p>^€<¯åkgúºÖ·ÓÊ¸°ªÀj® kª¸•p¸å\×   ô!;@c=map{$i<<=$_-$P if$_>$P;$P=$_;sprintf"%${l}b",$i++}$L=~/./g;while($b){$b=~s/^$c[$_]// and$g.=($C=~/./sg)[$_]for 0..$#c}$_=pop;s/-/:/;y/apm-/;</d;for$a(0..5){map{$o.=substr((split$/,$g)[$a],($x=-48+ord)*12,('6356766766099'=~/./g)[$x]+3)}/./g;$o.=$/}print$o

```

This program expects the time in the 2nd format (*"12-34-am"*) as a commandline argument.

Commented:

```
($L,$C,$b) = unpack "W/aW/aB*",             # extract code lengths, chars, and bitstream
    q!12346677889999 _|/\)(
'<,>.` PP¨
¨@T @ôäð˜SÀ§€fÌU`à¨Àäð'€GÖf`3 X½`fÍ5 s Î|½`gËÖ— $¡))õ™˜À8Sô BÁªx~O àÔýåËþÏÃÆ~O‡ŸY¬Àf s
½`À*õŸ/X8|½`p>^€<¯åkgúºÖ·ÓÊ¸°ªÀj® kª¸•p¸å\×   ô!;
@c = map {                                  # reconstruct huffman prefix codes
    $i <<= $_-$P if $_ > $P;                # increase code size
    $P = $_;                                # keep track of previous code
    sprintf "%${l}b", $i++                  # append code as bitstring
}
$L=~/./g;                                   # canonical huffman prefix lengths
while ( $b ) {                              # decompress font
        $b =~ s/^$c[$_]//                   # match and strip prefix code
        and $g .= ($C=~/./sg)[$_]           # append char for prefix code
    for 0..$#c                              # iterate prefix codes in order
}                                           # luckily we can omit checking trailing bytes

$_ = pop;                                   # get cmdline arg "12-34-am"
s/-/:/;                                     # ord(':')-ord('0')=10
y/apm-/;</d;                                # 'a'-> chr(11), 'p' -> chr(12), strip -,m
for $a (0..5) {                             # iterate 6 output lines
    map {                                   # iterate each char in input
        $o .= substr(
            ( split $/, $g )[$a],           # grab line $a
            ( $x=-48+ord ) * 12,            # $x=glyph index, 12=glyph width
            ('6356766766099'=~/./g)[$x]+3   # glyph display width
        )
    } /./g;
    $o .= $/                                # append newline
}
print $o                                    # output

```

Note that due to character encoding issues, when you paste the above code in a file, the output may be somewhat malformed. So here's the golfed version, base-64 encoded. Copy it, and paste it into `base64 -d > 510.pl`:

```
KCRMLCRDLCRiKT11bnBhY2siVy9hVy9hQioiLHEhDjEyMzQ2Njc3ODg5OTk5DiBffC9cKSgKJzws
Pi5gFQBQAVACqAIgCqgBQBVUAqAFQAH05PAOmANTwBqngGbMBlVgHOAaqMDk8AcngEfWZmAzAA9Y
Ar1gZs0DNQBzoAHOBny9YGfL1g+XoAUkoSkp9ZmYDMAHOANT9A1Cwap4Bn5PABzgH9T9AeV/GBAB
y/7Pw8Z+Tx+Hn1mswGYAc6AKvWAMwCr1gZ8vWAc4Bny9YA5wPl6APK/lrWtn+rrWt9PKuAawBqrA
aq4AawGquAeVcA64AeVcAdcAAAABrfQhO0BjPW1hcHskaTw8PSRfLSRQIGlmJF8+JFA7JFA9JF87
c3ByaW50ZiIlJHtsfWIiLCRpKyt9JEw9fi8uL2c7d2hpbGUoJGIpeyRiPX5zL14kY1skX10vLyBh
bmQkZy49KCRDPX4vLi9zZylbJF9dZm9yIDAuLiQjY30kXz1wb3A7cy8tLzovO3kvYXBtLS87PC9k
O2ZvciRhKDAuLjUpe21hcHskby49c3Vic3RyKChzcGxpdCQvLCRnKVskYV0sKCR4PS00OCtvcmQp
KjEyLCgnNjM1Njc2Njc2NjA5OSc9fi8uL2cpWyR4XSszKX0vLi9nOyRvLj0kL31wcmludCRv

```

Here's the font I'm using. I've spaced the glyphs 12 characters apart (the size of the am/pm) for easy indexing.

```
   ___        __          ___         ____        _  _        _____         __        ______       ___         ___
  / _ \      /_ |        |__ \       |___ \      | || |      | ____|       / /       |____  |     / _ \       / _ \      _
 | | | |      | |           ) |        __) |     | || |_     | |__        / /_           / /     | (_) |     | (_) |    (_)          __ _ _ __   _ __ _ __
 | | | |      | |          / /        |__ <      |__   _|    |___ \      | '_ \         / /       > _ <       \__, |     _          / _` | '  \ | '_ \ '  \
 | |_| |      | |         / /_        ___) |        | |       ___) |     | (_) |       / /       | (_) |        / /     (_)         \__,_|_|_|_|| .__/_|_|_|
  \___/       |_|        |____|      |____/         |_|      |____/       \___/       /_/         \___/        /_/                              |_|

```

This font is 592 bytes.
The previous approach used a few variations on RLE compression to reduce this to 353 bytes, at the cost of 78 bytes decompression code.
The Huffman coding compresses the font to 221 bytes at the cost of 154 bytes for the decompression algorithm.
> 5 votes

# Answer
# Haskell, ~~932~~ 699 bytes

Yay, under 700 bytes!!

```
t=transpose
i=intercalate
l=lines
u=unlines
s=show
c(h,m,a)=u$t$l(i(r"!!\n!!\n")(map d(s h++':':(if m<10 then '0':s m else s m)))++r"!!"++(d$a!!0))
e s z n=i s$splitOn z n
r=e"   ""!"
d 'a'=b 10
d 'p'=b 11
d ':'=b 12
d n=b$read[n]
b n=splitOn(r"!!")(u$t$l$r$e" |""@"$e"___""$"$e"_|""~"$e"!!""*"$e"_ ""#""  $! __!$! $_! # _!  $__!  __! $$! $!  $*****  \n / #\\  /_@@_#\\ @$ \\ @@|@!| $~!/ /!|$#@  / #\\!/ #\\****!  #\n|@@@ @@! )@!__)@@@|@#@@__! / /_* / / @ (_)@@ (_)@  _###__! #_##__!(_)\n|@@@ @@!/ /!|_#< @__!~@$ \\ @ '#\\!  / /! > #<!\\__,@ / _`@ '  \\ @ '#\\ '  \\!#\n|@~@ @@  / /_!$)@!@@! $)@@ (_)@!/ /!@ (_)@! / /  \\__,~~~~@ .__/~~~ (_)\n \\$/!|~@$~@$_/! @~!|$_/!\\$/!/_/*\\$/! /_/**!@~** ")!!n

```

Somewhat ungolfed

```
module Clock where
import Data.Lists

main :: IO ()
main = putStr $ clock (5,05,"am")

clock :: (Int, Int, String) -> String
clock (h,m,a) | m <- if m < 10 then '0':show m else show m
              , hm <- intercalate "      \n      \n" (map digit (show h ++ ':' :m))
              =  unlines $ transpose $ lines (hm ++ "      "++(digit$a!!0))

digit :: Char -> String
digit 'a' = numbers 10
digit 'p' = numbers 11
digit ':' = numbers 12
digit n = numbers (read [n])

numbers :: Int -> String
numbers n = splitOn "      " (unlines $ transpose $ lines "  ___    __   ___    ____    _  _     _____     __    ______    ___     ___                                \n / _ \\  /_ | |__ \\  |___ \\  | || |   | ____|   / /   |____  |  / _ \\   / _ \\                             _ \n| | | |  | |    ) |   __) | | || |_  | |__    / /_       / /  | (_) | | (_) |  __ _ _ __    _ __ _ __   (_)\n| | | |  | |   / /   |__ <  |__   _| |___ \\  | '_ \\     / /    > _ <   \\__, | / _` | '  \\  | '_ \\ '  \\   _ \n| |_| |  | |  / /_   ___) |    | |    ___) | | (_) |   / /    | (_) |    / /  \\__,_|_|_|_| | .__/_|_|_| (_)\n \\___/   |_| |____| |____/     |_|   |____/   \\___/   /_/      \\___/    /_/                |_|             ") !! n

```

## How it works

(This is mostly how the ungolfed program works)

```
clock :: (Int, Int, String) -> String
clock (h,m,a) | m <- if m < 10 then '0':show m else show m
              , hm <- intercalate "      \n      \n" (map digit (show h ++ ':' :m))
              =  unlines $ transpose $ lines (hm ++ "      "++(digit$a!!0))

```

`clock` takes a tuple of the time and returns a string. `m` is the current minute with the leading `0` added if it is `<10`. `hm` is the hours and minutes joined with a `:`. The last thing it does is transpose the output.

```
digit :: Char -> String
digit 'a' = numbers 10
digit 'p' = numbers 11
digit ':' = numbers 12
digit n = numbers (read [n])

```

Fairly simple here. `digit` is a function that maps the chars to locations in the stored string.

```
numbers :: Int -> String
numbers n = splitOn "      " (unlines $ transpose $ lines  replace" |""@"$replace"___""$"$replace"_|""~"$replace"!!""*"$replace"_ ""#""  $! __!$! $_! # _!  $__!  __! $$! $!  $*****  \n / #\\  /_@@_#\\ @$ \\ @@|@!| $~!/ /!|$#@  / #\\!/ #\\****!  #\n|@@@ @@! )@!__)@@@|@#@@__! / /_* / / @ (_)@@ (_)@  _###__! #_##__!(_)\n|@@@ @@!/ /!|_#< @__!~@$ \\ @ '#\\!  / /! > #<!\\__,@ / _`@ '  \\ @ '#\\ '  \\!#\n|@~@ @@  / /_!$)@!@@! $)@@ (_)@!/ /!@ (_)@! / /  \\__,~~~~@ .__/~~~ (_)\n \\$/!|~@$~@$_/! @~!|$_/!\\$/!/_/*\\$/! /_/**!@~** ")!!n

```

This is the magic stored string.

The only real change between the golfed and ungolfed programs is that the golfed program adds some string compression by replacing some common char patterns with `!@$`. The original data string was `667` bytes, after the replace compression it is down to `390` bytes
> 3 votes

# Answer
# C++, 938 Bytes

Revised version with some basic compression of input data: Test here

```
#include <stdio.h>
#include <time.h>
int main(){char e[]="!1`2!3`1!2`1!4`2!4`!1`!4`4!4`1!3`5!4`2!4`2!35^!`!]!1^`!}!}`1!]!1}`2!]!1}!}1!}!2}!`3}!2^!^!2}`3!1}!2^!`!]!2^!`!]!31`!}!}!}!}!1}!}!3*!}!2`1*!}!}!}1!}`!1}!}`1!3^!^`!6^!^!2}!)`*!}!}!)`*!}!2`1!`!`!`1!3`!`1!`!`1!4)`*}!}!}!}!1}!}!2^!^!2}`1!=!1}`1!2`}!}`2!]!1}!(`!]!4^!^!4?!`!=!2]`1-!}!1^!`a!}!(!1]!1}!(`!]!(!1]!4`!}!}`}!}!1}!}!1^!^`!2`2*!}!3}!}!3`2*!}!}!)`*!}!2^!^!4}!)`*!}!3^!^!2]`1-`}`}`}`}!}!/`1^`}`}`}!2)`*!]`2^!2}`}!}`3}!}`3^!4}`}!2}`3^!2]`2^!2^`^!6]`2^!3^`^!16}`}!14",l[]="8578988998>?3",f[666],*q=f,*p=e,c,r;time_t z;time(&z);tm*u=localtime(&z);while(*p){if(*p>47&&*p<58){r=*p++-48;if(*p>47&&*p<58)r=r*10+*p++-48;while(r--)*q++=c;}else{*q++=c=*p++==94?48:p[-1];}}c=u->tm_hour;sprintf(e,"%02d<%02d%c",c%12,u->tm_min,':'+c/12);for(int s,n,o,r=0;r<6;r++){for(q=e;*q;q++){o=r*111;for(n=0; n<*q-48;n++)o+=l[n]-48;s=l[n]-48;for(n=o;n<o+s;n++)putchar(f[n]-1);}putchar('\n');}return 0;}

```
> 2 votes

# Answer
# Bash + GNU utilities + figlet, 134

Not sure if figlet is allowed or not, but it does seem to provide the right fonts - `big` for the digits and `small` for the `:` and `{a,p}m`:

```
f=figlet\ -f
b()(date +%$1|sed 's/./& /g'|$f big)
b -I|paste - <(echo "    ";$f small ": ") <(b M) <(echo;date +%P|$f small)|tr \\t \

```

The rest is just getting the right info from `date` and shuffling the formating around so it looks right:

```
  ___          _____    ___
 / _ \    _   | ____|  / _ \
| (_) |  (_)  | |__   | | | |   __ _ _ __
 > _ <    _   |___ \  | | | |  / _` | '  \
| (_) |  (_)   ___) | | |_| |  \__,_|_|_|_|
 \___/        |____/   \___/

```

Figlet may be installed on Ubuntu with `sudo apt-get install figlet`.
> 2 votes

# Answer
# JavaScript (ES6), ~~994~~ 985 bytes

Terrible attempt with raw data not compressed at all, and a very tacky method for outputting.

But hey... it's only my second codegolf answer!

```
d="   ___   !  / _ \\  ! | | | | ! | | | | ! | |_| | !  \\___/  0  __  ! /_ | !  | | !  | | !  | | !  |_| 0  ___   ! |__ \\  !    ) | !   / /  !  / /_  ! |____| 0  ____   ! |___ \\  !   __) | !  |__ <  !  ___) | ! |____/  0  _  _    ! | || |   ! | || |_  ! |__   _| !    | |   !    |_|   0  _____  ! | ____| ! | |__   ! |___ \\  !  ___) | ! |____/  0    __   !   / /   !  / /_   ! |  _ \\  ! | (_) | !  \\___/  0  ______  ! |____  | !     / /  !    / /   !   / /    !  /_/     0   ___   !  / _ \\  ! | (_) | !  > _ <  ! | (_) | !  \\___/  0   ___   !  / _ \\  ! | (_) | !  \\__, | !    / /  !   /_/   0   ! _ !(_)! _ !(_)!   0!! __ _ _ __ !/ _` | '  \\!\\__,_|_|_|_|!0!! _ __ _ __ !| '_ \\ '  \\!| .__/_|_|_|!|_|".split(0);
f=a=>{t="toString",s="split",h=a[0][t]()[s](""),m=a[1][s](""),p=a[2]=='am'?11:12,g=h.length>1?1:0,r="";for(i=0;i<6;i++){r+=d[h[0]][s]('!')[i];r+=(g&&1)?d[h[1]][s]('!')[i]:"";r+=d[10][s]('!')[i]+d[m[0]][s]('!')[i]+d[m[1]][s]('!')[i]+d[p][s]('!')[i]+"\n"}return r}

```

**Old submission (994 bytes)**:

```
d=["   ___   !  / _ \\  ! | | | | ! | | | | ! | |_| | !  \\___/  ","  __  ! /_ | !  | | !  | | !  | | !  |_| ","  ___   ! |__ \\  !    ) | !   / /  !  / /_  ! |____| ","  ____   ! |___ \\  !   __) | !  |__ <  !  ___) | ! |____/  ","  _  _    ! | || |   ! | || |_  ! |__   _| !    | |   !    |_|   ","  _____  ! | ____| ! | |__   ! |___ \\  !  ___) | ! |____/  ","    __   !   / /   !  / /_   ! |  _ \\  ! | (_) | !  \\___/  ","  ______  ! |____  | !     / /  !    / /   !   / /    !  /_/     ","   ___   !  / _ \\  ! | (_) | !  > _ <  ! | (_) | !  \\___/  ","   ___   !  / _ \\  ! | (_) | !  \\__, | !    / /  !   /_/   ","   ! _ !(_)! _ !(_)!   ","!! __ _ _ __ !/ _` | '  \\!\\__,_|_|_|_|!","!! _ __ _ __ !| '_ \\ '  \\!| .__/_|_|_|!|_|"];
f=a=>{
    t="toString",s="split",h=a[0][t]()[s](""),m=a[1][s],p=(a[2]=='am')?11:12,g=(h.length>1)?1:0,r="";
    for(i=0;i<6;i++){
        r+=d[h[0]].s('!')[i];
        r+=g&&1?d[h[1]].s('!')[i]:"";
        r+=d[10].s('!')[i]+d[m[0]].s('!')[i]+d[m[1]].s('!')[i]+d[p].s('!')[i]+"\n"
    }
return r
}

```

Split into lines to make it easier to read.

Basically:

```
var f = function (a) {
  hours = a[0].toString().split(""), // convert hours to a string then array to
                                    // handle single and and double numbers
  minutes = a[1].split(""), // ditto with minutes
  period = a[2] == "am" ? 11 : 12, // if it is am, get data[11], if pm, get data[12]
  g = hours.length > 1 ? 1 : 0, // if hours > 9, then g is true
  r = ""; // the string that will be returned
for (i = 0; i < 6; i++) {
    r += data[hours[0]].split("!")[i]; // add the first digit of hours to r
    r += g && 1 ? data[hours[1]].split("!")[i] : ""; // if g is true, add the second
                                                    //digit of hours to r
    r += data[10].split("!")[i] + // colon
    data[minutes[0]].split("!")[i] + // first digit of minutes
    data[minutes[1]].split("!")[i] + // second digit of minutes
    data[period].split("!")[i] + // am/pm
    "\n"; // and finally linebreak.
  } // entire loop repeated six times, each iteration adds one line to the string
return r; // return the string
};

```
> 1 votes

# Answer
## Python 3, ~~1085~~ 1072 bytes

### Golfed

```
def f(h,c="",n=["   ___   @  / _ \  @ | | | | @ | | | | @ | |_| | @  \___/  ","  __  @ /_ | @  | | @  | | @  | | @  |_| ","  ___   @ |__ \  @    ) | @   / /  @  / /_  @ |____| ","  ____   @ |___ \  @   __) | @  |__ <  @  ___) | @ |____/  ","  _  _    @ | || |   @ | || |_  @ |__   _| @    | |   @    |_|   ","  _____  @ | ____| @ | |__   @ |___ \  @  ___) | @ |____/  ","    __   @   / /   @  / /_   @ |  _ \  @ | (_) | @  \___/  ","  ______  @ |____  | @     / /  @    / /   @   / /    @  /_/     ","   ___   @  / _ \  @ | (_) | @  > _ <  @ | (_) | @  \___/  ","   ___   @  / _ \  @ | (_) | @  \__, | @    / /  @   /_/   ","   @ _ @(_)@ _ @(_)@   ","            @            @ __ _ _ __ @/ _` | '  \@\__,_|_|_|_|@            ","            @            @ _ __ _ __ @| '_ \ '  \@| .__/_|_|_|@|_|"]):
 for i in range(6):
  for j in range(3):
   if j<2:
    x=int(h[j]);d=x//10;u=x%10
    if d>0 or j>0:c+=n[d].split("@")[i]
    c+=n[u].split("@")[i]
    if j==0:c+=" "+n[10].split("@")[i]+" "
   else:y=11 if h[j]=="am" else 12;c+=" "+n[y].split("@")[i]
  c+="\n"
 return c

```

### Ungolfed

```
import os
from time import ctime

def asciiClock(hour):
    num = ["   ___   @  / _ \  @ | | | | @ | | | | @ | |_| | @  \___/  @","  __  @ /_ | @  | | @  | | @  | | @  |_| @",
   "  ___   @ |__ \  @    ) | @   / /  @  / /_  @ |____| @","  ____   @ |___ \  @   __) | @  |__ <  @  ___) | @ |____/  @",
   "  _  _    @ | || |   @ | || |_  @ |__   _| @    | |   @    |_|   @","  _____  @ | ____| @ | |__   @ |___ \  @  ___) | @ |____/  @",
   "    __   @   / /   @  / /_   @ |  _ \  @ | (_) | @  \___/  @","  ______  @ |____  | @     / /  @    / /   @   / /    @  /_/     @",
   "   ___   @  / _ \  @ | (_) | @  > _ <  @ | (_) | @  \___/  @","   ___   @  / _ \  @ | (_) | @  \__, | @    / /  @   /_/   @",
   "   @ _ @(_)@ _ @(_)@   @","            @            @ __ _ _ __ @/ _` | '  \@\__,_|_|_|_|@            @",
   "            @            @ _ __ _ __ @| '_ \ '  \@| .__/_|_|_|@|_|@"]
    clock = ""
    for i in range(6):
        for j in range(3):
            if j < 2:
                x = int(hour[j])
                d = x // 10
                u = x % 10
                if d > 0 or j > 0:
                    clock += num[d].split("@")[i]
                clock += num[u].split("@")[i]
                if j == 0:
                    clock += " " + num[10].split("@")[i] + " "
            else:
                y = 11 if hour[j] == "am" else 12
                clock += " " + num[y].split("@")[i]
        clock += "\n"
    return clock

previousMinute = -1
while True:
    hour = ctime().split()[3].split(":")
    h = int(hour[0])
    m = hour[1]
    x = "am" if h < 12 else "pm"
    if h > 12:
        h -= 12
    if  previousMinute != m:
        os.system("clear") # if using Windows change to "cls"
        print(asciiClock([h, m, x]))
    previousMinute = m

```
> 0 votes

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