Subscribe to Stuck in an Infiniteloop        RSS Feed
-----

String Permutations in Java

Icon 1 Comments
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:

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
0
Page 1 of 1

January 2022

S M T W T F S
      1
2345678
9101112131415
161718192021 22
23242526272829
3031     

Tags

    Recent Entries

    Recent Comments

    Search My Blog

    16 user(s) viewing

    16 Guests
    0 member(s)
    0 anonymous member(s)