[Question]
  [
Your challenge is to passwordify the string! What is passwordifying, you ask?
Take a string as input. This string will only contain uppercase letters, lowercase letters, digits, and spaces. 
You must replace all spaces with underscores and move all numbers to the end of the string in the order that they appear from left to right. Then, for every letter in the string, randomly change it to uppercase or lowercase. 
Examples (case of characters should vary every time):
```
Input
Hello world
Output
HElLo_wORld
Input
pa55 w0rd
Output
pA_Wrd550
Input
14 35
Output
_1435
Input
0971
Output
0971
Input
[space]
Output
_
```
## Shortest code in bytes wins!
Whoever asks on Information Security SE if this is a good hashing algorithm wins!--Don't worry SE overlords, I'm just kidding. 
  
[Answer]
## [Labyrinth](https://github.com/mbuettner/labyrinth), 76 bytes
```
 `:_64/"32}
,`    (3  :=-{
"`{"; _v2$  ;`3
"`".:@ ; ".5(`3.
<       "" `^`;>
```
Another collab with @MartinBüttner and on the more insane side of the Labyrinth spectrum – for the first time we have all four of `^>v<` in the one program. [Try it online!](http://labyrinth.tryitonline.net/#code=IGA6XzY0LyIzMn0KLGAgICAgKDMgIDo9LXsKImB7IjsgX3YyJCAgO2AzCiJgIi46QCA7ICIuNShgMy4KPCAgICAgICAiIiBgXmA7Pg&input=cGE1NSB3MHJk)
### Explanation
The general algorithm, which runs in a loop, is as follows:
```
 1.   Read a char
 2.   If EOF:
 3.     Move all digits from auxiliary stack to main
 4.     Output all digits on main stack
 5.     Halt
      Otherwise:
 6.     If char is a letter (c >= 64):
 7.       If random turns left:
 8.         Output char XOR 32
          Otherwise:
 9.         Output char
        Otherwise:
10.       Shift char to auxiliary stack
11.       If char is space (c-32 == 0):
12.         Pull char back from auxiliary stack
13.         Output underscore
          Otherwise:
14.         Continue loop
```
To keep the explanation compact, here's roughly how each part of the program corresponds to the pseudocode above:
[![enter image description here](https://i.stack.imgur.com/3NKYa.png)](https://i.stack.imgur.com/3NKYa.png)
Here are the interesting parts.
### Getting randomness in Labyrinth
There's only one way to get randomness in Labyrinth, and it's when the IP tries to go forwards but 1) there's neither a path forwards nor backwards and 2) there's paths available left and right. In this case, the IP randomly chooses between the left and right routes.
This is only possible using the`^>v<` operators, which pop `n` and shift the row/column `n` away by 1. For example, the program ([Try it online!](http://labyrinth.tryitonline.net/#code=IiAxCiIidiFACiAgMgogICAhQA&input=))
```
" 1
""v!@
  2
   !@
```
outputs either 1 or 2 randomly, since the `v` shifts the column with offset 0 (i.e. the column the IP is on) by 1, yielding
```
"
""1!@
  v
  2!@
```
The IP is facing rightward and tries to go forwards (top of stack is zero) but can't. It also can't move backwards, so it randomly chooses between left or right.
### Golf tricks
* The program starts from the first char in reading order, which you'll notice is actually step 6. However, popping from an empty Labyrinth stack yields 0, so steps 10 and 14 occur, shifting a zero to the auxiliary stack, which is effectively a no-op.
* The main stack is effectively empty after every iteration, which allows us to golf the code layout by using `>` and `<` on the implicit zeroes at the bottom. The `>` wraps the bottom row around so that the IP moves from the bottom right to the bottom left, and the `<` shifts the row back. The IP then happily moves up the left column to continue the loop.
* Digits in Labyrinth pop `n` and push `10*n + <digit>`. In addition, chars are taken modulo 256 before being output. Putting these two together lets us output 95 (underscore) by doing ``33` to 32 (space), which works because `-3233 % 256 = 95`. Even though there are other ways to turn 32 into 95 (`;95` being the easiest), working with a negative number here allows us to compact the code a bit with left turns.
[Answer]
# Pyth, 15 bytes
```
s}D`MTrRO2Xzd\_
```
[Demonstration](https://pyth.herokuapp.com/?code=s%7DD%60MTrRO2Xzd%5C_&input=pa55+w0rd&debug=0)
```
s}D`MTrRO2Xzd\_
                   Implicit: z = input(), d = ' '
          Xzd\_    In z, replace ' ' with '_'.
      rR           To each character, apply r-function
        O2         Randomly 0 or 1. r 0 is lowercase, r 1 is uppercase.
 }D                Order the characters based on presence in
   `MT             The strings of the numbers 0 to 9.
s                  Concatenate into a string.
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~22~~ ~~21~~ 20 bytes
Code:
```
þ¹žh-s«ð'_:vyždÈiš}?
```
Uses **CP-1252** encoding.
[Try it online!](http://05ab1e.tryitonline.net/#code=w77CucW-aC1zwqvDsCdfOnZ5xb5kw4hpxaF9Pw&input=cGE1NSB3MHJk)
[Answer]
## Python, 107 bytes
```
from random import*
lambda s:''.join([choice(c+c.swapcase()),'_'][c<'!']for c in sorted(s,key=str.isdigit))
```
An improvement on the [other](https://codegolf.stackexchange.com/a/76550/21487) [two](https://codegolf.stackexchange.com/a/76501/21487) Python answers because:
* `[...,'_'][c<'!']` is used instead of `s.replace(' ','_')`, and
* `choice(c+c.swapcase())` is used instead of `choice([c.upper(),c.lower()])`
[Answer]
# [CJam](https://sourceforge.net/projects/cjam/), 25 bytes
```
lelS'_er{58<}${2mr{eu}&}%
```
[**Try it online!**](http://cjam.tryitonline.net/#code=bGVsUydfZXJ7NTg8fSR7Mm1ye2V1fSZ9JQ&input=SGVsbG8sIDEyMyBpdCBpcw)
### Explanation
Translation of my MATL answer.
```
l                            e# read line as a string
 el                          e# make lowercase
   S'_er                     e# replace spaces by underscores
        {58<}$               e# (stable) sort with key "is digit"
              {        }%    e# map block over the string
               2mr           e# generate 0 or 1 equiprobably
                  {eu}&      e# if it's 1, make uppercase
```
[Answer]
## CJam, 23 bytes
```
lS'_er{60<}${eu_el+mR}%
```
[Test it here.](http://cjam.aditsu.net/#code=lS'_er%7B60%3C%7D%24%7Beu_el%2BmR%7D%25&input=pa55%20w0rd)
### Explanation
```
l       e# Read input.
S'_er   e# Turn spaces into underscores.
{60<}$  e# Sort (stably) by whether the character is a digit or not. This moves digits
        e# to the end, without changing the relative order within digits or non-digits.
{       e# Map this block over the characters...
  eu    e#   Convert to upper case.
  _el   e#   Make a copy and convert to lower case.
  +     e#   Join them into one string.
  mR    e#   Randomly choose one of the characters. Of course, this entire block is a
        e#   no-op for non-letter characters.
}%
```
[Answer]
## JavaScript (ES6), ~~114~~ 101 bytes
```
s=>s.replace(/./g,c=>c>'9'?c[`to${Math.random()<.5?"Low":"Upp"}erCase`]():c>' '?(s+=c,''):'_',s='')+s
```
47 bytes just to randomise the case of a character...
Edit: Saved a massive 13 bytes thanks to @edc65.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 27 bytes
```
k32'_'XEt58<2$S"@rEk?Xk]]v!
```
[**Try it online!**](http://matl.tryitonline.net/#code=azMyJ18nWEV0NTg8MiRTIkByRWs_WGtdXXYh&input=J3BhNTUgdzByZCc)
```
k         % implicit input. Make lowercase. Non-lettters are not affected
32'_'XE   % replace spaces by underscores
t58<      % duplicate. Create logical index: true for digits, false otherwise
2$S       % sort first string according to second. Sort is stable
"         % for each character in that string
  @       %   push that character
  rEk     %   generate 0 or 1 with 1/2 probability each
  ?       %   if it's a 1
    Xk    %     make uppercase. Non-letters are not affected
  ]       %   end if
]         % end for each
v         % vertically concatenate all stack contents
!         % transpose into a row char array, i.e. a string. Implicit display
```
[Answer]
# Python 3, ~~128 122~~  118 chars
```
from random import*
s=lambda x:''.join(choice(i.upper()+i.lower())for i in sorted(x.replace(' ','_'),key=str.isdigit))
```
Thanks to xnor for shaving off 6 bytes.
[Answer]
# Perl 6, ~~77~~ ~~75~~ 61 bytes
```
{[~] |S:g/' '/_/.comb(/\D/)».&{(.lc,.uc).pick},|.comb(/\d/)}
```
`S///` is like `s///` except it doesn't modify `$_` in place
[Answer]
# Pyth, 17 bytes
```
smrdO2o}N`UT:zd\_
```
[Try it here!](http://pyth.herokuapp.com/?code=smrdO2o%7DN%60UT%3Azd%5C_&input=pa55%20w0rd&debug=0)
## Explanation
```
smrdO2o}N`UT:zd\_   # z = input
            :zd\_   # replace spaces with underscores
      o             # Sort ^ with key function(N)
       }N`UT        # N in "0123456789", gives 1 for numbers so they get sorted to the right
 m                  # map every character d of ^
  rdO2              # Convert d randoms to upper- or lowercase
s                   # join list back into one string
```
[Answer]
## Mathematica, 86 bytes
*Thanks to Sp3000 for saving 1 byte.*
```
RandomChoice[{ToLowerCase,Capitalize}]@#/." "->"_"&/@Characters@#~SortBy~{DigitQ}<>""&
```
Ahhh, string processing Mathematica... isn't it lovely. This is an unnamed function that takes and returns a string.
Due to all the syntactic sugar, the reading order is a bit funny:
```
Characters@#
```
Split the string into characters, otherwise we can't really do anything at all with it.
```
...~SortBy~{DigitQ}
```
Sorts the digits to the end. By wrapping the test function in a list, we make the sorting stable.
```
...&/@...
```
Maps the left-hand function over each character in the list.
```
RandomChoice[{ToLowerCase,Capitalize}]
```
Chooses a random case-changing function for the current character.
```
...@#...
```
Applies it to the current character.
```
.../." "->"_"
```
Replaces spaces with underscores.
```
...<>""
```
Finally joins all the characters back together into a string.
[Answer]
# PowerShell, 113 Bytes
```
-join([char[]]$args[0]-replace" ","_"|%{if($_-match"\d"){$d+=$_}else{"'$_'.To$("Low","Upp"|random)er()"|iex}})+$d
```
---
PowerShell stands for horrible golfing language. Split into char array and replace spaces with underscores. Take each character and process. Collect numbers into variable $d for later output. Each other character is randomly make into uppercase or lowercase by invoking an expression using `'char'.ToLower()` or `'char'.ToUpper()`. If any digits were collected append them on the end.
[Answer]
# Perl, ~~51~~ 48 bytes
Includes +2 for `-lp`
Run with the input on STDIN:
```
perl -lp passwordify.pl <<< "Hel1lo wo4rld"
```
`passwordify.pl`:
```
s%\pL%$&^$"x rand 2%eg;$_=y/ 0-9/_/dr.s/\D//gr
```
[Answer]
# Julia, ~~88~~ ~~87~~ 78 bytes
```
s->join([c<33?'_':rand([ucfirst,lcfirst])("$c")for c=sort([s...],by=isdigit)])
```
This is an anonymous function that accepts a string and returns a string. To call it, assign it to a variable.
First we break the input string into an array of its characters, and sort the array according to whether each character is a digit. This maintains order in the text and digits but pushes digits to the end. Then, for each character in the array, we check whether it's a space. If so, replace with an underscore, otherwise randomly choose one of `ucfirst` or `lcfirst` to apply to the character, thereby converting it to upper- or lowercase, respectively. Join the array into a string and we're done!
[Try it here](http://goo.gl/NiwvFh)
Saved 9 bytes thanks to Sp3000!
[Answer]
# Ruby, 84 bytes
Anonymous function. Removing the space before `c.downcase` causes a syntax error for some reason and I'm not sure why.
```
->s{q="";s.gsub(/./){|c|c=~/\d/?(q+=c;p):c==" "??_:rand<0.5?c.upcase: c.downcase}+q}
```
[Answer]
# Factor, 154 bytes
or 222 with importing `kernel splitting sequences ascii combinators.random regexp`
```
: f ( x -- y ) R/ \d/ R/ \D/ [ all-matching-subseqs ] bi-curry@ bi [ { [ >upper ] [ >lower ] } call-random ] map [ "" join ] bi@ " " "_" replace prepend ;
```
I'm not too good at golfing in factor, and I'm not sure if I took the best approach here, but thought I'd give it a go
[Answer]
## Lua, 125 Bytes
When object meets functional, you can do some pretty things, even in lua! I don't think I can golf this down, it's already quite a huge mess, and I'm already happy to beat most of the python answers :D.
```
s=""print((...):gsub("%d",function(d)s=s..d return""end):gsub("%s","_"):gsub("%a",1<math.random(2)and s.upper or s.lower)..s)
```
### Ungolfed and explanations
```
s=""                       -- Initialise the string that will contains the digits
print((...)                -- apply the following to the argument then print it
  :gsub("%d",function(d)   -- iterate over the digits
    s=s..d                 -- concatenate them in s
    return""               -- remove them from the arg
   end)
  :gsub("%s","_")          -- replace spaces by underscores
  :gsub("%a",              -- iterate over letters
    1<math.random(2)       -- pick a random integer between 1 and 2
      and s.upper          -- if it is 2, use the function upper() of object s
      or s.lower)          -- else, use the function lower() of object s
  ..s)                     -- concatenate with s
```
[Answer]
## Seriously, 25 bytes
```
,`'_' (Æ≈"ûù"J£ƒ`M;ì;(-+Σ
```
[Try it online!](http://seriously.tryitonline.net/#code=LGAnXycgKMOG4omIIsO7w7kiSsKjxpJgTTvDrDsoLSvOow&input=J3BhNTUgdzByZCc)
Explanation:
```
,`'_' (Æ≈"ûù"J£ƒ`M;ì;(-+Σ
,`              `M         map over input:
  '_' (Æ                     replace spaces with underscores
        ≈                    cast to int (does nothing if cast fails)
         "ûù"J£ƒ             randomly upper- or lowercase it (does nothing if not letter)
                  ;ì;(-+   move ints to back
                        Σ  join
```
[Answer]
# [IPOS](https://github.com/DenkerAffe/IPOS) - non competing, 14 bytes
```
S'_RE`N-`dE!k?
```
Yes, I added builtins for this challenge, but those are not especially targeted at this problem.
This works with [version 0.1 of the interpreter](https://github.com/DenkerAffe/IPOS/releases/tag/v0.1).
## Example run
```
> python IPOS.py S'_RE`N-`dE!k? -i "pa55 w0rd"
Pa_WrD550
```
## Explanation
```
     # Implicit: place input on the stack (C)
S    # Push a space to the stack (B)
'_   # Push an underscore to the stack (A)
R    # In C replace B with A -> replace underscores with spaces
     # the stack contains now only the replaced string (C)
E    # Push an empty string (B)
`    # Start a command literal,
     # the stack for this gets initialized with a single character (B) later
N    # Push the digits 0-9 as string to the stack (A)
-    # Remove every character from B that is in A
`    # End command literal (A)
d    # split C on B, sort the parts descending with the key A and join back on B.
     # The key function A transforms each character of the string to an empty string if it is a digit.
     # Since the resulting char does not contain a digit, it's key value is it's length.
     # This maps the key 0 to digits and the key 1 to non-digits. Sorting this in descending
     # order moves the digits to the right and leaves non-digits in the order they were before.
E    # Push an empty string
!k   # Push the command k (=swapcase)
?    # Apply ^ to every character randomly
     # Implicit: Output stack contents
```
[Answer]
# PHP, 368 bytes
```
$str = "pa55 w0rd";
$str = str_replace(" ","_",$str);
$output AND $numStr = "";
$numArray = ['0','1','2','3','4','5','6','7','8','9'];
for($i=0;$i<strlen($str);$i++){
    in_array($str[$i],$numArray)?($numStr = $numStr.$str[$i]):((rand(10,100)%2==0)?$str[$i] = strtoupper($str[$i]) AND $output = $output.$str[$i]:$output = $output.$str[$i]);
}
echo $output = $output.$numStr;
```
Ungolfed Code:
```
$str = "pa55 w0rd";
$str = str_replace(" ","_",$str);
$len = strlen($str);
$output = "";
$numStr = "";
$numArray = ['0','1','2','3','4','5','6','7','8','9'];
for($i=0;$i<$len;$i++){
  if(in_array($str[$i],$numArray)){
    $numStr = $numStr.$str[$i];
  }else {
      if(rand(10,100)%2==0)
      {
        $str[$i] = strtoupper($str[$i]);
      }
      $output = $output.$str[$i];
  }
}
$output = $output.$numStr;
echo $output;
```
[Answer]
## Python 2, 179 bytes
```
from random import*
f=lambda s,a=[str.upper,str.lower],n='0123456789':''.join(map(lambda x:choice(a)(x),filter(lambda x:x not in n,s).replace(' ','_')))+filter(lambda x:x in n,s)
```
There's probably a lot of room for improvement here that I'll work out later.
[Answer]
## AWK, 128 Bytes
```
{srand();for(;++i<=split($0,a,"");){s=a[i];if(s!=s+0){o=s==" "?"_":rand()>0.5?tolower(s):toupper(s);A=A o}else{N=N s}}print A N}
```
The `srand()` is needed to give us different random numbers each time it runs.  
For this to work properly with multi-line input, we'd need to put something like `A=N=""` before the `for` loop.
[Answer]
# Python 3.5 - 118 bytes:
```
from random import*
lambda y:''.join(choice([q.upper(),q.lower()])for q in sorted(y.replace(' ','_'),key=str.isdigit))
```
As you can see, I am basically using the random module's `choice` function to choose a random function (either .upper() or .lower()) for each letter in the sorted version of the string given, in which all the digits go to the end. Also, every space is replaced with an underscore in the sorted string.
[Answer]
## Python 3, 151 bytes
```
import random as r
x=input();s="";n=""
for c in x:
 if c.isdigit():n+=c
 else:s+=c.upper() if r.randint(0,1) else c.lower()
print(s.replace(" ","_")+n)
```
[Answer]
# PHP, 164 158 chars/bytes
This is better than [the other PHP golf](https://codegolf.stackexchange.com/a/76757/43587), because:
* It takes inputs
* It's shorter
# Script
```
<?$a=$b='';foreach(str_split(strtolower($argv[1]))as$c){if($c==' ')$c='_';if(preg_match("/[0-9]/",$c))$a.=$c;else$b.=(rand(0,1)?$c:strtoupper($c));}echo$b.$a;
```
# Example
```
php password.php 'thats some 1337 shit'
```
> 
> ThATs\_Some\_\_sHiT1337
> 
> 
> 
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 73 bytes
```
 i:"@")?v:" ")?v0) ?\rl?!;o01!.<
 v8<    8>00.! <o"_"/
8<>x<%*4/^o+*
 ^c<
```
Nothing crazy here, it :
* prints `_` when it encounters
* takes the mod 32 of letters, then randomly adds 8\*8 or 12\*8 before printing them
* stacks the number and print them once the end of the input is reached
You can try it [here](https://fishlanguage.com/playground) !
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 86 bytes
```
-join$(switch -r($args){' '{'_'}'[A-Z]'{"$_"|%('*per','*wer'|random)}\d{$n+="$_"}})+$n
```
[Try it online!](https://tio.run/##TZBda8IwFIavl19xcHFp1Y7KLGMXgjIGXgwUvRjMSenS4xe16ZJKBzW/vTtt3di5Ocnz5LwJyVSB2uwxSSq@HZeVd1SHlDumOORyD552eKR3xi0FiFKEwor11HvfiLLDw86l64hehloMRI9SxEVHaaxOrv2IS572x/UZa90@TyvL2MRhbOCIGV2loFA6iWlu9pK8qrCYL2nn1jqLggAKX9cym4ZvOg4Cv1XDETwEhMPhiHqD/KfHIZGmNQBqT0vmwgW6UDKg4ibXh3Q3AI7fGcocYxgDD1un0ZyTnMAd38KkPdmY9WL1fDa5Os0/jzS0mbRhda3OUqIxdcp13MOvf@k3t5AqgpLoHjXeQ65AqlMWaYT2k0BGBs1f4vL3FdfARlhmqx8 "PowerShell – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 19 bytes
```
kd$F?kd↔+ð\_Vƛk≈℅ßN
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=s&code=kd%24F%3Fkd%E2%86%94%2B%C3%B0%5C_V%C6%9Bk%E2%89%88%E2%84%85%C3%9FN&inputs=happy%20sword%20123%20green&header=&footer=)
```
  $F                # Filter out
kd                  # Digits
    ?               # Take input
       ↔         # Filter out
     kd             # Non-digits
        +           # Concatenate
         ð\_V       # Replace spaces with underscores
             ƛ      # Map...
              k≈℅ß  # If random bit
                  N # Swap case
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
v rS'_ ñ§9 Ëpu ö
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=diByUydfIPGnOSDLcHUg9g&input=InBhNTUgdzByZCI)
```
v rS'_ ñ§9 Ëpu ö     :Implicit input of string
v                    :Lowercase
  r                  :Replace
   S                 :  Space
    '_               :  with underscore
       ñ             :Sort by
        §9           :  <=9
           Ë         :Map
            p        :  Append
             u       :    Uppercase
               ö     :  Random character
```
]