text:
Arrow those variables!
Challenge
Robin likes having his variables declaration in the shape of an arrow. Here's how he does it:

Input any number of strings
Order them by ascending length
Output them ordered by the middle to roughly form a negative arrowhead, like this (whichever order golfs the best):
5  or  4
3      2
1      1
2      3
4      5

Test Cases
Input:
bow
arrows
sheriffOfNottingham
kingRichard
maidMarian
princeJohn
sherwoodForest

Output:
sheriffOfNottingham
kingRichard
maidMarian
bow
arrows
princeJohn
sherwoodForest

Input:
a
bb
cc

Output (both are valid):
bb
a
cc

cc
a
bb

Input:
one
four
seven
fifteen

Possible output (the only other valid output is its vertical mirror):
seven
one
four
fifteen

Notes

The strings are in camelCase and have no numbers or special characters, only lowercase and uppercase letters.
The input can be anything you like: comma-separated as one string, array, ... Any I/O format is allowed.
Between strings with the same length, any order is accepted.

I feel like there was a very similar challenge before...but welcome to PPCG!

@Giuseppe Yeah that's what I thought after posting, there's no way it hasn't been done before. Would you be ok with me deleting it now that you've answered it?

well I've been searching for a dupe but I'm not very good at the search...we do have a sandbox for posting challenges which can often catch things like that. I'm perfectly OK with you deleting it if you're worried about it being a dupe.

@Giuseppe Well it's too late, with 2 answers SE won't let me delete it. I had hoped for a better start in PPCG...

It's OK, we all start from the beginning :-)

Could you add a test case with an even number of strings?

Are we guaranteed that all strings will be unique?

@Shaggy No, that's not a necessity

May we return a list of strings?

Will strings have at least one character each?

@Adám, "Any I/O format is allowed."

Python 2, 47 bytes
lambda l:l.sort(key=len)or l[1::2][::-1]+l[::2]

Try it online!

You'll need to rearrange some stuff, but you can use [::-2] directly to save 5 bytes.

@Sherlock9 I tried that, but then I had to check for the length, as lists with even / uneven lengths have to be handled differently.

Also works for Python 3. Would removing "lambda l:" and "or" and make it on 2 lines to save 11 bytes still be acceptable as "Any I/O format is allowed" ?

R, 63 48 bytes
function(L)c(rev(o<-L[order(nchar(L))]),o)[!0:1]

Try it online!
Sort by string lengths, then combine the reversed list with the sorted list, finally, take every 2nd element, starting at 1-based index 1.

o<-L[... The other way to 'arrow variables'.
A less important aside, pryr::f(...) works here for 46. Try it online!

@CriminallyVulgar using additional libraries turns this into a separate language, R + pryr which is why I typically avoid doing it unless there's a good reason to -- like for number theory questions, numbers is indispensable.

Javascript 77 bytes
Takes input as an array of strings, outputs an arrow-sorted array of strings.
s=>s.sort((a,b)=>a.length-b.length).reduce((m,x,i)=>i%2?[...m,x]:[x,...m],[])

Explanation
s =>                                 // take input as an array of strings s
  s.sort((a,b)=>a.length-b.length)   // sort input by string length
  .reduce(                           // reduce
    (m,x,i)=>i%2?[...m,x]:[x,...m],  // if index is even, stick string x at the end of the memo
                                     // array, else at the beginning
    []                               // memo initialized to empty array
  )

I don't think you have to count f=. 77

That is inconsistent in the js code golf submissions from what I have seen. I'm happy to exclude it if it doesn't count.

I think it depends whether your function uses recursion. i.e. f=x=>x?f(x-1). If so, you need to include f since you are calling it in your function. However, since you are not using recursion, you shouldn't have to include f. There are several posts in Meta, this one seems to explain it a little better. https://codegolf.meta.stackexchange.com/a/9032/8340

That would explain the inconsistencies I've seen.

Ruby, 51 bytes
->l{r=1;l.sort_by!(&:size).map{l[r-=2]||(l*2)[~r]}}

Try it online!

Jelly, 9 8 bytes
LÞŒœm"-Ẏ

Try it online!
LÞŒœṚ;¥/

is also 8 bytes.
Thanks to @EriktheOutgolfer and @JonathanAllan for both offering golfs to save a byte.

Nice! Clever golf: Ṛ€1¦ can become m"-.

Or you could go for LÞŒœṚ;¥/

C# (Visual C# Interactive Compiler), 89 bytes
n=>(n=n.OrderBy(x=>x.Length)).Where((a,b)=>b%2>0).Reverse().Concat(n.Where((a,b)=>b%2<1))

Try it online!

K (oK), 24 bytes
Solution:
x(<#:'x)(|&~w),&w:2!!#x:

Try it online!
Explanation:
Generate the 6 4 2 0 1 3 5 sequence, use that to index into the ascending lengths of input, and use that to index into the original array:
x(<#:'x)(|&~w),&w:2!!#x: / the solution
                      x: / save input as x
                     #   / count (#) of x
                    !    / range 0 to ...
                  2!     / modulo 2
                w:       / save as w
               &         / indices where true
              ,          / join with
        (    )           / do this together
           ~w            / not (~) w
          &              / indices where true
         |               / reverse
 (     )                 / do this together
   #:'x                  / count (#:) of each (') x
  <                      / indices to sort ascending
x                        / index into x

J, 11 bytes
,~`,/@\:#&>

Try it online!
We sort it down first.
Then we reduce the list form right to left, but alternating which side we put the new element on.  Done.

Very nice! You have a space at the end though, remove it for 11 bytes :)

Thanks Galen.  Fixed!

05AB1E, 6 5 bytes
Saved 1 byte thanks to Kevin Cruijssen
I/O is a list of strings.
Link is modified for newline separated I/O for easier testing.
éι`Rì

Try it online!
Explanation
é       # sort by length ascending
 ι      # uninterleave into 2 parts, both sorted ascending
   `    # push the 2 parts separately to the stack
    R   # reverse the second part
     ì  # and append it to the first

You can remove the first R and replace « with i to save a byte, since the third bullet-point rule allows both versions of uninterleaving.

@KevinCruijssen: Oh yeah, Thanks!

PHP, 144 141 bytes
function($a){usort($a,function($b,$c){return strlen($b)-strlen($c);});$e=[];foreach($a as$d)(array_.[unshift,push][++$i%2])($e,$d);return$e;}

Try it online!
-3 bytes thanks to @Ismael Miguel!

nice one. Where can I read more about [array_unshift,array_push][++$i%2]($e,$d)?

@abhig10 sure. It's an array with the two function names ['array_push','array_unshift'] with [++$i%2] as the index of the array alternating between a 0 or 1 so will evaluate to the other function each time. PHP's "variable functions" let you assign a varible to a function and execute by calling with parenthesis (ex: $f='array_push'; $f($e,$d); == array_push($e,$d)) so the ($e,$d) is then calling the evaluated element of the array. Just a shorter way to do if (++$i%2) array_push($e,$d); else array_unshift($e,$e);. Guess there was some PHP syntactic sugar after all!

Okay, it took me sometime to understand this. Awesome.

You can save 3 bytes by replacing [array_unshift,array_push][++$i%2]($e,$d) with (array_.[unshift,push][++$i%2])($e,$d). What I did was to remove the repeated array_, concatenated it and then the result is passed to the call.

@IsmaelMiguel that's brilliant.  Thank you!

PowerShell, 66 bytes
1..($a=$args|sort l*).count|?{$_%2}|%{$a[-$_];$x=,$a[-++$_]+$x};$x

Try it online!
Takes input via splatting, which manifests on TIO as separate command-line arguments. sorts on the length, stores that into $a, and constructs a range from 1 up to the count of input strings. We then pull out only the odd ones ?{$_%2} and feed those into a loop |%{...}. Each iteration, we put the "last", then the "third from last", and so on onto the pipeline with $a[-$_]. Separately, we also accumulate into $x the "second from last", "fourth from last", etc. Out of the loop and the pipeline is flushed (so those elements are output) and then we output $x. In both instances, the default output gives us newlines between items automatically.

MATLAB, 87 bytes
function f(y);[B,I]=sort(cellfun(@(x)length(x),y));{y{flip(I(1:2:end))},y{I(2:2:end)}}'

Takes input as cell array of strings, outputs column of strings (not sure if that's legal)
> s = {'qweq qwe qw','qweqw','12132132131231231','asdasdasda','qwe','w'};
> f(s)
> >>
> ans =
>
>   6×1 cell array
>
>     {'qweq qwe qw'      }
>     {'qweqw'            }
>     {'qwe'              }
>     {'1234'             }
>     {'asdasdasda'       }
>     {'12132132131231231'}

PS: Thanks  Sanchises for pointing to a bug with odd-length inputs

This fails on odd number of input strings, e.g. f({'loooooooong','medium','short'})

Also some general golfing tips: the end is optional for a function. Using function x=f(y);x={...}' is shorter than function f(y);disp({...}').

If you're stuck, here's how I would do it.

@Sanchises thanks for pointing bug out. I did fix it exactly like you did. My issue with disp is i am not sure what output rules are. Should it be pure text or not? or disp({...}) is okay or even just x={...} as you suggest

That question can be quite tricky to answer. In general however, input/output is as flexible as possible so you can focus on the main challenge (there's a list of allowed I/O by default on meta) and in this case, no extra restrictions are specified by the OP. In my experience, just y=input('');doSomething() (without trailing semicolon to output the result) is shortest in MATLAB

(and one final hint: note that my solution was actually three bytes shorter still; it's really worth looking at what all the different braces actually do wrt cell arrays)

@Sanchises my MATLAB doesn't allow removing end from function definition :-(

Interesting, what version do you use?

@Sanchises oh my bad. You cannot omit  end in in-script define functions. But saving function in a file allows it!

what version of MATLAB is this? I'm trying to golf this down but can't get it to work on my local version (R2016a)

This can be 58 bytes in Octave.

APL (Dyalog Unicode), 18 bytesSBCS
{⍵[⍋-@(2∘|)⍋⍋≢¨⍵]}

Try it online!
Fixed the bug  thanks to @ngn.
Explanation:
{⍵[⍋-@(2∘|)⍋⍋≢¨⍵]}
{                } ⍝ Function. Takes a single argument: ⍵, list of strings
             ≢¨⍵   ⍝ The length of each element in the list
           ⍋⍋      ⍝ Sort the lengths
    -@(2∘|)        ⍝ At (@) elements divisible by 2 (|), negate (-)
                   ⍝     gives -1 2 -3 4 -5
   ⍋               ⍝ Sort this list again, gives the indices of that list ^ sorted
 ⍵[             ]  ⍝ Use these indices to index into the argument

¹

≢¨×¯1*⍳∘⍴ -> (⊢∘-\≢¨) and it gets even shorter if you turn it into a dfn

however, i'm not sure this algorithm is correct. we should negate the length of every other string in their sorted order, not in the order they come from the input

Perl 6, 31 bytes
*.sort(&chars).sort:{$++%2*$--}

Try it online!
Sort by string length, then by static sequence 0, -1, 0, -3, 0, -5, ...

APL+WIN, 31 38 bytes
See Adams comment
⊃n[(⍳⍴n)~a],⌽n[a←2×⍳⌊.5×⍴n←n[⍒∊⍴¨n←⎕]]

Try it online Courtesy of Dyalog Classic!
Prompts for a nested vector of strings

Does APL+ not have Monadic ≢ "tally" to replace ∊⍴ ?

Fails on '12' '1234' '1234' '1234' '1234' '12345678' '12345678' '12345678' '12345678'. Clearly, the result should have been '12345678' '12345678' '1234' '1234' '12' '1234' '1234' '12345678' '12345678'

@Adám My ancient version of APL+ does not have ≢. Agreed on your second comment I will take a look at it tomorrow.

Retina, 26 bytes
N$`
$.&
*\,2,^A`.+
,2,G`.+

Try it online! Explanation:
N$`
$.&

Sort the lines in ascending order of length ($.& returns the length of the line).
*\,2,^A`.+

Temporarily delete alternate lines and output the remaining lines in reverse order.
,2,G`.+

Keep the only lines that were temporarily deleted and output them.

Japt, 8 bytes
ñÊó g0_w

-3 bytes thanks to Shaggy!
Try it

10 bytes with output as a 2D-array, which would seem to be allowed.

Or, maybe, 8 bytes? On my phone so haven't tested it properly.

@Shaggy I was looking for a function to find every nth element, but I couldn't find it. Thanks!

there's also A.ë() but I don't know if that'll lead to a shorter solution.

Gaia, 10 bytes
el∫v:v+2%ụ

Try it online!
e		| eval as Gaia code (list of strings)
 l∫		| ∫ort by lengths (ascending)
   v:v		| reverse, dup, reverse
      +		| concatenate lists
       2%	| take every other element
         ụ	| join by newlines and output

i like that your comments in unwrapped code form an arrow of strings

PowerShell, 49 bytes
$args|sort l*|sort{$_.Length*($global:x=-$x*2+1)}

Try it online!
The double distillation.

T-SQL, 84 bytes
Input is a table variable
SELECT a FROM(SELECT*,row_number()over(order by len(a))r
FROM @)x order by(r%2-.5)*r

Try it online

Javascript  95 Bytes
s=>s.sort((x,y)=>x.length-y.length).reduce((a,e,i)=>{i%2?a.push(e):a.unshift(e);return a;},[]);

-1 s.sort() sorts the strings lexicographically, not by string length.

Right, (x,y)=>x.length-y.length, should fix that.

C (gcc), 136 128 bytes
S(a,b)int**a,**b;{a=strlen(*b)-strlen(*a);}f(l,s,o,i,b,e)int**s,**o;{qsort(s,l,8,S);e=l-1;for(i=b=0;i-l;)o[i++%2?b++:e--]=s[i];}

Try it online!
-8 bytes thanks to ceilingcat.
The function f is the solution. It takes the number of strings, the strings themselves, and the output buffer as arguments (plus four more used internally).

Why is ./.bin.tio in the output?

@TeleportingGoat Probably because their footer is using all of argv, which includes the filename

Exactly, it was just a quick test. One can construct any data that takes appropriate format. I'll update the TIO link later.

haha, the problem with these short variable names: you forget what you hat t for in the first place and keep it around even when you don't need it!

122 bytes

Red, 116 101 bytes
func[b][sort/compare b func[x y][(length? x)> length? y]collect[forall b[keep take b]keep reverse b]]

Try it online!

perl 5 (-p0777F/\n/ -M5.01), 59 bytes
for$x(sort{$b=~y///c-length$a}@F){--$|?$\="$x
".$\:say$x}}{

TIO

Husk, 11 bytes
m!ÖL¹Ċ2§+ṡŀ

Try it online!

Vyxal a, 7 bytes
µL;yṘ$"

Try it Online!
Outputs as a list of two lists of lines.
The header and footer allow for multiline IO.

Japt, 8 6 bytes
Input as an array of lines, output as an array of 2 arrays of lines, one for each half of the list.
ñÊó vw

Try it (Header & footer allow for I/O as newline separated string)
ñÊó vw     :Implicit input of array
ñ          :Sort by
 Ê         :  Length
  ó        :Uninterleave
    v      :Modify first element
     w     :  Reverse

Julia 1.0, 41 bytes
!s=sort(s,by=length)[∪(end:-2:1,1:end)]

Try it online!

input and output are vectors of strings
end:-2:1 takes every second index, starting from the end
1:end is all indices
∪ (=union) removes duplicates


text:
Minimum cost of solving the Eni-Puzzle
You're tasked with writing an algorithm to efficiently estimate cost of solving an Eni-Puzzle from a scrambled state as follows:
You're given m lists of containing n elements each(representing the rows of the puzzle). The elements are numbers between 0 and n-1 inclusive (representing the colors of tiles). There are exactly m occurrences of each integers across all m lists (one for each list).
For example:
m=3, n=4 :

[[3, 0, 3, 1],            [[1, 3, 0, 1],
 [1, 0, 2, 2],     or      [0, 2, 3, 1],
 [3, 0, 1, 2]]             [0, 3, 2, 2]]

You can manipulate these lists in two ways:
1: Swapping two elements between circularly adjacent indices in (non circularly) adjacent lists. Cost=1.
Ex:
m=3, n=4 :

Legal:
Swap((0,0)(1,1))
Swap((1,0)(2,3)) (circularly adjacent)

Illegal:
Swap((0,0)(0,1)) (same list)
Swap((0,0)(2,1)) (lists are not adjacent)
Swap((0,0)(1,0)) (indices are not circularly adjacent (they're the same)
Swap((0,0)(1,2)) (indices are not circularly adjacent)

Circularly shifting one of the lists (Cost=number of shifts)

Your algorithm must efficiently calculate minimum cost required to manipulate the lists such that the resulting lists are all rotations of each other (meaning the puzzle can be fully solved from this state using only rotation moves) i.e.:
[[0, 1, 2, 3]          [[2, 1, 0, 3]
 [3, 0, 1, 2]    and   [0, 3, 2, 1]
 [1, 2, 3, 0]]         [3, 2, 1, 0]]

...are both valid final states.
Instead of lists, you may use any data structure(s) of your choice to represent the puzzle, so long as the cost of simulating a valid move (sliding or rotating) on the puzzle with this representation is O(n*m).  The setup cost of initializing this data structure can be disregarded.
A winning solution will compute the cost in the lowest asymptotic runtime in terms of m and n. Execution time will be assessed as a tie breaker.

Hi and welcome to PPCG :) I think you do not need [tag:fastest-code] or [tag:code-challenge] since you only actually specify the winning criterion as the algorithmic speed. Further, I think you should specify if you mean the asymptotic worst case, or average case (best case is not a good idea, for reasons that are hopefully obvious). For future use, we have a sandbox to post challenges to work out issues before you post to the main site. Good luck!

I edited the tags. Thanks!

why not define the winning state as the actual state where they're all lined up?

@JonathanAllan Yes. I've edited this to be more clear.

@Jonah Because The costs I've outlined here are not the actual number of moves required to make equivalent moves on the puzzle. "Swapping" moves have a higher cost. To solve the actual puzzle, you first reach the state I described, or a state that is only one sliding move away. Because my specifications don't allow direct sliding moves (swapping equal indices) like the puzzle does for the blank space, I don't need to consider this latter case. This reduces the problem so that only the two move types I described need to be considered and the concept of a moving  "blank space" can be ignored.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Do I have a twin with permutated remainders?
We define \$R_n\$ as the list of remainders of the Euclidean division of \$n\$ by \$2\$, \$3\$, \$5\$ and \$7\$.
Given an integer \$n\ge0\$, you have to figure out if there exists an integer \$0<k<210\$ such that \$R_{n+k}\$ is a permutation of \$R_n\$.
Examples
The criterion is met for \$n=8\$, because:

we have \$R_8=(0,2,3,1)\$
for \$k=44\$, we have \$R_{n+k}=R_{52}=(0,1,2,3)\$, which is a permutation of \$R_8\$

The criterion is not met for \$n=48\$, because:

we have \$R_{48}=(0,0,3,6)\$
the smallest integer \$k>0\$ such that \$R_{n+k}\$ is a permutation of \$R_{48}\$ is \$k=210\$ (leading to \$R_{258}=(0,0,3,6)\$ as well)

Rules

You may either output a truthy value if \$k\$ exists and a falsy value otherwise, or two distinct and consistent values of your choice.
This is code-golf.

Hint

 Do you really need to compute \$k\$? Well, maybe. Or maybe not.

Test cases
Some values of \$n\$ for which \$k\$ exists:
3, 4, 5, 8, 30, 100, 200, 2019

Some values of \$n\$ for which \$k\$ does not exist:
0, 1, 2, 13, 19, 48, 210, 1999

R, 63 59 46 43 bytes
\(n,a=c(2,3,5,7))any(diff(s<-n%%a)&s[-1]<a)

Attempt This Online!
-4 bytes thanks to Giuseppe
-13 bytes by switching to diff
-3 bytes inspired by a suggestion from Dominic van Essen
(The explanation contains a spoiler as to how to solve the problem without computing \$k\$.)
Explanation:
Let \$s\$ be the list of remainders. Note the constraint that s[1]<2, s[2]<3, s[3]<5 and s[4]<7. By the Chinese Remainder Theorem, there exists a \$k\$ iff there is a permutation of \$s\$, distinct from \$s\$, which verifies the constraint. In practice, this will be verified if one of the following conditions is verified:

s[2]<2 and s[2]!=s[1]
s[3]<3 and s[3]!=s[2]
s[4]<5 and s[4]!=s[3]

Could you explain why the permutation is necessarily distinct from $s$?

@dfeuer It is a consequence of the Chinese Remainder Theorem; I added a link. If two integers have the same remainders modulo 2, 3, 5 and 7 (without a permutation), then the two integers are equal modulo 235*7=210.

45 bytes

@DominicvanEssen Thanks! I'm actually down to 43 now, with a change that is related to your suggestion (and which generates a warning).

Haskell, 69 bytes
Based on the Chinese remainder theorem
m=[2,3,5,7]
f x|s<-mod x<$>m=or[m!!a>b|a<-[0..2],b<-drop a s,s!!a/=b]

Try it online!

Actually, my working title for this challenge was "Do I have a Chinese twin?" :)

Haskell, 47 bytes
g.mod
g r|let p?q=r p/=r q&&r q<p=2?3||3?5||5?7

Try it online!

Can you explain?

@dfeuer It's using Robin Ryder's method.

Perl 6, 64 61 59 43 bytes
{map($!=(*X%2,3,5,7).Bag,^209+$_+1)∋.&$!}

Try it online!
-16 thanks to @Jo King

C# (Visual C# Interactive Compiler), 125 42 38 36 bytes
n=>n%7<5&5<n%35|n%5<3&3<n%15|-~n%6>3

Direct port of @xnor's answer, which is based off of @RobinRyder's solution.
Saved 4 bytes thanks to @Ørjan Johansen!
Saved 2 more thanks to @Arnauld!
Try it online!

I found a variation that only ties for xnor's languages but helps for this: 38 bytes

Isn't -~n%6/4>0 just -~n%6>3?

BTW, this is a JavaScript polyglot.

Wolfram Language (Mathematica), 67 bytes
!FreeQ[Sort/@Table[R[#+k],{k,209}],Sort@R@#]&
R@n_:=n~Mod~{2,3,5,7}

Try it online!

Python 2, 41 bytes
lambda n:n%5!=n%7<5or n%3!=n%5<3or-~n%6/4

Try it online!
Uses the same characterization as Robin Ryder. The check n%2!=n%3<2 is shortened to -~n%6/4. Writing out the three conditions turned out shorter than writing a general one:
46 bytes
lambda n:any(n%p!=n%(p+1|1)<p for p in[2,3,5])

Try it online!

Java (JDK), 36 bytes
n->n%7<5&5<n%35|n%5<3&3<n%15|-~n%6>3

Try it online!
Credits

Port of xnor's solution, improved by Ørjan Johansen.

Wolfram Language (Mathematica), 56 bytes
Or@@(Min[s-#]>0&/@Rest@Permutations@Mod[#,s={2,3,5,7}])&

Try it online!
Finds all non-identity permutations of the remainders of the input modulo 2, 3, 5, 7, and checks if any of them are below {2,3,5,7} in each coordinate. Note that Or@@{} is False.

Ruby, 54 bytes
->n{[2,3,5,7].each_cons(2).any?{|l,h|n%l!=n%h&&n%h<l}}

Try it online!
Uses Robin Ryder's clever solution.

05AB1E, 16 bytes
Ƶ.L+ε‚ε4Åp%{}Ë}à

Try it online or verify all test cases.
Explanation:
Ƶ.L          # Create a list in the range [1,209] (which is k)
   +         # Add the (implicit) input to each (which is n+k)
    ε        # Map each value to:
     ‚       #  Pair it with the (implicit) input
      ε      #  Map both to:
       4Åp   #   Get the first 4 primes: [2,3,5,7]
          %  #   Modulo the current number by each of these four (now we have R_n and R_n+k)
           { #   Sort the list
      }Ë     #  After the inner map: check if both sorted lists are equal
     }à      # After the outer map: check if any are truthy by taking the maximum
             # (which is output implicitly as result)

See this 05AB1E tip of mine (section How to compress large integers?) to understand why Ƶ. is 209.

J, 40 bytes
1 e.(>:+i.@209)-:&(/:~)&(2 3 5 7&|"1 0)]

Try it online!
Brute force...

PHP, 81 78 72 bytes
while($y<3)if($argn%($u='235'[$y])!=($b=$argn%'357'[$y++])&$b<$u)die(T);

A riff on @Robin Ryder's answer.  Input is via STDIN, output is 'T' if truthy, and empty '' if falsy.
$ echo 3|php -nF euc.php
T
$ echo 5|php -nF euc.php
T
$ echo 2019|php -nF euc.php
T
$ echo 0|php -nF euc.php

$ echo 2|php -nF euc.php

$ echo 1999|php -nF euc.php

Try it online!
Or 73 bytes with 1 or 0 response
while($y<3)$r|=$argn%($u='235'[$y])!=($b=$argn%'357'[$y++])&$b<$u;echo$r;
$ echo 2019|php -nF euc.php
1
$ echo 1999|php -nF euc.php
0

Try it online (all test cases)!
Original answer, 133 127 bytes
function($n){while(++$k<210)if(($r=function($n){foreach([2,3,5,7]as$d)$o[]=$n%$d;sort($o);return$o;})($n+$k)==$r($n))return 1;}

Try it online!

R, 72 bytes
n=scan();b=c(2,3,5,7);for(i in n+1:209)F=F|all(sort(n%%b)==sort(i%%b));F

Try it online!

Jelly, 15 bytes
8ÆR©PḶ+%Ṣ¥€®ċḢ$

Try it online!
I’m sure there’s a golfier answer. I’ve interpreted a truthy value as being anything that isn’t zero, so here it’s the number of possible values of k. If it needs to be two distinct values that costs me a further byte.
Explanation
8ÆR             | Primes less than 8 [2,3,5,7]
   ©            | Copy to register
    P           | Product [210]
     Ḷ          | Lowered range [0, 1, ..., 208, 209]
      +         | Add to input
         ¥€     | For each of these 210 numbers...
       %   ®    |   Modulo 2, 3, 5, 7
        Ṣ       |   And sort
            ċḢ$ | Count how many match the first (input) number’s remainders

All good regarding truthy vs falsey. Using the meta agreed definition of truthy and falsey (effectively "what does the language's if-else construct do if there is one) zero is falsey and non-zeros are truthy (? is the if-else construct in Jelly; for some languages it's a harder question).

Oh, and you could get distinct values for no cost with Ḣe$ if you wanted :)

@JonathanAllan yes of course, thanks. :)

Python 3, 69 bytes
lambda x:int('4LR2991ODO5GS2974QWH22YTLL3E3I6TDADQG87I0',36)&1<<x%210

Try it online!
Hardcoded

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Reorder a Master List Based on a Reordered Subset
I recently had a problem to solve at work where I had two lists: a master list, and a smaller list that contains a subset of the items in the master list potentially in a different order. I needed to reorder the master list in such a way that the items in the subset would appear in the same order without changing the order of the items not found in the list and keeping items in the same location whenever possible. Okay, that probably sounds confusing, so I'll break it down:

The master list defines the default order of items.
The subset list defines relative order of certain items.
Where the master list has two elements out of order according to the subset list, the item that is earlier in the master list should be moved to the earliest index where it is in the correct location relative to other items within the subset list. (i.e. immediately after the later item)

Your task is to implement this reordering algorithm.
Example Test Cases
Master: [1, 2, 3]
Subset: []
Result: [1, 2, 3]

Master: [9001, 42, 69, 1337, 420]
Subset: [69]
Result: [9001, 42, 69, 1337, 420]

Master: [9001, 42, 69, 1337, 420, 99, 255]
Subset: [69, 9001, 1337]
Result: [42, 69, 9001, 1337, 420, 99, 255]

Master: [1, 2, 3, 4, 5]
Subset: [2, 5]
Result: [1, 2, 3, 4, 5]

Master: [apple, banana, carrot, duck, elephant]
Subset: [duck, apple]
Result: [banana, carrot, duck, apple, elephant]

Master: [Alice, Betty, Carol, Debbie, Elaine, Felicia, Georgia, Helen, Ilene, Julia]
Subset: [Betty, Felicia, Carol, Julia]
Result: [Alice, Betty, Debbie, Elaine, Felicia, Carol, Georgia, Helen, Ilene, Julia]

Master: [snake, lizard, frog, werewolf, vulture, dog, human]
Subset: [snake, werewolf, lizard, human, dog]
Result: [snake, frog, werewolf, lizard, vulture, human, dog]

Master: [Pete, Rob, Jeff, Stan, Chris, Doug, Reggie, Paul, Alex]
Subset: [Jeff, Stan, Pete, Paul]
Result: [Rob, Jeff, Stan, Pete, Chris, Doug, Reggie, Paul, Alex]

Master: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Subset: [8, 1, 2, 12, 11, 10]
Result: [3, 4, 5, 6, 7, 8, 1, 2, 9, 12, 11, 10]

Master: [lol, rofl, lmao, roflmao, lqtm, smh, jk, wat]
Subset: [wat, lmao, rofl]
Result: [lol, roflmao, lqtm, smh, jk, wat, lmao, rofl]

Rules

Standard loopholes, yadda yadda, convenient I/O, blah blah.
Even though the examples use numbers and strings, you only need to support one element type, whether that's integers, strings, or anything else with well-defined equality semantics, including heterogeneous lists if that's convenient in your language.
You may assume both the master list and the subset list contain no duplicates
You may assume that all items found in the subset list are found in the master list
Either list may be empty
You must, at minimum, support arrays up to 100 elements long.
Reordering may be implemented in-place or through the creation of a new list/array.

Happy Golfing!

A nice, beefy problem.

Is 8 1 3 4 5 6 7 2 9 12 11 10 a valid solution to the second-to-last one?

@Ven No. Even though that fits within the constraints of keeping the subset items in the same relative order, I wanted to make sure there was only one correct answer, so the earlier out-of-order item should be moved to be after the later out-of-order item.

Why does it matter that there are more than one correct answer? Please add the constraint to the rules of the challenge please.

Retina 0.8.2, 51 bytes
+`(\b(\w+),(\w+)\b.*¶.*\b)\3,(.*\b\2\b)
$1$4,$3
1A`

Try it online! Takes input as a comma-separated list of subwords on the first line and a comma-separated master list of words on the second line. Explanation:
(\b(\w+),(\w+)\b.*¶.*\b)\3,(.*\b\2\b)

Find two adjacent subwords where the second word precedes the first on the master list.
$1$4,$3

Move the second word to appear after the first word in the master list.
+`

Repeat until no words appear out of order.
1A`

Delete the subwords.

JavaScript (ES6),  96 89 74  71 bytes
This started as a bulky mess and was eventually shrunk to a rather concise and elegant form. I'd like to thank the .splice() method for its fruitful collaboration on that one. ;)
Takes input as (master)(subset). Outputs by updating the master list.
m=>s=>s.map(p=x=>m.splice(p,0,...m.splice(i=m.indexOf(x),p>i||!(p=i))))

Try it online!
How?
We are using two nested .splice() methods on the same array to conditionally move an element from position \$i\$ to position \$p\$:
m.splice(p, 0, ...m.splice(i, condition))

If the condition is truthy (coerced to \$1\$):

the inner .splice() removes and returns the element at position \$i\$ as a singleton array \$[element]\$
thanks to the spread syntax, this element is expanded as a 3rd argument for the outer .splice(), which causes it to be inserted back at position \$p\$

If the condition is falsy (coerced to \$0\$):

the inner .splice() removes nothing and returns an empty array
as a result, the outer .splice() receives undefined as its 3rd argument and nothing is inserted either

Commented
m => s =>                 // m[] = master list, s[] = subset list
  s.map(                  //
    p =                   // p = position in the master list of the last element from
                          //     the subset list (initialized to a non-numeric value)
    x =>                  // for each element x in the subset list:
    m.splice(             //   insert in the master list:
      p,                  //     at position p
      0,                  //     without removing any element
      ...m.splice(        //     remove from the master list and flatten:
        i = m.indexOf(x), //       i = position of x in the master list
        p > i             //       if p is greater than i, remove x from its current
                          //       position and insert it at position p
        || !(p = i)       //       otherwise, set p to i and don't remove/insert anything
      )                   //     end of inner splice()
    )                     //   end of outer splice()
  )                       // end of map()

"I'd like to thank the .splice() method for ..." Cue PPCG Oscar's Music... :)

More correctly, the outer splice call receives 3 or 2 arguments respectively, which makes it do the right thing.

Ruby, 73 68 bytes
->a,b{0while b.zip(a&b).find{|m,n|m!=n&&a=a[0..a.index(m)]-[n]|a};a}

Try it online!
How?

The intersection between a and b contains all elements of b, but in the same order as we would find them in a
So, if we iterate on b and on the intersection in parallel, as soon as we find a difference, we can relocate a single element.
Relocation is done by cutting a on the position of the element we found in b, then removing the element we found in the intersection, and then adding the remainder of a.
Repeat from the beginning, until all elements of b are in the right order in a

what is the 0 doing in 0while?

It's just a NOP.

why is it needed?

Because the comparison and manipulation is done in a single block, to avoid declaring a variable before starting the loop. It means: "do nothing while the operation returns true.", the code is shorter than "do operation while result is true"

Haskell, 79 bytes
(m:n)#u@(s:t)|m==s=m:n#t|all(/=m)u=m:n#u|(x,_:z)<-span(/=s)n=(x++s:m:z)#u
m#_=m

Try it online!
(m:n)#u@(s:t)                 -- m: head of master list
                              -- n: tail of master list
                              -- s: head of subset
                              -- t: tail of subset
                              -- u: whole subset
   |m==s                      -- if m==s
        =m:n#t                -- return 'm' and append a recursive call with 'n' and 't'
   |all(/=m)u                 -- if 'm' is not in 'u'
             =m:n#u           -- return 'm' and append a recursive call with 'n' and 'u'
   |                          -- else (note: 's' is element of 'n')
    (x,_:z)<-span(/=s)n       -- split 'n' into a list 'x' before element 's' and
                              -- a list 'z' after element 's' and
       = (x++s:m:z)#u         -- make a recursive call with
                              -- x++s:m:z as the new master list (i.e. 'm' inserted into 'n' after 's')
                              -- and 'u'
m # _ = m                     -- if either list is emtpy, return the master list

J, 49 bytes
[:(<@({:+i.@>:@-/)@i.~C.])^:(>/@i.~)&.>/]|.@;2<\[

Try it online!
explanation
We take the subset as the left arg and the full input as the right.
We'll work through the code with a specific example for clarity:
5 2 4 f 1 2 3 4 5

Take the boxed infixes of size two of the subset:
2 <\ [

producing:
┌───┬───┐
│5 2│2 4│
└───┴───┘

append them to the original input, and reverse the whole thing:
] |.@;

We get:
┌───┬───┬─────────┐
│2 4│5 2│1 2 3 4 5│
└───┴───┴─────────┘

Solving the problem becomes a right to left reduction on the above.  We need
only find the right verb to insert / between the items.
Each iteration of the reduction will update the rightmost box (the full input,
which we're transforming) so it conforms to the ordering constraint represented
by the pair to its left.  When the reduction is finished, the input will
respect the complete subset ordering.
If the ordering of the pair is the same as ordering in the input, the following
will evaluate to 0 and we'll do nothing:
^:(>/@i.~)

Otherwise it will evaluate to 1 and we'll apply the verb to the left of ^:
   {: + i.@>:@-/)@i.~ C. ]

which moves the left item to the right of the right item.  This movement is
simply a cyclic permutation of all the items between (and including) the two
elements in question.
J has primitive to apply such a cyclic permutation:
<cyclic permutation definition> C. ]

and the remainder of the verb does nothing but pick out the indexes we need to
cycle:
{: + i.@>:@-/)@i.~

which seems longer than it should be, but I wasn't able to golf that phrase
further.
Finally we rebox the result <@ and we're done.

Perl 6, 40 bytes
{*.permutations.first(*.grep(.any)eq$_)}

Try it online!
Anonymous code block that takes the input curried (like f(subList)(masterList), and finds the first lexographical permutation of the indexes of the master list where the elements from the sub list are in the correct order.
Intuitively, the first satisfying permutation will leave the correctly ordered elements in the original order, while moving the incorrectly placed ones the minimum needed distance forward in order to have them in the correct order, which places them directly after the previous element in the subset.
Explanation:
{*                                     } # Anonymous code block that returns a lambda
  .permutations                          # In all permutations of the master list
               .first(                )  # Find the first permutation
                     (*.grep(.any)       # Where the order of the subset
                                  eq$_   # Is the same as the given order

Jelly, 9 bytes
Œ!iⱮṢƑ¥ƇḢ

Try it online! or Test suite
Inefficient, particularly with large master lists. Generates all possible permutations, filters out those where the subset is in the wrong order, and then returns the first.
Explanation
Œ!        | Generate all permutations of the master list
      ¥Ƈ  | Filter including only those where...
  iⱮ      |   the index of each sublist item in this permutation...
     Ƒ    |   is...
    Ṣ     |   in order.
        Ḣ | Finally take the first item

This doesn't seem like it would conform to the rule "Where the master list has two elements out of order according to the subset list, the item that is earlier in the master list should be moved to the earliest index where it is in the correct location relative to other items within the subset list. (i.e. immediately after the later item)"

@Beefster it works on the ones I’ve tried so far. I think the ordering of the permutations is such that this is the correct result. Happy to be proved wrong if there’s a counterexample.

@Beefster I’ve now tried all of your examples except the female names and the 1..12 and the ordering of the result is correct.

@Beefster My answer has a partial explanation for why this works

Python 2, 124 109 106 99 96 bytes
def f(a,b,i=0):
 while b[i+1:]:x,y=map(a.index,b)[i:i+2];i+=1;x>y>a.insert(x,a.pop(y))
 return a

Try it online!

C# (Visual C# Interactive Compiler), 118 bytes
a=>b=>{for(int j;b.Any();)foreach(var e in b.Intersect(a.Take(j=a.IndexOf(b.Dequeue())))){a.Remove(e);a.Insert(j,e);}}

Try it online!
Leveraging some classes in the System.Collections.Generic namespace. The master is a List<T> and the subset is a Queue<T>.
// a: master
// b: subset
a=>b=>{
  // continue until b is empty
  for(int j;b.Any();)
    // iterate over values that are out of order in a
    // per the head of b using loop variable e
    foreach(var e in
      // the out of order values are determined by
      // intersecting remaining values in b with
      b.Intersect(
        // values in a occurring before the current head of b
        // save the position in a to variable j and remove the head of b
        a.Take(j=a.IndexOf(b.Dequeue()))
      )
    ){
      // push back the out of order element in a
      a.Remove(e);
      a.Insert(j,e);
    }
}

Jelly, 24 bytes
i@€MƤFṬœṗƲḊ;JḟF}W€ʋ@¥ṢFị

Try it online! or Test suite
Explanation
A dyadic link that takes the subset as the left and master list as right arguments. The below example uses 9001, 42, 69, 1337, 420, 99, 255 as master and 69, 9001, 1337 as subset.
i@€                      | Find the index of each subset item in the master list [3, 1, 4]
         Ʋ               | Previous 4 links as a monad
   MƤ                    | Find the index of the maximum for each prefix of this list [1, 1, 3]
     F                   | Flatten (because the previous result are actually each length one lists)
      Ṭ                  | Convert to a boolean list [1,0,1]
       œṗ                | Partition the [3, 1, 4] list before each 1 [[], [3, 1], [4]]
          Ḋ              | Remove the empty first list [[3, 1], [4]]
                    ¥    | Previous two links as a dyad
                  ʋ@     | Previous 4 links as a dyad with reversed arguments
            J            | Sequence along the master list [1, 2, 3, 4, 5, 6, 7]
             ḟF}         | Filter out items in the flattened [3, 1, 4] list
                W€       | Wrap each item as a list [[2], [5], [6], [7]]
           ;             | Concatenate rhis to the [[3, 1], [4]] list
                     Ṣ   | Sort (effectively by first item in each list) [[2], [3, 1], [4], [5], [6], [7]]
                      F  | Flatten
                       ị | Look up in original master list (and implicitly output)


text:
Today is the Center
Given a date as input in any convenient format, output a calendar with that date as the exact center of a five-week window. The header of the calendar must include the two-letter abbreviations for the days of the week (i.e., Su Mo Tu We Th Fr Sa). Three-letter or other abbreviations of the days are not allowed.
For example, given April 2 2019 as input, the output should be
Sa Su Mo Tu We Th Fr
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31  1  2  3  4  5
 6  7  8  9 10 11 12
13 14 15 16 17 18 19

so that the given date is the exact middle of the calendar.
Given February 19 2020, output
Su Mo Tu We Th Fr Sa
 2  3  4  5  6  7  8
 9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
 1  2  3  4  5  6  7

For September 14 1752, show the following:
Mo Tu We Th Fr Sa Su
28 29 30 31  1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30  1

Input and output can be given by any convenient method.
The input is guaranteed non-empty and valid (i.e., you'll never receive "" or Feb 31 etc.).
Assume Gregorian calendar for all dates.
Leap years must be accounted for.
Input dates will range from Jan 1 1600 to Dec 31 2500.
You can print it to STDOUT or return it as a function result.
Either a full program or a function are acceptable.
Any amount of extraneous whitespace is acceptable, so long as the characters line up appropriately.
Leading zeros on the single-digit days are allowed, as are aligning the single-digit days to be left-aligned instead.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

R, 77 72 bytes
function(d,`~`=format)write(c(strtrim(d+-3:3~"%a",2),d+-17:17~"%e"),1,7)

Try it online!
Fixed output to use 2 letter day abbreviations.
-1 byte using strtrim thanks to Aaron Hayman.
Pads date numbers with leading 0s; takes input as a Date, which can be created by using as.Date("YYYY/MM/DD").
Weirdly short for an R ascii-art answer...

05AB1E, 175 174 172 171 160 bytes
¦WΘ1š-1šVтFY`2ô0Kθ4ÖUD2Qi\28X+ë<7%É31α}‹iY¬>0ëY1¾ǝDÅsD12‹i>1ë\1Dǝ¤>2}}ǝVY})DJIJk18+£35.£¬.•4ιõ÷‡o‹ƶ¸•2ôs`UÐ3‹12*+>13*5÷s3‹Xα©т%D4÷®т÷©4÷®·()DćsćsO7%._s€нT‰J«7ô»

Input in the format [day, month, year]. Output with leading 0s for single-digit days, and lowercase mo through su (+1 byte can be added if titlecase is mandatory).
Try it online or verify all test cases.
Holy shit.. This might be my new record for longest 05AB1E answer, and then I include some very complex ascii-art challenges I did... >.> EDIT: Hmm ok, almost.. ;p
Important note: 05AB1E doesn't have any builtins for Date objects or calculations. The only builtin regarding dates it has is today's year/month/day/hours/minutes/seconds/microseconds.
So because of that, almost all of the code you see are manual calculations to calculated the previous and next days (including transition over years and keeping in mind the leap years), and calculating the day of the week by using Zeller's congruence.
Huge parts of the code are copied from this earlier 05AB1E answer of mine, which will also be relevant for the explanation below.
Explanation:
We start by going to the first day of the previous month:
¦          # Remove the first item (the days) from the (implicit) input
 W         # Get the minimum (without popping the list itself)
           # (since the year is guaranteed to be above 1599, this is the month)
  Θ        # Check if its exactly 1 (1 if 1, 0 if in the range [2,31])
   1š      # Prepend a 1 as list (so we now have either [1,1] or [1,0]
     -     # Subtract this from the month and year
      1š   # And prepend a 1 for the day
        V  # Pop and store this first day of the previous month in variable `Y`

Then I use that date as start date, and calculate the next 100 days:
тF    # Loop 100 times:
  Y`2ô0Kθ4ÖUD2Qi\28X+ë<7%É31α}‹iY¬>0ëY1¾ǝDÅsD12‹i>1ë\1Dǝ¤>2}}ǝV
      #  Calculate the next day in line
      #  (see the linked challenge above for a detailed explanation of this)
   Y  #  And leave it on the stack
 })   # After the loop: wrap the entire stack into a list, which contains our 100 days

Then, with the input-date as the middle, I only leave the 17 before and 17 after that input-date from the list:
DJ          # Duplicate the 100 dates, and join the day/month/year together to strings
  IJ        # Push the input, also joined together
    k       # Get the 0-based index of the input in this list
            # (the joins are necessary, because indexing doesn't work for 2D lists)
     18+    # Add 18 to this index (18 instead of 17, because the index is 0-based)
        £   # Only leave the first index+18 items from the 100 dates
     35.£   # Then only leave the last 35 items

Now we have our 35 days. Next step is to calculate the day of the week, and create the header of the output-table:
¬                # Get the first date of the list (without popping the list itself)
 .•4ιõ÷‡o‹ƶ¸•    # Push compressed string "sasumotuwethfr"
             2ô  # Split it into chunks of size 2
s                # Swap to get the first date again
 `UÐ3‹12*+>13*5÷s3‹Xα©т%D4÷®т÷©4÷®·()DćsćsO7%
                 # Calculate the day of the week (sa=0; su=1; ...; fr=6)
                 # (see the linked challenge above for a detailed explanation of this)
  ._             # Rotate the list of strings that many times

See this 05AB1E tip of mine (section How to compress strings not part of the dictionary?) to understand why .•4ιõ÷‡o‹ƶ¸• is "sasumotuwethfr".
Then we create the days to fill the table itself based on our earlier created list of dates. Which we'll merge together with the header. After which we can print the final result:
s           # Swap to get the list of dates again
 €н         # Only leave the first item of each date (the days)
   T‰       # Take the divmod 10 of each
     J      # Join those divmod results together
            # (we now have leading 0s for single-digit days)
      «     # Merge this list together with the header list
       7ô   # Split it into chunks of size 7
         »  # Join each inner list by spaces, and then each string by newlines
            # (and output the result implicitly)

That's a huge amount of work!

Yeah, Java beats 05AB1E! :D First time ever, I guess ;-)

@LuisMendo Most was done last time with the linked challenge, but yes, it was a lot of work.. ;) Explanation has been added btw.

@OlivierGrégoire Now we're the same bye-count. ;)

@OlivierGrégoire And now it's lower again, sorry. ;p

@KevinCruijssen I feel like you have no incentive to help me golf my Java answer anymore ;-)

@OlivierGrégoire Actually, I was just looking for something to golf in your Java answer, but can't really see anything to golf further..

JavaScript (ES6),  141  126 bytes
Saved 15 bytes by borrowing .toUTCString().slice(0,2) from Neil's answer
Takes input as a Date object.
f=(d,n=0)=>n<42?(D=new Date(d-864e5*(24-n)),n<7?D.toUTCString().slice(0,2):(i=D.getDate())>9?i:' '+i)+`
 `[++n%7&&1]+f(d,n):''

Try it online!

Huh, I could have sworn that my code failed for the third test case when I originally wrote it... well that saves me 52 bytes...

JavaScript (Node.js), 205 152 145 bytes

f=
d=>`012345`.replace(g=/./g,r=>`0123456
`.replace(g,c=>`${new Date(d-864e5*(24-c-r*7))[+r?`getUTCDate`:`toUTCString`]()}`.slice(0,2).padStart(3)))
<input type=date oninput=o.textContent=f(this.valueAsDate)><pre id=o>

Try it online! Takes input as JavaScript Date object or timestamp. Edit: Saved 1 byte thanks to @EmbodimentofIgnorance, which then allowed me to save a further 7 bytes by adding a trailing newline to the output. Saved 52 bytes when I discovered that I was working around behaviour that was not actually buggy in the first place...

padStart(2) -> padStart(3), remove the space in the join string for -1 byte

Perl 6, 87 bytes
{~rotate(<Th Fr Sa Su Mo Tu We>,.day-of-week),|comb 21,($_-17..$_+17)>>.day.fmt('%2d')}

Try it online!
Takes a Date object, returns a list of lines.

C# (Visual C# Interactive Compiler), 124 120 bytes
n=>{for(int i=0;i<42;)Write($"{(i<7?$"{n.AddDays(i-3):ddd}".Remove(2,1):n.AddDays(i-24).Day+""),3}"+(++i%7<1?"\n":""));}

Try it online!

Java (JDK), 149 bytes
d->{d.add(5,-24);for(int i=0,w;i<42;d.add(5,1))System.out.printf("%c%2s",i%7<1?10:32,i++<7?"SaSuMoTuWeThFr".substring(w=d.get(7)%7*2,w+2):d.get(5));}

Try it online!
Credits

-13 bytes thanks to Kevin Cruijssen.

Got it! 161 bytes. Now you can help me golfing my 05AB1E answer below yours again. ;p

159 bytes

@KevinCruijssen Wait... what? I congratulate you! I tried to do this, but couldn't find a way to do it, and yet you did it! Very nice :-)

At first I also didn't saw any way to golf it, but then I thought about using the strings with sizes 2, and combine it with the %3s of the format, which ended up with the 161 bytes version. And only then I noticed your original %s%3s and j++%7<1?"\n":"" could be golfed to %c%2s and j++%7<1?10:32. :)

Maybe you see something more to combine the i and j somehow? Or something shorter for j++%7<1?10:32 with some bitwise magic? But I'll leave that to you. I'm going back to work, lol. ;)

@KevinCruijssen I couldn't merge the variables, but I could simplify the w variable usage (I renamed in order to be more understandable).

Ah, of course.. Nice teamwork! ;) PS: Where does the w stand for? Why not h for header?

@KevinCruijssen w for "day of week". Also, bit twiddling can only lead to (i%7+6)/7*22+10 which is much longer.

Yeah, something similar as that one I also had, but it's indeed longer than the ternary check. Ah well, still -20 bytes from your original 172. :D As I mentioned, now you can help me with my 05AB1E answer, haha.

If only I knew that language...

MATL, 34 33 31 bytes
YO-17:17+t7:)8XOO3Z(!1ew7XOU7e!

Try it online!
Explanation
YO       % Implicit input. Convert to date number. This is a single number
         % that specifies the date
-17:17   % Push [-17 -16 ... 16 17]
+        % Add to date number, element-wise. This gives a row vector of 35
         % date numbers centered around the input date
t        % Duplicate
7:       % Push [1 2 ... 7]
)        % Index into the 35-element vector. This keeps the first 7 entries
8XO      % Convert to day-of-week in 3 letters. Gives a 3-col char matrix
O3Z(     % Write char 0 (equivalent to space for display purposes) into the
         % 3rd column
!1e      % Tranpose and linearize into a row. This produces a string such as
         % 'Tu We Th Fr Sa Su Mo ', to be used as column headings
w        % Swap. This brings to top the row vector of 35 date numbers
         % computed from the input
7XO      % Convert to day-of-month. Gives a 2-col char matrix
U        % Convert each row to number
7e!      % Reshape into 7-row matrix and transpose
         % Implicit display. This prints the string with the headings and
         % the matrix. The latter has a minimum-one-space separation between
         % columns, so it is aligned with the headings

Wolfram Language (Mathematica), 123 bytes
(s=#;Grid@Join[{StringTake[ToString@DayName[s~d~#]&/@Range[-3,3],2]},Partition[Last@d[s,#]&/@Range[-17,17],7]])&
d=DatePlus

Try it online!
I don't know why Grid doesn't work on TIO but this code outputs this

@DavidC saved 1 byte

Maybe Grid doesn't work because TIO can't center the items like in your picture?

@AdmBorkBork There is a way to load graphics like this in TIO. Someone had shown me last year I think. But i can't remember how to do it... So if anyone knows, let us know!

PHP, 197 189 187 bytes
for($d=date_create($argn)->sub($i=new DateInterval(P17D)),$i->d=1;$x++<35;$h.=$x<8?substr($d->format(D),0,2).' ':'',$d->add($i))$o.=str_pad($d->format(j),3,' ',2);echo wordwrap($h.$o,20);

Try it online!
Input is STDIN as a date string. Run with php -nF.
$ echo April 2 2019|php -nF cal.php

Sa Su Mo Tu We Th Fr
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31  1  2  3  4  5
 6  7  8  9 10 11 12
13 14 15 16 17 18 19

Verify all test cases
Or 174 bytes with zero-padded single digits.

Excel VBA, 190 159 bytes
Thanks @TaylorScott
Function z(i)
Dim d(5,6)
v=DateValue(i)-17
For x=1To 5
For y=0To 6
d(0,y)=Left(WeekdayName(Weekday(v+y)),2)
d(x,y)=day(v+y+(x-1)*7)
Next y,x
z=d()
End Function

Takes input in the form of a valid date string for Excel VBA (e.g. February 19, 2020; 2/19/2020; 19-Feb-2019), and returns an array with the given calendar centered on it.

You can get this solution down to 159 by removing the whitespace from this solution, Function z(i)
Dim d(5,6)
v=DateValue(i)-17
For x=1To 5
For y=0To 6
d(0,y)=Left(WeekdayName(Weekday(v+y)),2)
d(x,y)=Day(v+y+(x-1)*7)
Next y,x
z=d()
End Function

@TaylorScott Thanks, was only using the built in editor which autopopulates those spaces.

Red, 153 131 bytes
func[d][s: d - 24 loop 7[prin[""copy/part system/locale/days/(s/10) 2]s:
s + 1]loop 5[print""loop 7[prin pad/left s/4 3 s: s + 1]]]

Try it online!

T-SQL, 203 bytes
DECLARE @f date='2020-02-19'

,@ char(20)=0,@d char(105)=0SELECT
@=left(format(d,'D'),2)+' '+@,@d=right(d,2)+char(32-n%7/6*19)+@d
FROM(SELECT dateadd(d,number-17,@f)d,number n
FROM spt_values WHERE'P'=type)x ORDER BY-n
PRINT @+'
'+@d

The online version is slightly different, this posted version works in MS-SQL Studio Management. It saves 1 bytes compared with the online version, but doesn't give the correct result online
Try it online

Python 2, 115 bytes
from datetime import*
d=input()
for i in range(42):print(d+timedelta(i-24)).strftime('%'+'da'[i<7])[:2]+i%7/6*'\n',

Try it online!
Not sure if this is allowed... takes input from STDIN in the form date(year, month, day). This can also be represented as __import__('datetime').date(year, month, day). These are really __import__('datetime').date objects.


text:
Count using letters
What to do?
Starting from a, count in the sequence:
a, b, c, d, ... , y, z, aa, ab, ac, ... , ay, az, ba, bb, bc, ... , zy, zz, aaa, aab, aac, ... , zzy, zzz, aaaa, aaab, aaac, ...

Input
The input, n, will an integer representing how far to count.
Output
The output should be n space-separated strings following the above counting sequence.

Example
Note: some strings are removed from the output to be concise.
Input -> Output
15 -> a b c d e f g h i j k l m n o
100 -> a b c d ... cs ct cu cv
1000 -> a b c d ... ali alj alk all
10000 -> a b c d ... ntm ntn nto ntp
100000 -> a b c d ... eqxa eqxb eqxc eqxd

A nicely written first challenge, but one we've already had.

Welcome to PPCG! A bit of a shame about the duplication, it's a nicely laid out challenge. We have a sandbox to test the waters and iron out problems as well; hopefully you enjoy your time here! :-)


text:
Pristine Bit Checking
Write a program/function that takes two integers in the range \$0\$ to \$255\$ inclusive, and returns whether the binary forms of the numbers are exactly one bit different.
For example, \$1\$ and \$0\$ have binary forms 00000001 and 00000000, which are one bit apart. Similarly, \$152\$ and \$24\$ are 010011000 and 000011000, so they return true.
However, your code must be pristine, such that if any one bit in your program is flipped, it should throw an error. For example, if your program was the single byte a (01100001), then all the 8 possible modified programs:
á ! A q i e c `

