That's a lot of monkeys

35

2

The infinite monkey theorem states that, given infinite time, a machine sending an endless stream of random characters will always type any given text.

That sounds to me like a great idea for a challenge.

Process

In order to monkey-ize a string A, the following steps should be taken:

  1. Take an empty string. We will call this string B.
  2. Pick a uniformly random printable ASCII character (characters in the range 0x20 to 0x7E) and add that character to B.
  3. If A is a substring of B, B is our monkey-ized string. Otherwise, repeat step 2 until A is a substring of B.

This process is only an example, easier methods may exist depending on your language. You do not need to follow this method exactly, as long as the same distribution of outputs is achieved.

The challenge

Write a program or function that, given a non-empty string in any reasonable format, returns a monkey-ized version of that string.

Your program only has to practically work for inputs of length 3 or less. For longer inputs, it is allowed to terminate early with or without outputting anything.

Example

Unfortunately, it's kind of hard to create examples for this question due to the random nature of it and the large outputs.

However, I can supply a single example for the input hi, on Hastebin.

Scoring

Since this is , the submission with the fewest bytes wins.

LyricLy

Posted 2017-11-05T22:32:03.783

Reputation: 3 313

Sandbox – LyricLy – 2017-11-05T22:38:48.140

11

Do we need to follow the described procedure to produce the output? If yes, that's an unobservable requirement, which is problematic. If not, we can generate B directly by prepending a non-negative number n of random characters to A. The only real problem then is to know the distribution of n (I bet on a geometric distribution)

– Luis Mendo – 2017-11-05T23:24:52.930

@LuisMendo I have clarified that in the question body. – LyricLy – 2017-11-06T00:05:29.967

@LyricLy I attempted to clarify a small bit more, feel free to revert if you don't like my edit. – Rɪᴋᴇʀ – 2017-11-06T00:12:22.223

So I have a="ant" then b can be: b, be, bet, beta, betan, betant which a is a substring of. Is this correct? – VortexYT – 2017-11-06T01:15:59.143

@Goodra I'm not sure what you mean. The challenge is to create random characters until a given text is generated. For example, if the input was hi, the output could be ps.6@}7}RII!x^hi (although this is very improbable; the string is likely to be much longer) – LyricLy – 2017-11-06T01:58:21.010

how fast does the case of 3 need to execute? – Jonah – 2017-11-06T02:19:52.460

@Jonah It has no time limit, as long as it returns a valid result. – LyricLy – 2017-11-06T02:21:31.950

Can I prepend the generated character to B? The resulting string for hi, would look for ex. like hi%/2T'uF)XS, where i and h were the last 2 chars generated before exiting. – seshoumara – 2017-11-06T07:45:07.703

1@seshoumara You may not. – LyricLy – 2017-11-06T08:03:49.877

7@LuisMendo I thought along these lines, and it's actually not easy to generate the prefix directly. It can't contain the target string, including crossing the boundary where it meets the appended string. And the distribution of prefix lengths depends not just on the length of the target string, but its structure as well. – xnor – 2017-11-06T09:03:30.357

Related. – user202729 – 2017-11-06T15:00:33.667

10Some of the solution computer programs below, such as .W!}zH+ZOrd\k, look a lot like what a monkey has typed. – Jeppe Stig Nielsen – 2017-11-07T22:46:04.743

I knocked this up a while back http://monkeys.geotheory.co.uk/

– geotheory – 2017-11-13T19:26:07.573

Unless I am misunderstanding I think the theorem states "almost surely", not "always." You could just end up with an infinite string of as if you are exceedingly unlucky lol – Marie – 2018-07-30T19:34:48.850

Answers

12

C, 192 bytes

i;g(s,b,i,n,j)char*s,*b;{for(b[i+1]=0;b[n+j];++n)s[n]-b[n+j]&&(n=-1,++j);return n;}f(char*s){char*b=calloc(strlen(s),1);for(i=0;s[i];)i=(b[i]=putchar(rand()%95+32))-s[i]?i?g(s,b,i,0,0):0:i+1;}

Try it online!

It's a mess now, but at least it works even for the corner cases...


C,  63   62  61 bytes

Thanks to @Jonathan Frech for saving a byte!

i;f(char*s){for(i=0;s[i=putchar(rand()%95+32)-s[i]?0:i+1];);}

Try it online!

Steadybox

Posted 2017-11-05T22:32:03.783

Reputation: 15 798

I have absolutely no idea why this halts when it hits s, +1 – ATaco – 2017-11-05T22:48:34.210

1@ATaco It halts when i grows large enough that s[i] refers to the null terminator of the string (character 0). – Steadybox – 2017-11-05T22:52:50.853

Oh, so instead of throwing random characters at it until s is accidentally created, it throws random characters at it until it reaches s. Smart. – ATaco – 2017-11-05T22:53:53.833

As much as I like this answer, I believe it breaks for an input such as "ab" when the rand monkeys type "aab". – zennehoy – 2017-11-06T14:28:29.943

I guess you need something like KMP so that this approach can be valid. Assume the input string is ababc and the monkey generate !!abababc will your program halt? – user202729 – 2017-11-06T14:56:31.657

@zennehoy Thanks for pointing that out. It's fixed (and ugly and long) now. – Steadybox – 2017-11-06T16:43:39.270

@user202729 Thanks. It's fixed now. – Steadybox – 2017-11-06T16:44:20.833

167 bytes – ceilingcat – 2019-04-19T22:38:22.890

9

Python, 79 bytes

f=lambda x,s='':x in s and s or f(x,s+chr(randint(32,126)))
from random import*

Try it online!

This is theoretically sound, but will crash early due to python's recursion limits (you can set them further to get longer results)

Python, 84 bytes

from random import*
x,s=input(),''
while x not in s:s+=chr(randint(32,126))
print(s)

Try it online!

This one is ought to work for relatively longer strings, since it doesn't rely on recursion, at the cost of 5 bytes.

Uriel

Posted 2017-11-05T22:32:03.783

Reputation: 11 708

You can save three bytes by using backticks to do the string conversion (shown here as single quotes to the the markdown right) s+'randint(32,126)' – wnnmaw – 2017-11-06T16:24:58.123

1@wnnmaw backticked randint(32,126) would produce a string of the number, not the ascii char mapping – Uriel – 2017-11-06T16:59:20.610

8

Ohm v2, 10 bytes

Ý£D³ε‽α@§↔

Try it online!

Explanation:

Ý£D³ε‽α@§↔  Main wire, arguments: a (string)

Ý           Push empty string to top of stack
 £          Start infinite loop
  D³ε‽        If a is a substring of the ToS, break out of the loop
      α@§     If not, select a random printable ASCII character...
         ↔    ...and concatenate it with the ToS

Nick Clifford

Posted 2017-11-05T22:32:03.783

Reputation: 1 184

8

GNU sed + coreutils, 75 + 1(r flag) = 76 bytes

h
:
s:.*:shuf -i32-126|dc -e?P:e
H;g
s:\n::2g
/^(.+)\n(.*)\1/{s::\2\1:;q}
b

Try it online! (It takes a lot of runs to get an answer for a length 2 input, because most of the time you run out of allowed TIO computation time.)

Explanation:

h                                # copy input string 'A' to hold space
:                                # start loop
    s:.*:shuf -i32-126|dc -e?P:e # run shell script: shuf outputs a rnd permutation
                                 #of the set of numbers from 32 to 126, and '?P' in
                                 #dc converts the 1st read decimal to an ASCII char
    H;g                          # append char to hold space ('A\n.'), then copy
                                 #result back to pattern space
    s:\n::2g                     # remove all '\n's from pattern space, but first
    /^(.+)\n(.*)\1/{             # if pattern is 'A\n.*A' (A substring of B), then
        s::\2\1:;q               # search previous regex used and leave only '.*A',
                                 #then quit (implicit printing before exit)
    }
b                                # repeat loop

Benchmark: approximate, for scaling purposes only

  • input length: 1, 10 random inputs (runs), average time: < 1 s
  • input length: 2, 10 random inputs (runs), average time: 90 s
  • input length: 3, 10 random inputs (runs), average time: lots of hours!

seshoumara

Posted 2017-11-05T22:32:03.783

Reputation: 2 878

7

Funky, 64 bytes

s=>{S=""whileS::sub((#S)-#s)!=s S+=S.char(math.random(32,126))S}

This uses a few tricks I've been wanting to use in Funky, like a variable name after a keyword as in whileS, and using the fact that strings implicitly parent to the string library.

Ungolfed

function monkey(target){
    monkeyCode = ""
    while (monkeyCode::sub((#monkeyCode)-#target)!=target){
        monkeyCode += string.char(math.random(32,126))
    }
    monkeyCode
}

Try it online!

ATaco

Posted 2017-11-05T22:32:03.783

Reputation: 7 898

6So would that be... Funky monkeys? – Sebastian Lenartowicz – 2017-11-06T09:51:27.677

7

Haskell, 100 bytes

import System.Random
s#(a:b)|and$zipWith(==)s$a:b=s|1>0=a:s#b
m a=(a#).randomRs(' ','~')<$>newStdGen

Try it online!

Basic idea is to generate an infinite list of characters with randomRs and stop it once we find the string.

user1472751

Posted 2017-11-05T22:32:03.783

Reputation: 1 511

A shame isPrefixOf isn't in the standard Prelude…

– Bergi – 2017-11-08T02:02:52.397

7

C# (.NET Core), 86 bytes

a=>{var b="";for(var r=new Random();!b.Contains(a);b+=(char)r.Next(32,127));return b;}

I don't really like how much creating the Random instance takes, but I don't think there's a way around it.

Try it online!

Wakawakamush

Posted 2017-11-05T22:32:03.783

Reputation: 121

3

Welcome to PPCG! Currently your solution does not properly generate a random character since according the the docs, the upper bound passed to Random.Next(Int32,Int32) is exclusive and so not one of the numbers generated. This can be fixed by replacing 126 by 127.

– 0 ' – 2017-11-08T14:45:22.183

@0 ' Whoops, I thought about it while writing, but I forgot to check it before posting. Thanks! – Wakawakamush – 2017-11-08T14:56:41.023

There is actually a way around that long Random, you can remove the variable declaration! 79 bytes

– FlipTack – 2017-11-09T07:48:33.783

@FlipTack Interesting, I tried that in C# Interactive and it didn't work because it just kept generating the same number. Weird to see that it does work in TIO. – Wakawakamush – 2017-11-09T09:08:13.760

6

Charcoal, 15 14 12 bytes

W¬№ωθ≔⁺ω‽γωω

Try it online! Link is to verbose version of code. Edit: Saved 2 bytes due to a subsequent bug fix in Charcoal. Explanation:

    θ           Input string
   ω            Predefined variable `w`
  №             Count number of occurrences
 ¬              Logical not
W               Loop while true
       ω        Predefined variable `w`
      ⁺         Concatenated with
         γ      Predefined printable characters
        ‽       Random element
     ≔    ω     Assign to predefined variable `w`
           ω    Predefined variable `w`
                Implicitly print

Neil

Posted 2017-11-05T22:32:03.783

Reputation: 95 035

6

Perl 5, 31 +2 (-pa) bytes

}{$_.=chr 32+rand 95until/\Q@F/

Try it online

Nahuel Fouilleul

Posted 2017-11-05T22:32:03.783

Reputation: 5 582

You can save 3 bytes since the \E$ is extraneous – Zaid – 2017-11-07T19:18:04.857

indeed, thank you for having noticed – Nahuel Fouilleul – 2017-11-08T08:09:17.357

saved 2 more bytes – Nahuel Fouilleul – 2017-11-08T08:32:24.223

That's sneaky. Very nice indeed :) – Zaid – 2017-11-08T08:56:39.143

and even more, -3bytes – Nahuel Fouilleul – 2017-11-08T09:32:14.877

Sweet. Those whitespaces are an eyesore... there's space in there, make it smaller ;)

– Zaid – 2017-11-08T09:43:29.210

6

R, 79 76 75 bytes

-3 bytes thanks to MickyT for changing the random sampler

-1 byte thanks to Robin Ryder for tweaking the random sampler again

function(S){G=""
while(!grepl(S,G))G=paste0(G,intToUtf8(32+95*runif(1)))
G}

Try it online!

Giuseppe

Posted 2017-11-05T22:32:03.783

Reputation: 21 077

hi, your sample could be replaced with intToUtf8(runif(1,32,127)) – MickyT – 2017-11-06T21:05:08.223

@MickyT excellent, thank you! – Giuseppe – 2017-11-07T15:00:47.270

You can save 1 byte with 32+95*runif(1) as your random sampler. – Robin Ryder – 2019-04-15T21:41:08.567

6

Japt, 26 bytes

@(PbU >-1}a@P+=(Mq95 +32 d

Try it online!

Hawkings

Posted 2017-11-05T22:32:03.783

Reputation: 191

3

Very quick golf while on a smoke break: 22 bytes. Welcome to Japt :)

– Shaggy – 2017-11-25T23:57:40.850

5

Ruby, 42 bytes

->w,s=""{s+=[*" "..?~].sample;s[w]?s:redo}

Try it online!

Reinstate Monica -- notmaynard

Posted 2017-11-05T22:32:03.783

Reputation: 1 053

4

Pyth - 14 bytes

.W!}zH+ZOrd\k

Try it online here.

Maltysen

Posted 2017-11-05T22:32:03.783

Reputation: 25 023

W!}Qk=+kpOrd\ is 14 bytes as well, SE is messing with formatting because of unprintable but range is generated the same way – Dave – 2017-11-05T23:45:40.773

4

Mathematica, 65 bytes

""//.x_/;x~StringFreeQ~#:>x<>RandomChoice@CharacterRange[32,126]&

Try it online!

-3 bytes from Jonathan Frech

J42161217

Posted 2017-11-05T22:32:03.783

Reputation: 15 931

I think FromCharacterCode[RandomInteger@94+32] is equivalent to the shorter RandomChoice@CharacterRange[32,126]. – Jonathan Frech – 2017-11-05T23:12:48.550

@JonathanFrech yes,it is! – J42161217 – 2017-11-05T23:18:58.960

4

Lua, 99 102 bytes

  • Saved a bug thanks to ATaco, which added three bytes.
function f(B)s=string S=""while not(s.find(S,B,1,1))do S=S..s.char(math.random(32,126))end print(S)end

Try it online!

Jonathan Frech

Posted 2017-11-05T22:32:03.783

Reputation: 6 681

4

MATL, 17 16 bytes

''`6Y2TZrhtGXfn~

Try it online!

-1 byte thanks to Giuseppe

Cinaski

Posted 2017-11-05T22:32:03.783

Reputation: 1 588

4

Octave, 62 bytes

t=input(o="");while(~nnz(regexp(o,t)))o=[o,randi(95)+31];end;o

Try it online!

Explanation:

t=input(o="");               % get stdin and define output
while(~nnz(regexp(o,t)))     % while no matches
    o=[o,randi(95)+31];      % concatenate string with ascii char
end;                            
o                            % output result

Many thanks to Luis Mendo for the edits!

Alan

Posted 2017-11-05T22:32:03.783

Reputation: 161

1Welcome to the site! :) – James – 2017-11-06T21:00:54.650

Can't you replace isvector by nnz? And strfind by regexp. Also, you can use randi(95)+31, or maybe replace the whole sprintf statement by o=[o,randi(95)+31]; (implicit conversion to char) – Luis Mendo – 2017-11-06T23:38:39.503

Also, we usually require a function or a program that takes its input (as opposed to defining a variable containing the input) -- something like this

– Luis Mendo – 2017-11-06T23:48:06.093

I️ attempted to do that, but I️ couldn’t think of a concise way so I️ skipped it. Nice revisions! – Alan – 2017-11-07T00:21:23.817

1Feel free to incorporate those suggestions into your answer. That's standard on this site – Luis Mendo – 2017-11-07T11:37:20.220

4

Japt, 16 14 11 bytes

;_øU}a@P±Eö

Try it

Shaggy

Posted 2017-11-05T22:32:03.783

Reputation: 24 623

3

Alice, 21 bytes

/U!?"$~dr@
\idwz K"o/

Try it online!

Explanation

/...@
\.../

This is framework for mostly linear programs that operate entirely in Ordinal (string-processing) mode. The IP bounces diagonally up and down through the program twice, which means that the actual code is a bit weirdly interleaved. The commands in the order they're actually executed are:

i!w" ~"rUd?z$Kdo

Let's go through this:

i       Read all input.
!       Store the input on the tape for later.
w       Push the current IP address onto the return address stack.
        This marks the beginning of the main loop.

  " ~"    Push this string.
  r       Range expansion. Turns the string into " !...}~", i.e. a string
          with all printable ASCII characters.
  U       Random choice. Picks a uniformly random character from this
          string. This will remain on the stack throughout the rest of
          the program and will form part of the resulting string.
  d       Join stack. This takes all strings on the stack and joins them
          into a single string and pushes that (it does this without actually
          removing any elements from the stack).
  ?       Retrieve the input from the tape.
  z       Drop. If the joined string contains the input, everything up to
          and including the input will be discarded. Otherwise, nothing
          happens to the joined string. This means that the result will be
          an empty string iff the joined string ends with the input.
$K      If the top of the stack is not empty, jump back to the w to continue
        with another iteration of the main loop.
d       Join the stack into a single string once more.
o       Print it.

Martin Ender

Posted 2017-11-05T22:32:03.783

Reputation: 184 808

3

Perl 6, 39 bytes

{("",*~(" ".."~").pick...*~~/$_/)[*-1]}

Try it online!

(...)[*-1] returns the last element of the sequence defined by ..., of which:

  • "" is the first element;

  • * ~ (" " .. "~").pick generates the next element by appending a random character in the appropriate range to the previous element; and

  • * ~~ /$_/ is the ending condition, which is that the current element matches the main function's input argument $_ as a literal substring.

Sean

Posted 2017-11-05T22:32:03.783

Reputation: 4 136

3

Java 8, 81 79 78 bytes

a->{String b="";for(;!b.contains(a);b+=(char)(32+Math.random()*95));return b;}

-1 byte thanks to @OlivierGrégoire for pointing me to a (big >.<) mistake I've made..

Explanation:

Try it here.

a->{                    // Method with String as both parameter and return-type
  String b="";          //  Result-String, starting empty
  for(;!b.contains(a);  //  Loop as long as the result does not contain the input
    b+=(char)(32+Math.random()*95)
                        //   Append a random character to `b`
  );                    //  End of loop
  return b;             //  Return the result-String
}                       // End of method

Kevin Cruijssen

Posted 2017-11-05T22:32:03.783

Reputation: 67 575

1It should be 32+Math.random()*95. There... bug fixed and a byte saved! ;-) – Olivier Grégoire – 2017-11-07T18:00:23.490

@OlivierGrégoire Woops.. Looked at the hexadecimal code for the space, but regular decimal for tilde.. >.> Thanks for noticing. Not sure how I've missed that, since the output clearly had 'unprintable' symbols.. – Kevin Cruijssen – 2017-11-07T18:20:08.617

3

05AB1E, 10 9 bytes (-1 @ Emigna)

[žQΩJD¹å#

Try it online!


Do the monkey with me.


[              | Loop forever.
 žQ            | Push 0x20-0x7E as a single string.
   .R          | Pick from it randomly.
     J         | Join stack (B) with new char.
      D        | Duplicate (B).
       ¹å      | Push input (A) and check if input (A) is in (B).
         #     | If the previous statement is true, break loop.

Magic Octopus Urn

Posted 2017-11-05T22:32:03.783

Reputation: 19 422

1You can do Ω instead of .R. – Emigna – 2018-01-16T13:20:08.210

2Lol, using an Ohm, to beat Ohm v2. How nice. – Magic Octopus Urn – 2018-01-17T14:27:03.517

2

QBIC, 33 bytes

≈instr(Z,;)<1|Z=Z+chr$(_r32,126|)

Explanation

≈instr( , )<1|   WHILE InStr() can't find
         ;        the input (cmd line string argument) as part of
       Z          the output (Z$, which is printed automatically on exit)
Z=Z+             add to the output
chr$(         )  an ASCII character
     _r32,126|   with a random codepoint between 32 and 126 (incl)

Sample run:

Command line: hi

`;7L3f$qy )H99tZ@>(-Z1efL|Q-5'BE=P8BdX?Lem/fp|G#~WY[ Q4s9r~Af*T})P4`4d$#ud3AiuTwQPFS@8c7_59C$ GlJ%iJ[FA(rNt<y>Hl=r,wSbBB%q!8&#*CixWbnwE."wrZ:R53iKJkN*@hpQt aMj6Mw<KfT@hkik>_k'_>$~3)jl|J!S`n\Yw|lXi:WAKWp?K"F.cAGI/:~uR8*[;Die{]B*]@;Vhjv,$9]Ys:AIdy!j{aXlr:0=txCP-n{/3lgq,;jXaP\]u}.Zl/7eKF+N54[J9^r:>%/.e~*9aK%de>^TW%p%(_uJPvuV%d<&]zu`t;vkEPC>7pofok0Kj}j?9G{TUxSccth)[)J>@'E)NMzA(i!UV7%;$.Z#j3q@#9Q%}<" &VsbL*<SrG-$NC MAQ\`iIT+.P|5}nv )FZl5_.Kc*AUV9u&fvk.USt3Y!s7^UEL{|D$k#k8.9Fgqn#3dgr(0G.gw1#j$HfU3a|)3-O(d<)<A|`%pJ^/\{[w[H4N/>8J@z/YNsU,zY4o*X+h\Dy!~)Xr8.3"%.39v0d5_-8QBYR".Z]MZ}N>9e?f@hj#hor1IhJ[krrHOamRPxQC>^'dOh,cF_e2;8R@K**Jsx_~t9r~4J$Y;kPsb)8w~:o-`@MwP]OA{8yD%gL(=&M>$nTKw] R[}rS|~}&*gD 'g|gRSDLld+`,,}(1=]ao3Z%2*?wlqU$7=$8q$Fig:7n&+XKQ LV/Aq?BYl_*Ak-PqI$U_>`/`-yD5.3|Zg>,mC"RC`IV^szu:I;0ntn(l'/ZnK}T&i)9!zkd?7Ec/X+IN=-5wwsSV@^<?:K=9m%*@C;zDjc%:d>/E@f7@0NVt4Vz/E;8*0A25F1:JUQ/G#2)un9hQI>2^}&+cY+JP*-#$p+cFs}R|>E;w#q>pN"Jkv<>E_ZtCvV05Lh;0 9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lbrd8kD{B0Eeu<&oL2s.S4@Jo$zVq~BqeLsb;k-NG/'iU|)W_:X-.XUc<v\elx57ZZ"R!y_yzve*Wlt>.fE,#Eh:(#gn1kSQ+/3NYjD']I;"+@pnW[1EA.AyqM4,0,dJt.?r2oab.j\k@)BsZ|s39FdL87xyuJ0nXX=yz^~W,}acDZp8ukCpv^<^{CkRS<=GsS$}#fbP5%A$GHdg)+WZLLN9[ue073Q!F"J;X^49*$R'W%C.r~Fj&B`)tq[01a4En%H,kvyZG|,)%$44rJg[tq<wG9FjN<m@larki#;Bns%D}v_efPRH(OeRq0{=>Uc[~xcTcV_9|k54Q2*N.3]LlmFasY3"p =$$onbg$M+ReRsnH|9gV~#2?c1-V$35."DZH-O$~,c.gs]%,]p4\OFIW%l:,E,YT8FCeU8hy#lNq1lCpS 0I&q_*q>|=,(-dHuzi~6$GW22*A\w*&R< W`$HPRr,2A}3w\"Y?d%{2^xP:GqI\26A|.e'H2Z[M4=P.H87O~{)9|B*tHAC\j^S,StW!*snsz82R!:eD@uB4x+x&zSIN(3V|.^N_$=i=p}iK4h'v"$:I<t e:Y/XrSOF83=lkVNa0^k@jB@{ARE@r=Bja`(Bw>@?+`Wo,= u5HhXPeRMXS4@H#$-Jwg2"2-]%7p.o2Ar9J6Y1Ra?"3<oee&bpO^O{nw9=%\0brVNXrelWGoJyb/5W%MB0UBaPsc*29K<N~``NriWM$"eY0@xh^<$b:E/J~S%{#ry~6d?4Vv@^&9'=iBA#2U]bj9>UoJ#wQDN~6cB&/_Pu-XF?_hu3><(M7RW\%Ly@rTC9^b`?kVL~w%[{!&{#aS7<mc@J>ZaN7s}Y.c0:Y.\d&_[L{m|>|>%J^@!i9y0_lwejChi

steenbergh

Posted 2017-11-05T22:32:03.783

Reputation: 7 772

2

PHP, 55+1 bytes

while(!strpos(_.$argn,_.$s.=chr(rand(32,126))));echo$s;

Run as pipe with -nR. Not suitable for TIO cause of probable timeout.

Insert a space between the quotation marks for PHP older than 7.1.

This 51+1 bytes version will fail if input is 0:

while(!strstr($argn,$s.=chr(rand(32,126))));echo$s;

Titus

Posted 2017-11-05T22:32:03.783

Reputation: 13 814

2

Javascript 74 bytes

s=(a,b='')=>~b.search(a)?b:s(a,b+String.fromCharCode(32+Math.random()*95))

call like this:

s('hi')

RuteNL

Posted 2017-11-05T22:32:03.783

Reputation: 71

@Giuseppe thx, I have it added in the byte count – RuteNL – 2017-11-08T14:37:29.373

1I think you have to change 94 to 95 for the code to be valid – Hawkings – 2017-11-09T00:21:05.457

1@Hawkings Yea, you're right, fromCharCode ignores decimals it seems. Thanks for pointing it out! – RuteNL – 2017-11-09T09:39:31.687

Save a byte with ~b.search instead of b.includes. – Shaggy – 2018-01-16T11:02:54.527

@Shaggy Nice! Didn't know about search – RuteNL – 2018-01-16T13:07:26.603

2

Pushy, 20 18 bytes

LFZ^tCN[,` ~`U'x?i

Try it online!

The program keeps a stack len(input) characters long, and constantly removes the first and appends a new random char, until the initial input string is reached. Each character is printed as it is added, creating the desired effect.

Explanation:

                      \ == SETUP ==
 F                    \ Put input on second stack
L Z^tC                \ On the main stack, make length(input) copies of 0
      N               \ Remove printing delimiter (newline by default)

                      \ == MAIN LOOP ==

       [              \ Infinitely:
        ,             \    Pop the first item on stack
         ` ~`U        \    Add a new random character (between 32 and 126)
              '       \    Print this new character
               x?     \    If the stacks are now equal:
                 i    \        Exit program

FlipTack

Posted 2017-11-05T22:32:03.783

Reputation: 13 242

2

Julia 0.6, 53 bytes

a->(s="";while !contains(s,a) s*=randstring(1) end;s)

Try it online!

gggg

Posted 2017-11-05T22:32:03.783

Reputation: 1 715

2

Brachylog, 17 bytes

I⁰∧Ẹ{sI⁰&|;Ṭṛᵗc↰}

Try it online!

I⁰                   The global variable I⁰
                     is the input,
  ∧                  and
   Ẹ                 starting with the empty string
    {          ↰}    call this sub-predicate again
            ṛ        with a random
           Ṭ         printable ASCII character
          ;  ᵗc      appended to the string we're building
         |           unless
      I⁰             I⁰ (which is the input)
     s               is a substring of the string we've been building
        &            in which case the string is output.

Can randomly stack overflow. This makes use of two recently added features in Brachylog: global variables, and the apply-to-tail metapredicate .

Unrelated String

Posted 2017-11-05T22:32:03.783

Reputation: 5 300

1

Pyth, 13 bytes

W!}z=akpOrd\

where the unprintable character is 0x7F.

Test

Steven H.

Posted 2017-11-05T22:32:03.783

Reputation: 2 841

1

Bash 94 bytes

p=printf\ -v;until [[ $s = *"$1" ]];do $p x %x $[32+RANDOM%95];$p c \\x$x;s+=$c;done;echo "$s"

Try it online

Nahuel Fouilleul

Posted 2017-11-05T22:32:03.783

Reputation: 5 582

1

Excel VBA, 84 bytes

Dim b
Sub m(a)
b=b &Chr(Int(113*Rnd+14))
If InStr(1,b,a)Then [A1]=b Else m a
End Sub

It's a straightforward implementation. Output is to cell A1 in the active sheet

Engineer Toast

Posted 2017-11-05T22:32:03.783

Reputation: 5 769

1

Jelly, 17 bytes

³ẇ®¬
ḟµ;©ØṖX¤ø¢¿Ḋ

Try it online!

Explanation

³ẇ®¬            First link
³               Program input...
 ẇ              ...is a contiguous sublist of...
  ®             ...the register?
   ¬            Logical NOT

ḟµ;©ØṖX¤ø¢¿Ḋ    Main link
ḟ               Filter: With only one input this returns the empty list. Note ⁸ doesn't work here.
 µ              New monadic chain
    ØṖX¤        Random (X) element from printable ASCII (ØṖ).
  ;             Concatenate with the above
   ©            Copy the result of the concatenation with the above to check if program input is a sublist.
        ø       New niladic chain.
         ¢      Calls first link.
          ¿     Repeat the monadic chain until the first link returns false.
           Ḋ    Removes the first element of the result. 
                For some reason (???) the integer 0 is always at the beginning of the result which needs to be removed.

Tested with one and two character inputs (two character sometimes takes a long time or seems to stall) but should work in theory for any length input.

The recursive solution I came up with below is slightly longer.

Jelly, 19 bytes

³ẇ®¬
;©ØṖX¤ßµ¢¡
ḟ`Ç

Try it online!

dylnan

Posted 2017-11-05T22:32:03.783

Reputation: 4 993

1

J, 38 33 30 29 bytes

-9 bytes thanks to FrownyFrog

(],a.{~32+?@95}.~1#.E.)^:_&''

Try it online!

Jonah

Posted 2017-11-05T22:32:03.783

Reputation: 8 729

1(],a.{~32+?@95}.~1 e.E.)^:_&'' – FrownyFrog – 2019-04-16T15:27:51.750

Nice. I didn't know that '' -: 99 + '' – Jonah – 2019-04-16T16:08:27.987

11 e.E.-> 1#.E. – FrownyFrog – 2019-04-19T13:41:51.500

1

PowerShell, 55 73 bytes

+18 thanks to mazzy bringing it up to spec

for(;$args-cne-join($b+=[char](32..126|random))[-"$args".Length..-1]){}$b

Try it online!

First, it picks randomly an int from the printable range, casts that to a character, and appends it to our accumulator string. The monkeys will always form the word with the last character so keeps going until the ending of our generated string is the target word. So with that fact, it then compares the last n characters joined into a string (via reserve indexing) to the target.

Veskah

Posted 2017-11-05T22:32:03.783

Reputation: 3 580

nice. but it works incorrect when $args contains the special chars * and ?. – mazzy – 2019-04-17T06:29:10.730

1Try it online! – mazzy – 2019-04-17T10:14:47.060

@mazzy Danggit. Thanks for the fix – Veskah – 2019-04-17T12:04:34.437

Why don't you go back to your previous version, but do -cmatch"\$args" instead of -clike"*$args"? Try it online!

– AdmBorkBork – 2019-04-17T14:22:49.930

@AdmBorkBork Because that breaks in multiple ways depending on what the target string is

– Veskah – 2019-04-17T14:33:18.197

Haha, yes, I was just coming back to delete my comment after realizing that. lol – AdmBorkBork – 2019-04-17T14:40:42.607

@AdmBorkBork Shoot, wish your version worked. – Veskah – 2019-04-17T14:43:23.543

too many chars to escape with \ : 87 bytes. And I'm not sure that special characters can be escaped in like operator.

– mazzy – 2019-04-17T17:15:51.507

0

JavaScript 91 bytes

for(b="",a=prompt();b.search(a)<1;b+=String.fromCharCode(~~(Math.random()*95+32)));alert(b)

david

Posted 2017-11-05T22:32:03.783

Reputation: 51

0

Noether, 24 bytes

I~a""~b1(b94R32+BP+~ba/)

Try it online!

Beta Decay

Posted 2017-11-05T22:32:03.783

Reputation: 21 478

0

Perl 6, 52 bytes

{("",*~(' '..'~').roll...*).grep(*.contains($_))[0]}

Try it online!

bb94

Posted 2017-11-05T22:32:03.783

Reputation: 1 831

0

Emacs Lisp, 113 bytes

(lambda(a)(let((case-fold-search)(b""))(while(not(string-match a b))(setq b(concat b(string(+(random 95)32)))))))

Try it online!

Try-it-online version has an additional byte for printing purposes.

(case-fold-search) assures string-match proper casing, it can be omitted depending on your Emacs configurations (18 bytes).

Better readable version:

((lambda (a)
    (let ((case-fold-search) (b ""))
      (while (not (string-match a b))
    (setq b (concat b (string (+ (random 95) 32)))))
      )))

adl

Posted 2017-11-05T22:32:03.783

Reputation: 351