title: Find all times that follow a pattern

text:
# Question
Title: Find all times that follow a pattern
Your job is write a program that prints all times (in the format HH:MM, 24 hours) that follow any of the following patterns:

* Hours equal to minutes, e.g. 22:22,01:01
* Hours equal to reverse minutes, e.g. 10:01, 01:10, 22:22
* Sequences, that match H:MM, or HH:MM, always printed with HH:MM. E.g. 00:12, 01:23, 23:45, 03:45, etc (always a single step between digits)

Rules:

* You may choose any language you like
* You cannot print repeated times
* One time per line, following the order of the day
* The winner will be chosen in February 5.

PS: this is my first question, it might have some inconsistencies. Feel free to edit.

PS2: Here is the expected 44 solutions (already presented by Josh and primo, Thanks!)

```
00:00
00:12
01:01
01:10
01:23
02:02
02:20
02:34
03:03
03:30
03:45
04:04
04:40
04:56
05:05
05:50
06:06
07:07
08:08
09:09
10:01
10:10
11:11
12:12
12:21
12:34
13:13
13:31
14:14
14:41
15:15
15:51
16:16
17:17
18:18
19:19
20:02
20:20
21:12
21:21
22:22
23:23
23:32
23:45
```

# Answer
> 4 votes
**Golfscript (~~82~~ 72)**

Still very much a beginner, but there was no GS answer, so... :)

```
24,{'0'\+-2>..+\.-1%+}%5,{'0'7,{+}/>4<.(;0\+}%|{2=54<},$);{2/~':'\++}%n*

```

# Answer
> 4 votes
## C, 118 (initially 136)

```
h,m;main(){h<24&&main(m>57?m=0,h++:h==m|h==m%10*10+m/10|m-12==h*11|h==m-22&!(~-m++%11)&&printf("%02d:%02d\n",h,m-1));}

```

An iterative version with 119 characters:

```
h;main(m){for(;h<24;h++)for(m=0;m<57;m++)h==m|h==m%10*10+m/10|m-12==h*11|h==m-22&!(~-m%11)&&printf("%02d:%02d\n",h,m);}

```

A big thanks to @squeamish ossifrage !

# Answer
> 4 votes
## PHP - 93 bytes

```
<?for(;24>$h;)@ereg(+$h=&date(i,$i).$m=date(s,$i++),"0123456$h$h".strrev($h))&&print"$h:$m
";

```

This will find patterns like `02:34`, but will not find patterns like `00:23` or `00:02`. If i understand the OP's clarifications in the comments, this is correct.

Prints a total of 44 results:

```
00:00
00:12
01:01
01:10
01:23
02:02
02:20
02:34
03:03
03:30
03:45
04:04
04:40
04:56
05:05
05:50
06:06
07:07
08:08
09:09
10:01
10:10
11:11
12:12
12:21
12:34
13:13
13:31
14:14
14:41
15:15
15:51
16:16
17:17
18:18
19:19
20:02
20:20
21:12
21:21
22:22
23:23
23:32
23:45

```

# Answer
> 2 votes
**Python (178)**

```
s=sorted
for i in[x for x in['%04d'%i for i in range(2400)if i/10%10<6]if s(x[:2])==s(x[2:])or len({i-ord(y)for i,y in enumerate(x.lstrip('0'))})==1]:print'%2s:%2s'%(i[:2],i[2:])

```

Stripping all leading zeroes before sequences gives 57 results in total.

# Answer
> 2 votes
## APL (90)

```
F←{,'ZI2'⎕FMT⍵}⋄↑⊃¨{(F⍺),':',F⍵}/¨Z/⍨{(⍺=⍵)∨(≡/0 1⌽∘F¨⍺⍵)∨∧/¯1=2-/⍎¨(⍕⍺),F⍵}/¨Z←,1-⍨⍳24 60

```

# Answer
> 1 votes
# Javascript - 171 chars (5/2/14) !

```
for(h='00';+h<24;h=(++h<10?'0':'')+h)for(m='00';+m<60;m=(++m<10?'0':'')+m)if(h[1]+h[0]==m||h==m||+m[1]-m[0]==1&&+m[0]-h[1]==1&&(!+h[0]||+h[1]-h[0]==1))console.log(h+':'+m)

```

I seriously am getting the hang of golfing. If I look back from now, I have cut down almost 30 chars ! JSBin.

## Ungolfed (and commented) :

```
// Note: +'string' is same as 'parseInt(string, 10)'
// Also, this code is not the shortest one, I have purposely made this code longer for
// understanding purposes

for(h = '0'; +h < 24; h = +h + 1 + '') //initialize h(our), loop while it's less than 24
{                                      // increase it by 1 and cast back to string
    for(m = '0'; +m < 60; m= +m + 1 + '') // intialize m(inute), loop while < 60
    {                                  // increase it by 1 and cast back to string
        if(h.length < 2) h = 0 + h;    // if it is '9', convert to '09'
        if(m.length < 2) m = 0 + m;    // if it is '9', convert to '09'

        // Tests for printing
        if(h[0] === m[1] && m[0] === h[1] ||
           h === m ||
           +m[1] - +m[0] === 1 && +m[0] - +h[1] === 1 && (+h[0] === 0 || +h[1] -+ h[0] === 1))
        console.log(h + ':' + m);  // print
    } // inner loop end
}     // outer loop end

```

### 187 chars (Old) (4/2/14)

```
for(h='00';+h<24;h=(+h<9?'0':'')+(+h+1))for(m='00';+m<60;m=(+m<9?'0':'')+(+m+1))if(h[0]==m[1]&&m[0]==h[1]||h==m||+m[1]-m[0]==1&&+m[0]-h[1]==1&&(!+h[0]||+h[1]-h[0]==1))console.log(h+':'+m)

```

Little bit of experimenting, and lot improvement (9 chars) :) JSBin

### 196 chars (Old) (3/2/14)

```
for(h='00';+h<24;h=(+h<9?'0':'')+(+h+1))for(m='00';+m<60;m=(+m<9?'0':'')+(+m+1))if(h[0]==m[1]&&m[0]==h[1]||h==m||+m[1]-m[0]==1&&+m[0]-h[1]==1&&(!+h[0]||+h[1]-h[0]==1))console.log(h+':'+m)

```

Sat down with a fresh mind and improved it a lot, a one liner :) JSBin.

### 208 chars (Old) (2/2/14)

```
for(h='0';+h<24;h=+h+1+''){for(m='0';+m<60;m=+m+1+''){if(h.length<2)h=0+h
if(m.length<2)m=0+m
if(h[0]==m[1]&&m[0]==h[1]||h==m||+m[1]-+m[0]==1&&+m[0]-+h[1]==1&&(+h[0]==0||+h[1]-+h[0]==1))console.log(h+':'+m)}}

```

---

Gives exactly the 44 required times (each in new line)

Will keep improving my code.

I would highly appreciate any feedback. Thank you.

# Answer
> 1 votes
# Python 3, 248 characters

Guess I'm a little late and not very good as well, but finally, got my first codegolf thing to share:

I decided to only support real sequences like 01:23 and 23:45, not 00:12. Anyway, I bet theres plenty to do better, so please go ahead and share a comment with me.

```
import itertools as t
s=sorted
r=range
i=int
d='%02d'
e=d+':'+d
print([e%(i(a[0]),i(a[1])) for a in t.product([d% x for x in r(0,24)], [d% x for x in r(0,60)]) if s(a[0])==s(a[1]) or list(a[0]+a[1])==[str(x) for x in r(i(a[0][0]),i(a[1][-1])+1)]])

```

Got the very descriptive version along with it on my pastebin

# Answer
> 0 votes
# Delphi

Still working on it but this is what i have so far.
It works, but im sure its possible to get it shorter.
**Edit:** Prints 48 times.

## Without indent 422 characters

```
uses System.SysUtils,DateUtils;var t:TTime;a,b,c,d:integer;s:string;begin t:=StrToTime('00:01');while t<StrToTime('23:59')do begin s:=FormatDateTime('hhnn',t);a:=StrToInt(s[1]);b:=StrToInt(s[2]);c:=StrToInt(s[3]);d:=StrToInt(s[4]);if((a+1=b)and(b+1=c)and(c+1=d))or((a=0)and(b+1=c)and(c+1=d))or((a=0)and(b=0)and(c+1=d))or((a=d)and(b=c))or((a=c)and(b=d))then WriteLn(FormatDateTime('hh:nn',t));t:=IncMinute(t)end;ReadLn;end.

```

## With indent 557characters

```
uses
  System.SysUtils, DateUtils;

var
  t:TTime;
  a,b,c,d:integer;
  s:string;
begin
  t:=StrToTime('00:01');
  while t<StrToTime('23:59')do
  begin
    s:=FormatDateTime('hhnn',t);
    a:=StrToInt(s[1]);
    b:=StrToInt(s[2]);
    c:=StrToInt(s[3]);
    d:=StrToInt(s[4]);
    if((a+1=b) and (b+1=c) and (c+1=d)) or
      ((a=0) and (b+1=c) and (c+1=d)) or
      ((a=0) and (b=0) and (c+1=d)) or
      ((a=d) and (b=c)) or ((a=c) and (b=d)) then
      WriteLn(FormatDateTime('hh:nn',t));
    t:=IncMinute(t)
  end;
  ReadLn;
end.

```

# Answer
> 0 votes
# q (116)

```
distinct{t:string 00:00+x;$[(t[0 1]in(t[3 4];t[4 3]))|all 1=1_deltas{"I"$x}each t[0 1 3 4];t;"00:00"]}each til 1440

```

Increments 00:00 to 23:59, casts to string, then check (test 1 or 2) or 3

Output:

```
("00:00";"01:01";"01:10";"01:23";"02:02";"02:20";"03:03";"03:30";"04:04";"04:40";"05:05";"05:50";"06:06";"07:07";"08:08";"09:09";"10:01";"10:10";"11:11";"12:12";"12:21";"12:34";"13:13";"13:31";"14:14";"14:41";"15:15";"15:51";"16:16";"17:17";"18:18";"19:19";"20:02";"20:20";"21:12";"21:21";"22:22";"23:23";"23:32";"23:45")

```

# Answer
> 0 votes
# PHP - 56 39 31 bytes

```
<? http_redirect("goo.gl/W2M5mo")?>

```

It doesn't bend the rules in any way. You need the pecl\_http module installed and short\_open\_tag set to "1" in php.ini.

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


title: ASCII connected hexagons

text:
# Question
Title: ASCII connected hexagons
## Overview

**Given a number of hexagons, arrange them into a connected shape within the confines of a 50 by 50 ASCII art image. The shape you choose can be arbitrary - whatever you find most amenable to golfing - as long as it is connected. It may have holes provided they are larger than one hexagon (otherwise the number of hexagons will be ambiguous).**

---

## Layout

All hexagons must be in the following form (only this size and orientation is valid):

```
 __
/  \
\__/    Note there are 2 underscores per horizontal edge.

```

Two hexagons are ***directly connected*** if they share an edge:

```
 __               __
/  \__           /  \
\__/  \          \__/
   \__/    or    /  \
                 \__/

```

Two hexagons are not connected if they only share a vertex:

```
 __  __
/  \/  \
\__/\__/

```

Sharing half an edge also does not count as connected:

```
 __
/  \
\__/
 /  \
 \__/

```

A collection of hexagons is ***connected*** if there exists a path from any hexagon to any other using only *directly connected* hexagons.

## Holes

A hexagon sized hole in a connected collection of hexagons counts as a hexagon, so that any given piece of ASCII art has an unambiguous hexagon count.

This does *not* count as a hole since the prospective hole is a single hexagon:

```
    __
 __/  \__
/  \__/  \
\__/  \__/
/  \__/  \
\__/  \__/
   \__/      7 hexagons (not 6 with a hole)

```

This *does* count as a hole since it does not correspond to a single hexagon:

```
    __
 __/  \__
/  \__/  \__
\__/  \__/  \
/  \__   \__/
\__/  \__/  \
   \__/  \__/
      \__/      8 hexagons with a hole

```

# Input and output

### Input

An integer from 1 to 255.

### Output

An ASCII art string representing the input number of connected hexagons as described above.

* The number of rows (newline separated substrings) is at most 50, plus an additional optional trailing newline.
* The rows need not be the same length, but each must be of length at most 50.
* Zero length rows can exist above or below the connected shape provided the total number of rows does not exceed 50.
* Space-only rows can exist above or below the connected shape provided the total number of rows does not exceed 50.
* Spaces can appear to the left of the shape provided the row lengths do not exceed 50 (the shape does not need to be aligned to the left).
* Spaces can appear to the right of the shape provided the row lengths do not exceed 50.
* Any characters that do not form part of the connected shape must be either spaces or newlines.

Provided the output is correct, it is not required to be consistent from one run to the next.

## Examples

Input: `6`

Valid Outputs:

```
 __    __    __
/  \__/  \__/  \__
\__/  \__/  \__/  \
   \__/  \__/  \__/

```

---

```
 __    __
/  \__/  \
\__/  \__/
/  \__/  \
\__/  \__/
   \__/

```

---

```
          __
 __      /  \
/  \__   \__/
\__/  \__/  \
   \__/  \__/
      \__/
      /  \
      \__/

```

Invalid Outputs:

```
    __
 __/  \__
/  \__/  \
\__/  \__/
/  \__/  \
\__/  \__/
   \__/      Invalid for 6 as the centre hole counts as a 7th hexagon.

```

---

```
 __    __    __      __
/  \__/  \__/  \    /  \
\__/  \__/  \__/    \__/
   \__/  \__/                Invalid as the 6 hexagons are not connected.

```

---

```
 __    __    __  __
/  \__/  \__/  \/  \
\__/  \__/  \__/\__/
   \__/  \__/           Invalid as vertex touching does not count as connected.

```

---

```
 __    __       __
/  \__/  \     /  \
\__/  \__/     \__/
/  \__/  \
\__/  \__/
   \__/       Invalid as the 6 connected hexagons are not the only visible characters.

```

## Winning

The shortest valid answer in bytes wins.

---

# Leaderboard

*(using Martin's leaderboard snippet)*

```
var QUESTION_ID=54277;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table></div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table></div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table><table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table>
```

# Answer
# CJam, ~~64~~ ~~57~~ 55 bytes

```
" __
/  \
\__/"N/{_SS/\+_47>S3*f{\+}_2>\@?}q~(*]:..e>N*

```

Test it here.

This will generate the following pattern, *column-wise*:

```
 __    __    __    __    __    __
/  \__/  \__/  \__/  \__/  \__/  \
\__/  \__/  \__/  \__/  \__/  \__/
/  \__/  \__/  \__/  \__/  \__/  \
\__/  \__/  \__/  \__/  \__/  \__/
/  \__/  \__/  \__/  \__/  \__/  \
\__/  \__/  \__/  \__/  \__/  \__/
/  \__/  \__/  \__/  \__/  \__/  \
\__/  \__/  \__/  \__/  \__/  \__/
/  \__/  \__/  \__/  \__/  \__/  \
\__/  \__/  \__/  \__/  \__/  \__/
/  \__/  \__/  \__/  \__/  \__/  \
\__/  \__/  \__/  \__/  \__/  \__/
/  \__/  \__/  \__/  \__/  \__/  \
\__/  \__/  \__/  \__/  \__/  \__/
/  \__/  \__/  \__/  \__/  \__/  \
\__/  \__/  \__/  \__/  \__/  \__/
/  \__/  \__/  \__/  \__/  \__/  \
\__/  \__/  \__/  \__/  \__/  \__/
/  \__/  \__/  \__/  \__/  \__/  \
\__/  \__/  \__/  \__/  \__/  \__/
/  \__/  \__/  \__/  \__/  \__/  \
\__/  \__/  \__/  \__/  \__/  \__/
/  \__/  \__/  \__/  \__/  \__/  \
\__/  \__/  \__/  \__/  \__/  \__/
/  \__/  \__/  \__/  \__/  \__/  \
\__/  \__/  \__/  \__/  \__/  \__/
/  \__/  \__/  \__/  \__/  \__/  \
\__/  \__/  \__/  \__/  \__/  \__/
/  \__/  \__/  \__/  \__/  \__/  \
\__/  \__/  \__/  \__/  \__/  \__/
/  \__/  \__/  \__/  \__/  \__/  \
\__/  \__/  \__/  \__/  \__/  \__/
/  \__/  \__/  \__/  \__/  \__/  \
\__/  \__/  \__/  \__/  \__/  \__/
/  \__/  \__/  \__/  \__/  \__/  \
\__/  \__/  \__/  \__/  \__/  \__/
/  \__/  \__/  \__/  \__/  \__/  \
\__/  \__/  \__/  \__/  \__/  \__/
/  \__/  \__/  \__/  \__/  \__/  \
\__/  \__/  \__/  \__/  \__/  \__/
/  \__/  \__/  \__/  \__/  \__/
\__/  \__/  \__/  \__/  \__/  \
/  \__/  \__/  \__/  \__/  \__/
\__/  \__/  \__/  \__/  \__/  \
/  \__/  \__/  \__/  \__/  \__/
\__/  \__/  \__/  \__/  \__/  \
/  \__/  \__/  \__/  \__/  \__/
\__/  \__/  \__/  \__/  \__/

```

## Explanation

This is based on Dennis's excellent tip, using `.e>` to assemble an ASCII art output from several pieces. As he says, `.e>` takes the element-wise maximum of two arrays (or strings), and since spaces have the lowest character code, we can use this to impose any other characters on a string grid. Furthermore, if the two arrays don't have the same length, the extraneous elements of the longer array are simply copied unchanged. This means that the different patterns don't even need to be the same size. To apply this to two-dimensional arrays (because we don't want to insert the newlines until the very end), we apply `.e>` pairwise to lines, which gives `..e>`.

The basic idea of the code is to generate `N` copies of a single hexagon moved to the right position. We "move" the hexagon vertically by prepending empty lines and horizontally by prepending spaces. Once we're done, we fold all of the copies together, using the beautiful `:..e>` (probably the longest operator I've ever used in a CJam program).

Here is the code:

```
" __
/  \
\__/"N/    e# Get a 2D character grid of the hexagon.
{          e# Read input N, repeat this block N-1 times.
  _        e#   Make a copy, so we leave the last hexagon on the stack.
  SS/\+    e#   Prepend two empty lines.
  _47>     e#   Make a copy and discard the first 47 lines.
  S3*f{\+} e#   Prepend 3 spaces to each line. This copy has been moved back to
           e#   the top and one column to the right.
  _2>      e#   Make a copy and discard another two lines.
  \@?      e#   If any lines were left after that, pick the copy in the next column,
           e#   otherwise, stay in the same column.
}q~(*
]:..e>     e# Wrap all the hexagons in an array and fold them into a single grid.
N*         e# Join them with newline characters.

```
> 13 votes

# Answer
## Python 2, 219 207 chars

```
b=bytearray(' ');h=['__ ','/  \\','\\__/'];k=range;x=input();g=[b*50for _ in k(50)]
for i in k(x):
 c=i*3%48+1;r=(i*3+1)/48*2+i%2
 for m in k(i>15,3):n=m==0;g[r+m][c+n:c+4-n]=h[m]
print"\n".join(map(str,g))

```

Takes input on stdin.

Pretty much just creates a 50x50 grid of spaces of and plops the hexagons in where appropriate. After the 16th hexagon, I don't need the first row of `h` (the hexagon as a 2D array) so I use `i>15` to start the range at 1 instead of 0. `c=i*3%48+1;r=(i*3+1)/48*2+i%2` calculates the **c**olumn and **r**ow I need to start at. `n` is a boolean but is used as an integer to fix up the bounds (since `h[0]` is only 3 characters to avoid overwriting stuff).

I'm pretty happy with this one, I shaved off about 50 bytes since the initial version, especially when I remembered the `a[x:y]=b` syntax.

Output (n=30):

```
  __    __    __    __    __    __    __    __
 /  \__/  \__/  \__/  \__/  \__/  \__/  \__/  \__
 \__/  \__/  \__/  \__/  \__/  \__/  \__/  \__/  \
 /  \__/  \__/  \__/  \__/  \__/  \__/  \__/  \__/
 \__/  \__/  \__/  \__/  \__/  \__/  \__/  \
    \__/  \__/  \__/  \__/  \__/  \__/  \__/
(plus 44 lines of spaces each 50 wide)

```

Since trailing lines of whitespace are allowed I changed the creation of `g` to just create 50 `bytearray`s instead of `3+(x>1)+x/16*2`, which is the exact number of rows required, shaving off 12 bytes.
> 7 votes

# Answer
# Swift 2.0, ~~601~~ 591 bytes

```
import Cocoa
var a=Int(Process.arguments[1])!,b="/  \\__".join([String](count:9,repeatedValue:""))+"/",c="\\__/  ".join([String](count:9,repeatedValue:""))+"\\",d=c.startIndex,e=c.endIndex,j=[c.stringByReplacingOccurencesOfString("\\",withString:" ").stringByReplacingOccurencesOfString("/",withString:" ").substringToIndex(advance(d,3*a,e)),b.substringToIndex(advance(d,3*a+a%2,advance(e,-1)))]
while a>0{j+=[c.substringToIndex(advance(d,3*a+1,e)),b.substringToIndex(advance(d,3*a+(a+1)%2,e)]
a<=16 ?j+=[" "+j.removeLast().substringFromIndex(advance(d,1))]:()
a-=16}
for l in j{print(l)}

```

To run: `swift hexagons.swift 21`

Output:

```
 __    __    __    __    __    __    __    __
/  \__/  \__/  \__/  \__/  \__/  \__/  \__/  \__
\__/  \__/  \__/  \__/  \__/  \__/  \__/  \__/  \
/  \__/  \__/  \__/  \__/  \__/  \__/  \__/  \__/
\__/  \__/  \__/
   \__/  \__/

```

---

Swift's `substringToIndex` and `stringByReplacingOccurencesOfString` take up so many characters...
> 6 votes

# Answer
# C, 238 bytes

```
#define h(A) c[m+A/4][n+A%4]
i,m,n;
f(a)
{
    char c[50][51];
    for(i=0;i<50;i++)for(m=0;m<51;m++)c[i][m]=m-50?32:0;
    for(;a;)
        m=a/12*2,n=a%12*3,a--%2?m=a/12*2+1,n=a%12*3+3:0,
        h(1)=h(2)=h(9)=h(10)=95,h(4)=h(11)=47,h(7)=h(8)=92;
    for(;i;)puts(c-i--+50);
}

```

Only necessary spaces and newlines considered for character count.

It simply creates a matrix of characters, fills them in reverse order, and then prints the whole thing.
> 4 votes

# Answer
# JavaScript (ES6), 265 bytes

```
A=Array;f='forEach';U=x=1;y=0;a=A.from(A(51),_=>A.from(A(51),_=>' '));d=h=>(` __
/  \\
\\__/`.split`
`[f]((l,i)=>[...l][f]((c,j)=>{if('_/\\'.indexOf(a[x+i][y+j])<0)a[x+i][y+j]=c})),(x+=U*-2+1),(U=!U),(C-y<=3?((U=x+=2),y=0):y+=3),--h?d(h):a.map(d=>d.join``).join`
`)

```

Tessellates hexagons in a row, from left to right, alternating up and down—like a honeycomb—until the end of a row is reached.

Ungolfed with description (works in firefox):

```
'use strict';
const CAP = 51;
var a = Array.from(Array(51), () => Array.from(Array(51),() => ' '))

function draw (hexagons, x, y, a, up) {
  // x, y (row, col) represents the current position of the cursor
  /*

    Here's a map of the first three iterations:

            01234567
     0        __
     1     __/  \__
     2    /  \__/  \
     3    \__/  \__/

    For the first 17 iterations, the cursor will be at:

      # | x | y
      ----------
      1 | 1 | 0
      2 | 0 | 3
      3 | 1 | 6
      4 | 0 | 9
      5 | 1 | 12
      6 | 0 | 15
      7 | 1 | 18
      8 | 0 | 21
      9 | 1 | 24
     10 | 0 | 27
     11 | 1 | 30
     12 | 0 | 33
     13 | 1 | 36
     14 | 0 | 39
     15 | 1 | 42
     16 | 0 | 45
     17 | 3 | 0      <- moves back to the first row

  */
` __
/  \\
\\__/`
  // split the hexagon into three lines
  .split('\n').forEach((line, index) => {
    // and for each line
    ;[...line].forEach((char, j) => {
      // if the cursor position (x, y) translated
      // by (index, j) is not already part of a hexagon
      // then replace it with the current (index, j) piece
      // of the hexagon
      /*
         0123
       0  __
       1 /  \
       2 \__/

      */
      if ('_/\\'.indexOf(a[x + index][y + j]) < 0)
        a[x + index][y + j] = char
    })
  })

  // `up` represents the next hexagon
  // if true, the next hexagon will be drawn attached to
  // the top right edge of the current hexagon
  if (up) {
    x -= 1
  // otherwise, it'll be drawn attached to the bottom right edge
  } else {
    x += 1
  }

  // move three columns to the right
  y += 3
  // change directions
  up = !up

  // if within the right boundary of the 51x51 matrix,
  // move back to the left edge and down 2 rows
  // and draw the next hexagon as an `up` hexagon
  if (51 - y <= 3) {
    y = 0
    x += 2
    up = true
  }

  // if hexagons > 0, then recurse and draw the next hexagon
  // otherwise, return the array (join the columns in each row, then join each row
  // by a new line)
  return --hexagons ?
    draw(hexagons, x, y, a, up)
    : a.map(d => d.join('')).join('\n')
}

var n = parseInt(prompt('Number to draw:'))
var r = draw(n, 1, 0, a, true)
document.write('<pre>' + r.replace(/\n/g, '<br>') + '</pre>')
```
> 2 votes

# Answer
# Ruby, 120

```
->n{a=(1..50).map{' '*50}
n.times{|i|x=i%16*3
3.times{|j|a[47-i/16*2-x/3+j][x..x+3]=[' __ ','/  \\','\__/'][j]}}
puts a}

```

creates an array of 50 strings of 50 spaces, then substitutes 4 characters in 3 lines to add the hexagons:

```
" __ "
"/  \"
"\__/"

```

As the first line contains spaces, once a hexagon has been plotted we cannot plot another one below it, because the spaces would overwrite the previous hexagons.

Therefore the hexagons are added in the form of a 16x16 rhombus (distorted rectangle) from bottom to top, and slanting from bottom left to top right.

The string `" __ "` will then be overwritten with additional `\` and `/` where neccessary.

**Ungolfed in test program**

```
g=->n{
  a=(1..50).map{' '*50}              #make an array of 50 strings of 50 spaces
  n.times{|i|                        #loop through all hexagons
    x=i%16*3                         #x coordinate of top left corner of hexagon, 16 per row
    3.times{|j|                      #loop through 3 lines to print hexagon.
      a[47-i/16*2-x/3+j][x..x+3]=    #47-i/16*2 : start at the bottom and work up. each row is 2 lines high and contains 16 hexagons. x/3 : slant upwards as the row moves right.
       [' __ ','/  \\','\__/'][j]    #These are the symbols for each of the 3 lines required for a hexagon. [x..x+3] defines which characters have to be replaced in each string.
    }
  }
  puts a                             #print to stdout
}

N=gets.to_i
g.call(N)

```

**Typical output (n=250)**

There should be a few more rows of whitespace at the top here, to make a total of 50, but I don't know if there is a way to get Stackexchange to format to include them.

```
                                              __
                                           __/  \
                                        __/  \__/
                                     __/  \__/  \
                            __    __/  \__/  \__/
                         __/  \__/  \__/  \__/  \
                      __/  \__/  \__/  \__/  \__/
                   __/  \__/  \__/  \__/  \__/  \
                __/  \__/  \__/  \__/  \__/  \__/
             __/  \__/  \__/  \__/  \__/  \__/  \
          __/  \__/  \__/  \__/  \__/  \__/  \__/
       __/  \__/  \__/  \__/  \__/  \__/  \__/  \
    __/  \__/  \__/  \__/  \__/  \__/  \__/  \__/
 __/  \__/  \__/  \__/  \__/  \__/  \__/  \__/  \
/  \__/  \__/  \__/  \__/  \__/  \__/  \__/  \__/
\__/  \__/  \__/  \__/  \__/  \__/  \__/  \__/  \
/  \__/  \__/  \__/  \__/  \__/  \__/  \__/  \__/
\__/  \__/  \__/  \__/  \__/  \__/  \__/  \__/  \
/  \__/  \__/  \__/  \__/  \__/  \__/  \__/  \__/
\__/  \__/  \__/  \__/  \__/  \__/  \__/  \__/  \
/  \__/  \__/  \__/  \__/  \__/  \__/  \__/  \__/
\__/  \__/  \__/  \__/  \__/  \__/  \__/  \__/  \
/  \__/  \__/  \__/  \__/  \__/  \__/  \__/  \__/
\__/  \__/  \__/  \__/  \__/  \__/  \__/  \__/  \
/  \__/  \__/  \__/  \__/  \__/  \__/  \__/  \__/
\__/  \__/  \__/  \__/  \__/  \__/  \__/  \__/  \
/  \__/  \__/  \__/  \__/  \__/  \__/  \__/  \__/
\__/  \__/  \__/  \__/  \__/  \__/  \__/  \__/  \
/  \__/  \__/  \__/  \__/  \__/  \__/  \__/  \__/
\__/  \__/  \__/  \__/  \__/  \__/  \__/  \__/  \
/  \__/  \__/  \__/  \__/  \__/  \__/  \__/  \__/
\__/  \__/  \__/  \__/  \__/  \__/  \__/  \__/
/  \__/  \__/  \__/  \__/  \__/  \__/  \__/
\__/  \__/  \__/  \__/  \__/  \__/  \__/
/  \__/  \__/  \__/  \__/  \__/  \__/
\__/  \__/  \__/  \__/  \__/  \__/
/  \__/  \__/  \__/  \__/  \__/
\__/  \__/  \__/  \__/  \__/
/  \__/  \__/  \__/  \__/
\__/  \__/  \__/  \__/
/  \__/  \__/  \__/
\__/  \__/  \__/
/  \__/  \__/
\__/  \__/
/  \__/
\__/

```
> 2 votes

---
Tags: code-golf, ascii-art, hexagonal-grid, tiling
---


# Question
Title: Exponentiation of natural numbers using only primitive integer operations
## The challenge

Implement the C equivalent of the `pow()` function (exponentiation) for natural numbers, in a language of your choosing, using only **addition**, **subtraction** (which includes negation and comparisons), **bit-shifting**, **boolean operations** on signed and/or unsigned **integers**, and of course looping.

(Note that this is different from hyperexponentiation/tetration, which is repeated exponentiation. This is merely a single application of exponentiation, which can be expressed mathematically as repeated multiplication.)

This is a code-golf challenge, so the shortest answer is king.

## Input assumptions

You are computing *x* raised to the *y* power. You may assume that *x* ≥ 1 and *y* ≥ 1, because 0 is not a natural number. (In other words, you don't have to check for 0⁰.)

## Output

Your function should return the correct value for all *valid* input, except in the event of internal overflow, in which case you may return a garbage value. (In other words, if your language only supports 64-bit integers, then you may return whatever you like for input such as x=10, y=100.)

## Bonus

There is a –10 point bonus if your function properly detects internal overflow and either aborts or returns some sort of error condition to the caller.

# Answer
> 4 votes
# Java, 84

A boring "addition in a double loop" method. One loop is to multiply, the other makes it happen more than once. Works until overflow on `int` types. The -10 bonus just isn't worth it in Java ;)

```
int p(int x,int y){int r=1,p,i=0,j;for(;i++<y;r=p)for(p=0,j=0;j++<x;)p+=r;return r;}

```

# Answer
> 4 votes
# CJam, 21 bytes

```
{1@@,f{;0@@,f{;+}~}~}

```

Only uses stack manipulation, loops and addition.

Try it online.

# Answer
> 4 votes
# CJam, 22 bytes

Since the other CJam answer uses nested loops, I went with recursion. It's a lot slower.

```
{:X({:BX(F0\{B+}*}&}:F

```

Try it online.

# Answer
> 4 votes
# Element, 18 bytes

```
1__'['[2:'+"]#"]#`

```

This is just a simple double-loop solution. It only uses addition and simple stack operations. (I'm not done golfing yet).

Input is like

```
5
3

```

for `5^3` giving `125`.

Here's a very similar 18 byte solution:

```
1_'_'["#[2:'+"]']`

```

# Answer
> 1 votes
# Pyth, 27 bytes

```
K1Vr0@Q1J0Vr0@Q0=J+JK)=KJ)K

```

Works by adding numbers together whilst looping. Takes input in the form:

```
x,y

```

Try it here.

# Answer
> 1 votes
# Haskell, 37 bytes

```
(foldl1((sum.).replicate).).replicate

```

Usage example (note: exponent comes first, then base):

```
Prelude> ((foldl1((sum.).replicate).).replicate) 5 2
32

Prelude> ((foldl1((sum.).replicate).).replicate) 6 3
729

```

# Answer
> 1 votes
# Python 2, 67 62 bytes

```
m=lambda x,y:y and x+m(x,y-1);p=lambda x,y:y<1or m(x,p(x,y-1))

```

This is an obvious solution: define multiplication in terms of addition, then exponentiation in terms of multiplication.

Unfortunately, this rather naive implementation very quickly reaches the maximum recursion depth (Python's default maximum depth is `1000`, I think). For instance, you can do `p(9, 4)` and it immediately outputs `6561`. But if you try `p(10, 4)` it chokes, because it ultimately has to evaluate `m(10, 1000)` (that is, `10*1000`) and it takes `1000` nested additions to do it.

Of course, you can always raise the stack depth limit...

By the way, `p(0, 0)` returns `1`, which is desirable behavior in my view (if interested, please see my answer and comment here: https://math.stackexchange.com/questions/20969/prove-0-1-from-first-principles/1094926#1094926).

Thanks so much to xnor for saving me 5 bytes!

# Answer
> -1 votes
## Powershell - 124 bytes

```
:\>cat pow.ps1

filter m([double]$a,$b){$r=0;while($b--){$r+=$a};return $r}
filter p([double]$c,$d){$s=1;while($d--){$s=m $s $c};return $s}

:\>cat pow.ps1 | wc --chars
124

:\>runpow.bat

:\>powershell -nologo -noexit -c "& {. .\pow.ps1; p 3 4;p 2 10; p 10000 77; p 10000 78}"

81
1024
1.0000000000004E+308
Infinity  <------- if result above [double]::MaxValue

```

# PowerShell 51 bytes

(answer prior to edit concats a multipliable string and evaluates it )

```
$p=[string]$args[0]+"*";powershell($p*$args[1]+"1")

```

result

```
PS E:\> .\pow.ps1 10076.45 77
1.79755288402548E+308
PS E:\> .\pow.ps1 2 10
1024
PS E:\> .\pow.ps1 10 100
1E+100
PS E:\> .\pow.ps1 4 20
1099511627776
PS E:\> .\pow.ps1 20 4
160000
PS E:\> .\pow.ps1 10077 77
Infinity

```

---
Tags: code-golf, number, restricted-source, number-theory
---


title: Reflections in Water

text:
# Question
Title: Reflections in Water
Take a string as input. This string can be as long as you'd like, however, it may only include letters and spaces––no numbers, punctuation, etc. When a word is passed into your function, an image will be made out of it. This image is the input word written out using only these characters: , **/**, **\**, and **|**. You do not need to use all of these characters, but you may not use any others. **Only words are inputed; no numbers or any other characters.**

Here are a couple examples:

```
Input : "String"

Return :

 –––    –––    –––   –––  |\    |   –––
|        |    |   |   |   | \   |  |
 –––     |    |–––    |   |  \  |  | ––
    |    |    |   \   |   |   \ |  |   |
 –––     |    |    \ –––  |    \|   –––     //uppercase string written out
––––––––––––––––––––––––––––––––––––––––    //bar
                                            //line break
 –––     |    |    / –––  |    /|   –––
    |    |    |   /   |   |   / |  |   |
 –––     |    |–––    |   |  /  |  | ––
|        |    |   |   |   | /   |  |
 –––    –––    –––   –––  |/    |   –––     //uppercase string written upside-down (reflected)

```

After the all caps string written out, there is a bar and then a line break. After that, there is the same string, just mirrored/upside-down. The bar under the word spelled out should be the length of the written out string. The upside down word––the reflection––goes one line beneath the line break.

Here is another example:

```
Input : "hi"

Return :

|  |  –––
|  |   |
|––|   |
|  |   |
|  |  –––
–––––––––

|  |  –––
|  |   |
|––|   |
|  |   |
|  |  -––

```

## A bonus challenge/addition:

Add a ripple effect. Have something like a random indent between 0 and 3 spaces before each line in the reflection. Here's an example of what it could look like:

```
Input : "hi"

Return :

|  |  –––
|  |   |
|––|   |
|  |   |
|  |  –––
–––––––––

 |  |  –––
 |  |   |
  |––|   |
 |  |   |
  |  |  -––

```

## Your code should be in the following form:

```
function createAwesomeness(string) -> string {
    let s = //your code that creates the 'image'
    return s
}

print createAwesomeness("string")
print createAwesomeness("bananas")

```

## A couple notes:

* Every language is valid
* Suggestion: Do not copy the font-set as a dictionary or array because that adds a lot to your code's size. Both as a challenge and to lower your code's size, try to use a function of sorts to create the letters
* Along with your code, have:
    + The size in bytes **of your function**
    + The number of characters **of your function**
    + The two examples
* Shortest, working code wins
* There is currently no deadline

If any further explanation is needed, please tell me in the comments!

Any response is welcome and greatly appreciated!

# Answer
> 5 votes
# JavaScript (ECMAScript 6) (580 characters/bytes)

Probably not the best/shortest way to do this, but here's my two cents' worth:

```
a=x=>{l=["#####","#   #","#","  #","    #","# #","#  ##","####",""],g=[0,1,1],t=[8,8,8,8,8,0,1,...g,7,1,0,1,7,0,2,2,2,0,7,1,1,1,7,0,2,0,2,0,0,2,0,2,2,0,2,0,1,...g,...g,0,3,3,3,0,0,4,4,4,...g,5,5,1,2,2,2,2,0,0,...g,1,1,1,1,6,1,...g,1,0,0,1,0,2,2,...g,6,0,0,1,0,5,1,0,2,0,4,0,0,3,3,3,3,1,1,1,1,...g,1,1,3,1,1,1,0,...g,3,1,1,1,1,0,3,3,0,4,0,2,0],s=(n,r)=>l[t[5*n+r]].padRight(8),y=Array(10).fill("");for(r=-1,z=0;++r<5&z<x.length;r==4&&++z?r=-1:0){c=x[z].charCodeAt()&31;y[r]+=s(c,r),y[9-r]+=s(c,r)}return`${y.slice(0,5).join`
`}
${"-".repeat(y[0].length-3)}

${y.slice(5).join`
`}`}
console.log(a("string"))
console.log(a("bananas"))

```

Note that although this is standard ES6, this strictly requires sloppy mode (heh, get it?) which hasn't landed in all of the JS engines/transpilers yet; it'll probably be ready this winter. If anyone knows a way to run this code in a sloppy environment as of today, feel free to edit.

Well, since people still need to reproduce my output, I'll just give you the strict version that only differs in the way that it uses "let" to declare variables instead of making them globals by omitting it. Feel free to verify that I only added "let" in four places and changed nothing further. Here's the strict version that you can run today already using babel:

```
let a=x=>{let l=["#####","#   #","#","  #","    #","# #","#  ##","####",""],g=[0,1,1],t=[8,8,8,8,8,0,1,...g,7,1,0,1,7,0,2,2,2,0,7,1,1,1,7,0,2,0,2,0,0,2,0,2,2,0,2,0,1,...g,...g,0,3,3,3,0,0,4,4,4,...g,5,5,1,2,2,2,2,0,0,...g,1,1,1,1,6,1,...g,1,0,0,1,0,2,2,...g,6,0,0,1,0,5,1,0,2,0,4,0,0,3,3,3,3,1,1,1,1,...g,1,1,3,1,1,1,0,...g,3,1,1,1,1,0,3,3,0,4,0,2,0],s=(n,r)=>l[t[5*n+r]].rpad(8),y=Array(10).fill("");for(let r=-1,z=0;++r<5&z<x.length;r==4&&++z?r=-1:0){let c=x[z].charCodeAt()&31;y[r]+=s(c,r),y[9-r]+=s(c,r)}return`${y.slice(0,5).join`
`}
${"-".repeat(y[0].length-3)}

${y.slice(5).join`
`}`}
console.log(a("string"))
console.log(a("bananas"))

```

## Output

The first console.log yields **STRING**:

```
#####   #####   #####   #####   #   #   #####
#         #     #   #     #     #   #   #
#####     #     #####     #     #   #   #####
    #     #     # #       #     #  ##   #   #
#####     #     #   #   #####   #   #   #####
---------------------------------------------

#####     #     #   #   #####   #   #   #####
    #     #     # #       #     #  ##   #   #
#####     #     #####     #     #   #   #####
#         #     #   #     #     #   #   #
#####   #####   #####   #####   #   #   #####

```

and the second console.log yields **BANANAS**:

```
####    #####   #   #   #####   #   #   #####   #####
#   #   #   #   #   #   #   #   #   #   #   #   #
#####   #####   #   #   #####   #   #   #####   #####
#   #   #   #   #  ##   #   #   #  ##   #   #       #
####    #   #   #   #   #   #   #   #   #   #   #####
-----------------------------------------------------

####    #   #   #   #   #   #   #   #   #   #   #####
#   #   #   #   #  ##   #   #   #  ##   #   #       #
#####   #####   #   #   #####   #   #   #####   #####
#   #   #   #   #   #   #   #   #   #   #   #   #
####    #####   #   #   #####   #   #   #####   #####

```

## How it works:

My idea was to generate the the alphabet by compressing letters with respect to similar lines. Thus, every letter in the alphabet can be represented as a 5-dimensional vector of numbers that correspond to a string that again corresponds to a row in a letter.

This approach is made a lot easier when every letter has the same width, as this enables us to re-use some string patterns more effectively. With this idea in mind, I then designed a font that is optimized for similar-looking lines in letters, so that it compresses well:

```
#####
#   #
#####
#   #
#   #

####
#   #
#####
#   #
####

#####
#
#
#
#####

####
#   #
#   #
#   #
####

#####
#
#####
#
#####

#####
#
#####
#
#

#####
#
#####
#   #
#####

#   #
#   #
#####
#   #
#   #

#####
  #
  #
  #
#####

#####
    #
    #
    #
#####

#   #
#   #
# #
# #
#   #

#
#
#
#
#####

#####
#####
#   #
#   #
#   #

#   #
#   #
#   #
#  ##
#   #

#####
#   #
#   #
#   #
#####

#####
#   #
#####
#
#

#####
#   #
#   #
#  ##
#####

#####
#   #
#####
# #
#   #

#####
#
#####
    #
#####

#####
  #
  #
  #
  #

#   #
#   #
#   #
#   #
#####

#   #
#   #
#   #
#   #
  #

#   #
#   #
#   #
#####
#####

#   #
#   #
  #
#   #
#   #

#   #
#   #
#####
  #
  #

#####
    #
#####
#
#####

=========================================

0: #####
1: #   #
2: #
3:   #
4:     #
5: # #
6: #  ##
7: ####
8:

A = [0, 1, 0, 1, 1]
B = [7, 1, 0, 1, 7]
C = [0, 2, 2, 2, 0]
D = [7, 1, 1, 1, 7]
E = [0, 2, 0, 2 ,0]
F = [0, 2, 0, 2, 2]
G = [0, 2, 0, 1, 0]
H = [1, 1, 0, 1, 1]
I = [0, 3, 3, 3, 0]
J = [0, 4, 4, 4, 0]
K = [1, 1, 5, 5, 1]
L = [2, 2, 2, 2, 0]
M = [0, 0, 1, 1, 1]
N = [1, 1, 1, 6, 1]
O = [0, 1, 1, 1, 0]
P = [0, 1, 0, 2, 2]
Q = [0, 1, 1, 6, 0]
R = [0, 1, 0, 5, 1]
S = [0, 2, 0, 4, 0]
T = [0, 3, 3, 3, 3]
U = [1, 1, 1, 1, 0]
V = [1, 1, 1, 1, 3]
W = [1, 1, 1, 0, 0]
X = [1, 1, 3, 1, 1]
Y = [1, 1, 0, 3, 3]
Z = [0, 4, 0, 2, 0]

```

To further assist compression, I decided to only use number signs (#) to form letters, resulting in better compression. Another great thing about this approach is that it allows me to do a very simple reflection logic, since I'm not required to transform "\\" to "/". The resulting font is exceptionally ugly, but as long as it compresses well, I really don't mind about its looks.

In the end, I managed to represent every single letter of the alphabet by using eight different patterns in total (plus one additional dummy pattern for spaces). It was in my best interest to use no more than 10 different patterns (or else I'd have to pay the price of requiring two characters to write down some numbers in the code). I then serialized all letter information in an array, added a little bit of letter selection/concatenation logic, and voilà.

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


# Question
Title: Take It or Leave It II: A Game Show for Computers
This is the second in a series of puzzles that I will be posting every Monday at Midnight PST. The first puzzle is located Here.

**Context:**

> A reclusive billionaire has created a game show to attract the world's best and brightest programmers. On Mondays at the stroke of midnight, he chooses one person from a pool of applicants to be the contestant of the week, and provides them with a game. You are this week's lucky contestant!

**This week's game:**

> The host provides you with API access to a stack of 10,000 digital envelopes. These envelopes are randomly sorted, and contain within them a dollar value, between $1 and $10,000 (no two envelopes contain the same dollar value).
>
> You have 4 commands at your disposal:
>
> 1. Read(): Read the dollar figure in the envelope at the top of the stack.
> 2. Take(): Add the dollar figure in the envelope to your game show wallet, and pop the envelope off the stack.
> 3. Pass(): Pop off the envelope on the top of the stack.
> 4. Oracle(M): Returns the mean value of the next M envelopes in the stack, not including the one you can currently Read().

**The Rules:**

> 1. If you use Pass() on an envelope, the money within is lost forever.
> 2. If you use Take() on an envelope containing $X, from that point forward, you may never use Take() on an envelope containing \< $X. Take() on one of these envelopes will add $0 to your wallet.
> 3. If you use Oracle(M) on turn T, envelopes T+1 through T+M's mean will be returned. Oracle() is disabled until turn T+M.

Write an algorithm that finishes the game with the maximal amount of money.

If you're writing your algorithm in Python, feel free to use this controller provided by @Maltysen: https://gist.github.com/livinginformation/70ae3f2a57ecba4387b5

Notes 1: "Maximal" in this case means the median value in your wallet after N \>= 1000 runs. I expect, though I would love to be proven wrong, that the median value for a given algorithm will converge as N increases to infinity. Feel free to try to maximize the mean instead, but I have a feeling that the mean is more likely to be thrown off by a small N than the median is.

Note 2: as all solutions to the previous part of this puzzle are valid here, reposting them has little value. Only algorithmic improvements of previous puzzles will be considered for part II.

Edit: The prize condition has been removed, in light of this post on meta.

# Answer
# Groovy $713337 $817829 $818227

### Bootstrap code:

```
class Instance {
    List values = new ArrayList(1..10000); {
        Collections.shuffle(values)
    }
    int i = 0
    int value = 0
    int max = 0
    int nextOracle = 0

    def pass() {
        if (i >= 10000)
            throw new NoSuchElementException()
        i++
    }

    def take() {
        if (i >= 10000)
            throw new NoSuchElementException()
        int v = values[i]
        if (v > max) {
            max = v
            value += v
        }
        i++
    }

    double oracle(int m) {
        if (m <= 0 || i < nextOracle || i + m >= 10000)
            throw new NoSuchElementException()

        nextOracle = i + m
        values.subList(i + 1, i + m + 1).stream().reduce { l, r -> r+l }.get() / m
    }

    int read() {
        if (i >= 10000)
            throw new NoSuchElementException()
        values[i]
    }
}

```

### Algorithm

```
double square(double v) { v * v }
final double factor = Math.pow(1.5, 1.1)
int attempts = 5000
(1..attempts).stream().parallel().mapToLong {
    def puzzle = new Instance()

    int[] memory = 1..10000 // We will remember every envelope
    int memStart = 0

    while (memStart < 10000 - 3) {
        int value = puzzle.read()
        int i = Arrays.binarySearch(memory, memStart, 10000, value) - memStart
        if (i < 0) { // We can't use the money
            puzzle.pass()
            continue
        }
        if (i == 0) { // Of course we take the lowest
            puzzle.take()
            memStart++
            continue
        }
        int remaining = Arrays.stream(memory, i + 1 + memStart, 10000).sum() // Money we could win if taken
        int losing = Arrays.stream(memory, memStart, memStart + i).sum() // Money we cna't win if taken
        if (value > losing) { // If we pass, we lose money automatically
            puzzle.take()
            memStart += i + 1
        } else if ((losing - value * 16 / 7) * square(Math.log(i)) > remaining / factor) {
            System.arraycopy(memory, memStart, memory, ++memStart, i)
            puzzle.pass()
        } else {
            puzzle.take()
            memStart += i + 1
        }
    }

    // It's broken down to last three elements
    List values = Arrays.copyOfRange(memory, 10000 - 3, 10000)
    while (!values.contains(puzzle.read())) // Skip values we can't use
        puzzle.pass()
    int value1 = puzzle.read()
    int value2 = puzzle.oracle(1)
    if (value1 == values.max() && (
            values.contains(value2)
            ? (value1 * 2 < values.sum() && values.min() == value2)
            : (value1 < values.min() / 2 + (values - [value1]).max())
            )) {
        puzzle.pass()
    }

    // Finish it
    while (puzzle.i < puzzle.values.size()) {
        puzzle.take()
    }

    puzzle.value as Long
}.sum() / attempts // Sum runs and average

```

I compare remaining values with possible values. This script is not fast (takes 1-minute per 1000x simulations)... but it will perform the simulations simultaneously.

I have no idea why my algorithm works, but it was just trial and error: lumping mathematical operations together and manipulating the constants. I ran it 5000x for the current score, in an attempt to reduce the score's fluctuations (it's +/- $4000 depending on iteration count).

Even without the oracle at the end, it should still be (barely) beating @orlp's solution for the prior puzzle.
> 9 votes

# Answer
# C# - $803.603 now -\> $804.760 (with oracle)

Bootstrap Code

```
public static class ShuffleExtension
{
    private static Random rng = new Random();

    public static void Shuffle<T>(this IList<T> list)
    {
        int n = list.Count;
        while (n > 1) {
            n--;
            int k = rng.Next(n + 1);
            T value = list[k];
            list[k] = list[n];
            list[n] = value;
        }
    }
}

public class Puzzle
{
    public List<int> Values = new List<int>(10000);

    public Puzzle()
    {
        for ( int i = 1; i <= 10000; i++ )
        {
            Values.Add(i);
        }
        Values.Shuffle();
    }

    public int i = 0;
    public int value = 0;
    public int max = 0;
    public int nextOracle = 0;

    public void Pass() {
        if ( i >= Values.Count )
            throw new IndexOutOfRangeException();
        i++;
    }

    public void Take() {
        if (i >= Values.Count )
            throw new IndexOutOfRangeException();
        int v = Values[i];
        if (v > max) {
            max = v;
            value += v;
        }
        i++;
    }

    public double oracle(int m) {
    if (m <= 0) {
        throw new IndexOutOfRangeException();
    }
    if ( i < nextOracle ) {
        throw new IndexOutOfRangeException();
    }
    if ( i + 1 + m > Values.Count ) {
        throw new IndexOutOfRangeException();
    }

    nextOracle = i + m;
    var oracleValues = new List<int>();
    for ( int l = 0; l < m; l++ )
    {
        oracleValues.Add(Values[i + 1 + l]);
    }
    return oracleValues.Average (v => v);
}

    public int Read() {
        if (i >= Values.Count )
            throw new IndexOutOfRangeException();
        return Values[i];
    }
}

```

Game Code:

```
    void Main()
{
    var m = 0;
    for ( int l = 0; l < 1000; l++ )
    {
        var game = new Puzzle();
        var maxVal = 0;
        var lastOracle = 0;
        var lastOracleValue = 0.0m;
        var oracleValueForIOf = 0;

        for ( int i = 0; i < 10000; i++ )
        {
            var val = game.Read();
            var oracleStep = 1;
            var canUseOracle = (i - lastOracle >= oracleStep) && i + oracleStep + 1 <= 10000;
            if ( canUseOracle )
            {
                var oracle = game.oracle(oracleStep);
                lastOracle = i;
                lastOracleValue = (decimal)oracle;
                oracleValueForIOf = i + 1;
            }
            if ( TakeTheMoney(val, maxVal, oracleValueForIOf, lastOracleValue, i) )
            {
                maxVal = val;
                game.Take();
            }
            else
            {
                game.Pass();
            }
        }
        m += game.value;
    }
    ((int)(m / 1000)).Dump();
}

private bool TakeTheMoney(int val, int maxVal, int oracleValueForIOf, decimal lastOracleValue, int i)
{
    if ( val > maxVal )
    {
        if ( oracleValueForIOf != i + 1
            &&
            (val < 466.7m + (0.9352m * maxVal) + (0.0275m * i))
            )
        {
            return true;
        }

        if (oracleValueForIOf == i + 1)
        {
            if ( val < 466.7m + (0.9352m * maxVal) + (0.0275m * i) )
            {
                return true;
            }
            if ( lastOracleValue > 466.7m + (0.9352m * val) + (0.0275m * i + 1) )
            {
                if ( val < 466.7m + (0.9352m * maxVal) + (0.0275m * i + 1) )
                {
                    return true;
                }
            }
        }
    }
    return false;
}

```

Credit belongs to Reto Koradi (https://codegolf.stackexchange.com/a/54181/30910)

Edit: Basic Use of Oracle implemented. If the next oracle is above the threshold to use expand the current envelope to the index of the Oracle Index. This doesn't hit often but IT IS an Improvement ;-)
> 7 votes

# Answer
# Python - $74112

Only take, if the current value is lower than the next value (i.e. you can take both).

```
def algo():
  try:
    o=oracle(1)
  except ValueError:
    take()
  r=read()
  if r>o:
    passe()
  else:
    take()

```

# Python - (still calculating the mean)

This answer takes VERY LONG to calculate. It reaches around **670.000$**. I remember each envelope I saw. Every time I have to make a decision, I generate two lists of remaining envelopes that I could potentially add to my wallet if I take the current envelope or leave it respectively.

I did not optimize the code.

```
def algo_2():
  global max_taken, past
  weight=0.92 #Empirically chosen.
  r=read()
  if len(past)==0:
    past.append(r)
    passe()
    return
  if r<max_taken:
    past.append(r)
    take() #the same as passe
    return
  coming=[x for x in range(1,10001) if x not in past and x>max_taken and x!=r ]
  comingIfTake=[x for x in range(1,10001) if x not in past and x>r ]
  if sum(coming)*weight<=sum(comingIfTake)+r:
    past.append(r)
    take()
  else:
    past.append(r)
    passe()

```

And init\_game starts like this:

```
def init_game():
    global stack, wallet, max_taken, oracle_turns, past
    past=[]

```
> 4 votes

# Answer
# C# - $780.176

Check if the next value is within the lower 5% of all remaining values. Get more relaxed as we get to the end.

```
public class Taker
{
    private List<int> remaining;
    private Game game;

    public Taker(Game game)
    {
        this.game = game;
        remaining = Enumerable.Range(1, game.Size + 100).ToList();
    }

    int score = 0;

    public int PlayGame()
    {
        for (int i = 0; i < game.Size; i++)
        {
            if (game.Read() < game.Max ||
                game.Read() > selectThreshold() ||
                doOracle()
                )
            {
                remaining.Remove(game.Read());
                game.Pass();
                continue;
            }
            remaining = remaining.SkipWhile(j => j < game.Read()).ToList();
            score += game.Take();
        }
        return score;
    }

    private bool doOracle()
    {
        return game.Oracle(1) < game.Read() &&
            game.Oracle(1) > game.Max;
    }

    private int selectThreshold()
    {
        int selector = (int)(remaining.Count * 0.05);
        return remaining.ElementAt(selector);
    }
}

```

And my game class, very ugly, game class doesn't even validate if oracle is allowed, but since i only use Oracle(1) that shouldn't be a problem.

```
public class Game
{
    private int[] list;
    private int position = 0;
    private int max = 0;
    public int Max { get { return max; } }
    public int Size { get { return list.Length; } }

    public Game(int[] list)
    {
        this.list = list;
    }

    public int Read()
    {
        return list[position];
    }

    public int Take()
    {
        if (list[position] < max)
        {
            position++;
            return 0;
        }
        max = list[position];
        return list[position++];
    }

    public void Pass()
    {
        position++;
    }

    public int Oracle(int M)
    {
        int next = position + 1;
        M = Math.Max(0, Math.Min(M, list.Length - next));
        return new ArraySegment<int>(list, next, M).Sum();
    }
}

```
> 4 votes

# Answer
# Java, $804,991

Score is from 1001 rounds. It is probably too close to call between this answer and Stephan Schinkel's.

This is based on my answer in the previous challenge, in that it uses the same entropy-based calculation to estimate payoffs. The main difference is that it simply now takes envelopes in pairs (1 & 2, then 3 & 4, so on) and looks at the possible combinations of take-take, take-pass, pass-take, etc. It also calculates the exact estimated score when the number of valid envelopes is really small.

The "wrapper" I wrote isn't really a true wrapper, it just gives envelopes in pairs instead of calling an `Oracle(1)` function every other round.

Overall, I would say that, despite the increased complexity, this bot really isn't better than my previous one.

## Player

```
import java.lang.Math;
public class Player2
{
    public int[] V;

    public Player2(int s)
    {
        V = new int[s];
        for(int i = 0; i<V.length; i++)
        {
            V[i] = i+1;
        }
        ////System.out.println();
    }

    public boolean [] takeQ(int x, int y)
    {
        //System.out.println("Look: " + x + " " + y);
        boolean [] move = new boolean[]{false,false};
        double max = 0;
        double val = 0;
        int[] nextV = V;

        ////System.out.println("look " + x);
        int i = find(V,x);
        if(i >= 0)  //if found
        {
            //try taking first envelope
            int[] newVt = takeSlice(V,i);
            //System.out.println("  T: " + ats(newVt));
            int j = find(newVt,y);
            if(j >= 0)
            {
                //try taking first and second
                int[] newVtt = takeSlice(newVt,j);
                val = x + y + calcVal(newVtt);
                //System.out.println("  TT: " + ats(newVtt) + " " + val);
                if(val > max)
                {
                    move = new boolean[]{true,true};
                    max = val;
                    nextV = newVtt;
                }
            }
            //try taking first and passing second
            int[] newVtp = passSlice(newVt,j);

            val = x + calcVal(newVtp);
            //System.out.println("  TP: " + ats(newVtp) + " " + val);
            if(val > max)
            {
                move = new boolean[]{true,false};
                max = val;
                nextV = newVtp;
            }
        }
        int[] newVp = passSlice(V,i);
        //System.out.println("  V: " + ats(V));
        //System.out.println("  P: " + ats(newVp));
        int j = find(newVp,y);
        if(j >= 0)
        {
            //try passing first and taking second
            int[] newVpt = takeSlice(newVp,j);
            val = y + calcVal(newVpt);
            //System.out.println("  PT: " + ats(newVpt) + " " + val);
            if(val > max)
            {
                move = new boolean[]{false,true};
                max = val;
                nextV = newVpt;
            }
        }
        //try taking first and passing second
        int[] newVpp = passSlice(newVp,j);

        val = calcVal(newVpp);
        //System.out.println("  PP: " + ats(newVpp) + " " + val);
        if(val > max)
        {
            move = new boolean[]{false,false};
            max = val;
            nextV = newVpp;
        }
        V = nextV;
        //System.out.println("  NEW: " + ats(V));
        return move;
    }

    public static String ats(int [] a)
    {
        String s = "";
        for(int i = 0; i < a.length; i++)
        {
            s += a[i] + ",";
        }
        return s;
    }

    public static int[] takeSlice (int[] list, int loc)
    {
        int [] newlist = new int[list.length - loc - 1];
        for(int j = loc + 1; j < list.length; j++)
        {
            newlist[j - loc - 1] = list[j];
        }
        return newlist;
    }

    public static int[] passSlice (int[] list, int loc)
    {
        int [] newlist = list;
        if(loc >= 0)
        {
            newlist = new int[list.length-1];
            for(int k = 0; k < loc; k++)
            {
                newlist[k] = list[k];
            }
            for(int k = loc + 1; k < list.length; k++)
            {
                newlist[k-1] = list[k];
            }
        }
        return newlist;
    }

    public static double calcVal(int [] list)
    {
        if(list.length < 8)
        {
            for(int i : list)
            {
                ////System.out.print(i + ",");
            }

                ////System.out.println();
            return computeMean(list);

        }
        return smoothEstimate(list);
    }

    public static double computeMean(int[] V)
    {
        if(V.length == 1)
        {
            return V[0];
        }
        else if(V.length > 1)
        {
            double[] Es = new double[V.length];
            for(int i = 0; i < V.length; i++)
            {
                int[] newVp = new int[V.length - 1];
                for(int j = 0; j < i; j++)
                {
                    newVp[j] = V[j];
                }
                for(int j = i + 1; j < V.length; j++)
                {
                    newVp[j-1] = V[j];
                }
                double pass = computeMean(newVp);
                int[] newVt = new int[V.length - i - 1];
                for(int j = i + 1; j < V.length; j++)
                {
                    newVt[j - i - 1] = V[j];
                }
                double take = V[i] + computeMean(newVt);
                if(take > pass)
                {
                    Es[i] = take;
                }
                else
                {
                    Es[i] = pass;
                }
            }
            double sum = 0;
            for(double d : Es)
            {
                sum += d;
            }
            return sum/V.length;
        }
        else
        {
            return 0;
        }
    }

    public static double smoothEstimate(int [] list)
    {
        double total = 0;
        for(int i : list)
        {
            total+=i;
        }
        double ent = 0;
        for(int i : list)
        {
            if(i > 0)
            {
                ent -= i/total * Math.log(i/total);
            }
        }
        ////System.out.println("      total " + total);
        ////System.out.println("      entro " + Math.exp(ent));
        ////System.out.println("      count " + list.length);
        return total * Math.pow(Math.exp(ent),-0.5) * 4.0/3;// * 1.1287 + 0.05284);
    }

    public static int find(int[] list, int search)
    {
        int first  = 0;
        int last   = list.length - 1;
        int middle = (first + last)/2;

        while( first <= last )
        {
            if ( list[middle] < search )
                first = middle + 1;
            else if ( list[middle] == search )
                break;
            else
                last = middle - 1;

            middle = (first + last)/2;
        }

        if(first > last)
        {
            return -1;
        }
        return middle;
    }
}

```

## Controller

```
import java.lang.Math;
import java.util.Random;
import java.util.ArrayList;
import java.util.Collections;
public class Controller2
{
    public static void main(String [] args)
    {
        int size = 10000;
        int rounds = 1001;
        ArrayList<Integer> results = new ArrayList<Integer>();
        for(int round = 0; round < rounds; round++)
        {
            int[] envelopes = new int[size];
            for(int i = 0; i<envelopes.length; i++)
            {
                envelopes[i] = i+1;
            }
            shuffleArray(envelopes);
            Player2 p = new Player2(size);
            int cutoff = 0;
            int winnings = 0;
            for(int i = 0; i<envelopes.length; i+=2)
            {
                boolean [] take = p.takeQ(envelopes[i],envelopes[i+1]);
                if(take[0] && envelopes[i] >= cutoff)
                {
                    winnings += envelopes[i];
                    cutoff = envelopes[i];
                }
                if(take[1] && envelopes[i+1] >= cutoff)
                {
                    winnings += envelopes[i+1];
                    cutoff = envelopes[i+1];
                }
            }
            results.add(winnings);
        }
        Collections.sort(results);
        System.out.println(rounds + " rounds, median is " + results.get(results.size()/2));

    }

    //stol... I mean borrowed from http://stackoverflow.com/questions/1519736/random-shuffling-of-an-array
    static void shuffleArray(int[] ar)
    {
        Random rnd = new Random();
        for (int i = ar.length - 1; i > 0; i--)
        {
            int index = rnd.nextInt(i + 1);
            // Simple swap
            int a = ar[index];
            ar[index] = ar[i];
            ar[i] = a;
        }
    }
}

```

Bitcoin address: 1BVBs9ZEP8YY4EpV868nxi2R23YfL7hdMq
> 4 votes

# Answer
# Python 3 - $615570

Doesn't actually use the oracle... Eh :)

```
def algo():
    global prevs

    try:
        prevs.append(read())
    except NameError:
        prevs = [read()]

    if len(prevs) > 10000:
        prevs = [prevs[-1]]

    if read() < round(len(prevs),-1):
        take()
    else:
        passe()

```

Builds up a list of all previous envelopes and check if the current envelope is less than the number of previous envelopes in 10 envelope increments.
> 3 votes

# Answer
## Python, 87,424

Here's a plain and easy algorithm, the lucky seven.

```
def LuckyNumber7():
Test = read()
if "7" in str(Test):
    take()
else:
    passe()

test(LuckyNumber7)

```

Basically what it does is it converts read() to a string and checks if there's a seven in it. If there is, it takes the envelope. If not, it passes it.

It averages around 81,000, I haven't been keeping track.
> 0 votes

---
Tags: code-challenge, game, stack
---


title: Balance a set of weights on a seesaw

text:
# Question
Title: Balance a set of weights on a seesaw
# **Balancing Act**

**Overview**

Given an input of 3 single-digit positive integers representing a set of weights, output an ASCII representation of a seesaw with the weights placed on it so that it is in balance around a central pivot, taking lever effects into account.

Each number has a weight equal to its value. The torque of each number is the weight multiplied its the distance from the center in characters. For the seesaw to be in balance, the sum torque of the weights on the left of the seesaw must equal that of those on the right, like this.

**Input**

3 integers in the range of 1-9. You can input the integers however is convenient, e.g. a tuple, 3 comma-separated values etc. However your program must be able to handle numbers input in any order (i.e. no assuming the values will be sorted). Duplicate numbers may be input (e.g. 2,3,2).

The inputs will always mathematically allow for a valid output, otherwise the input is not valid.

**Output**

The output should be a 2-line ASCII representation of the seesaw with the weights placed on it. On the first line are the digits, spaced in order to balance them on the seesaw.

Numbers may not be placed in the very center of the scale, where the distance and therefore the torque would be zero. Valid distances from the center range from 1-10 characters inclusive to the left or right of the pivot.

In the spaces unoccupied by the numbers are 18 underscore characters (a center underscore and 10 on each side, minus the 3 positions occupied by the numbers). On the last line is a single caret character aligned with the center of the scale, representing the pivot.

**Examples**

Input:

```
4,7,2

```

Output:

```
________7___42_______
          ^

```

7\*2 = 4\*2 + 2\*3

Numbers can be output on either side, for example this would also be valid:

```
_______24___7________
          ^

```

2\*3 + 4\*2 = 7\*2

Numbers can be placed anywhere on the scale as long as they balance, e.g:

Input:

```
3,1,5

```

Output:

```
_____5________1__3___
          ^

```

5\*5 = 1\*4 + 3\*7

or

```
____5________1_____3_
          ^

```

5\*6 = 1\*3 + 3\*9

or

```
____5___________1_3__
          ^

```

5\*6 = 1\*6 + 3\*8

etc

Your program only has to output one of the valid outputs. It does not have to output an error if the input is not valid.

**Notes**

* This is so the shortest program in bytes wins
* Program may be a stand-alone or a function that accepts the numbers as input and returns a string.
* Trailing newline and white-space on last line is optional
* If you don't know what a seesaw is, it's also known as a teeter-totter or a teeterboard.

# Answer
> 13 votes
# CJam, ~~40~~ ~~39~~ 38 bytes

```
q~21Ue]e!{21,Af-Aest.*:+!}=0'_erNAS*'^

```

Try it online.

### How it works

```
q~                                     e# Read and evaluate the input.
  21Ue]                                e# Append zeroes to achieve a length of 21.
       e!                              e# Push all unique permutations.
         {               }=            e# Find the first permutation such that:
          21,                          e#  Push [0 ... 20].
             Af-                       e#  Subtract 10 from each.
                Aest                   e#  Replace the element at index 10 with the
                                       e#  current time (ms since epoch) to push
                                       e#  [-10 ... -1 <big number> 1 ... 10].
                    .*                 e#  Multiply each number of the permutation
                                       e#  by the corresponding distance.
                      :+               e#  Add the products.
                                       e#  The timestamp makes sure that this sum
                                       e#  is non-zero for a non-zero element in
                                       e#  the middle of the permutation.
                        !              e#  Push the logical NOT of the sum.
                           0'_er       e# Replace zeroes with underscores.
                                NAS*'^ e# Push a linefeed, ten spaces and a caret.

```

# Answer
> 5 votes
# Java, 519 414 321 bytes

```
static int f(int a,int b,int c){int i,j,k;for(i=-10;i<=10;i++)for(j=i+1;j<=10;j++)for(k=j+1;k<=10;k++){if(a*i+b*j+c*k==0&&i!=0&&j!=0&&k!=0){for(int q=0;q<21;q++){if(q==10+i)p(a);else if(q==10+j)p(b);else if(q==10+k)p(c);else p('_');}p("\n          ^\n");return 0;}}return 0;}static void p(Object a){System.out.print(a);}}

```

My first attempt at golfing.

You can call it with `f(a,b,c)`. Try it here

**EDIT:** Used izlin method of check `(a*i+b*j+c*k)==0`

**EDIT:** Thanks, J Atkin for the golfing suggestions.

# Answer
> 5 votes
## Pyth, ~~67~~ ~~58~~ ~~53~~ 49 bytes

~~This feels a little on the huge side for Pyth, but I'm not nearly familiar enough with the language to be able to get this much smaller.~~ Sub 50 bytes, I'm finally happy with this!

```
V.c-KrT-011Z3FY.pQIqs*VNYZjkm?}dN@YxNd\_K+*dT\^.q

```

Input is expected as an array of integers, for example `[1,2,3]`. Try it here.

Explaination:

```
V.c-KrT-011Z3FY.pQIqs*VNYZjkm?}dN@YxNd\_K+*dT\^.q
                                                       Implicit: Q = eval(input())
     rT-011                                            Create range from 10 to -10
    K                                                  Store in K
   -       Z                                           Drop 0 from the above
V.c         3                                          For N in (combinations of the above of size 3)
             FY.pQ                                     For Y in (permutations of input)
                     *VNY                              Multiply each element in N by the corresponding element in Y
                    s                                  Take the sum
                  Iq     Z                             If it's equal to zero:
                            m           K              For d in K (K = [10, ..., -10])
                             ?}dN                      Is d in N?
                                 @YxNd                 If so, get corresponding value from Y
                                      \_               Otherwise, get '_'
                          jk                           Join the resulting array into a string (implicit print)
                                         +*dT\^        Join 10 spaces and '^', implicit print
                                               .q      Break all loops and exit

```

And finally, some example inputs and outputs:

```
[1,1,1] ->
1__________1_______1_
          ^

[2,9,5] ->
2____5_________9_____
          ^

[9,8,5] ->
5____8______________9
          ^

```

# Answer
> 5 votes
# CJam, ~~46~~ 44 bytes

```
'_21*q~K,Am3m*{___&=*Afm1$.*:+!}=.{\t}NAS*'^

```

Test it here.

## Explanation

First, an observation: we never need to put two digits on the ends of the seesaw. Whenever that's a valid solution, there is at least one other valid solution (according to the pastebin in the comment on the challenge).

```
'_21*   e# Push a string of 21 underscores.
q~      e# Read and eval input.
K,      e# Push the array [0 1 .. 19 20]
Am      e# Remove the 10. This is now an array of all valid positions on the seesaw.
3m*     e# Get all 3-tuples of valid positions.
{       e# Select the first tuple for which the following block yields a truthy result.
  ___   e# Make three copies of the tuple.
  &=    e# Intersect the last two copies and check for equality with the first one.
        e# This yields 1 if all positions are distinct, and 0 otherwise.
  *     e# Repeat the original tuple that many times. That is, if the positions are
        e# distinct, leave the tuple unchanged. Otherwise, replace it with an empty array.
  Afm   e# Subtract 10 from each position to get its weight.
  1$    e# Copy the input digits.
  .*    e# Take the pairwise product of weights and digits. If the weights are empty
        e# (because they were not unique), this will just yield a list of the digits.
  :+    e# Sum the weighted digits. If the weights were not unique, this will just sum
        e# the digits and will always be positive.
  !     e# Logical NOT - give 1 if the sum was 0, or 0 otherwise.
}=
.{\t}   e# For each pair of digit and position, replace that position in the underscore
        e# string with the corresponding digit.
N       e# Push a newline.
AS*     e# Push ten spaces.
'^      e# Push a caret.

```

# Answer
> 4 votes
## C - ~~237~~ 228 Bytes

```
i,j,k;f(a,b,c){char o[]="_____________________\n          ^";for(i=-10;i<9;i+=i+1?1:2){for(j=i+1;j<11;j+=j+1?1:2){for(k=j+1;k<11;k+=k+1?1:2){if((a*i+b*j+c*k)==0){o[i+10]=a+48;o[j+10]=b+48;o[k+10]=c+48;printf("%s",o);return;}}}}}

```

You can call it with `f(a,b,c)`.

Try it here.

Example outputs:

```
f(4,7,2):
4_____________7_2____
          ^

f(3,1,5)
3____1___________5___
          ^

```

# Answer
> 3 votes
## Python 2.7 ~~235~~ ~~226~~ 219 Bytes

```
def s(n,p=__import__("itertools").permutations):
 l=["_"]*21
 for p,q in[[(a,x+10),(b,y+10),(c,10-z)]for a,b,c in p(n,3)for x,y,z in p(range(1,11),3)if x!=y and a*x+b*y==c*z][0]:l[q]=`p`
 return`l`[2::5]+"\n"+" "*10+"^"

```

Testing it with some basic examples- `(1,1,1),(1,2,1),(3,1,5),(4,7,2)` results in- :

```
(1, 1, 1)
_______1___11________
          ^
(1, 2, 1)
_____1_____12________
          ^
(3, 1, 5)
________5__3_____1___
          ^
(4, 7, 2)
_2_________47________
          ^

```

Outputs for all possible inputs pasted here

# Answer
> 3 votes
# PHP, 278 bytes

A brute-force solution that uses a bunch of nested loops and a couple of tests.

```
$p=explode(',',$argv[$i=1]);for(;$i<=10;$i++)for($j=1;$j<=10;$j++)
for($k=1;$k<=10;$k++)if($j-$k)for($l=0;$l<3;$l++){$q=array_shift($p);
if($i*$q==$j*$p[0]+$k*$p[1]){$o=str_repeat('_',21);$o[10-$i]=$q;$o[10+$j]=$p[0];
$o[10+$k]=$p[1];echo($o."\n          ^\n");}array_push($p,$q);}

```

As always, put it into a file (let's name it `seesaw.php`), join the lines (split here for readability), put the PHP marker (`<?php`) at the beginning of the file (technically, it is not part of the program) and you're good to go.

An example of execution:

```
$ php seesaw.php 9,2,1
_________9_2_____1___
          ^
_________9__2__1_____
          ^
_________9_1__2______
          ^
________9_____2_____1
          ^
________9______2__1__
          ^
________9_____1__2___
          ^
________9___1_____2__
          ^
_______9_________1__2
          ^
____2______9_1_______
          ^
___2_______9___1_____
          ^
__2________9_____1___
          ^
_2_________9_______1_
          ^

```

It generates and displays all the solutions (without reflections), but it does not strip the duplicates (when the input values contain duplicates).

# Answer
> 3 votes
# Julia, 154 bytes

```
f(a,b,c)=(x=replace(join(first(filter(p->p⋅[-10:-1,1:10]==0,permutations([a,b,c,zeros(Int,17)])))),"0","_");print(x[1:10]*"_"*x[11:20]*"\n"*" "^10*"^"))

```

Ungolfed + explanation:

```
function f(a,b,c)
    # Create a 20-element array of the input with 17 zeros
    z = [a,b,c,zeros(Int,17)]

    # Get the set of all permutations of z such that the dot product
    # of the permutation with the distances is 0
    d = filter(p -> p ⋅ [-10:-1,1:10] == 0, permutations(z))

    # Join the first element of d into a string and replace all of
    # the zeros with underscores
    x = replace(join(first(d)), "0", "_")

    # Print the output
    print(x[1:10] * "_" * x[11:20] * "\n" * " "^10 * "^")
end

```

# Answer
> 2 votes
# C, 252 (214) bytes

Call with a,b,c as arguments on command line.

```
e=48;main(_,v,x,y,z,a,b,c)char**v;{char s[]="_____________________\n          ^";x=*v[1]-e;y=*v[2]-e;z=*v[3]-e;for(a=-1;a+11;--a)for(b=-10;b-11;++b)_=a*x+b*y,!b|b==a|_%z?0:(c=-_/z,c&c<11&c>-11?s[a+10]=x+e,s[b+10]=y+e,s[c+10]=z+e,puts(s),exit(0):0);}

```

If main can be ommitted, byte count drops to 214 for a function.

```
a,b,c;f(x,y,z){char s[]="_____________________\n          ^";for(a=-1;a+11;--a)for(b=-10;b-11;++b)!b|b==a|(a*x+b*y)%z?0:(c=-(a*x+b*y)/z,c&&c<11&&c>-11?s[a+10]=x+48,s[b+10]=y+48,s[c+10]=z+48,puts(s),b=10,a=-b:0);}

```

Both use the same strategy of placing the first weight on the left, then scanning along possible second weight positions and calculating the third weight. This allows the removal of an inner loop.

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


title: Golfing with User Agents

text:
# Question
Title: Golfing with User Agents
Usually when performing an internet challenge, there's no problem with having to specify a user agent, but when it comes to dealing with Google, it changes.

Google blacklists the Urllib user agent, presumably to stop spambots, so you have to specify a user agent. This takes up many bytes, and is frankly rather annoying.

Example 1. Example 2. Example 3.

***Note:*** *I have updated my Python answers to use the tip suggested below*

So how do you get around this problem using the shortest number of bytes?

# Answer
> 4 votes
The requests module, if allowed, is much shorter and easier than urllib in Python (2 and 3):

```
__import__('requests').get('url').text

```

On my computer, the user agent defaults to:

```
python-requests/2.3.0 CPython/3.4.3 Darwin/14.3.0

```

---
Tags: code-golf, tips, internet
---


title: Magic Square Challenge

text:
# Question
Title: Magic Square Challenge
For the purpose of this question, a magic square is an `n`×`n` square of (not necessarily distinct) positive integers, where all rows, columns, and main diagonals add to a "magic constant" `m`.

### Your Task

Create a function or full program that, given the magic number `m` and a list representing a square **with at most one wrong number in each row and column**, will output a list with the entries rearranged to represent a correct square. Your program will be expected to handle any solvable square of any size. Your program should take less than twenty minutes for n=7 or smaller. Assume that all input is solvable.

### Example Input (list, m)

```
[16, 16, 11, 9, 14, 17, 9, 29, 13, 1, 15, 5, 6, 16, 15, 7, 3, 17, 11, 12, 14, 17, 3, 8, 6], 58

```

which represents this square1:

> 16 16 **11** 09 14
> **17** 09 29 13 01
> 15 05 06 **16** 15
> 07 **03** 17 11 12
> 14 17 03 08 **06**

A compliant solution has to solve the following 7x7 square within the time limit.

```
[31, 19, 10, 13, 14, 32, 15, 6, 21, 17, 22, 30, 17, 7, 17, 30, 17, 24, 17, 11, 8, 7, 22, 33, 13, 15, 17, 11, 14, 16, 21, 22, 13, 11, 29, 16, 13, 3, 19, 12, 12, 43, 27, 13, 19, 13, 20, 18, 11], 123

```

### Example Output

For the first test case, this is the only correct solution.

```
[16, 16, 3, 9, 14, 6, 9, 29, 13, 1, 15, 5, 6, 17, 15, 7, 11, 17, 11, 12, 14, 17, 3, 8, 16]

```

For a bonus of **-10**, format your output into a square and pad single digits with zeroes as below.2

> 16 16 **03** 09 14
> **06** 09 29 13 01
> 15 05 06 **17** 15
> 07 **11** 17 11 12
> 14 17 03 08 **16**

---

1 Bolded numbers are in incorrect cells.
2 Bolded numbers have switched cells.

# Answer
# CJam, ~~73~~ 70 bytes

```
q~:Q,mQ:Le!{QL/.{1$W$W*t_:+W*t}:Te_$Q$=Tz{W%_L,.=a\}2*++::+)-!*}=&T"%02d "ffe%N*

```

The above code is 80 bytes long and qualifies for the bonus.

Time complexity is **O(n!)** for **n×n** squares. For **9×9**, this translates to 7 seconds on my machine.

Try it online: permalink for Chrome | permalink for Firefox
> 3 votes

---
Tags: code-golf
---


title: X Marks the Spot

text:
# Question
Title: X Marks the Spot
# X Marks the spot

Your goal is to add a cross-hair around the capital X:

## Example Input / Output

Input:

```
                mdhyyyyyyyhhhddmmm
            mdyyssoo  oooosyyyhhhdmm
          hsso     oossoooooyyhhdhhdmmm
        yoooooo     oo ssysssyhhdyyyhmmmm
      myso oso  o  oyo    hhhdhhyhyhhm mm m
     mhsyhhys  oss      yyyhhhsosyhhmmmmdmmm
    mhyhhhy y         ssyhoho o shhdmmmmdmmmm
    hhyyyh   s   oo syysyyhhdysso oyhdhhhmmmmm
   dhysyys      sdysoXoyyyyhhso     syshm  mmm
   hhyhyo       o      osss y   shhyyhd mmmmmm
   yyhyyyss           o  oyyyydmmdmmmmmmmmm mm
   ysyhyhhho   s     osy  sdm m  mddmmddhydmmm
   h  oshhhyyyddhoo  ooyysshdmdohdmmdmddsshmmm
    y   oyhhhdhhsyhsssshdddsss    hdddyyyhddm
    dyyshyyhssyyhyyyyddhhmmdmmmdy syssoosyhdm
     hsyyhhhhsoo sooyyhhdoohdhhyhyysoo  osdm
      doyhhhyyyyhhhysyyy oossyyssso   osydm
        soyhyyhhhhhhyhyyyooos       ohdddm
         msoyyyyyyyhyyyyo ooo       syyd
            ho oyyysooo    osso   osyd
               dhyyysssyyyyyysoosdm
                    mmdddddmmm

```

Output:

```
                mdhyyyyyyyhhhddmmm
            mdyyssoo  oooosyyyhhhdmm
          hsso     oossoooooyyhhdhhdmmm
        yoooooo     oo ssysssyhhdyyyhmmmm
      myso oso  o  oyo    hhhdhhyhyhhm mm m
     mhsyhhys  oss   |  yyyhhhsosyhhmmmmdmmm
    mhyhhhy y        |ssyhoho o shhdmmmmdmmmm
    hhyyyh   s   oo s|ysyyhhdysso oyhdhhhmmmmm
   dhysyys      -----X-----hhso     syshm  mmm
   hhyhyo       o    | osss y   shhyyhd mmmmmm
   yyhyyyss          |o  oyyyydmmdmmmmmmmmm mm
   ysyhyhhho   s     |sy  sdm m  mddmmddhydmmm
   h  oshhhyyyddhoo  ooyysshdmdohdmmdmddsshmmm
    y   oyhhhdhhsyhsssshdddsss    hdddyyyhddm
    dyyshyyhssyyhyyyyddhhmmdmmmdy syssoosyhdm
     hsyyhhhhsoo sooyyhhdoohdhhyhyysoo  osdm
      doyhhhyyyyhhhysyyy oossyyssso   osydm
        soyhyyhhhhhhyhyyyooos       ohdddm
         msoyyyyyyyhyyyyo ooo       syyd
            ho oyyysooo    osso   osyd
               dhyyysssyyyyyysoosdm
                    mmdddddmmm

```

---

Input:

```
000000000000
000000000000
0000X0000000
0000000X0000
000000000000
000000000000
000000000000
000000000000
000000000000
000000000000
000000000000
000000000000

```

Output:

```
     |
 0000|00|0000
 0000|00|0000
-----X--+--00
 00--+--X-----
 0000|00|0000
 0000|00|0000
 0000000|0000
 000000000000
 000000000000
 000000000000
 000000000000
 000000000000

```

---

Input:

```
00000000000000000
00000000000000000
00000000000000000
00000X000X0000000
00000000000000000
00000000000000000
00000000000000000
00000000000000000
00000000000000000
00000000000000000
00000000000000000
00000000000000000

```

Output:

```
00000|000|0000000
00000|000|0000000
00000|000|0000000
----+#+++#+----00
00000|000|0000000
00000|000|0000000
00000|000|0000000
00000000000000000
00000000000000000
00000000000000000
00000000000000000
00000000000000000

```

## Crosshair

Your cross-hair should be a 3-tall and 5-wide:

```
     |
     |
     |
-----X-----
     |
     |
     |

```

### Input

Input will be at least 12x12 characters in size and will consist of only ASCII characters. It can be taken in through STDIN or function argument. The input will not always contain an X. Input will be in any shape and have an arbitrary amount of whitespace. The input will not contain any of: `+`, `-`, `#`, and `|`

### Output

Output can be through STDOUT or a function's return value. Output should be the input image with the cross-hair drawn. If there is not enough space to draw the crosshair, you must add lines / spaces to draw it. Overlapping spots should be replaced with a `+`. If the `|` or `-` of the crosshairs overlaps an `X`, instead of a `+`, an `#` should appear.

Trailing whitespace is not allowed *except* for a single newline at the very end.

---

This is code-golf so shortest code in bytes wins!

# Answer
> 4 votes
# CoffeeScript, ~~345~~ ~~336~~ 327 bytes

```
Z=(s,c)->s in'X#'&&'#'||s in'-|+'&&'+'||c
X=(s)->l=u=0;o=(r.split ''for r in s.split '\n');c in'X#'&&(i-x&&(o[y][i]=Z o[y][i],'-';i<l&&l=i)for i in[x-5..x+5];i-y&&((o[i]?=[])[x]=Z o[i][x],'|';i<u&&u=i)for i in[y-3..y+3])for c,x in r for r,y in o;((o[y][x]||' 'for x in[l...o[y].length]).join ''for y in[u...o.length]).join '\n'

```

`X` is the function to call.

### Explained:

```
# get new char. s - old char. c - '|' or '-'
Z=(s,c)->s in'X#'&&'#'||s in'-|+'&&'+'||c

X=(s)->

  # leftmost and upmost positions
  l=u=0

  # split input into 2D array
  o=(r.split ''for r in s.split '\n')

  # for every 'X' or '#'
  c in'X#'&&(

    # for positions to left and right
    i-x&&(

        # draw horisontal line
      o[y][i]=Z o[y][i],'-'

      # update leftmost position
      i<l&&l=i

    )for i in[x-5..x+5]

    # for positions above and below
    i-y&&(

      # add row if necessary and draw vertical line
      (o[i]?=[])[x]=Z o[i][x],'|'

      # update upmost position
      i<u&&u=i

    )for i in[y-3..y+3]

  )for c,x in r for r,y in o

  # concatenate into string, replacing empty chars with spaces
  ((o[y][x]||' 'for x in[l...o[y].length]).join ''for y in[u...o.length]).join '\n'

```

### Executable:

```
<script src="http://coffeescript.org/extras/coffee-script.js"></script>
<script type="text/coffeescript">

Z=(s,c)->s in'X#'&&'#'||s in'-|+'&&'+'||c
X=(s)->l=u=0;o=(r.split ''for r in s.split '\n');c in'X#'&&(i-x&&(o[y][i]=Z o[y][i],'-';i<l&&l=i)for i in[x-5..x+5];i-y&&((o[i]?=[])[x]=Z o[i][x],'|';i<u&&u=i)for i in[y-3..y+3])for c,x in r for r,y in o;((o[y][x]||' 'for x in[l...o[y].length]).join ''for y in[u...o.length]).join '\n'

################################################################################
# tests follow
s = ['''
                mdhyyyyyyyhhhddmmm
            mdyyssoo  oooosyyyhhhdmm
          hsso     oossoooooyyhhdhhdmmm
        yoooooo     oo ssysssyhhdyyyhmmmm
      myso oso  o  oyo    hhhdhhyhyhhm mm m
     mhsyhhys  oss      yyyhhhsosyhhmmmmdmmm
    mhyhhhy y         ssyhoho o shhdmmmmdmmmm
    hhyyyh   s   oo syysyyhhdysso oyhdhhhmmmmm
   dhysyys      sdysoXoyyyyhhso     syshm  mmm
   hhyhyo       o      osss y   shhyyhd mmmmmm
   yyhyyyss           o  oyyyydmmdmmmmmmmmm mm
   ysyhyhhho   s     osy  sdm m  mddmmddhydmmm
   h  oshhhyyyddhoo  ooyysshdmdohdmmdmddsshmmm
    y   oyhhhdhhsyhsssshdddsss    hdddyyyhddm
    dyyshyyhssyyhyyyyddhhmmdmmmdy syssoosyhdm
     hsyyhhhhsoo sooyyhhdoohdhhyhyysoo  osdm
      doyhhhyyyyhhhysyyy oossyyssso   osydm
        soyhyyhhhhhhyhyyyooos       ohdddm
         msoyyyyyyyhyyyyo ooo       syyd
            ho oyyysooo    osso   osyd
               dhyyysssyyyyyysoosdm
                    mmdddddmmm
'''
'''
000000000000
000000000000
0000X0000000
0000000X0000
000000000000
000000000000
000000000000
000000000000
000000000000
000000000000
000000000000
000000000000
'''
'''
00000000000000000
00000000000000000
00000000000000000
00000X000X0000000
00000000000000000
00000000000000000
00000000000000000
00000000000000000
00000000000000000
00000000000000000
00000000000000000
00000000000000000
'''
'X'
'XX\nXX'
]
document.write '<pre>'
document.write '\n\n',X x for x in s
</script>
```

# Answer
> 4 votes
# Python 3, ~~577~~ ~~519~~ ~~515~~ ~~490~~ ~~475~~ ~~467~~ 454 bytes

```
def c(g,d):
 R,L,V,e,b=range,list,len,'-|+','#';t,g=(lambda g,d:sum([[(i,j)for j in R(V(L(g.split('\n')[i])))if g.split('\n')[i][j]==d]for i in R(V(g.split('\n')))],[]))(g,d),[L(i)for i in g.split('\n')]
 for a,r in t:
  for j in R(a-3,a+4):
   if V(g)>j>-1:n=g[j][r];g[j][r]='+'if n in e else'#'if n in(d,b)else'|'
  for j in R(r-5,r+6):
   if V(g[a])>j>-1:n=g[a][j];g[a][j]='+'if n in e else'#'if n in(d,b)else'-'
 return'\n'.join(''.join(l)for l in g)

```

I'm not sure how much farther I can golf this.

### Usage:

```
c(g, d)

```

Where `g` is the input grid and `d` is the crosshair-marking character.

# Answer
> 3 votes
# Perl, 370 bytes

```
sub r{$h=pop;($=[$n=pop].=$"x(1+"@_"-length$=[$n]))=~s!(.{@_})(.)!"$1".($2=~/[-|+]/?'+':$2=~/[X#]/?'#':$h)!e}map{chop;push@c,[$-,pos]while/X/g;$-++}@==<>;($x,$y)=@$_,3-$x>$a?$a=3-$x:0,$x+5-@=>$b?$b=$x+5-@=:0,6-$y>$c?$c=6-$y:0 for@c;@==($",@=)for 1..$a;$_=$"x$c.$_ for@=;map{($x,$y)=@$_;$_&&r$y+$c+$_-1,$x+$a,'-'for-5..5;$_&&r$y+$c-1,$x+$_+$a,'|'for-3..3}@c;print@=,$,=$/

```

Usage, save above as `xmarks.pl`:

`perl xmarks.pl <<< 'X'`

I'm not sure how much smaller I can make this, but I'm sure I'll come back to it later! I might post an explanation if anyone is interested too.

Handles input of `X` and non-square inputs as well now.

# Answer
> 2 votes
# Python 2, ~~755 706 699 694 678~~ 626 Bytes

Expects input on stdin, with a trailing newline. The end of input is triggered with `cmd+d`.

```
import sys;a=sys.stdin.readlines();b=max;c=len;d=enumerate;e=c(b(a,key=lambda x:c(x)))-1;a=[list(line.replace('\n','').ljust(e))for line in a];R=range;f=lambda:[[i for i,x in d(h)if x=='X']for h in a+[[]]*4];q=lambda y,z:'#'if z=='X'else'+'if z in'|-+'else y;g=f();h=j=k=l=0
for m,n in d(g):
 if n:h=b(3-m,h);l=b(abs(n[0]-5),l);j=b(m-c(a)+4,j);k=b(n[-1]-e+6,k)
o=[' ']*(l+k+e);a=[o for _ in R(h)]+[[' ']*l+p+[' ']*k for p in a]+[o for _ in R(j)];g=f()
for m,x in d(a):
 for i in[3,2,1,-1,-2,-3]:
    for r in g[m+i]:x[r]=q('|',x[r])
 for r in g[m]:
    for i in R(5,0,-1)+R(-1,-6,-1):x[r+i]=q('-',x[r+i])
for s in a:print''.join(s)

```

Full program:

```
import sys

lines = sys.stdin.readlines()

# pad all lines with spaces on the right
maxLength = len(max(lines, key=lambda x:len(x))) - 1 # Subtract the newline
lines = [list(line.replace('\n', '').ljust(maxLength)) for line in lines]

def findX():
    global xs
    xs = [[i for i, ltr in enumerate(line) if ltr == 'X'] for line in lines+[[]]*4]

# add sufficient padding to the edges to prevent wrap
findX()
top,bottom,right,left=0,0,0,0
for ind, item in enumerate(xs):
    if item:
        top = max(3-ind, top)
        left = max(abs(item[0]-5), left)
        bottom = max(ind-len(lines)+4, bottom)
        right = max(item[-1]-maxLength+6, right)
clear = [' '] * (left+right+maxLength)
lines = [clear for _ in range(top)] + [[' ']*left + line + [' ']*right for line in lines] + [clear for _ in range(bottom)]

findX()
def chooseChar(expected, curr):
    return '#' if curr == 'X' else ('+' if curr in '|-+' else expected)

for ind, x in enumerate(lines):
    # try:
        for i in [3, 2, 1, -1, -2, -3]:
            for elem in xs[ind+i]:
                x[elem] = chooseChar('|', x[elem])
        for elem in xs[ind]:
            for i in [5, 4, 3, 2, 1, -1, -2, -3, -4, -5]:
                x[elem+i] = chooseChar('-', x[elem+i])
    # except:f

for line in lines: print(''.join(line))

```

I'm sure that a lot more golfing could be done on this (since I'm still learning python), so any help is appreciated.

## Edits

1. Shaved about 50 bytes from `findX` by using for comprehensions
2. Saved 7 bytes thanks to @mbomb007's suggestion about using `range` instead of a literal array
3. Removed 5 bytes by changing `findX` to a lambda
4. Saved 15 bytes by extending `xs` by 4 and eliminating the `try-except` block
5. Shaved 2 more by using tabs instead of spaces
6. Removed 5 bytes by using `h=i=j=k=l=0` instead of `h,j,k,l=0,0,0,0`
7. Thanks to @mbomb007, I removed about 40 more bytes from `chooseChar`

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