Passwordify the string

31

4

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.

Daniel

Posted 2016-03-29T17:24:44.070

Reputation: 6 425

47Great. Now you've published my scheme. Be right back, changing all my passwords... – Geobits – 2016-03-29T17:35:59.840

8It's not even a password hashing algorithm... it would be killed with fire on Security SE XD – Justin – 2016-03-29T18:08:31.807

1If only there was an easy way to do randomness in Retina... – mbomb007 – 2016-03-29T18:30:26.273

1I honestly wonder if someone were to post the most obfuscated of these answers if Security.SE would even be able to figure out what it was doing to shame it. – CAD97 – 2016-03-29T18:35:32.213

4This is not a good hashing algo because it's randomized – CalculatorFeline – 2016-03-29T19:57:45.670

If only there was a way to do randomness in Retina... – CalculatorFeline – 2016-03-29T20:01:04.553

6I'm tempted to use some of the answers as a password – MickyT – 2016-03-29T23:34:52.320

Full program or function? – HyperNeutrino – 2016-03-30T00:59:52.657

@AlexL. I think that either works. I didn't specify before, and I'm not sure yet if some people answered with full programs or functions, so I do not want to nullify any answers unfairly. – Daniel – 2016-03-30T01:02:38.823

@Dopapp Okay. Thanks. – HyperNeutrino – 2016-03-30T01:05:23.080

May I suggest changing the title to "Tr0ub4dor&3-ize the string"? Because of the popularity of the comic, a method of creating passwords similar to this is sometimes known as the "troubador method," and I suspect most who frequent StackExchange will understand the reference immediately.

– jpmc26 – 2016-04-01T01:02:47.650

@Dopapp I appreciate the thought of acceptance, but I don't think my answer's the shortest :P – Sp3000 – 2016-04-11T03:05:09.747

@Sp3000, well great answer anyway and a +1 from me – Daniel – 2016-04-11T03:07:03.847

Answers

12

Pyth, 15 bytes

s}D`MTrRO2Xzd\_

Demonstration

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.

isaacg

Posted 2016-03-29T17:24:44.070

Reputation: 39 268

27

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:

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

Sp3000

Posted 2016-03-29T17:24:44.070

Reputation: 58 729

2Every attacker trying to use this algorithm to find my password is sure to get lost... – J_F_B_M – 2016-03-31T18:44:28.013

3I'll just use this program as my password – ILikeTacos – 2016-04-01T00:56:29.037

8

05AB1E, 22 21 20 bytes

Code:

þ¹žh-s«ð'_:vyždÈiš}?

Uses CP-1252 encoding.

Try it online!

Adnan

Posted 2016-03-29T17:24:44.070

Reputation: 41 965

2

05AB1E code looks a bit like old English :-)

– Luis Mendo – 2016-03-29T18:28:39.943

1

@DonMuesli Hahaha, and some Czech/Bosnian/Slovene/Croatian/Slovak too :)

– Adnan – 2016-03-29T18:33:55.067

7

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

Luis Mendo

Posted 2016-03-29T17:24:44.070

Reputation: 87 464

7

CJam, 25 bytes

lelS'_er{58<}${2mr{eu}&}%

Try it online!

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

Luis Mendo

Posted 2016-03-29T17:24:44.070

Reputation: 87 464

7

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

Martin Ender

Posted 2016-03-29T17:24:44.070

Reputation: 184 808

7

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.

Neil

Posted 2016-03-29T17:24:44.070

Reputation: 95 035

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 – 2016-03-30T21:46:56.070

@edc65 Wow. Even just combining the space/underscore replacement with the upper/lower case replacement saves two bytes but this is fantastic! – Neil – 2016-03-30T23:37:30.730

7

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()])

Sp3000

Posted 2016-03-29T17:24:44.070

Reputation: 58 729

Oh, nice improvements. Great answer! +1 from me. – James – 2016-03-30T14:45:01.547

5

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.

James

Posted 2016-03-29T17:24:44.070

Reputation: 54 537

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 – 2016-03-29T22:54:50.723

@xnor Thanks! I really should learn and start using lambdas... – James – 2016-03-29T23:05:41.730

5

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

Hotkeys

Posted 2016-03-29T17:24:44.070

Reputation: 1 015

4

Pyth, 17 bytes

smrdO2o}N`UT:zd\_

Try it here!

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

Denker

Posted 2016-03-29T17:24:44.070

Reputation: 6 639

4

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.

Martin Ender

Posted 2016-03-29T17:24:44.070

Reputation: 184 808

3

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.

Matt

Posted 2016-03-29T17:24:44.070

Reputation: 1 075

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. – AdmBorkBork – 2016-03-29T20:49:56.320

3

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!

Alex A.

Posted 2016-03-29T17:24:44.070

Reputation: 23 761

2

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

Ton Hospel

Posted 2016-03-29T17:24:44.070

Reputation: 14 114

1

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

Hotkeys

Posted 2016-03-29T17:24:44.070

Reputation: 1 015

1

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}

Value Ink

Posted 2016-03-29T17:24:44.070

Reputation: 10 608

1

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

Katenkyo

Posted 2016-03-29T17:24:44.070

Reputation: 2 857

1

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

Mego

Posted 2016-03-29T17:24:44.070

Reputation: 32 998

1

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.

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

Denker

Posted 2016-03-29T17:24:44.070

Reputation: 6 639

1

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;

Siddharajsinh Zala

Posted 2016-03-29T17:24:44.070

Reputation: 11

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! – NoOneIsHere – 2017-02-01T17:22:26.327

0

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.

Mego

Posted 2016-03-29T17:24:44.070

Reputation: 32 998

0

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.

Robert Benson

Posted 2016-03-29T17:24:44.070

Reputation: 1 339

0

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.

R. Kap

Posted 2016-03-29T17:24:44.070

Reputation: 4 730

0

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

timmyRS

Posted 2016-03-29T17:24:44.070

Reputation: 329

0

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

Aaron

Posted 2016-03-29T17:24:44.070

Reputation: 3 689

-1

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)

Argenis García

Posted 2016-03-29T17:24:44.070

Reputation: 223