title: 2016 Time Capsule String: Coverage

text:
# Question
Title: 2016 Time Capsule String: Coverage
Consider the 74 characters from the 2016 time capsule string (note the leading space):

 !!!!!#$$%&())))*+...1449:=@@@AHILOQQQTTZ\\^`````````eefmpxy{||||~~~~~~~~~
</code></pre>

Your task is to write as many programs as possible (**in the same language**) using these characters. The output of each program must be nonempty. When all of the programs and their outputs are considered, it must only use each of the 74 above characters no more than once.

Your score is determined by the number of programs you have written, with the total length of the programs being a tie-breaker (greatest length wins).

Some more rules:

1. Each program must terminate.
2. Each program must be a full program and output in a reasonable format.
3. All output to STDERR is ignored.
4. You may not run your program with any flags, except those required to run the program. (E.g., a `-e` flag that executes program source.)
5. If the program has output that cannot be suppressed, you may ignore when considering the output. (E.g., you may ignore trailing newlines.)
6. Each program should be able to be executed with empty stdin.

## Example

If I had programs `4` and `T1~` that outputted `4` and `9` respectively, they would, when considered together, be:

```
44T1~9

```

Which can be seen to be a subset of the capsule string. However, if I had programs `4@|4` and `|e+` that outputted `4` and `f` respectively, they would be:

```
4@|44|e+f

```

And, since there are 3 `4`s, it is not a subset.

# Answer
> 2 votes
# PHP, 22 programs

Yeah, I get it's kind of boring.

Programs (separated by single newline):

```
!
!
$
)
)
.
4
@
Q
T
\
`
`
`
`
e
|
|
~
~
~
~

```

Output and programs combined:

<pre><code>!!!!$$))))..44@@QQTT\\````````ee||||~~~~~~~~
</code></pre>

# Answer
> 5 votes
# Japt, ~~11~~ 13 programs, length 61

```
\x:#).&~L // outputs 9  (41 & ~100)
~T+~Tf)p  // outputs 4  ((~0 + ~floor(0)) ** 2)
$~Q$ *\~Z // outputs 1  (~'"' * ~0)
I%A^O||@{=!(Hmy))  // outputs 4  (64 % 10 ^ {} || function(X,Y,Z) { return function() { return ((U = !(H.m("y")))) } })
`!        // outputs !
`!        // outputs !
`.        // outputs .
`@        // outputs @
`Q        // outputs Q
`e        // outputs e
`|        // outputs |
`~        // outputs ~
`~        // outputs ~

```

It's awfully hard to come up with an answer that isn't just a string literal and outputs something other than a number...

Output and programs combined:

<pre><code> !!!!!#$$%&())))*+...1449:=@@@AHILOQQQTTZ\\^`````````eefmpxy{||||~~~~~~~~~

I think I got 'em all...

---

When stripped down to the bare minimum:

```
#)&~L
~T+~T)p
~Q*~Z
I%A
`!
`!
`.
`@
`Q
`e
`|
`~
`~

```

It leaves these chars for future programs/outputs:

```
 !$$()).:=@HO\\^fmxy{||

```

You can trade two of `$`, `)`, or `|` for two of any of the chars in the nine string literals; that is, two of any of `!.@Qe|~`.

Additionally, you can trade out the `Q` in the third program for `H` or `O`, and the `Z` for `H`, `O`, `@`, or `{`.

# Answer
> 1 votes
# PowerShell, 2 programs, length 31

```
+!!($eefmpxy =9)

```

Try it online!

Outputs `1`.
Works by setting the variable `$eefmpxy` to `9`, encapsulating that in parens, taking the Boolean-not `!` of that (which turns it to `$False`), then the Boolean-not of *that* (which turns it to `$True`), then casts as an integer with `+`, turning it to `1`. That's left on the pipeline and output is implicit.

---

```
4*!$AHILOQQQTTZ

```

Try it online!

Outputs `4`.
Works by initializing the variable `$AHILOQQQTTZ` to the default of `$null`, the Boolean-not `!` of which is `$True`. That's implicitly cast to an integer `1` due to the multiplication of `4*`, so the result of `4` is left on the pipeline and output is implicit.

---

We're really limited in PowerShell for other things, as though we have plenty of pipe characters `|` to pipeline commands together, we only have one `{` and no `}`; too many `)` for the lone `(`; the backtick ``` is used as a "line continuation marker" to interpret multiple lines as one (used for readability), but we have no linefeed to go with it; and the `~` and `^` characters are "Reserved for future use" and thus toss a syntax error when you try to use them. So, most of the characters are useless, which is a shame.

While the `#` character starts a comment (and everything after it is completely ignored), it feels cheaty to use it that way, so I didn't include it above.

# Answer
> 0 votes
# 05AB1E, 4 programs, length 19

**Programs**

```
)O!            # outputs 1    fac(sum([]))
A`\            # outputs y    2nd_last(alphabet)
THf`x          # outputs 4    last_primefactor(int(10,16))*2
TL`\           # outputs 9    2nd_last(range[1 ... 10])

```

**Output and programs combined**

<pre><code>!)149AHLOTT\\```fxy

# Answer
> 0 votes
# Cardinal, 1 program, length 73

%#~~~~~~~~~!!!!!+=.*449eefmpxyAHLOQQQTTZ`````````@@@$$I\\^{|||| ())))&..:

Outputs 1

Try it online!

Cardinal can only have 1 valid program that will do anything as there is only 1 %.

---
Tags: code-challenge, restricted-source
---


# Question
Title: List all times in the day at a half hour rate
Shortest answer wins.

It must be sorted, and in 24hr time. The final line does not have a comma.

Output should be as follows:

```
'00:00',
'00:30',
'01:00',
'01:30',
'02:00',
'02:30',
'03:00',
'03:30',
'04:00',
'04:30',
'05:00',
'05:30',
'06:00',
'06:30',
'07:00',
'07:30',
'08:00',
'08:30',
'09:00',
'09:30',
'10:00',
'10:30',
'11:00',
'11:30',
'12:00',
'12:30',
'13:00',
'13:30',
'14:00',
'14:30',
'15:00',
'15:30',
'16:00',
'16:30',
'17:00',
'17:30',
'18:00',
'18:30',
'19:00',
'19:30',
'20:00',
'20:30',
'21:00',
'21:30',
'22:00',
'22:30',
'23:00',
'23:30'

```

# Answer
> 17 votes
# Pyth, 26 bytes

```
Pjbm%"'%02d:%s0',"d*U24"03

```

Demonstration.

We start with the cartesian product of `range(24)` (`U24`) with the string `"03"`.

Then, we map these values to the appropriate string formating substitution (`m%"'%02d:%s0',"d`).

Then, the resultant strings are joined on the newline character (`jb`).

Finally, we remove the trailing comma (`P`) and print.

# Answer
> 15 votes
# Befunge-93, 63 bytes

```
0>"'",:2/:55+/.55+%.":",:2%3*v
 ^,+55,","<_@#-*86:+1,"'".0. <

```

<sup>*(animation made with BefunExec)*</sup>

# Answer
> 14 votes
# Bash: ~~58~~ ~~47~~ 46 characters

```
h=`echo \'{00..23}:{0,3}0\'`
echo "${h// /,
}"

```

# Answer
> 10 votes
# CJam, ~~31 30~~ 29 bytes

```
24,[U3]m*"'%02d:%d0',
"fe%~7<

```

This is pretty straight forward using printf formatting:

```
24,                              e# get the array 0..23
   [U3]                          e# put array [0 3] on stack
       m*                        e# do a cartesian product between 0..23 and [0 3] array
                                 e# now we have tuples like [[0 0], [0 3] ... ] etc
         "'%02d:%d0',
"fe%                             e# this is standard printf formatting. What we do here is
                                 e# is that we format each tuple on this string
    ~7<                          e# unwrap and remove comma and new line from last line
                                 e# by taking only first 7 characters

```

Try it online here

# Answer
> 10 votes
# Python 2, ~~58~~ 56 bytes

```
for i in range(48):print"'%02d:%s0',"[:57-i]%(i/2,i%2*3)

```

Like sentiao's answer but using a `for` loop, with slicing to remove the comma. Thanks to @grc for knocking off two bytes.

# Answer
> 6 votes
# Java - 119 bytes

I started with Java 8's StringJoiner, but that means including an import statement, so I decided to do it the old way:

```
void f(){String s="";for(int i=0;i<24;)s+=s.format(",\n'%02d:00',\n'%02d:30'",i,i++);System.out.print(s.substring(2));}

```

Perhaps this can be improved by getting rid of the multiple occuring `String` and `System` keywords.

# Answer
> 5 votes
# Ruby, ~~94~~ ~~61~~ ~~56~~ 51

```
$><<(0..47).map{|i|"'%02d:%02d'"%[i/2,i%2*30]}*",
"

```

Thanks to @blutorange (again) for his help in golfing!

# Answer
> 5 votes
# Perl, ~~52~~ ~~50~~ ~~48~~ 45B

```
$,=",
";say map<\\'$_:{0,3}0\\'>,"00".."23"

```

With help from ThisSuitIsBlackNot :)

# Answer
> 4 votes
## JAVA ~~95~~ 94 bytes

I love the fact that printf exists in Java:

```
void p(){for(int i=0;i<24;)System.out.printf("'%02d:00',\n'%02d:30'%c\n", i,i++,(i<24)?44:0);}

```

Ungolfed

```
void p(){
    for(int i=0;i<24;)
        System.out.printf("'%02d:00',\n'%02d:30'%c\n", i,i++,(i<24)?44:0);
}

```

EDIT Replaced the `','` with `44`

# Answer
> 4 votes
# Pyth, ~~32~~ 31 bytes

I golfed something in python but it turned out to be exactly the same as Sp3000's answer. So I decided to give Pyth a try:

```
V48<%"'%02d:%d0',",/N2*3%N2-54N

```

It's a exact translation of Sp3000 answer:

```
for i in range(48):print"'%02d:%d0',"[:57-i]%(i/2,i%2*3)

