我编写了代码来实现我在字符串排列中找到的算法。我所拥有的是一个单词的arraylist(最多200个),我需要以5级的顺序排列列表。基本上将字符串单词分为五个并排列它们。我所取的前5个单词会产生排列并忽略其余的arraylist? 任何想法都赞赏。
Private Function permute(ByVal chunks As ArrayList, ByVal k As Long) As ArrayList
ReDim ItemUsed(k)
pno = 0
Permutate(k, 1)
Return chunks
End Function
Private Shared Sub Permutate(ByVal K As Long, ByVal pLevel As Long)
Dim i As Long, Perm As String
Perm = pString ' Save the current Perm
' for each value currently available
For i = 1 To K
If Not ItemUsed(i) Then
If pLevel = 1 Then
pString = chunks.Item(i)
'pString = inChars(i)
Else
pString = pString & chunks.Item(i)
'pString += inChars(i)
End If
If pLevel = K Then 'got next Perm
pno = pno + 1
SyncLock outfile
outfile.WriteLine(pno & " = " & pString & vbCrLf)
End SyncLock
outfile.Flush()
Exit Sub
End If
' Mark this item unavailable
ItemUsed(i) = True
' gen all Perms at next level
Permutate(K, pLevel + 1)
' Mark this item free again
ItemUsed(i) = False
' Restore the current Perm
pString = Perm
End If
Next
对于一个排列中的单词数,K以上是=到5但是当我将for循环更改为arraylist大小时,我得到索引超出范围的错误
答案 0 :(得分:0)
当你从1开始循环到长度时,通常会发生索引越界错误。 for循环如下。
For i = 0 to array.length - 1
答案 1 :(得分:0)
您将收到此错误。
当你这样做时
对于i = 1到K
i的最后一个值将是数组的大小。
chunks.Item(I)
当i等于数组的大小时会崩溃,因为索引从0开始。
我建议您将for循环更改为
对于i = 0到K - 1
或者您更改了访问数组中值的方式
chunks.Item第(i-1)
答案 2 :(得分:0)
C ++ Permutation
#include <stdio.h>
void print(const int *v, const int size)
{
if (v != 0)
{
for (int i = 0; i < size; i++)
{
printf("%4d", v[i] );
}
printf("\n");
}
} // print
void permute(int *v, const int start, const int n)
{
if (start == n-1) {
print(v, n);
}
else {
for (int i = start; i < n; i++) {
int tmp = v[i];
v[i] = v[start];
v[start] = tmp;
permute(v, start+1, n);
v[start] = v[i];
v[i] = tmp;
}
}
}
main()
{
int v[] = {1, 2, 3, 4};
permute(v, 0, sizeof(v)/sizeof(int));
}