title: Swap indices and values

text:
# Question
Title: Swap indices and values
# The task

Write a program or function whose input is a list/array *X* of integers, and whose output is a list of sets of integers *Y*, such that for each element *e* in each set *Y*\[*i*\], *X*\[*e*\] = *i*, and such that the total number of elements in the sets in *Y* equals the number of elements in *X*.

(This is basically the same operation as reversing a hashtable/dictionary, except applied to arrays instead.)

# Examples

These examples assume 1-based indexing, but you can use 0-based indexing instead if you prefer.

```
X             Y
[4]           [{},{},{},{1}]
[1,2,3]       [{1},{2},{3}]
[2,2,2]       [{},{1,2,3}]
[5,5,6,6]     [{},{},{},{},{1,2},{3,4}]
[6,6,5,5]     [{},{},{},{},{3,4},{1,2}]

```

# Clarifications

* You may represent a set as a list, if you wish. If you do so, the order of its elements does not matter, but you may not repeat elements.
* You can use any reasonable unambiguous I/O format; for example, you could separate elements of a set with spaces, and the sets themselves with newlines.
* *Y* should be finitely long, and at least long enough to have all elements of *X* as array indexes. It may, however, be longer than the maximal element of *X* (the extra elements would be empty sets).
* The elements of *X* will all be valid array indices, i.e. non-negative integers if you use 0-based indexing, or positive integers if you use 1-based indexing.

# Victory condition

As a challenge, shorter is better.

# Answer
> 10 votes
# MATL, 8 bytes

```
tn:IXQ&D

```

Input is a column vector, with `;` as separator (for example `[2;2;2]`). Output is the string representation of a cell array of row vectors (for example `{[]; [1 2 3]}`). A row vector of a single element is the same as a number (so `{1; 2; 3}` would be output instead of `{[1]; [2]; [3]}`).

Try it online! Or verify all test cases.

### Explanation

```
t     % Implicit input, say x. Duplicate
n     % Number of elements, say N
:     % Range: [1 2 ... N]
IXQ   % accumarray(x, [1 2 ... N], [], @(x){sort(x).'})
&D    % String representation

```

Most of the work is done by Matlab's higher-order function `accumarray`, which groups elements in the second input according to matching values in the first, and applies a specified function to each group. The function in this case is `@(x){sort(x).'}`, which outputs the sorted elements in each group and causes the results for all groups to be packed in a cell array.

# Answer
> 7 votes
# Python, 69 bytes

```
lambda s:[[j for j,x in enumerate(s)if x==i]for i in range(max(s)+1)]

```

Uses 0-based indexing.

# Answer
> 7 votes
# Jelly, ~~7~~ 5 bytes

```
=þṀT€

```

Try it online!

### How it works

```
=þṀT€  Main link. Argument: A (array)

  Ṁ    Yield m, the maximum of A.
=þ     Equals table; for each t in [1, ..., m], compare all elemnts of A with t,
       yielding a 2D Boolean array.
   T€  Truth each; for each Boolean array, yield all indices of 1.

```

# Answer
> 5 votes
# Jelly, 8 bytes

```
Jẋ"Ṭ€;"/

```

Try it online!

## How it works

```
Jẋ"Ṭ€;"/  argument: z           eg. [6,6,4,4]
J         [1 .. len(z)]             [1,2,3,4]
   Ṭ€     untruth each of z         [[0,0,0,0,0,1],
                                     [0,0,0,0,0,1],
                                     [0,0,0,1],
                                     [0,0,0,1]]
 ẋ"       repeat each of ^^         [[[],[],[],[],[],[1]],
          as many times as           [[],[],[],[],[],[2]],
          each of ^                  [[],[],[],[3]],
                                     [[],[],[],[4]]]
       /  reduce by...
     ;"   vectorized concatenation  [[],[],[],[3,4],[],[1,2]]

```

# Answer
> 4 votes
## Mathematica, 36 bytes

```
Join@@@#~Position~n~Table~{n,Max@#}&

```

## Explanation

For each `n` in `{1, 2, ..., Max@#}`, where `Max@#` is the largest integer in the input list, computes the `Position`s where `n` appears in the input list `#`. Since `Position[{6,6,5,5},5]` (for example) returns `{{3},{4}}`, we then `Apply` `Join` to all elements at level `{1}` of the result.

# Answer
> 3 votes
# Haskell, 45 bytes

`s` takes a list of integers and returns a list of lists. 1-indexed to keep the test case inputs unmodified (although the output gets some extra empty lists).

```
s l=[[i|(i,y)<-zip[1..]l,y==x]|x<-[1..sum l]]

```

Try it online!

These are pretty straightforward nested list comprehensions. The only slight tweak is taking advantage of the option to make a longer list by using `sum` instead of `maximum`.

# Answer
> 3 votes
# PHP, 55 bytes

```
<?while($i<=max($_GET))print_r(array_keys($_GET,$i++));

```

0-indexed.

# Answer
> 3 votes
# R, ~~68~~ ~~49~~ 47 bytes

```
lapply(1:max(x<-scan()),function(y)which(y==x))

```

Surprisingly, a lot more straightforward than the longer solutions. Takes a vector `x` from STDIN, creates a vector from `1` to `max(x)`, implicitly generates a list of length `max(x)`, and checks which indices in `x` correspond with those in the new list. Implicitly prints output.

## Older version:

```
o=vector('list',max(x<-scan()));for(i in x)o[[i]]=c(o[[i]],F<-F+1);o

```

Slightly different approach to the other R answer. Takes a vector to STDIN, creates a list with length equal to the maximum value in the input. Loops over the input and adds the index into the right place.

Uses 1-based indexing.

# Answer
> 2 votes
# Python 2, ~~91~~ ~~86~~ 85 bytes

I am programming on my phone but I really liked this challenge. I can most definitely golf this further.

```
def f(a):
 r=[[]for i in range(max(a)+1)]
 for i,j in enumerate(a):r[j]+=[i]
 print r

```

Try it online!

# Answer
> 2 votes
# Jelly, 9 bytes

```
Ṭ+\ịĠȧ@"Ṭ

```

1-indexed, empty sets represented as `0`, sets of one item represented as `N` sets of multiple items represented as `[M,N,...]`

**Try it online!**

### How?

```
Ṭ+\ịĠȧ@"Ṭ - Main link: list a        e.g. [6,6,4,4]
Ṭ         - untruth a                     [0,0,0,1,0,1]
  \       - cumulative reduce with:
 +        -   addition                    [0,0,0,1,1,2]
    Ġ     - group indices of a by value   [[3,4],[1,2]]
   ị      - index into                    [[1,2],[1,2],[1,2],[3,4],[3,4],[1,2]]
        Ṭ - untruth a                     [0,0,0,1,0,1]
       "  - zip with:
     ȧ@   -   and with reversed @rguments [0,0,0,[3,4],0,[1,2]]

```

# Answer
> 2 votes
## JavaScript (ES6), ~~64~~ 62 bytes

*Saved 2 bytes thanks to @SteveBennett*

---

Takes 0-indexed input. Returns a comma-separated list of sets.

```
a=>a.map((n,i)=>o[n]=[i,...o[n]||[]],o=[])&&`{${o.join`},{`}}`

```

### Test cases

```
let f =

a=>a.map((n,i)=>o[n]=[i,...o[n]||[]],o=[])&&`{${o.join`},{`}}`

console.log(f([3]))
console.log(f([0,1,2]))
console.log(f([1,1,1]))
console.log(f([4,4,5,5]))
console.log(f([5,5,4,4]))
```

---

### Alternate version, 53 bytes

If a simplified output such as `'||||3,2|1,0'` is acceptable, we can just do:

```
a=>a.map((n,i)=>o[n]=[i,...o[n]||[]],o=[])&&o.join`|`

```

# Answer
> 1 votes
## Mathematica 62 bytes

```
(Y={}~Table~Max@#;Y[[#[[j]]]]~AppendTo~j~Table~{j,Tr[1^#]};Y)&

```

I'll run it for you

```
(Y={}~Table~Max@#;Y[[#[[j]]]]~AppendTo~j~Table~{j,Tr[1^#]};Y)&[{4,5,2,3,3,8,6,3}]

```

> {{}, {3}, {4, 5, 8}, {1}, {2}, {7}, {}, {6}}

**Try it online** (just paste the code with ctrl-v and press shift+enter)
don't forget to paste the input list at the end like in the example above

# Answer
> 1 votes
# Bash, 109 bytes

Too bad there is no built-in for array max value.

```
a=($@)
for((x=m=1;x<=m;x++)){ for((y=0;y<$#;)){((m<a[y]))&&((m=a[y]));((a[y++]==x))&&printf "%d " $y;};echo;}

```

Try it online!

# Answer
> 1 votes
# R, ~~80~~ 72 bytes

1-indexed, takes `X` from stdin. Returns a list of vectors of the indices, with `NULL` as the empty set.

```
X=scan();Y=vector('list',max(X));Y[X]=lapply(X,function(x)which(X==x));Y

```

Try it online!

old version:

```
X=scan();Y=vector('list',max(X));for(i in 1:length(X))Y[[X[i]]]=c(Y[[X[i]]],i);Y

```

Try it online!

# Answer
> 1 votes
# Perl 6,  ~~36 32~~  29 bytes

```
->\a{map {a.grep(*==$_):k},1..a.max}

```

Try it

```
{map {.grep(*==$^a):k},1.. .max}

```

Try it

```
{map {.grep($^a):k},1.. .max}

```

Try it

---

## Expanded:

```
{  # bare block lambda with implicit parameter ｢$_｣

  map

    {  # bare block lambda with placeholder parameter ｢$a｣

      .grep(  # grep for the values in ｢$_｣
        $^a   # that are equal to the currently tested value (and declare param)
      ) :k    # return the key (index) rather than the value
    },

    1 .. .max # Range from 1 to the maximum value in ｢$_｣

}

```

---

Returns zero based indexes, to get 1 based use cross operator (`X`) combined with `+` op. (33 bytes)

```
{1 X+.grep($^a):k}

```

To get it to return Sets just add `set` in there (total 37 bytes)

```
{set 1 X+.grep($^a):k}

```

# Answer
> 1 votes
# Röda, 51 bytes

```
f s{seq(1,max(s))|[[s()|enum|[_2+1]if[_1=i]]]for i}

```

It's a port of the Python answer by Uriel.

Another version (88 bytes):

```
f a{I=indexOf;seq(1,max(a))|{|i|b=a[:]c=[]x=1{c+=x+I(i,b)b-=i;x++}until[I(i,b)<0];[c]}_}

```

Try it online!

Both a 1-indexed.

# Answer
> 1 votes
## PowerShell, 81 bytes

```
$args[0]|%{if($_-gt($c=$r.count)){$r+=@($t)*($_-$c)}$r[--$_]+=,++$i};$r|%{"{$_}"}

```

Try it online!

1-indexed.

# Answer
> 1 votes
# GNU Make, ~~214~~ ~~213~~ ~~208~~ 204 bytes

```
X=$(MAKECMDGOALS)
M=0
P=$(eval N=$(word $1,$X))$(if $N,$(if $(shell dc -e$Nd$Mds.\>.p),$(eval M=$N),)$(eval A$N+=$1$(call $0,$(shell expr $1 + 1))),)
$(call P,1)$(foreach K,$(shell seq $M),$(info $(A$K)))

```

I/O: input array via arguments, output to stdout, one per line, separated by spaces.

```
$ make -f swap.mk 2 2 2

3 2 1
make: *** No rule to make target `2'.  Stop.

```

## Explanation

```
X=$(MAKECMDGOALS)     # Input array
M=0                   # Max value encountered in X
P=$(eval
    N=$(word $1,$X))  # Get next word from X
  $(if $N,$(if $(shell dc -e$Nd$Mds.\>.p),
    $(eval M=$N),)    # Update M
    $(eval A$N+=$1    # Append index to a variable named after value
      $(call $0,      # Recurse (call returns empty string)
        $(shell expr $1 + 1))),)
$(call P,1)           # Initial call to P. 1 is the first index
$(foreach K,          # Print all values of A* variables
  $(shell seq $M),
  $(info $(A$K)))     # Uninitialized ones default to empty strings

```

The order of indices in sets is reversed because `P` calls itself recursively before updating `A$2` (call executed in the evaluation of the right-hand side).

# Answer
> 1 votes
# 05AB1E, 10 bytes

```
ZFā¹N-Ïˆ}¯

```

Try it online!

# Answer
> 1 votes
# Common Lisp, 91 bytes

```
(lambda(x &aux(l(make-list(eval`(max,@x))))(i 0))(dolist(y x l)(push(incf i)(nth(1- y)l))))

```

1-based indexing, returns the sets as lists.

Try it online!

# Answer
> 1 votes
# , 13 bytes

```
{(=x)@!1+|/x}

```

This is 0-indexed.

Try it online!

```
{           } /function(x)
 (=x)         /make a map/dictionary of values to their indices
         |/x  /get maximum value in x
      !1+     /make a range from 0 to the value, inclusive
     @        /get map value at each of the values in the range
              /    0N is given where there is no result

```

# Answer
> 1 votes
# Uiua, 6 bytes

```
⊕□∶⇡⧻.

```

Try it!

0-indexed.

```
⊕□∶⇡⧻.
     .  # duplicate
    ⧻   # length
   ⇡    # range
  ∶     # swap
⊕□      # group by box

```

# Answer
> 1 votes
# Japt, 7 bytes

Output is 0-based.

```
rÔõ@ð¶X

```

Try it

# Answer
> 0 votes
# Vyxal, 38 bitsv2, 4.75 bytes

```
Gǒ=vT

```

Try it Online!

Bitstring:

```
01011011100001100011111110111100010001

```

Exact same algorithm as Jelly, independently discovered.

## Explained

```
Gǒ=vT
 ǒ     # Reduce pairs in the cartesian product of
# the input
G      # and the maximum of the input
  =    # by equality
# This creates a list of [1s in places where input == x for x in range(max(input))]
   vT  # Get the indices of those 1s for each list

```

Created with the help of Luminespire.

# Answer
> 0 votes
# JavaScript (Node.js), 73 bytes

```
x=>x.map((n,i)=>A[(g=n=>n&&g(n-1,A[n]=A[n]||[]))(n),n].push(i),A=[[]])&&A

```

Try it online!

---
Tags: code-golf, array, sorting
---


# Question
Title: Random Golf of the Day #7: A distinctly random character
## 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.)*

# Answer
> 19 votes
# 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.

# Answer
> 24 votes
# 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.

# Answer
> 22 votes
# 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!.

# Answer
> 19 votes
# 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).

# Answer
> 14 votes
# 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))

```

# Answer
> 14 votes
# 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: ***************************************************************************

```

# Answer
> 11 votes
## 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.

# Answer
> 10 votes
# 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

# Answer
> 9 votes
# 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
       )

```

# Answer
> 9 votes
## \>\<\>, 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

```

# Answer
> 8 votes
# 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!*

# Answer
> 8 votes
# 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.

# Answer
> 6 votes
# 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">,@

```

# Answer
> 5 votes
## 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 `65`s, 66 `66`s, 67 `67`s, 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 `-f`ormat 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 %

```

# Answer
> 5 votes
# 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

```

# Answer
> 5 votes
# 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

```

# Answer
> 4 votes
## 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

# Answer
> 4 votes
## 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).

# Answer
> 4 votes
# 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)

# Answer
> 3 votes
# 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.

# Answer
> 3 votes
# 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%

# Answer
> 3 votes
# 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>
```

# Answer
> 3 votes
# 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

```

# Answer
> 3 votes
# 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.

# Answer
> 3 votes
# 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

```

# Answer
> 2 votes
# 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.

# Answer
> 2 votes
# 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

# Answer
> 2 votes
## 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.

# Answer
> 2 votes
## 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.

# Answer
> 2 votes
# 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.

# Answer
> 2 votes
# C#, ~~68~~ 66 bytes

Thanks to Leaky Nun for fixing the chance distribution.

```
var r=new Random();char f(char c='A')=>c<'Z'&r.Next(3)>0?f(++c):c;

```

Surprisingly short for a C# answer.

It defines a function `f` that returns a random character between the given one and `Z`. It has a 1/3 chance of returning the current character, otherwise it recurses on the next. If the current character is `Z`, it always returns. Default parameter is `A`, so calling it without any argument satisfies the challenge.

The resulting chances follow `2^(n-1) / 3^n`:

```
A: 1/3
B: 2/9
C: 4/27
D: 8/81
...
Y: 16777216/847288609443
Z: 67108864/2541865828329

```

# Answer
> 2 votes
## CJam, 10 bytes

CJam approach #3...

```
26mr)mr'A+

```

Try it online!

This creates a uniformly random number `x` between 1 and 26 and then uses that to create a uniformly random number between `0` and `x-1` which is added to `A`. This biases results towards smaller characters.

# Answer
> 2 votes
# Mathematica, 34 bytes

```
RandomChoice[Range@26->Alphabet[]]

```

`RandomChoice[wlist -> elist]` gives a random choice of `elist` weighted by `wlist`.

# Answer
> 2 votes
# Ruby, 42 bytes

```
$><<(?A..?Z).flat_map{|c|[c]*c.ord}.sample

```

Quite straightforward: Generate 65 `A`'s; 66 `B`'s; ... 90 `Z`'s, and randomly pick one of the letters generated.

# Answer
> 2 votes
# x86\_64 machine language for Linux, ~~15 19 17~~ 16 bytes

```
L1:
48 0f c7 f0             rdrand %rax
f3 48 0f b8 c0          popcnt %rax,%rax
3c 1a                   cmp    $0x1a,%al
7d f3                   jge    L1
04 41                   add    $0x41,%al
c3                      retq

```

This requires support for the POPCNT and RDRAND instructions.

A uniform distributed random number is generated, the number of 1's in that number is counted, if that number is less than 26, a letter is returned. One will need to let the code run a long time before one sees a letter A.

To test, try something like

```
#include<stdio.h>
#define TEST "\x48\xf\xc7\xf0\xf3\x48\xf\xb8\xc0\x3c\x1a\x7d\xf3\4\x41\xc3"
int main(){
  int hist[26]={0};
  for(int i=0;i<10000000;i++){
    hist[ ((int(*)())TEST)() - 'A' ]++;
  }
  for(int i=0;i<26;i++){
    printf("%c %d\n", 'A'+i, hist[i] );
  }
}

```

Sample output

```
A 0
B 0
C 0
D 0
E 0
F 0
G 0
H 0
I 0
J 0
K 0
L 8
M 32
N 137
O 511
P 1639
Q 5188
R 14475
S 37539
T 91670
U 205638
V 431381
W 842259
X 1536776
Y 2626524
Z 4206223

```

The analytical expression for the probability of each letter can be derived from the binomial distribution. The letter A is assigned index k=0, B is assigned k=1 and so on.

```
        /  \
       | 64 |
       | k  |
        \  /
p(k)=------------
      25
      --- /  \
      \  | 64 |
      /  | i  |
      --- \  /
      i=0

 p(A)~1.0483e-18
 p(B)~6.7093e-17
 p(C)~2.1134e-15
 p(D)~4.3678e-14
 p(E)~6.6608e-13
 p(F)~7.9930e-12
 p(G)~7.8598e-11
 p(H)~6.5124e-10
 p(I)~4.6401e-09
 p(J)~2.8872e-08
 p(K)~1.5879e-07
 p(L)~7.7953e-07
 p(M)~3.4429e-06
 p(N)~1.3772e-05
 p(O)~5.0169e-05
 p(P)~1.6723e-04
 p(Q)~5.1214e-04
 p(R)~1.4460e-03
 p(S)~3.7758e-03
 p(T)~9.1413e-03
 p(U)~2.0568e-02
 p(V)~4.3095e-02
 p(W)~8.4231e-02
 p(X)~1.5381e-01
 p(Y)~2.6276e-01
 p(Z)~4.2042e-01

```

# Answer
> 2 votes
# LaTeX, ~~122~~ 115 bytes

*-7 bytes by replacing `pgfmathparse{Hex(...)}` with `pgfmathHex{...}`.*

Or, if I'm allowed to skip the document class definition & setup, and just count the package import and functional code: **65 bytes**.

`pgfmathHex` parses the expression and its (hexadecimal) result is then fed into `\char` which turns the code point into a unicode character. The expression itself is identical to many other answers here.

```
\documentclass{book}\usepackage{tikz}\begin{document}\pgfmathHex{65+sqrt(rnd)*26}\char"\pgfmathresult\char"\pgfmathresult\end{document}

```

Ungolfed (with cherry-picked for loop for page-filling output):

```
\documentclass{book}
\usepackage{tikz}
\begin{document}
\noindent
\foreach \n in {0,...,1513}
{
\pgfmathHex{65+sqrt(rnd)*26}\char"\pgfmathresult
}
\end{document}

```

Output (w/ free page number :) ):

# Answer
> 2 votes
## Matlab, ~~24~~ 18 bytes

~~`char(floor(26*rand^2+65))`~~

it looks like using `floor(x)` isn't necessary as `char` also takes non-integer inputs

```
char(25*rand^2+65)

```

not using `['' x]` instead of `char(x)` so I won't get *warning: implicit conversion from numeric to char* for "purer" output.

`rand` yields a uniformly distributed random number in the interval `(0,1)` but `rand^2` isn't uniformy distributed anymore, the probability density function follows , see here.

with `(b-a)*rand+a` one can shift the interval of the distribution from `(0,1)` to `(a,b)`, this also works with `rand^2`.

~~because i use `floor` i need to stretch the interval to `(65,91)` so i don't lose "Z"~~

It might no be the shortest answer but i like the approach with using a uniform random distribution to get a non-uniform random distribution.

Below is the count for each generated numbers after 20000 iterations (using my first version of my answer).

# Answer
> 2 votes
# MATL, 12 bytes

```
1Y2toY"tnYr)

```

Try it online!

Explanation

```
1Y2          % Pushes the alphabet A...Z
   to        % Make a numeric copy [65 ... 90]
     Y"      % Run length decoding: 65 A's, 66 B's, etc. Let's call this [S]
        nYr  % Random number between 1 and length of [S], let's call this [i]
       t   ) % Index into a copy of [S] at the [i]'th position. Implicit display.

```

The selection from `[S]` is according to a uniform distribution, but since each letter in the alphabet occurs a distinct number of times in `[S]`, the resulting distribution is also distinct for each letter in the alphabet.

# Answer
> 2 votes
# SmileBASIC, ~~26~~ 22 bytes

I think it's unfair that most of these are biased towards earlier letters.

Here's one that prints `Z` the most:

```
?CHR$(90-RND(RND(27)))

```

# Answer
> 2 votes
# 05AB1E, 4 bytes

```
AƶJΩ

```

Try it online! Beats all other answers.

```
AƶJΩ  # full program
   Ω  # random character from...
  J   # joined...
A     # "abcdefghijklmnopqrstuvwxyz"...
 ƶ    # with each character repeated 1-indexed index of character in string times
      # implicit output

```

`AƶJ` generates the string `'abbcccddddeeeeeffffffggggggghhhhhhhhiiiiiiiiijjjjjjjjjjkkkkkkkkkkkllllllllllllmmmmmmmmmmmmmnnnnnnnnnnnnnnoooooooooooooooppppppppppppppppqqqqqqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrsssssssssssssssssssttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuvvvvvvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyzzzzzzzzzzzzzzzzzzzzzzzzzz'`, so the chances are as follows:

```
a: 0.285%
b: 0.57%
c: 0.855%
d: 1.14%
e: 1.425%
f: 1.709%
g: 1.994%
h: 2.279%
i: 2.564%
j: 2.849%
k: 3.134%
l: 3.419%
m: 3.704%
n: 3.989%
o: 4.274%
p: 4.558%
q: 4.843%
r: 5.128%
s: 5.413%
t: 5.698%
u: 5.983%
v: 6.268%
w: 6.553%
x: 6.838%
y: 7.123%
z: 7.407%

```

# Alternative, 4 bytes

```
AηJΩ

```

Try it online!

```
AηJΩ  # full program
   Ω  # random character from...
  J   # joined...
 η    # prefixes of...
A     # "abcdefghijklmnopqrstuvwxyz"
      # implicit output

```

`AηJ` generates the string `'aababcabcdabcdeabcdefabcdefgabcdefghabcdefghiabcdefghijabcdefghijkabcdefghijklabcdefghijklmabcdefghijklmnabcdefghijklmnoabcdefghijklmnopabcdefghijklmnopqabcdefghijklmnopqrabcdefghijklmnopqrsabcdefghijklmnopqrstabcdefghijklmnopqrstuabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvwabcdefghijklmnopqrstuvwxabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyz'`, so the chances are as follows:

```
a: 7.407%
b: 7.123%
c: 6.838%
d: 6.553%
e: 6.268%
f: 5.983%
g: 5.698%
h: 5.413%
i: 5.128%
j: 4.843%
k: 4.558%
l: 4.274%
m: 3.989%
n: 3.704%
o: 3.419%
p: 3.134%
q: 2.849%
r: 2.564%
s: 2.279%
t: 1.994%
u: 1.709%
v: 1.425%
w: 1.14%
x: 0.855%
y: 0.57%
z: 0.285%

```

# Answer
> 2 votes
# Zsh, 26 bytes

```
eval shuf -en1 {{a..z}..z}

```

Try it online! Includes a basic frequency analysis.

Explanation:

* `{a..z}` \- construct the string `a b ... z`
* `{{a..z}..z}` \- construct the string `{a..z} {b..z} ... {z..z}`
* `eval`uate that string - executes `shuf -en1 a b ... z b c ... z c d ... z ... y z z`
* `shuf -en1` \- picks one of those letters at random. In the pool, `z` is repeated 26 times, `y` 25 times, etc., which creates the distinct probabilities.

# Answer
> 2 votes
# Vyxal, 5 bytes

```
ka¦∑℅

```

Try it Online!

same idea as the Pyth answer.

# Answer
> 2 votes
# Phooey, 26 bytes

```
~?675@(&>@+1@<--@@^)>+63$c

```

Try it online!

The demo contains a simple infinite loop which resets the tape (this program expects a clean tape and doesn't clean up lul)

Similar to a lot of other answers, this generates a number from \\$0-675\\$ and uses *roughly* \\$\lfloor \sqrt{n}\rfloor\\$ to select the letter with varying probability.

Unfortunately, AFAICT, there is no way of doing a square root automatically since the pow operator uses integers. Maybe there is a fixed point method, but idk yet.

However, the naïve subtraction method works and is *probably* shorter than any other solution. It's only going to be running a few iterations, so the inefficiency isn't *that* bad.

```
int64_t isqrt(int64_t n)
{
    int64_t d = 0;
    while (n >= 0) {
        n -= d;
        d += 1;
        n -= d;
    }
    return d - 1;
}

```

My implementation actually has an off-by-one problem with my loop condition check. I use \\$x^x\\$ (`@^`) instead of \\$2^x\\$ (`@&2^`) which is the "proper" (at least, in Phooey) way to check for negatives, and when \\$x = -1\\$, it will report a false negative (or is it a false positive? ), as \\${-1}^{-1} = {-1}, {-1} \ne 0\\$.

HOWEVER, that doesn't affect the output's randomness. It just means that Z will appear once instead of A and we need \\$d - 2\\$ instead of \\$d - 1\\$.

With all values from \\$0-675\\$ tested, this is the frequency:

```
A 3   B 5
C 7   D 9
E 11  F 13
G 15  H 17
I 19  J 21
K 23  L 25
M 27  N 29
O 31  P 33
Q 35  R 37
S 39  T 41
U 43  V 45
W 47  X 49
Y 51  Z 1

```

How it works:

```
~?675@(&>@+1@<--@@^)>+63$c
~?675                       # Generate a random integer between 0 and 675 inclusive
     @                      # Push the initial n to the stack
                            # Begin our naïve semi-sqrt loop
      (            )        # while n >= 0
       &                    #    Pop n from the stack
        >                   #    Move left to d
         @                  #    Push d
          +1                #    Increment d
            @               #    Push d + 1
             <              #    Move back to n
              --            #    Subtract d and d + 1, popping them
                            #    Use a modified method I found in my Brexit post to check for < 0
                @           #    Save a copy of n
                 @^         #    Calculate n^n using double<->int64 conversion
                            #    The current cell will contain zero if n < -1, or nonzero otherwise.
                            #    Use that as our loop condition.
                    >       # Move to d
                     +63    # d += 'A' - 2
                        $c  # print as char

```

# Answer
> 1 votes
# Clojure, 61 bytes

```
#(char(- 90(count(take-while(fn[a](<(rand)0.5))(range 26)))))

```

Takes each successive element from the range of 26 elements with probability `1/2`. So the chance that one element is taken is `1/2`, 2 elements - `1/4` and so on. After that subtract from 90 number of elements taken and turn it into char.

`p(Z) = 1/2, p(Y) = 1/4, p(X) = 1/8 ... p(A) = 1/2^(26)`

See it online: https://ideone.com/Cg15FY

# Answer
> 1 votes
# Julia, 33 bytes

```
f()=['A':'Z'][ceil(26*√rand())]

```

Applies the square root to RNG.

Graph showing distribution:  Generated with:

```
using Gadfly
plot(x=ceil(26*√rand(10000)),Geom.histogram)

```

# Answer
> 1 votes
# ForceLang, 64 bytes

Noncompeting, uses language features (the `string.char` method) that postdate the question.

```
set s math.sqrt 676.mult random.rand()
io.write string.char 65+s

```

# Answer
> 1 votes
## Actually, 7 bytes

```
ú#;╚♀MJ

```

Try it online!

This answer uses the same approach as Dennis's Jelly answer.

Explanation:

```
ú#;╚♀MJ
ú#       lowercase English alphabet, as a list (this is to dodge a bug with the shuffle command)
  ;╚     duplicate, shuffle
    ♀M   pairwise maximum
      J  random element

```

# Answer
> 1 votes
## perl, 21 bytes

```
say+(A..Z)[rand$$%27]

```

Needs `-M5.010` or `-E` to run :

```
perl -E 'say+(A..Z)[rand$$%27]'

```

**How it works** : (A..Z) is an array. $$ is process ID, which introduces some randomness. $$%27 is a number between 0 and 26 (inclusive, and roughly evenly spread). Calling rand on that produces a number between 0 and 26 (inclusive at 0, exclusive at 26), but biased towards smaller numbers. We then use that number for an array lookup, which we print.

**Opportunities for improvement** :

$$ is random, but not cleanly random. We know that the chance of getting particular numbers differs, but not by much, and not in ways that are easy to predict cleanly. Therefore, the possibility of getting different each letter is probably not identical, but it's very close. If (and only if) we accept that probability{ $$%26 == x } is different for all x, then we could replace "rand$$%27" with "$$%26".

Alternately, we could replace "rand$$%27" with (for example) "26\*sin$$", and save one character. This gives a much less regular spread than simply "$$%26":

```
 perl -E 'for(1..32768){say+(A..Z)[26*sin$_]}' | sort | uniq -c
    832 A
   3269 B
   1648 C
   1360 D
   1183 E
   1133 F
   1043 G
   1071 H
    959 I
    978 J
    985 K
    939 L
    926 M
    950 N
    924 O
    939 P
    985 Q
    977 R
    959 S
   1072 T
   1043 U
   1135 V
   1182 W
   1360 X
   1647 Y
   3269 Z

```

But if you check, you'll see that it's not perfect. There are three pairs of numbers that have the same probability as each other: K&Q, I&S, L&P.

(If you use actual PIDs, then depending on what processes are actually running, and depending on the highest allowable pid on your machine, you might get more clashes, or less.)

"15\*sin$$" works better, only 2 clashes - but that is still 2 clashes. (Any number between 13 and 26 will work, in the sense of producing all 26 letters, because sin(x) spans -1 to +1 and perl treats negative number array look-ups as starting from the array end).

There might be some way of getting all 26 numbers, with different probabilities, using less (or no more) than the 8 characters that "rand$$%27" needs. But if so, it isn't coming to me.

# Answer
> 1 votes
# Dyalog APL, 14 bytes

See this meta post for information about the code page.

```
(?351)⊃⎕A/⍨⍳26

```

Gives instant results. Works by selecting an evenly distributed random character among "ABBCCCDDDD..."

`(?351)` RandInt(1,351)
picks among
`⎕A` "ABC...Z"
`/⍨` element-by-element replicated
`⍳26` {1, 2, 3, ..., 26} times

TryAPL online!

# Answer
> 1 votes
# Clojure, 62 bytes

```
(loop[i 65](if(or(> i 89)(neg?(rand)))(char i)(recur(inc i))))

```

This is somewhat stupid shortcut. The probability of exact zero double - the only (rand) to not break on condition (pos? x) - is around 1/(2^62) \[source\].

So chance for letter char(65+N) is around (1/(2^62))^N, slightly higher for Z (because it is last).

With (rand-int 2) - 6 more bytes - it becomes testable.

# Answer
> 1 votes
# Perl 6, 30 bytes

```
{('a'..'z'Zxx 1..*).flat.pick}

```

## Explanation:

```
# bare block lambda
{
  (

    'a' .. 'z' # the alphabet
    Z[xx]      # zipped ｢Z｣ using the list repeat operator ｢xx｣
    1 .. *     # with 1 to 26

    # ((a)(b b)(c c c)(d d d d)(e e e e e)...

  )
  .flat # flatten it from a list of lists into a single list
  .pick # pick an element from the list
}

```

# Answer
> 1 votes
# Lua, ~~100~~ 99 bytes

```
s="A"math.randomseed(os.time())for i=66,90 do
s=.6<math.random()and string.char(i)or s end
print(s)

```

Not really competitive, but still an interesting algorithm I think.

# Answer
> 1 votes
## Pip, 8 bytes

```
(zr*r*h)

```

`z` is a built-in for the lowercase alphabet, `h` for `100`. `r` is a special variable: each time it is evaluated, it generates a random number with uniform distribution, `0 <= r < 1`. Thus, `r*r*h` squares the uniform distribution and scales it a hundredfold (saving a character over using `26`). The result is used to index into `z`, auto-truncated and with index wrapping.

Try it here (frequency chart of 100,000 runs, takes about 30 seconds).

# Answer
> 1 votes
# IA-32 machine code, 12 bytes

Hexdump:

```
0F C7 F0 F6 E4 88 E0 D4 1A 04 61 C3

```

Source code:

```
rdrand eax
mul ah
mov al, ah
aam 26
add al, 'a'
ret

```

Or, as a C expression (assuming `r` is a uniformly generated random number of type `uint32_t`):

```
(r & 0xff) * ((r >> 8) & 0xff) / 0x100 % 26 + 'a'

```

Running this expression on values in the range 0...65535 gives the probabilities of the letters:

```
z 1968
y 2012
x 2068
w 2076
v 2134
u 2140
t 2194
s 2209
r 2233
q 2292
p 2335
o 2358
n 2410
m 2437
l 2475
k 2545
j 2571
i 2654
h 2696
g 2738
f 2818
e 2922
d 2955
c 3098
b 3241
a 3957

```

# Answer
> 1 votes
# Javascript, ~~93~~ 91 bytes

Yes there is a shorter one, but that does it differently. Also I spent half an hour on this so I'm not giving up.

```
q=>'abcdefghijklmnopqrstuvwxyz'.split``.map((i,k)=>i.repeat(k)).join``[Math.random()*351|0]

```

Explained:

```
q=> // define function, meaningless arg saves a byte
'abcdefghijklmnopqrstuvwxyz'.split`` // get each alphabet character in array
.map((i,k)=>i.repeat(k)) //replace each with it repeated index times
.join``[Math.random()*351|0] //turn to string and get random character.

```

Probability:

```
a - 1/351
b - 2/351
c - 3/351

```

Etcetera.

Note: according to this comment, I don't have to use a function declaration if it isn't recursive.

# Answer
> 1 votes
# MathGolf, 6 bytes

```
▄mÅî*w

```

Try it online.

**Explanation:**

```
▄       # Push the lowercase alphabet
 m      # Map over each letter
  Å     # using the following two characters as inner code-block:
   î    #  Push the 1-based map-index
    *   #  Repeat the current character that many times
     w  # After the map: pop and push a random character from this string
        # (after which the entire stack joined together is output implicitly as result)

```

Same probability as most other answers:

* a: \\$\frac{1}{351}\\$
* b: \\$\frac{2}{351}\\$
* ...
* y: \\$\frac{25}{351}\\$
* z: \\$\frac{26}{351}\\$

# Answer
> 0 votes
# Python 3, 58 bytes

```
from random import*;print(chr(randint(65,randint(65,91))))

```

it is like that perl answer.

# Answer
> 0 votes
# k4, 15 bytes

```
*1?a|-26?a:.Q.A

```

A port of *@Dennis's* Jelly answer.

# Answer
> 0 votes
# JavaScript ES6, 42 Bytes, modified from user81655's solution:

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

```

# Answer
> 0 votes
## Javascript, 49 bytes

```
f=()=>String.fromCharCode(65+Math.random()**2*26)

```

# Answer
> 0 votes
# Thunno 2, 4 bytes

```
ẠƒJɼ

```

Attempt This Online!

This takes the prefixes of the lowercase alphabet, joins them, and takes a random character from this string. This means that the probabilities are as follows:

* `a`: \\$26/351\\$
* `b`: \\$25/351\\$
* \\$...\\$
* `y`: \\$2/351\\$
* `z`: \\$1/351\\$

```
Ạ     # Push the lowercase alphabet      ->  "abcdefghijklmnopqrstuvwxyz"
 ƒ    # Get the prefixes of this string  ->  ["a","ab",...,"abcdefghijklmnopqrstuvwxyz"]
  J   # Join them into a single string   ->  "aababc...abcdefghijklmnopqrstuvwxyz"
   ɼ  # Take a random character from this string
      # Implicit output

```

# Answer
> 0 votes
# Lua, 69 bytes

```
math.randomseed(os.time())print(('').char(math.random(727)^.5//1+64))

```

Try it online!

---
Tags: code-golf, string, random
---


# Question
Title: Generate all square sub-matrices of a given size
You will be given a square matrix of integers **M** and another positive integer **n**, strictly smaller than the size of **M**. Your task is to generate all square sub-matrices of **M** of size **n**.

For the purposes of this challenge, a *square sub-matrix* is a group of **adjacent** rows and columns contained in **M**.

## Input / Output Formats

You are free to choose any other reasonable formats, these are just some examples.

**Input**

* A matrix in the native matrix type (if your language has one)
* A 2D array (an array of 1D arrays, each corresponding to one row / one column)
* A 1D array (since the matrix is always square)
* A string (you chose the spacing, but please do not abuse this in any way), etc.

**Output**

* A matrix of matrices.
* A 4D array, where each element (3D list) represents the sub-matrices on a row/column.
* A 3D array, where each element (2D list) represents a sub-matrix.
* A string representation of the resulting sub-matrices, etc.

## Specs

* You may choose to take the *size* of **M** as input too. It is guaranteed to be at least **2**.
* The orientation of the output is arbitrary: you may choose to output the sub-matrices as lists of columns or lists of rows, but your choice must be consistent.
* You can compete in any programming language and can take input and provide output through any standard method, while taking note that these loopholes are forbidden by default.
* This is , so the shortest submission (in bytes) for *every language* wins.

## Example

Given **n = 3** and **M**:

```
 1  2  3  4
 5  6  7  8
 9 10 11 12
13 14 15 16

```

The possible **3x3** submatrices are:

```
+-------+        +--------+     1  2  3  4         1  2  3  4
|1  2  3| 4     1| 2  3 4 |     +--------+         +--------+
|5  6  7| 8     5| 6  7 8 |     |5   6  7|8       5| 6  7  8|
|9 10 11|12     9|10 11 12|     |9  10 11|12      9|10 11 12|
+-------+        +--------+     |13 14 15|16     13|14 15 16|
13 14 15 16     13 14 15 16     +--------+         +--------+

```

So the result would be:

```
[[[1, 2, 3], [5, 6, 7], [9, 10, 11]], [[2, 3, 4], [6, 7, 8], [10, 11, 12]], [[5, 6, 7], [9, 10, 11], [13, 14, 15]], [[6, 7, 8], [10, 11, 12], [14, 15, 16]]]

```

As noted above, an output of:

```
[[[1, 5, 9], [2, 6, 10], [3, 7, 11]], [[2, 6, 10], [3, 7, 11], [4, 8, 12]], [[5, 9, 13], [6, 10, 14], [7, 11, 15]], [[6, 10, 14], [7, 11, 15], [8, 12, 16]]]

```

would also be acceptable, if you choose to return the sub-matrices as lists of rows instead.

## Test cases

The inputs **M, n**:

```
[[1,2,3],[5,6,7],[9,10,11]], 1
[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], 3
[[100,-3,4,6],[12,11,14,8],[0,0,9,3],[34,289,-18,3]], 2
[[100,-3,4,6],[12,11,14,8],[9,10,11,12],[13,14,15,16]], 3

```

And the corresponding outputs (sub-matrices given as lists of rows):

```
[[[1]],[[2]],[[3]],[[5]],[[6]],[[7]],[[9]],[[10]],[[11]]]
[[[1,2,3],[5,6,7],[9,10,11]],[[2,3,4],[6,7,8],[10,11,12]],[[5,6,7],[9,10,11],[13,14,15]],[[6,7,8],[10,11,12],[14,15,16]]]
[[[100,-3],[12,11]],[[-3,4],[11,14]],[[4,6],[14,8]],[[12,11],[0,0]],[[11,14],[0,9]],[[14,8],[9,3]],[[0,0],[34,289]],[[0,9],[289,-18]],[[9,3],[-18,3]]]
[[[100,-3,4],[12,11,14],[9,10,11]],[[-3,4,6],[11,14,8],[10,11,12]],[[12,11,14],[9,10,11],[13,14,15]],[[11,14,8],[10,11,12],[14,15,16]]]

```

Or, as lists of columns:

```
[[[1]],[[2]],[[3]],[[5]],[[6]],[[7]],[[9]],[[10]],[[11]]]
[[[1,5,9],[2,6,10],[3,7,11]],[[2,6,10],[3,7,11],[4,8,12]],[[5,9,13],[6,10,14],[7,11,15]],[[6,10,14],[7,11,15],[8,12,16]]]
[[[100,12],[-3,11]],[[-3,11],[4,14]],[[4,14],[6,8]],[[12,0],[11,0]],[[11,0],[14,9]],[[14,9],[8,3]],[[0,34],[0,289]],[[0,289],[9,-18]],[[9,-18],[3,3]]]
[[[100,12,9],[-3,11,10],[4,14,11]],[[-3,11,10],[4,14,11],[6,8,12]],[[12,9,13],[11,10,14],[14,11,15]],[[11,10,14],[14,11,15],[8,12,16]]]]

```

# Answer
> 6 votes
# 05AB1E, 8 bytes

```
2FεŒsù}ø

```

Try it online!

**Explanation**

```
2F            # 2 times do:
  ε    }      # apply to each element in the input matrix (initially rows)
   Œsù        # get a list of sublists of size input_2
        ø     # transpose (handling columns on the second pass of the loop)

```

# Answer
> 5 votes
# MATL, 4 bytes

```
thYC

```

Inputs are `n`, then `M`.

The output is a matrix, where each column contains all the columns of a submatrix.

Try it online!

### Explanation

```
thY    % Address the compiler with a formal, slightly old-fashioned determiner
C      % Convert input to ouput

```

More seriously, `t` takes input **n** implictly and duplicates it on the stack. `h` concatenates both copies of **n**, producing the array **\[n, n\]**. `YC` takes input **M** implicitly, extracts all its **\[n, n\]**-size blocks, and arranges them as columns in column-major order. This means that the columns of each block are stacked vertically to form a single column.

# Answer
> 4 votes
# APL (Dyalog Unicode), 26 bytesSBCS

Anonymous infix lambda taking **n** as left argument and **M** as right argument.

```
{s↓(-s←2⍴⌈¯1+⍺÷2)↓⊢⌺⍺ ⍺⊢⍵}

```

Try it online!

`{``}` anonymous lambda where  is the left argument and  is the right argument:

`⊢⍵` yield the right argument ( separates `⍺ ⍺` from )

`⊢⌺⍺ ⍺` all -by- submatrices including those overlapping the edges (those are padded with zeros)

`(``)↓` drop the following number elements along the first two dimensions:

`⍺÷2` half of

`¯1+` negative one plus that

round up

`2⍴` cyclically **r**eshape to a list of two elements

`s←` store in `s` (for **s**hards)

`-` negate (i.e. drop from the rear)

`s↓` drop `s` elements along the first and second dimensions (from the front)

# Answer
> 4 votes
# APL (Dyalog Unicode), 31 bytes

```
{(1↓2 1 3 4⍉⊖)⍣(4×⌊⍺÷2)⊢⌺⍺ ⍺⊢⍵}

```

Try it online!

A different approach than Adám's.

# Answer
> 4 votes
# , 75 bytes

```
function(M,N,S,W=1:N,g=N:S-N)for(i in g)for(j in g)print(M[i+W,j+W,drop=F])

```

Try it online!

Takes `M`, `N`, and the `S`ize of the matrix.

Prints the resultant matrices to stdout; `drop=F` is needed so the in the `N=1` case the indexing doesn't drop the `dim` attribute and yields a `matrix` rather than a `vector`.

# Answer
> 3 votes
# , 11 8 bytes

-3 bytes thanks to miles

```
<;._3~,~

```

Try it online!

# Answer
> 2 votes
# Haskell, 67 bytes

```
m#n|r<-[0..length m-n]=[take n.drop x<$>take n(drop y m)|x<-r,y<-r]

```

Try it online!

# Answer
> 2 votes
# Jelly, 5 bytes

```
Z⁹Ƥ⁺€

```

Uses the 4D output format. For 3D, append a  for **6 bytes**.

Try it online!

### How it works

```
Z⁹Ƥ⁺€  Main link. Left argument: M (matrix). Right argument: n (integer)

 ⁹Ƥ    Apply the link to the left to all infixes of length n.
Z        Zip the rows of the infix, transposing rows and columns.
   ⁺€  Map Z⁹Ƥ over all results.

```

# Answer
> 2 votes
# Brachylog, 13 bytes

```
{tN&s₎\;Ns₎}ᶠ

```

Try it online!

This returns lists of columns.

Technically, `tN&s₎\;Ns₎` is a generating predicate which unifies its output with any of those submatrices. We use `{…}ᶠ` only to expose all possibilities.

### Explanation

```
 tN&              Call the second argument of the input N
{          }ᶠ     Find all:
    s₎              A substring of the matrix of size N
      \             Transpose that substring
       ;Ns₎         A substring of that transposed substring of size N

```

# Answer
> 2 votes
# APL (Dyalog Classic), ~~24~~ 23 bytes

```
t∘↑¨(¯1-t←-2⍴⎕)↓,⍀⍪\⍪¨⎕

```

Try it online!

the result is a matrix of matrices, though Dyalog's output formatting doesn't make that very obvious

input the matrix (), turn each element into a nested matrix of its own (`⍪¨`), take prefix concatenations by row (`,\`) and by column (`⍪⍀`), input n (), drop the first n-1 rows and columns of nested matrices (`(¯1-t←-2⍴⎕)↓`), take the bottom right n-by-n corner from each matrix (`t∘↑¨`)

```
                                        ┌─┬──┬───┐
                                        │a│ab│abc│      ┼──┼───┤        ┼──┼───┤
 n=2       ┌─┬─┬─┐      ┌─┬──┬───┐      ├─┼──┼───┤      │ab│abc│        │ab│ bc│
┌───┐      │a│b│c│      │a│ab│bac│      │a│ab│abc│      │de│def│        │de│ ef│
│abc│  ⍪¨  ├─┼─┼─┤  ,\  ├─┼──┼───┤  ⍪⍀  │d│de│def│ 1 1↓ ┼──┼───┤¯2 ¯2∘↑¨┼──┼───┤
│def│ ---> │d│e│f│ ---> │d│de│edf│ ---> ├─┼──┼───┤ ---> │ab│abc│  --->  │  │   │
│ghi│      ├─┼─┼─┤      ├─┼──┼───┤      │a│ab│abc│      │de│def│        │de│ ef│
└───┘      │g│h│i│      │g│gh│hgi│      │d│de│def│      │gh│ghi│        │gh│ hi│
           └─┴─┴─┘      └─┴──┴───┘      │g│gh│ghi│      ┴──┴───┘        ┴──┴───┘
                                        └─┴──┴───┘

```

# Answer
> 1 votes
# Stax, 10 bytes

```
│Æ☼♂Mqß E╖

```

Run it

The ascii representation of the same program is

```
YBFMyBF|PMmJ

```

It works like this.

```
Y               Store the number in the y register
 B              Batch the grid into y rows each
  F             Foreach batch, run the rest of the program
   M            Transpose about the diagonal
    yB          Batch the transposed slices into y rows each
      F         Foreach batch, run the rest of the progoram
       |P       Print a blank line
         M      Transpose inner slice - restoring its original orientation
          mJ    For each row in the inner grid, output joined by spaces

```

# Answer
> 1 votes
# JavaScript (ES6), 91 bytes

Takes input in currying syntax `(a)(n)`. Returns the results as lists of rows.

```
a=>n=>(g=x=>a[y+n-1]?[a.slice(y,y+n).map(r=>r.slice(x,x+n)),...g(a[x+n]?x+1:!++y)]:[])(y=0)

```

### Test cases

```
let f =

a=>n=>(g=x=>a[y+n-1]?[a.slice(y,y+n).map(r=>r.slice(x,x+n)),...g(a[x+n]?x+1:!++y)]:[])(y=0)

;[
  [ [[1,2,3],[5,6,7],[9,10,11]], 1 ],
  [ [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], 3 ],
  [ [[100,-3,4,6],[12,11,14,8],[0,0,9,3],[34,289,-18,3]], 2 ],
  [ [[100,-3,4,6],[12,11,14,8],[9,10,11,12],[13,14,15,16]], 3]
]
.forEach(([m, a]) => console.log(JSON.stringify(f(m)(a))))
```

# Answer
> 1 votes
# Husk, 8 bytes

```
TmoTmX¹X

```

Try it online! This function takes **n** and **M** and returns a matrix of matrices.

# Answer
> 0 votes
# Ruby, 63 bytes

```
->c,g{n=c.size-g+1
(0...n*n).map{|i|c[i/n,g].map{|z|z[i%n,g]}}}

```

Try it online!

This is a lambda taking a 2D array and an int, returning a 3D array.

Ungolfed:

```
->m,n{
  a = m.size - n + 1     # The count of rows in m that can be a first row in a submatrix
  (0...a*a).map{ |b|     # There will be a*a submatrices
    m[b/a,n].map{ |r|    # Take each possible set of n rows
      r[b%a,n]           # And each possible set of n columns
    }
  }
}

```

# Answer
> 0 votes
# Python 2, 91 bytes

```
lambda a,n:(lambda R:[[r[i:i+n]for r in a[j:j+n]]for i in R for j in R])(range(len(a)+1-n))

```

Try it online!

# Answer
> 0 votes
# Uiua, 3 bytes

```
◫⊟.

```

Try it!

```
◫⊟.
  .  # duplicate
 ⊟   # couple
◫    # windows

```

---
Tags: code-golf, array, matrix
---


title: Yet another digit insertion problem

text:
# Question
Title: Yet another digit insertion problem
Given a positive number \\$n\\$ we call **another** (not same as n) positive number \\$m\\$ good if we insert same digits in both n and m and the resulting fractional value is same.

$$m/n = m\_{\text{transformed}}/n\_{\text{transformed}}$$ $$or$$ $$m\*n\_{\text{transformed}} = m\_{\text{transformed}}\*n$$

Clarifications:

* No leading zeros or trailing zero insertion is allowed (you can insert 0 at beginning or end, but this must not be the last digit added in that end),other than this you can insert any digit(same digit and same number of time in both) at any place,i.e you need not insert at same place in n and m.
* At least one insertion is required.

Examples :

Example 1: $$n= 12$$

here m=66 is a good number ,we can obtain it by inserting 1 in m and n such that they become 616 and 112.

Example 2:

$$n=30$$

here m=60 is a good number, we can get 300 and 600 by inserting 0 in **middle**, as mentioned we cannot insert 0 at end or beginning, but here we inserted it in middle.

Example 3:

$$n=4$$ here 7 is a good number, as we can insert 2 and 1 , making them 124 and 217 respectively, now the fractional value is same.

Example 4:

$$n=11$$ here 2 is a good number, as we can insert 2 and 2 , making them 1221 and 222 respectively, now the fractional value is same.

Example 5:

$$n=4269$$ here 1423 is a good number, as we can insert 0, making them 42069 and 14023 respectively, now the fractional value is same.

Example 6:

$$n=1331$$ here 242 is a good number, as we can insert 2 and 2, making them 123321 and 22422 respectively, now the fractional value is same.

**Task:**

You have to find out smallest good number for a given n (there always exists a good number as pointed out by a user in comments).

This is , so the shortest answer in bytes per language wins.

# Answer
> 3 votes
# Haskell, 154 bytes

```
g n=head[m|m<-[1..n*10],m/=n,w<-i m,v<-i n,w*n==v*m]
i m=[read$take n s++c:drop n s|let s=show m,let l=length s,n<-[0..l],c<-"123456789"++['0'|n/=0,n/=l]]

```

Try it online!

# Answer
> 0 votes
# JavaScript, 8 bytes

```
n=>-~n/n

```

Try it online!

Takes \\$n\\$ as a BigInt. Returns 1 for \\$n \ne 1\\$, 2 for \\$n=1\\$: 1 is good with every other number.

For example, 1 is good with 2 as follows:

```
105263157894736842**1** * 2 =
**2**105263157894736842
```

This can be constructed by starting with the digit 1 at the top right, and doing the multiplication by 2 while copying each digit of the product up and to the left, until it finishes by arriving at a 2 with no carry.

This always works. Let \\$x\\$ be the number formed by the inserted digits, and \\$l\\$ be the number of inserted digits. Then we need \\$(10x + 1)\*n = n\*10^l + x\\$, which rearranges to \\$(10n - 1)\*x = n\*10^l - 1\\$. This always has suitable integer solutions: by Euler's theorem, \\$l = \varphi(10n - 1) + 1\\$ works.

However, this inserts an ending zero (which is not allowed) when \\$n\\$ has an ending zero. A solution is to ignore all ending zeroes of \\$n\\$, then put them back at the end; for example, for \\$n=200\\$:

```
  105263157894736842**1** * 200 =
**2**105263157894736842**00**
```

Here's a function that does the full calculation, returning \\$\[m, n\_\mathrm{transformed}, m\_\mathrm{transformed}\]\\$:

**JavaScript, 86 bytes**

```
d=(n,N=n,y=T=10n,m=-~n/n,k=m*N*T,a=y/--k+y)=>N%T?y%k>1?d(n,N,y*T):[m,a*n,a*m]:d(n,N/T)

```

Try it online!

---
Tags: code-golf, math
---


# Question
Title: Determine if a Spider Solitaire game is stale
Let's introduce a simplified variant of the well known Spider Solitaire.

From Wikipedia:

> The main purpose of the game is to remove all cards from the table, assembling them in the tableau before removing them. Initially, 54 cards are dealt to the tableau in ten piles, face down except for the top cards. The tableau piles build down by rank, and in-suit sequences can be moved together. The 50 remaining cards can be dealt to the tableau ten at a time when none of the piles are empty. A typical Spider layout requires the use of two decks. The Tableau consists of 10 stacks, with 6 cards in the first 4 stacks, with the 6th card face up, and 5 cards in the remaining 6 stacks, with the 5th card face up. Each time the stock is used it deals out one card to each stack.

For the purpose of this challenge, you will receive a standard Spider Solitaire tableau with only a single suit and no extra stock, where you know the rank of all the cards, including the ones that normally could have been covered.

The task is to determine if a tableau is stale, i.e. the game can not be won/cleared from this position. This may happen because there are no moves, or there are moves, but they lead to repeating positions and do not ultimately end up with the whole rank sequence being taken off the board.

## Examples

The following tableau is stale (0 - king, 1 - queen, 2 - jack, etc..., all down to the ace):

```
3 9 5 3 9 10
1 2 10 12 8 4
10 5 5 4 5
11 1 3 0 1 2
0 6 2 10 10 11 12
1 5 6 4 4 5
3 6 9 3 8
4 8
2 3 8 9 10
6 5 1 5 1 2

```

Not stale:

```
0 1 2
3 4
11
9
5
10
12
8
6
7

```

Not stale either:

```
0 1 2
3 4
11 11
0 9 12
5 10
1 10 9
12 5
2 8 8
6 7
3 4 7 6

```

## Scoring criterion

Code size in bytes in a particular language.

# Answer
> 3 votes
# Jelly, 112 bytes

```
Iœr€1Ẉ‘rẈżị¥";@€"JȦƇẎW;ⱮṪẹ@¥ɗ€0ịⱮa‘$€Ɗ}Ẏɗ;pṆ€Tḣ1Ʋ}¥ɗị@œṖ@©ƭƒ@ḢWɗ1ị$}¦;€Fɼị@Wʋṛ¦ƭƒ€µœṣ13R¤F))Ṣ€
W©;Ç€ẎQ$ḟɗɼ$ÐLẸ€Ạ

```

Try it online!

A pair of links which are called monastically using a list of lists of integers as the starting tableau. Expects cards to be numbered from 1 (King) to 13 (Ace). Returns 1 if the tableau is stale and 0 if non-stale. Times out on TIO for more complex tableaux. This has taken a rather long time to get to this point but I will post an detailed explanation in due course. Removing the `Ṣ€` at the end of the first link should also work and saves two bytes, but it times out on even simpler examples like the one in the TIO link.

## Top-level explanation

1. Start with a list of current tableaux (on first iteration will be a single one).
2. For each tableau:
    * Work out which runs there are at the end of stacks.
    * Work out which of those runs can be moved to the end of another stack.
    * Also add the possibility of moving any run (including single cards) into the first empty stack.
    * Create new tableaux based on all of the moves identified above
3. Join the new tableaux created in step 2 into a single list
4. Remove any complete suits (from 1 to 13)
5. Filter out any we’ve seen before
6. Append to the list of all possibilities
7. Stop when this list is unchanged (i.e. no new possible tableaux were generated); otherwise feed the new tableaux back into step 1.
8. Determine whether all of the possible tableaux are non-empty

---
Tags: code-golf, decision-problem, card-games
---


title: Literate Programming in Base 26

text:
# Question
Title: Literate Programming in Base 26
Your task is to convert non-empty strings - between strings using the 26 letters, and programs, which are strings of bytes, where each byte has 256 possible values. You should use the same codepage your answer is written in for the possible values of bytes.

You need to do the following to do the conversion:

* Convert the letters to numbers `1-26`.
* Treat it as a base 26 bijective numeration number to convert it to a positive integer.
* Convert it to base 256 using `1-256`, again using bijective numeration.
* Turn it to bytes, where `i` turns to the byte with value `i-1`.

For example, for the string `hello`, you start with converting it to `[8, 5, 12, 12, 15]`, then you evaluate \\$15 + 12\cdot26 + 12\cdot26^2 + 5\cdot26^3 + 8\cdot26^4 = 3752127\\$. Then you convert \\$3752127 = 191 + 64\cdot256 + 57\cdot256^2\\$, so the answer is `[56, 63, 190]`.

**However**, you dislike gibberish. You want your code to be a concatenation of English words. You can't do that directly in your code, so instead you'll do that in its base26 representation.

## Rules

* Your code, when converted to base 26 using bijective numeration, has to be a concatenation of English words from this wordlist, with 1 or 2 letter words removed, except for `a, i, of, to, in, is, on, by, it, or, be, at, as, an, we, us, if, my, do, no, he, up, so, pm, am, me, go, ok, hi`.
* You can choose whether you want your input to have lowercase or uppercase letters, but it has to be consistent.
* Your input has to be a string, an array of characters or an array of bytes - you can't take an array of numbers from `1` to `26`, for example.
* Your output has to be a string, an array of characters, an array of bytes, or an array of numbers from `0` to `255`.
* Standard loopholes are disallowed.
* If your language uses a base which isn't 256 then use that base, as long as it isn't a power of 26. If it is that language can't compete.

## Test cases

```
input string -> array of bytes
hi -> [216]
iw -> [0, 0]
sr -> [0, 255]
cat -> [7, 25]
crxq -> [255, 0]
cshl -> [255, 255]
cshm -> [0, 0, 0]
hello -> [56, 63, 190]
helloworld -> [39, 138, 176, 111, 2, 107]
apple -> [10, 110, 12]
loremipsumdolorsitamet -> [81, 108, 15, 236, 169, 234, 61, 72, 24, 166, 102, 147, 49]

```

## Scoring

Your score is the length of your program, encoded in base 26. This is , so the shortest answer in each language wins.

# Answer
> 7 votes
# Jelly, score 23

The bijective base \\$26\\$ program as words:

```
yrs seo dts i am a be in cpu sap

```

The Jelly code:

```
ÑÞ²¶O_96ḅ26ḃ⁹’

```

**Try it online!**

Raw bytes as integers \\$\[1,256\]\\$:

```
[17, 21, 131, 128, 80, 96, 58, 55, 213, 51, 55, 232, 138, 254]

```

Converted from base \\$256\\$:

```
346505452333233856289746614520574

```

Converted to bijective base 26:

```
[25, 18, 19, 19, 5, 15, 4, 20, 19, 9, 1, 13, 1, 2, 5, 9, 14, 3, 16, 21, 19, 1, 16]

```

As characters, and then with spaces added to show the dictionary words used:

```
yrsseodtsiamabeincpusap
yrs seo dts i am a be in cpu sap

```

See this process starting with the Jelly code.

### How?

The first part, up to the  is filler to ensure we get a valid intermediate string, the  is equivalent to a newline and separates Links, and execution of Jelly programs start at the final Link. Since the final Link (`O_96ḅ26ḃ⁹’`) is not calling the previous one (`ÑÞ²`) and the full program parses without error, the final Link is called with an input of the input string as a list of characters:

```
O_96ḅ26ḃ⁹’ - Link: list of characters
O          - ordinals
 _96       - subtract 96 from each
    ḅ26    - convert from base 26
       ḃ⁹  - convert to bijective base 256
         ’ - decrement each

```

---

I also tried these suffixes (some will only work with upper case input):

```
¶O%32ḅ26ḃ⁹’
¶O%48ḅ26ḃ⁹’
¶O%64ḅ26ḃ⁹’
¶O_64ḅ26ḃ⁹’
¶Oạ64ḅ26ḃ⁹’
¶Oạ96ḅ26ḃ⁹’

```

There are many more that could be tried (like using unused code-page entires like `q` to create a new Link, or making a single Link that has some sort of no-op at the start etc.), so there may be terser out there.

---
Tags: code-golf, string, restricted-source, base-conversion
---