|

Java snippets of the day

Palindrome test

import java.util.Scanner;

public class PalindromeTest {
    static boolean isPalindrome(String source) {
		// Trivial case
        if (source == null)
            return false;
		// We ignore case when checking for palidrome
        String toTest = source.toLowerCase();
		// We start at the two ends of the string
        int start = 0;
        int end = toTest.length() - 1;
		// When the ends doesn't meet
        while (start < end) {
			// If they are not characters (like punctuation and spaces, we ignore them by
			// moving the pointer to the next character
            while (!Character.isLetter(toTest.charAt(start)))
                start++;
			// Similiar for the end pointer
            while (!Character.isLetter(toTest.charAt(end)))
                end--;

			// Compares the end and start pointer
            if (toTest.charAt(start) != toTest.charAt(end))
                return false;

			// Match, move to the next position
            start++;
            end--;
        }
		// The whole string has been testetd, so it's a palidrome
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isPalindrome("Dammit I'm mad"));
        System.out.println(isPalindrome("Was it a car or a cat I saw"));
        System.out.println(isPalindrome("A man, a plan, a canal - Panama!"));
        System.out.println(isPalindrome("Are we not drawn onward, we few, drawn onward to new era?"));
        System.out.println(isPalindrome("Go hang a salami; I'm a lasagna hog!"));
        System.out.println(isPalindrome("aaaaaaaaaaao"));
    }
}

String permutation

	import java.util.ArrayList;

	public class PermutationPrinter {

		// Returns the list of possible permutations
		static ArrayList getPermutations(String target) {
			ArrayList result = new ArrayList();
			if (target.length() == 1) {
				// There's only one permutation for "a", right?
				result.add(target);
			} else {
				// There's target.length() way to select a character from a string, so...
				for (int i = 0; i < target.length(); i++) {
					// We iteratively pick characters
					char theChar = target.charAt(i);
					// Take them out of the question, then find the rest 's permutation, the string is
					// smaller by one character, and it will keep getting smaller until there's only 1
					// character left
					ArrayList smaller = getPermutations(target.substring(0, i) + target.substring(i + 1));
					// For each permutation string of the smaller string, add the original character into it
					for (String s: smaller) {
						 result.add(theChar + s);
					}
				}
			}
			// Return theh result
			return result;
		}

		public static void main(String[] args) {
			ArrayList p = getPermutations("1234");
			for (String s: p) {
					System.out.println(s);
			}
		}
	}

Leave a Reply

Your email address will not be published. Required fields are marked *