must throw an error. Make sure you are modifying by bytes (e.g. the á up there is actually representing the byte \$225\$, not the actual two byte character á).
Test cases:
0,1     => Truthy
1,0     => Truthy
152,24  => Truthy
10,10   => Falsey
10,11   => Truthy
11,12   => Falsey
255,0   => Falsey

Rules:

Provide a testing framework that can verify that your program is properly pristine, since there will be a lot of possible programs (number of bytes*8), or else a complete proof of pristineness.

Please make sure your program is valid before you post it.

Output needs to be either truthy/falsey (either way around is fine), or else two distinct non-error values
Errors can be runtime, compiler, interpreter etc.

If anyone's looking for a way to generate all possible variations of their solution, this Japt programme should (someone please double check) do the job: https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=rK5jIKT5VDggrKNay15FpVnDrM1kw8PLo2hFWMPDY2lVILc&input=ImEi

Here's one in Python as well: Try it online!

I'm trying to think of a way to make Pristine machine code.  If a bit is flipped in a register field, it just reads the wrong register without crashing.  Perhaps the code could checksum itself.  Without that requirement x86 can do this in two instructions (xor and popcnt)

Python 2, 35 bytes
lambda a,b:(a^b)&-(a^b)in[a^b or[]]

Try it online!
Uses the power-of-two check n&-n==n, eliminating the n==0 false positive.
For reference, these are the pairs of one-char binary operators that are one bit apart, making them hard to use:
+ /
- /
* +
% -
< |
< >

Fortunately, & and ^ are not among these.
Also note that == can become <=, and + can become the comment character #.

Python 2, 41 bytes
lambda a,b:bin(a^b).count(`+True`)is+True

Try it online!
Taking TFeld's lambda a,b:bin(a^b).count('1')==1 and making it pristine by changing the 1's to +True and == to is. Thanks to Jo King for 1 byte.

Python 2, 72 67 50 bytes
lambda a,b:sum(map(int,'{:b}'.format(a^b)))is+True

Try it online!
-5 bytes, thanks to Jo King

Returns True/False for for truthy/falsey.
The program is basically the same as lambda a,b:bin(a^b).count('1')==1, but without numbers and other chars which work when bit-flipped.
Works by making sure that almost everything is a named function (which are all quite pristine)
The pristine test at the end flips a single bit (for every bit), and tries the function on an input. If that works (correct or not), that variation is printed. No printed programs = pristine function.

Java 8, 68 61 56 45 bytes
a->b->(a.bitCount(a^b)+"").equals(-~(a^a)+"")

-11 bytes thanks to @EmbodimentOfIgnorance, replacing constant java.awt.Font.BOLD with -~(a^a).
Try it online.
Explanation:
The shortest base function would be:
a->b->a.bitCount(a^b)==1

Try it online.
This is modified so there isn't a digit, =, nor one of the +/* operands in it for numeric calculations (so the + for String-concatenation is fine):
The +"" and .equals are to compare by String.equals(String) instead of int==int.
NOTE: Integer.equals(int) could be used here, but would be more bytes, since both the .bitCount and java.awt.Font.BOLD are primitive int instead of Integer-objects, so an additional new Integer(...) would be required to transform one of the two to an Integer-object, before we could use the .equals.

