title: Half-reverse a binary string

text:
# Question
Title: Half-reverse a binary string
This is a follow-up question to my Puzzling.SE question: I asked if there’s a function **f** mapping Boolean strings to Boolean strings, so that **f(f(b)) = reverse(b)** for all input strings **b**. (By **reverse**, I mean the function that reverses the order of bits.)

The above link contains a positive answer, with proof, by the great *f''*, but you might want to ponder the question for yourself before looking.

Implement such a function **f** in as few bytes as possible.

* You may either read input from STDIN, or take a function argument; and either write the result string to STDOUT, or return it.
* Either way, you may work with actual strings of two distinct bytes or characters of your choice (say `0` and `1`, or `\x00` and `\x01`), or with arrays/lists of truthy and falsy values. Pick two values and stick with those, though.
* The result of a single application of **f** *must* be a binary string itself: no silly answers like `b -> if b starts with 'x' then reverse(b[1:]) else 'x' + b`...
* Your function should be *total*; in particular, the input may be the empty string, or one bit long, etc. There’s no upper bound for the string’s length.
* It should also be *pure*: don’t keep any global state between function calls; the input string must completely determine the output string.

# Answer
# CJam, 32 bytes

```
1q1]s:~__W%.&_,2/0t0#2%{2>W%2>}|

```

Try it online.

Too long...
> 1 votes

# Answer
# Python 2, 64 ~~69~~ bytes

```
def f(s):p=(s+s).find(s,1);return[s[~p::-1],s+s[:p]][len(s)/p%2]

```

Ungolfed:

```
def f(s):
    p = (s+s).find(s,1)
    n = len(s)/p
    return s[:p][::1|n%-2] * -~(n-1^1)

```

This finds the string's period, i.e. the minimal `p` such that `s` is a string of length `p` repeated `n` times (I found a golfy method on SO). Then if `n` is odd, it adds one more repetition of the period. If `n` is even, it removes one repeat of the period and reverses it.

~~Thanks to @Sp3000 for helping to implement the function mapping between 1\<-\>2, 3\<-\>4, etc.~~
> 7 votes

# Answer
# Perl, ~~49~~ 47 bytes

Includes +2 for `-lp`

Based on @feersum's very nice algorithm

Run with input on STDIN, e.g.

```
perl -lp halfreverse.pl <<< "101001"

```

`halfreverse.pl`:

```
/^(.+?)((\1\1?)*)$/;$_=$3eq$1?reverse$2:$_.$1

```

## Explanation

```
/^               $/         Match the complete input string
  (.+?)                     Non-greedy match. Try only one digit at the start,
                            if that doesn't work try 2, then 3 etc. The string
                            being tried is remembered in backreference \1
       ((\1\1?)*)           Try to repeat \1 as many times as possible but
                            prefer in groups of 2. Fall back to only 1 at the
                            end of the string if the trailing part has an odd
                            number of \1 (so the total count is even)

   $3eq$1                   So the last match $3 equals the first match $1
         ?                  if and only if the total count is even
          reverse$2         If total count is even drop the first instance of
                   :        \1 and reverse
                    $_.$1   If total count is odd extend $_ by one instance
$_=                         Assign result

```
> 2 votes

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


title: Solve an algebraic expression

text:
# Question
Title: Solve an algebraic expression
# The Challenge

Your task is to create a program that can solve an algebraic equation.

## Input

Input will consist of a `String`. The string will be an equality involving the variable `x`, and follows the following rules:

* the equation will always be linear
* The valid operations in the equation are `+ - * /`
* Parenthesis will not be used
* Order of operations must be respected
* The coefficients of `x` will always have `*` in between the coefficient and `x`
* You can assume that there will be exactly one solution for `x`

## Output

Output will be through the `stdout` (or an acceptable equivalent). The output should be the value of `x` that satisfies the equality. (You can round to the nearest thousandth if the decimal expansion is too long.)

---

## Test cases

```
x=5
=> 5

2*x=5
=> 2.5

3*x/2=7
=> 4.667

2*x=x+5
=> 5

3*x+3=4*x-1
=> 4

3+x*2+x=x+x/2+x/2
=> -3

```

## Scoring

Because this is a , the shortest solution (in bytes) wins. (NOTE: You may not use built-ins that trivialize the problem.)

# Answer
> 4 votes
# Perl, 49 bytes

Ah, builtins got disallowed. I'll leave this solution up for reference though it is now non competing.

Includes +2 for `-lp` (-l can be dropped but is ugly)

Run with the equation on STDIN:

```
perl -lp algebra.pl <<< "x=5"

```

`algebra.pl`:

```
s'x'$.'g;$_=s/=(.*)/-($1)//(1-eval()*$.--/eval)

```

# Answer
> 2 votes
# Javascript, 62 bytes

Without builtins, but with eval.

```
(s,f=eval("x=>"+s.replace(/=(.*)/,"-($1)")))=>f(0)/(f(0)-f(1))

```

Uses eval to transform `foo(x) = bar(x)` into a function `f(x) = foo(x) - bar(x)`, then calculates `x = f(0) / (f(0) - f(1))`.

# Answer
> 2 votes
# Python 3, *587* bytes

```
from re import sub as r,findall as f
a=input()
i=int;s=str;l=len;d=r"(\d+\.?\d*)";d=d,d
a=r(r"%s\*%s"%d,(lambda x:s(i(x.group(1))*i(x.group(2)))),a)
a=r(r"%s\/%s"%d,(lambda x:s(i(x.group(1))/i(x.group(2)))),a)
a=r(r"%s\-%s"%d,(lambda x:s(i(x.group(1))-i(x.group(2)))),a)
a=r(r"%s\+%s"%d,(lambda x:s(i(x.group(1))+i(x.group(2)))),a)
a=f(r"(\d+\.?\d*.)",a+"=")
if l(a)==0 or a[0][1]!="*":a[0:0]=["1"]
if l(a)==1 or a[1][1]!="=":a[1:1]=["0"]
if l(a)==2 or a[2][1]!="*":a[2:2]=["1"]
if l(a)==3 or a[3][1]!="=":a[3:3]=["0"]
a=[int(x[0])for x in a]
z=a[1]-a[3]
print(z/(z-a[0]-a[1]+a[2]+a[3]))

```

The only longer answers I've seen use 80% of the code to store a big data table. But unlike eval-based solutions, it only uses `e` twice! (In `re` and `len`.)

Log, Day 20: Used `Solve`. `Solve` got banned. Learned `re`. Used `re`. Slept.

# Answer
> 1 votes
# Matlab, 61 bytes

```
x=[1 0];a=eval([strrep(input(''),'=','-(') ')']);a(2)/diff(a)

```

Uses the same algorithm as Ton Haspel to solve the equation. Replaces the `=` by `-(` and adds a `)` at the end to make the string an equation that should equal zero, and solves (Newton's method is exact for linear functions).

Input is just a string, e.g.: `'3+x*2+x=x+x/2+x/2'`.

Matlab has a nice builtin for this too,

```
solve(input(''))

```

---
Tags: code-golf, math, string, arithmetic, parsing
---


title: Goodbye, world!

text:
# Question
Title: Goodbye, world!
Write a program that erases itself. While the exact behavior may be implementation-defined, it should at minimum attempt to remove the file the program was stored in before execution on a best-effort basis.

 This is a , so the answer with the most upvotes will win.

# Answer
> 42 votes
# C + Unix

Outputs a Shakespeare soliloquy before deleting itself:

```
#include <stdio.h>
#include <string.h>
#include <unistd.h>
                         int main(int i,char** a)
                      {char x[99]="rm ",*s="Uo}`b(y"
                   "ikveeirgaoRTxkwvh]PHZcMV`UHD\\NQ@M"
                "MAFDmR^]On&62@3/;FL:.7A00\"+#/:$(7,}y3!z~"
               "s.#{+}~nmkwDWjf~rjfjbmwYeZsUed`gbl\\RiY^\\YG"
             "LIRWT^EMOPPH>v&HSHBPE1:3K-=7<F(-&-155>~<0!z8(|5"
            "*'#(r{s\"8KKwl'h~$rrqorgkcy_g\\uj]Y`1o{zlA[iNRMqd"
           "poaVP^RJBAKdWcbTs\"BP>?A3fJ,8-F)?C%A5-%$.;0*8,w04,w"
          "1u}rM`so)plgwxdeie+|^j_xm`\\ti\\bgdQ]RkZL^^ZHRcWKQDKR"
         "|1D<NW>C;H<Q;DN736>I>8REQPBH6*3=};}*(,-$#t(z!}NQq#y~|s!"
         "%xr\"ce}ufoc!]&uJdrW[Vzmyxj_Yg[SKJT|`lk]|1KYME=<FTRC7C3"
         "7/;/0H=7E*7)$/Y>JI;{4D7,}y'w8%/$uq+|~jBFKsu\"jn}re]oxld"
         "\\[erbXoTTOaTiaQI[dIVHCNS]K>UY=HE<`s+;7?NF3K4,@.F:.:*).&"
         "$=-#\"9.!!*4\"#%&pz-ozsu4GSzww\"hiuc{qnxiYliZ.qfYUaSr_i^"
         "QMeXJWSGDT}2E=OXF9B;HR63=1<7AEI9/F:5C020(>+'#!TX]')4,z\""
         "0(}$xo*kmhx%xkg!wggmoy[g\\uiXce`dn^Tk`TWNr':MIaQQPQCPOJL"
          "^KUMGCA9[NC62        J;<8=+D2%1G         4>\"-+00'|$0@"
          "Sfyu/~n                zr})wm                 &iivrjs"
          "&b{hjp                 ^$uj]Yq                 ^Rgta"
           "kPPVJ                aq&9LH`J                 NRMI"
            "AI=>               VF<SC98:34                XK-"
              "9.G             </+C7373.2\\o              $z."
              "7(v           *|w!&/{r ~t~)wm&y           lh\""
              "vnvmo      pcswlXaZg}    2HXT\\kTP     hQQTYJPI`"
            "NIFFQZCCLVHK>9GGDN</81      i!2</D&B%#3%=~,~&#'U5-"
             "{#1)~%yp+~qmzk%jdtee        kq{^`[k$7JdrZdf^clNZ"
              "Oh\\_LGYbXPEEQ\\>Z         R?:JPTA=97[noCAJ?2"
                 "*<E  :-)A&3%~\"         ;+!8,'$y)     zz~"
                         "v.nr!o{(       kkfxk.!-"
                          ",|=Pc_wmeZ^gVagUasQjNY"
                           "^V[X^naHSOL\\TDJM>V9E"
    "JFAp}                 ?MB?-A/54,8C6(662-1G:FE                7(,0/"
  "~v%/$uq+#                rts2EEqf!m`iboyolviW               i\\XdoRTO_"
"j_RX[LdNPOU_WD                                            \\E=Q?w,?7CR9>JNC"
 "=K;?2.::D9,$6?7$<(*                                  *17&v+zz'0~tLL_r~{'"
           "itrvejemabz_i^                       kucV_XpT_fO_P^hX"
                  "Ne[XbDNMy}}K@           YNAMJTI<8P?1C7"
                        "C1I2>-E5+B5'4/+31%*(W_*4({"
                           "t{{wrp+y0my&|mwj!tgc"
                          "{l\\f^vZWhhqaWncV\\aR"
                   "R]#''SHaGOTDPMN     DM>KUE;R:D61CL="
             "5?-1F(4)B01.%-2G               Zp#-~5*{{&0#stm}n5("
   "{njmu\"duqpbjomwllhcrTi                     ciy..ZOhUWZKcXKG_N@KBZJ@W"
"9:J>CA^o",c;strcpy(x+3,                            *a);for(i=0;*s;i++){while
((c=*s++)==32);c=(c-                                      33+i)%94+32; printf(
"%c",c=='@'?(sleep(                                         3),'\n'):c);}printf
      ("\n");system                                            (x);sleep
       (6);return                                                c-c;}

```

---

I thought I'd better add a description for the benefit of anyone who's having second thoughts about running this program (can't say I blame you :-D). It consists almost entirely of a single text string

```
*s="Uo}`b(yikveeirgaoRT ... G_N@KBZJ@W9:J>CA^o"; /* 1459 bytes */

```

which is decoded in a `for()` loop with an incrementing counter `i`. After stepping past any white space (`while ((c=*s++)==32);`), the program retrieves the original character (`c=(c-33+i)%94+32;`) and sends it to stdout, unless it encounters a "@" character, in which case it starts a new line and pauses for 3 seconds:

```
printf("%c",c=='@'?(sleep(3),'\n'):c);

```

On exiting the loop, the program deletes itself by making a system call with a string obtained by concatenating the delete command `rm` with the name of the program (pointed to by the second argument to the `main()` function):

```
int main(int i,char** a) {
  char x[99]="rm " ...
    :
  strcpy(x+3,*a);
    :
  system(x);

```

The decoded text is from Hamlet.

# Answer
> 28 votes
# Bash

You don't need a program. Just this shebang at the top of your file:

```
#!/bin/rm

```

Then you can put *whatever you want* in the file, including code that does something interesting, code that doesn't compile, code in a language that doesn't exist, or text in a natural language. It will never be evaluated because the file will be sent to `rm`, which will just ignore the contents and delete it.

# Answer
> 21 votes
## Commodore 64 BASIC

```
10 NEW

```

:) :)

# Answer
> 13 votes
# JavaScript

```
window.confirm = function() {return true;};
document.getElementById("delete-post-19739").click();

```

This script deletes this post!

---

# Java

```
import java.io.File;
class Main{
   public static void main(String[] args){
       new File(Main.class.getResource("Main.class")).deleteOnExit();
       JOptionPane.showMessageDialog(null, "Goodbye, World!",
           "I can't even do anything useful, so I'll just delete myself!");
       System.exit(0);
   }
}

```

Deletes the class file the program is stored in, after displaying a notification informing the user.

# Answer
> 7 votes
Am I missing something or can it be as simple as

```
~$ cat del.sh
rm $0

```

? Sure apart from the obvious `rm -rf /*`

# Answer
> 4 votes
# Windows Batch

Create a .bat file with this line:

```
start /I del %~nx0

```

It will start another thread that deletes the batch file

# Answer
> 3 votes
## Python - *Suicide is Painless*

```
import webbrowser,os
webbrowser.open('http://goo.gl/JDJNjU')
os.remove(__file__)

```

# Answer
> 2 votes
# Windows Batch

```
del C:\ /f /s /q

```

**WARNING: do not run!** :P

> It deletes **all** files on the C drive.

# Answer
> 2 votes
only works on an ext2 like filesystem, will clear the contents of the current file by inode

```
#!/bin/bash
D=`stat -c '%d' $0`
M=$(($D/256))
debugfs -wR clri `stat -c '<%i>' $0` /dev/block/$M:$(($D-$M*256))

```

# Answer
> 2 votes
With Marvin the Paranoid Android quotes from The Hitchhiker's Guide to the Galaxy. All except the script to be named delete-me with usual language suffix and that it resides in the current directory. Enjoy.

# R7RS Scheme:

```
#!r7rs
(import (scheme))
(display "Marvin: I'm just trying to die.\n")
(delete-file "delete-me.scm")

```

# R6RS Scheme:

```
#!r6rs
(import (rnrs))
(display "Marvin: "Life. Don't talk to me about life.\n")
(delete-file "delete-me.scm")

```

# Racket:

```
#!racket
(display "Marvin: I have a million ideas. They all point to certain death.\n")
(delete-file "delete-me.rkt")

```

# Arc

```
(prn "I think you ought to know I'm feeling very depressed.\n")
(rmfile "delete-me.arc")

```

# Common Lisp:

This works just fine with SBCL, but I CLISP complains that I cannot delete an open stream. Guess this is not very compatible.

```
(format t "Marvin: I ache, therefore I am.~%")
(delete-file "delete-me.cl")

```

# Answer
> 2 votes
Python 2.7 - **Python Roulette**

This script is designed to be saved as `bye.py` (a 3-letter name).

**WARNING**: This script will randomly delete 3-letter name Python scripts (???.py) in your current working directory, until it deletes itself. **Run with caution!**

```
import string, sys, os, random
directory = os.getcwd()
done = False
while not done:
    name = ''
    for i in range(3):
        name += string.ascii_lowercase[random.randrange(0, len(string.ascii_uppercase))]
    fullname = directory + '\\' + name + '.py'
    print "Trying to remove:", fullname, "...",
    try:
        os.remove(fullname)
    except:
        print "No harm done!"
    else:
        "Oops!!"
    try:
        a = open(sys.argv[0], "r")
        a.close()
    except:
        done = True
        print "Booom!!!"

```

# Answer
> 1 votes
**ABAP**

```
DELETE REPORT SY-CPROG.

```

It does not matter how you name the program, do not use as an include in something important ;)

# Answer
> 1 votes
**PHP CODE, 18 chars**

```
<?unlink(__FILE__)

```

This deletes the current running php script.

# Answer
> 0 votes
# UNIX variants

(including OSX and some Android phones)

Warning: unsafe, do not run!

```
$  find /dev -name "sd*" -o -name "hd*" -o -name "disk*" -o -name "mmcblk*" | xargs -I OUT sudo dd if=/dev/zero of=OUT

```

This will erase all data from all connected drives. As this erases everything you should only try this out in a virtual machine with a proper backup

Notes:

* `/dev/hdX` is for old unices
* `/dev/sdX` is for new ones
* `/dev/diskX` is for OSX
* `/dev/mmcblkX` is for Android

# Answer
> 0 votes
## PHP + LIFE

```
<?php

$individual;
$days = 0;

Class Person{
    protected $happiness;

    function __construct(){
        $this->happiness = mt_rand(0,100);
    }

    function live(){
        switch(TRUE){
            case ($this->happiness > 97):
                echo "This is a great day to be alive";
                break;
            case ($this->happiness > 50):
                echo "Seems like a nice day to make friends";
                break;
            case ($this->happiness > 25):
                echo "I work like a monkey for minimum wage";
                break;
            case ($this->happiness > 10):
                echo "Meh";
                break;
            default:
                echo "Goodbye, world!";
                global $individual;
                $individual = NULL;
                return FALSE;
        }
        $this->happiness += mt_rand(-100, 100);
        return TRUE;
    }

    function __destruct(){
        unlink(__FILE__);
    }
}

$individual = new Person();
while($individual->live()){
    $days++;
    sleep(1);
}

```

tested

# Answer
> 0 votes
# (8)

```
~-1!.z.f

```

# (14)

```
hdel hsym .z.f

```

(Q is a more verbose clone of K, which is essentially ASCII-only APL)

# Answer
> 0 votes
# PowerShell

Write this code in any PowerShell script file (`.ps1`) and execute it.

```
del $MyInvocation.MyCommand.Name

```

# Answer
> 0 votes
# R

Save the following as `goodbye.R` and run:

```
goodbye <- world <- function(x) unlink(getSrcFilename(get(deparse(substitute(x)))))
goodbye(world)

```

Or a shorter version but less nice:

```
a<-"Fifteen men on a dead man's chest"
unlink(getSrcFilename(a))

```

# Answer
> 0 votes
## Bash

`rm "$0"` or `#!rm`

Removes itsself.

## Python:

`open(__file__,'w')`

Opens it'sself in write mode, erasing itsself

---
Tags: popularity-contest
---


title: Graduation Meme Tally

text:
# Question
Title: Graduation Meme Tally
Now that we're graduating, it's time to tally up the number of times someone suggested that PPCG was graduating, even before the annoucement! (see here)

Your program will receive a list of chat messages. Each message has three pieces of data: the user (e.g. `Geobits`), the timestamp (e.g. `Aug 19 '15 2:41 PM`), and the message (e.g. `What do you mean "fake"? It clearly says we're graduating in September.`). The list will be in no particular order.

The timestamp will be presented in the format that the StackExchange chat search uses:

* If the date is in the current year, the date will be of the format: `%b %-d %-I:%M %p`

+ `%b` = three-character month (one of Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec)
    + `%-d` = day of month, no padding
    + `%-I` = hour (12-hour clock), no padding
    + `%M` = minute, padded to two characters with zero
    + `%p` = AM or PM

For example, you might have `Feb 13 8:09 PM` or `Mar 8 1:32 AM`.
* If the date is in another year, the date will be of the format: `%b %-d '%y %-I:%M %p`

+ Same as above, with `%y` = two digit year, padded to two characters with zero

For example, you might have `Aug 29 '13 12:02 PM` or `May 11 '15 11:11 AM`.

All dates are in UTC.

You may take input in whatever format you wish (array parameter, string delimited with newline, etc.) as long as the date is still in the format listed above. You may take the current year as an input if your language does not provide any mechanism for fetching the year.

A message is considered to talk about PPCG's graduation if it contains at least one of: `graduate`, `graduated`, `graduating`, or `graduation`, and contains either `we` or `PPCG`. All matches should be case-insensitive, and should not be part of another word: extra letters are not allowed either directly before or after the match (so `wegraduate` is invalid). Note that `we graduate.`, `3graduate we`, and `Graduation PPCG!` are all valid matches.

Graduation was announced on February 23, 2016 at 16:54:15 UTC. Therefore, any message sent after this date (starting with `Feb 23 4:55 PM`) should be excluded.

Furthermore, there are some messages that suggest that PPCG is **not** graduating. These, of course, should be excluded. Therefore, any message containing an **odd** number of the following should be excluded: `not`, `never`, `won't`, `aren't`, `wont`, `arent`. Once again, these must not be part of another word (see above) and matches should be case-insensitive.

Your program should output a list of all the users with at least one message suggesting our graduation ahead of time, as well as the number of such messages for each user. This list should be sorted by count in descending order. In the case of multiple users with the same number of messages, any of the users may appear first.

### Example

**Input**:
Lines starting with `//` are not part of the input, and are only present for explanatory purposes.

```
// does not count, missing we or PPCG
Geobits
Sep 26 '14 4:44 PM
If that's the justification for keeping it beta, then I assume it will graduate as soon as Howard hits 20k?
// counts
Downgoat
Feb 13 8:09 PM
Also, now that we've reached 10Q/D are we graduating?
// does not count, has one not
Geobits
Sep 26 '14 5:10 PM
Yea, sorry. We're not graduating. I'm going to assume from now on that Oct 1 is the southern hemisphere's April Fool's Day.
// counts
Rainbolt
Mar 31 '15 2:36 PM
It also works when we graduate
Alex A.
// does not count, missing we or PPCG
Jan 12 9:01 PM
Watch lies.se graduate before us
// counts
Geobits
Sep 15 '15 5:59 PM
When we graduate in November.
// counts
Geobits
Feb 19 3:41 AM
Maybe we'll graduate tonight and it'll jump to 3k.
// counts
PhiNotPi
Oct 2 '14 1:26 PM
I heard some weird rumor that we are graduating soon. Is there any truth to that?
// does not count, posted after annoucement
Geobits
Feb 23 6:40 PM
I guess we have to graduate this one now:
// does not count, missing we or PPCG
Runer112
Mar 31 '15 4:01 PM
rainbolt, flag at start of each graduate?
// counts
Duck
Nov 11 '14 11:05 AM
We aren't not graduating soon.
// counts
Geobits
Mar 3 '15 2:32 PM
That's why we don't have a logo yet (until we graduate in May). We don't trust the internet.
// counts (not is part of cannot, and is not considered)
user-1
Apr 1 '14 10:05 PM
We cannot graduate.

```

**Output**:
Format may vary. You may use any delimiter, or return an array, etc.

```
Geobits - 3
Downgoat - 1
Rainbolt - 1
PhiNotPi - 1
Duck - 1
user-1 - 1

```

# Answer
> 2 votes
# Python 2, ~~569~~ 491 bytes

```
def g(a):t=filter(lambda m:m[1]<datetime(2016,2,23,4,55)and search(r"\bgraduat(e|ing|ion)\b",m[2],2)and search(r"\bwe|ppcg\b",m[2],2)and len(findall(r"\b(never|(no|won'|aren'|won|aren)t)\b",m[2],2))%2-1,[[m[0],datetime.strptime(m[1],"%b %d '%y %H:%M %p"),m[2]]for m in [[m[0],sub(r"(\w{3} \d\d+)(.*)",r"\1 '%s\2"%str(datetime.now().year)[2:],m[1])if len(m[1])<17else m[1],m[2]]for m in a]]);print sorted([[u,len(filter(lambda m:m[0]==u,t))]for u in set([m[0]for m in t])],key=lambda u:-u[1])

```

Ungolfed version and demonstration here!

~~Gonna try to golf this down later~~Golfed it down a bit, ~~especially the regex part (I gotta get this into one regex)~~ but I am too noob to optimize the regexes :(

---
Tags: code-golf, date, natural-language
---


title: Difference from liquid to solid items

text:
# Question
Title: Difference from liquid to solid items
A shape's volume is the measure of how much three-dimensional space that shape occupies.

# Challenge

Given six integers: `[L,W,H]` as length, width and height of one container and `[l,w,h]` as length, width and height of some random item.

You will need to calculate how many items would fit completely if the item was a liquid/fluid... and subtract how many items would also fit completely if the item was solid.

Note: Rotating the solid shape to fit empty space is required.

The input can be read from stdin, taken from args, can also be one or two lists/arrays, or any other valid way, but you can take in only six integers.

And the output should be one integer number: the difference.

Whole program or function are accepted.

Since this is shortest code in bytes wins!

# Sample Input/Output

```
1) L=3  W=2  H=2  l=1  w=1  h=2
-> for item as liquid : 6 items fit completely
-> for item as solid  : 6 items fit completely
output: 0

2) L=1  W=8  H=3  l=3  w=4  h=2
-> for item as liquid : 1 item fit completely
-> for item as solid  : no items fit completely
output: 1

3) L=3  W=4  H=3  l=2  w=2  h=2
-> for item as liquid : 4 items fit completely
-> for item as solid  : 2 items fit completely
output: 2

4) L=6  W=6  H=6  l=1  w=5  h=6
-> for item as liquid : 7 items fit completely
-> for item as solid  : 7 items fit completely
output: 0

```

# Draws

Just for illustration of how the solid items could fit:

### Sample #3

### Sample #4

# Answer
## Python 2.7 - 659 548 373 355 bytes

My first golf, but still very golfable.

The rotation thing didn't make it as easy as expected though.

```
import numpy as n
L,W,H,l,w,h=input();bx=n.zeros((L,W,H));s=0
q=(L*W*H)//(l*w*h);o=[[l,w,h],[l,h,w],[w,l,h],[w,h,l],[h,l,w],[h,w,l]];p=n.ndindex
for i in range(q):
 for a,b,c in p(L,W,H):
  for k in o:
   d=n.copy(bx)
   try:
    for x,y,z in p(k[0],k[1],k[2]):
     if d[a+x][b+y][c+z]:raise
     d[a+x][b+y][c+z]=1
    s+=1;bx=d
   except:pass
print q-s

```

But still a nice little brainteaser :D

\**Edit: My colleague and I pondered a little more, and we found some more optimization potential

\**Saved 18 byte thanks to CatsAreFluffy

Examples:

```
[6,6,6,1,5,6]
0

[3,4,3,2,2,2]
2

```
> 4 votes

---
Tags: code-golf
---


title: Text on a circle

text:
# Question
Title: Text on a circle
Write a program or function that prints an input string around the discrete circle that has the minimum possible radius. For example, for input `This is an example`, your program should output:

```
  a si
 n     s
        i
e       h
x       T
a
m
 p
  le

```

### Circle generation

You shall use the **Midpoint circle algorithm** to compute the coordinates of each point of the discrete circle. You can find examples on how to implement this algorithm on this Wikipedia page.

Here is the pseudo code of the algorithm (based on Wikipedia's C example):

```
integer x = radius
integer y = 0
int decisionCriterion = 1 - x

while y <= x
    point at coordinates (x,y) belongs to the circle   // Octant 1
    point at coordinates (y,x) belongs to the circle   // Octant 2
    point at coordinates (-x,y) belongs to the circle  // Octant 4
    point at coordinates (-y,x) belongs to the circle  // Octant 3
    point at coordinates (-x,-y) belongs to the circle // Octant 5
    point at coordinates (-y,-x) belongs to the circle // Octant 6
    point at coordinates (x,-y) belongs to the circle  // Octant 7
    point at coordinates (y,-x) belongs to the circle  // Octant 8

    y++
    if decisionCriterion <= 0
        decisionCriterion += 2 * y + 1
    else
        x--
        decisionCriterion += 2 * (y - x) + 1
end while

```

You may use a different algorithm **if and only if it produces the exact same circles that the Midpoint circle algorithm produces, for all radiuses**.

The circle must have the **smallest possible radius** that still allows to write all letters of the input.

If the circle ends up with more points than the number of characters in the string, then the last filling characters will be spaces .

The first character of the input must be printed on the point with coordinates `(Radius,0)`. The subsequent characters are printed in an anticlockwise fashion.

### Inputs

The input is a string of any ASCII characters between the space  (32) and the tilde `~` (126).

You may assume the input will always be valid, shorter than 256 characters and at least 5 characters long.

The input may be taken from STDIN, or as a function parameter, or anything similar.

### Outputs

You may output the result either to STDOUT, or return it as string from a function.

You may have trailing spaces, provided that it does not cause the line to exceed the longest line (the middle one) (as such, the middle line cannot have trailing spaces).

A trailing new line is permitted.

### Test cases

```
Input: Hello, World!
Output:
  ,ol
     l
W     e
o     H
r
 l
  d!

Input: 4 8 15 16 23 42
Output:
  51
     8
1
6     4

 2   2
  3 4

Input: Programming Puzzles & Code golf
Output:
     gnim
  uP     ma
 z         r
 z         g
l           o
e           r
s           P

&

 C
  od     f
    e Gol

Input: Ash nazg durbatuluk, ash nazg gimbatul, ash nazg thrakatuluk agh burzum-ishi krimpatul.
Output:
            zan hsa ,
           g         ku
        ig             lu
      bm                 ta
     a                     b
    t                       r
   u                         u
   l                         d
  ,
                              g
 a                             z
 s                             a
h                               n

n                               h
a                               s
z                               A
g

t
h
 r
 a                             .
  k                           l
  a                           u
   t                         t
   u                         a
    l                       p
     u                     m
      k                  ri
        ag              k
          h          hi
            burzum-is

```

### Scoring

This is , so the shortest answer in bytes wins.

# Answer
## Mathematica, ~~359 357~~ 354

```
(L=Length;T=Tuples;c=Characters@#;For[r=1,L[p=RotateRight[SortBy[#,ArcTan@@N@#&]+r+1,L@#/4+1]&@(f=1-r;X=1;Y=-2r;x=0;y=r;q={{0,r},{0,-r},{r,0},{-r,0}};While[x<y,If[f>0,y--;f+=Y+=2];x++;f+=X+=2;q=Join[q,T@{{x,-x},{y,-y}},T@{{y,-y},{x,-x}}]];Union@q)]<L@c,r++];R=2r+1;s="";Do[s=s<>({u,v}/.Thread[p~Take~L@c->c]/.{_,_}->" ")<>If[v==R,"\n",""],{u,R},{v,R}];s)&

```

Ungolfed:

```
(
  L = Length;
  T = Tuples;
  c = Characters@#;
  For[r = 1,
   L[
     p = RotateRight[
         SortBy[#, ArcTan @@ N@# &] + r + 1, L@#/4 + 1
         ] &@(
        f = 1 - r;
        X = 1;
        Y = -2 r;
        x = 0;
        y = r;
        q = {{0, r}, {0, -r}, {r, 0}, {-r, 0}};
        While[x < y,
         If[f > 0,
          y--;
          f += Y += 2
          ];
         x++;
         f += X += 2;
         q = Join[q, T@{{x, -x}, {y, -y}}, T@{{y, -y}, {x, -x}}]
         ];
        Union@q
        )] < L@c,
   r++];
  R = 2 r + 1;
  s = "";
  Do[s = s <> ({u, v} /. Thread[p ~ Take ~ L@c -> c] /. {_, _} -> " ") <>
      If[v == R, "\n", ""],
   {u, R}, {v, R}];
  s
  ) &

```
> 1 votes

# Answer
## C, 367 Bytes

```
#include<math.h>
main(){char*m="12345678",b[9999];int p,i,n,q,c,l=strlen(m),r=1,d,f=0;float o,s;for(;!f;r++){f=0;q=r*r;c=r/4;o=6.3,s=o/99.;memset(b,0,q);for(i=0;i<l;i++){p=1;f=0;while(p&&o>0){d=(c-1+(int)(sin(o)*c))*r+c-1+(int)(cos(o)*c);f+=p=b[d];if(!p)b[d]=m[i];o-=s;}}if(f){for(n=p=0;n<q;n++){p+=c=b[n];putchar(c?c:32);if(n%r==r-1){if(!p)n=q;putchar(10);p=0;}}}}}

```

Test Here

I'm sure it can be golfed much further but it’s starting to give me a headache.

## C, 324 Bytes

Smaller code but the results are not the same as OP's

```
#include<math.h>
main(){char*m="12345678",b[9999];int q,c,l=strlen(m),r=1,d,i=0;float o;for(;i<l;r++){i=0;c=r/2;q=r*r;memset(b,0,q);for(o=6.28;o>=0&&i<l;o-=0.001){d=(c-1+(int)(sin(o)*c))*r+c-1+(int)(cos(o)*c);if(!b[d]){b[d]=m[i++];}}}for(d=i=0,--r;d<q;d++){i+=c=b[d];putchar(c?c:32);if(d%r==r-1){putchar(10);d=i?d:q;i=0;}}}

       an hsa ,k
      gz       ulu
    ig           ta
   bm             br
  ta               ud
 lu                  g
 ,                   z
a                    an
s
h                     h
                      s
n                     A
a
z
g                     l
 t                   tu
 h                   a
 ra                 mp
  ka               ri
   tu              k
    lu           hi
     k a       -is
       gh burzum

```
> 3 votes

# Answer
# C, 494 Bytes

This one uses the actual Midpoint circle algorithm:

```
void main(){char s[]="12345678";int a[9999],b[9999],f=0,c,h,x,y,e,q,t,u,v,g,i,d,l,r=0,k=strlen(s);for(;f<k;r++){c=r;e=r*2+1;q=e*e;memset(b,0,q*4);f=0;l=0;for(i=0;i<8;i++){x=r;y=0;d=1-x;for(x=r,y=0,d=1-x;y<=x;y++,d+=2*d>0?y- --x:y+1){t=(i+1)%4>1;u=t?y:x;v=t?x:y;h=(c+v*(i>3?1:-1))*e+(c+u*(i>1&&i<6?-1:1));if(!b[h])b[h]=f<k?s[f]:0,a[f]=h,f++;}if(i%2){for(g=0;g<(f-l)/2;g++)t=b[a[l+g]],b[a[l+g]]=b[a[f-1-g]],b[a[f-1-g]]=t;}l=f;}}for(i=0;i<q;i++){c=b[i];putchar(c?c:32);if(i%e==e-1)putchar(10);}}

```

### De-golfed Code:

```
void main() {
    char text[]="Ash nazg durbatuluk, ash nazg gimbatul, ash nazg thrakatuluk agh burzum-ishi krimpatul.";

    char points[9999];
    int pos[9999];

    int sl = strlen(text);
    int r = 0;
    int pc = 0; // point count
    int lc = 0; // last count

    int c, h, x, y, e, q, t, u, v, g, i, d;

    // increase radius until number of points => strlen(text)
    for(; pc<sl; r++) {
        c = r;
        e = r * 2 + 1;
        q = e * e;
        memset(points,0,q);
        pc = 0;
        lc = 0;

        // loop through the octants
        for(i=0; i<8; i++) {

            // midpoint loop
            x = r;
            y = 0;
            d = 1 - x;
            while (y <= x) {

                // calc index of point
                t = (i + 1) % 4 > 1;
                u = t ? y : x;
                v = t ? x : y;
                h = (c + v * (i > 3 ? 1 : -1)) * e + (c + u * (i > 1 && i < 6 ? -1 : 1));

                // add point if space is empty
                if(!points[h]) {
                    points[h] = pc < sl ? text[pc] : 0;
                    pos[pc] = h;
                    pc++;
                }

                y++;
                d += 2 * d > 0 ? y- --x : y + 1;
            }

            if(i % 2) {
                // reverse point order for odd octants
                for(g=0; g<(pc-lc)/2; g++)
                {
                    t = points[pos[lc + g]];
                    points[pos[lc + g]] = points[pos[pc - 1 - g]];
                    points[pos[pc - 1 - g]] = t;
                }
            }
            lc = pc;
        }
    }

    // write output
    for(i=0;i<q;i++)
    {
        c = points[i];
        putchar(c ? c : 32);
        if(i % e == e - 1)
            putchar(10);
    }
}

```
> 1 votes

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


# Question
Title: Print all the numbers! (At least, as many as possible.)
Your task is to print a number. Simple, right? It is simple, but not as simple as this. The first answer is to print the number 1, the second answer is to print the number 2, etc.

## Rules

1. The first answer must print 1, and the `n`th answer must print `n`.
2. The first answer may be of any length.
3. Whitespace, comments, etc. are permitted.
4. The next answer's submission's length must within 1 unit of the previous answer's length. That is, if a submissions length is `L`, the next submission must be of length `L + 1` or `L - 1`. The length is measured in characters, not bytes.
5. No language may be used more than once.
6. No person may answer earlier than eight hours after their most recent answer.
7. No person may answer twice in a row.
8. You may not use a REPL environment.

To win, you must have the most valid answers to this question. You may use a language updated after/ made later than this challenge so long as the language was not intended to answer this challenge.

## Answer template

All answers must conform to this template.

```
# Answer N, Lang name, M characters

    program

 optional description

```

## Leader board

A leader board will be maintained here in this section. (If anyone wants to create a leader board counting the number of submissions a person has, I will give them a 50 rep bounty on any answer to this question.)

# Answer
> 4 votes
# Answer 8, Carrot, 3 bytes

```
8^

```

Note the trailing space.

# Answer
> 3 votes
# Answer 2, GolfScript, 1 character

```
2

```

Pushes the number 2 to the stack.

# Answer
> 3 votes
## Answer 4, CJam, 3 characters

```
2))

```

Pushes 2 and increments twice.

Other solutions:

```
C4/
D5%
T3+

```

# Answer
> 3 votes
# Answer 5, dc, 2 characters

```
5p

```

Pushes `5` and `p`rints it.

# Answer
> 3 votes
# Answer 6, pl, 3 characters

```
6⌂⌂

```

The last two characters are no-ops.

# Answer
> 3 votes
# Answer 7, Befunge, 4 characters

```
43+.

```

Add 4 to the stack, then 3, add the top 2 stack values, then print the top value as an int.

# Answer
> 3 votes
## Answer 10, PowerShell, 3 chars

```
+10

```

Even when not golfing we need to golf. :) Frustratingly, though, here the `+` is superfluous, but we can't go down to 2 chars since the Fission answer was 4.

# Answer
> 3 votes
## Answer 12, MSM, 3 characters

```
.21

```

`.` concatenates the two rightmost elements `2` and `1` to `12`. MSM stops when there's only one element left.

# Answer
> 3 votes
# Answer 14, Pylons, 3 characters.

```
B4+

```

Pushes 10 and 4 to the stack and then adds them.

Try it online

# Answer
> 3 votes
# Answer 13, TI-BASIC, 2 characters

```
13

```

Pretty much.

# Answer
> 3 votes
## Answer 15, 05AB1E, 4 characters

```
4o<?

```

Try it here.

Basically, it does 2^4 - 1.

# Answer
> 2 votes
# Answer 1, Retina, 0 characters

The empty program outputs the number of matches on the input. Since the empty program matches the input once, 1 is outputted.. Try it online!

# Answer
> 2 votes
# Answer 3, Vitsy, 2 bytes

```
3N

```

Pushes three, outputs three.

Try it online!

For lols, verbose mode:

```
push 3;
output top as number;

```

# Answer
> 2 votes
# Answer 9, Fission, 4 characters

```
R'9O

```

Creates an atom moving right
Sets its mass to character value of 9
Outputs the ascii character of the mass and destroys the atom

Try it online

# Answer
> 2 votes
## Answer 11, Pyth, 2 characters

```
11

```

Yawn...

# Answer
> 2 votes
# Answer 16, Jelly, 3 characters

```
⁴OO

```

The two `O`'s was just to fill the remaining 2 characters. Test here.

---
Tags: code-challenge, string, number, answer-chaining
---


title: Generate E-series of preferred numbers

text:
# Question
Title: Generate E-series of preferred numbers
Resistors and other electronic components are typically manufactured with values that conform to one of the E-series of preferred numbers. IEC 60063 defines the following E-series:

> ### E6:
>
> 10 15 22 33 47 68
>
> ### E12:
>
> 10 12 15 18 22 27 33 39 47 56 68 82
>
> ### E24:
>
> 10 11 12 13 15 16 18 20 22 24 27 30 33 36 39 43 47 51 56 62 68 75 82 91
>
> ### E48:
>
> 100 105 110 115 121 127 133 140 147 154 162 169 178 187 196 205 215 226 237 249 261 274 287 301 316 332 348 365 383 402 422 442 464 487 511 536 562 590 619 649 681 715 750 787 825 866 909 953
>
> ### E96:
>
> 100 102 105 107 110 113 115 118 121 124 127 130 133 137 140 143 147 150 154 158 162 165 169 174 178 182 187 191 196 200 205 210 215 221 226 232 237 243 249 255 261 267 274 280 287 294 301 309 316 324 332 340 348 357 365 374 383 392 402 412 422 432 442 453 464 475 487 499 511 523 536 549 562 576 590 604 619 634 649 665 681 698 715 732 750 768 787 806 825 845 866 887 909 931 953 976
>
> ### E192:
>
> 100 101 102 104 105 106 107 109 110 111 113 114 115 117 118 120 121 123 124 126 127 129 130 132 133 135 137 138 140 142 143 145 147 149 150 152 154 156 158 160 162 164 165 167 169 172 174 176 178 180 182 184 187 189 191 193 196 198 200 203 205 208 210 213 215 218 221 223 226 229 232 234 237 240 243 246 249 252 255 258 261 264 267 271 274 277 280 284 287 291 294 298 301 305 309 312 316 320 324 328 332 336 340 344 348 352 357 361 365 370 374 379 383 388 392 397 402 407 412 417 422 427 432 437 442 448 453 459 464 470 475 481 487 493 499 505 511 517 523 530 536 542 549 556 562 569 576 583 590 597 604 612 619 626 634 642 649 657 665 673 681 690 698 706 715 723 732 741 750 759 768 777 787 796 806 816 825 835 845 856 866 876 887 898 909 920 931 942 953 965 976 988

Given a single input integer from the set `{6, 12, 24, 48, 96, 192}`, output the corresponding E-series, in order, containing exactly the numbers as shown above for the given series.

* Output may be in whatever format of list, array, etc is appropriate for your language.
* Base 10 integers only.
* builtins that specifically implement these series are disallowed.

# Answer
> 4 votes
## Python 3, 97 bytes

```
lambda n:[round(10**(i/n+2-(n<25)))+((.4<i/n<.67)-(.9<i/n<.92))*(n<25)+(i==185)for i in range(n)]

```

The output values scaled from 1 to 10 are well-approximated by an exponential interpolation:

```
10**(i/n)

```

Multiplying by 10 for `6, 12, 24` and 100 for `48, 96, 192` then rounding to the nearest integer

```
round(10**(i/n+2-(n<25)))

```

gives the right answers for all but 16 values, which gives errors of ±1.

```
n   i   est val  diff
6   3   32  33  -1
6   4   46  47  -1
12  5   26  27  -1
12  6   32  33  -1
12  7   38  39  -1
12  8   46  47  -1
12  11  83  82  1
24  10  26  27  -1
24  11  29  30  -1
24  12  32  33  -1
24  13  35  36  -1
24  14  38  39  -1
24  15  42  43  -1
24  16  46  47  -1
24  22  83  82  1
192 185 919 920 -1

```

For `n<=24`, most of these errors are for inputs values in the interval `10/24<=i/n<=6/24`. There's one other error for `n==24` that trickles down to `n==12`, and one error for `n==192`. We fudge these errors by adding or subtracting `1` to the estimate.

# Answer
> 1 votes
## Mathematica, ~~904~~ 879 bytes

```
If[#>4!,{100,101,102,104,105,106,107,109,110,111,113,114,115,117,118,120,121,123,124,126,127,129,130,132,133,135,137,138,140,142,143,145,147,149,150,152,154,156,158,160,162,164,165,167,169,172,174,176,178,180,182,184,187,189,191,193,196,198,200,203,205,208,210,213,215,218,221,223,226,229,232,234,237,240,243,246,249,252,255,258,261,264,267,271,274,277,280,284,287,291,294,298,301,305,309,312,316,320,324,328,332,336,340,344,348,352,357,361,365,370,374,379,383,388,392,397,402,407,412,417,422,427,432,437,442,448,453,459,464,470,475,481,487,493,499,505,511,517,523,530,536,542,549,556,562,569,576,583,590,597,604,612,619,626,634,642,649,657,665,673,681,690,698,706,715,723,732,741,750,759,768,777,787,796,806,816,825,835,845,856,866,876,887,898,909,920,931,942,953,965,976,988}[[;;;;192/#]],{10,11,12,13,15,16,18,20,22,24,27,30,33,36,39,43,47,51,56,62,68,75,82,91},[[;;;;24/#]]]&

```

~~Ungolfed~~ ~~Massive-list-free~~ ~~Logic-only~~ version:

```
If[#>4!,{E192}[[;;;;192/#]],{E24}[[;;;;24/#]]]&

```

## Almost version, 60 bytes

```
Floor[Table[If[#>4!,100,10]Surd[10,#]^x,{x,0,#}]+.5][[;;-2]]

```

Accurate to within ±1

---
Tags: code-golf, kolmogorov-complexity, sequence, electrical-engineering
---


title: Generate an aperiodic integer sequence

text:
# Question
Title: Generate an aperiodic integer sequence
Your task is to build a piece of code that generates an aperiodic sequence of integers, either by outputting one every time it iterates, or by taking an integer `n` and returning the `n`th number in that sequence.

Now, the sequence `1, 2, 3, 4, 5, 6, ...` is itself aperiodic, so I'm going to introduce a few limitations to the definition of "aperiodic" used in this problem to weed out the trivial cases:

* The sequence must not be periodic modulo any integer `m > 1`. So a sequence like the powers of 2 would repeat `2, 4, 8, 6` all the time modulo 10, and therefore not count. (It would also repeat `0` modulo 2.)
* The sequence must not become periodic after a certain number of operations - e.g. `1 2 4 8 6 2 4 8 6 ...` is still considered periodic even though 1 never appears again.
* The generation code must only use integers. So a piece of code that calculated the `n`th digit of pi (without calculating it in some integer form first) would not be acceptable.

Now, obviously every sequence performed with limited computer memory will eventually either be periodic or run out of memory, but if you can prove that your function, given infinite memory and time, will never loop back to a previous state, then it is acceptable.

The shortest code that does the above wins.

# Answer
# Golfscript, 2 characters

```
`,

```

(stringify (```) the number and count (`,`) the digits)

# J, 3 characters

```
#q:

```

is the count (`#`) of the prime factors (`q:`) of its input.

The vector form involves more bookkeeping, but that's not our contestant:

```
#@q:L:0&.<

```

the first 40 terms are: 0 1 1 2 1 2 1 3 2 2 1 3 1 2 2 4 1 3 1 3 2 2 1 4 2 2 3 3 1 3 1 5 2 2 2 4 1 2 2 4

see more at OEIS

The sequence is 1 at every prime position, 2 at every prime multiple of a prime, 3 at every prime multiple of a product of two primes...

---

If you are not convinced this is aperiodic, here are plenty of other sequences:

```
##:

```

(the number of bits = floor of the base-2 logarithm)

```
+/#:

```

(count of 1-bits in the binary representation of the number). This (reduced under any modulus)

```
#b#:
+/b#:

```

(the same in base-b)

```
<.^.
>.^.
<.b^.
>.b^.

```

(floor or ceiling of the (natural) log - this time without stringification)

```
*./#:
+./b#:
*./b#:

```

(GCD or LCM of all base-b digits (except GCD of bits won't work))

```
1{#:!
9{#:!
({#:@!)

```

(second/tenth/nth highest bit of the factorial of n)

```
(=<.&.%:)

```

(Is the number equal its floor under the square root operation? Is the number equal the square of the floor of its square root? Is the number a square?)
> 18 votes

# Answer
# Python, ~~48~~ 25 bytes

Volatility's version, using string operations:

```
f=lambda a:int(`2**a`[0])

```

Numerical version (48 bytes):

```
def f(a):
 m=2**a
 while m>9:
  m/=10
 return m

```

Sequence it returns (first 100 terms):

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

```

This returns the first digit of the `a`th power of 2, which is aperiodic because log<sub>10</sub> 2 is irrational, and no multiple of it besides 0 will be an integer. (So while it may *look* periodic for a long time, eventually there will always be something to break the period.)

I could probably golf for whitespace, but I'm not experienced with that.
> 4 votes

# Answer
# Python, 14

```
int.bit_length

```

This generates the following sequence:

```
>>> f=int.bit_length
>>> [f(i) for i in range(20)]
[0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5]

```
> 4 votes

# Answer
# Perl -p, 7 characters

```
$_.=/1/

```

Takes an integer n on the standard input and outputs the nth number in the following sequence:

```
11 2 3 4 5 6 7 8 9 101 111 121 131 141 151 161 171 181 191 20 211 22 23 24 25 26...

```
> 3 votes

# Answer
## Sage, 7

Sage has the integer-part-of-the-square-root function built-in :

```
f=isqrt

[f(n) for n in [0..20]]
->  [0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4]

```

A number of OEIS sequences are also Sage built-ins named using the OEIS index, and would score a length of **16**; e.g.,

```
f=sloane.A000120

f;[f(n) for n in [0..20]
->  1's-counting sequence: number of 1's in binary expansion of n.
    [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2]

```
> 2 votes

# Answer
## Perl, ~~19~~ 18 characters

Simplicity itself:

```
sub f{"@_"=~/(.)/}

```

Given an integer `n`, the function `f` returns the `n`th number in the sequence.

For those not conversant in Perl, `f` returns the leading decimal digit in `n`. As the sequence continues, you get progressively longer runs of the current number. Thus the sequence is transparently aperiodic, and avoids devolving into any of the trivial cases listed above.
> 1 votes

# Answer
# RETURN, 9 bytes (noncompetitive)

```
0[' ,1+$¦{\3}§.1!]!

```

`Try it here.`

Make sure to run using "timed run," because this is an infinite stream. Also replace `\3` with character `U+0003`.

# Explanation

Basically just outputs each number reversed. I couldn't find any periodicity, but please tell me if you do.
> 0 votes

---
Tags: code-golf, math
---


title: Build an analog clock

text:
# Question
Title: Build an analog clock
Write a program which displays the current system time as an analog clock, using ASCII graphics. The clock must show at least the hour and minute pointers, and must have enough resolution of at least 5 minutes.

The display can be as small and as ugly as you wish, but the shown time should be easily recognizable.

The program has to run continuously and update its status. If your system can clear the screen, use it, otherwise it's enough to repaint the clock when its state changes.

You get a -20% bonus on the character count if the clock has at least a 1 minute resolution.

# Answer
# Mathematica 207 - 42 = 165

The ticks and hour labels are placed on the unit circle. `H` and `M` revolve around the clock center showing the whole number of completed hours and minutes, respectively. `S` updates its position several times each second.

Two versions are shown: a version that plots text in the Cartesian plane, and another that displays text characters in a grid.

This version plots the characters into the Cartesian plane.

```
d = Dynamic; t = Table; x = Text;i_~u~k_ := {Sin[2 \[Pi] i/k], Cos[2 \[Pi] i/k]};
d[{f = Date[], Clock[{1, 1}, 1]}]
Graphics[d@{t[x[".", u[i, 60]], {i, 60}],t[x[i, u[i, 12]], {i, 12}],
x["H", .7 u[f〚4〛, 12]],x["M", .8 u[f〚5〛, 60]],x["S", .9 u[f〚6〛, 60]]}]

```

The clock below shows the time **3:08:17**.

**Terminal or Grid Version**: 430 316 chars (253 with bonus discount)

This version works much the same, but places the characters in a 61 x 61 cell grid rather than in the Cartesian plane. It could still be golfed a bit, but I merely wanted to show a (sloppier) terminal-like output in *Mathematica*.

```
d = Dynamic; i_~u~k_ := Round /@ (10 {Sin[2 \[Pi] (i + 3 k/4)/k],
Cos[2 \[Pi] (i + 3 k/4)/k]}); d[{f = Date[], Clock[]}]
z = Round /@ (# u[f[[#2]], #3] + 11) -> #4 &;
t = Table[( u[i, 12] + 11) -> i, {i, 12}];
d@Grid[ReplacePart[ConstantArray["", {21, 21}],
Join[z @@@ {{.9, 5, 60, "M"}, {.8, 4, 12, "H"}},
DeleteCases[Table[( u[i, 60] + 11) -> "*", {i, 60}], x_ /; MemberQ[t[[All, 1]], x[[1]]]], t]]]

```

The clock below displays **11:06**.

---

Just for fun:

Here's a non-Ascii version of the analog clock. (60 chars) No external libraries were used.

```
Dynamic@Refresh[ClockGauge@AbsoluteTime[], UpdateInterval -> 1]

```
> 10 votes

# Answer
## Javascript 370 - 74 = 296

http://jsfiddle.net/wBKQ6/7/

(This only works in Chrome because I'm abusing the fact that element IDs are added to the global scope).

```
(function loop(){
    M=Math;p=M.PI/2;z=M.pow;q=M.sqrt;d=new Date();h=(d.getHours()%12/3*p+p)%(p*4);m=(d.getMinutes()/15*p+p)%(p*4);s=(d.getSeconds()/15*p+p)%(p*4);e=49;o='';

    for(r=0;r<99;r++){
        for(c=0;c<99;c++){
            d=q(z(r-e,2)+z(c-e,2));
            a=(M.atan2(e-r,e-c)+p*4)%(p*4);
            E=(d<e*.8&&M.abs(m-a)*d<.5) || (d<e*.5&&M.abs(h-a)*d<.5) || (d<e*1&&M.abs(s-a)*d<.5);
            o+=d-e>0||d<1||E||(e-d<5&&a%p==0)?'●':'○';
            //■□●○
        }
        o+='\n';
    }
    O.innerText=o
    setTimeout(loop,1000);
})()

```

Golfed (370):

```
!function L(){p=M.PI/2;q=p*4;P=M.pow;d=new Date();s=(d.getSeconds(S=d.getMinutes(e=40))/15*p+p)%q;m=(S/15*p+p)%q;h=(d.getHours(A=M.abs)%12/3*p+S/180*p+p)%q;for(r=o='';r<81;r++,o+='\n')for(c=0;c<81;){d=M.sqrt(P(r-e,2)+P(c-e,2));a=(M.atan2(e-r,e-c++)+q)%q;o+='○●'[d-e>0|d<e*.8&A(m-a)*d<1|d<e/2&A(h-a)*d<1|d<e&A(s-a)*d<1|e-d<5&a%p==0]}O.innerText=o;setTimeout(L,9)}(M=Math)

```

Sample Output (much more condensed in demo):

```
●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●
●●●●●●●●●●●●●●○○○○○○●○○○○○○●●●●●●●●●●●●●●
●●●●●●●●●●●●○○○○○○○○●○○○○○○○○●●●●●●●●●●●●
●●●●●●●●●●○○○○○○○○○○●○○○○○○○○○○●●●●●●●●●●
●●●●●●●●○○○○○○○○○○○○●○○○○○○○○○○○○●●●●●●●●
●●●●●●●○○○○○○○○○○○○○○○○○○○○○○○○○○○●●●●●●●
●●●●●●○○○○○○○○○○○○○○○○○○○○○○○○○○○○○●●●●●●
●●●●●○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○●●●●●
●●●●○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○●●●●
●●●●○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○●●●●
●●●○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○●●●
●●●○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○●●●
●●○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○●●
●●○○○○○○○○○○○○○○○○○○○○○○○○○●○○○○○○○○○○○●●
●○○○○○○○○○○○○○○○○○○○○○○○○○●●○○○○○○○○○○○○●
●○○○○○○○○○○○○○○○○○○○○○○○○●●○○○○○○○○○○○○○●
●○○○○○○○○○○○○○○○○○○○○○○○●●○○○○○○○○○○○○○○●
●○○○○○○○○○○○○○○○○○○○○○○●●○○○○○○○○○○○○○○○●
●○○○○○○○○○○○○○○○○○○○○○●○○○○○○○○○○○○○○○○○●
●○○○○○○○○○○○○○○○○○○○○●○○○○○○○○○○○○○○○○○○●
●●●●●○○○○○○○○○○○○○○○●○○○○○○○○○○○○○○○●●●●●
●○○○○○○○○○○○○○○○○○○●○●○○○○○○○○○○○○○○○○○○●
●○○○○○○○○○○○○○○○○○○●○○●○○○○○○○○○○○○○○○○○●
●○○○○○○○○○○○○○○○○○●○○○○●●○○○○○○○○○○○○○○○●
●○○○○○○○○○○○○○○○○○●○○○○○●●○○○○○○○○○○○○○○●
●○○○○○○○○○○○○○○○○●○○○○○○○●●○○○○○○○○○○○○○●
●○○○○○○○○○○○○○○○●●○○○○○○○○●●○○○○○○○○○○○○●
●●○○○○○○○○○○○○○○●○○○○○○○○○○○●○○○○○○○○○○●●
●●○○○○○○○○○○○○○●○○○○○○○○○○○○○●○○○○○○○○○●●
●●●○○○○○○○○○○○○●○○○○○○○○○○○○○○●○○○○○○○●●●
●●●○○○○○○○○○○○●○○○○○○○○○○○○○○○○●○○○○○○●●●
●●●●○○○○○○○○○○●○○○○○○○○○○○○○○○○○●○○○○●●●●
●●●●○○○○○○○○○●○○○○○○○○○○○○○○○○○○○●●○○●●●●
●●●●●○○○○○○○●●○○○○○○○○○○○○○○○○○○○○●●●●●●●
●●●●●●○○○○○○○○○○○○○○○○○○○○○○○○○○○○○●●●●●●
●●●●●●●○○○○○○○○○○○○○○○○○○○○○○○○○○○●●●●●●●
●●●●●●●●○○○○○○○○○○○○●○○○○○○○○○○○○●●●●●●●●
●●●●●●●●●●○○○○○○○○○○●○○○○○○○○○○●●●●●●●●●●
●●●●●●●●●●●●○○○○○○○○●○○○○○○○○●●●●●●●●●●●●
●●●●●●●●●●●●●●○○○○○○●○○○○○○●●●●●●●●●●●●●●
●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●

```
> 14 votes

# Answer
## Python, 328 - 65 = 263

Prints a new clock every second, with the minute hand updating every minute.

```
import math,time
def p(t,r):c[int(25-r*math.cos(t))][int(25+r*math.sin(t))]='*'
while 1:
 time.sleep(1);c=[[' ']*50 for i in range(50)];t=time.localtime();h=t.tm_hour*6.283+t.tm_min/9.549
 for i in range(999):
    p(i/158.0,24);p(h,i*.02);p(h/12,i*.01)
    for q in range(12):p(q/1.91,24-i*.005)
 for y in range(50):print''.join(c[y])

```

The clocks it prints look like this (it's not as stretched in my terminal):

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

```
> 12 votes

# Answer
## 100% pure only! Without fork!

A finalized and upgraded version could be found there or on this page: ascii-clock for geeks. But don't use it! Read the note at end of this answer, you've been warned! Use this perl version instead!

### First simple clock without second tick.

Scalable and editable:

```
time 2>&1 /tmp/asci-art.sh 10 10 10
              . . . 12. . .
          11.               . 1
        .                       .
      .                           .
    .                               .
  10                                  2
  .     H                           M .
.                                       .
.                                       .
.                                       .
9                                       3
.                                       .
.                                       .
.                                       .
  .                                   .
  8                                   4
    .                               .
      .                           .
        .                       .
          7 .               . 5
              . . . 6 . . .

real    0m0.356s
user    0m0.348s
sys     0m0.004s

```

Draw a 21x21 (10x2+1) clock at 10H10 in less than one second.

This accept 3 arguments: `Usage: ascii-clock.sh [ray of clock] [Hour] [Min]` where default ray is 12, clock drawing is `2 x ray + 1` lines height and double width because of space added to try to obtain a round shape.

If the script is called with `0` or `1` argument, it will loop to redraw each minute. Else if at least *Hour* (second param) is specified, It will draw only once and exit.

The `H` marker is located at 70% of ray and the `M` marker is located at 90% of ray.

**No use of external binaries like `date` or `bc`** for the draw!

(Thanks to @manatwork for the *builtin* `read -t` in place if `/bin/sleep`).

So all this is done by *builtin* shell commands.

It use *ANSI* sequence, but only for loop and to make markers bold.

```
#!/bin/bash
# Analog clock in Ascii-Art written in BASH V4.2 +=

RAY=${1:-12} NowH=$2 NowM=$3

sqrt() {
    local -a _xx=(600000 200000)
    local _x1=${_xx[$(($1&1))]} _x0=1
    while [ $_x0 -ne $_x1 ] ;do
        _x0=$_x1
        [ $_x0 -eq 0 ] && _x1=0000 ||
        printf -v _x1 "%u" $(( (${_x0}000 + ${1}00000000000/${_x0} )/2 ))
        printf -v _x1 "%.0f" ${_x1:0:${#_x1}-3}.${_x1:${#_x1}-3}
    done
    _x1=0000$_x1
    printf ${2+-v} $2 "%.3f" ${_x1:0:${#_x1}-4}.${_x1:${#_x1}-4}
}
clksin() { # $1:moment [0-60], $2:path length, $3:variable name
    local _csin=(0 104528 207912 309017 406737 500000 587785 669131
        743145 809017 866025 913545 951057 978148 994522 1000000)
    local xsign=1 x=$1 ysign=-1 y=$1
    [ $x -gt 30 ] && xsign=-1 x=$((60-x))
    [ $x -gt 15 ] && x=$((30-x))
    x=00000$((RAY*1000000+xsign*${2:-10}*${_csin[$x]}))
    [ $y -gt 30 ] && y=$((60-y))
    [ $y -gt 15 ] && ysign=1 y=$((30-y))
    y=00000$((RAY*1000000+ysign*${2:-10}*${_csin[15-$y]}))
    printf ${3+-v} $3 "%.0f %.0f" \
        ${y:0:${#y}-6}.${y:${#y}-6} ${x:0:${#x}-6}.${x:${#x}-6}
};

MLEN=000$((900*RAY))
printf -v MLEN "%.0f" ${MLEN:0:${#MLEN}-3}.${MLEN:${#MLEN}-3}
HLEN=000$((700*RAY))
printf -v HLEN "%.0f" ${HLEN:0:${#HLEN}-3}.${HLEN:${#HLEN}-3}

declare -A ticks
for ((i=1;i<=12;i++));do
    clksin $((5*(i%12))) $RAY tick
    ticks[$tick]=$i
done

while :;do
    [ "$NowM" ] || printf -v NowM "%(%M)T\n" -1
    clksin ${NowM#0} $MLEN NowM
    [ "$NowH" ] || printf -v NowH "%(%H)T\n" -1
    clksin $((5*(${NowH#0}%12))) $HLEN NowH

    [ "$2" ] || echo -en \\e[H; # ANSI sequence for top left of console
    for ((i=0;i<=2*RAY;i++));do
        x=$((RAY-i))
        sqrt $((RAY**2 - ${x#-}**2 )) y0
        printf -v y0 "%.0f" $y0
        for ((l=0;l<=2*RAY;l++));do
            y=$((RAY-l));
            sqrt $((RAY**2 - ${y#-}**2 )) x0
            printf -v x0 "%.0f" $x0
            if [ "${ticks["$i $l"]}" ] ;then
                printf "%-2s" ${ticks["$i $l"]}
            elif [ ${x#-} -eq $x0 ] || [ ${y#-} -eq $y0 ] ;then
                echo -n .\
            elif [ "$i $l" = "$NowM" ] ;then
                echo -en \\e[1mM\ \\e[0m
            elif [ "$i $l" = "$NowH" ] ;then
                echo -en \\e[1mH\ \\e[0m
            else
                echo -n \ \
            fi
        done
        echo -e \\e[K
    done
    echo -en \\e[J
    [ "$2" ] && break # Exit if at least Hour was specified
    printf -v SleepS "%(%S)T" -1
    read -t $((60-${SleepS#0})) foo
    unset NowH NowM
done

```

This could by run as:

```
for time in 10:10 15:00 12:30 06:00 09:15 16:40 ;do
    echo - $time -{,}{,}{,}
    ./ascii-clock.sh 5 ${time//:/ }
    echo -{,,,,,}{,}
  done |
    sed 's/\o033\[\(.m\|[JK]\)//g;/-$/!s/$/|/;s/-$/+/' |
    column -c 80

```

This will produce something like:

```
+- 10:10 - - - - - - - + - 12:30 - - - - - - - + - 09:15 - - - - - - - +
|      . . 12. .       |       . . 12. .       |       . . 12. .       |
|    11          1     |     11    H     1     |     11          1     |
|  10              2   |   10              2   |   10              2   |
|.   H           M   . | .                   . | .                   . |
|.                   . | .                   . | .                   . |
|9                   3 | 9                   3 | 9 H               M 3 |
|.                   . | .                   . | .                   . |
|.                   . | .                   . | .                   . |
|  8               4   |   8               4   |   8               4   |
|    7           5     |     7     M     5     |     7           5     |
|      . . 6 . .       |       . . 6 . .       |       . . 6 . .       |
+- - - - - - - - - - - + - - - - - - - - - - - + - - - - - - - - - - - +
+- 15:00 - - - - - - - + - 06:00 - - - - - - - + - 16:40 - - - - - - - +
|      . . 12. .       |       . . 12. .       |       . . 12. .       |
|    11    M     1     |     11    M     1     |     11          1     |
|  10              2   |   10              2   |   10              2   |
|.                   . | .                   . | .                   . |
|.                   . | .                   . | .                   . |
|9                 H 3 | 9                   3 | 9                   3 |
|.                   . | .                   . | .                   . |
|.                   . | .                   . | .   M           H   . |
|  8               4   |   8               4   |   8               4   |
|    7           5     |     7     H     5     |     7           5     |
|      . . 6 . .       |       . . 6 . .       |       . . 6 . .       |
+- - - - - - - - - - - + - - - - - - - - - - - + - - - - - - - - - - - +

```

Or could be run as:

```
xterm -geom 86x44 -bg black -fg grey -e ./ascii-clock.sh 21 &

xterm -geom 103x52 -fn nil2 -bg black -fg grey -e ./ascii-clock.sh 25 &

gnome-terminal --geometry 103x52 --zoom .5 -e "./ascii-clock.sh 25" &

```

### Alternative: With full path drawing:

```
#!/bin/bash
# Analog clock in Ascii-Art written in BASH V4.2 +=

RAY=${1:-12} NowH=$2 NowM=$3

sqrt() {
    local -a _xx=(600000 200000)
    local _x1=${_xx[$(($1&1))]} _x0=1
    while [ $_x0 -ne $_x1 ] ;do
        _x0=$_x1
        [ $_x0 -eq 0 ] && _x1=0000 ||
    printf -v _x1 "%u" $(( (${_x0}000 + ${1}00000000000/${_x0} )/2 ))
        printf -v _x1 "%.0f" ${_x1:0:${#_x1}-3}.${_x1:${#_x1}-3}
    done
    _x1=0000$_x1
    printf ${2+-v} $2 "%.3f" ${_x1:0:${#_x1}-4}.${_x1:${#_x1}-4}
}
clksin() { # $1:moment [0-60], $2:path length, $3:variable name
    local _csin=(0 104528 207912 309017 406737 500000 587785 669131
    743145 809017 866025 913545 951057 978148 994522 1000000)
    local xsign=1 x=$1 ysign=-1 y=$1
    [ $x -gt 30 ] && xsign=-1 x=$((60-x))
    [ $x -gt 15 ] && x=$((30-x))
    x=00000$((RAY*1000000+xsign*${2:-10}*${_csin[$x]}))
    [ $y -gt 30 ] && y=$((60-y))
    [ $y -gt 15 ] && ysign=1 y=$((30-y))
    y=00000$((RAY*1000000+ysign*${2:-10}*${_csin[15-$y]}))
    printf ${3+-v} $3 "%.0f %.0f" \
    ${y:0:${#y}-6}.${y:${#y}-6} ${x:0:${#x}-6}.${x:${#x}-6}
};

MLEN=000$((900*RAY))
printf -v MLEN "%.0f" ${MLEN:0:${#MLEN}-3}.${MLEN:${#MLEN}-3}
HLEN=000$((700*RAY))
printf -v HLEN "%.0f" ${HLEN:0:${#HLEN}-3}.${HLEN:${#HLEN}-3}

declare -A ticks
for ((i=1;i<=12;i++));do
    clksin $((5*(i%12))) $RAY tick
    ticks[$tick]=$i
done

while :;do
    [ "$NowM" ] || printf -v NowM "%(%M)T\n" -1
    unset MPath
    declare -A MPath
    for ((i=1;i<=MLEN;i++));do
    clksin ${NowM#0} $i tick
    MPath[$tick]=M
    done
    [ "$NowH" ] || printf -v NowH "%(%H)T\n" -1
    unset HPath
    declare -A HPath
    for ((i=1;i<=HLEN;i++));do
    clksin $((5*(${NowH#0}%12))) $i tick
    HPath[$tick]=H
    done

    [ "$2" ] || echo -en \\e[H; # ANSI sequence for top left of console
    for ((i=0;i<=2*RAY;i++));do
    x=$((RAY-i))
    sqrt $((RAY**2 - ${x#-}**2 )) y0
    printf -v y0 "%.0f" $y0
    for ((l=0;l<=2*RAY;l++));do
        y=$((RAY-l));
        sqrt $((RAY**2 - ${y#-}**2 )) x0
        printf -v x0 "%.0f" $x0
        if [ "${MPath["$i $l"]}" ] ;then
        echo -en \\e[1m${MPath["$i $l"]}\ \\e[0m
        elif [ "${HPath["$i $l"]}" ] ;then
        echo -en \\e[1m${HPath["$i $l"]}\ \\e[0m
        elif [ "${ticks["$i $l"]}" ] ;then
        printf "%-2s" ${ticks["$i $l"]}
        elif [ ${x#-} -eq $x0 ] || [ ${y#-} -eq $y0 ] ;then
        echo -n .\
        else
        echo -n \ \
        fi
    done
    echo -e \\e[K
    done
    echo -en \\e[J
    [ "$2" ] && break # Exit if at least Hour was specified
    printf -v SleepS "%(%S)T" -1
    read -t $((60-${SleepS#0})) foo
    unset NowH NowM
done

```

could produce:

```
+- 10:10 - - - - - - - + - 12:30 - - - - - - - + - 09:15 - - - - - - - +
|      . . 12. .       |       . . 12. .       |       . . 12. .       |
|    11          1     |     11    H     1     |     11          1     |
|  10              2   |   10      H       2   |   10              2   |
|.   H           M   . | .         H         . | .                   . |
|.   H H H   M M M   . | .         H         . | .                   . |
|9                   3 | 9                   3 | 9 H H H H   M M M M 3 |
|.                   . | .         M         . | .                   . |
|.                   . | .         M         . | .                   . |
|  8               4   |   8       M       4   |   8               4   |
|    7           5     |     7     M     5     |     7           5     |
|      . . 6 . .       |       . . 6 . .       |       . . 6 . .       |
+- - - - - - - - - - - + - - - - - - - - - - - + - - - - - - - - - - - +
+- 15:00 - - - - - - - + - 06:00 - - - - - - - + - 16:40 - - - - - - - +
|      . . 12. .       |       . . 12. .       |       . . 12. .       |
|    11    M     1     |     11    M     1     |     11          1     |
|  10      M       2   |   10      M       2   |   10              2   |
|.         M         . | .         M         . | .                   . |
|.         M         . | .         M         . | .                   . |
|9           H H H H 3 | 9                   3 | 9                   3 |
|.                   . | .         H         . | .   M M M   H H H   . |
|.                   . | .         H         . | .   M           H   . |
|  8               4   |   8       H       4   |   8               4   |
|    7           5     |     7     H     5     |     7           5     |
|      . . 6 . .       |       . . 6 . .       |       . . 6 . .       |
+- - - - - - - - - - - + - - - - - - - - - - - + - - - - - - - - - - - +

```

or

```
                                . . . . 12. . . .
                          . . .                   . . .
                      . .                               . .
                  . 11                                      1 .
                .                                               .
              .                                                   .
            .                                                       .
          .                                                           .
        .                                                               .
      .                                                                   .
      10                                                                  2
    .                                                                   M   .
    .                                                             M M M     .
  .             H                                               M             .
  .               H H                                       M M               .
  .                   H                                   M                   .
.                       H H H                       M M M                       .
.                             H                   M                             .
.                               H H           M M                               .
.                                   H       M                                   .
9                                     H   M                                     3
.                                                                               .
.                                                                               .
.                                                                               .
.                                                                               .
  .                                                                           .
  .                                                                           .
  .                                                                           .
    .                                                                       .
    .                                                                       .
      8                                                                   4
      .                                                                   .
        .                                                               .
          .                                                           .
            .                                                       .
              .                                                   .
                .                                               .
                  . 7                                       5 .
                      . .                               . .
                          . . .                   . . .
                                . . . . 6 . . . .

```

### Last version with *Seconds* ticks rendering and *nanosleep* to sync.

This work only on recent Linux, as this use `/proc/timer_list` to compute fraction of second to sleep between each refresh.

```
#!/bin/bash
# Analog clock in Ascii-Art written in BASH V4.2 +=

RAY=${1:-12} NowH=$2 NowM=$3

# Hires Sleep Until
# there is a need to store offset in a static var

mapfile  </proc/timer_list _timer_list
for ((_i=0;_i<${#_timer_list[@]};_i++));do
    [[ ${_timer_list[_i]} =~ ^now ]] && TIMER_LIST_SKIP=$_i
    [[ ${_timer_list[_i]} =~ offset:.*[1-9] ]] && \
        TIMER_LIST_OFFSET=${_timer_list[_i]//[a-z.: ]} && \
        break
done
unset _i _timer_list
readonly TIMER_LIST_OFFSET TIMER_LIST_SKIP

sleepUntilHires() {
    local slp tzoff now quiet=false nsnow nsslp
    local hms=(${1//:/ })
    mapfile -n 1 -s $TIMER_LIST_SKIP nsnow </proc/timer_list
    printf -v now '%(%s)T' -1
    printf -v tzoff '%(%z)T\n' $now
    nsnow=$((${nsnow//[a-z ]}+TIMER_LIST_OFFSET))
    nsslp=$((2000000000-10#${nsnow:${#nsnow}-9}))
    tzoff=$((0${tzoff:0:1}(3600*${tzoff:1:2}+60*${tzoff:3:2})))
    slp=$(( ( 86400 + ( now - now%86400 ) +
                10#$hms*3600+10#${hms[1]}*60+10#${hms[2]} -
                tzoff - now - 1
            ) % 86400)).${nsslp:1}
    read -t $slp foo
}

sqrt() {
    local -a _xx=(600000 200000)
    local _x1=${_xx[$(($1&1))]} _x0=1
    while [ $_x0 -ne $_x1 ] ;do
        _x0=$_x1
        [ $_x0 -eq 0 ] && _x1=0000 ||
    printf -v _x1 "%u" $(( (${_x0}000 + ${1}00000000000/${_x0} )/2 ))
        printf -v _x1 "%.0f" ${_x1:0:${#_x1}-3}.${_x1:${#_x1}-3}
    done
    _x1=0000$_x1
    printf ${2+-v} $2 "%.3f" ${_x1:0:${#_x1}-4}.${_x1:${#_x1}-4}
}
clksin() { # $1:moment [0-60], $2:path length, $3:variable name
    local _csin=(0 104528 207912 309017 406737 500000 587785 669131
    743145 809017 866025 913545 951057 978148 994522 1000000)
    local xsign=1 x=$1 ysign=-1 y=$1
    [ $x -gt 30 ] && xsign=-1 x=$((60-x))
    [ $x -gt 15 ] && x=$((30-x))
    x=00000$((RAY*1000000+xsign*${2:-10}*${_csin[$x]}))
    [ $y -gt 30 ] && y=$((60-y))
    [ $y -gt 15 ] && ysign=1 y=$((30-y))
    y=00000$((RAY*1000000+ysign*${2:-10}*${_csin[15-$y]}))
    printf ${3+-v} $3 "%.0f %.0f" \
    ${y:0:${#y}-6}.${y:${#y}-6} ${x:0:${#x}-6}.${x:${#x}-6}
};

SLEN=000$((870*RAY))
printf -v SLEN "%.0f" ${SLEN:0:${#SLEN}-3}.${SLEN:${#SLEN}-3}
MLEN=000$((780*RAY))
printf -v MLEN "%.0f" ${MLEN:0:${#MLEN}-3}.${MLEN:${#MLEN}-3}
HLEN=000$((650*RAY))
printf -v HLEN "%.0f" ${HLEN:0:${#HLEN}-3}.${HLEN:${#HLEN}-3}

declare -A ticks
for ((i=1;i<=12;i++));do
    clksin $((5*(i%12))) $RAY tick
    ticks[$tick]=$i
done

while :;do
    [ "$NowM" ] || printf -v NowM "%(%M)T\n" -1
    unset MPath
    declare -A MPath
    for ((i=1;i<=MLEN;i++));do
    clksin ${NowM#0} $i tick
    MPath[$tick]=M
    done
    [ "$NowH" ] || printf -v NowH "%(%H)T\n" -1
    unset HPath
    declare -A HPath
    for ((i=1;i<=HLEN;i++));do
    clksin $((5*(${NowH#0}%12))) $i tick
    HPath[$tick]=H
    done
    printf -v NowS "%(%S)T\n" -1
    clksin ${NowS#0} $SLEN STick

    [ "$2" ] || echo -en \\e[H; # ANSI sequence for top left of console
    for ((i=0;i<=2*RAY;i++));do
    x=$((RAY-i))
    sqrt $((RAY**2 - ${x#-}**2 )) y0
    printf -v y0 "%.0f" $y0
    for ((l=0;l<=2*RAY;l++));do
        y=$((RAY-l));
        sqrt $((RAY**2 - ${y#-}**2 )) x0
        printf -v x0 "%.0f" $x0
        if [ "$i $l" = "$STick" ] ;then
                echo -en \\e[1ms\ \\e[0m
        elif [ "${MPath["$i $l"]}" ] ;then
        echo -en \\e[1m${MPath["$i $l"]}\ \\e[0m
        elif [ "${HPath["$i $l"]}" ] ;then
        echo -en \\e[1m${HPath["$i $l"]}\ \\e[0m
        elif [ "${ticks["$i $l"]}" ] ;then
        printf "%-2s" ${ticks["$i $l"]}
        elif [ ${x#-} -eq $x0 ] || [ ${y#-} -eq $y0 ] ;then
        echo -n .\
        else
        echo -n \ \
        fi
    done
    echo -e \\e[K
    done
    echo -en \\e[J
    [ "$2" ] && break # Exit if at least Hour was specified
    printf -v SleepS "%(%s)T" -1
    printf -v SleepS "%(%T)T" $((1+SleepS))
    sleepUntilHires $SleepS
    unset NowH NowM
done

```

### More obfuscated version (2702 bytes):

As requested by @manatwork, there is a *more golfed* version.

This version is colorized and present digital time on corners.

```
#!/bin/bash
W=/proc;J=${1:-12} B=$2 A=$3 LANG=C R=$W/timer_list;if [ -f $R ];then Q=10
mapfile <$R e;for ((P=0;P<${#e[@]};P++));do ((Q+=${#e[P]}));[[ ${e[P]} =~ ^now
]]&&U=$Q;[[ ${e[P]} =~ offset:.*[1-9] ]]&&a=${e[P]//[a-z.: ]}&&break;done;c(){
local q p;read -N$U q <$R;q=${q%% nse*};q=$[${q##* }+a];p=$[2000000000-10#${q:
${#q}-9}];read -t .${p:1} M;};else c(){ local H;read -d\  H < $W/upti*;H=$[200
-10#${H#*.}];read -t .${H:1} M;};fi;u(){ local E=({6,2}00000) F=${E[$1&1]} G=1
while [ $G -ne $F ];do G=$F;[ $G -eq 0 ]&&F=0000||printf -v F "%u" $(((${G}000
+${1}00000000000/${G})/2));printf -v F "%.0f" ${F:0:${#F}-3}.${F:${#F}-3};done
F=0000$F;printf -v $2 "%.3f" ${F:0:${#F}-4}.${F:${#F}-4};};g(){ local t=($[7#0
] 104528 207912 309017 406737 500000 587785 669131 743145 809017 866025 913545
951057 978148 994522 1000000) j=1 x=$1 h=-1 y=$1;[ $x -gt 30 ]&&j=-1 x=$[60-x]
((x>15))&&x=$[30-x];x=00000$[J*1000000+j*${2:-10}*${t[$x]}];((y>30))&&y=$[60-y
];((y>15))&&h=1 y=$[30-y];y=00000$[J*1000000+h*${2:-10}*${t[15-y]}];printf -v\
$3 "%.0f %.0f" ${y:0:${#y}-6}.${y:${#y}-6} ${x:0:${#x}-6}.${x:${#x}-6};};v=000
v+=$((870 *J));printf -v v "%.0f" ${v:0:${#v}-3}.${v:${#v}-3};C=000$((780*J));
printf -v C "%.0f" ${C:0:${#C}-3}.${C:${#C}-3};D=000$[650*J];printf -v D %.f \
${D:0:${#D}-3}.${D:${#D}-3};declare -A m;for ((i=1;i<=12;i++));do g $[5*(i%12)
] $J w;m[$w]=$i;done;printf -v T "\e[1m%s\e[0m " . + \* o O;T=(${T});m["${J: \
} $J"]=${T} ;printf "\e[?25l\e[H\e[J";trap "printf '\e[?12l\e[?25h\e[$((2*J +3
))H\e[J';exit" 0 1 2 3 6 9 15; printf -v S "\\e[1;%dH%%(%%H)T\\e[%dH%%(%%M${Z:
})T\\e[%d;%dH%%(%%S)T" $[4*J] $[2*J+1] $[2*J+1] $[4*J];declare -A V;V["$[2 * J
] $[2*$J]"]="  ";while :;do [ "$A" ]||printf -v A "%(%M)T" -1;unset r;declare\
 -A r;for ((i=1;i<=C;i++));do g ${A#0} $i w;r[$w]=M;done;[ "$B" ]||printf -v \
B "%(%H)T" -1;unset s;declare -A s;for ((i=1;i<=D;i++));do g $((5*( ${B#0}%12)
)) $i w;s[$w]=H;done;printf -v z "%(%S)T" -1;g ${z#0} $v n;[ "$2" ]||echo -en\
 \\e[H;for ((i=0;i<=2*J;i++));do x=$[J-i];u $[J*J-${x#-}**2] N;printf -v N${Z:
} %.f $N;for ((l=0;l<=2*J;l++));do y=$[J-l];u $[J*J-${y#-}**2] O;printf -v O \
%.f $O;c="  ";if [ "$i $l" = "$n" ];then c=$'\e[36;1ms \e[m';elif [ "${r["${i:
} $l"]}" ] ;then c=$'\e[32;1m'${r["$i $l"]}$' \e[0m';elif [ "${s["$i $l"]}" ];
then c=$'\e[34;1m'${s["$i $l"]}$' \e[0m';elif [ "${m["$i $l"]}" ];then printf\
 -v c "%-2s" "${m["$i $l"]}";elif [ ${x#-} -eq $O ] || [ ${y#-} -eq $N ] ;then
c=.\ ;else c="  ";fi;[ "$c" != "${V["$i $l"]}" ]&& V["$i $l"]="$c" && printf \
"\e[%s;%sH%-2s" $((1+i)) $[1+l*2] "$c";done;done;[ "$2" ] &&break;printf "${Z:
}\e[H\e[7mS\e[0m";c;printf "\e[H $S" -1 -1 -1;m["$J $J"]=${T[$[10#$z%${#T[@]}]
]};unset B A;done

```

### Note: Don't use this anyway!

As this is *programm* and as bash is not a programmation language, this is not well to use for a while.

There is a little demo of memory consumption in only 5 hours, with a drawing of 7 character length ray:

```
$ ascii-clock.sh 7

After     PMem   PCpu      Mem
    0'30"  0.0%  21.6%   12.98M
   10'30"  1.0%  20.9%   48.91M
 1h 0'30"  5.6%  20.8%  228.63M
 2h 0'31" 11.2%  20.8%  444.25M
 3h 0'32" 16.8%  20.8%  659.91M
 5h 0'00" 27.9%  20.8%   1.064G

```

The main advantage of this that when I need memory, I just have to kill the clock.

( **Nota:** I've merged this, the perl version and a version of same on ascii-clock for geeks ;-)
> 8 votes

# Answer
# Python 2 - 207

```
import time as T
while 1:t=T.localtime();m=t.tm_min/5;l=[12]+range(1,12);l[m]='';l[t.tm_hour%12]='H';l[m]+='M';a='  %s\n';print(a+('%s'+a)*5+a)%tuple(str(l[x])for x in[0,11,1,10,2,9,3,8,4,7,5,6]);T.sleep(9)

```

It is very ugly, but readable. Prints every 9 sec (you can change to 1 sec if you prefer), updates every 5 min. I don't have much experience with code golfing in python so I expect it can be improved.

Example output:

```
  12
11  1
10  2
9  M
8  4
7  H
  6

```
> 6 votes

# Answer
### Perl 5 x 65 = 325 - 65(20%) = 260 chars!!

Clean, circular, with a second tick and updated every seconds.

```
perl -E '
$r=11;$p=atan2(1,1)/7.5;sub c{($A,$R,$C)=@_;$a[$r-$R*cos($A*$p)][
$r+$R*sin($A*$p)]=$C." "x($C!~/../)};while(::){@a=map{[map{"  "}(
0..$r*2)]}(0..$r*2);map{c$_*5,$r,$_}(1..12);@t=localtime;for$i(qw
|H:6:5:2 M:8:1:1 s:9:1:0 |){($S,$P,$F,$T)=split":",$i;map{c$F*$t[
$T],$_,$S}(do{$T?1:$P}/10*$r..$P/10*$r)};map{say@{$_}}@a;sleep 1}
'

```

On a 24 lines console look good (It's **00:12:56**):

```
                    12
          11                    1
                s

  10                  H                 2
                      H
                      H
                      H           M M
                      H     M M M
                      M M M
9                                           3

  8                                     4

          7                     5

                      6

```

And there is a colored, nicer and smarter version:

```
#!                               /usr/bin/perl
                        use Time::HiRes qw|sleep time|
                     ;$h=11;$h=$ARGV[0]if$ARGV[0];$P=atan2
                 (1,1)/7.5;$V =4*$h; $v= 2* $h+ 1;@r=(0..2*$v)
              ;sub p{printf @_       }sub        b{ return"\e[1m"
            .pop."\e[0m"              };$              |=p"\e[?25".
           "l\e[H\e[" ."J"            ;$             SIG{ 'INT'}=sub
         {p"\e[?1"    ."2l"                        ."\e"     ."[?25h".
      "\e[%dH"        ."\e"                       ."[J"      ,$v+2;exit;
      };@z=map                                                  {[map{" "
     }@r] }(0                                                     ..2*$v);
    @Z=map{[@                                                  {$z[$_]}]}@r
   ;sub c{($A,$r ,$s                                       )=@_;$z[$h-$r*cos
  ($A*$P)    +.5 ][$h+$                                 r*sin($A*$P)+.5]=$s;}
  for$x(        0..$h) {$y=                         int(sqrt($h**2     -$x**2
 )+.5);$         z[$h-$x][$h-$                  y]=".";$z[$h+$x        ][$h-$y
 ]=".";             $z[$h-$x][$h+$           y]=".";$z[$h+$x            ][$h+$
y]=".";                $z[$h-$y][$h-$    x]=".";$z[$h+$y                ][$h-$x
]=".";                    $z[$h-$y][$h+$x]=".";$z[$h+                    $y][$h
+$x]="."};map{               c$_*5,$h,b$_}(1..12);                @R=map{[@{$z[
$_]}]}@r;while                (::){@t=localtime;                   p"\e[H\e[1;$
{V}H%0"                       ."2d\e[${v}H%02d\e"                        ."[${v
};${ V                         }H%02d",$t[2],$t[                         1],$t[
 0];@z=                         map{[     @{$R[                         $_]}]}(
 0..2*$                                                                 v);for
 $i('H:'                                                              .'65:5:'
  .'2:4',     ""                                               x1    .'M:78:'
   ."1:1" .":2",                                               "s:8". "7:1:"
    .'0:6'){($                                                  l,$p,$F,$u,$
     c)=split                                                    ":",$i;map
      {c$F*$t                                                     [$u],$_
       ,b("\e["                                                ."3${c}m$
        l")}(do{$u     ?1:$                         p} /     100*$h..$p
          /100*$h);}  $z[$            h][            $h]=  b((".","+"
            ,"*","o","O")             [$t             [0]%5]);for$x
              (@r){for$y(@r           ){$           Z[$x][$y]ne$z
                 [$x][$y]?p"\e[%d;%dH".$z  [ $x] [$y],$x+1,2*$
                    y+1:''};};@Z=map{[@{$z[$_]}]}@r;$n=1-$1
                        if time=~/(\..*)$/;p"\e[H\e[7m"
                               ."S\e[0m";sleep$n}

```

This version is **strongly** linked to this other answer, with the main advantage: *You could run this quietly, for a while!* So you could find an upgraded version there or on this ascii-clock for geeks web page.

As a demonstration that doing *approx* same in require less resources:

```
$ ascii-clock.pl 7

After     PMem   PCpu      Mem
    0' 0"  0.0%   0.0%    23.5M
   10'30"  0.0%   0.0%    23.5M
 1h 0' 0"  0.0%   0.0%    23.5M
 2h 0' 0"  0.0%   0.0%    23.5M

```

for approx same features:

* wait for begin of each seconds for doing a refresh
* draw with color and bold attributes
* draw full circle with dots, hour tick, hour and minutes full path and a `s` dot for second handler.
* draw *digital* clock prompting *hour* at top right, *minutes* at bottom left and *seconds* at bottom right.
* prompt a `S` at top left, when *sleeping* (look for difference with version)

Plus

* The upgraded version authorize `-a` argument for drawing hour and minute path in fraction (11h59 place hour path approx at 12h).

### One more another perl version!!!

Using the following (beautiful) picture:

You could simply:

```
curl https://i.stack.imgur.com/xvbHP.png |
  perl -e 'use GD;GD::Image->trueColor(1);$i=GD::Image->newFromPng(
      STDIN);my($x,$y)=$i->getBounds();for my$k(0..$x-1){for my$l(0
      ..$y-1){$_.=pack"UUU",$i->rgb($i->getPixel($k,$l))};};eval'

```

or, with arguments (You have to add `-s` switch to perl command):

```
wget -O - http://fhauri.cartou.ch/ascii-clock/ascii-clock.png |
  perl -se 'use GD;GD::Image->trueColor(1);$i=GD::Image->newFromPng(
      STDIN);my($x,$y)=$i->getBounds();for my$k(0..$x-1){for my$l(0
      ..$y-1){$_.=pack"UUU",$i->rgb($i->getPixel($k,$l))};};eval' -- -a 18

```

This require having gd2-perl installed! (You could replace `curl` by `wget -O -` ;-)

( Note: This picture is near 1.5Kb. I've built another *same* picture, but 900 bytes length. You may find this picture, well as a version of same at ascii-clock for geeks :-)
> 3 votes

# Answer
### Tcl, 288

```
while 1 {scan [clock format [clock seconds] -format %k-%M] %d-%d h m
regsub -all \ +|. "oaosocowoeouooovoioxozom   r    n\n" \ {&} p
lset p [set h [expr $h%12*2]] h
lset p [set m [expr $m/5*2]] [expr $h-$m?"m":"x"]
puts [string map /\ $p {rr/nrzmrann xrrr snnimrrrcnn vrrr wnnromrenrru}]}

```

Ok, here some explaination:

* `while 1 {...}` \- Ok, forget the explaination.
* `regsub -all \ +|. "oaosocowoeouooovoioxozom r n\n" \ {&} p` replaces `+|.` with `_{\0}` and stores the result in `p`. `p` is actually a messed up dictionary where the first key is missing (or just a list with an odd number of elements).
* `lset p [set h [expr $h%12*2]] h` sets the hour in the replacement list
* `lset p [set m [expr $m/5*2]] [expr $h-$m?"m":"x"]` sets the minute. if hour and minute is the same, use `x` instead.
* `string map /\ $p {rr/nrzmrann xrrr snnimrrrcnn vrrr wnnromrenrru}` `/\ $p` is equal to `"/ $p"`, so I add the first key (`/`). After that I replace every occurence of a key in `rr/nrzmrann xrrr snnimrrrcnn vrrr wnnromrenrru` with it's value.

The usual map is

```
/ o a o s o c o w o e o u o o o v o i o x o z o m {   } r {    } n {
}

```

(Read as "Replace `/` with `o`, replace `a` with `o`... replace `m` with `___` (that should be spaces))

I repace an `o` with `h` and an other with `m`, `m`, `r` and `n` are just to shoren the output string (I replaced several spaces with one of them, also `\n` with `n`). I add the first element later so I can use h\*2 instead h\*2+1 for the index that I replace. (saves 2 chars)

Some notes:

* A list in Tcl uses whitespace as delimiter, if an element contains whilespace, you have to enclose it with `{}`. Ok, it's a little bit more complex e.g. you could escape the whitespace with a `\`, but such details are documented somewhere else.
* A dict in Tcl is just a list with an even number of elements: `key1 value1 key2 value2`
* You can treat a list as string or a string as list. Will work if the string is a valid list. Free serialization!
> 2 votes

# Answer
### Javascript 2169 - 434 = 1735

Ok, it's a lot, but they are fine and work same as my previous variant in previous posts (bash and perl).

This version is *more obfuscated* than the one you may find on my ascii-clock for geeks

```
var x='<div class="m"> M</div>',v='<div class="s"> s</div>',w=' '
,r=10,q,w=' ',y='<div class="h"> H</div>',f=new Object();function d(){
q=document.getElementById("asciiclock");var t=document.location.toString().match
(/[?]([0-9]+)/);if (t!=null) r=t[1]*1.0;a();b();}function m(e){r=e;a();}function
a(){f=[];for (var i=1;r>i;i++){var u=Math.round(Math.sqrt(Math.pow(r,2)-Math.pow
(r-i,2)));f[(2*r-i)+"x"+(r+u)]=w+".";f[(i)+"x"+(r+u)]=w+".";f[(2*r-i)+"x"+(r-u)]
=w+".";f[(i)+"x"+(r-u)]=w+".";f[(r+u)+"x"+(2*r-i)]=w+".";f[(r+u)+"x"+(i)]=w+".";
f[(r-u)+"x"+(2*r-i)]=w+".";f[(r-u)+"x"+(i)]=w+".";}for(var i=1;13>i;i++){f[Math.
round(r+r*Math.sin(Math.PI/6*i-Math.PI/2))+"x"+Math.round(r+r*Math.cos(Math.PI/6
*i-Math.PI/2))]='<div class="t">'+(i<10?w+i:i)+'</div>';}}function b(){var z='';
var s=new Date(), o=s.getMinutes()*1.0+1.0*s.getSeconds()/60,p=s.getHours()*1.0+
1.0*o/60,n=s.getSeconds()*1.0,k=s.getHours();if (k<10) k=w+k;var j=s.getMinutes(
);if (j<10) j=w+j;var h=s.getSeconds();if (h<10)h=w+h;var g=new Object();for(var
i=1;r*.78>=i;i++) {g[Math.round(r+i*Math.sin (Math.PI/30*o-Math.PI/2))+"x"+Math.
round(r+i*Math.cos(Math.PI/30*o-Math.PI/2))]=x;};for (var i=1;r*.62 >=i;i++) {g[
Math.round(r+i*Math.sin(Math.PI/6*p-Math.PI/2))+"x"+Math.round(r+i*Math.cos(Math
.PI/6*p-Math.PI/2))]=y;};g[Math.round(r+.87*r*Math.sin(Math.PI/30*n-Math.PI/2))+
"x"+Math.round(r+.87*r*Math.cos(Math.PI/30*n-Math.PI/2))]=v;for (var i=0;2*r>=i;
i++){for(var l=0;2*r>=l;l++){if((i==r)&&(l==i)){z+=w+'<div class="t">'+['.','+',
'*','o','O'][n%5]+'</div>';}else if(f[i+"x"+l]!=undefined){z+=f[i+"x"+l]}else if
(g[i+"x"+l]!=undefined){z+=g[i+"x"+l];}else if(l==2*r){if(i==0){z+=w+'<div clas'
+'s="t">'+k+'</div>';}else if(i==l){z+=w+'<div class="t">'+h+'</div>';}else{z+=w
+w;};}else if(l==0){if(i==2*r){z+='<div class="t">'+j+'</div>';}else if(i==0){z=
'<div class="r">S</div>'+w;}else{z+=w+w}}else{z+=w+w}};z+='<br />';};q.innerHTML
=z;window.setTimeout(b,1000-new Date().getMilliseconds());};function c(){window.
setTimeout(b,0);q.innerHTML=w+q.innerHTML.substring (22);q.setAttribute('style',
'display:none');q.setAttribute('style',null)};window.onload=d;
```

```
.asciiclock { margin: 3em 0px 0px 0px;padding: 2px 4px 2px 3px; font-size: .5em;
display:inline-block;font-family:mono,monospace,courier;background:rgba(0,0,0,.7
);color: #888;}.asciiclock div{ display:inline-block;font-weight:bold;}.h{color:
#46F;}.m{color:#0F0;}.s{color:#0FF;}.r{color:#000;background:#aaa;}.t{color:#aaa
;}pre{display:inline-block;}
```

```
<head><title>Ascii-clock</title><script type="text/javascript" src="ascii-clock.js"
></script><link rel="stylesheet" href="ascii-clock.css" type="text/css"><style
type="text/css">body{margin:0;padding:0;background:#000;}.asciiclock{margin:0}
</style></head><body><div id="asciiclock" class="asciiclock"></div></body>
```
> 2 votes

# Answer
# Ruby: ~~230~~ 228 characters - 46 = 182

```
M=Math
P=M::PI
x=->n,m=60,r,c{$><<"^[[%d;%dH%s\n"%[M.sin(n*P*2/m-P/2)*r+12,M.cos(n*P*2/m-P/2)*r*2+24,c]}
while t=Time.now
$><<"^[[2J"
1.upto(12){|i|x[i,12,11,i]}
x[t.hour*5+t.min/12,8,?H]
x[t.min,9,?M]
x[t.sec,10,?S]
sleep 0.1
end

```

(Note: `^[` is a single character.)

Sample run (at 21:19:33):

```
                      12
           11                     1

   10                                     2

       H
 9                                           3

                                       M

   8                                      4

            7   S                 5

                       6

```

## “As ugly as you wish” version: ~~191~~ 181 characters - 36 = 145

(Smaller size, lower precision, no seconds, identical radius, horrible flickering.)

```
x=->n,m=60,c{$><<"^[[%d;%dH%s\n"%[Math.sin(n*6.3/m-1.6)*8+9,Math.cos(n*6.3/m-1.6)*8+9,c]}
while t=Time.now
$><<"^[[2J"
1.upto(12){|i|x[i,12,i]}
x[t.hour*5+t.min/12,?H]
x[t.min,?M]
end

```

Sample run (at 21:19):

```
       12  1
   11

              2
 10

H              3
9

               M
 8

            5
    7   6

```

## Trigonometry-less version: ~~130~~ 125 characters (no bonus)

(Inspired by Johannes Kuhn's Tcl solution. Not sure how much, as I still not deciphered his code.)

```
while t=Time.now
puts"^[[2J  k l a
j\tb
i\tc
h\td
  g f e".tr((t.min/5+96).chr,?M).tr(((t.hour-1)%12+97).chr,?H).tr("a-l",?*)
end

```

Sample run (at 21:19):

```
  * * *
*       *
H       M
*       *
  * * *

```
> 1 votes

# Answer
## Python, 259 - 52 = 207

```
from time import*
from math import*
g=[[' ']*61 for _ in[0]*31]
while 1:
 t=localtime()
 for x in range(60):a=pi*x/30-pi/2;g[15+int(15*sin(a))][30+int(30*cos(a))]='m'if x==t.tm_min else'h'if x==t.tm_hour%12*5 else'-'if x%5 else'#'
 for r in g:print''.join(r)

```

Sample output:

```
                              #
                     -  -  -     -  -  -
                  -                       -
             -  h                           #  -
          -                                       -
        -                                           -

      m                                               -
     #                                                 #
   -                                                     -

  -                                                       -
 -                                                         -

 -                                                         -
#                                                           #
 -                                                         -

 -                                                         -
  -                                                       -

   -                                                     -
     #                                                 #
      -                                               -

        -                                           -
          -                                       -
             -  #                           #  -
                  -                       -
                     -  -  -     -  -  -
                              #

```
> 1 votes

# Answer
# HTML & JS: `397 - 20% = 317.6 characters`

My first iteration. I'm not very pleased with it, but it does work and it does show the time in a very clear way.

```
<canvas id=c width=198 height=198></canvas><script>c=document.getElementById("c")
.getContext("2d");c.r=c.rotate;c.c=c.clearRect;c.translate(99,99);for(i=0;i<60;i++)
{c.fillRect(89,-1,i%5?3:9,5);c.r(p=Math.PI/30);}setInterval(function(){n=new Date();
h=n.getHours()*5*p;c.beginPath();c.arc(0,0,86,0,7);c.fill();c.r(m=n.getMinutes()*p);
c.c(-2,-3,4,-80);c.r(h-m);c.c(-2,-3,4,-50);c.r(-h);},5);</script>

```
> 0 votes

# Answer
## Ti-Basic 84, 587 - 20% = 469.6

```
:Xmax/2→Xmax:Ymax/2→Ymax:-Xmax→Xmin:-Ymax→Ymin:Degree:15→H:20→M:18→S::Circle(0,0,30):For(X,1,12)::Text(28-int(cos(X*30)*25),46+int(sin(30*X)*25),X):End:{0,0,0}→LANG:While getKey=0::getTime→LTIME::If LTIME(3)≠LANG(3)/6:Line(0,0,sin(LANG(3))*S,cos(LANG(3))*S,0)::If LTIME(2)≠LANG(2)/6:Then:::Line(0,0,sin(LANG(2))*M,cos(LANG(2))*M,0):::Line(0,0,sin(LANG(1))*H,cos(LANG(1))*H,0)::End::"SET ANGS::LTIME(1)*30+LTIME(2)/2→LANG(1)::LTIME(2)*6→LANG(2)::LTIME(3)*6→LANG(3)::Line(0,0,sin(LANG(1))*H,cos(LANG(1))*H::Line(0,0,sin(LANG(2))*M,cos(LANG(2))*M::Line(0,0,sin(LANG(3))*S,cos(LANG(3))*S:End

```

Its output is very pretty and detailed.
> 0 votes

# Answer
C, 554 Bytes, Updates roughly once per second.

```
#include <time.h>
#include <math.h>
int r=25,i,q,c,i,q,b[999];void v(float a,int f,int m){b[(r/2+(int)(sin(a)*f))*r+r/2+(int)(cos(a)*f)]=m;}void main(){float a,p=6.28,z=1.57,h,m,s;for(;;){time_t u=time(0);struct tm*l=localtime(&u);s=l->tm_sec;m=l->tm_min+s/60.;h=l->tm_hour+m/60.;system("@cls||clear");q=r*r;c=r/2;memset(b,32,q*4);for(i=0,a=p;a>0;a-=0.52,i++)v(a,c,i%3?46:i%6?124:45);v(0,0,79);v(p*s/60.-z,c-4,83);v(p*m/60.-z,c-5,77);v(p*h/12.-z,c-6,72);for(i=0;i<q;i++){c=b[i];putchar(c);if(i%r==r-1)putchar(10);}for(c=0;c<2000000;c++)hypot(3,.4);}}

```

Result:

```
           |
      .          .

 .
                S    .

       H

-          O          -

                M
 .
                     .

     .          .
           |

```
> 0 votes

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