Sorry, meant to put it in the last post, but I was still translating it from Python to AS.
Here's my code... probably not the best way to do it, but it's still significantly faster than having 4 nested for(1..100) loops:
(AS3... although it wouldn't be too hard to convert to AS2)
The ratios() function tries every possible combination and returns the ones that match. It takes just about 1 second on my computer, which should be decent for your needs.Code:function combinations(_n:int) {
var combArray:Array = new Array();
for (var ix=1; ix<_n+1; ix++) {
for (var xi=1; xi<_n+1; xi++) {
if (combArray.indexOf(ix*xi)==-1) {
combArray.push(ix*xi);
}
}
}
return combArray.sort(0x10);
}
function inverseArray(_a:Array) {
var invArray:Array = new Array(_a.length);
for (var ix=_a.length-1; ix+1; ix--) {
invArray[ix]=(1/_a[ix]);
}
return invArray;
}
function ratios(_n:Number,_max:int) {
var found:Array = [];
var n:int = _n*10000;
var min:Number;
var ratio:int;
for (var ix=0; ix<combs.length; ix++) {
min = _n/combs[ix];
for (var xi=0; xi<inv.length; xi++) {
ratio = Math.round(10000*combs[ix]*inv[xi]);
if (ratio==n) {
found.push([decompose(combs[ix],_max),decompose(int(1/inv[xi]),_max)]);
} else if (inv[xi]<min) {
break;
}
}
}
return found;
}
function decompose(_n:int,_max:int) {
var decomp:Array = [];
for (var ix=1; ix<_max+1; ix++) {
if (_n/ix<_max+1&&!(_n/ix%1)) {
decomp.push([ix,int(_n/ix)]);
}
}
return decomp;
}
const MAX_TEETH = 100;
var combs:Array = combinations(MAX_TEETH);
var inv:Array = inverseArray(combs);
var t:int = getTimer();
var r = ratios(2.5117,MAX_TEETH);
trace(getTimer()-t);
trace(countCombinations(r));
function countCombinations(_r:Array) {
var count:int=0;
for (var i in _r) {
count+=_r[i][0].length*_r[i][1].length;
}
return count;
}
It returns an array like this (for 2.5117):
[ [[[19,62],[31,38],[38,31],[62,19]],[[7,67],[67,7]]], ...]
Each element of the array is formatted like:
[ [ [a1,c1] , [a2,c2], ... ] , [ [b1,d1] , [b2,d2], ... ] ]
So that any combination of an element from the numerator array combined with an element of the denominator array will give the ratio.
Looking at just the first element of the 2.5117 array, you can create the following (8) combinations:
1. a=19, b=7, c=62, d=67
2. a=62, b=7, c=19, d=67
3. a=31, b=7, c=38, d=67
4. a=38, b=7, c=31, d=67
5. a=19, b=67, c=62, d=7
6. a=62, b=67, c=19, d=7
7. a=31, b=67, c=38, d=7
8. a=38, b=67, c=31, d=7
(keep in mind this includes all the duplicates too... i.e. #1 and #2 are essentially the same, just the a and c values switched)
Counting all the other elements, you get a grand total of 292 combinations for 2.5117.
That probably wasn't the best explanation, but if you have any other questions, just ask.

