2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【javascript】フィボナッチ(トリボナッチ等)数列をワンライナーで(追記コード1個)

Last updated at Posted at 2021-04-22

#引数

  • f … 2:フィボナッチ、3:トリボナッチ、4:テトラナッチ ……
  • n … 配列の長さ

#コード(追記)

const nacci = (f,n) => [...Array(n-2)].reduce((p,_,i) => 
	(p.push(p[i+f]*2 - p[i]), p), [...Array(f-1).fill(0),1,1] ).slice(f-1);

コメントで指摘を受けて追記。
先のものよりは軽くなったと思う。

#コード

const nacci = (f, n) => 
	[...Array(n-1)].reduce(p => p.concat( p.slice(-f).reduce((s,x)=>s+x) ), [1]);

console.log( nacci(2, 15) );
// [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

※表示の都合上、改行してます

#感想
reduce楽しい。
先頭の0は残した形の方が良いのでしょうか?

ワンライナーにこだわらなければ

const nacci = (f,n) => {
	const a = [...new Int8Array(f-1),1,1];
	for (let i=0; i<n; i++) a.push(a[i+f]*2 - a[i]);
	return a.slice(f-1,-2);
};
console.log( nacci(2,15).pop() );
2
0
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?