Make me a minimum magic sum Keeping this challenge short.

You are given 4 numbers: p1, p2, p3 and p4.

The magic sum of the numbers are defined as follows:

magic_sum = |p1 - p2| + |p2 - p3| + |p3 - p4| + |p4 - p1|

You are only allowed to change one of the above integer values (p1, p2, p3 or p4). You need to change the value such that the magic sum of the values attains its minimum value.

For example:

p1, p2, p3, p4 = 17, -6, 15, 33. The value of the magic sum is 78 in this case.

You can change the -6 here to 16, and the value of the magic sum will become 36, which is the minimum attainable value.

Do keep in mind that numbers can be positive or negative integers.

This is code-golf, so least bytes in code wins. Brownie points for using a Practical Language over a Recreational language. May the 4th be with you.

To reiterate:

Sample 1

Input 1

17 -6 15 33

Output 1

36

Explanation 1

  The -6 can be replaced with 16 and that gives us the minimum attainable
  magic sum possible.

Sample 2

Input 2

10 10 10 10

Output 2

0 or 2

either is acceptable

Explanation 2

  The minimum attainable magic sum is 0 since the minimum sum of 4 positive
  integers is 0. If a number has to be changed, then one of the 10's can be
  changed to a 9 and thus yielding the output 2.

Sample 3

Input 3

1 2 3 4

Output 3

4

Explanation 3

  The input by itself yields 6 as its magic sum. Changing the 4 to 1 and the minimum magic sum is attained, which is 4.

Python 2, 44 bytes

a,b,c,d=sorted(input())
print min(c-a,d-b)*2

Try it online!

Sorts the input as a,b,c,d, in ascending order, takes the smaller of c-a and d-b, and doubles it. Why does this work?

First, note that when we change an element to maximize to total cyclic sum of distances, it's optimal (or tied for optimal) to change it to equal a neighbor, such as 17, -6, 15, 33 -> 17, 17, 15, 33. That's because its new total distance to its left and right cyclic neighbors is at least the distance between those neighbors, so making these be equal is the best we can do.

Now, deleting one of two adjacent copies of a number gives the same cyclic sum of distances. In the example, this is 17, 15, 33, giving distances 2 + 18 + 16. So instead of replacing one of the four numbers, it's equivalent to just delete it leaving three numbers, and using the sum of their cyclic distances.

Notice that with 3 numbers, the largest distance is the sum of the two smaller ones. This is because if we sort the numbers to have a ≤ b ≤ c, then |a - c| = |a - b| + |b - c|. In other words, we travel between the largest and smallest number twice, using the medium number as a pit stop one of the times. So, the sum of the three distances is just twice the distance between the minimum and maximum, so (c-a)*2.

So, the question is which number we delete to get the smallest distance between the minimum and maximum of the three numbers that remains. Clearly we delete either the smallest or the largest of the numbers. Calling them a, b, c, d in sorted order, deleting a leaves d - b, and deleting d leaves c - a, and the final result is double whichever is smaller.


When does Santa enter the basement? (AOC Day 1) I'm reproducing the second part of the first day of Advent of Code, with permission from the creator.

Santa is trying to deliver presents in a large apartment building, but he can't find the right floor - the directions he got are a little confusing. He starts on the ground floor (floor 0) and then follows the instructions one character at a time.

An opening parenthesis, (, means he should go up one floor, and a closing parenthesis, ), means he should go down one floor.

The apartment building is very tall, and the basement is very deep; he will never find the top or bottom floors.

Given a set of instructions, find the position of the first character that causes him to enter the basement (floor -1).

As examples:

input ) causes him to enter the basement at character position 1.

input ()()) causes him to enter the basement at character position 5.

A long input is given here that should yield the solution 1797.

This is code golf, so the shortest solution wins!

Jelly, 8 7 bytes

O-*+\i-

Thanks to @Sp3000 for golfing off 1 byte!

Try it online!

How it works

O-*+\i-    Main link. Input: s (string)

O          Ordinal; replace each character with its code point.
           This maps "()" to [48, 49].
 -*        Apply x -> (-1) ** x.
           This maps [48, 49] to [1, -1].
   +\      Compute the cumulative sum, i.e., the list of partial sums.
     i-    Find the first index of -1.


Expand that Australian state There are 8 Australian states and territories, each with a 2 or 3 letter abbreviation:

ACT: Australian Capital Territory
NSW: New South Wales
NT: Northern Territory
QLD: Queensland
SA: South Australia
TAS: Tasmania
VIC: Victoria
WA: Western Australia

  Your task is to write a function/program which takes a valid Australian state abbreviation in upper case, and returns the correct full name (case-sensitive as above).

No extra whitespace permitted, other than a single trailing newline where this is an unavoidable side-effect of every program in that language.

For example:

f("TAS") => "Tasmania"

Standard code-golf rules (shortest code in bytes wins!) and loopholes apply.

Retina, 135 121 bytes

13 bytes golfed thanks to @Neil by using clever space insertion tactics, which inspired one more byte being golfed

AS
asmania
^W
Western
NT
NorthernT
T$
 Territory
A
Australia
aC
an Capital
IC
ictoria
LD
ueensland
SW
ew SWales
S
South

Try it online!

Note the trailing spaces on the fourth and the last lines.


Meta Length Logarithms Good Evening Golfers,

Your challenge, this evening, is logarithmic, and (as Abed would put it) "Meta"

Your goal is to write a program that takes an input from stdin or the command line, and returns the logarithm of that number, in the base of the length of your program in bytes.

So, if your program is 10 bytes, it must return the Log10 of the input number.

Rules:

Program must be longer then 1 character
Program must be able to accept floating point input in a form of your choice, or scientific format in a form of your choice with a minimum accuracy of 6 digits
Program must output to a minimum of 6 digits of accuracy in decimal or scientific format
Program must be entirely self contained, and must not access any files or network resources.

Your score in the natural logarithm of the amount of bytes in your source code.

Good luck.

APL 1.0986122886681098
3⍟⎕

⎕ Requests numerical screen input. Examples of use:
      3⍟⎕
      10
2.0959032742893844

      3⍟⎕
      1E1
2.0959032742893844

      3⍟⎕
      ○1
1.041978045992186

In the last example ○1 represents pi.


Find the Cell's Neighbours ...or Toroidal Moore Neighbourhoods

Given positive integers h, w and a non-negative  integer i, return all of the indices surrounding i.

You are to assume a matrix consisting of h rows of w elements, numbered from lowest, in the top left-hand corner, to highest, in the bottom right-hand corner, and return, in any reasonable format, a list of the indices that would surround the index, i. This matrix is a torus (an infinite map that wraps around each edge).

For example, inputs h=4 and w=4, would result in the matrix:

 0  1  2  3
 4  5  6  7
 8  9 10 11
12 13 14 15

but more specifically:

15 12 13 14 15 12
 3  0  1  2  3  0
 7  4  5  6  7  4
11  8  9 10 11  8
15 12 13 14 15 12
 3  0  1  2  3  0

so that if i was 0, you'd need to return 15, 12, 13, 3, 1, 7, 4, 5 (0-based).

Examples

0-based:

h   w   i       Expected result

4   4   5       0, 1, 2, 4, 6, 8, 9, 10
4   4   0       15, 12, 13, 3, 1, 7, 4, 5
4   5   1       15, 16, 17, 0, 2, 5, 6, 7
1   3   2       1, 2, 0, 1, 0, 1, 2, 0
1   1   0       0, 0, 0, 0, 0, 0, 0, 0

1-based:

h   w   i       Expected result

4   4   6       1, 2, 3, 5, 7, 9, 10, 11
4   4   1       16, 13, 14, 4, 2, 8, 5, 6
4   5   2       16, 17, 18, 1, 3, 6, 7, 8
1   3   3       2, 3, 1, 2, 1, 2, 3, 1
1   1   1       1, 1, 1, 1, 1, 1, 1, 1

Rules

Your answer may be 0 or 1-indexed, your choice, please specify.
You can assume that i < h * w (or i <= h * w for 1-indexed answers).
You can assume that i >= 0 (or i > 0 for 1-indexed answers).
The order of the returned values is not important as long as just the eight desired values are included.
Standard loopholes are forbidden.
This is code-golf so the shortest answer, in each language, wins!

Thanks to @Conor O'Brien for the more technical sounding title and @ngm for more test cases!

JavaScript (ES6), 75 bytes
Saved 2 bytes thanks to @KevinCruijssen
Expects a 0-based index.

(h,w,i)=>[...'12221000'].map((k,j,a)=>(i+w+~-k)%w+~~(i/w+h+~-a[j+2&7])%h*w)

Try it online!
The surrounding indices are returned in the following order:
$$\begin{matrix}5&4&3\\6&\cdot&2\\7&0&1\end{matrix}$$
How?
The indices \$I_{dx,dy}\$ of each surrounding cell at \$(x+dx,y+dy)\$ are given by:
$$\begin{align}I_{dx,dy}&=((x+dx) \bmod w)+w((y+dy) \bmod h)\\&=((N+dx) \bmod w)+w((\left\lfloor\frac{N}{w}\right\rfloor+dy) \bmod h)\end{align}$$
where \$N=wy+x\$ is the index of the target cell.
We walk through the list \$[1,2,2,2,1,0,0,0]\$ and subtract \$1\$ to get the value of \$dx\$, which gives:
$$[0,1,1,1,0,-1,-1,-1]$$
For the corresponding values of \$dy\$, we use the same list shifted by 2 positions, which gives:
$$[1,1,0,-1,-1,-1,0,1]$$


Go away! No-1's Here! I was playing around with some numbers and found a sequence that, of course, is on OEIS. It is A005823: Numbers whose ternary expansion contains no 1's. It goes:

  a(2n) = 3*a(n)+2

  a(2n+1) = 3*a(n+1)

  a(1) = 0

  a = 0,2,6,8,18,20,24,26,54....

I wrote a CJam program that generates the first n of these numbers by converting the index to binary, replacing the 1's with 2's, and converting from ternary to decimal.

I also noticed that any even number can be obtained by taking the sum of two numbers in the sequence (sometimes the number with itself).

The Challenge:

Given any non-negative even number as input, output the indices of two numbers in the sequence that sum to it. (Note that sometimes multiple pairs are possible.)

The Rules:

Specify if you're using 0- or 1-indexing.
If you're outputting as a string, put a delimiter between the two indices.
You are allowed to output as a complex number.
If you so desire, you can output every valid pair.
Code Golf: shortest answer wins

Test Cases

I use 0-indexing. Here I list every possible output for each input, but you only need to output one.

0:      [0 0]
2:      [1 0]
4:      [1 1]
6:      [2 0]
8:      [2 1]   [3 0]
10:     [3 1]
12:     [2 2]
14:     [3 2]
16:     [3 3]
18:     [4 0]
30:     [6 2]
32:     [6 3]   [7 2]
46:     [7 5]
50:     [7 6]
120:    [10 10]
338:    [19 18]
428:    [30 23] [31 22]
712:    [33 27] [35 25] [41 19] [43 17] [49 11] [51 9]  [57 3]  [59 1]
1016:   [38 37] [39 36] Thanks to @Luis Mendo for test case help.

Related: Is it within the Cantor set?

Husk, 21 14 13 bytes
-7 bytes, thanks to @Neil's JS answer
-1 byte inspired by betaveros's Parradoc answer
Uses 0-indexing
mḋTmMo±>ḋ2B3½

Try it online!
Explanation
            ½    Half the input
          B3     Convert to Base 3
   m             Map over the list
    Mo±>ḋ2       Function such that: 0 -> [0,0], 1 -> [0,1], 2 -> [1,1]
        ḋ2       Binary 2, [1,0]
    M            For each in that list
     o±>         check if the argument is greater than it
  T              Transpose
mḋ               Convert each from binary

Previous 21 byte Solution
First time I've seen a use for ».
mḋT»o%2+ȯ?´eḋε%3`-0B3

Try it online!
Longer, as I was dealing with carries


Recursive Binary Description Recursive Binary Description

Recently, I made my very first contribution to OEIS by extending and adding a b-file to sequence A049064. The sequence starts with 0, and then the next values are derived from giving a "binary description" of the last item.

For example, the second term would be 10, because there was one 0 in the first element. The third term would be 1110, because there was one 1 and one 0. The fourth would be 11110. because there are three (11 in binary!) 1s and one 0. Below is a breakdown of the fifth term to make this process clear:

> 11110
> 1111 0    (split into groups of each number)
> 4*1 1*0   (get count of each number in each group)
> 100*1 1*0 (convert counts to binary)
> 100110    (join each group back together)

And here's an example for going from the 6th to the 7th term:

> 1110010110
> 111 00 1 0 11 0
> 3*1 2*0 1*1 1*0 2*1 1*0
> 11*1 10*0 1*1 1*0 10*1 1*0
> 111100111010110

You can check out a reference programφ I made to calculate the terms.

Your Job

You need to create a program or function which takes in a number n via standard input or function arguments, and prints out the sequence from the 1st term to the (n+1)th term, separated by a newline. If you would like a look at the lower numbers, you may refer to the b-file from the OEIS page. However, your program/function should support 0 <= n <= 30, i.e. up to the 31st term. This is no small feat, as A049064(30) is over 140,000 digits longδ. If you would like to see what the 31st term should be, I've put it on Pastebin.

Example I/O

func(10)
0
10
1110
11110
100110
1110010110
111100111010110
100110011110111010110
1110010110010011011110111010110
1111001110101100111001011010011011110111010110
1001100111101110101100111100111010110111001011010011011110111010110

func(0)
0

func(3)
0
10
1110
11110

There is only one rule: No standard loopholes!

This is code-golf, so the lowest byte count wins.

φ - Gist can be found here, and an ideone demo is here.

δ - Just in case you were wondering, my estimates at the length of the 100th term put it at approximately 3.28x10250 characters long, which would be quite a lot for anyone to calculate.

CJam, 18 17 bytes

0{sN1$e`2af.b}ri*

Thanks to @MartinBüttner for golfing off one byte!

Try it online in the CJam interpreter.

How it works

