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]

Respuestas:
Python 3,
3028 bytesPruébalo en línea!
{*m}lanza la lista a unsetobjeto, 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.
fuente
{*m}atajo en lugar deset, ¡bien jugado!lambda m:~-len(m[len({*m}):])Casco , 4 bytes
Pruébalo en línea!
Explicación
fuente
MATL ,
7, 6 bytesPruébalo en línea!
¡Un byte guardado gracias a @Guiseppe!
Explicación:
fuente
sessumysumsuma a lo largo de la primera dimensión no única (columnas), y la matriz es simétrica, ¿no podría ser esto enslugar deXs?Haskell , 34 bytes
Pruébalo en línea! Basado en la respuesta de H.PWiz .
fuente
Jalea ,
85 bytesPruébalo en línea!
Explicación
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)fuente
QL_Ldaría como resultado-1verdadero y algún número menor que-1o0para falsey (por ejemplo[1,6,3,4,4,7,9,9,9], regresaría-3, mientras[1,6,3,4,7,9]que regresaría0).-2.JavaScript (ES6), 30 bytes
Pruébalo en línea
fuente
Pushy , 8 bytes
Implementación simple de verificar si
len(set(list)) == len(list)-1:Explicación:
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!
fuente
Octava , 25 bytes
Esto no está utilizando un enfoque
groupo ununiqueenfoque como muchas de las otras respuestas, sino más bien el "producto cartesiano" de todas las comparaciones posibles.Explicación
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
Pruébalo en línea!
fuente
J ,
76 bytes=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!
fuente
.~con=Retina ,
151211 bytesGracias a Neil por guardar 1 byte.
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
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).
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).Asegúrese de eliminar exactamente un duplicado.
fuente
A`.to count newlines, because it drops the last one.)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 terminatingAandGoutput 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.^$¶.Ais identical regardless of whether it retains a single empty line or discards all lines.05AB1E, 4 bytes
Try it online!
Outputs
1as truthy, any other non-negative integer as falsy. In 05AB1E,1is the only truthy number (thanks @Emigna for the insight!).Explanation
fuente
Ruby, 32 bytes
fuente
Array#size?->s{s.uniq.size==s.size-1}C# (.NET Core), 35 + 18 bytes
+18 for using
System.Linq.Try it online!
67 byte alternative without Linq:
Try it online!
fuente
Excel, 42 bytes
Danish language version
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:
English language version (44 bytes)
fuente
R,
3231 bytes-1 byte thanks to @JarkoDubbeldam
Try it online!
Reads from stdin, writes to stdout.
duplicatediterates through the list, replacing the values oflwithTRUEif that value occurs earlier in the list, andFALSEotherwise. If there's a unique pair of soulmates, there should be exactly oneTRUEvalue, so the sum should be1.fuente
scan()approach.PowerShell,
4037 bytesTry it online!
The
Sort-Objectcommand (aliassort) 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
.countof this object (i.e., how many elements it has) is-equal to the.countof our input array-1(i.e., we have exactly one duplicate entry).Saved 3 bytes thanks to Sinusoid.
Fixed bug thanks to TessellatingHeckler.
fuente
1,2,1-get-uniqueonly works on pre-sorted input. How about($args|sort -u).count-eq$args.count-1which is also 37 but does work for all the test cases, if you call it likef 1 2 1instead off 1,2,1?Perl 5, 36 + 1 (
-a) = 37 bytesTry it online!
fuente
@k{@F}++;say@F==1+keys%kHaskell, 37 bytes
Try it online!
fuente
Octave / MATLAB (with Statistics package / toolbox), 21 bytes
Anonymous function. Input is a column vector. Output is
true(displayed as1) orfalse(displayed as0).Try it online!
Explanation
pdist(x)computes a vector of Euclidean distances between all pairs of rows fromx. 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
xis a column vector, so Euclidean distance between two rows is just absolute difference between the two numbers.~is logical (Boolean) negation,nnzis number of nonzeros, and==1compares to1. So the result istrueif and only if there is only one pair that gives zero distance.fuente
Jq 1.5,
5325 bytesInspired by Riley's answer and much shorter then my original solution.
Try it online!
fuente
Julia,
3926 bytesExplanation
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.
fuente
!a=sum(a.==a')==endof(a)+2saves a few bytes. Try it online!Pyth, 6 bytes
Verify all the test cases.
l{- Gets the number of unique elements.tlQ- Gets the length of the input list, decremented.q- Checks equality.7 bytes
Verify all the test cases
fuente
Octave,
2326 bytesTry 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
xas input, and compares it to itself transposed. This will give a matrix where all diagonal elements are1, 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
4if there are only two equal elements (2*2*1*1*1*1*...), and something other than4if there are no duplicates, or more than two.fuente
PHP, 46 bytes
Counts the number of entries in
$argvand 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!
fuente
$argvis the list of command line parameters. So: no, he cannot just use$a.05AB1E,
65 bytesTry it online!
1being 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:
fuente
Θ, as1is the only truthy value in 05AB1E.¢will not work. It would count[19,4,4,9]as false and[19,9]as true since it finds the0in10.{¥_Oshould be okay as well.APL (Dyalog Unicode), 7 bytesSBCS
Try it online!
Explanation:
fuente
Jelly, 10 bytes
Try it online!
a longer but different approach
fuente
Japt, 7 bytes
Try it
Explanation
Remove duplicates (
â), get length (Ê) and compare equality (¶) with the length (Ê) of the input (U) minus 1 (É).fuente
âÊɶmultibyte characters?Haskell, 37 bytes
Try it online!
fuente
05AB1E, 5 bytes
Try it online!
In 05AB1E 1 is the only truthy value, so for a truthy result there must be exactly 1 duplicate element removed by the uniquify.
fuente