How to resolve the algorithm Palindrome detection step by step in the Cowgol programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Palindrome detection step by step in the Cowgol 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 Cowgol programming language
Source code in the cowgol programming language
include "cowgol.coh";
# Check if a string is a palindrome
sub palindrome(word: [uint8]): (r: uint8) is
r := 1;
# empty string is a palindrome
if [word] == 0 then
return;
end if;
# find the end of the word
var end_ := word;
while [@next end_] != 0 loop
end_ := @next end_;
end loop;
# check if bytes match in both directions
while word < end_ loop
if [word] != [end_] then
r := 0;
return;
end if;
word := @next word;
end_ := @prev end_;
end loop;
end sub;
# Check if a string is an inexact palindrome
sub inexact(word: [uint8]): (r: uint8) is
var buf: uint8[256];
var ptr := &buf[0];
# filter non-letters and non-numbers
while [word] != 0 loop
var c := [word];
if (c >= 'a' and c <= 'z') or (c >= '0' and c <= '9') then
# copy lowercase letters and numbers over verbatim
[ptr] := c;
ptr := @next ptr;
elseif c >= 'A' and c <= 'Z' then
# make uppercase letters lowercase
[ptr] := c | 32;
ptr := @next ptr;
end if;
word := @next word;
end loop;
[ptr] := 0;
r := palindrome(&buf[0]);
end sub;
var tests: [uint8][] := {
"civic", "level", "racecar",
"A man, a plan, a canal: Panama",
"Egad, a base tone denotes a bad age",
"There is no spoon."
};
var i: @indexof tests := 0;
while i < @sizeof tests loop
print(tests[i]);
print(": ");
if palindrome(tests[i]) == 1 then
print("exact palindrome\n");
elseif inexact(tests[i]) == 1 then
print("inexact palindrome\n");
else
print("not a palindrome\n");
end if;
i := i + 1;
end loop;
You may also check:How to resolve the algorithm Quickselect algorithm step by step in the Erlang programming language
You may also check:How to resolve the algorithm Currying step by step in the Ecstasy programming language
You may also check:How to resolve the algorithm String matching step by step in the Lambdatalk programming language
You may also check:How to resolve the algorithm Colour pinstripe/Printer step by step in the FreeBASIC programming language
You may also check:How to resolve the algorithm Almost prime step by step in the V (Vlang) programming language