Permutation

#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <assert.h>

/*
* Swap two integer.
* Param:
* a: One integer.
* b: Another integer.
*/
inline void swap(int &a, int &b)
{
int c = a ;
a = b ;
b = c ;
}

/*
* Print a line of numbers in 'arr'.
* Param:
* arr: The array which contain a line of numbers.
* len: The number of elements in 'arr'.
*/
void p_line(int arr[], int len)
{
for (int i = 0 ; i < len ;i++)
{
printf("%d ", arr[i]) ;
}
printf("\n") ;
}

/*
* The procedure of generating permutation.
* Param:
* arr: The array containing numbers.
* len: The number of elements in 'arr'.
* from: This parameter identify the begining index where
* to generate permutation.
* to: This parameter identify the ending index where to
* stop the procedure.
*
* Note:
* This function will put the result to STDOUT.
*/
void permutation(int arr[], int len, int from, int to)
{
if (from + 1 >= to)
{
p_line(arr, len) ;
}
else
{
for (int i = 0 ;i < to-from ;i++)
{
swap(arr[from], arr[from+i]) ;
permutation(arr, len, from+1, to) ;
swap(arr[from], arr[from+i]) ;
}
}
}

/*
* Generate permutation begin at 'from' and
* ending at 'to'.
* This function is a interface of function
* 'permutation'.
*
* Param:
* m: The begining number.
* n: The ending number.
*
* Note:
* This function will put the result to STDOUT.
*/
void gen_permutation(int m, int n)
{
assert(m <= n) ;

int *arr = new int[n-m] ;
memset(arr, '\0', (n-m) * sizeof(arr[0])) ;
for (int i = 0 ;i < n-m ;i++)
{
arr[i] = m+i ;
}

permutation(arr, n-m, 0, n-m) ;

delete []arr ;
arr = NULL ;
}

int main()
{
gen_permutation(5, 10) ;
}

 
posted @ 2011-10-13 13:10  walfud  阅读(361)  评论(0编辑  收藏  举报