Minimally sort a list into a matrix Given an unsorted list of unique strictly positive integers, minimally sort it into a 2D matrix. The input list is guaranteed to be of composite length, which means the output matrix is not necessarily square, but is of size n x m with n,m > 1.

"Minimally sort" here means the following:

Sort the list in ascending order.
Compact the output matrix as much as possible -- minimize the sum of the dimensions of the matrix (for example, for 20 input elements as input, a 5x4 or 4x5 output matrix is required, and not a 2x10).
Compact the sorted numbers as far to the upper-left of the matrix as possible, starting with the first element in the sorted list.
This can be thought of as sorting the list, then slicing it along the matrix's anti-diagonals, starting with the upper-left.

Examples:

For input 1..20 output is either a 5x4 or a 4x5 matrix as follows:

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

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

For input [3, 5, 12, 9, 6, 11] output is a 2x3 or 3x2 as follows

3  5  9
6 11 12

 3  5
 6  9
11 12

For input [14, 20, 200, 33, 12, 1, 7, 99, 58], output is a 3x3 as follows

 1   7  14
12  20  58
33  99 200

For input 1..10 the output should be a 2x5 or 5x2 as follows

1 2 4 6  8
3 5 7 9 10

1  2
3  4
5  6
7  8
9 10

For input [5, 9, 33, 65, 12, 7, 80, 42, 48, 30, 11, 57, 69, 92, 91] output is a 5x3 or 3x5 as follows

 5  7 11 33 57
 9 12 42 65 80
30 48 69 91 92

 5  7 11
 9 12 33
30 42 57
48 65 80
69 91 92

Rules

The input can be assumed to fit in your language's native integer type.
The input and output can be given by any convenient method.
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Jelly, 24 22 20 bytes

pS€ỤỤs
LÆDżṚ$SÞḢç/ịṢ

Try it online!

Saved 2 bytes thanks to @Jonathan Allan.

Explanation

pS€ỤỤs  Helper link. Input: integer a (LHS), integer b (RHS)
p       Cartesian product between [1, 2, ..., a] and [1, 2, ..., b]
 S€     Sum each pair
   Ụ    Grade up
    Ụ   Grade up again (Obtains the rank)
     s  Split into slices of length b

LÆDżṚ$SÞḢç/ịṢ  Main link. Input: list A
L              Length
 ÆD            Divisors
     $         Monadic pair
    Ṛ            Reverse
   ż             Interleave
                 Now contains all pairs [a, b] where a*b = len(A)
      SÞ       Sort by sum
        Ḣ      Head (Select the pair with smallest sum)
         ç/    Call helper link
            Ṣ  Sort A
           ị   Index into sorted(A)


Matlab/Octave Eratosieve using minimal big-O iterations I'm trying to come up with ways to write Sieve of Eratosthenes in Octave that vectorize as much as possible (ie minimizing the number of times iterating over the for-loop/while-loop/recursive call)

I found one that requires only O(log(log(n))) iterations inside the for-loop, but the big-O running time (and also space) is O(n^(5/4)/log(n)) so it's arguably not the Sieve of Eratosthenes

Now I think I have one with the usual running time O(nlog(log(n))) and only O(log(n)) iterations, but I want to see if someone else comes up with a better solution.

Here's my solution
The loop clearly runs O(logn) times and it's easy to see that the number of operations is bounded above by the normal number of operations for SOE(2n) so it's within O(nlog(logn)) big-O running time

function [primes] = eratosieve(n)
    isprime = ones(n, 1);
    isprime(1) = false;
    m = 1;
    while(m ^ 2 < n)
        nprimes = find(isprime(m + 1 : m * 2)) + m;
        mult = (m + 1) : (n/(m + 1));
        a = nprimes * mult;
        isprime(a(a<=n)) = false;
        m *= 2;
    end
    primes = find(isprime);
endfunction


Is it a balanced number? A number is balanced if the sum of the digits on each half of the number is equal, so: 1423 is balanced because 1+4 = 2+3, so is: 42615 because 4+2=1+5. Note that the middle digit is not included on either side (or it's included on both sides) if there's an odd number of digits.

Challenge:

Take a positive integer as input, and output a truthy value if it's balanced and a falsy value if it's unbalanced.

Test cases (true)

1
6
11
141
1221
23281453796004414
523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088

Test cases (false)

10
12
110
15421
5234095123508321
6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454

There will not be numbers starting with zero, for instance 00032 instead of 32. You must support numbers up to at least 100 digits (so larger than 2^64-1). As always, optional input format, so you may surround the number with apostrophes if desired.

05AB1E, 14 7 bytes

€D2äO`Q

Explanation

Using 141 as example:

€D       # duplicate each (turns the number into a list of digits)
         # STACK: ['1','1','4','4','1','1']
  2ä     # split list in 2 (as we duplicated each element,
         # the middle element will exist on both sides for an odd length input
         # STACK: [['1','1','4'],['4','1','1']]
    O    # sum each sublist
         # STACK: [6,6]
     `   # flatten
         # STACK: 6, 6
      Q  # compare for equality
         # STACK: 1 (true)

Try it online!


Shortest terminating program whose output size exceeds Graham's number Write the shortest possible program (length measured in bytes) satisfying the following requirements:

no input
output is to stdout
execution eventually terminates
total number of output bytes exceeds Graham's number

Assume that programs run until "normal" termination on an ideal computer1 able to access unlimited resources, and that the common programming languages are modified if necessary (without changing the syntax) to allow this. Because of these assumptions, we might call this a kind of Gedankenexperiment.

To get things started, here's a 73-byte Ruby program that computes fω+1(99) in the fast-growing hierarchy:

f=proc{|k,n|k>0?n.times{n=f[k-1,n]}:n+=1;n};n=99;n.times{n=f[n,n]};puts n

1 EDIT: More precisely, suppose we're taking an existing system and modifying it only to have no upper limit on storage size (but it is always finite). The execution-times of instructions are not supposed to be modified, but the machine is assumed to be ideal in that it will have no upper limit on its operating lifetime.

Haskell, 59 57 55 63

(f%s)1=s;(f%s)n=f.(f%s)$n-1
main=print$((flip((%3)%(3^))3)%4)66

How it works: % simply takes a function and composes it n-1 times on top of s; i.e. %3 takes a function f and returns a function of n that equals applying it f to 3, n-1 times in a row. If we iterate the application of this higher-order function, we get a fast-growing sequence of functions – starting with exponentiation, it's exactly the sequence of Knuth-arrow-forest sizes:
((%3)%(3^))1 n = (3^)n     = 3ⁿ = 3↑n
((%3)%(3^))2 n = ((3^)%3)n = (3↑)ⁿ⁻¹ $ 3  = 3↑↑n
((%3)%(3^))3 n = (((3^)%3)%3)n = (3↑↑)ⁿ⁻¹ $ 3  = 3↑↑↑n
 and so on. ((%3)%(3^))n 3 is 3 ↑ⁿ 3, which is what appears in the calculation to Graham's number. All that's left to do is composing the function (\n -> 3 ↑ⁿ 3) ≡ flip((%3)%(3^))3 more than 64 times, on top of 4 (the number of arrows the calculation starts with), to get a number larger than Graham's number. It's obvious that the logarithm (what a lamely slow function that is!) of g₆₅ is still larger than g₆₄=G, so if we print that number the output length exceeds G.

⬛


Water held in a hexagonal rod scuplture I have bunch of hexagonal rods glued together into an odd sculpture. The rods
are 1 to 99 centimetres (cm) long and 1 square cm in cross-section area. All
rods are glued on a hexagonal face to at least one other rod. The rods are all
aligned at their bottom edge.

After some heavy rain, the sculpture is full of water. How much water does it
hold?

Input

Your program should read in (via stdin or a file) a number of lines consisting of
pairs of spaces and pairs of digits specifying the length of the rods in this format:

  aa  bb
cc  dd  ee
  ff  gg

Each rod (like dd here) is glued to a maximum of 6 surrounding rods as shown in the examples. Missing rods are holes and do not gather water. For example, the input

  04  04
04  01  03
  04  04

would represent the following sculpture:

The centre rod is height 1 (I didn't find a good angle where that rod is also visible). Now the column above that rod could hold 2 cm of water, before it would overflow over the 3 rod on the right. Since none of the other rods can hold any water above them, the answer would be 2. Here are two more complex examples:

Example 2:
55  34  45  66
  33  21  27
23  12  01  77
  36  31  74
answer = 35 (  2 on top of 21
             +11 on top of 12
             +22 on top of 01, before everything overflows over 23)

Example 3:
        35  36  77  22                      23  32  54  24
      33  07  02  04  21                  54  07  07  07  76
    20  04  07  07  01  20              54  11  81  81  07  76
  20  67  67  22  07  01  78          54  07  81  07  81  09  76
20  67  07  67  22  22  07  44  55  54  07  81  07  07  61  07  20
  67  57  50  50  07  07  14  03  02  15  81  99  91  07  81  04
67  07  50      50  87  39  45  41  34  81  07  07  89  07  81  79
  67  07  50  50  07  07  07  27  07  27  81  07  07  79  81  78
20  67  67  07  07  07  07  99  33  46  02  81  07  07  81  01  20
  33  07  07  01  05  01  92          20  02  81  07  81  15  32
    22  07  20  20  07  20              63  02  80  81  15  32
      45  20  01  20  39                  20  15  07  15  32
        23  20  20  29  43  21  18  41  20  66  66  43  21
      90                  99  47  07  20
    50                      20  02  48
  70                          56  20
                                90

answer = 1432

Output

Your program should output a single integer giving the volume of water in cubic
centimetres.

Score

Your score is the byte count of your source code. Lowest wins.

The standard loopholes are prohibited as usual.

This puzzle was inspired by a
SPOJ Question.

Python 2, 222 bytes

import sys
y=h=v=0;B={}
for l in sys.stdin:
 z=y;y+=2j
 while l:
    if"0"<l:B[z]=int(l[:2])
    l=l[2:];z+=1
while B:C=B;B={b:B[b]for b in B if(h<B[b])+sum(3>abs(c-b)for c in B)/7};a=C==B;h+=a;v+=a*sum(h>B[b]for b in B)
print v

Reads input through STDIN and writes the result to STDOUT.

Explanation

We start at zero and incrementally increase the water level as follows:
Suppose that the water level is h, and we want to add 1 centimeter of water.
We'll call hexagons of height h or less, ones that are about to go (or already are) underwater, "submerged."
The water will spill through any submerged hexagon that isn't surrounded by six neighbors.
We eliminate all such hexagons; of course, now some other submerged hexagons might have less than six neighbors, and they need to be eliminated as well.
We continue in this fashion until convergence, i.e., until all remaining submerged hexagons have exactly six neighbors.
At this point we add the number of submerged hexagons (the gained water volume) to the total count, and increment the water level.

Eventually, all the hexagons will have been eliminated and we halt.


Hello World socket server Write the shortest program that answers "Hello, World" to a network connection.

Conditions:

Program shall listen on port 12345
When a client connects, program shall write "Hello, World" to the newly opened socket connection and then close the connection
Program shall accept connections in a loop, i.e. handle any number of connects
Program does not need to handle parallel connections

Test:

prompt> telnet localhost 12345
Hello, World
prompt>


Draw an ASCII meandering curve For the purpose of this question a meandering curve is one that follows the general direction from left to right, but makes repeatedly n+1 turns at 90 degrees to the left and then n+1 turns to the right (for n>0).

In fact the meander itself will have n segments.

The turns are denoted with +.

The width of the meanders (the distance between two +) is 3 at the horizon (---) and 1 at the vertical (|)

Here are the single segments a meandering curve with sizes n from 1 to 5:

                                                           +-------------------+
                                                           |                   |
                                       +---------------+   |   +-----------+   |
                                       |               |   |   |           |   |
                       +-----------+   |   +-------+   |   |   |   +---+   |   |
                       |           |   |   |       |   |   |   |   |   |   |   |
           +-------+   |   +---+   |   |   +---+   |   |   |   +---+   |   |   |
           |       |   |   |   |   |   |       |   |   |   |           |   |   |
   +---+   +---+   |   +---+   |   |   +-------+   |   |   +-----------+   |   |
   |   | 1     |   | 2         |   | 3             |   | 4                 |   | 5
---+   +-------+   +-----------+   +---------------+   +-------------------+   +

Challenge:

Given two positive numbers n and m, draw m segments of a meandering curve with size n.
You can write a full program or a function.

Input:

n > 0 The size of the curve

m > 0 Number of segments to draw

Output:

An ASCII representation of the meandering curve.

Examples:

n = 3
m = 2
   +-----------+   +-----------+
   |           |   |           |
   |   +---+   |   |   +---+   |
   |   |   |   |   |   |   |   |
   +---+   |   |   +---+   |   |
           |   |           |   |
-----------+   +-----------+   +

n = 2
m = 5
   +-------+   +-------+   +-------+   +-------+   +-------+
   |       |   |       |   |       |   |       |   |       |
   +---+   |   +---+   |   +---+   |   +---+   |   +---+   |
       |   |       |   |       |   |       |   |       |   |
-------+   +-------+   +-------+   +-------+   +-------+   +

n = 4
m = 4
   +---------------+   +---------------+   +---------------+   +---------------+
   |               |   |               |   |               |   |               |
   |   +-------+   |   |   +-------+   |   |   +-------+   |   |   +-------+   |
   |   |       |   |   |   |       |   |   |   |       |   |   |   |       |   |
   |   +---+   |   |   |   +---+   |   |   |   +---+   |   |   |   +---+   |   |
   |       |   |   |   |       |   |   |   |       |   |   |   |       |   |   |
   +-------+   |   |   +-------+   |   |   +-------+   |   |   +-------+   |   |
               |   |               |   |               |   |               |   |
---------------+   +---------------+   +---------------+   +---------------+   +

Winning criteria:

This is code-golf, so the shortest code in bytes in each language wins.
Please explain your code, if you have time to do it.

Charcoal, 52 34 33 bytes

Ｎθ↶ＦＮＦ⊗⊕θ«+⊖⊗×⊕﹪κ²∨↔⁻θ∧κ⊖κ¹¿›κθ↷↶

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

Ｎθ

Input the size of the meander.

↶

Pivot upwards as the drawing starts at the right and works left.

ＦＮ

Loop over the desired number of meanders.

Ｆ⊗⊕θ«

Loop over the segments of the meander.

+

Print a +.

∨↔⁻θ∧κ⊖κ¹

Compute the kth element of the list \$ n, n, n-1, n-2 ... 3, 2, 1, 1, 1, 2, 3, ... n \$.

⊖⊗×⊕﹪κ²...

Alternate between doubling and quadrupling the lengths since the horizontal lines are twice as long, but decrement the result before printing to take account of the + that was just printed.

¿›κθ↷↶

Pivot appropriately for the next segment.


Extract a string from a given string You are given a string and two characters. You have to print the string between these characters from the string.

Input

Input will first contain a string (not empty or null). In the next line, there will be two characters separated by a space.

Challenge

Return the string between the two characters

Example

Hello! What's your name?
! ?

should result in the output:

" What's your name"

Rules

The string will not be longer than 100 characters and will only contain ASCII characters in range (space) to ~(tilde) (character codes 0x20 to 0x7E, inclusive). See ASCII table for reference.
You must take input from the stdin( or closest alternative ).
The output should be surrounded with quotes(").
You can write a full program, or a function which takes input, and outputs the final string
The two characters will only contain ASCII characters in range (space) to ~(tilde) (character codes 0x20 to 0x7E, inclusive). See ASCII table for reference.
There is no guarantee that both the characters will be in the string.
If any of the characters is not found in the string, print "null".
If any of the characters is found more than one times (unless both the characters are same) in a string, print "null".
If both the characters are the same character, print the string "null".

Test Cases

1)

<HTML>code</HTML>
> <                       --> "null"

2)

What's what?
' '                       --> "null"

3)

abcdefghijklmnopqrstuvwxyz
n k                       --> "lm"

4)

Testing...
e T                       --> ""

5)

Last test-case
  -                       --> "test"

Scoring

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

CJam, 34 33 32 bytes

'"l_l2%&2*2>NerN/0"null"t_,3=='"

Try it online in the CJam interpreter.

Idea

Remove the second character from line 2.
Form a string consisting of a single copy of all characters that both lines have in common.
Repeat the resulting string twice and discard its first two characters.

This results in a two-character string (if the characters from line 2 are different and both occur in line 1) or an empty string.
Replace the characters of the resulting string in line 1 by linefeeds.
Split line 1 at linefeeds.

The resulting array's second element will be the desired string if the array contains exactly three chunks.
Replace the first element of the array with the string null.
Retrieve the second element of the array if its length is 3 and the first otherwise.
Prepend and append a double quote.

Code

'"       e# Push a double quote.
l_       e# Read one line from STDIN. Push a copy.
l2%      e# Read one line from STDIN. Only keep characters at odd indexes.
&        e# Intersect both strings.
2*2>     e# Repeat the intersection twice and discard the first two characters.
Ner      e# Replace the characters of the resulting string with linefeeds.
N/       e# Split the result at linefeeds.
0"null"t e# Replace the first element of the resulting array with "null".
_,3=     e# Push 1 if the length of the array is 3 and 0 otherwise.
=        e# Retrieve the corresponding element from the array.
'"       e# Push a double quote.


The meta-polyglot quine In my time on PPCG, I've noticed that quine problems and polyglot problems are quite popular. Also, meta-solutions to problems, that is, scripts which generate a program which is the solution to a problem, tend to get a lot of positive feedback from the community. Therefore, I have created this challenge, which implements these three ideas.

Your task then, reader and code-golf enthusiast, is to create as short as possible a script which can run in two languages A and B to generate quines for A and B. When your program is run in language A, it should generate a program that is a quine in language B but not in language A and vice versa. The languages A and B can be different version of the same language, provided you keep in mind that the generated quines should only work in one of the versions.

Keep in mind that the standard loopholes should be considered closed and only proper quines are allowed.

Good luck, fewest characters wins!

CJam / Fission, 22 bytes

"'!+OR'")5-"{'_'~}_~";

Try it in CJam. Try it in Fission.

In CJam, this prints the standard Fission quine:

'!+OR"

Try the Fission quine.

In Fission, this prints a "-less variant of the standard CJam quine:

{'_'~}_~

Try the CJam quine.

This also works for 22 bytes (printing the same quines):

"& *NQ!":)R"{'_'~}_~";

Explanation

In CJam:

"'!+OR'"    e# Push this string.
)           e# Pull off the last character.
5-          e# Subtract 5, turning ' into ".
"{'_'~}_~"  e# Push this string.
;           e# And discard it again.

So at the end of the program, the stack contains the string "'!+OR" and the character ", both of which are implicitly printed.

In Fission, program flow starts at the R with a right-going atom. '" just changes the atoms mass, ), 5 and - are ignored for various reasons. Then the atom enters print mode at the " and prints {'_'~}_~. ; destroys the atom and terminates the program.


Make a ;#*:) interpreter A few month back, I made a language called ;# (Semicolon Hash) and it started a little bit of a craze (it even got its own tag, as you can see). But, as with everything, the craze died down, and questions related to it stopped being posted.

However, a few people were annoyed at the lack of capability of ;# and this lead to someone creating a Turing complete version. Eventually, I decided to create ;# 2.0 with an extended set of commands:

; - Increment the accumulator
# - Modulo the accumulator by 127, output as ASCII character and reset the accumulator to 0
: - Open a while loop
) - Close a while loop. You can assume that all loops will be closed.
* - Take a byte of input, and add it to the accumulator. Input is recycled, so if the end of the input is reached, it wraps around to the start.

FYI: ;#*:) still isn't Turing complete

For example, a cat program would be

*:#*)

*     - Take a byte of input
 :  ) - While the input character is not a null byte...
  #   -   Print as character
   *  -   Take a byte of input

For this, the input must be terminated with a null byte, otherwise the program will repeat the input until the heat death of the universe.

and to add two numbers (input and output as char codes):

**#

*   - Take input (e.g. \x02); A=2
 *  - Take input (e.g. \x03); A=5
  # - Output A as character (\x05)

Your task is to interpret ;#*:). Your program/function will be given 2 inputs, the program and the program's input, and you have to interpret the given program.

A few rules:

1) Your program may not halt termination due to an error unless 2) happens. Output to STDERR is allowed, just so long as it doesn't affect the program's execution.

2) If the second input is empty (a ;#*:) program with no input) and * occurs in the code, you don't have to handle the error and can cause any kind of behaviour you want; summon Cthulhu, make Dennis lose his rep, anything you want.

3) All characters that aren't ;#*:) are ignored and have no effect on anything.

Nested loops can happen, and all loops will be closed, so ;:*:#*);) is valid code

This is a code golf, so shortest code wins.

Some tests to check your program against:

program, input (as ASCII characters; \xxx is a byte literal) => output

*#*:#*), "1" => 11111111...
**#, "12" => c
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#, "abc" => Hello, World!
*#, "" => undefined
Hello, World!, "" => (nothing)
*:#*):;#*)*#, "Hello,\x00World!" => Hello,W
*:#*), "Testing\x00" => Testing
*:#*), "Testing" => TestingTestingTestingTesting...
;:*:#*);*), "123\x00" => 223d3d3d...

And, to help you even more, this is an ungolfed reference implementation in Python. In this version, I have decided to make the * on empty input be ignored.

Good luck!

Ruby, 147 144 bytes

Saved 3 bytes thanks to m-chrzan!

z=STDIN.read
eval ARGV[i=a=0].gsub(/./){|e|"#{{?;=>"a+=1",?#=>"putc(a%127);a=0",?:=>"while a>0",?)=>"end",?*=>"a+=z[i%=z.size].ord;i+=1"}[e]};"}

Try it online!

Program is taken from first command line argument.


Hello, Permutations! For this challenge, you will be required to write 3 programs:

The first program should be a quine, i.e, it should print it's own source code.
The second program should read the input and print all of it.
The third program should simply print the string "Hello, Permutations!", with or without quotes.

In addition to that, all the three programs should be permutations, i.e, starting from any of the three programs, you should be able to obtain the other by re-arranging it's characters. So all programs will have the same byte count and frequency of characters. For example: abcd, dbca and adbc are permutations.
Rules

You may choose to write functions instead of programs.

For the first program, you are not allowed to read the source file and print it.

You only need to read the input for the second program. No input will be provided to the other two programs.

Standard loopholes are forbidden.

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

Underload (stringie), 33 bytes each
((aS(:^):SHello, Permuttions!):^)
(S(Hello, Permutations!)(:::^^S))
((Hello, Permutations!)S(:::^^S))

Try it online!
These are function submissions that input via the argument stack, but output to standard output. (The functions also produce garbage output using the more normal mechanism for function output, but according to our normal I/O rules, we only look in one place.)
Explanations
(aS(:^):SHello, Permuttions!):^
(aS(:^):SHello, Permuttions!)     string literal
                             :    non-destructive
                              ^     eval
 a                                enclose {the string literal} in parens
  S                               print it
   (:^)                           string literal
        S                         print that too
       :                          retaining a copy
         Hello, Permuttions       no-ops
                           !      discard the retained copy

S(Hello, Permutations!)(:::^^S)
S                                 print {function input}
 (Hello, Permutations!)           string literal {2nd return value}
                       (:::^^S)   string literal {1st return value}

(Hello, Permutations!)S(:::^^S)
(Hello, Permutations!)            string literal
                      S           print it
                       (:::^^S)   string literal {return value}

If we weren't exploiting this site's I/O rules, it'd cost one extra byte (along with a little code rearrangement) to output the output we wanted (either to standard output or as the function return value), and delete the output we didn't want. But just leaving the extra characters that we're forced to use in order to make a permutation on the argument stack is very slightly shorter.
The quine is an eval quine: we write most of the program in a string literal and eval it, but we still have the original string literal available (because we made the eval non-destructive) and can print it in addition to running it. (This isn't code reading itself, rather the :^ reads one string and uses it for two different purposes.)


Levenshtein distance & OEIS (Cops) This is the Cop post. The Robber post is here.

Your task is to take an integer input N and output the Nth digit in the sequence OEIS A002942.

The sequence consists of the square numbers written backwards:

1, 4, 9, 61, 52, 63, 94, 46, 18, 1, 121, 441, ...

Note that leading zeros are trimmed away (100 becomes 1, not 001). Concatenating this into a string (or one long number gives):

1496152639446181121441

You shall output the Nth digit in this string/number. You may choose to take N as 0-indexed or 1-indexed (please state which one you choose).

Test cases (1-indexed):

N = 1,      ==> 1
N = 5,      ==> 1
N = 17,     ==> 1   <- Important test case! It's not zero.
N = 20,     ==> 4
N = 78,     ==> 0
N = 100,    ==> 4

Your code should work for numbers up to N = 2^15 (unless your language can't handles 32 bit integers by default, in which case N can be lower).

Cops:

You must write two functions/programs, in the same language, that do the same thing. You have to post one of the functions/programs, as well as the Levenshtein distance between the two functions/programs you have written. The Levenshtein distance is measured in characters (so addition of a two byte character will give a LD = 1).

The unrevealed code can not be longer than the original solution (but it can be the same size). The robbers will attempt to write a code with the exact Levenshtein distance you gave (it can be different from your unrevealed code, as long as it works).

The winner will be the uncracked submission that has the lowest Levenshtein distance.

You may check the Levenshtein distance here!

If your submission goes uncracked for 7 days then you may reveal the alternative code you have written and mark your submission as safe.

Haskell, LD = 13, cracked

((snd.span(<'1').reverse.show.(^2)=<<[1..])!!)

Try it online!

I double-checked that leading zeros are trimmed ;)

Explanation:

                    [1..]     -- for each element in [1,2,3,4,5,...]
                 =<<          -- apply the following functions
             (^2)             -- square [1,4,9,16,25,...]
           show.              -- convert to string ["1","4","9","16","25",...]
       reverse.               -- reverse ["1","4","9","61","52",...,"001",...]
   span(<'1').                -- split into leading zeros and remainder [("","1"),("","4"),...,("00","1"),...]
  snd.                        -- only keep remainder ["1","4","9","61","52",...,"1",...]
                              -- and concatenate the result "1496152..."
((                       )!!) -- index into the sequence


Find the number of n-by-n (-1, 0, 1) matrices with zero permanent as quickly as possible The permanent of an \$n\$-by-\$n\$ matrix \$A = (a_{i,j})\$ is defined as:

$$\operatorname{perm}(A)=\sum_{\sigma\in S_n}\prod_{i=1}^n a_{i,\sigma(i)}$$

For a fixed \$n\$, consider the \$n\$-by-\$n\$ matrices whose entries are taken from \$\{-1, 0, +1\}\$ .

Task

For each \$n\$ from 1 upwards, output the number of \$n\$-by-\$n\$ \$(-1, 0, 1)\$ matrices with zero permanent.

The output format looks like this:

n = 1, 1
n = 2, 33
n = 3, 7555
n = 4, 13482049
n = 5, 186481694371
n = 6, ...

Score

Your score is the largest \$n\$ your code gets to in 20 minutes in total on my computer, this is not 20 minutes per \$n\$.

If two entries get the same \$n\$ score, then the winning entry will be the one that gets to the highest \$n\$ in the shortest time on my machine. If the two best entries are equal on this criterion too then the winner will be the answer submitted first.

You are in no way allowed to hard-code solutions.

Languages and libraries

You can use any freely available language and libraries you like. I must be able to run your code so please include a full explanation for how to run/compile your code in windows if at all possible.

My Machine

The timings will be run on my machine, Intel Core i7-9750H 6 cores, 12 threads, The machine runs Windows 10.

Updated

Brute forcing every matrix (of which there are \$3^{n^2}\$) is not necessarily a particularly good answer, especially since there are many symmetries that preserve the value of the permanent. Thanks for @isaacg.

Rust, \$A(5) = 186481694371\$ in 0.2 s, \$A(6) = 19733690332538577\$ in 580 s

(Unofficial times on a Core i7-10710U with 6 cores/12 threads.)

src/main.rs

use itertools::Itertools;
use num_integer::gcd;
use rayon::prelude::*;
use std::cmp::Ordering;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::sync::Mutex;

type Count = u64;
type Coeff = i32;

fn sort_scols(n: u32, i: u32, sets: &[u32], state: &[Coeff]) -> Vec<u32> {
    let mut scol_ranks: Vec<u32> = (0..2 * n).map(|scol| (scol >> 1 > i) as u32).collect();
    let mut sorted_scols: Vec<u32> = (0..2 * n).collect();
    let mut scol_descs = vec![vec![]; 2 * n as usize];
    for (set_index, (&set, &coeff)) in sets.iter().zip(state).enumerate() {
        if coeff != 0 {
            for col in 0..n {
                if set & 1 << col != 0 {
                    scol_descs[(col as usize) << 1].push(set_index);
                    scol_descs[(col as usize) << 1 | 1].push(set_index);
                }
            }
        }
    }
    let mut sorted_set_indexes: Vec<_> = (0..sets.len()).collect();
    let mut set_ranks: Vec<u32> = vec![!0; sets.len()];
    let mut set_descs = vec![(0, vec![]); sets.len()];

    while {
        for (&coeff, set_desc) in state.iter().zip(&mut set_descs) {
            set_desc.0 = coeff;
            set_desc.1.clear();
        }
        let mut seen = 0;
        for &scol in &sorted_scols {
            if seen & 1 << (scol >> 1) == 0 {
                seen |= 1 << (scol >> 1);
                if scol & 1 == 0 {
                    for (&set, set_desc) in sets.iter().zip(&mut set_descs) {
                        if set_desc.0 != 0 && set & 1 << (scol >> 1) != 0 {
                            set_desc.1.push(scol_ranks[scol as usize]);
                        }
                    }
                } else {
                    for (&set, set_desc) in sets.iter().zip(&mut set_descs) {
                        if set_desc.0 != 0 && set & 1 << (scol >> 1) != 0 {
                            set_desc.0 = -set_desc.0;
                            set_desc.1.push(scol_ranks[scol as usize]);
                        }
                    }
                }
            }
        }

        let set_index_key =
            |&set_index: &usize| (set_descs[set_index].0.abs(), &set_descs[set_index].1);
        sorted_set_indexes.sort_by_key(set_index_key);
        if sets.len() != 0 {
            let mut next_set_rank = 0;
            set_ranks[sorted_set_indexes[0]] = next_set_rank;
            for (&set_index0, &set_index1) in sorted_set_indexes.iter().tuple_windows() {
                if set_index_key(&set_index0) < set_index_key(&set_index1) {
                    next_set_rank += 1;
                }
                set_ranks[set_index1] = next_set_rank;
            }
        }

        let scol_set_index_key = |scol: u32| {
            let sign = 1 - 2 * (scol & 1) as Coeff;
            let set_ranks = &set_ranks[..];
            let set_descs = &set_descs[..];
            move |&set_index: &usize| (set_ranks[set_index], set_descs[set_index].0 * sign)
        };
        for (scol, scol_desc) in scol_descs.iter_mut().enumerate() {
            scol_desc.sort_by_key(scol_set_index_key(scol as u32));
        }
        let scol_cmp = |&scol0: &u32, &scol1: &u32| {
            scol_ranks[scol0 as usize]
                .cmp(&scol_ranks[scol1 as usize])
                .then_with(|| {
                    scol_descs[scol0 as usize]
                        .iter()
                        .map(scol_set_index_key(scol0))
                        .cmp(
                            scol_descs[scol1 as usize]
                                .iter()
                                .map(scol_set_index_key(scol1)),
                        )
                })
        };
        sorted_scols.sort_by(scol_cmp);

        let mut new_scol_ranks = vec![!0; 2 * n as usize];
        let mut next_rank = 0;
        let mut changed = false;
        new_scol_ranks[sorted_scols[0] as usize] = next_rank;
        for (&scol0, &scol1) in sorted_scols.iter().tuple_windows() {
            if scol_ranks[scol0 as usize] < scol_ranks[scol1 as usize] {
                next_rank += 1;
            } else if scol_cmp(&scol0, &scol1) == Ordering::Less {
                changed = true;
                next_rank += 1;
            }
            new_scol_ranks[scol1 as usize] = next_rank;
        }
        scol_ranks = new_scol_ranks;

        changed
    } {}

    let mut seen = 0;
    sorted_scols.retain(|scol| {
        seen & 1 << (scol >> 1) == 0 && {
            seen |= 1 << (scol >> 1);
            true
        }
    });
    assert_eq!(seen, !(!0 << n));

    sorted_scols
}

fn count(n: u32) -> Count {
    static ERR: &str = "n is too large";
    Count::checked_pow(3, TryFrom::try_from(n * n).expect(ERR)).expect(ERR);
    (1..=Coeff::try_from(n).expect(ERR)).fold(1, |x: Coeff, y| x.checked_mul(y).expect(ERR));

    let mut cur_sets = vec![0];
    let mut cur_set_indexes = vec![0];

    let mut cur_states = HashMap::new();
    cur_states.insert(vec![1], 1);

    for k in 0..n {
        for i in 0..n {
            let keep_set = |&set: &u32| {
                if set.count_ones() == k {
                    !set & !1 << i & !(!0 << n) != 0
                } else {
                    set & 1 << i == 0
                }
            };
            let enlarge_set = |&set: &u32| set.count_ones() == k && set & 1 << i == 0;
            let new_sets: Vec<u32> = cur_sets
                .iter()
                .copied()
                .filter(keep_set)
                .chain(
                    cur_sets
                        .iter()
                        .copied()
                        .filter(enlarge_set)
                        .map(|set| set | 1 << i),
                )
                .collect();
            let mut new_set_indexes = vec![!0; 1 << n];
            for (set_index, &set) in new_sets.iter().enumerate() {
                new_set_indexes[set as usize] = set_index;
            }

            let new_states = Mutex::new(HashMap::new());
            cur_states.into_par_iter().for_each(|(cur_state, count)| {
                for elt in -1..=1 {
                    let mut new_state: Vec<Coeff> = cur_sets
                        .iter()
                        .copied()
                        .zip(&cur_state)
                        .filter(|(set, _)| keep_set(set))
                        .map(|(_, &coeff)| coeff)
                        .chain(
                            cur_sets
                                .iter()
                                .copied()
                                .zip(&cur_state)
                                .filter(|(set, _)| enlarge_set(set))
                                .map(|(set, &coeff)| {
                                    let mut new_coeff = coeff * elt;
                                    if set & !(!0 << i) != 0 {
                                        new_coeff +=
                                            cur_state[cur_set_indexes[set as usize | 1 << i]];
                                    }
                                    new_coeff
                                }),
                        )
                        .collect();

                    let factor = new_state.iter().copied().fold(0, gcd);
                    if factor > 1 {
                        for coeff in &mut new_state {
                            *coeff /= factor;
                        }
                    }

                    let sorted_scols = sort_scols(n, i, &new_sets, &new_state);

                    let new_state: Vec<Coeff> = new_sets
                        .iter()
                        .map(|&set| {
                            let mut permuted_set = 0;
                            let mut sign = 0;
                            for (col, &permuted_scol) in sorted_scols.iter().enumerate() {
                                sign ^= set >> col & permuted_scol & 1;
                                permuted_set |= (set >> col & 1) << (permuted_scol >> 1);
                            }
                            (1 - 2 * sign as Coeff)
                                * new_state[new_set_indexes[permuted_set as usize] as usize]
                        })
                        .collect();

                    *new_states.lock().unwrap().entry(new_state).or_insert(0) += count;
                }
            });

            cur_sets = new_sets;
            cur_set_indexes = new_set_indexes;
            cur_states = new_states.into_inner().unwrap();
        }
    }

    *cur_states.get(&vec![0]).unwrap_or(&0)
}

fn main() {
    for n in 1..=6 {
        println!("{} {}", n, count(n));
    }
}

Cargo.toml

[package]
name = "permanent"
version = "0.1.0"
authors = ["Anders Kaseorg <andersk@mit.edu>"]
edition = "2018"

[dependencies]
num-integer = "0.1.41"
rayon = "1.2.1"
itertools = "0.8.2"

Building and running

$ cargo build --release
$ time target/release/permanent
1 1
2 33
3 7555
4 13482049
5 186481694371
6 19733690332538577
5995.30user 282.67system 9:42.97elapsed 1076%CPU (0avgtext+0avgdata 6479028maxresident)k
0inputs+0outputs (0major+3259222minor)pagefaults 0swaps

How it works

This counts matrices using dynamic programming so we don’t need to enumerate all of them directly.  Basically, the state of a partially filled matrix is represented by the coefficients of an expression for the permanent as a polynomial in the remaining unfilled elements.  Specifically, it corresponds to a partial execution of the following algorithm for calculating the permanent:

\$\operatorname{perm} A = c_{\{0, 1, \dotsc, n - 1\}}\$, where \$c_\varnothing = 1\$, \$c_S = \sum_{i \in S} c_{S \smallsetminus \{i\}}a_{|S| - 1, i}\$ for \$S \ne \varnothing\$.

For example, here’s the \$n = 4\$ calculation written out explicitly:

c = 1

c0 = c * a00
c1 = c * a01
c2 = c * a02
c3 = c * a03

c01  = c1 * a10; c02  = c2 * a10; c03  = c3 * a10
c01 += c0 * a11; c12  = c2 * a11; c13  = c3 * a11
c02 += c0 * a12; c12 += c1 * a12; c23  = c3 * a12
c03 += c0 * a13; c13 += c1 * a13; c23 += c2 * a13

c012  = c12 * a20; c013  = c13 * a20; c023  = c23 * a20
c012 += c02 * a21; c013 += c03 * a21; c123  = c23 * a21
c012 += c01 * a22; c023 += c03 * a22; c123 += c13 * a22
c013 += c01 * a23; c023 += c02 * a23; c123 += c12 * a23

c0123  = c123 * a30
c0123 += c023 * a31
c0123 += c013 * a32
c0123 += c012 * a33

return c0123

After executing each line, we can forget the filled elements a… and represent the current state with just the c… variables that are still live.  This representation collapses many different partially filled matrices into the same coefficient vector.  For example, swapping any two filled rows results in the same coefficient vector.

The sort_scols function further collapses the state space by using the symmetries of column permutations and column sign flipping to try to find a canonical representation for each state.  It doesn’t do a perfect job, but this imperfection only impacts performance, not correctness.


Word Length-Sum Multiples A port of my other question: Double Prime Words
Consider a word/string of n alphanumeric characters with sum of the characters, s, using their numeric position in the alphabet (a=1, B=2, c=3, etc.) or numeric value (0,1, 2, 3 - 9). Numeric characters should be taken at individual value. (66 is two 6 characters for a sum of 12)
A word is a Length-Sum Multiple if and only if s is a multiple of n, specifically s/n is a positive integer {1,2,3,4...}. In the case of s=0, and n={0,00,000,...}, 0 is a multiple of any n but it does not yield a positive integer. Hence an input of {0,00,000,...} is False.
Input can be any combination of numbers and upper or lower case alphabetic characters, as there is no numeric difference between a or A. Handling empty input, n=s=0, is not required.
Output is any appropriate logical format related to your language. i.e. True or False, T or F, 1 or 0, positive for truthy and 0 for falsy, etc. Specifying what format your output will appear is highly appreciated, but not required. (Output need not include n or s, but I include them below as demonstration and example)
Winning condition: In as few bytes as possible, write a function that is able to determine if a string is a Length-Sum Multiple.
Examples
Input -> Output (n,s)

hello -> False (5, 52)
MuLtIpLe -> False (8, 108)
Junct10n -> False (8, 83)
Order66 -> False (7, 72)
CodeGolf -> False (8, 67)
SUM -> False (3, 53)
ID -> False (2, 13)

25 -> False (2, 7)
0 -> False (1, 0) 0/1 = 0 which is not a positive integer
10 -> False (2, 1)

hello2 -> True (6, 54)
5um -> True (3, 39)
length -> True (6, 66)
Order64 -> True (7, 70)
Covid19 -> True (7, 63)
Word -> True (4, 60)
APPLE -> True (5, 50)
lawYER -> True (6, 84)
abc123 -> True (6, 12)
is -> True (2, 28)
television -> True (10, 130)
19 -> True (2, 10)
234 -> True (3, 9)

a -> True (1, 1)
b -> True (1, 2)
C -> True (1, 3)
Z -> True (1, 26)
1 -> True (1, 1)
9 -> True (1, 9)

05AB1E, 16 15 bytes
þIáÇ32%«ODXgÖ*Ā

Input as a list of characters.
-1 byte implicitly thanks to @ovs.
Try it online or verify all test cases.
Explanation:

þ                # Only leave the digits of the (implicit) input-list
 Iá              # Push the input-list again, and only leave its letters
   Ç             # Convert each letter to its codepoint integer
    32%          # Take modulo-32 on each codepoint
       «         # Merge it to the list of digits
        O        # Sum this list
         D       # Duplicate this sum
          Ig     # Push the input-list again, and pop and push its length
            Ö    # Check if the sum is divisible by this length
             *   # Multiply it by the duplicated sum
              Ā  # And check that this is NOT 0
                 # (after which the result is output implicitly)

3 bytes (D*Ā) are used for edge-cases 0/00/000/etc.


Optimize the Scralphabet Scralphabet
A normal bag of Scrabble tiles contains the following letters (? is a blank tile, which can stand for any other letter):
AAAAAAAAABBCCDDDDEEEEEEEEEEEEFFGGGHHIIIIIIIIIJKLLLLMMNNNNNNOOOOOOOOPPQRRRRRRSSSSTTTTTTUUUUVVWWXYYZ??

The letters have the following value:
{"A": 1,"B": 3,"C": 3,"D": 2,"E": 1,"F": 4,"G": 2,"H": 4,"I": 1,"J": 8,"K": 5,"L": 1,"M": 3,"N": 1,"O": 1,"P": 3,"Q": 10,"R": 1,"S": 1,"T": 1,"U": 1,"V": 4,"W": 4,"X": 8,"Y": 4,"Z": 10,"?": 0}

Given a normal bag of Scrabble tiles, construct the highest-scoring set of non-intersecting words (i.e., individual words, not on a Scrabble board) given the following conditions:

The score for each word is sum(letter_values) * length(word).
You may only include a maximum of one word starting with each letter of the alphabet (so, a maximum of 26 words).
Only valid Scrabble words (from this dictionary) may be included. You may read the dictionary from a file, hard-code it (ugh), or scrape it from the website.
You need not use every tile, but all unused tiles form a single word, scored the same way, which subtracts from your score.

If you wish, your code may accept two inputs: the bag contents as a string, and the letter values in some format similar to a python dict (as above); alternatively, you can hard-code the bag contents and letter values. It should output the words in your set, their respective scores, and your total score, in some reasonable format.
Highest scoring set of words wins, with ties going to first posted.

C, 2765 (optimal)

Edit

Now all in a single C file. This just finds all the optimal solutions. They all must have 6 words of 15 letters and one 10-letter word consisting of 8 letters of value 1 and two blanks. For that I only need to load a fraction of the dictionary and I don't have to look for 15 letter words with blanks.
The code is a simple exhaustive depth-first search.

#include <stdio.h>
#include <stdint.h>
#include <string.h>
struct w {
    struct lc { uint64_t hi,lo; } lc;
    char w[16];
} w15[6000], w10[40000];
int n15,n10;
struct lc pool = { 0x12122464612, 0x8624119232c4229 };
int pts[27] = {0,1,3,3,2,1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8,4,10};
int f[27],fs[26], w15c[27],w15l[27][6000];
int count(struct lc a, int l) { return (l < 16 ? a.lo << 4 : a.hi) >> 4*(l&15) & 15; }
int matches_val(uint64_t a, uint64_t b) {
    uint64_t mask = 0x1111111111111111ll;
    return !((a - b ^ a ^ b) & mask);
}
int matches(struct lc all, struct lc a) { return matches_val(all.hi,a.hi) && matches_val(all.lo,a.lo); }
int picks[10];
void try(struct lc cur, int used, int level) {
    int c, i, must;
    if (level == 6) {
    for (i = 0; i<27; i++) if (count(cur, i) && pts[i]>1) return;
    for (i = 0; i < n10; i++) if(!(used & (1 << (w10[i].w[0] & 31))) && matches(w10[i].lc, cur)) {
        for (c = 0; c<level; c++) printf("%s ",w15[picks[c]].w);
        printf("%s\n",w10[i].w);
    }
    return;
    }
    for (i = 0; i < 26;i++) if (count(cur,fs[i])) break;
    must = fs[i];
    for (c = 0; c < w15c[must]; c++) { i = w15l[must][c]; if(!(used & (1 << (w15[i].w[0] & 31))) && matches(cur, w15[i].lc)) {
    struct lc b = { cur.hi - w15[i].lc.hi, cur.lo - w15[i].lc.lo };
    picks[level] = i;
    try(b, used + (1 << (w15[i].w[0] & 31)), level+1);
    }}
}
int cmpfs(int *a, int *b){return f[*a]-f[*b];}
void ins(struct w*w, char *s, int c) {
    int i;
    strcpy(w->w,s);
    for (;*s;s++)
    if (*s&16) w->lc.hi += 1ll << 4*(*s&15); else w->lc.lo += 1ll << 4*(*s&15) - 4;
    if (c) for (i = 0; i < 27;i++) if (count(w->lc,i)) f[i]++, w15l[i][w15c[i]++] = w-w15;
}
int main() {
    int i;
    char s[20];
    while(scanf("%s ",s)>0) {
    if (strlen(s) == 15) ins(w15 + n15++,s,1);
    if (strlen(s) == 10) ins(w10 + n10++,s,0);
    }
    for (i = 0; i < 26;i++) fs[i] = i+1;
    qsort(fs, 26, sizeof(int), cmpfs);
    try(pool, 0, 0);
}

Usage:

$time ./scrab <sowpods.txt
cc -O3    scrab.c   -o scrab
JUXTAPOSITIONAL DEMISEMIQUAVERS ACKNOWLEDGEABLY WEATHERPROOFING CONVEYORIZATION FEATHERBEDDINGS LAURUSTINE
JUXTAPOSITIONAL DEMISEMIQUAVERS ACKNOWLEDGEABLY WEATHERPROOFING CONVEYORIZATION FEATHERBEDDINGS LUXURIATED
JUXTAPOSITIONAL DEMISEMIQUAVERS ACKNOWLEDGEABLY WEATHERPROOFING CONVEYORIZATION FEATHERBEDDINGS LUXURIATES
JUXTAPOSITIONAL DEMISEMIQUAVERS ACKNOWLEDGEABLY WEATHERPROOFING CONVEYORIZATION FEATHERBEDDINGS ULTRAQUIET
JUXTAPOSITIONAL DEMISEMIQUAVERS ACKNOWLEDGEABLY WEATHERPROOFING CONVEYORIZATION FEATHERBEDDINGS UTRICULATE
JUXTAPOSITIONAL DEMISEMIQUAVERS WEATHERPROOFING ACKNOWLEDGEABLY CONVEYORIZATION FEATHERBEDDINGS LAURUSTINE
JUXTAPOSITIONAL DEMISEMIQUAVERS WEATHERPROOFING ACKNOWLEDGEABLY CONVEYORIZATION FEATHERBEDDINGS LUXURIATED
JUXTAPOSITIONAL DEMISEMIQUAVERS WEATHERPROOFING ACKNOWLEDGEABLY CONVEYORIZATION FEATHERBEDDINGS LUXURIATES
JUXTAPOSITIONAL DEMISEMIQUAVERS WEATHERPROOFING ACKNOWLEDGEABLY CONVEYORIZATION FEATHERBEDDINGS ULTRAQUIET
JUXTAPOSITIONAL DEMISEMIQUAVERS WEATHERPROOFING ACKNOWLEDGEABLY CONVEYORIZATION FEATHERBEDDINGS UTRICULATE
OVERADJUSTMENTS QUODLIBETARIANS ACKNOWLEDGEABLY WEATHERPROOFING EXEMPLIFICATIVE HYDROGENIZATION RUBIACEOUS
OVERADJUSTMENTS QUODLIBETARIANS WEATHERPROOFING ACKNOWLEDGEABLY EXEMPLIFICATIVE HYDROGENIZATION RUBIACEOUS

real    0m1.754s
user    0m1.753s
sys 0m0.000s

Note every solution is printed twice because when adding a 15-letter 'W' word 2 orders are created because there are 2 'W' tiles.

The first solution found with the point breakdown:

JUXTAPOSITIONAL 465
DEMISEMIQUAVERS 480
ACKNOWLEDGEABLY 465
WEATHERPROOFING 405
CONVEYORIZATION 480
FEATHERBEDDINGS 390
LAURUSTINE (LAURU?TI?E) 80
no tiles left

Edit: explanation

What makes searching the entire space possible? While adding a new word I only take into account words that have the rarest remaining letter. This letter need to be in some word anyway (and a 15 letter word since this will be a non 1-value letter, though I don't check for that). So I start with words containing J, Q, W, W, X, Z which have counts around 50, 100, 100, 100, 200, 500. At lower levels I get more cutoff because some words are eliminated by the lack of letters. Breadth of the search tree at each level:

0: 1
1: 49
2: 3046
3: 102560
4: 724040
5: 803959
6: 3469

Of course a lot of cutoff is gained by not checking non-optimal solutions (blanks in 15 letter words or shorter words). So it is lucky that 2765 solution can be achieved with this dictionary (but it was close, only 2 combinations of 15 letter words give a reasonable leftover). On the other hand it is easy to modify the code to find lower scoring combinations where not all the leftover 10 letters are 1-valued, though it would be harder to prove this would be an optimal solution.

Also the code shows classic case of premature optimization. This version of matches function makes the code only 30% slower:

int matches(struct lc all, struct lc a) {
    int i;
    for (i = 1; i < 27; i++) if (count(a, i) > count(all, i)) return 0;
    return 1;
}

I even figured out how to make the bit magic parallel comparison even shorter than in my original code (highest nibble cannot be used in this case, but this is not a problem, as I only need 26 out of 32 nibbles):

int matches_val(uint64_t a, uint64_t b) {
    uint64_t mask = 0x1111111111111111ll;
    return !((a - b ^ a ^ b) & mask);
}

But it gives zero advantage.

Edit

Writing the explanation above I realized that most of the time is spent on scanning the list of words for those containing a specific letter not in the matches function. Calculating the lists upfront gave 10x speedup.


Finding The nth Prime such that the prime - 1 is divisible by n Problem
The goal is as the title says to find the \$n\$th prime such that \$\text{the prime}-1\$ is divisible by \$n\$.
Explanation
Here is an example so you understand the question, this is not necessarily the way it ought to be solved. It merely as a way to explain the question
given \$3\$ as an input we would first look at all the primes
 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 ...

Then we select the primes such that \$\text{the prime}-1\$ is divisible by \$n\$ (3 in this case)
 7 13 19 31 37 43 61 67 73 79 97 103 107 109 127 ...

We then select the \$n\$th term in this sequence
We would output \$19\$ for an input of \$3\$
Note
We can also think of this as the \$n\$th prime in the sequence \$\{1, n + 1, 2n + 1, 3n + 1 ...kn + 1\}\$ where \$k\$ is any natural number
Test Cases
  1 --> 2
  2 --> 5
  3 --> 19
  4 --> 29
100 --> 39301
123 --> 102337

05AB1E, 9 8 bytes

05AB1E uses CP-1252 encoding.

Saved a byte thanks to Osable

µN¹*>Dp½

Try it online!

Explanation

µ          # for N in [1 ...] loop until counter == input
 N¹*>      # N*input+1 (generate multiples of input and increment)
     D     # duplicate
      p½   # if prime, increase counter
           # implicitly output last prime


Shortest Substring Index I'm a lazy but efficient person, as many of you probably are as well. So, whenever I'm doing something I want to do it with minimal effort. Which is why I'm asking you to solve this problem for me.

What I have here is a document of sorts. On every line of this document is a single word or short phrase. The document is not sorted, but that's ok I know where everything is. I could use some help finding things faster, and for that I need a second list. This is where you come in. For every line of text in this document, I need some identifier. Something I can CTRL+F, but it can't be longer than absolutely necessary for getting that one result.

Example input:

(blank)
an apple
spiderman 3
7pm pick up laundry
tequila
fake mustache
dishes on wednesday
banana
biscuits
(blank)

Example output:

ap,3,7,q,f,w,ba,bi

I'm going to repeat myself here, to make sure we're on the same page:

The input is an unformatted text file containing a list of items, separated by line breaks. I have it here in .txt format, it's called "STUFF.TXT"
The first and last line of the document are empty. Every other line contains an entry of length >0.
The file contains only alfanumeric characters (all lower case), spaces, and line breaks.
Desired output is a list of identifiers, in the same order as my original list.
I don't want more than one search word for every list item. If there are multiple answers, pick one, I don't care which. In the above example I picked 'ap' for an apple, but you could have picked 'n ', ' a', 'pp', 'pl' or 'le'. Not 'an', because that's in banana.
I can assure you, the file is never empty, and it never contains duplicates.
If necessary, you can match on the line terminator. But that's a last resort only to be used when there's no other way to distinguish between list items (e.g. 'apple' and 'apples').

Standard loopholes are not allowed. Also, this is code golf so shortest code wins.

One more example:

(blank)
ban
any
king
bean
yen
rake
raki
bar
(blank)

And its output:

ban,ny,g,be,ye,ke,aki,ar

Pyth, 39 bytes
Lsm.:bdtUbKfT.zj\,mhf!}Yjb-Kk+yky++bkbK

Bruteforces all subsets of every string in increasing length and checks if that string occurs inside any other. If that doesn't work, it will do the same except for all subsets of \nstring\n.


Make a word cloud from a text The code should take text from standard input:

The definition of insanity is quoting the same phrase again and again and not expect despair.

The output should be a PNG file containing the word cloud corresponding to that text:

The above word cloud was created using a specialized online application and it filtered the word The and other common words (of, is, and, not, and the). Since this is code golf, the common words will not be filtered and I leave secondary aesthetics of the word cloud to the choice of each coder. Unlike the image exampled here, no words should be excluded, common or otherwise. The definition of a word is defined below.

In this case a word is anything alpha-numeric; numbers are not acting as separators. So, for example, 0xAF qualifies as a word. Separators will be anything that is not alpha-numeric, including .(dot) and -(hyphen). Thus i.e. or pick-me-up would result in 2 or 3 words, respectively. Should be case sensitive - This and this would be two different words,  ' would also be separator so wouldn and t will be 2 different words from wouldn't.

The tags should appear clustered but not overlapping and the font size should be directly proportional to the number of occurrences of that word in the text. The word should appear only once. Specific font color is not required in this case. Semantic association is not a requirement.

Hint - This other code golf could help:
Count the words in a text and display them

Python 3, 363 308 293 274 characters

import os,sys,re,collections as C
c=C.Counter()
n=sys.argv[1]
o="graph d{"
for w in re.findall("\w*",open(n).read()):c[w]+=1
for w,x in c.most_common(75)[1:]:o+="%s[fontsize=%s,shape=none];"%(w,x/5)
open(n+'.dot','w').write(o+"}")
os.system("fdp -Tpng %s.dot>%s.png"%(n,n))

Call it like this: python cloud.py file.txt. The script uses Graphviz's fdp force-directed graph generator to generate the image (it will spit out a GraphViz file to file.txt.dot and a PNG image file to file.txt.png). This means you'll need to have Graphviz installed.

The image above is the cloud it makes of Shakespeare's Hamlet - you can tell, since it contains "To be or not to be". There's also some delightful nonsense to be found:

  It is, to You and I, the Ham of Not thatO lord have us, what now...


Draw an ASCII-O'-Lantern for Halloween Halloween is almost here, the holiday after which most people need to wean themselves off a hollow diet of sugar.

Write a program that takes in a positive integer. If the integer is less than 31 (1 through 30), output this ASCII-art jack-o'-lantern, looking to the right as if looking forward to Halloween:

 _____I_____
| | | | | | |
| | |^| |^| |
| | | |^| | |
| | |VvVvV| |
|_|_|_|_|_|_|

If the input is 31 (the October date Halloween is on), output the same ASCII-o'-lantern, but looking left:

 _____I_____
| | | | | | |
| |^| |^| | |
| | |^| | | |
| |VvVvV| | |
|_|_|_|_|_|_|

If the input is greater than 31, output a bloated-looking ASCII-o'-lantern who probably ate too much candy. He can face either left or right since queasyness can be disorientating. So output:

 _____I_____
| | | | | | |
| |o| |o| | |
| | |^| | | |
| |XXXXX| | |
|_|_|_|_|_|_|

or

 _____I_____
| | | | | | |
| | |o| |o| |
| | | |^| | |
| | |XXXXX| |
|_|_|_|_|_|_|

Whichever you prefer. It may even be different for different numbers above 31.

The shortest code in bytes wins.


Black and white shirt 2 This is a more complicated version of this puzzle. The premise is the same but a few rules differ in a few key places, making for a more complex problem.

Assume I have some number of black shirts and some number of white shirts, both at least 1. Both colors of shirt have a non-zero durability. All shirts of a given color start with the same durability.

Every day, I pick out a clean shirt to wear, and it becomes dirty. Once I run out of all clean black shirts or all clean white shirts, I wash all my dirty shirts of both colors and start over. Clean shirts do not get washed. Whenever a shirt gets washed, its durability goes down by one. Immediately after washing, if the durability of a shirt reaches 0, it must be thrown out.

When picking which shirt to wear of a particular color, I specify whether I choose a shirt with highest (h) or lowest (l) remaining durability.

Challenge:

Take in an arbitrarily long sequence of four indicators (eg. bh bh bl wl bl wh wl bh...) representing my choice of shirt to wear on that day. Continue execution until either my last black shirt or my last white shirt is thrown out. Once this occurs, stop consuming input and print out the remaining shirts’ durabilities.

Inputs:

Number of black shirts, number of white shirts, durability of black shirts, durability of white shirts, and a sequence of shirt selections of arbitrary length at least long enough for one color of shirt to run out (can be considered infinitely long). The selection can be represented by a character pair (eg. bh, bl, wh, wl), or a single character (eg. b, B, w, W). Your choice, as long as there are four distinct inputs of 1 or 2 characters.

Output:

Status of each remaining shirt, sorted by durability. All shirts will be of one color.

Test cases:

The following test cases represent the amount of input the program should need to process before halting. The input is arbitrarily long otherwise.

1 1 1 1 bh
1

1 3 1 10 wh bh
10 10 9

1 5 2 10 wh wh bh wl wl wl bh
10 10 9 8 8

2 5 1 10 bh wh wh wl bl
10 10 9 9 9

1 5 6 5 wl wh bl wl wh bl wl wh bl wl wl bl wl wl wl bl wl wl wl wl bl
4 3 2 1

1 1 1 10 bl wh wh wh wh wh wh wh wh wh wh wh wh
10
#note the processing would stop occurring after the first bl and everything else should be ignored.

General rules:

This is code-golf, so shortest answer in bytes wins.
Default I/O rules apply

Perl 5, 254 bytes

sub f{@s=map[$_>$_[0]||0,$_>$_[0]?$_[3]:$_[2],1],1..$_[0]+$_[1];while(join('',map$$_[0],@s)=~/01|10/){($c,$p)=&{$_[4]};(@w=sort{$p*($$b[1]<=>$$a[1])}grep$$_[2]&&$$_[0]eq$c,@s)[0][2]=0;@s=grep$$_[2]||++$$_[2]&&--$$_[1],@s if@w<2}sort{$b<=>$a}map$$_[1],@s}

Try it online!

Ungolfed but same – with tests:

use Test::More tests=>6;
sub fu {
  my($countb,$countw,$durb,$durw,$get_todays)=@_;            #get 5 inputs
  my @s=( (map{{col=>'b',dur=>$durb,clean=>1}}1..$countb),   #init shirts array
          (map{{col=>'w',dur=>$durw,clean=>1}}1..$countw) );
  while(join('',map$$_{col},@s)=~/bw|wb/){                   #while still both colors left
    my($col,$p) = &$get_todays;                              #todays color and preference
    my @w = grep $$_{clean} && $$_{col} eq $col, @s;         #@w=wearable shirts
    my $shirt = (sort{$p*($$b{dur}<=>$$a{dur})}@w)[0];       #pick todays shirt w/most|least durability left
    $$shirt{clean}=0;                                        #dirty in the evening
    map{$$_{clean}=1;$$_{dur}--}grep!$$_{clean},@s if @w==1; #wash if there was only one this morning
    @s=grep$$_{dur}>0,@s;                                    #toss out worn outs
  }
  return sort{$b<=>$a}map$$_{dur},@s
}
my @test=(
'1 1 1 1 bh',                                                             '1',
'1 3 1 10 wh bh',                                                         '10 10 9',
'1 5 2 10 wh wh bh wl wl wl bh',                                          '10 10 9 8 8',
'2 5 1 10 bh wh wh wl bl',                                                '10 10 9 9 9',
'1 5 6 5 wl wh bl wl wh bl wl wh bl wl wl bl wl wl wl bl wl wl wl wl bl', '4 3 2 1',
'1 1 1 10 bl wh wh wh wh wh wh wh wh wh wh wh wh',                        '10'  #should see sequence not empty
);
while(@test){
  my($countb,$countw,$durb,$durw,@col)=split' ',shift@test;
  my @expected                        =split' ',shift@test;
  my $msg='';
  my $feederu=sub{ (shift(@col)//do{@expected='!',$msg='sequence ran out!'})
                   =~/(.)(.)/;($1,{h=>1,l=>-1}->{$2}) };
  my $feeder=sub{ (shift(@col)//do{@expected='!',$msg='sequence ran out!'})
                   =~/(.)(.)/;($1 eq 'w'||0,{h=>1,l=>-1}->{$2}) };
  my @got=fu($countb,$countw,$durb,$durw,$feederu);
 #my @got=f($countb,$countw,$durb,$durw,$feeder);
  $msg='sequense not empty' if @col;
  is(join(" ",@got),
     join(" ",@expected), $msg);
}


Russian Roulette, varying chances Russian roulette

It's Russian roulette! The rules are simple. Shoot a revolver with n slots for bullets and one round inside at your head and you might not die!
This Question is different from other Russian roulette questions because it takes input to change the chance of exiting with an error.

Task:

Make a program that takes integer n (you can assume that 10<=n<=128) as input and outputs nothing.

  but how do I tell if I'm dead?

The program generates a random number x in the range 0 - n inclusive. If x=0 the revolver fires and the program exits with an error (you die). Otherwise the program exits normally.

If your language needs it, the range can be 1-n inclusive.

Standard loopholes forbidden, etc. Upvote answers in fun languages! What I'd really like to see is an answer in a language that doesn't have normal randomness (eg. in Befunge where ? sends you in a random direction instead of giving a random number).

APL (Dyalog Unicode), 3 bytes

Full program. Exits with code 11 or 0. Requires ⎕IO←0.

÷?⎕

Try it online!

⎕ prompt for n

? generate random integer in range 0…n-1

÷ reciprocal (errors if argument is 0)


Unfurling-Safe Quine Write a proper quine containing at least one newline/linefeed whose every unfurling is either itself a proper quine or outputs the original quine. Your answer can mix and match outputting itself and outputting the original quine.

Unfurlings

Unfurlings consist of:

Appending spaces to make the input a rectangle.
Taking all lines above the bottom one and rotating them a quarter-turn clockwise about the lower-right corner so that the right edge is on the same level as the bottom edge.
Repeat step (2) until the string is a single line to find all unfurlings.

For example, the first unfurling of

GFE
HID
ABC

is

   HG
   IF
ABCDE

and the rest are

   HG
   IF
ABCDE

     IH
ABCDEFG

       I
ABCDEFGH

ABCDEFGHI

This process is automated with this program adapted from Emigna's answer here,where each step of unfurling in the output is delimited by a dashed line.

Example

For example, if you have a program

K
AB

(no trailing spaces)

then it must be a proper quine and print itself('K\nAB', where \n represents a linefeed/newline).
According to the output of the unfurling program, we see that the next step in unfurling is

  K
AB

(note trailing space)

This must either print itself('  K\nAB ') or the original program ('K\nAB').
The next step in the unfurling is

AB K

This must either print itself ('AB K'), or the original program('K\nAB').

The byte-count of this program is 4 (K, \n, A, B).

Score

This is code-golf, so the shortest answer in bytes wins. Standard loopholes apply, as usual.

Python 3, 48 bytes

_='\n_=%r;print(_%%_,end="")';print(_%_,end="")

Try it online!

I mean, it works :p


Different Way Forward Given a list of integers produce a Forward Difference at a specified order/depth.

For the list of integers:

(10, 18, -12, 4, 8, -3, -5, 67, 9, 14)

The Forward Differences at the various orders/depths are:

0   10,   18,  -12,    4,    8,   -3,   -5,  67,  9,  14
1      8,  -30,   16,    4,  -11,   -2,   72, -58,  5
2       -38,   46,  -12,  -15,    9,   74, -130, 63
3           84,  -58,   -3,   24,   65, -204, 193
4            -142,   55,   27,   41, -269, 397
5               197,  -28,   14, -310, 666
6                 -225,   42, -324, 976
7                    267, -366, 1300
8                      -633, 1666
9                         2299

So with the input of

4, (10, 18, -12, 4, 8, -3, -5, 67, 9, 14)

You would return the list

(-142,   55,   27,   41, -269, 397)

Input

The input can be via STDIN or function parameters.

An integer specifying the depth to return.  This will be 0 to the length of the list minus 1

A list of integers to calculate the forward difference for

Output

The output can be via STDOUT or returned by the function.

The forward differences for the specified depth as a list of integers

Rules

Built in and 3rd Party functions that do this directly are not allowed.

Standard loophole restrictions apply.

Shortest code wins

J, 15 9 7 bytes

Very easy. Takes depth and list as left and right arguments.

-~/\~&2

As an explicit definition without all the adverbial trickery, this reduces to

4 : '(2 -~/\ ])^:x y'

-~/\~&2 y – The forwards difference of y.
x -~/\~&2 y – The x-th forwards difference of y.

If I were to make a serious (i. e. non-golfed) definition of this function, I would probably do something like this:

(}. - }:) : ($:@[&0)

The monadic case computes the forward difference whereas the dyadic case computes the x-th forward difference.

Even simpler, but not exactly equal:

+/\inv

+/\ yields a vector of the sums of the prefixes of the argument. inv (defined as ^:_1) is a conjunction that inverses a verb. This works wherever J knows how to inverse a verb and for the case of +/\, J knows how to.


Visualize a Difference Pyramid A difference pyramid is a pyramid where each new diagonal is the absolute value of the differences between the elements of the last diagonal. For example, if we start with the array

2 5 4 9 3 4

Now, we arrange these in a diagonal column:

     2
      5
       4
        9
         3
          4

Now, we fill in the next diagonal. The absolute differences between the consecutive elements of this array are:

3 1 5 6 1

So that is our next diagonal.

     2
    3 5
     1 4
      5 9
       6 3
        1 4

Repeat until the pyramid is filled in:

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

The Challenge

Given a list of positive integers in the range [0, 9], generate this ASCII-art representation of the difference pyramid for that particular array. The input is guaranteed to contain at least two elements. You may take these numbers in any reasonable format. (Array/list/whatever you call it, a string, command line arguments, etc.) Trailing spaces on each line and up to one trailing newline are allowed.

Test IO

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

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

[4, 7]

 4
3 7

[3, 3, 3]

  3
 0 3
0 0 3

[1, 3, 6, 3, 4, 9]

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

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

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

As usual, this is code-golf, so standard loopholes apply, and shortest answer in bytes wins!

Inspired by this OEIS and this conjecture.


count of numbers between A and B (inclusive) that have sum of digits equal to S Task:
Find the count of numbers between A and B (inclusive) that have sum of digits equal to S.
Also print the smallest such number between A and B (inclusive).

Input:
Single line consisting of A, B, and S.

Output:
Two lines.

In first line, the number of integers between A and B having sum of digits equal to S.

In second line, the smallest such number between A and B.

Constraints:

1 <= A <= B < 10^15

1 <= S <= 135

GolfScript, 35 bytes

~:S;),>{.10base{+}*S=!{;}*}%(\,)]n*

How it works

~         # Interpret the input string.
:S;       # Save the last integer in variable “S” and pop it from the stack.
),        # Increment it by 1 and create the array “[0 ... B]”
>         # Remove the first “A” elements. This leaves the array “[A ... B]”
{         # For each of those integers:
  .10base # Push its digits in base 10.
  {+}*    # Add the digits.
  S=!{;}* # If the sum is not equal to “S”, pop the integer from the stack.
}%        # Collect the results into an array.
(\        # Extract the first and swap it below the array.
,)        # Count the elements of the array of all remaining integers and increment by one.
n\        # Separate the results by a newline.


Lowest-Base Palindrome Given a number \$n\$, write a program that finds the smallest base \$b ≥ 2\$ such that \$n\$ is a palindrome in base \$b\$. For example, an input of \$28\$ should return the base \$3\$ since \$28_{10} = 1001_3\$. Although \$93\$ is a palindrome in both base \$2\$ and base \$5\$, the output should be \$2\$ since \$2<5\$.
Input
A positive integer \$n < 2^{31}\$.
Output
Return the smallest base \$b ≥ 2\$ such that the base \$b\$ representation of \$n\$ is a palindrome. Do not assume any leading zeros.
Samples (input => output):

\$11 \to 10\$
\$32 \to 7\$
\$59 \to 4\$
\$111 \to 6\$

