[Question]
      [
The goal here is to simply reverse a string, with one twist:
Keep the capitalization in the same places.
Example Input 1: `Hello, Midnightas`
Example Output 1: `SathginDim ,olleh`
Example Input 2: `.Q`
Exmaple Output 2: `q.`
**Rules**:
* Output to STDOUT, input from STDIN
* The winner will be picked 13th of July on GMT+3 12:00 (One week)
* The input may only consist of ASCII symbols, making it easier for programs that do not use any encoding that contains non-ASCII characters.
* Any punctuation ending up in a position where there was an upper-case letter must be ignored.

[Answer]
# VIM, 46 bytes
It'd be three bytes `g~G` if we didn't need to read from stdin or write to stdout, but oh well...
```
vim -es '+normal! g~G' '+%print|q!' /dev/stdin
```
To test this, run
```
echo "testString" | vim -es '+normal! g~G' '+%print|q!' /dev/stdin
```
This is my first submission on here, not sure if this kind of submission is acceptable.
[Answer]
## Javascript (using external library) (224 bytes)
```
(s)=>{t=_.From(s);var cnt=t.Count();var caps=t.Select(x=>{return x.toUpperCase()===x&&x.toLowerCase()!==x}).ToArray(),i=-1;return t.AggregateRight((a,b)=>{i++;var c=caps[i];return c?a+b.toUpperCase():a+b.toLowerCase()},"");}
```
Disclaimer: Using a library I wrote to bring C#'s LINQ to Javascript
[![Image 1](https://i.stack.imgur.com/2dMRM.png)](https://i.stack.imgur.com/2dMRM.png)
[Answer]
# Sed, 113 + 1 = 114 bytes
Why? Because it's fun to use the *wrong* tool to do things :P
Usage: Run `sed -rf file`, enter text and press `Ctrl` + `D` (send EOF).
Golfed:
```
s/[A-Z]/\a\l&/g;s/^.*$/\f&\v/;:x;s/\f\a/\a\f/;s/\a\v/\v\a/;s/\f(.)(.*)(.)\v/\3\f\2\v\1/;tx;s/\f|\v//g;s/\a./\U&/g
```
Ungolfed:
```
s/[A-Z]/\a\l&/g #Prepend all upper-case letters with a
                #BEL ASCII character and make them lowercase
s/^.*$/\f&\v/   #Wrap text between a from feed (\f) and a vertical tab (\v)
                #These are used as markers
:x #Define a label named x
s/\f\a/\a\f/;s/\a\v/\v\a/ #Move BEL characters outside of the boundary, so they're not moved later
s/\f(.)(.*)(.)\v/\3\2\1/  #This part does the switching itself
                          #It grabs a character preceded by a form feed and another
                          #one followed by a vertical tab and swaps them, while keeping the text in-between
                          #and replaces the marker \f and \v
tx             #Conditional jump (t) to label x
               #Jumps to the label x if the last substitution (s command) was successful
s/\f|\v//g     #Delete markers
s/\a(.)/\u\1/g #Make letters preceded by a BEL upper-case
```
[Answer]
# Java 7, ~~221~~ ~~217~~ 180 bytes
```
void c(char[]s){int x=0,y=s.length-1;for(char t;x<y;s[x]=s(t,s[y]),s[y]=s(s[y],t),x++,y--)t=s[x];}char s(char a,char b){return(char)(64<a&a<91?96<b&b<123?b-32:b:64<b&b<91?b+32:b);}
```
Loads of bytes saved thanks to *@LeakuNun*'s approach.
**Ungolfed & test cases:**
[Try it here.](https://ideone.com/oqyLIU)
```
class Main{
  void c(char[] s){
    int x = 0,
        y = s.length-1;
    for(char t; x < y; s[x] = s(t, s[y]),
                       s[y] = s(s[y], t),
                       x++,
                       y--){
       t = s[x];
    }
  }
  char s(char a, char b){
    return (char)(64 < a & a < 91
                    ? 96 < b & b < 123
                        ? b-32
                        : b
                    : 64 < b & b < 91
                        ? b+32
                        : b);
  }
  public static void main(String[] a){
    print("Hello, Midnightas");
    print("TEST");
    print("test");
    print("Test");
    print(".,..,,!@");
    print("ABCDefgHijklMNOPqrsTuVWxyz");
    print("AbCdEfGHIJKlmnop123");
  }

  static void print(String s){
    char[] t = s.toCharArray();
    c(t);
    System.out.println(t);
  }
}
```
**Output:**
```
SathginDim ,olleh
q.
TSET
tset
Tset
@!,,..,.
ZYXWvutSrqpoNMLKjihGfEDcba
321pOnMLKJIhgfedcba
```
[Answer]
# Lua, 132 Bytes
```
function(s)o=""i=0 for m in s:gmatch(".")do n=s:sub(#s-i,#s-i)l=m:lower()o=o..(m==l and n:lower()or n:upper())i=i+1 end print(o)end
```
There might be a better way to do this in lua, but I think this works.
[Answer]
# Ruby, 64 bytes
[Try it online!](https://repl.it/Coos)
```
->s{i=0;s.gsub(/./){c=s[i-=1];$&=~/[A-Z]/?c.upcase: c.downcase}}
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 24 bytes
```
{b?UCaa}MZLCRVa(_NAZ Ma)
```
Gets a binary array for the uppercase indices and uppercases those places in the reversed lowercase string.
[Try it online!](https://tio.run/##K8gs@P@/Osk@1DkxsdY3ysc5KCxRI97PMUrBN1Hz////Hqk5Ofk6Cr6ZKXmZ6RklicUA "Pip – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
Âls€.uÅÏu
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cFNO8aOmNXqlh1sP95f@/@@RmpOTr6Pgm5mSl5meUZJYDAA "05AB1E – Try It Online")
**Commented:**
```
Â          # Push input and input reversed
 l         # lowercase reversed input
  s        # swap to normal input
   €.u     # map is_upper
      ÅÏ   # where this is true,
           # apply to the reversed input:
        u  # uppercase
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
£ÔgY mvc-X¦v
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=o9RnWSBtdmMtWKZ2&input=IkhlbGxvLCBNaWRuaWdodGFzIg)
```
£ÔgY mvc-X¦v     :Implicit input of string U
£                :Map each character X at 0-based index Y
 Ô               :  Reverse U
  gY             :  Get the character at index Y
     m           :  Map
      v          :    Literal "v"
       c-        :    Reduce charcode by
         X¦      :      X does not equal
           v     :      Its lowercase
                 :(This results in mapping the character by either "v",
                 : which is Japt's lowercase method or "u",
                 : which is Japt's uppercase method)
```
[Answer]
# [Arturo](https://arturo-lang.io), 62 bytes
```
$->s[i:0map reverse lower s'c[if<=>s\[i]`A``Z`->upper'c'i+1c]]
```
[Try it](http://arturo-lang.io/playground?Ye1pKi)
Takes a string, returns a list of characters.
[Answer]
# Commodore C64 (just for fun/non-competing), 194 Tokenised BASIC Bytes
To enter this on a real C64, you must use [BASIC keyword abbreviations](https://www.c64-wiki.com/wiki/BASIC_keyword_abbreviation), as you are not able to enter more than 80 characters onto a C64 BASIC line though once entered the interpreter will show the keywords in full. The listing is shown as abbreviations with switched character modes to upper/lower case. You may do this by pressing SHIFT + C=. The program will switch modes anyway on line 0 with the control character N (achieved by pressing `CTRL+N` after the opening quote).
```
0input"{CTRL+N}";a$:ifa$=""tHeN
1l=len(a$):dIp(l),b(l):fOx=1tol:p(x)=aS(mI(a$,x,1))>127:nE:i=1:fOx=lto1stE-1
2b(i)=aS(mI(a$,x,1))aN127:i=i+1:nE:fOx=1tol
3ifb(x)>64tH?cH(b(x)-128*p(x));
4ifb(x)<65tH?cH(b(x));
5nE
```
**Note** I've marked this as non-competing because whilst the character encoding on the Commodore C64 (PETSCII) is compatible with ASCII, it is not ASCII. As this question is six years old at the time of writing, and the questioner has left, I'm sure no one will mind.
Some caveats, string handling with the `INPUT` command has some limitations. For instance, if you wanted to enter `Hello, World!` as a test, you would need to enter it starting with a double quotation mark, so `"Hello, World!"`.
A quick explanation:
* Line 0 switches the character set to upper/lower case, rather than PETSCII graphics mode, and waits for a user input; if there is an empty string entered then the program terminates. I added this otherwise it will error, as the `FOR/NEXT` loops are expecting at least one character to iterate over.
* Line 1 will set l to the length of the string, and set up two numeric arrays, called `p(l)` and `b(l)`. `p(l)` is used for determines whether the positional character is upper case or not, by checking if the character code is 128 or more. If so, a `-1` is added to the array at position `x`, otherwise it is `0`. When that loop ends, we set variable `i` to `1`, and start a new loop counting down from the string length to 1.
* Line 2 sets the array `b(l)` at position `i` to the PETSCII character code; this value is `AND`ed with 127 so that each position will be the lower-case character code. `i` is then incremented by `1` and the loop ends. We then set up a final `FOR/NEXT` loop, again counting up from 1 to `l`.
* Line 3 checks if array position `b(x)` is 65 or greater (this is for characters `a` - `z` inclusive). If so, it prints the character -128 multiplied by the contents of `p(x)`, which is `-1` for upper-case at that position, or `0` if not. `-128*-1` will add `128` so converting the character at that position to upper case.
* Line 4 checks if array position `b(x)` has a value below 64; if so, we don't want to convert this to upper case or we will get some odd results for numbers and punctuation etc.
* Line 5 iterates the loop again until it is done. When the loop is finished, the program will end gracefully.
The screen shot below shows the BASIC program as the interpreter lists it.
This was a fun challenge and took a little while to get the logic right, so it's quite likely that there are some further optimisations to save some BASIC bytes.
[![Reverse a string while maintaining the capitalization in the same places, Commodore C64](https://i.stack.imgur.com/AvrPI.png)](https://i.stack.imgur.com/AvrPI.png)
[Answer]
# Excel VBA, 256 bytes
```
Function z(d)
r = Len(d)
ReDim E(1 To r)
For i = 1 To r
b = Mid(d, i, 1)
If Asc(b) > 64 And Asc(b) < 91 Then E(i) = 1
Next i
i = 1
For p = r To 1 Step -1
v = Mid(d, p, 1)
If E(i) = 1 Then z = z & UCase(v) Else z = z & LCase(v)
i = i + 1
Next p
End Function
```
[Answer]
# Google Sheets, 133
Closing parens already discounted.
Input: `A1`
* `A2`: `=LEN(A1)`
* `B1`: `=ArrayFormula(MID(A1,1+A2-SEQUENCE(A2),1))`
	+ Reverse string
* `C1`: `=JOIN(,ArrayFormula(if(REGEXMATCH(MID(A1,SEQUENCE(A2),1),"[A-Z]"),UPPER(B:B),LOWER(B:B))))`
	+ Compare capital positions, capitalize if originally upper, lower if not. Then join. `EXACT(UPPER(...),...)` is worse because we're dealing with a range here.
	+ It's a little sluggish because we don't chop off the `B:B` at the blanks.
[Answer]
C
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
  char *a,*b,*c;
  a=c=strdup(argv[1]);
  b=&argv[1][strlen(a)-1];
  for(;*a;a++,b--){
    *a=(*a>='A'&&*a<='Z')?((*b>='a'&&*b<='z')?*b-32:*b):((*b>='A'&&*b<='Z')?*b+32:*b);
  }
  puts(c);
  free(c);
  return 0;
}
```
]


[Question]
      [
Given two positive integers, 'a' and 'b', output an ascii-art "box" that is *a* characters wide and *b* characters tall. For example, with '4' and '6':
```
****
*  *
*  *
*  *
*  *
****
```
Simple right? Here's the twist: The border of the box must be the characters of "a" and "b" alternating. This starts at the top left corner, and continues in a clockwise spiral. For example, the previous example with 4 and 6 should be
```
4646
6  4
4  6
6  4
4  6
6464
```
A and B *may* be two-digit numbers. For example, the inputs "10" and "3" should output this:
```
1031031031
1        0
3013013013
```
In order to keep the output relatively small, you do not have to support three or more digit numbers. Also, since inputs are restricted to *positive* integers, '0' is an invalid input, which you do not have to handle.
Here are some more test cases:
```
Input: (3, 5)
Output:
353
5 5
3 3
5 5
353
Input: (1, 1)
Output:
1
Input: (4, 4)
Output:
4444
4  4
4  4
4444
Input: (27, 1)
Output:
271271271271271271271271271
Input: (1, 17)
Output:
1
1
7
1
1
7
1
1
7
1
1
7
1
1
7
1
1
Input: (12, 34):
Output:
123412341234
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
432143214321
```
You may take input and output in any reasonable format, and standard loopholes are banned. Since this is code-golf, the shortest answer in bytes wins!

[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~65~~ 51 bytes
```
~~juXGhHX@GhHeH@jkQ~hZ{s[+L]0UhQ+R]thQUeQ+L]teQ\_UhQ+R]0\_UeQ)m\*;hQeQ~~
AQjuXGhHX@GhHeH@jkQ~hZ{s[,L0G,RtGH_,LtHG_,R0H)m*;GH
```
[Try it online!](http://pyth.herokuapp.com/?code=AQjuXGhHX%40GhHeH%40jkQ~hZ%7Bs%5B%2CL0G%2CRtGH_%2CLtHG_%2CR0H%29m%2a%3BGH&input=10%2C3&debug=0)
[Answer]
## C#, 301 bytes
I'm sure there is a lot more golfing that can be done here but I'm just happy I got a solution that worked.
I found a bug where the bottom line was in the wrong order, damnit!
```
a=>b=>{var s=new string[b];int i=4,c=b-2,k=a;var t="";for(;i++<2*(a+b);)t+=t.EndsWith(a+"")?b:a;s[0]=t.Substring(0,a);if(b>2){for(i=0;++i<b-1;)s[i]=(a<2?t.Substring(1,c):t.Substring(2*a+c))[c-i]+(a>1?new string(' ',a-2)+t.Substring(a,c)[i-1]:"");for(;--k>=0;)s[b-1]+=t.Substring(a+c,a)[k];}return s;};
```
Old version: 280 bytes
```
a=>b=>{var s=new string[b];int i=4,c=b-2;var t="";for(;i++<2*(a+b);)t+=t.EndsWith(a+"")?b:a;s[0]=t.Substring(0,a);if(b>2){for(i=0;++i<b-1;)s[i]=(a<2?t.Substring(1,c):t.Substring(2*a+c))[c-i]+(a>1?new string(' ',a-2)+t.Substring(a,c)[i-1]:"");s[b-1]=t.Substring(a+c,a);}return s;};
```
[Answer]
# Python 2, 199 bytes
```
w,h=input()
s=(`w`+`h`)*w*h
r=[s[:w]]+[[" "for i in[0]*w]for j in[0]*(h-2)]+[s[w+h-2:2*w+h-2][::-1]]*(h>1)
for y in range(1,h-1):r[y][w-1],r[y][0]=s[w+y-1],s[w+h+w-2-y]
print"\n".join(map("".join,r))
```
[Answer]
# Ruby, 128 bytes
```
->w,h{s="%d%d"%[w,h]*q=w+h;a=[s[0,w]];(h-2).times{|i|a<<(s[2*q-5-i].ljust(w-1)+s[w+i,1])[-w,w]};puts a,h>1?(s[q-2,w].reverse):p}
```
Outputs trailing newline if height is 1.
Ideone link: <https://ideone.com/96WYHt>
[Answer]
# JavaScript, ~~213~~ ~~212~~ 202
```
c=>a=>{for(a=$=a,c=_=c,l=c*a*2,b=0,s=Array(l+1).join(c+""+a),O=W=s.substr(0,a),W=W.substr(0,a-2).replace(/./g," ");--_;)O+="\n"+s[l-c+_]+W+s[$++];return O+"\n"+[...s.substr(l-a-c+1,a)].reverse().join``}
```
Surely has room for improvement.
**Edit:** Saved a byte thanks to TheLethalCoder
[Answer]
# C, 311 bytes
```
char s[5];sprintf(s,"%d%d",a, b);int z=strlen(s);int i=0;while(i<a){printf("%c",s[i++%z]);}if(b>2){i=1;while(i<b-1){char r=s[(a+i-1)%z];char l=s[(2*a+2*b-i-4)%z];if(a>1){printf("\n%c%*c",l,a-1,r);}else{printf("\n%c",l);}i++;}}printf("\n");if(b>1){i=0;while(i<a){printf("%c",s[(2*a+b-i-3)%z]);i++;}printf("\n");}
```
Uses automatically included libraries `stdio.h` and `string.h`.
[Answer]
## JavaScript (ES6), 171 bytes
```
(w,h)=>[...Array(h)].map((_,i)=>i?++i<h?(w>1?s[p+p+1-i]+` `.repeat(w-2):``)+s[w+i-2]:[...s.substr(p,w)].reverse().join``:s.slice(0,w),s=`${w}${h}`.repeat(p=w+h-2)).join`\n`
```
Where `\n` represents the literal newline character. Creates a repeated digit string, then decides what to concatenate based on which row we're on; top row is just the initial slice of the repeated digit string, bottom row (if any) is a reversed slice from the middle of the string, while intervening rows are built up using characters taken from other parts of the string.
[Answer]
# TSQL, 291 bytes
**Golfed:**
```
DECLARE @ INT=5,@2 INT=4
,@t INT,@z varchar(max)SELECT @t=iif(@*@2=1,1,(@+@2)*2-4),@z=left(replicate(concat(@,@2),99),@t)v:PRINT iif(len(@z)=@t,left(@z,@),iif(len(@z)>@,right(@z,1)+isnull(space(@-2)+left(@z,1),''),reverse(@z)))SET @z=iif(len(@z)=@t,stuff(@z,1,@,''),substring(@z,2,abs(len(@z)-2)))IF @<=len(@z)goto v
```
**Ungolfed:**
```
DECLARE @ INT=5,@2 INT=4
,@t INT,@z varchar(max)
SELECT @t=iif(@*@2=1,1,(@+@2)*2-4),@z=left(replicate(concat(@,@2),99),@t)
v:
  PRINT
    iif(len(@z)=@t,left(@z,@),iif(len(@z)>@,right(@z,1)
      +isnull(space(@-2)+left(@z,1),''),reverse(@z)))
  SET @z=iif(len(@z)=@t,stuff(@z,1,@,''),substring(@z,2,abs(len(@z)-2)))
IF @<=len(@z)goto v
```
**[Fiddle](https://data.stackexchange.com/stackoverflow/query/526524/code-golf-abcs-the-ascii-box-challenge)**
[Answer]
# Python 3, ~~155~~ 148 bytes
Golfed off 7 more bytes:
```
p=print
def f(w,h):
 s=((str(w)+str(h))*w*h)[:2*w+2*h-4or 1];p(s[:w])
 for i in range(h-2):p(['',s[-i-1]][w>1]+' '*(w-2)+s[w+i])
 p(s[1-h:1-h-w:-1])
```
Substituted `2*w+2*h-4or 1` for `max(1,2*w+2*h-4)` and
`['',s[-i-1]][w>1]` for `(s[-i-1]if w>1else'')`.
Prior version:
```
p=print
def f(w,h):
 s=((str(w)+str(h))*w*h)[:max(1,2*w+2*h-4)];p(s[:w])
 for i in range(h-2):p((s[-i-1]if w>1else'')+' '*(w-2)+s[w+i])
 p(s[1-h:1-h-w:-1])
```
]


[Question]
      [
The purpose of this challenge is to produce an ASCII version of the cover of [this great album](https://en.wikipedia.org/wiki/The_Wall) by the rock band Pink Floyd.
The brick junctions are made of characters `_` and `|`. Bricks have width 7 and height 2 characters, excluding junctions. So the basic unit, including the junctions, is:
```
_________
|       |
|       |
_________
```
Each row of bricks is **offset by half a brick width** (4 chars) with respect to the previous row:
```
________________________________________
  |       |       |       |       |
  |       |       |       |       |
________________________________________
      |       |       |       |       |
      |       |       |       |       |
________________________________________
  |       |       |       |       |
  |       |       |       |       |
```
The wall is **parameterized** as follows. All parameters are measured in chars including junctions:
1. **Horizontal offset** of first row, `F`. This is the distance between the left margin and the first vertical junction of the upmost row. (Remember also the half-brick relative offset between rows). Its possible values are `0`, `1`, ..., `7`.
2. Total **width**, `W`. This includes junctions. Its value is a positive integer.
3. Total **height**, `H`. This includes junctions. Its value is a positive integer.
The top of the wall always coincides with the top of a row. The bottom may be ragged (if the total height is not a multiple of `3`). For example, here's the output for `6`, `44`, `11`:
```
____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |
  |       |       |       |       |       |
____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |
```
and a visual explanation of parameters:
```
          F=6
         ......
     .   ____________________________________________
     .         |       |       |       |       |
     .         |       |       |       |       |
     .   ____________________________________________
     .     |       |       |       |       |       |
H=11 .     |       |       |       |       |       |
     .   ____________________________________________
     .         |       |       |       |       |
     .         |       |       |       |       |
     .   ____________________________________________
     .     |       |       |       |       |       |
         ............................................
                             W=44
```
## Additional rules
You may provide a program or a function.
Input format is flexible as usual. Output may be through STDOUT or an argument returned by a function. In this case it may be a string with newlines or an array of strings.
Trailing spaces or newlines are allowed.
Shortest code in bytes wins.
## Test cases
Inputs are in the order given above, that is: horizontal offset of first row, total width, total height.
```
6, 44, 11:
____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |
  |       |       |       |       |       |
____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |
2, 20, 10:
____________________
  |       |       |
  |       |       |
____________________
      |       |
      |       |
____________________
  |       |       |
  |       |       |
____________________
1, 1, 1:
_
1, 2, 3:
__
 |
 |
3, 80, 21:
________________________________________________________________________________
   |       |       |       |       |       |       |       |       |       |
   |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
       |       |       |       |       |       |       |       |       |       |
       |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
   |       |       |       |       |       |       |       |       |       |
   |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
       |       |       |       |       |       |       |       |       |       |
       |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
   |       |       |       |       |       |       |       |       |       |
   |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
       |       |       |       |       |       |       |       |       |       |
       |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
   |       |       |       |       |       |       |       |       |       |
   |       |       |       |       |       |       |       |       |       |
```

[Answer]
# C, 86 85 83 82 bytes
3 bytes saved thanks to Lynn.
1 byte saved thanks to charlie.
```
i;f(o,w,h){++w;for(i=0;++i<w*h;)putchar(i%w?i/w%3?i%w+i/w/3*4+~o&7?32:124:95:10);}
```
[Answer]
# C, 92 bytes
```
b(f,w,h,y,x){for(y=0;y<h;y++,puts(""))for(x=0;x<w;x++)putchar(y%3?(x+y/3*4-f)%8?32:124:95);}
```
Invoke as `b(F, W, H)`.
[Answer]
# Pyth, ~~43~~ 27 bytes
I ***need*** to golf it heavily... the score is too shameful.
```
AQVE<*H?%N3X*8d+G*4/N3\|\_H
```
[Try it online already.](http://pyth.herokuapp.com/?code=AQVE%3C%2aH%3F%25N3X%2a8d%2BG%2a4%2FN3%5C%7C%5C_H&input=6%2C44%0A11&debug=0)
### Input format
```
6,44
11
```
### Output format
```
____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |
  |       |       |       |       |       |
____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |
```
## Explanation
```
AQVE<*H?%N3X*8d+G*4/N3\|\_H   First two inputs as list in Q,
                              third input as E.
AQ                            Assign G to the first item in Q
                              and H to the second item in Q.
  VE                          For N from 0 to E-1:
                   /N3            N floor-div 3.
                                    if N gives a remainder of 3 or 4 or 5
                                    when divided by 6, this will be odd;
                                    otherwise, this will be even.
                 *4               Multiply by 4.
                                    if the above is odd, this will leave
                                    a remainder of 4 when divided by 8;
                                    otherwise, the remainder would be 0.
               +G                 Add G (as an offset).
           X*8d       \|          In the string "        " (*8d),
                                  replace (X) the character with the
                                  index above with "|" (modular indexing,
                                  hence the manipulation above).
       ?%N3             \_        If N%3 is non-zero, use the above;
                                  otherwise, use "_".
     *H                           The above repeated H times.
    <                     H       Take the first H characters of above.
                                  Implicitly print with newline.
```
[Answer]
# Perl, 63 bytes
```
#!perl -nl
$y+=print+map$y%3?$_++-$`&7?$":'|':_,($y%6&4)x$&for/ \d+/..$'
```
Counting the shebang as 2, input is taken from stdin, whitespace separated.
**Sample Usage**
```
$ echo 2 20 10 | perl bricks.pl
____________________
  |       |       |
  |       |       |
____________________
      |       |
      |       |
____________________
  |       |       |
  |       |       |
____________________
```
[Answer]
## Haskell, 83 bytes
```
q s="_":[s,s]
(f!w)h=take h$cycle$take w.drop(7-f).cycle<$>q"       |"++q"   |    "
```
This defines a ternary infix function `!` which returns a list of strings. Usage example:
```
*Main> putStrLn $ unlines $ (3!14) 7
______________
   |       |
   |       |
______________
       |
       |
______________
```
How it works:
```
            q"       |"++q"   |    "  -- build a list of 6 strings
                                      --   1:     "_"
                                      --   2:     "       |"
                                      --   3:     "       |"
                                      --   4:     "_"
                                      --   5:     "   |    "
                                      --   6:     "   |    "
         <$>                          -- for each of the strings
     take w.drop(7-f).cycle           -- repeat infinitely, drop the first 7-f chars
                                      --    and take the next w chars
  cycle                               -- infinitely repeat the resulting list
take h                                -- and take the first h elements
```
[Answer]
## JavaScript (ES6), ~~96~~ 95 bytes
```
g=
(f,w,h)=>[...Array(h)].map((_,i)=>(i%3?`       |`:`_`).repeat(w+7).substr(f^7^i%6&4,w)).join`
`
;
```
```
<div onchange=o.textContent=g(f.value,w.value,+h.value)><input id=f type=number min=0 max=7 placeholder=Offset><input id=w type=number min=0 placeholder=Width><input id=h type=number min=0 placeholder=Height></div><pre id=o>
```
Explanation: Creates a string of either the repeating 7 spaces plus `|` pattern or just repeated `_`s, but at least long enough to be able to extract the `w` characters required for each row. The first three rows start at position `f^7` and then the next three rows start at position `f^3`, so I achieve this by ~~toggling bit 2 of `f` on every third row~~ using the opposite bit 2 on the last two rows of each block of 6 for a saving of 1 byte.
[Answer]
# Python 2, ~~93~~ 88 bytes
~~2nd indentation level is tab~~ Saving some bytes thanks to Leaky Nun and some own modifications, also now correct offset:
```
def f(F,W,H):
 for h in range(H):print["_"*W,((("|"+7*" ")*W)[8-F+h%6/3*4:])[:W]][h%3>0]
```
previous code:
```
def f(F,W,H,x="|"+7*" "):
 for h in range(H):
    print ["_"*W,(x[F+4*(h%6>3):]+x*W)[:W]][h%3>0]
```
Same length as unnamed lambda:
```
lambda F,W,H,x="|"+7*" ":"\n".join(["_"*W,(x[F+4*(h%6>3):]+x*W)[:W]][h%3>0]for h in range(H))
```
[Answer]
# MATL, ~~42~~ ~~36~~ 33 bytes
```
:-Q'_ | |'[DClCl]Y"8et4YShwi:3$)!
```
Input format is: `nCols`, `offset`, `nRows`
[**Try it Online**](http://matl.tryitonline.net/#code=Oi1RJ18gfCB8J1tEQ2xDbF1ZIjhldDRZU2h3aTozJCkh&input=NDQKNgoxMQ)
The approach here is that we setup a "template" which we then index into by using the row indices (`[1 2 ... nRows]`) and column indices shifted by the first input (`[1 2 ... nCols] - shift`). Thanks to MATL's modular indexing, it will automatically result in a tiled output. As a side-note, to save some space, technically I work with a transposed version of the template and then just take a transpose (`!`) at the end.
The template is this:
```
________
       |
       |
________
  |
  |
```
[Answer]
# QBasic, ~~121~~ 109 bytes
## (Tested on QB64)
Thanks to @DLosc for golfing my `IF` statement with a mathematical equivalent. That was worth 12 bytes.
## General Method:
Loop through each cell one at a time and determine whether it should be a `_`, , or `|` depending on its location. `MOD` statements and boolean logic are used to determine brick boundaries and how much to stagger the bricks.
## Code:
```
INPUT F,W,H
FOR y=0TO H-1:FOR x=0TO W-1
?CHR$((y MOD 3>0)*(((x-(y MOD 6>3)*4)MOD 8=F)*92+63)+95);
NEXT:?:NEXT
```
## Usage Note:
QBasic expects input to be numbers separated by commas.
[Answer]
# Java, ~~149~~, ~~147~~, ~~146~~, 143 bytes
Golfed:
```
String f(int o,int w,int h){String s="";for(int y=0,x;y<h;++y){for(x=0;x<w;++x){s+=y%3>0?(x-o+(y-1)/3%2*4)%8==0?'|':' ':'_';}s+='\n';}return s;}
```
Ungolfed:
```
public class AllInAllItsJustUhAnotherTrickInCodeGolf {
  public static void main(String[] args) {
    int offset = 6;
    int width = 44;
    int height = 11;
    System.out.println(new AllInAllItsJustUhAnotherTrickInCodeGolf()
        .f(offset, width, height));
  }
  // Begin golf
  String f(int o, int w, int h) {
    String s = "";
    for (int y = 0, x; y < h; ++y) {
      for (x = 0; x < w; ++x) {
        s += y % 3 > 0 ? (x - o + (y - 1) / 3 % 2 * 4) % 8 == 0 ? '|' : ' ' : '_';
      }
      s += '\n';
    }
    return s;
  }
  // End golf
}
```
[Answer]
# Ruby, ~~72~~ 66 bytes
```
->f,w,h{h.times{|i|puts i%3<1??_*w:((?|+' '*7)*w)[8-f+i%6/4*4,w]}}
```
Thanks @Value Ink for 6 bytes!
Simple string multiplication and slicing.
Works in Ruby 2.3.0 (Ideone's version 2.1 threw syntax error).
[Answer]
# Julia: ~~150~~ ~~128~~ ~~116~~ ~~108~~ 107 bytes
```
# in codegolf.jl
r=repmat;b=r([' '],6,8);b[[1,4],:]='_';b[[2,3,23,24]]='|';b=r(b,h,w)[1:h,o+=1:o+w];b[:,end]=10;print(b'...)
```
to run with arguments: `julia -e 'o=2;h=18;w=40;include("codegolf.jl")'`
If you feel calling from bash is cheating and you want a function inside the interpreter, then the function version is 117 bytes :)
```
f(o,h,w)=(r=repmat;b=r([' '],6,8);b[[1,4],:]='_';b[[2,3,23,24]]='|';b=r(b,h,w)[1:h,o+=1:o+w];b[:,end]=10;print(b'...))
```
[demo](http://julia.tryitonline.net/#code=ZihvLGgsdyk9KGI9MzIqb25lcyhJbnQzMiw2LDgpO2JbWzEsNF0sOl09OTU7YltbMiwzLDIzLDI0XV09MTI0O2I9cmVwbWF0KGIsaCx3KVsxOmgsbysxOm8rdysxXTtiWzosZW5kXT0xMDtwcmludChyZWludGVycHJldChDaGFyLGInKS4uLikpCmYoMiwgMTgsNDAp&input=)
(Thanks, @glen-o for the extra byte-saving tip!)
[Answer]
## JavaScript, ~~172~~ ~~168~~ ~~165~~ ~~157~~ ~~147~~ ~~142~~ 137 bytes
```
(O,W,H)=>{t='_'.repeat(W),x='|       '.repeat(W),f=t+`
`;for(i=0;++i<H;)f+=(!(i%3)?t:(i%6)>3?x.substr(O,W):x.substr(8-O,W))+`
`;return f}
```
```
N = (O,W,H)=>{t='_'.repeat(W),x='|       '.repeat(W),f=t+`
`;for(i=0;++i<H;)f+=(!(i%3)?t:(i%6)>3?x.substr(O,W):x.substr(8-O,W))+`
`;return f}
let test_data = [[6,44,11],
                 [2,20,10],
                 [1,1,1],
                 [1,2,3],
                 [3,80,21]];
for (test of test_data)
    console.log(N(...test));
```
[Answer]
# Dyalog APL, 29 bytes
`↑⎕⍴⎕⍴¨a,4⌽¨a←'_',2⍴⊂⌽⎕⌽¯8↑'|'`
tests:
[`6 44 11`](http://tryapl.org/?a=F%20W%20H%u21906%2044%2011%20%u22C4%20%u2191H%u2374W%u2374%A8a%2C4%u233D%A8a%u2190%27_%27%2C2%u2374%u2282%u233DF%u233D%AF8%u2191%27%7C%27&run),
[`2 20 10`](http://tryapl.org/?a=F%20W%20H%u21902%2020%2010%20%u22C4%20%u2191H%u2374W%u2374%A8a%2C4%u233D%A8a%u2190%27_%27%2C2%u2374%u2282%u233DF%u233D%AF8%u2191%27%7C%27&run),
[`1 1 1`](http://tryapl.org/?a=F%20W%20H%u21901%201%201%20%u22C4%20%u2191H%u2374W%u2374%A8a%2C4%u233D%A8a%u2190%27_%27%2C2%u2374%u2282%u233DF%u233D%AF8%u2191%27%7C%27&run),
[`1 2 3`](http://tryapl.org/?a=F%20W%20H%u21901%202%203%20%u22C4%20%u2191H%u2374W%u2374%A8a%2C4%u233D%A8a%u2190%27_%27%2C2%u2374%u2282%u233DF%u233D%AF8%u2191%27%7C%27&run),
[`3 80 21`](http://tryapl.org/?a=F%20W%20H%u21903%2080%2021%20%u22C4%20%u2191H%u2374W%u2374%A8a%2C4%u233D%A8a%u2190%27_%27%2C2%u2374%u2282%u233DF%u233D%AF8%u2191%27%7C%27&run)
`⎕` is evaluated input; as the expression executes from right to left, it prompts for `F`, `W`, and `H` in that order
`¯8↑'|'` is `' |'`
`⎕⌽` is rotate, it chops F chars from the front and puts them at the end of the string
the other `⌽` means reverse
`'_',2⍴⊂` creates a 3-tuple of '\_' followed by two separate copies of the string so far
`a,4⌽¨a←` append the 4-rotation of everything so far, we end up with a 6-tuple
`⎕⍴¨` reshape each element to the width
`⎕⍴` reshape to the height
`↑` mix vector of vectors into a matrix
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~25~~ ~~24~~ 23 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
'_'|7úD)³∍ε73N3÷è¹-._²∍
```
-1 byte thanks to *@Grimmy*.
Inputs in the order \$\text{offset}, \text{width}, \text{height}\$.
Output as a list of string-lines.
[Try it online](https://tio.run/##yy9OTMpM/f9fPV69xvzwLhfNQ5sfdfSe22pu7Gd8ePvhFYd26urFH9oEFPtfe2j3fzMuExMuQ0MA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpSbKWgZF@pw6XkX1oC5AJ5OpUJh1bGhIX@V49XrzE/vMtF89C6Rx2957aaG/sZH95@eEWErl58JFDkf@2h3TqaMYe22f@PjjbTMTHRMTSM1Yk20jEy0DE0ALIMdYAQTBvpGANpYx0LAx0jkIiBjqWOSWwsAA).
**Explanation:**
```
'_           '# Push "_"
'|           '# Push "|"
  7ú          # Pad 7 leading spaces: "       |"
    D         # Duplicate it
     )        # Wrap all three values on the stack into a list
³∍            # Extend this list to the (third) input-height amount of lines
              #  i.e. height=7 → ["_","       |","       |","_","       |","       |","_"]
ε             # Map over each line:
   N          #  Push the (0-based) map-index
    3÷        #  Integer-divide it by 3
 73   è       #  Index it into 73 (0-based and with wraparound)
              #   i.e. indices=[0,1,2,3,4,5,6,7,...] → [7,7,7,3,3,3,7,7,...]
       ¹+     #  Subtract the (first) input-offset
              #   i.e. offset=6 → [-3,-3,-3,1,1,1,-3,-3,...]
         ._   #  Rotate the string that many times towards the left
              #   i.e. ["_","       |","       |","_","       |","       |","_"] and
              #     [-3,-3,-3,1,1,1,-3] → ["_","      | ","      | ","_","  |     ","  |     ","_"]
           ²∍ #  After this inner loop: push the (second) input-width
              #  Extend/shorten the line to a size equal to the (second) input-width
              #   i.e. width=5 and line="   |    " → "   | "
              #   i.e. width=20 and line="   |    " → "   |       |       |"
              #   i.e. width=5 and line="_" → "_____"
              #   i.e. width=20 and line="_" → "____________________"
              # (after which the list of string-lines is output implicitly as result)
```
`73N3÷è` could alternatively be `₃€ÐÍNè` for the same byte-count:
[Try it online](https://tio.run/##ATsAxP9vc2FiaWX//ydfJ3w3w7pEKcKz4oiNzrXigoPigqzDkMONTsOowrktLl/CsuKIjf99wrv/Ngo0NAoxMQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpSbKWgZF@pw6XkX1oC5AJ5OpUJh1bGhIX@V49XrzE/vMtF89C6Rx2957Y@amp@1LTm8ITDvX6HV0To6sVHAoX/1x7araMZc2ib/f/oaDMdExMdQ8NYnWgjHSMDHUMDIMtQBwjBtJGOMZA21rEw0DECiRjoWOqYxMYCAA).
```
 ₃            #  Push builtin 95
  €Ð          #  Triplicate each digit: [9,9,9,5,5,5]
    Í         #  Decrease each by 2: [7,7,7,3,3,3]
     Nè       #  Index the (0-based) map-index into this (0-based and with wraparound)
```
[Answer]
# [Actually](https://github.com/Mego/Seriously), ~~44~~ ~~43~~ 40 bytes
This is an Actually port of the algorithm in [Neil's JS answer](https://codegolf.stackexchange.com/a/90076/47581). Golfing suggestions welcome. [Try it online!](https://tio.run/##S0wuKU3Myan8///R1OmPps4tetSzwNpMQ9VE7dHUOeZxcY@mzlavMVdSUNLS1ioBchw8QCLxWsYaqpGej3oW@mb@/29oyGViwmUGAA "Actually – Try It Online")
```
╗╝r⌠;6(%4&╜7^^╛'|7" "*+*t╛@H╛'_*3(%YI⌡Mi
```
**Ungolfing:**
```
          Takes implicit input in the order h, w, f.
╗╝        Save f to register 0. Save w to register 1.
r⌠...⌡M   Map over range [0..h-1]. Call this variable i.
  ;         Duplicate i
  6(%       i%6...
  4&        ...&4
  ╜7^^      ...^i^7. Call it c.
  ╛         Push w.
  '|7" "*+  The string "       |"
  *t╛@H     (("       |" * w)[c:])[:w]
  ╛'_*      Push "_" * w
  3(%       Push 3, move duplicate i to TOS, mod.
  YI        If not i%3, take "_"*w, else (("       |" * w)[c:])[:w]
            Function ends here.
i         Flatten the resulting list and print the bricks implicitly.
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~101~~ 88 bytes
```
param($n,$w,$h)0..--$h|%{(('|       '*$w|% S*g(8-$n+4*($_%6-gt3))$w),('_'*$w))[!($_%3)]}
```
[Try it online!](https://tio.run/##LY3RCoJAEEXf9ys2GdsZG2NXJSLoK@otRCQsH8xEhX1Iv31zrWG4nDt34HZvW/VDXTWNg8f547qyL18ILYNlqEnv93EM9RR@ENUkf6MisFMoL9ETjzG0uyxCKMJD/BxTIrDEqAr/Q3Tb@CSlfHazEIgHzjI2hlhgwolmoz0aln7/mLBMPaYsj3qxhmipF744uFbDKO/lUJ0kFMF6k1t4LOamc69m1SRfI6XE7L4 "PowerShell – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 30 bytes
```
(n₃[¹\_*,|7\|꘍¹*⁰ǔǔn3ḭ∷[4ǔ]¹Ẏ,
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%28n%E2%82%83%5B%C2%B9%5C_*%2C%7C7%5C%7C%EA%98%8D%C2%B9*%E2%81%B0%C7%94%C7%94n3%E1%B8%AD%E2%88%B7%5B4%C7%94%5D%C2%B9%E1%BA%8E%2C&inputs=10%0A44%0A1&header=&footer=)
A big mess.
```
(                              # (height) times (to make each row)
 n₃[                           # If the iteration is divisible by 3 (flat row) then...
    ¹\_*,                      # (width) underscores
         |                     # Else (part of a brick)...
          7\|꘍                 # Prepend seven spaces to an underscore
              ¹*               # Repeat (width) times
                ⁰ǔǔ            # Cycle by (offset), then cycle once more
                   n3ḭ∷[  ]    # If it's an offset row
                        4ǔ     # Cycle once more
                           ¹Ẏ, # Trim to the correct length and print.
```
[Answer]
# Octave ~~80~~ 76 bytes
```
% in file codegolf.m
c(6,8)=0;c([1,4],:)=63;c([2,3,23,24])=92;char(repmat(c+32,h,w)(1:h,o+1:o+w))
```
to run from terminal: `octave --eval "o=2;h=18;w=44; codegolf"`
(alternatively, if you think the terminal call is cheating :p then an anonymous function implementation takes 86 bytes :)
```
c(6,8)=0;c([1,4],:)=63;c([2,3,23,24])=92;f=@(o,h,w)char(repmat(c+32,h,w)(1:h,o+1:o+w))
```
Call `f(2,18,44)` at the octave interpreter.
[Answer]
# Bash + Sed, ~~411~~ ~~395~~ ~~381~~ 370 bytes:
```
F=`printf '_%.s' $(eval echo {1..$2})`;V="       |";(($[($2-$1)/8]>0))&&L=`printf "$V%.s" $(eval echo {1..$[($2-$1)/8]})`||L=;Z=`printf "%$1.s|%s\n" e "$L"`;I=$[($2-(${#Z}-4))/8];(($I>0))&&W=`printf "$V%.s" $(eval echo {1..$I})`||W=;J=${Z:4}$W;for i in `eval echo {1..$[$3/3+1]}`;{ (($[$i%2]<1))&&O+="$F\n$J\n$J\n"||O+="$F\n$Z\n$Z\n";};echo "`echo -e "$O"|sed -n 1,$3p`"
```
Well, here is my very first answer in Bash, or any shell scripting language for that matter. This is also by far the longest answer here. Takes in a sequence of space-separated command line arguments in the format `Offset Width Height`. This can probably be a lot shorter than it currently is, so any tips and/or tricks for golfing this down more are appreciated.
[Answer]
## Delphi/Object Pascal, 305, 302, 292 bytes
Full console program that reads 3 parameters.
```
uses SySutils,Math;var i,q,o,w,h:byte;begin o:=StrToInt(paramstr(1));w:=StrToInt(paramstr(2));h:=StrToInt(paramstr(3));for q:=0to h-1do begin for i:=1to w do if q mod 3=0then Write('_')else if IfThen(Odd(q div 3),((i+o)mod 8),((i-o)mod 8))=1then Write('|')else Write(' ');Writeln('');end end.
```
### ungolfed
```
uses
  SySutils,
  Math;
var
  i,q,o,w,h:byte;
begin
  o:=StrToInt(paramstr(1));
  w:=StrToInt(paramstr(2));
  h:=StrToInt(paramstr(3));
  for q := 0 to h-1 do
  begin
    for i := 1 to w do
      if q mod 3 = 0  then
        Write('_')
      else
        if IfThen(Odd(q div 3),((i+o)mod 8),((i-o)mod 8)) = 1 then
          Write('|')
        else Write(' ');
    Writeln('');
  end
end.
```
Sadly, Delphi does not have a ternary operator and it is quite a verbose language.
### test case
```
D:\Test\CodeGolfWall\Win32\Debug>Project1.exe 2 20 10
____________________
  |       |       |
  |       |       |
____________________
      |       |
      |       |
____________________
  |       |       |
  |       |       |
____________________
D:\Test\CodeGolfWall\Win32\Debug>Project1.exe 6 44 11
____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |
  |       |       |       |       |       |
____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |
```
Edit: Could shave of 3 bytes by using byte as type for all variables.
Edit 2: And console applications do not *need* the program declaration, -10
[Answer]
# JavaScript (ES6), ~~81 78~~ 77 bytes
*Saved 3 bytes thanks to @mypronounismonicareinstate*
Takes input as `(F, W)(H)`.
```
(F,W,x=y=0)=>g=H=>y<H?`
|_ `[x++<W?y%3?(x+~F^y/3<<2)&7?3:1:2:x=+!++y]+g(H):''
```
[Try it online!](https://tio.run/##bczBCsIgAIDhe09hh5qi1dRRITpvY2@wQ1QbaxvFmNEiFKJXN6@xzh//f6te1Vg/rvfnajCXxrfKw4wUxCqnYqTSTuUqdTLX5ex9BuXBYiwL7RZcQ4s/2cltuJQMLXeaCyqYsArPMXZH3MEciSjytRlG0zfr3nSwhVsCkgRBShGa/QojgMVB4olQAgBFENC/woLwiXAC9uHGQuO/ "JavaScript (Node.js) – Try It Online")
]


[Question]
      []


[Question]
      [
## Background
I have a collection of "weekday socks", which are seven pairs of socks labeled by the days of the week.
When I wash my socks, they end up in a pile, and I must arrange them into the correct pairs before putting them into the closet.
My strategy is to pull one random sock from the pile at a time and put it on a drawer.
Whenever there's a matching pair of socks on the drawer, I tie them together and put them in the closet.
Your task is to simulate this random process and return the number of draws required to find the first matching pair.
## Input
Your input is an integer **N ≥ 1**.
It represents the "number of days in a week": there are **N** pairs of socks in the pile, and each pair has a distinct label.
If necessary, you may also take a PRNG seed as input.
## Output
Your output is the number of socks I have to draw before the first matching pair is found.
For example, if the first two socks already form a matching pair, the output is `2`.
Of course, the output is random, and depends on the drawing order.
We assume that *all drawing orders are equally likely*, so that each time a sock is drawn, the choice is uniform and independent from all other choices.
## Example
Let **N = 3**, so that we have 6 socks in total, labeled **A A B B C C**.
One possible run of the "sock-drawing protocol" is as follows:
```
       | Pile   | Drawer | Pairs
Begin  | AABBCC | -      | -
Draw B | AABCC  | B      | -
Draw C | AABC   | BC     | -
Draw B | AAC    | C      | BB
Draw A | AC     | AC     | BB
Draw A | C      | C      | AA BB
Draw C | -      | -      | AA BB CC
```
The first matching pair was found after drawing the second **B**, which was the third sock to be drawn, so the correct output is `3`.
## Rules and scoring
You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
Input and output can be in any reasonable format, including unary (string of `1`s).
You may assume that your language's built-in RNG is perfect.
You don't have to actually simulate the sock-drawing protocol, as long as your outputs have the correct probability distribution.
## "Test cases"
Here are the approximate probabilities of all outputs for the input **N = 7**:
```
Output       2     3     4     5     6     7     8
Probability  0.077 0.154 0.210 0.224 0.186 0.112 0.037
```
To test your solution, you can run it for, say, 40 000 times and see whether the output distribution is reasonably close to this.

[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ḤX€Ṛ<RTḢ
```
[Try it online!](http://jelly.tryitonline.net/#code=4bikWOKCrOG5mjxSVOG4og&input=&args=MTAw) or [verify the distribution for **N = 7**](http://jelly.tryitonline.net/#code=4bikWOKCrOG5mjxSVOG4ogrigJjCteKAmXg0yLc0w4figqzEi8OQ4oKsUsO3NMi3NMW8QFJH&input=&args=Nw).
### Background
Let **n** be the number of pairs; there are **2n** individual socks.
For the first draw, there are **2n** socks and **0** of them would result in a matching pair. Therefore, the probability of success is **0 / 2n = 0**.
Since the first draw wasn't successful, there are **2n - 1** socks on the pile and **1** of them would result in a matching pair. Therefore, the probability of success is **1 / (2n - 1)**.
*If* the second draw wasn't successful, there are **2n - 2** socks on the pile and **2** of them would result in a matching pair. Therefore, the probability of success is **2 / (2n - 2)**.
In general, if the first **k** draws were unsuccessful, there are **2n - k** socks on the pile and **2** of them would result in a matching pair. Therefore, the probability of success is **k / (2n - k)**.
Finally, if none of the first **n** draws was successful, there are **2n - k** socks on the pile and all of them would result in a matching pair. Therefore, the probability of success is **n / (2n - n) = 1**.
### How it works
```
ḤX€Ṛ<RTḢ  Main link. Argument: n
Ḥ         Unhalve; yield 2n.
 X€       Map `random draw' over [1, ..., 2n], pseudo-randomly choosing an integer
          from [1, ..., k] for each k in [1, ..., 2n].
   Ṛ      Reverse the resulting array.
     R    Range; yield [1, ..., n].
    <     Perform vectorized comparison.
          Comparing k with the integer chosen from [1, ..., 2n - (k - 1)] yields 1
          with probability (k - 1) / (2n - (k - 1)), as desired.
          The latter half of elements of the left argument do not have a counter-
          part in the right argument, so they are left untouched and thus truthy.
      T   Truth; yield all indices of non-zero integers.
       Ḣ  Head; extract the first one.
```
[Answer]
## Jelly, 8 bytes
```
Rx2ẊĠṪ€Ṃ
```
[Try it online!](http://jelly.tryitonline.net/#code=Ungy4bqKxKDhuarigqzhuYI&input=&args=NQ)
```
R    generate [1, 2, ..., n]
x2   duplicate every element (two socks of each pair)
Ẋ    shuffle the list, to represent the order in which socks are drawn
Ġ    group indices by value. this will produce a list of pairs of indices;
       each pair represents the point in time at which each of the corresponding
       socks were drawn
Ṫ€   take the last element of each pair. this returns an array of n integers
       which represent the points in time at which a matching sock was drawn
Ṃ    minimum, find the first point at which a matching sock was drawn
```
To verify, [here is a version](http://jelly.tryitonline.net/#code=Ungy4bqKwqnEoOG5quKCrOG5gizCrg&input=&args=NQ) that displays both the desired output and the result of the "shuffle list" operation (to see what order socks were drawn in).
[Answer]
# Python, 66 bytes
```
from random import*
f=lambda n,k=1:k>randint(1,n*2)or-~f(n-.5,k+1)
```
Dennis thought up a clever way to rearrange things, saving 5 bytes.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~16~~ 15 bytes
```
Q:"r@qGEy-/<?@.
```
[Try it online!](http://matl.tryitonline.net/#code=UToickBxR0V5LS88P0Au&input=Mw) Or [observe the empirical distribution](http://matl.tryitonline.net/#code=MWUzOiJHClE6InJAcUdFeS0vPD9ALgpdXV0Kdkc6UT1ZbTVNd3Y&input=Nw) for 1000 samples in the *N*=7 case (it takes a while).
This **directly generates the random variable** representing the result, based on its probability distribution. Let *N* be the number of sock pairs, and let *p*(*k*) denote the probability that the *k*-th draw is successful, conditioned on the fact that the *k*-1-th draw was not succesful. Then (see also [here](http://gondolin.blogspot.com.es/2009/04/socks-problem.html)):
* *p*(1) is obviously 0. You can't have a pair with a single sock.
* *p*(2) is 1/(2\**N*−1). At the second draw there is one winning sock that may be chosen out of 2\**N*−1 remaining socks.
* *p*(3) is 2/(2\**N*−2). At the third draw there are 2 winning socks out of 2\**N*−2. The number of winning socks is 2 because the two socks you got after the second draw were different.
* In general, by the same reasoning, *p*(*k*) is (*k*−1)/(2\**N*−*k*+1)
* By the above formula, *p*(*N*+1) is 1. If you get to the *N*+1-th draw you are guaranteed to succeed then.
So the code iterates for a maximum of *N*+1 draws. At the *k*-th draw a random variable is generated that equals 1 with probability (*k*-1)/(2\**N*-*k*), or 0 otherwise. Whenever the random variable equals 1 (the draw has been succesful) the process stops and the current *k* is output.
```
Q:      % Input N implicitly. Generate [1 2 ... N+1] (values of draw index, k)
"       % For each
  r     %   Random variable uniformly distributed on the interval (0,1)
  @q    %   Push iteration index, k-1
  GE    %   Push 2*N
  y     %   Duplicate: push k-1 again
  -     %   Subtract: gives 2*N-k+1
  /     %   Divide: gives (k-1)/(2*N-k+1)
  <     %   Push 1 if random value is less than (k-1)/(2*N-k+1), 0 otherwise
  ?     %   If we got a 1
    @   %     Push k
    .   %     Break loop
        %   End if implicitly
        % End loop implicitly
        % Display implicitly
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~14~~ 13 bytes
```
EZ@G\&=XRafX<
```
[Try it online!](http://matl.tryitonline.net/#code=RVpAR1wmPVhSYWZYPA&input=Mw) Or [observe the empirical distribution](http://matl.tryitonline.net/#code=NGUzOiJHCkVaQEdcJj1YUmFmWDwKXQp2RzpRPVltNU13dg&input=Nw) for 4000 samples in the *N*=7 case (it takes a while).
```
E      % Input N implicitly. Multiply by 2
Z@     % Random permutation of [1 2 ... 2*N]
G\     % Modulo N: random permutation of [0 0 1 1 ... N-1 N-1]
&=     % Compare all pairs for equality. Gives an N×N matrix
XR     % Upper triangular part excluding the diagonal
a      % True for each column if it contains at least one true entry
f      % Get indices of true values
X<     % Take minimum. Implicitly display
```
[Answer]
# JavaScript, ~~77~~ 73 bytes
```
n=>{p={};for(i=n;i--;p[i]=2);while(--p[n*Math.random()|0])i++;return i+2}
```
**Explanation**
```
var f = (n) => {
    var index;      // used first to initialize pile, then as counter
    var pile = {};  // sock pile

    // start with index = n
    // check that index > 0, then decrement
    // put 2 socks in pile at index
    for(index = n; index--; pile[index] = 2);
    // index is now -1, reuse for counter

    // pick random sock out of pile and decrement its count
    // continue loop if removed sock was not the last
    while(--pile[n * Math.random() | 0]) {
        index++;    // increment counter
    }
    // loop finishes before incrementing counter when first matching pair is removed
    // add 1 to counter to account for initial value of -1
    // add 1 to counter to account for drawing of first matching pair
    return index + 2;
};
```
[Answer]
## CJam, 17 bytes
```
ri,2*mr{L+:L(&}#)
```
[Test it here.](http://cjam.aditsu.net/#code=ri%2C2*mr%7BL%2B%3AL(%26%7D%23)p&input=7)
[Answer]
# Python 3, ~~142~~ ~~105~~ 104 bytes
Thanks to *Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ* for saving one byte!
My first answer:
```
import random
i=[x/2 for x in range(int(2*input()))]
d=[]
a=0
random.shuffle(i)
while 1:
 b=i.pop()
 if b in d:
  print(a)
  s
 d=d+[b]
 a+=1
```
My new answer:
```
from random import*
i=range(int(input()))*2
shuffle(i)
j=0
for x in i:
 if x in i[:j]:print(1+j)+s
 j+=1
```
Both exit with a `NameError` on `s`.
[Answer]
# R, 49
```
N=scan();which(duplicated(sample(rep(1:N,2))))[1]
```
I'm sure there must be a better way of doing this in R! I tried doing something cleverer but it didn't work.
Edit: Improved by @bouncyball since it doesn't have to be a function.
[Answer]
# Python 2, 101 bytes
```
from random import*
d=[]
p=range(input())*2
shuffle(p)
while list(set(d))==d:d+=p.pop(),
print len(d)
```
[Answer]
## VBA, 61 bytes
```
Function K(D):While 2*D-K>K/Rnd:K=K+1:Wend:K=K+1:End Function
```
- models the shifting probability of sock match given previous failure to match. At the point of evaluation, K is "socks in hand", so draw number is one more.
[Answer]
# Pyth, 14 bytes
```
lhfnT{T._.S*2S
```
Explanation:
```
       ._        #Start with a list of all prefixes of
         .S      #a randomly shuffled
           *2S   #range from 1 to input (implicit), times 2.
  f              #filter this to only include elements where
   nT{T          #element is not equal to deduplicated self (i.e. it has duplicates)
lh               #print the length of the first element of that filtered list
```
]


[Question]
      [
If you don't know what the [Tower of Hanoi](https://en.wikipedia.org/wiki/Tower_of_Hanoi) is, I'll explain it briefly: There are three rods and some discs each of which has a different size. In the beginning all discs are on the first tower, in sorted order: The biggest one is at the bottom, the smallest at the top. The goal is to bring all the discs over to the third rod. Sounds easy? Here's the catch: You can't place a disc on top of a disc that is smaller than the other disc; you can only hold one disc in your hand at a time to move them to another rod and you can only place the disc on rods, not on the table, you sneaky bastard.
### ascii example solution:
```
  A      B      C
  |      |      |
 _|_     |      |
__|__    |      |
  A      B      C
  |      |      |
  |      |      |
__|__   _|_     |
  A      B      C
  |      |      |
  |      |      |
  |     _|_   __|__
  A      B      C
  |      |      |
  |      |     _|_
  |      |    __|__
```
# Challenge
There are three rods called A,B and C. (You can also call them 1,2 and 3 respectivly if that helps) In the beginning all n discs are on rod A(1).
Your challenge is to verify a solution for the tower of hanoi. You'll need to make sure that:
1. In the end all n discs are on rod C(3).
2. For any given disc at any given state there is no smaller disc below it.
3. No obvious errors like trying to take discs from an empty rod or moving discs to nonexistant rods.
(the solution does not have to be optimal.)
# Input
Your program will receive two inputs:
1. The number of discs n (an integer)
2. The moves which are taken, which will consist of a set of tuples of: (tower to take the currently uppermost disc from),(tower to take this disc to) where each tuple refers to a move. You can choose how they are represented. For example something like the following ways of representing the solution for n=2 which I've drawn in ascii above. (I'll use the first one in the test cases, because it's easy on the eyes):
"A->B ; A->C ; B->C"
[("A","B"),("A","C"),("B","C")]
[(1,2),(1,3),(2,3)]
"ABACBC"
[1,2,1,3,2,3]
# Output
* Truthy, if the conditions that can be found under "challenge" hold.
* Falsy, if they don't.
# Test cases:
### True:
```
n=1, "A->C"
n=1, "A->B ; B->C"
n=2, "A->B ; A->C ; B->C"
n=2, "A->C ; C->B ; A->C ; B->C"
n=2, "A->C ; A->B ; C->B ; B->A ; B->C ; A->C"
n=3, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C"
n=4, "A->B ; A->C ; B->C ; A->B ; C->A ; C->B ; A->B ; A->C ; B->C ; B->A ; C->A ; B->C ; A->B ; A->C ; B->C"
```
### False:
*3rd one suggested by @MartinEnder, 7th by @Joffan*
```
n=1, "A->B"
n=1, "C->A"
n=2, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C"
n=2, "A->B ; A->C ; C->B"
n=2, "A->C ; A->B ; C->B ; B->A"
n=2, "A->C ; A->C"
n=3, "A->B ; A->D; A->C ; D->C ; A->C"
n=3, "A->C ; A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C"
n=3, "A->C ; A->B ; C->B ; A->B ; B->C ; B->A ; B->C ; A->C"
n=3, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; C->B"
n=4, "A->B ; A->C ; B->C ; A->B ; C->A ; C->B ; A->B ; A->C ; B->C ; B->A ; C->A ; B->C ; A->B ; A->C"
n=4, "A->B ; A->B ; A->B ; A->C ; B->C ; B->C ; B->C"
```
This is [code-golf](https://codegolf.stackexchange.com/questions/tagged/code-golf), shortest solution wins. Standard rules and loopholes apply. No batteries included.

[Answer]
## [Retina](https://github.com/m-ender/retina), ~~167~~ ~~165~~ ~~157~~ ~~150~~ 123 bytes
This totally looks like a challenge that should be solved with a single regex... (despite the header saying "Retina", this is just a vanilla .NET regex, matching valid inputs).
```
^(?=\D*((?=(?<3>1+))1)+)((?=A(?<1-3>.+)|B(?<1-4>.+)|C(?<1-5>.+)).(?=A.*(?!\3)(\1)|B.*(?!\4)(\1)|C.*(?!\5)(\1)).)+(?!\3|\4)1
```
Input format is the list of instructions of the form `AB`, followed by `n` in unary using the digit `1`. There are no separators. Output is `1` for valid and `0` for invalid.
[Try it online!](http://retina.tryitonline.net/#code=JWBeKD89XEQqKCg_PSg_PDM-MSspKTEpKykoKD89QSg_PDEtMz4uKyl8Qig_PDEtND4uKyl8Qyg_PDEtNT4uKykpLig_PUEuKig_IVwzKShcMSl8Qi4qKD8hXDQpKFwxKXxDLiooPyFcNSkoXDEpKS4pKyg_IVwzfFw0KTE&input=QUMxCkFCQkMxCkFCQUNCQzExCkFDQ0JBQ0JDMTEKQUNBQkNCQkFCQ0FDMTEKQUNBQkNCQUNCQUJDQUMxMTEKQUJBQ0JDQUJDQUNCQUJBQ0JDQkFDQUJDQUJBQ0JDMTExMQpBQjEKQ0ExCkFCQUNDQjExCkFDQUJDQkJBMTEKQUNBQzExCkFDQUNBQkNCQUNCQUJDQUMxMTEKQUNBQkNCQUJCQ0JBQkNBQzExMQpBQ0FCQ0JBQ0JBQkNDQjExMQpBQkFDQkNBQkNBQ0JBQkFDQkNCQUNBQkNBQkFDMTExMQpBQkFCQUJBQ0JDQkNCQzExMTE) (The first two characters enable a linefeed-separated test suite.)
Alternative solution, same byte count:
```
^(?=\D*((?=(?<3>1+))1)+)((?=A(?<1-3>.+)|B(?<1-4>.+)|C(?<1-5>.+)).(?=A.*(?!\3)(\1)|B.*(?!\4)(\1)|C.*(?!\5)(\1)).)+(?<-5>1)+$
```
This can possibly be shortened by using `1`, `11` and `111` instead of `A`, `B` and `C` but I'll have to look into that later. It might also be shorter to split the program into several stages, but where's the challenge in that? ;)
### Explanation
This solution makes heavy use of .NET's balancing groups. For a full explanation [see my post on Stack Overflow](https://stackoverflow.com/a/17004406/1633117), but the gist is that capturing groups in .NET are stacks, where each new capture pushes another substring and where it's also possible to pop from such a stack again. This lets you count various quantities in a string. In this case it lets us implement the three rods directly as three different capturing groups where each disc is represented by a capture.
To move discs around between rods we make use of a weird quirk of the `(?<A-B>...)` syntax. Normally, this pops a capture from stack `B` and pushes onto stack `A` the string between that popped capture and the beginning of this group. So `(?<A>a).(?<B-A>c)` matched against `abc` would leave `A` empty and `B` with `b` (as opposed to `c`). However, due to .NET variable-length lookbehinds it's possible for the captures of `(?<A>...)` and `(?<B-A>...)` to overlap. For whatever reason, if that's the case, the *intersection* of the two groups is pushed onto `B`. I've detailed this behaviour in the "advanced section" on balancing groups [in this answer](https://stackoverflow.com/a/36047989/1633117).
On to the regex. Rods `A`, `B` and `C` correspond to groups `3`, `4` and `5` in the regex. Let's start by initialising rod `A`:
```
^                 # Ensure that we start at the beginning of the input.
(?=               # Lookahead so that we don't actually move the cursor.
  \D*             # Skip all the instructions by matching non-digit characters.
  (               # For each 1 at the end of the input...
    (?=(?<3>1+))  # ...push the remainder of the string (including that 1)
                  # onto stack 3.
  1)+
)
```
So e.g. if the input ends with `111`, then group 3/rod `A` will now hold the list of captures `[111, 11, 1]` (the top being on the right).
The next bit of the code has the following structure:
```
(
  (?=A...|B...|C...).
  (?=A...|B...|C...).
)+
```
Each iteration of this loop processes one instruction. The first alternation pulls a disc from the given rod (onto a temporary group), the second alternation puts that that disc onto the other given rod. We'll see in a moment how this works and how we ensure that the move is valid.
First, taking a disc off the source rod:
```
(?=
  A(?<1-3>.+)
|
  B(?<1-4>.+)
|
  C(?<1-5>.+)
)
```
This uses the weird group-intersection behaviour I've described above. Note that group `3`, `4` and `5` will always hold substrings of `1`s at the end of the string whose length corresponds to the disc's size. We now use `(?<1-N>.+)` to pop the top disc off stack `N` and push the intersection of this substring with the match `.+` onto stack `1`. Since `.+` always necessarily covers the entire capture popped off `N`, we know that this simply moves the capture.
Next, we put this disc from stack `1` onto the stack corresponding to the second rod:
```
(?=
  A.*(?!\3)(\1)
|
  B.*(?!\4)(\1)
|
  C.*(?!\5)(\1)
)
```
Note that we don't have to clean up stack `1`, we can just leave the disc there, since we'll put a new one on top before using the stack again. That means we can avoid the `(?<A-B>...)` syntax and simply copy the string over with `(\1)`. To ensure that the move is valid we use the negative lookahead `(?!\N)`. This ensures that, from the position where we want to match the current disc, it's impossible to match the disc already on stack `N`. This can only happen if either a) `\N` will never match because the stack is completely empty or b)`the disc on top of stack`N`is larger than the one we're trying to match with`\1`.
Finally, all that's left is ensuring that a) we've matched all instructions and b) rods `A` and `B` are empty, so that all discs have been moved onto `C`.
```
(?!\3|\4)1
```
We simply check that neither `\3` nor `\4` can match (which is only the case if both are empty, because any actual disc *would* match) and that we can then match a `1` so that we haven't omitted any instructions.
[Answer]
# Java "only" ~~311 272 263 261 260 259~~ 256 bytes
Saved ~~39~~ countless bytes due to @Frozn noticing an older debug feature as well as some clever golfing tricks.
Golfed version
```
int i(int n,int[]m){int j=0,k=0,i=n;Stack<Integer>t,s[]=new Stack[3];for(;j<3;)s[j++]=new Stack();for(;i-->0;)s[0].push(i);for(;k<m.length;k+=2)if((t=s[m[k+1]]).size()>0&&s[m[k]].peek()>t.peek())return 0;else t.push(s[m[k]].pop());return s[2].size()<n?0:1;}
```
ungolfed with explanation and pretty printed stacks at each step
```
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package codegolf;
/**
 *
 * @author rohan
 */
import java.util.Arrays;
import java.util.Stack;
public class CodeGolf {
    //golfed version
    int i(int n,int[]m){int j=0,k=0,i=n;Stack<Integer>[] s=new Stack[3];for(;j<3;j++)s[j]=new Stack();for(;i-->0;)s[0].push(i);for(;k<m.length;System.out.println(Arrays.toString(s)),k+=2)if(!s[m[k+1]].isEmpty()&&s[m[k]].peek()>s[m[k+1]].peek())return 0;else s[m[k+1]].push(s[m[k]].pop());return s[2].size()==n?1:0;}
    /** Ungolfed
        * 0 as falsy 1 as truthy
        * @param n the number of disks
        * @param m represents the zero indexed stacks in the form of [from,to,from,to]
        * @return 0 or 1 if the puzzle got solved, bad moves result in an exception
        */
    int h(int n, int[] m) {
        //declarations
        int j = 0, k = 0, i = n;
        //create the poles
        Stack<Integer>[] s = new Stack[3];
        for (; j < 3; j++) {
            s[j] = new Stack();
        }
        //set up the first tower using the "downto operator
        for (; i-- > 0;) {
            s[0].push(i);
        }
    //go through and perform all the moves
        for (; k < m.length; System.out.println(Arrays.toString(s)), k += 2) {
            if (!s[m[k + 1]].isEmpty() && s[m[k]].peek() > s[m[k + 1]].peek()) {
                return 0;//bad move
            } else {
                s[m[k + 1]].push(s[m[k]].pop());
            }
        }
        return s[2].size() == n ? 1 : 0;// check if all the disks are done
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
    //test case
        System.out.println( new CodeGolf().h(3,new int[]{0,2,0,1,2,1,0,2,1,0,1,2,0,2})==1?"Good!":"Bad!");
    }
}
```
The ungolfed version has a feature where it will print out what the stacks look like at each step like so...
```
[[2, 1], [], [0]]
[[2], [1], [0]]
[[2], [1, 0], []]
[[], [1, 0], [2]]
[[0], [1], [2]]
[[0], [], [2, 1]]
[[], [], [2, 1, 0]]
Good!
```
[Answer]
# Python 2, ~~186~~ ~~167~~ ~~158~~ ~~135~~ ~~127~~ ~~115~~ ~~110~~ 102 bytes
```
n,m=input()
x=[range(n),[],[]]
for a,b in m:p=x[a].pop();e=x[b];e and 1/(p>e[-1]);e+=p,
if x[0]+x[1]:_
```
Takes input on STDIN in the following format:
```
(1,[(0,1),(1,2)])
```
That is, a Python tuple of the number of discs and a Python list of tuples of `(from_rod,to_rod)`. As in Python, the surrounding parentheses are optional. Rods are zero-indexed.
For example, this test case:
```
n=2; "A->B ; A->C ; B->C"
```
would be given as:
```
(2,[(0,1),(0,2),(1,2)])
```
If the solution is valid, outputs nothing and exits with an exit code of 0. If it is invalid, throws an exception and exits with an exit code of 1. Throws an `IndexError` if moving to a nonexistant rod or trying to take a disc off a rod that has no discs on it, a `ZeroDivisionError` if a disc is placed on top of a smaller disc, or a `NameError` if there are discs left on the first or second rods at the end.
*Saved 13 bytes thanks to @KarlKastor!*
*Saved 8 bytes thanks to @xnor!*
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~84~~ 80 Bytes
-5 bytes thanks to Martin Ender
```
~
 ~$'
$
ABC
{`^(.)(.*)( ~+)\1
$3$2$1
}`^(\W+)(\w)(.*)(?<=\1~+|\w)\2
$3$1$2
^AB
```
[Try it online!](http://retina.tryitonline.net/#code=JShHYAp-CiB-JCcKJApBQkMKe2BeKC4pKC4qKSggfispXDEKJDMkMiQxCn1gXihcVyspKFx3KSguKikoPzw9XDF-K3xcdylcMgokMyQxJDIKXkFCIA&input=QUN-CkFCQkN-CkFCQUNCQ35-CkFDQ0JBQ0JDfn4KQUNBQkNCQkFCQ0FDfn4KQUNBQkNCQUNCQUJDQUN-fn4KQUJBQ0JDQUJDQUNCQUJBQ0JDQkFDQUJDQUJBQ0JDfn5-fgpBQn4KQUNBQ34KQUNCQ34KQ0F-CkFCQUNDQn5-CkFDQUJDQkJBfn4KQUNBQ35-CkFDQUNBQkNCQUNCQUJDQUN-fn4KQUNBQkNCQUJCQ0JBQkNBQ35-fgpBQ0FCQ0JBQ0JBQkNDQn5-fgpBQkFDQkNBQkNBQ0JBQkFDQkNCQUNBQkNBQkFDfn5-fgpBQkFCQUJBQ0JDQkNCQ35-fn4KQUJBQn4KQUNBQkNCQUNCQUJDQUNDQUNBfn5-) (plus 5 bytes for line-by-line tests)
The code simulates a full game.
* Input is given as `ACABCBACBABCAC~~~`.
`~~~` means three discs.
* First four lines convert the input to the game format: `ACABCBACBABCAC ~~~ ~~ ~ABC`.
In the beginning the A rod has all 3 discs, and B and C rods are empty.
* Next we have a loop of two steps:
	+ Take the first letter in the line, which indicates the next source rod. Find this rod, and take the last disc on in. Remove the letter and move the disc to the stark (pick it up).

	In out example, after the first step, the text will look like:
	`~CABCBACBABCAC ~~~ ~~ABC`.
	+ In the second stage we find the target rod, and move the disc there. We validate the rod is empty, or has a bigger disc at the top: `ABCBACBABCAC ~~~ ~~AB ~C`.
* Finally we confirm the A and B rods are empty - this means all discs are in C (there's an extra space at the last line).
[Answer]
# Python 2.7, ~~173~~ ~~158~~ ~~138~~ ~~130~~ ~~127~~ 123 bytes:
```
r=range;a,b=input();U=[r(a,0,-1),[],[]]
for K,J in b:U[J]+=[U[K].pop()]if U[J]<[1]or U[K]<U[J]else Y
print U[-1]==r(a,0,-1)
```
Takes input through the stdin in the format `(<Number of Discs>,<Moves>)` where `<Moves>` is given as an array containing tuples corresponding to each move, which each contain a pair of comma separated integers. For instance, the test case:
```
n=3, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C"
```
given in the post would be given as:
```
(3,[(0,2),(0,1),(2,1),(0,2),(1,0),(1,2),(0,2)])
```
to my program. Outputs an `IndexError` if the 3rd condition isn't met, a `NameError` if the 2nd condition isn't met, and `False` if the 1st condition isn't met. Otherwise outputs `True`.
[Answer]
# VBA, ~~234~~ ~~217~~ ~~213~~ 196 bytes
```
Function H(N,S)
ReDim A(N)
While P<Len(S)
P=P+2:F=1*Mid(S,P-1,1):T=1*Mid(S,P,1)
E=E+(T>2):L=L+T-F
For i=1 To N
If A(i)=F Then A(i)=T:Exit For
E=E+(A(i)=T)+(i=N)
Next
Wend
H=L+9*E=2*N
End Function
```
Input format for moves is a string with an even number of digits (012). Invocation is in spreadsheet, =H([number of discs], [move string])
The array A holds the rod position of the various discs. A move is simply updating the first occurrence of the "From" rod number into the "To" rod number. If you encounter a "To" rod disc first, or no "From" rod disc, it's an invalid move. The total "rod value" of A is held in L, which needs to end at 2N. Errors are accumulated as a negative count in E.
In common with other solutions, "moving" a disc from a tower to the same tower is not forbidden. I could forbid it for another 6 bytes.
## Results
Function result in first column (the last n=3 case is my addition using an extra rod).
```
TRUE    1   02
TRUE    1   0112
TRUE    2   010212
TRUE    2   02210212
TRUE    2   020121101202
TRUE    3   02012102101202
TRUE    4   010212012021010212102012010212
FALSE   1   01
FALSE   1   20
FALSE   2   02012102101202
FALSE   2   010221
FALSE   2   02012110
FALSE   2   0202
FALSE   3   0202012102101202
FALSE   3   0201210112101202
FALSE   3   02012102101221
FALSE   3   0103023212
FALSE   4   0102120120210102121020120102
FALSE   4   01010102121212
```
[Answer]
# php, 141 bytes
```
<?php $a=$argv;for($t=[$f=range($a[++$i],1),[],[]];($r=array_pop($t[$a[++$i]]))&&$r<(end($t[$a[++$i]])?:$r+1);)$t[$a[$i]][]=$r;echo$t[2]==$f;
```
Command line script, takes input as the height then a series of array indexes (0 indexed) e.g. 1 0 2 or 2 0 1 0 2 1 2 for the 1 or 2 height shortest test cases.
Echos 1 on true cases and nothing on false ones.
Gives 2 notices and 1 warning so needs to be run in an environment that silences those.
[Answer]
# JavaScript (ES6), 108
```
n=>s=>!s.some(([x,y])=>s[y][s[y].push(v=s[x].pop())-2]<v|!v,s=[[...Array(s=n)].map(_=>s--),[],[]])&s[2][n-1]
```
**Input format:** function with 2 arguments
* arg 1, numeric, number of rings
* arg 2, array of strings, each string 2 characters '0','1','2'
**Output:** return 1 if ok, 0 if invalid, exception if nonexisting rod
**Less golfed** and explained
```
n=>a=>(
  // rods status, rod 0 full with an array n..1, rod 1 & 2 empty arrays
  s = [ [...Array(t=n)].map(_=>t--), [], [] ],
  // for each step in solution, evaluate function and stop if returns true
  err = a.some( ([x,y]) => {
    v = s[x].pop(); // pull disc from source rod
    // exception is s[x] is not defined
    if (!v) return 1; // error source rod is empty
    l = s[y].push(v); // push disc on dest rod, get number of discs in l
    // exception is s[y] is not defined
    if(s[y][l-2] < v) return 1; // error if undelying disc is smaller
  }),
  err ? 0 // return 0 if invalid move
  : s[2][n-1]; // il all moves valid, ok if the rod 2 has all the discs
)
```
**Test**
Note: the first row of the Test function is needed to convert the input format given in the question to the input expected by my function
```
F=
n=>s=>!s.some(([x,y])=>s[y][s[y].push(v=s[x].pop())-2]<v|!v,s=[[...Array(s=n)].map(_=>s--),[],[]])&s[2][n-1]
Out=x=>O.textContent+=x+'\n'
Test=s=>s.split`\n`.map(r=>[+(r=r.match(/\d+|.->./g)).shift(),r.map(x=>(parseInt(x[0],36)-10)+''+(parseInt(x[3],36)-10))])
.forEach(([n,s],i)=>{
  var r
  try {
    r = F(+n)(s);
  }
  catch (e) {
    r = 'Error invalid rod';
  }
  Out(++i+' n:'+n+' '+s+' -> '+r)
})
Out('OK')
Test(`n=1, "A->C"
n=1, "A->B ; B->C"
n=2, "A->B ; A->C ; B->C"
n=2, "A->C ; C->B ; A->C ; B->C"
n=2, "A->C ; A->B ; C->B ; B->A ; B->C ; A->C"
n=3, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C"
n=4, "A->B ; A->C ; B->C ; A->B ; C->A ; C->B ; A->B ; A->C ; B->C ; B->A ; C->A ; B->C ; A->B ; A->C ; B->C"`)
Out('\nFail')
Test( `n=1, "A->B"
n=1, "C->A"
n=2, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C"
n=2, "A->B ; A->C ; C->B"
n=2, "A->C ; A->B ; C->B ; B->A"
n=2, "A->C ; A->C"
n=3, "A->B ; A->D; A->C ; D->C ; A->C"
n=3, "A->C ; A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C"
n=3, "A->C ; A->B ; C->B ; A->B ; B->C ; B->A ; B->C ; A->C"
n=3, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; C->B"
n=4, "A->B ; A->C ; B->C ; A->B ; C->A ; C->B ; A->B ; A->C ; B->C ; B->A ; C->A ; B->C ; A->B ; A->C"
n=4, "A->B ; A->B ; A->B ; A->C ; B->C ; B->C ; B->C"`)
```
```
<pre id=O></pre>
```
]


[Question]
      [
Write a program or function that outputs an `L` if run on a little endian architecture or a `B` if run on a big endian architecture. Lower case output `l` or `b` is also acceptable.
There is no input.
Scoring is code golf, so the code with the fewest bytes wins.
**Edit:** *As per the comments below, I am clarifying that the entry must be able to run on either architecture.*
*I believe that there is only one answer that this affects, and that answer has clearly indicated that this is the case.*

[Answer]
# Python, 33 bytes
```
import sys
exit(sys.byteorder[0])
```
`sys.byteorder` is either `'little'` or `'big'` (and for those of you who will read this sentence without looking at the code, `[0]` means take the first character).
[Answer]
# C, 26 bytes
```
a=66<<24|76;f(){puts(&a);}
```
Assumes 32-bit `int` and ASCII characters. Tested on amd64 (little-endian) and mips (big-endian).
# GCC, 23 bytes
```
00000000: 613d 2742 0000 4c27 3b66 2829 7b70 7574  a='B..L';f(){put
00000010: 7328 2661 293b 7d                        s(&a);}
```
Suggested by feersum. The value of multi-character constants is implementation-dependent, but this seems to work in GCC. Tested on the same architectures.
[Answer]
# MATLAB / Octave, 24 bytes
```
[~,~,e]=computer;disp(e)
```
The [`computer`](http://es.mathworks.com/help/matlab/ref/computer.html) function gives information about, well, the computer it's running on. The third output is endianness: `L` or `B` for little- or big-endian respectively.
[Try it on Ideone](http://ideone.com/FpfrEb).
[Answer]
# JavaScript ES6, 50 bytes
```
_=>"BL"[new Int8Array(Int16Array.of(1).buffer)[0]]
```
I don’t know who decided it was a good idea for [TypedArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) objects to expose the native endianness of the interpreter, but here we are.
[Answer]
# C, ~~36~~ 35 bytes
**1 byte thanks to @algmyr and @owacoder.**
```
~~main(a){printf(\*(char\*)&a?"L":"B");}~~
main(a){putchar(66+10**(char*)&a);}
main(a){putchar("BL"[*(char*)&a]);}
```
* Version 1: [Ideone it!](http://ideone.com/uWicng)
* Version 2: [Ideone it!](http://ideone.com/OjpPrP)
* Version 3: [Ideone it!](http://ideone.com/DzmxIa)
Credits [here](https://stackoverflow.com/a/4181991/6211883).
Untested since I don't have a big-endian machine.
[Answer]
### Mathematica, 22
```
{B,L}[[$ByteOrdering]]
```
This probably breaks some rule about not using a built-in function but I'm not really interested in rube goldberging an alternative.
[Answer]
# C, 27
One byte longer, but here it is anyway:
```
f(){putchar(htons(19522));}
```
[Answer]
# PowerPC machine code - 20 bytes
PowerPC is bi-endian (the endianness can be set up at startup), so this code should conform to the challenge request of being able to run both on BE and LE machines. This is a function that *returns*1 `'L'` or `'B'` depending on the endianness currently set.
As a function, AFAICT it conforms the SVR4 PowerPC ABI (used by Linux on ppc32), the PowerOpen ABI (used e.g. by AIX) and the OS X ABI. In particular, it relies just on the fact that GPR 0 is a volatile scratch register, and GPR 3 is used to return "small" values.
```
00000000 <get_endian>:
   0:   7c 00 00 a6     mfmsr   r0
   4:   54 03 0f fe     rlwinm  r3,r0,1,31,31
   8:   1c 63 00 0a     mulli   r3,r3,10
   c:   38 63 00 42     addi    r3,r3,66
  10:   4e 80 00 20     blr
```
Now, it goes like this:
* the [MSR](https://en.wikipedia.org/wiki/Machine_state_register) is read into GP register 0; the MSR contains at bit 31 the endianness settings (0 = big endian; 1 = little endian);
* `rlwinm` extracts just that bit: it takes the value in GPR0, **r**otates **l**eft by 1 place (so that now is in position 0) and **m**asks it with 1 (the mask generated by those 31,312); the result is put into GP register 3;
* multiply the result by 10 and sum 66 (`'B'`) (10 is the difference between `'L'` and `'B'`)
* finally, return to the caller
---
### Notes
1. yep, the question does ask to *print*, but it's not clear how I should print stuff in assembly expected to run unmodified on different operating systems. =)
2. for those interested, see the [rlwinm](https://www.ibm.com/support/knowledgecenter/en/ssw_aix_71/com.ibm.aix.alangref/idalangref_rlwinm_rlinm_rtlwrdimm_instrs.htm) documentation; knowing next to nothing about PowerPC, I found this kind of instructions extremely interesting.
**2018 update**: Raymond Chen is publishing a series about the PowerPC architecture, you can find [here](https://blogs.msdn.microsoft.com/oldnewthing/20180810-00/?p=99465) his great post about `rlwinm` & friends.
[Answer]
# Java 8, ~~96, 64~~ 52 bytes
```
()->(""+java.nio.ByteOrder.nativeOrder()).charAt(0);
```
A golf based on [this SO answer](https://stackoverflow.com/a/9431652). All credit goes to @LeakyNun and @AlanTuning. Java keeps the loosing streak.
96 bytes:
```
 char e(){return java.nio.ByteOrder.nativeOrder().equals(java.nio.ByteOrder.BIG_ENDIAN)?'b':'l';}
```
64 bytes:
```
char e(){return(""+java.nio.ByteOrder.nativeOrder()).charAt(0);}
```
Untested b/c I don't have access to a big-endian machine.
[Answer]
# Perl, ~~38~~ 36 bytes
```
say+(pack"L",1 eq pack"V",1)?"L":"B"
```
Works by packing a number in the system's default byte order and comparing it to a number packed in little-endian byte order.
[Answer]
# (G)Forth, 24 bytes
```
here $4200004C , c@ emit
```
Assumes that cells are 32 bits (and that your Forth interpreter supports Gforth's [base prefixes](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/Number-Conversion.html#fnd-2)). It simply stores the number 0x4200004C in memory and then displays the byte at the low end.
[Answer]
# C, 34 bytes
This assumes ASCII character encoding
```
main(a){putchar(66+10**(char*)a);}
```
Call without argument.
Explanation:
On call, `a` will be 1. `*(char*)a` accesses the first byte of `a`, which on little-endian platforms will be 1, on big-endian platforms will be 0.
On big-endian platforms, this code will therefore pass 66 + 10\*0 = 66 to `putchar`. 66 is the ASCII code for `B`. On little-endian platforms, it will pass 66 + 10\*1 = 76, which is the ASCII code for `L`.
[Answer]
# C#, 60 52 bytes
C# is surprisingly competitive in this one.
```
char e=>System.BitConverter.IsLittleEndian?'L':'B';
```
Credits to Groo for the C#6 syntax.
60 bytes:
```
char e(){return System.BitConverter.IsLittleEndian?'L':'B';}
```
[Answer]
# Julia, ~~24~~ 19 bytes
```
()->ntoh(5)>>55+'B'
```
This is an anonymous function that takes no input and returns a `Char`. To call it, assign it to a variable. It assumes that integers are 64-bit.
The `ntoh` function converts the endianness of the value passed to it from network byte order (big endian) to that used by the host computer. On big endian machines, `ntoh` is the identity function since there's no conversion to be done. On little endian machines, the bytes are swapped, so `ntoh(5) == 360287970189639680`. Which is also, perhaps more readably, equal to: `0000010100000000000000000000000000000000000000000000000000000000` in binary.
If we right bit shift the result of `ntoh(5)` by 55, we'll get 0 on big endian machines and 10 on little endian machines. Adding that to the character constant `'B'`, we'll get `'B'` or `'L'` for big or little endian machines, respectively.
Saved 5 bytes thanks to FryAmTheEggman and Dennis!
[Answer]
# PHP 5.6, ~~41~~ 31 bytes (thx to isertusernamehere)
`<?=unpack(S,"\x01\x00")[1]-1?B:L;`
# PHP 7, 41 bytes
`echo unpack('S',"\x01\x00")[1]-1?'B':'L';`
Idea stolen from: <https://stackoverflow.com/a/24785578/2496717>
[Answer]
## Common Lisp, 27 bytes
*Tested on SBCL and ECL. For a portable approach, one should use [trivial-features](https://github.com/trivial-features/trivial-features/blob/master/SPEC.md).*
```
(lambda()'L #+big-endian'B)
```
The `#+` notation is a [read-time condition](http://clhs.lisp.se/Body/01_ebaa.htm), that *reads* the next form only if the conditional expression evaluates to true. Here the condition is the whole `#+big-endian` text which means that the test is satisfied if the `:big-endian` keyword belongs to the [`*FEATURES*`](http://clhs.lisp.se/Body/v_featur.htm) list (a list which contains among other things platform-specific information). The following expression is `'B`, which is either read or skipped according to the outcome of the test.
If your platform is big-endian and you write the above form in the REPL, it is exactly as if you wrote the following:
```
CL-USER>(lambda()'L 'B)
```
 (NB.`CL-USER>` is the prompt)
A function's body is an implicit [`PROGN`](http://clhs.lisp.se/Body/s_progn.htm), meaning that only the evaluation of the last expression is returned. So the above actually returns symbol ̀`B`.
If however the read-time condition evaluates to false, the form reads as if you wrote:
```
CL-USER>(lambda()'L)
```
... which simply returns symbol `L`.
[Answer]
## ARMv6 and later: 20 bytes machine code
```
0xE10F1000 : MRS   r0,CPSR        ; read current status register
0xE3110C02 : TST   r0,#1<<9       ; set Z flag if bit 9 set
0x03A0004C : MOVEQ r0,#'L'        ; return 'L' if Z clear
0x13A00042 : MOVNE r0,#'B'        ; return 'B' if Z set
0xEBxxxxxx : BL    putchar        ; print it (relative branch)
```
Untested, as I don't have a suitable machine to hand. Bit 9 of the CPSR gives the current load/store endianness.
[Answer]
# Perl 5, 21 + 1 = 22 bytes
Run with `perl -E`.
```
say ord pack(S,1)?L:B
```
Tested on amd64 (little-endian) and mips (big-endian).
[Answer]
# R, ~~28~~ 23 bytes
```
substr(.Platform$endian,1,1)
```
`.Platform$endian` returns `big` if run on big endian and `little` if on little. Here, using `substr`, it returns the first letter of the output, so either `b` or `l`.
As `endian` is the only object starting with an `e` contained in object `.Platform` we can reduce it thanks to partial matching to the following 23 bytes code:
```
substr(.Platform$e,1,1)
```
[Answer]
# Clojure, ~~46~~ 44 bytes
```
#(nth(str(java.nio.ByteOrder/nativeOrder))0)
```
This is a function that uses the Java builtin to get the endianness of the machine. Then get the string representation of it which will be either `"LITTLE_ENDIAN"` or `"BIG_ENDIAN"` and take the first character of whichever string is chosen and return that.
Saved 2 bytes thanks to @[cliffroot](https://codegolf.stackexchange.com/users/53197/cliffroot).
[Answer]
# Ruby, ~~31~~30 chars.
```
puts [1].pack("s")>"\01"??L:?B
```
Hmm, must be a better way. Count 5 characters less if the char need not to be output as I think other solutions omit printing. i.e. remove the "puts " part if you don't want anything printed.
[Answer]
# Bash (and other unix shells), 32 (33) bytes
First and second attempt:
```
case `echo|od` in *5*)echo B;;*)echo L;;esac # portable
[[ `echo|od` =~ 5 ]]&&echo B||echo L         # non-portable
```
Thanks to Dennis, shorter version:
```
od<<<a|grep -q 5&&echo L||echo B  # non-portable
echo|od|grep -q 5&&echo B||echo L # portable
```
The `echo` utility outputs a newline, with hex value `0A`, and no other output. For `<<<a` it is `61 0A`.
The `od` utility, by default, interprets the input as two-byte words, zero-padded if the number of bytes is odd, and converts to octal. This results in the output of echo being interpred as `0A 00`, which is converted to `005000` as big-endian or `000012` in little-endian. `61 0A` becomes `005141` in little-endian and `060412` in big-endian. The full output of od also includes address and size data meaning we cannot use `0`, `1`, or `2` for the test.
The command is well-defined to expose the system's endianness. From [the standard](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/od.html):
>
> The byte order used when interpreting numeric values is implementation-defined, but shall correspond to the order in which a constant of the corresponding type is stored in memory on the system.
>
>
>
## Compatibility notes
I am not certain if putting `echo|od` in backquotes with no double quotes around them [which results in a three-word argument to `case`] is supported on all systems. I am not certain if all systems support shell scripts with no terminating newline. I am mostly certain but not 100% of the behavior of od with adding the padding byte on big-endian systems. If needed, `echo a` can be used for the portable versions. All of the scripts work in bash, ksh, and zsh, and the portable ones work in dash.
[Answer]
## PHP, 16 bytes
```
<?=pack(S,14)^B;
```
This uses two tricks not used in the two existing PHP answers:
1. The value passed to pack() or unpack() can be anything, not just 0 or 1.
2. The bitwise XOR operator (`^`) works on strings, and the result is only as long as the shorter string, avoiding the need for a string indexing or ternary operator.
[Answer]
# Node, 42 bytes
```
n=>require('os').endianness()[0]
```
Pro: there's a builtin. Con: property names are very long
[Answer]
# PowerShell, 44 bytes
```
[char](66+10*[BitConverter]::IsLittleEndian)
```
Character 66 is `B`, and 10 characters later is number 76, `L`. A Boolean value of "true" becomes `1` when cast to a number. `BitConverter` is a standard .NET class.
[Answer]
## Bash, 27 bytes
```
iconv -tucs2<<<䉌|head -c1
```
`䉌` ([U+424C](http://www.unicode.org/cgi-bin/GetUnihanData.pl?codepoint=424C)) is encoded as three UTF-8 bytes: `E4 89 8C`.
It is assumed that `iconv` uses the function from glibc and that a UTF-8 locale is used.
[Answer]
# Racket, ~~35~~ 28 bytes
```
(if(system-big-endian?)'B'L)
```
`'B` or `'L` respectively. Let me know if this is not specific enough :)
[Answer]
# PHP, 22 bytes
```
<?=ord(pack(S,1))?L:B;
```
[Answer]
## Haskell (using GHC-only size-restricted numeric types), 75 bytes
```
import Unsafe.Coerce
import GHC.Int
f="BL"!!fromEnum(unsafeCoerce 1::Int8)
```
(not tested on a big-endian architecture, but it seems like it *ought* to work!)
[Answer]
## K, 15 bytes
```
    ("bl")@*6h$-8!`
    ,"l"
```
Explanation;
```
    From right to left;
    -8!`       /serialises the back tick and returns (0x010000000a000000f500)
    6h$-8!`    /This casts the result to `int which is type 6h(could have used `int$-8!`) - the result is (1 0 0 0 10 0 0 0 245 0i)
    *6h$-8!`   /* means first, we take the first item which is 1. Since it will be either 1 or 0, we can use it to index (@) into the two element list on the left i.e. ("bl")1 returns "l" and ("bl")0 returns b

```
]