text:
Who will win the election?
This is a challenge in which two people, 1 and 2, are running for office. People deterministically vote in certain ways in the world of 1 and 2, which can allow for the candidates to figure out the results before the election.
NOTE: this is not meant to refer to any outside elections or other political events.
Two people are running for office. We'll call these people 1 and 2. Because they both want to know if they will win the election, they decide to use their knowledge of people and some code to figure out what the result will be. Due to the want to minimize government spending, the code needs to be a short as possible.
Your task: Given a string of people based on how they are voting, output who wins the election.
There are five kinds of people in the fun and exciting world of 1 and 2:

A: people who will definitely vote for 1.
B: people who will definitely vote for 2.
X: people who will vote for whoever the person to their left will vote for. If there is no person to their left, then they vote for whoever the person at their right will vote for. If it is not clear who the person to their right is voting for, then they do not vote.
Y: people will vote the opposite of the person to their left. If there is no person to their left, then they vote opposite of whoever is at their right. If it is not clear who the person to their right is voting for, then they do not vote.
N: people who do not vote.

This is evaluated from left to right.
Example:
Whoever is being "evaluated" is in lowercase, for clarity.
Input: `XXAYAN`
        xX      Votes for whoever their friend is voting for. Their friend has not decided yet, so it is unclear, so they do not vote.
        Xx      Person to left is voting "none" so votes "none."
          a     Votes for 1
          Ay    Since person on left is voting for 1, votes for 2.
            a   Votes for 1
             n  Does not vote

Final poll:

2 people voted for 1
1 people voted for 2
3 people did not vote

1 has the most votes, so 1 wins!
Test cases:
You may use other characters or values as input and output, as long as they are distinct. (For example: numbers instead of letters, different letters, lowercase letters, truthy/falsy or positive/negative (for output), etc.)
Input -> Output

"AAAA" -> 1
"BBBB" -> 2
"BBAXY" -> 2
"BAXYBNXBAYXBN" -> 2
"XXAYAN" -> 1
"AAAABXXXX" -> 2
"AXNXXXXAYB" -> 1
"NANNY" -> 1
"XA" -> 1
"YAB" -> 2
"XY" -> anything (do not need to handle test cases with no victor)
"AB" -> anything (do not need to handle test cases with no victor)

Can NX or NY appear?

@EriktheOutgolfer Yes, but not alone. (See last valid test case)

So, ANNY is the same as AY? Like, do we just remove Ns?

@EriktheOutgolfer ANNY is the same as just A NN. NX and NY become NN.

It might be clearer to use uppercase/lowercase instead of an asterisk.

@SolomonUcko Good idea, editing.

It might be worth specifying that none is the opposite of none, if the behavior for NY in the comments is correct.

IMHO there should be testcases beginning with XA, XB, YA and YB.

May input contains only 1 letters? e.g. "A", "X", "Y", "N".

Does the output have to be two distinct values, or can we for example output any positive integer if 1 wins and any negative integer if 2 wins?

@tsh Do you mean like an array of characters? If so, yes.

@KevinCruijssen It can be positive/negative. (I'll clarify in the challenge).

@Neil Yes, adding. Thank you.

@ComradeSparklePony I mean, what the output for "X"? The behavior of a single "X" is confused to me.

@tsh for a single X, due to having no decided neighbors, would be N. But then no one wins. As such, you do not need to handle such a case. (I'll clarify the challenge when I get to a computer).

This is a really interesting logic challenge, thanks!

Do we have to handle single letter cases?

Java 8, 153 141 135 131 129 bytes
a->{int l=a.length,t,r=0,i=-1;for(;++i<l;r+=(t=a[i]=a[i]>4?t<3?t^3:3:a[i]>3?t:a[i])>2?0:3-t*2)t=a[i>0?i-1:i<l-1?i+1:i];return r;}

Uses an integer array as input with A=1, B=2, N=3, X=4, Y=5 and outputs a positive integer (>= 1) if A wins, a negative integer (<= -1) if B wins, or 0 if it's a draw.
-18 bytes thanks to @OlivierGrégoire.
Try it online.
Explanation:
a->{                      // Method with int-array parameter and boolean return-type
  int l=a.length,         //  Length of the input-array
      t,                  //  Temp integer, uninitialized
      r=0,                //  Result-integer, starting at 0
  i=-1;for(;++i<l         //  Loop `i` in the range [0, l):
           ;              //    After every iteration:
            r+=           //     Increase the result by:
             (t=a[i]=     //       Change `i`'th item in the array to:
                 a[i]>4?  //        If the `i`'th item is a 5:
                  t<3?    //         If `t` is 1 or 2:
                   t^3    //          Use `t` Bitwise-XOR 3 to invert it
                          //          (1 becomes 2; 2 becomes 1)
                  :       //         Else (`t` is 3, 4, or 5 instead):
                   3      //          Set it to 3
                 :a[i]>3? //        Else-if the `i`'th item is a 4:
                  t       //         Set it to `t`
                 :        //        Else (the `i`'th item is a 1, 2 or 3):
                  a[i])   //         Leave it unchanged
             )>2?         //      And if this new `i`'th value is 3, 4, or 5:
              0           //       Leave the result the same by increasing it with 0
             :            //      Else (it's 1 or 2 instead):
              3-t*2;      //       Increase it by 3 minus two times the `i`'th value
                          //       (which is 1 for 1; and -1 for 2)
         t=               //   Set `t` to:
           a[i>0?         //    If `i` is not the first item:
              i-1         //     Set `t` to the previous (`i-1`'th) value
             :i<l-1?      //    Else-if `i` is not the last item:
              i+1         //     Set `t` to the next (`i+1`'th) value
             :            //    Else (`i` is the first or last item):
              i];         //     Set `t` to the current item itself
  return r;}              //  Return the result
                          //  (positive if A wins; negative if B wins; 0 if it's draw)

i=0;for(int n:a)i+=n<2?1:n<3?-1:0;return i>0; saves a few bytes bytes.

Actually, i=0;for(int n:a)i+=n>2?0:3-n*2;return i>0; is even shorter.

@OlivierGrégoire Thanks! When I saw your first comment I was about to find something shorter, but you beat me to it with your second comment. ;)

131 bytes by merging the second loop in the first one. It doesn't feel right, though, and some test cases might have to be added...

@OlivierGrégoire Thanks! Been able to golf 4 more bytes by merging it some more with the temp variable. And what feels wrong about it? If you add a System.out.println(java.util.Arrays.toString(a)); after the loop you can see it changed as you would expect (imo). What kind of test case would you think results in an incorrect result and due to what part of the code?

I was wrong with my comment: I felt like in a specific line, we modified a[i+1] or a[i-1] which would have lead to invalid data at some point if r is computed immediately rather than afterwards. But... it doesn't happen so no consequences! Which leads me to another golf that I'll post in a few minutes (edit: oops, no: no further golf)

122 bytes: a->{int l=a.length,t,r=l,i=-1;for(;++i<l;r+=~(a[i]=a[i]>4?t<3?t^3:3:a[i]>3?t:a[i])%3)t=a[i>0?i-1:i<l-1?i+1:i];return r<0;} saves 9 more bytes if I count well. The r=l comes from a golf of ~(t=a[i]=...)%3 +1. And ~t%3+1 is the mapping with the ternary values (1 -> 1, 2 -> -1, 3 -> 0). Then I continued golfing to reach the result presented. I know it'll be hard to explain, so sorry in advance ;-)

@OlivierGrégoire Hmm, your 122 bytes version gives an incorrect result for one of the test cases. Here is that single test case in the 131 bytes version and here is that same test case in your 122 bytes version. The conversion of the array is the same, so that's good, but the result is different. Probably because the items will not just be 1->1, 2->-1, 3->0, but can also still be 4->0 or 5->0 when it starts with multiple X/Y, and your ~t%3+1 will map 4->-1 and 5->1 instead.

Oh, I somehow thought that those 4 and 5 were replaced by a 3. My bad.

@OlivierGrégoire Most indeed, but not all. :)

Haskell, 60 50 48 59 bytes
l#(v:o)|v<2=v+v#o|n<-(3-v)*l=n+n#o
_#_=0
f x=rem(x!!1)2#x>0

Uses 1 for A, -1 for B, 0 for N, 2 for X and 4 for Y. Returns True if A wins, else False.
Try it online!
On the recursive way down the input list we add 1 for every vote for A, -1 for every vote for B and 0 for "no vote". l is the last vote, v the next. If v=1, -1 or 0 (or v<2) we just add it to the sum. If v is "vote same" (X in the challenge, 2 for my solution) we keep and add l ((3-2)*l = l). If v is "vote opposite" (Y in the challenge, 4 for my solution) we first negate l ((3-4)*l = -l) and then add it. Base case is the empty list which starts the sum with 0. Recursion is started with l set to rem s 2 where s is the second element of the input list (x!!1). rem s 2 maps 1 and -1 to itself, all other values to 0. Fix votes ignore l anyway [*] and X or Y get the right neighbor if it's a fix vote. If the overall sum is positive, A wins.
[*] this makes singleton lists with fix votes like [1] work, because due to Haskell's laziness access to the second element is never evaluated. Inputs like [2] fail with error, but don't have to be considered.

This does not correctly handle X and Y without left neighbors

@Grimy: thanks for pointing out. Fixed.

Perl 5, 56 80 72 65 53 bytes
+26 bytes to handle the case X or Y in first position and A or B in second. output is 1 if 1 wins empty (false value in perl) otherwise.
s/^X(.)/$1$1/,s/A\KX|B\KY|^Y(?=B)/A/|s/B\KX|A\KY|^Y(?=A)/B/&&redo;$_=y/A//>y/B//

TIO
using P and S instead of X and Y allowing to use xor operation on characters, would save some more bytes
s/(?|^(P|S)(?=(A|B))|(A|B)\K(P|S))/P^$1^$2/e&&redo;$_=y/A//>y/B//

uses a branch reset group (?|..|..), so that $1 $2 refering to corresponding group in branch.
Using \0 and \3 instead of X and Y
$_=s/^\W(?=(\w))|(\w)\K\W/$1.$2^$&/e?redo:y/A//>y/B//

72 bytes
65 bytes
53 bytes

from my last understanding they are not counted any more

This does not correctly handle X and Y at the start of the string. Try XBA and YAB.

@Grimy, updated

JavaScript (ES6),  78 75  73 bytes
Takes input as an array of integers with: \$0\$ = N, \$1\$ = A, \$2\$ = B, \$4\$ = Y, \$8\$ = X.
Returns \$false\$ if the first candidate wins or \$true\$ if the 2nd candidate wins.
a=>a.reduce((v,x,i)=>v+~~[,1,-1][p=x?x&3||~-x%7^(p&3||a[i+1]&3):0],p=0)<0

Try it online!

05AB1E, 34 33 32 30 bytes
gFÐNè©2@iNx1.S-èDÄ2‹*D(‚®èNǝ]O

Uses an integer-array as input with A=-1, B=1, N=0, X=2, Y=3 and outputs a negative integer (<= -1) if A wins, a positive integer (>= 1) if B wins, or 0 if it's a draw.
Try it online or verify all test cases.
Explanation:
g             # Take the length of the (implicit) input-list
              #  i.e. [3,1,3,3,2,0,1] → 7
 F            # Loop `N` in the range [0, length):
  Ð           #  Triplicate the list at the top of the stack
              #  (which is the implicit input-list in the first iteration)
   Nè         #  Get the `N`'th item of the list
              #   i.e. [3,1,3,3,2,0,1] and `N`=0 → 3
              #   i.e. [-1,1,-1,3,2,0,1] and `N`=3 → 3
     ©        #  Store it in the register (without popping)
   2@i        #  If it's larger than or equal to 2 (so either 2 or 3):
      Nx      #   Push `N` and `N` doubled both to the stack
              #    i.e. `N`=0 → 0 and 0
              #    i.e. `N`=3 → 3 and 6
        1.S   #   Compare the double integer with 1 (-1 if N*2<1; 0 if N*2==1; 1 if N*2>1)
              #   (So this will be -1 in the first iteration, otherwise it will be 1)
              #    i.e. 0 → -1
              #    i.e. 6 → 1
           -è #   Subtract that from the index, and index it into the list
              #    i.e. `N`=0 and -1 → 1 (first item, so get the next index)
              #     → [3,1,3,3,2,0,1] and 1 → 1
              #    i.e. `N`=3 and 1 → 2 (fourth item, so get the previous index)
              #     → [-1,1,-1,3,2,0,1] and 2 → -1
      D       #   Duplicate that value
       Ä2‹    #   Check if that value is -1, 0, or 1 (abs(i) < 2) (truthy=1; falsey=0)
          *   #   And multiply that with the value
              #   (remains the same if truthy; or becomes 0 if falsey)
      D(‚     #   Pair it with its negative (-1 becomes [-1,1]; 1 becomes [1,-1])
         ®è   #   And index the `N`'th value (from the register) into it (with wraparound)
              #   (if it was a 2, it uses the unchanged (first) value of the pair;
              #    if it was a 3, it uses the negative (second) value of the pair)
              #     i.e. [1,-1] and 3 → -1
              #     i.e. [-1,1] and 3 → 1
      Nǝ      #   And replace the `N`'th value with this
              #    i.e. [3,1,3,3,2,0,1], `N`=0 and -1 → [-1,1,3,3,2,0,1]
              #    i.e. [-1,1,-1,3,2,0,1], `N`=3 and 1 → [-1,1,-1,1,2,0,1]
 ]            # Close both the if-statement and loop
  O           # Sum the modified list (which now only contains -1, 0, or 1)
              #  i.e. [-1,1,-1,1,1,0,1] → 2

JavaScript (Node.js), 42 bytes
s=>s.map(c=>x+=l=c%2|l*c/2,l=s[x=1]%2)|x>1

Try it online!
Save 1 bytes, thanks to Shaggy.

Input as integer array where N = 0, A = -1, B = 1, X = 2, Y = -2;
Output 1 = Falsy, 2 = Truthy

Your TIO seems to output 0, 1 and 3 instead of 1 and 2?

@KevinCruijssen But OP allowed truthy vs. falsy as output if i understand correctly. Falsy means 1 won the game, and truthy means 2 won.

Ah ok, forgot 3 is truthy in JS as well. I always think of 0/1 as falsey/truthy. And since we no longer need distinct outputs, 0 = 1 wins and >= 1 = 2 wins is fine as well. So +1 from me.

It looks like you could save a byte using bitwise OR, instead of logical OR.

@Shaggy So strange. It works.

Python 2, 95 73 bytes
lambda(v):sum([l for l in[2*int(v[1]/2)]for i in v for l in[i*l**(i%2)]])

Try it online!

Input as integer array where N = 0, A = -2, B = 2, X = 1, Y = -1;
Output negative = A, 0 = draw, positive = B
If first input is X or Y, then 2*int(v[1]/2) maps second to itself or 0

Bug fix was required that added extra bytes, but converting to lambda thanks to @Stephen reduced it back to 95

74 bytes by removing whitespace and changing the function to a lambda function

64 bytes by removing unnecessary parens and brackets, and using a bit mask,

Retina 0.8.2, 70 bytes
AY
AB
BY
BA
}`(A|B)X
$1$1
^X(A|B)|^Y[AB]
$1$1
+`N|X|Y|AB|BA

.+|(?<=B)

Try it online! Link includes test cases. Outputs 0 for a tie. Explanation:
AY
AB
BY
BA

Handle Y voters to the right of people with decided votes.
}`(A|B)X
$1$1

Handle X voters to the right of people with decided votes, and then loop back until all possible Y and X votes can be decided.
^X(A|B)|^Y[AB]
$1$1

Handle an initial X voter next to a decided vote, and also an initial Y voter next to a decided vote. As this voter will vote opposite to the decided vote, we can just delete both votes in this case.
+`N|X|Y|AB|BA

Delete any remaining no vote or undecided votes, and cancel out all pairs of opposing decided votes. Repeat until all possible votes are cancelled. In the case of a tie, nothing will be left, otherwise the remaining votes will all be of the same type.
.+|(?<=B)

Output 1 if there are any votes, but 2 if they are B votes.

Python 3.8+, 55 bytes
lambda v:[l:=v[1]&~1]and sum((l:=i*l**(i%2))for i in v)
Attempt This Online!
Port of ABridgeTooFar's Python 2 solution, since we took the time in TNB to figure out why and how that list comprehension does anything at all.

Python 3 2, 125 121  117 bytes
(Thanks to Jonathan Frech)
def f(x):
    for i,v in enumerate(x):n=x[i-(i>0)];x[i]=(v>3)*n+abs(n-1)*(v<0)+x[i]*(0<v<4)
    print x.count(1)>x.count(0)

Using tab indentation
Input: list of ints where 'A'=1, 'B'=0, 'X'=4, 'N'=3, 'Y'=-1, so "AAAA" is [1, 1, 1, 1] and "XXAYAN" is [4, 4, 1, -1, 1, 3].
[{'A': 1, 'B': 0, 'X': 4, 'N': 3, 'Y': -1}[c] for c in s] will convert the strings to the needed input format.
You can Try it online! (Thanks to Jonathan Frech for the suggestion)

Hello and welcome to PPCG. I would recommend using TIO, as it nicely formats your code. Furthermore, I do not quite understand your input format. You may have to ask the OP about its validity.

As a golfing tip, (i, i-1)[i>0] should be equivalent to i-(i>0).

Furthermore, your ifs could probably become x[i]+=(v>3)*n+abs(n-1)*(v<0). You can then save on indentation by moving the now non-compound statement (using ;) on the same line as the for.

@JonathanFrech Thank you very much; I hope I explained the input better

Python 3, 187 156 bytes
Really not that competitive with the other python answers on this, but I had some good ideas for using dicts to make an answer that actually takes string inputs, and it didn't turn out horribly long.
def E(s):
 r,g,*v=range(len(s)),lambda**d:d.get(s[i],0),*s
 for i in r:v[i]=g(A=1,B=-1)
 for i in r:v[i]=g(X=1,Y=-1)*v[(i-1,i+1)[i<1]]or v[i]
 return sum(v)

Try it online!
Edit -21 bytes: Some beautifully horrific abuse of python by @Unrelated String
Loops through the input twice to fill out an output list containing the vote of each person (1 for A, -1 for B, 0 for no vote), and filling out the Xs and Ys on the second loop. I thought I could do it with one loop, but irritatingly that fails on an X or Y at the beginning of the string, as it hasn't processed the following vote yet. The return value is positive if candidate 1 wins, and negative if candidate 2 wins. (The absolute value of it also happens to be the margin of victory)

164 with the dict constructor, aliasing range(x) (hard to remember it's not a mutable iterator sometimes!), fiddling with the eval a bit, and initializing v a bit more messily.

...although the dict constructor bit doesn't matter if you remove the N key, since it's 0 anyways

this has NO right to work

holy s#!7 @UnrelatedString thats some beautiful abuse of python right there

Perl 5, 54 bytes
s/^\W(?=(\w))|(\w)\K\W/$1^$2^$&/e&&redo;$_=y/A//>y/B//

Try it online!
Uses A for A, B for B, N for N, \0 for X and \3 for Y (the last two being literal control chars). The trick is that A bitwise-xor \3 equals B, and vice-versa.

it uses many ideas of my answer, i wasn't sure we can use non printable character as input and output, except i didn't realize the benfit of using backslash character classes

Javascript (ES6) - 133 bytes
a=>(i=($=_=>'AB'.search(_)+1)(a[1],o=0),[...a].map(v=>(r=['NAB','NBA']['XY'.search(x)],p=r?r[i]:v,i=$(p),o+='NA'.search(p))),o>0?1:2)

Takes in a string with the format given in the OP and returns 1 if candidate 1 won and 2 otherwise (I'll admit it, I'm even-biased).


text:
Prime Difference
Given an integer n, output the smallest prime such that the difference between it and the next prime is at least n.
For example, if n=5, you would output 23, since the next prime is 29, and 29-23>=5.
More Input/Output Examples
1 -> 2 (3 - 2 >= 1)
2 -> 3 (5 - 3 >= 2)
3 -> 7 (11 - 7 >= 3)
4 -> 7
5 -> 23
6 -> 23
7 -> 89
8 -> 89

This is code-golf, so shortest code wins.

OEIS A104138.

It's interesting that on a language-by-language basis, most answers are considerably shorter than the answers to the exact duplicate posted in August 17. I'd conclude that the code-golfing skills of the community as a whole continue to grow.

... or the golfing languages keep getting terser

Husk, 8 bytes
Ψḟo≥⁰≠İp

Try it online!
Inspired by this post in chat
ḟ, under normal circumstances, finds the first element of a list that satisfies a predicate. However, when combined with the function Ψ, it finds the first element that satisfies a predicate with respect to its successor in the list.
The predicate is o≥⁰≠, which asks if the absolute difference of two numbers is at least the input.
The list is İp, the list of prime numbers

Perl 6, 40 bytes
{1-$_+first ++($*=!*.is-prime)>=$_,2..*}

Try it online!
38 bytes, 0-based (I'm not sure this is allowed):
{-$_+first ++($*=!*.is-prime)>$_,2..*}

Try it online!

Perl 6, 56 bytes
{first {$^a.$![1]-$a>=$_},.$!}
$!={grep &is-prime,$_..*}

Try it online!
I feel like there's definitely some improvement to be made here, especially in regards to the $![1]. This is an anonymous code block that can be assigned to a variable, as well as a helper function assigned to $!.

40 bytes: {1-$_+first ++($*=!*.is-prime)>=$_,2..*} (TIO).

@Grimy This looks sufficiently different to post as separate answer.

@nwellnhof Alright, I made it a separate answer.

J, 26 24 22 bytes
>:@]^:(>:4&p:-])^:_ 2:

Try it online!
0-based
Explanation:
                      2:  start with the first prime number and
      ^:(        )^:_     while
         >:               the argument is greater or equal to the
               -          difference of
           4&p:           the next prime number and
                ]         the current prime number
  >:@]                    go to the next number

C (gcc), 58 bytes
Same logic as my JS answer, with a non-recursive implementation.
f(n,p,q,x){for(p=q=x=2;q-p<n;q%x--||(p=x?p:q,x=q++));q=p;}

Try it online!

Jelly, 8 bytes
2Æn:+ɗ1#

Try it online!
How it works
2Æn:+ɗ1#  Main link. Argument: n

2         Set the return value to 2.
      1#  Find the first k ≥ 2 such that the link to the left, called with arguments
          k and n, returns a truthy value.
     ɗ    Dyadic chain:
 Æn           Find the next prime p ≥ k.
    +         Yield k + n.
   :          Perform integer division.

JavaScript (ES6),  61 57 56  54 bytes
n=>(g=(q,x=q++)=>q-p<n?q%x--?g(q,x):g(x?q:p=q):p)(p=2)

Try it online!
Commented
n => (                    // n = input
  g = (                   // g = recursive function taking:
    q,                    //   q = prime candidate
    d = q++               //   d = divisor
  ) =>                    //
    q - p < n ?           // if q - p is not large enough:
      q % d-- ?           //   decrement d; if d was not a divisor of q:
        g(q, d)           //     try again until it is
      :                   //   else:
        g(                //     do a recursive call to look for the next prime
          d ? q : p = q   //       if q was prime, update the previous prime p to q
        )                 //     end of recursive call
    :                     // else:
      p                   //   success: return p
                          //   NB: we don't know if q is prime or not, but the only
                          //       thing that matters at this point is that the next
                          //       prime is greater than or equal to q
)(p = 2)                  // initial call to g with p = q = 2

