Friday, December 3, 2010

generating all the possible permutations in actionscript/flex

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="main()">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
private function main():void {
var ac1:ArrayCollection = new ArrayCollection();
ac1.addItem(1);
ac1.addItem(2);
ac1.addItem(3);
ac1.addItem(4);
var output:ArrayCollection = permute(ac1);
for(var i:int = 0; i<output.length; ++i) {
var tmpAc:ArrayCollection = output.getItemAt(i) as ArrayCollection;
var singleLine:String = "";
for(var j:int = 0; j<tmpAc.length; ++j) {
singleLine += String(tmpAc[j])+" ";
}
trace(singleLine);
}
}
private function permute(inputListOfNumbers:ArrayCollection):ArrayCollection {
var output:ArrayCollection = new ArrayCollection();
if(inputListOfNumbers.length == 2) {
var ac1:ArrayCollection = new ArrayCollection();
ac1.addItem(inputListOfNumbers.getItemAt(0));
ac1.addItem(inputListOfNumbers.getItemAt(1));
output.addItem(ac1);
var ac1:ArrayCollection = new ArrayCollection();
ac1.addItem(inputListOfNumbers.getItemAt(1));
ac1.addItem(inputListOfNumbers.getItemAt(0));
output.addItem(ac1);
return output;
}
for(var i:int = 0; i<inputListOfNumbers.length; ++i) {
var otherThanIth:ArrayCollection = getElementsOtherThanIth(inputListOfNumbers,i);
var tmpRes:ArrayCollection = 
prependNumber(inputListOfNumbers.getItemAt(i) as int,permute(otherThanIth));
for(var j:int = 0; j<tmpRes.length; ++j) {
output.addItem(tmpRes.getItemAt(j));
}
}
return output;
}
private function prependNumber(i:int,ac1:ArrayCollection):ArrayCollection {
for(var j:int = 0; j<ac1.length; ++j) {
var tmpAc:ArrayCollection = ac1.getItemAt(j) as ArrayCollection;
tmpAc.addItemAt(i,0);
}
return ac1;
}
private function getElementsOtherThanIth(ac1:ArrayCollection,i:int):ArrayCollection {
var output:ArrayCollection = new ArrayCollection();
for(var j:int = 0; j<ac1.length; ++j) {
if(i != j) {
output.addItem(ac1.getItemAt(j));
}
}
return output;
}
]]>
</mx:Script>
</mx:Application>

No comments:

Blog Archive