答:
Matlab, 37 bytes

Quite simple:

Uses the builtin intersect to find the intersection. The source code is hard coded. Input must be given inside quotation marks ''

```<code>intersect(input(''),'''intersc(pu),')
</code>```

Title: Input ∩ Source Code

Body:
Intro

The challenge is to create a program/function that prints the intersection of its own source code and a given string input. This is code golf and to be more precise:

Let I be the input set

{"a","b","c"}

Let S be the source code set

{"b","f"}

Then the intersection is what they share

I ∩ S = {"b"}

Input

Input is flexible. It should be able to handle the character encoding used for the source code.

Output

Output is flexible. It should be the set of characters that the input and source code share. Also, sets are unordered collections of distinct objects. In summary:

Output is flexible:

Could be any data structure (string or otherwise)

Could unordered

Could have a trailing \n

Should be distinct

Restriction

Similar to quine challenges, the program/function may not read its own source code and 0-byte solutions are not allowed.

Examples

#1

```<code>functor x(I){ return I ∩ self; }

Inputs                                Outputs
------                                -------
enter preformatted text here      ->  {"e","n","t","r","f","o","x"}

["Albrt"," Einstin"]              ->  {"l","r","t","n","s"}
</code>```

#2

```<code>(_)->_&"(_)->&\"\\"

Inputs                                Outputs
------                                -------
"Security at the expense of       ->  "
usability comes at the expense
of security."

(0____0)                          ->  (_)
</code>```

#3

```<code>ಠa益длф

Inputs                                Outputs
------                                -------
Far out in the uncharted backwaters ->"a"
of the unfashionable end of the
Western Spiral arm of the Galaxy lies
a small unregarded yellow sun.
Orbiting this at a distance of roughly
ninety-eight million miles is an
utterly insignificant little blue-green
planet whose ape-descended life forms
are so amazingly primitive that they
still think digital watches are a pretty
neat idea.

(ノಠ益ಠ)ノ彡┻━┻                      ->"ಠ益"
</code>```

Test Cases

```<code>Albert Einstein

\__( O__O)_/

!@#$%^&*()_+{}|:"<>?

1234567890-=[]\;',./

(ノಠ益ಠ)ノ彡┻━┻

“¤>%,oỊȤʠ“ØụĊ5D³ṃṠɼQ»j;Ç;“;}¶”

┬──┬ ノ( ゜-゜ノ)

Far out in the uncharted backwaters of the unfashionable end of the Western Spiral arm of the Galaxy lies a small unregarded yellow sun. Orbiting this at a distance of roughly ninety-eight million miles is an utterly insignificant little blue-green planet whose ape-descended life forms are so amazingly primitive that they still think digital watches are a pretty neat idea.
</code>```

Update

[16-08-10]: sets are unordered collections of distinct objects

[16-08-10]: trailing newline is acceptable

Body:
Matlab, 37 bytes

Quite simple:

Uses the builtin intersect to find the intersection. The source code is hard coded. Input must be given inside quotation marks ''

intersect(input(''),'''intersc(pu),')


问:
Render "Digital Clock Style" Numbers
Write the shortest program which will take a string of numbers (of up to at least 20 length) as input, and display the output using the standard digital clock style numbers.  For instance for input 81, a solution with ascii output would give:

```<code> _
|_|  |
|_|  |
</code>```

Graphical output is also acceptable, if it helps.

ContentLicense: CC BY-SA 2.5

Title: Render "Digital Clock Style" Numbers

Body:
Perl (182 180)

#!perl -l
$_=<<7;
 _     _  _     _  _  _  _  _
| |  | _| _||_||_ |_   ||_||_|
|_|  ||_  _|  | _||_|  ||_| _|
7
@b=map{[/(...)/g]}split/\n/;@d=split//,<>;for$p(@b){print map$p->[$_],@d}

reads from STDIN.

$ perl 7segment.pl
1234567890987654321
    _  _     _  _  _  _  _  _  _  _  _  _  _     _  _     _
  | _| _||_||_ |_   ||_||_|| ||_||_|  ||_ |_ |_| _| _|  || |
  ||_  _|  | _||_|  ||_| _||_| _||_|  ||_| _|  | _||_   ||_|

ContentLicense: CC BY-SA 3.0


问:
Snakes all around

Challenge

The challenge is simple: print a snake.

You will get the length of the snake as input.

A snake of length 2 looks like this:

```<code>==(:)-
</code>```

A snake of length 7 looks like this:

```<code>=======(:)-
</code>```

In other words, the length of a snake is how many equal signs are before the head.

Usage

Let's say I made a C++ implementation and compiled it to ./getsnake.

I could run it like so:

```<code>$ ./getsnake 10
==========(:)-
</code>```

Clarifications

Standard loopholes are disallowed.

You can get input and output in any acceptable way.

You can assume all inputs given are positive integers.

You may write a function instead of a regular program.

答:
Fourier, 28 bytes

```<code>I(61ai^~i)40a-8a58a32a41a+4a
</code>```

Try it online

Title: Snakes all around

Body:
Fourier, 28 bytes

I(61ai^~i)40a-8a58a32a41a+4a

Try it online


问:
Make a (somewhat) self-referential string
You want to make a string where the (1-indexed) character at index n is n. When n is less than 10, this is easy: "123456789". When n is 12, for example, it becomes impossible, since numbers greater than 9 (in base 10) take up more than one character. We can compromise by dividing the string into two-character substrings: "020406081012". Now the index of the end of each substring n is n.

This can be generalized for any d-digit number. Here's an explanation for the "0991021" part of the string for a three-digit number:

```<code>Index:     ... * 97  98  99*100 101 102*103 ...
               *           *           *
               *---+---+---*---+---+---*---+
Character: ... * 0 | 9 | 9 * 1 | 0 | 2 * 1 | ...
               *---+---+---*---+---+---*---+
</code>```

If you haven't figured it out yet, you are to write a program/function that takes a string or integer and output its self-referential string as specified above. You can also output an array of single-digit numbers, chars, or single-character strings.

The given integer will always be positive and divisible by its length (e.g. 126 is divisible by 3; 4928 is divisible by 4). Your program should theoretically work for an arbitrarily large input, but you can assume it is smaller than your language's maximum integer and/or string length.

Some observations if you still don't get it: The length of the output will always be the input itself, and the numbers that appear in the output will be divisible by the number of digits in the input.

This is code-golf, so shortest answer in bytes wins.

Test cases

```<code>1    => 1
9    => 123456789
10   => 0204060810
105  => 003006009012015018021024027030033036039042045048051054057060063066069072075078081084087090093096099102105
1004 => 00040008001200160020002400280032003600400044004800520056006000640068007200760080008400880092009601000104010801120116012001240128013201360140014401480152015601600164016801720176018001840188019201960200020402080212021602200224022802320236024002440248025202560260026402680272027602800284028802920296030003040308031203160320032403280332033603400344034803520356036003640368037203760380038403880392039604000404040804120416042004240428043204360440044404480452045604600464046804720476048004840488049204960500050405080512051605200524052805320536054005440548055205560560056405680572057605800584058805920596060006040608061206160620062406280632063606400644064806520656066006640668067206760680068406880692069607000704070807120716072007240728073207360740074407480752075607600764076807720776078007840788079207960800080408080812081608200824082808320836084008440848085208560860086408680872087608800884088808920896090009040908091209160920092409280932093609400944094809520956096009640968097209760980098409880992099610001004
</code>```

答:
R, <s>149</s> <s>142</s> 138 bytes

```<code>x=rep(0,n);a=strtoi;b=nchar;for(i in 1:(n=scan()))if(!i%%b(a(n)))x[i:(i-b(a(i))+1)]=strsplit(paste(a(i)),"")[[1]][b(a(i)):1];cat(x,sep="")
</code>```

Leaving nchar in the code gives a program with the same number of bytes than replacing it with b, but having random letters wandering around in the code makes it more... mysterious

Ungolfed :

Each nchar(strtoi(something)) permits to compute the number of numerals in a given number.

```<code>n=scan()   #Takes the integer
x=rep(0,n) #Creates a vector of the length of this integer, full of zeros

for(i in 1:n)
    if(!i%%b(strtoi(n)))         #Divisibility check
        x[i:(i-nchar(as.integer(i))+1)]=strsplit(paste(a(i)),"")[[1]][nchar(as.integer(i)):1];
        #This part replace the zeros from a given position (the index that is divisible) by the numerals of this position, backward.

cat(x,sep="")
</code>```

The strsplit function outputs a list of vectors containing the splitten elements. That's why you have to reach the 1st element of the list, and then the ith element of the vector, writing strsplit[[1]][i]

Body:
R, <s>149</s> <s>142</s> 138 bytes

x=rep(0,n);a=strtoi;b=nchar;for(i in 1:(n=scan()))if(!i%%b(a(n)))x[i:(i-b(a(i))+1)]=strsplit(paste(a(i)),"")[[1]][b(a(i)):1];cat(x,sep="")

Leaving nchar in the code gives a program with the same number of bytes than replacing it with b, but having random letters wandering around in the code makes it more... mysterious

Ungolfed :

Each nchar(strtoi(something)) permits to compute the number of numerals in a given number.

n=scan()   #Takes the integer
x=rep(0,n) #Creates a vector of the length of this integer, full of zeros

for(i in 1:n)
    if(!i%%b(strtoi(n)))         #Divisibility check
        x[i:(i-nchar(as.integer(i))+1)]=strsplit(paste(a(i)),"")[[1]][nchar(as.integer(i)):1];
        #This part replace the zeros from a given position (the index that is divisible) by the numerals of this position, backward.

cat(x,sep="")

The strsplit function outputs a list of vectors containing the splitten elements. That's why you have to reach the 1st element of the list, and then the ith element of the vector, writing strsplit[[1]][i]


问:
ROT-13 transform standard input

Task

Read a string of characters and produce the ROT13 of it. All characters besides [a-zA-Z] should be output verbatim. Each letter in the output may be in any case you wish (you do not have to preserve it).

ROT13 is a simple substitution cipher where each letter of the alphabet is rotated by 13 places (it doesn't matter whether you do it forward or backward, since ROT13 is it's own inverse).

Examples

```<code>Input
Output

Hello, world!
Uryyb, jbeyq!

Code Golf and Coding Challenges is awesome.
Pbqr Tbys naq Pbqvat Punyyratrf vf njrfbzr.

Mod abuse!1!!1
Zbq nohfr!1!!1
</code>```

答:
05AB1E, <s>13</s> 12 bytes

Saved a byte thanks to robbie0630

```<code>ADu)øJD2äRJ‡
</code>```

Try it online!

Explanation

```<code>ADu           # push lower-case and uppercase alphabet
   )øJ        # zip, flatten and join, producing aAbB..zZ
      D2äRJ   # split a copy in 2 pieces, reverse and join producing nNoO..mM
           ‡  # translate input by replacing members of the alphabet
              # with the corresponding member of the rot-13 alphabet
              # implicitly display
</code>```

ContentLicense: CC BY-SA 4.0

Title: ROT-13 transform standard input

Body:
05AB1E, <s>13</s> 12 bytes

Saved a byte thanks to robbie0630

ADu)øJD2äRJ‡

Try it online!

Explanation

ADu           # push lower-case and uppercase alphabet
   )øJ        # zip, flatten and join, producing aAbB..zZ
      D2äRJ   # split a copy in 2 pieces, reverse and join producing nNoO..mM
           ‡  # translate input by replacing members of the alphabet
              # with the corresponding member of the rot-13 alphabet
              # implicitly display


问:
List of possible birth years of living humans
The Challenge

Output a list of years that starts with the current year and ends 120 years ago. The birth year of every living human would be included in this list.

Details

The list should be in descending order.

Every built-in function to manipulate arrays and/or lists is allowed.

Shortest code in bytes wins.

When run this year 2016, the output would be

2016, 2015, ..., 1897, 1896

When run next year 2017, the output would be

2017, 2016, ..., 1898, 1897

Etc.

Update

Some have asked about the format of the list. As most have guessed, it doesn't matter. Insert any separator between the numbers. Intuitively most inserted a comma or space or both, newline or output an array.

Quasi superhumans like Jeanne Calment are an exception to the rule stated in my question.

答:
jq, 46 characters

(45 characters code + 1 character command line option)

```<code>now|strftime("%Y")|tonumber|range(.;.-121;-1)
</code>```

Sample run:

```<code>bash-4.3$ jq -n 'now|strftime("%Y")|tonumber|range(.;.-121;-1)' | head
2016
2015
2014
2013
2012
2011
2010
2009
2008
2007
</code>```

On-line test

Body:
jq, 46 characters

(45 characters code + 1 character command line option)

now|strftime("%Y")|tonumber|range(.;.-121;-1)

Sample run:

bash-4.3$ jq -n 'now|strftime("%Y")|tonumber|range(.;.-121;-1)' | head
2016
2015
2014
2013
2012
2011
2010
2009
2008
2007

On-line test


问:
Sort the months of the year
Write a function or program that takes string inputs, fully-spelled, English month names in title case: January, February, March, etc. (null/CR/LF terminated OK, delimited with some non-alpha character if you so choose) and either

compares two inputs, returning a Truthy value if the second input is greater (in month order) than the first. Equal values result in a Falsey value

or sorts an arbitrary sequence (list, delimited string, etc.) of them in chronological order

(The crux of the challenge is defining a method/expression that gives the correct lexicographical sort. Some languages might have a shorter answer with one or the other)

You cannot use any internal time parsing methods (e.g. strptime) to translate the month name into a number or a pre-canned mapping of month names. Use properties of the strings themselves, a parsimonious look-up table you define, or something clever.

Example

Functioning examples, though the first is prohibited by the rules...

```<code>import datetime
def is_later_month(a, b):
    '''
    Example of prohibited code because it relies on language
    features about how to parse month names
    '''
    return datetime.strptime(a, '%B') < datetime.strptime(b, '%B')
</code>```

The below versions are OK though, because we code that info

```<code>months = {
    'January':  1, 'February':  2, 'March':      3,
    'April':    4, 'May':       5, 'June':       6,
    'July':     7, 'August':    8, 'September':  9,
    'October': 10, 'November': 11, 'December':  12,
}
def is_later_month(a, b):
    """
    Returns True/False when comparing two months.
    """
    return months[a] < months[b]
</code>```

Or you could do a sorting function

```<code>months = {'as above...'}
def sort_months(l):
    """
    Sorts list and returns it. Different input and output than the above,
    but equally valid. Sorting versus comparing might be shorter in your
    favorite language.
    """
    return sorted(l, key=lambda x: months[x])
</code>```

Example tests

```<code>assert is_later_month('January', 'February')
assert is_later_month('January', 'December')
assert is_later_month('November', 'December')
assert not is_later_month('July', 'July')
assert not is_later_month('October', 'September')
</code>```

答:
Haskell, 118 characters

```<code>data M=Ju|Fr|Mc|Ai|My|Je|Jy|Au|St|Oo|Ne|De deriving(Ord,Eq,Read)
r=read.([head,last]<*>).lines.take 4
a#b=(r a::M)<r b
</code>```

Uses the fact that each month name is unique in its first and fourth characters (or 3rd for May) to define a data type that can be automatically parsed and compared by the language.  The 'r' function converts a string by grabbing the first four characters (or fewer), then just picking the first and last.  Then 'a#b' is an operator to compare the values:

```<code>*Main> "June" # "March"
False
*Main> "June" # "July"
True
*Main> "January" # "July"
True
*Main> "January" # "November"
True
*Main> "December" # "November"
False
</code>```

Could probably be done in a more efficient way, but I wanted to try doing it using a useful data type to represent the months.

Title: Sort the months of the year

Body:
Haskell, 118 characters

data M=Ju|Fr|Mc|Ai|My|Je|Jy|Au|St|Oo|Ne|De deriving(Ord,Eq,Read)
r=read.([head,last]<*>).lines.take 4
a#b=(r a::M)<r b

Uses the fact that each month name is unique in its first and fourth characters (or 3rd for May) to define a data type that can be automatically parsed and compared by the language.  The 'r' function converts a string by grabbing the first four characters (or fewer), then just picking the first and last.  Then 'a#b' is an operator to compare the values:

*Main> "June" # "March"
False
*Main> "June" # "July"
True
*Main> "January" # "July"
True
*Main> "January" # "November"
True
*Main> "December" # "November"
False

Could probably be done in a more efficient way, but I wanted to try doing it using a useful data type to represent the months.


问:
Fun with strings and string lengths

Introduction

Inspired by Dyalog Ltd.'s 2016 student competition. The challenge there is to write good APL code, but this is a code-golf and it is open to all languages. Derived from this closed challenge.

The real challenge here is to combine the various (quite trivial) parts of the problem in a byte-efficient way by reusing values and/or algorithms.

If you find this challenge interesting and you use Dyalog APL (free download here), you may also want to participate in the original competition, but note that the objective there is to submit quality code – not necessarily short code. If you are a student, you can win USD 100 for Phase I. Phase II (not related to this code golf challenge) can win you up to USD 2000 and a free trip to Scotland!

Task

Take two strings (of any 7-bit ASCII characters) by any means and order (but please include input format in your answer). You may take them as separate arguments/inputs or as a single list of strings. One string contains the delimiters in the other. E.g. given ',;/' and 'hello,hello;there;my/yes/my/dear,blue,world', the sub-strings are ['hello', 'hello', 'there', 'my', 'yes', 'my', 'dear', 'blue', and 'world'].

You will do some statistics and ordering based on the lengths of those sub-strings that are not duplicated in the input. (You may chose to consider casing or not.) In the example given, those are ['there', 'yes', 'dear', 'blue', 'world'].

Give (by any means) a list of four elements in the overall structure [Number_1, Number_2, [List_3], [[List_4_1], [List_4_2]]]:

The mean of the lengths of the non-duplicated strings. In our example, that is 4.2

The median of the lengths of the non-duplicated strings. In our example, that is 4.

The mode(s) of the lengths of the non-duplicated strings. In our example, that is [4, 5].

The original sub-strings (including duplicates), divided into two lists; the first are those that are not one of the above mode lengths, and the second are those that are. In our example: [['my', 'my', 'yes'], ['dear', 'blue', 'hello', 'hello', 'there', 'world']]

The combined final answer of our example case is: [4.2, 4, [4, 5], [['my', 'my', 'yes'], ['dear', 'blue', 'hello', 'hello', 'there', 'world']]]

Considerations

Don't forget to reuse code and values. E.g. the median is the average of the 1 or 2 middle elements, and you'll need the mode(s) to reorder the original list.

Watch out for division by zero; an empty input means one string with length zero, so the mean length is zero. If there are no non-unique sub-strings, return zero for both mean and median, an empty list for modes, and put all original sub-strings onto the non-mode list.

The list of modes, and the sub-lists of non-mode-length strings, and mode-length strings, do not need to be sorted in any way.

If all non-duplicated sub-strings have different lengths, then all the lengths are considered modes.

Wherever the term list is used, you may use any collection of multiple data pieces that your language supports, e.g. tuples, arrays, dictionaries, etc.

The numeric values only need to be within 1% of the actual value.

Example cases

Example A

',;/' 'hello,hello;there;my/yes/my/dear,blue,world'

gives

[4.2, 4, [4, 5], [['my', 'my', 'yes'], ['dear', 'blue', 'hello', 'hello', 'there', 'world']]

Example B

'+|' ''

gives

[0, 0, [0], [[], ['']]]

Note: while there are two delimiter characters, none of them occur in the data string, so this is just one empty string. Mean, median, and mode are therefore zero There are no strings in the non-mode list and just the single empty string in the mode list.

Example C

'' 'ppcg.se.com'

gives

[11, 11, [11], [[], ['ppcg.se.com']]]

Note: no delimiters, so the entire input is one string.

Example D

',;' ',math,,math;'

gives

[0, 0, [], [['', 'math', '', 'math', ''], []]]

Note: there are three empty sub-strings, and since all sub-strings have at least one duplicate, the mean and median default to zero, as per Considerations, above.

Example E

',;' 'new,math,math;!;'

gives

[1.333, 1, [0,1,3], [['math', 'math'], ['new', '!', '']]]

Note: there is only one of each length among the non-duplicated sub-strings, so all three lengths are modes.

You can verify my explicit permission to post this challenge here by contacting the author of the original competition.

答:
Python 3, 341 chars, 343 bytes

from statistics import*
def f(d,s,l=len):
 w=sorted(''.join(x if not x in d else'ÿ'for x in s).split('ÿ'),key=l)
 L=[l(x)for x in w if w.count(x)<2]
 if L==[]:return 0,0,L,[s,L]
 a,q=mean(L),median(L)
 D={x:L.count(x)for x in L}
 m=[x for x in D if D[x]==max(D.values())]
 i=[l(x)for x in w].index(m[0])
 return a,q,m,[w[:i],w[i:]]
```

As built-ins are not forbidden, using the statistics module is fine for mean and median, but its mode does not allow multiples.

Edit1: check for non-uniqueness

Edit2: shorter list comprehension on m

Edit3: l=len and L==[]

Edit4: for the empty L case, use it instead of []

Edit5: figured empty strings were not handled well, introduced non-7-bit-ASCII sentinel ÿ

Title: Fun with strings and string lengths

Body:
Python 3, 341 chars, 343 bytes

from statistics import*
def f(d,s,l=len):
 w=sorted(''.join(x if not x in d else'ÿ'for x in s).split('ÿ'),key=l)
 L=[l(x)for x in w if w.count(x)<2]
 if L==[]:return 0,0,L,[s,L]
 a,q=mean(L),median(L)
 D={x:L.count(x)for x in L}
 m=[x for x in D if D[x]==max(D.values())]
 i=[l(x)for x in w].index(m[0])
 return a,q,m,[w[:i],w[i:]]

As built-ins are not forbidden, using the statistics module is fine for mean and median, but its mode does not allow multiples.

Edit1: check for non-uniqueness

Edit2: shorter list comprehension on m

Edit3: l=len and L==[]

Edit4: for the empty L case, use it instead of []

Edit5: figured empty strings were not handled well, introduced non-7-bit-ASCII sentinel ÿ


答:
Haskell, 51 bytes

```<code>f n|k<-length$show n=[k,2*k..n]>>=tail.show.(+10^k)
</code>```

Title: Make a (somewhat) self-referential string

Body:
You want to make a string where the (1-indexed) character at index n is n. When n is less than 10, this is easy: "123456789". When n is 12, for example, it becomes impossible, since numbers greater than 9 (in base 10) take up more than one character. We can compromise by dividing the string into two-character substrings: "020406081012". Now the index of the end of each substring n is n.

This can be generalized for any d-digit number. Here's an explanation for the "0991021" part of the string for a three-digit number:

```<code>Index:     ... * 97  98  99*100 101 102*103 ...
               *           *           *
               *---+---+---*---+---+---*---+
Character: ... * 0 | 9 | 9 * 1 | 0 | 2 * 1 | ...
               *---+---+---*---+---+---*---+
</code>```

If you haven't figured it out yet, you are to write a program/function that takes a string or integer and output its self-referential string as specified above. You can also output an array of single-digit numbers, chars, or single-character strings.

The given integer will always be positive and divisible by its length (e.g. 126 is divisible by 3; 4928 is divisible by 4). Your program should theoretically work for an arbitrarily large input, but you can assume it is smaller than your language's maximum integer and/or string length.

Some observations if you still don't get it: The length of the output will always be the input itself, and the numbers that appear in the output will be divisible by the number of digits in the input.

This is code-golf, so shortest answer in bytes wins.

Test cases

```<code>1    => 1
9    => 123456789
10   => 0204060810
105  => 003006009012015018021024027030033036039042045048051054057060063066069072075078081084087090093096099102105
1004 => 00040008001200160020002400280032003600400044004800520056006000640068007200760080008400880092009601000104010801120116012001240128013201360140014401480152015601600164016801720176018001840188019201960200020402080212021602200224022802320236024002440248025202560260026402680272027602800284028802920296030003040308031203160320032403280332033603400344034803520356036003640368037203760380038403880392039604000404040804120416042004240428043204360440044404480452045604600464046804720476048004840488049204960500050405080512051605200524052805320536054005440548055205560560056405680572057605800584058805920596060006040608061206160620062406280632063606400644064806520656066006640668067206760680068406880692069607000704070807120716072007240728073207360740074407480752075607600764076807720776078007840788079207960800080408080812081608200824082808320836084008440848085208560860086408680872087608800884088808920896090009040908091209160920092409280932093609400944094809520956096009640968097209760980098409880992099610001004
</code>```

Body:
Haskell, 51 bytes

f n|k<-length$show n=[k,2*k..n]>>=tail.show.(+10^k)


问:
Lemon-Limify a String
Write a program or function that takes in a nonempty single-line string. You may assume it only contains printable ASCII excluding space.

Print or return an ASCII art lozenge shape similar to a lemon or lime made from the prefixes of the string.

Suppose the input string is n letters long. Then, such a shape consists of 2n − 1 columns of ASCII art stitched together, each consisting of 2n − 1 lines. Counting from 1, the k-th column is f(k) = min(k, 2n − k) characters wide, and contains f(k) copies of the first f(k) characters of input, centered vertically, with single blank lines separating the copies.

For example, if the input is Lemon, the output should be:

```<code>          Lemon
      Lemo     Lemo
   Lem    Lemon    Lem
 Le   Lemo     Lemo   Le
L  Lem    Lemon    Lem  L
 Le   Lemo     Lemo   Le
   Lem    Lemon    Lem
      Lemo     Lemo
          Lemon
</code>```

If the input is lime the output should be:

```<code>      lime
   lim    lim
 li   lime   li
l  lim    lim  l
 li   lime   li
   lim    lim
      lime
</code>```

And the same pattern is followed for other inputs:

```<code>a

a

Be

 Be
B  B
 Be

/\

 /\
/  /
 /\

cat

   cat
 ca   ca
c  cat  c
 ca   ca
   cat

|||

   |||
 ||   ||
|  |||  |
 ||   ||
   |||

.__.

      .__.
   .__    .__
 ._   .__.   ._
.  .__    .__  .
 ._   .__.   ._
   .__    .__
      .__.

$tring

               $tring
          $trin      $trin
      $tri     $tring     $tri
   $tr    $trin      $trin    $tr
 $t   $tri     $tring     $tri   $t
$  $tr    $trin      $trin    $tr  $
 $t   $tri     $tring     $tri   $t
   $tr    $trin      $trin    $tr
      $tri     $tring     $tri
          $trin      $trin
               $tring
</code>```

Lines in the output may have trailing spaces and there may be one optional trailing newline.

The shortest code in bytes wins.

答:
C, 167 bytes

This program expects the input text to be passed as the first parameter to the program (via command line or however else) and will write the output to stdout.

int i,j,k,l,v;main(h,s)char**s;{h=strlen(s[1]);l=h*2;for(;++i<l;puts(""))for(j=0;++j<l,v=j<h?j:l-j;)for(k=0;k++<v;putchar((i+j+h%2)%2&&v>h-(i<h?i:l-i)?s[1][k-1]:32));}
```

<p>This is my first attempt at code golf here as it seemed like a reasonable challenge, so it can probably be golfed more than I was able to just due to how I did it.</p>

<h3>Explanation</h3>

<pre class="lang-c prettyprint-override"><code>/* Static variables
   i - "Row" number
   j - "Column" number
   k - String character counter
   l - Double length of the input string
   v - Inverted column distance from center */
int i,j,k,l,v;

/* Main parameters
   h - (argc) Input string length
   s - argv */
main(h, s)
char**s;
{
  /* Assign the input string length and double length */

  h = strlen(s[1]);
  l = h * 2;

  /* Display content */

    /* Loop over rows l - 1 times and put a newline after each */
  for (; ++i < l; puts(""))
      /* Loop over columns l - 1 times and set the inverted column
         distance each time */
    for (j = 0; ++j < l, v = ((j < h) ? j : l - j);)
        /* Loop over characters up to the inverted column distance from the
           center (this generates the pattern of output lengths needed) */
      for (k = 0; k++ < v;)
        putchar(
            /* Check for if the current row + column (with an offset based on
               the input parity) parity is even or odd, creating the needed
               checkerboard pattern */
          (i + j + h % 2) % 2 &&
            /* If the inverted column distance from the center is more than the
               row distance from the center, then the cell is inside the
               circular shape */
          v > (h - ((i < h) ? i : l - i)) ?
              /* Display the requested character (minus one for 0 based) */
            s[1][k-1] :
            32 /* Otherwise display a space (ASCII 32) */
        );
}
</code>```

It is significant enough to note the usage of (n < m) ? n : (m * 2) - n in the program at least twice to get the inverted distance from a center position m on a range of m * 2 with the input n. If there is a shorter way to do that then it could be golfed down some more easily as that algorithm is important for how this program works.

Title: Lemon-Limify a String

Body:
C, 167 bytes

This program expects the input text to be passed as the first parameter to the program (via command line or however else) and will write the output to stdout.

int i,j,k,l,v;main(h,s)char**s;{h=strlen(s[1]);l=h*2;for(;++i<l;puts(""))for(j=0;++j<l,v=j<h?j:l-j;)for(k=0;k++<v;putchar((i+j+h%2)%2&&v>h-(i<h?i:l-i)?s[1][k-1]:32));}

This is my first attempt at code golf here as it seemed like a reasonable challenge, so it can probably be golfed more than I was able to just due to how I did it.

Explanation

/* Static variables
   i - "Row" number
   j - "Column" number
   k - String character counter
   l - Double length of the input string
   v - Inverted column distance from center */
int i,j,k,l,v;

/* Main parameters
   h - (argc) Input string length
   s - argv */
main(h, s)
char**s;
{
  /* Assign the input string length and double length */

  h = strlen(s[1]);
  l = h * 2;

  /* Display content */

    /* Loop over rows l - 1 times and put a newline after each */
  for (; ++i < l; puts(""))
      /* Loop over columns l - 1 times and set the inverted column
         distance each time */
    for (j = 0; ++j < l, v = ((j < h) ? j : l - j);)
        /* Loop over characters up to the inverted column distance from the
           center (this generates the pattern of output lengths needed) */
      for (k = 0; k++ < v;)
        putchar(
            /* Check for if the current row + column (with an offset based on
               the input parity) parity is even or odd, creating the needed
               checkerboard pattern */
          (i + j + h % 2) % 2 &&
            /* If the inverted column distance from the center is more than the
               row distance from the center, then the cell is inside the
               circular shape */
          v > (h - ((i < h) ? i : l - i)) ?
              /* Display the requested character (minus one for 0 based) */
            s[1][k-1] :
            32 /* Otherwise display a space (ASCII 32) */
        );
}

It is significant enough to note the usage of (n < m) ? n : (m * 2) - n in the program at least twice to get the inverted distance from a center position m on a range of m * 2 with the input n. If there is a shorter way to do that then it could be golfed down some more easily as that algorithm is important for how this program works.


答:
Haskell, 74 bytes

My first code golf, yay! The general idea of this one is inspired by the top answer in Jelly, and the fact that when the month names are cycled, the 11th character is always unique.

```<code>e s=head.drop 10$cycle s;a#b=elem(e b)$tail$dropWhile(/=e a)"ubMAanlseovc"
</code>```

Here is an ungolfed version to see how it works:

```<code>order :: String
order = "ubMAanlseovc"

eleventhChar :: String -> Char
eleventhChar
  = head . drop 10 $ cycle

inOrder :: String -> String -> Bool
inOrder m1 m2
  = elem (eleventhChar m2) (tail $ dropWhile (/= eleventhChar m1) order)
</code>```

The e function represents the eleventhChar function (sadly can't strip off 4 bytes due to the monomorphism restriction I think) and the # infix function corresponds to the inOrder function.

A neat little solution, but there may be ways of shaving off more bytes (I found some just while writing this!)

Title: Sort the months of the year

Body:
Write a function or program that takes string inputs, fully-spelled, English month names in title case: January, February, March, etc. (null/CR/LF terminated OK, delimited with some non-alpha character if you so choose) and either

compares two inputs, returning a Truthy value if the second input is greater (in month order) than the first. Equal values result in a Falsey value

or sorts an arbitrary sequence (list, delimited string, etc.) of them in chronological order

(The crux of the challenge is defining a method/expression that gives the correct lexicographical sort. Some languages might have a shorter answer with one or the other)

You cannot use any internal time parsing methods (e.g. strptime) to translate the month name into a number or a pre-canned mapping of month names. Use properties of the strings themselves, a parsimonious look-up table you define, or something clever.

Example

Functioning examples, though the first is prohibited by the rules...

```<code>import datetime
def is_later_month(a, b):
    '''
    Example of prohibited code because it relies on language
    features about how to parse month names
    '''
    return datetime.strptime(a, '%B') < datetime.strptime(b, '%B')
</code>```

The below versions are OK though, because we code that info

```<code>months = {
    'January':  1, 'February':  2, 'March':      3,
    'April':    4, 'May':       5, 'June':       6,
    'July':     7, 'August':    8, 'September':  9,
    'October': 10, 'November': 11, 'December':  12,
}
def is_later_month(a, b):
    """
    Returns True/False when comparing two months.
    """
    return months[a] < months[b]
</code>```

Or you could do a sorting function

```<code>months = {'as above...'}
def sort_months(l):
    """
    Sorts list and returns it. Different input and output than the above,
    but equally valid. Sorting versus comparing might be shorter in your
    favorite language.
    """
    return sorted(l, key=lambda x: months[x])
</code>```

Example tests

```<code>assert is_later_month('January', 'February')
assert is_later_month('January', 'December')
assert is_later_month('November', 'December')
assert not is_later_month('July', 'July')
assert not is_later_month('October', 'September')
</code>```

Body:
Haskell, 74 bytes

My first code golf, yay! The general idea of this one is inspired by the top answer in Jelly, and the fact that when the month names are cycled, the 11th character is always unique.

e s=head.drop 10$cycle s;a#b=elem(e b)$tail$dropWhile(/=e a)"ubMAanlseovc"

Here is an ungolfed version to see how it works:

order :: String
order = "ubMAanlseovc"

eleventhChar :: String -> Char
eleventhChar
  = head . drop 10 $ cycle

inOrder :: String -> String -> Bool
inOrder m1 m2
  = elem (eleventhChar m2) (tail $ dropWhile (/= eleventhChar m1) order)

The e function represents the eleventhChar function (sadly can't strip off 4 bytes due to the monomorphism restriction I think) and the # infix function corresponds to the inOrder function.

A neat little solution, but there may be ways of shaving off more bytes (I found some just while writing this!)


问:
Swap 2 objects, without using a temporary variable
There are two objects:

```<code>Object1, Object2
</code>```

You can easily swap them by:

```<code>Object3 = Object1
Object1 = Object2
Object2 = Object3
</code>```

However, you must solve this problem by using no temporary object and Object1 should be changed to Object 2. (and vice versa)

答:
Python

I'll say it first.

```<code>object1, object2 = object2, object1
</code>```

Body:
Python

I'll say it first.

object1, object2 = object2, object1


问:
Making Future Posts Runnable Online with Stack Snippets
Stack Snippets were recently added to PPCG! Reminiscent of JSFiddle, Stack Snippets allow HTML, CSS, and JavaScript to be run directly in posts!

Here is a very simple Stack Snippet:

alert('This is JavaScript')```
<pre class="snippet-code-css lang-css prettyprint-override"><code>h3 { color: red } /* This is CSS */</code>```

This is HTML
```

This feature of Stack Exchange would be very useful for us if languages besides JavaScript were supported. (The answers to challenges could be tested on the spot, example inputs could be generated dynamically, etc.) This is where you come in.

Challenge

The goal of this challenge is to write an interpreter for some programming language using Stack Snippets and JavaScript. The point is to make something that can be easily copied and used in future PPCG questions and answers.

More or less, you need to create a Stack Snippet that has a "run" button and two textboxes, one for code and one for input. Clicking the run button will execute the code (written in the language you're interpreting) on the input and display the result (probably in another textbox). The snippet should be something akin to cjam.aditsu.net or the sample answer.

For most languages it would make sense for the input and output to represent stdin and sdout respectively, and you might have another input box for the command line. But not all languages have have such traditional I/O mechanisms. HQ9+, for example, doesn't even have input, making a textbox for it pointless. So feel free to take some liberties, design around the language, not this spec. The main requirement is that your language be "runnable" in a Stack Snippet in the accepted sense of the term.

Notes

Implementing every single feature of your language, though ideal, is not required. Some things like reading and writing files or importing libraries may be unwieldy or impossible. Focus on making an interpreter that maximizes utility for use on this site.

Posting a "language X to JavaScript" interpreter that you didn't write is ok (with attribution).

Stack Exchange limits answers to 30,000 characters, so plan accordingly if your interpreter is likely to be long.

It is best that you make a version of your interpreter as easy as possible to include in future posts. For example, in the sample answer, the raw Markdown for the entire snippet is provided, with obvious places to put code and input.

Although this question is intended to be more a compendium of interpreters than a proper challenge, it is still a popularity-contest, so the highest voted answer wins.

List of Current Interpreters

(sorted alphabetically by language name)

Beam

Befunge-93

Brainfuck

Brainfuck

CHIQRSX9+

Deadfish

Deadfish (only runs preset code)

Fourier

FRACTRAN

Hello++

HQ9+

Insomnia

Japt

JavaScript (sample answer)

JavaScript ES2015

Marbelous

Neoscript

oOo CODE

Ouroboros

Prelude

Python 2

STATA

TI-Basic

Unary (translates to BF)

(This question might be better suited for Meta but it will be more visible here. People might actually produce very useful interpreters, I think they deserve the rep for it.)

答:
Neoscript

Only work on ES6 browsers

"use strict";

function nodejswrapper(url) {
    let data = $.ajax({
        type: "GET",
        url: url,
        async: false
    }).responseText;
    return new Function("let module={};" + data + "return module.exports;")();
}

let tokenize, parse, transpile;

function compile(code) {
    return transpile(parse(tokenize(code)));
}

console.log = function(msg) {
    $("#console").append((""+msg).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">") + "
");
}
console.clear = function(msg) {
    $("#console").html("");
}

$(function() {
    tokenize = nodejswrapper("http://crossorigin.me/https://raw.githubusercontent.com/tuxcrafting/neoscript/master/src/tokenizer.js").tokenize;
    parse = nodejswrapper("http://crossorigin.me/https://raw.githubusercontent.com/tuxcrafting/neoscript/master/src/parser.js").parse;
    transpile = nodejswrapper("http://crossorigin.me/https://raw.githubusercontent.com/tuxcrafting/neoscript/master/src/transpilers/javascript.js").transpile;
    $("#run").on("click", function() {
        let code = $("#code").val();
        let js = compile(code);
        new Function(js)();
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#console {
    width: 400px;
    height: 400px;
    overflow: auto;
    background: black;
    color: white;
    float: right;
    font-family: monospace;
}</code>```

<textarea id="code" cols="40" rows="15"></textarea>

<button id="run">Run</button>```

Body:
Neoscript

Only work on ES6 browsers

"use strict";

function nodejswrapper(url) {
    let data = $.ajax({
        type: "GET",
        url: url,
        async: false
    }).responseText;
    return new Function("let module={};" + data + "return module.exports;")();
}

let tokenize, parse, transpile;

function compile(code) {
    return transpile(parse(tokenize(code)));
}

console.log = function(msg) {
    $("#console").append((""+msg).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;") + "<br />");
}
console.clear = function(msg) {
    $("#console").html("");
}

$(function() {
    tokenize = nodejswrapper("http://crossorigin.me/https://raw.githubusercontent.com/tuxcrafting/neoscript/master/src/tokenizer.js").tokenize;
    parse = nodejswrapper("http://crossorigin.me/https://raw.githubusercontent.com/tuxcrafting/neoscript/master/src/parser.js").parse;
    transpile = nodejswrapper("http://crossorigin.me/https://raw.githubusercontent.com/tuxcrafting/neoscript/master/src/transpilers/javascript.js").transpile;
    $("#run").on("click", function() {
        let code = $("#code").val();
        let js = compile(code);
        new Function(js)();
    });
});

#console {
    width: 400px;
    height: 400px;
    overflow: auto;
    background: black;
    color: white;
    float: right;
    font-family: monospace;
}

<script type="application/javascript" src="https://raw.githubusercontent.com/tuxcrafting/neoscript/master/src/stdlib/stdlib.js"></script>
<script type="application/javascript" src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<div id="console"></div>
<textarea id="code" cols="40" rows="15"></textarea><br />
<button id="run">Run</button>


答:
JavaScript (ES6), 66

Recursive, input n as a string (not a number) and limiting the output string size to 2GB (that is above the string limit of most javascript engines)

f=(n,i=1e9,s='',l=n.length)=>s[n-1]?s:f(n,i+=l,s+(i+'').slice(-l))
```
<p><strong>Test</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>f=(n,i=1e9,s='',l=n.length)=>s[n-1]?s:f(n,i+=l,s+(i+'').slice(-l))

function test() {
  var v=I.value;
  Alert.textContent=v % v.length ?
    'Warning: input value is not divisible by its string length':'\n';
  Result.textContent=f(v);
}

test()</code>```

<input type=number id=I value=105 oninput='test()' max=500000>

```
<pre id=Result>``````

Body:
JavaScript (ES6), 66

Recursive, input n as a string (not a number) and limiting the output string size to 2GB (that is above the string limit of most javascript engines)

f=(n,i=1e9,s='',l=n.length)=>s[n-1]?s:f(n,i+=l,s+(i+'').slice(-l))

Test

f=(n,i=1e9,s='',l=n.length)=>s[n-1]?s:f(n,i+=l,s+(i+'').slice(-l))

function test() {
  var v=I.value;
  Alert.textContent=v % v.length ?
    'Warning: input value is not divisible by its string length':'\n';
  Result.textContent=f(v);
}

test()

<input type=number id=I value=105 oninput='test()' max=500000>
<pre id=Alert></pre>
<pre id=Result></pre>


Body:
Perl, 40 bytes

39 bytes code + 1 for -n.

$}=y///c;printf"%0$}d",$i+=$}while$i<$_

Usage

echo -n 9 | perl -ne '$}=y///c;printf"%0$}d",$i+=$}while$i<$_'
123456789
echo -n 10 | perl -ne '$}=y///c;printf"%0$}d",$i+=$}while$i<$_'
0204060810
echo -n 102 | perl -ne '$}=y///c;printf"%0$}d",$i+=$}while$i<$_'
003006009012015018021024027030033036039042045048051054057060063066069072075078081084087090093096099102
echo -n 1000 | perl -ne '$}=y///c;printf"%0$}d",$i+=$}while$i<$_'
0004000800120016002000240028003200360040004400480052005600600064006800720076008000840088009200960100010401080112011601200124012801320136014001440148015201560160016401680172017601800184018801920196020002040208021202160220022402280232023602400244024802520256026002640268027202760280028402880292029603000304030803120316032003240328033203360340034403480352035603600364036803720376038003840388039203960400040404080412041604200424042804320436044004440448045204560460046404680472047604800484048804920496050005040508051205160520052405280532053605400544054805520556056005640568057205760580058405880592059606000604060806120616062006240628063206360640064406480652065606600664066806720676068006840688069206960700070407080712071607200724072807320736074007440748075207560760076407680772077607800784078807920796080008040808081208160820082408280832083608400844084808520856086008640868087208760880088408880892089609000904090809120916092009240928093209360940094409480952095609600964096809720976098009840988099209961000


问:
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

```<code>ABCDEFGHIJKLMNOPQRSTUVWXYZ
</code>```

or

```<code>abcdefghijklmnopqrstuvwxyz
</code>```

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="
"+e.body.replace(OVERRIDE_REG,"")+"
")});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;/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;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```
</div>
</div>
</p>

<p><strong>The first post of the series also generates an overall leaderboard.</strong></p>

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

```## Language Name, N bytes
```

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

```## 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.)

答:
R, <s>40</s> 27 bytes

```<code>LETTERS[sample(26,1,,1:26)]
</code>```

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 :

```<code>sample(
       26, #How many numbers to generate
        1, #How many numbers to sample
         , #Replacing ? Here, no by default
     1:26, #Weight of probabilities
       )
</code>```

Body:
R, <s>40</s> 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
       )


答:
MATL, 10 bytes

```<code>1Y2rU26*k)
</code>```

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:

```<code>bar(0:25, histc(floor(26*rand(1,1e6).^2), 0:25))
</code>```

Title: Random Golf of the Day #7: A distinctly random character

Body:
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

```<code>ABCDEFGHIJKLMNOPQRSTUVWXYZ
</code>```

or

```<code>abcdefghijklmnopqrstuvwxyz
</code>```

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="
"+e.body.replace(OVERRIDE_REG,"")+"
")});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;/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;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```
</div>
</div>
</p>

<p><strong>The first post of the series also generates an overall leaderboard.</strong></p>

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

```## Language Name, N bytes
```

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

```## 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.)

Body:
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))


答:
Python 2, 72 bytes

```<code>from random import*
print choice(''.join(i*chr(i)for i in range(65,91)))
</code>```

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:

```<code>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
</code>```

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

Body:
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


答:
q, 38 bytes

Not particularly short but...

```<code>.Q.A(reverse 0.9 xexp til 26)binr 1?1f
</code>```

The discrete cumulative distribution function is the sequence

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

And we merely sample from the distribution.

Body:
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.


答:
05AB1E, 6 bytes

Code

```<code>A.pJ.R
</code>```

Explanation

```<code>A        # Pushes the alphabet
 .p      # Computes all prefixes
   J     # Join them together
</code>```

We now have the following string:

```<code>aababcabcdabcdeabcdefabcdefgabcdefghabcdefghiabcdefghijabcdefghijkabcdefghijklabcdefghijklmabcdefghijklmnabcdefghijklmnoabcdefghijklmnopabcdefghijklmnopqabcdefghijklmnopqrabcdefghijklmnopqrsabcdefghijklmnopqrstabcdefghijklmnopqrstuabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvwabcdefghijklmnopqrstuvwxabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyz
</code>```

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

The probabilities

```<code>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%
</code>```

Try it online!.

Body:
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!.


答:
Mathematica

A standard feature:

```<code>a = 1; b = 2;
Print[a, " ", b];
{a, b} = {b, a};
Print[a, " ", b];
</code>```

Output

```<code>(*
1 2

2 1
*)
</code>```

Title: Swap 2 objects, without using a temporary variable

Body:
There are two objects:

```<code>Object1, Object2
</code>```

You can easily swap them by:

```<code>Object3 = Object1
Object1 = Object2
Object2 = Object3
</code>```

However, you must solve this problem by using no temporary object and Object1 should be changed to Object 2. (and vice versa)

Body:
Mathematica

A standard feature:

a = 1; b = 2;
Print[a, " ", b];
{a, b} = {b, a};
Print[a, " ", b];

Output

(*
1 2

2 1
*)


答:
PowerShell v2+, <s>33</s> 31 bytes

```<code>[char](65..90|%{,$_*$_}|Random)
</code>```

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)

```<code>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 %
</code>```

Body:
PowerShell v2+, <s>33</s> 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 %


答:
JavaScript (ES2017), 346 bytes

```<code>f=(p,q,a=p?q.split(p[0]):[q])=>p[1]?f(p.slice(1),a.join(p[1])):(s=a.filter(e=>a.indexOf(e)==a.lastIndexOf(e)).map(e=>e.length).sort((a,b)=>a-b),t=l=0,r=[],s.map(e=>r[t+=e,l++,e]=-~r[e]),[l&&t/l,l&&(s[l>>1]+s[l-1>>1])/2,[...m=new Set(s.filter(e=>r[e]==Math.max(...Object.values(r))))],[a.filter(e=>!m.has(e.length)),a.filter(e=>m.has(e.length))]])
</code>```

For ES6 replace Object.values(r) with Object.keys(r).map(k=>r[k]) at a cost of 11 bytes. Explanation:

```<code>f=(p,q,a=p?q.split(p[0]):[q])=>         split on first seprator
 p[1]?f(p.slice(1),a.join(p[1])):       recurse for each separator
  (s=a.filter(e=>                       search through list for
     a.indexOf(e)==a.lastIndexOf(e))    unique strings only
    .map(e=>e.length)                   get lengths of each string
    .sort((a,b)=>a-b),                  sort lengths into order
   t=l=0,                               total and length
   r=[],                                frequency table
   s.map(e=>r[t+=e,l++,e]=-~r[e]),      build frequency table and total
   [l&&t/l                              mean = total / length
   ,l&&(s[l>>1]+s[l-1>>1])/2            median = mean of middle elements
   ,[...m=new Set(s.filter(e=>r[e]==    unique elements matching
    Math.max(...Object.values(r))))]    maximum length frequency
   ,[a.filter(e=>!m.has(e.length))      filter on non-modal length
    ,a.filter(e=>m.has(e.length))]])    filter on modal length
</code>```

Title: Fun with strings and string lengths

Body:
Introduction

Inspired by Dyalog Ltd.'s 2016 student competition. The challenge there is to write good APL code, but this is a code-golf and it is open to all languages. Derived from this closed challenge.

The real challenge here is to combine the various (quite trivial) parts of the problem in a byte-efficient way by reusing values and/or algorithms.

If you find this challenge interesting and you use Dyalog APL (free download here), you may also want to participate in the original competition, but note that the objective there is to submit quality code – not necessarily short code. If you are a student, you can win USD 100 for Phase I. Phase II (not related to this code golf challenge) can win you up to USD 2000 and a free trip to Scotland!

Task

Take two strings (of any 7-bit ASCII characters) by any means and order (but please include input format in your answer). You may take them as separate arguments/inputs or as a single list of strings. One string contains the delimiters in the other. E.g. given ',;/' and 'hello,hello;there;my/yes/my/dear,blue,world', the sub-strings are ['hello', 'hello', 'there', 'my', 'yes', 'my', 'dear', 'blue', and 'world'].

You will do some statistics and ordering based on the lengths of those sub-strings that are not duplicated in the input. (You may chose to consider casing or not.) In the example given, those are ['there', 'yes', 'dear', 'blue', 'world'].

Give (by any means) a list of four elements in the overall structure [Number_1, Number_2, [List_3], [[List_4_1], [List_4_2]]]:

The mean of the lengths of the non-duplicated strings. In our example, that is 4.2

The median of the lengths of the non-duplicated strings. In our example, that is 4.

The mode(s) of the lengths of the non-duplicated strings. In our example, that is [4, 5].

The original sub-strings (including duplicates), divided into two lists; the first are those that are not one of the above mode lengths, and the second are those that are. In our example: [['my', 'my', 'yes'], ['dear', 'blue', 'hello', 'hello', 'there', 'world']]

The combined final answer of our example case is: [4.2, 4, [4, 5], [['my', 'my', 'yes'], ['dear', 'blue', 'hello', 'hello', 'there', 'world']]]

Considerations

Don't forget to reuse code and values. E.g. the median is the average of the 1 or 2 middle elements, and you'll need the mode(s) to reorder the original list.

Watch out for division by zero; an empty input means one string with length zero, so the mean length is zero. If there are no non-unique sub-strings, return zero for both mean and median, an empty list for modes, and put all original sub-strings onto the non-mode list.

The list of modes, and the sub-lists of non-mode-length strings, and mode-length strings, do not need to be sorted in any way.

If all non-duplicated sub-strings have different lengths, then all the lengths are considered modes.

Wherever the term list is used, you may use any collection of multiple data pieces that your language supports, e.g. tuples, arrays, dictionaries, etc.

The numeric values only need to be within 1% of the actual value.

Example cases

Example A

',;/' 'hello,hello;there;my/yes/my/dear,blue,world'

gives

[4.2, 4, [4, 5], [['my', 'my', 'yes'], ['dear', 'blue', 'hello', 'hello', 'there', 'world']]

Example B

'+|' ''

gives

[0, 0, [0], [[], ['']]]

Note: while there are two delimiter characters, none of them occur in the data string, so this is just one empty string. Mean, median, and mode are therefore zero There are no strings in the non-mode list and just the single empty string in the mode list.

Example C

'' 'ppcg.se.com'

gives

[11, 11, [11], [[], ['ppcg.se.com']]]

Note: no delimiters, so the entire input is one string.

Example D

',;' ',math,,math;'

gives

[0, 0, [], [['', 'math', '', 'math', ''], []]]

Note: there are three empty sub-strings, and since all sub-strings have at least one duplicate, the mean and median default to zero, as per Considerations, above.

Example E

',;' 'new,math,math;!;'

gives

[1.333, 1, [0,1,3], [['math', 'math'], ['new', '!', '']]]

Note: there is only one of each length among the non-duplicated sub-strings, so all three lengths are modes.

You can verify my explicit permission to post this challenge here by contacting the author of the original competition.

Body:
JavaScript (ES2017), 346 bytes

f=(p,q,a=p?q.split(p[0]):[q])=>p[1]?f(p.slice(1),a.join(p[1])):(s=a.filter(e=>a.indexOf(e)==a.lastIndexOf(e)).map(e=>e.length).sort((a,b)=>a-b),t=l=0,r=[],s.map(e=>r[t+=e,l++,e]=-~r[e]),[l&&t/l,l&&(s[l>>1]+s[l-1>>1])/2,[...m=new Set(s.filter(e=>r[e]==Math.max(...Object.values(r))))],[a.filter(e=>!m.has(e.length)),a.filter(e=>m.has(e.length))]])

For ES6 replace Object.values(r) with Object.keys(r).map(k=>r[k]) at a cost of 11 bytes. Explanation:

f=(p,q,a=p?q.split(p[0]):[q])=>         split on first seprator
 p[1]?f(p.slice(1),a.join(p[1])):       recurse for each separator
  (s=a.filter(e=>                       search through list for
     a.indexOf(e)==a.lastIndexOf(e))    unique strings only
    .map(e=>e.length)                   get lengths of each string
    .sort((a,b)=>a-b),                  sort lengths into order
   t=l=0,                               total and length
   r=[],                                frequency table
   s.map(e=>r[t+=e,l++,e]=-~r[e]),      build frequency table and total
   [l&&t/l                              mean = total / length
   ,l&&(s[l>>1]+s[l-1>>1])/2            median = mean of middle elements
   ,[...m=new Set(s.filter(e=>r[e]==    unique elements matching
    Math.max(...Object.values(r))))]    maximum length frequency
   ,[a.filter(e=>!m.has(e.length))      filter on non-modal length
    ,a.filter(e=>m.has(e.length))]])    filter on modal length


答:
J, <s>20</s> 18 bytes

```
<s>({~?@#)u:64+#~1+i.26</s>
({~?@#)u:64+#~i.27
```

Online interpreter

Uppercase.

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

Body:
J, <s>20</s> 18 bytes

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

Online interpreter

Uppercase.

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


答:
PHP, 92 84 bytes

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

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%

Body:
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%


答:
Pyth, 5

```<code>Os._G
</code>```

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.

Body:
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.


Body:
Java 7, <s>62</s> <s>57</s> 56 bytes

5 bytes thanks to Poke.

1 byte thanks to trichoplax.

<s>char r(){return(char)(65+(int)Math.sqrt(Math.random()*676));}</s>
<s>char r(){return(char)(65+Math.sqrt(Math.random()*676));}</s>
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: ***************************************************************************


答:
CJam, <s>21</s> <s>17</s> 12 bytes

Thanks to Martin Ender for saving me 5 bytes!

New version

```<code>'\,:,s_el-mR
</code>```

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

```<code>'\,          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
</code>```

Old version

```<code>26,:)'[,'A,- .*M*mr0=
</code>```

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

```<code>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
</code>```

Body:
CJam, <s>21</s> <s>17</s> 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.

<a href="http://cjam.aditsu.net/#code='%5C%2C%20%20%20%20%20%20%20%20%20%20e%23%20Push%20the%20range%20of%20all%20characters%20up%20to%20'Z'%0A%20%20%20%3A%2C%20%20%20%20%20%20%20%20e%23%20For%20each%20one%2C%20take%20the%20range%20of%20all%20characters%20up%20to%20it%0A%20%20%20%20%20s%20%20%20%20%20%20%20e%23%20Convert%20the%20array%20of%20ranges%20to%20one%20string%0A%20%20%20%20%20%20_el-%20%20%20e%23%20Subtract%20the%20lower%20case%20version%20of%20the%20string%20from%20itself%0A%20%20%20%20%20%20%20%20%20%20%20%20%20e%23%20This%20leaves%20only%20capital%20letters%20in%20the%20string%0A%20%20%20%20%20%20%20%20%20%20mR%20e%23%20Take%20a%20random%20character%20from%20it" rel="nofollow">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


答:
Python 2, <s>58</s> 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!

Body:
Python 2, <s>58</s> 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!


答:
Perl, 24 bytes

-4 bytes thanks to @Martin Ender

-1 byte  thanks to @Dom Hastings

```<code>say+(A..Z)[rand rand 26]
</code>```

Needs -M5.010 or -E to run :

```<code>perl -E 'say+(A..Z)[rand rand 26]'
</code>```

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

```<code>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
</code>```

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.

Body:
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.


Body:
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

```<code>ABCDEFGHIJKLMNOPQRSTUVWXYZ
</code>```

or

```<code>abcdefghijklmnopqrstuvwxyz
</code>```

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="
"+e.body.replace(OVERRIDE_REG,"")+"
")});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;/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;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```
</div>
</div>
</p>

<p><strong>The first post of the series also generates an overall leaderboard.</strong></p>

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

```## Language Name, N bytes
```

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

```## 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.)


答:
PostScript

In PostScript, it's common to use the stack instead of named variables, so a simple

```<code>exch
</code>```

would do the job. But if you have variables, you can do it like

```<code>/a 1 def
/b 2 def
/a b /b a def def
</code>```

Body:
PostScript

In PostScript, it's common to use the stack instead of named variables, so a simple

exch

would do the job. But if you have variables, you can do it like

/a 1 def
/b 2 def
/a b /b a def def


答:
Clojure, 61 bytes

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

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

Body:
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


答:
R, 23 bytes

```<code>sample(LETTERS,1,,1:26)
</code>```

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

Body:
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.


答:
CJam, 11 bytes

```<code>4.mrmqC*'A+
</code>```

or

```<code>676.mrmq'A+
</code>```

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.

Body:
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.


答:
PHP, <s>44</s> <s>36</s> <s>29</s> 27 bytes

Crossed out 44 is still regular 44 ;(

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

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

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

Body:
PHP, <s>44</s> <s>36</s> <s>29</s> 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


答:
JavaScript (ES6), 45 bytes

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

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

<h2>Test</h2>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>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');</code>```

```</code>```

Body:
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>


答:
Batch, 116 bytes

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

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

Body:
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.


答:
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;
```

<p>Un-golfed</p>

<pre class="lang-sql prettyprint-override"><code>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
</code>```

Body:
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


答:
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.

```<code>['' 96+min(1/rand,26)]
</code>```

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

Body:
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.


答:
C#, <s>68</s> 66 bytes

Thanks to Leaky Nun for fixing the chance distribution.

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

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:

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

Body:
C#, <s>68</s> 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