text:
Shift the digits
Here, x (supplied as input) and n (the result of your computation) are both positive integers. n * x = n shifted. Find n.
Here's an example of shifting:
123456789 -> 912345678
abcdefghi -> iabcdefgh (letters = any 0~9 digit)
123       -> 312

Shifting only happens once to the right. Shifting left, e.g.
123456789 -> 234567891

is not a valid shifting.
Rules

Preceding zeros count after shifting. If the number is 10 and is multiplied by 0.1 (0.1 isn't a valid input), the result is 1, which isn't equal to 01 (10 after shifting).
If your number only has one digit, the shifted result is your number:

1 -> 1
4 -> 4
9 -> 9

Given enough time and resources, your program/function should work for any x input, but you only have to support x in the range [1,9] without timing out on Try It Online.

Test cases
For more test cases, this is OEIS A092697.
1 -> 1 (1 * 1 = 1 shifted.)

9 -> 10112359550561797752808988764044943820224719
(In this test case, x = 9 and n = 10112359550561797752808988764044943820224719.
n shifted = n * x =              91011235955056179775280898876404494382022471)

6 -> 1016949152542372881355932203389830508474576271186440677966
```

Can we have some more test cases / a fully working reference program? I'm still a little unsure of what the program needs to do.

@Lyxal Assuming $x\le9$, I think the longest output is for $x=6$, for which I've found 1016949152542372881355932203389830508474576271186440677966.

Is the task actually possible for any input 10 or bigger? If I'm understanding right your rule about leading zeroes, the shifted value always has the same number of digits as the original, where the multiplied value has more digits in this case.

Agree with @xnor, I doubt if this has solutions ever for $x>9$ without leading zeros because the numbers before and after transformation have the same length

This is https://oeis.org/A092697. Or, rather, the smallest possible outputs are in the sequence. I found this by Googling the large number given for x=9. One formula given says the output is x*(10^m-1)/(10x-1) for the smallest m that makes this a whole number.

Just to be clear, the problem with the current spec is Given enough time and resources, your program/function should work for any x input, since the sequence is apparently not defined for $x>9$.

05AB1E (legacy), 12 bytes
T*<•GIs•°s÷*

Try it online!
T*             - Multiply input by 10
  <            - subtract 1
   •GIs•°      - 10**1045044
         s÷    - Integer divide
           *   - Multiply by input again

Port of xnor's answer

N.B. It computes (as required) but the answer does not fit in TIO's output :D

Actually the answer is incorrect, and I'm not sure why - for x=9 the result should start 101123595... (see here)

is it just the integer division? m=43 seems to work :/

^ or 44 even, sorry.

Python 2, 31 bytes
lambda x:10**1045044/(10*x-1)*x

Try it online!
Produces enormous million-digit numbers. Uses the formula from the OEIS page, x*(10^m-1)/(10*x-1). But, instead of using the smallest possible m for the given x, we hardcode m=1045044, which works for each x from 1 to 9. (I'm assuming only these x need to be supported, because bigger ones are impossible.)
We need an m that's divisible by the order of 10 modulo 10*x-1. So, to get one that works for all x, we take the least common multiple (LCM) of the orders, giving m=1045044.
x order
-----
1 1
2 18
3 28
4 6
5 42
6 58
7 22
8 13
9 44

We save a few bytes by doing 10^m/(10*x-1) instead of (10^m-1)/(10*x-1), since Python 2's floor division cuts off the remainder and gives the same result, as long we move the *x after the division.
Despite how the massive the results are, TIO can in fact compute them for every x from 1 to 9 without timing out. Validating the rotating property of an output string-wise takes longer, but if you set validate=True in the TIO link and the limit to a single x, this also completes before timing out. I've also validated all the results on my machine.

JavaScript (Node.js),  54 48  44 bytes
Saved 4 bytes thanks to @xnor
Takes input as a BigInt. Based on the formula given in A092697.
f=(x,m=t=10n)=>~-m%(q=t*x-1n)?f(x,m*t):m/q*x

Try it online!

JavaScript (Node.js),  165 153  151 bytes
Takes input as a BigInt and performs a recursive search.
f=(x,n='',i=-1)=>+n[[d,...a]=[...x*BigInt(n)+''],s=a.join``+d,0]&&n==s?o=n:n.slice(0,i++)==s.slice(-i,-1)&i<60&&([...2**29+'4'].some(k=>f(x,k+n,i)))&&o

Try it online!

NB: Both solutions assume \$1\le x\le9\$.

It looks like you can avoid aliasing p, and not bother decrementing before the division: Try it online!

Wolfram Language (Mathematica), 42 bytes
#(10^MultiplicativeOrder[10,a=10#-1]-1)/a&

Try it online!
xnor's method n-shifted my bytes...
Wolfram Language (Mathematica), 24 bytes
#(10^1045044-1)/(10#-1)&

Try it online!

@ExpiredData Yes, I noticed xnor's answer, which makes this challenge trivial. I'll post it as a second approach

I don't know Mathematica, but is the a short floor-division operator that you replace the division with use to avoid decrementing -1 after the 10^1045044?

Also, 29! should work for the constant, but this surely would make the code take too long to run.

Jelly, 13 bytes
⁵×’⁵*“ÐṂ+’¤:×

Try it online! (The 1045044 digits do not fit within TIO's output)
An implementation of xnor's LCM method.
⁵×’⁵*58!$¤:× works in theory for 12, but there's no chance of calculating results with \$58!\$ digits within 60s using Jelly.
⁵×’⁵*“ÐṂ+’¤:× - Link: integer,    x
⁵             - 10                10
 ×            - multiply          10x
  ’           - decrement         10x-1
          ¤   - nilad followed by link(s) as a nilad:
   ⁵          -   10              10
     “ÐṂ+’    -   1045044         1045044
    *         -   exponentiate    10^1045044
           :  - integer division  10^1045044//(10x-1)
            × - multiply          10^1045044//(10x-1)*x


text:
The most common substring
The purpose of this task is to write a program or function to find the most common substring within a given string, of the specified length.
Inputs

A string, s, of any length and characters that are valid as inputs for your language.
A number, n, indicating the length of substring to find. Guaranteed to be equal to or less than the length of the string.

Output
The most common (case-sensitive) substring of s of length n. In the case of a tie, any of the options may be output.
Win Criteria
This is code-golf, so lowest bytes wins; usual exceptions etc. apply.
Examples
Hello, World!, 1 > l (appears 3 times)
Hello! Cheerio!, 2 > o! (appears twice)
The Cat sat on the mat, 2 > at (appears three times)
The Cat sat on the mat, 3 > at  or he  (both with trailing spaces. Both appear twice - note case-sensitivity so The and the are different substrings)
Mississippi, 4 > issi (appears twice, note that the two occurrences overlap each other)
Some more examples, all using the same input string*
Bb:maj/2
F:maj/5
Bb:maj/2
G:9/3
Bb:maj7
F:maj/3
G:min7
C:sus4(b7,9)
C:sus4(b7,9)
C:sus4(b7,9)
F:maj
F:maj

(note the trailing newline)
1 > \r\n(appears 12 times, counting \r\n as a single character - my choice, your code may differ on this - otherwise either \r or \n appear the same number of times). : also appears 12 times
2 > :m (appears 8 times)
3 > :ma or maj (appears 7 times)
4 > :maj (appears 7 times)
5 > F:maj or \r\nF:ma or :maj/ (appears 4 times)
14 > \r\nC:sus4(b7,9)\r\n (appears 3 times)
(* input is taken from How predictable is popular music?. The result of this task might be used, for example, to find the most efficient way to apply a substitution in order to compress the string)

@KevinCruijssen thanks for the n=5 spot. regarding your second point, each line in the test case ends with a newline - there are 12 lines in the test case, so 11 newlines. Or am I missing something? Or maybe the formatting is messing things up?

...but, : does appear 12 times (not sure how you got 8?) - so that's actually the largest. I've added a trailing newline to the test case, so now we have \r\n and : tying.

Ah oops, not sure how I got 8 instead of 12 indeed.. Mainly wanted to say : occurs one more than \n, but with a trailing newline they indeed both occur an equal amount of times.

Is it acceptable to return the highest occurring substring with its count? (C.f. this answer)

@RGS sure, why not?

More interesting is requiring the solution run faster than $O(|s|^2)$. See rolling hashes and https://stackoverflow.com/questions/1597025/most-common-substring-of-length-x

@qwr feel free to submit an answer using that technique, it would be interesting to see even if it didn't win the code-golf competition

05AB1E, 5 bytes
ŒIù.M

Try it online or verify the smaller test cases or verify the larger test case (which is a bit slow).
Explanation:
Œ      # Push all substrings of the (implicit) input-string
 Iù    # Only keep substrings of a length equal to the second input-integer
   .M  # Only keep the most frequent item of the remaining substrings
       # (after which it is output implicitly as result)

Python 3.8, 75 68 97 63 bytes
lambda s,n:max(l:=[s[j:j+n]for j in range(len(s))],key=l.count)

You can try it online! Increased byte count because, as @xnor kindly pointed out, Python's str.count doesn't count overlapping substrings... But then @xnor's reformulation of what I was doing allowed to slice a third of the bytes!
How:
l:=[s[j:j+n]for j in range(len(s))]

This creates a list of all the substrings in s of size n, plus the suffixes of size n-1, n-2, ..., 1. Then we find the max on that list, with the numerical value being used to sort given by
l.count

That means that if a and b are from l, a > b if a shows up more times in l than b. This means the shorter suffixes are never the result of the max because they only show up once, and even if the correct-sized substrings only show up once, they are first in l so they come out instead of the short suffixes. This allows me to save some bytes in the range used, given that I don't have to prevent i+n from being larger than len(s).
# Python, 83 64 bytes
lambda s,n:max((s[i:i+n]for i in range(len(s)-n+1)),key=s.count)

Thanks to @mypetlion I saved a LOT of bytes :D
You can try it online with my very own incredible test case!

Replace sorted(...)[-1] with max(...) to save 7 bytes.

Replace lambda t:s.count(t) with s.count to save 12 bytes.

Incredible! You shaved 19 bytes already!!

fixes typos

makes sense, too

or if you prefer this

@S.S.Anne gives credit, too

It looks like this unfortunately doesn't get the "Mississippi", 4 test case right, due to how Python counts substrings.

@xnor defining my own str.count is a possible fix but it is extremely long :/ do you have any hints for better ideas?

@RGS My best thought is to generate the list of substrings and do max(l,l.count) on it.

@xnor that is incredible, as it allowed me to golf even further than my initial answer :O

Brachylog, 8 bytes
s₎ᶠọtᵒth

Try it online!
Explanation
  ᶠ        Find all…
s          …substrings of <1st element of input>…
 ₎         …of length <2nd element of input>
   ọ       Get the list of each substring with its number of occurrence
    tᵒ     Order by the number of occurrence
      t    Take the last one
       h   Output the substring itself

Perl 6, 49 46 bytes
-3 bytes thanks to SirBogman
{$^n;bag($^a~~m:ov/.**{$n}/X~$).max(*{*}).key}

Try it online!
Explanation
{                                            }  # Anonymous block
 $^n;  # Declare argument
         $^a~~m   /       /  # Regex match input string
               :ov           # Also return overlapping matches
                   .**{$n}   # Match n-character strings
                           X~$   # Stringify matches
     bag(                     )  # Convert to Bag (multiset)
                               .max(*{*})  # Find Pair string=>count with max value
                                         .key  # Get key (string)

46 bytes /.**{$n}/ works. Not sure why /.**$n/ doesn't.

@SirBogman Cool, this sure would have helped me a few times. /$n/ is supposed to interpolate literal text (like \Q...\E in Perl 5), so I can see why .**$n doesn't work.

I don't fully understand what .max(*{*}) is doing. It seems like both of those whatever parameters are Pairs?

@SirBogman Only the first * is a whatever parameter. The second * is simply to get a full slice of the Pair, returning a list containing its only value. So *{*} is effectively the same as *.values.

Cool. Those whatevers are very flexible.

JavaScript (ES6),  85 83  80 bytes
Takes input as (string)(length).
s=>n=>[...s].map(o=m=(x,i)=>(o[k=s.substr(i,n)]=-~o[k])<m|!k[n-1]?0:m=o[O=k])&&O

Try it online!

Java 10, 212 211 196 195 146 143 bytes
s->n->{String r="",t;for(int m=0,c,j,i=s.length();i-->n;)for(c=0,j=-1;(j=s.indexOf(t=s.substring(i-n,i),j+1))>=0;)if(++c>m){m=c;r=t;}return r;}

-15 bytes by outputting the substrings with their count, which is allowed.
-1 byte thanks to @ceilingcat.
-52 bytes thanks to @OlivierGrégoire.
Try it online.
Explanation:
s->n->{         // Method with String and Integer parameters and String return-type
  String r="",  //  Result-String, starting empty
         t;     //  Temp-String
  for(int m=0,  //  Largest count, starting at 0
          c,    //  Temp count integer
          j,    //  Temp index integer
          i     //  Index-integer `i`
      =s.length();i-->n;)
                //  Loop `i` in the range (input-length, n]:
    for(c=0,    //   Reset the temp-count to 0
        j=-1;   //   And the temp-index integer to -1
        (j=s.indexOf(t=s.substring(i-n,i)
                //   Set String `t` to a substring of the input-String in the range [i-n,i)
           j+1))//   Set the temp-index `j` to the index of String `t` in the input-String,
                //   only looking at the trailing portion after index `j+1`
        >=0;)   //   And continue looping as long as long as that substring is found
      if(++c>m){//    If the temp-count + 1 is larger than the current largest count:
        m=c;    //     Set this current largest count to this temp-count + 1
        r=t;}   //     And the result-String to this temp-String
  return r;}    //  After the nested loops, return the result-String

146 bytes: S->n->{String R="",x;for(int M=0,I=0,m,i;I<S.length()-n;I++)for(m=0,i=-1;(i=S.indexOf(x=S.substring(I,I+n),i+1))>=0;)if(++m>M){M=m;R=x;}return R;} (no imports, and Java 8, not 10)

@OlivierGrégoire Thanks! That's a much better approach. I had the feeling it was possible without the Map and/or stream, but couldn't figure it out.

I also tried with .split("\\Q"+substring+"\\E"), without success because of the overlapping test case in Mississippi

143 bytes: s->n->{String r="",t;for(int m=0,c,j,i=s.length();i-->n;)for(c=0,j=-1;(j=s.indexOf(t=s.substring(i-n,i),j+1))>=0;)if(++c>m){m=c;r=t;}return r;} (just changing the iteration manner)

PHP, 133 126 bytes
for(;$k<=strlen($i=$argv[1])-$j=$argv[2];)$s[]=substr($i,$k++,$j);$c=array_count_values($s);asort($c);echo array_key_last($c);

Try it online!
Annoyingly asort() and end() can't be chained into one expression.
-7 bytes thanks to @manatwork

PHP 7.3 has array_key_last() to reduce it to 126 characters.

I really should learn all my array functions.

JavaScript (Node.js), 92 bytes
s=>n=>s.map(F=t=>([F[w=(w+t).slice(-n)]=-~F[w],w]),w="").sort(([a],[b])=>a-b)[s.length-1][1]

Try it online!
Takes s as a list of characters in (s)(n) syntax.

=>a-b)[s.length-1] to =>b-a)[0] to sort in reverse order and save some bytes.

@KevinCruijssen That could fail if there are no repeating substrings. Try f([..."123456"])(2).

Ah, you're indeed right. My bad.

C# (Visual C# Interactive Compiler), 97, 96, 92 bytes
s=>n=>s.Skip(n-1).Select((_,i)=>s.Substring(i,n)).GroupBy(x=>x).OrderBy(g=>g.Count()).Last()

Try it online!
Explanation:
s.Skip(n-1).Select((_,i)=>s.Substring(i,n)) //select every substring of size n
    .GroupBy(x=>x)                          //group by value
        .OrderBy(g=>g.Count())              //order by increasing recurrence
            .Last()                         //return the last one

-1 byte by using a currying lambda (s,n)=> to s=>n=>: Try it online.

I'm pretty sure returning a Grouping is not acceptable.

@mypronounismonicareinstate check the comments section

Charcoal, 28 bytes
ＮθＦ⊕⁻Ｌηθ⊞υ✂ηι⁺θιＵＭυ⟦№υιι⟧⊟⌈υ

Try it online! Link is to verbose version of code. Outputs the lexicographically largest substring with the highest count. Explanation:
Ｎθ

Input the desired substring length.
Ｆ⊕⁻Ｌηθ⊞υ✂ηι⁺θι

Extract all substrings of that length and push them to a list.
ＵＭυ⟦№υιι⟧

Replace each substring with a tuple of its count and the substring..
⊟⌈υ

Print the substring with the highest count.

Japt -g, 8 bytes
ãV ü ñÊÌ

Try it

Is there any specific reason you use your own interpreter instead of the ethproductions one or the TIO one?

@S.S.Anne I don't know about Shaggy, but I use it because it has a lot of features that make golfing in Japt a lot easier, like the autogolf button

Wolfram Language (Mathematica), 30 bytes
#&@@Commonest[##~Partition~1]&

Takes an array of characters, returns an array of characters.
Try it online!
Wolfram Language (Mathematica), 36 bytes
#&@@Commonest[##~StringPartition~1]&

Takes a string, returns a string.
Try it online!

Zsh, 89 bytes
local -A m
repeat $#1 ((++m[${1:$[i++]:$2}]))
for k v (${(kv)m})((v>M))&&r=$k&&M=$v
<<<$r

Try it online!
local -A m                    # associative array, "local" is shorter than "typeset"
repeat $#1 {                  # looping for the length of the string will cause the
                              # program to use shorter, invalid strings as
                              # the bash-style slice gets cut short
    ((++m[${1:$[i++]:$2}]))   # increment the map at the key with substring
}                             # starting at $[i++] with length $2
for k v (${(kv)m}) {          # loop over the associative array's keys/values
    ((v>M)) && r=$k && M=$v   # find the max value M, save the key as r.
}                             # looping forward ensures we avoid our invalid subtrings
<<<$r                         # print $r

C++ (clang), 201 \$\cdots\$ 151 150 bytes
#import<map>
using S=std::string;S f(S s,int n){std::map<S,int>m;S t,r;for(int i=0,x=0;i<=s.size()-n;r=x<++m[t=s.substr(i++,n)]?x=m[t],t:r);return r;}

Try it online!
Ungolfed
#include<map>
#include<string>
std::string f(const std::string& s,int n) {
    std::map<std::string,int> m;
    for(int i=0;i<=s.size()-n;++i) {
        m[s.substr(i,n)]++;
    }
    int x=0;
    std::string r;
    for(auto a:m) {
         if(x<a.second) {
             x=a.second;
             r=a.first;
         }
    }
    return r;
}

Excel (Ver. 1911), 60 Bytes
B2 'Input: String
B3 'Input: Sub-string Length
C2 =-COUNTIF(D2#,D2#)
D2 =MID(B2,SEQUENCE(LEN(B2)),B3)
E2 =SORT(C2#:D2)
F2 'Output

Test Sample
Note: Newlines do exist in cells, but default formatting doesn't show them. Also only 10 of the 105 rows are shown to keep the image a decent size.

Jelly, 6 bytes
I have a feeling there may be an elusive 5-byter out there.
ṡċ@Þ`Ṫ

Try it online!

PowerShell, 72 bytes
param($s,$n)(0..($s.Length-$n)|%{$s|% s*g $_ $n}|group|sort C*|% N*)[-1]

Try it online!
Unrolled:
param($s,$n)
(
    0..($s.Length-$n)|%{
        $s|% substring $_ $n
    }|group|sort Count|% Name
)[-1]

Ruby, 58 bytes
->s,n{a=(0..s.size).map{|i|s[i,n]};a.max_by{|e|a.count e}}

Try it online!

Perl 5 -lp, 47 bytes
++$k{$_}>$k{$\}&&($\=$_)for<>=~/(?=(.{$_}))/g}{

Try it online!

Japt -h, 8 bytes
ãV
ñ@è¶X

Try it

Go, 131 bytes
func f(s string,l int)(p string){x,i:=0,0
m:=map[string]int{}
for;i<=len(s)-l;i++{t:=s[i:i+l]
m[t]++
if m[t]>x{x=m[t]
p=t}}
return}

Takes as input a string and an int representing the string and the length of the substring respectively.
Some newlines can be replaced by semicolons if people prefer one-liners.
Try it online!

source: Stack Exchange

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

sort: votes


text:
Generate a secure password
Task
Your task is to generate a password that is both secure and short in the fewest bytes possible given an integer seed as input.
Input
No seed
Or
An integer seed
Output
A password
Scoring
Your score is how many seconds the password takes to crack on How secure is my password divided by (bytes * password length)
Scoring is unbalanced because this is for fun

Surely the score needs to be for a specific seed? Otherwise it will vary depending on the seed...

It would probably have been more interesting with a maximum length for the password (such as 32 characters), to prevent the infinite score from being reached.

I'm voting to close this question as off-topic because it's really a question of the length of the output.  Without more details or restrictions, it's just a "generate infinite output" challenge.

@Brzyrt You should probably use the Sandbox to test questions before posting, this feels half-baked.

Given that the output is supposed to be random or depend on the input seed, which output(s) are used for scoring?

APL (Dyalog Unicode), ∞
Full program. Does not need a seed.
⎕AV

Try it online!
⎕AV is the Atomic Vector, i.e. the code page: "\u0000\b\n\r \f\u0006\u0007\u001B\t⌶ɫ%'⍺⍵_abcdefghijklmnopqrstuvwxyz\u0001\u0002¯.⍬0123456789\u0003⊢¥$£¢∆ABCDEFGHIJKLMNOPQRSTUVWXYZ\u0004\u0005ý·⍙ÁÂÃÇÈÊËÌÍÎÏÐÒÓÔÕÙÚÛÝþãìðòõ{€}⊣⌷¨ÀÄÅÆ⍨ÉÑÖØÜßàáâäåæçèéêëíîïñ[/⌿\\⍀<≤=≥>≠∨∧-+÷×?∊⍴~↑↓⍳○*⌈⌊∇∘(⊂⊃∩∪⊥⊤|;,⍱⍲⍒⍋⍉⌽⊖⍟⌹!⍕⍎⍫⍪≡≢óôöø\"#\u001E&´┘┐┌└┼─├┤┴┬│@ùúû^ü`∣¶:⍷¿¡⋄←→⍝)]\u001F §⎕⍞⍣"

05AB1E, Infinite score.
Gets Forever on the password generator. So score is Infinite.
žĆ

Try it online!

Why can't I type it @a'_'

Yeah, a bit of ALT-code never hurt anybody.

JavaScript (Node.js), 11 bytes, score = Infinity
An evil password.
_=>1n<<666n

Try it online!
Generates:
306180206916083902309240650087602475282639486413866622577088471913520022894784390350900738
050555138105234536857820245071373614031482942161565170086143298589738273508330367307539078
392896587187265470464n

The final 'n' in the output is what makes howsecureismypassword.net believe that there are enough distinct characters for this to take forever to crack.
Without it, it would take only 79,220,219,535,072,410,000,000,000,000 quinquagintillion years. :-)

Python 3, 19 6 bytes, Score: Inf
Whopping -13 thanks to @a'_'

help()

Try it online!

Finally an answer that I can golf! 6 bytes

SOGL V0.12, 1 byte, score: Infinity
Since we can't win 05AB1E, what about a shorter solution? This program basically yields the full SOGL code page.
█

Try it Here!

Ahaha! That is very funny indeed. I like how this challenge devolved from "who can generate a good random password" to "who can print the weirdest gobbledygook in the fewest characters".

GolfScript, 4 bytes, score = Infinity
An evil password.
74,`

Try it online!
Generates:
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73]

The final '`' is what makes howsecureismypassword.net believe that there are enough distinct characters for this to take forever to crack.
Without it, it would take only 79,220,219,535,072,370 quinquagintillion years. :-)

brainfuck, 5 bytes, Score = Inf
+[+.]

Try it online!

PHP, 10 bytes -> Infinite score
phpinfo();

Try it online!
Basically a kind of port of @SurculoseSputum's python answer

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


text:
Simulate a random walk
Context
In this challenge, a random walk is a stochastic process in which a particle at a position with integer coordinates (or a drunk man) moves at each integer time step (that is, at t = 1, 2, 3, ...) by taking a step of size 1 to any of its neighbouring positions, with the direction of the step being aligned with the axis, but chosen randomly
For example, in one dimension, we may have the following table of positions at the given times, starting at t = 0 with the initial condition p = 2:
----------
| t |  p |
----------
| 0 |  2 |
----------
| 1 |  3 |
----------
| 2 |  2 |
----------
| 3 |  3 |
----------
| 4 |  2 |
----------
| 5 |  1 |
----------
| 6 |  0 |
----------
| 7 | -1 |
----------
| 8 |  0 |
----------
| 9 | -1 |
----------
   ...

Task
Your task is to simulate a random walk in n dimensions from a supplied starting point, until the drunk man arrives at the origin for the first time, i.e. when we reach the point with coordinates [0,0,...,0] for the first time. If we start at the origin, nothing has to be done because we already arrived.
In the example above, the program would have stopped at t = 6.
You can take whatever probability distribution you want over the possible directions to go, so long as, for any position and any direction, there is a non-zero probability of that direction being picked.
Notice that your program must work for an arbitrary dimension, even though in practice, for higher dimensions it will not stop in a reasonable amount of time.
Input
Any initial position with integer coordinates, of any positive size (so 1 or more). You can infer the dimensions of the random walk from the size of the input or you can take the dimension as an extra input. If you do, assume the dimension given matches the size of the initial position.
Input of initial position can be in any sensible format, including:

a list of integers
one input coordinate per function argument

Your program should work for any n, even though in practice it will time out for n >= 3 unless you are incredibly lucky :)
Output
You should return or print any of the following:

all the intermediate positions occupied by the particle until the end of the random walk
all the intermediate steps taken by the particle until the end of the random walk

The intermediate positions can be displayed in any human-readable way, as long as no two different positions are displayed the same way. Same applies to intermediate steps taken.
Test cases
These should finish on TIO often:
[3]
[1, 0]
[0, -2]
[1, 1]
[-1,1]
[0]
[0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0]

These will probably timeout, but that is fine as long as your program runs:
[1, 0, 0, 0]
[0, 0, 3, 0, -2, 100]
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

You can check this reference program where I set the seed so that you can see it terminating for a random walk of 3 dimensions.

This is code-golf so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it... And happy golfing!

Does that walk actually have to be random, or can we walk home deterministically?

And what exactly is the rule about stopping when you get to the origin? Can you keep going? Or pass it once but return and stop later? Does the stopping always have to happen in any run, or is this just part of the non-zero probability of arriving home?

@xnor I had used bad wording for that. I want non-zero probability of any direction being picked at any position, so we can't walk deterministically. You can use heuristics to weigh the chances, though. If you want that. And the stopping rule is the termination criteria for your program. Your program should stop as soon as you get home and only when you get home.

The point here really isn't about getting home. It is about simulating a random walk. "Getting home" is just some artificial criterion for your programs to be able to stop at some point and provide some observable output.

Thanks, that clears it up. To make sure, any distribution that gives nonzero chance to each direction at each point is valid then?

@xnor yes, that is correct. In other words, given any two points, there is a non-zero probability of going from one to the other. Correct?

For more than 2 dimensions there’s a nonzero probability that the walk never returns to the origin. So if the program outputs the steps when finished, it may never finish, and so no output will be produced. Is that allowed? Or should each step be output on the fly, producing a possibly infinite sequence of steps?

@LuisMendo It is ok that the program never finishes in those cases. You can output the steps on the fly or by the end of the program, that is up to you. I just want the programs to be able to handle arbitrary dimensions, I don't want to be maths :)

Are we allowed to print 0,0 or the origin?

@S.S.Anne yes that is fine

Because the probability of the directions doesn't have to be equal, I think a program that chose the dimension with the greatest absolute value with 90% probability, and chose to head toward the origin along that dimension with 90% probability, would comply and would reach the origin pretty quickly even for a high number of dimensions.

That's not a criticism, just an observation. Oh, and if two or more dimensions had equally high values it could pick between them with equal probability.

@DavidConrad that is correct, yes. But the point of the challenge is not to reach the origin, so I don't really mind if your program never really gets there :)

I realize reaching the origin isn't the goal, but was thinking about it because of your comment that a program will probably time out for high n "unless you are incredibly lucky :)"

Must we output the beginning and ending positions as well, or can one (or both) of them be omitted?

@JungHwanMin one or both may be ommitted

Jelly,  13  12 bytes
LXṬ,N$X+µẸÐ¿

A monadic Link accepting a list of integers which yields a list of lists of integers.
Try it online!
How?
LXṬ,N$X+µẸÐ¿ - Link: list of integers, p (length d)
          Ð¿ - collect up while...
         Ẹ   - ...condition: any? (when we reach [0]*d this does not hold
        µ    - ...do: the monadic chain - i.e. f(v); initially v=p:
L            -   length (of v) = d
 X           -   random integer (in range [1,d])
  Ṭ          -   untruth     e.g. 4 -> [0,0,0,1]
     $       -   last two links as a monad:
    N        -     negate              [0,0,0,-1]
   ,         -     pair                [[0,0,0,1],[0,0,0,-1]]
      X      -   random choice         [0,0,0,1] OR [0,0,0,-1]
       +     -   add (to v)  e.g. [0,0,0,-1] + [4,2,3,2,5] = [4,2,3,1,5]

Nice Jelly submission! +1

Wolfram Language (Mathematica), 99 bytes
#//.i_/;Union@i!={0}:>(i+RandomChoice@Select[Tuples[{-1,1,0},d=Tr[1^i]],#~Count~0==d-1&])&&Print@i&

Try it online!

Nice submission! Thanks for your work +1

Python 3, 92 87 82 81 75 bytes
Input: the starting position (as list) and number of dimensions.

def f(p,d):
 r=id(f)
 while any(p):p[r%d]+=r//d%2*2-1;print(p);r=hash((r,))

Try it online!
Explanation
I created my own custom random generator as follow:

r=id(f): seed the generator - this is the source of randomness since the ID of f is different each time the program runs.
r=hash((r,)) generates the next random by hashing the tuple (r,). This is the shortest I could find, as hash(r) just returns r, while hash([r]) is not valid due to list not being hashable.

This ended up being shorter than using random or time module.
For each iteration, the program simply picks a random coordinate and add 1 or -1 (randomly) to it.

r%d is a random number between 0 and d-1 inclusive, used to pick a random coordinate.
r//d%2 is a random number in \$\{0,1\}\$, and (r//d%2)*2-1 maps it to \$\{-1,1\}\$.

any(p) checks if p has some non-zero coordinate, in which case the programs continue to run.

In case id and hash are not considered "random" enough, here is the same program but using time for randomness
Python 3, 92 87 82 81 bytes
-1 byte thanks to @RGS
import time
t=time.time_ns
def f(p,d):
 while any(p):p[t()%d]+=t()%2*2-1;print(p)

Try it online!

You can save a byte if you do import time; t=time.time_ns instead of from time import *; t=time_ns.

Even though the id of f is different every time the program is run, it still remains the same in the same session, for example, which violates the rule of the function being reusable.

@JoKing Didn't know that, thanks! Still trying to fix this.

Perl 6, 48 bytes
{{[(.rand+|0=>(-1,1).pick){^$_}Z+@$_]}...*.none}

Try it online!
Returns all intermediate positions.
Explanation
{                                              }  # Anonymous list
                                      ...  # Create sequence
 {                                   }  # Compute next item by
   (        =>           )  # Create pair with
    .rand+|0                # random integer in [0,dim) as key
              (-1,1).pick   # -1 or 1 as value
                          {^$_}  # Lookup values [0,dim)
                               Z+@$_   # Add to previous vector
  [                                 ]  # Store in array
                                         *.none  # Until all coords are zero

Cool perl submission! +1

05AB1E, 15 bytes
[=D_P#āDΩQD(‚Ω+

Inspired by @JonathanAllan's Jelly answer.
Try it online.
Explanation:
[           # Start an infinite loop:
 =          #  Print the current list with trailing newline (without popping),
            #  (which will use the implicit input-list in the very first iteration)
  D         #  Duplicate the current list
   _        #  Check for each value whether it is 0
            #   i.e. [0,4,0] → [1,0,1]
    P       #  And if all are truthy:
     #      #   Stop the infinite loop
  ā         #  Push a list in the range [1,length] (without popping)
            #   i.e. [0,4,0] → [1,2,3]
   D        #  Duplicate it
    Ω       #  Pop and push a random value from this list
            #   i.e. [1,2,3] → 3
     Q      #  Check for equality; the random 1-based position becomes 1, the others 0
            #   i.e. [1,2,3] and 3 → [0,0,1]
      D(‚   #  Pair it with a negative copy of itself
            #   i.e. [0,0,1] → [[0,0,1],[0,0,-1]]
         Ω  #  Pop and push either of these two lists
            #   i.e. [[0,0,1],[0,0,-1]] → [0,0,-1]
          + # And the values at the same indices
            #  i.e. [0,4,0] + [0,0,-1] → [0,4,-1]

Thanks for your 05AB1E solution! I was starting to think this would never happen :'(

ah I see. I thought you could code this in 5 minutes, like in the toilet :p have a nice week

PowerShell, 68 63 61 57 bytes
-4 bytes thanks to mazzy
param($n,$d)for(;$n-ne0){$n[(random $d)]+=1,-1|random;$n}

Try it online!
Less Ugly Form for 2 extra bytes.
The neat part of this answer is the for conditional, $n-ne0. When you apply comparison operations to arrays, it applies it to each element and acts as a filter, in this case filtering out all 0s. If we filter everything out (i.e., we're at (0,0,...,0)), we get an empty array and those are considered false. As a side note, for the singleton case, you have to explicitly cast the parameter to a list. Otherwise, it wants to play ball as an int which doesn't go over well.
I reread the comments and noticed you didn't need to print the initial config, saving 5 bytes. This now means things that start at the origin return nothing but that seems up to spec.

Hey there, I don't know what you mean by n lines in a row represents a step but it probably counts! :P

@RGS Looks a bit like this

That is fine, yes. It is annoying, but it is unambiguous.

may be $n-ne0 instead $n|?{!!$_}?

@mazzy But that doesn't look as cool. (Thanks :D)

Ruby, 46 bytes
p(l) prints the contents of l and then returns the same array as well, making things very convenient as we can wrap the print statement into the termination condition.
->l,d{l[rand d]+=rand(2)*2-1until[]==p(l)-[0]}

Try it online!

Looking good! :D +1

C (gcc), 161 bytes
z(a,l,r)int*a;{for(r=0;l--;)r|=a[l];l=r;}p(a,l)int*a;{for(puts("");l--;)printf("%d,",*a++);}f(a,l)int*a;{for(srand(&l);p(a,l),z(a,l);)a[rand()%l]+=1-rand()%2*2;}

Prints all coordinates.
Example output:
0,-2,
1,-2,
1,-1,
1,0,
2,0,
1,0,
0,0,

-1 byte thanks to ceilingcat!
Try it online!

Nice submission! +1 This output is acceptable, don't worry. But why does it have all the leading #?

@RGS It was originally because without it you wouldn't be able to tell the coordinates apart. But now I might be able to remove it and the output would still be clear.

It may at least save one byte if you remove it from the code, no? and technically the output doesn't need to be pretty. It just needs to be "parseable"

@RGS There. That's much better. (before, all the coordinates were smashed together and you couldn't tell one set from the next)

@ceilingcat Thanks!

Charcoal, 25 bytes
Ｗ⌈↔θ«≔‽Ｌθι§≔θι⁺§θι⊖⊗‽²⟦Ｉθ

Try it online! Link is to verbose version of code. Explanation:
Ｗ⌈↔θ«

Repeat until the origin is reached. (Ｗ⊙θκ« also works for the same byte count.)
≔‽Ｌθι

Pick a random dimension.
§≔θι⁺§θι⊖⊗‽²

Move one step randomly along that dimension.
⟦Ｉθ

Output the new coordinates. The ⟦ double-spaces the coordinates for clarity, but if that's not required then it could be removed.
Bonus program:
ＪＮＮＷ∨ⅈⅉ✳⊗‽φ¹@

Try it online! Takes two dimensions only. Sample output:
    |
 ||----
----@
||
|-

I like the bonus program. +1 Is it printing some representation of the random walk?

@RGS It prints a - if it walks horizontally or a | if it walks vertically, but of course it also overwrites as it goes so it's nowhere near an acceptable representation for the purposes of the answer, but I thought it was cool to show what you could do in 13 bytes.

that is what I guessed. It is quite cool indeed! Thanks for sharing this :D

Python 3, 105 \$\cdots\$ 89 86 bytes
Saved 3 bytes thanks to Surculose Sputum!!!
from random import*
def f(p,l):
 while any(p):p[randrange(l)]+=choice((-1,1));print(p)

Try it online!

Good job on this sub +1!

Easy -3 bytes if you take the number of dimensions as an extra input, which is allowed!

@SurculoseSputum Missed that - thanks! :-)

BATCH, 563 560 539 509 653 bytes
@ECHO OFF
Setlocal EnableDelayedExpansion
Set "#=Set "
!#!/P N=D
!#!"F=For /L "
!#!I= in (1,1,
!#!D=) Do (
!#!E=) ELSE (
!#!C=CALL :
!#!Y=2
%F%%%A%I%!N!%D%
!#!O%%A=0
!#!/P S%%A=Ax%%A
!#!H%%A=!S%%A!)
%F%%%A%I%50000%D%
!#!v=0
!C!R U N
!C!M S!U! H!U!
!#!]=@
%F%%%B%I%!N!%D%
!#!"]=!]!!S%%B!,"
IF %%B==!N! !#!]=!]:~,-1!
IF !O%%B!==!S%%B! !#!/A v+=1
IF !v!==!N! GOTO :E
)
ECHO(!]!
)
:E
ECHO(!]!
pause
:M
!C!R R Y
!C!R P Y
IF !R!==1 (IF !%1! LEQ 0 (IF !P!==1 (!#!/A %1+=1%E%!#!/A %1-=1)%E%!#!/A %1-=1)%E%IF !%1! GEQ !%2! (IF !P!==2 (!#!/A %1-=1%E%!#!/A %1+=1)%E%!#!/A %1+=1))
Exit /B
:R
!#!/A %1=!random! %%!%2! +1
Exit /B

Update
At the cost of alot of bytes, I corrected the issues with zero chance for movement along any axis under the previous conditions, and through the use of an additional random test in an Ugly, byte hungry conditional statement still biased movement (In a non zero manner compliant with the terms outlined).
also modified the output to match the specified form.
Example Output

numerical input for number of dimensions and each dimensions target position required. starting postion for each axis is set randomly to a maximum of target pos + 1 (reduces time to proccess). each step along each axis is randomly taken - or + 1, Steps along any axis cease to be taken after reaching the correct position for that axis

Constraint added to keep walker within the grid

this does not meet the requirements! At any position, it should be possible to go in any direction! If you stop walking in a direction when it reaches 0, this isn't true

post ammended to match the terms (I do hope I've got the non-zero terms right this time)

JavaScript (ES6),  63  62 bytes
f=a=>a.join``==0?[a]:[a,...f(a.map(x=>x+~-(3*Math.random())))]

Try it online!

Thanks for your submission! +1

Wolfram Language (Mathematica), 83 79 75 bytes
For[r=RandomInteger;i=#,!0==##&@@i,j=r@{1,Tr[1^i]};i[[j]]+=2r[]-1,Print@i]&

Try it online!
Omits the last result (which is the origin anyway).

Nice solution! +1 for your work

@J42161217 That doesn't work because of some finnicky evaluations inside Part (observe that there are duplicate lines in the output sometimes) Related: https://mathematica.stackexchange.com/a/107621/35945

Octave, 74 bytes
x=input('');do disp(x),x(randi(size(x)))+=2*randi([0 1])-1;until~x;disp(x)

Try it online!

Thanks for your work! +1 for this


text:
Creating words by structure
Context
As a conlanger, I am interested in creating a uniform, naturalistic language. One of the tricks is to create vocabulary according to certain structures of words. An example from English: In English, we have the word “tap” structured consonant-vowel-consonant. Usually, this means that there are many other words of this structure: “cat”, “dog”, “rock”, “fog”, “good”, etc.
Task
As input, you have:

an array C containing strings: consonants (C is the first letter in the word consonants). Identical consonants cannot be repeated on this list. For example, this list cannot contain ['b', 'b'].
an array V containing strings: vowels (V is the first letter of the word vowels).  Identical vowels cannot be repeated on this list.
string S, which contains something like this "CVCCV" (any combination of "C" and "V")

Your task is to replace “C” in the string with a randomly taken string from array C and replace “V” in the string with a randomly taken string from array V and return (or display) this string.
"randomly" is defined as all possibilities having an equal chance of being selected. This is a kind of simplification: in real languages as well as in conlangs, there are very frequent (for example 'r' in English) and not very frequent sounds but this is just a code-golf.
Rules
This is code-golf so the lowest byte count wins.
Examples
Input:
C = ['p', 'b', 't', 'd', 'k', 'g', 'm', 'n', 'w']
V = ['a', 'o', 'u', 'i', 'e', 'ä']
S = 'CVCCV'

Output:
pakto

Input:
C = ['p', 'b', 't', 'd', 'k', 'g', 'v', 's', 'r']
V = ['a', 'o', 'u', 'i', 'e', 'ä', 'ᵫ']
S = 'CVVCCVCCV'

Output:
koebrᵫvtä

05AB1E, 4 bytes
Takes input as S, [V,C]
Çè€Ω

Try it online!

Jelly,  5  4 bytes
-1 thanks to Neil!
OịX€

A dyadic Link accepting a list of characters, S, on the left and a list of two lists of characters, [C, V], on the right which yields a list of characters.
Try it online!
If we could take S as a list of 1s and 0s we'd have the three byte solution ịX€.
How?
OịX€ - Link: S, [C,V]
O    - ordinals (of S)          i.e. 'C':67 'V':86
 ị   - index into [C,V] (vectorises)      C      V   [Jelly indexing is 1-indexed and modular]
   € - for each:
  X  -   random choice

I like both solutions! The 5 and the 3 byte ones +1

What does Jelly do if an index is out of range? (Charcoal automatically reduces it modulo the range, so I don't need to extract the bit manually.)

@Neil you just saved a byte - thanks! I even noted in my code break-down that "Jelly indexing is 1-indexed and modular".

Python 3, 92 68 61 bytes
Takes input as S, C, V:
lambda s,*w:[random.choice(w[a>"u"])for a in s]
import random

You can try it online! How it works:
The *w is used so that the lists of consonants and vowels are packed in a list w.
When we do w[a > "u"] we are essentially checking if a (a character of s) is "v" or not. If it is, then a > "u" returns True, which indexes as 1 into w. If a is "c", then a > "u" returns False, which indexes as 0.
We use those indices to retrieve the correct list of letters from w and then choose randomly from that list, picking the list of choices.
Thanks @Arnauld for saving one byte and to @Jonathan Allan for citing this meta, saving me 7 bytes.

This is what I would've done in my C solution had it not been for that the lists of consonants and vowels are not of equal length.

I believe that you should be able to take s as a list of characters and return the same (see this meta) and as such can replace the "".join(...) with [...].

@JonathanAllan thanks for this reference! Shaved 7 bytes :)

APL+WIN, 35 34 bytes
One byte saved thanks to Adam
Prompts for consonants and vowels as continuous strings and the desired output as a comma separated string
c←⍞⋄v←⍞⋄C←',c[?⍴c]'⋄V←',v[?⍴v]'⋄⍎⎕

Try it online! Courtesy of Dyalog Classic

If you liked this golf question, please vote to reopen it.

If you don't like this golf challenge, please retain its closed state.

This is the first time I have been lobbied from both sides of a question closure. Personally I had no problem understanding the question and as I got two up votes I assume at least two people agreed with my interpretation and my answer

By using ⍞ instead of ⎕ you can specify that input shouldn't have quotes, and then use ⎕ instead of ⍎⎕ to save a byte: Try it online!

@Adám Thanks for the suggestion but whilst it works in Dyalog Classic I cannot get it to work in APL+WIN. If I run the code as you suggest it simply outputs the concatenated code string which needs the second ⍎ to execute.

@Graham Even if the C,V,… is input into a ⎕: prompt without quotes?

@Adám It does work!!! Not sure why not before. I simply deleted the quotes around the inputs on my screen and successively hit enter on those lines when required. Finally typing each input when required I get the expected result. Thanks again for the suggestion.

@Graham Does v c←⍞⍞⋄C←',c[?⍴c]'⋄V←',v[?⍴v]'⋄⍎⎕ work in APL+WIN?

@Adám. No it throws an error. It does work if v c are enclosed in parentheses. In which case moving back to ⎕ allows a nested vector of v and c to be entered but we do not save any bytes.

@Graham Ah right, Dyalog is (unfortunately) lenient with that. Good for golfing, though.

W f j, 4 bytes
Hmm, let's do a pure-ASCII port of that.
C[gr

Explanation
C    % Convert the string to its codepoints
 [   % Index into the other list
   r % For every indexed item:
  g  % "g"et a random item in this list

Flag:f % Flatten the output list
Flag:j % Join the flattened output list
```

@KevinCruijssen I absolutely can't understand the challenge, so feel free to post your answer so that I can get a better understanding of this. (I guess I'd keep it deleted because I don't know how to fix it.)

Ruby, 45 40 bytes
->s,*l{s.bytes.map{|x|l[x%2].sample}*''}

Try it online!

I didn't think that ruby could outgolf python. Great!

Ruby code is usually shorter than the equivalent python code.

Charcoal, 7 bytes
⭆η‽§θ℅ι

Try it online! Link is to verbose version of code. Takes the input in the form [V, C], S where each value can be either a string or an array of characters as desired. Explanation:
 η      `S`
⭆       Map over elements/characters
    θ   `[V, C]`
   §    Cyclically indexed by
     ℅  Ordinal of
      ι Current element/character
  ‽     Random element/character
        Implicitly print

C# (Visual C# Interactive Compiler), 66 bytes
(C,V,s)=>s.Select(x=>(x<68?C:V).OrderBy(l=>Guid.NewGuid()).Last())

Try it online!

Japt, 6 bytes
ËcgV ö

Takes input as S, [V,C]
Try it

@a'_' Ok.6 more to go...

@a'_' By the way, did you like this code-golf question?

@VictorVosMottorthanksMonica I loved it. But it was blatant that I can't re-open it, because I don't have enough reputation to do so.

Let us continue this discussion in chat.

@VictorVosMottorthanksMonica, liking a challenge is not a valid reason to VTR it. Address the issues that led to it being closed and, once done so to the community's satisfaction, it will be reopened.

@a'_', similarly, not liking a challenge is not grounds for closing it or leaving it closed. There have been many challenges here over the years I haven't personally liked, as there have been for everyone - if you don't like a challenge, just skip it and move on to the next one.

JavaScript (ES6),  65  64 bytes
(C,V,s)=>s.replace(/./g,x=>eval(x).sort(_=>Math.random()-.5)[0])

Try it online!
Or 55 bytes if we can use an array of characters as I/O.

The eval trick is really nice! Sadly enough I don't think I can use it in my answer to save some bytes :(

55 seems fine unless OP has explicitly said not since I==O and if it quacks like a duck, it is a duck (i.e. strings are lists of characters)

@a'_' I think I'm privileged enough to hammer this question, which I think would be inappropriate either way.

PHP, 68 bytes
function($C,$V,$s){for(;$r=$s[$i++];)echo$$r[rand(0,count($$r)-1)];}

Try it online!

C (gcc), 92 bytes
f(s,c,v,m,n)char*s,**c,**v;{for(srand(&s);*s;)printf("%s",*s++/86?v[rand()%n]:c[rand()%m]);}

Takes as input a string (s), an array of consonant strings (c), an array of vowel strings v, the length of c (m), and the length of v (n).
Could use a temporary variable for the result of rand but it wouldn't save me anything.
Try it online!


text:
Toggle Shift Key
Objective
Given an ASCII character, toggle its "shift-ness" on the standard US keyboard (ANSI-INCITS 154-1988 (R1999)), then output it.
Mapping
) ↔ 0
! ↔ 1
@ ↔ 2
# ↔ 3
$ ↔ 4
% ↔ 5
^ ↔ 6
& ↔ 7
* ↔ 8
( ↔ 9
" ↔ '
+ ↔ =
, ↔ <
- ↔ _
. ↔ >
/ ↔ ?
: ↔ ;
(Capital Latin letters) ↔ (Small Latin letters)
[ ↔ {
\ ↔ |
] ↔ }
` ↔ ~
(ASCII whitespaces and control characters are left intact)

Rule

Non-ASCII characters fall into don't care situation.

Examples
Given a character 0, output ).
Given a character C, output c.
Given a character  (space), output .
Given a character \t (horizontal tab), output \t.
Given a character \a (bell), output \a.

Is it ok if we do the UK keyboard? Just four differences that I can tell.

@ouflak I'm afraid not.

x86-16, Genuine IBM PC, 32 31 29 bytes
00000000: b4f0 8ec0 bfe5 e8b3 3ab1 74a0 8200 f2ae  ........:.t.....
00000010: 3acb 7f02 f7db 268a 41ff cd29 c3         :.....&.A..).

Build with xxd -r.
Unassembled listing:
B4 F0       MOV  AH, 0F0H               ; BIOS segment address (F000H)
8E C0       MOV  ES, AX                 ; set ES to BIOS segment for SCASB
BF E8E5     MOV  DI, E8E5H              ; set to LABEL K10
B3 3A       MOV  BL, 58                 ; size of table
B1 74       MOV  CL, 58*2               ; size of both tables
A0 0082     MOV  AL, BYTE PTR DS:[82H]  ; get input char from command line
F2/ AE      REPNZ SCASB                 ; search BIOS table for char
3A CB       CMP  CL, BL                 ; found in the lowercase table?
7F 02       JG   UPPER                  ; if so, convert with uppercase table by adding
F7 DB       NEG  BX                     ; otherwise subtract the offset
        UPPER:
26:8A 41 FF MOV  AL, ES:[BX+DI-1]       ; get char from table
CD 29       INT  29H                    ; DOS fast write to console
C3          RET                         ; return to DOS

Input/Output:

How does it work?
Well, the PC BIOS already contains all of the code and tables necessary for this since it actually handles the conversion of scan codes received from the keyboard to ASCII chars (in real/DOS mode at least).  There's no way (that I know of) to actually hook this on just any "PC-compatible" BIOS, however if you know the location of the table in ROM (on the IBM PC it starts at F000:E8E5), you can use that.
On Page A-25 of Appendix A the IBM PC Technical Reference (listing of the entire source code of the PC BIOS) is the disassembly of this table:

Unfortunately, this address will be different on any given PC-clone BIOS and of course, there's no guarantee that it would even be implemented in the same way by anyone else.  Thus, this submission is guaranteed to run only on a Genuine IBM PC.  Go Big Blue!

JavaScript (Node.js),  110 ... 97  96 bytes
c=>(s=")0@2^6&7*8(9\"'+=-_:;`~")[s.indexOf(c)^1]||(B=Buffer)([([n]=B(c),n%127>32)<<4+n/64^n])+''

Try it online!
How?
We use a lookup table for these pairs:
) ↔ 0
@ ↔ 2
^ ↔ 6
& ↔ 7
* ↔ 8
( ↔ 9
" ↔ '
+ ↔ =
- ↔ _
: ↔ ;
` ↔ ~

For all other characters, we use the following code:
(B = Buffer)([   // generate a buffer from a singleton array:
  (              //
    [n] = B(c),  //   n = ASCII code of the input character
    n % 127 > 32 //   1 if 32 < n < 127, or 0 otherwise
  )              //
  << 4 + n / 64  //   left-shifted by 4 if n < 64, or by 5 otherwise
  ^ n            //   XOR'ed with n
]) + ''          // end of Buffer(); coerce it to a string

which supports these 3 cases:

If \$32<n<64\$, we XOR the ASCII code with \$16\$, which is what we need for:
! ↔ 1
# ↔ 3
$ ↔ 4
% ↔ 5
, ↔ <
. ↔ >
/ ↔ ?

If \$64\le n<127\$, we XOR the ASCII code with \$32\$, which toggles the case of letters and also works for these pairs:
[ ↔ {
\ ↔ |
] ↔ }

If \$n\le32\$ or \$n=127\$, the character is left unchanged (ASCII code XOR'ed with \$0\$).

Retina 0.8.2, 34 bytes
T`-~A-]d';-?/.+,:"(*&^%$#@!)}-_`Ro

Try it online! Link includes test cases.
Explanation: The T command is Retina's transliteration operation. Among its special characters are:

`: Delimit the parts of the command
-: Introduce a range (this suppresses the following special characters so d-o just means defghijklmno)
_: Delete the matching character
d: 0-9
R: Reverse the next range
o: Take the source string as the range

The trick is therefore to create as many ranges as possible to reduce the length, plus avoiding having the - and _ characters where they would be interpreted as a special character and avoiding the ` at all by including it inside a range. Additionally arranging for the range to transliterate to its reversal allows that to be expressed very cheaply.

Bash + core utilities, 58 \$\cdots\$ 51 49 bytes
Added 47 50 bytes to fix a bug kindly pointed out by Giuseppe.
Saved 8 bytes thanks to Value Ink!!!
Saved 2 bytes thanks to Mitchell Spector!!!
a='"A-]`=<_>?)!@#$%^&*(;'
b=\'a-~+-:
tr $a$b $b$a

Try it online!

I like the idea behind this, but it doesn't seem to be coming out right.  For example, 'A' => 'b'.  Also, it's not actually bash -- it's "bash + core utilities", so I think the language listed should be changed accordingly.  (tr isn't a bash built-in.)

@MitchellSpector Sorry it's a bit of a hack, did this from my phone! T_T Will fix it when I get a chance.

From your phone? That's impressive in itself! I don't think I could do that.

@MitchellSpector Have termux which is very sweet! :-)

I haven't seen that app, but it must be nice :) .  @Noodle9

Do you really need the square brackets around each quote? The Wikipedia article on tr syntax doesn't seem to indicate the need for either unless you're using a special sequence like [:alnum:]. I think removing them won't affect the program, but I can't be sure until you fix the other issues that were brought up. Also, I feel like you don't need to escape the !

@ValueInk I made the whole string a regex for the [0-9], [A-Z] and [a-z] regex's.

Yes, but the tr page on Wikipedia says you don't need it. Might depend on the version of coreutils you have but the one on TIO works this way. Example with reduced charset

@ValueInk Sweet! Just got back from holiday after a long journey. Will sort this out properly on my much missed box tomorrow - thanks! :-)

@ValueInk Fixed! Nice one - using your no [] tip and it works, thanks! :-)

@MitchellSpector All fixed now.

@Giuseppe All fixed now.

Nice solution! -

I think you can shave off 2 bytes by removing the single quotes around '0-9'.

@MitchellSpector Yes indeed, nice one - thanks! :-)

By the way, I've just added an answer which is basically a port of this nice solution to pure bash (without using tr or other utilities).  It's shorter than my earlier pure bash solution, which uses a different approach.  (I tried to tag you in the answer, but apparently you can't do that.)

Apparently you can’t tag people in answers, only in comments, and even then it seems you can only tag people who commented earlier. (This is unless I’m missing something, of course!)

@MitchellSpector I see what you mean now, you can mention them but they don't get notified. Looks like a wrinkle in the software! If only the had access to people who ciuld fix this... T_T

Exactly. But I think it’s on purpose, to prevent spamming people who haven’t expressed an interest in the answer.

@MitchellSpector Always the bad ones who spoil things, makes sense.

APL (Dyalog Extended), 86 bytesSBCS
This solution has been out-golfed but is preserved due to being interesting for its sourcing of the data.
Anonymous prefix lambda. Requires 0-based indexing (⎕IO←0).
{⍵∊a←↑'[!-~]{2}'⎕S'&'↓⍉↑'\w\w...'⎕R(5⍴'')↓11 71↑30↓⎕FMT⌂notes.keyboards:a⌷⍨~@1⊃⍸⍵=a⋄⍵}

Try it online!
This works by extracting the character pairs from a built-in note about keyboards.
{…} "dfn"; argument character is ⍵:
 ⌂notes.keyboards the built-in string
 ⎕FMT ForMaT as a character matrix
 30↓ drop the first 30 lines
 11 71↑ take the first 11 lines' first 71 columns
 ↓ split into list of strings
 '\w\w...'⎕R(…) PCRE Replace word-character,word-character,any-symbol,any-symbol with:
  '' the empty string
  5⍴ reshaped to length 5, padding with spaces; i.e. 5 spaces
 ↑ mix list of strings into character matrix
 ⍉ transpose
 ↓ split matrix into list of strings
 '[!-~]{2}'⎕R'&' PCRE Search and return any pair of printable ASCII characters
 ↑ mix list of character pairs into two-column matrix
 a← store in a (for all)
 ⍵∊…: if the argument character is a member of that matrix:
  ⍵= Boolean matrix mask where they are equal
  ⍸ get indices where true
  ⊃ pick the first (row,column) pair
  ~@1 negate the number at position 1 (the column; i.e. 1→0 and 0→1)
  a⌷⍨ use that to index into the matrix of all pairs
 ⋄ else:
  ⍵ the argument character

Is taking the first 71 columns necessary?

Could '\w\w...'⎕R(5⍴'') be replaced by a reverse-each line (so that the Caps<>Lock mapping is never used)?

@JonathanAllan The 71 chops "Backspace" into  "Backs" and reversing would expose "Enter" instead.

Ah, I see, so you'd need to ignore all characters paired with spaces too.

Python 3, 99 95 bytes
Same strategy as @Arnauld's answer.
-4 bytes thanks to @mypetlion
lambda c,s=")0!1@2#3$4%5^6&7*8(9\"'+=,<-_.>/?:;[{\\|]}`~":[c.swapcase(),s[s.find(c)^1]][c in s]

Try it online!
Explanation

s=")0!1@2#3$4%5^6&7*8(9\"'+=,<-_.>/?:;[{\\|]}`~" contains all pairs of special toggles.
s[s.index(c)^1] gets the index of the other character from the same pair
If the character is a Latin or control character (c in s is False), c.swapcase() is returned. c.swapcase() toggles the case of a Latin character, but doesn't affect control character.

Change everything after the colon to [c.swapcase(),s[s.find(c)^1]][c in s] to save 4 bytes.

Clever use of boolean index!

Thanks @mypetlion for spotting the erroneous extra space at the end!

Jelly,  38  37 bytes
“Æz⁶ɦG!€u<ʂCP]ƭƝ’œ?ØṖḟØB¤ḊØD;ṙ21,ƊyŒs

