title: Score rock-paper-scissors

text:
# Question
Title: Score rock-paper-scissors
Given two string inputs of "Rock", "Paper", or "Scissors", determine the outcome of the RPS round. Output 1 if the first player wins, -1 if the second player wins, or 0 for a tie.

```
Rock Rock -> 0
Rock Paper -> -1
Rock Scissors -> 1
Paper Rock -> 1
Paper Paper -> 0
Paper Scissors -> -1
Scissors Rock -> -1
Scissors Paper -> 1
Scissors Scissors -> 0

```

You must use the exact strings "Rock", "Paper", and "Scissors" as inputs. You may choose whether the first players' choice is (consistently) given first or second. You may alternatively take them as a single input with a single-character or empty separator. The input is guaranteed one of the 9 possible pairings of the three choices in your input format.

The output should be a number 1, 0, or -1, or its string representation. Floats are fine. So are `+1`, `+0,` and `-0`.

Related: Coding an RPS game

---

**Leaderboard:**

```
var QUESTION_ID=106496,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/106496/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
> 77 votes
# Groovy, ~~67~~ ~~56~~ 50 Bytes

```
{a,b->Math.sin(1.3*((int)b[0]-(int)a[0])).round()}

```

Try it online!

Turns out that the rock, paper, scissors game has a pretty cool property.
Given strings a and b, take the first letter of each, this results in two of the following: `R,P,S`

The exhaustive list of possible values are (When 2 choices are combined):

```
XX=ASCII=Y=Wanted output
RR=82-82=0=0
PP=80-80=0=0
SS=83-83=0=0
RS=82-83=-1=1
RP=82-80=2=-1
PS=80-83=-3=-1
PR=80-82=-2=1
SR=83-82=1=-1
SP=83-80=3=1

```

Reorganizing the list to:

```
-3->-1
-2->1
-1->1
0->0
1->-1
2->-1
3->1

```

Gives us a sequence that looks inversely sinusoidal, and you can actually represent this formula as approximately (and by approximately I mean just barely enough to work, you could get an equation that is dead on but costs more bytes):

```
-sin((4*a[0]-b[0])/PI).roundNearest() = sin(1.3*(b[0]-a[0])).roundNearest()

```

The simplification of 4/pi to 1.3 was suggested first by ***@flawr*** and then tested by ***@titus*** for a total savings of 6 bytes.

Using groovy's double rounding properties, this results in the correct output for rock-paper-scissors.

---

# 05AB1E, 10 bytes (non-compete)

```
Ç¥13T/*.½ò

```

Try it online!

Same answer ported to 05AB1E using the new commands added 10/26/2017.

# Answer
> 44 votes
# C, ~~50~~ 35 bytes

```
#define f(i)*(short*)(i+7)%51%4%3-1

```

Call `f` with a string containing both players, without separator, and it will return whether the first one wins.

### Explanation:

By looking at the nine possible strings, it turns out that the letter pairs on columns 7 and 8 are unique:

```
       vv
RockPaper
PaperScissors
ScissorsRock
RockRock         // Sneakily taking advantage of the terminating zero
PaperPaper
ScissorsScissors
RockScissors
PaperRock
ScissorsPaper
       ^^

```

The offset and savage cast to `short*` retrieve these letter pairs, and interpret them as numbers:

```
29285
29545
21107
107
25968
21363
29555
27491
20595

```

Then it was a matter of brute-force to find the `51` and `4` remainders, which applied successively reduce these numbers to:

```
3 0 0 1 1 1 2 2 2

```

Which is just perfect to tack yet another remainder at the end, and offsetting the result.

See it live on Coliru

# Answer
> 18 votes
# MATLAB/Octave, ~~63 54~~ 52 bytes

It is very convenient that the ASCII-codes of the first letters of `Rock,Paper,Scissors` are `R=82,P=80,S=83`. If we subtract `79` we get conveniently `3,1,4`, which we will use now as matrix indices: Here a 4x4-matrix is hardcoded, where the `i,j`-th entry corresponds to the outcome if you plug in the values from just before:

```
     1   2   3   4
  +---------------
1 |  0   0   1  -1
2 |  0   0   0   0
3 | -1   0   0   1
4 |  1   0  -1   0

```

```
A(5,5)=0;A(4:7:18)=1;A=A-A';@(x,y)A(x(1)-79,y(1)-79)

```

Try it online!

# Answer
> 17 votes
# Python, ~~40~~ 30 bytes

```
lambda x,y:(len(2*x+y)^67)%3-1

```

Try it online!

### Background

I've started with the function template

```
lambda x,y:(len(a*x+b*y)^c)%d-e

```

and ran a brute-force search for suitable parameters using the following program, then picked one with a minimal-length implementation.

```
RPS = 'Rock Paper Scissors'.split()
g = lambda x,y:2-(94>>len(6*x+y)%7)%4
r = range(1,10)
R = range(100)

def f(a, b, c, d, e):
    h = lambda x,y:(len(a*x+b*y)^c)%d-e
    return all(g(x, y) == h(x, y) for x in RPS for y in RPS)

[
    print('%2d ' * 5 % (a, b, c, d, e))
    for e in r
    for d in r
    for c in R
    for b in r
    for a in r
    if f(a, b, c, d, e)
]

```

Try it online!

# Answer
> 16 votes
# Pure Bash, 31

Borrowing @Dennis's formula:

```
a=$1$1$2
echo $[(${#a}^67)%3-1]

```

Try it online.

---

Previous answer:

# Pure Bash, 43 35

```
echo $[(7+(${#2}^3)-(${#1}^3))%3-1]

```
* Get the string length of each arg (`4`, `5`, `8` respectively for Rock, Paper, Scissors)
* XOR each with 3 to give `7`, `6`, `11` (which when taken mod 3 give `1`, `0`, `2`)
* Then subtract and fiddle with mod 3 to get the desired result.

Try it online.

# Answer
> 14 votes
# Mathematica, 32 bytes

```
Mod[{1,-1}.(Length/@#-3)!,3,-1]&

```

Unnamed function taking an ordered pair of lists of characters, such as `{{"R","o","c","k"},{"P","a","p","e","r"}}`, and returning `-1|0|1`.

I wanted the code to avoid not only the three input words, but also the way-too-long function name `ToCharacterCode`; so I worked with the length `4,5,8` of the input words instead, and looked for a short function of those lengths that gave distinct answers modulo 3. (Integer division by 2 is mathematically promising, but those functions have too-long names in Mathematica.)

It turns out that taking the factorial of (the length – 3) gives the answers `1,2,120`, which are `1,-1,0` modulo 3. Then we just compute, modulo 3, the difference of the two values (via the dot product `{1,-1}.{x,y} = x-y`, which is a good way when the two values are in a list).

# Answer
> 12 votes
# Ruby, 36 35 30 bytes

```
a=->a,b{(a+b)[12]?a<=>b:b<=>a}

```

Try it on ideone.com

Test output:

```
a=->a,b{(a+b)[12]?a<=>b:b<=>a}

puts a.call("Rock", "Rock")
puts a.call("Rock", "Paper")
puts a.call("Rock", "Scissors")
puts a.call("Paper", "Rock")
puts a.call("Paper", "Paper")
puts a.call("Paper", "Scissors")
puts a.call("Scissors", "Rock")
puts a.call("Scissors", "Paper")
puts a.call("Scissors", "Scissors")

0
-1
1
1
0
-1
-1
1
0

```

Takes advantage of the fact that 7 of the 9 correct results are generated just by doing a lexicographic comparison using the spaceship operator `<=>`. The `(a+b)[12]` just reverses the inputs to the comparison if the inputs are `Paper` and `Scissors` (and also `Scissors` `Scissors` \- but that's `0` either way round).

With thanks to Horváth Dávid for saving me a character, and thanks to G B for saving me another 5.

# Answer
> 10 votes
# Python, ~~39~~ ~~36~~ ~~34~~ 33 bytes

```
lambda x,y:2-(94>>len(6*x+y)%7)%4

```

Try it online!

### How it works

Let's take a look at a few values of the length of six copies of **x** and one copy of **y** modulo **7**.

```
                                l(x,y) =:
x        y        len(x) len(y) len(6*x+y)%7
--------------------------------------------
Rock     Rock          4      4            0
Rock     Paper         4      5            1
Rock     Scissors      4      8            4
Paper    Rock          5      4            6
Paper    Paper         5      5            0
Paper    Scissors      5      8            3
Scissors Rock          8      4            3
Scissors Paper         8      5            4
Scissors Scissors      8      8            0

```

We can encode the outcomes (**{-1, 0, 1}**) by mapping them into the set **{0, 1, 2, 3}**. For example, the mapping **t ↦ 2 - t** achieves this and is its own inverse.

Let's denote the outcome of **x** and **y** by **o(x, y)**. Then:

```
x        y        l(x,y) o(x,y) 2-o(x,y) (2-o(x,y))<<l(x,y)
-----------------------------------------------------------
Rock     Rock          0      0        2                10₂
Rock     Paper         1     -1        3               110₂
Rock     Scissors      4      1        1            010000₂
Paper    Rock          6      1        1          01000000₂
Paper    Paper         0      0        2                10₂
Paper    Scissors      3     -1        3             11000₂
Scissors Rock          3     -1        3             11000₂
Scissors Paper         4      1        1            010000₂
Scissors Scissors      0      0        2                10₂

```

Luckily, the bits in the last columns all agree with each other, so we can OR them to form a single integer **n** and retrieve **o(x, y)** as **2 - ((n ≫ o(x,y)) % 4)**. The value of **n** is **94**.

# Answer
> 9 votes
## Retina, ~~35~~ 31 bytes

```
G`k P|r S|s R
*\)`.+
-
D`\w+
 .

```

Try it online!

### Explanation

This works in two steps. First, we print the minus signs for the relevant inputs. Then we print a `0` for ties and a `1` otherwise.

```
G`k P|r S|s R
*\)`.+
-

```

This is two stages. The `)` in the second stage groups them together, the `*` makes them a dry run (which means the input string will be restored after they were processed, but the result will be printed) and `\` suppresses printing of a trailing linefeed. The two stages together will print a `-` if applicable.

The first stage is a `G`rep stage which only keeps the line if it contains either `k P`, `r S`, or `s R`. These correspond to the cases where we need to output `-1`. If it's not one of those cases, the input will be replaced with an empty string.

The second stage replaces `.+` (the entire string, but only if it contains at least one character) with `-`. So this prints a `-` for those three cases and nothing otherwise.

```
D`\w+
 .

```

This is two more stages. The first stage is a `D`eduplication. It matches words and removes duplicates. So if and only if the input is a tie, this drops the second word.

The second stage counts the number of matches of  `.`, which is a space followed by any character. If the input was a tie, and the second word was removed, this results in `0`. Otherwise, the second word is still in place, and there's one match, so it prints `1` instead.

# Answer
> 9 votes
# 05AB1E, ~~18~~ ~~17~~ ~~15~~ ~~10~~ 9 bytes

6 bytes saved with *Digital Trauma's* input length trick

```
€g3^Æ>3%<

```

Takes input as `[SecondPlayersChoice,FirstPlayersChoice]`

Try it online! or Validate all test-cases

**Alternative 9 byte solution:** `íø¬ÇÆ>3%<`

**Explanation**

```
€g          # length of each in input
  3^        # xor 3
    Æ       # reduce by subtraction
     >      # increment
      3%    # modulus 3
        <   # decrement

```

**Previous 15 byte solution**

```
A-D{„PSÊiR}Ç`.S

```

Try it online! or Validate all test-cases

**Explanation**

```
 A-               # remove the lowercase alphabet from the input (leaves a 2 char string)
   D{             # sort a copy of the leftover
     „PSÊ         # check if the copy isn't "PS" (our special case)
         iR}      # if true, reverse the string to get the correct sign
            Ç`    # convert the two letters to their character codes
              .S  # compare their values

```

# Answer
> 6 votes
# Jelly, 8 bytes

```
L€Iµ-*×Ṡ

```

Try it online! (test suite, casts to integer for clarity)

### How it works

```
L€Iµ-*×Ṡ  Main link. Argument: A (string array)

L€        Take the length of each string.
  I       Increments; compute the forward difference of the length.
   µ      Begin a new chain with the difference d as argument.
    -*    Compute (-1)**d.
      ×Ṡ  Multiply the result with the sign of d.

```

# Answer
> 6 votes
## CJam, ~~15~~ ~~14~~ 12 bytes

```
rW=rW=-J+3%(

```

Take the ascii code of the last character of each string, then returns:

`(a1 - a2 + 19) % 3 - 1`

Test it here!

# Answer
> 6 votes
# Python 2, ~~46~~ 40 bytes

```
lambda x,y:+(x!=y,-1)[x[0]+y[0]in'RPSR']

```

Try it online!

With many thanks to @Dennis for letting me borrow his Try it online test code and for saving me 6 bytes.

**Edit**

@hashcode55 - Pretty much as you describe. (x!=y,-1) is a two element sequence and \[x\[0\]+y\[0\]in'RPSR'\] is computing which element to take. If the first letter of x + the first letter of y is in the character list then it will evaluate to True or 1 so (x!=y,-1)\[1\] will be returned. If it is not then (x!=y,-1)\[0\]. This is where it gets a bit tricky. The first element is in itself effectively another if. If x!=y then the first element will be True otherwise it will be False so if x\[0\]+y\[0\]in'RPSR' is false then either True or False will be returned depending on whether x==y. The + is a bit sneaky and thanks again to @Dennis for this one. The x!=y will return a literal True or False. We need a 1 or a 0. I still don't quite know how but the + does this conversion. I can only assume that by using a mathematical operator on True/False it is forcing it to be seen as the integer equivalent. Obviously the + in front of the -1 will still return -1.

Hope this helps!

# Answer
> 5 votes
## JavaScript (ES6), ~~46~~ 38 bytes

```
(a,b)=>(4+!b[4]+!b[5]-!a[4]-!a[5])%3-1

```

Makes use of the fact that Rock-Paper-Scissors is cyclic. JavaScript has neither spaceship nor balanced ternary operators, otherwise the answer would be `(a,b)=>((b<=>'Rock')-(a<=>'Rock'))%%3`.

Edit: Saved 8 bytes thanks to @WashingtonGuedes.

# Answer
> 5 votes
# Python 3, 54 bytes

```
lambda o,t:(o!=t)*[-1,1]['RPS'['PS'.find(t[0])]!=o[0]]

```

Try it online!

# Answer
> 5 votes
# MATL, ~~14~~ 13 bytes

```
TTt_0vic1Z)d)

```

Try it online! Or verify all test cases.

### Explanation

If the ASCII code of the initial letter of the first string is subtracted from that of the second string we get the value in the **D** column below. Taking modulo 5 gives the value **M**. The final value in parentheses is the desired result, **R**.

```
                        D        M     R
                       ---      ---   ---
Rock Rock          ->   0   ->   0   ( 0)
Rock Paper         ->  −2   ->   3   (−1)
Rock Scissors      ->   1   ->   1   ( 1)
Paper Rock         ->   2   ->   2   ( 1)
Paper Paper        ->   0   ->   0   ( 0)
Paper Scissors     ->   3   ->   3   (−1)
Scissors Rock      ->  −1   ->   4   (−1)
Scissors Paper     ->  −3   ->   2   ( 1)
Scissors Scissors  ->   0   ->   0   ( 0)

```

Thus if we compute **D** and then **M**, to obtain **R** we only need to map 0 to 0; 1 and 2 to 1; 3 and 4 to −1. This can be done by indexing into an array of five entries equal to 0, 1 or −1. Since indexing in MATL is 1-based and modular, the array should be `[1, 1, −1, −1, 0]` (the first entry has index 1, the last has index 5 or equivalently 0). Finally, the modulo 5 operation can luckily be avoided, because it is implicitly carried out by the modular indexing.

```
TT     % Push [1 1]
t_     % Duplicate, negate: pushes [−1 −1]
0      % Push 0
v      % Concatenate vertically into the 5×1 array [1; 1; −1; −1; 0]
i      % Input cell array of strings
c      % Convert to 2D char array, right-padding with zeros if necessary
1Z)    % Take the first column. Gives a 2×1 array of the initial letters
d      % Difference
)      % Index into array. Implicit display

```

# Answer
> 5 votes
# CJam, 12 bytes

```
0XXWW]rcrc-=

```

The two inputs are space-separated. Their order is reversed with respect to that in the challenge text.

Try it online! Or verify all test cases.

### Explanation

Translation of my MATL answer. This exploits the fact that in CJam `c` (convert to char) applied on a string takes its first character. Also, the array for the mapping is different because indexing in CJam is 0-based.

```
0XXWW    e# Push 0, 1, 1, -1, -1
]        e# Pack into an array
rc       e# Read whitespace-separated token as a string, and take its first char
rc       e# Again
-        e# Subtract code points of characters
=        e# Index into array. Implicitly display

```

# Answer
> 4 votes
# dc, 18

```
1?Z9+2/rZ1+2/-3%-p

```

Try it online.

Note that the two args are passed (space-separated) on one line to STDIN. The args are contained in square brackets `[ ]` as this is how `dc` likes its strings.

`dc` has *very* limited string handling, but it turns out one of the things you can do is use the `Z` command to get a string length, which luckily is distinct for "Rock", "Paper" and "Scissors", and can be fairly simply arithmetically manipulated to give the desired result.

# Answer
> 4 votes
# Java 7, 82 bytes

```
int c(String...a){int x=(a[0].charAt(1)-a[1].charAt(1))%5/2;return x%2==x?x:x/-2;}

```

**Ungolfed:**

```
int c(String... a){
   int x = (a[0].charAt(1) - a[1].charAt(1)) % 5 / 2;
   return x%2 == x
           ? x
           : x / -2;
}

```

**Explanation:**

* The second letters are `o`, `a` and `c`, with the ASCII decimals `111`, `97` and `99`.
* If we subtract these from each other for the test cases we have the following results:
    + `0` (Rock, Rock)
    + `14` (Rock, Paper)
    + `12` (Paper, Scissors)
    + `-14` (Paper, Rock)
    + `0` (Paper, Paper)
    + `-2` (Paper, Scissors)
    + `-2` (Scissors, Rock)
    + `2` (Scissors, Paper)
    + `0` (Scissors, Scissors)
* If we take modulo 5 for each, we get `4`, `2`, `-4`, `-2`, `-2`, `2`.
* Divided by 2 `x` is now the following for the test cases:
    + x=0 (Rock, Rock)
    + x=2 (Rock, Paper)
    + x=1 (Paper, Scissors)
    + x=-2 (Paper, Rock)
    + x=0 (Paper, Paper)
    + x=-1 (Paper, Scissors)
    + x=-1 (Scissors, Rock)
    + x=1 (Scissors, Paper)
    + x=0 (Scissors, Scissors)
* Only the `2` and `-2`are incorrect, and should have been `-1` and `1`instead. So if `x%2 != x` (everything above `1` or below `-1`) we divide by `-2` to fix these two 'edge-cases'.

**Test code:**

Try it here.

```
class M{
  static int c(String...a){int x=(a[0].charAt(1)-a[1].charAt(1))%5/2;return x%2==x?x:x/-2;}

  public static void main(String[] a){
    String R = "Rock",
           P = "Paper",
           S = "Scissors";
    System.out.println(c(R, R)); // 0
    System.out.println(c(R, P)); // -1
    System.out.println(c(R, S)); // 1
    System.out.println(c(P, R)); // 1
    System.out.println(c(P, P)); // 0
    System.out.println(c(P, S)); // -1
    System.out.println(c(S, R)); // -1
    System.out.println(c(S, P)); // 1
    System.out.println(c(S, S)); // 0
  }
}

```

**Output:**

```
0
-1
1
1
0
-1
-1
1
0

```

# Answer
> 4 votes
# JavaScript, ~~37~~, ~~32~~, 31 bytes

```
a=>b=>a==b?0:!(a+b)[12]^a>b||-1

```

If a equals b, output zero.

Otherwise, xor the result of checking if length not greater than 12 (comparison of Scissors and Paper) with the comparison of a greater than b.
If this returns 1, return it.

If it returns 0, use the OR operator to replace with -1.

# Answer
> 4 votes
# PHP, 34 bytes

```
<?=md5("BMn$argv[1]$argv[2]")%3-1;

```

# Answer
> 4 votes
# Perl 5 `-p`, 24 bytes

```
$_=/kS|rR|sP/-/kP|rS|sR/

```

The input should be on stdin without separators, e.g.:

```
echo PaperRock | perl -pe'$_=/kS|rR|sP/-/kP|rS|sR/'

```

The first regexp searches for first player win, the second for his loss. The difference is printed.

Try it online!

# Answer
> 3 votes
# C#, ~~85~~ 84 bytes

Saved 1 byte, thanks to TheLethalCoder

```
a=>b=>a==b?0:(a[0]=='R'&b[0]=='S')|(a[0]=='P'&b[0]=='R')|(a[0]=='S'&b[0]=='P')?1:-1;

```

It accepts two strings as an input, and outputs an integer. There is a tie, if the two strings are equal, otherwise it checks for the first charachter of the strings, in order to determine, which player wins.

# Answer
> 3 votes
# Pyth, 16

```
t%+7h.+mx3ldQ3

```

Probably could be shorter.

```
        x3ld      # lambda to get string length then XOR with 3
       m    Q     # map over the input (array of 2 strings)
     .+           # difference of the two results
    h             # flatten one-element array
  +7              # add 7
 %           3    # mod 3
t                 # subtract 1 and implicit print

```

Online.

# Answer
> 2 votes
## Perl, 33 bytes

32 bytes of code + `-p` flag.

```
$_=/(.+) \1/?0:-/k P|r S|s R/||1

```

To run it:

```
perl -pe '$_=/(.+) \1/?0:-/k P|r S|s R/||1' <<< "Rock Paper"

```

*Saved 3 bytes by using the regex of Martin Ender's Retina answer. (my previous regex was `/R.*P|P.*S|S.*R/`)*

**Explanation:**

First, `/(.+) \1/` checks if the input contains twice the same word, if so, the result is `0`. Otherwise, `/k P|r S|s R/` deals with the case where the answer is `-1`. If this last regex is false, then `-/k P|r S|s R/`is false, so we return `1`.

# Answer
> 2 votes
## Batch, 116 bytes

```
@if %1==%2 echo 0&exit/b
@for %%a in (RockScissors PaperRock ScissorsPaper)do @if %%a==%1%2 echo 1&exit/b
@echo -1

```

# Answer
> 2 votes
# Japt, 19 bytes

```
-Ms(4*(Uc -Vc)/MP¹r

```

Try it here!

<sub>Inspired by carusocomputing's solution</sub>

Old 53-byte Solution

```
W=Ug c X=Vg c W¥X?0:W¥82©X¥83?1:W¥80©X¥82?1:W¥83©X¥80?1:J

```

Try it online!

<sub>Thanks again, ETHproductions!</sub>

# Answer
> 2 votes
# Jelly, 9 bytes

```
L€^3Iæ%1.

```

This uses the algorithm from @DigitalTrauma's Bash answer.

Try it online!

### How it works

```
L€^3Iæ%1.  Main link. Argument: A (string array)

L€         Take the length of each string.
  ^3       XOR the lengths bitwise with 3.
    I      Increments; compute the forward difference of both results.
     æ%1.  Balanced modulo 1.5; map the results into the interval (-1.5, 1.5].

```

# Answer
> 2 votes
# PHP, ~~55~~ 53 bytes

```
<?=(3-(ord($argv[2])%6%4-ord($argv[1])%6%4+3)%3*2)%3;

```
* takes the ascii values of the first letters (from command line arguments): 82,80,83
* %6: 4,2,5
* %4: 0,2,1
* difference (b-a):
    + PS:1-2,SR:2-0,RP:2-0 -\> -1 or 2; +3,%3 -\> 2
    + SP:2-1,RS:0-2,PR:0-2 -\> -2 or 1; +3,%3 -\> 1
    + RR,PP,SS:0; +3,%3: 0
* (3-2\*x): -1,1,3
* %3: -1,1,0

**sine version, ~~49~~ 46 bytes**

```
<?=2*sin(1.3*(ord($argv[2])-ord($argv[1])))|0;

```

a golfed port of carusocomputing´s answer:

3 bytes saved by @user59178

# Answer
> 2 votes
## Python 2, 32 bytes

```
lambda*l:cmp(*l)*(1|-('R'in`l`))

```

Try it online

A fairly short "natural" solution, though not as short as Dennis's brute-forced solution.

The `cmp(*l)` compares the inputs lexicographically, giving -1, 0, or +1 for smaller, equal, and greater. This gives the right negated answer on each pair of `"Paper", "Rock", "Scissors"` except on Paper vs Scissors in either order. To fix that, we multiply by -1 on any input without an 'R' in the string rep. This also flips Scissors vs Scissors and Paper vs Paper, but those gave 0 anyway.

Thanks to xsot for saving a byte with the `(1|-(_))` construct to turn a Bool into ±1. This is shorter than the alternatives.

```
lambda*l:cmp(*l)*cmp(.5,'R'in`l`)
lambda*l:cmp(*l)*(-1)**('R'in`l`)
lambda*l:cmp(*l)*(1-2*('R'in`l`))

```

# Answer
> 2 votes
# APL (Dyalog Unicode), 12 bytes

```
1-3|1+1-.⊃⍒¨

```

Try it online!

ngn's solution.

# APL (Dyalog Extended), ~~28~~ ~~26~~ ~~19~~ 18 bytes

```
(××¯1*3>|)-⍥⎕UCS⍥⊃

```

Try it online!

Jo King's similar train based solution.(-3 bytes)

(⍥ function is new in Dyalog 18.0, a polyfill is used instead in TIO.)

-2 more bytes from Jo King.

-7 bytes golfed by Bubbler.

-1 byte from Adám (change to Dyalog Extended)

# APL (Dyalog Unicode), 31 bytes

```
{¯1 1 1 0 ¯1 ¯1 1[3+-/⎕UCS⊃¨⍵]}

```

Subtracts the unicode values of the first character of each string.

Then adds three to the difference, and returns the correct value as per this mapping:

```
 0  1  2  3  4  5  6
---------------------
-1  1  1  0 -1 -1  1

```

## Code Explanation:

```
{¯1 1 1 0 ¯1 ¯1 1[3+-/⎕UCS⊃¨⍵]}
                           ¨⍵   For each value of ⍵
                          ⊃     Get the first letters
                      ⎕UCS      Transform them to their Unicode codepoints
                    -/          Reduce them by subtraction
                  3+            Add three to the difference
{¯1 1 1 0 ¯1 ¯1 1[           ]} Return the value, using the difference +3 as index

```

Try it online!

# Answer
> 1 votes
## Scala, 148 bytes

```
object R extends App{val t=Seq('R','P','S')
val(a,b)=(args(0)(0),args(1)(0))
print(if(a==b)0 else if(t.indexOf(a)%3==(t.indexOf(b)-1)%3)-1 else 1)}

```

Thankfully, since semicolons are required to separate multiple commands on the same line, Scala benefits from having formattable golf code!

In this golfing attempt I learned that you can replace

```
"somestring".charAt(index)

```

with

```
"somestring"(index)

```

because Scala lets you treat strings as arrays for the purpose of getting characters.

# Answer
> 1 votes
# C++, 98 bytes#

```
int main(int c,char*v[]){int a=v[2][0]-v[1][0];if(a%3==0)a=-a;if(a>1)a/=a;if(a<-1)a/=-a;return a;}

```

Could definitely be shortened, but I don't have that skill or knowledge. Enlightenment?

# Answer
> 1 votes
# GNU Sed, ~~39~~, 38 bytes

*36* bytes code + *2* bytes for the "nr" flags

**Golfed**

```
/^(.+)\1/{a0
b}
/kP|rS|sR/{a-1
b}
a1

```

**Test**

```
>RPS() { echo "$1 => "`sed -rnf rps.sed<<<$1`; }

>RPS RockRock
RockRock => 0

>RPS RockPaper
RockPaper => -1

>RPS RockScissors
RockScissors => 1

>RPS PaperRock
PaperRock => 1

>RPS PaperPaper
PaperPaper => 0

>RPS PaperScissors
PaperScissors => -1

>RPS ScissorsRock
ScissorsRock => -1

>RPS ScissorsPaper
ScissorsPaper => 1

>RPS ScissorsScissors
ScissorsScissors => 0

```

# Answer
> 1 votes
# ///, 87 bytes

```
/_/1\/\///Paper/p//Rock/r//Scissors/s// ///pr/_rs/_sp/_rp/-_sr/-_ps/-_pp/0//rr/0//ss/0/

```

**Try it online!**

## Ungolfed

```
/Paper/p//Rock/r//Scissors/s// //
/pr/1//rs/1//sp/1/
/rp/-1//sr/-1//ps/-1/
/pp/0//rr/0//ss/0/

```

# Answer
> 1 votes
## Clojure, 43 bytes

```
#(get[0 1 1](mod(-(count %)(count %2))6)-1)

```

Uses `(length(arg_1) - length(arg_2)) % 6` as a lookup to `[0 1 1]` and returns `-1` if it goes out of bounds.

# Answer
> 1 votes
# Clojure, ~~114~~ 75 bytes

-39 bytes by accepting 2 parameters instead of parsing 1, and changing the "else" placeholder from `:e` to `0`.

```
 (fn[[p][q]](let[d(-(int p)(int q))](cond(#{-1 -2 3}d)1(#{1 2 -3}d)-1 0 0)))

```

Ungolfed:

```
(defn rps-scorer [[p1] [p2]] ; Deconstruct out the first letters of each word
  (let [d (- (int p1) (int p2))] ; And find the difference of their numeric values
    (cond (#{-1 -2 3} d) 1 ; If it's a winning difference, return 1, else
          (#{1 2 -3} d) -1 ; If it's a losing difference, return -1, else
          :else 0))) ; return 0, because they're the same.

```

Totally naïve approach here. I found out if you subtract the ascii values of the first letter of each play, winning values will be -1, -2 and 3, and losing values will be 1, 2 and -3. I just check which set the plays fall into, then return based on membership.

# Answer
> 1 votes
# C#, 43 bytes

```
a=>b=>(a[0]-b[0])/3*2+Math.Sign(b[0]-a[0]);

```

C# treats characters like integers that you can add and subtract.

# Answer
> 1 votes
# SmileBASIC, 39 bytes

```
INPUT A$,B$?(67XOR LEN(A$*2+B$))MOD 3-1

```

A port of Dennis's algorithm. `XOR` and `MOD` are really long, I'm sure this could be made shorter.

# Answer
> 1 votes
# Zsh, 29 bytes

```
<<<${${:-{,,-,-}1}[#2-#1]:-0}

```

Try it online!

```
<<<${${:-{,,-,-}1}[#2-#1]:-0}
         {,,-,-}1                # expands to the list (1 1 -1 -1)
     ${:-        }               # empty-fallback (anon parameter)
   ${             [     ]   }    # index into list
                   #2-#1         # difference between each parameter's first character's codes
   ${                    :-0}    # if empty, substitute 0

```

This is similar to one of the CJam answers. However, since Zsh indexes from 0, we need the `${ :-0}` empty fallback to handle the `'P' - 'P' => 0` case.

# Answer
> 1 votes
# Ruby -n, 20 bytes

```
p$_.to_i(30)/522%3-1

```

Try it online!

Take input in the form of "RockPaper", interpret it as a base 30 integer 18248834542947, divide by 522 rounding down to 34959453147, modulo 3 is 0, minus 1 is -1.

# Answer
> 1 votes
# , 39 bytes

*with thanks to Giuseppe for bug-spotting*

```
d=diff(nchar(scan(,'')));sign(d)*(-1)^d

```

Try it online!

I came to this challenge 3 years late, but there doesn't seem to be an answer in  yet.
So here's a first shot at it, before browsing the other (currently 51!) answers...

*Edit after some browsing: this approach was already used in Dennis's Jelly answer 3 years ago...*

Uses number of characters in the strings "Rock" (4), "Paper" (5) and "Scissors" (8).
Difference in characters (player 1 - player 2) gives the following table:

```
diff  answer
0  => 0
1  => 1
-1 => -1
3  => 1
-3 => -1
4  => -1
-4 => 1

```

So for all differences with an absolute value below 4, the answer is just the sign. We need to reverse it for absolute values of 4, but not of 1 or 3.
Luckily 1 and 3 are odd, and 4 is even, so we can use powers of -1 (which is -1 for all odd, and 1 for all even numbers).

# Answer
> 1 votes
# LaTeX, 81 bytes

## Function

```
\def~#1#2{\ifcase\numexpr"#1"-"#2"+3{}-1'1'1'0'-1'-1'1\fi}\def"#1#2"{`#1}\let'\or

```

This works by taking the first character of the two strings and using its ASCII-value. Then the difference is used in a switch cases to leave the correct result in the input stream.

## Complete Document

```
\documentclass[preview,border=3.14]{standalone}

\catcode`\"13
\catcode`\'13

\def~#1#2{\ifcase\numexpr"#1"-"#2"+3{}-1'1'1'0'-1'-1'1\fi}\def"#1#2"{`#1}\let'\or

\begin{document}

~{Rock}{Rock} should be 0

~{Rock}{Paper} should be -1

~{Rock}{Scissors} should be 1

~{Paper}{Rock} should be 1

~{Paper}{Paper} should be 0

~{Paper}{Scissors} should be -1

~{Scissors}{Rock} should be -1

~{Scissors}{Paper} should be 1

~{Scissors}{Scissors} should be 0

\end{document}

```

## Results (in PDF)

# Answer
> 1 votes
# Brain-Flak, 210 bytes

```
{({}(<()>))({}[((((()()()()()){}){}){}){}]){({}[()()]){({}[()]){(<{}({}[()()()])>)}(<{}({}())>)}(<{}({}())>)}{}({}()){({}<>)(<>)}{}}<>({}[{}()()]){({}()()()()){(<([()()()])>)}(<(()())>)}(([]){[{}]{}([])}{}[()])

```

Try it online!

```
{                           while input not empty
  ({}(<()>))                push identifier 0 under the first character
  ({}[((((()()()()()){}){}){}){}]) decrement input by 80 "P"
  {                         if not input = "P"
    ({}[()()]){             if not input = "R"
      ({}[()]){             if not input = "S"
        (<{}({}[()()()])>)  character = 0; identifier = -3
      }
      (<{}({}())>)          identifier += 1
    }
    (<{}({}())>)            identifier += 1
  }
  {}                        delete character
  ({}())                    identifier += 1
  {                         if identifier != 0
    ({}<>)                  push it onto the right stack
    (<>)                    return to left stack and push 0 for exit if
  }
  {}                        delete identifier or exit-if-0
}
<>                          go to right stack
({}[{}()()])                result = first item - second item - 2
                            # first - second would return the correct
                            # results for most cases. Only "Paper Scissors"
                            # or "Scissors Paper" results in -2 or 2.
{                           if result != 2
  ({}()()()()){             if result != -2
    (<([()()()])>)          push -3 0
  }
  (<(()())>)                push 2 0
}
(([]){[{}]{}([])}{}[()])    push sum of values - 1

```

# Answer
> 1 votes
Well, no Batch submission so far, So:

# Batch 140 bytes

```
@Set/A RR=PP=SS=0,RP=PS=SR=-1,RS=PR=SP=1&Title press:RSP&@Set "#=@For /F Delims^= %%# in ('Choice /N /C:RSP')Do @"
%#:#=1%%#:#=2%Set %%1%%2

```
* Input is taken via the Choice command In Macro form
* Input Macro uses substring modification to substitute the For metavariable
* Output is done using the set command on the values gained from the input macro to refer to the variables assigned for Win/Draw/Loss.
* 16 bytes could be shaved off by eliminating the Title command + Instructions ("&Title press:RSP")

# Answer
> 1 votes
# Vyxal, 10 bytes

```
vtCƒ-19+ǒ‹

```

Try it Online!

### Explained

```
vtCƒ-19+ǒ‹
v          # vectorise
 t         # tail
  C        # char
   ƒ-      # reduce by substraction
     19+   # +19
        ǒ  # modulus 3
         ‹ # decrement

```

# Answer
> 0 votes
# Perl 6,  ~~63 54 40~~  39 bytes

```
{2>($_=[-] %(<Rock -1 Paper 0 Scissors 1>){@_})>-2??$_!!-.sign}

```

Try it

```
{3>($_=[R-] @_>>.substr(0,1)>>.ord)>-3??.sign!!-.sign}

```

Try it

```
{3>($_=[R-] @_>>.ord)>-3??.sign!!-.sign}

```

Try it

```
{($_=[-](82 X<=>@_».ord)%3)>1??-1!!$_}

```

Try it

# Answer
> 0 votes
# C#, 28 bytes

```
(a,b)=>""[*a-*b+3]-2;

```

Contains unprintable characters, so here's a hex dump:

~~Turns out my solution is pretty similar to Dennis's Python 3 answer, but calculates the index differently.~~ not anymore

This uses `unsafe` so the `string` inputs need to be put in `char*` first.

How it works:

```
// Delegate signature
unsafe delegate int Signature(char* c, char* z);

/*unsafe Signature Lambda = */ (a, b) =>
    "\x1\x3\x3\x2\x1\x1\x3"               // The outcomes
    [*a - *b + 3]                         // Index by subtracting value of first char of p2
                                          // from p1, adding 3 so the result is >= 0
    -2                                    // Subtract 2 to put in range [-1, 1]

```

# Answer
> 0 votes
## C 355 bytes

```
#define S strcmp f(char *a,char *b){*c[]={"Rock","Paper","Scissors"}; if((!S(a,c[0])&&!S(b,c[1]))||(!S(a,c[1])&&!S(b,c[2]))||(!S(a,c[2])&&!S(b,c[0]))==1 )puts("-1");if( (!S(a,c[0])&&!S(b,c[0]))||(!S(a,c[1])&&!S(b,c[1]))||(!S(a,c[2])&&!S(b,c[2]))==1 )puts("0");if( (!S(a,c[0])&&!S(b,c[2]))||(!S(a,c[1])&&!S(b,c[0]))||(!S(a,c[2])&&!S(b,c[1]))==1 )puts("1");}

```

Accept user inputs(`argv[1],argv[2]`) and pass it onto `f(char *a, char *b)`; Here is the Ungolfed version:

```
 #define S strcmp
 void f(char *a,char *b)
 {
   char *c[]={"Rock","Paper","Scissors"};
   if( (!S(a,c[0])&&!S(b,c[1]))||(!S(a,c[1])&&!S(b,c[2]))||(!S(a,c[2])&&!S(b,c[0]))==1 )
     puts("-1");
   if( (!S(a,c[0])&&!S(b,c[0]))||(!S(a,c[1])&&!S(b,c[1]))||(!S(a,c[2])&&!S(b,c[2]))==1 )
     puts("0");
   if( (!S(a,c[0])&&!S(b,c[2]))||(!S(a,c[1])&&!S(b,c[0]))||(!S(a,c[2])&&!S(b,c[1]))==1 )
     puts("1");
 }

```

There must definitely be a way to shorten this! I don't know though.

@Timtech Hope i understood you right. This code works, but prints 0 even if the strings are not exact, not sure if that satisfies the specification.

```
`#define S strcmp f(){printf("%d",(!S(a,c[0])&&!S(b,c[1])||!S(a,c[1])&&!S(b,c[2])||!S(a,c[2])&&!S(b,c[0]))?-1:(!S(a,c[0])&&!S(b,c[2])||!S(a,c[1])&&!S(b,c[0])||(!S(a,c[2])&&!S(b,c[1]) )?1:0));}

```

# Answer
> 0 votes
# TI-Basic, 64 bytes

There is probably a shorter way but I'm not seeing it right now...

```
DelVar R1->P:2->S
Prompt Str1,Str2:1
If sum(not({~2,1}-sum(eval(sub(Str1,1,1)+"-"+sub(Str2,1,1
~1:Str1!=Str2

```

# Answer
> 0 votes
# TI-84 BASIC, 55 bytes

```
Prompt Str1,Str2
sub(Str1,1,1→Str3
sub(Str2,1,1
(Str3≠Ans)*(1-2not(inString("SPPRRS",Str3+Ans

```

I saved a byte by using `Prompt` instead of `Input` thanks to Timtech.

## Execution:

Input is given as two strings as prompted. The TI-84 does not have native lowercase letters.

```
prgmRPS
Str1=?"ROCK"
Str2=?"SCISSORS"

               1

```

# Answer
> 0 votes
## C#, 48 bytes

```
(a,b)=>a==b?0:(a[0]>b[0])^(a[0]+b[0]==163)?-1:1;

```

# Answer
> 0 votes
# Noodel, 21 bytes

```
1220200Ḷ2ėạȥḃ1€Ė⁻ạɲ⁻1

```

Try it:)

### How It Works

The first input is the first player:) It works by using the first character of both the string inputs then subtract them. Then using that result to index into an string to get the correct value.

The result from each game after subtracting the values of the first characters:

```
"Rock"     -> "Rock"     =  0
"Rock"     -> "Paper"    = -2
"Rock"     -> "Scissors" =  1
"Paper"    -> "Rock"     =  2
"Paper"    -> "Paper"    =  0
"Paper"    -> "Scissors" =  3
"Scissors" -> "Rock"     = -1
"Scissors" -> "Paper"    = -3
"Scissors" -> "Scissors" =  0

```

How each position in the string is used to correspond to which game:

```
[0] or [-7] = 1 => "Rock" -> "Rock", "Paper" -> "Paper", "Scissors" -> "Scissors"
[1] or [-6] = 2 => "Rock" -> "Scissors"
[2] or [-5] = 2 => "Paper" -> "Rock"
[3] or [-4] = 0 => "Paper" -> "Scissors"
[4] or [-3] = 2 => "Scissors" -> "Paper"
[5] or [-2] = 0 => "Rock" -> "Paper"
[6] or [-1] = 0 => "Scissors" -> "Rock"

```

Break down of the actual script:

```
1220200               # Pushes the string "1220200" onto the stack.

       Ḷ2ėạȥḃ1€       # A loop that grabs the first character, turns it into a number, and then throws away the string.
       Ḷ2             # Loop the following block two times.
         ė            # Places what is on the top to the bottom (first loop is the string created before, second loop places the result of player two)
          ạ           # Grabs the first element of the string.
           ȥ          # Convert the string to a number as if it was a base 98 number.
            ḃ1        # Remove the second item off of the stack.
              €       # End of the loop.

               Ė⁻     # Grabs what is at the bottom of the stack then subtracts what was on the top from that.
               Ė      # Grabs what is at the bottom of the stack (which is the first number calculated (player two).
                ⁻     # Subtracts player one from player two producing the index into the string.

                 ạɲ⁻1 # Grabs an element from the string and decrements it by one to get the final result.
                 ạ    # Access the string based off of the number produced from the subtraction.
                  ɲ   # Turns that string into a number.
                   ⁻1 # Subtracts one from that number.

```

# Answer
> 0 votes
# Common Lisp, 83 bytes

```
(setq c(- #1=(char-code(elt(read)0))#1#))(cond((= c 0)0)((member c'(1 2 -3))-1)(1))

```

Try it online!

The algorithm is ported from Carcigenicate’s answer.

# Answer
> 0 votes
# C#, 151 bytes

```
public class P{public static void Main(string[]a){int v=(a[0][0]-a[1][0]);v=v==2?-1:v==-1?1:v==-2?1:v==0?0:v==1?-1:v==3?1:-1;System.Console.Write(v);}}

```

Try Online

# Answer
> 0 votes
# Rust, ~~110~~ 107 bytes

```
fn r(a:&str,b:&str)->i8{let p=if a.as_bytes()[0]+b.as_bytes()[0]==163{(b,a)}else{(a,b)};p.1.cmp(&p.0)as i8}

```

Try it online!

# Answer
> 0 votes
# Thunno 2, 9 bytes

```
C€tẸ-⁺3%⁻

```

Attempt This Online!

Somehow passes all the test cases (I checked all 9).

#### Explanation

```
C€tẸ-⁺3%⁻  # Implicit input
C          # Convert to codepoints
 €t        # Last item of each
   Ẹ-      # Reduce by subtraction
     ⁺     # Increment
      3%   # Mod 3
        ⁻  # Decrement
           # Implicit output

```

---
Tags: code-golf, game
---


title: My daughter's alphabet

text:
# Question
Title: My daughter's alphabet
The other day we were writing sentences with my daughter with a fridge magnet letter. While we were able to make some(`I love cat`), we didn't have enough letters to make the others (`I love you too`) due to an insufficient amount of letters `o` (4)

