Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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):

Hello world

pa55 w0rd

14 35



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.

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

27 Answers 27

up vote 12 down vote accepted

Pyth, 15 bytes



                   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.
share|improve this answer

Labyrinth, 76 bytes

,`    (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!


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
 6.     If char is a letter (c >= 64):
 7.       If random turns left:
 8.         Output char XOR 32
 9.         Output char
10.       Shift char to auxiliary stack
11.       If char is space (c-32 == 0):
12.         Pull char back from auxiliary stack
13.         Output underscore
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

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

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


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.

share|improve this answer
Every attacker trying to use this algorithm to find my password is sure to get lost... – J_F_B_M Mar 31 at 18:44
I'll just use this program as my password – AlanChavez Apr 1 at 0:56

05AB1E, 22 21 20 bytes



Uses CP-1252 encoding.

Try it online!

share|improve this answer
05AB1E code looks a bit like old English :-) – Luis Mendo Mar 29 at 18:28
@DonMuesli Hahaha, and some Czech/Bosnian/Slovene/Croatian/Slovak too :) – Adnan Mar 29 at 18:33

CJam, 25 bytes


Try it online!


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
share|improve this answer

CJam, 23 bytes


Test it here.


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.
share|improve this 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.

share|improve this answer
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 – edc65 Mar 30 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 at 23:37

MATL, 27 bytes


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
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
share|improve this 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 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()])
share|improve this answer
Oh, nice improvements. Great answer! +1 from me. – Dr Green Eggs and Ham DJ Mar 30 at 14:45

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.

share|improve this answer
It looks shorter to get the numbers at the end by sorting: lambda x:''.join(choice([i.upper(),i.lower()])for i in sorted(x.replace(' ','_'),key=str.isnumeric)) – xnor Mar 29 at 22:54
@xnor Thanks! I really should learn and start using lambdas... – Dr Green Eggs and Ham DJ Mar 29 at 23:05

Pyth, 17 bytes


Try it here!


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
share|improve this 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:


Split the string into characters, otherwise we can't really do anything at all with it.


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.


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.

share|improve this 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

share|improve this 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.

share|improve this answer
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. – TimmyD Mar 29 at 20:49

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

Saved 9 bytes thanks to Sp3000!

share|improve this 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

share|improve this 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}
share|improve this 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
  :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
share|improve this answer

Perl, 51 48 bytes

Includes +2 for -lp

Run with the input on STDIN:

perl -lp <<< "Hel1lo wo4rld"

s%\pL%$&^$"x rand 2%eg;$_=y/ 0-9/_/dr.s/\D//gr
share|improve this answer

Seriously, 25 bytes

,`'_' (Æ≈"ûù"J£ƒ`M;ì;(-+Σ

Try it online!


,`'_' (Æ≈"ûù"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
share|improve this 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.

share|improve this 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.

share|improve this 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.

share|improve this answer

IPOS - non competing, 14 bytes


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 S'_RE`N-`dE!k? -i "pa55 w0rd"


     # 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
share|improve this answer

PHP Golfed Code.

$str = "pa55 w0rd";
$str = str_replace(" ","_",$str);
$output AND $numStr = "";
$numArray = ['0','1','2','3','4','5','6','7','8','9'];
    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;

PHP 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'];
    $numStr = $numStr.$str[$i];
  }else {
        $str[$i] = strtoupper($str[$i]);
      $output = $output.$str[$i];
$output = $output.$numStr;
echo $output;
share|improve this answer

PHP, 164 158 chars/bytes

This is better than the other PHP golf, because:

  • It takes inputs
  • It's shorter


<?$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;


php password.php 'thats some 1337 shit'


share|improve this answer

><>, 73 bytes

 i:"@")?v:" ")?v0) ?\rl?!;o01!.<
 v8<    8>00.! <o"_"/

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 !

share|improve this answer

Python 3, 151 bytes

import random as r
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)
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.