Anagram Generator

From Java Example Source Code

Jump to: navigation, search

Contents

[edit] Overview - Anagram Generator

This is a Java example program.

[edit] Java Source Code

  • Package: example.algorithms
  • File: AnagramApp.java
  1. package example.algorithms;
  2.  
  3. import java.io.IOException;
  4.  
  5. public class AnagramApp {
  6.     static int size;
  7.  
  8.     static int count;
  9.  
  10.     static char[] charArray;
  11.  
  12.     public static void main(String[] args) throws IOException {
  13. 	String input = "Java Source and Support";
  14. 	size = input.length();
  15. 	count = 0;
  16. 	charArray = new char[size];
  17. 	for (int j = 0; j < size; j++)
  18. 	    charArray[j] = input.charAt(j);
  19. 	doAnagram(size);
  20.     }
  21.  
  22.     public static void doAnagram(int newSize) {
  23. 	int limit;
  24. 	if (newSize == 1) // if too small, return;
  25. 	    return;
  26. 	// for each position,
  27. 	for (int i = 0; i < newSize; i++) {
  28. 	    doAnagram(newSize - 1); // anagram remaining
  29. 	    if (newSize == 2) // if innermost,
  30. 		display();
  31. 	    rotate(newSize); // rotate word
  32. 	}
  33.     }
  34.  
  35.     // rotate left all chars from position to end
  36.     public static void rotate(int newSize) {
  37. 	int i;
  38. 	int position = size - newSize;
  39. 	// save first letter
  40. 	char temp = charArray[position];
  41. 	// shift others left
  42. 	for (i = position + 1; i < size; i++)
  43. 	    charArray[i - 1] = charArray[i];
  44. 	// put first on right
  45. 	charArray[i - 1] = temp;
  46.     }
  47.  
  48.     public static void display() {
  49. 	System.out.print(++count + " ");
  50. 	for (int i = 0; i < size; i++)
  51. 	    System.out.print(charArray[i]);
  52. 	System.out.println();
  53.     }
  54. }

[edit] What Result You Can Get

Run the program, you will get:

6547087 Java Source ntaupor Spd
6547088 Java Source ntaupor Sdp
6547089 Java Source ntaupor pdS
6547090 Java Source ntaupor pSd
6547091 Java Source ntaupor dSp
6547092 Java Source ntaupor dpS
6547093 Java Source ntauporSpd 
6547094 Java Source ntauporSp d
6547095 Java Source ntauporSd p
6547096 Java Source ntauporSdp 
6547097 Java Source ntauporS pd
...

[edit] Required External Libraries and/or Files for this Java Example

Need nothing.


[edit] How to Run this Java Example Program

We recommend running this Java example program with Eclipse.

For assistance in working with Eclipse, please see How to Run Java Program with Eclipse.

It's fairly easy.



[edit] Question & Answer

Any question?

Click edit and post your question or answer here.


Personal tools