Nadie sabe los números GAU

22

Déjame presentarte los números GAU

GAU(1) = 1  
GAU(2) = 1122  
GAU(3) = 1122122333  
GAU(4) = 11221223331223334444  
GAU(6) = 11221223331223334444122333444455555122333444455555666666  
...  
GAU(10) = 11221223331223334444122333444455555122333444455555666666122333444455555666666777777712233344445555566666677777778888888812233344445555566666677777778888888899999999912233344445555566666677777778888888899999999910101010101010101010  

¡Este desafío es bastante simple!

Dado un número entero n> 0, encuentre el número de dígitos de GAU (n)

Ejemplo

Hagamos GAU (4)
, tomamos los siguientes pasos (hasta llegar a 4) y los concatenamos

[1][122][122333][1223334444]   

debe escribir cada número tantas veces como sea su valor, pero debe contar cada vez desde 1

Intentemos hacer GAU (5)
tendremos que contar del 1 al 1

[1]   

luego de 1 a 2 (pero repitiendo cada número tantas veces como su valor )

[122]     

luego de 1 a 3

[122333]   

luego de 1 a 4

[1223334444]    

y finalmente del 1 al 5 (este es el último paso porque queremos encontrar GAU ( 5 ))

[122333444455555]     

Ahora tomamos todos estos pasos y los concatenamos,
el resultado es GAU (5)

11221223331223334444122333444455555     

Estamos interesados ​​en la cantidad de dígitos de estos números GAU.

Casos de prueba

Entrada⟼Salida

n   ⟼ Length(GAU(n))

1   ⟼ 1  
2   ⟼ 4  
3   ⟼ 10  
10  ⟼ 230   
50  ⟼ 42190  
100 ⟼ 339240  
150 ⟼ 1295790  

Este es un desafío de .
El código más corto en bytes ganará.

Si todavía tiene alguna pregunta, hágamelo saber.
Realmente quiero que todos aquí comprendan este patrón complejo mágicamente oculto


fuente
44
¿Qué significa GAU?
Leaky Nun
21
G es para GAU, A y U simplemente están ahí sin razón
2
Hasta n = 9, las longitudes son números tetraédricos, pero más allá de eso, los números de varios dígitos se interponen en el camino de una forma cerrada simple
Miff
Para su información, su caso de prueba dice n ⟼ Length(GUA(n)), no GAU (n).
numbermaniac
2
@numbermaniac gracias por ver esto. Los números GUA son totalmente diferentes. ¡Todavía no se han inventado!

Respuestas:

14

SOGL V0.12 , 11 10 8 7 5 bytes

∫∫l*+

Pruébalo aquí! - esto espera ser llamado como una función con la entrada en la pila y el cuadro de entrada vacío.
Alternativa de 7 bytes que toma la entrada del cuadro de entrada:

0.∫∫l*+

Pruébalo aquí!

0      push 0
 .     push the input
  ∫    iterate over a range 1..POP (input) inclusive, pusing the current number
   ∫    iterate over 1..POP (above loops number) inclusive, pusing the current number
    l    push that numbers length without popping the number
     *   multiply the length by the number
      +  add to the zero, or whatever it is now
dzaima
fuente
push that numbers length without popping the numberagradable
Erik the Outgolfer
7

Brain-Flak , 166 bytes

<>(((()()())({}){})())<>{({}[()]<({}({}<<>({}[()])((){[()](<()>)}{}){{}((((({})({})){}{}){}))<>(({}<({}())>){()<({}[({})])>}{})(<>)}{}<>>({}({})())))>)}{}({}<{}{}{}>)

Pruébalo en línea!

Explicación

<>(((()()())({}){})())<>           # Initialize second stack with 9 and 10
{({}[()]<                          # Do main loop n times:
  ({}
    ({}
      <
        <>({}[()])                 # Subtract 1 from counter to next power of 10
        ((){[()](<()>)}{}){        # If reached a power of 10 (say, 10^k):
          {}((((({})({})){}{}){})) # Multiply existing (10^k*0.9) by 10 and push twice
          <>                       # On first stack
          (
            ({}<({}())>)           # Increment length of numbers
            {()<({}[({})])>}{}     # Divide length of new set of numbers by this length
          )                        # Add together to get new set of numbers length
        (<>)}  
      {}<>>  
      ({}({})())                   # Add number length to number set length
    )                              # Add number set length to new segment length
  )                                # Add new segment length to total length
>)}                                # End main loop
{}({}<{}{}{}>)                     # Put result on stack by itself
Nitrodon
fuente
7

Casco , 5 bytes

ṁLΣQḣ

Pruébalo en línea!

Explicación

ṁ  map over
 L  length
  Σ  sum list
   Q  all sublists
    ḣ  range 1 .. N
Icer Wild
fuente
Buen algoritmo!
H.PWiz
4

05AB1E , 5 bytes

LŒJJg

Pruébalo en línea!

Explicación

L      # push [1 .. a]
 Π    # all substrings (a)
  J    # numbers to strings (inner)
   J   # numbers to strings (outer)
    g  # length
Icer Wild
fuente
Bienvenido al sitio :)
DJMcMayhem
3

Casco , 7 bytes

Σ∫mS*Lḣ

Pruébalo en línea!

Ungolfed / Explicación

         -- implicit input N                        | 10
  m   ḣ  -- map the following function over [1..N]  | [1,2,3,4]
   S*L   --   multiply length of number by itself   | [1,2,3,4] (only important for numbers ≥ 10)
 ∫       -- prefix sums                             | [0,1,3,6,10]
Σ        -- sum                                     | 20
ბიმო
fuente
3

Casco , 7 bytes

ṁLṁṘNḣḣ

Pruébalo en línea!

Explicación

          Implicit input, e.g 4
      ḣ   Range from 1 to n                               [1,2,3,4]
     ḣ    Prefixes                                        [[],[1],[1,2],[1,2,3],[1,2,3,4]]
  ṁ       Map and then concatenate
   ṘN     Repeat each number in each list by its index    [[],[1],[1,2,2],[1,2,2,3,3,3],[1,2,2,3,3,3,4,4,4,4]]
                                                          [1,1,2,2,1,2,2,3,3,3,1,2,2,3,3,3,4,4,4,4]
ṁ         Map and then sum
 L        Length (of number: 10 -> 2)                     26
H.PWiz
fuente
Oh, otra solución de Husk :) No vi tu envío al publicar el mío, el mismo bytecount pero son lo suficientemente diferentes, así que también dejaré el mío aquí.
ბიმო
3

Python 2 , 59 58 bytes

Otro bytes el polvo gracias a Jonathan Frech.

f=lambda n:n and sum(i*len(`i`)for i in range(n+1))+f(n-1)

Pruébalo en línea!

No es corto pero eh ... qué diablos.

totalmente humano
fuente
len(`i`)*i for-> i*len(`i`)for.
Jonathan Frech
53 bytes , no recursivo.
Jonathan Frech
3

CJam , 20 bytes

q~),(\{),{_s,*+}*+}%

Pruébalo en línea!

El número se pasa en el campo "entrada".

Explicación no reflejada: (entrada de ejemplo = 2)

q~),(\{),{_s,*+}*+}%                                             | Stack:
q                     read input as string                       | "2"
 ~                    eval input (add it to stack as integer)    | 2
  )                   add 1                                      | 3
   ,                  range (convert to array with values 0...N) | [0, 1, 2]
    (                 pop first item of array                    | [1, 2] 0
     \                swap top two values of stack               | 0 [1, 2]
      {           }   for each item in array...                  | 0 1
       )              add 1                                      | 0 2
        ,             range (convert to array with values 0...N) | 0 [0, 1]
         {     }      for every element in the array...          | 0 0
          _           duplicate                                  | 0 0 0
           s          convert to string                          | 0 0 "0"
            ,         get length of string                       | 0 0 1
             *        multiply                                   | 0 0
              +       add                                        | 0 1
                *     fold                                       | 0 1
                 +    add                                        | 1
                   %  repeat                                     | 4

Parece difícil cuando se explica lol.

Iaka Noe
fuente
2

J, 24 bytes

[:+/[:+/\[:(*#@":"0)1+i.

Enfoque de alto nivel similar a la respuesta APL de dzaima, traducido a J, excepto calculamos la longitud de la serie al convertirlo en una cadena primera vez de tomar registros, y se llega a utilizar el gancho de J para multiplicar esa longitud por el número en sí: (*#@":"0). Después de eso es solo la suma de la suma de escaneo.

Pruébalo en línea!

Jonás
fuente
1
1(#.]*#\*#\.)1#@":@+i.también funciona para 22 bytes
millas
@miles Eso es inteligente, me tomó un poco entenderlo. ¿Cuánto tiempo llevas programando en J?
Jonás
Un poco después me uní a code-golf. En realidad, no lo uso para escribir ningún programa real, ya que no sé que sería capaz de leerlo, pero ahora lo uso como una calculadora de escritorio avanzada, y generalmente siempre tengo una ventana abierta para calcular algo.
millas
2

R , 39 bytes

function(n)sum(nchar(rep(1:n,n:1*1:n)))

¡Verifique todos los casos de prueba!

Algoritmo simple; Observé, como la mayoría lo hizo, que para iadentro 1:n, ise repite i*(n-i+1)veces. Entonces creo ese vector, cuento el número de caracteres en cada uno y los sumo.

Giuseppe
fuente
1

Python 2, 51 50 bytes

lambda n:sum(~k*(k-n)*len(`k+1`)for k in range(n))
orlp
fuente
@LeakyNun ¿Por qué? Desarrollé esta respuesta yo mismo. Ni siquiera revisé las otras respuestas.
orlp
1
Esto ni siquiera da la respuesta correcta, da 0 para n = 1, 3 para n = 2 y 14 para n = 3
Halvard Hummel
@HalvardHummel Vaya, estropeó un letrero y olvidé un +1. Corregido ahora.
orlp
¡Veo que finalmente entendiste lo patern! ¿Hay alguna forma de probar su código en línea o la otra respuesta de Python 2 también cubre esto?
1

JavaScript (ES6), 50 42 bytes

Actualizado: ahora es básicamente un puerto de lo que están haciendo otras respuestas.

f=(n,i=1)=>n&&`${n}`.length*n*i+f(n-1,i+1)

Casos de prueba

Arnauld
fuente
1

Mathematica, 66 bytes

Tr[1^(f=Flatten)[IntegerDigits/@f@(a=Array)[a[#~Table~#&,#]&,#]]]&
J42161217
fuente
1

QBIC , 21 bytes

[:|[a|[c|A=A+!c$}?_lA
Steenbergh
fuente
1

En realidad , 13 bytes

R♂R♂i⌠;n⌡Mεjl

Pruébalo en línea!

Explicación:

R♂R♂i⌠;n⌡Mεjl
R              range(1, n+1)
 ♂R            range(1, x+1) for x in previous
   ♂i          flatten into 1D list
     ⌠;n⌡M     for x in list:
      ;n       repeat x x times
          εj   concatenate to string
            l  length
Mego
fuente
1

Japt , 12 11 10 9 bytes

õõÈ*sÊÃxx

Pruébelo o pruebe todos los números del 1 al 150 .


Explicación

Entrada implícita de entero U.

õõ

Genere una matriz de enteros de 1 a Uy luego genere sub-matrices de 1 a cada entero.

È   Ã

Pase los elementos de cada subconjunto a través de una función.

*sÊ

Convierta el elemento actual en una cadena ( s), obtenga su longitud ( Ê) y multiplíquelo por el elemento.

xx

Reduzca la matriz principal mediante la adición después de hacer lo mismo con cada matriz secundaria.

Lanudo
fuente
1

Jq 1.5 , 82 49 43 bytes

[range(.)+1|range(.)+1|"\(.)"*.|length]|add

Expandido

[   range(.)+1        # for i=1 to N
  | range(.)+1        # for j=1 to i
  | "\(.)"*.          # "j" copied j times
  | length            # convert to length
] | add               # add lengths

Ejecución de muestra

$ jq -Mr '[range(.)+1|range(.)+1|"\(.)"*.|length]|add' <<< "150"
1295790

Pruébalo en línea! también jqplay.org

jq170727
fuente
1

Apilado , 28 bytes

[~>[~>[:rep]"!]"!flat''#`#']

Pruébalo en línea!

Algunos podrían preguntar: "¿En qué punto son ilegibles los alias?" Si esto no está cerca, tiene una definición muy liberal de "legibilidad".

Explicación

[~>[~>[:rep]"!]"!flat''#`#']    input: N
 ~>[          ]"!               for each number K from 1 to N
    ~>[    ]"!                  for each number J from 1 to K
       :rep                     repeat J J times
                 flat           flatten the resultant array
                     ''#`       join by the empty string
                         #'     get the length of said string
Conor O'Brien
fuente
1

C # (.NET Core) , 94 80 74 bytes

n=>{int b=0,a=0,i;while(a++<n)for(i=0;i++<a;)b+=(i+"").Length*i;return b;}

Pruébalo en línea!

Esperaba encontrar una solución directa como la respuesta de @ kamoroso94 , pero me di por vencido porque estaba pasando demasiado tiempo en ello. Probablemente haya una forma de hacerlo, pero la fórmula debe ajustarse para cada paso de magnitud.

Expresiones de gratitud

14 bytes guardados gracias a @someone

6 bytes guardados gracias a @Kevin Cruijssen

Ayb4btu
fuente
1
n=>{int b=0,a=0,i;for(;a++<n;)for(i=0;i++<a;)b+=i.ToString().Length*i;return b;} Pruébalo en línea! para 80 bytes y rendimiento.
mi pronombre es monicareinstate
1
i.ToString()puede ser (i+"")guardar algunos bytes más.
Kevin Cruijssen
1

MATL , 15 bytes

:ttP*Y"10&YlQks

Pruébalo en línea!

Explicación:

:                range 1:input (implicit input)
 tt              duplicate twice
   P             reverse
    *            multiply elementwise
     Y"          runlength decoding
       10&Yl     log10
            Qk   increment and floor
              s  sum (implicit output)
Giuseppe
fuente
Ese logaritmo es costoso :-) Puede reemplazarlo convirtiéndolo en cadena, eliminando espacios, longitud::ttP*Y"VXzn
Luis Mendo
1

Perl 6 , 36 bytes

{[+] 1..*Z*($_...1).map:{.chars*$_}}

Pruébalo

Expandido:

{  # bare block lambda with implicit parameter 「$_」

  [+]               # reduce the following using &infix:«+»

    1 .. *          # Range from 1 to infinity

    Z*              # zip using &infix:«*»

    ( $_ ... 1 )    # sequence from the input down to 1
    .map:           # for each one
    { .chars * $_ } # multiply the number of digits with itself
}
Brad Gilbert b2gills
fuente
1

Carbón , 18 14 bytes

IΣE⊕NΣE⊕ι×λLIλ

Pruébalo en línea! El enlace es a la versión detallada del código. Editar: El uso Summe salvó 4 bytes. Explicación:

  E⊕N           Map from 0 to the input (loop variable i)
      E⊕ι       Map from 0 to i (loop variable l)
            Iλ  Cast l to string
           L    Take the length
         ×λ     Multiply by l
     Σ          Sum the results
 Σ              Sum the results
I               Cast to string
                Implicitly print
Neil
fuente
: | Suma suma números en las cadenas cuando se le dan argumentos de cadena
solo ASCII
@ Solo ASCII No fue eso, solo estaba imprimiendo un Σlugar ...
Neil
@ Solo ASCII Además, lo mejor que puedo hacer Sumes con 18 bytes:Print(Cast(Sum(Map(InclusiveRange(1, InputNumber()), Sum(Map(InclusiveRange(1, i), Times(l, Length(Cast(l)))))))));
Neil
@ ASCII de sólo traté suma de producto, sino que era 17 bytes: ≔⊕NθIΣEθ×⁻θι×ιLIι. Sin embargo, ¡en Incrementedlugar de InclusiveRangeafeitarme 4 bytes de mi comentario anterior!
Neil
1

[Dyalog APL], 22 20 bytes

{+/≢¨⍕¨↑,/(/⍨¨⍳¨⍳⍵)}

Pruébalo en línea!

Explicación:

{+/≢¨⍕¨↑,/(/⍨¨⍳¨⍳⍵)}
{                  } anonymous function with right argument named 
                ⍳⍵   range 1 to right arg
              ⍳¨     for each, range 1 to it
             ¨       for each
           /⍨          for each item, repeat right arg left arg times
          (       )  take that and
        ,/           join the sub-arrays together
                    convert from a nested array to a simple array (or something like that, I don't quite understand it :p)
     ⍕¨              convert each number to a char-array (aka string version)
   ≢¨                get length of each
 +/                  sum that together
dzaima
fuente