方法來產生可紡串
我已經實現了一個簡單的方法來解決這個問題的所有permuatuons。 它需要一個包含可旋轉文本字符串的ArrayList參數。 我使用它來生成多個可旋轉字符串的所有排列。
它具有支持可選塊的額外功能,支持「[]」括號。
Eq。: 如果ArrayList中有一個字符串對象,其內容爲: {A | {B1 | B2} [B可選]}
它填充 「提取」 方法的調用之後 內容與所有的排列的數組列表,: 甲 B1 B1乙可選 B2 B2乙可選
您也可以傳遞多個字符串作爲參數來爲它們生成排列: 例如: 輸入: 帶兩個字符串的ArraList {A1 | A2} {B1 | B2}調用之後 內容: A1 A2 B1 B2
此實現的工作方式是總是尋找在第一紡絲的部分最內側托架對,然後將其解壓縮。我這樣做直到刪除所有特殊的{},[]字符。
private void ExtractVersions(ArrayList list)
{
ArrayList IndicesToRemove = new ArrayList();
for (int i = 0; i < list.Count; i++)
{
string s = list[i].ToString();
int firstIndexOfCurlyClosing = s.IndexOf('}');
int firstIndexOfBracketClosing = s.IndexOf(']');
if ((firstIndexOfCurlyClosing > -1) || (firstIndexOfBracketClosing > -1))
{
char type = ' ';
int endi = -1;
int starti = -1;
if ((firstIndexOfBracketClosing == -1) && (firstIndexOfCurlyClosing > -1))
{ // Only Curly
endi = firstIndexOfCurlyClosing;
type = '{';
}
else
{
if ((firstIndexOfBracketClosing > -1) && (firstIndexOfCurlyClosing == -1))
{ // Only bracket
endi = firstIndexOfBracketClosing;
type = '[';
}
else
{
// Both
endi = Math.Min(firstIndexOfBracketClosing, firstIndexOfCurlyClosing);
type = s[endi];
if (type == ']')
{
type = '[';
}
else
{
type = '{';
}
}
}
starti = s.Substring(0, endi).LastIndexOf(type);
if (starti == -1)
{
throw new Exception("Brackets are not valid.");
}
// start index, end index and type found. -> make changes
if (type == '[')
{
// Add two new lines, one with the optional part, one without it
list.Add(s.Remove(starti, endi - starti+1));
list.Add(s.Remove(starti, 1).Remove(endi-1, 1));
IndicesToRemove.Add(i);
}
else
if (type == '{')
{
// Add as many new lines as many alternatives there are. This must be an in most bracket.
string alternatives = s.Substring(starti + 1, endi - starti - 1);
foreach(string alt in alternatives.Split('|'))
{
list.Add(s.Remove(starti,endi-starti+1).Insert(starti,alt));
}
IndicesToRemove.Add(i);
}
} // End of if(>-1 && >-1)
} // End of for loop
for (int i = IndicesToRemove.Count-1; i >= 0; i--)
{
list.RemoveAt((int)IndicesToRemove[i]);
}
}
我希望我能幫上忙。 也許這不是最簡單和最好的實現,但它對我來說很好。請反饋並投票!
幹得好。支持可選塊的絕妙想法 – LeMoussel