text:
Mark a UKMT IMC Paper
I did the IMC this year. Did anyone else here do it?
In a UKMT Intermediate Maths Challenge paper, there are twenty-five questions. The first fifteen questions give you five marks if you get them right. For the other ten questions, you get six marks for getting them right. In the last ten questions, you lose marks if you get them wrong! For questions sixteen to twenty, you lose one marks and for the last five questions, you lose two marks. If you leave a question blank, no marks are awarded or deducted. No marks are deducted for getting any of the first fifteen questions wrong. The paper is multiple choice; you can choose any answer out of A, B, C, D and E for each question. There is always just one right answer for each question.
Create a program/function that takes two strings and outputs a score. The first string will be your answers to the paper. If you skip a question, use a space, a null byte or an underscore. Otherwise, use the letter A, B, C, D or E for the answer. You can either have the inputs uppercase or lowercase. The second string will be the correct answers for each question in the paper. Your program/function will then output a score. Make your code short.
Test cases:
DDDDDDDDDDDDDDDDDDDDDDDDD
ABCDEABCDEABCDEABCDEABCDE
15

BDBEACCECEDDBDABBCBDAEBCD
BDBEACCECEDDBDABBCBDAEBCD
135

DBACBDCDBAEDABCDBEECACDC_
DBADBDCDBAEDABCDBEEDACDCA
117

_________________________
DABDABDABDABDABDABDABDABD
0

DBADBDCDBAEDABCD_E__A__C_
DBADBDCDBAEDABCDBEEDACDCA
99

_______________BBBBBBBBBB
AAAAAAAAAAAAAAAAAAAAAAAAA
-15

Should "For questions fifteen to twenty" be "For questions sixteen to twenty"?

Can we use a null byte to represent skipped questions?

And shouldn't the first score be 27-12=15?

@GregMartin Three of the first fifteen were right. 3*5 = 15. One of the next five was right. 6+4(-1) = 2. One of the last five was right. 6+4(-2) = -2. Yes, you're right.

@betseg Go on, then.

@GregMartin Fixed.

Has anyone seen/done the UKMT papers? They are really fun. Check out the puzzles at ukmt.org.uk. I get most of my ideas for challenges from maths questions.

Your test cases should probably include a submission with a negative score.

I've done these papers! Got a few gold certificates, never qualified for a follow on though...

@FourOhFour Did you do it this year? I got 117 -- my best ever score!

@Dennis I thought I'd added one... fixed.

@J843136028 Congratulations on getting onto the Hot Network Questions list!

Related.

@ETHproductions This is different because you don't get all the same marks from each question, so it wouldn't just be a trivial list comprehension or anything.

@wizzwizz4 So is that why I'm getting so much rep?

@J843136028 This year I did the Senior challenge. Never got 117 though, that's a brilliant score :)

@FourOhFour What did you get in the SMC? I really want to do it a year early (I am kicking myself for not doing it this year) next year. I tried this year's paper and I got 106.

@J843136028 - not that good, I ran out of time. I think in the 80s?

@FourOhFour Aw, that's annoying. In last year's challenge, time was up when my pencil was literally one centimetre away from the answer sheet.

C, 88 87 86 81 bytes
c,d;i(char*a,char*b){for(c=d=0;*b;c++,a++)d+=*a^*b++?*a?-c/15-c/20:0:5+c/15;d=d;}

Try it online!

Since ABCDE are all below the point 95, I think you can use *a<95.

Since the question allows taking null byte instead of underscores, -(c/15+c/20)*(*a<95) can become *a?-c/15-c/20:0.

80 bytes

Jelly, 26 23 22 bytes
=s5ị"“HHHQP‘D¤_2Fæ.n⁶¥

Try it online!
How it works
=s5ị"“HHHQP‘D¤_2Fæ.n⁶¥  Main link. Argument: t (answer to test), s (answer sheet)

=                       Test the characters of t and s for equality.
 s5                     Split into chunks of length 5.
             ¤          Combine the two preceding links into a niladic chain.
     “HHHQP‘              Yield the code points, i.e., [72, 72, 72, 81, 80].
            D             Decimal; yield [[7, 2], [7, 2], [7, 2], [8, 1], [8, 0]].
   ị"                   Index zipwith; use the Booleans in each chunk to index into
                        the corresponding pair. Indexing is 1-based and modular, so
                        1 gives the first element and 0 the last.
              _2        Subtract 2 from each result.
                F       Flatten the resulting 5x5 matrix.
                     ¥  Combine the two preceding links into a dyadic chain.
                   n⁶     Test the characters of t for inequality with space.
                 æ.     Take the dot product of the integers to the left and the
                        Booleans to the right.

JavaScript (ES6), 70 68 66 bytes
Saved 2 bytes thanks to Neil
Saved 2 bytes thanks to ETHproductions
Takes applicant answers a and correct answers c in currying syntax (a)(c). Expects skipped questions to be marked with a space.
a=>c=>a.replace(/\S/g,(a,i)=>s+=a==c[j=i>14,i]?5+j:-j^i>19,s=0)&&s

Test cases

let f =

a=>c=>a.replace(/\S/g,(a,i)=>s+=a==c[j=i>14,i]?5+j:-j^i>19,s=0)&&s

console.log(f
  ("DDDDDDDDDDDDDDDDDDDDDDDDD")
  ("ABCDEABCDEABCDEABCDEABCDE")
);
console.log(f
  ("BDBEACCECEDDBDABBCBDAEBCD")
  ("BDBEACCECEDDBDABBCBDAEBCD")
);
console.log(f
  ("DBACBDCDBAEDABCDBEECACDC ")
  ("DBADBDCDBAEDABCDBEEDACDCA")
);
console.log(f
  ("                         ")
  ("DABDABDABDABDABDABDABDABD")
);
console.log(f
  ("DBADBDCDBAEDABCD E  A  C ")
  ("DBADBDCDBAEDABCDBEEDACDCA")
);
console.log(f
  ("               BBBBBBBBBB")
  ("AAAAAAAAAAAAAAAAAAAAAAAAA")
);

If you change the skipped question to a non-word character (e.g. space) then you can use /\w/g to save you two bytes.

I think -j-(i>19) is the same as -j^i>19, though I'm not certain.

@ETHproductions Indeed. This is parsed as (-j)^(i>19) so, yes, this works.

Python 2, 86 85 83 77 bytes
f=lambda t,s,i=24:~i and(i/10*-(14<i<t[i]<'_'),5+i/15)[t[i]==s[i]]+f(t,s,i-1)

Try it online!
How it works
This defines a recursive function f that takes two non-optimal arguments: t (the answers to the test) and s (the answer sheet). When called only with these two arguments, f initializes i to 24, the last index of both t and s.
Every time f is called, it first checks if ~i (the bitwise NOT of i) is truthy/non-zero. Since ~(-1) = 0, this happens once the i reaches the value -1. If i = -1, ~i = 0 is returned, but as i takes values from 24 to 0 (all indices of t and s), the code following and is executed and f returns the result.
While i is non-negative, the following happens. First,
(i/10*-(14<i<t[i]<'_'),5+i/15)

creates a tuple of length 2:

The quotient i/10 is 0 if 0 ≤ i < 10, 1 if 10 ≤ i < 20, and 2 if 20 ≤ i < 25. The chained comparison 14<i<t[i]<'_' returns True if and only if all individual comparisons return True, i.e., if and only if i ≥ 15 (the range of questions with penalty), i is smaller than t[i] (always true since all numbers are smaller than all iterables in Python 2), and t[i] is not an underscore.
If the comparison returns False, the unary - returns 0 and the entire expression evaluates to 0. However, if the comparison returns True, the unary - returns -1, so the entire expression evaluates to 0 if 0 ≤ i < 10, -1 if 10 ≤ i < 20, and -2 if 20 ≤ i < 25; these are the net results for wrong or missing answers for all indices i.
5+i/15 returns 5 + 0 = 5 if 0 ≤ i < 15 and 5 + 1 = 6 if 15 ≤ i < 25. These are the net results for correct answers for all indices i.

Finally, [t[i]==s[i]] selects the first element of the constructed tuple if t[i] and s[i] differ (wrong or missing answer) and the second one if they are equal (correct answer), then adds the return value of f called with decremented i to that result. Once i reaches -1, the final score has been computed and is returned by f.

Jelly, 22 21 bytes
Zm0ṁ135µ;t€⁶E€’;E€ṫ⁹S

Try it online!
I thought @Dennis's answer was probably beatable. And after trying out a huge number of different possibilities and benefitting from an amazing coincidence, I've finally managed it!
This program takes a pair of [student's answers, correct answers] as input, and uses spaces to indicate a missing answer.
Explanation
This program uses some bizarre internal input formats to keep track of what's going on, so we'll take this a step at a time.

Z
This transposes the input, so we'll end up with a list of 25 elements, one for each question; each element is of the form [student's answer, correct answer]. We'll indicate an element of this form with a capital letter; A for question 1, B for question 2, and so on. So the answers are currently being stored as
ABCDEFGHIJKLMNOPQRSTUVWXY

m0
This is a "greater palindrome" operation; we append the reverse of the current value to the value itself, yielding this:
ABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQPONMLKJIHGFEDCBA

ṁ135
The ṁ (mold) operator does a number of things, but in this context, it effectively takes the first 135 elements of the infinite list produced by appending the current value to itself repeatedly. That gives us the following (which I've broken into groups of 50 elements for convenience; this is just a list of 135 pairs internally):
ABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQP

µ;
µ sets the current value as the new default for missing operands. We then immediately see a builtin that's missing an operand; ; appends, but we haven't specified what to append with. As a result, the current value is appended to the value as of the last µ (which is also the current value), giving us the following 270-element current value:
ABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQPABCDEFGHIJKLMNO
PQRSTUVWXYYXWVUTSRQPONMLKJIHGFEDCBAABCDEFGHIJKLMNO
PQRSTUVWXYYXWVUTSRQPONMLKJIHGFEDCBAABCDEFGHIJKLMNO
PQRSTUVWXYYXWVUTSRQP

t€⁶
Remember that all the capital letters above represent pairs of [student's answer, correct answer]. The t€⁶ operation operates on each (€) pair, and deletes (t) spaces (⁶) from either side of the pair (i.e. any space that appears in the pair). So we still have the same convoluted list of 270 questions with many repeats, but they're of the form [correct answer] (student didn't answer) or [student's answer, correct answer] (student did answer).
E€’
The E€’ operation also operates on each (€) element, and, due to the use of E, replaces the element with 1 if all the elements are equal (i.e. the student didn't answer or got the question right), or 0 if not all the elements are equal (i.e. the student answered but got the question wrong). The use of ’ here changes the numbering, meaning that we now use -1 or 0 respectively. I'll use lowercase letters for this new sort of element, which uses -1 for an answer which would be penalised if it were on a penalty-eligible question, or 0 for a missing or correct answer:
abcdefghijklmnopqrstuvwxyyxwvutsrqponmlkjihgfedcba
abcdefghijklmnopqrstuvwxyyxwvutsrqponmlkjihgfedcba
abcdefghijklmnopqrstuvwxyyxwvutsrqpabcdefghijklmno
pqrstuvwxyyxwvutsrqponmlkjihgfedcbaabcdefghijklmno
pqrstuvwxyyxwvutsrqponmlkjihgfedcbaabcdefghijklmno
pqrstuvwxyyxwvutsrqp

;E€
We've seen both E€ and ; before; we're appending something to the current value, and we're using a format of 1 if all the elements are equal, or 0 if some are different (no ’ this time!). There's a missing operand here, so we use the value as of the last µ (i.e. the output of step 3). Back in step 3, we hadn't deleted spaces from the elements, so we'll have 1 for a correct answer, or 0 for an incorrect or missing answer (because a space won't match the correct answer). From now on, I'll use capital letters for this 1=correct, 0=incorrect/missing format, and continue to use lowercase letters for 0=correct/missing, -1=incorrect. The resulting value has 405 elements, and looks like this:
abcdefghijklmnopqrstuvwxyyxwvutsrqponmlkjihgfedcba
abcdefghijklmnopqrstuvwxyyxwvutsrqponmlkjihgfedcba
abcdefghijklmnopqrstuvwxyyxwvutsrqpabcdefghijklmno
pqrstuvwxyyxwvutsrqponmlkjihgfedcbaabcdefghijklmno
pqrstuvwxyyxwvutsrqponmlkjihgfedcbaabcdefghijklmno
pqrstuvwxyyxwvutsrqpABCDEFGHIJKLMNOPQRSTUVWXYYXWVU
TSRQPONMLKJIHGFEDCBAABCDEFGHIJKLMNOPQRSTUVWXYYXWVU
TSRQPONMLKJIHGFEDCBAABCDEFGHIJKLMNOPQRSTUVWXYYXWVU
TSRQP

ṫ⁹
Here comes the amazing coincidence I mentioned earlier. Before talking about this bit of the code, I want to take stock of where we've got to.
Each capital letter represents +1 for a correct answer; the first 15 questions (A through O) appear 5 times each in the string, and the last 10 questions (P through Y) appear 6 times each. That bit isn't really magical; I designed it that way when I chose the number 135 earlier on in the program (which is 5 × 15 + 6 × 10), and the only stroke of luck here is that 5 happens to be an odd number (so it's the last 10 questions that end up appearing the extra times, rather than the first 10). The 15 letters immediately preceding this contain p through t (the -1 penalty questions) once, and u through y (the -2 penalty questions) twice. That also isn't much of a coincidence; because we used m0 earlier, the extra copies of the questions are in the order PQRSTUVWXYYXWVUTSRQP, and the later questions will naturally occur near the middle of that string (so taking the last 15 of the "extra" questions will give fewer repeats to the ones near the edges; and of course, it's not a surprise that the "extra" questions come last).
Because each lowercase letter subtracts 1 from the score for an incorrect, non-missing answer, and each uppercase letter adds 1 to the score for a correct answer, we therefore simply need to take the last 135 + 15 = 150 elements in order to get each sort of element the correct number of times. Jelly's command for getting a substring at the end of a list is ṫ; however, it doesn't specify the number of elements you want, but rather the index of the first element you want. We have 405 elements at this point, and want 150, so we need to start at index (405 - 150 + 1), or 256. In an amazing coincidence, 256 happens to be the number of distinct octets that exist, and thus has a short representation in Jelly (⁹). There was very little I could do in order to make this happen; step 4 added another 135 elements to the start of the list in order to hit the round number, but the fact that it was 135 elements I had to add (a value which was readily available at that point in the program) was really convenient, with basically any other number being completely unhelpful in this situation.
Here's how the internal value looks now:
uvwxyyxwvutsrqpABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQP
ONMLKJIHGFEDCBAABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQP
ONMLKJIHGFEDCBAABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQP

S
Finally, now we've got a list of modifications to the score from questions, all we need to do is sum them using S, and we're done.

Mathematica, 114 bytes
Tr@(m=MapThread)[#/.True->#2/.False->-#3&,{Tr/@Partition[m[Equal,#/."_"->u]/.u==_->0,5],{5,5,5,6,6},{0,0,0,1,2}}]&

Pure function taking an ordered pair of lists of characters and returning an integer. m[Equal,#/."_"->u] returns a list of booleans, except for unevaluated entries of the form u=="B" in places where the answer equaled "_"; then right away, u==_->0 turns those unevaluated entries into 0s. Tr/@Partition[...,5] adds these entries up 5 at a time, resulting in a list like {4False+True, 4False+True, 4False+True, 4False+True, 4False+True} for the first test case or {5True, 5True, 5True, 2True, 2True} for the last test case. Then in each coordinate, True and False are mapped to the appropriate scores, and the results are added together.

Python 2, 93 91 bytes
f=lambda a,b,n=0:a>""and((a[0]==b[0])*(5+n/15)or-(n/15*n/10)*(a[0]<"^"))+f(a[1:],b[1:],n+1)

Try it online!
-2 bytes thanks to @KritixiLithos

Input:

a : Answers of the student as a string, _ for skipped question
b : correct answers
n : the number of the current question 0-based, defaults to 0

You can do a[0]<'^' instead of a[0]!="_" to save bytes

I think a>"" can work instead of a!=""

If your initial check is just ending the recursion when a is empty, can't you just do a and? An empty string is false, otherwise it's true.

@FlipTack this would throw a TypeError as the the last recursive call would return a string

Octave, 61 54 bytes
@(a,b)[a==b,-(a<95&a~=b)]*[(x=1:25>15)+5,(1:25>20)+x]'

Try it online!
Previous answer:
@(a,b)(m=a==b)*(((f=kron(z=[0 0 0:2],z|1)')&1)+5)-(a<95&~m)*f

k, 52 bytes
Function takes 2 strings, format per the test cases
{+/(~x="_")*(+,/'(15 5 5#'0 -1 -2;15 10#'5 6))@'x=y}

Example:
k){+/(~x="_")*(+,/'(15 5 5#'0 -1 -2;15 10#'5 6))@'x=y}["DBADBDCDBAEDABCD_E__A__C_";"DBADBDCDBAEDABCDBEEDACDCA"]
99

JavaScript (ES6), 105 103 101 94 89 88 85 84 78 77 bytes
My first solution in ES6, maybe even first in Javascript O.o
f=(s,a,i=24)=>i+1&&(s[i]>'Z'?0:s[i]==a[i]?5+(i>14):~(i>19)*(i>14))+f(s,a,i-1)

s is the submitted solution and a is the correct solution. Both will be taken as strings.
Here's a non-recursive solution at 78 bytes:
s=>a=>eval([...s].map((c,i)=>c>'Z'?0:c==a[i]?5+(i>14):~(i>19)*(i>14)).join`+`)

Takes input through the currying syntax.
Thanks to @ETHproductions for saving 9 bytes! s[i] to c and (-1-(i>19|0)) to ~(i>19).
Thanks to @Kritixi Lithos for saving a byte! c=='_' to c>'Z'.
Try it online!

Talking of this being your first solution in JS, what is your main language for code golf? I've only ever used Python and brainfuck for code golf.

@J843136028 My main language is Python, but I have golfed quite a bit with C# too. Haxe has been laying off for a while, but I might return to it.

Cool! I've only ever used brainfuck once, so my main language is Python too.

@J843136028 Yeah, I've actually seen your answers here and there. As my bio yields, I don't spend that much time figuring out solutions, so they aren't of interest most of the time. I've only done so little with BrainF*ck, as it takes a lot of time to find short solutions, even to intermediate problems.

I know what you mean about BF. I'm surprised people look at my answers.

I believe (-1-(i<19|0)) is the same as ~(i<19), which will save you 6 bytes.

Also, s[i] is the same as c :-)

~(i<19) doesn't seem to work, but the latter suggestion does, thanks! :)

Are you sure it doesn't work? (-1-(i<19|0)) == ~(i<19) gives true for 18, 19, and 20. I think maybe the mistake is that it needs to be i<20 instead

I think c=='_' can be replaced with c>'Z'

@ETHproductions I'm pretty sure. i<20 doesn't work either :/ If you're able to test it on your own, that would be great. I have tried VS and TIO nexus, and they both yield wrong results. However, now that I'm thinking about it, I'm not sure if my code works every edge case, which might lead to the confusion here... who knows :D

@KritixiLithos It indeed can, thanks! :-)

In any case, -1-(i>19|0) is exactly the same as -1-(i>19), because booleans are implicitly cast to numbers when used in arithmetic.

Ooooooh, the problem is that I had the > backwards. Duh :P (-1-(i>19|0)) == ~(i>19)

Works for me now

Haskell, 84 bytes
i x a b|a>'Z'=0|a==b=6-0^x|1<2= -x
w x=x<$[1..5*3^0^x]
(sum.).zipWith3 i(w=<<[0..2])

Usage example: ((sum.).zipWith3 i(w=<<[0..2])) "DBADBDCDBAEDABCD_E__A__C_" "DBADBDCDBAEDABCDBEEDACDCA" -> 99. Try it online!.
How it works: i x a b calculates the score for a single answer a with correct result b and the penalty x for a wrong answer (a non-negative value). If you skip (a>'Z'), the score is 0, if the answer is right (a==b), the score is 6-0^x, else the score is -x.
w=<<[0..2] makes a list of penalties for all 25 questions by applying w to 0, 1 and 2, i.e. making 5*3^0^x copies of each number (-> 15 times 0, 5 times 1 and 5 times 2).
zipWith3 applies i to the list of penalties, list of answers and list of correct results. Finally all scores are added (sum).


text:
More fun with case-(very)-sensitive strings
Inspired by this challenge (or, more specifically, by misreading it), I've come up with the following challenge:
Given an input string S, reverse the order of all uppercase characters, and all lowercase characters. Leave all non-letter characters in place. For instance:

Note that the uppercase W (the first uppercase letter) was replaced with H (the last). Same goes for the lowercase letters: 'd' (the first) is swapped with e (the last), l (second) gets replaced with l (pen-ultimate) ... All the non-letter characters are left in place.
Input

Input is a string with only ASCII characters in the range 32-126.
Input is guaranteed to be at least 1 character long, and won't exceed your language's limit.

Output

That same string, with the characters swapped as described.

Additional rules

Standard loopholes are forbidden
Answer must be a full program or a function, not a snippet or a REPL-entry.
code-golf, shortest answer in bytes wins.

Test cases
A
A

Ok
Ok

OK
KO

Hello, World!
Wdlro, Holle!

0123456789
0123456789

The quick brown Fox jumps over the lazy doge
Feg odyza lehtr Tev ospmu jxon wor bkci uqeh

odd
ddo

racecar
racecar

EtOn Em OsN R AaToNsIsIhT!!1!
ThIs Is NoT A RaNsOmEnOtE!!1!

You might want to include a 2-char testcase, my original solution failed on that at first. (Fixed at no cost by changing .+ to .*)

"lazy doge" reminded me of this: https://www.youtube.com/watch?v=W-d6uUSY9hk

MATL, 14 bytes
2:"t@Y2myy)Pw(

Try it at MATL Online
Explanation
        % Impicitly grab input as a string
2:      % Push the array [1, 2] to the stack
"       % For each value in this array
  t     % Duplicate the top element of the stack (S)
  @     % Get the current loop index
  Y2    % Load the predefined literal 1Y2 ('ABC...Z') on the first loop
        % and the predefined literal 2Y2 ('abc...z') on the second loop (M)
  m     % Create a logical array the length of S that is TRUE when a character is in the
        % array M and FALSE otherwise (B)
  yy    % Make a copy of both S and B
  )     % Grab just the letters of S that were in M using B as an index
  P     % Reverse this array
  w     % Flip the top two stack elements
  (     % Assign them back into the string
        % Implicit end of for loop and implicit display

Great job! I had 2:"tttXk>f)5MP(Yo for 17 bytes

Retina, 19 bytes
Retina doesn't have a direct way to reverse a string, but we can do it by exploiting the sorting stage:
O^#`[a-z]
O^#`[A-Z]

Sort (O), reading them as numbers (#), and then reverse the ordering (^), of all the strings matching the given regex (lowercase letters for the first line, and uppercase letters for the second).
This works because when we try to read strings without numeric characters as numbers they get treated as 0, so all the characters have the same value for sorting. Since sorting is stable they are left in the same order, and reversing them returns the original string reversed.
Try it online!

Perl, 45 bytes
44 bytes of code + -p flag.
for$c(u,l){@T=/\p{L$c}/g;s/\p{L$c}/pop@T/ge}

Try it online!
Unicode characters classes \p{Lu} and \p{Ll} matches respectively uppercase and lowercase letters.
So /\p{L$c}/ will return the list of all upper (or lower) case letters (and store it inside @T).
And then, the regex s/\p{$c}/pop@T/ge will replace each (upper, then lower case) letter by the last letter of @T while removing it from @T.

JavaScript (ES6), 74 73 71 70 bytes

f=
s=>(g=r=>s=s.replace(r,_=>a.pop(),a=s.match(r)))(/[A-Z]/g,g(/[a-z]/g))
<input oninput=o.textContent=f(this.value)>

Edit: Saved 1 byte thanks to @Arnauld.

I knew there was a better way...

JavaScript (ES6), 92 bytes
s=>(F=(r,s)=>s.replace(r,([x],a,y)=>y+F(r,a)+x))(/[a-z](.*)([a-z])/,F(/[A-Z](.*)([A-Z])/,s))

There has got to be a way to take advantage of the similarity between the regexes...
Test snippet

let f =
s=>(F=(r,s)=>s.replace(r,([x],a,y)=>y+F(r,a)+x))(/[a-z](.*)([a-z])/,F(/[A-Z](.*)([A-Z])/,s))
<input style="width:500px" value="Wdlro, Holle!" oninput="O.value=f(this.value)">

<input style="width:500px" value="Hello, World!" id=O disabled>

Does this assume that the function is assigned to a variable called f? Shouldn;t that be in the byte count?

@steenbergh The function is anonymous, it can be called whatever you want it to be

@steenbergh Nope, it's an anonymous function which creates another function F then calls it recursively twice. The outer function doesn't actually call itself at any point.

Why do you use parentheses around .* in the regexes?

@Luke to capture those characters (the a in ([x],a,y)=>)

Perl 6, 75 69 bytes
{my @a=.comb;@(grep $_,@a).&{@$_=[R,] $_} for /<:Lu>/,/<:Ll>/;[~] @a}

How it works

my @a=.comb;
Split the string into characters, and store them in an array.
for /<:Lu>/,/<:Ll>/
For two regexes matching upper and lower-case letters, respectively...

@(grep $_,@a)
Get a slice of all array entries matching the regex.
.&{@$_=[R,] $_}
Assign the reverse of the slice to itself.

[~] @a
Concatenate the modified array to form a string again, and return it.

-6 bytes by stealing the idea to use Unicode classes instead of character ranges, from @Dada's solution.

Jelly, 14 bytes
nŒlT,Ṛ$yJịŒsµ⁺

Try it online!
How it works
nŒlT,Ṛ$yJịŒsµ⁺  Main link. Argument: s (string)

 Œl             Convert to lowercase.
n               Test for inequality.
   T            Truth; yield all indices of 1's.
    ,Ṛ$         Pair with its reverse. Yields [A, B] (pair of lists).
        J       Indices; yield I := [1, ..., len(s)].
       y        Translate; replace the integers of I that occur in A with the
                corresponding integers in B.
          Œs    Swapcase; yield s with swapped case.
         ị      Use the translated index list to index into s with swapped case.
            µ   Combine all links to the left into a chain.
             ⁺   Duplicate the chain, executing it twice.

not to be nitpicky but.. 14 characters != 23 bytes :) https://mothereff.in/byte-counter

@Gizmo Jelly uses a codepage. See this meta post for more information.

@Suever Oh that's neat, learned something today ^.^

Bash + Unix utilities, 122 121 bytes
f()(p=[^$1*
v="\)\([$1\)\("
for((n=99;n;n--)){
q="$q;s/^\($p$v.*$v$p\)$/\1\4\3\2\5/"
p=[^$1*[$1$p
}
sed $q)
f a-z]|f A-Z]

Try it online!
Not really very short; maybe someone can golf it further.
Input on stdin, output on stdout.
This will work correctly on inputs of less than 200 characters.
(Actually it correctly handles any string with fewer than 200 lower-case letters and fewer than 200 upper-case letters.)
If you increase the 99 in the code to 102 (at the cost of one additional byte), it will handle strings up to 205 characters.
However, you can't increase the 99 in the code beyond 102 since you'll then exceed sed's maximum argument length.
Here's a version without any particular input size limitation, but the count is a little longer, 137 bytes.  (This longer version writes to an auxiliary file named t.)
f()(p=[^$1*
v="\)\([$1\)\("
for((n=`wc -c<t`;n;n--)){
sed -i "s/^\($p$v.*$v$p\)$/\1\4\3\2\5/" t
p=[^$1*[$1$p
})
cat>t
f a-z]
f A-Z]
cat t

Test runs:
for x in A Ok OK 'Hello, World!' 0123456789 'The quick brown Fox jumps over the lazy doge' odd racecar 'EtOn Em OsN R AaToNsIsIhT!!1!'
  do
    echo "$x"
    ./swapping3 <<<"$x"
    echo
  done

A
A

Ok
Ok

OK
KO

Hello, World!
Wdlro, Holle!

0123456789
0123456789

The quick brown Fox jumps over the lazy doge
Feg odyza lehtr Tev ospmu jxon wor bkci uqeh

odd
ddo

racecar
racecar

EtOn Em OsN R AaToNsIsIhT!!1!
ThIs Is NoT A RaNsOmEnOtE!!1!

Interesting that it fails in TIO. ☹ May depend on the sed implementation installed on your system, but to GNU sed you can add -r option and remove the \ escaping of all parenthesis.

Python 2, 115 bytes
s=input();u=str.isupper
exec"r='';i=0\nfor c in s:r+=c[u(c):]or filter(u,s)[~i];i+=u(c)\ns=r.swapcase();"*2
print s

Try it online!

Can you replace \n with ;?

Unfortunately, no. The argument of exec is parsed as usual Python code, so the for loop must be on its own line.

Java (OpenJDK 8), 271 bytes
s->new String(new Error(){char[]o=s.toCharArray();char c;int b;{while(b++<2)for(int l=0,r=o.length;l<r;l++){for(--r;r>l&&f(r);r--);for(;l<r&&f(l);l++);if(l<r){o[l]=o[r];o[r]=c;}}}boolean f(int i){c=o[i];return b>1?!Character.isUpperCase(c):!Character.isLowerCase(c);}}.o)

Try it online!

You could save some bytes by making this into a lambda. s->new String...

@NonlinearFruit thank you! 294 -> 272, also fixed mistake when r an l was reused without initialization.

Welcome to PPCG! Some things you could still golf: char[]o=s.toCharArray();char c;int b; to char o[]=s.toCharArray(),c,b;; and both && to &'; and c=o[i];return b>1?!Character.isUpperCase(c):!Character.isLowerCase(c); to c=o[i];Character x=c;return b>1?!x.isUpperCase(c):!x.isLowerCase(c); (259 bytes in total). And I probably missed some things to golf it more. Also, if you haven't seen it yet, tips for golfing in Java might be interesting to read.

R, 107 bytes
u=utf8ToInt(scan(,''));for(i in c(65,97)){l=which(u%in%i:(i+25));u[l]=u[rev(l)]};cat(intToUtf8(u,T),sep="")

Adapted from my response to the linked challenge. This is considerably easier than just swapping pairs. I wonder if I could get sub 100 with some golfs...
Try it online!

05AB1E, 19 bytes
2FÐlø€Ë≠āsƶ0KÂ‡<è.š

I/O as a list of characters.
Based on my 05AB1E answer in the related challenge.
Try it online or verify all test cases.
Explanation:
2F            # Loop 2 times:
  Ð           #  Triplicate the current character-list
              #  (which will use the implicit input-list in the first iteration)
   l          #  Lowercase all letters of the top copy
    ø         #  Zip/transpose the top two lists; pairing them together, and swapping
              #  rows/columns
     €Ë≠      #  Check for each pair whether they're NOT the same
              #  (so uppercase characters that have now become lowercase)
  ā           #  Push a list in the range [1, length] (without popping)
   s          #  Swap so the mapped list is at the top again
    ƶ         #  Multiply each 1/0 by its 1-based index
     0K       #  Remove all 0s
       Â      #  Bifurcate it (short for Duplicate & Reverse copy)
        ‡     #  Transliterate the indices with the reversed indices in [1, length]
         <    #  Decrease each by 1 (because 05AB1E uses 0-based indexing)
          è   #  Index them into the current character-list
           .š #  And swap all cases (lowercase to uppercase, and vice-versa)
              # (after the loop, the resulting character-list is output implicitly)

source: Stack Exchange

license: 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/

sort: votes


text:
Carpet an Airport
In 2015 the Portland International Airport began the replacement of their iconic carpet.  I want you to write a program to draw their old carpet in as few bytes as possible.
The carpet:

Specifications

Here is a link to a scalable pdf image of one tile.  Your output should match the relative dimensions and placement of that image.
All colors in your final image should be within 15 of every RGB value in the specified image.  These are listed below for your convenience.
            Red   Green Blue
Teal:       0,    168,  142
Magenta:    168,  108,  185
Orange:     247,  58,   58
Light Blue: 90,   166,  216
Dark Blue:  0,    77,   117

Your output must be at least 150x150 pixels and should be square.  If you choose to output in a scalable format like a vector image you should match the image exactly.
You may output the image in any preexisting image format.
This is code-golf so you should aim to minimize the number of bytes in your code.

Inspired by Reddit?

@Hexaholic I don't think so I was hitting random on wikipedia and I hit the page.  However I may have also seen it on reddit before hand.

Does it have to be a two-dimensional image or could it be something like a model viewed from a specific angle?

I revisited this problem after 2 years of abstinence from code golf. Could you elaborate on the ratio of
a) size of squares vs. size of spaces inbetween squares, and
b) size of square vs. size of "border", i.e. distance from the outermost square to the border of the whole tile? I'd appreciate gathering this info for modifying my code to fit the exact sepcs of your challenge, @TaylorAlexRaine. Thx!

Tikz, 725 693 681 671 bytes

Some significant improvements can be made to this answer.  If you would like to make major golfs then you should post your own answer with your modified version.  For minor improvements that I just missed, and don't require large explanation, feel free to comment them.  I would like to reward major improvements, and I will definitely upvote any answer that beats this.

\documentclass{standalone}\usepackage{xcolor,tikz}\begin{document}\tikz[line width=20,every node/.style={minimum size=20}]{\definecolor{t}{RGB}{0,168,142}\definecolor{m}{RGB}{168,99,185}\definecolor{o}{RGB}{247,58,58}\definecolor{b}{RGB}{90,166,216}\definecolor{d}{RGB}{40,77,117}\fill[t](-7.5,-7.5)rectangle(7.5,7.5);\draw(-1,0)node[fill=o]{};\foreach\x in{1,...,7}{\draw(-\x,-1)node[fill=m]{};\draw(0,\x)node[fill=b]{};}\foreach\x in{1,...,3}{\draw(\x,\x)node[fill=d]{};\draw(3+\x,-3-\x)node[fill=d]{};\draw(-3-\x,3+\x)node[fill=d]{};\draw(4+\x,1)node[fill=o]{};}\draw[d](.65,0)--(7.35,0);\draw[d,dash pattern=on20off8.5on162.5off8.5](0,-7.35)--(0,3.35);}\end{document}

Try it Online!
Explanation
A good deal of the code is a wrapper:
\documentclass{standalone}\usepackage{xcolor,tikz}\begin{document}\tikz{...}\end{document}

This is a slight variation on the standard Tikz wrapper in that it also has the line \usepackage{xcolor} so that we can create the colors properly.
The first thing that is done is line width=20,every node/.style={minimum size=20}] which sets the lines and nodes to be the proper size.
Once that is done we define the colors we will be using for the various parts of the image:
\definecolor{t}{RGB}{0,168,142}\definecolor{m}{RGB}{168,99,185}\definecolor{o}{RGB}{247,58,58}\definecolor{b}{RGB}{90,166,216}\definecolor{d}{RGB}{40,77,117}

Now that everything is set up we paint the background to our canvas teal:
\fill[t](-7.5,-7.5)rectangle(7.5,7.5);

(I wont include an image of this because it is just a teal square, but I will be including images of each other step)
The first node we add is the orange node just left of the center of the canvas.
\draw(-1,0)node[fill=o]{};

Now we will draw the light blue and magenta nodes.  There are 7 blue nodes and 4 blue nodes, but we can draw extra nodes that will be covered up by lines later on so we will draw 7 of each.
\foreach\x in{1,...,7}{
    \draw(-\x,-1)node[fill=m]{};
    \draw(0,\x)node[fill=b]{};
}

Now we will draw all the groups of 3 dots using a single \foreach loop
\foreach\x in{1,...,3}{\draw(\x,\x)node[fill=d]{};\draw(3+\x,-3-\x)node[fill=d]{};\draw(-3-\x,3+\x)node[fill=d]{};\draw(4+\x,1)node[fill=o]{};}

Now we draw the right line. This line will be a simple line with offsets of .35 in each direction to match the size of a node.
\draw[d](.65,0)--(7.35,0);

Now we must draw in the dark blue lines and squares on the x-axis.  We will draw them with one line using a custom dash pattern.
This pattern is [dash pattern=on20off8.5on162.5off8.5] This creates a square with a long solid tail.  Our line will start from the bottom and will not quite cover 2 cycles of the pattern.
\draw[d,dash pattern=on20off8.5on162.5off8.5](0,-7.35)--(0,3.35);

And now we are done.

Can you use numbers to represent RGB colours in Tikz, instead of typing the RGB offsets?

@TuukkaX I think so but I couldn't figure it out.  If you know how I would be thankful to be enlightened.

I don't know Tikz at all, so can't help with that :( However, if I understood your rule about "within 15 of every RGB" right, you can change 108 to 99, since the error is under 15.

Using \definecolor with the HTML specification (rather than RGB) allows you to specify colors using hex.

@Joe85AC I've seen both of your edit suggestions.  I would like it most if you could post this as your own answer.  The changes represent a significant amount of work and I believe that it would be most representative if that appeared as your own answer.  This is consistent with the way the site generally handles golfing improvements.  Additionally it would be a good way to get the reputation which is required to comment in the future.

@AdHocGarfHunter Thank you for pointing me to the right thing to do. I may now comment :-) Please have a look at my five easy improvements to your solution: You can (a) refrain from loading xcolor, (b) use \definecolorset and do that before you start \tikz{} OR define dark blue in the right manner (0 instead of 40 for the R-value), (c) add t, to the general \tikz-options in favour of leaving out [t] after your \fill-command, (d) use {1,2,3} instead of {1,...,3} in your second \foreach-loop, (e) leave out the last ;.

Hey there, @WheatWizard, I've revisited this problem after more than 2 years in yet another holiday break. Found some more improvements. Have a look @ my solution ;-)

@Joe85AC Nice.  I've improved my tikz since as well, maybe I should give it a spin and see how I compare.

Pure HTML, 873 bytes

HTML + CSS, 625 bytes

#l{background:#5AD}th{background:#057}#o{background:#F33}#m>td{background:#A6B

literal PNG file, 283, 234 227 bytes
EDIT: Using online image compression service https://compress-or-die.com/, this went down another 7 bytes.
albn@alexhij:~/tmp$ ls -l carpet3.png
-rw-r--r-- 1 albn albn 227 15. Feb 12:01 carpet3.png
albn@alexhij:~/tmp$ base64 carpet3.png
iVBORw0KGgoAAAANSUhEUgAAAJgAAACYBAMAAADq7D0SAAAAD1BMVEUAqI4ATXWobLn3Ojpapthl
S7nNAAAAj0lEQVR4Ae3ThRHCQBQGYVqgBVq4Fui/Jt4ILks8/80uLvkyOTlkd67EILHojtWEyxQT
Sw6uFS5TTCw/uFa+TDGx/PjS3z+KiS2GcRtgzIqJdboDPomteniCxMTyatXtMiExMcB22amCJ7wG
MbHpBWBiYmJiYmJwAjGx/ncAn0VMrP8dwL+KieXHFyImltoF6oWZiblRTNQAAAAASUVORK5CYII=

The 227 bytes are the actual size of the binary file carpet.png. When encoded in base64, as displayed in the quoted block above, it is a few bytes longer (308 bytes). Encapsulating that in an html snippet that renders the image rightaway will add another few bytes:
HTML, 414, 343, 336 bytes

 as Shaggy suggested. Also compressed the image down another 17, 24 bytes

I don't think a literal file is considered a valid programming language here on code-golf. It is up to the OP whether this is valid or not.

You may be right, but even the description of the tag kolmogorov-complexity on https://codegolf.stackexchange.com/tags/kolmogorov-complexity/info mentions a complex string, which shortest representation might be to print it literally. If a literal string is considered the "worst case solution" to a string based code-golf, a literal image file could be considered a "worst case solution" to an image based code-golf.
Edit: I only posted the file, because I was surprised that it was actually shorter than the other solutions posted earlier. (after removing the optional tIME chunk from the file)

If its up to me I'm fine with it.

If you used HTML, you could save yourself a good few bytes. . Here's a 366 byte version I was working on before I saw your answer: <img src=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJgAAACYBAMAAADq7D0SAAAAD1BMVEUAqI4ATXWobLlaptj3OjrqGXAuAAAAp0lEQVRo3u3YQQqFMAxFUbeQLbiFbsH9r8k3y8CmTiKm7b2Dwv/CgUAD4jF3TYGBRdgKmRqPCQa28gaMZ20KDGz5DQhnbQoMTG2wAcPR/ScY2HeYVw4zBQYWYDUvbRLWFS/lBxhYhM3bpXzMcWBgEVa5U70cpsDAnkf1FxcwMDAwMLBczP8DAwuwmpc2HzMFBhY8qHlp8zFTYGCdyn8GKrhOYBtjv3QDvf+Zic+8bOsAAAAASUVORK5CYII

@ComradeSparklePony We generally don't require programming language answers to questions like this: https://codegolf.meta.stackexchange.com/questions/3610/should-answers-to-fixed-output-challenges-be-written-in-a-programming-language

Mathematica, 285 bytes
e={1,1};r=RGBColor["#"<>#]&;c=Cuboid;s=c[3#-e,3#+e]&;a=Array;b=a[s[{1,-1}#]&,3,#]&;Graphics@{r@"0a8",c[-23e,23e],r@"a6b",a[s@{-#,-1}&,7],r@"f33",a[s@{#,1}&,3,5],s@{-1,0},r@"5ad",a[s@{0,#}&,4,4],r@"057",a[s[e#]&,4,0],b@4,b[-6],s@{0,-7},{-1,2}~c~{1,10},{-1,-2}~c~{1,-19},{2,-1}~c~{22,1}}

Easier to read:
 1  c = Cuboid; e = {1, 1};
 2  s = c[3 # - e, 3 # + e] &;
 3  a = Array; b = a[s[{1, -1} #] &, 3, #] &;
 4  r = RGBColor["#" <> #] &;
 5  Graphics@{
 6   r@"0a8", c[-23 e, 23 e],
 7   r@"a6b", a[s@{-#, -1} &, 7],
 8   r@"f33", a[s@{#, 1} &, 3, 5], s@{-1, 0},
 9   r@"5ad", a[s@{0, #} &, 4, 4],
10   r@"057",
11    a[s[e #] &, 4, 0], b@4, b[-6], s@{0, -7},
12    {-1, 2}~c~{1, 10}, {-1, -2}~c~{1, -19}, {2, -1}~c~{22, 1}
13  }

Lines 1–3 define short names for functions, the most important of which is s which draws a square centered at the coordinates it receives (really 3 times its coordinates, for appropriate scaling). Line 4 defines a color function using Mathematica's "shortcut" RGB system: RGBColor["#xyz"], where xyz are hexadecimal digits, stands for RGBColor[{17x, 17y, 17z}] (so that each coordinate has 16 equally spaced options running from 0 to 255). The first commands on lines 6–10 switch the current color, using the shortcut colors that are closest to the designated five colors (no value is off by more than 8 when we round to the nearest multiple of 17).
Line 6 draws the large teal square. Line 7 draws the line of magenta squares, Line 8 draws the line of orange squares and the single orange square. Line 9 draws the line of light blue squares. Line 11 draws the three diagonal lines of dark blue squares, as well as the single dark blue square at the bottom. Finally, line 12 draws the three long dark blue rectangles. The output is below:

(Golf tip: the command Cuboid, which is intended for 3d graphics objects, works just fine in 2d and is shorter than Rectangle.)

TikZ, 671>439>432>377>334>311 (282) bytes

My original answer started from the code that Ad Hoc Garf Hunter provided above, cf. Tikz, 671 bytes.
I took this code and my knowledge about general LaTeX to make some improvements to the length of it, saving a bit more than 1 out of every 3 bytes.
However, two years later, I returned to this problem and gave it another try by starting from scratch.

Here's my all new, personal solution.
Note that the solution uses non-printable single-byte characters.
In the depiction of this solution, they are replaced by circled characters. The circled characters can be mapped by 0x(circled character) with the help of an ASCII table.
\documentclass[tikz]{standalone}\begin{document}\tikz{\let~\def~Ⓒ{;\color[HTML]}~④{)rectangle++(.7}~Ⓕ{\fill(}~~#1#2{Ⓕ0x#1,0x#2④,.7);}Ⓒ{00a88e}Ⓕ.85,.85④+14.3,15)Ⓒ{004d75}~2E~3D~4C~BB~AA~99~88~C4~D3~E2~81Ⓕ8,2④,5.7)(8,9④,2.7)(9,8④+6,.7)Ⓒ{5aa6d8}~8F~8E~8D~8CⒸ{f73a3a}~D9~E9~F9~78Ⓒ{a86cb9}~17~27~37~47~57~67~77}\stop

Try it Online!
Output

Explanation
Here's a more readable version of my personal new solution.
01: \documentclass[tikz]{standalone}\begin{document}\tikz{
02: \let~\def~Ⓒ{;\color[HTML]}~④{)rectangle++(.7}~Ⓕ{\fill(}
03: ~~#1#2{Ⓕ0x#1,0x#2④,.7);}
04: Ⓒ{00a88e}Ⓕ.85,.85④+14.3,15)
05: Ⓒ{004d75}~2E~3D~4C~BB~AA~99~88~C4~D3~E2~81
06: Ⓕ8,2④,5.7)(8,9④,2.7)(9,8④+6,.7)
07: Ⓒ{5aa6d8}~8F~8E~8D~8C
08: Ⓒ{f73a3a}~D9~E9~F9~78
09: Ⓒ{a86cb9}~17~27~37~47~57~67~77
10: }\stop

Let's start with the wrapper in lines 1 and 10. This is basically the standard TikZ-wrapper.
In line 2, we assign a shorthand (~) to the command \def within the TikZ-scope. Note that the only available printable single-character command ~ (catcode=13) is now defined as a command within the \tikz{} scope. This helps us to define even more shorthands in a very compact way. We then assign a shorthand to \color that allows us to change the color that we use for \fill-commands later on. As we have five colors in total, we will use the command Ⓒ five times. Note that Ⓒ for \color is a mnemonic declaration. We assign a shorthand to a string that will be used quite a lot to draw rectangles. ④ for rectangle (with four sides) is a mnemonic assignment as well. It contains the closing bracket for the first and the opening bracket for the second coordinate as well as the most common value for the x-value of the second coordinate. In the end of the line, we define a shorthand for the \fill command. The assignment is again mnemonic: Ⓕ. Note that all of the three assignments to "circled characters" are really assignments to non-printable single-byte control characters (0xY, Y standing for the corresponding circled character, being interpreted as ASCII hex value). These characters are all active (catcode=13) characters. All those assignments are displayed as mid-dots in the "Try It Online"-version at Overleaf. This renders an actually sort of "unreadable" (but completely working!) code view that can be ameliorated if you just copy the code to another editor, e.g. here.
In line 3, we continue to redefine ~ and, from now on, use this command to draw little squares. We benefit from the fact that the whole tile can be divided in 15 by 15 squares which is less than 16 by 16. Therefore, we can use hexadecimal one-digit numbers to refer to a unique square with only two characters.
In lines 4 and 6, we draw a huge square in teal and some rectangles, more exactly: all those not being square, in dark blue. We don't need to pick the color dark blue, since this happens in line 5, see below.
Lines 5, 7, 8, and 9 draw all the squares in four different colors. As we pick dark blue as our color for the squares in line 5, we can keep it for the rectangles, see above. Thus, we only have to use the Ⓒ-command five times.
We can make it even shorter!
If you visited the "Try It Online"-link, you might have found a "hacky" version with 29 bytes less. This version produces the same output. However, it throws errors and has a white border. Therefore, the "hacky" version is non-competing. It differs from the version described above by two things: (A) We don't use \begin{document}. This produces errors, but we obtain an output nevertheless. We can save 16 bytes. (B) In the "hacky" definition of the final version of ~, ~ calls itself. This helps us to save a lot of ~ characters in lines 6, 7, 8, and 9 (10+3+3+6 = 22, to be exact). However, we will have to introduce the ~ character in line 3 and one pair of curly braces for each of the lines 6, 7, 8, and 9 to make this work, leaving us with a difference of 13 bytes.
Comments regarding Ad Hoc Garf Hunter's solution
I did not like the fact that I didn't fully understand the dash pattern that the other solution is using. Also, I tried to avoid nodes and lines by concentrating on rectangles. Furthermore, I believe in the metric system. Thus, I refrained from using other units than mm or cm. ;-) I believe that my second approach is much cleaner now.
Improvements
Please feel free to comment and help me save more bytes.
Literal PNG file, 223 bytes
I've created this PNG file from my TikZ output.

@Ad Hoc Garf Hunter: Some minor improvements that do not need a lot of explanation also can be made to your code. You can (a) refrain from loading xcolor, (b) use \definecolorset and do that before you start \tikz{} OR define dark blue in the right manner (0 instead of 40 for the R-value), (c) add t, to the general \tikz-options in favour of leaving out [t] after your \fill-command, (d) use {1,2,3} instead of {1,...,3} in your second \foreach-loop, (e) leave out the last ;.

FYI that ping doesn't fork, since Ad Hoc Garf Hunter has had no interaction with this answer. If you want to suggest improvements to Ad Hoc Garf Hunter's answer, you'll have to wait until you get 50 reputation and then comment on it.

"fork" is a typo for "work" in my above comment.

@pppery Thanks, I know that. Anyways, I did have some sort of chat with Ad Hoc Garf Hunter through the comments. Just hope, that he checks back here until I can comment :-)

(You can now comment, given that you have 71 rep)

@pppery Thanks, already did that :-)

Python, 420
from PIL import Image,ImageDraw
B=0,77,117
I=Image.new('RGB',(300,300),(0,168,142))
r=ImageDraw.Draw(I).rectangle
for x,y,c in['7172737a98cde670123456bcd70112233456666778888888bcde23232323331111300000003333'[x::26]for x in range(26)]:exec'r([W,W,14+W,14+W],[(168,108,185),(247,58,58),(90,166,216),B][%s]);'.replace('W','2+20*0x%s')%(x,y,x,y,c)
r([162,142,296,156],B)
r([142,82,156,136],B)
r([142,162,156,276],B)
I.show()

T-SQL, 680 bytes
CREATE TABLE g(c INT,s geometry)
INSERT g SELECT c,geometry::Point(x,y,0).STBuffer(.4)
FROM(VALUES(1,7,8),(1,13,9),(1,14,9),(1,15,9),(2,2,14),(2,3,13),(2,4,12)
 ,(2,8,8),(2,9,9),(2,10,10),(2,11,11),(2,8,1),(2,12,4),(2,13,3),(2,14,2)
 ,(3,1,7),(3,2,7),(3,3,7),(3,4,7),(3,5,7),(3,6,7),(3,7,7)
 ,(35,8,12),(35,8,13),(35,8,14),(35,8,15))a(c,x,y)
INSERT g SELECT c,geometry::STLineFromText('LINESTRING('+v+')',0).STBuffer(.4)
FROM(VALUES(0,'.8 .8,15.2 15.2'),(2,'8 2,8 7'),(2,'8 9,8 11'),(2,'9 8,15 8'))a(c,v);
WITH t AS(SELECT 4n UNION ALL SELECT n+1FROM t WHERE n<34)
INSERT g SELECT n,geometry::Point(1,1,0).STBuffer(.01)FROM t;
SELECT c,geometry::UnionAggregate(s.STEnvelope())FROM g GROUP BY c

Line breaks added for readability.
Make sure to DROP TABLE g after you run it, I didn't include that in the byte total.
Uses geospatial features supported in SQL 2008 and higher.

So, this doesn't entirely satisfy the color requirement, but as I explain below, that's not fully under my control. Let's call this the faded carpet version.
Formatted/commented code and output:

Notes:

The points (and lines) in the table are expanded into a circle with STBuffer, then squared off with STEnvelope.
The SQL spatial results pane has a fixed color palette, so I am limited in what colors I can display (no bright red, etc)
To get the colors I want, I have to select them in the correct order. Column c in my table defines the grouping order; the large teal square is group 0, the 4 blue squares are group 35.
To get multiple objects of the same color, I have to combine them into a single object, that's the purpose of the UnionAggregate() function at the end.
To "skip ahead" through the color palette to get to the light blue, I have to insert 31 dummy objects that are big enough to get assigned a color, but small enough not to show.

To see more strange uses of SQL spatial features, see draw the biohazard symbol and draw the Easter Bunny.

HTML/SVG, 550 542 521 bytes

<svg><path fill=#0a8 d="M0 0h152v152H0z"/><path fill=#5ad d="M72 2h8v8h-8zm0 10h8v8h-8zm0 10h8v8h-8zm0 10h8v8h-8z"/><path fill=#057 d="M12 12h8v8h-8zm10 10h8v8h-8zm10 10h8v8h-8zm40 10h8v28h-8zm0 30h8v8h-8zm10-10h8v8h-8zm10-10h8v8h-8zm10-10h8v8h-8zM82 72h68v8H82zM72 82h8v58h-8zm0 60h8v8h-8zm40-30h8v8h-8zm10 10h8v8h-8zm10 10h8v8h-8z"/><path fill=#f33 d="M62 72h8v8h-8zm60-10h8v8h-8zm10 0h8v8h-8zm10 0h8v8h-8z"/><path fill=#a6b d="M2 82h8v8H2zm10 0h8v8h-8zm10 0h8v8h-8zm10 0h8v8h-8zm10 0h8v8h-8zm10 0h8v8h-8zm10 0h8v8h-8z"

HTML/SVG + JavaScript (ES6), 500 499 bytes
An extra > is required in order for this to function as a Snippet, see this Fiddle for actual code.

[[t="5ad",2],[t,o=12],[t,p=22],[t,q=32],[,o,o],[,p,p],[,q,q],[,42,,28],[],[,v=62,s=82],[,52,92],[,42,102],[,,s,,68],[,s,,58],[,142],[,112,112],[,122,122],[,132,132],[t="f33",,v],[t,v,122],[t,v,132],[t,v,142],[t="a6b",s,2],[t,s,o],[t,s,p],[t,s,q],[t,s,42],[t,s,52],[t,s,v],["0a8",0,0,152,152]].map(x=>a(x[0],x[1],x[2],x[3],x[4]),a=(f="057",y=72,x=72,h=8,w=8)=>(c.after(r=c.cloneNode()),r.id++,r[s="setAttribute"]("fill","#"+f),r[s]("x",x),r[s]("y",y),r[s]("width",w),r[s]("height",h)))
<svg><rect id=c>

Explanation
An array of arrays is mapped to function a, creating clones of the rect in the HTML, inserting them after the initial rect and setting their fill, x, y, width & height attributes. Each array contains values for those attributes, in that order, with any missing values being set by the default parameters of a. The seemingly unnecessary r.id++ allows the use of cloneNode() while ensuring there is only ever 1 rect with an id of c; this saves the need to use the ridiculously expensive document.createElementNS("http://www.w3.org/2000/svg","rect").

PHP+SVG, 425 Bytes
<svg><rect x=0 y=0 fill=#00a88e width=150 height=150 /><?foreach(["004d75"=>[[1,1],[2,2],[3,3],[7,14],[7,7],[8,6],[9,5],[10,4],[11,11],[12,12],[13,13],[7,4,0,2],[8,7,6,0],[7,8,0,5]],"5aa6d8"=>[[7,0],[7,1],[7,2],[7,3]],a86cb9=>[[0,8],[1,8],[2,8],[3,8],[4,8],[5,8],[6,8]],f73a3a=>[[6,7],[12,6],[13,6],[14,6]]]as$c=>$p)foreach($p as$v)echo"<rect x={$v[0]}1 y={$v[1]}1 width=".(8+10*$v[2])." height=".(8+10*$v[3])." fill=#$c />";

expanded
<svg><rect x=0 y=0 fill=#00a88e width=150 height=150 />
<?foreach([
"004d75"=>[[1,1],[2,2],[3,3],[7,14],[7,7],[8,6],[9,5],[10,4],[11,11],[12,12],[13,13],[7,4,0,2],[8,7,6,0],[7,8,0,5]]
,"5aa6d8"=>[[7,0],[7,1],[7,2],[7,3]]
,a86cb9=>[[0,8],[1,8],[2,8],[3,8],[4,8],[5,8],[6,8]]
,f73a3a=>[[6,7],[12,6],[13,6],[14,6]] # Array containing color and position ,width, height of each rect without the background
]as$c=>$p)
  foreach($p as$v)
    echo"<rect x={$v[0]}1 y={$v[1]}1 width=".(8+10*$v[2])." height=".(8+10*$v[3])." fill=#$c />"; # Output the rects

The result of the code in a HTML snippet

<svg><rect x=0 y=0 fill=#00a88e width=150 height=150 /><rect x=11 y=11 width=8 height=8 fill=#004d75 /><rect x=21 y=21 width=8 height=8 fill=#004d75 /><rect x=31 y=31 width=8 height=8 fill=#004d75 /><rect x=71 y=141 width=8 height=8 fill=#004d75 /><rect x=71 y=71 width=8 height=8 fill=#004d75 /><rect x=81 y=61 width=8 height=8 fill=#004d75 /><rect x=91 y=51 width=8 height=8 fill=#004d75 /><rect x=101 y=41 width=8 height=8 fill=#004d75 /><rect x=111 y=111 width=8 height=8 fill=#004d75 /><rect x=121 y=121 width=8 height=8 fill=#004d75 /><rect x=131 y=131 width=8 height=8 fill=#004d75 /><rect x=71 y=41 width=8 height=28 fill=#004d75 /><rect x=81 y=71 width=68 height=8 fill=#004d75 /><rect x=71 y=81 width=8 height=58 fill=#004d75 /><rect x=71 y=01 width=8 height=8 fill=#5aa6d8 /><rect x=71 y=11 width=8 height=8 fill=#5aa6d8 /><rect x=71 y=21 width=8 height=8 fill=#5aa6d8 /><rect x=71 y=31 width=8 height=8 fill=#5aa6d8 /><rect x=01 y=81 width=8 height=8 fill=#a86cb9 /><rect x=11 y=81 width=8 height=8 fill=#a86cb9 /><rect x=21 y=81 width=8 height=8 fill=#a86cb9 /><rect x=31 y=81 width=8 height=8 fill=#a86cb9 /><rect x=41 y=81 width=8 height=8 fill=#a86cb9 /><rect x=51 y=81 width=8 height=8 fill=#a86cb9 /><rect x=61 y=81 width=8 height=8 fill=#a86cb9 /><rect x=61 y=71 width=8 height=8 fill=#f73a3a /><rect x=121 y=61 width=8 height=8 fill=#f73a3a /><rect x=131 y=61 width=8 height=8 fill=#f73a3a /><rect x=141 y=61 width=8 height=8 fill=#f73a3a />

PHP+SVG, 375 Bytes
This Byte count can be reach with compressing the SVG
<?=bzdecompress(base64_decode("QlpoNDFBWSZTWY2177gAASSZgEgA/+c/5B3gMAE5TQVtQeig0AAACU0VNMAAAEYIlEnpMKNlGahso2plh0zoaSEpIkukINaC3RWRF74IvArdRF1FcBXrSTFWXTorp2xvpb3k7FbaV62syISgiBEweHhxtWUmgWCsqqaKSEARyAOAEZJJOwYBQqTAWotSrmEXJbBRTYNhCg4RPaKOUUbAX+Fr4VfIrzzIQQkkJCWfMEEOOISTuDkOzgQzDQDNQKu/4K7AZh8L41DddV8iv2LQOBXv+iugriHAr6sK/IrUV1FeRXMV3FdhW8V9KugrmK8CvOQin+LuSKcKEhG2vfcA"));

HTML, 366 bytes
Sunday got a Base64 answer up while I was still working on this; if s/he chooses to use it then I'll delete this answer.

<img src=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJgAAACYBAMAAADq7D0SAAAAD1BMVEUAqI4ATXWobLlaptj3OjrqGXAuAAAAp0lEQVRo3u3YQQqFMAxFUbeQLbiFbsH9r8k3y8CmTiKm7b2Dwv/CgUAD4jF3TYGBRdgKmRqPCQa28gaMZ20KDGz5DQhnbQoMTG2wAcPR/ScY2HeYVw4zBQYWYDUvbRLWFS/lBxhYhM3bpXzMcWBgEVa5U70cpsDAnkf1FxcwMDAwMLBczP8DAwuwmpc2HzMFBhY8qHlp8zFTYGCdyn8GKrhOYBtjv3QDvf+Zic+8bOsAAAAASUVORK5CYII

If the Base64 string on it's own is a valid answer then that's just 335 bytes:
iVBORw0KGgoAAAANSUhEUgAAAJgAAACYBAMAAADq7D0SAAAAD1BMVEUAqI4ATXWobLlaptj3OjrqGXAuAAAAp0lEQVRo3u3YQQqFMAxFUbeQLbiFbsH9r8k3y8CmTiKm7b2Dwv/CgUAD4jF3TYGBRdgKmRqPCQa28gaMZ20KDGz5DQhnbQoMTG2wAcPR/ScY2HeYVw4zBQYWYDUvbRLWFS/lBxhYhM3bpXzMcWBgEVa5U70cpsDAnkf1FxcwMDAwMLBczP8DAwuwmpc2HzMFBhY8qHlp8zFTYGCdyn8GKrhOYBtjv3QDvf+Zic+8bOsAAAAASUVORK5CYII

Looks like they've chosen to use it.

HTML + Javascript(jQuery) : 474(js)+ 22(HTML) => 496bytes

a=$("table"),a.append("
".repeat(15)),$("tr").append("".repeat(15)),o={g:"#0a8",b:"#057",c:"#5AD",r:"#F33",p:"#A6B"},z="14g,b,",s="7g,c,8g,b,5g,c,9g,b,4g,c,10g,b,3g,c,"+z+"2g,b,11g,b,g,b,12g,2b,3g,3r,6g,r,8b,7p,b,"+z+z+z+"3g,b,10g,b,4g,b,9g,b,5g,b,8g,b",m="",t=s.split(",");for(var i=0;i<t.length;i++)m+=t[i].length>1?t[i].charAt(1).repeat(t[i].match(/(\d+)/g)):t[i].charAt(0);for(i=0;i<225;i++)$("td:eq("+i+")").attr("bgcolor",o[m.charAt(i)]);

HTML + Javascript, 378 bytes

document.write`<canvas id=Y>`
c=Y.getContext`2d`
N=(w,o)=>[...w].map(d=>Number('0x'+d)*10+o)
S=f=>c.fillStyle='#'+f
T=(z,p,s)=>c.fillRect(...N(p,1),...N(s,8))
S('0a8');c.fillRect(0,0,150,150)
U=(f,s)=>{S(f);s.replace(/../g,w=>T(0,w,'00'))}
U('a6b','08182838485868')
U('f33','67c6d6e6')
U('5ad','70717273')
U('057','112233bbccdd778695a47e')
'740278058760'.replace(/(..)(..)/g,T)

Explanation
document.write`<canvas id=Y>`                   // draw a canvas element

c=Y.getContext`2d`                              // Canvas2DContext

N=(w,o)=>[...w].map(d=>Number('0x'+d)*10+o)     // take a string, interpret each letter
                                                // as a hex number and add an offset

S=f=>c.fillStyle='#'+f                          // set global fill color

T=(z,p,s)=>c.fillRect(...N(p,1),...N(s,8))      // fill a rect
                                                // each x and y is (hex digit)*10 + 1,
                                                // each w and h is (hex digit)*10 + 8

S('0a8');c.fillRect(0,0,150,150)                // draw background

U=(f,s)=>{S(f);s.replace(/../g,w=>T(0,w,'00'))} // draw 8x8 squares

U('a6b','08182838485868')                       // magenta squares,  each represented
                                                // as two digits in the string

U('f33','67c6d6e6')                             // orange squares

U('5ad','70717273')                             // light blue squares

U('057','112233bbccdd778695a47e')               // dark blue squares

'740278058760'.replace(/(..)(..)/g,T)           // dark blue rects, each represented
                                                // as four digits in the string

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

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


text:
Rafting Problem (Knapsack variant)
First puzzle from me, suggestions for improvement gladly received!
The scenario is;
You work as a manager for a whitewater rafting company. Every morning, you are given a list of bookings, and you have to sort them into raft loads. Write a program or function in your chosen language that does this for you.
Each raft holds a maximum of n clients, and each booking is for a group of between 1 and n people (inclusive).
The following rules must be observed;

No groups may be split up. If they booked together, they must all be in the same raft.
The number of rafts must be minimised.
Subject to the two preceeding rules, the groups must be spread as equally as possible between the rafts.

Inputs.
The number n (you may assume that this is a positive integer), and the size of all the bookings. This may be an array, list or similar data structure if your language supports such things. All of these will be positive integers between 1 and n. The order of the bookings is not defined, nor is it important.
Output.
A list of the booking numbers, grouped into raft loads. The grouping must be indicated unambiguously, such as;

a list, or array of arrays.
a comma separated list for each raft. Newline between each raft.

How you implement the third rule is up to you, but this could involve finding the average raft occupancy, and minimising deviations from it as much as possible. Here are some test cases.
n  Bookings       Output
6  [2,5]          [5],[2]
4  [1,1,1,1,1]    [1,1,1],[1,1]
6  [2,3,2]        [2,2],[3]
6  [2,3,2,3]      [2,3],[2,3]
6  [2,3,2,3,2]    [2,2,2],[3,3]
12 [10,8,6,4,2]   [10],[8,2],[6,4]
6  [4,4,4]        [4],[4],[4]
12 [12,7,6,6]     [12],[7],[6,6]

Standard rules apply, shortest code wins. Have fun!
Edited;
A suggested way to define as equally as possible for the third rule.
Once the number of rafts r has been determined (subject to the second rule), the average occupancy a can be calculated by summing over the bookings, and dividing by r. For each raft, the deviation from the average occupancy can be found using d(x) = abs(n(x)-a), where n(x) is the number of people in each raft and 1 <= x <= r.
For some continuous, single-valued function f(y), which is strictly positive and has a strictly positive first and non-negative second derivatives for all positive y, we define a non-negative quantity F, as the sum of all the f(d(x)), 1 <= x <= r. Any choice of raft allocation that satisfies the first two rules, and where F is equal to the global minimum will satisfy the third rule also.

For future reference you can post to our sandbox to get feedback on a challenge before you post.

Welcome to Programming Puzzles & Code Golf! This looks like a nice challenge, knowing that its your first challenge. Next time, however, it might be better to post the challenge in the Sandbox first, so people can give suggestions there. Then when you think the challenge is done, you can post it on the main site. Thank you for reading, and have a nice day!

How is as equally as possible measured?

@Dennis; I will put a suggested way to define this in an edit. However if you have a different method, and can justify it for your answer, that is fine.

Leaving things up to the implementation is fine, as long as it's clear what is valid and what not, and your latest edit achieves that imo. I'm a bit surpised that we can't use g(y) = y (second derivate zero) or g(y) = y² (first derviate zero when y = 0) though.

@Dennis: I indended that g(y) = y² be allowed, as the requirement is only for positive y, which excludes y=0 - apologies for not being clearer.

If f(y) = y is disallowed, you should add a test-case where it doesn't give the required result. Because for all the current test-cases I get the same result with f(y) = y and f(y) = y².

@smls; You are right. I have edited to allow a larger class of functions.

I've edited the title to improve searchability, because I suspect this will be used in the future as a dupe target.

Perl 6, 163 158 bytes
{[grep $^n>=*.all.sum,map ->\p{|map {p[0,|$_ Z..^|$_,p]},(1..^p).combinations},$^s.permutations].&{.grep: .map(+*).min}.min({.map((*.sum-$s.sum/$_)**2).sum})}

Try it online!
How it works

map ->\p{|map {p[0,|$_ Z..^|$_,p]},(1..^p).combinations},$^s.permutations
Generates all possible partitions of all permutations of the input array.
grep $^n>=*.all.sum,
Filters the ones where no raft is overbooked.
.&{.grep: .map(+*).min}
Filters the ones where the number of rafts is minimal.
.min({.map((*.sum-$s.sum/$_)**2).sum})}
Gets the first one with minimal ∑(nx-a)2.

-4 bytes thanks to @Pietu1998

Do you need to do .abs if you square the result?

@Pietu1998: I don't, good catch.

Haskell 226 228 234 268 bytes
Naive answer in Haskell
import Data.List
o=map
u=sum
p=foldr(\x t->o([x]:)t++[(x:y):r|(y:r)<-t>>=permutations])[[]]
m x=foldl(\[m,n]x->[m+(x-m)/(n+1),n+1])[0,0]x!!0
a!z=abs$u z-a
s t=(length t,u$o((m$o u t)!)t)
a n=head.sortOn s.filter(all$(<=n).u).p

Or ungolfed
partition' :: [a] -> [[[a]]]
partition' [] = [[]]
partition' (x:xs) = [[x]:ps     | ps <- partition' xs]
                 ++ [(x:p):rest | ps <- partition' xs, (p:rest) <- permutations ps]

-- from Data.Statistics
mean :: [Double] -> Double
mean xs = fst $ foldl (\(m, n) x -> (m+(x-m)/n+1, n+1)) (0, 0) xs

diff :: Double -> [Double] -> Double
diff avg xs = abs $ sum xs - avg

rawScore :: [[Double]] -> Double
rawScore xs = sum . map (diff avg) $ xs where avg = mean . map sum $ xs

score :: [[Double]] -> (Int, Double)
score xs = (length xs, rawScore xs)

-- from Data.Ord
comparing :: (Ord b) => (a -> b) -> a -> a -> Ordering
comparing p x y = compare (p x) (p y)

candidates :: Double -> [Double] -> [[[Double]]]
candidates n xs = filter (all (\ ys -> sum ys <= n)) . partition' $ xs

answer :: Double -> [Double] -> [[Double]]
answer n xs = minimumBy (comparing score) $ candidates n xs

With some test cases
import Text.PrettyPrint.Boxes

testCases :: [(Double, [Double])]
testCases = [(6 , [2,5])
            ,(4 , [1,1,1,1,1])
            ,(6 , [2,3,2])
            ,(6 , [2,3,2,3])
            ,(6 , [2,3,2,3,2])
            ,(12, [10,8,6,4,2])
            ,(6 , [4,4,4])
            ,(12, [12,7,6,6])]

runTests tests = transpose
                 $ ["n", "Bookings", "Output"]
                 : map (\(n, t) -> [ show . floor $ n
                                   , show . map floor $ t
                                   , show . map (map floor) $ a n t]) tests

test = printBox
     . hsep 3 left . map (vcat top) . map (map text) . runTests $ testCases

Where test yields
n    Bookings       Output
6    [2,5]          [[2],[5]]
4    [1,1,1,1]      [[1,1],[1,1,1]]
6    [2,3,2]        [[2,2],[3]]
6    [2,3,2,3]      [[2,3],[2,3]]
6    [2,3,2,3,2]    [[2,2,2],[3,3]]
12   [10,8,6,4,2]   [[10],[8,2],[6,4]]
6    [4,4,4]        [[4],[4],[4]]
12   [12,7,6,6]     [[12],[7],[6,6]]

Edit
Thanks to @flawr and @nimi for advice.
Squashed p a bit.
Shaved off a couple bytes.

You could set s=sum and then use s instead of sum, and perhaps you could also replace fst$ ... with ...!!0.

You can replace minimumBy(c s) with head.sortOn s and remove function c. Also: \t->sum t<=n is (<=n).sum.

@flawr, good suggestion, thanks!

Python3, 224 bytes
def p(c):
 if len(c)==1:yield[c];return
 for s in p(c[1:]):
  for n,u in enumerate(s):yield s[:n]+[[c[0]]+u]+s[n+1:]
  yield[[c[0]]]+s
s=sum
r=lambda n,b:min(p(b),key=lambda c:s(abs(s(x)-s(b)/(s(b)//n+1))for x in c))

With testcases:
tc = [[6,[2,5]],[4,[1,1,1,1,1]],[6,[2,3,2]],[6,[2,3,2,3]],[6,[2,3,2,3,2]],[12,[10,8,6,4,2]],[6,[4,4,4]],[12,[12,7,6,6]]]
for case in tc:
    print(str(case[0]).ljust(3),str(case[1]).ljust(16),"|",r(*case))

How does it work?
The p function simply generates all partitions of a given list (all possible ways to divide it up into sublists). s=sum simply renames the sum function, so the last line does all the work.
r=lambda n,b:min(p(b),key=lambda c:s(abs(s(x)-s(b)/(s(b)//n+1))for x in c))
r=lambda n,b:                                                               Initialize the lambda
                 p(b)                                                       Calculate all possible raft arrangements
                     ,key=lambda c:                                         Map the following lambda onto the list:
                                              s(b)/(s(b)//n+1)              Calculate the ideal average amount of people per raft
                                     abs(s(x)-                )             Calculate how close is the current raft
                                                               for x in c   For each raft in the partition
                                   s(                                    )  Sum it (the sum is a score of how close to ideal the function is),
             min(                                                         ) And find the lowest valued partition.

I'm certain that this can be golfed further, especially the p function, but I worked on this for hours already, so here you go.


text:
Mama Say Mama Sa Mama Coosa
Mama Say Mama Sa Mama Coosa
I'm sure all of you have heard of Michael Jackson and some of you have listened to MJ's song "Wanna be starting something". The line "Mama Say Mama Sa Mama Coosa" is repeated throughout the song.
Specification
In this line, the word "Mama"occurs three times, "Say", "Sa", "Coosa" occurs once. The task is the following: Given the input number of occurrences of the words "Mama", "Say", "Sa", "Coosa", output the number of times MJ can sing "Mama Say Mama Sa Mama Coosa", like in a complete sentence.
Input
Input is a single line with four positive integers denoting the number of times he says the words "Mama", "Say", "Sa","Coosa" respectively .
Output
Output the number of times MJ can sing "Mama Say Mama Sa Mama Coosa"
Shortest code wins.
Testcases
Testcase 1
Input -->  3 1 1 1
Output-->  1

Testcase 2
Input -->  6 1 1 1
Output-->  1

Testcase 3
Input -->  1000 3 2 3
Output-->  2

Testcase 4
Input -->  7 3 4 3
Output-->  2

I am a bit confused by the specification.  It would be nice to include exactly what is being calculated.

Any constraints about the number? Like are they necessary all strictly positive?

@Dada Yes , i updated the question.

Just a note. 1 minute in the sandbox isn't enough time for any feedback.

@LliwTelracs Oh should i delete the question please?

So, you want the minimum of four numbers where the first is divided by three first?

There are already answers so don't delete the question. Next time you should wait for feedback in the sandbox before posting

@JanDvorak Yes only four numbers are allowed, not more not less. Yes the first input number is divided by three.

Updated the question

Jelly, 5 bytes
Ḣ:3«Ṃ

Try it online!
How it works
Ḣ:3«Ṃ  Main link. Argument: [a, b, c, d]

Ḣ      Head; pop and yield a.
 :3    Perform integer division by 3,
    Ṃ  Yield the minimum of [b, c, d].
   «   Take the minimum of a and the result to the right.

Giving you a +1 for :3

@Okx Another 5 byte solution, :1¦3Ṃ, and one can bastardise that one into the 6 byte :-3¦3Ṃ

Python 2, 23 bytes
lambda a,*x:min(a/3,*x)

Try it online!

What does the asterisk before the x do?

Create a function with a variable number of arguments. The first argument becomes a, all remaining ones are stored in the tuple x.

The second time the *x is used it unpacks an array (x) into arguments for  min.

MATL, 9 8 bytes
1 byte saved thanks to @Luis
I7Bh/kX<

Try it at MATL Online
Explanation
        % Implicitly grab input as an array
I       % Push the literal 3 to the stack
7B      % Push 7 and convert to binary ([1, 1, 1]) and push it to the stack
h       % Horizontally concatenate the two to create the array [3 1 1 1]
/       % Perform element-wise division
k       % Round all values towards minus infinity
X<      % Compute the minimum of the resulting array
        % Implicitly display the result

Perl 6, 19 bytes
{min $^a div 3,|@_}

Try it online!
How it works
{                 }  # A lambda.
     $^a             # First argument.
         div 3       # Integer division by 3.
                @_   # All regaining arguments as a list.
        ,      |     # Slipped into the outer list.
 min                 # Smallest number in the list.

The $^a and @_ are in-place parameter declarations for the surrounding block lambda. One is a positional parameter, and the other to a slurpy parameter that takes all remaining positional arguments.

Cubix, 24 bytes
O;@sI3,>I?;^>..^.-!..;;?

Try it here
    O ;
    @ s
I 3 , > I ? ; ^
> . . ^ . - ! .
    . ;
    ; ?

I Read number from the input3, Push 3 onto the stack and integer divide> Redirect to the rightI? Read number from input and test
if 0 (end of input), ; remove from stack. ^ redirect to top face, O@ Output TOS and quit
if positive, - subtract from TOS
? Test.  For 0 and positive ; remove TOS, for negative ;s remove TOS and swap top items on the stack.  This keeps the lowest number at the top.
Follow arrows back to the 2nd I and repeat until done.

MATLAB / Octave, 26 bytes
@(a)min(fix(a./[3 1 1 1]))

Creates an anonymous function named ans which you can then pass the input array as: ans([3 1 1 1])
Online Demo

Mathematica, 18 bytes
⌊#/3⌋~Min~##2&

Pure function taking four integer arguments and returning an integer. Computes the floor of the first argument divided by 3, then finds the minimum of that number and the remaining arguments ##2.

Batch, 71 bytes
@set/am=%1/3
@for %%n in (%*)do @set/a"n=%%n-m,m-=(n>>31)*n
@echo %m%

Unrolling the loop would have been 7 bytes longer.

C#, 62 bytes
Golfed
int i(int a,int b,int c,int d){return new[]{a/3,b,c,d}.Min();}

Pretty self-explanatory I think.

JavaScript (ES6), 30 bytes
a=>Math.min(a[0]/3,...a)|0

Usage
f=a=>Math.min(a[0]/3,...a)|0
f([2,1,1,1])

Output
0

Explanation
This function takes an array as argument, and then feeds all its elements to Math.min as well as the first element devided by three. Since a[0]/3 is smaller than a[0] (because a[0] is guaranteed to be positive), we don't have to remove it from the main array. Math.min returns the minimum value, which is then floored and returned.

You will be given 4 numbers as input and not 3

Oops, cost me 2B to fix

If you take the arguments as a single array parameter then you can save 4 bytes.

PowerShell, 44 bytes
$a,$b=$args;[int]($a/3),$b|measure -mi|% Mi*

Try it online!

R, 26 bytes
As an unnamed function that takes a vector of numbers as the parameter.
function(x)min(x,x[1]%/%3)

Return the min of the parameter and the first item integer divided by 3.
So for an input of 7,8,9,10, it will return the min of 7,8,9,10,2.  This was shorter than dividing the complete vector by c(3,1,1,1)


text:
Your Memory's Leaking
Your task is to write a program that:

Runs indefinitely
Produces no output
Consumes an unbounded amount of memory

Specifications

You must list the implementation used for your program. This is relevant because some implementations might preform optimizations while others do not. For example, the LISP code (defun f () (f)) (f) may or may not consume infinite memory depending on whether the implementation optimizes tail recursion.
Obviously, your program may terminate from running out of memory.

Examples
BF:
+[>+]

Python:
l = []
while True:
    l.append(1)

JavaScript:
l = [];
while (true)
    l.push(1);

C (I'm not sure if this works):
#include <stdio.h>
int main() {
    while (1)
        malloc(1);
}

This is code-golf, so the shortest valid solution (in bytes) wins.

A dup of http://codegolf.stackexchange.com/questions/101709/shortest-program-that-continuously-allocates-memory/101834#101834

Depending on how strictly you interpret things: if a C compiler can prove that code has no effect, it can replace it with anything else that also has no effect. So given an arbitrarily smart compiler, it might not be possible to write an infinite C program with no effect. In practice this is hampered by the fact that none of our compilers can solve the halting problem. Also, malloc is in stdlib.h, not stdio.h.

@ephemient That's why I forced you to specify the implementation. Also, some compilers will already include <stdlib.h> by default.

Some compilers will happen to pull in stdlib.h transitively via stdio.h. That doesn't mean they include stdlib.h by default.

Jelly, 2 bytes
‘ß

Increments and calls itself recursively. As the integer gets bigger, more memory is required to store it.
You can Try it online!, but it's not much to look at.

Wouldn't this cause stack overflow before your computer runs out of memory?

No, Jelly has tail call optimization. This is just a fancy while loop.

Python 3, 16 bytes
i=9
while i:i*=9

As ints in Python3 are only limited by the memory, this will run until there is no more memory available.

Ruby, 15 bytes
i=[];loop{i<<0}

Befunge-98, 1 byte
'

Fills the stack with strings containing '

Java (OpenJDK 9), 75 bytes
interface G{static void main(String[]a){a=new String[1];for(;;)a[0]+=' ';}}

Try it online!

Vim, 13 bytes
qqaa<esc>"Ax@qq@q

This defines a macro, q that appends the letter a to the register A and then calls itself. This results in an infinite loop of making register A bigger and bigger, only limited by memory.

It looks to me like you're missing an <esc> in the macro. This will just output a"Ax@qq@q and exit.

Brain-Flak, 8 bytes
(()){()}

Try it online!

Since the {...} monad keeps track of the value of each run, you could simply do (()){[]} or (()){()} instead.

Bash, 17 bytes
for((;;)){ a+=a;}

Try it online!


text:
Closest Woodall Prime
A Woodall Prime is a prime which can be calculated, given a positive integer n, with n * 2^n - 1.
Your task is to, given a integer k, generate a Woodall Prime with k digits. If no such Woodall Prime exists, you must generate a Woodall Prime with the closest amount of digits. If two primes exist with the same digit count difference, you may use either.
You may assume that there exists no two Woodall Primes with the same amount of digits.
There is no time complexity limit, and you must be able to handle at least the first ten Woodall Primes (you can see them in the OEIS link at the start of the question)
You may write a full program or a function, and you may print or return the output.
Examples:
1 -> 7
4 -> 383
0 -> 7
-100 -> 7
7 -> 383 or 32212254719 (you may pick either of these)
8 -> 32212254719

As this is code-golf, that shortest code wins!
(there are only nine Woodall Primes on the linked OEIS sequence, so you might want to look at this for more Woodall Primes: https://oeis.org/A002234)

Handling negative input seems like a excess requirement, if the input is supposed to be how many digits the output should be. What even does -100 digits mean?

@AdmBorkBork 1 digit is closest to -100 digits. -100 digits isn't possible, and the question asks for the Woodall Prime with the closest amount of digits.

Someone watched numberphile today. :)

In the or scenario do we have to output both separated by or, or are we allowed to pick either or.

@carusocomputing You make pick either, obviousy

@Okx it's not obvious, which is why I asked. Your example says the output for 7 is 383 or 32212254719 someone may take that literally, you should change it to 383 or 32212254719 (pick one).

@carusocomputing It does mention you may use either somewhere else in the question. Well, I've edited it anyways.

Jesus, I am absolutely NOTORIOUS for missing text bits inside of questions, sorry for coming off rude. I didn't see the snippet about either near the top.

"you must be able to handle at least the first ten Woodall Primes" I don't understand what this means for this challenge.

@Fatalize this means you should be able to output at least any of the first ten Woodall Primes.

What does that mean "be able to output"? Time limit? Memory limit?

@Fatalize Your program should simply have the ability to output it without causing errors (eg integer overflow)

Brachylog, 28 26 bytes
:K≜+ℕ~lṗ.+₁~×[İ,J]h:2^₍J≜∧

Try it online!
This is too slow for TIO for inputs bigger than 4.
Explanation
:K                             The list [Input, K]
  ≜                            Assign a value to K (0, then 1, then -1, then 2, etc.)
   +ℕ                          Input + K >= 0
     ~l .                      Output is a number of length (Input + K)
       ṗ.                      Output must be a prime number
         +₁                    Output + 1...
           ~×[İ,J]             ... = İ × J, İ being an integer...
                  h:2^₍J       ... and J = 2^İ
                         ≜∧    Check that it is possible to find a value for İ that satisfies
                                 all of those constraints. If not, go back to the beginning
                                 and try another value for K through backtracking.

We use a common trick in Brachylog for "find the closest X to Y": labeling a completely free variable (which we do when we use ≜ on the list [Input, K] will label it with this pattern: 0, 1, -1, 2, -2, 3, .... Therefore, when backtracking if the value Input + K doesn't work as the number of digits, the next choice we will try will be the next possible closest choice.

Mathematica, 72 bytes
Nearest@<|Thread[w->IntegerLength[w=# 2^#-1&~Array~999~Select~PrimeQ]]|>

Pure function taking an integer as input and returning the set of Woodall primes whose lengths are closest to the input. For example, applying this function to 6 results in {383}, while applying it to 7 yields }{383,32212254719}.
w=# 2^#-1&~Array~999~Select~PrimeQ constructs a list of the first 15 Woodall primes, by testing all numbers of the form n*2^n-1 with n up to 999. <|Thread[w->IntegerLength[w]]|> creates an association taking the number of digits of each of these Woodall primes to the primes themselves. Then Nearest picks out the Woodall primes whose numbers-of-digits are closest to the input.

Perl 6,  71  68 bytes
->\k{({$/ if is-prime $/=2**++$*++$-1}...*.chars>k).min:{abs k-.chars}}

Try it
{({$/ if is-prime $/=2**++$*++$-1}...*.comb>$^k).min:{abs $k-.comb}}

Try it
Expanded:
{         # bare block lambda with parameter ｢$k｣
  (  # sequence of possible candidates

    {
      $/         # use the Woodall number
      if         # but only if
      is-prime(  # this is prime

        $/ =     # store the Woodall number in $/

         2 **    # 2 to the power of
         ++$     # n           ( preincrement of anon state variable )
         *       # times
         ++$     # n           ( preincrement of anon state variable )
         -1      # -1

      )
    }

    ...          # keep generating Woodall primes until:

    *.comb > $^k  # it has more digits than ｢$k｣ (declare ｢$k｣ as a parameter)

  ).min: { abs $k - .comb } # find the nearest one
}


text:
How many Blackjack sequences in that list?
Your task is to find how many distinct Blackjack sequences can be found in an ordered list of 12 cards.
A Blackjack sequence is defined as a sequence of consecutive cards whose sum of points is exactly 21. Points are counted according to the following table:
Symbol | Name  | Points     Symbol | Name  | Points
-------+-------+--------    -------+-------+--------
   2   | Two   | 2             9   | Nine  | 9
   3   | Three | 3             T   | Ten   | 10
   4   | Four  | 4             J   | Jack  | 10
   5   | Five  | 5             Q   | Queen | 10
   6   | Six   | 6             K   | King  | 10
   7   | Seven | 7             A   | Ace   | 1 or 11
   8   | Eight | 8

Input
A 12-character string, using the symbols described above. We do not care about the colors of the cards, so they are not provided.
Example:
K6K6JA3Q4389
Output
The number of distinct Blackjack sequences that can be found in the input string.
Example:
K6K6JA3Q4389 includes two distinct Blackjack sequences:

JA, with the Ace being counted as 11 points (10 + 11 = 21)
A3Q43, with the Ace being counted as 1 point (1 + 3 + 10 + 4 + 3 = 21)

So the answer would be 2.
Rules

Two Blackjack sequences are considered distinct if they contain different cards or the same cards in different orders. If the exact same sequence appears at different positions in the input list, it must be counted only once.
The Blackjack sequences may overlap each other.
Each kind of card may appear up to 12 times in the sequence. (We assume that the cards are picked from at least 3 different decks.)
If no Blackjack sequence can be found in the input string, you must return 0 or any other falsy value.
This is code-golf, so the shortest answer in bytes wins. Standard loopholes are forbidden.

Test cases
The sequences are provided for information purposes, but you're only required to output the number of them.
Input        | Output | Distinct sequences
-------------+--------+--------------------------------------------------------
3282486Q3362 | 0      | (none)
58A24JJ6TK67 | 1      | 8A2
Q745Q745Q745 | 1      | Q74
AAAAAAAAAAAA | 1      | AAAAAAAAAAA
T5AQ26T39QK6 | 2      | AQ, 26T3
JQ4A4427464K | 3      | A442, 44274, 7464
Q74Q74Q74Q74 | 3      | Q74, 74Q, 4Q7
37AQKA3A4758 | 7      | 37A, 37AQ, AQ, AQK, QKA, KA, A3A475
TAQA2JA7AJQA | 10     | TA, TAQ, AQ, QA, A2JA7, 2JA7A, JA, AJ, AJQ, JQA
TAJAQAKAT777 | 13     | TA, TAJ, AJ, JA, JAQ, AQ, QA, QAK, AK, KA, KAT, AT, 777

Hmm, shouldn't the sequences be limited to those of length 5 or less?

@JonathanAllan That's a good point. I think that would be indeed the limit in a casino. But this is no real Blackjack game. Instead, I've chosen to limit the input to 12 cards so that many Aces do not require too much computation time. Does that sound OK?

Next challenge: Find the 12-char string with the most unique Blackjack sequences :D

Limiting the input to 10 cards would have been so much easier...

@Neil Well, that would have made the 'eleven Aces' case impossible, but is there really a significant optimization behind that? I suppose you may have something else in mind.

I had to use a different approach, although @ETHproductions helped me cut my losses to a single byte.

Jelly, 30 29 bytes
1e×5,⁵Ḥ‘
O_48«26%⁴µSeÇ
ẆÇÐfQL

Try It Online! or check out the test suite
How?
Note that, if we always value an ace as 1 then the only valid sums are 21 and 11, the latter being acceptable iff an ace appears in the sequence.
ẆÇÐfQL - Main link: string
Ẇ      - all non-empty contiguous sublists
  Ðf   - filter keep if...
 Ç     -     last link (2) as a monad ...is truthy
    Q  - unique results
     L - length

O_48«26%⁴µSeÇ - Link 2, isBlackjackSubtring: char array  e.g. ['A','2','8','Q']
O             - cast to ordinal values                        [ 65, 50, 56, 81]
 _48          - subtract 48                                   [ 17,  2,  8, 33]
     26       - 26
    «         - minimum (vectorises)                          [ 17,  2,  8, 26]
        ⁴     - 16
       %      - modulo                                        [  1,  2,  8, 10]
         µ    - monadic chain separation (call the result v)
          S   - sum(v)                                        21
            Ç - last link (1) as a monad link_1(v)            [11,21]
           e  - exists in?                                    1

1e×5,⁵Ḥ‘ - Link 1 validSums: value list (where A is 1, and {T,J,Q,K} are 10)
1e       - 1 exists in? (are there any aces? Yields 1 or 0)
  ×5     - multiply by 5 (5 or 0)
     ⁵   - 10
    ,    - pair ([5,10] or [0,10])
      Ḥ  - double ([10,20] or [0,20])
       ‘ - increment ([11,21] or [1,21])
         -                        ^
         -     note: if no ace is in the sequence it's sum can't be 1 anyway

Python 2, 215 bytes
def b(s,a=[],r=range):
 S=map(lambda x:":">x>"1"and int(x)or 10-(x=="A")*9,s)
 for i in r(12):
  for j in r(13):
   if 21in[x*10+sum(S[i:j])for x in r(S[i:j].count(1)+1)]and s[i:j]not in a:a+=s[i:j],
 return len(a)

Comments added:
def b(s,a=[],r=range):                                      # Define the function b and a list, a, which holds all the blackjack sequences
 S=map(lambda x:":">x>"1"and int(x)or 10-(x=="A")*9,s)      # Set S to the score of each card in b
 for i in r(12):                                            # Loop with i from 0 to 11
  for j in r(13):                                           # Loop with j from 0 to 12
   if 21in[x*10+sum(S[i:j])for x in r(S[i:j].count(1)+1)]\  # If 21 is included in all the possible sums that the scores between i and j in S can be
           and s[i:j]not in a:                              # And that sequence is not already included,
               a+=s[i:j],                                   # Append that sequence to a
 return len(a)                                              # Return the amount of elements in a

JavaScript (ES6), 144 138 129 128 126 124 bytes
g=([c,...s],a=[],q=new Set)=>c?g(s,[...a,[,21]].map(([x,y,A])=>[x+=c,y-=+c||(c<'B'?A=1:10),A,y&&y^10*A||q.add(x)]),q):q.size

Old attempt at 128:
s=>(q=new Set,f=s=>s?f(s.slice(1))&f(s.slice(0,-1))&[...s].map(c=>t+=-c||~(c<'B'?A=0:9),t=A=21)|t&&t-10*!A?q:q.add(s):q)(s).size

s.search\A`>-1could be~s.search`A``

@Luke No, actually, because that returns values such as -2, and 1&-2 == 0

True. Maybe set t to 0 in the .slice(0,-1) call (saves 2B)?

@Luke I don't think that would work, as t is a global variable and it would be reset because of the call to f(s.slice(0,-1)). But I found a way around s.search`A`>-1 :-)

I'm curious to see what you have when you're done golfing this. I seem to be stuck at 113 for now.

+c||(c<'B'?A=1:10) could be +c||10-9*(c=="A") for 1B :-)

@Traktor53 That wouldn't work because we need to set the A variable to 1 at the same time to remember that there's at least one Ace in the sequence.

@Arnauld 113?! I've got quite aways to go...

I've posted my solution. It has a lot in common with your answer, but I tried to avoid using a Set.

JavaScript (ES6), 123 bytes

f=
t=>eval("for(s=new Set,i=0;t[i];i++)for(a=0,b=21,j=i;c=t[j++];b&&b-a*10||s.add(t.slice(i,j)))b-=+c||(c>'A'?10:a=1);s.size")
<input oninput=o.textContent=/[^2-9TJQKA]/.test(this.value)?'':f(this.value)><pre id=o>

Great idea, but this returns 0 for AAAAAAAAAAAA rather than 1. (A can simultaneously be 1 and 11)

By combining our two entries you can get s=>eval("q=new Set;for(i=0;s[i];i++)for(t=A=0,j=i;c=s[j++];t==21|t==11&A&&q.add(s.slice(i,j)))t+=+c||(c<'B'?A=1:10);q.size") for 124 bytes

@ETHproductions Starting from 21 still seems to save me a byte.

@ETHproductions ... it does help if I post the correct byte count ...

Python, 134 130 bytes
lambda x:len({x[i:j]for i in range(12)for j in range(13)if sum(min(26,ord(c)-48)%16for c in x[i:j])in([11,21][~('A'in x[i:j]):])})

Try it online!
How?
An unnamed function, taking the string of length 12 as x.
x[i:j] is a slice of the string from the i+1th to the jth character.
Slices are taken such that we have all sublists by traversing from i=0 to i=11 with for i in range(12), for each of which we traverse from j=0 to j=12 with for j in range(13).
(We only need j=i+1 and up, but slices with j<=i are just empty strings, so we can golf off 4 bytes from for j in range(i+1,13))
These are filtered for those with the correct sum...
Valid sums are 11 and 21 if there is an ace in a slice, or just 21 if not. 'A'in x[i:j] gives us this information and ~(v) performs -1-v, which we use to slice [11,21] - thus if an ace is in the sequence we get [11,21][-2:] and if not we get [11,21][-1:], resulting in [11,21] and [21] respectively.
The sum itself needs to treat A as 1, digits as their values, and T, J, Q, and K as 10. This mapping is achieved by first casting to ordinals:
" 2   3   4   5   6   7   8   9   T   J   Q   K   A" (without the spaces) becomes
[50, 51, 52, 53, 54, 55, 56, 57, 84, 74, 81, 75, 65], subtracting 48 to get
[ 2,  3,  4,  5,  6,  7,  8,  9, 36, 26, 33, 27, 17], taking the min with 26 yields
[ 2,  3,  4,  5,  6,  7,  8,  9, 26, 26, 26, 26, 17], and mod (%) sixteen those are
[ 2,  3,  4,  5,  6,  7,  8,  9, 10, 10, 10, 10,  1], as required for the sum, sum(...).
The filtered results are place into a set with {...}, so only the unique results remain and the length, len(...) is the count

05AB1E, 39 38 37 bytes
'A1:vTy‚ydè})ŒvyO¸y1åiDT+ì}21å})¹ŒÏÙg

Try it online!
Explanation
'A1:                  # replace A with 1 in input

v      }              # for each card
 Ty‚                  # pair 10 and the card
    yd                # check if the card is a digit
      è               # use this to index into the pair, giving 10 for JQK
        )             # wrap in list
                      # we now have a list of cards as numbers in range [1 ... 10]

Œv               }    # for each sublist
  yO¸                 # create a list with the sum of the sublist
     y1åi    }        # if the sublist contain 1
         DT+ì         # add sum+10 to the list
              21å     # check if 21 is in that list
                  )   # wrap in list
                      # we now have a list with 1 where the sublist sums to 21 and
                      # 0 otherwise

¹Œ                    # get sublists of the input
  Ï                   # keep only those which sum to 21
   Ù                  # remove duplicates
    g                 # count the number of lists

JavaScript (ES6), 112 bytes
f=(s,x=[k=0])=>s?f(s.slice(1),x,[...s].map(c=>x[t+=+c||10^(c<'B'?a=11:0),b+=c]||t-21&&t-a?0:x[b]=++k,a=b=t=0)):k

This code logic is quite similar to the one used in existing JS answers from ETHproductions and Neil. But it's using a basic array to keep track of the encountered Blackjack sequences rather than a Set.
Formatted and commented
f = (                     // given:
  s,                      //  - s = list of cards
  x = [k = 0]             //  - x = array of Blackjack sequences
) =>                      //  - k = number of distinct Blackjack sequences
  s ?                     // if s is not empty:
    f(                    //   do a recursive call:
      s.slice(1),         //     starting at the next card in the list
      x,                  //     without re-initializing x[]
      [...s].map(         //   for each card 'c' in the list:
        c => x[           //
          t+ =            //   update the total number of points:
            +c ||         //     using the number of the card (for 2 ... 9)
            10 ^ (        //     or using 10 for all other cards
              c < 'B' ?   //     except the Ace which is
                a = 11    //     counted as 1 point and sets 'a' to 11
              :           //     (which means that a total number of points
                0         //     of 11 will be considered valid from now on)
            ),            //
          b += c          //   update the current sequence 'b'
        ] ||              //   if x[b] was previously stored as a Blackjack sequence
        t - 21 &&         //   or the total number of points is not equal to 21
        t - a ?           //   and not equal to 'a':
          0               //     do nothing
        :                 //   else:
          x[b] = ++k,     //     store the current sequence in x[] and increment k
        a = b = t = 0     //   initialization of all variables used in map()
      )                   //
    )                     //
  :                       // else:
    k                     //   return k

Test cases

f=(s,x=[k=0])=>s?f(s.slice(1),x,[...s].map(c=>x[t+=+c||10^(c<'B'?a=11:0),b+=c]||t-21&&t-a?0:x[b]=++k,a=b=t=0)):k

console.log(f('3282486Q3362')) // 0
console.log(f('58A24JJ6TK67')) // 1
console.log(f('Q745Q745Q745')) // 1
console.log(f('AAAAAAAAAAAA')) // 1
console.log(f('T5AQ26T39QK6')) // 2
console.log(f('JQ4A4427464K')) // 3
console.log(f('Q74Q74Q74Q74')) // 3
console.log(f('37AQKA3A4758')) // 7
console.log(f('TAQA2JA7AJQA')) // 10
console.log(f('TAJAQAKAT777')) // 13

I tried double recursion, moving backward through the string, cumulatively calculating each possible string as each character is consumed... and yet the shortest approach is simply to run through each slice. Nice one! (Using a Set appears to be three bytes longer, if I calculated correctly)

05AB1E, 40 39 38 37 36 bytes
-4 Thanks to Emigna
Ç<çJŒÙ'@0:[Ž„èµJuS9:S>D1å2‚T*>sOå½]¾

Try it online!
Ç<ç                                  # decrement characters by 1
   JŒÙ                               # get all unique substrings
      '@0:                           # replace @ (was A) with 0
          [Ž                      ]  # for everything on the stack
            „èµJuS9:                 # replace what was T,J,Q,K with 9
                    S>D              # increment all values
                       1å2‚T*>       # push [11,21] if there was an A, [1,21] otherwise
                              sO     # sum the values of the cards
                                å½   # increment the counter_variable if the sum
                                     # is in the array
                                   ¾ # end loop and push (print) the counter_variable

We need to do the decrement -> substring -> increment thing so that face cards are represented by a single digit number.

Nice way of getting around double digits! You can remove the first S as Ç turns the string into a list of character codes.

Also, "SIPJ" could be „èµJu

@Emigna Thanks. I thought there was a way to do that, but I couldn't find how to use „ in the documentation.

You can save 2 more bytes rewriting it as Ç<çJŒÙ'@0:)vy„èµJuS9:S>D1å2‚T*>sOå}O Then you're 1 byte shorter than my answer :)

@Emigna This is the same byte count and is more like my original.

You can still replace 5*T‚· with 2‚T* to save another byte (while keeping your looping).

Bash + Unix utilities, 145 142 141 bytes
for n in {9..155}
{ echo ${1:n%12:n/12};}|sort -u|sed 's/\(.\)/+\1/g;s/A/{1,11}/g;s/[J-T]/10/g;s/^/eval echo $[0/;s/$/]/'|sh|grep -c '\<21\>'

Try it online!
Test runs:
for x in 3282486Q3362 58A24JJ6TK67 Q745Q745Q745 AAAAAAAAAAAA T5AQ26T39QK6 JQ4A4427464K Q74Q74Q74Q74 37AQKA3A4758 TAQA2JA7AJQA TAJAQAKAT777
  do
    echo -n "$x "
    ./21 "$x"
  done

3282486Q3362 0
58A24JJ6TK67 1
Q745Q745Q745 1
AAAAAAAAAAAA 1
T5AQ26T39QK6 2
JQ4A4427464K 3
Q74Q74Q74Q74 3
37AQKA3A4758 7
TAQA2JA7AJQA 10
TAJAQAKAT777 13

PHP, 240 bytes
$a=str_split($argv[1]);foreach($a as$k=>$v)$n[$k]=$v=='A'?1:($v==0?10:$v);for($i=0;$i<=$k;$i++){$s=$a[$i];$r=$n[$i];for($j=$i+1;$j<=$k;$j++){$s.=$a[$j];$r+=$n[$j];if ($r==21||($r==11&&stristr($s,'A')))$f[]=$s;}}echo count(array_unique($f));

Ungolfed :
$a = str_split($argv[1]);
foreach ($a as $k=>$v)
    $n[$k] = $v == 'A' ? 1 : ($v == 0 ? 10 : $v);
for ($i=0; $i<=$k; $i++) {
    $s = $a[$i];
    $r = $n[$i];
    for ($j=$i+1; $j<=$k; $j++) {
        $s .= $a[$j];
        $r += $n[$j];
        if ($r == 21 || ($r == 11 && stristr($s,'A')) )
            $f[] = $s;
    }
}
echo count(array_unique($f));

Try it here!

Weird, I could have sworn it worked on my local tests, but it seems you're right. Anyway; the problem came from the fact that $i wasn't declared. Added 4 bytes and it works perfectly.