1
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】LevelLabelをfor文で

Last updated at Posted at 2021-04-26

#前置き

FizzBuzz問題の次を考えた!その名も「LevelLabel問題」 - Qiita
https://qiita.com/yamitake@github/items/6a82de2cf235544f2f97

上記記事で提案された新たな問いです。
コメントで良さげな解があるのでいまさらですが。。。
私も微妙なコメントをした記事ですが、改めて考えてみました。

#LevelLabelとは
3つ以上の連番をまとめて文字列で出力。
元記事では「・」と「~」で区切ってますが、この記事では「,」と「-」で区切ります。

//こんな配列を
[1,2,3,5,7,9,10,11,20,21]
//こうまとめる
'1-3,5,7,9-11,20,21'

#コード

const levelLabel = a => {
	const r = [];
	for(let i=0,s=0; i<a.length; s=i){
		//要素の前後を比較して条件が合えば`変数i`を増やして処理対象をワープ
		while (a[i]===a[++i]-1) {}
		r.push(i-s<3 ? a.slice(s,i) : a[s]+'-'+a[i-1]);
	}
	return r.join();
};

const arr = [1,2,3,5,7,9,10,11,20,21];
console.log( levelLabel(arr) );
//1-3,5,7,9-11,20,21

コードゴルフには弱い

1
0
4

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
1
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?