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.

• Great. Now you've published my scheme. Be right back, changing all my passwords... Mar 29 '16 at 17:35
• It's not even a password hashing algorithm... it would be killed with fire on Security SE XD Mar 29 '16 at 18:08
• If only there was an easy way to do randomness in Retina... Mar 29 '16 at 18:30
• This is not a good hashing algo because it's randomized Mar 29 '16 at 19:57
• I'm tempted to use some of the answers as a password Mar 29 '16 at 23:34

# Pyth, 15 bytes

s}DMTrRO2Xzd\_


Demonstration

s}DMTrRO2Xzd\_
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.


## 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! ### 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: 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!) " 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. • Every attacker trying to use this algorithm to find my password is sure to get lost... – JFBM Mar 31 '16 at 18:44 • I'll just use this program as my password Apr 1 '16 at 0:56 # 05AB1E, 2221 20 bytes Code: þ¹žh-s«ð'_:vyždÈiš}?  Uses CP-1252 encoding. Try it online! ## 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 two Python answers because: • [...,'_'][c<'!'] is used instead of s.replace(' ','_'), and • choice(c+c.swapcase()) is used instead of choice([c.upper(),c.lower()]) • Oh, nice improvements. Great answer! +1 from me. Mar 30 '16 at 14:45 • c+c.swapcase() can be (c+c).title() for -1 Aug 18 at 10:15 # CJam, 25 bytes lelS'_er{58<}${2mr{eu}&}%


Try it online!

### Explanation

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  ## CJam, 23 bytes lS'_er{60<}${eu_el+mR}%


Test it here.

### 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. }%  ## 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.

• I'm late to the party again. The low/upp is great! But the rest can be simpler: f=s=>s.replace(/./g,x=>x>'9'?x[to${Math.random()<.5?"Low":"Upp"}erCase]():x>' '?(s+=x,''):'_',s='')+s Mar 30 '16 at 21:46 • @edc65 Wow. Even just combining the space/underscore replacement with the upper/lower case replacement saves two bytes but this is fantastic! – Neil Mar 30 '16 at 23:37 # MATL, 27 bytes k32'_'XEt58<2$S"@rEk?Xk]]v!


Try it online!

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

# Pyth, 17 bytes

smrdO2o}NUT:zd\_


Try it here!

## Explanation

smrdO2o}NUT:zd\_   # z = input

:zd\_   # replace spaces with underscores
o             # Sort ^ with key function(N)
}NUT        # 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


## 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.

# 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.

• PowerShell is great and does all things. :D You can save a couple bytes by using $_-in0..9 and the -in operator introduced in PowerShell v3 instead of the regex -match. Mar 29 '16 at 20:49 # 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


# Julia, 8887 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 Saved 9 bytes thanks to Sp3000! # 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}  # 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 ## 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  ## Seriously, 25 bytes ,'_' (Æ≈"ûù"J£ƒM;ì;(-+Σ  Try it online! 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  # IPOS - non competing, 14 bytes S'_REN-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. ## Example run > python IPOS.py S'_REN-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  # 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;

• This is a great start, but you can golf this a lot more. Please change all the variables to 1-char names, and remove extra whitespace. When you do that, this will be a first-class golf! Feb 1 '17 at 17:22

## 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.

{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. # 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. ## 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)  # PHP, 164 158 chars/bytes This is better than the other PHP golf, 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 # ><>, 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 ! # PowerShell, 86 bytes -join$(switch -r($args){' '{'_'}'[A-Z]'{"$_"|%('*per','*wer'|random)}\d{$n+="$_"}})+$n  Try it online! # Vyxals, 19 bytes kd$F?kd↔+ð\_Vƛk≈℅ßN


Try it Online!

  \$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

• @Shaggy Oh ok. Fiixing... Aug 18 at 9:01

# Japt v2.0a0, 16 bytes

v rS'_ ñ§9 Ëpu ö


Try it

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
`