Create program that counts the total number of letters common to two names, and finds the product of their lengths, to function as a "love tester."

Conditions: you may not get a 1:1 answer (being 3 out of 3, etc.) output.


Two names from STDIN or closest alternative.


Compute x as the total number of letters in common between the two names, ignoring case. Compute y as the product of the lengths of the names. Then the output, to STDOUT or closest alternative, is

Name1 and Name2 have x out of y chances of love.





Wesley and Polly have 2 out of 30 chances of love.

Wesley and Polly have 2 letters in common, y and l, and the product of their lengths is 6 * 5 = 30.




Bill and Jill have 3 out of 16 chances of love.


  • Subtract 30 bytes for using simplified fractions, i.e. x out of y is in fully reduced form.


Ranking will be determined by languages. The code golf ends on October 17 at 10:20 pm Pacific Daylight Time (California)

Rep Prizes

  • You will receive 10 rep (an upvote) for being in the top 5 (except first place).
  • You will receive 15 rep (accepted entry) for being the first place.
  • You might also get a bounty reward from another person.

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.**

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

# Language Name, N bytes

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

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

var QUESTION_ID=60459;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/;
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>

**Stack snippet from Sign That Word by Kslkgh

Congratulations to the following:

  1. Winner Dennis (Pyth)
  2. Dennis (CJam)
  3. NBZ (APL)
  4. molarmanful (JavaScript ES6)
  5. Alex A. (Julia)
  • 3
    \$\begingroup\$ What should the output be for Aaron\nAhmad? Or samename\nsamename? \$\endgroup\$ – lirtosiast Oct 12 '15 at 5:17
  • 3
    \$\begingroup\$ I'm unclear how you're counting total letters in common when letters repeat. If the names have a and b of some letter, do those count for min(a,b) repeats? \$\endgroup\$ – xnor Oct 13 '15 at 8:40
  • \$\begingroup\$ as @xor says, how are you counting repeated letters? From the second example, it appears you're counting repeated characters, so if the first example were reversed, then do you expect a different result? \$\endgroup\$ – Rnet Oct 15 '15 at 17:41
  • \$\begingroup\$ Is it totally unrelated to kolmogorov-complexity? \$\endgroup\$ – user54200 Jun 28 '16 at 14:37

Pyth, 40 bytes

jd[z"and"Jw"have"/K-lzl.-rz0rJ0i=J*lzlJK"out of"/JiJK"chances of love.

The code is 70 bytes long and qualifies for the -30 bytes bonus.

Try it online.

  [                        Begin an array and fill it with the following:
   z                         The first line of input.
   "and"                     That string.
   Jw                        The second line of input, saved in J.
   "have"                    That string.
           rz0rJ0              Convert both lines to lowercase.
         .-                    Remove the characters form the second string
                               from the first, counting multiplicities.
        l                      Get the length.
     -lz                       Subtract it from the length of the first line.
    K                          Save in K.
                  =J*lzlJ      Save the lines' lengths' product in J.
                 i       K     Compute the GCD of J and K.
   /                         The quotient of K and the GCD.
   "out of"                  That string.
   /JiJK                     The quotient of J and the GCD of J and K.
   "chances of love.         That string.
jd                         Join the elements, separated by spaces.

Dyalog APL, 94 91-30= 61 bytes

Usually APL golfing results in code that is more compact – but not more complex – than normal, but in this case I save chars in ugly ways:

{1↓(∊' ',¨⍵,⍪'and' 'have'),' love.',⍨∊((⊢÷∨/)(≢⊃∩/32|⎕ucs¨⍵),×/≢¨⍵),⍪'out of' 'chances of'}

,⍪'out of' 'chances of' create a 2×2 table of numbers (left) and texts (right)
×/≢¨⍵ product of lengths
32|⎕UCS¨⍵ harmonize upper- and lowercase UCS values
≢⊃∩/ tally the intersection of the two sets
⊢÷∨/ divide the tally and the product with their GCD
,' love.',⍨∊ make it into a simple list and append love.
⍵,⍪'and' 'have' create a 2×2 table of names (left) and texts (right)
∊' ',¨ prepend a space to each table cell and then make into simple list
1↓ drop the initial superfluous space

Thanks to ngn for -3 bytes.

  • \$\begingroup\$ It appears this is only a function, whereas the OP specified input from STDIN and output to STDOUT (i.e. a full program rather than just a function). \$\endgroup\$ – Alex A. Oct 13 '15 at 21:07
  • \$\begingroup\$ @AlexA. APL doesn't have STDIN, but can issue a prompt to accept the two names in the format 'Wesley' 'Polly'. If you think this would be more fair, feel free to append (U+2395) to then very end of the line (after the }), and adjust the score to 65. \$\endgroup\$ – Adám Oct 13 '15 at 21:30

Javascript ES6, 123 bytes

(a,b)=>a+` and ${b} have ${[...a].map(x=>eval(`/${x}/i.test(b)&&c++`),c=0),c} out of ${a.length*b.length} chances of love.`

So much for "love"... I could really do with less bytes.

Run the code snippet in Firefox.

x=(a,b)=>a+` and ${b} have ${[...a].map(x=>eval(`/${x}/i.test(b)&&c++`),c=0),c} out of ${a.length*b.length} chances of love.`
<input id="a" value="Bill"><input id="b" value="Jill"><button onclick="o.innerHTML=x(a.value,b.value)">Calculate!</button>
<div id="o"></div>

  • 2
    \$\begingroup\$ It appears this is only a function, whereas the OP specified input from STDIN and output to STDOUT (i.e. a full program rather than just a function). \$\endgroup\$ – Alex A. Oct 13 '15 at 6:36

Julia, 129 bytes

The code is 159 bytes but it qualifies for the -30 bonus.

print("$A and $B have $(r.num) out of $(r.den) chances of love.")

This could probably be made shorter by not going for the bonus, but I wanted to show off Julia's rational number type. :)


# Read two names from STDIN on separate lines
A, B = map(chomp, readlines())

# Construct their lowercase equivalents
a, b = map(lowercase, [A, B])

# Construct a rational number where the numerator is the
# length of the intersection of a and b and the denominator
# is the product of the lengths
r = Rational(length(a ∩ b), length(a) * length(b))

# Tell us about the love
print("$A and $B have $(r.num) out of $(r.den) chances of love.")

The Rational() function constructs an object of type Rational which has fields num and den, corresponding to the numerator and denominator respectively. The benefit of using this type here is that Julia does the reduction for us; we don't have to worry about reducing the fraction ourselves.


CJam, 55 bytes

out of
chances of love."N/.{}S*

The code is 85 bytes long and qualifies for the -30 bytes bonus.

Try it online in the CJam interpreter.

How it works

ll]      e# Read two lines and wrap them in an array.
_~       e# Copy the array and dump the lines on the stack.
@_       e# Rotate the array on top and push a copy.
{        e# For each line of the copy.
  '~,    e#   Push the array of all ASCII charcters up to '}'.
  \el    e#   Convert the line to lowercase.
  fe=    e#   Count the occurrences of each character in the line.
}/       e#
.e<      e# Vectorized minimum of the occurrences.
:+       e# Add to find the number of shared charaters.
\:,      e# Compute the length of each line.
:*       e# Push the product.
]_       e# Wrap the stack in an array and push a copy.
2>~      e# Discard the lines of the copy and dump the calculated integers.
{_@\%h}; e# Compute their GCD, using the Euclidean algorithm.
f/       e# Divide each element of the array by the GCD.
         e# This also splits the names, which won't affect printing.

out of
chances of love."

N/       e# Split the above string at linefeeds.
.{}      e# Vectorized no-op. Interleaves the arrays.
S*       e# Join the results elements, separated by spaces.

Dyalog APL, 84-30= 54 bytes

∊' and ' ' have' 'out of' 'chances of love.',¨⍨⊢,{+/⌊⌿+⌿↑1↑¨⍨-32|⍉⎕ucs↑⍵}(,÷∨)(×/≢¨)

This is a train, inspired by Adám's answer.

×/≢¨ product of the lengths

{+/⌊⌿+⌿↑1↑¨⍨-32|⍉⎕ucs↑⍵} chances of love

(,÷v) the concatenation divided by the GCD; between the above two expressions, this reduces the fraction

⊢, prepend the names

,¨⍨ shuffles the strings on the left with the values on the right


"Chances of love" computation in detail: {+/⌊⌿+⌿↑1↑¨⍨-32|⍉⎕ucs↑⍵} ↑⍵ arrange the names in a 2×N matrix, pad with spaces ⎕ucs take ascii codes ⍉ transpose the matrix as N×2 32| modulo 32 to case-fold 1↑¨⍨- for each X create a vector 0 0...0 1 of length X ↑ arrange into a 3d array, pad with 0s +⌿ 1st axis sum, obtain freqs per letter and per name ⌊⌿ 1st axis min, obt. nr of common occurrences per letter +/ sum

test, test2


Java 8, 192 bytes

BiFunction y=(a,b)->a+" and "+b+" have "+(""+a).chars().filter(c->(""+b).toUpperCase().indexOf(c>'Z'?c-32:c)>=0).count()+" out of "+(""+a).length()*(""+b).length()+" chances of love.";



Ruby, 153 bytes

Longer than I expected. I don't know if the 30 bytes bonus applies for this.

d=[];2.times{d<<gets.chop<<$_.downcase.chars<<$_.length-1};$><<"#{d[0]} and #{d[3]} have #{d[2]-(d[1]-d[4]).length} out of #{d[2]*d[5]} chances of love."
  • \$\begingroup\$ Could you please add a link to a compiler? (I recommend Ideone) \$\endgroup\$ – juniorRubyist Oct 15 '15 at 16:37

Python 2.7, 161 bytes

import string;r=raw_input;a,b=r(),r();print'%s and %s have %i out of %i chances of love'%(a,b,sum(map(lambda c:c in a and c in b,string.letters)),len(a)*len(b))

Test it here : http://ideone.com/jeoVgV

And here is a version that simplifies the fraction :

import string,fractions;r=raw_input;a,b=r(),r();F=fractions.Fraction(sum(map(lambda c:c in a and c in b,string.letters)),len(a)*len(b))
print'%s and %s have %i out of %i chances of love'%(a,b,F.numerator,F.denominator)

Unfortunately this one's score is 219-30=189...


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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