Equilibrium index of a sequence Equilibrium index of a sequence is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. For example, in a sequence A:

A[0]=-7 A[1]=1 A[2]=5 A[3]=2 A[4]=-4 A[5]=3 A[6]=0

3 is an equilibrium index, because:

A[0]+A[1]+A[2]=A[4]+A[5]+A[6]

6 is also an equilibrium index, because:

A[0]+A[1]+A[2]+A[3]+A[4]+A[5]=0

(sum of zero elements is zero) 7 is not an equilibrium index, because it is not a valid index of sequence A.

The idea is to create a program that given a sequence (array), returns its equilibrium index (any) or -1 if no equilibrium indexes exist.

Golfscript 17 16

Since the form of the input isn't specified, this takes a string in Golfscript array format from stdin.

~0\{1$+.@+\}/])?

So run as e.g.

golfscript.ry eqindex.gs <<<"[-7 1 5 2 -4 3 0]"

The idea is very simple: it takes an array of A_i and maps to an array of A_i + 2 SUM_{j<i} A_j and then looks for the first index which is equal to the sum of the whole array.

For @mellamokb's challenge I offer:

~0\{1$+.@+\}/:S;]:A,,{A=S=},`

for 29 chars.


Is this skew symmetry? In this challenge, your task is to detect (vertical) Skewer Symmetry. This means that one half of the pattern can be produced by mirroring the other half along a vertical axis, and then moving it vertically.

For example, the following pattern has skewer symmetry:

asdf
jkl;fdsa
    ;lkj

Because if you start from the left half...

asdf
jkl;

...then mirror it along a vertical axis...

    fdsa
    ;lkj

...then move it down by a character (filling the empty rows with spaces)...

    fdsa
    ;lkj

...you get the second half.

Rules:

You may assume the input is rectangle and has an even number of columns.
If the pattern itself exhibits reflection symmetry, it is considered skewer symmetry.
This is strict character by character symmetry, so [[ is considered symmetrical, but not [].
You should output truthy if the input has skewer symmetry, falsy otherwise.
Default I/O rules apply, standard loopholes are banned.

Test Cases

Truthy cases:

asdf
jkl;fdsa
    ;lkj

asdffdsa

[

 [

  ba
abdc
cd

Falsy cases:

[
 ]

ab
ba

aa
a
 a

a  a
b b

ab
  b
   a

APL (Dyalog Unicode), 44 34 bytesSBCS

crossed out 44 is still regular 44 ;(

Hats off to @Bubbler, @ngn and @TesselatingHeckler as they managed to shave some bytes off of my solution, more or less independently but coming up with the same simplifications.

{1∊(l↓⍵)⍷⍨a/⍨∨⌿' '≠a←⊖⍵↑⍨l←2÷⍨≢⍵}⍉

Try it online!

Now I'll explain how it works:

{                                   }⍉  ⍝ We define a monadic function that we apply right after transposing (⍉) the input [this means we will be operating on columns instead of rows]
                              2÷⍨≢⍵    ⍝ Start by finding how many  columns the input has (≢),split that in half (2÷⍨)
                            l←          ⍝   and assign that to l (l←) ...
                        ⍵↑⍨            ⍝ Using it right away to take (↑⍨) l columns from the original input ⍵
                       ⊖               ⍝   which we then reverse (⊖) [effectively flipping the columns upside down]
                     a←                 ⍝   and assign to a (a←)
                 ' '≠                   ⍝ We then compare each character in a to ' '
               ∨⌿                       ⍝   and we "interleave" the logical OR (∨) over the columns (⌿) [to find columns where at least one character is different from ' ']
           a/⍨                          ⍝   finally selecting those columns from a (a/⍨)
         ⍷⍨                             ⍝ Now we superimpose that piece of the original character matrix over all possible locations
   (l↓⍵)                               ⍝   of the columns of ⍵ that remain after we drop (↓) the first l columns [i.e. we take the second half of the columns]
 1∊                                    ⍝   and we look for matches by checking if there is a 1 (Truthy) in any position (∊)


Add TIO link to messages! It's annoying when you have to search for a language homepage, get its link, and add it to your SE comment/answer, right? Let's write a script to do that for you!

Challenge

For each language name (intentional or not) in the input, replace it with the markdown link to the language home page, defined by TIO.

Rules

(important) You can only connect to https://tio.run.
Use the language list on TIO at the time your program is run.
The input is a string. Assume no newline (because multiline messages can't have markdown anyway). Unicode characters may be inside the string because they can exist in chat messages (example).
The input is valid markdown, but it is unlikely that this is related to the challenge.
You can assume there is no link inside the input. (Whoops, I missed this when the challenge was in the sandbox, thanks mercator for pointing that out. As far as I can see this should not invalidate any existing answers)
Case sensitive or insensitive, whatever you choose.
Only word breaks (not both adjacent to an English letter) are considered. (for example, matlab should not be converted to matlab, 47 should be converted to 47)

  Note: It's too hard to define what's a "character" in Unicode, so your program can detect a word break or not if one of the two surrounding characters are not printable ASCII.

Only use markdown [...](...), not HTML link ... because the latter doesn't work in chat.
Markdown components (* / _ for italic, ** for bold, --- for strikethrough (in chat)) in messages should not matter, because AFAIK there are no languages with such names on TIO.
Use the language name (Wolfram Language (Mathematica)), not language ID.
No overlapping replacement.
In case there are multiple output, pick whichever. See example below.
Although by default chat markdown doesn't allow links in code blocks, for simplicity I would just assume that they don't need to be treated specially.

Winning criteria

code-golf.

Test cases

Input -> Output
matlab -> matlab
47 -> [4](https://github.com/urielieli/py-four)[7](https://esolangs.org/wiki/7)
/// -> [///](https://esolangs.org/wiki////)
//// -> [///](https://esolangs.org/wiki////)/ or /[///](https://esolangs.org/wiki////)
////// -> [///](https://esolangs.org/wiki////)[///](https://esolangs.org/wiki////) or //[///](https://esolangs.org/wiki////)/
Uṅıċȯḋė -> Uṅıċȯḋė

More test cases

(suggested by Adám. Any replacement is fine as long as they don't overlap (valid markdown source))

\///
S.I.L.O.S.I.L.O.S
Del|m|t
Del|m|tcl

Javascript (ES6) + jQuery, 247 bytes

s=>c=>$.getJSON('https://tio.run/static/645a9fe4c61fc9b426252b2299b11744-languages.json',data=>{for(l of Object.values(data))s=s.replace(eval(`/([^a-zA-Z]|^)${l.name.replace(/[\\/+.|()]/g,"\\$&")}(?![a-zA-Z])/g`),`$1[${l.name}](${l.link})`);c(s)})

Explanation (less golfed)

s=>c=>
// Load TIO languages using jQuery
$.getJSON('https://tio.run/static/645a9fe4c61fc9b426252b2299b11744-languages.json',data=>{
  // For every language
  for(l of Object.values(data)) {
    // Construct a regex that matches the language name
    var regex = eval(`/([^a-zA-Z]|^)${l.name.replace(/[\\/+.|()]/g,"\\$&")}(?![a-zA-Z])/g`
    // Replace all occurences of the language name with the language name and link
    s=s.replace(regex),`$1[${l.name}](${l.link})`)
  }
  // Return using callback
  c(s);
});

f=
s=>c=>$.getJSON('https://tio.run/static/645a9fe4c61fc9b426252b2299b11744-languages.json',data=>{for(l of Object.values(data))s=s.replace(eval(`/([^a-zA-Z]|^)${l.name.replace(/[\\/+.|()]/g,"\\$&")}(?![a-zA-Z])/g`),`$1[${l.name}](${l.link})`);c(s)})

f("47")(console.log);
f("///")(console.log);
f("////")(console.log);
f("//////")(console.log);
f("Uṅıċȯḋė")(console.log);
f("\///")(console.log);
f("S.I.L.O.S.I.L.O.S")(console.log);
f("Del|m|t")(console.log);
f("Del|m|tcl")(console.log);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


JSON tips: filter objects from array of objects where object name is alpha What could be the shortest code for filtering the following array in Javascript without any library?

My code is:

filtered_obj = _.where(obj, { name: "Alpha" });

This uses a JS library called underscore.

Test case:

objs = [{'id':1,'name':'Alpha'},{'id':2,'name':'Beta'},
{'id':3,'name':'Gamma'},{'id':4,'name':'Eta'},
{'id':5,'name':'Alpha'},{'id':6,'name':'Zeta'},
{'id':7,'name':'Beta'},{'id':8,'name':'Theta'},
{'id':9,'name':'Alpha'},{'id':10,'name':'Alpha'}];

filtered_obj =[{'id':1,'name':'Alpha'},{'id':5,'name':'Alpha'},
{'id':9,'name':'Alpha'},{'id':10,'name':'Alpha'}]

45 bytes

filtered_obj=objs.filter(n=>n.name=='Alpha');

This uses the filter function for arrays.

Ideone it!


Can I string all my cords and adapters together? Suppose one day you are digging through your big box of unused computer cords and adapters (USB to USB mini, VGA to DVI, etc.). There are tangled cords everywhere making quite a mess, and you wonder if you could simplify things by attaching all the cords together in one long strand, and then just rolling it up.
The question is, is it possible to connect all of your cords and adapters in one long line like this? It's obviously not always possible, e.g. if you only had two cords with completely different plugs, they could not be connected together. But if you had a third cord that can connect to both of them, then you could string all your cords together.
You don't care about what type of plugs are on the ends of the all-cord strand. They don't need to plug into one another to form a loop. You only want to know if making the all-cord strand is possible, and if it is, how to do it.
Challenge
Write a program or function that takes in a multiline string where every line depicts one of the cords you own. A cord is made up of one or more dashes (-), with a plug on either end. A plug is always one of the 8 characters ()[]{}<>.
So these are some valid cords:
>->
(--[
}-{
<-----]
(---)

But these are not:
-->
(--
)--
[{
---

When connecting cords, only plugs with the exact same bracket type can be connected together.
So these are some valid cord connections:
...---((---...
...---))---...
...---]]---...
...---{{---...
...---<<---...

And these are invalid:
...---()---...
...---)(---...
...---{]---...
...---{[---...
...---><---...
...--->)---...

If all the cords in the input can be rearranged and attached together in one long strand, then output that strand to stdout on one line (with an optional trailing newline). When there are multiple solutions you can choose any one of them to output. If making a single strand is not possible, then output nothing (or output an empty string with an optional trailing newline).

For example, if the input is
[-->
{---]
>----{

the output could be
[-->>----{{---]

where all the cords are strung together.
However if the input were
[-->
{---]

the cords cannot be connected so there would be no output.

Note that cords can be flipped around as much necessary to make connections. e.g. [--> and <--] are effectively the same cord because they can make the same type of connections. Some outputs may depend on flipping the input cords.

For example
(-[
}--]

could have output
(-[[--{

where the second cord is flipped, or
}--]]-)

where the first cord is flipped.
(Note that in general flipping the entire output is valid because it's the same as initially flipping every cord individually.)

The lengths of the cords in the output should of course match the lengths of the corresponding input cords. But the cords may be reordered and flipped  around as much as you want in order to make the all-cord strand. The input will always contain at least one cord.
The shortest code in bytes wins.
Test Cases
Cases with output:
[-->
{---]
>----{
gives
[-->>----{{---]
or
[---}}----<<--]

(-[
}--]
gives
(-[[--{
or
}--]]-)

(-)
gives
(-)

[--{
gives
[--{
or
}--]

[-]
]-[
gives
[-]]-[
or
]-[[-]

[----->
)------------[
{--<
}---)
could give
[----->>--}}---))------------[
or
>--}}---))------------[[----->
or
}---))------------[[----->>--}
or
{--<<-----]]------------((---{
etc.

>-->
>->
>--->
could give
>-->>->>--->
or
>--->>-->>->
or
>->>-->>--->
or
<--<<---<<-<
etc.

(-]
]->
>-}
}-)
)-[
[-<
<-{
{-(
could give
(-]]->>-}}-))-[[-<<-{{-(
or
{-((-]]->>-}}-))-[[-<<-{
or
<-{{-((-]]->>-}}-))-[[->
etc.

Cases without output:
[-->
{---]

[-]
[-]

(-]
]->
}-)

>->
>-->
]---]

[-------------------]
]-------------------[
[-----------------]
[-----------------]

{--[
]--}


Curiosity killed the cat? Some people say curiosity killed the cat. Other say it was the box and poison. The RSPCA say Erwin Schrödinger needs to lose the right to own pets.

With animal rights activists outside his house. The cat murderer scientist Schrödinger has finally come up with his greatest invention. A special, radioactive mix of unobtanium and handwavium that can have any half life, and a single gram of the product is capable of killing any living creature. Unfortunately, when he tried to test it on his final cat: Bob, he forgot that cats have 9 lives, and so would need 9 grams to kill. With some water but no food, poor Bob will live exactly 1 week (7 days) if the product doesn't kill him first.

The task:
Given an input of a mass in milligrams and a half-life in milliseconds -  both integers which can exceed 2^31, write a program that outputs whether or not the mystery super product kills the cat, or if it's 1 week time limit expires first. Assume true/yes/1/anything specified in the answer is for when he does not die from starvation.

For the product to kill him, a total of 9 grams must decay. So out of a sample of 18 grams, 1 half-life must pass. If the sample contains less than or equal to 9 grams, this will never be achieved, and so it can be immediately assumed 1 week will pass before 9 grams decays.

You may assume:

Bob dies the microsecond 9 grams has decayed.
The change is mass due to decay does not matter.
All days and times follow generally accepted earth time.
The box Bob is sealed in is unbreakable and unopenable, so there is no chance of death from other causes.
Oxygen is also no issue.
If both happen at the exact same time either output is acceptable.
All inputs should be below 2^63-1

Test cases:

Example:

18000 604800001

For 9 grams to decay, exactly 1 half life must pass (18000/2 = 9000 milligrams or 9 grams). 1 half life is 604800001 milliseconds, or 168 hours and 1 millisecond, or exactly 1 week and 1 millisecond. Since Bob dies of hunger at exactly 1 week, the output is false as he died from hunger just before the 9 gram product limit was reached

8000 40000 false

70000 800 true

18000 604800000 either

18000 604800001 false

18000 604799999 true

1 1 false

100000 1 true

1000000000 1000000000 true

Scoring:
Naturally we want Bob's suffering to end quickly, and so a shorter half-life is best. Half-life and byte both end in E, so clearly the shortest byte count wins.

Python 3, 33 bytes

lambda a,b:a-a*.5**(6048e5/b)>9e3

Explanation:

         6048e5         # number of milliseconds in 1 week
               /b       # half-lifes per week
  a*.5**(        )      # mgs of substance remaining after 1 week
a-                      # mgs of substance decayed after one week
                  >9e3  # return true if more than 9000mgs has decayed in 1 week

Try here


Count the trailing zeros Given two positive integers \$n\$ and \$b\$, such that \$n > 2\$ and \$n > b > 1\$, count the trailing zeros when converting \$n\$ to base \$b\$. Your program should be able to handle any value of \$b\$ within your integer maximum.
The digits of \$n =  18\$, \$b =  3\$ are \$[2,0,0]\$, so the correct output is \$2\$.
The digits of \$n = 107\$, \$b = 43\$ are \$[2, 42]\$, so the correct output is \$0\$
This is code-golf, so the shortest code in bytes wins
Test cases
  n   b  out
512   2   9
248   2   3
364 265   0
764   2   2
336 284   0
517 422   0
554  37   0
972   3   5
 12   6   1
 72   2   3
 44   2   2
 51  16   0
 32   2   5
 56   7   1
 60   2   2
  8   3   0
 18   3   2
107  43   0

Credit to Anush for the inspiration
There is a one byte answer in Jelly. Can you find it?

Vyxal, 1 byte
Ǒ

Try it Online!
laughs in stolen jelly built-ins


Generate Pascal's Braid This is Pascal's Braid:

 1 4  15  56   209   780    2911    10864     40545      151316      564719
1 3 11  41  153   571   2131    7953     29681     110771      413403      1542841
 1 4  15  56   209   780    2911    10864     40545      151316      564719

I totally made that up. Blaise Pascal didn't have a braid as far as I can tell, and if he did it was probably made of hair instead of numbers.

It's defined like this:

The first column has a single 1 in the middle.
The second column has a 1 at the top and at the bottom.
Now we alternate between putting a number in the middle or two copies of a number at the top and bottom.
If the number goes on the top or the bottom, it will be the sum of the two adjacent numbers (e.g. 56 = 15 + 41). If you tilt your head a little, this is like a step in Pascal's triangle.
If the number goes in the middle, it will be the sum of all three adjacent numbers (e.g. 41 = 15 + 11 + 15).

Your task will be to print (some part of) this braid.

Input

You should write a program or function, which receives a single integer n, giving the index of the last column to be output.

You may choose whether the first column (printing only a single 1 on the middle line) corresponds to n = 0 or n = 1. This has to be a consistent choice across all possible inputs.

Output

Output Pascal's Braid up to the nth column. The whitespace has to match exactly the example layout above, except that you may pad the shorter line(s) to the length of the longer line(s) with spaces and you may optionally output a single trailing linefeed.

In other words, every column should be exactly as wide as the number (or pair of equal numbers) in that column, numbers in successive columns should not overlap and there should be no spaces between columns.

You may either print the result to STDOUT (or the closest alternative), or if you write a function you may return either a string with the same contents or a list of three strings (one for each line).

Further Details

You may assume that n won't be less than the index of the first column (so not less than 0 or 1 depending on your indexing). You may also assume that the last number in the braid is less than 256 or the largest number representable by your language's native integer type, whichever is greater. So if your native integer type can only store bytes, you can assume that the largest n is 9 or 10 (depending on whether you use 0- or 1-based n) and if it can store signed 32-bit integers, n will be at most 33 or 34.

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

OEIS

Here are a few relevant OEIS links. Of course, these contain spoilers for different ways to generate the numbers in the braid:

Top/bottom: A001353 or A010905 or A106707 or A195503
Middle: A001835 or A079935
Both: A002530

Test Cases

These test cases use 1-base indexing. Each test case is four lines, with the first being the input and the remaining three being the output.

1

1

---
2
 1
1
 1
---
3
 1
1 3
 1
---
5
 1 4
1 3 11
 1 4
---
10
 1 4  15  56   209
1 3 11  41  153
 1 4  15  56   209
---
15
 1 4  15  56   209   780    2911
1 3 11  41  153   571   2131    7953
 1 4  15  56   209   780    2911
---
24
 1 4  15  56   209   780    2911    10864     40545      151316      564719       2107560
1 3 11  41  153   571   2131    7953     29681     110771      413403      1542841
 1 4  15  56   209   780    2911    10864     40545      151316      564719       2107560

Pyth, 44 bytes

The number generation took 20 bytes, and the formatting took 24 bytes.

jsMC+Led.e.<bkC,J<s.u+B+hNyeNeNQ,1 1Qm*;l`dJ

Try it online!

jsMC+Led.e.<bkC,J<s.u+B+hNyeNeNQ,1 1Qm*;l`dJ   input as Q
                   .u          Q,1 1           repeat Q times, starting with [1,1],
                                               collecting all intermediate results,
                                               current value as N:
                                               (this will generate
                                                more than enough terms)
                       +hNyeN                  temp <- N[0] + 2*N[-1]
                     +B      eN                temp <- [temp+N[-1], temp]

now, we would have generated [[1, 1], [3, 4], [11, 15], [41, 56], ...]

jsMC+Led.e.<bkC,J<s                 Qm*;l`dJ
                  s                            flatten
                 <                  Q          first Q items
                J                              store in J
                                     m    dJ   for each item in J:
                                         `     convert to string
                                        l      length
                                      *;       repeat " " that many times

jsMC+Led.e.<bkC,
              C,     transpose, yielding:
[[1, ' '], [1, ' '], [3, ' '], [4, ' '], [11, '  '], ...]
(each element with as many spaces as its length.)
        .e            for each sub-array (index as k, sub-array as b):
          .<bk            rotate b as many times as k

[[1, ' '], [' ', 1], [3, ' '], [' ', 4], [11, '  '], ...]

jsMC+Led
    +Led              add to each sub-array on the left, the end of each sub-array
   C                  transpose
 sM                   sum of each sub-array (reduced concatenation)
j                     join by new-lines


Write a function/method that takes in a string and spells that word out using the NATO Phonetic Alphabet. Titlecase optional Write a program that takes in a string and spells that word out using the NATO Phonetic Alphabet.

The mapping is as follows:

'A' -> 'Alfa'
'B' -> 'Bravo'
'C' -> 'Charlie'
'D' -> 'Delta'
'E' -> 'Echo'
'F' -> 'Foxtrot'
'G' -> 'Golf'
'H' -> 'Hotel'
'I' -> 'India'
'J' -> 'Juliett'
'K' -> 'Kilo'
'L' -> 'Lima'
'M' -> 'Mike'
'N' -> 'November'
'O' -> 'Oscar'
'P' -> 'Papa'
'Q' -> 'Quebec'
'R' -> 'Romeo'
'S' -> 'Sierra'
'T' -> 'Tango'
'U' -> 'Uniform'
'V' -> 'Victor'
'W' -> 'Whiskey'
'X' -> 'Xray'
'Y' -> 'Yankee'
'Z' -> 'Zulu'

Example:

'Hello World' -> ['Hotel', 'Echo', 'Lima', 'Lima', 'Oscar', 'Whiskey', 'Oscar', 'Romeo', 'Lima', 'Delta']

The input can be any string, but will always be comprised of only letters and spaces. Case is irrelevant in the output, but the input may contain letters in uppercase, lowercase, or both. Spaces should be ignored in the output.

You can output in any reasonable format, but it must be a delimited set of NATO callsigns.

sfk, 78 59 57 bytes

+filt
+spell -nato
+xed _ph_f_ _et_ett_ _-__ "*: [keep]""

Try it online!

Just use the right tool.

Output is the phonetics separated by one or more spaces.


Tips for golfing in TeX/LaTeX What tips do people have for golfing in TeX/LaTeX? Please post one tip per answer, each at least somewhat specific to TeX/LaTeX.

Context: I noticed this answer and that there is no tips question for TeX/LaTeX, so I'm creating this one. There's some overlap with the narrower question tips for golfing in TikZ (as TikZ is a specific macro package on top of TeX/LaTeX): answers to this question will probably also apply there, but not the other way around.

Consider internal LaTeX macros rather than the documented ones

For example, \roman is a documented LaTeX macro that works on LaTeX counters. To turn 42 into XLIV you'd have to use something like

\newcounter{z}
\setcounter{z}{42}
\roman{z}

Instead, by looking up how \roman is implemented (use \show\roman to get this interactively, instead of reading the source files), one can see that it's implemented in terms of a useful macro called \@roman, and instead use that directly:

\catcode`@11
\@roman{42}

\catcode`@11 is the golfy way of writing \makeatletter (clean way in LaTeX) or \catcode`\@=11 (clean way in plain TeX). It's needed only once at the beginning, after this you can use macro names containing @.


Generate all solvable 2xN mazes Your job is to write a program that takes a number N as input and outputs all 2-by-N mazes that are solvable.
Output format can be in the form of any two distinct values representing wall and empty - I use x and . here but you can use anything. You can have a matrix, array, string, ascii art, whatever is convenient, and it can be horizontal, as shown in my examples, or vertical.
A maze is solvable if it has a path of empty cells (represented here as .) from the left end to the right end. For example,
xxxx.....
.....x..x

is solvable, because you can trace a path (marked with O):
xxxxOOOOO
OOOOOx..x

But this is not.
xxx.x..
..xxx..

You cannot pass through diagonal gaps, so this is also not:
xxx...
...xxx

Testcases
1:

.
.

.
x

x
.

2:

..
..

..
.x

.x
..

..
x.

..
xx

x.
..

xx
..

Excel, 163 143 bytes
=LET(a,BASE(SEQUENCE(3^A1)-1,3,A1),b,FILTER(a,ISERROR(FIND(12,a))*ISERROR(FIND(21,a))),SUBSTITUTE(b,2,0)&"
"&SUBSTITUTE(SUBSTITUTE(b,1,0),2,1))

Use 1 for walls and 0 for empty cells.
Original
=LET(a,BASE(SEQUENCE(3^A1)-1,3,A1),b,FILTER(a,ISERROR(FIND(12,a))*ISERROR(FIND(21,a))),SUBSTITUTE(SUBSTITUTE(b,1,"X"),2,0)&"
"&SUBSTITUTE(SUBSTITUTE(b,2,"X"),1,0))

Uses 0 for empty cells and X for walls.
Link to Spreadsheet


Robbers: Crack the regex - Make a snake This is the robber's thread. The cop's thread is here.

A snake matrix is a square matrix that follows this pattern:

3-by-3:

1  2  3
6  5  4
7  8  9

and 4-by-4:

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

Your task is to write a code that takes an input n and creates such a matrix, in the same language as a cop post, and with a code that matches the cop's regex. The output format of your code must match the output format of the cop's code.

Please leave a comment under the Cop's post to indicate that you have cracked it.

Winning criterion:

The winner will be the user that has cracked the most submissions. In case of a tie, then there will be multiple winners.

Jelly, 9 bytes, cracks @Dennis' answer

²sµUFḤ$¦G

Try it online!

Should be correct now; I had to rather rethink what I was doing.

Explanation

The hardest part of this problem is getting a list of the even indices inside the ¦ (which applies an operation at specific indices). Unlike most operations, which use the input to the whole program as a default for the second operand, ¦ uses the most recently seen value as a default (because it conceptually has two left operands, rather than a left and a right operand like most things that take in two values).

However, we can observe that we have a list of numbers, including all integers from 1 to half the input, already in the current value at the time. As such, flattening and doubling it gives us a list of even numbers, including all the even indices (also some other even numbers but we don't care about those). It's even possible to spend one µ solely to avoid a parsing ambiguity and still come in within 9 characters.

²sµUFḤ$¦G
 s         Split
²          {the list of numbers from 1 to} the square of {the input}
  µ        into a number of pieces equal to {the input};
   U       then reverse
       ¦   the elements at indexes
    F      obtained by flattening the split list
      $    and
     Ḥ     doubling each element in the flattened list;
        G  finally, format it into a grid.


JavaScript (ES6), 123 bytes
Returns the order as a space-separated string.

f=n=>n?(x=n>128|n==125?125:n>50?n<54?25:n-70?302256705>>n-80&n>79&n<109?80:50:n:n-24&&n-49?n<31|n%5<1?n:25:9)+' '+f(n-x):''

Try it online!
How?
Given a number \$n\$ of wings, we recursively apply the following strategy.
High values: \$n>128\$ or \$n=125\$
For high values, our best option is to buy \$125\$ wings. So that's what we're doing as long as \$n\$ is greater than or equal to \$129\$ or when \$n\$ is exactly equal to \$125\$.
We can't do that for \$125 < n < 129\$ because we'd be left with less than \$4\$ wings to buy, which is not possible.
Low values: \$n<31\$
For \$n<31\$, the best deal is to buy all remaining wings at once, except for \$n=24\$ which must be purchased as either \$2\times 12\$, \$18+6\$ or \$15+9\$. We arbitrarily buy \$9\$ wings in that case.
Range \$31 \le n \le 50\$
In this range, buying \$25\$ wings usually leads to an optimal order. But the following exceptions apply:

If \$n\$ is a multiple of \$5\$, we must buy all remaining wings at once.
If \$n=49\$, the best deals are \$40+9\$ and \$28+21\$. We arbitrarily buy \$9\$ wings in that case.

Range \$51 \le n \le 53\$
We can't buy \$50\$ wings in that range or we'll be left with less than \$4\$ wings. Our best option is to buy \$25\$ of them instead. (We could buy \$2\times26\$ wings for \$n=52\$, but buying \$25+27\$ is just as good.)
Range \$54 \le n \le 128\$ with \$n \neq 125\$
In this range, buying \$50\$ wings usually leads to an optimal order. But the following exceptions apply:

If \$n=70\$, we must buy all of them at once.

If \$n\$ is in \$\{80,86,89,92,98,105,108\}\$, we must buy \$80\$ wings. These values are encoded with the following bitmask, where the least significant bit is mapped to \$80\$ and the most significant one to \$108\$:
$$10010000001000001001001000001_{(2)} = 302256705_{(10)}$$


Determine number of connected components You are given a graph represented through an adjacency list. For example, the input

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

would correspond to the graph with nodes 1, 2, 3 and 4, where 1 is connected to 2, 2 is connected to 3, 3 is connected to 4, and 4 is connected to 1 (forming a square).

The task is to determine the number of of connected components of the graph represented by an inputted adjacency list. A "connected component" is a set of nodes from which there is no path to any other node that is not in the set.

Example:

  Intput: 1-2 2-3 4-5
  Output: 2

Language of your choice - shortest code possible.

Ruby, 77 characters
gets;0while$_.sub!(/\b(\d+)\b(.*) (\1-\d+|\d+-\1)\b/,'\3\2');p$_.count(" ")+1

A first plain attempt in Ruby. It collects the sub-graphs using a regular expression until no more connections can be made.
Examples:
> 1-2 2-3 3-4 4-1
1

> 1-2 2-3 4-5
2

> 1-2 3-4 8-9 1-6 5-7 7-4 10-9
3


Make a long type signature Challenge
Find an expression, at most 100 bytes long, with the longest type signature.
Rules

Any statically typed language with type inference is allowed
The type must be non-ambiguous, but otherwise may include types without defined instances. For example Num [a] and Eq [a] are allowed, even without a defined instance
No imports other than the minimum required to compile a program with STDIN/STDOUT
Infinite types are not allowed
If an answer has more than one expression, only one may contribute to the score. For example, although the type signature of composition is (.) :: (b -> c) -> (a -> b) -> a -> c, having a score of 20, the answer with 25 copies of (.)\n would have a score of 20, not 500
The expression must be, at most, 100 bytes
The score is the number of characters in the type signature, excluding the name of the function and any whitespace. For example, f :: (a -> b) -> a -> b would have a score of 12
The highest score wins!

Examples
Although other languages are allowed, the following examples are in Haskell:
Score: 112
map.map.map.map.map.map.map.map.map.map.map.map.map.map.map.map.map.map.map.map.map.map.map.map.map
f :: (a -> b)
 -> [[[[[[[[[[[[[[[[[[[[[[[[[a]]]]]]]]]]]]]]]]]]]]]]]]]
 -> [[[[[[[[[[[[[[[[[[[[[[[[[b]]]]]]]]]]]]]]]]]]]]]]]]]

Score: 240
(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.)
f :: (b->c)->(a->a1->a2->a3->a4->a5->a6->a7->a8->a9->a10->a11->a12->a13->a14->a15->a16->a17->a18->a19->a20->a21->a22->a23->a24->b)->a1->a2->a3->a4->a5->a6->a7->a8->a9->a10->a11->a12->a13->a14->a15->a16->a17->a18->a19->a20->a21->a22->a23->a24->c

Score: 313
foldl$foldl$foldl$foldl$foldl$foldl$foldl$foldl$foldl$foldl$foldl$foldl$foldl$foldl$foldl$foldl(.)
f :: (Foldable t, Foldable t1, Foldable t2, Foldable t3, Foldable t4,
  Foldable t5, Foldable t6, Foldable t7, Foldable t8, Foldable t9,
  Foldable t10, Foldable t11, Foldable t12, Foldable t13,
  Foldable t14, Foldable t15) =>
 (b -> c)
 -> t (t1 (t2 (t3 (t4 (t5 (t6 (t7 (t8 (t9 (t10 (t11 (t12 (t13 (t14 (t15 (b
 -> b))))))))))))))))
 -> b
 -> c

Score: 538
lex.show.foldl1.mapM.traverse.sum.mapM.sum.traverse.(.).mapM.scanl.zipWith3((.traverse).(.traverse))
 (Num
    (a -> ([[c]] -> t3 [[a1 -> f b]]) -> [[c]] -> t3 [[a1 -> f b]]),
  Num
    (([[c]] -> t3 [[a1 -> f b]])
     -> t1 (t2 ([[c]] -> t3 [[a1 -> f b]]))
     -> [[c]]
     -> t3 [[a1 -> f b]]),
  Show
    (t (t1 (t2 ([[c]] -> t3 [[a1 -> f b]])))
     -> t1 (t2 ([[c]] -> t3 [[a1 -> f b]]))),
  Applicative f, Foldable t,
  Foldable ((->) (t1 (t2 ([[c]] -> t3 [[a1 -> f b]])) -> a)),
  Foldable
    ((->) (([[c]] -> t3 [[a1 -> f b]]) -> a -> t3 [a1 -> f b])),
  Traversable t1, Traversable t2, Traversable t3, Traversable t4,
  Traversable t5,
  Traversable ((->) (t1 (t2 ([[c]] -> t3 [[a1 -> f b]])))),
  Traversable ((->) ([[c]] -> t3 [[a1 -> f b]]))) =>
 [(t5 (t4 a1) -> f (t5 (t4 b))) -> c -> a1 -> f b]
 -> [(String, String)]

Haskell, ~2^(2^18)
f x=(x,x)
g=f.f.f.f
h=g.g.g.g
i=h.h.h.h
j=i.i.i.i
k=j.j.j.j
l=k.k.k.k
m=l.l.l.l
n=m.m.m.m
n.n.n.n$0

Each application of f roughly double the type signature by transforming the type signature T to (T,T). For example, the fourfold composition f.f.f.f$0 has type
Num a => ((((a, a), (a, a)), ((a, a), (a, a))), (((a, a), (a, a)), ((a, a), (a, a))))

Each line quadraples the number of applications of f, giving 4^9 = 2^18 at the end. So, the type signature has size of the order of 2^(2^18).


Euler-Poincaré-Characteristic of Polyhedra Given a triangulation of the surface of a polyhedron p, calculate its Euler-Poincaré-Characteristic χ(p) = V-E+F, where V is the number of vertices, E the number of edges and F the number of faces.

Details

The vertices are enumerated as 1,2,...,V. The triangulation is given as a list, where each entry is a list of the vertices of one face, given in clockwise or counterclockwise order.

Despite the name, the triangulation can also contain faces with more than 3 sides. The faces can assumed to be simply connected that means that the boundary of each faces can be drawn using one closed non-self-intersecting loop.

Examples

Tetrahedron: This tetrahedron is convex and has χ = 2. A possible triangulation is

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

Cube: This cube is convex and has χ = 2. A possible triangulation is

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

Donut: This donut/toroid shape has χ = 0. A possible triangulation is

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

Double Donut: This double-donut should have χ = -2. It is constructed by using two copies of the donut above and identifying the sides [1,2,5,4] of the first one with the side [1,3,6,4] of the second one.

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

(Examples verified using this Haskell program.)

Haskell, 49 46 bytes

u=length
f x|j<-x>>=id=maximum j+u x-u j`div`2

Try it online!

I get the number of vertices by concating the faces and finding the maximum.  I find the number of faces by taking the length.  I find the number of edges by summing the lengths of the faces and dividing by 2.


Identifying Sequences for Cellular Automata Background

For the purposes of this challenge, an n-state cellular automaton is simply a binary function f that takes two numbers from the state set {0, 1, ..., n-1} as inputs, and returns another number from that set as output.
It can be applied to a list of numbers L = [x0, x1, x2, ..., xk-1] of length at least 2 by

f(L) = [f(x0, x1), f(x1, x2), f(x2, x3), ..., f(xk-2, xk-1)]

Note that the resulting list has one fewer element than the original.
A spacetime diagram of f starting from L is the list of lists obtained by repeatedly applying f to L, and collecting the results in a list.
The final list has length 1.
We say that the list L is an identifying sequence for f, if every two-element list over the state set is a contiguous sublist of some row of the spacetime diagram starting from L.
This is equivalent to the condition that no other n-state CA has that exact spacetime diagram.

Input

Your inputs are an n-by-n integer matrix M, a list of integers L of length at least 2, and optionally the number n.
The matrix M defines an n-state CA f by f(a,b) = M[a][b] (using 0-based indexing).
It is guaranteed that n > 0, and that M and L only contain elements of the state set {0, 1, ..., n-1}.

Output

Your output shall be a consistent truthy value if L is an identifying sequence for the CA f, and a consistent falsy value otherwise.
This means that all "yes"-instances result in the same truthy value, and all "no"-instances result in the same falsy value.

Example

Consider the inputs n = 2, M = [[0,1],[1,0]], and L = [1,0,1,1].
The matrix M defines the binary XOR automaton f(a,b) = a+b mod 2, and the spacetime diagram starting from L is

1 0 1 1
1 1 0
0 1
1

This diagram does not contain 0 0 on any row, so L is not an identifying sequence, and the correct output is False.
If we input L = [0,1,0,0] instead, the spacetime diagram is

0 1 0 0
1 1 0
0 1
1

The rows of this diagram contain all pairs drawn from the state set, namely 0 0, 0 1, 1 0 and 1 1, so L is an identifying sequence and the correct output is True.

Rules

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

Test Cases

Trivial automaton
[[0]] [0,0] 1 -> True
Binary XOR
[[0,1],[1,0]] [1,0,1,1] 2 -> False
[[0,1],[1,0]] [1,0,1,0] 2 -> True
[[0,1],[1,0]] [0,1,0,0] 2 -> True
Addition mod 3
[[0,1,2],[1,2,0],[2,0,1]] [0,1,1,0,0,0,1,0,0] 3 -> False
[[0,1,2],[1,2,0],[2,0,1]] [0,1,1,0,0,0,1,0,1] 3 -> True
Multiplication mod 3
[[0,0,0],[0,1,2],[0,2,1]] [0,1,1,2,0,0,1,0,1] 3 -> False
[[0,0,0],[0,1,2],[0,2,1]] [0,1,1,2,2,2,1,0,1] 3 -> True
Some 4-state automata
[[3,2,2,1],[0,0,0,1],[2,1,3,1],[0,1,2,3]] [0,0,0,0,1,1,1,1] 4 -> False
[[3,2,2,1],[0,0,0,1],[2,1,3,1],[0,1,2,3]] [0,0,0,1,0,1,1,1] 4 -> False
[[3,2,2,1],[0,0,0,1],[2,1,3,1],[0,1,2,3]] [0,1,2,3,3,1,2,3,0] 4 -> True
[[0,1,2,1],[1,0,2,0],[2,2,1,0],[1,2,0,0]] [0,0,1,1,2,2,0,2,1] 4 -> False
[[0,1,2,1],[1,0,2,0],[2,2,1,0],[1,2,0,0]] [0,3,1,3,2,3,3,0,1] 4 -> False
[[0,1,2,1],[1,0,2,0],[2,2,1,0],[1,2,0,0]] [0,3,1,3,2,3,3,0,1,2] 4 -> True

Python 2: 93 byte

M,L,n=input();a=[]
while L:z=zip(L,L[1:]);a+=z;L=[M[i][j]for i,j in z]
print len(set(a))==n*n

Straightforward implementation: Find all pairs by zipping, memorize them for later and apply M to L. Repeat. Compare the number of unique pairs found.

Input is of the form [[0,1],[1,0]], [0,1,0,0], 2.


Generate a "random" color set Your challenge is to write a program that takes input from stdin, creates a set of 1 to ncolors and outputs them on stdout, formatted as a 6-digit-hex value with a prefixed #.

The starting color should have following values (in a hsv colorspace) (pesudocode)

h=rand(), s=0.5, v=0.95.

Every subsequent color should have its hue value increased by

1/Φ

After every 5th color, the saturation and value for the forthcoming colors should be

saturation - increased by 0.1
value - decreased by 0.2

e.g.
Color  #    h         s       v
       1  0.5        0.5     0.95
       2  0.118...   0.5     0.95
      11  0.680...   0.7     0.55

Input
Your program shall receive an Integer nas input (stdin), which defines the number of colors, to be generated. Where 0 < n < 16
Output

On each call, the hues' start value  should be different from the last call (Don't just take the same random start number on every call)
Output should be on stdout with one color per line.
The array shall contain n different hex codes.
The hex codes should be prefixed with a "#" and be padded with a "0", such that you always get a 7 character string like "#FFFFFF"

Additional Rules

The use of built in functions/tools/etc  for the following conversions is forbidden

HSV->RGB
RGB->HEX representation of RGBa function which specifically converts rgb to hex, generic tools like sprintf are ok.
HSV->HEX representation of RGBjust to make sure...

Scoring
The size of your code in bytes.
Test Cases(result of rand() in parantheses)
3 (0.35389856481924653) ->
    #79f388
    #f3798e
    #79b1f3

8 (0.763850917108357) ->
    #c079f3
    #79f39d
    #f37979
    #4c6ec0
    #90c04c
    #c04cb1
    #4cc0ac
    #c08b4c

15 (0.10794945224188268) ->
    #f3c879
    #a479f3
    #79f381
    #f37995
    #79b8f3
    #aac04c
    #b44cc0
    #4cc092
    #c0704c
    #4f4cc0
    #448c2a
    #8c2a61
    #2a7e8c
    #8c7e2a
    #612a8c

for a visualization of the codes, you can paste your output here
I will change the accepted Answer, as soon as new appear

Python 184 bytes

from random import*
h,s,v=random()*6,.5,243.2
for i in range(input()):
 h+=3.708;print'#'+'%02x'*3%((v,v-v*s*abs(1-h%2),v-v*s)*3)[5**int(h)/3%3::int(h)%2+1][:3]
 if i%5/4:s+=.1;v-=51.2

The HSV ⇒ RGB conversion is taken directly from wikipedia.

A few implementation notes.

h is defined as its proper value times 6, which simplifies region determination.
v is defined as its proper value times 256, which propagates through to all three RGB values.
6/Φ  (approximately ~3.708) is used instead of 1/Φ, in agreement with the scaling of h. Similarly, the decrement value for v is also scaled by 256.
The bit of magic
((v,v-v*s*abs(1-h%2),v-v*s)*3)[5**int(h)/3%3::int(h)%2+1][:3]
is logically equivalent to
c=v*s;m=v-c;x=c-c*abs(1-h%2)+m;c+=m;[(c,x,m),(x,c,m),(m,c,x),(m,x,c),(x,m,c),(c,m,x)][int(h)%6]

Sample usage:

$ echo 3 | python color-set.py
#f37994
#79b8f3
#dbf379

$ echo 8 | python color-set.py
#d2f379
#f079f3
#79f3cc
#f3a979
#8579f3
#62c04c
#c04c84
#4ca6c0

$ echo 15 | python color-set.py
#7984f3
#a8f379
#f379cb
#79eff3
#f3d379
#804cc0
#4cc05e
#c04c5c
#4c7dc0
#9fc04c
#8b2a8c
#2a8c6f
#8c522a
#352a8c
#3b8c2a

A visualization of the values for n = 15:

and the corresponding html.


Rotation invariant fingerprinting Imagine we have some polyomino and would like to uniquely identify them, however the polyominos can be rotated, so blindly hashing them won't give us the same fingerprint for a piece and a rotation thereof (in general).

For example if we have the L-tetromino

x
x
xx

we would like it to have the same fingerprint as any of these:

         xx
  x       x      xxx
xxx  ,    x  or  x

Note: We only allow rotations on the plane (ie. they are one-sided polyominos) and therefore the following polyomino would be a different one:

 x
 x
xx

Challenge

The task for this challenge is to implement a fingerprinting-function/program which takes an \$m\times n\$ Boolean/\$0,1\$-valued matrix/list of lists/string/.. encoding a polyomino and returns a string - the fingerprint of a polyomino. The fingerprint must be equal for all of the possible rotations (in general 4).

Input / Output

\$m \geq 1\$ and \$n \geq 1\$ (ie. no empty polyomino)
you're guaranteed that \$m,n\$ are as small as possible (ie. all \$0\$ are trimmed to fit \$m\$ and \$n\$
you're guaranteed that the input is

simply connected
has no holes

output must be a string which is the same for each possible rotation of a polyomino

Examples

Here are some equivalence classes, for each class the fingerprint must be the same & for any two polyominos from two distinct classes they must differ.

The rotations of the L-tetromino from the example:

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

The J-tetromino:

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

The unit polyomino:

[[1]]

A \$5\times 1\$ bar:

[[1,1,1,1,1]]
[[1],[1],[1],[1],[1]]

A \$2\times 2\$ corner:

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

W-pentomino:

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

Python 2, 48 bytes

f=lambda l,z=5:z and max(l,f(zip(*l)[::-1],z-1))

Try it online!

Takes the largest of the four rotations in terms of list comparison. Based on FlipTack's solution.

The code uses Python 2's ability to compare objects of different types. The base case value of 0 is harmless for max because it's smaller than any list. Also, zip produces a list of tuples while the input is a list of lists, but tuples are bigger than lists so the input list-of-lists is never a contender. This is why we rotate 5 times rather than 4, so that we get back to a tuplified version of the initial list. (Taking a list of tuples would also work, if that's an allowed form of input.)


Collatz's First Conjecture Background

The Collatz Conjecture is quite well-known. Take any natural number. Triple and increment if odd; cut in half if even. Repeat, and it will reach 1 eventually. This famous conjecture, however, is only that, for it is yet unproven.

Little-known to the world, that was not Lothar Collatz's first attempt at fame. His first Conjecture (now proven) was a touch simpler:

Take any natural number n.
While n ≠ 4, find the length of its written-out form (English). Store this value to n.

The conjecture is that all natural numbers will eventually become 4. This did not catch on as well as Collatz had hoped, so he returned to the drawing board.

Your task

Read a positive integer n < 2147483648 (2^31) from input and return/print the number of iterations required to reach 4.

Things to note

Do not use and. 228 is "two hundred twenty-eight," not "two hundred and twenty-eight."

Do not use articles. 145 is "one hundred forty-five," not "a hundred forty-five.)

Commas set apart each three orders or magnitude: "one million, four hundred eighty-two thousand, one hundred seventy-five."

Punctuation is counted. Spaces are not. Hyphenate 21-99 except multiples of ten.

Test cases

  4 (four): 0
  3 (three→five→four): 2
  6278 (six thousand, two hundred seventy-eight→thirty-five→eleven→six→three→five→four): 6
  1915580 (one million, nine hundred fifteen thousand, five hundred eighty→fifty-five→ten→three→five→four): 5
  2147483647 (two billion, one hundred forty-seven million, four hundred eighty-three thousand, six hundred forty-seven→ninety-three→twelve→six→three→five→four): 6

This is code-golf, so the shortest code (in bytes) in each language WINS! Good luck!

Python 3 + inflect,  122  114 bytes

Saved 8 bytes thanks to Scrooble.

from inflect import*
f=lambda k,i=0:k!=4and f(len(engine().number_to_words(k,andword="").replace(" ","")),i+1)or i

This cannot be tested online because of the package it uses. Running the test suite gives:

4 -> 0
3 -> 2
6278 -> 6
1915580 -> 5


Verify Wolstenholme's theorem Definition

Wolstenholme's theorem states that:

where  a and b are positive integers and p is prime, and the big parentheses thingy is Binomial coefficient.

Task

To verify that, you will be given three inputs: a, b, p, where a and b are positive integers and p is prime.

Compute:

where  a and b are positive integers and p is prime, and the parentheses thingy is Binomial coefficient.

Specs

Since:

where and the parentheses thingy is Binomial coefficient.

You can assume that 2b <= a

Testcases

a b p  output
6 2 5  240360
3 1 13 3697053
7 3 13 37403621741662802118325

Haskell, 73 71 bytes
Due to the recursion, this implementation is very slow. Unfortunately my definition of the binomial coefficient has the same length as import Math.Combinatorics.Exact.Binomial.
n#k|k<1||k>=n=1|1>0=(n-1)#(k-1)+(n-1)#k --binomial coefficient
f a b p=div((a*p)#(b*p)-a#b)p^3       --given formula

An interesting oddity is that Haskell 98 did allow for arithmetic patterns which would have shortened the same code to 64 bytes:
g a b p=div((a*p)#(b*p)-a#b)p^3
n+1#k|k<1||k>n=1|1>0=n#(k-1)+n#k


Number of string permutations that are palindromes Your input will be a string consisting of small english letters.

Your task is to determine the number of distinct permutations of the original string that are a palindrome.

The input string has up to 100 letters. In the case of a longer string the result might be very big so the output should be the number of permutations modulo 666013.

For example,

cababaa -> 3

The possible permutations are:

aabcbaa
abacaba
baacaab

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

Brachylog (2), 15 bytes

{p.↔}ᶠdl%₆₆₆₀₁₃

Try it online!

Explanation

{p.↔}ᶠdl%₆₆₆₀₁₃
{   }ᶠdl          Count (l) the number of distinct (d) results (ᶠ) obtainable by:
 p                  permuting {the input}
  .                 to produce an output
   ↔                that, if reversed, is still the output
        %₆₆₆₀₁₃   then take that number modulo 666013


Parenthifiable Binary Numbers If you express some positive integer in binary with no leading zeros and replace every 1 with a ( and every 0 with a ), then will all the parentheses match?

In most cases they won't. For example, 9 is 1001 in binary, which becomes ())(, where only the first two parentheses match.

But sometimes they will match. For example, 44 is 101100 in binary, which becomes ()(()), where all the left parentheses have a matching right parenthesis.

Write a program or function that takes in a positive base ten integer and prints or returns a truthy value if the binary-parentheses version of the number has all matching parentheses. If it doesn't, print or return a falsy value.

The shortest code in bytes wins.

Related OEIS sequence.

Truthy examples below 100:

2, 10, 12, 42, 44, 50, 52, 56

Falsy examples below 100:

1, 3, 4, 5, 6, 7, 8, 9, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 43, 45, 46, 47, 48, 49, 51, 53, 54, 55, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99

Pyth, 10 bytes

!uscG`T.BQ

Try this test suite in the Pyth Compiler.

How it works

              (implicit) Store the evaluated input in Q.
       .BQ    Return the binary string representation of Q.
 u            Reduce w/base case; set G to .BQ and begin a loop:
     `T         Return str(10) = "10".
   cG           Split G (looping variable) at occurrences of "10".
  s             Join the pieces without separators.
              Set G to the returned string.
              If the value of G changed, repeat the loop.
              This will eventually result in either an empty string or a
              non-empty string without occurrences of "10".
!             Return (and print) the logical NOT of the resulting string.


128 years? Hypothetical leap year reform The solar year is 365 days, 5 hours, 48 minutes, 45 seconds, and 138 milliseconds, according to this video. With the current Gregorian calendar, the rules for leap years are as follows:

if      year is divisible by 400, LEAP YEAR
else if year is divisible by 100, COMMON YEAR
else if year is divisible by 4,   LEAP YEAR
else,                             COMMON YEAR

Unfortunately, this method is off by one day every 3216 years.

One possible method of reforming the calendar is the following rule:

if      year is divisible by 128, COMMON YEAR
else if year is divisible by 4,   LEAP YEAR
else,                             COMMON YEAR

This has the benefit of not requiring us to change our calendars again for another 625,000 years, give or take.

Say the entire world decides that, starting now, we use this system of every fourth year is a leap year except every 128th year, changing our calendars as follows:

YEAR    GREGORIAN    128-YEAR
2044    LEAP         LEAP
2048    LEAP         COMMON
2052    LEAP         LEAP
 ...
2096    LEAP         LEAP
2100    COMMON       LEAP
2104    LEAP         LEAP
 ...
2296    LEAP         LEAP
2300    COMMON       LEAP
2304    LEAP         COMMON
2308    LEAP         LEAP

How would this affect our day of the week algorithms?

The challenge

Given a date from the year 2000 to the year 100000, find the day of the week under this new calendar.
Any input and output format is allowed as long as you clearly specify which formats you are using.
This is code golf so try to make your solutions as golfy as possible!

Test cases

"28 February 2048" -> "Friday"
"March 1, 2048"    -> "Sat"
(2100, 2, 29)      -> 0           # 0-indexed with Sunday as 0
"2100-02-29"       -> 7           # 1-indexed with Sunday as 7
"28 Feb. 2176"     -> "Wednesday"
"1-Mar-2176"       -> "Th"
"28/02/100000"     -> "F"         # DD/MM/YYYYYY
"Feb. 29, 100000"  -> 6           # 1-indexed with Sunday as 7
"03/01/100000"     -> 1          # MM/DD/YYYYYY and 1-indexed with Sunday as 1

Suggestions and feedback on the challenge are welcome. Good luck and good golfing!

C (gcc), 60 bytes

f(m,d,y){y-=m<3;return(y+y/4-y/128+"-bed=pen+mad."[m]+d)%7;}

Try it online!

Simple modification of Sakamoto's method. Takes input as integer arguments in the order month, day, year, and outputs the number of the day (0-indexed on Sunday).


Filling Arbitrary Ice Cube Trays Suppose this grid of spaces and X's represents the cross section of some strangely shaped empty ice cube trays:

   X     X X
X  X X  XX X  XX   X
XXXXXX XXXXXXXXXXXXX

Columns without X's represent holes or gaps in the trays that can't hold water, draining into an infinite capacity sink. Water falling off the leftmost or rightmost edge of the grid goes into this endless sink as well.

If we were to position a faucet above the trays and let them fill with water until the water level in all compartments remains stable, the exact compartments that become filled would depend on exactly where the water stream was positioned above the trays. (Assume a thin, steady stream of water with no splashing.)

For example, if our faucet F were above the very left grid column

F
   X     X X
X  X X  XX X  XX   X
XXXXXX XXXXXXXXXXXXX

the water would fall down to the topmost X in that column and spread left and right, the left half spilling into the sink below, and the right half filling up the 2×1 compartment. Once the compartment fills, the right half of the water stream has nowhere to flow but into the sink and the water level everywhere is essentially stable.

Turning the faucet off, the tray now looks like this: (with ~ as water)

   X     X X
X~~X X  XX X  XX   X
XXXXXX XXXXXXXXXXXXX

Similarly, if we position the faucet like this:

   F
   X     X X
X  X X  XX X  XX   X
XXXXXX XXXXXXXXXXXXX

It will fill up the two leftmost compartments but the rest of the water will drain away:

   X     X X
X~~X~X  XX X  XX   X
XXXXXX XXXXXXXXXXXXX

If we position the faucet like this:

         F
   X     X X
X  X X  XX X  XX   X
XXXXXX XXXXXXXXXXXXX

The left half of the stream will flow into the sink but the right half will eventually fill up the three rightmost compartments because there's no limit to how far water can travel horizontally on a flat surface:

   X     X~X
X  X X  XX~X~~XX~~~X
XXXXXX XXXXXXXXXXXXX

Positioned like this, however:

        F
   X     X X
X  X X  XX X  XX   X
XXXXXX XXXXXXXXXXXXX

All the water drains away and no compartments are filled:

   X     X X
X  X X  XX X  XX   X
XXXXXX XXXXXXXXXXXXX

Challenge

Write a program or function that takes in a rectangular grid of spaces, X's, and one F. The top row will always contain the F and otherwise only contain spaces. The X's in each column (if there are any) will extend in a solid line up from the base of the grid, i.e. there will be no caves or overhangs.

Print or return the grid after the faucet F has filled what it can with water ~ as described above. Leave the top F row out of the output.

The grid apart from the faucet row will be 1×1 at minimum so

F
X

is the smallest input you need to support.
The input will come in as a complete text rectangle. Leading and trailing spaces do matter in the input and output. e.g. the input

    F
  X  X
  XXXX

should result in

  X~~X
  XXXX

(note the leading and trailing spaces)
Having a single trailing newline in the input or output is fine.
You can use any four distinct printable ASCII characters in place of space, X, F, ~.

The shortest code in bytes wins.

Big Example:

Input:

                F
              X             X
              X             X X
X            XXX       X    X X           X    X
X   X     XXXXXXX      X    XXX     XXXXXXX X  X
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXX

Output:

              X~~~~~~~~~~~~~X
              X~~~~~~~~~~~~~X~X
X~~~~~~~~~~~~XXX~~~~~~~X~~~~X~X~~~~~~~~~~~X    X
X~~~X~~~~~XXXXXXX~~~~~~X~~~~XXX~~~~~XXXXXXX X  X
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXX

Lua 5.2, 581 Bytes

Again, slow start with so ineffective language for golfing and with ineffective algorithm. But I will improve :)

r=io.read w=io.write F=r()f=F:find("F")o={[1]=F}W=#F i=2
repeat s=r()if s==nil then break end o[i]={}for j=1,W do o[i][j]=s:sub(j,j)end i=i+1 until false
function e(i,j)
local k,l,b,c=j+1,j-1,false
if i>=#o or(o[i+1][j]==" "and e(i+1,j)==0)then return 0 end
while k<=W do
b=b or o[i][k]=="X"
if b or(o[i+1][k]==" "and e(i+1,k)==0)then break end
k=k+1 end
while l>0 do
c=c or o[i][l]=="X"
if c or(o[i+1][l]==" "and e(i+1,l)==0)then break end
l=l-1 end
if b and c then for m=l+1,k-1 do o[i][m]="~"end return 1 end
return 0 end
e(1,f)for i=2,#o do for j=1,W do w(o[i][j])end w"\n"end

Test cases (with water source):

---------
    F
  X~~X
  XXXX
--------------------
         F
   X     X~X
X  X X  XX~X~~XX~~~X
XXXXXX XXXXXXXXXXXXX
--------------------
   F
   X     X X
X~~X~X  XX X  XX   X
XXXXXX XXXXXXXXXXXXX
--------------------------------------------------
                F
              X~~~~~~~~~~~~~X
              X~~~~~~~~~~~~~X~X
X~~~~~~~~~~~~XXX~~~~~~~X~~~~X~X~~~~~~~~~~~X    X
X~~~X~~~~~XXXXXXX~~~~~~X~~~~XXX~~~~~XXXXXXX X  X
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXX

from bash it is possible to test this way, but it doesn't look so nice:

$ echo "    F
  X  X
  XXXX   " | lua f.lua


Infinite Sequence of Unique Random Integers Output an infinite sequence of positive integers, such that, for each element in the sequence, all positive integers that have not yet been output have a positive probability of being chosen, and no value is repeated.
For example, if the first integer is 3, then 3 may not be output again, but all other positive integers have a positive probability of being chosen for the second integer.
Acceptable output methods

Writing to STDOUT, with a consistent, unambiguous separator between integers (such as a newline), with output prior to termination of the program
A named or unnamed function which returns an infinite iterable (such as a Python generator)
A named or unnamed function which outputs the sequence one integer at a time each time it is called within a single execution of the program
A named or unnamed function or program which outputs the next integer in the sequence when called with the previous integer(s) as its sole argument(s) (the first call may either take no arguments or take a seed argument, which may be included in the arguments to later calls)

Rules

There will be no input except an optional seed value, which will be an infinite sequence of random bits.
Submissions must be capable of producing different outputs given different initial conditions (outputting the same sequence every time is not acceptable).
Each element of the sequence must be chosen randomly out of the valid elements (positive integers not already present in the sequence).
You may assume that you have infinite memory available.
You may assume that any real numbers returned by a PRNG are infinite-precision. In other words, if you have a function called rand that returns a random value in [0, 1), you may assume every real value in that interval has a positive probability of being chosen, rather than just the subset of the reals that are representable with floats.
Each integer must be output in a finite amount of time after the last integer (so you can't wait until program termination to output part of the sequence). The first integer must be output in a finite amount of time after the program is started or the function is called.

Python 3, 137 127 123 138 117 99 98 bytes

  A named or unnamed function which returns an infinite iterable (such as a Python generator)

from random import*
def f(x=[],y=1):
 while y in x or.5<random():y+=1
 yield y;yield from f(x+[y])

-10 bytes by putting the conditional in one line (Thanks, @Dennis)
-4 bytes by initializing r at the beginning of the loop
+15 bytes by remembering numbers can contain zeroes...
-21 bytes by renaming randint, and moving the condition in the head of the inner loop
-18 bytes by switching to a functional paradigm
-1 bytes by moving from or ...>.5 to .5<random() (thanks, @JonathanAllan)


Implement bottom (encode) Challenge
The challenge is to implement the bottom encoding (only encoding, not decoding). There is a wide variety of existing implementations in the bottom-software-foundation org.
Bottom is a text encoding where each character is separated into multiple emoji.

Unicode escape(s)
Character
Value

U+1FAC2

200

U+1F496

50

U+2728
✨
10

U+1F97A

5

U+002C
,
1

U+2764, U+FE0F
❤
0

Unicode escape(s)
Character
Purpose

U+1F449, U+1F448

Byte separator

Notes on encoding

The output stream will be a sequence of groups of value characters (see table above) with each group separated by the byte separator character, i.e.
✨✨✨,,,,✨✨✨✨,,✨,✨,,,

The total numerical value of each group must equal the decimal value of the corresponding input byte.

For example, the numerical value of ,,,,, as according to the
character table above, is
50 + 50 + 1 + 1 + 1 + 1, or 104. This sequence would thus represent U+0068 or h,
which has a decimal value of 104.
Note the ordering of characters within groups. Groups of value characters must be in descending order.
While character order (within groups) technically does not affect the output in any way,
arbitrary ordering can encroach significantly on decoding speed and is considered both illegal and bad form.

Byte separators that do not follow a group of value characters are illegal, i.e ,,,,
or ,,,,. As such,  alone is illegal.
Groups of value characters must be followed by a byte separator. ,,,, alone is illegal, but ,,,, is valid.
The null value must not be followed by a byte separator. ,,,,❤,,,, and ,,,,❤ alone are valid, but ,,,,❤ is illegal.

Some pseudocode to illustrate how each character is converted:
for b in input_stream:
    # Get `b`'s UTF-8 value
    let v = b as number
    let o = new string

    if v == 0:
        o.append("❤")
    else:
        while true:
            if v >= 200:
                o.append("")
                v = v - 200
            else if v >= 50:
                o.append("")
                v = v - 50
            else if v >= 10:
                o.append("✨")
                v = v - 10
            else if v >= 5:
                o.append("")
                v = v - 5
            else if v >= 1:
                o.append(",")
                v = v - 1
            else:
                break

        o.append("")

return o

Rules

The standard I/O rules apply.
The input must be a string, not a list of bytes.
An empty string should return an empty string.
It should return the same result as bottom-web for any input with no null bytes (UTF-8 validation is not required).

Some test cases:

test -> ✨,,✨✨,
Hello World! -> ✨✨,,,,,,,,,✨,✨✨✨,,✨✨✨,,✨,✨,,,,,,,✨✨✨,,,
 -> ✨✨✨✨,,,,✨✨✨✨,
   (2 spaces) -> ✨✨✨,,✨✨✨,,
 -> ✨✨✨✨✨✨✨✨,,,,✨✨,,,✨✨✨,,,
⍉⃠ -> ✨✨,✨✨✨✨,✨✨✨,,✨✨,✨✨✨,✨
X⃩ -> ✨✨✨,,,✨✨,✨✨✨,✨,,,,
❤ -> ✨✨,,,✨,,,,✨✨✨,,,,✨✨✨,,,,✨✨✨✨,,,
.\0. (null byte surrounded by full stops) -> ✨✨✨✨,❤✨✨✨✨,

This is code-golf, so fewest bytes win!

APL(Dyalog Unicode), 133 bytes SBCS
{↑,/{⍵=0:'❤'⋄'',⍨⍬{⍵≥200:(⍺,'')∇⍵-200⋄⍵≥50:(⍺,'')∇⍵-50⋄⍵≥10:(⍺,'✨')∇⍵-10⋄⍵≥5:(⍺,'')∇⍵-5⋄⍵≥1:(⍺,',')∇⍵-1⋄⍺}⍵}¨'UTF-8'⎕ucs⍵}

Try it on APLgolf!
-5 thanks to ovs.


Complementary colors Given an input of a color in #rrggbb hex format, output its RGB complement in
the same format.

The RGB complement R2G2B2 of any color
R1G1B1 is defined as the color with
R2 value 255 - R1, B2 value 255 -
B1, and G2 value 255 - G1.

Hex digits may be either in uppercase (#FFAA20) or lowercase (#ffaa20). The
case of the input and output need not be consistent (so you may take input in
lowercase but output in uppercase, and vice versa).

Since this is code-golf, the shortest code in bytes wins.

Test cases (note that since giving your program/function its own output should
result in the original input (it is
involutory), the test
cases should work in both directions):

In/Out   Out/In
----------------
#ffffff  #000000
#abcdef  #543210
#badcab  #452354
#133742  #ecc8bd
#a1b2c3  #5e4d3c
#7f7f80  #80807f

Pyth, 9 8 bytes
Thanks to @isaacg for -1 byte!
sXz.HM16

Subtracting a certain color's value from 255 is equivalent to subtracting each of its hexadecimal digits from 15. Say a number is 16a+b. Then the value of the number created by subtracting its digits from 15 is 16(15-a) + (15-b) = 255 - (16a+b).
sXz.HM16     implicit: z=input()
      16
   .HM        map hex representation over range
   .HM16     '0123456789abcdef'
  z           the input string
 X            Translate characters in x1 present in x2 to reversed x2
              that is, '0' becomes f, '1' becomes 'e', and so on.
              The initial '#' is unchanged.
s             That produced a list, so join into a string by reducing +

Try it here. Test suite.


Even a clock that isn't working gets the time right two or three times a day Context

When I was a little kid, I watched a Disney movie where Goofy told his son "Boy, even a broken clock is right two or three times a day." (see this youtube clip, courtesy of @Arnauld).

Rationale

Given the previous statement, we wish to look at a clock that is stopped and answer the following question: is this clock telling the correct time?, decision-problem-style. But we will also do it Goofy style, assuming a stopped clock gets the correct time 3 times a day.

Task

Pick some time of the morning with at least minute precision. Call it \$t\$.

The function/full program/etc you submit must satisfy the following requirements:

if executed at \$t\text{ am}\$ and at \$t\text{ pm}\$, your code produces an observable output a (think Truthy in decision-problem challenges).
for every calendar day, there is a third time \$t_1\$ distinct from \$t\text{ am}\$ and \$t\text{ pm}\$ such that, if your code is ran at that time, your code also deterministically produces the observable output a. This means \$t_1\$ may be constant or it may be a function of the day the code is ran at.
if ran at any other time of the day, your code produces an observable output b that must be distinct from a (think Falsy in decision-problem challenges).

Recall that your code should be precise at least to the minute. This means that you may decide that seconds don't matter for your answer, but you might also want to decide that your answer checks up to nanoseconds in order to decide if it is that time of the day.

Input

Either your code takes no input or it takes the "current" time. For the time, acceptable formats include, but are not limited to:

Any ISO format for date/time strings where time is given at least to the minute;
An integer list with [hours, minutes] or [hours, minutes, seconds] or any similar list with further subdivisions of the second; (this order may be reversed but may not be shuffled)
Different arguments, each representing one element from the lists above.

Output

A single, well-defined, observable output a if your code is run at \$t\text{ am}\$, at \$t\text{ pm}\$, or at \$t_1\$, as specified in your answer. If ran at any other time, your code produces the observable output b, distinct from a.

Bonus imaginary internet points

Bonus imaginary internet points will be awarded to the shortest answer for which \$t_1\$ isn't constant. If this question turns out to receive enough attention, this will turn into an actual rep bounty.

This is code-golf so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it! If you dislike this challenge, please give me your feedback. Happy golfing!

JavaScript (ES6), 13 bytes
Takes input as (h)(m). Returns true for 01:00, 02:00 and 13:00, or false for anything else.

h=>m=>26%h<!m

Try it online!
How?
Testing \$26\bmod h<\delta_m\$ is equivalent to test that we have \$m=0\$ and \$26\equiv 0\pmod h\$.
For \$0<h\le23\$, we have \$26\equiv 0\pmod h\$ iff \$h\$ divides \$26\$, i.e. \$h\in\{1,2,13\}\$.
For the edge case \$h=0\$, 26%h results in NaN which is neither greater nor lower than any other value, so the test returns false as expected, no matter the value of \$m\$.
Other possible values
This program generates all possible values \$n<1000\$ for the expression \$n\bmod h\$.

for(n = 1; n < 1000; n++) {
  A = [...Array(24)].map((_, x) => x).filter(x => n % x == 0);
  if(A.length == 3 && A.some(x => A.includes(x + 12))) {
    console.log(n, A);
  }
}

Try it online!


Create a rotating quine A rotation of a string is made by splitting a string into two pieces and reversing their order, for example "world! Hello," is a rotation of "Hello, world!". It is possible to create programs that can be rotated to form a different, but still valid program. Consider this example in python:

print ")import sys; sys.stdout.write("

It can be rotated to form

import sys; sys.stdout.write("print ")

Which is itself a valid python program.

Your challenge is to write a program that outputs a rotation of itself, which when run will output the original program. Bonus points to any entry with a cycle length greater than two!

This is code golf, the exact scoring will be: (length of code)/(cycle length - 1).

EDIT: We have a winner (unless someone else is able to beat a score of 4)! I'd still be very interested to see any other solutions, whether they're contenders or not.


List where pinballs would exit a grid of bumpers from different entrance points Inspired by this lumosity mini game, Pinball Recall

We start with a rectangular grid (viewed from above) with several bumpers as follows. Entrances/exits are numbered counter-clockwise starting from the leftmost of the bottom of the grid, as number 0.

   24 23 22 21 20 19 18 17 16 15
25  .  .  .  .  .  /  .  .  .  . 14
26  .  .  .  .  .  .  .  .  .  . 13
27  .  /  \  .  .  \  .  .  \  . 12
28  .  .  .  .  .  .  .  .  .  . 11
29  .  .  .  .  .  .  /  .  .  . 10
    0  1  2  3  4  5  6  7  8  9

Pinballs can be fired from each entrance into the grid at a direction perpendicular to the grid wall, e.g. in the above example:

0 to 9: fired upwards
10 to 14: fired to the left
15 to 24: fired downwards
24 to 29: fired to the right

The pinballs will move in a straight line until they reach an exit, or a bumper, in which case the ball will bounce off the bumper and change direction. So in above diagram,

from 0, ball goes straight to 24
from 1, ball goes up to / and bounces off to reach \, then bounces off again and ends up at 2
from 10, ball goes left to / and bounces off to 6

Inputs

Program shall receive the grid width and height.
Then program receives the bumper orientation (represented as / or \) followed by coordinates, which also start from 0 from bottom left, e.g.

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

"done" keyword used to indicate end of input

edit: as suggested by ngn, program may receive list of bumper coordinates instead so the "done" keyword is not needed

Output

Program should print out the exit locations of a pinball if they are fired from 0 to the last entrance of grid, in above case, 0 to 29

Sample input and output

Input

10 5
/ 1 2 / 5 4 / 6 0 \ 2 2 \ 5 2 \ 8 2
done

Output

24 2 1 21 20 22 10 17 14 15 6 28 16 26 8 9 12 7 29 25 4 3 5 27 0 19 13 23 11 18

Leaderboard (as of 20Oct2019)

Neil, Charcoal, 133 bytes
Arnauld, JavaScript (ES6), 212 bytes
Embodiment of Ignorance, C# (Visual C# Interactive Compiler), 277 bytes
Chas Brown, Python 2, 290 bytes

edit: FryAmTheEggman points out a similar question to try

JavaScript (ES6),  218 215 213  212 bytes
Takes input as (w,h,o) where \$o\$ is an object whose keys are the coordinates of the bumpers in 'x,y' format and whose values are either '/' or '\'.

(w,h,o)=>(A=[...Array(w+h<<1)].map((_,n)=>(p=n-w)<0?[n,-1,3]:p<h?[w,p]:(p-=w)<h?[h+~p,h,1]:[-1,2*h+~p,2])).map(g=([x,y,d])=>A.every(([X,Y])=>X-x|Y-y&&++i,(c=o[[x+=~-d%2,y+=~-~-d%2]])?d^=c<{}||3:i=0)?g([x,y,d]):i)

Try it online!
Commented
We first create an array \$A[\:]\$ of tuples \$[x, y, d]\$ where \$(x, y)\$ is the starting position along the borders of the playfield and \$d\$ is the initial direction.
( A = [...Array(w + h << 1)]  // create an array A[] of (w + h) * 2 items
  .map((_, n) =>              // for each item at position n in A[]:
    (p = n - w) < 0 ?         //   set p = n - w; if this is the bottom side:
      [n, -1, 3]              //     start at (n, -1) in direction 3
    :                         //   else:
      p < h ?                 //     if this is the right side:
        [w, p]                //       start at (w, p) in direction 0 (implicit)
      :                       //     else:
        (p -= w) < h ?        //       subtract w from p; if this is the top side:
          [h + ~p, h, 1]      //         start at (h + ~p, h) in direction 1
        :                     //       else (left side):
          [-1, 2 * h + ~p, 2] //         start at (-1, 2 * h + ~p) in direction 2
  )                           // end of map()
)                             //

We then simulate the trajectory of the ball, starting at each position defined above, until it reaches another starting position.
.map(g = ([x, y, d]) =>       // for each tuple [x, y, d] in A[]:
  A.every(([X, Y]) =>         //   for each tuple [X, Y] in A[]:
    X - x | Y - y             //     break if (x, y) = (X, Y)
    && ++i,                   //     otherwise, increment i
    ( c =                     //     define c as
        o[[                   //       the bumper character at
          x += ~-d % 2,       //         (x, y), once updated according to d
          y += ~-~-d % 2      //         (0 = West, 1 = South, 2 = East, 3 = North)
        ]]                    //
    ) ?                       //     if c is set:
      d ^= c < {} || 3        //       XOR d with 1 (for '/') or 3 (for '\')
    :                         //     else:
      i = 0                   //       initialize i to 0
  ) ?                         //   end of every(); if truthy:
    g([x, y, d])              //     do a recursive call to move the ball further
  :                           //   else:
    i                         //     we've reached a starting position: yield i
)                             // end of map()


Help me golf my numbers! When writing code-golf programs, I usually end up using some numeric constants. I always put them in decimal because that's how I think, but I just realized that my language supports other number formats that might let me shorten my code slightly.

Challenge

Given a non-negative integer less than 2^53-1, decide whether that integer has the shortest representation in:

Decimal
Hexadecimal
Scientific Notation

Decimal

Since this is the default format of my language, there is no extra notation needed for this format. Every number is represented as usual for decimal.

Hexadecimal

My languages uses the 0x prefix for hexadecimal constants. This means that if a number has 4 hexadecimal digits, it will take 6 bytes to represent that number.

Scientific notation

My language uses the following format for scientific notation:

  [Real base]e[Integer exponent of 10]

For example, 700 would be represented as 7e3, and 699 would be represented as 6.99e3, because the base must be between -10 and 10 (non-inclusive). For the purposes of this challenge, the base will always be at least 0, since the inputted number is non-negative.

Output

You should return a way of identifying which format is shortest (i.e. 0 for decimal, 1 for hex, 2 for scientific). Alternatively, you may output the smallest representation of the number itself.

Test cases

Decimal       | Hexadecimal  | Scientific        | Winner
--------------|--------------|-------------------|-------------
0             | 0x0          | 0e0               | Decimal
15            | 0xF          | 1.5e1             | Decimal
6999          | 0x1B57       | 6.999e3           | Decimal
7000          | 0x1B58       | 7e3               | Scientific
1000000000000 | 0xE8D4A51000 | 1e12              | Scientific
1000000000001 | 0xE8D4A51001 | 1.000000000001e12 | Hexadecimal
1000000001000 | 0xE8D4A513E8 | 1.000000001e12    | Hexadecimal
1000001000000 | 0xE8D4B45240 | 1.000001e12       | Scientific

Scoring

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

05AB1E, 23 bytes

hgÌ¹gD<g>¹ÀðìÁ0ÜðÜg+)Wk

Try it online!

-1 thanks to Emigna.

0 for hexadecimal, 1 for decimal, 2 for scientific.


Write an interactive Deadfish interpreter Deadfish is a joke "programming language" with four commands. Because the Esolang page is a bit contradictory and the interpreters on that page don't all work exactly the same, you should implement the following variation:

Specification

There is an accumulator which is at least 16 bits in size, more is allowed but less is not. Negative numbers do not need to be supported. The accumulator is 0 when the program starts.
There are the following two sets of four commands, and your program must support both at the same time.

  Standard Deadfish    │   XKCD Variant   │    Meaning
  ─────────────────────┼──────────────────┼────────────────────────────────────
        i              │        x         │    Increment accumulator
        d              │        d         │    Decrement accumulator
        s              │        k         │    Square ( acc = acc * acc )
        o              │        c         │    Output accumulator, as a number

If, after executing a command, the accumulator is either -1 or 256, the accumulator must be reset to zero. Note that this is not normal wrap-around. If, say, the accumulator is 20, and the s command is run, the accumulator should be 400 afterward. Similarly, if the accumulator is 257 and the d command is run, the accumulator should become 0.
Any input that isn't one of these commands should be ignored.

Test programs

xiskso should output 0
xiskisc should output 289

I/O

Your program should display a prompt: >>. The prompt must be at the beginning of a new line. It should then read a line of user input, and run the given commands left-to-right. When outputing numbers, the numbers must be separated. I.e., 12 34 is OK, 12,34 is OK,

12
34

is OK, but 1234 is not.

Your program should keep doing this in a loop, at least until EOF is reached.

Example session:

>> xiskso
0
>> xiskisc
289
>> ddddo ddddo
285
281
>> ddddo ddddo
277
273
>> dddddddo
266
>> dddddddddo
257
>> do
0
>> do
0
>> io
1
>>

Perl 5, 90 bytes

do{print+(map{$?+=/i|x/-/d/;$?**=1+/s|k/;$?=~s/-1|^256$/0/;"$?
"x/o|c/}/./g),'>> '}while<>

Try it online!

Thanks to @xfix for his help on this previously! Saved 4 bytes thanks to @Xcali!


Copy Memory Only Using Store And Subtraction A peer of mine approached me with this challenge and I wasn't able to come up with an elegant solution. After discussing my approach, we began to wonder what the people at Code Golf would come up with.

Given

A processor that implements only two instructions:

STO <register>, <address> (store from this register to this address)
SUB <register>, <address> (subtract the value at this address from this  register)

It also only contains 2, 32-bit registers: A and B
As well as 2, 32-bit RAM address: 0x00 and 0x01
The values of A and B are unknown

Challenge

Write a program to copy RAM address 0x00 into 0x01 optimised to use the fewest number of instructions possible.

Assuming registers are signed and/or wrapping

8 instructions:

STO A 0x01
SUB A 0x01
SUB A 0x00
STO A 0x00
SUB A 0x00
SUB A 0x00
STO A 0x00
STO A 0x01

A 7-instruction version provided by lrn:

STO A 0x01
SUB A 0x01
SUB A 0x00
STO A 0x01
SUB A 0x01
SUB A 0x01
STO A 0x01


Draw/plot a heart graph Your challenge is to draw/plot one of the hearts below. The size must be at least 50x50 pixels (vector graphics is OK). You may choose which of the hearts you want to draw/plot. Axes, grid lines etc. are accepted. There must be at least 100 distinct coordinates/points on the graph. The heart can be filled with color if you want to.

The equations are either:

or

t is in the range [-1, 1].

or

or

This is code-golf so the shortest code (in each language) in bytes wins. Please provide the output (or link to an online interpreter).

TI-80 BASIC, 45 43 41 39 bytes
LBL 1
RAND4-2->X
RAND4-2
IF (X²+ANS²-1)³<X²ANS³
PT-ON(X,ANS
GOTO 1

This took a while, and my battery is low so I didn't want to keep going.
I tried to use the second equation, but couldn't get it to work it actually turned out to be longer, so I just adapted the other answer I had.
EDIT: I just noticed the 50x50 pixel requirement, unfortunately the screen is only 47 pixels high so this isn't possible.


Code-Golf: Lattice Points inside a Circle The following picture shows the problem:

Write a function that, given an integer as the circle radius, calculates the number of lattice points inside the centered circle (including the boundary).

The image shows:

f[1] = 5  (blue points)
f[2] = 13 (blue + red points)

other values for your checking/debugging:

f[3]    = 29
f[10]   = 317
f[1000] = 3,141,549
f[2000] = 12,566,345

Should have a reasonable performance. Let's say less than a minute for f[1000].

Shortest code wins. Usual Code-Golf rules apply.

Please post the calculation and timing of f[1001] as an example.

J, 21 19 18

+/@,@(>:|@j./~@i:)

Builds complexes from -x-xj to x+xj and takes magnitude.

Edit: With >:

Edit 2: With hook and monadic ~. Runs a few times slower for some reason, but still 10-ish seconds for f(1000).


Ordered list of binary sequences of multiple dimensions Given a positive integer n, output the 2^n binary sequences of length n sorted in the following precise ordering.

Test cases:

0:

0 or 1 (defining this is a matter of debate)

1:

0
1

2:

00
01
10
11

3:

000
001
010
100
011
101
110
111

4:

0000
0001
0010
0100
1000
0011
0101
1001
0110
1010
1100
0111
1011
1101
1110
1111

etc.

Additionally, the pattern of combinatorics is related to Pascal's Triangle.

0:

1 (this is given regardless of the definition given to 2^0)

1:

1
1

2:

1
2
1

3:

1
3
3
1

4:

1
4
6
4
1

etc.

Haskell, 78 bytes

import Data.List
f n=sortOn(\x->sum x:reverse(map(1-)x))$mapM id$[0,1]<$[1..n]

Usage example: f 2 -> [[0,0],[0,1],[1,0],[1,1]].

How it works:

         [0,1]<$[1..n]  -- make n copies of the list [0,1]
     mapM id            -- make all lists where the ith element is from the ith list.
                        -- that gives us all binary sequences
sortOn                  -- sort this list of list
    sum x               -- first by number of ones
      reverse(map(1-)x) -- then by the reversed list with bits flipped


Print a quine that contains the input Task

You will be given a string in the input consisting only of the characters from a to z, i.e. the input will match the regex /^[a-z]*$/.

Your output should be a complete program in the same language, whose source code contains the input, and is a proper quine.

Example

Your program would receive the input abc and output:

...abc...

The above should be a complete program in the same language which takes no input and outputs:

...abc...

i.e. it outputs itself.

Scoring

This is code-golf. Shortest answer in bytes wins.

References

What counts as a proper quine?

Python 3, 57 61 bytes

lambda x:"s='s=%r;print(s%%s)';print(s%s)".replace('s',x+'x')

Takes a basic python 3 quine from here and replaces the variable name with the input.

Note: As pointed out by Hyper Neutrino in comments, this does not work for reserved keywords like for, if, etc.

Appending a character that none of the reserved keywords ends with such as 'x' or any number fixes this. (Ørjan Johansen).


Intersection of Two Lines Given equation of two lines in the format Ax+By=C, determine their intersection point. If they are parallel print 'parallel' without quotes. For input/output format refer sample input/output.

Input
1x+1y=1
1x-1y=1

Output
(1.00,0.00)

Input
0x+1y=0
1x+0y=0

Output
(0.00,0.00)

-1000000 <= A,B,C <= 1000000.
Note their intersection point may not be integer. Print upto two decimal places.
Shortest solution wins.


I don't like change! Input:

Two strings without newlines or whitespaces.

Output:

Both input strings on separate lines, with spaces where necessary† for one of the two strings. And a third line with the characters A, R, M and , representing added, removed, modified, and unchanged.

† We add spaces to either the top or bottom input string (if we have to). The goal of this challenge is to output with the least amount of changes (ARM) possible, also known as the Levenshtein distance.

Example:

Let's say the input strings are ABCDEF and AFBECD, then the output would be this:

A B CDEF
AFBECD
 A A  RR

Here are some other possible invalid outputs as example (and there are a lot more):

ABCDEF
AFBECD
 MMMMM

A BCDEF
AFBECD
 A MMMR

AB CDEF
AFBECD
 MAMMMR

ABC DEF
AFBECD
 MMAMMR

ABC  DEF
AFBECD
 MMAA RR

ABCDEF
AFB ECD
 MMR MA

 AB CDEF   // This doesn't make much sense,
AFBECD     // but it's to show leading spaces are also allowed
AM A  RR

None of these have only four changes however, so only A B CDEF\nAFBECD  \n A A  RR is a valid output for this challenge.

Challenge rules:

You can assume the input strings won't contain any new-lines or spaces.
The two input strings can be of different lengths.
One of the two input strings should remain as is, except for optional leading/trailing spaces.
If your languages doesn't support anything besides ASCII, you can assume the input will only contain printable ASCII characters.
The input and output format are flexible. You can have three separate Strings, a String array, a single String with new-lines, 2D character array, etc.
You are allowed to use something else instead of ARM, but state what you've used (i.e. 123, or abc., etc.)
If more than one valid output is possible with the same amount of changes (ARM), you can choose whether to output one of the possible outputs or all of them.
Leading and trailing spaces are optional:

A B CDEF
AFBECD
 A A  RR

or

"A B CDEF\nAFBECD\n A A  RR"
                 ^
                 Note there are no spaces here

General rules:

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

Test cases:

In: "ABCDEF" & "AFBECD"

Output (4 changes):
A B CDEF
AFBECD
 A A  RR

In: "This_is_an_example_text" & "This_is_a_test_as_example"

Possible output (13 changes):
This_is_an       _example_text
This_is_a_test_as_example
         MAAAAAAA        RRRRR

In: "AaAaABBbBBcCcCc" & "abcABCabcABC"

Possible output (10 changes):
AaAaABBbBBcCcCc
 abcABCab cABC
R MM  MMMR MM R

In: "intf(){longr=java.util.concurrent.ThreadLocalRandom.current().nextLong(10000000000L);returnr>0?r%2:2;}" & "intf(){intr=(int)(Math.random()*10);returnr>0?r%2:2;}"

Possible output (60 changes):
intf(){longr=java.util.concurrent.ThreadLocalRandom.current().nextLong(10000000000L);returnr>0?r%2:2;}
intf(){i ntr=(      i    n      t)(M  ath.r   andom        ()*         10          );returnr>0?r%2:2;}
       MR M  MRRRRRR RRRR RRRRRR MMMRR MMMMRRR     RRRRRRRR  MRRRRRRRRR  RRRRRRRRRR

In: "ABCDEF" & "XABCDF"

Output (2 changes):
 ABCDEF
XABCD F
A    R

In: "abC" & "ABC"

Output (2 changes):
abC
ABC
MM

JavaScript (ES6), 413 ... 343 342 bytes

Saved 5 bytes by tweaking the loop indices, as suggested by @KevinCruijssen

Takes input as 2 strings in currying syntax. Returns an array of 3 strings.

b=>a=>{m=[];x=a.length;y=b.length;for(i=j=0,c=d='';i<=y;c+=R='R')m[i]=[[c,i++]];for(;j++<x;)m[i=0][j]=[d+=A='A',j];for(;i<y;i++)for(j=0;j<x;)[C]=m[[X,S]=m[i][j],[Y,I]=m[i+1][j],[Z,D]=m[i][++j],Q=[Z+R,D+1],i+1][j]=b[i]==a[j-1]?[X+' ',S]:S<I?D<S?Q:[X+'M',S+1]:D<I?Q:[Y+A,I+1];return[(g=s=>C.replace(/./g,c=>c==s?' ':b[i++],i=0))(A),g(R,b=a),C]}

Test cases

let f =

b=>a=>{m=[];x=a.length;y=b.length;for(i=j=0,c=d='';i<=y;c+=R='R')m[i]=[[c,i++]];for(;j++<x;)m[i=0][j]=[d+=A='A',j];for(;i<y;i++)for(j=0;j<x;)[C]=m[[X,S]=m[i][j],[Y,I]=m[i+1][j],[Z,D]=m[i][++j],Q=[Z+R,D+1],i+1][j]=b[i]==a[j-1]?[X+' ',S]:S<I?D<S?Q:[X+'M',S+1]:D<I?Q:[Y+A,I+1];return[(g=s=>C.replace(/./g,c=>c==s?' ':b[i++],i=0))(A),g(R,b=a),C]}

console.log(f('ABCDEF')('AFBECD').join`\n`);
console.log(f('This_is_an       _example_text')('This_is_a_test_as_example').join`\n`);
console.log(f('AaAaABBbBBcCcCc')('abcABCabcABC').join`\n`);
console.log(f("intf(){longr=java.util.concurrent.ThreadLocalRandom.current().nextLong(10000000000L);returnr>0?r%2:2;}")("intf(){intr=(int)(Math.random()*10);returnr>0?r%2:2;}").join`\n`);
console.log(f('ABCDEF')('XABCDF').join`\n`);

Less golfed

b => a => {
  m = []; x = a.length; y = b.length;

  // initialize the leftmost column and the topmost row
  for(i = j = 0, c = d = ''; i <= y; c += R = 'R')
    m[i] = [[c, i++]];
  for(; j++ < x;)
    m[i = 0][j] = [d += A = 'A', j];

  // walk through the Levenshtein matrix
  for(; i < y; i++)
    for(j = 0; j < x;)
      [C] = m[                                // C = current string, once updated
        [X, S] = m[i][j],                     // substitution
        [Y, I] = m[i + 1][j],                 // insertion
        [Z, D] = m[i][++j],                   // deletion
        Q = [Z + R, D + 1],                   // precomputed update for deletion
        i + 1
      ][j] =
        b[i] == a[j - 1] ?
          [X + ' ', S]                        // unchanged character
        :
          S < I ?
            D < S ? Q : [X + 'M', S + 1]      // deletion or substitution
          :
            D < I ? Q : [Y + A, I + 1];       // deletion or insertion

  return [
    // g = helper function to format the output strings by inserting spaces
    (g = s => C.replace(/./g, c => c == s ? ' ' : b[i++], i = 0))(A),
    g(R, b = a),

    // final modification string, picked from the last visited cell
    C
  ]
}

Example

Below is the initial matrix for b = "foo" and a = "ok":

//                     'o'           'k'
[ [ [ '',    0 ], [ 'A',   1 ], [ 'AA',  2 ] ],
  [ [ 'R',   1 ],  (undefined),  (undefined) ],  // 'f'
  [ [ 'RR',  2 ],  (undefined),  (undefined) ],  // 'o'
  [ [ 'RRR', 3 ],  (undefined),  (undefined) ] ] // 'o'

and here is the final matrix after all iterations:

//                     'o'           'k'
[ [ [ '',    0 ], [ 'A',   1 ], [ 'AA',  2 ] ],
  [ [ 'R',   1 ], [ 'M',   1 ], [ 'MA',  2 ] ],  // 'f'
  [ [ 'RR',  2 ], [ 'R ',  1 ], [ 'R A', 2 ] ],  // 'o'
  [ [ 'RRR', 3 ], [ 'RR ', 2 ], [ 'R M', 2 ] ] ] // 'o'

The final modification string along with the Levenshtein distance are stored in the bottom-right cell.


Find the Infinity Words! (Note: This is a spin-off of my previous challenge Find the Swirling Words!)

Definition of Infinity Word:

If you connect with curves all the characters of an Infinity Word on the alphabet (A-Z) you obtain the infinity symbol ∞ like in the diagrams below.
All the even connection must be down, all the odd connections must be up.
You can ignore upper/lowercase or consider/convert all to upper case or all to lower case.
The input words are only characters in the alphabet range of A-Z, no spaces, no punctuation, or symbols.
Each word must be exactly 5 characters. Words > 5 or < 5 are not valid.
If a word has double consecutive characters, the word is not valid, like "FLOOD" or "QUEEN".
All the Infinity Words start and end with the same character.

Here there are some examples:

Task:

Write a full program or function that will take a word from standard input and will output if is an Infinity Word or not. The output can be true/false, 1/0, 1/Null, etc.

Test cases:

Infinity Words:
ALPHA, EAGLE, HARSH, NINON, PINUP, RULER, THEFT, WIDOW

NOT Infinity Words:
CUBIC, ERASE, FLUFF, LABEL, MODEM, RADAR, RIVER, SWISS, TRUST,
KNEES, QUEEN, GROOVE, ONLY, CHARACTER, OFF, IT, ORTHO

Rules:

Shortest code wins.

Optional Task:

Find, as a list, as many Infinity Words as you can in an English dictionary. You can take for example as reference the complete list of English words here.

Jelly, 43 41 40 25 24 23 22 21 14 13 bytes
-7 bytes thanks to fireflame241 (0ị=1ị$->=ṚḢ and use of IIA⁼2,2 to test for the 4 rotations)
-1 Thanks to Kevin Cruijssen (use of previously unavailable nilad Ø2 which yields [2,2])
=ṚḢȧOIṠIIA⁼Ø2

TryItOnline
Or all test cases (plus "RULES")
How?
An infinity word has:

the same first and last letter;
length 5;
no equal letters next to each other;
sum of its four alphabet deltas equal to zero;
sum of its four alphabet deltas signs equal to zero;
two positive alphabet deltas or two negative alphabet deltas in a row.

All but (1) and (equivalently) (4) may be boiled down to a condition that the alphabet delta signs are some rotation of [1,1,-1,-1] (where the sign of 0 is 0)
fireflame241 noted that this is then equivalent to the deltas of the deltas of the alphabet delta signs being in [[2,2],[2,-2],[-2,2],[-2,-2]] which may be tested by the absolute values being equal to [2,2]!
How?
=ṚḢȧOIṠIIA⁼Ø2 - Main link: word
 Ṛ            - reverse word
=             - equals? (vectorises)
  Ḣ           - head (is the first character equal to the last?)
   ȧ          - and
    O         - cast word to ordinals
     I        - increments - the alphabet deltas (or just [] if 1st != last)
      Ṡ       - sign (vectorises)
       I      - increments - deltas of those signs
        I     - increments - deltas of those
         A    - absolute value (vectorises)
           Ø2 - literal [2,2]
          ⁼   - equals? (non-vectorising version)


Generate a Monotonic Function Overview

In this challenge, your task is to randomly generate a monotonic mathematical function between two sets.

Input

Your inputs are two positive integers s and n.

After getting these inputs, your program shall generate a random mathematical function f from the set {0,1,...,s-1}n to {0,1,...,s-1}.
In other words, f is a "rule" that takes in an n-tuple of integers between 0 and s-1, and returns one such integer.
Additionally, f should be monotonic in the following sense.
If A and B are two n-tuples such that A[i] ≥ B[i] holds for every coordinate i, then f(A) ≥ f(B).

The exact distribution of the monotonic functions f doesn't matter, as long as each such function has a positive probability of being generated (assuming a perfect RNG).

Output

Your output shall be an enumeration of the inputs and outputs of f.
It shall contain all n-tuples of integers between 0 and s-1 in some order, each one being followed by the corresponding output of f.
The exact output format is flexible (within reason).

Examples

The inputs s = 3 and n = 2 might produce the output

(0, 0) 0
(0, 1) 1
(0, 2) 2
(1, 0) 0
(1, 1) 1
(1, 2) 2
(2, 0) 1
(2, 1) 1
(2, 2) 2

It contains all the pairs over the set {0, 1, 2} exactly once, and each one is followed by its f-value.
The monotonicity condition is also satisfied.
The tuples are given here in lexicographical order, but this is not necessary.

As another example, s = 2 and n = 4 might produce

(0, 0, 0, 0) 0
(0, 0, 0, 1) 0
(0, 0, 1, 0) 0
(0, 0, 1, 1) 0
(0, 1, 0, 0) 1
(0, 1, 0, 1) 1
(0, 1, 1, 0) 1
(0, 1, 1, 1) 1
(1, 0, 0, 0) 0
(1, 0, 0, 1) 1
(1, 0, 1, 0) 0
(1, 0, 1, 1) 1
(1, 1, 0, 0) 1
(1, 1, 0, 1) 1
(1, 1, 1, 0) 1
(1, 1, 1, 1) 1

The following are all possible outputs for s = 2 and n = 2 (up to reordering the tuples); your program should randomly output one of them:

(0,0) 0
(0,1) 0
(1,0) 0
(1,1) 0
-------
(0,0) 0
(0,1) 0
(1,0) 0
(1,1) 1
-------
(0,0) 0
(0,1) 0
(1,0) 1
(1,1) 1
-------
(0,0) 0
(0,1) 1
(1,0) 0
(1,1) 1
-------
(0,0) 0
(0,1) 1
(1,0) 1
(1,1) 1
-------
(0,0) 1
(0,1) 1
(1,0) 1
(1,1) 1

Rules and Scoring

You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
Code with explanation is preferred.

There are no restrictions on time complexity, but I'll give a bonus of -15 % if your solution is always guaranteed to finish in a certain amount of time (depending on the inputs, and assuming a perfect RNG that runs in constant time).

Pyth, 35 bytes (38 - 15% = 31.45 farther down)

#I!sm><FhMds<MCeMd^JC,mOQK^UQvzK2JB

Demonstration

Input is in the format:

n
s

Output is in the format:

[[value, tuple], [value, tuple], ...]

Simply generates random possibilities and tests them.

Alternative 37 byte version which I believe qualifies for the bonus:

Of!sm><FhMds<MCeMd^T2mC,d^UQvz^UQ^Qvz

Demonstration

This starts by generating all possible monotonic functions, then outputs one at random. It is much slower, and tops out at 2,2.


minigolf - display anything 3d The goal is to write the smallest program in any language which displays any three dimensional output. It might be graphics, it might be ASCII art, but any reasonable person should immediately and unambiguously recognize it as "something 3d".

Opening external files or other resources is not allowed. All output has to be generated by your program.

The shortest code with a score higher than 1 wins.

QBASIC 211 bytes

SCREEN 13
WINDOW(-160,-100)-(159,99)
FOR x=0TO 63
 PALETTE x,x*65793
NEXT
FOR i=16TO-16STEP-.1
 FOR j=16TO-16STEP-.05
  s=SQR(i*i/2+j*j/2)
  PSET(i*10,j*5+17.32*COS(s)),18.2*(COS(s)-SIN(s)*j/s)+31+RND
 NEXT
NEXT

The color for each pixel is chosen by adding the z value on the curve with the partial derivative with respect to y, generating a 'fake' lighting effect. The added random value helps to smooth the borders between regions. Produces something similar to the following: