VBAで順列
VBAで配列を与えると全ての順列を返すユーザー定義関数を紹介します。
JavaScriptの配列関連メソッドをVBAのユーザー定義関数に | You Look Too Cool
で紹介したユーザー定義関数のうち「splice」「push」「concat」が必要です。
Function junretsu(a)
'配列を与えると全ての順列を配列で返す。
If UBound(a) = 0 Then
junretsu = Array(a)
Else
arrs = Array()
For i = 0 To UBound(a)
b = a
c = splice(b, i, 1)
res = junretsu(b)
For j = 0 To UBound(res)
d = push(arrs, concat(Array(a(i)), res(j)))
Next j
Next i
junretsu = arrs
End If
End Function
'配列を与えると全ての順列を配列で返す。
If UBound(a) = 0 Then
junretsu = Array(a)
Else
arrs = Array()
For i = 0 To UBound(a)
b = a
c = splice(b, i, 1)
res = junretsu(b)
For j = 0 To UBound(res)
d = push(arrs, concat(Array(a(i)), res(j)))
Next j
Next i
junretsu = arrs
End If
End Function
要素を配列で与えると、各要素の全ての順列を配列で返します。
厳密には配列の配列です。例えばArray(1,2,3)を与えると最初の要素はArray(1,2,3)、次の要素はArray(1,3,2)、その次の要素はArray(2,1,3)となります。
使用例は次のとおりです。
Sub 使用例()
a = Array(1, 2, 3, 4)
res = junretsu(a)
temps = Array()
For i = 0 To UBound(res)
temp = push(temps, Join(res(i), ","))
Next i
MsgBox Join(temps, "/")
End Sub
a = Array(1, 2, 3, 4)
res = junretsu(a)
temps = Array()
For i = 0 To UBound(res)
temp = push(temps, Join(res(i), ","))
Next i
MsgBox Join(temps, "/")
End Sub
実行すると次のとおりとなります。
1,2,3,4/1,2,4,3/1,3,2,4/1,3,4,2/1,4,2,3/1,4,3,2/
2,1,3,4/2,1,4,3/2,3,1,4/2,3,4,1/2,4,1,3/2,4,3,1/
3,1,2,4/3,1,4,2/3,2,1,4/3,2,4,1/3,4,1,2/3,4,2,1/
4,1,2,3/4,1,3,2/4,2,1,3/4,2,3,1/4,3,1,2/4,3,2,1
[ 2015年12月26日 | カテゴリー: Excel | タグ: VBA , 配列 ]
« 横濱家系ラーメン上野商店 | 「エンジニアが1時間未満で解くべき五つの問題」をVBAで解く »
[…] VBAで順列 | You Look Too Cool […]