(int)Math.log(Math.E) is 21 bytes

59 bytes

@ExpiredData Thanks, actually just found a shorter constant with java.awt.Font.BOLD, but your Objects.equals is a nice golf, thanks!

@ExpiredData Actually, Objects is part of the java.util. import, so I have to add that to the byte-count I'm afraid, making it 69 bytes.. :(

Would -~(a^a) work for 1?

@EmbodimentofIgnorance Thanks, that indeed seems to work.

C (gcc), 56 bytes
d(a,b){return(sizeof((char)d))^__builtin_popcount(a^b);}

Try it online!
Returns 0 if the pair differ by 1, non-zero otherwise. Slightly unusual for C, unless you consider it returning EXIT_SUCCESS if the pair differ by 1, any other value otherwise.
Uses sizeof((char)d)) to produce the constant 1 in a pristine way while also forcing the function name to be pristine.
It then XORs that 1 with the popcount of the XOR of the arguments. Luckily the ^ symbol is easy to keep pristine, as is the very long identifier __builtin_popcount.
Meanwhile, here is the script used to test the solution:
#!/bin/bash

SOURCE_FILE=$1
FOOT_FILE=$2
TMP_SRC=temp.c

LENGTH="$(wc -c <"$SOURCE_FILE")"
BITS=$((LENGTH*8))

