Interview Question
function take_out_char( str, chr ) {
// TODO: use buffer????
let result = '';
for( let n=0; n<from.length; n++ ) {
if( str[n]!=chr ) {
result += str[n];
}
}
return result;
}
function get_chars_less_or_equal_to( str, chr ) {
// TODO: use buffer????
let result = '';
for( let n=0; n<str.length; n++ ) {
if( str[n]<=chr ) {
result += str[n];
}
}
return result;
}
function factorial( n ) {
if( n==1 ) return 1;
return n*factorial(n-1);
}
function count_number_of_strings_between( from, to ) {
if( from.length!=to.length )
throw Error("String lengths do not match");
if( from.length==0 )
return 0;
let result = 0;
// Let's find the number of possible variations with given first character of "to"
let tmp = get_chars_less_or_equal_to(from,to[0]);
for( let k=0; k<tmp.length; k++ ) {
if( tmp[k]==to[0] ) {
// In this case we need to fix the first char of the "fitting" combination to tmp[k]
// and count the number of strings between (from without the tmp[k]) and
// (to without to[0])
result += count_number_of_strings_between(take_out_char(from,tmp[k]),to.substring(1));
}
else {
// Here tmp[k] is less than to[0].
// in this case we can make tmp[k] to be the first character and we do not
// care what the rest of the string is. The number of all possible "rests" is
// the factorial
result += factorial(from.length-1);
}
}
return result;
}
let from = 'abc';
let to = 'ddd';
// Subtract 1 to avoid counting string from itself
console.log(count_number_of_strings_between(from,to)-1);
read about std::next_permutation
- Alok September 22, 2018