Это много обезьян


35

Теорема о бесконечной обезьяне гласит, что, учитывая бесконечное время, машина, отправляющая бесконечный поток случайных символов, всегда будет печатать любой заданный текст.

Это звучит для меня как отличная идея для испытания.

Процесс

Для обезьяньей строки A необходимо выполнить следующие шаги:

  1. Возьми пустую строку. Мы назовем эту строку B.
  2. Выберите равномерно произвольный печатный символ ASCII (символы в диапазоне 0x20до 0x7E) и добавьте этот символ в B.
  3. Если A является подстрокой B, B является нашей обезьяньей строкой. В противном случае повторите шаг 2, пока A не станет подстрокой B.

Этот процесс является лишь примером, более простые методы могут существовать в зависимости от вашего языка. Вам не нужно точно следовать этому методу, если достигается такое же распределение выходов.

Соревнование

Напишите программу или функцию, которая, учитывая непустую строку в любом приемлемом формате , возвращает обезьянью версию этой строки.

Ваша программа должна практически работать только для входов длиной 3 или меньше. Для более длинных входов допускается досрочное завершение с или без вывода чего-либо.

пример

К сожалению, довольно сложно создавать примеры для этого вопроса из-за его случайного характера и больших результатов.

Тем не менее, я могу предоставить один пример для ввода hi, на Hastebin.

счет

Поскольку это , выигрывает представление с наименьшим количеством байтов.



11
Нужно ли следовать описанной процедуре для получения результата? Если да, то это ненаблюдаемое требование , которое проблематично. Если нет, мы можем генерировать Bнапрямую, добавляя неотрицательное число nслучайных символов в A. Единственная реальная проблема - узнать распределение n(я держу пари на геометрическом распределении)
Луис Мендо,

1
@seshoumara Вы не можете.
LyricLy

7
@LuisMendo Я думал в этом направлении, и на самом деле не так просто сгенерировать префикс напрямую. Он не может содержать целевую строку, включая пересечение границы, где он встречает добавленную строку. А распределение длины префикса зависит не только от длины целевой строки, но и от ее структуры.
xnor

10
Некоторые из приведенных ниже компьютерных программ, например .W!}zH+ZOrd\k, выглядят очень похоже на то, что напечатала обезьяна.
Джеппе Стиг Нильсен

Ответы:


12

C 192 байта

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

Попробуйте онлайн!

Сейчас это беспорядок, но, по крайней мере, он работает даже для угловых случаев ...


C  63   62  61 байт

Спасибо @Jonathan Frech за сохранение байта!

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

Попробуйте онлайн!


Я понятия не имею, почему это останавливается, когда оно достигает s, +1
ATaco

1
@ATaco Останавливается, когда iстановится достаточно большим, что s[i]ссылается на нулевой терминатор строки (символ 0).
Steadybox

О, так что вместо того, чтобы бросать в него случайные символы, пока s не будет случайно создан, он выбрасывает в него случайные символы, пока не достигнет s. Умная.
ATaco

As much as I like this answer, I believe it breaks for an input such as "ab" when the rand monkeys type "aab".
zennehoy

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

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.


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

1
@wnnmaw backticked randint(32,126) would produce a string of the number, not the ascii char mapping
Uriel

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

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!

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!


6
So would that be... Funky monkeys?
Sebastian Lenartowicz

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.


A shame isPrefixOf isn't in the standard Prelude…
Bergi

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!


3
Добро пожаловать в PPCG! В настоящее время ваше решение не генерирует случайный символ должным образом, так как согласно документам верхняя граница, переданная, Random.Next(Int32,Int32)является эксклюзивной и поэтому не является одним из сгенерированных чисел. Это можно исправить, заменив 126на 127.
0 '

@0 ' Whoops, I thought about it while writing, but I forgot to check it before posting. Thanks!
Wakawakamush

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

@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



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!


hi, your sample could be replaced with intToUtf8(runif(1,32,127))
MickyT

@MickyT excellent, thank you!
Giuseppe

You can save 1 byte with 32+95*runif(1) as your random sampler.
Robin Ryder

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



4

Mathematica, 65 bytes

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

Try it online!

-3 bytes from Jonathan Frech


I think FromCharacterCode[RandomInteger@94+32] is equivalent to the shorter RandomChoice@CharacterRange[32,126].
Jonathan Frech

@JonathanFrech yes,it is!
J42161217



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!


1
Welcome to the site! :)
DJMcMayhem

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

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

I️ attempted to do that, but I️ couldn’t think of a concise way so I️ skipped it. Nice revisions!
Alan

1
Feel free to incorporate those suggestions into your answer. That's standard on this site
Luis Mendo


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.

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.


You can lose the *~~ for -3 tio.run/##K0gtyjH7n1upoJamYPu/…
Phil H

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

1
It should be 32+Math.random()*95. There... bug fixed and a byte saved! ;-)
Olivier Grégoire

@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


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

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;

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

@Giuseppe thx, I have it added in the byte count
RuteNL

1
I think you have to change 94 to 95 for the code to be valid
Hawkings

1
@Hawkings Yea, you're right, fromCharCode ignores decimals it seems. Thanks for pointing it out!
RuteNL

Save a byte with ~b.search instead of b.includes.
Shaggy

@Shaggy Nice! Didn't know about search
RuteNL


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

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 .



Используя наш сайт, вы подтверждаете, что прочитали и поняли нашу Политику в отношении файлов cookie и Политику конфиденциальности.
Licensed under cc by-sa 3.0 with attribution required.