Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- class PrintAllPermutationsOfInterval1ToNHeapAlg
- {
- static void HeapPermute(int[] arrayOfPermutes, int length, List<string> CurrentList)//The heap algorythm for ermutations
- {
- int swapBuffer = 0; //A buffer used to swap the elements in the array
- if (length == 1) //If length has reached 1 it is time to record the currentList that contains one of the permutations
- {
- string currentPermutation = ""; //Create a string to hold the current positions of the numbers
- for (int i = 0; i < arrayOfPermutes.Length; i++)
- {
- currentPermutation += arrayOfPermutes[i] + " ";
- }
- CurrentList.Add(currentPermutation); //Add the string to a list to print it later
- }
- else
- {
- for (int i = 0; i < length; i++) //If we are still in the recursion
- {
- HeapPermute(arrayOfPermutes, length - 1, CurrentList); //Recursion with length minus one.
- if (length % 2 == 1) //Heap algorithm: if the remainder is 1-st we swap the first element with the element that has lenght-1
- {
- swapBuffer = arrayOfPermutes[0];
- arrayOfPermutes[0] = arrayOfPermutes[length - 1];
- arrayOfPermutes[length - 1] = swapBuffer;
- }
- else//Heap algorithm: if the remainder is not 1 we swap the i-th element with the element that has lenght-1
- {
- swapBuffer = arrayOfPermutes[i];
- arrayOfPermutes[i] = arrayOfPermutes[length - 1];
- arrayOfPermutes[length - 1] = swapBuffer;
- }
- }
- }
- }
- static void Main()
- {
- int numN = 4; //The number to permute! Be careful even for 10 it takes a lot of time! It print numN! permutations!
- List<string> CurrentList = new List<string>(); //A list used to store and later print the current permutation
- int[] arrayOfNumbers = new int[numN]; //The starting array of numbers
- for (int i = 0; i < numN; i++)//Generates and fills the elemnets of the array from 1 to numN
- {
- arrayOfNumbers[i] = i + 1;
- }
- //Do the Heap algorithm on the array to generate the permutations
- HeapPermute(arrayOfNumbers, numN, CurrentList);
- //Print the resulting list
- for (int i = 0; i < CurrentList.Count; i++)
- {
- Console.WriteLine(CurrentList[i]);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement