Challenge: take ciphered text and decipher, also print out if it was offset to the left or right Problem:

Take input text like this: (all input should be considered strings)

 Upi djpi;f ytu yu[omh pmr yp yjr ;rgy.

And figure out if it was offset left or offset right (on a standard qwerty keyboard as pictured below).

Also only keys that output something to the screen are considered valid, so these keys: caps, shift, tab, enter, delete(backspace), should not be considered when doing this challenge.

Once you have figured out what the offset is, print out the offset and the correct text.

For example the above input would have this output

 text: You should try typing one to the left.
 offset: right

Your program has to 'know' that the sentence is correct before it prints out. (so no asking for user verification). Also no using libraries (should be a given).

All input will begin with a capital and end in a period (the period will not be offset left or right so you won't be able to use it to determine the offset.)

Another example:

U kujw oeife'nnubf xibrwara.

I like programming contests.

Some input samples to use:

 X'ra 'bs sifa 'ew ai o'aaw.
 Yjod vpmysod sm stnoysto;u ;pmh eptf.
 Rgw x'r ;b rgw g'r qwbr iyr ri v'r.
 Og upi vtrsyr s d,s;; fovyopmstu pg yjr ,pdy vp,,pm rmh;odj eptfd yjrm upi vsm vjrvl upit piy[iy gpt yjpdr eptfd' yjr eptf ayjra smf yjr eptf asmfa str imowir ejrm pggdry ;rgy smf pggdry tohjy. //<< don't put this deciphered text in your answers.

And bonus option: write your program to be able to handle the input switching offsets.

Example above with switching offset:

Upi djpi;f ytu yu[omh ibw ri rgw kwdr.

text: You should try typing one to the left.
offset: right -> index[21], then left.

Winning criterion:

Faster code gets more points (out of 10) so O(logn) would score more then O(n^2) solutions (obviously).
Elegance (out of 20) There is a very elegant and simple solution to this problem. The closer you get to the simple solution the higher your score. (bonus +5 if you think of something simpler then my solution).
This is not a code golf, but concise readable code will be scored (out of 10).
Bonus is all or nothing for 5 extra points.

So A perfect score would be 40 but you could score up to 50 if you get both bonuses.

bonus +2 if you read all instructions

Python

The original version didn't deal with punctuation too well, so here's a revised version.

r = dict(zip('\\qwertyuio\'asdfghjkl;/zxcvbnm|:"?', 'qwertyuiopasdfghjkl;\'zxcvbnm,Q"AZ'))
l = dict(zip('wertyuiop[\'asdfghjkl;xcvbnm,.{:"<', 'qwertyuiop;\'asdfghjklzxcvbnm,PL:M'))
shifts = {'right': r, 'left': l}

def shift(ciphered):
    letters = set(ciphered)
    if letters & set('p[{,<') or any(i in ciphered for i in ('yjr', 'smf')):
        return 'left'
    elif letters & set('qz\\|/?') or any(i in ciphered for i in ('rgw', '\'bs')):
        return 'right'
    else:
        return 'right' if ciphered.count('w') > ciphered.count('y') else 'left'

def decipher(ciphered):
    ciphered = ciphered.split('.', 1)[0].lower()
    shift_ = shift(ciphered)
    text = ''.join(shifts[shift_].get(i, i) for i in ciphered).capitalize()
    print 'text:', text + '.'
    print 'offset:', 'left' if shift_ == 'right' else 'right'

decipher(raw_input())

This is how it works:

If any of the characters p[{,< are in the ciphered string, or yjr or smf (the and and shifted right respectively) are in the string, then the string must have been shifted right.
If any of the characters qz\|/? are in the ciphered string, or rgw or 'bs (the and and shifted left respectively) are in the string, then the string must have been shifted left.
If neither of the above are true, then we compare the counts of 'w' and 'y' in the string. If there are more 'w's, then it is most likely to have been shifted left, because 'e' is more common than 'u' in English. If not, then it probably would have been shifted right, since 't' is much more common than 'q' in English.

The original function used 'w' and 's', however using e/u and q/t will theoretically produce much stabler results, as the frequency differences between the letter pairs are higher than those of the original e/d and q/a.
This will work for most strings, however theoretically there might be some strings who will give the wrong output. (If you find one, post the offender in the comments and I will try to make the test more stable)

We reverse-shift the string accordingly, to produce the output.

Note that if there is a comma in a string that has been shifted right (ie there is a . in the ciphered string excluding the one at the end), then this will not work, as the function only deciphers the part before the first period in the string.

Here are some sample test results.


Chicken McNugget Numbers Description

Chicken McNugget numbers are numbers that can be expressed as a sum of 6, 9 or 20 - the initial sizes of the famous Chicken McNuggets boxes sold by McDonald's. In that sum, a number may occur more than once, so 6 + 6 = 12 is such a number too, and the number must "contain" at least one of the mentioned sizes. The first Chicken McNugget numbers are:

6
9
6 + 6 = 12
6 + 9 = 15
9 + 9 = 6 + 6 + 6 = 18
20
6 + 6 + 9 = 21
...

Challenge

Your task is to write a program or function, that, given a positive integer, determines whether this number can be expressed in the described way, therefore is such a Chicken McNugget number. It should then output a truthy or falsy value based on its decision.

Test cases

6 -> true
7 -> false
12 -> true
15 -> true
21 -> true
40 -> true
42 -> true

This is code-golf, so the shortest answer in bytes wins and the standard loopholes apply!

Python, 27 bytes

lambda n:0x82492cb6dbf>>n&1

Try it online!


Find a criminal from his ear, finger, and head Prior to the discovery of fingerprints and DNA testing, the British police used an anthropometric system to identify repeat offenders. Certain parts of the bodies of criminals were measured and stored in records -- these parts of the body were assumed to not change in size after adulthood. This system was known as bertillonnage.

The diagram below shows a filing system used by the police to access these records quickly.

Diagram 1: A filing system with numbered drawers.
 Note: if you cannot see the image, try the imgur mirror  or compile it yourself.

The filing cabinet consists of 81 numbered drawers. Each drawer contains cards, and each card has measurements of particular parts of a criminal's body:

The length of their head (H)
The breadth of their head (B)
The width of their right ear (E)
The length of their index finger (F)

Each measurement is classified as either small, medium or large.

For example, drawer 56 contains cards with the following characteristics: small H, large B, medium E, and small F. This can be notated using the letters S, M, and L in place of small, medium, and large:

SH,LB,ME,SF

Note that the size letter goes first, then what the measurement is. In addition, an exclamation point ! may be placed in front to cause a negative:

!SH,LB,!ME,SF

This indicates cards that have the following characteristics: not small H, large B, not medium E, and small F. There are four drawers that contain cards with these characteristics -- 58, 60, 61, and 63.

Your task is to write a program, that, when given a string notating some characteristics, outputs all of the drawers that contain cards with those characteristics. If there are no drawers that contain cards with the given characteristics, output 0.

Here are some sample inputs and outputs.

Input: SH,LB,ME,SF
Output: 56
Input: !SH,LB,!ME,SF
Output: 58,60,61,63
Input: SB,!MF,!LF
Output: 1,2,3,4,5,6,7,8,9
Input: MH,!MH
Output: 0

This is code golf, so the shortest entry wins. Ask questions in the comments if the specification is not clear.

Ruby 1.9.3 - 173 157 143

x=(1..81).select{|j|$*[0].split(?,).all?{|y|i=j-1
z='SML'
[z[i%9/3]+?H,z[i%3]+?E,z[i/27]+?B,z[i/9%3]+?F].member?(y[-2,2])^y[?!]}}
p x==[]?[0]:x

Edit:

applied Three If By Whiskey's tips.
taken parameters from the command line to save some more chars

Online demo: http://ideone.com/lodTLt


Haskell, 45 bytes

n!a=not$any(n!)[x|x<-[n..a-1],mod a x<1]||n>a

Try it online!

I define a nice recursive function (!):

n!a checks if any factor of a, in the range [n,a-1], is an n-prime. Then it negates the result. It also makes sure that n>a


Draw a range of mountain ranges Inspired by Fibonacci domino tiling, this problem is about generating ASCII art representing another famous combinatorial sequence.

A n-step mountain diagram is a drawing of a mountain range, using exactly n '/' and n '\' characters, such that characters sketch a continuous curve which never dips below its initial "altitude".  For example,

   /\/\
/\/    \

and

   /\
/\/  \/\

are both 4-step mountain diagrams, but

/\  /\/\
  \/

is not.

Input

The program should accept an integer n from stdin or as the parameter to a function.

Output

Print all n-step mountain diagrams to stdout. The diagrams can be in any order, but should be separated by some sort of whitespace. You can decide if different diagrams will be output horizontally, vertically, etc.

As in the domino tiling problem, you can use whatever whitespace you want. This includes extra newlines before or after the printed output.

Example

Some sample valid outputs for n=3:

Valid output A:

                                        /\
         /\             /\             /  \    /\/\
/\/\/\  /  \/\       /\/  \           /    \  /    \

Valid output B:

   /\
/\/  \

 /\/\
/    \

/\/\/\

  /\
 /  \
/    \

 /\
/  \/\

Valid output C:

  /\
 /  \       /\
/    \   /\/  \
                  /\/\
 /\              /    \
/  \/\   /\/\/\

This is code golf; shortest program (in bytes) wins.

Python 2: 151 chars

N=2*input()
for i in range(2**N):
 L=[];c=1;exec"b=i%2;c+=2*b-1;L+=[[' ']*N];L[-1][b-c]='\/'[b];i=i/2*(c>0);"*N
 for x in(c==1)*zip(*L):print"".join(x)

#Output for n=3:

  /\
 /  \
/    \

 /\/\
/    \

   /\
/\/  \

 /\
/  \/\

/\/\/\

Wow, this is a mess.

The first idea is to use the numbers 0 to 2**N-1 to encode all sequences of N up-moves and down-moves in their bits. We read off these bits one by one by repeated %2 and /2, iterated in an exec loop.

We store the running mountain range sideways in a transposed list of strings L. Each time, we generate a new a row of spaces are replace one space in the new row with / or \ depending on whether an up-move or down-move happened.

The index of that space is c spaces from the end, where c is the running height. Doing it from the front would make the mountains upside down. We further shift it by b to align upward and downward moves , getting [b-c]. Starting c at 1 rather than 0 fixes an off-by-one error.

To eliminate cases where c dips below the start value 1, when this happens, we set i to 0, which causes all further moves to be downward, making c become more negative. Then, when we check whether c ended at 1, we also check whether c ever fell below it. We only print the mountain range if c is 1.

To print, we do zip(*L) to transpose the range from vertical to horizontal, and print each joined string. A lot of trouble in this answer came from Python treats strings as immutable, so we worked with them as lists of characters and only joined them into strings for printing.

Thanks to @flornquake for help and improvements.


Is it truthy or falsy? There are so many different ways to express whether something is true or not! The goal of this challenge is to produce a standardized output of truthy or falsy for various input truthy and falsy values.

For the purposes of this challenge, the following inputs are considered truthy:

A string representing a signed integer with a non-zero value (contains only the digits [0-9], with an optional - at the beginning). Note that the string -0 will never be given as input. A non-zero integer will never be preceded by a 0 (i.e. 01 will never be given as input, similarly -01 will never be gien as input).
The case-insensitive strings equivalent to one of defined, found, nonnil, non-nil, on, success, t, true, y, and yes

For the purposes of this challenge, the following inputs are considered falsy:

The string 0. Repeated zeros (00, 00...) will never be given as input.
An empty string
The case-insensitive strings equivalent to one of f, failure, false, n, nan, nil, no, notfound, not-found, null, nullptr, off, and undefined

Input

The input is a string representing a truthy/falsy value. The string may come from any source desired (stdio, function parameter, etc.). There is no leading/trailing whitespace.

The input is guaranteed to match one of the allowed truthy/falsy values above (i.e. you do not need to provide any error handling).

Output

Your program/function must output a truthy/falsy value which represents the "truthy-ness" or "falsy-ness" of the input.
You are only allowed to specify exactly 1 truthy and 1 falsy value which your output must convert the input to (these are your "standardized" truthy/falsy value). The output may be written to any sink desired (stdio, return value, output parameter, etc.).

Please specify what truthy and falsy value you chose in your answer.

Ex.: If you choose the string true as a truthy value, you cannot also have the integer 1 for truthy.

Test Cases

Test cases are formatted as the first line is the input, and the second line is the output.

-1
true

1
true

1234
true

-4321
true

defined
true

deFined
true

Found
true

nonnil
true

non-nil
true

ON
true

SuCCess
true

T
true

true
true

y
true

YeS
true

0
false

'' (empty string)
false

faLSE
false

f
false

Failure
false

n
false

NaN
false

nil
false

no
false

notfound
false

not-Found
false

NULL
false

nullptr
false

OFF
false

unDefined
false

Scoring

This is code-golf; shortest code in bytes wins. Standard loopholes apply. You may use any built-ins desired.

MATL, 20 bytes
U|sG36ZA13\[BID1]m+g

Input is a string enclosed in single quotes. Output is 1 for truthy or 0 for falsy.
Try it online! Or verify all test cases.
How it works
U|s      % Take input implicitly. Interpret as number, absolute value, sum
G36ZA    % Push input again. Convert from base-36
13\      % Modulo 13
[BID1]   % Push array [6 3 8 1]
m        % True if member: gives 1 iff the result from modulo 13 is in the array
+g       % Add, convert to logical. Display implicitly

This performs two tests on the input:

Try to interpret the input as a number, and detect if it is nonzero. The function used to interpret a string as a number outputs an empty array if it's not possible; and the sum of the entries of an empty array is 0. So it suffices to try the conversion, take the absolute value, and sum. This gives a positive value if the input contains a nonzero number, and 0 otherwise.
Assuming the input string doesn't represent a number, we need to classify it into one of the two given sets. To do this, the input is interpreted as the digits of a number expressed in base-36, using alphabet '01...9ab...z'. The base conversion function is case-insensitive and ignores digits not present in the alphabet (in our case, '-'). It turns out that the modulo 13 of the resulting number is 1, 3, 6 or 8 for the truthy strings, and doesn't give any of those values for the falsy strings. So it can be used as a signature. We thus perform modulo 13 and see if the result is any of those four values. This gives 1 if it is, or 0 otherwise.

The final result should be truthy if any of the two conditions is met, and falsy otherwise. So we add the two numbers resulting from 1 and 2 above and convert to logical, which gives 1 or 0 as standardized truthy/falsy values.


Pythagorean Triplets The Pythagorean Theorem states that for a right triangle with sides a, b, and c, a2+b2=c2.

A Pythagorean triplet is a set of three numbers, where a2+b2=c2, a
To extend this even further, a primitive Pythagorean triplet is a Pythagorean triplet where gcd(a,b,c)=1.

The goal is to find 100 primitive Pythagorean triplets.

Input: No input.

Output: 100 primitive Pythagorean triplets, in whatever order and shape, as long as the output contains only those triplets.

Shortest code wins. Good luck!

Python, 42

i=4
while i<203:print 2*i,i*i-1,i*i+1;i+=2


"Add one" to every color in an image You would simply take this image and make every color added one to every hexadecimal digit. For example, #49de5f would become #5aef60 (with the 9 looping to an a, and the f looping to a 0.)

This would also mean that all white (#ffffff) would become black (#000000) because all f loops back to 0, but all black will become a lighter shade of black (#111111).

Scoring is based on the least number of bytes used, as this is a code-golf question.

Use the below image as the input image for your code, and put the output image of your code into your answer.

If you want to, you can also use this other rainbow image:

Mathematica, 78 bytes

Image@Apply[16#+#2&,Mod[IntegerDigits[#~ImageData~"Byte",16,2]+1,16]/255,{3}]&

Takes and returns an image object (to create an image object, just paste the image into Mathematica).

Result for the test case:

Taking input and returning output as a 3D array of integer channel values, this reduces to 51 bytes:

Apply[16#+#2&,Mod[IntegerDigits[#,16,2]+1,16],{3}]&

But those meta posts don't have an overwhelming amount of support yet, so I'm going with the 78-byte version for now.


TyPe LiKe ThIs AnD iRrItAtE yOuR fRiEnDs Your goal is to alternate uppercase and lowercase letters, while ignoring non-alphaneumeric characters.

Input => Output
abc => aBc OR AbC
a c => A c OR a C
abc123abc => AbC123aBc OR aBc123AbC

Shortest answer wins.

JavaScript, 116

s=>{x=!0;return s.split("").map(e=>{if(e.match(/[a-zA-Z]/))x=!x;return x?e.toUpperCase():e.toLowerCase()}).join("")}

Saved two bytes thanks to NTCG


How many towers can you see? This question is based on the number-placement puzzle Towers (also known as Skyscrapers), which you can play online. Your goal is to take a solution to the puzzle and determine the clues -- the numbers of towers visible along each row and column. This is code golf, so fewest bytes wins.

How Towers works

The solution to a Towers puzzle is a Latin square -- a n*n grid in which every row and column contains a permutation of the numbers 1 through n. An example for n=5 is:

4 3 5 2 1
5 4 1 3 2
1 5 2 4 3
2 1 3 5 4
3 2 4 1 5

Each row and column is labelled with a clue at each end like:

       2 3 1 4 5
       v v v v v

 2 >   4 3 5 2 1   < 3
 1 >   5 4 1 3 2   < 4
 2 >   1 5 2 4 3   < 3
 3 >   2 1 3 5 4   < 2
 3 >   3 2 4 1 5   < 1

       ^ ^ ^ ^ ^
       2 2 2 2 1

Each clue is a number from 1 to n that tells you how many towers you "see" looking along the row/column from that direction, if the numbers are treated as towers with that height. Each tower blocks shorter towers behind it. In other words, the towers you can see are the ones that are taller than any tower before them.

For example, let's look at the first row.

 2 >   4 3 5 2 1   < 3

It has a clue of 2 from the left because you can see the 4 and the 5. The 4 blocks the 3 from sight and the 5 blocks everything else. From the right, you can see 3 towers: 1, 2, and 5.

Program requirements

Write a program or function that takes in the grid of numbers and outputs or prints the clues, going clockwise from the top left.

Input

An n*n Latin-square with 2<=n<=9.

The format is flexible. You can use any data structure that represents a grid or list containing numbers or digit characters. You may require a separator between the rows or no separator at all. Some possibilities are a list, a list of lists, a matrix, a token-separated string like

43521 54132 15243 21354 32415,

or a string without spaces.

You're not given n as part of the input.

Output

Return or print the clues starting from the top left and going clockwise. So, first the upper clues reading rightwards, then the right clues reading downwards, then the lower clues reading leftwards, the the left clues reading upwards.

This would be 23145 34321 12222 33212 for the previous example

       2 3 1 4 5
       v v v v v

 2 >   4 3 5 2 1   < 3
 1 >   5 4 1 3 2   < 4
 2 >   1 5 2 4 3   < 3
 3 >   2 1 3 5 4   < 2
 3 >   3 2 4 1 5   < 1

       ^ ^ ^ ^ ^
       2 2 2 2 1

Just as for the input, you can use a list, string, or any ordered structure. The four "groups" can be separated or not, in a nested or a flat structure. But, the format must be the same for each group.

Example test cases:

(Your input/output format doesn't have to be the same as these.)

>> [[1 2] [2 1]]

[2 1]
[1 2]
[2 1]
[1 2]

>> [[3 1 2] [2 3 1] [1 2 3]]

[1 2 2]
[2 2 1]
[1 2 3]
[3 2 1]

>> [[4 3 5 2 1] [5 4 1 3 2] [1 5 2 4 3] [2 1 3 5 4] [3 2 4 1 5]]

[2 3 1 4 5]
[3 4 3 2 1]
[1 2 2 2 2]
[3 3 2 1 2]

>> [[2 6 4 1 3 7 5 8 9] [7 2 9 6 8 3 1 4 5] [5 9 7 4 6 1 8 2 3] [6 1 8 5 7 2 9 3 4] [1 5 3 9 2 6 4 7 8] [3 7 5 2 4 8 6 9 1] [8 3 1 7 9 4 2 5 6] [9 4 2 8 1 5 3 6 7] [4 8 6 3 5 9 7 1 2]]

[4 2 2 3 3 3 3 2 1]
[1 3 3 2 2 2 2 3 3]
[4 3 2 1 2 3 3 2 2]
[3 1 2 4 3 3 2 2 5]

For you convenience, here are the same test cases in a flat string format.

>> 1221

21
12
21
12

>> 312231123

122
221
123
321

>> 4352154132152432135432415

23145
34321
12222
33212

>> 264137589729683145597461823618572934153926478375248691831794256942815367486359712

422333321
133222233
432123322
312433225

APL 19

≢¨∪/⌈\(⍉⍪⌽⍪⊖∘⌽∘⍉⍪⊖)

(golfed a bit more after ngn's suggestion, thanks)

Explanation:

(⍉⍪⌽⍪⊖∘⌽∘⍉⍪⊖)  rotates matrix 4 times appending results
⌈\ gets maximums for each row up to current column (example: 4 2 3 5 1 gives 4 4 4 5 5)
≢¨∪/ counts unique elements for each row

Try it on tryapl.org


Playing with the musical turtle My two kids like to play with the following toy:

The colored areas with the shapes inside can be touched and the turtle then lights the area and plays a sound or says the name of the color or the shape inside. The middle button changes the mode. There is one mode in which the areas play different musical notes when touched, with a twist: if the kid touches three consecutive areas clockwise, a special melody 1 is played. If the three consecutive areas touched are placed counterclockwise, a special melody 2 is played.

The challenge

Let's simulate the internal logic of the toy. Given a string with 3 presses of the kid, return two distinct, coherent values if the three presses are for consecutive areas (clockwise or counterclockwise) and a third distinct value if they are not.

Details

The input areas will be named with a character each, which can be their color: ROYGB for red, orange, yellow, green and blue; or their shape: HSRTC for heart, square, star (R), triangle and circle. Case does not matter, you can choose to work with input and output just in uppercase or in lowercase.
The program will receive a string (or char array or anything equivalent) with three presses. Examples (using the colors): RBO, GYO, BBR, YRG, YGB, ORB...
The program will output three distinct, coherent values to represent the three possible outcomes: a first value if the combination does not trigger a special melody, a second value if the combination triggers the clockwise special melody, and a third value if the combination triggers the counterclockwise special melody. Example: 0 for no special combination, 1 for the melody triggered by a clockwise combination and -1 for the melody triggered by a counterclockwise combination.
You do not need to worry about handling wrong input.

Test cases

Input   Output      // Input based on colors
--------------
RBO     0           // No special combination
GYO     -1          // Counterclockwise melody triggered
BBR     0           // No special combination
YRG     0           // No special combination
YGB     1           // Clockwise melody triggered
ORB     -1          // Counterclockwise melody triggered
OOO     0           // No special combination
BRO     1           // Clockwise melody triggered

This is code-golf, so may the shortest code for each language win!

Java 8, 48 39 33 bytes

s->"ROYGBRO BGYORBG".indexOf(s)|7

-6 bytes thanks to @RickHitchcock, so make sure to upvote him as well!
Takes uppercase color as input-String. Outputs -1 for none, 7 for clockwise, and 15 for counterclockwise.
Try it online.
Explanation:
s->      // Method with String parameter and integer return-type
   "ROYGBRO BGYORBG".indexOf(s)
         //  Get the index of the input in the String "ROYGBRO BGYORBG",
         //  which will result in -1 if the input is not a substring of this String
    |7   //  Then take a bitwise-OR 7 of this index, and return it as result

Old 39 bytes answer:
s->(char)"ROYGBRO BGYORBG".indexOf(s)/7

Takes uppercase color as input-String. Outputs 9362 for none, 0 for clockwise, and 1 for counterclockwise.
Try it online.
Explanation:
s->      // Method with String parameter and integer return-type
   (char)"ROYGBRO BGYORBG".indexOf(s)
         //  Get the index of the input in the String "ROYGBRO BGYORBG",
         //  which will result in -1 if the input is not a substring of this String
         //  And cast it to a char (-1 becomes character with unicode value 65535)
    /7   //  Integer-divide it by 7 (the char is implicitly converted to int doing so)


Convert to Suzhou numerals Suzhou numerals (蘇州碼子; also 花碼) are Chinese decimal numerals:

0 〇
1 〡 一
2 〢 二
3 〣 三
4 〤
5 〥
6 〦
7 〧
8 〨
9 〩

They pretty much work like Arabic numerals, except that when there are consecutive digits belonging to the set {1, 2, 3}, the digits alternate between vertical stroke notation {〡,〢,〣} and horizontal stroke notation {一,二,三} to avoid ambiguity. The first digit of such a consecutive group is always written with vertical stroke notation.

The task is to convert a positive integer into Suzhou numerals.

Test cases

1          〡
11         〡一
25         〢〥
50         〥〇
99         〩〩
111        〡一〡
511        〥〡一
2018       〢〇〡〨
123321     〡二〣三〢一
1234321    〡二〣〤〣二〡
9876543210 〩〨〧〦〥〤〣二〡〇

Shortest code in bytes wins.

JavaScript, 81 bytes

s=>s.replace(/./g,c=>(p=14>>c&!p)|c>3?eval(`"\\u302${c}"`):'〇一二三'[c],p=0)

Try it online!

Using 14>>c saves 3 bytes. Thanks to Arnauld.


Draw a Random Walk with Slashes Write a program or function that takes in a positive integer N (via stdin/command line/function arg) and prints or returns a string representation of a two dimensional random walk that is N steps long, drawn out of slashes: / \ (plus spaces and newlines for spacing).

A 2D random walk starts at the origin of an infinite integer lattice. Then N times repeatedly, a cardinal direction (up, down, left, right) is chosen uniformly at random and the walker moves one unit in that direction. The resulting path taken is the random walk.

Here is a random walk for N = 6. Notice that it traverses back on itself when it reaches (-1, 3).

To draw this with slashes we essentially need to rotate the entire thing 45° clockwise. The axes and start and end points are not drawn in the slash version.

/
\
 \
 /\

A more complex walk like this (N = 20, though there's no way to tell):

Would become this:

     /
/\/ /\
\/\/
/\/
\/

Your program needs to generate these type of slash versions of random walks. You must randomly choose each new direction the walk takes, so every running of the program for a certain N will almost definitely produce a different walk. (Pseudorandomness is fine.)

There should never be any empty lines above or below the lowest and highest slashes (except for one optional trailing newline), and there should never be empty columns of spaces before or after the leftmost and rightmost slashes.

So for N = 1, the output is always / or \, but never something like:

 /

Trailing spaces are allowed as long as they don't go past the column of the rightmost slash.

The submission with the fewest bytes wins. Here's a handy byte counter.

Python 2, 300 285 257 246 236 bytes

Something to kick things off. It should be possible to shrink this down further. Thanks @Maltysen for shaving 10 bytes.

from random import*
N=input()
x=y=0;G={}
exec'n=randrange(4);l=n<2;u=n&1;G[(x-l,y-u)]="\\/"[l^u];x-=2*l-1;y-=2*u-1;'*N
f=lambda i:range(min(x[i]for x in G),max(x[i]for x in G)+1)
for i in f(0):print"".join(G.get((i,j)," ")for j in f(1))

Generates the walk output into a dictionary G of visited (x,y) tuples, updating our location as we go. Each random step n is both either u/d (u) and l/r (l).


Parity of sum of other elements Task

Given an array of positive integers, replace each element with the parity of the sum of the other elements. The array is guaranteed to have at least 2 elements.

Definition

Parity: whether a number is odd or even.

Example

For the array [1,2,3,1]:

Replace 1 with the parity of 2+3+1, i.e. even.
Replace 2 with the parity of 1+3+1, i.e. odd.
Replace 3 with the parity of 1+2+1, i.e. even.
Replace 1 with the parity of 1+2+3, i.e. even.

Output: [even, odd, even, even]

Input

An array of positive integer.

You may take it as a proper array, or as a linefeed-separated string of positive integers.

You may assume that the array and the values inside are within the handling capability of your language.

Output

An array of two consistent values, one representing odd, one representing even.

You may output it as a linefeed-separated string of the two values.

Testcases

Inputs:

[1, 2, 3, 1]
[1, 2, 3, 2, 1]
[2, 2]
[100, 1001]

Outputs:

[even, odd, even, even]
[even, odd, even, odd, even]
[even, even]
[odd, even]

Note: you may choose other consistent values other than odd and even.

Scoring

This is code-golf. Shortest answer in bytes wins.

Standard loophole applies.

Jelly, 3 bytes

+SḂ

Try it online!

How it works

+SḂ  Main link. Argument: A (array)

 S   Compute the sum of A.
+    Add the sum to each element of A.
     Using _ (subtraction) or ^ (bitwise XOR) would also work.
  Ḃ  Bit; compute the parity of each resulting integer.


1D monochrome Link-a-Pix solvability Background
Link-a-Pix is a puzzle on a rectangular grid, where the objective is to reveal the hidden pixel art by the following rules:

Connect two cells with number N with a line spanning N cells, so that the two cells are at the two ends of the line.
The number 1 is considered connected to itself (which makes it an exception to the rule of "connect two cells").
Two different lines are not allowed to overlap.
The puzzle is solved when all the given numbers on the grid are connected by the above rules. There may be some unused cells after the puzzle is solved.

The following is an example puzzle and its unique solution.

(Source: The NP completeness of some lesser known logic puzzles, 2019)
A Link-a-Pix puzzle often involves colors and reveals a colorful picture when solved, but we will ignore them for simplicity, and focus on "monochrome" puzzles.
Task
In this challenge, the puzzle is limited to one dimension, or equivalently, a grid of height 1.
Given a 1D Link-a-Pix puzzle instance, check if it has a solution or not. A puzzle instance is given as a sequence of non-negative integers, where each cell with a given number contains that number and the others contain 0.
For output, you can choose to

output truthy/falsy using your language's convention (swapping is allowed), or
use two distinct, fixed values to represent true (affirmative) or false (negative) respectively.

Test cases
Truthy
[0, 1, 0, 4, 0, 0, 4, 2, 2, 0, 1]
[0, 0, 0, 0] (the puzzle is solved vacuously)
[12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12] (multi-digit numbers must be supported)
[2, 2, 0, 2, 2, 2, 2, 1, 2, 2] (suggested by tsh)

Falsy
[0, 4, 0, 3, 4, 3, 0] (two lines cannot overlap)
[3, 0, 3, 0, 3, 1, 3, 0, 3, 0, 3]
[1, 0, 2, 2, 2, 2, 2, 0, 1] (one of 2s have nowhere to connect)
[3, 3, 3, 3] (suggested by tsh)
[3, 3, 3]
[0, 0, 4, 4] (the 4s must begin and end the 4-cell line)
[12, 2] (multi-digit numbers must not be treated as multiple single-digit numbers)

JavaScript (ES6), 41 bytes
Returns false for valid or true for invalid.

a=>a.some(p=(x,i)=>--p>0?x:a[i+x-1]^=p=x)

Try it online!
Commented
a =>            // a[] = input
a.some(p =      // start with p NaN'ish
  (x, i) =>     // for each value x at position i in a[]:
  --p > 0 ?     //   decrement p; if it's positive:
    x           //     make sure that we have x = 0
                //     (because we're currently over a connection 'line')
  :             //   else:
    a[          //     XOR the entry at ...
      i + x - 1 //     ... i + x - 1 ...
    ]           //
    ^= p = x    //     ... with x; and set p = x
                //     this must give 0 if the puzzle is valid
)               // end of some()

The trickiest case is when a \$0\$ is reached at position \$i\$ and we're currently outside a connection (i.e. \$p\le0\$), which causes the entry at \$i-1\$ to be XOR'ed with \$0\$. If the puzzle is valid, this will always result in \$0\$ as expected because:

if \$i=0\$, we do undefined ^ 0
if \$i>0\$, the entry at \$i-1\$ either was already set to \$0\$ or was cleared by the previous XOR


Quine permutation group Write a program or function which, when run, outputs another program or function which is valid in the same language as the original program, and which itself will output another program or function that has the same properties. You must at one point end up back to your initial program or function.
Example
Suppose you write program A. When run, it outputs program B. When you run B, it outputs program C. When you run C, it outputs program A, thus completing the circle. A, B and C are all valid in the same language and are all different by at least one character.
Scoring
Your score is calculated as <Number of bytes of the initial program>/<number of iterations to get back to the initial program>
For instance, with the programs A, B and C in the previous example, the number of iterations is 3 (you have to run 3 times to get back to A) and the number of bytes is the number of bytes of A.
This incentivize both golfing your initial code, and having an initial program that leads to a longer chain.
The smallest score wins

CJam, score → 0

{)1e9%"X$~"}0X$~

Try it online in the CJam interpreter.

The actual score of this program is obviously positive, but 1e9 can be replaced with 1e99, 1e999, 1e9999, 1e99999, etc.

The numerator of the score grows much slower than the denominator.

How it works

{          }     e# Define a block:
 )               e#   Increment the integer on the stack.
  1e9%           e#   Take the incremented integer modulo 1,000,000,000.
      "X$~"      e#   Push that string.
            0    e# Push 0.
             X$~ e# Copy the block and execute the copy.

                 e# The stack now holds the block, the modified integer and
                 e# the string "X$~", all of which CJam prints before exiting.

Executing the code prints {)1e9%"X$~"}1X$~ which, when executed, prints {)1e9%"X$~"}2X$~, etc.

After reaching {)1e9%"X$~"}999999999X$~, one more execution yields the original code.


Tips for golfing in CJam CJam is a GolfScript-inspired stack-based golfing language, created by PPCG user aditsu.

So, in the vein of other language-specific tips questions:

What general tips do you have for golfing in CJam? Please post one tip per answer.

Correct modulo for negative numbers

It's often annoying that the result of the modulo operation gives the same sign as the first operand. E.g. -5 3% gives -2 instead of 1. More often than not you want the latter. The naive fix is to apply modulo, add the divisor once and apply modulo again:

3%3+3%

But that's long and ugly. Instead, we can use the fact that array indexing is always modular and does work correctly with negative indices. So we just turn the divisor into a range and access that:

3,=

Applied to -5, this gives 1 as expected. And it's only one byte longer than the built-in %!

If the modulus is a power of 2, you can save another byte using bitwise arihmetic (which is also a lot faster). Compare:

32,=
31&

For the special case of 65536 == 2^16 another byte can be saved by making use of the wrapping behaviour of the character type:

ci


Check my tunneling arrays Imagine you have an array of integers, whose non-negative values are pointers to other positions in the same array, only that those values represent tunnels, so if the value in position A is positive and points to position B, then the value in position B must be also positive and point to position A to represent both ends of the tunnel. So:

Challenge

Given an array of integers, check if the array complies with the restriction to be a tunneling array and return two distinct, coherent values for truthy and falsey.
The values in the array will be below zero for non-tunnel positions, and zero or above for tunnel positions. If your array is 1-indexed, then the zero value represents a non-tunnel position. Non-tunnel values do not need to be checked.
If a positive value in a cell points to itself, that's a falsey. If A points to B, B to C and C to A, that's a falsey. If a positive value points beyond the limits of the array, that's a falsey.

Examples

The following examples are 0-indexed:

[-1, -1, -1, 6, -1, -1, 3, -1, -1]  Truthy (position 3 points to position 6 and vice versa)
[1, 0]                              Truthy (position 0 points to position 1 and vice versa)
[0, 1]                              Falsey (positions 0 and 1 point to themselves)
[4, 2, 1, -1, 0, -1]                Truthy
[2, 3, 0, 1]                        Truthy
[1, 2, 0]                           Falsey (no circular tunnels allowed)
[-1, 2, -1]                         Falsey (tunnel without end)
[]                                  Truthy (no tunnels, that's OK)
[-1, -2, -3]                        Truthy (no tunnels, that's OK)
[1, 0, 3]                           Falsey (tunnel goes beyond limits)
[1]                                 Falsey (tunnel goes beyond limits)
[1, 0, 3, 7]                        Falsey (tunnel goes beyond limits)

This is code-golf, so may the shortest code for each language win!

R, 47 bytes

function(v,a=v[v>0],b=sort(a))all(v[a]==b&a!=b)

Try it online!

Unrolled code and explanation :

f=
function(v){          # v vector of tunnel indexes (1-based) or values <= 0

  a = v[v>0]          # get the tunnel positions

  b = sort(a)         # sort the tunnel positions ascending

  c1 = v[a]==b        # get the values of 'v' at positions 'a'
                      # and check if they're equal to the sorted positions 'b'
                      # (element-wise, returns a vector of TRUE/FALSE)

  c2 = a != b         # check if positions 'a' are different from sorted positions 'b'
                      # (to exclude tunnels pointing to themselves, element-wise,
                      #  returns a vector of TRUE/FALSE)

  all(c1 & c2)        # if all logical conditions 'c1' and 'c2' are TRUE then
                      # returns TRUE otherwise FALSE
}


Enumerate an undecidable set An undecidable set is a set for which determining whether an object is an element of the set is an undecidable problem

Write a program which runs forever, printing the elements of any undecidable set, each element appearing on its own line.  For any element in the set, there must be a finite amount of time after which your program will print that element.  Each element should only be printed once.

Since you have to enumerate the elements, the set you choose will be RE.

Some examples of undecidable sets which are RE:

Programs of any Turing-complete language which halt.
Post correspondence problem instances with solutions.
Sets of Wang tiles which can't tile the plane.

Haskell, 404 characters

This Haskell program prints all FRACTRAN programs which halt when given the input 2. (The syntax of a FRACTRAN program is a list of positive rational numbers.)

import Data.Ratio
import Data.List
import Data.Either
r=do
 z<-[1..]
 let r=repeat z
 (p,q)<-zip r[1..z]++zip[1..z]r
 if gcd p q==1 then[p%q]else[]
o l=d[map(:xs)r|xs<-l]
e p n=n:maybe[](e p)(find((==1).denominator)$map(*n)p)
h p=map Left(e p 2)++[Right p]
main=mapM print$rights$d$map h$d$iterate o[[]]
d=concat.s
s[]=[]
s([]:b)=s b
s((x:a):b)=[x]:z a(s b)
z[]b=b
z a[]=map(:[])a
z(x:a)(y:b)=(x:y):z a b

I have made no great effort to compress this program. Furthermore, the GCD test in the definition of r is purely an optimization (it avoids duplicates).

(Also, If you are interested in running it, be sure to compile it, perhaps with optimization; I found that running it in ghci quickly consumed gigabytes of memory.)

It operates by successively constructing infinite lists of infinite lists and then flattening them in a diagonal order: the list of all positive rational numbers, the list of all lists of positive rational numbers (all programs), and the list of all evaluation states (including “halted”) of all programs. We then print only the halted states (which are annotated with the program which halted).

Here is the uncompressed and commented version:

import Data.Ratio
import Data.List
import Data.Either

-- List of all positive rational numbers
rationals = do
  limit <- [1..]
  let r = repeat limit
  (p,q) <- zip r [1..limit] ++ zip [1..limit] r
  if gcd p q == 1 then [p%q] else []
-- List of all lists of positive rational numbers (all FRACTRAN programs)
programs = diagonal $ iterate oneMore [[]]
oneMore l = diagonal [map (:xs) rationals | xs <- l]

-- FRACTRAN evaluator
evalStep p n = find ((== 1) . denominator) $ map (* n) p
evaluation p n = n : maybe [] (evaluation p) (evalStep p n)
evaluationWithHaltMarker p = map Left (evaluation p 2) ++ [Right p]

-- All evaluation states of all programs
evaluations = diagonal $ map evaluationWithHaltMarker programs

-- All halting programs
haltingPrograms = rights evaluations

main = mapM_ print haltingPrograms

-- from http://stackoverflow.com/questions/7141287/haskell-cartesian-product-of-infinite-lists
diagonal :: [[a]] -> [a]
diagonal = concat . stripe
    where
    stripe [] = []
    stripe ([]:xss) = stripe xss
    stripe ((x:xs):xss) = [x] : zipCons xs (stripe xss)

    zipCons [] ys = ys
    zipCons xs [] = map (:[]) xs
    zipCons (x:xs) (y:ys) = (x:y) : zipCons xs ys

The Left values are never actually looked at since we don't care about non-halting states; it's just the shortest way I saw to carry through the incremental evaluation.

Some “future work” if one were trying to write a practical implementation to generate interesting programs, rather than golfing, would be to reduce the needed work by restricting the set of programs under consideration to those which:

do not have a statically obvious loop (e.g. an integer).
are unique under “register renaming”; e.g. [3/2, 5/3] is the same as [7/2, 5/7].
have no dead code under the assumption that the input is 2; e.g. in [5/3, 7/2], 5/3 is dead code because no 3s are in numerators.
have no dead code due to preceding code; e.g. in [3/2, 5/2], 3/2 will always take precedence over 5/2.

I mention these cases in particular because (other than the looping one) they form the majority of the output. As far as I've run it, it has not produced any output program of length greater than 2.


Gambler's Fallacy Dice The gambler's fallacy is a cognitive bias where we mistakenly expect things that have occurred often to be less likely to occur in the future and things that have not occurred in a while to be more likely to happen soon. Your task is to implement a specific version of this.

Challenge Explanation

Write a function that returns a random integer between 1 and 6, inclusive. The catch: the first time the function is run, the outcome should be uniform (within 1%), however, each subsequent call will be skewed in favor of values that have been rolled fewer times previously. The specific details are as follows:

The die remembers counts of numbers generated so far.
Each outcome is weighted with the following formula: \$count_{max} - count_{die} + 1\$

For instance, if the roll counts so far are \$[1, 0, 3, 2, 1, 0]\$, the weights will be \$[3, 4, 1, 2, 3, 4]\$, that is to say that you will be 4 times more likely to roll a \$2\$ than a \$3\$.
Note that the formula means that a roll outcome of \$[a, b, c, d, e, f]\$ is weighted the same as \$[a + n, b + n, c + n, d + n, e + n, f + n]\$

Rules and Assumptions

Standard I/O rules and banned loopholes apply
Die rolls should not be deterministic. (i.e. use a PRNG seeded from a volatile source, as is typically available as a builtin.)
Your random source must have a period of at least 65535 or be true randomness.
Distributions must be within 1% for weights up to 255

16-bit RNGs are good enough to meet both the above requirements. Most built-in RNGs are sufficient.

You may pass in the current distribution as long as that distribution is either mutated by the call or the post-roll distribution is returned alongside the die roll. Updating the distribution/counts is a part of this challenge.
You may use weights instead of counts. When doing so, whenever a weight drops to 0, all weights should increase by 1 to achieve the same effect as storing counts.

You may use these weights as repetitions of elements in an array.

Good luck. May the bytes be ever in your favor.

R, 59 bytes

function(){T[o]<<-T[o<-sample(6,1,,max(T)-T+1)]+1
o}
T=!1:6

Try it online!

Keeps the counts in T, which is then transformed to be used as the weights argument to sample (which then most likely normalizes them to sum to 1).

The [<<- operator is used to assign a value to T in one of the parent environments (in this case, the only parent environment is .GlobalEnv).


Implement wc (word count) shortest code wins Write a stripped down version of the wc command. The program can simply open a file which does not need to be configurable or read from stdin until it encounters the end of file. When the program is finished reading, it should print:

# bytes read
# characters read
# lines read
max line length
# words read

Program must at least work with ascii but bonus points if it works on other encodings.

Shortest code wins.

Haskell - 80 characters
l=length
main=interact$ \s->show$map($s)[l,l,l.lines,maximum.map l.lines,l.words]


Mozart golf - mini "Rondo" Output "Mozart - Alla Turca" to stdout (see the sample for "reference implementation")

Try to find how to pack both synthesizer and the music into minimal size.

Requirements:

Format suitable for feeding into aplay -f cd (signed 16-bit little endian, 2 channels);
Entire music should be played (no skipped notes or parts, at least not less than in sample program), polyphony is not required though;
Can't just call /usr/bin/timidity, /usr/bin/sox or something like that (e.g. require to install a special music module);
Can't access network or assume that the music is available locally;

"Reference implementation" with parsable score: https://gist.github.com/vi/5478693
(Old sample Perl program: https://gist.github.com/vi/5447962)

Polyphonic, Haskell, 2826 3177 4719

Audio output:
https://www.dropbox.com/s/nba6489tfet740r/hs-golf-turca.ogg

Features:

All notes from the right hand. I could of course add the left hand, too (done that).
Proper articulation of the staccato notes etc.
Reasonably nice sound with dynamics. Not just simple volume modulation, but proper morphing of the attack character and overtone content, like you get on a real piano actually, rather more... hey this piece is supposed to be imitating Turkish Janissary bands, right?
Reverb. Doesn't sound amazingly great, but not too bad, either.
Dynamic compression. Don't ask...
Dithering of the output. This is kind of ridiculous: with proper 16-bit resolution, hardly anybody would hear the quantisation artifacts, but to avoid including the binary library, I effectively use only 7-bits resolution, which I can cover with ASCII output. The dither itself is rather loud, no noise-shaping...
Multithreaded calculation of polyphonic chords.

import Control.Parallel
main=mapM_ (\(d,s)->(\p->p>>p>>p>>p).putChar.toEnum.round.(+d).(*62).min 2.abs$s+1).zip(dθ 1).lim.rev.hgp 9. pl 9e6 (\_->0) . ä
 $[mT%8.1,t2%16.1,t3(∡7)%8,t4%8,t5%16,t3(∡7)%8,mT%8.1,t2%16.1,t3(tev arp8)%8,cdT%99] >>= \e->[e,e]
mM=ä[2-^8,1-^8,0-^8,1-^8,3-^4]
cM=ä[7-^20,8-^20,9.^4,F[(7,0),(6,1)](map((∡2).(.^4))[6,5,6])%0.75]
cMv=ä[10-^2,8.^4,9.^4,hom(.^4)[[24,5],[23,8,12],[22,4],[21,6,9],[22,3],[19,5,8],[20,4],[18,6,9],[17]]#7&(-14)%2.5,tr 2%0.4,1-^9,2-^12,1-^1]%4.5
 ⋎(ä[6-^4,lp(8.^4∡3)%(3/4),sil%2,lp(5.^4∡3)%h,lp(5.^4∡2)%h,1-^1∡7]&(-14)#7#4%5)
mMa f=ä[(1-3*f).^4,lp(5.^4∡(-2-f))%0.75,mMa f%1.5,mMa(f*2)%h,mMa f%1]#7
mTm=ä[mM%1,mM&2%1,mM#4&4%h,mM&7%h,mM&7%1,8.^4,ä[10.^4]%0.2,cM%1,cM%1,cM%0.85,ä[4.^4∡2,5.^2]#6#4%2]#7
mT=p$ä[mTm%8.1⋎(ä[sil%h,mMa 0%4,mMa 1%2.75,2.^4,(-2)-^2]&(-7)%8)]
m2=ä[ä(map((∡2).(.^4))[1,2,3,3]++[es[6,5,4,3]%h]++[0-^2∡2])%2
 ⋎(ä[sil%h,1.^4,8.^4,3.^4,10.^4,5-^2]⊿1.3&(-14)%2)]
t2=p$ä[m2&2%1.8,0-^5,m2&2%2,m2#7%1.8,(-2)-^5,m2#7%2,mT%3.5,cMv]
m3=ä$[3-^4,4-^4,5-^2]++map(-^4)[3,4,5,4,3,2,1,2,3,4,2,0]
m3a=ä[(ä[sil%(1/8),lp(8.^4)%1]:zw(\d n->ä[sil%(d/24),n-^1]⊿cos d)[0..][1,3,5],s),m3a%1]
m3ra=(map((%1). \[a,b,c]->es[a,c,b,c,a,c,b,c])[[1,3,5],[1,4,6],[-2,0,5]]!!)
t3 o=ä[ä[o$ḋ[m3%4,m3%2.5,1-^4,4-^4,2-^4,0-^4]&(-2)%7.5,1-^2∡7]%8
 ⋎(ḋ[sil%(3/8),m3a&4%2,m3a%h,m3a#4%h,m3a&1%1,m3a&4%2,m3a%h,m3a&1%(5/8),5-^2]&(-18)%8)]
mQ=es[2,1,0,2]
m4=mM⇆4
i4 e=ḋ[m4⇅11%h,m4⇅9%h,mQ⇆4⇅8%h,F[(5,e),(4,1)][mQ⇅7%h,mQ⇅5%h,m4&5%h,m4&7%h]%2,es[10,9,10,9]#2%h ]
mla[b,c,d]=ä[b-^4,lp(c-^4⋎(d-^4))%1]%1
i4a=ḋ[sil%h,ä(map mla[[1,3,5],[2,4,5],[1,3,5],[0,2,5]])#5%4,ä(map mla[[1,3,5],[2,5,7],[2,6,8]])#4%3,5-^2⋎(7-^2)]
t4=p$ä[ḋ[i4 1%4,i4 0%2.5,ä[mQ⇅6%h,mQ⇅4%h]#4#2%1,3-^2]%8⋎(i4a&(-9)%8)]
mlaa=mla[1,3,5]
m5=ä$map(-^8)[1..4]
i5=ḋ[m5⇅6%h,m5%h,m5&4%h,m5⇅9%h]
i5d=hom(-^4)[[2],[4,5],[0],[4,5]]%1
i5a=ḋ[sil%h,mlaa,i5d,mlaa,mla[-2,0,4],mlaa,i5d,sq 4[1,-1,-3,-2,-6,1]%2]&(-7)
t5=ḋ[ḋ[i5%2,i5%1.5,ä[8-^4,9-^4]#1%h,i5%2,ḋ[es[5,4,3,2,3,5,1,3,2,4,0,2]%2]%1.5,1-^2]%8⋎(i5a%8)
 ,p(ä[ä[i4 1%4,es[3,2,3,1,4,3,4,3,4,3,4,3]#2#1&7%1.5,m5⇅13%h,mQ⇅8%h,m5&7%(3/8),6-^8,mQ⇅7#5%h,6-^2]%8
 ⋎(ä[i4a%3.5,F[(1,-1),(7,0),(6,1)][hom(-^4)[[-2],[3,5],[2,5],[1,5]]%1]%1,mla[-3,1,4],mla[-3,2,4],hom(-^4)[[-2],[1,3],[-2],[2,4],[1,3]]%1.5]&(-9)%8)])%8]⊿0.8
am d=3-^d∡2∡5
amf=1-^υ∡2⋎(5-^1∡3)
vh v(c,d)=lp(ä[v-^12]:map(\t->ä[t⊿0%0.04,t%d])c,d)
aam=vh 11.am
aar=ä[1-^10,4-^10,6-^1]&4
eam=vh 10.em
dm=6-^1∡2⋎(11-^1)
em d=5-^d∡2⋎(9-^1)
cdM=ḋ[4-^8,3-^8,2.^8,3.^8,cdM%1]
cdT=ḋ[ä[3-^(8/3)∡7,10-^6,am 1,am 1,cdM&7%1,dm,aam 4.05%1,em(4/3),12-^4,am 1,am 1,cdM&7%1,dm,aam 1%1,eam 4%1]%12.5⋎(ä(sil%(11/24) : map((%1).(m3a&))[4,4,4,0,4,1,4,4,4,0,4,1])&(-18)%13.1)
 ,p(ä[ä[ä[8-^2]⊿2%h,aar%(3/8),10-^8,aar%1,aar%1,cdM&7%1,11-^1,vh 11(10-^4)%1,9-^(4/3)]%7⋎(ä(map m3ra[0,0,0,0,1,0,2])&(-7)%7)])%6.75
 ,ä[p(ä[12-^4])%(1/4),am 1,am 1,cdM&7%1,dm,aam 1%1,eam 4%1,amf,ä[3-^4,1-^υ,5-^4,1-^υ,3-^4,1-^4,3-^4,1-^4,5-^4,1-^2]%3.75∡7,ä[amf∡(-14)]%0.56,ä[amf∡(-14)]⊿0.8%1]%12⋎(ä(sil%(1/8):map((%1).(m3a&))[4,4,4,0,4,1,4,4,4]++[m3a&4%h,m3a&4%h,5-^(8/5)])&(-18)%12)]
type D=Double
data F=N Int D|F[(Int,D)][([F],D)]
φ⇸F a fs=F a$map(\(f,d)->(map φ f,d))fs
_⇸N i d=N i d
i##c
 |i<1=(i+7)##c/2
 |i>7=(i-7)##c*2
 |1>0=1.06**(c i+case i of{1->0;3->3;4->5;5->7;6->8;7->10;_->fri i})
pl dur acc(N n v)=(\ω η->map(sin.(\x->x+τ x^2/η). \i->v*exp(-i*η/s)*τ(i*v)*(0.8-τ((i-dur)/90))*sin(i*ω))[1..dur])(n##acc/15.5).exp$fri n/9
pl dur acc(F accm fs)=pl' dur (foldr(\(q,m)f i->if q==i then m else f i)acc accm) fs
pl' dur _ _|dur<=0 = []
pl' dur _ []=map(\_->0)[1..dur]
pl' dur acc((f,dr):fs)|n<-min dr dur=trans(round n)(foldr1(\a b->sum a`par`sum b`pseq`zw(+)a b)(map(pl(n+99)acc)f))$pl'(dur-dr)acc fs
trans n a b|(f,ol)<-splitAt n a,(or,l)<-splitAt 99 b=f++zw(+)ol or++l
fri=fromIntegral
F a fs#q=F((q,1):a)fs
N i d&n=N(n+i)d
f&n=(&n)⇸f
N i d⇅n=N(n-i)d
f⇅n=(⇅n)⇸f
N i d⇆_=N i d
F a fs⇆n=F a.reverse$take n fs
N i d⊿v=N i$d*v
f⊿v=(⊿v)⇸f
p=(⊿0.3)
n.^q=([F[][([N n 1],s/2/q)]],s/q)
n-^q=([N n 1],s/q)
(l,d)⋎(r,_)=(l++r,d)
(l,d)∡j=(l++map(\h->ä[h⊿0%0.01,h&j%100])l,d)
f%t=([f],s*t)
tr n=F[]$cycle[n-^15,(n+1)-^20]
ä=F[];ḋ=F$zip[6,3,7][1,1,1]
lp=ä.repeat
sil=N 0 0
tev f(l,d)=(map f l,d)
h=1/2
υ=4/3
s=4e+4
sq d=ä.map(-^d)
es=sq 8
arp8 n@(N i v)=F[][([n,ä[n⊿0%(1/8),n&7⊿(v/υ)%100]],s)]
arp8 f=arp8⇸f
hom q=ä.map(foldr((⋎).q)$sil%1)
dθ l=2*asin l/pi:dθ(abs.sin$l*1e+9)
rev ls=(\z->z id(foldr(\m sg->(\v->z(*v)(map(*0)[0..m*14349]++sg)sg)$abs(cos$(m*3)^2)-0.6)ls.take 9$dθ 1)ls)$(.lwp 3 0).zw.((+).)
lwp ω c(x:l)=c:lwp ω((x+c*ω)/(ω+1))l
lwp _ _ _=[]
hgp ω l=zw(-)l$lwp ω 0 l
lime e(x:l)
 |abs(e*x)>1,e'<-((e*8+abs(1/x))/9)=e':lime e' l
 |1>0=e:lime((e*49999+1)/5e4)l
lime _[]=[]
lim ls=zw(\a u->τ$a/9+max(-2)(min 2$a*u)/6)(map(*0)[0..500]++ls).lwp 9 0.lime 1$hgp 9 ls
zw=zipWith
τ=tanh

  $ make
  ghc -o bin/def0-hs def0.hs -O2 -fllvm -threaded
  [1 of 1] Compiling Main             ( def0.hs, def0.o )
  Linking bin/def0-hs ...
  time sh -c 'bin/def0-hs +RTS -N4 > hsoutp.pcm'
  189.39user 138.41system 2:06.62elapsed 258%CPU (0avgtext+0avgdata 6440240maxresident)k
  0inputs+0outputs (0major+403037minor)pagefaults 0swaps
  ffmpeg -loglevel panic -y -f s16le -ar 44.1k -ac 2 -i hsoutp.pcm hsoutp.ogg

Here's a partially ungolfed and commented version: https://gist.github.com/leftaroundabout/5517198.


Condense these page numbers! Disclaimer: while I have been on this site for entertainment purposes for a little while now, this is my first question, so please forgive any minor errors.

Background

When assigning us homework, my teacher is really annoying and writes out all the problems we have to do individually. As such, it takes me forever to copy down which problems I have to do. I thought to make my life easier, I would send him a program that could make the list of problems take up less space.

While writing down a list of page or problem numbers, we use a dash to denote a range. For example, 19-21 becomes 19, 20, 21. If there is a gap in between, two comma-separated ranges are used: 19-21, 27-31 becomes 19, 20, 21, 27, 28, 29, 30, 31.
Right about now, you're probably thinking: "this seems pretty trivial". In fact, this has already been answered here and here.

However, there is a catch. If we have a range with equal consecutive digits, the repeated digits can be left out. For example: 15, 16, 17 becomes 15-7, and 107, 108, 109 becomes 107-9. For a bonus, if the last consecutive equal digit is 1 greater and the upper limit's last digit is less than or equal to that of the lower, the following can be omitted (sorry if that sounded confusing; perhaps some examples will clear it up). 109-113 becomes 109-3, as a lower last digit implies increasing the 10s place.

Challenge

Your program should take a list of integers via input (whatever is standard for your language, or a function).  You can decide whether this list is comma-separated, space-separated, or as an actual list/array.

Output the shortest way (first sorted by number of ranges, then the sum of the characters included in the ranges) to represent that list using this notation. Each dashed range must be on the same line, but the ranges can be separated by commas or newlines (trailing newlines or commas are allowed). These ranges must be in order.

Since our school Wi-Fi is terrible, I have to make the file as small as possible in order to send it to him. The shortest code (in bytes) wins.

Bonuses

My teacher is sloppy, so there are a few things that would help him out.
Multiple bonuses stack through multiplication, e.g. a -10% bonus (x 90%) and a -25% (x 75%) bonus = 90% * 75% = x 67.5% (-32.5% bonus).

Sometimes he puts them in the wrong order (he's not a math teacher). Take a -20% bonus if your program can accept integers that are not sorted least-to-greatest.
Our book is weird, and each section starts counting the problems at -10. If your program can accept negative numbers, take a -25%.
If it accepts the bonus of a lower last digit increasing 10's place, e.g. 25-32 reducing to 25-2, take a -50% bonus.

Test Cases

In:  1, 2, 3, 4, 5
Out: 1-5

In:  3, 4, 5, 9, 10, 11, 12
Out: 3-5, 9-12

In:  149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160
Out: 149-60

In: 1 2 3 4
Out: 1-4

For bonuses:

In: 109, 110, 111, 112, 113
Out: 109-3

In:  19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29
Out: 19-9

In: -3, -2, -1, 0, 1, 2
Out: -3-2

In: -3, -2, -1
Out: -3--1

An answer will be accepted on Saturday, 19 December 2015.

GLHF!

C++11, 451 * 80% * 75% * 50% = 135.3 bytes
Saved 9 bytes thanks to @kirbyfan64sos.
Saved 19 bytes thanks to @JosephMalle and @cat.
Saved 11 bytes thanks to @pinkfloydx33.
#include<vector>
#include<cmath>
#include<algorithm>
#include<string>
#define T string
#define P append
using namespace std;T f(vector<int>v){sort(v.begin(),v.end());T r=to_T(v[0]);int b=1;int m=v[0];for(int i=1;i<=v.size();i++){if(i!=v.size()&&v[i]==v[i-1]+1){if(!b){m=v[i-1];}b=1;}else{if(b){T s=to_T(v[i-1]);r.P("-").P(s.substr(s.size()-(v[i-1]-m==1?1:log10(v[i-1]-m)),s.size()));}if(i!=v.size()){r.P(", ").P(to_T(v[i]));}b=0;}}return r;}

This qualifies for all the bonuses.
Sample parameter test and result:
In:  [1, 2, 3, 4, 5]
Out: 1-5

In:  [3, 4, 5, 9, 10, 11, 12]
Out: 3-5, 9-12

In:  [149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160]
Out: 149-60

In:  [1, 2, 3, 4]
Out: 1-4

In:  [109, 110, 111, 112, 113]
Out: 109-3

In:  [19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
Out: 19-9


Key length of Vigenère cipher The Vigenère cipher is a substitution cipher where the encryption of each letter of the plaintext depends on a different character in a keyword.  This stops you using simple methods of frequency analysis to guess the correct substitution.  However, the keyword is repeated if it is shorter than the plaintext.  This is a weakness.  If the length of the keyword is known (n, say), however, and is much shorter than the message, then you can decompose the message into separate sections by taking every nth letter.  You can then use frequency analysis on these.

The Kasiski examination is a method to work out the most likely key lengths.  It does this by considering identical substrings which happen to be a multiple of the key length apart.  They are therefore encrypted in the same way.  Turning this round, identical substrings in the ciphertext are likely to be a multiple of the key length apart.  If you identify these distances, then the key length is likely to be a common factor of all these distances.

Your job is to write a function or program that can guess the most likely length of the keyword, given some encrypted text.  To be precise, the function or program (just called function below) will satisfy the following:

Inputs consist of a string representing the ciphertext and a positive integer (len, for the purposes of this spec) representing the shortest common substring to look at.
The ciphertext will consist of upper case A-Z characters only. Any length is permitted.
You can assume valid inputs without checking.
The inputs may be passed in, or read from stdin.
The function will identify all pairs of identical substrings in the ciphertext which have a length of at least len.
Substrings in each pair may not overlap but substrings in different pairs can overlap.
The function will return, or write to stdout, the highest common factor of the distances between the starts of these identical pairs.
If there are no identical substrings then the function will return 0.

For example:

"AAAAAAAAAAAAAAAAAA", n returns 1 for any n from 1 to 8, 9 for n = 9 (as the only possible non-overlapping substrings of length 9 happen to be the same) and 0 otherwise.

"ABCDEFGHIJKL", n returns 0 for any n

"ABCDEABCDE", n returns 5 for n<=5 and 0 otherwise

"ABCABABCAB", 2 returns 1 because "AB" pairs are separated by 2,3,5 & 8

"ABCABABCAB", 3 returns 5

"VHVSSPQUCEMRVBVBBBVHVSURQGIBDUGRNICJQUCERVUAXSSR", 4 returns 6 because the repeating "VHVS" are 18 characters apart, while "QUCE" is separated by 30 characters

Naturally, lowest byte count wins and avoid standard loopholes.

CJam, 67 bytes

Definitely still room for improvement, but I'll post what I have so far.

Try it online

0r:T,,ri>{T,L(-,_m*{~:XT>L<T@LX+e>,{0t}/X>\#_W>\2$?{\1$_!+%}h;}/}fL


"list comprehension" in php. PHP has closures, let's play around with them.

I have some arrays similar to, $wannabelist = array (1, 2, 3, 4, 5, 6).

I want to do this: compr( expression($params), $wannabelist, $wannabilist2 ...).

compr() should do the following:

Take all the possible combinations of elements of the arrays given as parameters;
Pass each of them to the expression passed as first parameter;
Yield the result.

A particularly satisfying function will:

Avoid changing the value of any variable;
Be elegant;
Contain an inordinate amount of nested parenthesis/brackets;
Avoid foreach() loops.

First, a few neat things about list comprehensions, from a Haskell perspective:

The list monad in Haskell is set up so any list comprehension can be transformed into do notation rather easily:

> [(i,j) | i <- [1..3], j <- [1..3]]
[(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)]
> do {i <- [1..3]; j <- [1..3]; return (i,j)}
[(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)]

Haskell has a sequence function that takes a list of "actions" in a monad and returns a list of the results:

> sequence [getLine, getLine, getLine]
one
two
three
["one","two","three"]

Consequently, using sequence with the list monad gives you combinations for free:

> do {i <- [1..3]; j <- [1..3]; return [i,j]}
[[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]
> sequence [[1..3], [1..3]]
[[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]

Hence, the sequence function is very similar to the compr function asked for.  It just needs to be wrapped and mapped a bit:

function compr()
{
    $args = func_get_args();
    $f = $args[0];
    $call_f = function($array) use ($f) {
        return call_user_func_array($f, $array);
    };
    return array_map($call_f, sequence(listMonad(), array_slice($args, 1)));
}

Now, without further ado, here is a nearly direct translation of the list monad and sequence function from Haskell to PHP:

# instance  Monad []  where
#     m >>= k          = concat (map k m)
#     return x         = [x]
#     fail s           = []
function listMonad()
{
    return (object) array(
        'bind'   => function($m, $k) {
            return call_user_func_array('array_merge', array_map($k, $m));
        },
        'return' => function($x) { return array($x); },
        'fail'   => function($s) { return array(); }
    );
}

# sequence       :: Monad m => [m a] -> m [a]
# sequence       =  foldr mcons (return [])
#                     where mcons p q = p >>= \x -> q >>= \y -> return (x:y)
function sequence($monad, $list)
{
    $mcons =
        function($p, $q) use ($monad) {
            return call_user_func($monad->bind, $p,
                function($x) use ($monad, $q) {
                    return call_user_func($monad->bind, $q,
                        function($y) use ($monad, $x) {
                            return call_user_func($monad->return, cons($x, $y));});});};
    return foldr($mcons, call_user_func($monad->return, array()), $list);
}

# foldr            :: (a -> b -> b) -> b -> [a] -> b
# foldr f z []     =  z
# foldr f z (x:xs) =  f x (foldr f z xs)
function foldr($f, $z, $xs)
{
    if (empty($xs))
        return $z;
    return call_user_func($f, $xs[0], foldr($f, $z, array_slice($xs, 1)));
}

function cons($x, $xs)
{
    return array_merge(array($x), $xs);
}

I believe this meets all four of your criteria, especially the "inordinate amount of nested parenthesis/brackets" part.

Test code:

function printList($show, $list)
{
    echo showList($show, $list) . "\n";
}

function showList($show, $list)
{
    $str = "[";
    foreach($list as $x) {
        if ($str !== "[")
            $str .= ",";
        $str .= call_user_func($show, $x);
    }
    return $str . "]";
}

# Count in binary
printList('strval',
    compr(function($a, $b, $c, $d) {
        return "$a$b$c$d";
    }, array(0,1), array(0,1), array(0,1), array(0,1)));

# Combinations of items
printList(function($a) {return showList('strval', $a);},
    compr(function($a, $b, $c) {
        return array($a, $b, $c);
    }, array(1, 2), array(3, 4, 5), array(6, 7, 8, 9)));

Output:

[0000,0001,0010,0011,0100,0101,0110,0111,1000,1001,1010,1011,1100,1101,1110,1111]
[[1,3,6],[1,3,7],[1,3,8],[1,3,9],[1,4,6],[1,4,7],[1,4,8],[1,4,9],[1,5,6],[1,5,7],[1,5,8],[1,5,9],[2,3,6],[2,3,7],[2,3,8],[2,3,9],[2,4,6],[2,4,7],[2,4,8],[2,4,9],[2,5,6],[2,5,7],[2,5,8],[2,5,9]]


Alternating Power Fibonacci Sequence Definition

The Alternating Power Fibonacci Sequence is formed as follows.

Start with the empty sequence and set n to 1.
Compute fn, the nth non-negative Fibonacci number, with repetitions.
0 is the first, 1 is the second and the third, 2 is the fourth. All others are obtained by summing the two previous numbers in the sequence, so 3 = 1 + 2 is the fifth, 5 = 2 + 3 is the sixth, etc.
If n is odd, change the sign of fn.
Append 2n-1 copies of fn to the sequence.
Increment n and go back to step 2.

These are the first one hundred terms of the APF sequence.

 0  1  1 -1 -1 -1 -1  2  2  2  2  2  2  2  2 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3
-3 -3 -3 -3 -3 -3  5  5  5  5  5  5  5  5  5  5  5  5  5  5  5  5  5  5  5
 5  5  5  5  5  5  5  5  5  5  5  5  5 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8
-8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8

Task

Write a full program or a function that takes a positive integer n as input and prints or returns the nth term of the APF sequence.

If you prefer 0-based indexing, you can alternatively take a non-negative integer n and print or return the APF number at index n.

This is code-golf; may the shortest code in bytes win!

Test cases (1-based)

    1 ->    0
    2 ->    1
    3 ->    1
    4 ->   -1
    7 ->   -1
    8 ->    2
  100 ->   -8
  250 ->   13
  500 ->  -21
 1000 ->   34
11111 ->  233
22222 -> -377
33333 ->  610

Test cases (0-based)

    0 ->    0
    1 ->    1
    2 ->    1
    3 ->   -1
    6 ->   -1
    7 ->    2
   99 ->   -8
  249 ->   13
  499 ->  -21
  999 ->   34
11110 ->  233
22221 -> -377
33332 ->  610

Python 2, 30 bytes

f=lambda n:n<1or f(n/4)-f(n/2)

Try it online!

One-indexed.

The sequence felt like a puzzle, something that Dennis generated by having a short way to express it. The power-of-two repetitions suggest recursing by bit-shifting (floor-dividing by 2). The alternating-sign Fibonacci recursion f(n)=f(n-2)-f(n-1) can be adapted to bitshift in place of decrementing. The base case works out nicely because everything funnels to n=0.


Given a Diagram, Find X Find X
I was inspired by math questions in which one is asked to "Find X" for a given shape. Originally, I was just going to have the challenge be to print the x and y location of the character 'x' in a String. But I supposed that would be too simple. So I considered the context they were normally in, and decided finding the length of a Line next to the x just seemed appropriate.
Given a string input containing a Diagram of ascii 'lines' as well as a single 'x' and potentially junk characters, print the length of the only line that has an 'x' directly adjecent to it.
Examples
Input:
|
|
|x
|
|

Ouput:
5

Input:
|\
| \x
|  \
|___\

Output:
4

Input:
Diagram of a Wobbly Line:
IRRELEVANTTEXT____
____     ____/
    \___/ X ;)
      x

Output:
3

Input:
  ______________
 / ____________ \
 |/ __________ \|
 ||/ ________ \||
 |||/ ______ \|||
 ||||/      \||||
 |||||/  x  |||||
 |||||\_____/||||
 ||||\_______/|||
 |||\_________/||
 ||\___________/|
  \_____________/

Output:
5

Notes

The Valid line characters are \/_|
\ connects the top left and bottom right of itself.
/ connects the top right and bottom left of itself.
_ connects the left and right of itself
| connects the top and bottom of itself
A line will always be straight, and only consist of one of the line characters repeated n times.
The x will always be lowercase, and it will always be the only one in the diagram.
Adjecent refers to the x being exactly one character above, below, or besides.
The x will always be next to exactly one Line.
Tabs will never appear in the input.
Input and Output may be any acceptable format.
This is Code Golf, so Shortest Code Wins!
HAVE FUN. DO IT. ENJOY YOURSELF.

Reference Implementation

Python 3, 428 408 385 378 bytes

Working, but has a ton of potential to be golfed. I'm a bit rusty.

Assumes input is padded with spaces to make a rectangle.

EDIT: Thanks to @Artyer for 23 byte savings!

EDIT2: Wow I completely missed a 6 byte savings. Saved 1 more by swapping sides of an equals check.

*i,=map(list,input().split('\n'))
r=c=s=q=e=w=0
o=lambda y,x:len(i[0])>x>=0<=y<len(i)
d='\/_|'
for l in i:
 if'x'in l:r=i.index(l);c=l.index('x')
for a,b in(1,0),(0,1),(-1,0),(0,-1):
 y,x=r+a,c+b;f=o(y,x)and i[y][x]
 if f in d:s=f;w=d.index(f);q,e=y,x
k=lambda y,x,g=[1,1,0,1][w],v=[1,-1,1,0][w]:o(y,x)and s==i[y][x]and(exec('i[y][x]=0')or 1+k(y+g,x+v)+k(y-g,x-v))
print(k(q,e))

Expanded version with explanation:

inputtt='''  ______________.
 / ____________ \
 |/ __________ \|
 ||/ ________ \||
 |||/ ______ \|||
 ||||/      \||||
 |||||/  x  |||||
 |||||\_____/||||
 ||||\_______/|||
 |||\_________/||
 ||\___________/|
  \_____________/'''

# First, we get the input from STDIN and make it
# into a doubly-nested array

*input_text,=map(list,inputtt.split('\n'))

# A pretty cool Python trick to assign 0 to
# mulitple variables at once.

row=col=line_letter=line_row=line_col=line_char_index=0

# A function to check if a certian row and col is
# in bounds or not. Uses python's comparator chaining

in_bounds=lambda y,x:len(input_text[0])>x>=0<=y<len(input_text)

# A string to store all the line characters.
chars='\/_|'

# Search for the x
for line in input_text:

 # If this line contains the x...
 if'x'in line:

     # Mark the row and column
     row=input_text.index(line);col=line.index('x')

# For each direction...
for down,right in(1,0),(0,1),(-1,0),(0,-1):

 # Move in that direction
 y,x=row+down,col+right

 # If the position is in bounds, mark the char at that position
 line_found=in_bounds(y,x)and input_text[y][x]

 # If the char is a line char, set all the variables saying we found it
 if line_found in chars:
  line_letter=line_found
  line_char_index=chars.index(line_found)
  line_row,line_col=y,x

recur=lambda y,x,\
       # Find which directions we are supposed to recur in based on the line char
       g=[1,1,0,1][line_char_index],v=[1,-1,1,0][line_char_index]:\
       # If the char is in bounds and we are still on the line...
       in_bounds(y,x)and input_text[y][x]==line_letter and\
       # Set the spot to a 0, so we won't go back, increment,
       # and recur in both directions
       (exec('i[y][x]=0')or 1+recur(y+g,x+v)+recur(y-g,x-v))

# Finally, print the answer
print(recur(line_row,line_col))


Let's build a Staircase We don't have enough (semi-)easy challenges for beginners. More and more of the easy ones are already taken. So I tried to come up with something that might be achievable by beginners, but that isn't a duplicate.
Input:
A single string separated with your OS new-line (i.e. \r\n),
or an array with multiple strings.
Output - The Stairs:
Remove all non-alphabetic and non-numeric symbols. So all that's left is [A-Za-z0-9]. And then 'build a stairs'; basically ordering them on length with the smallest at top and widest at the bottom.
Challenge rules:

When two strings are of equal length, we merge them with each other as one big string (the order doesn't matter, so it could be from first to last or last to first, whichever of the two you prefer).
The rule above can stack when the merged strings are of equal length again (see test case 2).

General rules:

The input is STDIN and contains only ASCII characters. And the output is STDOUT.
The case of the output must be the same as the input.
Each submission must be a full program able to compile and run, so not just a method/function. EDIT: I'm rather new, so perhaps it's indeed better to use the default from now on, even though I prefer a full program myself. Sorry for everyone that has already posted a full program. Feel free to edit, and I'll try to not change the post mid-challenge next time.
This is code-golf, so the shortest answer in bytes wins. I probably accept the shortest answer in a year from now.
Don't let code-golf answers discourage you from posting golfed non-codegolf languages like C# and alike! Try to come up with the shortest answer for any programming language.
Feel free to use newer languages than this question.

Test cases:
Input 1:
This is a sample text,
that you will have to use to build stairs.
The wood may be of excellent quality,
or pretty crappy almost falling apart and filled with termites.
Bla bla bla - some more text
Ok, that will do

Output 1:
Okthatwilldo
Thisisasampletext
Blablablasomemoretext
Thewoodmaybeofexcellentquality
thatyouwillhavetousetobuildstairs
orprettycrappyalmostfallingapartandfilledwithtermites

Input 2:
A
small
one
that
contains
equal
length
strings
for
the
special
rule

Output 2:
A                   Or alternatively:       A
length                                      length
oneforthe                                   theforone
smallequal                                  equalsmall
stringsspecial                              specialstrings
thatrulecontains                            containsrulethat

Steps explained of 2:
First order on length:
A
one
for
the
that
rule
small
equal
length
strings
special
contains

First merge:
A
oneforthe
thatrule
smallequal
length
stringsspecial
contains

Second order on length:
A
length
thatrule
contains
oneforthe
smallequal
stringsspecial

Second merge:
A
length
thatrulecontains
oneforthe
smallequal
stringsspecial

Third order on length:
A
length
oneforthe
smallequal
stringsspecial
thatrulecontains

Input 3:
Test,
test.
This
is
a
test.

Output 3:
a                   Or alternatively:       a
is                                          is
TesttestThistest                            testThistestTest

Input 4:
a
bc
d!
123

Output 4:
123     Or alternatively:    123
adbc                         dabc

Python 3, 264 Bytes
I'm not good at code golf so I'm confident this won't be the best Python 3 answer. This uses recursion and an ordered dict with all the words for each length.
from collections import*
def f(i):
 d = defaultdict(list)
 for l in i: x = "".join(c for c in l if c.isalnum());d[len(x)].append(x)
 n = (sorted(["".join(d[z]) for z in d.keys()], key=len))
 if n == i:return "\n".join(n)
 return f(n)
print(f(eval(input())))

Takes input from stdin as a list, for example, test it with this list:
['A', 'small', 'one', 'that', 'contains', 'equal', 'length', 'strings', 'for', 'the', 'special', 'rule']

Will output:
A
length
oneforthe
smallequal
stringsspecial
thatrulecontains


Compute the Optimal Square Matrix The optimal matrix (for the rather narrow scope of this challenge) is obtained by "zipping" the elements from the corresponding rows and columns of a square matrix and getting the maximum of each pair.
For instance, given the following matrix:
4 5 6
1 7 2
7 3 0

You can combine it with its transpose to get: [[[4,5,6],[4,1,7]],[[1,7,2],[5,7,3]],[[7,3,0],[6,2,0]]]. If you zip each pair of lists, you obtain the following: [[(4,4),(5,1),(6,7)],[(1,5),(7,7),(2,3)],[(7,6),(3,2),(0,0)]]. The last step is to get the maximum of each pair to get the optimal matrix:
4 5 7
5 7 3
7 3 0

Your task is to output the optimal matrix of a square matrix given as input. The matrix will only contain integers. I/O can be done in any reasonable format. The shortest code in bytes (either in UTF-8 or in the language's custom encoding) wins!
Tests

[[172,29],[29,0]] -> [[172,29],[29,0]]
[[4,5,6],[1,7,2],[7,3,0]] -> [[4,5,7],[5,7,3],[7,3,0]]
[[1,2,3],[1,2,3],[1,2,3]] -> [[1,2,3],[2,2,3],[3,3,3]]
[[4,5,-6],[0,8,-12],[-2,2,4]] -> [[4,5,-2],[5,8,2],[-2,2,4]]

Jelly, 2 bytes

»Z

Try it online!

How it works

»Z  Main link. Argument: M (integer matrix)

 Z  Zip the rows of M, transposing rows and columns.
»   Take the maxima of all corresponding integers.


What's the voltage over each component? The picture below shows a RLC circuit. A RLC circuit is an electrical circuit consisting of a resistor (R), an inductor (L), and a capacitor (C), connected in series or in parallel. (1)

In order to simplify computations, it's common to work in the frequency (Laplace) domain instead of the time domain.

Your task is:

Take the values R, L and C as input, and return the voltages VR, VL and VC

The conversion to the Laplace domain is as follows:

R = R
XL = j*w*L      // OK, XL = w*L, and ZL = j*XL, but don't mind this here.
XC = 1/(j*w*C)  // I haven't ruined physics, it's only a minor terminology tweak

where j = sqrt(-1), and w = 2*pi*50 (The frequency is 50 Hz).

The combined impedance, when the components are in series is Z = R + XL + XC. You might remember U = R*I from high school physics lectures. It's almost the same, but a bit more complex now: VS = Z*I. The current is calculated by dividing the voltage VS by the total impedance Z. To find the voltage over a single component, you need to know the current, then multiply it by the impedance. For simplicity, the voltage is assumed to be VS = 1+0*j.

Equations you might need are:

XL = j*w*L
XC = 1/(j*w*C)
Z = R + XL + XC   // The combined impedance of the circuit
I = VS / Z         // The current I (Voltage divided by impedance)
VR = I * R        // Voltage over resistance (Current times resistance)
VL = I * XL       // Voltage over inductor (Current times impedance)
VC = I * XC       // Voltage over capacitor (Current times impedance)

The input is from either STDIN or as function arguments. The output/result must be three complex numbers, in a list, string or whatever is most practical in your language. It's not necessary to include names (ex VR = ...), as long as the results are in the same order as below. The precision has to be at least 3 decimal points for both the real and imaginary part. The input and output/results can be in scientific notation if that's default in your language.

R and L are >= 0, and C > 0. R, L, C <= inf (or the highest possible number in your language).

A simple test case:

R = 1, L = 1, C = 0.00001

VR = 0.0549 + 0.2277i
VL = -71.5372 +17.2353i
VC = 72.4824 -17.4630i

For the results above, this could be one (of many) valid ouput format:

(0.0549 + 0.2277i, -71.5372 +17.2353i, 72.4824 -17.4630i)

Some valid ouput formats for one voltage value are:

1.234+i1.234,   1.23456+1.23456i,   1.2345+i*1.2345,   1.234e001+j*1.234e001.

This list is not exclusive, so other variants can be used, as long as the imaginary part is indicated by an i or a j (common in electrical engineering as i is used for current).

To verify the result for other values of R,L and C, the following must be true for all results: VR + VL + VC = 1.

The shortest code in bytes win!

By the way: Yes, it's voltage over a component, and current through a component. A voltage has never gone through anything. =)

Mathematica, 33 bytes

So close to Pyth...

l/Tr[l={#,#2(x=100Pi*I),1/x/#3}]&

This is an unnamed function, which takes R, L and C as its three arguments and returns a list of complex numbers as the result (in the required order VR, VL, VC). Example usage:

l/Tr[l={#,#2(x=100Pi*I),1/x/#3}]&[1, 1, 0.00001]
(* {0.0548617 + 0.22771 I, -71.5372 + 17.2353 I, 72.4824 - 17.463 I} *)


Aircraft Marshalling School Given a string representing a series of aircraft marshalling hand signals, write a function or program to calculate the final position of an aircraft following these signals.

N.B.: Co-ordinates in this challenge are represented as a pair of Cartesian co-ordinates, plus a compass direction heading: (x, y, h) where x is the x-coordinate, y is the y-coordinate, and h is one of N, E, S, or W.

You start with an aircraft at (0, 0, N) on an imaginary grid, with engines off. Your input is a string containing comma-delimeted pairs of characters, where each pair represents one marshalling signal. You must follow each marshalling signal in turn, and output the co-ordinates in (x, y, h) form of the aircraft's final position.

If a signal requires your aircraft to move, assume it moves one unit in the required direction for each signal of that type that it receives. If a signal requires your aircraft to turn, assume it turns 90 degrees in the required direction for each signal of that type that it receives.

An aircraft cannot move if its engines are off. If your aircraft's engines are off and you receive a movement/turn signal, do not apply the movement/turn.

Signals

Each marshalling signal is represented by one pair of characters. The first of the pair represents the position of the marshaller's left arm, from the aircraft's point of view, and the second the right arm from the same POV. This handy chart of signals may help.

o/  —  START ENGINES (no movement, no turn)
-/  —  CUT ENGINES   (no movement, no turn)
-~  —  TURN LEFT     (no movement, left turn)
~-  —  TURN RIGHT    (no movement, right turn)
~~  —  COME FORWARD  (forward movement, no turn)
::  —  MOVE BACK     (backward movement, no turn)
/\  —  NORMAL STOP   (no movement, no turn)

This is not the complete list of marshalling signals, but it's all you're required to support.

Input

Input is a comma-delimeted string containing pairs of characters. This string will always be valid - you do not have to validate the input.

Output

Output is a set of co-ordinates as described above. You can return this in any convenient format - if your language supports multiple return values, you may use that; alternatively, you can use a string (the brackets surrounding the co-ordinates are non-compulsory), array, tuple, list, or whatever else you find convenient. The only rule is that it must contain x, y, and h values, in that order.

Test Cases

Input  —  Output
o/,~~,~~,~-,::  —  (-1, 2, E)
::,~-,o/,/\,~~,-~,~~,~~,~~  —  (-3, 1, W)
o/,::,-/,~~,o/,~-,~~,~~,~-  —  (2, -1, S)
o/,~-,~-,::,::,~-,~~,-~  —  (-1, 2, S)
~-,~-,o/,::,::,-/,~~,-~  —  (0, -2, N)

Java 8, 505 bytes
Golfed (with help from @masterX244 for shaving a big chunk off)
class f{static boolean T(String u,String v){return u.equals(v);}public static void main(String[]a){java.util.Scanner q=new java.util.Scanner(System.in);String s=q.nextLine();int x=0;int y=0;int d=0;int[][]v={{0,1},{-1,0},{0,-1},{1,0}};int b=1;for(String r:s.split(",")){if(T(r,"o/")||T(r,"-/"))b=~1;if(b<0){if(T(r,"~-"))d=(d+3)%4;if(T(r,"-~"))d=(d+1)%4;if(T(r,"~~")){x+=v[d][0];y+=v[d][1];}if(T(r,"::")){x-=v[d][0];y-=v[d][1];}}}System.out.println("("+x+","+y+","+"NWSE".charAt(d)+")");}}

More readable
class f {
    static boolean T(String u,String v){return u.equals(v);}
    public static void main(String[] a) {
        java.util.Scanner q=new java.util.Scanner(System.in);
        String s=q.nextLine();
        int x=0;
        int y=0;
        int d=0;
        int[][] val = {
                {0,1},  // N
                {-1,0}, // W
                {0,-1}, // S
                {1,0}   // E
        };
        int b=1;
        for (String r: s.split(",")) {
            // toggle b if either start or stop engine
            if(T(r,"o/") || T(r,"-/"))
                b=~1;
            if(b<0){
                // right
                if(T(r,"~-")) d=(d+3)%4;
                // left
                if(T(r,"-~")) d=(d+1)%4;
                // come forward
                if(T(r,"~~")) {
                    x+=val[d][0];
                    y+=val[d][1];
                }
                // move back
                if(T(r,"::")) {
                    x-=val[d][0];
                    y-=val[d][1];
                }
            }
        }
        System.out.print("("+x+","+y+","+"NWSE".charAt(d)+")");
    }
}


Output a shuffled deck using random input Input/Output:

Input: A uniformly random, infinitely long, string of '0's and '1's, taken from stdin.  The string is assumed to be truly random, not pseudo-random.  It is uniform in that each character is equally likely to be a '0' or '1'.

Careful! The input is infinitely long, so you can't store it all in memory using a function like raw_input() in python.  If I'm not mistaken, golfscript will fail with infinite input, since it pushes the entire input onto the stack prior to running.

Output: A uniformly random shuffled standard deck, without jokers.  It is uniform in that all orderings are equally likely.

Each card in the output is it's rank, A, 2-9, T, J, Q or K concatenated with it's suit, c, d, h or s.  For example, the 10 of spades is Ts

The cards of the deck should be separated by spaces.

You may not use built-in random libraries or functions because they are not truly random, only pseudo-random.

Example input

You may use the following python script to pipe input into your program:

import sys, random
try:
    while True:
        sys.stdout.write(str(random.randint(0,1)))
except IOError:
    pass

If you save the script as rand.py, test your program with python rand.py | your_program

In python 3 it runs as expected, but in python 2.7 I get an error message after my program's output, but only after everything's done, so just ignore the error message.

Example output:

Here's how the deck should be printed if it happened to be shuffled into a sorted order:

Ac 2c 3c 4c 5c 6c 7c 8c 9c Tc Jc Qc Kc Ad 2d 3d 4d 5d 6d 7d 8d 9d Td Jd Qd Kd Ah 2h 3h 4h 5h 6h 7h 8h 9h Th Jh Qh Kh As 2s 3s 4s 5s 6s 7s 8s 9s Ts Js Qs Ks

Scoring:

This is a code golf.  Shortest code wins.

Example program:

Here is a python 2.7 solution, not golfed.

import sys
def next():
    return int(sys.stdin.read(1))==1
def roll(n):
    if n==1:
        return 0
    if n%2==0:
        r=roll(n/2)
        if next():
            r+=n/2
        return r
    else:
        r=n
        while(r==n):
            r=roll(n+1)
        return r
deck = [rank+suit for suit in 'cdhs' for rank in 'A23456789TJQK']
while len(deck)>0:
    print deck.pop(roll(len(deck))),


Check membership of an infinite list As input you will receive

An integer \$a\$
A list of integers that is infinite and strictly-monotonic1.

Your program should check in finite time if \$a\$ appears the list.

You should output one of two disctinct values.  One if \$a\$ appears in the list and the other if \$a\$ does not.

This is code-golf so answers will be scored by their length in bytes with fewer bytes being better.

You may take an infinite lists in any of the following formats:

A list, stream, iterator or generator if your language allows them to be infinite.
A function or pointer to a function that outputs the next value when queried with no input.
A function or pointer to a function that outputs the \$n\$th value when passed \$n\$ as an input.

Additionally you may repeatedly query STDIN with the assumption that each query will provide the next term in the sequence.

Test cases

Since I cannot put infinite lists in the body of a challenge I will provide the first couple terms along with a description of the list and a definition in Haskell.

6
1 2 3 4 5 6 7 8 9 10 ... (positive integers) l=[1..]
 =>
True

6
-1 -2 -3 -4 -5 -6 -7 -8 -9 -10 ... (negative integers) l=[-1,-2..]
 =>
False

109
0 2 4 6 8 10 12 14 16 18 20 ... (non-negative even integers) l=[0,2..]
 =>
False

-5
200 199 198 197 196 195 194 193 192 ... (integers smaller than 201) l=[200,199..]
 =>
True

256
1 2 3 5 8 13 21 34 55 89 144 ... (unique fibonacci numbers) l=1:2:zipWith(+)l(tail l)
 =>
False

1
1 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 ... (integers less than 2) l=[1,0..]
 =>
True

1: A strictly monotonic sequence is either entirely increasing or entirely decreasing.  This means if you take the differences between consecutive elements they will all have the same sign.

Python 2, 43 bytes

Takes as input the target integer \$a\$, and a lambda function \$g\$. Since the list is always either strictly increasing or decreasing, we only need to check if \$a\$ appears in the next \$ |a-g(0)|+1 \$ numbers.

lambda a,g:a in map(g,range(abs(a-g(0))+1))

Try it online!


n-level Ouroboros Quine This 128-language quine ouroboros (a program which outputs a program in another language, which outputs a program in yet another language, (125 languages later), which outputs the original program) is pretty impressive. But unfortunately, it has a static number of iterations.

Write a program which outputs a program (not necessarily in another language, but it can be), which outputs a program, which outputs a program, etc., which after n iterations, outputs the original program for the first time (i.e. no intermediate program should be the same as the original, because otherwise a quine which ignores its input would work), where n is a non-negative integer provided as input. The input can't be just a number in the original source code (e.g. putting x = <the value of n> at the start of your program), it should be one of the following:

Passed as a command-line argument
Read from standard input
Passed as an argument to a function, which returns/outputs the new program.

For intermediate stages in the ouroboros, your program can either be a fully-functioning program, or a function with no arguments, which, when called, will return/output the next one.

You may not read from the source file itself, or use any quine-like builtins (I don't think there are any which would do this, but there might be)

To be clear, if n = 0, the program should output its own source code.

If n = 1, the program should output a different program, which outputs the original source code.

And so on...

Fewest bytes wins!

Edit:

I should have written "For intermediate stages in the ouroboros, your program can either be a fully-functioning program with no input, or a function with no arguments". If your program outputs the next one in the chain, then waits for input, that's fine, but your program shouldn't need the original value of n.

05AB1E, 28 bytes

-4 bytes + fix thanks to Kevin Cruijssen

"34çìD«s<©di®ì"34çìD«s<©di®ì

Try it online!

Explanation

This works by appending the remaining number to print to the front of the code, which means it's added to the stack the same way an input would be. In the base case of input of "0" it will not concatenate the 0 on the front.


Make a Bit Continent Let's imagine we have a matrix of bits (which contains at least one 1):

0 1 0 1 1 0 1 0 0 1 0
0 1 0 1 0 0 1 0 1 1 0
0 0 1 0 1 1 0 1 0 1 0
1 1 0 0 1 0 0 1 1 0 1
0 0 0 1 0 1 1 0 0 1 0

We want to set some of the bits in this matrix such that it forms a contiguous blob of 1s, in which every 1 is directly or indirectly connected to every other 1 through orthogonal movement:

0 1 1 1 1 1 1 0 0 1 0
0 1 0 1 0 0 1 0 1 1 0
0 1 1 0 1 1 1 1 0 1 0
1 1 0 0 1 0 0 1 1 1 1
0 0 0 1 1 1 1 0 0 1 0

(You can see this more clearly by searching for 1 with your browser's "find" feature.)

However, we also want to minimize the number of bits that we set.

The Task

Given a matrix (or array of arrays) of bits or booleans, return the minimum number of bits that need to be set to create a contiguous continent of 1s. It should be possible to get from one set bit in the matrix to another by only traveling in an orthogonal direction to other set bits.

This is code-golf, so the shortest valid submission (measured in bytes) wins.

Test Cases

0 1 0 1 1 0 1 0 0 1 0
0 1 0 1 0 0 1 0 1 1 0
0 0 1 0 1 1 0 1 0 1 0
1 1 0 0 1 0 0 1 1 0 1
0 0 0 1 0 1 1 0 0 1 0
=> 6

1 0 0 0 0 0 1 0 0
1 1 0 0 1 1 1 0 0
1 1 1 0 1 1 1 1 1
0 1 0 0 0 0 0 0 0
0 0 0 0 0 1 1 1 1
0 1 0 0 0 0 1 1 0
1 0 0 0 0 0 1 0 0
=> 4

0 0 0 1 1 1 0 1 1
0 0 1 0 0 0 0 1 0
0 0 1 1 1 1 1 1 0
1 1 0 0 1 1 0 0 0
0 0 1 1 1 0 0 1 1
0 1 1 1 0 0 0 0 0
1 1 1 0 0 1 1 1 0
1 1 1 0 1 1 0 1 1
0 0 0 0 1 0 0 0 1
1 1 0 0 1 1 0 1 1
0 0 0 0 0 0 0 1 0
0 1 1 1 1 0 0 0 0
0 0 0 1 1 0 0 0 1
0 1 0 0 1 0 1 1 0
0 1 1 1 0 0 0 0 1
=> 8

1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
=> 0

C (gcc), 308 306 bytes

Function f receives (height, width, flattened array, pointer to ans), and returns answer by pointer.

If there's no 1 in the matrix, it will return 0.

#define v A[i]
N,M,K,R,C,T,i,*A;s(x,y){i=x*M+y;if(!(x<0|y<0|x>=N|y>=M|v^1))v=2,s(x,y+1),s(x,y-1),s(x+1,y),s(x-1,y);}g(i){if(C<R){if(i^K){g(i+1);if(!v)C+=v=1,g(i+1),v=0,C--;}else{T=1;for(i=0;i<K&&!v;i++);s(i/M,i%M);for(i=0;i<K;i++)T&=v^1,v=!!v;if(T)R=C;}}}f(n,m,a,b)int*a,*b;{K=R=(N=n)*(M=m),A=a;g(0);*b=R;}

Try it online!

Ungolfed:

N,M,R,C,T,i,*A; // height, width, result, recursion depth

s(x,y)
{ // depth first search: replace all 1 in the same connected component with 2
    i=x*M+y;
    if(!(x<0|y<0|x>=N|y>=M|A[i]^1)) { // check if out of boundary
        A[i]=2;
        s(x, y+1),s(x, y-1),s(x+1, y),s(x-1, y);
    }
}

g(i)
{ // enumerate all posible solutions
    if(C<R) {
        if(i!=N*M) {
            g(i+1);      // nothing change for this entry
            if (!A[i]) { // set the entry to 1
                C++, A[i]=1;
                g(i+1);
                C--, A[i]=0;
            }
        }
        else {
            T=1;
            for (i=0; i<N*M && !A[i]; i++); // find first non-zero entry
            s(i/M, i%M);     // replace the connected component
            for (i=0; i<N*M; i++) {
                T&=A[i]!=1;   // check if no other components
                A[i]=!!A[i]; // change 2s back to 1
            }
            if (T) R=C;      // update answer
        }
    }
}

f(n,m,a,b)int*a,*b;{
    R=(N=n)*(M=m), A=a;
    g(0);
    *b=R;
}


Concise case changing code Create the shortest program that given an input string it outputs the opposite-cased string. For example if I pass the string "HeLlO" the program should output "hElLo".

Of course, neither aggregate functions can be used, nor framework functions like toupper() or tolower(). Any language is welcome.

Bash shell, 16 characters

tr A-Za-z a-zA-Z

Sample runs:

llama@llama:~$ tr A-Za-z a-zA-Z
ThIs is a TeSt!
tHiS IS A tEsT!
llama@llama:~$ echo 'Programming Puzzles & Code Golf Stack Exchange' | tr A-Za-z a-zA-Z
pROGRAMMING pUZZLES & cODE gOLF sTACK eXCHANGE

It works in a file, too (of course):

llama@llama:~$ echo 'tr A-Za-z a-zA-Z' > swapcase.sh
llama@llama:~$ echo 'This is a test!' | bash swapcase.sh
tHIS IS A TEST!


Output the Military Order In almost every row nowadays, the people tends to order themselves as militaries would do.

Challenge

Suppose 4 people where:

person 1 has priority against person 2, 3 and 4,
person 2 has priority against person 3 and 4,
person 3 has priority against person 4,
person 4 has the lowest priority.

Then, when ordering those 1...4 people in a row, the possibilities are:

1
2
3
4
1 2
1 3
1 4
2 3
2 4
3 4
1 2 3
1 2 4
1 3 4
2 3 4
1 2 3 4

Your mission is:

Given as input the number N of people. Output all the possibilities for 1...N people in the military order.

Since this is code-golf, then the shotest answer in bytes wins!

Input can be integer or string, followed by optional newline/whitespace, or an argument to your function. You can assume 1<=N<=10.

The output should be every sequence in a row, in any order. For each row, output a list/array or any other valid way for the numbers in military order.


Official Ruby Inspector Here is a simple ASCII art ruby:
  ___
 /\_/\
/_/ \_\
\ \_/ /
 \/_\/

As a jeweler for the ASCII Gemstone Corporation, your job is inspect the newly acquired rubies and leave a note about any defects that you find.
Luckily, only 12 types of defects are possible, and your supplier guarantees that no ruby will have more than one defect.
The 12 defects correspond to the replacement of one of the 12 inner _, /, or \ characters of the ruby with a space character ( ). The outer perimeter of a ruby never has defects.
The defects are numbered according to which inner character has a space in its place:

So a ruby with defect 1 looks like this:
  ___
 /\_/\
/_/  _\
\ \_/ /
 \/_\/

A ruby with defect 11 looks like this:
  ___
 /\_/\
/_/ \_\
\ \_/ /
 \ _\/

It's the same idea for all other defects.
Challenge
Write a program or function that takes in the string of a single, potentially defective ruby. The defect number should be printed or returned. The defect number is 0 if there is no defect.
Take input from a text file, stdin, or a string function argument. Return the defect number or print it to stdout.
You may assume that the ruby has a trailing newline. You may not assume that it has any trailing spaces or leading newlines.
The shortest code in bytes wins. (Handy byte counter.)
Test Cases
The 13 exact types of rubies, followed directly by their expected output:
  ___
 /\_/\
/_/ \_\
\ \_/ /
 \/_\/
0
  ___
 /\_/\
/_/  _\
\ \_/ /
 \/_\/
1
  ___
 /\ /\
/_/ \_\
\ \_/ /
 \/_\/
2
  ___
 /\_/\
/_  \_\
\ \_/ /
 \/_\/
3
  ___
 /\_/\
/_/ \_\
\  _/ /
 \/_\/
4
  ___
 /\_/\
/_/ \_\
\ \ / /
 \/_\/
5
  ___
 /\_/\
/_/ \_\
\ \_  /
 \/_\/
6
  ___
 /\_/\
/_/ \ \
\ \_/ /
 \/_\/
7
  ___
 /\_ \
/_/ \_\
\ \_/ /
 \/_\/
8
  ___
 / _/\
/_/ \_\
\ \_/ /
 \/_\/
9
  ___
 /\_/\
/ / \_\
\ \_/ /
 \/_\/
10
  ___
 /\_/\
/_/ \_\
\ \_/ /
 \ _\/
11
  ___
 /\_/\
/_/ \_\
\ \_/ /
 \/_ /
12

Ruby 2.0, 69 bytes

#!ruby -Kn0rdigest
p'×ñF<ìX‚É²Ÿ_'.index Digest::MD5.digest(gets)[0]

Hexdump (to faithfully show the binary data in the string):

00000000  23 21 72 75 62 79 20 2d  4b 6e 30 72 64 69 67 65  |#!ruby -Kn0rdige|
00000010  73 74 0a 70 27 d7 f1 46  3c 1f ec 58 82 c9 b2 9f  |st.p'..F<..X....|
00000020  5f 02 27 2e 69 6e 64 65  78 20 44 69 67 65 73 74  |_.'.index Digest|
00000030  3a 3a 4d 44 35 2e 64 69  67 65 73 74 28 67 65 74  |::MD5.digest(get|
00000040  73 29 5b 30 5d                                    |s)[0]|

Explanation:

The -Kn option reads the source file as ASCII-8BIT (binary).
The -0 option allows gets to read in the whole input (and not just one line).
The -rdigest option loads the digest module, which provides Digest::MD5.
The code then does an MD5 of the input, takes the first byte of the digest, and gets its index in the given binary string.