Down the drain it goes I once encountered this (mini) game where you had 4 or more vertical pipes that were connected by a number of horizontal pipes and you have to drop a ball or water into the vertical pipes.
There are 2 kinds I know of:

Get the object into a bucket/basket under one of the exits (guess
what pipe to throw it in)
Guess what pipe the object will come from.

Sample pipes:

|       |       |-------|
|-------|       |-------|
|       |-------|       |
|-------|-------|-------|
|       |-------|       |
|-------|       |-------|
|-------|       |-------|
|       |-------|       |

Basic rules:

When moving through a horizontal pipe the object will go down when
possible
When moving through a vertical pipe the object will turn into a horizontal pipe when possible.

Your job

Write a program that will create a random grid of pipes(see sample
pipes).
There should be at least 4 vertical pipes and a fair amount of horizontal pipes at least 10.
The length of the vertical pipes is up to you.
Show the path that the object took to reach the bottom and show how many turns it took to get there.
(Optional) input to deterimine starting point, pipes numbered 1..N from left to right.

Display:

 | vertical pipe
 - horizontal pipe
 : vertical pipe used by the object
 = horizontal pipe used by the object
 V Object starting point
 ^ Object ending point

Example:

V
:       |       |-------|
:=======:       |-------|
|       :=======:       |
|-----!-:=======:       |
|       :=======:-------|
|-------|       :=======:
|-------|       :=======:
|       :=======:       |
        ^
14 turns were taken to get to the end.

Detail
The object enters pipe 1 and starts moving down, goes left into the first horizontal pipe.
Back down and into the second pipe followed by a U-turn into the third pipe.
At the end of the third pipe you see an exclamation mark,
shouldnt be in your result but I used this to show you the object could have gone straight ahead.
However rule number 1 prevents that.

Winner will be determined by votes in 3 weeks from now 24-02-2014 (dd-mm).

Happy coding ^.^

Mathematica
The 2D code generates a graph showing the path of the water. I displayed the vertex numbers for convenient cross-checking with the 3D display.  Normally the vertex numbers would be hidden.
Input:
r=10;c=7;
result=flow2D[{r,c},3]

Actually, the result contains multiple objects. The first object, result[[1]], is the 2D graph shown here.

The 3 dimensional pipes are Tube's  (3D lines) plotted in 3 space.  The coordinates computed based on the vertices of the 2D graph along a 3rd coordinate that was randomly generated (This allows the pipes to assume different positions along y each time the code is run.)
The axes are displayed to help the reader convince herself that the 3D rendering is indeed based on the 2D rendering.
The 3D input of interest here is:
Graphics3D[{CapForm[None],verticalPipes,allRungs,Darker@Red,connections},
ImageSize->600,Axes-> True,Ticks->{Range[1,2 r,2],Range[c],Range[10]},ViewPoint->{0,-2,1.5}]

The number or rows, columns and entry column are taken from the 2D code.  They do not have to be re-entered.

2D Code
In the coming days I will document and tidy up the code for 2D and 3D.
flow2D[{rows_,columns_},startColumn_]:=
Module[{r=rows,c=columns,g,j,h,ends,middle,midcuts,direction="down",turns=0,path,rungs},

   (*complete gridgraph*)
g=GridGraph[{r,c},VertexSize-> Medium,GraphStyle->"Prototype",EdgeStyle->"Thick",
  VertexLabels->"Name",ImagePadding-> 30,ImageSize->470];

(*horizontal pipes that must be removed*)
ends=Table[r(c1-1)+r1\[UndirectedEdge] r(c1)+r1,{c1,1,c-1},{r1,{1,r}}];

(*horizontal pipes to consider removing *)
middle=Table[r(c1-1)+r1\[UndirectedEdge] r(c1)+r1,{c1,1,c-1},{r1,2,r-1}];
midcuts=RandomSample[#,RandomInteger[Round[{r/15,2r/5}]]]&/@middle;

rungs=Flatten[midcuts(*Join[ends,midcuts]*)];

j=EdgeDelete[g,Flatten[Join[ends,midcuts]]];

h[path_]:= Module[{start=path[[-1]],right,left,up,down,newnodes},
     {v=NeighborhoodGraph[j,start,1,(*VertexLabels\[Rule]"Name",*)ImagePadding->25],
     VertexList[v]};newnodes=Complement[VertexList[v],path];
     If[newnodes=={},path,
     h[Append[path,
  Switch[direction,
   "down",Which[
     MemberQ[newnodes,start+r],(turns++;direction="right";start+r),
     MemberQ[newnodes,start-r],(turns++;direction="left";start-r),
     MemberQ[newnodes,start-1],start-1],
   "right",Which[
     MemberQ[newnodes,start-1],(turns++;direction="down";start-1),
     MemberQ[newnodes,start+r],start+r],
   "left",Which[
     MemberQ[newnodes,start-1],(turns++;direction="down";start-1),
     MemberQ[newnodes,start-r],start-r]
    ]]]]];
{HighlightGraph[j,path=h[{r*startColumn}],ImageSize->300],path,rungs,ends,midcuts}]

convert[node_,r_,c_]:=Append[footing[[Quotient[node-1,r]+1]],Mod[node-1,r]+1(*Mod[node,r]*)]
connect[a_\[UndirectedEdge]b_,r_,c_]:=Tube[Line[{convert[a,r,c],convert[b,r,c]}],0.2]

3D Code and results
r=10;c=7;
result=flow2D[{r,c},3];
g2D=result[[1]];
path2D=result[[2]];
\[AliasDelimiter]
xScale=2;
footing = {#, RandomInteger[{1, 6}]} & /@ Range[1,xScale c, xScale];
verticalPipes=Tube[Line[{Append[#,1],Append[#,r]}],.19]&/@footing;
Graphics3D[{CapForm[None],verticalPipes},ImageSize->600,Axes->True,AxesEdge->Automatic,ViewPoint->{0,-2,1.5},
Ticks->{Range[1,2 r,2],Range[c],Range[10]}];

path3D=UndirectedEdge@@@Partition[Riffle[stops=path2D,Rest@stops],2];
allRungs=connect[#,r,c]&/@rungs;
connections=connect[#,r,c]&/@path3D;

path2D;
g2D
Graphics3D[{CapForm[None],verticalPipes,allRungs,Darker@Red,connections},
ImageSize->600,Axes-> True,Ticks->{Range[1,2 r,2],Range[c],Range[10]},ViewPoint->{0,-2,1.5}]


Find the Block on the Extended Periodic Table Using the Diagonal Rule The periodic table gets its shape from the arrangement of elements into blocks:

An element is assigned its block based on what type of orbital holds its valence electron(s). For instance, the sole valence electron of neutral hydrogen occupies the 1s orbital in the 1s subshell, and so hydrogen belongs to the s-block.
The least energetic subshell is the 1s subshell, followed by 2s, 2p, 3s, etc. Electrons fill orbitals in less-energetic subshells first, in accordance with the following chart:

The diagonal arrows give the diagonal rule its name.
When finding the block of an element, there are some important facts to consider:

Each subsequent element has one more electron than its predecessor.

Every new type of subshell (s, p, d . . . ) can hold four more electrons than its predecessor as a consequence of the presence of two additional orbitals.

All subshells (1s, 2s . . . ) have an odd number of orbitals, each of which can hold two electrons. As such, all subshells can hold twice an odd number of electrons.

Subshells beyond s, p, d and f have names reserved for their eventual observation: after f comes the rest of the alphabet, starting with g and omitting j.

The Challenge
Given the atomic number of an element, output its block (a letter).
Because one can tell how many electrons are held by theorized, not-yet-observed subshells, input will be less than or equal to 17296 (found with the sum \$2\sum_{n=1}^{23}\sum_{\ell=0}^{n-1}2\left(2\ell+1\right)\$), the atomic number of the last element with valence electrons in the 46s subshell. Letters beyond z would be needed for elements past that point, and so they will not be included in the challenge. An extended version of the diagonal line chart above can be seen here.
Rules

This is code-golf so the shortest answer in bytes in each language wins

For the purpose of this challenge, when s and p are reached a second time after f, they will be capitalized. This means letters are sequenced as follows: s p d f g h i k l m n o P q r S t u v w x y z. Additionally, it means output is case-sensitive.

Assume only valid input is given.

There is a discrepancy between the periodic table above and the expected output: in reality, lanthanum and actinium (57 and 89) are in the d-block, and lutetium and lawrencium (71 and 103) are in the f-block. The diagonal rule implies that lanthanum and actinium are in the f-block, and that lutetium and lawrencium are in the d-block, and so that is what the program should state.

Test Cases
In: 1
Out: s

In: 5
Out: p

In: 21
Out: d

In: 57
Out: f

In: 2784
Out: l

In: 17296
Out: s

In: 15181
Out: z

In: 12024
Out: q

Charcoal, 59 bytes
Ｎθ⊞υ²Ｗ›θ⊗Συ«≧⁻⊗Συθ⊞υ⁺⁴⌈υ»§”>-◧βYTＢ↷p{ï⭆Σ]¬∕↷›”ＬΦυ‹﹪⊖θΣυΣ✂υκ

Try it online! Link is to verbose version of code. Explanation:
Ｎθ

Input the atomic number.
⊞υ²

Start with just an s-shell.
Ｗ›θ⊗Συ«

Repeat while the number of electrons left will fill all the shells twice...
≧⁻⊗Συθ

... remove those electrons, and...
⊞υ⁺⁴⌈υ

... add another shell which can hold 4 more electrons than the previous.
»§”>-◧βYTＢ↷p{ï⭆Σ]¬∕↷›”ＬΦυ‹﹪⊖θΣυΣ✂υκ

Count how many of the remaining shells have no electrons and look that up in the compressed string of block letters. (Because of the way Sum works in Charcoal, the calculation is adjusted slightly to avoid a sum of no elements, which ends up offsetting the result by 1, which is compensated by moving the z to the beginning of the string where it can be cyclically indexed.)


Organize a tournament Here is a real question somebody asked me. Suppose you have n teams, one terrain.

Each team must play each other team exactly once.
The number of times a team plays two matches in a row should be minimized.

The problem is hard if not optimized. Your program should be able to answer this question for up to 6 teams (at least) in a reasonable time (say less than an hour). For 5 teams I have a working program which works in less than a minute.

Here is an example for 5 teams.

$ organize_for 5
[(3,5),(1,2),(4,5),(1,3),(2,4),(1,5),(2,3),(1,4),(2,5),(3,4)]

And another for 6 teams.

$ organize_for 6
[(2,4),(1,5),(2,3),(1,6),(3,5),(1,4),(2,5),(1,3),(4,6),(1,2),(3,6),(4,5),(2,6),(3,4),(5,6)]

NB for 3 and 4 teams, you'll have at least two occurrences of a team playing two matches in a row.

To win: make the shortest program to answer this problem fast enough to give you a correct answer for 6 teams.

Bonuses:

The median of the median of the waiting time between two matches for all teams should be maximized.
Example: from organize_for 5 ;
nb match between the next one (sorted, median is the one in the center)

team 1 -> 1, 1, 1 (sorted => 1, 1, 1, median => 1)
team 2 -> 2, 1, 1 (sorted => 1, 1, 2, median => 1)
team 3 -> 2, 2, 2 (sorted => 2, 2, 2, median => 2)
team 4 -> 1, 2, 1 (sorted => 1, 1, 2, median => 1)
team 5 -> 1, 2, 2 (sorted => 1, 2, 2, median => 2)

medians: (1, 1, 2, 1, 2), sorted => (1, 1, 1, 2, 2)
median of the medians = 1.

Generalize for k terrains. All match have the same duration.

The most important rules remains a team shouldn't do a match just after another.
The global time for all matches should be minimized

Haskell: 291 chars

Another solution which terminate only if there is a solution without any collision (5 and 6). It is also very fast:

import System.Environment
import Data.List
a n=[(x,y)|x<-[1..n],y<-[1..n],x<y]
s []=[[]]
s (m:[])=[[m]]
s ((x,y):(x',y'):xs )
 |(x==x')||(x==y')||(y==x')||(y==y')=s((x,y):xs++[(x',y')])
 |0<1=[(x,y):ys|ys<-s((x',y'):xs)]
main=do
 args <- getArgs
 print $ head $ s $ a (read(head args)::Int)


Write biSp in point-free form using as few terms as possible The Haskell function biSp has type signature

biSp :: (a -> c) -> (b -> d) -> (c -> d -> e) -> a -> b -> e

and (for those who prefer combinator calculus) can be defined as

biSp g h f x y = f (g x) (h y)

Your task is to implement biSp in point-free form (equivalently: as a combinator without any lambdas) using only two primitives:

(.) :: (b -> c) -> (a -> b) -> a -> c
flip :: (a -> b -> c) -> b -> a -> c

or

(.) f g x = f (g x)
flip f x y = f y x

For those with a background in combinator calculus, these are respectively the B and C combinators.

You may define helper functions so long as they are point-free. Your score is the total number of terms in all right-hand-side expressions.

Testing

You can test a Haskell solution without installing any software using Ideone. By providing an explicit type alongside the definition you ensure a compile-time error if the function is incorrect. E.g. using the :pl reference implementation (online demo):

biSp :: (a -> c) -> (b -> d) -> (c -> d -> e) -> a -> b -> e
biSp = flip . ((flip . ((.) .)) .) . flip (.)
main = putStrLn "Compiled ok"

7 terms

We again define a helper combinator BBQ = B B (C B), which has reduction rule

BBQ w x y z = x y (w z)

Then biSp = BBQ BBQ BBQ

  BBQ BBQ BBQ g h f x y
= BBQ g (BBQ h) f x y
= BBQ h f (g x) y
= f (g x) (h y)

Online demo

By brute force, this is the only 7-term solution and there is no smaller solution.

8 terms

There are a handful of 8-term solutions. Firstly, the obvious

C BBQ BBQ BBQ

which reduces in one step to BBQ BBQ BBQ.

Then there are three solutions of the form X X X with a five-term X:

X = B (B B) C B which reduces in one step to BBQ
X = C B (C B) B which reduces in one step to BBQ and allows the further extraction, for no net gain or loss, of a helper combinator Q = C B
X = C (B C (B B))

There is one solution of the form X X with a six-term X:

X = C B (B B (C B)) (again, with an equivalent version which extracts Q = C B)

And there is one solution which can only be written in 8 terms with two helper combinators:

Q = C B
X = Q (Q Q B)
biSp = X X


Create a regex to match a given range of integers in a given radix Task

Write a program/function that, given three integers n,a,b prints a regular expression which matches all of the base-n integers from a to b (and no integers outside of that range).

Your algorithm should, in theory, work for arbitrarily large integers. In practice, you may assume that the input can be stored in your data type. (don't abuse native data type, that's a standard loophole)

Input

Three integers, n, a, b where n is in the range 1-32. a and b may be taken as base-n string/character list/digit list.

Output

A single string, represent the regex.

Rules

Base-n integers use the first n digits of 0123456789ABCDEFGHIJKLMNOPQRSTUV, you can choose to use upper-case or lower-case.
a and b may be negative, denoted by a - in front of the integer
You may assume a ≤ b.
Any regex flavor is allowed.
The behavior of the regex on strings not a base-n integer is undefined.

Winning criteria

Answers will be scored by the length of the code in bytes. (so code-golf rules apply)

05AB1E, 17 bytes

ŸεD0‹'-×sÄIB«}'|ý

Try it online!

For some reason I don't seem to be able to replace I with ³.


Code Golf: Word Unscrambler Write a program that either accepts input via stdin or from the command line. It will then unscramble the words, printing out the unscrambled version of each word.You get a text file containing every word (most of them) in the English dictionary to use. (Here is the file: Word List, and you can either use it from the web or save it as a text file and use it from there.)
Inputs to measure the score:

bbuleb lwrfoe kaec rtawe cokr kmli pcaee

Correct Outputs:

bubble flower cake water rock milk peace
bubble fowler cake water cork milk peace

(Word case doesn't matter, and please post your score and outputs along with your code!)
Scoring:
Score = (Amount of correct outputs) x (100 / (Code Length))
The code with the highest score wins!
Edit: This is my first post, please be kind!

Python 3 / 84 chars / 7 correct outputs / score 8.3333

edit As per clarifications, removed .upper() and considering all 7 ouputs correct.

a=sorted
for b in input().split():print([c for c in open('x')if a(b)==a(c[:-1])][0])

Output:

BUBBLE
FLOWER
CAKE
WATER
CORK
MILK
PEACE


Organise the Gregorian Church's Music The year is 930, and the Gregorian Church is having a problem. They have thousands of pages of chant music, but the problem is that all the sheet music was simply thrown onto a pile instead of having any real organisation system:

Image by user gamerprinter at Cartographers' Guild.

The Church needs to organise all the sheet music, so they have hired a medieval software engineer to write a program to organise it for them. You are the software engineer that has been hired. However, the compilation process in medieval times involves the program being written onto paper by a team of slow biblical scribes. To decrease the time it takes for the team of scribes to compile your code, you must make the program as small as possible.

The Church wants the chant music to be organised based off the musical scale they are written in. All of the Church's chant music is written in Dorian scales. Given the notes of a certain piece of music, your program will output the Dorian scale that it is in. Here, I will explain exactly what a Dorian scale is. If you already know, you may skip this section.

There are 12 possible notes in any melody. Here they are in order:

C C# D D# E F F# G G# A A# B

A semitone (represented using a S) is incrementing one step to the right, wrapping around (so a semitone up from B would be back to C). A tone (represented using a T) is two semitones. For instance, a semitone up from F# would be G. A tone up from F# would be G#.

To create a Dorian scale, we start from any note in the list, and then move up in the following pattern, listing the notes that we encounter:

T, S, T, T, T, S

An example. I start from A. The notes of my Dorian scale becomes:

A
B  (up a tone)
C  (up a semitone)
D  (up a tone)
E  (up a tone)
F# (up a tone)
G  (up a semitone)

The scale has the notes A, B, C, D, E, F#, and G. Because I started from A, we will call this the Dorian scale in A. There are therefore 12 different Dorian scales, each of which are named after the note that they started from. Each of them use the same pattern of tones and semitones, just starting from a different position. If my explanation is not coherent you may also consult Wikipedia.

The input of the program can be given from whatever is appropriate for your program (e.g. STDIN, command line argument, raw_input()). It may be not pre-initialised in a variable. The input will be a list of comma seperated notes, representing the melody of the piece. There may be repeated notes. There will always be enough different notes in the input to be able to decisively deduce the scale of the piece. An example input:

B,B,D,E,D,B,A,G#,A,G#,E,D,F#,E,F#,E,F#,G#,A

The output of the program should be the string Dorian scale in X, where X is the starting note of the scale. The output of the example input:

Dorian scale in B

Comparing this with the Dorian scale in B (B C# D E F# G# A) we see that all the notes of the melody are within this scale. The note C# is unused in this case. However there are sufficient notes to unambiguously identify B Dorian as the correct key. No other Dorian scale fits, because whatever other scale we try, there is always at least one note of the melody that does not belong to the scale.

This is code golf, so the entry with the shortest number of characters wins. Ask in the comments if you have questions.

C, 171 146
i,b;main(int c,char**v){for(;c=v[1][i];)b|=c/65<<c*2%7+v[1][++i]%2*7;for(i=12;i--;)b&(1016056>>i)||printf("Dorian scale in %c%c",65+i*3%7,(i<5)*35);}

Parsing strings in C is not that easy, so I went for a more mathematical approach.
I take advantage of the Circle of Fifths. If we arrange the notes in the following order based on counting up 7 semitones at a time (known as a "fifth"), we find that all the notes permitted in any given scale form a consecutive block of 7 notes and all the prohibited notes form a consecutive block of 5 notes.
F C G D A E B F# C# G# D# A#

(it's a circle, it wraps back around to F at the end.)
The position of a natural note in the above sequence can be calculated as (ASCII code) * 2 % 7. Then if the next character is odd (applies to # but not comma, space or zero byte) we add 7 to make it sharp. We store a bitmap of the notes that have been used.
The number 243 (binary 11111000) corresponds to the notes prohibited in the scale of A# Dorian. I multiplied this by (1<<12)+1=4097 to give the magic number 1016056. This is rightshifted to check (by ANDing) if the melody contains prohibited notes for each of the 12 scales in turn. If the melody does not contain prohibited notes, the scale is printed.
For the output we need to print the scale name encoded in the reverse order to cycle of fifths above, remember we are going backwards because we are rightshifting.) The ASCII sequence ADGCFBEADGCF is generated by 65+i*3%7. For the first five of these a sharp must also be printed.
Ungolfed code
i,b;
main(int c,char**v){
  for(;c=v[1][i];)                          //for each character in first commanline argument v[1]
                                               //if it is a letter (assume uppercase, ASCII 65 or over)
   b|=c/65<<c*2%7+v[1][++i]%2*7;               //convert to position in the circle of fifths.
                                               //Add 7 if the next character is odd (ASCII'#')
                                               //leftshift 1 by this number and OR this with the contents of b.

  for(i=12;i--;)b&(1016056>>i)||printf         //if melody includes no prohibited notes for the scale i, print
   ("Dorian scale in %c%c",65+i*3%7,(i<5)*35); //the scale letter, and a # (ASCII 35) if required, otherwise an ASCII 0.
}

Invalid input behaviour: If insufficient notes are supplied to unambiguously determine the scale, it will output all possible scales. If an impossible combination of notes is supplied, it will output nothing. Notes must be delimited by a comma (or other non-whitespace character with an even ASCII code <= 64.) Spaces cannot be used as everything after the first space would be considered a different argument. ASCII codes >64 will be interpreted as notes in the manner described.


Enumerate valid Brainf**k programs Golunar/Unary is a way to encode all valid Brainfuck programs, but it is not an enumeration, since most natural numbers do not correspond to a valid program.
For the purpose of this challenge, assume a doubly infinite tape and no comments, i.e., a Brainfuck program is valid if and only if it consists solely of the characters <>+-.,[] and all left and right brackets match.
For example, the empty program, ,[+][-]., [>+<[--].] and +[+[+][+[+]+]+]+. are valid Brainfuck programs, while ][, and a[] are not.
Task
Write a program or function that accepts a valid Brainfuck program as input and returns a natural number (1, 2, 3, …), with the following constraints:

The generated output must be different for all valid Brainfuck programs.

For every natural number n, there must be a valid Brainfuck program that, when provided as input, generates the output n.

Additional rules

Given a Brainfuck program of 100 or less bytes, your program or function must finish within one minute.
This means that you cannot iterate over all valid Brainfuck programs until you match the input.

Standard code-golf rules apply.

Python 3, 443 158 155 154 134 131 128 124 117 116 115 bytes

c=d=C=D=0
for e in input():v='[<>,.-+]'.find(e);d=d*8+v;c+=c<0<6<v;c-=d>1>v;C,D=(c,C+1,d,D)[v>6::2]
print(-~D*8**C)

Several bytes thanks to Sp3000 and Mitch Schwartz :D

How this works:

This maps all valid BF programs into all possible, valid or invalid, BF programs, that don't start with a [, in a one-to-one ratio. After that, the new program is simply converted into octal.

Here is the mapping formula:

Separate a BF program into 3 parts. The first part is the largest prefix consisting of only [ characters. The third part is the largest postfix consisting of only ] characters. The second part is the middle.
Dispose of the first part. These can be recomputed later.
Remove all ] brackets in the third part that match [ brackets in the second part. These can also be recomputed later.
Concatenate the second and third parts together.

If you don't understand this explanation, you can find an extended explanation in chat starting here.

For reference, here are the first 20 programs:

1 :
2 : <
3 : >
4 : ,
5 : .
6 : -
7 : +
8 : []
9 : <[]
10 : <<
11 : <>
12 : <,
13 : <.
14 : <-
15 : <+
16 : [<]
17 : >[]
18 : ><
19 : >>
20 : >,

Here are the first 1000 programs: http://pastebin.com/qykBWhmD
Here is the program I used to generate them: http://ideone.com/e8oTVl

Here is Hello, World!:

>>> ++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
457711481836430915510337664562435564418569135809989841510260388418118348571803953323858180392373


Code 39 barcode encoder Write a function or program that encodes a string into a Code 39 format barcode, where each character is encoded as five bars separated by four gaps. Either two of the bars and one of the gaps are wide and others are narrow (10*4 codes), or three of the gaps are wide and none of the bars are (4 codes). This gives 44 different codes, from which one is a reserved code that is used to denote the start and end of the encoded string.
The challenge
The input is a string containing only characters from the set
1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ-. +/$%

The output is the string encoded as a barcode string. The narrow gap and intercharacter gaps are a single space and a wide gap is three spaces. The narrow bar is the UTF-8 byte sequence for the Unicode character "Full block", █, i.e. 0xE2 0x96 0x88 and wide bar is three such byte sequences / characters (███). The full list of codes is:
      Spaces
      0100 0010 0001 1000 1011 1101 1110 0111
Bars
00000                       +    /    $   %
10001   1    A    K    U
01001   2    B    L    V
11000   3    C    M    W
00101   4    D    N    X
10100   5    E    O    Y
01100   6    F    P    Z
00011   7    G    Q    -
10010   8    H    R    .
01010   9    I    S  space          1=wide
00110   0    J    T  start/end      0=narrow

The bars and spaces are interleaved, starting at a bar, so for example Q is
bar   0 0 0  1     1
code  █ █ █ ███   ███
space  0 0 0    1

After encoding all the characters, the string is delimited at both ends with █   █ ███ ███ █. The intercharacter gap, a single space, is inserted between every letter. Your solution may output trailing spaces and a trailing newline (in that order).
Examples
""     → "█   █ ███ ███ █ █   █ ███ ███ █"

"A"    → "█   █ ███ ███ █ ███ █ █   █ ███ █   █ ███ ███ █"

"C++"  → "█   █ ███ ███ █ ███ ███ █   █ █ █   █ █   █   █ █   █ █   █   █ █   █ ███ ███ █"

"GOLF" → "█   █ ███ ███ █ █ █ █   ███ ███ ███ █ ███ █   █ █ ███ █ █   ███ █ ███ ███   █ █ █   █ ███ ███ █"

Standard input/output formats are allowed and standard loopholes are disallowed. This is code-golf, so the shortest code measured in bytes wins!

JavaScript (ES6), 225 212 bytes
Saved 4 bytes thanks to @l4m2
s=>`#${s}#`.replace(/./g,c=>'0202020202'.replace(/./g,(j,k)=>[C='█',C+C+C,' ','   '][(i="%+/$U1AKV2BLW3CMX4DNY5EOZ6FP-7GQ.8HR 9IS#0JT".indexOf(c),[170,257,260,5,272,17,20,320,65,68,80][i>>2]^2<<i%4*2)>>k&1|j]))

Try it online!
How?
The table can be rearranged such that the 9-bit binary mask of the character is quickly deduced from its row and column using the following formula:
n = m XOR (2 << k)

with:
  m  | k: 0   2   4   6
-----+------------------      Examples:
 170 |    %   +   /   $
 257 |    U   1   A   K         'G' = 320 XOR (2 << 4) = 320 XOR 32 = 352
 260 |    V   2   B   L
   5 |    W   3   C   M         '+' = 170 XOR (2 << 2) = 170 XOR 8  = 162
 272 |    X   4   D   N
  17 |    Y   5   E   O
  20 |    Z   6   F   P
 320 |    -   7   G   Q
  65 |    .   8   H   R
  68 |   spc  9   I   S
  80 |    #   0   J   T


Fair outcome using unfair coin I have been thinking a lot about the following puzzle, but could not arrive at a solution.

Can someone explain to me how can you get a fair (equal probability) outcome using only an unfair coin (where unfair means that it will land head with probability p and tails 1-p where p != .5)?

It will require some extra tosses, but you can get a fair result this way:

Always use two throws to determine the answer, a HH or TT throw is discarded.

HT == True
TH == False

You know that the probability of HT is the same as the probability of TH.


Predict the Bomb's Landing Point! Introduction
It was just a normal day, here at your military base. Suddenly, you looked up to see a bomb falling down from the sky! You need to create a program to predict where it will fall, and tell you the location.
Challenge
You will be given a bomb in the form of Start-X Start-Y X-velocity Y-velocity. You can assume that they will all be positive integers. 0 is a valid input only for Start-x and Start-y. The bomb starts with x Start-x, and y Start-y. Each "frame" (no graphical output required), the bomb will move x-velocity units right, then y-velocity units down. Continue doing this until the bomb reaches y of 0 or below. Then, output what it's x was when it hit the ground.
Test Cases
1
Input:0 10 2 2
Output:10
2
Input:5 4 3 2
Output:11
3
Input:11,8,7,3
Output:32
This is code-golf, so shortest answer in bytes wins!

JavaScript, 29 28 bytes

Thanks @user5090812 for golfing off 1 byte

(a,b,x,y)=>a+x*((b+y-1)/y|0)

Try it online!

If it did not have to move x then y but was instead falling in a straight line it would be 18 bytes

(a,b,x,y)=>a+x*b/y


Can you loop without crashing? Many of us are familiar with the game Tron. You control a "lightcycle" placed on a grid. The lightcycle always moves forward (though you control the direction) and leaves a permanent trail behind it. If you run into a trail, you crash!

The goal here is to determine if a given path is a valid loop, that is, it returns to its starting point without "crashing". To do this, we assume we start at the point (0,0). An input is given in the form N2E1S2W1, with a series of cardinal directions (N is north, E is east, and so on), each followed by the distance to travel that direction. In this example, you would travel

N2 : North 2 to (0,2)
E1 : East 1  to (1,2)
S2 : South 2 to (1,0)
W1 : West 1  to (0,0)

A path is considered valid if it ends at (0,0) without visiting any other coordinate more than once (it visits (0,0) exactly twice. Once at the start, and once at the end). Keep in mind than in the above example, to get from (0,0) to (0,2), we necessarily visit (0,1) as well.

Other examples:

input        -> output
N1E1S1W1     -> true
N1E1N1E1S2W2 -> true
N1S1E1W1     -> false     // Visits (0,0) 3 times
N4E2S2W4S2E2 -> false     // Visits (0,2) twice
N3E2S3       -> false     // Does not return to (0,0)
N1S1         -> anything  //I don't care how you evaluate this case

Your output can be in any form so long as it gives the same output for any truthy or falsey value.

The input can be taken as a string or as a list of characters, either in the form S1N2E3... or SNNEEE... There's is also no hard limit on the grid size, but assume the input isn't going to overflow anything. As long as the code is fundamentally sound, It's not crucial to handle cases like N99999999999999.

NOTE: You may evaluate the cases N1S1, E1W1, S1N1, and W1E1 however you would like. They're technically valid paths, but they go against the "Tron" spirit of the challenge.

Scoring

This is code-golf, so the shortest answer wins!

Pyth, 44 39 bytes

&!eJsM._smm^.j)x"NESW"hdstd:z".\d+"1{IJ

Test suite.


Create a simple line editor In: a string without line breaks*
Allow the user to edit and submit the line
Out: the modified string (optionally with a trailing linebreak)
The line editor must at minimum allow the user to:

move a visible cursor left and right

insert and/or overwrite characters at the cursor position

remove characters at the cursor position

submit the new string, i.e. cease editing cause the modified string to be returned/printed/displayed/saved… (with no other text)

Appreciated, but not required:

explanation of your code.

link to an online testing site that can demonstrate your program/function

an animated image demonstrating usage (TIO, for instance, does not allow interactivity)

Note:

key-bindings are suggestions only

GUI or visual styling is not required

Examples
In the following, the cursor is illustrated with _.
In: Just some text
Allow the user to edit:
 Just some text_   User presses ← (left arrow key) nine times
 Just ̲some text    User presses Del four times
 Just ̲ text        User presses any
 Just any_text     User presses Enter
Out: Just any text
In: Remove me
Allow the user to edit:
 Remove me_        User presses Backspace nine times
 _                 User presses Enter
Out:  (empty string)

* To prevent trivial editor solutions, this must either be supplied via a different input method than the editing commands, or must be separated from them by a newline or similar.

JavaScript (ES6), 15 14 bytes
I don't understand why this is getting so many upvotes!
s=>prompt(s,s)

Saved a byte thanks to Adám's suggestion that I display the original input in the prompt.

Try It

f=
s=>prompt(s,s)
console.log(f("Edit this ..."))


Calculate the size of the moon The size of the moon mystery

I am sure you have heard that the moon changes its size. When you're in love and you're lucky, the moon is almost twice in size compared to normal situations. Some people say the reason is the atmosphere which acts as a lens. Others think that it is only a matter of comparison to other objects such as trees nearby. Whatever explanation you read, it's quite subjective.

The size of the moon science

Ok, we're programmers, aren't we? We rely on facts, right? So here's the experiment:

Take a nice camera which supports setting time and aperture manually.
Set your camera to maximum zoom level.
Go out, take some photographs of the moon in order to detect the best settings so that the moon is sharp and lighting is just fine.
Remember the settings
Take photos of the moon with those settings every time you think the moon is large or small.
Calculate the size of the moon in pixels

The camera won't lie, would it? By counting the bright pixels we can effectively measure the size of the moon - at least in pixels.

If the size is the same across all photos, then it's a bug in our brain. If the size differs, then there's room for speculation

the moon really grows (but what does it eat?)
there's an atmospherical lens effect
the moon has an elliptical curve and is sometimes nearer, sometimes further away from earth
...

But I'll leave that open until your task is completed. Of course you want to know in advance if your software can calculate the moon size accurately.

The task

Given a few optimized pictures of the moon, please calculate the size of the moon. The optimization is: the pixels are either black or white. Nothing in between. No antialiasing. That makes it easy, doesn't it?

The caveat: the moon is not always full, you know ... it can be a sickle! But even in shape of a sickle, the size of the moon is larger. So you'll calculate the full size, please.

Your program takes a PNG as input, e.g. as file name command line argument, piped into stdin or as a Bitmap object (of a standard framework library) if you write a function instead of a program.
Your program works with any reasonable input bitmap size, not necessarily square. Minimum width and height of 150 pixels are guaranteed.
The full moon covers at least 25% of the picture.
Your program outputs the calculated size of the moon in pixels as if it were a full moon.
We assume that the moon is a perfect sphere.
The exact size is always an integer number, but you can output a decimal number if your calculation returns that.
The accuracy should be between 98% and 102%. (That's rather a guess than something I could guarantee to be achievable. If you think it's too hard to reach, please leave a comment.)

Update:

The center of the moon isn't necessarily in the middle of the picture.
The minimum visible area is 5% of the moon or 1.25% of the total number of pixels.
The picture is taken in a way that the whole moon would fit the image, i.e. the total number of pixels is an upper boundary for the moon size.
The moon will not be cropped / clipped.

The samples

You can generate your own samples using the blend file if you like. I have created the following pictures for you. You can count pixels in a PNG file using WhitePixelCounter.exe (needs .NET) to check whether the image contains black and white pixels only and how many of them.

The following 256x256 pixel images differ in the amount of white pixels, but should all result in a calculated moon size of 16416 pixels.

And these 177x177 pixel images should return 10241 pixels. The images are basically the same, but this time a camera with a different focal length was used.

Non-square and non-centered samples with a result of 9988:

Oh, I don't have a reference implementation for now and I even don't know whether I am able to implement something. But in my brain there is a strong belief that tells me it must be mathematically solvable.

The rules

This is Code Golf. The shortest code on 2015-03-30 gets accepted.

Mathematica 126 119 109 bytes
Mathematica can measure the elongation of a component in an image.  A full moon, being perfectly symmetric, has an elongation of 0, on a scale of 0 to 1.
A diminishing moon becomes increasingly elongated, to a maximum of roughly 0.8.
0.998 -0.788 x-0.578 x^2 was the empirically determined model (based on the large photos) for `predicting the fullness of the moon (by area), given its elongation.
I adjusted the model to 1- 0.788 x -0.578 x^2 so that with exactly zero elongation (full moon) the model will return 1 for the pixel scale factor.  It saves 4 bytes and still stays within the accuracy limits.
This model is used for any size images.  The moon image does not need to be centered. It also does not need to cover a fixed proportion of the photo.
Here are the data points (elongation, displayedMoonPixels/fullMoonPixels) for the large images and the parabolic model that was generated to fit the data. Linear models fit ok, but the quadratic model is dead on, within limits (see below).
Here the data are from the large pictures.  So is the model

Below, the data (the red points) are from the small pictures.  The model (the blue curve) is the one generated by the large pictures, the same one as displayed above.
The smallest crescent has 7.5% the area of a full moon.  (The smallest crescent among the large photos is 19% of a full moon.)  If the quadratic model had been based on the small photos the fit below would be better, only because it accommodated the small crescent.  A robust model, that would stand up under a wide range of conditions, including very small crescents, would be better made from a larger variety of pictures.
The closeness of fit shows that the model was not hard-coded for the given pictures. We can be fairly certain that the elongation of a moon is independent of the size of the photo, as one would expect.

f takes the image, i, as input and outputs the predicted size of the full moon, in pixels.  It works for off-center shots.
As the data below show, it all of the test cases except one.
The moons were arranged from full to most diminished.
i_~c~t_ := Max@ComponentMeasurements[i, t][[All, 2]];
f@i_ := i~c~"Count"/(1 - 0.788 x - 0.578 x^2 /. x -> i~c~"Elongation")

More than one image component may turn up in a photo.  Even a single pixel separated from the others will be considered a distinct component.  For this reason, it is necessary to search "all" components, to find the one that has the greater number of pixels.  (One of the small photos has more than one image component.)
Large pictures
Predictions of moon size made from the large photos were uniformly accurate.
{"predicted size of full moon", f[#] & /@ large}
{"accuracy", %[[2]]/16416}

{"predicted sizes of full moon", {16422., 16270.9, 16420.6, 16585.5, 16126.5, 16151.6}}
{"accuracy", {1.00037, 0.991161, 1.00028, 1.01033, 0.982367, 0.983891}}

Small pictures
Predictions of moon size made from the small photos were uniformly, with one great exception, the final picture.  I suspect the issue stems from the fact that the crescent is very narrow.
{"predicted sizes of full moon", f[#] & /@ small}
{"accuracy", %[[2]]/10241}

{"predicted sizes of full moon",{10247.3, 10161., 10265.6, 10391., 10058.9, 7045.91}}
{"accuracy", {1.00061, 0.992192, 1.0024, 1.01465, 0.982221, 0.68801}}


Tips for golfing in Ruby What general tips can you give for golfing in Ruby?

I'm looking for ideas that can be applied to code golf problems in general that are specific to Ruby. (For example, "Remove comments" would not be an answer.)

Please post one tip per answer.

The numbers 100 to 126 can be written as ?d to ?~ in 1.8.
On a similar note if you need a single-character string in 1.9 ?x is shorter than "x".
If you need to print a string without appending a newline, $><<"string" is shorter than print"string".
If you need to read multiple lines of input $<.map{|l|...} is shorter than while l=gets;...;end. Also you can use $<.read to read it all at once.
If you're supposed to read from a file, $< and gets will read from a file instead of stdin if the filename is in ARGV. So the golfiest way to reimplement cat would be: $><<$<.read.


Paeth-transform arrays One of the key parts of PNG's compression algorithm is the Paeth transformation, which transforms the image in a way that makes it compress better (usually). In this challenge, your task is to write a program to compute a Paeth transformation. The operation of a Paeth transformation is described below.

The Paeth Transformation

The Paeth transformation subtracts from each member X of a 2-dimensional array a predictor. The predictor is that element of the array member to the left (A), top (B), and top-left (C) of X whose value has the least difference to A + B - C.

┼─┼─┼
│C│B│
┼─┼─┼
│A│X│
┼─┼─┼

If one of A, B, or C, would be out of bounds, its value is replaced by 0. Here is pseudocode from the PNG specification outlining how this predictor is computed:

function PaethPredictor (a, b, c)
begin
     ; a = left, b = above, c = upper left
     p := a + b - c        ; initial estimate
     pa := abs(p - a)      ; distances to a, b, c
     pb := abs(p - b)
     pc := abs(p - c)
     ; return nearest of a,b,c,
     ; breaking ties in order a,b,c.
     if pa <= pb AND pa <= pc then return a
     else if pb <= pc then return b
     else return c
end

For this challenge, the array members are natural numbers in the range from 0 to 255. If the Paeth transformation results in a value outside of that range, it shall be reduced modulo 256 to a value in that range.

Input and Output

The input is two integers x and y in the range from 2 to 1023 denoting width and height of the matrix to transform and an array of x × y elements. The input is formatted as decimal numbers separated by one blank character terminated with a linefeed. Here is what this input could look like:

2 3 4 5 6 7 8 9

This would represent a 2 by 3 matrix with the entries:

4 5
6 7
8 9

The output shall have the same format as the input with the relaxiation that the numbers may be separated by an arbitrary non-zero amount of whitespace characters (space, horizontal or vertical tab, line or form feed) and be terminated by an arbitrary amount of whitespace characters.

Input shall be received from stdin, output shall go to stdout. If this is not possible, choose a different way of receiving input and writing output that is not hard-coding the input.

The behaviour of your program when presented with invalid input is not part of this challenge.

Judging and Reference Implementation

An ANSI C program is provided to generate sample input, solve instances and verify solutions. Call the program with g to generate input, with s to solve an input instance and with v to verify the correctness of a solution.

If you think the reference implementation is faulty, please let me know so I can correct it as soon as possible.

Example input and output

By popular request.

10 5 166 156 108 96 63 227 122 99 117 135 125 46 169 247 116 55 151 1 232 114 214 254 6 127 217 88 206 102 252 237 75 250 202 145 86 198 172 84 68 114 58 228 66 224 186 217 210 108 11 179

representing the array

166 156 108  96  63 227 122  99 117 135
125  46 169 247 116  55 151   1 232 114
214 254   6 127 217  88 206 102 252 237
 75 250 202 145  86 198 172  84  68 114
 58 228  66 224 186 217 210 108  11 179

is transformed into

166 246 208 244 223 164 151 233  18  18
215 177 123  78 125  84  96 135 231 138
 89 129   8 121 101 228  55 101  20 123
117 175 196 199 125 112 222 238  72  46
239 234 120 158  41  19  12  24 183 111

which is encoded as

10 5 166 246 208 244 223 164 151 233 18 18 215 177 123 78 125 84 96 135 231 138 89 129 8 121 101 228 55 101 20 123 117 175 196 199 125 112 222 238 72 46 239 234 120 158 41 19 12 24 183 111

Winning Condition

For this challenge, write a program that generates correct Paeth transformation of the input and writes them out. This is code-golf, the program with the least amount of characters in its source code wins. Please try to attach an explanation and a readable version of your code to your submission so others can see what it does.

J - 77 char

Taking an approach that looks different from FUZxxl's answer but is actually very similar.

1!:2&4":2({.,|.@{.,@(256|$-0(0{[/:+`-/|@-])"1@|:(-#:1 2 3)|.!.0$)}.)0".1!:1]3

Some comments on the interesting bits.

1!:2&4": (...) 0".1!:1]3 - If J wasn't terrible about I/O and parsing, this could be refactored as to use &.".&.stdin'', to save 3 chars. But it is so we can't. Rest in peace, precious characters.
2 ({.,|.@{.,@( ... stuff using $ ... )}.) - This disassembles the input and reassembles the output. We use $ both as a reference to the input in stuff using $, and as an operation we need to perform on the input before running the stuff on it.
0( blah )"1@|: - Yes, that's a dyadic Transpose: we regroup the three rotation results as the innermost array axis, so that the Paeth logic can apply on each set separately with "1.
0{[/:+`-/|@-] - The Paeth logic: sort a,b,c by the magnitudes of (p minus each of a,b,c), and take the first.


May the wind be always at your back You are Odysseus, and are finally free from Calypso (who has kept you captive for many years) after you drugged her while she was sleeping1. You wish to return to your homeland of Ithaca, but the ship you've stolen is a bit damaged and cannot steer. However, you have also stolen a map which contains the location of Calypso’s island as well as the locations of Ithaca and the small islands that lie in between, as well as information about the wind currents of the area. Your ship can only sail by the wind currents, but you get to choose the direction you start in (north, south, east, west). If the currents bring you to another island, you also get to choose the direction in which you depart that island.
Can you get home to Ithaca?
[1] Because that definitely happens in the epic.
Input Format
The input consists of:

positive integers w and h
a w-by-h grid of characters representing the map, where:

~ denotes calm sea
^ denotes a wind blowing north
v denotes a wind blowing south
< denotes a wind blowing west
> denotes a wind blowing east
c denotes Calypso's island, your starting point
i denotes Ithaca, the destination
* denotes an intermediate island

Each “wind” character moves you one cell in the direction of the wind, and winds never form loops (i.e. there is no way to get trapped in a cycle of winds).
You may take input however you want (reading a file, from STDIN, as function parameters etc.)
Output
Output a truthy value if it is possible to get to Ithaca, and a falsy value if that is not possible.
Test Cases
w=10, h=5
~^~~~~~~~~
~c>>*>>v~~
~v~~v~~v~~
~>>*<~~*>i
~~~v~~~~~~
Expected Output: True
Explanation: Go east, then east again, then east again

w=8, h=5
~~~~~~~~
~~>>v~~~
<<c~~~~~
~~>~i~~~
~~~~~~~~
Expected Output: False
Explanation: There are two paths that lead to cells neighboring Ithaca,
but there is no wind on those cells.

w=5, h=2
<c>>>
~v~~i
Expected Output: False
Explanation: Although you can get to a distance of one cell away from
Ithaca, the wind on that cell is eastward which pushes Odysseus
off the map instead of to Ithaca.

w=20, h=6
~~~~~~~~~~~~~~~~~~~~
~~v<<<<<<*<<>>>v>~~~
~~i~<<*<<<<c~~~*~~~~
~~~~~~^~~~~v~~~^~~~~
~~~~~~<<*>>>>>>^~~~~
~~~~~~~~~~~~~~~~~~~~
Expected Output: True
Explanation: North, then West

w=20, h=6
~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~*<<>>>v>~~~
~~i<v<*<<<<c~~~*~~~~
~~~~v~^~~~~v~~~^~~~~
~~~~v~<<*>>>>>>^~~~~
~~~~v~~~~~~~~~~~~~~~
Expected Output: False
Explanation: Although there is a wind leading to Ithaca, it is inaccessible.

Standard loopholes are prohibited. This is code-golf, so the shortest solution in bytes in each language wins.

Python 3.8 (pre-release), 176 bytes

lambda w,h,b:b.find('i')in(r:={b.find('c')})|{r.update(*([{(d:={'<':i-1,'>':i+1,'^':i+~w,'v':i-~w}).get(b[i],i)},{*d.values()}][b[i]in'*c']for i in r if-1<i<len(b)))for _ in b}

Try it online!
Ungolfed
def f(w,h,b):
  r = {b.find('c')}
  for _ in b:
    for i in list(r):
      if 0 <= i < len(b):
        d = {'<':i-1,'>':i+1,'^':i-w-1,'v':i+w+1}
        if b[i] in '*c':
          r.update(d.values())
        r.add(d.get(b[i],i))
  return b.find('i') in r


Drunkard's Journey Home Drunkard's Journey Home
In this challenge you are to write a program which simulates a drunkard stumbling his way home from the bar.
Input:
The input will be an adjacency matrix (representing a directed graph) which represents paths the drunkard can take. At each location, the drunkard will choose one path at random (Each option has an approximately equal chance and is independent of prior choices) to follow.
Assume that the drunkard always starts at the bar (first row in the adjacency matrix).
If the drunkard enters a dead-end it can be assumed that he has either made his way home or has been arrested for public intoxication and the program should return his path.
It can be assumed that the graph will always contain at least one dead-end.
It can also be assumed that the drunkard will always be able to exit the bar (the first row will not be all zeroes) and that if the drunkard would be stuck in a location, that the row would be represented by all zeroes.
Output:
The output will be the path the drunkard took in his attempt to make his way home. The values for the locations can be either zero or one indexed.
Examples:
Input
[1,0,1,1]
[0,0,0,0]
[1,0,0,0]
[1,1,1,1]

Possible Outputs
[0,2,0,3,2,0,0,3,1]
[0,3,0,3,1]

Input
[0,1,1,1,0,1]
[1,0,1,0,1,1]
[0,0,0,0,0,0]
[0,0,0,0,0,1]
[1,0,0,0,0,0]
[0,0,0,0,0,0]

Possible outputs
[0,1,5]
[0,5]
[0,1,4,0,2]
[0,3,5]
[0,3,0,1,4,0,5]

Deterministic path:

Input
[0,0,1,0]
[0,0,0,1]
[0,1,0,0]
[0,0,0,0]

Output
[0,2,1,3]

Mathematica, 72 bytes

{1}//.{r___,x_}:>{r,x,n=1;Check[RandomChoice[#[[x]]->(n++&/@#)],##&[]]}&

This is a function takes the matrix as an argument and returns a list, and it uses 1-indexing.

The basic idea is to start with

{1}//.

which repeatedly applies the rule that follows to the list {1} until it stops changing. The rule matches the pattern

{r___,x_}:>

which means "a list with zero or more elements called r followed by an element called x." This gives x as the last element in the current list, and we replace the list with

{r,x,<stuff>}

which is the original list with <stuff> appended. The stuff in question is

RandomChoice[#[[x]]->(n++&/@#)]

which takes #[[x]] (the xth element of the input matrix) as a list of weights and maps them to n++&/@#, which is short for Range@Length@# (i.e. {1,2,3,...} with the appropriate length). This will throw an error if the weights are all zero, which is why it's wrapped in a

Check[...,##&[]]

which will return ##&[] if an error message is generated. This is just a fancy way of writing Sequence[], which acts as a "nothing" element ({1,2,Sequence[],3} evaluates to {1,2,3}) and therefore leaves the list unchanged, causing the //. to stop replacing.


Polynomial Interpolation Write a program that performs Polynomial Interpolation  using true arbitrary precision rational numbers. The input looks like this:

f(1) = 2/3
f(2) = 4/5
f(3) = 6/7
...

You may assume that there's exactly one whitespace before and after the = sign, all the numbers are either fractions or integers. You may also assume, that all fraction in the input are already irreducible.
No error checking is needed, you may assume, that the input is valid and no x is doubled in the f(x).
The output should be in a LaTeX compatible form, the emitted LaTeX code should yield the same graphical representation as the output given here.

f(x) = 123x^2 + \frac{45}{2}x + \frac{7}{4}

The fraction must be reduced as much as possible, eg. something like \frac{2}{4}  is not allowed. If the number is integer, don't use a fraction.
Special rules:
Your program should...

work for polynomials up to degree 12
complete in less then 1 minute for reasonable input
not use any functions that do the whole calculation for you
output the polynomial of smallest possible degree

Testcases:
The given testcases are just for clarification. Your program should yield correct result for all correct inputs.
Input

f(1) = 2/3
f(2) = 4/5
f(3) = 6/7

Output

f(x) = - \frac{4}{105}x^2
       + \frac{26}{105}x
       + \frac{16}{35}

Input

f(-12) = 13/2
f(5/3) = 3/5
f(13) = -6
f(1/5) = -3/4

Output

f(x) = - \frac{2186133}{239455744}x^3
       + \frac{2741731}{149659840}x^2
       + \frac{26720517}{29201920}x
       - \frac{279464297}{299319680}

Input

f(4/3) = 617/81
f(2) = 20/3
f(-8/3) = 6749/81
f(-5) = 7367/12
f(0) = 23/3

Output

f(x) = \frac{1}{2}x^4
     - 2x^3
     + \frac{7}{4}x^2
     + \frac{23}{3}

Input

f(0) = 5
f(1) = 7
f(2) = 9
f(3) = 11
f(4) = 13

Output

f(x) = 2x
     + 5

Input

f(1/2) = -1/2
f(-25) = -1/2
f(-54/12) = -1/2

Output

f(x) = -\frac{1}{2}


Your code has an uncanny mirror twin… Write two programs, each taking a string s and a number n ≥ 0, such that:

The first program prints s n times, separated by newlines.
The second program prints each character of s n times, with repeated characters separated by newlines.
Every character at column x, line y in one program equals the character at column y, line x in the other program.

Both programs must contain at least two lines. You may take input in any reasonable order or format that works for both programs.

This is code-golf; the less bytes, the better. Count bytes from your longer program (that is, the one with more lines than columns).

Here's an example in a hypothetical programming language, with s = "Hello, world!" and n = 3:

Program A

a(b*c
defg
h.ij)

Output

Hello, world!
Hello, world!
Hello, world!

Program B

adh
(e.
bfi
*gj
c )

Output

HHH
eee
lll
lll
ooo
,,,

www
ooo
rrr
lll
ddd
!!!


The Permutation Pigeon-hole Principle In the game of sudoku, many players like to "pencil in" possible numbers that can go in each square:

The above row can be represented as an array:
[[1,2,9], [6], [5], [7], [1,2,9], [1,2,9], [3], [1,2,4], [8]]

Now, notice that there is only 1 place where a 4 can go.  This effectively lets us simplify the above list to:
[[1,2,9], [6], [5], [7], [1,2,9], [1,2,9], [3], [4], [8]]

The goal of this challenge is to take a list of possible numbers in a permutation, and deduce which possibilities can be eliminated.
As another example, lets say you have the following array of possibilities:
[[0,1,3], [0,2,3], [1,2], [1,2]]

The last two places must be filled with 1 and 2.  Therefore, we can remove those possibilities from the first two elements in the array:
[[0,3], [0,3], [1,2], [1,2]]

As another example:
[[0,1,2,3], [0,2], [0,2], [0,2]]

Its impossible to construct a permutation from the above possibilities, as there's only 1 location for both 1 and 3, and you would want to return an empty array.
You need to input a list of possibilities and output the remaining possibilities after the maximum number of possibilities have been eliminated.

If a particular array is impossible, you either need to return an empty array, or an array where one of the subarrays is empty.
You may assume that the array will be well-formed, and have at least 1 element.
Given an array of size N, you can assume the numbers in the subarray will always be in the range [0:N), and that N <= 10
You may not assume that every number from 0 to N-1 will be present
You may assume that numbers within a single subarray are unique.
If a subarray contains only a single possibility, you can either represent the possibility in an array or by itself.  [[1],[2],[0]], [1,2,0], [[1,2],0,[1,2]] are all valid.
You may accept the array either in a reasonable string format or in list/array format.
Subarrays can be in any order.
Instead of dealing with ragged arrays, you can pad empty places with -1.

Test cases
[[0]]                                         -> [[0]]
[[1],[0]]                                     -> [[1],[0]]
[[1],[1]]                                     -> []
[[1],[0,1]]                                   -> [[1],[0]]
[[0,1,2],[1,2],[1,2]]                         -> [[0],[1,2],[1,2]]
[[0,1],[1,2],[0,2]]                           -> [[0,1],[1,2],[0,2]]
[[2,1],[1,2],[1,2]]                           -> []
[[0,3],[2,1],[3,0],[3,2]]                     -> [[0,3],[1],[0,3],[2]]
[[0,1],[0,1],[2,3],[2,3,0]]                   -> [[0,1],[0,1],[2,3],[2,3]]
[[0,1],[0,3],[3,2],[0]]                       -> [[1],[3],[2],[0]]
[[3,5,2],[0,2,4],[4,0],[0,1,3,5],[2,1],[2,4]] -> [[3,5],[0,2,4],[4,0],[3,5],[1],[2,4]]
[[6,9,8,4],[4,5],[5,3,6],[3,8,6,1,4],[3,1,9,6],[3,7,0,2,4,5],[9,5,6,8],[6,5,8,1,3,7],[8],[8,0,6,2,5,6,3]] -> [[6,9,4],[4,5],[5,3,6],[3,6,1,4],[3,1,9,6],[0,2],[9,5,6],[7],[8],[0,2]]
[[3,5,0],[5,7],[5,1,2],[1,3,0],[5,3],[5,0],[5,3,7,8,0,6],[7,5,0,1,8],[1,0,8],[0,6]] -> []
[[9,0,2,3,7],[0,7,6,5],[6,9,4,7],[9,1,2,3,0,5],[2,8,5,7,4,6],[6,5,7,1],[5,9,4],[5,9,3,8,1],[5,0,6,4],[0,7,2,1,3,4,8]] -> [[9,0,2,3,7],[0,7,6,5],[6,9,4,7],[9,1,2,3,0,5],[2,8,5,7,4,6],[6,5,7,1],[5,9,4],[5,9,3,8,1],[5,0,6,4],[0,7,2,1,3,4,8]]
[[2,6,0],[0,4,3],[0,6,2],[0,7],[0,9,2,3,6,1,4],[1,7,2],[2,7,8],[8,6,7],[6,5,2,8,0],[5,8,1,4]] -> [[2,6,0],[3],[0,6,2],[0,7],[9],[1],[2,7,8],[8,6,7],[5],[4]]
[[8],[8,0,6,5,7,2,4,1],[8,6,9,3,5,0,7],[3,9,1,0],[9],[9,2,6],[2,8,3],[3,1,6,8,2],[6],[6,4,5,3,0,7]] -> [[8],[5,7,4],[5,7],[0],[9],[2],[3],[1],[6],[4,5,7]]
[[8,1,0],[5,8,7,6,2,0],[6,8,2],[2,4,0,9],[4,1,7,3,6,8],[8,1],[8,0,3],[0,8,2],[0,8,3],[1,8,0]] -> []

This is a code-golf so make your answers as short as possible!

Brachylog, 21 bytes

:1fz:da|,[]
:2a#d
:Am

Try it online!

Try it online!

Predicate 0 (main predicate)

:1fz:da|,[]
:1f            Find all solutions of Predicate 1 using Input as Input.
   z           Transpose
    :da        Deduplicate each.
       |,[]    If there is no solution, return [] instead.

Predicate 1 (auxiliary predicate 1)

:2a#d
:2a     Each element of Output satisfies Predicate 2 with each element of Input as Input
   #d   Each element is different

Predicate 2 (auxiliary predicate 2)

:Am     Output is member of Input


Peel away the layers - Robbers This is the Robbers thread. For the Cops challenge, see here
As the robbers, your job is to crack the cops' answers. Choose an uncracked, unsafe cop answer and attempt to figure out which languages, in which order, the cop used.
Note that a crack is valid even if the languages are different. So long as the the languages you find, in the order you state them, produce the specified final phrase, the crack is valid, even if the languages are not the same as the intended or original cop answer.
If you are unable to fully crack a cop's answer and decide to abandon your attempt, you can (but are by no means expected to) comment underneath the cop's answer with the languages you've already figured out, in order to help other users.
Having fully cracked a cop's answer, post an answer to this thread listing all the languages, along with their outputs in the following format:
# [<cop>'s answer](<link to answer>), <N> layers

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

---

<anything else>

After posting an answer, leave a comment below the cop's post to let them know it's been cracked. If you have \$<50\$ reputation at the time of posting, and therefore cannot comment, I (or another able user) will be happy to do so for you, simply make a note of this in your answer and someone will take care of it.
This challenge can result in some very difficult answers to crack - more so than the standard cops-and-robbers - due to the fact that the number of languages a cop could've used increases exponentially per layer they have. Therefore, be sure to check out the Robbers' chatroom to get help cracking an answer, or to help others.
Your score is calculated the following way:

If you crack \$n\$ answers, with \$x_1, x_2, ..., x_n\$ languages being used (i.e. the first has \$x_1\$ languages, the second \$x_2\$ etc.), your score is

$$\frac{1}{n}\sum^n_{i=1}x_i$$
i.e. the total number of languages you cracked, divided by the total number of answers you cracked. The lower your score, the better. Don't bother editing your score into your answers, a winner will be declared when all cop answers are either cracked or safe.
Good luck!

Sisyphus's Answer, 33 layers
i=496;a=     0
print('gREETINGS!'.swapcase()if a==447775else'i=%3s;a=%6s%s'%(i-16,a+(int(1/2*2)*int('syd0s6ncczl7ka1ioletm9t1atoqjq2awpshwfxcorai94tcmzim91j2zzq2c08wxjmfmzr0x9euhjojhltjpay0g8t1o78y83a',36)>>i&0xFFFF),open(__file__).read().strip()[14:]))

All layers are Python, in this order: 3, 3, 3, 3, 3, 2, 3, 3, 2, 2, 2, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2/3 (the last layer does not matter).
Special thanks to @Riolku for helping me find the right algorithm for subset sum (because I'm bad at computer science and Google)
Since there are so many layers, writing them all as a list would be rather difficult and take me a lot of time (and anyone who wants to verify it a ton of time), so instead you can verify it by running all 33 layers with this Bash program that compiles all of the layers together.
Let me know if this posting format is invalid.


Is my OS 32-bit or 64-bit? It's not too important anymore, but occasionally somebody needs to know.

Here is a simple golf: Taking no user input, tell me if the computer on which the code is run is on a 64-bit operating system, or a 32-bit operating system!

If the code is run on a 32-bit operating system, print "32", if the code is run on a 64 bit operating system, output "64". Important:  Print any other non-empty string of alphanumeric characters if it's neither 32 or 64 bit.

Please note that a 32 bit program running on a computer with a 64 bit operating system should output "64". You can assume that users will use 64 bit software whenever possible.

To be eligible for entry, your code must be able to run on Windows 4.10 or newer Microsoft supported Windows systems, and at least one flavor of Linux of your choosing (so long as that flavor is gratis). Compatibility mods can be installed, so long as the program still returns the right value.

The usual code-golf rules apply.

Note: If your  answer is only meant to print out 32 or 64, but not the alt case, I'll accept it, but it is not a competing answer.

I'll try and post some results of running these codes on different OSes later!

x86 machine code, 12 bytes
8c c8 83 f8 23 b0 20 75 02 00 c0 c3

Ungolfed:
getKernelBitness:
    mov eax,cs
    cmp eax,0x23 ; 32 bit process on 64 bit kernel has this selector in CS
    mov al,32
    jne kernelIs32Bit
    add al,al    ; return value in eax
kernelIs32Bit:
    ret

This function works in Linux when used in ELF32, following i386 SysV ABI, as well as in Windows/Wine when used in PE32, following stdcall calling convention.


It's a Slippery Slope There has not been a challenge regarding slope fields, as a far as I can tell. So, I might as well make one.

The challenge

Given:

A black box function f which takes two arguments, x and y (both real numbers) , and returns the value of the slope at point (x,y) (also a real number)
A list of real numbers, X, representing the values along the x axis,
Another list of real numbers, Y, representing the values along the y axis.
A list of (x,y) pairs, U, which represents the inputs that f is undefined on. This argument can be removed if your language can detect errors.

Output:

A rectangle with a length of the length X, and a height of the length of Y. At each combination of row r and column c in the rectangle, (starting from the bottom left corner), the character that is placed at that position will depend on the sign value of f evaluated at x=c and y=r:

If the value is positive, the character is /.
If the value is zero, the character is -.
If the value is negative, the character is \.
If (x,y) is not in the domain of f (a.k.a. a member of U), then the character is . f is guaranteed to not error on every combination of x within X and y within Y if U is utilized.

Since I am horrible at explaining things, here's an example:

Input:

f(x,y) = x / y
X=[-1,0,1]
Y=[-1,0,1]
U=[[-1,0],[0,0],[1,0]]

Output:

\-/

/-\

At (0,0) (the bottom left corner), the corresponding X and Y values are -1 and -1 (since X[0] = -1 and Y[0] = -1). f(-1,-1)=(-1)/(-1)=1, thus / is used.
At (1,0) (the bottom row, middle column): X[1] = 0, Y[0] = -1, f(0,-1)=(0)/(-1)=0, and 0 is zero (duh), so the character is -.
At (1,1) (the center): X[1] = 0, Y[1] = 0. [0,0] is a member of U. Therefore, it corresponds to the  character. Or, if done without U: 0/0 is undefined, thus the character is .
At (2,2) (the top left): X[2] = 1, Y[2] = 1, f(1,1)=(1)/(1)=1, which is positive. Therefore, it corresponds to the / character.
Etc...

Floating Point

Any value of f within the range [-1e-9,1e-9] should be considered to have a sign of 0.

Winning condition

This is a code-golf, so lowest byte count wins!

Jelly, 23 bytes

Ṛ⁹,2⁶v$Ṡ$e⁵$?¥þị“/ \-”Y

Try it online!

Arguments: Y, X, U, f

f is a Python string containing Jelly code. Be sure to quote it appropriately, otherwise you may encounter errors.

Also, f takes a pair [x, y] as its argument, not two arguments x and y.


Fibtraction - Fibonacci but with subtraction The Fibtraction sequence (as I call it) is similar to the Fibonacci sequence except, instead of adding numbers, you subtract them.

The first few numbers of this challenge are:

1, 2, -1, 3, -4, 7, -11, 18, -29, 47, -76, 123, -199, 322, -521, 843, -1364...

The sequence starts with 1 and 2. Every next number can be calculated by subtracting the previous number from the number before it.

1
2
-1 = 1 - 2
3  = 2 - (-1) = 2 + 1
-4 = -1 - 3
7  = 3 - (-4) = 3 + 4
...

In other words:

f(1) = 1
f(2) = 2
f(n) = f(n - 2) - f(n - 1)

This is OEIS sequence A061084.

Challenge

Write a program/function that takes a positive integer n as input and prints the nth number of the Fibtraction sequence.

Specifications

Standard I/O rules apply.
Standard loopholes are forbidden.
Your solution can either be 0-indexed or 1-indexed but please specify which.
This challenge is not about finding the shortest approach in all languages, rather, it is about finding the shortest approach in each language.
Your code will be scored in bytes, usually in the encoding UTF-8, unless specified otherwise.
Built-in functions that compute this sequence are allowed but including a solution that doesn't rely on a built-in is encouraged.
Explanations, even for "practical" languages, are encouraged.

Test cases

These are 0-indexed.

Input      Output

1          2
2          -1
11         123
14         -521
21         15127
24         -64079
31         1860498

That pattern was totally not intentional. :P

This challenge was sandboxed.

  Before you go pressing any buttons that do scary things, hear me out. This might be considered a dupe of the regular Fibonacci challenge and I agree, to some extent, that it should be easy enough to port solutions from there. However, the challenge is old and outdated; is severely under-specified; allows for two types of solutions; has answers that don't have easy ways to try online; and in general, is lacking of answers. Essentially, in my opinion, it doesn't serve as a good "catalogue" of solutions.

plz send teh codez

Oasis, 4 bytes
c-21

Try it online!
0-indexed.
I saw this language used for a similar challenge once, and immediately I knew I should try it here. Can't say I'm disappointed.
Explanation
   1    a(0) = 1
  2     a(1) = 2
c       a(n) = a(n - 2)
 -                      - a(n - 1)


Primes of Ulam's Spiral Ulam's spiral is a truly fascinating, yet puzzling, topic in mathematics. How it works in detail can be found here, but a short summary can be explained as so:

I start off by writing a one, then I write a two to the right of it. Above the two, I write a three, and to the left of that I write four. I continue this pattern of circling around 1 (and any numbers between me and 1) infinitely (or until told to stop), forming a spiral pattern. (see example below)

The Objective

Make a program that accepts n (will always be an odd number greater than zero) as an input that correlates with the number of rows, then prints out the values of the primes row by row of the Ulam spiral. The formatting can be any fashion, but must be human readable and obvious.

For example, given the input 3, your program should output 5,3,2,7, because 3 rows produces the following spiral:

5 4 3 <-- first row has the primes 5 and 3
6 1 2 <-- second row has the prime 2
7 8 9 <-- third row has the prime 7

As this is a code golf, the answer with the fewest bytes wins (no matter how inefficient)! Standard loopholes are not acceptable.

Pyth, 20 bytes

f}TPTsuC+R=hZ_GtyQ]]

Try it online: Demonstration

This code generates the fully Ulam's spiral, connects all lines and filters for primes.

Explanation:

f}TPTsuC+R=hZ_GtyQ]]   implicit: Z = 0
      u           ]]   reduce, start with G = [[]]
               tyQ     for H in [0, 1, ..., 2*input-2] do:
             _G           reverse the order of the lines
        +R=hZ             append Z + 1 at the end of each line,
                          updating Z each time with the new value Z + 1
       C                  update G with the transposed of ^
                       this gives the Ulam's spiral
     s                 combine all lines to a big list of numbers
f                      filter for numbers T, which satisfy:
 }TPT                    T appears in the prime-factorization of T
                         (<==> T is prime)


Leon's shooting range problem Leon's story

Leon is a professional sling shooter and he comes to a shooting range everyday to practice. A casual target is not a challenge for him anymore so before shooting he first covers the target of radius 1.0 with k rectangle stickers. He then fires n shots that cannot hit the stickers.

What's special about Leon is that he always shoots randomly but with a uniform distribution.

Leon everyday takes on a bigger challenge and puts more stickers. However he started noticing that shooting takes too much time now so he decided to ask you for the best strategy.

Task

Implement a program which will randomly pick n points with the lowest time complexity possible. Each point should be inside a circle target, and none of them lands in any of k rectangle stickers.

Input:

List of k rectangles in whatever form fits you.

Eg. where each rectangle is a list of:

[x_min, x_max, y_min, y_max]

The list could be:

[[0.1, 0.3, -0.2, 0.1], [-0.73, -0.12, 0.8, 1.4]]

Output:

List of coordinates of n points in whatever form fits you.

Rules:

Points have to be picked randomly with uniform distribution
Every point lays inside a circle
None of the points lays inside a rectangle sticker
Stickers can overlap each other
Circle's radius is equal to 1.0 and its center is at coordinates (0.0, 0.0)
Every coordinate is in form of floating point number
For edge cases - choose whatever fits you

EDIT:
Thanks to @Luis Mendo and @xnor it turned out that one more rule might be useful.

With each new sticker 1/4 of the remaining board will be covered. This means that having k stickers the uncovered part of the target will be (3/4)^k of the whole.

Rating

The best time complexity wins!

EDIT:

For the sake of rating we will assume that k and n are linearly proportional, meaning that O(k^2 + n) will be rated equally to O(k + n^2)

Area-based algorithm, \$O(k^2+n\log(k))\$
Our general strategy is to instead select points (outside the sticker rectangles) from the square (-1,-1) to (1,1), then repeat if we don't get a point within the circle. On average, we will have to select \$\frac{4}{\pi}\$ points from the square for each point in the circle.
The runtime is not depend on rectangle coverage, but it does depend on measures of rectangle intersection (denoted L in the complexity analysis in the code). For the listed complexity, I use \$L=O(k)\$, which is probably not tight. If \$L=O(\log(k))\$ can be proven, then the complexity is \$O((k+n)\log(k))\$ (see get_heights for an algorithmic alternative).
Define "open area" to be the area that points could be generated in. Recall that we are using a square instead of a circle, so the total area is piece-wise linear in x.

Precompute the total open height function \$h(x)\$ (this is piece-wise constant, so store the change at each transition: either the start or end of a new rectangle). Similarly, pre-compute the cumulative areas \$\int_{-1}^{x} h(x)\$, which is piece-wise linear, so once again store the value at each transition. This can be done in \$O(k \log(k))\$ time

Precompute the intervals on which y coordinates can be distributed for a given x (again, only storing this interval on each transition). This might be able to be done in \$O(k \log(k))\$, but this algorithm only succeeds at \$O(k^2)\$ time

Generate points. For each point: (average \$\frac{4}{\pi} n\$ times for a total runtime of \$O(n\log(k))\$
a. Choose a random value \$r\$ for the area (\$O(1)\$)
b. Find \$x\$ such that \$\int_{-1}^{x} h(t) dt = r\$. This is accomplished through binary search on the pre-computed heights \$h\$ and cumulative areas \$\int h\$, so this is done in \$O(\log(k))\$ time
c. Choose a random value \$y\$ for the given x such that (x,y) is in an open area. Through similar binary search as 3b, this is done in \$O(\log(k))\$ time
d. Reject the point if it is outside the circle (constant factor 4/pi)

The total runtime is \$O(k\log(k)) + O(k^2) + O(n\log(k)) = O(k^2+n\log(k))\$
In the following example images, I used the same n=10000, so more rectangle coverage meant a higher density of points.

Full python code below, including matplotlib display:
import math
import random
# for binary search
import bisect
# matplotlib for plotting the output points
import matplotlib.pyplot as plt
import matplotlib

def find_le(ls, x):
    # find_le is O(log(|ls|))
    # Find rightmost value less than or equal to x in ls
    i = bisect.bisect_right(ls, x)
    return i-1, ls[i-1]

class Interval:
    def __init__(self, lo, hi):
        # each range is tuple (lo, hi)
        # ranges shall be sorted in ascending order
        # each range does not overlap with other ranges
        self.ranges = [(lo, hi)]

    def remove(self, lo, hi):
        new_ranges = []
        for self_range in self.ranges:
            if lo <= self_range[0] <= hi < self_range[1]:
                new_ranges.append((hi, self_range[1]))
            elif self_range[0] < lo <= self_range[1] <= hi:
                new_ranges.append((self_range[0], lo))
            elif self_range[0] < lo < hi < self_range[1]:
                new_ranges.append((self_range[0], lo))
                new_ranges.append((hi, self_range[1]))
            elif lo <= self_range[0] < self_range[1] <= hi:
                pass
            elif hi <= self_range[0] or self_range[1] <= lo:
                # no overlap
                new_ranges.append(self_range)
        self.ranges = new_ranges

    def cache_lengths(self):
        # If L is the number of subintervals of this Interval
        # then cache_lengths is O(L) ⊂ O(k)

        # in cum_lengths, (0.6, 0.7) means that the total length to the
        # left of x=0.7 in this interval is 0.6
        self.cum_lengths = [(0, -1)]
        last_length = 0
        for self_range in self.ranges:
            length = self_range[1] - self_range[0]
            self.cum_lengths.append((last_length, self_range[0]))
            last_length += length
        self.total_length = last_length

    def random_point(self):
        # If L is the number of subintervals of this Interval
        # then random_point is O(log(L)) ⊂ O(log(k))
        r = random.random()*self.total_length
        # This find_le is O(log(L))
        i, (length_left, x_left) = find_le(self.cum_lengths, (r,))
        return (r - length_left) + x_left

    def __repr__(self):
        return "I" + str(self.ranges)

def interval_complement(rects):
    # O(L) where L is the length of rects list
    interval = Interval(-1, 1)
    for rect in rects:
        interval.remove(rect.bottom, rect.top)
    return interval

class Rect:
    def __init__(self, left, right, bottom, top):
        self.left = min(left, right)
        self.right = max(left, right)
        self.bottom = min(bottom, top)
        self.top = max(bottom, top)
        self.width = self.right - self.left
        self.height = self.top - self.bottom

    def __repr__(self):
        return f"Rect({self.left}, {self.right}, {self.bottom}, {self.top})"

    def overlap(self, others):
        # returns vertical (y) overlap between self and other rects
        total_overlap = 0
        # https://pyinterval.readthedocs.io/en/latest/guide.html#operations is
        # looking so tempting right now, but unions/merges would
        # require Principle Inclusion-Exclusion which can be k^2 worst case
        starts = sorted(others, key=lambda rect: rect.bottom, reverse=True)
        ends = sorted(others, key=lambda rect: rect.top, reverse=True)
        active_rects = set()
        overlap_start = self.bottom
        while ends:
            if starts and starts[-1].bottom < ends[-1].top:
                active_rect = starts.pop()
                if not active_rects and active_rect.bottom > self.bottom:
                    # This is the start of an overlap interval
                    overlap_start = active_rect.bottom
                active_rects.add(active_rect)
            else:
                active_rect = ends.pop()
                active_rects.remove(active_rect)

                if not active_rects:
                    # This is the end of an overlap interval
                    # Rare cases of negative = started and ended below start of self
                    total_overlap += max(0, min(active_rect.top, self.top) - overlap_start)
        return total_overlap

    def as_matplotlib_rect(self):
        return matplotlib.patches.Rectangle((self.left, self.bottom), self.width, self.height)

def get_heights(rects):
    # get_heights is O(k log(k)) total
    # Sorting: O(k log(k))
    # Use these lists as a queue
    starts = sorted(rects, key=lambda rect: rect.left, reverse=True)
    ends = sorted(rects, key=lambda rect: rect.right, reverse=True)
    # list of tuples (open height starting at x, x, open intervals starting at x)
    heights = [(2, -1, Interval(-1,1))]
    active_rects = set()
    while ends:
        # inner loop performed once for k left edges and k right edges,
        # so this is O(k)
        if starts and starts[-1].left < ends[-1].right:
            # next x-pos is the start of a new rect
            rect = starts.pop()
            height_diff = rect.height - rect.overlap(active_rects)
            height = heights[-1][0] - height_diff
            active_rects.add(rect)
            # interval_complement is O(L) so this is O(k^2), not sure if it is O(k log(k))
            heights.append((height, rect.left, interval_complement(active_rects)))
        else:
            # next x-pos is the end of an old rect
            rect = ends.pop()
            active_rects.remove(rect)
            # rect.overlap is O(L) as well
            height_diff = rect.height - rect.overlap(active_rects)
            # Two choices to get O(k log(k)):
               # 1. prove that |active_rects| is O(log(k)) under the given approaches
               # 2. avoid using interval_complement on each transition using some increments approach, and avoid doing rect.overlap on each transition
            height = heights[-1][0] + height_diff
            heights.append((height, rect.right, interval_complement(active_rects)))
    heights.append((2, 1, Interval(-1,1)))
    # cum_areas is the cumulative areas from -1 to x (of not rects)
    # Not subtracting curve because we will be sampling from square
    cum_areas = [(0, -1, Interval(-1, 1))]
    last_height = 2
    for height, x, interval in heights[1:]:
        last_area, last_x, _ = cum_areas[-1]
        new_area = (x-last_x)*last_height
        cum_areas.append((last_area + new_area, x, interval))
        last_height = height
    return (heights, cum_areas)

def random_pick_points(rects, num_points):
    # random_pick_points is O((n+k) log(k))
    # Step 1. Precompute heights: O(k log (k))
    heights, cum_areas = get_heights(rects)
    total_area = cum_areas[-1][0]
    points = []
    # Step 2. Precompute vertical intervals: O(k)
    for _, _, y_interval in cum_areas:
        y_interval.cache_lengths()
    # Step 3. Sample points outside rects and within circle
    # Total time complexity of this loop is O(n log(k))
    while len(points) < num_points:
        # This loop is reached average (4/pi)*n = O(n) times
        # Each occurence has complexity O(log(k))
        # Step 3a. Choose a random area value
        area = random.random()*total_area
        # Step 3b. Choose the x value such that area is the total area
        # outside rects and within 2x2 square to the left of x
        # There are 2k+1 total cum_areas so this find_le is O(log(k))
        i, (area_left, x_left, y_interval) = find_le(cum_areas, (area,))
        height, _, _ = heights[i]
        x = x_left + (area - area_left) / height
        # Step 3c. Choose a y value uniformly in the open spaces of that x value
        # Interval.random_point() is O(log(k))
        y = y_interval.random_point()
        # Step 3d. Rejection sample until points are inside the circle
        # On average, takes constant 4/pi random points to land within the circle
        if x*x + y*y < 1:
            points.append((x, y))
    # Done!
    return points

def display_points(rects, points):
    fig, ax = plt.subplots(1)
    ax.plot(*zip(*points), 'ko', markersize=1, alpha=0.5)
    ax.axis([-1, 1, -1, 1])
    ax.add_collection(
        matplotlib.collections.PatchCollection(
            [rect.as_matplotlib_rect() for rect in rects],
            facecolor = 'r', edgecolor='None', alpha=0.5
        )
    )
    plt.show()

def display_random_points(rects, num_points):
    points = random_pick_points(rects, num_points)
    display_points(rects, points)

def random_rects(k):
    return [Rect(*[random.random()*2-1 for _ in range(4)]) for i in range(k)]

k = 20
# rects = random_rects(k)
# print("Rects:", rects)
n = 10000
# print("Points:", random_pick_points(rects, n))
display_random_points(random_rects(k), n)

Try it online I guess, if you can read a list of points.


Largest Prime Exponents Given an integer n >= 2, output the largest exponent in its prime factorization. This is OEIS sequence A051903.
Example
Let n = 144. Its prime factorization is 2^4 * 3^2. The largest exponent is 4.
Test Cases
2 -> 1
3 -> 1
4 -> 2
5 -> 1
6 -> 1
7 -> 1
8 -> 3
9 -> 2
10 -> 1
11 -> 1
12 -> 2
144 -> 4
200 -> 3
500 -> 3
1024 -> 10
3257832488 -> 3

05AB1E, 2 bytes

ÓZ

Try it online!

How?

Ó   exponents of prime factors
 Z  maximum


Convert integer to balanced dozenal Create a function which takes an integer and returns an array of integers representing the number in balanced base twelve. Specifically, the representation should follow these rules regarding 6 & -6 (from the above link):

  If the last digit of a number could be written with either 6 or ϑ, we use the one whose sign is opposite the sign of the first digit. For example, we write decimal 30 as dozenal 3ϑ, but decimal -30 as as dozenal ε6, not ζϑ.
  If a 6 or ϑ occurs before the last digit of a number, we use the one whose sign is opposite the next digit after it. For example, we write decimal 71 as dozenal 6τ, but decimal 73 as as dozenal 1ϑ1, not 61.
  If a 6 or ϑ is followed by a 0, we keep looking to the right until we can apply one of the first two rules. For example, we write decimal -72 as dozenal τ60, not ϑ0.

Otherwise, the only restrictions are to use only digits in [-6..6], and for the output, when interpreted as big-endian base twelve, to be equivalent to the input.

Example of use:

f(215) => [1,6,-1]
f(216) => [2,-6,0]
f(-82) => [-1,5,2]
f(0)   => [0]

Winner is the shortest, with upvotes being the tiebreaker.

J, 74 72 characters

Here's my J implementation (f =. not included in character count):

f =. **}.^:(*@#*0={.)@([:((12-~[),0>:@{.@]`[`]}])`,@.(6>[)/&.|.0,12&#.^:_1)@|

And some tests (each result is boxed, and underscore means negative):

   NB. Integers [-10..10]:
   (<@f"0)i:10
┌────┬────┬────┬────┬────┬──┬──┬──┬──┬──┬─┬─┬─┬─┬─┬─┬────┬────┬────┬────┬────┐
│_1 2│_1 3│_1 4│_1 5│_1 6│_5│_4│_3│_2│_1│0│1│2│3│4│5│1 _6│1 _5│1 _4│1 _3│1 _2│
└────┴────┴────┴────┴────┴──┴──┴──┴──┴──┴─┴─┴─┴─┴─┴─┴────┴────┴────┴────┴────┘
   NB. Some boundary values:
   (<@f"0)215 216 217 71 72 73
┌──────┬──────┬──────┬────┬──────┬──────┐
│1 6 _1│2 _6 0│2 _6 1│6 _1│1 _6 0│1 _6 1│
└──────┴──────┴──────┴────┴──────┴──────┘

Interestingly, the rules for 6 have no special place in the function. They work that way just by handling all digits >= 6 together and only working on positive numbers.

I made another version, which doesn't rely on #.^:_1, but it's longer:

**_2&([:}.^:(0={.)+/\)@(((<.@%&12,(1,-&12)`(0,])@.(6>])@(12&|))@{.,}.)^:(0~:{.)^:_)@(,&0)@|


Code Golf: Make a Web Crawler A Web Crawler is a program that starts with a small list of websites and gets the source code for all of them. It then finds all the links in those source codes, gets the website it links to then puts them in a list. It then starts again but with the new list of websites.The main reason for a Web Crawler is to find all (or most) of the websites in the internet. Google use this to power their search engine.Wikipedia Page about Web Crawlers

Your task is to create a Web Crawler in any language you wish.

Rules

  Your first list can contain any amount of websites <= 5 and any websites you wish.
  Your web crawler can ignore any websites with the HTTP GET request or any other pages other than the home page, e.g. www.somewebsite.com/?anything=1 and www.somewebsite.com/secondpage can be ignored, we are only trying to find the website/domain, e.g. www.somewebsite.com
  You can use any method you wish to store the list of websites currently being "crawled".
  Although this is code golf, the highest voted answer/solution will win, and don't forget to have fun!

Javascript, 491

Golfed

var C=function(c){w=c.length;for(i=0;i<w;i++){var b=new XMLHttpRequest;b.setRequestHeader("Access-Control-Allow-Origin","*");b.setRequestHeader("X-Requested-With","XMLHttpRequest");b.open("GET",c[i],!0);b.send();if(200===b.status){a=b.responseText.match(/\<[(a|img)]+\s[^\>]+[(http|https)]+:\/\/([\w\.])+([.])+.+?[^.]+?./gi);u=c[i].substr(7);re=RegExp(u,"i");for(j=0;j<a.length;j++)if(a[j].match(re)&&(b=a[j].match(/[(http|https)]+:\/\/([\w\.])+([.])/gi))&&!c.indexOf(b))c.push(a[j]),w++}}};

Un-Golfed

var C = function(s){
  w = s.length;
  for(i = 0; i < w; i++){
    var r = new XMLHttpRequest();
    r.setRequestHeader("Access-Control-Allow-Origin", "*")
    r.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    r.open('GET', s[i], true); r.send();
    if(r.status === 200) {
      a = r.responseText.match(/\<[(a|img)]+\s[^\>]+[(http|https)]+:\/\/([\w\.])+([.])+.+?[^.]+?./gi);
      u = s[i].substr(7),
      re = new RegExp(u,'i');
      for(j = 0; j < a.length; j++){
        if(!a[j].match(re)) continue;
        var uri = a[j].match(/[(http|https)]+:\/\/([\w\.])+([.])/gi);
        if(uri && !s.indexOf(uri)) {
          s.push(a[j]); w++;
        }
      }
    }
  }
}

Method

var c = new C(['http://www.cnn.com', 'http://www.usatoday.com', 'http://www.huffingtonpost.com', 'http://www.drudgereport.com/', 'http://news.cnet.com']);


Set the sum and product Given two positive reals \$a\$ and \$b\$, output some positive reals \$r_i\$, such that \$\sum r_i=a\$ and \$\prod\left(r_i+1\right)=b\$. You can assume that it's possible. You can also assume that your float type have infinite precision.
Test cases:
2,3 => 2
2,4 => 1,1 or 1/2,(sqrt(57)+9)/12,(9-sqrt(57))/12 or etc.
2,5 => 1/3,1/2,2/3,1/2 or etc.
2,8 => (undefined behavior)
2,2 => (undefined behavior)
e,2e => 1,e-1 or etc. (e is natural base, though any number>1 work)
3,e^3 => (undefined behavior) (It's possible to get as close as you want to e^3, but not reaching)

Shortest code wins.
Notes

Given the assumption with infinite precision, you can't solve arbitrary equation if your language doesn't have such functions(you can still use functions like Solve in Mathematica to solve such). In this case, some forms may have solution mathematically but you can't work it out, e.g. \$p,p,p,...,p,q\$ where \$p\$ and \$q\$ are reals. (At least software don't provide exact solution for x*x*x*y=5,3*x+y=7)

Haskell, 67 bytes

a#b|h<-a/2,c<-sqrt$(1+h)^2-b,c>0=h+c:[h-c|h>c]|l<-(a/2)#sqrt b=l++l

Try it online!
Based on this solution of Delfad0r, who also saved 1 byte off this
We first try to find a two-element solution with \$r_1+r_2=a\$ and \$(r_1+1)(r_2+1)=b\$, which we do by solving a quadratic equation. If we get real solutions, we're done. (If one solution is zero, we remove it and output a singleton.)
If this quadratic isn't solvable in the reals, we replace \$a \to a/2\$ and \$b \to \sqrt{b}\$ and solve from there. If we find a solution to this, then duplicating the list (that is, repeating each element a second time) gives a solution to the original problem, since this doubles the sum and squares the product of numbers-plus-one. We recursively make these substitutions until we simplify \$(a,b)\$ to ones that give a two-element solution.
We show that this process always reaches a solution. For the problem to be solvable, we must have \$b < e^a\$, which follows directly from \$\sum r_i=a\$ and \$\prod\left(r_i+1\right)=b\$ along with \$e^{r_i}>r_i+1\$. Since \$e^a\$ is the increasing limit of \$(1+a/N)^N\$ as \$N \to \infty\$, the bound \$b < e^a\$ implies that \$b < (1+a/N)^N\$, or equivalently that \$b^{1/N} < 1+a/N\$, for sufficiently large \$N\$. By choosing \$N=2^n\$ as a large power of \$2\$, doing \$n-1\$ steps of the substitution \$a \to a/2\$ and \$b \to \sqrt{b}\$ gives us \$a' = 2a/N\$ and \$b' = b^{2/N}\$, which we've shown satisfy \$\sqrt{b'} < 1 + a'/2\$.
This is exactly what we need to have real solutions for \$r_1+r_2=a\$ and \$(r_1+1)(r_2+1)=b\$, which gives a quadratic with discriminant \$(1+a/2)^2-b\$. It solutions are $$r  = a/2 \pm \sqrt{(1+a/2)^2-b}$$


Convert to Bubble Letters So I was playing around with my compose key, and found some cool things, one of them being that by pressing compose + ( + alphanumeric + ), you get that character inside a bubble, like so: ⓐ.

Your task in this challenge is simple, to convert ordinary text to bubble letter text.

Here are the ascii chars, the bubble characters and their Unicode code points:

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
⓪①②③④⑤⑥⑦⑧⑨ⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏ
9450 9312 9313 9314 9315 9316 9317 9318 9319 9320 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423

Your input will contain only printable ascii characters, and if a character cannot be bubbleified, leave it as is.

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

Note: This is not isomorphic to my earlier challenge about small-caps conversion since unlike small-caps, bubble letters are in a mostly contiguous segment of code-points, allowing for more interesting approaches.

Retina, 20 bytes

T`Lld`Ⓐ-⓪①-⑨

Try it online!

How it works

There's a gap between the code points of (0) and (1), but – fortunately – the character right after (z) is (0). This way, we can transliterate the character from concatenated ranges A-Za-z0-9 to the characters of the concatenated ranges (A)-(0)(1)-(9).

The rest is straightforward: T activates transliteration mode, Lld yields all uppercase ASCII letters (L), all lowercase ASCII letters (l) and all digits (d), and Ⓐ-⓪①-⑨ the corresponding bubble characters.


Eating Skittles Like a Normal Person Skittles are colored candy where there are 5 distinct flavors; grape, green apple, lemon, orange, and strawberry represented by (p)urple, (g)reen, (y)ellow, (o)range, and (r)ed respectively. I used to eat skittles by sorting all the different colors, then eating them in sequence. After getting a few weird looks in the office, I now pretend to eat them like a normal person. Your task is to emulate this:

Your code (full program or function) will receive an array of skittles (10x10) as input (in any reasonable format). This array will represent a pile of unsorted skittles. Your task is to "eat" them from your least favorite to favorite color. My preferred order is grape, green apple, lemon, orange, strawberry, but you are free to choose any order so long as it is consistently enforced (please list your preference in your submission so I can judge you for it). After eating each piece of candy your code will output (in the same format you take input) the remaining pile with the eaten piece replaced by a space. You will repeat until only your favorite remains. You may choose any skittle to eat (may be random or deterministic). Trailing spaces must be kept.

For example, your output sequence could look like this (using 5x5 for brevity and showing spaces as .)

start   1     2     3     4     5        n
.org. .org. .org. .org. .or.. .or..    ..r..
prgrg .rgrg .rgrg .rgrg .rgrg .r.rg    .r.r.
gggpr gggpr ggg.r ggg.r ggg.r ggg.r    ....r
oyyor oyyor oyyor oyyor oyyor oyyor    ....r
.r.p. .r.p. .r.p. .r... .r... .r...    .r...

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

TL;DR Rules:

Submission may be full program or function
Input may be taken in any reasonable format (string, list, matrix, etc) by any reasonable method (STDIN, function arguments, etc.). However there must be some delineation between rows
Output must be produced in the same format as input by any reasonable method (STDOUT, function return, ect.). Intermediate output may or may not be delimited
First output shall be the first input
Trailing spaces must be preserved
Any color order may be used (list in your answer)
Any skittle of the current color may be eaten
Last output shall be only your favorite color and spaces
If possible, include a link to an online compiler to test your submission

Jelly, 16 14  13 bytes

Ṅ⁶ỤṪ$¦µQL>3µ¿

TryItOnline!

Most to least favourite, as for anyone serious about their O.C.D., is alphabetical!

Takes input and outputs as text (i.e. the rows are delimited by new lines).

3 bytes saved by reversing the direction and using a different method: grade up rather than finding characters from the alphabet.

How?

Ṅ⁶ỤṪ$¦µQL>3µ¿ - Main link: Skittle text
      µ    µ  - monadic chain separation
            ¿ - while
       Q      - unique items
        L     - length
         >3   - greater than 3 (until only new lines, spaces and 'g's remain)
Ṅ             -     print z and a line feed, yield z
    $         -     treat last two links as a monad
  Ụ           -         grade up (get indices of: new lines; spaces; gs; os; ps; rs; ys)
   Ṫ          -         tail (the last of those, so last y if there is one, else last r, ...)
 ⁶            -     space character
     ¦        -     apply at index (replace that index with a space)


Draw a descendant pyramid (addition) Challenge

Given a sequence of non-negative integers, create a function that output a descendant pyramid where the children are the sum of both parent numbers.

The result is outputted as an string using tab \t.

Note: trailing tabs on each line are not required

1\t\t2\t\t3\n\t3\t\t5\t\n\t\t8\t\t results in
1       2       3
    3       5
        8

Optionally result can be outputted as an array using an empty position as space.

[[1,,2,,3],
[,3,,5,],
[,,8,,]]

Example:

Given 4,5,7,3,4,2 Output:

4       5       7       3       4       2
    9       12      10      7       6
        21      22      17      13
            43      39      30
                82      69
                    151

Rules

Standard code-golf rules apply
Input can be a string using any separator or an array
Leading/trailing newlines and tabs are permitted (but not required as long as the output is an inverted pyramid)

Test Cases

Input: 1,3,5

1       3       5
    4       8
        12

Input: 9,8,7,6,5

9       8       7       6       5
    17      15      13      11
        32      28      24
            60      52
                112

Input: 5,5,2,5

[[5,,5,,2,,5],
[,10,,7,,7,],
[,,17,,14,,],
[,,,31,,,]]

Input: 3,3,3

[[3,,3,,3],
[,6,,6,],
[,,12,,]]

Winning criteria is code-golf

Note: This challenge is very close to Generate Pascal's triangle. The difference is the custom starting sequence (pascal goes from 1 and in ascendant mode, this from an input and in descendant mode).

Sandbox post

Jelly,  14  13 bytes

14 -> 13 assumes trailing spaces-only entry is allowed in the list format output; if not I shall revert to the 14 (asked)

+ƝƬK€z⁶Zṙ"JC$

A monadic link. Output is a list of lists using space characters as the spaces (includes a single trailing spaces-only entry).

Try it online! (includes a footer to show the list structure since running the monadic link as a full program will print smashed output implicitly.)