title: 9 Hole Challenge

text:
# Question
Title: 9 Hole Challenge
# The 9 Hole Challenge

* 9 code golfing challenges of varying difficulty.
* Penalties for using the same language more than once.
* The question will be updated with pars, hole champions and trophy winners.

*This comes from a competition I have with some friends, it's not the usual format, but I hope some of you will appreciate the different spin on it. Challenges, rules and trophies below.*

# Holes

1. # Greenway (24)

`f(c:string, n:integer)`
Prints a line containing `n` instances of `c`.
2. # Somewhere in the Rough (73)

`f(t:string, s:string, n:integer) -> i`
Where `i` is the index of the `nth` instance of `s` in `t`.
3. # Curry for Dinner (6235)

`f(x:function, y: function) -> g` Where `g` is a function that will call `y`, `n` times; where `n` is the return value of `x`
4. # Spew (92)

`f(p:string)` Writes to file at `p` and fills it with a randomly sized rectangle of random characters (ascii).
5. # Treasure Hunt (75)

`f(p:string, c:char) -> (x, y)` Reads file at `p` which contains a grid of symbols and returns the `x` and `y` coordinates of the first instance of that symbol within the grid, assume it exists.
6. # Bridge on the River Kwai (179)

`f(l:list[int])` Prints difference bridges diagram for `l`. E.g for `[1,7,3,17,1]`

```
 /+6\ /-4\ /+14\  /-16\
1    7    3     17     1

```

Make sure that the spaces are created according to the size of the number above. For a 3 digit long number, you are going to need 4 spaces between the digits on the line below.

Catch: Somewhere, your code must spell trousers (Must have at least 1 non-alphanumeric delimiters. E.g. `tr(ou,se)(rs)`
7. # Time Flies When You're Playing Golf (1157)

`f(p:string) -> [h, m]` Reads file at `p` which contains an ASCII representation of an analogue clock, where the hour hand is represented with one lines, and the minutes by two. Output a list containing two elements: the hours and minutes shown on the clock. If only one hand is visible, assume both point to that position.

Here are all the possible combinations for a hand.

```
\ | /
 \|/
--o--
 /|\
/ | \

```

These positions, respectively are (12, 1, 3, 5, 6, 7, 9, 11). Assume that the other characters within the clock face are spaces.
8. # Timber! ()

`f(p:string) -> b:boolean` Where p is the path to a file with an ascii building in. Blocks with white space underneath them will fall. (Except from slashes, which stay in place if there is a stable block in the opposite direction to the way they face). If the building is structurally integral return true, otherwise return false. All non whitespace blocks are counted as being solid and other than slashes, they all fall.

Structurally safe

```
____
|/\|
|  |

```

Not Safe

```
|__
  |
  |

```

Safe version

```
|__
\\|
  |

```
9. # Slacker News (218)

`f(s:string, r:string, p:string)` Gets the titles of the top 20 stories on Hacker News and changes all instances of `s` to `r`, then writes the new titles to a html file at `p`, where each title is contained within a h1 element.

The outputted file should something like this

`<h1>Some title</h1></h1>Some other title</h1>...etc`

**Catch**:

* You may not use the HN api.
    * You may not use Regex.
    * You may not use angle braces anywhere in your code.

---

# Scoring

* Character count is the length of the function that will compile & run correctly. However you still need to submit the full code, including imports.
* **+10%** for every repeated language in your submission. (E.g. If you use Ruby for 3 solutions, then your final score will be multiplied by 1.2). Different versions of the same language count still count as the same language.
* Par will be average score for each hole.
* Submit your solutions in one answer.
* Your overall score is your character count + your language penalty, then round it up.

---

# Trophies

* **Gold Jacket** \- (@Sprigyig \- 1290) Lowest overall score
* **Shooter** \- (@Sprigyig \- 9) Most languages used
* **Bunker** \- Most above par score on any hole
* **Snakes on a Plane** \- (@AsksAnyway \- 1727) Highest python character submission in a single solution
* **Good Parts** \- (@AsksAnyway \- 255) Highest JS character count in a single solution
* **Shakey Steve** \- Shortest solution that uses interfaces
* **You're Not From Round Here** \- Shortest unique language solution that's language has the shortest wikipedia page.
* **Happy Gilmoore** \- (@AsksAnyway \- 31) Shortest solution that has the word 'alligator' in the code.
* **Unicycling Dwarf Magic** \- The default extensions of your 9 submission source files are a perfect anagram of a word in the Oxford Dictionary.

*You are only eligible for a trophy once you have completed all 9 holes*

---

# Submissions

1. @Sprigyig 1290
2. @Firefly 1320
3. @grc 1395
4. @Trevor M 1465
5. @C Gearhart 1654
6. @Guy Sirton 1719
7. @AsksAnyway 4651

# Answer
# Score: 4651

*2907 + 60% penalty*

### 1. GolfScript - 14 characters

```
{*}:a;lligator

```

Usage: `c n a` e.g. `"test" 3 a` -\> `testtesttest`

Happy Gilmoore

### 2. Python - 72 characters

```
def f(t,s,n,p=-1):
 while n:p=t.find(s,p+1);n-=1 if p+1 else n
 return p

```

### 3. Javascript - 255 characters

```
/*
Curry for Dinner

f(x:function, y: function) -> g Where g is a function that will call y, n times; where n is the return value of x
*/
function f(x, y) {
    var g = function() {
        var n = x();
        for (var i = 0; i < n; ++i) {
            y();
        }
    };
    return g;
}

```

Bunker Good Parts

### 4. Python - 132 characters

```
from random import randrange as r
def f(p):l=range(r(9));open(p,'w').writelines([''.join([chr(r(94)+33)for _ in l])+'\n'for _ in l])

```

### 5. Python - 89 characters

```
def f(p,c):
 for y,d in enumerate(open(p).readlines()):
  x=d.find(c)
  if x+1:return x,y

```

### 6. Python - 189 characters

```
def f(l):
 for i in 0,1:
  for n,u in enumerate(l):
   o=l[n+1] if len(l)>n+1 else id
   if i:print u,' '*4,
   elif o!=id:print' /'+('+' if o-u>0 else '')+str(o-u)+'sers'*0+'\\ ',
  print

```

### 7. Python - 1727 characters

```
def f(p):
    lines = open(p).read().split('\n')

    # preprocess lines to ensure correct format
    if len(lines) < 5:
        for i, line in enumerate(list(lines)):
            if 'o' in line:
                if i == 0:
                    lines.insert(0, ' ' * 5)
                    lines.insert(0, ' ' * 5)
                elif i == 1:
                    lines.insert(0, ' ' * 5)
        while len(lines) < 5:
            lines.append(' ' * 5)

    # find characters that can only be the hour hand
    for i, line in enumerate(lines):
        if i == 0:
            if '\\' in line:
               hour = 11
            elif '|' in line:
                hour = 12
            elif '/' in line:
                hour = 1
        elif i == 2:
            if '--o' in line:
                hour = 9
            elif 'o--' in line:
                hour = 3
        elif i == 4:
            if '/' in line:
               hour = 7
            elif '|' in line:
                hour = 6
            elif '\\' in line:
                hour = 5

    # find characters that might represent the minute hand
    possible_minutes = []
    for i, line in enumerate(lines):
        if i == 1:
            if '\\' in line:
                possible_minutes.append(55)
            if '|' in line:
                possible_minutes.append(0)
            if '/' in line:
                possible_minutes.append(5)
        elif i == 2:
            if '-o' in line:
                possible_minutes.append(45)
            if 'o-' in line:
                possible_minutes.append(15)
        elif i == 3:
            if '/' in line:
                possible_minutes.append(35)
            if '|' in line:
                possible_minutes.append(30)
            if '\\' in line:
                possible_minutes.append(25)

    HOUR_MINUTES = {
        12: 0,
        1: 5,
        3: 15,
        5: 25,
        6: 30,
        7: 35,
        9: 45,
        11: 55,
    }

    # remove minute hand that is actually hour hand
    if len(possible_minutes) > 1:
        not_minute = HOUR_MINUTES[hour]
        if not_minute in possible_minutes:
            possible_minutes.remove(not_minute)

    assert(len(possible_minutes) == 1)
    minute = possible_minutes[0]

    h, m = hour, minute
    return [h, m]

```

Snakes on a Plane

### 8. Python - 226 characters

```
def f(p):
 e=set;q,t=e(),True
 for l in open(p).readlines():
  r,b,q=e(q),e(),e()
  for i,c in enumerate(l):
   if c.strip():b.add(i);q.add(i-1 if c == '/' else i+1 if c == '\\' else i)
  if not r.issubset(b):t=False
 return t

```

### 9. Python - 203 characters

```
import urllib
def f(s,r,p):f,l,g=open(p,'w'),'\74','\76';[f.write(l+'h1'+g+t.replace(s,r)+'h1'+g)for i,t in enumerate(urllib.urlopen('http://x.co/3WYln').read().split('title'+g))if(i in range(2,42))&i%2]

```
> 11 votes

# Answer
## Score: 1320

I've plenty to do to improve this score... Oh well, at least I avoided repeated-language penalties. :-)

### 1. Python (21 chars)

```
def f(c,n):print(c*n)

```

The "obvious" solution.

### 2. ECMAScript 6 (47 chars)

```
f=(t,s,n)=>t.split(s).slice(0,n).join(s).length

```

Finds the index in a bit of an unconventional way, by counting the length of the substring before it.

### 3. J (12 chars)

```
f=:2 :'v^:u'

```

The built-in conjunction `^:` raises a function to a power (i.e. repeats a function a given number of times). That is, `f^:3 y = f (f (f y)))`. However, it's overloaded to alos accept functions rather than integers, in which case it runs the function on the input to get the number of repetitions. Unfortunately we need to flip the operands for the task, otherwise we'd have the consise answer `f=:^:`.

### 4. C (95 chars)

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

f(char*p){FILE*f=fopen(p,"a");for(int n=rand(),y=n*n;y--;y%n||putc(10,f))putc(rand()%94+32,f);}

```

This task leaves quite a bit of room for interpretation and abuse: is it okay to just output a random printable ASCII character and say it's a randomly-dimensioned rectangle with dimensions from the set {1}? Probably not. Anyway, I went with plain `rand()` but in reality you probably want to add `%9` or something if you want to test it. On my linux box I didn't have to flush the file in order for it to be written (I guess it flushes automatically on program exit), but I'm pretty sure you have to flush it to be standards-compliant, so feel free to add `fflush(f);` to the count here.

### 5. Haskell (100 chars)

```
import Control.Arrow
import Data.List
import Data.Tuple
import Control.Applicative

h p c=head.filter(p c.snd).zip[1..]
g c=swap.(id***fst.h(==)c).h elem c.lines
f p c=g c<$>readFile p

```

I like the repeated pattern between finding the row and the column (abstracted via `h`).

### 6. Lua (261 chars)

```
function f(s,m,y,...)if s and m then for i,v in pairs(m)do
io.write(v,(" "):rep(#tostring(s[i])))end print()elseif s then
r=unpack f(s,{"",f(trouse,r(s))})f({f(nil,r(s))},s)elseif y then
return ("/%s%d\\"):format(m<y and"+"or"-",math.abs(m-y)),f(s,y,...)end end

```

Makes use of multiple return values and recursion to deal with computing the differences. It cost me a few characters to match the sample output exactly (adding the right amount of spaces everywhere).

### 7. Go (307 chars)

```
func f(p string)[]int{var l[]string
g,_:=os.Open(p)
H,M,s,m:=0,0,bufio.NewScanner(g),[][]int{{-1,-1,11},{-1,0,12},{-1,1,1},{0,-1,9},{0,1,3},{1,-1,7},{1,0,6},{1,1,5}}
for s.Scan(){l=append(l,s.Text())}
for _,a:=range m{if l[2+a[0]*2][2+a[1]*2]!=' '{M=a[2]}
if l[2+a[0]][2+a[1]]!=' '&&(H==0||M!=a[2]){H=a[2]}}
return[]int{H,M}}

```

Could probably be golfed a lot more; I barely know Go.

### 8. CoffeeScript (+ node.js) (223 chars)

```
f=(p)->
 a=require('fs').readFileSync(p).toString().split "\n"
 U=(i,j)->a[i]?[j]and a[i][j]==' '
 for l,i in a
  for c,j in l
   m =
    "/":[i+1,j-1]
    "\\":[i+1,j+1]
    a:[i+1,j]
   return if U.apply(0,m[c]or m.a)
 1

```

A bit of a cheap-shot since I already have JS. Oh well. Returns a falsy value (namely, `undefined`) or a truthy value (namely, `1`) to indicate the answer.

### 9. Bash (254 chars)

```
f(){
curl https://news.ycombinator.com/rss|
awk -Ftitle '{OFS="h1\76\n\74h1";ORS="";print substr(OFS,4);print$2,$4,$6,$8,$10,$12,$14,$16,$18,$20,$22,$24,$26,$28,$30,$32,$34,$36,$38,$40;print substr(OFS,0,3)}'|
while read l;do echo ${l//$1/$2};done|
tee $3
}

```

(Newlines after pipes added for readability.) Working around the restrictions with the shell was fun. I realise there's probably a better way to do `$2,$4,$6,...`, but this was what I came up with anyway.
> 7 votes

# Answer
# Score: 1,394.4

*996 characters + 40% penalty*

**1. Greenway - Haskell, 19 chars**

```
f c n=replicate n c

```

Usage:

```
> f "hello" 5
["hello","hello","hello","hello","hello"]

```

**2. Rough - PHP, 72 chars**

```
<?
function f($t,$s,$n){for($i=-1;$n--;$i=strpos($t,$s,++$i));return$i;}

```

**3. Curry - JavaScript 1.8, 45 chars**

```
f=function(x,y)function(){for(i=x();i--;)y()}

```

**4. Spew - J, 43 chars**

```
f=:3 :'((33+?(1+?2#100)$1#93){a.)fwrites y'

```

Usage:

```
f 'file.txt'

```

**5. Treasure - J, 64 chars**

```
f=:4 :0
a=.freads x
b=.1+a i.u:10
c=.a i.y
d=.<.c%b
e=.d,c-b*d
)

```

Usage:

```
'file.txt' f 'c'

```

**6. Bridge - Python, 166 chars**

```
def f(l):J=''.join;t=map;r=lambda n:' '*len(n);s=t(str,l);o=['/%+d\\'%(y-x)for x,y in zip(l,l[1:])];print J(t(J,zip(t(r,s),o)))+'\n'+J(t(J,zip(s,t(r,o)+['users'*0])))

```

**7. Time - Python, 205 chars**

```
def f(p):
 s=open(p).read();a=[s[:12],s[18:],s[11:15],s[15:18]];z=[0]*3
 for l in(0,1):
  for c in'/|\\':z[a[l].count(c)]=('|/'.find(c)+6*l)%12or 12
  z[a[2+l].count('-')]=3+6*l
 print[z[1]or z[2],z[2]*5%60]

```

Assumes lines are space padded to be five characters wide. Uses tabs for second indentation level.

**8. Timber - Python, 190 chars**

```
def f(p):g=open(p).readlines();C='\\/ ';return all(1-[x+2>len(g[y])or g[y][x+1]in C,x<1or g[y][x-1]in C,0,' '==g[y+1][x]][C.find(g[y][x])]for y in range(len(g)-1)for x in range(len(g[y])-1))

```

**9. Slacker - Python, 192 chars**

```
import urllib
def f(s,r,p):F=open(p,'w');d=urllib.urlopen('http://x.co/3WYmQ').read()[37:];o,c='\x3c\x3e';exec"d=d[d.find(o+'t')+7:];F.write(o+'h1'+c+d[:d.find(o)].replace(s,r)+o+'/h1'+c);"*20

```

Thanks to Tyzoid for the url shortener idea.
> 5 votes

# Answer
Had fun touching a few languages for a little bit...

Character counts obtained after removing unnecessary spaces/newlines but submission mostly kept readable. Since the question is a mix of functions and programs I included only the body of the function where required... Also some liberty taken with what the meaning of "return" is...

Total **~1719**

1- **Python** (~20)

```
def f(c, n):
    print c*n

```

2- **C** (~109)

```
int f(char*t,char*s,int n){int i;char*q=t;int l=strlen(s);for(i=0;i<n;++i){t=strstr(t, s)+l;}return(t-q-l);}

```

Readable version:

```
#include <string.h>

int f(const char *t, const char *s, int n)
{
  int i;
  char *start = t;
  int l = strlen(s);
  for(i = 0; i < n; ++i)
  {
    t = strstr(t, s) + l;
  }
  return(t - start - l);
}

```

3- **Javascript** (~56)

```
function(x, y) {return function() {for(i=0; i<x(); i++) y();}}

```

4- **Rexx** (~136)

```
f: Procedure
  Parse arg p
  w = random(1, 9)
  h = random(1, 9)
  Do y = 1 to h
    Do x = 1 to w
      Call CHAROUT p, d2c(random(32, 99))
    End
    Call LINEOUT p, ""
  End

```

5- **Scala** (~290)

```
def f(p: String, c: Char) {
  def sc(w: String, c: Char, x: Int, y:Int ): Boolean =
    {
      if(w.isEmpty) false else
      if(w.head==c) {println(x, y); true} else sc(w.tail, c, x+1, y)
    }
  def sr(w: Array[String], c: Char, x: Int, y: Int)
  {
    if(!sc(w.head, c, 0, y)) sr(w.tail, c, 0, y+1)
  }
  sr(io.Source.fromFile(p).mkString.split('\n'), c, 0, 0)
}

```

6- **C++** (~355)

```
void b(list<int> l) // trouser+s
{
  auto i = l.begin();
  auto j = i;
  j++;
  list<int> d;
  while(j!=s.end()) d.push_back(*j++ - *i++);
  j = d.begin();
  ostringstream o[2];
  for(auto i : l)
  {
    while(o[0].tellp()!=o[1].tellp()) o[1] << " ";
    o[1] << i;
    if(j != d.end())
    {
      while(o[0].tellp()!=o[1].tellp()) o[0] << " ";
      o[0] << "/" << (*j>=0 ? "+" : "") << *j++ << "\\";
    }
  }
  cout << o[0].str() << endl << o[1].str() << endl;
}

```

7- **Go** (~301)

Note this requires the clock to be padded (i.e. all lines are same length).

```
func f(p string)(h int,m int) {
  var a=[8]int {0, 2, 4, 12, 16, 24, 26, 28}
  var b=[8]int {7, 8, 9, 13, 15, 19, 20, 21}
  var d=[8]int {11, 12, 1, 9, 3, 7, 6, 5}
  h=9
  c, e := ioutil.ReadFile(p)
  if e==nil {
    for i:=range a {
      if c[a[i]]>32 {
        m=i
      }
    }
    for i:= range b {
      if c[b[i]]>32 {
        if i!=m {
          h=i
        }
      }
    }
    if h==9 {
      h=m
    }
    h=d[h]
    m=d[m]*5%60
  }
  return
}

```

8- **Ruby** (~259)

```
def f(p)
  a,b = File.read(p).split(/\n/).reverse,Hash.new(1)
  a.each_with_index {
    |l,i|
    l.split("").each_with_index {|k,j|
      case k
        when ' '
          b[j] = 0
        when '/'
          b[j] = b[j]|b[j-1]
        when '\\'
           b[j] = b[j]|b[j+1]
      end
      unless k==' '
        if b[j]==0
          return 0
        end
      end
    }
  }
  return 1
end

```

9- **bash/Unix hack** (~193)

```
wget -qO - http://news.ycombinator.com/rss | tr "\074\076" "\n" | grep -B1 /title | awk 'NR % 3 == 1' | head -21 | tail -20 | sed 's/$1/$2/' | awk '{ print "\074h1\076" $0 "\074/h1\076"}' > $3

```
> 4 votes

# Answer
Edit: Think I'll just submit this as is: 1290 total, no language repeats.

**Greenway, C#** 53

```
void g(string s,int n){while(n-->0)Console.Write(s);}

```

I decided to swap languages with #1 and #9. Totally worth 30 here for hundreds later.

**Somewhere In The Rough, Python** 59

I really shouldn't have used up such a good language on an easy problem. Also, how is this not part of any language's indexOf family of functions? I seem to always need this...

```
def f(t,s,n):return sum(map(len,t.split(s))[:n+1])+n*len(s)

```

**Curry For Dinner, Lisp** 61

I haven't touched lisp since that one week in college....

```
(defun f (c g)(loop for i from 1 to(funcall c)do(funcall g)))

```

**Spew, Bash/shell utils** 102

My bash-foo was never that good to begin with. I'll fiddle with this one later. BTW if you want it to finish faster, switch it over to /dev/urandom.

```
f(){
c=$(($RANDOM%9+9))
for i in $(seq $c);do
echo `tr -cd [:print:]</dev/random|head -c$c`>>$1
done
}

```

**Treasure Hunt, C** 113

Probably one of the more C friendly problems. I interpreted "return two integers" as take a return array pointer as an argument. Warnings? What warnings? An int\* is just as good as a FILE\* =p.

```
void f(int*p,int c,int*r){int*f,t;*r=r[1]=0;f=fopen(p,"r");while(c-(t=fgetc(f))){*r=t-'\n'?*r+1:0;r[1]+=*r?0:1;}

```

**Bridge on the River Kwai, Perl** 207

I started learning perl while writing this one. (Better late than never!) I came into this wanting to do regex heroics, so I form the string as both layers of the bridge together, then use regexes with space replacements to form the two different lines.

```
sub f{@trouse=0..$#_-1;foreach $i(@trouse){$r.=sprintf("%d/%+d\\",$_[$i],$_[$i+1]-$_[$i])}$r.=$_[$#_]."\n";print$r=~s/(^|\\)(\d+)(\/|$)/$1.' 'x length($2).$3/egr;print$r=~s/(\/[+-]\d+\\)/' 'x length($1)/egr}

```

**Time Flies When You're Playing Golf, Java** 297

You can only do so much to make java terse... It assumes the clock is space padded so each line is 5 spaces long.

```
public boolean p(int r,int m,String s){int c[]={1,1,0,-1,-1,-1,0,1};return s.charAt(6*c[(r+6)%8]*m+14+c[(r)%8]*m)!=' ';}
public int[]time(String c){int h=9,m=0,t[]={3,5,6,7,9,11,12,1};for(int i=0;i<8;i++)if(p(i,1,c))if(p(i,2,c))m=i;else h=i;if(h==9)h=m;m=(t[m]*5)%60;h=t[h];return new int[]{h,m};}

```

**Timber! Javascript** 201

It runs in chrome's console. I make no guarantees elsewhere =p. It requires that the lines be space padded out to the length of the longest line. I feel like this is a reasonable request of ASCII art.

```
function f(s) {s=s.split("\n")
d={};m={'/':-1,'\\':1};r=1
s.forEach(function(x){t={}
for(i=0;i<x.length;i++){if(x[i]!=' '){j=m[x[i]]?i+m[x[i]]:i
t[j]=1}}for(n in d){if(x[n]==' '){r=0}}d = t})
return r}

```

**Slacker News, Ruby** 197

```
def s(f,s,t)
l=60.chr
r=62.chr
IO.write(f,l+"h1"+r+URI.parse("https://news.ycombinator.com").read().split('mhead')[0,20].map{|x|x[0,x.length-19].split(r).last.sub(s,t)}.join(l+"/h1#{r+l}h1"+r))
end

```
> 4 votes

# Answer
Not really here to golf, but here's some Tcl, since the language needs more love:

```
set holes {
    greenway
    rough
    curry
    spew
    hunt
    bridge
    time
    timber
    slacker
}

proc greenway {c n} {
    puts [string repeat $c $n]
}

proc rough {t s n} {
    set i [string first $s $t] ;# a bit wet
    while {[incr n -1]} {
        incr i [string first $s $t $i]
    }
    return $i
}

proc curry {x y} {
    set n [uplevel 1 $x]
    set body [string repeat "$y;" $n]
    return [list apply [list args $body]]
}

proc spew {p} {
    set w [expr {int(rand()*80)}]
    set h [expr {int(rand()*80)}]
    set f [open $p w]
    for {set y 0} {$y<$h} {incr y} {
        set ln ""
        for {set x 0} {$x<$h} {incr x} {
            append ln [format %c [expr {int(rand()*96+32)}]]
        }
        puts $f $ln
    }
    close $f
}

proc hunt {p c} {
    set f [open $p r]
    set y 0
    while {[gets $f line]>=0} {
        set x [string first $f $c]
        if {$x != -1} {
            return [list $x $y]
        }
        incr y
    }
}

proc bridge {l} {
    set l [lassign $l m]
    set top ""
    set btm $m
    foreach n $l {
        set t "/[expr {$n>$m?"+":""}][expr {$n-$m}]\\"
        append top "[string repeat \  [string length $m]]$t"
        append btm "[string repeat \  [string length $t]]$n"
        set m $n
    }
    # trousers
    return $top\n$btm
}

proc time {p} {
    set f [open $p r]
    while {[gets $f line] >= 0} {
        set line [format %-.5s $line]
        lappend c [split $line {}]
    }
    close $f
    foreach {x y h} {
        -1 -1  0
         0 -1  1
         1 -1  3
         1  0  5
         1  1  6
         0  1  7
        -1  1  9
        -1  0 11
    } {
        set 2x x; incr 2x $x
        set 2y y; incr 2y $y
        if {[lindex $c $2y $2x] != " "} {
            set hh $h
        } elseif {[lindex $c $y $x] != " "} {
            set mm $h
        }
    }
    if {![info exists $mm]} {
        set mm $hh
    }
    set mm [expr {$mm*5}]
    if {$hh == 0} {set hh 12}
    list $hh $mm
}

proc timber {p} {
    set f [open $p r]
    set must {}
    while {[gets $f line] >= 0} {
        set line [format %-.5s $line]
        foreach i $must {
            if {[string index $line $must] eq " "} {
                close $f
                return false
            }
        }
        set must {}
        set i 0
        foreach c [split $line] {
            switch $c {
                "\\" {lappend must [expr {$i+1}]}
                "/"  {lappend must [expr {$i-1}]}
                " "  { }
                default  {lappend $must $i}
            }
            incr i
        }
    }
    close $f
    return true
}

proc slacker {s r p} {
    package require tdom
    set f [open $p w]
    set h [::http::geturl https://news.ycombinator.com/]
    set html [string trim [::http::data $h]]
    ::http::cleanup $h
    set dom [dom parse $html]
    lappend map , [string index $html 0]
    lappend map . [string index $html end]
    set root [$dom documentElement]
    foreach n [$root selectNodes {//td[@class=title]/a}] {
        set x [$n text]
        set x [string map [list $s $r] $x]
        puts $f [string map $map ",h1.$x,/h1."]
    }
    close $f
}

```

Mostly untested because writing these procs in half an hour is much more interesting than trying to properly engineer golf code. Enjoy!
> 2 votes

# Answer
Only had time to work on 1/2 of these. You seem to want them in the form of a function and not a one liner. So all of these are functions. Testing code below the function. In Perl.

**Greenway:**

```
sub f{print$_[0]x$_[1]}

#test
&f("abc",5);

```

**Rough:**

```
sub f{$i=-1;$n=$_[2];do{$i=index$_[0],$_[1],$i+1;$n--}while($n>0 && $i>-1);print$i+1}

#test
&f("abcefgacefgabcefgabcefgabcefg","cef",4);

```

**Curry:**

```
use Sub::Curried;
curry f($x,$y){$q=0;foreach(1..&$x){$q=&$y};return $q;}

#test
sub fy { return 1;}
sub fx { return 10;}
print&f(\&fx,\&fy);

```

**Spew:**

```
use Crypt::PRNG qw(random_string_from irand);
sub f{open($o,">$_[0]");$m=(irand)%10+1;map{printf $o "%s\n",random_string_from(['A'..'z'],$m)}(1..$m)}

#test
&f('/tmp/t');

```

**Treasure:**

```
sub f{open($i,"<$_[0]");$x=$y=0;@l=<$i>;while($y<=$#l){$x=1+index$l[$#l-$y],$_[1];@a=($x,$y+1)if($x);$y++;}return\@a}

#test
@b=@{&f('/tmp/t','f')};
print join(",",@b);

```

I'll work on 6-9 tomorrow.
> 2 votes

# Answer
# WIP. Note, character counts may be off due to `'\n'` and `wc`

### \[1 Greenway\] Mindf\*ck, 54 characters

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

```

Usage: Once the code is written, input your string, and terminate your string with a ^a (ctr+a), then immediately after, enter your number.

One caveat: the number given must only be from 0-9 (if you wish a larger one, the ascii value-48 of whatever character you input will be used as `n`)

Screenshot:

### \[3 Curry for Dinner\] Javascript, 59 characters

```
function f(x,y){return function(){n=x();while(--n!=0)y();}}

```

### \[4 Spew\] BASH, 56 characters

```
f(){ dd if=/dev/urandom of="$1" count=$((RANDOM%30+2));}

```

### \[7 Time Flies When You're Playing Golf\] C, 334 Characters (412 with macro definition)

```
#define E(A) else if(s[A]==
#define G(A) else if(A)m=
#define M(A) &&m!=A)h=A
int (*f(char* s)){short h=0,m=0;if(s[0]=='\\')m=11;G(s[2]=='|')12;G(s[4]='/')1;G(s[11]=='-')9;G(s[15]=='-')3;G(s[22]=='/')7;G(s[24]=='|')6;G(s[26]=='\\')5;if(s[7]=='\\'M(11);E(8)'|'M(12);E(9)'/'M(1);E(12)'-'    M(9);E(14)'-'M(3);E(18)'/'M(7);E(19)'|'M(6);E(20)'\\'M(5);int* i=malloc(sizeof(int)*2);i[0]=(h==0)?m:h;i[1]=m*5;return i;}

```

Note: this function returns a pointer to a two dimensional integer array, formatted like so: {3, 55} (for a clock position of hour on 3, minute on 11)

### \[9 Slacker News\] PHP, 246 characters

```
function f($a,$b,$c){$t=file_get_contents("http://x.co/3WQoY");$g=explode('d class="t',$t);$f=fopen($c,"w");for($i=1;++$i!=count($g)-10;){$e=explode("\x3e",$g[$i]);fwrite($f,"\x3ch1\x3e".str_replace($a,$b,s    ubstr($e[2],0,-3))."\x3c/h1\x3e\n");}}

```

**Seperate/Original implementation in BASH+AWK, 218 characters**

```
f(){ wget -qO- x.co/3WQoY|grep "e_"|awk '{n=split($0,a,"d class=\"t");for(q=1;++q!=n-10;){split(a[q],b,"\x3e");m=substr(b[3],0,index(b[3],"\x3c/")-1);gsub("'"$1\",\"$2"'",m);print "\x3ch1\x3e"m"\x3c/h1\x3e"    }}'>"$3";};

```
> 2 votes

# Answer
# 1654

## 1. Greenway (Haskell - 37)

```
f x y=do print(concat(replicate x y))

```

## 2. Somewhere in the Rough (Mathematica - 43)

```
f[t_,s_,n_]:=StringPosition[t, s][[n+1, 1]]

```

## 3. Curry for Dinner (Lisp - 58)

```
(defun f(x y)(lambda()(dotimes(c(funcall x))(funcall y))))

```

## 4. Spew (Matlab/Octave - 83)

```
function x(f)
    save f arrayfun(@char,randi(255,randi(255),randi(255)))
endfunction

```

## 5. Treasure Hunt (C - 176)

```
char* f(char* s,char c){FILE* n;char* r;int i=0,j=0,k=0;n=fopen(s,"r");while(!feof(n)){k=fgetc(n);if(k==(int)c)break;j++;if(k=='\n'){i++;j=0;}}sprintf(r,"%d %d",i,j);return r;}

```

## 6. Bridge on the River Kwai (Ruby - 192)

```
def f(l)
    trouse="\n%s"
    rs = l[0].to_s
    for i in 1..l.length-1
        s = "/%+d\\"%(l[i]-l[i-1])
        print " "*l[i-1].to_s().length+s
        rs += " "*s.length+"%d"%l[i]
    end
    puts trouse%rs
end

```

## 7. Time Flies When You're Playing Golf (Node.js - 406)

```
function f(n){var g,h,m,q;fs.readFile(n,'ascii',function(e,d){l=d.split('\n');g=function(x,y){try{return l[x][y].trim()&&1;}catch(e){return 0;}};h=g(0,0)*11||g(0,2)*12||g(0,4)*1||g(2,0)*9||g(2,4)*3||g(4,0)*7||g(4,2)*6||g(4,4)*5;m=(g(1,1)&&h!=11)*55||(g(1,2)&&h!=12)*0||(g(1,3)&&h!=1)*5||(g(2,1)&&h!=9)*45||(g(2,3)&&h!=3)*15||(g(3,1)&&h!=7)*35||(g(3,2)&&h!=6)*30||(g(3,3)&&h!=5)*25||h*5%60;return [h,m];});}

```

## 8. Timber! (Go - 329)

```
func f(p string)bool{
    x,_:=ioutil.ReadFile(p)
    b:=strings.Split(string(x),"\n")
    for j:=0;j<len(b)-2;j++{
        for i:=0;i<len(b[j]);i++{
            r,o:=1,0
            switch string(b[j][i]){
            case " ": continue
            case "/": r,o=0,-1
            case "\\": r,o=0,1
            }
            if i+o<len(b[j]) && b[j+r][i+o]==' ' {
                return false
            }
        }
    }
    return true
}

```

## 9. Slacker News (Python - 330)

```
def f(s,r,p):
    w=urllib2.urlopen('http://news.ycombinator.com')
    a=[l.get_text() for l in BS(w).body("a") if l.find_parent("td", class_="title")]
    t=lambda x:u"\x3c{}\x3e{}\x3c/{}\x3e".format(x,'{}',x)
    m=''.join(t("h1").format(l.replace(s,r)) for l in a[:20])
    with open(p,'w') as h:
        h.write(t("html").format(m).encode('utf8'))

```
> 2 votes

# Answer
I’m a cheater & I ain’t played all 9 holes … *yet*. Nonetheless, here’s my hole 8, “Timber” solution in Perl (149 char).

One of my coworkers put this up as as a challenge at work. We’ve been having fun with it, especially me, since I have the lowest par solution so far!

Our rules were that it had to be a stand alone script that outputted `true` or `false` followed by a newline to `STDOUT`, and that no “shebang” was OK.

Below is the “minified” solution. I also put up a “gist” of the same that includes non-“minified” code & (often tortuously long) explanations of the reasoning behind my approach.

---

```
$r=tru;open F,pop;while(<F>){y/0/6/;s/^|\s|$/0/g;s#\\(?=0)|(?<=0)/|[^\\/0]#6#g;@n=split//;for(0..@n){!$n[$_]&&$l[$_]==6?$r=fals:1}@l=@n;}print$r,'e
'

```
> 1 votes

# Answer
I am too lazy to modify it according to the competition rules Meh, but it works fine...

```
from numpy import *
import sys

def greenway(c,n):
    print c*n

def somewhereintherough(t,s,n):
    i=-1
    count=0
    while(count<n):
        i = t.find(s,i+1)
        count+=1
    return i

def curryfordinner(x,y):
    def g():
        for i in range(x()):
            y()
    return g

def spew(p):
    f = open(p,'w')
    n = random.randint(1,28)
    for i in range(n):
        if(i>0):
            f.write('\n')
        str1 = ''.join([chr(random.randint(32,126)) for _ in range(n)])
        f.writelines(str1)
    f.close()
    print "Grid size: ",n,'x',n

def treasurehunt(p,c):
    f = open(p,'r')
    arr = f.readlines()
    n = len(arr)
    f.close()
    f = open(p,'r')
    found=False
    for i in range(n):
        line = f.readline()
        #print line
        loc = line.find(c)
        if(loc!=-1):
            print c,"found in",p,"at",i,loc
            found=True
            break
    if(not found):
        print c,"not in",p
    f.close()

def bridgeontheriverkwai(l):
    str_list = []
    for i in range(len(l)-1):
        sign = '+' if l[i+1]-l[i]>0 else '-'
        str_1 = '/'+sign+str(abs(l[i+1]-l[i]))+'\\'
        sys.stdout.write(' '*(len(str(l[i])))+str_1)
        str_list.append(str_1)
    print
    for i in range(len(l)):
        if i<len(l)-1:
            print str(l[i])+' '*(len(str_list[i])-1),
        else:
            print l[i]

def timeflieswhenyoureplayinggolf(p):
    f = open(p,'r')
    #clock = [[0]*5,[0]*5,[0]*5,[0]*5,[0]*5]
    line1 = f.readline()
    line2 = f.readline()
    line3 = f.readline()
    line4 = f.readline()
    line5 = f.readline()
    h = 0
    m = 0
    if line1.find('\\')!=-1:
        h = 11
        m = 55
    elif line1.find('|')!=-1:
        h = 12
        m = 0
    elif line1.find('/')!=-1:
        h = 1
        m = 5
    elif line5.find('/')!=-1:
        h = 7
        m = 35
    elif line5.find('|')!=-1:
        h = 6
        m = 30
    elif line5.find('\\')!=-1:
        h = 5
        m = 25
    elif line3[4]=='-':
        h = 3
        m = 15
    elif line3[0]=='-':
        h = 9
        m = 45

    if line2[1]=='\\' and h!=11:
        m = 55
    elif line2[3]=='/' and h!=1:
        m = 5
    elif line3[1]=='-' and h!=9:
        m = 45
    elif line3[3]=='-' and h!=3:
        m = 15
    elif line4[1]=='/' and h!=7:
        m = 35
    elif line4[3]=='\\' and h!=5:
        m = 25
    elif line2[2]=='|' and h!=12:
        m = 0
    elif line4[2]=='|' and h!=6:
        m = 30

    print h,m

def timber(p):
    f = open(p,'r')
    linecount=0
    line_size = 0
    line = f.readline()
    while(line):
        linecount+=1
        line_size = max(line_size,len(line)-1)
        line = f.readline()
    block = array([[0]*line_size]*linecount)
    f.seek(0)
    for i in range(linecount):
        line = f.readline()
        for j in range(len(line)-1):
            if(line[j]==' '):
                block[i][j]=0
            elif(line[j]=='/'):
                block[i][j]=1
            elif(line[j]=='\\'):
                block[i][j]=2
            else:
                block[i][j]=3
    f.close()
    for i in range(linecount):
        for j in range(line_size):
            if(block[i][j]==1 and j!=0 and block[i][j-1]==3):
                block[i][j]=4
        for j in range(line_size-1,0,-1):
            if(block[i][j]==2 and j!=line_size-1 and block[i][j+1]==3):
                block[i][j]=4
    for i in range(linecount):
        for j in range(line_size):
            if(block[i][j]==3 and i<linecount-1 and block[i+1][j]==0):
                print "Unsafe Structure"
                return
    print "Safe Structure"

def slackernews(s,r,p):
    import urllib2
    response = urllib2.urlopen('https://news.ycombinator.com')
    html = response.read()
    titles_list = []
    ix = -1
    count = 0
    index_list =  []
    while(count<21):
        ix = html.find("<td class=\"title\"",ix+1)
        index_list.append(ix)
        count+=1
    for i in range(len(index_list)-1):
        line = html[index_list[i]:index_list[i+1]]
        line = line[line.find("a href"):]
        start = line.find('>')
        end = line.find('<')
        titles_list.append(line[start+1:end])
    f = open(p,'w')
    for title in titles_list:
        title = title.replace(s,r)
        f.write('<h1>'+title+'</h1>')
    print "Done writing, Check : ",p
    f.close()

greenway('test!',2)
s='this is a cat. this is a dog. dog is an animal, animal is a beast in disguise.'
t='is'
ix=somewhereintherough(s,t,8)
print ix,s[ix:]
def x():
    return 4
def y():
    print ' !y_called! '
g = curryfordinner(x,y)
g()
spew('test.dat')
treasurehunt('test.dat','a')
bridgeontheriverkwai([-7,-22,6,9])
timeflieswhenyoureplayinggolf('clock.dat')
timber('block.dat')
slackernews('a','b','slacker.html')

```
> 0 votes

# Answer
Another work in progress here, and I'm at work so I'll head back later.

**Greenway** in Ruby (14 characters, 24 with *#alligator*), call with `f.(c, n)`

```
f=->c,n{p c*n}#alligator

```

***Screenshot***

**Somewhere in the Rough** in CoffeeScript (38 characters)

```
f=(t,s,n)->t.split(s,n).join(s).length

```

***Screenshot***

**Curry for Dinner** in JavaScript (54 characters)

```
f=function(x,y){return function(){for(i=x();i--;)y()}}

```

***Screenshot***

**Spew** in PHP (111 characters)

This requires `short_open_tag` in the PHP configuration file to be enabled. Otherwise the opening delimiter should be `<?php`, the `@` symbols are used to silence `PHP_NOTICE` errors that are thrown for avoiding enclosing `rand` in quotes, and for not explicitly declaring the `$s` variable. This will generate a square grid of ascii characters between 4 and 30 characters on both axis.

```
<? @$r=rand;$x=$r(4,30);for($i=$x*$x;--$i;){@$s.=$i%$x!=0?chr($r(33,126)):"\n";}file_put_contents($argv[1],$s);

```

***Screenshot***
> 0 votes

# Answer
First code golf! (Still a work in progress...)

# 1. Greenway

Language: Python 3.2.3
File size: 23 bytes
Code:

```
def f(c,n): print(c*n)

```

# 3. Curry for Dinner

Language: Python 3.2.3
File size: 64 bytes
Code:

```
def f(x,y):
    def g():
        for i in [1]*x(): y()
    return g

```
> 0 votes

# Answer
# 1. Greenway (Python 2: 20)

```
def a(x,n):print x*n

```

Example input: `a("asdf",3)` -\> string(`asdfasdfasdf`)

# 2. Somewhere in the Rough (Python 2: 47)

```
def b(t,s,n):return len(s.join(t.split(s)[:n]))

```

Example input: `b("1,2,333,4,5,6",",",3)` -\> int(7)

# 3. Curry for Dinner (Javascript: 61)

```
function c(a,b){d=a();return function(){while(d){d--;b()}};};

```

Example input: `function z(){ return 3; }; function y(){ console.log( '1' ) }; myfunc = c(z,y); myfunc();` -\> logs `string(1)` to the console... 3 times.

As per the specs, `c` returns a function, and doesn't actually execute that function itself.

# 4. Spew (C++11: 171)

```
#include<fstream>
using namespace std;void d(string f){ofstream o;int i=rand()%10;int j=rand()%10;o.open(f);for(int x=0;x<i;x++){for(int y=0;y<j;y++){o.put(rand()%256);}}}

```

Not actually tested this, but should work.
> 0 votes

# Answer
Some indentation is left intact for readability but it was taken out when counting characters. The total is around ~~1227~~. Or not, I forgot a problem. ~~1486~~ 1465 characters.

**1. MIPS ASM (55 chars)**

```
#a0 : the address of the null terminated string.
#a1 : the repetition count.
f:
li $v0,4
syscall
addi $a1,$a1,-1
bne $a1,$0,f
jr $ra

```

**2. Scheme (52 chars)**

```
(define (f t s n)(list-ref(string-search-all s t)n))

```

**3. F# (39 chars)**

```
let f x y=fun()->for i in 1..x() do y()

```

**4. Powershell (133 chars)**

```
Function f($p){
$r=(Get-Random)%100
$z="";for($b=$r*$r;$b -gt 0;$b--){$z+=[char](33+(Get-Random)%94);if($b%$r -eq 1){"$z">>$p;$z=""}}
}

```

**5. C++ (~~184~~ 152 chars)**

```
#include <istream>
#include <string>
int*f(std::string p,char c){int*x=new int[2]();std::ifstream i(p);for(;i>>p;x[1]++)if((x[0]=p.find(c))>0)return x;}

```

**6. C# (~~291~~ 282 chars)**

```
static void f(List<int> l)
{
    var z = "";
    var o = l[0].ToString();
    for (int j = 1; j < l.Count;j++)
    {
        int p = l[j-1];
        int i = l[j];
        var q = "/"+(i-p<0?"":"+")+(i-p).ToString()+"\\";
        o += new String(' ',q.Length)+i.ToString();
        z+=new String(' ',p.ToString().Length)+q;
    }
    Console.Out.Write(z+"\n"+o);
}

```

**7. Haskell (~~318~~ 306 chars)**

I was looking for an excuse to try out Haskell. I thought I was clever by generating the list of positions via combinations of numbers, but with the number of characters it took I could have hard coded the damn thing. Oh well. The code is atrocious but it was fun to write anyway.

edit: Fixed so it correctly returns minutes.

```
w i s=[s!!(j!!1)!!(j!!0)/=' '|j<-mapM(const i)[1,2],j/=[2,2]]
k[e,r](i,o,n)|i&&o=[e, n]|i&&not o=[n, r]|not$o||i=[e, r]
g s=let[h,m]=foldl k[0,0](zipWith3(\x y z->(x,y,z))(w[1,2,3]s)(w[0,2,4]s)[11,9,7,12,6,1,3,5])in let u=mod(m*5)60 in if h==0 then[m,u]else[h,u]
f p = do
  s<-readFile p
  return$g$lines s

```

**8. Lua (259 chars)**

I was surprised to find that strings didn't support array style indexing, so I had to rely on sub.

```
function f (p)
    s=' ' g=''
    for l in io.open(p):lines() do l=l..s:rep(#g-#l) for v=1,#g do
        d=({['/']=v-1,['\\']=v+1,[s]=0})[g:sub(v,v)] or -1
        if l:sub(v,v)==s and (d<0 or d>0 and g:sub(d,d)==s and l:sub(d,d)==s) then
            return false
        end
    end g=l end
    return true
end

```

**9. Python (187 chars)**

Thanks to grc/Tyroid for the url shortener.

```
import urllib2
def f(s,r,p):[open(p,'a').write('\074h1\076'+i.split("\074")[0].replace(s,r)+'\074/h1\076') for i in urllib2.urlopen("http://x.co/3WYmQ").read().split("\074title\076")[2:]]

```
> 0 votes

---
Tags: code-challenge, math, ascii-art, multiple-holes
---


title: Make me a window manager!

text:
# Question
Title: Make me a window manager!
I hate code bloat!

So I have decided to replace my Windows 7 system by a golfed version. However, I know that it is not easy, so let's build a prototype first. It will take a list of windows from the user and show them using a pseudo-graphic display on the standard output.

For example: user input:

```
0,0,15,10
15,10,20,15
10,13,15,15
9,1,16,3
17,5,20,7
11,2,17,4
15,4,19,6
13,3,18,5

```

The Code Golf® Window Manager™ outputs:

```
┌──────────────┐
│::::::::┌─────┴┐
│::::::::│:┌────┴┐
│::::::::└─┤:┌───┴┐
│::::::::::└─┤::::├┐
│::::::::::::└─┬──┘├┐
│::::::::::::::├─┬─┘│
│::::::::::::::│ └──┘
│::::::::::::::│
│::::::::::::::│
└──────────────┼────┐
               │::::│
               │::::│
          ┌────┤::::│
          │::::│::::│
          └────┴────┘

```

Input:

* Taken from standard input (or, if your system has no `stdin`, any method that can provide several lines of input)
* Each line contains 4 numbers, delimited by commas - coordinates of a window
* First two numbers: upper-left corner; last two numbers: lower-right corner
* Using `x,y` notation

Output:

* Write it to standard output (or, if your system has no `stdout`, anything that displays monospaced text)
* Use single box-drawing characters from Code Page 437 for drawing window boundaries
* Windows specified later in input obscure those specified earlier
* Fill the windows with the colon character: `:`
* Leading and trailing spaces are OK, as long as they don't break alignment of the windows

Notes:

* Maximum resolution I want to support: 76 (horizontal) by 57 (vertical)
* No need to support bad input
* Maximum number of windows: 255 (if you need a limit)
* My Windows 7 `cmd` shell displays codepage 437 characters by default; if anyone has a way to do that on linux (using `xterm` or whatever), please describe it here

For reference, the character codes are:

```
┌da   ─c4   ┬c2   ┐bf

│b3   :3a   │b3   │b3

├c3   ─c4   ┼c5   ┤b4

└c0   ─c4   ┴c1   ┘d9

```

Total: 12 different characters.

# Answer
# Python, 397 characters

```
#coding:437
import os
J=range
M=[[0]*76 for _ in J(57)]
for A,C,B,D in[map(int,q.split(','))for q in os.read(0,9999).split('\n')]:
 for x in J(A+1,B):
    for y in J(C+1,D):M[C][A]|=5;M[C][B]|=6;M[D][A]|=9;M[D][B]|=10;M[C][x]|=3;M[D][x]|=3;M[y][A]|=12;M[y][B]|=12;M[y][x]=16;M[y][x-1]&=~1;M[y][x+1]&=~2;M[y-1][x]&=~4;M[y+1][x]&=~8
C=" rl─d┌┐┬u└┘┴│├┤┼:"
for l in M:print''.join((C+C[1:])[m]for m in l)

```

Change `C="...` to `C=u"...` and it'll print in unicode instead! It might be tricky to get the file to save properly because the code page 437 characters are not escaped (the first 'coding' comment line is required).

The approach is to incrementally build a map using bit-wise operators. Less golfed version with comments:

```
#coding:437
import os
J=range
# set up the field
# Each element is a bitfield. Flags are:
# 16 - inside a window?
# 8  - up
# 4  - down
# 2  - left
# 1  - right
M=[[0]*76 for _ in J(57)]
# for each window...
for A,C,B,D in[map(int,q.split(','))for q in os.read(0,9999).split('\n')]:
    # add the directions for the corners
    M[C][A]|=5;M[C][B]|=6;M[D][A]|=9;M[D][B]|=10
    # add the top and bottom edges
    for y in J(C+1,D):M[y][A]|=12;M[y][B]|=12
    # add the left and right edges
    for x in J(A+1,B):M[C][x]|=3;M[D][x]|=3
    # deal with the middle
    for x in J(A+1,B):
       for y in J(C+1,D):
           # Clear the current spot by setting to inside a window
           M[y][x]=16
           # Remove the right direction from the left spot, top from the bottom, etc
           M[y][x-1]&=~1;M[y][x+1]&=~2;M[y-1][x]&=~4;M[y+1][x]&=~8
 # print it out
 C=u" rl─d┌┐┬u└┘┴│├┤┼:"
 for l in M:print''.join((C+C[1:])[m]for m in l)

```
> 3 votes

# Answer
## JavaScript ES6 (FF ≥ 31.0), 404 chars

```
w=s=>{a=[];for(i=0;i<57;)a[i++]=Array(76).fill(0);s.split('\n').map(e=>{r=e.split(',');a[x=r[1]][w=r[0]]|=5;a[x][y=r[2]]|=6;a[z=r[3]][w]|=9;a[z][y]|=10;for(i=x;++i<z;)a[i][w]|=12,a[i][w]&=14,a[i][y]|=12,a[i][y]&=13;for(i=w;++i<y;)a[x][i]|=3,a[x][i]&=11,a[z][i]|=3,a[z][i]&=7;for(i=x;++i<z;)for(j=w;++j<y;)a[i][j]=16});console.log(a.map(e=>e.map(t=>t==16?':':' xx─x┌┐┬x└┘┴│├┤┼'[t&15]).join('')).join('\n'))}

```

Without ES6 :

```
function w(s){a=[];for(i=0;i<57;i++){a[i]=[];for(j=0;j<76;j++)a[i][j]=0}s.split('\n').forEach(function(e){r=e.split(',');a[r[1]][r[0]]|=5;a[r[1]][r[2]]|=6;a[r[3]][r[0]]|=9;a[r[3]][r[2]]|=10;for(i=r[1];++i<r[3];)a[i][r[0]]|=12,a[i][r[0]]&=14,a[i][r[2]]|=12,a[i][r[2]]&=13;for(i=r[0];++i<r[2];)a[r[1]][i]|=3,a[r[1]][i]&=11,a[r[3]][i]|=3,a[r[3]][i]&=7;for(i=r[1];++i<r[3];)for(j=r[0];++j<r[2];)a[i][j]=16});console.log(a.map(function(e){return e.map(function(t){return t==16?':':' xx─x┌┐┬x└┘┴│├┤┼'[t&15]}).join('')}).join('\n'))}

```

`w('0,0,15,10\n15,10,20,15\n10,13,15,15\n9,1,16,3\n17,5,20,7\n11,2,17,4\n15,4,19,6\n13,3,18,5');` outputs correctly the OP's example.

The edges of windows are built using bitwise operators (Up=8, Bottom=4, Left=2, Right=1).
> 6 votes

# Answer
## Python, 672 chars

The less readable version:

```
import sys
r=range
M=[0,0,0,191,0,196,218,194,0,217,179,180,192,193,195,197]
Z=[map(int,l.split(",")) for l in sys.stdin.readlines()]
S=[[[0]*5 for x in r(77) ] for y in r(58)]
for i in r(len(Z)):
 A,C,B,D=Z[i]
 for a,b,c in [(C,A,2),(C,A,3),(D,A,1),(D,A,2),(C,B,3),(C,B,4),(D,B,1),(D,B,4)]:S[a][b][c]=1
 for x in r(A+1,B):
  for a,b in [(C,2),(C,3),(C,4),(D,1),(D,2),(D,4)]:S[a][x][b]=(b+1)&1
 for y in r(C+1,D):
  for a,b in [(A,1),(A,2),(A,3),(B,1),(B,3),(B,4)]:S[y][a][b]=b&1
 for x in r(A+1,B):
  for y in r(C+1,D):S[y][x]=[i+1]+[0]*4
O=sys.stdout.write
for l in S:
 for k in l:
  c=' ';x=M[k[1]*8|k[2]*4|k[3]*2|k[4]]
  if k[0]:c=':'
  if x:c=chr(x)
  O(c)
 O('\n')

```

Started from the version below:

```
import sys

coords = [ tuple(map(int,l.strip().split(","))) for l in sys.stdin.readlines() ]

screen = [ [ [-1, [False,False,False,False]] for x in range(0, 77) ] for y in range(0, 58) ]

def mergeBorders(screen, w):
    x0,y0,x1,y1 = w
    screen[y0][x0][1][1] = True
    screen[y0][x0][1][2] = True
    screen[y1][x0][1][0] = True
    screen[y1][x0][1][1] = True
    screen[y0][x1][1][2] = True
    screen[y0][x1][1][3] = True
    screen[y1][x1][1][0] = True
    screen[y1][x1][1][3] = True

    for x in range(x0+1,x1):
        screen[y0][x][1][1] = True
        screen[y0][x][1][2] = False
        screen[y0][x][1][3] = True
        screen[y1][x][1][0] = False
        screen[y1][x][1][1] = True
        screen[y1][x][1][3] = True

    for y in range(y0+1,y1):
        screen[y][x0][1][0] = True
        screen[y][x0][1][1] = False
        screen[y][x0][1][2] = True
        screen[y][x1][1][0] = True
        screen[y][x1][1][2] = True
        screen[y][x1][1][3] = False

def paintInside(screen, w, wId):
    x0,y0,x1,y1 = w
    for x in range(x0+1,x1):
        for y in range(y0+1,y1):
            screen[y][x][0] = wId
            screen[y][x][1] = [False, False, False, False]

for wId in range(len(coords)):
    w = coords[wId]
    mergeBorders(screen, w)
    paintInside(screen, w, wId)

borderMap = { (False, True, True, False): 0xda,
              (False, True, False, True): 0xc4,
              (False, True, True, True):  0xc2,
              (False, False, True, True): 0xbf,
              (True, False, True, False): 0xb3,
              (True, True, True, False):  0xc3,
              (True, True, True, True):   0xc5,
              (True, False, True, True):  0xb4,
              (True, True, False, False): 0xc0,
              (True, True, False, True):  0xc1,
              (True, False, False, True): 0xd9 }

def borderChar(c):
    return chr(borderMap[(c[0],c[1],c[2],c[3])])

for screenLine in screen:
    for contents in screenLine:
        c = ' '
        if True in contents[1]:
            c = borderChar(contents[1])
        elif contents[0] >= 0:
            c = ':'
        sys.stdout.write(c)
    sys.stdout.write('\n')

```
> 0 votes

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


# Question
Title: Solving Systems of Equations using Cramer's Rule
Create an algorithm that uses Cramer's Rule (with determinants of matrices) to solve for the solutions of a system of linear equations. The code should work for an "n" number of variables.

**You may use whatever data structure you want to hold the matrix and return the result**

**Note:** Also, consider that a possible system can have no solutions and may have infinitely many solutions **:)**, so, your solution should take account of this...

If this is the case, just print out or return "none" or "infinitely many".

Since this is code golf, smallest code wins...

**EDIT**: To make this more challenging, you cannot use a language's built-in matrix operations libraries.

Also, your algorithm DOES NOT have to deal how to get the input, just how to process the input and return the correct output. As said before, you can store this input in whatever structure.

# Answer
## Mathematica 40

Setting up the problem in your reference link:

```
s = {{2, 1, 1}, {1, -1, -1}, {1, 1, 1}};
r = {3, 0, 0};

```

The algorithm (spaces not needed):

```
i = 1; (a = s; a[[All, i++]] = r; Det@a/Det@s) & /@ r

```

result:

```
{1, -2, 3}

```

If the system has infinite solutions it returns `Indeterminate` or `ComplexInfinite`

Please note that Mathematica can solve linear systems natively. Among other possible ways you could use:

```
s~LinearSolve~r

```

or

```
Solve[s.{x,y,z}==r]

```
> 3 votes

# Answer
## Python3 - 310

```
def det(m,n):
 if n==1: return m[0][0]
 z=0
 for r in range(n):
  k=m[:]
  del k[r]
  z+=m[r][0]*(-1)**r*det([p[1:]for p in k],n-1)
 return z
w=len(t)
d=det(h,w)
if d==0:r=[]
else:r=[det([r[0:i]+[s]+r[i+1:]for r,s in zip(h,t)],w)/d for i in range(w)]
print(r)

```

The determinant is calculated using Laplace's formula, nothing fancy :)

Supply the matrix and the known terms respectively in an array named h and t, like this

```
h = [[2, 1, 1],[1, -1, -1],[1, 2, 1]]
l = [3, 0, 0]

```

Which gives

```
[1.0, -2.0, 3.0]

```
> 1 votes

# Answer
# Matlab ~~(157)~~ ~~(155)~~(151)

I am not sure which parts of the program count for the score? (Currently only counting the algorithm, just as @belisarius did.)

```
%input
a = [1,2,3;4,5,6;7,4,2]
b = [1;3;4]

%algo
%%functiondefinition
function e = d(a)
z=length(a)
if z==1
    e=a
else
    e=0
    w=2:z
    for i=1:z
        e=e-(-1)^i*a(1,i)*d([a(w,1:i-1),a(w,i+1:end)])
    end
end
%%main
for i=1:numel(b)
    c=a
    c(:,i)=b
    x(i)=d(c)/d(a)
end

%output
if any(isinf(d))
    'no solutions'
elseif ~d(a)
    'infinite solutions'
end
x

```

Matlab can of course solve linear systems natively:

```
a\b

```
> 0 votes

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


title: Where does the laser go?

text:
# Question
Title: Where does the laser go?
Take a 2-dimensional grid and draw a number of line segments on it to represent mirrors. Now pick a point to place a theoretical laser and an angle to define the direction it's pointing. The question is: if your follow the laser beam path for some specified distance, what coordinate point are you at?

Example:

In this image, `L` is the location of the laser, `t` is it's angle (measured from the positive X axis), `M1`, `M2`, and `M3` are all line segment mirrors, and `E` is the point on the laser beam path after `D = d1 + d2 + d3 + d4` units, starting from `L`.

# Goal

Write the shortest program (in bytes) that outputs `E` given `L`, `t`, `D`, and a list of mirrors.
(Use http://mothereff.in/byte-counter to count bytes.)

# Input Format

Input will come from stdin in the format:

```
Lx Ly t D M1x1 M1y1 M1x2 M1y2 M2x1 M2y1 M2x2 M2y2 ...

```
* All the values will be floating points matching this regex: `[-+]?[0-9]*\.?[0-9]+`.
* There is always exactly one space between each number.
* Requiring quotes around the input is allowed.
* `t` is in degrees, but not necessarily in the `[0, 360)` range. (If you prefer you may use radians instead, just say so in your answer.)
* `D` may be negative, effectively rotating the laser 180 degrees. `D` may also be 0.
* There may be arbitrarily many mirrors (including none at all).
* The order of the mirrors should not matter.
* You may assume the input will come in multiples of 4 numbers. e.g. `Lx Ly t` or `Lx Ly t D M1x1` are invalid and will not be tested. No input at all is also invalid.

The layout above might be input as:

```
1 1 430 17 4.8 6.3 6.2 5.3 1.5 4.8 3.5 6 6.3 1.8 7.1 3

```

(Note that the image was drawn freehand and these values are only approximations. Martin Büttner's input values of

```
1 1 430 17 4.8 5.3 6.2 4.3 1.5 4.8 3.5 6 6.3 1.8 7.1 3

```

will give more collisions though they do not match the sketch.)

# Output Format

Output should go to stdout in the format:

```
Ex Ey

```

These are also floats and may be in exponential form.

# Notes

* Mirrors may intersect each other.
* Both sides of mirrors are reflective.
* The beam may hit the same mirror many times.
* The beam goes on forever.

# Undefined Cases

You may assume that the cases where

* the laser starts on a mirror line segment
* the laser beam hits the endpoint of a mirror
* the laser beam hits the intersection between two mirrors

are undefined and will not be tested. Your program may do anything if these occur, including throw an error.

# Bonus

Just for fun, I will award 200 bounty points to the highest voted submission that outputs a graphical representation of the problem (you could even write an interactive script). These bonus submission do not need to be golfed and can be lenient with how input and output are handled. They are distinct from the actual golfed submissions but **both should be submitted in the same answer**.

*Note:* Only submitting a bonus answer is fine, you just wont be the accepted answer. To be accepted you must exactly follow the input/output spec (e.g. output only involves `Ex Ey`, not images), and be the shortest.

# Answer
## Ruby, 327 bytes

(scroll to the bottom)

## Mathematica, bonus answer

I'm only going for the graphical submission right now. I might port this to Ruby later and golf it if I feel like it.

```
(* This function tests for an intersection between the laser beam
   and a mirror. r contains the end-points of the laser, s contains
   the end-points of the mirror. *)
intersect[r_, s_] := Module[
   {lr, dr, nr, ds, ns, \[Lambda]},
   (* Get a unit vector in the direction of the beam *)
   dr = r[[2]] - r[[1]];
   lr = Norm@dr;
   dr /= lr;
   (* Get a normal to that vector *)
   nr = {dr[[2]], -dr[[1]]};

   (* The sign of dot product in here depends on whether that end-point
      of the mirror is to the left or to the right of the array. Return
      infinity if both ends of s are on the same side of the beam. *)
   If[Apply[Times, (s - {r[[1]], r[[1]]}).nr] > 0,
    Return[\[Infinity]]];

   (* Get a unit vector along the mirror. *)
   ds = s[[2]] - s[[1]];
   ds /= Norm@ds;
   (* And a normal to that. *)
   ns = {ds[[2]], -ds[[1]]};
   (* We can write the beam as p + λ*dr and mirror as q + μ*ds,
      where λ and μ are real parameters. If we set those equal and
      solve for λ we get the following equation. Since dr is a unit
      vector, λ is also the distance to the intersection. *)
   \[Lambda] = ns.(r[[1]] - s[[1]])/nr.ds;
   (* Make sure that the intersection is before the end of the beam.
      This check could actually be slightly simpler (see Ruby version). *)
   If[\[Lambda] != 0 && lr/\[Lambda] < 1, Infinity, \[Lambda]]
   ];

(* This function actually does the simulation and generates the plot. *)
plotLaser[L_, t_, distance_, M_] := Module[
   {coords, plotRange, points, e, lastSegment, dLeft, \[Lambda], m, p,
     d, md, mn, segments, frames, durations},

   (* This will contain all the intersections along the way, as well
      as the starting point. *)
   points = {L};
   (* The tentative end point. *)
   e = L + distance {Cos@t, Sin@t};
   (* This will always be the currently last segment for which we need
      to check for intersections. *)
   lastSegment = {L, e};
   (* Keep track of the remaining beam length. *)
   dLeft = distance;

   While[True,
    (* Use the above function to find intersections with all mirrors
       and pick the first one (we add a small tolerance to avoid
       intersections with the most recent mirror). *)
    {\[Lambda], m} =
     DeleteCases[
       SortBy[{intersect[lastSegment, #], #} & /@ M, #[[1]] &],
       i_ /; i[[1]] < 1*^-10][[1]];
    (* If no intersection was found, we're done. *)
    If[\[Lambda] == \[Infinity], Break[]];
    (* Reduce remaining beam length. *)
    dLeft -= \[Lambda];
    (* The following lines reflect the beam at the mirror and add
       the intersection to our list of points. We also update the
       end-point and the last segment. *)
    p = lastSegment[[1]];
    d = -Subtract @@ lastSegment;
    d /= Norm@d;
    md = -Subtract @@ m;
    md /= Norm@md;
    mn = {md[[2]], -md[[1]]};
    AppendTo[points, p + \[Lambda]*d];
    d = -d + 2*(d - d.mn*mn);
    e = Last@points + dLeft*d;
    lastSegment = {Last@points, e};
    ];
   (* Get a list of all points in the set up so we can determine
      the plot range. *)
   coords = Transpose@Join[Flatten[M, 1], {L, e}];
   (* Turn the list of points into a list of segments. *)
   segments = Partition[points, 2, 1];
   (* For each prefix of that list, generate a frame. *)
   frames = Map[
     Graphics[
       {Line /@ M,
        Red,
        Point@L,
        Line /@ segments[[1 ;; #]]},
       PlotRange -> {
         {Min@coords[[1]] - 1, Max@coords[[1]] + 1},
         {Min@coords[[2]] - 1, Max@coords[[2]] + 1}
         }
       ] &,
     Range@Length@segments];
   (* Generate the initial frame, without any segments. *)
   PrependTo[frames,
    Graphics[
     {Line /@ M,
      Red,
      Point@L},
     PlotRange -> {
       {Min@coords[[1]] - 1, Max@coords[[1]] + 1},
       {Min@coords[[2]] - 1, Max@coords[[2]] + 1}
       }
     ]
    ];
   (* Generate the final frame including lastSegment. *)
   AppendTo[frames,
    Graphics[
     {Line /@ M,
      Red,
      Point@L,
      Line /@ segments,
      Line[lastSegment],
      Point@e},
     PlotRange -> {
       {Min@coords[[1]] - 1, Max@coords[[1]] + 1},
       {Min@coords[[2]] - 1, Max@coords[[2]] + 1}
       }
     ]];

   (*Uncomment to only view the final state *)
   (*Last@frames*)

   (* Export the frames as a GIF. *)
   durations = ConstantArray[0.1, Length@frames];
   durations[[-1]] = 1;
   Export["hardcoded/path/to/laser.gif", frames,
    "GIF", {"DisplayDurations" -> durations, ImageSize -> 600}];

   (* Generate a Mathematica animation form the frame. *)
   ListAnimate@frames
   ];

```

You can call it like

```
plotLaser[{1, 1}, 7.50492, 95, {
  {{4.8, 5.3}, {6.2, 4.3}}, {{1.5, 4.8}, {3.5, 6}}, {{6.3, 1.8}, {7.1, 3}},
  {{5, 1}, {4, 3}}, {{7, 6}, {5, 6.1}}, {{8.5, 2.965}, {8.4, 2}},
  {{8.5, 3.035}, {8.6, 4}}, {{8.4, 2}, {10.5, 3}}, {{8.6, 4}, {10.5, 3}}
}]

```

That will give you an animation in Mathematica and also export a GIF (the one at the top for this input). I've slightly extended the OPs example for this, to make it a bit more interesting.

### More examples

A tube with slightly diverging walls but a closed end:

```
plotLaser[{0, 0}, 1.51, 200, {
  {{0, 1}, {20, 1.1}},
  {{0, -1}, {20, -1.1}},
  {{20, 1.1}, {20, -1.1}}
}]

```

An equilateral triangle and an initial direction that is almost parallel to one of the sides.

```
plotLaser[{-1, 0}, Pi/3 + .01, 200, {
  {{-2.5, 5 Sqrt[3]/6}, {2.5, 5 Sqrt[3]/6}},
  {{0, -5 Sqrt[3]/3}, {-2.5, 5 Sqrt[3]/6}},
  {{0, -5 Sqrt[3]/3}, {2.5, 5 Sqrt[3]/6}}
}]

```

One more:

```
plotLaser[
 {0, 10}, -Pi/2, 145,
 {
   {{-1, 1}, {1, -1}}, {{4.5, -1}, {7.5, Sqrt[3] - 1}},
   {{11, 10}, {13, 10}}, {{16.5, Sqrt[3] - 1}, {19.5, -1}},
   {{23, -1}, {25, 1}}, {{23, 6}, {25, 4}}, {{18, 6}, {20, 4}}, {{18, 9}, {20, 11}},
   {{31, 9}, {31.01, 11}}, {{24.5, 10.01}, {25.52, 11.01}}, {{31, 4}, {31, 6}}, {{25, 4.6}, {26, 5.6}}, {{24.5, 0.5}, {25.5, -0.5}},
   {{31, -1}, {33, 1}}, {{31, 9}, {33, 11}}, {{38, 10.5}, {38.45, 9}}
 }
]

```

## Ruby, golfed answer

```
x,y,t,p,*m=gets.split.map &:to_f
u=q=Math.cos t
v=r=Math.sin t
loop{k=i=p
u=x+q*p
v=y+r*p
m.each_slice(4){|a,b,c,d|((a-u)*r-(b-v)*q)*((c-u)*r-(d-v)*q)>0?next: g=c-a
h=d-b
l=(h*(x-a)-g*(y-b))/(r*g-q*h)
f=(g*g+h*h)**0.5
t,k,i=g/f,h/f,l if l.abs>1e-9&&l/i<1}
i==p ?abort([u,v]*' '): p-=i
x+=q*i
y+=r*i
n=q*k-r*t
q-=2*n*k
r+=2*n*t}

```

This is basically a direct translation of the Mathematica solution to Ruby, plus some golfing and making sure it meets the I/O criteria.
> 39 votes

# Answer
# Python 3(~~421C 390C~~,366C)

Use `builtin.complex` as 2d vector. So

```
dot = lambda a, b: (a.conjugate() * b).real
cross = lambda a, b: (a.conjugate() * b).imag

```

In order to beat the 368C Ruby solution, I've find a quite compact method to calculate point reflection along a mirror. And also used some complex algebra to reduce more characters. These can be easily found in the ungolfed code.

Here's the golfed version.

```
C=lambda a,b:(abs(a)**2/a*b).imag
J=1j
x,y,r,d,*a=map(float,input().split())
p=x+y*J
q=p+d*2.718281828459045**(r*J)
M=[]
while a:x,y,z,w,*a=a;M+=[(x+y*J,z-x+w*J-y*J)]
def T(m):x,y=m;d=C(y,r)+1e-9;t=C(y,x-p)/d;s=C(r,x-p)/d;return[1,t][(1e-6<t<1)*(0<s<1)]
while 1:
 r=q-p;m=f,g=min(M,key=T)
 if T(m)==1:break
 p+=r*T(m);q=(q/g-f/g).conjugate()*g+f
print(q.real,q.imag)

```

## Ungolfed

```
# cross product of two vector
# abs(a)**2 / a == a.conjugate()
cross = lambda a, b: (abs(a)**2 / a * b).imag
# Parse input
x, y, angle, distance, *rest = map(float, input().split())
start = x + y * 1j
# e = 2.718281828459045
# Using formula: e**(r*j) == cos(r) + sin(r) * j
end = start + distance * 2.718281828459045 ** (angle * 1j)
mirrors = []
while rest:
    x1, y1, x2, y2, *rest = rest
    # Store end point and direction vector for this mirror
    mirrors.append((x1 + y1 * 1j, (x2 - x1) + (y2 - y1) * 1j))

def find_cross(mirror):
    # a: one end of mirror
    # s: direction vector of mirror
    a, s = mirror
    # Solve (t, r) for equation: start + t * end == a + r * s
    d = cross(s, end - start) + 1e-9 # offset hack to "avoid" dividing by zero
    t = cross(s, a - start) / d
    r = cross(end - start, a - start) / d
    return t if 1e-6 < t < 1 and 0 < r < 1 else 1

def reflect(p, mirror):
    a, s = mirror
    # Calculate reflection point:
    #  1. Project r = p - a onto a coordinate system that use s as x axis, as r1.
    #  2. Take r1's conjugate as r2.
    #  3. Recover r2 to original coordinate system as r3
    #  4. r3 + a is the final result
    #
    # So we got conjugate((p - a) * conjugate(s)) / conjugate(s) + a
    # which can be reduced to conjugate((p - a) / s) * s + a
    return ((p - a) / s).conjugate() * s + a

while 1:
    mirror = min(mirrors, key=find_cross)
    if find_cross(mirror) == 1:
        break
    start += (end - start) * find_cross(mirror)
    end = reflect(end, mirror)
print(end.real, end.imag)

```

# Bonus: HTML, Coffeescript, Realtime Adjustment & Calculation

This is, you drag any end points(or lazer, mirros), then the track is rendered. It also support two types of input, the one described in the question and the one used by @Martin Büttner.

The scaling is also adjusted automatically.

For now it doesn't has animation. Maybe I'll improve it later. However, dragging the white points and you can see another type of animation. Try it online here yourself, it's funny!

The whole project can be found Here

## Update

Here I provide an interesting case:

```
0 0.6 -0.0002 500.0 0.980785280403 -0.195090322016 1.0 0.0 1.0 0.0 0.980785280403 0.195090322016 0.980785280403 0.195090322016 0.923879532511 0.382683432365 0.923879532511 0.382683432365 0.831469612303 0.55557023302 0.831469612303 0.55557023302 0.707106781187 0.707106781187 0.707106781187 0.707106781187 0.55557023302 0.831469612303 0.55557023302 0.831469612303 0.382683432365 0.923879532511 0.382683432365 0.923879532511 0.195090322016 0.980785280403 0.195090322016 0.980785280403 6.12323399574e-17 1.0 6.12323399574e-17 1.0 -0.195090322016 0.980785280403 -0.195090322016 0.980785280403 -0.382683432365 0.923879532511 -0.382683432365 0.923879532511 -0.55557023302 0.831469612303 -0.55557023302 0.831469612303 -0.707106781187 0.707106781187 -0.707106781187 0.707106781187 -0.831469612303 0.55557023302 -0.831469612303 0.55557023302 -0.923879532511 0.382683432365 -0.923879532511 0.382683432365 -0.980785280403 0.195090322016 -0.980785280403 0.195090322016 -1.0 1.22464679915e-16 -1.0 1.22464679915e-16 -0.980785280403 -0.195090322016 -0.980785280403 -0.195090322016 -0.923879532511 -0.382683432365 -0.923879532511 -0.382683432365 -0.831469612303 -0.55557023302 -0.831469612303 -0.55557023302 -0.707106781187 -0.707106781187 -0.707106781187 -0.707106781187 -0.55557023302 -0.831469612303 -0.55557023302 -0.831469612303 -0.382683432365 -0.923879532511 -0.382683432365 -0.923879532511 -0.195090322016 -0.980785280403 -0.195090322016 -0.980785280403 -1.83697019872e-16 -1.0 -1.83697019872e-16 -1.0 0.195090322016 -0.980785280403 0.195090322016 -0.980785280403 0.382683432365 -0.923879532511 0.382683432365 -0.923879532511 0.55557023302 -0.831469612303 0.55557023302 -0.831469612303 0.707106781187 -0.707106781187 0.707106781187 -0.707106781187 0.831469612303 -0.55557023302 0.831469612303 -0.55557023302 0.923879532511 -0.382683432365 0.923879532511 -0.382683432365 0.980785280403 -0.195090322016

```

And the result is:
> 19 votes

# Answer
## HTML JavaScript, ~~10,543~~, ~~947~~ 889

I fixed a bug and made sure the output meets the question spec. The webpage below has the golfed version and also the graphical bonus version. I also fixed a bug pointed out by @Ray which saved 58 characters. (Thanks Ray.) You can also run the golfed code in a JavaScript console. (Now I'm using a 2mW green laser.)

**Golf Code**

```
a=prompt().split(" ").map(Number);M=Math,Mc=M.cos,Ms=M.sin,P=M.PI,T=2*P,t=true;l=new S(a[0],a[1],a[0]+a[3]*Mc(a[2]),a[1]+a[3]*Ms(a[2]));m=[];for(i=4;i<a.length;)m.push(new S(a[i++],a[i++],a[i++],a[i++]));f=-1;for(;;){var h=!t,d,x,y,n,r={};for(i=0;i<m.length;i++)if(i!=f)if(I(l,m[i],r))if(!h||r.d<d){h=t;d=r.d;x=r.x;y=r.y;n=i}if(h){l.a=x;l.b=y;l.e-=d;l.f=2*(m[f=n].f+P/2)-(l.f+P);l.c=l.a+l.e*Mc(l.f);l.d=l.b+l.e*Ms(l.f);}else break;}alert(l.c+" "+l.d);function S(a,b,c,d){this.a=a;this.b=b;this.c=c;this.d=d;this.e=D(a,b,c,d);this.f=M.atan2(d-b,c-a)}function D(a,b,c,d){return M.sqrt((a-c)*(a-c)+(b-d)*(b-d))}function I(l,m,r){A=l.a-l.c,B=l.b-l.d,C=m.a-m.c,L=m.b-m.d,E=l.a*l.d-l.b*l.c,F=m.a*m.d-m.b*m.c,G=A*L-B*C;if(!G)return!t;r.x=(E*C-A*F)/G;r.y=(E*L-B*F)/G;H=r.d=D(l.a,l.b,r.x,r.y),O=D(l.c,l.d,r.x,r.y),J=D(m.a,m.b,r.x,r.y),K=D(m.c,m.d,r.x,r.y);return(H<l.e)&&(O<l.e)&&(J<m.e)&&(K<m.e);}

```

**Input**

```
1 1 7.50492 17 4.8 6.3 6.2 5.3 1.5 4.8 3.5 6 6.3 1.8 7.1 3

```

**Output**

```
14.743305098514739 3.759749038188634

```

You can test it here: http://goo.gl/wKgIKD

**Explanation**

The code in the webpage is commented. Basically I calculate the intersection of the laser with every mirror assuming the laser and mirrors are infinitely long. Then I check if the intersection is within the finite length of the mirror and the laser. Then I take the closest intersection, move the laser to that point, and continue until the laser misses all the mirrors.

Very fun project. Thanks for asking this question!

**Readable code**

```
// a = input array
// M = Math, Mc = M.cos, Ms = M.sin, P=M.PI, T=2*P, t=true
// l = laser segment
// m = array of mirror segments
// i = loop variable
// S = segment class (this.a=x1,b=y1,c=x2,d=y2,e=len,f=theta)
// D = distance function
// I = intersect function
// f = last mirror bounced from
// h = hits a mirror
// n = next intersecing mirror
// d = distance to mirror
// x = intersection point x
// y = intersection point y
// r = mirror intersection result (d,x,y)
// b = number of bounces (FOR DEBUGGING)
// A,B,C,E,F,G,H,J,K,L,O temp variables
// s = laser segment array

// get input array
var a = prompt().split(" ").map(Number);

// some constants
var M = Math, Mc = M.cos, Ms = M.sin, P = M.PI, T = 2 * P, t = true;

// laser segment
var l = new S(a[0], a[1], a[0] + a[3] * Mc(a[2]), a[1] + a[3] * Ms(a[2])), s = [];

// mirror segments
var m = []; for (var i = 4; i < a.length;) m.push(new S(a[i++], a[i++], a[i++], a[i++]));

// bounce until miss
var f = -1, b = 0; for (; ;) {

    // best mirror found
    var h = !t, d, x, y, n, r = {};

    // loop through mirrors, skipping last one bounced from
    for (var i = 0; i < m.length; i++)
        if (i != f)
            if (I(l, m[i], r))
                if (!h || r.d < d) { h = t; d = r.d; x = r.x; y = r.y; n = i }

    // a mirror is hit
    if (h) {

        // add to draw list, inc bounces
        s.push(new S(l.a, l.b, x, y)); b++;

        // move and shorten mirror
        l.a = x; l.b = y; l.e -= d;

        // calculate next angle
        l.f = 2 * (m[f = n].f + P / 2) - (l.f + P);

        // laser end point
        l.c = l.a + l.e * Mc(l.f); l.d = l.b + l.e * Ms(l.f);

    } else {

        // add to draw list, break
        s.push(new S(l.a, l.b, l.c, l.d));
        break;
    }
}
// done, print result
alert("X = " + l.c.toFixed(6) + ",  Y = " + l.d.toFixed(6) + ",  bounces = " + b);
PlotResult();

// segment class
function S(a, b, c, d) { this.a = a; this.b = b; this.c = c; this.d = d; this.e = D(a, b, c, d); this.f = M.atan2(d - b, c - a) }

// distance function
function D(a, b, c, d) { return M.sqrt((a - c) * (a - c) + (b - d) * (b - d)) }

// intersect function
function I(l, m, r) {

    // some values
    var A = l.a - l.c, B = l.b - l.d, C = m.a - m.c, L = m.b - m.d, E = l.a * l.d - l.b * l.c, F = m.a * m.d - m.b * m.c, G = A * L - B * C;

    // test if parallel
    if (!G) return !t;

    // intersection
    r.x = (E * C - A * F) / G; r.y = (E * L - B * F) / G;

    // distances
    var H = r.d = D(l.a, l.b, r.x, r.y), O = D(l.c, l.d, r.x, r.y), J = D(m.a, m.b, r.x, r.y), K = D(m.c, m.d, r.x, r.y);

    // return true if intersection is with both segments
    return (H < l.e) && (O < l.e) && (J < m.e) && (K < m.e);
}

```
> 17 votes

# Answer
# Python - 765

Good challenge. This is my solution which gets input from stdin and outputs to stdout. Using @Martin Büttner's example:

```
python mirrors.py 1 1 70.00024158332184 95 4.8 5.3 6.2 4.3 1.5 4.8 3.5 6 6.3 1.8 7.1 3     5 1 4 3 7 6 5 6.1 8.5 2.965 8.4 2 8.5 3.035 8.6 4 8.4 2 10.5 3 8.6 4 10.5 3

7.7094468894 3.84896396639

```

Here is the golfed code:

```
import sys;from cmath import*
l=[float(d) for d in sys.argv[1:]];c=180/pi;p=phase;q=exp;u=len;v=range
def o(l):
 L=l[0]+1j*l[1];t=l[2]/c;D=l[3];S=[L,L+D*q(1j*t)];N=[[l[i]+1j*l[i+1],l[i+2]+1j*l[i+3]] for i in v(4,u(l),4)];a=[];b=[]
 for M in N:
  z=S[1].real-S[0].real;y=M[0].real-M[1].real;x=S[1].imag-S[0].imag;w=M[0].imag-M[1].imag;d=M[0].real-S[0].real;f=M[0].imag-S[0].imag;g=z*w-x*y;h=w/g;j=-y/g;m=-x/g;n=z/g;a.append(h*d+j*f);b.append(m*d+n*f)
 i=1;e=-1
 for k in v(u(N)):
  if 1>b[k]>0:
   if i>a[k]>1e-14:
    i=a[k];e=k
 if e>-1:
  L=S[0]+i*(S[1]-S[0]);M=N[e];l[0]=L.real;l[1]=L.imag;l[2]=c*(p(M[1]-M[0])+p(q(1j*p(M[1]-M[0]))*q(1j*-t)));l[3]=D*(1-i)
  return l
 J=S[0]+i*(S[1]-S[0])
 print J.real, J.imag
 return J.real, J.imag
while u(l)>2:
 l=o(l)

```

And here is the ungolfed code with a bonus figure

```
import sys
from cmath import*
import matplotlib
import matplotlib.pyplot as plt
l=[float(d) for d in sys.argv[1:]]
def nextpos(l):
    L=l[0]+1j*l[1]
    t=l[2]/180*pi
    D=l[3]
    S=[L,L + D * exp(1j * t)]
    MM=[[l[i]+1j*l[i+1],l[i+2]+1j*l[i+3]] for i in range(4,len(l), 4)]
    a=[]
    b=[]
    for M in MM:
        #determine intersections
        a11 = S[1].real-S[0].real
        a12 = M[0].real-M[1].real
        a21 = S[1].imag-S[0].imag
        a22 = M[0].imag-M[1].imag
        b1  = M[0].real-S[0].real
        b2  = M[0].imag-S[0].imag
        deta = a11*a22-a21*a12
        ai11 = a22/deta
        ai12 = -a12/deta
        ai21 = -a21/deta
        ai22 = a11/deta
        a.append(ai11*b1+ai12*b2)
        b.append(ai21*b1+ai22*b2)
    #determine best intersection
    mina = 1
    bestk = -1
    for k in range(len(MM)):
        if 1>b[k]>0:
            if mina>a[k]>1e-14:
                mina=a[k]
                bestk=k
    if bestk>-1:
        #determine new input set
        L=S[0]+mina*(S[1]-S[0])
        M=MM[bestk]
        l[0]=L.real
        l[1]=L.imag
        angr=phase(exp(1j*phase(M[1]-M[0]))*exp(1j *-t))
        l[2]=180/pi*(phase(M[1]-M[0])+angr)
        l[3]=D*(1-mina)
        return l
    J= S[0]+mina*(S[1]-S[0])
    print J.real, J.imag
    return J.real, J.imag
#plotting
xL = [l[0]]
yL = [l[1]]
fig = plt.figure()
ax = fig.add_subplot(111,aspect='equal')
for i in range(4,len(l), 4):
    plt.plot([l[i],l[i+2]],[l[i+1],l[i+3]], color='b')
while len(l)>2:
    #loop until out of lasers reach
    l = nextpos(l)
    xL.append(l[0])
    yL.append(l[1])
plt.plot(xL,yL, color='r')
plt.show()

```
> 6 votes

# Answer
# Matlab (388)

## Plot

## Concepts

### Reflection Points

For calculating the reflection points we basically have to interesect two straight lines. One with the point p0 and vector v, the other between the two points p1,p2. So the equation to solve is (s,t are parameters): p0+t*v = s*p1+(1-s)\*p2.

The parameter s is then a barycentric coordinate of the mirror so if 0

### Mirroring

The mirroring of v is pretty simple. Let us assume that ||v|| = ||n|| = 1 where n is the normal vector of the current mirror. Then you can just use the formula v := v-2\**n where \<,\> is the dot product.

### Validity of step

While computing the nearest 'valid' mirror we have to consider some criterias that make it valid. First the interception point of the mirror must lie between the two endpoints, so it must be 0

## Program

```
p = [1 1 430 17 4.8 5.3 6.2 4.3 1.5 4.8 3.5 6 6.3 1.8 7.1 3];
hold on
grid on
for i=2:length(p)/4
    i = i*4+1-4
    p2=p(i+2:i+3)';
    p1=p(i:i+1)'
    plot([p1(1),p2(1)],[p1(2),p2(2)],'r-')
    text(p1(1),p1(2),['m' num2str((i+3)/4-1)])
end
%hold off

history = p(1:2)';

currentPosition = p(1:2)';%current
currentDirection=[cos(p(3)*pi/180);sin(p(3)*pi/180)];
while p(4)>0%as long as we do not have finished our distance
   distanceBuffer = Inf%distance next point buffer
   intersectionBuffer = NaN %next point buffer
   for i=2:length(p)/4%number of mirrors
       i = i*4+1-4 %i is now the index of the firs coordinate of the mirror
       %calculate all crosspoints
       p2=p(i+2:i+3)';
       mirrorVector = p2-p(i:i+1)';
       % idea: p0+s*currentDirection = s*p1+(1-s)*p2 solving for s,t
       r=[currentDirection,mirrorVector]\[p2-currentPosition];
       if r(1)<distanceBuffer && 0.001< r(1) && r(1)<p(4) &&0<=r(2) && r(2)<=1 %search for the nearest intersection
           distanceBuffer=r(1);
           intersectionBuffer=r(1)*currentDirection+currentPosition;
           mirrorBuffer = mirrorVector
       end
   end
   if distanceBuffer == Inf %no reachable mirror found
       endpoint = currentPosition+p(4)*currentDirection;
       counter = counter+1
       history = [history,endpoint];
       break
   else %mirroring takes place
       counter = counter+1
       history = [history,intersectionBuffer];
       currentPosition=intersectionBuffer;
       normal = [0,-1;1,0]*mirrorBuffer;%normal vector of mirror
       normal = normal/norm(normal)
       disp('arccos')
       currentDirection = currentDirection-2*(currentDirection'*normal)*normal;
       %v = v/norm(v)
       p(4)=p(4)-distanceBuffer
   end
end
history
plot(history(1,:),history(2,:))

```

## Slightly golfed (388)

```
p=[1 1 430 17 4.8 5.3 6.2 4.3 1.5 4.8 3.5 6 6.3 1.8 7.1 3];
c=p(1:2)'
b=pi/180
v=[cos(p(3)*b);sin(p(3)*b)]
f=p(4)
while f>0
q=Inf
for i=2:length(p)/4
b=p(i+2:i+3)'
u=b-p(i:i+1)'
r=[v,u]\[b-c]
s=r(1)
t=r(2)
if s<q&&0.001<s&&s<f&&0<=t&&t<=1
q=s
n=s*v+c
m=u
end
end
if q==Inf
disp(c+f*v)
break
else
c=n
g=[0,-1;1,0]*m
g=g/norm(g)
v=v-2*(v'*g)*g
f=f-q
end
end

```
> 6 votes

---
Tags: code-golf
---


title: Draw a Permutation Path

text:
# Question
Title: Draw a Permutation Path
Imagine the following diagrams as sets of vertical criss-crossing tubes.

```
1 2    1 2    1 2 3 4
\ /    \ /    \ / \ /
 X      |      |   |
/ \    / \    / \ / \
2 1    1 2   |   X   |
              \ / \ /
               X   X
              / \ / \
              3 1 4 2

```

In the leftmost diagram, the `1` and `2` slide down their respective slashes, cross at the `X`, and come out at opposite sides from where they started.

It's the same idea in the middle diagram, but the `|` signifies that the paths do not cross, so nothing changes.

The rightmost diagram shows a more complex tube routing that permutes `1 2 3 4` into `3 1 4 2`.

# Goal

Your goal in this code golf challenge is to draw these "tube routing diagrams" given a permutation such as `3 1 4 2`. The shortest program in bytes will win.

# Details

1. Input comes from stdin as any permutation of the numbers from 1 to *n* separated by spaces, where *n* is a positive integer. You may assume all input is well formed.
2. The routing diagram output goes to stdout.

* "Dropping" the numbers 1 through *n* in order into the top of the diagram should result in the input permutation coming out at the bottom. (Top and bottom are always layers of slashes.)
    * The diagram does not need to be optimally small. It may be as many levels as necessary as long as it is correct.
    * The diagram should only contain the characters `\/ X|` as well as newlines (no numbers).
    * `|` should always be used on the outermost intersections since using `X` wouldn't make sense.
    * A few leading or trailing spaces is fine as long as the diagram is all lined up correctly.

# Examples

An input of `3 1 4 2` might produce (same as above)

```
 \ / \ /
  |   |
 / \ / \
|   X   |
 \ / \ /
  X   X
 / \ / \

```

An input of `1` might produce

```
 \
  |
 /
|
 \
  |
 /

```

An input of `3 2 1` might produce

```
 \ / \
  X   |
 / \ /
|   X
 \ / \
  X   |
 / \ /

```

An input of `2 1 3 4 6 5` might produce

```
\ / \ / \ /
 X   |   X
/ \ / \ / \

```

# Answer
# Python 2, 218 219 220 222 224 227 243 247 252 259 261 264

```
l=map(int,raw_input().split())
f=n=len(l)
o=s=n*' \ /'
while f+n%2:
 f-=1;i=f+n&1;a=s[2*i:][:2*n]+'\n|   '[::2-i]
 while~i>-n:a+='|X'[l[i+1]<l[i]]+'   ';l[i:i+2]=sorted(l[i:i+2]);i+=2
 o=a+f%2*'|'+'\n'+o
print o[:-2*n]

```

I took a slightly different approach: I find the swaps necessary to sort the input, then vertically invert that to get the swaps necessary to turn the sorted list into the input. As an added bonus of this approach, it can take an arbitrary list of numbers and give the permutation path to turn the sort of the input into the input.

Example:

```
$ python sort_path.py <<< '3 1 4 5 9 2 6 8 7'
 \ / \ / \ / \ / \
  |   |   |   |   |
 / \ / \ / \ / \ /
|   |   |   |   |
 \ / \ / \ / \ / \
  |   |   |   |   |
 / \ / \ / \ / \ /
|   |   |   |   |
 \ / \ / \ / \ / \
  |   |   |   |   |
 / \ / \ / \ / \ /
|   X   |   |   X
 \ / \ / \ / \ / \
  |   X   |   X   |
 / \ / \ / \ / \ /
|   |   X   X   |
 \ / \ / \ / \ / \
  X   |   X   |   |
 / \ / \ / \ / \ /
|   |   |   |   X
 \ / \ / \ / \ / \

```

Improvements:

264 -\> 261: Switched outer loop from for to while.

261 -\> 259: Used `f%2` instead of `(c^m)`, because in python arithmetic operators have higher priority than bitwise operators.

259 -\> 252: Switched inner loop from for to while. Combined `i` and `c` variables.

252 -\> 247: Changed build then reverse to just build in reverse order.

247 -\> 243: Added newlines manually, instead of using join.

243 -\> 227: Adopted grc's method of slash line generation (thanks grc!) and added s.

227 -\> 224: Moved slash line generation to before inner while loop to remove a `%4` and save a character by using extended slicing.

224 -\> 222: Removed m.

222 -\> 220: `f%2+n%2` -\> `f+n&1`

220 -\> 219: `| 1<n-1|` -\> `|~i>-n|` (removed leading space)

219 -\> 218: Combined initializations of `o` and `s` and moved the slice to the end.
> 5 votes

# Answer
## Python, 290

```
def g(o,u=1):
 s=['|']*o
 for i in range(o,n-1,2):v=r[i+1]in a[:a.index(r[i])]*u;s+=['|X'[v]];r[i:i+2]=r[i:i+2][::1-2*v]
 print'  '*(1-o)+'   '.join(s+['|']*(o^n%2))*u+'\n'*u+(' / \\'*n)[2*o:][:n*2]
a=map(int,raw_input().split())
n=len(a)
r=range(1,n+1)
o=1
g(1,0)
g(0)
while r!=a:g(o);o^=1

```

I went for a fairly basic approach, but it turned out a bit longer than I was hoping. It considers the list in pairs and decides whether or not to swap each pair. This is repeated for every intersecting row until the list matches the input.

Example:

```
$ python path.py
5 3 8 1 4 9 2 7 6
 \ / \ / \ / \ / \
  |   |   |   X   |
 / \ / \ / \ / \ /
|   X   X   X   X
 \ / \ / \ / \ / \
  X   X   X   X   |
 / \ / \ / \ / \ /
|   X   X   |   X
 \ / \ / \ / \ / \
  X   X   X   |   |
 / \ / \ / \ / \ /
|   |   |   X   |
 \ / \ / \ / \ / \

```
> 9 votes

# Answer
## HTML JavaScript, ~~553~~ 419

Thank you to @izlin and @TomHart for pointing out my errors.

```
p=prompt();b=p.split(" "),l=b.length,d=l%2,o="",s=["","","\\/"],n="\n",a=[];for(i=0;i<l;i++){a[b[i]-1]=i+1;s[1]+=" "+s[2][i%2];s[0]+=" "+s[2][(i+1)%2];o+=" "+(i+1)}s[1]+=n,s[0]+=n;o+=n+s[1];f=1,g=2;do{var c="";for(var i=(f=f?0:1);i<l-1;i+=2)if(a[i]>a[i+1]){c+="  x ";g=2;t=a[i];a[i]=a[i+1];a[i+1]=t;}else c+="  | ";if(g==2){o+=(d?(f?"| "+c:c+"  |"):(f?"| "+c+"  |":c))+n;o+=(s[f]);}}while(--g);o+=" "+p;alert(o);

```

Test here: http://goo.gl/NRsXEj
> 2 votes

# Answer
## Javascript - 395

378 if i don't print the numbers on my output, but it looks much better and improves the readability.
Test it here. (with ungolfed version)
golfed Version:

```
a=prompt(),n=a.split(" "),l=n.length,k=[],s="",i=1;for(j=0;j<l;j++){k[n[j]-1]=j+1;s+=" "+(j+1)}s+="\n";while(i++){for(j=0;j<l;j++)s+=i%2?j%2?" \\":" /":j%2?" /":" \\";for(z=0,y=0;z<l-1;z++)if(k[z]>k[z+1])y=1;if(y==0&&i!=2)break;s+="\n";for(m=i%2;m<l;m+=2){s+=i%2&&m==1?"|":"";if(k[m]>k[m+1]){[k[m],k[m+1]]=[k[m+1],k[m]];s+=i%2?"   X":"  X "}else{s+=i%2?"   |":"  | "}}s+="\n"}s+="\n "+a;alert(s)

```

### Explanation

First I substitude the input, with the index number and change the first line with the results. For example

```
3 1 4 2
v v v v substitude with
1 2 3 4

so the first line will become:
1 2 3 4
v v v v
2 4 1 3

sorting 1,2,3,4 to 3,1,4,2 is equivalent to 2,4,1,3 to 1,2,3,4

```

With this substitution i can use a bubble-sort algorithm to sort 2,4,1,3 to 1,2,3,4 and the graph will be the shortest possible one we're searching for.
If you have any ideas how i can make the code smaller just comment :)

### Example

```
input: 3 4 2 1 7 5 6
output:
 1 2 3 4 5 6 7
 \ / \ / \ / \
  X   |   |   |
 / \ / \ / \ /
|   X   |   X
 \ / \ / \ / \
  X   X   X   |
 / \ / \ / \ /
|   X   |   |
 \ / \ / \ / \
 3 4 2 1 7 5 6

```
> 1 votes

# Answer
# Cobra - 334 ~~344~~ ~~356~~ ~~360~~

```
class P
    def main
        a,o,n=CobraCore.commandLineArgs[1:],['/','\\'],0
        c,l=a.count,a.sorted
        while (n+=1)%2or l<>a
            p,d='',(~n%4+4)//3
            for i in n%2*(c+1-c%2),p,o=p+o[1]+' ',[o.pop]+o
            for i in 1+d:c-n%2*c:2
                z=if(l[:i]<>a[:i],1,0)
                l.swap(i-z,i)
                p+=' ['|X'[z]]  '
            print[['','| '][d]+[p,p+'|'][d^c%2],p][n%2][:c*2]

```

It works by moving each element into place starting from the left. Due to this, it will often output a ridiculously large (although still correct) path-map.

## Examples:

```
3 1 4 2

\ / \ /
 X   X
/ \ / \
|  X  |
\ / \ /
 X   X
/ \ / \
|  X  |
\ / \ /
 X   X
/ \ / \
|  X  |
\ / \ /

```
> 1 votes

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