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.

対応するかっこのインデックスを返す

Posted at

対応するかっこのインデックスを返す

Brainfuck のインタプリタを作ろうかと思って。

これはなに

かっこ ([]) の対応を調べる。
対応するかっこがあればそのインデクスを返す。
なければ -1 を返す。
そもそもかっこでなければ自分のインデクスを返す。

例:

let str = '++[>++[>++<-]<-]>>';
let foo = bracket(str, 2);	// 15
let bar = bracket(str, 12);	// 6
let baz = bracket(str, 7);	// 7
let err = '[[[][][]][][]';
let qux = bracket(err, 0);	// -1
function bracket(s, p) {
	if (!/\]|\[/.test(s[p])) {
		return p;
	}
	let nest = 1;
	if (s[p] === '[') {
		for (p++; nest; p++) {
			if (p >= s.length) { return -1; }
			s[p] === '[' && nest++;
			s[p] === ']' && nest--;
		}
		p--;
	}
	else {
		for (p--; nest; p--) {
			if (p < 0) { return -1; }
			s[p] === ']' && nest++;
			s[p] === '[' && nest--;
		}
		p++;
	}
	return p;
}
1
0
2

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?