cat "$SOURCE_FILE" >"$TMP_SRC"
cat "$FOOT_FILE" >>"$TMP_SRC"
if gcc -w $TMP_SRC -o t.out >/dev/null 2>&1; then
    if ./t.out; then
        echo "Candidate solution..."
    else
        echo "Doesn't even work normally..."
        exit
    fi
else
    echo "Doesn't even compile..."
    exit
fi

for i in $(seq 1 $BITS); do
    ./flipbit "$i" <"$SOURCE_FILE" >"$TMP_SRC"
    cat "$FOOT_FILE" >>"$TMP_SRC"
    if gcc -w $TMP_SRC -o t.out >/dev/null 2>&1; then
        echo "Testing flipped bit $i:"
        cat "$TMP_SRC"

        ./t.out >/dev/null 2>&1
        STATUS=$?
        if [ "$STATUS" -eq 0 ]; then
            echo "It works!"
            exit
        elif [ "$STATUS" -eq 1 ]; then
            echo "It doesn't work..."
            exit
        else
            echo "It crashes"
        fi
    fi
done

Which uses the ./flipbit tool I wrote whose source is simply:
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    int bittoflip = atoi(argv[1]) - 1;
    int ch;

    while ((ch = fgetc(stdin)) != EOF) {
        if (bittoflip < 8 && bittoflip >= 0) {
            putchar(ch ^ (1 << bittoflip));
        } else {
            putchar(ch);
        }

        bittoflip -= 8;
    }

    return 0;
}

The tricky bits were:

Whitespace: All whitespace (including newlines) have pristine twins that will work similarly
Comparison: = doesn't work well, since it can be a comparison in every case it could appear. Similarly - doesn't work well. Thus ^ is used to assert equality with 1.
Variable names: f would clash with b, so had to use d as the function name instead.

How do you keep the ^ operator pristine? If the bits on that were changed, what's to stop it from becoming a different operator? This would still compile, but would just give you the wrong answer. Am I misunderstanding something about the meaning of the word "pristine" here?

By flipping only one bit, ^ can only be changed into any one of _\ZVN~Þ or the unprintable character at codepoint 30. ~ is the only one of those which is an operator, but it's only a unary operator.

Other answers have found -~(a^a) works as a 1.  IDK if that helps, because then you'd need another way to make the function pristine.  Maybe call d(a,b) after the return, so it doesn't execute but has to parse.

I don't suppose we can use Test if a bitboard have only one bit set to 1 a&&!(a&(a-1)) bithack to test for having exactly 1 bit set while being pristine.  And it might even be longer than __builtin_popcount.  Plus you need the number multiple times, so you'd need a^=b; and then use a.

@Peter Cordes I looked into such solutions as well. Unfortunately ! is one bit off from   so it is very tricky to incorporate. Similarly - and = can always be swapped as can + and * or / (and usually ;) so those operators are pretty much not going to work.

Can you do (sizeof(char)) instead of (sizeof((char)d)) to save 3 bytes? https://tio.run/##bZDBDoIwDIbvPEWPnWIiJnqZPIkRMsbQJTrI3Iwb4dlxSFCM9tC06ff/TctXJ877vkQWF6TVwlit8Ca9qCvkZ6YJyfK8sPJipMqbuuG1VQZZVhDa9VIZuDKpcCiYPvEYBg0sQn0/HAm0EYQYpi729NVUtQb0kMKagoc9bLY7Csuln@A340bGfRg3ZyZjLW72YgJboo8doT@AVeLRCG5EGSD8c4zPgnGaQhLE3@oKcLJPZz7kixpi/Bskn@1dNOZoNl7TqOuf

Or even use __LINE__ instead of sizeof(char).  I think its fine to assume that your function will be on line 1 of your .c file.  Or even unix is defined to 1 on TIO, and probably most other Linux.

The main reason for the char-casted sizeof is to get d baked into the source in the fewest bytes possible. Otherwise d (or whatever you name the function) can just be changed and the code will still work. Even (__LINE__) with d(); wont work because d(); can be changed to any other letter and it will still compile since the function never has to be called, thus isn't linked.

@LambdaBeta If the name of the function changes, then there will be a link error, even if d is not self-referential.  I think this is sufficient, personally.

R, 38 37 bytes
-1 byte thanks to Nick Kennedy.
dpois(log2(bitwXor(scan(),scan())),T)

Try it online! (Thanks to Giuseppe for setting up the TIO properly.)
Proof that it is pristine (using Nick Kennedy's checker).
Outputs 0 for falsey, and a positive value for truthy, which I understand is acceptable since R will interpret these as False and True.
Explanation: bitwXor(a,b) gives (as an integer) the bitwise XOR between a and b. To check whether it is a power of 2, check whether its log in base 2 is an integer. The function dpois gives the probability density function of the Poisson distribution: its value is 0 for non-integer values, and something positive for non-negative integers. The T is there because dpois requires a second argument (any positive real works, and T is interpreted as 1).
If we insist on outputting to distinct values, the following version outputs FALSE or TRUE in 42 bytes (thanks to Giuseppe for -8 bytes):
dpois(log2(bitwXor(scan(),scan())),T)%in%F

and is also pristine. Try it online!

Well done on getting something so much smaller than mine! You could replace pi with T to save a byte (still pristine). Also your TIO doesn’t correspond to your answer at the moment.

@NickKennedy Thanks! (And thanks for writing the code to check it is pristine!).
The TIO I linked to is a modified version that checks all the test cases. I'll add a TIO to the actual code, but I can't figure out how to get TIO to run properly with two calls to scan(); do you have an idea? (The code works fine on a computer.)

@NickKennedy Maybe something like this? for getting the TIO and the code to match?

@Giuseppe Wonderful, thanks!

your second version could use F instead of exp(-Inf), along the same lines as Nick's T :-)

@Giuseppe Duh! I spent a long time looking for pristine code to get integers (floor(sqrt(pi)) or exp(exp(-Inf)) for 1 for example) and never thought of the simple F and T!

Finally, my deleted mathematica answer in use IntegerQ@*Log2@*BitXor. This is the only time I wish mathematica threw more errors!

R, 83 bytes
t(identical(sum(.<-as.double(intToBits(Reduce(bitwXor,scan())))),sum(T^el(.[-T]))))

Try it online!
Proof that this is pristine
Working around the fact that as.integer, as.double etc. are only a bit away from is.integer, is.double etc. was the hardest bit. In the end, using sum(T^el(.[-T]) as a way of both generating a one and checking that as.double has returned a >1 length vector was the best I could do. The wrapping t is to handle the fact that otherwise identical can become ide~tical.

Julia 0.7, 20 bytes
(a,b)->ispow2(a⊻b)

Try it online!
Here is a pristine validator that tries running each modified anonymous function against some input, and neither passes successfully. Note that the code has a multi-byte unicode character, and some possible outputs from bit flipping are not even included, as those produce invalid UTF-8 strings.

x and y are one bit apart, so I believe this is a counter example. y and x are also 1 bit off 9 and 6 respectively.

Damn, while thinking about complex things, I absolutely missed the simplest one. Hopefully, changing the variables will fix it.

C# (Visual C# Interactive Compiler), 37 bytes
a=>b=>a!=b&((a^b)&-(a^b)).Equals(a^b)

The a=>b=> part cannot be changed, or else the function is invalid.
In a!=b, the = cannot be changed since int cannot be converted to bool.
Try it online!

C# (Visual C# Interactive Compiler), 128 101 77 70 61 74  bytes
-27 bytes thanks to Ascii-Only

a=>b=>{var d=Math.Log(a^b,(int)Math.E);return d.Equals((int)Math.Abs(d));}

Try it online!
You have to be quite creative to get numbers in C# without using literals. Only uses ^ operator. Variables a,b are all more than 1 bit away from each other and everything else is a keyword/name.

you don't need to count bits - checking if it's a power of 2 between 1 and 128 inclusive is enough

@ASCII-only Good luck checking that in a reasonable number of bytes when we can't use integers nor +/*= for mathematical or validating operations. ;)

@KevinCruijssen C# has enums too :(. damnit

101?

@ASCII-only Ik. And with some flags in the Visual C# Interactive Compiler you don't even need the imports. Still, how would you check if it's a power of 2 and within that range? Usually when I check if it's a power of 2 I use a&~-a==0, but the ==0 should then already be replaced, and the &, -, ~ possibly as well (haven't checked those yet).

@KevinCruijssen .Equals works in C# :P. and i was thinking an Enumerable.Range and a Some (?) but maybe that doesn't work?

@ASCII-only Ah of course, .Equals works with primitives in C#. Well, in that case go right ahead. ;p haha. Hmm, Enumerable.Range might perhaps be possible. I'm not too skilled with C#, so I'll leave that to you guys. :)

@ASCII-only I get 121 bytes with enumerable.range (Int64 better than Uint16)

sadly, it really is longer :( (Uint16, not Int16)

O_o another -24. btw you no longer use +

Invalid, the = can be replaced with a -,see https://tio.run/##bc4xD4IwEAXg3V/heJcUQhuZkCYOOOHsZnKtoE2wjbYM/vpacTCC4/vycve0z7Q3cT9avT0/Ld2MZlMwNjDl3CDluq8j1VLVEig7ULjmrbsAnRSDVMJJGsS8uY80ePjiTnkgxCpWq@PDhK41toMeOEKR9McKTDwzXgoEsVnwu1v81eWJ9IuLuYqy/EyILw

Fixed @EmbodimentofIgnorance, seems odd I thought that would work but ran it and tio threw an exception. Must have had something else broken at the time

JavaScript (ES6 in strict mode), 61 bytes
(y,z,e)=>eval(`(y${(e='^=z)*!(y&~-y)')!='^=z)*!(y&~-y)'||e}`)

Try it online! or Make sure that all modified programs are wrong

Oh my gosh I didnt realize I clicked a code golf link and saw this answer out of context and almost had a heart attack. Like, OMG NO

@Marie Caution! You can only stare at this code with certified golf glasses. Otherwise, it may burn your retina. :p

Groovy, 47 36 bytes
a,b->a.bitCount(a^b).equals(-~(a^a))

Try it online!
Adapted version of Kevin Cruijssen's Java answer.

MATLAB, 37 bytes
@(c,e)eq(nnz(de2bi(bitxor(c,e))),eye)

Sorry, no TIO link, because I can't get the test suite to work under Octave. Thanks @ExpiredData for some helpful comments.
Test suite:
program = '@(c,e)eq(nnz(de2bi(bitxor(c,e))),eye)';
number_of_characters = nnz(program);
success = [];
for character_counter = 0 : number_of_characters
    for bit_no = 1:8
        prog_temp = program;
        if(character_counter > 0)
            prog_temp(character_counter) = bitxor(double(prog_temp(character_counter)),2^(bit_no-1));
        elseif(bit_no<8) % Test the unmodified program once
            continue
        end
        try
            eval(prog_temp);
            eval('ans(2,3)');
            disp(prog_temp)
            success(end+1)=1;
        catch
            success(end+1)=0;
        end
    end
end
assert(nnz(success)==1)

41 bytes

@ExpiredData Thanks for the suggestion. I went for a MATLAB numel instead, because my test suite does not seem to be working in Octave.

38 bytes maybe.. not got a matlab license but should work

@ExpiredData Thanks, one can actually do one byte better with eye!

is this strategy maybe better? @(a,b)eq(nnz(diff(de2bi([a;b]))),eye)
It's equivalent but i think this strategy can be golfed.

@ExpiredData Sadly, that fails on [a:b] and [a+b] also being valid programs.

36? - @(c,e)~(nnz(de2bi(bitxor(c,e)))-eye)

@ExpiredData @(c,e)~(nnz(de2bi(bitxor(c,e)))-eye)
@(c,e)~(nnz(de2bi(bitxor(c,e)))/eye) There's a good reason why I'm avoiding numbers as well as operators.

Yes shame I can't test these as I go

@ExpiredData I know, I'm very annoyed at Octave too. But using the Python program in the OP comments is handy to see if you can introduce a new character without problems.

Perl 6, 77 43 bytes
Thanks to Jo King for -33 bytes.
{elems(i)eq(sum [+^](@_).polymod(+@_ xx*))}

This is equivalent to
{1 eq(sum [+^](@_).polymod(2 xx*))}

1 was rewritten as elems([""]). 2 was rewritten as sum(elems([""]),elems([""])); elems(["",""]) might seem to work but elems([""-""]) is also valid and seems to hang the tester.
Try it online!

JavaScript (Node.js), 20 bytes
b=>d=>[i=d^b][i--&i]

Try it online!
validator by Arnauld, modified (not use strict)