Permute 2, 3 gives us the results (2, 3) and (3, 2). Notice how we consolidated the branches for the 2nd and 3rd numbers into three recursive calls?įor instance, the orange branches in the original solution are replaced with the recursive call “Permute 2, 3” in the solution above. Instead of listing all possible branches of the diagram, we can consolidate the branches for the second and third numbers, as shown in the diagram below: To do that, we need to look at the tree diagram differently. We can modify this diagram to represent the solution as a recursive solution. How to permute numbers using recursion?Ī tree diagram allows us to systematically list all possible permutations of a given set of numbers. The rest of the results can be obtained using the same logic. This gives us 1, 3, 2 as result (2nd result above). If the second number is 3, the third number must be 2. This gives us 1, 2, 3 as the result (1st result above). If the second number is 2, the third number must be 3. If the first number is 1, the second number can be 2 or 3 (shown in orange above). The diagram below shows how we can do it. Suppose we want to permute the numbers 1, 2, and 3. The most systematic way to do it is to use a tree diagram. How to permute numbers Mathematically?īefore proceeding with the programming for today’s challenge, we need to first know how to permute numbers mathematically. We’ll be using recursion with a for loop today, which is slightly more complicated than what we did in previous posts. If you are unfamiliar with recursion, I strongly recommend that you check out previous posts on recursion ( here, here and here). As mentioned in previous posts, recursion is an excellent approach to use when the solution to the problem depends on solutions to smaller instances of the same problem. We’ll be using recursion to solve the challenge in this post.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |