54
\$\begingroup\$

About the Series

This is a guest entry for the Random Golf of the Day series.

First off, you may treat this like any other code golf challenge, and answer it without worrying about the series at all. However, there is a leaderboard across all challenges. You can find the leaderboard along with some more information about the series in the first post.

Input

No input is taken.

Output

A single letter of the alphabet (case irrelevant), with an optional trailing newline. Each letter must have non-zero probability of being chosen, and all 26 probabilities must be distinct. To remove all ambiguity: Distinct means that there must not be two probabilities that are equal to each other.

Scoring

This is code golf. Shortest code in bytes wins.

A valid entry is a full program or function that has zero probability of not terminating.

Alphabet

To avoid confusion, the particular alphabet to be used is the Latin alphabet:

Either

ABCDEFGHIJKLMNOPQRSTUVWXYZ

or

abcdefghijklmnopqrstuvwxyz

You may choose to output upper case or lower case. Alternatively, you may choose to output different cases on different runs if that helps. The probability for a given letter is the probability of that letter appearing in either case (upper or lower).

Explanation

As it won't be at all obvious from the output, please include a clear explanation of how you achieved the 26 distinct probabilities.

Leaderboard

(from here)

var QUESTION_ID=89621,OVERRIDE_USER=20283;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

The first post of the series also generates an overall leaderboard.

To make sure that your answers show up, please start every answer with a headline, using the following Markdown template:

## Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

## Ruby, <s>104</s> <s>101</s> 96 bytes

(The language is not currently shown, but the snippet does require and parse it, and I may add a by-language leaderboard in the future.)

\$\endgroup\$
5
  • \$\begingroup\$ how would you measure 26 distinct probabilities? by running program 26 times? \$\endgroup\$
    – YOU
    Aug 12, 2016 at 12:47
  • 1
    \$\begingroup\$ @YOU have a look through the solutions - there are a few different approaches with excellent explanations \$\endgroup\$ Aug 12, 2016 at 12:49
  • \$\begingroup\$ If it is a function does it need to print or can it just return the character value? \$\endgroup\$ Aug 13, 2016 at 6:12
  • \$\begingroup\$ @Geoff According to our defaults for input and output, either printing to STDOUT or returning a character are fine. \$\endgroup\$ Aug 13, 2016 at 10:48
  • \$\begingroup\$ @Geoff note that it must be a character, not just a number value representing it. For example, A rather than 65. \$\endgroup\$ Aug 13, 2016 at 10:50

62 Answers 62

24
\$\begingroup\$

MATL, 6 Characters

1Y2Xr)

Explanation:

Xr Take a normally distributed random number ) Use this to index into... 1Y2 The alphabet

The distribution is symmetrical around 0, and the translation of number to char is symmetrical around 0.5. As such the probabilities should be distinct.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ Oh, very good idea to use a Gaussian distribution! \$\endgroup\$
    – Luis Mendo
    Aug 12, 2016 at 14:50
  • 1
    \$\begingroup\$ "best" language for the job, still beaten by jelly. Excellent solution though. \$\endgroup\$ Aug 12, 2016 at 15:41
22
\$\begingroup\$

05AB1E, 6 bytes

Code

A.pJ.R

Explanation

A        # Pushes the alphabet
 .p      # Computes all prefixes
   J     # Join them together

We now have the following string:

aababcabcdabcdeabcdefabcdefgabcdefghabcdefghiabcdefghijabcdefghijkabcdefghijklabcdefghijklmabcdefghijklmnabcdefghijklmnoabcdefghijklmnopabcdefghijklmnopqabcdefghijklmnopqrabcdefghijklmnopqrsabcdefghijklmnopqrstabcdefghijklmnopqrstuabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvwabcdefghijklmnopqrstuvwxabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyz

After that, we pick a random element using .R.

The probabilities

a > 7.4074074074074066%
b > 7.122507122507122%
c > 6.837606837606838%
d > 6.552706552706553%
e > 6.267806267806268%
f > 5.982905982905983%
g > 5.698005698005698%
h > 5.413105413105414%
i > 5.128205128205128%
j > 4.843304843304843%
k > 4.5584045584045585%
l > 4.273504273504274%
m > 3.988603988603989%
n > 3.7037037037037033%
o > 3.418803418803419%
p > 3.133903133903134%
q > 2.849002849002849%
r > 2.564102564102564%
s > 2.2792022792022792%
t > 1.9943019943019944%
u > 1.7094017094017095%
v > 1.4245014245014245%
w > 1.1396011396011396%
x > 0.8547008547008548%
y > 0.5698005698005698%
z > 0.2849002849002849%

Try it online!.

\$\endgroup\$
19
\$\begingroup\$

Pyth, 5

Os._G

Try it here

Computes the prefixes of the alphabet, so: ["a", "ab", "abc", ..., "abcdefghijklmnopqrstuvwxyz"]. Then flattens the list and selects a random element from it uniformly. This means that since a appears 26 times, while b appears 25 times, all the way down to z with only 1 appearance, each letter has a different chance of appearing. The total string has 351 characters.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ I like that answer. Very clever. \$\endgroup\$ Mar 6, 2018 at 20:11
19
\$\begingroup\$

Jelly, 5 bytes

ØA»ẊX

Try it online!

How it works

ØA«ẊX  Main link. No arguments.

ØA     Set argument and return value to the alphabet.
   Ẋ   Shuffle it.
  »    Yield the maximum of each letter in the sorted alphabet, and the
       corresponding character in the shuffled one.
    X  Pseudo-randomly select a letter of the resulting array.

Background

Let L0, …, L25 denotes the letters of the alphabet in their natural order, and S0, …, S25 a uniformly at random selected permutation of L. Define the finite sequence M by Mn = max(Ln, Sn).

Fix n in 0, … 25 and define k as the index such that Ln = Sk.

With probability 1 / 26, Ln = Sn and n = k, so Mn = Ln and Ln occurrs once in M.

With probability 25 /26, Ln ≠ Sn and n ≠ k. In this case, the following happens.

  • With probability n / 25, Sn is one of L0, …, Ln - 1, so Ln > Sn and Mn = Ln.

  • Independently, also with probability n / 25, k is one of 0, … n - 1, so Sk > Lk and Mk = Sk = Ln.

Thus, the expected number of occurrences of Ln in M is 1/26 + 25/26 · (n/25 + n/25) = (2n + 1)/26.

Finally, if we now select a term m of M uniformly at random, the letter Ln we be chosen with probability (2n + 1)/26 / 26 = (2n + 1)/676.

This yields the following distribution of probabilities.

p(m = A) =  1/676 ≈ 0.00148
p(m = B) =  3/676 ≈ 0.00444
p(m = C) =  5/676 ≈ 0.00740
p(m = D) =  7/676 ≈ 0.01036
p(m = E) =  9/676 ≈ 0.01331
p(m = F) = 11/676 ≈ 0.01627
p(m = G) = 13/676 ≈ 0.01923
p(m = H) = 15/676 ≈ 0.02219
p(m = I) = 17/676 ≈ 0.02515
p(m = J) = 19/676 ≈ 0.02811
p(m = K) = 21/676 ≈ 0.03107
p(m = L) = 23/676 ≈ 0.03402
p(m = M) = 25/676 ≈ 0.03698
p(m = N) = 27/676 ≈ 0.03994
p(m = O) = 29/676 ≈ 0.04290
p(m = P) = 31/676 ≈ 0.04586
p(m = Q) = 33/676 ≈ 0.04882
p(m = R) = 35/676 ≈ 0.05178
p(m = S) = 37/676 ≈ 0.05473
p(m = T) = 39/676 ≈ 0.05769
p(m = U) = 41/676 ≈ 0.06065
p(m = V) = 43/676 ≈ 0.06361
p(m = W) = 45/676 ≈ 0.06657
p(m = X) = 47/676 ≈ 0.06953
p(m = Y) = 49/676 ≈ 0.07249
p(m = Z) = 51/676 ≈ 0.07544

You can empirically verify the distribution by calling the link 100,000 times (takes a few seconds).

\$\endgroup\$
12
  • 1
    \$\begingroup\$ @RobertFraser the shuffle-and-yield step produces a list with an A anywhere an A appeared in either list, a B where a B appeared in either list and anything other than A in the other list, ... a Z anywhere that Z appeared in both lists. so there are approx 52x as many A as Z in the result. \$\endgroup\$
    – Sparr
    Aug 12, 2016 at 23:47
  • 1
    \$\begingroup\$ @RobertFraser I've added an explanation. \$\endgroup\$
    – Dennis
    Aug 13, 2016 at 0:02
  • 2
    \$\begingroup\$ @DennisJaheruddin In UTF-8, yes. However, Jelly uses a custom code page that encodes all the characters it understands as a single byte each. The bytes link in the header points to it. \$\endgroup\$
    – Dennis
    Aug 13, 2016 at 6:56
  • 2
    \$\begingroup\$ I see, when I read the explanation it was not immediately clear that you cannot take advantage of the regular UTF-8 range as well. So, am I right to assume that by changing the interpreter and mapping all characters onto individul UTF-8 characters you would have completely identical code (just less readable/typable)? -- If so, consider expanding the explanation to mention that a char should count for a byte for golf purposes. \$\endgroup\$ Aug 13, 2016 at 7:13
  • 2
    \$\begingroup\$ @DennisJaheruddin As explained in the README (first link in the header), the interpreter has two modes (Jelly code page and UTF-8), so you can save this program in an actual 5-byte file. I could add all that information to every answer I write, but there are hundreds of them, so I chose linking instead. \$\endgroup\$
    – Dennis
    Aug 13, 2016 at 16:40
14
\$\begingroup\$

MATL, 10 bytes

1Y2rU26*k)

Try it online!

The code generates a uniform random variable on the interval (0,1) (r) and computes its square (U). This results in a non-uniform, decreasing probability density. Multiplying by 26 (26*) ensures that the result is on the interval (0,26), and rounding down (k) produces the values 0,1,...,25 with decreasing probabilities. The value is used as an index ()) into the uppercase alphabet (1Y2). Since MATL uses 1-based modular indexing, 0 corresponds to Z, 1 to A, 2 to B etc.

As an illustration that the probabilities are distinct, here's a discrete histogram resulting from 1000000 random realizations. The graph is produced by running this in Matlab:

bar(0:25, histc(floor(26*rand(1,1e6).^2), 0:25))

enter image description here

\$\endgroup\$
7
  • 1
    \$\begingroup\$ Nice! The best solution I could come up with is 16 bytes \$\endgroup\$
    – DJMcMayhem
    Aug 12, 2016 at 12:49
  • 1
    \$\begingroup\$ @DJMcMayhem Nice approach! \$\endgroup\$
    – Luis Mendo
    Aug 12, 2016 at 13:14
  • \$\begingroup\$ Maybe, but a lot longer. :P \$\endgroup\$
    – DJMcMayhem
    Aug 12, 2016 at 13:21
  • \$\begingroup\$ Another fun alternative: matl.suever.net/… \$\endgroup\$
    – Suever
    Aug 12, 2016 at 14:16
  • \$\begingroup\$ Actually you dont need the k ! Noticed that whilst trying codegolf.stackexchange.com/a/89648/11159 \$\endgroup\$ Aug 12, 2016 at 14:26
14
\$\begingroup\$

Java 7, 62 57 56 bytes

5 bytes thanks to Poke.

1 byte thanks to trichoplax.

char r(){return(char)(65+(int)Math.sqrt(Math.random()*676));}
char r(){return(char)(65+Math.sqrt(Math.random()*676));}
char r(){return(char)(65+Math.sqrt(Math.random())*26);}

Ideone it!

Frequency diagram (1e6 runs, scaling factor 1/1000)

A: *
B: ****
C: *******
D: **********
E: *************
F: ****************
G: *******************
H: **********************
I: *************************
J: ***************************
K: ******************************
L: **********************************
M: ************************************
N: ***************************************
O: *******************************************
P: *********************************************
Q: ************************************************
R: ***************************************************
S: ******************************************************
T: *********************************************************
U: ************************************************************
V: ***************************************************************
W: ******************************************************************
X: *********************************************************************
Y: ************************************************************************
Z: ***************************************************************************
\$\endgroup\$
5
  • 1
    \$\begingroup\$ I don't think you need to typecast to int \$\endgroup\$
    – Poke
    Aug 12, 2016 at 13:16
  • \$\begingroup\$ @Poke Thanks, golfed. \$\endgroup\$
    – Leaky Nun
    Aug 12, 2016 at 13:20
  • \$\begingroup\$ Can you save a byte by moving the 676 outside the parentheses? \$\endgroup\$ Aug 13, 2016 at 11:51
  • \$\begingroup\$ @trichoplax What do you mean? \$\endgroup\$
    – Leaky Nun
    Aug 13, 2016 at 12:26
  • 2
    \$\begingroup\$ sqrt(x*y*y) = sqrt(x)*y \$\endgroup\$ Aug 13, 2016 at 12:39
11
\$\begingroup\$

Perl, 24 bytes

-4 bytes thanks to @Martin Ender
-1 byte thanks to @Dom Hastings

say+(A..Z)[rand rand 26]

Needs -M5.010 or -E to run :

perl -E 'say+(A..Z)[rand rand 26]'

Running the following code will show the occurrence of each letter :

perl -MData::Printer -E '$h{(A..Z)[rand rand 26]}++ for 1 .. 1_000_000;$h{$_} = int($h{$_} / 100) / 100 for A .. Z;p %h;'
A 16.4
B 11.02
C 8.99
...
Z 0.07


How it works : I guess the code is pretty explicit, but still : it chooses a random number between 0 and rand 26. So there is a much higher probability that numbers close to 0 (letter A) are choosen.

\$\endgroup\$
3
  • \$\begingroup\$ The explanation makes sense to me :) \$\endgroup\$ Aug 12, 2016 at 14:56
  • \$\begingroup\$ Nice solution! You can save 1 byte using a bare list and +: say+(A..Z)[rand rand 26] \$\endgroup\$ Aug 12, 2016 at 18:20
  • \$\begingroup\$ @DomHastings aarf, I'm stupid. I tried (A..Z)[...] and it didn't work, so I thought I could use an anonymous array like that, but that was just because of the say.. thanks! :) \$\endgroup\$
    – Dada
    Aug 12, 2016 at 22:51
10
\$\begingroup\$

PHP, 44 36 29 27 bytes

Crossed out 44 is still regular 44 ;(

Thanks to insertusernamehere, Petah, and Crypto for all the help

<?=chr(65+rand(0,675)**.5);

It chooses a random number between 0 and 675 (=262-1), takes its square root, and floors it (the chr function converts its argument to an integer). Since the squares have different intervals between them, the probability of each number being chosen is distinct. Every n is chosen with probability (2n+1)/676.

Adding 65 to this number gives you a random character from A to Z.

Ideone of the code running 1,000,000 times

\$\endgroup\$
9
  • \$\begingroup\$ You can golf off 4 bytes: range(A,Z). \$\endgroup\$ Aug 12, 2016 at 15:21
  • \$\begingroup\$ @insertusernamehere: Thanks for the tip, but I was able to golf 8 bytes by not using range at all and just using chr(). \$\endgroup\$ Aug 12, 2016 at 15:26
  • 3
    \$\begingroup\$ Even better. Unfortunately crossed out 44 is still regular 44. :) \$\endgroup\$ Aug 12, 2016 at 15:33
  • 1
    \$\begingroup\$ @insertusernamehere You give up too easily :-) <s>&nbsp;44&nbsp;</s> \$\endgroup\$
    – MonkeyZeus
    Aug 12, 2016 at 20:00
  • \$\begingroup\$ <?=chr(65+sqrt(rand(0,675))); \$\endgroup\$
    – Petah
    Aug 14, 2016 at 10:08
9
\$\begingroup\$

R, 40 27 bytes

LETTERS[sample(26,1,,1:26)]

This will take 1 number from 26 numbers generated with growing probability toward Z, without replacing, and display a letter the index of which is this number, from the list of uppercase letters LETTERS.

The arguments of the sample function are :

sample(
       26, #How many numbers to generate
        1, #How many numbers to sample
         , #Replacing ? Here, no by default
     1:26, #Weight of probabilities
       )
\$\endgroup\$
6
  • \$\begingroup\$ Yup', that won't work. There might me a cleverest way ! \$\endgroup\$
    – Frédéric
    Aug 12, 2016 at 12:41
  • \$\begingroup\$ Well, there will always be a lining somewhere ! Gotta think 'bout it... \$\endgroup\$
    – Frédéric
    Aug 12, 2016 at 12:48
  • 1
    \$\begingroup\$ Fixed and shorter - impressive :) \$\endgroup\$ Aug 12, 2016 at 13:59
  • 1
    \$\begingroup\$ @trichoplax Thanks ! Nice challenge btw ! \$\endgroup\$
    – Frédéric
    Aug 12, 2016 at 16:18
  • 2
    \$\begingroup\$ @AlbertMasclans : It can indeed, but it has already been done in someone else's answer, so I don't want to "copy" ! But thanks anyway ! ;) \$\endgroup\$
    – Frédéric
    Aug 30, 2016 at 17:00
9
\$\begingroup\$

><>, 14 bytes

lx
;>dd+%'A'+o

><> is a toroidal 2D language, and the distinct probabilities part just naturally happens due to the language's only source of randomness. Try it online!

The relevant commands are:

[Row 1]
l          Push length of stack
x          Change the instruction pointer direction to one of up/down/left/right
           This gives a 50/50 chance of continuing on the first row (moving
           left/right) or going to the next row (moving up/down, wrapping if up)

[Row 2]
>          Change IP direction to right
dd+%       Take top of stack mod 26 (dd+ = 13+13 = 26)
'A'+       Add 65
o          Output as character
;          Halt

Thus the output probabilities are:

A:  1/2^1  + 1/2^27 + 1/2^53 + ... = 33554432 / 67108863 ~ 0.50000000745
B:  1/2^2  + 1/2^28 + 1/2^54 + ... = half of chance for A
C:  1/2^3  + 1/2^29 + 1/2^55 + ... = half of chance for B
...
Z:  1/2^26 + 1/2^52 + 1/2^78 + ... = half of chance for Y
\$\endgroup\$
8
\$\begingroup\$

R, 23 bytes

sample(LETTERS,1,,1:26)

Just 'samples' a letter from a builtin. the 1:26 is a vector of weights giving each letter a different probability.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ 1:26 is a vector of weights for each letter \$\endgroup\$ Aug 12, 2016 at 13:38
  • \$\begingroup\$ That makes it a valid answer. It's worth editing in an explanation so people not familiar with R can understand how it works. \$\endgroup\$ Aug 12, 2016 at 14:15
  • 1
    \$\begingroup\$ I was going to, and then I realized that the guy above me had done much the same thing in his code and given an in depth explainer. \$\endgroup\$ Aug 12, 2016 at 14:48
  • \$\begingroup\$ It's good that you added an explanation - the order in which solutions appear on the page can vary as the votes come in so the ones "above" might not be above later. \$\endgroup\$ Aug 12, 2016 at 15:12
8
\$\begingroup\$

Python 2, 58 57 bytes

from random import*
print chr(int(65+(random()*676)**.5))

Explanation: this generates a random floating point number in the interval [0, 676), takes the square root and then floors it. Then it adds 65 (the ascii value of "A"), converts it to a char, and prints it.

This gives each number from 0 to 25 a distinct probability. To understand why, think about it like this. How many numbers, ignoring non-integers, when you take the square root and floor give 0? Only one number will (zero). This means that zero has a probability of 1/676. How many numbers will produce 1? 3 will, 1, 2, and 3. This means one has a probability of 3/676. A two can be produced with a 4, 5, 6, 7, or 8, giving it probability 5, a three has probability 7, etc. and since the difference between consecutive squares increases steadily by two, this pattern continues for every number up to 25 (Z).

1 byte saved thanks to leaky nun!

\$\endgroup\$
11
  • \$\begingroup\$ chr(int(65+randint(676)**.5)) \$\endgroup\$
    – Leaky Nun
    Aug 12, 2016 at 13:11
  • 1
    \$\begingroup\$ You could do chr(int(65+random()**.5*26)). Its the same thing algebraically because 26 == √676. and now order of operations is on your side \$\endgroup\$
    – Wheat Wizard
    Aug 12, 2016 at 14:56
  • 3
    \$\begingroup\$ @EamonOlive For another byte **2*26 could be used for the inverse distribution. \$\endgroup\$
    – user81655
    Aug 12, 2016 at 16:44
  • 1
    \$\begingroup\$ 1/random()%26 should also work. \$\endgroup\$
    – xnor
    Aug 13, 2016 at 5:55
  • 1
    \$\begingroup\$ @xnor that will sometimes give 1/0%26 \$\endgroup\$ Aug 13, 2016 at 14:27
6
\$\begingroup\$

Befunge, 40 bytes

Revisiting this 7 years later, I realized I I could just add the whole alphabet in one string and pop off a random amount of letters before printing. Suddenly it beats Python!

"ZYXWVUTSRQPONMLKJIHGFEDCBA"> #$?:#@ #,_

Probabilities are the same as before; Starting from A, there is a 1/4 chance of printing the top of the stack, 2/4 to try again, and 1/4 to pop off one letter and repeat. If it somehow manages to move past Z it just starts over again with A. Trying a few times, the highest I got was an E.

Try it online!

Befunge, 168 164 bytes

More compact than the first one, with a little different probabilities: The first ? have a 1/4 chance of printing an A on "first try", 2/4 chance to come back to the same ?, and 1/4 to move to the next. The rest of the ?s each have 1/4 chance of printing the letter underneath them, 1/4 to try again, 1/4 moving to the next letter, 1/4 moving to the previous. Again, the probability of printing an A is a lot higher than printing a Z.

??????????????????????????>
""""""""""""""""""""""""""
ABCDEFGHIJKLMNOPQRSTUVWXYZ
""""""""""""""""""""""""""
>>>>>>>>>>>>>>>>>>>>>>>>>>,@
##########################

Befunge, 186 bytes

Obviously not gonna win with this, but I think it's an interesting answer nonetheless :)

v and > steers the cursor respectively downwards and to the right. The ? operator sends the cursor off in one of four directions randomly. The first ? is "blocked" by v and > in two directions, so it only has two way to go: Either to print the A, or down to the next ?. So from the first ? alone there is a 50% chance of printing an A.

The next ? has a 1/3 chance of printing a B, 1/3 of going back up, and 1/3 of going further down. Etc etc.

It should be quite obvious that the higher letters have a much larger chance of being printed than the lower ones, but I'm not exactly sure what each letter's chances are.

Some help with the exact math would be appreciated :)

At least there's a 1/2 * 1/3^25 chance that the cursor moves all the way down to the Z on the first try, but I'm uncertain how the chances of the cursor moving up and down affects each letter.

,@ prints and quits.

 v
>?"A"v
>?"B"v
>?"C"v
>?"D"v
>?"E"v
>?"F"v
>?"G"v
>?"H"v
>?"I"v
>?"J"v
>?"K"v
>?"L"v
>?"M"v
>?"N"v
>?"O"v
>?"P"v
>?"Q"v
>?"R"v
>?"S"v
>?"T"v
>?"U"v
>?"V"v
>?"W"v
>?"X"v
>?"Y"v
>?"Z">,@
\$\endgroup\$
1
  • 1
    \$\begingroup\$ +1 because you included the alphabet in a plywood sandwich. \$\endgroup\$ Sep 2, 2023 at 12:33
5
\$\begingroup\$

PowerShell v2+, 33 31 bytes

[char](65..90|%{,$_*$_}|Random)

Takes a range from 65 to 90 (i.e., ASCII A to Z), pipes it through a loop. Each iteration, we use the comma-operator to create an array of that element times that number. For example, this will make 65 65s, 66 66s, 67 67s, etc. That big array is piped to Get-Random which will (uniformly PRNG) select one element. Since there are different quantities of each element, each character has a slightly distinct percentage chance of being picked. We then encapsulate that in parens and cast it as a char. That's left on the pipeline and output is implicit.

(Thanks to @LeakyNun for golfing a few bytes even before it was posted. :D)


The probabilities

(slight rounding so I could demonstrate the P option of the -format operator)

PS C:\Tools\Scripts\golfing> 65..90|%{"$([char]$_): {0:P}"-f($_/2015)}
A: 3.23 %
B: 3.28 %
C: 3.33 %
D: 3.37 %
E: 3.42 %
F: 3.47 %
G: 3.52 %
H: 3.57 %
I: 3.62 %
J: 3.67 %
K: 3.72 %
L: 3.77 %
M: 3.82 %
N: 3.87 %
O: 3.92 %
P: 3.97 %
Q: 4.02 %
R: 4.07 %
S: 4.12 %
T: 4.17 %
U: 4.22 %
V: 4.27 %
W: 4.32 %
X: 4.37 %
Y: 4.42 %
Z: 4.47 %
\$\endgroup\$
1
  • 1
    \$\begingroup\$ I started without looking at any of the answers; tried to build on gal output ([char[]]"uz$(gal|out-string)"-cmatch'[a-z]'|random) got to 50 characters, then 48, switched to numbers and got 42, then 31 and stopped there; looked on the leaderboard to see where that would put me. Right here. Character for character identical. Welp, I probably can't beat that. \$\endgroup\$ Aug 13, 2016 at 19:57
5
\$\begingroup\$

CJam, 21 17 12 bytes

Thanks to Martin Ender for saving me 5 bytes!

New version

'\,:,s_el-mR

This forms an array of strings following the pattern A, AB, ABC, and so on. It flattens it and chooses a random character. Since this string contains 26 A's, 25 B's, 24 C's, and so on, each letter has a distinct probability of being chosen.

Try it online!

Explanation

'\,          e# Push the range of all characters up to 'Z'
   :,        e# For each one, take the range of all characters up to it
     s       e# Convert the array of ranges to one string
      _el-   e# Subtract the lower case version of the string from itself
             e# This leaves only capital letters in the string
          mR e# Take a random character from it

Old version

26,:)'[,'A,- .*M*mr0=

Gets distinct probabilities by making a string in which each letter appears a number of times equal to its position in the alphabet.

26,:)                 e# Push 1, 2, ... 26
     '[,'A,-          e# Push 'A', 'B', ... 'Z'
             .*       e# Vectorize: repeat each letter the corresponding number of times
               M*     e# Join with no separator
                 mr   e# Shuffle the string
                   0= e# Get the first character
\$\endgroup\$
0
5
\$\begingroup\$

C, 35 bytes

This program assumes RAND_MAX is (2^32 / 2) - 1 as it is on gcc by default. Compile with the -lm flag to link the sqrt function. The output is written to stdout as capital letters without trailing newlines.

f(){putchar(sqrt(rand())/1783+65);}

Optionally, if RAND_MAX is (2^16 / 2) - 1, a shorter 32 byte version can be used:

f(){putchar(sqrt(rand())/7+65);}

Just for fun, I also made a version that does not use the sqrt function or require the math library included (this one must have RAND_MAX as (2^32 / 2) - 1), but it ended up being longer even though I thought it was pretty cool:

f(){float r=rand()/64+1;putchar((*(int*)&r>>23)-62);}

Explanation

[First Program]

For the first two using sqrt, the function simply maps the range [0, RAND_MAX) to [0, 25] through division, and then adds 65 (ASCII A) to the value to shift it into the ASCII alphabet before outputting it.

[Second Program]

The second program is a bit more complex as it does a similar strategy, but without the sqrt operator. Since a floating point's exponent bits are automatically calculated upon assigning an integer, they can effectively be used as a crude way to get the base 2 logarithm of a number.

Since we only want the range up to RAND_MAX to reach an encoded exponent value of 25, the calculation (2^32 / 2 - 1) / (2 ^ 25) gives us just about 64, which is used during the division of rand to map it to this new range. I also added 1 to the value as 0's floating point representation is rather odd and would break this algorithm.

Next, the float is type-punned to an integer to allow for bitshifting and other such operations. Since in IEEE 754 floating point numbers the exponent bits are bits 30-23, the number is then shifted right 23 bits, cutting off the mantissa and allowing the raw exponent value to be read as an integer. Do note that the sign bit is also beyond the exponent bits, but since there are never any negatives it does not have to be masked out.

Rather than adding 65 to this result like we did before however, floating point exponents are represented as an unsigned 8 bit integer from 0 to 255, where the exponent value of 0 is 127 (Simply subtract 127 to get the actual "signed" exponent value). Since 127 - 65 is 62, we instead simply subtract 62 to both shift it out of this floating point exponent range and into the ASCII alphabet range all in one operation.

Distribution

I'm not math expert so I cannot say for sure the exact formula for these distributions, but I can (and did) test every value on the range [0, RAND_MAX) to show that the distance between where one letter's range ends and the other begins are never the same. (Note these tests assume the (2^32 / 2) - 1) random maximum)

[First Program]

Letter - Starting Location
A - 0
B - 3179089
C - 12716356
D - 28611801
E - 50865424
F - 79477225
G - 114447204
H - 155775361
I - 203461696
J - 257506209
K - 317908900
L - 384669769
M - 457788816
N - 537266041
O - 623101444
P - 715295025
Q - 813846784
R - 918756721
S - 1030024836
T - 1147651129
U - 1271635600
V - 1401978249
W - 1538679076
X - 1681738081
Y - 1831155264
Z - 1986930625

[Second Program]

Letter - Starting Location
A - 0
B - 64
C - 192
D - 448
E - 960
F - 1984
G - 4032
H - 8128
I - 16320
J - 32704
K - 65472
L - 131008
M - 262080
N - 524224
O - 1048512
P - 2097088
Q - 4194240
R - 8388544
S - 16777152
T - 33554368
U - 67108800
V - 134217664
W - 268435392
X - 536870848
Y - 1073741760
Z - 2147483520
\$\endgroup\$
2
  • \$\begingroup\$ Wouldn't it be shorter to just return the ordinal than to print it? Since char is an integral type in C, that should be acceptable. \$\endgroup\$
    – user45941
    Aug 14, 2016 at 6:31
  • \$\begingroup\$ @Mego Oh well yeah if you can do that, I'm just new to golfing so I'm not too familiar with what is considered acceptable output. \$\endgroup\$
    – Lemon Drop
    Aug 14, 2016 at 7:07
4
\$\begingroup\$

Python 2, 72 bytes

from random import*
print choice(''.join(i*chr(i)for i in range(65,91)))

Multiplies the character by its ascii value, then picks one character at random from the resulting string.

Here are the probabilities for each letter being selected, in percentages:

A 3.23
B 3.28
C 3.33
D 3.37
E 3.42
F 3.47
G 3.52
H 3.57
I 3.62
J 3.67
K 3.72
L 3.77
M 3.82
N 3.87
O 3.92
P 3.97
Q 4.02
R 4.07
S 4.12
T 4.17
U 4.22
V 4.27
W 4.32
X 4.37
Y 4.42
Z 4.47

Try it: https://repl.it/Cm0x

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

Labyrinth, 19 bytes

__v6%_65+.@
" )
"^2

Try it online!

This is a loop which, at each iteration, either a) increments a counter which starts at zero or b) terminates, both with probability 50%. At the end of the loop, the counter is taken modulo 26 and added to 65 to give a letter between A and Z.

This gives a probability for A just a bit over 50%, B just a bit over 25% and so on up to Z just a bit over 1/226. In theory, there is the possibility of this running forever, but this event has probability zero as required by the challenge (in practice that's probably not possible anyway because the PRNG will return both possible results at some point over its period).

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

Jelly, 5 bytes

ØAxJX

(Equal score, but a different method, to an existing Jelly solution by Dennis.)

The probability of yielding each letter is it's 1-based index in the alphabet divided by 351 - the 26th triangular number:

  • P(A) = 1 / 351, P(B) = 2 / 351, ..., P(Z) = 26 / 351.

Since 1+2+...+26 = 351, P(letter) = 1.

Implementation:

ØAxJX    - no input taken
ØA       - yield the alphabet: 'ABC...Z'
   J     - yield [1,...,len(Left)]: [1,2,3,...26]
  x      - Left times Right: 'abbccc...zzzzzzzzzzzzzzzzzzzzzzzzzz'
    X    - choose random element from Left

Test it on TryItOnline or get the distribution of 100K runs (code credit to Dennis)

\$\endgroup\$
3
  • \$\begingroup\$ Where'd you learn to be so good at Jelly? I find it hard to believe that Jelly would be common knowledge outside of PPCG. \$\endgroup\$ Aug 14, 2016 at 21:34
  • 2
    \$\begingroup\$ @Syxer I just looked at the wiki and bashed away - still don't get all of it :) \$\endgroup\$ Aug 14, 2016 at 21:38
  • 1
    \$\begingroup\$ Well then. Welcome to PPCG, have an up vote. \$\endgroup\$ Aug 14, 2016 at 21:42
3
\$\begingroup\$

q, 38 bytes

Not particularly short but...

.Q.A(reverse 0.9 xexp til 26)binr 1?1f

The discrete cumulative distribution function is the sequence

0.9 ^ 26, 0.9 ^ 25, ..., 0.9 ^ 0

And we merely sample from the distribution.

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

JavaScript (ES6), 45 bytes

_=>(n=Math.random(),10+n*n*26|0).toString(36)

Achieves non-uniform distribution by squaring the random value. Math.random() returns a float of the range [0,1) so the result of squaring this tends towards 0 (or a).

Test

var solution =

_=>(n=Math.random(),10+n*n*26|0).toString(36)

var frequency = Array(26).fill(0);
for (var i = 0, tests = 1000000; i < tests; i++)
  frequency[solution().charCodeAt(0) - 97]++;
result.textContent = frequency
  .map((n, i) => [ String.fromCharCode(97 + i), n ])
  .sort((a, b) => b[1] - a[1])
  .map((x) => `${x[0]}: ${(x[1] / tests * 100).toFixed(2)}%`)
  .join('\n');
<pre id="result"></pre>

\$\endgroup\$
1
  • \$\begingroup\$ 42 B, (n=Math.random(),10+26*n+n|0).toString(36) \$\endgroup\$ Nov 30, 2017 at 2:52
3
\$\begingroup\$

Oracle SQL 11.2, 212 bytes

Using character position in the alphabet as probability

SELECT c FROM(SELECT dbms_random.value(0,351)v FROM DUAL),(SELECT c,e,LAG(e,1,0)OVER(ORDER BY c)s FROM(SELECT CHR(LEVEL+64)c,SUM(LEVEL)OVER(ORDER BY LEVEL)e FROM DUAL CONNECT BY LEVEL<27))WHERE v BETWEEN s AND e;

Un-golfed

SELECT c FROM
  (SELECT dbms_random.value(0,351)v FROM DUAL), -- random value
  (
    SELECT c,e,LAG(e,1,0)OVER(ORDER BY c)s -- Mapping each character to its interval 
    FROM   (
             -- Each char has it's position in the alphabet as probability
             SELECT CHR(LEVEL+64)c,SUM(LEVEL)OVER(ORDER BY LEVEL)e 
             FROM   DUAL 
             CONNECT BY LEVEL<27
           )  
  )
WHERE v BETWEEN s AND e -- match the random value to an interval
\$\endgroup\$
3
\$\begingroup\$

TI-Basic, 39 bytes

sub("ABCDEFGHIJKLMNOPQRSTUVWXYZ",int(26^rand),1

rand generates a uniform value in (0,1]. This gives 26^rand a different probability to equal the integers from 1 to 26.

Older version, 45 bytes

sub("ABCDEFGHIJKLMNOPQRSTUVWXYZAAA",1+int(4abs(invNorm(rand))),1

Limited precision of the TI-Basic integers limits normal distributions to generating numbers within µ±7.02σ (see randNorm(). So we get the absolute value of a random number with µ 0 and σ 1, multiplying by four to increase the practical range mentioned before to µ±28.08σ. Then, we floor the value and add 1, since sub( is 1-indexed, giving us a range from 1-29 with different probabilities of each.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ @trichoplax That was my mistake, I had 30 left over from the old version that was [0,29]. I fixed it now. \$\endgroup\$
    – Timtech
    Aug 12, 2016 at 16:20
  • \$\begingroup\$ The interval (0,1] is supposed to be [0,1). \$\endgroup\$
    – kamoroso94
    Aug 14, 2016 at 3:12
  • \$\begingroup\$ @kamoroso94 Have you checked? "Note: Due to specifics of the random number generating algorithm, the smallest number possible to generate is slightly greater than 0. The largest number possible is actually 1" - quoted from tibasicdev.wikidot.com/rand \$\endgroup\$
    – Timtech
    Aug 14, 2016 at 22:27
3
\$\begingroup\$

PHP, 92 84 bytes

for($i=65,$x=0;$i<91;$a.=str_repeat(chr($i++),$x))$x++;echo substr($a,rand(0,$x),1);

Builds a string of all letters, repeated the number of times through the loop we are, and then picks a letter from that string at random. Letters later in the alphabet have a higher probability as a result

Thanks to insertusernamehere for shaving off bytes

outcome probabililities (ordered by %)

A => 0.29%
B => 0.62%
C => 0.82%
D => 1.15%
E => 1.50%
F => 1.65%
G => 2.00%
H => 2.27%
I => 2.52%
J => 2.80%
K => 3.13%
L => 3.47%
M => 3.72%
N => 3.93%
O => 4.15%
P => 4.59%
Q => 4.81%
R => 5.17%
S => 5.44%
T => 5.68%
U => 6.06%
V => 6.13%
W => 6.60%
X => 6.95%
Y => 7.17%
Z => 7.38%

\$\endgroup\$
5
  • 1
    \$\begingroup\$ changed to actually adhere to the rules. My mistake \$\endgroup\$
    – gabe3886
    Aug 12, 2016 at 13:37
  • \$\begingroup\$ @insertusernamehere I get undefined variable notices when I run that and no letter output \$\endgroup\$
    – gabe3886
    Aug 12, 2016 at 15:53
  • \$\begingroup\$ Oh I'm sorry. I think I got carried away and removed$x=0 which is obviously necessary. Here's a 84 bytes version: for($i=65,$x=0;$i<91;$a.=str_repeat(chr($i++),$x))$x++;echo substr($a,rand(0,$x),1); Did you ever manage to get a value greater then G when running your code? Anyway, you can always ignore notices when golfing. \$\endgroup\$ Aug 12, 2016 at 16:05
  • 1
    \$\begingroup\$ I did, but it takes a while to crop up. I ran it through about 100k iterations to check \$\endgroup\$
    – gabe3886
    Aug 12, 2016 at 16:13
  • \$\begingroup\$ The strlen of $a is 351, but you are only picking a random character out of the first $x (26) characters. You can fix it and keep your probabilities with a change of the final $x to 350 for +1 byte. Here is a 77 byte version that fixes the issue but also brings the probabilities much closer together: for($i=65;$i<91;$a.=str_repeat(chr($i),$i++));echo substr($a,rand(0,2014),1); \$\endgroup\$
    – Jo.
    Nov 30, 2017 at 6:11
3
\$\begingroup\$

Julia, 24 bytes

!c='a':c|>rand;c()=!!'z'

Try it online!

How it works

The function c() simply calls ! twice, with initial argument z. In turn !c creates a character range from a to its argument c and pseudo-randomly selects a character from this range. The distribution of probabilities is as follows.

Let x1, …, x26 denote the letters of the alphabet in their natural order. Select a letter Y among these, uniformly at random, then select a letter X from L1, … Y, also uniformly at random.

Fix n and k in 1, …, 26.

If n ≤ k, then p(X = xn | Y = xk) = 1/k. On the other hand, if n > k, then p(X = xn | Y = xk) = 0.

Therefore, p(X = xn) = Σ p(Y = xk) * p(X = xn | Y = xk) = 1/26 · (1/n + ⋯ + 1/26), giving the following probability distribution.

p(X = a) = 103187226801/696049754400 ≈ 0.148247
p(X = b) =  76416082401/696049754400 ≈ 0.109785
p(X = c) =  63030510201/696049754400 ≈ 0.090555
p(X = d) =  54106795401/696049754400 ≈ 0.077734
p(X = e) =  47414009301/696049754400 ≈ 0.068119
p(X = f) =  42059780421/696049754400 ≈ 0.060426
p(X = g) =  37597923021/696049754400 ≈ 0.054016
p(X = h) =  33773473821/696049754400 ≈ 0.048522
p(X = i) =  30427080771/696049754400 ≈ 0.043714
p(X = j) =  27452509171/696049754400 ≈ 0.039440
p(X = k) =  24775394731/696049754400 ≈ 0.035594
p(X = l) =  22341654331/696049754400 ≈ 0.032098
p(X = m) =  20110725631/696049754400 ≈ 0.028893
p(X = n) =  18051406831/696049754400 ≈ 0.025934
p(X = o) =  16139182231/696049754400 ≈ 0.023187
p(X = p) =  14354439271/696049754400 ≈ 0.020623
p(X = q) =  12681242746/696049754400 ≈ 0.018219
p(X = r) =  11106469546/696049754400 ≈ 0.015956
p(X = s) =   9619183746/696049754400 ≈ 0.013820
p(X = t) =   8210176146/696049754400 ≈ 0.011795
p(X = u) =   6871618926/696049754400 ≈ 0.009872
p(X = v) =   5596802526/696049754400 ≈ 0.008041
p(X = w) =   4379932326/696049754400 ≈ 0.006293
p(X = x) =   3215969526/696049754400 ≈ 0.004620
p(X = y) =   2100505176/696049754400 ≈ 0.003018
p(X = z) =   1029659400/696049754400 ≈ 0.001479
\$\endgroup\$
2
\$\begingroup\$

J, 20 18 bytes

({~?@#)u:64+#~1+i.26
({~?@#)u:64+#~i.27

Online interpreter

Uppercase.

Each letter's probability is its 1-based index in the alphabet.

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

zsh, 63 bytes

for i in {A..Z};for j in {1..$[#i]};s+=$i;echo $s[RANDOM%$#s+1]

it works by creating this string:

AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ

aka 65 times A, 66 times B, 67 times C...

and then it chooses a random character in it

\$\endgroup\$
2
  • \$\begingroup\$ Why'd you start at 65? \$\endgroup\$
    – gcampbell
    Aug 12, 2016 at 17:01
  • 1
    \$\begingroup\$ @gcampbell 65 is A in ascii. you can start from 1, but then the inner loop becomes {65..$[#i]} which is 1 char longer \$\endgroup\$
    – izabera
    Aug 12, 2016 at 19:09
2
\$\begingroup\$

CJam, 11 bytes

4.mrmqC*'A+

or

676.mrmq'A+

Try it online!

This solution is similar to Luis's idea and creates a non-uniform distribution by taking the square root of the random variable.

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

Batch, 116 bytes

@set/ar=%random%%%676,s=r/26,r%%=26,s-=(r-s)*(r-s^>^>31)
@set a=ABCDEFGHIJKLMNOPQRSTUVWXYZ
@call echo %%a:~%s%,1%%

Works by picking the larger or smaller (I forget which) of two random variables.

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

Matlab, 22

Will often return early letters, but can theoretically touch them all!

Takes one devided by a random number, limits this to 26 and turns it in to a character.

['' 96+min(1/rand,26)]

Not very short of course, but perhaps the concept can inspire other answers.

\$\endgroup\$
4
  • \$\begingroup\$ Does rand return a value in [0, 1)? That is, including zero but not including one. If this occasionally results in 1/0, will min(1/0,26) still return 26, or an error? \$\endgroup\$ Aug 13, 2016 at 11:40
  • \$\begingroup\$ As far as I know rand returns a value in (0,1), so there shouldn't be a problem \$\endgroup\$ Aug 17, 2016 at 13:39
  • 1
    \$\begingroup\$ @trichoplax Even though you won't see rand return 0 in practice, min(1/0,26) actually returns 26. \$\endgroup\$ Aug 17, 2016 at 13:45
  • \$\begingroup\$ In that case, nice solution :) \$\endgroup\$ Aug 17, 2016 at 14:13

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.