0                 e# Push 0.
 {           }ri* e# Repeat int(input)) times:
  s               e#   Stringify the element on top of the stack.
                       EXAMPLE: [[[1 1] '1] [[1] '0]] -> "11110"
   N              e#   Push a linefeed.
    1$            e#   Copy the last stack.
      e`          e#   Perform run-length encoding.
                  e#   EXAMPLE: "100110" -> [[1 '1] [2 '0] [2 '1] [1 '0]]
        2a        e#   Push [2].
          f.b     e#   For each pair [x 'y], execute: [x 'y][2].b
                  e#   This pushes [x2b 'y], where b is base conversion.


Simulate rotating a board Introduction

You're playing a matching game, in which coins are inserted at the top and fall to the bottom (onto the top coin) due to gravity.

So this

O <- inserting this coin

OO O
OOOOO

will become this

O
OO O
OOOOO

Now imagine someone rotates the board clockwise. The following will happen:

1. The board is rotated

OOO
OO
O
OO
O

2. Coins fall down due to gravity

O
O
OO
OO
OOO

Your task

Your task is to simulate the rotation of the board by writing a program or a function. For the sake of simplicity we're only dealing with one kind of coin (it's not a too exciting matching game, is it…). You can assume that gravity is applied only after the rotation is complete. The board is rotated clockwise.

Input

The input is going to be a string, which contains 3 types of characters:

O (capital o) OR 0 (zero) - a coin (you decide which one your solution supports)
(space) - an empty field
\n (new line) - end of row

The input represents the state of the board. You can assume, the input is well formed and contains a valid state of the board (no coins are floating).
The input can be a function parameter, or can be read from the standard input or from a file.

Output

The output is the new state of the board after rotation. The output contains the same 3 types of characters as the input. The output can be returned from your function or can be written to the standard output or to a file.

Sample

Input1:

O
OO O
OOOOO

Output1:

O
O
OO
OO
OOO

Input2:

O O
O O

Output2:

OO
OO

You can use any language and the standard library of the chosen language. Shortest program in bytes wins.

GolfScript, 14 12 characters
' '-n%zip$n*

Input must be given on STDIN, the character for coins can be any non-whitespace characters. Try here. Thanks to Peter for pointing out a two character reduction.


Shortest script that gives the time passed since a Unix timestamp What you need to do to win this challenge is to write the shortest "timeago" script that outputs the number of decades, years, weeks, days, hours, minutes, and seconds between a given Unix timestamp and the time the script is run.
You must give the time difference in "lowest terms", e.g. 1 week not 7 days, 9 years not 0 decades 9 years. You also must use plural forms correctly, e.g. 1 day not 1 days.
Your script must be accurate to within plus or minus 1 second (so the exact second rounding method is unimportant).
Time Equivalency Table
1 decade = 10 years
1 year = 31536000 seconds (not technically correct but close enough)
1 week = 7 days
1 day = 24 hours
1 hour = 60 minutes
1 minute = 60 seconds

The output should be of the form
A decade(s) B year(s) C week(s) D day(s) E hour(s) F minute(s) G second(s)

where A...G are all non-negative integers and the s is only there for plurals.
Notes

The timestamp will always be a time from the past. It may be negative.
Input and output may be anything reasonable: stdin/stdout, function input and return value, etc.
You may not use any tools that already do this. i.e. if your language has a timesince(timestamp) function built in you may not use that function.

I have vastly edited this to make it clearer in hopes to assuage the somewhat silly battle between new users with unclear questions and old users who require perfection. It was not a terrible question (though now it may be too similar to this).
Given that enough time is passed since the last answer, I declare Three If By Whiskey with its 177 bytes Ruby implementation the winner of this context!

J , 165

;' '&,@":&.>@((#~([:*&>{."1))@((;:' decades years weeks days hours minutes seconds')(],.([}.~[:-1=])&.>)<"0@(_ 10 52 7 24 60 60&#:)@(-~([:".@}:[:2!:0'date +%s'"_))))

Can probably be golfed more. Uses a shell call to date for getting the current unix epoch time, since Unix epoch is unavailable in J.

Example run:

;' '&,@":&.>@((#~([:*&>{."1))@((;:' decades years weeks days hours minutes seconds')(],.([}.~[:-1=])&.>)<"0@(_ 10 52 7 24 60 60&#:)@(-~([:".@}:[:2!:0'date +%s'"_)))) 0
4 decades 4 years 41 weeks 3 days 12 hours 54 minutes 1 second


Identify the Kaomoji! Background
This is loosely based on the now closed Kaomoji question asked a few hours ago.
Kaomojis are sequences of characters designed to express a given emotion. In this code-challenge, you'll be writing a program that takes a Kaomoji as input, and must output the emotion expressed by the Kaomoji.
Input
A Kaomoji. In this challenge, there are 13 categories of emotions the kaomojis can express:

Joy
Love
Embarrassment
Sympathy
Dissatisfaction
Anger
Sadness
Pain
Fear
Indifference
Confusion
Doubt
Surprise

You will be given one kaomoji from any of these lists as input. This link contains all of the kaomojis in this challenge. Here's a pastebin version.
Output
Your program should output the emotion expressed by the kaomoji. You can express this as an integer (i.e., Joy = 1, Love = 2, etc), or output a string containing the emotion.
Scoring
Your score is (B+1)*exp(3W/(360-W)), where B is the number of bytes in your program, and W is the number of kaomojis that your program incorrectly categorizes. Lowest score wins!

JavaScript (ES6), Score 643
 656 651 646  642 bytes, no error
Returns an integer from 1 to 13.
s=>`qv%s!u.r0vPyqv*s"r'yqyu@y2r%{ }1u!v(u{y8|!ru;rur&z+z,w'z-{){{0x'r*z/{Py$t w#z,xFt,}qzr.{#s$t%vv6{@s&v z$x@{!{6v,sCr6s<v z.r s*w=w,r0u5s r){,y!s-s%v8t.xrqyWr7r?z#uBz9r&v#v5yBw+w"})vNw-u4sz)y"zEu/z r"}/rqw w\\t0|(r*rw(uAw&v {uYw#x wqz*|)v2u/|'v!r#sBs}0w&r2y&s r%r6w+}){"r2{-usqw'}C|/v$y={!r!x!t/rt>r1r"svuCy*{qr>v1x2r6x#{5{.wv8wGwqr!r:vJ|#r#u%uqst-}'r"z\`zqw uHy$sYr-z0w#|3{8x7vqz.w!|Ez$uvw!z.{t'w+{5x&|.xmrt"s,u"vuqwy{$t5u&s'wAv"vsTw#z%u*z0s r/w v#}+w'r9}0r0|AvxHv,r*}qw:x r3w}!u0v(w{qvv"y.rSr0w4yr#r.}qw"}%s"v#r!w!u/| tCs u`.replace(/[ -p]/g,c=>"q".repeat(c[C='charCodeAt']()-30))[C]([...s].map((c,i)=>s^=c[C]()<<i%5)|s%8788*3672%4051)%56

Try it online!
Or test all kaomojis.
How?
The input string is turned into an integer N with:
[...s].reduce((p, c, i) => p ^ c.charCodeAt() << i % 5, 0)

(using .map() instead of .reduce() in the golfed code)
Example for ٩(◕‿◕｡)۶:
 code | << |  shifted bit-mask
------+----+--------------------
 1641 |  0 |        11001101001
   40 |  1 |            101000.
 9685 |  2 |   10010111010101..
 8255 |  3 |  10000000111111...
 9685 |  4 | 10010111010101....
65377 |  0 |   1111111101100001
   41 |  1 |            101001.
 1782 |  2 |      11011110110..
------+----+--------------------
       XOR = 110010100100101110 = 207150

In the lookup string:

The emotions are encoded as 'q' to '}' (ASCII codes 113 to 125).
The characters ' ' to 'p' (ASCII codes 32 to 112) encode a run of consecutive 'q' (which, in addition to 'joy', also depicts an unused slot). The length of such a run is ord(c) - 30 (minimum = 2, maximum = 82).

We first expand the lookup string to 4048 characters by replacing /[ -p]/g with the runs of 'q' and then extract the relevant character with the following hash formula, which was found by brute-forcing some random values during a few minutes:
N % 8788 * 3672 % 4051

The final answer is the ASCII code of the character modulo 56.


Tell my friends to which "comma club" they belong Inspired by Silicon Valley's "three-comma club" scenes, like this one, in this challenge you'll be telling ten people the "comma club" to which they each belong.

If you're unfamiliar with the term "comma club," let me explain: you're in the one-comma club if the money you have is in the inclusive range $1,000.00 to $999,999.99; you're in the two-comma club if it's in the range $1,000,000.00 to $999,999,999.99; these "clubs" repeat through the three-comma club, since no individual on Earth (AFAIK) owns more than one trillion U.S. dollars (Japanese Yen would be a different story very quickly). So, the number of commas your bank account has, according to the notation standards most common in the United States and Great Britain, denotes the comma club to which you belong. The same "comma" rules apply for negative numbers (although you wouldn't want to be in the negative comma club): negative amounts in the inclusive range [-0.01, -999.99] belong to the zero-comma club, amounts in the range [-1000.00, -999999.99] belong to the one-comma club, etc.

The test cases

Friend    Amount
John      100000
Jamie     0.05
Kylie     1549001.10
Laura     999999999.99
Russ      986000000
Karla     1
Reid      99.99
Mark      999.99
Manson    1000.01
Lonnie    999999999999.00
Nelly     -123.45

The right answers:

John is in the 1-comma club.
Jamie is in the 0-comma club.
Kylie is in the 2-comma club.
Laura is in the 2-comma club.
Russ is in the 2-comma club.
Karla is in the 0-comma club.
Reid is in the 0-comma club.
Mark is in the 0-comma club.
Manson is in the 1-comma club.
Lonnie is in the 3-comma club.
Nelly is in the 0-comma club.

Whatever array setup you need to get a friends array and amounts array does not count towards your score. So for Python, the following code doesn't count:

f = ['John', 'Jamie', 'Kylie', 'Laura', 'Russ', 'Karla', 'Reid', 'Mark', 'Manson', 'Lonnie']
a = ['100000', '0.05', '1549001.10', '999999999.99', '986000000', '1', '99.99', '999.99', '1000.01', '999999999999.00']

Edit: Please see the revised test cases

I removed the actual string commas from the test cases to make things a bit more difficult, as opposed to just counting commas.

JavaScript (ES6), 80 bytes

a=>a.map(([s,n])=>s+` is in the ${n.toFixed(n<0?3:4).length/3-2|0}-comma club.`)

Takes an array of [friend, amount] arrays and returns an array of "friend is in the n-comma club." strings. Works by adding extra trailing zeros so that the length is 6-8 for the 0-comma club, 9-11 for the 1-comma club, 12-15 for the 2-comma club etc.

https://jsfiddle.net/cau40vmk/1/


Freehand red circles Over on http://meta.stackoverflow.com, we have a few memes of our own. One of them is Freehand Red Circles.
See this post:

So, the challenge is,
can you draw freehand red circles... with code?
Additional restrictions:

You will take an image as input, and you must output the image with freehand red circle added.
Must be predictable, i.e. same image input must result in same output. You can use randomness, but results have to be consistent for same input.
Output must be exactly the same image as input, except with circle (no other alterations).
The freehand red circle must look freehand (no perfect circles!), be red (obviously), and look generally like a circle (no random squiggly lines).

This is a popularity-contest, so the answer with the most upvotes at the beginning of March 2014 will win. There is no specific goal, other than "freehand red circles," so be as creative as possible so you get the most upvotes! (To be as unbiased as possible, I will upvote any answer that follows the rules.)

C + GD library
Instead of just drawing circles any old where, I thought it would be fun to find something red in the picture and draw a circle around that.
Here are some examples of the results obtained with a few photos from Wikimedia Commons:

And here's the code. It's a bit messy, but not too difficult to follow, I hope:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gd.h>

#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))

/* Used for image segmentation */
int floodfill(int *tmp, int i, int w, int id) {
  int np=1;
  tmp[i]=id;
  if (tmp[i-w-1]<0) np+=floodfill(tmp,i-w-1,w,id);
  if (tmp[i-w]<0) np+=floodfill(tmp,i-w,w,id);
  if (tmp[i-w+1]<0) np+=floodfill(tmp,i-w+1,w,id);
  if (tmp[i-1]<0) np+=floodfill(tmp,i-1,w,id);
  if (tmp[i+1]<0) np+=floodfill(tmp,i+1,w,id);
  if (tmp[i+w-1]<0) np+=floodfill(tmp,i+w-1,w,id);
  if (tmp[i+w]<0) np+=floodfill(tmp,i+w,w,id);
  if (tmp[i+w+1]<0) np+=floodfill(tmp,i+w+1,w,id);
  return np;
}

int main(int argv, char *argc[]) {
  FILE          *infile,*outfile;
  gdImagePtr    img;
  int           *t, *tmp;
  int           w,h,x,y,r,g,b;
  int           c,redness,rgb;
  int           i,np,max,min,thresh;
  int           xt,yt,n;
  int           areaID,size,maxID;
  double        xmin,ymin,xmax,ymax,rad,r0,th;
  gdPoint       v[33];

  /* Check command line and open source JPEG file */
  if (argv!=3) return printf("Usage: %s <in.jpg> <out.jpg>\n",argc[0]);
  if (!(infile=fopen(argc[1],"r"))) return printf("Can't open <%s>\n",argc[1]);
  if (!(img=gdImageCreateFromJpeg(infile))) return printf("Bad JPEG: <%s>\n",argc[1]);
  fclose(infile);

  /* Extract red pixels and auto-threshold */
  w=img->sx;
  h=img->sy;
  np=w*h;
  t=tmp=calloc(np,sizeof(int));
  for (max=0,min=255,y=1;y<h-1;y++) {
    for (x=1;x<w-1;x++) {
      rgb=gdImageGetTrueColorPixel(img,x,y);
      r = (rgb&0xff0000)>>16;
      g = (rgb&0xff00)>>8;
      b = rgb&0xff;
      redness = max(0,r-(max(g,b)+abs(g-b)));
      if (redness>max) max=redness;
      if (redness<min) min=redness;
      *t++ = redness;
    }
    t += 2;
  }
  thresh = (max+min)/2;
  for (t=tmp,i=0;i<np;i++,t++) *t=((*t>thresh)?-1:0);

  /* Label each area detected */
  areaID=1;
  maxID=0;
  max=-1;
  for (t=tmp,i=0;i<np;i++,t++) {
    if (*t<0) {
      size=floodfill(tmp,i,w,areaID);
      if (size>max) {
        max = size;
        maxID = areaID;
      }
      areaID++;
    }
  }

  /* Calculate centre coordinates and area */
  if (max>0) {
    xt=yt=n=xmax=ymax=0;
    xmin=w; ymin=h;
    for (t=tmp,y=0;y<h;y++) {
      for (x=0;x<w;x++) {
        if (*t++==maxID) {
          xt+=x;
          yt+=y;
          n++;
          if (x<xmin) xmin=x;
          if (y<ymin) ymin=y;
          if (x>xmax) xmax=x;
          if (y>ymax) ymax=y;
        }
      }
    }
    x = xt/(2*n) + (xmax+xmin)/4;
    y = yt/(2*n) + (ymax+ymin)/4;

    r0 = max(20,min(min(w,h),max(xmax-xmin,ymax-ymin))/2);
  }
  /* Default circle if nothing found */
  else {
    x=w/2; y=h/2; r0=min(w,h)/3;
  }

  /* Draw a red circle */
  for (th=4.0,i=0;i<33;i++) {
    rad = r0 * (1.2 + (" ,<MYZVSB>@EJIOSWZfgb^bbfgeZTOI@2"[i]-87)/160.0);
    v[i].x = x + rad * sin(th);
    v[i].y = y + rad * cos(th);
    th += 0.22;
  }
  gdImageSetThickness(img,7);
  c = gdImageColorAllocate(img,255,0,0);
  gdImageOpenPolygon(img,v,33,c);

  /* Output results to file */
  printf("Saving...\n");
  if (!(outfile=fopen(argc[2],"w"))) {
    return printf("Can't open <%s> for writing\n",argc[2]);
  }
  gdImageJpeg(img,outfile,85);
  fclose(outfile);
  gdImageDestroy(img);
  printf("Finished\n");
  return 0;
}

Note: Markdown messed up my link in the comments, so I'll just point out that the code uses segmentation to identify all the areas of red in the picture, and then draws a circle around the largest of these. For example, this image:

produces the following output:


Write a function that reduces compositions of linear operators You are given two functions \$g(x)\$ and \$h(x)\$, each of which takes an integer \$x\$ and returns the number \$ax + b\$ (where \$a\$ and \$b\$ are integers defined in the function).
Your task is to write a function \$f(g, h)\$ that takes these two functions, and returns a function \$k(x) = g(h(x))\$, but where the procedure of \$k(x)\$ is also simply of the form \$ax + b\$.
For example, given \$g(x) = 2x + 3\$ and \$h(x) = 3x + 4\$, you would need to return \$k(x) = 6x + 11\$, and not \$k(x) = 2(3x + 4) + 3\$.

GolfScript, 41 40 23 19 characters
{2,0+%/-{@*+}++}:k;

Thanks to Peter Taylor for pointing out this solution. Accepts two function bodies as arguments.
The following examples show how to use function k:
# As function
{2*3+} {3*4+} k         # => {11 6 @*+}

# Apply to value
5 {2*3+} {3*4+} k ~     # => 41

If one wants to retain the original output format, the following 22 character solution is possible:
{2,0+%/-{*}+\+{+}+}:k;

{2*3+} {3*4+} k         # => {6 * 11 +}

Explanation of the code:
{                       # on stack are functions g h
  2,                    # build array [0 1] -> g h [0 1]
  0+                    # append 0 -> g h [0 1 0]
  %                     # apply function h to each element -> g [h(0) h(1) h(0)]
  /                     # apply function g to each element
                        # and break up the array -> g(h(0)) g(h(1)) g(h(0))
  -                     # subtract last two -> g(h(0)) g(h(1))-g(h(0))
  {@*+}++               # append function body to these values
}:k;                    # save function to variable k


Convert arbitrary roman numeral input to integer output The usual rules: no external resources, or the like.  Input will be a positive integer in valid Roman numeral format less than 10 thousand, say.

Use all the Roman numeral characters:

I =  1
V =  5
X =  10
L =  50
C =  100
D =  500
M =  1,000

Respect subtractive notation (copied from the Wikipedia page):

the numeral I can be placed before V and X to make 4 units (IV) and 9 units (IX) respectively
X can be placed before L and C to make 40 (XL) and 90 (XC) respectively
C can be placed before D and M to make 400 (CD) and 900 (CM) according to the same pattern[5]

Mathematica, 33 chars
FromDigits[InputString[],"Roman"]


Parse a Python string literal The challenge is to parse a string like Python does and print the contents of the string.

Input (command-line argument or stdin): a string literal (e.g. "hello") (or multiple literals, see string literal concatenation below)
Output (stdout): the contents of the string (e.g. hello)

Rules for parsing the string:

A string literal is enclosed in matching pairs of single quotes ('a'), double quotes ("a"),  triple single quotes ('''a''') or triple double quotes ("""a""").  The first reoccurrence of the type of quotes that opened the string ends the string.
Backslash escapes: \' within a string becomes ', \" becomes " and \\ becomes \.  You do not need to implement any other backslash escapes.  A backslash that is not part of an escape sequence stays a backslash.
String literal concatenation: The contents of adjacent string literals are concatenated. For example, "hello" 'world' becomes helloworld.
The input may contain spaces that are not part of any literal.
You do not need to support any other kind of whitespace, neither within nor outside literals.

Additional rules:

eval, exec and similar stuff is not allowed for parsing the literal or parts of it.
You may assume that the input is valid.
You may assume a maximum input length of 1023 characters.

Examples:

"hello"  ' world' -> hello world
"""\"""'\\\A""" -> """'\\A
( '''"""'''"""'''""" ) (without parentheses, but with spaces) -> """'''

Shortest code wins.

Perl, 54 characters

#!/usr/bin/perl -p
s/ |("""|'''|"|')((\\?.)*?)\1/$2/g;s/\\(["'\\])/$1/g

Just as I was posting this, I noticed that it's almost identical to Jan Dvorak's Ruby solution. I'm a little put out by how similar it is, in fact, but I'm going to say "Great minds think alike" and let it go at that.

This program highlights a weird corner case in counting characters in Perl scripts: By my reading, the presence of single-quotes in the script means that I need to count the -p option as two characters towards my total. Typically, when computing Perl script sizes, the initial dash character on the options is considered to be free, on the justification that it can be bundled with the -e that introduces the program proper ... but then you also have to account for any extra escapes you need to enter the script on the command-line. The single-quotes require lots of escaping, so to avoid that penalty I have to count it as a script run from a file, and therefore I get the #!/usr/bin/perl for free, but not any option characters. It's a little confusing.


Play Wythoff's Nim perfectly Your goal is to write a perfect player for the game of Wythoff's Nim.

Rules of Wythoff's Nim

Wythoff's Nim is a deterministic two-player game played with two piles of identical counters. Players alternate turns, in which they do one of these:

Remove one or more counters from the first pile
Remove one or more counters from the second pile
Remove an equal number of counters (one or more), from both the first pile and the second pile.

Of course, piles can't go negative, but they can to 0. Whichever player removes the last counter overall wins the game.

For the more geometrically-minded, here is an equivalent formulation of the game that you can play on this applet. A single queen starts on some square of a quarter-infinite chessboard whose corner is in the bottom-left. Players alternate moving the queen, which moves like a chess queen but restricted to three directions:

Down
Left
Diagonally down and left

Whoever moves the queen to the corner wins.

Associating the queen's coordinates (with corner (0,0)) to the sizes of the respective piles, it's easy to see both games are the same.

Perfect play

(You can skip this if familiar with the notions of perfect play and winning moves.)

Since Wythoff's Nim is a finite and deterministic game, it has a notion of perfect play. A perfect player is a strategy that will always win from a theoretically won position, meaning a position in which there exists a strategy that guarantees a win.

To be a winning strategy, it suffices to move to always move to a theoretical winning position for the player who just moved, and thus the player not going next. The first of these winning positions (also called cold positions) are (0,0), (1,2), (2,1), (3,5), (5,3). See the Wikipedia article for an explanation of an algorithm to find a winning strategy for Wythoff's Nim, as well as a formula to generate win positions.

Program requirements

Write a program or function takes a position as input and outputs a winning move in the form of the position after that move. Fewest bytes wins.

If no winning move exists, i.e., the position is a theoretical loss, your program should indicate so and forfeit.

Your program must run within a reasonable amount of time. So, an exponential recursive game tree search will not suffice. If you want to precompute and hard-code a strategy, that's fine.

Input

A pair (i,j) of non-negative numbers representing pile sizes, each at most 99. This can be two numbers, a tuple, a list, or whatever container you prefer.

Output

Print or output the position after your move, again as two numbers or a container thereof. This must be a legal move to a winning position. If there's multiple such moves, any one is fine, but only one.

If there's no winning move, you must indicate this in the output. Any output like False, None, 0, or (-1,-1) will do, as long as it's not a legal position, and is the same for every losing input.

Example runs

f(5,0)   = (0,0)
f(2,2)   = (1,2)   # Or (2,1) or (0,0)
f(1,2)   = False
f(13,9)  = (13,8)  # Or (10,6)
f(10,6)  = False
f(5,10)  = (5,3)
f(25,30) = (8,13)

Haskell, 167 165 characters
c p=o p:c(o p:p)
o p=[(a,b)|a<-[0..],b<-[0..a],(a,b)?p==[]]!!0
(a,b)?p=[y|y@(c,d)<-p,c==a||c==b||d==b||a+d==b+c]
f x@(a,b)|a<b=f(b,a)|x?c[]!!0==x=(0,-1)|1>0=x?c[]!!0

The algorithm is inefficient, but it still runs within a second (though not in the interactive console) for inputs < 100.
Explanation:
c p=o p:c(o p:p)

The list of cold positions given a set of previous cold positions is one cold position followed by the list of cold positions given this position and the previous ones (Inefficiency: this position is generated twice)
o p=[(a,b)|a<-[0..],b<-[0..a],(a,b)?p==[]]!!0

One cold position is the first pair such that there are no cold positions reachable from that pair (Inefficiency: we should search from the previous pair instead)
(a,b)?p=[y|y@(c,d)<-p,c==a||c==b||d==b||a+d==b+c]

Positions reachable from a pair are those such that their first elements match, their second elements match, their difference matches, or the smaller heap before removal is the larger heap after removal.
f x@(a,b)|a<b=f(b,a)
         |x?c[]!!0==x=(0,-1)
         |1>0=x?c[]!!0

(main method) If the heaps are in the wrong order, swap them. Else, if the first cold position reachable from a position is the position itself, indicate failure (ideally, one would return Maybe (Int,Int) instead). Else return that cold position (Inefficiency: said pair is looked up twice. Worse, the list of cold positions is generated twice)


Tips for golfing in Underload Underload is a stack-based semi-functional tarpit created by ais523. I've recently been trying to golf in it, as it's a surprisingly elegant language.

What tips do you have for golfing in Underload? (One tip per answer)

"Dirty" Decrement

The functionally-pure way to decrement a Church numeral is to use the lambda calculus predecessor function:

\n.n(\p.\z.z($(pT))(pT))(\z.z0[whatever you define the predecessor of 0 to be])

Where 0 = \x.\y.y, T = \x.\y.x, and $ is the successor.

Rewritten in Underload, this is 28 bytes:

(!())~(!())~(!:(:)~*(*)*~)~^!

This is alright, but we can exploit some of Underload's useful properties, namely that :! and ()* do are no-ops. This means that, for a number n, :ⁿ!!()()*ⁿ (where cⁿ is c repeated n times) yields n-1. For example doing this for the Church numeral 3 yields this:

:::!!()()***

Removing no-op pairs, we get:

:*

Which is 2.

So this is the new and shorter predecessor operation:

:(:)~^(!!()())*~(*)~^*

This is 7 bytes shorter.


D&D Skill Challenges In Dungeons & Dragons, almost everything is decided by rolling a die. Typically, if the roll is greater than or equal to a specified value, your attempt at doing whatever you wanted to do succeeds, and fails otherwise. Most commonly, a 20-sided die (aka d20) is used to roll.

Other times, the skill challenge system is used. It is similar to the simple system described above, but success is determined by whether or not the player(s) succeed individual rolls a certain number of times before failing a certain number of times. For example, the player(s) may be trying to pick multiple locks on a door with a limited number of lockpicks. Individual successful rolls represent successfully picking one of the locks, and individual failing rolls represent breaking a lockpick. Overall success would mean successfully picking all of the locks before breaking all of the lockpicks.

Furthermore, certain rolls can be critical rolls. On a d20, rolling a 1 is a critical failure, resulting in immediately failing the entire challenge (in the above example, the player(s) might accidentally alert a guard). Rolling a 20 is a critical success, resulting in immediately succeeding the entire challenge (in the above example, the player(s) might find a set of keys to the locks, removing the need to pick them). In the case of a critical roll, the challenge is immediately over and the outcome decided, regardless of the previous number of successes and failures.

In this challenge, you will be given a difficulty, the number of successes needed, and the number of failures at which the challenge is failed. You must simulate a player attempting the challenge, and output the result.

Input

3 integers, representing the value that must be met or exceeded to succeed at an individual roll, the number of successes needed to succeed at the challenge, and the number of failures at which the challenge is failed. The order and format of the inputs does not matter, as long as you specify what order you will be using. The difficulty will be between 1 and 20, inclusive, and the number of successes and failures will both be between 1 and 100, inclusive.

Output

The results of each of the d20 rolls (integers, in order), and the overall result of the challenge (a truthy/falsey value). The format does not matter, as long as the individual results are in order, the overall result either comes before or after all of the individual rolls (you can't output the overall result in the middle of the rolls, for example), and you specify what output format you use and use it consistently.

Examples (values in parentheses are for explanation and need not be included):

Input:

12 5 3 (difficulty successes failures)

Output:

15 (success, 1-0)
10 (failure, 1-1)
5  (failure, 1-2)
16 (success, 2-2)
12 (success, 3-2)
15 (success, 4-2)
19 (success, 5-2)
True (overall success)

Input:

15 2 3 (difficulty failures successes)

Output:

0  (overall failure)
15 (success, 1-0)
12 (failure, 1-1)
13 (failure, 1-2)

Input:

5 5 10 (successes failures difficulty)

Output:

11 (success, 1-0)
5  (failure, 1-1)
20 (critical success)
1  (overall success)

Input:

3 10 3 (failures difficulty successes)

Output:

12 (success, 1-0)
11 (success, 2-0)
1  (critical failure)
False (overall failure)

Rules

This is code-golf, so shortest code in bytes wins
You must randomly choose an integer value between 1 and 20 (inclusive) for each roll. Each value should have an equal probability of being chosen (or as close to equal as possible).

Python, 134 bytes
Thanks Pietu1998 for the bytes saved
from random import*
def g(a,b,c):
 s,z=[],[c,b]
 while z[0]*z[1]:d=randint(1,20);z[a<d]-=[1,z[a<d]][d in[1,20]];s+=[d]
 return[z[0]]+s

Pretty simple, can probably be golfed a bit more, but we needed something to kick this off. Try it online.


Create a black window with as little memory as possible Today I installed MonoGame and ran the test application, which creates a basic colored window. I was surprised to see that the process was using 32.2 MiB of memory, and I thought it could be improved.

Your challenge is to write a program that creates a 640 by 480 window displaying only black pixels. Whatever program uses the least physical memory to do so wins. You may use any operating system released after the year 2000.

C, 96KiB
Never seen restricted-memory but i guess code length doesn't matter here. RAM usage was taken from gnome-system-monitor (i hope it's accurate).
#include <stdlib.h>
#include <stdio.h>

#include <xcb/xcb.h>

int main ()
{
  xcb_connection_t    *c;
  xcb_screen_t        *screen;
  xcb_drawable_t       win;
  xcb_generic_event_t *e;
  uint32_t             values[2];

  char string[] = " ";

  c = xcb_connect (NULL, NULL);
  screen = xcb_setup_roots_iterator (xcb_get_setup (c)).data;
  win = screen->root;

  win = xcb_generate_id(c);
  values[0] = screen->black_pixel;
  values[1] = XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_KEY_PRESS;
  xcb_create_window (c,XCB_COPY_FROM_PARENT,win,screen->root,
  0, 0,640,480,10,XCB_WINDOW_CLASS_INPUT_OUTPUT,screen->root_visual,XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK, values);

  xcb_map_window (c, win);
  xcb_flush (c);

  while ((e = xcb_wait_for_event (c))) {
    switch (e->response_type & ~0x80) {
    case XCB_EXPOSE:
      xcb_flush (c);
      break;
    }
    free (e);
  }
  return 0;
}

This code works on pretty much every linux with a running xserver. To compile add -lxcb for the xcb libs.


Am I a Sophie Germain prime? A Sophie Germain Prime is a prime number P such that 2P+1 is prime as well. Given a prime number as input, your task is to determine whether it is a Sophie Germain Prime.

Standard Input/Output rules and Default Loopholes apply.
This is a decision-problem, so standard rules for this tag apply (returning two distinct and consistent values for each case, e.g: True/False).

Test Cases

Truthy (Sophie Germain primes)

These are the first few of them (OEIS A005384):

2, 3, 5, 11, 23, 29, 41, 53, 83, 89, 113

Falsy

7, 13, 17, 31, 37, 43, 47

Please note that answers with explanations are encouraged!

It's code-golf, hence the shortest code in bytes in every language wins!

x86-64 Machine Code, 24 bytes
01 FF FF C7 6A 01 59 89 F8 FF C1 99 F7 F9 85 D2 75 F5 39 F9 0F 94 C0 C3

The above code defines a function that takes a single parameter (the input value, known to be a prime) in EDI (following the System V AMD64 calling convention used on Gnu/Unix), and returns a Boolean result in AL (1 if the input is a Sophie Germain prime, 0 otherwise).
The implementation is very similar to the solution to this challenge, since all we really have to do is determine whether a number is prime using as little code as possible, which means an inefficient iterative loop.
Basically, we take the input and immediately transform it into 2 × input + 1. Then, starting with a counter set to 2, we loop through and check to see if the counter is a factor. The counter is incremented each time through the loop. As soon as a factor is found, the loop ends and that factor is compared against 2 × input + 1. If the factor is equal to the test value, then that means we didn't find any smaller factors, and therefore the number must be prime. And since we have thus confirmed that 2 × input + 1 is prime, this means that input must be a Sophie Germain prime.
Ungolfed assembly language mnemonics:
IsSophieGermainPrime:
   add   edi, edi            ; input *= 2
   inc   edi                 ; input += 1
   push  1
   pop   rcx                 ; counter = 1

.CheckDivisibility:
   inc   ecx                 ; increment counter
   mov   eax, edi            ; EAX = input (needs to be in EAX for IDIV; will be clobbered)
   cdq                       ; sign-extend EAX into EDX:EAX
   idiv  ecx                 ; EDX:EAX / counter
   test  edx, edx            ; check the remainder to see if divided evenly
   jnz   .CheckDivisibility  ; keep looping if not divisible by this one

   cmp   ecx, edi            ; compare counter to input
   sete  al                  ; set true if first found factor is itself;
   ret                       ;          otherwise, set false


Is the number binary-heavy? An integer is binary-heavy if its binary representation contains more 1s than 0s while ignoring leading zeroes. For example 1 is binary-heavy, as its binary representation is simply 1, however 4 is not binary heavy, as its binary representation is 100. In the event of a tie (for example 2, with a binary representation of 10), the number is not considered binary-heavy.

Given a positive integer as input, output a truthy value if it is binary-heavy, and a falsey value if it is not.

Testcases

Format: input -> binary -> output

1          ->                                1 -> True
2          ->                               10 -> False
4          ->                              100 -> False
5          ->                              101 -> True
60         ->                           111100 -> True
316        ->                        100111100 -> True
632        ->                       1001111000 -> False
2147483647 ->  1111111111111111111111111111111 -> True
2147483648 -> 10000000000000000000000000000000 -> False

Scoring

This is code-golf so fewest bytes in each language wins

x86 Machine Code, 15 14 bytes

F3 0F B8 C1 0F BD D1 03 C0 42 2B D0 D6 C3

This is a function using Microsoft's __fastcall calling convention (first and only parameter in ecx, return value in eax, callee is allowed to clobber edx), though it can trivially be modified for other calling conventions that pass arguments in registers.

It returns 255 as truthy, and 0 as falsey.

It uses the undocumented (but widely supported) opcode salc.

Disassembly below:

;F3 0F B8 C1
  popcnt eax, ecx ; Sets eax to number of bits set in ecx

;0F BD D1
  bsr edx, ecx    ; Sets edx to the index of the leading 1 bit of ecx

;03 C0
  add eax, eax

;42
  inc edx

;2B D0
  sub edx, eax

  ; At this point,
  ;   edx = (index of highest bit set) + 1 - 2*(number of bits set)
  ; This is negative if and only if ecx was binary-heavy.

;D6
  salc           ; undocumented opcode. Sets al to 255 if carry flag
                 ; is set, and to 0 otherwise.

;C3
  ret

Try it online!

Thanks to Peter Cordes for suggesting replacing lzcnt with bsr.


Display 0 - 1000 - 0 each on a separate line I've tried this question on two forums and have been told this is the best place for this type of question. I'm trying to print from 0 to 1000 then back to 0 again (and all numbers in-between), printing 1000 only once. Also, each number must be on a separate line using vanilla PHP.
My current code is 60 characters long. Is there a way to do the same thing but in less characters?
PHP, 60 bytes

echo implode("<p>",array_merge(range(0,999),range(1000,0)));

Try it online!

PHP, 38 bytes

for(;$i-=1|$x|=$i/1001;)echo~$i,"<p>";

Try it online!
A one-byte improvement by JoKing. The idea is that by decrementing $i instead of incrementing it, we can save on the minus in the 1|-$x construction by having $x become -1 instead of 1 as a signal. This is achieved by using $i/1001, which is 0 if $i>-1001 and -1 otherwise. This would break even if not for the fact we can now use ~$i instead of $i-1.
PHP, 39 bytes

for(;$i+=1|-$x|=$i>1e3;)echo$i-1,"<p>";

Try it online!
In collaboration with primo on the code.golf discord.
The idea is to have a signal variable $x that is zero until $i hits 1000 then is 1 afterwards. We use the bitwise construction 1|-$x which is a shorter version of $x ? -1 : 1 to select whether to go upwards or downwards.


Shortest way to get an EOF Error It's simple, simply output text to STDERR containing the string EOF.

Input/Output

Your input will be none; however, you should output the message to STDERR.

Rules

Since this is code-golf, the shortest answer wins.
No standard loopholes please.
Any method approved by Standard I/O is allowed.
Your code may not contain the "EOF" that you will output as-is in your error.
Outputting "EOI" is technically allowed, because the input can also be considered as a separate file.

APL (Dyalog Unicode) 17.0, 0 bytes

Dyalog 17.0 expects programs to terminate themselves cleanly and will throw an EOF INTERRUPT (and exit with a code 2) if they don't: Try it online!

In contrast, here is the minimal program which does terminate itself cleanly, causing no error (and code 0 upon exit): Try it online!


Average Length of Google I was messing around with Pyth's url request feature, and noticed that google always gave a response with a slightly different length for me, usually ~10500 characters.
So your task in this challenge is to print out the average length of the html response from http://google.com.
Specs

You will take an input n which is the number of requests to make.
For each request, you will make an HTTP get request.
You will count the response body (the html text), not the headers.
Output the arithmetic mean of the lengths of the responses.
You can only access the url http://google.com, not any other.
This is code-golf, so shortest code in bytes wins!

Sample output for input 10: 10560.1
(I used Python's urllib for that)
P.S: does anyone know why google does this?

Bash + system utilities, 56 53 49 48 bytes

Update: saved 4 bytes thanks to Digital Trauma and 1 byte more thanks to Dennis

curl -L `yes google.com|sed $1q`|wc|dc -e1k?$1/p

In my original answer I was using yes in combination with xargs to emulate a for loop. But curl can accept as input a list of URLs, so only the output from yes is actually needed.

When curl accesses google.com, it receives a 302 redirection page that has the new URL in the body section, so the -L option is needed to follow it.

Run example: answer is printed to STDOUT, I redirect STDERR just for clarity

me@LCARS:/PPCG$ ./google_length.sh "8" 2> /dev/null
10583.2

Explanation: (of the initially submitted code)

yes google.com|     # repeatedly output a line containing the string "google.com"
sed $1q|            # print the first $1 lines only (shorter than head -$1)
xargs curl -sL|     # xargs reads the input lines and executes "curl -sL" with the
                    #current input line as an additional argument.
wc -m|              # count the number of characters
dc -e1k?$1/p        # dc script: set precision to 1, read input, push $1 and divide

Edit: I replaced wc -m with wc, because even if without arguments it prints 2 more statistics than the one I wanted, the same dc script following this output still works, because the count we want is, happily, placed on top of the stack during parsing.


Find the submatrix with the smallest mean You're given a n-by-m matrix of integers, where n,m > 3. Your task is to find the 3-by-3 sub-matrix that has the lowest mean, and output this value.

Rules and clarifications:

The integers will be non-negative
Optional input and output format
The output must be accurate up to at least 2 decimal poins (if it's non-integer)
The submatrices must be made up of consecutive rows and columns

Test cases:

35    1    6   26   19   24
 3   32    7   21   23   25
31    9    2   22   27   20
 8   28   33   17   10   15
30    5   34   12   14   16
 4   36   29   13   18   11

Minimum mean: 14

100    65     2    93
  3    11    31    89
 93    15    95    65
 77    96    72    34

Minimum mean: 46.111

1   1   1   1   1   1   1   1
1   1   1   1   1   1   1   1
1   1   1   1   1   1   1   1
1   1   1   1   1   1   1   1

Minimum mean: 1

4   0   0   5   4
4   5   8   4   1
1   4   9   3   1
0   0   1   3   9
0   3   2   4   8
4   9   5   9   6
1   8   7   2   7
2   1   3   7   9

Minimum mean: 2.2222

This is code-golf so the shortest code in each language wins. I encourage people to post answers in languages that are already used, even if it's not shorter than the first one.

Octave, 30 bytes
@(A)min(mean(im2col(A,[3,3])))

Try it online!


Find the Words on the Grid! Write a program or function that extracts a word from a wordsearch using its start and end coordinates.

The Input

Your program or function should accept three parameters: the start coordinate, the end coordinate, and a wordsearch from which to extract the word.

The start coordinate can be taken in any format.

It will always be an integer
The bottom left of the grid is (0, 0)
You will not be provided with coordinates that go outside the bounds of the grid
You will not be provided with coordinates that are not vertical, horizontal, or perfectly diagonal to each other, such as (7, 0) and (0, 6).

The end coordinate will be taken in the same format as the start coordinate
The wordsearch will be a string, or your language's closest equivalent

It will be a grid of characters separated by a single space, with each row on a newline. It can have any height or width - which can be different - but it will always be a rectangle. For example:

A G O A T C A T
E A T M E N O W
W O R D S E A R
A K L L K J H G
N P L F G H F D
A S P L K J H G
O P I L F G H J
T F A S E J K L

J H P B L D J L T
F J L N F N P W H
W P R D T F J R Q
J L L L L J H H W
N P L F H H F D S
J T P L L J H H K
P P J L F H H J N
L F J T F J L L O

The Output

You should output a string, or your language's closest equivalent. As no wordsearches in real life ever ask to find a single letter, you may output nothing if the coordinates are the same.

Examples and Test Cases

First Grid Above:
(0, 4) and (4, 0) --> "APPLE"

(4, 0) and (0, 4) --> "ELPPA"

(1, 7) and (4, 7) --> "GOAT"

(0, 5) and (7, 5) --> "WORDSEAR"

(0, 6) and (5, 6) --> "EATMEN"

(0, 6) and (0, 7) --> "EA"

(7, 0) and (0, 7) --> "LHJGLRAA"

----------

Second Grid Above:
(1, 0) and (8, 7) --> "FJLHJJWT"

(1, 4) and (4, 4) --> "LLLL"

(1, 4) and (1, 4) --> "L" or ""


The unique multiplication spiral This one is inspired by Calvin's Hobbies recent multiplication table challenge.

Write a function or program that takes an integer N as input and prints or returns a N-by-N unique multiplication spiral. The code must (in theory) work for N between 0 and 1000 (outputting this can be hard though). The output should be equivalent to the table produced by the following procedure:

Fill out an N-by-N multiplication table. E.g. for N = 3:

1 2 3
2 4 6
3 6 9

Follow a spiral clockwise from the upper left corner, noting the numbers that you visit. When you visit a number which you have already visited, replace it with 0.

A few examples might make it more clear:

n = 0:
0

n = 1:
1

n = 2:       //   Spiral order:
1  2         //   1  2
0  4         //   4  3

n = 3:
1  2  3      //   1  2  3
0  4  6      //   8  9  4
0  0  9      //   7  6  5

n = 4:
1  2  3  4   //   1   2   3   4
0  0  6  8   //  12  13  14   5
0  0  9 12   //  11  16  15   6
0  0  0 16   //  10   9   8   7

n = 5:
1   2   3   4   5
0   0   6   8  10
0   0   9  12  15
0   0   0  16  20
0   0   0   0  25

n = 10:
1   2   3   4   5   6   7   8   9  10
0   0   0   0   0  12  14  16  18  20
0   0   0   0  15   0  21  24  27  30
0   0   0   0   0   0  28  32  36  40
0   0   0   0  25   0  35   0  45  50
0   0   0   0   0   0  42  48  54  60
0   0   0   0   0   0  49  56  63  70
0   0   0   0   0   0   0  64  72  80
0   0   0   0   0   0   0   0  81  90
0   0   0   0   0   0   0   0   0 100

The numbers are found like this:

Any reasonable output format is accepted, but it must be an N-by-N matrix, it cannot be just a list. Formats such the ones below are accepted, as there are N easily distinguishable 1-by-N columns, or N-by-1 rows:

[[1 2 3][0 4 6][0 0 9]]   <-- OK

[[1 0 0][2 4 0][3 6 9]]   <-- OK

ans =                     <-- OK
    1  2  3
    0  4  6
    0  0  9

Shortest code in bytes win.

Mathematica 123 122 117 98 92 73 bytes

With 24 bytes saved thanks to LegionMammal978 and another 19 by alephalpha !

Surprisingly, in this table, multiple instances of any whole number n will have the same relative ordering in the spiral as they do in the table itself!
The first appearance of a number n lies at the very cell where that number appears first in the table (when one fills in the table row by row).  This means that the approach can disregard the spiral constraint altogether, for it has no bearing on the outcome.  (See explanation below.)

ReplacePart[t=1##&~Array~{#,#},Join@@(Rest[t~Position~#]&/@Union@@t)->0]&

Example

ReplacePart[t=1##&~Array~{#,#},Join@@(Rest[t~Position~#]&/@Union@@t)->0]&[10]

  {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, {0, 0, 0, 0, 0, 12, 14, 16, 18,
    20}, {0, 0, 0, 0, 15, 0, 21, 24, 27, 30}, {0, 0, 0, 0, 0, 0, 28, 32,
     36, 40}, {0, 0, 0, 0, 25, 0, 35, 0, 45, 50}, {0, 0, 0, 0, 0, 0, 42,
     48, 54, 60}, {0, 0, 0, 0, 0, 0, 49, 56, 63, 70}, {0, 0, 0, 0, 0, 0,
     0, 64, 72, 80}, {0, 0, 0, 0, 0, 0, 0, 0, 81, 90}, {0, 0, 0, 0, 0,
    0, 0, 0, 0, 100}}

Grid[%]

Explanation

We exploit the fact that the spiral-order of the positions of any digit, n, is the same as the the order of row-col positions returned by the function, Positions!

The location of the first occurrence of each number (whether one orders by the spiral or by the table position) will be the first element returned by Position.  That first-occurrence cell will be left as it is. The remaining instances of the number are replaced by 0.

Let's look at how this works, examining for the case of n==18. The idea is to start with the multiplication table:

(t = Table[k Range@#, {k, #}] &[10]) // Grid

and locate the row-col positions of each number.  For example, 18 is located at
Row 2, Col 9 (the first instance); Row 3, Col 6; Row 6, Col 3; and Row 9, Col 2.
These have the respective spiral-order positions {44, 58, 68, 82}.

Position[t, 18]

  {{2, 9}, {3, 6}, {6, 3}, {9, 2}}

as the following table shows.

The final 3 instances of 18 need to be replaced by 0.  (We'll use a large bold blue zeros so they can be easily spotted.)

ReplacePart[%, {{3, 6}, {6, 3}, {9, 2}} -> Style[0, {Blue, Bold, 16}]]// Grid


Parallelogram a Number Now that we know how to properly square and triangle a number, we are going to learn how to parallelogram one.  To parallelogram a number, we first arrange it as a parallelogram by stacking it on top of itself a number of times equal to the number of digits it has, and adding spaces to make it a parallelogram.  So 123 would form:

   123
  123
 123

Now we take each horizontal and vertical number and add them, 123+123+123+1+12+123+23+3, which equals 531, which is the parallelogram of 123.

Your Task:

Write a program or function that, when given a number as input, returns the parallelogram of the number.

Input:

A non-negative integer, or a non-negative integer represented by a string.

Output:

The parallelogram of the integer.

Test Cases:

1234567 -> 10288049
123     -> 531
101     -> 417
12      -> 39

Scoring:

This is code-golf, lowest score in bytes wins!

MATL, 12 bytes
tnEXyPY+c!Us

Input is a string. Try it online!
Explanation
Consider input '123' as an example.
The code duplicates the input (t) and builds an identity matrix (Xy) of size twice the input length (nE):
1 0 0 0 0 0
0 1 0 0 0 0
0 0 1 0 0 0
0 0 0 1 0 0
0 0 0 0 1 0
0 0 0 0 0 1

then flips it upside down (P):
0 0 0 0 0 1
0 0 0 0 1 0
0 0 0 1 0 0
0 0 1 0 0 0
0 1 0 0 0 0
1 0 0 0 0 0

The input string, interpreted as ASCII codes of the digits, is equivalent to the numeric row vector
49 50 51

Full-size two-dimensional convolution (Y+) of the above vector and matrix gives
 0  0  0  0  0 49 50 51
 0  0  0  0 49 50 51  0
 0  0  0 49 50 51  0  0
 0  0 49 50 51  0  0  0
 0 49 50 51  0  0  0  0
49 50 51  0  0  0  0  0

Interpreting those numbers back as ASCII codes (c) gives the following char matrix, with char 0 represented as space:
     123
    123
   123
  123
 123
123

Transposition (!) transforms this into
     1
    12
   123
  123
 123
123
23
3

Interpreting each row as a number (U) gives the numeric column vector
  1
 12
123
123
123
123
 23
  3

and summing it (s) gives the final result, 531.


Output the list of musical notes This task is simple: Write a program or function that outputs the list of all musical notes (using English note names) from A♭ to G♯.

All notes without a name consisting of a single letter (i.e. black notes on a musical keyboard) should have their name printed twice, once as the sharp of a note, once as the flat of one. Sharp or flat notes that can be described with a single letter, like B♯ (C) or F♭ (E) should not be outputted.

Here is an example of the output:

Ab, A, A#, Bb, B, C, C#, Db, D, D#, Eb, E, F, F#, Gb, G, G#

Specifications

The program or function must not take any input.
The notes may be printed in any order, and in any list output permitted by our standard I/O rules
The sharp and flat Unicode symbols (♯/♭) may be substituted with b
and #
As always, Standard loopholes are forbidden.
As this is code-golf, the smallest program, in bytes, wins.

Malbolge, 482 370 353 bytes

R1: Removed commas inbetween (as not required by the challenge)

R2: Shave off a few bytes

('<;_#!=6Z|{8xUwvt,PrqonKmk)"FhCUTdb?`+<;:[Z7YtVU2T|/g-O+i(gJrHc#EC~B{@zZxw:tt'r5Qo"!l/K-hUfe?bP``_Lo~[}|X2VCTR3Q+N`_^9+7Hji3ffdAc~w|u;]\wpon4VUSSQ.PONcb(JI^]#DCYX|@?>=<:u9NMRKo32MFj.C,Ae)>'<%:^"!~5:3WxwwuRts0q(Lnml)"Fhgfe"y?a`_zyxq7YXWlUj0RgfkjMb(JI^c\[Z~BAV?T=Rv987Mq44310FEi-,G@)>b&%#"8=6Z{{yyw/Sut1*)('Km$k(!Efe{zyx>`uz]r8ZXnm3TTih.PkNchg`&HFF[DY}Az

Try it online!


It's super effective! In Pokémon there are 18 types:

Normal    Fighting  Flying  Poison  Ground  Rock
Bug       Ghost     Steel   Fire    Water   Grass
Electric  Psychic   Ice     Dragon  Dark    Fairy

A Pokémon can have single or dual typing. For example, Pikachu is Electric, and Tyranitar is Rock/Dark. The order of the types does not matter. A Pokémon can't have the same type twice. An attacking move has exactly one of the above 18 types.

Some Pokémon types are weak to a certain type of attack. For example, a Fire Pokémon is weak against Water attacks. This gives a damage multiplier of 2.
Some Pokémon types are resistant to a certain type of attack. For example, a Rock Pokémon is resistant against a Normal attack. This gives a damage multiplier of 0.5.
Some Pokémon types are immune to a certain type of attack. For example, a Flying Pokémon is immune against a Ground attack. This gives a damage multiplier of 0.

A pokemon can be doubly weak, doubly resistant or any other combination against an attacking type. Multiply the multipliers to get a total effectiveness.

Write a program or function that given a move type and a Pokémon typing outputs the total damage multiplier of the attack. A Pokémon typing is always written either as A or A/B, where A and B are distinct types from the list above. You must accept the Pokémon typing in this format. Other than this restriction you may take input in any reasonable manner. An example input format that acceptable is:

"Ice", "Dragon/Flying"

But this is unacceptable:

["Ice", ["Dragon", "Flying"]]

Your output must be exactly one of the following strings, followed by an optional trailing newline:

0x    0.25x    0.5x    1x    2x    4x

Examples

Ground, Fire -> 2x
Normal, Rock/Dragon -> 0.5x
Fighting, Ghost/Steel -> 0x
Steel, Water/Steel -> 0.25x
Ice, Dragon/Flying -> 4x
Water, Ground/Water -> 1x
Ghost, Ghost -> 2x

Type effectiveness

For a human-friendly type chart I'd like to refer you to Gamepedia. To make the golfing process a bit faster I'll give you a compressed computer-friendly matrix of effectiveness. Divide every number by two to get the true multiplier (1 -> 0.5, 4 -> 2):

              Defending type
               (same order)

   Normal   222221201222222222
   Fighting 421124104222214241
A  Flying   242221421224122222
t  Poison   222111210224222224
t  Ground   220424124421422222
a  Rock     214212421422224222
c  Bug      211122211124242241
k  Ghost    022222242222242212
i  Steel    222224221112124224
n  Fire     222221424114224122
g  Water    222244222411222122
   Grass    221144121141222122
T  Electric 224202222241122122
y  Psychic  242422221222212202
p  Ice      224242221114221422
e  Dragon   222222221222222420
   Dark     212222242222242211
   Fairy    242122221122222442

Shortest code in bytes wins.


Slime Molds Can Count! Background

Slime molds are awesome.
If you place them on a surface with food sources, they will spread their tendrils to find the food, after which they form a network of connections between the sources.
In this challenge, you shall simulate a slime mold looking for food.
Moreover, this particular mold will stop once it's found enough.

Input

Your inputs shall be a list L of 2D integer coordinates in the native format of your language, and a nonnegative integer N.
The list L is guaranteed to be duplicate-free, but it may not be sorted.
The input N is between 0 and the length of L, inclusive.

The list L represents a set of coordinates for food sources.
For example, the list

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

could be interpreted visually as

     o
o

   o
o
  o

Output

Your output is another duplicate-free list K of 2D integer coordinates on the same format as the input.
It represents the network formed by the slime mold, and it shall satisfy the following conditions:

The intersection of L and K has size exactly N.
The set K is connected as a subset of the integer grid (via orthogonal or diagonal adjacencies).
If any coordinate of K is removed, it no longer satisfies the first two conditions.

Note that if N = 0, the output must be an empty list.

An example of an acceptable output for the above list L and N = 4 would be

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

which can be visualized as

   xxO
Oxx
x  x
x  x
x  O
O
  o

where each O represents a coordinate in both L and K, and each x represents a coordinate in K but not in L.
Other outputs are also acceptable, and the "tendrils" don't have to be the shortest possible.
For example, this is also an acceptable solution:

   xxOxx
Oxx     x
  x    x
 x    x
x  o x
O   x
  Ox

Rules

Both the input and output shall be lists, not sets or other datatypes.
The coordinates themselves can be lists or tuples.
You can change the order of the two inputs if needed.

You can write either a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.

Test Cases

Your program should work on these lists for all applicable values of N.

[]
[(2,3)]
[(0,0),(1,0),(0,1),(1,1)]
[(0,0),(2,-1),(3,1),(0,4),(5,5)]
[(0,0),(1,0),(2,0),(3,0),(0,3),(1,3),(2,3),(3,3)]
[(0,0),(1,0),(2,0),(3,0),(0,3),(1,3),(2,3),(3,3),(0,1),(0,2),(3,1),(3,2),(8,1),(8,2),(-5,1),(-5,2)]
[(0,0),(20,0),(15,15),(-10,4),(-10,3),(0,-5),(7,6),(7,7),(8,8),(9,8),(10,-2),(-1,12),(-3,10)]
[(0,0),(1,0),(2,0),(3,0),(5,0),(6,0),(7,0),(0,9),(1,9),(2,9),(3,8),(4,9),(5,10),(6,10),(7,9),(3,3),(4,4),(5,5)]

Visualized:

===
o
===
oo
oo
===
     o
o

   o
o
  o
===
oooo

oooo
===
     oooo
o    o  o    o
o    o  o    o
     oooo
===
                         o

         o

       o

                  oo
                 o
                 o

o
o

          o                   o

                    o

          o
===
     oo
ooo o  o
   o

     o
    o
   o

oooo ooo

CJam, 77 95 bytes

I think this can be golfed a bit more, but here goes:

q~$<_{{:X;]{[X\]z::-~mhW*}$~:Y{_)Y1{_@=X@=}:B~-g-{+__X=!\}:C~1B=!&}g{_(Y0B-g-\C0B=!&}g}*]_&}L?p

Input goes like N <Array of coordinate array>. For example:

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

Output:

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

Algorithm:

The algorithm is pretty straight forward and goes like:

Sort the input coordinate array. This makes the coordinates sorted first by row and then by column.
Now we pick first N points
Now we reduce on these N points. The destination is the last point and the source is the closes point to that last point.
Then we start with the top-left most point, walk right (or left) till its on or directly above the next point.
Then we walk down to reach the next point.
It is guaranteed that there will be no uncovered point left to the above point in the same row. This ensures that we do not touch any other point that the chosen N. Choosing the closes point also ensures that second rule is held true.

Try it online here


triplegolf - not only the source code length counts! The goal of this challenge is to write a program where the length of the following three are exactly the same:

the length of the source code
the length of the output it prints to the standard output
the length of the compiler warnings it generates with the (unmodded) compiler of your choice

The winner is the shortest code to fulfill all three criteria, and has to be at least 1 character long.

To spice things up, if the output has less than three different characters, it gets a 5 point penalty added to the length for each one (so +10 if only a single type, +5 for two).

(Newlines count either as 1 or 2 characters, your choice, but it has to be consistent through all three criteria. Leading and trailing white-spaces are ignored in all lines in all three criteria)

In case of equal score, the one printing the most interesting result (instead of garbage) is the winner.

Bash, 23 characters
Error:
bash: /: Is a directory

Source:
echo       $0-$01234;/;

Output:
/bin/bash-/bin/bash1234

Brainf*ck, 32 characters
This code executes for about 3 seconds and stops and displays the following error and output.
Error:
bff: out of memory (-2058691272)

Source:
+++++[......-]..+[>>>>>>>>>>>>-]

Output: (Hexdump)
0505 0505 0505 0404 0404 0404 0303 0303
0303 0202 0202 0202 0101 0101 0101 0000

C, 35 characters
Warning:
b.c:1:30: warning: division by zero

Source and Output:
main(){system("cat "__FILE__)/0;;;}

PHP, 50 characters
Warning:
PHP Warning:  Division by zero in /tmp/3 on line 1

Source and Output:
<?php echo (0/0).''.file_get_contents(__FILE__);?>


Wave-Particle Duality Laterally Programmatically Write a program or function that takes in a nonempty single-line string. The string will either be zero or more spaces followed by one period (a particle), such as . or          ., or the string will be a sequence of one or more alternating forward and back slashes (a wave) that could start with either one, such as \ or /\/ or \/\/\/\/\/\/.

In either case, propagate the particle/wave to the right by one unit.

Specifically, in the particle case, insert a space before the ., moving it one place to the right, then output the resulting string. For example:

. →  .
 . →   .
  . →    .
   . →     .
    . →      .
     . →       .
      . →        .
       . →         .

In the wave case, append either / or \ appropriately so the wave keeps alternating and it's length increases by one, then output the resulting string. For example:

/ → /\
\ → \/
/\ → /\/
\/ → \/\
/\/ → /\/\
\/\ → \/\/
/\/\ → /\/\/
\/\/ → \/\/\

In either case, the output may not have trailing spaces but an optional trailing newline is allowed.

The shortest code in bytes wins.

C, 69 bytes

p;f(char*s){p=s[strlen(s)-1]^46;p^=p?93:3022856;printf("%s%s",s,&p);}

This requires a little-endian machine, and output to a terminal that support ASCII escape codes.

p=s[strlen(s)-1]^46 grabs the last ASCII code of the input string, and XORs it with the ASCII code of a dot.

p^=p?93:3022856 will cause p to be p^93 if the ASCII code is not a (back)slash, where p^46^93 == p^115, which will toggle between back and forward slash. If p is a dot, it will instead be 3022856, which is little-endian for "\b .".

printf("%s%s",s,&p); prints the input string followed by the integer p, interpreted as a little-endian byte string.


win a virtual fencing match (against your fellow stack exchangers) WARNING: this is a fairly complex problem, in a king-of-the-hill combat style, with an added randomness to it, the best code may not always win. Please read all rules in full, as it is quite complex!

FLAVOR TEXT

Bill and Steve  decided to have a "friendly" duel, however being so rich and smart, decided to let their best programmers try their hand at coming up with the code to beat each other. You are said programmer.

OBJECTIVE

In fencing, your goal is to score the most hits on your opponent, while getting hit the least yourself

MOVES

Your code will have the following choices of "moves"

Attack
Parry
Block
Lunge
AND
Head
Chest
Feet

SCORING POINTS

Attacking beats Parrying, for 1 point
Lunging beats Blocking, for 1 point
Parrying Beats Lunging, for 1 point
Blocking beats Attacking, for 1 point
Lunging ties Attacking, with the lunging player unable to block or parry the next round, and the attacking player unable to attack or lunge the next round
Blocking ties Parrying, with the parrying player unable to block or parry the next round, and the blocking player unable to attack or lunge the next round

HEIGHT OF ACTION

you will also choose a "height" for your action, whereupon the outcomes above only take place if the heights of both players match the attack height. if the heights do not match, both players may no longer select the same action (height is not restricted) as the previous tying rounds, until a point is scored, or all 4 actions have been filled (once a tie is broken, all actions are available again)

CODE REQUIREMENTS

for each round, it should prompt the move of the opponent the previous round (barring round 1), compare it with its own, determine the outcome of the previous round, then output the next round number, the score, and its choice / position for that round

ex:
  INPUT: LC (lunge chest)
  OUTPUT: previous round: PM vs LC - PM scores! score is now 2-1, action for next round is AH (attack head)

WINNER

the game ends after 50 rounds, or after 3 points have been scored

AGAINST OTHER PLAYERS

the first answer will be given an instant guaranteed win, as long as it functions to actually work/play. Each answer will be evaluated, in order of posting, against the previous winner, and if winning, will be declared the new winner. I ask that while winning, or waiting to compete, that you do NOT change your code. Once being defeated, you may no longer compete for championship status with that same language, you may however submit a different language answer (must be significantly different, no using variations of the same base stuff).

I will attempt to run each challenge and will post the results in the comments of the champion and challenger, as well as declare a new winner - as I may not be able to run every language, especially some of the more obscure ones, I ask any possible help you can give to make sure your answer gets run be taken into consideration. Thank you!

Python

En garde!

My warrior combines unpredictability with a keen eye for weakness in his opponent's stance.  He's pretty confident he'll be able to dispose of aggressive foes but his trainer (me) may have failed to anticipate certain scenarios or, perhaps more worrying, may have misinterpreted the rules (bugs!!).

Anyway I'm new so hopefully this is an ok format for the code:

from random import choice, random

def cleverly_pick_move(me_allowed,op_allowed,opp_last_move=None) :
    """ Behold the genius you're up against!
    Pretty much everything else is just flavour text or match rules
    so you'll probably only want to read this...
    """
    heights = ['head','chest','feet']
    rand_choice = lambda a,h : {'type':choice([t for t in a if a[t]]),
                                'height':choice(h)}

    if opp_last_move is None or feeling_like_a_lucky_punk():
        return rand_choice(me_allowed,heights)

    if sum(1 for x in op_allowed if op_allowed[x]) == 3 :
        for i in op_allowed:
            if not op_allowed[i] :
                weakness = i
                break
        return {'type':exploit_weakness(weakness,me_allowed),
                'height':choice(heights)}
    return rand_choice(me_allowed,heights)

def exploit_weakness(weakness,me_allowed) :
    moves = ['attack','parry','lunge','block']
    for i,move in enumerate(moves) :
        if move == weakness :
            if me_allowed[moves[(i+1) % 4]] :
                return moves[(i+1) % 4]
            break
    if me_allowed[weakness] :
        return weakness
    return choice([x for x in me_allowed if me_allowed[x]])

def feeling_like_a_lucky_punk() :
    return random() > 0.8

def main():

    this_round = 1
    opp_last_move = None
    score   = {'myself':0, 'the blaggard':0}
    quips   = ['blaggard', 'fool', 'scum', 'raggamuffin']
    adverbs = ['deftly', 'skillfully', 'gracefully', 'clumsily']

    me_allowed = {'attack':True,'block':True,'lunge':True,'parry':True}
    op_allowed = {'attack':True,'block':True,'lunge':True,'parry':True}

    while (this_round <= 50 and
           all([points < 3 for points in score.values()])) :

        if this_round == 1 :
            move = cleverly_pick_move(me_allowed,op_allowed)
        else:
            move = cleverly_pick_move(me_allowed,op_allowed,
                                      opp_last_move=opp_last_move)

        print "Our hero %s %ss at the %s's %s" % (
            choice(adverbs),
            move['type'],
            choice(quips),
            move['height']
            )
        print "We await the %s's response..." % choice(quips)
        print "Our hero's move: " + (move['type'][0]+move['height'][0]).upper()

        opp_move = parse_move(raw_input("Opponent's move: "))

        outcome,me_allowed,op_allowed = get_outcome(move,opp_move,me_allowed,
                                                    op_allowed)
        if outcome == 'WIN' :
            print "Our hero pulls off an excellent round!"
            score['myself'] += 1
        elif outcome == 'LOSE' :
            print "Never before have we seen such blatant cheating!"
            score['the blaggard'] += 1
        else :
            print "Our hero is clearly toying with his opponent as he allows \
a drawn round."

        print ("""The score after round %d:\nOur hero:\t%d\nHis opponent:\t%d"""
                % (this_round, score['myself'], score['the blaggard']))
        opp_last_move = opp_move
        this_round += 1

    print "Match over, surely the victory is mine!"
    print """Final score:\n
             Our hero:\t%d\nOpponent:\t%d""" % (score['myself'],
                                                score['the blaggard'])

    if score['myself'] > score['the blaggard'] :
        print "My victory was inevitable!"
    elif score['myself'] == score['the blaggard'] :
        print "An even match! Huzzar!"
    else :
        print ""
    return

def reset_allowed(dictionary) :
    return dict((x,True) for x in dictionary)

def get_outcome(mymove,opmove,me_allowed,op_allowed) :
    result = ''

    if not me_allowed[mymove['type']] :
        print "Whoops, I forgot I couldn't do that..."
        result = 'LOSE'

    if not op_allowed[opmove['type']] :
        print "Haha! What a clutz!"
        result = 'WIN'

    if mymove['height'] != opmove['height'] :
        print "The combatants flail at each other with little effect!"
        print "They'll have to try something else next round!"
        result = 'DRAW'

    if mymove['type'] == opmove['type'] :
        if mymove['type'] in ['attack','lunge']:
            print "The combatants' blades clash dramatically!"
        else :
            print "Both combatants take a moment to practice their \
defensive stance..."
        result = 'DRAW'

    if result :
        me_allowed, op_allowed = (reset_allowed(me_allowed),
                                  reset_allowed(op_allowed))
        if mymove['height'] != opmove['height'] :
            me_allowed[mymove['type']] = op_allowed[opmove['type']] = False
        return (result, me_allowed,op_allowed)
    else :
        return compare_attacks(mymove,opmove,me_allowed,op_allowed)

def compare_attacks(mymove,opmove,me_allowed,op_allowed) :
    """
    0 A > P 1
     ^  x  v
    3 B < L 2
    """
    print "Our hero %ss, his opponent %ss!" % (mymove['type'],opmove['type'])

    move_val = {'attack':0,'parry':1,'lunge':2,'block':3}
    result_num = (move_val[opmove['type']] - move_val[mymove['type']]) % 4
    results = ['DRAW','WIN','DRAW','LOSE']

    me_allowed, op_allowed = (reset_allowed(me_allowed),
                              reset_allowed(op_allowed))
    if result_num == 1 :
        print "Our hero easily outwits his foe! *Huge cheers from crowd*"
        return ('WIN',me_allowed,op_allowed)
    elif result_num == 3 :
        print "Our hero graciously allows his opponent a charity point.\
*A torrent of boos from the crowd*"
        return ('LOSE',me_allowed,op_allowed)
    else:
        # Combatants drew and will have their moves restricted next round.
        if mymove['type'] in ['attack','parry'] :
            me_allowed['attack'] = me_allowed['lunge'] = False
            me_allowed['parry']  = me_allowed['block'] = True
            op_allowed['parry']  = op_allowed['block'] = False
            op_allowed['attack'] = op_allowed['lunge'] = True
        else :
            me_allowed['parry']  = me_allowed['block'] = False
            me_allowed['attack'] = me_allowed['lunge'] = True
            op_allowed['attack'] = me_allowed['lunge'] = False
            op_allowed['parry']  = op_allowed['block'] = True
        return ('DRAW',me_allowed,op_allowed)

def parse_move(move_string) :
    m_types = {'A':'attack','B':'block','L':'lunge','P':'parry'}
    m_heights = {'C':'chest','H':'head','F':'feet'}

    move_string = move_string.strip().upper()
    if not move_string :
        print "Couldn't understand your input: %s" % move_string
        return parse_move(raw_input("Opponent's move: "))

    if move_string[0] not in m_types :
        move_string = move_string[::-1]

    try :
        move = {'type':m_types[move_string[0]],
                'height':m_heights[move_string[1]]}
        return move
    except KeyError :
        print "Couldn't understand your input: %s" % move_string
        return parse_move(raw_input("Opponent's move: "))

if __name__ == '__main__' :
    main()


The square root of the square root of the square root of the… This code-golf challenge will give you an integer n, and ask you to count the number of positive integer sequences \$S = (a_1, a_2, \dots, a_t)\$ such that

\$a_1 + a_2 + \cdots + a_t = n\$, and
\$\displaystyle
\sqrt{a_1+\sqrt{a_2 + \cdots + \stackrel{\vdots}{\sqrt{a_t}}}}
\$ is an integer.

Example
If n = 14, then there are 8 such sequences:

\$\sqrt{2+\sqrt{2+\sqrt{2+\sqrt{2+\sqrt{2+\sqrt{3+\sqrt{1}}}}}}} = 2\$
\$\sqrt{2+\sqrt{2+\sqrt{2+\sqrt{2+\sqrt{2+\sqrt{4}}}}}} = 2\$
\$\sqrt{1+\sqrt{7+\sqrt{2+\sqrt{3+\sqrt{1}}}}} = 2\$
\$\sqrt{2+\sqrt{1+\sqrt{7+\sqrt{3+\sqrt{1}}}}} = 2\$
\$\sqrt{2+\sqrt{2+\sqrt{1+\sqrt{8+\sqrt{1}}}}} = 2\$
\$\sqrt{1+\sqrt{7+\sqrt{2+\sqrt{4}}}} = 2\$
\$\sqrt{2+\sqrt{1+\sqrt{7+\sqrt{4}}}} = 2\$
\$\sqrt{2+\sqrt{2+\sqrt{1+\sqrt{9}}}} = 2\$

(In this example, all of the nested square root expressions are equal to 2, but in general, this may not be the case.)
Pairs \$(n,(a(n))\$ for \$n \leq 25\$:
(1,1),(2,0),(3,0),(4,2),(5,0),(6,2),(7,0),(8,2),(9,2),(10,4),(11,2),(12,6),(13,2),(14,8),(15,4),(16,14),(17,6),(18,20),(19,8),(20,28),(21,14),(22,44),(23,20),(24,66),(25,30)

Your code must be robust against floating-point errors, that is it must work for arbitrarily large inputs, in principle.
Since this is a code-golf challenge, the shortest code wins.

(This is now on the On-Line Encyclopedia of Integer Sequences as
A338271. Sequence A338268 has been added too, based on Bubbler's \$f\$ function.)

APL (Dyalog Unicode), 39 bytes

+/⊢{∨/⍺⍵<⍵0:0⋄⍺=0:1⋄+/∊∇¨/⍺(⍵*2)-⊂⍳⍺}¨⍳

Try it online!
A tacit function containing an inner dfn to use recursion. Does not use floating point numbers at all.
How it works
First of all, observe that
$$
\displaystyle
\sqrt{a_1+\sqrt{a_2 + \cdots + \stackrel{\vdots}{\sqrt{a_t}}}} \le \cdots \le \sqrt{a_1+a_2 + \cdots + a_t} \le a_1+a_2 + \cdots + a_t = n
$$
and this holds for all suffixes of any given sequence of positive integers.
Let's define a function \$f(x,y)\$ as the number of sequences where the sum is \$x\$ and the "root sum" is \$y\$. Then the following holds:
$$
\begin{align}
f(0, 0) &= 1 \\
f(0, y) &= 0, \qquad 0 < y \\
f(x, y) &= 0, \qquad x < y \text{ or } y < 0 \\
f(x, y) &= \sum_{i=1}^{x}{f(x-i, y^2-i)}
\end{align}
$$
Then the desired result is the sum \$\sum_{i=1}^{n}{f(n,i)}\$.


Generate a Markdown Template for your Post Your task is simple: Write a program (or function) that takes no input and outputs something like this:

## *name*, *length* bytes
    *code*

Where *name* is the name of the language you are using, *length* is the number of bytes in your code, and *code* is your program's source code. If *code* contains multiple lines, it have four spaces before each line.

Here's a 124-byte example implementation in Python 3:

s = "## Python 3, 124 bytes{2}    s = {1}{0}{1}{2}print(s.format(s,chr(34),chr(10)))"
print(s.format(s,chr(34),chr(10)))

The output is:

## Python 3, 124 bytes
    s = "## Python 3, 124 bytes{2}    s = {1}{0}{1}{2}print(s.format(s,chr(34),chr(10)))"
    print(s.format(s,chr(34),chr(10)))

Which in Markdown is:

  Python 3, 124 bytes

s = "## Python 3, 124 bytes{2}    s = {1}{0}{1}{2}print(s.format(s,chr(34),chr(10)))"
print(s.format(s,chr(34),chr(10)))

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

RProgN 2, 28 Bytes
«"  %s"F"#RProgN 2, 28 Bytes"


Squish-unsquish ligatures Here is a list of some common
ligatures in Unicode (the
ones I could create with my Compose key on Debian):

Orig  Ascii  Lig
ae    [ae]   æ
AE    [AE]   Æ
oe    [oe]   œ
OE    [OE]   Œ
ij    [ij]   ĳ
IJ    [IJ]   Ĳ
ff    [ff]   ﬀ
fi    [fi]   ﬁ
fl    [fl]   ﬂ
ffi   [ffi]  ﬃ
ffl   [ffl]  ﬄ

You have two options in this challenge: use the actual UTF-8 ligatures, or use
the ASCII-only variant. If you use the actual UTF-8 ligature variants, you gain
a 20% bonus. If you use the ASCII-only variant, you may assume square brackets
will never be involved except to signify a ligature.

The challenge: given a string as input, output the same string

with all original ligatures replaced by their expanded counterparts.

match greedily: affib becomes aﬃb (a[ffi]b), not aﬀib (a[ff]ib)
or afﬁb (af[fi]b).

with all "expanded" letter sequences replaced by ligatures.

for example, æOEfoo ([ae]OEfoo) becomes aeŒfoo (ae[OE]foo).

Do this completely independently: ﬀi ([ff]i) becomes ffi (ffi), not ﬃ
([ffi]).

Sound simple enough? There's a catch: every time two non-ligatures overlap by
exactly one character, both of the ligatures must be inserted into the
string. Here's a few test cases to demonstrate:

Input   Ascii-output      Output
fij     [fi][ij]          ﬁĳ
fIJ     f[IJ]             fĲ     * remember, capitalization matters!
fffi    [ff][ffi]         ﬀﬃ
fff     [ff][ff]          ﬀﬀ
ffffi   [ff][ff][ffi]     ﬀﬀﬃ
ffffij  [ff][ff][ffi][ij] ﬀﬀﬃĳ

Be careful: the same greedy matching applies (note especially the last few test
cases).

code-golf, so shortest code in bytes wins.

JavaScript (ES6), 213 bytes - 20% bonus = 170.4

s=>eval('for(p=o="";m=s.match(r="ﬄ|ﬃ|ﬂ|ﬁ|ﬀ|Ĳ|ĳ|Œ|œ|Æ|æ|ffl|ffi|fl|fi|ff|IJ|ij|OE|oe|AE|ae",x=r.split`|`);s=s.slice(i+t.length-(p=t<"z")))o+=s.slice(p,i=m.index)+x[(x.indexOf(t=m[0])+11)%22];o+s.slice(p)')

Explanation

s=>                           // s = input string
  eval(`                      // use eval to avoid writing {} or return
    for(                      // iterate over each ligature match
      p=                      // p = 1 if the last match was a non-unicode ligature
        o="";                 // o = output string
      m=s.match(              // find the next ligature

        // r = regex string for ligatures (unicode and non-unicode)
        r="ﬄ|ﬃ|ﬂ|ﬁ|ﬀ|Ĳ|ĳ|Œ|œ|Æ|æ|ffl|ffi|fl|fi|ff|IJ|ij|OE|oe|AE|ae",
        x=r.split\`|\`        // x = arrray of r

      );
      s=s.slice(i+t.length    // remove the part that has been added to the output
        -(p=t<"z"))           // if we matched a non-unicode ligature, keep the last
    )                         //     character so it can be part of the next match
      o+=s.slice(p,i=m.index) // add the text before the match to the output
        +x[(x.indexOf(        // add the opposite type of the matched ligature
          t=m[0]              // t = matched text
        )+11)%22];            // (index + 11) % 22 returns the opposite index
    o+s.slice(p)              // return o + any remaining characters
  `)

Test

var solution = s=>eval('for(p=o="";m=s.match(r="ﬄ|ﬃ|ﬂ|ﬁ|ﬀ|Ĳ|ĳ|Œ|œ|Æ|æ|ffl|ffi|fl|fi|ff|IJ|ij|OE|oe|AE|ae",x=r.split`|`);s=s.slice(i+t.length-(p=t<"z")))o+=s.slice(p,i=m.index)+x[(x.indexOf(t=m[0])+11)%22];o+s.slice(p)')
<input type="text" id="input" value="ﬀiffffij" oninput="result.textContent=solution(input.value)" />


"Creative" ways to determine if an array is sorted Given an integer array, write a program that determines if it is sorted in ascending order.

Remember that this is a code trolling question.

I am looking for most interesting ways that people come up with.

The answer with most upvotes wins.

This question is inspired by a 'creative' solution that a candidate gave me in an interview :)

The 'creative' solution was something like this:

  Because for a sorted array

  all the elements on the left side of any element must be smaller
  all the elements on the right side of any element must be bigger

  Therefore, run a main loop for all elements and check the above two conditions by running two nested loops inside the main one (one for left side and one for right side)

I was shocked!!.

Ruby
Everyone knows: sorting is very slow and takes many cycles (the best you can do is something with n log(n)). Thus it is quite easy to check if the array is sorted. All you have to do is compare the runtime of sorting the array and sorting the sorted array.
array = [1, 5, 4, 2, 3]

## measure the time needed to sort the array 1m times
tstart = Time.now
1000000.times {
  array.sort
}
trun = Time.now - tstart

## now do a reference measurement on a sorted array
array.sort!
tstart = Time.now
1000000.times {
  array.sort
}
treference = Time.now - tstart

## compare run times
if trun > treference
  print "array was not sorted"
else
  print "array was sorted"
end


Smallest Diversifying Exponent A pandigital number is an integer which contains every digit from 0 to 9 at least once. 1234567890, 1902837465000000, and 9023289761326634265 are all pandigital. For the purposes of this challenge, numbers such as 123456789 are not pandigital, since they do not contain a 0, even though 123456789 = 0123456789.

A diverse pair of integers is a pair of integers \$(a, b)\$ such that \$a^b\$ is pandigital. \$b\$ is called the diversifying exponent.

Challenge: Given an integer \$a\$, find the smallest corresponding diversifying exponent \$b\$. This is a code-golf, so the shortest program in bytes wins.

(You may assume that there exists such an exponent, that is, your program will not be given invalid input, such as a power of 10.)

Your solution must be able to handle at the minimum the given test cases, but it should theoretically handle all valid inputs.

This is A090493 on OEIS.

Test cases

2 -> 68
3 -> 39
4 -> 34
5 -> 19
6 -> 20
7 -> 18
8 -> 28
9 -> 24
11 -> 23
12 -> 22
13 -> 22
14 -> 21
15 -> 12
16 -> 17
17 -> 14
18 -> 21
19 -> 17
20 -> 51
21 -> 17
22 -> 18
23 -> 14
24 -> 19
25 -> 11
26 -> 18
27 -> 13
28 -> 11
29 -> 12
30 -> 39
31 -> 11
32 -> 14
33 -> 16
34 -> 14
35 -> 19
36 -> 10
1234567890 -> 1

Brachylog (v2), 9 bytes

;.≜^dl10∧

Try it online!

This is a function submission. The TIO link contains a wrapper that makes a function into a full program.

Explanation

;.≜^dl10∧
 .≜        Brute-force all integers, outputting the closest to 0
;  ^         for which {the input} to the power of the number
    d        has a list of unique digits
     l10     of length 10
        ∧  (turn off an unwanted implicit constraint)


Binary Recurrence Sequences A binary recurrence sequence is a recursively-defined sequence of the following form:
$$F(1) = a_1 \\ \vdots \\ F(y) = a_y \\
F(n) = \alpha F(n-x) + \beta F(n-y), n > y$$
This is a generalization of the Fibonacci (\$x = 1, y = 2, a = [1, 1], \alpha = 1, \beta = 1\$) sequence and the Lucas (\$x = 1, y = 2, a = [2, 1], \alpha = 1, \beta = 1\$) sequence.
The Challenge
Given \$n, x, y, a, \alpha\$, and \$\beta\$, in any reasonable format, output the \$n\$th term of the corresponding binary recurrence sequence.
Rules

You may choose for the sequence to be either 1-indexed or 0-indexed, but your choice must be consistent across all inputs, and you must make note of your choice in your answer.
You may assume that no invalid inputs would be given (such as a sequence that terminates prior to \$n\$, or a sequence that references undefined terms, like \$F(-1)\$ or \$F(k)\$ where \$k > n\$). As a result of this, \$x\$ and \$y\$ will always be positive.
The inputs and outputs will always be integers, within the boundaries of your language's natural integer type. If your language has unbounded integers, the inputs and outputs will be within the range \$[-2^{31}, 2^{31}-1]\$ (i.e. the range for a 32-bit signed two's complement integer).
\$a\$ will always contain exactly \$y\$ values (as per the definition).

Test Cases
Note: all test cases are 0-indexed.
x = 1, y = 2, a = [1, 1], alpha = 1, beta = 1, n = 6 => 13
x = 1, y = 2, a = [2, 1], alpha = 1, beta = 1, n = 8 => 47
x = 3, y = 5, a = [2, 3, 5, 7, 11], alpha = 2, beta = 3, n = 8 => 53
x = 1, y = 3, a = [-5, 2, 3], alpha = 1, beta = 2, n = 10 => -67
x = 5, y = 7, a = [-5, 2, 3, -7, -8, 1, -9], alpha = -10, beta = -7, n = 10 => 39

JavaScript (ES6), 51 44 bytes

(x,y,z,a,b)=>g=n=>n<y?z[n]:a*g(n-x)+b*g(n-y)

Note that the function is partially curried, e.g. f(1,2,[1,1],1,1)(8) returns 34. It would cost 2 bytes to make the intermediate functions independent of each other (currently only the last generated function works correctly).

Edit: Saved 7 bytes thanks to @Mego pointing out that I'd overlooked that the the passed-in array always contains the first y elements of the result.