連結されたシーケンスを並べ替える


17

f(n) = f(n-1)+f(n-2)で始まる再帰関係に基づくシーケンスを考えf(1) = x1, f(2) = x2ます。の場合x1 = 2, x2 = 1、シーケンスは次のように始まります。

2  1  3  4  7  11  18  29  47  76  123  199  322  521  843

これを文字列に連結すると、次のようになります。

213471118294776123199322521843

ここで、このリストをを与える最小の数に分割しますy(n) > y(n-1)。最初の番号から始めて、2番目の番号から始めます。最初の出力番号は常に1桁でなければなりません。最後の数字に必要な数のゼロを埋め込みます。

2 13 47 111 829 4776 12319 93225 218430

(x1, x2)任意の便利な形式で、入力として2つの数値を取得します。課題は、ソートされたリストを出力することです。

ルール:

  • 機能とプログラムはOK
  • 初期シーケンスには、正確に15個の数字が必要です(最後の数字はf(15))。
  • x1そして、x2負ではありません(ゼロも可能です)。
  • 出力は任意の便利な形式にすることができます
  • 出力ベクトルyは、次のように作成する必要がありますy2 > y1
    • まず可能な限り最小のy1、そして可能な限り最小y2、その後、y3というように。
  • その場合x1 = x2 = 0、15個のゼロを出力します(他の出力と同じ形式、つまり000000000000000)。

Input: 1 1
Output: 1  12  35  81  321  345  589  1442  3337 7610

Input: 3 2
Output: 3  25  71  219  315  0811 3121  23435 55898 145300
                             |
                             Optional leading zero 
Input: 0 0
Output: 0  0  0  0  0  0  0  0  0  0  0  0  0  0  0

バイト単位の最短コードが優先されます。可能であれば、オンライン通訳へのリンクを含めてください。


「可能な限り小さい数」とはどういう意味ですか?最小平均?最小の最大値?他に何か?
isaacg

@isaacgしたがって、n番目の数値は(n-1)番目より大きくなります。
ニカエル

1
私の質問を明確にするために、適切な区分は5467何ですか?54 675 46 70
isaacg


3
0ということは、かなり面倒で不必要な例外のようです。
マーティンエンダー

回答:


1

Pyth、56バイト

LsgM.:sMb2?sQsM.WyHX_1Z`0u?yGX_1GHaGHjkhM.u,eNsN14QYmZ15

テストスイート

説明:

まず、入力が正確かどうかを確認します0, 0。その場合、15個のゼロを印刷します。

それ以外の場合は、シーケンスを生成しjkhM.u,eNsN14Qます。これは、フィボナッチ数列の標準のPythアルゴリズムに似ています。

次に、この文字列を縮小します。アキュムレータは、分割されたシーケンスの各数値を表す文字列のリストです。各リダクションステップで、次の文字を取得し、yで定義されたヘルパー関数を使用して、アキュムレータLsgM.:sMb2が正しいかどうかを確認します。順序どおりであれば、次の文字をリストに独自の番号として追加します。そうでない場合は、最後の文字列の最後に次の文字を追加します。これはで達成されu?yGX_1GHaGH ... Yます。

次に、機能的なwhileループを実行します。ループは、実行中のリストが正常になるまで続き、ヘルパー関数を再利用します。各ステップ0で、リストの最後の文字列の末尾にa が追加されます。これはで達成され.WyHX_1Z`0ます。

最後に、文字列はで整数に変換されsM、印刷されます。


Pyth、51バイト

LsgM.:sMb2?sQsM.WyHX_1Z`0hf!yT_./jkhM.u,eNsN14QmZ15

これはうまくいくと思いますが、テストするには遅すぎます-文字列を分割するためのブルートフォースソリューションです。


私はX関数にいくつかの改良を加えますが、上記のコードは質問が投稿されたときに最新であったPythのバージョンで動作します。


5

JavaScript ES6、127 135

(a,b)=>eval("for(n=r=[],v=13,o=a+n+b;v--;a=b,b=t)o+=t=b+a;for(d of o+'0'.repeat(99))(n+=d)>+v&&(r.push(v=n),n='');+v?r:[...o]")

テスト

F=(a,b)=>eval("for(n=r=[],v=13,o=a+n+b;v--;a=b,b=t)o+=t=b+a;for(d of o+'0'.repeat(99))(n+=d)>+v&&(r.push(v=n),n='');+v?r:[...o]")

// less golfed

U=(a,b)=>{
  for(n=r=[], o=a+n+b, v=13; v--; a=b, b=t)
    o+= t= b+a;
  for(d of o+'0'.repeat(99))
    if ((n+=d) > +v)
      r.push(v=n), n='';
  return +v ? r : [...o]
}

function test(){
  var i = I.value.match(/\d+/g)
  O.textContent = i.length > 1 ? F(+i[0],+i[1]) : ''
}
test()
A,B : <input id=I value='0 1' oninput='test()'>
<pre id=O></pre>


x1 = 0、x2> 0、たとえば入力「0 1」にはエラーがあります。
flornquake

@flornquakeが修正されました。バイトカウントは同じままで、ゼロフィリングコードが少し減りました
-edc65

2

JavaScriptのES6、187 180 187 184 182 179 175 172 165の 160 155 154バイト

(a,b)=>eval('d=""+a+b;for(i=-12,j=1;++i<99;)i<2?(c=b,d+=b=a+b,a=c,r=a?[d[0]]:"0,".repeat(15)):(f=+d.slice(j,i))>r[r.length-1]?(r.push(f),j=++i-1):d+=0;r')

以下のためにそれを実行したときに、私は同様の結果を得る1,1と、3,2テストケース。0,026バイトを超えています...

デゴルフ+ ES5に変換+デモ:

function s(a, b) {
  d = "" + a + b;
  for (i = -12, j = 1; ++i < 99;)
    i < 2 ?
      (c = b, d += b = a + b, a = c, r = a ? [d[0]] : "0,".repeat(15))
    : (f = +d.slice(j, i)) > r[r.length - 1] ?
      (r.push(f), j = ++i - 1)
      : d += 0;
  return r
}
document.write(
   s(1,1)+"<br>"+
   s(3,2)+"<br>"+
   s(0,0)
)


なぜより多くの数字を生成するのですか?そして、簡単に修正できるはずではありませんか?要件はn <= 15です。
スチューウィーグリフィン

@Stewieでもねえ、最初は15より小さいだ12と第2の11を生成
nicael

初期シーケンスf(n) = f(n-1)+f(n-2)の最大値は正確に15です。出力値の数は、アルゴリズムに基づいて決定されます。
スチューウィーグリフィン

@Stewie OK、それは正確に15でなければなりませんよね?次に、n <= 15とは、入力数が15未満であることを意味しますか?
ニカエル

初期シーケンスの値の数は15です。開始値でf(1)=x1ありf(2)=x2、15を超えることができます。出力値の数は、入力値に基づいて決定されます。なぜなら、3 2それは10になるからです。
Stewie Griffin

1

JavaScript(ES6)、162バイト

(a,b)=>(k=[...Array(15).keys(y="")],p=-1,z=k.map(_=>0),a|b?[...k.map(f=n=>n--?n?f(n)+f(n-1):b:a).join``,...z].map(d=>+(y+=d)>p?(p=y,y=" ",p):"").join``:z.join` `)

説明

(a,b)=>(
  k=[...Array(15).keys(y="")],     // k = array of numbers 0 to 14, initialise y
  p=-1,                            // initialise p to -1 so that 0 is greater than p
  z=k.map(_=>0),                   // z = array of 15 zeroes
  a|b?[                            // if a and b are not 0
      ...k.map                     // for range 0 to 14
      (f=n=>n--?n?f(n)+f(n-1):b:a) // recursive sequence function (0 indexed)
      .join``,                     // join result of f(0) to f(14) as a string
      ...z                         // append zeroes for padding
    ].map(d=>                      // for each digit of concatenated result
      +(y+=d)                      // append the digit to the current number y
      >p?(                         // if the current number is greater than the previous p
        p=y,                       // set previous to the current number
        y=" ",                     // reset y (with space as a separator)
        p                          // output the current number (with space at the start)
      ):""                         // else add nothing to the output
    )
    .join``                        // return the output as a string
  :z.join` `                       // return a bunch of zeroes if a and b are 0
)

テスト


1

Mathematica、192バイト

f[{0,0}]:=0~Table~15
f@l_:=(t=0;q={};If[#>0,q~Join~{10^⌈Log10[t/#]⌉#},q]&[Last@#]&@FoldList[If[#>t,AppendTo[q,t=#];0,#]&[10#+#2]&,0,Flatten@IntegerDigits@SequenceFoldList[#+#2&,l,Range@13]])

テストケース:

f[{2, 1}]
(* {2, 13, 47, 111, 829, 4776, 12319, 93225, 218430} *)
f[{3, 2}]
(* {3, 25, 71, 219, 315, 811, 3121, 23435, 55898, 145300} *)
f[{0, 0}]
(* {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} *)

関数名の長さが私を殺している。


1

ハスケル、165の 159 152 142 141バイト

w=take 15
x#y=x:scanl(+)y(x#y)
0%0=w[0,0..]
x%y=g(-1)(w(x#y)++0%0>>=show)(-1)
g _""_=[]
g b l@(h:t)a|b>a=b:g 0l b|1<2=g(max 0b*10+read[h])t a

使用例:3 % 2-> [3,25,71,219,315,811,3121,23435,55898,145300]

オンラインデモmainラッパー付き)。

使い方:

w=take 15
x#y=x:scanl(+)y(x#y)              -- fibonacci sequence generator for x and y

0%0=w[0,0..]                      -- special case 0%0
x%y=g(-1)(w(x#y)++0%0>>=show)(-1) -- calculate fib sequence, add some extra 0 and
                                  -- flatten all digits into a single string.
                                  -- start calculating the resulting sequence

g _""_=[]                         -- if we don't have digits left, stop.
                                  -- the final 0 in the second parameter is ignored.
g b l@(h:t)a
  |b>a=b:g 0l b                   -- if the current number is greater than the
                                  -- previous one, take it and start over.
  |1<2=g(max 0b*10+read[h])t a    -- otherwise add the next digit and retry.
                                  -- The "max" fixes the initial call with -1.

0

PowerShell、167 166バイト

param($x,$w)if($w-lt($x-eq0)){"0`n"*15;exit}[char[]]("$x"+-join(0..13|%{$w;$w=$x+($x=$w)}))|%{$z+="$_";if(+$z-gt$y){($y=$z);$z=""}};if($z){while(+$z-lt$y){$z+="0"}$z}

