最初のn個の弾む数の合計を求める


19

用語

数字の増加は、各数字がその左側のすべての数字以上であるものです(例:12239)

減少する数字は、各数字がその左側のすべての数字以下であるものです(例:95531)

弾む数は、増加または減少していない任意の数です。これには少なくとも3桁が必要であるため、最初の弾む数は101です。

タスク

1以上の整数nが与えられた場合、最初のn個の弾力のある数の合計を求めます

ルール

  • これはコードゴルフであるため、バイト数が最も少ない答えが優先されます
  • 言語に整数サイズの制限がある場合(例:2 ^ 32-1)nは、合計が整数に収まるほど十分に小さい
  • 入力は、任意の合理的な形式(stdin、ファイル、コマンドラインパラメーター、整数、文字列など)にすることができます
  • 出力は、任意の合理的な形式(標準出力、ファイル、数字を表示するグラフィカルユーザー要素など)にすることができます。

テストケース

1 > 101
10 > 1065
44701 > 1096472981

3
私はあなたの制限を理解しているかわかりません。sort番号を確認して、元の番号と同じかどうかを確認できますか?それは組み込み(sort)を使用していますが、増加しているかどうかを確認するための厳密な組み込みではありません。監視できないプログラムの要件を確認し、「回避策」のメタ投稿でYなしのXを実行します。
AdmBorkBork

5
こんにちは、PPCGへようこそ!これは素敵な最初の投稿(1)ですが、私はいくつかの小さな提案をしている:なしの組み込みコマンド数が増加している場合は、チェックを使用してもよいことは文字列が辞書的に増加している場合はありませんが、そのチェックを組み込みコマンドを使用することができる(組み込みコマンドを許可しません)ある挑戦を書くときに回避するためのもの提案された課題のためサンドボックスがあり、フィードバックとガイダンスを受け取るために投稿前に投稿のアイデアを共有できます:)
Xcoder氏18

投稿したリンクの「例外」カテゴリによりよく一致するように制限を更新しました
18

4
そもそもそのような制限があるという点はまだわかりません。もちろん、それを保持するかどうかはあなた次第ですが、ビルトインを禁止することは通常悪い習慣です。ビルトインによって課題が簡単になったと思う場合、単に制限するだけではタスクの解決が面白くならず、定型句が追加されることに注意してください。その制限を取り除くことを検討してもらえますか?(ちなみに、これはまだYのないDo Xに該当します)それ以外の場合、私はこのアイデアが非常に好きであり、実際のタスクを損なうために少し主観的な制限が欲しくありません。
ミスターXcoder

10
それは方法そのコミュニティのためのより楽しいであることは明らかである、と確保の課題は、最高の品質であることを、ここでのガイドラインとベストプラクティスを信頼するように私は、しかし、制限を削除した
avern

回答:


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` –数値を文字列にキャストし、その逆で分岐(ペア)します。
      #–それらをフィルターキープ...
     I –それは不変です...
    S –ソート。
           –明確にするために、I(不変式)は2つの入力を取る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+1がtrueを返すx+1まで、後続関数を適用し{}ます

10\x の10進数です x

a: 割りあてる a

|\ の最大スキャン(部分最大値) a

&\ 同様に、最小スキャンは

a~|\aないaその最大スキャンが一致?

| または

a~&\a その最小スキャン?

+/


4

JavaScript(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

Python 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ありがとう。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


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回のみ機能します。

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

追加is内側のループの次のパスのために弾みテストが失敗し、そうあること、および単項桁のコピーを削除しiた後、少なくとも増分されます。

\G#

s10進数に変換します。

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、少なくとも1 回は増分されてから1回のみ機能します。

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

追加is内側のループの次のパスのために弾みテストが失敗し、そうあること、および単項桁のコピーを削除しiた後、少なくとも増分されます。

:.*

を削除しiます。



3

Java 8、114 112バイト

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

Python 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


1
私が使用することをお勧めし;ますが、コードの一部を再利用することができますので、できるだけ単一行に多くの書類として入れて空白を削除し、非常に似ている2つの長い行のための関数を定義します。また、できますa=b=s=0およびlen(g)!=h-1!=len(d)
mbomb007

ヒントをありがとう。今行かなければなりません。しかし、私は後でそれに取り組みます。
ハッシュブラウン


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 iよりも5バイト短いto-string i


0

MATL31 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.