열차가 라벨이있는 다리를 건너


9

양의 정수의 숫자로 연결된 타일로 형성된 길이 B 의 브리지를 고려하십시오 . 예를 들어, B 가 41 인 경우 다음과 같습니다.

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

이제 다리를 건너는 길이 T 의 기차를 상상해보십시오 . 열차의 가장 왼쪽 지점은 X 위치 (1 인덱스) 에서 시작합니다 . 문제를 더 잘 이해하려면 B = 41, T = 10, X = 10 인 이벤트 체계를 만들어 봅시다 . 열차는 등호 ( =)와 선을 사용하여 그려집니다 .

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

기차는 각 단계마다 고유 한 타일의 합계로 전진 할 수 있습니다. 예를 들어, 기차가 위에있는 [1, 0, 1, 1, 1, 2, 1, 3, 1, 4]타일은 다음 [1, 0, 2, 3, 4]과 같습니다. 고유 한 (중복 된) 타일은 다음 과 같습니다 10. 따라서 열차는 10타일 별로 이동할 수 있습니다 . 다시 그려서 열차의 가장 왼쪽 지점이 마지막 타일을 통과 할 때까지 과정을 반복해야합니다.

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

독특한 타일의 합 : 1 + 5 + 6 + 7 + 8 + 9 = 36. 기차는 36 타일로 진행합니다 ...

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

기차는 분명히 다리를 완전히 지나갔으므로 이제 멈춰야합니다.

내부 사람들은 지루하기 때문에 매번 기차가 전진 한 타일 수를 계산합니다. 이 특정한 경우 1036. 모든 것을 요약하면, 기차는 46다리를 통과하기 전에 움직 였습니다.


직무

B (브릿지 길이), T (열차 길이) 및 X (시작 위치, 1- 인덱스 )의 3 가지 양의 정수가 주어지면 , 규칙에 따라 다리를 건널 때까지 기차가 얼마나 많은 타일을 이동했는지 확인해야합니다. 위.

  • 다음과 같이 가정 할 수 있습니다.
    • BT 보다 높습니다 .
    • XB 보다 낮습니다 .
    • T2 이상 입니다.
    • 기차는 결국 다리를 건 es니다.
  • 우리의 모든 표준 규칙이 적용됩니다.
  • 이것은 바이트 단위의 가장 짧은 코드가 이깁니다!

테스트 사례

입력 ([B, T, X])-> 출력

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

마지막 테스트 사례에 대한 또 다른 효과적인 예 :

다리 길이는 50, 기차 6, 시작 위치는 11입니다.

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

고유 타일 : [0, 1, 2]. 합계 : 3.

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

고유 타일 : [1, 2, 3, 4]. 합계 : 10

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

고유 타일 : [1, 7, 8, 9]. 합계 : 25

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

독특한 타일 : [9, 3]. 합 : 12.
                                                            ______
                                                            | ==== |
                                                            | ==== |
--------------------------------------------------
12345678910111213141516171819202122232425262728293

기차는 다리가 있습니다. 총계 : 3 + 10 + 25 + 12 = 50.

6
기차 결국 다리를 건너고 있다고 가정 할 수 있습니까 ? 와 같은 입력의 (200, 2, 169)경우, 열차가 00안으로 멈춰 있습니다 …9899100101102….
Lynn

@Lynn 조금 늦습니다. 가능합니다.
Mr. Xcoder

답변:


3

껍질 , 20 바이트

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

온라인으로 사용해보십시오!

T , B , X 순서로 세 개의 인수를 사용 합니다.

설명

ṁ←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

파이썬 (2) , 110 (105) 104 (103) 100 97 96 바이트

  • Mr. Xcoder 덕분에 5 바이트를 절약했습니다 . 불필요한 할당을 제거하고 부정을 사용 가능한 공백으로 옮겼습니다.
  • Mr. Xcoder 덕분에 바이트를 절약했습니다 . 에 골프 [~-x:x+~-t]를 쳤다 [~-x:][:t].
  • 바이트를 저장했습니다. 에 골프 ...range(1,-~b)))[:b]를 쳤다 ...range(b)))[1:-~b].
  • 3 바이트를 절약했습니다. 에 골프 [1:-~b][~-x:]를 쳤다 [:-~b][x:].
  • 3 바이트를 절약했습니다. 에 골프 [:-~b][x:]를 쳤다 [x:-~b].
  • Lynn 덕분에 바이트를 절약했습니다 . while루프를 exec문에 골프
b,t,x=input();S=x;exec"x+=sum(set(map(int,''.join(map(str,range(b)))[x:-~b][:t])));"*b;print-S+x

온라인으로 사용해보십시오!


대안적인 105 바이트 길이의 솔루션.
Jonathan Frech

104 바이트 . [~-x:x+~-t]대체 가능[x-1:][:t]
Mr. Xcoder

exec"x+=sum(set(map(int,''.join(map(str,range(b)))[x:-~b][:t])));"*b(기차는 b다리를 떠나기위한 단계 이상을 거치지 않으며 , x+=0일단 운행이 끝날 때 까지 계속 운행 될 것 입니다.)
Lynn

4

하스켈 106 102 바이트

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)

온라인으로 사용해보십시오!

(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 바이트

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}

설명 된 알고리즘 만 구현하십시오.

R은 문자열에서 상당히 끔찍합니다.

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
}

온라인으로 사용해보십시오!


2

젤리 ,  22  21 바이트

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

세 가지 인수를 취하는 전체 프로그램-순서는 B , X , T- 결과를 인쇄합니다.

온라인으로 사용해보십시오!

어떻게?

ḣ⁵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

자바 스크립트 (ES6), 117 바이트

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

재귀 함수 쌍 :

  1. f() 열차의 움직임을 합산합니다.
  2. g() 숫자 열을 만듭니다.

덜 골프 :

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 바이트

<?$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;

온라인으로 사용해보십시오!

PHP의 낮은 버전, 변화와 호환되도록하려면 [,$p,$q,$r]=list(,$p,$q,$r)=(4 바이트).

<?
[,$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
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.