Rules
The shortest code wins.

GolfScript, 20 characters
~:x,2>{x\base.-1%=}?

A different approach with GolfScript other than Dennis'. It avoids the costly explicit loop in favour of a find operator. Try online.
~:x        # interpret and save input to variable x
,2>        # make a candidate list 2 ... x-1 (note x-1 is the maximum possible base)
{          # {}? find the item on which the code block yields true
  x\       # push x under the item under investigation
  base     # perform a base conversion
  .-1%     # make a copy and reverse it
  =        # compare reversed copy and original array
}?


Removing The Nineteenth Byte Introduction
The Nineteenth Byte is CGCC's official chatroom (go check it out!). Its name is a play on the nineteenth hole, and it also refers to golf, which is appropriate for CGCC's chatroom's name. The name is also precisely \$19\$ bytes long, as its name states.
Challenge
Your task is to write a program that outputs Stack Exchange Chat - The Nineteenth Byte exactly. However, if the nineteenth byte and only the nineteenth byte of your source code is removed, it should output only Stack Exchange Chat. Because of this, the best score you can get will be \$19\$ bytes. For example, if your code is abcdefghijklmnopqrstuvwxyz, then abcdefghijklmnopqrstuvwxyz must output Stack Exchange Chat - The Nineteenth Byte and abcdefghijklmnopqrtuvwxyz must output Stack Exchange Chat.
Rules

Standard loopholes are forbidden.
Trailing whitespace is allowed.
If possible, please link to an online interpreter (e.g. TIO) to run your program on.
Please explain your answer. This is not necessary, but it makes it easier for others to understand.
Languages newer than the question are allowed. This means you could create your own language where it would be trivial to do this, but don't expect any upvotes.
You are scored by the length of the program that outputs Stack Exchange Chat - The Nineteenth Byte.
This is code-golf, so shortest code in bytes wins!

Jelly, 25 bytes
“¡TƑ9ı2ṆR“¡⁸¢6ṅȯ*ỵ#K»iƇ”h

Try it online! or Try it without #
Jelly, 25 bytes
“¡TƑ9ı2ṆR“¡TḟKY=ɱø~»tƑƇ⁶K

Try it online! or Try it without ~
How they work
“¡TƑ9ı2ṆR“¡⁸¢6ṅȯ*ỵ#K»iƇ”h - Main link. No arguments
“¡TƑ9ı2ṆR“¡⁸¢6ṅȯ*ỵ#K»     - Pair of compressed strings ["Stack Exchange Chat", " - The Nineteenth Byte"]
                      Ƈ   - Keep those for which the following is True:
                     i ”h - They contain "h"; ["Stack Exchange Chat", " - The Nineteenth Byte"]
                            Smash together and output

“¡TƑ9ı2ṆR“¡⁸¢6ṅȯ*ỵK»iƇ”h  - Main link. No arguments
“¡TƑ9ı2ṆR“¡⁸¢6ṅȯ*ỵK»      - Pair of compressed strings ["Stack Exchange Chat", "^Backets reamyappenzell"]
                     Ƈ    - Keep those for which the following is True:
                    i ”h  - They contain "h"; ["Stack Exchange Chat"]
                            Smash together and output

And the second one:
“¡TƑ9ı2ṆR“¡TḟKY=ɱø~»tƑƇ⁶K - Main link. No arguments
“¡TƑ9ı2ṆR“¡TḟKY=ɱø~»      - Pair of compressed strings ["Stack Exchange Chat", "- The Nineteenth Byte"]
                     ƑƇ   - Keep those where the following has no effect:
                    t  ⁶  -   Removing spaces from the front and end; ["Stack Exchange Chat", "- The Nineteenth Byte"]
                        K - Join with spaces; "Stack Exchange Chat - The Nineteenth Byte"

“¡TƑ9ı2ṆR“¡TḟKY=ɱø»tƑƇ⁶K  - Main link. No arguments
“¡TƑ9ı2ṆR“¡TḟKY=ɱø»       - Pair of compressed strings ["Stack Exchange Chat", " Backets reamyappenzell"]
                    ƑƇ    - Keep those where the following has no effect:
                   t  ⁶   -   Removing spaces from the front and end; ["Stack Exchange Chat"]
                       K  - Join with spaces; "Stack Exchange Chat"


Draw an ASCII cuboid Given three integers >= 2, create an ASCII cube in an orthogonal (cabinet) projection.
The three integers represent height, width and depth (measured in visible characters) including the corners. The corners should be 'o's or '+', free choice.

w: 10, h: 5, d: 4
Thus gives:

   o--------o
  /        /|
 /        / |
o--------o  |
|        |  o
|        | /
|        |/
o--------o

Now, to make this slightly harder, all faces can either be solid, transparent or missing.
We order the faces like this:

   o--------o
  /        /|
 /    2   / |
o--------o 3|
|        |  o
|   1    | /
|        |/
o--------o

  ---
  |2|
-------
|5|1|3|
-------
  |4|
  ---
  |6|
  ---

And supply a list of tokens, S, T or M. The original example is thus:

w 10
h 5
d 4
S S S S S S

   o--------o
  /        /|
 /        / |
o--------o  |
|        |  o
|        | /
|        |/
o--------o

If one face is transparent, we can see anything that is behind it:

T S S S S S

   o--------o
  /        /|
 /        / |
o--------o  |
|  o-----|  o
| /      | /
|/       |/
o--------o

T T T T T T

   o--------o
  /|       /|
 / |      / |
o--------o  |
|  o-----|--o
| /      | /
|/       |/
o--------o

For pairs of missing faces, adjacent edges or corners are no longer visible:

M M S S S S

   o--------o
  /|       /|
 / |      / |
o  |     o  |
|  o-----|  o
| /      | /
|/       |/
o--------o

M M S S M S

   o--------o
   |       /|
   |      / |
   |     o  |
   o-----|  o
  /      | /
 /       |/
o--------o

Code golf, shortest code wins!
Trailing spaces and newlines are fine, you're free to choose input method and input order.

Charcoal, 190 181 bytes

ＮωＡ⁻ω²ςＮηＡ⁻η²γＮδＡ⁻δ²χＡ⪪Ｓ αＦ›⊟αMＦ⟦ςγςγ⟧«oκ↶»Ｆ∧›⊟αM²«oς↷³oχ↷¹»Ｆ∧›⊟αM²«↷³oχ↷³oγ↶»Ｍ⁻ωδ⁻δηＦ⁼§α²SＧ↗δ↓η↙δ↑η Ｆ∧›⊟αM²«↶¹oχ↷³oγ↷»Ｆ⁼§α¹SＧ↗δ←ω↙δ→ω Ｆ∧›⊟αM²«↶¹oχ↶³oς»Ｆ⁼§α⁰SＵＯ±ωη ↷Ｆ›⊟αMＦ⟦γςγς⟧«oκ↷

Try it online! Link is to verbose version of code. Edit: Saved 9 bytes by optimising my conditions. Charcoal has no else token, so if commands always have two alternatives, unless they're at the end of a block or program. To avoid this, I use for (<bool>) instead of if (<bool>) which has a similar effect when the expression can only have the values 0 or 1 but saves a byte. (In order to achieve this I had to change the expressions so that they were always true when the body needed to be executed.) I was also able to optimise if (<bool>) for (<int>) into for (And(bool, int)).


Golf the pseudoprimes! Introduction / Background
In a recent discussion in the crypto chat I was challenged to discuss / help with the Fermat primality test and Carmichael numbers. This test is based on the premise that a^(p-1) mod p==1 will always hold for primes p, but not always for composites. Now a carmichael number is essentially the Fermat's test worst enemy: A number for which you have to pick a to be not co-prime with p to get a^(p-1) mod p!=1. Now if a is not co-prime, you essentially found a non-trivial factor of p and as we all know factoring can be quite hard. Especially if all factors are sufficiently large. You may now realize why the Fermat test isn't used in practice as often (well there are better algorithms), it's because there are numbers for which you as a defender (in security terms) would have to do a similar amount of work as an attacker (namely factor the number).
So now that we know why these numbers are somewhat fascinating, we're gonna generate them in the shortest way possible, so we can just memorize the generating code if we ever need any!
Carmichael numbers are also known as A002997 on OEIS.
There is a related challenge already, but entries from there are not competitive here because they are optimized for speed as opposed to size. The same argument holds for the inverse direction, entries here are likely to make trade-offs against speed in favor of size.
Specification
Input
This is a standard sequence challenge, so you take a positive or non-negative integer n as input. n may be 0- or 1-indexed as you prefer (please indicate).
Output
Your output will either be the n-th carmichael number or the first n carmichael numbers, as you prefer (please indicate).
Specification
An integer x is a Carmichael number if and only if x is composite and for all integers y with gcd(x,y)=1, it holds that y^(x-1) mod x==1.
Who wins?
This is code-golf, so the shortest code in byte wins! Standard IO and loophole rules apply.
Test Cases
The first few carmichael numbers are:
 561,1105,1729,2465,2821,6601,8911,10585,15841,
 29341,41041,46657,52633,62745,63973,75361,101101,
 115921,126217,162401,172081,188461,252601,278545,
 294409,314821,334153,340561,399001,410041,449065,
 488881,512461

Mathematica, 71 bytes
(t=s=1;While[t<=#,If[++s~Mod~CarmichaelLambda@s==1&&!PrimeQ@s,t++]];s)&

Try it online!
50->1461241  Try it online!


Minecraft Language Files Updater In 1.13, Minecraft language files were switched from being a simple multi-line key=value format to JSON.
Challenge
Write a program converting from the original format returning a JSON string. Input can be taken using any standard input method, output must be json from any standard output method
The original format contains lines with key=value pairs, for example
tile.dirt.name=Dirt
advMode.nearestPlayer=Use "@p" to target nearest player

build.tooHigh=Height limit for building is %s blocks

Should be converted to one large JSON object with key=value
{
    "tile.dirt.name": "Dirt",
    "advMode.nearestPlayer": "Use \"@p\" to target nearest player",
    "build.tooHigh": "Height limit for building is %s blocks"
}

Some details

Any valid JSON is allowed as long as it contains only the correct key/value pairs. Trailing commas are allowed because Minecraft allows them.
The only things that must be escaped are quotes. (No newlines, backslashes, or other json-breaking things existed in the language file prior to 1.13)
Empty lines should be ignored
Lines contain exactly one equals

Test Cases
Input:
tile.dirt.name=Dirt
advMode.nearestPlayer=Use "@p" to target nearest player

build.tooHigh=Height limit for building is %s blocks

Output:
{
    "tile.dirt.name": "Dirt",
    "advMode.nearestPlayer": "Use \"@p\" to target nearest player",
    "build.tooHigh": "Height limit for building is %s blocks"
}

Input:
translation.test.none=Hello, world!
translation.test.complex=Prefix, %s%2$s again %s and %1$s lastly %s and also %1$s again!
translation.test.escape=%%s %%%s %%%%s %%%%%s
translation.test.invalid=hi %
translation.test.invalid2=hi %  s
translation.test.args=%s %s
translation.test.world=world

Output:
{
  "translation.test.none": "Hello, world!",
  "translation.test.complex": "Prefix, %s%2$s again %s and %1$s lastly %s and also %1$s again!",
  "translation.test.escape": "%%s %%%s %%%%s %%%%%s",
  "translation.test.invalid": "hi %",
  "translation.test.invalid2": "hi %  s",
  "translation.test.args": "%s %s",
  "translation.test.world": "world",
}

Input:
stat.mineBlock=%1$s Mined
stat.craftItem=%1$s Crafted
stat.useItem=%1$s Used
stat.breakItem=%1$s Depleted

Output:
{
    "stat.mineBlock": "%1$s Mined",
    "stat.craftItem": "%1$s Crafted",
    "stat.useItem": "%1$s Used",
    "stat.breakItem": "%1$s Depleted"
}

Python 3, 91 77 bytes
-14 Bytes thanks to OMᗺ
I thought that the printout of a Python dictionary would be close enough to JSON to make it a very competitive language for this challenge.  However, the string representation of python dictionaries is different enough from JSON that I had better luck using python's built-in JSON library. I'll bet this can be done more succinctly in JavaScript.
import json
f=lambda x:json.dumps(dict(i.split("=")for i in x.split("\n")if i))

Try it Online!

Edit:
Bash + Sed, 68 63 bytes
Bug fix thanks to OMᗺ and Night 2
-5 Bytes thanks to OMᗺ
I realized that it might be more byte efficient to directly convert the text to JSON without bundling it in an object, as was my approach for the python solution.  Per byte, sed is the most powerful language for regex replacement that I know of.
echo {`echo "$1"|sed 's/"/\\\"/g;s/\(.*\)=\(.*\)/"\1":"\2",/'`}

Try it Online!
Explanation
echo {`                                  #  prints the leading curly brace
       echo "$1"|sed                     # feeds the input into sed
       's/"/\\"/g;                       # replaces " with \"
       s/\(.*\)=\(.*\)/"\1":"\2",/'      # surrounds the left and right hand sides of the equals with quotes and joins them with a colon
`}                                       # prints the closing curly brace


Code-Golf Ascii Art Mini-Golf Intro

Let's play some mini-golf! The golf ball is represented by a . and the hole by a O.
You want to get a hole in one on every hole, but you are not good at putting. In fact, you refuse to attempt putting diagonally! Only up, down, and to either side.

You plan to cheat by placing extra bumpers \ and / so you can put the ball in with one shot. The ball bounces off of the bumpers at right angles, as shown in this picture.

Remember to call your shot! Tell us what direction you're putting.

Holes

1: The first hole is easy, a straight shot! No bumpers needed to place here.

Input:

.         O

Output:

right
.         O

2: Another basic one, a short turn. The ball is hit off the bumper into the hole.

Input:

     .
O

Output:

left
/    .
O

or

down
     .
O    /

3: Some holes have bumpers already!

Input:

.   \O

Output:

right
.   \O
    \/

or

right
   / \
.  /\O

4: Some holes are overly complex!

Input:

    /  \  \    /
   /  . \  \  /
  /  /\/   /\ \  /
 /  /     /  \ \/
/  /   /\ \  /  \  /
\  \  /  \ \/    \/
      \  /          /
  /\   \//\ \      /
 /  \   /  \ \     \/
 \  /\  \  /  \     \
  \/  \  \/    \ O/  \
      /         \/

Output: (one possible solution, more exists)

down
    /  \  \    /
   /  . \  \  /
  /  /\/   /\ \  /
 /  /     /  \ \/
/  /   /\ \  /  \  /
\  \  /  \ \/    \/
/     \  /          /
  /\   \//\ \      /
\/  \   /  \ \     \/
 \  /\  \  /  \  /  \
  \/  \  \/    \ O/  \
      /  \      \/
                \   /

Rules

The input is the mini-golf hole on STDIN.
The output is the direction you hit the ball and the mini-golf hole with newly placed bumpers on STDOUT.
Existing bumpers cannot be moved.
You can add any number of bumpers to solve a hole.
Assume there are valid locations for the bumpers to be placed that will allow the course to be solved in one putt.
The outputted hole may be bigger than the input.
The input may be padded with trailing white space, but please specify in your answer if you do this.
The output must look correct, but can have leading or trailing white space.
Your program should work for any valid hole. Feel free to post your test cases too!

Scoring

This is code-golf. Your score is the number of characters in your program. Lowest score wins!


How do I find the factorial of a positive number? The challenge:

  Write a program or a function that inputs a positive number and returns its factorial.

Note: This is a code-trolling question. Please do not take the question and/or answers seriously. More information here. Every code-trolling question is also a popularity-contest question, so the highest voted answer wins.

This is a very simple numerical computing problem that we can solve with Stirling's approximation:

As you can see, that formula features a square root, which we will also need a way to approximate. We will choose the so-called "Babylonian method" for that because it is arguably the simplest one:

Note that computing the square root this way is a good example of recursion.

Putting it all together in a Python program gives us the following solution to your problem:

def sqrt(x, n): # not the same n as below
    return .5 * (sqrt(x, n - 1) + x / sqrt(x, n - 1)) if n > 0 else x

n = float(raw_input())
print (n / 2.718) ** n * sqrt(2 * 3.141 * n, 10)

With a simple modification the above program can output a neat table of factorials:

1! =    0.92215
2! =    1.91922
3! =    5.83747
4! =   23.51371
5! =  118.06923
6! =  710.45304
7! = 4983.54173
8! = 39931.74015
9! = 359838.58817

This method should be sufficiently accurate for most applications.


Impress Donald Knuth by counting polyominoes on the hyperbolic plane This challenge is inspired by a talk about Schläfli symbols, etc that I gave in a Geometry seminar. While I was putting together this challenge, I saw that Donald Knuth himself was interested in (some subset of) this problem. In October 2016, he commented on a related OEIS sequence:

If [the OEIS author] is wrong about the hyperbolic {4,5} pentominoes, the next number is probably mistaken too. I don't have [time] right now to investigate further.

Successful completion of this challenge will have you investigating something that Donald Knuth might have investigated if only he had more time, and will result in new additions (and perhaps a rare correction) to the On-Line Encyclopedia of Integer Sequences.

Challenge
This code-golf challenge will have you create a function that counts "free polyforms" on the hyperbolic plane. In particular, you will write a function that takes three positive integer parameters p, q, and n and counts the number of \$n\$-cell "free polyforms" on the tiling of the hyperbolic plane given by the Schläfli symbol \$\{p,q\}\$.
Shortest code wins.

Definitions
The Schläfli symbol \$\{p,q\}\$ describes a tiling of the hyperbolic plane by \$p\$-gons, where each vertex touches exactly \$q\$ of the polygons. As an example, see the Wikipedia page for the \$\{4,5\}\$ tiling that Donald references above.
A free polyform is a collection of regular polygons that meet at their edges, counted up to rotation and reflection.

Input
You can assume that the values of p and q which define the tiling indeed describe an actual tiling of the hyperbolic plane. This means that \$p \geq 3\$, and

when \$p = 3\$, \$q \geq 7\$,
when \$p = 4\$, \$q \geq 5\$,
when \$p = 5\$, \$q \geq 4\$,
when \$p = 6\$, \$q \geq 4\$, and
when \$p \geq 7\$, \$q \geq 3\$.

Data
OEIS sequence A119611 claims that f(4,5,n) = A119611(n), but Donald Knuth disputes the reasoning for the value of \$A119611(5)\$. (When I counted by hand, I got Knuth's answer, and I've included it in the table below.)

\$p\$
\$q\$
\$n\$
\$f(p,q,n)\$

3
7
1
1

3
7
2
1

3
7
3
1

3
7
4
3

3
7
5
4

3
7
6
12

3
7
7
27

3
9
8
82

4
5
3
2

4
5
4
5

4
5
5
16

6
4
3
3

7
3
1
1

7
3
2
1

7
3
3
3

8
3
3
4

9
3
3
4

Note: these values are computed by hand, so let me know if you suspect any mistakes.
Final notes
The output of this program will result in quite a lot of new, interesting sequences for the OEIS. You are of course free to author any such sequences—but if you're not interested, I'll add the values you compute to the Encylopedia with a link to your answer.

GAP and its kbmag package, 711 682 658 bytes

Note that the kbmag package consists not only of GAP code, it contains C programs that have to be compiled (see the package's README file).

LoadPackage("kbmag");I:=function(p,q,n)local F,H,R,r,s,x,c;F:=FreeGroup(2);s:=F.1;r:=F.2;R:=KBMAGRewritingSystem(F/[s^2,r^p,(s*r)^q]);AutomaticStructure(R);H:=SubgroupOfKBMAGRewritingSystem(R,[r]);AutomaticStructureOnCosets(R,H);x:=w->ReducedCosetRepresentative(R,H,w);c:=function(n,U,S,P)local N,Q,Z;if n=0 then Z:=Set(U,t->Set(U,p->(p/t)));return 1/Size(SetX(Union(Z,Set(Z,Q->Set(Q,q->(MappedWord(q,[s,r],[s,r^-1]))))),[1..p],{Q,i}->Set(Q,q->x(q*r^i))));fi;if P=[]then return 0;fi;N:=P[1];Q:=P{[2..Size(P)]};Z:=Filtered(Set([1..p],i->x(s*r^i*N)),w->not w in S);return c(n,U,S,Q)+c(n-1,Union(U,[N]),Union(S,Z),Union(Q,Z));end;return c(n,[],[r/r],[r/r]);end;

This is the result of removing indentation and newlines from this version, and some inlining:

LoadPackage("kbmag");
I:=function(p,q,n)
  local F,G,H,R,r,s,x,c;
  F:=FreeGroup(2);
  s:=F.1;r:=F.2;
  G:=F/[s^2,r^p,(s*r)^q];
  R:=KBMAGRewritingSystem(G);
  AutomaticStructure(R);
  H:=SubgroupOfKBMAGRewritingSystem(R,[r]);
  AutomaticStructureOnCosets(R,H);
  x:=w->ReducedCosetRepresentative(R,H,w);
  c:=function(n,U,S,P)
    local N,Q,Z;
    if n=0 then
      Z:=Set(U,t->Set(U,p->(p/t)));
      Z:=Union(Z,Set(Z,Q->Set(Q,q->(MappedWord(q,[s,r],[s,r^-1])))));
      Z:=SetX(Z,[1..p],{Q,i}->Set(Q,q->x(q*r^i)));
      return 1/Size(Z);
    fi;
    if P=[]then return 0;fi;
    N:=P[1];Q:=P{[2..Size(P)]};
    Z:=Filtered(Set([1..p],i->x(s*r^i*N)),w->not w in S);
    return c(n,U,S,Q)+c(n-1,Union(U,[N]),Union(S,Z),Union(Q,Z));
  end;
  return c(n,[],[r/r],[r/r]);
end;

If the line containing {Q,i}-> doesn't work, your GAP is too old. You can then replace that line with:

Z:=SetX(Z,[1..p],function(Q,i)return Set(Q,q->x(q*r^i));end);

Several of the Set operations could be slightly faster List operations (the improved version at least uses that it is a set for even more golfing and a little speed compensation), but that would cost one byte each time.

And yes, Knuth's and your result is confirmed:

gap> Read("i.gap");
─────────────────────────────────────────────────────────────────────────────
Loading  kbmag 1.5.9 (Knuth-Bendix on Monoids and Automatic Groups)
by Derek Holt (https://homepages.warwick.ac.uk/staff/D.F.Holt/).
Homepage: https://gap-packages.github.io/kbmag
─────────────────────────────────────────────────────────────────────────────
gap> I(4,5,5);
16
gap> I(4,5,6);
55
gap> I(4,5,7);
224
gap> I(4,5,8);
978
gap> I(4,5,9);
4507
gap> I(4,5,10);
21430

The \$n=7\$ computation already takes several minutes. My computations also agree with the other results in the table.


Is it a vampire number? Repost and improvement of this challenge from 2011
A vampire number is a positive integer \$v\$ with an even number of digits that can be split into 2 smaller integers \$x, y\$ consisting of the digits of \$v\$ such that \$v = xy\$. For example:
$$1260 = 21 \times 60$$
so \$1260\$ is a vampire number. Note that the digits for \$v\$ can be in any order, and must be repeated for repeated digits, when splitting into \$x\$ and \$y\$. \$x\$ and \$y\$ must have the same number of digits, and only one can have trailing zeros (so \$153000\$ is not a vampire number, despite \$153000 = 300 \times 510\$).
You are to take a positive integer \$v\$ which has an even number of digits and output whether it is a vampire number or not. You can either output:

Two consistent, distinct values
A (not necessarily consistent) truthy value and a falsey value

For example, "a positive integer for true, 0 for false"

You may input and output in any convenient method. This is code-golf, so the shortest code in bytes wins.
The first 15 vampire numbers are \$1260, 1395, 1435, 1530, 1827, 2187, 6880, 102510, 104260, 105210, 105264, 105750, 108135, 110758, 115672\$. This is sequence A014575 on OEIS. Be sure to double check that your solution checks for trailing zeros; \$153000\$ should return false.

Husk, 18 17 14 13 12 bytes
Edit: -3 bytes, and then another -1 byte, thanks to Leo, and -1 byte thanks to inspiration from pajonk's R answer (3rd edit)
€¹mΠ†dm½f→Pd

Try it online!
Outputs nonzero integer if it's a vampire number, zero otherwise.
Commented penultimate version:
€¹                  # index of input if present, zero otherwise, in
  mΠ                # products of each element-pair
    †d              # combining digits as a number from
         m½         # first & second halves of
           P        # all permutations of
            d       # digits of input;
      f             # and filtering only element-pairs for which
       ṁ→           # sum of last digits is nonzero


Diophantine Approximation: find lowest possible denominator to approximate within given precision Challenge
Given a number x and a precision e, find the lowest positive integer q such that x can be approximated as a fraction p / q within precision e.
In other words, find the lowest positive integer q such that there exists an integer p such that abs(x - p/q) < e.
Input

The pair (x, e) where x is a floating-point number, and e is a positive floating-point number.
Alternatively, a pair (x, n) where n is a nonnegative integer; then e is implicitly defined as 10**(-n) or 2**(-n), meaning n is the precision in number of digits/bits.

Restricting x to positive floating-point is acceptable.
Output
The denominator q, which is a positive integer.
Test cases

Whenever e > 0.5 ------------------------> 1 because x ≈ an integer
Whenever x is an integer ----------------> 1 because x ≈ itself
(3.141592653589793, 0.2) ------------> 1 because x ≈ 3
(3.141592653589793, 0.0015) --------> 7 because x ≈ 22/7
(3.141592653589793, 0.0000003) ---> 113 because x ≈ 355/113
(0.41, 0.01) -------------------------------> 12 for 5/12 or 5 for 2/5, see Rules below

Rules

This is code-golf, the shortest code wins!
Although the input is "a pair", how to encode a pair is unspecified
The type used for x must allow a reasonable precision
Floating-point precision errors can be ignored as long as the algorithm is correct. For instance, the output for (0.41, 0.01) should be 12 for 5/12, but the output 5 is acceptable because 0.41-2/5 gives 0.009999999999999953

Related challenges

Find the simplest value between two values
Closest fraction

R, Xx bytes
Note: this challenge is quite a good introductory-challenge for R, which is the 'language-of-the-month' for September 2020, so I've blanked-out my answer in the hope of encouraging some other golfers to have a shot at it in R, too...

 50 bytes

    function(x,e,s=1:e^-1)s[(x-round(x*s)/s)^2<e^2][1]

Try it online!
Function with arguments x & error e.  Can handle negative x (even though not required for challenge)

Note 2: dammit!  a port of xnor's approach is 6 bytes shorter still:

 44 bytes

    function(x,e,s=1:e^-1)s[(x+e)%%(1/s)<2*e][1]

Try it online!