text:
The Camouflage Color Changing Chameleon Challenge
Chameleon challenges are a bad thing, apparently. Too bad, chameleons are beautiful creatures. Time for a change!

As we all know, many chameleons posses a remarkable ability to blend in with their surroundings by changing the color of their skin. Which is also the objective of this challenge.
Challenge
Imagine a square of nine pixels. Eight pixels are the surroundings. At the center is the chameleon.
Like this:
The chameleon naturally tries to blend in with its surroundings. It does so by changing its color to the average of that of the surrounding pixels. So, in this case, the chameleon would change its color to .
Objective
Given the colors of the surrounding pixels, output the color of the chameleon.
The color of the chameleon is defined as the total of all red, green and blue in the pixels ÷ 8.
Input
An array of color values for the eight surrounding pixels, starting at the top left and continuing clockwise, like this:
[[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>]]

You may choose to receive input in a different form, as long as it consists of eight triples of decimal numbers 0-255.
If you receive input in a different form, numbers must either be of a consistent length or have a non-numeric separator between them. Triples must have a separating character unless they are 0-padded to 9 digits. (E.g. 044200255044200255044200255044200255044200255044200255044200255044200255 is valid, so are 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 and 44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255, but 4420025544200255442002554420025544200255442002554420025544200255 is not.)
Output
An array / string / etc. containing the colors of the center pixel (in decimal), like this:
[<red>,<green>,<blue>]

In case you output something other than an array: Numbers must either be of a consistent length or have a non-numeric separator between them. (E.g. 044200255 is valid, so is 44 200 255, but 44200255 is not.)
The numbers may not contain decimal points, so e.g. 44.0 200 255.0 is invalid.
Rounding
Output must be rounded to the nearest integer. (Halves must be rounded up.) E.g., if the sum of all red is 1620, you must output 203, not 202 or 202.5.
Examples
Pictures are for illustration only. The middle pixel is the output, the surrounding pixels are the input.
Input:
[[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200]]

Output:
[200,200,200]

Input:
[[0,0,0],[255,255,255],[0,0,0],[255,255,255],[255,255,255],[0,0,0],[255,255,255],[0,0,0]]

Output:
[128,128,128]

Input:
[[0,200,200],[200,0,200],[200,200,0],[60,200,0],[200,0,200],[0,200,220],[2,200,0],[0,0,0]]

Output:
[83,125,103]

Input:
[[0,56,58],[65,0,200],[33,200,0],[60,33,0],[98,0,200],[0,28,220],[2,200,0],[99,0,5]]

Output:
[45,65,85]

Submissions can be a full program or a function. Standard I/O and loophole rules apply.

The average of colors ain't the average of their RGB values.

@LeakyNun Thanks for the link. It won't really matter for this challenge, but I'll keep it in mind should I do a something similar in the future.

Funnily enough, I think this is a bit of a chameleon question for handling rounding.

"as long as it consists of eight triples of decimal numbers 0-255" Can it be in binary? Unary?

Also, can I transpose it beforehand?

@LeakyNun By "decimal" I mean the input must be in base 10. (It's pretty much the same as the output format.) The wording could have been more clear perhaps.

@LeakyNun I added a bunch of input examples.

Is it okay if the output is like [128.0,128,0,128,0]?

@LeakyNun interestingly enough, if you work with colors represented as float vectors in unity shaders, the gamma correction is already handled for you.

@R. Kap Is that an array or a string? In case it's an array: no, it should only contain the requested numbers (and there should be no decimal points in them). In case it's a string: I'm going to clarify the rules that separators aren't allowed to contain digits.

@user2428118 I meant if it was allowed for floating points to be output, i.e. if something like [128.0,128.0,128.0] was allowed. My mistake in the typo of my previous comment.

@R.Kap I've updated the rules to explicitly state decimal points in the output aren't allowed.

MATL, 8 4 bytes
YmYo

Try it online!
4 bytes saved thanks to beaker!
Explanation:
Ym          "Get the average of each column
  Yo        "And round up

I like the abuse of the python array syntax! You can replace s8/ with Xm (i.e mean down the columns). Also you may be able to specify input as 3 x 8 to begin with and get rid of the 3e!

Yeah, YmYo should do it... just take the input as [[R,G,B];[R,G,B];...] with semicolons between the RGB rows.

@beaker Woah! Thanks!

does Yo round up, or round to closest with ties being rounded up? The challenge wants the latter.

@JanDvorak It rounds to the nearest integer (up or down) http://matl.tryitonline.net/#code=YApZbwpEVF0&input=MAowLjI1CjAuNQowLjc1CjE

Python, 38 bytes
lambda l:[sum(r)+4>>3for r in zip(*l)]

Rounds the average (towards the nearest integer, with halves rounding up) by adding 4 to the sum, then floor-dividing by 8 via the bit-shift >>3.

Jelly, 5 bytes
S+4:8

Test suite. (Slightly modified so as to verify all testcases at once.)
S+4:8
S      sum (vectorized)
 +4    add 4
   :8  floor division by 8

C, 151 123 103 91
Requires 24 parameters passed to the program, in the order R G B R G B ... and outputs the triplet R G B without a newline.
i,t;main(c,v)char**v;{for(i=0;t=4,i++<3;printf("%d ",t/8))for(c=i;c<24;c+=3)t+=atoi(v[c]);}

main(c,v)char**v;{ to save 2 bytes? Also +1 for <3 in source code!

JavaScript, 75 64 55 bytes
a=>a.reduce((p,c)=>p.map((e,i)=>e+c[i])).map(x=>x+4>>3)

A JavaScript answer to get you started.
Edit: Saved 11 bytes thanks to Dendrobium, and another  9 thanks to Neil.

55 bytes: a=>a.reduce((p,c)=>p.map((e,i)=>e+c[i])).map(x=>x+7>>3)

@Dendrobium [[0,200,200],[200,0,200],[200,200,0],[60,200,0],[200,0,200],[0,200,220],[2,200,0],[0,0,7]] yields 83, 125, 104 instead of 83, 125, 103 with your code.

Ah, misread the question, thought it was supposed to ceil. 64 bytes: a=>a.reduce((p,c)=>p.map((e,i)=>e+c[i])).map(x=>(x/8).toFixed())

x+4>>3 should round correctly.

Pyth, 8 bytes
m.R.Od0C

Test suite.
m.R.Od0C     input: Q
m.R.Od0CQ    implicit arguments
        Q    input
       C     transpose
m    d       for each:
   .O            take average
 .R   0          round off

Pyke, 7 bytes
,FsOO8f

Try it here!

J, 11 bytes
0.5<.@++/%#

Takes the input as an 8x3 array where each row is an RGB value
Explanation
0.5<.@++/%#  Input: a
          #  Count the number of rows
       +/    Sum along the columns
         %   Divide each sum by the count to get the averages
0.5   +      Add 0.5 to each average
   <.@       Floor each value and return

Lisp - 180 179 bytes
EDIT: Formatted for further golfing.
(defun a(l)(/(apply #'+ l)(length l)))(defun r(a)(if(integerp(* a 2))(ceiling a)(round a)))(defun c(s)(mapcar(lambda(i)(r(sqrt(a(mapcar(lambda(x)(expt(nth i x)2))s)))))'(0 1 2)))

Does it the correct way, I guess. Untested.

a is just average
r is this challenge's proper rounding, since Lisp round rounds to the nearest even integer
c does the real work, taking in input in the format
    '((R G B) (R G B) (R G B) (R G B) (R G B) (R G B) (R G B) (R G B)), and returning a '(R G B) list containg the answer.

Nim, 134 126 115 108 78 bytes
import math,future
x=>lc[(lc[x[j][i]|(j<-0..7),int].sum+4)shr 3|(i<-0..2),int]

Defines an anonymous procedure, which requires the input passed in as a double-nested sequence and outputs as a 3-element array. The procedure can only be used as an argument to another procedure; to test, use the following wrapper:
import math,future
import strutils
proc test(x: seq[seq[int]] -> seq[int]) =
 echo x(#[ Insert your input here ]#)
test(x=>lc[(lc[x[j][i]|(j<-0..7),int].sum+4)shr 3|(i<-0..2),int])

A Nim sequence is an array with @ in front, like @[1, 2, 3]. An input to this procedure could therefore be:
@[@[0,0,0],@[255,255,255],@[0,0,0],@[255,255,255],@[255,255,255],@[0,0,0],@[255,255,255],@[0,0,0]]

Runic Enchantments, 41 bytes
>iRi+ i+ i+ i+ i+ i+ i+8,'rA' q$;
>iU
>iU

Try it online!
Utilizes 3 instruction pointers to parse the input in the correct order (as the input values are always in the order RGB, RGB,...) and as long as each of the three IPs don't merge, and don't advance to the next read input command too early (hence all the spaces), it works out and saves bytes over having to continuously rotate the stack to keep the correct value on top in order to calculate the sums.
Technically this code contains an error in correctly rounding x.5 values for some inputs, but this is due to the default rounding method used by C#, which is to round to the nearest event number, rather than upwards and is due to issues in floating point accuracy loss, and I was unaware of this issue prior to writing this answer and checking the test cases. This will be fixed in a future build, along with a few other things such as this unhandled exception.
In the meantime, this modification makes the necessary adjustment.

Japt v2.0a0, 8 7 bytes
y_x÷8 r

Try it
y_x÷8 c     :Implicit input of 2D array
y           :Transpose
 _          :Map
  x         :  Reduce by addition
   ÷8       :  Divide by 8
      r     :  Round

Forth (gforth), 65 bytes
: f 3. do 8. do 3 j - i * 2 + roll loop 4 8. do + loop 8 / loop ;

Try it online!
Takes input as stack arguments (r g b order)
Explanation
For each of the 3 color channels:

move all the numbers of that channel to the top of the stack
add them together
add 4 (to handle rounding)
divide by 8

Code Explanation
: f            \ start new word definition
  3. do        \ start a counted loop from 0 to 2
    8. do      \ start a counted loop from 0 to 7
      3 j -    \ get the offset of the channel
      i * 2 +  \ get the absolute position of the channel value
      roll     \ move the value to the top of the stack
    loop       \ end the inner loop
    4          \ add 4 to the top of the stack
    8. do      \ loop from 0 to 7
      +        \ add the top two stack numbers
    loop       \ end loop. (Result on top of stack with be sum of values for channel + 4)
    8 /        \ divide by 8
  loop         \ end outer loop
;              \ end word definition

Husk, 8 bytes
mȯ÷8+4ΣT

Try it online! Transposes the array and does the usual transformation.


text:
Duplicate & switch case
The goal is, having taken a string as input, duplicate each latin letter and "toggle" its case (i.e. uppercase becomes lowercase and vice-versa).
Example inputs & outputs:
Input      Output
bad        bBaAdD
Nice       NniIcCeE
T e S t    Tt eE Ss tT
s E t      sS Ee tT
1!1!1st!   1!1!1sStT!
n00b       nN00bB
(e.g.)     (eE.gG.)
H3l|@!     Hh3lL|@!

The input consists of printable ASCII symbols.
You shouldn't duplicate non-latin letters, numbers, special chars.

This is a very nice, simple-but-not-trivial challenge.

Jelly, 5 bytes
żŒsQ€

Try it online!
How it works
żŒsQ€  Main link. Argument: s (string)

 Œs    Yield s with swapped case.
ż      Zip s with the result.
   Q€  Unique each; deduplicate each pair of characters.

Python, 56 54 bytes
lambda s:''.join(c+c.swapcase()*c.isalpha()for c in s)

Test it on Ideone.

Dang! Out golfed me by 4 bytes...

How does this maintain the non-letter characters? I'd think they'd show up as empty strings.

@atlasologist As you can see on Ideone, they do not. * has higher precedence than +, so it only affects the c with swapped case.

Ohh, okay, I didn't think of it like that. Nice.

JavaScript ES6, 70 68 66 64 bytes
Saved 2 bytes thanks to @Kevin Lau - not Kenny
Saved 2 bytes thanks to @Cᴏɴᴏʀ O'Bʀɪᴇɴ
s=>s.replace(/[A-Z]/gi,l=>l+l[`to${l<"a"?"Low":"Upp"}erCase`]())

Explanation
This uses a really hacky:
l[`to${l<"a"?"Low":"Upp"}erCase`]()

which ungolfed is:
l[`to${
   l < "a" ?
   "Low" :
   "Upp"
}erCase`]()

Basically l < "a" checks if the code point of the letter is less then the code point of a (therefore being an uppercase letter). If it is it'll do to + Low + erCase which becomed l['toLowerCase']() and makes the character lowercase. ` quotes allow string formatting so essentially you can think of:
`to${l < "a" ?"Low" : "Upp"}erCase`

as: "to" + (l<"a" ? "Low" : "Upp") + "erCase" which generates the function to call (make the string upper or lower case). We put this in square brackets [ ... ] which lets us access a property given its name as a string. This returns the appropriate function and then we just call it.

/[A-Z]/gi is a shorter regex :3

@KevinLau-notKenny oh nice catch, thanks!

to${l<"a"?"Lower":"Upper"}Case to to${l<"a"?"Low":"Upp"}erCase

@CᴏɴᴏʀO'Bʀɪᴇɴ oh nice, thanks!

l[`to${l<"a"?"Low":"Upp"}erCase`]() I think we have a new definition of evil.

That toUpperCase() trick is really clever. +1

Ruby, 37 33 (30 +  -p flag) bytes
swapcase to the rescue! Sort of. -4 bytes from @Lynn.
gsub(/[a-z]/i){$&+$&.swapcase}

gsub(/[a-z]/i){$&+$&.swapcase} plus the p flag is 31 bytes.

@Lynn I believe consensus was edit difference needed from default script, so the p flag is (space)-p aka 3 bytes.

C, 63 60 bytes
f(char*s){for(;*s;s++)isalpha(putchar(*s))&&putchar(32^*s);}

Uses the fact that 'a' XOR 32 == 'A', etc.
Three bytes saved thanks to FryAmTheEggman.

you can move the s++ in the last putchar (&&putchar(32^*s++))  to save one byte

I think you can replace && with *, can't you?

I’m pretty sure both of those don’t work, if I think about how &&’s short-circuiting behaviour works.

f(char*s){isalpha(putchar(*s))&&putchar(32^*s);*s&&f(1+s);} recursive?

f(char*s){*s&&f(1+s,isalpha(putchar(*s))&&putchar(32^*s));} recursive?

CJam, 11 bytes
l_el_eu.+.|

Test it here.
Explanation
l      e# Read input.
_el    e# Duplicate, convert to lower case.
_eu    e# Duplicate, convert to upper case.
.+     e# Concatenate the two characters in matching positions from those two
       e# strings. E.g. "ab!" "AB!" would give ["aA" "bB" "!!"].
       e# For each character from the original string and the corresponding
.|     e# string from this list, take the set union (which eliminates duplicates
       e# and keeps the order the values appear in from left to right, so that
       e# the original case of each letter comes first).

Pyth, 7 bytes
sm{+dr2

Test suite.
sm{+dr2    input: Q
sm{+dr2dQ  implicit arguments

        Q  input
 m         for each character as d:
     r2d       swapcase
   +d          prepend d
  {            deduplicate
s          join as string

Haha, that's really fast :D

Python 3.5, 60 56 bytes:
for i in input():print(end=i+i.swapcase()[:i.isalpha()])

A full program. Will try to golf more.
Try It Online! (Ideone)

Haskell, 73 bytes
l=['a'..'z']
u=['A'..]
(>>= \c->c:maybe""pure(lookup c$zip l u++zip u l))

Cheddar, 118 104 bytes
(s)->s.chars.map((i)->{if String.letters has i.lower{if i<"a"{i+i.lower}else{i+i.upper}}else{i}}).join()

First real Cheddar answer!!! This is a lot less climactic than I thought it would be... ;_;
Works with release 1.0.0-beta.9, non-competing.

As you can tell I didn't design cheddar to be golfy :/
Ungolfed:
(str) -> str.chars.map(
    (i) -> {
        if String.letters has i {
            if i < "a" { // Check char code, meaning it's upper case if true
                i+i.lower
            }
            else {
                i+i.upper
            }
        } else {
            i
        }
    }
).join()

Usage:
var doThing = <code here>;
doThing("input...");

Update: 7/14/16 I've finished ternaries making this come down to 84 bytes
Cheddar, 84 bytes
(s)->s.chars.map((i)->String.letters has i.lower?i<"a"?i+i.lower:i+i.upper:i).join()

works as of version v1.0.0-beta.14

Yay! We've been waiting for this moment for a long time!

With one or two method name changes, is also valid Sidef

@cat o_o the similarity is unsettling

Well, they're both influenced by Perl, Perl 6, Ruby, Python, etc, so it's not that surprising :P

@cat oh no no no no no, cheddar was not influenced by python

@Downgoat xD I meant JavaScript because Sidef wasn't influenced (much) by Python either -- more coffee pls

@Downgoat ewwwww python. Also I love these lambdas with implicit returns

Retina, 28 27 21 bytes
Those are tabs, not spaces.
.
$&  $&
T`lL    p`Ll_`  .
Try it online
Thanks for the suggestions everyone.

The spaces are eaten by SE.

[A-Za-z] -> i\[A-Z]`

Martin and I were talking in chat, and we came up with: http://retina.tryitonline.net/#code=LgokJsK2JCYKVGBsTMK2cGBMbF9gwrYu&input=YmEgZDEhenp6

@FryAmTheEggman Ah, I forgot about _. I'm going to use tabs so I can test all test cases at once, though.

You can build a test suite by using per-line mode and a group! http://retina.tryitonline.net/#code=JShHYAouCiQmwrYkJgpUYGxMwrZwYExsX2DCti4&input=YmFkCk5pY2UKVCBlIFMgdApzIEUgdAoxITEhMXN0IQpuMDBiIAooZS5nLikKSDNsfEAh

@FryAmTheEggman Sure, but it's not golfed. :P

But the test suite doesn't have to be golfed :P Just leaving a note saying "the first line makes it run separately on each line" is usually good enough. Here, it would save you the craziness of tab characters.

@FryAmTheEggman I'm on Team Tabs. Sorry.

C, 87 80
Pass a string as input to f() and the output is written to STDOUT. The string is not modified.
f(char*v){for(;*v;++v)putchar(*v),isalpha(*v)?putchar(*v-32+64*!islower(*v)):0;}

Can you provide a way to try it online?

@aloisdg Try http://ideone.com

sed, 30 bytes
29 bytes code + 1 byte parameter -r
s/([a-z])|([A-Z])/&\u\1\l\2/g

Usage:
echo -e 'bad\nNice\nT e S t\ns E t\n1!1!1st!\nn00b\n(e.g.)\nH3l|@!' |\
sed -r 's/([a-z])|([A-Z])/&\u\1\l\2/g'

Ruby, 31+1=32 30+1=31 bytes
With the -p flag, run
gsub(/(?<=(.))/){$1.swapcase!}

Takes advantage of the fact that swapcase! will return nil on anything but an ASCII letter, which translates to an empty string when returned out of the gsub block. @Jordan saved a byte by capturing the previous character in a look-behind.

Matching with // and then using $`[-1] is clever.

I managed to shave off six bytes with lookbehind: gsub(/(?<=(.))/){$1.swapcase!}. Same basic concept, though, so feel free to use it.

Cool! That looks one byte shorter to me.

Er, yes, one byte. I think I had some extra code in there to test that I accidentally counted.

There is no need to use the self-modifying version of .swapcase!. (I mean, remove the !.)

No, that part's still necessary to avoid duplicating non-alphabet characters.

J, 31 29 bytes
[:;]<@~."1@,.tolower,.toupper

Explanation
[:;]<@~."1@,.tolower,.toupper  Input: s
                      toupper  Convert s to all uppercase
             tolower           Convert s to all lowercase
                    ,.         Join them as columns in a 2d array
   ]                           Identity function, get s
           ,.                  Prepend s as a column to the 2d array
      ~."1@                    Take the unique chars on each row
    <@                         Box them
[:;                            Unbox the list of boxes and join their contents and return

Haskell, 121, 101, 85, 82
import Data.Char
g n|isLower n=toUpper n|1<2=toLower n
(>>= \x->x:[g x|isAlpha x])

By replacing the if-then-else by guards, you can save 15 bytes or so. And isLower is shorter than the construct with elem, for 5 bytes more.

>>= is concatMap (or concat.map) with arguments flipped: f n = n >>= (\x->if isAlpha x then[x,r x]else[x]). You can go pointfree and omit the function name and replace the definition of f with (>>= \x->if isAlpha x then[x,r x]else[x]).

Instead of otherwise you can use any expression that evaluates to True, e.g. 1<2. You can replace the if .. then .. else with a list comprehension: \x->[x]++[g x|isAlpha x]. Oh, and there's a bug: the second toUpper in g must be a toLower.

Oh, one more: [x]++ is x:.

Perl, 36 bytes (35 + -n flag)
s/[a-z]/$&.(ord$&<97?lc$&:uc$&)/ige

(-p tag needed)
(-2 bytes thanks to @Dom Hasting)
Short explanation:
ord returns the numeric value of a char. ord(any lower case) >= 97, and ord(any upper case) <= 90).
Run with :
perl -pe 's/[a-z]/$&.(ord$&<97?lc$&:uc$&)/ige'

You still need to use /i or your regexp will match several codepoints between letters.

@OlegV.Volkov oh right, thanks, answer edited.

Got it down one more byte, using your method: Try it online!

R, 191 187 168 156 98 99 bytes
99 bytes due to improvements fro Giuseppe and MickyT.
paste0(x<-unlist(strsplit(readline(),"")),gsub("[^A-Za-z]","",chartr("a-zA-Z","A-Za-z",x)),collapse="")

98 bytes -- maybe sometime next year, we can find another golf of this, hahaha.

I hate to be the bearer of bad new, but it fails on test cases with spaces.  readline() can be used, but it will cost a byte

@MickyT thanks, fixed now.

@MickyT scan will work with input given wrapped in quotes (as is often the case for command-line arguments in other languages)

@Giuseppe Sorry I didn't realise that.  I just thought it automatically split on whitespace unless you specify a non whitespace character.  Sorry rturnbull

05AB1E, 7 bytes
Code:
vyyš«Ù?

Explanation:
v       # For each in input.
 yyš    # Push y and y swapcased.
    «Ù  # Concatentate and uniquify.
      ? # Print without a newline.

Uses the CP-1252 encoding. Try it online!

Maybe you could provide a link to the interpreter?

@nicael It IS linked... It's right there on github.

So no online interpreter? :(

@nicael Then download it, and run it. There doesn't have to be an online interpreter, just an interpreter.

@nicael Yeah, there is no online interpreter available yet :(. The offline version should work though.

@mbo I'm not saying it doesn't, I was just wondering if there is one. Neither I was implying that the off-line interpreters are bad.

Pyke, 8 6 bytes
FDl4+}

Try it here!

V, 21 bytes
Try it online!
Too many bytes...
Ó./°ò
Íá/°°
Îlg~lÎHògJ

Actually, 8 bytes
`;Öo╔`MΣ

Try it online!
Explanation:
`;Öo╔`MΣ
`;Öo╔`M   for each character in input:
 ;          duplicate the character
  Ö         swap case
   o        append to original character
    ╔       remove duplicated characters
       Σ  concatenate

MATL, 11 9 bytes
tYov"@uv!

Try it Online
Explanation
        % Implicitly grab input as string
t       % Duplicate the input
Yo      % Swap case of all characters
v       % Vertically concatenate the original and swap-cased versions
"       % For each column (letter in the original)
  @u    % Compute the unique values (without sorting)
  v!    % Vertically concatenate with the existing output and transpose
        % Implicit end of for loop and implicit display

Common Lisp (Lispworks), 262 bytes
(defun f(s)(let((b""))(dotimes(i(length s))(if(lower-case-p(elt s i))(progn #1=(setf b(concatenate 'string b(string #2=(elt s i))))(setf b(concatenate 'string b(string(char-upcase #2#)))))(progn #1#(setf b(concatenate 'string b(string(char-downcase #2#)))))))b))

ungolfed:
(defun f (s)
  (let ((b ""))
    (dotimes (i (length s))
      (if (lower-case-p (elt s i))
          (progn
           #1=(setf b (concatenate 'string b (string #2=(elt s i))))
           (setf b (concatenate 'string b (string (char-upcase #2#)))))
        (progn
          #1#
          (setf b (concatenate 'string b (string (char-downcase #2#)))))))
    b))

Usage:
CL-USER 1 > (f "abc")
"aAbBcC"

CL-USER 2 > (f "bad")
"bBaAdD"

This might be smaller if the input is coerced into a list and append is used instead of (concatenate 'string ...)

Invalid because It duplicates spaces. :r

You can (coerce (apply 'nconc (map... over string where map collects a list of list of chars. I reduced it to 162 bytes Try It Online

Perl, 28 22 21 bytes (20 + -p flag)
s/[a-z]/$&.$&^$"/ige

I imagine you can save a byte by using $" instead of ' ', but I haven't tested.

@msh210, nice! How could I forget to check perlvar for default strings? Thanks!

Not sure if it's a version change or something, but it seems . has higher precedence than ^ resulting in slightly wrong output, but you can combine \K and capturing match for the 19 bytes and valid output: Try it online!

Just realised you don't need to /i any more with \pl for another -1!

Stax, 7 6 bytes
Thanks to @recursive for a byte saved!
┤§ÆP♦■

Run and debug it at staxlang.xyz! (link is to unpacked version)
Unpacked (7 bytes):
c:~\{um

Explanation:
c:~\{um
c          Copy the top element of the stack (the input, in this case).
 :~        Switch case of each letter in the copy.
   \       Zip. This produces an array of two-character strings.
    { m    Map a block over this array of two-character strings.
     u       Get all unique elements.
           Implicit concatenate and print.

Thanks for giving stax a try.  One easy improvement you can make is to use u instead of :g.  It will get all the unique elements in an array, which is exactly what you want in this case.  Other than that, this looks well golfed.

@recursive Thanks! Forgot about that one :/ Will edit in soon.

Doesn't work for 123. You may need to change the format for all inputs (i.e. quote them). The link is also broken. You need to replace m=11 with m=2. There is a PPCG post generating button on staxlang.xyz so you may want to use that one.

@WeijunZhou Thanks, fixed!

Python, 59 bytes
lambda s:''.join((x,x+x.swapcase())[x.isalpha()]for x in s)

Edited to fix repeating non-alphabetic characters

Julia, 40 bytes
!s=[print(c,isalpha(c)?c$' ':"")for c=s]

Try it online!

not s is (list comprehension) okay, Julia...

C#, 82 71 bytes
s=>string.Concat(s.Select(c=>c+(char.IsLetter(c)?(char)(c^32)+"":"")));

C# lambda where the input and the output are string. Try it online.
11 bytes thanks to @Lynn trick.

PHP 4.1, 57 bytes
This code assumes access through a web server (Apache, for example), using the default configuration.
You can pass the string by sending the key S by any means (POST, GET, COOKIE, SESSION...).
<?for($i=0;$c=$S[$i++];)echo$c,ctype_alpha($c)?$c^' ':'';

Java 8, 105 104 80 bytes
a->{for(char c:a)System.out.print(c+(c>64&c<91|c>96&c<123?(char)(c^32)+"":""));}

Explanation:
Try it here.
a->{                          // Method with character-array parameter and no return-type
  for(char c:a)               //  For each character in the input:
    System.out.print(c        //   Print the current character
     +(c>64&c<91|c>96&c<123?  //   And if it's a letter:
       (char)(c^32)+""        //    Print the letter again with reversed case
      :                       //   Else:
       ""));}                 //    Print nothing more

T-SQL, 244
The byte total includes a one-byte string.  Replace the example input string "Q" with the string you want to try.
DECLARE @I VARCHAR(MAX)='Q',@O VARCHAR(MAX)='',@ CHAR #:SELECT @=LEFT(@I,1),@O+=@+CASE WHEN @ LIKE'[A-Za-z]'COLLATE Thai_BIN THEN CASE WHEN ASCII(@)/13IN(5,6)THEN LOWER(@)ELSE UPPER(@)END ELSE''END,@I=STUFF(@I,1,1,'')IF LEN(@I)>0GOTO # PRINT @O

This script works in SQL Server 2008 R2, although you can try it in SQL Server 2016 here.  This SQL works by iterating through the characters in the input string @I, checking each character using a short-named collation and ASCII codes.  When one character is processed, the result is added to the output string @O and removed from @I.

Japt v2.0a0, 8 bytes
r\lÈ+c^H

Try it

Explanation
r            :Replace
 \l          :Regex /[a-z]/gi
   È         :Pass each match X through a function
    +        :  Append
    c        :  The charcode of X
     ^       :  Bitwise XORed
       H     :  With 32

str, 6 bytes
d#S:#q

Try it online!
Explanation
d#S:#q
          over each character:
d         duplicate
 #S       swapcase
   :      concatenate
    #q    uniq-ify string

C, 62 bytes
Function that reads from stdin and writes to stdout:
f(c){while(c=getchar())printf(isalpha(c)?"%c%c":"%c",c,c^32);}

Erlang, 106 bytes
f(S)->G=string,lists:flatten([case G:to_upper(C)==G:to_lower(C)of true->C;false->[C,C bxor 32]end||C<-S]).

Uses Lynn's XOR trick to toggle the case.

Gema, 37 characters
<J>=$1@upcase{$1}
<K>=$1@downcase{$1}

Sample run:
bash-4.3$ gema '<J>=$1@upcase{$1};<K>=$1@downcase{$1}' <<< 'H3l|@!'
Hh3lL|@!

PowerShell, 102 Bytes
-join([char[]]$args[0]|%{$_;if($_-cmatch'[A-Z]'){"$_".ToLower()}if($_-cmatch'[a-z]'){"$_".ToUpper()}})

Run the script with an argument like so:
PS C:\PretendDirectory> .\DupeCase.ps1 "Hello World ?!!1"
HheElLlLoO WwoOrRlLdD ?!!1

Ungolfed:
-join([char[]]$args[0] | % {
    $_
    if($_-cmatch'[A-Z]'){
        "$_".ToLower()
    }
    if($_-cmatch'[a-z]'){
        "$_".ToUpper()
    }
})

Explanation:
This script splits the argument from a string into a character array, and loops through the array. It returns a given character then, if it's an upper case letter between A and Z returns a lowercase version using the built in function, does the same for lowercase letters. To wrap up it joins the array into a single string.

If you go with v3 or higher for the -in operator, you can exploit the fact that char and int can implicitly cast back and forth and use string multiplication instead of ifs to cut it down to 88 -- -join([char[]]$args[0]|%{$_;"$_".ToLower()*($_-in65..90)+"$_".ToUpper()*($_-in97..122)})

Rust, 250 bytes
fn main(){let(mut i,mut o)=(String::new(),String::new());std::io::stdin().read_line(&mut i);let b:&[u8]=i.trim().as_bytes();for x in b{o.push(*x as char);if*x>64&&*x<91{o.push((x+32)as char)}else if*x>96&&*x<123{o.push((x-32)as char)}}print!("{}",o)}

Ungolfed
fn main() {
    let (mut input_string, mut output_string) = (String::new(), String::new());
    std::io::stdin().read_line(&mut input_string);
    let bytes: &[u8] = input_string.trim().as_bytes();

    for x in bytes {
        output_string.push(*x as char);
        if *x > 64 && *x < 91 {
            //is_uppercase
            output_string.push((x + 32) as char);
        } else if *x > 96 && *x < 123 {
            //is_lowercase
            output_string.push((x - 32) as char);
        }
    }
    print!("{}", output_string);
}

This answer assumes the input only consists of ASCII characters. It uses comparisons and addition/subtraction instead of library functions as it is shorter.

Add++, 100 bytes
D,g,@,O91 65r$e
D,l,@,O123 97r$eBn
D,w,@~,S
D,f,@~,€gB]VAbU€lB]GBcB+32€*B]VAbU€OB]GBcB+€CJABc€wB@B+J

Try it online!
This is annoyingly long. Let's compare this answer to the current shortest, Dennis' Jelly answer:
żŒsQ€
Here, I've split it into three parts: ż, Œs and Q€, highlighted to show the corresponding parts in the Add++ code, as so:
D,g,@,O91 65r$e
D,l,@,O123 97r$eBn
D,w,@~,S
D,f,@~,€gB]VAbU€lB]GBcB+32€*B]VAbU€OB]GBcB+€CJABc€wB@B+J

How it works
		; A note on functions:
		; Each function returns the value on the top of the stack
		; A function has 'flags' that change its behaviour:
		;
		;	@	-	Specifies an argument to be taken
		;	~	-	Splats the arguments to the stack

D,u,@,		; Declare a monadic function 'u'
		; Example argument:	['I']
	O	; Ordinal;	STACK = [73]
	91 65r	; [65 ... 90];	STACK = [73 [65 66 ... 89 90]]
	$e	; Contains?	STACK = [1]

D,l,@,		; Declare a monadic function 'l'
		; Example argument:	['i']
	O	; Ordinal;	STACK = [105]
	123 97r	; [97 ... 122];	STACK = [105 [97 98 ... 121 122]]
	$e	; Contains?	STACK = [1]
	Bn	; Negate;	STACK = [-1]

D,w,@~,		; Declare a monadic function 'w'
		; Example argument:	[['N' 'n']]
	S	; Deduplicate;	STACK = [['N' 'n']]

D,f,@~,		; Declare a monadic function 'f'
		; Example argument:		['N' 'i' 'c' 'e' '!']
	€u	; Map 'u' over €ach;	STACK = [1 0 0 0 0]
	B]	; Wrap the stack;	STACK = [[1 0 0 0 0]]
	V	; Save;			STACK = []
	AbU	; Push argument;	STACK = ['N' 'i' 'c' 'e' '!']
	€l	; Map 'l' over €ach;	STACK = [0 -1 -1 -1 0]
	B]	; Wrap;			STACK = [[0 -1 -1 -1 0]]
	G	; Retrieve;		STACK = [[0 -1 -1 -1 0] [1 0 0 0 0]]
	BcB+	; Column sums;		STACK = [1 -1 -1 -1 0]
	32€*	; Multiply €ach by 32;	STACK = [32 -32 -32 -32 0]
	B]	; Wrap;			STACK = [[32 -32 -32 -32 0]]
	V	; Save;			STACK = []
	AbU€OB]	; Codepoints of input;	STACK = [[78 105 99 101 33]]
	G	; Retrieve;		STACK = [[78 105 99 101 33] [32 -32 -32 -32 0]]
	BcB+	; Column sums;		STACK = [110 73 67 69 33]
	€C	; Convert to chars;	STACK = ['n' 'I' 'C' 'E' '!']
	JABc	; Zip with argument;	STACK = [['n' 'N'] ['I' 'i'] ['C' 'c'] ['E' 'e'] ['!' '!']]
	€w	; Map 'w' over €ach;	STACK = [['n' 'N'] ['I' 'i'] ['C' 'c'] ['E' 'e'] ['!']]
	B@	; Reverse each;		STACK = [['N' 'n'] ['i' 'I'] ['c' 'C'] ['e' 'E'] ['!']]
	B+	; Sum each;		STACK = ['Nn' 'iI' 'cC' 'eE' '!']
	J	; Join;			STACK = ['NniIcCeE!']

Kotlin, 87 86 bytes
x->x.map{c->if(c.isLetter())"$c${(c.toInt()xor 32).toChar()}" else c}.joinToString("")

Try it online!
I wish Kotlin had a ternary operator, but it doesn't so I'm stuck with the more verbose if/else.
I feel like I can get this shorter if I can find a way to consolidate map{} and joinToString() in one call.

SNOBOL4 (CSNOBOL4), 139 bytes
	U =&UCASE
	L =&LCASE
	I =INPUT
S	I LEN(1) . X REM . I	:F(O)
	X ANY(L U)	:S(D)F(A)
D	X =X REPLACE(X,L U,U L)
A	O =O X	:(S)
O	OUTPUT =O
END

Try it online!
The line X ANY(L U)     :S(D)F(A) checks if any of X are Upper or Lowercase, going to D if so or to A if not. Then D duplicates and swaps case, and A concatenates the results together, finally outputting once I has no characters.

Looks like this challenge is still getting some attention and I am not sure how to revive it since there're already really short answers which are difficult to outgolf. :)

@nicael there are always more languages! This is a really good challenge, and I've taken the perspective that code golf is trying to find the shortest answer in each language!

Vyxal d, 5 bytes
ƛǍ[N"

Try it Online!
ƛ     # Map to...
 Ǎ[   # If alphabetical
   N" # Pair with swap_case
      # (Otherwise leave it)
      # (d flag) Print deep sum of stack

Java, 259 bytes
for (i=0;i<in.length();i++)
{
if(Character.isLowerCase(in.charAt(i))){
o=o+in.charAt(i)+Character.toUpperCase(in.charAt(i));}
else if(Character.isUpperCase(in.charAt(i))){o=o+in.charAt(i)+Character.toLowerCase(in.charAt(i));}
else {o=o+in.charAt(i);}}

This is the code golf, your answer should be as short as possible (and defintely lack any excess spacing, tabbing, etc). Also you should include the length of your code in bytes.

@nicael , I edited. Is it OK ?

I've removed other whitespace and newlines.

Also, just a useful post :)

@nicael Unlike Stack Overflow and other SE sites, please don't edit others' answers, even if you are the OP. it's up to them.

@cat Okay, sorry for that! I have edited not because of being the question OP, but just because wanted to help the new user.

Yabasic, 133 bytes
A yabasic answer that takes input as a raw string and outputs to the STDOUT.
Line Input""S$
For i=1To Len(S$)
c$=Mid$(S$,i,1)
u$=Upper$(c$)
?c$;
If"@"<u$And u$<"["Then
If c$=u$Then?Lower$(c$);Else?u$;Fi
Fi
Next

Try it online!

x86-16 machine code, IBM PC DOS, 26 bytes
Binary:
00000000: b401 cd21 3c61 7c08 3c7a 7ff4 24df eb06  ...!<a|.<z..$...
00000010: 3c41 7cec 0c20 cd29 ebe6                 <A|.. .)..

Unassembled listing:
        START:
B4 01       MOV  AH, 1                  ; DOS read char from STDIN
CD 21       INT  21H                    ; read char into AL
3C 61       CMP  AL, 'a'                ; is letter < ASCII 'a'?
7C 08       JL   UPPER                  ; if so, check if uppercase
3C 7A       CMP  AL, 'z'                ; is letter > ASCII 'z'?
7F F4       JG   START                  ; if so, don't repeat
24 DF       AND  AL, NOT ('A' XOR 'a')  ; uppercase it
EB 06       JMP  WRITE                  ; continue to display
        UPPER:
3C 41       CMP  AL, 'A'                ; is letter < ASCII 'Z'?
7C EC       JL   START                  ; if so, don't repeat either
0C 20       OR   AL, 'A' XOR 'a'        ; lowercase it
        WRITE:
CD 29       INT  29H                    ; write AL to screen
EB E6       JMP  START                  ; keep looping

Standalone IBM PC DOS executable.  Input via STDIN, output to console.
I/O:

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:
Directory Structure Graphical Treefication
Convert a classical directory structure like this:
config.yml
drafts
    begin-with-the-crazy-ideas.textile
    on-simplicity-in-technology.markdown
includes
    footer.html
    header.html

Into this
.
├── config.yml
├── drafts
|   ├── begin-with-the-crazy-ideas.textile
|   └── on-simplicity-in-technology.markdown
└── includes
    ├── footer.html
    └── header.html

Four spaces specify a nested folder or file of the above dir.
Nested categories levels allowed can vary.

Update

filenames: valid Linux filenames without spaces and linefeeds: any byte except NUL, / and spaces, linefeeds
drawing characters:

| vertical line (U+007C)
─ box drawings light horizontal (U+2500)
├ box drawings light vertical and right (U+251C)

Winner: Shortest Code in Bytes wins!

Welcome to PPCG! Nice first post!

Are the vertical lines supposed to be \x7C Vertical Line or \u2502 Box Drawings Light Vertical?

@Neil I wasn't aware of "Box Drawings Light Vertical", I've used "Vertical Line" in the example and there are already two answers with that. It would have more sense to use the former one anyway because the other two characters are Box Drawings type, should I update the question with \u2502?

Since I can't easily type box drawing characters into my REPL of choice, I wrote my answer using L, + and - characters, and then adjusted the score believing you were using box drawing characters throughout, although I had in fact just copied and pasted from your question without checking. If vertical line is acceptable, I could reduce my score by 1.

@Neil ok sorry, It would be better to be consistent with all the characters being box drawings as you suggested but I think it is better to leave the original characters now, to not change the rules after it has already been asked, so vertical line should be used.

Excellent, since it now saves my 2 bytes on my new answer!

Retina, 88 bytes
m`^ *
$&├──
 {4}
|
T+`|├` └`(?<=(.)*).(?!.+¶(?>(?<-1>.)*)[|├└])
^
.¶

Try it online!
I suppose I could technically count this as one byte per character by swapping out some characters, reading the source as ISO 8859-1 and then finding a single-byte encoding for the output which contains ├ and └, but I can't be bothered to work out the details right now. (For the record, that would be 72 bytes.)
Explanation
Stage 1: Substitution
m`^ *
$&├──

We start by matching the indentation on each line and inserting ├──.
Stage 2: Substitution
 {4}
|

Next, we match every group of 4 spaces and replace the first with a |. Now all that needs fixing is | that go to the bottom of the output and ├ that should be └. Both of those cases can be recognised by looking at the character directly below the one we potentially want to change.
Stage 3: Transliteration
T+`|├` └`(?<=(.)*).(?!.+¶(?>(?<-1>.)*)[|├└])

The (?<=(.)*) counts how many characters precede the match on the current line to measure it's horizontal position. Then the lookahead skips to the next line with .+¶, matches as many characters as we've captured in group 1 with (?>(?<-1>.)*) (to advance to the same horizontal position) and then checks whether the next character (i.e. the one below the actual match) is one of |├└. If that's the case, the match fails, and in all other cases it succeeds and the stage substitutes spaces for | and └ for ├.
This won't fix all characters in a single run, so we apply this stage repeatedly with the + option until the output stops changing.
Stage 4: Substitution
^
.¶

All that's left is the first line, so we simply match the beginning of the string and prepend a . and a linefeed.

Explanation please?

@Neil There you go.

Would it help to use +\(?<=(.))|(?!.+¶\1[|├])(space)+`(?<=(.))├(?!.+¶\1[│├└]) └`?

@Neil I tried something like that but I don't think I managed to save bytes with it.

New idea: m\^  $&└──  T+` └`|├`(?<=(.)).(?=.+¶\1[|└])`

JavaScript (ES6), 237 128 bytes
f=(s,r=`.\n`+s.replace(/^ */gm,"$&└── "),q=r.replace(/^(.*)( |└)(?=.+\n\1[|└])/m,(_,i,j)=>i+`|├`[+(j>' ')]))=>q==r?r:f(s,q)

Where \n represents the literal newline character. Explanation: r is created from s by prepending the . line and inserting the └── at the end of each line's indent. This is now correct for the last line of the input, but each └ must be "extended" upwards as far as possible. This is the job of q, which searches for a └ and recursively replaces the spaces directly above it with |s unless it reaches another └ which gets turned into ├ instead. The recursion ends when no further replacements can be made. Note that if the character above the └ is a space or a └ then the text to the left of the └ is always the same as that on the previous line so I can just use \1 to test that the one character is above the other.

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


text:
Find the paths!
You must write a program or function.
The input is a 'map' of numbers. You can choose to take the map as either a string with new line characters (\n) or a 2D array of strings.
All maps are 5 characters by 5 characters, and the characters are always either digits greater than 0 or spaces.
Here is an example of a map:
12 45
11233
  233
    1
2 899

Your task is to find the connected components in the map. A valid component is a series of at least three horizontally and/or vertically (not diagonally) connected identical digits (not spaces). You will then need to replace the characters of the valid connected components with xs and print or return that result.
So, the output for the above example would be:
x2 45
xx2xx
  2xx
    1
2 899

Here's another test case (thanks to Martin Ender):
Input:
2   3
    4
 1  5
111 6
11  7

Output:
2   3
    4
 x  5
xxx 6
xx  7

This is code golf so shortest code in bytes wins!

Related. Related. Related.

Are built-ins allowed?

@Joannes, yeah.

JavaScript (ES6), 171 161 139 137 136 133 132 bytes

f=(a,i=0)=>(F=i=>" "<c&&a[i]===c&&(a[i]=n,1+F(i-1)+F(i+1)+F(i-6)+F(i+6)),n=1,c=a[i],n=F(i)>2?"x":c,c=1,F(i),i>28?a:f(a,++i+(i%6>4)))
<textarea rows=5 cols=6 oninput="document.querySelector`pre`.innerHTML=this.value.length==29?f([...this.value]).join``:'invalid input'">12 45
11233
  233
    1
2 899</textarea>

This is a translation of my Python answer. I/O as character arrays.
Too bad there's no efficient way of doing sum...

Python 3, 238 237 200 199 192 181 bytes
def f(a,i=0):F=lambda i,n,c:29>i>=0!=" "!=a[i]==c!=n and(a.__setitem__(i,n)or-~sum(F(i+j,n,c)for j in[-1,1,-6,6]));j=i+i//5;F(j,[a[j],"x"][2<F(j,1,a[j])],1);i>23or f(a,i+1);return a

Defines a function f(a) that takes the input as an array of characters and returns the same array modified. (Arrays of characters are acceptable as strings by default.)
Ungolfed with explanation
The modified code is recursive, but works the same.
# The main function; fills all continuous nonempty areas of size >= 3 in array
# with x's. Both modifies and returns array.
def findpaths(array):
    # Fills a continuous area of curr_char in array with new_char, starting
    # from index. Returns the number of cells affected.
    def floodfill(index, new_char, curr_char):
        if (0 <= index < 29                   # Check that the position is in bounds
                and (index + 1) % 6 != 0      # Don't fill newlines
                and array[index] != " "       # Don't fill empty cells
                and array[index] == curr_char # Don't fill over other characters
                and curr_char != new_char):   # Don't fill already filled-in cells
            array[index] = new_char # Fill current position
            return (1 # Add neighboring cells' results, plus 1 for this cell
                    + floodfill(index + 1, new_char, curr_char)  # Next char
                    + floodfill(index - 1, new_char, curr_char)  # Previous char
                    + floodfill(index + 6, new_char, curr_char)  # Next line
                    + floodfill(index - 6, new_char, curr_char)) # Previous line
        return 0 # Nothing was filled. The golfed solution returns False here,
                 # but that's coerced to 0 when adding.

    for i in range(25): # Loop through the 25 cells
        i += i // 5 # Accommodate for newlines in input
        curr_char = array[i] # Get the cell's contents
        # Fill the area from the cell with dummies
        area_size = floodfill(i, 1, curr_char)
        # Convert dummies to "x" if area was large enough, back to original otherwise
        fill_char = "x" if 2 < area_size else curr_char
        floodfill(i, fill_char, 1)
    return array

2 bytes off to beat the mathematica solution...

@FlipTack Yeah. I don't think it's happening today, but I'm translating this to JS and it looks promising.

Ruby, 304 bytes
def b(s,i)
  @v=[]
  b2(s,i,s[i])
end
def b2(s,i,c)
  if(0...s.size)===i&&s[i]==c&&!@v[i]
    @v[i]=s[i]='x'
    [1,-1,6,-6].each{|j|b2(s,i+j,c)}
  end
  s
end
def f(s)
  z = s.dup
  ps = ->(i){b(z.dup,i).scan('x').size}
  (0...s.size).each{|i|b(s, i)if ![' ',"\n"].include?(s[i])&&ps.call(i)>2}
  s
end

example usage:
puts f(File.read("map.txt"))

the code reuses the 'blot' method to calculate the path length.
variables/methods:

f(s): function to convert map string, returns new map with 'x's
ps(i): path size from map index i (where x = i % 6, y = i / 6)
s: input string, map lines separated by "\n"
z: copy of input string
b(s,i): 'blot' function: writes 'x' from map index i over paths
@v: 'visited' array

Attempt at more detailed explanation:
make a copy of the input string, which we use for finding the length of the path from any given point in the map.
z = s.dup

define a 'ps' (path length) anonymous function (lambda) which takes the map index i as an argument. it returns the length of the path from that point. it does this by calling the 'b' (blot) method to insert x's on a copy of the original map and then counting the number of x's in the returned string.
  ps = ->(i){b(z.dup,i).scan('x').size}

the following part iterates over each character in the map (index i, character s[i]). it calls the 'b' (blot) function on map position i if the path length from position i is greater than 2, and if it's not a space or newline character.
  (0...s.size).each { |i|
     b(s, i) if ![' ',"\n"].include?(s[i]) && ps.call(i) > 2
  }

the b (blot) function takes the map string and an index as argument. it initialises @v (visited array) and calls the b2 helper function.
def b(s,i)
  @v=[]
  b2(s,i,s[i])
end

the b2 function takes the map string, a map position (i), and a character in the current path (c). it calls itself recursively to replace connected sections of digits with the 'x' character. it returns the input string (this is so the ps function can call scan() on the return value).
this if statement is checking that the map position (i) given is within the bounds of the string (0...s.size) and that the character at s[i] is the same as the starting character. also @v[i] is checked to avoid infinite recursion.
if(0...s.size) === i && s[i] == c && !@v[i]

this is the bit that replaces the character at index (i) with the 'x' character. it also marks that index as visited.
@v[i] = s[i] = 'x'

this is where b2 calls itself recursively searching for the path. i+1 is one character to the right, i-1 is one character to the left, i+6 is one row down (5 digits + 1 newline = 6 characters), i-6 is one row up.
[1,-1,6,-6].each { |j| b2(s, i+j, c) }

C(Ansi), 243 233 179 188 Bytes
Golfed:
#define O o[1][l]
x,n,l,L;r(o,l)char**o;{if(!(l>L|l<0|O<47|O!=x))n++,O++,r(o,l-1),r(o,l+6),r(o,l-6),r(o,l+1),n>2?O='x':O--;}main(g,o)char**o;{for(;(L=30)>l;l++)n=0,x=O,r(o,l);puts(o[1]);}

With Annotations:
#define O o[1][l]
x,n,l,L;      /*-------------------------- Globals*/
r(o,l)char**o;{ /*------------------------ Recursive Function*/
    if(!(l>L|l<0|O<47|O!=x)) /*----------- if this cell is valid(in
                                              range, is a number, is the
                                              same as the parent number*/
    n++,     /*--------------------------- Increment count*/
    O++,     /*--------------------------- Increment character to mark*/
    r(o,l-1),  /*------------------------- Recurse left*/
    r(o,l+6),  /*------------------------- Recurse down*/
    r(o,l-6),  /*------------------------- Recurse down*/
    r(o,l+1),  /*------------------------- Recurse right*/
    n>2?O='x':O--;  /*---------------------If greater than 3, replace with x, else decrement character*/
}          /*----------------------------- Return*/

main(g,o)char**o;{ /*--------------------- Main*/
    for(;l<(L=30);l++){ /*---------------- For entire string and set L*/
        n=0;
        x=O;        /*-------------------- set counter to 0*/
        r(o,l); /*------------------------ Recurse*/
    } /*---------------------------------- End While*/
    puts(o[1]); /*------------------------ Print*/

}
Input:
Expects a newline at the beginning and end of the string.
Example Input:
./findPaths "
12 45
11233
  233
    1
2 899
"

Example Output:
x2 45
xx2xx
  2xx
    1
2 899

Update
Making the grid fixed allowed me to shave off nearly 60 bytes.

I guess I can save like 22 characters if I change this to a fixes map size - I'll change that if I find anything else I want to change

Mathematica, 180 bytes
(f=Flatten@#;p=Partition)[If[Tr[1^VertexComponent[r~Graph~Cases[##&@@p[#,2,1]&/@Join[g=p[r,5],g],{a_,b_}/;(A=f[[a]])==f[[b]]&&A!=" ":>a<->b],#]]<3,f[[#]],"x"]&/@(r=Range@25),5]&

Explanation:
(f=Flatten@#;p=Partition)[
  If[
    Tr[1^VertexComponent[
        r~Graph~Cases[
          ##&@@p[#,2,1]&/@Join[g=p[r,5],g],
          {a_,b_}/;(A=f[[a]])==f[[b]]&&A!=" ":>a<->b
        ],
        #
      ]]<3,
    f[[#]],
    "x"
  ]&/@(r=Range@25),
  5
]&

Pure function which accepts a 5x5 array.  is the 3-byte private-use character U+F3C7 representing the postfix transpose operator \[Transpose].
(f=Flatten@#;p=Partition): Flattens the input list and stores it in f. Sets p = Partition and returns it.
g=p[r,5]: The array {{1,2,3,4,5}, ..., {21,22,23,24,25}} (this is because r gets set to Range@25).
Join[g=p[r,5],g]: the list of rows and columns of g.
p[#,2,1]&: Pure function which partitions the list # into sublists of length 2 with overlap 1; i.e., the list of adjacent pairs in #.
##&@@p[#,2,1]&: Same as above except it returns a Sequence.
##&@@p[#,2,1]&/@Join[g=p[r,5],g]: Maps the previous function of the rows and columns of g to obtain a list of all of the adjacent entries in g. My gut says there is a shorter way to do this.
r~Graph~Cases[...]: Graph whose vertices are the integers 1, ..., 25 and whose edges are the edges between adjacent entries in g which have the same corresponding entries in the input array (other than " ")
{a_,b_}/;(A=f[[a]])==f[[b]]&&A!=" ": Pattern which matches {a,b} such that f[[a]] == f[[b]] (same value in the input array) and which are not equal to " ". Set A = f[[a]] to save 1 byte.
...:>a<->b: Replace every match with an undirected edge from a to b.
VertexComponent: Returns the connected component of the second argument (a vertex) in the first argument (a graph).
Tr[1^VertexComponent[...]]: The size of the connected component. Saves 1 byte from Length@VertexComponent[...].
If[Tr[...]<3,f[[#]],"x"]&: Pure function which takes an entry # in g. If the size of its connected component is less than 3, replace it with the corresponding entry in the input. Otherwise, replace it with "x".
(f=Flatten@#;p=Partition)[...,5]: And finally reshape the result to be a 5x5 array.

Clojure, 188 bytes
This is quite overwhelming :D
#(apply str(map-indexed(fn[i v](if((set(flatten(for[m(range 30)](let[n(for[p[-1 -6 1 6]:when(=(get %(+ m p)0)((set"123456789")(% m)))](+ m p))](if(< 1(count n))(conj n m)[])))))i)\x v))%))

Called like this (it takes a 1D vector of characters):
(def f #(apply str(...))

(print (str "\n" (f (vec (str "12 45\n"
                              "11233\n"
                              "  233\n"
                              "    1\n"
                              "2 899\n")))))

(print (str "\n" (f (vec (str "2   3\n"
                              "    4\n"
                              " 1  5\n"
                              "111 6\n"
                              "11  7\n")))))

Too lazy to ungolf it but basically for[m(range 30)] visits each index and for each index the inner let[n(for[p[-1 -6 1 6]...(+ m p))] makes a list of 0 to 4 elements which lists locations which had the same value (1 - 9) as the middle location. If more than 1 neighbour matches the mid piece it means that all these form a cluster, so those locations are added to the set used at (if((set(flatten(...)))i). If index i is found from the set then \x is emitted and the original value otherwise. That :when( ... ) is quite interesting...

Julia
256 bytes
too long...
readable version:
~A=(
  B=hcat(collect.(split(A,"\n"))...);C=copy(B);
  s\T=(
    L=[s];
    C[s...]='_';
    [(-1,0),(1,0),(0,-1),(0,1)].|>y->get(C,y.+s,'_')==T&&(L=vcat(L,(y.+s)\T));
    L
  );
  keys(C).|>x->isdigit(C[x])&&length((L=Tuple(x)\C[x];L))>2&&L.|>y->B[y...]='x';
  join(eachcol(B).|>join,"\n")
)

Attempt This Online!

classical floodfill
converts the input to char matrix (B), copy it (C, it is used for admin the visitedness), then performs floodfill from each (current) digits of C. \ returns the vector of connected component L and if it fulfills the reqs then modify B. At the end it builds a string from B.
works for arbitrary, "rectangular" strings

194 bytes
input as char matrix (split+join are outsourced):
~B=(
  C=copy(B);
  s\T=(
    L=[s];
    C[s...]='_';
    [(-1,0),(1,0),(0,-1),(0,1)].|>y->get(C,y.+s,'_')==T&&(L=vcat(L,(y.+s)\T));
    L
  );
  keys(C).|>x->isdigit(C[x])&&length((L=Tuple(x)\C[x];L))>2&&L.|>y->B[y...]='x';
  B
)

Attempt This Online!


text:
Post-determined Array Sorting
Input:

An array containing three integers: 0, 1 and 2 in any order (i.e. [2, 0, 1])
And a string of length >= 2 only containing alphabetic letters (both lower- and uppercase) and digits (i.e. a1B2c3)

Output:
Based on the array we sort and output the string.
How does this work?

The array indicates the order precedence of a-z, A-Z and 0-9, the first being 0; second being 1; and third being 2.
The individual characters of the string can then be ordered based on that.

Example:

Array: [2, 0, 1]
String: a1B2c3

Based on the array, we know our order precedence is 0-9a-zA-Z.
Based on that, we can convert and output the string: 123acB.
Challenge rules:

For the array you can choose to use 0-indexed or 1-indexed input, so [3, 1, 2] is also a valid input if you prefer to use 1-indexed arrays.
The string (both input and output) only contains valid characters: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.
If your language doesn't support arrays (or if you choose to), you are free to use strings instead of arrays for the first parameter (i.e. 012, [0,1,2], etc.).

General rules:

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

Test cases:
[2, 0, 1]  &  a1B2c3             ->   123acB
[2, 1, 0]  &  aAaA909UuHWw9gh2   ->   02999AAHUWaaghuw
[2, 1, 0]  &  6Bx43              ->   346Bx
[1, 0, 2]  &  jfjf33g            ->   ffgjj33
[0, 2, 1]  &  AbC13              ->   b13AC
[1, 2, 0]  &  Qfl0l              ->   Q0fll
[0, 1, 2]  &  9870abcABC         ->   abcABC0789
[0, 2, 1]  &  test123            ->   estt123
[2, 0, 1]  &  WHAT               ->   AHTW
[2, 0, 1]  &  WhAt               ->   htAW
[1, 0, 2]  &  102BACbac          ->   ABCabc012

Would "123" be a valid format for the first parameter?

Related: Imitate an ordering

@Mego Yeah why not. It's not affecting the main part of the challenge. I've edited my question to reflect the change. Feel free to use 123, 012, [0,1,2], [0, 1, 2], 0;1;2 or whichever you prefer.

05AB1E, 15 14 12 bytes
Code:
v²žK26ôyèÃ{?

Explanation:
v             # For each in the input array.
  žK          #   Push a-zA-Z0-9.
    26ô       #   Split into pieces of 26.
       yè     #   Get the element-th element of the array.
 ²       Ã    #   Keep the characters of that element from the second input.
          {?  #   Sort pop and print without a newline.

Uses the CP-1252 encoding. Try it online!.

This can be 10 bytes now by removing the ² and using ₂ instead of 26.

Python 2, 67 66 bytes
lambda s,k:`sorted(s,key=lambda c:`k.index(3-ord(c)/32)`+c)`[2::5]

Test it on Ideone.

JavaScript (ES6), 87 bytes
(a,s)=>a.map(n=>[...s].sort().join``.replace([/[^a-z]/g,/[^A-Z]/g,/\D/g][n],``)).join``

If the input array gave the order, rather than the precedence, of the three ranges (this only makes a difference for [1, 2, 0] and [2, 1, 0] whose effects are swapped) then this would have worked for 80 bytes:
(a,s,o=c=>a[(c<'a')+(c<'A')])=>[...s].sort((a,b)=>o(a)-o(b)||(a>b)-(a<b)).join``

I misread the question and still got 7 upvotes with this. Feel free to remove your upvotes and give them to @CharlieWynn instead, who came up with the best correction to my approach.
(a,s)=>a.map(n=>s.replace([/[^a-z]/g,/[^A-Z]/g,/\D/g][n],``)).join``

Ooh, very interesting solution! I was thinking of a different ES6 answer to use Array.sort's optional function parameter but this woks way better.

I really like this solution, but I think it fails test 2, 3 and probably others.  I guess you're supposed to sort each of the three segments?

@CharlieWynn Sorry, I must have misread the question. (It's a common fault of mine.)

@Neil, I don't think the question made it very clear to sort the array, just noticed the test cases seemed to have that feature.

@CharlieWynn Most of the test cases appeared to be already sorted w.r.t. lower/upper/numeric portions anyway...

Pyth, 17 16 15 bytes
s@RSz@L[GrG1`UT

Test suite.
       [          array literal containing...
        G           the alphabet (lowercase)
         rG1        the alphabet, converted to uppercase
            `UT     inspect-range-10, generating the range [0,10) and
                      stringifying it, resulting in a string that contains no
                      letters and all numbers (so equivalent to '0123456789' for
                      filtering)
                    this creates ['ab...z', 'AB...Z', '01...9']

     @L           map over first (implicit) input (the ordering array) and take
                   the nth element in this array for each item
                   this gives us ['01...9', 'ab...z', 'AB...Z']

   Sz             take another line of input as a string and sort it, and then...
 @R               map over intersection: filter the line of input over presence
                    in each element in the new array
                    this results in ['123', 'ac', 'B']

s                 concatenate all and implicitly output

Thanks to @FryAmTheEggman for a byte and @Jakube for another!

You can use 'UT instead of s'MT.

@Jakube I'm using a backtick, not a single quote. But 'UT is an error, and \UT` doesn't result in the same string.

Yes,  I meant a backtick. But a backtick is hard to write in the comments.  Yes,  it generates a different string,  but it shouldn't matter. The generated string contains all digits and no letters.

@Jakube Oh, I see. That's clever; thanks!

Javascript es6 77 bytes
(a,s)=>a.map(o=>s.match([/[a-z]?/g,/[A-Z]?/g,/\d?/g][o]).sort().join``).join``

//test
f=(a,s)=>a.map(o=>(s.match([/[a-z]/g,/[A-Z]/g,/\d/g][o])||[]).sort().join``).join``

f([2, 0, 1], "a1B2c3")             == "123acB" &&
f([2, 1, 0], "aAaA909UuHWw9gh2")   == "02999AAHUWaaghuw" &&
f([2, 1, 0], "6Bx43")              == "346Bx" &&
f([1, 0, 2], "jfjf33g")            == "ffgjj33" &&
f([0, 2, 1], "AbC13")              == "b13AC" &&
f([1, 2, 0], "Qfl0l")              == "Q0fll" &&
f([0, 1, 2], "9870abcABC")         == "abcABC0789" &&
f([0, 2, 1], "test123")            == "estt123" &&
f([2, 0, 1], "WHAT")               == "AHTW" &&
f([2, 0, 1], "WhAt")               == "htAW" &&
f([1, 0, 2], "102BACbac")          == "ABCabc012"

Stole @Neil's very neat regex array idea

By adding ?s to each regex, this ensures that the match returns results (mostly empty strings, but they disappear anyway), avoiding the (||[]), thus saving you 3 bytes overall.

@Neil wonderful, thanks.. I wasn't sure why you had those in yours :P

Jelly, 13 bytes
2_ịØWs26¤Ff@€

Try it online! or verify all test cases.
How it works
2_ịØWs26¤Ff@€  Main link. Arguments: k (permutation of [0, 1, 2]), s (string)

2_             Subtract the integers in k from 2, mapping [0, 1, 2] -> [2, 1, 0].
        ¤      Combine the three links to the left into a niladic chain.
   ØW          Yield the string following string.
               'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_'
     s26       Split it into chunks of 26 chars, i.e., ['A...Z', 'a...z', '0...9'].
  ị            Retrieve the chunks from the right result at the indices of the
               left result. The indices of the chunks are modular and 1-based;
               1 retrieves 'A...Z', 2 retrieves 'a...z', and 3 retrieves '0...9'.
         F     Flatten the resulting array of strings.
          f@€  Filter (swapped, each); for each character in the constructed
               string, select all occurrences of that character from s.

TSQL, 199 191 bytes
Golfed:
DECLARE @i varchar(99)='abA7B34',@s char(3)='213'

,@ varchar(99)=''SELECT @+=n FROM(SELECT top 99n FROM(SELECT top 99substring(@i,row_number()over(order by 1/0),1)n FROM sys.messages)c ORDER BY CHARINDEX(CHAR(ascii(n)/32+48),@s),n)d SELECT @

Ungolfed:
DECLARE @i varchar(99)='abA7B34'
-- 1 numbers, 2 upper case, 3 lower case
DECLARE @s char(3)='213'

,@ varchar(99)=''
SELECT @+=n
FROM
  (
    SELECT top 99 n
    FROM
      (
         SELECT top 99substring(@i, row_number()over(order by 1/0), 1)n
         FROM sys.messages
      )c
    ORDER BY CHARINDEX(CHAR(ascii(n)/32+48),@s),n
  )d

SELECT @

Fiddle

APLX, 19 bytes
s[(∊(⎕a⎕A⎕D)[a])⍋s]

⎕a⎕A⎕D lower upper digits
(…)[a] reorder according to array a
∊ flatten
(…)⍋s according to that "alphabet", give the indices that would sort string s
s[…] use that to reorder s

Too bad Dyalog APL does not have ⎕a and the the uppercase to lowercase translation takes up a lot of bytes in the solution :-) Not that I am not suggesting for Dyalog APL to include ⎕a given that its usefulness would be pretty much reduced to code-golfing challenges, as far as I can tell.

@lstefano I don't like ⎕a, because it is a case-sensitive quad name. Much better (for golfing and in general) what I'm lobbying for; to get ⌈ and ⌊ to fold case on character data, just like in K. Then we'll have ⌊⎕A instead of ⎕a.

Python 2, 121 Bytes
lambda a,s:"".join(sum([[sorted(filter(eval(u),s))for u in["str.islower","str.isupper","str.isdigit"]][i]for i in a],[]))

Clojure, 74 bytes
#(apply str(mapcat sort(for[i %](re-seq([#"[a-z]"#"[A-Z]"#"[0-9]"]i)%2))))

For each value in first list, gets appropriate regex and apply it to the input string. The result is a list of lists of symbols which match the regex. Then sort each one and concatenates the result into one list and transform it to string.
You can see it online here: https://ideone.com/dqAkxg

Retina, 43 39 bytes
Byte count assumes ISO 8859-1 encoding. The trailing linefeed is significant.
2=`.
!$&"
T04`¶d`#^@%
O`\W?.
O`.\w+
\W

Input is expected to be the sort order as a zero-based list without delimiters on the first line, and the string to be sorted on the second line, e.g.
120
fOo42BaR

Try it online!
Explanation
I will use the above input example to walk you through the code:
120
fOo42BaR

Stage 1: Substitution
2=`.
!$&"

The regex itself is just . (matches any non-linefeed character), which is surrounded with !...". However, the 2= is a limit telling Retina to apply the substitution only to the second match of the regex. So we get this:
1!2"0
fOo42BaR

Stage 2: Transliteration
T04`¶d`#^@%

A transliteration stage simply does a character-by-character substitution. The ¶ represents a linefeed and d expands to 0123456789 (although we can ignore all digits after 2). That means, this transliteration corresponds to the following mapping:
¶012
#^@%

The 04 at the front are two limits, which together indicate that only the first four characters from this set should be transliterated. That happens to be the digits on the first line, as well as the linefeed separating the two lines, so we get this:
@!%"^#fOo42BaR

At the front of the string we've now got three pairs of these characters:
@!
%"
^#

Note that the second characters of the pairs are simply in their normal ASCII order (and will always be the same). We'll use these later to sort the groups of characters in the main input into the required order.
The first characters are bit more interesting: their significance is that % comes before digits in the ASCII table, @ comes before upper case letters (but after digits), and ^ comes before lower case letters (but after upper case letters). This will help us group the position markers (i.e. the second character in each pair) with the right set of characters.
Stage 3: Sort
O`\W?.

This is a simple sort stage. It matches two characters if the first one isn't a word character (thereby matching all three pairs I just talked about) or a single character otherwise (matching each character of the main input individually), and sorts those strings. This has two purposes: it brings the characters within each group in the correct order (and since sorting is stable, this order won't be messed up in the next stage), and it due to the %@^ markers, it inserts the pairs in the right positions:
%"24@!BOR^#afo

Stage 4: Sort
O`.\w+

This stage sorts all matches of the .\w+ regex which, due to greediness, matches one position marker (i.e. one of !"#) together with all the word characters after it. That is, it sorts these three strings, whose order is determined solely by the marker character:
"24
   !BOR
   #afo
While this shuffles around those markers (while leaving the other three markers in place), most importantly it brings the digits and letters in the correct order:
%!BOR@"24^#afo

Stage 5: Substitution
\W

All that's left is a little clean-up, where we remove all the markers by matching them and replacing them with nothing.

Haskell, 62 63 bytes
a#b=[c|i<-b,c<-[' '..],d<-a,d==c,div(fromEnum c)16==[6,4,3]!!i]

Usage example: "cD12ab" # [2,0,1] -> "12abcD".
How it works:
i<-b                                  -- loop i through the input array
   [c|   c<-[' '..]]                  -- loop through all chars c
       d<-a                           -- loop through all chars d in the input string
       d==c                           -- and keep those that are in the input string
       div(fromEnum c)16==[6,4,3]!!i  -- and where the the ascii value divided by
                                      -- 16 equals the number from [6,4,3] indexed
                                      -- by the current i

Edit: @Christian Sievers found a bug. Thanks! Fixed for 1 additional byte.

What about chars occuring more than once?

@ChristianSievers: you're right, that's a bug. Fixed. Thanks you!

Ruby, 56 bytes
Ported from @Dennis answer.
->a,s{s.chars.sort_by{|c|a.index(3-c.ord/32).to_s+c}*''}

An alternate 58 bytes solution that I like better, inspired by @Neil and modified slightly from his answer.
->a,s{a.map{|i|s.scan([/[a-z]/,/[A-Z]/,/\d/][i]).sort}*''}

Try either version online! (commented-out version is the alternate solution)

JavaScript (ES6), 65
Note: 'natural' ASCII order is 0-9, A-Z, a-z, that is just the opposite of the OP 0,1,2. So

order the string adding invalid chars to separate runs
split it in 3 segmenents - invalid chars mark each
get segments one by one in the requested order
reassemble

s=>w=>w.map(w=>[...'^@'+s].sort().join``.split(/\W/)[2-w]).join``

F=s=>w=>w.map(w=>[...'^@'+s].sort().join``.split(/\W/)[2-w]).join``

;[['201','a1B2c3','123acB']
,['210','aAaA909UuHWw9gh2','02999AAHUWaaghuw']
,['210','6Bx43','346Bx']
,['102','jfjf33g','ffgjj33']
,['021','AbC13','b13AC']
,['120','Qfl0l','Q0fll']
,['012','9870abcABC','abcABC0789']
,['021','test123','estt123']
,['201','WHAT','AHTW']
,['201','WhAt','htAW']
,['102','102BACbac','ABCabc012']]
.forEach(t=>{
  var w=t[0],s=t[1],k=t[2], r=F(s)([...w])
  console.log(w,s,r,(r==k?'OK':'KO (expected '+k+')'))
})

Stax, 15 bytes
┐°!'àÉgYg8∟╗`╖ë

Run and debug it online
This 15 byte submission is packed into a variant of the CP437 character set.  The corresponding ascii representation takes 18 bytes:
EVlVd+26/s@:fs{[Io

Pretty sure it can be further trimmed down though.
E                   Put the two inputs on main stack
 Vl                 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
   Vd               "0123456789"
     +              Concatenate
      26/           Partition to blocks of size 26 (array `a`)
         s@         Index array `a` with the input index array
           :fs      Flatten to get a string `s`
              {[Io  Order the input string
                        Using the char array `s` as the key
                    Implicit output

VlVd+ can also be VLA|(, which left rotates the 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ by ten elemenets. The whole code can also be VlVd+26/,e@:f,{[Io, which reads the input stack twice instead of reading them all at the beginning to the main stack, and uses a different (more traditional) input format, as shown in this.

You can remove the E, but it doesn't change bytecount.

Dyalog APL, 22 bytes
s[s⍋⍨∊(819⌶⎕A)⎕A⎕D[a]]

(819⌶⎕A) fold the uppercase alphabet to lowercase
(…)⎕A⎕D[a] lower upper digits reordered according to array a
∊ flatten
s⍋⍨ for string s, get the indices that would sort s according to that "alphabet"
s[…] use that to reorder s

mmm.... 819⌶ only exists in the unicode version of Dyalog APL. So I would surmise that the byte count should be multiplied by 2 since the input is effectively composed of Unicode entry points.Or my understanding of the byte counting for APL submissions is wrong?

@lstefano The Unicode edition is able to load Classic workspaces, right?

That's sneaky ;-)

Python 2, 140 117 101 100 99 bytes
Everyone say, "Ewww!". At least it's readable... cough not really cough
lambda l,s:`sorted(s,key=lambda c:[[c<'a',c<'A'or'Z'<c,c>'9'][l[i]]for i in 0,1,2]+[ord(c)])`[2::5]

Try it online

PowerShell v2+, 107 bytes
param($n,[char[]]$s)-join(-join(($s=$s|sort)|?{$_-ge97}),-join($s|?{$_-in65..96}),-join($s|?{$_-lt58}))[$n]

I'm exploring algorithms using regex, but thus far they all seem longer.
Takes input as explicit array $n (see examples below) and string $s which is immediately cast to a char-array. We're then constructing three elements of a new dynamic array, each of them encapsulated with a -join:
- (($s=$s|sort)|?{$_-ge97})
- ($s|?{$_-in65..96})
- ($s|?{$_-lt58})
The first we take $s and run it through Sort-Object. Thankfully, since we've already cast it as a char-array, it's case-sensitive sorting. That gets re-saved into $s and then piped to a Where-Object with a clause of greater than 97 (i.e., ASCII lowercase a-z). The second is for A-Z and the third for 0-9.
Thus we now have an array of strings, where each string is composed one of the three character types and is sorted. We slice that with [$n] and then -join the result together to form our final output string. That is left on the pipeline and printing is implicit.
Test Cases
PS C:\Tools\Scripts\golfing> $test = (@(2,0,1),'a1B2c3'), (@(2,1,0),'aAaA909UuHWw9gh2'), (@(2,1,0),'6Bx43'), (@(1,0,2),'jfjf33g'), (@(0,2,1),'AbC13'), (@(1,2,0),'Qfl0l'), (@(0,1,2),'9870abcABC'), (@(0,2,1),'test123'), (@(2,0,1),'WHAT'), (@(2,0,1),'WhAt'), (@(1,0,2),'102BACbac')

PS C:\Tools\Scripts\golfing> $test |%{"($($_[0]-join',')) & $($_[1])".PadRight(28)+" -> " + (.\post-determined-array-sorting.ps1 $_[0] $_[1])}
(2,0,1) & a1B2c3             -> 123acB
(2,1,0) & aAaA909UuHWw9gh2   -> 02999AAHUWaaghuw
(2,1,0) & 6Bx43              -> 346Bx
(1,0,2) & jfjf33g            -> ffgjj33
(0,2,1) & AbC13              -> b13AC
(1,2,0) & Qfl0l              -> Q0fll
(0,1,2) & 9870abcABC         -> abcABC0789
(0,2,1) & test123            -> estt123
(2,0,1) & WHAT               -> AHTW
(2,0,1) & WhAt               -> htAW
(1,0,2) & 102BACbac          -> ABCabc012

32-bit x86 machine code, 70 bytes
In hex:
fc31c031c95189e3ac84c0740a34cf0404880c0341ebf189fe9160ac88c2c0e805d788c652ac88c2c0e805d788c658740e6639d076029241aa92aa4e4febdc85c96175d658c3

This procedure expects character class sorting order to be a 3-char (0..2) NULL-terminated string in ESI and the string to sort in EDI. Sorting is done in-place using extremely sub-optimal (performance-wise) version of bubble sort.
0:  fc                  cld
1:  31 c0               xor eax, eax
3:  31 c9               xor ecx, ecx
5:  51                  push ecx        ;Allocate 4 bytes on the stack
6:  89 e3               mov ebx, esp    ;char EBX[4]
_loop0:                                 ;Parsing class order string
8:  ac                  lodsb
9:  84 c0               test al,al      ;Break on NULL
b:  74 0a               jz _break0
d:  34 cf               xor al, 0xCF    ;AL=~atoi(AL)
f:  04 04               add al, 4       ;'0'->3, '1'->2, '2'->1
11: 88 0c 03            mov [ebx+eax], cl    ;EBX[AL]=CL
14: 41                  inc ecx
15: eb f1               jmp _loop0
_break0:
17: 89 fe               mov esi,edi
19: 91                  xchg eax,ecx    ;ECX=0
_bsort:
1a: 60                  pusha
_cx2b:
1b: ac                  lodsb           ;Get the first char to compare
1c: 88 c2               mov dl,al       ;Save to DL
1e: c0 e8 05            shr al,5        ;Char class: [0-9]->1, [A-Z]->2, [a-z]->3
21: d7                  xlat            ;AL=EBX[AL] - priority for the char class
22: 88 c6               mov dh,al       ;... goes to DH
24: 52                  push edx        ;First "comparable char" in DX goes to the stack
25: ac                  lodsb           ;Get the second char to compare
26: 88 c2               mov dl,al       ;\
28: c0 e8 05            shr al,5        ; > Same as the above
2b: d7                  xlat            ;/
2c: 88 c6               mov dh, al      ;Second "comparable char" in DX
2e: 58                  pop eax         ;The first one goes to AX
2f: 74 0e               jz _endpass     ;ZF is set by the last 'shr', and only on AL==0
31: 66 39 d0            cmp ax,dx       ;Upper halves of 32-bit regs may contain trash
34: 76 02               jbe _sorted
36: 92                  xchg eax,edx    ;Now AX<=DX
37: 41                  inc ecx         ;Swap counter
_sorted:
38: aa                  stosb           ;Store AL in-place
39: 92                  xchg eax,edx    ;AL=DL
3a: aa                  stosb           ;Store the second char
3b: 4e                  dec esi         ;Move pointers...
3c: 4f                  dec edi         ;...back one byte
3d: eb dc               jmp _cx2b       ;Repeat with the next two chars
_endpass:
3f: 85 c9               test ecx,ecx    ;Full pass completed, checking # of swaps made
41: 61                  popa            ;Restores ECX(0), ESI, EDI. Doesn't affect flags
42: 75 d6               jnz _bsort      ;If there were changes, repeat
_end:
44: 58                  pop eax         ;Deallocate EBX[]
45: c3                  ret

Emacs Lisp, 183 bytes
(lambda(s p)(let(l u n)(apply'concat(mapcar(lambda(l)(sort l'<))(dolist(e(string-to-list s)(mapcar(lambda(i)(nth i(list l u n)))p))(push e(cond((< ?` e)l)((< ?@ e)u)((< ?/ e)n))))))))

Slightly shorter than Java...

Clojure, 77 bytes
#(apply str(mapcat sort(map(group-by(fn[v](condp <(int v)90 0,57 1,2))%2)%)))

Not quite as short as the re-seq based one, and I couldn't figure out how to express that "(apply str(mapcat sort(map(...))))" in less space. group-by creates a hash-map which can be used as a function, when queried with an ingeger between 0 and 2 it returns the corresponding group, this orders the three different classes of characters.
This would be more compact than the re-seq solution if there were more character classes to handle as this only takes 5 extra characters / group like 57 1, instead of 8 for expression like #"[a-z]".

R, 101 bytes
function(a,s,o=unlist(list(letters,LETTERS,0:9)[a]))cat(o[sort(match(strsplit(s,'')[[1]],o))],sep='')

Creates a vector with a-z, A-Z and 0-9 in given order and reorders characters of input string to match this ordering.
Try it online!

Java 8, 221 212 193 156 bytes
I should of course try to answer my own challenge as well. :) (And as usual in Java.)
a->i->{for(byte c[],j=0;j<3;System.out.print(new String(c)))java.util.Arrays.sort(c=i.replaceAll("[^a-z];[^A-Z];[^0-9]".split(";")[a[j++]],"").getBytes());}

-28 bytes saved thanks to @cliffroot.
Explanation:
Try it here.
a->i->{          // Method with integer-array and String parameters and no return-type
  for(byte c[],  //  Temp byte-array
      j=0;j<3;   //  Loop from 0 to 3 (exclusive)
      System.out.print(new String(c)))
                 //    After every iteration: print the byte-array as String
    java.util.Arrays.sort(
                 //   Sort the byte-array
      c=         //    After we've replaced the byte-array with
        i.replaceAll("[^a-z];[^A-Z];[^0-9]".split(";")[a[j++]],"").getBytes());}
                 //    all bytes of the uppercase letters, lowercase letters, or digits,
                 //    depending on the next number in the input-array

You can replace your regexps with [^a-z] [^A-Z] [^0-9] and you can use getBytes() instead of toCharArray()

@cliffroot Thanks. I'm pretty bad at regexes, but not using the ^ (not) was pretty dumb.. ;)

removes repetitive replaceAll calls
String c(int[]a,String z){String r[]={"[^a-z]","[^A-Z]","[^0-9]"},o="";for(byte c[],i=0;i<3;){c=z.replaceAll(r[a[i++]],"").getBytes();java.util.Arrays.sort(c);o+=new String(c);}return o;}

J, 40 bytes
;@:{[:(<@/:~@}./.~2-64 96 I.3&u:)'aA0'&,