This is a highly miscellaneous Java snippet to find palindromes.
It will read stdin
line-by-line and spit back the palindromes it finds.
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
|
import java.io.*;
class Palindrome {
/* Return palindromes from a given list of words read from stdin */
public static void main(String[] args) {
boolean okay;
String line;
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
do {
try {
/* Read a line, and spit it back again it if is a palindrome */
line = input.readLine();
if(isPalindrome(line)) {
System.out.println(line);
}
okay = true;
} catch (Exception e) {
/* Exception will be raised after end-of-file */
okay = false;
}
} while(okay);
}
static boolean isPalindrome(String test) {
/* Return true if a string is palindromic, false otherwise */
int len = test.length();
if(len <= 1) {
/* Disallow null / single-char palindromes */
return false;
}
for(int i = 0; i < len; i++) {
/* Compare first and last, second and second-last, etc) */
if(test.charAt(i) != test.charAt(len - 1 - i)) {
/* Found different letters, stopping. */
return false;
}
}
return true;
}
}
|
On a UNIX-like system, you could feed it a dictionary to list all of the palindromes like so:
1
|
java Palindrome < /etc/dictionaries-common/words
|
On my computer that returns 57 palindromes made from ordinary words:
In alphabetical order, those are: aha bib bob
boob civic dad
deed deified did
dud eke ere
eve ewe eye
gag gig hah
huh kayak kook
level ma’am madam
MGM minim mom
mum non noon
nun oho pap
peep pep pip
poop pop pup
radar redder refer
rotor sagas sees
seres sexes shahs
sis solos stats
tat tenet tit
toot tot wow.
There are certainly more if we allow 1-letter words or case-insensitive matching (allowing all sorts of proper nouns), but I really don’t think they count.