概述:約翰遜特羅特算法
我想實現約翰遜豬蹄算法在Java中,這樣我可以在Project Euler解決問題。我已經找了又找,但據我可以看到我把一切都實現正確的,你知道是錯的,否則我就不會問這個問題:)
的基本算法是這樣的:
Johnson Trotter(n)
//Input: A positive integer n
//Output: A list of all permutations(0..n)
initialize the first permutation with: <0, <1, <2
//(all elements pointing left)
while (//there exists a mobile element)
//find the largest mobile element K
//swap K with the element it points toward
//reverse the direction of all elements > K
//add the permutation to a list
我創建了一個Element
對象,該對象具有用於此算法的屬性(value, isMobile, Direction)
。當我交換值時,只發生一次交換,然後在原來的訂單上反覆打印。
代碼:
public void generatePermutations(int n)
{
ArrayList<String> permutations = new ArrayList<String>();
ArrayList<Element> elements = new ArrayList<Element>();
//Initialize the first permutation,
//all Elements are mobile and point LEFT
for(int i = 0; i < n; i++)
{
elements.add(new Element(i, true, Direction.LEFT));
}
//add initial permutation to the list
permutations.add(combineElementsToString(elements));
while(hasMobileElement(elements))
{
//find the largest mobile element
int maxIndex = getLargestMobileIndex(elements);
Element k = elements.get(maxIndex);
//Swap the largest Element with the Element it points to
if(k.getDirection() == Direction.LEFT)
{
//get the index of the element to the left of k
int leftIndex = (maxIndex - 1) >= 0 ? (maxIndex - 1) : maxIndex;
Collections.swap(elements, maxIndex, leftIndex);
}
else
{
//get the index of the element to the right of k
int rightIndex =
(maxIndex + 1) < elements.size() ? (maxIndex + 1) : maxIndex;
Collections.swap(elements, maxIndex, rightIndex);
}
//reverse the direction of all elements larger than K
for(Element e : elements)
{
//System.out.println(e);
if(e.getValue() > k.getValue())
{
Direction opposite = Direction.opposite(e.getDirection());
e.setDirection(opposite);
}
}
//add the new permutation to the list
permutations.add(combineElementsToString(elements));
if(STOP++ == 10) System.exit(0);
}
}
//converts all the values of the Element
//objects then adds them to a String
public String combineElementsToString(ArrayList<Element> elements)
{
String perm = "";
for(Element e : elements)
{
perm += Integer.toString(e.getValue());
}
return perm;
}
//finds largest Mobile element and returns it's index
public int getLargestMobileIndex(ArrayList<Element> elements)
{
int maxIndex = 0;
for(int i = 0; i < elements.size(); i++)
{
if(elements.get(i).isMobile() && i > maxIndex)
{
maxIndex = i;
}
}
return maxIndex;
}
//determines if there is a remaining mobile element
public boolean hasMobileElement(ArrayList<Element> elements)
{
for(Element e : elements)
{
if(e.isMobile())
return true;
}
return false;
}
期望: 我期望算法做這樣的事
開始:
<0 <1 <2
<0 <2 <1
<2 <0 <1
等
實際
這就是它實際上
開始:
<0 <1 <2
<0 <2 <1
<0 <2 <1
<0 <2 <1
它不第一個交換後更改
任何幫助將是真棒,此外,如果您有意見/關於我的風格的指針,也將非常感謝,謝謝。
對不起,對於很長的文章。
謝謝!這絕對是我沒有看到的問題。現在最大的元素交換到左邊,然後沒有其他事情發生。無論謝謝。 –
@獵人我懷疑你的isMobile有問題。你確定它不是:1)只檢查左邊的移動元素2)如果最大元素位於列表的最左邊,則將最大元素視爲移動元素? –
你又對了。無論位置如何,我仍然在考慮2最大。謝謝 –