Palabras primas dobles

Sep 09 2020

Considere una palabra / cadena de longitud \$n\$, incluyendo solo las letras AZ, az. Una palabra / cadena es una palabra prima doble si y solo si n es prima y la suma de las letras, s, también es prima, usando su posición numérica en el alfabeto ( a=1, B=2, c=3, etc.).

La entrada puede ser cualquier combinación de caracteres alfabéticos en mayúsculas o minúsculas, ya que no hay diferencia numérica entre ao A.

La salida es cualquier formato lógico apropiado relacionado con su idioma. es decir, Verdadero o Falso, V o F, 1 o 0, etc. Se agradece mucho especificar en qué formato aparecerá su salida, pero no es obligatorio. (La salida no necesita incluir n, s, pero los incluyo a continuación como demostración y ejemplo)

La condición ganadora es el código más corto en bytes capaz de detectar si una cadena es un número primo doble, ajustando ambas condiciones para que n y s sean primos. (Ahora he incluido casos de las 4 situaciones posibles de n, s).

Ejemplos

Input -> Output (n, s)

Prime -> True (5, 61)
han -> True (3, 23)
ASK -> True (3, 31)
pOpCoRn -> True (7, 97)
DiningTable -> True (11, 97)
METER -> True (5, 61)

Hello -> False (5, 52)
SMILE -> False (5, 58)
frown -> False (5, 76)

HelpMe -> False (6, 59)
John -> False (4, 47)
TwEnTy -> False (6, 107)

HelloWorld -> False (10, 124)
Donald -> False (6, 50)
telePHONES -> False (10, 119)

A -> False (1, 1) 
C -> False (1, 3) {1 is not prime}
d -> False (1, 4)

Respuestas

5 cairdcoinheringaahing Sep 09 2020 at 05:03

Gelatina , 12 bytes

ŒuO_64µL,SẒP

¡Pruébelo en línea!

Cómo funciona

ŒuO_64µL,SẒP - Main link, takes string s as argument e.g. s = "Prime"
Œu           - Convert to upper case                          "PRIME"
  O          - Convert to ordinals                            [80, 82, 73, 77, 69]
   _64       - Subtract 65 (call this L)                      [16, 18, 9, 13, 5]
      µ      - Start a new link with L as the left argument
       L     - Take the length                                5
         S   - Take the sum                                   61
        ,    - Pair the two values                            [5, 61]
          Ẓ  - Take primality of each                         [1, 1]
           P - Take product                                   1
5 RobinRyder Sep 09 2020 at 20:34

R , 68 71 bytes

+3 bytes para corregir un error señalado por Dominic van Essen

`?`=sum;s=?b<-utf8ToInt(scan(,""))%%32;l=?b^0;l-1&5>?c(!s%%1:s,!l%%1:l)

¡Pruébelo en línea!

Observe que para convertir letras mayúsculas y minúsculas a los números enteros 1 ... 26, podemos tomar el punto de código ASCII módulo 32. sum(!x%%1:x)es una forma elegante de contar el número de divisores de x, que será igual a 2 sif xes primo.

Sin golf:

`?` = sum                       # shorthand for sum
b = utf8ToInt(scan(, "")) %% 32 # take input and convert to ASCII, then take mod 32
s = sum(b)
l = sum(b^0)                    # l = length(b)
5 > sum(c(!s%%1:s,!l%%1:l))    # sum the number of divisors of s and l, and check whether you get <5.
       & l!=1                   # and that l is not 1
5 Razetime Sep 09 2020 at 14:37

Rubí , 27 59 bytes

->a{[a.size,a.upcase.bytes.map{|i|i-64}.sum].all? &:prime?}

+33 bytes después de corregir la solución, gracias a DrQuarius.

¡Pruébelo en línea! o Verificar todos los casos de prueba

4 Abigail Sep 09 2020 at 06:48

perl -Mfeature = say -MList :: Util = sum -pl, 95 bytes

s/[^a-z]//gi;$m=sum map-64+ord,split//,uc;$_=(1 x y===c)!~/^(11+)\1+$|^1$/&&(1x$m)!~/^(11+)\1$/

¡Pruébelo en línea!

¿Como funciona?

s/[^a-z]//gi;   # Clean the input, remove anything which isn't an ASCII letter.

                          uc;     # Upper case the string
                  split//,        # Split it into individual characters
          -64+ord                 # Calculate its value: 
                                  #           subtract 64 from its ASCII value
       map                        # Do this for each character, return a list
$m=sum                            # Sum the values, and store it in $m

     y===c                        # Returns the length of the input string
(1 x y===c)                       # Length of the input string in unary

/^(11+)\1+$|^1$/                  # Match a string consisting of a composite
                                  # number of 1's, or a single 1
!~                                # Negates the match, so
(1 x y===c)1~/^(11+)\1+$|^1$/     # this is true of the input string (after
                                  # cleaning) has prime length

(1x$m)!~/^(11+)\1+$/              # Similar for the sum of the values --
                                  # note that the value is at least 2, so
                                  # no check for 1.

Combinando esto, el programa imprimirá 1 en las líneas que coinciden con las condiciones, y una línea vacía para las líneas que no coinciden.

4 KevinCruijssen Sep 09 2020 at 13:41

05AB1E , 10 bytes

gAIlk>O‚pP

Ingrese como una lista de caracteres.

Pruébelo en línea o verifique todos los casos de prueba .

Explicación:

g           # Get the length of the (implicit) input-list
 A          # Push the lowercase alphabet
  I         # Push the input-list of characters
   l        # Convert the input to lowercase
    k       # Get the (0-based) index of each character in the alphabet-string
     >      # Increase each by 1 to make them 1-based indices
      O     # Take the sum of that
       ‚    # Pair the length together with this sum
        p   # Check for both whether they're a prime (1 if it's a prime; 0 if not)
         P  # And check if both are truthy by taking the product of the pair
            # (after which the result is output implicitly)
4 DominicvanEssen Sep 10 2020 at 04:51

R , 70 bytes

function(s,S=sum,t=S(utf8ToInt(s)%%32))S(!nchar(s)%%1:t)^S(!t%%1:t)==4

¡Pruébelo en línea!

Me obligué a no mirar la respuesta de Robin Ryder antes de intentarlo, y (satisfactoriamente) resulta que hemos utilizado algunos trucos de golf bastante diferentes.

tes el total de todos los índices de letras. Es seguro que sea mayor o igual que nchar(s)(solo es igual si la cadena ses "A" o "a"). Por lo tanto, podemos usar módulo 1:tpara probar la primacía de la longitud de la cadena en lugar de módulo 1:nchar(s), y no es necesario desperdiciar caracteres en una declaración de variable para almacenar nchar(s).

Ambas pruebas de primalidad sum(!t%%1:t)y sum(!nchar(s)%%1:t)deben ser iguales a 2 si tanto los índices de suma de letras como la longitud de la cadena son primos.
Podríamos comprobar si ambos son 2, pero esto requiere ==2dos (más a &o equivalente), lo que parece un desperdicio. ¿Está bien comprobar que el total es 4? El caso de borde del que debemos preocuparnos es si uno de ellos es igual a 1 y el otro a 3: esto sucede para la cadena "D" (longitud = 1 e índice de caracteres = 4 con divisores 1, 2 y 4). Entonces no está bien. ¿Podemos multiplicarlos? Además no, porque 1 y 4 volverán a dar 4 (piense en la cadena "F").
Pero, dado que sabemos que la longitud de la cadena debe ser menor o igual a la suma de índices de caracteres, podemos usar la potenciación: la única forma de obtener 4 es 4 ^ 1 o 2 ^ 2, y dado que la suma de índices de caracteres no puede ser 1 si la longitud de la cadena es 4, 2 ^ 2 es la única posibilidad.

Entonces, la verificación final combinada para la doble primalidad es sum(!nchar(s)%%1:t)^sum(!t%%1:t)==4guardar 3 caracteres en comparación con probarlos por separado.

4 Shaggy Sep 11 2020 at 23:47

Rockstar , 327 321 319 bytes

¡No incorporado para probar primos!
¡Sin conversión de caso!
¡No hay forma de obtener el punto de código de un personaje!

¡¿Por qué me hago estas cosas ?! Pasé tanto tiempo haciendo que la maldita cosa funcionara, estoy seguro de que está lejos de ser un golf óptimo, pero funcionará por ahora.

F takes N
let D be N
let P be N aint 1
while P and D-2
let D be-1
let M be N/D
turn up M
let P be N/D aint M

return P

G takes I
Y's0
N's27
while N
cast N+I into C
if C is S at X
return N

let N be-1

return G taking 64

listen to S
X's0
T's0
while S at X
let T be+G taking 96
let X be+1

say F taking T and F taking X

Pruébelo aquí (deberá pegar el código)

3 Neil Sep 09 2020 at 05:21

Retina 0.8.2 , 77 bytes

\W|\d|_

$
¶$`
\G.
1
T`L`l
[t-z]
55$&
[j-z]
55$&
T`_l`ddd
.
$*
A`^(..+)\1+$

¡Pruébelo en línea! El enlace incluye casos de prueba. Explicación:

\W|\d|_

Elimina todo lo que no sea una letra.

$
¶$`

Duplica las letras.

\G.
1

Reemplaza las letras de la primera línea con 1s, tomando así la longitud en unario.

T`L`l

Convierte las letras restantes a minúsculas.

[t-z]
55$&
[j-z]
55$&
T`_l`ddd

Conviértelos en dígitos que sumen su posición numérica.

.
$*

Convierta los dígitos en unario, obteniendo así su suma.

A`^(..+)\1+$

Elimina los valores compuestos.

Compruebe que todavía estén presentes ambos valores.

3 Noodle9 Sep 09 2020 at 07:15

Python 3 , 86 78 87 bytes

Ahorro de 8 bytes gracias a ovs !!!
Se agregaron 9 bytes para corregir un error amablemente señalado por Robin Ryder .

lambda s:~-len(s)*all(n%i for n in(len(s),sum(ord(c)&31for c in s))for i in range(2,n))

¡Pruébelo en línea!

Devuelve un valor verdadero o falso.

3 xash Sep 10 2020 at 05:18

Brachylog , 11 bytes

ḷạ-₉₆ᵐ+ṗ&lṗ

¡Pruébelo en línea!

Cómo funciona

ḷạ-₉₆ᵐ+ṗ&lṗ (is the implicit input)
ḷ           to lowercase
 ạ          to list of char codes
  -₉₆ᵐ      minus 96 (so 'a' -> 1)
      +     summed
       ṗ    prime?
        &l  and is the input's length
          ṗ prime?
3 J42161217 Sep 09 2020 at 04:59

Wolfram Language (Mathematica) , 34 bytes

PrimeQ@*Tr/@(LetterNumber@#&&1^#)&

¡Pruébelo en línea!

-22 bytes de @att

2 Shaggy Sep 09 2020 at 06:37

Japonés , 16 bytes

Êj ©Uu ¬mc xaI j

Intentalo

2 Jonah Sep 10 2020 at 11:24

J , 27 22 18 bytes

1*/@p:#,1#.32|3&u:

¡Pruébelo en línea!

-5 bytes gracias a xash

-4 bytes gracias a Dominic van Essen

  • 32|3&u: Convierta cada letra en su índice convirtiendo primero a su número ascii, el modding por 32.
  • 1#. Suma.
  • #, Anteponer la longitud de la lista.
  • 1...p: ¿Son primos cada uno de esos dos números?
  • */@ Multiplíquelos juntos, ¿son todos primos?
2 tom Sep 10 2020 at 01:53

C - 119108 99 98 bytes (gcc)

¡@ceilingcat guardó otro byte!

b,t,e;p(c){for(;--e&&c%e;);c=e==1;}a(char*a){t=0;for(e=b=strlen(a);b;)t+=a[--b]%32;t=p(e)*p(e=t);}

pruébalo en línea

previamente

¡Muchas gracias a @DominicvanEssen y @ceilingcat por ahorrar 20 bytes! - y particularmente a Dominic por corregir el error en n = 1 (no primo)

b,t,e;p(c){for(b=c;--b&&c%b;);c=b==1;}a(char*a){t=0;for(e=b=strlen(a);b;)t+=a[--b]%32;t=p(e)*p(t);}

primer intento por debajo de 119 bytes

a(char*a){int t=0,d=strlen(a),e=d;while(d)t+=a[--d]%32;return p(e)*p(t);}
p(int c){int b=c;while(--b&&c%b);return b<2;}

De hecho, puede ahorrar 3 bytes usando while(c%--b)en la segunda rutina, pero esto falla para el caso de p (1), por ejemplo, 'a'. u otros personajes individuales.

pruébalo en línea

2 user Sep 09 2020 at 09:00

Scala , 75 74 69 bytes

| =>p(|size)&p(|map(_&95-64)sum)
def p(n:Int)=(2 to n/2)forall(n%_>0)

¡Pruébelo en línea!

1 GalenIvanov Sep 09 2020 at 14:08

Factor , 78 bytes

: d ( s -- ? ) dup [ length ] dip >lower [ 96 - ] map sum [ prime? ] bi@ and ;

¡Pruébelo en línea!

1 Lyxal Sep 09 2020 at 06:18

05AB1E , 11 bytes

uÇ64-Op¹gp&

¡Pruébelo en línea!

Bytes eliminados debido a la falta de restricciones de entrada

1 Arnauld Sep 09 2020 at 05:55

JavaScript (Node.js) , 88 bytes

Devuelve 0 o 1 .

s=>(g=k=>n%--k?g(k):k==1)(Buffer(s).map(c=>x+=n<(n+=c>64&(c&=31)<27&&c),x=n=0)|n)&g(n=x)

¡Pruébelo en línea!

Comentado

Función auxiliar

g = k =>                   // g is a helper function testing if n is prime
  n % --k ?                //   decrement k; if it does not divide n:
    g(k)                   //     do recursive calls until it does
  :                        //   else:
    k == 1                 //     test whether k = 1

Función principal

s =>                       // s = input string
  g(                       // test if the 'sum of the letters' is prime
    Buffer(s).map(c =>     //   for each ASCII code c in s:
      x +=                 //     increment x if ...
        n < (              //       ... n is less than ...
          n +=             //         ... the new value of n:
            c > 64 &       //           if c is greater than 64
            (c &= 31) < 27 //           and c mod 32 is less than 27:
            && c           //             add c mod 32 to n
        ),                 //
      x = n = 0            //     start with x = n = 0
    ) | n                  //   end of map(); yield n
  )                        // end of the first call to g
  & g(n = x)               // 2nd call to g with the 'length' x
1 Xcali Sep 11 2020 at 10:36

Perl 5 -pl , 52 bytes

Utiliza la expresión regular de identificación principal de la respuesta de @ Abigail

$_.=$".1x s/./1x(31&ord$&)/ge;$_=!/\b((11+)\2+|1)\b/

¡Pruébelo en línea!

1 DrQuarius Sep 13 2020 at 12:39

Rubí , 50 55 50 bytes

->s{[s.size,s.upcase.sum-64*s.size].all? &:prime?}

¡Pruébelo en línea!

+5 bytes debido a un malentendido sobre si las matrices se pueden considerar verdaderas.

-5 bytes gracias a Razetime, usando el buen truco de poner "&: prime?" al final en lugar de hacer un ".map (&: prime?)" antes de ".all?".

Publicado por separado porque la solución de Razetime en realidad no sumaba el índice alfabético, sino simplemente los ordinales ascii. Falla para las palabras primarias dobles "DiningTable" y "METER" .

1 LegionMammal978 Oct 28 2020 at 01:05

Cáscara , 12 bytes

&ṗL¹ṗṁȯ-64ca

¡Pruébelo en línea! Emite un número verdadero si la palabra es una palabra prima doble y 0 en caso contrario.