text:
Add Numbers deux — Bitwise Addition
Your job is to implement bitwise addition.
To ensure that this is done, you will compute and print the result of addition without carry (or bitwise XOR). Then, you will compute the carry of the addition (bitwise AND) and multiply it by two (bitwise left shift). If the carry is nonzero, then you add the carry and the previous result until the carry is zero, at which point you stop producing output. If all is done correctly, the final result printed should be the sum of the two integers that you received as input.
Here's an ungolfed reference implementation in C:
#include <stdio.h>

void print_add(unsigned a, unsigned b)
{
    unsigned carry;

    while(b)
    {
        carry = a & b;
        a ^= b;
        printf("%u\n", a);
        b = carry << 1;
    }
}

Input
Two positive integers in any convenient format.
Output
A list of positive integers in any convenient format representing each result of addition without carry. Leading/trailing whitespace/newlines are allowed.
Rules

This is code-golf. The answer with the least bytes in each language wins, which means that I will not accept an answer.
Standard loopholes are forbidden. This includes, but is not limited to, Abusing native number types to trivialize a problem.

Testcases
1, 1 -> 0, 2
3, 17 -> 18, 16, 20
6, 7 -> 1, 13
21, 19 -> 6, 36, 32, 40
10, 9 -> 3, 19
20, 20 -> 0, 40

Your code must work for at least all pairs of positive integers that your integer type can represent the sum of.

This would have been far more interesting (at least to me) as an efficiency-golf challenge.

@CodyGray As in fastest-code or fastest-algorithm? fastest-code would be somewhat hard to test and fastest-algorithm is trivial, it's used here.

JavaScript (ES6), 34 bytes
Takes input as (A)(B), where A+B is a positive-looking 32-bit integer, i.e. less than 0x80000000.
Returns an array.
A=>g=B=>B?[A^=B,...g((B&~A)*2)]:[]

Try it online!
Or for 35 bytes, a BigInt version with unlimited input:
A=>g=B=>B?[A^=B,...g((B&~A)*2n)]:[]

Try it online!
How?
In order to use only 2 variables and pass a single variable to the recursive function, we apply the XOR right away to A and prepend the result to the output array.
Instead of computing (A AND B) * 2, we now need to compute (B AND (A XOR B)) * 2. Fortunately this can also be expressed as:
(B AND (NOT A)) * 2

leading to the rather short (B&~A)*2 in JS syntax.

sed -En, 120 bytes
:L;s/0(.{8})0/a\1a/;s/0(.{8})1/b\1a/;s/1(.{8})0/b\1a/;s/1(.{8})1/a\1b/;tL;y/ab /01\
/;P;s/$/0/;tM;:M;s/\
.(.*1)/\
\1/;tL

Try it online!
Or try all the test cases online!
Input: Two 8-bit integers written in binary (on one line, with a space in between them).
Output: Also 8-bit binary numbers.
For convenience this is written for 8-bit integers, but if you want to use 32-bit integers, for instance, just change the instances of 8 in the script to 32. You can try out the 32-bit version here.

Bash, 69 \$\cdots\$ 56 45 bytes
11 bytes less, thank to Mitchell Spector!
d()(echo $[a=$1^$2];((c=$1&$2))&&d $a $[c*2])

Try it online!
Commented long version:
# Defines function d with parenthesis sub-shell block (commands), rather than
# curly-braces commands block, to save leading space and trailing semicolons.
d ()
(
  # Print and assign new value, using deprecated $[expression] syntax, rather
  # than modern's $((expression)) syntax, saves 2 bytes.
  echo $[a=$1^$2]
  # Bash stand-alone arithmetic expression's return-code, conditions recursive
  # call, with argument 2 computed inline, using deprecated but shorter
  # arithmetic expression.
  ((c=$1&$2)) && d $a $[c*2]
)

Note that the shorter but deprecated $[expression] syntax is going to be removed in later Bash versions.
See: man bash Bash 5.0.3(1)-release

Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result.
The format for arithmetic expansion is:
$((expression))
The old format $[expression] is deprecated and will be removed in upcoming versions of bash.

See also: bug-bash ML:
On Sun, Apr 8, 2012 at 12:50 AM, Linda Walsh  wrote:

Re: status on $[arith] for eval arith vsl $((arith))??
  ...
  Some linux distributions patch the man page and document $[ ] as deprecated.
The SUS rationale says:
In early proposals, a form $[expression] was used. It was functionally
  equivalent to the "$(())" of the current text, but objections were
  lodged that the 1988 KornShell had already implemented "$(())" and
  there was no compelling reason to invent yet another syntax.
  Furthermore, the "$[]" syntax had a minor incompatibility involving
  the patterns in case statements.

Welcome to Code Golf, Léa! Congrats on your first entry, hope the 69 was just a coincidence :p Unfortunately, I don't know Bash, so I can't comment on the execution. However, as for the format: You'll soon notice many people use TIO to link to their code in a functioning environment for all to play around with! Not just that, but it makes it easier to show off the test inputs, in the footer or input slot depending, and boilerplate can be hidden in the header. Finally, it'll autogenerate your post which you can paste!

All that'll be left to add is an explanation, and you'll notice nearly everyone copies and pastes that autogenerated bit, which is why all the answers have the same format! Here's the TIO link I created for you, with the input cases as well! To copy the classic formatting after you click on the link, just press Esc1, S and then G... Vim Style!!! I highly recommend pasting that here. Golf away!

@AviF.S. Really nice guidance with TIO. Shortened code even more than my initial submission.

Welcome -- Nice first answer!  By the way, I think you can shorten it to 45 bytes like this.

Do you happen to know what the "minor incompatibility" is between the $[...] syntax and case-statement patterns?  I know that $[...] is said for many years to have been heading towards deprecation, so I don't use it in production code, but I don't see what parsing issues could arise in a case statement that uses it.

@MitchellSpector case "$1" in $[abc]) echo 'Case conflicting with deprecated $[expression] shall match $a, $b or $c';;esac. Forces escaping of the $ sign as: in \$[abc])

Thanks, Léa, that makes sense.

C (gcc), 65 \$\cdots\$ 46 45 bytes
Saved 5 bytes thanks to ceilingcat!!!
f(a,b){for(;b;b&=~a,b*=2)printf("%d ",a^=b);}

Try it online!

I added a clarification so you don't need that long -- ugh.

@S.S.Anne Great - thanks for the clarification! :-)

Rust, 69 68 bytes
|mut a:u8,mut b:u8|while b>0{let c=(a&b)*2;a^=b;b=c;print!("{} ",a)}

A port of math junkie's python answer.
Try it on Rust Playground.
I had to use a temporary variable because destructuring in assignments is still being worked on

I believe the trailing semicolon shouldn't be included in the byte count (as it is part of the assignment to g and not the closure), which saves a byte.

You're probably right, as the code without the semicolon is an expression that evaluates to a closure, which could also be used as a return value.

Python 2, 39 bytes
def f(a,b):1/b;print a^b;f(a^b,(a&b)*2)

Try it online!
A recursive function that prints all intermediate values, then terminates with an exception.

Python 2, 41 bytes
f=lambda a,b:b*[0]and[a^b]+f(a^b,(a&b)*2)

Try it online!
A recursive function that takes in two summands and returns a list of intermediate results.

Jelly,  12  11 bytes
&/Ḥṭ^/ƲƬḢ€Ḋ

A monadic Link accepting a list of two integers which yields a list of integers.
Try it online!
How?
Note that at the end of proceedings we'll have the sum and a carry of zero, and if we were to compute the addition without carry and the carry once more we'd get the same results, so we can keep going until [sum-without-carry, carry] does not change...
&/Ḥṭ^/ƲƬḢ€Ḋ - Link: list of two integers, [a,b]
       Ƭ    - Collect up (starting with [a,b]) while results are distinct applying:
      Ʋ     -   last four links as a monad:
 /          -     reduce (current pair, [x,y]) by:
&           -       bitwise AND
  Ḥ         -     double
     /      -     reduce (current pair, [x,y]) by:
    ^       -       bitwise XOR
   ṭ        -     tack -> [x^y, (x&y)*2]
        Ḣ€  - head each
          Ḋ - dequeue (remove a from the front)

MATL, 13 bytes
`Z~t1MZ&Et]xx

Try it online! Or verify all test cases.
Explanation
`       % Do...while
  Z~    %   Bitwise XOR. Takes the two inputs implicitly the first time
  t     %   Duplicate
  1M    %   Push the inputs of the latest bitwise XOR again
  Z&    %   Bitwise AND
  E     %   Multiply by 2
  t     %   Duplicate. This copy will be used as loop condition
]       % End. If the top of the stack is not 0 a new iteration is run
xx      % Delete top two elements (a 0 from the last bitwise AND and a
        % copy of the result from the last bitwise XOR)
        % Implicitly display

Batch, 68 bytes
@if %2==0 exit/b
@set/a"a=%1^%2,b=(%1&%2)*2
@echo %a%
@%0 %a% %b%

Explanation:
@if %2==0 exit/b

Repeat until b is zero.
@set/a"a=%1^%2,b=(%1&%2)*2

Calculate the XOR and the carry.
@echo %a%

Output the next result.
@%0 %a% %b%

Restart with the new operands.

Java (JDK), 54 bytes
(a,b)->{for(;b>0;b=(b&~a)*2)System.out.println(a^=b);}

Try it online!

05AB1E, 12 bytes
Δ`^=y`&D_#·)

Try it online!

Python 2, 44 43 bytes
-1 byte thanks to @SurculoseSputum
a,b=input()
while b:a,b=a^b,(a&b)*2;print a

Try it online!
Very simple implementation. Pretty much a golfed version of the reference code.

-1 byte by not using c.

@SurculoseSputum Ah, thanks. I played around with that a little bit, but I didn't get the ordering quite right

Javascript ES6, 48 chars, uint32 full support
a=>b=>{for(;b;alert(a>>>0))[a,b]=[a^b,(a&b)<<1]}

Test with console.log instead of alert:

f=a=>b=>{for(;b;console.log(a>>>0))[a,b]=[a^b,(a&b)<<1]}

g=(x,y,...res)=>console.log(`=== ${x} ${y} => ${res} ===`)+f(x)(y)

g(2147483648, 2147483648, 0)
g(3000000000, 1, 3000000001)
g(2147483648, 0)
g(1, 1, 0, 2)
g(3, 17, 18, 16, 20)
g(6, 7, 1, 13)
g(21, 19, 6, 36, 32, 40)
g(10, 9, 3, 19)
g(20, 20, 0, 40)
.as-console-wrapper.as-console-wrapper { max-height: 100vh }

Javascript ES6, 43 chars, int32 except 2**32
a=>b=>{for(;b;alert(a))[a,b]=[a^b,(a&b)*2]}

Test with console.log instead of alert:

f=a=>b=>{for(;b;console.log(a))[a,b]=[a^b,(a&b)*2]}

g=(x,y,...res)=>console.log(`=== ${x} ${y} => ${res} ===`)+f(x)(y)

g(2147483648, 2147483648, 0, 'never')
g(3000000000, 3000000000, 0, 1705032704)
g(3000000000, 1, 3000000001)
g(2147483648, 0)
g(1, 1, 0, 2)
g(3, 17, 18, 16, 20)
g(6, 7, 1, 13)
g(21, 19, 6, 36, 32, 40)
g(10, 9, 3, 19)
g(20, 20, 0, 40)
.as-console-wrapper.as-console-wrapper { max-height: 100vh }

Javascript ES 2020, 44 chars, infinite integers
a=>b=>{for(;b;alert(a))[a,b]=[a^b,(a&b)*2n]}

Test with console.log instead of alert:

alert=x=>console.log(x+"")

f=a=>b=>{for(;b;alert(a))[a,b]=[a^b,(a&b)*2n]}

g=(x,y,...res)=>console.log(`=== ${x} ${y} => ${res} ===`)+f(x)(y)

g(2147483648n, 2147483648n, 0, 4294967296)
g(3000000000n, 3000000000n, 0, 6000000000)
g(3000000000n, 1n, 3000000001)
g(2147483648n, 0)
g(1n, 1n, 0, 2)
g(3n, 17n, 18, 16, 20)
g(6n, 7n, 1, 13)
g(21n, 19n, 6, 36, 32, 40)
g(10n, 9n, 3, 19)
g(20n, 20n, 0, 40)
.as-console-wrapper.as-console-wrapper { max-height: 100vh }

psst neither 2^31 nor 2^32 can be represented in any traditional integer format (which Javascript's integer type is)

This answer shows that they can ;)

Sorry, meant to say "signed integer format".

Formally js doesn't have integer type at all, only double. And BigInt from 2020 standard.

interesting. Still, 32-bit signed two's complement has bitwise 0x80000000 as negative.

The built in code runner here i neat

Charcoal, 24 bytes
ＮθＮηＷη«≧＆θη≔⁻｜θιηθ≦⊗η⟦Ｉθ

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

Input a and b.
Ｗη«

Repeat while b is non-zero. This also makes a copy of b.
≧＆θη

Bitwise And b with a.
≔⁻｜θιηθ

Bitwise Or a with the copy of b, and subtract the above value, thus replacing a with the Bitwise Xor of a and b.
≦⊗η

Bitwise left shift b as it is now the carry.
⟦Ｉθ

Output the value of a on its own line.

C# (Visual C# Interactive Compiler), 48 bytes
(a,b,c,d)=>{for(;b>0;c=a&b,d.Add(a^=b),b=c<<1);}

Try it online!
This is my first time using a for loop to do operations within the actual iterator, which feels weird, and uncomfortable, but also calming.
Mostly just tried to play with the reference, and make it more compact. Will be returning to this later. Need to double check my answer is fully legal (using the List), but this is my initial attempt.
More Info:
(a,b,c,d)=>{         //Pass in variables via lambda expression, and now a  for loop
                     //Note, the c# for statement format is:
                     //for (initializer; condition; iterator)
                     ////body
                     //
    for(             //Start of for loop statement
        ;            //A mustache... jk. I am using no initializers, so just a ";" - totally blank
        b>0;         //My for loop conditional.  I used an int rather than a c bool, which is not as compact, maybe there's a better way
                     //For loop Iterators:
        c=a&b,       //c is carry
        d.Add(a^=b), //Append to end of list: a equals a xor b
        b=c<<1       //left shift
    )                //End Initializers, condition, and iterator parts of for loop
    ;                //Body of for loop (nothing)
}                    //End lambda expression

Why no c# link?

Try the above link "Try It online!", does that work?

I meant the link to an implementation. I've been curious to see what c# is like for a while.

I updated my code, sorry, I think  that's what you meant right?

It looks like you removed the link that TIO puts in for C# in your answer. I'll add it back, hang on... (there are some templates for Code Golf if you click the chain link on the top middle). I run Linux so Microsoft's C# doesn't work for me. Since I know that TIO runs on Linux, I knew there had to be a free implementation. That turns out to be Mono.

Great, thank you. That's what Unity uses, a cross platform C# implementation like that - https://github.com/dotnet/roslyn - which should work on linux

K4, 32 31 bytes
Solution:
1_*+(1 2*2/:'(~=/;&/)@\:0b\:')\

Examples:
q)k)1_*+(1 2*2/:'(~=/;&/)@\:0b\:')\1 1
0 2
q)k)1_*+(1 2*2/:'(~=/;&/)@\:0b\:')\3 17
18 16 20
q)k)1_*+(1 2*2/:'(~=/;&/)@\:0b\:')\6 7
1 13
q)k)1_*+(1 2*2/:'(~=/;&/)@\:0b\:')\21 19
6 36 32 40
q)k)1_*+(1 2*2/:'(~=/;&/)@\:0b\:')\10 9
3 19
q)k)1_*+(1 2*2/:'(~=/;&/)@\:0b\:')\20 20
0 40

Explanation:
Lots of eaches...
1_*+(1 2*2/:'(~=/;&/)@\:0b\:')\ / the solution
    (                        )\ / iterate
                        0b\:'   / convert each into into binary
                     @\:        / apply (@) each-left (\:) function to right
             (   ;  )           / two item list
                  &/            / AND
              ~=/               / XOR
         2/:'                   / convert each from binary
     1 2*                       / multiply first item by 1, 2nd by 2
   +                            / flip
  *                             / first
1_                              / drop first element


text:
How much weight can you lift?
With all the gyms closed down with the COVID-19 situation, we have to exercise with the weight we have lying around at home. The problem is, we have a small selection of plates at varying weights, and can't immediately determine if we can create a setup at the desired weight.
Given an unsorted array of weighted plates and an unsorted array of barbells of different weights, determine the fewest amount of plates you need to put on a barbell to reach the desired weight, in ascending order mirrored at the halfway point, basically mirroring how it would be loaded on a real barbell (see example output). The plates have to be in pairs; you cannot use a particular plate an odd number of times since you put one plate on each side for equilibrium (e.g. every plate of a certain weight on one side should have a counterpart of the same weight on the otherside). If the desired weight cannot be achieved, approximate as closely as possible (while still maintaining equilibrium on both sides).

Examples:

Input (3 barbells, a set of plates, and goal weight): [[10, 45, 6], [3.5,37,20,15,2.5,15,2.5,3.5,5,7], 47]
Output (exact match, barbell and plate arrangement): [10, [3.5,15,15,3.5]

Input (3 barbells, a set of plates, and goal weight): [[10, 45, 6], [3.5,37,20,15,2.5,15,2.5,3.5,5,7], 45]
Output (exact match, barbell and plate arrangement): [45, []]

Input (3 barbells, a set of plates, and goal weight): [[10, 45, 6], [3.5,37,20,15,2.5,15,2.5,3.5,5,7], 0]
Output (closest approximation, barbell and plate arrangement): [6, []]

Input (3 barbells, a set of plates, and goal weight): [[10, 45, 6], [3.5,37,20,15,2.5,15,2.5,3.5,5,7], 9001]
Output (closest approximation, barbell and plate arrangement): [45, [2.5,3.5,15,15,3.5,2.5]]
Winners will be selected first by time complexity, then character count for tie-breaker.

So to clarify, does equilibrium mean that 1. There must be the same number of plates on each side of the barbell. 2. For each individual plate on the left there should also be a matching plate on the right with the same weight.

I will clarify the question, your second point captures my intent. Each weighted plate on one side should have a counterpart of the same weight on the other side.

Welcome to the site!

Updated to only consider time complexity as primary judgment criteria then using character count for tie-breaking :-)

The 'equilibrium' requirement seems to me to mean that the plates with weights 5, 7, 20, and 37 in the examples can't ever be used, as there's only one of each. Is that the intention?

Yes that's correct, I added them to demonstrate the equilibrium requirement (47 would be easy to achieve with a 10lb barbell and a single 37 pound plate but it's not allowed). I'm currently working on this puzzle myself and will add more test cases once I have a working solution and some edge cases.

You might want to add the fastest-algorithm tag.

Good call, I've added the fastest-algorithm tag

C++ (gcc), \$ O(2^{\frac{|P|}4} \times (|B| + \frac{|P|}2)) \$, 933 bytes
Input/Output Format
Takes as input a vector of plates \$ P \$, a vector of barbells \$ B \$, and a target weight \$ W \$. It outputs the plate arrangement on the first line, and the barbell on the second line.
#include <bits/stdc++.h>
using namespace std;using d=double;
int f(auto b,auto p,d w){
unordered_map<d,int>u;vector<d>s,A,B;
for(auto i:p)u[i]++;
for(auto i:u)while((i.second-=2)>=0)s.push_back(i.first*2);
int z=s.size(),i,j,k;vector<pair<d,vector<d>>>x(1<<z/2),y(1<<z/2+1);d m=DBL_MAX,n,r;
for(i=0,k=1;i<z/2;i++){
for(j=0;j<k;j++)x[j+k]=x[j];
for(;j<k*2;j++)x[j].first+=s[i],x[j].second.push_back(s[i]/2);
auto _=x.begin();inplace_merge(_,_+k,_+k*2);k*=2;
}
for(k=1;i<z;i++){
for(j=0;j<k;j++)y[j+k]=y[j];
for(;j<k*2;j++)y[j].first+=s[i],y[j].second.push_back(s[i]/2);
auto _=y.begin();inplace_merge(_,_+k,_+k*2);k*=2;
}
for(auto f:b)
for(i=0,j=(1<<z-z/2)-1;i<1<<z/2&&j>=0;n>w?j--:i++){
n=x[i].first+y[j].first+f;
if(abs(n-w)<m)r=f,A=x[i].second,B=y[j].second,m=abs(n-w);
}
A.insert(A.end(),B.begin(),B.end());
sort(A.begin(),A.end());for(auto i:A)cout<<i<<' ';
reverse(A.begin(), A.end());for(auto i:A)cout<<i<<' ';
cout<<'\n'<<r;
}

Try it online!
Explanation
The algorithm calculates all possible subset sums \$ S \$ of \$ P \$, and then finds the sum \$ s + b \$ which is closest to \$ W \$, where \$ s \$ and \$ b \$ are elements in \$ S \$ and \$ B \$, respectively. Using the meet-in-the-middle approach decreases the complexity quite a bit. (I'm aware this code is super long, and I'll try to shrink it a bit eventually).

871 bytes

Python 2, \$ O(2^{\frac{|W|}2} \cdot |B| \cdot |W| + |W|^2) \$, 203 bytes
Naive implementation, looks at all combinations of possible weights \$W\$ and barbells \$B\$.
lambda B,W,T:min([(w+w[::-1],b)for w in p(sorted(sum([W.count(x)/2*[x]for x in set(W)],[])))for b in B],key=lambda(a,b):((T-sum(a)-b)**2,len(a)))
p=lambda l:l and[l[:1]+x for x in p(l[1:])]+p(l[1:])or[l]

Try it online!
Ungolfed
def f(Barbells, Weights, Target):
  # For every pair of same weights keep one, order them ascending
  usable_weights = concat([Weights.count(x)/2 * [x] for x in set(Weights)])
  usable_weights = sorted(usable_weights)

  # list all possible combinations of symmetric weights and barbells
  possible_setups = [(w+w[::-1], b)for w in powerset(usable_weights)for b in Barbells]

  # Find the one with the weight being the closest to the target,
  # on a tie take the one with the lowest number of weights
  return min(possible_setups, key=lambda(a,b): ((Target - sum(a) - b)**2, len(a)))

concat = lambda ls:sum(ls, [])
powerset = lambda l:l and [l[:1]+x for x in powerset(l[1:])]+powerset(l[1:]) or [[]]

Try it online!

Looks like the last test case doesn't adhere to the plate arrangement ([3.5, 2.5, 15, 15, 2.5, 3.5], 45) should be ([2.5, 3.5, 15, 15, 3.5, 2.5], 45)

@JosueEspinosa I missed the part about the ascending order, thanks for reminding me. Should be fixed now

Haskell, \$O(Wlog(W)+B2^WW) \$, 159 bytes
Worst case time, where \$W\$ is the number of weights and \$B\$ is the number of barbells.
import Data.List
h(a:b:r)|a==b,p<-h r=[a:q++[b]|q<-p]++p|1>0=h$b:r
h _=[[]]
(b#w)g|p<-h$sort w=snd$snd$minimum[(abs$g-a-sum q,(length q,(a,q)))|a<-b,q<-p]

Try it online!
I was never good at calculating time complexity, so feel free to correct me if you think I'm wrong. Here's some annotated source code to show some of my thinking:
import Data.List
-- O(h 0) = 1
-- O(h W) = 2*O(h$W-2) = 2^W
h(a:b:r)|a==b,p<-h r=[a:q++[b]|q<-p]++p|1>0=h$b:r
h _=[[]]
-- O(B#W$_) = W*log(W)+B*O(h W)*W = W*log(W)+B*2^W*W
(b#w)g|p<-h$sort w=snd$snd$minimum[(abs$g-a-sum q,(length q,(a,q)))|a<-b,q<-p]

The \$Wlog(W)\$ is for sorting the weights and the \$W\$ factor on the second part is for the linear time calculation of length q and sum q.
My implementation is a fairly straightforward brute force approach. I don't even optimize for the ideal case because it's extra bytes and it wouldn't help the worst case time anyway. The idea is to sort the list of weights and pick up on adjacent weights of equal value. I remove them from the list and recur, returning the resulting list along with those results with that weight on either side. In this way I build up a list of all possible weight combinations. Then it's a simple matter of looping over each barbell and finding the setup with the minimum error.
I've also tried to ensure that Haskell doesn't calculate some values like h$sort w and h r multiple times. I believe the compiler can usually optimize cases where it notices redundancy like that but I thought it best to err on the side of caution.

source: Stack Exchange

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

sort: votes


text:
Is it a Self-divisor?
Task
Write a function or program that takes n as a parameter and prints the first n self-divisors.
Definition of Self-divisor
A positive integer is called a “self-divisor” if every decimal digit of the number is a divisor of the number, that is, the number is evenly divisible by each and every one of its digits.
Example
For example, the number 128 is a self-divisor because it is evenly divisible by 1, 2, and 8. However, 26 is not a self-divisor because it is not evenly divisible by the digit 6. Note that 0 is not considered to be a divisor of any number, so any number containing a 0 digit is NOT a self-divisor. There are infinitely many self-divisors.
Scoring
This is code-golf, so the shortest answer in bytes wins

This seems really familiar, I'm pretty sure I've golf this challenge here before, or at least one that determines if a number is a self-divisor, but I'm not finding it now.

Are we allowed to take the index - 1, as per [tag:sequence] defaults? (Or simply output the whole sequence)

@xnor I believe that is this question. Duplicate?

@dingledooper Thanks, too bad SE search doesn't show that on the first page of "divide digit".

I think this is a duplicate because the additional part of "output the first n" isn't enough to make it different. People should feel free to reopen if they feel otherwise. I guess there's an argument that the other question is too old and has weird rules?

05AB1E, 16 bytes
05AB1E probably has some sort of slice, but I failed to find it.
∞ʒDSÖß}ʒ0å_}ηs<è

Try it online!
Explanation
∞                [1, 2, 3, ...]
 ʒ               Filter all that satisfies:
  DS                 its DigitS
    Ö                is divisible
     ß}              ßy the original number.
       ʒ         Filter out ^ that satisfies:
        0å_}         0 is å digit of the output.
            ηs<è Trunctuatè by the input.

I think this is missing 1 in the output

@mathjunkie Probably fixed.

8 bytes in the legacy version of 05AB1E: µNDSÖPD– (The second and fourth bullet-points of this 05AB1E tip are relevant.) PS: £ is what you were probably looking for?

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


text:
Multiple, Lit Plume, Mute Pill and so on
We say two positive integers are anagrams of each other if the digits in one of them (in decimal representation) can be rearranged to form the other. Leading zeros don't count. For example, 110020222 is an anagram of 212102020, but not of 221100011; neither is 22002211 even though it can be written as 022002211.
Interestingly enough, every arithmetic sequence of positive integers contains arbitrarily large sets of elements, all anagrams of each other. In this challenge, we use a special case of this fact.
Task
For this challenge, you have to write a program or function in a language of your choice, that takes as input two positive integers: k and N, and outputs N different positive integers, all of which are multiples of k and anagrams of each other.
Rules

You can assume N is bigger than 1.
Input and output can be taken in any of the standard ways.
Standard loopholes are forbidden.
Output may contain spaces and newlines.

Winning Criterion
This is code-golf, so shortest code in bytes wins.
Examples
Note that there are more than one possible output (infinitely many, in fact) given any k and N. Here are some examples:

  k  |   N   |  Possible output
-----+-------+------------------
  9  |   4   |  234
     |       |  243
     |       |  342
     |       |  432
-----+-------+------------------
 351 |   6   | 142857
     |       | 428571
     |       | 285714
     |       | 857142
     |       | 571428
     |       | 714285

Python 2, 48 bytes
lambda k,N:[k*(10**N**k+10**i)for i in range(N)]

Try it online!
For example, k=12,n=4 produces this list of numbers, written out in lines for clarity, with the ...'s hiding a big string of zeroes:
1200...0000012
1200...0000120
1200...0001200
1200...0012000

So, we have a prefix of k, followed by another k in a position that moves one place left each time, and the rest zeroes. We need the prefix because leading zeroes aren't allowed for the anagrams, so we make it so that all the outputs have the same number of digits.
We leave enough zeroes to ensure that the right string to never bump into the left one. N**k zeroes more than suffices for this, giving extremely big numbers; N+k or even N+log_10(k) would be enough. Note that Python right-associates 10**N**k as 10**(N**k).
Unfortunately this variable bound doesn't lend well to recursive solutions that update k as they go. An upper bound on how big k can be, even if enormous, would simplify this.

This is such an unexpected approach, I love it :)

Maybe the challenge should've specified the smallest group of values that qualifies, but this would be significantly harder to find...

J, 18 bytes
10#.[,.[}.[*=@i.@+

Try it online!
xnor's wonderful technique, adapted for J.  Be sure to upvote him.
explanation
Taking n=4, k=12 as an example, we notice that...
12 0 0 0 0 0 0 0 0 0 0 0 0 12  0  0  0
12 0 0 0 0 0 0 0 0 0 0 0 0  0 12  0  0
12 0 0 0 0 0 0 0 0 0 0 0 0  0  0 12  0
12 0 0 0 0 0 0 0 0 0 0 0 0  0  0  0 12

is actually just 12 zipped with a (12 + 4) x (12 + 4) identity matrix, multiplied by 12, with the first 12 rows chopped off.
Then we convert back to numbers with 10#.

05AB1E, 8 bytes
m°IL<°+*

Port of @xnor's Python 2 answer, so make sure to upvote him!!
Try it online.
A more original (although extremely slow) approach, is this 11-byter:
∞*æIù.Δ€{íË

Try it online. (Will time out if \$N\geq3\$..)
Both take \$k\$ as first input and \$N\$ as second.
Explanation:
m           # Take the 2nd (implicit) input to the power of the 1st (implicit) input: N^k
 °          # Take 10 to the power that: 10^(N^k)
  IL        # Push a list in the range [1, N]
    <       # Decrease it by 1 to make the range [0, N)
     °      # Push 10 to the power for each value: [10^0, 10^1, ..., 10^{N-1}, 10^N]
      +     # Add the earlier 10^(N^k) to each
       *    # And multiply it by the second (implicit) input N
            # (after which the list is output implicitly)

∞           # Push an infinite list of positive integer: [1,2,3,...]
 *          # Multiply each by the first (implicit) input k: [k,2k,3k,...]
  æ         # Take the (lazy) powerset of that infinite list
   Iù       # And only leave the inner lists of a size equal to the second input N
     .Δ     # Find the first inner list which is truthy for:
       €{   #  Sort the digits of each integer in the list
         í  #  in descending order (since we aren't allowed to start with a leading 0)
          Ë #  And check if all are equal
            # (after which the list is output implicitly)

Python 2, 101 bytes
k,n=input()
l=[];m=0;s=sorted
while 1:m+=k;l+=m,;t=[x for x in l if s(`x`)==s(`m`)];n==len(t)>exit(t)

Try it online!
Generate all multiples m of k, each time checking if there are n anagrams of m in the list of current multiples.
The result is printed as exit message.

Retina 0.8.2, 37 bytes
^.+
$*0
0(?=.*¶(.+))
$1$`$1$%'¶
¶¶.+

Try it online! Takes input in the order N, k. Uses @xnor's algorithm. Explanation:
^.+
$*0

Convert N to N zeros.
0(?=.*¶(.+))

Match each zero in turn.
$1$`$1$%'¶

Output k, the zeros to the left of this zero, k again, then the zeros to the right of this zero.
¶¶.+

Delete k.
Using Retina 1 would save 5 bytes, mostly from the use of L$ which effectively automatically delets k:
^.+
*0
L$`0(?=.*¶(.+))
$1$`$1$%'

Try it online!

C (gcc), 61 65 bytes
Added 4 bytes to fix a bug kindly pointed out by Kevin Cruijssen.
Uses xnor's idea  in his Python answer.
i;f(k,n){for(i=0;i<n;)printf("%d%0*d%0*d ",k,n+k+i,k,n+k-i++,0);}

Try it online!

Glad I could help. Now everything looks fine, so +1 from me. ;) I will delete my comments now.

cQuents, 12 bytes
&A(t^n^A+t^$

Try it online!
Port of xnor's Python answer. Go upvote his answer!
Explanation
              takes two inputs, A n
&             output first n terms in sequence
              each term equals:
 A(           A * (                            )
   t^n^A            10 ** n ** A
        +                        +
         t^$                       10 ** index

APL (Dyalog Classic), 21 bytes
Port of Kevin Cruijssen's 05AB1E answer. Don't forget to upvote him!
{⍺×(10*⍵*⍺)+10*¯1+⍳⍵}

Try it online!


text:
Help, I've mixed my week up!
My dog ate my calendar, and now my days are all mixed up. I tried putting it back together, but I keep mixing up the days of the week! I need some help putting my calendar back together, with the days in the correct order.
And since I need my calendar put together as fast as possible, don't waste my time by sending me superfluous bytes. The fewer bytes I have to read, the better!
Input
The days of the week, in any order. Input can be taken as a list of strings, or a space separated string, or any reasonable way of representing 7 strings (one for each day of the week).
The strings themselves are all capitalized, as weekdays should be, so the exact strings are:
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

Output
The days of the week, in sorted order (Monday - Sunday, because of course we adhere to ISO 8601). Output can be as a list of strings, or printed with some delimiter.
Disclaimer
Note that this is a kolmogorov-complexity challenge, with the added benefit of being able to use the input to shorten your code. You are not required to use the input if you don't want to. You are also free to use any approach, from a builtin datetime library to hard-coding the output.
Examples
To see example input and output, you can consult this python script.

I hope you've learnt your lesson from this: never leave dogs with calendars.

any delimiter allowed?

@Helena I'd say any delimiter within reason. I'd prefer space, comma, or newline, but if the language you're using has another default separator, or you'll be able to knock off a few bytes, go for it. Though I will specify that it has to be the same separator between all output words.

I hope you have learnt your lesson from this: it is a dog-eat-calendar world.

in any order = in random order? because thats what many of the answers seem to be assuming

@ASCII-only The program should work for any of the $7!$ different ways to order the days of the week. I used a random shuffle in my example code just to show that the output order is independent of the input order.

Pyth, 7 bytes
o%CN258

Try it online!
Convert each string to a number via treating its ASCII codes as a base 256 number, then take that mod 258, and sort. This gives the mapping
['Monday', 49]
['Tuesday', 75]
['Wednesday', 89]
['Thursday', 99]
['Friday', 103]
['Saturday', 125]
['Sunday', 211]

Same length but less fun is
.P1314S

The 1314th permutation of the sorted input in lexicographic order.

How did you find that?

@Adam I just searched the first 1000 moduluses and got very lucky. On average, it should take over 5040 (7!) moduluses to find one that gives a specific ordering, but this one appears quite early.

If you ask people "how did you find that", they probably just brute-forced.

I wanted to wait a bit before posting my own solution, but you had the exact same idea that I had (and you did it with 7 bytes instead of 8). Good solution!

JavaScript (Node.js),  37 36  35 bytes
This should also work in Chrome and Edge (Chromium)
Returns a list of strings.
a=>a.sort().sort(_=>-(a=a*595|5)%7)

Try it online!
How?
We first sort the input array in lexicographical order. Whatever the input is, we get:
Friday, Monday, Saturday, Sunday, Thursday, Tuesday, Wednesday

We then invoke sort() a second time with a callback function that, while ignoring its input, generates a sequence of positive and negative values in such a way that the underlying sorting algorithm (insertion sort) is tricked into putting the array in the desired order.
Below is a summary of all steps. Note that because of the bitwise OR, the value stored in \$a\$ is always coerced to a signed 32-bit integer (and so are the 3rd and 4th columns in this table).
  A  |  B  | previous a  | -(a*595|5)  | mod 7 | new order
-----+-----+-------------+-------------+-------+-----------------------------------
 Fri | Mon |  NaN        | -5          |  -5   | Mon Fri Sat Sun Thu Tue Wed
 Mon | Sat |  5          | -2975       |   0   | unchanged
 Fri | Sat |  2975       | -1770125    |   0   | unchanged
 Fri | Sun |  1770125    | -1053224375 |   0   | unchanged
 Sat | Sun |  1053224375 |  396722091  |   3   | unchanged
 Sat | Thu | -396722091  | -173557135  |  -3   | Mon Fri Thu Sat Sun Tue Wed
 Fri | Thu |  173557135  | -187280221  |  -2   | Mon Thu Fri Sat Sun Tue Wed
 Mon | Thu |  187280221  |  237418201  |   6   | unchanged
 Fri | Tue | -237418201  | -470091173  |  -6   | Mon Thu Tue Fri Sat Sun Wed
 Thu | Tue |  470091173  | -531373695  |  -6   | Mon Tue Thu Fri Sat Sun Wed
 Mon | Tue |  531373695  |  1660231379 |   2   | unchanged
 Fri | Wed | -1660231379 | -4807575    |  -3   | Mon Tue Thu Wed Fri Sat Sun
 Tue | Wed |  4807575    |  1434460171 |   4   | unchanged
 Thu | Wed | -1434460171 | -1194690159 |  -5   | Mon Tue Wed Thu Fri Sat Sun

This relies on Node's specific sorting algorithm, so it's not generic ES6.

Woot. I think that means I'm winning the generic JavaScript category (39 characters). That never happens. :) Still, never thought of using only one argument in the sort callback, that's...nuts.

Wait, you're not using either argument. So whacky.

FWIW, in FireFox for me it gives the wrong answer: [ "Saturday", "Sunday", "Friday", "Monday", "Tuesday", "Thursday", "Wednesday" ]

@SteveBennett Ah, you're right. I've added a note to clarify.

@Arnauld Not sure what you mean by all major JS engines, as I get Wednesday, Monday, Thursday, Tuesday, Friday, Saturday, Sunday in Safari.

@Neil Hopefully I got it right, this time. :p

Yeah, that's much better, thanks.

Ooh, I have equalled 37 characters with a much more straightforward and also cross-platform solution. :)

Two more characters, nice one!

@SteveBennett I got a bit lucky with this last pattern, as -(a=a*595|5)%7 is the only expression of this form that produces the correct sequence.

Pyke, 2 bytes
Pyke has some weird constant built-ins (a link to the Stack Exchange API, the lengths of months as numbers, the names of the days of the week and so on).
~C

Doesn't take input.
Try it online!

I don't think anyone is going to beat this

I won't be surprised if there is some language I forgot about with a 1-byter for this.

APL (Dyalog Unicode) 18.0 beta, 19 bytes

Full program, taking no input.
'Dddd'(1200⌶)⍳7

Returns a list of strings:
┌──────┬───────┬─────────┬────────┬──────┬────────┬──────┐
│Monday│Tuesday│Wednesday│Thursday│Friday│Saturday│Sunday│
└──────┴───────┴─────────┴────────┴──────┴────────┴──────┘

⍳7 Integers 1…7, representing the dates Jan 1–7, 1900
(1200⌶) Format Date-time ("12:00") as follows:
 'Dddd' long Day name

I get a domain error when trying the code online: line(1,0) : error AC0008: error (DOMAIN ERROR) executing line "'Dddd'(1200⌶)⍳7"

@maxb I forgot to remove the TIO link as TIO is on 17.1. Works locally by me. I'll add a link to the docs instead.

"The Nineteenth Byte"

JavaScript, 37 characters
e=>[...'1564023'].map(a=>e.sort()[a])

JavaScript, 38 characters
e=>[1,5,6,4,0,2,3].map(a=>e.sort()[a])

Javascript, 39 characters
e=>e.map((a,i)=>e.sort()['1564023'[i]])

Javascript, 45 characters
e=>e.map((a,i)=>e.sort()[[1,5,6,4,0,2,3][i]])

Javascript, 51 characters
e=>(v=e.sort(),v.map((a,i)=>v[[1,5,6,4,0,2,3][i]]))

Javascript, 52 characters
e=>(v=e.sort(),[v[1],v[5],v[6],v[4],v[0],v[2],v[3]])

Javascript, 61 characters
I tried a couple of things, but they were fractionally longer than:
z=>'Monday Tuesday Wednesday Thursday Friday Saturday Sunday'

The 54 is 52 because the z= shouldn't have been included in the count.

I wonder if it would be possible to do e=>e.map((_,n)=>e.sort()[some_magic_with(n)]) instead, but that seems unlikely. ¯\(ツ)/¯

Yeah, I pondered something along those lines. There's about 8 characters to play with (assuming the magic is going to contain n and we want 36 characters or fewer total).

Python 3, 40 38 bytes
-2 bytes thanks to xnor
from calendar import*;print(*day_name)

Try it online!

Python 2, 44 43 bytes
lambda d:sorted(d,key=lambda x:~hash(x)%72)

Try it online!

The perfect built-in! I think from calendar import*;print(*day_name) would be allowed.

By the way, I've been looking for a solution similar to your sorting one, but with an object method for the key so as to avoid writing a lambda. I had hopes for "...".strip or "...".translate, but it seems none of those can work. Perhaps you have a better idea with this.

Thanks for the improvement, I clearly missed that! As for my 2nd answer, I will definitely try to shave off bytes if I can. As you said, the lambda takes up quite a few bytes.

Java (JDK), 27 bytes
java.time.DayOfWeek::values

Try it online!
Doing this because the challenge input is very structured, but the output is not structured at all.
No built-ins, 49 bytes
l->l.sort((a,b)->~a[0]*a[4]%-473-~b[0]*b[4]%-473)

Try it online!

APL (Dyalog Unicode), 21 bytes
Anonymous prefix lambda. Port of isaacg's Pyth solution — go upvote that!
{⍵[⍋258|256⊥¨⎕UCS¨⍵]}

Try it online!
{…} "dfn"; argument is ⍵:
 ⍵[…] reorder the argument into the following order:
  ⎕UCS¨⍵ Universal Character Set code points of each string
  256⊥¨ evaluate each in base-256
  258| the division remainder when divided by 258
  ⍋ grade (permutation that would sort it)

You posted 3 different answers for APL...

@petStorm Sure, why not? The are completely different in their approaches.

C (gcc) -m32, 50 bytes
main(i){for(;puts(nl_langinfo(131079+i%7))-i++;);}

Try it online!
Explanation
Simply put, nl_langinfo() is a useful function which returns a particular string given an argument. It just turns out that the argument to pass for obtaining weekday names is 131079 ... 131086. One other thing is that we must add the flag -m32, which is explained nicely in this answer.

I was really confused by the -i++ part, does it work because Sunday happens to be 6 letters (and the 7th day of the week)? EDIT: In nl'_langinfo Sunday is the first day of the week, but your i%7 seems to handle that.

The i variable starts to 1, and is incremented after every iteration. That means we actually start at 131080 instead of 131079. This is on purpose, since as you said, Sunday is the first day of the week when using nl_langinfo. On the last iteration, when i equals 7, the number becomes 131079 because of the modulo, printing Sunday. The reason it terminates after outputting Sunday is because puts returns the length of the string (including newline), so Sunday returns 7. It also happens that i equals 7, so subtracting them exits the loop.

Wolfram Language (Mathematica), 27 bytes
DayName@{#}&/@198~Range~204

Try it online!

I'm confused. Care to explain?

@Adám DayName works like this: DayName[date] . So I found another way by using integers. Unfortunately the order didn't work for Friday....

How comes the integers are not representing dates in order?

I really don't know... range[7] returns {Monday, Tuesday, Wednesday, Thursday, Saturday, Sunday, Monday}. This is not supposed to work with integers. It's an abuse

Not really an abuse. The date format that DayName takes can be {year,month,day} (or even have hours/minutes/seconds); or it can be {year,month} in which case the day is assumed to be 1 if needed; or it can even be {year} in which case the month and day are assumed to be 1 if needed. So this code is calculating the day of the week for 1 January 198, 1 January 199, ... through 1 January 204. I believe it's doing so assuming (wrongly) that our current Gregorian calendar extends back indefinitely. ...

... Anyway, it's a convenient coincidence that in non-leap-years, the day of the week of January 1 (or any given date) is one day later then in the previous year. (This is because 365 is 1 more than a multiple of 7.) Unfortunately it's hard to find a stretch of seven consecutive non-leap-years—but it is possible, because 100, 200, 300, 500, 600, 700, 900, ... are not leap years. If we were lucky, we could have saved a byte by finding a range of years around 100 that started with a Monday, but a quick check reveals that the year 96 just gets in the way.

05AB1E, 6 bytes
Port of isaacg's base conversion answer.
Σ₁ö29%

Try it online!
Explanation
Σ      Filter the input by this function:
 ₁ö    Base-convert it from 256
   ₁   Constant 256
    Ì  Add 2 (= 258)
     % Modulo by this number

05AB1E, 6 bytes
-1 byte thanks to Expired Data
{œŽ5dè

Try it online!
05AB1E, 21 bytes
Σ"TuWeThFrSaSu"2ôåāsÏ

Try it online!
Explanation
Σ                     Sort by the output of this function.
 "TuWeThFrSaSu"2ô     Split every item of that by length of 2.
                 å    Contains?
                  āsÏ Find all truthy indices of that.

You can get 6 with the other approach too

{œŽ5dè was exactly the same solution I've found o-o

Using ö instead of β also gives 6 bytes, and doesn't require a footer to pretty-print.

You can remove the footer in that second approach of @ExpiredData by replacing the ' in the input-list with ": try it online. Also, there is an $n^{th}$ permutations builtin .I, which is faster than generating all permutations first before indexing: {Ž5d.I (although it's irrelevant for the byte-count).

APL (Dyalog Unicode), 35 bytes
Anonymous prefix lambda. This one actually sorts its argument and doesn't use any "cheating" built-ins.
{⍵[⍋((∊∘⎕A⊂⊢)'MoTuWeThFrSa')⍳2↑¨⍵]}

Try it online!
{…} "dfn"; argument is ⍵:
 ⍵[…] reorder the argument into the following order:
  2↑¨ take the first two letters from each input day name
  (…)⍳ find the index in the following list (missing items become 1 beyond last index)
   (…)'MoTuWeThFrSa' apply the following tacit function to this string:
    ⊢ the argument
    ⊂ split on
    ∊∘⎕A membership of the uppercase Alphabet
  ⍋ grade (permutation that would sort it)

R, 30 bytes
Assuming an English locale
weekdays(as.Date("1/1/1")+0:6)

Try it online!
January 1st of the year 1 is a Monday (according to R).

Technically, this only works if your computer is set to a locale such as en_GB where the day names are the same as the question's. I think you are allowed to assume any reasonable locale you like for these sorts of challenges so it's not an invalid answer, but you should perhaps say at the top that you are assuming an English locale.

@JDL Thanks, never thought about that

T-SQL, 49 bytes
SELECT DATENAME(w,RANK()OVER(ORDER BY d)-1)FROM t

Input is taken as a pre-existing table t with varchar column d, per our IO standards.
My code doesn't actually use the values in the input table in any way, so the input order doesn't matter (nor do the actual strings, they just have to be distinct). Instead, it uses the fact that it has 7 rows, along with the RANK() function, to generate the numbers 1 through 7.
After subtracting 1, these numbers are implicitly cast as dates (0=Mon Jan 1, 0001, 6=Sun Jan 7, 0001), and the DATENAME function returns the corresponding day of the week.

Python 2, 45 43 bytes
-2 bytes thanks to @xnor!

lambda l:map(sorted(l).pop,[1,4,4,3,0,0,0])

Try it online!
Sort by normal string comparison first, then look up the correct permutation.

Python 3, 58 bytes
lambda l:sorted(l,key=lambda s:"TuWeThFrSaSu".find(s[:2]))

Try it online!
Use the first 2 letters of each day to look up the order.

Nice that you skip Mo, which results in -1 for Monday.

Nice idea with the sorting! Here's a small byte save, though it needs Python 2 since Python 3 produces a map object unless you unpack.

@xnor Thank you! I was looking at __getitem__, but totally forgot about pop.

Factor, 20 bytes
day-names 1 rotate .

Try it online!
Factor has a built-in sequence for the days of the week, but is starts with Sunday - that's why I need to rotate the items to the right.

Kotlin , 58 bytes
DayOfWeek.values().map{it.name.toLowerCase().capitalize()}

C (gcc), 72 70 bytes
Saved 2 bytes thanks to gastropner!!!
f(){puts("Monday Tuesday Wednesday Thursday Friday Saturday Sunday");}

Try it online!
Just prints the days of the week.
Unfortunately this is shorter than sorting the input! T_T
C (gcc) Little Endian Byte Order, 123 \$\cdots\$ 99 85 bytes
h,s;c(int**a,int**b){h=(h=**a%274%79)>(s=**b%274%79)-(h<s);}f(int*s){qsort(s,7,8,c);}

Try it online!
Function f takes a list of strings as input and sorts it.
How
Reads the first four characters as a 32-bit int, \$i\$, and then calculates \$((i\mod{274})\mod{79})\$:
Monday -> 5
Tuesday -> 7
Wednesday -> 11
Thursday -> 23
Friday -> 47
Saturday -> 59
Sunday -> 61

Then uses qsort to sort the array.

You could save 2 bytes by using puts() instead of printf().

@gastropner Nice one - thanks! :-)

Perl 5, 33 29 bytes
print+(sort<>)[1,5,6,4,0,2,3]

Try it online! Just another sort/permute answer. Edit: Saved 4 bytes thanks to @Xcali.

Shaved 4 bytes: Try it online!

@Xcali Thanks! I don't really know Perl, I was just putting in parentheses until it stopped erroring...

I just found another issue there.  Thursday and Friday are reversed in your output.

@Xcali Thanks for spotting my typo... (I got the sequence of digits correct in my other answer at least.)

PHP, 39 bytes
for(;$i<7;)echo" ".jddayofweek($i++,1);

Try it online!
Works in Windows but not in TIO, gotta find how to activate the extension.. takes no input.
We could save 4 bytes with an empty delimiter (which is "some delimiter" the question doesn't say a non-empty delimiter) but I'm not that nasty..
EDIT: version that works universally for 1 byte more
PHP, 40 bytes
for(;$i<7;)echo date("l ",1e6+$i++*8e4);

Try it online!

Powershell, 23 bytes
1..6+0|%{[DayOfWeek]$_}

Convert integers to weekday, but bump array by one because .net prefers Sundays.
37 bytes sorting
($args|%{[DayOfWeek]$_}|sort)[1..6+0]

input is string list to args.

21 bytes

MathGolf, 8 bytes
á{$ûÞ♠$%

Try it online!
Explanation
á{         sort by the output given from a code block
  $        convert to ordinal (base 256)
   ûÞ♠     push "Þ♠"
      $    convert to ordinal (gives 1791)
       %   modulo

I had the exact same idea as isaacg's Pyth answer, but in MathGolf I had to use another modulo. I tried every number up to 1000000, and noticed that the ordinal strings for each weekday ended up in the correct order for sorting when taking them modulo 1791.

Tried to find a shorter way to generate 1791, but can't find one unfortunately. I did found an equal-bytes alternative, though: ○♠~+ (2048+~256).

@KevinCruijssen I thought about modifying the input string (e.g. "Monday") or its ordinal, in order to change the 1791 into another nicer number (hopefully a 1-byte builtin), but I didn't investigate further there. Best case scenario is that it saves 2 bytes, which would be tied with 05AB1E.

You mean like removing the first character of the string before the $ or something along those lines?

@KevinCruijssen Yes, something along those lines. It could also be squaring the number after the $, or something similar. But there were so many operators to try that I gave up before I started.

Retina, 40 bytes
^
MTuWThFSaSu
,6L$s`(.+)(?=.*(\1\w+))
$2

Try it online! Link shuffles input in header. Explanation:
^
MTuWThFSaSu

Insert unique day name abbreviations.
,6L$s`(.+)(?=.*(\1\w+))
$2

Find the first seven duplicate substrings, and output the word containing the duplicate, thus unabbreviating the names.

Charcoal, 29 25 bytes
≔Ｅ⁷ＳθＷ⁻θυ⊞υ⌊ιＥ1564023§υＩι

Try it online! Link is to verbose version of code. Explanation:
≔Ｅ⁷Ｓθ

Input the seven days.
Ｗ⁻θυ⊞υ⌊ι

Sort the days lexicographically.
Ｅ1564023§υＩι

Apply the permutation to the array.

MATL, 4 bytes
23Y2

Built-in ¯\_(ツ)_/¯. Takes no input.
Try it online!

Retina 0.8.2, 32 29 27 26 bytes
Tu
13
T`MWT`E
O`
T`d`MTWuT

Try it online!
Approach: Replace the first letter of the days with A, B, C, etc. so we can sort them lexicographically. Replace the M in Monday with a 0, the T in Tuesday with a 1, the W in Wednesday with a 2, and the T in Thursday with 4. To help golf off a byte, also replace the u in Tuesday with 3
Tu
13
T`MWT`E

Perform the replacements described above (The E inserts even numbers 02468)
O`

Sort lexicographically. At this point, our list of words looks like this:
0onday
13esday
2ednesday
4hursday
Friday
Saturday
Sunday

Notice that Friday, Saturday, and Sunday are already conveniently in alphabetical order.
T`d`MTWuT

Undo the transformations we performed above (The d inserts the range 0-9)

Japt, 8 bytes
n á g#4

Try it here

Python 3, 64 62 59 chars
Takes input as a list of strings, sorts it inplace:
lambda l:l.sort(key=lambda x:'uehrau'.find(x[1],x[0]=='S'))

Try it:   https://ideone.com/rYxtff

R (English locale), 36 bytes
weekdays(.leap.seconds[c(8:12,6:7)])

Not quite as short as the other answer, but I posted it because it makes use of one of the strangest objects kicking around in base R — a list of all the leap seconds. It so happens that leap seconds frequently occur in increasing sequences of days so we only have to take two "chunks" from the list.
Luckily, the leap seconds object has the oldest leap second first, so I don't have to qualify this program with "will only work for the next 2–3 years"!
TIO link here.

This is certainly one of the most interesting approaches. I've never coded in R, but you could add a TIO link, something like this.

Thanks — I used your link to edit my answer — hope that's alright!

Well I used your code in my link, so I guess we're even.

Keg, 15 bytes
“jnsDt[rƳm⑺dQ7⅍

Try it online!
You'd think this was some sort of fancy sorting algorithm, but no. It's simply a compressed string.

Meh, I've got 22 in Jelly: “¡²2GỌḌ¹Ẹṙṙ,ßṃþ-wẈÇUx»

Bash + Unix utilities, 29 bytes
jot "-wdate +%%A -d7-1-" 7|sh

Try it online!

Nice solution, but it isn't ISO 8601 compliant unfortunately. The week should start with Monday for this challenge.

Fixed.  Thanks for pointing it out.

Red, 24 bytes
print system/locale/days

Try it online!

J, 10 bytes
1314 A./:~

Try it online!
J Port of isaacg's alternative Pyth solution — please upvote him!

Python
Input: Space separated strings
Once the input is sorted then the output should be ordered using indices [1, 5, 6, 4, 0, 2, 3] of the sorted array
inp=sorted(input().split())
for i in [1, 5, 6, 4, 0, 2, 3]:
  print(inp[i])

Try it here

What language is this?

Welcome to Code Golf! While it is a good answer, I'll suggest some general code golf optimizations: make all variables 1 byte, and remove all unnecessary whitespace. With those optimizations, your code becomes 14 bytes shorter.

Deadfish~, 464 bytes
{{i}dd}dddc{i}{i}{i}iiiicdc{d}cdddc{i}{i}iiiic{{d}}{d}dc{{i}ddd}iiiic{i}{i}{i}iiic{d}ddddddc{i}iiiic{d}dddddcdddc{i}{i}iiiic{{d}}{d}dc{{i}dd}dddc{i}iiiicdc{i}c{d}ic{i}iiiic{d}dddddcdddc{i}{i}iiiic{{d}}{d}dc{{i}ddd}iiiic{i}{i}c{i}iiicdddcic{d}dddddcdddc{i}{i}iiiic{{d}}{d}dc{{i}dddd}c{{i}dddddd}iiiic{d}icdddddcdddc{i}{i}iiiic{{d}}{d}dc{{i}ddd}iiic{i}iiiic{i}{i}dcicdddc{d}ddddcdddc{i}{i}iiiic{{d}}{d}dc{{i}ddd}iiic{i}{i}{i}iiiic{d}iiic{d}cdddc{i}{i}iiiic{{d}}{d}dc

Try it online!
Deadfish - the worst compression algorithm.


text:
Determine the cyclical shift your program is in
Write a program that outputs the number 0.
That's a bit trivial, isn't it?
Let the length of your program be \$S\$. Write a program that outputs the number 0. When your program is cyclically shifted \$i < S\$ bytes left, it should output \$i\$. To cyclically shift a string \$i\$ bytes left means to move the last \$i\$ bytes (including newlines) to the front, without changing the order.
For example, if your code is ABCD, then ABCD should output 0; DABC should output 1; CDAB should output 2; BCDA should output 3.
Rules

Your program must be at least 3 bytes long.
"Output" represents any acceptable output: on the stack, to STDOUT, as a return value, as an exit code, etc.
Your program is to not take any form of input.
This is code-golf, so shortest code wins.

I would say this is more interesting as an attempt to make the longest program that satisfies this restriction. Otherwise, a submission of length 3 is automatically the winner.

@RGS Won't a brainfuck ".++++++++++++++++++++++++++++++++++++++ ` work?

@BaaingCow also true :) except that in most bf implementations you are capped at 255 because the memory is mod 256

i'm disappointed :(

Can you right shift instead of left shift?

@petStorm I'll allow it here

@BaaingCow please update the challenge to allow the right-shift, comments can become cluttered and are a non-optimal way of providing specifications.

No reasonable language would allow this :D at least maybe you could exclude the keyword used for output from the shift? Or else only implicit output languages can compete

brainfuck, 3 bytes
.++

Try it online!
how it works: it's really simple, actually. The internal memory is initialized at 0 so we output (with .) the original cell and we get 0. By shifting the program, we are shifting memory increments (done with +) to before the output, so each byte shifted corresponds to one more increment, and hence we increase the counter.

FGITW, you win.

@petStorm *LGITW to be honest; (luckiest instead of fastest) I haven't been around much and I was lucky enough to scroll past this challenge while it had no answers :)

Jelly, 3 bytes
‘n¬

The implicit input of a Jelly program is 0:
Try ‘n¬ online! 0 incremented \$\neq\$ not(0)    \$\implies0+1 \neq 1 \implies 1\neq 1 \implies 0\$
Try ¬‘n online! not(0) incremented \$\neq\$ 0 \$\implies1+1\neq 0 \implies 2\neq 0 \implies 1\$
Try n¬‘ online! (0 \$\neq\$ not(0)) incremented \$\implies(0\neq 1)+1 \implies 1+1 \implies 2\$

Keg -hd, 3 bytes
210

Try it online!
How?
Keg only outputs the top item of the stack. These individual digits push themselves onto the stack. So for every cyclic shift, it outputs the character code of the top of the stack.
Program ->   Stack   -> Output last item
  210   -> [2, 1, 0] ->       [0]
  021   -> [0, 2, 1] ->       [1]
  102   -> [1, 0, 2] ->       [2]

05AB1E, 3 bytes
Right-shifts instead of left-shifts.
>>g

Try it online!
Explanation
>>g : >>  Increment empty string twice
        g Find the length of the empty string (0)

>g> : >   Increment empty string
       g  Find the length (0)
        > Increment that (1)

g>> : g   Find length of empty string (0)
       >> Increment twice (2)


text:
Determine the lexicographical permutation your code is in
Write a program that outputs the number 0.
That's a bit trivial, isn't it?
Let's sort all distinct permutations of your code in lexicographical order. When any of these codes are run, it should output the its location in the array (0-indexed or 1-indexed).
This means that your code must be the lexicographically smallest permutation of your code possible.
For example, if your code is ABB, then ABB -> 0; BAB -> 1; BBA -> 2.
Rules

Out of all distinct permutations of your code, it must be the lexicographically smallest.
Your program must be at least 3 bytes long.
"Output" represents any acceptable output: on the stack, to STDOUT, as a return value, as an exit code, etc.
Your program is to not take any form of input.
This is code-bowling, so longest code wins.

The third is a fun challenge!

This seems really, really hard :)

@BaaingCow can we do it the other way around like BBA -> 0,  BAB -> 1, ABB -> 2, just like your specification of the previous challenge?

Wait a minute, does a Lenguage program that computes pi and then multiplies it by 0 work? (note: I plan to post an answer if that is okay)

If two permutations have the same value, can we treat it as the same permutation?

@petStorm I can't really see how would you distinguish between equal permutations :)

I think the score should be the number of distinct permutations, not the length.

It would be a good idea if you sandboxed your challenges instead of posting them right away... It would help you trim down the rough ends and help you create really neat challenges.

Love this! Am wondering for this and your previous 2 similar challenges, is one allowed to assume constant input? That is, have the input always set to some constant value, and have the rest of the code work partially by relying on it?

@AviF.S. I'm almost certain that is a standard loophole.

This really should have also had an irreducibility requirement added. That way, infinite answers would be so trivial.

I’m voting to close this question because it's too easy to get an infinitely large score, leaving the challenge effectively without an objective winning criterion.

I have to agree with @pppery. As it seems as though a majority of languages can get a "score = bytes" score, this essentially lacks a winning criteria

brainfuck, bytes = score
...

Try it online!
How it works: this program only has one distinct permutation and it outputs 0. It trivially satisfies all the other restrictions. The score can be made arbitrarily large by adding more ..

Can be extended indefinitely to be made arbitrarily large! Highly recommend adding ∞ bytes. Also, perhaps clarifying that it outputs ascii(0), rather than a literal 0. Want to let you do as you see fit with it, but if you don't see this, I'll gladly make the edit for you! Unless, others chime in and think it a bad idea, but it seems to me fair game as it's still in the spirit of your answer!

Python 2, score = arbitrary
000

Try it online!
Returns through exit code, which is always 0.
The source code is 0 repeated arbitrary many times. Since there's only 1 permutation of the source code, the permutation number is always 0.

!@#$%^&*()_+, 548+++ bytes
#^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Try it online!
This can also be just#^^. # prints and ^ increments. Please tell me if this is not lexicographic order, instead of downvoting.

Since this is infinitely expandable, you could just say "infinite" bytes.

Good job for having multiple distinct characters!

this might work in other stacked languages using many increments and one output

dc, Arbitrarily large number of bytes.
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

Try it online!
No matter how many 0s you write, it will leave a 0 on the stack, which is an acceptable output form for the challenge.  (The p in the TIO footer prints the stack so you can see what it is.)
Of course, the only permutation is the program itself.

MathGolf, 3 bytes (3 distinct permutations)
Outputs via unary, with a different set of output: 2 -> 3 -> 4.
00\

Try it online!
Explanation
00\
00  Push 2 0's
  \ Swap (resuting in 2 0's)

0\0
0   Push 0
 \  Swap
  0 Push 0 (3 0's)

\00
\   Swap the empty stack (appends 2 0's)
 0  Push 0
  0 Push another 0 (resulting in 4 0's)

Uhh, I can't seem to find a permutation that outputs 6 zeroes.

@mypronounismonicareinstate What about now? It seems that equivalent permutations are considered the same this time.


text:
Escape the Candlelit Maze
You find yourself in a strange place. A frighteningly dark maze, lit only by dim candles resting in the occasional hallway. Numerous paths lie only in impassable darkness, foreboding and-- ...Hm? What? Pick up a candle and carry it with you? No, no, that would be extremely rude.
The Task
Given a maze as input, output the minimum moves to solve it, or any falsey/invalid output if the maze cannot be solved. The catch: The maze is very dark, but is lit by candles placed on some of the grid squares. The player may only move in a direction if they can see light in that direction.
Rules

Take the maze as input in any convenient format (string, 1d array, 2d array, etc).
x represents a wall, @ represents the player, ^ represents a candle and # represents the exit.
The maze will be surrounded on all sides by walls, except for the player's starting space and the exit space, each of which will be in one of the walls. The corners will always be walls.
The player may only make orthogonal moves one space at a time in the direction of visible light. This is either a candle or the exit.
Candlelight only reaches the space it's on, but is visible from any distance.
Output the minimum number of legal moves the player can make to reach the exit, or any "invalid" value (such as a negative value, zero, false, the string "Unsolvable!", etc) if the maze is unsolvable within the rules. The player must move into the exit space to solve the maze.
Standard loophole restrictions and i/o rules apply.

Test Cases
1-
Input:
xxxxxxxxxx
@^x    ^xx
x^  ^xxxxx
xxxx x^  #
x xx x xxx
x ^ ^ ^x x
x xxxx  ^x
xxxxxxxxxx

Output:
15

2-
Input:
xxxxxxxxxxxx
x^ ^xxxxxxxx
x x        #
x x^xxxx xxx
x xxxx   xxx
x^  ^xxx^xxx
xxxx@xxxxxxx

Output:
19

Once the player moves into a space that can see a new light source, such as the exit, they can then start moving towards that light source.
3-
Input:
xxxxxxxx
#  xx ^x
xx^  ^xx
x ^xx xx
xxxxx@xx

Output:
Unsolvable

4-
Input:
xxxxxxxxx
@      ^x
x xxxxx x
x x^   ^x
x x xxxxx
x x^   ^x
x xxxxx x
x^ ^   ^x
xxx#xxxxx

Output:
10

The player must take the shortest path.
5-
Input:
xxxxxxxxx
x   ^  ^x
xxxx xxxx
#  x    x
x^xx^xxxx
x^   x  x
xxxx x xx
x     ^ x
xxxx@xxxx

Output:
Unsolvable

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

BTW: this a nice and well-specified first challenge!

@Arnauld Thanks! I've been lurking here for several months now, so that probably helped. :p

Retina 0.8.2, 229 bytes
T`#^`d
s`@.*
$&_
@\d|@ ( *\d)
@=$1
(\d *) @|\d@
$1=@
m`^(((.))*@.*\n(?<-2>.)*(?(2)$))(\d| ((.*\n)+(?<-3>.)*(?(3)$)\d))
$1=$5
m`^(((.))*)(\d|(\d(.*\n)+(?<-2>.)*(?(2)$)) )(.*\n(?<-3>.)*(?(3)$)@)
$1$5=$7
@
x
}sT`=`@`.*0.*
s`.*0.*

_

Try it online! Outputs 0 for unsolvable, since solutions must take at least one step. Explanation:
T`#^`d

Change the candle and exit to golfier characters, saving 7 bytes
s`@.*
$&_

If there are still squares to check, then increment the counter. (This allows the loop to terminate once it runs out of squares to check.)
@\d|@ ( *\d)
@=$1

Mark the square to the right if it is lit.
(\d *) @|\d@
$1=@

Mark the square to the left if it is lit.
m`^(((.))*@.*\n(?<-2>.)*(?(2)$))(\d| ((.*\n)+(?<-3>.)*(?(3)$)\d))
$1=$5

Mark the square below if it is lit.
m`^(((.))*)(\d|(\d(.*\n)+(?<-2>.)*(?(2)$)) )(.*\n(?<-3>.)*(?(3)$)@)
$1$5=$7

Mark the square above if it is lit.
@
x

Turn the squares that were checked into walls.
sT`=`@`.*0.*

If the exit still exists, then turn all of the marked squares into squares that need to be checked.
}`

Repeat the above until the exit is reached or no new steps could be taken.
s`.*0.*

If the exit was not reached then delete the count.
_

Convert the count to decimal and delete the input.

JavaScript (ES6),  196 ... 179  177 bytes
Takes input as a matrix of characters. Returns \$0\$ if there's no solution.
m=>(o=F=(X,Y,n)=>m.map((r,y)=>r.map((c,x)=>n?(h=x-X)*h+(v=y-Y)*v-1?0:c=='#'?o=o<n?o:n:r[(g=w=>1/(C=m[z+=v][w])?g(w+h):C<g)(x,z=Y)&&F(x,y,n+1,r[x]=g),x]=c:c=='@'&&F(x,y,1))))()|o

Try it online!
How?
This is a depth-first search. We first look for the position of the player and then initiate the recursion. We keep track of the number of moves in \$n\$ and the length of the shortest path in \$o\$.
Given the previous position \$(X,Y)\$, we iterate on all cells \$(x,y)\$ of the maze and compute \$dx=x-X\$ and \$dy=y-Y\$. We can move to the new cell if:

\$dx^2+dy^2=1\$
and the first non-empty cell encountered along the ray \$(X+k\cdot dx,Y+k\cdot dy),k>0\$ is either a candle or the exit

Commented
m => (                           // m[] = input matrix
  o =                            // o = output, initially non-numeric
  F = (X, Y, n) =>               // F is the main recursive function:
    m.map((r, y) =>              //   for each row r[] at position y in m[]:
      r.map((c, x) =>            //     for each character c at position x in r[]:
        n ?                      //       if n is defined:
          (h = x - X) * h +      //         h = dx, v = dy
          (v = y - Y) * v - 1 ?  //         if the quadrance is not equal to 1:
            0                    //           abort
          :                      //         else:
            c == '#' ?           //           if we've reached the exit:
              o = o < n ? o : n  //             update o if n is better
            :                    //           else:
              r[                 //             wrapper to update r[]:
                ( g =            //               we use g to look for a candle
                  w =>           //               or the exit in this direction:
                  1 / (C =       //                 move along (dx, dy) and store
                    m[z += v][w] //                 the content of the cell in C
                  ) ?            //                 if C is a space:
                    g(w + h)     //                   keep moving until it's not
                  :              //                 else:
                    C < g        //                   success if C is not 'x'
                )(x, z = Y)      //               initial call to g at (X, Y)
                &&               //               if the move is valid:
                  F(             //                 do a recursive call:
                    x, y, n + 1, //                   at (x, y) with n + 1
                    r[x] = g     //                   invalidate the current cell
                  ),             //                 end of recursive call
                x                //               actual index in r[] ...
              ] = c              //             ... to restore the cell
        :                        //       else (n undefined):
          c == '@' && F(x, y, 1) //         initiate the recursion if c is '@'
    ))                           //   end of map() loops
)() | o                          // initial call to F; return o

PowerShell 6+ for Windows, 162 bytes
$f={param($m,$l)++$l
1..4|%{switch -r($m){'@#'{$l}'@ *[#^]'{&$f($m-replace'@.','x@')$l}}$m=&{($a=$m[-1..-$m.Count])[0]|% t*y|%{-join($a|% Ch*($i++))}}}|sort -t 1}

Try it online!
Unrolled:
$f = {
    param($maze,$len)   # len = $null if parm omited

    ++$len
    1..4|%{
        #recursive call
        switch -Regex ($maze){
            '@#'{$len}
            '@ *[#^]'{
                &$f ($maze -replace '@.','x@') $len   # leave a wall behind to avoid infinite loops
            }
        }
        #rotate -90
        $maze = &{  # new context to reinit $array and $i
            $array=$maze[-1..-$maze.Count]
            $array[0]|% toCharArray|%{
                -join($array|% Chars($i++))
            }
        }
    }|sort -Top 1          # Powershell 6+ for Windows
#   }|sort|select -First 1 # Powershell 5- for Windows
#   }|sort-object -Top 1   # Powershell for Linux
}

Perl 5, 238 bytes
sub f{%s=@_=(1,pop);while(@_){$i=shift;$m=shift;for(1..4){@a=$m=~/.+/g;!$s{$m=join$/,reverse map{$j=$_-1;join'',map/.{$j}(.)/?$1:0,@a}1..length$a[0]}++&&push@_,$i,$m};$_=$m;s/@( *[\^#])/'x@'.substr$1,1/e&&(/#/||return$i)&&push@_,$i+1,$_}}

Try it online!
Rotates the maze 90° four times at each position. Easier to regexp-search-replace the entire maze as one string for @ +[^#] with x@ + one less space when the next light or end is always ahead if at all. @^ and @# with no space are replaced by x@ so the # disappears which means the exit has been reached and we return $i steps taken. Array @_ contains mazes to try out next. Hash %s keeps track of which mazes we've already tried so those are skiped. Nothing left to try in @_ means no solution is to be found and 0 is returned.


text:
Evaluate Conway chained arrow notation
Background
Conway chained arrow notation is a notation to express very large numbers. It consists of zero or more positive integers separated by right arrows, e.g. \$2 \to 3 \to 4 \to 5 \to 6 \$.
Assuming \$p, q, a_1, \dots, a_n\$ are positive integers and \$X\$ is an abbreviation for a nonempty chain \$a_1 \to a_2 \to \dots \to a_n\$, the rules for evaluating such a notation are as follows:
$$
\begin{align}
(\text{empty chain}) &= 1 \\
(p) &= p \\
p \to q &= p^q \\
X \to 1 &= X \\
X \to 1 \to p &= X \\
X \to (p+1)\to (q+1) &= X \to (X \to p\to (q+1))\to q
\end{align}
$$
A length-3 chain has an equivalent up-arrow notation: \$ p \to q \to r = p \uparrow^r q\$.
Note that the arrow notation cannot be treated as some kind of binary operator:
$$
\begin{align}
2 \to 3 \to 2 &= 16 \\
2 \to (3 \to 2) &= 512 \\
(2 \to 3) \to 2 &= 64
\end{align}
$$
More examples can be found on the Wikipedia page linked above.
Task
Given a (possibly empty) list of positive integers, interpret it as Conway chained arrow notation and evaluate it into a single number.
It is OK if your program gives wrong answers for large values due to the limits (bounds and/or precision) of your language's number type, as long as the underlying algorithm is correct.
Standard code-golf rules apply. The shortest code in bytes wins.
Test cases
Input => Output
[] => 1
[1] => 1
[99999999] => 99999999
[5, 5] => 3125
[4, 8] => 65536
[1, 2, 4] => 1
[2, 2, 4] => 4
[2, 3, 2] => 16
[2, 4, 2] => 65536
[4, 3, 2] => 4^256 = 1.34e154
[2, 2, 3, 2] => 4

Can we take the input list in reversed order?

@Leo Yes, no problem, as long as you state so in your answer.

Interesting, but even after coding the algorithm, I feel I don't have any real insight into it.   Did you read the original source?  Does it have background on the intuition and motivation that led Conway to this definition?

@Jonah Idk, I don't have access to the original source, and I don't see any such information even on the Wikipedia page. One possible explanation could be that 4-chains and longer can express even faster-growing numbers than Knuth's up-arrows (and the Ackermann function).

@Jonah There's a little motivation here.

@MitchellSpector I looked it up in The Book of Numbers and the explanation there is pretty good: fundamentally, it looks like a generalization and more compact version of up arrow notation.  Although all these things grow so fast they defy anything we have intuition about

Haskell, 75 68 63 bytes
f(q:p:x)|p^q>p,x>[]=f$q-1:f(q:p-1:x):x|1<2=f$p^q:x
f[x]=x
f _=1

Try it online!
Takes input as a list in reversed order, since in Haskell it's easier to deal with the beginning of a list than with the end of it.
Now shorter and uglier!
Rules 3,4,5,6 are combined in the first line. The most important trick is realizing that p^q==p iff p==1||q==1 (where ^ is exponentiation and we're dealing with strictly positive numbers). We check the conditions to apply rule 6 (p and q greater than 1, at least three elements in the input) and if they are valid we do so recursively. If these conditions fail we know that either there is a 1 in the first two elements or there are just two elements in total: for both of this cases f(p^q:x) can solve the task.
The last two lines deal with inputs with less than two elements. They could be rewritten as a single line f x=last$1:x but the score would not change.

Below the original solution, no golfing tricks, just beautiful Haskell code:
f[]=1
f[p]=p
f[q,p]=p^q
f(1:x)=f x
f(_:1:x)=f x
f(q:p:x)=f$q-1:f(q:p-1:x):x

Try it online!

Haskell is just beautiful. Amazing that this syntax easily beats the dc and c "golfed" implementations.

and aside of absence of whitespaces, it's actually not golfed at all.

That's right, compared to "real" code this is just missing a type declaration and a more meaningful name for the function, so we could say my golfing was just removing comments and whitespace :D I'm a bit disappointed that I couldn't find a way to really golf this more, but I'm always happy to show how beautiful Haskell can be.

Ok, sorry to ruin all of this, I found a way to golf it and made everything ugly :/

dc, 112 107 bytes
?[dz0r^+q]sZ[rd3Rd_3R^q]sE[ilfx1rq]sA[iSplfx1rLprq]sB[z2>Zz2=Ed1=Ard1=B1-rlfx3RSpr1-lfx_3Rri1+Lp1+r3R]dsfxp

Try it online!
Or verify all the test cases.
The input is on stdin (a line with space-separated numbers), and the output is on stdout.

How it works:
dc is a stack-based language.  The recursive macro f does the Conway chained-arrow calculation, but the stack is treated differently from what you usually see:

The input to f is the entire stack when the call is made.  (So f essentially takes a variable number of arguments.)
If the stack at the time of call is

$$a_1 \; a_2  \; \dots  \; a_n$$
(with the top of the stack on the right), f will compute the value of
$$a_1 \to a_2 \to \dots \to a_n$$
and push it on top of the stack, but it leaves the arguments on the stack also.
So f turns the stack
$$a_1  \; a_2  \; \dots  \; a_n$$
into
$$a_1  \; a_2  \; \dots  \; a_n  \; [\text{ArrowValue}(a_1  \; a_2  \; \dots  \; a_n)]$$
where I've written \$\;[\text{ArrowValue}(a_1  \; a_2  \; \dots  \; a_n)]\;\$ for the value of \$\;a_1 \to a_2 \to \dots \to a_n.\$
There are several auxiliary macros as well.  All the usual complex control structures other languages have (loops, conditionals, functions) are implemented in dc using macros.

Note that dc produces a few error messages or warnings due to the golfing tricks used, but they don't interrupt program execution, and the messages are just written to stderr. Examples of these: duplicating when there's nothing on the stack, adding when there's only one item on the stack, or setting the input base to an illegal value.
The code also makes use of the fact that we can distinguish positive numbers from \$0\$ by whether the power \$0^x\$ is \$0\$ or \$1.\$

Here's a detailed summary of the program's operation, updated for the revised, shorter answer.
?  Read a line of space-separated numbers, written in the usual
   Conway chained-arrow order, pushing them onto the stack in turn.
   (The chained arrow sequence will start at the bottom of the stack,
   since that's pushed first, and will end at the top of the stack, since
   that's pushed last.)

        MACRO Z
Macro Z will only be called when the stack either is empty or
has just one item p on it.  We'll analyze both possibilities.
[   Start macro.
         Stack: Empty   or   p
 d    Duplicate.
         Stack: Empty   or   p p
 z    Push the size of the stack.
         Stack: 0       or   p p 2
 0    Push 0.
         Stack: 0 0     or   p p 2 0
 r
      Swap.
         Stack: 0 0     or   p p 0 2
 ^    Exponentiate.
         Stack: 1       or   p p 0
 +    Add top 2 items if they exist.
         Stack: 1       or   p p
 q    Exit this macro and the macro which called it.
]sZ End macro and name it Z.

Summary of Z:
      Turn: Empty stack
      Into: 1
and
      Turn: p
      into: p p

        MACRO E
[       Start a macro.  Assume the stack is: ... p q (top on right).
 r        Swap.                         Stack: ... q p
 d        Duplicate.                    Stack: ... q p p
 3R       Rotate left the top 3 items.  Stack: ... p p q
 d        Duplicate.                    Stack: ... p p q q
 _3R      Rotate right the top 3 items. Stack: ... p q p q
 ^        Exponentiate.                 Stack: ... p  q p**q
 q        Exit this macro and the macro which called it.
]sE     End the macro and name it E.
Summary of E:
  Turn: ... p q
  into: ... p q p**q

        MACRO A
[       Start a macro.  Assume the stack is:   ... p (top on right).
 i        Discard the top of stack.  (Actually make it the new input radix just because dc wants a place to put it.)
                                        Stack: ...
 lfx      Call f recursively.           Stack: ... ArrowValue(...)
 1        Push 1.                       Stack: ... ArrowValue(...) 1
 r        Swap.                         Stack: ... 1 ArrowValue(...)
 q        Exit this macro and the macro which called it.
]sA     End the macro and name it A.
Summary of A:
  Turn: ... p
  into: ... 1 ArrowValue(...)

        MACRO B
[       Start a macro.  Assume the stack is:    ... p q (top on right).
 i        Discard top of stack (by storing it as the input radix).
                                         Stack: ... p
 Sp       Pop p off the stack and
          push it onto stack p.          Stack: ...
 lfx      Call f recursively.            Stack: ... ArrowValue(...)
 1        Push 1.                        Stack: ... ArrowValue(...) 1
 r        Swap.                         Stack: ... 1 ArrowValue(...)
 Lp       Pop the old value of p from stack p.
                                        Stack: ... 1 ArrowValue(...) p
 r        Swap                          Stack: ... 1 p ArrowValue(...)
 q        Exit this macro and the macro which called it.
]sB     End the macro and name it B.
Summary of B:
  Turn: ... p q
  into: ... 1 p ArrowValue(...)

        MACRO f
[       Start a macro.
 z      Push the stack size.
 2>     If the stack size was 0 or 1,
 O        then call macro Z and return from f.
          In this case, we've turned ...
                                into ... 1

                     or we've turned ... p
                                into ... p p

 z2=E   If the stack size was 2,
          then call macro E and return from f.
          In this case, we've turned ... p q
                                into ... p q p**q

        If we get here, the stack size is at least 3.

 d1=A   If the item at the top of the stack == 1,
          then call macro A and return from f.
          In this case, we've turned ... 1
                                into ... 1 ArrowValue(...)

        If we get here, the stack size is at least 3 and the item at the top of the stack isn't 1.
                              Stack: ... p q r
          where r != 1.
 r      Swap.                 Stack: ... p r q
 d1=B   If the item at the top of the stack == 1,
          then call macro B and return from f.
        In this case, we've turned   ... p 1 r
                              into   ... p 1 r ArrowValue(... p)

        If we get here, the stack size is at least 3, neither of the items at the top of the stack is 1,
        and we've already gone from
                              Stack: ... p q r
                           to Stack: ... p r q
 1-     Subtract 1.           Stack: ... p r q-1
 r      Swap.                 Stack: ... p q-1 r
 lfx    Call f recursively.   Stack: ... p q-1 r [ArrowValue(... p q-1 r)]
 3R     Rotate left the top 3 items on the stack.
                              Stack: ... p r [ArrowValue(... p q-1 r)] q-1
 Sp     Pop q-1 off the stack and push it onto stack p.
                              Stack: ... p r [ArrowValue(... p q-1 r)]
 r      Swap.                 Stack: ... p [ArrowValue(... p q-1 r)] r
 1-     Subtract 1.           Stack: ... p [ArrowValue(... p q-1 r)] r-1
 lfx    Call f recursively.   Stack: ... p  [ArrowValue(... p q-1 r)]  r-1  [ArrowValue(... p ArrowValue(... p q-1 r) r-1)]
 _3R    Rotate right the top 3 items on the stack.
                              Stack: ... p  [ArrowValue(... p ArrowValue(... p q-1 r) r-1)]  [ArrowValue(... p q-1 r)]  r-1
 r      Swap:                 Stack: ... p  [ArrowValue(... p ArrowValue(... p q-1 r) r-1)]  r-1  [ArrowValue(... p q-1 r)]
 i      Discard the top item. Stack: ... p  [ArrowValue(... p ArrowValue(... p q-1 r) r-1)]  r-1
 1+     Add 1                 Stack: ... p  [ArrowValue(... p ArrowValue(... p q-1 r) r-1)]  r
 Lp     Load the old value of q-1 from stack p.
                              Stack: ... p  [ArrowValue(... p ArrowValue(... p q-1 r) r-1)]  r  q-1
 1+     Add 1.                Stack: ... p  [ArrowValue(... p ArrowValue(... p q-1 r) r-1)]  r  q
 r      Swap.                 Stack: ... p  [ArrowValue(... p ArrowValue(... p q-1 r) r-1)]  q  r
 3R     Rotate left the top 3 items on the stack.
                              Stack: ... p  q  r  [ArrowValue(... p ArrowValue(... p q-1 r) r-1)]
]       End the macro,
dsf       save it on the stack, and name it f.
Summary of f:
  Turn: ...
  into: ... ArrowValue(...)

x       Execute f.
p       Print the desired value, which is now at the top of the stack.

C (gcc) -m32 -lm, 159 150 137 136 bytes
f(a,b,u,t)int*a,*b;{t=a-b?b-a-1?*a-1?b-a-2?a[1]-1?t=a[1]--,a[1]=f(a,b),--*a,u=f(a,b),++*a,a[1]=t,u:f(a+2,b):pow(a[1],*a):f(a+1,b):*a:1;}

Try the test cases online! (except for [4, 3, 2], which overflows).
9 bytes off thanks to ceilingcat!
And saved 1 more byte thanks to ceilingcat too.

Input is taken as an array of ints in reverse order, and is passed as a pointer to the beginning and a pointer to (the location immediately after) the end.

The following applies to the previous version of the program.  The current version uses exponentiation from the C math library.  The compilation flag -m32 is now used so that the usual #include <math.h> line can be omitted.
C doesn't have exponentiation built in, so the previous version handled that by changing the 3rd and 4th rules of the recursive definition from
$$
\begin{align}
p \to q &= p^q \\
X \to 1 &= X \\
\end{align}
$$
to
$$
\begin{align}
\quad\quad\quad\quad\quad X \to 1 &= X \\
 p \to q &= (p \to q-1)*p \\
\end{align}
$$

APL (Dyalog Unicode), 57 49 48 46 bytes
Saved 8 bytes thanks to @Bubbler!
{3>≢w←⍵↓⍨⊃⍸1≠⍵:*/⌽w⋄(∇(⊃w-1),,∘(2↓w))⍣(1⊃w)⊢1}

Try it online!
A monadic function that must be given the input in reverse. Now also requires zero-indexing. This is slightly different from Conway's definition, but I think it's equivalent. If anyone can find a more math-y proof, that'd be great.
This is how Conway described his chained arrow notation:

Our own "chained arrow" notation names some even larger numbers. In this, a^^...^^b (with c arrows) is called a->b->c.
a->b-> ... ->x->y-> 1 is another name for a->b-> ... ->x->y
and a ... x->y->(z+1) is defined to be
a ... x if y = 1,
a ... x->(a...x)->z if y = 2,
a ... x->(a...x->(a...x)->z)->z if y = 3
and so on.

No one likes ones (and \$X\to 1\$ evaluates to \$X\$), so we first remove leading ones using ⍵↓⍨⊃⍸1≠⍵. ⊃⍸1≠⍵ is the first (⊃) index where (⍸) there isn't a 1 (1≠⍵), and we drop (↓) until that index. The result of that is assigned to w to reuse.
We can replace the first rule from here with the first three rules from the question. So if w has 0, 1, or 2 elements (3>≢w), we can fold over it with exponentiation (*/⌽w), because according to APL's rules, */x is x and */⍬ (⍬ is an empty set) is 1. We do have to reverse (⌽) w again, though, because it was reversed in the first place.
The second part of the function takes care of cases when w is in the form \$X \to y \to (z+1)\$. It's essentially \$y\$ applications of the function \$\lambda a. X \to a \to z\$, starting, with 1.
If \$y\$ and \$z\$ are both 1, then this becomes \$X \to 1 \to 1\$. Next iteration, w will be just \$X\$. If only \$y\$ is 1, then it becomes \$X \to 1 \to z\$. After that, it becomes \$X \to 1 \to (z-1)\$, then \$X \to 1 \to (z-2)\$, and so on until it reaches \$X \to 1 \to 1\$, which gives us \$X\$. So this satisfies the fifth rule in the question (\$X \to 1 \to p = X\$).
If \$y\$ is greater than 1, this becomes
$$
X \to (X \to (... (X \to (X \to (1) \to z) \to z) ...) \to z) \to z\\
= X \to (X \to (... (X \to (X) \to z) ...) \to z) \text{ (by question's 5th rule)}
$$
The second is Conway's definition (there are \$y\$ copies of \$X\$ and \$y-1\$ copies of \$z\$). In the first, there are \$y\$ copies of both \$X\$ and \$z\$.

The second one doesn't work on TIO because you're using ⍤ as Atop (f⍤g) which was added in 18.0, while TIO is still at 17.1. You can convert that part into a train (eliminating the need of Atop). Also, 1 1, in */⌽1 1,⍵ can be entirely removed (*/⍬ is 1). Finally, using a variable for 2↓⍵ gives 49 bytes.

J, 90 79 75 bytes
(1:`]`(^~/)`(2&}.$:@,~<:@{.,[:$:]-2=#\)@.(3<.#))`($:@}.~1+i.&1)@.(1 e.2&{.)

Try it online!
Takes input in reverse order.
I suspect there's room for more golfing yet.  I may return to it tomorrow.

Rust, 161 bytes
fn f(s:&[u32])->u32{match
s{[]=>1,[x]=>*x,[p,q]=>p.pow(*q),[x@..,1]=>f(x),[x@..,1,_]=>f(x),[x@..,p,q]=>f(&[x,&[f(&[x,&[p-1],&[*q]].concat())],&[q-1]].concat())}}

Uses Rusts pattern matching. The last case is a little verbose, because there's no spread operator.
Try it on the rust playground.
Readable version
fn f(s: &[u32]) -> u32 {
    match s {
        []=>1,
        [x]=>*x,
        [p,q]=>p.pow(*q),
        [x@..,1]=>f(x),
        [x@..,1,_]=>f(x),
        [x@..,p,q]=>f(&[x, &[f(&[x,&[p-1,*q]].concat())], &[q-1]].concat())
    }
}

Python 2, 117 112 111 bytes
f=lambda x:(len(x)<3)*reduce(lambda a,b:b**a,x,1)or f((1in x[:2])*x[1:]or[x[0]-1,f([x[0],x[1]-1]+x[2:])]+x[2:])

Try it online!
Takes input in reverse order.
A recursive function that takes in a list of positive integers and returns a single number.
In order to save bytes, we combine the 3 base cases into one expression:
(len(x)<3)*reduce(lambda a,b:b**a,x,1)

which returns either \$1\$, \$p\$, or \$p^q\$.

The recursive cases are also mashed together via:
f((1in x[:2])*x[1:]or[x[0]-1,f([x[0],x[1]-1]+x[2:])]+x[2:])

which becomes f(x[1:]) when x[0] is \$1\$ or x[1] is \$1\$, and becomes f([x[0]-1,f([x[0],x[1]-1]+x[2:])]+x[2:]) otherwise.

JavaScript (ES7),  78  77 bytes
Takes the list in reverse order.
f=([q,p,...a])=>a+a?f(--q?--p?[q,f([++q,p,...a]),...a]:a:[p,...a]):p**q||q||1

Try it online!
With BigInt support (78 bytes)
This version accepts either a list of Numbers or a list of BigInts and returns a value of the same type.
f=([q,p,...a])=>a+a?f(--q?--p?[q,f([++q,p,...a]),...a]:a:[p,...a]):p?p**q:q||1

Try it online!

Is that supposed to be a[0]? By my reading, that should be ...a...

@Neil You're right: $X$ is ...a. Thank you!

Erlang (escript), 111 bytes
Port of the Haskell answer. The last case seems to time out.
f([])->1;f([P])->P;f([1|X])->f(X);f([Q,P])->math:pow(P,Q);f([_,1|X])->f(X);f([Q,P|X])->f([Q-1,f([Q,P-1|X])|X]).

Try it online!

Factor, 144 bytes
:: g ( x -- y )
x llength 3 < [ x 1 [ swap ^ ] foldl ]
[ x car 1 = [ x cdr g ]
[ 1 x cadr [ x cdr cdr cons x car 1 - swons g ] times ] if
] if ;

Try it online!
Takes a linked list in reverse order. Uses the algorithm described in user's APL answer.
Using linked lists is shorter than using arrays when the code involves a lot of dissection at the start (and you don't need sophisticated sequence operations):
first (5)              > car (3)
rest (4)               > cdr (3)
second (6) > 1 nth (5) > cadr (4)
prefix (6)             > cons (4)
swap prefix (11)       > swons (5)
unclip (6)             = uncons (6)
unclip swap (11)       > unswons (7)

How it works
:: g ( x -- y )         ! Takes a list `x` and returns a number
  x llength 3 < [         ! If x has 2 or fewer numbers...
    x 1 [ swap ^ ] foldl    ! Reduce by ^ on reversed arguments
  ] [                     ! Otherwise `x` is in the form of `X->y->z`
    x car 1 = [           ! If z is 1...
      x cdr g               ! Remove z(=1) and recurse
    ] [                   ! Otherwise...
      1                     ! Setup the initial value of 1
      x cadr                ! Setup the loop count of y
      [ x cdr cdr cons      ! Build y':X
        x car 1 - swons g ] ! Build z-1:y':X
      times                 ! Iterate the above function y times to 1
    ] if
  ] if

This paper's pretty interesting, although I don't know if it would be of any help.

Java, 282 chars
interface c{int n[]=new int[99];static void main(String[]a){int i=0,j=a.length;for(;i<j;)n[i]=new Integer(a[i++]);System.out.print(j<1?1:j<2?n[0]:c(j));}static int c(int j){j-=n[j-2]<2?2:n[j-1]<2?1:0;if(j<3)return(int)Math.pow(n[0],n[1]);n[j-2]--;n[j-2]=c(j);n[j-1]--;return c(j);}}

Readable version:
interface c{
    int n[]=new int[99];
    static void main(String[]a){
        int i=0,j=a.length;for(;i<j;)n[i]=new Integer(a[i++]);
        System.out.print(j<1?1:j<2?n[0]:c(j));
    }
    static int c(int j){
        j-=n[j-2]<2?2:n[j-1]<2?1:0;
        if(j<3)return(int)Math.pow(n[0],n[1]);
        n[j-2]--;
        n[j-2]=c(j);
        n[j-1]--;
        return c(j);
    }
}

05AB1E, 68 66 bytes
"D©g2‹iPë`i)Y.Vëi)Y.Vë)\®`®g<imëX®šUs<s)Y.VXćsUDgÍsŠǝRć<šRY.V"DV.V

This was pretty hard in a stack-based language..
Try it online or verify all test cases.
Explanation:
"                          "# Start a string we can execute as 05AB1E code
                            # to mimic recursive calls:
 D                          # Duplicate the list at the top of the stack
                            # (which will be the (implicit) input at the start)
  ©                         # Store it in variable `®` (without popping)
   g2‹i                     # Pop one, and if its length is smaller than 2:
       P                    #  Take the product
                            #  ([] → 1; [p] → p)
   ë                        # Else (the length is >= 2):
    `                       #  Dump the contents of the list onto the stack
     i                      #  Pop the top value, and if it's a 1:
      )                     #   Wrap the remaining values into a list
       Y.V                  #   And do a recursive call
                            #   (p=1 for [...,q,p] → recursive call to [...,q])
     ë                      #  Else:
      i                     #   Pop the second top value, and if it's a 1:
       )                    #    Wrap the remaining values into a list
        Y.V                 #    And do a recursive call
                            #    (q=1 for [...,q,p] → recursive call to [...])
      ë                     #   Else:
       )\                   #    Discard everything on the stack
         ®`                 #    Dump the contents of `®` onto the stack again
           ®g<i             #    If the length of `®` is 2:
               m            #     Take the power of the two values
                            #     ([p,q] → p^q)
              ë             #    Else (the length is >= 3):
               X®šU         #     Prepend `®` to list `X`
                            #     (`X` is 1 by default, but that doesn't matter;
                            #      it'll become [[...,p,q],1] and the 1 is ignored)
               s<s)         #     Decrease the second value from the top by 1
                   Y.V      #     And do a recursive call
                            #     ([...,p,q] → recursive call to [...,p-1,q],
                            #      let's call its result `R` for the moment)
               Xć           #     Extract the first list from variable `X` again,
                 sU         #     and pop and store the remaining values as new `X`
                 DgÍ        #     Take its length - 2 (without popping by duplicating first)
                            #     (let's call this length-2 `I` for the moment)
                    sŠ      #     Swap & triple-swap ([...,R,[...,p,q],I] → [...,[...,p,q],R,I])
                      ǝ     #     Insert value `R` into the list at (0-based) index `I`
                            #     ([...,[...,p,q]] → [...,[...,R,q]])
                 Rć<šR      #     And decrease the last value in the top list by 1
                            #     ([...,[...,R,q]] → [...,[...,R,q-1]])
                       Y.V  #     And do a recursive call again
"                          "# End the string of 05AB1E code
 DV                         # Store a copy of this string in variable `Y`
   .V                       # Execute it as 05AB1E code (`Y.V` is how we can do recursive calls)
                            # (after which the result is output implicitly)

Pyth, 40 38 bytes
L?tJtby?}1<b2J+,thby+,hbthJtJttb|^F_b1

Try it online!
Takes input in reverse order.
L defines a recursive function named y that takes in a list b of positive integers and returns a single number.
Similarly to my Python answer, the base cases are combined into one expression:
|^F_b1

in which ^F_b folds the exponentiation function ^ over b in reverse. If b has 2 elements \$(q,p)\$ this will return \$p^q\$, if b has 1 element \$(p)\$ it will return \$p\$, and if b is empty it will return 0 (| .. 1 turns the 0 into 1, as needed)

The recursive cases are handled by:
y?}1<b2J+,thby+,hbthJtJttb

This part is a pretty straightforward translation of the recursive rules. If either of the first two elements of b are 1 it calls y on tb (equivalent to b[1:] in Python)*. Otherwise, the formula \$X \to (X \to p\to (q+1))\to q\$ is passed recusively to y.
*The rule \$X \to 1 \to p = X\$ thus takes two steps instead of one, but doing it this way saves a few bytes.

Clojure, 117 bytes
(defn f([]1)([q]q)([q p](Math/pow p q))([q p & x](if(== p(f q p))(apply f p x)(apply f(dec q)(apply f q(dec p)x)x))))

Try it online!
Handles all test cases, takes input arguments in reverse order.

Scala, 156 141 bytes
val f:Seq[Int]=>Int={case x if x.size<3=>(x:\1.0)(math.pow(_,_))toInt
case 1::x=>f(x)case p::1::x=>f(x)case q::p::x=>f(q-1::f(q::p-1::x)::x)}

Try it in Scastie
Note: Input must be a reversed List. If it's not reversed, the algorithm won't work correctly, and if it's not a List, there'll be a MatchError.
I hate that math.pow(_,_) works but just math.pow would need the first argument to be a Double.

Wolfram Language (Mathematica), 67 66 bytes
f[x__,1,_:0]=f@x
f[x___,p_:1,q_:1]=If[x<1,p^q,f[x,f[x,p-1,q],q-1]]

Try it online!