title: Make a Math Competition Grader

text:
# Question
Title: Make a Math Competition Grader
I enjoy participating in math competitions run by Mu Alpha Theta, a mathematics honor society in the United States. At competitions, I take a 30-question multiple choice test. There are five choices per question, labeled A through E.

My score on a test is four points for each correct answer, zero points for a question left blank, and negative one points for each wrong answer.

Write a program that grades a test according to the above scoring system. There should be two components to the input: an answer key followed by responses. Questions left blank are to be inputted as blank spaces. The first input must contain only the letters A-E (or a-e, your choice), and it can be assumed that there is no whitespace in the input. The second input must only contain blank spaces and the letters A-E (or a-e). Inputs not implementing 30-question tests must print `Invalid test` as output.

The output should be the grade or `Invalid test`.

*Bonus*

If your program prints the number right, number left blank, and number wrong after the final score as `(aR bB cW)`, take off 20 bytes.

**Sample input**

```
CABBDCABECDBACDBEAACADDBBBEDDA    //answer key
CABEDDABDC BACDBBAADE  CBBEDDA    //responses

```

**Sample output**

*No bonus*

```
73

```

*Bonus*

```
73 (20R 3B 7W)

```

---

Standard rules apply. Shortest code in bytes wins.

# Answer
# Pyth, ~~53~~ 51

```
?&!-sJ.z+d<G5&FqR30lMJ+sm?qFd4_1CJ/eJd"Invalid test

```

Try it online

The checks are done by seeing if the entire input contains any characters when all of the spaces and `a-e` are removed, and by checking if both strings have length `30`.

The score calculation is done by zipping the two lines together, then by mapping each pair to: `(letters are equal) ? 4 : -1`. Then simply summing the values, and adding the number of spaces in the second line back to the score.
> 7 votes

# Answer
## Seriously, 86 bytes

,`;l5╙¬=);' UΣS" ABCDE"=(**;l`Mi@)=YWé"Invalid test"0WX@Z```i@;(=5*(' =D+`(;l@)5╙¬=IMΣ
</code></pre>

Takes input like `"CABBDCABECDBACDBEAACADDBBBEDDA", "CABEDDABDC BACDBBAADE CBBEDDA"`

Try it online (you will have to manually enter the input because permalinks don't like quotes)

~~Working on the bonus now.~~ Nope, adding the bonus would cost more than 20 bytes.

I knew I was forgetting something... `Invalid Test` wasn't being printed in the event of an error. There go my hopes of out-golfing Dennis.
> 7 votes

# Answer
# JavaScript (ES6), 134 bytes

**Edit:** The question requirements changed. This answer is from when the program needed to make sure each answer character is A-E, each response character is A-E or space and they both have lengths of 30, else return `Invalid test`.

```
(a,r)=>[...a].map((q,i)=>q>"E"|q<"A"?x=1:(c=r[l=i])==" "?0:c>"E"|c<"A"?x=1:c==q?s+=4:s--,s=x=0)&&x|l!=29|r.length!=30?"Invalid test":s

```

## Explanation

```
(a,r)=>                   // a = answer string, r = responses string
  [...a].map((q,i)=>      // iterate over answers, q = answer, i = question number
    q>"E"|q<"A"?x=1:      // x = 1 if answer is invalid
    (c=r[l=i])==" "?0:    // c = question response, l = answer length, add 0 for space
    c>"E"|c<"A"?x=1:      // x = 1 if response is invalid
    c==q?s+=4:s--,        // add 4 if correct, subtract 1 if incorrect
    s=x=0                 // s = total score, x = is invalid
  )&&
    x|l!=29|r.length!=30? // check input lengths for validity
      "Invalid test":
      s                   // return the score

```

## Test

```
<input type="text" id="answers" value="CABBDCABECDBACDBEAACADDBBBEDDA" />

<input type="text" id="responses" value="CABEDDABDC BACDBBAADE  CBBEDDA" />

<button onclick='result.innerHTML=(

(a,r)=>[...a].map((q,i)=>q>"E"|q<"A"?x=1:(c=r[l=i])==" "?0:c>"E"|c<"A"?x=1:c==q?s+=4:s--,s=x=0)&&x|l!=29|r.length!=30?"Invalid test":s

)(answers.value,responses.value)'>Go</button>

```
> 4 votes

# Answer
# CJam, 60 bytes

```
2{l_,30=\N?}*_2$|S'F,65>+-!@2$.{=4W?}@' f=+:+"Invalid test"?

```

Try it online in the CJam interpreter.
> 3 votes

# Answer
# JavaScript (Firefox 31+), 86 bytes

```
(x,y)=>(r=i=0,[for(l of y)x[i++]==l?r+=4:r-=l!=' '],i!=30|i-x.length?'Invalid test':r)

```

Uses array comprehension which is proposed for ES7. Thus support is limited to Firefox for the moment.

## With bonus, 106 bytes (126 - 20)

```
(x,y)=>[r=w=i=0,[for(l of y)x[i++]==l?r++:w+=l!=' '],`${r*4-w} (${r}R ${i-r-w}B ${w}W)`,'Invalid test'][i!=30||i-x.length?3:2]

```

**Edit:** Previously my solution only checked answer or question length, now checks both.

```
F=(x,y)=>(r=i=0,[for(l of y)x[i++]==l?r+=4:r-=l!=' '],i!=30|i-x.length?'Invalid test':r)
G=(x,y)=>[r=w=i=0,[for(l of y)x[i++]==l?r++:w+=l!=' '],`${r*4-w} (${r}R ${i-r-w}B ${w}W)`,'Invalid test'][i!=30||i-x.length?3:2]

var score = () => result.innerHTML = (bonus.checked ? G:F)(questions.value, answers.value);

questions.oninput = answers.oninput = bonus.onchange = score;
score();
```

```
* {
    box-sizing: border-box;
}

label {
  float: left;
  clear: left;
  vertical-align: middle;
  line-height: 2;
  padding-right: 0.5em;
}

input[type="text"] {
  width: 100%;
  vertical-align: middle;
  line-height: 2;
  font-family: monospace;
  padding: 0 0.5em;
}

input[type="checkbox"] {
  vertical-align: middle;
  line-height: 2;
  margin: 0.5em;
}

hr {
  clear: both;
}

.input-wrapper {
  overflow: hidden;
  width: auto;
}

#result, #error {
  font-weight: bold;
}

#error {
  display: none;
}
```

```

Q:

  <input id="questions" type="text" value="CABBDCABECDBACDBEAACADDBBBEDDA"/>

A:

  <input id="answers" type="text" value="CABEDDABDC BACDBBAADE  CBBEDDA"/>

Bonus:

  <input id="bonus" type="checkbox" checked/>

  Result:

  ERROR: Unsupported browser! Try Firefox 31+

```
> 3 votes

# Answer
## C#, 162 154 148 134 bytes

```
string g(string k,string a)=>k.Length!=30||a.Length!=30?"Invalid Test!":Enumerable.Range(0,30).Sum(e=>a[e]==' '?0:k[e]==a[e]?4:-1)+"";

```

Usage

```
g("CABBDCABECDBACDBEAACADDBBBEDDA", "CABEDDABDC BACDBBAADE  CBBEDDA")

```

Test

http://csharppad.com/gist/15f7c9c3c8cfce471ff2
> 2 votes

# Answer
# Haskell, ~~144~~ 138 bytes

```
a%b|map length[a,b]==[30,30]&&"ABCDE"!a&&"ABCDE "!b=show$sum$zipWith(?)a b|0<1="Invalid test"
l!s=all(`elem`l)
_?' '=0
x?y|x==y=4|0<1=0-1

```

Would be about 50 without the validation. *sniff*.

Usage: `"ABCDEABCDEABCDEABCDEABCDEABCDE" % "AAAAABBBBBCCCCCDDDDDEEEEEAAAAA"`
> 2 votes

# Answer
# Japt, 71 bytes

**Japt** is a shortened version of **Ja**vaScri**pt**. Interpreter

```
Ul ¥30©Vl ¥30«(U+V k"[A-E ]+" ?U¬r@VgZ ¥Y?X+4:VgZ ¥S?X:X-1,0 :`InvÃ. È.

```

The two `.`s at the end should be the unprintable Unicode chars U+0017 and U+0099, respectively.

### How it works

```
Ul ==30&&Vl ==30&&!(U+V k"[A-E ]+" ?Uq r@VgZ ==Y?X+4:VgZ ==S?X:X-1,0 :"Invalid test
                    // Implicit: U = first input, V = second input
Ul ==30&&Vl ==30&&  // If both input lengths are 30, and
!(U+V k"[A-E ]+"?   // removing all ABCDE and spaces from (U+V) results in an empty string:
Uq r@            ,0 //  Reduce U with this function, starting with a value of 0:
VgZ ==Y?            //   If the matching char in V is equal to this char,
X+4                 //    return previous value + 4.
:VgZ ==S?X          //   Else if the matching char in V is a space, return previous value.
:X-1                //   Else (if it's wrong), return previous value - 1.
:"Invalid test      // Else, return "Invalid test".
                    // Implicit: output last expression

```

I hope there's a shorter way to make sure both lengths are equal to 30. Suggestions welcome!
> 2 votes

# Answer
## Python 2.7, ~~131, 116, 109~~, 139

I tried to do a "short" python solution... Well here it is, suggestions are more than welcome

```
lambda c,d:d.count(' ')+sum([-1,4][a==b]for a,b in zip(c,d)if b!=' ')if not set('ABCDE ')^set(c+d)and len(c)==len(d)==30 else'Test Invalid'

```

Adding a few more characters makes it far more readable...

```
def m(c, d):
    if len(c)==len(d)==30:return d.count(' ')+sum((a==b)*4+(a!=b)*-1 for a,b in zip(c,d)if b!=' ')
    return'Test Invalid'

```
> 2 votes

# Answer
# Java, ~~183~~ 169 bytes

This was a nice bit of Java 8 practice:

```
String f(String a,String r){return a.length()==30&r.length()==30?""+IntStream.range(0,30).map(i->a.charAt(i)==r.charAt(i)?4:r.charAt(i)!=' '?-1:0).sum():"Invalid test";}

```
> 2 votes

# Answer
# Ruby, 81 characters

```
->t,s{r=0;30.times{|i|r+=t[i]==s[i]?4:s[i]>' '?-1:0};t.size==30?r:'Invalid test'}

```

Sample run:

```
2.1.5 :001 > ->t,s{r=0;30.times{|i|r+=t[i]==s[i]?4:s[i]>' '?-1:0};t.size==30?r:'Invalid test'}['CABBDCABECDBACDBEAACADDBBBEDDA','CABEDDABDC BACDBBAADE  CBBEDDA']
 => 73

2.1.5 :002 > ->t,s{r=0;30.times{|i|r+=t[i]==s[i]?4:s[i]>' '?-1:0};t.size==30?r:'Invalid test'}['CCCATCH','CABEDDABDC BACDBBAADE  CBBEDDA']
 => "Invalid test"

```
> 2 votes

# Answer
# brainfuck, 354 bytes

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

```

Requires an interpreter that allows you to go left from cell 0. Output is a signed byte. For example, the byte `0x49` is printed for the example input, and `0xFF` is printed for input with the same first line but the second line replaced with "C" and 29 spaces.

The score starts at 0, and as the second line of input is read these changes are made to it:

* Input is correct: Do nothing
* Input is incorrect: Subtract 5
* Input is a space: Subtract 4

Finally, 120 is added. This is functionally the same as assuming a perfect score and applying penalties, rather than starting at 0.

With comments:

```
+[--[>]<<+>-]                          Get 29

,----------[[<<<]>>->[>>>],----------] Get first line of input; for each char sub one
                                       from the 29

<<<[<<<]>>+                            Add one to the cell that originally held 29

[                                      If the cell that originally held 29 is nonzero:

  Write "Invalid test"
  <-[-------<+>]<.+[---<+>]<.++++++++.[-<+++>]<-.+++++++++++.---.-----.-[---<+>]<-.---[-<++++>]<.+++[-<+++>]<.[---<+>]<----.+.

>]

>[                                     If the cell to the right is nonzero:

  This block is only ever entered if "Invalid test" isn't written!

  [                                      For all 30 characters of the first input:

    >,                                     Get char from second input to the right

    ----------                             Subtract 10 for consistency

    -                                      Subtract one more

    >+++++++[<---<<+++>>>-]                Subtract 21 (plus above lines = 32)

    <[                                     If it's nonzero:

      <<+[>>+<<-]                            Add 22 to the character

    ]

    >[>]<<<[                                 If the above block wasn't entered:

      >[>+>+<<-]>>[<<+>>-]                   Make a copy of the character from input 1

      >[>>>]>----                            Subtract 4 from the score

      <<<<[<<<]>>[-]                         Go to the cell just before first character

    ]

    >[>-<-]                                Subtract input 1 char from input 2 char

    >[                                     If the result is nonzero:

      >>[>>>]>-----                          Subtract 5 from the score

      <<<<[<<<]>[-]                          Go back to the result and set it to 0

    ]

    >>                                     Move on to next character

  ]

  ----[>+++<--]>--                       Add 120 to score (perfect score)

  .                                      Print score

  <                                      Go to an empty cell to kill loop

]

```
> 2 votes

# Answer
# Python 3, ~~187 179 175 165 155~~ 151

```
lambda a,b:(['Invalid test',sum([-1,4][i==j]for i,j in zip(a,b))+b.count(' ')][len(a)==len(b)==30and set(a)^set('ABCDE')==set(b)^set('ABCDE ')==set()])

```
> 1 votes

# Answer
# JavaScript ES7, 102

As usual, the bonus is not worth the effort.

```
(k,h,t=i=0)=>[for(x of h)t+=k[i++]==x?4:1-x?0:-1]|/[^ A-E]/.test(k+h)|i-30|k.length-i?"Invalid test":t

```

Checking for invalid spaces in first input (as this makes sense to me) **112**

```
(k,h,t=i=0)=>[for(x of h)(y=k[i++])>' '?t+=y==x?4:1-x?0:-1:k=h+h]|/[^ A-E]/.test(k+h)|i-30|k[i]?"Invalid test":t

```
> 1 votes

# Answer
## C# 6.0 --\> (270 - 20 = 250) 246 - 20 = 226 bytes

```
void m(string b,string c){if((b+c).Length==60){var a=new int[3];int s=0;for(int i=0;i<30;i++){if(b[i]==c[i]){a[0]++;s+=4;}else if(c[i]==' ')a[2]++;else{a[1]++;s--;}}Console.Write(s+$" ({a[0]} {a[2]} {a[1]})");}else Console.Write("Invalid test");}

```

Readable & ungolfed version:

```
    void m(string b, string c)
    {
        if ((b+c).Length==60)
        {
            var a = new int[3];
            int s = 0;
            for (int i = 0; i < 30; i++)
            {
                if (b[i]==c[i])
                {
                    a[0]++;
                    s+=4;
                }
                else if (c[i] == ' ')a[2]++;
                else
                {
                    a[1]++;
                    s--;
                }
            }
            Console.Write(s+$" ({a[0]} {a[2]} {a[1]})");
        }
        else Console.Write("Invalid test");
    }

```

Really wanted to get the bonus :D
> 1 votes

# Answer
# Prolog, 165 bytes

More than half the bytes are for the invalid tests check.
**Code:**

```
p(X,X,4).
p(_,32,0).
p(_,_,-1).
A*B:-length(A,30),length(B,30),subset(A,`ABCDE`),subset(B,`ABCDE `),maplist(p,A,B,L),sum_list(L,S),write(S);write('Invalid Test').

```

**Explained:**

```
p(X,X,4).                                       % If corresponding elements are equal, 4p
p(_,32,0).                                      % If answer is 'space', 0p
p(_,_,-1).                                      % Else, -1p
A*B:-length(A,30),length(B,30),                 % Check that input is of correct length
     subset(A,`ABCDE`),subset(B,`ABCDE `),      % Check that input has correct characters
     maplist(p,A,B,L),sum_list(L,S),write(S);   % Create a list of scores (L) and print sum
     write('Invalid Test').                     % If anything failed, write Invalid Test

```

**Example:**

```
`CABBDCABECDBACDBEAACADDBBBEDDA`*`CABEDDABDC BACDBBAADE  CBBEDDA`.
73

```

Try it out online here
> 1 votes

# Answer
## MATLAB, 92 90 bytes

Thanks to Tom Carpenter for helping me to reduce my answer by 2 bytes!

```
function c(q,a),if nnz(q)~=30,t='Invalid test';else s=q-a;t=5*nnz(~s)-sum(s<9);end,disp(t)

```

Function can be called by assigning the answer sheet to *q* and the submitted answers to *a*. e.g.:

```
c('CABBDCABECDBACDBEAACADDBBBEDDA','CABEDDABDC BACDBBAADE  CBBEDDA')

```

The answer is simply printed to the screen. **8 bytes** could be saved if it is allowed to print *ans = 73*
> 1 votes

# Answer
# Groovy 2.4.5, 107 bytes

Just a simple translation of the earlier Java answer.

```
f={a,b->a.length()==30&b.length()==30?(0..29).collect{a[it]==b[it]?4:b[it]!=' '?-1:0}.sum():'Invalid test'}

```
> 0 votes

# Answer
# C, 273 - 20 = 253 bytes

```
#include<stdio.h>
#include<string.h>
int main(int c,char**v){char*p=v[1],*q=v[2],*s=" ABCDE",r[]={0,0,0};if(strspn(p,s+1)!=30||p[30]||strspn(q,s)!=30||q[30])puts("Invalid test");else{for(;*p;++q)++r[(*p++!=*q)+(*q==' ')];printf("%d (%dR %dB %dW)",4**r-r[1],*r,r[2],r[1]);}}

```

I've taken the bonus, even though it cost me 23 bytes just to print it. :-(

## Explanation

```
#include <stdio.h>
#include <string.h>
int main(int c,char**v)
{
    char *p=v[1], *q=v[2],      /* arguments */
        *s=" ABCDE",            /* valid chars */
        r[]={0,0,0};            /* results - right, wrong, blank */

    if (strspn(p,s+1) != 30     /* validity check - answer key begins with [A-E]{30} */
        || p[30]                /* and ends there */
        || strspn(q,s) != 30    /* same for answers, but allow space, too */
        || q[30])
    {
        puts("Invalid test");
    } else {
        for ( ;  *p;  ++q)      /* for each answer */
            ++r[(*p++!=*q)+(*q==' ')]; /* increment the appropriate counter */
        printf("%d (%dR %dB %dW)",4**r-r[1],*r,r[2],r[1]); /* print result */
    }
}

```

There's twice as much code to check for invalid input as there is to count the answers - the real meat of the challenge is in the `for` loop near the end. In fact here's a version that assumes the input is always valid, in 163-20 = 143 bytes:

```
#include<stdio.h>
int main(int c,char**v){char*p=v[1],*q=v[2],r[]={0,0,0};for(;*p;++q)++r[(*p++!=*q)+(*q==' ')];printf("%d (%dR %dB %dW)",4**r-r[1],*r,r[2],r[1]);}

```

And one that makes the same assumption and prints only the score, in 133 bytes:

```
#include<stdio.h>
int main(int c,char**v){char*p=v[1],*q=v[2],r[]={4,-1,0};for(c=0;*p;++q)c+=r[(*p++!=*q)+(*q==' ')];printf("%d",c);}

```
> 0 votes

# Answer
## **SAS** 9.4, 291-20 = 271 bytes(with bonus), or 231 bytes(without bonus)

With bonus:

```
data a;k='CABBDCABECDBACDBEAACADDBBBEDDA';r='CABEDDABDC BACDBBAADE  CBBEDDA';c=0;b=0;w=0;if length(k) ne 30 then put "Invalid test";do i=1 to 30;if substr(k,i,1)=substr(r,i,1) then c=c+1;else if substr(r,i,1) =' ' then b=b+1;else w=w+1;end;a=cat(c*4-w,' (',c,'R ',b,'B ',w,'W)');put a;run;

```

Without bonus:

```
data a;k='CABBDCABECDBACDBEAACADDBBBEDDA';r='CABEDDABDC BACDBBAADE  CBBEDDA';c=0;if length(k) ne 30 then put "Invalid test";do i=1 to 30;if substr(k,i,1)=substr(r,i,1) then c=c+4;else if substr(r,i,1)ne' ' then c=c-1;end;put c;run;

```

Sas does not really have an input/output, so you would need to replace the k='..' with the key, and r='..' with the response. The output is printed to the log.
> 0 votes

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


title: Compressed days of the week

text:
# Question
Title: Compressed days of the week
Given an input of a list of days of the week, output the shortest sorted representation of the list.

The format of the input is a string consisting of one or more of the two-character substrings `Su` (Sunday), `Mo` (Monday), `Tu` (etc.), `We`, `Th`, `Fr`, and `Sa`. The input may not necessarily be given in sorted order.

To convert the input to the output format,

* Sort the input by day of week, starting from Sunday (ex. `ThMoSaSuFrTuWe` -\> `SuMoTuWeThFrSa`).
* Reduce the abbreviations down to one letter *if it leaves no ambiguity*. For example, `SuMoTuWe` should become `SMTW` because the first S couldn't possible be Saturday, as that would make the output unsorted (same for the T). However, `ThFrSa` should become `ThFS`, as both Tuesday and Thursday come before Friday and reducing it down to `TFS` would create ambiguity.
* If the output is now `MTWTF`, output `D` instead (which stands for "week**day**s"). Similarly, `SS` should become `E` for week**end**. Finally, `SMTWTFS` should become `A` for **all** days.

The input and output must both be a single string.

Since this is , the shortest code in bytes wins.

Test cases:

```
In              Out    | In              Out
-----------------------|--------------------
SuTu            STu    | SuTuWe          STW
SuTuSa          STuS   | SuWeTh          SWT
TuThSa          TTS    | TuThSu          STT
Su              Su     | Sa              Sa
WeTh            WT     | FrTh            ThF
WeTu            TW     | FrTu            TuF
FrWeMo          MWF    | SaWeSu          SWS
ThTu            TT     | We              W
ThTuMoFrWe      D      | SaSu            E
SuMoWeTuThFr    SMTWTF | ThMoSaSuFrTuWe  A

```

# Answer
# Retina, 152 88

Massively golfed with @Martin's and @randomra's help! Thanks both of you!

```
^
SuMoTuWeThFrSa
([A-Z].)(?!.*\1)

T`l``Su\B|\BSa|o|r|u?We.?.?|uTh
^MTWTF$
D
SS
E
.{7}
A

```

Try it online. A couple of the lines start with `m``  with this online interpreter link. This is so the program works with multiple input lines (to run all tests in one shot). However, multiple input lines is not a requirement, so these are not included above or in my score.
> 6 votes

# Answer
# JavaScript (ES7), ~~187~~ ~~178~~ ~~168~~ ~~157~~ 143 bytes

```
x=>({SMTWTFS:'A',SS:'E',MTWTF:'D'}[x=[for(a of'Su M Tu W Th F Sa'.split` `)if(x.match(a))x.match({S:/.../,T:/W|T.*T/}[b=a[0]])?b:a].join``]||x)

```

The regex tests helped make quick work of the special day rules, and while less than ideal, the object map does it's work. I'm certain I can squeeze a few more out of this though.
> 5 votes

# Answer
# Python 3, 321 Bytes

```
def w(n,a=lambda b,c,d:b.replace(c[0],d).replace(c[1],d)):d=''.join([[o[0],o][o[0]in'ST']for o in['Su','Mo','Tu','We','Th','Fr','Sa']if o in[n[i:i+2]for i in range(0,len(n),2)]]);d=[d,a(d,['Tu','Th'],'T')][('W'in d)+('TuT'in d)];l=len(d);d=[d,a(d,['Su','Sa'],'S')][l>2];return[[[d,'A'][l>8],'E'][d=='SS'],'D'][d=='MTWTF']

```

Test on ideone
> 2 votes

# Answer
# JavaScript (ES6), 197 bytes

```
s=>eval(`n=0;d="SuMoTuWeThFrSa";s.match(/../g).map(t=>n|=1<<d.search(t)/2);o="";for(i=0;i<7;i++)n&1<<i?o+=d.substr(i*2,n<2|n==64|(!(n&8|(n&20)>19)&&i==2|i==4)?2:1):0;n-127?n-62?n-65?o:"E":"D":"A"`)

```

## Explanation

Encodes each day as a bit and stores the input as a number `n`. Bit 0 = Sunday ... bit 6 = Saturday. This allows the ambiguity rule checking code to be a lot shorter due to the bit-wise operations and being able to compare the entire combination with a number that is always less than 128.

```
s=>
  eval(`                   // eval enables the for loop without {} or return
    n=0;                   // n = input encoded as a number
    d="SuMoTuWeThFrSa";    // d = day strings
    s.match(/../g).map(t=> // for each day string t in the input
      n|=1<<d.search(t)/2  // set the bit in n that corresponds to the day
    );
    o="";                  // o = output string
    for(i=0;i<7;i++)       // for each day i from Sunday to Monday
      n&1<<i?              // if the day was in the input
        o+=d.substr(i*2,   // add the day string to the output
          n<2              // Sunday by itself is ambiguous
          |n==64           // Saturday by itself is ambiguous
          |(!(n&8          // Without Wednesday...
            |(n&20)>19     // ...or both Tuesday and Thursday,
            )&&i==2|i==4)  // ...Tuesday or Thursday are ambiguous
          ?2:1             // 2 characters if ambiguous, else 1
        )
      :0;
    n-127?                 // n == 127 = All days (A)
      n-62?                // n == 62 = All week days (D)
        n-65?              // n == 65 = All weekend days (E)
          o                // else output the constructed string
        :"E"
      :"D"
    :"A"
  `)

```

## Test

```
var solution = s=>eval(`n=0;d="SuMoTuWeThFrSa";s.match(/../g).map(t=>n|=1<<d.search(t)/2);o="";for(i=0;i<7;i++)n&1<<i?o+=d.substr(i*2,n<2|n==64|(!(n&8|(n&20)>19)&&i==2|i==4)?2:1):0;n-127?n-62?n-65?o:"E":"D":"A"`)
```

```
<input type="text" id="input" value="FrTh" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
> 2 votes

---
Tags: code-golf
---


title: Stop Internet Warming!

text:
# Question
Title: Stop Internet Warming!
## Task

Write a program that will output another distinct program, and so on, while using as few distinct characters (and as few bytes) as possible.

For example, program 1 should output program 2, and when program 2 is executed, it should output program 3. This can be nested as deeply as needed, but must be at least 3 distinct programs deep.

---

## Rules

* Your program can take no input.
* When the program is executed, the output should be the source of another, different program. This includes the STDERR stream. This can continue as many times as needed, but must occur at least three times.
* The output source code may be in a separate language.

---

## Example

```
$ <program-1>
<program-2>

$ <program-2>
<program-3>

$ <program-3>
<empty>

```

---

## Scoring

Each answer is scored by the following formula:

```
(length_in_bytes * number_of_distinct_characters) / number_of_distinct_programs

```

For example, if your answer was 10 bytes long, contained 5 distinct characters, and output 3 distinct programs, your score would be:

```
(10 * 5) / 3

```

or `16.66`.

Lowest score wins.

---

Note: This challenge was inspired by the comments on this StackOverflow question.

# Answer
> 3 votes
# Vitsy, 8 bytes, 8 distinct character, ∞ programs (score 0)

This is a simple proof in another stack-based language of Mego's comment.

```
'Drd3*Z1
' rd3*Z   Standard quine formula
 D     1  Increase the number of ones every output (output 1 will have 11,
          2: 111, 3: 1111, etc.)
```

# Answer
> 3 votes
# Perl 5 - 34 bytes, 19 distinct characters, 10000000 programs (score 0.0000646)

```
$p="print q{$p}"for 1..1e7;print$p

```

The score can be lowered arbitrarily by increasing the constant `1e7`, at the expense of taking longer and producing larger programs.

---
Tags: code-challenge, code-generation
---


title: Make a Surfin' Word

text:
# Question
Title: Make a Surfin' Word
Your goal is to map a piece of text to a sine curve of the form:

# a sin ( mx - b )

Where *a* and *m* are non-zero rational numbers, *b* is a rational number, and the calculations are in radians.

It doesn't really matter where the origin of your graph is, as long as you fit all the letters in your output. Also, it must be ASCII art, no graphical output.

You can take the equation input in as a string OR you can have a separate input for each parameter: *a*, *m*, and *b*.

Also

### Examples:

Input: "A-well-a", "3sin(x)" or (3,1,0)

Output:

```
 -w
       a

A  e
      -
    l
     l

```

Explanation:

The index of the character is the x-value, and each line represents one y-value. So we take 3sin(x) of the appropriate indices and round them to the nearest integer to get our values:

```
  'A' : 3sin(0) = 0 => (0,0)
  '-' : 3sin(1) = 2.5244 => (1,3)
  'w' : 3sin(2) = 2.7279 => (2,3)
   etc. , to give you the rest of the word.

```

---

Input: "Everybody's", "3.5sin(x-2)" or (3.5,1,2)

Calculations:

> **3.5sin(x-2)**, x = 0,1,2,3,...,10 -3.1815,-2.9435,0,2.9435,3.1815,0.4935,-2.6495,-3.3565,-0.9765,2.2995,3.4615,

Output:

```
   ry     s
         '

  e  b
        y

Ev    od

```

---

Input: "heard", "4sin(2x)" or (4,2,0)

**4sin(2x)** \[0-4\] = 0,3.636,-3.028,-1.116,3.956,

Output:

```
 e  d

h
   r

  a

```

---

Input: "about","-5sin(x+1)" or (-5,1,-1)

**-5sin(x+1)** \[0-4\] : -4.205,-4.545,-0.705,3.785,4.795,

Output:

```
    t
   u

  o

a
 b

```

---

Input: "the word", "-2.4sin(0.5x-1.2)" or (-2.4,0.5,1.2)

**-2.4sin(0.5x-1.2)** \[0-7\] : 2.2368,1.5456,0.4776,-0.7104,-1.7208,-2.3136,-2.3376,-1.7904

Output:

```
th

  e

    word

```

See also

# Answer
> 3 votes
# Dyalog APL, 37 bytes

```
{⍉↑v⌽¨⍵↑¨⍨v←(-∘1-⌈/)⌊.5+⎕×1○⎕-⍨⎕×⍳≢⍵}

```

Takes text as right argument, and then prompts for *m*, *b*, and *a*.

# Answer
> 1 votes
## Python 2, ~~190~~ ~~159~~ 171 bytes

```
import math
a,b,c,d=input()
q=len(a)
s=""
m=int(abs(b)+.5)
for i in range(2*m*q+q):s+=""if i%q else"\n";s+=a[i%q]if i/q==-int(round(b*math.sin(i%q*c-d)))+m else" "    print s

```

Example usage:

```
$ python2 surfin2.py
"about",-5,1,-1

    t
   u

  o

a
 b

```

~~This can probably be golfed further, but I can't see how at the moment. I just wanted to see this question get at least one answer.~~ EDIT: Decently golfed once I saw how to do it in one pass. May have extra leading and trailing lines, but such was expressly allowed: "It doesn't really matter where the origin of your graph is, as long as you fit all the letters in your output."

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


# Question
Title: Paint by Numbers (using programming, not numbers)
Your task is to create a program which takes a black-and-white outlined image (example images are below) and fills it in with colour. It is up to you how you section off each region and which colour to fill it with (you could even use an RNG).

For example:

As you can see I am clearly an artist of a superior calibre when it comes to MS Paint.

---

## Scoring

This is a popularity contest, so the answer with the most net votes wins. Voters are encouraged to judge answers by

* Input criterion: any image that consists of white/light-grey background and black/dark-grey outlines
* How well the colouring is done; meaning few or no areas are white unlike the above (unless you obviously intend to use white e.g. for clouds)
* Customisability of the colours used in certain sections
* How well the system works on a range of different images (of varying detail)
* Post how long your program takes per image. We might not be playing code golf, but shorter, faster and more efficient code should be regarded as better
* Should output the new image either onto the screen or to a file (no larger than 2MB so that it can be shown in the answer)
* Please justify why you chose to output to that image type and comment/explain the workings of your code
* The applicability of the colour used to the respective shape it is bound by (realistic colour scheme i.e. grass is green, wooden fences are brown etc.)
> "I could randomly color each area, but if I could identify the "fence" and make it similarly colored, then that's something that deserves upvotes." - NathanMerrill

Seeing as this *is* a popularity contest, you can also optionally judge by:

* Overall appeal (how good the image looks)
* Artistic flair; if you can program in shading or watercolour-style colouring etc.

**In general, the smallest outputted image (file size) of the highest quality, with the fasted program and the highest public vote will win.**

If you have other judging specifications that you think should be used, please recommend them in the comments of this post.

---

## Examples

*I own nothing; all example images are of a creative commons license.*

Source: https://pixabay.com/ro/stejar-arbore-schi%C5%A3%C4%83-natura-303890/ Source: http://www.freestockphotos.biz/stockphoto/10665 Source: http://crystal-rose1981.deviantart.com/art/Dragon-Tattoo-Outline-167320011 Source: http://jaclynonacloudlines.deviantart.com/art/Gryphon-Lines-PF-273195317 Source: http://captaincyprus.deviantart.com/art/Dragon-OutLine-331748686 Source: http://electric-meat.deviantart.com/art/A-Heroes-Farewell-280271639 Source: http://movillefacepalmplz.deviantart.com/art/Background-The-Pumpkin-Farm-of-Good-old-Days-342865938

---

EDIT: Due to anti-aliasing on lines causing non-black/white pixels and some images that may contain grey instead of black/white, as a bonus challenge you can attempt to deal with it. It should be easy enough in my opinion.

# Answer
> 30 votes
# Spectral airbrushing (Python, PIL, scipy)

This uses a sophisticated mathematical algorithm to produce colourful nonsense. The algorithm is related to Google's PageRank algorithm, but for pixels instead of web pages.

I took this approach because I thought that unlike flood-fill based methods it might be able to cope with images like the chicken and the tree, where there are shapes that aren't entirely enclosed by black lines. As you can see, it sort of works, though it also tends to colour in different parts of the sky in different colours

For the mathematically minded: what it's doing is essentially constructing the adjacency graph of the while pixels in the image, then finding the top 25 eigenvectors of the graph Laplacian. (Except it's not quite that, because we do include the dark pixels, we just give their connections a lower weight. This helps in dealing with antialiasing, and also seems to give better results in general.) Having found the eigenvectors, it creates a random linear combination of them, weighted by their inverse eigenvalues, to form the RGB components of the output image.

In the interests of computation time, the image is scaled down before doing all this, then scaled back up again and then multiplied by the original image. Still, it does not run quickly, taking between about 2 and 10 minutes on my machine, depending on the input image, though for some reason the chicken took 17 minutes.

It might actually be possible to turn this idea into something useful, by making an interactive app where you can control the colour and intensity of each of the eigenvectors. That way you could fade out the ones that divide the sky into different sections, and fade in the ones that pick up on relevant features of the image. But I have no plans to do this myself :)

Here are the output images:

(It didn't work so well on the pumpkins, so I omit that one.)

And here is the code:

```
import sys
from PIL import Image
import numpy as np
import scipy.sparse as sp
import scipy.sparse.linalg as spl
import os
import time

start_time = time.time()

filename = sys.argv[1]
img = Image.open(filename)
orig_w, orig_h = img.size

# convert to monochrome and remove any alpha channel
# (quite a few of the inputs are transparent pngs)
img = img.convert('LA')
pix = img.load()
for x in range(orig_w):
    for y in range(orig_h):
        l, a = pix[x,y]
        l = (255-a) + a*l/255
        a = 255
        pix[x,y] = l,a
img = img.convert('L')

orig_img = img.copy()

# resize to 300 pixels wide - you can get better results by increasing this,
# but it takes ages to run
orig_w, orig_h = img.size
print "original size:", str(orig_w)+ ', ' + str(orig_h)
new_w = 300
img = img.resize((new_w, orig_h*new_w/orig_w), Image.ANTIALIAS)

pix = img.load()
w, h = img.size
print "resizing to", str(w)+', '+str(h)

def coords_to_index(x, y):
    return x*h+y

def index_to_coords(i):
    return (int(i/h), i%h)

print "creating matrix"

A = sp.lil_matrix((w*h,w*h))

def setlink(p1x, p1y, p2x, p2y):
    i = coords_to_index(p1x,p1y)
    j = coords_to_index(p2x,p2y)
    ci = pix[p1x,p1y]/255.
    cj = pix[p2x,p2y]/255.
    if ci*cj > 0.9:
        c = 1
    else:
        c =  0.01
    A[i,j] = c
    return c

for x in range(w):
    for y in range(h):
        d = 0.
        if x>0:
            d += setlink(x,y,x-1,y)
        if x<w-1:
            d += setlink(x,y,x+1,y)
        if y>0:
            d += setlink(x,y,x,y-1)
        if y<h-1:
            d += setlink(x,y,x,y+1)
        i = coords_to_index(x,y)
        A[i,i] = -d

A = A.tocsr()

# the greater this number, the more details it will pick up on. But it increases
# execution time, and after a while increasing it won't make much difference
n_eigs = 25

print "finding eigenvectors (this may take a while)"
L, V = spl.eigsh(A, k=n_eigs, tol=1e-12, which='LA')

print "found eigenvalues", L

out = Image.new("RGB", (w, h), "white")
out_pix = out.load()

print "painting picutre"

V = np.real(V)
n = np.size(V,0)
R = np.zeros(n)
G = np.zeros(n)
B = np.zeros(n)

for k in range(n_eigs-1):
    weight = 1./L[k]
    R = R + V[:,k]*np.random.randn()*weight
    G = G + V[:,k]*np.random.randn()*weight
    B = B + V[:,k]*np.random.randn()*weight

R -= np.min(R)
G -= np.min(G)
B -= np.min(B)
R /= np.max(R)
G /= np.max(G)
B /= np.max(B)

for x in range(w):
    for y in range(h):
        i = coords_to_index(x,y)
        r = R[i]
        g = G[i]
        b = B[i]
        pixval = tuple(int(v*256) for v in (r,g,b))
        out_pix[x,y] = pixval

out = out.resize((orig_w, orig_h), Image.ANTIALIAS)
out_pix = out.load()
orig_pix = orig_img.load()

for x in range(orig_w):
    for y in range(orig_h):
        r,g,b = out_pix[x,y]
        i = orig_pix[x,y]/255.
        out_pix[x,y] = tuple(int(v*i) for v in (r,g,b))

fname, extension = os.path.splitext(filename)
out.save('out_' + fname + '.png')

print("completed in %s seconds" % (time.time() - start_time))

```

# Answer
> 25 votes
# Python 2 + PIL too, my first coloring book

```
import sys, random
from PIL import Image

def is_whitish(color):
    return sum(color)>500

def get_zone(image, point, mask):
    pixels = image.load()
    w, h = image.size
    s = [point]
    while s:
        x, y = current = s.pop()
        mask[current] = 255
        yield current
        s+=[(i,j) for (i,j) in [(x,y-1),(x,y+1),(x-1,y),(x+1,y)] if 0<=i<w and 0<=j<h and mask[i,j]==0 and is_whitish(pixels[i,j])]

def get_zones(image):
    pixels = I.load()
    mask = Image.new('1',image.size).load()
    w,h = image.size
    for y in range(h):
        for x in range(w):
            p = x,y
            if mask[p]==0 and is_whitish(pixels[p]):
                yield get_zone(image, p, mask)

def apply_gradient(image, mincolor, maxcolor, points):
    minx = min([x for x,y in points])
    maxx = max([x for x,y in points])
    miny = min([y for x,y in points])
    maxy = max([y for x,y in points])
    if minx == maxx or miny==maxy:
        return
    diffx, diffy = (maxx - minx), (maxy-miny)
    stepr = (maxcolor[0] - mincolor[0] * 1.0) / diffy
    stepg = (maxcolor[1] - mincolor[1] * 1.0) / diffy
    stepb = (maxcolor[2] - mincolor[2] * 1.0) / diffy
    r,g,b = mincolor
    w, h = (abs(diffx+1),abs(diffy+1))
    tmp = Image.new('RGB', (w,h))
    tmppixels = tmp.load()
    for y in range(h):
        for x in range(w):
            tmppixels[x,y] = int(r), int(g), int(b)
        r+=stepr; g+=stepg; b+=stepb
    pixels = image.load()
    minx, miny = abs(minx), abs(miny)
    for x,y in points:
        try:
        pixels[x,y] = tmppixels[x-minx, y-miny]
    except Exception, e:
            pass

def colors_seq():
   yield (0,255,255)
   c = [(255,0,0),(0,255,0),(0,0,139)]
   i=0
   while True:i%=len(c);yield c[i];i+=1

def colorize(image):
    out = image.copy()
        COLORS = colors_seq()
    counter = 0
    for z in get_zones(image):
        c1 = COLORS.next()
        c2 = (0,0,0) if counter == 0 else (255,255,255)
        if counter % 2 == 1:
            c2, c1 = c1, c2
        apply_gradient(out, c1, c2, list(z))
        counter +=1
    return out

if __name__ == '__main__':
    I = Image.open(sys.argv[-1]).convert('RGB')
    colorize(I).show()

```

I did quite the same as CarpetPython did, except that I fill the region with 'gradients', and use a different color cycle.

My most magnificient colorings :

## Computation times on my machine :

* image 1 (chinese dragon): real 0m2.862s user 0m2.801s sys 0m0.061s
* image 2 (gryffon) : real 0m0.991s user 0m0.963s sys 0m0.029s
* image 3 (unicornish dragon): real 0m2.260s user 0m2.239s sys 0m0.021s

# Answer
> 24 votes
# Python 2 and PIL: Psychedelic Worlds

I have used a simple algorithm to flood fill each white-ish area with a color from a cycling palette. The result is very colorful, but not very lifelike.

Note that the "white" parts in these pictures are not very white. You will need to test for shades of grey too.

Code in Python 2.7:

```
import sys
from PIL import Image

WHITE = 200 * 3
cs = [60, 90, 120, 150, 180]
palette = [(199,199,199)] + [(R,G,B) for R in cs for G in cs for B in cs]

def fill(p, color):
    perim = {p}
    while perim:
        p = perim.pop()
        pix[p] = color
        x,y = p
        for u,v in [(x+dx, y+dy) for dx,dy in [(-1,0), (1,0), (0,1), (0,-1)]]:
            if 0 <= u < W and 0 <= v < H and sum(pix[(u,v)]) >= WHITE:
                perim.add((u,v))

for fname in sys.argv[1:]:
    print 'Processing', fname
    im = Image.open(fname)
    W,H = im.size
    pix = im.load()
    colornum = 0
    for y in range(H):
        for x in range(W):
            if sum(pix[(x,y)]) >= WHITE:
                thiscolor = palette[colornum % len(palette)]
                fill((x,y), thiscolor)
                colornum += 1
    im.save('out_' + fname)

```

Example pictures:

# Answer
> 11 votes
# Matlab

```
function [output_image] = m3(input_file_name)
a=imread(input_file_name);
b=im2bw(a,0.85);
c=bwlabel(b);
h=vision.BlobAnalysis;
h.MaximumCount=10000;
ar=power(double(step(h,b)),0.15);
ar=[ar(1:max(max(c))),0];
f=cat(3,mod((ar(c+(c==0))-min(ar(1:end-1)))/ ...
    (max(ar(1:end-1))-min(ar(1:end-1)))*0.9+0.8,1),c*0+1,c*0+1);
g=hsv2rgb(f);
output_image=g.*cat(3,c~=0,c~=0,c~=0);

```

We use HSV colorspace and choose each regions Hue based on it's relative size between the white regions. The largest region will be blue (`Hue = 0.7`) and the smallest region will be violet (`Hue = 0.8`). The regions between these two sizes are given Hues in the range `0.7 -> 1=0 -> 0.8`. The Hue on the range is linearly selected in respect to the function `area^0.15`. Saturation and Value is always 1 for every non-black pixel.

It takes less then 1 second to color an image.

The 3 pictures with closed regions where the algorithm works decently:

And the rest of the images:

On these images there are big white connected regions which should be ideally colored by multiple colors (this problem was nicely solved in Nathaniel's solution.

# Answer
> 8 votes
## Python 3 with Pillow

The code is a bit long to include in this answer, but here's the gist of it.

1. Take the input image and, if it has an alpha channel, composite it onto a white background. (Necessary at least for the chicken image, because that entire image was black, distinguished only by transparency, so simply dropping the alpha was not helpful.)
2. Convert the result to greyscale; we don't want compression or anti-aliasing artifacts, or grey-lines-that-aren't-quite-grey, to mess us up.
3. Create a bi-level (black and white) copy of the result. Shades of grey are converted to black or white based on a configurable cutoff threshold between white and the darkest shade in the image.
4. Flood-fill every white region of the image. Colours are chosen at random, using a selectable palette that takes into account the location of the starting point for the flood-fill operation.
5. Fill in the black lines with their nearest-neighbour colours. This helps us reintroduce anti-aliasing, by keeping every coloured region from being bordered in jaggy black.
6. Take the greyscale image from step 2 and make an alpha mask from it: the darkest colour is fully opaque, the lightest colour is fully transparent.
7. Composite the greyscale image onto the coloured image from step 5 using this alpha mask.

Those last few steps, unfortunately, have still not eliminated lighter "halos" that are visible in darker-coloured regions, but they've made a noticeable difference, at least. Image processing was never my field of study, so for all I know there are more successful and more efficient algorithms to do what I tried to do here... but oh well.

So far, there are only two selectable palettes for step 4: a purely random one, and a very rough "natural" one, which tries to assign sky colours to the upper corners, grass colours to the lower corners, brown (rocks or wood) colours to the middle of each side, and varied colours down the centre. Success has been... limited.

---

### Usage:

```
usage: paint_by_prog.py [-h] [-p PALETTE] [-t THRESHOLD] [-f | -F] [-d]
                        FILE [FILE ...]

Paint one or more line-art images.

positional arguments:
  FILE                  one or more image filenames

optional arguments:
  -h, --help            show this help message and exit
  -p PALETTE, --palette PALETTE
                        a palette from which to choose colours; one of
                        "random" (the default) or "natural"
  -t THRESHOLD, --threshold THRESHOLD
                        the lightness threshold between outlines and paintable
                        areas (a proportion from 0 to 1)
  -f, --proper-fill     fill under black lines with proper nearest-neighbour
                        searching (slow)
  -F, ---no-proper-fill
                        fill under black lines with approximate nearest-
                        neighbour searching (fast)
  -d, --debug           output debugging information

```

---

### Samples:

`paint_by_prog.py -t 0.7 Gryphon-Lines.png`

`paint_by_prog.py Dragon-Tattoo-Outline.jpg`

`paint_by_prog.py -t 0.85 -p natural The-Pumpkin-Farm-of-Good-old-Days.jpg`

`paint_by_prog.py -t 0.7 Dragon-OutLine.jpg`

`paint_by_prog.py stejar-arbore-schiţă-natura.png`

The chicken doesn't look very good, and my most recent result for the Link image isn't the best; one that came from an earlier version of the code was largely pale yellow, and had an interesting desert vibe about it...

---

### Performance:

Each image takes a couple of seconds to process with default settings, which means an approximate nearest-neighbour algorithm is used for step 5. True nearest-neighbour is significantly slower, taking maybe half a minute (I haven't actually timed it).

# Answer
> 3 votes
# Java

Random color selection from your choice of pallette.

Warning: Region finding currently very slow, unless the white regions are unusually small.

```
import java.awt.Color;
import java.awt.image.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Random;
import java.util.Scanner;
import java.util.function.Supplier;

import javax.imageio.ImageIO;

public class Colorer{
    public static boolean isProbablyWhite(int x,int y){
        Color c=new Color(image.getRGB(x, y));
        if(c.getRed()<240)return false;
        if(c.getBlue()<240)return false;
        if(c.getGreen()<240)return false;
        return true;
    }
    static class Point{
        int x,y;
        public boolean equals(Object o){
            if(o instanceof Point){
                Point p=(Point)o;
                return x==p.x&&y==p.y;
            }
            return false;
        }
        public Point(int x,int y){
            this.x=x;
            this.y=y;
        }
    }
    static BufferedImage image;
    static int W,H;
    public static void check(Point p,List<Point>l1,List<Point>l2,List<Point>l3){
        if(!isProbablyWhite(p.x,p.y))return;
        if(l1.contains(p))return;
        if(l2.contains(p))return;
        if(l3.contains(p))return;
        l1.add(p);
    }
    public static void process(int x,int y,Color c){
        List<Point>plist=new LinkedList<>();
        int rgb=c.getRGB();
        plist.add(new Point(x,y));
        List<Point>l3=new LinkedList<>();
        int k=0;
        for(int i=0;i<W*H;i++){
            System.out.println(k=l3.size());
            List<Point>l2=new LinkedList<>();
            for(Point p:plist){
                int x1=p.x;
                int y1=p.y;
                if(x1>0){
                    check(new Point(x1-1,y1),l2,plist,l3);
                }
                if(y1>0){
                    check(new Point(x1,y1-1),l2,plist,l3);
                }
                if(x1<W-1){
                    check(new Point(x1+1,y1),l2,plist,l3);
                }
                if(y1<H-1){
                    check(new Point(x1,y1+1),l2,plist,l3);
                }
            }
            while(!plist.isEmpty()){
                l3.add(plist.remove(0));
            }
            if(l3.size()==k)break;
            plist=l2;
        }
        plist=l3;
        for(Point p:plist){
            image.setRGB(p.x,p.y,rgb);
        }
    }
    public static void main(String[]args) throws Exception{
        Random rand=new Random();
        List<Supplier<Color>>colgen=new ArrayList<>();
        colgen.add(()->{return new Color(rand.nextInt(20),50+rand.nextInt(200),70+rand.nextInt(180));});
        colgen.add(()->{return new Color(rand.nextInt(20),rand.nextInt(40),70+rand.nextInt(180));});
        colgen.add(()->{return new Color(150+rand.nextInt(90),10+rand.nextInt(120),rand.nextInt(5));});
        colgen.add(()->{int r=rand.nextInt(200);return new Color(r,r,r);});
        colgen.add(()->{return Arrays.asList(new Color(255,0,0),new Color(0,255,0),new Color(0,0,255)).get(rand.nextInt(3));});
        colgen.add(()->{return Arrays.asList(new Color(156,189,15),new Color(140,173,15),new Color(48,98,48),new Color(15,56,15)).get(rand.nextInt(4));});
        Scanner in=new Scanner(System.in);
        image=ImageIO.read(new File(in.nextLine()));
        final Supplier<Color>sup=colgen.get(in.nextInt());
        W=image.getWidth();
        H=image.getHeight();
        for(int x=0;x<W;x++){
            for(int y=0;y<H;y++){
                if(isProbablyWhite(x,y))process(x,y,sup.get());
            }
        }
        ImageIO.write(image,"png",new File("out.png"));
    }
}

```

Requires two inputs: the filename, and the palette ID. Includes some antialiasing correction, but does not include logic for transparent pixels.

The following palettes are currently recognized:

```
0: Blue and greeen
1: Blue
2: Red
3: Greyscale
4: Three-color Red, Green, and Blue
5: Classic Game Boy pallette (four shades of green)

```

# Results:

Dragon, Game Boy palette:

The other dragon, blue + green palette:

GOL still life mona lisa (as rendered by this program), tricolor palette:

---
Tags: popularity-contest, graphical-output, image-processing
---


title: Lego gear ratios

text:
# Question
Title: Lego gear ratios
I'm building a giant lego robot and I need to generate some particular gear ratios using a set of gears. I have lots of gears with the common lego gear sizes: 8, 16, 24, or 40 teeth. Write a program I can use where I input a gearing ratio and the program tells me what combination of gears I should use to get the requested ratio.

The input ratio will be specified on standard input (or your language's equivalent) with two integers separated by a colon. A ratio of `a:b` means that the output shaft should turn `a/b` times as fast as the input shaft.

The output to standard output should be a single line containing a space-separated list of gear ratios, in the form of `x:y` where `x` is the size of the gear on the input shaft and `y` is the size of the gear on the output shaft. You must use the minimum possible number of gears for the given ratio. Each `x` and `y` must be one of `8,16,24,40`.

examples:

```
1:5 -> 8:40
10:1 -> 40:8 16:8
9:4 -> 24:16 24:16
7:1 -> IMPOSSIBLE
7:7 ->
6:15 -> 16:40

```

If the desired gear ratio is impossible, print "IMPOSSIBLE". If no gears are required, print the empty string.

This is code golf, shortest answer wins.

# Answer
# Python - 204

Ok, I'll go first:

```
def p(n,a=[1]*9):
 n=int(n)
 for i in(2,3,5):
    while n%i<1:n/=i;a=[i]+a
 return a,n
(x,i),(y,j)=map(p,raw_input().split(':'))
print[' '.join(`a*8`+':'+`b*8`for a,b in zip(x,y)if a!=b),'IMPOSSIBLE'][i!=j]

```
edit:

To 'optimize' the output, this can be added before the `print` statement,

```
for e in x:
 if e in y:x.remove(e);y.remove(e)

```

bringing the total up to **266 characters**, I believe.
> 4 votes

# Answer
# Perl - 310 306 294 288 272

I'm a little rusty with perl and never did a code-golf... but no excuses. Char-count is without line-breaks. Using perl v5.14.2 .

```
($v,$n)=<>=~/(.+):(.+)/;
($x,$y)=($v,$n);($x,$y)=($y,$x%$y)while$y;
sub f{$p=shift;$p/=$x;for(5,3,2){
while(!($p%$_)){$p/=$_;push@_,$_*8}}
$o="IMPOSSIBLE"if$p!=1;
@_}
@a=f($v);@b=f($n);
if(!$o){for(0..($#b>$#a?$#b:$#a)){
$a[$_]||=8;
$b[$_]||=8;
push@_,"$a[$_]:$b[$_]"}}
print"$o@_\n"

```

I'm looking forward to critics and hints. It's not so easy to find tips and tricks for code-golf (in perl).
> 4 votes

# Answer
# C, 246 216 213 bytes

In a (futile) attempt to beat my own Prolog solution, I completely rewrote the C solution.

```
b,c,d;f(a,b,p){while(c=a%5?a%3?a%2?1:2:3:5,d=b%5?b%3?b%2?1:2:3:5,c*d>1)c<2|b%c?d<2|a%d?p&&printf("%d:%d ",8*c,8*d):(c=d):(d=c),a/=c,b/=d;c=a-b;}main(a){scanf("%d:%d",&a,&b);f(a,b,0);c?puts("IMPOSSIBLE"):f(a,b,1);}

```

My original C solution (246 bytes):

```
#define f(c,d) for(;a%d<1;a/=d)c++;for(;b%d<1;b/=d)c--;
b,x,y,z;main(a){scanf("%d:%d",&a,&b);f(x,2)f(y,3)f(z,5)if(a-b)puts("IMPOSSIBLE");else
while((a=x>0?--x,2:y>0?--y,3:z>0?--z,5:1)-(b=x<0?++x,2:y<0?++y,3:z<0?++z,5:1))printf("%d:%d ",a*8,b*8);}

```

It was a nice exercise to prove it can be done without building lists.
> 2 votes

# Answer
# swi-prolog, 324 250 248 204 bytes

Prolog does pretty well at solving a problem like this.

```
m(P):-(g(P,L),!;L='IMPOSSIBLE'),write(L).
g(A:A,''):-!.
g(A:B,L):-A/C/X,C>1,B/C/Y,!,g(X:Y,L);A/C/X,!,B/D/Y,C*D>1,g(X:Y,T),format(atom(L),'~D:~D ~a',[C*8,D*8,T]).
X/Y/Z:-(Y=5;Y=3;Y=2;Y=1),Z is X//Y,Y*Z>=X.

```

Input is passed as a term parameter to predicate `m`. Output is written to stdout. Sorry about the trailing 'true'; that's just the interpreter's way of letting me know everything was fine.

```
?- m(54:20).
24:40 24:16 24:8
true.

?- m(7:7).
true.

?- m(7:1).
IMPOSSIBLE
true.

```
> 2 votes

# Answer
## Pyth, 101 bytes

```
D'HJH=Y[)VP30W!%JN=/JN=Y+NY))R,YJ;IneKhm'vdcz\:J"IMPOSSIBLE").?V.t,.-Y.-hK=J.-hKYJ1In.*Npj\:m*8d_Np\

```

An implementation of @daniero' python answer but semi-optimised for Pyth.

```
D'H                               - Define a function (') which takes an argument, H.
   JH                             - J = H (H can't be changed in the function)
     =Y[)                         - Y = []
         V                        - For N in ...
          P30                     - Prime factors of 30 (2,3,5)
             W!%JN                - While not J%N
                  =/JN            - J /= N
                      =Y+NY       - Y = N + Y
                           ))R,YJ - To start of function, return [Y,J]

ENDFUNCTION

If
         cz\:  - Split the input by the ':'
     m'vd      - ['(eval(d)) for d in ^]
   Kh          - Set K to the first element of the map (before the :)
  e            - The second returned value
             J - The second returned value after the : (The variables are globals)
 n             - Are not equal

