Increasing, decreasing, none or all? Take two inputs, a non-empty vector/list containing digits 1 and 2 and a string (no, you may not take 0/1 instead). The string will be one of the following (in lowercase, exactly as written below:

increasing
decreasing
ones
twos
all
none

If the string is ____ then you shall return the indices ___:

increasing ... where the list changes from 1 to 2 (every 2 that follows directly after a 1)
decreasing ... where the list changes from 2 to 1 (every 1 that follows directly after a 2)
ones ... of all digits that are 1
twos ... of all digits that are 2
all ... all the digits
none ... none of the digits. 0 is fine if the list is 1-indexed. A negative number is fine if the list is 0-indexed. You may also output an empty list or string.

Test cases:

These are 1-indexed. You may choose if you want 1-indexed or 0-indexed. The same vectors are used for different strings in the test cases.

--------------------------------
Vector:
1 1 2 2 2 1 2 2 1 1 2

String       - Output
increasing   - 3, 7, 11
decreasing   - 6, 9
ones         - 1, 2, 6, 9, 10
twos         - 3, 4, 5, 7, 8, 11
all          - 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
none         - 0 / []

------------------------------------
Vector:
1

String:
ones         - 1
all          - 1
decreasing / increasing / twos / none  - 0 / []

Scoring

As this is code-golf, the answer with the least bytes wins.

Explanations are encouraged!

JavaScript (Firefox 30-57), 74 73 bytes

(a,[s],i=0,p)=>[for(e of a)if({i:e>p,d:e<p,o:e<2,t:e>1,a:1}[p=e,i++,s])i]

Array comprehensions are a neat way of combining map and filter in one go. Edit: Saved 1 byte thanks to @edc65.


Can the number reach 1 by repeatedly subtracting the largest prime less than it? Challenge:

Given a number, take the largest prime strictly less than it, subtract it from this number, do this again to this new number with the biggest prime less than it, and continue doing this until it's less than 3. If it reaches 1, your program should output a truthy value, else, the program should output a falsey value.

Examples:

All of these should give a truthy value:

3
4
6
8
10
11
12
14
16
17
18
20
22
23
24
26
27
29
30
32
34
35
37
38
40
41
42
44
46
47
48
50

All of these should give falsey values:

5
7
9
13
15
19
21
25
28
31
33
36
39
43
45
49

Rules:

You can either write a program or function.
You can assume that the input is bigger than 2.
Standard loopholes apply
This is code-golf so the shortest answer wins!

Retina, 31 bytes

.+
$*
+`1(?!(11+)\1+$)11+
1
^1$

Prints 0 (falsy) or 1 (truthy).

Try it online! (The first line enables a linefeed-separated test suite.)

Explanation

.+
$*

Convert input to unary by turning input N into N copies of 1.

+`1(?!(11+)\1+$)11+
1

Repeatedly remove the largest prime less than the input. This is based on the standard primality test with regex.

^1$

Check whether the result is a single 1.


Return of the Hydra Slayer Its been a while since you killed that hydra, you basked in the glory for years, but now people are calling you washed up, a has been.  Well its time you prove them wrong, you've heard the whereabouts of annother hydra.  Simply kill it and you will be awarded all the glory you deserve.

You arrive at the armory to receive your swords but they're all out of regular swords all they have left are Sectors.  An n-sector will divide the number of heads on a Hydra by n, but can only be used if the number of heads is divisible by n.

Once again you are going to write some code to help you slay the hydra.
Your code will take as input the number of head the hydra, begins the fight with, the number of heads the hydra grows each turn, and a list of n-sectors you can use.  Your code will output an optimal pattern of moves to slay the hydra as quickly as possible

Each turn of the fight you may select a single sword to use, if after a slice the hydra has only one head you win, if not it grows heads.  You may never make no move, and if there are no possible moves available you lose.

If no solution is possible you may output anything other than a solution, e.g. an empty list, nothing, the number zero, etc.

This is code-golf so answers will be scored as their byte counts, with less being better.

Test cases

Here are some super basic test-cases, more test-cases will be added upon request.

24 heads, 1  heads per turn, [2,3] -> [3,3,2,3]
25 heads, 2  heads per turn, [2,3] -> No solutions
4  heads, 2  heads per turn, [2]   -> No solutions
4  heads, 3  heads per turn, [2,5] -> [2,5]
10 heads, 17 heads per turn, [2, 3, 7, 19] -> No solutions
10 heads, 6  heads per turn, [1,16] -> [1,16]
6  heads, 2  heads per turn, [2, 3, 5] -> [2, 5]
125 heads, 1  head per turn, [1, 2, 3, 127] -> [1, 1, 127]


What's my middle name? Note: The winning answer will be selected on 4/12/17 the current winner is Jolf, 1 byte.

I'm surprised that we haven't had a what's my middle name challenge on this site yet. I did alot of searching but found nothing. If this is a dup, please flag it as such.

Your challenge

Parse a string that looks like Jo Jean Smith and return Jean.

Test cases

Input: Samantha Vee Hills
Output: Vee

Input: Bob Dillinger
Output: (empty string or newline)

Input: John Jacob Jingleheimer Schmidt
Output: Jacob Jingleheimer

Input: Jose Mario Carasco-Williams
Output: Mario

Input: James Alfred Van Allen
Output: Alfred Van

(That last one is incorrect technically, but fixing that  would be too hard.)

Notes:

Names will always have at least 2 space-separated parts, with unlimited middle names between them or can be a list/array of strings.
Names may contain the alphabet (case-insensitive) and - (0x2d)
You may output a trailing newline.
You may require input to have a trailing newline.
Input from STDIN, a function parameter, or command-line argument is allowed, but hard-coding it in is not allowed.
Standard loopholes forbidden.
Output may be function return value, STDOUT, STDERR, etc.
Trailing spaces/newlines/tabs in the output are allowed.
Any questions? Comment below!

This is code-golf, so the shortest anwser in bytes wins!

Ohm, 2 bytes (CP437)

Accepts and returns a list of strings.

()

Explanation:

()   Main wire, arguments: a

(    Remove the first element of a
 )   ...and then the last element of that
     Implicit output


Solve the Halting Problem for Befinge Let's define a simple 2D language, which we'll give the incredibly original name befinge. Befinge has 5 instructions:

<>^v, as in most 2D esolangs, redirect the instruction pointer in their respective directions.
. is  a no-op.

The instruction pointer starts out at the top-left corner going right. If the instruction pointer gets to an edge, the program halts. Every Befinge program will obviously either halt or go into an infinite loop which does nothing. Here are two examples:

Halting:

>.v
..<

Non-Halting:

>....v
..v..<
..>v..
^..<..

The halting problem is not solvable for a Turing-complete language, but it is for this one. Your task is to write a program (or function) that takes as input a string representing the befinge program and returns a truthy or falsey value depending on whether it halts or not.

You can assume that the input will consist only of these characters and will be padded with spaces to form a rectangle.
You can use any set of five characters for the instructions (e.g. adws ).

Test Cases

Halting:

.

v>
>^

....v....
....>...v
.^..<....
.......v<
.......v.
....^..<.

v<>v>v^
>v^>^>v
<>>^v<v
v^<>v^<

Non-Halting:

>..v
^..<

>v<
v<.
>v.
v<.
>.^

>.>.>.v
.><.<.<

This is code-golf, so the shortest program (in bytes) wins.


All Your Base Are Belong To Us (Restricted) Input must not be required, and output must read "All your base are belong to us".
Restrictions

No external resources.
Plus a minimum of two of the following:

You cannot use "a", "b", "t", "u", or "y" in any case in your code (bonus -10 to your golf score if you can do this)

You cannot use "l", "o", "s", "e", or "r" in any case in your code (bonus -20 to your golf score if you can do this)

You cannot use "n", "g", "0", "1", or "2" in any case in your code (bonus -30 to your golf score if you can do this)

So for example, if you manage to get the code done with 40 characters and use rules 1 and 2, your golf score is 40 - 10 - 20 = 10 chars.
Smallest code golf score wins... Good luck!

GolfScript, -22 (38 characters, -60 bonus)
"„¯¯c¼²¸µc¥¤¶¨c¤µ¨c¥¨¯²±ªc·²c¸¶"{67-}%


remove duplicates from array You have given an array from which we need to remove duplicates.

Rules:

First or immediate duplicates gets removed first.
Array contains natural numbers a[i]>0 for i>=0
no. of elements in the array is greater than 1 i.e. n>1

e.g.

{1,2,3,4,5,5,4,6,6,7,8}=> {1,2,3,7,8}
{1,2,3,3,4,5,6,7,7,8} => {1,2,4,5,6,8}
{1,1,3,3,4,4,6,6}=>{}
{4,2,6,8,3,1,1,3,8,6,2,4}=>{}
{6,6,6,1}=>{6,1}

Only adjacent duplicate elements like [1, 2, 2, 1] are removed, but not [1, 2, 1, 2]. This process is repeated until no further modifications are made.

For winning criteria is the one which gives the fastest result.

Python 2, 201 bytes

array = input()
index = 0
while index < len(array) - 1:
	if index >= 0 and array[index] == array[index + 1]:
		array = array[:index] + array[index + 2:]
		index -= 1
		continue
	index += 1
print(array)

Try it online!

Optimizations thanks to Mr. Xcoder


Code Golf : Parsing google results When you search something on google, within the results page, the user can see green links, for the first page of results.
In the shortest form possible, in bytes, using any language, display those links to stdout in the form of a list. Here is an example, for the first results of the stack exchange query :

Input :
you choose : the URL (www.google.com/search?q=stackexchange&ie=utf-8&oe=utf-8) or just stackexchange
Output :
french.stackexchange.com/, stackoverflow.com/, fr.wikipedia.org/wiki/Stack_Exchange_Network, en.wikipedia.org/wiki/Stack_Exchange,...

Rules :

You may use URL shorteners or other search tools/APIs as long as the results would be the same as searching https://www.google.com.

It's ok if your program has side effects like opening a web browser so the cryptic Google html/js pages can be read as they are rendered.

You may use browser plugins, userscripts...

If you can't use stdout, print it to the screen with, eg. a popup or javascript alert !

You don't need the ending / or the starting http(s)://

You should not show any other link

Shortest code wins !

Good luck !

EDIT :
This golf ends the 07/08/15.

Bash + grep + lynx, 38
Since we can open a web browser, then I will use lynx:
lynx -dump $1|grep -Po '(?<=d:)[^&]+'

(Thanks to @manatwork for grep usage instead of sed)
We pass in the whole URL in as a parameter:
$ ./gr.sh "www.google.com/search?q=stackexchange&ie=utf-8&oe=utf-8"
http://stackexchange.com/
https://en.wikipedia.org/wiki/Stack_Exchange
https://twitter.com/stackexchange
https://play.google.com/store/apps/details?id=com.stackexchange.marvin
https://github.com/StackExchange/StackExchange.Redis
https://github.com/StackExchange/StackExchange.Redis/blob/master/Docs/Basics.md
https://www.crunchbase.com/organization/stack-exchange
$

Which gives the same list as:


Edge Elimination Number From Erich Friedman's Math Magic, (problem #2 on that page) your challenge is to find the edge elimination number of a connected graph.
A single edge elimination is the removal of an edge from a graph, without disconnecting the graph, except for creating lone vertices.  For instance, in the graph below, the two leftmost edges and the rightmost edge may be legally eliminated, but the center edge may not, because that would lead to two  disconnected components larger than a single vertex.

An edge elimination sequence is the elimination of every edge in a graph in a specified order. Each elimination must be legal at the point in the sequence when it is performed. For instance, one legal edge elimination sequence on the above graph would be to remove the rightmost edge, then the center edge, then the top-left edge, then the bottom-left edge.
The edge elimination number of a graph is the number of different edge elimination sequences that a graph has. For instance, the above graph has an edge elimination number of 14. There are 4 sequences starting with the top left edge, 4 with the bottom left edge, and 6 with the right edge.
Input: The input graph is guaranteed to be connected. The graph will be given as a list of edges with labeled vertices. for instance, the above graph might be given as:
[(0,2), (1,2), (2,3), (3,4)]

Within that requirement, whatever format is most convenient for your language/code is fine. Don't cheese this. (e.g. no code in the vertex labels.)
Code: You may write a program taking input from the command line or from STDIN, or a function, or a verb, or your language's equivalent.
This is code golf, fewest bytes wins.
Tests:
One edge:
[(0,1)]
1

Path:
[(0,1), (1,2), (2,3), (3,4)]
8

Triangle with two additional edges off one vertex:
[(0,1), (1,2), (0,2), (0,3), (0,4)]
92

Randomly generated:
[(0, 2), (0, 4), (1, 2), (1, 4), (2, 5), (3, 4), (3, 5)]
1240

[(0, 2), (0, 3), (1, 3), (1, 4), (1, 5), (2, 3), (3, 4), (3, 5)]
16560

Again, this is code golf, fewest bytes wins. Please ask any clarifying questions, or tell me if I've done something wrong.

APL (77)

{0=⍴,⍵:1⋄C←0/⍨⍴V←∪∊G←⍵⋄0∊C⊣{C[V⍳⍵]:⍬⋄C[V⍳⍵]←1⋄∇¨⍵~⍨∊G/⍨⍵∊¨G}⊃V:0⋄+/∇¨⍵∘~∘⊂¨⍵}

This is a function that takes a list of edges as a graph, i.e.:

      {0=⍴,⍵:1⋄C←0/⍨⍴V←∪∊G←⍵⋄0∊C⊣{C[V⍳⍵]:⍬⋄C[V⍳⍵]←1⋄∇¨⍵~⍨∊G/⍨⍵∊¨G}⊃V:0⋄+/∇¨⍵∘~∘⊂¨⍵} (0 2)(0 3)(1 3)(1 4)(1 5)(2 3)(3 4)(3 5)
16560

(Incidentally, this takes about half a second on my computer.)

So the format is [[v1,v2], [v1,v2], ...]. To pass in a single-edge graph, you need to enclose it first, otherwise you get [0,1] instead of [[0,1]]:

      {0=⍴,⍵:1⋄C←0/⍨⍴V←∪∊G←⍵⋄0∊C⊣{C[V⍳⍵]:⍬⋄C[V⍳⍵]←1⋄∇¨⍵~⍨∊G/⍨⍵∊¨G}⊃V:0⋄+/∇¨⍵∘~∘⊂¨⍵} ⊂0 1
1

Explanation:

Base case 1 (empty graph):

0=⍴,⍵:1: if the graph is empty, return 1: the current path has emptied the graph while keeping it connected.

Base case 2 (unconnected graph):

C←0/⍨⍴V←∪∊G←⍵: store the list of edges in G, the vertices in V, and a 0 for each vertex in C.
{...}⊃V: See if the graph is connected. Starting with the first vertex:

C[V⍳⍵]:⍬: if the vertex has already been visited, do nothing
C[V⍳⍵]←1: mark the current vertex as visited
G/⍨⍵∊¨G: find each edge this vertex is connected to
⍵~⍨∊: find all vertices involved in those edges, except the current vertex
∇¨: visit all those vertices

0∊C...:0: afterwards, if one of the vertices is not visited, the graph is no longer connected. The current path is invalid, so return 0.

Recursive case:

⍵∘~∘⊂¨⍵: For each edge, create the graph formed by removing that edge, along with any orphaned vertices, from the current graph.
∇¨: For each of those graphs, find its edge elimination number.
+/: Sum those.


How compute WPA key? WPA2, the actual encryption standard that secures all modern wifi networks, has been cracked... This challenge has nothing to do with the way that the WPA2 was cracked, however is is about computing the 64-digit hexadecimal key that corresponds to a given WPA-PSK pass-phrase.

A wireless network with WPA-PSK encryption requires a pass-phrase to be entered to get access to the network. Most wireless drivers accept the pass-phrase as a string of at most 63 characters, and internally convert the pass-phrase to a 256-bit key. However, some systems also allow the key to be entered directly in the form of 64 hexadecimal digits. So the challenge is to calculate the 64-digit hexadecimal key that corresponds to a given pass-phrase.

The hexadecimal key is computed from the pass-phrase and the network SSID (an SSID is a unique ID that consists of 32 characters).

Details of the calculation

For WPA-PSK encryption, the binary key is derived from the pass-phrase according to the following formula: Key = PBKDF2(pass-phrase, SSID, 4096, 256)

The function PBKDF2 is a standardized method to derive a key from a pass-phrase.
It is specified in RFC2898 with a clear explanation on how to compute it.
The function needs an underlying pseudo-random function.
In the case of WPA, the underlying function is HMAC-SHA1.

SHA1 is a function that computes a 160-bit hash from an arbitrary amount of input data.
It is clearly explained in RFC3174.
HMAC is a standardized method to turn a cryptographic hash function into a keyed message authentication function.
It is specified in RFC2104.

To summarize, the key derivation process involves iterating a HMAC-SHA1 function 4096 times, and then doing that again to produce more key bits.

Inputs

SSID a string of at most 32 characters (e.g. stackexchange)
pass-phrase a string of at most 63 characters (e.g. <ra(<@2tAc<$)

Output any reasonable output of the 64 hexadecimal digits

e.g.
24343f69e98d3c08236a6db407584227cf2d1222b050e48f0cf25dee6563cd55
it is the result of the previous inputs

This is code-golf, so please make your program as short as possible!

C# (.NET Core) lambda expression, 88 82 81 bytes

Takes input as byte arrays (curried, see comments), returns key as byte array.

p=>s=>new System.Security.Cryptography.Rfc2898DeriveBytes(p,s,4096).GetBytes(32);

Try it online!


Chunky vs. Smooth Strings Consider a string of length N, such as Peanut Butter with N = 13. Notice that there are N-1 pairs of neighboring characters in the string. For Peanut Butter, the first of the 12 pairs is Pe, the second is ea, the last is er.
When the pairs are mostly different characters, the string has a chunky quality, e.g. chUnky.
When these pairs are mostly the same character, the string has a smooth quality, e.g. sssmmsss.
Define the chunkiness of a string to be the ratio of the number of pairs with two different characters to the total number of pairs (N-1).
Define the smoothness of a string to be the ratio of the number of pairs with two identical characters to the total number of pairs (N-1).
For example, Peanut Butter only has one pair with identical characters (tt), so its smoothness is 1/12 or 0.0833 and its chunkiness is 11/12 or 0.9167.
Empty strings and strings with only one character are defined to be 100% smooth and 0% chunky.
Challenge
Write a program that takes in a string of arbitrary length and outputs either its chunkiness or smoothness ratio as a floating point value.

Take input via stdin or the command line, or you may write a function that takes a string.
You can assume the input string only contains printable ASCII characters (and hence is single-line).
Print the float to stdout to 4 or more decimal places, or you can choose to return it if you wrote a function. Decimal places that convey no information are not required, e.g. 0 is fine instead of 0.0000.
Choose chunkiness or smoothness as you prefer. Just be sure to say  which one your program outputs.

The shortest code in bytes wins.
Examples
Peanut Butter → Chunkiness: 0.91666666666, Smoothness: 0.08333333333
chUnky → Chunkiness: 1.0, Smoothness: 0.0
sssmmsss → Chunkiness: 0.28571428571, Smoothness: 0.71428571428
999 → Chunkiness: 0.0, Smoothness: 1.0
AA → Chunkiness: 0.0, Smoothness: 1.0
Aa → Chunkiness: 1.0, Smoothness: 0.0
! → Chunkiness: 0.0, Smoothness: 1.0
[empty string] → Chunkiness: 0.0, Smoothness: 1.0
Bonus question: Which do you prefer, chunky or smooth strings?

CJam, 19 bytes

q_1>_@.=:!1b\,d/4mO

100% chunky source code that calculates chunkiness.

Try this chunky goodness online.

How it works

q_                  e# Read from STDIN and push a copy.
  1>_               e# Discard the first character and push a copy.
     @              e# Rotate the original on top.
      .=            e# Vectorized comparison (1 if equal, 0 if not).
        :!          e# Mapped logical NOT (0 if equal, 1 if not).
          1b        e# Base 1 conversion (sum).
            \,      e# Swap with the shortened string and push its length.
              d/    e# Cast to double and divide.
                4mO e# Round to four decimal places.

Obviously, NaN rounded to 4 decimal places is 0.


Word Search on a Torus The Challenge
Given a list of words and a grid of letters, your job is to determine which of the given words can be found on the grid in all 8 directions (forward, backward, up, down, and the 4 diagonal directions), much like a word search. The grid is toroidal, so the grid wraps around on the edges. Letters can be reused with this wrap-around property.
Wrapping around for diagonals behaves as you might expect. On a 4x6 grid going diagonally down and right, you would expect movement to look like this:
9 . 5 . 1 .
. . . 6 . 2
3 . . . 7 .
. 4 . . . 8

For an example of a wrap-around reuse word:
S E A H O R

Would be able to make SEAHORSE
Example Test Cases
Given this grid and the word list [ANT, COW, PIG]:
A N T
W C O
P G I

The result would be [ANT, COW, PIG]

Given this grid and the word list [CAT, DOG, DUCK, GOOSE, PUMPKIN]:
N O O D M E
O I O C U U
P G K O T C
K A U P S K

The result would be [DOG, DUCK, PUMPKIN]

Given this grid and the word list [TACO, BEEF, PORK]:
T A C B
A P O R
K E E F
B F C P

The result would be an empty list

Given this grid and the word list [ACHE, ASK, BAD, BOOK, COOK, CROW, GAS, GOOD, LESS, MARK, MASK, MEAL, SAME, SEAHORSE, SELL, SHOW, SLACK, WOOD]:
G S L A C K
H A E S R O
C M S K O O
A K S D W B

The result would be [ASK, BOOK, COOK, CROW, GAS, GOOD, LESS, MASK, SEAHORSE, SHOW, SLACK]

Given this grid and a list of all English words that are at least 3 letters long:
A R T U P
N T U B O
E S R O H
Q E T I U
E A T D P

The result would be [AEQ, AES, ANE, ART, ARTS, ATRIP, BOID, BON, BREE, BUD, BUT, DUB, DUE, DUET, EAN, EAR, EAT, EER, EST, HES, HIT, HOP, HOR, HORS, HORSE, HUP, NAE, NOB, NOBUT, ONT, OOT, OPP, ORS, OUR, OUT, PAR, PART, PAT, PEA, PEAT, PEE, PEER, PIR, POH, PUT, QAT, QUI, QUIT, QUITE, RAP, REE, RIP, RIPA, RTI, RUT, SEA, SEAR, STD, STR, STRA, STRAE, SUU, TAA, TAE, TAP, TAPIR, TEE, TIU, TOO, TRA, TRAP, TRI, TRIP, TUB, TUP, TUR, UDI, UIT, URE, UTE]
Rules

No exploiting standard loopholes
This is code-golf, so shortest code wins
Input and output may be in any convenient format
You may assume that both the grid and the words list will use only capital letters
The output order of the words does not matter
You do not have to, but may, filter out duplicates

Jelly, 25 bytes

Lẋ@Zɗ⁺ZU$3Ð¡;ŒD$€Ẏw€⁸ẸðÐf

A dyadic link accepting a list of lists of characters (the words) on the left and a list of lists of characters (the rows of the grid) on the right which returns a list of list of characters (the found words).

Try it online!

How?

Filters the words by their existence in the grid tiled to be word-length times as wide and word-length times as high:

Lẋ@Zɗ⁺ZU$3Ð¡;ŒD$€Ẏw€⁸ẸðÐf - Link: words, grid
                       Ðf - filter (the words) keeping those for which
                      ð   - ...the dyadic link to the left ...is truthy:
     ⁺                    -   perform this twice:
    ɗ                     -     last three links as a dyad:
L                         -       length (of the current word)
 ẋ@                       -       repeat (the rows) by (that number)
   Z                      -       transpose (making the rows become the columns)
         3Ð¡              -   repeat three times and collect the results (inc input):
        $                 -     last two links as a monad:
      Z                   -       transpose
       U                  -       upend     (together these rotate by a quarter)
                €         -   for €ach:
               $          -     last two links as a monad:
             ŒD           -       get forward-diagonals
            ;             -       concatenate
                 Ẏ        -   tighten (to get all the runs across the grid)
                    ⁸     -   chain's left argument (the word)
                   €      -   for €ach run:
                  w       -     sublist-index (0 if not found)
                     Ẹ    -   any truthy? (i.e. was the word found?)


Code ladder, Robbers This is the robbers' thread. The cops' thread goes here.
Write a code that has the same number of bytes as the cop post and where the revealed characters are identical. The code must produce 1 in its initial state, and produce the numbers 2, 3 .. when single alterations are made.
The winner will be the robber that cracked the most posts.
Example post:
MyLang, 9 bytes, 8 numbers (including link to answer), Cop's username.
Original code:
abc1efghi

Code that produces 1 - 8:
1: abc1efghi
2: abc2efghi
3: abc2efghij
4: kbc2efghij
5: kbc23fghij
6: kbc23fghi
7: kbc63fghi
8: kbc63fhi

Explanations are encouraged. The exact format of the robber post is optional.

Retina, 2 bytes, 10 numbers, by Martin Ender.
Original code:

1

This replaces the empty input by the number 1.
Code that produces 1 - 10 (showing newlines as \n for convenience):
1 : \n1
2 : \n1\n
3 : \n11\n
4 : \n111\n
5 : \n1111\n
6 : \n11111\n
7 : \n111111\n
8 : \n1111111\n
9 : \n11111111\n
10: \n111111111\n

For 2 and onwards, we count the number of empty strings in the previous stage. For 2, there is an empty string before and after the 1. For 3 there is an empty string before the ones, in between the ones and after the ones. This works all the way up to 10.
Try it online


Count all binary relations A binary relation on a set \$X\$ is simply a subset \$S \subseteq X \times X\$; in other words, a relation is a collection of pairs \$(x,y)\$ such that both \$x\$ and \$y\$ are in \$X\$. The number of different relations grows quickly with the size of the set: if \$X\$ contains \$n\$ elements, there are \$2^{n^2}\$ binary relations on \$X\$.
This challenge will have you computing the number of binary relations subject to certain constraints, listed here:

A binary relation is called "reflexive" if \$(x,x) \in S\$ for all \$x \in X\$.

A binary relation is called "irreflexive" if \$(x,x) \not\in S\$ for all \$x \in X\$.

A binary relation is called "symmetric" if whenever \$(x,y) \in S\$, then \$(y,x) \in S\$.

A binary relation is called "asymmetric" if whenever \$(x,y) \in S\$, then \$(y,x) \not\in S\$.

A binary relation is called "transitive" if whenever \$(x,y) \in S\$ and \$(y,z) \in S\$ then \$(x,z) \in S\$.

A binary relation is called "antitransitive" if whenever \$(x,y) \in S\$ and \$(y,z) \in S\$ then \$(x,z) \not\in S\$.

Challenge
The goal of this code-golf challenge is to write a function that takes in a nonnegative integer \$n\$, and some subset of the six conditions above in any reasonable format*, and returns the number of binary relations on the set \$\{1,2,\dots,n\}\$ satisfying all of the conditions in the aforementioned subset.
Brute-force strategies are okay, but your code should be able to handle all \$n \leq 4\$ on TIO.
Test Data
n | conditions                         | number of binary relations
--+------------------------------------+-------------------------
0 | {reflexive, antitransitive}        | 1
3 | {reflexive, antitransitive}        | 0
3 | {}                                 | 512
3 | {antitransitive}                   | 39
4 | {antitransitive}                   | 921
4 | {reflexive, irreflexive}           | 0
4 | {symmetric, asymmetric}            | 1
4 | {transitive, antitransitive}       | 87
4 | {reflexive, symmetric, transitive} | 15
4 | {symmetric, transitive}            | 52
4 | {asymmetric, antitransitive}       | 317

Example
For \$n = 3\$, there are \$39\$ antitransitive relations, as shown by the illustration below. (Strictly speaking, the illustration shows unlabeled relations.)

There is \$1\$ empty relation.
There are \$6\$ relations consisting of just one pair.
There are \$3 + 3 + 6 + 3\$ relations consisting of two pairs.
There are \$6 + 6 + 2\$ relations consisting of three pairs.
There are \$3\$ relations consisting of four pairs.

* For example, you could take the conditions as a list like [False, False, True, False, False, True], with each position referring to the particular condition. As another example, you could take a set of strings like {"transitive", "asymmetric"}.

APL (Dyalog Extended), 99 93 bytes

r←0∊0 0⍉⊢
R←r~
s←⊢≢⍉
S←1∊⊢∧⍉
t←0∊⊢≥∨.∧⍨
T←1∊⊢∧∨.∧⍨
{×⍵:+/∧⌿~(⍺,'0'){(⍎⍺)⊣⍵}\⍵-⍛↑∘⊤¨,⍳⍵⍴2*⍵⋄1}

Try it online!
-5 bytes thanks to @ovs for spotting R←r~, and -1 by taking the boolean negation of the intermediate results.
Takes the condition as a string, using the abbreviation as follows:
r: reflexive
R: irreflexive
s: symmetric
S: asymmetric
t: transitive
T: antitransitive

For example, reflexive + symmetric + transitive is given as 'rst' and "no condition" is given as ''.
How it works (before golfing)
⍝ Each of rRsStT takes an adjacency matrix and determines if the condition is met

⍝ reflexive: the diagonal is all ones
r←∧/0 0⍉⊢
⍝ irreflexive: the diagonal is all zeros
R←∧/0 0⍉~
⍝ symmetric: transpose is equal to self
s←⊢≡⍉
⍝ antisymmetric: each position in self and transpose cannot be both ones
S←~1∊⊢∧⍉
⍝ transitive: self includes the transitive square of self
t←~0∊⊢≥∨.∧⍨
⍝ antitransitive: each position in self and transitive square cannot be both ones
T←~1∊⊢∧∨.∧⍨

⍝ main function
{×⍵:+/∧⌿(⍺,'≡'){(⍎⍺)⍵}\⍵-⍛↑∘⊤¨,⍳⍵⍴2*⍵⋄1}  ⍝ ⍵: n, ⍺: conditions
{×⍵: ... ⋄1}  ⍝ Take 0 as a special case, always returning 1
,⍳⍵⍴2*⍵       ⍝ Generate all length-n vectors of 0..2^n-1
⍵-⍛↑∘⊤¨       ⍝ Convert them to n×n binary matrices
(⍺,'≡')       ⍝ Add a default function that always returns 1 to the list of conditions
{...}\        ⍝ Take outer product of conditions and matrices...
 (⍎⍺)⍵        ⍝ Eval the condition function and apply it to the matrix
+/∧⌿          ⍝ Count the matrices which satisfy all the conditions


Tips for golfing in Pip Pip is an imperative golfing language with infix operators. It also borrows some features from functional and array programming.
What general tips do you have for golfing in Pip? I'm looking for approaches and tricks that are commonly useful for code golf and are specific to Pip (e.g. "remove comments" is not an answer).
Please post one tip per answer.

Use preinitialized variables
Pip has many global variables that are pre-initialized so you can avoid manually writing a number/string/something else out yourself.
Here are some of them (complete list):

_ Identity function (== {a})

h 100

i 0

k ", "

l Empty list

m 1000 (mnemonic: Roman numeral M)

n Newline character

o 1

s Space character

t 10

v -1

w Matches whitespace \s+

x Empty string

z Lowercase alphabet a to z

B Block that returns its second argument ({b})

G Block that returns its argument list ({g})

AZ Uppercase alphabet A to Z

CZ Lowercase consonants b to z

PA All Printable ASCII characters, 32 through 126

PI \$\pi\$ (3.141592653589793)

VW Lowercase vowels a to u

VY Lowercase vowels a to y

XA Matches one Latin letter [A-Za-z] (there are more X* commands)

Link to documentation


What will you bring for Thanksgiving? Thanksgiving in the United States is coming up on November 24th. Many people will have a large dinner with their families, traditionally including turkey and many side dishes. This typically means the family members must coordinate who's going to bring each of the various dishes. In this challenge, the goal is to write a polyglot that outputs a different dish in each language it's run in.

Menu

(Selected from Wikipedia. In case it's not obvious, each line is one item.)

turkey
stuffing
dressing
cranberry sauce
mashed potatoes
gravy
winter squash
sweet potatoes
corn
green beans
green bean casserole
mac and cheese
macaroni and cheese
salad
rolls
biscuits
corn bread
pumpkin pie
apple pie
mincemeat pie
sweet potato pie
pecan pie
apple cider
sweet tea

Rules

Each submission must run in at least 3 languages, each of which must output a different item from the menu. You may not use multiple versions of the same language (e.g. Python 2 and Python 3 cannot be used in the same answer).
Each entry must have the same bytes in each language's encoding. For example, ɱ is byte 0x1D in Jelly's encoding, which corresponds to ¢ in 05AB1E's encoding.
Different languages may use different output methods, but entries must be full programs in all languages, and follow one of our default allowed IO methods.
No programs may take input, but any of the programs may print to STDERR or throw runtime/compile time errors and warnings as long as the correct output is still printed to STDOUT or a file.
Case and whitespace do not matter. For example, an output of GreenbeAN      S would still count as green beans.
As the central dish of every1 American Thanksgiving meal is turkey, one language must output turkey (ignoring case and whitespace).

Scoring

The submission that produces unique valid outputs in the most languages wins. In case of a tie, the shortest of the tied entries in bytes wins.

1. Yes, turkey is not the only main dish, but we're going to pretend it is.

Pyke, Pyth, Python 2, Foo, Brain****, GolfScript, Actually, <><, Gol<><, Seriously, Befunge, Fission, Haystack, 13 languages, 546 bytes
When I saw the other 10 11 12 language answer, I had to add an extra one two 3. I'm also seriously considering dropping Pyth if only to save on bytes. (at the moment 162 of them)
#\ s[\g\r\a\v\y)w.q)\r\o\l\l\ssp00/;oooooooo'stuffing;oooooo~'`turkey'
print'corn'#))))))))))))))))))))))))]+[--------->++<]>+w.q++[->+++<]>++w.q+++++++++++w.q-----------w.q----------------;))!+f'!n'!i'!s'!s'!e'!r'!d'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))L
'bread'#)))\é'i'n'o'r'a+++++))))))))))))))))))))))))))))))))))))))))))))))))\♀1X'c'a'm++++'e's'e'e'h'c'd'n'a++++++++)+.&\�0\ó))))))))))))))))))
#\25*8*0+c25*6*9+c25*6*7+c25*6*5+c25*7*8+c25*8*0+c25*7*3+c25*6*9+c|000000
# ,,,,,,,,@0>00000000\#"biscuits"aetteews"

Pyke: Try it here! rolls
Relevent line of code:
#s[\g\r\a  \v\y)w.q)\r\o\l\l\ssp00/;oooooooo'stuffing;oooooo~'`turkey'

#s[\g\r\a  \v\y)w.q) - effectively a comment because # doesn't do anything with an empty stack
\r\o\l\l\ss - sum("r", "o", "l", "l", "s")
p - print(^)
00/ - raise a ZeroDivisionError to stop running code

Pyth: Try it here! gravy
Relevent line of code:
#s[\g\r\a  \v\y)w.q)\r\o\l\l\ssp00/;oooooooo'stuffing;oooooo~'`turkey'

#...) - while True:
s[\g\r\a  \v\y) - sum(["g", "r", "a", "v", "y"])
w - input()
.q - quit

All the )'s are for Pyth to make it compile without erroring on no input.

Python 2: corn
Line 1 is a whole comment
Line 2 prints "corn" and then has a comment
Line 3 has a string literal and then a comment
Line 4 onwards are comments

Foo: Try It Online! biscuits
Foo prints out anything enclosed in double quotes ("). In this case I was careful to only include languages that could cope with other forms of string input (Special case for Befunge). If there was any text after the final ", that would be printed too.

Brain****: Try It Online! salad
I copied the output of constant string generator. I had to escape all . characters with .q so it would play with Pyth and w. so it would play with Pyke. I added some extra - characters so the cells would get to the right points before printing at another . character in the 3rd line

GolfScript: Try It Online! cornbread
In GolfScript, # is a comment until end of line.
What GolfScript interpreter sees:
#comment
print'corn'#comment
'bread'#comment

In GolfScript, for whatever reason, print takes a string and prints it without a newline. Just having bread is enough to print it as well.

Actually: Try It Online! macandcheese
Relevant line:
'bread'#)))\é'i'n'o'r'a+++++))))))))))))))))))))))))))))))))))))))))))))))))\♀1X'c'a'm++++'e's'e'e'h'c'd'n'a++++++++)+.&\�0\ó))))))))))))))))))

é - clears the stack of whatever junk was on it before.
'i'n'o'r'a+++++ - create string "aroni"
) - rotate entire stack (effectively comments as stack is only 1 long)
♀1X - pop stack (now empty)
'c'a'm++++ - constructs the string "mac"
'e's'e'e'h'c'd'n'a++++++++ - constructs the string "andcheese"
) - rotate stack (reverse)
+ - "mac" + "andcheese"
� - quit

<><: Copy+Paste only turkey

Gol<><: Try It Online! stuffing
As <>< except ` skips the first ' and only outputs enough characters to print stuffing

Seriously: Try It Online! macaroniandcheese
Relevant line:
'bread'#)))\é'i'n'o'r'a+++++))))))))))))))))))))))))))))))))))))))))))))))))\♀1X'c'a'm++++'e's'e'e'h'c'd'n'a++++++++)+.&\�0\ó))))))))))))))))))
é - clears the stack of whatever junk was on it before.
'i'n'o'r'a+++++ - create string "aroni"
) - rotate entire stack (effectively comments as stack is only 1 long)
♀1X - no-op
'c'a'm++++ - constructs the string "mac" + "aroni"
'e's'e'e'h'c'd'n'a++++++++ - constructs the string "andcheese"
) - rotate stack (reverse)
+ - "macaroni" + "andcheese"
. - print stack
0\ó - exit

Befunge: Try It Online! sweettea
Code that is looked at
#s[\g\r\a  \v - |
            ) - | - Directing the stack pointer to the correct place
            é - |
# ,,,,,,,,@0>00000000\#"biscuits"aetteews"

            >                              - change direction of travel
             00000000\#"biscuits           - a load of no-ops `#` skips the opening `"`
                                "aetteews" - add the chars to the stack in reverse order
  ,,,,,,,,@                                - output 8 chars from the stack and exit.

Fission: Try It Online! dressing
Code looked at:
;))!+f'!n'!i'!s'!s'!e'!r'!d'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))L

Of which are used:
;!+f'!n'!i'!s'!s'!e'!r'!d'L
                          L - start an atom going left
                      !d'   - create the character `d` and print it
                              ...
;                           - exit

Haystack (2015): PECANPIE (with EXTRA newlines!)
#\
 r
 b
 \25*8*0+c25*6*9+c25*6*7+c25*6*5+c25*7*8+c25*8*0+c25*7*3+c25*6*9+c

Of which do something functional:
  25*8*0+c25*6*9+c25*6*7+c25*6*5+c25*7*8+c25*8*0+c25*7*3+c25*6*9+c

I construct each upper case ascii codepoint for the letters in PECANPIE  in uppercase because they're all below 100. I then print them all out as characters.


Peel away the layers - Cops In this cops-and-robbers challenge, robbers must crack cop answers by finding out which languages the cops used.
This is the Cops thread. For the Robbers' challenge, see here
Cops, you are to write a program, which, when executed in a specific language, does one of the following:

Outputs one of the 5 phrases below
Outputs a piece of code, which when executed in a specific language (not necessarily the same language as the first program), does either point 1. or point 2. This may be either a function or a full program, and should output in a reasonable method

That is, the first program should output the code for the second, which outputs for the third, and so on, until the final program outputs one of the below phrases. If any of the codes uses non-ASCII characters, you should output the bytes that represent the program, not the characters.
None of the programs may be longer than \$65535\$ bytes long, to keep it somewhat sane.
You may repeat languages, but the languages you choose should all meet all of the following criteria:

It has an English Wikipedia article, an esolangs.org article or a Rosetta Code article at the time this challenge was posted, or is on Try It Online!. Having an interpreter linked in any of these pages makes that interpreter completely legal.

Given that the influx of languages to TIO has been paused, languages that have been requested to be added, but haven't yet been added, are also legal languages

It must satisfy our rules on what constitutes a programming language
It must have a free interpreter (as in beer), per site standards for cops-and-robbers posts

The phrases you may choose from are:

Game Over!
Greetings!
Code Golf.
It's Done.
The Last 1

Despite being a possible interpretation of the initial task, you may not write a program which simply outputs one of these phrases, to avoid the challenge being to similar to an existing challenge. Your submission must use a minimum of 2 languages
In your answer, you should reveal the following information:

The number of layers your submission has (note "layers", not "languages")
The initial code that will output all following layers (but not the language this code was written in)
The final outputted phrase

The robbers will be attempting to guess the languages you've used for each layer. Each robber must crack your entire submission for it to be a valid crack.
Note that a crack is valid even if the languages are different. So long as the robber's languages, in the order they state them, produce the specified final phrase, the crack is valid, even if the languages are not the same as yours.
If your answer has not been cracked within 14 days, you can claim it as safe. You should reveal the languages used and the codes in said languages. Note that your answer is not safe until you've revealed the languages and code and robbers can still crack your answer until then. The submission which is safe and uses the least amount of distinct languages wins!
Formatting
Cops, please format your original answer as so:
# <N> layers

    <code>

<Final output>

---

And, when cracked, please edit in the following format (underneath the ---):
Languages used (in order):

- [<language 1>](<link to interpreter>), outputted <output>
- [<language 2>](<link to interpreter>), outputted <output>
...
- [<language N>](<link to interpreter>), outputted <final phrase>

---

<anything else>

and you should edit your header to read
# <N> layers, cracked by [<robber>](<link to robber's post>)

If your answer is safe, edit this into the title, along with the complete list of intended languages. Your answer can still be cracked until you do.
Good luck!


Lossless English language text compression challenge Challenge:

Your challenge (should you choose to accept it) is to compress and decompress the 5MB "Complete Works of William Shakespeare" as found here:
http://www.gutenberg.org/cache/epub/100/pg100.txt

(MD5: a810f89e9f8e213aebd06b9f8c5157d8)

Rules:

You must take input via STDIN and output via STDOUT...
...and you must provide an identical decompressed result to the input.

(This is to say you must be able to cat inpt.txt | ./cmprss | ./dcmpress | md5 and get the same MD5 as above.)
(Anything via STDERR is to be discarded.)

You must use less than 2048 characters for your total source code.

(This is not code-golf.  You are not being scored based on length of source-code.  This is was just a rule to keep things finite.)
(Take the concatenated length of all source code if you have split it out.)

You must be able to (theoretically) process similar plain-text inputs too.

(e.g. hard coding a mechanism which is only capable of outputting the provided Shakespeare input is unacceptable.)
(The compressed size of other documents is irrelevant - provided the decompressed result is identical to the alternative input.)

You may use any choice of language(s).

(e.g. feel free to compress using awk and decompress using java)

You may write two separate programs or combine them with some form of "switch" as you please.

(There must be clear demonstrations of how to invoke both the compression and decompression modes)

You may not use any external commands (e.g. through exec()).

(If you are using a shell language - sorry.  You'll have to make do with built-ins.  You're welcome to post an "unacceptable" answer for the sake of sharing and enjoyment - but it won't be judged!)

You may not use any built-in or library provided functions who's stated purpose is to compress data (like gz, etc)

(Altering the encoding is not considered compression in this context.  Some discretion may be applied here.  Feel free to argue the acceptableness of your solution in the submission.)

Please try to have fun if choose to participate!

All good competitions have an objective definition of winning; ergo:

Provided all rules are adhered to, the smallest compressed output (in STDOUT bytes) wins.

(Report your output please via ./cmprss | wc -c)

In the event of a draw (identical output sizes), the most community up-voted wins.
In the event of a second draw (identical community up-votes), I'll pick a winner based on completely subjective examination of elegance and pure genius. ;-)

How to submit:

Please format your entry using this template:

<language>, <compressed_size>
-----------------------------

<description>  (Detail is encouraged!)

    <CODE...
    ...>

<run instructions>

I would encourage readers and submitters to converse through comments - I believe there's real opportunity for people to learn and become better programmers through codegolf.stack.

Winning:

I'm away on vacation soon: I may (or may not) be monitoring submissions over the next few weeks and will draw the challenge to a close on the 19th September.  I hope this offers a good opportunity for people to think and submit - and for a positive sharing of techniques and ideas.

If you've learned something new from participating (as a reader or submitter) please leave a comment of encouragement.

Perl 5, 3651284

Just a simple word-based dictionary scheme. Analyzes the word frequency of
the corpus, and uses that to determine whether to use one or two bytes of
overhead per word. Uses two special symbols for the bytes \0 and \1 since
they do not appear in the corpus. There are plenty of other symbols that
could be used. This was not done. Does not do any huffman encoding or any
of that jazz.

Compression script shakespeare.pl:

use strict;
use warnings;
use bytes;

my $text = join "", <>;
my @words = split/([^a-zA-Z0-9]+)/, $text;

my %charfreq;
for( my $i = 0; $i<length($text); ++$i ) {
    $charfreq{ substr($text, $i, 1) }++
}
for my $i ( 0..255 ) {
    my $c = chr($i);
    my $cnt = $charfreq{$c} // 0;
}

my %word_freq;
foreach my $word ( @words ) {
    $word_freq{ $word }++;
}

my $cnt = 0;
my ( @dict, %rdict );
foreach my $word ( sort { $word_freq{$b} <=> $word_freq{$a} || $b cmp $a } keys %word_freq ) {
    last if $word_freq{ $word } == 1;

    my $repl_length = $cnt < 127 ? 2 : 3;
    if( length( $word ) > $repl_length ) {
        push @dict, $word;
        $rdict{ $word } = $cnt;
        $cnt++;
    }
}

foreach my $index ( 0..$
    print "$dict[$index]\0";
}
print "\1";

foreach my $word ( @words ) {
    my $index = $rdict{ $word };
    if ( defined $index && $index <= 127 ) {
        print "\0" . chr( $index );
    } elsif ( defined $index ) {
        my $byte1 = $index & 127;
        my $byte2 = $index >> 7;
        print "\1" . chr( $byte2 ) . chr( $byte1 );
    } else {
        print $word;
    }
}

Decompression script deshakespeare.pl:

use strict;
use warnings;
use bytes;

local $/;
my $compressed = <>;
my $text = $compressed;
$text =~ s/^.+?\x{1}//ms;
my $dictionary = $compressed;
$dictionary =~ s/\x{1}.*$//ms;

my $cnt = 0;
my @dict;
foreach my $word ( split "\0", $dictionary ) {

    push @dict, $word;
}

my @words = split /(\x{0}.|\x{1}..)/ms, $text;
foreach my $word ( @words ) {
    if( $word =~ /^\x{0}(.)/ms ) {
        print $dict[ ord( $1 ) ];
    } elsif( $word =~ /^\x{1}(.)(.)/ms ) {
        my $byte1 = ord( $1 );
        my $byte2 = ord( $2 );
        my $index = ( $byte1 << 7 ) + $byte2;
        print $dict[ $index ];
    } else {
        print $word;
    }
}

Run using:

perl shakespeare.pl < pg100.txt >pg100.txt.compressed
perl deshakespeare.pl <pg100.txt.compressed >pg100.txt.restored
diff pg100.txt pg100.txt.restored


Compute the superset Your task here is simple:

Given a list of integer sets, find the set union.  In other words, find the shortest list of integer sets that contain all the elements in the original list of sets (but no other elements).  For example:

[1,5] and [3,9] becomes [1,9] as it contains all of the elements in both [1,5] and [3,9]
[1,3] and [5,9] stays as [1,3] and [5,9], because you don't want to include 4

Sets are notated using range notation: [1,4] means the integers 1,2,3,4.  Sets can also be unbounded: [3,] means all of the integers >= 3, and [,-1] means all of the integers <= -1.  It is guaranteed that the first element of the range will not be greater than the second.

You can choose to take sets in string notation, or you can use 2-element tuples, using a constant non-integer as the "infinite" value. You can use two distinct constants to represent the infinite upper bound and the infinite lower bound. For example, in Javascript, you could use [3,{}] to notate all integers >= 3, as long as you consistently used {} across all test cases.

Test cases:

[1,3]                     => [1,3]
[1,]                      => [1,]
[,9]                      => [,9]
[,]                       => [,]
[1,3],[4,9]               => [1,9]
[1,5],[8,9]               => [1,5],[8,9]
[1,5],[1,5]               => [1,5]
[1,5],[3,7]               => [1,7]
[-10,7],[1,5]             => [-10,7]
[1,1],[2,2],[3,3]         => [1,3]
[3,7],[1,5]               => [1,7]
[1,4],[8,]                => [1,4],[8,]
[1,4],[-1,]               => [-1,]
[1,4],[,5]                => [,5]
[1,4],[,-10]              => [1,4],[,-10]
[1,4],[,]                 => [,]
[1,4],[3,7],[8,9],[11,20] => [1,9],[11,20]

This is code-golf, so make your answer as short as possible!

R + intervals, 90 87 81 bytes

function(...)t(reduce(Intervals(rbind(...),type="Z")))+c(1,-1)
library(intervals)

Try it online!

Input is a list of intervals. -Inf and Inf are R built-ins for minus/plus infinity. Output is a matrix of columns of intervals.

Not usually a fan of using non-standard libraries but this one was fun. TIO doesn't have intervals installed. You can try it on your own installation or at https://rdrr.io/snippets/

The intervals package supports real and integer (type = "Z") intervals and the reduce function is a built-in for what the challenge wants, but the output seems to default to open intervals, so close_intervals +c(1,-1) is needed to get the desired result.

Old version had examples in list of lists which might be convenient so I've left the link here.


Will all the dominoes fall? The purpose of this challenge is to figure out whether all the dominoes will fall, given an input string representing a top view of the table.
Input format
The program can take the input as a single string with newlines or a list of strings. Spaces denote, well, empty spaces, and the rest represent dominoes.
The start domino and the direction the dominoes start to fall will be denoted by one of <(left),> (right), ^ (up), v(down). There will be exactly one start domino in the input.
The other dominoes will be represented by one of the following four characters:

| - falls right when pushed from the left, falls left when pushed from the right
- - falls up when pushed from the bottom, falls down when pushed from above
/ - falls right when pushed from the top and vice versa, falls left when pushed from the bottom and vice versa
\ - falls left when pushed from the top and vice versa, falls right when pushed from the bottom and vice versa.

Basically, | and - keep the momentum going in the same direction, and the slashes (/ and \) cause quarter-turns.
Dominoes may not fall twice. If a domino falls, you may consider that an empty space in the next iteration.
Pushing - from the left or right and pushing | from the top or bottom are undefined behavior.
Output
A truthy/consistent value if all the dominoes will fall, and a consistent falsy value otherwise
Here's an example to make it a bit more clear (o represents a fallen domino for the sake of this example):
Step 1 - Starts at the 4th domino in the first row
\||<
-
-  -
\||\

Step 2 - start domino has fallen
\||o
-
-  -
\||\

Step 3 - Go left because start was '<'
\|oo
-
-  -
\||\

Step 4 - keep going left
\ooo
-
-  -
\||\

Step 5 - keep going left
\ooo
-
-  -
\||\

Step 6 - keep going to left, will go down next
oooo
-
-  -
\||\

Step 7 - change direction, go down because of '\'
oooo
o
-  -
\||\

Step 8 - keep going down
oooo
o
o  -
\||\

Step 9 - go down, will go left next because of '\'
oooo
o
o  -
o||\

Oops! Can't go any further, so output should be a falsy value

Rules
Just to clarify, there's no gravity or anything. The direction depends on the position of the domino (/, \, |, or -)
This is code-golf, so shortest code in bytes wins.
More test cases:
Truthy
>
_________________________________________________________

\|||<
-
-
/|||
__________________________________________________________

     \|/
     /|/
       -
       -
    \||\
    ^

Falsy
\|/
- -
/|/|  <-This last '|' doesn't fall, because the '/' before it has already fallen once
  ^
__________________________________________________________

|< |  <- This last '|' doesn't fall, because the dominoes don't wrap around.
__________________________________________________________

>||\||   Because after the '\', it tries to go up

Undefined behavior:
>-       Can't push '-' from the left
```

Charcoal, 86 69 bytes
ＷＳ⊞υι≔⪫υ¶θ≔v>^<ηＰθ…θ⌈Ｅη⌕θιＷ№ηＫＫ«↶⊗⁺³⌕ηＫＫ≔ⅈι ≔§⪪\-//|\³⁻ⅈιη»≔⌈ＫＡθ⎚→‹θ!

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. - if all the dominoes fall, nothing if some remain. Explanation:
ＷＳ⊞υι≔⪫υ¶θ

Input the table as an array of strings and join them together.
≔v>^<η

Make a string of rotations for the starting domino characters. The string starts with the character for a clockwise rotation, then the one for no rotation, then an anticlockwise rotation, then a u-turn.
Ｐθ…θ⌈Ｅη⌕θι

Print the table and then up until the (last) occurrence of one the starting domino characters.
Ｗ№ηＫＫ«

While the current character is present in the table of rotations...
↶⊗⁺³⌕ηＫＫ

... pivot according to the position of the character in the table of rotations (annoyingly I have to spend an extra byte adding 3 instead of subtracting 1 because Charcoal can't pivot by negative amounts)...
≔ⅈι ≔§⪪\-//|\³⁻ⅈιη

... and, temporarily saving the current X-coordinate, erase the current character, moving in the current direction, then choose the list of valid characters (again listed in the order rotate clockwise, don't rotate, rotate anticlockwise) depending on whether the current direction is vertical or horizontal (detected via the change in X-coordinate, since Charcoal has no builtin to read the current direction).
»≔⌈ＫＡθ⎚→‹θ!

Check that only spaces are left.


Electronic Piggy Bank A piggy bank is a container used to collect coins in. For this challenge use the four US coins: quarter, dime, nickel, and penny.

Challenge

Your challenge is to create an electronic piggy bank. Write a program (or function) that when run (or called), outputs (or returns) the count of each coin you have, as well as the total amount the coins amount to.

Input

A string, array, etc...(your choice) of the coins into your piggy bank(case insensitive).

 Q - Quarter(Value of 25)
 D - Dime(Value of 10)
 N - Nickel(Value of 5)
 P - Penny(Value of 1)

Output

The count of coins from the input and the total amount, separated by the non-integer delimiter of your choice. (The order in which you output the coin totals does not matter, but the total coin value(sum) must be the last element)

Examples

 Input          ->       Output

 P              ->       1,0,0,0,1 or 0,0,0,1,1 or 0,0,1,0,1 or 1,1
 N              ->       0,1,0,0,5
 D              ->       0,0,1,0,10
 Q              ->       0,0,0,1,25
 QQQQ           ->       0,0,0,4,100
 QNDPQNDPQNDP   ->       3,3,3,3,123
 PPPPPPPPPP     ->       10,0,0,0,10
 PNNDNNQPDNPQND ->       3,6,3,2,113

Rules

Standard loopholes are not allowed.

This is code-golf, so the shortest code in bytes for each language wins!

Python 2, 73 bytes

-3 bytes thanks to @Rod

C=map(input().count,'QDNP')
print C+[sum(map(int.__mul__,C,[25,10,5,1]))]

Try it online!


Unique Brick Tilings Within A Rectangle I was browsing Stackoverflow and saw this question about tiling an MxN rectangle, and I thought it would be great for golfing. Here is the task.

Given the dimension M and N, write a program that outputs how many unique ways a MxN rectangle (N is the number of rows, not columns. Not that it really matters) can be tiled given these constraints.

All tiles are 2x1 or 3x1
All tiles stay within their row (ie they are all horizontal)
Between every two adjacent rows tiles should not be aligned, except on the two ends
M and N are guaranteed to be at least 1

For example, a valid tiling of a 8x3 matrix would be

  2    3     3
  |    |     |
  v    v     v
 _______________
|___|_____|_____|
|_____|_____|___|
|___|_____|_____|

But the following would be invalid, because the rows align

  2    3     3
  |    |     |
  v    v     v
 _______________
|___|_____|_____|
|_____|___|_____|
|_____|_____|___|

Test cases:

8x3: 4

3x1: 1

1x1: 0

9x4: 10

Code golf, so shortest answer wins.

Jelly, 20 bytes

2*ḃ€2‘ÄṪ⁼¥Ƈ⁸ṗfƝẸ$€ċ0

Try it online!


Calculate Chinese Zodiac sign Given that the Chinese New Year is coming, here is a challenge to calculate the Chinese Zodiac, element and Taijitu for a given date.

The input should be a date:

1/31/2014

The date used here is the US style mm/dd/yyyy, but may alternatively be ISO-8601 style: yyyy-mm-dd so the style of date input is not strict.

The output should be the animal sign in the Chinese Zodiac including the element that corresponds to the date, and its Taijitu counterpart:

Horse - Wood - Yang

A table showing the Zodiac - element - Taijitu relationship can be seen here: Chinese Zodiac - Years

The output format is not strict but should contain animal, element and Taijitu component, and should be delimited in some fashion.

Examples of valid output for the above date might include:

(horse, wood, yang)
["Horse", "Wood", "Yang"]

Your program should return valid output for a range of at least 100 years, including today's date. This means that it will need to account for at least two 60 year (Sexagenary) cycles.

Python 2: 360* 387 586 594 - Characters

Reduced further

m,n,p=map(int,raw_input().split("/"));p-=1924;d=int("5od2nauh6qe4obvj8rf5pd2math6re3ocvi8sf5pd2l9uh6rf3nbvi7sg5pd2k9th6rf4navj7sg5oc1m9ti7qe3navj8sg5pc1math6qd3nbvj8sf4oc1ma"[p],36);p-=31*m-31+n<(d<21)*31+d;print"Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey Rooster Dog Pig".split()[p%12],"Wood Fire Earth Metal Water".split()[p%10/2],["Yang","Yin"][p%2]

The above code works for the following interval:  5 Feb 1924 – 31 Dec 2043

Example: after pasting the above code in the python interpreter cursor

>>> m,n,p=map(int,raw_input().split("/"));p-=1924;d=int("5od2nauh6qe4obvj8rf5pd2math6re3ocvi8sf5pd2l9uh6rf3nbvi7sg5pd2k9th6rf4navj7sg5oc1m9ti7qe3navj8sg5pc1math6qd3nbvj8sf4oc1ma"[p],36);p-=31*m-31+n<(d<21)*31+d;print"Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey Rooster Dog Pig".split()[p%12],"Wood Fire Earth Metal Water".split()[p%10/2],["Yang","Yin"][p%2]

and then press Enter, input a date like this

6/13/2018

and then press Enter again, output will be

Dog Earth Yang

* reduced further 27 bytes with Brian's help see comments.


Reconstruct a missing RGB channel Look at these photographs of natural scenes, with one of the RGB channels taken out of them:

Source (with red): https://en.wikipedia.org/wiki/File:Altja_j%C3%B5gi_Lahemaal.jpg

Source (with green): https://commons.wikimedia.org/wiki/File:2007_mather-lake_hg.jpg

Source (with blue): https://commons.wikimedia.org/wiki/File:Fox_01.jpg

Even without one of the channels, you can probably make out what colours certain things are supposed to be, or at least have a good idea if a reconstruction of the missing channel is accurate.

For example, here is the first picture with a red channel added back onto it which is just random noise:

This image clearly isn't an accurate reconstruction of the red channel. This is because nature photos generally don't use the entire RGB spectrum, but only a subset of "natural-looking colours". Also, the shades of red will follow certain gradients that correlate with the others.

Your task is to build a program that will take a photograph that's had one channel removed and attempt to approximate the original image as closely as possible by reconstructing what it believes is the missing channel.

Your program will be scored on how closely the missing channel matches with the channel of the original image, by counting the percentage of pixels whose values of that channel are within ±15 (inclusive) of the actual value in the original image (where the values range from 0 to 255 as in a standard 8-bit colour channel).

The test cases that your program will be scored on can be found here (9.04 MB zip file, 6 images). Currently it only contains the three example images above and their originals, but I'll add a few more later to make the full suite once I've done them.

Each image is scaled down and cropped to 1024 x 768, so they will have the same weight in your score. The program that can predict the most pixels within the given tolerance wins.

Python 3 + scikit-image

Simply sets the color of the missing channel to the average of the other two.

import sys
from skimage import io, color

im = io.imread(sys.argv[1])
h, w, c = im.shape

removed_channel_options = {0, 1, 2}
for y in range(h):
    for x in range(w):
        if len(removed_channel_options) == 1: break
        removed_channel_options -= {i for i, c in enumerate(im[y][x]) if c > 0}
removed_channel = removed_channel_options.pop()

for y in range(h):
    for x in range(w):
        p = [float(c) / 255 for c in im[y][x][:3]]
        p = [sum(p)/2 if i == removed_channel else p[i]
             for i in range(3)]
        im[y][x] = [int(c*255) for c in p] + [255]*(c == 4)

io.imsave(sys.argv[2], im)

And the restored images:


convert tabs to spaces Write the shortest possible code which converts tabs to spaces in the input. Tab size should be supplied as a parameter or be hardcoded in the code in a single place.

Spaces on output should point to the right column, e.g. (\t represents a tab character):

a\tb
aa\tb
aaa\tb
aaaa\tb

should become (for tab size 4):

a   b
aa  b
aaa b
aaaa    b

Of course there can be more than one tab in a line.

Line separator and tab character should match the system defaults (e.g. ASCII 10 and 9 on Unix).

Perl 5, 36 bytes

1while s/	/$"x($^I-length($`)%$^I)/e