A monadic Link accepting a list of characters which yields a list of characters.
Try it online!
How?
Forms a mapping for non alphabetic characters, applies the translate atom,  y,
and then swaps case.
“Æz⁶ɦG!€u<ʂCP]ƭƝ’œ?ØṖḟØB¤ḊØD;ṙ21,ƊyŒs - Link: list of characters, S
“Æz⁶ɦG!€u<ʂCP]ƭƝ’                     - base 250 number              =53994992086540427749431907521542401
                        ¤             - nilad followed by link(s) as a nilad:
                   ØṖ                 -   printable characters       = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
                      ØB              -   base-62 characters         =0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
                     ḟ                -   filter discard             = !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
                 œ?                   - lexicographical permutation  = '=<_>?;{|}~)!@#$%^&*("+,-./:[\]`
                         Ḋ            - dequeue                      ='=<_>?;{|}~)!@#$%^&*("+,-./:[\]`
                          ØD          - digit characters             =0123456789
                            ;         - concatenate                  =0123456789'=<_>?;{|}~)!@#$%^&*("+,-./:[\]`
                                 Ɗ    - last three links as a monad:
                              21      -   twenty-one
                             ṙ        -   rotate left                =)!@#$%^&*("+,-./:[\]`0123456789'=<_>?;{|}~
                                ,     -   pair                       =)!@#$%^&*("+,-./:[\]`0123456789'=<_>?;{|}~ and 0123456789'=<_>?;{|}~)!@#$%^&*("+,-./:[\]`
                                  y   - translate (S)
                                   Œs - swap case

Pure Bash, 170 165 bytes
a=`echo {A..Z}`')!@#$%^&*("+,-./:[\]`'
b=`echo {a..z}`0123456789"'=<_>?;{|}~"
c=$a$b
d=$b$a
for((;n<164;n++)){ [ "$1" = "${c:n:1}" ]&&echo ${d:n:1}&&exit;}
echo "$1"

Try it online!
I decided to implement a solution inspired by @Noodle9's very nice answer, but using pure bash without any utilities (like tr).
Note that you need to run this in an empty directory; this can be fixed at the cost of 2 bytes by using quotes for "{d:n:1}".  (This issue only arises with a non-empty current directory when the input is 8, so the output is supposed to be *.)
On the other hand, you can gain 2 bytes if you don't require output for the input \n: just eliminate the quotes in the final echo.

You save 3 bytes using echo {a..z} {0..9} like this.

@Noodle9 Thanks for the suggestion.  I had tried that before posting, but it was a little bit longer that way.   (The problem is that {0..9} expands to 0 1 2 3 4 5 6 7 8 9, so I needed to add spaces into the other string to make the two strings still match up correctly.)  But maybe you figured out some clever way of dealing with that?  (Your link looks like it's just a link to your original answer, not to whatever you intended to link to.)

Sorry I sent the wrong link. I didn't perform any magic, simply substituted {0-9} for 0123456789 and it worked for your test. So incorrect then. :-(

@Noodle9  That's a shame -- I was hoping you had come up with some cool trick for getting past that issue!  (If it worked for you on some test, you must have gotten lucky with the particular input you happened to try.)

@Noodle9 Unfortunately, that doesn't work :( .  If you look at the test in your link, you'll see that, for instance, b gets mapped to b, instead of to B.  I investigated it a bit when I was working on this answer, and it turns out that the {A..Z} construct isn't expanded on the right side of an assignment statement.

Yes,  just noticed letters aren't working.

166 3rd time lucky! :D

@Noodle9  That was actually what I mentioned in the last paragraph of the answer -- "On the other hand, you can gain 2 bytes if you don't require output for the input \n: just eliminate the quotes in the final echo."  You can do this, but then it doesn't have the right output for input \n.  Normally the output is the intended output character followed by a \n, but if you do this, then the output for \n is just \n, instead of \n\n.  I felt that was at best borderline acceptable, so I didn't do it.

@Noodle9  But thanks for looking at it!

@Noodle9  I just noticed that you also changed "$1" to $1 in the for loop.  But unfortunately that won't work if the input is a space, for instance.

Ah, this reminds me of writing scripts that'll process every weird filename possible! :-)

I know -- avoiding weird characters is a real nuisance with bash.  But that's really only because it's so flexible, so I can't complain.

True, bash is amazingly powerful working on the command line where everything is a stream of characters that process streams of characters. Love it! :-)

I agree :).  @Noodle9

05AB1E, 53 36 35 bytes
.šžQžiмDœ•1ĀêŽƵÆ{çIΣeÿí‚Ð"pkālrÙ•è‡

-1 byte implicitly thanks to @Grimmy due to his comment.
Try it online or verify all printable ASCII characters. NOTE: The TIO versions use the S•...•.I (builtin for the n'th permutation of a list) instead of œ•...•è (push all permutations of the string (extremely slow bottleneck for a string this large), and index into it).
Explanation:
.š        # Switch-case of the (implicit) input-character (if it's a letter)
  žQ      # Push all printable ASCII characters:
          #   !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
    žiм   # Remove all letters [A-Za-z]:
          #   !"#$%&'()*+,-./0123456789:;<=>?@[\]^_`{|}~
  D       # Duplicate it
   œ      # Push a list of all permutations of this string
    •1ĀêŽƵÆ{çIΣeÿí‚Ð"pkālrÙ•
         "# Push compressed integer 540470878544692028277787799913384202055137480696656
     è    # Index it into the string-list of permutations:
          #   1'3457"908=<_>?)!@#$%^&*(;:,+./2{|}6-~[\]`
  ‡       # Transliterate the characters at the same indices
          # (after which the result is output implicitly)

See this 05AB1E tip of mine (section How to compress large integers?) to understand why •1ĀêŽƵÆ{çIΣeÿí‚Ð"pkālrÙ• is 540470878544692028277787799913384202055137480696656.
This number(+1) is generated by the Jelly builtin Œ¿, which gets the 1-based index of the permutation.

Oooh we have an nth-permutation built-in, why did i never notice that! Though I guess it doesn't actually save any bytes over œ + è...

@Grimmy Hmm, seeing your comment actually made me realize that œ...è is a byte shorter here, since .I doesn't work on strings (only on lists). So I can drop the S.

Perl 5 -p, 92 91 bytes
-1 byte thanks to @ValueInk
s/[]a-z{}|\\[]/$&^$"/gei;y/0-9)!@#$%^&*(`~\-=_+';":,.\/<>?/)!@#$%^&*(0-9~`_+\-=":';<>?,.\//

Try it online!

/[]a-z{}|\\[]/ lets you cut out the extra backslash while still matching ] in your first regex. Also, why did you put those particular characters into its own s/// operation instead of wrapping them into the y///? I don't know much about Perl but I did use the Ruby y/// analogue (tr) in my own solution without needing to do a regex sub at all. Maybe that could help you out with golfing your solution.

You don't need the substitution, but it works out to be a couple of bytes shorter than accounting for those characters in the translation.

Hmmm. Could you have 2 strings (one with upper only and one with lower only) and pass them into tr in different orders similar to what I did in my Ruby solution? I'm not sure how costly it is to declare variables in Perl though

No.  tr/// is a quote-like operator in Perl.  It does not do variable interpolation.  You'd have to put it inside an eval, costing even more bytes.

I figured it out; eval might cost bytes, but not as much as it saves. 77 bytes, probably can be golfed further depending on how the strings are set up

Julia, 87 bytes
x->Char[0:32;b"1'3457\"908=<_>?)!@#$%^&*(;:,+./2";97:125;b"6-~";65:93;96;127][Int(x)+1]

Try it online!

Pure Bash, 217 bytes
P=printf\
a=`$P%x "'$1"`
case $a in 3[ab])x=1;;2[27])x=5;;2[68]|3[79])x=17;;2a|38)x=18;;2b|3d)x=22;;29|30)x=25;;36|5e)x=104;;2d|32|40|5f)x=114;;20|7f)x=0;;60|7e)x=30;;[23]?)x=16;;[4-7]?)x=32
esac
$P\\`$P%o $[0x$a^x]`

Try it online!
Just bash -- no Unix utilities.
Input character is passed as an argument, and the output is on stdout.
_____________________________________________________________
Test runs:
$ cat shifttoggle
P=printf\
a=`$P%x "'$1"`
case $a in 3[ab])x=1;;2[27])x=5;;2[68]|3[79])x=17;;2a|38)x=18;;2b|3d)x=22;;29|30)x=25;;36|5e)x=104;;2d|32|40|5f)x=114;;20|7f)x=0;;60|7e)x=30;;[23]?)x=16;;[4-7]?)x=32
esac
$P\\`$P%o $[0x$a^x]`

$cat shifttoggleTest
#!/bin/bash

count=1

for s in ')!@#$%^&*("+,-./:' "0123456789'=<_>?;" ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz '[\]`' '{|}~' $' \a\n\r\t\x7F\x80\x88\x8F'
  do
    echo "TEST #$count"

    for ((n=0;n<${#s};n++))
      do
        c="${s:$n:1}"
        d=`./shifttoggle "$c"`

    # Backticks remove any trailing newline, so restore that here for the case where c is \n (you can check that shifttoggle really prints \n in that case).
    if test -z "$d"
          then
            d=$'\n'
        fi

    if test "$count" -eq 7
          then
            printf "  ASCII %d => ASCII %d\n" "'$c" "'$d"
      else
            echo "  $c => $d"
        fi

      done

      (( count++ ))
      echo ''
  done

$ ./shifttoggleTest
TEST #1
  ) => 0
  ! => 1
  @ => 2
  # => 3
  $ => 4
  % => 5
  ^ => 6
  & => 7
  * => 8
  ( => 9
  " => '
  + => =
  , => <
  - => _
  . => >
  / => ?
  : => ;

TEST #2
  0 => )
  1 => !
  2 => @
  3 => #
  4 => $
  5 => %
  6 => ^
  7 => &
  8 => *
  9 => (
  ' => "
  = => +
  < => ,
  _ => -
  > => .
  ? => /
  ; => :

TEST #3
  A => a
  B => b
  C => c
  D => d
  E => e
  F => f
  G => g
  H => h
  I => i
  J => j
  K => k
  L => l
  M => m
  N => n
  O => o
  P => p
  Q => q
  R => r
  S => s
  T => t
  U => u
  V => v
  W => w
  X => x
  Y => y
  Z => z

TEST #4
  a => A
  b => B
  c => C
  d => D
  e => E
  f => F
  g => G
  h => H
  i => I
  j => J
  k => K
  l => L
  m => M
  n => N
  o => O
  p => P
  q => Q
  r => R
  s => S
  t => T
  u => U
  v => V
  w => W
  x => X
  y => Y
  z => Z

TEST #5
  [ => {
  \ => |
  ] => }
  ` => ~

TEST #6
  { => [
  | => \
  } => ]
  ~ => `

TEST #7
  ASCII 32 => ASCII 32
  ASCII 7 => ASCII 7
  ASCII 10 => ASCII 10
  ASCII 13 => ASCII 13
  ASCII 9 => ASCII 9
  ASCII 127 => ASCII 127
  ASCII 128 => ASCII 128
  ASCII 136 => ASCII 136
  ASCII 143 => ASCII 143

C (gcc), 100 bytes
char*strchrnul(),*s=")0@2^6&7*8(9\"'+=-_:;`~\0";f(c){c=s[strchrnul(s,c)-s^1]?:(c%127>32)<<4+c/64^c;}

Similar to the Javascript strategy. I'd like to get rid of the extra parentheses but this is pretty good.
Try it online!

Ruby -p, 66 bytes
Builds the "lowercase" and "uppercase" strings so that everything lines up, and connects them together to be passed into the tr function so it can do the proper conversions.
l="\\-a-z0-9=[-];',./`"
u='_A-Z)!@#$%^&*(+{|}:"<>?~'
$_.tr!u+l,l+u

Try it online!

APL (Dyalog Extended), 60 bytesSBCS
Anonymous tacit prefix function.
-(,⊃⍨⍳-¯1*⍳)⍨('"''+=,<-_.>/?:;[{\|]}`~',∊')!@#$%^&*(',¨⎕D),-

Try it online!
- swap case
(…), prepend the following:
 ⎕D the digits
 ')!@#$%^&*(',¨ prepend each of these characters to the corresponding digit
 ∊ ϵnlist (flatten)
 '"''+=,<-_.>/?:;[{\|]}`~', prepend these characters ('' is an escaped single quote)
-(…)⍨ apply the following function with that as left argument and the case-swapped original argument as right argument:
 ⍳ ɩndex of the case-swapped argument in the substitution string
 ¯1* negative one raised to that power
 ⍳- subtract that from the ɩndex of the case-swapped argument in the substitution string
 ,⊃⍨ use that to pick an element from the case-swapped argument appended to the substitution string

PowerShell, 111 bytes
$k=')!@#$%^&*("+,-./:[\]`'+'A'..'Z'+"0123456789'=<_>?;{|}~"+'a'..'z'
"$k$k$args"[($p=$k|% i*f @args)+72*!!++$p]

Try it online!
i*f is shortcut for indexOf.
Explain:

The shift series contains 72 chars )!@#..A B C.. Y Z.
The shift-ness series contains 72 chars also
$k contains concatenated shift and shift-ness series
if $args does not found in $k, then indexOf returns -1 and script returns the last char from string $k+$k+$args. It is $args.
if $args found in $k, then the script return shifted char.

PowerShell, 189 bytes
param($x)if(($s=")0@2^6&7*8(9""'+=-_:;``~").contains($x)){$s[$s.indexof($x)-bxor1]}else{
$n=[byte][char]$x;if($n-in32..64){[char]($n-bxor16)}elseif($n-in65..127){[char]($n-bxor32)}else{$x}}

Try it online!


text:
Broken Keyboard
You're writing your favorite language and you want to display the following string: abcdefghijklmnopqrstuvwxyz to your happy customer. Unfortunately, your keyboard is broken and you can now only type symbols !+-*/[]().
You must submit a code that evaluates to be the string abcdefghijklmnopqrstuvwxyz or print the string abcdefghijklmnopqrstuvwxyz and contain only symbols !+-*/[](). For example, +![]+[] in javascript evaluates to be the string 0.
The shortest valid submission in 7 days wins. If there're multiple ones, I'll accept the one with the earliest last modification time. Good luck!

This looks similar to a previous code golf JSFuck challenge, which only allowed []()!+. Do you think the inclusion of *, -, and / makes this sufficiently different?

@xnor I didn't know that challenge, but I think it's probably sufficient.

I have allowed all languages.

You have not allowed all languages. C can't have functions or even print anything without at least the underscore, numbers, and semicolon (plus whitespace). Can you allow everything except the alphabetic characters instead?

Already some answers here, so probably I'll not change the restriction. I indeed allow all languages, it's up to you.

@S.S.Anne - [tag:restricted-source] often excludes some languages by virtue of the source restriction. (C is also by no means the only language "allowed" but impossible in which to actually compete in this case.)

W c, 149 bytes
DISCLAIMER: This answer has nothing to do with the water closet.
The c flag confuses the interpeter with strings and character arrays, therefore outputting the lowercase alphabet. Note that I already had this idea before this challenge.
How to enter an empty input: just type "" as the input, W will not recognize this operand.
]+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))

Explanation
After compilation, it looks like this:
] % Roll the whole stack into a list (surrounding the input).
  % The stack: []

+ % W is short of operands, so an implicit argument is added.
  % The input is 0 by default if it's empty.
  % The stack: [0]

) % Increment all (automatically vectorizes)
  % The stack: [1]

+ % Join with the implicit input
  % The stack: [0,1]
)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+

% After all that boring stuff, the stack becomes:

% [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]

97+

% For clarity the 97 )'s are converted to addition. Stack:

% [97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122]

Flag:C % Convert the numeric array to a string

% Output: abcdefghijklmnopqrstuvwxyz
```

Aww, I was totally thinking I could use this as a bathroom! Doesn't matter! :P

Lenguage, \$1.5161 \times 10^{27}\$ characters
Everyone's favourite language when short of available characters!
A program consisting of any 1516111794593168227366643743 characters will print abcdefghijklmnopqrstuvwxyz then exit.
This is because that length in binary, left padded to a multiple of 3 bits with zeros is:
001 001 110 011 000 011 001 001 010 010 001 001 001 001 001 111
011 001 001 001 001 001 011 110 001 001 010 100 000 011 111

Which translated from Binaryfuck to Brainfuck is this  50 49 41  31 character program:
--[<+<-->>-----]<-----<[-->.+<]

Which we can easily try online!
How?
Brainfuck starts with an infinite tape of zeros, which may be incremented or decremented (\$0\$ decrements to \$255\$ and \$255\$ increments to \$0\$).
[...] or ] are ignored if the value under the head is \$0\$ otherwise ] loops back to its matching [
> and < move the head right and left respectively.
. prints the value under the head as a character.
--[<+<-->>-----]<-----<[-->.+<]  | print the alphabet  - tape = ". . n A x . ."
--                               | x -= 2  -> x = 254
  [            ]                 | while x != 0:
   <+                            |   move to A; A += 1
     <--                         |   move to n; n -= 2
        >>-----                  |   move to x; x -= 5
                                 |     -> 254//5 + 1 + 255//5 = 102 loops
                                 |        leaving n = 52, A = 102, x = 0
                <-----           | move to A; A -= 5
                      <          | move to n
                       [      ]  | while n != 0:
                        --       |   n -= 2
                          >.     |   move to A; print character(A)
                            +<   |   A += 1; move to n
                                 |     -> 52//2 = 26 loops, printing 'abc...xyz'

It might just be quicker to order a new keyboard though.

This makes me think that this challenge would have been better off being a code-bowling challenge rather than a code-golfing challenge.

...I'm trying to golf it down :)

Brain-Flak, 396 bytes
((((((((((((((((((((((((((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())[()])[()])[()])[()])[()])[()])[()])[()])[()])[()])[()])[()])[()])[()])[()])[()])[()])[()])[()])[()])[()])[()])[()])[()])[()])

Try it online!
Explanation
This answer is pretty simple.  We push z by doing a bunch of ()s
( () × 122 )

Then we use that as a starting place to count down each letter subtracting one each time.
( ... [()])

Where the ... is the code that pushed all the letters prior.
The unfortunate thing is that the structure of the goal string actually makes it a lot harder to do anything fancy.  [] is basically useless since by the time we have anything on the stack we just want to count down.  And as if that weren't enough all of the fun operations {...}, {} and <> are unusable.
This answer is likely optimal for brain-flak (without using -r).
Brain-Flak -r, 296 bytes
((((((((((((((((((((((((((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())())())())())())())())())())())())())())())())())())())())())())())())())())

Try it online!
Explanation
This works like the last one except we start at a and count up.  This is cheaper since a has a smaller code point and adding one is cheaper than subtracting one.  It saves exactly 100 bytes because there are 26 letters in the alphabet, going down to 'a' from 'z' saves 2 bytes per letter down which is 50 and changing minus one to plus one saves 2 bytes per letter, which is another 50.
The one issue is that this method does put things in the reverse order so we need -r to correct it, which is a flag that just reverses the order that things are output.

Javascript,  19793 9031 3318 chars
(![]+[])[+!![]]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]]+([]+[][(![]+[])[+[]]+(![]+[])[!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]]+([][[]]+[])[!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[+[]]+(+(!![]+!![]+!![]+[!![]+!![]+!![]+!![]]+(!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(!![]+!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![])+(+!![])+(+!![])+(+[])+(!![]+!![])+(!![]+!![]+!![]+!![]+!![]+!![])+(+!![])+(+!![])+(!![]+!![]+!![])))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+([]+[])[([]+[][(![]+[])[+[]]+(![]+[])[!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+(![]+[])[!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+(!![]+[])[+!![]]][([][[]]+[])[+!![]]+(![]+[])[+!![]]+([]+(+[])[([]+[][(![]+[])[+[]]+(![]+[])[!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+(![]+[])[!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+(!![]+[])[+!![]]])[+!![]+[+!![]]]+(!![]+[])[!![]+!![]+!![]]]](!![]+!![]+[!![]+!![]+!![]+!![]+!![]+!![]+!![]])+(!![]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(+(!![]+!![]+!![]+!![]+!![]+[!![]+!![]+!![]]+(!![]+!![]+!![]+!![]+!![]+!![])+(+[])+(!![]+!![]+!![]+!![]+!![])+(+!![])+(+!![])+(!![]+!![]+!![]+!![]+!![])))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+([]+[])[([]+[][(![]+[])[+[]]+(![]+[])[!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+(![]+[])[!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+(!![]+[])[+!![]]][([][[]]+[])[+!![]]+(![]+[])[+!![]]+([]+(+[])[([]+[][(![]+[])[+[]]+(![]+[])[!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+(![]+[])[!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]])[+!![]+[+[]]]+(!![]+[])[+!![]]])[+!![]+[+!![]]]+(!![]+[])[!![]+!![]+!![]]]](!![]+!![]+!![]+[!![]+!![]+!![]+!![]+!![]+!![]])

See, this is what happens when people can't be bothered to write javascript by hand. They use generators. Still, that was an interesting challenge!
A better generator dropped over 10k 16k chars. Wow.

If you switch to new browsers only on https://jscrew.it/ you can even drop 6K more. Not working on TIO tho.


text:
Bracket Checker
Given a string of brackets tell the user whether or not the brackets are well matched or not. Brackets include []{}(). For example:
() <---- Well Matched
([{}][]) <---- Well Matched

({)} <---- Not Well Matched
({]) <----- Not Well Matched

This is a code-golf challenge so as always the shortest solution wins.

Welcome to the site! Nice question, unfortunately we already have it.


text:
Visualize a Recursive Acronym
Background
Famously, the acronym GNU stands for GNU's Not Unix. 1
It's recursive because, after expanding it once, it still contains the acronym GNU, and so must be exanded again:
(GNU's Not Unix)'s Not Unix

And so on, ad infinitum.  Visualizing this, we get a kind of Droste effect:
┌────────────────────────────────────────────┬───────────┐
│┌──────────────────────────────┬───────────┐│'s Not Unix│
││┌────────────────┬───────────┐│'s Not Unix││           │
│││┌──────────────┐│'s Not Unix││           ││           │
││││GNU's Not Unix││           ││           ││           │
│││└──────────────┘│           ││           ││           │
││└────────────────┴───────────┘│           ││           │
│└──────────────────────────────┴───────────┘│           │
└────────────────────────────────────────────┴───────────┘

Recursive acronyms need not recurse on the first word, or only once.  For example:

YOPY: Your Own Personal YOPY
PIPER: PIPER Is PIPER Expanded Recursively

Visualized:

Challenge
Input
You will be given two inputs:

A string whose space-delimited words form a recursive acronym.  That is, if you form a string from the first letter of each word, that string is guaranteed to be either:

One of the words of the input string (it may occur more than once).
A prefix of one or more of those words (e.g. GNU is a prefix of GNU's)
The casing will match exactly

A non-negative integer -- the number of times to recursively expand.  Given 0, you'll return the input unaltered (or "framed" once, in its entirety).  Given 1, you'll expand once.  Etc.

Output
The output is the input string with all instances of the acronym visually expanded, recursively, the specified number of times.
You must use some visual effect to "frame" the nesting -- at minimum, distinct start and end delimiters like parentheses.  Ascii boxing of some sort, as in the examples above, is also fine.  As would be outputting an actual image that showed the nesting.
I'm flexible as long as the nesting is in fact visualized.
For clarity, parenthesized output would like this:
(((GNU's Not Unix)'s Not Unix)'s Not Unix)'s Not Unix

You are guaranteed that parentheses will never be part of acronym.  Other than alphanumeric characters, the acronym will only contain apostrophes, commas, quotes, question marks and exclamation points, and those will only occur as valid punctuation (e.g., a question mark will not appear at the beginning of a word).
This is code golf, fewest bytes wins, no loopholes.
Test Cases
This assumes you're using a parentheses visualization.
Format for test cases:

Input string (the acronym)
Input integer (recursion)
Expected Output

GNU's Not Unix
0
GNU's Not Unix

GNU's Not Unix
2
((GNU's Not Unix)'s Not Unix)'s Not Unix

YOPY Own Personal YOPY
1
(YOPY Own Personal YOPY) Own Personal (YOPY Own Personal YOPY)

YOPY Own Personal YOPY
2
((YOPY Own Personal YOPY) Own Personal (YOPY Own Personal YOPY)) Own Personal ((YOPY Own Personal YOPY) Own Personal (YOPY Own Personal YOPY))

YourYOPY Own Personal YOPY
2
YourYOPY Own Personal (YourYOPY Own Personal (YourYOPY Own Personal YOPY))

looks like a duplicate of this challenge :)

quotes, question marks and exclamation points. Is ?uestion Mark I For ?MIF? valid input?

@Adám That wouldn't be allowed.  I added a bit more clarification.  It probably would have been simpler to disallow punctuation altogether but I don't see how I can post this challenge without allowing the GNU one, so...

Hmm.. I was hoping your challenge was going to about producing the sort of picture you have under "Visualizing this, we get a kind of Droste effect:".

Next level: visualize mutually recursive acronyms. Eg. “Hurd” → “Hird of Unix-Replacing Daemons” / “Hird” → “Hurd of Interfaces Representing Depth”.

Would ( ( GNU's Not Unix )'s Not Unix )'s Not Unix be an acceptable output? (note the extra spaces.)

@Grimmy, Yes, it would.

@Anush That's absolutely acceptable, even encouraged.  Just not required.

I don't see why we handle YourYOPY Own Personal YOPY as if the YOPY in YourYOPY is not the acronym - the caps seem to imply it should be :/

@JonathanAllan It's a reasonable objection.  The reasoning is that you'd rarely realistically have an acronym embedded midway like that, but you do have things like GNU's, so I made the prefix rule.  Then Adam suggested that test case.   Though quoted acronyms might be an exception to that.  In retrospect, it might have been better to just always expand and avoid special cases altogether.  But there's too many answers to make the change now.

...well it certainly makes it more challenging!

...and to be clear what is the desired output for ("ARAS Recurse ARA", 1) - is it "ARAS Recurse (ARAS Recurse ARA)" or "(ARAS Recurse ARA)S Recurse (ARAS Recurse ARA)"?  -- i.e. is punctuation special or prefixing?

Both get expanded according to the current rules, which seems like more evidence of their deficiency and the complexity of writing ones we really “want“.  Cest la vie.

Stax, 11 bytes
û╟;±å↕êg╥σç

Run and debug it
Regex is pretty nice.
Explanation
D.\bxjMh+x:{R X → input
D             do the following n times, with the first input on stack
 .\b          push "\b" (word boundary)
    xj        split X on spaces
      M       transpose
       h      take first row to get abbreviation
        +     add that to the boundary
         x:{  push X, embedded in braces
            R replace matches of the created regex with "(X)"

APL (Dyalog Extended), 33 32 bytes
-1 byte thanks to Bubbler.
Anonymous infix lambda. Takes count as left argument and string as right argument.
{('\b',⊃¨⍵⊆⍨≠⍵)⎕R(1⌽')(',⍵)⍣⍺⊢⍵}

Try it online!
{…} "dfn"; number is ⍺ and text is ⍵:
 ⊢⍵ on the text:
 ⍣⍺ repeat given number of times
 (…)⎕R(…) PCRE Replace:
  ')(',⍵ the text prefixed by ")("
  1⌽ cyclically rotated one step left (puts ")" at end)
  … with:
  ≠⍵ The mask of non-spaces in the text
  ⍵⊆⍨ characters runs in the text corresponding to runs of 1s in that
  ⊃¨ first character of each
 '\b', prepend PCRE for word boundary

I like that rotation trick for the parens

Unfolding (≠⊆⊢)⍵ into ⍵⊆⍨≠⍵ saves a byte. Actually I was about to post the same thing as a full program, which has the same byte count.

JavaScript (ES9),  88 85  82 bytes
Takes input as (string)(n).
s=>g=n=>n?s.replace(eval(`/\\b${s.match(/(?<=^| )./g).join``}/g`),`(${g(n-1)})`):s

Try it online!
Commented
s =>                       // s = string
  g = n =>                 // g is a recursive function taking the counter n
    n ?                    // if n is not equal to 0:
      s.replace(           //   replace in s:
        eval(              //     each word matching:
          `/\\b${          //       a word boundary followed by
            s.match(       //       the acronym which consists of
              /(?<=^| )./g //         the letters that are preceded by
                           //         either a space or nothing at all
            ).join``       //       joined together
          }/g`             //
        ),                 //     with:
        `(${               //     the result of
          g(n - 1)         //       a recursive call
        })`                //     surrounded with parentheses
      )                    //   end of replace()
    :                      // else:
      s                    //   end of recursion: just return s

What level of JavaScript is this???

05AB1E, 27 25 22 bytes
ðìÐ#€нJðìs" (ÿ )"Iи.:¦

Try it online!
To make sure we only match the acronym at the beginning of a word, we match an extra leading space. This results in extra spaces in the output, which is allowed.
ðì                      # prepend a space to the input
  Ð                     # triplicate
   #€нJ                 # acronymize (split on spaces, head of each, join)
       ðì               # prepend a space to the acronym
         s              # swap
          " (ÿ )"       # surround with parentheses
                 Iи     # repeat the following second-input times:
                   .:   #  replace the acronym with the parenthesized string
                     ¦  # remove the leading space

Husk, 20 bytes
!→⁰Ṡ¡§¤σΘom←w`J"()"Θ

Try it online! Takes the number followed by the string. Outputs with parentheses, prefixing each expansion with a space.
Explanation
!→⁰Ṡ¡§¤σΘom←w`J"()"Θ  (Let X and Y denote the arguments.)
                   Θ  Take Y prefixed with a space; denote this Y'.
!→⁰                   Take element X + 1 of
   Ṡ¡                  the infinite list created by iterating this function on Y':
       σ                Take the argument and substitute
          m←              the string containing the first character of
   Ṡ §      w              each space-separated word of Y',
      ¤ Θ                prefixed with a space, with
   Ṡ §       `J           the characters of Y' placed between
               "()"        '(' and ')',
      ¤ Θ                prefixed with a space.

Perl 6, 48 bytes
{($^s,{S:g/$([~] $s~~m:g/<<./)/($s)/}...*)[$^x]}

Try it online!
Explanation
{                                              }  # Anonymous block
 (   ,                               ...*)  # Construct infinite sequence
  $^s                                       # starting with input string.
      {                             }  # Compute next item by
       S:g/                   /    /   # globally replacing
           $(                )         # interpolated
                 $s~~m:g/<<./          # first letters of each word
             [~]                       # joined (the acronym)
                               ($s)    # with input string in parens
                                          [$^x]  # Take nth item

Perl 5 -apl, 49 43 bytes
/./,$p.=$&for@F;for$a(1..<>){s/\b$p/(@F)/g}

Try it online!

Python 3, 104 96 bytes
-7 bytes thanks to @DeathIncarnate, and another -1 byte thanks to @wastl
import re
f=lambda s,n:n and re.sub('\\b'+''.join(c[0]for c in s.split()),f'({s})',f(s,n-1))or s

Try it online!
Explanation:
re.sub(
  '\\b'+''.join(c[0]for c in s.split()), # match all acronyms that starts on a word boundary
  '('+s+')',                             # replace with the original string in parenthesis
  f(s,n-1)                               # on the result of the (n-1)th recursion
)

This is the acronym expanded n times.
return n and recursive_case or base_case

This returns base_case if n is 0, and recursive_case otherwise. This works because in Python, 0 is Falsy and non-empty string is Truthy.

If n is 0, n and recursive_case short circuits to False, then False or base_case is evaluated which returns base_case.
If n is not 0, n and recursive_case evaluates to recursive_case which is Truthy, so recursive_case or base_case is short-circuited to recursive_case.

Obvious saving is to make this a lambda 97 bytes Try it online!

And using f-strings, there's another byte to be saved: Try it online!

My understanding of the rules is that 2 bytes can be saved by swapping the lines and moving the f= to the header. Is that correct?

@Seb Not if it's a recursive function, and in a language that doesn't support anonymous, recursive function calls. For example, Python.

@mypetlion Makes sense. Thanks for explaining!

Retina, 48 bytes
~(`$
 ¶($%`)
(.).*? (?=.*¶)
$1
^(.+)¶
1A`¶$1+`\b

Try it online! Takes the expansion count and acronym string on separate lines. Explanation:
~(`

After performing the script, interpret the result as a new script to be evaluated on the original input.
$
 ¶($%`)

Append a space to the string, and append a copy of the string wrapped in ()s on a new line.
(.).*? (?=.*¶)
$1

Turn the string into the acronym.
^(.+)¶
1A`¶$1+`\b

Replace the count with a Retina repeat instruction, and also prefix an instruction to delete the count from the original input.
For example, the result of evaluating the inner script on the input 2 GNU's Not Unix is
1A`
2+`\bGNU
(GNU's Not Unix)

This deletes the count from the original input, and then performs the acronym expansion twice.

sed 4.2.2, 180 bytes
h
s/(.)[^ ]* */\1/g
G
s/$/\n/
G
h
N
s/.*\n//
tx
:l
s/^(.*)\n(.*)\b\1(.*)\n(.*)\n(.*)/\1\n\2\n(\5)\3\4\n\5/
tl
s/\n(.*)\n(.*)\n/\n\1\2\n\n/
x
tx
:x
s/.//
x
tl
s/.*\n(.*)\n.*\n.*/\1/

Try it online!
Well, finding one part of input in another part of input is not that simple in sed. Input is on two lines: first line is the acronym string; second line is number of expansions in unary.

You should be able to include \ns in the capturing groups of your two longest substitutions to save some bytes in the respective replacements

You can simplify the last substitution using the P command, and shave more bytes by using the -n flag. Also this is sed 4.2.2, so you can use empty labels. All together, you should save 22 bytes

Python 2, 93 bytes
f=lambda s,n:n and re.sub('\\b'+''.join(zip(*s.split())[0]),'('+s+')',f(s,n-1))or s
import re

Try it online!
Similar to a few other answers.
If simple substitutions were allowed, I could do...
Python 2, 78 bytes
f=lambda s,n:n and f(s,n-1).replace(''.join(zip(*s.split())[0]),'('+s+')')or s

Try it online!
Except I didn't see the YourYOPY example when I put this together...

PowerShell, 106 bytes
function f($a,$n){$s="\b"+(($a.split(" ")|%{$_[0]})-join'')+"\b"
$o=$a;1..$n|%{$a=$a-replace$s,"($o)"};$a}

Try it online!

PowerShell, 84 71 bytes
Inspired by Wasif
param($n,$a)$o=$a
1..$n*!!$n|%{$a=$a-creplace'\b[A-Z]{2,}\b',"($o)"}
$a

Try it online!

Python 3, 123 106 118 bytes
Rolled back to my initial post.
Chas Brown kindly pointed out I was going down a rabbit hole.
Added 17 bytes to fix word boundary bug.
import re
def f(a,n):
 o=a
 for i in[1]*n:a=re.sub(r'\b'+''.join([i[0]for i in o.split()])+r'\b',f"({o})",a)
 return a

Try it online!

Clever, but I think this fails for GIGA Is GIGA Again.

@ChasBrown Oh no! I thought we were only to expand the first instance. T_T