text:
Basic sort, with annoying bug
Your input is a list/sequence/vector/array of 5-255 positive integers, not necessarily unique.  You may assume whatever input format is most suitable, and that each integer (as well as the quantity of integers) is chosen uniformly at random from the range 5-255.
The goal is to output the same list, in the same (or equivalent) format, but sorted into increasing (nondecreasing) order. A common early exercise in learning a language.  Submissions to include:

An answer which works correctly and achieves the goal; and
A second answer which contains an annoying bug.  Between 1% and 10% of the time, the output needs to be a list in the correct format and containing the correct elements, but in the wrong order (any order except correctly sorted).  The rest of the time, the program must work correctly and achieve the goal.

The two answers must have Levenshtein distance one; that is, we can get one from the other by deleting one byte, or adding one byte, or changing one byte.
Scoring as usual in code-golf (based on the shorter of your two answers), with usual loopholes forbidden.
10% bonus (decrease to score) if the annoying bug is input-independent, i.e. using the same input again doesn't reproduce the bug (except between 1% and 10% of the time).

Welcome to PPCG! I suggest removing the bonus, it’s not really good practice.

It seems that an answer that simply doesn't distinguish between two of the values (say, it can't tell 5 apart from 6, so it leaves 5s and 6s in the order they were given) fails with probability approximately 10.8%, which is just over the threshold.

It's unclear what is the probability of each possible input length.

Should the bugged program work correctly 1-10% of the time for each individual length, or is the length of the input also chosen at random? If it is, what is the distribution?

Should the spec between 1% and 10% of the time be fulfilled for each input or just overall for the set of possible inputs? For some inputs like [5,5,5] it's impossible to produce the wrong order

There's a subtlety regarding our default IO formats. If our code defines a function, is it OK if it has some chance of defining the function consistently buggy, as opposed to defining a function that has some chance of being buggy?

@LuisMendo, overall -- that's why I specified the probabilities as I did.

@Zgarb, the input length is 5-255, chosen uniformly at random.

@xnor, I'm afraid I don't understand the question.  If I run your code on the input (as specified, with random integers of random length), I should get buggy output between 1% and 10% of the time.

@VadimPonomarenko On this site people are allowed to provide functions as well as full programs. xnor is asking whether it is allowed to have a function that, 1% to 10% of the time when created, is a buggy function that will always have a bug. Keeping to the letter of your question the answer's probably no, but it would be more fun if it was yes.

@wizzwizz, the purpose of the challenge is to simulate a programmer trying to track down an intermittent bug.  If the buggy function always produces the wrong answer, then the bug is not intermittent.

@VadimPonomarenko I'm making a distinction between the function object that exists in the memory of the interpreter / program and the textual representation of code that creates the function. 1% to 10% of the time that the textual representation of code is evaluated, the function created will always have a bug. The rest of the time, the function created will not have the bug. Is this clearer?

@wizzwizz4, the transitory storage of the function object in memory is immaterial to this challenge.  What matters is usage of the code on data sets.  If I evaluate the code, and run it on 1000 data sets, I should get (roughly) 10-100 wrong outputs.  If instead there is a 5% chance of getting 1000 wrong outputs, then the bug is not intermittent.

It depends how you're doing it. If you are using something like Python's timeit with both the function definition and parameters, it would give you roughly 10-100 wrong outputs.

@wizzwizz4, if it gives 10-100 wrong outputs (1%-10% on average) then it is a valid submission.

But it depends how you test it. (cc: @xnor) I recommend allowing this since in most languages it won't shorten the program, but in languages where it's golfy it'll make it more interesting. But it's up to you as the OP.

If you choose to accept an answer, you should accept the answer that wins by the winning criteria (here: lowest score).

Python 3, 36 bytes
Bug-free version, 37 bytes
lambda l:sorted(l,reverse=l[-9:]==[])

Try it online!
Annoying version, 36 bytes
lambda l:sorted(l,reverse=l[9:]==[])

Try it online!
This depends on the input and therefore does not qualify for the bonus.
It has a probability of around 2% to fail. It fails when the input length is lower then 10.
Combined with LyricLy's answer this gets 34 bytes:
lambda l:sorted(l)[::l[9:]>[]or 1]
lambda l:sorted(l)[::l[9:]>[]or-1]

I don't think you need the space in the bug-free version.

@wizzwizz4 without the space or1 will get interpreted as an variable name and raises a syntax error.

05AB1E, 5*0.9 = 4.5 bytes
Working solution
{TLΩi

Try it online!
Explanation
{      # sort input
 TL    # push the range [1 ... 10]
   Ω   # pick a random number in the range
    i  # if true (equal to 1), do nothing

Solution containing the bug
Gives the wrong solution 10% of the time (independent on input).
{TLΩiR

Try it online!
Explanation
Same as the working solution, except it reverses the list if the number picked is true.

Seriously what the hey. Output isn't even of the right cardinality.

@Joshua What do you mean?

Try it online shows it outputting a list of lists.

@Joshua The TiO link includes a header 100F and a footer }, that help us visualize the result of the function called on the input multiple times. This shows us that the working solution always returns correct results, whilst the bugged one has flawed output .

Please, someone, explain the algorithm.  Soon I will accept the top-ranked submission (or one of the top-ranked submissions).  I can't accept any solution which I can't understand.

@VadimPonomarenko: Added an explanation

Jelly, 7 * (100% - 10%) = 6.3 bytes
Ṣ¹⁵X:¤¡

Try it online!
Buggy version:
ṢẊ⁵X:¤¡

Try it online!
In both links, there's a test harness that will run the code 100 times, each time with the list you give as the argument, and then return the results.
The probability of each input length is:
0.1 - 0.1/(length!)

So for length 1 there's a 0% probability, for length 2 5%, for length 3 8.83̅%, for length 4 9.583̅% etc. until length ∞ which has a 10% probability.

Should be 0.1 - 0.1/(length!).

@user202729 sure

Ṣ⁵X’¤¡ and Ṣ⁵X¤¡ should works too: buggy version return the list unsorted <10% of the time, and given that the input is chosen uniformly random, it should work, save 2 bytes.

If you don't like that solution you can obviously just delete the ¹ to save 1 byte (the rule count number of byte = the shorter one) ; also there is an extraneous combining overline after the second 6 in 6.6̅%.

@user202729 Unfortunately then it won't be input-independent anymore, and no I can't "just remove the ¹" because then it wouldn't sort at all 10% of the time.

Python 3, score 58 57 - 10% = 51.3
Saved a byte thanks to ovs.
Bug-free version, 57 bytes
lambda m:sorted(m)[::random()>.1or 1]
from random import*

Try it online!
Bugged version, 57 bytes
lambda m:sorted(m)[::random()>.1or-1]
from random import*

Try it online!
I decided to try a solution that uses the bonus. It doesn't beat the other Python answer, but I had fun thinking it up.

C, 71*0.9 = 63.9 bytes
Bug-free:
c(int*a,int*b){return*a-*b;}f(a,n)int*a;{if(rand()%1<9)qsort(a,n,4,c);}

Try it online!
Buggy:
c(int*a,int*b){return*a-*b;}f(a,n)int*a;{if(rand()%10<9)qsort(a,n,4,c);}

Try it online!

+1 for %1 (oh come on 6 more to go you gotta be kidding me)

Groovy, 31 bytes
Bugged solution:
{a->a.sort()[a[9]?0..-1:-1..0]}

Working solution:
{a->a.sort()[a[0]?0..-1:-1..0]}

The Groovy subscript operator (the getAt method) returns null for lists if the index is bigger than the size. So if there's a ninth element it'll stay the same as the sorted list, but if not (1.99203187% chance) it'll be reversed. However there will always be a first element because the list's size is always bigger than or equal to 5. So the 0 in a[0] could be swapped with 1, 2, 3 or 4.

Welcome to the site and nice first post!

Pyth, score 8 * 0.9 = 7.2
First snippet (correct one):
h.uSNT.S

Try it here!
Second snippet (bugged one):
O.uSNT.S

Try it here!
Saved two bytes (and 1.8 score) thanks to isaacg!

I think 9 rather than 10 new copies would be fine. The possibility of .S returning the input unchanged means that in those (rare) cases, our chances of getting the wrong answer drop from 10% to 0% - so on average, it's still in the right range. Of course, 10 copies are fine too.

@MishaLavrov I have made a mistake in my explanation, now addressed. I said .S might also return the input itself (which wouldn't be a problem), but I meant .S might also return the sorted list.

Right, that's what I meant too.

Same idea, but shorter: O.uSNT.S

Wolfram Language (Mathematica), 29 bytes
This is 26.1 bytes with the bonus, but I'm not entirely sure I earn the bonus; on already-sorted input, both versions always produce sorted output.
Bug-free version (29 bytes)
If[RandomReal[]<0.,#,Sort@#]&

Try it online!
Annoying version (30 bytes)
If[RandomReal[]<0.1,#,Sort@#]&

Try it online!

PHP, 70 bytes
Bug-free version, 70 bytes
<?unset($argv[0]);((rand(1,9)?"":r).sort)($argv);echo join(" ",$argv);

Try it online!
Bugged version, 70 bytes
<?unset($argv[0]);((rand(0,9)?"":r).sort)($argv);echo join(" ",$argv);

Try it online!
The bugged version sorts in reverse order 10% of the time (based on a random number generator).

no need for the tag with -r (-2 bytes). join by underscore; that should be equivalent (-2 bytes). use asort instead of sort (-1 byte).

... or use the whole word instead of prefix (or not): unset($argv[0]);(rand(1,9)?sort:rsort)($argv);echo join(_,$argv); (also 65 bytes)

Python 2, 26 bytes
Buggy:
lambda l:l[9:]and l.sort()

Try it online!
Outputs by modifying the input list.  Sorts the list only if its length is at least 10. The non-buggy version replaces the 9 with a 0 to always sort.
Working:
lambda l:l[0:]and l.sort()

Try it online!
We can modify the function to return the list at the cost of 4 bytes, for 30 bytes total:
lambda l:l[9:]and l.sort()or l

Try it online!

25 bytes with some stretches of the rules:
[list,sorted][id(0)%17>0]

Try it online!
Outputs a function literal that either sorts or is the identity, using id(0) as a random source. Change > to >= to fix, or 0 to ~0.

Husk, 6 bytes
Buggy version:
?OIV¦9

Try it online!
Correct version:
?OIVK9

Try it online!
Explanation
These programs are completely deterministic.
In fact, Husk has currently no support at all for random numbers.
?  V    If any element
    ¦9  is divisible by 9 (in buggy version),
    K9  is truthy when replaced by 9 (in correct version),
 O      sort the list,
  I     otherwise return it unchanged.

I claim that the output of the buggy program is not sorted with a probability between 1% and 2%.
Denote by N = 251 the number of possible values of the elements.
The probability that a random list of length L contains no multiples of 9 is ((N-K)/N)^L, where K is the number of values divisible by 9 (in our case K = 28).
The total probability is the average of this for 5 ≤ L ≤ 255, which is about 1.98%.
Some of these lists are false positives, since they are already sorted.
The probability of a random list of length L to be sorted is at most ((N+N*(N-1)/2)/N^2)^⌊L/2⌋: if we break the list into chunks of length 2, each of the ⌊L/2⌋ chunks must be sorted.
The total probability of a list being sorted is bounded by the average of the above for 5 ≤ L ≤ 255, which is about 0.30%.
Thus the probability of the function returning a non-sorted list is between 1.67% and 1.98%.

divisible by 9 gives approx 11% chance of failure. and not sorting doesn´t guarantee that the list is unsorted.

@Titus I address this in the analysis. Failure to sort occurs only if the list contains no elements that are divisible by 9. The probability of this is about 1.98%. And it's true that if the list is already sorted, doing nothing will also give a sorted list. However, the probability of the list being already sorted is at most 0.30%, which is low enough that the total probability of outputting an unsorted list is above 1%.

true ... and the input being sorted doesn´t change the bug.

Could you maybe use ↓9 instead of V¦9, and shorten it to just 9 for the correct version? This would make it always fail on short inputs and always work correcly on longer ones, but since the input length follows a random distribution it should still be a valid answer

Bash, 26 bytes
Correct version
s=n
sort -${s:RANDOM%20<0}

Try it online! or check the probabilities.
Bugged version
s=n
sort -${s:RANDOM%20<1}

Try it online! or check the probabilities.
Takes input as newline-separated numbers. Uses the builtin variable RANDOM, which always returns a (pseudo)random number in the range 0 - 32767. Using %20 results in about a 5% failure rate (thanks @Titus for clarifying issues with %10).
This randomness means the failure rate is independent of the input, but this does require that the input array includes at least one number with more than one digit, because the failure output is sorted lexicographically.
Alternate version, 27 bytes
((RANDOM+20))||cat&&sort -n

Bugged version replaces the + with a %. Try it online or try it bugged.

penny picking: %10 has a higher chance of returning 0 to 7 than 8 or 9, so the chance for failure is above 10% ;)

@Titus Thanks, I forgot about that fact. Updated to use %20 like your answer does.

JavaScript (ES6), 24 bytes
Bug-free version (at least for integers in the range 0-2147483647, so anything in the given range):
a=>a.sort((a,b)=>a-b>>0)

Buggy version:
a=>a.sort((a,b)=>a-b>>1)

Depends on a) the engine's sorting algorithm and b) the input list containing two values in the wrong order that differ by 1. (If the probability of that turns out to be too low then the 1 can be increased, but by the time you get to 8 it simply won't sort anything in the range 5-255.)

MATL, 7*0.9 = 6.3 6*0.9 = 5.4 bytes
Buggy version:
Gr.9<?S

Try it online!
Explanation:
G        % Grab input
 r       % Push a random number between 0 and 1
  .9     % Push 0.9
    <    % Check if the random number is smaller than 0.9
     ?   % If true
      S  % Sort input
         % Implicit output

Bug-free version:
Gr9<?S

Try it online!
Explanation:
G       % Grab input
 r      % Push a random number between 0 and 1
  9     % Push 9
   <    % Check if the random number is smaller than 9 (always true)
    ?   % If true
     S  % Sort the input
        % Implicit output

PHP, 62 bytes
inspired by Jo´s solution (and I just noticed: it´s a port of Justin Mariner´s):
working (sorts ascending):
unset($argv[0]);(r[rand()+20].sort)($argv);echo join(_,$argv);

buggy (approx. 5% chance of descending sort):
unset($argv[0]);(r[rand()%20].sort)($argv);echo join(_,$argv);

Run with -nr

Pushy, 9 bytes - 10% = 8.1
Bugged Solution:
g0TUn?};_

Try it online!
Working Solution:
g1TUn?};_

Try it online!
The bugged code does the following:
g0TUn?};_

g          \ Sort the stack correctly
 0TU       \ Generate random(0, 10)
    n? ;   \ If this is zero:
      }    \    Cyclically shift the stack right once
        _  \ Print the result

The fixed code simply changes 0 to 1. As random(1, 10) will never be 0, the if statement will never be executed.

Octave, 36*0.9 = 32.4 bytes
Buggy version:
@(x)sort(x)(shift(1:end,+(rand<.1)))

Try it online!
Bug-free version:
@(x)sort(x)(shift(1:end,+(rand<.0)))

Try it online!
This sorts the vector, then shifts all numbers one to the right if a random number is less than 0.1.

Yes, you're of course right :) Thanks :)

Jq 1.5, 42 bytes
Buggy
sort|if length%13<=0then reverse else. end

Working (delete the =)
sort|if length%13<0then reverse else. end

Assuming line lengths are uniform in range [5,255] about 7% will trigger the bug
Try it online!

J, 22.5 bytes (25 bytes - 10%)
with bug:
[:]`(1&A.)@.(0.1>?@0:)/:~

without bug:
[:]`(0&A.)@.(0.1>?@0:)/:~

Try it online!

R, 30*.9 = 27 bytes
(buggy)
function(l)sort(l,runif(1)<.1)

Try it online!
(not buggy)
function(l)sort(l,runif(1)<.0)

The buggy version sorts in decreasing=T 10% of the time, sampling from a uniform(0,1) distribution. The un-buggy version is always decreasing=F

Röda, 42 bytes - 10% = 37.8
Bug-free:
{sort key={|i|currentTime|[_%20//19*0+i]}}

Buggy:
{sort key={|i|currentTime|[_%20//19*i+i]}}

Try it online!
This uses the currentTime function to create random numbers. It seems that their distribution varies a little between machines. The ratio 20//19 can be adjusted to get different results for no byte penalty (unless it is smaller than 99//98).

Java 8, 45 34.2 (50 38 - 10%) bytes
Normal version:
a->{if(Math.random()>0.)a.sort(null);}

Explanation:
Try it here.
a->{                    // Method with ArrayList<Integer> parameter and no return-type
  if(Math.random()>0.)  //  If the random 0-1 double is larger than 0:
    a.sort(null);       //   Sort the input-List
}                       // End of method

Bugged version (51 39 bytes):
a->{if(Math.random()>0.1)a.sort(null);}

LD of 1: 1 added.
Explanation:
Try it here.
a->{                     // Method with ArrayList<Integer> parameter and no return-type
  if(Math.random()>0.1)  //  If the random 0-1 double is larger than 0.1:
    a.sort(null);        //   Sort the input-List
}                        // End of method

JavaScript, 25*0.9=22.5
new Date%25?x:x.sort()

input x


text:
Tips for Golfing in SQLite?
I was looking for this page to help me enhance my first answer with SQLite, but I couldnt find one. So here we are!
What general tips do you have for golfing in SQLite? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to SQLite. Please post one tip per answer.
Thanks to Michael B for the idea. :)
Related: Tips for Golfing in T-SQL?

source: Stack Exchange

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

sort: votes


text:
An Array of Challenges #3: Moving Averages
Note: This is #3 in a series of array-manipulation challenges. For the previous challenge, click here.
Moving Average of a List

The moving average of a list is a calculation resulting in a new, smoothed out list, created by averaging small overlapping sublists of the original.

When creating a moving average, we first generate the list of overlapping sublists using a certain 'window size', shifting this window to the right once each time.
For example, given the list [8, 4, 6, 2, 2, 4] and the window size 3, the sublists would be:
[8,  4,  6,  2,  2,  4]          Sublists:
(         )                  <-  [8, 4, 6]
    (         )              <-  [4, 6, 2]
        (         )          <-  [6, 2, 2]
            (         )      <-  [2, 2, 4]

We then calculate the mean average of each sublist to obtain the result: [6.0, 4.0, 3.3, 2.7] (each value rounded to one decimal place).

The Challenge
Your task is to write a program or function which, given a list L, and an integer 1 ≤ n ≤ length(L), calculate the moving average for L using the window size n.
Rules:

Your program may use integer division or float division. In the case of float division, small inaccuracies due to the data type's limitations are permitted, as long as the value is otherwise correct.
You may submit a full program, or a function (but not a snippet).
You may assume that the list will only contain positive integers.
Standard loopholes are forbidden.
This is code-golf, so the shortest answer (in bytes) wins!

Test Cases
Note that, for ease of readability, all values are rounded to one decimal place.
n=5, [1, 2, 3, 4, 5, 6, 7, 8]      ->      [3, 4, 5, 6]
n=3, [100, 502, 350, 223, 195]     ->      [317.3, 358.3, 256]
n=1, [10, 10, 10]                  ->      [10, 10, 10]
n=3, [10, 20, 30]                  ->      [20]
n=2, [90, 40, 45, 100, 101]        ->      [65, 42.5, 72.5, 100.5]

Do we have to round float values, or can we leave them as they are?

@cairdcoinheringaahing Note that, for ease of readability, all values are rounded to one decimal place. In my opinion, you can definitely leave them as they are (at least that's what I understand).

@cairdcoinheringaahing I've been quite liberal with I/O: integer or float values are fine, you may round if you want but don't have to, and floating point errors are allowed

Is it okay to return fractions instead of floating point numbers?

@JungHwanMin If for accuracy, your language will store values as fractions rather than floats, it's fine to print them as accurate fractions in their simplest forms.

Related (sliding window on a string)

Dyalog APL, 4 bytes
1 byte saved thanks to @Graham
2 bytes saved thanks to @jimmy23013
Did I mention APL is not a golfing language?
⊢+/÷

with n on the right, or
+/÷⊣

with L on the right.
Try it online!
How?
÷ - divide L by n
⊢+/ - reduce + on windows of n

Why not divide L by n before the reduction. Saves a byte

⊢+/÷

Or +/÷⊣

@jimmy23013 thanks alot! I tried that one earlier, but must've typed the arguments wrong cos it didn't work.

Jelly, 3 bytes
ṡÆm

Try it online!
Pretty simple thanks to ṡ
How it works
ṡÆm - Main dyadic link. Arguments: l (list) and n (integer)
ṡ   - Split l into sublists of length n
 Æm - Mean of each

Wolfram Language (Mathematica), 13 bytes
Mathematica has a built-in for everything
MovingAverage

Try it online!
Takes a list and then a radius...

MovingAverage ಠ_____ಠ I refuse to believe this

@cairdcoinheringaahing Takes the numerical value. MovingAverage returns a set of fractions. Now that it's been allowed by the OP, MovingAverage should suffice indeed.

Haskell, 47 bytes
n!a|length a<n=[]|_:t<-a=div(sum$take n a)n:n!t

Try it online!
Saved two bytes thanks to xnor!

tail a can be extracted in the guard.

Gah, I knew I was missing something like that. Thank you!

Python, 48 bytes
f=lambda n,l:l[n-1:]and[sum(l[:n])/n]+f(n,l[1:])

Try it online!
A recursive function. Shorter than the program (50 bytes)
n,l=input()
while l[-n]:print sum(l[:n])/n;l=l[1:]

Try it online!
This saves 2 bytes by terminating with error on the while condition.

Enlist, 3 bytes
ṡÆm

Try it online!

Polyglot with Jelly :P

@cairdcoinheringaahing I only just noticed your Jelly answer too lol :P

Perl 6, 33 bytes
{@^a.rotor($^b=>1-$b)».sum X/$b}

Test it
Expanded:
{  # bare block with placeholder parameters ｢@a｣, ｢$b｣

  @^a                # declare and use first param

  .rotor(            # split it into chunks
    $^b              # declare and use second param
    =>               # pair it with
    1 - $b           # one less than that, negated

  )».sum             # sum each of the sub lists

  X/                 # cross that using &infix:«/»

  $b                 # with the second param
}

C,  86   84  83 bytes
i,j,s;f(a,l,n)int*a;{for(i=-1;i+++n<l;s=!printf("%d ",s/n))for(j=n;j--;)s+=a[i+j];}

Try it online!
Unrolled:
i, j, s;
f(a, l, n)int*a;
{
    for(i=-1; i+++n<l; s=!printf("%d ", s/n))
        for(j=n; j--;)
            s += a[i+j];
}

Ohm v2, 3 bytes
ÇÆm

Try it online!
Explanation:
ÇÆm  Main wire, arguments l (list) and n (integer)

Ç    All consecutive sublists of l with length n
 Æm  Arithmetic mean of each sublist

J, 7 5 bytes
]+/\%

Try it online!
Takes n as the right argument and the list as the left. Credit to Uriel's solution for the idea of doing only the summation in the infix.
Explanation
]+/\%
    %  Divide list by n
]+/\   Sum on overlapping intervals of size n

Previous solution (7 bytes)
(+/%#)\
      \  Apply to overlapping intervals of size n
(+/%#)   Mean
 +/        Sum
   %       Divided by
    #      Length

Pyth, 5 bytes
.O.:F

Try it here!
How this works

.O.:F  - Full program.

    F  - Reduce the input (nested list) with...
  .:   - ... Sublists.
.O     - Average of each.

Octave, 33 31 bytes
@(x,n)conv(x,~~(1:n)/n,'valid')

Try it online!
Explanation
Convolution (conv) is essentially a moving weighted sum. If the weights are chosen as [1/n, ..., 1/n] (obtained as ~~(1:n)/n) the result is a moving average, of which only the 'valid' part is kept.

Python 3, 55 bytes
lambda n,A:[sum(A[j:n+j])/n for j in range(-n-~len(A))]

Try it online!

05AB1E, 5 bytes
ŒsùÅA

Explanation:
Œ     All substrings
 sù   Keep those only where the length is equal to <the second input>
   ÅA Arithmetic mean of each element in the resulting array.

Try it online!

Japt v2.0a0, 7 bytes
ãV ®x÷V

Try it

Explanation
Implicit input of array U and integer V.
ãV

Get subsections of U with length V
®

Map over the subsections.
÷V

Divide each element by V.
x

Sum all elements.

R, 72 bytes
function(l,n)(k=sapply(0:sum(l|1),function(x)mean(l[x+1:n])))[!is.na(k)]

Try it online!
Computes the mean of all the size n windows; when the window goes past the edge of l, the results are NA so we filter them out.
R + zoo package, 13 bytes
zoo::rollmean

The zoo package (S3 infrastructure for Regular and Irregular Time Series) has a lot of handy functions. You may try it here (R-fiddle).

Factor + math.extras, 14 bytes
moving-average

Try it online!
Built-in.

Factor, 22 bytes
[ clump [ mean ] map ]

Try it online!
Explanation:
A non-trivial answer. It's a quotation (anonymous function) that takes a sequence and an integer from the data stack as input and leaves a sequence on the data stack as output.

clump Split a sequence into groups of n with overlapping. This creates the moving window.
[ mean ] map Map each window to its mean.

Python 3, 61 bytes
lambda l,n:[sum(e)/n for e in zip(*[l[i:]for i in range(n)])]

Try it online!

Mathematica, 21 bytes
Mean/@##~Partition~1&

Try it online!
-3 bytes JungHwan Min

-3 bytes: N[Mean/@##~Partition~1]&

CJam, 14 12 bytes
 -2 bytes thanks to @aditsu
{_@ew::+\f/}

Proton, 46 bytes
n=>l=>[sum(l[h to h+n])/n for h:0..len(l)-n+1]

Try it online!
Note that this takes input via currying functions syntax, and returns a list of fractions.

Jq 1.5, 61 bytes
def f(N;L):[L|range(0;1+length-N)as$i|.[$i:$i+N]|add/length];

Expanded
def f(N;L):
  [   L
    | range(0;1+length-N) as $i        # generate
    | .[$i:$i+N]                       # sublists
    | add/length                       # compute mean
  ];

Try it online!

Make only N a parameter, and take L from the stream: 57 bytes JqPlay (I know I'm years late, but couldn't resist)

x86 Machine Code, 20 bytes
86 89 D9 31 C0 03 44 8F FC E2 FA 31 D2 F7 F3 AB 39 F7 72 ED C3

The above bytes define a function that calculates the moving average of a list, modifying the elements of the list in-place. It assumes that the list is a contiguous array of integer elements. The function takes the following inputs in registers

edi: the address of the first element in the list (i.e., a pointer to the beginning of the array)
esi: the address of the element following the last element in the list (i.e., a pointer to one past the end of the array)
ebx: the size of the window (i.e., number of elements to consider in each window)

This is a custom calling convention, which is common when writing machine/assembly language functions. All averaging operations are done internally in integer mode, as provided for by the challenge.
The input array, bounded by the addresses specified as edi and esi, is modified in-place by the function: the first n elements are replaced with the corresponding moving average. Thus, the caller just discards all but the first n elements.
Try it online!
Here are the ungolfed assembly mnemonics:
MovingAverage:
; Inputs:
;    edi = &array[0]
;    esi = &array[N]
;    ebx = cWindow
; Outputs:
;    array is modified in-place, starting from the beginning
; Clobbers:
;    eax, ecx, edx, edi, flags
              OuterLoop:
89 D9            mov    ecx, ebx
31 C0            xor    eax, eax
              InnerLoop:
03 44 8F FC      add    eax, DWORD PTR [edi + ecx * 4 - 4]
E2 FA            loop   InnerLoop
31 D2            xor    edx, edx
F7 F3            div    ebx
AB               stos ; DWORD PTR [edi], eax; sub edi, 4
39 F7            cmp    edi, esi
72 ED            jb     OuterLoop
C3               ret

The assembly code should be pretty self-explanatory, although I hope sufficiently clever! The code basically just runs two loops. The outer loop iterates through the entire array, one element at a time. The inner loop starts at the current element, iterates through the length of the window, and computes the sum. After the inner loop, the sum is used to compute the average (simple division by the window size), and then the resulting moving average for that "sublist" is written back into the original array at the current index.
Very few notable "tricks" here. Of mention:

Cleverly choosing the calling convention allows significant savings with the elision of unnecessary MOV instructions. (Of course, that burden is transferred onto the caller, but they're not playing code golf!)
The string instruction, STOSD, is used to save a large number of bytes; encoded with only 1 byte, it writes the contents of the eax register back to the memory location contained in edi, while simultaneously incrementing edi by 4 bytes to contain the location of the next element.
The LOOP instruction (which does a combined decrement of ecx and loop if its new value is not equal to 0) is used to save a couple of bytes.

Clojure, 48 bytes
(fn[n a](map #(/(apply + %)n)(partition n 1 a)))

Try it online!

DataWeave, 50 bytes
fun s(l,w)=0 to(sizeOf(l)-w)map avg(l[$ to $+w-1])

%dw 2.0
output application/json

fun sma(list: Array<Number>, window: Number) =
  0 to (sizeOf(list) - window)  // generate starting indices of sublists
  map list[$ to $ + window - 1] // generate sublists
  map avg($)                    // calculate averages

---
sma([90, 40, 45, 100, 101], 2)

Stacked, 22 bytes
[infixes[:sum\#'/]map]

Try it online!
Explanation
infixes generates all the windows of the given length. Then, we map our own average function over each infix.

Common Lisp, 77 bytes
(defun f(x y)(if(>=(length x)y)(cons(/(apply'+(subseq x 0 y))y)(f(cdr x)y))))

Try it online!

Funky, 67 66 bytes
Saved a byte with curry syntax.
n=>t=>{k={}fori=0i<=(#t)-n i++k[i]=(forj=c=0c<n c++j+=t[i+c])/n k}

Try it online!

Java 8, 111 bytes
a->n->{int l=a.length-n+1,i=0,j;float[]r=new float[l];for(;i<l;r[i++]/=n)for(j=i;j<i+n;r[i]+=a[j++]);return r;}

Explanation:
Try it here.
a->n->{                 // Method with array and int parameters and float-array return-type
  int l=a.length-n+1,   //  New length of the return-array
      i=0,j;            //  Index-integers
  float[]r=new float[l];//  Return-array
  for(;i<l;             //  Loop (1) from 0 to `l` (exclusive)
      r[i++]/=n)        //    After every iteration, divide the current item by input `n`
    for(j=i;j<i+n;      //   Inner loop (2) from `i` to `i+n` (exclusive)
      r[i]+=a[j++]      //    Sum the result at index `i` with the items of the input-array
    );                  //   End of inner loop (2)
                        //  End of loop (1) (implicit / single-line body)
  return r;             //  Return the resulting float-array
}                       // End of method

Ruby, 35 bytes
->l,n{l.each_cons(n){|x|p x.sum/n}}

Try it online!

JavaScript (ES6), 53 bytes
(l,n)=>l.map(e=>(s+=e-=a[i-n]||0)/n,s=i=0).slice(n-1)

PHP, 94 bytes
function f($l,$n){while($i<=count($l)-$n)$r[]=array_sum(array_slice($l,$i++,$n))/$n;return$r;}

Try it online!

K (oK), 13 11 bytes
Solution:
{+/+x':y%x}

Try it online!
Examples:
{+/+x':y%x}[3;8 4 6 2 2 4]
6 4 3.3333 2.6667
{+/+x':y%x}[5;1 2 3 4 5 6 7 8]
3 4 5 6

Explanation:
oK has a built-in for creating a sliding window, then sum up resulting arrays and divide by sliding window size to get mean:
{+/+x':y%x} / the solution
{         } / lambda function taking x and y as implicit parameters
       y%x  / y (list) by x (sliding array size)
    x':     / sliding window of size x over list y
   +        / flip array (rotate by 90 degrees)
 +/         / sum up array

Looks like you don't need the flip array +, and if K has commute like APL you can move x%[commute] to left and drop the parens

The flip is needed to ensure the sum is across rather than down each list, and fairly sure there's no commute operator, at least nothing to suggest it in the manual. Cheers though!

Python 57 bytes:
lambda L,n:[sum(L[i:(i+n)])/n for i in range(len(L)-n+1)]

Husk, 3 bytes
mAX

Try it online!
Output as a list of rationals.

mAXimum conciseness indeed.

Look ma, no Unicode!

Perl 5 -MList::Util=sum -a, 44 bytes
say sum(@F[$_..$_+$,-1])/$,for 0..@F-($,=<>)

Try it online!

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

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


text:
Pick-flatten a list
Consider the process of "picking" a nested list. Picking is defined as follows:

If the argument is a list, take an element from the list at random (uniformly), and pick from that.
If the argument is not a list, simply return it.

An example implementation in Python:
import random
def pick(obj):
    if isinstance(obj, list):
        return pick(random.choice(obj))
    else:
        return obj

For simplicity, we assume that nested lists only contain integers or further nested lists.
Given any list, it is possible to create a flattened version which is indistinguishable by pick, i.e. picking from it yields the same results, with the same probability.
For example, "pick-flattening" the list
[1, 2, [3, 4, 5]]

yields the list
[1, 1, 1, 2, 2, 2, 3, 4, 5]

. The reason simply flattening is invalid is because elements of sub-lists have a lower probability of being chosen, e.g. in the list [1, [2, 3]] the 1 has a 2/4 = 1/2 chance of being chosen while 3 and 4 both have a 1/4 chance each.
Also note that picking from a singleton list is equivalent to picking from its element, and that picking from an empty list has no meaning.
The Challenge
Given a nested list of nonnegative integers, return a flattened list of nonnegative integers from which picking yields the same results with the same probability.
This is code-golf, so the shortest valid answer (measured in bytes) wins.
Specifications

The inputs [2, 3, 4], [2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4], and [2, [3, 3], [[4]]] are equivalent (i.e. they should give equivalent results).
The outputs [2, 2, 2, 2, 3, 3, 3, 3] and [2, 3] are equivalent (i.e. either one could be output).
You can assume only numbers in the inclusive range 1-100 will be present in the lists.
You can assume the top-level input will be a list, i.e. 2 is not a valid input.
You can use any reasonable representation of nested lists, for example:
[1, [2, 3]], 1 {2 3}, "[ 1 [ 2 3 ] ]", etc.
Instead of a list, you can output a multiset or a mapping, or, since only numbers in the range 1-100 are allowed, a length-100 list of integers representing quantities.

Test Cases
Note that the listed outputs are only one valid possibility; see specifications for what constitutes a valid input or output.
format:
input -> output
[3]                          -> [3]
[1, [1, 1]]                  -> [1]
[1, [2, 3]]                  -> [1, 1, 2, 3]
[2, 3, [4, [5, 5, 6], 6, 7]] -> [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7]
[[1, 1, 2], [2, 3, 3]]       -> [1, 2, 3]
[[1, 1, 2], [2, 3, 3, 3]]    -> [1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3]

Given the length encoding option and the bounded range, may we alternatively output a list of 100 elements depicting the occurrences of every integer? (which will result with many zeros for the given examples)

@Uriel Sure; I'll reword it.

Wolfram Language (Mathematica), 41 20 bytes
Flatten@*Tuples//@#&

Try it online! Ignore the many warnings, it all works out in the end.
How it works
For a list of depth 2 such as {{1,2},{3},{4,5,6}}, Tuples will generate the list {{1,3,4},{1,3,5},{1,3,6},{2,3,4},{2,3,5},{2,3,6}} corresponding to all the ways to pick an element from {1,2} and pick an element from {3} and pick an element from {4,5,6}.
If we Flatten this, then we get all the elements with the correct frequencies, because picking an element from one of {1,2}, {3} or {4,5,6} is equivalent to picking an element from all of them, then choosing which one to keep.
We use //@ to apply this at all levels of the input. In the process, Mathematica complains a lot, because it's turning atoms such as 17 into Tuples[17], which is really not supposed to be a thing. But these simplify to the right result later on (Tuples is happy to treat Tuples[17] as a list of length 1, even if it has a head other than List), so the complaining is irrelevant.

Python 2, 105 102 99 bytes
g=lambda y=[],*z:[w+[n]for n in y for w in g(*z)]or[y]
f=lambda x:x<[]and[x]or sum(g(*map(f,x)),[])

Try it online!

Jelly, 9 8 bytes
ß€Œp$¬¡F

Try it online!
How it works
ß€Œp$¬¡F  Main link. Argument: x (array or positive integer)

     ¬    Compute elementwise logical NOT of x: a non-empty array for a non-empty array, 0 for a positive integer.
      ¡   Apply the link to the left once if ¬ returned a non-empty
          array, zero timed if it returned 0.
    $     Monadic chain:
ß€            Map the main link over x.
  Œp          Take the Cartesian product.
       F  Flatten the result.

Jelly, 10 bytes
L€P⁸ṁ€ẎµÐL

Try it online!

@Challenger5 sorry, no time for that yesterday

Python 2, 128 bytes
def f(l,p=0):m=reduce(int.__mul__,[i*0<[]or len(i)for i in l]);return p*(p==l)or f(sum([(([i],i)[i*0>0]*m)[:m]for i in l],[]),l)

Try it online!
Port of my Jelly answer.
-12 thanks to Jonathan Frech.

I think type(i)==int can be i*0<[].

@JonathanFrech Sure, 0<[]...and type(i)==list can be i*0>0 ;)

C (gcc), 234 223 bytes
h[9][101];o[101];n[9];l;L;e;main(x){for(;(x=scanf("%d",&e))>=0;x?++h[l][e],++n[l]:(e=getchar())-'['?e-']'?0:--l:++l>L&&++L);for(e=1,l=L+1;l--;){for(x=101;--x;o[x]+=e*h[l][x]);e*=n[l];}while(o[x]--?printf("%d ",x):++x<101);}

Try it online!
Explanation:
h[9][101];  // <- number occurences per nesting level
o[101];     // <- number occurences in "flattened" array
n[9];       // <- number of entries per nesting level
l;          // <- current nesting level
L;          // <- max nesting level
e;          // <- multi-purpose temporary
main(x){    // x: multi-purpose temporary
    for(;
            // while not EOF try reading number
            (x=scanf("%d",&e))>=0;

            // number was read?
            x

                // then increment occurence and # entries in level
                ?++h[l][e],++n[l]

                // else read any character ... if not [
                :(e=getchar())-'['

                    // if not ]
                    ?e-']'

                        // do nothing
                        ?0

                        // else decrement nesting level
                        :--l

                    // else increment nesting level and adjust max level
                    :++l>L&&++L);

    // init factor in e to 1, iterate over nesting level from innermost
    for(e=1,l=L+1;l--;){

        // iterate over all numbers
        for(x=101;
                --x;

                // add factor times occurence on current level to output
                o[x]+=e*h[l][x]);

        // multiply factor by number of entries on current level
        e*=n[l];
    }

    // iterate over all numbers and output count times
    while(o[x]--?printf("%d ",x):++x<101);
}

216 bytes

Python 2, 144 139 bytes
def f(A,p):[F.append((len(A)*p,a))if a*0<[]else f(a,len(A)*p)for a in A]
F=[];f(input(),1);R=[]
for v in F:R+=max(F)[0]/v[0]*[v[1]]
print R

Try it online!

JavaScript (ES6), 132 131 bytes
f=A=>(_=(a,m)=>[].concat(...a.map(m)),n=1,A=A.map(a=>a.map?f(a):[a]),_(A,a=>n*=a.length),_(A,a=>_(a.map(x=>Array(n/a.length).fill(x)))))

f=A=>(_=(a,m)=>[].concat(...a.map(m)),n=1,A=A.map(a=>a.map?f(a):[a]),_(A,a=>n*=a.length),_(A,a=>_(a,x=>Array(n/a.length).fill(x))))

console.log( f( [3] ) )
console.log( f( [1, [1, 1]] ) )
console.log( f( [1, [2, 3]] ) )
console.log( f( [2, 3, [4, [5, 5, 6], 6, 7]] ) )
console.log( f( [[1, 1, 2], [2, 3, 3]] ) )
console.log( f( [[1, 1, 2], [2, 3, 3, 3]] ) )
console.log( f( [1, 2, [3, 4, 5], [6, 7]] ) )


text:
Convert between Music clefs
Before you leave, you do not have to understand much musical notation to do this challenge.
EXPLANATION
In standard sheet music,  double clefs go across the page serving as reference points to the notes, letting you know what note should be played. If you are not already familiar with the treble and bass clef,  here is a description from Wikipedia:

A clef is a musical symbol used to indicate the pitch of written notes. Placed on one of the lines at the beginning of the stave, it indicates the name and pitch of the notes on that line. This line serves as a reference point by which the names of the notes on any other line or space of the stave may be determined.

In the image above, the top half of the lines is the Treble clef, denoted with a
The bottom half is the Bass clef, denoted with a
As you can see on the treble clef a note on the bottom-most line is an E. (I am not counting notes outside of the clef lines for this challenge) On the bass clef, the lowest line is a G.
To complete this challenge, you must do the following:
CHALLENGE
Given an input in one of the following forms (your choice), convert it to the opposite clef. Whether it is the Treble or Bass clef can be a Truthey/Falsey value in your language (not just any two values), e.g.
F# T
or
F# True
or
F# Treble
but not
F# -1
or
F# 4
Spaces and capitalization are optional, Flats will not appear, and trailing whitespace is not allowed.
Input          Expected Output
E   Treble     G
F   Treble     A
F#  Treble     A#
G   Treble     B
G#  Treble     C
A   Treble     C
A#  Treble     C#
B   Treble     D
C   Treble     E
C#  Treble     F
D   Treble     F
D#  Treble     F#
E   Treble     G
F   Treble     A
F#  Treble     A#
G   Bass       E
G#  Bass       F
A   Bass       F
A#  Bass       F#
B   Bass       G
C   Bass       A
C#  Bass       A#
D   Bass       B
D#  Bass       C
E   Bass       C
F   Bass       D
F#  Bass       D#
G   Bass       E
G#  Bass       F
A   Bass       F
A#  Bass       F#

Be forewarned, this is not a trivial constant difference challenge. Look closely at the inputs and outputs. If you look at a piano,

the black keys are sharps, denoted by #. Note that there is not an E# or a B#. This means that if you are given G# on the Bass clef, instead of returning E#, you need to return F
This is code-golf, so the smallest byte-count wins.

Do we have to worry about flats? How about double flats/sharps?

Please don't create tags for topics that don't warrant them.

Is trailing whitespace (returning C  instead of C) okay?

Is using 1 and -1 (or even say, 4 and -4) for the clef indicator input allowed or would this only be acceptable if they are truthy/falsey values in our language?

Naturally, there should be bonus points for the less common clefs: https://en.wikipedia.org/wiki/Clef#Individual_clefs

This is a nice and well presented challenge, but it would have been even better IMO with slightly relaxed input/output formats.

Jelly,  35  34 bytes
I have a feeling some arithmetic may win over this method.
ØAḣ7µW€ż;€”#$Ẏ
Ç”C4¦”F⁵¦
Ñi+_⁸?4ị¢

Try it online!
A full program taking 1) the clef indicator 0 or 1 for Bass or Treble respectively and 2) the note; and printing the resulting note.
Would be 31 bytes if -4 and 4 were acceptable as the clef indicator input values (then Ñi+_⁸?4ị¢ can become Ñi+⁸ị¢) but this has been clarified as not allowed unless -4 is falsey and 4 is truthy, which is not the case for Jelly.
How?
Builds a keyboard with phantom B# and E# keys, finds the index of the input, offsets that by 4 in the required direction, indexes back into a keyboard with those phantom keys replaced by their required results (the key above them):
ØAḣ7µW€ż;€”#$Ẏ - Link 1, keyboard with phantoms: no inputs
ØA             - alphabet yield        -> ['A', 'B', ..., 'Z']
   7           - literal seven
  ḣ            - head                  -> ['A','B','C','D','E','F','G']
    µ          - new monadic chain, call that K
     W€        - wrap €ach             -> ["A","B","C","D","E","F","G"] ("" being lists of characters)
            $  - last two links as a monad:
          ”#   -   character '#'
        ;€     -   concatenate to €ach -> ["A#","B#","C#","D#","E#","F#","G#"]
       ż       - zip together          -> [["A","A#"],["B","B#"],["C","C#"],["D","D#"],["E","E#"],["F","F#"],["G","G#"]]
             Ẏ - tighten               -> ["A","A#","B","B#","C","C#","D","D#","E","E#","F","F#","G","G#"]

Ç”C4¦”F⁵¦ - Link 2, keyboard with phantoms replaced: no inputs
Ç         - call the last link (1) as a monad  ["A","A#","B","B#","C","C#","D","D#","E","E#","F","F#","G","G#"]
    ¦     - sparse application:
   4      - ...to index: literal four
 ”C       - ...action: character 'C'    -> ["A","A#","B","C","C","C#","D","D#","E","E#","F","F#","G","G#"]
        ¦ - sparse application:
       ⁵  - ...to index: literal ten
     ”F   - ...action: character 'F'    -> ["A","A#","B","C","C","C#","D","D#","E","F","F","F#","G","G#"]

Ñi+_⁸?4ị¢ - Main link: integer, clef (1 Treble / 0 Bass); list of characters, key
                                      e.g. 0; "D#"
Ñ         - next link (1) as a monad (no atom for next link as a nilad, but this works here anyway)
          -                               ["A","A#","B","B#","C","C#","D","D#","E","E#","F","F#","G","G#"]
 i        - first index of key in that    8
      4   - literal four
     ?    - if:
    ⁸     - ...condition: chain's left argument, clef
  +       - ...then: addition
   _      - ...else: subtraction          4
        ¢ - next link as a nilad          ["A","A#","B","C","C","C#","D","D#","E","F","F","F#","G","G#"]
       ị  - index into                    "C"

Green check: Hmm, so nobody yet beat this score - I am fairly shocked.

Befunge, 70 64 bytes
~0~:70p##~+2%00p+"A"-~7%2++7%:3%2%00g*:10p+"A"+,00g!10g+#@_"#",@

Try it online!
The input should be in the form C# Treble or F Bass, although the clef can simply be the first letter (i.e. T or B), since the rest of the input is ignored anyway.
Explanation
~0        Read the note and push a zero (the purpose of this will become apparent later).
~:70p     Read the following sharp or space and write that out as the next instruction.

As a result of this code modification, the next sequence of instructions will take one of two forms:
##~       The first # jumps over the second, and thus we perform the read instruction.
 #~       But if there's only one #, we'll ending up skipping the read instruction.

At this point the stack either contains note,0,sharp,space or note,0,space.
+2%       Add the top two stack items mod 2, returning 1 if we read a sharp, else 0 if not.
00p       Save this 'sharp' boolean for later use.

At this point the stack either contains note,0 or just note (with an implicit zero below).
+         By adding the top two items, we combine the 0 (if present) onto the note below.
"A"-      We can then subtract 'A' to convert the note into a number in the range 0 to 6.
~7%2+     Read the T/B clef, then mod 7 and add 2, returning 2 or 5 (the conversion offset).
+7%       Add that offset to our note number, then mod 7, to get the converted note number.
:3%2%     Make a dup, and calculate mod 3 mod 2 to determine the special cases (B# or E#).
00g*      Multiply that by the 'sharp' boolean, since we only care if the input was sharp.
:10p      Duplicate and save this special case boolean for later.
+         Now add it to the note number, since the special cases need to be offset by 1.
"A"+,     Then we can finally convert the number back into a character and output it.
00g!10g+  Now we check if the original note was not sharp, or if this was a special case.
#@_       If so, we exit immediately.
"#",@     Otherwise, we output a '#'.

Python 2, 77 bytes
Function which prints to STDOUT. True converts bass to treble, and False converts treble to bass.
def f(n,c):N=ord(n[0])-63-4*c;M=-~N%3<1<len(n);print chr((N+M)%7+65)+n[1:2-M]

Try it online!
Explanation:

The first statement, N=ord(n[0])-63-4*c;, calculates the index (0 to 7) of the new note's letter, disregarding sharps.

ord(N[0])-63-4*c gets the current letter's index, and adds or subtracts 2 depending on the value of c (variable to toggle conversion direction)

The next statement, M=-~N%3<1<len(n); calculates whether or not this variable will need to be adjusted. For example, if the new note is E, and the original note had a sharp, this will need to be adjusted to an F. The chained inequality works as follows:

-~N%3<1 checks whether the new note's index is in the sequence 3n-1. This will only  yield true for E and B, the two notes which do not have a sharp.
1<len(n) checks if the original note had a sharp (this would make the string's length larger than 1). This is necessary as, if there was no sharp, there is no need to adjust the new note letters.
This sets the value of M to either True or False, which can be used in calculation as 1 and 0 respectively, so to perform the adjustment we need only add M to N and modulo by 7.

The final statement creates and outputs the final result.

chr((N+M)%7+65) adds the adjustment if necessary, then converts the value from an index back to a character.
+n[1:2-M] will append a sharp symbol if both M=0 (no adjustment was made) and the original value also had a sharp.

Sorry, only 0&1, Truthey&Falsey, or T&B

@tfbninja thanks for the clarification

Perl 5, 56 bytes
$_=<>;s/./chr 65+(-4*<>+ord$&)%7/e;s/B#/C/;s/E#/F/;print

Reads the note and clef as two lines from STDIN and prints the new note to STDOUT. The clef is 0 for treble and 1 for bass.

can save 11 bytes using -p flag https://tio.run/##K0gtyjH9/79YX08/OaNIwcxUW0PXRMvGTju/KEVFTVPVXD/VuljfSVnfWR9Iuyrru@n//@@uzGX4L7@gJDM/r/i/bgEA

JavaScript (ES6) 74 bytes
Takes input in currying syntax (note)(clef) where clef is 0 for bass and 1 for treble.
n=>c=>'FC.DAFCGDAEBF'[k=(parseInt(n,36)*15+!n[1]*90+c)%98%13]+(k<5?'#':'')

Demo

let f =

n=>c=>'FC.DAFCGDAEBF'[k=(parseInt(n,36)*15+!n[1]*90+c)%98%13]+(k<5?'#':'')

;[1, 0].forEach(c => {
  [ 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B', 'C', 'C#', 'D', 'D#' ].forEach(n => {
    console.log(
      (n + '  ').slice(0, 3) +
      ['Bass  ', 'Treble'][c] +
      ' --> ' +
      f(n)(c)
    )
  })
})

How?
This is actually slightly less fun than my previous version, but the underlying lookup table is now F#,C#,(unused),D#,A#,F,C,G,D,A,E,B,F which allows to shorten the # condition while avoiding the NUL character trick -- which was a bit border-line, I suppose.

Previous version 76 75 bytes
n=>c=>'ACCDFF.CDEFGABCDE'[k=parseInt(4*!!n[1]+c+n,21)%24%17]+'\0#'[45>>k&1]

Demo

let f =

n=>c=>'ACCDFF.CDEFGABCDE'[k=parseInt(4*!!n[1]+c+n,21)%24%17]+'\0#'[45>>k&1]

;[1, 0].forEach(c => {
  [ 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B', 'C', 'C#', 'D', 'D#' ].forEach(n => {
    console.log(
      (n + '  ').slice(0, 3) +
      ['Bass  ', 'Treble'][c] +
      ' --> ' +
      f(n)(c)
    )
  })
})

How?
The input (n, c) is processed through the following steps:

We first evaluate 4 * !!n[1] + c + n where !!n[1] is true (coerced to 1) if the note contains a #, and false (coerced to 0) otherwise. The expression 4 * !!n[1] + c results in a numeric value which is added in front of the string n.
Implicit step: leading zeros and trailing # are ignored by parseInt(). For instance, "5G#" is actually parsed as "5G".
We convert the new string to a decimal value by parsing it as a base-21 quantity.
We apply modulo 24.
We apply modulo 17.

Below is the summary table for all possible input pairs, along with the expected output. Note that a # must be added to the output if the final result is 0, 2, 3 or 5. Hence the use of the binary mask 101101 (45 in decimal).
 n   | c | (1)   | (2)   | (3) | (4) | (5) | Output
-----+---+-------+-------+-----+-----+-----+-------
"E"  | 1 | "1E"  | "1E"  |  35 |  11 |  11 | "G"
"F"  | 1 | "1F"  | "1F"  |  36 |  12 |  12 | "A"
"F#" | 1 | "5F#" | "5F"  | 120 |   0 |   0 | "A#"
"G"  | 1 | "1G"  | "1G"  |  37 |  13 |  13 | "B"
"G#" | 1 | "5G#" | "5G"  | 121 |   1 |   1 | "C"
"A"  | 1 | "1A"  | "1A"  |  31 |   7 |   7 | "C"
"A#" | 1 | "5A#" | "5A"  | 115 |  19 |   2 | "C#"
"B"  | 1 | "1B"  | "1B"  |  32 |   8 |   8 | "D"
"C"  | 1 | "1C"  | "1C"  |  33 |   9 |   9 | "E"
"C#" | 1 | "5C#" | "5C"  | 117 |  21 |   4 | "F"
"D"  | 1 | "1D"  | "1D"  |  34 |  10 |  10 | "F"
"D#" | 1 | "5D#" | "5D"  | 118 |  22 |   5 | "F#"
-----+---+-------+-------+-----+-----+-----+-------
"E"  | 0 | "0E"  | "E"   |  14 |  14 |  14 | "C"
"F"  | 0 | "0F"  | "F"   |  15 |  15 |  15 | "D"
"F#" | 0 | "4F#" | "4F"  |  99 |   3 |   3 | "D#"
"G"  | 0 | "0G"  | "G"   |  16 |  16 |  16 | "E"
"G#" | 0 | "4G#" | "4G"  | 100 |   4 |   4 | "F"
"A"  | 0 | "0A"  | "A"   |  10 |  10 |  10 | "F"
"A#" | 0 | "4A#" | "4A"  |  94 |  22 |   5 | "F#"
"B"  | 0 | "0B"  | "B"   |  11 |  11 |  11 | "G"
"C"  | 0 | "0C"  | "C"   |  12 |  12 |  12 | "A"
"C#" | 0 | "4C#" | "4C"  |  96 |   0 |   0 | "A#"
"D"  | 0 | "0D"  | "D"   |  13 |  13 |  13 | "B"
"D#" | 0 | "4D#" | "4D"  |  97 |   1 |   1 | "C"

Java 8, 119 bytes
n->b->(b?"C D E F G A B C# F F# A# C":"F G A B C D E F# A# C D# F").split(" ")["A B C D E F G A#C#D#F#G#".indexOf(n)/2]

Explanation:
Try it here.
n->b->         // Method with String and boolean parameters and String return-type
  (b?          //  If it's Treble:
    "C D E F G A B C# F F# A# C"
               //   Use this String
   :           //  Else (it's Bass):
    "F G A B C D E F# A# C D# F")
               //   Use this String
  .split(" ")  //  Split this String by spaces,
   [           //  and then get the item at index:
    "A B C D E F G A#C#D#F#G#".indexOf(n)
               //   Get the index of the String on the left,
    /2]        //   and divide this by 2
               // End of method (implicit / single-line return-statement)

another solution  with 99 bytes: n->b->((char)((n.charAt(0)-(b?0:4))%7+65)+n.substring(1)).replaceAll("B#","C").replaceAll("E#","F")

@NahuelFouilleul Ah nice! I was indeed thinking something with a char-cast and some modulo might be shorter. But since it's a bit too different from my current answer, feel free to post it as a separate answer. You've got my upvote if you do. :)

R, 111 bytes
function(k,C,N=paste0(LETTERS[2:15%/%2],c("","#")))sub("E#","F",sub("B#","C",N[which(k==N[(4:17+6*C)%%14+1])]))

Try it online!
Ungolfed:
function(k,C){
  N=paste0(LETTERS[2:15%/%2],c("","#")) # Generate a vector of the notes, including E# and B#
  M=N[(4:17+6*C)%%14+1])                # Create a copy that's cycled either up 4 or down 4
  P=N[which(k==M)]                      # Look up the input note in the complementary vector
  P=sub("B#","C",P)                     # Replace B# with C
  P=sub("E#","F",P)                     # Replace E# with F
}


text:
Goto the Nth Page
It is common to need to make a page selection interface. It typically looks like this:
prev 1 ... 3 4 [5] 6 7 ... 173 next

Which means there are totally 173 pages, and you are on the 5th page currently.
This challenge requires you take the total number of pages and the current page number as input, and output a string (or an array) to "display" the page selector.
Input
2 positive integers

current page number
count of pages

It is guaranteed that 1 <= current <= total.
Output
Output a string or an array which represent the ui for page selectors.

If output as string, a single space (U+0020) should be used between each pages.
If output as an array, the array should produce same result as the string after convert each item to string and join them with a single space.

The three dots (...) is not optional for array output.

Details

If current == 1, no "prev" will be outputted, otherwise, "prev" comes first.
If current == total, no "next" will be outputted, otherwise, "next" comes last.
The first page (1) and the last page (total) should always be outputted.
The current page, (current - 1) page, (current - 2) page, (current + 1) page, (current + 2) page should be outputted as long as the are in the range of [1..total].
No other pages numbers should be outputted.
Pages outputted should be sorted in ascending order.
Output should not contain duplicate page numbers.
Current page should be highlighted by wrap it in a pair of [].
If there is a gap between any neighbors, three dots (...) should be inserted.

Test Cases
Current Total    Output
1       1        [1]
1       2        [1] 2 next
1       10       [1] 2 3 ... 10 next
3       3        prev 1 2 [3]
3       6        prev 1 2 [3] 4 5 6 next
4       6        prev 1 2 3 [4] 5 6 next
4       7        prev 1 2 3 [4] 5 6 7 next
3       10       prev 1 2 [3] 4 5 ... 10 next
5       10       prev 1 ... 3 4 [5] 6 7 ... 10 next
10      10       prev 1 ... 8 9 [10]
52      173      prev 1 ... 50 51 [52] 53 54 ... 173 next

Rules

This is code-golf, the shortest code wins!

Are trailing spaces ok?

@TomCarpenter No. Output should be as is what described. Although a single trailing new line is acceptable for answers printing to console.

Might be worth adding 4 , 6 as a test case. Similar to the 3, 6 case, but ensures dots are not added to the left side.

Just gonna YOINK some of these for a web project...

Building on @TomCarpenter 's comment a 4,7 test case would be greatly appreciated - would insure that both of the boundary cases that exclude ellipses may be concurrently met

@TaylorScott Both added.

@StanStrum The next challenge is to write an infinite scroller.

JavaScript (ES6), 130 122 121 bytes
Invoke with currying syntax, e.g. f(3)(10).
x=>X=>[x>1&&'prev 1',x>4&&'...',x>3&&x-2,x>2&&x-1,`[${x}]`,(X-=x)>1&&x+1,X>2&&x+2,X>3&&'...',X&&X+x+' next'].filter(_=>_)

f=

x=>X=>[x>1&&'prev 1',x>4&&'...',x>3&&x-2,x>2&&x-1,`[${x}]`,(X-=x)>1&&x+1,X>2&&x+2,X>3&&'...',X&&X+x+' next'].filter(_=>_)

console.log(f(1)(1))
console.log(f(1)(2))
console.log(f(1)(10))
console.log(f(3)(3))
console.log(f(3)(6))
console.log(f(4)(6))
console.log(f(4)(7))
console.log(f(3)(10))
console.log(f(5)(10))
console.log(f(10)(10))
console.log(f(52)(173))

Try it online!
-1 byte (Arnauld): Set X to X-x.

Gotta love those lambdas

You should add +8 ... The .join is not part of your count! I was going crazy trying to figure why your code would work without a join, while my similar code wouldn't. Then I say you just didn't include it in your solution, but did include it in your snippet!

@nl-x Whoops! I forgot to update my snippet. The challenge allows you to output a string or an array; I'd recommend you output as an array.

Retina, 125 113 109 107 bytes
.+
$*
r`1\G
 1$'
¶

O`1+
\b(1+) \1\b
[$1]
 .* (1+ 1+ \[)|(] 1+ 1+) .*
$2 ... $1
^1
prev 1
1$
1 next
1+
$.&

Try it online! Link includes test cases. Saved 12 bytes thanks to @MartinEnder. Explanation:
.+
$*

Convert to unary.
r`1\G
 1$'

Generate all the page numbers in reverse order.
¶

Delete the newline separating the input. (There's also a space there from the page number generation anyway.)
O`1+

Sort the pages back into ascending order. This also sorts the current page, which is now duplicated.
\b(1+) \1\b
[$1]

Unduplicate and wrap []s around the current page.
 .* (1+ 1+ \[)|(] 1+ 1+) .*
$2 ... $1

Add an ellipsis if the current page is at least 5, or if there are at least 4 pages after the current page. (Note trailing space, to avoid including the last page in the ellipsis.)
^1
prev 1

Add the prev if the current page is not 1.
1$
1 next

Add the next if the current page is not the last page.
1+
$.&

Convert back to decimal.

Saved a few bytes: https://tio.run/##LYwxCsJAEEX7f4opRt3dwJCfoJaWlhaWSSQWKWxCCEE8mQfwYutEhHnD/Dfw52F5jPe8CddeshXQhLlne4ZQd7j0wgKBRfy8JVg6xZbQqlF2EEvBv@u0TfRopkTo/i5aEijdCm7ENA9PIaigjMNrgfeqbXPmaqVyWKKW2jk4HvbrYvk7K@Gx/gI (one of which required changing the input format to linefeed separation).

@MartinEnder Thanks, I particularly like that trailing ellipsis golf, although I think I can shave off another three four bytes.

6502 machine code (C64), 160 bytes
00 C0 20 9B B7 86 FB CA F0 01 CA 86 FD 20 9B B7 86 FC A6 FB E8 E4 FC B0 01 E8
86 FE A2 01 E4 FB F0 1A A9 91 A0 C0 20 1E AB A2 02 E4 FD B0 0D A9 2E 20 D2 FF
CA 10 FA 20 3F AB A6 FD 86 9E E4 FB D0 05 A9 5B 20 D2 FF A9 00 20 CD BD A6 9E
E4 FB D0 05 A9 5D 20 D2 FF 20 3F AB A6 9E E4 FC F0 25 E4 FE F0 05 E8 86 9E D0
D5 E8 E4 FC F0 0D A2 02 A9 2E 20 D2 FF CA 10 FA 20 3F AB A6 FC A9 00 20 CD BD
20 3F AB A6 FC E4 FB F0 07 A9 99 A0 C0 20 1E AB 60 50 52 45 56 20 31 20 00 4E
45 58 54 00

Online demo -- Usage: sys49152,[current],[total], e.g. sys49152,5,173.
The numbers must be in the range [1..255] with current <= total. As this wasn't specified otherwise, this is the "natural" unsigned integer range on an 8bit processor.

Explanation as commented disassembly listing:
         00 C0       .WORD $C000        ; load address
.C:c000  20 9B B7    JSR $B79B          ; read 8bit integer
.C:c003  86 FB       STX $FB            ; store current page
.C:c005  CA          DEX                ; calculate lower start for ...
.C:c006  F0 01       BEQ .stl
.C:c008  CA          DEX
.C:c009   .stl:
.C:c009  86 FD       STX $FD            ; ... range and store
.C:c00b  20 9B B7    JSR $B79B          ; read 8bit integer
.C:c00e  86 FC       STX $FC            ; store total pages
.C:c010  A6 FB       LDX $FB            ; load current page
.C:c012  E8          INX                ; calculate upper end for ...
.C:c013  E4 FC       CPX $FC
.C:c015  B0 01       BCS .stu
.C:c017  E8          INX
.C:c018   .stu:
.C:c018  86 FE       STX $FE            ; ... range and store
.C:c01a  A2 01       LDX #$01           ; check whether first page is current
.C:c01c  E4 FB       CPX $FB
.C:c01e  F0 1A       BEQ .sequence      ; then directly to sequence
.C:c020  A9 91       LDA #<.prev        ; output string for ...
.C:c022  A0 C0       LDY #>.prev
.C:c024  20 1E AB    JSR $AB1E          ; ... "prev 1 "
.C:c027  A2 02       LDX #$02           ; check whether page 2 is in range ...
.C:c029  E4 FD       CPX $FD
.C:c02b  B0 0D       BCS .sequence      ; ... then directly to sequence
.C:c02d  A9 2E       LDA #$2E           ; load character '.'
.C:c02f   .ellip1:
.C:c02f  20 D2 FF    JSR $FFD2          ; output ...
.C:c032  CA          DEX
.C:c033  10 FA       BPL .ellip1        ; ... 3 times
.C:c035  20 3F AB    JSR $AB3F          ; output space
.C:c038  A6 FD       LDX $FD            ; load lower start for range
.C:c03a   .sequence:
.C:c03a  86 9E       STX $9E            ; store to temporary
.C:c03c   .seqloop:
.C:c03c  E4 FB       CPX $FB            ; compare with current
.C:c03e  D0 05       BNE .notcurrent1   ; yes -> output '['
.C:c040  A9 5B       LDA #$5B
.C:c042  20 D2 FF    JSR $FFD2
.C:c045   .notcurrent1:
.C:c045  A9 00       LDA #$00
.C:c047  20 CD BD    JSR $BDCD          ; output number
.C:c04a  A6 9E       LDX $9E            ; compare with current
.C:c04c  E4 FB       CPX $FB
.C:c04e  D0 05       BNE .notcurrent2   ; yes -> output ']'
.C:c050  A9 5D       LDA #$5D
.C:c052  20 D2 FF    JSR $FFD2
.C:c055   .notcurrent2:
.C:c055  20 3F AB    JSR $AB3F          ; output space
.C:c058  A6 9E       LDX $9E
.C:c05a  E4 FC       CPX $FC            ; compare position with last page
.C:c05c  F0 25       BEQ .printnext     ; if eq jump to part printing "next"
.C:c05e  E4 FE       CPX $FE            ; compare position to upper end of range
.C:c060  F0 05       BEQ .printellip2   ; if eq jump to part printing "..."
.C:c062  E8          INX
.C:c063  86 9E       STX $9E            ; next number
.C:c065  D0 D5       BNE .seqloop       ; and repeat loop for sequence
.C:c067   .printellip2:
.C:c067  E8          INX
.C:c068  E4 FC       CPX $FC            ; compare next number with last page
.C:c06a  F0 0D       BEQ .printlast     ; if eq jump to part printing page num
.C:c06c  A2 02       LDX #$02
.C:c06e  A9 2E       LDA #$2E           ; load character '.'
.C:c070   .ellip2:
.C:c070  20 D2 FF    JSR $FFD2          ; output ...
.C:c073  CA          DEX
.C:c074  10 FA       BPL .ellip2        ; ... 3 times
.C:c076  20 3F AB    JSR $AB3F          ; output space
.C:c079   .printlast:
.C:c079  A6 FC       LDX $FC            ; output last page number
.C:c07b  A9 00       LDA #$00
.C:c07d  20 CD BD    JSR $BDCD
.C:c080  20 3F AB    JSR $AB3F          ; output space
.C:c083   .printnext:
.C:c083  A6 FC       LDX $FC            ; compare current page with last page
.C:c085  E4 FB       CPX $FB
.C:c087  F0 07       BEQ .done          ; if eq nothing else to do
.C:c089  A9 99       LDA #<.next        ; output string for ...
.C:c08b  A0 C0       LDY #>.next
.C:c08d  20 1E AB    JSR $AB1E          ; "next"
.C:c090   .done:
.C:c090  60          RTS
.C:c091   .prev:
.C:c091  50 52 45 56 .BYTE "prev"
.C:c095  20 31 20 00 .BYTE " 1 ", $00
.C:c099   .next:
.C:c099  4E 45 58 54 .BYTE "next"
.C:c09d  00          .BYTE $00

R, 214 bytes 168 bytes
function(c,m,`~`=function(x,y)if(x)cat(y)){o=-2:2+c
o=o[o>0&o<=m]
o[o==c]=paste0('[',c,']')
c>1~'prev '
c>3~'1 '
c>4~' ... '
T~o
c+3<m~' ...'
c+2<m~c('',m)
c<m~' next'}

Try it online!
Thanks to @user2390246 for some great golfing tips

197 bytes

186 bytes with a reversal of logic. Doesn't really feel like a distinct premise.

175 bytes golfing down @CriminallyVulgar's logic.

165 bytes with further golfing. Also doesn't use the function c(), which gets rid of the horrible confusion with the object called c.

Actually, we can save an extra 2 bytes in a really bizarre way

Back up to 171 bytes correcting an error that appears in several of the commented versions!

@user2390246 redefining ~ is inspired!! but you missed one use, T~o instead of cat(o), so back to 168 bytes

@Giuseppe Good spot! I got the idea here and had been itching for a good place to use it...

Another little improvement for 164 bytes. Sorry for completely hijacking this, I got a bit carried away!

@user2390246 Your latest example doesn't work for f(1,1) or f(1,2) (as examples).  f(1,1) doesn't print anything and f(1,2) includes a -1

@Mark Good point! Scratch that last one.

Wolfram Language (Mathematica), 131 114 109 bytes
Range@#2/.{#->"["<>(t=ToString)@#<>"]",1->"prev 1",#2->t@#2<>" next",#-3|#+3:>"...",x_/;Abs[x-#]>2:>Nothing}&

Try it online!
How it works
Lots of replacing. Starting with a list of all pages, replace, in order:

#->"["<>(t=ToString)@#<>"]": the current page with a bracketed string,
1->"prev 1": page 1 with the string prev 1,
#2->t@#2<>" next": the last page with the string (number) next, with
#-3|#+3:>"...": page current-3 and page current+3 with the string "...",
x_/;Abs[x-#]>2:>Nothing: all other (integer) pages below current-2 or above current+2 with nothing. (Yes, Nothing is a built-in.)

APL (Dyalog), 83 82 bytes
Anonymous infix function taking current as left argument and total as right argument.
{('prev '/⍨⍺>1),('x+'⎕R'...'⍕∊(⊂1⌽'][',⍕)@⍺⊢'x'@(~∊∘(1,⍵,⍺+3-⍳5))⍳⍵),' next'/⍨⍺<⍵}

Try it online!
{…} explicit lambda where ⍺ and ⍵ represent the left and right arguments:
 ⍺<⍵ is current smaller than total?
 ' next'/⍨ if so (lit. use that to replicate) the text
 (…), prepend the following:
  ⍳⍵ ɩntegers 1 through total
  'x'@(…) replace with an x at the positions where the items are…
   ~ not
   ∊ members of
   1 one
   , followed by
   ⍵ the total
   , followed by
    ⍳5 the first five ɩntegers ([1,2,3,4,5])
    3- subtracted from three ([2,1,0,-1,-2])
    ⍺+ added to the current ([⍺+2,⍺+1,⍺,⍺-1,⍺-2])
   ⊢ yield that (serves to separate ⍺ from 'x')
   (…) apply the following tacit function at the current position:
    ⍕ format (stringify)
    '][', prepend the text`
    1⌽ rotate one step leftward (moves the ] to the end)
    ⊂ enclose (so that it is a scalar which will fit in the single indicated position)
   ∊ ϵnlist (flatten – because we made it nested when we inserted brackets)
   ⍕ format (stringify – 1 space separating numbers from each other and from x runs)
  'x+'⎕R'...' PCRE Replace x runs with three periods
 (…), prepend the following:
  ⍺>1 is current larger than 1?
  'prev '/⍨ if so (lit. use that to replicate) the text

Funky, 218 210 bytes
Saved some bytes, some of which thanks to tsh
p=>m=>{t={}a=t::push b=t::pop fori=p-2i<p+3i++a(i)t[2]="[%i]"%p whilet[0]<1b(0)whilet[n=-1+#t]>m b(n)ifp>4a(0,"...")ifp>3a(0,1)ifp>1a(0,"prev")ifp<m-3a("...")ifp<m-2a(m)ifp<m a("next")t::reduce((a,b)=>a+" "+b)}

Try it online!

I don't know Funky, but it seems that i<=p+2 can be golfed to i<p+3,and t[2]="["+t[2]+"]" may be t[2]="["+p+"]"?

Python 2, 135 bytes
lambda c,t:re.sub('  +',' ... ','prev '*(c>1)+' '.join(`[x,[x]][x==c]`*(x%t<2or-3<x-c<3)for x in range(1,t+1))+' next'*(c<t))
import re

Try it online!
First we create a string like prev 1  3 4 [5] 6 7   10 next, which has “gaps” caused by erasing some numbers but not their delimiting spaces. Then we replace any run of 2+ spaces by ... using a regex.

You can flip (-3<x-c<3or x%t<2) to (x%t<2or-3<x-c<3) for -1, both arguments to the or operator will return a boolean value.

Python 2, 136 130 bytes
lambda p,n:[i for i,j in zip(['prev',1,'...',p-2,p-1,[p],p+1,p+2,'...',n,'next'],[1,3,4,2,1,.1,-n,1-n,3-n,2-n,-n])if p*cmp(j,0)>j]

Try it online!

If output as an array, the array should produce same result as the string after convert each item to string and join them with a single space.

Try it online! in prettified form, where you can see the footer translates quite literally to "convert each to string, join on spaces".
This is an alternative to Lynn's approach.

Save a byte with i or'...' and zeros (like this)

Octave, 169 196 190 181 175 169 166 bytes
@(n,m)(r=[(n>1)*'prev ' (g=n>4)*'1 ... ' (s=@sprintf)(f='%d ',max(n-3+g,1):n-1) s('[%d]',n) 32*(q=n<m) s(f,n+1:min(n+3-(l=n<m-3),m)) l*['... ' s(f,m)] q*'next'])(r>0)

Try it online!
I'll add an explanation later on.
Hmm, seems there were some issues with the output format. These have now been resolved - all outputs are correct. But alas it cost 27 bytes. Managed to claw all of those back though with a bit of fat trimming.

Save 6 bytes by using * instead of .* - thanks @StewieGriffin
Save 9 bytes using sprintf instead of num2str as I already had that handle in s.
Save 6 bytes by pulling [] into the sprint call.
Save 6 bytes by finding a way to reduce the number of comparisons.
Save 3 bytes by removing need for strtrim() without causing trailing space.

There is 1 more space after number 54 in your output.

@tsh fixed now. I've added all test cases to the TIO output.

Java (OpenJDK 8), 218 179 177 167 166 bytes
c->t->{String p,e="... ",x="["+c+"] ";int i=c-2;for(p=c>1?"prev 1 "+(c>4?e:""):x;i<c+3;i++)p+=i>1&i<t?i==c?x:i+" ":"";return p+(i<t-1?e:"")+(c<t?t+" next":t>1?x:"");}

Try it online!

Nice answer, shorter than mine! You can golf five bytes by putting a space already after "["+c+"] ";: 172 bytes

Oh, and one more byte by putting the last p+= before the for-loop inside the for-loop declaration: 171 bytes

Java 8, 201 200 197 bytes
t->n->(n<2?"[1] ":"prev 1 ")+(n>4?"... "+(n-2)+" "+~-n+" ["+n+"] ":n>3?"2 3 [4] ":n>2?"2 [3] ":n>1?"[2] ":"")+(n<t?(n>t-2?"":n>t-3?t-1+" ":n>t-4?(t-2)+" "+~-t+" ":++n+" "+-~n+" ... ")+t+" next":"")

Explanation:
Try it here.
t->n->             // Method with two integer parameters and String return-type
  (n<2?            //  If the current page is 1:
    "[1] "         //   Start with literal "[1] "
   :               //  Else:
    "prev 1 ")     //   Start with literal "prev 1"
  +(n>4?           //  +If the current page is larger than 4:
     "... "        //    Append literal "... "
     +(n-2)+" "    //    + the current page minus 2, and a space
     ~-n           //    + the current page minus 1, and a space
     +" ["+n+"] "  //    + "[current_page]" and a space
    :n>3?          //   Else-if the current page is 4:
     "2 3 [4] "    //    Append literal "2 3 [4] "
    :n>2?          //   Else-if the current page is 3:
     "2 [3] "      //    Append literal "2 [3] "
    :n>1?          //   Else-if the current page is 2:
     "[2] "        //    Append literal "[2] "
    :              //   Else (the current page is 1):
     "")           //    Append nothing
  +(n<t?           //  +If the current page and total amount of pages are not the same:
     (n>t-2?       //    If the current page is larger than the total minus 2:
       ""          //     Append nothing
      :n>t-3?      //    Else-if the current page is larger than the total minus 3:
       t-1+" "     //     Append the total minus 1, and a space
      :n>t-4?      //    Else-if the current page is larger than the total minus 4:
       (t-2)+" "   //     Append the total minus 2, and a space
       +~-t+" "    //     + the total minus 1, and a space
      :            //    Else:
       ++n+" "     //     Append the current page plus 1, and a space
       +-~n+       //     + the current page plus 2, and a space
       " ... ")    //     + literal "... "
     +t            //    + the total itself
     +" next")     //    + literal " next"
    :              //   Else (current page and total amount of pages are the same):
     "")           //    Append nothing
                   // End of method (implicit / single-line return-statement)

Jelly, 59 bytes
+2Rṫ-4>Ðḟ⁹1;;QµI’a3R”.ṁ⁸żẎ
Ị¬;n“¢©ỵY“¡&ç»ẋ"W€jçLÐfKṣ⁸j⁸WŒṘ¤

A full program* printing the result to STDOUT. Takes arguments current and total in that order.
Try it online! or see the test-suite.
How?
+2Rṫ-4>Ðḟ⁹1;;QµI’a3R”.ṁ⁸żẎ - Link 1, numbers and ellipses: current, total
                           -                                   e.g. 52, 173
 2                         - literal two                            2
+                          - add to current                         54
  R                        - range                                  [1,2,3,...,53,54]
    -4                     - literal minus four                     -4
   ṫ                       - tail from index (i.e. right five)      [50,51,52,53,54]
         ⁹                 - chain's right argument, total          173
       Ðḟ                  - filter discard if:
      >                    -  greater than?                         [50,51,52,53,54]
          1                - literal one                            1
           ;               - concatenate                            [1,50,51,52,53,54]
            ;              - concatenate (implicit right = total)   [1,50,51,52,53,54,173]
             Q             - unique (remove excess 1 and/or total)  [1,50,51,52,53,54,173]
              µ            - new monadic chain, call that X
               I           - incremental differences                [49,1,1,1,1,119]
                ’          - decrement (vectorises)                 [48,0,0,0,0,118]
                  3        - literal three                          3
                 a         - logical and (vectorises)               [3,0,0,0,0,3]
                   R       - range (vectorises)                     [[1,2,3],[],[],[],[],[1,2,3]]
                    ”.     - literal '.' character                  '.'
                      ṁ    - mould like that                        [['.','.','.'],[],[],[],[],['.','.','.']]
                       ⁸   - chain's left argument, X               [1,50,51,52,53,54,173]
                        ż  - zip with that                          [[1,['.', '.', '.']],[50,[]],[51,[]],[52,[]],[53,[]],[54,['.','.','.']],[173]]
                         Ẏ - tighten                                [1,['.', '.', '.'],50,[],51,[],52,[],53,[],54,['.','.','.'],173]

Ị¬;n“¢©ỵY“¡&ç»ẋ"W€jçLÐfKṣ⁸j⁸WŒṘ¤ - Main link: current, total   e.g. 52, 173
Ị                                - insignificant? (abs(current)<=1)  0
 ¬                               - logical not                       1
   n                             - not equal (current != total)      1
  ;                              - concatenate                       [1,1]
    “¢©ỵY“¡&ç»                   - list of compressed strings        [['p','r','e','v'], ['n','e','x','t']]
               "                 - zip with:
              ẋ                  -   repeat (zeros -> empty lists)   [['p','r','e','v'], ['n','e','x','t']]
                W€               - wrap €ach (prep for the join)     [[['p','r','e','v']], [['n','e','x','t']]]
                   ç             - call last link (1) as a dyad      [1,['.', '.', '.'],50,[],51,[],52,[],53,[],54,['.','.','.'],173]
                  j              - join                              [['p','r','e','v'],1,['.','.','.'],50,[],51,[],52,[],53,[],54,['.','.','.'],173,['n','e','x','t']]
                     Ðf          - filter keep if:
                    L            -   length (removes empty lists)    [['p','r','e','v'],1,['.','.','.'],50,51,52,53,54,['.','.','.'],173,['n','e','x','t']]
                       K         - join with spaces                  ['p','r','e','v',' ',1,' ','.','.','.',' ',50,' ',51,' ',52,' ',53,' ',54,' ','.','.','.',' ',173,' ','n','e','x','t']
                         ⁸       - chain's left argument, current    52
                        ṣ        - split at that                     [['p','r','e','v',' ',1,' ','.','.','.',' ',50,' ',51,' ',],[,' ',53,' ',54,' ','.','.','.',' ',173,' ','n','e','x','t']]
                               ¤ - nilad followed by link(s) as a nilad:
                           ⁸     -   chain's left argument, current  52
                            W    -   wrap                            [52]
                             ŒṘ  -   Python string representation    ['[','5','2',']']
                          j      - join                              ['p','r','e','v',' ',1,' ','.','.','.',' ',50,' ',51,' ','[','5','2',']',' ',53,' ',54,' ','.','.','.',' ',173,' ','n','e','x','t']
                                 - implicit print                    prev 1 ... 50 51 [52] 53 54 ... 173 next

* As a dyadic link taking current on the left and total on the right this returns a list with a mix of characters and integers; this list includes the spaces. The byte K cannot simply be removed to adhere to the spec however, since the result would then have the bracketed current as separate characters (like [...'[','5','2',']'...]) so the "convert each item to string and join them with a single space" would fail to produce the desired result)

C++ - 247 bytes
#include <iostream>
#define c std::cout<<
#define N (a-i<3?i-a<2?1:b-i:a-i-2)
void s(int a,int b){if(a>1)c"prev ";for(int i=1;i<=b&&N!=0;i+=N)c(i==1?"":" ")<<(a==i?"[":"")<<i<<(a==i?"]":"")<<(N>1?" ...":"");if(a<b-2)c" "<<b;if(a<b)c" next";c"\n";}

Try it online!

Note that "No other pages numbers should be outputted."

Ohh sorry I missed that rule. I'll correct it soon.

Also, the link is broken.

@Appleguy: look at this -- your code to be measured goes in the "code" field on TIO. Then you can easily create your whole post from there.

Python 2, 178 170 bytes
x,y=input()
e="... ",""
o=("Prev 1 ","[1] ")[y<2]+e[y<5]
for z in range(2,x):o+=("",(`z`,`[z]`)[z==y]+" ")[y-3<z<y+3]
print o+("",e[x-y<4]+(`x`+" Next",`[x]`)[y==x])[x>1]

Try it online!
Second attempt after reading the rules more carefully.
-8 by losing some unneeded brackets.

Python 2,  128  124 bytes
-4 bytes thanks to Jonathan Allan!
lambda c,l:["prev"]*(c>1)+[range(1,c),[1,"...",c-2,c-1]][c>4]+[[c]]+[range(c+1,l+1),[c+1,c+2,"...",l]][l-c>4]+["next"]*(c<l)

Try it online!
Output as a list, but tio link includes pretty-print.

while ~0: is an odd thing to use when while 1: works fine.

@JonathanAllan I know :P - But it still works :D

-4 bytes moving the [[c]] out (like this) EDIT - so does while 2*3*4*5*6*7*8*9*'I know a song that will get on your nerves, get on your nerves, get on your nerves;\n': :p

@JonathanAllan Yes thanks, I was just playing around with it because I felt it's redundant.

C# (.NET Core), 195 192 bytes
Saved 3 bytes thanks to Kevin Cruijssen.
c=>t=>{var n=c>1?"prev ":"";n+=c>4?"1 ... ":c<2?"[1] ":"1 ";if(t>1){for(int i=c-3;i++<c+2;)if(i>1&i<t)n+=i==c?$"[{i}] ":i+" ";n+=c<t-4?"... "+t:c==t?$"[{t}]":t+"";n+=c<t?" next":"";}return n;}

Try it online!

You can save 2 bytes by removing the brackets of the for-loop. And 1 more by using a currying input c=>t=>. Try it here: 192 bytes

CJam, 74
q~\:A\:B]3e*[1T4A3+1A].>["prev"1'.3*_B"next"]:a.*3/5,A2-f+B,2>&*:+_A#Aa`tp

Outputs as array. Try it online
Replace the final p with S* to output as string.
Explanation:
q~          read and evaluate the input (pushing 2 numbers on the stack)
\:A\:B      store the numbers in A and B, keeping them in the same order
]3e*        wrap in array, then repeat each number 3 times - [A A A B B B]
[1T4        make an array containing 1, 0 (T=0 by default), 4,
A3+1A]      then A+3, 1, and A
.>          compare the 2 arrays element by element - [A>1 A>0 A>4 B>A+3 B>1 B>A]
             (each result is 1 or 0)
["prev"1    make an array containing "prev", 1,
'.3*_       "..." twice ("..." = '.' repeated 3 times),
B"next"]    then B and "next"
:a          wrap each of its elements in an array - [["prev"][1]["..."]…]
.*          repeat each of these arrays according to the previous array
             e.g. ["prev"] is repeated A>1 times - ["prev"] if A>1, else []
             [1] is repeated A>0 times (always 1), etc.
             obtaining an array of 6 arrays, some of which may be empty
3/          split into 2 arrays of 3 arrays each (between the "..." parts)
5,A2-f+     make an array [0 1 2 3 4] then add A-2 to each element
B,2>&       intersect with the array [2 3 … B-1] (these are the middle numbers)
*           join the 2 previous arrays by adding these numbers between them
:+          concatenate all these arrays and numbers together
             obtaining an array containing only numbers and strings
_A#         duplicate the array then find the position of A in it
Aa`         generate the "[A]" string (with the actual number for A)
             by wrapping A in an array and getting its string representation
t           put it in the array at A's position
p           print the array's string representation

PHP (<7.2), 157 150 bytes
taking the details literally turned out to be the shortest approach:
[,$k,$n]=$argv;for($k>1&&print"prev ";$i++<$n;)$g=in_array($i,range($k-2,$k+2)+[5=>1,$n])?!print$i-$k?"$i ":"[$i] ":$g||print"... ";$k<$n&&print next;

Run with php -nr '<code>' <curpage> <numpages> or try it online.

Haskell, 145 129 bytes
s x=show x
a#t=["prev 1"|a>1]++["..."|a>4]++map s[max 4a-2..a-1]++s[a]:map s[a+1..min(a+3)t-1]++["..."|t-a>3]++[s t++" next"|a<t]

Try it online!
Edit: @Ørjan Johansen saved 16 bytes. Thanks!

(1) You can drop the unwords$, array output is permitted. (2) s x=show x; ... s[a] is shorter, after which it can be merged with the next one with : and map, and then id=<< becomes longer than just using ++s. (3) max 4a-2 and min(a+3)t-1 are shorter. Try it online!

Golf Script - 104 characters
~\:a;:b;1a<'prev '*3a<'1 ... '*[5,{a 2-+}/]{.0>\b)<&},{.a={'['\']'}*' '}/;b a-:c 2>' ... 'b+*0c<' next'*

Ungolfed
~\:a;:b;       # a = 1st arg, b = 2nd arg
1a<'prev '*    # if a > 1: print 'prev '
3a<'1 ... '*   # if a > 3: print '1 ... '
[5,{a 2-+}/]   # creates an array [a-2 a-1 a a+1 a+2]
{.0>\b)<&},    # keeps only elements >0 and <=b
{
  .a={'['\']'}*      # puts '[' ']' around the element equal to a
  ' '}/;             # prints each element with a leading space
b a-:c 2>' ... 'b+*  # if b-a > 2: print ' ... ' + b
0c<' next'*          # if b-a > 0: print ' next'

You can remove all newlines.

Yes, thank you. I was on mobile, it was a little unconfortable to cram all the code.

Perl 5, 113+1 (-p) 109 +3(-pal) bytes
$_=join$",1..<>;s/\b@F\b/[$&]/;s/^1/prev 1/;s/\d$/$& next/;s/(^|\] )\w+ \w+ \K[\w ]*(?= \w+ \w+( \[|$))/.../g

Try it online

Nice use of $` and $'! Had a little play with this, but wasn't able to get it down much, but by using <> instead of the regex and using -a to keep a reference to $_, I was able to drop to 111: Try it online! (-l added for readability)

Fine, I didn't think to @F

I've been enjoying the use of "@F" for singular inputs, it's a nice workaround! The -l isn't needed in byte count though, only for running all tests at once :). I didn't say, but your ellipsis validation is very nice!

indeed i've just seen one of my first posts could be improved

IBM/Lotus Notes Formula, 217 211 Bytes
-2 with thanks to @KevinCruijssen
-4 by using variables for the @Text values
o:=@If(a=1;"[1]";"Prev 1 ")+@If(a>4;"... ";"");@For(x:=2;x<b;x:=x+1;T:=@Text(x);o:=o+@If(x>a-3&x<a+3;@If(a=x;"["+T+"]";T)+" ";""));Z:=@Text(b);o:=o+@If(b>1;@If(b-a>3;"... ";"")+@If(a=b;"["+Z+"]";Z+" Next");"");o

Basically a port of my Python 2 answer just for the fun of trying to remember how to use Formula.
There's no TIO for Formula so here's a screenshot of some of the test cases:

Is there a reason why spaces are required at x>a-3 & x<a+3 in Lotus Notes Formula? Is &x reserved for something, or is there no reason in particular why the spaces on both sides are mandatory? I never programmed in this language btw, was just curious. :)

@KevinCruijssen - To be honest I don't know. Never thought of trying it without. Too used to writing readable code :-). I'll check tomorrow when I get to a machine with Notes installed and let you know.

@KevinCruijssen - you were right!

Hehe, glad I could help. :) +1 from me, and I see you've golfed some more by creating a variable for @Text. When I saw it was used two times two yesterday it crossed my mind that might be possible.

Ruby, 127 bytes
I'm not particularly happy with this, especially the prev/next logic.
->c,t{"prev #{(1..t).chunk{|n|n<2||n==t||n>c-3&&n<c+3}.map{|t,a|t ?a:?.*3}*" "} next".sub(/(prev )?\b(#{c})\b( next)?/,'[\2]')}

Try it online!
Ungolfed
->c,t{
  "prev #{
    (1..t)
    .chunk {|n| n < 2 || n == t || n > c - 3 && n < c + 3 }
    .map {|t,a| t ? a : ?. * 3 } * " "
  } next"
  .sub(/(prev )?\b(#{ c })\b( next)?/, '[\2]')
}

Excel VBA, 202 201  Bytes
Anonymous VBE immediate window function that takes input from range A1:A2 and outputs to the VBE immediate window.
For i=[Max(A1-2,1)]To[Min(A1+2,A2)]:s=s &IIf([A1]=i,"[" &i &"]",i)&" ":Next:?[If(A1=1,"","prev "&If(A1>3,1&If(A1>4," ... "," "),""))]s[If(A1<A2,If(A1-A2<-3,"... ","")&If(A1-A2<-2,A2&" ","")&"next","")]

Subroutine Version
Included for readablity
Public Sub PageSelect(Optional ByVal Current As Long = -1, _
                      Optional ByVal Total   As Long = -1)

    Call Sheet1.Activate

    Let [A1] = IIf(Current = -1, [A1], Current)
    Let [A2] = IIf(Total   = -1, [A1], Total)

    Dim s As String
    Let s = ""

    For i = [Max(A1-2,1)] To [Min(A1+2,A2)] Step 1
        Let s = s & IIf([A1] = i, "[" & i & "]", i) & " "
    Next
    Debug.Print [If(A1=1,"","prev "&If(A1>3,1&If(A1>4," ... "," "),""))]; _
                s; _
                [If(A1<A2,If(A1-A2<-3,"... ","")&If(A1-A2<-2,A2&" ","")&"next","")]
End Sub

PHP (Browser), 267 Bytes
<?php parse_str($_SERVER['QUERY_STRING']);$c=$a!=1?$a>3?$a>4?'prev 1 . . . ':'prev 1 ':'prev ':'[1] ';$d=$a<$b-2?$a+3:$b;for($i=$a<=2?$a==1?$i=2:$i=$a-1:$i=$a-2;$i<$d;$i++)$c.=$a==$i?"[$i] ":"$i ";if($a<$b-2)$c.=" . . . $b next";else $c.=$a==$b?"[$b]":"$b next";echo $c?>

Try it online!
Definitely not as small as it could have been, and as was demonstrated above, using PHP in command line can be much smaller. The input is through GET requests, a is the selected number, b is the limit. This looks like foo.bar.com/index.php?a=2&b=12
Ungolfed
<?
    parse_str($_SERVER['QUERY_STRING']);
    $c=$a!=1?$a>3?$a>4?'prev 1 . . . ':'prev 1 ':'prev ':'[1] ';
    $d=$a<$b-2?$a+3:$b;
    for($i=$a<=2?$a==1?$i=2:$i=$a-1:$i=$a-2;$i<$d;$i++)
        $c.=$a==$i?"[$i] ":"$i ";

    if($a<$b-2)$c.=" . . . $b next";else
    $c.=$a==$b?"[$b]":"$b next";
    echo $c
?>

I am pretty sure my ternary operators can be improved, feel free to try.

Making my answer work in a browser would cost one or two bytes: [,$k,$n]=$argv;  --> <?[$k,$n]=$_GET; if I insist on current page being the first argument and number of pages the second; <?extract($_GET); if I want to use named arguments.

fails for a=b-3; replace $a<$b-2 with $a<$b-3 to fix.

golfed: <?=($a=$_GET['a'])>1?'prev 1 ':'[1] ',$a>4?'... ':'';for($i=$a>4?$a-3:1;$i<$a+3&++$i<$b=$_GET['b'];)echo$a-$i?"$i ":"[$i] ";echo$a<$b-3?"... ":"",$a<$b?"$b next":"[$b]"; (169 bytes)

C - 173 Bytes
#define p c&&printf(
c;main(t){scanf("%u%u",&c,&t);c&&t/c?1-p"prev 1"),3<p" ... %d",c-2),2<p" %d",c-1),1|p" [%d] ",c),t>1+p"%d ",c+1),t>2+p"%d ... ",c+2),t-p"%d next",t):0;}

Thanks to @ceilingcat for -45 bytes.
Ungolfed (original version)
#define p printf
c;

main(t)
{
    scanf("%u%u", &c, &t);

    if(1 <= c && c <= t)
    {
        p(c != 1 ?"prev 1" :"");

        p(c - 2 > 1 ?" ... %d" :"", c - 2);
        p(c - 1 > 1 ?" %d" :"", c - 1);

        p(" [%d] ", c);

        p(c + 1 < t ?"%d " :"", c + 1);
        p(c + 2 < t ?"%d ... " :"", c + 2);

        p(c != t ?"%d next" :"", t);
    }
}

PowerShell, 237 bytes
param($a,$n)('prev 1','[1]')[$n-lt2]+" ... $($n-2) $($n-1) [$n]"*($n-gt4)+" 2 3 [4]"*($n-eq4)+" 2 [3]"*($n-eq3)+" [2]"*($n-eq2)+" $($n+1) $($n+2) ..."*($n-lt$a-3)+" $($n+1) $($n+2)"*($n-eq$a-3)+" $($n+1)"*($n-eq$a-2)+" $a next"*($n-ne$a)

Try it online!
One gigantic string concatenation with way too many dollar signs. Working on golfing further. Nope, I think this is as short as this approach can go.

Javascript (ES6), 265 263 258 240 239 220 194 193 182 178 bytes
-2 from removing a debug tool
-5 from realizing that I'm using ES6 and can do away with parenthesis sometimes
-18 from removing something from an earlier version that is now obsolete
-1 from doing some sneaky stuff
-19 from removing unnecessary variables
-26 bytes from removing the all too complicated remove falsey values. I'm new to ES6
-1 from using shorter comparisons
-11 from using a recursive function
*-4 from replacing ?...:0 with &&..., and ... ${t} with ...+t
This took way too much of my life, and didn’t give enough upvotes.  but I am so glad the final code is a power of 2 (2^8) I do know there is another JavaScript answer that is about 120 bytes.  but I still love this code
EDIT: i don't know what i was thinking. 265 is not 2^8...
While making this, I managed to break the ungolfed version. God, do I hate ungolfing code.
EDIT 2: now it's looking like the better 121 byte solution
y=(e,i,t="")=>i++<e?y(e,i,t+i+' '):t.slice(0,-1);m=(t,p)=>[p-1&&"prev",p<5?y(p-1,0):"1 ... "+y(p-1,p-3),`[${t}]`,t-p<4?y(t,p):y(p+2,p)+` ... `+t,t-p&&"next"].filter(e=>e).join` `

Explanation:
to come but basically y is range(end, start) and it does some cool stuff like:

show prev if page is 1
show left dots if page > 4
show right dots if total - page < 4
show next if total - page == 0

and stuff like that and just joins it by ' '. I know you don't have to but I like the fact that is semi-conventional. I don't know. Enjoy.
Try it online!
Validate it online!
Here's a 186 185 174 170 byte solution that I don't like: Try it online!

PowerShell, 141 bytes
param($c,$t)($('prev'*($c-ne1)
1
'...'*($c-gt4)
($c-2)..($c+2)-gt1-lt$t
'...'*($t-$c-gt4)
$t
'next'*($t-ne$c))|?{$_}|gu)-replace"^$c$","[$c]"

Try it online!
Less golfed:
param($current,$total)
$uiElements=$(
    'prev'*($current-ne1)
    1
    '...'*($current-gt4)
    ($current-2)..($current+2)-gt1-lt$total
    '...'*($total-$current-gt4)
    $total
    'next'*($total-ne$current)
)
($uiElements|where{$_}|Get-Unique)-replace"^$current$","[$current]"