첫 n 탄력 번호의 합을 구합니다


19

술어

증가하는 숫자는 각 숫자가 왼쪽의 모든 숫자보다 크거나 같은 숫자입니다 (예 : 12239).

감소하는 숫자는 각 숫자가 왼쪽의 모든 숫자보다 작거나 같은 숫자입니다 (예 : 95531).

탄력 번호는 증가하거나 감소하지 않는 숫자입니다. 최소 3 자리 숫자가 필요하기 때문에 첫 번째 탄력 번호는 101입니다.

작업

정수 n이 1보다 크거나 같으면 첫 번째 n 탄력 숫자의 합을 찾으십시오.

규칙

  • 이것은 코드 골프이므로 가장 짧은 바이트 수의 답이 이깁니다.
  • 언어에 정수 크기 (예 : 2 ^ 32-1)에 대한 제한이있는 경우, 합계가 정수에 맞을만큼 충분히 작습니다.
  • 입력은 합리적인 형식 (stdin, 파일, 명령 행 매개 변수, 정수, 문자열 등) 일 수 있습니다.
  • 출력은 합리적인 형식 (stdout, 파일, 숫자를 표시하는 그래픽 사용자 요소 등) 일 수 있습니다.

테스트 사례

1 > 101
10 > 1065
44701 > 1096472981

3
귀하의 제한 사항을 이해하지 못했습니다. 내가 할 수있는 sort숫자와 그들이 원래의 수와 동일 있다면 확인? 그것은 내장 ( sort)을 사용하고 있지만 그것이 증가하고 있는지 확인하기 위해 내장 된 것은 아닙니다. 확인 되지 않은 관찰 프로그램 요구 사항Y없이 할 X를 우리의 "상황을 방지하기 위해"메타 게시물에.
AdmBorkBork

5
안녕하세요, PPCG에 오신 것을 환영합니다! 이 멋진 첫 번째 게시물 (+1)이지만, 좀 작은 제안이 : 수표 번호를 사용할 수있다 증가되는 경우 있음 없음 내장 명령 , 없음 내장 명령을 확인하는 것이 문자열을 사 전적으로 사용할 수 있습니다 증가하는 경우 (내장 명령을 허용하지) A는 도전을 작성할 때 피하는 것은 ; 의견과 안내를 받기 위해 제출하기 전에 게시물 아이디어를 공유 할 수있는 제안 된 문제에 대한 샌드 박스 가 있습니다.)
Mr. Xcoder

게시 한 링크의 "예외"범주와 일치하도록 제한 사항을 업데이트했습니다
avern

4
나는 아직도 그런 제한이 있다는 점을 아직 알지 못한다. 물론, 유지할지 말지 여부는 사용자에게 달려 있지만 내장 기능을 금지하는 것은 일반적으로 나쁜 습관입니다. 빌트인에 의해 도전이 사소한 것처럼 느껴지면, 단순히 제한하는 것만으로도 과제를 더 흥미롭게 해결하는 것이 아니라 오히려 보일러 플레이트를 추가한다는 점에 유의해야합니다. 이 제한을 제거 할 수 있습니까? (그러나, 이것은 여전히 Y가없는 Do X에 속합니다 ) 그렇지 않으면 아이디어를 많이 좋아하며 실제 작업에서 벗어나기 위해 약간 주관적인 제한을 원하지 않습니다.
Mr. Xcoder

10
그러나 나는 그 방법으로 커뮤니티가 더 즐겁다는 것이 분명해
졌기

답변:


8

젤리 , 10 8 바이트

ṢeṚƬ¬µ#S

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

작동 원리

ṢeṚƬ¬µ#S  Main link. No arguments.

      #   Read an integer n from STDIN and call the chain to the left with argument
          k = 0, 1, 2, ... until n of them return a truthy result.
          Yield the array of successful values of k.
     µ    Monadic chain. Argument: k (integer)
Ṣ           Sort, after promoting k to its digit array.
  ṚƬ        Reverse 'til the results are no longer unique and yield unique results.
            Calling Ṛ on k promotes it to its digit array. If k = 14235, the 
            result is [14235, [5,3,2,4,1], [1,4,2,3,5]].
 e          Check if the result to the left appears in the result to the right.
    ¬       Negate the resulting Boolean.
       S  Take the sum.

4
+1 ṚƬ은 매우 깔끔합니다.
Mr. Xcoder

6

Pyth , 10 바이트

s.f!SI#_B`

여기 사용해보십시오!

어떻게 작동합니까?

sf! SI # _B` – 전체 프로그램. STDIN에서 정수 Q를 가져 와서 STDOUT으로 출력합니다.
 .f – 특정 조건을 만족하는 첫 번째 Q 양의 정수를 찾습니다.
   ! SI # _B – 조건. 탄력 번호에 대해서만 true를 리턴합니다.
       _B` – 숫자를 문자열로 캐스트하고 그 반대로 뒤집습니다.
      # – 필터 유지 ...
     나는 – 그것은 변하지 않는 ...
    S – 정렬.
           – 명확히하기 위해, I (불변)는 두 개의 입력을받는 Pyth 연산자입니다. 
             함수와 값을 확인하고 function (value) == value인지 확인합니다.
             이것은 기술적으로 내장 된 것이 아닙니다.
   ! – 논리적이 아닙니다. 빈 목록은 true로, 다른 값은 false로 매핑됩니다.
s – 합계

4

K (ngn / k) , 37 바이트

{+/x{{(a~&\a)|a~|\a:10\x}(1+)/x+1}\0}

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

{ } 인수가있는 함수입니다 x

x{ }\0중간 결과를 유지하면서 정시 {}에 적용0 x

(1+) 후속 기능입니다

{ }(1+)/x+1x+1이후에 {}true를 리턴 할 때까지 후속 함수를 적용 합니다.

10\x 십진수입니다 x

a: 할당하다 a

|\ 최대 스캔 (부분 최대 값) a

&\ 마찬가지로, 최소 스캔입니다

a~|\a않습니다 a자사의 최대 스캔 일치?

| 또는

a~&\a 최소 스캔?

+/ 합집합


4

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

f=(i,n=0,k,p)=>i&&([...n+''].map(x=>k|=x<p|2*(p<(p=x)))|k>2&&i--&&n)+f(i,n+1)

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

댓글

f = (                     // f = recursive function taking:
  i,                      //   i = number of bouncy numbers to find
  n = 0,                  //   n = current value
  k,                      //   k = bitmask to flag increasing/decreasing sequences
  p                       //   p = previous value while iterating over the digits
) =>                      //
  i && (                  // if there's still at least one number to find:
    [...n + '']           //   turn n into a string and split it
    .map(x =>             //   for each digit x in n:
      k |=                //     update k:
        x < p |           //       set bit #0 if x is less than the previous digit
        2 * (p < (p = x)) //       set bit #1 if x is greater than the previous digit
                          //       and update p
    )                     //   end of map()
    | k > 2               //   if both bits are set (n is bouncy):
    && i--                //     decrement i
    && n                  //     and add n to the total
  ) + f(i, n + 1)         //   add the result of a recursive call with n + 1

3

파이썬 2, 110 92 89 바이트

n=input()
x=s=0
while n:b={-1,1}<=set(map(cmp,`x`[:-1],`x`[1:]));s+=x*b;n-=b;x+=1
print s

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

이 함수는 숫자가 탄력적인지 여부를 결정합니다.

lambda x:{-1,1}<=set(map(cmp,`x`[:-1],`x`[1:]))

문자를 직접 비교할 수 있습니다. 실제로, 당신의 이해력이 될 수 있습니다 set(map(cmp,`x`[:-1],`x`[1:])).
Jakob

@Jakob 감사합니다. 나는 당신이 map그런 식으로 사용할 수 있다는 것을 항상 잊어 버립니다 .
mbomb007

1
x=s=0\nwhile n:b={-1,1}<=set(map(cmp,`x`[:-1],`x`[1:]));s+=x*b;n-=b;x+=13 바이트 절약
Xcoder Mr.


3

망막 , 93 바이트

K`:
"$+"{/(?=.*;(_*);\1_)(?=.*_(_*);\2;)/^{`:(#*).*
:$1#;$.($1#
)`\d
*_;
)`:(#+).*
$1:$1
\G#

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

K`:

초기화합니다 s=i=0. ( s#의 앞에 있는 수이고 :, 뒤에 i있는 수입니다 #.)

"$+"{
...
)`

n시간을 반복하십시오 .

/(?=.*;(_*);\1_)(?=.*_(_*);\2;)/^{`
...
)`

i탄력이없는 동안 반복하십시오 .

:(#*).*
:$1#;$.($1#

증분 i하고 10 진수로 복사합니다.

\d
*_;

사본의 자릿수를 단항으로 변환하십시오. 바운스 테스트는 단항 사본을 사용하므로 한 번만 i증분 된 경우에만 작동합니다 .

:(#+).*
$1:$1

추가 is내부 루프의 다음 패스의 bounciness 테스트가 실패하고 그래서, 및 단항 숫자의 사본을 삭제 i한 번에 적어도 증가됩니다.

\G#

s십진수로 변환 합니다.

121 바이트 버전은 10 진수로 계산하므로 더 큰 값을 사용할 수 있습니다 n.

K`0:0
"$+"{/(?=.*;(_*);\1_)(?=.*_(_*);\2;)/^{`:(\d+).*
:$.($1*__);$.($1*__)
)+`;\d
;$&*_;
)`\d+:(\d+).*
$.(*_$1*):$1
:.*

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

K`0:0

초기화합니다 s=i=0.

"$+"{
...
)`

n시간을 반복하십시오 .

/(?=.*;(_*);\1_)(?=.*_(_*);\2;)/^{`
...
)

i탄력이없는 동안 반복하십시오 .

:(\d+).*
:$.($1*__);$.($1*__)

증분 i하고 사본을 만듭니다.

+`;\d
;$&*_;

사본의 자릿수를 단항으로 변환하십시오. 바운스 테스트는 단항 사본을 사용하므로 한 번만 i증분 된 경우에만 작동합니다 .

\d+:(\d+).*
$.(*_$1*):$1

추가 is내부 루프의 다음 패스의 bounciness 테스트가 실패하고 그래서, 및 단항 숫자의 사본을 삭제 i한 번에 적어도 증가됩니다.

:.*

삭제 i.


3

05AB1E , 12 바이트

µN{‚Nå_iNO¼

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

설명

µ              # loop over increasing N until counter equals input
     Nå_i      # if N is not in
 N{‚          # the pair of N sorted and N sorted and reversed
         NO    # sum N with the rest of the stack
           ¼   # and increment the counter

3

자바 8, 114112 바이트

n->{int i=0,s=0;for(;n>0;++i)s+=(""+i).matches("0*1*2*3*4*5*6*7*8*9*|9*8*7*6*5*4*3*2*1*0*")?0:--n*0+i;return s;}

정규식을 사용하여 숫자가 증가 또는 감소하는지 확인합니다. 온라인으로 사용해보십시오여기에서 .

언 골프 드 :

n -> { // lambda
    int i = 0, // the next number to check for bounciness
        s = 0; // the sum of all bouncy numbers so far
    for(; n > 0; ++i) // iterate until we have summed n bouncy numbers, check a new number each iteration
        s += ("" + i) // convert to a String
             .matches("0*1*2*3*4*5*6*7*8*9*" // if it's not an increasing  number ...
             + "|9*8*7*6*5*4*3*2*1*0*") ? 0 // ... and it's not a decreasing number ...
             : --n*0 // ... we have found another bouncy number ...
               + i; // ... add it to the total.
    return s; // return the sum
}

2

파이썬 2, 250 바이트

n=input()
a=0
b=0
s=0
while a<n:
    v=str(b)
    h=len(v)
    g=[int(v[f])-int(v[0]) for f in range(1,h) if v[f]>=v[f-1]]
    d=[int(v[f])-int(v[0]) for f in range(1,h) if v[f]<=v[f-1]]
    if len(g)!=h-1 and len(d)!=h-1:
       a+=1
       s+=b
    b+=1
print s

어서 오십시오! 이 페이지를보고 싶다면 Python의 골프 팁
mbomb007

1
내가 사용하는 것이 좋습니다 ;당신이 코드의 일부를 재사용 할 수 있도록 가능한 한 줄에 여러 문장, 공백을 제거하고 매우 유사 2 긴 줄에 대한 함수를 정의로 넣어. 또한, 당신은 할 수 a=b=s=0len(g)!=h-1!=len(d).
mbomb007

팁 주셔서 감사합니다. 나는 지금 가야한다. 하지만 나중에 작업하겠습니다.
Hashbrowns


0

빨강 , 108 바이트

func[n][i: s: 0 until[t: form i
if(t > u: sort copy t)and(t < reverse u)[s: s + i n: n - 1]i: i + 1
0 = n]s]

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

더 읽기 쉬운 :

f: func [ n ] [
    i: s: 0
    until [
       t: form i  
       if ( t > u: sort copy t ) and ( t < reverse u ) [
            s: s + i
            n: n - 1
       ]
       i: i + 1
       0 = n
    ]
    s
]

사용하기에 좋은 기회가 form- form i5 바이트 짧은to-string i


0

MATL , 31 30 바이트

l9`tVdZS&*0<a?wQtG>?.]y]QT]xvs

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

l       % Initialize counter to 1
9       % First value to check for being bouncy
`       % Start do-while loop
  tV    % duplicate the current number and convert to string
        % (let's use the iteration where the number is 1411)
        % stack: [1, 1411, '1411']
  d     % compute differences between the characters
        %  For non-bouncy numbers, this would be either all 
        %  positive values and 0, or all negative values and 0
        % stack: [1, 1411, [3 -3 0]]
  ZS    % keep only the signs of those differences
        % stack: [1, 1411, [1 -1 0]]
  &*    % multiply that array by its own transpose, so that
        %  each value is multiplied by every other value
        %  for non-bouncy numbers, all products will be >=0
        %  since it would have had only all -1s or all 1 (other than 0s)
        % stack: [1, 1411, [1 -1  0
                            -1  1 0
                            0  0  0]]
  0<a?  % if any value in the matrix is less than 0
    wQ    % switch the counter to top, increment it
          % stack: [1411, 2]
    tG>?  % duplicate it, check if it's gotten greater than the input limit
      .]    % if so, break out of loop
  y]    % else, duplicate bouncy number from inside stack,
        %  keeping a copy to be used for summing later
        % stack: [1411, 2, 1411]
  QT    % increment number, push True to continue loop
]     % loop end marker
x     % if we've broken out of loop, remove counter from stack
v     % concatenate the bouncy numbers we've collected in stack and 
s     % sum them

0

R , 96 바이트

function(n){while(n){y=diff(T%/%10^(0:log10(T))%%10);g=any(y<0)&any(y>0);F=F+T*g;n=n-g;T=T+1};F}

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

설명 :

while(n){                         # while n > 0

        T%/%10^(0:log10(T))%%10   # split T into digits(T==TRUE==1 at the 1st loop)
y=diff(                         ) # compute the diff of digits i.e. digits[i] - digits[i+1]

g=any(y<0)&any(y>0)               # if at least one of the diff is < 0 and 
                                  # at least one is > 0 then T is "bouncy"

F=F+T*g                           # if bouncy increment F (F==FALSE==0 at the 1st loop)

n=n-g                             # decrement n by 1 if bouncy

T=T+1}                            # increment T by 1 and loop

F}                                # return F

0

루비 (123 바이트)

o=0
x=["0"]
while n>0 do x=(x.join.to_i+1).to_s.split('')
(x.sort!=x&&x.sort!=x.reverse ? (n-=1;o+=x.join.to_i):'')
end
p o

나에게 꽤 못 생겼어. 바운스는이 블록에서 정의됩니다x.sort!=x&&x.sort!=x.reverse



0

C (gcc), 104 바이트

f(b,o,u,n,c,y){for(o=u=0;b;u+=y?0:o+0*--b,++o)for(n=o,y=3;n/10;)c=n%10,n/=10,y&=(c-=n%10)<0?:c?2:y;b=u;}

여기에서 온라인으로 사용해보십시오 .

언 골프 드 :

f(n, // function: return type and type of arguments defaults to int;
     // abusing extra arguments to declare variables
  i,   // number currently being checked for bounciness
  s,   // sum of the bouncy numbers
  j,   // copy of i to be used for checking bounciness in a loop
  p,   // used for investigating the last digit of j
  b) { // whether i is not bouncy; uses the two least significant bits to indicate increasing/decreasing
    for(i = s = 0; // check numbers from zero up; initial sum is zero
        n; // continue until we have n bouncy numbers
        s += b ? 0 // not bouncy, no change to the sum
        : i + 0* --n, // bouncy, add it to the sum and one less bouncy number to go
        ++i) // either way, move to the next number
        for(j = i, b = 3; j/10; ) // make a copy of the current number, and truncate it from the right until there is just one digit left
        // bounciness starts as 0b11, meaning both increasing and decreasing; a value of 0 means bouncy
            p = j % 10, // get the last digit
            j /= 10, // truncate one digit from the right
            b &= // adjust bounciness:
                 (p -= j % 10) // compare current digit to the next
                 < 0 ? // not an increasing number, clear second to least significant bit
                 : p ? 2 // not a decreasing number, clear least significant bit
                 : b; // keep it the same
    n = s; // gcc shortcut for return s
}

제안 u+=!y?--b,o:0,++o대신 u+=y?0:o+0*--b,++o, ;y&=(c-=n%10)<0?:c?2:y)c=n%10,n/=10;대신;)c=n%10,n/=10,y&=(c-=n%10)<0?:c?2:y;
ceilingcat
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.