$s変数を削除し、出力ループに直接フィードするだけで1バイトを節約しました。

非ゴルフとコメント:

param($x,$w)           # Take input parameters as x and w
if($w-lt($x-eq0)){     # If x=0, ($x-eq0)=1, so $w-lt1 implies w=0 as well
  "0`n"*15             # Print out 15 0's separated by newlines
  exit                 # And exit program
}                      # otherwise ...
[char[]](              # Construct the sequence string as a char-array
"$x"+-join(            # Starting with x and concatenated with a joined array
  0..13|%{             # Loop
    $w                 # Add on w
    $w=$x+($x=$w)      # Recalculate for next loop iteration
  }
))|%{                  # Feed our sequence as a char-array into a loop
  $z+="$_"             # z is our output number, starts with the first digit
  if(+$z-gt$y){        # If z is bigger than y (initialized to 0)
    ($y=$z)            # Set y equal to z and print it
    $z=""              # Reset z to nothing to start building the next number
  }
}
if($z){                # If there is remaining digits, we need to pad zeroes
  while(+$z-lt$y){     # Until z is bigger than y
    $z+="0"            # Tack on a zero
  }
  $z                   # Print the final number
}

0

Perl 6、107バイト

{$_=@=(|@_,*+*...*)[^15].join.comb;.sum??[.shift,{last if !@$_;until (my$a~=.shift//0)>$^b {};$a}...*]!!$_} # 107

使用法:

# give it a lexical name for ease of use
my &code = {...}

# use 「eager」 because the anonymous block returns a lazy array
# and 「say」 doesn't ask it to generate the values
say eager code 2, 1;
# [2 13 47 111 829 4776 12319 93225 218430]
say eager code 1, 1;
# [1 12 35 81 321 345 589 1442 3337 7610]
say eager code 3, 2;
# [3 25 71 219 315 0811 3121 23435 55898 145300]
say eager code 0, 0;
# [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
say eager code 0, 1;
# [0 1 12 35 81 321 345 589 1442 3337 7000]

説明

(引数で始まる、一連のようにフィボナッチを作成します@_)(滑っ|中)

|@_,*+*...*

そのシーケンスの最初の15要素を取ります

(…)[^15]

それを単一の文字列(.join)に結合し、個々の文字のシーケンス()に分割し、シーケンスを可変配列に強制した後、最初に匿名配列()に格納することで、それを.comb「デフォルト」スカラー($_)に格納します@

$_=@=(…)[^15].join.comb;

デフォルトのスカラー内の値の合計を見つけ、それがゼロの場合、15個のゼロの配列を含むデフォルトのスカラーを返します

.sum??  !!$_

合計がゼロでない場合、最初にデフォルトのスカラーの最初の要素からシフトしてリストを作成します

.shift,  

その後、残りの値を生成し、前の値と照合し ます($^b
デフォルトのスカラーが値を使い果たした場合、代わりに0を使用します(//0

…,{  ;until (my$a~=.shift//0)>$^b {};$a}...*

デフォルトのスカラーに要素が残っていないときに停止する

…,{last if !@$_;  }...*

なぜスペースが必要なのuntil (my$a...ですか?(特別な区切り文字ではありませんか?

@catという名前のサブルーチンの呼び出しになりますが、このサブルーチンuntilは存在しません。
ブラッドギルバートb2gills
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.