text:
Calculate the Progressive Mean™
Disclaimer: This challenge is inspired by a coding error I once made.

Okay, time for a maths lesson. A normal mean average looks like this:
Work out the sum of all numbers in a list
then divide by the size of the list.

But what if we don't know all the numbers at the time we're working out the average? We need a way to work out the average which can be added to over time. For this reason, I present the algorithm for a Progressive Mean™
The running total is the first number in the list
For each of the remaining numbers
  Add the number to the running total
  Divide the running total by two

So in effect we're averaging each number with the current average. (We could add to this later and get the same result)
BUT
This doesn't give the same result at all. It gives an average, but it differs from the standard methodology for finding the mean. Now the order of the list of numbers is significant.
Of course, being a curious type, I want to work out if the Progressive Mean™  tells us anything about the order of our list of numbers. So for this reason I want to compare Mean with Progressive Mean™ by means of a simple subtraction:
trend = Progressive Mean™ - Standard Mean

The Challenge

Write a piece of code which accepts a list of numbers (in any format) which then calculates three pieces of information about it:

Standard Mean
Progressive Mean™
Trend (Progressive - standard)

Work in any language you like.
It's golf, attempt to do the challenge in as few bytes as you can.
Avoid Standard Loopholes
I want the output to be human-readable numbers.
Please include a link to an online interpreter such as tio.run

Test Cases:
[1,2,3]

Normal Mean:        2.0
Progressive Mean:   2.25
Trend:              0.25

[3, 2, 1]

Normal Mean:        2.0
Progressive Mean:   1.75
Trend:              -0.25

[10, 20, 30]

Normal Mean:        20.0
Progressive Mean:   22.5
Trend:              2.5

[300, 200, 100]

Normal Mean:        200.0
Progressive Mean:   175.0
Trend:              -25.0

[10, 100, 10]

Normal Mean:        40.0
Progressive Mean:   32.5
Trend:              -7.5

[4, 4, 9, 8, 1, 8, 6, 9, 1, 1]

Normal Mean:        5.1
Progressive Mean:   2.62890625
Trend:              -2.4710937499999996

[1, 1, 1, 4, 4, 6, 8, 8, 9, 9]

Normal Mean:        5.1
Progressive Mean:   8.5390625
Trend:              3.4390625000000004

[9, 9, 8, 8, 6, 4, 4, 1, 1, 1]

Normal Mean:        5.1
Progressive Mean:   1.47265625
Trend:              -3.6273437499999996

Do we have to output all 3 calculations, or just the trend?

...also a set has no order, while here the order is paramount.

I’m fine with it being called list. Yes, all three calculations, please.

I believe your progressive mean is a type of decaying average.

"a set of numbers (in any format)" — even in reverse?

@Adám I was more thinking about it being expressed as string formats, binary, array etc. I'd say when the order in significant we probably shouldn't allow reversed order.

@AJFaraday I'd keep the order, just read it from right to left.

Do we need to output decimal points?

@ssanne yes, we definitely need decimal points.

Can we assume the list is non-empty?

@IMP1 Yes, you can definitely assume that.

Just commenting to point out that your "progressive mean" is well known and used; it's an exponentially weighted moving average with coefficient 1/2.

@acwaters That's interesting, thank you.

suggested test case: [1] -> 1,1,0; this was screwing up my answers before. I would also include a 2-element test case, which will of course have identical progressive/regular means.

Jelly, 9 bytes
Æm;+H¥/ṄI

A full program which accepts a list of decimals which prints:
[mean, progressive-mean]
trend

Try it online!
How?
Æm;+H¥/ṄI - Link: list of numbers, A
Æm        - arithmetic mean       sum(A)/length(A)            = mean
      /   - reduce (A) by:
     ¥    -   the dyad f(leftEntry, rightEntry):
   +      -     addition          leftEntry + rightEntry
    H     -     halve            (leftEntry + rightEntry) / 2 = progressiveMean
  ;       - concatenate           [mean, progressiveMean]
       Ṅ  - print this list and yield it
        I - deltas                [progressiveMean - mean]
          - implicit print (Jelly represents with a single item as the item)

R, 57 bytes
function(v,`!`=sum,N=!1^v)c(A<-!v/N,P<-!v/2^c(N:1,N),P-A)

Try it online!
A clever collaboration with digEmAll and RobinRyder; uses the observation by Grimmy and Kevin's explanation from the comments, which I replicate below:

For anyone else wondering why the example [a,b,c,d] -> [a,b,c,c,d,d,d,d] doesn't match the explanation of the code, it actually transforms [a,b,c,d] to [a,b,b,c,c,c,c,d,d,d,d,d,d,d,d,a] (so two of each value in comparison to the example). The example confused me for a moment. But nice answer, +1 from me! I also like that it has all these different types of the letter 'A' in the code: āÅÅAÂÆª. xD

This uses R's recycling rules to use two copies of l[1]/2^N in the sumby just sticking an extra N at the end of the decay rate.
R, 62 bytes
function(l)c(p<-Reduce(function(x,y)(x+y)/2,l),a<-mean(l),p-a)

Try it online!
Straightforward implementation.

Try it online! - same length (62) but using the fancier approach (maybe I'm missing some trivial improvements)

59 bytes by building on @digEmAll 's approach.

@RobinRyder neither yours nor digEmAll's (nor my 51 byte solution) works for the case of 1 element...I guess I can ask about that.

@digEmAll actually, using the observation of Kevin's comment here, we can just use R's recycling rules to take Robin's answer and shave off another two bytes.

J, 17 bytes
Translation of this.
-:@+/@|.(,,-)+/%#

Anonymous tacit prefix function. Returns list of Progressive Mean™, Standard Mean, Trend.
Try it online!
This consists of three parts: (2÷⍨+)⌿∘⌽ (,,-) +⌿÷≢
+/ % # is the sum divided by the number of elements
…⌿@|. reverses the list and then reduces from right to left using the function:
 -:@+ add next value to previous value and halve that
(,,-) is the concatenation of the PM and the SM, concatenated to their difference

Python 3.8 (pre-release), 70 69 bytes
-1 byte thanks to Kyle Gullion
returns (mean, p_mean, trend)
lambda x:(m:=sum(x)/len(x),[p:=x[0],*[p:=(p+n)/2for n in x]][-1],p-m)

Try it online!
Alternate version with more of a reducer implementation (89 bytes):
lambda x:(m:=sum(x)/(l:=len(x)),[x:=[sum(x[0:2])/2]+x[2:]for n in range(l-1)][-1],x[0]-m)

Although this is longer, I suspect this reducer implementation may be useful for future python 3.8 code golfing.
Try it online!
I know there has to be some more clever tricks to golf this further...

can shave a byte using tuple unpacking: Try it online!

05AB1E, 13 bytes
ÅAIÅ»+;}θ‚ÂÆª

Outputs as a triplet [mean, progressive-mean, trend].
Try it online or verify all test cases.
Explanation:
ÅA     # Calculate the arithmetic mean of the (implicit) input-list
I      # Push the input-list again
 Å»    # Left-reduce it by:
   +   #  Add the two values together
    ;  #  And halve it
 }θ    # After the reduction, leave only the last value
‚      # Pair it with the earlier calculated arithmetic mean
 Â     # Bifurcate this pair; short for Duplicate & Reverse copy
  Æ    # Reduce it by subtraction
   ª   # And append this trend to the pair
       # (after which the result is output implicitly)

@Grimmy I kinda wish Å»+;}θ could be done shorter though. Unfortunately .»ÅA doesn't work, since ÅA only works on lists, and not on the values on the stack, so it will just output the last integer of the input-list unfortunately.

I found the fix: ā<oÅΓĆ‚€ÅAÂÆª. The first number has the same weight as the second number, my mistake was giving it only half of that weight. This is now 13 bytes like yours; I'll make it a separate answer.

Actually, ÅA vectorizes, so I can drop the € for a 12.

Scratch 2.0/3.0, 35 blocks/263 bytes

SB Syntax:
when gf clicked
set[i v]to(2
set[L v]to(length of[I v
set[T v]to(item(1)of[I v
set[P v]to(T
repeat((L)-(1
change[T v]by(item(i)of[I v
change[P v]by(item(i)of[I v
set[P v]to((P)/(2
change[i v]by(1
end
set[T v]to((T)/(L
say(join(join(join(join(P)[,])(T))[,])((P)-(T

It's accidentally a polyglot. I accidentally forgot my password and email for my other scratch account so I had to make a new one so y'all can Try it on Scratch!
Y'all need to change the input list shown in the top left corner on the project for this to work properly.

Python 3, 81 \$\cdots\$ 75 71 bytes
Saved 15 bytes thanks to Reinstate Monica!!!
def f(l):
 m=sum(l)/len(l);p=l[0]
 for n in l:p=(p+n)/2
 return m,p,p-m

Try it online!

You can remove the parentheses in the return statement, no?

@ReinstateMonica Didn't know that - Thanks! :-)

No problem! Also, since (p[0]+p[0])/2 == p[0], the pop is unnecessary; you can just use l[0]

@ReinstateMonica Clever - thanks again! :-)

JavaScript (ES6), 55 bytes
Returns [mean, p_mean, trend].
a=>a.map(v=>t=(s+=v,n++)?(t+v)/2:v,n=s=0)&&[s/=n,t,t-s]

Try it online!

APL (Dyalog Unicode), 20 18 bytesSBCS
-2 thanks to Bubbler.
Anonymous tacit prefix function. Returns list of Progressive Mean™, Standard Mean, Trend.
(2÷⍨+)⌿∘⌽(,,-)+⌿÷≢

Try it online!
This consists of three parts: (2÷⍨+)⌿∘⌽ (,,-) +⌿÷≢
+⌿ ÷ ≢ is the sum divided by the count
(…)⌿∘⌽ reverses the list and then reduces from right to left using the function:
 2÷⍨+ add next value to previous value and divide that by two
(,,-) is the concatenation of the PM and the SM, concatenated to their difference

05AB1E, 12 bytes
āÍoîÅΓ‚ÅAÂÆª

Try it online!
The progressive mean is equivalent to a weighted arithmetic mean, with exponentially increasing weights. For example, the progressive mean of a 4 element list [a, b, c, d] is the arithmetic mean of [a, b, c, c, d, d, d, d].
ā              # range [1..length of input]
 Í             # subtract 2 from each
  o            # 2**each: [0.5, 1, 2, ...]
   î           # round up: [1, 1, 2, ...]
    ÅΓ         # run-length decode
      ‚        # pair with the input
       ÅA      # arithmetic mean of each list
         Â     # push a reversed copy
          Æ    # reduce by subtraction
           ª   # append

For anyone else wondering why the example [a,b,c,d] -> [a,b,c,c,d,d,d,d] doesn't match the explanation of the code, it actually transforms [a,b,c,d] to [a,b,b,c,c,c,c,d,d,d,d,d,d,d,d,a] (so two of each value in comparison to the example). The example confused me for a moment. But nice answer, +1 from me! I also like that it has all these different types of the letter 'A' in the code: āÅÅAÂÆª. xD

@KevinCruijssen I changed the code to match the explanation (same byte count).

Factor, 80 79 bytes
: f ( s -- s ) [ mean ] [ dup first [ + 2. / ] reduce ] bi 2dup swap - 3array ;

Try it online!

Wolfram Language (Mathematica), 31 bytes
{a=Mean@#,b=+##/2&~Fold~#,b-a}&

Try it online! Pure function. Takes a list of numbers as input and returns a list of rational numbers as output. I'm pretty sure that improper fractions count as human-readable, but if they aren't, adding N@ (+2 bytes) to the start causes the function to output approximate numbers.

PowerShell, 54 bytes
$args|%{$y+=$_;$z=($_+$z)/(2-!$i++)}
($y/=$i)
$z
$z-$y

Try it online!
Takes input by splatting. The only neat trick is the !$i++ bit which negates the first iteration where $i is 0 to 1, and all subsequent numbers to 0.

Raku(Perl 6), 41 40 bytes
{|($/=(.reduce((*+*)/2),.sum/$_)),$0-$1}

My original solution had my \a=and used [-]|@a at the end, but abusing $/ is always fun, especially with also abusing assignments.  Pretty straightforward calculation wise.
Try it online!

FWIW, the TIO link no longer matches the solution.

C (gcc), 111 109 bytes
#define P printf("%f "
f(a,l,i)int*a;{float s=*a++,p=s;for(i=l-1;i--;p+=*a++,p/=2)s+=*a;P,s/=l);P,p);P,p-s);}

Try it online!

95 bytes

Haskell, 84 bytes
I thought Haskell could do decently here because this challenge works on lists and I tend to think Haskell and lists go well together... But I couldn't come up with anything very clever. Let's see if @xnor drops by and has anything nice :P
f(h:l)=g$foldl(\(p,s,w)n->((p+n)/2,s+n,w+1))(h,h,1)l
f[]=f[0]
g(p,s,l)=(s/l,p,p-s/l)

I am defining an anonymous function \(p,s,w) n -> ((p+n)/2, s+n, w+1) that receives a triplet and the next list element, and does three things: updates the progressive mean, sums the whole list and computes its length. In the end, function g does some last-minute calculations.
You can try it online

Charcoal, 27 bytes
≔∕ΣθＬθη≔§θ⁰ζＦθ≔⊘⁺ιζζＩ⟦ηζ⁻ζη

Try it online! Link is to verbose version of code. Explanation:
≔∕ΣθＬθη

Calculate the arithmetic mean.
≔§θ⁰ζ

Start with the first element. We therefore end up averaging this element with itself, but that doesn't affect the final result of course.
Ｆθ≔⊘⁺ιζζ

Loop over each element an average it with the progressive mean so far.
Ｉ⟦ηζ⁻ζη

Print the arithmetic and progressive means and their difference.
If we had only needed the result once then ΣＥθ∕ιＸ²⁻Ｌθ∨κ¹ could have been used to calculate the progressive mean directly, saving 3 bytes over the naïve method.

PHP, 90 88 bytes
function($i){for($j=$i[0];$x=$i[$c++|0];$s+=$x,$j+=$x,$j/=2);return[$s/=$c-1,$j,$j-$s];}

Try it online!

Perl 5 -MList::Util=sum,reduce -pa, 51 50 bytes
say+($\=reduce{$a=$a/2+$b/2}@F)-($_=(sum@F)/@F.$/)

Try it online!
Output format is
trend
traditional
progressive

Burlesque, 19 bytes
psJr{.+2./}javq.-c!

Try it online!
Takes input of the form 300.0 200.0 100.0. If we didn't have to print the other values would be 3 bytes shorter (i.e. Without the continuation).
Returns progressive mean™, arithmetic mean, trend
ps    # Parse list to array
J     # Duplicate
r{    # Reduce by (Progressive Mean)
  .+  # Adding
  2./ # Dividing by 2
}
jav   # Calulcate regular mean
q.-   # Quoted (boxed) subtract {.-}
c!    # On a non-destructive stack

Python 3.8, 91 bytes
I wanted to flatten the recursive relation, and I got this:
lambda l:(m:=sum(l)/(n:=len(l)),(p:=sum(l[-i]/2**i for i in range(1,n))+l[0]/2**(n-1)),p-m)

Try it online!
The use of range instead of the list itself makes it much longer.

you can remove the brackets around the middle section to save 2 bytes Try it online!

Ruby, 54 bytes
->x{a=x.sum/x.size;b=x.inject{|a,b|a/2+b/2};[a,b,b-a]}

Try it online!
Takes a list of numbers in the format [1.0, 2.0, 3.0]
and returns an array containing the mean, progressive-mean, and trend, respectively.

Haskell, 58 bytes
s!p=(s,p,p-s)
f x=(sum x/sum[1|_<-x])!foldl1(((/2).).(+))x

Try it online!

Rust, 144 122 bytes
let f=|y:&[f64]|{let m=y.iter().sum::<f64>()/y.len()as f64;let pm=y[1..].iter().fold(y[0],|acc,x|(acc+x)/2.);(m,pm,pm-m)};

Straightforward approach. Shaved 22 bytes thanks SirBogman, and thanks Mabel for showing TIO's Rust support.
Try it online!

here you go :) Try it online!

You can remove the return keyword and the semicolon following the return statement.

Java (JDK), 116 115 bytes
v->{float m=0,p=0;for(int i=0;i<a.length;i++){m+=a[i];p+=a[i];p=i!=0?p/2:p;}m/=a.length;return m+"\n"+p+"\n"+(p-m);

Try it online!

105 bytes

Factor, 48 bytes
[ [ unclip [ + 2 / ] reduce ] keep mean 2dup - ]

Try it online!

Arturo, 57 bytes
$[b][a:average b@[p:fold.seed:b\0b[x y][//x+y 2]a p p-a]]

Try it

Scala, 126 bytes
Golfed version. Try it online!
def f(v:Array[Float])={var m,p:Float=0;for(i<-v.indices){m+=v(i);p+=v(i);p=if(i!=0)p/2 else p;};m/=v.length;s"$m\n$p\n${p-m}"}

Ungolfed version. Try it online!
object Main extends App {
  val a: Array[Float] = Array(9, 9, 8, 8, 6, 4, 4, 1, 1, 1)
  val f: Array[Float] => String = v => {
    var m, p: Float = 0
    for (i <- v.indices) {
      m += v(i)
      p += v(i)
      p = if (i != 0) p / 2 else p
    }
    m /= v.length
    s"$m\n$p\n${p - m}"
  }
  println(f(a))
}


text:
Roll a cube to a target position
You have your very heavy cubical box on a flat floor at position (0,0). All you can do with it is roll it in four cardinal directions (east, north, west, south). Your task is to bring it to a target position, such that the side facing up is the same as before your manipulations.
Make a program or function which receives target coordinates and returns the minimal sequence of moves which results in the box arriving to target in upright position.
Input: two integers x, y

Get it in any convenient format - as a pair, as a complex number, etc.
You can assume x² + y² ≠ 0

Output: a string of instructions containing characters E, N, W, S

Spaces and newlines are allowed
UPPER-CASE, lower-case and MiXeD-cAsE are allowed

Test cases:
2, 2 => EENN
2, 3 => ENENN
1, 0 => NES
-1, 0 => NWS
-1, -1 => ESWNWS
3, 4 => ENNENEN
-9, 0 => NWWWWWWWWWS
20, 5 => EEEEEEEEEEEEEEEEEEENENNNN

Note: the solutions above are not unique, so your code can have slightly different output. But it's required to output a minimal solution.
Invalid test cases:
0, 0 => not required to handle (the solution is an empty string)
1, 0 => N (invalid - the box arrives to x=0, y=1)
1, 0 => E (invalid because the box on its side)
2, 2 => ENWNESENWNES (invalid because it's not minimal)

When you say we can assume $x \times y \neq 0$ what do you mean? Because some of your test cases have $x\times y = 0$

I meant to exclude only one case! Fixed the text.

Do we really have to output NSEW or can we any other four distinct values?

I prefer leaving the requirement as it is. Otherwise it would be hard to verify the outputs. I don't think the additional freedom in encoding the 4 options would be very interesting.

I was thinking it would allow me to do some rotations and then undoing them by multiplying the directions by i.

There is a puzzle similar to this in Super Mario Odyssey for anyone that hasn't played.

MATL, 62 59 54 bytes
`J@4_YA4L)XH^sG=0H"'(-9@%3Vuao'F6Za4e@b3$)]>~}'NWSE'H)

Input is a complex number.
(Don't) Try it online!
The program is quite slow, and times out online for all of the test cases, but works offline. Here's an example with two test cases:

Explanation
Let the four directions in which the cube can be rolled be numbered as
1: N, 2: W, 3: S, 4: E.

Let the six positions of the cube faces be numbered as
0: top, 1: north, 2: west, 3: south, 4: east, 5, bottom

The face which is initially at the top will be called "reference face".
The essential part of the code is a matrix M that indicates, for any direction of roll (matrix row) and given the current position of the reference face (matrix column), what is the new position of the reference face:
   1 2 3 4 5 0
   -----------
1| 5 2 0 4 3 1
2| 1 5 3 0 4 2
3| 0 2 5 4 1 3
4| 1 0 3 5 2 4

For instance, M(4,2) = 0 indicates that if the cube is rolled east (4) when the reference face is on the west side of the cube (2), the reference face moves to the top (0).
This matrix is stored in the program in compressed form. It has been represented with column index 0 at the end because MATL's indexing is 1-based and modular, so 0 represents the last column.
The code generates all paths, with increasing length, until a solution is found. Each path is a sequence of numbers 1, 2, 3, 4, indicating roll directions. A path is a solution if it arrives at the destination (*) with the reference face at the top (**). To see how these conditions are checked, consider an example path 1,4,1,3,4 (NENSE).

(*) The first condition is checked using complex-number operations. The imaginary unit j raised to each number in the path gives a direction in the complex plane. The sum of all the complex numbers is the final location for the path. In this example, j^1 + j^4 + j^1 + j^3 + j^4 = j+1+j−j+1 = 2+j. This is compared with the input.
(**) The second condition is checked by repeatedly indexing into the above matrix. The initial position of the reference face is 0 (top). Since the first step of the path is 1 (N), we read M(1,0) = 1. So the reference face is now in the north side (1) of the cube. The next step of the path is 4 (E), and M(4,1) = 1. Next, M(1,1) = 5; and so on. The final result should be 0 for the path to be valid.

To generate all paths we increase a counter starting at 1, convert to base 4 with digits 1,2,3,4 instead of 0,1,2,3, and remove the first digit. If the first digit were not removed, paths starting with 1 (which is the zero digit in this numbering system) would not be generated.
`                % Do...while
  J              %   Push j (imaginary unit)
  @              %   Push loop counter, starting at 1. Each value generates a path
  4_YA           %   Convert to base 4 using 1,2,3,4 as digits
  4L)            %   Remove first digit. This is the path
  XH             %   Copy into clipboard H
  ^              %   Element-wise power
  s              %   Sum
  G=             %   Does it equal the input? This gives true (1) or false (0) (*)
  0              %   Push 0. This is the initial position of the reference face
  H              %   Push path again
  "              %   For each step in the path (with value 1, 2, 3 or 4)
    '(-9@%3Vuao' %     Push this string
    F6Za         %     Convert base from ASCII chars except single quote to base 6
    4e           %     Reshape as a 4-column matrix. This is matrix M
    @            %     Push current step
    b            %     Bubble up: move current position of reference face to top of stack
    3$)          %     Index into the matrix. This updates the position of reference face
  ]              %   End. Top of stack contains the final position of reference face (**)
  >~             %   Less than or equal? This gives false if and only if (*) is 1 and
                 %   (**) is 0, which means a solution has been found; and in that case
                 %   the loop will be exited
}                % Finally: execute on loop exit
  'NWSE'         %   Push this string
  H              %   Push current path, which is the solution
  )              %   Index. This gives a string with 1 replaced by 'N' etc
                 % Implicit end. The loop exits if the top of the stack is falsy
                 % Implicit display

JavaScript (ES6),  146 ... 138  125 bytes
Saved 2 bytes thanks to @Klaycon
Takes input as [x,y]. Brute-forces a path.
p=>eval("for(n=0;s=([X,Y]=p,k=0,++n+'').replace(/./g,n=>n<4&&'ENWS'[X+=~-n%2,Y+=~-~-n%2,k+=(n&2^6)+(k-~n)%3,n]),X|Y|k%6;);s")

Try it online!
How?
The position of the top face is \$k \bmod 6\$:
$$\begin{array}{c|c|c|c|c|c}
0&1&2&3&4&5\\[5px]
\hline
\text{top}&\text{left}&\text{back}&\text{bottom}&\text{right}&\text{front}
\end{array}$$
The current direction is \$n\$:
$$\begin{array}{c|c|c|c}
0&1&2&3\\[5px]
\hline
\text{East}&\text{North}&\text{West}&\text{South}
\end{array}$$
Given \$k\$ and \$n\$, the new position of the top face is:
$$k'=k+((n\operatorname{and}2)\operatorname{xor}6)+((k+n+1)\bmod3)$$
The values of \$k'\bmod6\$ given \$n\$ and \$k\bmod6\$ are summarized in the following table:
$$\begin{array}{c|cccccc}
k \bmod 6 & 0 & 1 & 2 & 3 & 4 & 5\\
\hline
n = 0 & 1 & 3 & 2 & 4 & 0 & 5\\
n = 1 & 2 & 1 & 3 & 5 & 4 & 0\\
n = 2 & 4 & 0 & 2 & 1 & 3 & 5\\
n = 3 & 5 & 1 & 0 & 2 & 4 & 3
\end{array}$$
Commented
Note: this is a version without eval() for readability
p => {                   // p = [x, y] = starting position
  for(                   // main loop:
    n = 0;               //   start with n = 0
    s = (                //   s is the move string that we're going to build
      [X, Y] = p,        //     start with [X, Y] = starting position
      k = 0,             //     start with k = 0
      ++n + ''           //     increment n and coerce it to a string
    ).replace(/./g, n => //   for each digit n in the resulting string:
      n < 4 &&           //     abort if n is greater than or equal to 4
      'ENWS'[            //     replace it with a direction character
        X += ~-n % 2,    //       X += dx
        Y += ~-~-n % 2,  //       Y += dy
        k +=             //       update k
          (n & 2 ^ 6) +  //
          (k - ~n) % 3,  //
        n                //       actual index for the direction character
      ]                  //
    ),                   //   end of replace()
    X | Y | k % 6;       //   stop when X = Y = k mod 6 = 0
  );                     // end of for()
  return s               // return the solution
}                        //

You can save one byte by removing the ; before the final s in the eval.

@famous1622 No, I can't. It would return the penultimate value of s.

Okay, sorry. Need more coffee >.<

-2 bytes removing extraneous array brackets surrounding the whole .replace() callback body

@Klaycon You're right. I think they were left there from a previous version. Thanks! (The only case where it's a problem is (0,0) but we're not supposed to support it.)

Charcoal, 78 bytes
≔⁰ζＷ¬υ«≔↨ζ⁵εＦε≔Ｉ§§⪪”)➙∨¤nDχτ⁺yφφY”⁷⊖κιι¿∧∧⁼¹ι⁼⁻№ε²№ε⁴Ｉθ⁼⁻№ε¹№ε³Ｉη⊞Ｏυ⍘ζ NESW≦⊕ζ

Try it online! Link is to verbose version of code. Brute-forces the answer by trying all strings of letters NESW until a solution is found. Explanation:
≔⁰ζ

Start counting through the strings.
Ｗ¬υ«

Repeat until a solution is found (in which case we'll push it to the empty list so that the loop will terminate). This always sets the loop variable to 1 (true).
↨ζ⁵ε

Convert the counter to a string of NESW letters. This ought to be done in bijective base 4 but Charcoal doesn't do bijective base conversion so it's golfier to do it in base 5 and filter out the zeros later.
Ｆε

Loop through each direction.
≔Ｉ§§⪪”)➙∨¤nDχτ⁺yφφY”⁷⊖κιι

Update the loop variable with the result of rolling the box in that particular direction using a look-up table, but if we hit a zero then the box falls into an impossible state from which it can never return to being the right-side up, thus excluding invalid solutions.
¿∧∧⁼¹ι

If the loop variable is back to 1 (meaning that the box is the right way up again)...
⁼⁻№ε²№ε⁴Ｉθ

... and the box is at the right x-coordinate...
⁼⁻№ε¹№ε³Ｉη

... and the box is at the right y-coordinate...
⊞Ｏυ⍘ζ NESW

... then convert the base-5 number to a string of direction letters, push it to the empty list, and print the resulting list (this has no effect on the output) ...
≦⊕ζ

otherwise increment the string counter.

Due to what is apparently a bug in Charcoal, the output is 0 for an (invalid) input of 0 0, when I was expecting a space or nothing at all.

Good idea using base 5 and removing zeros! In my answer I’m using base 4 and removing the leading digit, but I think this can save me 1 or 2 bytes. (MATL also needs bijective base conversion...)

@LuisMendo Removing leading elements is expensive in Charcoal which is why I avoided it, although I did get it down to 80 bytes, and it avoids my 0 0 bug too.

PHP, 230 223 213 211 202 bytes
function($a,$b){for(;;){$f=$x=$y=0;$q='';foreach(str_split(base_convert($i++,10,4))as$d){$q.='ENWS'[$d];$f='132405213540402135510243'[$f+$d*6];$x-=--$d%2;$y-=~-$d%2;}if([$x,$y,$f]==[$a,$b,0])return$q;}}

Try it online!
-2 bytes thanks to @Kevin Cruijssen

$x-=~-$d%2;$y-=~-~-$d%2; can be $x-=--$d%2;$y-=~-$d%2; to save 2 bytes.

C (gcc), 266 236 bytes

-30 thanks to @ceilingcat

the formula is based on @Arnauld 's answer
x,y,L,i,F,G,P[98];O(I,M,N,j){if(F=I-L)for(j=0;j<4;O(I+1,F=j%2?M+2-j:M,G=j%2?N:N+3-j))P[I]=j++;else{for(i=L;i--;)F+=(P[i]&2^6)+(P[i]-~F)%3;if(F%6<1&x==M&y==N){for(;++i<L;)printf(L"ENWS"+P[i]);exit(0);}}}K(X,Y){x=X;for(y=Y;;L++)O(0,0,0);}

Try it online!
much faster but longer. Solves 20, 5 in 0.088s
#define Q for(i=0;i<L;i++
x,y,L,i,F,G,P[98];O(I,M,N){if(abs(x-M)+abs(y-N)<=L-I){if(I==L){F=0;Q)F+=(P[i]&2^6)+(P[i]+F+1)%3;if(F%6<1){Q)putchar("ENWS"[P[i]]);exit(0);}}else for(int j=0;j<4;j++){P[I]=j;F=M;G=N;if(j%2)G+=2-j;else F+=1-j;O(I+1,F,G);}}}K(X,Y){x=X;y=Y;for(;;L++)O(0,0,0);}

Try it online!
Prune at Manhattan distance between current location & destination > remaining steps
Usage: K(x, y)

can be called more than once 231 bytes

Wolfram Language (Mathematica), 147 bytes
x""<>StringPart["ENWS",1+SelectFirst[Join@@({0,1,2,3}~Tuples~#&/@Range@10),6∣Fold[#+#2~BitAnd~2~BitXor~6+Mod[#+#2+1,3]&,0,#]&&Total[I^#]==x&]]

Try it online!
You need to change 10 to a larger number to enable calculation for longer paths (and much slower).
Take complexes as input, e.g. 1+I as [1, 1].

IA-32 machine code, 161 bytes
Hexdump:
60 e8 0d 00 00 00 03 05 09 11 15 29 51 00 0f 17
65 77 57 5e 8b 46 0a 66 bb 6e 73 8b 7c 24 24 85
c9 79 04 f7 d9 86 c4 85 d2 79 04 f7 da 86 df 3b
ca 73 03 93 87 ca 83 f9 05 76 09 aa aa aa aa 83
e9 04 eb eb 8d 2c 11 2b ca 4a 79 15 83 f9 04 66
9c 74 03 88 1f 47 f3 aa 66 9d 74 3e 88 3f 47 eb
39 4a 79 26 83 f9 03 75 09 aa 88 1f 47 aa aa aa
eb 28 88 1f 47 49 79 04 88 27 47 41 e3 02 f3 aa
88 1f 47 aa 88 3f 47 aa eb 10 03 f1 8a 0c 96 50
d0 e9 0f 42 c3 aa 58 4d 75 f5 c6 07 00 61 c2 04
00

Assembly source (MS Visual Studio inline-assembler style):
    pushad;

    call skip0;
    _emit(0x03);
    _emit(0x05);
    _emit(0x09);
    _emit(0x11);
    _emit(0x15);
    _emit(0x29);
    _emit(0x51);
    _emit(0x00);
    _emit(0x0f);
    _emit(0x17);
    _emit('e');
    _emit('w');
    _emit(0x57);
skip0:
    pop esi;

    // ecx = x
    // edx = y
    mov eax, [esi + 10];    // al = 'e', ah = 'w'
    mov bx, 'sn';           // bl = 'n', bh = 's'
    mov edi, [esp + 0x24];  // edi = pointer to output

    test ecx, ecx;
    jns skip1;
    neg ecx;
    xchg al, ah;
skip1:

    test edx, edx;
    jns skip2;
    neg edx;
    xchg bl, bh;
skip2:
    ;// now there are no negative coordinates

myloop4:
    cmp ecx, edx;
    jae skip3;
    xchg eax, ebx;
    xchg ecx, edx;
skip3:
    ;// now x >= y

    cmp ecx, 5;
    jbe myloop4_done;

    stosb; // output 'e'
    stosb; // output 'e'
    stosb; // output 'e'
    stosb; // output 'e'
    sub ecx, 4;
    jmp myloop4;
myloop4_done:
    ;// now y <= x <= 5

    lea ebp, [ecx + edx];
    sub ecx, edx;

    dec edx;
    jns check1;

    // Processing y = 0
    cmp ecx, 4;
    pushf;
    je skip4;
    //     Processing y = 0, x != 4
    mov [edi], bl; // output 'n'
    inc edi;
skip4:
    rep stosb; // output 'eee...e'
    popf;
    je done;
    //     Processing y = 0, x != 4
    mov [edi], bh; // output 's'
    inc edi;
    jmp done;

check1:
    dec edx;
    jns do_n;

    // Processing y = 1
    cmp ecx, 3;
    jne skip6;
    // Processing y = 1, x = 4
    stosb; // output 'e'
    mov [edi], bl; // output 'n'
    inc edi;
    stosb; // output 'e'
    stosb; // output 'e'
    stosb; // output 'e'
    jmp done;
skip6:

    // Processing y = 1, x != 4
    mov [edi], bl; // output 'n'
    inc edi;
    dec ecx;
    jns skip7;
    mov [edi], ah; // output 'w'
    inc edi;
    inc ecx; // set ecx = 0
skip7:
    jecxz skip8;
    rep stosb; // output 'eee...e'
skip8:
    mov [edi], bl; // output 'n'
    inc edi;
    stosb; // output 'e'
    mov [edi], bh; // output 's'
    inc edi;
    stosb; // output 'e'
    jmp done;

    // Processing y > 1
do_n:
    add esi, ecx;
    mov cl, [esi + edx * 4];
myloopn:
    push eax;
    shr cl, 1;
    cmovc eax, ebx;
    stosb; // output 'e' or 'n'
    pop eax;
    dec ebp;
    jnz myloopn;

done:
    mov byte ptr [edi], 0;

    popad;
    ret 4;

It is a "prescriptive" algorithm - it doesn't search but generates the output using patterns which I found separately.
First of all, it transforms the input by reflections, such that 0 ≤ y ≤ x. The reflections are implemented by negations of x and y and some register swaps.
Then, it subtracts 4 from x repeatedly, until x ≤ 5. While doing this, transposing is sometimes necessary to keep 0 ≤ y ≤ x.
Afterwards, the following holds: 0 ≤ y ≤ x ≤ 5. This is a finite set of cases, further subdivided into y = 0, y = 1 and y > 1.

If y = 0:

If x ≠ 4, output n in the beginning and s at the end.
In any case, output e x times.

If y = 1:

If x = 4, the output is eneee.
If x = 1, the ouptut is nwnese
Otherwise, the ouptut is n(e...)nese - here e is repeated x-2 times.

If y = 2:
There are 10 cases:
x = 2 y = 2: nnee
x = 3 y = 2: nenee
x = 4 y = 2: neenee
x = 5 y = 2: neeenee
x = 3 y = 3: nenene
x = 4 y = 3: neenene
x = 5 y = 3: neeenene
x = 4 y = 4: nnnneeee
x = 5 y = 4: nnneneeee
x = 5 y = 5: nnneneneee

I encode them using 1 bit per character, n = 1, e = 0, starting from LSB. Their length is x + y, which makes decoding easy. Even though some of them contain more than 8 bits, the MSB are zero, so they all fit into 1 byte.
Also, because y ≤ x, some entries in the 4x4 table are unused. Two of them are adjacent, so I use them to store the bytes w and e there.

source: Stack Exchange

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

sort: votes


text:
Concentric rings on a snub square tiling
This challenge takes place on the snub square tiling.
Start by choosing any triangle, and color it \$c_1\$.
Next, find all tiles which touch this triangle at any vertex, and color them \$c_2\$. Next, find all tiles which share a vertex with any \$c_2\$-colored tile, and color these \$c_3\$.
Continue this process ad infinitum.
Illustration

Initial terms
The sequence begins
  a(1) = 1
  a(2) = 9
  a(3) = 21
  a(4) = 35

Notice:

a(1) = 1 corresponds to the red triangle;
a(2) = 9 corresponds to the number of tiles in the second, orange layer;
a(3) = 21 corresponds to the number of tiles in the third, green layer; and so on.

(Note, this sequence is now in the OEIS; OEIS sequence A296368 is closely related.)
Challenge
Your goal is to write a program that takes in a positive integer n and returns the number of tiles that are colored \$c_n\$, (i.e. the number of tiles in the \$n\$-th layer.) This is a code-golf challenge, so the shortest code in bytes wins.

This looks like a lion! +1

Can this be zero indexed?

@JoKing, I'd like to keep it one-indexed—partly because folks have already submitted solutions with that assumption.

Jelly, 8 bytes
’3cạ×ʋ12

Try it online!
How?
’3cạ×ʋ12 - Link: integer, n
’        - decrement              (n-1)                1   2   3   4   5   6   7  ...
      12 - twelve                 12                  12  12  12  12  12  12 12  ...
     ʋ   - dyad:
 3       -   three                3                    3   3   3   3   3   3   3  ...
  c      -   choose               3C(n-1)              1   3   3   1   0   0   0  ...
    ×    -   multiply             (n-1)*12             0  12  24  36  48  60  72  ...
   ạ     -   absolute difference  |3C(n-1)-(n-1)*12|   1   9  21  35  48  60  72  ...

Ah, cool that Jelly has a way to avoid duplicating ’. I still have no idea how any of it works =p

Yeah even with Lynn's excellent tutorial and its Chains section, it's still a tricky beast :)

Ruby, 26 bytes
->n{~-n*12-496/4**n%4+1/n}

Try it online!
Revised version adding 1/n and subtracting 496/4**n%4 to get the +1,-3,-3,-1 offset for the first 4 terms.
Ruby, 32 bytes
->n{n>4?~-n*12:[0,1,9,21,35][n]}

Try it online!
After 4, the sequence settles down to (n-1)*12. See diagram below (the equilateral triangles have been distorted into 45 degree isosceles triangles and the entire diagram rotated 45 degrees, but it remains topologically equivalent.)

Really nice job :D

Well done on finding a way to simplify the topology and providing a closed formula for n>4!

JavaScript (ES6), 23 bytes
Based on Level River St's answer.
n=>[1,5,13,7][--n]^n*12

Try it online!
How?
We compute \$(n-1)\times12\$ and adjust the first 4 values with a XOR.
$$\begin{array}{c|c}
n&1&2&3&4&5&6&7&8&9&10\\
\hline
(n-1)\times12&0&12&24&36&48&60&72&84&96&108\\
\hline
\text{XOR}&1&5&13&7&\color{grey}0&\color{grey}0&\color{grey}0&\color{grey}0&\color{grey}0&\color{grey}0\\
\hline
a(n)&1&9&21&35&48&60&72&84&96&108
\end{array}$$

05AB1E, 9 bytes
<©12*3®cα

Try it online! or try a test suite.
<           # input - 1
 ©          # save to register
  12*       # multiply by 12
      ®     # push the register
     3 c    # binomial coefficient(3, input - 1)
        α   # absolute difference

With 0-indexing, this would be 7 bytes:
12*3Icα

Python, 31 bytes
lambda n:n*12-11-(n>4or 5%-n%5)

Try it online!

APL (Dyalog Unicode), 14 bytesSBCS
12(|×-3!⍨⊢)-∘1

Try it online!
Direct translation of Jonathan Allan's Jelly answer. Even the code structure is the same. Jelly is a golfy descendant of APL; if you want to learn Jelly, learn APL first!
How it works
12(|×-3!⍨⊢)-∘1  ⍝ Monadic train, input: n
12(       )-∘1  ⍝ Pass on to the inner function with left←12 and right←n-1
    ×             ⍝ left × right
     -            ⍝ minus
      3!⍨⊢        ⍝ binomial(3, right)
   |              ⍝ absolute value of the above

Jelly, 15 9 bytes
’3cạ×12$Ʋ

Try it online!
A monadic link taking \$n\$ as its argument and returning \$a(n)\$.
Based on @LevelRiverSt’s clever Ruby answer so be sure to upvote that one too!
Thanks to @Grimmy for saving 6 bytes!
Explanation
 ’       | Subtract 1
       Ʋ | Following as a monad
3c       | - Number of ways of picking (n-1) items from 3
  ạ   $  | - Absolute difference from:
   ×12   |   - Multiply (n-1) × 12

Here’s 9 bytes

@Grimmy thanks! I’d missed that because of the difference for n=1 being -1, though of course with absolute difference that doesn’t matter.

@Grimmy I was trying to golf exactly that, and now managed it :)

brainfuck, 50 bytes
>>>>>>+<++<<----<+<,-[>++++++++++++[[>+<-]<]>>-]>.

Does i/o as raw byte values, like the others here.

You can remove leading >> by using the implementation available on TIO.

That's a nonstandard language extension that I'd like to see stamped out. I'm not a fan of the fragmentation of brainfuck into incompatible dialects, and I work against that where I can.

Perl 6, 26 bytes
{$_*12-[-1,3,3,1][$_]}o*-1

Try it online!
If this could be zero-indexed the o*-1 at the end can be removed. Returns (n-1)*12, offsetting the first 4 values.

Python 3, 40 36 bytes
lambda n:~-n*12-(*n*[0],1,3,3,-1)[4]

Try it online!

Python 3, 39 bytes
lambda n:n>4and~-n*12or[1,9,21,35][n-1]

Try it online!
Total rip of Level River St's answer so upvote him.

Python, 38 bytes
lambda n:n*12-11-([1]*n+[2,4,4,0])[-n]

Try it online!

J, 14 bytes
12(*|@-3!~])<:

Try it online!
A J port of Bubbler's APL answer, so it's also a port of Jonathan Allan's Jelly answer.

C (gcc), 34 33 32 bytes
Saved a byte thanks to Grimmy!!!
f(n){n=--n<4?"!)5C"[n]-32:n*12;}

Try it online!

32

@Grimmy Nice - takes care of all the n-1s with a decrement  up front. Thanks! :-)

brainfuck, 78 bytes
++++[->+++<]>>>+>--->--->-<<<<<<,-[->>>[+]<[->+<]<[->+>+<<]<[->+<]>]>>[->+<]>.

You can try it online over at TIO (the input is a line-feed (ascii 10) and the output is an l (ascii 108))
You can also try the verbose code at this online interpreter where input can be inserted as decimals, e.g. \6 gives 6 as input. After running, you can hit the "view memory" button and check the value of the output cell in bold, to ensure the result is right.

brainfuck, 61 bytes
,-[>++<-[>+++<-[>+++>++<<-[>+++>+<<-[>+++<-]]]]]>[>++++<-]>+.

Input/output as character codes (meta).
Try it online! or try it with decimal I/O.

Good work on this one!

Stax, 10 bytes
Å²@8Ω@╩vä3

Run and debug it

Rust - 52 bytes
let m=|n|(match n{1=>1,2=>9,3=>21,4=>35,_=>n}-1)*12;

oh gosh.. it loses even to Brainf***

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


text:
It's all about the sum of the digits
The sequence
Given an integer \$n>0\$, we define \$a(n)\$ as the lowest positive integer such that there exists exactly \$n\$ positive integers smaller than \$a(n)\$ whose sum of digits is equal to the sum of the digits of \$a(n)\$.
Edit: this sequence has since been published as A332046
First terms
  n | a(n) | sum of digits | matching integers
----+------+---------------+------------------------------------------------------
  1 |  10  |       1       | [1]
  2 |  20  |       2       | [2, 11]
  3 |  30  |       3       | [3, 12, 21]
  4 |  40  |       4       | [4, 13, 22, 31]
  5 |  50  |       5       | [5, 14, 23, 32, 41]
  6 |  60  |       6       | [6, 15, 24, 33, 42, 51]
  7 |  70  |       7       | [7, 16, 25, 34, 43, 52, 61]
  8 |  80  |       8       | [8, 17, 26, 35, 44, 53, 62, 71]
  9 |  90  |       9       | [9, 18, 27, 36, 45, 54, 63, 72, 81]
 10 | 108  |       9       | [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]
 .. |  ..  |      ..       | ..
 20 | 216  |       9       | [9, 18, 27, 36, 45, 54, 63, 72, 81, 90, ..., 207]
 .. |  ..  |      ..       | ..
 30 | 325  |      10       | [19, 28, 37, 46, 55, 64, 73, 82, 91, 109, ..., 316]
 .. |  ..  |      ..       | ..
 40 | 442  |      10       | [19, 28, 37, 46, 55, 64, 73, 82, 91, 109, ..., 433]
 .. |  ..  |      ..       | ..
 50 | 560  |      11       | [29, 38, 47, 56, 65, 74, 83, 92, 119, 128, ..., 551]

More examples
a(13) = 135
a(17) = 171
a(42) = 460
a(57) = 660
a(81) = 1093
a(82) = 1128
a(118) = 1507
a(669) = 9900
a(670) = 10089
a(1000) = 14552
a(5000) = 80292
a(10000) = 162085

As a side note, you may not assume that the sum of the digits may only increase. For instance, the sum of the digits for \$a(81)\$ is \$1+0+9+3=13\$, while the sum of the digits for \$a(82)\$ is \$1+1+2+8=12\$.
Rules

You may either:

take a 1-indexed integer \$n\$ and return \$a(n)\$
take a 0-indexed integer \$n\$ and return \$a(n+1)\$
take a positive integer \$n\$ and return the \$n\$ first terms
print the sequence indefinitely

This is code-golf!

A simple proof that $a_n$ is defined for any $n$: $10^n$ has digit sum of 1, and has exactly $n$ positive integers smaller than itself whose sum of digits is 1, namely $10^0 \cdots 10^{n-1}$.

Did you invent a(n)? I couldn't find it in https://oeis.org. That's an interesting function in order to troll "Continue the sequence" questions. What comes after 10, 20, 30, 40, 50, 60, 70, 80, 90? 108.

@EricDuminil Yes I invented it and I'm actually half-tempted to submit it on OEIS.

Sure, why not? One advantage is that you could hear from other possible definitions when people google 10, 20, 30, 40, 50, 60, 70, 80, 90, 108 or 80292, 162085.

@EricDuminil OEIS draft

It's all about the base.

Pyth, 12 bytes
f}hQ_XsjT;H1

Try it online!

f: Count up from 1 to find the first number such that:
X ... H1: Increment or insert the value 1 into the dictionary H at index
sjT;: sum of base ten digits of current number
_: values of dictionary
}hQ: check whether input + 1 is contained within.

The first time this is true, exactly input numbers must have the same digit sum as the current number, for the first time.

Gaia, 13 10 bytes
1⟨┅Σ¦ṅC=⟩#

Try it online!
Straightforward implementation.
Explanation:
1⟨	⟩#	| find the first 1 positive integers N where:
      C		| the count of
     ṅ		| the digital sum d(N)
  ┅Σ¦		| in the list [d(1)..d(N-1)]
       =	| is equal to the (implicit) input

Jelly, 10 bytes
D€§ċṪ$=ʋ1#

Try it online!
A monadic link taking an integer \$n\$ and returning \$a(n)\$.
Explanation
       ʋ1# | Find the first integer x where the following is true;
D€         | - Digits of 1..x
  §        | - Sum each
   ċṪ$     | - Count the number equal to the tail (after popping tail)
      =    | - Equal to (implicit original argument to link)

05AB1E, 10 bytes
∞.Δ1Ÿ1öć¢Q

Try it online!

Ah, I keep forgetting about 1ö being the non-vectorizing digit-sum! Apart from that it's similar as what I had before I saw your answer.

APL (Dyalog Unicode), 27 bytesSBCS
{⌈⌿+\∘.=⍨1⊥10⊥⍣¯1⍳20×⍵}⍳+∘1

Try it online!
How it works
{⌈⌿+\∘.=⍨1⊥10⊥⍣¯1⍳20×⍵}⍳+∘1  ⍝ Right argument: n
{                     }⍳+∘1  ⍝ Find the first index of n+1 from...
 ⌈⌿+\∘.=⍨1⊥10⊥⍣¯1⍳20×⍵       ⍝ ... the list of cumulative count of own digit sum (sort of)
                  20×⍵         ⍝ Practical upper bound 20×n (could also use theoretical 10*⍵)
                 ⍳             ⍝ Range: 1..20×n
           10⊥⍣¯1  ⍝ Extract decimal digits from each
         1⊥        ⍝ Sum the digits of each number
     ∘.=⍨    ⍝ Self outer product by equality
   +\        ⍝ Cumulative sum in row direction; cumulative counts of own digit sum
 ⌈⌿          ⍝ Maximum in column direction; cumulative maximum of cumulative count

Python 2, 71 bytes
f=lambda n,x=[0]:x.count(x[-1])+~n and-~f(n,x+[sum(map(int,`len(x)`))])

Try it online!

Charcoal, 16 bytes
Ｗ⁻№υΣＬυθ⊞υΣＬυＩＬυ

Try it online! Link is to verbose version of code. Explanation:
Ｗ⁻№υΣＬυθ

Count the number of entries in the predefined list that are equal to the digital sum of the length of the list and repeat while that does not equal the input...
⊞υΣＬυ

... append the digital sum of the length of the list to the list.
ＩＬυ

Output the length of the list.

Ruby, 55 bytes
->n,r=0,*w{w<<k=(r+=1).digits.sum until w.count(k)>n;r}

Try it online!

Python 2, 92 93 bytes
f=lambda n,x=1:n==sum(sum(map(int,`i`))==sum(map(int,`x`))for i in range(x))and x or f(n,x+1)

Try it online!
All I can get for now but I suspect someone much more competent than I am could do much better.

Because you define the function recursively, you have to give it a name, so you have 94 bytes :/ at least for now :)

And then 93 bytes if you put the n== in the beginning, which allows for the next keyword to come closer to the ).

I see and thanks @RGS

JavaScript (Node.js), 68 67 63 bytes
-1 -5 byte thanks Arnauld
n=>(F=z=>F[g=eval([...z+''].join`+`)]^n?F(-~z,F[g]=-~F[g]):z)``

Try it online!

Java 8, 138 bytes
n->{for(int a=9,c,i;;a++){for(c=i=0;++i<a;)c+=(i+"").chars().map(q->q-48).sum()==(a+"").chars().map(q->q-48).sum()?1:0;if(c==n)return a;}}

Try it online.
Explanation:
n->{               // Method with integer as both parameter and return-type
  for(int a=9,     //  Integer `a_i`, starting at 9 (since a(1)=10)
          c,       //  Count-integer
          i;       //  Loop-integer
      ;            //  Loop indefinitely:
       a++){       //    After every iteration: increase `a_i` by 1
    for(c=i=0;     //   Reset both the count and loop integers to 0
        ++i<a;)    //   Inner loop `i` in the range (0,a):
      c+=          //    Increase the count by:
         (i+"").chars().map(q->q-48).sum()
                   //     If the digit-sum of `i`
           ==(a+"").chars().map(q->q-48).sum()?
                   //     equals the digit-sum of `a_i`:
            1      //      Increase the count by 1
           :       //     Else:
            0;     //      Leave the count the same by increasing with 0
    if(c==n)       //   If the count equals the input integer `n` after the inner loop:
      return a;}}  //    Return `a_i` as our `a(n)` result

PowerShell, 74 72 bytes
$a=@{}
1.."$args"|%{for(;$_-$a.(++$i|%{"$_"[0..9]-join'+'|iex})++){}}
$i

Try it online!
2^31 = 2147483647, so the expression "$_"[0..9] works with any Powershell [int] > 0.

Wolfram Language (Mathematica), 92 or 113 bytes
Brute force short version:
(t=Total@IntegerDigits@#&;Catch@Do[If[Count[Range@(k-1),x_/;t@x==t@k]==#,Throw@k],{k,∞}])&

Try it online!
Time- and memory-optimized version. Print table of values up to given number:
(n=0;a=<||>;r={};Do[While[FreeQ[a,i+1],a[k]=Lookup[a,k=Total@IntegerDigits@++n,0]+1];AppendTo[r,{i,n}],{i,#}];r)&

Try it online!
Ungolfed self-explained:
next = 0; assoc = <||>;
max = 30; result = {};
Do[
 While[FreeQ[assoc, n + 1],
  next += 1;
  key = Total@IntegerDigits@next;
  assoc[key] = Lookup[assoc, key, 0] + 1
  ];
 AppendTo[result, {n, next}]
 , {n, max}]; result

Scala, 115 bytes
Golfed version. Try it online!
def f(n: Int)={var r,k=0;var w=List[Int]();do{r+=1;k=r.toString.map(_.asDigit).sum;w:+=k}while(w.count(_==k)<=n);r}

Ungolfed version. Try it online!
object RubyToScala {
  def main(args: Array[String]): Unit = {
    println(f(1))
    println(f(2))
    println(f(3))
    println(f(30))
    println(f(50))
    println(f(1000))
  }

  def f(n: Int): Int = {
    var r = 0
    var w = List[Int]()
    var k = 0
    do {
      r += 1
      k = r.toString.map(_.asDigit).sum
      w :+= k
    } while (w.count(_ == k) <= n)
    r
  }
}

Japt, 14 bytes
@¶XÇìxÃè¶Xìx}a

Try it

Thunno 2, 6 bytes
ƘRʂṪc=

Try it online!
Explanation
ƘRʂṪc=  # Implicit input
Ƙ       # Find the first positive integer, n, where:
 R      #  Push [1..n]
  ʂ     #  Get the digital sum of each number
   Ṫ    #  Remove the last item and push it separately
    c   #  Count the occurrences of this in the list
     =  #  Does this equal the input?

Lua, 93 bytes
t={}n=0repeat m=0n=n+1(n..''):gsub('.',load'm=m+...')t[m]=(t[m]or 0)+1until...+0<t[m]print(n)

Try it online!
Ungolfed version:
t={}n=0
repeat
    m=0 n=n+1                        --Increment n, set m to 0
    (n..''):gsub('.',load'm=m+...')  --Sum digits of n, store in m
    t[m]=(t[m]or 0)+1                --Increment t[m], or set to 1 if null
until...+0<t[m]                      --If input < t[m], stop loop
print(n)


text:
Computing a specific coefficient in a product of polynomials
Generator functions
This gives the context for why this challenge came to life. Feel free to ignore.
Generator functions are a nice way of encoding the solution to a problem of combinatorics. You just write some polynomials, multiply them and then your solution is the coefficient of one of the terms.
For example, how many bouquets of 10 flowers can you make if you want to use 3 or more dandelions, really want to use an even number of lilies and cannot afford more than 5 roses? Easy, just find the coefficient of x^10 in
$$(x^3 + x^4 + x^5 + x^6 + x^7 + x^8 + x^9 + x^{10})\times(1 + x^2 + x^4 + x^6 + x^8 + x^{10})\times(1 + x + x^2 + x^3 + x^4 + x^5)$$
Task
Compute a specific coefficient from a product of polynomials.
Example
If k = 3 and the product given is "(1 + 3x + 5x^2)(5 + 3x + 2x^2)" then we have
$$(1 + 3x + 5x^2)(5 + 3x + 2x^2) = (5 + 3x + 2x^2) + (15x + 9x^2 + 6x^3) + (25x^2 + 15x^3 + 10x^4) = 5 + 18x + 36x^2 + 21x^3 + 10x^4$$
And because k = 3 we get 21.
Input
You receive an integer k and several polynomials. k is always a non-negative integer, and so are the coefficients and the exponents in the input polynomials.
k may be larger than the combined degree of all the input polynomials.
The input polynomials can be in any sensible format. A few suggestions come to mind:

A string, like "(1 + 3x + 5x^2)(5 + 3x + 2x^2)"
A list of strings, like ["1 + 3x + 5x^2", "5 + 3x + 2x^2"]
A list of lists of coefficients where index encodes exponent, like [[1, 3, 5], [5, 3, 2]]
A list of lists of (coefficient, exponent) pairs, like [[(1, 0), (3, 1), (5, 2)], [(5, 0), (3, 1), (2, 2)]]

An input format must be sensible AND completely unambiguous over the input space.
Test cases
0, "(1 + 3x + 5x^2)(5 + 3x + 2x^2)" -> 5
1, "(1 + 3x + 5x^2)(5 + 3x + 2x^2)" -> 18
2, "(1 + 3x + 5x^2)(5 + 3x + 2x^2)" -> 36
3, "(1 + 3x + 5x^2)(5 + 3x + 2x^2)" -> 21
4, "(1 + 3x + 5x^2)(5 + 3x + 2x^2)" -> 10
5, "(1 + 3x + 5x^2)(5 + 3x + 2x^2)" -> 0
6, "(1 + 2x^2 + 4x^4)(2x^2 + 4x^4 + 8x^8)(4x^4 + 8x^8 + 16x^16)" -> 8
7, "(1 + 2x^2 + 4x^4)(2x^2 + 4x^4 + 8x^8)(4x^4 + 8x^8 + 16x^16)" -> 0
8, "(1 + 2x^2 + 4x^4)(2x^2 + 4x^4 + 8x^8)(4x^4 + 8x^8 + 16x^16)" -> 32
9, "(1 + 2x^2 + 4x^4)(2x^2 + 4x^4 + 8x^8)(4x^4 + 8x^8 + 16x^16)" -> 0
17, "(1 + 2x^2 + 4x^4)(2x^2 + 4x^4 + 8x^8)(4x^4 + 8x^8 + 16x^16)" -> 0
18, "(1 + 2x^2 + 4x^4)(2x^2 + 4x^4 + 8x^8)(4x^4 + 8x^8 + 16x^16)" -> 160
19, "(1 + 2x^2 + 4x^4)(2x^2 + 4x^4 + 8x^8)(4x^4 + 8x^8 + 16x^16)" -> 0
20, "(1 + 2x^2 + 4x^4)(2x^2 + 4x^4 + 8x^8)(4x^4 + 8x^8 + 16x^16)" -> 384

Do we need to handle cases where k is greater then the combined degrees of the input polynomials?

@ChasBrown the 6th test case shows you do, yes.

Is [5, 3, 1] (reversed version of [1, 3, 5]) for 5x^2+3x+1 allowed? Some languages would prefer this format.

Can we take k as 1-indexed?

@tsh this is allowed, yes

@NickKennedy for some reason, I don't feel very comfortable accepting that... :/

@RSG I think the reason is that k has a definite meaning (degree of coefficient), it’s not just an index

@RGS I just want to thank you for teaching me a new way to solve combinatorics problems today

@Wboy glad you enjoyed it ^^

J, 21 19 18 bytes
{ ::0[:+//.@(*/)/>

Try it online!
-1 byte thanks to FrownyFrog
J has a nice geometric idiom for multiplying polynomials, which we
represent as lists of coefficients, with explicit zeroes where needed:
+//.@(*/)

Let's see how this works using the example:
1 3 5 +//.@(*/) 5 3 2

First it creates a multiplication table */:
 5  3  2
15  9  6
25 15 10

And @: then it computes the sums along each diagonal +//. using the Oblique /. adverb:

This works because moving down a diagonal is equivalent to decrementing the
power of one x while incrementing the power of another, meaning that the
numbers along a diagonal represent all the components of some a factor x^n
for some n.
The rest of the solution is just mechanics for the problem as stated:
{ ::0[: <polynomial idiom> />

Since we can have an arbitrary number of polynomials, we represent them as a list of boxes (each box containing one polynomial) and take that as the right arg.  The left arg is the index we want.
Now { ::0 ... is a dyadic hook asking for the index specified by the left arg, after transforming the right arg by everything in ....  And, if you can't find the index, return 0 ::0.
Finally [: <polynomial idiom> /> says to first unbox > the right arg lists, filling any missing coefficients with 0.  Then reduce / that list using the polynomial multiplication idiom.

@ works without the colon.

Nice, thank you sir

MATL, 18 15 bytes
Y:iWB1G"Y+]2GQ)

Input is a cell array of numerical vectors with the polynomial coefficients, followed by an integer (k).
Try it online! Or verify all test cases.
Explanation
Polynomial multiplication is convolution of their coefficients. And

convolution is the key to success

Y:     % Implicit input: cell array of numeric vectors. Unbox into its constituents
iWB    % Input k. 2 raised to that. Convert to binary. Gives [1 0...0] with k zeros
1G     % Push first input (cell array of numeric vectors) again
"      % For each. This runs n iterations, where n is the number of polynomials
  Y+   %   Convolution
]      % End
       % The first convolution uses one of the polynomials in the input and the
       % [1 0...0] vector. This doesn't alter the actual coefficients, but adds k
       % zeros. Thus the final product polynomial will contain k zeros after the
       % highest-degree nonzero coefficient. This ensures that k doesn't exceed
       % the number of existing coefficients
2G     % Push second input (k) again
Q      % Add 1
)      % Index. This retrieves the k-th degree coefficient. Implicit display

"convolution is the key to success" - thanks, you saved me 10 of my 17 bytes!!

@Jonathan Quote is from flawr :-)

Sure, but your post is what saved me bytes.

Polynomial multiplication is convolution of their coefficients Which general mathematical definition of convolution are we using here?

I'm using this definition (is there any other definition for discrete convolution?)

Haskell, 42 bytes
n%((h:t):l)=h*n%l+(n-1)%(t:l)
0%[]=1
_%_=0

Try it online!
An infix function taking a number n and a lists of lists of coefficients with lowest exponents first.
Here's the key recursive idea. Instead of actually multiplying out the polynomials to get one big polynomial, we only just try to extract the coefficient. Algorithmically, this isn't faster than multiplying out coefficient, but in terms of brevity, it saves us from needing to product lists for the intermediate or final product.
When multiply \$p(x)\cdot q(x)\$, we can split up \$p(x)\$ into its constant and remaining terms as \$p(x)=p_0(x) +x \cdot p_{\mathrm{rest}}(x)\$. Then, the coefficient of \$x^n\$ in \$p(x)\cdot q(x)\$ can be written as:
$$
\begin{align}
[p(x)\cdot q(x)]_n &= [(p_0 +x \cdot p_{\mathrm{rest}}(x)) \cdot q(x)]_n \\
&= [p_0 \cdot q(x)]_n + [x \cdot p_{\mathrm{rest}}(x) \cdot q(x)]_n \\
&= p_0 \cdot q(x)_n + [p_{\mathrm{rest}}(x) \cdot q(x)]_{n-1} \\
\end{align}
$$
We can continue expanding this out recursively until we get \$p=0\$, where the remaining result is zero. If \$q(x)\$ is itself expressed as a product of polynomials, we continue to extract coefficients from there. The base case is that the empty product is \$1\$, so its \$x^0\$ coefficient is \$1\$ and the rest are zero.

Just to be sure, you are defining % as an infix function, right? Also, I liked your recursive approach.

@RGS Yes, exactly.

Mathematica, 20 bytes
A nice benchmark for other answers:
Coefficient[#2,x,#]&

Takes the symbolic expressions as input.
You can try it online!

Jelly,  22 17  7 bytes
-10 bytes by realising I'd implemented convolution - go upvote Luis Mendo's MATL answer too, as that was what made me realise this.
æc/ṫ‘}Ḣ

A dyadic link accepting a list of coefficient lists on the left and the exponent on the right.
Try it online! Or see the test suite.
How?
æc/ṫ‘}Ḣ - Link: list of lists, Ps; integer, E
  /     - reduce (Ps) by:
æc      -   convolution
     }  - use right argument (E) for:
    ‘   -   increment -> E+1
   ṫ    - tail from (1-indexed) index (E+1)
      Ḣ - head (if given an empty list yields 0)

The 17 (without the convolution atom) was:
×€Œd§ṙLC${Ṛð/ṫ‘}Ḣ

Isn't there an elegant way to gracefully return 0 when the exponent is too high? :/

@RGS I've found a much more elegant way to combine the indexing and the maximal exponent issue (tail from index exponent+1 then take the head, since head for an empty list yields zero)

this answer is 3x shorter! Well golfed :D

Python, 67 bytes
f=lambda n,p,*q:p>[]and(f(n,*q)if q else n==0)*p[0]+f(n-1,p[1:],*q)

Try it online!
Takes input like f(3,[1,2,3],[4,5,6]), with the polynomials as separate arguments. The idea for the recursion if the same as in my Haskell answer. But, since Python doesn't have as nice pattern matching, we need to check for empty lists explicitly.

Husk, 18 16 bytes
!→⁰+→G(mΣ∂Ṫ*)²∞0

First Husk answer. This took so much longer to complete than I thought it would. I'm glad there is a tutorial with good explanation of how the input-order and super-numbers work, otherwise I had to give up. I never programmed in Haskell, and maybe I'm just too used to the left-to-right stack-based 05AB1E, but Husk isn't exactly straight-forward due to its strong-typed nature and right-to-left execution (including input-arguments) imho..
But, it works, which is what counts in the end. :)
First input-argument is a list of lists of coefficients where index encodes exponent, like the third input example in the challenge description. Second argument is the coefficient integer \$k\$.
Try it online.
Explanation:
             ²    # Use the first argument,
     G(     )     # and left-reduce it by:
          Ṫ       #  Apply double-vectorized:
           *      #   Multiply
                  #  (This basically results in the multiplication table of the lists)
         ∂        #  Take the diagonals of this multiplication table
       m          #  Map over these diagonal-lists:
        Σ         #   And sum each together
    →             # Only leave the last list after the reduce-by
              ∞0  # Push an infinite list of 0s: [0,0,0,...]
   +              # Merge the two lists together
  ⁰               # Push the second argument `k`
 →                # Increase it by 1 (since Husk uses 1-based indexing instead of 0-based)
!                 # And use it to index into the list we created
                  # (after which the result is output implicitly)

Great work on this!

@RGS I'm glad I got it's working in the end. I kept getting the Could not infer valid type for program error almost every step of the way, haha. I should have read that tutorial more thoroughly sooner though, bit my own fault. At first I tried to use implicit inputs, which works with a single argument. Took me a while to realize only the even superscript digits ⁰²⁴⁶⁸ are used to get arguments (odd ones are used to push an argument twice), and also in reversed order.. So with my two argument program, ² is the first argument and ⁰ the second. Ah well..

if you didn't know husk, why did you go for it?

@RGS To try something new. :) And I remember Husk had a 1-byte diagonals builtin, so I figured it would be pretty short using a rather similar approach as the J answer.

05AB1E, 32 24 23 bytes
Å»δ*εā_«N(._}øO}θIÅ0«Iè

Definitely not the right language to use for this challenge (no builtins for convolution, polynomials, getting all diagonals of a matrix, etc.).. But with some -rather long- workarounds, it still works (although is too slow for the last test cases).
Input as a list of list of coefficients where index encodes exponent, as well as the integer \$k\$ as second input.
Inspired by @Jonah's J answer.
-8 bytes by porting two approaches I've used in my Husk answer.
Try it online or verify some more test cases (outputs all coefficients without the indexing part).
Explanation:
Å»        # Left reduce the (implicit) input-list of lists of integers by:
          #  1) Calculate the multiplication table of the current two lists:
  δ       #   Apply double-vectorized:
   *      #    Multiply
          #  2) Take the sums of each diagonal:
  ε       #   Map each inner list to:
   ā      #    Push a list in the range [1,list-length] (without popping the list itself)
    _     #    Convert each to 0, so we'll have a list of 0s of the same length
     «    #    Append this list of 0s to the current list
      NF  #    Loop the 0-based map-index amount of times:
        Á #     And rotate the current list that many times towards the right
  }}      #   End the loop and map
    ø     #   Zip/transpose; swapping rows/columns
          #   (We now have a list of all diagonals)
     O    #   And take the sum of each inner list
}θ        # After the reduce-by is done, pop and push the final resulting list
  ∞_«     # Append an infinite amount of trailing 0s
     Iè   # And then use the second input to (0-based) index into this list
          # (after which the result is output implicitly)

Good job nonetheless :D

Python 2, 139 131 bytes
lambda k,L:sum(reduce(lambda a,(i,c):a*c[i],zip(p,L),1)for p in product(*map(range,map(len,L)))if sum(p)==k)
from itertools import*

Try it online!
Takes as inputs k and then polynomials as a list of lists of coefficents [c0, c1, c2, ...]. Forms all tuples of indexes into the polynomials that sum to the desired coefficent; and then sums up the products of the corresponding coefficients.

JavaScript (Node.js), 55 bytes
f=(k,[p,...t],s=0)=>p?p.map((n,i)=>s+=f(k-i,t)*n)&&s:!k

Try it online!
The first argument is k. The second argument is "a list of lists of coefficients where index encodes exponent", like [[1, 3, 5], [5, 3, 2]].

51

Jelly, 19 15 bytes
×þŒJ§SƙFƲ¥/ṫ‘}Ḣ

Try it online!
A dyadic link taking k as the left argument and the list of polynomials as a list of lists of coefficients as the right argument. Returns an integer. If k could be 1-indexed, ‘} could be deleted for 13 bytes.
Adapted to use @JonathanAllan’s revised method for dealing with larger k; be sure to upvote his (still shorter) answer too!

R, 68 bytes
function(P,k)Re(Reduce(function(x,y)convolve(x,y,,"o"),P,!0:k)[k+1])

Try it online!
Convolution is the key to success here, too, since it's a port of Luis' answer.
Takes input as a list() of vectors c() of coefficients in decreasing order, because R's convolve documentation says:

Note that the usual definition of convolution of two sequences x and y is given by convolve(x, rev(y), type = "o").

Thanks for your R submission! Waiting for your R submission in the mirror challenge about division!

Pari/GP, 29 bytes
f(k,p)=polcoeff(vecprod(p),k)

Try it online!

Good job on this one! +1

Sledgehammer, 6 bytes
⣈⠲⡎⡒⢢⣑

Only works in the interactive app (that requires excessive amounts of tinkering to get it to actually decompress the Braille code itself, but it's possible), because of a bug where the console app doesn't call postprocess and ends up replacing all occurrences of #, #1, #2, ## by s1, s2, s3, ss1.
Accepts input as, for example, {"(1 + 2x1^2 + 4x1^4)(2x1^2 + 4x1^4 + 8x1^8)(4x1^4 + 8x1^8 + 16x1^16)", 20} - x1 is the variable the first undefined variable used gets replaced with.
Obtained from the Mathematica code Coefficient[ToExpression@#, z, #2] (where ToExpression is eval and Coefficient simply gets the right coefficient, and z gets replaced by x1 as part of the compression).

Itr, 9 bytes
#RC*µS«#@
Input: nonempty list of polynomials (given as coefficient vectors) followed by index of coefficient that should be computed
Does not work if input list is empty
online interpreter
Explanation
#          ; read the list of polynomials
 R     «   ; reduce with
  C*µS     ; polynomial multiplication
  C*       ; go through the diagonals of the Cartesian product, multiplying the two elements in the pairs
    µS     ; sum up the diagonals
        #@ ; get the specified coefficient
           ; implicit output

Itr, 10 bytes
Also works for empty input list
1#MC*µS«#@
Input: list of polynomials (given as coefficient vectors) followed by index of coefficient that should be computed
Explanation
1           ; push 1
 #          ; read the list of polynomials
  M     «   ; for polynomial in the list
   C*µS     ; multiply that polynomial with the top stack value
         #@ ; get the specified coefficient
            ; implicit output

Itr, 8  bytes (only works for 2 inputs)
##C*µS#@
Input: two list of coefficients for the polynomials followed by the index of the coefficents
online interpreter
Explanation
##       ; read the two coefficient lists for standard input
  C*µS   ; multiply them as polynomials
  C*     ; go through the diagonals of the Cartesian product, multiplying the two elements in the pairs
    µS   ; sum up the diagonals
      #@ ; get int specified coefficient
         ; implicit output

The input may contain more than two polynomials.

K (ngn/k), 39 bytes
{0^({.+/'(*/x@'i)@=+/i:!#'x:(x;y)}/y)x}

Try it online!

Charcoal, 52 bytes
≔⟦Ｅ²ι⟧ζＦη«≔⟦⟧υＦιＦζ⊞υＥκ⎇ν×μ§λ¹⁺μ§λ⁰≔υζ»Ｉ∨ΣＥΦυ⁼§ι⁰θ⊟ι⁰

Try it online! Link is to verbose version of code. Takes input using the last suggestion but with the exponent first, then the coefficient. Explanation:
≔⟦Ｅ²ι⟧ζ

Initialise a variable to the polynomial 1.
Ｆη«

Loop over the input polynomials.
≔⟦⟧υ

Accumulate terms in a temporary variable.
ＦιＦζ

Loop over the Cartesian product of both sets of terms.
⊞υＥκ⎇ν×μ§λ¹⁺μ§λ⁰

Multiply the coefficients and add the exponents.
≔υζ

Move the resulting terms back to the original variable. (Charcoal doesn't have any flattening operators, and this is the golfiest way of flattening manually.)
»Ｉ∨ΣＥΦυ⁼§ι⁰θ⊟ι⁰

Filter for the terms with the desired exponent and sum the coefficients, unless there weren't any, in which case the result is 0.

Brachylog, 16 bytes
⟨∋ᵐ{tᵐ+}⟩ᶠhᵐ²×ᵐ+

Try it online!
Takes input as a list of lists of [coefficient, exponent] pairs, paired with k. Could be trivially modified to accept index-as-exponent coefficient lists by replacing ∋ with i, which is in fact what I did originally before I made an error writing out the test cases and switched for my own convenience.
⟨       ⟩           Call the first element of the input L and the last element k.
         ᶠ          Find every
 ∋                  selection of a [coefficient, exponent] pair
  ᵐ                 from each polynomial in L
   {   }            such that k is
      +             the sum of
    tᵐ              the exponents.
          hᵐ²       Extract the coefficients from each selection,
             ×ᵐ     multiply the coefficients extracted from each selection,
               +    and output the sum of the products.

{⟨∋ᵐ{tᵐ+}⟩hᵐ×}ᶠ+ is an equally valid solution at the same length, but I'm not sure I remember ever superscripting ᵐ before this, so I'm just going with the version that does that.


text:
Solve a meta-knowledge puzzle
Alice and Bob are perfect logicians trapped on an island with a puzzle generator. Although they can instantly solve the Riemann hypothesis and P=NP just by thinking about it, rather than doing anything useful, they amuse themselves by giving each other puzzles. The setup is as follows: a positive integer n is chosen by the puzzle generator, and is told to Alice and Bob. The puzzle generator also chooses a secret integer k, with 0 <= k < n. Next, the puzzle generator gives information about k to Alice and Bob in alternating turns. Whenever either one learns k, they immediately yell out "I know the number!" Furthermore, Alice and Bob both know this setup. Your task is, given the puzzle generator's output, determine when each one learns the number, if they ever do.
Input
You will receive n, k and a list of list of integers, with each list being length n. These lists are all public knowledge and indicate what the person would have received for every hypothetical value of k. Only the person whose turn it is actually receives the hint (the kth value of the array), but both players know what hint would have been received for any particular value of k. The first clue is given to Alice, the next to Bob, then Alice etc. An example is more illuminating than text:
n=5 k=0 [[1, 1, 2, 2, 2], [1, 2, 1, 1, 1], [0, 0, 0, 0, 0]] --> (2, 2)

Let's walk through the example. Alice first receives the number 1, because k=0 and the 0th element of [1, 1, 2, 2, 2] is 1. Both Alice and Bob receive the information about what Alice would have gotten had k been something else, so Alice now knows that either k=0 or k=1 and Bob knows that Alice knows whether k=0 or 1 or k=2, 3, or 4. Since Alice doesn't yet know k, she says nothing.
Next, Bob receives the number 1, because k=0. Thus, Bob learns that k=0, 2, 3, or 4. In addition, the fact that Bob says nothing lets Alice rule out the possibility that k=1, since if k=1, Bob would have gotten 2 and would have learned it, so now Alice knows that k=0 and says that she knows k.  Bob knows that if k=2, 3, or 4, this would not be possible, because the fact that he said nothing only rules out k=1 for Alice, which she would have already ruled out anyway. Thus, Bob also learns that k=0. Thus, they both require 2 clues to learn k, so the output is (2, 2). Note that all clues after both Alice and Bob learn k don't matter; in particular, [0, 0, 0, 0, 0] doesn't give any information anyway, but regardless of what it is, you can essentially ignore it.
Output
Output or return two integers, the number of clues for Alice to learn k and the number of clues for Bob to learn k respectively. In the special case where n=1, the output is always (0, 0) since both Alice and Bob immediately know, without any clues, that k=0 just upon learning n. If one of the two never learns k, output -1, Infinity, None, NaN, or something else that makes it clear that they do not learn k.
Your code only has to work in theory; if in practice it results in a Stack Overflow error, that is fine, as long as you can show that your code would work given unlimited resources and an infinite call stack size.
Test cases
n=2 k=1 [[0, 1], [1, 1], [0, 0], [1, 0]] --> (1, 4)
n=3 k=1 [[0, 1, 1], [0, 1, 1], [1, 2, 2]] --> (-1, -1)
n=5 k=2 [[1, 1, 2, 2, 2], [1, 1, 1, 2, 2], [1, 1, 3, 1, 2]] --> (3, 3)
n=4 k=0 [[0, 1, 2, 3], [0, 0, 0, 0], [0, 0, 0, 0]] --> (1, -1)
n=6 k=5 [[0, 1, 1, 1, 1, 1], [1, 0, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1], [1, 1, 1, 0, 1, 1], [1, 1, 1, 1, 0, 1]] --> (5, -1)
n=5, k=2, [[1, 1, 2, 2, 2], [1, 2, 2, 3, 3]] -> (2,2)

That last one is a bit tricky so here's a step-by-step: First, Alice receives 2, so she knows either k=2, k=3, or k=4. Then, on the second step, Bob learns that either k=1 or k=2. Since he doesn't know what it is, he says nothing, so Alice learns that k is not 0, and moreover, Bob now knows Alice knows this. However, Alice still doesn't say anything (in fact she already knew that k was not 0). The fact that Alice doesn't say anything lets Bob eliminate the case k=1, since if k=1, Alice would have received 1 as her first input, so eliminating k=0 would let her know that k=1. Hence, Bob knows that k=2, and says so. Now, Alice knows that what just happened is consistent with k=2. Is it consistent with k=3 or k=4? If k=3 or k=4, Bob would have gotten 3 as his clue, and there haven't been any clues so far that distinguish between k=3 and k=4 for anyone, so Bob couldn't know which one it is. Therefore, Alice also learns that k=2.
This is code golf, so shortest code wins!

Maybe you mean this: n is made public to all at the start; and k is hidden to all. On each turn, both players are shown the next list in the lists of lists for as many turns as are allotted (which is why there are more than two such lists); but only the person whose turn it is is given the 'hint', which is the value of the k-th element of that list. That would explain why Alice knows k in {0,1}, but Bob only knows that either k in {0,1} or k in {2,3,4}. Is that correct?

@ChasBrown Yes exactly. I updated the question a little, is it a bit more clear?

@Arnauld afaict Bob can figure it out after hearing Alice say she knows the number, so the output should be (3, 3).

Suggested test case: n=5, k=2, [[1, 1, 2, 2, 2], [1, 2, 2, 3, 3]] -> (2,2). On the 2nd turn, Alice learns that $k\neq0$ because Bob says nothing. Bob then learns that $k\neq1$ because Alice doesn't say she knows the answer once she knows that $k\neq0$. So Bob figures out that $k=2$ and says he knows the answer. Finally, Alice says she knows the answer as well, because that was the only way for Bob to find it.

BTW: It might be a bit clearer if each player explicitly says either I know or I don't know rather than not saying anything. In the above example of mine, the sequence for the 2nd turn is "Bob: I don't know. Alice: I don't know. Bob: I know! Alice: I know!".

@Arnauld Thanks, I was going for something like that in the last test case, but didn't quite know how to make it work.

JavaScript (ES7), 300 bytes
Takes input as (n, k, clues). Returns a pair in the format used in the challenge.
(n,k,a)=>n>1?a.map((c,t)=>[...m,...m].map((_,p)=>m.map(M=m=>!(v=m[p])|v&~-v?0:m[M|=v,p]=0,(x=~R[p&=1]|!(v=m[k][p])|v&~-v)?0:R[p]=t+1)|x?m.map(m=>m[p^1]&=~M):M&~-M&m[k][p^=1]?0:m[k][p]&=M,m.map((m,i)=>m[t&1]&=c.map(o=(v,j)=>o|=(v==c[i])<<j)|o)),m=[...Array(n)].map(_=>[x=2**n-1,x]),R=[-1,-1])&&R:[0,0]

Try it online!
How?
We first build an array \$m[\;]\$ of \$n\$ pairs of bitmasks:
m = [...Array(n)].map(_ => [x = 2**n - 1, x])

The bitmask \$m[i][p]\$ represents the possible answers from the perspective of player \$p\$, assuming that the identifier of the \$i\$-th clue was received so far.
In the main loop, we iterate on each list \$c[\;]\$ of clues at position \$t\$ and then \$n\$ times on each player \$p\$, alternately:
a.map((c, t) => [...m, ...m].map((_, p) => ...))

For each list of clues, we update \$m[\;]\$ for the player that will receive the clue at this turn:
m.map((m, i) =>
  m[t & 1] &=
    c.map(o = (v, j) => o |= (v == c[i]) << j) | o
)

For each player iteration, we test:

whether there's only one possible remaining answer given what was actually received (i.e. from this player's perspective)
whether there would be only one possible remaining answer if another clue was received so far (i.e. from the other player's perspective)

This is performed in the following loop:
m.map(M = m =>
  !(v = m[p]) | v & ~-v ?
    0
  :
    m[M |= v, p] = 0,
  (x = ~R[p &= 1] | !(v = m[k][p]) | v & ~-v) ?
    0
  :
    R[p] = t + 1
)

If the current player doesn't say that he knows the answer (\$x\neq0\$), we remove all hypotheses where an answer is found at this point from the bitmasks of the other player:
m.map(m => m[p ^ 1] &= ~M)

If the current player says he knows the answer (\$x=0\$), we update the bitmask of the other player accordingly:
M & ~-M & m[k][p ^= 1] ?
  0
:
  m[k][p] &= M

Python3, 956 bytes:
E=enumerate
def f(n,k,h):
 m,o,c,r,I=[[],[]],[[],[]],0,[-1,-1],[[],[]]
 while h:
  if-1not in r:return r
  H=h.pop(0);V=[i for i,a in E(H)if a==H[k]and i not in I[c%2]and(m[c%2]==[]or i in m[c%2])];I[c%2]+=[i for i in m[c%2]if i not in V];m[c%2]=V;d={}
  for i,a in E(H):d[a]=d.get(a,[])+[i]
  if r[not c%2]==-1:o[not c%2]=[*d.values()]
  A,F,P=0,1,not c%2
  if len(m[c%2])==1 and r[c%2]==-1:r[c%2]=c+1;A=1
  while F:
   F=0
   if A==0:
    for i in o[P]:
     if len(i)==1:
      m[P]=[j for j in m[P]if j!=i[0]];I[P]+=i
      if(N:=[J for j in o[not P]if(J:=[u for u in j if u!=i[0]])])!=o[not P]:o[not P]=N;F=1;P=not P
   else:
    for i in o[not P]:
     if len(i)==1:
      if len(K:=[J for j in o[P]if(J:=[u for u in j if u!=i[0]and u in m[P]])and len(J)==1])==1:m[P]=K[0]
    if len(K:=[J for j in o[P]if len(J:=[u for u in j if u in m[P]])==1])==1:m[P]=K[0]
   for i,a in E(m):
    if r[i]==-1and len(a)==1:r[i]=c+1;F=1;A=1;P=not i
  c+=1
 return r

Try it online!

You seem to have a comment (#print(c,m,o,A,P,I)) which you can remove


text:
pleTriwapt Sgpin (Triplet Swapping)
Intro/Background
I was looking at a Flybuys card at Coles recently and noticed that if I took something like this:

Source, randomly found on the Internet
And swapped some words around, I'd get this:

After I finished laughing (don't judge my sense of humour please),  I said to myself: "I need a program that can generate text like that". So I devised a set of rules for substring swapping and wrote yet another CGCC challenge!
The Challenge
Given a single string as input, output a string with its substrings swapped. This can be done by:

Splitting the string into chunks of three. The last triplet can possibly be shorter. (abcdefgh => [abc, def, gh])
Swap every triplet with every other triplet, leaving the last triplet in place if there is an odd amount of triplets.

The above bullet point more succinctly:

[D]ivide the list into adjacent pairs and swap each pair ~ @FlipTack

Test Cases

Input->Output
flybuys->buyflys
Once->eOnc
Triplet->pleTrit
Code Golf->e GCodolf
TopAnswers!->AnsTops!wer
Never gonna let you down->er Nevna gon yoletownu d
I'm Sorry, I Haven't a Clue-> SoI'm, Irryven Haa C't lue
Can I please have my vegetables back?-> I Canasepleve  havegmy bleetaacks b?
You are filled with determination-> arYouille fwited eteh dnatrmiion
->

Reference Program
Some Test Cases Explained
flybuys
[fly, buy, s] (split)
[buy, fly, s] (swapped)
buyflys

Once
[Onc, e] (split)
[e, Onc] (swapped)
eOnc

Triplet
[Tri, ple, t] (split)
[ple, Tri, t](swapped)
pleTrit

Code Golf
[Cod, e G, olf] (split)
[e G, Cod, olf] (swapped)
e GCodolf

TopAnswers!
[Top, Ans, wer, s!] (split)
[Ans, Top, s!, wer] (swapped)
AnsTops!wer

Rules

Input/output can be taken/given in any reasonable and convenient format
The input will not contain newlines
Strings can be of any length, and can be empty
Input will only contain printable ASCII characters
All standard loopholes are forbidden

Scoring
This is code-golf, so the answer with the lowest bytes wins

Maybe this could use some better wording - how about "divide the list into adjacent pairs and swap each pair"?

No, the output for Input should be putIn.

@S.S.Anne I assume you mean output for Input should be utInp per the Reference Program.  Though I get you were saying that humorously. :)

J, 13 bytes
[:;_2|.\_3<\]

Try it online!
Example input: 'flybuys'

_3<\] Box every group of 3
┌───┬───┬─┐
│fly│buy│s│
└───┴───┴─┘

_2|. Split that into groups of 2, and reverse each one:
┌───┬───┐
│buy│fly│
├───┼───┤
│s  │   │
└───┴───┘

[:; Raze the result:
buyflys

Perl 6, 24 bytes
{S:g/(...)(..?.?)/$1$0/}

Try it online!
Simple regex substitution that swaps every pair of three and up to three.

Jelly, 5 bytes
s3ṭ2/

A full program accepting a string which prints the result.
Try it online!
How?
s3ṭ2/ - Main Link: list of characters
s3    - split into threes
   2/ - 2-wise reduce with:
  ṭ   -   tack
      - implicit, smashing print

Gema, 13 characters
<u3><u3>=$2$1

Sample run:
bash-5.0$ echo -n 'flybuys' | gema '<u3><u3>=$2$1'
buyflys

Try it online! / Try all test cases online!

I immediately thought of Gema when I saw this challenge and was wondering if you'd reply.  It's as elegant as I thought it would be.

Brainfuck, 37 33 bytes
,[>,>,>>,>,>,<<[.>]<[<]<<<[.>]>,]

-4 bytes thanks to @JoKing
You can try it online
Cell layout is |a|b|c|0|d|e|f|, I read unconditionally and then print what is there to be printed.
Probably still golfable...

APL (Dyalog Unicode), 17 bytesSBCS
⍬∘(⍋⍋-6×3≤6|⍋)⊃¨⊂

Try it online!
Uses ⎕IO←0, i.e. 0-based indexing.
How it works
Uses ⍬⍋ generating index trick, though simply using ⍳≢ gives the same byte count here (thanks @ngn for pointing this out).
⍬∘(⍋⍋-6×3≤6|⍋)⊃¨⊂
⍬∘( ⍋-6×3≤6|⍋)     ⍝ Generate some numbers to apply "sortBy" on the input
⍬∘          ⍋        ⍝ Generate 0-based indexes
          6|         ⍝ Modulo 6
        3≤           ⍝ 1 if 3≤x is true, 0 otherwise
      6×             ⍝ 6 times
⍬∘  ⍋-               ⍝ Subtract from the original 0-based indexes;
                     ⍝ the result looks like 0 1 2 ¯3 ¯2 ¯1 6 7 8 3 4 5 12 13 ..
   ⍋          ⊃¨⊂  ⍝ "sortBy"; sort the input in the increasing order of above

PHP, 60 57 bytes
for($a=str_split($argn,3);$b=$a[$i++|0];)echo$a[$i++],$b;

Try it online!

Factor, 62 bytes
: f ( s -- s ) 3 group 2 group [ reverse concat ] map concat ;

Try it online!
Factor defies golfing :)

W, 5 bytes
"jC?┐

Uncompressed
3,2,_r

Explained
3,%Split the input into chunks of three
2,%Group the inputs into chunks of two
_r%Reverse every two-chunk of the input

Jelly, 6 bytes
s3s2Ṛ€

Try it online!
A full program taking a string and implicitly printing the rearranged string. This could be turned into a monadic link that returns a Jelly string by adding F (flatten) to the end.
Explanation
s3     | Split into sublists length 2
  s2   | Split into sublists length 2
    Ṛ€ | Reverse each

JavaScript (Node.js), 36 bytes
x=>x.replace(/(...)(..?.?)/g,"$2$1")

Try it online!
Simple regex substitution.

05AB1E, 6 bytes
3ô2ôíS

Outputs as a list of characters.
Try it online or verify all test cases.
Explanation:
3ô      # Split the (implicit) input-string into parts of size 3
  2ô    # Split this list into parts of size 2
    í   # Reverse each inner pair of triplets
     S  # Convert it to a flattened list of characters
        # (after which this is output implicitly)

Burlesque, 13 bytes
3co2co)<-FL\[

Try it online!
3co # Chunks of 3
2co # Chunks of 2
)<- # Map - Reverse
FL  # Flatten
\[  # Concatenate

GolfScript, 10 bytes
3/2/{-1%}%

Try it online!
Explanation
3/         # Split the input into chunks of three
  2/       # Group the inputs into chunks of two
    {-1%}% # Reverse every two-chunk of the input
           # This deals with the last two-chunk, in which
           # no reversing is done

Charcoal, 10 bytes
⭆⪪Ｓ⁶⪫⮌⪪ι³ω

Try it online! Link is to verbose version of code. Splitting into groups of 6 and splitting those works out shorter because it keeps the two numbers separate. Explanation:
  Ｓ         Input string
 ⪪ ⁶        Split into substrings of 6 characters
⭆           Map over substrings and join
       ι    Current substring
      ⪪ ³   Split into substrings of 3 characters
     ⮌      Reverse the substrings
    ⪫    ω  Join together
            Implicitly print

Haskell, 50 42 bytes
s(a:b:c:d)=take 3d++a:b:c:s(drop 3d)
s x=x

-8 bytes thanks to Post Rock Garf Hunter.
Try it online!

lambdas are rarely a good idea, yours costs you 3 bytes

In fact the whole split binding costs you

@PostRockGarfHunter Ah, I was comparing the lambda to let or where. I wasn't even thinking about pattern guards. (And I would have never guessed using take and drop separately would be shorter.) Nice catches!

K (ngn/k), 15 bytes
,//|'0N 2#0N 3#

Try it online!
0N 3# chunks of 3; last may be shorter
0N 2# pairs of chunks; last may be a singleton list
|' reverse each
,// flatten

Ruby, 33 bytes
->s{s.gsub /(...)(.{,3})/,'\2\1'}

Try it online!

Japt -P, 7 bytes
ò3 ò cw

Try it

PHP, 153 bytes
$c=($h='array_chunk')($h(str_split($argn),3),2);foreach($c as&$i)count($i)-1&&[$i[0],$i[1]]=[$i[1],$i[0]];echo implode(($m='array_merge')(...$m(...$c)));

Try it online!

Lua, 43 bytes
print(((...):gsub('(...)(.?.?.?)','%2%1')))

Try it online!
Take input as argument, print result to stdout. TIO link include program that check all testcases given in question. Uses Lua patterns to capture three and up to three characters, then swap those groups.

naz, 210 190 bytes
2a2x1v1x1f1r3x1v2e2x2v1r3x1v3e2x3v1r3x1v4e2x4v1r3x1v5e2x5v1r3x1v6e2x6v1r3x1v7e2x7v5v1o6v1o7v1o2v1o3v1o4v1o1f0x1x2f0a0x1x3f2v1o0x1x4f2v1o3v1o0x1x5f2v1o3v1o4v1o0x1x6f5v1o5f0x1x7f5v1o6v1o5f0x1f

I finally fixed the bug in the linked implementation that made solving challenges like this one impossible!
The main part of this program uses a ton of conditional instructions to properly split strings of any length, so I've split it onto multiple lines in the below explanation to aid readability.
Works for any input string terminated with the control character STX (U+0002).
Edit: Saved 20 bytes by calling function 5 directly from functions 6 and 7 instead of repeating its logic verbatim.
Explanation (with 0x commands removed)
2a2x1v                       # Set variable 1 equal to 2
1x1f1r3x1v2e2x2v             # Function 1
                             # Read a byte of input
                             # Jump to function 2 if it equals variable 1
                             # Otherwise, store it in variable 2
  1r3x1v3e2x3v               # This pattern continues for the next 5 bytes of input
  1r3x1v4e2x4v               # ...
  1r3x1v5e2x5v               # ...
  1r3x1v6e2x6v               # ...
  1r3x1v7e2x7v               # ...
  5v1o6v1o7v1o2v1o3v1o4v1o   # Output variables 5, 6, and 7, then variables 2, 3, and 4
                          1f # Then, jump back to the start of the function
1x2f0a                       # Function 2
                             # Add 0 to the register
1x3f2v1o                     # Function 3
                             # Output variable 2
1x4f2v1o3v1o                 # Function 4
                             # Output variables 2 and 3
1x5f2v1o3v1o4v1o             # Function 5
                             # Output variables 2, 3, and 4
1x6f5v1o5f                   # Function 6
                             # Output variable 5, then variables 2, 3, and 4
1x7f5v1o6v1o5f               # Function 7
                             # Output variables 5 and 6, then variables 2, 3, and 4
1f                           # Call function 1

Perl 5 -p, 21 bytes
s/(...)(..?.?)/$2$1/g

Try it online!

Python 3, 67 77 75 63 bytes

s is the variable holding the string to manipulate.
''.join(sum([(s[k+3:k+6],s[k:k+3]) for k in range(0,len(s),6)],()))

Try it online!
Edit:
77 bytes to respect the rules of Code Golf
f=lambda s:''.join(sum([(s[k+3:k+6],s[k:k+3])for k in range(0,len(s),6)],()))

Try it online!
Edit 2: Dropped the f=
lambda s:''.join(sum([(s[k+3:k+6],s[k:k+3])for k in range(0,len(s),6)],()))

Try it online!
Edit 3: Post Rock Garf Hunter made this version which gets rid of the sum(...,()) call, bringing the byte count down to 63!
lambda s:''.join(s[k+3:k+6]+s[k:k+3]for k in range(0,len(s),6))

Try it online!

Welcome to the site.  We don't do input from variables here for a number of reasons.  You should rewrite your submission to either define a function or be a complete program.

You can read about how we do input on this post.  Prepending your answer with lambda s: will make it valid, but will cost you

Thank you! I modified the entry accordingly. I added a f= so that it is callable. From my understanding prepending lambda s: creates an anonymous lambda which would need to be called right away?

Ok, thanks! I wonder if the range(0,len(s),6) could be shortened.

I don't think you can, but the rest can be Try it online!.

Oh yes, the concatenation instead of tuples, makes the list 1-dimensional which allows us to get rid of the sum(...), very nice!

Red, 59 bytes
func[s][until[move/part skip s 3 s 3""= s: skip s 6]head s]

Try it online!

Kotlin, 64 bytes
{chunked(3).chunked(2).fold(""){a,v->a+v.getOrElse(1){""}+v[0]}}

{chunked(3)                                                       // split string into triplets
           .chunked(2)                                            // group triplets by two
                      .fold(""){a,v->a+                           // join to string
                                       v.getOrElse(1){""}+v[0]}}  // putting second before first (if exists)

Try it online!

Husk, 7 bytes
Σṁ↔C2C3

Try it online!

Vyxal s, 5 bytes
3ẇy$Y

Try it Online!
3ẇ    # Divide into chunks of three
  y$Y # Swap each pair