I then found out that while one set included 3 `e` letters it had only 2 `o` letters. Probably inspired by http://en.wikipedia.org/wiki/Letter\_frequency this would still not reflect the actual situation "on the fridge".

## Problem

Given the text file where each line contains a "sample sentence" one would want to write on the fridge, propose an alphabet set with minimum amount of letters but still sufficient to write each sentence individually.

Note: ignore cases, all magnet letters are capitals anyway.

## Input

The file contain newline separated sentences:

```
hello
i love cat
i love dog
i love mommy
mommy loves daddy

```

## Output

Provide back sorted list of letters, where each letter appears only as many times to be sufficient to write any sentence:

```
acdddeghillmmmoostvyy

```

(thanks, isaacg!)

## Winner

Shortest implementation (code)

### UPDATED: Testing

I have created an extra test and tried with various answers here:

https://gist.github.com/romaninsh/11159751

# Answer
> 18 votes
# GolfScript, 28 / 34 chars

```
n/:a{|}*{a{.[2$]--}%*$-1=}%$

```

The 28-character program above assumes that all the input letters are in the same case. If this is not necessarily so, we can force them into upper case by prepending `{95&}%` to the code, for a total of 34 chars:

```
{95&}%n/:a{|}*{a{.[2$]--}%*$-1=}%$

```

Notes:

* For correct operation, the input must include at least one newline. This will be true for normal text files with newlines at the end of each line, but might not be true if the input consists of just one line with no trailing newline. This could be fixed at the cost of two extra chars, by prepending `n+` to the code.
* The uppercasing used in the 34-character version is really crude — it maps lowercase ASCII letters to their uppercase equivalents (and spaces to `NUL`s), but makes a complete mess of numbers and most punctuation. I'm assuming that the input will not include any such characters.
* The 28-character version treats all input characters (except newlines and `NUL`s) equally. In particular, if the input contains any spaces, some will also appear in the output; conveniently, they will sort before any other printable ASCII characters. The 34-character version, however, does ignore spaces (because it turns out I can do that without it costing me any extra chars).

Explanation:

* The optional `{95&}%` prefix uppercases the input by zeroing out the sixth bit of the ASCII code of each input byte (`95 = 64 + 31 = 1011111<sub>2</sub>`). This maps lowercase ASCII letters to uppercase, spaces to null bytes, and leaves newlines unchanged.
* `n/` splits the input at newlines, and `:a` assigns the resulting array into the variable `a`. Then `{|}*` computes the set union of the strings in the array, which (assuming that the array has at least two elements) yields a string containing all the unique (non-newline) characters in the input.
* The following `{ }%` loop then iterates over each of these unique characters. Inside the loop body, the inner loop `a{.[2$]--}%` iterates over the strings in the array `a`, removing from each string all characters not equal to the one the outer loop is iterating over.

The inner loop leaves the ASCII code of the current character on the stack, below the filtered array. We make use of this by repeating the filtered array as many times as indicated by the ASCII code (`*`) before sorting it (`$`) and taking the last element (`-1=`). In effect, this yields the longest string in the filtered array (as they all consist of repeats of the same character, lexicographic sorting just sorts them by length), *except* if the character has ASCII code zero, in which case it yields nothing.
* Finally, the `$` at the end just sorts the output alphabetically.

# Answer
> 13 votes
# J - 37 char

Reads from stdin, outputs to console.

```
dlb#&a.>./+/"2=/&a.tolower;._2[1!:1]3

```

`1!:1]3` is the call to stdin. `tolower;._2` performs double duty by splitting up the lines and making them lowercase simultaneously. Then we count how many times a character occurs in each row with `+/"2=/&a.`, and take the pointwise maximum over all lines with `>./`.

Finally, we pull that many of each character out of the alphabet with `#&a.`. This includes spaces—all found at the front due to their low ASCII value—so we just delete leading blanks with `dlb`.

# Answer
> 12 votes
# JavaScript (ECMAScript 6) - ~~148~~ ~~139~~ 135 Characters

**Version 2:**

Updated to use array comprehension:

```
[a[i][0]for(i in a=[].concat(...s.split('\n').map(x=>x.split(/ */).sort().map((x,i,a)=>x+(a[i-1]==x?++j:j=0)))).sort())if(a[i-1]<a[i])]

```

**Version 1:**

```
[].concat(...s.split('\n').map(x=>x.split(/ */).sort().map((x,i,a)=>x+(a[i-1]==x?++j:j=0)))).sort().filter((x,i,a)=>a[i-1]!=x).map(x=>x[0])

```

Assumes that:

* The input string is in the variable `s`;
* We can ignore the case of the input (as specified by the question - i.e. it is all in either upper or lower case);
* The output is an array of characters (which is about as close as JavaScript can get to the OP's requirement of a list of characters); and
* The output is to be displayed on the console.

With comments:

```
var l = s.split('\n')             // split the input up into sentences
         .map(x=>x.split(/ */)   // split each sentence up into letters ignoring any
                                  // whitespace
                  .sort()         // sort the letters in each sentence alphabetically
                  .map((x,i,a)=>x+(a[i-1]==x?++j:j=0)))
                                  // append the frequency of previously occurring identical
                                  // letters in the same sentence to each letter.
                                  // I.e. "HELLO WORLD" =>
                                  // ["D0","E0","H0","L0","L1","L2","O0","O1","R0","W0"]
[].concat(...l)                   // Flatten the array of arrays of letters+frequencies
                                  // into a single array.
  .sort()                         // Sort all the letters and appended frequencies
                                  // alphabetically.
  .filter((x,i,a)=>a[i-1]!=x)     // Remove duplicates and return the sorted
  .map(x=>x[0])                   // Get the first letter of each entry (removing the
                                  // frequencies) and return the array.

```

If you want to:

* Return it as a string then add `.join('')` on the end;
* Take input from a user then replace the `s` variable with `prompt()`; or
* Write it as a function `f` then add `f=s=>` to the beginning.

**Running:**

```
s="HELLO\nI LOVE CAT\nI LOVE DOG\nI LOVE MOMMY\nMOMMY LOVE DADDY";
[].concat(...s.split('\n').map(x=>x.split(/ */).sort().map((x,i,a)=>x+(a[i-1]==x?++j:j=0)))).sort().filter((x,i,a)=>a[i-1]!=x).map(x=>x[0])

```

**Gives the output:**

```
["A","C","D","D","D","E","G","H","I","L","L","M","M","M","O","O","T","V","Y","Y"]

```

# Answer
> 11 votes
## Perl - 46 bytes

```
#!perl -p
$s=~s/$_//ifor/./g;$s.=uc}for(sort$s=~/\w/g){

```

Counting the shebang as 1. This is a loose translation of the Ruby solution below.

---

## Ruby 1.8 - 72 bytes

```
s='';s+=$_.upcase.scan(/./){s.sub!$&,''}while gets;$><<s.scan(/\w/).sort

```

Input is taken from `stdin`.

Sample usage:

```
$ more in.dat
Hello
I love cat
I love dog
I love mommy
Mommy loves daddy

$ ruby fridge-letters.rb < in.dat
ACDDDEGHILLMMMOOSTVYY

```

# Answer
> 9 votes
# Python - ~~206~~ ~~204~~ ~~199~~ ~~177~~ ~~145~~ ~~129~~ ~~117~~ ~~94~~ 88 chars

```
print(''.join(c*max(l.lower().count(c)for l in open(f))for c in map(chr,range(97,123))))

```

I wasn't sure how I was supposed to obtain the file name, so at the moment the code assumes that it is contained in a variable named `f`. Please let me know if I need to change that.

# Answer
> 6 votes
## Ruby 1.9+, 51 (or 58 or 60)

```
a=*$<
?a.upto(?z){|c|$><<c*a.map{|l|l.count c}.max}

```

Assumes everything's in lowercase. Case insensitivity costs 7 characters via `.upcase`, while case insensitivity *and lowercase output* costs 9 characters via `.downcase`.

# Answer
> 4 votes
# R (156, incl. file read)

With *table* I construct the letter frequency table for each sentence. Then I end up with taking for each letter the maximum value.

```
a=c();for(w in tolower(read.csv(fn,h=F)$V1))a=c(a,table(strsplit(w,"")[[1]]));a=tapply(seq(a),names(a),function(i)max(a[i]))[-1];cat(rep(names(a),a),sep="")

```

Ungolfed:

```
a=c()
words = read.csv(fn,h=F)$V1
for(w in tolower(words))
  a=c(a, table(strsplit(w, "")[[1]]))
a = tapply(seq(a), names(a), function(i) max(a[i]))[-1] ## The -1 excludes the space count.
cat(rep(names(a), a), sep="")

```

Solution:

```
acdddeghillmmmoooooostuvyy

```

# Answer
> 4 votes
# Haskell, ~~109~~ 108

```
import Data.List
import Data.Char
main=interact$sort.filter(/=' ').foldl1(\x y->x++(y\\x)).lines.map toLower

```

The program reads from stdin and writes to sdtout.

It is quite straightforward: it breaks the string into a list of lines, and rebuilds it by iterating on the list and adding the new letters contained in each line.

# Answer
> 4 votes
# Perl 6: ~~56~~ *53* characters; ~~58~~ *55* bytes

```
say |sort
([∪] lines.map:{bag comb /\S/,.lc}).pick(*)

```

For each line, this combs through it for the non-space characters of the lower-cased string (`comb /\S/,.lc`), and makes a `Bag`, or a collection of each character and how many times it occurs. `[∪]` takes the union of the `Bag`s over all the lines, which gets the max number of times the character occurred. `.pick(*)` is hack-y here, but it's the shortest way to get all the characters from the `Bag` replicated by the number of times it occurred.

EDIT: To see if it would be shorter, I tried translating histocrat's Ruby answer. It is 63 characters, but I still very much like the approach:

```
$!=lines».lc;->$c{print $c x max $!.map:{+m:g/$c/}} for"a".."z"

```

# Answer
> 3 votes
# Haskell, 183 162 159

Assuming the file is in `file.txt`!

```
import Data.Char
import Data.List
main=readFile"file.txt">>=putStr.concat.tail.map(tail.maximum).transpose.map(group.sort.(++' ':['a'..'z'])).lines.map toLower

```

If file.txt contains, for example

```
abcde
abcdef
aaf

```

The script will output

```
aabcdef

```

Basically I'm appending the whole alphabet to each line, so that when grouping and sorting, I'm sure I'll end up with a list that contains 27 elements. Next, I transpose the "frequency table", so that each row in this array consists of the frequencies of a single letter in each line, e.g. `["a","","aaa","aa","aaaa"]`. I then choose the maximum of each array (which works just like I want because of how the `Ord`-instance of Strings work), and drop the letter that I appended at the start, get rid of the spaces, and output the result.

# Answer
> 3 votes
## Javascript, 261 chars

```
eval('s=prompt().toUpperCase().split("\\n");Z=[########0,0];H=Z.slice();s@r){h=Z.slice();r.split("")@c){if(c.match(/\\w/))h[c.charCodeAt(0)-65]++});H=H@V,i){return V>h[i]?V:h[i]})});s="";H@n,i){s+=Array(n+1).join(String.fromCharCode(i+97))});s'.replace(/@/g,".map(function(").replace(/#/g,"0,0,0,"))

```

Remove the `eval(...)` and execute to get the real code; this is (*somewhat*) compressed.

`s` multi-functions as the array of lines and as the outputted string, `h` contains the histogram of the letters per line and `H` contains the histogram with the maximum values up until now. It's case-insensitive, and just ignores anything but a-z and A-Z (I think... JS arrays are sometimes weird).

<sub>*Now correct :)*</sub>

