Love Tester Code Golf


9

Crea un programma che conti il ​​numero totale di lettere comuni a due nomi e trova il prodotto della loro lunghezza per funzionare come "tester d'amore".

Condizioni: potresti non ottenere un risultato di risposta 1: 1 (essendo 3 su 3, ecc.).

Ingresso

Due nomi da STDIN o alternativa più vicina.

Produzione

Calcola xil numero totale di lettere in comune tra i due nomi, ignorando il caso. Calcola ycome prodotto delle lunghezze dei nomi. Quindi l'output, a STDOUT o alternativa più vicina, è

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

Esempi

Ingresso:

Wesley
Polly

Produzione:

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

Wesley e Polly hanno 2 lettere in comune ye l, e il prodotto della loro lunghezza è 6 * 5 = 30.

Ingresso:

Bill
Jill

Produzione:

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

bonus

  • Sottrai 30 byte per l'utilizzo di frazioni semplificate, ovvero x out of yè in forma completamente ridotta.

Classifica:

La classifica sarà determinata dalle lingue. Il codice golf termina il 17 ottobre alle 22:20 Pacific Daylight Time (California)

Premi Rep

  • Riceverai 10 rappresentanti (un voto positivo) per essere tra i primi 5 (tranne il primo posto).
  • Riceverai 15 rappresentanti (ingresso accettato) per essere il primo posto.
  • Potresti anche ricevere una ricompensa di taglie da un'altra persona.

Ecco uno snippet di stack per generare sia una classifica regolare che una panoramica dei vincitori per lingua. **

Per assicurarti che la tua risposta venga visualizzata, ti preghiamo di iniziare la risposta con un titolo, usando il seguente modello Markdown:

# Language Name, N bytes

dov'è Nla dimensione del tuo invio. Se si migliora il punteggio, è possibile mantenere i vecchi punteggi nel titolo, colpendoli. Per esempio:

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

** Stack snippet di Sign That Word di Kslkgh


Congratulazioni per quanto segue:

  1. Vincitore Dennis (Pyth)
  2. Dennis (CJam)
  3. NBZ (APL)
  4. molarmanful (JavaScript ES6)
  5. Alex A. (Julia)

3
A cosa dovrebbe servire l'output Aaron\nAhmad? Oppure samename\nsamename?
lirtosiast,

3
Non sono chiaro come stai contando le lettere totali in comune quando le lettere si ripetono. Se i nomi hanno ae bdi qualche lettera, contano le min(a,b)ripetizioni?
xnor

come dice @xor, come stai contando le lettere ripetute? Dal secondo esempio, sembra che stai contando i caratteri ripetuti, quindi se il primo esempio è stato invertito, ti aspetti un risultato diverso?
Rnet,

È totalmente estraneo alla complessità del kolmogorov ?

Risposte:


1

Pyth, 40 byte

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

Il codice è lungo 70 byte e si qualifica per il bonus di -30 byte .

Provalo 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.

3

Dyalog APL , 94 91-30 = 61 byte

Di solito il golf APL si traduce in un codice più compatto - ma non più complesso - del normale, ma in questo caso salvo i caratteri in brutti modi:

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

,⍪'out of' 'chances of'creare una tabella 2 × 2 di numeri (a sinistra) e testi (a destra) del
×/≢¨⍵prodotto delle lunghezze
32|⎕UCS¨⍵armonizzare i valori UCS maiuscoli e minuscoli
≢⊃∩/conteggio dell'intersezione dei due set
⊢÷∨/dividere il conteggio e il prodotto con il loro GCD lo
,' love.',⍨∊rendono in un semplice elenco e accoda amore.
⍵,⍪'and' 'have'creare una tabella 2 × 2 di nomi (a sinistra) e testi (a destra)
∊' ',¨anteporre uno spazio a ciascuna cella della tabella e quindi fare in un semplice elenco
1↓eliminare lo spazio superfluo iniziale

Grazie a ngn per -3 byte.


Sembra che questa sia solo una funzione, mentre l'OP ha specificato l'input da STDIN e l'output a STDOUT (ovvero un programma completo anziché solo una funzione).
Alex A.

@AlexA. APL non ha STDIN, ma può emettere un prompt per accettare i due nomi nel formato 'Wesley' 'Polly'. Se ritieni che ciò sia più giusto, sentiti libero di aggiungere (U + 2395) alla fine della linea (dopo il }) e regola il punteggio a 65.
Adám

2

Javascript ES6, 123 byte

(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.`

Tanto per "amore" ... Potrei davvero fare con meno byte.

Esegui lo snippet di codice in Firefox.


2
Sembra che questa sia solo una funzione, mentre l'OP ha specificato l'input da STDIN e l'output a STDOUT (ovvero un programma completo anziché solo una funzione).
Alex A.

2

Julia, 129 byte

Il codice è di 159 byte ma si qualifica per il bonus di -30.

A,B=map(chomp,readlines())
a,b=map(lowercase,[A,B])
L=length
r=Rational(L(ab),L(a)L(b))
print("$A and $B have $(r.num) out of $(r.den) chances of love.")

Questo potrebbe probabilmente essere abbreviato non andando per il bonus, ma volevo mostrare il tipo di numero razionale di Julia. :)

Ungolfed:

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

La Rational()funzione costruisce un oggetto di tipo Rationalche ha campi nume den, rispettivamente, corrispondenti al numeratore e al denominatore. Il vantaggio di usare questo tipo qui è che Julia fa la riduzione per noi; non dobbiamo preoccuparci di ridurre noi stessi la frazione.


2

CJam, 55 byte

ll]_~@_{'~,\elfe=}/.e<:+\:,:*]_2>~{_@\%}h;f/"and
have
out of
chances of love."N/.{}S*

Il codice è lungo 85 byte e si qualifica per il bonus di -30 byte .

Provalo online nell'interprete CJam .

Come funziona

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.

"and
have
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.

1

Dyalog APL, 84-30 = 54 byte

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

Questo è un treno , ispirato alla risposta di Adám .

×/≢¨ prodotto delle lunghezze

{+/⌊⌿+⌿↑1↑¨⍨-32|⍉⎕ucs↑⍵} possibilità d'amore

(,÷v)la concatenazione divisa per il GCD; tra le due espressioni precedenti, ciò riduce la frazione

⊢, anteporre i nomi

,¨⍨ mescola le stringhe a sinistra con i valori a destra

appiattire


Calcolo "Probabilità d'amore" in dettaglio: {+/⌊⌿+⌿↑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


0

Java 8, 192 byte

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.";

Ex:

System.out.println(y.apply("Bill","Jill"));
System.out.println(y.apply("Wesley","Polly"));

0

Rubino, 153 byte

Più del previsto. Non so se il bonus di 30 byte si applica a questo.

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."

Potresti per favore aggiungere un link a un compilatore? (Consiglio Ideone)
juniorRubyist,

0

Python 2.7, 161 byte

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

Provalo qui: http://ideone.com/jeoVgV

Ed ecco una versione che semplifica la frazione:

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)

Sfortunatamente il punteggio di questo è 219-30 = 189 ...


1
Ecco un compilatore che puoi aggiungere: ideone.com/jeoVgV
juniorRubyist
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.