Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- public class Program
- {
- public static void Main()
- {
- Console.WriteLine("Please insert a character array, separated by ','");
- string mystring = Console.ReadLine();
- string[] myarray = mystring.Split(',');
- // When we work with recursions, we can sometimes use helper parameters
- // These parameters are used to "keep memory" and indicate in which step of the recursion we are
- // In this recursion, I will use an index, to indicate the position in the array I currently want to fill in the array
- // When filling a position in the array, I can either:
- // 1. Leave the value as-is
- // 2. Switch it with another value in the array
- Permutations(myarray, 0);
- }
- public static void PrintArray(string[] arr) {
- for (int i = 0; i < arr.Length; i++) {
- Console.Write(arr[i]);
- }
- Console.WriteLine();
- }
- public static void Permutations(string[] myarray, int start_index) {
- // Base condition. We reached the end of the array, can only leave the current index as-is
- if (start_index == myarray.Length - 1) {
- PrintArray(myarray);
- return;
- }
- // Option 1: leave the index as-is and continue the recursion
- Permutations(myarray, start_index + 1);
- // Option 2: switch it with a different value in the array (loop over every possibility)
- for (int i = start_index + 1; i < myarray.Length; i++) {
- // Switch between start_index and i
- string tmp = myarray[start_index];
- myarray[start_index] = myarray[i];
- myarray[i] = tmp;
- // Call the recursion
- Permutations(myarray, start_index + 1);
- // Switch between start_index and i back, in order to continue the recursion safely
- myarray[i] = myarray[start_index];
- myarray[start_index] = tmp;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement