Advertisement
sylviapsh

All Permutations [1..N] with Heap's Algorithm

Jan 14th, 2013
505
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.33 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. class PrintAllPermutationsOfInterval1ToNHeapAlg
  6. {
  7.   static void HeapPermute(int[] arrayOfPermutes, int length, List<string> CurrentList)//The heap algorythm for ermutations
  8.   {
  9.     int swapBuffer = 0; //A buffer used to swap the elements in the array
  10.  
  11.     if (length == 1) //If length has reached 1 it is time to record the currentList that contains one of the permutations
  12.     {
  13.       string currentPermutation = ""; //Create a string to hold the current positions of the numbers
  14.       for (int i = 0; i < arrayOfPermutes.Length; i++)
  15.       {
  16.         currentPermutation += arrayOfPermutes[i] + " ";
  17.       }
  18.       CurrentList.Add(currentPermutation); //Add the string to a list to print it later
  19.     }
  20.     else
  21.     {
  22.       for (int i = 0; i < length; i++) //If we are still in the recursion
  23.       {
  24.         HeapPermute(arrayOfPermutes, length - 1, CurrentList); //Recursion with length minus one.
  25.  
  26.         if (length % 2 == 1) //Heap algorithm: if the remainder is 1-st we swap the first element with the element that has lenght-1
  27.         {
  28.           swapBuffer = arrayOfPermutes[0];
  29.           arrayOfPermutes[0] = arrayOfPermutes[length - 1];
  30.           arrayOfPermutes[length - 1] = swapBuffer;
  31.         }
  32.         else//Heap algorithm: if the remainder is not 1 we swap the i-th element with the element that has lenght-1
  33.         {
  34.           swapBuffer = arrayOfPermutes[i];
  35.           arrayOfPermutes[i] = arrayOfPermutes[length - 1];
  36.           arrayOfPermutes[length - 1] = swapBuffer;
  37.         }
  38.       }
  39.     }
  40.   }
  41.  
  42.   static void Main()
  43.   {
  44.     int numN = 4; //The number to permute! Be careful even for 10 it takes a lot of time! It print numN! permutations!
  45.     List<string> CurrentList = new List<string>(); //A list used to store and later print the current permutation
  46.     int[] arrayOfNumbers = new int[numN]; //The starting array of numbers
  47.  
  48.     for (int i = 0; i < numN; i++)//Generates and fills the elemnets of the array from 1 to numN
  49.     {
  50.       arrayOfNumbers[i] = i + 1;
  51.     }
  52.  
  53.     //Do the Heap algorithm on the array to generate the permutations
  54.     HeapPermute(arrayOfNumbers, numN, CurrentList);
  55.  
  56.     //Print the resulting list
  57.     for (int i = 0; i < CurrentList.Count; i++)
  58.     {
  59.       Console.WriteLine(CurrentList[i]);
  60.     }
  61.   }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement