Challenge: Functioning Blackjack Game This is kept fairly original:

Write a program that creates a standard blackjack game:

input "h" means hit or draw another card
input "s" means stand, or take what you have already

Rules:
cards values are as follows:
2-9 = face value of card
10, J, Q, K = 10
aces = 11 unless player busts,  then it's only a 1
if 2 or more aces are drawn the first is 11, and each one after is a 1
the bank needs 18-21, and has to draw another card until they are in this range
this game runs forever

Procedure:

The player gets 2 cards at the beginning, shown by "Player:" in the console
(Example: Player gets 2 and 5 at the beginning. Console output: "Player: 2, 5").
The cards can be shown in the console by their values
(For example: 2, 10, 1 | No need for: 2, K, A), but you can also use
the card-names instead. Your choice
The input by the player is "h" for "hit" and "s" for "stand". Also allowed is 1 and 0
The bank gets one card at the beginning, shown by "Bank:"
At the end you get the output "Win", "Lose", "Draw",
or "Blackjack", depending on the game

This game is a code-golf challenge.

Python 3, 574 \$\cdots\$ 338 337 bytes

from random import*
e,L,B,P=exit,"Lose","Bank:","Player:"
d=[*range(2,12)]*4+[10]*12
c=d.pop
def h(l,m):
 l+=[c()]
 if sum(l)>21and 11in l:l[l.index(11)]=1
 print(m,*l);return sum(l)
shuffle(d)
b=[]
t=h(b,B)
p=[c()]
u=h(p,P)
u>20<e("Blackjack")
while'h'==input():u=h(p,P)
u>21<e(L)
while t<18:t=h(b,B)
22>t>u<e(L)
u==t<e("Draw")
e("Win")

Try it online!

Saved 34 bytes thanks to @ReinstateMonica!!!


A calculator as a list of numbers and operators Your task is to take a list of arguments that are either integers or operators, and parse them like so:

There is a current operator, which starts as +.
Each time an operator is found, the current operator will change to it.
The possible operators are: "+", "-", "*", "/", and "%", which correspond to their meanings in C and most languages.
There is a running solution kept, which starts at 0.
Each time an integer is found, the solution is modified by the number depending on the operator; e.g. if the operator is "/" then the solution is divided by the number.
If an operation would result in a mixed number (i.e. with a decimal) then it must be floored back to an integer (i.e. the decimal must be chopped off).
Output the final solution.

For example:

The arguments 5 8 25 * 9 6 2 - 104 / 4 7 + 6 % 14 would result in:

  5 8  25 * 9   6    2    - 104  / 4    7      + 6 % 14
0 5 13 38   342 2052 4104   4000   1000 142   148    8  -> 8

The inputs will be as command-line or function arguments, or an equivalent for your language.

Shortest code wins!

JavaScript (ES6) 53

A function taking an array as input.

Run the snippet in Firefox to test.

f=a=>a.map(t=>t<'0'?o=t:v=eval(v+o+t)|0,v=0,o='+')&&v

// TEST
out=x=>O.innerHTML=x;

input = [5,8,25,"*",9,6,2,"-",104,"/",4,7,"+",6,"%",14];
out(input.join(' ')+' -> '+f(input));

function go() {
  i=I.value.split(/ +/),out(I.value+' -> '+f(i))
}

Your test:<input id=I><button onclick='go()'>GO</button>


Resolve doubling and tripling actions in Dominion Inspiration

This question is inspired by the cards Throne Room and King's Court from the popular deck-building card game Dominion.

As part of one's turn, one plays a sequence of actions. These two particular actions cause the next-played action to repeat two or three times*. Other "generic" actions cause specific game effects, but we won't be interested in the particulars, simply labelling them with letters.

The interesting case is when a Throne Room or King's Court affects another Throne Room of King's Court, causing the doubling or tripling effect to itself be doubled or tripled. Long chains of Throne Rooms, King Courts, and multiplied actions can confuse even experienced Dominion players.

Your goal is to write code that correctly resolves these chains, using as few bytes as possible. I'll describe the program requirements before explaining how the chains resolve in the Dominion rules.

*Technically, you choose the action affected as part of resolving Throne Room or King's Court, but this view is cleaner for this challenge.

Program Requirements

Write a program or named function. It should take in the chain of actions played (STDIN or function input), and output or print the resulting chain of actions from the effects of doubling and tripling. Fewest bytes wins.

Input

A string representing the sequence of actions played. Generic actions are represented by capital letters A through Z. The special doubling action Throne Room is represented by the character 2, and the tripling action King's Court by 3,

The number of characters (actions) will be between 1 and 30, inclusive. You may have the input end in a newline if you wish.

Example input: WA23G3GA

Output

A string of capital lettersA to Z. This should be the sequence of generic actions that results from resolving the doubling and tripling effects, in the order than they happen.

You may have the output end in a newline if you wish. There should be no additional characters otherwise.

Example output: WAGGGGGGAAA.

How doubling and tripling works in Dominion

Here, I'll go through how chains of Throne Rooms (2's) and King's Courts (3's) work as per the Dominion rules.

After you play a 2, the next action to be resolved happens twice. So, if you first play 2, then A, you get A happening twice.

2A -> AA

Similarly,

A2BC -> ABBC
3DE -> DDDE
3N2BC3XY2 -> NNNBBCXXXY

Note in the last example that the final 2 had nothing to double, so it had no effect.

The interesting thing happens when doubling or tripling effects are themselves doubled or tripled. For example,

22AB -> AABB

First, you play 2. Then, you play another 2, which is doubled from the previous 2. As a result, the next two actions are doubled. First, the two copies of A resolve. Then, the copies of B resolve.

Note that A is not quadrupled: after the first copy of 2 acts on the first A, the next copy acts on the next unresolved action, which is B. Without the B, we'd have

22A -> AA

where the second copy of 2 is waiting for the next action to double, but no action comes.

Finally, let's look at a complex example.

223BCDE -> BBBCCCDDE

As before, the first 2 causes the second 2 to be doubled. So, the next two actions will be doubled. The first copy of 2 doubles the next action 3, which must be resolved completely before resolving the next copy of 2. The first copy of 3 triples B, and the second copy triples C. Now, the still-waiting second copy of 2 doubles the next still-unresolved action, which is D. After this, no doubling or tripling effects remain, and the final action E simply happens.

Test cases

These are given as (input,output).

(FY, FY)
(A2BC, ABBC)
(3DE, DDDE)
(3N2BC3XY2, NNNBBCXXXY)
(WA23G3GA, WAGGGGGGAAA)
(32, )
(33RST, RRRSSSTTT)
(2A32B2CDEFG, AABBCCDDEEFG)
(A2A323AB2CD2D2E3ABC, AAAAAABBBCCDDDDEEAAABBBC)
(P22LL3Q2Q22T, PLLLLQQQQQTT)
(322322ABCDEFGHIJKLMN, AABBCCDDEEEFFGGHHIJKLMN)

GolfScript (29 26 bytes)

](1/{\1+(3&@*.23-\1$-@+}/;

Online demo

Dissection

This slightly abuses the loose typing of GolfScript. The stack of how many times to repeat subsequent actions starts out as an array and later turns into a string - but 1+ appends a 1 and (3& pops the first value and correctly puts it in the range 0 to 3 regardless of the type change.

](         # Push an empty array under the input string to serve as rep stack
1/{        # Loop over the input string as a series of 1-char strings
           #   Stack is ... reps ch
           #   where the ... covers zero or more strings which will be output
  \        #   Bring the rep stack to the top
  1+(      #   Push a `1` on the bottom of it to avoid underflow and then pop
  3&       #   Coerce to correct range, because if rep stack is a string then
           #   we just got an ASCII value
  @*       #   Apply repetition to the 1-char string: it's now an n-char string
  .23-     #   Duplicate it and remove chars '2' and '3': this becomes output
  \1$-     #   Get the original copy and remove the output string's chars
           #   So the stack is now ... reps output non-output
           #   where non-output is either an empty string or a string of '2's
           #   or '3's
  @+       #   Push non-output onto the repetition stack
}/         # Loop
;          # Pop whatever's left of the repetition stack


Print an alphabet wave You are to print this exact text:

ABABABABABABABABABABABABAB
BCBCBCBCBCBCBCBCBCBCBCBCBC
CDCDCDCDCDCDCDCDCDCDCDCDCD
DEDEDEDEDEDEDEDEDEDEDEDEDE
EFEFEFEFEFEFEFEFEFEFEFEFEF
FGFGFGFGFGFGFGFGFGFGFGFGFG
GHGHGHGHGHGHGHGHGHGHGHGHGH
HIHIHIHIHIHIHIHIHIHIHIHIHI
IJIJIJIJIJIJIJIJIJIJIJIJIJ
JKJKJKJKJKJKJKJKJKJKJKJKJK
KLKLKLKLKLKLKLKLKLKLKLKLKL
LMLMLMLMLMLMLMLMLMLMLMLMLM
MNMNMNMNMNMNMNMNMNMNMNMNMN
NONONONONONONONONONONONONO
OPOPOPOPOPOPOPOPOPOPOPOPOP
PQPQPQPQPQPQPQPQPQPQPQPQPQ
QRQRQRQRQRQRQRQRQRQRQRQRQR
RSRSRSRSRSRSRSRSRSRSRSRSRS
STSTSTSTSTSTSTSTSTSTSTSTST
TUTUTUTUTUTUTUTUTUTUTUTUTU
UVUVUVUVUVUVUVUVUVUVUVUVUV
VWVWVWVWVWVWVWVWVWVWVWVWVW
WXWXWXWXWXWXWXWXWXWXWXWXWX
XYXYXYXYXYXYXYXYXYXYXYXYXY
YZYZYZYZYZYZYZYZYZYZYZYZYZ
ZAZAZAZAZAZAZAZAZAZAZAZAZA

Specs

You can print all lowercase instead of all uppercase. However, case must be consistent throughout the output.
You may print one extra trailing linefeed.

Scoring

Since this is an alphabet wave that fluctuates to a small extent, your code should also be small in terms of byte-count. In fact, the smallest code in terms of byte-count wins.


Evaluate a Stratego Battle In the game Stratego, the main game mechanic is when you attack an opponent's piece with yours. In this challenge, you job is to simulate one of these battles and say who survives.
Specs
You will get as input a pair of string representing Stratego pieces. The pieces are one of "S 1 2 3 4 5 6 7 8 9 10 B" (S is the Spy, and B are bombs). The first of the pair will be the attacker, and the second the attacked.
Here are the rules for determining the results of a battle:

The higher number beats the lower number: ["4", "6"] -> ["6"].
If both are the same, then both die: ["7", "7"] -> [].
Spies are at the bottom, underneath even 1: ["S", "2"] -> ["2"].
However, if a spy attacks the 10, then the spy wins: ["S", "10"] -> ["S"].
But the normal rules still apply if the 10 is the one attacking: ["10", "S"] -> ["10"].
If anything attacks a bomb, the bomb wins: ["5", "B"] -> ["B"].
However, a miner (a 3), can defuse a bomb: ["3", "B"] -> ["3"].
A bomb will never be the attacker.
A spotter (a 1), can attack using the normal mechanism, but they can also try to "guess" the rank of the other player, which can be denoted with any sane notation.
If they guess correctly, the other piece dies: ["1(5)", "5"] -> ["1"].
If they guess wrong, nothing happens: ["1(3)", "5"] -> ["1", "5"].
Spotters can spot bombs: ["1(B)", "B"] -> ["1"].

This is code-golf, so shortest code in bytes wins!
(You can use the examples up there as test-cases, because I'm too lazy to put them all together in one list).

Haskell, 131 bytes

This solution is in the form of an infix function # with type String -> String -> String

Input is accepted through the two string arguments. The format for spotter input is 1 x where x is the guess.Output is given as a string. In the case where both units survive, the returned string contains both separated by a space.

My original solution was unfortunately bugged and the fix cost me a few bytes.

('1':' ':x)#y|x==y="1"|1>0="1 "++y
"S"#"10"="S"
"3"#"B"="3"
_#"B"="B"
x#y|x==y=[]
t@"10"#_=t
_#t@"10"=t
"S"#x=x
x#"S"=x
x#y=max x y


Are the rooms connected? You are locked in a massive fortress, slowly starving to death. Your guards inform you that there is food in the fortress, and even tell you where it is and provide a map of the building.
However, you are not sure that you can actually reach the food, given that the every door is locked, and every room is its own labyrinth. Are you able to reach the food? If you're in the same room, you should try. If you're not in the same room, then you might as well stay put, preserving your strength in case help from the outside world comes.
Input
Two arrays: 3 coordinates of where you are, and 3 coordinates of where the food is. (Both are 0-based)
:Optional: an array of three numbers, indicating the size of the following fortress in each dimension.
A three dimensional array of the fortress, where each point in the array is either 1/true (if that point is a wall) or 0/false (if the point is empty). The array is a rectangular prism, and there is no guarantee that the structure follows the laws of physics. (Thus, the bottom floor might be completely empty.)
The place where you are and the place where the food is both have a 0/false.
Output
Are the two points in the same room, unseparated by a wall? Note that you can not move through a diagonal.
Format
You may write a program or a function.
The input may be through STDIN, command line or function arguments, or reading from a file. If you choose a text-based input (like STDIN) you may use any delimiters to help your program parse the input.
The output may be through STDOUT or the function result. You can output/return "true"/"false", 0/1, or the like.
Examples
In these examples, I put a Y where you are, and a F where the food is. This is just to help you understand the examples; in the actual input they would be 0/false.
Input
[0 0 1]      // You are at x = 0, y = 0, z = 1
[1 2 2]      // The food is at x = 1, y = 2, z = 2
[[[0 0 0]    // z = 0, y = 0
  [0 0 0]    // z = 0, y = 1
  [1 1 1]]   // z = 0, y = 2
 [[Y 0 0]
  [0 0 0]    // z = 1
  [1 1 1]]
 [[0 0 0]
  [1 1 0]    // z = 2
  [0 F 0]]]

Output
True. (The places are connected. You can move from [0 0 1] > [2 0 1] > [2 0 2] > [2 2 2] > [1 2 2].)
Input
[3 0 1]
[1 1 0]
[4 2 2]         // If you want, you can include this in the input, to indicate the fortress's size
[[[0 1 0 0]     // z = 0, y = 0
  [0 F 1 0]]    // z = 0, y = 1
 [[0 0 1 Y]
  [0 1 0 0]]]

Output
False. (There are two rooms. Your room includes [2 0 0], [2 1 1], [3 0 0], [3 0 1], [3 0 1], and [3 1 1]. The food's room includes the other empty spaces. Note that a wall of 1's divides the fortress in half.
Winning criterion
Code golf. Shortest code for your function/program wins.


How much candy can you eat? Credit to Geobits in TNB for the idea

A post without sufficient detail recently posited an interesting game:

2 children sit in front of an array of candy. Each piece of candy is numbered 1 to x, with x being the total amount of candy present. There is exactly 1 occurrence of each number.

The goal of the game is for the children to eat candy and multiply the values of the candy they have eaten to arrive at a final score, with the higher score winning.

However the original post missed key information, such as how candy is selected, so the kids in our story decided that the older kid gets to go first, and can eat up to half the candy, however once he announces the end of his turn, he can't change his mind.

One of the kids in this game doesn't like candy, so he wants to eat as little as possible, and he once watched his dad write some code once, and figures he can use the skills gained from that to work out how much candy he needs to eat to ensure victory, whilst still eating as little as possible.

The Challenge

Given the total number of candy x, your program or function should output the smallest amount of candy he has to eat to ensure victory, n, even if his opponent eats all the remaining candy.

Naturally bigger numbers make bigger numbers, so whatever amount you'll give him, he'll eat the n largest numbers.

The Rules

x will always be a positive integer in the range 0 < x! <= l where l is the upper limit of your language's number handling capabilities
It is guaranteed that the kid will always eat the n largest numbers, for example for x = 5 and n = 2, he will eat 4 and 5

Test cases

x = 1
n = 1
(1 > 0)

x = 2
n = 1
(2 > 1)

x = 4
n = 2
(3 * 4 == 12 > 1 * 2 == 2)

x = 5
n = 2
(4 * 5 == 20 > 1 * 2 * 3 == 6)

x = 100
n = 42
(product([59..100]) > product([1..58]))

x = 500
n = 220
(product([281..500]) > product([1..280]))

Scoring

Unfortunately, our brave contestant has nothing to write his code with, so he has to arrange the pieces of candy into the characters of the code, as a result, your code needs to be as small as possible, smallest code in bytes wins!

Python 3, 76 bytes

F=lambda x:x<2or x*F(x-1)
f=lambda x,n=1:x<2or n*(F(x)>F(x-n)**2)or f(x,n+1)

Try it online!

Relies on the fact that for eating \$n\$ candies to still win and the total number of candies being \$x\$, \$\frac{x!}{(x-n)!}>(x-n)!\$ must be true, which means \$x!>((x-n)!)^2\$.

-1 from Skidsdev

-3 -6 from BMO

-3 from Sparr

+6 to fix x = 1


My [sub] strings are hiding! Introduction
A while ago a lost SO user posted a question here and its now been deleted but I think it would make a good challenge so here it goes...
Challenge
Write a full program or function that takes two strings and checks whether any permutation of the first string is a sub-string of the second string.
Input
Two strings, a string and a sub-string to test for (you may choose the order).
Output:
A truthy value if the string contains any permutation of the sub-string.
A falsey value if the string does not contain any permutations of the the sub-string.
The test is case sensitive.
Examples/Test cases
         sub-string    string
input    d!rl          Hello World!
output   truthy

input    Pog           Programming Puzzles & Code Golf
output   falsey

input    ghjuyt        asdfhytgju1234
output   truthy

Brachylog, 2 bytes
sp

Try it online!
Explanation
Input variable = "Hello World!", Output variable = "d!rl"

(?)s        Take a substring of the Input variable
    p(.)    It is a permutation of the Output variable


Decrypting a block of AES Today your goal is to decrypt a secret message using AES. Given a ciphertext and key you will decrypt and print the message.

Your program may be in any language. It will be run with input on stdin, and its output on stdout will be checked for correctness.
The first line of input on stdin will be the 16 byte key, encoded in hexadecimal. The second line of input on stdin will be the 16 byte ciphertext, encoded in hexadecimal.
The output of the program must be the 16 byte message after decrypting the ciphertext using AES-128 with the given key. You must output the result interpreted as ASCII octets. You may assume that any result is valid ASCII after decrypting.
You may not use any library/built-in features that implement AES. You may use such features to convert between hex/binary/ASCII encodings.

Shortest code in bytes wins.

Example input and output:

bd8ab53f10b3d38576a1b9a15cf03834
02c0ee126cae50ba938a8b16f0e04d23

   Attack tomorrow.

And another:

f4af804ad097ba832906db0deb7569e3
38794338dafcb09d6b32b04357f64d4d

   Congratulations.

Python, 661 chars

R=range
I=lambda x:[int(x[2*i:2*i+2],16)for i in R(16)]
k=I(raw_input())
c=I(raw_input())
P=[]
x=1
for i in R(512):P+=[x];x^=x*2^(x>>7)*0x11b
S=[255&(99^j^(j>>4)^(j>>5)^(j>>6)^(j>>7))for i in R(256)for j in[(P[255-P.index(i)]if i else 0)*257]]
for r in R(10):
 for i in R(4):k+=[k[-16]^S[k[-3-(i>2)*4]]]
 k[-4]^=[1,2,4,8,16,32,64,128,27,54][r]
 for i in R(12):k+=[k[-16]^k[-4]]
for r in R(11):
 c=[x^y for x,y in zip(k[160-16*r:],c)]
 if r>9:break
 for i in[0,4,8,12]*(r>0):c[i:i+4]=[x^y^z^w for j in R(4)for x,y,z,w in[[P[a+P.index(v)]if v else 0 for a,v in zip((2*[104,238,199,223])[3-j:],c[i:i+4])]]]
 c=(c*13)[::13];c=map(S.index,c)
print''.join(map(chr,c))

k is the key, c is the ciphertext.  I build P, the powers of 3 in the field, then S, the sbox.  Then k is extended with the key schedule.  Finally we do the AES decryption.  Mixcolumns is the hard phase, all the other phases are pretty straightforward.


Write a mutating, replicating program This is a variant on the self-replicating program, defined here as a program that outputs its source (or a quine). Below is an example of a self-replicating program in Python:

s = 's = %r\nprint(s%%s)'
print(s%s)

When run from a file, this script should output itself.

Instead of a self-replicating program, I want you to write a mutating, replicating program. This is a program that outputs something similar to its source, but with a mutation. The mutated source must also be able to replicate, but it should change the functionality of the program in some way. Here is an example:

s = 's = %r\ns = s.replace(s[-17],str(int(s[-17])+222))\nprint(s%%s)'
s = s.replace(s[-17],str(int(s[-17])+222))
print(s%s)

When this Python script is run, it outputs the following program:

s = 's = %r\ns = s.replace(s[-17],str(int(s[-17])+224224224))\nprint(s%%s)'
s = s.replace(s[-17],str(int(s[-17])+224224224))
print(s%s)

If you repeat a number of times, you will see that it continues to mutate but remain functional.

Incorporating a raw dynamic environment variable in your code, like a comment with a timestamp, is boring. Don't do that.

Edit: For that matter, let's follow the standard quine rule of no input.

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

Clarifications: I've been asked to clarify, but without much information I'm not sure what needs clarifying. Here's my best shot:

Each iteration should have source code that is different from the last.
The iteration must still run.
The iteration must still replicate according to the same rules.
Comments or strings can't be the only thing that changes. In dzaima's answer the operations on the string are duplicated, not just the contents of the string--so that is valid.
Each iteration must be runnable in the same language you started in.

Jelly, 4 bytes

⁾ṘȮṘ

Try it online!

(Equivalent to the 5-byte: “ṘȮ”Ṙ)

Exponentially spawns:

“ṘȮ”ṘȮ
“ṘȮ”ṘȮṘȮ
“ṘȮ”ṘȮ“ṘȮ”ṘȮṘȮ
“ṘȮ”ṘȮṘȮ“ṘȮ”ṘȮ“ṘȮ”ṘȮṘȮ
“ṘȮ”ṘȮ“ṘȮ”ṘȮṘȮ“ṘȮ”ṘȮṘȮ“ṘȮ”ṘȮ“ṘȮ”ṘȮṘȮ

Since Ṙ is a monadic atom which prints a Jelly representation of its input and then yields it's input, and Ȯ is a monadic atom which prints its input and yields it's input (neither printing any newlines), while “...” defines a list of characters. So each “ṘȮ”Ṙ prints “ṘȮ” and yields to the following Ȯ which prints ṘȮ and yields... a trailing Ȯ finally yields for the programs return value, which is implicitly printed, so the pattern will continue until resources no longer suffice.


Trim that distracting background off! Isn't it annoying when you're taking a picture, but the background detracts from the actual substance of the image? I'd say it is. I need to know how much I should crop so that I get rid of this problem! But - as usual - I am quite lazy, so I need someone to do this for me...

Task & Rules

Given a binary matrix representing the image, output the dimensions (width and height) of the smallest sub-matrix that contains all the \$1\$s in the original matrix. A sub-matrix is a block of adjacent entries from the original matrix. Equivalently, it is a new matrix formed by overlapping a subset of adjacent rows and a subset of adjacent columns of the original.

It is allowed to take the width and the height of the matrix as input as well.
The input is guaranteed to contain at least one \$1\$.
You can take input and provide output through any standard method, while taking note that these loopholes are forbidden by default. This is code-golf, so try  to complete the task in the least bytes you can manage in your language of choice.

Example

$$\left[\begin{matrix}
\color{red}0&\color{red}0&\color{red}0&\color{red}0&\color{red}0&\color{red}0\\
\color{red}0&\color{blue}1&\color{blue}0&\color{blue}1&\color{blue}0&\color{blue}0\\
\color{red}0&\color{blue}1&\color{blue}1&\color{blue}0&\color{blue}1&\color{blue}1\\
\color{red}0&\color{blue}0&\color{blue}1&\color{blue}0&\color{blue}1&\color{blue}0\\
\color{red}0&\color{red}0&\color{red}0&\color{red}0&\color{red}0&\color{red}0\end{matrix}\right] \longrightarrow \left[\begin{matrix}1&0&1&0&0\\1&1&0&1&1\\0&1&0&1&0\end{matrix}\right]\longrightarrow(5,3)$$

Test cases

Input | Output

[[0,1,0,0,0,1,0]]
--> (5,1) or (1,5)

[[0,0,0,0,0],[0,1,0,1,0],[0,0,1,0,0]]
--> (3,2) or (2,3)

[[1,1,1,1],[0,0,0,0],[0,0,0,0],[1,0,0,0]]
--> (4,4)

[[0,0,0,0,0,0],[0,1,0,1,0,1],[0,0,0,0,0,0]]
--> (5,1) or (1,5)

[[0,0,0,0,0],[0,1,0,1,0],[0,0,1,0,0],[0,1,0,1,0],[0,0,0,0,0]]
--> (3,3)

[[0,0,0,0,0,0],[0,1,0,1,0,0],[0,1,1,0,1,1],[0,0,1,0,1,0],[0,0,0,0,0,0]]
--> (5,3) or (3,5)

MATL, 5 bytes
JYaZy

Try it online! Or verify all test cases.
Explanation
JYa   % Implicit input. Unpad matrix. This removes outer zeros
Zy    % Size. Implicit display


How much Mana do I need? Dungeon Master was one of the first ever real-time role-playing games, originally released in 1987 on the Atari ST. Among other exciting things for the time, it offered a rather sophisticated spell system based on runes.

Your task today is to write a program or function that evaluates the number of Mana points required to cast a given spell in Dungeon Master.

The 'spell cast' system is the top right cyan box in the above picture.

Spells, runes and Mana

Dungeon Master spells are composed of 2 to 4 runes, picked among the following categories, in this exact order:

Power (mandatory)
Elemental Influence (mandatory)
Form (optional)
Class / Alignment (optional)

It means that valid spells are either:

Power + Elemental Influence
Power + Elemental Influence + Form
Power + Elemental Influence + Form + Class / Alignment

Each category contains 6 runes, and each rune has an associated base Mana cost:

=============================================================================
| Power               | Rune      |   Lo |   Um |   On |   Ee |  Pal |  Mon |
|                     +-----------+------+------+------+------+------+------+
|                     | Base cost |    1 |    2 |    3 |    4 |    5 |    6 |
=============================================================================
| Elemental Influence | Rune      |   Ya |   Vi |   Oh |  Ful |  Des |   Zo |
|                     +-----------+------+------+------+------+------+------+
|                     | Base cost |    2 |    3 |    4 |    5 |    6 |    7 |
=============================================================================
| Form                | Rune      |  Ven |   Ew | Kath |   Ir |  Bro |  Gor |
|                     +-----------+------+------+------+------+------+------+
|                     | Base cost |    4 |    5 |    6 |    7 |    7 |    9 |
=============================================================================
| Class / Alignment   | Rune      |   Ku |  Ros | Dain | Neta |   Ra |  Sar |
|                     +-----------+------+------+------+------+------+------+
|                     | Base cost |    2 |    2 |    3 |    4 |    6 |    7 |
=============================================================================

Evaluating the Mana cost

The Mana cost of the spell is the sum of the Mana cost of all runes:

The cost of the Power rune always equals its base cost (from 1 to 6).
For the other runes, the following formula applies:

where power is the base cost of the Power rune.

Examples

Spell: Lo Ful
Cost : 1 + floor((1 + 1) * 5 / 2) = 1 + 5 = 6

Spell: Um Ful
Cost : 2 + floor((2 + 1) * 5 / 2) = 2 + 7 = 9

Spell: Pal Vi Bro
Cost : 5 + floor((5 + 1) * 3 / 2) + floor((5 + 1) * 7 / 2) = 5 + 9 + 21 = 35

Clarifications and rules

Your input will consist of 2 to 4 strings designating the runes of the spell. You can take them in any reasonable format, such as 4 distinct parameters,  an array of strings (e.g. ['Lo', 'Ful']), or just one string with a single-character separator of your choice (e.g. 'Lo Ful'). Please specify the selected input format in your answer.
The runes are guaranteed to be valid.
The order of the categories must be respected. Unused categories may be either missing or replaced with some falsy value.
You can accept the runes in any of these formats: 1. A capital letter followed by lower case ('Ful') 2. All lower case ('ful') 3. All upper case ('FUL'). But you can't mix different formats.
Quite obviously, we do not care to know whether the spell actually has some effect in the game (for the curious, useful spells are listed here.)
This is code-golf, so the shortest code in bytes wins.
And remember: Lord Chaos is watching you!

Test cases

Spell          | Output
---------------+-------
Lo Ful         | 6
Um Ful         | 9
On Ya          | 7
Lo Zo Ven      | 12
Pal Vi Bro     | 35
Ee Ya Bro Ros  | 31
On Ful Bro Ku  | 31
Lo Zo Kath Ra  | 20
On Oh Ew Sar   | 35
Ee Oh Gor Dain | 43
Mon Zo Ir Neta | 68
Mon Des Ir Sar | 75

Python 2, 135 119 115 bytes

b=[int('27169735 2  4567 435262'[int(x,36)%141%83%50%23])for x in input()]
print b[0]+sum(a*-~b[0]/2for a in b[1:])

Try it online!

Input is list of strings from stdin


Is it true? Ask Jelly! Background

Inspired by Octave's (and, by extension, MATL's) very convenient interpretation of truthy/falsy matrices, Jelly got the Ȧ (Octave-style all) atom.

Ȧ takes an array as input and returns 1 if the array is non-empty and does not contain the number 0 (integer, float, or complex) anywhere in the tree structure; otherwise, it returns 0.

For example, the array [[]] is truthy because it is non-empty and contains no zeroes, but [[0]] is falsy because it contains a 0 at the innermost level.

Task

In a programming language of your choice, write a full program or a function that takes a possibly empty, possibly jagged array of integers as input and prints or returns a truthy or falsy value that indicates if Ȧ would return 1 or 0, respectively.

Your submission must abide to the following rules.

The truthy and falsy values must be consistent for all inputs, i.e, all arrays for which Ȧ returns 1 must map to the same truthy value, and all arrays for which Ȧ returns 0 must map to the same falsy value.
Since full programs can only take string representations of arrays as input, this is allowed. However, you must use the canocical representation of your language, as returned by repr or similar.

In particular you cannot assume that the first element of the array will be preceded by a space.
If (and only if) your language cannot represent jagged arrays natively, you may take a string representation of the input, using the canonical syntax of any pre-existing programming language.
If your language has several ways of representing jagged arrays (e.g., lists and tuples), you only have to support one of them.
If your language has a built-in that is itself a valid submission to this challenge, you may not use it in your answer. All other built-ins are allowed.
You are encouraged to post answers using both array and string manipulation, even if one is significantly shorter than the other.
All standard code-golf rules apply.

May the shortest code in bytes win!

Truthy test cases

[1]
[10]
[[]]
[[[[1]]]]
[[], [1], [1, 2]]
[[1], [1, [2]], [1, [2, [3]]]]
[[8], [8, [9]], [8, [9, [10]]]]

Falsy test cases

[]
[0]
[0, -1]
[-1, 0]
[[[[0]]]]
[[0], [1, 2], [3, 4, 5]]
[[8], [8, [9]], [8, [9, [1, 0]]]]
[-1, 0, 0, 0]

Jelly, 3 bytes

ṭFẠ

F flattens the input list.

ṭ tacks on the original input list as an element, which is falsy if and only if it is empty.

Ạ then checks if any element in the flattened list, or the original list itself, is falsy.

(Original answer)

FẠ^Ṇ

Thanks to Dennis for encouraging finding a solution matching his.

FẠ gives 0 if the input contains a falsy value at any depth, else 1. This is what Ȧ does, except for empty lists.

Ṇ gives 1 if the input is a falsy value, else 0. The only falsy list is the empty list.

XOR-ing the two gives the answer.

F;WẠ

This is much in the same spirit as Dennis's F;LẠ, but instead of using L to put a zero in the list when the list is empty, it uses W to put the empty list into itself (producing [[]]), making it contain a falsy element.


The Baum-Sweet Sequence The Baum-Sweet Sequence (A086747 with a Twist)

Take in a positive integer n and print the integers from 1 to n for which the Baum-Sweet sequence returns true. The Baum-Sweet sequence should return falsy if the binary representation of the number contains an odd number of consecutive zeros anywhere in the number, and truthy otherwise. For more information, click the link. Here's a couple of examples:

1 -> 1 -> Truthy
2 -> 10 -> Falsy
3 -> 11 -> Truthy
4 -> 100 -> Truthy (Even run of zeros)

Here's an example given n=32

Step 1: The Baum-Sweet sequence visualized for n=32

1               1 (1)
1 0             0 (2)
11              1 (3)
1 00            1 (4)
1 0 1           0 (5)
11 0            0 (6)
111             1 (7)
1 000           0 (8)
1 00 1          1 (9)
1 0 1 0         0 (10)
1 0 11          0 (11)
11 00           1 (12)
11 0 1          0 (13)
111 0           0 (14)
1111            1 (15)
1 0000          1 (16)
1 000 1         0 (17)
1 00 1 0        0 (18)
1 00 11         1 (19)
1 0 1 00        0 (20)
1 0 1 0 1       0 (21)
1 0 11 0        0 (22)
1 0 111         0 (23)
11 000          0 (24)
11 00 1         1 (25)
11 0 1 0        0 (26)
11 0 11         0 (27)
111 00          1 (28)
111 0 1         0 (29)
1111 0          0 (30)
11111           1 (31)
1 00000         0 (32)

So, after computing the Baum-Sweet sequence for n, take the numbers that were truthy for the sequence and collect them for the final result. For n=32 we would have:

[1, 3, 4, 7, 9, 12, 15, 16, 19, 25, 28, 31]

As the final answer.

This is code-golf, shortest byte count wins.

JavaScript (ES6), 70 68 63 bytes

g=n=>n?g(n-1).concat(/0/.test(n.toString(2).split`00`)?[]:n):[]

console.log(g(1000).join(", "))

Slightly more interesting recursive solution:

n=>[...Array(n+1).keys()].filter(f=n=>n<2?n:n%4?n&f(n>>1):f(n/4))

67 bytes thanks to @Neil.

g is the function to call.


Print 1 to 15, using different printers Making a versatile integer printer is nice and all, but writing a single code that prints a lot of different numbers is cumbersome. Wouldn't it be easier to make a script that outputs a number, but also gives you a new script to get the next number?

Challenge:

Write a code that outputs a single integer N and an executable code. The next code should output N+1 and a code that can output N+2. Continue this path until you reach N = 15. (The last printed number should be 15).

Rules:

No input (assume the input is empty).
Full program or function or other convenient formats are allowed.
The first code should output 1.
You can't output leading zeros. I.e. you can't print 01 for 1.
The output must be on the format N, Code_for_N+1. Note that the output is separated by a comma and a single space. The code for N+1 has no surrounding quotation marks.  N , Code_for_N+1 is not accepted (space in front of the comma). Trailing newlines are OK.
The first character(s) of the output must be the number. (No leading spaces, or ans = N).
The printed number should not be part of the next code (the code can contain this number, but you can't take the output number as part of the code)

Example: The output for N=2 can be: 2, printer 2. In this case, printer 2 is the code for N=3. You can't use the entire output: 2, printer 2 as code for N=3.

The scripts may be in different languages
The datatypes are irrelevant (the number can be a string), but it can't be surrounded by anything (quotation marks, parentheses etc).
If there is a code outputted for N=15 then it must either print STOP! (see bonus), or don't print anything at all (not even a space or newline).

The code for N=15 can not crash (but outputting to STDERR is OK).
You are disqualified if the output code for N=15 prints 16 or anything else (except the bonus case).

Built in quine operators are not allowed.
Accessing the source file through the file system is not allowed.

Bonus:

-10 bytes if the code that prints 15 also produces a code that prints "STOP!"

Examples using Python syntax: (obviously, these will only work for the selected integers, not from 1 to 15.)

N = 1
print "1, print 2"
1, print 2

---
N = 15
print 15
15

---
N = 15   (Qualifies for the -10 bytes bonus)
print "15, print 'STOP!'"
15, print 'STOP!'

print 'STOP!'
STOP!

----

N = 15   (Qualifies for the -10 bytes bonus)
print "15, disp('STOP!')"
15, disp('STOP!')        (disp('STOP!') outputs STOP! in MATLAB)

----
N = 15   (This one is not OK. The submission is disqualified)
print "15, print 16"
15, print 16

Standard golfing rules apply! Smallest code (for N=1) in bytes win!

Pyth + ///, 15 bytes - 10 = 5
pPt`S15", STOP!

This prints 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, STOP! in Pyth, by taking range(1,15+1) and stripping off the start and end brackets, and printing it immediately followed by ", STOP!".
The next fourteen programs are in ///, which directly outputs all programs that don't contain / or \. So the second program
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15

gives 2 and the third program 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15. The penultimate program, 15, STOP!, prints 15, STOP!, so the last program is just STOP!.


Fastest yes in the west There has been a question about yes in the past, but this one is slightly different. You see, despite yes having a rather long size, it is incredibly fast. Running the following command:

timeout 1s yes > out

yields a file that is 1.9 GB. Compared to this program:

int puts();main(){while(1){puts("y");}}

which yields a measly 150 Mb.

The goal is to write a program that outputs y\n (that's y with a newline) repeatedly forever, in as few lines as possible, outputting the biggest size file in as short time as possible.

The scoring works with the equation: b * y/y'. The value b is the size of your program in bytes. The value of y is the size in bytes of the out file after running the following command: timeout 1s yes > out. The value of y' is the size in bytes of the out file after running the following command: timeout 1s PROG > out where PROG is your program, eg. ./a.out. Your program should match the output of the gnu coreutils program yes ran with no arguments exactly, albeit outputting y at any speed you like. Outputting zero bytes would be a divide by zero in the original equation, resulting in a score of inf for these purposes.

Lowest score wins.

Edit:

I will run all code on my computer, please show compilation commands and any setup required.

Specs (in case you want to optimize or something):

OS: Arch Linux 5.5.2-arch1-1
CPU: AMD Ryzen 2600X
SSD: Samsung 970 EVO NVMe
RAM: 16GB 3200MHz

Here is a script to calculate the score, since it seems people are having trouble:

b=$(wc -c < $1)
timeout 1s yes > out
y=$(wc -c < out)
timeout 1s $2 > out
y2=$(wc -c < out)
rm out
echo "scale=3;$b*$y/$y2" | bc

Example, given that the script is called score.sh and your program is yes.py:

./score.sh yes.py "python yes.py"

C, 112 bytes, 28 TB/s, score ≈ 0.008

long b[9<<21];main(){for(b[2]=write(*b=1,wmemset(b+8,'\ny\ny',1<<25),1<<27)/2;b[3]=b[2]*=2;ioctl(1,'@ ”\r',b));}

(If you’re having trouble copying and pasting this, replace the multicharacter constant '@ ”\r' with '@ \x94\r' or 1075876877.)

This writes 128 MiB of y\ns to stdout, and then repeatedly invokes the FICLONERANGE ioctl to double the file’s length by adding new references to the same disk blocks.  Requires Linux x86-64 and a filesystem supporting FICLONERANGE, such as Btrfs or XFS; stdout must be opened in read-write mode (e.g. ./prog 1<> out in bash).

Self-contained testing script

This script loop-mounts a freshly created filesystem from a memory-backed image file and runs the program there.  (I get about 43 TB/s in-memory, but the ratio with yes(1) is similar.)  It works with either Btrfs or XFS, but Btrfs seems to give better scores.

#!/usr/bin/env bash
set -eux
dir="$(mktemp -dp /dev/shm)"
cd "$dir"
trap 'umount fs || true; rm -r "$dir"' EXIT
printf "long b[9<<21];main(){for(b[2]=write(*b=1,wmemset(b+8,'\\\\ny\\\\ny',1<<25),1<<27)/2;b[3]=b[2]*=2;ioctl(1,'@ \\x94\\\\r',b));}" > prog.c
b="$(stat -c %s prog.c)"
gcc -O3 prog.c -o prog
dd of=fs.img bs=1 count=0 seek=8G

# Pick one:
mkfs.btrfs fs.img
#mkfs.xfs -m reflink=1 fs.img

mkdir fs
mount fs.img fs
sync
timeout 1 yes 1<> fs/out || true
y="$(stat -c %s fs/out)"
rm fs/out
sync
timeout 1 ./prog 1<> fs/out || true
y1="$(stat -c %s fs/out)"
echo "score = $b * $y / $y1 = $(bc -l <<< "$b * $y / $y1")"


Tips for golfing in Bash What general tips do you have for golfing in Bash? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Bash (e.g. "remove comments" is not an answer). Please post one tip per answer.

Undocumented, but works in every version I've run into for legacy sh backwards compatibility:

for loops allow you to use { } instead of do done.  E.g. replace:

for i in {1..10};do echo $i; done

with:

for i in {1..10};{ echo $i;}


Place a stone on an empty Go board See also: Make a move on a Go board.

Task

Go is a board game where two players (Black and White) place stones on the intersections of grid lines on a 19×19 board. Black moves first — for example, on D4:

In this challenge, you must take a Go board coordinate like D4 as input, and output an ASCII representation of a board with the first move played at the given point.

  Note that there is no column I. This is, historically, to reduce confusion with J and L.

This output consists of 19 lines, each containing 19 characters. The point with the stone on it is marked O. Empty points on the board are shown as ., except for the nine star points (at D4, D10, D16, K4, K10, K16, Q4, Q10, and Q16), which are marked *.

For example, given F5 as an input, your answer’s output must be:

...................
...................
...................
...*.....*.....*...
...................
...................
...................
...................
...................
...*.....*.....*...
...................
...................
...................
...................
.....O.............
...*.....*.....*...
...................
...................
...................

And given Q16 as input, your output must be:

...................
...................
...................
...*.....*.....O...
...................
...................
...................
...................
...................
...*.....*.....*...
...................
...................
...................
...................
...................
...*.....*.....*...
...................
...................
...................

Rules

You may write a function that takes the coordinate as an argument, or a program that reads the coordinate from the command line or from STDIN.
You may choose to accept input either in lower-case or upper-case, but your answer doesn’t need to handle both.
The input is always a single string like a1 or T19, never a string + number or two strings.
If you write a full program, your answer must be printed to STDOUT as a string, optionally followed by a trailing newline. If your answer is a function, you may print to STDOUT, or return a string, or return an array/list of strings (rows), or return a two-dimensional array or nested list of characters.
This is code-golf. The shortest answer in bytes wins.

C, 212 195 193 181 171 132 103 98 bytes
Saved 1 byte thanks to @FryAmTheEggman, 5 bytes thanks to @orlp
Call f() with the position to play (must be capitalized), and it prints out the resulting board.
i;f(char*p){for(i=380;i--;)putchar(i%20?i^20*atoi(p+1)+64-*p+(*p>72)?i%6^4|i/20%6^3?46:42:79:10);}

Try it on ideone.


Create a pyramidal matrix A pyramidal matrix is a square matrix where all numbers increase or decrease from the center point, like the two matrices below:

1  1  1  1  1
1  2  2  2  1
1  2  3  2  1
1  2  2  2  1
1  1  1  1  1

Or:

3  3  3  3  3
3  2  2  2  3
3  2  1  2  3
3  2  2  2  3
3  3  3  3  3

Given a non-zero integer n, create a pyramidal matrix where the numbers goes from 1 to n either in increasing order (if n<0), or decreasing order (if n>0) from the center. If n is even, then there will be 4 center numbers (see the examples).

As always:

Optional input and output format

Number of spaces, delimiter etc. is optional

Test cases:

1
1

-1
1

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

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

2
1  1  1  1
1  2  2  1
1  2  2  1
1  1  1  1

-2
2  2  2  2
2  1  1  2
2  1  1  2
2  2  2  2

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

Python 2, 109 99 98

n=input()
r=range(1,abs(n)+1)
l=r+r[~n|-2::-1]
for j in l:print[abs((n<0)*~-n+min(i,j))for i in l]

Create list

l = [1,2,3,4,5,4,3,2,1]

and play with it a little.

edit: new way of creating list + thx Lynn for two bytes


Keep your distance on a circle This is based on this challenge and Geobits's/CarpetPython's idea to improve it:

Keep your distance!

For this challenge, the distance between two numbers is measured on a loop, so, for example, the distance between 0 and 999 is 1. This should prevent strategies like always picking the lowest or highest number from winning almost every time. The only other change is that the lowest number that can be chosen is now 0 instead of 1.

I'll summarize it here:

Write a function in Java, Python, or Ruby that takes three arguments:

the number of rounds played so far
the number of players
the numbers picked in the previous rounds, as an array of space-separated strings

It should return an integer from 0 to 999, inclusive
The score for a program each round is the sum of the square roots of the distances to the numbers each other program picked
The program with the highest score after 100 rounds wins.
One answer per person

The control program is here:

https://github.com/KSFTmh/src/

Leaderboard

NumberOne, by TheBestOne, is winning.

NumberOne - 9700
NumberOnePlusFourNineNine - 9623
AncientHistorian - 9425
FindCampers - 9259
WowThisGameIsSoDeep - 9069
Sampler - 9014
SabotageCampers - 8545

Apparently, my camper sabotage...er(?) doesn't work very well.

Here are the full results: https://github.com/KSFTmh/src/blob/master/results-3

I think this is different enough to not be a duplicate.

By the way, this is my first time asking a question on Stack Exchange, so let me know if I'm doing something wrong.

Python 2, Sampler

This entry is based on the same code for Keep your distance, Sampler entry. I hope it will do better here where the 1 and 999 advantages do not exist.

Out of a list of places, choose the one that is farthest away from recently used
numbers, ignoring the previous turn (because other entries may predict based on just the previous turn).

def choose(turn, players, history):
    sample = map(int, (' '.join( history[-5:-1] )).split())
    def distance(x):
        return sum(min(1000-abs(x-y), abs(x-y))**0.5 for y in sample)
    score, place = max((distance(x), x) for x in range(1000))
    return place


Reduce the amount of loops when finding if an element is stored only once in the array? I was amazed to find that there is a way to reduce the times you loop on an array to find if a element is contained once.

One would think that the only way would be to loop through the whole array, and increasing a variable every time you find a match, and then check if it is equal to 1. However, lets look at this JavaScript code:

function isOnce(itm,arr){
    var first_match=-1;
    for(var i=0,len=arr.length;i<len;i++){
        if(arr[i]===itm){
            first_match=i;
            break;
        }
    }
    if(first_match!=-1){
        var last_match=-1;
        for(i=arr.length-1;i>first_match;i--){
            if(arr[i]===itm){
                last_match=i;
                break;
            }
        }
        if(last_match==-1){
            return true;
        }
    }
    return false;
}

It can reduce the times you loop when these two points met:

There are 2 or more matches
The first and last match are at least 1 space apart

so, arr=["a", ...(thousands of items here)... ,"a"]; //we only looped 2 times

I was wondering if there are other ways to reduce the looping in *certain cases.

*There are obviously some cases that one will need to loop through every item on these worst-case scenarios. So it might not work all the time.

D

bool containsOnce(E,R)(R haystack,E needle){
     bool foundOnce=false;
     foreach(e;haystack){
          if(e==needle){
              if(foundOnce)return false;
              foundOnce=true;
          }
     }
     return foundOnce;
}

this is pretty much the best case on unsorted data, you loop until you find a match and then set a flag to true and continue looping, when you find the second match return false immediately, when you looped over the entire thing return state of the flag

this has better timebounds when the double match is found near the beginning of the array (and in general when the items are close together) (but is better in a code-golf contest ;) )

in interest of time bound you'll remain at O(n) regardless on any algorithm (sometimes there simply are no improvements possible except with micro-optimizations). as finding a single match (a subproblem of the current problem) in an unsorted array is O(n)


One Expression, Many Values Using our familiar mathematical symbols: +, x, parenthesis, and any rational number, it's easy to create expressions that evaluates to some desired number. For example: 1+(2x3)=7, (1+2)+(3x6.5)=22.5 and so on. Boring enough.
In this challenge, we'll use a new operator: ±. The use of ± in an expression means you need to evaluate the expression by replacing the ±'s by + or - in all possible ways, and return the set of all possible values. For example:

1±2±3 = {-4,0,2,6} because 1±2±3 can be any of 1+2+3, 1+2-3, 1-2+3 and 1-2-3 and their values are 6,0,2,-4 respectively.
(±2)x(2±3) = {-10,-2,2,10} for similar reasons.

Now, as it turns out, given any set of distinct real numbers, it's possible to create an expression with +,x,(,),±, and real numbers that evaluates to the given set.
Task
Your task is to write a program or function in a language of your choice, that takes a sequence (list/array/any convenient format) of integers and outputs an expression (as a string) consisting of +,x,(,),±, and rational numbers that evaluates to the set of the given numbers.

Note that the exact character ± doesn't matter; you can use any other character of your choice as long as it's distinguishable from the other characters you're using.  But you must mention which character you are using in your submission.
The input is allowed to consist of decimal approximations (up to reasonable accuracy) of the rational numbers used.
Input and output can be taken in any of the standard ways.
Standard loopholes are forbidden.
You can assume the given integers will be distinct, and provided in increasing order.
Output may contain spaces and newlines.

Winning Criterion
This is code-golf, so shortest code in bytes wins.
Examples

Input        |  Possible output
-------------+-----------------------------
[1,2,3]      |  2±0.5±0.5
[-7,-3,1,21] |  (1±2)x(3±4)

Idea taken from a question in the Tournament of Towns, Fall 2015.

Python 2, 56 bytes

f=lambda h,*t:t and"(.5?.5)*(%s+%%s)+"%f(*t)%-h+`h`or`h`

Try it online!

The ? stands for ±. Example usage:

f(-3,5,20) ->
(.5?.5)*((.5?.5)*(20+-5)+5+3)+-3

The idea is that we can take an expression E and adjoin a new value h to its set of values by doing (.5±.5)*(E+-h)+h.


Autoscale complex function Context: We are working on a complex image drawing program to produce mugs, t-shirts, and so on. Here is an example of such function

However, we are facing the following problem: Random generated functions are mostly white and black (where black is close to zero and white close to infinity). The idea of this contest is to find a number to scale all numbers so that corresponding colors are in the visible spectrum.

Problem

The input is, formatted the way you want:

An array of double precision A[1..n] randomly sorted of positive numbers (>0).
An expected inclusive lower bound L > 0
An expected inclusive upper bound U > 0

The expected output is

A number f so if we multiply all elements of A by f, it maximizes the number of the new elements between L and U. If there are multiple solutions, f should be as close to 1 as possible.

Write a program computing f in a few operations as possible.

To check, post the result of your program on the following (sorted for convenience) input:

A = [0.01, 0.02, 0.5, 1 , 5, 9.5, 9.8, 15, 18, 20, 50, 100]
L = 1
U = 5

The result should be f = 0.25

Winning conditions: The winner will be the one with the best time complexity. If there are multiple algorithms of the same complexity, the fastest one will win. If your program is obfuscated or hard to read, please also attach an unobfuscated version with explanations.

C++
Comments indicate how code works.
#include<iostream>
#include<vector>
using namespace std;

int main(){
    // input stores input, sum_values stores the sum of values in the valid range after multiplying
    vector<double>input;
    vector<double>sum_values;

    // stores input, and ends of range
    double num, lower, higher;

    cout<<"Enter the array of values, use 0 to exit: ";

    // input
    while(1){
        cin>>num;
        if(num==0)break;
        input.push_back(num);
    }

    cout<<"Enter the mimimum and maximum values: ";

    cin>>lower>>higher;

    // if array is empty or lower is greater than higher, print 1 and exit
    if(lower>higher||input.size()==0){cout<<"1";return 0;}

    // iterate through all values between .0001 and .9999
    for(double d=.0001;d<1;d+=.0001){

        // check each d for valid ranges
        for(int i=0,valid=0;i<input.size();i++){

            // check if input * d is in valid range
            if(d*input[i]>=lower&&d*input[i]<=higher)valid++;

            // store final number
            if(i==input.size()-1)sum_values.push_back(valid);
        }
    }

    // iterate through compiled sum of ranges and find highest
    int position=0, biggest=-.1;
    for(int i=0;i<sum_values.size();i++){

        // return value closest to 1 for equal values
        if(sum_values[i]>=biggest){
            biggest=sum_values[i];
            position=i;
        }
    }

    // print value
    cout<<(double)position*.0001;

    return 0;
}


Perl 6, 31 bytes

{$^a;first {$a**$_~~/$a/},2..*}

Try it online!


Quine Anagrams! (Robbers' Thread) This is the robbers' thread. For the cops' thread, click here.
Cops' Task
For the cops' thread, click here.
Robbers' Task

Find an uncracked submission on the cops' thread. (A submission may only be cracked once.)
Unscramble the code to find a working quine.
Post an answer on the robbers' thread. Include the language, the byte count, the user who posted the scrambled code, a link to that answer, and the unscrambled code.

Here is an example of a robber submission:

Python, 29 bytes, Oliver
_='_=%r;print _%%_';print _%_

Scoring
The user with the most cracks will be the winner of this section.

Vim, 22 bytes, Loojvo
qtiqtqx0l"tp^V^[^[qx0l"tp

Try it online!
Explanation:
qt                  " Start recording in register 'q'
  i                 " Enter insert mode
   qtqx0l"tp        " Enter this string
            ^V^[    " Enter a literal 'esc' character
                ^[  " Exit insert mode
                  q " Stop recording

At this point, the buffer looks like this:
qtqx0l"tp^[

And the cursor is on the last column (the 'esc' key).
x                   " Delete the esc character
 0l                 " Move to the second character on this line
   "tp              " And paste register 't'


Finding Distant Primes Let us call a prime \$p\$ an \$(m,k)\$-distant prime \$(m \ge 0, k \ge 1, m,k \in\mathbb{Z})\$ if there exists a power of \$k\$, say \$k^x (x \ge 0, x \in\mathbb{Z})\$, such that \$|k^x-p| = m. \$ For example, \$23\$ is a \$(9,2)\$-distant prime as \$|2^5 - 23| = 9\$. In other words, any prime which is at a distance of \$m\$ from some non-negative power of \$k\$ is an \$(m,k)\$-distant prime.
For this challenge, you can either:

Take input three integers \$n, m, k\; (n,k \ge1, m \ge0)\$ and print the \$n^{th}\$ \$(m,k)\$-distant prime. You do not need to handle inputs where answer does not exist. You can take \$n\$ as zero-indexed if you want.
Take \$n, m, k\$ as input and print the first \$n\$ \$(m,k)\$-distant primes.
Or, take only \$m\$ and \$k\$ as input and print all \$(m,k)\$-distant primes. It is fine if your program runs infinitely and does not terminate if there aren't any \$(m,k)\$-distant primes, or all such primes have already been printed.

Examples
m,k    -> (m,k)-distant primes
1,1    -> 2
0,2    -> 2
1,2    -> 2, 3, 5, 7, 17, 31, 127, 257, 8191, 65537, 131071, 524287, ...
2,2    -> 2, 3
2,3    -> 3, 5, 7, 11, 29, 79, 83, 241, 727, 6563, 19681, 59051
3,2    -> 5, 7, 11, 13, 19, 29, 61, 67, 131, 509, 1021, 4093, 4099, 16381, 32771, 65539, 262147, ...
20,2   -> None
33,6   -> 3
37,2   -> 41, 53, 101, 293, 1061, 2011, 4133, 16421, ...
20,3   -> 7, 23, 29, 47, 61, 101, 223, 263, 709, 2207, 6581, 59029, 59069, 177127, 177167
20,7   -> 29, 2381, 16787
110,89 -> 199, 705079

Rules

Standard loopholes are forbidden.
You may choose to write functions instead of programs.
This is code-golf, so the shortest code (in bytes) wins.

JavaScript (ES6), 103 bytes
Expects (m)(k)(n) and returns the \$n\$-th \$(m,k)\$-distant prime (1-indexed).

m=>k=>F=(n,p)=>(g=d=>p%--d?g(d):d^1)(p)|(g=(n,K=1)=>K>n||K<n&k>1&&g(n,K*k))(p+m)*g(p-m)||--n?F(n,-~p):p

Try it online!
Commented
m => k =>            // outer functions taking m and k
F = (n, p) =>        // inner recursive function taking n
(                    // and using p = current prime candidate
  g = d =>           // g is a recursive function taking a divisor d
    p % --d ? g(d)   //   decrement d until it divides p
            : d ^ 1  //   return a truthy value if p is composite
)(p) |               // initial call to g with d = p
(                    //
  g = (n,            // g is a recursive function taking n = p + m or p - m
          K = 1) =>  // and K = k ** x
    K > n ||         //   if K is greater than n
    K < n & k > 1 && //   or K is less than n and k is greater than 1:
      g(n, K * k)    //     do a recursive call with k raised to the next exponent
)(p + m) *           // unless the above function is truthy for p + m ...
g(p - m)             // ... and for p - m (meaning that we don't have |k**x-p|=m)
                     // or p was composite:
|| --n               //   decrement n
?                    // if all of the above is truthy:
  F(n, -~p)          //   try again with p + 1
:                    // else:
  p                  //   success: return p


Digits in their lanes Input:

A list of integers

Output:

Put each digit (and the minus sign) in its own lane, in the order -0123456789, ignoring any duplicated digits.

Example:

Input: [1,729,4728510,-3832,748129321,89842,-938744,0,11111]

Output:

-0123456789  <- Added as clarification only, it's not part of the output

  1
   2    7 9
 012 45 78
-  23    8
  1234  789
   2 4   89
-   34  789
 0
  1

Challenge rules:

Any duplicated digits in the number are ignored.
I/O can be in any reasonable format. Input can be as a list/array of strings or character-array. Output can be as a list of strings, characters, character-matrix, etc.
Trailing spaces are optional.
Any amount of leading or trailing new-lines are optional (but not in between lines).
Input will always contain at least one integer
You'll have to support an integer range of at least -2,147,483,648 though 2,147,483,647 (32-bit).
The input-list will never contain -0, 00 (or more than two zeroes), or integers with leading zeroes (i.e. 012).
If you language uses a different symbol for negative numbers (like an upper ¯), you are also allowed to use that instead, as long as it's consistent.
You are allowed to have a space delimiter between digits (so a line without 5 or 8 can be - 0 1 2 3 4   6 7   9 instead of -01234 67 9), as long as it's consistent (and therefore there should also be a space between - and 0).

General rules:

This is code-golf, so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
Default Loopholes are forbidden.
If possible, please add a link with a test for your code.
Also, please add an explanation if necessary.

Test cases:

Input: [1,729,4728510,-3832,748129321,89842,-938744,0,11111]
Output:
  1
   2    7 9
 012 45 78
-  23    8
  1234  789
   2 4   89
-   34  789
 0
  1

Input: [4,534,4,4,53,26,71,835044,-3559534,-1027849356,-9,-99,-3459,-3459,-94593,-10234567859]
Output:
      4
     345
      4
      4
     3 5
    2   6
   1     7
  0  345  8
 -   345   9
 -0123456789
 -         9
 -         9
 -   345   9
 -   345   9
 -   345   9
 -0123456789

Input: [112,379,-3,409817,239087123,-96,0,895127308,-97140,923,-748]
Output:
  12
   3    7 9
-  3
 01 4   789
 0123   789
-      6  9
 0
  123 5 789
-01  4  7 9
   23     9
-    4  78

Input: [-15,-14,-13,-12,-11,10,-9,-8,-7,-5,-4,-3,-1,0,9,100,101,102,1103,104,105,106,116,-12345690]
Output:
- 1   5
- 1  4
- 1 3
- 12
- 1
-01
-         9
-        8
-       7
-     5
-    4
-   3
- 1
 0
          9
 01
 01
 012
 01 3
 01  4
 01   5
 01    6
  1    6
-0123456  9

Input: [99,88,77,66,55,44,33,22,11,10,0,0,0,-941]
Output:
          9
         8
        7
       6
      5
     4
    3
   2
  1
 01
 0
 0
 0
- 1  4    9

05AB1E, 13 bytes

Code:

v'-žh«DyмSð:,

Uses the 05AB1E encoding. Try it online!

Explanation:

v               # For each element in the input..
 '-žh«          #   Push -0123456789
      D         #   Duplicate this string
       yм       #   String subtraction with the current element
                    e.g. "-0123456789" "456" м  →  "-0123789"
         Sð:    #   Replace all remaining elements with spaces
                    e.g. "-0123456789" "-0123789" Sð:  →  "     456   "
            ,   #   Pop and print with a newline


Take It or Leave It: A Game Show for Computers Context:

A reclusive billionaire has created a game show to attract the world's best and brightest programmers. On Mondays at the stroke of midnight, he chooses one person from a pool of applicants to be the contestant of the week, and provides them with a game. You are this week's lucky contestant!

This week's game:

The host provides you with API access to a stack of 10,000 digital envelopes. These envelopes are randomly sorted, and contain within them a dollar value, between $1 and $10,000 (no two envelopes contain the same dollar value).
You have 3 commands at your disposal:

Read(): Read the dollar figure in the envelope at the top of the stack.

Take(): Add the dollar figure in the envelope to your game show wallet, and pop the envelope off the stack.

Pass(): Pop off the envelope on the top of the stack.

The Rules:

If you use Pass() on an envelope, the money within is lost forever.

If you use Take() on an envelope containing $X, from that point forward, you may never use Take() on an envelope containing < $X. Take() on one of these envelopes will add $0 to your wallet.

Write an algorithm that finishes the game with the maximal amount of money.
If you're writing a solution in Python, feel free to use this controller to test out algorithms, courtesy of @Maltysen: https://gist.github.com/Maltysen/5a4a33691cd603e9aeca
If you use the controller, you cannot access globals, you can only use the 3 provided API commands, and local scoped variables. (@Beta Decay)
Notes: "Maximal" in this case means the median value in your wallet after N > 50 runs. I expect, though I would love to be proven wrong, that the median value for a given algorithm will converge as N increases to infinity. Feel free to try to maximize the mean instead, but I have a feeling that the mean is more likely to be thrown off by a small N than the median is.
Edit: changed the number of envelopes to 10k for easier processing, and made Take() more explicit.
Edit 2: The prize condition has been removed, in light of this post on meta.
Current high scores:
PhiNotPi    - $805,479
Reto Koradi - $803,960
Dennis      - $770,272 (Revised)
Alex L.     - $714,962 (Revised)

CJam, $87,143 $700,424 $720,327 $727,580 $770,272

{0:T:M;1e4:E,:)mr{RM>{RR(*MM)*-E0.032*220+R*<{ERM--:E;R:MT+:T;}{E(:E;}?}&}fRT}
[easi*]$easi2/=N

This program simulates the entire game multiple times and calculates the median.

How to run

I've scored my submission by doing 100,001 test runs:

$ time java -jar cjam-0.6.5.jar take-it-or-leave-it.cjam 100001
770272

real    5m7.721s
user    5m15.334s
sys     0m0.570s

Approach

For each envelope, we do the following:

Estimate the amount of money that will inevitably be lost by taking the envelope.

If R is the content and M is the maximum that has been taken, the amount can be estimated as R(R-1)/2 - M(M+1)/2, which gives the money all envelopes with contents X in the interval (M,R) contain.

If no envelopes had been passed yet, the estimation would be perfect.
Calculate the amount of money that will inevitably be lost by passing the envelope.

This is simply the money the envelope contains.
Check if the quotient of both is less than 110 + 0.016E, where E is the number of remaining envelopes (not counting envelopes that cannot be taken anymore).

If so, take. Otherwise, pass.


Tips for golfing in Jolf Jolf is a procedural golfing language made by @CᴏɴᴏʀO'Bʀɪᴇɴ.

What tips do you have for golfing in Jolf?

Please post one tip per answer.

These tips should be at least somewhat specific to Jolf, e.g. remove comments is an answer, but not a very good one.

Know your auto-assigning variables!

Jolf has many ways to "auto assign" variables. The standard one is γ, which takes the value of the next expression. Β is the same thing, but converts the next expression to a number.

Also, ζ (zeta) is a variable initialized to -1/12 (guess why), and can be re-assigned with Ζ (Zeta).

For example, let's say you want to compare I (the input string) to an operation over itself. For now, let's see if I + I = reverse(I + I). This is written as, conventionally:

=+II_+II

But this can be golfed down to:

=γ+II_γ


Downgrade to a Palindrome Given a string s, return the smallest contiguous substring you can remove to create a palindrome.

Examples:
800233008   -> 2
racecarFOOL -> FOOL
abcdedcba   -> (empty string)
ngryL Myrgn -> "L " (or " M")
123456789   -> 12345678 (or 23456789)
aabcdbaa    -> c (or d)
[[]]        -> [[ (or ]])
a           -> (empty string)

Test case suggestions from users (if you find an edge case not listed, please post a comment):
aabaab      -> b    | Suggested by Zgarb, some returned "aa".

Rules

Only printable ASCII characters will appear in the input (no newlines, keep it simple).
Not really a rule, but note <>, /\, (), [] and {} are not palindromes.

This is code-golf, smallest byte-count wins.

+100 bounty has been claimed by Adnan

J, 24 bytes

(0{::(-:|.)\.#&,<\)~i.@#

Try it online!

Explanation

(0{::(-:|.)\.#&,<\)~i.@#  Input: array of chars S
                       #  Length of S
                    i.@   Range, [0, 1, ..., len(S)-1]
(                 )~      Dyadic verb on range and S
           \.               For each outfix of S of size x in range
        |.                    Reverse
      -:                      Matches input (is palindrome)
                <\          Box each infix of S of size x in range
             #&,            Flatten each and copy the ones that match
 0{::                       Fetch the result and index 0 and return


Fill the Screen with Wang Tiles It has been proven that the following 13 square Wang tiles always tile the plane aperiodically. This means that when the squares are arranged in a grid with all neighboring sides the same color, a translation of the pattern will never match up with itself.

We'll represent each tile textually by a 3×3 grid filled with spaces at the center and corners, and the numbers 1 through 5 instead of the colors red, green, blue, yellow, grey, at the edges:

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

Goal

Your task is to write a program that takes in a width and height and outputs a valid Wang tile grid with those dimensions. A valid tiling is one in which all the adjacent tile edges have the same color (or number). The smallest program in bytes wins.

Your input should come from stdin or command line arguments and output should go to stdout. The exact input format can be anything reasonably obvious, like >>> wangtiler 3 2. The width and height are always positive integers.

Example (width = 3, height = 2)

Notice that when we layout the textual tiles the neighboring edges form necessary redundant pairs of digits:

 1  2  1
2 11 22 1
 2  3  2
 2  3  2
4 55 55 4
 1  2  2

(This is NOT the proper output format.)

We can compress these horizontally and vertically to get:

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

This compressed format is the proper output format you must use. The odd numbered lines must include their trailing space.

Graphical Bonus

Instead of having any textual output, your program may output an image of the tiled grid. The graphical tiles must be made up of four 45-45-90 triangles arranged in a square and use five easily distinguishable colors like the tiles above. The black borders are not required. The graphical tiles must be at least 32×32 pixels in size. No "compression" is applied to them.

Example bonus image: (same grid as example above)

The bonus is worth minus 150 bytes.

Notes

You must use this set of 13 tiles.
Tiles may not be rotated.
Tiles may appear any number of times (including none at all).
You may assume a valid tiling with any dimensions is possible.

Python (565 - 150 = 415)

Btw... it seems that we can't naively just decide the next tile by the its left and top tile. There's some combination of tiles that will fit each other.
This solution fills in left->right, top->down brute forces through all possible combinations and backtracks if a tile cannot fit in.

For more info about the 13 tile proof: An aperiodic set of 13 Wang tiles

Width and Height are specified by W and H

Red, Green, Blue, Yellow and Noir specified by R, G, B, Y and N

import Image,sys
W,H=map(int,sys.argv[1:])
R=99
G=R<<8
B=G<<8
Y=G+R
N=0
s="RGB";u=32;g=[[0,0]]*W*H;k=f=0
def t(c):i=Image.new(s,(2,2));k=i.load();q=16;k[1,0],k[1,1],k[0,1],k[0,0]=c;return i.resize([64]*2).rotate(45).crop((q,q,q+u,q+u))
while k<H*W:
 z=g[k][1];v=-1;j=k/W;i=k%W
 while z<13:
    l=map(eval,"GGGRRRYBGGYBGGBBRRGYYNNNNYBGBGBGRGRYRGGRRGGBBYYYYNNN"[z::13])
    if(j<1or g[(j-1)*W+i][0][2]==l[0])and(i<1or g[j*W+i-1][0][1]==l[3]):g[k]=[l,z+1];v=1;z=99
    z+=1
 g[k][1]*=(v>0);k+=v
m=Image.new(s,(W*u,H*u))
for e in g:m.paste(t(e[0]),(f%W*u,(f/W)*u));f+=1
m.show()

Output. Not the actual color scheme... cuz too glaring. This might make some interesting interior decor patterns...:


Help me pair my left and right socks! Inspired by Help me pair my socks, and the fact that I have some pairs of socks where the left sock is distinct from the right.

Background

Again, I have a huge pile of socks. And a machine that can give the list of labels of the socks for me. This time, the labels follow these rules:

Some socks have left and right versions. In this case, left socks are labelled -n and right socks are labelled n, where n is a unique positive integer. The list of such socks will be explicitly given to you.
The others don't have such a thing, and they just match themselves. All socks of this type are simply labelled n (no negative labels).

An example pile would look like this:

[3, 3, -2, 4, -1, -1, 1, 4, 4, 3, 2, 3, -1, 4, 4]

where 1 and 2 have left and right versions. Then the pairs and leftovers are:

pairs: {3: 2, 4: 2, 1: 1, 2: 1} or [1, 2, 3, 3, 4, 4]
leftovers: {4: 1, -1: 2} or [-1, -1, 4]

Note that two -1s don't make a pair because both are left socks.

Challenge

Given the pile of socks and the list of sock labels having L/R versions, output the pairs that can be made from the pile, and leftovers that are not part of any pairs.

Input and output

You can assume the following for input:

Zeros won't appear in either list.
L/R labels are unique and all positive, but possibly not sorted.
Negative numbers that are not part of L/R labels won't appear in the pile.

Both outputs can be represented as either a mapping type (label to count) or a flat list (each item appearing once per count). You can output in following ways:

Pairs can be represented as either a pair (3, 3) / (-1, 1) or a single number 3 / 1 / -1, or a mixture of both. But the same pairs should be represented in the same way in a single run, e.g. outputting [3, (3, 3)] or [(-1, 1), (1, -1)] or [1, -1] is not allowed.
For both pairs and leftovers, a pair and single number can be wrapped in any kind of containers, e.g. singleton arrays can be used to represent a single leftover.
For both pairs and leftovers, the order of items is not important.
If you use a mapping type, zero-count items are allowed, even the ones not in the pile of socks.

Scoring and winning criterion

Standard code-golf rules apply. The shortest code in bytes wins.

Test cases

Pile: [3, 3, -2, 4, -1, -1, 1, 4, 4, 3, 2, 3, -1, 4, 4]
LR: [1, 2]
Pairs: [1, 2, 3, 3, 4, 4]
Leftovers: [-1, -1, 4]

Pile: [1, 1, 2, 2]
LR: [1]
Pairs: [2] (two right 1's and two simple 2's, so only 2's make a pair)
Leftovers: [1, 1]

Pile: [5, -10, 5, 10, -10, 10]
LR: [10, 20]
Pairs: [5, 10, 10]
Leftovers: []

Pile: [-6, 7, -9, 3, 4, -6, 4, -9, 8]
LR: [6, 9, 4]
Pairs: []
Leftovers: [-6, 7, -9, 3, 4, -6, 4, -9, 8]

Pile: []
LR: [1, 2]
Pairs: []
Leftovers: []

05AB1E, 40 27 bytes
.¡Ä}εDÄIåài{γζðδKë2ô]€`é.¡g

Inputs are in the order Pile, LR and outputs in the order Leftovers, Pairs in the format ([[1],[2],[3]], [[1,1], [-2,2], [3,3]]).
-13 bytes by porting @AZTECCO's Japt answer, so make sure to upvote him!
Try it online or verify all test cases.
Explanation:

.¡ }              # Group the (implicit) input integer-list `Pile` by:
  Ä               #  Their absolute values
    ε             # Then map each group to:
          i       #  If
       Iåà        #  any values of the second input-list `LR`
     DÄ           #  is in the current group's absolute values:
           {      #   Sort the values in the group
            γ     #   And then group it on subsequent equal values
             ζ    #   Zip/transpose to create pairs of positive & negative values,
                  #   with space as default filler if the lists are of unequal length
              ðδK #   And remove all those spaces
          ë       #  Else:
           2ô     #   Split split the group into parts of size 2
    ]             # Close the if-else statement and map
     €`           # Flatten each inner list once to remove the groups again
       é          # Sort each inner list by length
        .¡g       # And also group by length
                  # (after which this result is output implicitly as result)


Reduce html to n characters while keeping the formatting Almost every language has a built-in function that can split a string at a given position. However, as soon as you have html tags in the string, the built-in function will not work properly.

Your task is to write a program or function which splits a string at the nth character but does not count characters of html tags and will output a valid html. The program must keep the formatting. Spaces outside the html tags may be counted or not counted, as you wish, but must be preserved. You can, however, exchange multiple consecutive spaces into a single space.

Input:

the string
the position to split at (0-based)

These can be taken as program or function arguments or can be read from the standard input.

Output:
The split string which can be returned or written to the standard output.

The input will be valid html, it won't contain any entities (such as &nbsp;). Tags that are opened after the character limit should be omitted from the output (see the last example).

Example:

Input: test, 3
Output: tes

Input: more complicated, 7
Output: more co

Input: no html, 2
Output: no

Input: no html root, 5
Output: no ht

Input: no imgmore text, 6
Output: no img

You can use any language and the standard library of the given language. This is code golf, shortest program wins. Have fun!

This answer is no longer valid with the latest rule.

Javascript (ES6) 94 91

f=(s,l)=>s.split(/(<[^>]+>)/).map(x=>x[0]=='<'?x:[l-->0?y:''for(y of x)].join('')).join('')

f('more complicated', 7);
// 'more co'

Ungolfed:

f=(s,l)=>
    s.split(/(<[^>]+>)/). // split string s by <*>, capture group is spliced into the array
    map(x=> // map function to every item in the array
        x[0]=='<'? // if first character is a <
            x // don't modify the string
        : // else
            [ // array comprehension
                for(y of x) // for every character y in x
                    l-->0? // if l > 0 (and decrement l)
                        y // character y
                    : // else
                        '' // empty string
            ].join('') // join characters in array
        ).
    join('') // join all strings in array


XKCD Password Generator Introduction
Apparently, this question has been asked here and it unfortunately closed. I thought it was a good idea to try again with it, but done right.
XKCD looks at the how we are  trained to use "hard to remember passwords", thinking it's secure, but instead, would take a computer 3 days to crack. On the flip side, remembering 4-5 words brings Kuan's Password Intropy up, and is easy to remember. Crazy how that works, huh?
Challenge
The job today is to create 5 passwords using words. 4 words per password and a minimum of 4 letters per word, but no maximum. Kuan's Password Intropy will need to be calculated for every password, but a forced minimum will not be set.
What is Kuan's Password Intropy?
Kuan's Password Intropy is a measurement of how unpredictable a password is, according to Kuan. There is a simple calculation: E = log2(R) * L. E being Kuan's Password Intropy, R being range of available characters and L for password length.
Range of available characters is self explanatory. It's the range of characters that a password can have, in this case is Upper and lower case. Since there is 26 characters in the alphabet, 26 x 2 = 52 characters in the whole range of the password.
Password Length is also self explanatory. It's the total length of the password after creation.
Constraints

No input.
A word cannot reappear in the same password.
No symbols or numbers allowed in a password.
4 words per password, but a forced minimum of 4 letters per word.
No spaces between words.
You cannot generate the same password over and over again.
Each word has to be capitalized in a password.
Output has to be human-readable, must be spaced out. Must also include Kuan's Password Intropy of the password with it using Kuan's Password Intropy equation above.
Dictionary. You must use this, download it as a text file and integrate accordingly. This will be the list from which you grab words from. Your code should assume its available.
This is code-golf, shortest bytes win.

Output
TriedScarProgressPopulation 153.9
TryingPastOnesPutting 119.7
YearnGasesDeerGiven 108.3
DoubtFeetSomebodyCreature 142.5
LiquidSureDreamCatch 114.0

Python 2, 102 101 97 91 bytes

from random import*
exec"x=''.join(x.title()for x in sample(f,4));print(x,57*len(x)/10);"*5

Assumes the dictionary as a list named f.

Can be tested by saving the file as dict.txt and calling

f = open('dict.txt').readlines()


My array should equal this, but it doesn't! Given an array of integers a which contains n integers, and a single  integer x; remove the fewest amount of elements from a to make the sum of a equal to x. If no combinations of a can form x, return a falsy value.

As pointed out in a comment this is the maximum set with a sum of x, excuse my lesser math brain. I forgot a lot of terms since college.

Examples (Truthy):

f([1,2,3,4,5,6,7,8,9,10], 10) = [1,2,3,4]

f([2,2,2,2,2,2,2,2,2], 10) = [2,2,2,2,2]

f([2,2,2,2,-2,-2,-2,-4,-2], -8) = [2,2,-2,-2,-2,-4,-2]

f([-2,-4,-2], -6) = [-4,-2] OR [-2,-4]

f([2,2,2,4,2,-2,-2,-2,-4,-2], 0) = [2,2,2,4,2,-2,-2,-2,-4,-2] (Unchanged)

f([], 0) = [] (Unchanged Zero-sum Case)

Examples (Falsy, any consistent non-array value):

Impossible to Make Case: f([-2,4,6,-8], 3) = falsy (E.G. -1)

Zero Sum Case: f([], non-zero number) = falsy (E.G. -1)

Note: any value like [-1] cannot be valid for falsy, as it is a potential truthy output.

Rules:

Input may be taken in array form, or as a list of arguments, the last or first being x.
Output may be any delimited list of integers. E.G. 1\n2\n3\n or [1,2,3].
Any value can be used as a falsy indicator, other than an array of integers.
Your code must maximize the size of the end array, order does not matter.

E.G. For f([3,2,3],5) both [2,3] and [3,2] are equally valid.
E.G. For f([1,1,2],2) you can only return [1,1] as [2] is shorter.

Both the sum of a and the value of x will be less than 2^32-1 and greater than -2^32-1.
This is code-golf, lowest byte-count wins.
If there are multiple subarrays of the same size that are valid, it is not acceptable to output all of them. You must choose a single one and output that one.

Let me know if this has been posted, I couldn't find it.

Posts I found like this: Related but closed, ...

Brachylog, 8 bytes
h⊇.+~t?∧

Try it online!
Monthly Brachylog answer. Returns false. if it is not possible.
Explanation
h⊇.           The output is a subset of the head of the input
  .+~t?       The sum of the elements of the output must equal the tail of the input
       ∧      (Avoid implicit unification between the output and the input)


Integer goes back and forth through time Input:

An integer.

Output:

First convert the integer to it's equivalent Roman Numeral.
Then convert each capital letter of that Roman Numeral to their ASCII/UNICODE decimal value.
And output the sum of those.

Example:

1991 -> MCMXCI -> 77+67+77+88+67+73 -> 449
^ input                                ^ output

Roman Numerals:

Here is a perhaps useful Roman Numeral Converter.

Challenge rules:

Standard Roman Numeral rules are applied, so no alternative forms like IIII or VIIII instead of IV and IX.*
The Macron lines above the Roman Numerals past 1,000 are ¯ (UNICODE nr. 175). So one line counts as +175 and two as +350.
You are allowed to use any kind of input and output type, as long as it represents the integers.
The test cases will be in the range of 1 - 2,147,483,647.

* Roman Numeral rules (quote from Wikipedia):

  Numbers are formed by combining symbols and adding the values, so II is two (two ones) and XIII is thirteen (a ten and three ones). Because each numeral has a fixed value rather than representing multiples of ten, one hundred and so on, according to position, there is no need for "place keeping" zeros, as in numbers like 207 or 1066; those numbers are written as CCVII (two hundreds, a five and two ones) and MLXVI (a thousand, a fifty, a ten, a five and a one).

  Symbols are placed from left to right in order of value, starting with the largest. However, in a few specific cases, to avoid four characters being repeated in succession (such as IIII or XXXX), subtractive notation is often used as follows:

  I placed before V or X indicates one less, so four is IV (one less than five) and nine is IX (one less than ten)
  X placed before L or C indicates ten less, so forty is XL (ten less than fifty) and ninety is XC (ten less than a hundred)
  C placed before D or M indicates a hundred less, so four hundred is CD (a hundred less than five hundred) and nine hundred is CM (a hundred less than a thousand)
  For example, MCMIV is one thousand nine hundred and four, 1904 (M is a thousand, CM is nine hundred and IV is four).

  Some examples of the modern use of Roman numerals include:
  1954 as MCMLIV; 1990 as MCMXC; 2014 as MMXIV
  SOURCE

General rules:

This is code-golf, so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.
Default Loopholes are forbidden.
If possible, please add a link with a test for your code.
Also, please add an explanation if necessary.

Test cases:

100          ->   67
1            ->   73
4            ->   159
22           ->   322
5000         ->   261
2016         ->   401
1000000000   ->   427
1991         ->   449
9999         ->   800
1111111111   ->   2344
2147483647   ->   5362


How slow is Python really? (Or how fast is your language?) I have this code which I have written in Python/NumPy

from __future__ import division
import numpy as np
import itertools

n = 6
iters = 1000
firstzero = 0
bothzero = 0
""" The next line iterates over arrays of length n+1 which contain only -1s and 1s """
for S in itertools.product([-1, 1], repeat=n+1):
    """For i from 0 to iters -1 """
    for i in xrange(iters):
        """ Choose a random array of length n.
            Prob 1/4 of being -1, prob 1/4 of being 1 and prob 1/2 of being 0. """
        F = np.random.choice(np.array([-1, 0, 0, 1], dtype=np.int8), size=n)
        """The next loop just makes sure that F is not all zeros."""
        while np.all(F == 0):
            F = np.random.choice(np.array([-1, 0, 0, 1], dtype=np.int8), size=n)
        """np.convolve(F, S, 'valid') computes two inner products between
        F and the two successive windows of S of length n."""
        FS = np.convolve(F, S, 'valid')
        if FS[0] == 0:
            firstzero += 1
        if np.all(FS == 0):
            bothzero += 1

print("firstzero: %i" % firstzero)
print("bothzero: %i" % bothzero)

It is counting the number of times the convolution of two random arrays, one which is one longer than the other, with a particular probability distribution, has a 0 at the first position or a 0 in both positions.

I had a bet with a friend who says Python is a terrible language to write code in that needs to be fast.  It takes 9s on my computer.  He says it could be made 100 times faster if written in a "proper language".

The challenge is to see if this code can indeed by made 100 times faster in any language of your choice.  I will test your code and the fastest one week from now will win.  If anyone gets below 0.09s then they automatically win and I lose.

Status

Python. 30 times speed up by Alistair Buxon! Although not the fastest solution it is in fact my favourite.
Octave. 100 times speed up by @Thethos.
Rust. 500 times speed up by @dbaupp.
C++. 570 times speed up by Guy Sirton.
C. 727 times speed up by @ace.
C++. Unbelievably fast by @Stefan.

The fastest solutions are now too fast to sensibly time.  I have therefore increased n to 10 and set iters = 100000 to compare the best ones. Under this measure the fastest are.

C. 7.5s by @ace.
C++. 1s by @Stefan.

My Machine The timings will be run on my machine. This is a standard ubuntu install on an AMD FX-8350 Eight-Core Processor.  This also means I need to be able to run your code.

Follow up posted As this competition was rather too easy to get a x100 speedup, I have posted a followup for those who want to exercise their speed guru expertise. See How Slow Is Python Really (Part II)?

Python2.7 + Numpy 1.8.1: 10.242 s

Fortran 90+: 0.029 s 0.003 s 0.022 s  0.010 s

Damn straight you lost your bet! Not a drop of parallelization here too, just straight Fortran 90+.

EDIT I've taken Guy Sirton's algorithm for permuting the array S (good find :D). I apparently also had the -g -traceback compiler flags active which were slowing this code down to about 0.017s. Currently, I am compiling this as

ifort -fast -o convolve convolve_random_arrays.f90

For those who don't have ifort, you can use

gfortran -O3 -ffast-math -o convolve convolve_random_arrays.f90

EDIT 2: The decrease in run-time is because I was doing something wrong previously and got an incorrect answer. Doing it the right way is apparently slower. I still can't believe that C++ is faster than mine, so I'm probably going to spend some time this week trying to tweak the crap out of this to speed it up.

EDIT 3: By simply changing the RNG section using one based on BSD's RNG (as suggested by Sampo Smolander) and eliminating the constant divide by m1, I cut the run-time to the same as the C++ answer by Guy Sirton. Using static arrays (as suggested by Sharpie) drops the run-time to under the C++ run-time! Yay Fortran! :D

EDIT 4 Apparently this doesn't compile (with gfortran) and run correctly (incorrect values) because the integers are overstepping their limits. I've made corrections to ensure it works, but this requires one to have either ifort 11+ or gfortran 4.7+ (or another compiler that allows iso_fortran_env and the F2008 int64 kind).

Here's the code:

program convolve_random_arrays
   use iso_fortran_env
   implicit none
   integer(int64), parameter :: a1 = 1103515245
   integer(int64), parameter :: c1 = 12345
   integer(int64), parameter :: m1 = 2147483648
   real, parameter ::    mi = 4.656612873e-10 ! 1/m1
   integer, parameter :: n = 6
   integer :: p, pmax, iters, i, nil(0:1), seed
   !integer, allocatable ::  F(:), S(:), FS(:)
   integer :: F(n), S(n+1), FS(2)

   !n = 6
   !allocate(F(n), S(n+1), FS(2))
   iters = 1000
   nil = 0

   !call init_random_seed()

   S = -1
   pmax = 2**(n+1)
   do p=1,pmax
      do i=1,iters
         F = rand_int_array(n)
         if(all(F==0)) then
            do while(all(F==0))
               F = rand_int_array(n)
            enddo
         endif

         FS = convolve(F,S)

         if(FS(1) == 0) then
            nil(0) = nil(0) + 1
            if(FS(2) == 0) nil(1) = nil(1) + 1
         endif

      enddo
      call permute(S)
   enddo

   print *,"first zero:",nil(0)
   print *," both zero:",nil(1)

 contains
   pure function convolve(x, h) result(y)
!x is the signal array
!h is the noise/impulse array
      integer, dimension(:), intent(in) :: x, h
      integer, dimension(abs(size(x)-size(h))+1) :: y
      integer:: i, j, r
      y(1) = dot_product(x,h(1:n-1))
      y(2) = dot_product(x,h(2:n  ))
   end function convolve

   pure subroutine permute(x)
      integer, intent(inout) :: x(:)
      integer :: i

      do i=1,size(x)
         if(x(i)==-1) then
            x(i) = 1
            return
         endif
         x(i) = -1
      enddo
   end subroutine permute

   function rand_int_array(i) result(x)
     integer, intent(in) :: i
     integer :: x(i), j
     real :: y
     do j=1,i
        y = bsd_rng()
        if(y <= 0.25) then
           x(j) = -1
        else if (y >= 0.75) then
           x(j) = +1
        else
           x(j) = 0
        endif
     enddo
   end function rand_int_array

   function bsd_rng() result(x)
      real :: x
      integer(int64) :: b=3141592653
      b = mod(a1*b + c1, m1)
      x = real(b)*mi
   end function bsd_rng
end program convolve_random_arrays

I suppose the question now is will you stop using slow-as-molasses Python and use fast-as-electrons-can-move Fortran ;).


m3ph1st0s's programming puzzle 4 (C/C++): “3-way swap” My last puzzle has generated some confusion and controversy so I decided to give up, for now, on those "replace one character"-type puzzles.

Hope this 4th puzzle will redeem myself after all the edits in puzzle 3 and will put your brains at work once more.

I've really put up all the effort to make this one as clear as possible and hope you will enjoy it!

So here it goes:

We start from a very short C program:

int main() {
   int a = 93;
   int b = 11;
   int c = 22528;

   // insert your code here

}

Your job will be to swap the values of the variables a,b,c like this: a <= b, b <= c, c <= a. To make it even more clear: new a = old b, new b = old c, new c = old a.

You are required to do this by inserting one single instruction in the line indicated by the comment in the code. To be clear once again, this line will contain only one semicolon (;) indicating the end of the lone instruction. After the execution of this program, a will contain 11, b will contain 22528, c will contain 93.
However, there are some conditions that need to be met. So we'll have 4 different puzzles with different cryteria.

4.1. Do it by using whatever you want. Just one statement. -> most creative solution wins this one.

4.2. Do it without using any comma (,). -> most creative wins

4.3. Do it without any comma and with no more than 4 letters (+any other characters). -> shortest code wins

4.4. Do it without any comma and with no more than 4 letters and no more than 4 digits (+any other characters). -> shortest code wins

To make sure you understood, here's some code that is valid under the condition required but does not solve the problem:

4.1:

I_hereby_call_my_beautiful_function(nice_argument), int q=w, who_the_hell_is(w)+1;

4.2:

one = single + assignment;

4.3:

int w=12345678;

4.4:

int w=1234;

P.S. In case you haven't already noticed, 4.4 is the tough one here (I hope :D).

For 4.4 (14 characters, 1 digit and 4 letters):

int main()
{
  int a = 93;
  int b = 11;
  int c = 22528;

  b<<=a=(c=a)/8;
}

VS2010 with /Wall didn't show any warnings, but I'm still a bit suspicious about using a twice in there (even though it's only modified once).


Change the Code, Change the Sequence: Cops This is a cops-and-robbers challenge. For the robbers thread, go here.

This challenge involves two OEIS sequences chosen by the cops -- S1, S2 -- and how well those sequences can be golfed and obfuscated.

The Cops' Challenge

Your challenge as a cop is to pick a freely available language, and two OEIS sequences. Then, write code A in that language that takes input n and produces S1(n). When that code is modified by a Levenshtein distance of X characters (with X no more than 0.5 * (length A)), and turned into code B in the same language, it must then produce S2(n). You must actually write this code B, but don't reveal it until your challenge is safe (see below).

The cops' submissions must include the language name, the full code A, the byte-count of A, the X value of how many changes to get to their secret B code, and the chosen S1 and S2 sequence numbers. You can choose whether each sequence is 0-indexed or 1-indexed, but please specify that in your submission.

To crack a particular submission, robbers must come up with a program C in the same language (and version) that produces S2(n) and is Y character changes away from A (with Y <= X). Robbers do not necessarily need to find the exact same B code that the cop (secretly) produced.

Winning and Scoring

If your cop answer has not been cracked within 7 days (168 hours), you may reveal your own B solution, at which point your answer is considered safe. As long as you don't reveal your solution, it may still be cracked by robbers, even if the 7 days have already passed. If your answer does get cracked, please indicate this in the header of your answer, along with a link to the corresponding robber's answer.

Cops win by having the uncracked submission with the shortest A. If tied, then the smallest X will be used as tie-breaker. If still tied, the earlier submission will win.

Further Rules

You must not use any built-ins for hashing, encryption, or random number generation (even if you seed the random number generator to a fixed value).
Either programs or functions are allowed, but the code must not be a snippet and you must not assume a REPL environment.
You may take input and give output in any convenient format. The input/output methods must be the same for both sequences.
The definitive calculator for the Levenshtein distance for this challenge is this one on Planet Calc.
In addition to being a CnR challenge, this is code-golf so all usual golfing rules apply.

Brain-Flak, 28 bytes, Distance of 4, A002817, A090809 Cracked
This answer uses 1-indexing
(({({}[()])}{}){({}[()])}{})

Try it online
For anyone interested there are 27475 valid Brain-Flak programs with Levenshtein distance 4 from this program and 27707 with distance 4 or less.  So a brute force solution would be feasible on a consumer grade computer.


Biggest square in a grid Challenge

Given a grid like this,

  1 2 3 4 5 6 7 8
1 . . . . . . . .
2 . # . . . # . .
3 . . . . . . . .
4 . . . . . . . .
5 . . . . . . . .
6 . . # . . . . .
7 . . . . . . . .
8 . . . . . . . .

write a piece of code that can determine the size of the largest square that does not include a '#'. (The answer to this input is 5x5 as the bottom right 5x5 grid is the biggest square possible).

The square must have sides parallel to the x and y axes.

As some small details: the original grid is always a square and its side length is given to you. The coordinates of the '#' symbols are also given to you.

Input Details

First line: N (1 <= N <= 1000), the side length of the square grid, and T (1 <= T <= 10,000) the number of '#' signs.

Next T Lines: The coordinates of each of the T #'s

Test Cases

Input #1:

8 3
2 2
2 6
6 3

Result #1: 5

================

Input #2:

8 4
1 1
1 8
8 1
8 8

Result #2: 6

================

Input #3:

5 1
3 3

Result #3: 2

This is a fastest-code problem, so the fastest code tested on the rextester compiler wins.

Have fun!

Node.js
Takes input as (w, l), where w is the width and l is an array of coordinates [x, y]. (This may be changed if the input format really is as strict as described.) Works in O(w²).

f = (w, l) => {
  var x, y,
      W = w * w,
      a = new Uint16Array(W),
      best = 0;

  l.forEach(([x, y]) => a[(y - 1) * w + x - 1] = 1);

  for(y = w; y < W; y += w) {
    for(x = y + 1; x < y + w; x++) {
      if(a[x]) {
        a[x] = 0;
      }
      else {
        best = Math.max(
          best,
          a[x] = Math.min(a[x - 1], a[x - w], a[x - w - 1]) + 1
        );
      }
    }
  }

  return best;
}

Try it online!