Implementation of permutation algorithm using recursion and loop

Arrangement is to take m numbers from n numbers (considering the order of the numbers) to have several cases. This is a mathematical definition and may be difficult to understand. From a more life-like point of view, it is to take 3 balls from a box containing a red ball, a yellow ball, a green ball, a white ball and a black ball (consider the order of the balls) There are several situations. . The permutation algorithm was invented to solve this kind of problem.

We can solve this problem by drawing a tree diagram:



As can be seen from the above figure, taking 3 numbers from ['A', 'B', 'C', 'D'] to arrange 6 * 4 = 24 cases. So the question is, how should we use the program to realize the solution process of the tree diagram? In fact, we can see that we need to draw several layers to take out a few numbers. Each layer is actually a traversal of the data, and the operations of each layer are similar, so we can use recursion and looping to implement this tree. graph solution process. The code is as follows (described in JS language):

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Assortment</title>
  <script>
    var arr = ['A', 'B', 'C', 'D'];
    var count = 3;
    var iNow = 1;

    function rangeCombination(arr, count) {
      var resultNum = 0;

      if (count == 1) {
        return arr.length;
      }
      function change(arr, iNow) {

        for (var i = 0; i < arr.length; i++) {
          var result = arr.concat();
          result.splice(i, 1);
          if (count == iNow) {
            resultNum += result.length;
          } else {
            change(result, iNow + 1);
          }

        }

      }
      change(arr, iNow + 1);


      return resultNum;
    }
    console.log(rangeCombination(arr, count));
  </script>
</head>
<body>

</body>
</html>



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325762792&siteId=291194637