Encuentra cuántos caracteres alfanuméricos pueden estar formados por un solo número

23

Los caracteres alfanuméricos tienen valores ASCII:

0-9  ->  48-57
A-Z  ->  65-90
a-z  ->  97-122

Su desafío es tomar un número entero como entrada y generar la cantidad de caracteres que pueden formarse utilizando dígitos consecutivos de ese número. Los códigos de caracteres pueden superponerse. 666debe resultar en 2, ya que tiene 66dos veces.

Casos de prueba:

Input: 5698
Possible characters: '8' (56), 'E' (69), 'b' (98)
Output: 3

Input: 564693
Possible characters: '8' (56), 'E' (69)
Output: 2

Input: 530923864209124521
Possible characters: '5' (53), 'V' (86), '4' (52)  
Output: 3

Input: 1111111
Possible characters: 'ooooo' (5*111)
Output: 5

Input: 5115643141276343
Possible characters: '3' (51), '8' (56), 'L' (76), 's' (115)
Output: 4

Input: 56789
Possible characters: '8' (56), 'C' (67), 'N' (78), 'Y' (89)
Output: 4

Input: 94
Possible characters: ''
Output: 0

Input: 1
Output: 0

Los formatos de entrada y salida son opcionales (sí, puede tomar el entero como una cadena).

Stewie Griffin
fuente

Respuestas:

11

05AB1E , 8 7 bytes

žKÇIŒÃg

Pruébalo en línea!

Explicación

žK       # push [a-zA-Z0-9]
  Ç      # convert to list of ascii codes
   IΠ   # push all substrings of input
     Ã   # keep only the subtrings which exist in the list of acsii codes
      g  # push length of resulting list
Emigna
fuente
ŒžKÇÃgno funciona
Urna mágica del pulpo
@carusocomputing: Desafortunadamente, falla el 1111111caso de prueba.
Emigna
Ã, eso tiene MUCHO más sentido ahora que leí lo que está haciendo, mierda.
Urna mágica del pulpo
7

Brachylog , 22 bytes

∧Ạụ:Ạ:Ịcạ:?{tT&h∋~sT}ᶜ

Pruébalo en línea!

Explicación

       c                 Concatenate together:
∧Ạụ:                       "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    Ạ:                     "abcdefghijklmnopqrstuvwxyz"
      Ị                    "0123456789"
        ạ                Get the list of ASCII codes of that string
         :?{        }ᶜ   Count the number of results, for input [list of codes, Input], of:
            tT             Call the Input T
              &h∋          Take one ASCII code
                 ~sT       It is a substring of T
Fatalizar
fuente
Desafortunadamente para mí, afortunadamente para ti, no tengo acceso a una computadora en este momento;)
Leaky Nun
@LeakyNun He pensado en formas más cortas de hacerlo, ambas fallando debido a errores.
Fatalize
¿Puedes unir los dos Tjuntos?
Leaky Nun
1
¿Cuál es la causa de este error?
Leaky Nun
1
@LeakyNun Para, por ejemplo, el número entero 13, hay infinitas listas e infinitos números enteros que contienen 13, y no es obvio en qué orden debe enumerarlas.
Fatalize
7

MATL , 17 13 bytes

8Y2"G@oVXf]vn

Pruébalo en línea! O verificar todos los casos de prueba .

Explicación

8Y2     % Predefined literal: string with all letters, uppercase and lowercase,
        % and digits
"       % For each character in that string
  G     %   Push input, for example the string '5115643141276343'
  @     %   Push current character, such as 'A'
  o     %   Convert to its ASCII code, such as 65
  V     %   String representation, such as '65'
  Xf    %   Find string '65' within string '5115643141276343'. This gives a vector
        %   (possibly empty) with indices of occurrences
]       % End
v       % Concatenate all stack contents vertically
n       % Number of entries. Implicitly display
Luis Mendo
fuente
6

Java 7, 204 197 195 bytes

int c(String n){int r=0,i=0,e=n.length()-1,t;for(;i<e;r+=((t=new Byte(n.substring(i,i+2)))>47&t<57)|(t>64&t<91)|(t>96&t<100)|((t=new Short(n.substring(i,i++>e-2?i:i+2)))>99&t<123)?1:0);return r;}

Explicación:

int c(String n){       // Method with String parameter and integer return-type
  int r=0,             //  Result
      i=0,             //  Index
      e=n.length()-1,  //  Length of String -1
      t;               //  Temp integer
  for(;i<e;            //  Loop over the String using the index
    r+=                //   Append the result-sum with:
      ((t=new Byte(n.substring(i,i+2)))>47&t<57)|(t>64&t<91)|(t>96&t<100)
                       //    If two adjacent digits are a digit or letter
      |                //    or
      ((t=new Short(n.substring(i,i++>e-2?i:i+2)))>99&t<123)?
                       //    if three adjacent digits are a letter
       1               //     Raise the sum by 1
      :                //    Else:
       0               //     Keep the sum the same (by adding 0)
  );                   //  End of loop (implicit / no body)
  return r;            //  Return result
}                      // End of method

Código de prueba:

Pruébalo aquí

class M{
  static int c(String n){int r=0,i=0,e=n.length()-1,t;for(;i<e;r+=((t=new Byte(n.substring(i,i+2)))>47&t<57)|(t>64&t<91)|(t>96&t<100)|((t=new Short(n.substring(i,i++>e-2?i:i+2)))>99&t<123)?1:0);return r;}

  public static void main(String[] a){
    System.out.println(c("5698"));
    System.out.println(c("564693"));
    System.out.println(c("530923864209124521"));
    System.out.println(c("1111111"));
    System.out.println(c("5115643141276343"));
    System.out.println(c("56789"));
    System.out.println(c("94"));
    System.out.println(c("1"));
  }
}
Kevin Cruijssen
fuente
No puedo acceder a una computadora en este momento, así que no puedo confirmar, pero aquí hay dos sugerencias: 1. poner las iniciaciones en el bucle for. 2. en lugar de la manipulación de cadenas, use aritmética (use la división de enteros para iterar a través de los dígitos y use el módulo para extraer los últimos 2 o 3 dígitos).
Leaky Nun
@LeakyNun Gracias por las sugerencias. En cuanto a la primera, la razón por la que las inicializaciones de enteros están fuera del ciclo for es porque tengo que devolver el resultado ( r). Sin embargo, he podido jugar golf de 7 bytes al poner todo lo demás dentro del ciclo for, en un solo ternario. Veré si puedo hacer tu segunda sugerencia más tarde, tal vez. Mi hora de almuerzo ha terminado de nuevo, así que tendré que volver al trabajo. Lo tendré en cuenta.
Kevin Cruijssen
5

JavaScript (ES6), 71 70 bytes

f=([a,...b])=>a?(a&(a+=b[0])+b[1]<123|a>47&a<58|a>64&a<91|a>96)+f(b):0

Casos de prueba

Arnauld
fuente
4

Perl 5 , 47 bytes

46 bytes de código + -pbandera.

$"="|";$_=()=/(?=@{[48..57,65..90,97..122]})/g

Pruébalo en línea!

No pude encontrar una forma más corta de escribir eso 48..57,65..90,97..122: map{ord}0..9,a..z,A..Z(obtener el valor ascii de los caracteres) es un byte más largo. Y haciendo for$c(0..122){$\+=chr($c)=~/\pl|\d/ for/(?=$c)/g}}{(buscando todos los números, pero manteniendo solo aquellos cuyos números corresponden al valor ascii de letras ( \pl) o dígitos ( \d)) será 5 bytes más largo (tenga en cuenta que \pl|\dno puede ser reemplazado por \weste último también incluye guiones bajos)) .


Enfoque anterior (49 bytes):

for$@(48..57,65..90,97..122){$\+=()=/(?=$@)/g}}{
Dada
fuente
2

PHP, 68 bytes

for(;a&($a=$argn)[$i];)$d+=ctype_alnum(chr($a[$i].$a[++$i]));echo$d;

Versión en línea

Jörg Hülsermann
fuente
1

JavaScript (ES), 165 161 156 154 153 bytes

¡Sí, RegEx definitivamente no era la herramienta adecuada para el trabajo aquí!

n=>[/\d{2}/g,/\d{3}/g].map(e=>eval("while(x=e.exec(n)){a.push(m=x[0]);e.lastIndex-=m.length-1}"),a=[])|a.filter(x=>x>47&x<58|x>64&x<91|x>96&x<123).length

Intentalo

f=

n=>[/\d{2}/g,/\d{3}/g].map(e=>eval("while(x=e.exec(n)){a.push(m=x[0]);e.lastIndex-=m.length-1}"),a=[])|a.filter(x=>x>47&x<58|x>64&x<91|x>96&x<123).length

console.log(f(5698))//3
console.log(f(564693))//2
console.log(f(530923864209124521))//3
console.log(f(1111111))//5
console.log(f(5115643141276343))//4
console.log(f(56789))//4
console.log(f(94))//0
console.log(f(1))//0

Lanudo
fuente
Regexp no es tan malo; Un puerto de mi respuesta Retina llegó a 78 bytes.
Neil
1

Haskell, 161 157 138 129 126 bytes

import Data.List
f x=sum[1|y<-nub$concat$words.concat<$>mapM(\c->[[c],c:" "])x,any(elem$read y)[[48..57],[65..90],[97..122]]]

Me pregunto si hay una mejor manera de eliminar los engaños de la lista que importar Data.List para nub?

eje de arce
fuente
1
Si importa Data.Listsen lugar de Data.List, puede utilizar: y<-tail$powerslice x.
nimi
@nimi ¿Va en contra de las reglas del golf si tengo que descargar e instalar módulos no estándar? No creo que Data.Lists sea estándar en GHC.
maple_shaft
Hasta donde sé, todavía no tenemos consenso sobre lo que cuenta como un módulo estándar. Hay un par de respuestas de Haskell por aquí que usan Data.Lists. Incluso se menciona en los consejos de golf para Haskell : nadie se ha quejado hasta ahora.
nimi
@nimi Bueno, sinceramente, creo que si puedo descargar cualquier paquete de Cabal, podría escribir una función que resuelva el problema, subirlo e importar el módulo en mi solución. Técnicamente podría hacer trampa. Pero luego, ciertos desafíos no se pueden hacer con GHC básico, como cosas criptográficas, así que no lo sé.
maple_shaft
1
Volver a jugar al golf consejos: or $ f <$> listes any f list: any(elem$read y)[...].
nimi
0

Pyth, 19 17 14 bytes

l@jGUTmr0Csd.:

toma una cuerda.

-3 Bytes gracias a @LeakyNun

¡Intentalo!

Explicación

l@jGUTmr0Csd.:
    UT                # the list of digits [0,1,2,...,9]
  jG                  # join that on the lowercase alphabet (repetition doesn't matter)
              Q       # implicit input
            .:        # all substrings of the input
      m               # for each of those substrings
          sd          # Convert the string to a base 10 integer
         C            # convert that integer to the character with that number
       r0             # make that character lowercase
l@                    # length of the intersection of those two list of chars we generated
KarlKastor
fuente
En lugar de usar idT, puedes usar sd.
Leaky Nun
Además, l@jGUTmr0Csd.:podría ser más corto (no estoy seguro si funciona).
Leaky Nun
@LeakyNun ¡Gracias, esto funciona!
KarlKastor
0

Jalea , 8 bytes

ØBODf@ẆL

La entrada es una matriz de dígitos.

Pruébalo en línea!

Cómo funciona

ØBODf@ẆL  Main link. Argument: A (digit array)

ØB        Base 62; yield all alphanumeric ASCII characters.
  O       Ordinal; get their code points.
   D      Decimal; convert the code points into digit arrays.
      Ẇ   Window; yield all contiguous subarrays of A.
    f@    Filter swapped; keep all elements of the result to the right that appear
          in the result to the left.
       L  Length; count the matches.
Dennis
fuente
0

Ruby, 50 bytes.

p (0..~/$/).any?{|n|$_[n,2].to_i.chr=~/\p{Alnum}/}

Lee de entrada estándar; requiere que se invoque al intérprete de Ruby con la -nopción (implícitowhile gets bucle ).

Podría reducirse a 43 bytes si se le permitiera hacer coincidir los guiones bajos.

p (0..~/$/).any?{|n|$_[n,2].to_i.chr=~/\w/}
Ray Hamel
fuente
Esto no devuelve la cantidad de veces que aparecen los personajes. Además, falla 111, lo que debería volver 1pero estás devolviendo 0.
Value Ink