57
\$\begingroup\$

Remember those brute-force programs to crack password that show every combination they are trying? More precisely, at one point, the n first characters are fixed (they have been guessed successfully), and every possible character for the remaining ones is being tested. You've probably seen some in movies, or in some software written by people that like fancy interfaces.
Sorry to disappoint, but we won't write a program to crack password, only one to reproduce the nice output.

Challenge

Given a string containing printable ascii characters but no newlines (ascii code 32 to 126 or matching the regex ^[ -~]{2,}$), print an output following this rules:

  • At time t=n seconds, the n first characters printed are the n first characters of the input string.
  • After the n fixed characters, you should append a string formed random character (chosen uniformly pseudo-randomly from the unicode range   to ~ (code 32 to 126)) to form a string of the length of the initial one.
  • You should output at least (more on that later) 20 lines every second: every one of them will have the same n first characters, but a different random end.

It's probably not very clear yet what you are supposed to do, so lets go through an example:

Example

I'll print only 5 different lines for every seconds instead of the 20 minimum just to make it more readable.

Consider the input abcde.
During the first second, a valid output can be something like (completely random):

dGuT4
S!jkN
"gQ>[
TU3! 
*fAjV

Then, t=1, the first character of every following string will be a (the first character of the input):

a);jD
aHv^p
aqw5*
a|.?:
a{gbK

Now, t=2, the first two characters will be ab:

abTJ"
ab\ e
ab3T#
abYWS
ab"#<

Now, t=3, the first three characters will be abc :

abcvW
abc3G
abc(g
abc{@
abc@4

Now, t=4, the first four characters will be abcd :

abcdD
abcdv
abcdj
abcd$
abcd6

Finally, t=5, we print the input (only once):

abcde

A few precisions

  • You shouldn't bother too much with your language precision toward the seconds (ie. If your algorithm is correct but your system/language lacks precision then it's fine).
  • The first second can be shorter than one second (That is, if you launch you program during a second, the first second can be just the remaining time until the end of the current second). Or put differently, you don't have to wait for the start of a new second to start printing the outputs.
  • At least 20 lines per second: The more natural way would be an infinite loop with a special behaviour one every second (or a timeout, or whatever), so that will result in probably a few thousand lines per second (and that's perfectly fine!). But if you have another idea, feel free to use it as long as you print at least 20 lines per second.
  • The input will always be more than 2 characters long.
  • You can consider that the input won't be more that 30 characters long if it helps. (But if it works for longer ones, it's for the best)
  • The input format should be the most natural representation of a string in your language.
  • You are allowed to print a trailing newline.

Code example

If you still don't understand exactly what you have to do, you can run the following code in a linux terminal to see:

perl -F -aplE 'map{$t=time;print$s,map{chr 32+rand 94}@F until$t-time;$s.=shift@F}@F' <<< "Cracking in progress\!"

Winning criterion

This is , so shortest code in byte wins!


Thanks to Laikoni and Flp.Tkc for their suggestions and improvement in the sandbox.

\$\endgroup\$
15
  • 7
    \$\begingroup\$ Like this scene from the movie War Games? \$\endgroup\$ Commented Nov 21, 2016 at 23:07
  • 1
    \$\begingroup\$ Is it mandatory to separate the lines of output with \r (making them all replace each other onscreen like in the animation), or is \n acceptable? \$\endgroup\$
    – user62131
    Commented Nov 21, 2016 at 23:10
  • 1
    \$\begingroup\$ @ais523 \n is perfectly acceptable. The version with \r is just here because it looks better, but you don't need those \r. \$\endgroup\$
    – Dada
    Commented Nov 21, 2016 at 23:12
  • \$\begingroup\$ If the random generation happens to crack the password earlier is it alright to stop at that point? \$\endgroup\$ Commented Nov 21, 2016 at 23:40
  • 3
    \$\begingroup\$ Shouldn't you include in the rules that the random characters should not be the actual character in that place ? Otherwise random strings can match the password given, but the search goes on, which movie buffs would rate as a glitch. \$\endgroup\$
    – Tom
    Commented Nov 22, 2016 at 10:29

27 Answers 27

28
\$\begingroup\$

HTML/JavaScript, 170 168 167 bytes

setInterval('o.textContent=i.value.replace(/./g,(c,i)=>new Date-d>++i*1e3?c:String.fromCharCode(Math.random()*95+32))',d=50)
<input id=i oninput=d=Date.now()><pre id=o>

Edit: Saved 2 bytes thanks to @ETHproductions. Saved 1 byte thanks to @jrich.

\$\endgroup\$
2
  • \$\begingroup\$ Haven't tested this, but I believe setInterval will accept a string to be eval'd, which could potentially save a byte?setInterval('o.textContent...',d=50) saves the _=> and adds a pair of quotes \$\endgroup\$
    – jrich
    Commented Nov 23, 2016 at 0:29
  • \$\begingroup\$ @jrich That was handy, as I'd forgotten to update my byte count! \$\endgroup\$
    – Neil
    Commented Nov 23, 2016 at 1:31
20
\$\begingroup\$

Node, 145 142 bytes

for(s=process.argv[2],d=new Date;s[a=(new Date-d)/1e3|0]+console.log(s.replace(/./g,(c,i)=>i<a?c:String.fromCharCode(32+Math.random()*95))););

This seems a little long, and there's probably a little room for golfing. Note that the semicolon at the end is required; without it the program throws a syntax error because the for statement has no body.

Outputs way more than 20 lines per second; a little birdie told me that it's roughly 12 thousand. Here's how it looks in the ConEmu terminal emulator on my computer (recorded at 30 fps):

enter image description here

\$\endgroup\$
10
\$\begingroup\$

05AB1E, 26 bytes

I post this as a different answer with respect to the other 05AB1E answer since the approach is different

.põ¸ì¨vT·FyžQ.r¹gyg-£«}}¹»

.p                         Generate ordered prefix of input (e.g., ["a", "ab", "abc", "abcd", "abcde"] for "abcde")
  õ¸ì                      Prepend an empty string (e.g., result is ["", "a", "ab", ...])
     ¨                     Strip the last element (the same string as the input)
      v                    For each string in the array
       T·F                 For N in range(20)
          y                Push the current string
           žQ.r            Push all printable characters, shuffled
               ¹gyg-       Take the difference between the length of the input and the length of the current string -> x
                    £      Take the x first characters from the shuffled printable characters
                     «     Yield currentString + shuffledCharacters
                      }    End inner for
                       }   End outer for
                        ¹  Push input (last iteration)
                         » Join everything with newlines and implicitly display

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Nice answer, +1 from me! NOTE: It can be 22 bytes with the newer builtins these days: η instead of .p; õš (where š is prepend as list) instead of õ¸ì (where ¸ì is wrap in list, and prepend); (where is 26 if no second input is given) instead of (which is push 10, and double); ] instead of }} (where ] closes all loops, if-else statements, etc. at the same time) \$\endgroup\$ Commented Oct 16, 2018 at 9:48
8
\$\begingroup\$

BASH, 99 93 92 91 88 bytes

with tr + head + urandom

while ((${#1}-n));do
echo "${1::n=SECONDS}`tr -dc \ -~</dev/ur*|head -c$[${#1}-n]`"
done

(thx. to @manatwork )

\$\endgroup\$
7
  • 5
    \$\begingroup\$ [ "$n" = ${#1} ]((n==${#1})); ${1:0:$n}${1::n} \$\endgroup\$
    – manatwork
    Commented Nov 22, 2016 at 11:18
  • \$\begingroup\$ @manatwork: whoa! \$\endgroup\$ Commented Nov 22, 2016 at 11:32
  • 1
    \$\begingroup\$ 1 more: the space in front of input redirection < is not needed. \$\endgroup\$
    – manatwork
    Commented Nov 22, 2016 at 11:54
  • 1
    \$\begingroup\$ @manatwork ((n==${#1})) --> ((${#1}-n)) \$\endgroup\$ Commented Nov 22, 2016 at 12:41
  • 1
    \$\begingroup\$ Either because you reversed the logic or because I banged my previous test, but ${1::n=SECONDS} seems to work now. \$\endgroup\$
    – manatwork
    Commented Nov 22, 2016 at 12:46
7
\$\begingroup\$

05AB1E, 30 bytes

gFžcUNV[¹Y£žQ.r¹gY-£J,XžcÊ#}¹,

Uses the CP-1252 encoding. Try it online!

Please help me golf this down.

\$\endgroup\$
0
6
\$\begingroup\$

C, 182 176 128 126 125 bytes

Golfed:

i;s;n;x;g(char*c){time(&s);while(c[++x]);do{n=time(0)-s;for(i=0;i<x;i++)putchar(i<n?c[i]:32+rand()%95);puts("");}while(n<x);}

Ungolfed:

#include "stdio.h"
#include "stdlib.h"
#include "time.h"
int i,s,n,x;
void g(char* c) {
  time(&s); //Get the initial time
  while(c[++x]); // x = strlen(c) (happy about this one)
  do {
    n = time(0) - s; //seconds since beginning
    for(i = 0; i < x; i++)
      //after each second, print another char of the password
      putchar(i < n ? c[i] : 32 + rand() % 95);
    puts("");
  } while(n < x); //while we haven't printed the whole word
}

I've heard that it's possible to drop some standard #includes, but I couldn't get it to work on the MingW GCC compiler I just downloaded. Also couldn't figure out how to #define b #include without using more space than it was worth. I'm just an idiot, it works fine without them.

\$\endgroup\$
10
  • \$\begingroup\$ X=0 is not required instead declare it with others like this a,b,c,d; cuz all global variables declared like that are int and init by 0 also since you are returning nothing you should write it in main () \$\endgroup\$ Commented Nov 22, 2016 at 18:42
  • 1
    \$\begingroup\$ Thanks, I didn't know about static scope initialization. I did declare them like that, just with semi-colons instead of commas. Also I didn't use main because I think then I'd need to take (int argc, char ** argv) and that's a ton of bytes. I hope leaving it as a function is OK, although it takes input as a parameter and output to stdout which is slightly odd. \$\endgroup\$
    – nmjcman101
    Commented Nov 22, 2016 at 21:07
  • 1
    \$\begingroup\$ Use while(i++<x) instead of for (...) \$\endgroup\$ Commented Nov 22, 2016 at 23:31
  • \$\begingroup\$ Really good idea, but i needs to be zero everytime the for loop runs again. \$\endgroup\$
    – nmjcman101
    Commented Nov 23, 2016 at 12:18
  • \$\begingroup\$ Then in the same for replace i <x with i++<x and remove i++ \$\endgroup\$ Commented Nov 23, 2016 at 13:06
5
\$\begingroup\$

Java 7, 271 265 207 bytes

void c(String s)throws Exception{for(int i=0,j,l=s.length();i<=l*20;i++){String r=s.substring(0,i/20);Thread.sleep(45);for(;j++<l;r+=(char)(32+Math.random()*95);System.out.println(r);if(s.equals(r))return;}}

-58 bytes saved thanks to @OliverGrégoire. (Don't forget to upvote his even shorter Java 8 answer.)

Ungolfed:

void c(String s) throws Exception{
  for(int i = 0, j, l = s.length(); i <= l*20; i++){
    String r = s.substring(0, i/20);
    Thread.sleep(45);
    for( ; j++ < l; r += (char)(32+Math.random()*95));
    System.out.println(r);
    if(s.equals(r)){
      return;
    }
  }
}

Input: abcde
Output:

enter image description here

\$\endgroup\$
6
  • \$\begingroup\$ I'm not sure if you designed it purposefully to only print 20 lines per second, but if it helps your golfing, you only have to print at least 20 lines per second. I don't know if changing the "20 lines per second" math to "change every second" math would help or not. \$\endgroup\$
    – nmjcman101
    Commented Nov 22, 2016 at 16:03
  • \$\begingroup\$ You don't need x: r+=(char)(33+Math.random()*94). Also Thread.sleep(9) to save a byte. \$\endgroup\$ Commented Nov 22, 2016 at 21:40
  • 1
    \$\begingroup\$ Also, r=s.substring(0,i/20) instead of the loop on j. \$\endgroup\$ Commented Nov 22, 2016 at 21:42
  • \$\begingroup\$ Given the significant changes I made, I decided to post my answer with those comments taken in account. Also, it's a Java 8 solution to go rather low in the byte count (Java-wise, ofc). \$\endgroup\$ Commented Nov 22, 2016 at 23:53
  • \$\begingroup\$ @OlivierGrégoire Thanks. And I've upvoted your answer. I haven't made all changes, only the r.substring(0,i/20) (pretty stupid of me), and the (char)(33+Math.random()*94) (nice trick from you). \$\endgroup\$ Commented Nov 23, 2016 at 8:14
4
\$\begingroup\$

WinDbg, 400 391 bytes

.for(r$t1=@$t0;by(@$t1);r$t1=@$t1+1){};m@$t0 L@$t1-@$t0+1 @$t1+1;r$t4=2*@$t1+2-@$t0;r$t8=@$t4+f;r$t3=0;.for(r$t2=0;@$t2<@$t1-@$t0;da@$t0){.for(r$t7=@$t0+@$t2;by(@$t7);r$t7=@$t7+1;r$t8=@$t8+1){eb@$t7 by(@$t8)%5e+20};r$t9=0;.foreach(p {.echotime}){.if7==@$t9{ea@$t4"p";.if1>@$t3{r$t3=by(@$t4+7)}};r$t9=@$t9+1};j@$t3!=by(@$t4+7)'m@$t0+@$t4-@$t1+@$t2-1 L1 @$t0+@$t2;r$t2=@$t2+1;r$t3=by(@$t4+7)'}

-9 bytes by simplifying some math

This definitely does not seem to be the kind of thing WinDbg is intended to do. ;)

Input is taken by entering an ascii string at a memory location and setting that address to the pseudo-register $t0. Eg:

r$t0 = 2000000
eza @$t0 "abcde"

The prng I'm using is whatever the contents in memory, some bytes past the input string. Chrome.exe appears to fill the memory space after 0x2000000 with random-looking-enough bytes so I used a dump of chrome.exe. Unknown if this is uniform, but looks random-enough to me.

How it works:

.for(r$t1=@$t0; by(@$t1); r$t1=@$t1+1){};         * From $t0, increment $t1 until the byte
                                                  * at $t1 is 0 to find length of input
m@$t0 L@$t1-@$t0+1 @$t1+1;                        * Duplicate input (memory 
                                                  * becomes: "input\0input\0")

r$t4=2*@$t1+2-@$t0;                               * Set $4 to the byte after \0 of the 
                                                  * duplicated input
r$t8=@$t4+f;                                      * Set $t8 to $t4+15, this is the prng
r$t3=0;                                           * Init $t3=0, this will hold the time

.for(r$t2=0; @$t2<@$t1-@$t0; da@$t0){             * For $t2=0, loop until it's input length,
                                                  * printing the string at $t0 after each
                                                  * loop. $t0 is where the password crack
                                                  * progress is written.
    .for(r$t7=@$t0+@$t2; by(@$t7); r$t7=@$t7+1;   * Loop over each uncracked char
                                   r$t8=@$t8+1){  * also incrementing prng ($t8)
        eb@$t7 by(@$t8)%5e+20                     * Write a visible ascii char onto the
                                                  * uncracked char position based on the 
                                                  * current byte of prng%0x5e+0x20 (prng%126+32)
    };

    r$t9=0;                                       * Set $t9=0 for updating current time
    .foreach(p {.echotime}){                      * For each (string) word in a statement
                                                  * like "Debugger (not debuggee) time: Mon 
                                                  * Nov 21 18:23:08.433 2016 (UTC - 8:00)"
        .if7==@$t9{                               * If the 7th word, ie- the current time
            ea@$t4"p";                            * Write the time at $t4
            .if1>@$t3{                            * If $t3 has not been set yet
                r$t3=by(@$t4+7)                   * ...save the current second in $t3
            }
        };
        r$t9=@$t9+1                               * Increment $t9 until it's 7
    };

    j@$t3!=by(@$t4+7)'                            * If the current second has changed
        m@$t0+@$t4-@$t1+@$t2-1 L1 @$t0+@$t2;      * Copy the cracked char from dupe input
        r$t2=@$t2+1;                              * Increment $t2 (loop ends when this is input length)
        r$t3=by(@$t4+7)                           * Save the new current second
    '
}                                                 * Final crack is printed by for loop

Note: Some bytes could be golfed by using j instead of the .if's, but that causes it to run too slowly on my machine so it doesn't output at least 20 lines per second, so not saving those bytes.

Sample Output: http://pastebin.com/H4H74sAx

\$\endgroup\$
4
\$\begingroup\$

R, 138 bytes

z=Sys.time;n=nchar(x<-scan(,""));s=z();t=0;while(t<=n){t=t+z()-s;cat(substr(x,1,f<-floor(t)),intToUtf8(sample(32:126,n-f,T)),"\n",sep="")}

Reads input from stdin.

Counted approximately 61 lines on my machine between each additional letter in the "password".

\$\endgroup\$
4
\$\begingroup\$

Bash, 247 245 212 207 bytes

R()(echo $SECONDS);w=`R`;until [ "$a" = "$1" ];do for i in `seq 1 $[${#1}-${#a}]`;{ a+=`printf "\x$(printf %x $[$RANDOM%127+32])"`;};echo -e "$a\r";a=${1:0:q};((`R`-w>0))&&{ w=`R`;((q++));}||:;done;echo "$a"

Thanks a lot Bash for being so whitespace sensitive...

Anyways, output is given in real time on separate lines. Save as a .sh script and invoke with:

bash <File Name>.sh <Input>

For example, bash Cracking_In_Progress.sh okayerty results in the following output, recorded at 30 frames per second:

Example Output

\$\endgroup\$
4
\$\begingroup\$

Haskell (GHC), 202 bytes

import System.Random
import Control.Concurrent
f s|l<-length s=mapM_(\n->putStr('\r':take n s)>>mapM(\_->toEnum<$>randomRIO(32,126))[1..l-n]>>=putStr>>threadDelay 50000)$[n|n<-[0..l-1],f<-[1..20]]++[l]

-5 bytes without fancy carriage return action

enter image description here

\$\endgroup\$
2
  • \$\begingroup\$ Looks good! But what's that > doing at the end of the output? \$\endgroup\$
    – Mast
    Commented Nov 23, 2016 at 14:54
  • 3
    \$\begingroup\$ @Mast that's the prompt. Since the code doesn't print a newline at the end, the prompt goes there. \$\endgroup\$
    – Angs
    Commented Nov 23, 2016 at 15:00
4
\$\begingroup\$

MATL, 26 bytes

`GZ`:)' ~'olGn4Mk-I$YrhD7M

Try it online!

Below is the real-time output from the offline compiler. Note that the animated GIF was recorded at 20 fps to keep its size small, but the actual speed is much greater.

enter image description here

How it works

           % Implicitly start timer
`          % Do...while
  G        %   Push input
  Z`       %   Push timer's current value, say t
  :)       %   Select the first t elements of the input, with t
           %   implicitly rounded down
  ' ~'     %   Push this string
  o        %   Convert to numbers, i.e. [32 126]
  l        %   Push 1
  Gn       %   Push input size, say n
  4Mk      %   Push floor(t), where t is the same value used above
  k        %   Subtract. Gives n-floor(t)
  I$Yr     %   Generate a row vector of n-floor(t) integers randomly
           %   chosen from 32 to 126
  h        %   Concatenate with the first characters of the input
  D        %   Display
  7M       %   Push the value n-floor(t) used above. This is used
           %   as loop condition: iz zero the loop is exited 
           % Implicit end
\$\endgroup\$
2
  • 2
    \$\begingroup\$ This code is so happy. :) \$\endgroup\$ Commented Nov 23, 2016 at 21:07
  • \$\begingroup\$ @SethMichaelLarson That's because its quote marks are balanced, which doesn't usually happen :-) \$\endgroup\$
    – Luis Mendo
    Commented Nov 23, 2016 at 22:03
3
\$\begingroup\$

Pyth - 27 24 bytes

This actually looks pretty cool :D

WJ-lQKs.d1+<QKsmOr;\~J;Q

Try it online here (obviously not in real time, but if you scroll it down with a steady hand).

\$\endgroup\$
3
\$\begingroup\$

Python3, 149 141 139 bytes

import time,random
i,x=input(),0;l=len(i)
while x<l:x=int(time.clock());print(i[:x]+"".join(chr(random.randint(32,126))for _ in"a"*(l-x)))

Input from stdin.

Eyes version (157 bytes):

import time,random
p,i,x=print,input(),0;l=len(i)
while x<l:x=int(time.clock());p(i[:x]+"".join(chr(random.randint(32,126))for _ in"a"*(l-x)),end="\r")
p(i)
\$\endgroup\$
6
  • 1
    \$\begingroup\$ I think you can save a few bytes by not "renaming" things that you only do once. For instance you have t=time.clock, but you only use t once in the code. Replacing it with just time.clock will save 3 bytes. Same thing for print. \$\endgroup\$
    – nmjcman101
    Commented Nov 22, 2016 at 16:17
  • \$\begingroup\$ @nmjcman101 Oops, carry over from prev ver. Thanks! \$\endgroup\$
    – matsjoyce
    Commented Nov 22, 2016 at 16:20
  • \$\begingroup\$ Also your for _ in range(l-x) can be for _ in"a"*(l-x) for 2 bytes. \$\endgroup\$
    – nmjcman101
    Commented Nov 22, 2016 at 16:53
  • \$\begingroup\$ @nmjcman101 Nice! I must remember that one... \$\endgroup\$
    – matsjoyce
    Commented Nov 22, 2016 at 16:59
  • \$\begingroup\$ Try print(i[:x]+''.join(map(chr,random.sample(range(32,127),l-x)))) instead of print(i[:x]+"".join(chr(random.randint(32,126))for _ in"a"*(l-x))) \$\endgroup\$ Commented Nov 24, 2016 at 17:43
3
\$\begingroup\$

Node.js, 134 bytes

for(s=[...process.argv[2]],n=new(d=Date);s[m=(new d-n)/1e3|0]+console.log(s.map((a,i)=>i<m?a:Buffer([Math.random()*95+32])).join``););

Similar to @ETHproductions (borrowed some of his optimizations), but otherwise takes a different approach. Uses Node's Buffer to handle character generation instead of the lengthy String.fromCharCode, which has the side benefit of letting us use map without much string->array->string conversion overhead.

\$\endgroup\$
1
  • \$\begingroup\$ Nice, I should learn more about Buffer. Just so you know, reassigning Date to D doesn't save any bytes; I tried that myself. \$\endgroup\$ Commented Nov 22, 2016 at 23:56
3
\$\begingroup\$

Python 3, 167 166 bytes

import time,random
t=time.time
p,s=input(),t()
while t()-s<len(p):print(p[:int(t()-s)]+''.join(chr(random.randint(32,126))for _ in range(len(p)-int(t()-s))))
print(p)

Reads input from stdin. A 171-byte version runs under Python 2 (replaced input with raw_input):

import time,random
t=time.time
p,s=raw_input(),t()
while t()-s<len(p):print(p[:int(t()-s)]+''.join(chr(random.randint(32,126))for _ in range(len(p)-int(t()-s))))
print(p)

Ungolfed:

import random
import time

p = input()
start = time.time()
while time.time() - start < len(p): 
    print(
        p[:int(time.time() - start)] + 
        ''.join(chr(random.randint(32, 126)) for _ in range(len(p) - int(time.time()-start)))
    )
print(p)
\$\endgroup\$
3
\$\begingroup\$

Dyalog APL, 59 58 bytes

Solution

Requires ⎕IO←0 which is default on many systems.

⊢⊣≢{⍵{≢⎕←⍵↑⍺,⎕UCS 32+?⍵⍴95}⍣{t≤2⊃⎕AI}⍺⊣t←1E3+2⊃⎕AI}¨⍳∘≢↑¨⊂

Display

By adjusting the window to two lines, we get the illusion of an in-place transformation:
Dyalog APL code cracking animation

Explanation

This is an anonymous function train which takes the password as right argument.

⊢⊣ return the password and dismiss the result of

≢{... the below function, with the length of the password as left argument, applied to each of

2⊃⎕AI current up-time (lit. third element of Account Information)

1E3+ add a second

t← assign that to t

dismiss that

⍵{...}⍣{t≤2⊃⎕AI}⍺ apply the following function (with sub-string as and password length as ) repeatedly until the up-time reaches t

  ⍵⍴95 95 repeated as many times as there are characters in the password

  ? random integer 0...94

  32+ add 32 (thus yielding random integers in the range 32...126)

  ⎕UCS convert to Unicode character

  ⍺, prepend the currently processed sub-string

  ⍵↑ take only as many character as there are in the password

  ⎕← output that on a separate line

   return the length of the outputted string (= the length of the password)

⍳∘≢ 0 ... length-1

↑¨each taking characters from

the password

\$\endgroup\$
2
\$\begingroup\$

Java, 159 bytes

s->{for(int i=0,j,l=s.length();i<=l*99;i++){String r=s.substring(0,j=i/20);Thread.sleep(9);for(;j++<l;r+=(char)(32+Math.random()*95));System.out.println(r);}}

Same algorithm as Kevin Cruijssen's answer, only totally optimized for Java 8.

Ungolfed:

public class Tmp {

  interface X {

    void f(String s) throws Exception;
  }
  static X f = s -> {
    for (int i = 0, j, l = s.length(); i <= l * 20; i++) {
      String r = s.substring(0, j = i / 20);
      Thread.sleep(48);
      for (; j++ < l; r += (char) (32 + Math.random() * 94));
      System.out.println(r);
    }
  };

  public static void main(String[] args) throws Exception {
    f.f("abcde");
  }
}
\$\endgroup\$
1
\$\begingroup\$

C#, 203 197 195 190 bytes

Golfed:

void F(string s){int l=s.Length,t=0;var w=Stopwatch.StartNew();do{if(w.Elapsed.Seconds>t)t++;Console.WriteLine($"{s.Substring(0,t)}{Path.GetRandomFileName().Substring(0,l-t)}");}while(t<l);}

Ungolfed:

    void F(string s)
    {
        int l = s.Length, t = 0;
        var w = Stopwatch.StartNew();

        do
        {
            if (w.Elapsed.Seconds > t)
                t++;

            Console.WriteLine($"{s.Substring(0, t)}{Path.GetRandomFileName().Substring(0, l - t)}");
        } while (t < l);
    }

l stores input length.

StopWatch and Path.GetRandomFileName() are parts of .NET framework.

EDIT1: Implicit Stopwatch declaration.

EDIT2: l initialization merged with declaration.

EDIT3: Thanks, @Chris.

\$\endgroup\$
7
  • \$\begingroup\$ You can use the static method Stopwatch.StartNew() to save newing up the stopwatch, and explicitly starting it \$\endgroup\$
    – Chris
    Commented Nov 22, 2016 at 16:16
  • \$\begingroup\$ @Chris, I didn't know about that method, thx. \$\endgroup\$
    – paldir
    Commented Nov 22, 2016 at 19:40
  • \$\begingroup\$ t++ can be inserted somewhere in if () \$\endgroup\$ Commented Nov 23, 2016 at 13:08
  • \$\begingroup\$ @MukulKumar Could you provide more details, please? \$\endgroup\$
    – paldir
    Commented Nov 23, 2016 at 13:16
  • \$\begingroup\$ Use if (w.Elapsed.Seconds > t++) and remove t++; \$\endgroup\$ Commented Nov 23, 2016 at 13:18
1
\$\begingroup\$

Scala, 259 254 248 233 232 231 227 225 bytes

import scala.concurrent.duration._;(b:String)=>{val d=b.length.seconds.fromNow;while(d.hasTimeLeft)println(b.zipWithIndex.map{case(f,g)=>if(g<b.length-d.timeLeft.toSeconds-1)f else(32+math.random*94)toChar}mkString);print(b)}

Ungolfed:

import scala.concurrent.duration._;

(b:String) => {
    val d = b.length.seconds.fromNow;
    while(d.hasTimeLeft)
        println(
            b.zipWithIndex.map{
                case(f,g) => 
                    if(g<b.length-d.timeLeft.toSeconds-1)
                        f 
                    else
                        (32+math.random*94)toChar}
            mkString
        );

    print(b)
}
\$\endgroup\$
1
\$\begingroup\$

ForceLang, 322 309 bytes

def s set
s g goto
s W io.writeln
s k io.readln()
s T timer.new()
def a T.poll()
label 1
s P math.floor a.mult 1e-6
if P=k.len
 W k
 exit()
s j 0
s t ""
if P=0
g 4
label 3
s v k.charAt j
s t t+v
s j 1+j
if j-P
g 3
label 4
if j=k.len
 W t
 g 1
s r 94.mult random.rand()
s v string.char 32+r
s t t+v
s j 1+j
g 4
\$\endgroup\$
2
  • \$\begingroup\$ Could you add a link for the programming language you used? \$\endgroup\$ Commented Oct 14, 2018 at 16:22
  • \$\begingroup\$ @SolomonUcko Here you go. \$\endgroup\$ Commented Oct 14, 2018 at 22:46
1
\$\begingroup\$

C++ (gcc), 280 278 bytes

#include<iostream>
#include<chrono>
#include<cstdlib>
#include<thread>
int i,n,t,q;void f(std::string s){for(t=s.size(),n=0;n<=t;n++)for(q=n<t?20:1;q--;std::this_thread::sleep_for(std::chrono::milliseconds(50)))for(std::cout<<"\n"<<s.substr(0,i=n);i++<t;)putchar(32+rand()%84);}

Try it online!

It just prints 20 random strings waiting for 50 std::chrono::milliseconds between each other (thus outputting exactly 20 lines per second) and then proceeds to the next "cracking" step.

\$\endgroup\$
1
\$\begingroup\$

Go, 244 bytes

import(."fmt"
."math/rand"
."time")
func a(s string){Seed(Now().Unix())
for i:=0;i<len(s);i++{t:=Now().Truncate(Second).Add(Second)
for Now().Before(t){q:=[]rune(s)
for p:=len(q)-1;p>=i;p--{q[p]=rune(32+Intn(95))}
Println(string(q))}}
Print(s)}

Try it online! (truncates the result so it doesn't show every instance)

This is my first Golang answer \o/

enter image description here

(Filmed @ 30fps)

How:

func a(s string) {                      //function a
Seed(Now().Unix())                      //Create a seed for the pRNG
for i := 0; i < len(s); i++ {           //set helper var i (this is the number of characters we'll keep)
t := Now().Truncate(Second).Add(Second) //set helper var t = 1 second from now
for Now().Before(t) {                   //while inside that 1 second window
q := []rune(s)                          //put each character in a rune slice and assign that to q
for p := len(q) - 1; p >= i; p-- {      //loops through the rune slice
q[p] = rune(32 + Intn(95))              //replace the character in position p with a random code point in [32,126]
}
Println(string(q))                      //print the rune slice as a string
}
}
Print(s)                                //finally, print the original string
}
\$\endgroup\$
0
\$\begingroup\$

PHP, 222 bytes

$a=$argv[1];$c=range(32,126);$t=time();$s=$t;$e=$t+strlen($a);while(time()<=$e){$l=time();$p=$l-$s;$x=substr($a,0,$p);$k=$e-$l;$r='';for($i=$k;$i>0;$i--)$r.=chr($c[rand(0,94)]);$o=$x.$r;echo"$o\n";if($o==$a&&$l==$e)break;}

Ungolfed

<?php
$input = $argv[1];
$chars = range(32, 126); // count() is 95

$startTime = time();
$endTime = time() + strlen($input);

while (time() <= $endTime) {
    $plaintextAmountToPrint = time() - $startTime;

    $plain = substr($input, 0, $plaintextAmountToPrint);

    $cryptAmountToPrint = $endTime - time();

    $crypt = '';

    for ($i = $cryptAmountToPrint; $i > 0; $i--)
        $crypt .= chr($chars[rand(0, 94)]);

    $output = $plain . $crypt;

    echo $output . "\n";

    if ($output == $input && time() == $endTime)
        break;
}

(i know the video is crap) enter image description here

\$\endgroup\$
7
  • \$\begingroup\$ This could be golfed a lot more. For example, instead of $c=range(32,127) and then $r=chr($c[rand(0,94)]), why not just $r=chr(rand(0,94)+32) ? \$\endgroup\$
    – Xanderhall
    Commented Nov 23, 2016 at 13:55
  • \$\begingroup\$ Good point. It's my first golf :P \$\endgroup\$
    – onin
    Commented Nov 23, 2016 at 13:58
  • \$\begingroup\$ <?$l=strlen($a=$argv[1]);$e=$l+$s=time();while(time()<=$e&&$o!=$a){$o=substr($a,0,time()-$s);while(strlen($o)<$l)$o.=chr(rand(0,94)+32);echo "$o\n";} is 149 bytes, and I'm sure it can be golfed further \$\endgroup\$
    – Xanderhall
    Commented Nov 23, 2016 at 14:14
  • \$\begingroup\$ Cool, you should post that man. \$\endgroup\$
    – onin
    Commented Nov 23, 2016 at 14:21
  • \$\begingroup\$ Just edit your answer, you're allowed to change and improve it. \$\endgroup\$
    – Xanderhall
    Commented Nov 23, 2016 at 14:28
0
\$\begingroup\$

Tcl, 295 bytes

First golf for me in Tcl. Not a very golfable language, since everything is treated as strings here so whitespace is usually a must...

set l [string length $argv];set s [clock seconds];set r -1;while {$r<$l-1} {puts -nonewline [string range $argv 0 $r];set k $l;while {[set k [expr $k-1]]>$r} {puts -nonewline [format %c [expr int(rand()*95+32)]]};puts "";if {[expr [clock seconds]-$s]>[expr $r+1]} {set r [expr $r+1]}};puts $argv

Ungolfed:

set l [string length $argv]
set s [clock seconds]
set r -1
while {$r < $l-1} {                                      # loop on time
  puts -nonewline [string range $argv 0 $r]
  set k $l
  while {[set k [expr $k-1]] > $r} {                     # loop on "unfound" chars
    puts -nonewline [format %c [expr int(rand()*95+32)]]
  }
  puts ""
  if {[expr [clock seconds]-$s] > [expr $r+1]} {         # advance time
    set r [expr $r+1]
  }
}
puts $argv
\$\endgroup\$
9
  • \$\begingroup\$ Why don't you store the output on a variable then join them all, to avoid -nonewline on the puts parameter? \$\endgroup\$
    – sergiol
    Commented May 27, 2017 at 21:28
  • \$\begingroup\$ I think you don't need the two expr at the end; one is enough, and you can also avoid the spaces around > \$\endgroup\$
    – sergiol
    Commented May 27, 2017 at 21:30
  • \$\begingroup\$ Thanks @sergiol, There are no spaces around >, look at the condensed version. Please advise how to use one expr at the end, I can't see it. \$\endgroup\$
    – hdrz
    Commented May 28, 2017 at 1:34
  • \$\begingroup\$ demo of my two suggestions. \$\endgroup\$
    – sergiol
    Commented May 28, 2017 at 10:07
  • 1
    \$\begingroup\$ [set k [expr $k-1]]can be [incr k -1]. And every ` < ` can be <, no spaces required. \$\endgroup\$
    – sergiol
    Commented May 28, 2017 at 10:16
0
\$\begingroup\$

Kotlin, 188 bytes

Golfed

val x=readLine()!!;val n=System::currentTimeMillis;val t=n();do{val s=(n()-t)/1000;x.mapIndexed{i,c->print(if(i<s)c else((Math.random()*(126-32))+32).toChar())};println()}while(s<x.length)

Ungolfed

val input = readLine()!!
val time = System::currentTimeMillis
val startTime = time()
do {
    val crackIndex = (time() - startTime) / 1000
    input.mapIndexed{ i, letter ->
        print(
            if (i < crackIndex) letter else ((Math.random()*(126-32))+32).toChar()
        )
    }
    println()
} while(crackIndex < input.length)

enter image description here

Renaming System.currentTimeMillis saved quite a few bytes!

\$\endgroup\$
0
\$\begingroup\$

QBIC, 92 88 bytes

I've cracked it!

t=20;_LA|[a*t-t|B=$left$|(A,b/t)[a|B=B+$CHR$|(_r94|+32)]?$left$|(B,a)~b%t=0|$sleep 1|}?A

This relies on QBasic's SLEEP function using the code literal $sleep 1|, and on QBasic's LEFT$ function because I haven't implemented that function in QBIC yet...

Managed to scrape a few bytes by substituting all the 20's for t and setting that to 20. Also, streamlined a call to random and a FOR loop.

Explanation:

' Get cmd line param with 'password' and the length of that string, set t to 20
t=20;_LA|

' loop from 1 (implicitly) to (#chars-1) * 20 cracks per char
[a*-t|

'have our crack-display start with the first N chars of
'the password, where N is the number of seconds passed   
B=$left$|(A,b/t)

' loop to add the 'crack-visual'
' It's too long, but we'll trim it down to the original length
[a|B=B+$CHR$|(_r92|+34)]?$left$|(B,a)

' if we've done 20 cracks, sleep for 1 second
~b%20=0|$sleep 1|}

' We've cracked it!
?A

Output (a piece of the middle section on 'helloworld')

hewnoluZfs
heb!mrc2g@
hee+yh"5ut
he0?V+O)Uu
heqf(#M/BM
hez|DGX%a8
he<_n[6-.+
helkxQ#g%,
hel&^A9$I8
hel43{b5]t
helszK50%F
hel`kdy ;b
hel Vr6Z}s
helLIR7*7o 
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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