# Answer
> 3 votes
# Bash, 171 ~~159~~ 158, 138 with junk output

Requires lowercase-only input. Assumes that the file is called `_` (underscore). Maximum of 26 lines in the input file due to the annoying filenames which `split` creates (xaa, xab... xaz, ???).

In `bash`, `{a..z}` outputs `a b c d e f ...`.

```
touch {a..z}
split _ -1
for l in {a..z}
do for s in {a..z}
do grep -so $l xa$s>b$l
if [ `wc -l<b$l` -ge `wc -l<$l` ]
then mv b$l $l
fi
done
tr -d '\n'<$l
done

```

# Sample output

```
acdddeghillmmmoostvyy

```

# Explanation

```
touch {a..z}

```

Create files that we will be reading from later on so that bash doesn't complain that they don't exist. If you remove this line you will save 13 chars but get a lot of junk output.

```
split _ -1

```

Split the input file into sections, each storing 1 line. The files this command creates are named xaa, xab, xac and so on, I have no idea why.

```
for l in {a..z}
do for s in {a..z}

```

For each letter `$l` read through all lines stored in files `xa$s`.

```
do grep -so $l xa$s>b$l

```

Remove the `-s` switch to save 1 char and get a lot of junk output. It prevents `grep` from complaining about nonexistent files (will occur unless you have 26 lines of input). This processes the file `xa$s`, removing anything but occurences of `$l`, and sending output to the file `b$l`. So "i love mommy" becomes "mmm" with new lines after each letter when `$l` is m.

```
if [ `wc -l<b$l` -ge `wc -l<$l` ]

```

If the number of lines in the file we just created is greater than or equal to (i.e. more letters since there is one letter per line) the number of lines in our highest result so far (stored in `$l`)...

```
then mv b$l $l

```

...store our new record in the file `$l`. At the end of this loop, when we have gone through all the lines, the file `$l` will store x lines each containing the letter `$l`, where x is the highest number of occurences of that letter in a single line.

```
fi
done
tr -d '\n'<$l

```

Output the contents of our file for that particular letter, removing new lines. If you don't want to remove the new lines, change the line with `tr` to `echo $l`, saving 6 chars.

```
done

```

# Answer
> 3 votes
**C, 99 chars**

```
t[256];main(c){for(--*t;++t[1+tolower(getchar())];);for(c=97;c<123;c++)while(t[c]--)putchar(c-1);}

```

It crashes if less than one newline is provided. I think it could be fixed quite easily.

# Answer
> 3 votes
## kdb (q/k): 59 characters:

```
d:.Q.a! 26#0
.z.pi:{d|:.Q.a##:'=_y}.z.exit:{-1@,/.:[d]#'!:d}

```
* generate pre-sorted seed dictionary from alphabet .Q.a
* process each line of input, convert to lowercase, group into dictionary, count each element, take alphabetic characters from result (I.e. prune spaces, newlines, etc at this stage) and use max-assign to global d to keep a running total.
* define exit handler, which gets passed in to .z.pi to save a delimiter but otherwise unused there. Take from each key-value to generate list of characters, flatten and finally print to stdout.

-1 adds a newline, using 1 would save a character but does not generate the output specified. Wish I could get rid of the .z.pi / .z.exit boilerplate, which would remove 14 characters.

Edit: avoid use of inter/asc by using seed dictionary.

# Answer
> 3 votes
## Perl, 46

```
for$:(a..z){$a[ord$:]|=$:x s/$://gi}}{print@a

```

Here's another Perl solution, reads from STDIN, requires `-n` switch (+1 to count), ties with primo's score but runs without complaints :-). It exploits the fact that bitwise `or`'s result has longer string argument's length.

# Answer
> 3 votes
## C#, 172 bytes

```
var x="";foreach(var i in File.ReadAllText(t).ToLower().Split('\r','\n'))foreach(var j in i)if(x.Count(c=>c==j)<i.Count(c=>c==j))x+=j;string.Concat(x.OrderBy(o=>o)).Trim();

```

# Answer
> 3 votes
I'm adding my own solution:

## Bash - 72

Assumes that input is in file "i"

```
for x in {A..Z};do echo -n `cat i|sed "s/[^$x]//g"|sort -r|head -1`;done

```

## Explanation

For each possible letter, filters it out only from input file resulting in something like this:

```
AAA
A
A

AAAA

A
AAAAAAAAAAAAAAAA

```

Then result is sorted and the longest line is selected. `echo -n` is there to remove newlines.

# Answer
> 3 votes
# 05AB1E, ~~12~~ ~~10~~ 8 bytes

```
Aεδ¢ày×?

```

-2 bytes thanks to *@ovs*, which also allowed -2 more bytes.

Input taken as a list of lowercase strings. (Would require 1 additional byte if taking the input newline-delimited is mandatory.)

Try it online.

**Explanation:**

```
A        # Push the lowercase alphabet
 ε       # For-each over the letters:
  δ¢     #  Count how many times this letter occurs in each string of the (implicit)
         #  input-list
    à    #  Pop and leave the maximum of these counts
     y×  #  Repeat the current letter that many times
       ? #  And print it (without newline)

```

# Answer
> 2 votes
# Python 2 - 129

Idea from @Tal

```
a,r=[0]*26,range(26)
for l in open('f'):a=[max(a[i],l.lower().count(chr(i+97)))for i in r]
print''.join(chr(i+97)*a[i]for i in r)

```

A couple more ways to do the same thing in the same number of characters:

```
a=[0]*26
b='(chr(i+97)))for i in range(26)'
exec'for l in open("f"):a=[max(a[i],l.lower().count'+b+']\nprint"".join(a[i]*('+b+')'

a=[0]*26
b='(chr(i+97)))for i in range(26))'
exec'for l in open("f"):a=list(max(a[i],l.lower().count'+b+'\nprint"".join(a[i]*('+b

```

This assumes the file is saved as f in an accessible directory. This program is directly runable, with no extra input necessary.

# Answer
> 2 votes
## Mathematica v10 - 110

It's not out yet, but reading new documentation very carefully, I think this should work:

```
StringJoin@MapIndexed[#2~Table~{#1}&,Rest@Merge[Counts/@Characters@StringSplit[ToLowerCase@Input[],"\n"],Max]]

```

# Answer
> 2 votes
# Scala, 125 characters

```
val i=""::io.Source.stdin.getLines.toList.map(_.toLowerCase);println('a'to'z'map(c=>(""+c)*i.map(_.count(_==c)).max)mkString)

```

First I read the input, converting it into lower case and adding one empty line.

Then for each letter from `a` to `z` I repeat that letter maximum number of times it appears in any of the lines (that's why I need the empty line: `max` cannot be called on an enpty input). Then I just join the results and print to the output.

To read from a file, replace `stdin` with `fromFile("FILENAME")`, increasing the size of the code to 132 characters + file name length.

# Answer
> 2 votes
# JavaScript (*ES5*) 141 bytes

Assuming variable `s` is the input string with no case-checking requirements and array output:

```
for(a in s=s[o=_='',y='split']('\n'))for(i=0;x=s[a][i++];)o+=x!=0&&(l=s[a][y](x).length-~-o[y](x).length)>0?Array(l).join(x):_;o[y](_).sort()

```

# Answer
> 2 votes
## Groovy, 113/127 102/116 characters

Assuming the file is all in one case (102 chars):

```
t=new File('f').text;t.findAll('[A-Z]').unique().sort().each{c->print c*t.readLines()*.count(c).max()}

```

Assuming the file is in mixed case (116 chars):

```
t=new File('f').text.toUpperCase();t.findAll('[A-Z]').unique().sort().each{c->print c*t.readLines()*.count(c).max()}

```

Basically:

* `t=new File('f').text` To get the text of the file.
* `t.findAll('[A-Z]').unique().sort().each{c->` To get the unique characters, sort them, and iterate.
* `print c*t.readLines()*.count(c).max()` Get the max occurances in a single line and print the character that many times.

# Answer
> 2 votes
# Python 2, 154 bytes

```
import collections
c = collections.Counter()
for line in open("input.txt"):
    c |= collections.Counter(line.upper())
print "".join(sorted(c.elements()))

```

# Answer
> 2 votes
## PowerShell - 141

Reads text from a file named 'a'.

```
$x=@{}
gc a|%{[char[]]$_|group|%{$c=$_.name.tolower().trim()
$n=$_.count;$x[$c]=($n,$x[$c])[$n-lt$x[$c]]}}
($x.Keys|sort|%{$_*$x[$_]})-join""

```

# Answer
> 2 votes
# Bash (mostly awk) - ~~172~~ ~~163~~ 157

```
awk -v FS="" '{delete l;for(i=1;i<=NF;i++)l[toupper($i)]++;for(i in l)o[i]=(o[i]>l[i]?o[i]:l[i])}END{for(i in o)for(j=0;j<o[i];j++)print i}'|sort|tr -d ' \n'

```

Text needs to be piped in to awk (or specified as a file).

### Example Input

```
Hello
I love cat
I love dog
I love mommy
Mommy loves daddy

```

### Example Output

```
ACDDDEGHILLMMMOOSTVYY

```

# PHP (probably could be better) - ~~174~~ 210

```
$o=array();foreach(explode("\n",$s) as $a){$l=array();$i=0;while($i<strlen($a)){$k=ucfirst($a[$i++]);if($k==' ')continue;$o[$k]=max($o[$k],++$l[$k]);}}ksort($o);foreach($o as $k=>$v)for($i=0;$i<$v;$i++)echo $k;

```

Assumes that the string is contained in the variable $s

### Example Input

```
Hello
I love cat
I love dog
I love mommy
Mommy loves daddy

```

### Example Output

```
ACDDDEGHILLMMMOOSTVYY

```

# Answer
> 2 votes
I realize this probably isn't the most efficient answer, but I wanted to try and solve the problem anyways. Here's my ObjC variation:

```
- (NSArray *) lettersNeededForString:(NSString *)sourceString {
    sourceString = [sourceString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    sourceString = [sourceString stringByReplacingOccurrencesOfString:@" " withString:@""];
    const char * sourceChars = sourceString.UTF8String;
    NSMutableArray * arr = [NSMutableArray new];
    for (int i = 0; i < sourceString.length; i++) {
        [arr addObject:[NSString stringWithFormat:@"%c", sourceChars[i]]];
    }
    return [arr sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
}

```

Then you can call it for whatever string:

```
NSArray * letters = [self lettersNeededForString:@"Hello\nI love cat\nI love dog\nI love mommy\nMommy loves daddy"];
NSLog(@"%@",letters);

```

I was thinking about applications with larger amounts of text and I'd rather not have to count my array. For this, I added to the method to get this:

```
- (NSDictionary *) numberOfLettersNeededFromString:(NSString *)sourceString {

    sourceString = [sourceString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    sourceString = [sourceString stringByReplacingOccurrencesOfString:@" " withString:@""];
    const char * sourceChars = sourceString.UTF8String;
    NSMutableArray * arr = [NSMutableArray new];
    for (int i = 0; i < sourceString.length; i++) {
        [arr addObject:[NSString stringWithFormat:@"%c", sourceChars[i]]];
    }

    static NSString * alphabet = @"abcdefghijklmnopqrstuvwxyz";
    NSMutableDictionary * masterDictionary = [NSMutableDictionary new];
    for (int i = 0; i < alphabet.length; i++) {
        NSString * alphabetLetter = [alphabet substringWithRange:NSMakeRange(i, 1)];
        NSIndexSet * indexes = [arr indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
            if ([[(NSString *)obj lowercaseString] isEqualToString:alphabetLetter]) {
                return YES;
            }
            else {
                return NO;
            }
        }];

        masterDictionary[alphabetLetter] = @(indexes.count);
    }

    return masterDictionary;
}

```

Run like:

```
NSDictionary * lettersNeeded = [self numberOfLettersNeededFromString:@"Hello\nI love cat\nI love dog\nI love mommy\nMommy loves daddy"];
NSLog(@"%@", lettersNeeded);

```

Will give you:

> { a = 2; b = 0; c = 1; d = 4; e = 5; f = 0; g = 1; h = 1; i = 3; j = 0; k = 0; l = 6; m = 6; n = 0; o = 8; p = 0; q = 0; r = 0; s = 1; t = 1; u = 0; v = 4; w = 0; x = 0; y = 3; z = 0; }

Which I think is better if I had a very large amount of text and I just needed to know how many of each letter I would need.

# Answer
> 2 votes
# C, 298 bytes

```
char c;
int j,n;
char C[26];
char D[26];
int main()
{
char a='a';
while((c=getchar())>=0)
{
c=tolower(c);
if(c>=a&&c<='z'){j=c-a;D[j]++;}
if(c=='\n'){
for(j=0;j<26;j++){
if(D[j]>C[j])
{C[j]=D[j];}
D[j]=0;
}
}
}
for(j=0;j<26;j++)
{
n=C[j];
while(n--)
{
putchar(a+j);
}
}
}

```

Array D holds tally of letters for each line, then the maximum count is copied to C.

Note: I put my answer yesterday but is now not listed, maybe I pressed delete instead of edit by mistake?

# Answer
> 2 votes
## PHP, 143 bytes

Assuming that input is passed in variable `$s`:

```
$i=explode("\n",$s);foreach(range('a','z')as$c){$x=array_map(function($l)use($c){return substr_count($l,$c);},$i);echo str_repeat($c,max($x));}

```

## Explanation

For each possible letter I'm mapping array containing list of strings through a user-defined function which replaces each line with number of characters used. For letter 'd' the line "Mommy loves daddy" will be mapped into 3.

Afterwards I find maximum value inside array and output letter just this many times. Here is multi-line version:

```
$i=explode("\n",$s);
foreach(range('A','Z')as $c){
    $x=array_map(function($l)use($c){
        return substr_count($l,$c);
    },$i);
    echo str_repeat($c,max($x));
}

```

# Answer
> 2 votes
# K, 34

```
{`$a@<a:,/(.:a)#'!:a:|/#:''=:'0:x}

```

# Answer
> 2 votes
# Haskell, 41 bytes

```
f s=do c<-['a'..];maximum$filter(==c)<$>s

```

Try it online! `f` takes a list of lines as input.

Add `main=interact$f.lines` to get a full program for a total of **63 bytes**.

**Explanation**

```
f s=                -- input s is the list of lines
 do c<-['a'..];     -- for each char c starting at c='a', concatenate the following strings
    filter(==c)<$>s -- for each line in s remove all characters except for the current c
   maximum$         -- take the longest of those strings

```

# Answer
> 2 votes
# Jelly, 7, 6, 5 or 4 bytes

```
ỴŒuœ|/Ṣ

```

Try it online!

Function submission. Depending on how you interpret the I/O rules, it may be possible to drop the leading  (which would then require input to be the data structure "list of strings", as opposed to a single string that was divided using newlines); and it may be possible to drop the `Œu` (which would then require the input to use a consistent case for the output to be correct).

## Explanation

```
ỴŒuœ|/Ṣ
Ỵ        Split on newlines
 Œu      Uppercase each resulting string
     /   Combine the resulting strings using…
   œ|      …multiset union
      Ṣ  Sort

```

# Answer
> 2 votes
# Julia

## 78 bytes

it is my 1st approach

```
!I=join((A='A':'Z').^[max([count(c->c==a,i)
for i=split(I,'\n')]...) for a=A])
```

Attempt This Online!

or

## ~~69~~ 66 bytes

* -3 bytes: @MarcMush, thank You
* it is inspired by @Laikoni's Haskell answer

```
!I=prod(maximum(filter(==(a),i) for i=split(I,'
')) for a='A':'Z')
```

Attempt This Online!

# Answer
> 1 votes
# Python (209, with the sample included, 136 without.):

```
from collections import*;c=Counter()
for i in ["Hello","I love cat", "I love Dog", "I love mommy", "Mommy loves daddy"]:
 for j in i.lower(): c[j]=max(c[j],list(i).count(j))
print "".join(sorted(c.elements()))

```

I'll post a PYG sample this afternoon.

# Answer
> 1 votes
# JavaScript - 244

Accepts a parameter of string with newlines.

```
function s(z){n=m="",y=[];z.toLowerCase().split("\n").map(function(g){a=[];g.replace(/ /g,n).split(n).map(function(e,i){if((+y[e]|0)<(a[e]=(+a[e]|0)+1))y[e]=a[e];});});for(var b in y){m+=Array(y[b]+1).join(b);}return m.split(n).sort().join(n);}

```

Not happy with the sorting and preparation of the output.

Edit: case-insensitive regex unnecessary! Thanks @Bergi

# Answer
> 1 votes
# C++, 264 characters.

Reads lowercase text from standard input.

```
#include<algorithm>
#include<iostream>
#include<map>
using namespace std;main(){string s;map<int,long> m;while(getline(cin,s)){int c='`';while(c++<'z')m[c]=max(m[c],count_if(begin(s),end(s),[c](int d){return d==c;}));}for(auto i:m)cout<<string(i.second,i.first);}

```

# C++ function, 205 characters.

```
string a(istream&i){string s;map<int,long> m;while(getline(i,s)){int c='`';while(c++<'z')m[c]=max(m[c],count_if(begin(s),end(s),[c](int d){return d==c;}));}for(auto i:m)s.append(i.second,i.first);return s;}

```

# Answer
> 1 votes
# JavaScript, 199 characters

```
function(n){for(s in p=n.toUpperCase(t=[]).split("\n"))for(i in p[k={},s])t[l=p[s][i]]=Math.max(t[l]||0,k[l]=k[l]+1||1);for(l in t)t.push(new Array(t[l]+1).join(l));return t.sort().join('').trim()}

```

# Answer
> 1 votes
# Lua - 206 Chars

```
g=string
f,t,b,e=io.lines(({...})[1]),{},g.byte,g.char
for s in f do for c=b"a",b"a" do _,d=s:lower():gsub(e(c),"");t[c]=t[c]and(t[c]>d and t[c])or d end end for c=b"a",b"z" do io.write(g.rep(e(c),t[c]))end

```

Reads from the file passed via command line, then creates a table with the maximum number of occurences per letter. Finally outputs the occuring letters.

# Answer
> 1 votes
# Julia, 159

My objective is help understand/improve the expressiveness of Julia. Here's a first attempt.

```
a='a'-1;print(foldl((c,n)->(global a+=1;"$c"*"$a"^n),"",int(mapreduce(s->hist(int({s...}),0:255)[2],(S,T)->max(S,T),zeros(255),readlines(STDIN))[97:122]))"\n")

```

Here's my crazy idea.

Using **mapreduce**, **foldl**, and **hist** (builtin histogram) were advantageous, but having to deal assembling an array from a string and then back to a string from an array and globals expanded the length.

Program reads from *STDIN*. Required **foldl** which is new in Julia 0.30.

### Sample Input

```
alskdja
flkjaslakjd
asa
as
g
alkdjaslkajsd

```
Output
```
aaaddfgjjkkllss

```

# Answer
> 1 votes
# Java, 335

Here is the executable code in java in a more readable form. Once all the unnecessary white spaces are removed, you will see 335 characters in all. The output is:

> ACDDDEGHILLMMMOOSTVYY

It gets a filename as input and reads each character from the file, converts it to uppercase and stores the count of it's occurrence in an array. For every new line, the maximum occurrence of each character is updated. At last it is printed. Pre-requiste: The file should end with a newline.

```
class F {
    public static void main(String[] a) throws Exception {
        java.io.FileInputStream f = new java.io.FileInputStream(a[0]);
        int j, r, l = 256;
        int[] i = new int[l], t = new int[l];
        while ((r = f.read()) > 0) {
            r = r > 96 ? r - 32 : r;
            if (r == 10)
                for (j = 0; j < l; j++) {
                    i[j] = i[j] < t[j] ? t[j] : i[j];
                    t[j] = 0;
                }
            else
                t[r]++;
        }
        for (j = 65; j < 91; j++)
            while (i[j]-- > 0)
                System.out.print((char) j);
    }
}

```

After removing the white spaces the code will look like the following:

```
class F{public static void main(String[] a)throws Exception{java.io.FileInputStream f=new java.io.FileInputStream(a[0]);int j,r,l=256;int[] i=new int[l],t=new int[l];while((r=f.read())>0){r=r>96?r-32:r;if(r==10)for(j=0;j<l;j++){i[j]=i[j]<t[j]?t[j]:i[j];t[j]=0;}else t[r]++;}for(j=65;j<91;j++)while(i[j]-->0)System.out.print((char)j);}}

```

# Answer
> 1 votes
# C#, 265 characters

Assuming input is in variable `s`, here's a C# Expression, using mainly **LINQ** (Enumerable.cs):

```
string.Join("",s.ToLower().Split('\n').Select(e=>e.Where(l=>l!=' '&&l!='\r')
.GroupBy(l=>l).ToDictionary(k=>k.Key,v=>v.Count())).SelectMany(u=>u).GroupBy(l=>l.Key)
.Select(g=>new String(Enumerable.Range(1,g.Max(v=>v.Value)).Select(i=>g.Key).ToArray()))
.OrderBy(l=>l))

```

# Answer
> 1 votes
# Japt v1.4.5, 11 bytes

```
;CËpUmèD rw

```

Try it online!

### Unpacked & How it works

```
;CmDEF{DpUmèD rw

;                 Use an alternative set of predefined variables
 C                "abc...z"
  mDEF{           Map over each char and form a string...
         UmèD       Map over input array into char count
              rw    Reduce with max
       Dp           Repeat the char this number of times

```

# Answer
> 1 votes
# Powershell, ~~118~~ ~~116~~ 87 bytes

```
-join($args|%{$_|% t*y|group|%{-join$_.Group}}|sort|group{$_[0]}|%{$_.Group[-1]})|% t*m

```

Less golfed test script:

```
$f = {

$x=$args|%{$_|% t*y|group|%{-join$_.Group}} # unsorted groups of the same letters for each sentence: (h,e,ll,o), (...), (...), (i, ,l,oo,v,e,d,g),...
$y=$x|sort|group{$_[0]}                     # sort all groups and group it again by the first letter (( , , , ), (a,a), (c), (d,ddd), ... (y,yy))
$z=$y|%{$_.Group[-1]}                       # get a last item (maximum item) from each group
-join($z)|% t*m                             # join it and trim spaces

}

@(
    ,("acdddeghillmmmoostvyy",
      "hello",
      "i love cat",
      "i love dog",
      "i love mommy",
      "mommy loves daddy")

    ,("AAAAAAAAAAAAAAAABBBCCCCDDDDDEEEEEEEEEFFGGGGHHHHHHIIIIIIIIIIJJKKLLLLMMMMMMMNNNNNNNNNNNNNOOOOOOOOOPPPPPPPQRRRRRRSSSSSSSTTTTTTUUUUUVWWXYYY",
      "I SAW THE MAN WITH THE BINOCULARS",
      "THEY ARE HUNTING DOGS",
      "FREE WHALES",
      "POLICE HELP DOG BITE VICTIM",
      "HE SAW THAT GAS CAN EXPLODE",
      "TURN RIGHT HERE",
      "WE SAW HER DUCK",
      "IN ANIMAL CRACKERS GROUCHO MARX AS CAPTAIN RUFUS T SPAULDING QUIPPED ONE MORNING I SHOT AN ELEPHANT IN MY PAJAMAS HOW HE GOT IN MY PAJAMAS I DONT KNOW",
      "SHIP SAILS TOMORROW",
      "BOOK STAYS IN LONDON",
      "WANTED A NURSE FOR A BABY ABOUT TWENTY YEARS OLD",
      "THE GIRL IN THE CAR THAT NEEDED WATER IS WAITING",
      "DID YOU EVER HEAR THE STORY ABOUT THE BLIND CARPENTER WHO PICKED UP HIS HAMMER AND SAW",
      "THOSE PROSECUTORS HAVE BEEN TRYING TO LOCK HIM UP FOR TEN YEARS",
      "FLYING PLANES CAN BE DANGEROUS",
      "I ONCE SAW A DEER RIDING MY BICYCLE",
      "TOILET OUT OF ORDER PLEASE USE FLOOR BELOW",
      "LOOK AT THE DOG WITH ONE EYE")
) | %{
    $expected,$s = $_
    $result = &$f @s
    "$($result-eq$expected): $result"
}

```

Output:

```
True: acdddeghillmmmoostvyy
True: AAAAAAAAAAAAAAAABBBCCCCDDDDDEEEEEEEEEFFGGGGHHHHHHIIIIIIIIIIJJKKLLLLMMMMMMMNNNNNNNNNNNNNOOOOOOOOOPPPPPPPQRRRRRRSSSSSSSTTTTTTUUUUUVWWXYYY

```

# Answer
> 1 votes
# Vyxal `as`, 12 bytes

```
ȧ∑U:ƛ?vOG;*s

```

Try it Online!

```
  U          # Unique characters of...
ȧ∑           # The input, with whitespace removed
          *  # Repeated by...
   :ƛ    ;   # Themselves mapped to...
        G    # The highest...
      vO     # Amount of...
             # (implicit) That character
     ?       # In the input
           s # Sorted.

```

# Answer
> 1 votes
# Japt `-Px`, ~~9~~ 8 bytes

I *knew* there had to be a way to to it in 8!

```
cü üÎËÍÌ

```

Try it

```
cü üÎËÍÌ     :Implicit input of array
c            :Flat map
 ü           :  Group & sort by value
   ü         :Group & sort by
    Î        :  First character
     Ë       :Map
      Í      :  Sort
       Ì     :  Last element
             :Implicitly join, trim and output

```

## Original (w/o flags), 9 bytes

Takes input as an array of lowercase strings.

```
;C£ËoXÃÍo

```

Try it

```
;C£ËoXÃÍo     :Implicit input of array U
;C            :Lowercase alphabet
  £           :Map each X
   Ë          :  Map U
    oX        :    Remove all characters but X
      Ã       :  End inner map
       Í      :  Sort
        o     :  Pop last element

```

# Answer
> 1 votes
# JavaScript (Node.js), 95 bytes

```
a=>(g=i=>i?g(i-1,i=i.toString(36))+i.repeat(Math.max(...a.map(y=>y.split(i).length))-1):'')(35)

```

Try it online!

# Answer
> 0 votes
# C, 298 bytes

(242 bytes by not counting newlines)

Array D keeps tally of letters in each line, then the maximum count of each letter is copied into array C.

```
char c;
int j,n;
char C[26];
char D[26];
int main()
{
char a='a';
while((c=getchar())>=0)
{
c=tolower(c);
if(c>=a&&c<='z'){j=c-a;D[j]++;}
if(c=='\n'){
for(j=0;j<26;j++){
if(D[j]>C[j])
{C[j]=D[j];}
D[j]=0;
}
}
}
for(j=0;j<26;j++)
{
n=C[j];
while(n--)
{
putchar(a+j);
}
}
}

```

Note: I just discovered Notepad++ which gives my character count, counts newlines as 2 chars. Should these be subtracted?

# Answer
> 0 votes
# C# / LINQPad, 181 bytes

*In C# Expression mode; assumes input file is named `a` (and probably in the LINQPad Program Files folder)*

```
string.Join("",File.ReadAllLines("a").SelectMany(s=>s.ToUpper().Where(c=>c>64&&c<91).GroupBy(c=>c)).GroupBy(g=>g.Key).Select(g=>new string(g.Key,g.Max(x=>x.Count()))).OrderBy(s=>s))

```

### Ungolfed

```
string.Join("",                                                     // concat all substrings, with no separator
    File.ReadAllLines("a")                                          // read all lines from text file called 'a'
        .SelectMany(                                                // apply function to each subset and union into a single set
            s => s.ToUpper()                                        // convert strings to uppercase
                  .Where(c => c > 64 && c < 91)                     // shorter than char.IsLetter(c) for all uppercase
                  .GroupBy(c => c)                                  // group on each character in the string
         )
        .GroupBy(g => g.Key)                                        // group again on each character (I'd love to get rid of this...)
        .Select(g => new string(g.Key, g.Max(x => x.Count())))      // string(char, count) constructor build repeating-char string
        .OrderBy(s => s)                                            // sorted set required
)

```

### Input (text file called `a`)

```
Hello
I love cat
I love dog
I love mommy
Mommy loves daddy

```

### Output

```
ACDDDEGHILLMMMOOSTVYY

```

# Answer
> 0 votes
# C# - 146 Bytes

```
var x="";foreach(var l in File.ReadAllLines(t))foreach(var p in l)if(x.Count(c=>c==p)<l.Count(c=>c==p))x+=p;string.Concat(x.OrderBy(o=>o)).Trim();

```

Well, I think this is as short as C# can get. This code expects a path to the text file in the variable t.

# Answer
> 0 votes
# Kotlin, 189 bytes

```
lines().map{it.filter{it.isLetter()}.groupingBy{it}.eachCount()}.fold(mutableMapOf<Char,Int>()){r,i->i.map{(t,u)->r[t]=maxOf(r[t] ?:0,u)}
r}.flatMap{(k,v)->(0..v-1).map{k}}.joinToString("")

```

## Beautified

```
lines()
    .map { it.filter { it.isLetter() }.groupingBy { it }.eachCount() }
    .fold(mutableMapOf<Char, Int>()) { r, i ->
        i.map { (t, u) -> r[t] = maxOf(r[t] ?: 0, u)}
        r
    }
    .flatMap { (k, v) -> (0..v-1).map { k } }
    .joinToString("")

```

## Test

```
fun String.f() =

lines().map{it.filter{it.isLetter()}.groupingBy{it}.eachCount()}.fold(mutableMapOf<Char,Int>()){r,i->i.map{(t,u)->r[t]=maxOf(r[t] ?:0,u)}
r}.flatMap{(k,v)->(0..v-1).map{k}}.joinToString("")

fun main(args: Array<String>) {
    val i = """hello
i love cat
i love dog
i love mommy
mommy loves daddy"""
    println(i.f().map { it }.sorted().joinToString(""))
    println("acdddeghillmmmoostvyy")
}

```

## TIO

TryItOnline

# Answer
> 0 votes
# Stax, 8 bytes

```
ü2lLÜ▀⌂æ

```

Run and debug it

1. Reduce the array of inputs using a multiset union operation.
2. Sort the resulting characters.
3. Remove spaces.

# Answer
> 0 votes
# PHP, 116 bytes

```
foreach(file(T)as$y=>$s)for($i=0;~$c=ucfirst($s[$i++]);)$$c[$y]++;for($c=A;!$c[1];$c++)echo str_repeat($c,max($$c));

```

assumes filename `T`. Run with `-nr`.

**breakdown**

```
foreach(file(T)as$y=>$s)            # loop through lines of file
    for($i=0;~$c=ucfirst($s[$i++]);)    # loop through line characters
        $$c[$y]++;       # increment counter ($A..$Z)
 for($c=A;!$c[1];$c++)    # loop $c through uppercase letters
  echo str_repeat($c,max($$c));      # get max from $A, $B etc, use as multiplier for str_repeat

```

# Answer
> 0 votes
# JavaScript, ~~105~~ 104 bytes

Takes input as an array of character arrays and returns a string.

```
a=>[...new Set(a+``)].sort().map(c=>c.repeat(a.map(r=w=>r=w.map(l=>o+=c>{}&c==l,o=0)|o<r?r:o)|r)).join``

```

Try it online

# Answer
> 0 votes
# Pyth, ~~14~~ 10 bytes

```
smeS@Ld.zG

```

Accepts input as lowercase strings. Try it online here.

```
smeS@Ld.zG   Implicit: .z=input as list of strings, G=lowercase alphabet
 m       G   Map each letter in G, as d, using:
     L .z      In each string in .z ...
    @ d        ... keep only those characters which match d
   S           Sort by length
  e            Take the last element (i.e. longest)
s            Concatenate into string, implicit print

```

*Edit: golfed 3 bytes. Previous version: `sm*deSml@dk.zG`*

# Answer
> 0 votes
# Vyxal `s`, 5 bytes

```
ɾƒÞ∪s

```

Try it Online!

# Answer
> 0 votes
# jq, 94 bytes

```
[.,inputs]|map(explode-[32]|group_by(.)[])|group_by(.[0])|map(max_by(length)|implode)|join("")

```

Try it online!

---

```
[., inputs]                          # from raw input to array of strings
                                     # e.g. ["hello", "i love cat", …]

| map(explode-[32] | group_by(.)[])  # splits each string into groups of
                                     # similar codepoints (excluding spaces)
                                     # e.g. "hello" -> [[101],[104],[108,108],[111]]

| group_by(.[0])                     # groups all groups of similar codepoints

| map(max_by(length)|implode)        # then only keep the largest group of
                                     # each sub groups and transform the
                                     # group into a string

| join("")                           # finally join all the strings

```

# Answer
> 0 votes
# Thunno 2 `J`, 7 bytes

```
ẠıȷcGn×

```

Attempt This Online!

Port of Kevin Cruijssen's 05AB1E answer.

#### Explanation

```
ẠıȷcGn×  # Implicit input
Ạı       # Map over lowercase alphabet:
  ȷc     #  Count in each input string
    G    #  Pop and leave the maximum
     n×  #  Repeat the character that many times
         # Implicit output, joined

```

---
Tags: code-golf
---