forked from biblelamp/JavaExercises
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanagram.java
More file actions
69 lines (62 loc) · 2.28 KB
/
anagram.java
File metadata and controls
69 lines (62 loc) · 2.28 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* Book: Data Structures and Algorithms in Java, by Robert LaFore
* Chapter 6:
* anagram.java
* creates anagrams
* to compile this code: javac anagram.java
* to run this program: java AnagramApp
*/
import java.io.*;
class AnagramApp {
static int size;
static int count;
static char[] arrChar = new char[100];
public static void main(String[] args) throws IOException {
System.out.print("Enter a word: "); // get word
String input = getString();
size = input.length(); // find its size
count = 0;
for (int j=0; j<size; j++) // put it in array
arrChar[j] = input.charAt(j);
doAnagram(size); // anagram it
}
public static void doAnagram(int newSize) {
int limit;
if (newSize == 1) // if too small,
return; // go no further
for(int j=0; j<newSize; j++) { // for each position,
doAnagram(newSize-1); // anagram remaining
if (newSize==2) // if innermost,
displayWord(); // display it
rotate(newSize); // rotate word
}
}
// rotate left all chars from position to end
public static void rotate(int newSize) {
int j;
int position = size - newSize;
char temp = arrChar[position]; // save first letter
for (j=position+1; j<size; j++) // shift others left
arrChar[j-1] = arrChar[j];
arrChar[j-1] = temp; // put first on right
}
public static void displayWord() {
if (count < 99)
System.out.print(" ");
if (count < 9)
System.out.print(" ");
System.out.print(++count + " ");
for (int j=0; j<size; j++)
System.out.print( arrChar[j] );
System.out.print(" ");
System.out.flush();
if (count%6 == 0)
System.out.println("");
}
public static String getString() throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
}