How to resolve the algorithm Palindrome detection step by step in the Processing programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Palindrome detection step by step in the Processing programming language

Table of Contents

Problem Statement

A palindrome is a phrase which reads the same backward and forward. Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Palindrome detection step by step in the Processing programming language

Source code in the processing programming language

void setup(){
	println(isPalindrome(InsertPalindromeHere));
}

boolean isPalindrome(string check){
	char[] letters = new char[check.length];
	string invert = " ";
	string modCheck = " " + check;
	for(int i = 0; i < letters.length; i++){
		letters[i] = check.charAt(i);
	}
	for(int i = letters.length-1; i >= 0; i--){
		invert = invert + letters[i];
	}
	
	if(invert == modCheck){
		return true;
	} else {
		return false;
	}
}

void setup(){
    println("PalindromeDetection");

    String[] tests = {
        "abcba",
        "aa",
        "a",
        "",
        " ",
        "ab",
        "abcdba",
        "A man, a plan, a canal: Panama!",
        "Dammit, I’m Mad!",
        "Never odd or even",
        "ingirumimusnocteetconsumimurigni"
    };

    for (int i = 0; i < tests.length; i++){
        println((i + 1) + ". '" + tests[i] + "' isExactPalindrome: " + isExactPalindrome(tests[i]) + " isInexactPalindrome: " + isInexactPalindrome(tests[i]));
    }
}

/*
* Check for exact palindrome using StringBuilder and String since String in Java does not provide any reverse functionality because Strings are immutable.
*/
boolean isExactPalindrome(String s){
	StringBuilder sb = new StringBuilder(s);
	return s.equals(sb.reverse().toString());
}

/*
* Check for inexact palindrome using the check for exact palindromeabove.
*/
boolean isInexactPalindrome(String s){
    // removes all whitespaces and non-visible characters, 
    // remove anything besides alphabet characters
    // ignore case
    return isExactPalindrome(s.replaceAll("\\s+","").replaceAll("[^A-Za-z]+", "").toLowerCase());
}

  

You may also check:How to resolve the algorithm Hex words step by step in the 11l programming language
You may also check:How to resolve the algorithm S-expressions step by step in the APL programming language
You may also check:How to resolve the algorithm Call a function step by step in the BASIC programming language
You may also check:How to resolve the algorithm Conway's Game of Life step by step in the Red programming language
You may also check:How to resolve the algorithm Equilibrium index step by step in the Batch File programming language