おつかれさまーーでーーすーーー
寝不足気味のなずなです。
暖かくなるとプログラム書きたくなりますよね!
絶好の引きこもり日和というやつです。
というわけで、たまたま目に入ったのがこちらの記事
やりたいことはわかるけど、
なにやってるかさっぱりわかんない
どうしよう。。。
ってなわけで、無理やり適当に書いてみました。
これって有名なスタックのアルゴリズム的な何かですよね!
訓練時代にJAVAで出てきたときは寝てました←
ざざっとコードはこちら
Sub sample() Dim str '対象文字列の格納セル str = Range("A1").Value Dim res '出力先セル Set res = Range("A2") Range("A1").Copy res '全角半角対策 str = Replace(str, "(", "(") str = Replace(str, ")", ")") '--------------文字列の括弧の位置を取得! Dim i Dim statCol As New Collection Dim cnt As New Collection Dim kakko As New Collection Dim s For i = 1 To Len(str) s = Mid(str, i, 1) If s = "(" Then statCol.Add i End If If statCol.Count > 0 Then If s = ")" Then Dim tmp ReDim tmp(2) tmp(0) = statCol(statCol.Count) tmp(1) = i tmp(2) = statCol.Count '深さを取得 cnt.Add tmp statCol.Remove (statCol.Count) If statCol.Count = 0 Then kakko.Add cnt Set cnt = New Collection End If End If End If Next ' If statCol.Count > 0 Then ' MsgBox "括弧の閉じ忘れがあるよ!!" ' Exit Sub ' ' End If '---------------------色格納。変更したいときは適当に上から順番に深さです。 Dim colorList As New Collection colorList.Add vbRed colorList.Add vbBlue colorList.Add vbMagenta colorList.Add vbGreen colorList.Add vbCyan 'colorList.Add vbYellow '白背景だとみにくいです。 '---------------色変更処理 Dim y Dim colorPos Dim x For x = 1 To kakko.Count Dim nes As Collection Set nes = kakko(x) For y = nes.Count To 1 Step -1 Dim sPos Dim ePos sPos = nes(y)(0) ePos = nes(y)(1) - nes(y)(0) + 1 colorPos = nes(y)(2) 'ネストが深すぎる時用対策 If colorPos > colorList.Count Then colorPos = 1 End If res.Characters(Start:=sPos, Length:=ePos).Font.Color = colorList(colorPos) Next Next End Sub
貼り付けると思ったより長いですな。。。
い、いちおう ほかに転用したい理由があってこの長さなんです。。。
プロシージャわけてないのはわざとですよ。。。?
変数名は気にしたら負けです。
わたしのだとかっこまで色がついちゃうのは
仕様です←
今にして思えばスタック覚えるために
出てくる例題ですが、さっぱりわかりませんな。
とりあえず
キューは並んだ順番
スタックは詰んだ順番
って覚えれば大丈夫な気がする。
コード自体はどうでもいいとして
改めてコードの書き方で気になるとこがあるんです。
Dim tmp ReDim tmp(2) tmp(0) = statCol(statCol.Count) tmp(1) = i tmp(2) = statCol.Count '深さを取得 cnt.Add tmp
この部分です。
どういうわけなのか、JAVA習って以来
癖になった書き方です。
なんかデメリットありそうでいやだなーと思いつつも
なんか好きなのでやめない
詳しい人いたら教えて!