text:
Are my triangles similar?
Given (in any structure; flat list, two lists of lists, a tuple of matrices, a 3D array, complex numbers,…) the coordinates for two non-degenerate triangles ABC=[[Ax,Ay],[Bx,By],[Cx,Cy]] and PQR=[[Px,Py],[Qx,Qy],[Rx,Ry]], determine if they are similar, that is,

they both have the same shape, or one has the same shape as the mirror image of the other. More precisely, one can be obtained from the other by uniformly scaling (enlarging or reducing), possibly with additional translation, rotation and reflection.[Wikipedia]

You may assume that all coordinates are integers.
You must either return a truthy/falsey value indicating similar/dissimilar respectively, or two consistent values; please state your choice.
Failing on some cases due to limitations in floating point precision  is acceptable so long as the algorithm is correct in principle.
Bonus task: Add a comment to this post stating whether you would like the same challenge generalised to polygons in N-space.
Walked-through example case
ABC=[[0,0],[1,0],[0,1]] and PQR=[[1,0],[-1,0],[1,-2]]

Reflect ABC in the x-axis: [[0,0],[-1,0],[0,1]]
Reflect in the y-axis: [[0,0],[-1,0],[0,-1]]
Enlarge by a factor of 2: [[0,0],[-2,0],[0,-2]]
Translate right by 1 unit: [[1,0],[-1,0],[1,-2]]

This gives us PQR.
Test cases
Similar
[[8,4],[5,-5],[0,0]] and [[-4,-1],[5,-1],[-1,5]]
[[-2,1],[4,-2],[6,2]] and [[-1,-1],[2,-1],[-1,1]]
[[-1,0],[1,0],[0,2]] and [[-2,5],[2,5],[0,1]]
Dissimilar
[[0,0],[-1,0],[0,1]] and [[1,0],[-1,0],[2,-3]]
[[2,1],[4,2],[6,2]] and [[-1,-1],[2,-1],[-1,1]]
[[-1,0],[1,0],[0,3]] and [[-2,5],[2,5],[0,1]]

Are flat-list input formats allowed, i.e. [1,2,3,4,5,6] instead of [[1,2],[3,4],[5,6]]?

@MamaFunRoll Sure.

Suggested test case: two similar isosceles triangles [[-1,0],[1,0],[0,2]] and [[-2,5],[2,5],[0,1]]

@Adám Isosceles triangles have fewer unique edges and angles. This may pose a problem when your approach includes counting the number of unique features of the triangles.

@Jitse Added both similar and dissimilar isosceles triangles.

it looks like a number of solutions unfortunately will reject some similar triangles due to float limitation if a few more test cases are tried. For example, passing in the first test case with inputs swapped can reveal this. I think this applies to any solution that uses square roots or abs for distance in a language that represents it with finite precision.

@xnor Thank you for pointing that out. I've added a clause to permit such failures.

MATL, 15 12 bytes
,i4:)d|S]/da

The program inputs two  3×1 vectors of complex numbers representing the coordinates; and outputs 0 for similar, 1 for not similar.
Try it online! Or verify all test cases.
Explanation
The code checks if the side lengths, sorted for each triangle, are proportional between the two triangles.
,      % Do twice
  i    %   Take input: 3×1 vector of complex numbers
  4:)  %   Modular index to repeat 1st number after the 3rd. Gives a 4×1 vector
  d    %   Consecutive differences
  |    %   Absolute value, element-wise
  S    %   Sort
]      % End
/      % Divide, element-wise
d      % Consecutive differences
a      % Any: gives 0 if and only if all values are 0
       % Implicit display

05AB1E, 11 bytes
Port of Luis Mendo's MATL answer.
Outputs 1 for similar, 0 otherwise.
vyĆüαnO{}/Ë

Try it online!

Jelly, 9 bytes
ṁ4IAṢ)÷/E

A monadic Link accepting a list of two triangles - lists of complex numbers (coordinates on the Cartesian plane). Similar triangles yield 1, dissimilar ones yield 0.
Try it online! (includes footer to translate from coordinate pairs for ease of use)
Or see the test-suite.
How?
ṁ4IAṢ)÷/E - Link: list       [[a, b, c], [d, e, f]]
     )    - for each:
ṁ4        -   mould like 4   [[a, b, c, a], [d, e, f, d]]
  I       -   deltas         [[b-a,c-b,a-c],[e-d,f-e,d-f]] (i.e. vectors of sides as complex numbers)
   A      -   absolute value (i.e. side lengths)
    Ṣ     -   sort           (ordered side lengths = [[G, H, I], [J, K, L]])
       /  - reduce by:
      ÷   -   division       [G÷J, H÷K, I÷L]
        E - all equal?

JavaScript (ES7),  122 120 117  112 bytes
Takes input as (a)(b), where both parameters are in the format used in the challenge.
Returns false for similar or true for dissimilar.
a=>b=>(g=a=>a.map((c,i)=>(h=j=>(c[j]-a[-~i%3][j])**2)(0)+h(1)).sort((a,b)=>a-b))(a).some((x,i)=>a-(a=x/g(b)[i]))

Try it online!
Commented
a => b =>                    // a[] = 1st triangle; b[] = 2nd triangle
  ( g = a =>                 // g is a helper function that computes the squared lengths
                             // of the sides of the triangle a[] and sorts them:
      a.map((c, i) =>        //   for each pair c[] of coordinates [x,y] at position i:
        ( h = j =>           //     h is a helper function that computes ...
          ( c[j] -           //       ... the difference between either x(i) and x(i+1)
            a[-~i % 3][j]    //           or y(i) and y(i+1) (in a circular way)
          ) ** 2             //       and squares it
        )(0)                 //     compute (x(i) - x(i+1))²
        + h(1)               //     add (y(i) - y(i+1))²
      )                      //   end of map()
      .sort((a, b) => a - b) //   sort the results in numerical order
  )(a)                       // computes the squared lengths for a[]
  .some((x, i) =>            // for each squared length x at position i:
    a -                      //   compute the difference between the previous ratio
    (a = x / g(b)[i])        //   and the new ratio defined as x / g(b)[i]
                             //   (always NaN for the 1st iteration)
  )                          // end of some()

Python 3, 85 bytes
lambda a:len({i/j for i,j in zip(*[sorted(map(abs,[p-q,q-r,r-p]))for p,q,r in a])})<2

Try it online!
-17 bytes thanks to FlipTack
-7 bytes thanks to tsh
Takes a list of lists of coordinates represented by complex numbers as input. Calculates the distances between all points in each set and sorts by magnitude. Then, it checks for all pairs of distances between the two sets if there is a common scaling factor. If so, the triangles are similar.

103 bytes with complex numbers.

@FlipTack very nice, thanks!

85 bytes

@tsh Thanks, good find!

J, 39 34 32 bytes
1=[:#@~.%&([:/:~#:@3 5 6|@-/@#])

Try it online!
Takes input as 3 complex numbers for each triangle.
For each triangle, we get each possible pair of points using a boolean mask filter.  Ie, #:@3 5 6 translates 3, 5, and 6 to their binary representations, and each row selects one possible pair:
0 1 1
1 0 1
1 1 0

We then get the euclidean distances between of each of these pairs |@-/ and then sort them /:~.
Finally we pairwise divide the 3 sorted sides of the triangle %, take the length of the unique elements of that result #@~. and test if it equals one 1=.

APL+WIN, 40 bytes
Prompts for the co-ordinates of each triangle as a 4 x 2 matrix with first row repeated as last row. Confirmed with OP that this is compliant with the input rules
 0=+/2-/(y[⍋y←⍎c])÷x[⍋x←⍎c←'+/(-2-⌿⎕)*2']

Try it online! Courtesy of Dyalog Classic

@Adám Thanks for your clarification I will edit it back to the original.

Python 3, 84 bytes
lambda*M:len({x/y for x,y in zip(*[sorted(abs(3*x-sum(l))for x in l)for l in M])})<2

Try it online!
Takes input as 3 complex numbers. Outputs True for similar, False for dissimilar. The first test case fails due to a float precision issue with two extremely close float values being unequal; the challenge allows this.
This uses a bit of a different method than other answers that fingerprint congruent triangles by their edges having equal length. Instead of taking the distance between pairs of vertices, we use the distance between each vertex and the center-of-mass of the three vertices, that is their average.
To demonstrate that a unique triangle satisfies this up to congruence, note that the three vectors emanating from the center of mass to the vertices must add by zero by definition, which means these vectors must themselves be able to make a triangle. Since their lengths are fixed and we only get to choose their angles (slopes), this is the same as arranging three sticks as the edges of a triangle, which as noted before is unique up to congruence.
To check similarity, we sort the respective distances and check that their ratios are all equal.
This alternative method is shorter, but I haven't proved that it doesn't give false positives.
79 bytes
lambda a,b:g(a)==g(b)
g=lambda l:{abs((x-y)/(3*x-sum(l)))for x in l for y in l}

Try it online!

Brachylog, 23 21 bytes
{{{⊇Ċ-^₂}ᶠ}ᵐz+ᵐo}ᵐz/ᵛ

-2 bytes thanks to Unrelated String
A predicate that only accepts similar triangles.
Note that for negative values you have to type _1 instead of -1
Try it online!

-2 bytes using ᵛ instead of ᵐ= and taking each triangle as [[x1,x2,x3],[y1,y2,y3]] instead of [[x1,y1],[x2,y2],[x3,y3]] (input can be "in any structure")

Ruby, 87 82 77 74 bytes
->*a{a.map!{|a,b,c|x,y,z=[a-b,b-c,a-c].map(&:abs).sort;[x/z,y/z]}.uniq!=a}

Try it online!
Given the 2 triangles as vectors of 3 complex numbers, calculate length of the three sides as distance between points, sort ascending, then check if a/b and a/c are the same for both.

Julia 1.0, 65 bytes
!x=sort(abs.(diff(push!(x,x[1]))))
g(a,b,z=!a./!b)=all(z.≈z[1])

Revised to not abuse the "any input structure" statement, as people seemed down on that. Found extra golfing, so it's only 1 byte longer. The input is two vectors of complex numbers. ! is a helper function that appends the first element to the end of each input list and returns the result, then takes the difference ob subsequent elements, elementwise absolute value, and sorts. Then calculate the ratios of the sorted lengths of the sides and check that they are all approximately equal. It costs the same number of bytes to compare square side lengths (replace abs with abs2 and ≈ by ==).
Try it online!

I disagree with your input method being within the rules. Instead of requiring the coordinates as input, you require the coordinates plus a bit, which is not valid per meta consensus. Other answers (1,2,3,4,5) in this thread would also benefit from this, but have worked around it inside their code.

I've revised my answer to take only 3 points as input. I would disagree that that conensus applies (the example is including the answer in the input, not redundancy), but the limit of "any structure" would include a custom data structure with methods defined such that all work is in part of the structure, which is an useless limit.

Wolfram Language (Mathematica), 38 bytes
Equal@@Sort/@PolygonAngle/@Polygon/@#&

Try it online!
Takes a list containing two lists of coordinates.
Checks if the two triangles' angles are equal. As PolygonAngle was introduced in version 12.0, this code does not (yet) work on TIO.

Charcoal, 46 bytes
≔ＥＡＥιΣＸＥλ⁻ν§§ι⊕μξ²θＵＭθ×⟦⌊ι⌈ιΣι⟧Σ§θ¬κ⬤⊟θ⁼ι§§θ⁰κ

Try it online! Link is to verbose version of code. Outputs - for similar, nothing for dissimilar. Accepts triangles in any N-dimensional space. Explanation:
≔ＥＡＥιΣＸＥλ⁻ν§§ι⊕μξ²θ

Input the two triangles and calculate the squared lengths of their sides.
ＵＭθ×⟦⌊ι⌈ιΣι⟧Σ§θ¬κ

Calculate the shortest, longest and sum of the squared sides of each triangle, then scale by the sum of the squared sides of the other triangle.
⬤⊟θ⁼ι§§θ⁰κ

Check that the shortest and longest and sum of the squared sides are equal. (The middle squared side is the difference between the sum and the other two sides individually, so if they are all equal then the middle squared sides are also equal.)

Zsh, 156 122 116 bytes
s(){m=
for a b x y;m+=($[(a-x)**2+(b-y)**2])
n+=(${(n)m})}
s $=1
s $=2
((r=(n[1]+0.)/n[4],r*n[5]-n[2]||r*n[6]-n[3]))

Try it online!
Try it online!

Try it online!
Saves 34 bytes by abusing "any structure" for input. Given a pair of triangles:
[[1,2],[3,4],[5,6]] and [[7,8],[9,10],[11,12]]

The input should be the two strings:
'1 2 3 4 3 4 5 6 5 6 1 2' '7 8 9 10 9 10 11 12 11 12 7 8'

I believe this is within the rules; there is no calculation done beforehand, simply duplication. No sorting criteria is applied either.
I provide a helper function in the TIO link to prepare an argument list from a string in almost any format (it removes all non-numeric characters and splits).
Here is the first 156 byte answer, which takes the input in a less abusive format. The abusive format removes line 2 in s, and reduces line 3:
s() { # helper function, calculates squares and sorts them for one triangle
    m=                             # unset m in case it was already used
    t=(${@:^argv} $1)              # t=('x1 y1' 'x1 y1' 'x2 y2' 'x2 y2' 'x3 y3' 'x3 y3' 'x1 y1'
    for a b x y (${=t:1})          # Remove first element of $t, and split on spaces:
        m+=($[(a-x)**2+(b-y)**2])  # (a b x y): (x1 y1 x2 y2) (x2 y2 x3 y3) (x3 y3 x1 y1)
    m=(${(n)m})                    # sort squared lengths in numeric order
}

s $@[1,3]                          # run s with the first three arguments
n=($m)                             # save first result in n
s ${@:4}                           # run s with the last three arguments
((r=(n[1]+0.)/m[1], r*m[2]-n[2] || r*m[3]-n[3]))  # returns truthy if not similar

I disagree with your input method being within the rules. Instead of requiring the coordinates as input, you require the coordinates plus a bit, which is not valid per meta consensus. Other answers (1,2,3,4,5) in this thread would also benefit from this, but have worked around it inside their code.

I agree that allowing this is invalid in general. However, I wrote it after seeing this answer using repeated input, which was allowed by OP.  If I wrote the challenge, I would not have allowed that answer or mine. But I make the case that allowing that answer would allow mine.  If I am simply way off the mark, and the APL answer isn't abusing extended input, then I will gladly revert.


text:
Make a haystack (with a needle)
(Essentially the inverse of Find the needle in the haystack)
Given two tuples, (w, h) and (x, y), generate a haystack composed of a single random printable ASCII character of w width and h height with a needle made of a different random printable ASCII character at (x, y) when measured from the upper-left.
For example, when given (5,4) for the width and height, and (3,1) (zero-indexed) for the location of the needle, a possible haystack could be the following:
#####
###N#
#####
#####

Another possibility could be
*****
***$*
*****
*****

among hundreds of others.
Rules and Clarifications

Input and output can be given by any convenient method. This means you can take input as a list of list of integers, as a single string, as two integers via command-line and a tuple via function argument, etc.
You can print the result to STDOUT or return it as a function result.
Either a full program or a function are acceptable.
You can choose whether the (x, y) tuple is zero-indexed or one-indexed, but please specify in your solution which you're using.
You do not get to pick which characters to use. That's part of the challenge - randomly selecting the characters.
Every possible output for a given input must have a non-zero chance of appearing, but the randomness doesn't need to be uniform.
The haystack is guaranteed to be at least 2x2 in size, so it's unambiguous which is the needle and which is the hay.
There is only ever one needle, and it's only ever one character in size, and it's guaranteed to be within the boundaries of the haystack.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Can we return a flat list of characters?

@TFeld No, you must have \n (or equivalent) included where appropriate.

can we return a matrix of characters?

@dzaima But of course.

Obligatory xkcd about the choice of the characters. Applies to a few early answers... :p

@Arnauld I don't know what was the magic here, but I completely read the challenge as I can use any ASCII printable characters "that I like", instead of "random", and it is funny another person also did same exact thing! I didn't mean to implement the random in such a beautiful way :P

Can the order of elements in the tuples be altered, and can the input format be mangled in any other ways?

@UnrelatedString Yes and yes? Those are standard I/O rules.

Just a quick question for clarity - the two random printable ASCII characters should be by definition, dissimilar, correct?

@TaylorScott Yes, that's covered in the opening paragraph. The two characters need to be different.

@AdmBorkBork- Thanks for the clarification, I can be completely blind sometimes and did not see that! Cheers

JavaScript (Node.js),  122 120 106  103 bytes
Recursively builds the output character by character. The coordinates are 0-indexed.
(w,h,x,y)=>(s=new Date%9023,g=X=>Y<h?Buffer([X-w?(x-X|y-Y?s+1:s%96)%95+32:13])+g(X<w?X+1:!++Y):'')(Y=0)

Try it online!
How?
Problem
To generate the haystack and the needle, we could either:

generate a random haystack and process some loop to generate a random needle until it's different from the haystack
shuffle the whole range of printable characters and pick the first 2 of them

Unfortunately, both approaches are rather lengthy in JS.
Solution
We use instead a method that guarantees to generate 2 distinct characters with a single random number and without any loop.
We pick a random seed \$s\$ in \$[0..9022]\$ and define the haystack \$h\$ and needle \$n\$ as:
$$\begin{align}&h=(s+1)\bmod 95\\
&n=(s\bmod 96)\bmod 95\end{align}$$
(we then need to add \$32\$ to turn them into printable ASCII codes)
Basically, \$h\$ follows the pattern:
$$1,2,3,...,94,0,1,2,3,...$$
while \$n\$ follows the pattern:
$$0,1,2,3,...,94,\color{red}0,0,1,2,3,...$$
The sequences are progressively shifted relative to each other because of the extra \$0\$ in the needle pattern.
This code shows that it does eventually lead to all possible pairs \$(h,n)\$ with \$h\neq n\$ (there are \$95\times 94=8930\$ of them).
And because we need only one random number, we can afford to use the current timestamp in milliseconds as our entropy source with new Date%9023 instead of the longer Math.random()*9023.
Commented
(w, h, x, y) => (      // w = width, h = height, (x, y) = coordinates
  s = new Date % 9023, // s = random seed in [0..9022]
  g = X =>             // g = recursive function taking X
    Y < h ?            //   if we've not reached the end of the grid:
      Buffer([         //     append the next character:
        X - w ?        //       if we haven't reached the end of the line:
          ( x - X |    //         if this is not the position of the needle:
            y - Y ?    //
              s + 1    //           append the haystack character
            :          //         else:
              s % 96   //           append the needle character
          ) % 95 + 32  //
        :              //       else:
          13           //         append a linefeed
      ]) +             //
      g(X < w ? X + 1  //     append the result of a recursive call
              : !++Y)  //     with either (X+1, Y) or (0, Y+1)
    :                  //   else:
      ''               //     stop recursion
)(Y = 0)               // initial call to g with X = Y = 0

Never seen new Date be used to generate a random seed before. Cool.

@DanielVestøl, it's a common tactic in challenges where "random" is un(der)specified.

Jelly, 14 13 bytes
p/⁼€ịØṖẊ¤s⁸Ḣ¤

Try it online!
-1 byte thanks to Unrelated String
Returns a list of lines. The last line in the Footer section displays it as a square. Takes input as [w, h] and [y, x], where x and y are 0-indexed.
How it works
p/⁼€ịØṖẊ¤s⁸Ḣ¤ - Main link. Takes [w, h] on the left and [y, x] on the right
p/            - Reduce Cartesian product over the arguments.
                This yields a list of co-ordinates from (1, 1) to (h, w)
   €          - Over each list:
  ⁼           -   Is it equal to [x, y]?
              - This yields a list where every element except 1 is 0
        ¤     - Create a nilad:
     ØṖ       -   Printable ASCII characters
       Ẋ      -   Shuffled
    ị         - Index into the shuffled characters, replacing 1 with the first char in the shuffled list and 0 with the last. Therefore, the two characters will be distinct
            ¤ - Create a nilad:
          ⁸   -   Yield [w, h]
           Ḣ  -   Extract w
        s     - Split the list of characters into rows of length w
              - Implicitly output

-1 byte if you take [y, x] instead of [x, y] so you can drop the U

@UnrelatedString Huh, weird. That didn't work for me when I first posted it, but is now. Thanks!

Excel VBA, 128 118 106 94 96 bytes
-12 bytes inspired by agtoever
-12 bytes thanks to Taylor Scott, VBA extraordinaire
+2 bytes and -1 bug thanks to Taylor's unnecessary, intimidating, and much appreciated work
Sub n(w,h,x,y)
a=94*Rnd
[A1].Resize(h,w)=Chr(a+32)
Cells(y,x)=Chr(32+(a+93*Rnd+1)Mod 95)
End Sub

Input and output are one-indexed. Output is to the top left cell range of the active sheet.
a=94*Rnd+32: (126-32)*Rnd+32 gives a number between 32 and 126, inclusive.
Range(~)=Chr(a): Fills all the cells with the ASCII character.
Cells(y,x)=Chr(~): Fills just that one cell with the other ASCII character.
(a+62*Rnd)Mod 95+32: {(a+[94-32]*Rnd) Mod (126-32+1)}+32 gives a random number between 32 and 126 inclusive that is not the same as a. (I can't prove that mathematically but 100 million tests showed no collisions.)
Example output:

Shorter: b=Chr(Asc(a)+1+95*Rnd Mod 127) instead of the do-while loop.

Oh. And then you can just insert that statement in Cells(y,x)=... instead of assigning it to b.

@agtoever I tested that. It results character codes up to 221 which is not allowed. I can't figure out how to modify it to generate a uniquely random integer 32-126. I kept hitting a ≈1.5% match rate, which is no good. However, that helped me find an error in my original code since it allowed up to 127 instead of 126. (It turns out that Chr() rounds instead of truncating.)

Ow. Adding (+) has a lower operator precedence than Mod. Add parenthesis: Cells(y,x)=Chr((Asc(a)+1+94*Rnd)Mod127)) (not tested, maybe spaces are mandatory around Mod...)

@agtoever I tried that when I was trying to get the previous suggestion to work. As written, b ends up in the range 0-126 instead of 32-126 although it's always unique from a. I massaged it a bit to get the most recent edit, which had 0% failure rate over 100 million runs.

You can get down to 94 bytes if you use [A1].Resize(h,w)=Chr(a)

The 62 in the needle declaration didn't quite sit well with me, so I went and checked the math - it looks like as written it does avoid all possible collisions of a and b, but, it also fails to give 31 expected b values for every a value. I did work out a solution to this should only cost you two bytes - a=94*Rnd, Chr(a+32) and Chr(32+(a+93*Rnd+1)Mod 95) should give you everything you need. Uh, I've also been working on my own commenting and formatting habits, so here is a needlessly well commented proof of the above. Cheers!

Python 2, 134 133 120 112 111 bytes
lambda w,h,x,y:zip(*[iter(chr(r[x+y*w==i]+32)for i in range(w*h))]*w)
from random import*
r=sample(range(95),2)

Try it online!

PowerShell v6, 102 96 bytes
param($x,$y,$a,$b)$j,$k=' '..'~'|random -C 2
-join((,$j*$x+++'
')*$y|%{"$_$k"[$i++-eq$b*$x+$a]})

Try it online!
This answer, thanks to mazzy, uses the character range feature added in v6 to save several bytes over the more flexible answer below.
PowerShell, 119..105 102 bytes
-16 bytes thanks to mazzy
-1 byte thanks to AdmBorkBork
param($x,$y,$a,$b)$j,$k=32..126|random -C 2
-join((,$j*$x+++'
')*$y|%{[char]($_,$k)[$i++-eq$b*$x+$a]})

Try it online!
Gets two ints in the range of [32,126]. We first make a 1D array out of the first value, appending a new line after every $xchars. Doing this means we also have to increment $x so that our index math isn't affected. We then iterate through the array, and either yield a char-ified first value or the needle. Finally, we join all the yielded values and output it.
Answer is 0-indexed by the way.

Jelly, 11 bytes
QŒṬƤSḂịØṖẊ¤

A monadic Link accepting a list of lists, [[height, width], [row, column]] (1-indexed), which yields a list of lists of characters.
Try it online! (The footer calls the link and joins with newlines.)
How?
QŒṬƤSḂịØṖẊ¤ - Link: [[h, w], [r, c]]
Q           - de-duplicate (i.e. [[h, w]] if [r, c] == [h, w] else [[h, w], [r, c]])
   Ƥ        - for prefixes (of that list):
 ŒṬ         -   get a 2D array with ones at the coordinates specified
    S       - sum (vectorises) (giving us an h*w matrix with zeros almost everywhere,
                                except a 1 at our needle and, if [h, w] != [r,c], a 2 at
                                the bottom-right)
     Ḃ      - modulo two (replacing the 2 with a zero if it exists)
          ¤ - nilad followed by link(s) as a nilad:
       ØṖ   -   list of printable characters
         Ẋ  -   shuffled
      ị     - (left) index into (right) (vectorises)

Dyalog APL, 24 23 21 bytes
⎕UCS(32+2?95)[⎕∘≡¨⍳⎕]

Try it online! 0-indexed.
-1 thanks to ngn, -2 thanks to Adám suggesting to use a different I/O format.

(⎕UCS 32+2?95) -> ⎕UCS(32+2?95)

⎕UCS(32+2?95)[⎕∘≡¨⍳⎕]

Python 2, 133 bytes
from random import*
r=range
def f(h,w,x,y):
 p=sample(r(32,127),2)
 for i in r(h):
	print ''.join(chr(p[i==y and j==x])for j in r(w))

Try it online!
-12 thanks to Value Ink for suggesting using a loop comprehension. -2 thanks to Unrelated String for suggesting python 2 instead of python 3 to get rid of parenthesis in the print function!

Welcome to PPCG! My first thought was to wrap the innermost loop into a loop comprehension that is then joined together and printed, to eliminate both the end='' part as well as the additional print() call after the loop. This cut the size down to 135 bytes. Try it online!

You can also shave two more off by using Python 2 instead of 3, but it's minor.

print(end=chr(p[i==y and j==x])) saves three bytes

Python 2, 110 bytes
from random import*
w,h,x,y=input()
m,n=sample(map(chr,range(32,127)),2)
l=eval(`[[m]*w]*h`)
l[x][y]=n
print l

Try it online!
I copied TFeld's solution and managed to golf a char using list assignment. The eval() trick is used to make a mutable matrix to avoid the list mutation applying to every row.
111 bytes
lambda w,h,x,y:[[chr(r[x^i<1>y^j]+32)for i in R(w)]for j in R(h)]
from random import*
R=range
r=sample(R(95),2)

Try it online!
A smaller change that only tied. Calling the function multiple times always give the same random choices, which I hope is OK.
109 bytes
lambda w,h,x,y:[m*w]*y+[m*x+n+m*(w+~x)]+[m*w]*(h+~y)
from random import*
m,n=sample(map(chr,range(32,127)),2)

Try it online!
A shorter function making the list of lines via multiplication. Also generates the characters just once.

Nice! I didn't know about that eval trick.

Perl 5, 86 bytes
($,,$b)=keys%{{map{chr,1}33..126}};$_=($,x$F[0].$/)x$F[1];s;(.*
){$F[3]}.{$F[2]}\K.;$b

Try it online!

Julia 1.0, 71 bytes
f(w,h,x,y)=(z=unique(rand(' ':'~',9));g=fill(z[1],(h,w));g[y,x]=z[2];g)

x,y are one indexed. Returns a 2d array of characters, I spent the extra bytes to make sure the default printing has the right orientation (' for transpose no longer works because they stick to a strict mathematical meaning). Getting two distinct randoms is surprisingly verbose, this has about a 1e-18 chance of failing to do so, one more byte could make it 1e-196.
Try it online!

J, 21 bytes
u:@(32+2?95){~#.=i.@[

Try it online!
Inspired by dzaima's APL answer.
Thanks to Galen and Adam for the randomize fix.

Fix by Adam

You need two tuples as input

Yeah I just noticed that, will fix.  Thanks for the other fix btw.

Octave with Statistics Package, 45 bytes
@(x)randsample(' ':'~',2)(sparse(x{:},0:1)+1)

The input is a cell array of 2 numeric vectors of length 2: {[h y] [w x]}, with x,y 1-based.
Try it online!

Ruby, 62 bytes
->w,h,x,y{a,b=[*?\s..?~].sample 2;r=[a*w]*h*$/;r[y*-~w+x]=b;r}

Try it online!

Excel + CSV, 104 bytes
,,,,=94*RAND()+32,=REPLACE(REPT(REPT(CHAR(E1),A1)&"
",B1),D1*A1+D1+C1+1,1,CHAR(MOD(E1+62*RAND(),95)+32))

Save as CSV, add input as A1 - D1.
Output will be in F1.
Using @Engineer Toast's solutoin for generating 2 unique characters.
Needle position is 0-indexed, which is curious, as Excel itself if 1-indexed.
Changing to 1-indexed input adds 3 bytes ((D2-1)*(A2+1)+C2 instead of D1*A1+D1+C1+1).

@Arnauld, it does not.  Thanks for poingin out.  Have updated.

Just wanted to let you know that the indicated solution for the needle character is not quite correct. You should switch to CHAR(MOD(E1+93*RAND()+1,95)+32) to insure that your solution covers all possible combinations of needle and haystack

Pyth, 56 50 48 41 bytes
JEKE=TE=Yrd\~=Zh.SYVJVQ ?qHK?qNTpeYpZpZ)d

I'm somewhat struggling to golf Pyth, but posting this to force myself to learn.
Edit 1: Golfed it down a bit, and made it an actual solution -6 bytes
Edit 2: Looked at it after posting it and realized a few bytes save by ignoring space. -2 bytes
Edit 3: Today I learned about character ranges, which shortens things significantly. -7 bytes

C (clang), 87 bytes
f(w,h,x,y){x+=y*w;h*=++w;for(y=time(0)%9023;h--;)putchar(h%w?(x--?y+1:y%96)%95+32:10);}

Try it online!
Stealing from @Arnauld answer

PHP, 113 109 bytes
for([,$w,$h,$x,$y]=$argv,$a=range(' ','~'),shuffle($a);$i++<$h;print"
")for(;$$i++<$w;)echo$a[$i-$y||$$i-$x];

Try it online!
Pass inputs as command arguments ($argv) in order of w, h, x and y. The x and y are one-indexed.
for(
  [,$w,$h,$x,$y]=$argv, // put inputs from $argv array into 4 short named variables
  $a=range(' ','~'),    // create $a array containing printable ASCII characters
  shuffle($a);          // shuffle the array
  $i++<$h;              // loop $h times (rows)
  print"\n"             // print a newline after every row
)
  for(;$$i++<$w;)       // loop $w times (columns)
    echo                // print
      $a[               //   a character from $a (1st char for needle and 2nd for heystack)
        $i-$y ||        //   when row and y don't match
        $$i-$x          //   or when col and x don't match (will be false only for needle)
      ];

Add++, 65 bytes
D,g,?!,
L,c95Rdb[€BXd¦=BFV#@G+b[95€Ω%31€+€CA€RbU‽g$€=$€Ω:A$pbUp$T

Try it online!
Takes input as [y x] and [w h]. x and y are 1-indexed. Outputs a list of lines.
Added 17 bytes to make sure the needle is distinct.
How it works
We start by generating two ranges from \$1\$ to \$95\$ inclusive, before choosing a random value from each. If the two values are equal, we add one to the one of them. We then add \$31\$ to each, yielding two characters ord points in the ASCII range. Finally, we convert them to characters.
Next, we generate a list of all co-ordinates in the grid, and compare them with [y x]. If the co-ordinates match, we yield \$1\$, otherwise \$0\$. Next, we index each of these \$1\$s and \$0\$s into the two characters, creating a grid of \$0\$ characters with 1 \$1\$ character in it at [y x]. Finally, we retrieve the width and split the grid into that many rows.

SOGL, 18 bytes
 ~Δψ] ~Δψ⁴⁴=}A*∙až

Try it here! 1-indexed.

C# (Visual C# Interactive Compiler), 145 bytes
(a,b,c,d)=>{int l=0;for(var j=Enumerable.Range(32,95).OrderBy(k=>Guid.NewGuid()).ToList();l<a*b;)Write((char)j[l==c*a+d?1:0]+(++l%a<1?"\n":""));}

Try it online!

Icon, 119 bytes
procedure f(w,h,x,y)
until m:=char(32+?95)&n:=char(32+?95)&m~==n
t:=[];1to h&put(t,repl(m,w))&\z
t[y,x]:=n
return t
end

Try it online!
xand yare 1-indexed

Python 3, 137 bytes
lambda w,h,x,y,c=chr:"\n".join([c(a)*w,c(a)*x+c(n)+c(a)*(w-x-1)][r==y]for r in range(h));a,n=__import__("random").sample(range(32,127),2)

Try it online!
Uses zero-based indexing for the needle position.

from random import* is shorter than __import__("random"). 136 bytes.

Perl 6, 57 bytes
{(' '..'~').pick(2)[0 xx$^a*$^b-1,1;*].pick(*).rotor($a)}

Try it online!

Charcoal, 17 bytes
ＵＯＮＮ‽γＪＮＮ‽Φγ¬⁼ιＫＫ

Try it online! Link is to verbose version of code. Explanation:
ＵＯＮＮ‽γ

Draw a rectangle of the given width and height using a random printable ASCII character.
ＪＮＮ

Jump to the 0-indexed position of the needle.
‽Φγ¬⁼ιＫＫ

Print a random printable ASCII character, but filtering out the character under the cursor.

K (oK), 27 23  bytes
-4 bytes thanks to ngn!
{`c$(32+-2?95)x#&/y=!x}

Try it online!
0-indexed x and y
Similar to Dzaima's APL and Jonah's J solutions.

(x/y)=x#!*/x -> x#&/y=!x

@ngn That's much better than my naive solution. Thanks!

@ngn Clever use of the odometer for 2d matching!

Red, 156 bytes
func[w h x y][c: :collect p: take/part random c[repeat i 95[keep to sp 32 + i]]2
c[repeat i h[keep/only c[repeat j w[keep pick p i * w + j
=(y * w + x)]]]]]

Try it online!
x and y are 1-indexed. Returns a list of strings.
Readable:
f: func [w h x y] [
    c: take/part random collect [
        repeat i 95 [
            keep to sp 32 + i
        ]
    ] 2
    collect[
        repeat i h [
            keep/only collect [
                repeat j w [
                    keep pick c i * w + j = (y * w + x)
                ]
            ]
        ]
    ]
]

Python 2, 144 132 131 bytes
from random import*
i,j,k,l=input()
n,h=sample(range(32,127),2)
for x in range(j):a=[chr(n)]*i;a[k]=chr((n,h)[x==l]);print`a`[2::5]

Try it online!
Corrected the problem with the guaranteed uniqueness of the characters and saved 12 bytes along the way.

I liked the idea of this solution well enough that I shaved off 3 more bytes for you: https://tio.run/##JYxBCoMwEEX3OUUQhIzOxthSEHKS4EJaraPJJKQp2NOn0q4@vPf48ZPXwLqUJQUv08SPc8jHkHIjCDfc0Rni@M4KBONqXpOPblZn@ZxVr7HTN0ANYglJHpJY/s0GQ0zEuarvVUO1UozQ7K2y58doD2PciND@KIEdaCzlihfssfsC

Nice and also different enough for you to post as your own if you wish :)

Eh, it's not that different. It is a direct modification of yours edited directly on TIO. Posting it separately would have been actual effort.

Forth (gforth), 140 bytes
include random.fs
: x 95 random 32 + ;
: f x -rot 0 do cr dup 0 do 2over i j d= >r over r> if begin x 2dup - until nip then emit loop loop ;

Try it online!
0-indexed
Code Explanation
include random.fs        \ import the random library

\ Generate a random number in range 32 to 126 inclusive
: x                      \ start a new word definition
  95 random              \ generate a random number between 0 and 94
  32 +                   \ add 32
;                        \ end word definition

: f                      \ start a new word definition
  x -rot                 \ generate a random number for the haystack, then move it
  0 do                   \ loop from 0 to h-1 (inclusive)
    cr                   \ output a newline
    dup 0 do             \ loop from 0 to w-1 (inclusive)
      2over i j d=       \ check if this is the needle square
      >r over r>         \ hide result, grab a copy of the haystack char, then grab result back
      if                 \ if it is a needle
        begin            \ begin indefinite loop
          x 2dup -       \ generate a new random number and compare to haystack char
        until            \ only end loop when values differ
        nip              \ drop haystack char
      then               \ end if block
      emit               \ output ascii char for value on top of stack
    loop                 \ end row loop
  loop                   \ end column loop
;                        \ end word definition

Japt -R,34 30 29 24 bytes
;E=öx)ÎpU*V hW*U+XEg1)òU

Try it
5 Bytes saved thanks to @Shaggy.
Inputs are U,V => size , W,X => needle coords 0 indexed
 ;E=   // set of printable characters
     öx) // random permutation
 Î // => g0  pU*V    repeats U*V times first element of set
           hW*U+XEg1) // overwrite at W,X with 2nd element
                      òU // split

@Shaggy my first try, the best I can do, any suggestions are implicitly welcome!

A few quick savings for you here.

Thanks @Shaggy! The good thing is that I 've understood your improvements, though I'm still far from a good usage of this language, maybe due to my poor experience in JS

you don't really need a JS background to learn Japt.

05AB1E, 15 bytes
žQΩIP×žQΩIPǝ¹нô

Coordinates are 1-indexed. Outputs as a list of lines.
Try it online (» in the footer joins the list of strings by newlines to pretty-print, feel free to remove it to see the actual output).
Explanation:
žQ              # Push all printable ASCII characters
  Ω             # Pop and push a random character
   IP           # Push the first input (rectangle-size), and take its product
     ×          # Repeat the random character that many times as string
      žQΩ       # Push a random character again
         IP     # Push the second input (1-based coordinate), and take its product as well
           ǝ    # Insert the random character at this (0-based) index into the string
            ¹н  # Push the first input again, and only leave its first value (width)
              ô # Split the string into parts of that size
                # (after which the resulting list of strings it output implicitly as result)

C (clang), 130 117 116 109  106 bytes
c[2];f(w,h,x,y){x+=y*w;for(h*=++w;y++<h|*c==c[1];)c[y%2]=time(0)%94+33;for(;h--;)printf(h%w?c+!x--:"\n");}

Try it online!
Saved 13 thanks to @ceilingcat
Didn't thought using just only time() was enough
And also didn't thought printf accepted a int pointer as a format string!
Needle is 0 indexed
c[2]; // needle and hay stored in array
f(w,h,x,y){
 x+=y*w; // sets counter for needle (x no more needed)
 for(
     h*=++w; // while incrementing w for newline sets counter for haystack
     y++<h  // more than 2 iterations to fill array
     |*c==c[1]; // until they're different
     )
     c[y%2]=time(0)%94+33; // assign value to array (I've excluded spaces )
 for( ;h--; ) printf(h%w?c+!x--:"\n")
 // output: on h%w =0 => newline
 //              if  x != 0 => hay
 //              when x=0 => needle
 //              and continue to finish haystack

Zsh, 108 bytes
Needle location is 1-indexed
repeat $2 : $[h=r++?h:RANDOM%95]&&(repeat $1 s+=${(#)$((n=r-$4||++c-$3?h:(n=RANDOM%94)+(n>=h),32+n))};<<<$s)

Try it online!
repeat $2
  # set hay when row is 0 (shorter than setting it before due to the cost of "(( ))")
  # ": $[  ]" always exits true. "((  ))" would exit false if hay == 0
  : $[hay = row++ ? hay : RANDOM % 95] && (
    # inner loop in (subshell), $str and $col will be empty every time
    repeat $1
      # ${(#)$((x))} expands to the Unicode character at codepoint $x
      str+=${(#)$((offset =
        row - $4 || ++col - $3
        ? hay
        : (offset = RANDOM % 94) + (offset >= hay),
        32 + offset
      ))}
      <<< $str
  )

Proof of correctness by exhaustion, for all combinations of RANDOM%95 and RANDOM%94.

source: Stack Exchange

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

sort: votes


text:
Plain Hunt Bell-Ringing
Your task is to create a plain hunt (a bell ringing pattern) with n bells. An example with 6 bells:
123456
214365
241635
426153
462513
645231
654321
563412
536142
351624
315264
132546
123456

Each number "bounces" off the side of the grid. From Wikipedia:

Each bell moves one position at each succeeding change, unless they reach the first or last position, when they remain there for two changes then proceed to the other end of the sequence.

In other words, you swap the bells in adjacent pairs, alternating between taking pairs starting from the the first bell and from the second bell. (Thanks to @xnor for this explanation.) You finish in the same order as the start.
This rule be applied to any number of bells, taken as input.
Standard loopholes are forbidden.
Test Cases
6
123456
214365
241635
426153
462513
645231
654321
563412
536142
351624
315264
132546
123456

3
123
213
231
321
312
132
123

2
12
21
21
12

1
1

0: Falls in to "I don't care" situation.

Is the starting row always 1 ... n or can it be in any order (e.g. 2314 for n=4)?

@nimi Always 1 ... n

1 is a special case since it doesn’t have separate start and end rows both equal to 1. Would it be permissible to return 1, 1 for the input of 1?

Can I print in list form, like [1,2,3,4] or something similar?

Can you add a test case for n>9?

As a bell-ringer, having anything other than 2n changes for plain hunt on n triggers me...

Can we use 0..n-1 instead of 1..n?

I agree that the n=1 test case having one entry seems out of place. For all the rest, we only checking if we've returned to the start after the first change, since otherwise the first line of course equals itself and we'd stop immediately. So, that would gives [[1], [1]] You could also consider putting n=1 under "don't care" to avoid a potential  edge case.

Python 2, 93 bytes
lambda n:[[.5+abs((n+j-i*(-1)**(i+j))%(2*n)-n+.5)for j in range(n)]for i in range(2*n+(n>2))]

Try it online!
Outputs a list of lists of integer-valued floats.
The map (i,j) -> j-i*(-1)**(i+j) is very similar to multiplication in the dihedral group. This isn't a coincidence. If we let \$a\$ represent swapping every other element starting from the first, and \$b\$ doing so starting from the second, then these generate the dihedral group \$D_{2n}\$ gives by relations \$a^2 = b^2 =(ab)^n =1 \$. Note that the sequence we're asked to output has us alternate applying \$a\$ and \$b\$, and the fact that \$ (ab)^n =1 \$ confirms that we return to where we started after \$2n\$ total steps.
We can see the dihedral connection more clearly if we extend the top row to \$2n\$ elements rather than \$n\$, and write it zero-indexed. Doing the alternating swaps as usual gives a pattern like below for \$n=3\$. This is almost a multiplication table for the dihedral group \$D_{2n}\$, except that we invert the first group element before multiplying \$g,h \to g^{-1} h \$, giving zeroes (identity) on the diagonal \$g=h\$.
  012345
 +------
0|012345
1|103254
2|430521
3|345012
4|254103
5|521430

To return the values back into the range [0,1,2], we need to map back 3->2, 4->1, 5->0. In the code, surprisingly many characters as spent on the simple-looking mapping doing modular indexing into the palindromic "bouncing" list [1,2,...,n-1,n,n,n-1,...,2,1], We implement this as .5+abs((n+k)%(2*n)-n+.5). The Python 3.8 walrus can save at least 2 bytes, though I haven't optimized it.

Haskell, 83 bytes
f(a:b:c)=b:a:f c
f c=c
q l|a:b<-f l=l:f l:q(a:f b)
g n=take(2*n+sum[1|n>2])$q[1..n]

Try it online!

PHP, 120 bytes
for($b=$a=range(1,$argn);print join($b)."
",$a[1]&&!$i||$a!=$b;)for($j=$i++%2;$n=$b[++$j];$b[$j-2]=$n)$b[$j++]=$b[$j-2];

Try it online!
for(
  $b=$a=range(1,$argn); // set $a and $b to an array of [1...n]
  print join($b)."\n",  // on start of each iteration print $b
  $a[1]&&               // stop when input is 1 (we only print a single 1 for input of 1)
  !$i||                 // allows first iteration to happen since $a==$b on first iteration
  $a!=$b;               // stop when $a and $b are equal again
)
  for(
    $j=$i++%2;          // set $j to 0 or 1 (alternates each time)
    $n=$b[++$j];        // increment $j by one and set $n to
                        //   last number of next pair in $b, stop if it doesn't exist
    $b[$j-2]=$n         // swap one of bells in $b
  )
    $b[$j++]=$b[$j-2];  // increment $j by one and swap one of bells in $b

A much nicer approach if I can ignore case 1:
J, 42 bytes
[:/:"{i.+/\@|:@,.(2*-/\@i.)|."{[:(,-)i.<<:

Try it online!

official J, 68 62 59 bytes
[:>[:(]C.~_2<\(}.i.@#))&.>/@:|.\<@:>:@i.,(0;1)$~+:-1#.<&2 3

Try it online!
51 bytes if 1 case is allowed to return 2 lines: Try it online!
Another 48 byte solution which fails only case 1

how for official answer
Could likely be golfed more but I was happy with the idea.
Essentially, everything flows from noting that to get from one element to the next, you apply 1 of two cyclic permutations:
For example, in this case of n=6, to get from a row with an even index to the next row you apply:
┌───┬───┬───┐
│1 2│3 4│5 6│
└───┴───┴───┘

To get from an odd row to an even you apply:
┌─┬───┬───┬─┐
│1│2 3│4 5│6│
└─┴───┴───┴─┘

Once you set that up, the result is just a right to left scan over those alternating permutations.  Everything else is the boring details of constructing the permutations and the list to apply them to.

Zsh, 75 95 bytes
s(){echo $a;a=;for x y;a+=($y $x)}
a=({1..$1})
(($1-1))&&repeat $1 s $a&&s '' $a
(($1-2))&&s $a

Try it online!

Try it online!
Defines a function s which swaps each pair of arguments and assigns them to a.
s is called once normally ABCD -> BADC and then once with an empty element prepended: ABCD -> ACBD; repeated n times. s is called once more at the end, just to print out the array once more.
echo $a is used instead of <<<$a to suppress the empty element causing extra space.

Gives triple 1 for 1; the result for 2 is also longer than it should be

Thanks, fixed. Not pretty, but it works.

Jelly, 25 bytes
s2UF
RÇŻÇfƊƭƬmn2$Ṃṭ$⁸>2¤¡

A monadic Link accepting a non-negative integer which yields a list of lists of non-negative integers.
Try it online! (The footer calls the Link and formats the result as a grid)
How?
s2UF - helper Link: list                e.g. [4, 2, 5, 1, 3]
s2   - split into chunks of length two       [[4, 2], [5, 1], [3]]
  U  - reverse each                          [[2, 4], [1, 5], [3]]
   F - flatten                               [2, 4, 1, 5, 3]

RÇŻÇfƊƭƬmn2$Ṃṭ$⁸>2¤¡ - Main Link: non-negative integer, N
R                    - range = [1,2,...,N]
       Ƭ             - collect up while unique, applying (starting with X = range result):
      ƭ              -   apply previous (default 2) links in turn each time called:
 Ç                   -     1) call helper link as a monad
     Ɗ               -     2) last three links as a monad - i.e. g(X):
  Ż                  -          prefix a zero
   Ç                 -          call helper link as a monad
    f                -          filter keep only those values in X (i.e. remove the zero)
           $         - last two links as a monad:
          2          -   literal two
         n           -   not equal (N)?
        m            - modulo slice (m1 gives every element back,
                                     m0 performs reflection, which is required when N = 2)
                       [m0 reflecting is a very nice behaviour decision by Dennis IMO]
                   ¡ - repeat...
                  ¤  -   ...number of times: nilad followed by link(s) as a nilad:
               ⁸     -                         chain's left argument, N
                >2   -                         greater than 2?
              $      -   ...action: last two links as a monad:
            Ṃ        -                minimum (always [1,2,...,N])
             ṭ       -                tack (appending the final peel for N>2)

Charcoal, 54 bytes
ＮθＦθ«Ｊι⁰≔⁻⁶∧‹⁺ι¬﹪ι²θ∨﹪ι²±¹ηＦ⎇‹θ³×θθ⊕⊗θ«✳ηＩ⊕ι≧⁺⁻¬ⅈ⁼⊕ⅈθη

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

Input n.
Ｆθ«

Loop over each bell.
Ｊι⁰

Jump to its starting position.
≔⁻⁶∧‹⁺ι¬﹪ι²θ∨﹪ι²±¹η

Calculate its starting direction. For odd bells this is normally 7 (south east) and for even bells this is normally 5 (south west) but if the last bell its odd then its staring direction is 6 (south).
Ｆ⎇‹θ³×θθ⊕⊗θ«

Loop over each row, either n² for n<3 or 2n+1 for n>3.
✳ηＩ⊕ι

Print the current bell and move in the current direction.
≧⁺⁻¬ⅈ⁼⊕ⅈθη

Adjust the direction if the bell has reached the side so that it bounces.

Perl 6, 52 bytes
{$_,|({S:g:p($++%2)/(.)(.)/$1$0/}...$_)}o{[~] 1..$_}

Try it online!
Explanation
                                         {[~] 1..$_}  # Concat numbers 1..n
{                                      }o  # Feed into block
 $_,  # Start with first string
                                 ...  # Sequence constructor
      {                         }  # Compute next item by
       S:g         /      /    /   # replacing globally
          :p($++%2)  # starting at alternating positions 0, 1, 0, 1, ...
                    (.)(.)  # any two chars
                           $1$0  # swapped
                                    $_  # Until item equals original string
    |(                                )  # Flatten into result list

C# (Visual C# Interactive Compiler), 128 bytes
x=>{var m=Enumerable.Range(1,x).ToList();for(int i=0,j=0;i<x*2+1-2/x;j=++i%2)for(Print(m);j<x-1;)(m[j],m[++j])=(m[j],m[~-j++]);}

Try it online!

Jelly, 28 bytes
¹©Rµ¬ɼks€2UFµ⁺⁻J$Ð¿;@WẋL’ẸƊƊ

Try it online!
A monadic link that takes an integer as its input and returns a list of lists of integers. Could be 16 bytes if only needed to handle numbers 3 and above, and 22 if only 2 and above.

Python 2, 110 104 bytes
n=input()
R=range
s=R(1,n+1)
for k in R(n*2-2/n+1):
 print s
 for i in R(k%2,n-1,2):s[i:i+2]=s[i+1],s[i]

Try it online!
Full program that prints a list of integers for each "change" in the "hunt".

JavaScript (ES6), 99 bytes
n=>(z=0,g=a=>[a=a.map((v,i)=>v?a[i+=i+z&1||-1]||v:i+1),...z++^2*n^'027'[n]?g(a):[]])([...Array(n)])

Try it online!
Commented
n => (                  // n = input
  z = 0,                // z = counter
  g = a => [            // g = recursive function taking the list of bells a[]
    a =                 // update a[] and append it as a new entry
      a.map((v, i) =>   //   for each value v at position i in a[]:
        v ?             //     if v is defined:
          a[            //       take the bell
            i +=        //         at position:
              i + z & 1 //           i + 1 if i + z is odd
              || -1     //           i - 1 if i + z is even
          ]             //
          || v          //       or leave it unchanged if the above value is undefined
        :               //     else:
          i + 1         //       the array is not yet initialized: set the bell to i + 1
      ),                //   end of map()
    ...z++ ^ 2 * n      // we stop when z = 2n, except for
           ^ '027'[n]   // n = 1 (2n xor 2 -> z = 0) and n = 2 (2n xor 7 -> z = 3)
    ?                   // if the above result is not equal to 0:
      g(a)              //   do a recursive call
    :                   // else:
      []                //   stop
  ]                     //
)([...Array(n)])        // initial call to g with a[] = array of n entries

C (gcc), 270 224 206 190 bytes
Not a "winning" answer but a fun challenge.
Thanks @ceilingcat for some good cleanup.  Learned something new.
Update: further golfed based on how I now know the game to be played.
Further golfed by @ceilingcat
#define w(x)for(i=x;i<n;i++)
#define pb w(0)printf(b+i);puts("");
i,x,n;z(int*b){n=*b;w(0)b[i+n*4]=b[i]=i+49;do{if(n-1)pb;w(x++%2+1)b[i++-1]^=b[i]^=b[i-1]^=b[i];}while(bcmp(b,b+n*4,n*4));pb}

Try it online!

Great edit.  Forgot some of those tricks.

Red, 159 bytes
func[n][r: collect[repeat i n[keep i]]repeat i either n < 3[n * n][2 * n + 1][print r:
head r r: skip r i + 1 % 2 until[move r next r(index? r: skip r 2)> n]]]

Try it online!
If two 1s  are allowed as a solution for 1:
Red, 155 bytes
func[n][r: collect[repeat i n[keep i]]b: copy r t: on until[print b if t:
not t[b: next b]until[move b next b(index? b: skip b 2)> n]r = b: head b]print b]

Try it online!

Icon, 119 bytes
procedure f(n)
a:="";a||:=1to n&\z;b:=a
n>1&o:=|(0|1)&write(b)&b[o+(k:=seq(1,2)\n)]:=:b[o+k+1]&b==a
write(b);return
end

Try it online!

05AB1E, 35 bytes
≠iL[ˆ¯DÁ2£ËNĀ*#θNÈi2ôëćs2ôsš}ε¸˜}í˜

Try it online or verify all test cases.
Not too happy with it.. I have the feeling the duplicated 2ô could be golfed somehow, and some of the workarounds could be more elegant (/shorter). Could be 33 bytes if [1,1] instead of 1 is allowed as output; and could be 28 bytes if we'd only had to handle \$\geq3\$.
Explanation (of the 35 bytes version):
≠i              # If the (implicit) input is NOT 1:
  L             #  Create a list in the range [1, (implicit) input]
   [            #  Start an infinite loop:
    ˆ           #   Add the top list to the global array
    ¯D          #   Push the entire global array twice
      Á         #   Rotate the copy once towards the right
       2£       #   Then only leave the first two items
         Ë      #   Check whether those two items are NOT the same
     N          #   Push the current loop-index
      Ā         #   Check whether it is NOT 0 (so not the first iteration)
          *     #   If both checks are truthy:
           #    #    Stop the infinite loop
                #    (after which the TOS global array is output implicitly as result)
     θ          #   Only leave the last list of the global array
      NÈi       #   If the loop-index is even:
         2ô     #    Split the list into parts of size 2
        ë       #   Else (the loop-index is odd):
         ć      #    Extract head; pop and push the remainder-list and first item separated
          s     #    Swap so the remainder-list is at the top of the stack
           2ô   #    Split it into parts of size 2
             s  #    Swap to get the extracted first item again
              š #    And prepend it back in front of the list
        }ε      #   After the if-else: map over the pairs (and potentially loose items):
          ¸     #    Wrap them into a list
           ˜    #    And flatten them
                #   (this is a workaround to wrap multi-digit integers into an inner list,
                #    otherwise an integer like 10 would be reversed to "01"..)
         }í     #   After this map: reverse each inner pair
           ˜    #   And flatten it to a single list again for the next iteration

Ruby -p, 72 bytes
puts$_=s=[*?1..$_]*''
puts$_ until s[gsub /\B{#{1&$.+=1}}(.)(.)/,'\2\1']

Try it online!
Alternately replaces using the regexps /\B{0}(.)(.)/ and /\B{1}(.)(.)/. The latter matches any two characters other than at the beginning of the string, while the former just matches any two characters--{0} means "repeated zero times" turning the \B into a no-op.

Husk, 22 bytes
-;1ḟΓ€ḣ`Goṁ↔`C¢Se:1∞2ḣ

Try it online!
Explanation
-;1ḟΓ€ḣ`Goṁ↔`C¢Se:1∞2ḣ  Implicit input, say n=5
                     ḣ  Range: [1,2,3,4,5]
                   ∞2   Infinite list of 2s.
               Se       Pair it with
                 :1     prepend 1: [[2,2,2,2..],[1,2,2,2..]]
              ¢         Cycle: [[2,2,2..],[1,2,2..],[2,2,2..],[1,2,2..]..]
       `G               Cumulative reduce this list using the range
                        as a starting point with the following function:
            `C            Split into chunks of given lengths: [[1,2],[3,4],[5]]
         oṁ↔              Reverse each and concatenate: [2,1,4,3,5]
                        Result is infinite list [[1,2,3,4,5],[2,1,4,3,5],[2,4,1,5,3],[4,2,5,1,3]..]
      ḣ                 Prefixes: [[[1,2,3,4,5]],[[1,2,3,4,5],[2,1,4,3,5]]..]
   ḟ                    Find the first one that satisfies this:
    Γ€                    The first element occurs in the tail.
                        The result is the plain hunt, except for n=1, which gives [[1],[1]]
-;1                     Remove an occurrence of [1] to account for it.

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


text:
Letters associated with prime numbers
If we assign each letter a respective integer, starting from 1, then a is 1, b is 2, c is 3, and so on. After z, the letters loop back around, but with a in front (aa, ab, ac). It then goes to ba, bb, bc... After this is completed, as you may have figured, another letter is added (aaa, aab, aac).  "Prime letters" would be letters that are associated with a prime number. b would be the first prime letter, followed by c, e, g, et cetera.
The Challenge
Given an input n, find the nth "prime letter."
Examples
Input:
1

Output:
b

Input:
4

Output:
g

Input:
123

Output:
za

Scoring Criteria
This is code golf, so the shortest answer in bytes wins!

Basically, yes.

Welcome to the site! This is a nice first question, but given the task, I believe it is a duplicate (although I can't find it just now). I'd recommend that for your next challenge you post it in the Sandbox first to receive feedback.

Perhaps include test cases beyond Z?

related; this is the inverse (letters->numbers). I think the numbers->letters exists somewhere (even if it's just in a bijective base-n question), and prime-related challenges have been done to death. Not saying this is a bad challenge, just that it's a composite of existing ones.

Suggested test cases of big numbers so you can verify the letter wrapping works correctly.

Add the test case 123 -> za. Several current answers get it wrong.

How large can n be?

Also related

Python 3,262 236 209 196 179 114 93 92  97 bytes
def f(n):
 m=k=1;s=''
 while n:m*=k*k;k+=1;n-=m%k
 while k:s=chr(~-k%26+97)+s;k=~-k//26
 return s

Try it online!
Fixed a bug mentioned by @benrg about getting a wrong output for the input 123.
Thanks to:
- @AdmBorkBork for help me getting started and save a few bytes
- @Sriotchilism O'Zaic for saving me 6 bytes
- @mypetlion for saving me 65 bytes and bringing me under 150 bytes :)
- @dingledooper for saving me 21 bytes and bringing me under 100 bytes :D
- @Jitse for saving 1 byte

98 bytes
f=lambda n,i=1,p=1:n and-~f(n-p%i,i+1,p*i*i)
g=lambda n,s='':n and g(~-n//26,chr(~-n%26+97)+s)or s

Try it online!

Welcome to Code Golf SE! I'm not a Python guy, but I know you can save a bunch of bytes by converting your indents to tabs instead of multiple spaces.

Thanks for the tip :)

Also, make sure to check out the Python tips thread.

You might want to give your answer a comb over for extra spaces, I can see 5 spaces right now that are not neccessary.

@SriotchilismO'Zaic Thanks for the suggestion :)

It's not required but Try it online! is a cool site that counts bytes, runs code, and can generate a CG&CC post

You seem to have a small bug somewhere. I tried a large number: Try it online!

@Veskah Thanks for the hint

114 bytes with the same approach Try it online!

@mypetlion thank you, may i take your improvement :)

@Delta Sure. Any improvements posted in the comments are free for you to use. If somebody doesn't want you to use it, they will post it as their own answer.

93 bytes by using a better prime algorithm: Try It Online!

@dingledooper Thnak you for the improvement

-1 byte by using a function instead: Try it online!

@Jitse Thank you :)

Jelly, 8 bytes
ÆNḃ26ịØa

A monadic Link which accepts a non-negative integer that yields a list of characters.
Try it online!
How?
ÆNḃ26ịØa - Link: integer, n
ÆN       - nth prime
   26    - literal 26
  ḃ      - bijective base
      Øa - literal list of characters = ['a', 'b', ..., 'z']
     ị   - index into

For input 123 the output should be za but this code currently prints AZA.

Ah it's bijective base decompression, I guess it has to be ÆNḃ26ịØA then :(

...and that'll be exactly the same as the other Jelly entry becomes.

JavaScript (Node.js), 83 bytes
f=(n,k=0)=>n?f(n-(g=d=>~k%d--?g(d):!d)(++k),k):k<0?'':f(n,k/26-1)+Buffer([k%26+65])

Try it online!
Commented
f = (                // f is a recursive function taking:
  n,                 //   n = input
  k = 0              //   k = counter
) =>                 //
  n ?                // if n is not equal to 0:
                     //   == 1st pass: find the requested prime ==
    f(               //   do a recursive call:
      n - (          //     pass the updated value of n
        g = d =>     //     g is a recursive function which takes d = k
                     //     and tests the primality of k + 1:
          ~k % d-- ? //       if d is not a divisor of (k + 1):
                     //       (decrement d afterwards)
            g(d)     //         do recursive calls until it is
          :          //       else:
            !d       //         return true if d = 0
      )(++k),        //     increment k and invoke g
                     //     so we decrement n if k is prime
      k              //     pass k
    )                //   end of recursive call
  :                  // else:
                     //   == 2nd pass: convert the prime to a string ==
    k < 0 ?          //   if k is negative:
      ''             //     return an empty string and stop
    :                //   else:
      f(             //     do a recursive call:
        n,           //       pass n (which is now 0)
        k / 26 - 1   //       pass k / 26 - 1
      ) +            //     end of recursive call
      Buffer([       //     append the letter corresponding to
        k % 26 + 65  //     k mod 26
      ])             //

Wolfram Language (Mathematica), 53 bytes
Flatten[Tuples[Alphabet[],#]&/@Range@4,1][[Prime@#]]&

Try it online!

Ruby -rprime, 48 47 46 43 bytes
-5 bytes from GB.
->n{(?A..?Z*n).take(Prime.take(n)[-1])[-1]}

Try it online!

Use take instead of first for -1 byte.

And: get nth element of [?a..?a*n] instead of iterating, save 10 bytes.

@GB the second suggestion unfortunately doesn't work on inputs greater than 5 (both on TIO and my machine). Instead, it runs for a few mintues before it gives IndexError (index 268435456 too big) and then the memory overload from constructing the list seems to cause irb segfault as well. I'll use the first suggestion, though!

You don't need r, actually, you could just use [-1]

@GB you are right and I'm amazed that I didn't actually connect the dots.

PHP, 69 bytes
for($n=1,$a=a;$argn||!print$a;$m||--$argn,$a++)for($m=$n++;$n%$m--;);

Try it online!

The guy who decided that $s="z";echo++$s; should give "aa" is either a genius or insane.

@Arnauld I have seen this in other languages too, but PHP contains about 2 decades of mysteries in it. See this: Try it online! and this: Try it online!

Java (JDK), 170 163 158 157 155 bytes
String p(int n){int c=0,i,v=1;String s="";while(c<n){v++;for(i=2;i<=v;i++)if(v%i<1)break;if(i==v)c++;}while(v>0){s=(char)(~-v%26+97)+s;v=~-v/26;}return s;}

Try it online!
Thanks to @Delta for saving me 14 bytes in total

hey you can save some bytes Try it online!.

You can also look her to improve your anwser Code Golf in java

130 bytes

Java, 169 Bytes
isProbablePrime is only valid for 32 bit integers, but it is correct for every 32 bit integer, so this is a valid solution.
(int n)->{int x=-1;for(int i=0;i<n;){x++;if(BigInteger.valueOf(x).isProbablePrime(15))i++;}String r="";while(x>0){x--;int m=x%26;r=(char)(m+97)+r;x=(x-m)/26;}return r;};

I realize now this is basically redundant to the answer by Batscha2k

148 bytes

05AB1E, 18 bytes
<Ø[₂‰˜0KZ27‹#}<Asè

Isn't there a convenient builtin to do this shorter?.. I have the feeling I should be able to use one of the base-conversion builtins here, but it isn't really working out.. Can without a doubt be golfed substantially, though..
Try it online or verify some more test cases.
Explanation:
<              # Decrease the (implicit) input-integer by 1 to make it 0-based
 Ø             # Get the 0-based n'th prime
  [            # Start an infinite loop:
   ₂‰          #  Take the divmod 26
     ˜         #  Flatten the resulting list
      0K       #  And remove any 0s
        Z      #  Get the maximum of the list (without popping)
         27‹   #  If it's smaller than 27:
            #  #   Stop the infinite loop
  }<           # After the loop: decrease all values by 1 to make it 0-based
    A          # Push the lowercase alphabet
     sè        # And index the list of integers into it
               # (after which the resulting character-list is output implicitly as result)

Icon, 135 bytes
procedure f(n)
k:=seq()&s:=0&0=k%(i:=2to k)&s+:=1&i=k&s=1&p:=k-1&n-:=1&n=0
t:="";until t[1:1]:=char(97+p%26)&p:=p/26-1&p<0;return t
end

Try it online!

Pyth, 27 bytes
VQ.VhZIP_b=ZbB;p*\a/Z26@GtZ
Explaination:
                            # Implicit Q = eval(input())
                            # Implicit Z = 0
VQ                          # for N in range(Q)
  .VhZ                      #     for b in infinite_range(Z+1)
      IP_b                  #         if is_prime(b)
          =Zb               #             Z = b
             B;             #             break
             p*\a/Z26       # print("a"*Z//26, end="")
                     @GtZ   #
                            # Implicit print(G[Z-1])


text:
Reconstruct the ASCII art from a string
I have a bunch of ASCII art that I have recovered from a failed hard drive. Unfortunately, all of the newlines were stripped out, and I don't know the resolution of the original artwork. I do know that each one was originally rectangular, but to make matters worse, all the white space at the beginning and end was stripped out too!
I do at least know what one small piece of each one looks like. Can you help me recover the artwork based on the input stream of bytes and the piece of ASCII art I remember?
Example
I remember this one:
__(((55^$$%^/\__%%//\/_666332@12

Had this diamond in it:
/\
\/

The original artwork in this case was 8 characters wide:
__(((55^
$$%^/\__
%%//\/_6
66332@12

Then there's this one, which had a bigger diamond in it.
/\/\/\/\/\:;/  \00F\/\/\  /E%epopox\/e

The diamond looked like this:
 /\
/  \
\  /
 \/

The original artwork contained that diamond, but the white space surrounding the diamond was not white space in the original artwork. I’ve only added in the white space to the left to get the indentation right.
More generally, in each row, any space to the left of the first non-white-space character is indentation padding, and any white space to the right necessarily represents actual white space.
Note that this is also one of those pieces that has had its white space trimmed off. Here's the original, 11 characters wide, with white space restored:
   /\/\/\/\
/\:;/  \00F
\/\/\  /E%e
popox\/e

Remember, the amount of white space removed is unknown. That means I can’t even figure out the possibilities for line length by finding the divisors of the input’s character count.
Input
A string of characters (the artwork, sans newlines, trimmed of white space at the beginning and end), and a two-dimensional string of characters (the piece to look for)
Essentially, the string of characters can be generated from the original artwork thus: artwork.Replace("\n", "").Trim(" ")
Output
The original artwork with newlines inserted where necessary, and with trimmed white space re-added to the beginning of the first line and the end of the last line. If there is more than one possible solution, you may return one arbitrarily (or all of them if you really want to).
Test Cases
Input:
__(((55^$$%^/\__%%//\/_666332@12
/\
\/

Output:
__(((55^
$$%^/\__
%%//\/_6
66332@12

-----------
Input:
 _-/\-_-_vv:;/  \00F\\||\  /E%epopox\/e0
 /\
/  \
\  /
 \/

Output:
   _-/\-_-_
vv:;/  \00F
\\||\  /E%e
popox\/e0

--------
Input:
__               (  )               ||                ||            ___|""|__.._     /____________\    \____________/~~~.
(  )
 ||
 ||
 ""

Output:
     __
    (  )
     ||
     ||
 ___|""|__.._
/____________\
\____________/~~~.

--------
Input:
..XX...XX.......X..X..X  X.....X..X...X  X.....XX......XX...
 XX
X  X
X  X
 XX

Output:
..XX...XX.......
X..X..X  X.....X
..X...X  X.....X
X......XX...

Notably, in this last case, the following is not valid output:
..XX...XX......
.X..X..X  X....
.X..X...X  X...
..XX......XX...

Credit to jrei @ asciiart.eu for the joystick
Rules

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

Is it a problem if we return some extra row of white spaces at the begin/end? Can the pattern have a row/column of white spaces at the begin/end?

Is it guaranteed that the output is rectangular (all row have the same length)?

Is it OK if we assume that any space in the original artwork may have been replaced with another character, or are we supposed to make sure that only surrounding spaces have been replaced?

there are many solutions, for example for the 2nd case the output could also be           _
-/\-_-_vv:;
/  \00F\\||
\  /E%epopo
x\/e0

@user202729 Yes, the output will always be rectangular (although the input does not necessarily contain all of the characters necessary to create such a rectangle, due to missing white space)

@NahuelFouilleul as noted in the original question, if there is more than one answer, you can output an arbitrary one.

@Arnauld not sure exactly what you mean... if you are referring to the space around the diamond in the example, only the space around the outside may actually be another character. If there is any space between two non-white-space characters, either horizontally or vertically, it necessarily represents white space.

@user202729 one could argue that since the amount of white space that has been trimmed out is unknown, you can add in an arbitrary amount of white space before the first row or after the last row. I always store my ASCII art in as compact a form as possible though, so the original did not have any blank rows at the top or bottom, or any blank columns on the left or right.

Here is an example where it does make a difference. If the 1st output really is invalid, then I think you should add such a test case because it makes the challenge significantly harder.

@Arnauld noted. Your example has been added

Can I use other variables than spaces for the padding of "small piece", or does it have to be whitespaces? (Only applies if we can input the small piece as a matrix, like Jonah asked)

@Jonah he answered that before, scroll up a few comments.

Can you confirm that if the following is the "small piece", all spaces are necessary. X  X\n XX \n XX \nX  X

@Kroppeb I’m fine with any convenient padding, as long as the input is still rectangular.

Can we use standard input rules and take the part we're searching for as a matrix (rather than a string with newlines separating each one)?

@Jonah As noted in the original post, yes, default I/O rules apply.

@Kroppeb I have revised the detection of padding to indicate that the horizontal spacing in that example is still padding

Perl 5, 192 bytes
To be golfed more

($_,@F)=@F;$l=max map length,@F;map{$_.=" "x($l-y///c);s/(^ +| +$)|\W/$1=~y, ,.,r||"\\$&"/gme}@F;for$i(0..y///c){$"=".{$i}";$i+=$l,$_=" "x($i-"@-").$_,map{printf"%-$i\s
",$_}/.{1,$i}/g if/@F/}

Try it online!

Can this be adjusted to make sure it outputs a rectangular image? It’s missing the extra space on the last line.


text:
ASCII TURNED SHAPE
How can we depict a turned shape simply and nicely using ascii characters in 3D space?
I suggest this method :
Instead of a circle we use a square rotated by 45° for the cutting section so that we only need '/' and '\' characters to draw it.

 /\
/  \
\  /
 \/

And we use '_' character for the profiles: upper, lower and median.

  _________
 /\        \
/  \________\
\  /        /
 \/________/

Isn't it Turning complete? Well, if you agree, write a full program or a function taking an unsigned integer value N , representing a number of steps , producing a 3d shape as described below.
The profile of this turned shape has the form of a stair step curve raising from 0 to N steps and lowering back to 0 where each step is 2 char('/') high and 5 char long ('_').
Maybe some examples describes it more clearly.
For N = 0 you may output nothing but it's not mandatory to handle it.

  N = 1

   _____
  /\    \
 /  \____\
 \  /    /
  \/____/
.

      N = 2

        _____
       /\    \
   ___/_ \    \__
  /\    \ \    \ \
 /  \____\ \____\_\
 \  /    / /    / /
  \/____/ /    /_/
      \  /    /
       \/____/
.

       N = 3
             _____
            /\    \
        ___/_ \    \__
       /\    \ \    \ \
   ___/_ \    \ \    \ \__
  /\    \ \    \ \    \ \ \
 /  \____\ \____\ \____\_\_\
 \  /    / /    / /    / / /
  \/____/ /    / /    / /_/
      \  /    / /    / /
       \/____/ /    /_/
           \  /    /
            \/____/

Rules :
  - Margins are not specified.
    - Standard loopholes are forbidden.
    - Standard input/output methods.
    - Shortest answer in bytes wins.

What if I don't agree ? I may be wrong, but I don't have any task in that case.

Sandbox: https://codegolf.meta.stackexchange.com/a/18149/84844

Charcoal, 70 69 bytes
ＮθＦθ«Ｊ⊕×⁷⊕ι⁰≔⊗⊕ιι↙ι↑←×⁵_Ｐ↖²→↗ι×⁴_↖ι←×⁵_↓Ｐ↙²→↘ιＪ⁻×⁹θ⊗ι⊖ι__↗ι←Ｐ←__↖ι←__

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

Input N and loop that many times.
Ｊ⊕×⁷⊕ι⁰

Jump to the (middle) right corner of the front slice.
≔⊗⊕ιι

Get the size of the slice.
↙ι↑←×⁵_Ｐ↖²→↗ι×⁴_↖ι←×⁵_↓Ｐ↙²→↘ι

Draw the front slice.
Ｊ⁻×⁹θ⊗ι⊖ι

Jump to the bottom (that we can see) of the back slice.
__↗ι←Ｐ←__↖ι←__

Draw the back slice.

JavaScript (ES8),  322 282 278  272 bytes
Builds the output line by line.
f=(n,y=0,Y=(k=y>2*n)?4*n-y:y,S='___/_25__,/\\    \\25,\\/____/14_/,\\ 14,\\/____/,_____, \\____\\, /    /, \\    \\,_\\, /, \\'.split`,`)=>~Y?(y-2*n?''.padEnd(n*5-(Y>>1)*5-3-y%2-k)+S[y?Y?k*2+y%2:4:5]:'/ 03').replace(/\d/g,n=>S[+n+6].repeat(Y-(n>2||-k)>>1))+`
`+f(n,y+1):''

Try it online!
How?
For each row \$0 \le y \le 4n\$, we define:
$$k=\cases{
0,&\text{if $y \le 2n$}\\
1,&\text{if $y > 2n$}
}$$
$$Y=\cases{
y,&\text{if $k=0$}\\
4n-y,&\text{if $k=1$}
}$$
Each row is first converted into a main pattern. A main pattern may contain digits: they are placeholders for repeated sub-patterns that are expended afterwards.
The middle row (when \$y=2n\$) is a special case which is processed separately. For all other rows, we compute the main pattern ID \$p\$ with:
$$p=\cases{
5,&\text{if $y=0$}\\
4,&\text{if $y \neq 0, Y=0$}\\
2k+(y \bmod 2),&\text{otherwise}\\
}$$
There are no leading spaces for the middle row. For all other rows, the number \$s\$ of leading spaces is given by:
$$s=5n-5\left\lfloor\frac{Y}{2}\right\rfloor-3-(y\bmod 2)-k$$
There are inner sub-patterns (marked with a digit \$\le2\$) and outer sub-patterns (marked with a digit \$>2\$), which are repeated \$n_1\$ and \$n_2\$ times respectively:
$$n_1=\left\lfloor\frac{Y+k}{2}\right\rfloor\\
n_2=\left\lfloor\frac{Y-1}{2}\right\rfloor$$
The above formulae apply to the middle row as well, but are irrelevant for the first and last rows, which do not have sub-patterns.
Below is what we get for \$n=3\$:
  y Y k |  p  |  s  |   before .replace()  | n1 | n2 |      after .replace()
--------+-----+-----+----------------------+----+----+-----------------------------
  0 0 0 |  5  | 12  | ............_____    |  0 | -1 | ............_____
  1 1 0 |  1  | 11  | .........../\    \25 |  0 |  0 | .........../\    \
  2 2 0 |  0  |  7  | .......___/_25__     |  1 |  0 | .......___/_ \    \__
  3 3 0 |  1  |  6  | ....../\    \25      |  1 |  1 | ....../\    \ \    \ \
  4 4 0 |  0  |  2  | ..___/_25__          |  2 |  1 | ..___/_ \    \ \    \ \__
  5 5 0 |  1  |  1  | ./\    \25           |  2 |  2 | ./\    \ \    \ \    \ \ \
  6 6 0 | n/a | n/a | / 03                 |  3 |  2 | /  \____\ \____\ \____\_\_\
  7 5 1 |  3  |  0  | \ 14                 |  3 |  2 | \  /    / /    / /    / / /
  8 4 1 |  2  |  1  | .\/____/14_/         |  2 |  1 | .\/____/ /    / /    / /_/
  9 3 1 |  3  |  5  | .....\ 14            |  2 |  1 | .....\  /    / /    / /
 10 2 1 |  2  |  6  | ......\/____/14_/    |  1 |  0 | ......\/____/ /    /_/
 11 1 1 |  3  | 10  | ..........\ 14       |  1 |  0 | ..........\  /    /
 12 0 1 |  4  | 11  | ...........\/____/   |  0 | -1 | ...........\/____/


text:
A Change in Perspective
In this challenge you will write a piece of text which when viewed from two different angles will create two different programs.
Your string as viewed from above must take a string containing only characters ASCII 10, 32 - 126 and output it as viewed from above.  Additionally your program when viewed from the left must take a string containing only characters ASCII 10, 32 - 126 and output it as viewed from the left.
A string viewed from above will be the first non-space character in every column of the string, or a space if no such character exists, in the order of the columns.
Here is a Haskell program that implements this:
stitchZip (' ' : b) (c : d) = c : stitchZip b d
stitchZip (a : b) (c : d)   = a : stitchZip b d
stitchZip [] x = x
stitchZip x [] = x

main = getContents >>= (putStr . foldr1 stitchZip . lines)

Try it online!
A string viewed from the left will be the first non-space character in every row of the string, or a space if no such character exists, in the reverse order of the rows. We reverse the order of the rows since our left hand would be towards the bottom of the string.
Here is a Haskell program that implements this:
stitch ' ' y = y
stitch x y = x

main = getContents >>= (putStr . reverse . map (foldl stitch ' ') . lines)

Try it online!
Your program may use characters outside of that ASCII range, but for layout purposes all characters (other than newlines) are considered to have a width of 1.  As a side effect of how the views work, your programs cannot have newlines in them (although your string almost certainly will).
Scoring
Your score will be the number of non-space characters in your submission plus the number of space characters that appear in the two programs.
For example if your program were:
sc  e ex mp e
g
        a
   r

d
           l
  o

you would score 16 since there are 14 non whitespace characters in the submission, and each program (score example and old rags) has 1 space.
Your goal is to have as low a score as possible.

Had trouble locating what the programs were supposed to do, might want to add a header of somesort indicating the section describing the desired output of the two programs. Additionally, if a program wanted to contain a newline, how would that be represented (if even possible)?

Maybe that could be achieved by moving "For this challenge..." up above "The first program...", making the first occurrences of each of "viewed from above" and "viewed from the left" bold (or otherwise emphasised), and titling the "The first program..." as "Viewed From Above" & similarly titling "The second program..." as "Viewed From The Left"?

@Draco18s I've reordered things as suggested by JonathanAllan.  As far as newlines go "As a side effect of how the views work, your programs cannot have newlines in them".

Jelly, score 9 + 0 = 9
 Z
       ⁶
      €
     ɗ
    o
   Ḣ
  ḟ
 Ṛ
Ỵ

From the top:
ỴZḟḢoɗ€⁶

Try it online! (or see it self-operate)
From the side:
ỴṚḟḢoɗ€⁶Z

Try it online! (or see it self-operate)
How?
Ỵ Z|Ṛ ḟḢoɗ€⁶ [Z]  - Link list of characters:
Ỵ                 - split at newline characters
  Z               - | top: transpose to get columns
    Ṛ             - | side: reverse the lines
           ⁶      - set the right argument to a literal space character
          €       - for each (x = column (top) OR line (side)):
         ɗ        -   last three links as a dyad - i.e. f(x, space)
      ḟ           -     filter discard (spaces from x)
       Ḣ          -     pop & yield the head (first remaining character or 0 if none left)
        o         -     logical OR (with space character) (replace a 0 with a space)
                  - | top: no code remaining
              Z   - | side: transpose (at this point a no-op since we have a flat list)

Pyth, 15 score
           z
        .T.
        ;
       d
       +
      !
     \
    D
   <
  h
 m
s
_

The two programs are:
smh<D\!d.T.z

Try it online!
_smh<D\!+d;.z

Try it online!
I attempted to make the code as similar as possible between the two programs, hence a few inefficiencies in each. Both programs filter out unwanted spaces by sorting the rows/columns by if the character is less than a !. Since the sorts are stable this preserves the rest of the line. The rest of the programs are fairly straightforward.
The main save that I think could be made for this approach would be to make the code that converts from empty lines to a space more similar. I haven't found a way to do that that isn't wastefully long.

Wolfram Language (Mathematica), score 31 + 2 = 33
                        &
                       )
                    #
                  @
                 /
                ]
               &
              2
             #
            >
           -
          "

        "
       .
      /
     #
    [
   d
  l
 o
F
                   (
@
e
s
r
e
v
e
R

From the top:
Fold[#/." "->#2&]/@(#)&

Try it online!
From the side:
Reverse@(Fold[#/." "->#2&]/@#)&

Try it online!
Takes a matrix of characters as input. If the rows are not guaranteed to have equal length, add another \$18+2\times2=22\$ by replacing # with (PadRight@#/. 0->" ").
If input must be a list of strings, add \$11\$ by replacing # with Characters@#
If input must be a single string, add \$29\$ instead by replacing # with Characters[#~StringSplit~"\n"]
In these cases, if lines are not guaranteed to have equal length, add an additional \$15\$ instead of 22 by replacing Characters with Characters@StringPadRight.

Charcoal, score 22 18
              κ→
              Ｐ
             !
            Ｋ
           Ｋ
          ‹
         ¿
        ι
       Ｆ
       ←
  «Ｊ⁰¬¹
 Ｓ
Ｗ

Note: This is designed for a pleasant input format i.e. at least one character on each line, then a completely empty line to terminate the input. Replace Ｗ with Ｆ and Ｓ with Ａ for a JSON-like input format which allows for empty lines. Additionally, the variable width characters that Charcoal uses (even in a fixed width font, sigh...) mean that the columns don't quite line up nicely. Check the output of the sample link for the expected result.
From the top: Try it online! Link is to verbose version of code. Explanation:
ＷＳ«

Repeatedly read the input.
Ｊ⁰¬¹

Start at the top left of the canvas each time.
Ｆι

Loop through the characters on each line.
¿‹ＫＫ!κ→

Output the current character unless it would overwrite something already there in which case simply move right.
From the side: Try it online! Link is to verbose version of code. Explanation:
ＷＳ«

Repeatedly read the input.
←

Move left for each character, thus reversing the output.
Ｆι

Loop through the characters on each line.
¿‹ＫＫ!Ｐκ

Output the current character without moving the cursor unless it would overwrite something already there.

APL (Dyalog Unicode), score 11 + 2 = 13
         1⍉
        ⍤
       )
      '

    '
   ∘
  ~
 ⊃
(
⌽

Top view:
(⊃~∘' ')⍤1⍉

Left view:
⌽(⊃~∘' ')⍤1

Try it online!
How they work
[⌽] (⊃~∘' ')⍤1 [⍉]
                ⍉   Top view only: Transpose the given char matrix
    (      )⍤1      On each row:
     ⊃~∘' '         Remove all spaces and take the first char
 ⌽                  Left view only: Reverse the string

The lack of one-byte shortcut for a space adds 3 to the score; otherwise it'd be a tie with 05AB1E.

Python 3, 98 + 9 + 5 = 112

                                                                                )).strip()
                                                                                ]
                                                                                -
                                                                                :
                                                                                :
                                                        [
                                                                                )
                                                                                '
                                                                                n
                                                                                \
                                                                                '
                                                                                (
                                                                                t
                                                                                i
                                                                                l
                                                                                p
                                                                                s
                                                                               .
                                                                              s

                                                 n zip(* i+' '*len(s)for i in
                                                i

                                              i

                                            r
                                           o
                                          f
                                         '

                                       '
                                      r
                                     o
                                    ]
                                   1
                                  :
                                 [
                                )
                               (
                              p
                             i
                            r
                           t
                          s
                         .
                       i))
                      (
                   j(j
                  :
                 n
                i
               o
              j
             .
            '
           '
          =
         j
        ,
       s

     a
    d
   b
  m
 a
l

Top view:
lambda s,j=''.join:j(j(i).strip()[:1]or' 'for i in zip(*[i+' '*len(s)for i in s.split('\n')])).strip()

Left view:
lambda s,j=''.join:j(i.strip()[:1]or' 'for i in s.split('\n')[::-1])

Try it online!

05AB1E (legacy), score: 10 (10 non-space bytes + 0)
  ø
         q
        н
       «
      ð
     Û
    ð
   ε
  R
 B
.

Outputs as a list of characters.
Top view: .BøεðÛð«нq
Try it online.
Side view: .BRεðÛð«нqø
Try it online.
EDIT: I now notice it's very similar to the Jelly answer, although I've came up with this independent.. Great minds think alike I guess.
Explanation:
Uses the legacy version of 05AB1E because the zip/transpose builtin ø works on a list of strings (whereas the new version only works on 2D lists).
.B           # Split the (implicit) input-string by newlines,
             # and at the same time append spaces to make all lines of equal length
  ø          # Top view: Zip/transpose the lines; swapping rows/columns
  R          # Side view: Reverse the list of lines
   ε         # Map each string to:
    ðÛ       #  Remove all leading spaces
      ð«     #  Append a space
        н    #  Only leave the first character
         q   #  And exit the program (although it still finishes the map first)
             #  Top view: nothing more
          ø  #  Side view: no-op since we've already stopped the program with `q`
             # (after the map, the resulting character-list is output implicitly)