-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAlphabet.java
More file actions
58 lines (51 loc) · 1.59 KB
/
Copy pathAlphabet.java
File metadata and controls
58 lines (51 loc) · 1.59 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
package enigma;
/** An alphabet of encodable characters. Provides a mapping from characters
* to and from indices into the alphabet.
* @author NikkiTrueblood
*/
class Alphabet {
/** Array to represent all the characters in the alphabet. */
private char[] _alphabet;
/** A new alphabet containing CHARS. The K-th character has index
* K (numbering from 0). No character may be duplicated. */
Alphabet(String chars) {
char[] characters = new char[chars.length()];
for (int i = 0; i < chars.length(); i++) {
chars.getChars(i, i + 1, characters, i);
}
_alphabet = characters;
}
/** A default alphabet of all upper-case characters. */
Alphabet() {
this("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
}
/** Returns the size of the alphabet. */
int size() {
return _alphabet.length;
}
/** Returns true if CH is in this alphabet. */
boolean contains(char ch) {
for (int i = 0; i < size(); i++) {
if (_alphabet[i] == ch) {
return true;
}
}
return false;
}
/** Returns character number INDEX in the alphabet, where
* 0 <= INDEX < size(). */
char toChar(int index) {
return _alphabet[index];
}
/** Returns the index of character CH which must be in
* the alphabet. This is the inverse of toChar(). */
int toInt(char ch) {
int returner = 0;
for (int i = 0; i < size(); i++) {
if (_alphabet[i] == ch) {
returner = i;
}
}
return returner;
}
}