Un treno attraversa un ponte etichettato


9

Considera un ponte di lunghezza B formato da tessere etichettate con le cifre degli interi positivi concatenati. Ad esempio, se B avesse 41 anni, sarebbe simile al seguente:

-----------------------------------------
12345678910111213141516171819202122232425

Ora immagina un treno di lunghezza T che attraversi il ponte. Il punto più a sinistra del treno inizia dalla posizione X (1 indicizzato). Per comprendere meglio il problema, facciamo uno schema dell'evento, con B = 41, T = 10, X = 10 . Il treno viene disegnato usando segni uguali ( =) e linee:

         __________
         | ======== |
         | ======== |
-----------------------------------------
12345678910111213141516171819202122232425

Il treno può avanzare, ad ogni passo, per somma delle tessere uniche su cui si trova. Ad esempio, le tessere su cui si trova il treno sopra sono [1, 0, 1, 1, 1, 2, 1, 3, 1, 4]:, le tessere uniche (deduplicate) sono:, [1, 0, 2, 3, 4]e la loro somma è 10. Quindi, il treno può avanzare di 10tessere. Dovremmo disegnarlo di nuovo e ripetere il processo fino a quando il punto più a sinistra del treno ha superato l'ultima tessera:

                   __________
                   | ======== |
                   | ======== |
-----------------------------------------
12345678910111213141516171819202122232425

Somma di tessere uniche: 1 + 5 + 6 + 7 + 8 + 9 = 36. Il treno avanza di 36 tessere ...

                                                       __________
                                                       | ======== |
                                                       | ======== |
-----------------------------------------
12345678910111213141516171819202122232425

Il treno ovviamente ha attraversato completamente il ponte, quindi dovremmo fermarci ora.

Poiché le persone all'interno sono annoiate, contano le tessere che il treno ha avanzato ogni volta. In questo caso specifico, 10e 36. Riassumendo tutto, il treno si è mosso 46prima di passare il ponte.


Compito

Dati tre numeri interi positivi, B (la lunghezza del ponte), T (la lunghezza del treno) e X (la posizione di partenza, 1 indicizzata ), il tuo compito è determinare quante tessere il treno ha spostato fino a quando non ha attraversato il ponte seguendo le regole sopra.

  • Puoi presumere che:
    • B è superiore a T .
    • X è inferiore a B .
    • T è almeno 2 .
    • Il treno alla fine attraversa il ponte.
  • Si applicano tutte le nostre regole standard.
  • Questo è , quindi vince il codice più corto in byte!

Casi test

Ingresso ([B, T, X]) -> Uscita

[41, 10, 10] -> 46
[40, 10, 10] -> 46
[30, 4, 16] -> 24
[50, 6, 11] -> 50

Un altro esempio funzionante per l'ultimo caso di test:

Il ponte è di lunghezza 50, il treno 6 e la posizione di partenza è 11.

          ______
          | ==== |
          | ==== |
--------------------------------------------------
12345678910111213141516171819202122232425262728293

Piastrelle uniche: [0, 1, 2]. Somma: 3.

             ______
             | ==== |
             | ==== |
--------------------------------------------------
12345678910111213141516171819202122232425262728293

Piastrelle uniche: [1, 2, 3, 4]. Somma: 10.

                       ______
                       | ==== |
                       | ==== |
--------------------------------------------------
12345678910111213141516171819202122232425262728293

Piastrelle uniche: [1, 7, 8, 9]. Somma: 25.

                                                ______
                                                | ==== |
                                                | ==== |
--------------------------------------------------
12345678910111213141516171819202122232425262728293

Piastrelle uniche: [9, 3]. Somma: 12.
                                                            ______
                                                            | ==== |
                                                            | ==== |
--------------------------------------------------
12345678910111213141516171819202122232425262728293

Il treno esiste il ponte. Somma totale: 3 + 10 + 25 + 12 = 50.

6
Possiamo assumere il treno non attraversare il ponte alla fine? Per gli ingressi piace (200, 2, 169), il treno si blocca sulla 00a …9899100101102….
Lynn,

@Lynn Un po 'in ritardo, sì, puoi.
Mr. Xcoder,

Risposte:


3

Buccia , 20 byte

ṁ←U¡S↓←moΣuX_⁰↓Θ↑ṁdN

Provalo online!

Prende tre argomenti al fine T , B , X .

Spiegazione

ṁ←U¡S↓←moΣuX_⁰↓Θ↑ṁdN
                 ṁdN    Build the list of digits of natural numbers
              ↓Θ↑       Take the first B digits, add a 0 in front
                        then drop the first X digits
           X_⁰          Get all sublists of length T
       moΣu             Map the sum of unique values of each sublist

   ¡S↓←                 Repeatedly drop as many elements from the start of the list as the
                        first element of the list says;
                        keep all partial results in an infinite list.

  U                     Take elements until the first repeated one
                        (drops tail of infinite empty lists)

ṁ←                      Sum the first elements of each remaining sublist

6

Python 2 , 110 105 104 103 100 97 96 byte

  • Salvati cinque byte grazie a Mr. Xcoder ; rimosso l'assegnazione non necessaria, spostata la negazione nello spazio bianco disponibile.
  • Salvataggio di un byte grazie a Mr. Xcoder ; golfed[~-x:x+~-t] a [~-x:][:t].
  • Salvato un byte; golfed...range(1,-~b)))[:b] a ...range(b)))[1:-~b].
  • Tre byte salvati; golfed[1:-~b][~-x:] a [:-~b][x:].
  • Tre byte salvati; golfed[:-~b][x:] a [x:-~b].
  • Salvataggio di un byte grazie a Lynn ; golfare il whileciclo di una execdichiarazione.
b,t,x=input();S=x;exec"x+=sum(set(map(int,''.join(map(str,range(b)))[x:-~b][:t])));"*b;print-S+x

Provalo online!


Una soluzione alternativa lunga 105 byte .
Jonathan Frech,

104 byte . [~-x:x+~-t]può essere sostituito da[x-1:][:t]
Mr. Xcoder il

exec"x+=sum(set(map(int,''.join(map(str,range(b)))[x:-~b][:t])));"*bfunziona per 96. (Il treno non farà mai più di bpassi per lasciare il ponte, e l'intera operazione ammonterà x+=0all'infinito una volta lasciato.)
Lynn

4

Haskell, 106 102 byte

import Data.List
(b#t)x|x>b=0|y<-sum[read[c]|c<-nub$take t$drop(x-1)$take b$show=<<[1..]]=y+(b#t)(x+y)

Provalo online!

(b#t)x
   |x>b=0                 -- if the train has left the bridge, return 0
   |y<-sum[   ]           -- else let y be the sum of
      read[c]|c<-         -- the digits c where c comes from
        nub               -- the uniquified list of
            show=<<[1..]] -- starting with the digits of all integers concatenated
          take b          -- taking b digits (length of bridge)
         drop(x-1)        -- dropping the part before the train
        take t            -- take the digits under the train
     =y+(b#t)(x+y)        -- return y plus a recursive call with the train advanced

3

R , 123 byte

function(B,T,X){s=substring
while(X<B){F=F+(S=sum(unique(strtoi(s(s(paste(1:B,collapse=''),1,B),K<-X+1:T-1,K)))))
X=X+S}
F}

Implementa semplicemente l'algoritmo descritto.

R è abbastanza terribile alle corde.

function(B,T,X){
 s <- substring                         # alias
 b <- s(paste(1:B,collapse=''),1,B)     # bridge characters
 while(X<B){                            # until we crossed the bridge
  K <- X+1:T-1                          # indices of the characters
  S <- s(b,K,K)                         # the characters from b
  S <- sum(unique(strtoi(S)))           # sum
  F <- F + S                            # F defaults to 0 at the beginning
  X <- X + S                            # advance the train
 }
 F                                      # number of steps, returned
}

Provalo online!


2

Gelatina ,  22  21 byte

ḣ⁵QS
RDẎḣ⁸ṫṫÇ‘$$ÐĿÇ€S

Un programma completo che prende tre argomenti - l'ordine è B , X , T - che stampa il risultato.

Provalo online!

Come?

ḣ⁵QS - Link 1, calculate next jump: list of digits, bridge under and beyond train's left
 ⁵   - program's fifth command line argument (3rd input) = T (train length)
ḣ    - head to index (get the digits of the tiles under the train)
  Q  - de-duplicate
   S - sum

RDẎḣ⁸ṫṫÇ‘$$ÐĿÇ€S - Main link: number, B (bridge length); number, X (starting position)
R                - range(B) = [1,2,3,...,B-1,B]
 D               - to decimal list (vectorises) = [[1],[2],[3],...,[digits of B-1],[digits of B]]
  Ẏ              - tighten (flatten by one) = [1,2,3,...,digits of B-1,digits of B]
    ⁸            - chain's left argument, B
   ḣ             - head to index (truncate to only the bridge's digits)
     ṫ           - tail from index (implicit X) (truncate from the train's left)
           ÐĿ    - loop, collecting results, until no more change occurs:
          $      -   last two links as a monad:
         $       -     last two links as a monad:
       Ç         -       call last link (1) as a monad (get next jump)
        ‘        -       increment
      ṫ          -     tail from that index (remove the track to the left after train jumps)
             Ç€  - call last link (1) as a monad for €ach (gets the jump sizes taken again)
               S - sum
                 - implicit print

1

JavaScript (ES6), 117 byte

f=(B,T,X,g=b=>b?g(b-1)+b:'',o=0)=>X<B?[...g(B).substr(X-1,T)].map((e,i,a)=>o+=i+X>B|a[-e]?0:a[-e]=+e)&&o+f(B,T,X+o):0

Una coppia di funzioni ricorsive:

  1. f() somma le mosse del treno.
  2. g() crea la stringa di numeri.

Meno golf:

f=
(B,T,X,
 g=b=>b?g(b-1)+b:'',                       //creates the string of numbers
 o=0                                       //sum of tiles the train sits on
)=>
  X<B?                                     //if we're not past the bridge:
      [...g(B).substr(X - 1,T)].map(       //  grab the tiles we're sitting on
        (e,i,a)=>o += i + X > B |          //  if we've passed the bridge,
                      a[-e] ? 0 :          //  ... or we've seen this tile before, add 0 to o
                              a[-e] = +e   //  else store this tile and add its value to o
      ) &&
      o + f(B,T,X+o) :                     //recurse
  0


0

PHP> = 7,1, 153 byte

<?$s=substr;[,$p,$q,$r]=$argv;while($i<$p)$a.=++$i;$a=$s($a,0,$p);;while($r<$p){$x+=$n=array_sum(array_unique(str_split($s($a,$r-1,$q))));$r+=$n;}echo$x;

Provalo online!

Per renderlo compatibile con le versioni precedenti di PHP, cambia [,$p,$q,$r]=in list(,$p,$q,$r)=(+4 byte).

<?
[,$bridgelen,$trainlen,$position] = $argv;                  // grab input
while($i<$bridgelen)                                        // until the bridge is long enough...
  $bridgestr .= ++$i;                                       // add to the bridge
$bridgestr = substr($bridgestr,0,$bridgelen);               // cut the bridge down to size (if it splits mid-number)
while($position<$bridgelen){                                // while we are still on the bridge...
  $currtiles =                                              // set current tiles crossed to the...
    array_sum(                                              // sum of tiles...
      array_unique(                                         // uniquely...
        str_split(substr($bridgestr,$position-1,$trainlen)) // under the train
      )
    )
  ;
  $totaltiles += $currtiles;                                // increment total tiles crossed
  $position += $currtiles;                                  // set new position
}
echo $totaltiles;                                           // echo total tiles crossed
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.