2010-04-11 18 views
2

我已經編寫了代碼來實現我在字符串排列中找到的算法。我所擁有的是一個單詞列表(最多200個),我需要對列表中的5個級別進行排列。基本上將字符串單詞按五個進行分組並將其排列。我所擁有的前5個詞是否會產生排列並忽略其他的數組列表? 任何想法讚賞。上述排列出錯

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

你是什麼意思「在5個級別」是什麼意思? – 2010-04-11 20:08:33

+0

爲什麼你使用'SyncLock'?該代碼是否在多線程環境中使用?不建議!什麼是'pString',爲什麼它不是一個參數? – 2010-04-11 20:09:45

+0

如果您可以爲您的功能提供樣本輸入和所需的輸出,它可能會幫助我們弄清楚您要做什麼。 – CoderDennis 2010-08-10 17:23:23

回答

0

指數出界錯誤的通常在您從1開始循環時發生。 for循環如下。


For i = 0 to array.length - 1 
0

您將收到此錯誤。

當你

對於i = 1至K

我的最後一個值將是你的數組的大小。

chunks.Item(i)當我以來,該指數從0開始

我建議你改變你的for循環

對於我等於數組的大小

會崩潰= 0到K - 1

或者你改變你訪問你的陣列中的值

chunks.Item(I-1)的方式

0

C++排列

#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)); 
}