Calculate an integer sequence derived from prime factors Create a function, expression, or program which does the following:

Take the prime factors of any number and sum them. For example, the prime factors of 28 are 2 2 7, summed to 11.
Multiply the result by the number of prime factors for the given number. E.g, 28 has 3 prime factors which sum to 11. 11 * 3 is 33.
Repeat the process recursively, storing the resulting list (which starts with the original number), until you reach a number that is already included in the list. Halt without adding that final number, so that the list contains no duplicates. The progression for 28 is 28 33, because 33 results in 28 again.
Count the elements in the resulting list. In the case of 28, the answer is 2.

Here are the results for 0<n<=10, so you can check your algorithm.

2 1 1 10 1 11 1 9 5 10

(As balpha pointed out, the answer for higley(1) is 2, from the list 1 0. I originally had 1, due to a bug in my original algorithm written in J.)

Since I'm a conceited SOB and haven't found this on OEIS, let's call this the "Higley Sequence," at least for the duration of this round of code golf. As an added bonus, find the first two n having the lowest higley(n) where n is not prime and n>1. (I think there are only two, but I can't prove it.)

This is standard code golf, so as usual the fewest keystrokes win, but I ask that you please upvote clever answers in other languages, even if they are verbose.


Average Color of an Image Average color of an image

Scientists have been able to determine the average color of the universe but in how many bytes can we find the average color on an image?

Your task

Your input will be a single image which you will need to find the average of the colors in the image and output a hex color-string (#??????). The image can be any of the following formats

JPEG/JFIF

JPEG 2000

TIFF
GIF
BMP
PNG
PNM

PPM

The input can also be taken as a URL/URI to the image.

Build-in functions which calculate averages or sample the image at once such as ImageMeasurements are not allowed.

Examples

Results will differ slightly depending on how you calculate the average and which color models you use. I've added RGB and LCH (HSV) values for the images below.

 output: #53715F RGB, may also be #3B7D3D LCH (HSV)

 output: #8B7D41 RGB, #96753C LCH (HSV)

Bash, 46 bytes

ImageMagick scales image to one pixel which contains average of the colors in the image then outputs it as text.

convert $1 -scale 1x1\! txt:-|egrep -o '#\w+'


Quineoid Triple - A(B) = C Write three different programs such that when any one program is provided as input to one of the other two, you get the source of the remaining program as output. More explicitly, given programs \$A\$, \$B\$, and \$C\$, where \$f(g)\$ denotes the output obtained from inputting the text of program \$g\$ into program \$f\$, all of the following must hold:

\$ A(B) = C \$
\$ A(C) = B \$
\$ B(A) = C \$
\$ B(C) = A \$
\$ C(A) = B \$
\$ C(B) = A \$

Rules and Scoring

This is code-golf, so the shortest program length total, in bytes wins.
Standard quine rules apply.
Each program must be at least one byte different from the other two
Each program can be in any language. Any number of them may share languages or each may use a different language.
Use any convenient IO format as long as each program uses a consistent convention.

Functions are allowed, as this counts as "any convenient IO".

The result of feeding a program its own source code is undefined
The result of feeding anything other than program text of either of the other two programs is undefined.

C, 243 240 180 132 57 bytes
f(int*v){ v[4]^=1;}

f(int*v){ v[4]^=2;}

f(int*v){ v[4]^=3;}

Try it online: A B C
The input program can be passed as a char* to the function f, and is implicitly converted to an int*.
-60 bytes thanks to @Neil
-48 bytes thanks to @Bubbler
-72 bytes thanks to @AZTECCO


Hexadecimal and the Alphabet In this challenge, you will receive an input, convert it to hexadecimal, make a couple changes, and output the result.

Because they are only 16 characters in hexadecimal, your code will need to be as short as possible.

Examples

Examples are separated by a blank line. First line is input, second line shows the steps, third shows the output

234589
234589 -> 3945D -> 39454 -> 9A1E -> 9115 -> 239B -> 2392 -> 958
958

435234
435234 -> 6A422 -> 61422 -> EFEE -> 5655 -> 1617
1617

153
153 -> 99 -> 99 -> 63
1617

Steps

The input will always be a positive integer

In order to generate the output you will follow the following steps:

Convert the input to hexadecimal
Replace any letters with their index in the alphabet (e.g. a -> 1, b -> 2)
Convert the result back to hexadecimal
If the result contains any letters, go to step 2. If not, output the result

This is code-golf so shortest code in bytes wins!

Jelly, 18 bytes

b⁴µ:⁵©+¹%⁵ḅ⁵ß¹®S¤?

Try it online!

The binary, 18 byte version of the source code has the xxd dump

0000000: 62 b6 8c 3a b7 85 2b 8e 25 b7 a3 b7 95 8e 88 53 83 3f b..:..+.%......S.?

and works with this version of the Jelly interpreter.

How it works

b⁴µ:⁵©+¹%⁵ḅ⁵ß¹®S¤?  Define the main link -- Left input: a (number)

b⁴                  Convert from integer to base 16.
  µ                 Start a new, monadic link.
   :⁵               Divide all base 16 digits by 10.
     ©              Save the result in a register.
      +¹            Add the quotients to the base 16 digits.
        %⁵          Take all resulting sums modulo 10.
          ḅ⁵        Convert from base 10 to integer.
              ®S¤   Take the sum of the quotients from the list in the register.
                 ?  If the result is non-zero:
            ß         Recursively call the main link.
             ¹        Else, apply the identity function.

Ḍ (decimal-to-integer) should have worked as a shorthand for ḅ⁵, but the latest version of Jelly at the time of this post had a bug that prevented me from using it.


The half-step of Fibonacci Challenge
Implement the 1-indexed sequence A054049, which starts like this:
1, 2, 3, 6, 13, 5, 9, 377, 21, 11,
89, 14, 8, 233, 16, 987, 18, 2584, 20, 6765,
55, 23, 28657, 25, 75025, 27, 196418, 29, 514229, 31,
1346269, 33, 3524578, ...

This sequence is the lexicographically smallest sequence of positive integers, so that indexing into the sequence twice yields the regular Fibonacci sequence:
$$
a(a(1)) = a(1) = 1 \\
a(a(2)) = a(2) = 2 \\
a(a(3)) = a(3) = 3 \\
a(a(4)) = a(6) = 5 \\
a(a(5)) = a(13) = 8 \\
a(a(6)) = a(5) = 13 \\
a(a(7)) = a(9) = 21 \\ \vdots
$$
The value of \$a(34)\$, the first term that does not fit into the OEIS page, is equal to \$F(377+1)\$, or
4444705723234237498833973519982908519933430818636409166351397897095281987215864

I/O and scoring
The following I/O methods are allowed:

Take no input, and output the sequence indefinitely.
Take the value of \$n\$ (1-indexed), and output the value of \$a(n)\$.

This should follow the definition of \$a(1) = 1\$, \$a(2) = 2\$, and so on. The sequence is broken otherwise.

Take the value of \$n\$, and output first \$n\$ values of the sequence.

Due to the indexing nature of this sequence, the indexing is fixed to 1-indexing. The sequence can be considered 0-indexed by including \$a(0) = 1\$ in front of the sequence; you may use this alternative definition for any of the I/O methods.
Standard code-golf rules apply. The shortest code in bytes wins.

Python 2, 226 bytes

g=input()+2
f=lambda n,x=1,y=1:n and f(n-1,y,x+y)or x
k={1:1,2:2,3:3}
s=set(k)
x=4
y=6
while g/x:
	while g/x|g/y:k[y]=f(x);k[x]=y;s|={x};x,y=y,f(x)
	x,y=sorted(set(range(1,max(s)+3))-s)[:2];s|={y}
print map(k.get,range(1,g-1))

Try it online!
-33 bytes thanks to ovs


Dobble/SpotIt card generator Introduction
Dobble/SpotIt  is a card game, where people have to spot same symbol on pair of cards in shortest time, indicate it and move to next pair. Each card has multiple symbols (8 in normal version), but exactly one is common between each pair of cards.
Example from physical copy of game:

Challenge
Write a program, which given set of symbols (single ascii characters) and number of symbols on single card will produce output listing cards with symbols for each card. There are obviously many equivalent combinations, your program just has to write any of combinations which produces largest amount of cards for given input.
It is a code-golf, so shorter the code, better.
It would be also great if computation will finish before heat death of universe for most complicated case.
Input
Two arguments to function/stdin (your choice)

First of them being collection of symbols, something like 'ABCDE" or ['A','B','C','D','E'] - your choice of format, be it string, set, list, stream, or whatever is idiomatic for language of choice. Characters will be given from set of [A-Za-z0-9], no duplicates (so maximum size of input symbol set is 62). They won't be neccesarily ordered in (so you can get "yX4i9A" as well for 6-symbol case).

Second argument is integer, indicating amount of symbols on single card. It will be <= than size of symbol set.

Output
Print multiple lines separated by newlines, each one of them containing symbols for single card.
Examples
ABC
2
>>>>
AB
BC
AC

Or
ABCDEFG
3
>>>>
ABC
BDE
CEF
BFG
AEG
CDG
ADF

Or
ABCDE
4
>>>>
ABCD

Hints

Number of cards produced cannot be larger than amount of distinct symbols and in many combinations it will be considerably smaller
You might want to read up Some math background if you need help with math side of the problem

This is my first code golf challenge, so please forgive possible issues with formatting/style - I'll try to correct errors if you point them in comments.
Edit:
There is a very nice youtube video explaining the math behind the Dobble setup here:

Python 2, 192 162 bytes

I have an argument that this produces the maximum set of cards for every scenario and it does handle the 3 test cases.

from itertools import*
def m(a,s):
    C=["".join(x)for x in combinations(a,s)]
    while len(C):
        print C[0]
        C=list(set(A for A in C if len(set(A)&set(C[0]))==1<s))

Try it online!

Algorithm

Given an alphabet a and a card size s, take all combinations of s elements in a and call it C,  then:

Take the first element of C, call it C0
Save C0
Remove all elements fromC that have a union with C0 not equal to 1
Repeat with second element of C
Continue until C is empty

Then print the saved elements.

Argument

Some non-empty subset of C is our maximal solution, K. Since it contains at least one element and any two elements are indistinguishable, choose an arbitrary element, C0, of C to be in K. For any element e in the K, the cardinality of e union x is 1 for x != e in K; so eliminate all elements in C whose union with C0 does not have cardinallity 1. By the same reasoning, choose a new arbitrary element in C, add it to K, and reduce C. Eventually C is the empty set and K will be the maximal solution because at no point did we choose an element that was distinguishable from any other element.

Test Cases

These test cases were written before I realized that the printing was a requirement.

a=["a","b","c"]
b=2
c=3
d=m(a,b)
print d,len(d)==c
>> ['bc', 'ab', 'ac'] True

a=["a","b","c","d","e","f","g"]
b=3
c=7
d=m(a,b)
print d,len(d)==c
>> ['aef', 'abc', 'bde', 'ceg', 'adg', 'cdf', 'bfg'] True

a=["a","b","c","d","e"]
b=4
c=1
d=m(a,b)
print d,len(d)==c
>> ['abcd'] True

Update

+9 [16-12-07] Fit the print requirement
-11 [16-12-07] Golfed out my R variable
-30 [16-12-09] Golfed out my K variable, Thanks to @Leo!


Shuffle a ragged array A ragged array is an array where each element is an array of unknown number of positive integers.

For example, the following are ragged arrays:

[[1,2,3],[4],[9,10]]               Shape:  3,1,2
[[1],[2],[3]]                      Shape:  1,1,1
[[1,2,3,4,5,6,8]]                  Shape:  7

The following are not ragged arrays:

[1]   Each element will be an array
[]    The array will contain at least 1 element
[[1,2,3],[]]  Each subarray will contain at least 1 integer

You need to input a ragged array, and return a ragged array with the integers shuffled

The output array must have the same shape as the input array. We define the shape of the array as the length of each subarray.
Each integer must have an equally likely chance to appear in each possible location.
You can assume that your language's built-in random is random.

For example, if I passed in:  [[4],[1,2,3],[4]], then [[1],[4,4,2],[3]] would be a valid output, but [[4,1,3],[3],[4]] or [[4],[4],[1,2,3]] would not.

Jelly, 3 bytes in Jelly's codepage

FẊṁ

Explanation:

FẊṁ
F    flatten list
 Ẋ   shuffle the output from the previous line
  ṁ  unflatten the list, shaping it like…

Because the program is incomplete (ṁ doesn't have a second argument stated), the default is to use the program input; thus ṁ causes the output to have the same sublist pattern as the input.

Try it online!


Call a method without calling it Inspired by a now deleted StackOverflow question. Can you come up with a way to get a particular method executed, without explicitly calling it? The more indirect it is, the better.

Here's what I mean, exactly (C used just for exemplification, all languages accepted):

// Call this.
void the_function(void)
{
    printf("Hi there!\n");
}

int main(int argc, char** argv)
{
    the_function(); // NO! Bad! This is a direct call.
    return 0;
}

Original question:

C

#include <stdio.h>

int puts(const char *str) {
  fputs("Hello, world!\n", stdout);
}

int main() {
  printf("Goodbye!\n");
}

When compiled with GCC, the compiler replaces printf("Goodbye!\n") with puts("Goodbye!"), which is simpler and is supposed to be equivalent. I've sneakily provided my custom puts function, so that gets called instead.


Do we share the prime cluster? The prime cluster of an integer N higher than 2 is defined as the pair formed by the highest prime strictly lower than N and the lowest prime strictly higher than N.
Note that following the definition above, if the integer is a prime itself, then its prime cluster is the pair of the primes preceding and succeeding it.
Task
Given two integers integers N, M (N, M ≥ 3), output a truthy / falsy value based on whether N and M have the same prime cluster.
This is code-golf, so the aim is to reduce your byte count as much as possible. Thus, the shortest code in every programming language wins.
Test cases / Examples
For instance, the prime cluster of 9 is [7, 11], because:

7 is the highest prime strictly lower than 9, and
11 is the lowest prime strictly higher than 9.

Similarly, the  the prime cluster of 67 is [61, 71] (note that 67 is a prime).
Truthy pairs

8, 10
20, 22
65, 65
73, 73
86, 84
326, 318
513, 518

Falsy pairs

4, 5
6, 8
409, 401
348, 347
419, 418
311, 313
326, 305

Jelly, 6 4 3 5 4 bytes

rÆPE

Try it online! or Try all test cases.

How it works

rÆPE    Main link. Arguments: N, M
r       Yield the range of integers between N and M, inclusive.
 ÆP     For each integer, yield 1 if it is prime, 0 otherwise.
   E    Yield 1 if all items are equal (none in the range were prime,
        or there's only one item).

Works because two numbers have different prime clusters iff there is a prime between them, or either number is itself prime; unless both numbers are the same, in which case E returns 1 anyway (all items in a single-item array are equal).


Most Compact Code For A Simulated Explosion Can you write a program that renders to screen a group of pixels exploding apart (as in a simple particle engine) and can you do this in any remarkably small number of characters (key strokes)? (Recall the game lemmings, when those little guys would explode and their little pixel pieces fly apart.)

Someone programmed a simple particle system here as a Processing sketch and it is pretty hefty compared to what I think others should be able to accomplish if they tried. But I'd be much more impressed if it someone could do the same in c++ and sdl, or even java or c#.

Python, 245 chars

import random,time
R=lambda:random.randrange(-999,999)/1e3
P=[(40+20j,R()+1j*R())for i in' '*20]
for i in' '*20:
 C=([' ']*80+['\n'])*40
 for p,v in P:C[int(p.real)+81*int(p.imag)]='*'
 print''.join(C);P=[(p+v,v*.95)for p,v in P];time.sleep(.1)


Overlapping String-Blocks Challenge:

Given a list of multi-line strings, overlap them (in the top-left) and output the result.

Example:

Input: ["aaaa\naaaa\naaaa\naaaa","bb\nbb\nbb","c"]
Output:

cbaa
bbaa
bbaa
aaaa

Challenge rules:

Input-format is flexible. You are allowed to get the input as a 2D list of lines (i.e. [["aaaa","aaaa","aaaa","aaaa"],["bb","bb","bb"],["c"]]) or 3D list of characters (i.e. [[["a","a","a","a"],["a","a","a","a"],["a","a","a","a"],["a","a","a","a"]],[["b","b"],["b","b"],["b","b"]],[["c"]]]). You are allowed to take all the inputs one by one through STDIN. Etc.
Output format is strict. You can choose to print or return the multi-line string. (If your language doesn't have any strings, outputting as a 2D list of characters is allowed as alternative. But only if your language doesn't have strings at all.)
The order of the input-list is of course important (but you are allowed to take the input in reverse if you choose to).
Inputs will only contain printable ASCII in the unicode range \$[33,126]\$ (!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~).
Inputs will only be rectangles (so no weird shapes). The output aren't necessary rectangles, though.
Trailing spaces and a single trailing newline is allowed. Leading spaces and/or newlines not.

General rules:

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

Test cases:

Input: ["aaaa\naaaa\naaaa\naaaa","bb\nbb\nbb","c"]
Output:

cbaa
bbaa
bbaa
aaaa

Input: ["12345\n54321","00\n00\n00\n00","001\n011\n012"]
Output:

00145
01121
012
00

Input: ["sm\noo\nmr\nee\nt!\nh_\ni_\nn_\ng_","!@#$%^\n&*()_+\nqwerty\nuiopas","this\nis_a\ntest"]
Output:

this%^
is_a_+
testty
uiopas
t!
h_
i_
n_
g_

JavaScript (Node.js), 24 bytes

Saved 2 bytes thanks to @Grimy

Assumes that the returned string is printed on a terminal that supports ANSI escape codes. Contains the unprintable character ESC, which is escaped (no pun intended) as \x1B below.

a=>`\x1B[2J\x1B[H`+a.join`\x1B[H`

This doesn't work on TIO, but you can Try it online! to see the raw output instead.

How?

The CSI sequences used are:

ED (Erase in Display):

ESC[2J

where \$2\$ means "clear entire screen"
CUP (Cursor Position):

ESC[H

which means "moves the cursor to row \$n\$, column \$m\$" where both \$n\$ and \$m\$ are omitted and implicitly set to \$1\$ (top-left corner of the screen).

Example output


Perform several mathematic operations The task:

You have to input 2 numbers and output the results of several operations done with them.

Details:

Input 2 floating point numbers, x != 0 and y != 0 via stdin, command line or function arguments.
Output x+y,
       x*y,
       x^y (pow(x,y), not x XOR y),
       x-y,
       y-x,
       x/y and
       y/x on STDOUT separated by newlines, commas or spaces.

For languages which doesn't support floats, you may use an external library, implement them yourself or you can not participate :(
Standard loopholes apply, the shortest code in bytes wins. Good luck!

Dyalog APL, 15 bytes

Takes x as left argument and y as right argument.
+,×,*,-,-⍨,÷,÷⍨

Simply a long train of forks (3-trains):
+, the sum, followed by
×, the product, followed by
*, the exponentiation, followed by
-, the difference, followed by
-⍨, the swapped difference, followed by
÷, the ratio, followed by
÷⍨ the swapped ratio
TryAPL online!


Test if given number is a Keith number Since Fibonacci numbers and sequences seems like a popular subject for code golf I thought that it might be a fun challenge to code golf with Keith numbers.

So I propose a challenge that is to create a function that takes an integer and gives back a true or false depending on the number is a Keith number or not.

More about Keith numbers

  In recreational mathematics, a Keith number or repfigit number (short for repetitive Fibonacci-like digit) is a number in the following integer sequence:
  14, 19, 28, 47, 61, 75, 197, 742, 1104, 1537, 2208, 2580, …

Numberphile has a video explaining how to calculate a Keith number. But basically you take the digits of a number. Add them together and then take the last digits of the original number and add them to the sum of the calculation, rinse and repeat. And example to make it clear.

  141 + 4 = 5
  4 + 5 = 9
  5 + 9 = 14

Input

An integer.

Output

True if the number is a Keith number. False if it's not..

Python (78 75)

a=input()
n=map(int,`a`)
while a>n[0]:n=n[1:]+[sum(n)]
print(a==n[0])&(a>9)

n=n[1:]+[sum(n)] does all the magic. It takes every item but the first item of n, sticks on the sum of n (with the first item), then sets that to n.

I wish you could call list on an integer and have the digits seperated.

Returns False on all inputs below 10. Can be 8 characters shorter if it returned True.


Paradox of time travel A man has two devices.

A time machine - He can control this machine by thinking. It allows him to travel from any point in time to another point in time in the past or future (or even the present point in time) in no time at all. Note that if he travels to the past from B to A, then all normal events (time machines, alternators excluded) from A to B must repeat in the exact same way. Then from point B, he is taken back to point A. Thus, a single time travel creates an infinite loop.
Alternator - Realising this problem, he creates another machine. He notices that, even though all physical events get repeated in a loop, his thoughts may be different. Hence this machine was designed to be controllable by thought as well. The machine can be used at any time to provide an alternate future (but not past) with respect to the time he used it.

Example

I'll explain all the details using a lengthy example.

1000 T+250 250 T+0 500 T-200 100 T-50 125 A 225 T-400 500 A 100 T-200 150 T-25 100 T+100 50 A 25

1000 years pass. It is year 1000 now.
He travels from 1000 to 1250.
250 years pass. It is year 1500 now.
He travels from 1500 to 1500. This has no effect (and can be ignored).
500 years pass. It is now year 2000
He travels from 2000 to 1800.
100 years pass. It is year 1900 now.
He travels from 1900 to 1850.
125 years pass: However, this time, as he is in a loop, things are different. 50 years pass from 1850 to 1900. He loops back to 1850. Another 50 years pass from 1850 to 1900. He loops back again. 25 years pass and it is 1875, thus completing 125 years.
He uses the alternator. Now there exists an alternate future to the year 1875, which he is now in. The past has not changed.
225 years pass. It is now year 2100.
He travels from 2100 to 1700.
500 years pass: 175 years from 1700 to 1875 pass normally. No he encounters the alternator again, which means that now a 3rd future has been created post-1875. 325 years pass normally, making it year 2200.
Using an alternator now has no effect (and can be ignored) since there exists only one future to 2200 which has not yet been defined.
100 years pass. It is now 2300.
He travels from 2300 to 2100.
150 years pass: 100 years from 2100 to 2200 pass normally. A second future gets created from 2200. 50 years pass and it is now year 2250.
He is supposed to go from 2250 to 2225. However, there now exist two 2225s in two different timelines. Hence this leads to a paradox, since we cannot determine which point in time he will reach. (We will not assume that he goes to the more recent timeline) Hence this terminates our simulation.
Anything further 100 T+100 50 A 25 is completely ignored since a paradox has occured and our simulation has stopped running.

Hint: If you are struggling to understand the example, imagine time to be like a path you are digging in the earth. If you are time travelling, you are creating a teleporter. If you are using the alternator, you are digging a new path into the wall of an existing path.

Paradox

Assume A, B and C are three points in time (one after another). A paradox is said to have occurred iff:

you are at a point C, there exists an alternator at a point B, there exists more than one future to point B (and you are in one of them), and you attempt to access any point between B and C via time travel.
you are at a point A, there exists an alternator at a point B, there exists more than one future to point B, and you try to access a point C (after B) via time travel.

Input

A series of events, similar to the example. (Format is flexible.)

Output

A truthy/falsey value, indicating whether a paradox has occured.

Challenge

Shortest code (in bytes) wins.

Ruby, 510 460 bytes

p=[0];w=[n=x=0]
i=gets.split.map{|s|
if x!=1
if s[0]=="A"
w<<n
else
if s[0..1]=="T+"
t=n
q=s[2..-1].to_i
if w[-1]==t||(w[-1]>t&&w[-1]<n+q)
w<<w[-1]
n+=q
else
n+=(t<p[-1]&&n+q>p[-1])?q%(p[-1]-n):q
end
elsif s[0..1]=="T-"
t=n
p<<n
n-=s[2..-1].to_i
x=(x==0&&w[-1]>0&&t>w[-1]&&n>w[-1])?1:0
else
t=n
q=s.to_i
if w[-1]==t||(w[-1]>t&&w[-1]<n+q)
w<<w[-1]
n+=q
else
n+=(t<p[-1]&&n+q>p[-1])?q%(p[-1]-n):q
end
end
end
else
break
end}
p x

Input

As per example

Output

0 = No Paradox, 1 = Paradox

Sample

The sample input provided: 1000 T+250 250 T+0 500 T-200 100 T-50 125 A 225 T-400 500 A 100 T-200 150 T-25 100 T+100 50 A 25
returns 1, indicating a paradox occurred.

Notes

This is not only the first codegolf exercise I attempt, but it is also the first Ruby program I have written. Hence, it could probably be even shorter.

Brief Explanation

p: Infinite loops
w: Alternate timelines
n: Now (regardless of timeline)
x: Paradox

Infinite loops will only occur while traveling forward in time. I am happy for any feedback - especially if it is pointing out a better way to solve this.


Build a minifloat adding machine using NAND logic gates A minifloat is a binary representation of a floating-point number that has very few bits.

The minifloat in this question will be defined as an 6-bit number m, which has the following representation:

1 bit to repesent the sign of the number. This bit will be 0 if the number is positive, and 1 if the number is negative.
3 bits to represent the exponent of the number, offset by 3 (i.e. an exponent of 110 actually represents a factor of 23, not 26).

An exponent of 000 refers to a subnormal number. The mantissa refers to the fractional part of a number with an integer part of 0 multiplied by a factor of the lowest possible exponent (in this case, 2-2).

2 bits to represent the mantissa of the number. If the exponent is anything other than 000 or 111, the 2 bits represent the fractional part after a 1.

An exponent of 111 represents infinity if the mantissa is 0, and NaN (not a number) otherwise.

In the Wikipedia article, this would be referred to as a (1.3.2.3) minifloat.

Some examples of this minifloat's representation:

000000 =  0.00 = 0
000110 =  1.10 × 2^(1-3) = 0.375
001100 =  1.00 × 2^(3-3) = 1
011001 =  1.01 × 2^(6-3) = 10
011100 = infinity
011101 = NaN
100000 = -0.00 = -0
100011 = -0.11 × 2^(1-3) = -0.1875 (subnormal)
101011 = -1.11 × 2^(2-3) = -0.875
110100 = -1.00 × 2^(5-3) = -4
111100 = -infinity
111111 = NaN

Your task is to build a network of two-input NAND gates that takes 6 inputs representing a minifloat a and 6 inputs representing a minifloat b, and returns 6 outputs representing the minifloat a + b.

Your network must properly add subnormals. For example, 000001 + 000010 must equal 000011, and 001001 + 000010 = 001010.
Your network must add and subtract infinities properly. Anything finite added to an infinity is the same infinity. Positive infinity plus negative infinity is NaN.
A NaN plus anything must equal a NaN, although which NaN it equals is up to you.
How you handle adding positive zero and negative zero to each other is up to you, although zero plus zero must equal zero.

Your network can implement any of the following rounding rules depending on convenience:

Round down (toward negative infinity)
Round up (toward positive infinity)
Round toward zero
Round away from zero
Round to nearest, with halves rounded according to any of the above rules

To simplify things, you may use AND, OR, NOT, and XOR gates in your diagram, with the following corresponding scores:

NOT: 1
AND: 2
OR: 3
XOR: 4

Each of these scores corresponds to the number of NAND gates that it takes to construct the corresponding gate.

The logic circuit that uses the fewest NAND gates to correctly implement all the above requirements wins.

830 NANDs
It uses 24 NOTs, 145 ANDs, 128 ORs, 33 XORs. It always rounds towards zero, it may return either -0 or +0 for zero values, and I believe it treats Infinities and NaNs correctly:

± INF ± INF = ± INF
± INF + NaN = ± INF
± INF ∓ INF = NaN
± INF + number = ± INF
NaN + NaN = NaN
NaN + number = NaN

Below I have a coded representation of the circuit. I have little experience annotating these types of things, so I don't really know what the typical way to do this is, but every variable is a Boolean so it's clear to see that it describes a circuit. Another thing, I have neither the know-how nor probably the tenacity to try and make a diagram of this, but if there is any easy to use software out there anyone wants to point out I would be interested in taking a look.
a0,a1,a2,a3,a4,a5 = mini0
b0,b1,b2,b3,b4,b5 = mini1

neg = XOR(a0,b0)
nneg = NOT(neg)

na1 = NOT(a1)
na2 = NOT(a2)
na3 = NOT(a3)

a2_a3 = AND(a2,a3)
a2_na3 = AND(a2,na3)
na2_a3 = AND(na2,a3)
na2_na3 = AND(na2,na3)

a123 = AND(a1,a2_a3)
l0 = AND(a1,a2_na3)
l1 = AND(a1,na2_a3)
l2 = AND(a1,na2_na3)
l3 = AND(na1,a2_a3)
l4 = AND(na1,a2_na3)
l5 = AND(na1,na2_a3)
l6 = AND(na1,na2_na3)

a45 = OR(a4,a5)
a_nan = AND(a123,a45)
a_inf = AND(a123,NOT(a45))

m0 = l0
m1 = OR(l1,AND(l0,a4))
m2 = OR(l2,OR(AND(l1,a4),AND(l0,a5)))
m3 = OR(l3,OR(AND(l2,a4),AND(l1,a5)))
m4 = OR(l4,OR(AND(l3,a4),AND(l2,a5)))
m5 = OR(l5,OR(AND(l4,a4),AND(l3,a5)))
l5_l6 = OR(l5,l6)
m6 = OR(AND(l4,a5),AND(l5_l6,a4))
m7 = AND(l5_l6,a5)

nb1 = NOT(b1)
nb2 = NOT(b2)
nb3 = NOT(b3)

b2_b3 = AND(b2,b3)
b2_nb3 = AND(b2,nb3)
nb2_b3 = AND(nb2,b3)
nb2_nb3 = AND(nb2,nb3)

b123 = AND(b1,b2_b3)
k0 = AND(b1,b2_nb3)
k1 = AND(b1,nb2_b3)
k2 = AND(b1,nb2_nb3)
k3 = AND(nb1,b2_b3)
k4 = AND(nb1,b2_nb3)
k5 = AND(nb1,nb2_b3)
k6 = AND(nb1,nb2_nb3)

b45 = OR(b4,b5)
b_nan = AND(b123,b45)
b_inf = AND(b123,NOT(b45))

n0 = k0
n1 = OR(k1,AND(k0,b4))
n2 = OR(k2,OR(AND(k1,b4),AND(k0,b5)))
n3 = OR(k3,OR(AND(k2,b4),AND(k1,b5)))
n4 = OR(k4,OR(AND(k3,b4),AND(k2,b5)))
n5 = OR(k5,OR(AND(k4,b4),AND(k3,b5)))
k5_k6 = OR(k5,k6)
n6 = OR(AND(k4,b5),AND(k5_k6,b4))
n7 = AND(k5_k6,b5)

first = n0,n1,n2,n3,n4,n5,n6,n7

i7 = n7
i6 = XOR(n6,n7)
carry_6 = OR(n6,n7)
i5 = XOR(n5,carry_6)
carry_5 = OR(n5,carry_6)
i4 = XOR(n4,carry_5)
carry_4 = OR(n4,carry_5)
i3 = XOR(n3,carry_4)
carry_3 = OR(n3,carry_4)
i2 = XOR(n2,carry_3)
carry_2 = OR(n2,carry_3)
i1 = XOR(n1,carry_2)
carry_1 = OR(n1,carry_2)
i0 = XOR(n0,carry_1)
i_sign = OR(n0,carry_1)

n7 = OR(AND(nneg,n7),AND(neg,i7))
n6 = OR(AND(nneg,n6),AND(neg,i6))
n5 = OR(AND(nneg,n5),AND(neg,i5))
n4 = OR(AND(nneg,n4),AND(neg,i4))
n3 = OR(AND(nneg,n3),AND(neg,i3))
n2 = OR(AND(nneg,n2),AND(neg,i2))
n1 = OR(AND(nneg,n1),AND(neg,i1))
n0 = OR(AND(nneg,n0),AND(neg,i0))
n_sign = AND(neg,i_sign)

r7 = XOR(m7,n7)
carry_7 = AND(m7,n7)
hr6 = XOR(m6,n6)
hcarry_6 = AND(m6,n6)
r6 = XOR(hr6,carry_7)
carry_6 = OR(hcarry_6,AND(hr6,carry_7))
hr5 = XOR(m5,n5)
hcarry_5 = AND(m5,n5)
r5 = XOR(hr5,carry_6)
carry_5 = OR(hcarry_5,AND(hr5,carry_6))
hr4 = XOR(m4,n4)
hcarry_4 = AND(m4,n4)
r4 = XOR(hr4,carry_5)
carry_4 = OR(hcarry_4,AND(hr4,carry_5))
hr3 = XOR(m3,n3)
hcarry_3 = AND(m3,n3)
r3 = XOR(hr3,carry_4)
carry_3 = OR(hcarry_3,AND(hr3,carry_4))
hr2 = XOR(m2,n2)
hcarry_2 = AND(m2,n2)
r2 = XOR(hr2,carry_3)
carry_2 = OR(hcarry_2,AND(hr2,carry_3))
hr1 = XOR(m1,n1)
hcarry_1 = AND(m1,n1)
r1 = XOR(hr1,carry_2)
carry_1 = OR(hcarry_1,AND(hr1,carry_2))
hr0 = XOR(m0,n0)
hcarry_0 = AND(m0,n0)
r0 = XOR(hr0,carry_1)
carry_0 = OR(hcarry_0,AND(hr0,carry_1))
r_sign = XOR(n_sign,carry_0)

s7 = r7
s6 = XOR(r6,r7)
carry_6 = OR(r6,r7)
s5 = XOR(r5,carry_6)
carry_5 = OR(r5,carry_6)
s4 = XOR(r4,carry_5)
carry_4 = OR(r4,carry_5)
s3 = XOR(r3,carry_4)
carry_3 = OR(r3,carry_4)
s2 = XOR(r2,carry_3)
carry_2 = OR(r2,carry_3)
s1 = XOR(r1,carry_2)
carry_1 = OR(r1,carry_2)
s0 = XOR(r0,carry_1)

n_r_sign = NOT(r_sign)
r0 = OR(AND(n_r_sign,r0),AND(r_sign,s0))
r1 = OR(AND(n_r_sign,r1),AND(r_sign,s1))
r2 = OR(AND(n_r_sign,r2),AND(r_sign,s2))
r3 = OR(AND(n_r_sign,r3),AND(r_sign,s3))
r4 = OR(AND(n_r_sign,r4),AND(r_sign,s4))
r5 = OR(AND(n_r_sign,r5),AND(r_sign,s5))
r6 = OR(AND(n_r_sign,r6),AND(r_sign,s6))
r7 = OR(AND(n_r_sign,r7),AND(r_sign,s7))

h0 = r0
rest = h0
h1 = AND(r1,NOT(rest))
rest = OR(rest,h1)
h2 = AND(r2,NOT(rest))
rest = OR(rest,h2)
h3 = AND(r3,NOT(rest))
rest = OR(rest,h3)
h4 = AND(r4,NOT(rest))
rest = OR(rest,h4)
h5 = AND(r5,NOT(rest))
rest = OR(rest,h5)
h6 = AND(r6,NOT(rest))
rest = OR(rest,h6)
h7 = AND(r7,NOT(rest))

e0 = OR(h0,OR(h1,h2))
e1 = OR(h0,OR(h3,h4))
e2 = OR(h1,OR(h3,h5))

ne0 = NOT(e0)
ne1 = NOT(e1)
ne2 = NOT(e2)

e0e1 = AND(e0,e1)
e0ne1 = AND(e0,ne1)
ne0e1 = AND(ne0,e1)
ne0ne1 = AND(ne0,ne1)

x0 = AND(e0e1,  ne2)
x1 = AND(e0ne1, e2 )
x2 = AND(e0ne1, ne2)
x3 = AND(ne0e1, e2 )
x4 = AND(ne0e1, ne2)
x5 = AND(ne0ne1,e2 )
x6 = AND(ne0ne1,ne2)

u0 = AND(x0,r1)
u1 = AND(x1,r2)
u2 = AND(x2,r3)
u3 = AND(x3,r4)
u4 = AND(x4,r5)
u5 = AND(x5,r6)
u6 = AND(x6,r6)

v0 = AND(x0,r2)
v1 = AND(x1,r3)
v2 = AND(x2,r4)
v3 = AND(x3,r5)
v4 = AND(x4,r6)
v5 = AND(x5,r7)
v6 = AND(x6,r7)

f0 = OR(u0,OR(u1,OR(u2,OR(u3,OR(u4,OR(u5,u6))))))
f1 = OR(v0,OR(v1,OR(v2,OR(v3,OR(v4,OR(v5,v6))))))
sign = XOR(a0,r_sign)

either_nan = OR(a_nan,b_nan)
either_inf = OR(a_inf,b_inf)
ans_nan = OR(AND(AND(a_inf,b_inf),XOR(a0,b0)),AND(NOT(either_inf),either_nan))
nans_nan = NOT(ans_nan)
ans_inf = AND(nans_nan,OR(either_nan,either_inf))
ans_none = AND(nans_nan,NOT(ans_inf))
nans_none = NOT(ans_none)

result0 = OR(OR(AND(a_inf,a0),AND(b_inf,b0)),AND(ans_none,sign))
result1 = OR( nans_none, AND(ans_none,e0) )
result2 = OR( nans_none, AND(ans_none,e1) )
result3 = OR( nans_none, AND(ans_none,e2) )
result4 = OR( ans_nan, AND(ans_none,f0) )
result5 = OR( ans_nan, AND(ans_none,f1) )


How many mesas begin with a given string? Let's call a non-empty list of strings a mesa if the following conditions hold:

Each listed string is non-empty and uses only characters that occur in the first string.
Each successive string is exactly one character longer than the preceding string.
No string in the list is a subsequence of any other string in the list.

The term "mesa" is from visualizing like this (where the xs are to be various characters):
    xx..x
    xx..xx
    xx..xxx
    .
    .
    .
    xx..xxx..x

NB: It's a mathematical fact that only finitely many mesas begin with a given string. Note the distinction between subsequence vs.  substring; e.g., 'anna' is a subsequence (but not a substring) of 'banana'.
Challenge:

Write the shortest program that takes an arbitrary non-empty alphanumeric input string and outputs the number of mesas that begin with that string.

Input (stdin):

Any non-empty alphanumeric string.

Output (stdout):

The number of mesas that begin with the input string.

Scoring:

The winner is the program with the least number of bytes.

Example mesas
Only one mesa starts with a:
a

Only one mesa starts with aa:
aa

Many mesas start with ab:
ab        ab        ab        ab        (and so on)
          baa       aaa       bbb
                    bbba      bbaa
                              baaaa
                              aaaaaa

Ruby, 142 characters
m=->l{[*l[0].chars].repeated_permutation(l[-1].size+1).reduce(1){|s,x|l.any?{|y|x*''=~/#{[*y.chars]*'.*'}/}?s:s+m[l+[x*'']]}}
p m[[gets.chop]]

This algorithm is constructive, i.e. it builds all possible mesas for the input string and counts them. It makes the program really, really slow - but hey, it is codegolf.
Example runs:
> a
1
> aa
1
> ab
43


Solve the CodeSprint4 Leibniz code golf challenge in Python in 66 characters Check out this challenge:
https://www.hackerrank.com/codesprint4/challenges/leibniz
(The competition has already ended, so I'm just curious about the Python solution, which the organizers refused to reveal, so this is not cheating in any way.)
Modified from that page:

In Calculus, the Leibniz formula for \$\pi\$ is given by:
$$\sum_{n=0}^\infty \dfrac{\left(-1\right)^n}{2n+1}$$
You will be given an integer \$n\$. Your task is to print the summation of the Leibniz formula up to the \$n\$th term of the series correct to 15 decimal places.
That is given \$n\$ calculate:
$$\sum_{k=0}^n \dfrac{\left(-1\right)^k}{2k+1}$$
with the first 15 decimal places correct.
Input Format
The first line contains the number of test cases (\$T\$) which is less than 100. Each additional line is a test case for a positive integer value less than 10^7.
Output Format
Output \$T\$ lines each containing the calculated result for the corresponding line of the input.
Scoring
This is code-golf.

I only managed to solve the challenge in 77 characters. (Talking only about Python here.) However, one adr2370 managed to solve the challenge in 66 characters!
Please help me find the 66-character solution! I'm very very curious because I had to work really hard to bring mine down to 77, and I'm amazed as to how someone came up with a 66-character solution.
For reference, my solution:
for j in'x'*input():print'%.15f'%sum((-1)**i/(2.*i+1)for i in range(input()))

Python, 65 characters

exec'print`sum((-1.)**x/(x-~x)for x in range(input()))`;'*input()


Determine if land is fully enclosed by fences Imagine a two-dimensional array of boolean values, where the 0s represent squares of grass on a rectangular plot of land and the 1s represent fences.

Write a function that accepts the 2D array as an input and determines whether you can travel from any one area of grass to any other area of grass, using only north/east/west/south movements, without running into a fence.

If any area of grass in the array is fully enclosed by fences (meaning you can't travel N/E/W/S to reach every other area of grass in the array) the function should return false; otherwise, it should return true.

Below are two sample arrays you can use as inputs, although your function should be able to handle not just these but any 2D array of boolean values:

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

(should return true)

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

(should return false, since the middle 0 in the top row is fully enclosed)

Shortest working code wins.  I'll pick the winner after either a week has passed or there have been no new submissions within 24 hours.


Create a codeblock tool When using Markup, like on the SE network, an indentation of four spaces before a line of text denotes it as part of a code block, as I hope you know. If you don't, here's an example (with . representing a space):

....Code
....More code

results in

Code
More code

The problem is, when you copy-paste code into an answer, you need to indent each line manually. This is especially difficult when working with ungolfed code, as it's likely already indented and can cause confusion. You can just select your code and hit Ctrl + K, it turns out. Hours of my life wasted for no reason aside...

So, your goal is, given an input, return it with four spaces before each line. In the spirit of saving time copy-pasting, you are to process the entire input as a single string (so long as your language can parse it). If your language is unable to process a character (such as newlines) in strings, you may assume it is denoted/escaped through some other method supported by the language; however, the output must output each line on its own line (so no passing something like ....foo\n....bar).

Standard loopholes not allowed. As this is code-golf, the shortest answer in bytes wins. Good luck!

V, 4 bytes

Î4É

Try it online!

(Note the trailing space)

V is encoded in Latin1, where this is encoded like so:

00000000: ce34 c920                                .4.

Explanation

Î            " On every line
 4É<space>   " Prepend 4 spaces

Here's a solution that is also 4 bytes in UTF-8!

VG4>

VG          " Select everything
   >        " Indent
  4         " 4 times (with spaces)


Remove an unobstructed rectangle This image was made by overlaying 7 differently colored rectangles on top of each other:

The black and maroon rectangles are unobstructed, that is, no other rectangles are above them.
Write a program that takes in an image such as this and remove any single unobstructed rectangle, outputting the resulting image.

Example
If you ran your program on the image above and kept re-running it on the output, it might progress like this.
Run 1 - Black removed (could have been maroon):

Run 2 - Maroon removed (only choice):

Run 3 - Yellow removed (only choice):

Run 4 - Blue removed (could have been green):

Run 5 - Green removed (only choice):

Run 6 - Brown removed (only choice):

Run 7 - Red removed (only choice):

Any additional runs should produce the same white image.
Hopefully Stack Exchange has not lossily compressed any of these
images.

The image will always have a white background and each rectangle will be a unique RGB color that isn't white.
You can assume that the image can always be interpreted as a set of overlapping rectangles. Specifically, you can assume that, for a particular color, the pixel with that color closest to the top of the image is part of the top edge of that color's rectangle. The same holds for the bottom, left, and right edges.
So, for example, in this image, the top edge of the red rectangle would be just below the bottom edge of the yellow rectangle, as the the orange rectangle covered the old red top edge:

In this image, the red rectangle could be removed first (along with black/maroon/orange/gray):

When the order of the lower rectangles is ambiguous, you can give them any order.
For example, the left image here could become the middle or the right:

The output should not have paradoxical overlaps (so making it with the painter's algorithm should be possible). So in this image (thanks user23013), it would have to be green under the orange rectangle:

Additional Details

The image and rectangles may have any dimensions.
The rectangles may touch the image border.
There may be up to 2563 - 1 rectangles.
If the input is entirely white, the output should be as well.
You may use image libraries.
The input should be the image file name or the raw image data. It can come from stdin or the command line.
The output can be written to the same or another image file, spewed raw to stdout, or simply displayed.
Any common lossless truecolor image file format is allowed.

The submission with the fewest bytes wins.

CJam, 241 bytes
(with newlines removed.)
rri:Hri:Vri:Q[q~]3/_Qa3*a+_|$W%:Pf{\a#}:AH/:B0ff*
P,,[AHAW%HBz:+_W%V\V]2/
ff{~@@f=/::|1#}0Ua4*t:R;
P0f<
V{H{BI=J=_2$=
0R{"I>! I+V<J>! J+H<"4/+4/z{~~}%:&1$*\)}%);2$-|t
}fJ}fI
[P,{_La#\1$0t1$f-}*;;]
{:TR=2/~\~V\-,>\f{\_3$=@~H\-,>{Tt}/t}~}/
:~Pf=:~
~]S*N

It uses the ppm file format. Example usage (using ImageMagick):
convert IVYvE.png -compress none ppm:-| (time /path/to/cjam-0.6.4.jar 1.cjam) |display

Well, it is too long and too slow... Runs about a minute for the example.
I resized the test cases (and added some others) to make testing easier.

It seems the color space informations are lost so the colors are slightly different.


How many cardboard digits do I need? I need to prepare digits made of cardboard to display some number (example). I don't know beforehand which number I should display - the only thing I know is that it's not greater than n.

How many cardboard digits should I prepare?

Example: n = 50

To display any number in the range 0...50, I need the following digits:

A zero, for displaying the number 0, or any other round number
Two copies of digits 1, 2, 3 and 4, for displaying the corresponding numbers
One copy of digits 5, 6, 7 and 8, for the case they appear as least significant digit in the number
The digit 9 is never needed, because I can use the inverted digit 6 instead

Total: 13 digits

Test cases (each line is a test case in the format "input; output")

0 1
1 2
9 9
11 10
50 13
99 17
100 18
135 19
531 22
1000 27
8192 34
32767 38

Jelly, 9 bytes

‘ḶDœ|/ḟ9L

Try it online!

How it works

‘ḶDœ|/ḟ9L
‘Ḷ         [0,1,...,n]
  D        convert each to list of its digits
   œ|/     fold by multiset union
      ḟ9   remove 9
        L  length


A golfed golfing game You have to make a golf game with the following specification :-

The field is 10 X 10 characters without spaces.

Free ground is represented by .

A hole generated at random(not at 0,0) is shown by O (its alphabet and not zero).

The ball starts at 0,0 represented by X.

You can hit the ball with input d 4 (meaning direction to the bottom with magnitude of 4 characters after the ball more like vectors in physics).
Example:
X.........
..........
..........
..........
..........
..........
..........
..........
..........
.........O
score : 0
b 4

But, since you are not so good at golfing therefore the force you think is applied is often only close to the actual force that is applied !(if x the offset in force then -2 < X < +2)

you should have to tell the real force applied and display the ball moved to that real force like this :-
lets say the ball actually moved by 3.

..........
..........
..........
X.........
..........
..........
..........
..........
..........
.........O
score : 1
applied force : 4
real force    : 3

The four directions are U (up), D (down), l (left), r (right) and magnitude of force should be between 0 and 10 (excluding both 0 and 10).

The ball should not bounce off the edges, if the force reaches that much then the the ball stops at the last point at the boundary.
r 9

..........
..........
..........
.........X
..........
..........
..........
..........
..........
.........O
score : 2
applied force : 9
real force    : 11

In the end when the game is finished you have to display Par in <n> shots! (where n is score)

Coding:

You have to design a working program showing the exact output.
post the code in golfed and ungolfed versions.
also post a successful test run (images if possible).
No use of functions or languages excessively specialized to this task (I don't know if they really exist!)

Winner:
Winner will be chosen 1 week from now.
Winner is the submission with least characters.
And, most important thing
Best of luck :)

Scala, 605

Golfed:
import scala.util.Random;object G extends App{var b,h=(0,0);while(b==h)h =(Random.nextInt(10),Random.nextInt(10));var s=0;def f{for(y<- 0 to 9){for(x<- 0 to 9)print(if(b==(x,y))"X"else if(h==(x,y))"O"else ".");println};println("score : "+s)};f;while(b!=h){val i=readLine.split(" ");val x=i(1).toInt.ensuring(a=>a>0&&a<10)-1+Random.nextInt(3);b=i(0).toLowerCase match{case "d"=>(b._1,b._2+x) case "u"=>(b._1,b._2-x) case "r"=>(b._1+x,b._2) case "l"=>(b._1-x,b._2)};b=(b._1.min(9).max(0),b._2.min(9).max(0));s+=1;f;println("applied force : "+i(1));println("real force : "+x)};println("Par in "+s+" shots!")}

Just a straight-forwardly implemented ice-breaker. Input is read line-by-line from stdin and power lower then 1 or higher then 9 will result in an AssertionError to comply with the specs.
I am pretty sure there are shorter programs, but let's see how far we get ;-)
Ungolfed:
import scala.util.Random

object Golf extends App {
  var b, h = (0, 0)
  while (b == h) h = (Random.nextInt(10), Random.nextInt(10))
  var s = 0

  def field {
    for (y <- 0 to 9) {
      for (x <- 0 to 9)
        print(if (b ==(x, y)) "X" else if (h ==(x, y)) "O" else ".")
      println
    }
    println("score : " + s)
  }
  field
  while (b != h) {
    val i = readLine.split(" ")
    val x = i(1).toInt.ensuring(a => a > 0 && a < 10) - 1 + Random.nextInt(3)
    b = i(0).toLowerCase match {
      case "d" => (b._1, b._2 + x)
      case "u" => (b._1, b._2 - x)
      case "r" => (b._1 + x, b._2)
      case "l" => (b._1 - x, b._2)
    }
    b = (b._1.min(9).max(0), b._2.min(9).max(0))
    s += 1
    field
    println("applied force : " + i(1))
    println("real force : " + x)
  }
  println("Par in " + s + " shots!")
}

Random example run:

X......O..
..........
..........
..........
..........
..........
..........
..........
..........
..........
score : 0

r 8
.......OX.
..........
..........
..........
..........
..........
..........
..........
..........
..........
score : 1
applied force : 8
real force : 8

l 1
.......OX.
..........
..........
..........
..........
..........
..........
..........
..........
..........
score : 2
applied force : 1
real force : 0

l 1
.......X..
..........
..........
..........
..........
..........
..........
..........
..........
..........
score : 3
applied force : 1
real force : 1
Par in 3 shots!


Make a string into a triangle Challenge

Given a string, make it into a triangle as shown below:

Input

Hello, world!

Output

H
He
Hel
Hell
Hello
Hello,
Hello,
Hello, w
Hello, wo
Hello, wor
Hello, worl
Hello, world
Hello, world!

The first line contains the first character of the string. The following lines contain one more character on each line, until the full length of the original string is reached.

If you receive a one character string, just output it.

You will never receive an empty string.

Rules

Standard loopholes apply, as usual
This is code-golf, shortest solution wins.


Paint by Numbers (using programming, not numbers) Your task is to create a program which takes a black-and-white outlined image (example images are below) and fills it in with colour. It is up to you how you section off each region and which colour to fill it with (you could even use an RNG).

For example:

As you can see I am clearly an artist of a superior calibre when it comes to MS Paint.

Scoring

This is a popularity contest, so the answer with the most net votes wins. Voters are encouraged to judge answers by

Input criterion: any image that consists of white/light-grey background and black/dark-grey outlines
How well the colouring is done; meaning few or no areas are white unlike the above (unless you obviously intend to use white e.g. for clouds)
Customisability of the colours used in certain sections
How well the system works on a range of different images (of varying detail)
Post how long your program takes per image. We might not be playing code golf, but shorter, faster and more efficient code should be regarded as better
Should output the new image either onto the screen or to a file (no larger than 2MB so that it can be shown in the answer)
Please justify why you chose to output to that image type and comment/explain the workings of your code
The applicability of the colour used to the respective shape it is bound by (realistic colour scheme i.e. grass is green, wooden fences are brown etc.)

  "I could randomly color each area, but if I could identify the "fence" and make it similarly colored, then that's
  something that deserves upvotes." - NathanMerrill

Seeing as this is a popularity contest, you can also optionally judge by:

Overall appeal (how good the image looks)
Artistic flair; if you can program in shading or watercolour-style colouring etc.

In general, the smallest outputted image (file size) of the highest quality, with the fasted program and the highest public vote will win.

If you have other judging specifications that you think should be used, please recommend them in the comments of this post.

Examples

I own nothing; all example images are of a creative commons license.

Source: https://pixabay.com/ro/stejar-arbore-schi%C5%A3%C4%83-natura-303890/

Source: http://www.freestockphotos.biz/stockphoto/10665

Source: http://crystal-rose1981.deviantart.com/art/Dragon-Tattoo-Outline-167320011

Source: http://jaclynonacloudlines.deviantart.com/art/Gryphon-Lines-PF-273195317

Source: http://captaincyprus.deviantart.com/art/Dragon-OutLine-331748686

Source: http://electric-meat.deviantart.com/art/A-Heroes-Farewell-280271639

Source: http://movillefacepalmplz.deviantart.com/art/Background-The-Pumpkin-Farm-of-Good-old-Days-342865938

EDIT: Due to anti-aliasing on lines causing non-black/white pixels and some images that may contain grey instead of black/white, as a bonus challenge you can attempt to deal with it. It should be easy enough in my opinion.

Spectral airbrushing (Python, PIL, scipy)

This uses a sophisticated mathematical algorithm to produce colourful nonsense. The algorithm is related to Google's PageRank algorithm, but for pixels instead of web pages.

I took this approach because I thought that unlike flood-fill based methods it might be able to cope with images like the chicken and the tree, where there are shapes that aren't entirely enclosed by black lines. As you can see, it sort of works, though it also tends to colour in different parts of the sky in different colours

For the mathematically minded: what it's doing is essentially constructing the adjacency graph of the while pixels in the image, then finding the top 25 eigenvectors of the graph Laplacian. (Except it's not quite that, because we do include the dark pixels, we just give their connections a lower weight. This helps in dealing with antialiasing, and also seems to give better results in general.) Having found the eigenvectors, it creates a random linear combination of them, weighted by their inverse eigenvalues, to form the RGB components of the output image.

In the interests of computation time, the image is scaled down before doing all this, then scaled back up again and then multiplied by the original image. Still, it does not run quickly, taking between about 2 and 10 minutes on my machine, depending on the input image, though for some reason the chicken took 17 minutes.

It might actually be possible to turn this idea into something useful, by making an interactive app where you can control the colour and intensity of each of the eigenvectors. That way you could fade out the ones that divide the sky into different sections, and fade in the ones that pick up on relevant features of the image. But I have no plans to do this myself :)

Here are the output images:

(It didn't work so well on the pumpkins, so I omit that one.)

And here is the code:

import sys
from PIL import Image
import numpy as np
import scipy.sparse as sp
import scipy.sparse.linalg as spl
import os
import time

start_time = time.time()

filename = sys.argv[1]
img = Image.open(filename)
orig_w, orig_h = img.size

# convert to monochrome and remove any alpha channel
# (quite a few of the inputs are transparent pngs)
img = img.convert('LA')
pix = img.load()
for x in range(orig_w):
    for y in range(orig_h):
        l, a = pix[x,y]
        l = (255-a) + a*l/255
        a = 255
        pix[x,y] = l,a
img = img.convert('L')

orig_img = img.copy()

# resize to 300 pixels wide - you can get better results by increasing this,
# but it takes ages to run
orig_w, orig_h = img.size
print "original size:", str(orig_w)+ ', ' + str(orig_h)
new_w = 300
img = img.resize((new_w, orig_h*new_w/orig_w), Image.ANTIALIAS)

pix = img.load()
w, h = img.size
print "resizing to", str(w)+', '+str(h)

def coords_to_index(x, y):
    return x*h+y

def index_to_coords(i):
    return (int(i/h), i%h)

print "creating matrix"

A = sp.lil_matrix((w*h,w*h))

def setlink(p1x, p1y, p2x, p2y):
    i = coords_to_index(p1x,p1y)
    j = coords_to_index(p2x,p2y)
    ci = pix[p1x,p1y]/255.
    cj = pix[p2x,p2y]/255.
    if ci*cj > 0.9:
        c = 1
    else:
        c =  0.01
    A[i,j] = c
    return c

for x in range(w):
    for y in range(h):
        d = 0.
        if x>0:
            d += setlink(x,y,x-1,y)
        if x<w-1:
            d += setlink(x,y,x+1,y)
        if y>0:
            d += setlink(x,y,x,y-1)
        if y<h-1:
            d += setlink(x,y,x,y+1)
        i = coords_to_index(x,y)
        A[i,i] = -d

A = A.tocsr()

# the greater this number, the more details it will pick up on. But it increases
# execution time, and after a while increasing it won't make much difference
n_eigs = 25

print "finding eigenvectors (this may take a while)"
L, V = spl.eigsh(A, k=n_eigs, tol=1e-12, which='LA')

print "found eigenvalues", L

out = Image.new("RGB", (w, h), "white")
out_pix = out.load()

print "painting picutre"

V = np.real(V)
n = np.size(V,0)
R = np.zeros(n)
G = np.zeros(n)
B = np.zeros(n)

for k in range(n_eigs-1):
    weight = 1./L[k]
    R = R + V[:,k]*np.random.randn()*weight
    G = G + V[:,k]*np.random.randn()*weight
    B = B + V[:,k]*np.random.randn()*weight

R -= np.min(R)
G -= np.min(G)
B -= np.min(B)
R /= np.max(R)
G /= np.max(G)
B /= np.max(B)

for x in range(w):
    for y in range(h):
        i = coords_to_index(x,y)
        r = R[i]
        g = G[i]
        b = B[i]
        pixval = tuple(int(v*256) for v in (r,g,b))
        out_pix[x,y] = pixval

out = out.resize((orig_w, orig_h), Image.ANTIALIAS)
out_pix = out.load()
orig_pix = orig_img.load()

for x in range(orig_w):
    for y in range(orig_h):
        r,g,b = out_pix[x,y]
        i = orig_pix[x,y]/255.
        out_pix[x,y] = tuple(int(v*i) for v in (r,g,b))

fname, extension = os.path.splitext(filename)
out.save('out_' + fname + '.png')

print("completed in %s seconds" % (time.time() - start_time))


Un-average temperatures! There was a discussion going on in TNB once about the best temperature scale, and we agreed on something: Take the average of all four main temperature scales! That is, Celsius, Kelvin, Fahrenheit, and Rankine (Sorry Réaumur).

So, now the issue is, most people don't use this system. So, I need a program to convert back from this average!

Challenge

Given the average of the Celsius, Fahrenheit, Kelvin, and Rankine representations of a certain temperature, output the individual standard representations, in any prespecified and consistent order. It turns out that this is possible, based on my whiteboard calculations. Input will be a single floating-point value in whatever range your language can handle, and output will be four floating-point values in any reasonable format. You can restrict the input to force the output to be in the range of your language, but you must be able to support down to Absolute Zero (thus, you need to be able to handle negative numbers).

Test Cases

input -> (Celsius, Fahrenheit, Kelvin, Rankine)
100 -> (-70.86071428571424, -95.54928571428565, 202.28928571428574, 364.12071428571437)
20 -> (-128.0035714285714, -198.4064285714286, 145.14642857142857, 261.2635714285714)
-10 -> (-149.43214285714282, -236.97785714285715, 123.71785714285716, 222.69214285714287)
10000 -> (7000.567857142858, 12633.022142857144, 7273.717857142858, 13092.692142857144)

These values were generated with Uriel's Python program, and I verified that they were correct.

Python, 63 bytes
def f(a):x=(a+183.205)*5/7;m=x*9/5;return x-273.15,m-459.67,x,m

a is the average, returns a tuple of the results as (celsius, fahrenheit, kelvin, rankine)
Math involved:
kelvin = x
celsius = x - 273.15
fahrenheit = x * 9/5 - 459.67
rankine = x * 9/5

a = (x + x - 273.15 + x * 9/5 - 459.67 + x * 9/5) / 4 = x * 7/5 - 183.205
x = (a + 183.205) * 5/7


Want to see a Magic Card Trick? The first magic card trick I ever learned as a child was the following:

Have 1 deck of cards where the pattern on the back is not vertically symmetric.
Organize all cards to be facing one direction.
Ask an individual to, "pick a card, any card, memorize it and give it back to you".
Proceed to put it into the deck (in the wrong direction).
Shuffle vigorously, giving the illusion that you won't know where their card is.
Produce their card to their amazement.

This trick is obviously a little bit lack-luster in nature now-a-days, however it makes for a good challenge. Write a program, that when given no input, outputs a randomly shuffled deck of cards with one of the cards, chosen at random, reversed. However, when the input is a deck of cards with one card reversed, you must output the reversed card (in the correct order).

The Deck of Cards
A deck of cards is defined to be:
[2S,3S,4S,5S,6S,7S,8S,9S,TS,JS,QS,KS,AS,
 2D,3D,4D,5D,6D,7D,8D,9D,TD,JD,QD,KD,AD,
 2H,3H,4H,5H,6H,7H,8H,9H,TH,JH,QH,KH,AH,
 2C,3C,4C,5C,6C,7C,8C,9C,TC,JC,QC,KC,AC]

A card is defined as it's number, then the first letter of its suit. The reverse of a card is the exact opposite, the first letter of its suit followed by a number.
The Drawn Card
Example, if the card we randomly chose to reverse was the 4 of Clubs (4C), we'd end up with (without shuffling, obviously):
[2S,3S,4S,5S,6S,7S,8S,9S,TS,JS,QS,KS,AS,
 2D,3D,4D,5D,6D,7D,8D,9D,TD,JD,QD,KD,AD,
 2H,3H,4H,5H,6H,7H,8H,9H,TH,JH,QH,KH,AH,
 2C,3C,C4,5C,6C,7C,8C,9C,TC,JC,QC,KC,AC]

The Shuffling
Then, after shuffling:
[2H,2C,6S,4D,QH,6C,TD,8C,7H,5H,C4,3D,7S,7C,KC,QD,QC,JS,7D,6D,2S,5C,KD,3C,3S,2D,8H,KH,6H,AH,8S,JH,TS,AD,5D,9H,4H,JD,QS,4S,JC,3H,8D,TC,AS,TH,KS,AC,9C,9S,5S,9D]

This is a valid output given empty input.
The Deck Input
However, conversely, when our program receives the above output as input, it should output 4C. That is to say, for an input of:
[2H,2C,6S,4D,QH,6C,TD,8C,7H,5H,C4,3D,7S,7C,KC,QD,QC,JS,7D,6D,2S,5C,KD,3C,3S,2D,8H,KH,6H,AH,8S,JH,TS,AD,5D,9H,4H,JD,QS,4S,JC,3H,8D,TC,AS,TH,KS,AC,9C,9S,5S,9D]

You iterate through until you find the reversed card, and return it, reversed back to the normal state. So here we'd find C4, know that C isn't a number, and return it as 4C, which is correct.

Rules

You may not load the deck from any external sources.
An empty input should result in a randomly shuffled deck with 1 random card reversed.
A deck of cards with 1 card reversed as input should result in the reversed card.
Any other inputs can result in explosive llamas riding segways through a futuristic tube.

Or anything else, for that matter.

Both the chosen card and the shuffling order must be uniformly random.

I.E. all cards have equal chance of being selected to be reversed.
I.E. all combinations of cards have an equal chance of appearing.

You may use SHCD or shcd for the suits, but be consistent:

If you choose uppercase suits (SHCD) you must also use TJQKA.
If you choose lowercase suits (shcd) you must also use tjqka.

This is code-golf, winner is lowest bytes.

Retina, 61 60 59 bytes

G`[HCDS].
^$
23456789TJQK
/^2/&L$`.
$&H¶$&D¶$&C¶$&S
@V`
O?`

Try it online! Edit: Saved 1 2 bytes thanks to @MartinEnder. Explanation:

G`[HCDS].

Delete all unreversed cards. This should leave one reversed card or no cards.

^$
23456789TJQK
/^2/&L$`.
$&H¶$&D¶$&C¶$&S

If the input is (now) empty, create a pack of cards.

@V`

Randomly select one card and reverse it (unreverses the single reversed card).

O?`

Shuffle the card(s).


Find the closest HTML colour name Input
A single hex 6-digit colour code, capital letter, without #. Can also be a 24-bit integer if you prefer.
Output
The closest HTML color name (e.g red, or dark-salmon, as defined as https://www.w3schools.com/colors/colors_names.asp or see below). Distance is defined by summing the difference in red, green and blue channels.
Examples

FF04FE: magenta
FFFFFF: white
457CCB (halfway between steelblue and darkslateblue): steelblue (round up)

Rules

Standard loopholes apply.
Standard I/O applies
Round up to the color with the higher channel sum if halfway between two colors. If two colours have the same channel sum, output the one which is higher as a hex code: e.g  red = #FF0000 = 16711680 > blue = #0000FF = 256
If one hex code has two names (e.g. grey and gray), output either.
Outputs can be capitalised and hyphenated how you like
Trailing/preceding spaces/newlines are fine
You must output the names in full.
This is code-golf, so shortest answer in bytes wins.

Colors
As per suggestion in the comments, here are all of the color names with respective hex values in CSV format:
Color Name,HEX
Black,#000000
Navy,#000080
DarkBlue,#00008B
MediumBlue,#0000CD
Blue,#0000FF
DarkGreen,#006400
Green,#008000
Teal,#008080
DarkCyan,#008B8B
DeepSkyBlue,#00BFFF
DarkTurquoise,#00CED1
MediumSpringGreen,#00FA9A
Lime,#00FF00
SpringGreen,#00FF7F
Aqua,#00FFFF
Cyan,#00FFFF
MidnightBlue,#191970
DodgerBlue,#1E90FF
LightSeaGreen,#20B2AA
ForestGreen,#228B22
SeaGreen,#2E8B57
DarkSlateGray,#2F4F4F
DarkSlateGrey,#2F4F4F
LimeGreen,#32CD32
MediumSeaGreen,#3CB371
Turquoise,#40E0D0
RoyalBlue,#4169E1
SteelBlue,#4682B4
DarkSlateBlue,#483D8B
MediumTurquoise,#48D1CC
Indigo,#4B0082
DarkOliveGreen,#556B2F
CadetBlue,#5F9EA0
CornflowerBlue,#6495ED
RebeccaPurple,#663399
MediumAquaMarine,#66CDAA
DimGray,#696969
DimGrey,#696969
SlateBlue,#6A5ACD
OliveDrab,#6B8E23
SlateGray,#708090
SlateGrey,#708090
LightSlateGray,#778899
LightSlateGrey,#778899
MediumSlateBlue,#7B68EE
LawnGreen,#7CFC00
Chartreuse,#7FFF00
Aquamarine,#7FFFD4
Maroon,#800000
Purple,#800080
Olive,#808000
Gray,#808080
Grey,#808080
SkyBlue,#87CEEB
LightSkyBlue,#87CEFA
BlueViolet,#8A2BE2
DarkRed,#8B0000
DarkMagenta,#8B008B
SaddleBrown,#8B4513
DarkSeaGreen,#8FBC8F
LightGreen,#90EE90
MediumPurple,#9370DB
DarkViolet,#9400D3
PaleGreen,#98FB98
DarkOrchid,#9932CC
YellowGreen,#9ACD32
Sienna,#A0522D
Brown,#A52A2A
DarkGray,#A9A9A9
DarkGrey,#A9A9A9
LightBlue,#ADD8E6
GreenYellow,#ADFF2F
PaleTurquoise,#AFEEEE
LightSteelBlue,#B0C4DE
PowderBlue,#B0E0E6
FireBrick,#B22222
DarkGoldenRod,#B8860B
MediumOrchid,#BA55D3
RosyBrown,#BC8F8F
DarkKhaki,#BDB76B
Silver,#C0C0C0
MediumVioletRed,#C71585
IndianRed,#CD5C5C
Peru,#CD853F
Chocolate,#D2691E
Tan,#D2B48C
LightGray,#D3D3D3
LightGrey,#D3D3D3
Thistle,#D8BFD8
Orchid,#DA70D6
GoldenRod,#DAA520
PaleVioletRed,#DB7093
Crimson,#DC143C
Gainsboro,#DCDCDC
Plum,#DDA0DD
BurlyWood,#DEB887
LightCyan,#E0FFFF
Lavender,#E6E6FA
DarkSalmon,#E9967A
Violet,#EE82EE
PaleGoldenRod,#EEE8AA
LightCoral,#F08080
Khaki,#F0E68C
AliceBlue,#F0F8FF
HoneyDew,#F0FFF0
Azure,#F0FFFF
SandyBrown,#F4A460
Wheat,#F5DEB3
Beige,#F5F5DC
WhiteSmoke,#F5F5F5
MintCream,#F5FFFA
GhostWhite,#F8F8FF
Salmon,#FA8072
AntiqueWhite,#FAEBD7
Linen,#FAF0E6
LightGoldenRodYellow,#FAFAD2
OldLace,#FDF5E6
Red,#FF0000
Fuchsia,#FF00FF
Magenta,#FF00FF
DeepPink,#FF1493
OrangeRed,#FF4500
Tomato,#FF6347
HotPink,#FF69B4
Coral,#FF7F50
DarkOrange,#FF8C00
LightSalmon,#FFA07A
Orange,#FFA500
LightPink,#FFB6C1
Pink,#FFC0CB
Gold,#FFD700
PeachPuff,#FFDAB9
NavajoWhite,#FFDEAD
Moccasin,#FFE4B5
Bisque,#FFE4C4
MistyRose,#FFE4E1
BlanchedAlmond,#FFEBCD
PapayaWhip,#FFEFD5
LavenderBlush,#FFF0F5
SeaShell,#FFF5EE
Cornsilk,#FFF8DC
LemonChiffon,#FFFACD
FloralWhite,#FFFAF0
Snow,#FFFAFA
Yellow,#FFFF00
LightYellow,#FFFFE0
Ivory,#FFFFF0
White,#FFFFFF

C# (Visual C# Interactive Compiler), 231+21=252 bytes

s=>Color.FromArgb(Convert.ToInt32(s,16));f=s=>Enum.GetNames(typeof(KnownColor)).Select(x=>Color.FromName(x)).Where(x=>!x.IsSystemColor&x.A>254).OrderBy(x=>Math.Abs(x.R-C(s).R)+Math.Abs(x.G-C(s).G)+Math.Abs(x.B-C(s).B)).First().Name

Explanation:

using System.Drawing; //System library that handles Colors in C#

C=s=>Color.FromArgb(Convert.ToInt32(s,16));        //helper method. receives a hex string and returns it's Color

f=s=>Enum.GetNames(typeof(KnownColor))             //collection of color names from the System.Drawing.KnownColor enum
         .Select(x=>Color.FromName(x))             //convert the color names to Colors
             .Where(x=>!x.IsSystemColor&x.A>254)   //filter out unwanted colors
                 .OrderBy(x=>Math.Abs(x.R-C(s).R)  //order by increasing distance
                            +Math.Abs(x.G-C(s).G)
                            +Math.Abs(x.B-C(s).B))
                     .First().Name                 //return the closest color's name

For some reason, Tio complains that the namespace 'Drawing' does not exist in the namespace 'System', despite the source project Mono stating it's compatible. It works fine in VisualStudio though.

EDIT: apparently it hasn't been implemented into Tio yet!

Try it online!


Computing the geometric median Given a list of integer points in an n-dimensional space, output the geometric median. Note that the output is not necessarily integer. Your answer must be precise to at least two digits after the decimal point.

You may assume that n < 16 and that every component of each point fits in a 32-bit signed integer.

You may write a program or a function. You may take input and give output in any reasonable format. You may optionally pass n as a separate argument, instead of having to deduce it.

You must implement an algorithm to compute the geometric median, and not brute force over the output domain.

Examples:

(5), (14), (10), (7)                         -> any 7 <= x <= 10 is valid
(2, 3), (8, 4), (12, -3), (0, 0), (0, 0)     -> (2.17, 1.29)
(0, 0, 3), (20, 7, 3), (13, 14, 15)          -> (13.18, 7.94, 7.23)
(2, 20, 3, 30), (20, 2, 20, 2), (1, 2, 3, 4) -> (5.46, 5.12, 6.84, 8.06)

The answer is only unique if the set of points do not lie on a line. If the answer is not unique, you may return any valid answer.

Matlab, 77 75

I just use the definition of the geometric median with a numerical minimization. In this case I make use of the Nelder-Mead simplex algorithm. It sould always converge as we try to find the minimum of a convex function (according to Wikipedia).

n=@(m)trace((m'*m).^.5);f=@(m)fminsearch(@(y)n(bsxfun(@minus,m,y)),m(:,1))

Old version:
    n=@(m)sum(diag(m'*m).^.5);f=@(m)fminsearch(@(y)n(bsxfun(@minus,m,y)),m(:,1))

The input format is a matix with the input vectors as columns, e.g:

m = [[2; 20; 3; 30],[20; 2; 20; 2],[1; 2; 3; 4]];


Output quater-imaginary base numbers in binary Write a function or program that outputs Quater-imaginary base displayed as binary digits. The number base is 2i, where i is the square root of -1. See Complex Number for more details on i. Each digit position can go from 0 to 3 (quaternary), as each real and imaginary part is -4 times as large as the previous real and imaginary part. The quaternary digits in binary are as follows: 0: 00, 1: 01, 2: 10 & 3: 11.

Breakdown of digit positions:

re   im       16 -8i  -4  2i   1 -0.5i, etc.
 4    0        1   0   3   0   0        (quaternary representation)
              01  00  11  00  00        (binary representation)

The number 100110000 is 1x16 + 3x-4 = 16 + -12 = 4.

re   im       16 -8i  -4  2i   1 -0.5i, etc.
 0    5        0   0   0   3   0   2    (quaternary representation)
              00  00  00  11  00 .10    (binary representation)

The number 1100.1 is 3x2i + 2x-0.5i = 6i + -i = 5i.

Your code will take a pair of numbers, which could be integer or floating point, and will output the complex number as a string of binary digits. The first number will be real, the second input number will be the imaginary value. A binary point must only be printed if there are non-zero number positions below 1 (i.e. if any of the positions for -0.5i, -0.25, 0.125i, etc. have a non-zero digit). Leading and trailing zeros are not allowed, except for a single zero digit immediately before the binary point if there are no other digits. The output must not start with a binary point (*00.1 - wrong, 0.1 - right, *.1 - wrong, *0.10 - wrong). You may assume that all input numbers will have finite binary representations.

Test numbers:

re   im            output
 0    0                 0
 1    0                 1
 2    0                10
 3    0                11
 4    0         100110000
-1    0             10011
-2    0             10010
-3    0             10001
 0    1               100.1
 0    2               100
 0    3              1000.1
 0    4              1000
 0   -1                 0.1
 0   -2           1001100
 0   -3           1001100.1
 3    4              1011
 4    3         100111000.1
 6   -9         101110010.1
-6    9       10011100110.1
-9   -6           1110111
 0.5 14.125   10011001101.001001

Note: The output of all integer values will end in .1 if the imaginary part is odd.

Standard code-golf.

JavaScript (ES6), 340 bytes

f=x=>[0,...x.toString(16)].reverse().map(d=>s=d<'.'?s:d<`0`?d+s.slice(0,-1):`${(c=+`0x${d}`+(c>>4)+m^m)>>2&3}${c&3}`+s,c=s='.',m=x<0?3:12)&&s
g=(s,t,n=s.indexOf`.`,m=t.indexOf`.`)=>n<m?g(0+s,t):n>m?g(s,0+t):t[s.length]?g(s+0,t):s.replace(/\d/g,(c,i)=>`${t[i]>>1}${t[i]&1}${c>>1}${c&1}`).replace(/^0+(\d)|\.?0*$/g,'$1')
(r,i)=>g(f(r),f(i/2))

f converts a number into base -4 (with trailing . if the number is an integer). g takes two base -4 numbers, pads them at both ends to the same length and . position, shuffles the digits together, converts everything from base 4 to base 2, then finally strips leading and trailing zeros.

Explanation: To represent the given complex number in modified-base 2i we need to represent the real part and half of the complex part (i.e. dividing the imaginary part by 2i) in base 2i² (i.e. -4), shuffle the digits together, and then convert them from base 4 to base 2. To represent a real number in base -4 we start with the base 4 conversion. Alternate digits have the correct sign (in the case of a positive number, these are the digits in the even positions; in the case of a negative number, these are the digits in the odd positions) but the remaining digits have the wrong sign and a correction needs to be applied. Examples:

 0 -> 000 -> 000 (no correction needed)
 4 -> 010 -> 130 }
 8 -> 020 -> 120 } (correction includes carry)
12 -> 030 -> 110 }

As you can see, the correction is 8 minus the original digit, mod 8. However a slightly more convenient calculation is the original digit, plus 3, xor 3 (indeed in 32-bit integer arithmetic we could simply write +0xCCCCCCCC^0xCCCCCCCC to convert the entire number in one go). Finally as the correction applies to alternate digits it is simpler to do an initial conversion to base 16 which automatically picks up pairs of base 4 digits, then correct using a factor of either 3 or 0xC as appropriate. It just remains to ignore the - sign.


Dynamic ASCII Encoder! Introduction

Some ASCII characters are just so expensive these days...

To save money you've decided to write a program that encodes expensive characters using inexpensive ones.

However, character prices change frequently and you don't want to modify your program every time you need to encode or decode a different character!
You'll need a more dynamic solution.

Challenge

Your task is to write two programs: an encoder and a decoder.

The encoder should accept a list of five inexpensive characters, and a single expensive character.

It should output a single string made up of the inexpensive characters, that encodes the expensive character.

This string may not be longer than 4 characters, to remain inexpensive. However, it does not have to use all of the inexpensive characters in the encoding and encodings may be of different lengths.

The decoder should accept the string outputted by the encoder, and output the expensive character.

The decoder shall accept no input other than the encoded string. It must work, unmodified, from the encoder's output for any (valid) combination of inputs. In other words, your decoder program doesn't know which characters are expensive or inexpensive.

Scoring

Shortest combined code wins!

Notes

All characters will be either uppercase letters [A-Z], lowercase letters [a-z], or numbers [0-9].
The list of inexpensive characters won't contain duplicates. No character will be both inexpensive and expensive.
The encoder and decoder don't have to be written in the same language, but they can be. You may write a program or a function.
Input and output may be in any reasonable format for your language.
The two programs may not share any variables or data.

Summary

Input of some inexpensive characters and an expensive character is given to encoder.
Encoder outputs a string of inexpensive characters, encoding the expensive character.
Decoder is given the encoder's output, and outputs the expensive character.

Examples

Input:     a, b, c, d, e     f

Encoder Possibilities:     a     eeee     caec

Decoder:     f

Input:     a, b, c, d, e     h

Encoder Possibilities:     bc     cea     eeaa

Decoder:     h

Input:     q, P, G, 7, C     f

Encoder Possibilities:     777     P7     PPCG

Decoder:     f

CJam, 55 50 48 47 bytes

Encoder, 24 22 21 bytes

l$:L4m*{$L|L=},rc'0-=

Try it online.

Decoder, 31 28 27 26 bytes

4_m*{$4,|4,=},l_$_|f#a#'0+

Try it online.


Dizzy integer enumeration Your challenge today is to output a given term of a sequence enumerating all of the integers. The sequence is as follows: If we have a 0-indexed function generating the sequence f(n) and ceil(x) is the ceiling function, then f(0) = 0; abs(f(n)) = ceil(n/2); sign(f(n)) is positive when n and ceil(n/2) are either both even or both odd.

To help understand this sequence, the first few terms are as follows: 0 1 -1 -2 2 3 -3 -4 4 5 -5 -6 6 7 -7...

Your task is to write a program to that takes an integer n and outputs the nth term of the sequence. Input may be 0 or 1-indexed only.

Test cases (0-indexed):

0  =>  0
1  =>  1
2  => -1
3  => -2
4  =>  2
5  =>  3

This is code-golf, fewest bytes wins!

SOGL V0.12, 8 6 bytes
I».»⌡±

Try it Here! or try the first couple numbers (changed a bit so it'd work)
0-indexed.
Explanation:
I       increment the input
 »      floor divide by 2
  .     push the original input
   »    floor divide by 2
    ⌡   that many times
     ±    negate

Or simpler:
(input + 1) // 2 negated input // 2 times
        I     »     ±      .     »    ⌡


Find the Chromatic Number Surprisingly, we haven't had any challenges on graph colouring yet!

Given an undirected graph, we can give each vertex a colour such that no two adjacent vertices share the same colour. The smallest number χ of distinct colours necessary to achieve this is called the chromatic number of the graph.

For example, the following shows a valid colouring using the minimum number of colours:

(Found on Wikipedia)

So this graph's chromatic number is χ = 3.

Write a program or function which, given a number of vertices N < 16 (which are numbered from 1 to N) and a list of edges, determines a graph's chromatic number.

You may receive the input and produce the output in any convenient format, as long as the input is not pre-processed. That is, you can use a string or an array, add convenient delimiters to the string or use a nested array, but whatever you do, the flattened structure should contain the same numbers as the examples below (in the same order).

You may not use built-in graph-theory related functions (like Mathematica's ChromaticNumber).

You may assume that the graph has no loop (an edge connecting a vertex with itself) as that would make the graph uncolourable.

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

Examples

Your program must at least solve all of these in a reasonable amount of time. (It must solve all inputs correctly, but it may take longer for larger inputs.)

To shorten the post, in the following examples, I present the edges in a single comma-separated list. You may instead use line breaks or expect the input in some convenient array format, if you prefer.

Triangle (χ = 3)

3
1 2, 2 3, 1 3

"Ring" of 6 vertices (χ = 2)

6
1 2, 2 3, 3 4, 4 5, 5 6, 6 1

"Ring" of 5 vertices (χ = 3)

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

Example picture above (χ = 3)

6
1 2, 2 3, 3 4, 4 5, 5 6, 6 1, 1 3, 2 4, 3 5, 4 6, 5 1, 6 2

Generalisation of the above for 7 vertices (χ = 4)

7
1 2, 2 3, 3 4, 4 5, 5 6, 6 7, 7 1, 1 3, 2 4, 3 5, 4 6, 5 7, 6 1, 7 2

Petersen graph (χ = 3)

10
1 2, 2 3, 3 4, 4 5, 5 1, 1 6, 2 7, 3 8, 4 9, 5 10, 6 8, 7 9, 8 10, 9 6, 10 7

Complete graph of 5 vertices, plus disconnected vertex (χ = 5)

6
1 2, 1 3, 1 4, 1 5, 2 3, 2 4, 2 5, 3 4, 3 5, 4 5

Complete graph of 8 vertices (χ = 8)

8
1 2, 1 3, 1 4, 1 5, 1 6, 1 7, 1 8, 2 3, 2 4, 2 5, 2 6, 2 7, 2 8, 3 4, 3 5, 3 6, 3 7, 3 8, 4 5, 4 6, 4 7, 4 8, 5 6, 5 7, 5 8, 6 7, 6 8, 7 8

Triangular lattice with 15 vertices (χ = 3)

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

Python 2.7 - 122 109 111 109 108 103

f=lambda n,e,m=1:any(all(t*m//m**a%m!=t*m//m**b%m for(a,b)in e)for t in range(m**n))and m or f(n,e,m+1)

Usage:

print f(5, [(1, 2), (2, 3), (3, 4), (4, 5), (5, 1)])

Brute force by increasing the chromatic number (m) and check all possible colorings. One coloring can be described as a number in base m. So the possible colorings are 0, 1, ..., m^n-1.

edit: The complete graph of 8 vertices takes quite long. But my laptop solves it in about 10 minutes. The other test cases take only a few seconds.

edit 2: Read that preprocessing is allowed, so I let the index of the vertices start with 0: shortens t*m//m**x%m to t//m**a%m (-2). Dissolve lambda and put m into function params (-11)

edit 3: preprocessing is not allowed -> back to t*m (+4), simplified // to / (-2).

edit 4: remove square brackets in any (-2), thanks xnor.

edit 5: instead of taking modulo m twice, simply subtract them and afterwards use modulo (-1). This is also quite a performance improvement. All testcases together take about 25 seconds on my laptop.

edit 6: recursive call instead of while 1: and m+=1 (-5). Thanks again, xnor.


Swap letter and digit runs Given an input string containing only alphanumeric ASCII characters and starting with a letter, swap each letter run with the digit run which follows.

A run is a sequence of consecutive letters or digits. Note that in the case where the input string ends with a run of letters, this run is left untouched.

Walk-through example

For instance, given the input string uV5Pt3I0:

Separate runs of letters and runs of digits: uV 5 Pt 3 I 0
Identify pairs of runs: (uV 5) (Pt 3) (I 0)
Swap pairs of runs: (5 uV) (3 Pt) (0 I)
Concatenate: 5uV3Pt0I

Examples

uV5Pt3I0 -> 5uV3Pt0I
J0i0m8 -> 0J0i8m
abc256 -> 256abc
Hennebont56Fr -> 56HennebontFr
Em5sA55Ve777Rien -> 5Em55sA777VeRien
nOoP -> nOoP

This is code-golf so the shortest answer in bytes wins. Explanations are encouraged.

Retina, 15 bytes

(\D+)(\d+)
$2$1

This replaces the regex (\D+)(\d+) with $2$1. Let's break that down if you don't know what that means.

The \D means 'match anything that isn't a number'. \d means 'match everything that is a number'. The + sign means 'match this at least once but try to match it as many times as possible'. The brackets define a group. The first group is (\D+) and the second is (\d+)

In the second line we say that we want to put whatever was matched by the second group, followed by whatever was matched by the first group. This effectively swaps the letter and digit runs.

Try it online!


Naturally linear Diophantine equations A linear Diophantine equation in two variables is an equation of the form ax + by = c, where a, b and c are constant integers and x and y are integer variables.

For many naturally occurring Diophantine equations, x and y represent quantities that cannot be negative.

Task

Write a program or function that accepts the coefficients a, b and c as input and returns an arbitrary pair of natural numbers (0, 1, 2, …) x and y that verify the equation ax + by = c, if such a pair exists.

Additional rules

You can choose any format for input and output that involves only the desired integers and, optionally, array/list/matrix/tuple/vector notation of your language, as long as you don't embed any code in the input.
You may assume that the coefficients a and b are both non-zero.
Your code must work for any triplet of integers between -260 and 260; it must finish in under a minute on my machine (Intel i7-3770, 16 GiB RAM).
You may not use any built-ins that solve Diophantine equations and thus trivialize this task, such as Mathematica's FindInstance or FrobeniusSolve.
Your code may behave however you want if no solution can be found, as long as it complies with the time limit and its output cannot be confused with a valid solution.
Standard code-golf rules apply.

Examples

The examples below illustrate valid I/O for the equation 2x + 3y = 11, which has exactly two valid solutions ( (x,y) = (4,1) and (x,y) = (1,3) ).

Input:  2 3 11
Output: [4 1]

Input:  (11 (2,3))
Output: [3],(1)

The only valid solution of 2x + 3y = 2 is the pair (x,y) = (1,0).
The examples below illustrate valid I/O for the equation 2x + 3y = 1, which has no valid solutions.

Input:  (2 3 1)
Output: []

Input:  1 2 3
Output: -1

Input:  [[2], [3], [1]]
Output: (2, -1)

For (a, b, c) = (1152921504606846883, -576460752303423433, 1), all correct solutions (x,y) satisfy that (x,y) = (135637824071393749 - bn, 271275648142787502 + an) for some non-negative integer n.

Pyth, 92 bytes

I!%vzhK%2u?sm,ed-hd*ed/F<G2cG2@G1G+~Q,hQ_eQj9 2)J*L/vzhKtKeoSNm-VJ/RhK_*LdQsm+LdtM3/V*LhK_JQ

It's quite a monster.

Try it online: Demonstration. The input format is c\n[a,b] and the output format is [x,y].

In the case that no integer solution exists, I'll print nothing, and in the case that no natural integer solution exists, I'll simply print a random integer solution.

Explanation (Rough Overview)

At first I'll find an integer solution to the equation ax + by = gcd(a,b) by using the Extended Euclidean algorithm.
Then I'll modify the solution (my multiplying a and b with c/gcd(a,b)) to get an integer solution of ax + by = c. This works, if c/gcd(a,b) is an integer. Otherwise there doesn't exist a solution.
All the other integer solutions have the form a(x+n*b/d) + b(y-n*a/d) = c  with d = gcd(a,b) for integer n. Using the two inequalities x+n*b/d >= 0 and y-n*a/d >= 0 I can determine 6 possible values for n. I'll try all 6 of them and print the solution with the highest lowest coefficient.

Explanation (Detailed)

The first step is to find an integer solution to the equation ax' + by' = gcd(a,b). This can be done by using the extended Euclidean algorithm. You can get an idea on how it works at Wikipedia. The only difference is, that instead of using 3 columns (r_i s_i t_i) I'll use 6 columns (r_i-1 r_i s_i-1 s_i t_i-1 t_i). This way I don't have to keep the last two rows in memory, only the last one.

K%2u?sm,ed-hd*ed/F<G2cG2@G1G+~Q,hQ_eQj9 2)   implicit: Q = [a,b] (from input)
                                     j9 2    convert 9 to base 2: [1,0,0,1]
                            + Q              add to Q => [a,b,1,0,0,1]
                                             this is the initial row
   u                                     )   start with G = ^ and update G repeatedly
                                             by the following expression, until
                                             the value of G doesn't change anymore
    ?                   @G1                    if G[1] != 0:
                     cG2                         split G into parts of 2
      m                                          map the parts d to:
       ,                                           the pair
        ed                                           d[1]
          -hd*ed/F<G2                                d[0]-d[1]*G[0]/G[1]
     s                                           unfold
                                               else:
                           G                     G (don't change it, stop criterion for u)
 %2                                          take every second element
                                             we get the list [gcd(a,b),x',y']
K                                            store this list in K
                             ~Q,hQ_eQ        afterwards change Q to [Q[0],-Q[1]] = [a,-b]
                                             This will be important for the other parts.

Now I want to find a solution to ax + by = c. This is possible only, when c mod gcd(a,b) == 0. If this equation is satisfied, I simply multiplying x',y' with c/gcd(a,b).

I!%vzhK...J*L/vzhKtK   implicit: z = c in string format (from input)
  %vzhK                evaluated(z) mod K[0] (=gcd(a,b))
I!                     if not ^ than:
             /vzhK        c/K[0]
           *L     tK      multipy ^ to each element in K[1:] (=[x',y'])
          J               and store the result in J, this is now [x,y]

We have an integer solution for ax + by = c. Notice, that x, y or both may be negative. So our goal is to transform these to non-negative.

The nice thing about Diophantine equations is, that we can describe all solution using only one initial solution. If (x,y) is a solution, that all other solutions are of the form (x-n*b/gcd(a,b),y+n*a/gcd(a,b)) for n integer.

Therefore we want to find a n, where x-n*b/gcd(a,b) >= 0 and y+n*a/gcd(a,b >= 0. After some transformation we end up with the two inequalities n >= -x*gcd(a,b)/b and n >= y*gcd(a,b)/a. Notice that the inequality symbol might look in the other direction due the division with a potential negative a or b. I don't care that much about it, I simply say that one number of -x*gcd(a,b)/b - 1, -x*gcd(a,b)/b, -x*gcd(a,b)/b + 1 definitly satisfies inequality 1, and one number of y*gcd(a,b)/a - 1, y*gcd(a,b)/a, y*gcd(a,b)/a + 1 satisfies inequality 2. It there is a n, that satisfies both inequalities, one of the 6 numbers also does.

Then I calculate the new solutions (x-n*b/gcd(a,b),y+n*a/gcd(a,b)) for all 6 possible values of n. And I print the solution with the highest lowest value.

eoSNm-VJ/RhK_*LdQsm+LdtM3/V*LhK_JQ
                               _J    reverse J => [y,x]
                           *LhK      multiply each value with K[0] => [y*gcd,x*gcd]
                         /V      Q   vectorized division => [y*gcd/a,-x*gcd/b]
                  m                  map each d of ^ to:
                      tM3              [-1,0,1]
                   +Ld                 add d to each ^
                 s                   unfold
                                     these are the possible values for n
    m                                map each d (actually n) of ^ to:
             *LdQ                      multiply d to Q => [a*n,-b*n]
            _                          reverse => [-b*n,a*n]
        /RhK                           divide by K[0] => [-b*n/gcd,a*n/gcd]
     -VJ                               vectorized subtraction with J
                                       => [x+b*n/gcd,y-a*n/gcd]
 oSN                                 order the solutions by their sorted order
e                                    print the last one

The sort by their sorted order thing works the following way. I'm using the example 2x + 3y = 11

I sort each of the 6 solutions (this are called keys), and sort the original solutions by their keys:

solutions: [1, 3], [4, 1], [7, -1], [-5, 7], [-2, 5], [1, 3]
keys:      [1, 3], [1, 4], [-1, 7], [-5, 7], [-2, 5], [1, 3]
sort by key:
solutions: [-5, 7], [-2, 5], [7, -1], [1, 3], [1, 3], [4, 1]
keys:      [-5, 7], [-2, 5], [-1, 7], [1, 3], [1, 3], [1, 4]

This sorts a complete non-negative solution to the end (if there is any).


How Many Guineas in a Gross of Threepennies? Until decimalization in 1971, British money was based on dividing the pound into 240 pennies. A shilling was 12 pennies so 20 shillings made a pound. The smallest denomination was the farthing at one fourth of a penny. There were many other denominations and nicknames for coins, which can get quite confusing if you're not used to the system.
Challenge
Write a program or function that can convert (almost) any denomination of old English money to any other. To make it easier for the user you need to support plurals and nicknames.
These are the denominations and their synonymous terms you must support. For convenience their value in farthings leads each line.
1: farthing, farthings
2: halfpence, halfpenny, halfpennies
4: penny, pennies, pence, copper, coppers
8: twopenny, twopennies, twopence, tuppence, half groat, half groats
12: threepence, threepenny, threepennies, threepenny bit, threepenny bits, thruppence, thrupenny, thrupennies, thrupenny bit, thrupenny bits
16: groat, groats
24: sixpence, sixpenny, sixpennies, sixpenny bit, sixpenny bits, tanner, tanners
48: shilling, shillings, bob
96: florin, florins, two bob bit, two bob bits
120: half crown, half crowns
240: crown, crowns
480: half sovereign, half sovereigns
504: half guinea, half guineas
960: pound, pounds, pounds sterling, sovereign, sovereigns, quid, quids
1008: guinea, guineas

(I am not British, this list is by no means authoritative but it will suffice for the challenge.)
Via stdin or function argument you should take in a string of the form
[value to convert] [denomination 1] in [denomination 2]

and return or print
[value to convert] [denomination 1] is [converted value] [denomination 2]

where [converted value] is [value to convert] units of denomination 1 converted to denomination 2.
The [value to convert] and [converted value] are positive floats. In the output both should be rounded or truncated to 4 decimal places. If desired you may assume [value to convert] always has a decimal point and zero when input (e.g. 1.0 instead of 1).
Denominations 1 and 2 may be any two terms from the list above. Don't worry about whether they're plural or not, treat all denominations and synonyms the same. You may assume the input format and denominations are always valid.
Examples
1 pounds in shilling → 1 pounds is 20 shilling
(1.0000 pounds is 20.0000 shilling would be fine)
0.6 tuppence in tanner → 0.6 tuppence is 0.2 tanner
24 two bob bits in pounds sterling → 24 two bob bits is 2.4 pounds sterling
144 threepennies in guineas → 144 threepennies is 1.7143 guineas
Scoring
The shortest code in bytes wins.

Ruby, 345 306 302 288 287 278 273 253 252 242 232 221 202 190 bytes

f=->s{" !#+/7OďǿȗϟЏ'"[%w{fa fp ^pe|co r..p ^gr x|ta sh|^b fl|b f.c ^c f.s .gu d|v ^g .}.index{|k|s[/#{k}/]}].ord-31}
$><<gets.sub(/ (.+ i)n /){" #{r=$1}s %0.4f ".%$`.to_f/f[$']*f[r]}

Takes input from STDIN and prints to STDOUT.

I'm using short regular expressions to match only the desired denominations for each value. There are two arrays, one with regexes and one with values, at corresponding indices. The regex array is a space delimited array literal, and the value array is packed into a string of UTF-8 characters.

I'm selecting the index into the values by searching for a regex that matches each denomination. I'm also defaulting to the tuppence/half-groat case (value 8), because that required the longest regex. Likewise, some of the patterns assume that other values have already been matched by earlier patterns, so each regex only distinguishes the desired value only from the remaining ones. Using this, I could probably shave off another couple of bytes by rearranging the order of the denominations.

Thanks to Ventero for helping me beat Pyth making it shorter!


Make a Radiation Hardened Quine Last night I was looking for the Radiation Hardened Quine challenge, but I couldn't find it.  Turns out no one has asked it yet! So here it is:

Your task is to make a quine, that is a non-empty computer program that prints it's own source without reading it.  In addition if you remove any one byte from your original program the new program should print the source of your original program.

This is code-golf so answers are scored in bytes with fewer bytes being better.

Gol><>, 49 45 bytes

<<H~Kla}\`q%2l}}ss2"<\
<<H~Kla}\`q%2l}}ss2"<\

Try it online!

Verification!

I did this in Gol><> rather than ><> because the former has the handy K operator that copies the top n items on the stack, which makes duplicating the clean copy of the source code easier.

Explanation:

This works by having two copies of the executing code, and redirecting to the second one if the first is damaged. This fails when the last \ or the middle newline is removed, both of which are compensated for later.

<<                       Redirect left
                    <\  Switch to other source code if this line is irradiated
                   "     Push source with wrapping string literal
                ss2      Push quote
              }}         Move "< to end
          q%2l           If the length of the stack is not right
        \`               Push an extra \
       }                 Move the \ to the end
      a                  Newline
    Kl                   Duplicate the stack
   ~                     Pop the extra newline
  H                      Halt and print stack