javascript - Combination of a letter using recursive -
Suppose, if I give 'ABC' as input then I want to < Strong> 'ABC', 'ACB', 'CAB', 'CBA', 'BAC', 'BCA' . Each word has a combination of n! Where n is the length of the letter I think the recycling can make it easy. Here my code is written in javascript: Please use the detailed comment. Note: This program works under the assumption that the characters in the input string are unique. Three parameters passed in this function. First of all, there is an existing string that was created with recursion, the second is the array of characters from the actual string, the third one, which is already seen in the recurring tree. The first condition is the base position of this recursive solution. If the length of the current string is equal to the length of the actual string, then no letter has been left for us to operate and one of these combinations is. Therefore, we return to it. If that condition is not complete, then in the actual string for each letter, we check that it has been used in advance (we have The results of the recursion will be an array of strings. We should level them up (adding all elements of internal arrays). Therefore, we have the Finally, we get a result and here it is told how the recurring tree looks like
function againArange (word) {console.log (word); If (word.length & lt; 0) {return (-1); } And if (word.length == 0) {return (''); } Else {for (var _i = 0; _i & lt; word.length; _i ++) {var temp = word [_i]; For (var _j = 0; _j & lt; word.length; _j ++) {if (_i! = _j) {return word [_i] + rearrangement (word salis (_i, word.length)); }}}}}
function combination (current_string, real_string, seen) {var results = []; If (current_string.length === real_string.lamp) {return [current_string]; } Actual_string.forEach (function (current, index) {if (index.indexOf (index) === -1) {result = [] .concat.apply (result, combination (current_string + current customer, real_string, seen.concat) Index)));}}); Return result; } Console.log (combination ("", "ABC" .split (""), [])); ['ABC', 'ACB', 'Bac', 'BCA', 'CAB', 'ABC', 'BCA', 'CAB' 'CBA']
seen from index). If it is already used in the current recycling, then ignore it. Otherwise, be consistent with the current string and now include the variables seen in it and the recurs.
[]. Use concat.apply .
Comments
Post a Comment