字母表上的蛮力风格功能。可能有更简单的方法可以做到这一点。
function brute(alphabet, match, int_start, int_stop){
var a = alphabet, al = 0, // for alphabet
m = match.toString(), ml = m.length, // for our compare
i = int_start || 0, j = int_stop || 0, // range of numbers to test
k = 0, l = 0, add = 0, sub = 0, diff = 0, // for building test string
test = '', found = false; // test string and result
if(i < 0) throw 'int_start must be at least 0';
if(a.constructor !== undefined){ // We need a string or array as
if( a.constructor.name !== 'String' && // our alphabet so we check for
a.constructor.name !== 'Array' ) // correct input and modify if
a = a.toString(); // necessary, or if we can't,
}
else throw 'Bad alphabet type'; // we throw an error
al = a.length; // shorthand length
add = al; // when i=0, we start prefix here
while(add <= i - sub) sub += add, // then work out what we have to
add = add * al; // prefix our number with
diff = add - sub; // shorthand to save calculations
while( i < j ){ // actual brute force loop starts here
test = ''; // empty any previous string
k = diff + i; // convert our number from "x" to "1x"
while(k > 0){ // build it as a string
l = k % al; // get index of digit
test = a[l] + test; // add digit to string
k = ( k - l ) / al; // move digits along
}
test = test.substring(1); // cut off the initial "1" we added
if(test.length === ml && test === m){ // compare test to what you want
found = true;
break;
}
i++; // prepare for our next loop
if(i - sub === add) // and if we need another digit
sub += add, // then recalculate our prefix
add = add * al, // and then
diff = add - sub; // update the shorthand
}
// brute force ended, let's see what we've got
if(found === false) i = -1; // if not found, return -1 as index
return [i, test, m]; // index found, string found with, what we were looking for
}
然后通过例如使用
brute('0123abcd', '0c', 0, 20); // [14, "0c", "0c"]