Advertisement
vencinachev

Permutations

Sep 9th, 2021
1,337
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.67 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace Combinatorics
  6. {
  7.     class Program
  8.     {
  9.         static void swap(ref int a, ref int b)
  10.         {
  11.             int temp = a;
  12.             a = b;
  13.             b = temp;
  14.         }
  15.  
  16.         static void swap(ref char a, ref char b)
  17.         {
  18.             char temp = a;
  19.             a = b;
  20.             b = temp;
  21.         }
  22.  
  23.         static void Permutate(char[] arr, int n)
  24.         {
  25.             if (n == arr.Length - 1)
  26.             {
  27.                 Console.WriteLine(string.Join("", arr));
  28.                 return;
  29.             }
  30.             for (int i = n; i < arr.Length; i++)
  31.             {
  32.                 swap(ref arr[i], ref arr[n]);
  33.                 Permutate(arr, n + 1);
  34.                 swap(ref arr[i], ref arr[n]);
  35.             }
  36.         }
  37.  
  38.         static void Permutate(string str)
  39.         {
  40.             Permutate(str.ToCharArray(), 0);
  41.         }
  42.         static void Permutate(int[] arr, int n)
  43.         {
  44.             if (n == arr.Length - 1)
  45.             {
  46.                 Console.WriteLine(string.Join("", arr));
  47.                 return;
  48.             }
  49.             for (int i = n; i < arr.Length; i++)
  50.             {
  51.                 swap(ref arr[i], ref arr[n]);
  52.                 Permutate(arr, n + 1);
  53.                 swap(ref arr[i], ref arr[n]);
  54.             }
  55.         }
  56.  
  57.         static void Permutate(int[] arr)
  58.         {
  59.             Permutate(arr, 0);
  60.         }
  61.         static void Main(string[] args)
  62.         {
  63.             /*int[] arr = { 1, 2, 3, 4, 5 };
  64.              Permutate(arr);*/
  65.  
  66.             string s = "ABC";
  67.             Permutate(s);
  68.         }
  69.     }
  70. }
  71.  
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement