Encode - Shuffle - Decode Challenge

Your task is to encode an integer as a string of ASCII characters, then successfully decode it after said string has been randomly shuffled.

You will write two programs/functions, which will be referred to as Encoder and Decoder.

Encoder

Input: an integer \$n\$ in the range \$[0,2^{31}-1]\$.
Output: a string \$s\$ of ASCII characters (not necessarily printable).

Decoder

Input: a random permutation \$s'\$ of the string \$s\$.
Output: the integer \$n\$.

Scoring

Let \$A\$ be the maximum length of \$s\$ across all possible values of \$n\$. If the Encoder acts non-deterministically (which is allowed, see below), then the \$A\$ will be the maximum length of \$s\$ that may occur (possibly \$\infty\$).

Let \$L_E\$ be the length of the Encoder in bytes and \$L_D\$ the length of the Decoder in bytes.

Then your score is \$A\cdot(L_E+L_D)\$.

Victory is awarded to the submission the lowest score.

Time limit

There is a somewhat arbitrary time limit of 1 minute on the execution time of both the Encoder and the Decoder for a single testcase (i.e. a single value of \$n\$).

The goal is to avoid solution that find that brute-force the encoding by enumerating all sequences with certain properties. If your solution does something more clever than that, it will most likely fit the time constraint and will be considered valid. Likewise, if it works on TIO for some randomly selected values of \$n\$ it will be considered valid. Otherwise I will test it on my machine, but note that if your solution is pure brute-force it will almost certainly fail.

Rules

The Encoder and the Decoder must be written in the same language.
The Decoder must output the correct integer \$n\$ for every possible permutation \$s'\$ of the string \$s\$ returned by the Encoder.
The Encoder and the Decoder are not allowed to share information in any way (e.g. by means of global variables or files).
The output of the Encoder need not be deterministic (that is, the same input \$n\$ may produce different output strings if the Encoder is run multiple times), but the Decoder must always guess the correct integer \$n\$.
The Encoder and the Decoder may take and return the integer \$n\$ in any convenient way (e.g. if \$n=14\$ it is fine for the input to be 14, "14" or [1,4]).
The Encoder may output the string \$s\$ either by printing it on stdout or by returning a string, a list/array of characters or a list/array of integers in the range \$[0,127]\$; note that the Decoder will receive as input a permutation of \$s\$ as returned by the Encoder, so it should accept the string \$s'\$ in the same format as \$s\$.
Standard loopholes are forbidden.
If possible, explain how your code works and why the score you claim is correct.

Example

  Assume \$n=14\$.

  The Encoder receives 14 as input. It may output "qwerty".
  The Decoder receives a permutation of "qwerty" as input, for instance "tweyqr". It must output 14 (in any convenient format).

The Encoder could have returned [113,119,101,114,116,121] as well, in which case the Decoder would have received (for instance) [116,119,101,121,113,114].

Note that the string returned by the Encoder may also include non-printable ASCII characters (but always in the range [0x00, ..., 0x7F]).

Jelly, (17 bytes + 18 bytes) × length 6 = 210 points

b36µỤỤ+×3µŒ¿b3U+Ṣ

Ṣ:3_J
Ṣ%3Uḅ3œ?Çḅ36

Try it online! (or with extra debug info)

Having had a go at solving this challenge aiming at the stated victory condition, I thought it'd be interesting to go for a hypothetical alternative victory condition: code-golf given a minimum possible maximum length for the output.

Explanation

Encoding

The first step in the encoding is to represent the input as base 36 (b36). 366 = 2176782336 > 2147483647, so there will be at most 6 digits in the result, each of which is in the range 0–35.

Next, we transform this into a representation that contains 6 different digits. There are multiple possible algorithms for this, but the one used here is to add 1 to the smallest digit, 2 to the second-smallest, 3 to the third-smallest, and so on. This means that if two digits were the same, one of them will be arbitrarily considered smaller, and thus they'll become different; and obviously, this algorithm can't cause two different digits to become the same. In order to represent this in Jelly, we use Ụ ("sort indexes by values") to get a list of the indexes in sorted order; Ụ again to invert that, effectively mapping each element of the original to its position in sorted order; and µ…+ to add the original to the new list. The result is a representation of the input number as six different digits in the 1–41 range (minimum 0+1, maximum 35+6).

We then split this into yet another form: a sorted list of digits in the 1–41 range, alongside a number from 1 to 720 that represents which of the 720 possible permutations the digits were in. (The Œ¿ and Ṣ extract the permutation number and sorted list respectively.)

Finally, we convert the number from 1 to 720 into base 3 (b3), reverse it (U), and encode the six base 3 digits and six 1–41 digits via packing them each into a single ASCII character using reverse divmod (the value of the character mod 3 is the base 3 digit, the value divided by 3 is the 1–41 digit). The possible range of results is (1×3)+0=3 at minimum, and (41×3)+2=125 at maximum, fitting within our ASCII range. The packing is done via ×3 and +, together with an additional µ to make sure that every command operates on the right bit of data. (There's a bit of a golfing trick here, in that we do the multiplication by 3 before extracting the permutation; that saves the need to spend a byte on a grouping character.)

Incidentally, the reason to reverse the base 3 number is because it may have fewer digits than the 1–41 number. (It can't have more; the smallest number for which n! > 3n is slightly above 6.) Jelly effectively inserts trailing zeros when adding together two numbers of different lengths, in order to make them match up; trailing zeroes would affect the interpretation of the number, but leading zeroes wouldn't, so the reverse is used to ensure that the extra zeroes end up somewhere that won't mess up our answer.

Decoding

The first step in decoding is to extract the two numbers (the base 3 number and the 1–41 number). We can get their digits easily enough with division (:3) and modulo (%3) respectively, but how to know which order they were in? Well, the 1–41 number had its digits in sorted order, and digits in corresponding positions of the two numbers were stored in the same characters; thus, we can work out which order the 1–41 number's digits were shuffled into (by looking at their relative values) and know that the base-3 number's digits must have been shuffled the same way. In fact, because characters of our ASCII encoding sort the same way as the 1–41 number's digits (these were all distinct and they're more significant than the base 3 number's), we can simply put the characters of the encoding back into order with a sort Ṣ. So both extractions start with Ṣ, followed by %3 or :3 as appropriate.

While the 1–41 number's digits are still in sorted order, we have a very convenient/terse way to go back to the 0–35 digits of base 36; just subtract 1 from the first, 2 from the second, 3 from the third, and so on. In Jelly, we can do that with _J ("subtract index").

Meanwhile, in the other branch of the decode, we reverse the base 3 number's digits back into order (U), and convert it from base 3 back into a permutation index with ḅ3.

We can then combine the two branches with œ?Ç; œ? means "permute given this permutation index", and Ç means "the result of applying the line above", i.e. it's what tells Jelly to run both lines separately on the same input.

What we have now is the digits of the original number, in base 36 (due to the _J), and in the original order (due to the œ?), so we can simply do a ḅ36 to convert back from base 36 into a single integer.

Commentary

The TIO! link above uses 312699167 as the number to encode. This number in base 36 is [5, 6, 6, 8, 7, 35], and thus shows off all aspects of the encoding: the 35 tests the limit of the 0–127 range we have; the duplicate 6s test the resolution of identical digits in the original base 36; and the fact that the digits are almost (but not quite) sorted means that the permutation number is very small, giving it many fewer digits than the base 36 number, and thus showing the need to reverse it before adding it to the original.

It's really convenient how all the constants here fit together. 366 is only just high enough to fit 231, 36 is only just high enough to fit 6!, and (36+6)×3 is only just high enough to fit within the 128 possibilities we have. (The last constraint here is the least tight, because we could use 0-indexing rather than 1-indexing to make use of characters in the 0-2 range. Still, that'd only give enough room to use 37 as the base rather than 36.)


Python code to produce C++14 hex integer literal with ticks tl;dr? See bottom for The Competition

Integer literals

While programming, the 64-bit hexadecimal literal 0x123456789abcdefL is difficult to gauge the size of. I find myself mentally grouping digits from the right by fours to see that it's 15 digits' worth.

Python PEP 515 allows you to express the above literal, inside code, as 0x123_4567_89ab_cdefL. If you prefer binary, then it's even more invaluable: 0b1_0010_0011_0100_0101_0110_0111_1000_1001_1010_1011_1100_1101_1110_1111L

String representations

Python can also convert an integer into strings with spacing characters, as follows:

'{:#_b}'.format(81985529216486895L)
'{:#_x}'.format(81985529216486895L)
'{:,}'.format(81985529216486895L)

The first two produce what's shown above (although without the L suffix), while the last will produce

"81,985,529,216,486,895"

  Although with PEP 515, they would be better expressed as:

'{:#_b}'.format(81_985_529_216_486_895L)
'{:#_x}'.format(81_985_529_216_486_895L)
'{:,}'.format(81_985_529_216_486_895L)

Note, though, the following:

'_' is only legal for binary and hexadecimal strings - and Python will insert them every four characters (from the right);
',' is only legal for decimal strings - and Python will insert them every three characters (from the right);
No other separator characters are allowed.

Enough with the Python syntax lesson; on to C++!

C++14 also allows separators inside an integer literal to allow grouping, much like the above. Only (of course) it's a different character: the tick (single quote '). So the above literals would be:

0b1'0010'0011'0100'0101'0110'0111'1000'1001'1010'1011'1100'1101'1110'1111uL
0x123'4567'89ab'cdefuL
81'985'529'216'486'895uL

Python is often used to machine-generate C/C++ code, because it's so easy to do! But there's no native Python way to generate these new 'tick'-based identifiers - .format() can only use _. So, here's some code that I wrote to do it:

# Hex function with tick marks
def HexTicks(num) :
  # Convert to hex (without leading 0x - yet)
  s = '{:x}'.format(num)
  # Insert tick marks
  for i in range(len(s)-4, 0, -4) :
    s = s[:i] + "'" + s[i:]
  # Return the result
  return "0x" + s + "uLL"

The Competition

   Sorry @ASCII-only !

Write a Python 2.7.3 expression or lambda, smaller than the above function (not including whitespace or comments), that:

Takes any non-negative integer;
Produces the correct hexadecimal string for that integer;
With a leading 0x and trailing uLL;
No leading zeroes as part of the hex number;
With tick marks (') every four digits, counting backwards from the right;
No tick mark straight after the 0x.

ILLEGAL

0x0uLL       # If integer was anything other than zero (2.)
12'3456      # No 0x or uLL (3.)
0x0'1234uLL  # Leading zero (4.)
0x12'345uLL  # Not grouped by four (5.)
0x'1234uLL   # Tick mark before hex number (6.)

Bonuses

A. Can be easily modified to produce capital hex letters - but not the 0x or uLL parts;

  Note that .format() allows '{:_X}' to capitalise the hex characters - but '{:#_X}' will capitalise the 0X too

B. An extra digits parameter that will add leading zeros to that number of digits (not resultant characters; just hex digits) - unless it's already got that many.

  For example: HexTick(0x1234,6) would produce "0x00'1234uLL"

Python 2, 68 65 bytes

-3 bytes for both thanks to tsh

lambda n:"0x"+re.sub("(?!^)(?=(....)+u)","'","%xuLL"%n)
import re

Try it online!

Eligible for both bonuses, 76 73 bytes

lambda x,d:"0x"+re.sub("(?!^)(?=(....)+u)","'","%%0%dxuLL"%d%x)
import re

Try it online!


Python with numpy, 59 bytes

lambda M,N:trace(mat(tri(M+1)[::-1])**N)
from numpy import*

Try it online!

Uses matrix multiplication to count paths. If float precision is an issue, the mat could specify mat(...,int).


Generate Friedman numbers A Friedman number is a number that can be expressed by applying basic mathematical operations(^,/,*,+,-) to all it's digits. The operations need not be applied to each individual digit, but all the digits must be involved. That is, 121= 11^2 --> all digits are involved, but 1 & 1 have been clubbed together to make 11.
Use of parenthesis is allowed, but the trivial solution x= (x) is not a valid solution. Also not valid, x= +x.
Examples

25= 5^2
121= 11^2
343= (3+4)^3
2048 = (8^4)/2+0

Write a program that will take positive two integers and print the number of Friedman numbers in that range(inclusive), and the numbers with the expressions in subsequent lines.
Input -
n m    | n, m integers, n>=0, m>n

Output -
count    | number of Friedman numbers in the given range
fn1 exp1 | Friedman number, expression
fn2 exp2
fn3 exp3
.
.
.

Shortest code posted by Sunday 29th July 00:00 Hrs GMT will be the winner.

Python 2.7 - 380 378 372 371 367 363 357 354 352 348 336 chars

Just a simple brute force search.

from itertools import*
s=lambda x:[x]['1'>x>'0':]+['(%s%s%s)'%f for i in range(1,len(x))for f in product(s(x[:i]),'*/-+^',s(x[i:]))]
def E(e):
 try:return eval(e.replace("^","**"))
 except:0
A={i:e for i in range(input(),input()+1)for x in permutations(`i`)for e in s("".join(x))[x>='1':]if E(e)==i}
print len(A)
for v in A:print v,A[v]

Example run:

1
300
9
128 (2^(8-1))
289 ((9+8)^2)
216 (6^(1+2))
121 (11^2)
153 (3*51)
25 (5^2)
125 (5^(2+1))
126 (6*21)
127 ((2^7)-1)

Explanation:

s(x)
is a function that takes a string containing a sequence of digits and returns all expressions using those digits in that order.

[x]['1'>x>'0':]
evaluates to a list containing x if x is '0' or a sequence of digits not starting with '0'; otherwise, it evaluates to an empty list. Basically this handles the case where I join all the digits together.

['(%s%s%s)'%f for i in range(1,len(x))for f in product(s(x[:i]),'*/-+^',s(x[i:]))]
basically partitions x into two parts (both being of non-zero length), calls s() on each part and joins all the results together with some operator between them, by using product().

E(e)
is basically a safe eval. It returns the value of e if e is valid and None otherwise.

A={i:e for i in range(input(),input()+1)for x in permutations(`i`)for e in s("".join(x))[x>='1':]if E(e)==i}

Basically this code tries all the numbers in the range, permutes their digits and tests each expression s() generates for that permutation, ignoring the first expression if x doesn't start with '0', because if x doesn't start with '0' then the first expression will just be x.

Alternate version - 397 chars

Here is my code if you are required to use fractions:

from fractions import*
from itertools import*
s=lambda x:["Fraction(%s)"%x]['1'>x>'0':]+['(%s%s%s)'%f for i in range(1,len(x))for f in product(s(x[:i]),'*/-+^',s(x[i:]))]
def E(e):
 try:return eval(e.replace("^","**"))
 except:0
A={i:e for i in range(input(),input()+1)for x in permutations(`i`)for e in s("".join(x))[x>='1':]if E(e)==i}
print len(A)
for v in A:print v,A[v].replace("Fraction","")


Generate The SUDSI Sequence The SUDSI sequence (sum, difference, swap, increment) is a curious integer sequence that appears to exhibit rather chaotic behavior. It can be generated as follows:
Let S be an infinite list of the natural numbers: 1 2 3 4 5 6 .... Let Si denote the one-indexed ith element of S. So initially,  S1 is 1, S2 is 2, etc. (there is no S0).
Starting with S1 and S2 ...

Compute their sum: sum = S1 + S2

Compute their absolute difference (the larger one minus the smaller one): diff = |S1 - S2|

Swap the two values in S at the indices of the sum and difference: swap(Ssum, Sdiff)

Increment the indices of S you are working with. So next time you will compute the sum and difference of S2 and S3, and the time after that it will be S3 and S4, etc.

Repeat this process indefinitely.

Here are the first few stages of S as this process is applied. The brackets [] surround the two values that are about to be summed and differenced.
Original S:
[1 2] 3 4 5 6 7 8 9 10 11 12 ...

After S3 (3 = 1 + 2) and S1 (1 = |1 - 2|) are swapped:
3 [2 1] 4 5 6 7 8 9 10 11 12 ...

After S3 and S1 are swapped:
1 2 [3 4] 5 6 7 8 9 10 11 12 ...

After S7 and S1 are swapped:
7 2 3 [4 5] 6 1 8 9 10 11 12 ...

After S9 and S1 are swapped:
9 2 3 4 [5 6] 1 8 7 10 11 12 ...

After S11 and S1 are swapped:
11 2 3 4 5 [6 1] 8 7 10 9 12 ...

After S7 and S5 are swapped:
11 2 3 4 1 6 [5 8] 7 10 9 12 ...

etc.
The SUDSI sequence is defined as the sequence of the first elements in each of these lists. So the first few terms of the SUDSI sequence are 1 3 1 7 9 11 11.
Here are the first 200 terms of the SUDSI sequence (20 per line):
1 3 1 7 9 11 11 11 15 15 19 19 19 19 19 19 19 19 19 19
19 19 19 19 19 19 19 19 57 59 59 59 59 59 59 59 59 59 77 79
81 83 85 87 89 91 91 91 91 91 91 91 91 91 91 91 91 91 115 115
121 123 125 127 127 127 127 127 137 139 141 143 145 147 147 147 147 147 147 147
147 147 147 147 167 167 167 167 167 167 167 167 167 167 167 167 167 167 167 167
167 167 167 167 209 211 211 211 211 211 221 223 223 223 223 223 223 223 223 223
223 223 243 243 243 243 243 243 257 259 261 263 263 263 263 263 263 263 263 263
263 263 263 263 263 263 263 263 263 263 263 263 263 263 263 263 263 263 263 263
263 263 325 327 329 331 331 331 331 331 331 331 331 331 349 351 351 351 351 351
361 363 363 363 363 363 363 363 363 363 363 363 363 363 363 363 363 363 363 363

It is unclear (to me at least) how one might predict future terms. It only feels safe to say that that the terms are always odd, non-decreasing (after the second term), and that some numbers are repeated lots of times.
Challenge
Write a program or function that takes in a positive integer n and prints or returns the nth term of the SUDSI sequence. For example, if n is 1, the output is 1, if n is 2, the output is 3, if n is 200, the output is 363.
Take input in any usual way (stdin/command line/function arg).
The shortest answer in bytes wins.
(That site encodes things in UTF-8, but you may use any darn existing encoding you want.)
Mathy bonus: (potentially eligible for bounty)

Tell me more about the SUDSI sequence. What's the underlying pattern to what numbers are part of it and how many of them there are (and stuff like that)? (I couldn't find SUDSI on OEIS by the way.)

Mathematica, 88 bytes

Last[f@n_:=n;(r=f@1;{f@a,f@b}={f[b=+##],f[a=Abs[#-#2]]};r)&@@f/@{#,#+1}&/@Range@Input[]]

This is a full program, reading the input from a prompt. It's a very direct implementation of the definition, where I'm keeping track of the current sequence in f (whose values f[n] default to n).

Here is a slightly more readable version:

Last[
  f@n_ := n;
  (
    r = f@1;
    {f@a,f@b} = {f[b=+##],f[a=Abs[#-#2]]};
    r
  ) & @@ f /@ {#,#+1} & /@ Range @ Input[]
]

Some analysis

I've plotted the first 2000 elements of the sequence (it doesn't really get more interesting afterwards):

So the sequence is essentially linear with slope 2 and always has a few of those steps. It seems that the steps grow sublinearly (if they aren't even bounded), since they become barely noticeable as you increase the number of points you plot.

We can justify the linear growth quite easily (this is a bit handwavy, but I think it would hold up to a rigorous proof by induction): initially, the maximum affected number of a permutation step at n is n + (n+1) = 2n + 1. Also note that these numbers will always be moved to 1, since |n - (n+1)| = 1. So it's not surprising that we get numbers which are approximately 2n in the sequence. However, we can also note that for steps up to n, Sn+1 is always bounded by n+1, which means that no swapping step can swap two numbers which are both greater than n. Hence, numbers that still need to be processed will be less than or equal to their initial value. Hence, 2n + 1 is also the bound for the sequence itself.

I think finding an argument for the length of the steps will be trickier.


The least weird fact about the US presidency right now The least weird fact about the US presidency right now is that there have been two unrelated presidents whose last names start with T-R-U-M.

That made me think, how many US presidents share other combinations of characters? There are obviously two presidents that share the characters "BUSH", and "ROOSEVELT". But did you know there are four presidents who share the characters "BU" (Buchanan, Buren, Bush and Bush), three presidents who share "CL" (Cleveland, Cleveland and Clinton), but only one president whose name starts with an "E" (Eisenhower).

Challenge:

Take a non-empty string as input, and output how many presidents have names starting at those letters. You may assume that the string will match at least one president.

That means, you may get inputs such as "J" (Jackson, Jefferson, Johnson and Johnson), "TA" (Taft and Taylor) and "Nixon" (Nixon). You will not get inputs such as "Z", "RANT" and "RUMP".

Rules

The input is on any convenient format, with optional upper or lower case.
The output should be an integer in the range 1 ... 5.
Shortest code in bytes in each language wins

Test cases

There are three strings that should return 5 (C, H, T), two strings that should return 4 (BU, J), five strings that should return 3 (A, CL, HAR, M, R). There are many strings that should return 2. Where there are parentheses, it means both AD, ADA, ADAM and ADAMS should all return 2, as well as TR, TRU and TRUM. You will not get "TRUT" as input, since that doesn't match a president.

5: C, H, T
4: BU, J,
3: A, CL, HAR, M, R
2: AD (ADAMS), BUS (BUSH), CLE (CLEVELAND), F, G, HARR (HARRISON), JO (JOHNSON), P, RO (ROOSEVELT), TA, TR (TRUM), W
1: Every other valid string

Alphabetical list of surnames

Adams, Adams, Arthur, Buchanan, Buren, Bush, Bush, Carter, Cleveland, Cleveland, Clinton, Coolidge, Eisenhower, Fillmore, Ford, Garfield, Grant, Harding, Harrison, Harrison, Hayes, Hoover, Jackson, Jefferson, Johnson, Johnson, Kennedy, Lincoln, Madison, McKinley, Monroe, Nixon, Obama, Pierce, Polk, Reagan, Roosevelt, Roosevelt, Taft, Taylor, Truman, Trump, Tyler, Washington, Wilson
-------- Same list (obviously) -----------
'Adams', 'Adams', 'Arthur', 'Buchanan', 'Buren', 'Bush', 'Bush', 'Carter', 'Cleveland', 'Cleveland', 'Clinton', 'Coolidge', 'Eisenhower', 'Fillmore', 'Ford', 'Garfield', 'Grant', 'Harding', 'Harrison', 'Harrison', 'Hayes', 'Hoover', 'Jackson', 'Jefferson', 'Johnson', 'Johnson', 'Kennedy', 'Lincoln', 'Madison', 'McKinley', 'Monroe', 'Nixon', 'Obama', 'Pierce', 'Polk', 'Reagan', 'Roosevelt', 'Roosevelt', 'Taft', 'Taylor', 'Truman', 'Trump', 'Tyler', 'Washington', 'Wilson'

Python 2, 179 175 173 bytes

lambda s:sum(any(s==X[:len(s)]for X in x.split())for x in[A,B,'A CL HAR M R '+B,'ADAMS BUSH CLEVELAND F G HARRISON JOHNSON P ROOSEVELT TA TRUM W M',s])
A='C H T';B='BU J '+A

Try it online!


Prime numbers in large number Given a large number (in base 10), such as 1234567891011121314151617, find prime "subnumbers" in it.
A prime "subnumber" is a consecutive sequence of digits (taken from the input), which represents a prime number (in base 10).

Input:
A number (either a string, a file, or whatever you like).
Output:
All prime subnumbers separated somehow (either in a list, a file, comma-separated strings...)
If the result is empty, you can take any convention you like (hardcoded string, empty string, gibberish, but program should not crash.
Example
1234 -> 2, 3, 23
6542 -> 5, 2
14 -> [.. empty output]

This is code-golf. The shortest program wins!
[edit] : additional rule, program must be explained! Not everybody is fluent in Jelly :)

05AB1E (legacy), 3 bytes

Œʒp

Try it online!

Substrings of the input that are prime.


Find an array that fits a set of sums Consider an array A of length n. The array contains only positive integers.  For example A = (1,1,2,2).  Let us define f(A) as the set of sums of all the non-empty contiguous subarrays of A. In this case f(A) = {1,2,3,4,5,6}.  The steps to produce f(A)  are as follows:

The subarrays of A are (1), (1), (2), (2), (1,1), (1,2), (2,2), (1,1,2), (1,2,2), (1,1,2,2). Their respective sums are 1,1,2,2,2,3,4,4,5,6. The set you get from this list is therefore {1,2,3,4,5,6}.

Task

Given a set of sums S given in sorted order containing only positive integers and an array length n, your task is to output at least one array X such that f(X) = S.

For example, if S = {1,2,3,5,6} and n = 3 then a valid output is X = (1,2,3).

If there is no such array X your code should output any constant value.

Examples

Input: n=4, S = (1, 3, 4, 5, 6, 8, 9, 10, 13), possible output: X = (3, 5, 1, 4)

Input: n=6, S = (2, 3, 4, 5, 7, 8, 9, 10, 12, 14, 17, 22), possible output: X = (5, 3, 2, 2, 5, 5)

Input: n=6, S = (2, 4, 6, 8, 10, 12, 16), possible output: X = (4, 2, 2, 2, 2, 4)

Input: n=6, S = (1, 2, 3, 4, 6, 7, 8, 10, 14), possible output: X = (4, 2, 1, 1, 2, 4)

Input: n=10, S = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 23, 24, 25), possible output: X = (1, 1, 3, 1, 2, 1, 2, 5, 4, 5).

Input: n=15, S = (1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 30, 31), possible output: X = (1, 2, 1, 3, 3, 1, 3, 3, 1, 3, 3, 1, 2, 1, 3).

Input and output format

Your code can take input and give output in any easily human read format you find convenient. However, please show the output of testing it on the examples in the question.

Running time

You must be able to run the code to completion for all the examples in the question. It should in principle be correct for n up to 15 but you do not need to prove it would be fast enough for all inputs.

Husk, 20 bytes

ḟȯ⁰¦ṁ∫ṫ!¡Sof~Λ€∫×:¹g

Try it online!

Returns one solution, or an empty list if it doesn't exist.
The last test case (n=15) finishes in 3.8 seconds on TIO.

Explanation

The program has two parts.
In the first part (¡ and to the right of it), we construct an infinite list whose kth element is a list containing all length-k lists whose slice sums are in S.
We do this inductively, starting from the 1-element slices of S, and at each step prepending each element of S to each list, and keeping those whose prefix sums are in S.
In the second part (! and to the left of it), we take the nth element of the list, which contains length-n lists.
Of these, we select the first one whose slice sums actually contain every element of S.

In the code, let's first replace o and ȯ (which compose two and three functions into one) by parentheses for clarity.

¡S(f~Λ€∫)×:¹g  First part. Input is a list, say S=[1,2,3]
            g  Group equal adjacent elements: [[1],[2],[3]]
¡              Iterate function:
                Argument is a list of lists, say [[1,1],[1,2],[2,1]]
         ×      Mix (combine two lists in all possible ways)
          :     by prepending
           ¹    with the list S: [[1,1,1],[1,1,2],[2,1,1],[1,2,1],[2,1,2],[3,1,1],[2,2,1],[3,1,2],[3,2,1]]
   f            Filter by condition:
        ∫        Cumulative sums: [[1,2,3],[1,2,4],[2,3,4],[1,3,4],[2,3,5],[3,4,5],[2,4,5],[3,4,6],[3,5,6]]
     ~Λ          All of the numbers
 S     €         are elements of S: [[1,1,1]]
                 Only this list remains, since the other cumulative sums contain numbers not from S.
               Result of iteration: [[[1],[2],[3]],[[1,1],[1,2],[2,1]],[[1,1,1]],[],[],[]...

ḟ(⁰¦ṁ∫ṫ)!      Second part. Implicit input, say n=2.
        !      Take nth element of above list: [[1,1],[1,2],[2,1]]
ḟ              Find first element that satisfies this:
                Argument is a list, say [1,2]
      ṫ         Tails: [[1,2],[2]]
    ṁ           Map and concatenate
     ∫          cumulative sums: [1,3,2]
 ȯ ¦            Does it contain all elements of
  ⁰             S? Yes.
               Result is [1,2], print implicitly.

There are some parts that need more explanation.
In this program, the superscripts ⁰¹ both refer to the first argument S.
However, if α is a function, then α¹ means "apply α to S", while ⁰α means "plug S to the second argument of α".
The function ¦ checks whether its first argument contains all elements of the second (counting multiplicities), so S should be its second argument.

In the first part, the function that ¡ uses can be interpreted as S(f~Λ€∫)(×:)¹.
The combinator S behaves like Sαβγ -> (αγ)(βγ), which means that we can simplify it to (f~Λ€∫¹)(×:¹).
The second part, ×:¹, is "mix with S by prepending", and its result is passed to the first part.
The first part, f~Λ€∫¹, works like this.
The function f filters a list by a condition, which in this case is ~Λ€∫¹.
It receives a list of lists L, so we have ~Λ€∫¹L.
The combinator ~ behaves like ~αβγδε -> α(βδ)(γε): the first argument is passed to β, the second to γ, and the results are combined with α.
This means that we have Λ(€¹)(∫L).
The last part ∫L is just the cumulative sums of L, €¹ is a function that checks membership in S, and Λ takes a condition (here €¹) and a list (here ∫L), and checks that all elements satisfy it.
Put simply, we filter the results of the mixing by whether their cumulative sums are all in S.


Square root multiples This code-challenge is based on OEIS sequence A261865.

\$A261865(n)\$ is the least integer \$k\$ such that some multiple of \$\sqrt{k}\$ is in the interval \$(n,n+1)\$.

The goal of this challenge is to write a program that can find a value of \$n\$ that makes \$A261865(n)\$ as large as you can. A brute-force program can probably do okay, but there are other methods that you might use to do even better.
Example
For example, \$A261865(3) = 3\$ because

there is no multiple of \$\sqrt{1}\$ in \$(3,4)\$ (since \$3 \sqrt{1} \leq 3\$ and \$4 \sqrt{1} \geq 4\$);
there is no multiple of \$\sqrt{2}\$ in \$(3,4)\$ (since \$2 \sqrt{2} \leq 3\$ and \$3 \sqrt{2} \geq 4\$);
and there is a multiple of \$\sqrt{3}\$ in \$(3,4)\$, namely \$2\sqrt{3} \approx 3.464\$.

Analysis
Large values in this sequence are rare!

70.7% of the values are \$2\$s,
16.9% of the values are \$3\$s,
5.5% of the values are \$5\$s,
2.8% of the values are \$6\$s,
1.5% of the values are \$7\$s,
0.8% of the values are \$10\$s, and
1.7% of the values are \$\geq 11\$.

Challenge
The goal of this code-challenge is to write a program that finds a value of \$n\$ that makes \$A261865(n)\$ as large as possible. Your program should run for no more than one minute and should output a number \$n\$. Your score is given by \$A261865(n)\$. In the case of a close call, I will run all entries on my 2017 MacBook Pro with 8GB of RAM to determine the winner.
For example, you program might output \$A261865(257240414)=227\$ for a score of 227. If two entries get the same score, whichever does it faster on my machine is the winner.
(Your program should not rely on information about pre-computed values, unless you can justify that information with a heuristic or a proof.)

JavaScript (Node.js), score \$335\$
Pretty straight-forward algorithm. I made it multithreaded to be a bit faster.
// Run with: node ./square-root-multiples.js

const findMaxK = (fromN, toN) => {
  let maxK = 0;
  let maxN = 0;
  for (let n = fromN; n < toN; n++) {
    for (let k = 2, s = n * n; k < s; k++) {
      const r = Math.sqrt(k);
      const x = r * Math.ceil(n / r);
      if (x > n && x < n + 1) {
        if (k > maxK) {
          maxK = k;
          maxN = n;
        }
        break;
      }
    }
  }
  return { n: maxN, k: maxK };
};

const BATCH_SIZE = 10000000;

const cluster = require("cluster");
if (cluster.isMaster) {
  const start = Date.now();
  let nextBatch = 0;
  let maxK = 0;

  const numCpus = require("os").cpus().length;
  for (let i = 0; i < numCpus; i++) {
    const worker = cluster.fork();
    worker.on("message", (msg) => {
      if (msg.k > maxK) {
        maxK = msg.k;
        console.log(
          `found A261865(${msg.n}) = ${msg.k} in ${
            (Date.now() - start) / 1000
          }s`
        );
      }
      worker.send({ n: nextBatch, maxK });
      nextBatch += BATCH_SIZE;
    });
    worker.send({ n: nextBatch });
    nextBatch += BATCH_SIZE;
  }
} else {
  process.on("message", (msg) => {
    process.send(findMaxK(msg.n, msg.n + BATCH_SIZE));
  });
}

Output on my 2019 MacBook Pro:
found A261865(12779527) = 134 in 0.299s
found A261865(2345213) = 187 in 0.308s
found A261865(63856063) = 193 in 0.33s
found A261865(222125822) = 210 in 0.681s
found A261865(237941698) = 217 in 0.687s
found A261865(257240414) = 227 in 0.804s
found A261865(1217775885) = 230 in 2.704s
found A261865(1205703469) = 267 in 2.704s
found A261865(1558293414) = 299 in 3.306s
found A261865(4641799364) = 303 in 13.002s
found A261865(6600656102) = 323 in 20.045s
found A261865(11145613453) = 335 in 36.774s
found A261865(20641456345) = 354 in 73.047s

The highest K my machine found within 60s was A261865(11145613453) = 335.


Are these lists equal? As you may very well know python has lists.  As you might not know these lists can contain themselves.

a = []
a.append(a)

Python 2

Python 3

These are cool and there are lots of interesting things you can do with them, however you cannot compare them.

a = []
a.append(a)
b = []
b.append(b)
a == b

Python 2

Python 3

Task

Your job is to write a function in Python (or any language that can handle python objects directly) that will take two lists that may contain themselves and compare them.

Two lists are equal if they are the same length and there does not exist sequence of numbers such that indexing both of the lists by that sequence results in two objects that are not equal under this definition of equal.  All non-list objects contained in a list will be python integers for simplicity and should be compared with python's builtin equality for integers.

Your program should not rely on the recursion depth of python to determine if a list is infinitely deep.  That is:

def isInfinite(a,b):
 try:
  a==b
  return False
 except RunTimeError:
  return True

Is not a valid way of determining if two lists are self referential.

Testcases

Assumes you define a function equal

a = []
a.append(a)
b = []
b.append(b)
print(equal(a,b))

True

a = []
b = []
a.append(b)
b.append(a)
print(equal(a,b))

True

a = []
b = []
a.append(1)
a.append(b)
b.append(1)
b.append(a)
print(equal(a,b))

True

a = []
a.append(a)
b = [a]
print(equal(a,b))

True

a = []
b = []
c = []
a.append(b)
b.append(c)
c.append(a)
equal(a,b)

True

a=[1,[2]]
b=[1,[2,[1]]]
a[1].append(a)
b[1][1].append(b[1])

True

a = []
a.append(a)
b = [1]
b.append(a)
c = [1]
c.append([c])
print(equal(b,c))

False

a = []
b = []
a.append(1)
a.append(b)
b.append(a)
b.append(1)
print(equal(a,b))

False

a = []
b = []
a.append(a)
b.append(b)
b.append(b)
print f(a,b)

False

Python 2, 94 bytes

g=lambda c,*p:lambda a,b:c in p or all(map(g((id(a),id(b)),c,*p),a,b))if a>[]<b else a==b
g(0)

Try it online!

An improvement on isaacg's very clever solution of storing the id pairs of lists being processed and declaring them equal if the same comparison comes up on a lower level.

The recursive step all(map(...,a,b)) says that a and b are equal if all corresponding pair of elements in them are equal. This works nicely to reject unequal-length because map pads the shortest list with None, unlike zip which truncates. Since none of the actual lists contain None, these padded lists will always be rejected.


Cops and Robbers bowling (Cops) Cops' Thread
In this challenge, your goal is to write a function that accepts a integer N, and that function will return the first N primes.  However, you must do this in the most characters possible.

You may use any method you wish to produce the primes.
You are not allowed to modify your code after posting.
Only printable ASCII characters are allowed.
A character cannot appear in your code more than 100 times.

However, after posting your answer, the robbers will have the opportunity to crack your code by posting a modified version of your code.  Your code is considered cracked if:

The modified code has a maximum levenshtein-distance of 10 from yours, and has fewer characters.
The function, given the same valid input, will produce the same output in the same language of the same version
The robber posted the modified version within 168 hours (1 week) of your post.

If a robber failed to crack your code within 168 hours, your code is considered safe.  The winner of this challenge is the cop with the longest safe code.
The title of your thread should contain the language, the number of characters, and the current status (Open, Cracked, Safe) of your code.
The accompanying robbers thread can be found here
Relevant tools

Frequency counter
Character counter
Levenshtein distance

You can also use this snippet to calculate the Levenshtein distance:

var f=document.getElementById("f"),g=document.getElementById("s"); function h(){var a=f.value,e=g.value;if(128<a.length)a="First program is too long!";else if(128<e.length)a="Second program is too long!";else{if(0===a.length)a=e.length;else if(0===e.length)a=a.length;else{var d=[],b;for(b=0;b<=e.length;b++)d[b]=[b];var c;for(c=0;c<=a.length;c++)d[0][c]=c;for(b=1;b<=e.length;b++)for(c=1;c<=a.length;c++)d[b][c]=e.charAt(b-1)===a.charAt(c-1)?d[b-1][c-1]:Math.min(d[b-1][c-1]+1,Math.min(d[b][c-1]+1,d[b-1][c]+ 1));a=d[e.length][a.length]}a="Distance = "+a+""}document.getElementById("d").innerHTML=a}f.onkeyup=h;g.onkeyup=h;

First program

<textarea id=f rows=7 cols=80 style="width:100%"></textarea>

Second program

<textarea id=s rows=7 cols=80 style="width:100%"></textarea>

Credits to Doorknob!


Images with all colors Similar to the images on allrgb.com, make images where each pixel is a unique color (no color is used twice and no color is missing).

Give a program that generates such an image, along with a screenshot or file of the output (upload as PNG).

Create the image purely algorithmically.
Image must be 256×128 (or grid that can be screenshot and saved at 256×128)
Use all 15-bit colors*
No external input allowed (also no web queries, URLs or databases)
No embedded images allowed (source code which is an image is fine, e.g. Piet)
Dithering is allowed
This is not a short code contest, although it might win you votes.
If you're really up for a challenge, do 512×512, 2048×1024 or 4096×4096 (in increments of 3 bits).

Scoring is by vote. Vote for the most beautiful images made by the most elegant code and/or interesting algorithm.

Two-step algorithms, where you first generate a nice image and then fit all pixels to one of the available colors, are of course allowed, but won't win you elegance points.

* 15-bit colors are the 32768 colors that can be made by mixing 32 reds, 32 greens, and 32 blues, all in equidistant steps and equal ranges. Example: in 24 bits images (8 bit per channel), the range per channel is 0..255 (or 0..224), so divide it up into 32 equally spaced shades.

To be very clear, the array of image pixels should be a permutation, because all possible images have the same colors, just at different pixels locations. I'll give a trivial permutation here, which isn't beautiful at all:

Java 7

import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;

public class FifteenBitColors {
    public static void main(String[] args) {
        BufferedImage img = new BufferedImage(256, 128, BufferedImage.TYPE_INT_RGB);

        // Generate algorithmically.
        for (int i = 0; i < 32768; i++) {
            int x = i & 255;
            int y = i / 256;
            int r = i << 3 & 0xF8;
            int g = i >> 2 & 0xF8;
            int b = i >> 7 & 0xF8;
            img.setRGB(x, y, (r << 8 | g) << 8 | b);
        }

        // Save.
        try (OutputStream out = new BufferedOutputStream(new FileOutputStream("RGB15.png"))) {
            ImageIO.write(img, "png", out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Winner

Because the 7 days are over, I'm declaring a winner

However, by no means, think this is over. I, and all readers, always welcome more awesome designs. Don't stop creating.

Winner: fejesjoco with 231 votes

C#

I put a random pixel in the middle, and then start putting random pixels in a neighborhood that most resembles them. Two modes are supported: with minimum selection, only one neighboring pixel is considered at a time; with average selection, all (1..8) are averaged. Minimum selection is somewhat noisy, average selection is of course more blurred, but both look like paintings actually. After some editing, here is the current, somewhat optimized version (it even uses parallel processing!):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Drawing.Imaging;
using System.Diagnostics;
using System.IO;

class Program
{
    // algorithm settings, feel free to mess with it
    const bool AVERAGE = false;
    const int NUMCOLORS = 32;
    const int WIDTH = 256;
    const int HEIGHT = 128;
    const int STARTX = 128;
    const int STARTY = 64;

    // represent a coordinate
    struct XY
    {
        public int x, y;
        public XY(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
        public override int GetHashCode()
        {
            return x ^ y;
        }
        public override bool Equals(object obj)
        {
            var that = (XY)obj;
            return this.x == that.x && this.y == that.y;
        }
    }

    // gets the difference between two colors
    static int coldiff(Color c1, Color c2)
    {
        var r = c1.R - c2.R;
        var g = c1.G - c2.G;
        var b = c1.B - c2.B;
        return r * r + g * g + b * b;
    }

    // gets the neighbors (3..8) of the given coordinate
    static List<XY> getneighbors(XY xy)
    {
        var ret = new List<XY>(8);
        for (var dy = -1; dy <= 1; dy++)
        {
            if (xy.y + dy == -1 || xy.y + dy == HEIGHT)
                continue;
            for (var dx = -1; dx <= 1; dx++)
            {
                if (xy.x + dx == -1 || xy.x + dx == WIDTH)
                    continue;
                ret.Add(new XY(xy.x + dx, xy.y + dy));
            }
        }
        return ret;
    }

    // calculates how well a color fits at the given coordinates
    static int calcdiff(Color[,] pixels, XY xy, Color c)
    {
        // get the diffs for each neighbor separately
        var diffs = new List<int>(8);
        foreach (var nxy in getneighbors(xy))
        {
            var nc = pixels[nxy.y, nxy.x];
            if (!nc.IsEmpty)
                diffs.Add(coldiff(nc, c));
        }

        // average or minimum selection
        if (AVERAGE)
            return (int)diffs.Average();
        else
            return diffs.Min();
    }

    static void Main(string[] args)
    {
        // create every color once and randomize the order
        var colors = new List<Color>();
        for (var r = 0; r < NUMCOLORS; r++)
            for (var g = 0; g < NUMCOLORS; g++)
                for (var b = 0; b < NUMCOLORS; b++)
                    colors.Add(Color.FromArgb(r * 255 / (NUMCOLORS - 1), g * 255 / (NUMCOLORS - 1), b * 255 / (NUMCOLORS - 1)));
        var rnd = new Random();
        colors.Sort(new Comparison<Color>((c1, c2) => rnd.Next(3) - 1));

        // temporary place where we work (faster than all that many GetPixel calls)
        var pixels = new Color[HEIGHT, WIDTH];
        Trace.Assert(pixels.Length == colors.Count);

        // constantly changing list of available coordinates (empty pixels which have non-empty neighbors)
        var available = new HashSet<XY>();

        // calculate the checkpoints in advance
        var checkpoints = Enumerable.Range(1, 10).ToDictionary(i => i * colors.Count / 10 - 1, i => i - 1);

        // loop through all colors that we want to place
        for (var i = 0; i < colors.Count; i++)
        {
            if (i % 256 == 0)
                Console.WriteLine("{0:P}, queue size {1}", (double)i / WIDTH / HEIGHT, available.Count);

            XY bestxy;
            if (available.Count == 0)
            {
                // use the starting point
                bestxy = new XY(STARTX, STARTY);
            }
            else
            {
                // find the best place from the list of available coordinates
                // uses parallel processing, this is the most expensive step
                bestxy = available.AsParallel().OrderBy(xy => calcdiff(pixels, xy, colors[i])).First();
            }

            // put the pixel where it belongs
            Trace.Assert(pixels[bestxy.y, bestxy.x].IsEmpty);
            pixels[bestxy.y, bestxy.x] = colors[i];

            // adjust the available list
            available.Remove(bestxy);
            foreach (var nxy in getneighbors(bestxy))
                if (pixels[nxy.y, nxy.x].IsEmpty)
                    available.Add(nxy);

            // save a checkpoint
            int chkidx;
            if (checkpoints.TryGetValue(i, out chkidx))
            {
                var img = new Bitmap(WIDTH, HEIGHT, PixelFormat.Format24bppRgb);
                for (var y = 0; y < HEIGHT; y++)
                {
                    for (var x = 0; x < WIDTH; x++)
                    {
                        img.SetPixel(x, y, pixels[y, x]);
                    }
                }
                img.Save("result" + chkidx + ".png");
            }
        }

        Trace.Assert(available.Count == 0);
    }
}

256x128 pixels, starting in the middle, minimum selection:

256x128 pixels, starting in the top left corner, minimum selection:

256x128 pixels, starting in the middle, average selection:

Here are two 10-frame animgifs that show how minimum and average selection works (kudos to the gif format for being able to display it with 256 colors only):

The mimimum selection mode grows with a small wavefront, like a blob, filling all pixels as it goes. In the average mode, however, when two different colored branches start growing next to each other, there will be a small black gap because nothing will be close enough to two different colors. Because of those gaps, the wavefront will be an order of magnitude larger, therefore the algorithm will be so much slower. But it's nice because it looks like a growing coral. If I would drop the average mode, it could be made a bit faster because each new color is compared to each existing pixel about 2-3 times. I see no other ways to optimize it, I think it's good enough as it is.

And the big attraction, here's an 512x512 pixels rendering, middle start, minimum selection:

I just can't stop playing with this! In the above code, the colors are sorted randomly. If we don't sort at all, or sort by hue ((c1, c2) => c1.GetHue().CompareTo(c2.GetHue())), we get these, respectively (both middle start and minimum selection):

Another combination, where the coral form is kept until the end: hue ordered with average selection, with a 30-frame animgif:

UPDATE: IT IS READY!!!

You wanted hi-res, I wanted hi-res, you were impatient, I barely slept. Now I'm excited to announce that it's finally ready, production quality. And I am releasing it with a big bang, an awesome 1080p YouTube video! Click here for the video, let's make it viral to promote the geek style. I'm also posting stuff on my blog at http://joco.name/, there will be a technical post about all the interesting details, the optimizations, how I made the video, etc. And finally, I am sharing the source code under GPL. It's become huge so a proper hosting is the best place for this, I will not edit the above part of my answer anymore. Be sure to compile in release mode! The program scales well to many CPU cores. A 4Kx4K render requires about 2-3 GB RAM.

I can now render huge images in 5-10 hours. I already have some 4Kx4K renders, I will post them later. The program has advanced a lot, there have been countless optimizations. I also made it user friendly so that anyone can easily use it, it has a nice command line. The program is also deterministically random, which means, you can use a random seed and it will generate the same image every time.

Here are some big renders.

My favorite 512:

(source: joco.name)

The 2048's which appear in my video:

(source: joco.name)

(source: joco.name)

(source: joco.name)

(source: joco.name)

The first 4096 renders (TODO: they are being uploaded, and my website cannot handle the big traffic, so they are temporarily relocated):

(source: joco.name)

(source: joco.name)

(source: joco.name)

(source: joco.name)


Find the best move in a game of Tetris I like Tetris a lot, but I'm not very good at it. Just once I'd like to see that spaceship take off in front of my own eyes! And since computers are oh-so great at everything, the only possible solution is to make a program to play it for me... except you're going to do that bit for me!

Given a tetromino (shape made of four squares) and a map of the playing field, you are to place the tetromino such that it scores the greatest number of lines (makes the greatest number of rows completely full of blocks) and creates the least number of new holes (an empty space that cannot "see" the top of the playing field1).

Input

The input will contain a character on a single line that represents the dropping tetromino, followed by a 10*18 grid2 of spaces () and plus signs (+).

The character represents any of the seven base tetrominoes found in Tetris. All of the pieces can be rotated by 90 degrees, but not flipped. All the tetrominoes and their rotations are as follows:

         #
S =  ##  ##
    ##    #

          #
Z = ##   ##
     ##  #

    #   ###  ##
L = #   #     #    #
    ##        #  ###

     #  ###  ##
J =  #    #  #     #
    ##       #   ###

          #   #   #
T = ###  ##  ###  ##
     #    #       #

O = ##
    ##

    #
I = #  ####
    #
    #

The grid represents the playing field of Tetris, with + being previously-placed blocks. So, an example input might be the following:

I

+       ++
+    +++++
++ +++++++
++ +++++++
++ +++++++
++ +++++++
++++++ +++

Output

Your output will be identical to the input, but with the tetromino in the ideal position. The tetromino should be represented with # to differentiate them from the pre-placed blocks. In addition to this, you are also to output how many lines/holes your placement creates in the form xL yH on a new line.

The output for the example given above would be the following3:

I

+       ++
+    +++++
++#+++++++
++#+++++++
++#+++++++
++#+++++++
++++++ +++
4L 0H

You are to output only the best result(s); in the case of two or more cases giving the same score, you are to output all of them (separated by a blank line). The best results are to be determined by sorting by the number of lines scored (descending) first, then the number of new holes created (ascending). So, 1L 1H is a better score than 0L 0H.

I will work on creating a list of various inputs and expected output(s) that you can test your program against. Watch this space.

Rules and Disambiguation

This is code-golf, so shortest correct implementation wins.
Input/output may be in any medium that suits your target language (e.g. file, stdin/stdout, text area).
If your target language does not support multiple line input (or it is inconvenient to do so), you may instead delimit each line of the input with commas (,).
You may omit the output of any blank lines in the grid.
Remember that the tetromino falls from above - you may not place the piece "underground". You may therefore assume that all possible placements of the piece will be at "surface-level" (i.e. there are no blocks between the piece and the top of the board).
Assume that there will never be a situation in which you are forced into a game over (the placed tetromino touches the top-center of the field).
Solutions that are identical in output must be omitted (e.g. there are 3 solutions outputs if you naively rotate the O piece).

1 I'm aware that this will create some false positives, but it's a simplification.

2 This is the grid size used in the Game Boy version.

3 Yes, 0H is correct. Check again, I said new holes ;^)


Longest domino chain Challenge description

Dominoes is a game played with tiles with two values on it - one on the left, one on the right, for example [2|4] or [4|5]. Two tiles can be joined together if they contain a common value. The two tiles above can be joined like this:

[2|4][4|5]

We'll call a sequence of n joined tiles a chain of length n. Of course, tiles can be rotated, so tiles [1|2], [1|3] and [5|3] can be rearranged into a chain [2|1][1|3][3|5] of length 3.

Given a list of pairs of integers, determine the length of the longest chain that can be formed using these tiles. If the list is empty, the correct answer is 0 (note that you can always form a chain of length 1 from a non-empty list of tiles).

Sample input / output

[(0, -1), (1, -1), (0, 3), (3, 0), (3, 1), (-2, -1), (0, -1), (2, -2), (-1, 2), (3, -3)] -> 10
([-1|0][0|-1][-1|2][2|-2][-2|-1][-1|1][1|3][3|0][0|3][3|-3])

[(17, -7), (4, -9), (12, -3), (-17, -17), (14, -10), (-6, 17), (-16, 5), (-3, -16), (-16, 19), (12, -8)] -> 4
([5|-16][-16|-3][-3|12][12|-8])

[(1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1)] -> 7
([1|1][1|1][1|1][1|1][1|1][1|1][1|1])

[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, 11)] -> 1
(any chain of length 1)

[] -> 0
(no chain can be formed)

Brachylog, 23 bytes

s:papcb~k~c:{#=l2}al|,0

Try it online!

Explanation

s:papcb~k~c:{#=l2}al|,0
s                         Check subsets of the input (longest first).
 :pa                      Check all permutations inside the input's elements
    p                     and all permutations /of/ the input's elements.
     c                    Flatten the result;
      b                   delete the first element;
       ~k                 find something that can be appended to the end so that
         ~c               the result can be unflattened into
           :{    }a       a list whose elements each have the property:
             #=             all the elements are equal
               l2           and the list has two elements.
                   l      If you can, return that list's length.
                    |,0   If all else fails, return 0.

So in other words, for input like [[1:2]:[1:3]:[5:3]], we try to rearrange it into a valid chain [[2:1]:[1:3]:[3:5]], then flatten/behead/unkknife to produce [1:1:3:3:5:_] (where _ represents an unknown). The combination of ~c and :{…l2}a effectively splits this into groups of 2 elements, and we ensure that all the groups are equal. As we flattened (doubling the length), removed one element from the start and added one at the end (no change), and grouped into pairs (halving the length), this will have the same length as the original chain of dominoes.

The "behead" instruction will fail if there are no dominoes in the input (actually, IIRC the :pa will also fail; a dislikes empty lists), so we need a special case for 0. (One big reason we have the asymmetry between b and ~k is so that we don't also need a special case for 1.)


Program my microwave oven I'm very lazy so I try to always program my microwave with the fewest possible button presses.  My microwave has the following buttons:

A "minute plus" button which may only be pressed first and implies "start".  It may be pressed multiple times for multiple minutes, but it will not add a minute to a manually entered time.  Output +
A set of 0-9 buttons.  Time entry is MMSS (i.e. "130" means 1 minute 30 seconds).  Seconds may range from 0..99.  So "130" and "90" are equivalent entries.  Obviously each minute is 60 seconds even if the seconds part of the entry exceeds 59.  Output 0..9
A "start" button which must be pressed to start the microwave if the time is entered manually.  Output S

My food packages specify time in MM:SS and so the program must accept that input.

Examples

1:00 is + (remember "minute plus" implies start)
1:01 is 61S (seconds can exceed 59, but "minute plus" does not work in conjunction with digits -- I think this is a design flaw in my microwave)
9:00 is 900S (shorter than +++++++++)


Tips for golfing in TikZ TikZ is a Latex package used for drawing precise images in Latex documents.  It has a massive specification and a boatload of features that may be useful for graphical-output style questions.

What tips do people have for golfing in TikZ?  As always, tips should be specific to to TikZ (e.g. "Remove comments" is not an answer), and stick to a single tip per answer.

Use \def
\def is an incredibly powerful tool when it comes to golfing.  \def allows you to assign something to a variable.
This can be used simply with the to save a number you may use a bunch of times for instance
\def\x{1456}

Will define 1456 as \x for future use much like saving a variable might in a programming language.
However \def is much more powerful than that, because \def doesn't define a variable it defines a snippet of code to be substituted into the program whenever it is called.
For example say you want to draw some rectangles using \draw  you might write the following code:
\draw(0,0)rectangle(3,4)rectangle(8,0);\draw(2,2)rectangle(3,3);

Using \def this could be written as:
\def\x{)rectangle(}\draw(0,0\x3,4\x8,0);\draw(2,2\x3,3);


Equivalence classes on the Transitive Closure of a Reflexive Relation The goal of this challenge is to compute the set of equivalence classes over the transitive closure of a symmetric, reflexive relation. For those who don't know what that means, here is a brief introduction into the relevant terms:

A relation ◊ is symmetric if a ◊ b ↔ b ◊ a. It is reflexive if each object is related to itself, i.e. a ◊ a  always holds. It is transitive  if a ◊ b ∧ b ◊ c → a ◊ c, i.e. if a is related to b and b is related to c, then a is related to c. An equivalence relation is a relation that is symmetric, reflexive and transitive.

The transitive closure ◊* of ◊ is a transitive relation such that a ◊* b holds if and only if there is a (possibly empty) series of objects c1, c2, ..., cn such that a ◊ c1 ◊ c2 ◊ ··· ◊ cn ◊ b. The transitive closure of a symmetric, reflexive relation is an equivalence relation.

Let ≡ be an equivalence relation over the set S. An equivalence class a≡ of an object a over the relation ≡ is the largest subset of S such that a ≡ x for all x ∈ S or formally: a≡ = { x | x ∈ S, a ≡ x }. All elements of a≡ are equivalent to one another.

The set of equivalence classes S/≡ of ≡ over S is the set of equivalence classes of all members of S.

Constraints

In this task, your objective is to write a function that takes a binary relation ≅ and a finite non-empty set S. You may take input in a suitable way and choose a suitable data-structure for S (e.g. an array or a linked list). Assume that ≅ is a symmetric, reflexive relation over S. Your function should return or print out the set of equivalence classes over S of the transitiveclosure of ≅. You may choose a suitable output format or data structure for the result. As the result is a set, each object in S may appear only once.

You may not use library routines or other builtin functionality to find the components of a graph or related things.

Winning condition

The shortest answer in octets wins. The most elegant answer is chosen in case of a tie.

Sample input

The reflexive and symmetric members of ≅ have been omitted for brevity.

S1 = {A, B, C, D, E, F, G, H}
≅1 = {(A, B), (B, C), (B, E), (D, G) (E, H)}
S1/≅1* = {{A, B, C, E, H}, {D, G}, {F}}.

S2 = {α, β, γ, δ, ε, ζ, η, θ, ι, κ}
≅2 = {(α, ζ), (α, ι), (β, γ), (β, ε), (γ, δ), (γ, ε), (ζ, θ), (η, κ), (θ, ι)}
S2/≅2* = {{α, ζ, θ, ι}, {β, γ, δ, ε}, {η, κ}}

S3 = {♠, ♣, ♥, ♦}
≅3 = {}
S3/≅3* = {{♠}, {♣}, {♥}, {♦}}

S4 = {Α, Β, Γ, Δ, Ε, Ζ, Η, Θ, Ι, Κ, Λ}
≅4 = {(Α, Ε), (Β, Ζ), (Γ, Η), (Δ, Θ), (Ε, Ι), (Ζ, Κ), (Η, Λ), (Θ, Α), (Ι, Β), (Κ, Γ), (Λ, Δ)}
S4/≅4* = {{Α, Β, Γ, Δ, Ε, Ζ, Η, Θ, Ι, Κ, Λ}}

Pyth, 50 29 bytes

JchQ1FNeQAmf/@JTd0N XGJ.(JH;J

Input is expected to be a list of two elements where the first element is a list of all the objects in S, and the second element is a list of all the members in ≅, represented as lists. So for the first example, the input is

[["A", "B", "C", "D", "E", "F", "G", "H"], [["A", "B"], ["B", "C"], ["B", "E"], ["D", "G"], ["E", "H"]]]

Explanation:

                               Implicit assignment of Q to input, so head(Q) is S and end(Q) is ≅
JchQ1                          Assign J to chop(head(Q),1) e.g. [1,2,3] => [[1],[2],[3]]
     FNeQ                      For N in end(Q)
         A                       Assign [H,G] to following list
          m       N                Map following function over N
           f     0                   Return first T where following function of T starting at 0,1,2... is truthy
            /@JTd                      lambda d: true if d is J[T]
                    XGJ.(JH;     Append J[H] to J[G] and pop J[H]
                            J  Print J

Note that if transitive or reflexive members (i.e. redundant) members of ≅ are included, my code should output junk.

You can try it out here.


Draw the Ionising Radiation Hazard Symbol Draw the ionising-radiation-hazard-symbol in an arbitrary colour on a distinctly coloured background. The specific proportions were published in the June 27th 1974 issue of the Federal Register of the US Government.

Details

As output, writing to a file (raster and vector formats are permitted) or displaying on the screen are both allowed.
You can draw just the border or the filled shape.
If you use raster images, you should take a parameter (or two) as input that lets you adjust the resolution of the output (e.g. width/height).
The background must at least have the size of the bounding box of the symbol but may be larger.
Outputting the unicode symbol ☢ is not sufficient.
The exact ratios of the used distances are given in following diagram (which was originally from here):

Related: Draw the ☣ (Biohazard Symbol)

BBC BASIC, 200 bytes

f=500
g=1/SQR(3)
CIRCLE FILLf,f,f
GCOL15
MOVE-100,f
MOVEf,f
PLOT85,f*(1-g),0
MOVE1100,f
MOVEf,f
PLOT85,f*(1+g),0
MOVEf*(1-g),2*f
MOVEf,f
PLOT85,f*(1+g),2*f
CIRCLE FILLf,f,150
GCOL0
CIRCLE FILLf,f,100

Somehow outgolfing Python, this works by drawing a large black circle, filling in the white triangular sections, drawing a central white circle and finally drawing the central black circle.


Little Boxes on the Hillside There's a satirical song called Little Boxes, originally by Malvina Reynolds, about suburban sprawl that has lyrics as follows:

  Little boxes on the hillside,
  Little boxes made of ticky-tacky,
  Little boxes on the hillside,
  Little boxes all the same.
  There's a green one and a pink one
  And a blue one and a yellow one,
  And they're all made out of ticky-tacky
  And they all look just the same.

Your job here is, given an integer input n>1 that represents the size of the house, output the four "little boxes" using the following colors (in 0xRRGGBB notation):

Green -- 0x00FF00
Pink --- 0xFF00FF (technically magenta)
Blue --- 0x0000FF
Yellow - 0xFFFF00

If your particular console doesn't have these exact colors, you may use the closest available (e.g., ANSI escape codes).

The houses are constructed with n _ representing the floor and roofline. They are surrounded by n/2 (round-up) | characters representing the walls. The roofs are always 2 high and are two / on the left edge, two \ on the right edge, and n-2 - representing the roof peak. As the houses get larger, the comparative size of the roof gets smaller; this is intended.

Here's a house of size 2:

 /\
/__\
|__|

Here's size 3:

 /-\
/___\
|   |
|___|

Here's size 7:

 /-----\
/_______\
|       |
|       |
|       |
|_______|

Thus given an input of 7, output four houses of size 7 as described above, with the first one in green, the second in pink (magenta), the third in blue, and the fourth in yellow. Output of the colors in that order is important.

Example picture of size 3:

Rules

The houses can be horizontal or vertical so long as there is a clear separation between them.
Leading/trailing newlines or other whitespace are optional, provided that the houses line up appropriately.
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
Output can be to the console, saved as an image, etc.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Python 2, 123 121 119 111 109 108 bytes

Saved two bytes thanks to caird coinheringaahing; using the actual unprintable ASCII character instead of escaping it (\33)
Could (and did) save a byte by writing an entire program using input() instead of defining a function
Saved seven bytes thanks to ElPedro; using the fact that str(90+n) with 0<=n<=9 is "9%s"%n
Saved two three bytes by using string formatting rather than string concatenation

N=input()
for(n)in"2543":Z="_"*N;print"[9%sm /"%n+~-~-N*"-"+"\ \n/%s\\\n"%Z+~-N/2*("|%s|\n"%" "*N)+"|%s|"%Z

Try it online!

Uses ANSI escape codes for coloring the houses.


Concatenative counting Your challenge is to write N snippets of code such that, when you concatenate the first K ≥ 1 together, they produce the number K. The higher N, the better. Here's the catch: you may not use any character more than once across your snippets.

Rules

You may use the same character multiple times in one (and only one) snippet.
These snippets must be concatenated in the order they are presented, without skipping any.
You must write at least two snippets.
All snippets must be in the same language.
Remember: snippets do not have to be full programs or functions, nor do they have to function on their own. -1 is a valid snippet in Java, e.g.
All resulting concatenations must output the respective K value.
The winner is the person with the highest N value. Tie-breaker is shortest overall program length in bytes.

Example

Suppose your snippets were AD, xc, 123, and ;l. Then:

AD should produce 1
ADxc should produce 2
ADxc123 should produce 3
and ADxc123;l should produce 4.

This program would have a score of 4.

Perl 5, 50,091 151 snippets

First snippet:

use utf8; print length A

2nd through 26th snippets: B through Z

27th through 46nd snippets: a through z, excluding the characters in "length"

47th through 56th snippets: 0 through 9

57th snippet: _

The remaining snippets are the 50,105 individual Unicode characters which Perl regards as "word" characters, excluding the 14 distinct word characters in the initial snippet, in any order.

Well, it was a nice thought, but it turns out that after a certain length Perl gives you an "identifier too long" error.  This is the longest combined program I was able to get Perl to digest:

use utf8; print length A012345679BCDEFGHIJKLMNOPQRSTUVWXYZ_abcdjkmoqsvwxyzĀāĂăĄąĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬĭĮįİıĲĳĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňŉŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţ

The perldiag manual page says "Future versions of Perl are likely to eliminate these arbitrary limitations" but my Perl 5.18 has not done so.

Explanation:

In non-strict mode, Perl 5 interprets unquoted strings of word characters as "barewords," essentially quoting them for you automatically.  They're usually best avoided, but they sure help here!


BalancE the UppercasE Oh, No!
the sentences are out of balance.
Quick! balance them.

A word is defined as follows:

A sequence of letters [A-Za-z] separated by any non-letter character ([0-9] ~+- etc.)

A word is BaLanCeD if its capitalization is the same forwards as it is backwards.
Given a sentence with words, balance each word by capitalizing a letter on the right-hand side for each uppercase letter on the left-hand side, and the other way around. Do not make uppercase letters lowercase.
Rules

For each letter n chars from the beginning of a word, it and the letter n chars from the end of the word should both be made uppercase if either of them is upper case.
All input will be printable ASCII (codepoints 32   to 126 ~).

No need to balance if:

The capital is in the middle of a term (word) (equal amount of letters on each side)
No capitals are present in the term

Example:
eeeeE → EeeeE
eEeee → eEeEe
eeEee → eeEee
Eeee. → EeeE.
{EEee}1EEeEEEeeeeee → {EEEE}1EEeEEEEEEeEE

TesT CaSeS:
It was the first new century. →
IT was the first new century.

IiIIiiIIiiiI Ii iI iiiI iiii iIi. →
IiIIIIIIIIiI II II IiiI iiii iIi.

I sueD the airport for misplacing my Luggage. – I lost my Case. →
I SueD the airport for misplacing my LuggagE. – I lost my CasE.

The Policemen  CraCked THE CaSE of the lost cocaIne. →
ThE PolicemeN  CraCkeD THE CASE of the lost coCaIne.

JUST IN CASE. →
JUST IN CASE.

If(!1){ /\hElloBinOLIngo}elsE{ print( 'bOn aPPetit')} →
IF(!1){ /\hElLOBinOLInGo}ElsE{ print( 'bOn aPPeTIt')}

xK/TH"E7k['VyO%t>2`&{B9X.8^$GWc=!+@ 3Us}]JFM)jbuI,-:alPw*Qvpq5zi\Z(_n1dC~?<;fDAm0SR|eYg6#rN4Lho →
XK/TH"E7k['VyO%t>2`&{B9X.8^$GWC=!+@ 3US}]JFM)JbuI,-:aLPw*QvpQ5zi\Z(_n1DC~?<;fDAm0SR|eYg6#RN4LhO

Foo_bar →
FoO_bar

(the " →" will not be included in the input)
This is codegolf, so attempt to achieve least amount of bytes

JavaScript (Node.js),  76  72 bytes
Saved 2 bytes thanks to @tsh

s=>s.replace(/[a-z]+/gi,w=>Buffer(w).map((c,i,a)=>c&=a[w.length+~i]|95))

Try it online!
Commented
s =>                     // s = input string
s.replace(               // replace in s:
  /[a-z]+/gi,            //   match all words in a case-insensitive way
  w =>                   //   for each word w:
    Buffer(w)            //     turn it into a Buffer
    .map((c, i, a) =>    //     for each character c at position i in this array a[]:
      c &=               //       bitwise AND of c with:
        a[w.length + ~i] //         the counterpart character taken from the end of
                         //         the word
        | 95             //         OR 0b1011111
                         ///        (all letter bits except the lowercase bit)
    )                    //     end of map()
                         //     implicit coercion of the Buffer to a string
)                        // end of replace()


Write a program to display directory treehouse Given a directory (such as C:/), given from stdin or read from a file, produce a directory tree, with each file/folder indented based on its depth.

Example

If I have a C:/ drive which only contains two folders foo and bar, and bar is empty while foo contains baz.txt, then running with input C:/ produces:

C:/
    bar/
    foo/
        baz.txt

while running with input C:/foo/ should produce

foo/
    baz.txt

As this is codegolf, lowest byte count wins. The file extensions (such as baz.txt) are optional.
Extra notes: hidden files can be ignored, directories must actually exist, it can be assumed that files do not contain unprintable characters or new lines but all other printable ASCII characters are fine (file names with spaces must be supported). Output can be written to file or stdout. The indentations can be made up of either a tab character or 4 spaces.

bash, 61 58 54 bytes

find "$1" -exec ls -Fd {} \;|perl -pe's|.*?/(?!$)|  |g'

Takes input as a command line argument, outputs on STDOUT.

Note that the spaces near the end before the |g are actually a tab character (SE converts them to spaces when displaying posts).

find              crawl directory tree recursively
"$1"              starting at the input directory
-exec             and for each file found, execute...
ls -Fd {} \;      append a trailing slash if it's a directory (using -F of ls)
|perl -pe         pipe each line to perl
'
s|                replace...
.*?/              each parent directory in the file's path...
(?!$)             that doesn't occur at the end of the string...
|    |            with a tab character...
g                 globally
'

Thanks to @Dennis for 4 bytes!


How much reputation did you lose today? Assuming StackExchange doesn't decide to restore my account after deleting it due to age restrictions (even though I'm 14 already and almost 15 ಠ_ಠ), a lot of people on this site just lost reputation from my upvotes being deleted. This happened at around 5:30 PM on June 20th, 2017, UTC.

So, your challenge is to show how much PPCG reputation was lost from my deletion, given the user's PPCG ID.

Challenge

Input

A single integer will represent the user's UUID on PPCG.

Output

A single integer will represent how much reputation the user lost due to this. If the user lost reputation multiple times within the same hour all due to user removals, then it is acceptable if your program returns the number for the wrong user. In the event that the user gained reputation from my account being deleted, your program should return a negative number for losing negative reputation. And finally, should I have had no voting on that user (in the past 60 days), your program should return 0.

Test Cases

UUID  -> REP-LOST (Username) # Don't output the username
40695 -> 22 (Downgoat)
12012 -> 148 (Dennis)
8578  -> 61 (Martin Ender)

You can check by going to https://codegolf.stackexchange.com/users/<UUID>/?tab=reputation&sort=post and looking for User was removed (learn more)

Original idea thanks to Uriel with approval

Note

Thanks to JungHwan Min for this link!

https://codegolf.stackexchange.com/ajax/users/<UUID>/rep/day/1497916800

You can fetch raw data of a user's reputation change from this link above.

JavaScript ES6, 132 bytes

n=>fetch(`/ajax/users/${n}/rep/day/1497916800`).then(v=>v.text()).then(v=>alert((v.match(/rep-down">-(\d+)[^u]+user w/)||[0,0])[1]))

Tested on Safari 10. This uses the new fetch API and alerts the output. This is a function so pass the user id as the argument. This will output 0 for no rep changes.

Must be run on PPCG due to CORS (Cross-origin resource sharing), browsers do not allow JavaScript to perform a web request outside of the current domain.


How lit is this mountain? A mountain is defined to be a set of line segments whose first point has coordinates (0,a) where a > 0, and whose last point has coordinates (b,0), where b > 0. All intermediate points have a y-coordinate (ordinate) strictly greater than 0. You are given the points on the mountain sorted in ascending order of x-coordinate (abscissa). Note that two points can have the same x-coordinate, producing a vertical segment of the mountain. If you are given two points with the same x-coordinate, they should be connected in the order they are given. In addition, there can be horizontal segments of the mountain These horizontal segments are not lit, no matter what. All coordinates are nonnegative integers.

The question: what is the total length of the mountain that would be lit, assuming the sun is an infinite vertical plane of light located to the right of the mountain? This number does not need to be rounded, but if it is rounded, include at least four decimal places. I have included a picture:

Here, the lines that are bolded represent the segments that are lit. Note that in the input, P appears before Q (PQ is a vertical line segment) so the previous point is connected to P and not Q.

You may take input in any reasonable format, like a list of lists, a single list, a string, etc.

Test case:

(0,3000)
(500, 3500)
(2500, 1000)
(5000,5000)
(9000,2000)
(9000,3500)
(10200,0)

Output: 6200.0000

There are two lit-up segments here, as shown in this image:
The first one has length 5000/2 = 2500 and the second one has length 3700.

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

Python 2,  134 131 128 124 120 117 109  107 bytes

p=input();s=0
for X,Y in p[1:]:x,y=p.pop(0);n=y-max(zip(*p)[1]);s+=n*(1+((X-x)/(y-Y))**2)**.5*(n>0)
print s

Try it online!

Takes input as a list of tuples / two-element lists of floating-point numbers.

Explanation

We basically iterate through the pairs of points in the graph, and if
\$y_1 > y_2\$, then we calculate how much of the line is exposed to light. The pairwise iteration is performed with a for loop to get the next point, \$(x_2, y_2)\$, popping the first element in the list each time to retrieve the current point, \$(x_1, y_1)\$.

Maths – What part of the line segment is exposed to light?

Let \$(x_1, y_1)\$ be the coordinates of the current point. Let \$y_{max}\$ be the maximum height of a point after the current one (local maxima after the current point)  and \$(x_2, y_2)\$ be the coordinates of the next point. In order to calculate the length exposed to the sun, \$L\$, we ought to find \$x_3\$, as shown in the diagram. Naturally, if \$y_1 \le y_{max}\$, the  segment is not exposed to light at all.

In the triangle formed, the line segment of length \$x_3\$ is parallel to the base, of length \$x_2 - x_1\$, so all three angles are congruent. Therefore, from the Fundamental Theorem of Similarity (case Angle-Angle), we can deduce that \$\frac{x_3}{x_2 - x_1} = \frac{y_1-y_{max}}{y_1}\$. Hence, \$x_3 = \frac{(y_1-y_{max})(x_2 - x_1)}{y_1}\$. Then, we can apply the Pythagorean Theorem to find that:

$$L = \sqrt{(y_1-y_{max})^2+x_3^2}$$

By joining the two formulas, we arrive at the following expression, which is the core of this approach:

$$L = \sqrt{(y_1-y_{max})^2+\left(\frac{(y_1-y_{max})(x_2 - x_1)}{y_1}\right)^2}$$
$$L = \sqrt{(y_1-y_{max})^2\left(1+\frac{(x_2 - x_1)^2}{y_1^2}\right)}$$

Code – How does it work?

p=input();s=0                             # Assign p and s to the input and 0 respectively.
for X,Y in p[1:]:                         # For each point (X, Y) in p with the first
                                          # element removed, do:
    x,y=p.pop(0)                          # Assign (x, y) to the first element of p and
                                          # remove them from the list. This basically
                                          # gets the coordinates of the previous point.
    n=y-max(zip(*p)[1])                   # Assign n to the maximum height after the
                                          # current one, subtracted from y.
    s+=n*(1+((X-x)/(y-Y))**2)**.5         # Add the result of the formula above to s.
                                 *(n>0)   # But make it null if n < 0 (if y is not the
                                          # local maxima of this part of the graph).
print s                                   # Output the result, s.

Changelog

Gradually optimised the formula for golfing purposes.
Saved 1 byte thanks to FlipTack.
Saved 2 bytes by removing the unnecessary condition that y>Y, since if the local maxima of the Y-coordinate after the current point subtracted from y is positive, then that condition is redundant. This unfortunately invalidates FlipTack’s golf, though.
Saved 3 bytes by changing the algorithm a bit: instead of having a counter variable, incrementing it and tailing the list, we remove the first element at each iteration.
Saved 8 bytes thanks to ovs; changing (x,y),(X,Y) in the loop condition with a list.pop() technique.
Saved 2 bytes thanks to Ørjan Johansen (optimised the formula a little bit).


The cat ate your input again! Create a cat program, a.k.a a program that takes an input and prints it.

...Except, the program will randomly take characters away from your input and print that instead.

Each character in the input should have generally equal odds to be removed with the program, though, as it is hard to make that, the odds for each character can vary by 10% at most.

Your program should take the input, then randomly remove characters from the input, then print that version again. (You can print with trailing newlines or other characters in case your language has to print newlines.)

If the input was BOOOWL, it shouldn't remove all Os with an equal chance: each character (not unique) should be considered, so instead of every O combined having a 1/5 chance (for example), each O should have a 1/5 chance, so, instead of there being a 1/5 chance of BWL, there should be a 1/5 chance of BOWL, BOOWL.

Input is restricted to STDIN or closest equivalent.

Each character must have a minimum of 10% and a maximum of 30% chance to be removed.

Each character's odds should be calculated individually.

You can use any component of your language supporting random actions, be it functions or something other.

Output must be through STDOUT or the closest equivalent. If your language does have STDOUT, do not output in any other way. If your language cannot output strings as text, use closest equivalent (C's character array output's OK here).

This is code golf. Shortest program wins.

Japt -f, 2 bytes
5ö

The -f flag "runs the program on each element in the first input, outputting an array of those that return a truthy value." 5ö returns a random number between 0(inclusive) and 5(exclusive). Like JavaScript, 0 is falsy in Japt.
Try it


Make the Stretchy Snakes Kiss A stretchy snake looks something like this:
<||=|||:)~

Each separate sequence of vertical bars (|) in a stretchy snake, known as a stretchy portion, is individually extendable to twice its width, and is drawn with alternating slashes (/,\) once extended.
The particular snake above has two such stretchy portions, giving it four possible poses:
<||=|||:)~

</\/\=|||:)~

<||=/\/\/\:)~

</\/\=/\/\/\:)~

The general form of a stretchy snake in its least stretched pose is defined by this regex:
<(\|+=)*\|+:\)~

Which can be stated in words as:

<, followed by any number of sequences of |'s joined with = signs, followed by :)~.

So <|:)~ and <||:)~ and <|=|:)~ and <|=|=||=|||||=||:)~ are stretchy snakes, but <=:)~ and <=|:)~ and <||=:)~ and <|==||:)~ are not.
Stretchy snakes can also face left instead of right, e.g. ~(:|||=||>. The forms are the same, just mirrored.
Challenge
Write a program that takes in a single line string of two stretchy snakes facing each other, with some number of spaces in between. Both snakes will be in their least stretched pose (all vertical bars, no slashes). The string will start with the tail of the right-facing snake and end with the tail of the left-facing snake (you may optionally assume there's also a trailing newline).
For example, here's a possible input with five spaces between the snakes:
<|=||:)~.....~(:||||>

I'm using periods (.) instead of actual space characters for clarity.
Zero spaces between snakes is also valid input:
<|=||:)~~(:||||>

We say the snakes are kissing when their tongues are touching like this.
Your program needs to extend some combination of the stretchy portions of both of the snakes such that the snakes have the fewest number of spaces possible between them (without overlapping), i.e. such that the snakes are as close to kissing as possible.
Both the snakes' tails are fixed but their heads and bodies can move - right for the right-facing snake, left for the left-facing snake - according to what stretchy portions have been extended.
The output of your program is the single line string (plus optional trailing newline) that shows the snakes as close to kissing as possible, with alternating slashes drawn in place of vertical bars for stretchy portions that have been extended.

For example, the output for <|=||:)~.....~(:||||> (from above) would be:
</\=||:)~~(:/\/\/\/\>

This is the only solution here because with any other combination of the stretchy portions extended, the snakes would either overlap or be farther away from kissing.

If there are multiple solutions possible, the output may be any one of them.
For example, if the input were
<|=||:)~.....~(:|||=|>

the output could be
<|=/\/\:)~~(:/\/\/\=|>

or
</\=||:)~~(:/\/\/\=/\>

Remember that it won't always be possible to make the snakes kiss, but you still need to get them as close as possible.
For example, if the input were
<||=||||:)~...~(:||>

the output could be
</\/\=||||:)~.~(:||>

or
<||=||||:)~.~(:/\/\>

If the snakes are already kissing, the output will be the same as the input. e.g.
<|=||:)~~(:||||>

In general, the output will be the same as the input if the extension of any stretchy portion would make the snakes overlap. e.g.
<|||=|||:)~..~(:||||=|||||=||||||>

Notes

Takes input from stdin or the command line as usual, or write a function that takes a string. Print or return the output.
You can use periods (.) in the input and output in place of spaces ( ) if you prefer.
It's only important that slashes alternate within the sequence of vertical bars they replaced. Their ordering in the snake at large or whether a forward or backward slash comes first doesn't matter.
Stretchy portions cannot extend partway - it's exactly double or no extension at all.

Scoring
This is code-golf. The shortest submission in bytes wins. Tiebreaker is earlier answer.

Retina, 209 107 99 97 92 bytes

.(?=(.+)(?<=(?=<((\|+|(?<-5>\|(?=\1())?)+)[^|]+)+$(?(5)!)).+( )+\S+))\4
/ \
+` (.*~|~.*)
$1

For counting purposes, each line goes in a separate file, but you can run the code from a single file with the -s flag.

Bringing the best features of .NET regex and Retina together: balancing groups, arbitrary length lookbehinds and repeated regex substitution.

Essentially, the long regex encodes a valid solution and the regex engine's backtracker finds one of the optimal ones for me.

Explanation

First, let's consider how we can find a valid solution (not necessarily producing the correct output) with a regex. We can use .NET's balancing groups to help us count the stretchy parts. Consider the following simpler regex:

\S+( )+.+(?<=(?(1)!)^([^|]+(\|+|(?<-1>\|)*))+>)

We can disect that.

\S+( )+.+

This matches the entire string, pushing one capture onto the group 1 stack for each space in the input. We will use that stack to ensure that the stretchy parts exactly fill the space captured into those groups.

Next is a lookbehind. The catch is that lookbehinds are matched from right to left in .NET (so that's how you should read them). This gives us the opportunity to traverse the string a second time, figuring out whether there's a subset of stretchy part that sums to the number of matched spaces. Going through the lookbehind from right-to-left:

>

This is just ensure that we're actually starting from the end of the string (the snake's tail).

(
  [^|]+
  (
    \|+
  |
    (?<-1>\|)+
  )
)+

For each stretchy part, this either just matches the entire part without doing anything (\|+), or it matches the entire part while popping captures off stack 1 ((?<-1>\|)*). Having this alternation ensures that we can only fully extend a stretchy part or leave it unchanged, and not get stuff like |/\|. Then we move on to the next stretchy part with [^|]+.

(?(1)!)^

Finally, we ensure that we've traverse the entire string (both snakes), and that stack 1 is completely empty. I.e. that we've found a subset of stretchy part that exactly sums to the number of spaces we've captured earlier.

The backtracker will go back and forth through the string trying all combinations of unchanged and extended parts until the subset sum problem is solved. If such a subset doesn't exist, the lookbehind will fail. This will cause the backtracker to go back to the \S+( )+.+ part and try capturing one space less with ( )+ (which will just be cover by .+ instead). Due to the greediness of + we therefore try filling as many spaces as possible.

You can check the validity of this approach with this slightly modified substitution:

\S+(( )+).+(?<=(?(2)!)^([^|]+(\|+|(?<-2>\|)*))+>)
=$1=

Which will give you a string =spaces= with exactly the number of spaces that can be filled with the given snakes.

I've had to add some more trickery to actually expand the correct |s. Basically, I want to replace all |s which were matched using the (?<-1>\|)+ branch. The idea is to match an individual character, put the solver in a lookaround and set a flag if the match happens to be inside that branch. If that flag wasn't set we invalidate the match at the end to avoid replacement of other characters.

To do this, we use a bunch of nested lookarounds. Again, .NET's variable-length lookbehinds are matched from right to left, so if we nest lookaheads and lookbehinds, we can let the regex engine traverse the string several times. For golfing reasons, the solver is reversed in my actual solution (starting at the end, picking up the spaces from right to left, and then solving the subset sum from left to right), but otherwise the structure of the solver is exactly the same. Let's dissect the full regex:

.(?=(.+)...)

We match a single character, then capture the remainder of the string and move the cursor to the end of the string. We will use this group 1 later to check in the solver whether we're at the position of the match.

(?<=....+( )+\S+)

This is like the first part of the simple solver above, except that we pick up the spaces from right to left. The backtracking of the number of spaces works exactly the same as before, except that we're using group 5 now.

(?=<((\|+|(?<-5>\|(?=\1())?)+)[^|]+)+$(?(5)!))

This is the same as before, except we're going from left to right, and whenever we match a | in the expanding branch, we check if it's the one being matched right with

(?=\1())?

This is an optional lookahead. It tries to match group 1 again (which, here, is only possible if we're right after the character being matched), and if we do, we capture an empty string into group 4, which indicates that we did find the current character in one of the expanded bits. If \1 doesn't match, 4 won't capture anything, and the ? ensures that the failing lookahead won't affect the solver at all.

Finally, after all the solving is done, we just check with \4 whether this lookahead was used. If so, we want to replace the current character with /\.

One difficulty remains: removing the right amount of spaces. The shortest way to do this I've found so far is to insert a space along with the /\ and then get rid of one space between the tongues for each of those marker spaces in a separate step:

+` (.*~|~.*)
$1


"Stair-ify" a string You must write a program or function that creates a "stair-ified" string. Here is how you "stair-ify" a string:
For each character in the string:

If the character is an upper or lowercase vowel, not including 'y', output it then move the rest of the string up a column.

If the character is a space or a tab, output it then move the rest of the string down a colum.

If the character is neither, output it normally.

IO can be in any reasonable format. The input will not contain any newlines. If you want, you can remove any trailing whitespace.
If you choose to return the string, rather than printing it, please also include a short program that will print your string so that it can be visualized. This is not mandatory, nor will it go towards your byte-count. This is just a convenience for users who don't understand golf or esolangs (like me) to be able to verify output or tinker with the code.
Sample IO:
Output for "bcdef ghijkl":
    f    jkl
bcde  ghi

Output for "Programming Puzzles And Code-Golf":
                               lf
                            -Go
                  s  nd   de
         ng   zzle  A   Co
      mmi   Pu
   gra
Pro

Output for "Abcdefghijklmnopqrstuvwxyz":
                     vwxyz
               pqrstu
         jklmno
     fghi
 bcde
A

As usual, this is code-golf, so shortest answer in bytes wins.

Pyth, 63 bytes
V_Q aY?}rN0"aeiou"=hZ?}N"     "=tZZ;Jh.mbYKh.MZYjC.b++*d+JNY*dK_YQ
                         ^^^^^
                         |||||
                         |tabs
                        space

The spaces in the middle is actually a single tab character, but StackExchange renders it as four spaces.
Try it online!


Sequentially Divisible Sometimes to fall asleep, I'll count as high as I can, whilst skipping numbers that are not square-free. I get a little thrill when I get to skip over several numbers in a row - for example, 48,49,50 are all NOT square-free (48 is divisible by 2^2, 49 by 7^2, and 50 by 5^2).

This led me to wondering about the earliest example of adjacent numbers divisible by some arbitrary sequence of divisors.

Input

Input is an ordered list a = [a_0, a_1, ...] of strictly positive integers containing at least 1 element.

Output

Output is the smallest positive integer n with the property that a_0 divides n, a_1 divides n+1, and more generally a_k divides n+k. If no such n exists, the function/program's behavior is not defined.

Test Cases

[15] -> 15
[3,4,5] -> 3
[5,4,3] -> 55
[2,3,5,7] -> 158
[4,9,25,49] -> 29348
[11,7,5,3,2] -> 1518

Scoring

This is code-golf; shortest result (per language) wins bragging rights. The usual loopholes are excluded.

Wolfram Language (Mathematica), 51 bytes

Mod[ChineseRemainder[1-Range@Length@#,#],LCM@@#,1]&

Try it online!


Hofstadter H-sequence Definition

\$a(0) = 0\$
\$a(n) = n-a(a(a(n-1)))\$ for integer \$n > 0\$

Task
Given non-negative integer \$n\$, output \$a(n)\$.
Testcases
n     a(n)
0     0
1     1
2     1
3     2
4     3
5     4
6     4
7     5
8     5
9     6
10    7
11    7
12    8
13    9
14    10
15    10
16    11
17    12
18    13
19    13
20    14
10000 6823

References

WolframMathWorld
OEIS A005374

Haskell, 23 22 bytes

f 0=0
f n=n-f(f$f$n-1)

Simply uses the definition of the sequence. f(f$f$n-1) is equivalent to f (f (f (n-1))).

Test:

main = putStrLn . show $ map f [0..20]
-- => [0,1,1,2,3,4,4,5,5,6,7,7,8,9,10,10,11,12,13,13,14]

Thanks to Anders Kaseorg for a byte!


Alphabet to Number and Number to Alphabet Challenge

In this challenge you have to take a number as input and output the corresponding letter of the alphabet, and vice versa. (1 <=> A, 2 <=> B) etc.

1 -> A
2 -> B
...
26 -> Z

A -> 1
B -> 2
...
Z -> 26

Rules

This is code-golf, so shortest code in bytes wins.
The input will only consist of either an uppercase letter from A to Z or an integer from 1 to 26 inclusive.
Trailing whitespaces (space and newline) are allowed.

Pure Bash, 51
Most of the rest of the answers use some sort of conditional.  This one dispenses with conditionals entirely, and instead treats the input as a base-36 number which indexes into an appropriately constructed bash-brace-expansion array:
a=(_ {A..I} {1..26} {J..Z} {A..Z})
echo ${a[36#$1]}

Ideone.


Stroke Count of a Chinese Numeral Task
Given an integer \$n\in[0,10^{12})\$ in any convenient format, return the number of strokes needed to write that character in simplified Chinese.
Background
Chinese numerals are expressed in base 10 with a system of digits and places, with an important distinction that digits are in groups of four, rather than three.
The individual characters used to write Chinese can be described at the lowest level as a collection of strokes, laid out in a certain order and manner. The number of strokes required to write a character is that character's stroke count.
The (simplified) characters used to write numbers in Chinese are:
num   char　 strokes
0     零*    13
1     一     1
2     二**   2
3     三     3
4     四     5
5     五     4
6     六     4
7     七     2
8     八     2
9     九     2
10    十     2
100   百     6
1000  千     3
10^4  万     3
10^8  亿     3
 * 0 can also be written 〇, but we won't use that here.
** 两 is largely interchangeable with 二, apart from never
   appearing before 十. We won't consider it here for simplicity,
   but 两 is very common in actual usage.

For example, 9 8765 4321 is 九亿八千七百六十五万四千三百二十一: nine hundred-million (九 亿), eight thousand seven hundred sixty-five ten-thousand (八千七百六十五 万), four thousand three hundred twenty-one (四千三百二十一). In all, 53 strokes are needed to write this out.
There are additionally some special rules involving the digits 0 and 1. These can vary slightly between dialects, but we'll choose these:

When there are non-trailing 0s in a 4-digit group, they are combined into a single 零. No place marker is used.
(This is because e.g. 一百二 is a common way to say 120. We won't consider that form.)

1020 is 一千零二十.
6 0708 is 六万零七百零八.
3 0000 4005 is 三亿四千零五.
0 is 零.

If the number would begin with 一十, the 一 is omitted.

Powers of 10 are 一, 十, 一百, 一千, 一万, 十万, 一百万, etc.
111 is 一百一十一.

Test Cases
           n  strokes  chinese
           0  13       零
          10  2        十
         236  17       二百三十六
        7041  26       七千零四十一
       50010  23       五万零一十
      100000  5        十万
      860483  42       八十六万零四百八十三
     4941507  52       四百九十四万一千五百零七
    51001924  38       五千一百万一千九百二十四
   105064519  70       一亿零五百零六万四千五百一十九
   300004005  31       三亿四千零五
   987654321  53       九亿八千七百六十五万四千三百二十一
  1240601851  56       十二亿四千零六十万一千八百五十一
608726402463  79       六千零八十七亿二千六百四十万二千四百六十三

@user202729 provided a script in the sandbox to help with reading the Chinese numbers: Try it online!