35
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Sandbox \$\endgroup\$ – LyricLy Nov 5 '17 at 22:38
  • 11
    \$\begingroup\$ 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) \$\endgroup\$ – Luis Mendo Nov 5 '17 at 23:24
  • 1
    \$\begingroup\$ @seshoumara You may not. \$\endgroup\$ – LyricLy Nov 6 '17 at 8:03
  • 7
    \$\begingroup\$ @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. \$\endgroup\$ – xnor Nov 6 '17 at 9:03
  • 10
    \$\begingroup\$ Some of the solution computer programs below, such as .W!}zH+ZOrd\k, look a lot like what a monkey has typed. \$\endgroup\$ – Jeppe Stig Nielsen Nov 7 '17 at 22:46

38 Answers 38

12
\$\begingroup\$

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!

\$\endgroup\$
  • \$\begingroup\$ I have absolutely no idea why this halts when it hits s, +1 \$\endgroup\$ – ATaco Nov 5 '17 at 22:48
  • 1
    \$\begingroup\$ @ATaco It halts when i grows large enough that s[i] refers to the null terminator of the string (character 0). \$\endgroup\$ – Steadybox Nov 5 '17 at 22:52
  • \$\begingroup\$ 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. \$\endgroup\$ – ATaco Nov 5 '17 at 22:53
  • \$\begingroup\$ As much as I like this answer, I believe it breaks for an input such as "ab" when the rand monkeys type "aab". \$\endgroup\$ – zennehoy Nov 6 '17 at 14:28
  • \$\begingroup\$ 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? \$\endgroup\$ – user202729 Nov 6 '17 at 14:56
9
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ 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)' \$\endgroup\$ – wnnmaw Nov 6 '17 at 16:24
  • 1
    \$\begingroup\$ @wnnmaw backticked randint(32,126) would produce a string of the number, not the ascii char mapping \$\endgroup\$ – Uriel Nov 6 '17 at 16:59
8
\$\begingroup\$

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
\$\endgroup\$
8
\$\begingroup\$

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!
\$\endgroup\$
7
\$\begingroup\$

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!

\$\endgroup\$
  • 6
    \$\begingroup\$ So would that be... Funky monkeys? \$\endgroup\$ – Sebastian Lenartowicz Nov 6 '17 at 9:51
7
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ A shame isPrefixOf isn't in the standard Prelude… \$\endgroup\$ – Bergi Nov 8 '17 at 2:02
7
\$\begingroup\$

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!

\$\endgroup\$
  • 3
    \$\begingroup\$ 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. \$\endgroup\$ – 0 ' Nov 8 '17 at 14:45
  • \$\begingroup\$ @0 ' Whoops, I thought about it while writing, but I forgot to check it before posting. Thanks! \$\endgroup\$ – Wakawakamush Nov 8 '17 at 14:56
  • \$\begingroup\$ There is actually a way around that long Random, you can remove the variable declaration! 79 bytes \$\endgroup\$ – FlipTack Nov 9 '17 at 7:48
  • \$\begingroup\$ @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. \$\endgroup\$ – Wakawakamush Nov 9 '17 at 9:08
6
\$\begingroup\$

Perl 5, 31 +2 (-pa) bytes

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

Try it online

\$\endgroup\$
  • \$\begingroup\$ You can save 3 bytes since the \E$ is extraneous \$\endgroup\$ – Zaid Nov 7 '17 at 19:18
  • \$\begingroup\$ indeed, thank you for having noticed \$\endgroup\$ – Nahuel Fouilleul Nov 8 '17 at 8:09
  • \$\begingroup\$ saved 2 more bytes \$\endgroup\$ – Nahuel Fouilleul Nov 8 '17 at 8:32
  • \$\begingroup\$ That's sneaky. Very nice indeed :) \$\endgroup\$ – Zaid Nov 8 '17 at 8:56
  • \$\begingroup\$ and even more, -3bytes \$\endgroup\$ – Nahuel Fouilleul Nov 8 '17 at 9:32
6
\$\begingroup\$

Japt, 26 bytes

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

Try it online!

\$\endgroup\$
  • 3
    \$\begingroup\$ Very quick golf while on a smoke break: 22 bytes. Welcome to Japt :) \$\endgroup\$ – Shaggy Nov 25 '17 at 23:57
6
\$\begingroup\$

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!

\$\endgroup\$
  • \$\begingroup\$ hi, your sample could be replaced with intToUtf8(runif(1,32,127)) \$\endgroup\$ – MickyT Nov 6 '17 at 21:05
  • \$\begingroup\$ @MickyT excellent, thank you! \$\endgroup\$ – Giuseppe Nov 7 '17 at 15:00
  • \$\begingroup\$ You can save 1 byte with 32+95*runif(1) as your random sampler. \$\endgroup\$ – Robin Ryder Apr 15 at 21:41
6
\$\begingroup\$

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
\$\endgroup\$
5
\$\begingroup\$

Ruby, 42 bytes

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

Try it online!

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

Pyth - 14 bytes

.W!}zH+ZOrd\k

Try it online here.

\$\endgroup\$
  • \$\begingroup\$ W!}Qk=+kpOrd\ is 14 bytes as well, SE is messing with formatting because of unprintable but range is generated the same way \$\endgroup\$ – Dave Nov 5 '17 at 23:45
4
\$\begingroup\$

Mathematica, 65 bytes

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

Try it online!

-3 bytes from Jonathan Frech

\$\endgroup\$
  • \$\begingroup\$ I think FromCharacterCode[RandomInteger@94+32] is equivalent to the shorter RandomChoice@CharacterRange[32,126]. \$\endgroup\$ – Jonathan Frech Nov 5 '17 at 23:12
  • \$\begingroup\$ @JonathanFrech yes,it is! \$\endgroup\$ – J42161217 Nov 5 '17 at 23:18
4
\$\begingroup\$

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!

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

MATL, 17 16 bytes

''`6Y2TZrhtGXfn~

Try it online!

-1 byte thanks to Giuseppe

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

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!

\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to the site! :) \$\endgroup\$ – DJMcMayhem Nov 6 '17 at 21:00
  • \$\begingroup\$ 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) \$\endgroup\$ – Luis Mendo Nov 6 '17 at 23:38
  • \$\begingroup\$ 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 \$\endgroup\$ – Luis Mendo Nov 6 '17 at 23:48
  • \$\begingroup\$ I️ attempted to do that, but I️ couldn’t think of a concise way so I️ skipped it. Nice revisions! \$\endgroup\$ – Alan Nov 7 '17 at 0:21
  • 1
    \$\begingroup\$ Feel free to incorporate those suggestions into your answer. That's standard on this site \$\endgroup\$ – Luis Mendo Nov 7 '17 at 11:37
4
\$\begingroup\$

Japt, 16 14 11 bytes

;_øU}a@P±Eö

Try it

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

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.
\$\endgroup\$
3
\$\begingroup\$

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.

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

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
\$\endgroup\$
  • 1
    \$\begingroup\$ It should be 32+Math.random()*95. There... bug fixed and a byte saved! ;-) \$\endgroup\$ – Olivier Grégoire Nov 7 '17 at 18:00
  • \$\begingroup\$ @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.. \$\endgroup\$ – Kevin Cruijssen Nov 7 '17 at 18:20
3
\$\begingroup\$

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.
\$\endgroup\$
  • 1
    \$\begingroup\$ You can do Ω instead of .R. \$\endgroup\$ – Emigna Jan 16 '18 at 13:20
  • 2
    \$\begingroup\$ Lol, using an Ohm, to beat Ohm v2. How nice. \$\endgroup\$ – Magic Octopus Urn Jan 17 '18 at 14:27
2
\$\begingroup\$

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:AId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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
\$\endgroup\$
2
\$\begingroup\$

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;
\$\endgroup\$
2
\$\begingroup\$

Javascript 74 bytes

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

call like this:

s('hi')
\$\endgroup\$
  • \$\begingroup\$ @Giuseppe thx, I have it added in the byte count \$\endgroup\$ – RuteNL Nov 8 '17 at 14:37
  • 1
    \$\begingroup\$ I think you have to change 94 to 95 for the code to be valid \$\endgroup\$ – Hawkings Nov 9 '17 at 0:21
  • 1
    \$\begingroup\$ @Hawkings Yea, you're right, fromCharCode ignores decimals it seems. Thanks for pointing it out! \$\endgroup\$ – RuteNL Nov 9 '17 at 9:39
  • \$\begingroup\$ Save a byte with ~b.search instead of b.includes. \$\endgroup\$ – Shaggy Jan 16 '18 at 11:02
  • \$\begingroup\$ @Shaggy Nice! Didn't know about search \$\endgroup\$ – RuteNL Jan 16 '18 at 13:07
2
\$\begingroup\$

Julia 0.6, 53 bytes

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

Try it online!

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

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
\$\endgroup\$
2
\$\begingroup\$

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 .

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

Pyth, 13 bytes

W!}z=akpOrd\

where the unprintable character is 0x7F.

Test

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

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

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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