Then
"IMPOSSIBLE" - Print "IMPOSSIBLE"

Else
V                                      - For N in
 .t                1                   - transpose, padded with 1's
             .-hKY                     - 1st function first return - 2nd function first return
           =J                          - Set this to J
       .-hK                            - 1st function first return - ^
    .-Y                                - 2nd function first return - ^
   ,              J                    - [^, J]
                                         (Effectively XOR the 2 lists with each other)
                    I                  - If
                     n.*N              - __ne__(*N) (if n[0]!=n[1])
                         pj\:m*8d_N    - print ":".join([`d*8` for d in reversed(N)])
                                   p\  - print a space seperator

```

Try it here

Or test every case
> 2 votes

# Answer
## ES6, 230 bytes

```
x=>([a,b]=x.split`:`,f=(x,y)=>y?f(y,x%y):x,g=f(a,b),d=[],a/=g,f=x=>{while(!(a%x))a/=x,d.push(x*8)},[5,3,2].map(f),c=d,d=[],a*=b/g,[5,3,2].map(f),a>1?'IMPOSSIBLE':(c.length<d.length?d:c).map((_,i)=>(c[i]||8)+':'+(d[i]||8)).join` `)

```

One of my longest golfs, so I must have done something wrong... Ungolfed:

```
x => {
    [a, b] = x.split(":");
    f = (x, y) => y ? f(y, x % y) : x; // GCD
    g = f(a, b);
    f = x => {
        r = [];
        while (!(x % 5)) { x /= 5; r.push(5); }
        while (!(x % 3)) { x /= 3; r.push(3); }
        while (!(x % 2)) { x /= 2; r.push(2); }
        if (x > 1) throw "IMPOSSIBLE!";
        return r;
    }
    c = f(a);
    d = f(b);
    r = [];
    for (i = 0; c[i] || d[i]; i++) {
        if (!c[i]) c[i] = 8;
        if (!d[i]) d[i] = 8;
        r[i] = c[i] + ":" + d[i];
    }
    return r.join(" ");
}

```
> 0 votes

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


title: Finite State Machine validity

text:
# Question
Title: Finite State Machine validity
I've been around for a while, watching you golf and I really enjoy it. I came up with a challenge for you all so let's begin!

# Challenge

*I assume that everyone knows what Finite State Machine (FSM) is, I will edit the the description if needed.*

* Your program will take only one input consisting in a string that represents a FSM.
* The first character of the input is the FSM's initial state and the last character is the FSM's final state.
* Transitions are represented as two consecutive characters (`AB` will be the transition from state A to state B. `ABCD` will be the two transitions `A to B` and `C to D`)
* In this challenge, the FSM is considered valid when you have at least one path from the initial state to the final state.

# Goal

Output a truthy value, telling the world if the input is a valid FSM (any equivalent for `True` of `False` is fine)

### Bonus

* **-20%** if you add all the sequences of valid paths to the output

# Examples

`AB` should output (with bonus) `true AB`

`ABC` should output `false` (No transition to state C)

`ABCEBD` should output (with bonus) `true ABD` (The presence of unreachable states C and E doesn't make it false)

`ISSTSFTF` should output (with bonus) `true ISF ISTF`

`ABACBCCD` should output (with bonus) `true ACD ABCD`

`ABACBCD` should output `false`

`ABACADCDBCDEBE` should output (with bonus) `true ABE ADE ACDE ABCDE`

# Final word

If you think this challenge lacks something, please tell me, I'd really like to see the answers you can come up with

# Answer
> 3 votes
# JavaScript (ES6), 81 bytes

```
s=>(a=[...s]).map(_=>a.map((m,i)=>p=i%2&r[s[i-1]]?r[m]=1:r[m]),r={},r[s[0]]=1)&&p

```

## Explanation

Takes the states as a string and returns a `1` for true or `undefined` for false. This method was the shortest I could find, but it means that it's impossible to include the bonus because it just determines reachability, not the paths.

```
s=>
  (a=[...s])        // a = states as an array
  .map(_=>          // loop a number of times to ensure all states have been reached
    a.map((m,i)=>   // for each state m at index i
      p=            // p = the reachability of the final state
        i%2         // if this is the last state of a pair
        &r[s[i-1]]? // and the first state is reachable
          r[m]=1    // set the last state and p to reachable
          :r[m]     // else set p to the reachability of the state
    ),
    r={},           // map of truthy values for reachable states
    r[s[0]]=1       // set the initial state to reachable
  )
  &&p               // return the final result

```

## Test

```
var solution = s=>(a=[...s]).map(_=>a.map((m,i)=>p=i%2&r[s[i-1]]?r[m]=1:r[m]),r={},r[s[0]]=1)&&p
```

```
<input type="text" id="input" value="ABACADCDBCDEBE" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```

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


# Question
Title: Triangular Grids: Simply Connected Polyiamonds
While we're on a triangular grids kick, I'd like to point out that there is an equivalent to polyominoes on a triangular grid. They are called polyiamonds, and they are shapes formed by gluing equilateral triangles together along their edges. In this challenge you are going to be deciding which subsets of a triangular grid are polyiamonds, and whether they have holes in them. Because it only takes 9 triangles to make a polyiamond with a hole in it, your code needs to be as short as possible.

### The grid

We'll use Martin's triangular grid layout for the input:

Pay attention to the fact that the centers of the triangles form a roughly rectangular grid and that the top left triangle "points" upward. We can describe a subset of this grid, then, by giving a rectangular "star map" indicating which triangles are included and which are not included. For instance, this map:

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

```

corresponds to the smallest polyiamond which contains a hole:

### Holes

A polyiamond which contains a hole like the example above (a region not a part of the polyiamond, which is surrounded on all sides by regions which *are*) is not, topologically speaking, *simply connected*.

### The Challenge

Write a function or program which takes as input a "star map" as described above and output a truthy if and only if the indicated subset of the triangular grid is a *simply connected polyiamond*.

### More Examples

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

```

corresponds to the polyiamond

which is simply connected.

---

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

```

corresponds to the polyiamond

which is simply connected.

---

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

```

corresponds to the *non*-polyiamond

which would not be simply connected even if it *were* a polyiamond.

### Input Spec

* The input will consist only of asterisks, spaces, and line feeds.
* The first character of input will always be a space or asterisk (corresponding to the upward pointing triangle in the top left corner of the grid).
* There will always be at least one asterisk on the first and last lines.
* There is NO guarantee that lines after the first line won't be empty. Two linefeeds in a row may appear in a legitimate input.
* Line lengths need not all be the same.

### Winning Condition

This is , so shortest answer in bytes wins.

### Test Cases

Truthy maps:

```
1) *

2) *
   *

3) **

4) *** ***
   *******

5) *   *
   ** **
    ***

6) *
   **
    *

7)    **
     ***
   ****

8) ****
   **   *
    *****

9) ***********
   **    **  **
    ****  **  **
              **
   ************

```

Falsy maps:

```
1) *
   *
   *

2) * *

3) *
    *

4)  **
   **

5) ***

   ***

6) ** **
   *****

7) **  **
   *** **
    ****

8)  *
    *

9) *****
   **   *
    *****

```

# Answer
> 4 votes
# Snails, 95 bytes

```
F&
lr|=((ul.)2 ,l~a~)d|!((ul.)2 ,l~a~)u}\*}+l\ ,~a~|{\ (lr|=((ul.)2 ,l~a~)d|!((ul.)2 ,l~a~)u}+~

```

This really suffered from duplication, as I haven't implemented macros or any kind of back-reference. What it does is to check that for each star, there exists a path to the leftmost star on the top line; and for each space, there is a path to an edge of the grid.

```
F&                         ,, option F: pad lines with spaces to the length of the longest
                           ,, option &: print 1 iff match succeeds from every cell
lr                         ,, direction left or right, or
      | =((ul.)2 ,l~a~) d  ,, direction down, if we are an even number of orthogonal moves from the top left
      | !((ul.)2 ,l~a~) u  ,, or, direction up if we are odd number of moves from the top left
    }  \*                  ,, literal '*'
}+                         ,, 1 or more times
l\ ,~a~                    ,, check that we are on the leftmost * in the top line

|                          ,, the part before this is for starting on '*'; part after for starting on ' '

{ \                        ,, literal ' '
    (   lr                 ,, direction left or right, or
      | =((ul.)2 ,l~a~) d  ,, same drill as before...
      | !((ul.)2 ,l~a~) u
}+                         ,, 1 or more times
~                          ,, end on an out of bounds cell

```

# Answer
> 3 votes
## CJam, ~~101~~ 98 bytes

```
qN/_z,f{' e]}{S2*f+W%z}4*:eeee::f+:~{_(aL{+_{_2,.+1$2,.-@_:+1&!2*(a.+}%2${a1$&},\;@1$-@@}h;\;-}2*!

```

Try it online.

I finally overcame my fear of implementing a flood fill in CJam. It's about as ugly as I expected, and it can most definitely be golfed.

The general idea is to perform two flood-fills (which are actually implemented as removals from the list of unvisited cells). The first pass will remove all spaces that are reachable from the edge. The second pass will then pick the first `*` in reading order and remove all the triangles reachable from that. If and only if the resulting list is empty, the polyiamond was simply connected:

* If the polyiamond had a hole, the first flood fill is unable to reach and remove that hole.
* If the input consists of several disconnected polyiamonds, the second flood fill is unable to reach and remove all of them.

---
Tags: code-golf, hexagonal-grid
---


title: Nested Header List

text:
# Question
Title: Nested Header List
The goal of this challenge is to complete a list of consecutive nested header numbers when given a start and an end. When given `1.1.1` and `1.1.5` you should generate `1.1.1, 1.1.2, 1.1.3, 1.1.4, 1.1.5`

**Specific Rules**

1. Your entry must take in a `start`, `end`, and multiple optional `range` parameters. Parameters can be taken form STDIN (or nearest equivalent) or a file.
2. Your entry may assume valid input
3. Input will be of the following format:
    1. `start` and `end` will be strings of `.` delimited integers of the same length
    2. `start` and `end` will have three segments; (1) set values, (2) iterator, (3) trailing values.
        * The iterator is the first value which differs between `start` and `end`.
        * The set values are the values before the iterator. These values never change
        * The trailing values are the values after the iterator. These values iterate up as determined by the `range` parameter(s). **All trailing values in `start` and `end` will be `1`**.
    3. `range` will be a list of integers or strings (depending on which you prefer) with a length corresponding to the number of trailing values. When there are no trailing values, `range` is not specified. The value of `range` corresponding to each trailing value determines the *inclusive upper bound* which that entry iterates to.
4. Output will be to STDOUT (or closest alternative) and will show each value separated by at least one delimiter. Delimiter can by any character or string of characters, but it must be consistent. Output must be sorted correctly

**Examples**

```
start = '1.1.5.1', end = '1.1.6.1', range = [5]
Output: 1.1.5.1, 1.1.5.2, 1.1.5.3, 1.1.5.4, 1.1.5.5, 1.1.6.1
                                                  ^
                                                  previous value is iterated
                                                  only when iterating value
                                                  limit set by range

start = '1.1.5.1', end = '1.1.7.1', range = [5]
Output: 1.1.5.1, 1.1.5.2, 1.1.5.3, 1.1.5.4, 1.1.5.5, 1.1.6.1,
        1.1.6.2, 1.1.6.3, 1.1.6.4, 1.1.6.5, 1.1.7.1

start = '1.5.1.1', end = '1.6.1.1', range = [5,2]
Output: 1.5.1.1, 1.5.1.2, 1.5.2.1, 1.5.2.2, 1.5.3.1, 1.5.3.2,
        1.5.4.1, 1.5.4.2, 1.5.5.1, 1.5.5.2, 1.6.1.1

```

This is code golf so shortest code by bytes wins. Standard loopholes apply.

**Bonuses**

1. Allow trailing values to be values other than `1` in `end` parameter - **12.5% off**
2. Handle incorrect number of values in `range` parameter - **12.5% off**
3. Handle `end` less than `start` by producing list in reverse - **50% off**

Bonuses are calculated off of the original byte count; a 100 byte answer which receives all bonuses will have a final score of `100 bytes - 100*(0.125+0.125+0.5) = 25 bytes`

# Answer
## Haskell, ~~201~~ ~~194~~ 188\*0.25 = 47 bytes

```
import Data.Lists
l=length
p x=read<$>splitOn"."x
(s#e)r=intercalate".".map show<$>(fst$span(<=e)$sequence$zipWith enumFromTo s$take(l e-l r)e++r)
s!e|s<e=s#e|1<2=reverse.(e#s)
(.p).(!).p

```

I'm going for all bonuses.

"Normal" use:

```
*Main> ((.p).(!).p) "1.5.1.1" "1.6.1.1" [5,2]
["1.5.1.1","1.5.1.2","1.5.2.1","1.5.2.2","1.5.3.1","1.5.3.2","1.5.4.1",
"1.5.4.2","1.5.5.1","1.5.5.2","1.6.1.1"]

```

Bonus 1:

```
*Main> ((.p).(!).p) "1.5.1.1" "1.6.4.1" [5,2]
["1.5.1.1","1.5.1.2","1.5.2.1","1.5.2.2","1.5.3.1","1.5.3.2","1.5.4.1",
 "1.5.4.2","1.5.5.1","1.5.5.2","1.6.1.1","1.6.1.2","1.6.2.1","1.6.2.2",
 "1.6.3.1","1.6.3.2","1.6.4.1"]

```

Bonus 2:

```
*Main> ((.p).(!).p) "1.5.1.1" "1.6.1.1" [3]
["1.5.1.1","1.5.1.2","1.5.1.3","1.6.1.1"]

```

Bonus 3:

```
*Main> ((.p).(!).p) "1.6.1.1" "1.5.1.1" [5,2]
["1.6.1.1","1.5.5.2","1.5.5.1","1.5.4.2","1.5.4.1","1.5.3.2","1.5.3.1",
 "1.5.2.2","1.5.2.1","1.5.1.2","1.5.1.1"]

```

How it works:

Split `start` and `end` into lists of numbers, e.g. `"1.5.1.1"` -\> `[1,5,1,1]`. Prepend elements from `end` to `range` so that the resulting list has the same length as `end`, e.g. `[5,2]` and `"1.6.1.1"` -\> `[1,6,5,2]`. Zip this list and `start` with the list building function `enumFromTo`, e.g. `[1,5,1,1]` and `[1,6,5,2]`-\> `[[1],[5,6],[1,2,3,4,5],[1,2]]`. `sequence` builds all combinations thereof, where numbers at position i are drawn from sublist i, -\> `[[1,5,1,1],[1,5,1,2],[1,5,2,1],[1,5,2,2],...]`. Re-insert the dots and take elements as long as the they are less or equal than `end`.
> 3 votes

# Answer
# PowerShell, 214 bytes, no bonuses :(

```
param($s,$e,$r)
$f={param($v,$w)if($w){$w[0]|%{&$f "$v.$_" $w[1..$w.Count]}}else{$v;if($v-eq$e){break}}}
$x,$y=($s-split'\.'|diff $e.split('.')).inputobject
$q=,($x..$y)
$r|%{$q+=,(1..$_)}
&$f ($s-split".$x")[0] $q

```

e.g.

```
PS C:\Scripts> .\nestedh.ps1 '1.5.1.1' '1.6.1.1' @(5,2)
1.5.1.1
1.5.1.2
1.5.2.1
1.5.2.2
1.5.3.1
1.5.3.2
1.5.4.1
1.5.4.2
1.5.5.1
1.5.5.2
1.6.1.1

```

It:

* Uses `-split '\.'` feeding to `diff/Compare-Object` to find the two differing numbers, (this approach blocks the bonus where the tail values can change, because it changes the diff output).
* Builds an array of the ranges it will need for each header position, taking from the range parameters.This leaves something like `"$q=[[5,6], [1,2,3,4,5], [1,2]]"`
* Those get fed into the recursive function `$f` which takes the set values prefix and a list of sublists, adds the prefix to each number, and calls itself with that as the new prefix, and the remaining sublists
* quits when it hits the `$end` string
> 1 votes

---
Tags: code-golf
---


title: Calculate the Number, Divisors Edition

text:
# Question
Title: Calculate the Number, Divisors Edition
*Inspired by this question over on Math.*

Let the prime factorization of a number, *n*, be represented as: \\$P(n) = 2^a\times3^b\times5^c\times\cdots\\$. Then the number of divisors of *n* can be represented as \\$D(n) = (a+1)\times(b+1)\times(c+1)\times\cdots\\$. Thus, we can easily say that the number of divisors of \\$2n\\$ is \\$D(2n) = (a+2)\times(b+1)\times(c+1)\times\cdots\\$,
the number of divisors of \\$3n\\$ is \\$D(3n) = (a+1)\times(b+2)\times(c+1)\times\cdots\\$,
and so on.

### Challenge

Write a program or function that uses these properties to calculate \\$n\\$, given certain divisor inputs.

### Input

A set of integers, let's call them \\$w, x, y, z\\$, with all of the following definitions:

* all inputs are greater than 1 -- \\$w, x, y, z \> 1\\$
* \\$x\\$ and \\$z\\$ are distinct -- \\$x\ne z\\$
* \\$x\\$ and \\$z\\$ are prime -- \\$P(x)=x, D(x)=2, P(z)=z \text{ and } D(z)=2\\$
* \\$w\\$ is the number of divisors of \\$xn\\$ -- \\$D(xn)=w\\$
* \\$y\\$ is the number of divisors of \\$zn\\$ -- \\$D(zn)=y\\$

For the problem given in the linked question, an input example could be \\$(28, 2, 30, 3)\\$. This translates to \\$D(2n)=28\\$ and \\$D(3n)=30\\$, with \\$n=864\\$.

### Output

A single integer, \\$n\\$, that satisfies the above definitions and input restrictions. If multiple numbers fit the definitions, output the smallest. If no such integer is possible, output a falsey value.

### Examples:

```
(w, x, y, z) => output

(28, 2, 30, 3) => 864
(4, 2, 4, 5) => 3
(12, 5, 12, 23) => 12
(14, 3, 20, 7) => 0 (or some other falsey value)
(45, 13, 60, 11) => 1872
(45, 29, 60, 53) => 4176

```

### Rules:

* Standard code-golf rules and loophole restrictions apply.
* Standard input/output rules apply.
* Input numbers can be in any order - please specify in your answer which order you're using.
* Input numbers can be in any suitable format: space-separated, an array, separate function or command-line arguments, etc. - your choice.
* Similarly, if output to STDOUT, surrounding whitespace, trailing newline, etc. are all optional.
* *Input parsing and output formatting are not the interesting features of this challenge.*
* In the interests of sane complexity and integer overflows, the challenge number \\$n\\$ will have restrictions such that \\$1 \< n \< 100000\\$ -- i.e., you don't need to worry about possible answers outside this range.

### Related

# Answer
> 3 votes
# Jelly, ~~17~~ 16 bytes

```
×€ȷ5R¤ÆDL€€Z=Ḅi3

```

This is a brute force solution that tries all possible values up to 100,000. Try it online!

### Non-competing version

The latest version of Jelly has a bug fix that allows to golf down the above code to **15 bytes**.

```
ȷ5R×€³ÆDL€€=Ḅi3

```

Try it online!

### How it works

```
×€ȷ5R¤ÆDL€€Z=Ḅi3  Main link. Left input: x,z. Right input: w,y

     ¤            Combine the two atoms to the left into a niladic chain.
  ȷ5              Yield 100,000 (1e5).
    R             Apply range. Yields [1, ..., 100,000].
x€                Multiply each r in the range by x and z.
                  This yields [[x, ..., 100,000x], [z, ..., 100,000z]].
      ÆD          Compute the divisors of each resulting integer.
        L€€       Apply length to each list of divisors.
                  This counts the divisors of each integer in the 2D array.
           Z      Zip; group the divisors of kx and kz in pairs.
            =     Compare each [divisors(kx), divisors(kz)] with [w, y].
                  This yields a pair of Booleans.
             Ḅ    Convert each Boolean pair from binary to integer.
              i3  Find the first index of 3. Yields 0 for not found.

```

---
Tags: code-golf, math, number-theory
---


title: Attraction Between Words

text:
# Question
Title: Attraction Between Words
Newton's theory of gravitation says that the gravitational force between two point masses is

# F=(Gm1m2)/ r2

Where

* *G* is the gravitational constant: 6.674×10−11 N · (m/kg)2
* *m1* is the mass of the first object
* *m2* is the mass of the second object
* *r* is the distance between their centers of mass

## Challenge

You need to simulate the pull between two words. Each lowercase letter has mass given by its position in the alphabet. Capital letters have twice the mass of their lowercase counterparts! You will be given a string containing two words separated by several spaces, as well as a positive integer number of seconds, *s*. Output what the string would look like after *s* seconds.

## Info

* Because words are abstract they have a different set of units and constants
    + Mass: **WMU** (Word Mass Unit) - equal to the mass of the letter 'a'.
    + Distance: **em**, the length of one character.
    + Force: **NW** (Word Newton) = WMU · em/s2
    + Gravitational Constant: **G** = 1 Nw · (em/WMU)2
* The first character corresponds to the position 0 on the x-axis.
* All calculations should be done with as much precision as possible, only at the end do you round to the nearest em.
* You do not need to use calculus, you just need to recalculate the *F* every second, automatically apply the new acceleration to the velocity, and after a second apply the velocity to the position (see example).
* Once two words collide with each other (like  `catdog` ), they don't move any further.

## Center of Mass

The center of mass of a word can be found with the formula:

Where *M* is the total mass of the word, *mi* is the mass of a letter, and *ri* is the position of the letter.

## Example:

**(Note: Although this example doesn't show it, remember that capital letters have twice the mass of their lowercase counterparts.)**

Input: `cat dog`, 2

1. First what are the positions of each word? "cat" starts at position 0 and "dog" starts at position 9, so

* xc = 0 and xd = 9
2. Next, let's find the center of mass of "cat".

* It has a mass of 24 WMU (3+1+20).
    * Rc = 1/24(3\*0+1\*1+20\*2) = 41/24 = 1.70833 em
    * So unsurprisingly the center of mass is very close to the letter 't'.
3. Now let's get the center of mass of "dog"

* Rd = 1/26(4\*9+15\*10+7\*11) = 263/26 = 10.11538 em
    * So the center of mass for dog is close to the letter 'o', slightly towards 'g'.
4. Now we can calculate the force between the two words.

* F = 24\*26/(10.11538-1.70833)2 = 8.82871 Nw
5. Now we need to apply this force to both words and get their accelerations

* ac = 8.82871/24 = .36786 em/s2
    * ad = -8.82871/26 = -.33957 em/s2
6. Following the rules above, we apply the acceleration to the velocity, so

* vc = .36786 em/s
    * vd = -.33957 em/s
7. Then we apply the velocity to the position, so after one second,

* xc = .36786 em
    * xd = 9 -.33957 = 8.66043 em.
    * Rc = 1.70833+.36786 = 2.07619 em
    * Rd = 10.11538-.33957 = 9.77581 em
8. Now we repeat the procedure one more time with the new positions:

* F = 24\*26/((9.77581)-(2.07619))2 = 10.52558 Nw
    * ac = 10.52558/24 = .43857 em/s2, ad = 10.52558/26 = -.40483 em/s2
    * vc = .36786 + .43857 = .80643 em/s, vd = -.33957 - .40483 = -.74440 em/s
    * xc = .36786 + .80643 = 1.17429 em, xd = 8.66043 - .74440 = 7.91603 em
    * Rc = 2.07619 + .80643 = 2.88262 em, Rd = 9.77581 - .74440 = 9.03141 em
9. So we end up with "cat" at x=1.17429 and "dog" at x=7.91603.

* We round those to the nearest integer so "cat" goes to position 1 and "dog" goes to position 8, so the output is  `cat dog`

## Handling Collisions

Remember that the new acceleration is immediately added to the velocity every second. Therefore, if two words collide at certain time, use algebra to find the point of collision. Take this example:

* word 1 is 4 letters long (||w1|| = 4)
* word 2 is 4 letters long (||w2|| = 4)
* x1 = 3, x2 = 8
* v1 = 2,v2 = -6

Solve `3 + (4-1) + 2t = 8 - 6t`. t = .25s. The position of the collision is xcol = 6.5. Therfore, the collision should appear as occurring between x = 6 and x = 7, as such

`####@@@@` .

The explicit formula for the positions of the words after a collision is

* x1 = floor(xcol)-||w1||+1
* x2 = floor(xcol)+1

# Answer
## Python 3, 556 bytes

Thanks to FryAmTheEggman and Sherlock9 for some bytes

```
s,E,a,b,e=str.split,enumerate,lambda c:ord(c)%32*-~c.isupper(),lambda w:sum(map(a,w)),' '
def j(w):z,y=map(len,s(w));h=w.count(e);return sum(i*a(x)for i,x in E(w)if i<z)/b(w[:z]),sum(i*a(x)for i,x in E(w)if i>=y+h)/b(w[-y:])
def f(w):x,v=j(w);m,n=map(b,s(w));return m*n/(x-v)**2
def q(w):x,v=s(w);return f(w)/b(x),-f(w)/b(v)
def p(w,t):
 x,v=q(w);c,d=x,v;m,n=map(b,s(w));r,u=j(w);g,h=r,u;
 for i in range(t):r+=x;u+=v;f=m*n/(r-u)**2;c,d=f/m,f/n;x+=c;v+=d
 return int(r-g),int(1+h-u)
def g(w,t):x,y=p(w,t);u,v=s(w);return e*x+u+e*(len(w)-len(u+v)-x-y)+v+e*y

```

`g(w,t)` takes the string (`w`) and the time (`t`), and returns the result. The other functions are helpers.

Try it online (prints out `*`s instead of spaces so that it is more visible)
> 3 votes

---
Tags: code-golf, simulation, physics
---


title: Make a simple pretty-comment tool

text:
# Question
Title: Make a simple pretty-comment tool
# Challenge:

Some ascii-art is a pain to make, but makes code comments easier to read, especially when the code is dense. The challenge is to make a simple tool that converts comments to simple ascii-art with arrows. The comments to modify are delimited by empty comments.

For example, supposing Haskell comment syntax, convert this:

```
--
-- Here's a thing
-- Here's another thing
-- The most important thing
-- *    *     *
--
f x=x+1*x*1*1*0

```

To this:

```
-- /------------< Here's a thing
-- |    /-------< Here's another thing
-- |    |     /-< The most important thing
-- |    |     |
-- v    v     v
f x=x+1*x*1*1*0

```

# Rules:

* Your answer may be either a function or full program
* You may pick the language this is made to work with, replacing the "--" with two or more characters that delimit a comment in some language
* If using another comment format that requires beginning and ending delimiters, each line of the reformatted sections must be a proper comment
* The sections to be reformatted are delimited by the empty comment "\n--\n"
* Besides adding newlines, the program must not change any of the input except the delimited sections
* A comment filled with an arbitrary number of spaces may come immediately before a properly formatted section of output
* Standard loopholes are disallowed

# Additional Examples:

```
(input)
--
--
(output)
nothing

(input)
[Code Here]
--
-- important
--    *
--
(output)
[Code Here]
--    /-< important
--    |
--    v

(input)
--
-- Do
-- Re
-- Mi
-- Fa
-- So
-- *****
--
(output)
-- /-----< Do
-- |/----< Re
-- ||/---< Mi
-- |||/--< Fa
-- ||||/-< So
-- |||||
-- vvvvv

```

# Scoring:

* Fewest bytes wins
* Submissions without explanations or non-trivial example input/output will not be considered (though I will leave a grace period to allow time to add such)

# Answer
> 4 votes
# Ruby, 160 characters

```
->c{c.gsub(/^--$(.+?)^--$/m){*t,a=$&.lines[1..-2]
a&&a.chop!&&(t.map{|l|a[?*]=?/
l[0,2]=a.gsub(/(?<=\/).*/){?-*$&.size}+'-<'
a[?/]=?|
l}<<a+$/+a.tr(?|,?v))*''}}

```

Sample run:

```
2.1.5 :001 > puts ->c{c.gsub(/^--$(.+?)^--$/m){*t,a=$&.lines[1..-2];a&&a.chop!&&(t.map{|l|a[?*]=?/;l[0,2]=a.gsub(/(?<=\/).*/){?-*$&.size}+'-<';a[?/]=?|;l}<<a+$/+a.tr(?|,?v))*''}}["
2.1.5 :002"> --
2.1.5 :003"> -- Here's a thing
2.1.5 :004"> -- Here's another thing
2.1.5 :005"> -- The most important thing
2.1.5 :006"> -- *    *     *
2.1.5 :007"> --
2.1.5 :008"> f x=x+1*x*1*1*0
2.1.5 :009"> "]

-- /------------< Here's a thing
-- |    /-------< Here's another thing
-- |    |     /-< The most important thing
-- |    |     |
-- v    v     v
f x=x+1*x*1*1*0
 => nil

```

Brief description:

```
.lines splits the section to array items ─────────╮
                                                  ▽

.gsub extracts ⎧   --                             0
these sections ⎪   -- Here's a thing              1   t[0]
for processing ⎨   -- Here's another thing        2   t[1]
and replaces   ⎪   -- The most important thing    ⋮   t[2]
them with the  ⎪   -- *    *     *               -2   a
pretty version ⎩   --                            -1
rest untouched —   f x=x+1*x*1*1*0
                                                      △
only the needed lines get into variables ─────────────╯

a = "-- *    *     *" + "-<"           inside .gsub's block
        ↓↓                             the first 2 characters
t[0] = "-- Here's a thing"             of t's each item are
t[1] = "-- Here's another thing"       replaced with a's value
t[2] = "-- The most important thing"   and the the separator

not only t's items are transformed inside .gsub's block,
but a's value also gets changed in multiple small steps

                       change a's value    change the value    change a's value
   a's initial value   before insertion   being inserted now   after insertion
   ╭───────────────╮   ╭───────────────╮   ╭───────────────╮   ╭───────────────╮

0  "-- *    *     *" → "-- /    *     *" → "-- /-----------" → "-- |    *     *"
1  "-- |    *     *" → "-- |    /     *" → "-- |    /------" → "-- |    |     *"
2  "-- |    |     *" → "-- |    |     /" → "-- |    |     /" → "-- |    |     |"

                       ╰───────────────╯   ╰───────────────╯   ╰───────────────╯
                      change first * to /  change everything  change first / to |
                                          after / with string
                                          of - of same length

```

# Answer
> 5 votes
# JavaScript(ES6), ~~418~~, ~~237~~, ~~233~~, 236 bytes

```
f=(s)=>(d='\n//',s.split(d+'\n').map((x,y)=>y%2?'//'+(l=x.slice(2).split(d),t=l.pop().split('*'),l.map((i,j)=>t.map((k,m)=>m==j?k+'/':m<j?k+'|':k.replace(/ /g,'-')+'-').join('')+'<'+i).join(d)+d+t.join('|')+d+t.join('v')):x).join('\n'))

```

Whew, this is my first submission on CG. ~~Took, I think, a totally different tack from Washington Guedes. Ended up 54 bytes shorter than his first pass. Minifying all this by hand was grueling. My one regret is not being able to eliminate the while loop yet, which would also let me cut the return.~~

Total rewrite, taking partial inspiration from a couple of the other answers. I got to close the whole thing in maps, making returning much better. The code snippet contains the commented version.

Took a few more bytes off, and made the example operate on itself. (You're gonna need a bigger monitor.) :)

Forgot an entire letter in the spec! Fortunately, adding the leading '\<' was a tiny, trivial fix.

```
var comments = `
//
// New function, declare the comment delimiter
// Chop the string by the fancy comment delimiter
// Iterate over the array.
// Because of how it's delimited, and how JS splits strings, only the even elements will contain fancy comments.
// Add the original comment delimiter to the front of the first line, because join won't.
// we've got a single fancy comment, split it into lines.
// Take the last line, our asterisk template, and split it on the asterisks themselves. We were only gonna replace them anyway.
// Now we get to the real work. Iterate the remaining lines.
// For each chunk of whitespace in the template array, toss a different character on the end based on where we are in the series of lines.
// if we're at the matching asterisk, insert a slash
// Otherwise, if we're at a prior asterisk, add a pipe.
// Finally, replace anything afer the matching asterisk with dashes, join the template, and add it to the line text.
// Join the lines with the delimiter
// Add the pipe line...
// And the v line...
// For odd chunks, just return the chunk.
// Join all the code chunks and autoreturn.
//      *        *               *          *   *     *                     *                    *            *            *          *         *                                        *           *             *          *  *
//
`
f=(s)=>(d='\n//',s.split(d+'\n').map((x,y)=>y%2?'//'+(l=x.slice(2).split(d),t=l.pop().split('*'),l.map((i,j)=>t.map((k,m)=>m==j?k+'/':m<j?k+'|':k.replace(/ /g,'-')+'-').join('')+'<'+i).join(d)+d+t.join('|')+d+t.join('v')):x).join('\n'))

str = `
//
// This is a test
// with two lines
// actually three
// *  *       *
//
var myCode = function () {

}
// This doesn't cause any trouble.

moreCode(stuff--)

//
// another test?
//  *
//

`
document.getElementById('before').textContent = str;
document.getElementById('after').textContent = f(str);
document.getElementById('self').textContent = f(comments)+'f='+f.toString();
```

```
Test cases before:
<pre id="before" style="background:#eef"></pre>
Test cases after:
<pre id="after" style="background:#eef"></pre>
Self-annotated:
<pre id="self"></pre>
```

# Answer
> 3 votes
## Python 2, 299 bytes

Expects a trailing newline in the input

```
i=input().split('--\n')
a=0
for j in i:
 a+=1
 if a%2:print j,;continue
 if''==j:continue
 l=j.split('\n');n=l[-2];r=l[:-2];R=[n.replace('*','v'),n.replace('*','|')];L=R[1]
 for x in range(len(l)-2)[::-1]:L=L[:L.rfind('|')]+'/';R+=[L.ljust(n.rfind('*')+2,'-')+'< '+r[x][3:]]
 print'\n'.join(R[::-1])

```

---

**Explanation/Example**

Input:

```
[Code Here]
--
-- important
--    *
--

```

Splits the input by `--\n`. Every second string is a delimited comment block.

```
['[Code Here]\n',
'-- important\n-- stuff\n--    *  *\n',
'']

```

Runs through each string. If the string is not a comment, then just prints the string. Otherwise:

Splits each line in the comment block.

```
['-- important', '-- stuff', '--    *  *', '']

```

Makes the bottom two lines by replacing the lines of `*`s with `v` and `|`.

```
['--    v  v', '--    |  |']

```

For each line of comments(backwards) remove rightmost column, add `/`, pad with `-` and add comment.

```
'--    |  /'
'--    /'
'--    /----< important'

```

Print Everything

```
--    /----< important
--    |  /-< stuff
--    |  |
--    v  v

```

**Less golfed:**

```
i=input().split('--\n')
a=0
for j in i:
 a+=1
 if a%2:print j,;continue # Not commment
 if''==j:continue # Empty comment
 l=j.split('\n') # Split comment into lines
 r=l[:-2]
 # Replace line of *s with v and | respectively
 R=[l[-2].replace('*','v'),l[-2].replace('*','|')]
 L=R[1][3:] # line of |
 for x in range(len(l)-2)[::-1]: # For each comment line
  L=L[:L.rfind('|')]+'/' #Remove rightmost column
  # Add a line with '-- ',columns, and comment
  R+=['-- '+L.ljust(n.rfind('*')-1,'-')+'< '+r[x][3:]]
 print'\n'.join(R[::-1]) #Print all comment lines

```

# Answer
> 1 votes
# JavaScript (ES6), 253

As an anonymous function, with the code to format as a string parameter and returning the formatted code.

*Notes*

1. The pair of marker comments must enclose the right text (comment lines, then stars)
2. ... or the pair must enclose nothing (additional example 1)

```
t=>(t=t.split`
`,t.map((r,i)=>r=='--'?(c++&&l.map((r,j)=>(p+=q[j],z+=~q[j].length,t[i-n+j]=p+`/${'-'.repeat(z+1)}<`+r.slice(3),p+=`|`),q=l.pop(c=p=``)||p,z=q.length,q=q.split`*`,t[i]=p+q.join`v`,t[i-1]=p+q.join`|`),l=[]):n=l.push(r),c=0,l=[]),t.join`
`)

```

**Less golfed**

```
f=t=>{
  t = t.split`\n`; // string to array of lines
  l = []; // special coment text
  c = 0; // counter of marker comment '--'
  t.forEach((r,i)=>{ // for each line of t - r: current line, i: index
    if (r == '--') // if marker comment
    {
       ++ c; // increment marker counter
       if (c > 1) // this is a closing marker
       {
          c = 0; // reset marker counter
          if (n > 0) // n is the length of array l
             q = l.pop(); // get last line from l, have to be the star line
          else
             q = ''; // no text comment, no star line
          p = '';  // prefix for drawing the tree
          z = q.length; // length of star line, used to draw the tree horiz lines
          q = q.split('*'); // split to get star count and position
          // each element in q is the spaces between stars
          // modifiy the current and previous text line
          t[i] = p + q.join`v`; // current row was '--', becomes the V line
          t[i-1] = p + q.join`|`; // previous row was the star line, becomes the last tree line
          l.forEach((r,j)=>{ // for each line in l, r: current line, j: index
             // each line in tree is: prefix("-- |  |"...) + ... "---< " + text
             p = p + q[j]; // adjust prefix
             z = z - q[j].length - 1 // adjust length of '---'
             // modify text in t
             t[i-n+j] = p // prefix
                + '/' + '-'.repeat(z+1) + '<'  // horiz line and <
                + r.slice(3); // text, removed '-- '
             p = p + '|'; // add vertical bar to prefix
          });
       } // end if closing comment
       l = []; // reset l
    }
    else // not a special comment marker
       n = l.push(r) // add current line to l, set n to array size
  });
  return t.join`\n` // join to a single string
}

```

**Test**

```
f=t=>(
  t=t.split`\n`,
  t.map((r,i)=>
    r=='--'
    ?(
      c++&&l.map((r,j)=>(
        p+=q[j],z+=~q[j].length,t[i-n+j]=p+`/${'-'.repeat(z+1)}<`+r.slice(3),p+=`|`),
        q=l.pop(c=p=``)||p,z=q.length,q=q.split`*`,t[i]=p+q.join`v`,t[i-1]=p+q.join`|`
      ),l=[]
    ):n=l.push(r)
    ,c=0,l=[]
  ),
  t.join`\n`
)

function update(){O.textContent=f(C.value)}

update()
```

```
textarea, pre { width:50%; height: 200px }
```

```
Input<br>
<textarea id=C>
code line 1
--
-- Do
-- Re
-- Mi
-- Fa
-- So
-- *****
--
code to explain
--
--
code line n
code line n+1
--
-- important
--    *
--

</textarea><br>
Output <button onclick="update()">Update</button><br>
<pre id=O></pre>
```

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


title: Scheduling a chess tournament

text:
# Question
Title: Scheduling a chess tournament
### Introduction

Right now I'm participating a chess tournament. I got inspired by the tournament schedule. Right now, I'm in a competition with three other players. That means with the four of us, we are playing 3 rounds. The schedule goes as following:

```
Round 1: 1-4 3-2
Round 2: 3-4 2-1
Round 3: 1-3 4-2

```

This is also known as **Round Robin**. Also, this is a **valid** schedule. We say that a schedule is valid, when it satisfies the following conditions:

* Every player plays **once** against another player.
* `1-2` means that player `1` has **white**. Every player has or (*N / 2 - 0.5*) or (*N / 2 + 0.5*) times white, with *N* being the amount of rounds.

For example, in the above example, there are **3** rounds. So N = 3. As you can see, **the amount of rounds equals the amount of players - 1**. A player has either

* *N / 2 - 0.5* = **1** time white, or
* *N / 2 + 0.5* = **2** times white.

In the above example:

* player `1` has **2 times** white,
* player `2` has **1 time** white,
* player `3` has **2 times** white,
* player `4` has **1 time** white.

### The task

Given an **even** integer \> 1 representing the amount of players in the competition, output the tournament schedule.

### Test cases:

Input = 4, that means N = 3

```
Input:     Output:
4          1-4 3-2
           3-4 2-1
           1-3 4-2

```

Input = 10, that means N = 9

```
Input:     Output:
10         1-10  2-9  3-8  4-7  5-6
           10-6  7-5  8-4  9-3  1-2
           2-10  3-1  4-9  5-8  6-7
           10-7  8-6  9-5  1-4  2-3
           3-10  4-2  5-1  6-9  7-8
           10-8  9-7  1-6  2-5  3-4
           4-10  5-3  6-2  7-1  8-9
           10-9  1-8  2-7  3-6  4-5
           5-10  6-4  7-3  8-2  9-1

```

Input = 12, that means N = 11

```
Input:     Output:
12         1-14    2-13   3-12   4-11   5-10   6-9    7-8
           14-8    9-7    10-6   11-5   12-4   13-3   1-2
           2-14    3-1    4-13   5-12   6-11   7-10   8-9
           14-9    10-8   11-7   12-6   13-5   1-4    2-3
           3-14    4-2    5-1    6-13   7-12   8-11   9-10
           14-10   11-9   12-8   13-7   1-6    2-5    3-4
           4-14    5-3    6-2    7-1    8-13   9-12   10-11
           14-11   12-10  13-9   1-8    2-7    3-6    4-5
           5-14    6-4    7-3    8-2    9-1    10-13  11-12
           14-12   13-11  1-10   2-9    3-8    4-7    5-6
           6-14    7-5    8-4    9-3    10-2   11-1   12-13
           14-13   1-12   2-11   3-10   4-9    5-8    6-7
           7-14    8-6    9-5    10-4   11-3   12-2   13-1

```

Of course, the extra whitespaces I used between the numbers is **optional** but not necessary. You may output it in any form you like, as long as it's readable.

**Note:** The above examples aren't just the *only* valid outputs. There certainly are more valid outputs.

This is , so the submission with the least amount of bytes wins!

# Answer
# Python 2, ~~200~~ 186 Bytes

---

```
n=input()
t=range(2,n+1)
for k in t:
 s=[1]+t
 c=[[s[x],s[-x-1]] for x in range(n/2)]
 if k%2:c[0].reverse()
 t=t[-1:]+t[:-1]
 print"\t".join(["-".join([str(y) for y in x]) for x in c])

```

---

Example output:

```
$ python chess.py
4
1-4     2-3
3-1     4-2
1-2     3-4

$ python chess.py
10
1-10    2-9     3-8     4-7     5-6
9-1     10-8    2-7     3-6     4-5
1-8     9-7     10-6    2-5     3-4
7-1     8-6     9-5     10-4    2-3
1-6     7-5     8-4     9-3     10-2
5-1     6-4     7-3     8-2     9-10
1-4     5-3     6-2     7-10    8-9
3-1     4-2     5-10    6-9     7-8
1-2     3-10    4-9     5-8     6-7

$ python chess.py
14
1-14    2-13    3-12    4-11    5-10    6-9     7-8
13-1    14-12   2-11    3-10    4-9     5-8     6-7
1-12    13-11   14-10   2-9     3-8     4-7     5-6
11-1    12-10   13-9    14-8    2-7     3-6     4-5
1-10    11-9    12-8    13-7    14-6    2-5     3-4
9-1     10-8    11-7    12-6    13-5    14-4    2-3
1-8     9-7     10-6    11-5    12-4    13-3    14-2
7-1     8-6     9-5     10-4    11-3    12-2    13-14
1-6     7-5     8-4     9-3     10-2    11-14   12-13
5-1     6-4     7-3     8-2     9-14    10-13   11-12
1-4     5-3     6-2     7-14    8-13    9-12    10-11
3-1     4-2     5-14    6-13    7-12    8-11    9-10
1-2     3-14    4-13    5-12    6-11    7-10    8-9

```

---

Or **135 Bytes**, by using a less pretty (but still readable) output:

```
...
print c

```

Which produces something like:

```
$ python chess.py
4
[[1, 4], [2, 3]]
[[3, 1], [4, 2]]
[[1, 2], [3, 4]]

```
> 3 votes

---
Tags: code-golf
---


title: Read the tables

text:
# Question
Title: Read the tables
## Task

Read the contents of a table given a set of coordinates.

## Table formatting

Tables will be in this basic format:

```
      |[name]|[name]|
---------------------
[name]| [val]|[val] |
[name]| [val]|[val] |

```

Column names are always unique *within columns*. Row names are also unique *within rows*. This includes names that are the same except whitespace. Values, col names and row names will never have `|-` inside them. Names and values will never have spaces inside them, but may have leading or trailing space. Col width is adjustable based on the header/content. Column width is always consistent from top to bottom.

### Input

A table and a space separated list of `[name]`s.

Example

```
[table]
row col

```

If you are writing a function, these can be separate strings, otherwise the `row col` will always be the very last line in the input. `row col` has some flexibility for the format and may be represented many ways. (e.g. `(row, col)`, `r, c`, ...). The only hard requirement is that it be one line, and that it must appear in the order `col row`.

### Output

The contents of a cell specified by the input *with no leading or trailing space from the cell*.

## Examples

```
In:
   |a|z |_*|
------------
atb|1|85|22|
b  |5|6 |e$|
/+*|8|we|th|
atb a

Out:
1

In:
  | x| b |
----------
ab|l |mmm|
b |le| l |
b b

Out:
l

In:
   |a|z |_*|  ab  |
-------------------
atb|1|85|22| 5    |
b  |5|6 |e$|  8   |
/+-|8|we|th| 126  |
atb ab

Out:
5

```

# Answer
# Retina, 90 bytes

```
s`^(?=.*\n(.*) (.*))((?<a>\|)|.)*\|\s*\2\s*\|.*\n\1\s*((?<-a>\|)|[^|])*\|\s*([^\s|]*).*
$5

```

My first balancing group regex. It should be still well golfable. Will try to do it later.

The main idea is counting the pipes until the column name and then using the same amount of pipes up in the row starting with the desired row's name. After that we capture the next value which is the result.

Try it online here.
> 2 votes

# Answer
# JavaScript (ES6), 108

```
t=>(S=s=>s.split(/ *\| */),t=t.split`
`,[y,x]=t.pop().split` `,S(t.find(r=>S(r)[0]==y))[S(t[0]).indexOf(x)])

```

**TEST** in Firefox

```
f=t=>(
 S=s=>s.split(/ *\| */),
 t=t.split`\n`,
 [y,x]=t.pop().split` `,
 S(t.find(r=>S(r)[0]==y))[S(t[0]).indexOf(x)]
)

function test(){
  r=f(T.value);
  O.textContent=r
}
test()
```

```
#T { width: 50%; height: 9em}
```

```
Input<br><textarea id=T>   |a|z |_*|  ab  |
-------------------
atb|1|85|22| 5    |
b  |5|6 |e$|  8   |
/+-|8|we|th| 126  |
atb ab</textarea><br>
<button onclick="test()">Find</button>
<span id=O></span>
```
> 5 votes

# Answer
## Haskell, ~~117~~ ~~116~~ 111 bytes

```
import Data.Lists
s=splitOn"|".filter(>' ')
(t#b)a|l<-lines t=[c|r<-l,(d,c)<-zip(s$l!!0)$s r,d==a,s r!!0==b]!!0

```

Usage example:

```
*Main> ("  | x| b |\n----------\nab|l |mmm|\nb |le| l |\nb b" # "b") "b"
"l"

```

How it works:

```
s=splitOn"|".filter(>' ')         -- helper function to remove spaces and split a
                                  -- line at bars into words
l<-lines t                        -- split table at \n into lines and bind to l
[c|r<-l,                      ]   -- take c for every line r in l, where
       (d,c)<-zip(s$l!!0)$s r     -- a pair (d,c) is made by zipping the (split)
                                  -- header of the table with the (split) line r
        ,d==a                     -- and d (=header element) equals parameter a
        ,s r!!0==b                -- and the first word in r equals parameter b
                             !!0  -- pick the first (and only) element

```
> 4 votes

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