I'm sure we all have had to do this at one point or another and it is especially handy in courses like Linear Algebra. A permutation is the arrangement of items within a set of data. Typically it is a string and thus the characters that comprise the string. It could also be numbers (bit matrices/parity error checking comes to mind). We want to give the function the array/string and the beginning and ending of the range we want permutations for (usually the entire thing, but we could be more selective if we chose to). Consider the following code snippet:
The function recursively calls itself until the range is 1. Between each recursive call we swap two chars in order to get each permutation. We then output each permutation before continuing. In C++ we would use pointers for the swap function and just have two parameters as locations to the data we want to swap. However, java doesn't allow passing by reference in method arguments so we must pass the object itself so we can modify its contents. Thanks for reading!
--KYA
import java.io.*;
public class Permute {
public static void swap(char[] set, int first, int second) //java doesn't allow the same pass by reference like C++
{
char ch = set[second]; //so we pass the char array and assign, since this will hold
set[second] = set[first]; //swap the values
set[first] = ch;
}
public static int permute(char[] set, int begin, int end)
{
int i;
int range = end - begin;
if (range == 1) {
System.out.println(set);
} else {
for(i=0; i<range; i++) {
swap(set, begin, begin+i); //initial swap
permute(set, begin+1, end); //recursion
swap(set, begin, begin+i); //swap back
}
}
return 0;
}
//***************TEST EXAMPLE********************
public static void main(String[] args) {
char[] test = {'a','b','c','d'}; //create our string
permute(test, 0, 4); //call it
}
}
The function recursively calls itself until the range is 1. Between each recursive call we swap two chars in order to get each permutation. We then output each permutation before continuing. In C++ we would use pointers for the swap function and just have two parameters as locations to the data we want to swap. However, java doesn't allow passing by reference in method arguments so we must pass the object itself so we can modify its contents. Thanks for reading!
--KYA
1 Comments On This Entry
Page 1 of 1
Programming Geeks
25 March 2010 - 06:31 PM
Another solution : http://programmingge...utation-in-java
Page 1 of 1
← January 2022 →
| S | M | T | W | T | F | S |
|---|---|---|---|---|---|---|
| 1 | ||||||
| 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| 9 | 10 | 11 | 12 | 13 | 14 | 15 |
| 16 | 17 | 18 | 19 | 20 | 21 | 22 |
| 23 | 24 | 25 | 26 | 27 | 28 | 29 |
| 30 | 31 |
Tags
My Blog Links
Recent Entries
Recent Comments
Search My Blog
17 user(s) viewing
17 Guests
0 member(s)
0 anonymous member(s)
0 member(s)
0 anonymous member(s)



1 Comments









|