Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Output one random character for each character of source code (as illustrated below). The probability of each character is its frequency in the original source code. Thus the output will be fake source code resembling a quine.

Specification

  • Restrictions
    • Standard constrains apply. No empty programs or functions. Also no reading your own source.
  • Output
    • The number of characters output should be exactly the number of characters in the source code
    • Each output character should be randomly choosen
    • The probability of choosing any character is equal to (occurrences in source) / (length of source)
    • This means that even a unary solution needs to 'randomly' choose 1 with probability 1. Which is to say that the output can't be hard coded.
  • Winning
    • This is code golf, so fewest bytes wins

Example

Program           Frequency           Probability           Possible Output
-------           ---------           -----------           ---------------           
 a@!@              a - 1               a - 25%               @@a@
                   ! - 1               ! - 25%
                   @ - 2               @ - 50%
Program           Frequency           Probability           Possible Output
-------           ---------           -----------           ---------------
caBaDBcDaBDB       a - 3               a - 25%               aaaBBBBccDDD
                   B - 4               B - 33%
                   c - 2               c - 17%
                   D - 3               D - 25%
share|improve this question
    
Are single-character quines allowed? – Nathan Merrill yesterday
    
@NathanMerrill Yes, single character (and other unary) solutions are allowed. However, their output still needs to be randomly chosen. – NonlinearFruit yesterday
    
How shall I find the occurences of characters in a file if I am not allowed to read it? – Titus yesterday
1  
Is this code-golf? – OldBunny2800 yesterday
1  
@VolAnd No. The probability of each character appearing is based on the character frequency. If you flip a coin twice and it lands on heads once, it doesn't have to hand on tails the second time. – wizzwizz4 yesterday

14 Answers 14

CJam, 14 bytes

{{E*`mR}`mR}E*

Try it online!

Explanation

Each character appears exactly twice, so the probabilities of the characters should all be the same.

{           e# Repeat this block 14 times.
  {E*`mR}   e# Push this (nonsensical) block.
  `         e# Stringify it, giving the string "{E*`mR}", which contains each of the
            e# seven characters once.
  mR        e# Select one of the characters at random.
}E*
share|improve this answer

Jelly, 13 bytes

“;⁾vṾWṁ$X€”vṾ

Try it online!

How it works

“;⁾vṾWṁ$X€”vṾ  Main link. No arguments.

“;⁾vṾWṁ$X€”    Set the argument and return value to the string s := ';⁾vṾWṁ$X€'.
            Ṿ  Uneval; construct a string representation of s.
               This yields r := '“;⁾vṾWṁ$X€”'.
           v   Dyadic eval; evaluate s with argument r.


 ;⁾vṾWṁ$X€     Evaluated link (s). Argument: r

  ⁾vṾ          Yield 'vṾ'.
 ;             Concatenate r with 'vṾ'.
               This yields t := '“;⁾vṾWṁ$X€”vṾ', i.e., the original source code.
       $       Combine the previous two links into a monadic chain.
     W           Wrap; yield ['“;⁾vṾWṁ$X€”vṾ'].
      ṁ          Mold; repeat ['“;⁾vṾWṁ$X€”vṾ'] once for each charcter in t.
        X€     Random each; select a character, uniformly at random, of each
               of the 13 repetitions of t.
share|improve this answer

Japt, 22 bytes

"+Q ²£ZgMqB"+Q ²£ZgMqB

Test it online!

How it works

"+Q ²£ZgMqB"+Q ²£ZgMqB  // Implicit: B = 11
"+Q ²£ZgMqB"            // Take this string.
            +Q          // Append a quotation mark.
               ²        // Double the result.
                £       // Replace each char in the result Z with
                 Zg     //  the char in Z at index
                   MqB  //   random integer in the range [0, 11).
                        // Implicit: output last expression
share|improve this answer

Pyth, 16 Bytes

smO+N"m1NOs+6"16

try it online!

Contains each char twice therefore the probability is the same as if each was only in there once.

smO+N"m1NOs+6"16     #
   +N"m1NOs+6"       # Add a quotation mark to the string: "m1NOs+6
  O                  # random choice from the string
 m            16     # do this 16 times.
s                    # join the list into a string
share|improve this answer

PHP, 71 140 110 124 140 120 bytes

for($i=2*$n=strlen($s='for($i=2*$n=strlen($s=.chr(39));$i--;)echo$s[rand(0,$n-1)];'.chr(39));$i--;)echo$s[rand(0,$n-1)];

run with php -d

  1. creates a string containing the code without the quotation marks
  2. and concatenates the quotation mark once using ord
    (same probability as if I would double the string and add two quotes);
  3. then loops over twice the length of the string to get random characters from it.

Can possibly be golfed further, but my attempts on eval where futile so far.
I will probably not go deeper here.

share|improve this answer
1  
The probability of each character is its frequency in the original source code. I may be wrong, but it doesn't look like this entry meets this requirement. – ETHproductions yesterday
    
Oh I missed that point. Back to the editor. How can this be done without reading the code? – Titus yesterday
    
Using this, I got a syntax error, unexpected '<'. But I'm not familiar with PHP, how do I test this? – NonlinearFruit yesterday
    
@NonlinearFruit: Did you use the -d flag? This is supposed to be saved to a file and then called with php or php-cgi without any flags. Maybe you can use a heredoc. – Titus yesterday
    
@NonlinearFruit: ... or just remove the leading <? for usage with -d. – Titus 21 hours ago

Jelly, 44 bytes

I hope I have interpreted all the rules correctly (I'm not quite sure what the "carry payload" thing is in meta or if it's even relevant to this challenge).

“ẋ2;8220Ọ;8221ỌXµ44СḊ”ẋ2;8220Ọ;8221ỌXµ44СḊ

Test it out at TryItOnline

This constructs a string from which to choose characters. The initial string has all the character used except the open and close quotes. It then doubles that string and concatenates one of each of the open and close quotes from ordinals (hence the need to double the other characters). Lastly it repeatedly picks random characters from the composed string to the length of the program.

share|improve this answer
1  
@NonlinearFruit Oops - I updated to add a missed character from my string but did not update to 44 - thanks! – Jonathan Allan yesterday

Pyke, 35 bytes

35F\";"\\+3322 5**F;H)s"\"2*+2* H)s

Try it here!

To check: remove the final H and the resulting string contains the right number of each character (with the extra H)

This does NOT use a generalised quine or in fact a quine at all. It relies on being able to create a string containing all the characters in the source. It should be able to do it for any code but each character logarithmically increases code size. The only number of times a character is allowed in the source is 2 or 7

share|improve this answer

Python 2, 88 bytes

s='''from random import*; print "".join(choice(s) for c in "s='"+s+"';exec s")''';exec s

All actual merit in getting this far goes to mbomb007 - thanks for your help (and the pointer about backslashes)

share|improve this answer
1  
This is a quine-like challenge, without input or reading your source code (suppose it is n characters long), you need to print n random characters. Where the probability of a symbol c being chosen is equal to (number of times c occurs in your solution) / n. – NonlinearFruit 18 hours ago
    
So more like this? exec("""s = 'from random import choice; print "".join([choice(s) for c in s])'; exec(s)""") – user59421 17 hours ago
    
You haven't included the single quotes yet, and you don't need the square brackets within the join. – mbomb007 17 hours ago
    
Thanks - and right, I got a little caught up in the rush of nudging closer to the solution – user59421 17 hours ago
1  
Here you go: s='''from random import*;print"".join(choice(s)for c in s+"s='';''exec s''")''';exec s. I wish I'd thought of that. – mbomb007 17 hours ago

Ruby, 81 bytes

s="s=%p;a=s%%s;81.times{$><<a[rand(a.size)]}";a=s%s;81.times{$><<a[rand(a.size)]}

I didn't realize that you had to randomly select every time; I thought a shuffle would do the trick. This can probably be golfed, but it's the shortest I could get it.

Standard Ruby quine with a few modifications so it prints out the shuffled string. I'm sad because it took like fifteen minutes to figure out the formatting quirks before I realized that I was subconsciously stealing it anyway.

I think the string shuffling can be shortened but I don't know how; I might also be able to finagle the formatting into being shorter once I put some thought into it. Help would be appreciated.

Try it online!

share|improve this answer
    
I think (like my CJam) answer, it's not necessary to use a standard quine as the basis. A direct port of my CJam solution gives 64 bytes: 64.times{$><<"64.times{$><<.inspect[rand 32]}".inspect[rand 32]} – Martin Ender 1 hour ago
    
Nevermind, basing it on a standard quine is shorter, but you'll have to use the eval-based quine: eval r="47.times{$><<('eval r=%p'%r)[rand 47]}" – Martin Ender 1 hour ago

Python 3, 134 132 bytes

I use every character in my source code within the string the correct number of times, then multiply the string by two to include itself. The program prints a random character from that string for each character in the code (the length is hard-coded.)

from random import*
for i in[0]*134:print(choice("""from random import*
for i in[0]*134:print(choice(""*""2""),end='')"""*2),end='')

Try it online

I avoided backslashes like the plague. As soon as the code contains \n or \", you have a problem, because the string doesn't contain backslashes yet, so you have to add those also, but in a separate string multiplied by a higher number, because it takes two backslashes to represent one (\\).

Example output:

i(tc*"3]i o''r=,,,h34t"r
ri"](fco t)niap)t "it2nc0o  npoi3'"nto(*4 i(ido' r*4f"oi]d rm ,i"eif)m"d
m emi
dfr n*p 3*(i""r1d"dr menc hio'

I gotta say, it reminds me of FlogScript.

share|improve this answer

PowerShell v2+, 175 bytes

$d='$d={0}{1}{0}{2}-join(0..174|%{3}[char[]]($d-f [char]39,$d,"`n",[char]123,[char]125)|Random{4})'
-join(0..174|%{[char[]]($d-f [char]39,$d,"`n",[char]123,[char]125)|Random})

Quines in PowerShell suck, because the string replacement delimiters {} also denote loops and whatnot, so you need to use a bunch of chars in the -f operator, which bloats the code.

Similar-ish to my Quine on Every Line answer. Basically we loop from 0 to 174 and each iteration re-calculate the quine $d, cast it as a char-array, and pull out a Random element chosen uniformly from the input. By definition, this gives probability (occurrences in source) / (length of source) as required. Those characters are encapsulated in parens and -joined together back into a string.

Example

PS C:\Tools\Scripts\golfing> .\faux-souce-code.ps1
}}[${hr[`ini}}] [5i,=[]0,j2($=n4(dm]jh]jc]]7
}..j"rnj9|fn,4r]{9]('["jdh0}$rd,-f,a.c"}{h1 ]5d,),0n5|nh(]73a9da4aRi[5}a}430}}rd$,$r)-hhr%or79-R.R-`'r'aa|=1f0][|[{7}do1]$ja0 rd{h

(Yes, that's a newline in the output -- when a string containing a newline is char-array'd, the `n is treated as a character, since a char-array is just an array of byte codes, so it also has a 1/175th chance of being selected.)

share|improve this answer

Dyalog APL, 20 bytes

f←{(,⎕CR'f')[?⍴⍨20]}

f←{...} define f as

(,⎕CR'f') listified (,) Character (table) Representation (⎕CR) of f ('f')

[?⍴⍨20] indexed with ([...]) random-up-to (?) repeat-itself-times (⍴⍨) of twenty

Let us run it (with a dummy argument) a few times:

      f⍬
)0'0](⍨(([],}⎕))⎕'f2
      f⍬
{'['}f[←R[)2←?}⍨]}C2
      f⍬
,,⍨←?2}⍴?'⍨}C,'{⎕(C0

Fine, but is the distribution correct? Let us run it on 10,000 dummy arguments and see how many times each character occurs:

      {⍺ , 1E¯4× ⍴⍵}⌸ ∊ f¨ ⍳1E4
C 0.9952
⎕ 0.9996
' 1.9777
f 2.004 
← 1.0018
⍨ 1.0173
0 1.0213
] 1.0049
[ 0.9988
2 0.9943
{ 0.9895
) 1.0093
R 1.0054
, 1.0029
? 0.9943
} 0.9861
⍴ 1.0032
( 0.9944

Clearly, f and ' occur twice as often as the other characters, just like in the original source code.

How did we do it?

{⍺ , 1E¯4× ⍴⍵}⌸ ∊ f¨ ⍳1E4`

⍳1E4 generates the first 10,000 integers

runs f on each of those numbers

flattens all the pseudo-quines into a single 200,000-character string

is a higher-order function which for each unique character in the right side data, feeds the left-side function the unique element as left-argument and the indices where that character occurs as right-argument. The left-side function is

{⍺ , 1E¯4× ⍴⍵}

left-argument, i.e. the unique character

, followed by

1E¯4× 1×10⁻⁴ times

⍴⍵ the shape of the right-argument (the occurrence indices), i.e.how many times it occurs

Finally, puts it all together in a table.

share|improve this answer

C, 60 bytes

l,i;f(char*s){l=i=strlen(s);while(i--)putchar(s[rand()%l]);}

While for counting characters my solution needed 86:

c[256];i;f(char*s){i=256;while(*s)c[*s++]++;while(--i)while(c[i]?c[i]--:0)putchar(i);}
share|improve this answer
    
Why does f take input? – NonlinearFruit 23 hours ago
    
It should not? Perhaps I do not understand the rules of this quiz. My f takes string and prints to standard output: string can be any sequence of characters. – VolAnd 22 hours ago
1  
This is a quine-like challenge, without input or reading your source code (suppose it is n characters long), you need to print n random characters. Where the probability of a symbol c being chosen is equal to (number of times c occurs in your solution) / n. – NonlinearFruit 22 hours ago

Pyth: 1 byte

0

Try it Online

Simplistic approach. one character only needs to be printed out all the time, if you only use one character.

share|improve this answer
    
I don't believe this answer is valid. From the rules: ...even a unary solution needs to 'randomly' choose 1 with probability 1. Which is to say that the output can't be hard coded. – ETHproductions 16 hours ago
    
well I replaced random between 1 and 1 with just 1. It is the most random it will ever get. For the purposes of black box programming, it's 100% indistinguishable from a random source. I think that it follows the rules just fine, it prints out the solution with a probability of 1. – tuskiomi 16 hours ago
    
As much I dislike this rule of the challenge, the OP has expressed very clearly that fixed-output solutions that don't make (redundant) use of a PRNG are disallowed. – Martin Ender 16 hours ago
1  
Like I said, I don't like the rule either and you're free to downvote the challenge for it, but that doesn't mean its fine to ignore it and answer it anyway. – Martin Ender 16 hours ago
1  
If you take that argument, you're running afoul of this standard loophole – TimmyD 16 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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