# Question
Title: Format microseconds as hours:minutes:seconds, etc
The following is inspired by a question that came up on Stack Overflow today.

Given a number of microseconds, `0 <= n <= 86400000000` (e.g. `12345678900`), output a formatted string `hh:mm:ss:000:000`, e.g. `03:25:45:678:900`.

```
          0 -> '00:00:00:000:000'
12345678900 -> '03:25:45:678:900'
86400000000 -> '24:00:00:000:000'

```

I have a solution in Python in 209 bytes, but can it go lower?

# Answer
> 15 votes
# Python 2, ~~82~~ 79 bytes

```
n=input()
o=""
for k in[1000]*2+[60]*3:o=":%0*d"%(k%7/2,n%k)+o;n/=k
print o[1:]

```

Builds the string, iterating through a series of divmods. The only fancy bit is the `%7/2`, which maps `1000 -> 3` and `60 -> 2`.

# Answer
> 6 votes
# Pyth, 31 bytes

```
j\:_m>l`td+"00"%~/QddCM"ϨϨ<<<

```

Try it online: Demonstration

### Explanation:

```
                                 implicit: Q = input number
                       "ϨϨ<<<   string "ϨϨ<<<" (5 chars but 7 bytes)
                     CM          convert each to number => [1000, 1000, 60, 60, 60]
    m                            map each number d to:
                 /Qd                divide Q by d
                ~                   and update Q with the new value
               %~ Q d               but use the old value to calculate Q mod d
          +"00"                     add the result to the string "00"
     >                              but only take the last
      l`td                          len(str(d-1)) chars
   _                             revert order
j\:                              join the strings with ":"s

```

# Answer
> 5 votes
# Bash + coreutils, 61

Shortest "mainstream" language so far...

```
a=%02d:
printf $a$a$a%03d:%03d `dc -e$1\ A00~rA00~r60~r60~rf`

```

### Test output:

```
$ for t in 0 12345678900 86400000000; do ./usec.sh $t; echo; done
00:00:00:000:000
03:25:45:678:900
24:00:00:000:000
$

```

# Answer
> 4 votes
# CJam, ~~37 35~~ 34 bytes

This is prettty long .. Golfing now..

```
ri[1e3_60__]{:ImdsIBb,0e[':@}%W%2>

```

*UPDATE: 1 byte saved thanks to @Sp3000*

Try it online here

# Answer
> 4 votes
# q (34)

I'm sure it can be shorter

```
":"sv 0 8 11__[;8]15$2_($)16h$1e3*

```

e.g.

```
q)f:":"sv 0 8 11__[;8]15$2_($)16h$1e3*
q)f 12345678900
"03:25:45:678:900"

```

# Answer
> 4 votes
# C, 97 bytes

```
q=1000,s=60;
#define f(n)printf("%02d:%02d:%02d:%03d:%03d",n/s/s/q/q,n/s/q/q%s,n/q/q%s,n/q%q,n%q)

```

Test Code:

```
int main(int intc, char **argv)
{
    long long n = atoll(argv[1]);
    f(n);
}

```

# Answer
> 3 votes
# C#, ~~179~~ 175 Bytes

When you have builtins at your disposal, why not use 'em?

```
static void Main(string[]a){var t=TimeSpan.FromTicks(long.Parse(Console.ReadLine())*10);Console.Write(t.ToString((t.Days<1?"hh":@"\2\4")+@"\:mm\:ss\:ffffff").Insert(12,":"));}

```

With better formatting:

```
static void Main(string[]a){
    var t = TimeSpan.FromTicks(long.Parse(Console.ReadLine())*10);
    Console.Write(t.ToString((t.Days<1?"hh":@"\2\4")+@"\:mm\:ss\:ffffff").Insert(12,":"));
    Console.Read();
}

```

# Answer
> 3 votes
# Julia, ~~110~~ ~~96~~ 95 bytes

```
t->(o="";for i=int([36e8,6e7,1e6,1e3,1]) x,t=t÷i,t%i;o*=lpad(x,i>1e3?2:3,0)*":"end;o[1:end-1])

```

This creates an unnamed function that accepts an integer as input and returns a string. To call it, give it a name, e.g. `f=t->...`.

Ungolfed + explanation:

```
function f(t)
    # Initialize an output string
    o = ""

    # Loop over an array consisting of the number of microseconds in
    # an hour, minute, second, millisecond, and microsecond
    for i = int([36e8, 6e7, 1e6, 1e3, 1])

        # Get the quotient and remainder for microseconds into t,
        # setting t to be the remainder
        x, t = t ÷ i, t % i

        # Left-pad x with zeroes and append it to the output
        o *= lpad(x, i > 1e3 ? 2 : 3, 0) * ":"
    end

    # o has a trailing :, so return everything but the last character
    o[1:end-1]
end

```

Examples:

```
julia> f(12345678900)
"03:25:45:678:900"

julia> f(0)
"00:00:00:000:000"

julia> f(86400000000)
"24:00:00:000:000"

```

# Answer
> 3 votes
## Excel, 65 63 characters

Assuming your microseconds is in **A1**:

```
=TEXT(A1/50/1200^3,"[HH]:mm:ss:")&RIGHT(TEXT(A1,"000\:000"),7)

```

Output:

```
        A              B
1            0  00:00:00:000:000
2  12345678900  03:25:46:678:900
3  86400000000  24:00:00:000:000

```

# Answer
> 2 votes
# Perl, ~~141~~ 78 bytes

```
printf"%02d"x3.%03d:%03d",$_/36e8,$_/6e7%60,$_/1e6%60,$_/1e3%1e3,$_%1e3

```

77 bytes of code, +1 for the `-n` flag. Run with:

```
echo 12345678900 | perl -ne'printf"%02d"x3.%03d:%03d",$_/36e8,$_/6e7%60,$_/1e6%60,$_/1e3%1e3,$_%1e3'

```

Thanks to Thomas Kwa and chilemagic for cutting my code size nearly in half.

# Answer
> 1 votes
## JavaScript (ES6), ~~128~~ ~~118~~ ~~116~~ 111 bytes

There is probably some golfing potential in this.

```
f=t=>(t<864e8?new Date(t/1e3).toJSON().slice(11,-1):`24:00:00:000`).replace(`.`,`:`)+':'+('00'+t%1e3).slice(-3)

```

### Demo

It is ES6 so Firefox only, for now anyways:

```
f=t=>(t<864e8?new Date(t/1e3).toJSON().slice(11,-1):`24:00:00:000`).replace(`.`,`:`)+':'+('00'+t%1e3).slice(-3)

// DEMO
document.body.innerHTML += '<br>' + f(0);
document.body.innerHTML += '<br>' + f(12345678020);
document.body.innerHTML += '<br>' + f(86400000000);
```

# Answer
> 1 votes
## CoffeeScript, 127 bytes

Took the approach in ASCIIThenANSI's answer. It's too bad that the JavaScript Console API doesn't have format placeholders for padding numbers.

```
p=(a,b)->('00'+~~a).slice -b||-2
f=(t)->console.log '%s:%s:%s:%s:%s',p(t/36e8),p(t/6e7%60),p(t/1e6%60),p(t/1e3%1e3,3),p t%1e3,3

```

# Answer
> 1 votes
## Matlab - 88 ~~89~~ bytes

Gained one byte with a solution without using the built in function:

```
n=[36e8,6e7,1e6,1e3];f=@(t)sprintf('%02d:%02d:%02d:%03d:%03d',fix([t mod(t,n)]./[n 1]))

```

Create an inline function which takes a numeric input argument `t` and return a string.

it uses a vectorized combination of `fix` and `mod` to separate the time elements, then display.

it's a bit frustrating that the formatting of the output string takes so much, more than the calculations themselves ...

Test:

```
for t=[0 12345678900 86400000000]
    f(t)
end

ans =
00:00:00:000:000
ans =
03:25:45:678:900
ans =
24:00:00:000:000

```

---

89 bytes version:

```
f=@(t)sprintf('%s:%03d:%03d',datestr(fix(t/1e6)/86400,13),fix(mod(t,1e6)/1e3),mod(t,1e3))

```

It splits the number, uses a built-in function for the hh:mm:ss part, which cannot deal with microseconds so the string is completed with combination of `fix` and `mod` operations

# Answer
> 1 votes
# C, ~~113~~ ~~103~~ 105 bytes

*EDIT: shoved off some more bytes*

*FIX: removed long type, thanks to some user*

Not the shortest C answer, but I had some fun with carriage returns so I felt like someone might like this.

```
i,k,p=16;
#define f(n)for(;i<5;p-=i++<2?4:3)k=i<2?1000:60,printf("%0*d%c\r",p,n%k,i?58:13),n/=k;puts("");

```

Call it like:

```
int main() {
    long long n = 12345678900;
    f(n);

    return 0;
}

```

# Answer
> 1 votes
## Powershell,153

```
$t=[timespan]::FromTicks(($a=$args[0]));"{0:D2}:{1:D2}:{2:D2}:{3:D3}:{4:000}"-f
[int]($t.TotalHours),$t.Minutes,$t.Seconds,$t.Milliseconds,(($a%1e4)/10)

```

## Usage

```
powershell -nologo .\modprintsec.ps1 123456789000
03:25:45:678:900
powershell -nologo .\modprintsec.ps1 864000000000
24:00:00:000:000
powershell -nologo .\modprintsec.ps1 0
00:00:00:000:000

```

# Answer
> 1 votes
## F#, 111 92 102 bytes

First iteration: Base idea.

Second iteration: Smaller constants

Third iteration: Correct formatting for single digit portions.

Note this function must be given an int64 to work.

```
let s,t=60L,1000L
let f n=sprintf"%02d:%02d:%02d:%03d:%03d"(n/s/s/t/t)(n/s/t/t%s)(n/t/t%s)(n/t%t)(n%t)

```

Example outputs:

```
f 0L           -> "00:00:00:000:000"
f 12345678900L -> "03:25:45:678:900"
f 86400000000L -> "24:00:00:000:000"

```

# Answer
> 0 votes
# PHP - 115 102 bytes

A solution in 155 bytes (wrapped here on 3 lines for readability):

```
$a=$argv[1];
$h=($a-($m=($a=($a-($s=($a=($a-($t=($a=($a-($u=$a%1000))/1000)%1000))/1000)%60))/60)%60))/60;
printf("%02d:%02d:%02d:%03d:%03d",$h,$m,$s,$t,$u);

```

The second line computes (from inside to outside) the exact values of the components starting with the microseconds.

## The shorter version (115 bytes, wrapped on two lines for readability):

```
$u=$argv[1];$h=($m=($s=($t=$u/1000)/1000)/60)/60;
printf("%02d:%02d:%02d:%03d:%03d",$h,$m%60,$s%60,$t%1000,$u%1000);

```

It also uses embedded assignments to compute the convert the input number of microseconds in milliseconds, seconds, minutes and hours using floating point numbers. The modulus operator (`%`) and the decimal number format (`%d`) of `printf()` is then used to force them to integer numbers (the fractional part is ignored).

## Another solution that uses the date functions (102 bytes)

```
$u=$argv[1];
echo gmdate("H:i:s",strtotime("@".substr($u,0,-6))),":",substr($u,-6,3),":",substr($u,-3);

```

The hours:minutes:seconds part is handled by the PHP date functions `gmdate()` and `strtotime()`, the milli- and micro-seconds are extracted as strings from the input value.

### Usage:

```
$ php -r '$u=$argv[1];echo gmdate("H:i:s",strtotime("@".substr($u,0,-6))),":",substr($u,-6,3),":",substr($u,-3);' 7198898787; echo
01:59:58:898:787

```

# Answer
> 0 votes
## Java, 215 bytes

```
String f(long n){return p(n/3600000000l,2)+":"+p(n/60000000%60,2)+":"+p(n/1000000%60,2)+":"+p(n/1000%1000,3)+":"+p(n%1000,3);}String p(long n,int i){String s=String.valueOf(n);while(s.length()<i){s="0"+s;}return s;}

```

Method `f` does some calculations on `n` to work out the hours, minutes etc. and delegates to method `p` to format each value correctly.

**Formatted:**

```
String f(long n) {
    return p(n / 3600000000l, 2) + ":" + p(n / 60000000 % 60, 2) + ":"
            + p(n / 1000000 % 60, 2) + ":" + p(n / 1000 % 1000, 3) + ":" + p(n % 1000, 3);
}

String p(long n, int i) {
    String s = String.valueOf(n);
    while (s.length() < i) {
        s = "0" + s;
    }
    return s;
}

```

**Usage:**

```
public void demo() {
    long n = 12345678900l;
    System.out.println(f(n));
}

```

# Answer
> -1 votes
# Ruby - 82 Bytes

```
puts (t=Time.at(0,gets.to_i)).strftime("%2H:%2M:%2S:%3L:#{(t.usec%1000).to_s.rjust(3,?0)}")

```

---
Tags: code-golf, date
---


# Question
Title: Generate MathJax for the Golden Ratio Continued Fraction
**In anticipation of MathJax being temporarily disabled, the rendered MathJax in this question has been replaced with images. You are still welcome to post answers but you'll have to view the rendered MathJax on another site.**

PPCG just got MathJax! This means we can now easily include well formatted mathematical formulas into posts. (Handy MathJax tutorial.)

For example, here is the golden ratio expressed as an infinite continued fraction:

The MathJax code for this equation is

```
$$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}}$$
```

You can find this by right clicking the formula and following *Show Math As**TeX Commands*.
The `$$` means it is displayed on its own in the center of the page instead of inline. Use a single `$` for inline.

# Challenge

Write a program that takes in a non-negative integer, n, and outputs the MathJax code for that many "steps" of the continued fraction for the golden ratio.

**To keep things standard across answers, you must use this *exact* MathJax syntax:**

* For n = 0, the output must be `$$\varphi=1+\dots$$`.
Which is rendered as:
* For n = 1, the output must be `$$\varphi=1+\cfrac1{1+\ddots}$$`.
Which is rendered as:
* For n = 2, the output must be `$$\varphi=1+\cfrac1{1+\cfrac1{1+\ddots}}$$`.
Which is rendered as:
* For n = 3, the output must be `$$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}$$`.
Which is rendered as:

This pattern continues on for larger n. You could say that n represents the number of division lines in the equation.

### Notes

* `\cfrac` is used instead of the more common `\frac`.
* `\dots` is used instead of `\ddots` for n = 0.
* Take input from stdin or the command line.
* Output to stdout (with an optional trailing newline).
* Alternatively, you may write a function that takes in n as an integer and returns the MathJax code as a string (or still prints it).

# Scoring

The smallest submission in bytes wins. Tiebreaker goes to the earlier submission.

# Answer
# CJam, ~~51~~ 50 bytes

```
$$\varphi=1+""\cfrac1{1+"ri:R*'\"ddots"R!>'}R*'$_

```

Code explanation:

```
"$$\varphi=1+"             "This is a static string";
  "\cfrac1{1+"ri:R*'\      "Repeat this string input number times. Put a \ at the end";
    "ddots"R!>             "If input is 0, remove 1st characters, else not";
      '}R*                 "Put the closing bracket R times";
        '$_                "The final $$";

```

Few examples:

N = 0

```
$$\varphi=1+\dots$$

```

---

N = 4

```
$$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}}$$

```

---

N = 15

```
$$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}}}}}}}}}}}}}$$

```

*UPDATE* \- 1 byte saved thanks to Sp3000!

Try it online here
> 6 votes

# Answer
# Python, ~~70~~ ~~68~~ 67 bytes

```
lambda n:"$$\\varphi=1+\%sdots%s$$"%("cfrac1{1+\\"*n+"d"[:n],"}"*n)

```

This defines an anonymous function which just uses simple string multiplication and string formatting.

*(Thanks to @xnor for pointing out that `\\c` can just be written as `\c`, since `c` can't be escaped. Unfortunately this doesn't hold true for `\\v`, since `\v` is ASCII 11.)*

**Previous attempts:**

```
lambda n:"$$\\varphi="+"1+\\cfrac1{"*n+"1+\\"+"ddots"[n<1:]+"}"*n+"$$"
lambda n:r"$$\varphi=%s1+\%s$$"%("1+\cfrac1{"*n,"ddots"[n<1:]+"}"*n)

```
> 10 votes

# Answer
# Julia, ~~76~~ 73 bytes

```
n->("\$\$\\varphi=1+"*"\\cfrac1{1+"^n*"\\"*"d"^(n>0)*"dots"*"}"^n*"\$\$")

```

This creates a lambda function that takes a single integer as input and returns the MathJax as a string. To call it, give it a name, e.g. `f=n->...`.

Unfortunately both backslashes and dollar signs have to be escaped in Julia strings because they both have special meaning. String concatenation is performed using `*` and string repetition with `^`.

Examples:

```
julia> f(0)
"$$\varphi=1+\dots$$"

julia> f(4)
"$$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}}$$"

```

Suggestions are welcome as always!

---

**Edit:** Saved 3 bytes thanks to plannapus!
> 4 votes

# Answer
# \>\<\>, ~~89~~ 86 + 3 = 89 bytes

```
:&"$$"{\l?!;o70.
}-1v!?:<{"}"
&:&\~"stod"&:&?:
{1->:?!v}"\+1{1carfc"
rav\$$"\~"\+1=ihp

```

Run with the `-v` flag, e.g.

```
py -3 fish.py program.fish -v 3

```

Surprisingly \>\<\> doesn't do too badly here, since we can mimic string multiplication by having a counter which we decrement every iteration.

```
:&"$$"{\                     Put n into the register and push "$$"
}-1v!?:<{"}"                 Push n "}"s
&:&\~"stod"&:&?:             Push "stod", and copy the final "d" if n != 0
{1->:?!v}"\+1{1carfc"        Push n "\+1{1carfc"s
rav\$$"\~"\+1=ihp            Push "\+1=ihprav\$$"
       \l?!;o70.             Keep printing chars until the stack is empty

```

*(-3 bytes thanks to @randomra)*
> 4 votes

# Answer
# Retina, 160 + 7 = 167 bytes

```
;`.+
$$$$\varphi=1+\dots#$0$$$$

```

;+`(\d*)#(?:(((((((((9)|8)|7)|6)|5)|4)|3)|2)|1)|0)
$1$1$1$1$1$1$1$1$1$1$2$3$4$5$6$7$8$9$10#
 ;`#

```
;+`\\d?dots\d(\d*)
\cfrac1{1+\ddots$1}

```

Each line goes into a separate source file, so I've added 1 byte for each file after the first. However, for convenience, Retina now also supports the `-s` command-line flag, which allows you to put all of this into a single file (in which case the newlines are treated as file separators).

The largest part of the code (98 bytes) is used to convert the input from decimal to unary (files 3 to 6). The basic idea of the code is to surround the input in `$$\varphi=1+\dots...$$`, then convert the input to unary, and then expand `\dotsN` or `\ddotsN` to the next level of the continued fraction (while reducing `N` to `N-1`).
> 4 votes

# Answer
# T-SQL, ~~229~~ ~~227~~ 138

Been a while since I did an SQL answer and as always it's very verbose. **Edit** Of course I over complicated it and didn't need a recursive query at all.

```
CREATE FUNCTION A(@ INT)RETURNS TABLE RETURN SELECT'$$\varphi=1+\'+REPLICATE('cfrac1{1+\',@)+IIF(@>0,'d','')+'dots'+REPLICATE('}',@)+'$$'S

```

Original

```
CREATE FUNCTION A(@ INT)RETURNS TABLE RETURN WITH R AS(SELECT CAST('$$\varphi=1+\dots'AS VARCHAR(MAX))S,0N UNION ALL SELECT REPLACE(STUFF(S,14,0,'cfrac1{1+\'),'\do','\ddo')+'}',N+1FROM R WHERE N<=@)SELECT S+'$$'S FROM R WHERE N=@

```

This creates an inline table function that uses a recursive query to stuff in the additional `cfrac1{1+\` per iteration. Changing the dots to ddots was expensive, but saved a couple getting rid of the replace :). Also having to cast the original string as 'VARCHAR(MAX)' cost a bit.

It's used as follows SQLFiddle:

```
SELECT *
FROM (SELECT N FROM(VALUES(0),(1),(2),(3),(4),(5))A(N)) N
    CROSS APPLY A(N.N)
N   S
--- ---------------------------------------------------------------------------
0   $$\varphi=1+\dots$$
1   $$\varphi=1+\cfrac1{1+\ddots}$$
2   $$\varphi=1+\cfrac1{1+\cfrac1{1+\ddots}}$$
3   $$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}$$
4   $$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}}$$
5   $$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}}}$$

```
> 3 votes

# Answer
# Element, 63 Chars

```
_+2:'\$\$\\varphi\=1\+`[\\cfrac1\{1\+`]?\\[d.]`"dots`[\}`]\$\$`

```

This is the most straight-forward solution. Unfortunately, the large amount of symbols in the output causes a significant increase in program length (putting the strings in the program directly causes the symbols to perform operations). I'm sure there is room for golfing, but I don't have more time right now.

Since this language is still relatively unknown, here is a link to the interpreter, written in Perl.

```
_+2:                     take input, add 0 to it to make it a number, and duplicate
'                        put one copy onto the control stack
\$\$\\varphi\=1\+        a "bare" string
`                        output the string
[                        start a for loop, based on the input from earlier
    \\cfrac1\{1\+        a bare string
    `                    output it
]                        end the for loop
?                        test the second copy of the input for non-zero-ness
\\                       a bare \
[d.]                     a "for" loop used as an if block, appends a "d"
`                        output it
dots`                    output dots
"                        get rid of the if condition result so the old result is on top
[                        another for loop, still using the input from earlier
    \}`                  output a }
]                        end for loop
\$\$`                    output $$

```
> 3 votes

# Answer
# Ruby, ~~76~~ ~~75~~ ~~71~~ 70 bytes

This feels suspiciously straightforward, so please let me know if I messed up somewhere.

Incidentally, this is the first thing I've ever written in Ruby - I was looking for a language that supported string repetition by multiplying, and Ruby seemed to do the trick.

```
f=proc{|n|'$$\varphi=1+'+'\cfrac1{1+'*n+'\dd'[0,n+2]+'ots'+'}'*n+'$$'}

```

To be applied like so:

```
f.call(0)
$$\varphi=1+\dots$$

f.call(3)
$$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}$$

```
> 3 votes

# Answer
# R, ~~93~~ 90

Much the same as the other answers. Thanks to @plannapus for the scan tip.

```
cat('$$\\varphi=1+\\',rep('cfrac1{1+\\',n<-scan()),if(n)'d','dots',rep('}',n),'$$',sep='')

```

`cat` used rather than paste0 as the result would end up with `\\` rather than `\`.

In use

```
> > cat('$$\\varphi=1+\\',rep('cfrac1{1+\\',n<-scan()),if(n)'d','dots',rep('}',n),'$$',sep='')
1: 3
2:
Read 1 item
$$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}$$

```
> 2 votes

# Answer
# J, 60 bytes

```
(<;._2'$$\varphi=1+\ cfrac1{1+\ d dots } $$ ');@#~1,~5$1,],*

```

Usage:

```
   ((<;._2'$$\varphi=1+\ cfrac1{1+\ d dots } $$ ');@#~1,~5$1,],*) 0
$$\varphi=1+\dots$$

   ((<;._2'$$\varphi=1+\ cfrac1{1+\ d dots } $$ ');@#~1,~5$1,],*) 3
$$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}$$

```

Method:

The string `'$$\varphi=1+\ cfrac1{1+\ d dots } $$ '` is cut up at spaces and the parts are repeated `1 n signum(n) 1 n 1` times and then these parts are concatenated.

Try it online here.
> 2 votes

# Answer
# JavaScript, ~~114~~ ~~109~~ ~~106~~ 85 bytes thanks to George Reith

```
f=n=>'$$\\varphi=1+\\'+((x='cfrac1{1+\\'.repeat(n))&&x+'d')+'dots'+'}'.repeat(n)+'$$'

```

This is my first entry in a codegolf contest! Please tell me how to improve.

Previous entry (106 bytes):

```
w="$$\\varphi=";y=n=>{return a=!n?w+"1+\\dots$$":w+"1+\\cfrac1{".repeat(n)+"1+\\ddots"+"}".repeat(n)+"$$"}

```

Previous entry (109 bytes):

```
x="repeat",w="$$\\varphi=";y=n=>{return a=!n?w+"1+\\dots$$":w+"1+\\cfrac1{"[x](n)+"1+\\ddots"+"}"[x](n)+"$$"}

```

Previous entry (114 bytes):

```
x="repeat";y=n=>{return a=!n?"$$\\varphi=1+\\dots$$":"$$\\varphi="+"1+\\cfrac1{"[x](n)+"1+\\ddots"+"}"[x](n)+"$$"}

```

Paste into browser console and call as `f(n)` where `n` is the number of 'steps'.

**Simplified code**:

```
function y(n) {
   if(n === 0) {
      return "$$\\varphi=1+\\dots$$";
   } else {
      return "$$\\varphi=" + "1+\\cfrac1{".repeat(n) + "1+\\ddots"+"}".repeat(n)+"$$";
   }

```
> 2 votes

# Answer
# Pyth - 52 bytes

The simple approach in Pyth, pretty much stolen from @Sp3000's Python solution. Uses string formatting operator `%`.

```
%"$$\\varphi=1+\%sdots%s$$"(+*"cfrac1{1+\\"Q<\dQ*\}Q

```

Try it online here.

```
%                  String formatting
 "$$ . . . $$"     String to be formatted
 (                 Tuple (no need to close it)
  +                String concatenation
   *"..."Q         String repetition input times
   <\dQ            If Q>0 then d
  *                String repetition
   \}              The character "}"
   Q               Q times

```
> 1 votes

# Answer
# Pyth, 50 bytes

```
s["$$\\varphi=1+"*Q"\cfrac1{1+"\\<\dQ"dots"*Q\}"$$

```
> 1 votes

# Answer
# JavaScript (ES6), 76 ~~80~~

Partly recursive. The single/double d is most annoying part.

```
F=n=>"$$\\varphi=1+\\"+(R=d=>n--?"cfrac1{1+\\"+R("d")+"}":d+"dots")("")+"$$"

```

**Test** In Firefox /FireBug console

```
> for(i=0;i<5;i++)console.log(F(i))

$$\varphi=1+\dots$$
$$\varphi=1+\cfrac1{1+\ddots}$$
$$\varphi=1+\cfrac1{1+\cfrac1{1+\ddots}}$$
$$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}$$
$$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}}$$

```
> 1 votes

# Answer
# Python, ~~90~~ 116

since the most efficient solution has already been posted multiple times, i go with string replacement instead

```
f=lambda n:'$$\\varphi=1+\ddots$$'if n==0 else f(n-1).replace('\ddots','\cfrac{1+\ddots}')
# or, with exactly the same length
x='\ddots';f=lambda n:'$$\\varphi=1+'x+'$$'if n==0 else f(n-1).replace(x,'\cfrac{1+'x+'}')

```

Edit: damn, overlooked the `dots` instead of `ddots` for `n=0`, now the recursive solution with an extra clause tacked on is too ugly to compete.

```
x='$$\\varphi=1+\d%sots$$';f=lambda n:x%''if n==0 else x%'d'if n==1 else f(n-1).replace('\ddots','\cfrac{1+\ddots}')

```
> 0 votes

# Answer
# Haskell, 86

```
n%x=[1..n]>>x
f n="$$\\varphi=1+"++n%"\\cfrac1{1+"++'\\':drop(0^n)"ddots"++n%"}"++"$$"

```

Essentially the same approach as all solutions here. `drop(0^n)"ddots"` is cute, though!
> 0 votes

---
Tags: code-golf, math, kolmogorov-complexity
---


title: Roll my D&D character's ability scores

text:
# Question
Title: Roll my D&D character's ability scores
In Dungeons and Dragons, some of the most important atributes of a character are the ability scores. There are 6 ability scores, for the six abilities. The abilities are Strength, Dexterity, Constitution, Intelligence, Wisdom and Charisma.

When determining the scores for a character, I use the following procedure: Roll 4d6, drop the lowest, in any order. What this means is that I roll 4 six sided dice, ignore the lowest result, and sum the other 3. This is done 6 times. The resulting numbers are assigned to the abilities in any way I please.

The system I use for assigning scores to abilities is to assign the highest score to my character's most important skill, which depends on my character's class, assign the second highest score to Constitution, since everyone needs Constitution, and assign the other four scores arbitrarily.

Here's a table of the most important skills for various classes:

```
Bard - Charisma
Cleric - Wisdom
Druid - Wisdom
Fighter - Stregth
Monk - Wisdom
Paladin - Charisma
Rogue - Dexterity
Sorcerer - Charisma
Wizard - Intelligence

```

**Challenge:** I'll give you (as input) the first letter of my character's class (In uppercase). I'd like you to roll the abilities scores and assign them to the abilities as described above, and then output them in the order Strength, Dexterity, Constitution, Intelligence, Wisdom, Charisma.

**Example:**

```
Input: R
Rolls: 4316 3455 3633 5443 2341 6122
Scores: 13 14 12 13 9 10
Ordering: Highest goes to dexterity. Second goes to Constitution.
Output: 13 14 13 12 9 10
or
Output: 9 14 13 10 12 13
or etc.

```

Output may be given in any format where the numbers are clearly separated and in the proper order.

Shortest code in bytes wins. Standard loopholes banned.

# Answer
# CJam, ~~43~~ ~~41~~ 40 bytes

```
{6a4*:mr$0Zt:+}6*]$2m<"FRXWCDM"r#4e<3e\p

```

*Thanks to @Sp3000 for golfing off 1 byte.*

Try it online in the CJam interpreter.

### How it works

```
{             }6*                       e# Repeat 6 times:
 6a4*                                   e#   Push [6 6 6 6].
     :mr                                e#   Replace each six with a pseudo-randomly
                                        e#   generated integer in [0 ... 5].
        $                               e#   Sort the results.
         0Zt                            e#   Replace the lowest result by 3.
            :+                          e#   Add all four integers
                ]                       e# Wrap the 6 generated integers in an array.
                 $                      e# Sort.
                  2m<                   e# Rotate 2 units to the left to assign the
                                        e# second highest result to Constitution.
                     "FRXWCDM"          e# Push that string.
                              r#        e# Find the index of the input.
                                        e# The string doesn't contain B, P or S, so
                                        e# those push -1.
                                4e<     e# Truncate the index at 4. This way, C, D
                                        e# M all push 4.
                                   3e\  e# Swap the integer at that index with the
                                        e# one at index 3, i.e., the highest one.
                                      p e# Print.

```
> 5 votes

# Answer
# Python 3, 137 bytes

```
from random import*
S=sorted
*L,c,h=S(3+sum(S(map(randrange,[6]*4))[1:])for _ in[0]*6)
L[:"FRW BPS".find(input())]+=h,
L[:2]+=c,
print(L)

```

Outputs a list of integers, e.g. `[14, 9, 13, 12, 12, 13]` for `F`.

The mapping from the input char to assignments turned out to be surprisingly nice. First we start by having `L` contain the lowest 4 rolls, after which we want to insert

* The highest roll into the correct position based on the input, then
* The second-highest roll into index 2, for Constitution.

For each input, the indices we want for the highest rolls are:

```
Index    Ability          Input(s)
----------------------------------
0        Strength         F
1        Dexterity        R
2        Intelligence     W
3        Wisdom           CDM
4        Charisma         BPS

```

Amazingly, we only need `"FRW BPS".find(input())` for this, because:

* `FRW` work as expected, giving their respective indices,
* `CDM` are not present so `find` gives `-1`, which for a 4-element list is index 3, and
* `BPS` give 4, 5, 6 respectively, but it doesn't matter if we overshoot because we can only append an element at the end.
> 6 votes

# Answer
# J, ~~100~~ 97 bytes

```
(0;0,b)C.^:(b>0)(0;1 2)C.\:~+/"1]1}."1/:~"1]1+?6 4$4$6[b=.('BCDFMPRSW'i.1!:1[1){5 4 4 0 4 5 1 5 3

```

Takes input in `STDIN`
> 1 votes

# Answer
# C++ - 387 bytes

First attempt here, more golfing required, particularly in determining what class is being used.

Golfed:

```
#include<cstdlib>
#include<cstdio>
#include<time.h>
int main(int c,char**v){char*o=*v,l=*v[1];int b=-1,s=-1,i=6,x=0,q=l>=67&&l<=68||l==77?4:l==70?0:l==87?3:l==82?1:5;srand(time(0));for(;i-->0;){int w=9,d=4,u=3,t;for(;d-->0;){t=rand()%6;if(t<w){u+=w<9?w:0;w=t;}else u+=t;}if(u>s){c=s;s=u;u=c;}if(s>b){c=s;s=b;b=c;}if(u>=0)o[x++]=u;}for(i=0;i<6;i++)printf("%d ",i==2?s:(i==q?b:o[--x]));}

```

Rather ungolfed:

```
#include<cstdlib>
#include<cstdio>
#include<time.h>
int main(int c,char**v)
{
    //name of program must be at least 4 chars
    char*others=*v,clas=*v[1];
    int desired = clas>=67&&clas<=68||clas==77?4:clas==70?0:clas==87?3:clas==82?1:5; //TODO:

    srand(time(0));
    int best=-1,second=-1,i=6,otherIndex=0;
    for(;i-->0;)
    {
        int lowest=9,diecount=4,sum=3;
        for(;diecount-->0;)
        {
            int loc=rand()%6;
            if (loc<lowest)
            {
                sum+=lowest<9?lowest:0;
                lowest=loc;
            }
            else
            {
                sum+=loc;
            }
        }
        if(sum>second)
        {
            c=second;second=sum;sum=c;
        }
        if(second>best)
        {
            c=second;second=best;best=c;
        }
        if(sum>=0)
        {
            others[otherIndex++]=sum;
        }
    }

    for(i=0;i<6;i++)
    {
        printf("%d ",i==2?second:(i==desired?best:others[--otherIndex]));
    }

    getchar();
}

```
> 0 votes

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


title: 40 Numbers in 9 Bytes

text:
# Question
Title: 40 Numbers in 9 Bytes
There are 40 ways a directed Hamiltonian path can be arranged on a 3×3 grid:
This graphic (thanks Sp3000!) shows only the 20 undirected paths. Traverse each colored line in both directions for the 40 directed paths.

# Challenge

Using only printable ASCII, write a 3×3 grid of characters, such as:

```
ABC
DEF
GHI

```

When each of the 40 directed paths are read from this grid as 40 single-line, 9-character programs, the goal is to have each program output a unique integer from 1 to 40. Doing this for *all* 40 paths seems difficult and unlikely, so you only need to make it work for as many paths as you can.

**The submission whose 40 path-programs output the most distinct numbers from 1 to 40 will be the winner. Tiebreaker goes to the earlier submission.**

Path-programs that error or do not output an integer from 1 to 40 or output an integer that another path-program already covered are not counted. Specifically:

* Programs that error while compiling, running, or exiting are not counted. Warnings are ok.
* Programs that don't output an integer from 1 to 40 or output something slightly malformed such as `-35` or `35 36` are not counted.
* Programs that require user input to produce the output are not counted.
* Programs that never end are not counted.
* From now on, programs that aren't deterministic aren't counted.
* Otherwise valid programs that output an integer from 1 to 40 that another valid program has already output are not counted. (The first program *is* counted.)
* Only programs that output integer representations of numbers from 1 to 40 (inclusive) are counted towards your total. The numbers are expected to be in the usual `1`, `2`, ..., `39`, `40` format, unless that is not the norm for your language. (A trailing newline in the output is fine.)
* Which numbers your programs output and what order they are in does not matter. Only the number of distinct integers from valid programs matters.

**All path-programs must be run in the same language.** However, the "programs" may in fact be functions (with no required arguments) or REPL commands, as well as full programs, that print or return their target integer. You may mix and match between functions, REPL commands, and full programs.

Your 9 printable ASCII characters do not need to be distinct.

# Example

If your 3×3 grid were

```
ABC
DEF
GHI

```

and your 40 programs and outputs looked like this

```
ABCFEDGHI -> 26
ABCFIHEDG -> 90
ABCFIHGDE -> 2
ABEDGHIFC -> syntax error
ADEBCFIHG -> prints 40 but then errors
ADGHEBCFI -> 6
ADGHIFCBE -> 6
ADGHIFEBC -> 6
CBADEFIHG -> runtime error
CBADGHEFI -> 3
CBADGHIFE -> 4
CFEBADGHI -> -32
CFIHEBADG -> 38.0
CFIHGDABE -> "36"
EDABCFIHG -> 33
EFCBADGHI -> no output
EHGDABCFI -> compilation error
EHIFCBADG -> 8
GDABCFEHI -> 22
GHEDABCFI -> 41
IHGDEFCBA -> 0
GDEHIFCBA -> '9'
EDGHIFCBA -> +10
CFIHGDEBA -> 11
GHIFCBEDA -> error
IFCBEHGDA -> error
EBCFIHGDA -> prints 23 but then loops infinitely
CBEFIHGDA -> randomly prints either 24 or 44
GHIFEDABC -> error
IFEHGDABC -> 30
EFIHGDABC -> 39
IHGDABEFC -> 7
GDABEHIFC -> 29
EBADGHIFC -> -1
GHIFCBADE -> 26
IHGDABCFE -> 1
IFCBADGHE -> error
GDABCFIHE -> no output
IHEFCBADG -> no output
IFCBADEHG -> "quack"

```

your score would be 14, because there are 14 distinct integers from 1 to 40 validly output, namely `26 2 6 3 4 33 8 22 11 30 39 7 29 1`.

# Answer
> 27 votes
## PARI/GP - 24

```
1%1
 8
2+3

```

PARI/GP ignores spaces between digits, so that `1 8 2`, for example is treated as `182`. The same could work for perl by replacing the spaces with underscores. I haven't exhausted the entire search space, so there may be better candidates.

A program can be fed to gp as `gp -q -f program.gp`, or interactively in the repl.

---

**Output**

```
1%1 8 2+3 -> 4
1%1 3+8 2 -> 83 # invalid
1%1 3+2 8 -> 29
1%8 2+3 1 -> 32
1 8%1 3+2 -> 7
1 2+8%1 3 -> 20
1 2+3 1%8 -> 19
1 2+3 8%1 -> 12
1%1 8 3+2 -> 3
1%1 2+8 3 -> 84 # invalid
1%1 2+3 8 -> 39
1 8%1 2+3 -> 9
1 3+8%1 2 -> 21
1 3+2 1%8 -> 18
8 1%1 3+2 -> 5
8 1%1 2+3 -> 12 # dup
8+2 1%1 3 -> 16
8+3 1%1 2 -> 15
2 1%1 8+3 -> 6
2+8 1%1 3 -> 5  # dup
3+2 8 1%1 -> 3  # dup
2 8+3 1%1 -> 28
8 2+3 1%1 -> 82 # invalid
1 3+2 8%1 -> 13
2+3 1%8 1 -> 33
3 1%8+2 1 -> 28 # dup
8%1 3+2 1 -> 29 # dup
1%8 3+2 1 -> 22
2+3 8 1%1 -> 2
3 8+2 1%1 -> 38
8 3+2 1%1 -> 83 # invalid
3+2 1%8 1 -> 24
2 1%8+3 1 -> 36
8%1 2+3 1 -> 39 # dup
2+3 1%1 8 -> 15 # dup
3+2 1%1 8 -> 6  # dup
3 1%1 2+8 -> 15 # dup
2 1%1 3+8 -> 16 # dup
3+8 1%1 2 -> 12 # dup
3 1%1 8+2 -> 15 # dup

```

All but 4 values are within the required range, with 12 duplicate entries.

---

**Update**

I've finished crunching, there are six distinct 23s, and only one 24 (as read by rows):

```
23 1%1 6 2+3 [2, 3, 4, 5, 7, 8, 11, 12, 13, 14, 16, 17, 18, 19, 22, 24, 26, 27, 32, 33, 34, 36, 37]
23 1 2%3+2*8 [2, 5, 7, 8, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 22, 23, 25, 26, 29, 31, 32, 37, 40]
23 2 3%1+8 2 [2, 4, 6, 7, 10, 11, 12, 13, 14, 15, 16, 20, 21, 23, 24, 28, 29, 30, 31, 32, 33, 34, 40]
23 4%6%5*7+6 [2, 4, 5, 6, 7, 8, 9, 12, 13, 19, 21, 23, 24, 26, 29, 31, 32, 33, 34, 37, 38, 39, 40]
23 5%6%4*7+6 [2, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 16, 18, 25, 26, 29, 31, 33, 34, 37, 38, 39, 40]
23 5%6%4*8+6 [1, 3, 5, 6, 8, 9, 10, 12, 14, 15, 18, 22, 24, 25, 27, 29, 30, 32, 34, 36, 37, 39, 40]

24 1%1 8 2+3 [2, 3, 4, 5, 6, 7, 9, 12, 13, 15, 16, 18, 19, 20, 21, 22, 24, 28, 29, 32, 33, 36, 38, 39]

```

The program I used for crunching is below. PARI/GP has limited string processing capabilities, so deal mainly with char arrays (a.k.a. `Vecsmall`). The operators tested are `+`, `-`, `*`, `\` (floor div), `%`, `;` (expression separator, essentially discards everything before it), and  (space, as described above). The exponent operator `^` could also be added, but it becomes too slow to test exhaustively.

```
perms = {[
  [1, 2, 3, 6, 5, 4, 7, 8, 9], [1, 2, 3, 6, 9, 8, 5, 4, 7], [1, 2, 3, 6, 9, 8, 7, 4, 5], [1, 2, 5, 4, 7, 8, 9, 6, 3],
  [1, 4, 5, 2, 3, 6, 9, 8, 7], [1, 4, 7, 8, 5, 2, 3, 6, 9], [1, 4, 7, 8, 9, 6, 3, 2, 5], [1, 4, 7, 8, 9, 6, 5, 2, 3],
  [3, 2, 1, 4, 5, 6, 9, 8, 7], [3, 2, 1, 4, 7, 8, 5, 6, 9], [3, 2, 1, 4, 7, 8, 9, 6, 5], [3, 6, 5, 2, 1, 4, 7, 8, 9],
  [3, 6, 9, 8, 5, 2, 1, 4, 7], [3, 6, 9, 8, 7, 4, 1, 2, 5], [5, 4, 1, 2, 3, 6, 9, 8, 7], [5, 6, 3, 2, 1, 4, 7, 8, 9],
  [5, 8, 7, 4, 1, 2, 3, 6, 9], [5, 8, 9, 6, 3, 2, 1, 4, 7], [7, 4, 1, 2, 3, 6, 5, 8, 9], [7, 8, 5, 4, 1, 2, 3, 6, 9],
  [9, 8, 7, 4, 5, 6, 3, 2, 1], [7, 4, 5, 8, 9, 6, 3, 2, 1], [5, 4, 7, 8, 9, 6, 3, 2, 1], [3, 6, 9, 8, 7, 4, 5, 2, 1],
  [7, 8, 9, 6, 3, 2, 5, 4, 1], [9, 6, 3, 2, 5, 8, 7, 4, 1], [5, 2, 3, 6, 9, 8, 7, 4, 1], [3, 2, 5, 6, 9, 8, 7, 4, 1],
  [7, 8, 9, 6, 5, 4, 1, 2, 3], [9, 6, 5, 8, 7, 4, 1, 2, 3], [5, 6, 9, 8, 7, 4, 1, 2, 3], [9, 8, 7, 4, 1, 2, 5, 6, 3],
  [7, 4, 1, 2, 5, 8, 9, 6, 3], [5, 2, 1, 4, 7, 8, 9, 6, 3], [7, 8, 9, 6, 3, 2, 1, 4, 5], [9, 8, 7, 4, 1, 2, 3, 6, 5],
  [9, 6, 3, 2, 1, 4, 7, 8, 5], [7, 4, 1, 2, 3, 6, 9, 8, 5], [9, 8, 5, 6, 3, 2, 1, 4, 7], [9, 6, 3, 2, 1, 4, 5, 8, 7]
]}

ops = Vecsmall("+-*\\%; ")

ms = 1

for(c = 48, 57, {
 for(d = c, 57,
  for(f = d, 57,
   for(g = c, 57,
    for(e = 48, 57,
     print1(Strchr([c,d,e,f,g,13]));
     for(h = 1, #ops,
      for(i = 1, #ops,
       for(j = 1, #ops,
        for(k = 1, #ops,
         a = Vecsmall([c, ops[h], d, ops[i], e, ops[j], f, ops[k], g]);
         s = Set();
         for(m = 1, #perms,
          v = Strchr(vecextract(a, perms[m]));
          iferr(b = eval(v), E, b = 0);
          if(b >= 1 && b <= 40, s = setunion(s, [b]))
         );
         if(#s >= ms, ms = min(23, #s); print(#s, " ", Strchr(a), " ", s));
        )
       )
      )
     )
    )
   )
  )
 )
})

```

# Answer
> 29 votes
# Deadfish, 18

This was actually the first language I tried before I considered infix operators. I'm posting it now for the sheer hilarity of the idea that Deadfish could be useful for something.

```
iii
ios
sii

```

For those who don't know Deadfish, `i` is increment, `s` is square and `o` is output, with the accumulator starting at 0 (there's also a 4th instruction `d` for decrement not used here). The fact that we don't have automatic printing and need to use `o` is a major drawback, but surprisingly Deadfish doesn't do too terribly here, all things considered. It turns out that the optimal placement of the output operator is in the middle.

```
iiisoisii 9
iiisiiois 11
iiisiisio 122
iioisiisi 2
iioiisiis 2
iisioiisi 5
iisiisiio 38
iisiisoii 36
iiiiosiis 4
iiiisiosi 17
iiiisiiso 324
isoiiisii 1
isiioiiis 3
isiisiiio 12
oiiiisiis 0
osiiiisii 0
oisiiiisi 0
oiisiiiis 0
siiiisoii 16
sioiiiisi 1
iisiosiii 5
sioiisiii 1
oisiisiii 0
isiisioii 10
siisiioii 6
isiioisii 3
oiisiisii 0
iiosiisii 2
siisoiiii 4
isoisiiii 1
osiisiiii 0
iisiiiosi 7
siiioiisi 3
oiiisiisi 0
siisiiiio 8
iisiiiiso 64
isiiiisio 26
siiiisiio 18
iiosiiiis 2
isiiiiois 5

```

# Answer
> 25 votes
# Python REPL and many more, ~~22~~ 23

```
6+7
*5%
6%4

```

Key observation: If you colour the grid like a checkerboard, the path alternates grid colours as it goes and starts and ends on the same colour.

~~Still brute forcing for better.~~ Trying with `+*%` (and even `**` for languages where `^` is exponentiation) didn't turn up anything better, unfortunately. I also tried throwing in bitwise operators and only `^` (xor) seemed to mildly help, but the search was taking too long so I've given up.

```
6+7%5*6%4 6
6+7%4%5*6 24
6+7%4%6*5 21
6+5*6%4%7 8
6*5+7%4%6 33
6*6%5+7%4 4
6*6%4%7+5 5
6*6%4%5+7 7
7+6*5%4%6 9
7+6*6%5%4 8
7+6*6%4%5 7
7%5+6*6%4 2
7%4%5+6*6 39
7%4%6*6+5 23
5*6+7%4%6 33
5%7+6*6%4 5
5%6*6+7%4 33
5%4%7+6*6 37
6*6+7%5%4 38
6%5*6+7%4 9
4%6*5%7+6 12
6*5%4%7+6 8
5*6%4%7+6 8
7%4%6*5+6 21
6%4%7+5*6 32
4%7+5%6*6 34
5+7%4%6*6 23
7+5%4%6*6 13
6%4%5*6+7 19
4%5%6*6+7 31
5%4%6*6+7 13
4%6*6+5%7 29
6*6+5%4%7 37
5+6*6%4%7 5
6%4%7+6*5 32
4%6*6+7%5 26
4%7+6*6%5 5
6*6+7%4%5 39
4%5%7+6*6 40
4%7+6*5%6 4

```

# Answer
> 13 votes
# J, 15

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

```

This outputs only valid numbers, but a lot are duplicates. The unique values are `17 11 16 28 31 23 13 10 21 33 18 24 22 29 27`. You can definitely do better by changing operators and the integers involved.

```
2+1*3*2+3 -> 17
2+1*3+3*2 -> 11
2+1*3+2*3 -> 11
2+3*2+3*1 -> 17
2*3+1*3+2 -> 16
2*2+3+1*3 -> 16
2*2+3*1+3 -> 28
2*2+3*3+1 -> 28
1+2*3*3+2 -> 31
1+2*2+3*3 -> 23
1+2*2+3*3 -> 23
1*3+2*2+3 -> 13
1*3+3+2*2 -> 10
1*3+2*2+3 -> 13
3*2+1*3+2 -> 21
3*1+2*2+3 -> 33
3+2*2+1*3 -> 13
3+3*1+2*2 -> 18
2*2+1*3+3 -> 16
2+3*2+1*3 -> 17
3+2*3*1+2 -> 21
2*3+3*1+2 -> 24
3*2+3*1+2 -> 33
1*3+2*3+2 -> 13
2+3*1+3*2 -> 23
3*1+3+2*2 -> 24
3+1*3+2*2 -> 10
1+3*3+2*2 -> 22
2+3*3*2+1 -> 29
3*3+2*2+1 -> 27
3*3+2*2+1 -> 27
3+2*2+3*1 -> 13
2*2+3+3*1 -> 16
3+2*2+3*1 -> 13
2+3*1+2*3 -> 23
3+2*2+1*3 -> 13
3*1+2*2+3 -> 33
2*2+1*3+3 -> 16
3+3*1+2*2 -> 18
3*1+2*3+2 -> 33

```

# Answer
> 11 votes
## \>\<\>, 36\*

*If you're lucky enough!*

```
x;x
lxl
xnx

```

~~Since the challenge does not require the code to be deterministic we only have to prove that it is possible (even if improbable) to return 36 numbers and we are done.~~ It was good while it lasted I guess.

(For those not familiar with \>\<\>, a great intro on can be found here)

> \>\<\> is a stack-based 2D language. This means that instructions aren't executed linearly like most traditional languages — program flow can be up, down, left or right!

I decided to use the "x" instruction in \>\<\>, which changes the instruction pointers direction to either up, down, left or right at random. Since our code will only be one line, that means that we can only look at the cases when it goes right or left, since if the pointer goes up or down, it will just hit the "x" instruction again.

The "n" instruction pops the number at the top of the stack and prints it. However if the stack is empty and there is nothing to pop, an error is raised.

The "l" instruction simply pushes the length of the stack onto the stack (and lucky for us it does not send an error if the stack is empty), so for example if the stack were empty and "l" would be called, it would push 0 onto the stack. If we would now again call "l", then since the stack has one element (0), it would push 1 to the top of the stack and now that would mean that there would be two things on the stack and that would mean that if we were to call "l" again, we would push 2 onto the stack etc. So we can use "l" to push an arbitrary number onto the stack via the method shown earlier.

The ";" instruction ends the program.

The idea with using "x" is that, for example if there was only one "x" in the code (where A,B,C,D are some instructions):

```
ABCx;D

```

The program would execute A then B then C, and upon reaching "x" we would have two possibilites: the code either continues to go right and hits the ";" and exits or it goes left and executes C then B then A then D and only then exits. So if our code contained one "x", the program gains two possible program flows from which we may choose the most suited program.

I there are two or more "x"es then we gain an infinite number of possible program flows.

Our code has five "x"es, futhermore each of them is in a "starting cell" of the Hamiltonian paths, which means every single program will start with an "x", and every program will have the structure:

```
xAxBxCxDx

```

Where A, B, C, D belong to { ; , n, l, l} This means that there are only 12 unique programs. Furthermore since we always start on an "x", we may look at the case when the program goes left, thus symmetric programs can also be regarded the same. Up to symmetry there are only 6 different posible programs. Only 4 of them occur in the programs generated as hamiltonian paths:

```
xnxlxlx;x
xlxnxlx;x
xnxlx;xlx
xlxnx;xlx

```

Let us look at the first program "xnxlxlx;x" if we go right at the first step we hit the print command which will raise an error since we have nothing on the stack. If we go left we hit the end program command. So we **cannot output any number** from these programs.

The second program, "xlxnxlx;x", is a lot more hopeful, since upon going right at the begining a zero is put on the stack, if we then go left at the next "x", our stack gains a one, then going right again we have a 2 that we can then print and continue going right to end the program. We can observe that we can actually print **any even number**, since in the "xlx" part at the beginning we can reach a number of arbitrary size by going right then left then right again a certain number of times.

Similiarly it can be seen that the third program xnxlx;xlx can output **any odd number**, by going left at the beginning and then repeating the "xlx" routine only this time going left then right then left.

And the fourth program is essentially the same as the second program and can output **any even number**.

So for the required programs we have:

```
x;xlxlxnx (none)
x;xlxnxlx (any even number)
x;xlxnxlx (any even number)
x;xlxnxlx (any even number)
xlx;xlxnx (any odd number)
xlxnx;xlx (any even number)
xlxnxlx;x (any even number)
xlxnxlx;x (any even number)
x;xlxlxnx (none)
x;xlxnxlx (any even number)
x;xlxnxlx (any even number)
xlx;xlxnx (any odd number)
xlxnx;xlx (any even number)
xlxnxlx;x (any even number)
xlx;xlxnx (any odd number)
xlx;xlxnx (any odd number)
xnxlx;xlx (any odd number)
xnxlx;xlx (any odd number)
xlx;xlxnx (any odd number)
xnxlx;xlx (any odd number)
xnxlxlx;x (none)
xlxnxlx;x (any even number)
xlxnxlx;x (any even number)
xlxnxlx;x (any even number)
xnxlx;xlx (any odd number)
xlx;xnxlx (any even number)
x;xlxnxlx (any even number)
x;xlxnxlx (any even number)
xnxlxlx;x (none)
xlxnxlx;x (any even number)
xlxnxlx;x (any even number)
xnxlx;xlx (any odd number)
xlx;xnxlx (any even number)
x;xlxnxlx (any even number)
xnxlx;xlx (any odd number)
xnxlx;xlx (any odd number)
xlx;xlxnx (any odd number)
xlx;xlxnx (any odd number)
xnxlx;xlx (any odd number)
xlx;xlxnx (any odd number)

```

That's 4 programs that cant output numbers, 20 that can output any even number, 16 that can output any odd number. Since there are exactly 20 even numbers and at least 16 odd numbers in the range 1 to 40, then with a certain probability there exists a possibility that there would be 36 different numbers in the range 1 to 40 output by this code block.

# Answer
> 9 votes
# GolfScript, 8

```
192
6#7
281

```

~~Currently the highest scoring solution. :P~~ Was nice while it lasted.

### Programs

```
1927#6281 1927
192718#62 192718
19271826# 19271826
19#628172 19
16#927182 16
1628#9271 1628
16281729# 16281729
162817#92 162817
2916#7182 2916
291628#71 291628
29162817# 29162817
27#916281 27
2718#9162 2718
27182619# 27182619
#61927182
#72916281
#82619271
#81729162
261927#81 261927
28#619271 28
1826#7291 1826
26#817291 26
#62817291
271826#91 271826
281729#61 281729
1729#8261 1729
#92718261
29#718261 29
2817#6192 2817
17#826192 17
#71826192
182619#72 182619
2619#8172 2619
#91628172
28172916# 28172916
18261927# 18261927
17291628# 17291628
26192718# 26192718
18#729162 18
172916#82 172916

```

# Answer
> 8 votes
## CJam, 14

```
3(4
;];
0)1

```

Below the working programs:

```
3(4;];0)1 = 11
3(4;1)0;] = 22
3(];0)1;4 = 14
3;0)](4;1 = 11
3;0)1;4(] = 13
3;0)1;](4 = 14
4(3;];1)0 = 20
4(3;0)];1 = 1
4(3;0)1;] = 31
4;1)](3;0 = 20
4;1)0;3(] = 22
0;3(4;])1 = 21
0)];3(4;1 = 21
1)0;];4(3 = 33
4;1)0;](3 = 23
0)1;4(];3 = 3
1;4(])0;3 = 33
4(];1)0;3 = 23
0)1;];3(4 = 24
1)0;3(];4 = 4
0;3(])1;4 = 24
0)1;4(3;] = 13
1)0;3(4;] = 22
1;4(3;0)] = 31
0;3(4;1)] = 22
1)];4(3;0 = 30
1;4(3;])0 = 30

```

The values generated are: \[1, 3, 4, 11, 13, 14, 20, 21, 22, 23, 24, 30, 31, 33\]

# Answer
> 5 votes
# dc (20)

```
2+3
*p+
4+5

```

```
ABCFEDGHI -> 2+3+p*4+5 -> 5     $ **
ABCFIHEDG -> 2+3+5+p*4 -> 10    $ **
ABCFIHGDE -> 2+3+5+4*p -> 40    $ **
ABEDGHIFC -> 2+p*4+5+3 -> 2     $ **
ADEBCFIHG -> 2*p+3+5+4 -> 2       **
ADGHEBCFI -> 2*4+p+3+5 -> 6     $ **
ADGHIFCBE -> 2*4+5+3+p -> 14    $ **
ADGHIFEBC -> 2*4+5+p+3 -> 11    $ **
CBADEFIHG -> 3+2*p+5+4 -> 6       **
CBADGHEFI -> 3+2*4+p+5 -> 10      **
CBADGHIFE -> 3+2*4+5+p -> 15    $ **
CFEBADGHI -> 3+p+2*4+5 -> 3     $ **
CFIHEBADG -> 3+5+p+2*4 -> 8     $ **
CFIHGDABE -> 3+5+4*2+p -> 34    $ **
EDABCFIHG -> p*2+3+5+4 ->
EFCBADGHI -> p+3+2*4+5 ->
EHGDABCFI -> p+4*2+3+5 ->
EHIFCBADG -> p+5+3+2*4 ->
GDABCFEHI -> 4*2+3+p+5 -> 9     $ **
GHEDABCFI -> 4+p*2+3+5 -> 4     $ **
IHGDEFCBA -> 5+4*p+3+2 -> 20    $ **
GDEHIFCBA -> 4*p+5+3+2 -> 4       **
EDGHIFCBA -> p*4+5+3+2 ->
CFIHGDEBA -> 3+5+4*p+2 -> 32    $ **
GHIFCBEDA -> 4+5+3+p*2 -> 12    $ **
IFCBEHGDA -> 5+3+p+4*2 -> 8       **
EBCFIHGDA -> p+3+5+4*2 ->
CBEFIHGDA -> 3+p+5+4*2 -> 3       **
GHIFEDABC -> 4+5+p*2+3 -> 9       **
IFEHGDABC -> 5+p+4*2+3 -> 5       **
EFIHGDABC -> p+5+4*2+3 ->
IHGDABEFC -> 5+4*2+p+3 -> 22    $ **
GDABEHIFC -> 4*2+p+5+3 -> 6       **
EBADGHIFC -> p+2*4+5+3 ->
GHIFCBADE -> 4+5+3+2*p -> 24    $ **
IHGDABCFE -> 5+4*2+3+p -> 25    $ **
IFCBADGHE -> 5+3+2*4+p -> 20      **
GDABCFIHE -> 4*2+3+5+p -> 14      **
IHEFCBADG -> 5+p+3+2*4 -> 5       **
IFCBADEHG -> 5+3+2*p+4 -> 16    $ **

```

32 outputs, 20 of them distinct (marked with a `$`)

2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 14, 15, 16, 20, 22, 24, 25, 32, 34, 40

---
Tags: code-challenge, grid, graph-theory, source-layout, printable-ascii
---


# Question
Title: Create an interface that fits the XKCD Types
> colors.rgb("blue") yields "#0000FF". colors.rgb("yellowish blue") yields NaN. colors.sort() yields "rainbow"

Using the rules set out in the image and its title text (quoted here), create a program that accepts all the given input and displays the appropriate output.

* Input can be taken with stdin or nearest equivalent. There should be a line like `[n]>` on which to type it, and `n` increases by 1 each command. It should start at 1.
* The result should be displayed using stdout or nearest equivalent. There should be a `=>` on each line of output.

All 13 conditions, plus the 3 in the title (quoted) must work.

This is code golf, so shortest answer wins.

# Answer
> 20 votes
# Python 3, 700 698 697 689 683 639 611

Tabs as indentation.

```
from ast import*
E=literal_eval
O='=>%s\n'
P=print
I=int
def Q(a):P(O%a)
def W(a):Q('"%s"'%str(a))
def gb(a):W(_ if'y'in a else'#0000FF')
def t():W('rainbow')
def FLOOR(n):P(O%'|'*3+(O%'|{:_^10}').format(n))
def RANGE(*a):Q([('"','!',' ','!','"'),(1,4,3,4,5)][len(a)])
c=0
while 1:
    try:
        c+=1;A,*B=input('[%d]>'%c).split('+')
        if not A:W(c+I(B[0]))
        elif A=='""':Q("'\"+\"'")
        elif B:
            A=E(A);B=E(B[0])
            if A==B:Q('DONE')
            elif type(A)==list:Q(A[-1]==B-1)
            elif type(B)==list:W([I(A)])
            else:W(A+I(B))
        else:eval(A.lstrip('colrs.'))
    except:Q('Na'+['N','P','N.%s13'%('0'*13)][('-'in A)+len(B)])

```

*Since this uses a bare Except you can't Ctrl-C it. Ctrl-Z and kill %% work though*

Some of the conditions are generalized and others will only work with exact input.

1. `A+"B"` will work with any A and B not just when `A == B`
2. `"A"+[]` will work for any A that can be converted to an int (Includes hex and binary strings e.g 0xff and 0b01010)
3. `(A/0)` will work for any A, Eval Causes `DivideByZeroError` which is handled in the except
4. `(A/0)+B` will work with any A or B. `literal_eval` (E) raises an error.
5. `""+""` only works for the + sign. Anything else will print NaN, NaP or NaN.00...
6. `[A, B, C]+D` works by checking that `D == C+1` so will work for any length of list and any numbers.
7. ^^
8. `2/(2-(3/2+1/2))`, Anything that fails to parse that has `-` with a `+` somewhere after it will output NaN.000...13
9. `RANGE(" ")` Hardcoded
10. `+A` will work for any A. Ouputs `"current_line_number+A"`
11. `A+A` works for any A as long as they are the same and are bulitin python types
12. `RANGE(1,5)` Hardcoded.
13. `FLOOR(A)` works for any A.
14. `colors.rgb("blue")` The lstrip in eval turns this in `gb("blue")` which has a hardcoded response.
15. `colors.rgb("yellowish blue")` The lstrip in eval turns this in `gb("yellowish blue")` which attempts to use a non existent variable if `y` is present in the arguement causing an error which the except turns into NaN
16. `colors.sort()` The lstrip turns this into `t()` which has a hardcoded response.

*Brainsteel pointed out an error in my assumption for rule 10.*

# Answer
> 15 votes
# Python, 1110 bytes

Operator overloading isn't evil, right??

```
from re import*
class V(str):
 def __add__(s,r):return s[:-1]+chr(ord(s[-1])+r)
class S(str):
 def __str__(s):return "'"+s+"'"if '"'in s else'"'+s+'"'
 def __repr__(s):return str(s)
 def __add__(s,r):s=str(s)[1:-1];return S('['+s+']'if type(r)==L else '"+"' if(s,r)==('','')else s+r)
class I(int):
 def __add__(s,r):return type(r)(int(s)+int(r))if s!=r else V('DONE')
 def __div__(s,r):return N if r==0 else int(s)/int(r)
 def __pos__(s):return s+c*10
 def __mul__(s,r):return V('NaN.'+'0'*13+'13')if r==1 else int(s)*int(r)
class L(list):
 def __add__(s,r):return V(str(r==s[-1]+1).upper())
def RANGE(a,b=0):return 2*(a,S(chr(ord(a)+1)))if b==0 else tuple([a]+[b-1,a+2]*((b-a)/4)+[b-1,b])
def FLOOR(n):return V('|\n|\n|\n|___%s___'%n)
def colorsrgb(c):
 m={'blue':V('#0000FF')}
 return m.get(c,N)
def colorssort():return V('rainbow')
N=V('NaN')
c=1
while True:
 try:l=raw_input('[%d] >'%c)
 except:break
 l=sub(r'(?<!"|\.)(\d+)(?!\.|\d)',r'I(\1)',l)
 l=sub(r'"(.*?)"',r'S("\1")',l)
 l=sub(r'\[(.*?)\]',r'L([\1])',l)
 l=sub(r'/\(','*(',l)
 l=sub('s\.','s',l)
 for x in str(eval(l)).split('\n'):print ' =',x
 c+=1

```

My goal wasn't as much winning (obviously) as it is making it as generic as possible. Very little is hardcoded. Try stuff like `RANGE(10)`, `9*1`, and `RANGE("A")`, `(2/0)+14`, and `"123"` for fun results!

Here's a sample session:

```
ryan@DevPC-LX:~/golf/xktp$ python xktp.py
[1] >ryan@DevPC-LX:~/golf/xktp$ python xktp.py
[1] >1+1
 = DONE
[2] >2+"2"
 = "4"
[3] >"2"+2
Traceback (most recent call last):
  File "xktp.py", line 31, in <module>
    for x in str(eval(l)).split('\n'):print ' =',x
  File "<string>", line 1, in <module>
  File "xktp.py", line 7, in __add__
    def __add__(s,r):s=str(s)[1:-1];return S('['+s+']'if type(r)==L else '"+"' if(s,r)==('','')else s+r)
TypeError: cannot concatenate 'str' and 'I' objects
ryan@DevPC-LX:~/golf/xktp$ python xktp.py
[1] >ryan@DevPC-LX:~/golf/xktp$
ryan@DevPC-LX:~/golf/xktp$
ryan@DevPC-LX:~/golf/xktp$
ryan@DevPC-LX:~/golf/xktp$ python xktp.py
[1] >2+"2"
 = "4"
[2] >"2"+[]
 = "[2]"
[3] >"2"+[1, 2, 3]
 = "[2]"
[4] >(2/0)
 = NaN
[5] >(2/0)+2
 = NaP
[6] >(2/0)+14
 = Na\
[7] >""+""
 = '"+"'
[8] >[1,2,3]+2
 = FALSE
[9] >[1,2,3]+4
 = TRUE
[10] >[1,2,3,4,5,6,7]+9
 = FALSE
[11] >[1,2,3,4,5,6,7]+8
 = TRUE
[12] >2/(2-(3/2+1/2))
 = NaN.000000000000013
[13] >9*1
 = NaN.000000000000013
[14] >RANGE(" ")
 = (" ", "!", " ", "!")
[15] >RANGE("2")
 = ("2", "3", "2", "3")
[16] >RANGE(2)
Traceback (most recent call last):
  File "xktp.py", line 31, in <module>
    for x in str(eval(l)).split('\n'):print ' =',x
  File "<string>", line 1, in <module>
  File "xktp.py", line 15, in RANGE
    def RANGE(a,b=0):return 2*(a,S(chr(ord(a)+1)))if b==0 else tuple([a]+[b-1,a+2]*((b-a)/4)+[b-1,b])
TypeError: ord() expected string of length 1, but I found
ryan@DevPC-LX:~/golf/xktp$ python xktp.py
[1] >ryan@DevPC-LX:~/golf/xktp$ # oops
ryan@DevPC-LX:~/golf/xktp$ python xktp.py
[1] >RANGE("2")
 = ("2", "3", "2", "3")
[2] >RANGE(2*1)
Traceback (most recent call last):
  File "xktp.py", line 31, in <module>
    for x in str(eval(l)).split('\n'):print ' =',x
  File "<string>", line 1, in <module>
  File "xktp.py", line 15, in RANGE
    def RANGE(a,b=0):return 2*(a,S(chr(ord(a)+1)))if b==0 else tuple([a]+[b-1,a+2]*((b-a)/4)+[b-1,b])
TypeError: ord() expected a character, but string of length 19 found
ryan@DevPC-LX:~/golf/xktp$ python xktp.py # oops again
[1] >RANGE(1,20)
 = (1, 19, 3, 19, 3, 19, 3, 19, 3, 19, 20)
[2] >RANGE(1,5)
 = (1, 4, 3, 4, 5)
[3] >RANGE(10,20)
 = (10, 19, 12, 19, 12, 19, 20)
[4] >RANGE(10,200)
 = (10, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 12, 199, 200)
[5] >+2
 = 52
[6] >+"99"
Traceback (most recent call last):
  File "xktp.py", line 31, in <module>
    for x in str(eval(l)).split('\n'):print ' =',x
  File "<string>", line 1, in <module>
TypeError: bad operand type for unary +: 'S'
ryan@DevPC-LX:~/golf/xktp$ python xktp.py # oops again and again!
[1] >FLOOR(200)
 = |
 = |
 = |
 = |___200___
[2] >2+2
 = DONE
[3] >3+#
Traceback (most recent call last):
  File "xktp.py", line 31, in <module>
    for x in str(eval(l)).split('\n'):print ' =',x
  File "<string>", line 1
    I(3)+#
         ^
SyntaxError: unexpected EOF while parsing
ryan@DevPC-LX:~/golf/xktp$ python xktp.py
[1] >3+3
 = DONE
[2] >ryan@DevPC-LX:~/golf/xktp$

```

# Answer
> 6 votes
# C, 412 bytes

This is basically hardcoded, but all the other answers so far were missing something...

```
i;char b[99];main(){for(;;){printf("[%d]>",abs(++i));gets(b);i-=b[2]==50?26:0;printf("=>");puts(*b==82?b[6]==34?"('\"',\"!\",\" \",\"!\",'\"')":"(1,4,3,4,5)":*b==70?"|\n=>|\n=>|\n=>|___10.5___":*b==43?"12":*b==91?b[8]==50?"FALSE":"TRUE":*b==34?b[1]==34?"'\"+\"'":"\"[2]\"":*b==40?b[5]==43?"NaP":"NaN":*b==99?b[7]=='s'?"rainbow":b[12]==98?"#0000FF":"NaN":b[1]==43?b[2]==34?"\"4\"":"DONE":"NaN.000000000000013");}}

```

Output:

```
[1]>2+"2"
=>"4"
[2]>"2"+[]
=>"[2]"
[3]>(2/0)
=>NaN
[4]>(2/0)+2
=>NaP
[5]>""+""
=>'"+"'
[6]>[1,2,3]+2
=>FALSE
[7]>[1,2,3]+4
=>TRUE
[8]>2/(2-(3/2+1/2))
=>NaN.000000000000013
[9]>RANGE(" ")
=>('"',"!"," ","!",'"')
[10]>+2
=>12
[11]>2+2
=>DONE
[14]>RANGE(1,5)
=>(1,4,3,4,5)
[13]>FLOOR(10.5)
=>|
=>|
=>|
=>|___10.5___

```

# Answer
> 5 votes
## Python 3, 298

Everything is hardcoded, but the input is turned into a number that is then converted to a string and looked up in a large string that contains all these numbers followed by their answers.

```
B="""53"#0000FF"~62DONE~43NaN.000000000000013~25(1,4,3,4,5)~26"rainbow"~49"4"~21"[2]"~29FALSE~15|*|*|*|___10.5___~17'"+"'~1212~60('"',"!"," ","!",'"')~24NaN~31TRUE~64NaN~76NaP"""
i=0
while 1:i+=1;s=input("[%s]>"%i);print("=>"+B[B.find(str(sum(map(ord,s))%81))+2:].split("~")[0].replace("*","\n=>"))

```

# Answer
> 1 votes
# Python 3, 542 484 bytes

Since there was no mention of absolute hardcoding here's my solution.

```
a={'2+"2"':'"4"','"2"+[]':'"[2]"',"(2/0)":"NaN","(2/0)+2":"NaP",'""+""':"'\"+\"'","[1,2,3]+2":"FALSE","[1,2,3]+4":"TRUE","2/(2-(3/2+1/2))":"NaN.000000000000013",'RANGE(" ")':'(\'"\',"!"," ","!",\'"\')',"+2":"12","2+2":"DONE","RANGE(1,5)":"(1,4,3,4,5)","FLOOR(10.5)":"|\n|\n|\n|___10.5___",'colors.rgb("blue")':'"#0000FF"','colors.rgb("yellowish blue")':"NaN","colors.sort()":'"rainbow"'}
i=1
while 1:b=a[input("[%i]>"%i).replace("\t","")].split("\n");print("=> "+"\n=> ".join(b));i+=1

```

---
Tags: code-golf
---


# Question
Title: all non-empty sublists partitionings of a list
I had to write a code for finding all non-empty sublists partitionings of a list:

```
def f(s):
    if s:
        for j in range(1,len(s)+1):
            for p in f(s[j:]):
                yield [s[:j]]+p
    else:
        yield []

```

I managed to shorten it (for Python 3.4+) to:

```
def f(s, p=[]):
    if s:
        for j in range(1,len(s)+1):
            yield from f(s[j:],p+[s[:j]])
    else:
        yield p

```

using **yield from** and an accumulator argument `p` (prefix).

Any suggestions on how to shorten it even more?

Example output:

```
>>> for p in f([1,2,3,4]): print(p)
...
[[1], [2], [3], [4]]
[[1], [2], [3, 4]]
[[1], [2, 3], [4]]
[[1], [2, 3, 4]]
[[1, 2], [3], [4]]
[[1, 2], [3, 4]]
[[1, 2, 3], [4]]
[[1, 2, 3, 4]]
>>>

```

# Answer
> 3 votes
# 66 bytes

```
p=lambda l:[q+[l[i:]]for i in range(len(l))for q in p(l[:i])]or[l]

```

If the last part is changed from `[l]` to `[[]]`, then it can also be used with tuples or strings, in addition to lists.

---
Tags: code-golf, tips, python, set-partitions
---


title: Connecting Gaps with Tetris Pieces

text:
# Question
Title: Connecting Gaps with Tetris Pieces
You should write a program or function which given a list of tetris blocks as input outputs or returns the biggest gap between two points in the same height level which the pieces can connect.

The 7 types of tetris pieces are the following:

We will refer to these pieces by the letters I, J, L, O, S, T and Z respectively, referring to their shapes. You can rotate the pieces but cannot mirror them just like in a Tetris game.

Our task is to create an orthogonally connected area (sides connected to sides) from the given pieces. This area should connect (also orthogonally) two unit squares which are at the same height. We should find the biggest possible gap between the two squares which we can bridge.

## Detailed examples

With the piece L we can connect a gap of 3

```
   L
XLLLX

```

With the piece S we can connect a gap of 2

```
  SS
XSSX

```

With the pieces S,S,O we can connect a gap of 7 (Note that we can't connect a gap of 8)

```
 S
XSSOO SSX
  SOOSS

```

## Input

* A string representing the available pieces containing only the uppercase letters I, J, L, O, S, T and Z. Every letter represents a complete tetris piece.
* The letters will be in alphabetical order in the string.
* The string will be at least one character long.

## Output

* A single positive integer, the biggest gap connectable with the given pieces.

## Examples

Input =\> Output

```
OSS  =>  7

LS  =>  5

LZ  =>  6

ZZZZ  =>  10

LLSSS  =>  14

IIJSSSTTZ  =>  28

IISSSSSS  =>  24

OOOSSSSSSSSSSSSTT  =>  45

IJLOSTZ  =>  21

IJLOSTZZZZZZZ  =>  37

IIJLLLOSTT  =>  31

IJJJOOSSSTTZ  =>  35

```

This is code-golf so the shortest entry wins.

# Answer
# CJam, 53

```
'[,73>qf{1$e=s':+\+~}:+3*I+O-SZ-JO+m0e>ZS-LO+-e>2+3/-

```

Try it online

The idea is: assign each of the I, J, ..., Z variables to be the number of occurences of that letter, and calculate `string length * 3 + I - O`. Then count the number of non-compensated S's or Z's: an S can be compensated by Z, J or O, and a Z can be compensated by S, L or O, and subtract `ceil(that number/3)`, as we lose 1 unit for every 3 S's or Z's.
> 5 votes

---
Tags: code-golf, tetris
---


# Question
Title: Successfully navigating an asteroid field
# Introduction

Everyone knows that the possibility of successfully navigating an asteroid field is approximately 3,720 to 1. But despite your warning, Han Solo is still willing to try his luck.

Fearing for your artificial life, you decide to code, in the ship's peculiar dialect (*read: your preferred Code Golf language*), **an asteroid avoidance program that will decide which path to take in an asteroid field ASCII maze.**

# Input

The Millenium Falcon has an asteroid field mapping program, that gives data similar to this:

```
|   #####           #########  |
| ######  #          ###   #   |
|   # #  #  #  ####   #        |
@              ##    ####
|#   #   #       ###   ##      |
|##      ##      ####   #  #   |
|####           ##### #   ##   |

```

Top rows are left of the Falcon, bottom rows are right of the Falcon, and columns represent what is in front of the ship.

* Each `#` is an obstacle.
* Each space is empty space that the ship can fly in.
* The input is always 7 characters high. This is the asteroid mapping width limit.
* The input is always 32 characters long (30 for the field itself and 2 for the start and end limits). This is the asteroid mapping depth limit. Vertical bars `|` mark the beginning and the end of the mapping.
* `@` is the Falcon. It is always in the middle row (4th row) and first column in the input.
* The space left in the vertical bars on the last column is the place the ship must arrive at. It is always in the middle row (4th row) and last column in the input.

The input can be taken as a multi-line string, an array of strings, from STDIN or a function parameters, or read from a file.

# Possible maneuvers

You are pursued by TIE-Fighters, therefore you must always go forward. There are thus three ways the ship can fly at each step:

* `-` Forward
* `/` Forward and turn left
* `\` Forward and turn right

For example, these are valid paths:

```
@---

  --
 /  \ /
@    -

   -
  / \
 /   \
@     \

```

As you can see, there is always exactly one move per column. The Falcon is a piece of junk, therefore it cannot do violent turns. Which means moves such as `/\` or `\/` are **disallowed**. There must be atleast one pure forward `-` between two opposite turns. On the other hand, turning one way for multiple steps in a row is possible, as seen above.

The Falcon crashes if one move leads the ship to be in a spot where an obstacle is. For example, these moves lead to crashes:

```
@-#

@
 \
  #

  #
 /
@

```

Note that this is not a crash:

```
@-#
  \
   -

```

# Output

You must output the same asteroid field ASCII, with a valid path to the end. The Falcon must be printed at the end spot instead of the start spot.

For example, a valid output for the input example given before would be:

```
|   #####           #########  |
| ######  #--------  ###   #   |
|   # #  #/ #  ####\  #        |
 ---------      ##  \ #### ----@
|#   #   #       ### \ ## /    |
|##      ##      #### \ #/ #   |
|####           ##### #-- ##   |

```

Your path only needs to not crash the falcon. It doesn't need to be the shortest path possible.

You can assume that there will always be at least one possible path to the end.

You can output to STDOUT, in a file or any equivalent as long as the asteroid field is printed exactly like they are in this post (e.g. outputting a list of coordinates for the path is not valid).

# Test cases

* A normal asteroid field

```
|   #####           #########  |
| ######  #          ###   #   |
|   # #  #  #  ####   #        |
@              ##    ####
|#   #   #       ###   ##      |
|##      ##      ####   #  #   |
|####           ##### #   ##   |

```

Possible output

```
|   #####           #########  |
| ######  #--------  ###   #   |
|   # #  #/ #  ####\  #        |
 ---------      ##  \ #### ----@
|#   #   #       ### \ ## /    |
|##      ##      #### \ #/ #   |
|####           ##### #-- ##   |

```
* Hyperregular asteroid field

```
|# # # # # # # # # # # # # # # |
| # # # # # # # # # # # # # # #|
|# # # # # # # # # # # # # # # |
@ # # # # # # # # # # # # # #
|# # # # # # # # # # # # # # # |
| # # # # # # # # # # # # # # #|
|# # # # # # # # # # # # # # # |

```

Possible output

```
|# # # # # # # # # # # # # # # |
| # # # # # # # # # # # # # # #|
|# # # # # # # # # # # # # # # |
 -# #-# #-# #-# #-# #-# #-# #--@
|#\#/#\#/#\#/#\#/#\#/#\#/#\#/# |
| #-# #-# #-# #-# #-# #-# #-# #|
|# # # # # # # # # # # # # # # |

```
* Death star's core

```
|    #    #    #         #     |
|         #    #    #          |
|    #    #    #    #    #     |
@    #    #    #    #    #
|    #    #         #    #     |
|    #    #    #    #    #     |
|    #         #    #    #     |

```

Possible output

```
|    #    #    #   --    #     |
|  ---    #    #  / #\   -     |
| /  #\   #    # /  # \ /#\    |
 -   # \  #    #/   #  - # ----@
|    #  \ # ----    #    #     |
|    #   \#/   #    #    #     |
|    #    -    #    #    #     |

```
* Death star trench

```
|##############################|
|##############################|
|##############################|
@
|##############################|
|##############################|
|##############################|

```

Output

```
|##############################|
|##############################|
|##############################|
 ------------------------------@
|##############################|
|##############################|
|##############################|

```
* Asteroid cave

```
|### ##########################|
|## # ############### ## ######|
|# ###  ######## ### ## # #####|
@ ###### ###### ### ## ###
|########  ### ### ## #########|
|########## # ### ## ##########|
|###########              #####|

```

Possible output

```
|###-##########################|
|##/#\############### ##-######|
|#/###--######## ### ##/#\#####|
 -######\###### ### ##/###-----@
|########--### ### ##/#########|
|##########\# ### ##/##########|
|###########--------      #####|

```

# Scoring

R2D2 is busy swimming in swamps, so you're going to have to program the Falcon's controller by yourself, which is tedious. Therefore the **shortest code wins**.

# Answer
# JavaScript (ES6), 186 ~~201~~

```
f=([...s])=>(g=(i,l,c=k=" ")=>s[i]!=k&&s[i]!="@"?0:(i-130)?(s[i]=c,([..."/-\\"].some((c,j)=>!((--j&l&&j!=l)||!g(i+33*(l||j)+1,j,c)))||!(s[i]=k))):(s[i]="@",!console.log(s.join(""))))(99)

```

Runnable snippet:

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><textarea cols="33" rows="7" id="t"></textarea><br><button><b>Solve >>></b></button><hr><button id="1">Normal</button> <button id="2">Hyperregular</button> <button id="3">Death Star core</button> <button id="4">Death Star trench</button> <button id="5">Asteroid cave</button><script>f=(function($__0){var $__2,$__3,$__4,$__5;s = $__4 = $__0.split("");return (g = (function(i, l) {var c = arguments[2] !== (void 0) ? arguments[2] : k = " ";return s[i] != k && s[i] != "@" ? 0 : (i - 130) ? (s[i] = c, ("/-\\".split("").some((function(c, j) {return !((--j & l && j != l) || !g(i + 33 * (l || j) + 1, j, c));})) || !(s[i] = k))) : (s[i] = "@",$("#t").val(s.join("")));}))(99);});$("button").click(function() {this.id?$("#t").val(inputs[this.id]):f($("#t").val());});inputs = [,`|   #####           #########  |\n| ######  #          ###   #   |\n|   # #  #  #  ####   #        |\n@              ##    ####       \n|#   #   #       ###   ##      |\n|##      ##      ####   #  #   |\n|####           ##### #   ##   |`,`|# # # # # # # # # # # # # # # |\n| # # # # # # # # # # # # # # #|\n|# # # # # # # # # # # # # # # |\n@ # # # # # # # # # # # # # #   \n|# # # # # # # # # # # # # # # |\n| # # # # # # # # # # # # # # #|\n|# # # # # # # # # # # # # # # |`,`|    #    #    #         #     |\n|         #    #    #          |\n|    #    #    #    #    #     |\n@    #    #    #    #    #      \n|    #    #         #    #     |\n|    #    #    #    #    #     |\n|    #         #    #    #     |`,`|##############################|\n|##############################|\n|##############################|\n@                               \n|##############################|\n|##############################|\n|##############################|`,`|### ##########################|\n|## # ############### ## ######|\n|# ###  ######## ### ## # #####|\n@ ###### ###### ### ## ###      \n|########  ### ### ## #########|\n|########## # ### ## ##########|\n|###########              #####|`];$("#t").val(inputs[1]);</script
```

This function accepts a single string with newlines. The function splits the string into an array using the `...` operator and gets the index for `(x,y)` coordinates by `(33 * y) + x`.

The function runs recursively, testing out different possible moves for each space. When it encounters an obstacle, it returns a falsy value, and when it reaches the end goal space, it returns `true`. (In the golfed code, this `true` is created by `!console.log(...)`.)

Note that this code does not use long runs of right-turn moves, but punctuates them with straight moves. That is, it does the second option below, not the first:

```
\                       \
 \   (<= not this!)      -   (<= yes this!)
  \                       \

```

This seems to be legal, since `-` can legally come before or after a turn, so why not both at once? That looks especially strange at the end, when the final move is `\` but is displayed as `@`:

```
|  --#    #    #   ------#  -  |
| /  \    #    #  / #    \ / \ |
|/   #-   #    # /  #    #-   -|
     # \  #    #/   #    #     @
|    #  - # ----    #    #     |
|    #   \#/   #    #    #     |
|    #    -    #    #    #     |

```

My favorite nasty golf hack here is default argument abuse with `c=k=" "`. The arguments `(i,l,c=" ")` would say "use the string `" "` for `c` if `f` is not supplied a third argument". However, by doing `c=k=" "`, we say "if `c` is not supplied, store `" "` in the global variable `k` and then store that value in `c` as well". Since the recursion begins with only a single argument, `k` is always initialized at the first function call.

Mildly ungolfed:

```
// `i` - index in the string we're working on
// `l` - move character for this space (`/`, `\`, or `-`)
search = (i,l,c)=>{

  // not an open space; nip this recursive branch
  if(s[i]!=" "&&s[i]!="@") { return 0; }

  // we made it! the 130th space is (31,3)
  if(i==130) {
      s[i]="@";
      console.log(s.join(""));
      return true;
  }

  // fill in space with move character or a blank
  // (the space is only to blank out the initial `@`)
  s[i] = c || " ";

  // iterate through the 3 options and recursively explore the map
  return ['/','-','\\'].some((c,j)=>{
    --j;
    // if last move was sideways, and this is the opposite move, skip it
    if(l && j && j!=l) { return 0; }

    // recursively call search function on space pointed to by this move or the last move
    return search(i+33*(l||j)+1, j, c);
  })

  // if the `some` call is false (i.e. all options fail for this space)
  // then blank out this space and return false
  || !(s[i]=" ");

}

```
> 11 votes

# Answer
# C (complete program), 249 247 235 bytes

This is a complete program reading the input from a file and outputting the result to stdout. The name of the file is passed as a parameter to the program.

```
char f[7][33];g(i,j,c){return(i<0|i>6|f[i][j]%32?0:j<31?c%45-2?g(i,j+1,c)||g(i+1,j+1,92)||g(i-1,j+1,47):g(i+c/30-2,j+1,c)||g(i+c/30-2,j+1,45):1)?f[i][j]=j?j-31?c:64:32:0;}main(int p,char**v){read(open(v[1],0),f,231);g(3,0,45);puts(f);}

```

Ungolfed:

```
/* the field */
char f[7][33];

/* i - row
 * j - col
 * c - movement
 */
g(i,j,c)
{
    return
            /* if we're in bounds and not on an obstacle */
            (i >= 0 & i<7 & f[i][j] % 32 == 0 ?
                    /* if we haven't reached the end */
                    j < 31 ?
                            /* are we going straight ahead? */
                            c%45-2 ?
                                    /* try to go straight */
                                    g(i,j+1,c)
                                    /* try to turn right */
                                    || g(i+1,j+1,92)
                                    /* try to turn left */
                                    || g(i-1,j+1,47)
                            /* turning */
                            :
                                    /* try to keep turning */
                                    g(i+c/30-2,j+1,c)
                                    /* try to go straight */
                                    || g(i+c/30-2,j+1,45)
                    /* done */
                    :1 /* replace this with c==45 to better represent the last move being a turn */
            /* invalid move, fail */
            :0)
            /* add the correct movement to the field */
            ? f[i][j] = j ? j - 31 ? c : 64 : 32
            /* no path, much sads :( */
            :0;
}

main(int p,char*v[])
{
    /* read input file */
    read(open(v[1],0),f,231);

    /* calculate the path */
    g(3,0,45);

    /* print it out */
    puts(f);
}

```

Output:

```
$ ./a.out test.inp
|   #####           #########  |
| ######  #          ###   #   |
|   # #  #  #  ####   #      --|
 ------------- ##----####   /  @
|#   #   #    \ /### \ ##  /   |
|##      ##    - #### \ # /#   |
|####           ##### #---##   |

$ ./a.out test2.inp
|# # # # #-# # # # # #-# # # # |
| # # # #/#\# # # # #/#\# # # #|
|# # # #/# #\# # # #/# #\# # # |
 -# # #/# # #\# # #/# # #\# #  @
|#\# #/# # # #\# #/# # # #\# #/|
| #\#/# # # # #\#/# # # # #\#/#|
|# #-# # # # # #-# # # # # #-# |

$ ./a.out test3.inp
|    #    #    #   ------#     |
|    -    #    #  / #    \     |
|   /#\   #    # /  #    #\    |
 --- # \  #    #/   #    # \   @
|    #  \ #    /    #    #  \ /|
|    #   \#   /#    #    #   - |
|    #    ---- #    #    #     |

$ ./a.out test4.inp
|##############################|
|##############################|
|##############################|
 ------------------------------@
|##############################|
|##############################|
|##############################|

$ ./a.out test5.inp
|###-##########################|
|##/#\############### ##-######|
|#/###--######## ### ##/#\#####|
 -######\###### ### ##/###-----@
|########--### ### ##/#########|
|##########\# ### ##/##########|
|###########--------      #####|

```
> 7 votes

# Answer
# Common Lisp, 303 bytes

Had lots of fun with this challenge, it's the first codegolf task I did. Basically there's a simple recursive function that tries every viable move until the end position is reached.

## Golfed/Minified

```
(let((s(open "i"))(n nil)(f(make-string 231)))(read-sequence f s)(labels((r(p s u d)(and(< 0 p 224)(find(aref f p)" @")(setf(aref f p)(cond((= 130 p)#\@)((or(unless d(r(- p 32)#\/ t n))(unless u(r(+ p 34)#\\ n t))(r(+ p(cond(u -32)(d 34)(t 1)))#\- n n))s)((return-from r)))))))(r 99 #\- n n)(princ f)))

```

Reads input from a file **i** in working directory. I'm pretty sure there's still room for improvement.

## Plain code

```
(defun run-test (file)
  (let ((stream (open file)) ;;should use with-open-file for autoclose..
        (no nil) ;; alias for brevity
        (field (make-string 231)))
    (read-sequence field stream)
    (labels ((doit (pos sym going-up going-down)
               (and
                 (< 0 pos 224)
                 (find (aref field pos) " @")
                 (setf (aref field pos)
                       (cond
                         ((= 130 pos) #\@)
                         ((or
                            (unless going-down (doit (- pos 32) #\/ t no))
                            (unless going-up (doit (+ pos 34) #\\ no t))
                            (doit (+ pos (cond (going-up -32)
                                               (going-down 34)
                                               (t 1)))
                                  #\- no no))
                          sym)
                         ((return-from doit)))))))
      (doit 99 #\- no no)
      (princ field)
      nil)))

```

## Sample output

```
|   #####       --  #########  |
| ######  #    /  \  ###   # - |
|   # #  #  # /####\  #     / \|
--   -       / ##   \####  /   @
|#\ /#\  #  /    ### \ ## /    |
|##-   \ ##/     #### \ #/ #   |
|####   ---     ##### #-- ##   |

|  --#    #    #   --    #-    |
| /  \    #    #  / #\   / \   |
|/   #\   #    # /  # \ /#  \  |
-    # \  #    #/   #  - #   \ @
|    #  \ # ----    #    #    -|
|    #   \#/   #    #    #     |
|    #    -    #    #    #     |

|# #-# # # # # #-# # # # # #-# |
| #/#\# # # # #/#\# # # # #/#\#|
|#/# #\# # # #/# #\# # # #/# #\|
--# # #\# # #/# # #\# # #/# #  @
|# # # #\# #/# # # #\# #/# # # |
| # # # #\#/# # # # #\#/# # # #|
|# # # # #-# # # # # #-# # # # |

```
> 3 votes

# Answer
# ActionScript 3, 364 bytes

I split this into two functions; one to change the array into an array of arrays, and one recursive one to compute the flight path.

```
function m(f){for(var i=0;i<f.length;i++){f[i]=f[i].split("");}n(f,0,3,0);return f;}function n(f,x,y,m){var P=f[y][x],X=x+1,A=y-1,B=y,C=y+1,T=true,F=false,E='-';if (y<0||y>6||P=='#'||P=='|')return F;if (x==31){f[y][x]='@';return T;}if(m<0&&y>0){B=A;C=9;E='/';}else if(m>0&&y<6){A=9;B=C;E='\\';}if (n(f,X,B,0)||n(f,X,A,-1)||n(f,X,C,1)){f[y][x]=E;return T;return F;}

```

Ungolfed version in a program with one sample asteroid field defined:

```
package
{
    import flash.display.Sprite;

    public class AsteroidNavigator extends Sprite
    {
        var field:Array;
        public function AsteroidNavigator()
        {
            field = [
"|   #####           #########  |",
"| ######  #          ###   #   |",
"|   # #  #  #  ####   #        |",
"@              ##    ####       ",
"|#   #   #       ###   ##      |",
"|##      ##      ####   #  #   |",
"|####           ##### #   ##   |"];
            m(field);
            printField();
        }

        function m(f){
            for(var i=0;i<f.length;i++){
                f[i]=f[i].split("");\
            }
            n(f,0,3,0);
            return f;
        }

        private function n(field,x,y,m) {
            var C = field[y][x];
            if (x > 31 || C == '#' || C == '|') {
                return false;
            }
            if (x == 31 && y == 3) {
                field[y][x] = '@';
                return true;
            }
            if (m == 0) {
                if (n(x+1, y, 0) || ((y>0) && n(x+1, y-1, -1)) || ((y<6) && n(x+1, y+1, 1))) {
                field[y][x] = '-';
                return true;
                }
            } else if ((m<0) && (y>0)) {
                if ((n(x+1, y-1, -1) || n(x+1, y-1, 0))) {
                    field[y][x] = '/';
                    return true;
                }
            } else if ((m>0) && (y<6)) {
                if ((n(x+1, y+1, 1) || n(x+1, y+1, 0))) {
                    field[y][x] = '\\';
                    return true;
                }
            }
            return false;
        }

        private function printField() {
            var sb = "";
            for each (var row:Array in field) {
                sb += row.join("") + "\n";
            }
            trace(sb);
        }
    }
}

```
> 2 votes

---
Tags: code-golf, maze
---