Non-recursive version, 54 bytes
By porting back in JS my non-recursive port in C, it turns out that we can reach 54 bytes as well.
n=>eval(`for(p=q=x=2;q-p<n;q%x--||(p=x?p:q,x=q++));p`)

Try it online!
Performance
This piece of code is a good illustration of the utterly bad performance of eval(), which prevents JIT compilation:

It takes 35 to 40 sec. to compute \$a(1)\$ to \$a(37)\$ on TIO with the above code.
It takes ~1.5 sec. to do the same thing without eval():
// 55 bytes
n=>{for(p=q=x=2;q-p<n;q%x--||(p=x?p:q,x=q++));return p}

05AB1E, 9 bytes
∞<ØD¥I@Ïн

Try it online or verify all test cases.
Explanation:
∞           # Get an infinite list in the range [1, ...]
 <          # Decrease it by one to make it in the range [0, ...]
  Ø         # Get for each the (0-indexed) n'th prime: [2,3,5,7,11,...]
   D        # Duplicate this list of primes
    ¥       # Get all deltas (difference between each pair): [1,2,2,4,2,...]
     I@     # Check for each if they are larger than or equal to the input
            #  i.e. 4 → [0,0,0,1,0,1,0,1,1,0,...]
       Ï    # Only keep the truthy values of the prime-list
            #  → [23,31,47,53,61,...]
        н   # And keep only the first item (which is output implicitly)
            #  → 23

Brachylog, 12 bytes
∧⟧ṗˢsĊ-≥?∧Ċt

Try it online!
Explanation
∧⟧              Take a descending range from an unknown integer down to 0
  ṗˢ            Select only primes in that range
    sĊ          Take a substring of 2 elements in that range; call it Ċ
      -≥?       The subtraction of those 2 elements must be greater than the input
         ∧Ċt    The output is the tail of Ċ

Python 2, 63 bytes
n=input()
k=P=b=2
while k-b<n:
 if P%k:b=k
 P*=k*k;k+=1
print b

Try it online!

Pari/GP, 38 bytes
n->i=2;while(nextprime(i+1)-i<n,i++);i

Try it online!

Ruby, 39 38 bytes
->n,m=2{Prime.find{|i|i-m>=n||!m=i};m}

Try it online!

Husk, 9 bytes
→←ġo<⁰-İp

Try it online!
This is a really interesting question allowing a range of possible approaches (and Husk is a good fit for it; I learned the language for the challenge).
The TIO link contains a wrapper to run this function on all inputs from 1 to 10.
Explanation
→←ġo<⁰-İp
       İp   The (infinite) list of primes
  ġ         Group them, putting adjacent primes in the same group if
      -         the difference between them
    <⁰          is less than the input
   o          (fix for a parser ambiguity that causes this parse to be chosen)
→           Take the last element of
 ←          the first group

Grouping primes that are too close together means that the first break in the groups will be the first point at which the primes are sufficiently far apart, so we simply just need to find the prime just after the break.
Other potential solutions
Here's an 8-byte solution that, sadly, only works with even numbers as input (and thus isn't valid):
-⁰LU⁰mṗN
       N   On the infinite list of natural numbers
     m     replace each element with
      ṗ      0 if composite, or a distinct number if prime
   U       Find the longest prefix with no repeated sublist of length
    ⁰        equal to the input
-⁰         Subtract the input from
  L          the length of that prefix

The idea is that when we have two primes that are a distance of (say) 6 apart, there'll be a sequence of five consecutive zeroes in the mṗN sequence, which contains two identical sublists of length 4 (the first four zeroes and last four zeroes), but such a repetition cannot happen earlier (because as each prime is mapped to a unique number, any length-4 substrings before the first prime gap > 4 will contain a prime number, and the substring will therefore be unique as it's the only substring which contains that number in that position). Then we just have to subtract the trailing zeroes from the length of the prefix to get our answer.
This doesn't work with odd inputs because the sublist of input zeroes only occurs once rather than twice, so the code ends up finding the second point at which it occurs rather than the first.

Japt, 16 bytes
@§Xn_j}aXÄ)©Xj}a

Try it or test 0-20

source: Stack Exchange

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

sort: votes


text:
Pointer jumping
Suppose we have an array \$\texttt{ps}\$ of length \$n\$ with pointers pointing to some location in the array: The process of "pointer jumping" will set every pointer to the location the pointer it points to points to.
For the purpose of this challenge a pointer is the (zero-based) index of an element of the array, this implies that every element in the array will be greater or equal to \$0\$ and less than \$n\$. Using this notation the process can be formulated as follows:
for i = 0..(n-1) {
  ps[i] = ps[ps[i]]
}

This means (for this challenge) that the pointers are updated in-place in sequential order (ie. lower indices first).
Example
Let's work through an example, \$\texttt{ps = [2,1,4,1,3,2]}\$:
$$
\texttt{i = 0}: \text{the element at position }\texttt{ps[0] = 2}\text{ points to }\texttt{4} \\    \to \texttt{ps = [4,1,4,1,3,2]} \\
\texttt{i = 1}: \text{the element at position }\texttt{ps[1] = 1}\text{ points to }\texttt{1} \\    \to \texttt{ps = [4,1,4,1,3,2]} \\
\texttt{i = 2}: \text{the element at position }\texttt{ps[2] = 4}\text{ points to }\texttt{3} \\    \to \texttt{ps = [4,1,3,1,3,2]} \\
\texttt{i = 3}: \text{the element at position }\texttt{ps[3] = 1}\text{ points to }\texttt{1} \\    \to \texttt{ps = [4,1,3,1,3,2]} \\
\texttt{i = 4}: \text{the element at position }\texttt{ps[4] = 3}\text{ points to }\texttt{1} \\    \to \texttt{ps = [4,1,3,1,1,2]} \\
\texttt{i = 5}: \text{the element at position }\texttt{ps[5] = 2}\text{ points to }\texttt{3} \\    \to \texttt{ps = [4,1,3,1,1,3]}
$$
So after one iteration of "pointer jumping" we get the array \$\texttt{[4,1,3,1,1,3]}\$.
Challenge
Given an array with indices output the array obtained by iterating the above described pointer jumping until the array does not change anymore.
Rules
Your program/function will take and return/output the same type, a list/vector/array etc. which

is guaranteed to be non-empty and
is guaranteed to only contain entries \$0 \leq p < n\$.

Variants: You may choose

to use 1-based indexing or
use actual pointers,

however you should mention this in your submission.
Test cases
[0] → [0]
[1,0] → [0,0]
[1,2,3,4,0] → [2,2,2,2,2]
[0,1,1,1,0,3] → [0,1,1,1,0,1]
[4,1,3,0,3,2] → [3,1,3,3,3,3]
[5,1,2,0,4,5,6] → [5,1,2,5,4,5,6]
[9,9,9,2,5,4,4,5,8,1,0,0] → [1,1,1,1,4,4,4,4,8,1,1,1]

Related: Jump the array

Are we allowed to take the length n as additional input?

@KevinCruijssen, see this meta discussion.

It's too bad the entries need to be updated sequentially; if they could be updated simultaneously, Mathematica would have the 21-character solution #[[#]]&~FixedPoint~#&.

JavaScript, 36 bytes
Modifies the original input array.
a=>a.map(_=>a.map((x,y)=>a[y]=a[x]))

Try it online

Python 2, 53 bytes
def f(l):L=len(l);i=0;exec'l[i]=l[l[i]];i=-~i%L;'*L*L

Try it online!
-6 thanks to HyperNeutrino.
Alters l to the result in place.

Haskell, 56 bytes
foldr(\_->([]#))=<<id
x#a@(b:c)=(x++[(x++a)!!b])#c
x#_=x

Haskell and in-place updates are a bad match.
Try it online!

C++14 (gcc), 61 bytes
As unnamed generic lambda. Requires sequential containers like std::vector.
[](auto&c){auto d=c;do{d=c;for(auto&x:c)x=c[x];}while(d!=c);}

Try it online!

Swift, 68 53 bytes
{a in for _ in a{var i=0;a.forEach{a[i]=a[$0];i+=1}}}

Try it online!
-15 thanks to BMO

Welcome to PPCG! I don't know Swift, but on codegolf.SE the default is to accept typed lambda-functions which I guess a closure would count as. So this can be 53 bytes (you don't need to count f=). Enjoy your stay here!

Thank you for the welcome and advice which I have used to update my answer.

How about using map instead of forEach to make it shorter?

JavaScript (ES6), 41 bytes
f=a=>a+''==a.map((x,i)=>a[i]=a[x])?a:f(a)

Try it online!

Gah! I was waiting for this challenge to be posted so I could post the exact same solution :\ Damn your ninja skills! :p

@shaggy (this is supposed to be a Ninja Cat ... but it's probably not supported everywhere)

Japt, 15 13 7 bytes
Modifies the original input array.
££hYXgU

Try it (additional bytes are to write the modified input to the console)
££hYXgU
£           :Map
 £          :  Map each X at index Y
  hY        :    Replace the element at index Y
    XgU     :    With the element at index X

05AB1E (legacy), 8 bytes
ΔDvDyèNǝ

Try it online!
Explanation
Δ          # apply until the top of the stack stops changing
 D         # duplicate current list
  v        # for each (element y, index N) in the list
   Dyè     # get the element at index y
      Nǝ   # and insert it at index N

05AB1E, 14 bytes
[D©vDyèNǝ}D®Q#

Try it online!

Java 8, 105 54 bytes
a->{for(int l=a.length,i=0;i<l*l;)a[i%l]=a[a[i++%l]];}

Modifies the input-array instead of returning a new one to save bytes.
-51 bytes by just modifying the array \$length^2\$ times, instead of until it no longer changes.
Try it online.
Explanation:
a->{                // Method with integer-array parameter and no return-type
  int l=a.length,   //  Length of the input-array
  i=0;i<l*l;)       //  Loop `i` in the range [0, length squared):
    a[i%l]=         //   Set the (`i` modulo-length)'th item in the array to:
      a[            //    The `p`'th value of the input-array,
        a[i++%l]];} //    where `p` is the (`i` modulo-length)'th value of the array

Japt, 17 bytes

®
£hYUgX
eV ?U:ß

Try all test cases
This feels like it should be shorter, but unfortunately my initial thought of UmgU doesn't work because each g accesses the original U rather than modifying it at each step. Preserving different components appropriately cost a handful of bytes as well.
Explanation:
           #Blank line preserves input in U long enough for the next line

®          #Copy U into V to preserve its original value

£hY        #Modify U in-place by replacing each element X with...
   UgX     #The value from the current U at the index X

eV ?U      #If the modified U is identical to the copy V, output it
     :ß    #Otherwise start again with the modified U as the new input

C (clang), 32-bit, 49 44 bytes
i;f(**p,n){for(i=0;i<n*n;)p[i++%n]=*p[i%n];}

Try it online!
Uses pointers.
50 45 bytes with integers:
i;f(*p,n){for(i=0;i<n*n;)p[i++%n]=p[p[i%n]];}

Try it online!

Ruby, 37 34 bytes
->a{a.size.times{a.map!{|x|a[x]}}}

Try it online!
Returns by modifying the input array in-place.

R, 60 58 bytes
-2 bytes thanks to @digEmAll for reading the rules.
function(x,n=sum(x|1)){for(i in rep(1:n,n))x[i]=x[x[i]];x}

Try it online!
1-indexed.
n is the length of the input array.
rep(1:n,n) replicates 1:n n times (e.g. n=3 => 1,2,3,1,2,3,1,2,3)
Loop through the array n times. Steady state will be acheived by then for sure, in fact by the end of the n-1st time through I think. The proof is left to the reader.

I think you can remove the +1 and simply take the 1-based input, the post states : *You may choose
to use 1-based indexing*

-4 by switching to scan() for input. I always feel like my scan() solutions are suboptimal, so keep an eye out a shorter way to assign x and n together: n=length(x<-scan());for(i in rep(1:n,n))x[i]=x[x[i]];x Try it online!

Clojure, 136 bytes
(defn j[a](let[f(fn[a](loop[i 0 a a](if(= i(count a))a(recur(inc i)(assoc a i(a(a i)))))))](loop[p nil a a](if(= p a)a(recur a(f a))))))

Try it online!

Hello and welcome to PPCG. Would it be possible for you to provide a link to an online interpreter such that one could easily verify your solution? Furthermore, can loop [ not become loop[?

The most recent edit should fix the test failures. Sorry for the inconvenience everybody.

Red, 63 bytes
func[b][loop(l: length? b)* l[repeat i l[b/:i: b/(1 + b/:i)]]b]

Try it online!
Modifies the array in place

Common Lisp, 59 58 bytes
(lambda(a)(dolist(j a)(map-into a(lambda(x)(elt a x))a))a)

Try it online!

Clean, 80 bytes
import StdEnv

limit o iterate\b=foldl(\l i=updateAt i(l!!(l!!i))l)b(indexList b)

Try it online!

Perl 5, 35 34 26 bytes
using the fact that convergence is reach at most for the size number of iterations
$_=$F[$_]for@F x@F;$_="@F"

26 bytes
$_=$F[$_]for@F;/@F/ or$_="@F",redo

34 bytes
$_=$F[$_]for@F;$_="@F",redo if!/@F/

35 bytes

Clojure, 88 bytes
#(reduce(fn[x i](assoc x i(get x(get x i))))%(flatten(repeat(count %)(range(count %)))))

Try it online!

Charcoal, 16 bytes
ＦθＦＬθ§≔θκ§θ§θκＩθ

Try it online! Link is to verbose version of code. Sadly all the usual mapping functions only operate on a copy of the array with the result being that they just permute the elements rather than jumping them, so the code has to do everything manually. Explanation:
Ｆθ

Repeat the inner loop once for each element. This just ensures that the result stabilises.
ＦＬθ

Loop over the array indices.
§≔θκ§θ§θκ

Get the array element at the current index, use that to index into the array, and replace the current element with that value.
Ｉθ

Cast the elements to string and implicitly print each on their own line.

F#, 74 73 bytes
fun(c:'a[])->let l=c.Length in(for i in 0..l*l do c.[i%l]<-c.[c.[i%l]]);c

Nothing special. Uses the modulus idea seen in other answers.

K, 27 Bytes
{{@[x;y;:;x x y]}/[x;!#x]}/

{..}/ applies lambda {..} over arg (until convergence)
inside outer lambda:

{..}/[x;y] applies lambda iteratively over x (updated at each iteration) and an item of y (y is a list of values, and uses an item at each iteration). In this case arg y is !#x(til count x, that is, indexes of the array)
@[x;y;:;x x y] amend array x (at index y assign x[x[y]])

APL (Dyalog Unicode), 26 bytesSBCS
Requires ⎕IO←0

{m⊣{m[⍵]←m[m[⍵]]}¨⍳≢m←⍵}⍣≡

Try it online!

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


text:
Partition a square grid into parts of equal area
This challenge is based on the following puzzle: You are given an n by n grid with n cells marked. Your job is to the partition the grid into n parts where each part consists of exactly n cells, each containing exactly one marked cell.
Example
Here is a puzzle on the left and its (unique) solution on the right:

Challenge
You will be given a set of n zero-indexed coordinates in any reasonable format.
[(0,0), (0,3), (1,0), (1,1), (2,2)]

And your job is to write a program that returns any valid parition (again, in any reasonable format).
[
  [(0,0), (0,1), (0,2), (1,2), (1,3)],
  [(0,3), (0,4), (1,4), (2,4), (3,4)],
  [(1,0), (2,0), (3,0), (4,0), (4,1)],
  [(1,1), (2,1), (3,1), (3,2), (4,2)],
  [(2,2), (2,3), (3,3), (4,3), (4,4)]
]

If the puzzle has no solution, the program should indicate that by throwing an error or returning an empty solution.
Input/Output Examples
[(0,0)]               => [[(0,0)]]

[(0,0), (1,1)]        => [
                          [(0,0), (1,0)],
                          [(0,1), (1,1)]
                         ]

[(0,0), (0,1), (1,0)] => [] (no solution)

[(0,0), (0,1), (0,2)] => [
                          [(0,0), (1,0), (2,0)],
                          [(0,1), (1,1), (2,1)],
                          [(0,2), (1,2), (2,2)],
                         ]

[(0,0), (0,2), (1,2)] => [
                          [(0,0), (1,0), (2,0)],
                          [(0,1), (0,2), (1,1)],
                          [(1,2), (2,1), (2,2)],
                         ]

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

This was inspired by this Math Stack Exchange question.

@Arnauld, it looks like for Shikaku puzzles, "the objective is to divide the grid into rectangular and square pieces". In this case, there is no such constraint.

Sorry for the confusion. I think there might be a Shikaku challenge somewhere in the sandbox, or maybe I was planning to make one myself at some point -- I can't remember for sure. Either way, I thought it was the same thing at first glance.

Why is the result a 2d array of coordinates? I don't understand what is being expressed there... Can't it be a 2d array of the index of the array? For instance row 3, column 2 contains partition with coordinates at index 4?

May we assume that each area can be drawn by starting from the reference coordinates, as the example suggests? I've just realized that I've unconsciously taken this for granted.

@Arnauld, not necessarily. In principle, the marked cell could be at the center of a T-tetromino. I'll add an example.

@OlivierGrégoire, the array of coordinates gives the coordinates of each particular part (in this case in lexicographic order), for example [(0,0), (0,1), (0,2), (1,2), (1,3)] refers to the red region in the picture. However, any reasonable format that clearly shows that you have solved the puzzle is fine.

Can we take the length as a second input?

@lirtosiast, you cannot take the length as a second input because it is easily derivable from the (first) input.

Can we use 1-indexing if that's our language's default? And can we return all valid partitions instead of just one?

@caird, 1-indexing is allowed, and returning all valid partitions is valid output.

Jelly, 26 bytes
Jṗ2Œ!s€L_/ƝÆḊ€ỊẠƲ€Ạ$Ƈi"Ạ¥Ƈ

Try it online!
This is wildly inefficient, around \$O({n^2}!)\$ for an input of \$n\$ co-ordinates. As such, it times out on TIO for \$n \ge 3\$. I've tested it locally for the other test cases and it works as expected.
This takes input 1 indexed, and it returns a list of valid partitions. The Footer adjusts the output for you.
How it works
Jṗ2Œ!s€L_/ƝÆḊ€ỊẠƲ€Ạ$Ƈi"Ạ¥Ƈ - Main link. Takes a list of n coordinates on the left
J                          - [1, 2, ..., n]
 ṗ2                        - All pairs; [[1, 1], [1, 2], ..., [n, n]]
   Œ!                      - All permutations
       L                   - Yield n
     s€                    - Split each permutation into n parts
                   $Ƈ      - Keep the matrices for which the following is true:
                Ʋ€         -   Over each row:
          Ɲ                -     For each overlapping pair:
        _/                 -       Get the successive differences
           ÆḊ€             -     Get the norm for each
              ỊẠ           -     All are between -1 and 1?
                  Ạ        -   This is true for all rows?
                             This filters out matrices of non-adjacent coordinates
                        ¥Ƈ - Keep the matrices for which the following is true:
                     i"    -   Get the indices of each coordinate, or 0, if not in each row
                       Ạ   -   All non-zero?

JavaScript (ES7), 166 bytes
Outputs a matrix of integers that describe the partition, or \$false\$ if there's no solution.
a=>(m=a.map(_=>[...a]),g=(n,X,Y,j=0,i)=>a[n]?a[j]?m.some((r,y)=>r.some((v,x)=>++v|(X-x)**2+(Y-y)**2-1?0:g(r[x]=n,x,y,j+1,i|x+[,y]==a[n])?1:r[x]=v)):i&&g(n+1):1)(0)&&m

Try it online!
How?
We first build a square matrix \$m\$ of size \$N\times N\$, where \$N\$ is the length of the input:
m = a.map(_ => [...a])

Each row of \$m\$ consists of a copy of the input, i.e. an array of \$N\$ coordinate pairs. The important point here is that all cells of \$m\$ are initialized to non-numeric values. We'll be able to detect them by applying the prefix increment operator ++.
The recursive function \$g\$ takes a pointer \$n\$ into the input, the coordinates \$(X,Y)\$ of the previous cell, a counter \$j\$ that holds the number of filled cells in the current area, and a flag \$i\$ that is set when the marked cell is found in the area:
g = (n, X, Y, j = 0, i) => a[n] ? a[j] ? ... : i && g(n + 1) : 1

We test \$a[n]\$ to know if all areas have been processed and we test \$a[j]\$ to know if enough cells have been filled in the current area.
The main part of \$g\$ looks for the next cell of \$m\$ to fill by iterating on all of them:
m.some((r, y) =>          // for each row r[] at position y in m[]:
  r.some((v, x) =>        //   for each cell of value v at position x in r[]:
    ++v |                 //     if this cell is already filled (i.e. v is numeric)
    (X - x) ** 2 +        //     or the squared Euclidean distance between
    (Y - y) ** 2 -        //     (X, Y) and (x, y)
    1 ?                   //     is not equal to 1:
      0                   //       this is an invalid target square: do nothing
    :                     //     else:
      g(                  //       do a recursive call to g:
        r[x] = n,         //         pass n unchanged and fill the cell with n
        x, y,             //         pass the coordinates of the current cell
        j + 1,            //         increment j
        i |               //         update i:
        x + [,y] == a[n]  //         set it if (x, y) = a[n]
      ) ?                 //       if the result of the call is truthy:
        1                 //         return 1
      :                   //       else:
        r[x] = v          //         reset the cell to NaN
  )                       //   end of inner map()
)                         // end of outer map()


text:
Draw a path made by direction changers
This challenge takes place on a grid.
+----------+
|          |
|          |
|          |
|          |
|          |
|          |
|          |
|          |
|          |
+----------+

This one's 10 x 10, but it can be any rectangular shape.
There are four directions on this grid. Up, down, left and right.
The task is to draw a path starting with an upper case direction initial. In this example, will go directly upward from the U.
+----------+
|          |
|          |
|          |
|          |
|          |
|          |
|          |
|          |
|   U      |
+----------+

The path will go upwards and be comprised of full-stop characters (.), until it hits a wall, when it will terminate with an asterisk (*).
+----------+
|   *      |
|   .      |
|   .      |
|   .      |
|   .      |
|   .      |
|   .      |
|   .      |
|   U      |
+----------+

In addition to path starts, there's also direction changers, represented by a lower case direction initial.
+----------+
|          |
|          |
|          |
|   r.....*|
|   .      |
|   .      |
|   .      |
|   .      |
|   U      |
+----------+

Also, an upper case X us an obstacle which will terminate the path.
+----------+
|          |
|          |
|          |
|          |
|   r...*X |
|   .      |
|   .      |
|   .      |
|   U      |
+----------+

Rules

The input is a string consisting of a frame, (consisting of |, - and + characters) containing characters denoting path starts, direction changers, and obstacles.
Your code should add full stop characters to follow the path described by starts and direction changers, and an asterisk when/if the path meets a wall or obstacle.
There can be multiple path starts.
The code will still terminate without error if the path describes a loop.
If a path meets a path start, it will act as a direction changer.
It's code golf, low-byte code and no standard loopholes, please.
I always prefer links to an on-line interpreter.

Test Cases
1: Simple
+----------+
|          |
|          |
|          |
|          |
|          |
|          |
|          |
|          |
|   U      |
+----------+

+----------+
|   *      |
|   .      |
|   .      |
|   .      |
|   .      |
|   .      |
|   .      |
|   .      |
|   U      |
+----------+

2: Right turn
+----------+
|          |
|          |
|          |
|   r      |
|          |
|          |
|          |
|          |
|   U      |
+----------+

+----------+
|          |
|          |
|          |
|   r.....*|
|   .      |
|   .      |
|   .      |
|   .      |
|   U      |
+----------+

3: Crossroads
+----------+
|          |
|          |
|          |
|   r  d   |
|          |
| u    l   |
|          |
|          |
|   U      |
+----------+

+----------+
| *        |
| .        |
| .        |
| . r..d   |
| . .  .   |
| u....l   |
|   .      |
|   .      |
|   U      |
+----------+

4: 4 Crossing paths
+----------+
|      D   |
|          |
|          |
|R         |
|          |
|         L|
|          |
|          |
|   U      |
+----------+

+----------+
|   *  D   |
|   .  .   |
|   .  .   |
|R........*|
|   .  .   |
|*........L|
|   .  .   |
|   .  .   |
|   U  *   |
+----------+

5: First Loop
+----------+
|          |
|          |
|          |
|   r  d   |
|          |
|   u  l   |
|          |
|          |
|   U      |
+----------+

+----------+
|          |
|          |
|          |
|   r..d   |
|   .  .   |
|   u..l   |
|   .      |
|   .      |
|   U      |
+----------+

6: Starter as changer
+----------+
|          |
|          |
|          |
|   L      |
|          |
|          |
|          |
|          |
|   U      |
+----------+

+----------+
|          |
|          |
|          |
|*..L      |
|   .      |
|   .      |
|   .      |
|   .      |
|   U      |
+----------+

7: Straight Loop
+----------+
|          |
|          |
|          |
|          |
|   r  l   |
|          |
|          |
|          |
|   U      |
+----------+

+----------+
|          |
|          |
|          |
|          |
|   r..l   |
|   .      |
|   .      |
|   .      |
|   U      |
+----------+

8: Tight Knot
+----------+
|          |
|          |
|          |
|  d  l    |
|   r u    |
|  r u     |
|          |
|          |
|   U      |
+----------+

+----------+
|    *     |
|    .     |
|    .     |
|  d..l    |
|  .r.u    |
|  r.u     |
|   .      |
|   .      |
|   U      |
+----------+

9: An Obstacle
+----------+
|          |
|          |
|          |
|          |
|   r    X |
|          |
|          |
|          |
|   U      |
+----------+

+----------+
|          |
|          |
|          |
|          |
|   r...*X |
|   .      |
|   .      |
|   .      |
|   U      |
+----------+

10: S Shape
+----------+
|r     d   |
|          |
|  XXXXXXXX|
| d      l |
|ul        |
|XXXXXXX   |
|          |
|R       u |
|          |
+----------+

+----------+
|r.....d   |
|.     *   |
|. XXXXXXXX|
|.d......l |
|ul      . |
|XXXXXXX . |
|        . |
|R.......u |
|          |
+----------+

11: 4-Way Knot
+----------+
|      D   |
|          |
|   r      |
|R    d    |
|          |
|    u    L|
|      l   |
|          |
|   U      |
+----------+

+----------+
|    * D   |
|    . .   |
|   r.....*|
|R....d.   |
|   ....   |
|   .u....L|
|*.....l   |
|   . .    |
|   U *    |
+----------+

12: Busy Junctions
+----------+
|rrrrr rrrd|
| rlrl     |
|ul rrd    |
|ruX X     |
|udl ll    |
|ull       |
|rlr       |
|rdr  d    |
|Uruull    |
+----------+

+----------+
|rrrrr.rrrd|
|.rlrl    .|
|ul rrd   .|
|ruX.X.   .|
|udl.ll   .|
|ull.     .|
|rlr.     .|
|rdr..d   .|
|Uruull   *|
+----------+

13: Starts Into Edge
+----------+
|   U      |
|          |
|          |
|          |
|          |
|          |
|          |
|          |
|          |
+----------+

+----------+
|   U      |
|          |
|          |
|          |
|          |
|          |
|          |
|          |
|          |
+----------+

14: Crossing Dead Paths
+----------+
|          |
|          |
|          |
|      R   |
|          |
|          |
|          |
|          |
|         U|
+----------+

+----------+
|         *|
|         .|
|         .|
|      R..*|
|         .|
|         .|
|         .|
|         .|
|         U|
+----------+

@TFeld Added, thanks!

It seems like all direction changers are always reached in your test cases, which could allow to simplify the algorithm. I'd suggest to add a test case where it's not true.

@Arnauld I'm pretty sure there's some unused direction changers in case 12.

Ah, you're right. I missed that one.

suggested testcase

It is stated that the grid can be any rectangular shape, but all test cases seem to be identical in size and shape.

Suggested testcase based on @gastropner's comment

Can there be multiple of the same capital letters (i.e. 3 U)? Also, can there be any direction change characters that aren't used in the output? If yes to both: suggested test cases.

@KevinCruijssen I will be extending the use cases at some point soon. Some great suggestions. Just so you know, 12 has got some unused direction changers.

Can the input or output be a list of strings or a list of lists of 1-char strings?

@EriktheOutgolfer I don’t see why not.

JavaScript (ES6),  191 183  181 bytes
Thanks to @tsh for helping fix a bug
Takes input as a matrix of characters. Outputs by modifying the input.
f=(a,X,Y,d,n=0)=>a.map((r,y)=>r.map((v,x)=>(a+0)[i=' .*dlurDLUR'.indexOf(v),n]?X?X-x+~-d%2|Y-y+(d-2)%2?0:~i?f(a,x,y,i>2?i&3:d,n+1,r[x]=i?v:'.'):n?a[Y][X]='*':0:i>6&&f(a,x,y,i&3):0))

Try it online!
Commented
f = ( a,                           // a[]  = input matrix
      X, Y,                        // X, Y = coordinates of the previous cell
      d,                           // d    = current direction (0 .. 3)
      n = 0                        // n    = number of iterations for the current path
    ) =>                           //
  a.map((r, y) =>                  // for each row r[] a position y in a[]:
    r.map((v, x) =>                //   for each character v at position x in r[]:
      (a + 0)[                     //
        i = ' .*dlurDLUR'          //     i = index of the character
            .indexOf(v),           //     blocking characters '-', '|' and 'X' gives -1
        n                          //     by testing (a + 0)[n], we allow each cell to be
      ]                            //     visited twice (once horizontally, once vertically)
      ?                            //     if it is set:
        X ?                        //       if this is not the 1st iteration:
          X - x + ~-d % 2 |        //         if x - X is not equal to dx[d]
          Y - y + (d - 2) % 2 ?    //         or y - Y is not equal to dy[d]:
            0                      //           ignore this cell
          :                        //         else:
            ~i ?                   //           if this is not a blocking character:
              f(                   //             do a recursive call:
                a,                 //               pass a[] unchanged
                x, y,              //               pass the coordinates of this cell
                i > 2 ? i & 3 : d, //               update d if v is a direction char.
                n + 1,             //               increment n
                r[x] = i ? v : '.' //               if v is a space, set r[x] to '.'
              )                    //             end of recursive call
            :                      //           else (this is a blocking character):
              n ?                  //             if this is not the 1st iteration:
                a[Y][X] = '*'      //               set the previous cell to '*'
              :                    //             else:
                0                  //               do nothing
        :                          //       else (1st iteration):
          i > 6 &&                 //         if v is a capital letter:
            f(a, x, y, i & 3)      //           do a recursive call with this direction
      :                            //     else ((a + 0)[n] is not set):
        0                          //       we must be in an infinite loop: abort
    )                              //   end of inner map()
  )                                // end of outer map()

btw, [...""+a].map could create an array with at least 2x length of a. I'm not sure if it helps.

(a+0)[n] does save a byte, even though n now needs to be initialized.

Python 2, 283 279 293 288 279 bytes
e=enumerate
def f(M):
 s=[(x,y,c)for y,l in e(M)for x,c in e(l)if'A'<c<'X'];v=set(s)
 for x,y,C in s:
	d=ord(C)%87%5;q=d>1;X,Y=x-d+q*3,y+~-d-q;c=M[Y][X];N=(X,Y,[C,c]['a'<c<'x'])
	if'!'>c:M[Y][X]='.'
	if(c in'-|X')*('/'>M[y][x]):M[y][x]='*'
	if(c in'udlr. *')>({N}<v):v|={N};s+=N,

Try it online!
Takes a list of lists.
Outputs by modifying the input array.

Perl 5, 203 188 166 bytes
$l='\K[ a-z](?=';$t='([-|X])?';$s=$_;/
/;$n='.'x"@-";{$_|=s/(?|R[.*]*$l$t)|$t${l}[.*]*L)|D$n(?:[.*]$n)*$l$n$t)|$t$n$l$n([.*]$n)*U))/$&eq$"?$1?'*':'.':uc$&/es?redo:$s}

TIO
How it works

$s=$_ to save input into $s to restore lowercase changers. $_|=$s because bitwise or with space  will not change . and *, lowercase letters urld will be restored with bitwise or operation.
/\n/;$n='.'x"@-" to get "width" and $n to match any character "width" times
$l='\K[ a-z](?=';$t='([-|X])?' to reduce regex length ; $l to match a lowercase letter urld or a space on a path, $t to match a terminator.

After replacement :
(?|
R[.*]*\K[ a-z](?=([-|X])?)
|
([-|X])?\K[ a-z](?=[.*]*L)
|
D$n(?:[.*]$n)*\K[ a-z](?=$n([-|X])?)
|
([-|X])?$n\K[ a-z](?=$n([.*]$n)*U)
)

switches /e to eval, /s so that . (inside $n) matches also a newline character
$&eq$"?$1?'*':'.':uc$& if matched is a space, if termiator matched * otherwise . otherwise uppercase.

@Arnauld, it works if you input one test case at a time.

yes i posted quickly and couldn't check it's fixed reseting $s in footer. $s is used to save the input and to restaure lowercase letters because are switched to uppercase when drawing the path

Clean, 409 bytes
import StdEnv,Data.List
q=flatlines
$m=foldl(zipWith\a b|a=='*'||b=='*'='*'=max a b)(q m)[q(foldl(\m(_,y,x)=[[if(b<>x||a<>y)if(k=='*')'.'k'*'\\k<-r&b<-[0..]]\\r<-m&a<-[0..]])m(last(takeWhile(not o hasDup)(inits(f 0y 0x)))))\\l<-m&y<-[0..],c<-l&x<-[0..]|isUpper c]
where f a y b x=let(u,v)=(a+y,b+x)in(case toLower((m!!u)!!v)of' '=[((a,b),u,v):f a u b v];'r'=f 0u 1v;'l'=f 0u -1v;'u'=f -1u 0v;'d'=f 1u 0v;_=[])

Try it online!

Python 2, 250 bytes
def f(G,e=enumerate):
 for i,k in e(G):
	for j,l in e(k):
	 v=X=x=y=m,=l,
	 while(m in'-X|')<(l in'DLRU')>(X in v):v+=X,;y,x=zip((1,0,0,-1,y),(0,-1,1,0,x))['DLRU dlru'.find(m)%5];G[i][j]=(m,'.*'[G[i+y][j+x]in'-X|'])[m<'!'];i+=y;j+=x;X=x,i,j;m=G[i][j]

Try it online!
Takes a list of lists of 1-char strings, as explicitly allowed by the OP.
Changes the list in place.
For easier I/O, use this.


text:
Spot all (anti)diagonals with duplicated values
Challenge:
Given a matrix input, determine the amount of diagonals and anti-diagonals with duplicated numbers.
So if we have a matrix like this:
[[aa,ab,ac,ad,ae,af],
 [ba,bb,bc,bd,be,bf],
 [ca,cb,cc,cd,ce,cf],
 [da,db,dc,dd,de,df]]

All diagonals and anti-diagonals would be:
[[aa],[ab,ba],[ac,bb,ca],[ad,bc,cb,da],[ae,bd,cc,db],[af,be,cd,dc],[bf,ce,dd],[cf,de],[df],
 [af],[ae,bf],[ad,be,cf],[ac,bd,ce,df],[ab,bc,cd,de],[aa,bb,cc,dd],[ba,cb,dc],[ca,db],[da]]

Example:
[[1,2,1,2,1,2],
 [1,2,3,4,5,6],
 [6,5,4,3,2,1],
 [2,1,2,1,2,1]]

All diagonals and anti-diagonals would be:
[[1],[2,1],[1,2,6],[2,3,5,2],[1,4,4,1],[2,5,3,2],[6,2,1],[1,2],[1],
 [2],[1,6],[2,5,1],[1,4,2,1],[2,3,3,2],[1,2,4,1],[1,5,2],[6,1],[2]]

Removing all diagonals and anti-diagonals only containing unique numbers:
[[2,3,5,2],[1,4,4,1],[2,5,3,2],[1,4,2,1],[2,3,3,2],[1,2,4,1]]

So the output is the amount of diagonals and anti-diagonals containing duplicated numbers:
6

Challenge rules:

If the input matrix is empty, contains only 1 number, or contains only unique numbers across the entire matrix, the output is always 0.
Input is guaranteed to only contain positive digits [1,9] (unless it's completely empty).
The matrix will always be rectangular (i.e. all the rows are the same length).
I/O is flexible. Input can be taken as a list of lists of integers, or 2D array of integers, or a Matrix-object, as a string, etc. etc. You are also allowed to take one or both of the dimensions of the matrix as additional input if it would save bytes in your language of choice.

General rules:

This is code-golf, so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
Default Loopholes are forbidden.
If possible, please add a link with a test for your code (i.e. TIO).
Also, adding an explanation for your answer is highly recommended.

Test cases:
Input:                     Output:

[[1,2,1,2,1,2],            6
 [1,2,3,4,5,6],
 [6,5,4,3,2,1],
 [2,1,2,1,2,1]]

[[]]                       0

[[1,2],                    0
 [3,4]]

[[1,1],                    2
 [1,1]]

[[9,9,9],                  6
 [9,9,9],
 [9,9,9]]

[[7,7,7,7],                8
 [7,7,7,7],
 [7,7,7,7]]

[[1,1,1],                  1
 [2,3,4],
 [2,5,1]]

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

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

Husk, 9 bytes
#S≠uṁ∂Se↔

Try it online!
Explanation
#S≠uṁ∂Se↔
      S   hook: S f g x = f x (g x)
       e  pair the matrix
        ↔ with its reverse
    ṁ∂    get the antidiagonals of each, in a single list
#         count all diagonals which satisfy the following:
 S        hook: S f g x = f x (g x)
  ≠       diagonal does not equal
   u      itself uniquified?

Would you mind adding an explanation? Let me know when you've done so, then I will move the accepted mark to your answer, since it's shorter than the current Jelly answer. :)

@KevinCruijssen added it in.

R, 92 86 82 78 bytes
function(m,x=row(m),y=col(m),`|`=split,`^`=Map)sum(max^table^c(m|x-y,m|x+y)>1)

Try it online!
Explanation
First, we declare additional variables \$x\$  and \$y\$ that stand for row and column indices, respectively. Then we can delineate the diagonals and anti-diagonals by taking their difference and sum. E.g., for a 4x4 matrix:
\$x-y\$ gives:
0 -1 -2 -3
 1  0 -1 -2
 2  1  0 -1
 3  2  1  0
\$x+y\$ gives:
2  3  4  5
 3  4  5  6
 4  5  6  7
 5  6  7  8
Now split(m, x-y) and split(m, x+y) produce the actual lists of diagonals and anti-diagonals, which we join together.
Finally, we count the entries of the resulting list where duplicates are present.
Thanks for bytes saved:
-4 by CriminallyVulgar
-4 by digEmAll

Guess I can add row and col to my list of 'extremely situational functions'. Really clever solution.

I think you can move the c(m|x-y,m|x+y) straight into the sapply call, remove the l= part. I don't see any failed tests. Try it online!

Yep, that's correct, I just missed that after my first golf, there was only a single l instance remaining.

They must have added the row and column functions to R this morning, because I've never heard of them.

J, 21 20 bytes
-1 byte thanks to Jonah!
1#.|.,&((~:&#~.)/.)]

Try it online!
Explanation:
1#.                   find the sum of the
     ,                concatenation of
       (          )   the result of the verb in the parentheses applied to
                   ]  the input
      &               and
   |.                 the reversed input
        (      )/.    for each diagonal
         ~:&#~.       check if all elements are unique and negate the result

it's kind of crazy that you can't do better than (-.@-:~.) for "the unique items don't match" in J but i've encountered this many times too and i don't think you can... we have = and ~:, on one hand, and -: and <this is missing>.

Actually, managed to shave 1 more byte off: 1#.|.,&((~:&#~.)/.)].  Try it online!

@Jonah: cool use of &, thanks!

Japt, 31 bytes
ËcUî
ËéEÃÕc¡XéYnÃÕ mf fÊk_eZâÃl

Try all test cases
Explanation:
Ëc                            #Pad each row...
  Uî                          #With a number of 0s equal to the number of rows

ËéEÃÕ                         #Get the anti-diagonals:
ËéEÃ                          # Rotate each row right a number of times equal to the row's index
    Õ                         # Get the resulting columns
     c                        #Add to that...
      ¡XéYnÃÕ                 #The diagonals:
      ¡XéYnÃ                  # Rotate each row left a number of times equal to the row's index
            Õ                 # Get the resulting columns
              mf              #Remove the 0s from each diagonal
                 fÊ           #Remove the all-0 diagonals
                   k_   Ã     #Remove the ones where:
                     eZâ      # The list contains no duplicates
                         l    #Return the number of remaining diagonals

I also tried a version based on Kirill L.'s Haskell answer, but couldn't find a good way to "group by a function of the X and Y indices" and the alternative I found wasn't good enough.

31 bytes

Jelly, 10 bytes
ŒD;ŒdQƑÐḟL

Try it online! or Check out the test suite!
Alternatives:
ŒD;ŒdQƑ€¬S
ŒD;ŒdQƑ€ċ0

How it works?
ŒD;ŒdQƑÐḟL – Monadic link / Full program.
  ;        – Join:
ŒD           – The diagonals
             with
   Œd        – The anti-diagonals.
       Ðḟ  – Discard the lists that are not:
     QƑ      – Invariant under deduplication.
         L – Length (count them).

JavaScript (ES6),  107 105 101  98 bytes
f=(m,d=s=1)=>(m+0)[s-=~d/2]?m.some(o=(r,y)=>!r.every((v,x)=>x+d*y+m.length-s?1:o[v]^=1))+f(m,-d):0

Try it online!
Note
The way this code is golfed, the anti-diagonal consisting of the sole bottom-left cell is never tested. That's OK because it can't possibly contain duplicated values.
Commented
f = (                    // f = recursive function taking:
  m,                     //   m[] = input matrix
  d =                    //   d   = direction (1 for anti-diagonal or -1 for diagonal)
  s = 1                  //   s   = expected diagonal ID, which is defined as either the sum
) =>                     //         or the difference of x and y + the length of a row
  (m + 0)[               //
    s -= ~d / 2          // increment s if d = -1 or leave it unchanged otherwise
  ] ?                    // if s is less than twice the total number of cells:
    m.some(o =           //   o = object used to store encountered values in this diagonal
    (r, y) =>            //   for each row r[] at position y in m[]:
      !r.every((v, x) => //     for each cell of value v at position x in r[]:
        x + d * y +      //       x + d * y + m.length is the ID of the diagonal
        m.length - s ?   //       if it's not equal to the one we're looking for:
          1              //         yield 1
        :                //       else:
          o[v] ^= 1      //         toggle o[v]; if it's equal to 0, v is a duplicate and
                         //         every() fails which -- in turn -- makes some() succeed
      )                  //     end of every()
    )                    //   end of some()
    + f(m, -d)           //   add the result of a recursive call in the opposite direction
  :                      // else:
    0                    //   stop recursion

05AB1E, 25 bytes
í‚εεygÅ0«NFÁ]€ø`«ʒ0KDÙÊ}g

Try it online!
or as a Test Suite
Explanation
í                          # reverse each row in input
 ‚                         # and pair with the input
  ε                        # for each matrix
   ε                       # for each row in the matrix
    ygÅ0«                  # append len(row) zeroes
         NFÁ               # and rotate it index(row) elements to the right
            ]              # end loops
             €ø            # transpose each matrix
               `«          # append them together
                 ʒ     }   # filter, keep only rows that
                  0K       # when zeroes are removed
                    DÙÊ    # are not equal to themselves without duplicate values
                        g  # push length of the result

I feel like I've missed something here.
Need to try and golf this more later.

Doesn't help at all, but rotate N left would be N._ now. So í‚εεygÅ0«N._] also works. Can also remove the flatten with this new change... still no byte savings though: í‚vyεygÅ0«N._}ø}«ʒ0KDÙÊ}g

@MagicOctopusUrn: Interesting. I had missed that command. Only a left though. Thats weird.

@Emigna You can go right with N(._ I guess, but your NFÁ} is the same length, and even shorter in this case due to ] closing the loop and maps simultaneously. Overall the use of ._ is only useful when going left to save 1 byte, in comparison to NFÀ}.

@KevinCruijssen: Ah, cool. Although as you say, not very useful.

Python 2, 144 136 bytes
lambda m:sum(l(set(d))<l(d)for d in[[r[i*x+o]for i,r in enumerate(m)if-1<i*x+o<l(r)]for o in range(-l(`m`),l(`m`))for x in[-1,1]])
l=len

Try it online!

Octave, 98 bytes
@(A)nnz([(q=@(Q)arrayfun(@(n)nnz(z=diag(Q,n))-nnz(unique(z)),-([m,n]=size(Q)):n))(A),q(rot90(A))])

Try it online!

Are arrays indeed fun? ;p

And thanks for preparing the test cases in Octave format!

@KevinCruijssen Not just arrays! You can have cellfun too, and for the masochistic, structfun as well. In Octave, it's either a for-loop or having fun!

And don’t forget b-sx-fun!

Haskell, 118 112 bytes
import Data.List
r#(a:b)=sum[1|(/=)=<<nub$[h|h:_<-a:r]]+[t|_:t<-a:r]#b
[]#_=0
a#_=a#[[]]
h x=[]#x+[]#(reverse x)

Try it online!
r#(a:b)                      -- function '#' calculates the ant-diagonals of a matrix
                             -- where 'a' is the first row and 'b' all the others
                             -- as we recursively walk down the rows of the matrix,
                             -- 'r' holds the rows from before with the respective
                             -- head dropped
                             --
          [h|h:_<-a:r]       -- if the heads of the the current row and the rows
                             -- before
       (/=)=<<nub$           -- contain duplicates
    [1|                ]     -- make a singleton list [1] (else the empty list)
 sum                         -- and take the sum thereof
      +                      -- and add
             #               -- a recursive call with
 [t|_:t<-a:r]                -- the tails of the current row and the rows before
              b              -- and the rows below
                             --
[]#_=0                       -- base case if there aren't any tails anymore, return 0
a#_=a#[[]]                   -- if there are tails, but no further rows below,
                             -- continue with tails

h x=[]#x+[]#(reverse x)      -- main function, call '#' with input matrix 'x'
                             -- and the reverse of it to get the number of diagonals
                             -- and anti-diagonals. Recursion starts with no
                             -- rows before the 1st row.

-- example trace of function '#'
-- input matrix:
--   [[1,2,3,4],
--    [5,6,7,8],
--    [9,9,9,9]]
--
--  | r         a          b              a:r          heads   tails (r of next call)
-- -+----------------------------------------------------------------------------------
-- 1| []        [1,2,3,4]  [[5,6,7,8],    [[1,2,3,4]]  [1]     [[2,3,4]]
--  |                       [9,9,9,9]]
--  |
-- 2| [[2,3,4]]  [5,6,7,8]  [[9,9,9,9]]   [[5,6,7,8],  [5,2]   [[6,7,8],
--  |                                      [2,3,4  ]]           [3,4  ]]
--  |
-- 3| [[6,7,8],  [9,9,9,9]  []            [[9,9,9,9],  [9,6,3] [[9,9,9],
--  |  [3,4  ]]                            [6,7,8  ],           [7,8  ]
--  |                                      [3,4    ],           [4    ]
--  |
--  | ....

Charcoal, 61 56 53 bytes
Ｆ²ＦＬθＦＬ§θ⁰Ｆ⟦⁻κ×⊖⊗ιλ⟧⊞υ⊞Ｏ⎇∧λ﹪⁺μιＬθ⊟υ⟦⟧§§θμλＩＬΦυ⊙ι‹⌕ιλμ

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

Loop over forward and reverse diagonals; i=0 represents forward diagonals while i=1 represents reverse diagonals.
ＦＬθ

Loop over each row index. This represents the index of the start of the diagonal.
ＦＬ§θ⁰«

Loop over each column index.
Ｆ⟦⁻κ×⊖⊗ιλ⟧

Calculate the row index of the diagonal at this column index. I use a for loop over a single-element array instead of an assignment as this avoids having to wrap the assignment into a block with the following statement, thus saving a byte.
⎇∧λ﹪⁺μιＬθ

Check whether this is the first column or the diagonal is about to wrap around between bottom and top.
⊟υ

If it isn't then pop the last list from the list of lists.
⟦⟧

if it is then start a new empty list.
⊞Ｏ...§§θμλ

Add the current diagonal entry to that list.
⊞υ

And push that list (back) to the list of lists.
ＩＬΦυ⊙ι‹⌕ιλμ

Count the number of lists that contain duplicates.
Let's take an example when i=0 and k=1. This means that we've already collected two diagonals, [[1,1,5,2],[9,4,3,5]]. Here's our input:
 1 8 4 2 9 4 4 4
[5]1 2 7 7 4 2 3
 1 4 5 2 4 2 3 8
 8 5 4 2 3 4 1 5

We then loop l from 0 to 7. This advances both the row and column by 1 each time:
 1 8 4 2 9 4 4 4
[5]1 2 7 7 4 2 3
 1[4]5 2 4 2 3 8
 8 5[4]2 3 4 1 5

The list is now [[1,1,5,2],[9,4,3,5],[5,4,4]]. However when l is 3, we have k+l=4, a multiple of the height of the array. This means that we need to start a new list: [[1,1,5,2],[9,4,3,5],[5,4,4],[]]. We then continue to collect diagonal elements:
 1 8 4[2]9 4 4 4
[5]1 2 7[7]4 2 3
 1[4]5 2 4[2]3 8
 8 5[4]2 3 4[1]5

The list is now [[1,1,5,2],[9,4,3,5],[5,4,4],[2,7,2,1]]. Now when l is 7, we have k+l=8, another multiple of the height of the array. This means that we need to start a new list, which ends up with the last element of that diagonal: [[1,1,5,2],[9,4,3,5],[5,4,4],[2,7,2,1],[4]].
 1 8 4[2]9 4 4[4]
[5]1 2 7[7]4 2 3
 1[4]5 2 4[2]3 8
 8 5[4]2 3 4[1]5

By collecting wrapping diagonals starting at the first element of each row we eventually accumulate all of the diagonals of the array.

Wolfram Language (Mathematica), 99 98 96 94 83 bytes
Count[DuplicateFreeQ@Diagonal[#,i]~Table~{i,-t,t=#~Total~2}&/@{#,Reverse@#},1<0,2]&

Try it online!

Function[a,a~Diagonal~#&/@Range[t=-#~Total~2,-t]] gets all diagonals of a-- which works because #~Total~2 is larger than any dimension of a.

TSQL, 140 128 bytes
Found a way to golf 12 characters. This is no longer the longest solution.
Golfed:
SELECT sum(iif(y+x=j+i,1,0)+iif(y-x=j-i,1,0))FROM
@,(SELECT x i,y j,max(y)over()m,v w
FROM @)d WHERE(x*y=0or m=y)and v=w and x<i

Ungolfed:
DECLARE @ table(v int,x int,y int)
-- v = value
-- x = row
-- y = column
INSERT @ values
(1,0,0),(2,0,1),(1,0,2),(2,0,3),(1,0,4),(2,0,5),
(1,1,0),(2,1,1),(3,1,2),(4,1,3),(5,1,4),(6,1,5),
(6,2,0),(5,2,1),(4,2,2),(3,2,3),(2,2,4),(1,2,5),
(2,3,0),(1,3,1),(2,3,2),(1,3,3),(2,3,4),(1,3,5)

SELECT sum(iif(y+x=j+i,1,0)+iif(y-x=j-i,1,0))
FROM @,(SELECT x i,y j,max(y)over()m,v w FROM @)d
WHERE
  (x*y=0or m=y)
  and v=w
  and x<i

Try it out

Perl 5, 89 82 bytes
map{$i=0;map{$a[$x+$i].=$_;$b[@F-$x+$i++].=$_}/\d/g;$x++}@F;$_=grep/(.).*\1/,@a,@b

TIO

APL+WIN, 69 bytes
Prompts for a 2d matrix of the form 4 6⍴1 2 1 2 1 2 1 2 3 4 5 6 6 5 4 3 2 1 2 1 2 1 2 1
This yields:
1 2 1 2 1 2
1 2 3 4 5 6
6 5 4 3 2 1
2 1 2 1 2 1

+/~(v⍳¨v)≡¨⍳¨⍴¨v←(v←⊂[1](⌽0,⍳1↓n)⌽(n⍴0),m,((n←0 ¯1+↑⍴m)⍴0),⌽m←⎕)~¨0

Try it online! Courtesy of Dyalog Classic
Explanation:
(⌽0,⍳1↓n)⌽(n⍴0),m pad m with zeros to isolate diagonals

((n←0 ¯1+↑⍴m)⍴0),⌽m pad rotated m with zeros to isolate anti-diagonals

Yields:
1 2 1 2 1 2 0 0 0 2 1 2 1 2 1 0 0 0
0 1 2 3 4 5 6 0 0 0 6 5 4 3 2 1 0 0
0 0 6 5 4 3 2 1 0 0 0 1 2 3 4 5 6 0
0 0 0 2 1 2 1 2 1 0 0 0 1 2 1 2 1 2

v←(v←⊂[1](.....)~¨0 enclose the diagonals as a nested vector with padded zeros removed

+/~(v⍳¨v)≡¨⍳¨⍴¨v identify diagnols with duplicate entries and sum


text:
The Path Of The Wildebeest
Golf a program or function which gives the \$n^{\text{th}}\$ location of the wildebeest who starts at square \$1\$ on an infinite chessboard which is numbered in an anti-clockwise square spiral, where the wildebeest always visits the lowest numbered square she can reach that she has not yet visited.
Inspiration: The Trapped Knight and OEIS A316667.
Edit: This sequence is now on the OEIS as A323763.
The code may produce the \$n^{\text{th}}\$ location, the first \$n\$ locations, or generate the sequence taking no input.
Feel free to give her location after (or up to) \$n\$ leaps instead, but if so please state this clearly in your answer and make sure that an input of \$n=0\$ yields 1 (or [1] if appropriate).
This is code-golf, so the aim is to produce working code in as few bytes as possible in your chosen language.
Note: the wildebeest becomes trapped (much like the knight does at his \$2016^{\text{th}}\$ location, square \$2084\$, and the camel does at his \$3723^{\text{rd}}\$, square \$7081\$) at her \$12899744968^{\text{th}}\$ location on square \$12851850258\$. The behaviour of your code may be undefined for \$n\$ larger than this. (Thanks to Deadcode for the C++ code that found this!)
Detail
The board looks like the below, and continues indefinitely:
101 100  99  98  97  96  95  94  93  92  91
102  65  64  63  62  61  60  59  58  57  90
103  66  37  36  35  34  33  32  31  56  89
104  67  38  17  16  15  14  13  30  55  88
105  68  39  18   5   4   3  12  29  54  87
106  69  40  19   6   1   2  11  28  53  86
107  70  41  20   7   8   9  10  27  52  85
108  71  42  21  22  23  24  25  26  51  84
109  72  43  44  45  46  47  48  49  50  83
110  73  74  75  76  77  78  79  80  81  82
111 112 113 114 115 116 117 118 119 120 121

A wildebeest is a "gnu" fairy chess piece - a non-standard chess piece which may move both as a knight (a \$(1,2)\$-leaper) and as a camel (a \$(1,3)\$-leaper).
As such she could move to any of these locations from her starting location of \$1\$:
  .   .   .   .   .   .   .   .   .   .   .
  .   .   .   .  35   .  33   .   .   .   .
  .   .   .   .  16   .  14   .   .   .   .
  .   .  39  18   .   .   .  12  29   .   .
  .   .   .   .   .  (1)  .   .   .   .   .
  .   .  41  20   .   .   .  10  27   .   .
  .   .   .   .  22   .  24   .   .   .   .
  .   .   .   .  45   .  47   .   .   .   .
  .   .   .   .   .   .   .   .   .   .   .

The lowest of these is \$10\$ and she has not yet visited that square, so \$10\$ is the second term in the sequence.
Next she could move from \$10\$ to any of these locations:
  .   .   .   .   .   .   .   .   .   .   .
  .   .   .   .   .   .  14   .  30   .   .
  .   .   .   .   .   .   3   .  29   .   .
  .   .   .   .   6   1   .   .   .  53  86
  .   .   .   .   .   .   . (10)  .   .   .
  .   .   .   .  22  23   .   .   .  51  84
  .   .   .   .   .   .  47   .  49   .   .
  .   .   .   .   .   .  78   .  80   .   .
  .   .   .   .   .   .   .   .   .   .   .

However, she has already visited square \$1\$ so her third location is square \$3\$, the lowest she has not yet visited.

The first \$100\$ terms of the path of the wildebeest are:
1, 10, 3, 6, 9, 4, 7, 2, 5, 8, 11, 14, 18, 15, 12, 16, 19, 22, 41, 17, 33, 30, 34, 13, 27, 23, 20, 24, 44, 40, 21, 39, 36, 60, 31, 53, 26, 46, 25, 28, 32, 29, 51, 47, 75, 42, 45, 71, 74, 70, 38, 35, 59, 56, 86, 50, 78, 49, 52, 80, 83, 79, 115, 73, 107, 67, 64, 68, 37, 61, 93, 55, 58, 54, 84, 48, 76, 43, 69, 103, 63, 66, 62, 94, 57, 87, 125, 82, 118, 77, 113, 72, 106, 148, 65, 97, 137, 91, 129, 85

The first \$11\$ leaps are knight moves so the first \$12\$ terms coincide with A316667.

Comments are not for extended discussion; this conversation has been moved to chat.

JavaScript (Node.js),  191 ... 166  164 bytes
Saved 2 bytes thanks to @grimy.
Returns the \$N\$th term.
n=>(g=(x,y)=>n--?g(Buffer('QPNP1O?O@242Q3C3').map(m=c=>g[i=4*((x+=c%6-2)*x>(y+=c%7-2)*y?x:y)**2,i-=(x>y||-1)*(i**.5+x+y)]|i>m||(H=x,V=y,m=i))&&H,V,g[m]=1):m+1)(1,2)

Try it online! or See a formatted version
How?
Spiral indices
In order to convert the coordinates \$(x,y)\$ into the spiral index \$I\$, we first compute the layer \$L\$ with:
$$L=\max(|x|,|y|)$$
Which gives:
$$\begin{array}{c|ccccccc}
&-3&-2&-1&0&+1&+2&+3\\
\hline
-3&3&3&3&3&3&3&3\\
-2&3&2&2&2&2&2&3\\
-1&3&2&1&1&1&2&3\\
0&3&2&1&0&1&2&3\\
+1&3&2&1&1&1&2&3\\
+2&3&2&2&2&2&2&3\\
+3&3&3&3&3&3&3&3
\end{array}$$
We then compute the position \$P\$ in the layer with:
$$P=\begin{cases}
2L+x+y&\text{if }x>y\\
-(2L+x+y)&\text{if }x\le y
\end{cases}$$
Which gives:
$$\begin{array}{c|ccccccc}
&-3&-2&-1&0&+1&+2&+3\\
\hline
-3&0&1&2&3&4&5&6\\
-2&-1&0&1&2&3&4&7\\
-1&-2&-1&0&1&2&5&8\\
0&-3&-2&-1&0&3&6&9\\
+1&-4&-3&-2&-3&-4&7&10\\
+2&-5&-4&-5&-6&-7&-8&11\\
+3&-6&-7&-8&-9&-10&-11&-12
\end{array}$$
The final index \$I\$ is given by:
$$I=4L^2-P$$
NB: The above formula gives a 0-indexed spiral.
In the JS code, we actually compute \$4L^2\$ right away with:
i = 4 * (x * x > y * y ? x : y) ** 2

And then subtract \$P\$ with:
i -= (x > y || -1) * (i ** 0.5 + x + y)

Moves of the wildebeest
Given the current position \$(x,y)\$, the 16 possible target squares of the wildebeest are tested in the following order:
$$\begin{array}{c|cccccccc}
&-3&-2&-1&x&+1&+2&+3\\
\hline
-3&\cdot&\cdot&9&\cdot&11&\cdot&\cdot\\
-2&\cdot&\cdot&8&\cdot&10&\cdot&\cdot\\
-1&7&6&\cdot&\cdot&\cdot&12&13\\
y&\cdot&\cdot&\cdot&\bullet&\cdot&\cdot&\cdot\\
+1&5&4&\cdot&\cdot&\cdot&14&15\\
+2&\cdot&\cdot&2&\cdot&0&\cdot&\cdot\\
+3&\cdot&\cdot&3&\cdot&1&\cdot&\cdot
\end{array}$$
We walk through them by applying 16 pairs of signed values \$(dx,dy)\$. Each pair is encoded as a single ASCII character.
 ID | char. | ASCII code | c%6-2 | c%7-2 | cumulated
----+-------+------------+-------+-------+-----------
  0 |  'Q'  |     81     |   +1  |   +2  |  (+1,+2)
  1 |  'P'  |     80     |    0  |   +1  |  (+1,+3)
  2 |  'N'  |     78     |   -2  |   -1  |  (-1,+2)
  3 |  'P'  |     80     |    0  |   +1  |  (-1,+3)
  4 |  '1'  |     49     |   -1  |   -2  |  (-2,+1)
  5 |  'O'  |     79     |   -1  |    0  |  (-3,+1)
  6 |  '?'  |     63     |   +1  |   -2  |  (-2,-1)
  7 |  'O'  |     79     |   -1  |    0  |  (-3,-1)
  8 |  '@'  |     64     |   +2  |   -1  |  (-1,-2)
  9 |  '2'  |     50     |    0  |   -1  |  (-1,-3)
 10 |  '4'  |     52     |   +2  |   +1  |  (+1,-2)
 11 |  '2'  |     50     |    0  |   -1  |  (+1,-3)
 12 |  'Q'  |     81     |   +1  |   +2  |  (+2,-1)
 13 |  '3'  |     51     |   +1  |    0  |  (+3,-1)
 14 |  'C'  |     67     |   -1  |   +2  |  (+2,+1)
 15 |  '3'  |     51     |   +1  |    0  |  (+3,+1)

We keep track of the minimum encountered value in \$m\$ and of the coordinates of the corresponding cell in \$(H,V)\$.
Once the best candidate has been found, we mark it as visited by setting a flag in the object \$g\$, which is also our main recursive function.
On the first iteration, we start with \$x=1\$ and \$y=2\$. This ensures that the first selected cell is \$(0,0)\$ and that it's the first cell to be marked as visited.

So much golfing, can't wait for the rundown of how all the magic works!

did you have to use Buffer to force each character to be interpreted as a single byte?

@Jonah Although it's been deprecated, the Buffer constructor still accepts a string. So, yes, this is a rather cheap way to convert it to a list of bytes -- as opposed to [..."string"].map(c=>do_something_with(c.charCodeAt())).

-2 bytes on the coordinate encoding: TIO

@Grimy Nicely done!

05AB1E, 77 65 58 57 52 bytes
Xˆ0UF3D(Ÿ0KãʒÄ1¢}εX+}Dε·nàDtyÆ+yO·<.±*->}D¯KßDˆkèU}¯

-6 bytes thanks to @Arnauld by using a port of his formula.
Outputs the first \$n+1\$ values as a list (of decimals).
Try it online (the ï in the footer removes the .0 to make the output more compact, but feel free to remove it to see the actual result).
Code explanation:
Xˆ             # Put integer 1 in the global_array (global_array is empty by default)
0U             # Set variable `X` to 0 (`X` is 1 by default)
F              # Loop the (implicit) input amount of times:
 3D(Ÿ          #  Push the list in the range [-3,3]: [-3,-2,-1,0,1,2,3]
     0K        #  Remove the 0: [-3,-2,-1,1,2,3]
       ã       #  Cartesian product with itself, creating each possible pair: [[3,3],[3,2],[3,1],[3,-1],[3,-2],[3,-3],[2,3],[2,2],[2,1],[2,-1],[2,-2],[2,-3],[1,3],[1,2],[1,1],[1,-1],[1,-2],[1,-3],[-1,3],[-1,2],[-1,1],[-1,-1],[-1,-2],[-1,-3],[-2,3],[-2,2],[-2,1],[-2,-1],[-2,-2],[-2,-3],[-3,3],[-3,2],[-3,1],[-3,-1],[-3,-2],[-3,-3]]
        ʒ   }  #  Filter this list of pairs by:
         Ä     #   Where the absolute values of the pair
          1¢   #   Contains exactly one 1
               #  (We now have the following pairs left: [[3,1],[3,-1],[2,1],[2,-1],[1,3],[1,2],[1,-2],[1,-3],[-1,3],[-1,2],[-1,-2],[-1,-3],[-2,1],[-2,-1],[-3,1],[-3,-1]])
 εX+}          #  Add the variable `X` (previous coordinate) to each item in the list
 D             #  Duplicate this list of coordinates
  ε            #  Map each `x,y`-coordinate to:
   ·           #   Double both the `x` and `y` in the coordinate
    n          #   Then take the square of each
     à         #   And then pop and push the maximum of the two
   Dt          #   Duplicate this maximum, and take its square-root
     yÆ        #   Calculate `x-y`
       +       #   And add it to the square-root
   yO          #   Calculate `x+y`
     ·         #   Double it
      <        #   Decrease it by 1
       .±      #   And pop and push its signum (-1 if < 0; 0 if 0; 1 if > 0)
   *           #   Multiply these two together
    -          #   And subtract it from the duplicated maximum
   >           #   And finally increase it by 1 to make it 1-based instead of 0-based
  }D           #  After the map: Duplicate that list with values
    ¯K         #  Remove all values that are already present in the global_array
      ß        #  Pop the list of (remaining) values and push the minimum
       Dˆ      #  Duplicate this minimum, and pop and add the copy to the global_array
         k     #  Then get its index in the complete list of values
          è    #  And use that index to get the corresponding coordinate
           U   #  Pop and store this coordinate in variable `X` for the next iteration
}¯             # After the outer loop: push the global_array (which is output implicitly)

General explanation:
We hold all results (and therefore values we've already encountered) in the global_array, which is initially started as [1].
We hold the current \$x,y\$-coordinate in variable X, which is initially [0,0].
The list of coordinates we can reach based on the current \$x,y\$-coordinate are:
[[x+3,y+1], [x+3,y-1], [x+2,y+1], [x+2,y-1], [x+1,y+3], [x+1,y+2], [x+1,y-2], [x+1,y-3], [x-1,y+3], [x-1,y+2], [x-1,y-2], [x-1,y-3], [x-2,y+1], [x-2,y-1], [x-3,y+1], [x-3,y-1]]

The list I mention in the code explanation above holds these values we can jump to, after which the current \$x,y\$ (stored in variable X) is added.
Then it will calculate the spiral values based on these \$x,y\$-coordinates. It does this by using the following formula for a given \$x,y\$-coordinate:
$${T = max((2 * x) ^ 2, (2 * y) ^ 2)}$$
$${R = T - (x - y + √T) * signum((x + y) * 2 - 1) + 1}$$
Which is the same formula @Arnauld is using in his answer, but written differently to make use of 05AB1E's builtins for double, square, -1, +1, etc.
(If you want to see just this spiral part of the code in action: Try it online.)
After we've got all the values we can reach for the given \$x,y\$-coordinate, we remove all values that are already present in the global_array, and we then get the minimum of the (remaining) values.
This minimum is then added to the global_array, and variable X is replaced with the \$x,y\$-coordinate of this minimum.
After we've looped the input amount of times, the program will output this global_array as result.

FWIW, here is a port of my own formula to convert the coordinates into spiral indices. It's 5 bytes shorter but yields floats. (I don't know if this is a problem or not.)

(Note that $y$ in your code is $-y$ in mine.)

Coconut, 337 276 bytes
import math
def g((x,y))=
 A=abs(abs(x)-abs(y))+abs(x)+abs(y)
 int(A**2+math.copysign(A+x-y,.5-x-y)+1)
def f():
 p=x,y=0,0;s={p};z=[2,3,1,1]*2
 while 1:yield g(p);p=x,y=min(((a+x,b+y)for a,b in zip((1,1,2,-2,-1,-1,3,-3)*2,z+[-v for v in z])if(a+x,b+y)not in s),key=g);s.add(p)

Returns a generator of values. Could probably be golfed more. (Especially the sequence of difference tuples.) Spiral algorithm taken from this math.se answer.
Try it online!

for a,b in ( -> for a,b in( (maybe you can golf the delta tuple of tuples itself too)

No need for q and a zip is shorter for the tuples: 306 bytes may still be golfable of course

...how about this for 284? EDIT... this for 278

FWIW, that math.se answer has x and y swapped and both negative relative to the coordinate system in this challenge (where positive x is right and y is up). Not that it'd make any difference due to the symmetries, but still.

@Deadcode That's why my code says -x-y instead of x+y. x-y turns into itself after flipping the order and the signs.

0.5->.5 for another byte save; A**2->A*A for one more.

...infact .5-x-y gives yet one more :)