```

It's my first go at Pyth, so please do enlighten me about that 1 byte saving.

# Answer
> 3 votes
# Ruby, ~~54~~ 51 bytes

```
puts (0..23).map{|h|"'#{h}:00',
'#{h}:30'"}.join",
"

```

# Answer
> 3 votes
# PHP, 109 bytes

```
foreach(new DatePeriod("R47/2015-05-07T00:00:00Z/PT30M")as$d)$a[]=$d->format("'H:i'");echo implode(",\n",$a);

```

# Answer
> 3 votes
# C, ~~116~~,~~115~~,~~101~~,~~100~~,~~95~~,~~74~~,~~73~~, 71

May be able to scrape a few more bytes off this...

```
main(a){for(;++a<50;)printf("'%02d:%d0'%s",a/2-1,a%2*3,a<49?",\n":"");}

```

# Answer
> 3 votes
# T-SQL, ~~319~~ ~~307~~ 305 bytes

```
WITH t AS(SELECT t.f FROM(VALUES(0),(1),(2),(3),(4))t(f)),i AS(SELECT i=row_number()OVER(ORDER BY u.f,v.f)-1FROM t u CROSS APPLY t v),h AS(SELECT i,h=right('0'+cast(i AS VARCHAR(2)),2)FROM i WHERE i<24)SELECT''''+h+':'+m+CASE WHEN i=23AND m='30'THEN''ELSE','END FROM(VALUES('00'),('30'))m(m) CROSS APPLY h

```

Un-golfed version:

```
WITH
t AS(
    SELECT
        t.f
    FROM(VALUES
         (0),(1),(2),(3),(4)
    )t(f)
),
i AS(
    SELECT
        i = row_number() OVER(ORDER BY u.f,v.f) - 1
    FROM t u
    CROSS APPLY t v
),
h AS(
    SELECT
        i,
        h = right('0'+cast(i AS VARCHAR(2)),2)
    FROM i
    WHERE i<24
)
SELECT
    '''' + h + ':' + m + CASE WHEN i=23 AND m='30'
                              THEN ''
                              ELSE ','
                         END
FROM(
    VALUES('00'),('30')
)m(m)
CROSS APPLY h

```

# Answer
> 2 votes
# Pyth, 34 bytes

```
j+\,bmjk[\'?kgd20Z/d2\:*3%d2Z\')48

```

This can definitely be improved.

Try it online: Pyth Compiler/Executor

### Explanation:

```
     m                          48   map each d in [0, 1, ..., 47] to:
        [                      )       create a list with the elements:
         \'                              "'"
           ?kgd20Z                       "" if d >= 20 else 0
                  /d2                    d / 2
                     \:                  ":"
                       *3%d2             3 * (d%2)
                            Z            0
                             \'          "'"
      jk                               join by "", the list gets converted into a string
j+\,b                                join all times by "," + "\n"

```

# Answer
> 2 votes
# Swift, 74 bytes

Updated for Swift 2/3...and with new string interpolation...

```
for x in 0...47{print("'\(x<20 ?"0":"")\(x/2):\(x%2*3)0'\(x<47 ?",":"")")}

```

# Answer
> 2 votes
# Python 2, 69 bytes

```
print',\n'.join(["'%02d:%s0'"%(h,m)for h in range(24)for m in'03'])

```

Quite obvious, but here's an explanation:

* using double-for-loop
* alternating between `'0'` and `'3'` in string format is shorter than a list
* `%02d` does the padding for `h`
* `m`doesn't need padding as the alternating character is on a fixed position
* `'\n'.join()` solves the final-line requirements

I have no idea if it can be done shorter (in Python 2).

**by Sp3000, 61 bytes :** `print',\n'.join("'%02d:%s0'"%(h/2,h%2*3)for h in range(48))`

# Answer
> 2 votes
# golflua ~~52~~ 51 chars

```
~@n=0,47w(S.q("'%02d:%d0'%c",n/2,n%2*3,n<47&44|0))$

```

Using ascii 44 = `,` and 0 a space saves a character.

An ungolfed Lua version would be

```
for h=0,47 do
   print(string.format("'%02d:%d0'%c",h/2,h%2*3, if h<47 and 44 or 0))
end

```

The `if` statement is much like the ternary operator `a > b ? 44 : 0`.

# Answer
> 2 votes
# Julia: ~~65~~ ~~64~~ 61 characters

```
[@printf("'%02d:%d0'%s
",i/2.01,i%2*3,i<47?",":"")for i=0:47]

```

### Julia: 64 characters

(Kept here to show Julia's nice `for` syntax.)

```
print(join([@sprintf("'%02d:%d0'",h,m*3)for m=0:1,h=0:23],",
"))

```

# Answer
> 2 votes
# Python, ~~60 58~~ 64 bytes

```
for i in range(24):print("'%02d:00,\n%02d:30'"%(i,i)+', '[i>22])

```

Ungolfed:

```
for i in range(24):
    if i <23:
        print( ('0'+str(i))[-2:] + ':00,\n' + str(i) + ':30,')
    else:
        print( ('0'+str(i))[-2:] + ':00,\n' + str(i) + ':30')

```

Try it online here.

# Answer
> 2 votes
# Haskell, 85 bytes

```
putStr$init$init$unlines$take 48['\'':w:x:':':y:"0',"|w<-"012",x<-['0'..'9'],y<-"03"]

```

Unfortunately `printf` requires a 19 byte `import`, so I cannot use it.

# Answer
> 2 votes
# JavaScript (ES6), 77 86+1 bytes

Didn't realize there had to be quotes on each line (+1 is for `-p` flag with node):

```
"'"+Array.from(Array(48),(d,i)=>(i>19?"":"0")+~~(i/2)+":"+3*(i&1)+0).join("',\n'")+"'"

```

old solution:

```
Array.from(Array(48),(d,i)=>~~(i/2).toFixed(2)+":"+3*(i&1)+"0").join(",\n")

```

ungolfed version (using a for loop instead of `Array.from`):

```
var a = [];
// there are 48 different times (00:00 to 23:30)
for (var i = 0; i < 48; i++) {
    a[i] =
        (i > 19 ? "" : "0") +
            // just a ternary to decide whether to pad
            // with a zero (19/2 is 9.5, so it's the last padded number)
        ~~(i/2) +
            // we want 0 to 24, not 0 to 48
        ":" +  // they all then have a colon
        3*(i&1) +
            // if i is odd, it should print 30; otherwise, print 0
        "0" // followed by the last 0
}
console.log(a.join(",\n"));

```

# Answer
> 2 votes
# Fortran 96

```
do i=0,46;print'(a1,i2.2,a,i2.2,a2)',"'",i/2,":",mod(i,2)*30,"',";enddo;print'(a)',"'23:30'";end

```

Standard abuse of types & requirement only for the final `end` for compiling. Sadly, due to implicit formatting, the `'(a)'` in the final `print` statement is required. Still, better than the C and C++ answers ;)

# Answer
> 2 votes
# C# - 120 bytes

```
class P{static void Main(){for(var i=0;i<24;i++)System.Console.Write("'{0:00}:00',\n'{0:00}:30'{1}\n",i,i==23?"":",");}}

```

# Answer
> 2 votes
# , 39 chars / 67 bytes (non-competing)

```
↺;Ḁ⧺<Ḱ;)ᵖ`'⦃Ḁ<Ḕ?0:⬯}⦃0|Ḁ/2}:⦃Ḁ%2*3}0',”

```

`Try it here (Firefox only).`

*Not a single alphabetical character in sight...*

# Answer
> 2 votes
# PHP, 69 70 62 bytes

```
for($x=-1;++$x<47;)printf("'%02d:%d0',
",$x/2,$x%2*3)?>'23:30'

```

Try it online

Outputting `'23:30'` at the end is a bit lame, and so is closing the php context using `?>` without opening or re-opening it. An cleaner alternative (but 65 bytes) would be:

```
for($x=-1;++$x<48;)printf("%s'%02d:%d0'",$x?",
":'',$x/2,$x%2*3);

```

Try it online

Thank you @Dennis for the tips. Alternative inspired by the contribution of @ismael-miguel.

# Answer
> 1 votes
# Python 2, ~~74~~ 65 bytes

We generate a 2 line string for each hour, using text formatting:

```
print',\n'.join("'%02u:00',\n'%02u:30'"%(h,h)for h in range(24))

```

This code is fairly clear, but the clever indexing and integer maths in the answer by Sp3000 gives a shorter solution.

# Answer
> 1 votes
# Javascript, 89 bytes

```
for(i=a=[];i<24;)a.push((x="'"+("0"+i++).slice(-2))+":00'",x+":30'");alert(a.join(",\n"))

```

# Answer
> 1 votes
## Python 2: 64 bytes

```
print ',\n'.join(['%02d:00,\n%02d:30'%(h,h) for h in range(24)])

```

# Answer
> 1 votes
**Ruby - 52 bytes**

```
puts (0..47).map{|i|"'%02d:%02d'"%[i/2,i%2*30]}*",
"

```

# Answer
> 1 votes
# PHP ~~89~~ ~~88~~ ~~87~~ 85 bytes

```
<?for($i=0;$i<24;$i++){$a=sprintf("%02d",$i);echo"'$a:00',\n'$a:30'",$i<23?",\n":'';}

```

I tried but it isn't the shortest in PHP.

Old code:

```
<?for($i=0;$i<24;$i++){($i<10?$a="0$i":$a=$i);echo"'$a:00',\n'$a:30'".($i==23?'':",\n");}

```

# Answer
> 1 votes
## PowerShell, 69 Bytes

```
$d=date 0;(0..47|%{"'{0:HH:mm}'"-f$d;$d=$d.AddMinutes(30)})-join",`n"

```

I love how it's shorter to *use actual date functions* than simply try to brute force the numbers with `.ToString` operators to pad zeroes and logic to decide if we're in a `00` or a `30` output.

Sets a new date `$d` to be `00:00:00 Jan 1 0000`, then goes into a loop 48 times with `0..47|%{..}`. Each time in the loop we generate our output using the `-f` operator. The `HH:mm` format for dates gives us 24-hour time with minutes, just as we want. Then, we `addMinutes(30)` to prep us for the next go-round. Outside the loop, we `-join` everything together with a comma and a newline.

# Answer
> 1 votes
# TreeHugger, 1433 Bytes

TreeHugger is a bf variant that uses a binary tree instead of a linear tape. Read about it here and you can run scripts on the implementation here. As for how this program works, here is a rough run down:

* **Store** the characters needed
    + In the first loop, get within 5 of the desired value
    + Manually adjust to the correct value
* **Walk** through the tree and print the proper characters in the proper order
    + *WARNING:* This step is a little tedious

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

```

---

## Un-Golfed

The three digit numbers are the ASCII values we're aiming for in the approximation and adjustment phases. The numbers in the print phase, indicate the hour that we are printing.

```
# Approximation
+++++ +++++ [
058 > +++++ +
051 > +++++
048 > +++++
039 > ++++
044 > ++++
010 > +
^^^^^
053 < +++++
052 > +++++
^^^
039 < ++++
049 > +++++
053 > +++++
^
052 < +++++
^^
048 < +++++
051 > +++++
057 > +++++ +
^
056 < +++++ +
^^
050 < +++++
055 > +++++ +
^
054 < +++++
^^^^ -
]
# Adjustment
058 > --
051 > +
048 > --
039 > -
044 > ++++
010 >
^^^^^
053 < +++
052 > ++
^^^
039 < -
049 > -
053 > +++
^
052 < ++
^^
048 < --
051 > +
057 > ---
^
056 < ----
^^
050 <
055 > -----
^
054 < ++++
^^^^
# Print
0
<.<..^^     >.>>.[.>] ^^^^^ ^^^
<.<..^^     >[.>] ^^^^^ ^^^
1
<.<.^>.^^   >.>>.[.>] ^^^^^ ^^^
<.<.^>.^^   >[.>] ^^^^^ ^^^
2
<.<.<.^^^   >.>>.[.>] ^^^^^ ^^^
<.<.<.^^^   >[.>] ^^^^^ ^^^
3
<.<.>.^^^   >.>>.[.>] ^^^^^ ^^^
<.<.>.^^^   >[.>] ^^^^^ ^^^
4
<.<.^><.^^^ >.>>.[.>] ^^^^^ ^^^
<.<.^><.^^^ >[.>] ^^^^^ ^^^
5
<.<.^>>.^^^ >.>>.[.>] ^^^^^ ^^^
<.<.^>>.^^^ >[.>] ^^^^^ ^^^
6
<.<.<<.^^^^ >.>>.[.>] ^^^^^ ^^^
<.<.<<.^^^^ >[.>] ^^^^^ ^^^
7
<.<.<>.^^^^ >.>>.[.>] ^^^^^ ^^^
<.<.<>.^^^^ >[.>] ^^^^^ ^^^
8
<.<.><.^^^^ >.>>.[.>] ^^^^^ ^^^
<.<.><.^^^^ >[.>] ^^^^^ ^^^
9
<.<.>>.^^^^ >.>>.[.>] ^^^^^ ^^^
<.<.>>.^^^^ >[.>] ^^^^^ ^^^
10
<.>.^<.^^   >.>>.[.>] ^^^^^ ^^^
<.>.^<.^^   >[.>] ^^^^^ ^^^
11
<.>..^^     >.>>.[.>] ^^^^^ ^^^
<.>..^^     >[.>] ^^^^^ ^^^
12
<.>.^<<.^^^ >.>>.[.>] ^^^^^ ^^^
<.>.^<<.^^^ >[.>] ^^^^^ ^^^
13
<.>.^<>.^^^ >.>>.[.>] ^^^^^ ^^^
<.>.^<>.^^^ >[.>] ^^^^^ ^^^
14
<.>.<.^^^   >.>>.[.>] ^^^^^ ^^^
<.>.<.^^^   >[.>] ^^^^^ ^^^
15
<.>.>.^^^   >.>>.[.>] ^^^^^ ^^^
<.>.>.^^^   >[.>] ^^^^^ ^^^
16
<.>.^<<<.^^^^ >.>>.[.>] ^^^^^ ^^^
<.>.^<<<.^^^^ >[.>] ^^^^^ ^^^
17
<.>.^<<>.^^^^ >.>>.[.>] ^^^^^ ^^^
<.>.^<<>.^^^^ >[.>] ^^^^^ ^^^
18
<.>.^<><.^^^^ >.>>.[.>] ^^^^^ ^^^
<.>.^<><.^^^^ >[.>] ^^^^^ ^^^
19
<.>.^<>>.^^^^ >.>>.[.>] ^^^^^ ^^^
<.>.^<>>.^^^^ >[.>] ^^^^^ ^^^
20
<.<<.^.^^      >.>>.[.>] ^^^^^ ^^^
<.<<.^.^^      >[.>] ^^^^^ ^^^
21
<.<<.^^>.^^  >.>>.[.>] ^^^^^ ^^^
<.<<.^^>.^^  >[.>] ^^^^^ ^^^
22
<.<<..^^^    >.>>.[.>] ^^^^^ ^^^
<.<<..^^^    >[.>] ^^^^^ ^^^
23
<.<<.^>.^^^    >.>>.[.>] ^^^^^ ^^^
<.<<.^>.^^^    >.>.>.>.

```

This can be golfed down more, I have a `1198 byte` version that should work, but I think this implementation might have a bug. So stay tuned until I finish debugging my own implementation.

# Answer
> 1 votes
# Java, 93 bytes

```
void t(){for(int i=0;i<24;)System.out.printf("'%02d:00',\n'%02d:30'%s",i,i,i++<23?",\n":"");}

```

**Ungolfed**

```
void t()
{
    for(int i = 0; i < 24; i++)
    {
        System.out.printf("'%02d:00',\n", i);
        System.out.printf(   "'%02d:30'", i);
        System.out.printf( i < 23 ?",\n":"");
    }
}

```

# Answer
> 0 votes
# JavaScript, 127 bytes

I'm not a very good golfer :s

```
var r='',i,m=":00',\n",q="'"
for(i=0;i<23;i++){
h=("0"+i).slice(-2)
r+=q+h+m+q+h+":30',\n"
}
r+=q+i+m+q+i+":30'"
console.log(r)

```

# Java, 179 bytes

```
public class M{public static void main(String[] a){String r="",f="'%02d:%s',\n";for(int i=0;i<24;i++)r+=String.format(f+f,i,"00",i,"30");System.out.print(r.replaceAll(".$",""));}}

```

ungolfed

```
public class M {
    public static void main(final String[] a) {
        String r = "", f = "'%02d:%s',\n";
        for (int i = 0; i < 24; i++)r += String.format(f + f, i, "00", i, "30");
        System.out.print(r.replaceAll(".$", ""));
    }
}

```

# Answer
> 0 votes
# C++ - 104 bytes

I spend a while trying to find an obtuse way to remove the comma, but in the end the simple approach seemed to be by far the most efficient.

```
#include<cstdio>
int main(int c,char**v){for(c=-1;c++<47;printf("'%.2d:%d0'%s\n",c/2,c%2*3,c>46?"":","));}

```

I shouldn't need to initialize c to -1 but I couldn't get an inline postfix increment to work how I expected.

# Answer
> 0 votes
# JavaScript (ES6), ~~81~~ 77 bytes

Template strings work well for cutting down the size.

```
alert([...Array(48)].map((x,i)=>`'${i<20?0:''}${i/2|0}:${i%2*3}0'`).join`,
`)

```

# Answer
> 0 votes
# PHP, ~~82~~ 77 bytes

Nothing fancy, just abusing PHP's string capacities.

```
<?for($H=-1;$H++<23;)echo$H?",
'":"'",$H=str_pad($H,2,0,0),":00',
'$H:30'";

```

Probably there's something that I can cut off.

## Old version, 82 bytes:

```
<?foreach(range(0,23)as$H)echo$H?",
'":"'",$H=str_pad($H,2,0,0),":00',
'$H:30'";

```

# Answer
> 0 votes
**C# - lots (but give away free with windows)**

```
using System;
using System.Collections.Generic;
using System.Linq;
class P
{
    static void Main()
    {
        Console.Write(String.Join(",\n", Enumerable.Range(0, 48).Select(i => "'" + i / 2 + ":" + (i % 2) * 3 + "0'")));
    }
}

```

# Answer
> 0 votes
# PostgreSQL: 97 characters

```
select string_agg(to_char(x*interval'30m','''hh24:mi'''),','||chr(10))from generate_series(0,47)x

```

### PostgreSQL: ~~132~~ ~~131~~ 116 characters

Kept here to show PostgreSQL's cool way to generate timestamp series.

```
select string_agg(to_char(x,'''hh24:mi'''),','||chr(10))from generate_series('150511','150511 23:59',interval'.5h')x

```

# Answer
> 0 votes
# Python, 145 bytes

```
import time as t;i=48;a=t.asctime;w=3600;s=t.sleep;s(24-int(a()[11:13])*w+w-60*int(a()[14:16]));
while i:print '\''+a()[11:16]+'\',';i-=1;s(w)

```

I guess the code is fairly readable (altough quite long). Once you run the program it waits until actual local time is `00:00h`, then prints the time and waits for 30 min, time in which the program prints the hour again. It keeps repeating this process until `00:00h` of the next day is reached. Therefore, with lots of patience and no incidents that force your computer to shutdown all the times get printed.

# Answer
> 0 votes
## Ceylon, 101 bytes

```
shared void run(){print(",\n".join{for(h in 0..23)for(m in[0,3])"'``"``h``".pad(2,'0')``:``m``0'"});}

```

Formatted:

```
shared void run() {
    // original:
    print(",\n".join {
            for (h in 0..23)
                for (m in [0, 3])
                    "'``"``h``".pad(2, '0')``:``m``0'"
        });
}

```

This uses an iterable comprehension with two for-clauses, and nested string templates. `"``h``"` is a shorter way of writing `h.string` (we can't pad an integer directly). `",\n".join(iterable)` puts the commas and new-lines between the strings (this way we can avoid the `,` in the last line).

Unfortunately Ceylon has no `printf` functionality, which would certainly make things shorter (no `.pad` or `.string` necessary).

After finding that "straightforward" solution, I experimented with some variations, which unfortunately result in slightly longer shrinked solutions:

```
shared void run() {
    print(",\n".join(
            (0..23)
                *.string
                *.pad(2, '0')
                .map((x) => "'``x``:00',\n'``x``:30'")
        ));
}

```

(102 bytes)

```
shared void run() {
    print(",\n".join {
            for (h in 0..23)
                let (x = "``h``".pad(2, '0'))
                    "'``x``:00',\n'``x``:30'"
        });
}

```

(104 bytes)

```
shared void run() {
    print(",\n".join(
            (0..23)
                .map((i) => "``i``".pad(2, '0'))
                .map((x) => "'``x``:00',\n'``x``:30'")));
}

```

(111 bytes)

# Answer
> 0 votes
## Burlesque, 30 bytes

Burlesque is sadly rather weak when it comes to formatting because it doesn't have a `printf` (yet).

```
23rzm{2'0lp}":00 :30"wdcp)\[uN

```

Details see here.

# Answer
> 0 votes
## Pyth, 24 bytes

```
V24V2%"'%02d:%d0',",N*3H

```

Run code

```
V24                     for loop 0-23, N counter
  V2                    for loop 0-1, H counter
    %                   format string
      "'%02d:%d0',"     source string
      ,                 begin list tuple
        N               first element, hour
        *3H             second element, minutes

```

Every second iteration of the second for loop, `H` is 1, which toggles the minutes digit between 0 and 3.

Interpreted code generated by the debugger:

```
for N in num_to_range(24):
 for H in num_to_range(2):
  imp_print(mod("'%02d:%d0',",[N,times(3,H)]))

```

# Answer
> 0 votes
# PHP, ~~104~~ 96 bytes

```
for($h=$m=0;$h<24;){echo($h||$m?",\n":"")."'".($h<10?0:"")."$h:".($m*3)."0'";if($m)$h++;$m=!$m;}

```
**exploded view**
```
for ($h = $m = 0; $h < 24; ) {
  echo ($h || $m ? ",\n" : "") . "'" . // echoes ",\n" on all but the first loop
       ($h < 10 ? 0 : "") . "$h:" .    // leading 0 for 0:00 - 9:30
       ($m * 3) . "0'";                // :00 if $m=0, :30 if $m=1
  if ($m) $h++;                        // increments $h if :30
  $m = !$m;                            // swaps :00 <-> :30
}

```

# Answer
> 0 votes
# Java 7, 88 bytes

```
void c(){for(int i=0;i<48;)System.out.printf("'%02d:%s0'%s",i/2,i%2*3,i++<47?",\n":"");}

```

Shorter than the other three Java answers: 93 bytes & 94 bytes & 119 bytes

**Explanation:**

```
void c(){                  // Method
  for(int i=0;i<48;)       //  Loop from 0 to 48 (exclusive)
    System.out.printf(     //   Print with format:
      "'%02d:%s0'%s",      //    "'##:#0'X" (where `#` is a digit, and `X` is a String)
      i/2,                 //    (%02d) Current index divided by 2 and automatically floored
      i%2 * 3              //    (%s0) i%2 is either 0 or 1 (multiplied by 3 is either 0 or 3)
      i++<47 ? ",\n" : ""  //    (%s) A comma and new-line, unless it's the final line
                           //  End of loop
}                          // End of method

```

Try it here.

# Answer
> 0 votes
# AHK, 96 bytes

```
t=20000101000000
Loop,48{
FormatTime,i,%t%,HH:mm
Send,'%i%',`n
EnvAdd,t,30,Minutes
}
Send,{BS 2}

```

AHK does not play nicely with time values so I have to store two variables: one to track the time in the format `YYYYMMDDHH24MISS` and another just to store the pretty text in the format `HH:MI`.

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


# Question
Title: Change text gravity like the 2048 puzzle
In the game 2048, you have a grid, and you can move the elements in four directions. They all move in that direction as far as they can. For this challenge, you will be given a padded, square 2D string (either with newlines, or a list of strings), like so:

```
ab cd e
 f ghij
      kl
mno p
 q r st
u      v
 w x  y
z
```

or

```
['ab cd e ', ' f ghij ', '      kl', 'mno p   ', ' q r st ', 'u      v', ' w x  y ', 'z       ']

```

The four operations are `left`, `right`, `up`, and `down`. The result of each on the above input:

### Left:

```
abcde
fghij
kl
mnop
qrst
uv
wxy
z
```

or

```
['abcde   ', 'fghij   ', 'kl      ', 'mnop    ', 'qrst    ', 'uv      ', 'wxy     ', 'z       ']

```

### Right:

```
   abcde
   fghij
      kl
    mnop
    qrst
      uv
     wxy
       z
```

or

```
['   abcde', '   fghij', '      kl', '    mnop', '    qrst', '      uv', '     wxy', '       z']

```

### Up:

```
abocdiel
mf ghsjv
un rp k
zq x  t
 w    y

```

or

```
['abocdiel', 'mf ghsjv', 'un rp k ', 'zq x  t ', ' w    y ', '        ', '        ', '        ']

```

### Down:

```

 b    e
af c  j
mn gd k
uq rhitl
zwoxpsyv
```

or

```
['        ', '        ', '        ', ' b    e ', 'af c  j ', 'mn gd k ', 'uq rhitl', 'zwoxpsyv']

```

---

Your goal is to rotate which operation is performed each iteration, performing them on the input `n` times. So if your order is `URDL`, and the input says to start with `D` (`2`, 0-indexed), and you need `5` operations, you perform `D-L-U-R-D`, then print.

## Input:

* A string in a format like above
    + Trailing spaces are not required (but they are probably helpful)
    + It will be at least 2x2
    + Will only contain printable ASCII and spaces (and newlines per your input format)
    + You should theoretically support any length, but memory constraints are okay
* A non-negative integer, `n`, for the number of operations that will be performed
* An integer `0-3` or `1-4`, or a letter `UDLR`, describing the operation to start with.
    + So your program must be able to start or end with any operation
    + You may define them in any order for starting purposes, but it must be a consistent order, so `U` cannot sometimes follow `R` and also sometimes follow `L`.
* Operations must be performed non-trivially
    + You could do operations in the order `LDRU` (left, down, right, up) repeatedly, but not `DLRU` or `UDLR` (because `UD` is the same as `D`, and `LR` is the same just as doing `R`.)

## Output:

* The string after performing the four operations `n` times
* The output format must be the same as your input format
* Trailing spaces are not required (but they are probably helpful)

## Example:

This example uses the order `URDL`.

### Input:

```
10  (number of times operations are applied)
0   (starts with Up)

```

```
ab cd e
 f ghij
      kl
mno p
 q r st
u      v
 w x  y
z
```

### Outputs for n = 0-5: (just print the end result)

```
ab cd e
 f ghij
      kl
mno p
 q r st
u      v
 w x  y
z
---------------
abocdiel
mf ghsjv
un rp k
zq x  t
 w    y

---------------
abocdiel
 mfghsjv
   unrpk
    zqxt
      wy

---------------

      el
    dijv
   chspk
 bognrxt
amfuzqwy
---------------

el
dijv
chspk
bognrxt
amfuzqwy
---------------
eljvkxty
disprqw
chgnz
bofu
am

```

My pretty, ungolfed implementation

# Answer
> 2 votes
# Jelly, 23 bytes

```
UZ
Ç¡=⁶$Þ€Ç$⁴¡ZU$⁵+⁴¤¡Y

```

Try it online!

I'm a bit unsatisfied, but MATL needed some competition. :P

Uses the order `URDL`. Inputs:

* the input array as an array of padded lines
* the number of repetitions
* the move to start from (1 = `U`, 2 = `R`, 3 = `D`, 4 = `L`)

### Explanation

```
UZ       Helper link. Argument: A (the 2D array)
U        Reverse each line and...
 Z       ...transpose. Rotates 90° CCW.

Ç¡=⁶$Þ€Ç$⁴¡ZU$⁵+⁴¤¡Y    Main link. Arguments: A, n (2D array, repetitions)
Ç                       Rotate 90° CCW...
 ¡                      ...m times. (m = which move to start on)

     Þ                  Sort...
      €                 ...each line of the array...
  =⁶                    ...based on the characters' equality to " ".
       Ç                Rotate 90° CCW.
        $               Combine the sort and rotate to one action.
         ⁴¡             Do that n times. (n = repetition count)

           Z            Transpose and...
            U           ...reverse each line. Rotates 90° CW.
             $          Combine the transpose and reverse to one action.
                  ¡     Do that...
              ⁵+⁴¤      ...m + n times.

                   Y    Join the array by newlines.

```

# Answer
> 2 votes
## JavaScript (ES6), 168 bytes

```
(n,d,s,t=s.replace([RegExp(`( )([^]{${l=s.search`
`}})(\\w)`),/(.)(\b)( )/,RegExp(`(\\w)([^]{${l}})( )`),/( )(\b)(.)/][d%4],`$3$2$1`))=>n?t!=s?f(n,d,t):f(n-1,d+1,s):s

```

Ungolfed:

```
function gravity(count, direction, string) {
    let width = string.indexOf('\n');
    let up = new RegExp('( )([^]{' + width + '})(\\w)');
    let down = new RegExp('(\\w)([^]{' + width + '})( )');
    while (count--) {
        let regexp = [up, /(.)(\b)( )/, down, /( )(\b)(.)/][direction++ % 4];
        while (regexp.test(string)) string = string.replace(regexp, '$3$2$1');
    }
    return string;
}

```

`d` is the initial index into the directions which are `URDL`.

# Answer
> 1 votes
# Python 2, ~~226~~ ~~224~~ ~~204~~ 193 bytes

<sup>-1 byte thanks to Trelzevir</sup>

```
x,s,n=input()
j=''.join
g=lambda x,i:[eval("j(_.split(' ')).%sjust(len(_))"%'lr'[i%2])for _ in x]
for i in([0,3,1,2]*n)[s:s+n]:x=[map(j,zip(*g(map(j,zip(*x)),i))),g(x,i)][i>1];print'\n'.join(x)

```

Try it online!

Function that remove all spaces of each element in the list and complete with spaces on left or right.

```
g=lambda x,i:[eval("''.join(_.split(' ')).%sjust(len(_))"%'lr'[i%2])for _ in x]

```

This to transpose (rotate 90º) when the input is `0` or `1`(`U` or `D`) and apply `g`

```
x=[map(''.join,zip(*g(map(''.join,zip(*x)),i))),g(x,i)][i>1]

```

# Answer
> 1 votes
# MATL, ~~24~~ 23 bytes

```
:+"@X!XJ_JXzJ32>S(c@_X!

```

Order is `URDL`, `1`-based. So `1` is Ù`,`2`is`R\` etc.

Inputs are: number of times, initial direction, char matrix (using `;` as row separator).

Try it online!

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


# Question
Title: Make mathematics with minimal matchsticks
## Meta-background

This was set as a question on Puzzling, and the instant reaction was "well, someone will just solve that by computer". There was a debate about just how complex a program to solve this would have to be. Well, "how complex does this program have to be" is pretty much the definition of , so maybe PPCG can settle the issue?

## Background

A matchstick equation is basically a normal mathematical equation, but where the digits and operators are constructed physically by placing matchsticks onto a table. (The main relevant feature of matchsticks here is that they're fairly rigid and have a constant length; sometimes people use other objects instead, such as cotton swabs.)

For this challenge, we don't need to define specific rules for how the matchsticks are arranged (like the linked challenge does); rather, we just care about how many matchsticks we'll need to represent an expression that evaluates to a given number.

## The task

Here's an alphabet of digits and mathematical operators you can use, each having a cost in matchsticks:

* `0`, costing 6 matchsticks
* `1`, costing 2 matchsticks
* `2`, costing 5 matchsticks
* `3`, costing 5 matchsticks
* `4`, costing 4 matchsticks
* `5`, costing 5 matchsticks
* `6`, costing 6 matchsticks
* `7`, costing 3 matchsticks
* `8`, costing 7 matchsticks
* `9`, costing 6 matchsticks
* `+`, costing 2 matchsticks
* `-`, costing 1 matchstick
* `×`, costing 2 matchsticks

(You may represent `×` as `*` in your program's output if you wish, in order to avoid needing to use non-ASCII characters. In most encodings, `×` takes up more bytes than `*`, and so I imagine that most programs will want to take advantage of this leeway.)

You need to write a program that takes a nonnegative integer as input (via any reasonable means), and produces an expression that evaluates to that integer as output (again via any reasonable means). Additionally, the expression must be nontrivial: it must contain at least one operator `+`, `-`, or `×`. Finally, the expression you output must be the cheapest (or tied for the cheapest) in terms of total matchstick cost, among all outputs that otherwise comply with the specification.

## Clarifications

* You can form multiple-digit numbers via outputting multiple digits in a row (e.g. `11-1` is a valid output to produce `10`). Just to be completely precise, the resulting number gets interpreted in decimal. This sort of concatenation isn't an operation that works on intermediate results; only on literal digits that appear in the original expression.
* For the purpose of this challenge. `+`, `-`, and `×` are infix operators; they need an argument to their left and to their right. You aren't allowed to use them in prefix position like `+5` or `-8`.
* You don't have parentheses (or any other way to control precedence) available. The expression evaluates according to the typical default precedence rules (multiplications happen first, and then the additions and subtractions are evaluated left to right).
* You don't have access to any mathematical operators or constants other than the ones listed above; "lateral thinking" solutions are often accepted at Puzzling, but it doesn't make sense to require a computer to come up with them itself, and over here on PPCG, we like it to be objective whether or not a solution is correct.
* The usual integer overflow rules apply: your solution must be able to work for arbitrarily large integers in a hypothetical (or perhaps real) version of your language in which all integers are unbounded by default, but if your program fails in practice due to the implementation not supporting integers that large, that doesn't invalidate the solution.
* If you use the same digit or operator more than once, you have to pay its matchstick cost each time you use it (because, obviously, you can't reuse the same physical matchsticks in two different locations on the table).
* There's no time limit; brute-force solutions are acceptable. (Although if you have a solution that's faster than brute force, feel free to post it even if it's longer; seeing how alternative approaches compare is always interesting.)
* Although writing an explanation of your code is never *required*, it's likely to be a good idea; solutions are often very hard to read (especially to people not familiar with the language they're written in), and it can be hard to evaluate (and thus vote on) a solution unless you understand how it works.

## Victory condition

As a challenge, answers with fewer bytes are considered better. However, as usual, feel free to post answers with different approaches, or in specific languages even if they're more verbose than certain other languages; the goal of golf is really to see how far you can optimize a particular program, and doing things this way gives us lots of potential programs to optimize. So don't be discouraged if someone submits a solution using a completely different approach, or a completely different language, and gets a much shorter answer; it may well be that your answer is better-optimized and shows more skill, and voters on PPCG often appreciate that.

# Answer
> 1 votes
# PHP, 241 Bytes

Online Version

```
function m($i){for(;$s<strlen($i);)$e+="6255456376"[$i[$s++]];return$e;}foreach($r=range(0,2*$a=$argv[1])as$v)foreach($r as$w)$x[$v+$w]["$v+$w"]=$x[$v*$w]["$v*$w"]=1+$x[$v-$w]["$v-$w"]=m("$v")+m("$w")+1;echo array_search(min($x[$a]),$x[$a]);

```

## Breakdown

```
function m($i){
    for(;$s<strlen($i);)$e+="6255456376"[$i[$s++]];return$e; #return the count of the matchstick for an integer
}

foreach($r=range(0,2*$a=$argv[1])as$v) # limit to an input to 300 in the online version
foreach($r as$w)
       $x[$v+$w]["$v+$w"]=  #fill the 2D array in the form [result][expression] = count matchsticks
       $x[$v*$w]["$v*$w"]=
       1+$x[$v-$w]["$v-$w"]=
       m("$v")+m("$w")+1;
echo $k=array_search(min($x[$a]),$x[$a]); # Output expression with a minium of matchsticks
echo"\t".$x[$a][$k]; #optional Output of the count of the matchsticks

```

Way with a little better performance

```
function m($i){
for(;$s<strlen($i);)
$e+="6255456376"[$i[$s++]];return$e;} #return the count of the matchstick for an integer
foreach($r=range(0,2*$a=$argv[1])as$v)
foreach($r as$w){$c=m("$v")+m("$w")+1;
if($a==$v+$w)$x["$v+$w"]=1+$c; # fill array if value equal input
if($a==$v*$w)$x["$v*$w"]=1+$c;
if($a==$v-$w)$x["$v-$w"]=$c;}
echo $k=array_search(min($x),$x); # Output expression with a minium of matchsticks
    echo"\t".$x[$k]; #optional Output of the count of the matchsticks

```

## Support of negative integers

Version with negative integers

```
function m($i){
    $e=$i<0?1:0; # raise count for negative integers
    for($s=0;$s<strlen($i);)$e+=[6,2,5,5,4,5,6,3,7,6][$i[$s++]];return$e; #return the count of the matchstick for an integer
}
$q=sqrt(abs($argv[1]));
$l=max(177,$q);
$j=range(-$l,$l); # for second loop for better performance
foreach($r=range(min(0,($a=$argv[1])-177),177+$a)as$v)
foreach($j as$w){$c=m("$v")+m("$w")+1;
    if($a==$v+$w)$x["$v+$w"]=1+$c; # fill array if value equal input
    if($a==$v*$w)$x["$v*$w"]=1+$c;
    if($a==$v-$w)$x["$v-$w"]=$c;
    if($a==$w-$v)$x["$w-$v"]=$c; # added for integers <0
}
echo $k=array_search(min($x),$x); # Output expression with a minium of matchsticks
echo"\t".$x[$k]; #optional Output of the count of the matchsticks

```

# Answer
> 1 votes
## Python2, 1̶9̶8̶ ̶b̶y̶t̶e̶s̶ 182 bytes thanks to math\_junkie

```
def f(n,c=dict(zip('0123456789+-*',map(int,'6255456376212'))),e=[(0,'')]):
 while 1:
    v=(m,s)=min(e);e.remove(v)
    try:
     if eval(s)==n:return s
    except:0
    e+=[(m+c[x],s+x)for x in c]

```

This algorithm does nothing to exclude prefix versions of `+` and `-`, but they will either be worse than, or equal to and appear later in the search, their infix counterparts. Because it uses the keyword argument `e` mutably, it will give invalid results if called multiple times per session. To fix this, use `f(n, e=[(0,'')])` instead of just `f(n)`. Note that the four-spaced indents represent tabs, so this will only work with Python 2.

I also have an ungolfed and optimized version which runs quickly even for quite large numbers:

```
from heapq import heappop, heappush

def f(n):
    digits = list('0123456789')
    ops =['+','-','*','']
    costs = dict(zip(digits + ops, [6,2,5,5,4,5,6,3,7,6,2,1,2,0]))
    expressions = [(costs[d], abs(n - int(d)), int(d), d) for d in digits[1:]]
    seen = set()
    while 1:
        cost, d, k, expression = heappop(expressions)
        if d == 0:
            return expression
        for op in ops:
            if op in '+-' and k in seen:
                continue
            for digit in digits:
                if op and digit == '0':
                    continue
                expression1 = expression + op + digit
                k1 = eval(expression1)
                d1 = abs(n - k1)
                if d1 == 0:
                    return expression1
                heappush(expressions, (cost+costs[op]+costs[digit], d1, k1, expression1))
        seen.add(k)

```

---
Tags: code-golf, arithmetic, expression-building
---


title: Island Golf #1: Circumnavigation

text:
# Question
Title: Island Golf #1: Circumnavigation
<sup>*This is the first in a series of Island Golf challenges. Next challenge*</sup>

Given an island in ASCII-art, output an optimal path to circumnavigate it.

## Input

Your input will be a rectangular grid consisting of two characters, representing land and water. In the examples below, land is `#` and water is `.`, but you may substitute any two distinct characters you wish.

```
...........
...##......
..#####....
..#######..
.#########.
...#######.
...#####.#.
....####...
...........

```

There will always be at least one land tile. The land tiles will all be contiguous (i.e. there's only one island). The water tiles will also be contiguous (i.e. there are no lakes). The outer border of the grid will all be water tiles. Land tiles will **not** be connected diagonally: i.e., you will never see something like

```
....
.#..
..#.
....

```

## Output

Your code must output the same grid, with a *shortest circumnavigation* drawn on it. In the examples below, the circumnavigation path is drawn with `o`, but you may substitute any character as long as it is distinct from your land and water characters.

A *circumnavigation* is a simple closed curve, drawn entirely on water tiles, that fully encircles all land tiles on the grid. Diagonal connections **are** allowed. For instance, this is a circumnavigation of the above island (but not a shortest one):

```
.ooooo.....
o..##.oo...
o.#####.o..
o.#######o.
o#########o
ooo#######o
..o#####.#o
..oo####..o
....oooooo.

```

The length of a circumnavigation is computed as follows: For every pair of adjacent tiles on the path, if they are connected horizontally or vertically, add 1; if they are connected diagonally, add √2. The length of the above path is 22 + 7√2 (≈ 31.9).

A *shortest* circumnavigation is a circumnavigation with the shortest possible length. Your program should output any one path that satisfies this condition. For most islands, there will be multiple possible solutions. Here is one solution for the above island, with length 10 + 13√2 (≈ 28.4):

```
...oo......
..o##oo....
.o#####oo..
.o#######o.
o#########o
.o.#######o
..o#####.#o
...o####.o.
....ooooo..

```

## Details

Your solution may be a full program or a function. Any of the default input and output methods are acceptable.

Your input and output may be a multiline string or a list of strings. **If** your language has a character type distinct from single-character strings, you may substitute "list of characters" for "string" in the previous sentence. If your language needs to input the height and/or width of the grid, you may do so. Your output may (optionally) have a single trailing newline. As mentioned above, you may use any three distinct characters in place of `#.o` (please specify in your submission which characters you're using).

## Test cases

**A.** Islands with unique shortest circumnavigations:

```
...
.#.
...

.o.
o#o
.o.

......
.####.
......

.oooo.
o####o
.oooo.

......
......
..##..
...#..
......
......

......
..oo..
.o##o.
..o#o.
...o..
......

.......
.#####.
...#...
...#...
.#####.
.......

.ooooo.
o#####o
o..#..o
o..#..o
o#####o
.ooooo.

.......
...#...
...#...
.#####.
...#...
...#...
.......

...o...
..o#o..
.o.#.o.
o#####o
.o.#.o.
..o#o..
...o...

.......
.#####.
.##..#.
..#..#.
.......

.ooooo.
o#####o
o##..#o
.o#..#o
..oooo.

```

**B.** Example of an island with multiple possible solutions:

```
........
....##..
...####.
..###...
.#####..
.#####..
..##....
........

```

Possible outputs:

```
....oo..
...o##o.
..o####o
.o###.o.
o#####o.
o#####o.
.o##oo..
..oo....

....oo..
...o##o.
..o####o
.o###.o.
o#####o.
o#####o.
.o##.o..
..ooo...

....oo..
...o##o.
..o####o
.o###..o
o#####.o
o#####o.
.o##oo..
..oo....

....oo..
...o##o.
..o####o
.o###..o
o#####.o
o#####o.
.o##.o..
..ooo...

```

**C.** Large test case as a Gist

---

This is : the shortest code in each language wins.

# Answer
> 18 votes
## Mathematica (version 9), 165 bytes

The nice, short `ConvexHullMesh` function that Greg Martin used was only introduced in Mathematica version 10, so I thought I'd make an attempt without it, using my ancient Mathematica version 9. I managed to get it slightly shorter, though! It's a function that takes and returns a list of strings (with `.`, `#` and `o` as the symbols).

```
""<>#&/@("o"MorphologicalTransform[MorphologicalComponents[#,Method->"ConvexHull"],Max[#(1-#[[2,2]])CrossMatrix@1]&]+"#"#/.{0->"."})&[Characters@#/.{"."->0,"#"->1}]&

```

Explanation:

* First, `Characters@# /. {"."->0, "#"->1}` turns the input into a matrix of `0`s and `1`s.
* `"o"MorphologicalTransform[MorphologicalComponents[#,Method->"ConvexHull"],Max[#(1-#[[2,2]])CrossMatrix@1]&]+"#"#` then uses Mathematica's powerful (but extremely byte-heavy…) image processing capabilities to first fill in the island's convex hull (which is the shape you'd get if you stretched a piece of string around it), and then take its boundary. We then multiply this matrix by the string `"o"` to get a matrix of `0`s and `"o"`s (thanks to Mathematica's impressive adaptability about types), and add this to `"#"` times the matrix of the island.
* Finally, `""<>#& /@ (... /. {0->"."})` turns this matrix of `"o"`s, `"#"`s and `0`s into a matrix of `"o"`s, `"#"`s and `"."`s, and joins each row into a string.

When we test this on example **B**, we get the output

```
{"....oo..",
 "...o##o.",
 "..o####o",
 ".o###..o",
 "o#####o.",
 "o#####o.",
 ".o##oo..",
 "..oo...."}

```

\[Edit, thanks to Greg Martin:\] If we're allowed to use arrays of characters instead of lists of strings, we can trim this down to 144 bytes:

```
"o"MorphologicalTransform[MorphologicalComponents[#,Method->"ConvexHull"],Max[#(1-#[[2,2]])CrossMatrix@1]&]+"#"#/.{0->"."}&[#/.{"."->0,"#"->1}]&

```

# Answer
> 11 votes
(But go upvote Notatree's solution, it's better!)

# Mathematica, 168 bytes

```
(x_~n~y_:=Min[Norm[x-#]&/@y];i=#;p=i~Position~#&;t=p["#"|"."]~Select~#&;(i~Part~##="o")&@@@t[#~n~t[ConvexHullMesh[Join[s=p@"#",#+{.1,.1}&/@s]]~RegionMember~#&]==1&];i)&

```

Pure function taking a 2D array of characters as input and returning a 2D array of characters. An easier-to-read version:

```
1  (x_~n~y_ := Min[Norm[x - #] & /@ y];
2  i = #; p = i~Position~# &;
3  t = p["#" | "."]~Select~# &;
4  (i~Part~## = "o") & @@@
5    t[#~n~
6      t[ConvexHullMesh[
7        Join[s = p@"#", # + {.1, .1} & /@ s]]
8      ~RegionMember~# &] == 1 &];
9  i) &

```

Line 1 defines a function `n` that produces the (smallest) distance between a point `x` in the plane and a set `y` of other points. Line 2 initializes the variable `i` to the input, both to resolve a currying ambiguity later and to be able to modify it to produce the eventual output; line 2 also defines a function `p` that returns the coordinates of all occurrences of its input in `i`.

On line 3, `p["#" | "."]` represents every single coordinate from the input map (since all its characters are either `"#"` or `"."`), so `t` is a function that selects only those coordinates that satisfy a yet-unspecified property. On line 4, `i~Part~## = "o"` is going to change a bunch of entries of `i` to the character `"o"`; those characters will be selected from the set of possible coordinates according to the stuff on lines 5-8. And line 9 just returns the answer once it's computed.

Okay, infrastructure done, now to the actual computation. `ConvexHullMesh` is Mathematica's built-in for computing the convex hull of a set of points (the smallest convex polygon containing those points). Morally speaking, this should "fill in" the coves and fjords of the island (which is `s = p@"#"`), to rule them out of our cicrumnavigation. There's a little problem with `ConvexHullMesh` when that set of points is all in a line (thank you, test case #2), which we resolve by appending a slightly offset version of `s` to itself in line 7. This output is a polygon, so lines 7-9 (`t[...~RegionMember~# &]`) produces a list of the points with integer coordinates in that polygon. Finally, line 5 and the end of line 9 calculate all points that are at a distance exactly 1 (hence not 0) from this set of integer points; that set becomes the circumnavigating path.

Below is the output for the large test case at the OP's link. Notice at the upper left, the unusual choices of when to go west versus southwest hint at the fact that it's shadowing an invisible line of slope -2/3 between two peninsulas (said line segment being part of the convex hull's boundary).

```
........................
.............o..........
...........oo#ooooooo...
..........o#.#.##...#o..
........oo.#.#.###.##o..
.......o..########.##o..
.....oo...############o.
...oo#....############o.
..o#.###.##############o
.o##.##################o
.o####################o.
.o.##################.o.
.o##################..o.
.o..################..o.
o###################..o.
o#####################o.
o.##################.o..
o####################o..
o#...##############.o...
o##...#############o....
o#.....###....#oooo.....
.oooooo#ooooooo.........
.......o................

```

# Answer
> 10 votes
# Python 3, 779 bytes (indenting with tabs)

This is the whole program. It reads input from stdin and prints it to stdout. Stdin must end with EOF. Example run with the big input: https://ideone.com/XIfYY0

```
import itertools,sys
L=list
C=itertools.count
d=L(map(L,filter(None,sys.stdin.read().split('\n'))))
X=len(d[0])
Y=len(d)
R=range
def P(r):return all(d[y][x]=='.'for x,y in r)
def S(f):
    for n in C(0):
        if P(f(n)):l=n
        else:break
    for n in C(l+1):
        if P(f(n)):return l,n
def f(V,a,*b):return L(eval('lambda '+a+':('+i+')',V)for i in b)
V=locals()
def D(n):
    y=min(n,Y-1);x=n-y
    while y>=0and x<X:yield(x,y);x+=1;y-=1
def E(n):
    x=max(0,n-Y);y=x+Y-n
    while y<Y and x<X:yield(x,y);x+=1;y+=1
F=f(V,'p','(p,y)for y in R(0,Y)','(x,p)for x in R(0,X)')+[D,E]
r=f(V,'x,y','x','y','x+y','x-y+Y')
B=L(map(S,F))
for x in R(0,X):
    for y in R(0,Y):
        z=L(zip(r,B))
        if all(g(x,y)in R(a,b+1)for g,(a,b)in z)and any(g(x,y)in e for g,e in z):d[y][x]='o'
print('\n'.join(''.join(x)for x in d))

```

The idea is simple: it computes smallest octagonal bounds, and draws cells which are inside all of the computed bounds and intersect at least one of the edges.

# Answer
> 8 votes
## JavaScript (ES6), ~~369~~ 343 bytes

```
f=s=>(a=s.split`
`.map(s=>[...s]),m=Array(8),a.map((b,i)=>b.map((c,j)=>c>'#'||[i-j,i,j+i,j,j-i,-i,-i-j,-j].map((d,k)=>d>m[k]||(m[k]=d-1)))),[o,p,q,r,t,u,v,w]=m,g=(i,j,k,l,...p)=>i-k|j-l?a[i][j]=g(i+(k>i)-(k<i),j+(l>j)-(l<j),k,l,...p):1/p[0]?g(k,l,...p):'o',g(p,p-o,p,q-p,q-r,r,r-t,r,-u,t-u,-u,u-v,w-v,-w,o-w,-w,p,p-o),a.map(b=>b.join``).join`
`)

```

Explanation: The string is split into a character array (I'm unclear as to whether character array input is acceptable). The array is then iterated over and the positions of all the land squares are located. The bounding lines given by the equations `x - y = o`, `x = p`, `x + y = q`, `y = r`, `y - x = t`, `-x = u`, `-x - y = v`, `-y = w` are determined such that the maximum possible parameter is chosen where all the land lies beyond the line. This has the effect of enclosing the island in an octagon. The coordinates of the corners of the octagon are readily calculated from the parameters and the cells on its edge are filled in. The array is then joined back into a string. The reason an octagon suffices is as follows:

```
   /o#     /o#     /o#
 |/o #   |/o #   |/ o#
 *o###   * o #   *  o#
/|o #   /|o #   /| o#
 |o#     |o#     |o#

```

Consider a corner of the octagon. At some point along the two edges the path will be limited by the land because we constructed the octagon to touch the land as closely as possible. If there is no land at the corner itself, the path could take the alternate routes as shown on the right, but that is still the same number of orthogonal and diagonal steps, so the distance is unchanged.

# Answer
> 6 votes
# Python 3.5, ~~224, 263, 234~~ 218 bytes

Golfed off another 16 bytes by getting rid of the nested function and making it a one-liner.

```
def h(s,k=0,i=0):w=s.find('\n')+1;x=s.find('X')-w;k=k or x;d=[1,w+1,w,w-1,-1,-w-1,-w,-w+1]*2;u=s[:k]+'o'+s[k+1:];return['X'>s[k]and i<8and(h(u,k+d[i+2],i+2)or h(u,k+d[i+1],i+1)or h(u,k+d[i],i))or'',s][s[k]>'X'and k==x]

```

Golfed off 29 bytes:

```
def f(s):
 w=s.find('\n')+1;x=s.find('X')-w;d=[1,w+1,w,w-1,-1,-w-1,-w,-w+1]*2
 def h(s,k,i):u=s[:k]+'o'+s[k+1:];return['X'>s[k]and i<8and(h(u,k+d[i+2],i+2)or h(u,k+d[i+1],i+1)or h(u,k+d[i],i))or'',s][s[k]>'X'and k==x]
 return h(s,x,0)

```

Input is a single string using '~' for ocean, 'X' for land, and 'o' for the boundary. (Using 'X' saves a byte for '\>' instead of '==')

Less golfed version with comments:

```
def f(s):
    w=s.find('\n')+1                         # width of one row
    x=s.find('X')-w                          # starting point
    d=[1,w+1,w,w-1,-1,-w-1,-w,-w+1]*2        # delta to add to current index to move in
                                             # the 8 directions: E, SE, S, SW, W, NW,
                                             # N, NE. Make it long to avoid
                                             # lots of modulo operations in
                                             #    the recursive calls

    def h(s,k,i):                            # s is the island string, k the current
                                             # position, i the direction index
        if s[k]>'X'and k==x:                 # if back at the begining,
            return s                         #   return the map

        elif 'X'>s[k] and i<8:               # if there is water here, and haven't
                                             #  looped around,
            u=s[:k]+'o'+s[k+1:]              #  make a new map with an 'o' in the
                                             #  current spot

            r = h(u,k+d[i+2],i+2)            # try a 90 degree right turn
            if r: return r

            r = h(u,k+d[i+1],i+1)            # try a 45 degree turn
            if r: return r

            r= h(u,k+d[i],i)                 # try straight ahead
            if r: return r

        return ''                            # this path failed

    return h(s,x,0)

```

# Answer
> 5 votes
# C# 7 - ~~414~~ ~~369~~ 327 bytes

***Edit****: switched to 1D looping, computing `i` and `j` on the fly*

***Edit****: changed input method, collapsed lookup table, and switched to well defined initial bounds ...and removed the pointless space in the last outer for-loop*

```
using C=System.Console;class P{static void Main(){var D=C.In.ReadToEnd().Replace("\r","");int W=D.IndexOf('\n')+1,H=D.Length,z=H,k,q,c;int P()=>z%W*(k%3-1)+z/W*(k/3-1)+H;var B=new int[9];for(;z-->0;)for(k=9;k-->0&D[z]%7<1;)if(B[k]<=P())B[k]=P()+1;for(;++z<H;C.Write(q>9?'o':D[z]))for(q=k=9;k-->0;)q*=(c=P()-B[k])>0?0:c<0?1:2;}}

```

Try It Online

Complete program, takes input to standard in, prints it to standard out, uses `#`, `.`, and `o`. For each cell, it computes a 'profile' (which is the distance over 8 directions (it appears to compute a ninth for convenience, but this is always `0`), and records a maximum of each of these. It then writes out the whole map again, and replaces any cell which is both on a boundary and not outside any with a 'o'. The commented code below explains how it all works.

As per my answer to Save the Geese from Extinction, this produces the smallest octagon (valid circumnavigation with largest area) which bounds the island.

***Note****: that for once in my life I'm using something from the current decade, and this code requires C# 7 to compile. If you do not have C# 7, there is one line that will need to be replaced, which is clearly marked in the code.*

Example usage and output:

```
type t7.txt | IslandGolf1.exe

.........ooooooooooo....
........o....#......o...
.......o...#.#.##...#o..
......o....#.#.###.##.o.
.....o....########.##..o
....o.....############.o
...o.#....############.o
..o#.###.##############o
.o##.##################o
o.####################.o
o..##################..o
o.##################...o
o...################...o
o###################...o
o#####################.o
o.##################..o.
o####################o..
o#...##############.o...
o##...#############o....
o#.....###....#...o.....
.o.....#.........o......
..ooooooooooooooo.......

```

Formatted and commented code:

```
using C=System.Console;

class P
{
    static void Main()
    {
        // \n 10
        // # 35
        // . 46
        // o 111

        var D=C.In.ReadToEnd().Replace("\r",""); // map

        int W=D.IndexOf('\n')+1, // width
            H=D.Length, // length
            z=H, // position in map (decomposed into i and j by and for P)
            k, // bound index
            q, // bound distance, and later cell condition (0 -> outside, 8 -> inside, >8 -> on boudary)
            c; // (free), comparison store

        // 'indexes' into a profile for the point z at index k
        // effectively {i=z%W,j=z/W,-i,-j,i+j,j-i,-i-j,i-j,0}[k] (inside order is a bit different) (0 const is always treated as 'inside bounds')
        // each non-zero-const entry describes the distance in one of the 8 directions: we want to maximise these to find the 'outer bounds'
        // the non-zero-const bounds describe 8 lines, together an octogen
        int P()=>z%W*(k%3-1)+z/W*(k/3-1)+H; // new C#7 local method syntax (if you don't have C#7, you can test this code with the line below instead)
        //k=0;System.Func<int>P=()=>z%W*(k%3-1)+z/W*(k/3-1)+H; // old lambda syntax (must pre-assign k to make static checker happy)

        var B=new int[9]; // our current bounds, each is initially null (must only call P() when on a #)
        // B[k] starts off a 0, P() has a +H term, and W+(H/W)<H for W >= 3, so B[k] is assigned the first time we compare it (H-i-j always > 0)

        for(;z-->0;) // for each cell
            for(k=9;k-->0& // for each bound
                D[z]%7<1;) // if this cell is #
                if(B[k]<=P())B[k]=P()+1; // update bound if necessary (add one so that we define the bound _outside_ the hashes)
        // z=-1
        for(;++z<H; // for each cell
                C.Write(q>9?'o':D[z])) // print the cell (if q > 9, then we are on the bounds, otherwise, spit out whatever we were before)
            // check we are not 'outside' any of the bounds, and that we are 'on' atleast one of them
            for(q=k=9;k-->0;) // for each bound
                q*=(c=P()-B[k])>0?0: // outside bound (q=0)    (??0 is cheaper than (int) or .Value)
                    c<0?1: // inside (preserve q)
                    2; // on bound (if q != 0, then q becomes > 9)
    }
}

```

---
Tags: code-golf, ascii-art, grid, path-finding, optimization
---


title: Convert Binary to Text

text:
# Question
Title: Convert Binary to Text
Your task is to write a program, which takes a binary input and converts it to plain text. For Example:

```
01100001 01100010 01100011 = "abc"

```

## Rules

* Input can come from STDIN, function arguments, command line argument, file, whatever suits you.
* The program can be a function, full program, whatever works, really, as long as no external uncounted code/arguments are needed to run it.
* You can assume that the input is valid.
* The length of the input is **not** limited
* You can assume that all blocks are seperated with whitespaces

## Test Cases

```
01010100 01100101 01110011 01110100 = "Test"
01001000 01100101 01101100 01101100 01101111 = "Hello"
01010111 01101111 01110010 01101100 01100100 00001101 00001010 = "World"
01000101 01111000 01100001 01101101 01110000 01101100 01100101 00001101 00001010 = "Example"
01100010 01101001 01101110 00001101 00001010 = "bin"

```

This is , so the shortest solution wins.

# Answer
> 3 votes
# 05AB1E, 4 bytes

```
#CçJ

```

Uses the **CP-1252** encoding. Try it online!

# Answer
> 4 votes
# dc, 4 bytes

Needs as input the binary blocks with no separator. This is allowed by the OP.

```
2i?P

```

**Try it online!**

**Explanation:** using the "abc" example as test case

* `2i?` sets 2 as input radix, then reads the line (output radix is 10 by default). This converts the binary input to decimal: 011000010110001001100011 -\> 6382179.
* `P` is a special printing mode that assumes a base 256 number, using its "digits" as ASCII codes: 6382179 = (**97** * 256 2) + (**98** * 256 1) + (**99** * 256 0) -\> **abc**

# Answer
> 3 votes
# Perl 5, 15 bytes

14 bytes of code + `-p` flag.
The input must be supplied *without* final newline (with `echo -n` for instance).

```
$_=pack"B*",$_

```

Try it online!

# Answer
> 2 votes
## JavaScript (ES6), 52 bytes

```
s=>String.fromCharCode(...s.split` `.map(s=>`0b`+s))

```

# Answer
> 2 votes
## sed and dc, 23, 19 bytes

```
sed 's/.*/2i&P/'|dc

```

# Answer
> 1 votes
# Pyth, 7 Bytes

```
smCid2c

```

Takes input as string.

Try it!

# Answer
> 1 votes
## Python 2, 49 bytes

Try it online

```
lambda S:''.join(chr(int(c,2))for c in S.split())

```

# Answer
> 1 votes
# RProgN 2, 10 bytes

```
û{$-2Bo}r.

```

# Explained

```
û          # Split the implicit input by Spaces.
 {     }r  # Replace each element in a list based on a function.
  $-2B     # Convert from Base 2
      o    # Get the ordinal of the character.
         . # Concatenate the list.

```

Try it online!

# Answer
> 1 votes
## CJam, 10 bytes

```
l:~8/2fb:c

```

Try it online!

### Explanation

```
l    e# Read input.
:~   e# Evaluate each character, resulting in a flat list of bits.
8/   e# Split into chunks of 8 bits.
2fb  e# Convert each from binary to an integer.
:c   e# Convert each integer to a character.

```

# Answer
> 1 votes
## Mathematica, 50 bytes

```
FromCharacterCode[#~FromDigits~2&/@StringSplit@#]&

```

# Answer
> 1 votes
# Röda, ~~36~~ 35 bytes

```
{split|chr parseInteger(_,radix=2)}

```

Try it online!

This is an anonymous function that reads the input from the stream and prints the result.

It uses three builtins:

* `split` splits the input at whitespaces
* `parseInteger` converts a binary string to an integer value
* `chr` converts an integer to a Unicode character

# Answer
> 1 votes
# Gema, 33 characters

```
<D><s>=@int-char{@radix{2;10;$1}}

```

Sample run:

```
bash-4.3$ gema '<D><s>=@int-char{@radix{2;10;$1}}' <<< '01010000 01010000 01000011 01000111'
PPCG

```

## Gema, 31 characters

Using no delimiter in the input.

```
<D8>=@int-char{@radix{2;10;$1}}

```

Sample run:

```
bash-4.3$ gema '<D8>=@int-char{@radix{2;10;$1}}' <<< '01010000010100000100001101000111'
PPCG

```

# Answer
> 1 votes
# Ruby, 36 characters

```
->b{b.gsub(/\d+ ?/){$&.to_i(2).chr}}

```

Sample run:

```
irb(main):001:0> ->b{b.gsub(/\d+ ?/){$&.to_i(2).chr}}['01010000 01010000 01000011 01000111']
=> "PPCG"

```

# Answer
> 1 votes
## PHP \<5.3, 53 Bytes

Idea by @manatwork

```
foreach(split(" ",$argv[1])as$v)echo chr(bindec($v));

```

# PHP, 55 Bytes

I prefer cause it can work without spaces

```
foreach(str_split($argv[1],9)as$v)echo chr(bindec($v));

```

without spaces change `9` to `8` for 7 bits `7`

```
foreach(explode(" ",$argv[1])as$v)echo chr(bindec($v));

```

## PHP \>=7, 62 Bytes

```
<?=join(($a=array_map)(chr,$a(bindec,explode(" ",$argv[1]))));

```

# Answer
> 1 votes
# C (clang), 43 bytes

```
f(**v){*v&&f(v+!!putchar(strtol(*v,0,2)));}

```

Try it online!

# Answer
> 0 votes
## Jelly, *unfinished*

I still haven't figure out how to `repeat for every line in STDIN`, or get `amount of lines in STDIN` in Jelly. So far though, I came up for a solution for a single line/character.

```
ɠO_48ḄỌ

```

Any help is appreciated!

---
Tags: code-golf, math, binary, conversion
---


title: How much does this Integer score?

text:
# Question
Title: How much does this Integer score?
# The Challenge

Given an integer, calculate its score as described below.

The score is calculated by raising each digit of the input Integer to the power `n`, where `n` denotes the index of the digit in Input (beginning with 1) when counted from left to right (the index of leftmost digit should be 1), and then summing them all together. If the original number happens to be prime, then add the largest digit of the input integer to the score, else subtract the smallest digit of the input integer from it.

# Input

Your program should take an integer as input. You can take the input in whatever way you want to.

# Output

Output the score of the input integer through whatever medium your programming language supports. Function `return` is also allowed.

---

# Test Cases

```
 5328   ->  (5^1)+(3^2)+(2^3)+(8^4)-2 = 4116
 3067   ->  (3^1)+(0^2)+(6^3)+(7^4)+7 = 2627
 7      ->  (7^1)+7                   = 14

```

# Scoring

This is , so the shortest code in bytes wins!

# Answer
# Ohm, ~~17~~ 16 bytes (CP437)

**EDIT**: Fixed so that it checks the input's primality.

```
▓_^≥ⁿ;Σ┼Dp?╧+¿╤-

```

One of these days I need to get around to implementing vectorization. Maybe then I'll finally beat 05AB1E!

Explanation:

```
▓_^≥ⁿ;Σ┼Dp?╧+¿╤-    Main wire: arguments: n

▓    ;              Map the following over all digits of n:
 _^≥ⁿ                 Raise the digit to the (index + 1)th power
      Σ             Push the sum of all that
       ┼Dp          Is n prime?
          ?         If so...
           ╧+         Add the maximum digit of n to the sum
             ¿      Else...
              ╤-      Subtract the minimum digit of n from the sum
                    (Implicit output)

```
> 1 votes

# Answer
# Mathematica, 63 bytes

```
s+Max@If[PrimeQ[s=Tr[d^Range@Length[d=IntegerDigits@#]]],d,-d]&

```

Pure function taking a positive integer as input and returning an integer. Directly performs the indicated computation, with all the long Mathematica command names that requires. Perhaps the one innovation is noticing that, if `d` is the list of digits of the input, then the last addition/subtraction is the same as adding `Max[d]` if the initial sum was prime, and adding `Max[-d]` if not.
> 3 votes

# Answer
# 05AB1E, 16 bytes

```
DpiZëW(}¹gL¹SmO+

```

Try it online!

**Explanation**

```
D                  # duplicate input
 piZ               # if input is prime then max digit of input
    ëW(            # else -min digit of input
       }           # end if
        ¹gL        # range [1 ... len(input)]
           ¹S      # input split into digits
             m     # pow
              O    # sum
               +   # add

```
> 3 votes

# Answer
## Mathematica, 68 bytes

```
#+If[PrimeQ@#,Max@x,-Min@x]&@Tr[(x=IntegerDigits@#)^Range[Tr[1^x]]]&

```

## Explanation

Sets `x` equal to the list of digits of the input, then raises that to the power `Range[Tr[1^x]]`, effectively raising the first digit to the power `1`, the second digit to the power `2`, and so on up to `Tr[1^x]`, the length of `x`. `Tr` sums the resulting list, which is then passed into the function `#+If[PrimeQ@#,Max@x,-Min@x]&`.
> 3 votes

# Answer
# JavaScript, 173 bytes

Add an `f=` at the beginning and invoke like `f(n)`.

```
n=>{k=(n+"").split``;t=k.map((c,i)=>c**(i+1)).reduce((c,p)=>c+p);j=1;for(i=2;i<n;i++){j=n%i||n==2?1:0;if(!j)break}return j?t+Math.max.apply(Math,k):t-Math.min.apply(Math,k)}

```

---

**Explanation**

Takes in an Integer. Converts it into String. Then, converts it into Array. Uses `map` over the Array to make a new array having all its elements raised to their `index+1`th (+1 because JavaScript used zero-based indexes). Then uses `reduce` to sum them all together. Checks whether the obtained number is prime. If it is then it `return`s the obtained number incremented by the largest digit of the Array otherwise `return`s the obtained number decremented by smallest digit of it.

---

**Test Cases**

```
f=n=>{k=(n+"").split``;t=k.map((c,i)=>c**(i+1)).reduce((c,p)=>c+p);j=1;for(i=2;i<n;i++){j=n%i||n==2?1:0;if(!j)break}return j?t+Math.max.apply(Math,k):t-Math.min.apply(Math,k)}

console.log(f(5328));
console.log(f(3067));
console.log(f(7));
console.log(f(123));
console.log(f(1729));
console.log(f(2));
console.log(f(1458));
console.log(f(91));
```
> 2 votes

# Answer
# Python 3: 260 167 bytes

```
def s(n):
 t,l=0,list(str(n))
 for i,d in enumerate(l):t+=int(d)**(int(i)+1)
  for i in range(2,n-1):
   if n%i==0:t-=int(min(l))
  else:t+=int(max(l))
  break
 return t

```

93 bytes saved by Wheat Wizard
> 2 votes

# Answer
# Ruby, 98 bytes

```
->n{i= ~s=0
a=n.digits
a.map{|d|s+=d**(a.size-i+=1)}
s>1&&(2...s).all?{|i|s%i>0}?s+a.max: s-a.min}

```
> 1 votes

# Answer
# PHP, 174 bytes

```
function s($i){$i=str_split($i);foreach($i as $k=>$x){$r+=pow($x,$k+1);}if(p($r)){$r+=max($i);}else{$r-=min($i);}print$r;}function p($n){for($i=$n;--$i&&$n%$i;);return$i==1;}

```

Try it online!
> 1 votes

# Answer
# Python 2, 111 bytes

```
g=lambda n,z=1:n and(n%10)**len(`n`)+g(n/10,0)+int(['-'+min(`n`),max(`n`)][all(n%x for x in range(2,n))*n>1])*z

```

Try it Online!

Recursive function which calculates the sum starting with the last digit.

`n and(n%10)**len(`n`)+g(n/10,1)` is the recursive portion of the function

`int(['-'+min(`n`),max(`n`)][...])*z` returns `0` for all iterations except the first

`all(n%x for x in range(2,n))*n>1]` is the primality test

**Alternate solution (115 bytes):**

```
lambda n:sum(int(j)**(i+1)for i,j in enumerate(`n`))+int(['-'+min(`n`),max(`n`)][all(n%x for x in range(2,n))*n>1])

```

Try it Online!
> 0 votes

# Answer
# Python 3, 118 bytes

```
*a,=map(int,input())
x=sum(n**-~i for i,n in enumerate(a))
print(x+(-min(a),max(a))[all(x%z for z in range(2,x))*x>1])

```

Try it online!

Thanks to @math\_junkie for pointing out a bug.
> 0 votes

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


title: Permutation? Permutatino!

text:
# Question
Title: Permutation? Permutatino!
## Specifications

Your program must can take in an integer `n`, then take in `n` more strings (containing only alphanumeric characters) in your preferred method (separated by whitespace, file input, hash table etc.). You must then find the permutation before the inputted strings when sorted in lexicographical order, and output that in your preferred method.

If it is already sorted in lexicographical order, output the permutation in reverse regular lexicographical order.

### Rules

1. Code can be just a function
2. If you pipe in from a file, you can to exclude the file name's length from your program (just the filename, not full path)
3. If there are repeated characters, take the permutation before the first occurrence of the repeats

### Test cases

```
3 abc hi def

```

The possible permutations of this (in lexicographical order) are:

```
abc def hi
abc hi def
def abc hi
def hi abc
hi abc def
hi def abc

```

Now see that `abc hi def` is the 2nd permutation, so we output `abc def hi`.

If instead we pick `abc def hi`(the first permutation), then output `abc def hi`.

Another test case is in the title: your function should map `Permutation` to `Permutatino`

### Scoring:

The winner is the code with the smallest score, which is the length of the code multiplied by the bonus.

### Bonus:

20% -90% (to keep non-esolangs in the fight) of your byte count if you can do this in O(N) time.

-50% (stacks with the above -90% to give a total of -95%) if your solution isn't O(N!) which is listing out permutations, finding the element and getting the index, subtracting 1 from the index (keep it the same if the index is 0) and outputting the element with the subtracted index

With the above 2 bonuses, I won't be surprised if there's a 2 byte answer.

Hint: there is definitely a faster way to do this apart from listing all the permutations and finding the supposed element in the general case

Congrats to @Forty3 for being the first person to get the O(N) solution!

Here's some (C based) pseudocode:

```
F(A) { // A[0..n-1] stores a permutation of {1, 2, .., n}
  int i, j;
  for (i = n - 1; i > 0 && (A[i-1] < A[i]); i--)
    ; // empty statement
  if (i = 0)
    return 0;
  for (j = i + 1; j < n && (A[i-1] > A[j]); j++)
    ; // empty statement
  swap(A[i-1], A[j-1]); // swap values in the two entries
  reverse(A[i..n-1]); // reverse entries in the subarray
  return 1;
}

```

If you want to test if your program is O(N), try with `n=11` and the strings being the individual letters of `Permutation`. If it takes longer than a second, it's most definitely not O(N).

# Answer
> 4 votes
# Python 2, ~~118~~ 96 - 50% = 48 bytes

Takes input in the form `['abc','def','ghi']`. Note that this solution returns the list reversed if the input is sorted, as per a previous spec.

```
def f(n):m=n[1:];S=sorted;a=S(n);return[a.pop(a.index(n[0])-1)]+a[::-1]if m==S(m)else[n[0]]+f(m)

```

Try it Online!

Seems to be ~~the O(n) solution~~ more efficient than computing all permutations.

**Explanation:** Recursively checks if everything after the current element is in `sorted` order. If so, returns the string immediately lexicographically before (`a.index(n[0])-1)`) the first element `+` the rest of the list reversed (`a[::-1]`).

**Runtime: O(n^2 logn)** In the worst case (list is reversed), the function will call `sorted`, which has a runtime of **nlogn**, for each element in the list (`n` times).

# Answer
> 2 votes
# JavaScript, 460 399 369 332 - 95% = 16.6 bytes

## Unformatted

```
function f(n,v){var i=n-1,c=v[i],z="concat",y="slice",x="indexOf",w="reverse";for(;i>=0&&v[i]<=c;i--){c=v[i];}if(i==-1)return v;if(i==0){let s=v[z]().sort(),t=s[x](v[i])-1;return [s[t]][z]((s[y](0,t)[z](s[y](t+1)))[w]());}let p=v[y](0,i),r=v[y](i)[z]().sort()[w](),t=r[x](v[i])+1,m=r[t];r.splice(t-1,2,v[i]);return p[z]([m])[z](r);}

```

I am not convinced it is the O(n) solution but would appreciate if someone could take a quick glance and let me know. Also, I suspect there is some serious golfing which can be accomplished.. just haven't taken the time (yet).

## Formatted

```
function f2(n, v) {
  var i = n-1,c = v[i],z="concat",y="slice",x="indexOf",w="reverse";
  for ( ; i >= 0 && v[i] <= c; i--) {
    c = v[i];
  }
  if (i == -1) return v;
  if (i == 0) {
    let s = v[z]().sort(), t = s[x](v[i]) - 1;
    return [s[t]][z]((s[y](0, t)[z](s[y](t + 1)))[w]());
  }

  let p = v[y](0,i),
  r = v[y](i)[z]().sort()[w](),
  t = r[x](v[i])+1,
  m = r[t];
  r.splice(t-1,2,v[i]);
  return p[z]([m])[z](r);

}

```

Fiddle: https://jsfiddle.net/n2Lmswxf/8/

Edit 1 - whitespace and function name per @Emigna's suggestions.

Edit 2 - using some pointers from the link @Emigna suggested. If I *ever* found this code in a system I had to maintain, I would hunt the developer down and flog him.

Edit 3 - @Thunda - I hope it wasn't presumptuous to recalc the savings based on my latest golfing.

Edit 4 - Removed a sort and simplified the final reassembly logic.

# Answer
> 2 votes
# 05AB1E, ~~10~~ 8 bytes

```
œ{ûD¹k<è

```

Try it online!

**Explanation**

```
œ{           # get a list of sorted permutations of the input
  û          # append a reversed copy excepting the last element of the original
   D         # duplicate
    ¹k       # push the first index of the input in the list
      <      # decrement
       è     # index into the list with this

```

# Answer
> 2 votes
## Python 2, 83 bytes

-18 bytes, thanks to @Emigna

Takes strings without number as input. As rules were clarified, this is the solution.
Try it online

```
from itertools import*
def F(A):s=sorted(permutations(A))+[A];print s[s.index(A)-1]

```

# Answer
> 2 votes
# Jelly, 8 - 50% = 4 bytes

```
Œ¿’»1œ?Ṣ

```

Try it online!

Runs in O(*n* log *n*) time. (This typically takes just over a second, due mostly to Jelly's startup time – the time of just over a second is true for both very short and fairly long inputs. There's some variation in how long it takes in TIO; the fastest I've observed is 0.914 real, 0.772 user, 0.121 system.)

## Explanation

Jelly actually has builtins for most of the challenge, but the way they're defined requires a sort. As far as I know, Jelly uses a comparison sort to sort lists of strings, which is what leads to the O(*n* log *n*) performance.

```
Œ¿’»1œ?Ṣ
Œ¿         Find index of {the input} in a sorted list of its permutations
  ’        Decrement it
   »1      saturating from below at 1
     œ?    Find the nth permutation of
       Ṣ   the sorted input

```

`Œ¿` is a builtin with an optimized implementation (i.e. not slower than O(*n* log *n*)); it doesn't do brute-forcing.

## Variations

If wrap-around is allowed (it was under an earlier version of the spec), you can remove the `»1` for a 6-byte solution and a score of 3. (Most of Jelly's builtins, including the relevant ones here, will naturally wrap around in the absence of other hints about what to do with an out-of-range value.)

# Answer
> 2 votes
# JavaScript ES6, 170 - 95% = 8.5 bytes

```
f=n=>a=>{while(--n&&a[n]>=a[n-1]);if(!n)return a;s=a.slice(--n);for(k=s.length;s[--k]>=a[n];);t=a[n];s[0]=s[k];s[k]=t;return a.slice(0,n).concat(s[0],s.slice(1).reverse())}

function Permutatino() {
  input = document.getElementById("input").value.split(" ");
  console.log(input)
  num= input.length;
  document.getElementById("output").innerHTML=(f(num)(input));
}
```

```
<input type="text" id="input" value="abc def ghi">
<button onclick="Permutatino()"> Run </button>
<pre id="output">
```

```
n=>a=>{while(--n&&a[n]>=a[n-1]);if(!n)return a;s=a.slice(--n);for(k=s.length;s[--k]>=a[n];);t=a[n];s[0]=s[k];s[k]=t;return a.slice(0,n).concat(s[0],s.slice(1).reverse())}

```

This code is a sequence of O(n) operations.

Try it online!

## Explanation:

```
while(--n>0&&a[n]>=a[n-1]);

```

Find the last location in the array that is not sorted

```
if(!n)return a;

```

If already sorted return

```
s=a.slice(--n);

```

Get everything starting from the point where it was not sorted

```
for(k=s.length;s[--k]>=a[n];);

```

Find the index of the lexicographically closest element to the first element in the unsorted section which is lexicographically less than the first element.

```
t=a[n];s[0]=s[k];s[k]=t;

```

Swap the first element with the found element.

```
return a.slice(0,n).concat(s[0],s.slice(1).reverse())

```

Return the first section of the array + the first element of the second section + the reversed remainder of the second section of the array.

# Time complexity of operations:

slice() O(n)
concat() O(n)
reverse() O(n)
indexOf() O(n) //essentially what the for and while loops were

# O(Nlog(N)) solution 143 - 50% = 71.5 bytes

```
n=>a=>{while(--n&&a[n]>=a[n-1]);if(!n)return a;s=a.slice(--n).sort();t=s.splice(s.indexOf(a[n])-1,1);return a.slice(0,n).concat(t,s.reverse())}

```

Try it online!

# Answer
> 1 votes
# Ruby, ~~55~~ 41 bytes

```
->a{x=a.permutation.sort;x[x.index(a)-1]}

```

### Explanation:

* `permutation.sort` does exactly what is written on the box
* find the original string
* go back one step, if index is 0, wrap around to -1

# Answer
> 1 votes
# Pip, 21 bytes

20 bytes of code, +1 for `-s` flag.

```
(YSSST*PMa^sy@?a-:1)

```

Takes input as a single, space-delimited string on the command line. Try it online!

### Explanation

```
                      a is 1st cmdline arg; s is space (implicit)
                      Part 1:
         a^s           Split a on spaces
       PM              Get all permutations of a
    ST*                Map str() to each of them
                       Because of the -s flag, this joins each sublist on spaces
  SS                   Sort the list using string comparison
 Y                     Yank into the y variable
                      Part 2:
            y@?a       Find index of a in sorted list of permutations y
                -:1    Subtract 1 (using compute-and-assign for lower precedence than @?)
(                  )  Index into part 1 using part 2 (Pip's indexing is cyclical, which
                      takes care of the already-ordered-input case)
                      Print (implicit)

```

# Answer
> 0 votes
# Python 2, 73,81 bytes

```
s=s.split()
import itertools as i
x=sorted(list(i.permutations(s[1:],int(s[0]))))

```

Try it online!

**Edit:** Missed the lexicographical sort part of question.

# Answer
> 0 votes
# Mathematica, 57 bytes

```
(a=Permutations@Sort@#)[[Max[1,Position[a,#][[1,1]]-1]]]&

```

Anonymous function. Takes a list of strings as input and returns a list of strings as output.

---
Tags: code-challenge, permutations
---


title: Moles with SOCKS?

text:
# Question
Title: Moles with SOCKS?
Many applications that depend on network resources (such as games connecting to game servers) do not allow the user to set a proxy. There are a lot of ways to force the usage of a proxy regardless, I personally have always been a fan of a **local SOCKS tunnel.**

## What's that?

Instead of connecting directly, an application on your local machine listens on a locally bound address and *relays* any connection to a fixed endpoint using a remote SOCKS proxy.

Example: Let our target be 11.22.33.44:5555, and our remote socks proxy be 99.88.77.66:5555. Our application listens on 127.0.0.1:5555. Our route now looks like this:

*connect to* **127.0.0.1:5555** \- *relays via SOCKS proxy* \> **99.88.77.66:5555** \- *to* \> **11.22.33.44:5555**

Your goal is to implement the local application relaying connections to the target.

## Input

Three address/port pairs representing the bind, proxy and target address.

* You may deviate from the order (but specify if you do).
* Address parsing is up to your language/tools of choice, but should at the very minimum support IPv4 (11.22.33.44).
* You may use builtin types of your language. (like `InetSocketAddress` in Java, `struct in_addr` in C, etc.)

## Output

No rules for output due to .

## Additional

* This is , shortest answer in bytes wins.
* Standard rules apply, default loopholes are forbidden.
* You do not have to support more than 1 connection. The program may terminate after the first connection finishes.
* Program behaviour under network failures is undefined; you may crash the entire program, reject the incoming connection, do whatever you want.
* You may assume the remote SOCKS proxy's version (4/4a/5).
* Using libraries/inbuilts/etc. is encouraged, but not required.
* Stay in input scope (f.e. don't proxy all connections on the machine).

# Answer
# Kotlin, 240 bytes

This was fun and taught me some things I didn't know about Kotlin.

```
import java.net.*fun a(vararg p:InetSocketAddress){ServerSocket().run{bind(p[0])
accept().let{Socket(Proxy(Proxy.Type.SOCKS,p[1])).run{connect(p[2])
Thread{it.inputStream.copyTo(outputStream)}.start()
inputStream.copyTo(it.outputStream)}}}}

```

Tested locally with:

```
fun main(args: Array<String>) {
    thread { a(InetSocketAddress(2000), InetSocketAddress(3000), InetSocketAddress(4000)) }
    thread { Socket().connect(InetSocketAddress(2000)) }
    ServerSocket(3000).accept().getInputStream().run { generateSequence { read() } }
            .forEach { print("$it,") }
}

```

Prints `5,2,0,2,` which confirms an attempted SOCKS5 connection.
> 0 votes

---
Tags: code-golf, networking
---