Try it online!

Tab length is controlled with -i command-line parameter.


Which th second now in this year In this challenge you have to find out which nth second it is now in this year, current date and time now. Or in other words, how many seconds have passed since New Year.
An example current Date is (it's not given, you'll have to find the current Date):
March 5, 2021 1:42:44 AM

For which the answer is 5449364 (or optionally 5449365 if you count January 1, 2021 0:00:00 as the first second).
So you should return or output which 'th second it is now in this year. Standard loopholes apply, shortest code wins. You may keep fractional seconds in output optionally.

Python 2, 55 bytes

from time import*
k=86400
print~-gmtime()[7]*k+time()%k

Try it online!
-4 bytes thanks to Wasif
-11 bytes thanks to dingledooper


Compute a complex power The Rundown

Given any input x and y, perform a complex operation, and print a corresponding result.

How your program should work

Given an input x and y in the form z = x+yi, find zi-z
If the absolute real value of zi-z is larger than the absolute imaginary part, print the real part; vice versa for the other way around. If both values are equal, print one of the values.

Example

x: 2
y: 0

Therefore:

z = 2
z^(i-z) ~= 0.192309 + 0.159740i

Since the real part has a larger absolute value than the imaginary part, the program returns

0.192309

More examples

z = 1+i >> 0.5
z = i >> 1
z = 0.5 >> 1.08787
z = -2+8i >> 2.22964E7
z = -10i >> 3.13112E7

Jelly, 8 11 bytes

Thanks Johnathan Allan for updating the answer with the rules change.

ı_*@µĊ,ḞAÞṪ

Try it online!

ı_*@        z^(i-z)
    µ       new monadic link
     Ċ,Ḟ    pair real and imaginary parts
        AÞṪ sort by absolute value and take last value


Smallest Javascript CSS Selector Engine Create a small acceptably efficient JS CSS selector engine.  Standard css 2.0 properties should be supported in Firefox 3.0+,Safari , Opera, IE7+, and extra brownie points for IE6 support.

Smallest entry wins.

Hacks are permitted!

Please post size of script, and function to call preferable $(selector,context) style.

Funny, I just made one of these. It is quite efficient because it compiles selectors. I don't know if it's IE6-compatible but it should be, I think. It supports CSS3 too - bonus points? :)

if(![].indexOf)Array.prototype.indexOf=function(a,i){i=i||0;while(i<this.length)if(this[i++]===a)return i-1;return-1};
String.prototype.startsWith=function(s){return this.length>=s.length&&this.substring(0,s.length)===s};
String.prototype.endsWith=function(s){return this.length>=s.length&&this.substring(this.length-s.length)===s};

var Sprint = {
    Error: function(m) {
        this.message = m;
        this.toString = function() {
            return this.message;
        };
    },
    getAllElementsIn: function(element) {
        var r = [];
        var f = function recurse(l, arr) {
            from(l).each(function(k, v) {
                if(v.nodeType === 1) {
                    arr.push(v);
                    recurse(v, arr);
                }
            });
        };
        f(element, r);
        return r;
    },
    getAllElements: function() {
        return Sprint.getAllElementsIn(document.documentElement);
    },
    getSiblings: function(element) {
        return element.parentNode ? from(element.parentNode).where(function(k, v) { return v.nodeType === 1; }).toArray() : [element];
    },
    getInfo: function(selector) {
        var r = {ATTR: {}, CLASS: [], PSEUDO: []};

        var quotes = '\'"', nestable = '(){}', inAttribute = false, escaped = false, currentQuotes = null, currentNested = [], nonchar = /^[^a-zA-Z0-9_\-]$/, lastSplitter = null, i = -1, c, s = '';
        while(++i < selector.length) {
            c = selector.charAt(i);
            if(escaped) {
                escaped = false;
            } else if(c === '\\') {
                escaped = true;
                continue;
            } else if(currentQuotes) {
                if(currentQuotes === c) {
                    currentQuotes = null;
                }
            } else if(quotes.indexOf(c) > -1) {
                currentQuotes = c;
            } else if(currentNested.length) {
                if(nestable.indexOf(currentNested[currentNested.length - 1]) + 1 === nestable.indexOf(c)) {
                    currentNested.pop();
                }
            } else if(nestable.indexOf(c) > -1) {
                currentNested.push(c);
            } else if(nonchar.test(c)) {
                if(lastSplitter) {
                    switch(lastSplitter) {
                        case '#':
                            r.ID = s;
                            break;
                        case '.':
                            r.CLASS.push(s);
                            break;
                        case '[':
                        case ',':
                            if(inAttribute) {
                                var j;
                                if((j = s.indexOf('=')) > -1) {
                                    r.ATTR[s.substring(0, j)] = s.substring(j + 1);
                                } else {
                                    r.ATTR[s] = true;
                                }
                            }
                            break;
                        case ':':
                            r.PSEUDO.push(s);
                            break;
                    }
                } else {
                    r.TAG = s;
                }

                if(c === ']') {
                    inAttribute = false;
                } else if(c === '[') {
                    inAttribute = true;
                }

                lastSplitter = c;

                s = '';
                continue;
            }
            s += c;
        }

        if(lastSplitter) {
            switch(lastSplitter) {
                case '#':
                    r.ID = s;
                    break;
                case '.':
                    r.CLASS.push(s);
                    break;
                case '[':
                case ',':
                    if(inAttribute) {
                        var j;
                        if((j = s.indexOf('=')) > -1) {
                            r.ATTR[s.substring(0, j)] = s.substring(j + 1);
                        } else {
                            r.ATTR[s] = true;
                        }
                    }
                    break;
                case ':':
                    r.PSEUDO.push(s);
                    break;
            }
        } else {
            r.TAG = s;
        }

        return r;
    },
    compileSingle: function(info) {
        var f = 'var t=l.nodeName?l.nodeName.toLowerCase():"",i=l.id?l.id.toLowerCase():"",c=l.className?" "+l.className.toLowerCase()+" ":"",s=Sprint.getSiblings(l),ss=from(s).where(function(k,v){return v.nodeName?v.nodeName.toLowerCase()===t:false;}).toArray(),si=s.indexOf(l),ssi=ss.indexOf(l);return ';
        if(info.TAG && info.TAG !== '*') {
            f += 't===\'' + info.TAG.toLowerCase().replace(/[\\']/g, function(x) { return '\\' + x; }) + '\'&&';
        }
        if(info.ID) {
            f += 'i===\'' + info.ID.toLowerCase().replace(/[\\']/g, function(x) { return '\\' + x; }) + '\'&&';
        }
        if(info.CLASS) {
            for(var i = 0; i < info.CLASS.length; i++) {
                f += 'c.indexOf(\' ' + info.CLASS[i].toLowerCase() + ' \')>-1&&';
            }
        }
        if(info.PSEUDO) {
            for(var i = 0; i < info.PSEUDO.length; i++) {
                var p = info.PSEUDO[i], j, v = '';
                if((j = p.indexOf('(')) > -1) {
                    v = p.substring(j + 1, p.length - 1);
                    p = p.substring(0, j);
                }
                switch(p) {
                    case 'first-child':
                        f += '!si';
                        break;
                    case 'first-of-type':
                        f += '!ssi';
                        break;
                    case 'nth-child':
                        // TODO: Implement all nth-*** selectors.
                        break;
                    case 'nth-of-type':

                        break;
                    case 'last-child':
                        f += 'si===s.length-1';
                        break;
                    case 'last-of-type':
                        f += 'ssi===ss.length-1';
                        break;
                    case 'nth-last-child':

                        break;
                    case 'nth-last-of-type':

                        break;
                    case 'only-child':
                        f += 's.length===1';
                        break;
                    case 'only-of-type':
                        f += 'ss.length===1';
                        break;
                    case 'disabled':
                        f += 'l.disabled';
                        break;
                    case 'enabled':
                        f += '!l.disabled';
                        break;
                    case 'checked':
                        f += 'l.checked';
                        break;
                    case 'empty':
                        f += '!l.childNodes.length'; // TODO: Maybe restrict to elements (t 1) only?
                        break;
                    case 'not':
                        f += '!Sprint.isMatch(\'' + v.replace(/\\'/g, function(x) { return '\\' + x; }) + '\')(0,l)';
                        break;
                    default:
                        throw new Sprint.Error("Unrecognized pseudo-class \"" + p + "\".");
                }
                f += '&&';
            }
        }
        if(info.ATTR) {
            from(info.ATTR).each(function(k, v) {
                var c = k.charAt(k.length - 1);
                f += 'l.getAttribute(\'' + ('$^*~|'.indexOf(c) > -1 ? k.substring(0, k.length - 1) : k).replace(/\\'/g, function(x) { return '\\' + x; }) + '\')';
                if(typeof v === 'string') {
                    v = v.replace(/\\'/g, function(x) { return '\\' + x; });
                    switch(c) {
                        case '$':
                            f += '.endsWith(\'' + v + '\')';
                            break;
                        case '^':
                            f += '.startsWith(\'' + v + '\')';
                            break;
                        case '*':
                            f += '.indexOf(\'' + v + '\')+1';
                            break;
                        case '~':
                            f += '.split(\' \').indexOf(\'' + v + '\')+1';
                            break;
                        case '|':
                            f += '.split(\'-\').indexOf(\'' + v + '\')+1';
                            break;
                        default:
                            f += '===\'' + v + '\'';
                    }
                }
                f += '&&';
            });
        }

        if(f.substring(f.length - 2) !== '&&') {
            // It matches anything.
            f = 'return true  ';
        }

        return new Function(['l'], f.substring(0, f.length - 2) + ';');
    },
    compileTree: function(selector) {
        var t = Sprint.tokenizeSelector(selector), i = -1, j, splitters = ', >~+';
        while(++i < t.length) {
            if(splitters.indexOf(t[i]) > -1) {
                j = i;
                while(--j >= 0 && t[j] === ' ') t[j] = null;
                j = i;
                while(++j < t.length && t[j] === ' ') t[j] = null;
            }
        }
        return from(t).where().select(function(k, v) {
            return k % 2 ? v : Sprint.compileSingle(Sprint.getInfo(v));
        }).toArray();
    },
    matchSingleTree: function(element, tree) {
        if(!tree.length) {
            return true;
        }

        if(!tree[tree.length - 1](element)) {
            return false;
        }

        for(var i = tree.length - 3; i >= 0; i -= 2) {
            switch(tree[i + 1] || ' ') {
                case ' ':
                    while(true) {
                        if(!(element = element.parentNode)) {
                            return false;
                        }
                        if(tree[i](element)) {
                            break;
                        }
                    }
                    break;
                case '>':
                    if(!(element = element.parentNode) || !tree[i](element)) {
                        return false;
                    }
                    break;
                case '+':
                    while(true) {
                        if(!(element = element.previousSibling)) {
                            return false;
                        }
                        if(element.nodeType === 1) {
                            if(!tree[i](element)) {
                                return false;
                            } else {
                                break;
                            }
                        }
                    }
                    break;
                case '~':
                    while(true) {
                        if(!(element = element.previousSibling)) {
                            return false;
                        }
                        if(tree[i](element)) {
                            break;
                        }
                    }
                    break;
            }
        }

        return true;
    },
    matchTree: function(element, tree) {
        var c = [];
        for(var i = 0; i < tree.length; i++) {
            if(tree[i] === ',') {
                if(Sprint.matchSingleTree(element, c)) {
                    return true;
                }
                c = [];
            } else {
                c.push(tree[i]);
            }
        }
        return Sprint.matchSingleTree(element, c);
    },
    tokenizeSelector: function(selector) {
        var quotes = '\'"', nestable = '(){}[]', escaped = false, currentQuotes = null, currentNested = [], tokens = [], splitters = ', >~+', i = -1, c, s = '';
        while(++i < selector.length) {
            c = selector.charAt(i);
            if(escaped) {
                escaped = false;
            } else if(c === '\\') {
                escaped = true;
                continue;
            } else if(currentQuotes) {
                if(currentQuotes === c) {
                    currentQuotes = null;
                }
            } else if(quotes.indexOf(c) > -1) {
                currentQuotes = c;
            } else if(currentNested.length) {
                if(nestable.indexOf(currentNested[currentNested.length - 1]) + 1 === nestable.indexOf(c)) {
                    currentNested.pop();
                }
            } else if(nestable.indexOf(c) > -1) {
                currentNested.push(c);
            } else if(splitters.indexOf(c) > -1) {
                tokens.push(s);
                tokens.push(c);
                s = '';
                continue;
            }
            s += c;
        }
        tokens.push(s);

        return tokens;
    },
    isMatch: function(selector) {
        var f = Sprint.compileTree(selector);
        return function(key, element) {
            return Sprint.matchTree(element, f);
        };
    },
    select: function(selector) {
        return from(Sprint.getAllElements()).where(Sprint.isMatch(selector)).toArray();
    },
    selectIn: function(selector, element) {
        return from(Sprint.getAllElementsIn(element)).where(Sprint.isMatch(selector)).toArray();
    }
};

function from(x) {
    if(!x) {
        throw new Sprint.Error("null or undefined passed to Sprint:from().");
    }

    var r = {
        keys: [],
        values: []
    };

    if(x.length) {
        for(var i = 0; i < x.length; i++) {
            r.keys.push(i);
            r.values.push(x[i]);
        }
    } else if(x.childNodes) {
        return from(x.childNodes);
    } else {
        for(var y in x) {
            if(x.hasOwnProperty(y)) {
                r.keys.push(y);
                r.values.push(x[y]);
            }
        }
    }

    r.length = r.keys.length;

    r.where = function(f) {
        if(f) {
            if(typeof f === 'string') return this.where(new Function(['k', 'v'], 'return ' + f + ';'));

            var r = {};
            for(var i = 0; i < this.length; i++) {
                if(f(this.keys[i], this.values[i])) {
                    r[this.keys[i]] = this.values[i];
                }
            }
            return from(r);
        } else {
            return this.where(function(k, v) { return v; });
        }
    };

    r.select = function(f) {
        var r = {};
        for(var i = 0; i < this.length; i++) {
            r[this.keys[i]] = f(this.keys[i], this.values[i]);
        }
        return from(r);
    };

    r.each = function(f) {
        for(var i = 0; i < this.length; i++) {
            f(this.keys[i], this.values[i]);
        }
    };

    r.first = function() {
        return this.values[0];
    };

    r.last = function() {
        return this.values[this.length - 1];
    };

    r.splitBy = function(f) {
        if(typeof f === 'function') {
            var r = [], c = {};
            for(var i = 0; i < this.length; i++) {
                if(f(this.keys[i], this.values[i])) {
                    r.push(c);
                    c = {};
                } else {
                    c[this.keys[i]] = this.values[i];
                }
            }
            r.push(c);
            return from(r);
        } else {
            return this.splitBy(function(x) { return x === f; });
        }
    };

    r.limit = function(f) {
        var r = {}, i = -1;

        if(typeof f === 'function') {
            while(++i < this.length && f(this.keys[i], this.values[i])) {
                r[this.keys[i]] = this.values[i];
            }
        } else {
            while(++i < Math.min(this.length, f)) {
                r[this.keys[i]] = this.values[i];
            }
        }

        return from(r);
    };

    r.after = function(f) {
        var r = {}, i = -1;

        if(typeof f === 'function') {
            while(++i < this.length && !f(this.keys[i], this.values[i])) {
            }
            while(++i < this.length) {
                r[this.keys[i]] = this.values[i];
            }
        } else {
            if(f < this.length) {
                i = f - 1;
                while(++i < this.length) {
                    r[this.keys[i]] = this.values[i];
                }
            }
        }

        return from(r);
    };

    r.toArray = function() {
        return this.values;
    };

    return r;
}

You use it like so:

Sprint.selectIn("mySelector", element);

Or

Sprint.select("mySelector")

. The code is 6.89KB minified and 2.26KB gzipped.


Generate a random derangement Challenge description

A "derangement" of a sequence is a permutation where no element appears in its original position. For example ECABD is a derangement of ABCDE, but CBEDA is not:

ABCDE
 | |   <- B and D are in their orignal positions
CBEDA

Given a sequence, generate a random derangement of it.

Notes

You may take either a string as an input or an array/list of elements (integers, chars, objects...)
Instead of returning a new object, you can modify an existing one by swapping its elements
Each derangement should have an equal probability of being generated
You may assume that there is more than one element in the sequence and none appear more than once

CJam, 14 bytes

q:X{mr_X.=:|}g

Try it online!

Keeps shuffling the input until it's a derangement.

Explanation

q:X   e# Read input and store it in X.
{     e# While the condition at the end of the loop is truthy...
  mr  e#   Shuffle the string.
  _X  e#   Duplicate it and push the input.
  .=  e#   Element-wise equality check.
  :|  e#   Reduce OR over the list, gives something truthy if any character
      e#   remained in its original position.
}g


Input a number and return day of week Not restricted to any one programming language.

What I'm saying is you pass 1 to it and it returns Monday, 7 corresponds with sunday and so on.

I've managed a 146 byte statement in Java to do the same.

return (n<1?"invalid":(n<2?"monday":(n<3?"tuesday":(n<4?"wednesday":(n<5?"thursday":(n<6?"friday":(n<7?"saturday":(n<8?"sunday":"invalid"))))))));

Your program should:

output full words (STDOUT)
not crash if the input is less than 1 or greater than 7

Bash: 47 bytes

Still no bash entry? I'm disappointed ...

case $1 in
    [1-7]) date -d "14-08-1$1" +%A
esac

It uses the days of the current week and simply substitutes the last digit (11-17 August 2014 -- 11 is Monday, 12 is Tuesday, etc.).


Rosencrantz and Guildenstern are Code In the absurdist play Rosencrantz and Guildenstern are Dead, the two main characters Rosencrantz and Guildenstern(or are they?) are always mixing up which of them is who—or sometimes which of their own body parts is which—because of a perceived lack of individual identity. Wouldn't it be absurd if they even shuffled around their names?

Your task it to write a function which takes in a string of an even length(and by design, a multiple of 4) that is greater than 7 characters, split it, and shuffle it.

The splitting shall be as follows:
the string will be of format "abscd", with s acting as a seperator character. The first section and the separator, abs will be the first half of the string, whereas the second half will be cd

The length of a will be (string length / 4) - 1

The length of b will be (string length / 4)

The length of s will be 1

The length of c will be (string length / 4) + 1

The length of d will be (string length / 4) - 1

This may be really confusing, so let me show you
with some examples

("a" + "bb" + "s" + "ccc" + "d").length //8
  1     2      1      3      1
|-------4--------|  |----4-----| <--- (4 is half of 8)

("rosen" + "crantz" + "&" + "guilden" + "stern").length  //24
    5         6        1        7          5

("foo" + "barr" + "?" + "barry" + "foo").length
   3       4       1      5         3

Finally:

You then shuffle the parts around, outputting adscb

ex. "rosencrantz&guildenstern" --> "rosenstern&guildencrantz"

"foobarr?barryfoo" --> "foofoo?barrybarr"

Rulez:

Standard Loopholes are prohibited
Acceptable answers: a function which takes input through one input string and returns one output string
If the input string doesn't match the requirements provided above,
your code MUST error out(doesn't matter what kind of Exception or
Error)
This is code-golf, so the shortest(valid)answer (in each language)
wins!
Bonus points for a one-liner :-) (Not really tho, just cool points)

K (oK), 35 34 33 bytes

{$[8>#x;.;<x!4!-&4#-1 0 2+-4!#x]}

Try it online!

Without input validation (for ngn's bounty), 25 24 23 bytes

{<x!4!-&4#-1 0 2+-4!#x}

Try it online!

Quickly learned a bit of K and, looking at the list of verbs, I thought an alternative approach (not using cut) could work here. And it worked perfectly.

How it works

{<x!4!-&4#-1 0 2+-4!#x}
                 -4!#x    Length divided by four (floor division)
        4#-1 0 2+         Generate lengths (x/4-1, x/4, x/4+2, x/4-1)
       &                  Generate that many 0, 1, 2, 3's
    4!-                   Negate and modulo 4; effectively swap 1 and 3
 <x!                      Sort the original string by above

{$[8>#x;.; <code> ]}  Input validation
 $[8>#x           ]   If the length is less than 8
        .             Dynamically generate an error
           <code>     Otherwise, run the main code


Longest Increasing Substring Given a list of positive integers, write code that finds the length of longest contiguous sub-list that is increasing (not strictly).  That is the longest sublist such that each element is greater than or equal to the last.

For example if the input was:

\$[1,1,2,1,1,4,5,3,2,1,1]\$

The longest increasing sub-list would be \$[1,1,4,5]\$, so you would output \$4\$.

Your answer will be scored by taking its source as a list of bytes and then finding the length of the longest increasing sub-list of that list.  A lower score is the goal. Ties are broken in favor of programs with fewer overall bytes.

Pyth, score 2 (8 bytes)

lefSIT.:

Try it here!

Code points [108, 101, 102, 83, 73, 84, 46, 58]. Another shorter solution, leSI#.: scores 3, but its code points are [108, 101, 83, 73, 35, 46, 58], which are very close to a score of 1, actually. Rearranging a bit may help Nevermind, the substrings built-in is .: which cannot be rearranged, so the lowest score must be 2 if the program makes use of it.

How?

lefSIT.:     Full program. Accepts either a list or a string from STDIN.
      .:     Substrings.
  f  T       Only keep those that are...
   SI        Sorting-Invariant.
le           Length of the last item.


Lazy battleship placement Imagine the following scenario: you are playing battleships with a friend but decide to cheat. Rather than moving a ship after he shoots where your ship used to be, you decide not to place any ships at all. You tell him all his shots are misses, until it is impossible to place ships in such a way.
You have to write a function, or a full program, that somehow takes 3 arguments: the field size, a list of amounts of ship sizes, and a list of shots.
Battlefield
One of the given parameters is the board size. The battlefield is a square of cells, and the given parameter is simply one side of the square.
For example, the following is a board of size 5.

Coordinates on the field are specified as a 2-component string: a letter followed by a number. You can rely on the letters being in some particular case.
Letter specifies the column, number specifies the row of the cell (1-indexed). For example in the above picture, the highlighted cell is denoted by "D2".
Since there are only 26 letters, the field can't be larger than 26x26.
Ships
The ships are straight lines of 1 or more blocks. The amount of ships is specified in a list, where the first element is the amount of 1-cell ships, second - of 2-cell ships and so on.
For instance, the list [4,1,2,0,1] would create the following shipset:

When placed on the battlefield, ships cannot intersect, or even touch each other. Not even with corners. They can however touch the edges of the field.
Below you can see an example of valid ship placement:

You can assume that for a given shipset, there always exists a placement on an empty board of given size.
Output
If such placements of ships exist, you have to output any of them.
The program has to output a newline-separated matrix of ascii characters of either of 3 types - one to denote blank cell, one - a ship piece, and one - a cell marked as "missed". No other characters should be output.
For example,
ZZ@Z
\@@Z
@\\Z
\Z\\

(In this example, I defined @ to be blank cell, \ to be a "missed" cell, and Z to be ship piece)
If no such placement exists, the program/function should return without outputting anything.
Input
If you decide to make a fullblown program, it's up to specify you how the lists are input, some might go via arguments, some via stdin.
This is code-golf, lowest amount of characters wins.
An example non-golfed optimized solution can be found here
Compile with -std=c99, first argument is the size of the board, the other arguments are ship sizes. A newline-separated list of shots is given on stdin. Example:
./a 4 1 1 1 <<< $'A2\nA4\nB3\nC3\nC4\D4'

SWI-Prolog, 536 4411 bytes

1 UNIX line ending, final new line not counted

The version with all optimizations removed (441 bytes):

:-[library(clpfd)].
m(G,L):-maplist(G,L).
l(L,A):-length(A,L).
y(A,E,(X,Y)):-nth1(X,A,R),nth1(Y,R,F),var(F),F=E.
a(A,S):-l(L,A),X#>0,X#=<L,Y#>0,Y#=<L,h(S,(X,Y),A).
h(0,_,_).
h(L,(X,Y),A):-(B=A;transpose(A,T),B=T),y(B,s,(X,Y)),M#=L-1,Z#=Y+1,h(M,(X,Z),B).
e([],_,[]).
e([H|R],I,O):-J#=I+1,e(R,J,P),l(H,Q),Q ins I,append(P,Q,O).
r(R):-m(c,R),nl.
c(E):-var(E)->put(@);put(E).
g(L,H,S):-l(L,A),m(l(L),A),m(y(A,\),S),e(H,1,G),!,m(a(A),G),!,m(r,A).

Since the code is changed to minimize the number of bytes, it will no longer accept a list of shots that have duplicates.

The version with basic optimization, fully golfed (536 → 506 bytes)

:-[library(clpfd)].
m(G,L):-maplist(G,L).
l(L,A):-length(A,L).
x(A,I,E):-X=..[a|A],arg(I,X,E).
y(A,E,(X,Y)):-x(A,X,R),x(R,Y,E).
a(A,S):-l(L,A),X#>0,X#=<L,Y#>0,Y#=<L,(B=A;transpose(A,T),B=T),h(S,(X,Y),B).
h(0,_,_).
h(L,(X,Y),A):-y(A,E,(X,Y)),var(E),E=s,M#=L-1,Z#=Y+1,h(M,(X,Z),A).
e([],_,[]).
e([H|R],I,O):-J#=I+1,e(R,J,P),l(H,Q),Q ins I,append(P,Q,O).
r(R):-m(c,R),nl.
c(E):-var(E)->put(@);put(E).
g(L,H,S):-l(L,A),m(l(L),A),sort(S,T),m(y(A,\),T),e(H,1,G),!,l(E,T),sumlist(G,D),L*L-E>=D,m(a(A),G),!,m(r,A).

I implement some basic checks (count number of ship blocks necessary) to make the code exits faster for clearly impossible cases. The code is also immune to duplicate in the list of shots so far.

Below is the (somewhat) readable version, with detailed comments:

:-[library(clpfd)].

% Shorthand for maplist, which works like map in high order function
m(G,L):-maplist(G,L).

% Creating a square matrix A which is L x L
board(L,A):-l(L,A),m(l(L),A).

% Shorthand for length, with order of parameters reversed
l(L,A):-length(A,L).

% Unification A[I] = E
x(A,I,E):-X=..[a|A],arg(I,X,E).

% Unification A[X][Y]=E
idx2(A,E,(X,Y)):-x(A,X,R),x(R,Y,E).

% Mark positions that have been shot
markshot(A,S):-m(idx2(A,\),S).

% Place all ships on the board
placeships(H,A):-m(placeship(A),H).

% Place a length S ship horizontal/vertical forward on the board
placeship(A,S):-
    l(L,A), % Get length
    X#>0,X#=<L,Y#>0,Y#=<L, % Constraint X and Y coordinates
    transpose(A,T), % Transpose to work on columns
    (placeship_h(S,(X,Y),A) ; placeship_h(S,(Y,X),T)).

% Place ship horizontal, forward at (X,Y)
placeship_h(0,_,_).
placeship_h(L,(X,Y),A):-
    idx2(A,E,(X,Y)),var(E),E=s, % Make sure position is unassigned, then mark
    L2#=L-1,Y2#=Y+1, % Do this for all blocks of the ship
    placeship_h(L2,(X,Y2),A).

% Expand the list of ships
% e.g. [2,3,1] --> [3,2,2,2,1,1]
shipexpand(S,O):-shipexpand(S,1,O).

shipexpand([],_,[]).
shipexpand([H|R],I,O):-
    I2#=I+1,shipexpand(R,I2,O2), % process the rest
    l(H,O1),O1 ins I, % duplicate current ship size H times
    append(O2,O1,O). % larger ship size goes in front

% Print the result
pboard(A):-m(prow,A).
prow(R):-m(pcell,R),print('\n').
pcell(E):-var(E)->print(@);print(E).

game(L,H,S):-
    board(L,A), % create board
    sort(S,SS), % remove duplicates
    markshot(A,SS), % mark positions that have been shot
    shipexpand(H,HH),!, % make a list of ships
    l(SC,SS),sumlist(HH,BC),L*L-SC>=BC, % check to speed-up, can be removed
    placeships(HH,A),!, % place ships
    pboard(A). % print result

Query format:

game(Board_Size, Ships_List, Shots_List).

Sample query (using the sample in the question):

?- game(4,[1,1,1],[(2,1),(3,2),(3,3),(4,1),(4,3),(4,4)]).
ssss
\ss@
@\\@
\@\\
true.

?- game(4,[2,2,0,1],[(2,1),(3,2),(3,3),(4,1),(4,3),(4,4)]).
ssss
\sss
s\\s
\s\\
true.


Determine if a relation is transitive Challenge description

Let's start with some definitions:

a relation is a set of ordered pairs of elements (in this challenge, we'll be using integers)

For instance, [(1, 2), (5, 1), (-9, 12), (0, 0), (3, 2)] is a relation.

a relation is called transitive if for any two pairs of elements (a, b) and (b, c) in this relation, a pair (a, c) is also present,
[(1, 2), (2, 4), (6, 5), (1, 4)] is transitive, because it contains (1, 2) and (2, 4), but (1, 4) as well,
[(7, 8), (9, 10), (15, -5)] is transitive, because there aren't any two pairs
(a, b), (c, d) present such that b = c.
[(5, 9), (9, 54), (0, 0)] is not transitive, because it contains (5, 9) and (9, 54), but not (5, 54)

Given a list of pairs of integers, determine if a relation is transitive or not.

Input / output

You will be given a list of pairs of integers in any reasonable format. Consider a relation

[(1, 6), (9, 1), (6, 5), (0, 0)]

The following formats are equivalent:

[(1, 6), (9, 1), (6, 5), (0, 0)] # list of pairs (2-tuples)
[1, 9, 6, 0], [6, 1, 5, 0] # two lists [x1, x2, ..., xn] [y1, y2, ..., yn]
[[1, 6], [9, 1], [6, 5], [0, 0] # two-dimentional int array
[4, 1, 6, 9, 1, 6, 5, 0, 0] # (n, x1, y1, ..., xn, yn)
[1+6i, 9+i, 6+5i, 0+0i] # list of complex numbers

... many others, whatever best suits golfing purposes

Output: a truthy value for a transitive relation, falsy otherwise. You may assume that the input will consist of at least one pair, and that the pairs are unique.

Haskell, 42 bytes

f x=and[elem(a,d)x|(a,b)<-x,(c,d)<-x,b==c]

Usage example: f [(1,2), (2,4), (6,5), (1,4)]-> True.

(Outer)loop over all pairs (a,b) and (inner)loop over the same pairs, now called (c,d) and every time when b==c check if (a,d)is also an existent pair. Combine the results with logical and.


That's one odd mountain! Inspired by Display a chain of little mountains with an odd number on the top of it! by @sygmei.

Why have a chain of mountains when you can have one massive one?

Make a program that takes an input number and prints a mountain with every odd number up to the input number.

(Where "south west" means directly below and to the left, and "south east" means directly below and to the right)

Every number will have a / south west of it, and a \ south east. It starts from 1 at the top, and the next number will go south west of a / or south east of a \. The next number will go in the line closest to the top and to the left most possible.

For a multidigit number, just the 1st digit needs to be in the right place with the other digits directly after, and only the first digit should have \ and / coming out from it.

The mountain up to 1 or 2 is just:

 1
/ \

A mountain up to 3 or 4 is just:

   1
  / \
 3
/ \

For 25 or 26:

         1
        / \
       3   5
      / \ / \
     7   9   11
    / \ / \ / \
   13  15  17  19
  / \ / \ / \ / \
 21  23  25
/ \ / \ / \

Last two lines where the input is 121:

 111 113 115 117 119 121
/ \ / \ / \ / \ / \ / \

And the last two lines where the input is 1019:

 993 995 997 999 1001100310051007100910111013101510171019
/ \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \

You may assume that the input will be greater than 0 and less than 10001 (exclusive).

Trailing spaces are OK, and extra leading spaces are alright as long as there is the same on all lines.

This is code-golf, so the shortest program in bytes wins.

An ungolfed answer to this can be found online here (In Python on repl.it) if you need more test cases.

05AB1E, 54 52 47 46 bytes

ÅÉ¹L£D€g__ÏRv"/ \ "yg×N·©úˆyvy4yg-ð×}J®>úˆ}¯R»

Try it online!

Explanation

                                                # implicit input n
ÅÉ                                              # push a list of uneven numbers up to input
  ¹L£                                           # divide into sublists of length 1,2,3...n
     D€g__Ï                                     # remove empty sublists
           R                                    # reverse list
            v                                   # for each sublist
             "/ \ "                             # push the string "/ \ "
                   yg×                          # repeat it len(sublist) times
                      N·©ú                      # prepend (sublist index)*2 spaces
                          ˆ                     # add to global list
                           yv                   # for each number in sublist
                             y4yg-ð×            # prepend spaces until length is 4
                                    }           # end inner loop
                                     J          # join to string
                                      ®>ú       # prepend (sublist index)*2+1 spaces
                                         ˆ      # add to global list
                                          }     # end outer loop
                                           ¯    # push global list
                                            R   # reverse it
                                             »  # join rows by space and columns by newline
                                                # implicitly print

I could have saved 5 bytes with ÅÉ¹L£D€g__ÏRv"/ \ "yg×N·©úˆy4jJðÛ®>úˆ}¯R» if only I'd pushed that bugfix for j I wrote several weeks ago :/