Advertisement
Guest User

Untitled

a guest
May 25th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.74 KB | None | 0 0
  1. using System;
  2.                    
  3. public class Program
  4. {
  5.     public static void Main()
  6.     {
  7.         Console.WriteLine("Please insert a character array, separated by ','");
  8.         string mystring = Console.ReadLine();
  9.         string[] myarray = mystring.Split(',');
  10.        
  11.         // When we work with recursions, we can sometimes use helper parameters
  12.         // These parameters are used to "keep memory" and indicate in which step of the recursion we are
  13.         // In this recursion, I will use an index, to indicate the position in the array I currently want to fill in the array
  14.         // When filling a position in the array, I can either:
  15.         //      1. Leave the value as-is
  16.         //      2. Switch it with another value in the array
  17.         Permutations(myarray, 0);
  18.     }
  19.    
  20.     public static void PrintArray(string[] arr) {
  21.         for (int i = 0; i < arr.Length; i++) {
  22.             Console.Write(arr[i]); 
  23.         }
  24.         Console.WriteLine();
  25.     }
  26.    
  27.     public static void Permutations(string[] myarray, int start_index) {
  28.         // Base condition. We reached the end of the array, can only leave the current index as-is
  29.         if (start_index == myarray.Length - 1) {
  30.             PrintArray(myarray);
  31.             return;
  32.         }
  33.        
  34.         // Option 1: leave the index as-is and continue the recursion
  35.         Permutations(myarray, start_index + 1);
  36.        
  37.         // Option 2: switch it with a different value in the array (loop over every possibility)
  38.         for (int i = start_index + 1; i < myarray.Length; i++) {
  39.             // Switch between start_index and i
  40.             string tmp = myarray[start_index];
  41.             myarray[start_index] = myarray[i];
  42.             myarray[i] = tmp;
  43.            
  44.             // Call the recursion
  45.             Permutations(myarray, start_index + 1);
  46.            
  47.             // Switch between start_index and i back, in order to continue the recursion safely
  48.             myarray[i] = myarray[start_index];
  49.             myarray[start_index] = tmp;
  50.         }
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement