En busca de un alma gemela

40

Dada una lista finita no vacía de enteros, arroje un valor verdadero si hay exactamente dos entradas iguales y todas las demás entradas son distintas, y un valor falso de lo contrario.

Ejemplos

truthy:
[1,1]
[1,2,1]
[1,6,3,4,4,7,9]

falsey:
[0]
[1,1,1]
[1,1,1,2]
[1,1,2,2]
[2,1,2,1,2]
[1,2,3,4,5]
falla
fuente
¿Supongo que no podemos suponer que los enteros siempre serán menores que 10?
Martin Ender
1
Sí, excepto si su idioma no admite enteros más grandes.
flawr
1
¿Puedes elaborar lo que quieres decir con consistente ?
flawr
33
Vi esto en la parte superior de HNQ y pensé que habíamos llegado a la última pregunta interpersonal.se
gntskn
3
@Walfrat Publícalo como tu propio desafío. Además, esta retroalimentación generalmente se aprecia en el sandbox.
flawr

Respuestas:

22

Python 3, 30 28 bytes

lambda m:len({*m})+1==len(m)

Pruébalo en línea!

{*m}lanza la lista a un setobjeto, una lista desordenada de elementos sin duplicados. Hacer esto siempre disminuirá la longitud de la lista por el número de duplicados en ella. Al calcular cuánto ha cambiado la longitud, podemos determinar fácilmente si la lista tenía un solo duplicado y devolver el resultado de la prueba.

-2 bytes gracias a los ovs.

LyricLy
fuente
Exactamente la solución que tenía, pero olvidé el {*m}atajo en lugar de set, ¡bien jugado!
FlipTack
27 bytes para la negación . (Falsey cuando debería ser Verdad, etc.)
mbomb007
3
Aquí hay otra manera de hacerlo raro (también negación):lambda m:~-len(m[len({*m}):])
mbomb007
9

Casco , 4 bytes

εṠ-u

Pruébalo en línea!

Explicación

εṠ-u  Implicit input.
   u  Unique elements.
 Ṡ-   Delete them from input, counting multiplicities.
ε     Is the result a singleton list?
Zgarb
fuente
7

MATL , 7 , 6 bytes

&=sp4=

Pruébalo en línea!

¡Un byte guardado gracias a @Guiseppe!

Explicación:

&=  % Table of pair-wise equality comparisons
    %
    % [1 0 0 0 0 0 0
    %  0 1 0 0 0 0 0
    %  0 0 1 0 0 0 0
    %  0 0 0 1 1 0 0
    %  0 0 0 1 1 0 0
    %  0 0 0 0 0 1 0
    %  0 0 0 0 0 0 1]
    %
s   % Sum each Column. Stack:
    %
    % [1 1 1 2 2 1 1]
    %
p   % Product of the array. Stack:
    %
    % [4]
    %
4=  % Compare the stack to '4'
DJMcMayhem
fuente
1
Dado que ses sumy sumsuma a lo largo de la primera dimensión no única (columnas), y la matriz es simétrica, ¿no podría ser esto en slugar de Xs?
Giuseppe
1
@Giuseppe Ah, TIL. ¡Gracias!
DJMcMayhem
6

Jalea , 8 5 bytes

QL‘=L

Pruébalo en línea!

Explicación

QL‘=L  - Main link, argument L (a list)   e.g [1,6,3,4,4,7,9]
Q      - Deduplicated elements                [1,6,3,4,7,9]
 L     - Length                               6
  ‘    - Increment                            7
    L  - Length of the input                  7 ([1,6,3,4,4,7,9])
   =   - Are they equal?                      1

Si los valores de salida pueden ser valores consistentes, entonces QL_Lfunciona, lo que da como resultado -1verdadero y cualquier otro número no positivo para falsey (gracias @JonathanAllan)

caird coinheringaahing
fuente
QL_Ldaría como resultado -1verdadero y algún número menor que -1o 0para falsey (por ejemplo [1,6,3,4,4,7,9,9,9], regresaría -3, mientras [1,6,3,4,7,9]que regresaría 0).
Jonathan Allan
@ JonathanAllan Oh, sí. Supongo que los ejemplos en los que lo probé volvieron -2.
caird coinheringaahing
4

Pushy , 8 bytes

Implementación simple de verificar si len(set(list)) == len(list)-1:

LtvuL^=#

Explicación:

       \ Implicit: Put all input on stack
Ltv    \ Get the stack length - 1, save in auxiliary stack
u      \ Remove non-unique elements
L      \ Get the new length
^=     \ Compare with the previously saved length
#      \ Print result

Esto funciona ya que la longitud solo disminuirá en 1 si solo había exactamente 1 entero no distinto en la lista inicial.

Pruébalo en línea!

FlipTack
fuente
1
¡Guau, no he visto una respuesta agresiva en mucho tiempo! +1
caird coinheringaahing
1
@cairdcoinheringaahing Pushy nunca morirá. Solo volverá más fuerte.
FlipTack
4

Octava , 25 bytes

Esto no está utilizando un enfoque groupo un uniqueenfoque como muchas de las otras respuestas, sino más bien el "producto cartesiano" de todas las comparaciones posibles.

@(x)nnz(triu(x==x',1))==1

Explicación

             x==x'        %create a matrix where the entry at (i,j) compares whether x(i) == x(ju)
        triu(x==x',1)     %only consider the strict upper triangular matrix
    nnz(triu(x==x',1))    %count the number of nonzero entries
@(x)nnz(triu(x==x',1))==1 %check whether this number is actually 1

Pruébalo en línea!

Y debido a que ningún programa estaría completo sin una convolución (gracias @LuisMendo por corregir un error):

Octava , 40 bytes

@(x)nnz(~conv(sort(x),-1:2:1,'same'))==1

Pruébalo en línea!

falla
fuente
Me inspiraste para desarrollar este enfoque :)
Stewie Griffin
2
@StewieGriffin Creo que el MAT respuesta utiliza el enfoque exacto :)
flawr
4

J , 7 6 bytes

=&#0,=

=compruebe la igualdad de cada elemento con cada elemento único, crea una matriz con m filas para  m  elementos únicos.
0,agregue una fila vacía en la parte superior.
=&#¿El número de filas es igual a la longitud de entrada?

Pruébalo en línea!

FrownyFrog
fuente
Creo que puede reemplazar .~con=
H.PWiz
@ H.PWiz Nice, editado.
FrownyFrog
4

Retina , 15 12 11 bytes

Gracias a Neil por guardar 1 byte.

D`
Mm2`^$
1

Pruébalo en línea!

La entrada está separada por salto de línea. (El conjunto de pruebas utiliza la separación por comas por conveniencia).

Explicación

D`

Deduplicar las líneas en la entrada, lo que elimina cualquier número entero que haya aparecido antes (pero deja los saltos de línea circundantes).

Mm2`^$

Cuente la cantidad de líneas vacías, que es igual a la cantidad de duplicados que eliminamos, pero solo considere las dos primeras coincidencias. Por lo tanto, la salida solo será 0(sin duplicados), 1(un duplicado), 2(dos o más duplicados).

1

Asegúrese de eliminar exactamente un duplicado.

Martin Ender
fuente
Save a byte by limiting the newline match to 2, so that the input to the third line is always 0, 1, or 2, simplifying the test. (Annoyingly you can't use A`. to count newlines, because it drops the last one.)
Neil
@Neil Thanks, the limit is a neat idea. I also tried using A`., but the problem is rather that you can't distinguish a single empty line from having no lines at all. Maybe I should consider terminating A and G output with a linefeed if there are any lines. Although that should probably be an option since I can imagine that linefeed being annoying in other scenarios.
Martin Ender
Matching a single empty line is easy - that's just ^$¶.
Neil
@Neil No, I mean that the output of A is identical regardless of whether it retains a single empty line or discards all lines.
Martin Ender
Sorry, that's what I meant by "drops the last one" - it returns one fewer empty line, but then you can't distinguish between 0 and 1.
Neil
3

05AB1E, 4 bytes

{¥_O

Try it online!

Outputs 1 as truthy, any other non-negative integer as falsy. In 05AB1E, 1 is the only truthy number (thanks @Emigna for the insight!).

Explanation

{       Implicit input. Sort
 ¥      Consecutive differences
  _     Boolean negate
   O    Sum. Implicit display
Luis Mendo
fuente
3

Ruby, 32 bytes

->(s){s.uniq.length==s.length-1}
parenparen
fuente
Welcome to PPCG! Because this is code golf, you need to include the byte count of your program. I've taken the liberty of doing it for you this time.
Pavel
How about Array#size?
Travis
You can get down to 26 bytes by using ->s{s.uniq.size==s.size-1}
Conor O'Brien
3

C# (.NET Core), 35 + 18 bytes

+18 for using System.Linq.

n=>n.Distinct().Count()==n.Length-1

Try it online!

67 byte alternative without Linq:

n=>new System.Collections.Generic.HashSet<int>(n).Count==n.Length-1

Try it online!

Ian H.
fuente
3

Excel, 42 bytes

Danish language version

=TÆLV(A:A)=SUM(--(FREKVENS(A:A,A:A)>0))+1

Assumes each integer from the list in separate cell in column A.
If we were allowed for inconsistent falsey values, we could save 3 bytes:

=TÆLV(A:A)+SUM(-(FREKVENS(A:A,A:A)>0))

English language version (44 bytes)

=COUNTA(A:A)=SUM(--(FREQUENCY(A:A,A:A)>0))+1
pajonk
fuente
3

R, 32 31 bytes

-1 byte thanks to @JarkoDubbeldam

cat(sum(duplicated(scan()))==1)

Try it online!

Reads from stdin, writes to stdout.

duplicated iterates through the list, replacing the values of l with TRUE if that value occurs earlier in the list, and FALSE otherwise. If there's a unique pair of soulmates, there should be exactly one TRUE value, so the sum should be 1.

Giuseppe
fuente
1
31 bytes
JAD
1
@JarkoDubbeldam ah, of course. Good to see you again! It's been a while.
Giuseppe
Been busy with some other stuff, not sure I'm completely back yet.
JAD
@Giuseppe, I just read this question and immediately thought of your Original Approach.... Very nice! I would have never thought of the scan() approach.
Joseph Wood
3

PowerShell, 40 37 bytes

($args|sort -u).count-eq$args.count-1

Try it online!

The Sort-Object command (alias sort) with the -unique flag pulls out only the unique components of the input. For example, for input @(1,3,3,2), this will result in @(1,2,3).

Thus, we just need to make sure that the .count of this object (i.e., how many elements it has) is -equal to the .count of our input array -1 (i.e., we have exactly one duplicate entry).

Saved 3 bytes thanks to Sinusoid.
Fixed bug thanks to TessellatingHeckler.

AdmBorkBork
fuente
Can you use the get-unique alias 'gu' instead of group to reach the same result?
Sinusoid
@Sinusoid Yes, we can. Thanks!
AdmBorkBork
This doesn't work on the second test case 1,2,1 - get-unique only works on pre-sorted input. How about ($args|sort -u).count-eq$args.count-1 which is also 37 but does work for all the test cases, if you call it like f 1 2 1 instead of f 1,2,1 ?
TessellatingHeckler
@TessellatingHeckler Ah, good catch. All of the testing I did was with pre-sorted input. Thanks!
AdmBorkBork
2

Perl 5, 36 + 1 (-a) = 37 bytes

map$k{$_}++,@F;@a=keys%k;say@a+1==@F

Try it online!

Xcali
fuente
1
may be golfed @k{@F}++;say@F==1+keys%k
Nahuel Fouilleul
2

Octave / MATLAB (with Statistics package / toolbox), 21 bytes

@(x)nnz(~pdist(x))==1

Anonymous function. Input is a column vector. Output is true (displayed as 1) or false (displayed as0).

Try it online!

Explanation

pdist(x) computes a vector of Euclidean distances between all pairs of rows from x. It considers each pair only once (order of the two rows doesn't matter), and doesn't consider pairs formed by the same row twice.

In our case x is a column vector, so Euclidean distance between two rows is just absolute difference between the two numbers.

~ is logical (Boolean) negation, nnz is number of nonzeros, and ==1 compares to 1. So the result is true if and only if there is only one pair that gives zero distance.

Luis Mendo
fuente
2

Julia, 39 26 bytes

!a=sum(a.==a')==endof(a)+2

Explanation

The code generates a 2-dimensional table of booleans, which is then collected using the sum function, counting the number of same-element pairs in the cartesian square of A. Then this is compared to the length of the string plus two, and the quantities are equal only when there is exactly one repeat character.

This code redefines the NOT operator.

eaglgenes101
fuente
!a=sum(a.==a')==endof(a)+2 saves a few bytes. Try it online!
Dennis
2

Octave, 23 26 bytes

@(x)prod(sum(x==x'))==4

Try it online!

The x==x' part was inspired by flawr's answer. This is longer than Luis' answer, but it doesn't use any toolboxes.

Explanation:

This is an anonymous function that takes a vector x as input, and compares it to itself transposed. This will give a matrix where all diagonal elements are 1, and any off diagonal elements signals that there are duplicates elements.

The sum along any given column shows how many duplicates there are of that number. We want two of the numbers to have a duplicate, so we two values equal to two, and the rest unequal to two.

If we take the product of this matrix, we'll get 4 if there are only two equal elements (2*2*1*1*1*1*...), and something other than 4 if there are no duplicates, or more than two.

Stewie Griffin
fuente
2

PHP, 46 bytes

<?=count(array_unique($argv))==count($argv)-1;

Counts the number of entries in $argv and compares it to the number of unique entries. If the former is higher than the latter by 1 then truthy, else falsey.

Try it on eval.in!

roberto06
fuente
Do you have to use the variable name $argv can you not just use $a instead?
dading84
3
@dading84 $argv is the list of command line parameters. So: no, he cannot just use $a.
Titus
2

05AB1E, 6 5 bytes

{¥>ΘO

Try it online!

{¥>ΘO   # example input:               [1, 6, 3, 4, 4, 7, 9]
{       # sort                      -> [1, 3, 4, 4, 6, 7, 9]
 ¥      # get deltas                -> [  2, 1, 0, 2, 1, 2 ]
  >     # increment                 -> [  3, 2, 1, 3, 2, 3 ]
   Θ    # truthify (only 1 gives 1) -> [  0, 0, 1, 0, 0, 0 ]
    O   # sum                       -> 1

1 being the only truthy value in 05AB1E, we can stop here. (Thanks @Emigna for pointing that out.)

To get only two distinct values, we can optionally add:

     Θ  # equals 1?                 -> 1
Arnauld
fuente
1
If it is okay to return any falsey value for the falsey cases, you can skip the Θ, as 1 is the only truthy value in 05AB1E.
Emigna
@Emigna Thanks! I was not sure whether it was approved by the OP, but I guess it is.
Arnauld
I'm afraid you need to revert to the previous solution as ¢ will not work. It would count [19,4,4,9] as false and [19,9] as true since it finds the 0 in 10.
Emigna
@Emigna Thanks for spotting that. I think that's fixed.
Arnauld
{¥_O should be okay as well.
Emigna
2

APL (Dyalog Unicode), 7 bytesSBCS

1=≢-≢∘∪

Try it online!

Explanation:

1=≢-≢∘∪   Monadic function train
    ≢∘∪   Generate a list of unique items in the input,
          and return the length of that list
  ≢-      Take the length of the input and subtract the above
1=        If the difference is 1, true, otherwise false
voidhawk
fuente
1

Japt, 7 bytes

â ʶUÊÉ

Try it


Explanation

Remove duplicates (â), get length (Ê) and compare equality () with the length (Ê) of the input (U) minus 1 (É).

Shaggy
fuente
Isn't that 12 bytes? Aren't âÊɶ multibyte characters?
RedClover
1

05AB1E, 5 bytes

gIÙg-

Try it online!

g     # Get number of elements in input
 IÙg  # Get number of unique elements in input
    - # Subtract

In 05AB1E 1 is the only truthy value, so for a truthy result there must be exactly 1 duplicate element removed by the uniquify.

Riley
fuente