tasks a-s

This commit is contained in:
Ingy döt Net 2013-04-10 23:57:08 -07:00
parent 47bf37c096
commit b83f433714
12433 changed files with 156208 additions and 123 deletions

View file

@ -0,0 +1,30 @@
Write at least one function/method (or whatever it is called in your preferred
language) to check if a sequence of characters (or bytes) is
a [[wp:Palindrome|palindrome]] or not. The ''function'' must return
a boolean value (or something that can be used as boolean value, like an
integer).
It is not mandatory to write also an example code that uses the ''function'',
unless its usage could be not clear (e.g. the provided recursive C solution
needs explanation on how to call the function).
It is not mandatory to handle properly encodings (see [[String length]]),
i.e. it is admissible that the function does not recognize 'salàlas' as
palindrome.
The function must not ignore spaces and punctuations. The compliance to the
aforementioned, strict or not, requirements completes the task.
'''Example'''<br>
An example of a Latin palindrome is the sentence
"''In girum imus nocte et consumimur igni''",
roughly translated as: we walk around in the night and we are burnt by the
fire (of love). To do your test with it, you must make it all the same case and
strip spaces.
'''Notes'''<br>
* It might be useful for this task to know how to [[Reversing a string|reverse a string]].
* This task's entries might also form the subjects of the task [[Test a function]].
;Cf.
* [[Semordnilap]]

View file

@ -0,0 +1,5 @@
---
category:
- Recursion
- Classic CS problems and programs
note: Text processing

View file

@ -0,0 +1,17 @@
(defun reverse-split-at-r (xs i ys)
(if (zp i)
(mv xs ys)
(reverse-split-at-r (rest xs) (1- i)
(cons (first xs) ys))))
(defun reverse-split-at (xs i)
(reverse-split-at-r xs i nil))
(defun is-palindrome (str)
(let* ((lngth (length str))
(idx (floor lngth 2)))
(mv-let (xs ys)
(reverse-split-at (coerce str 'list) idx)
(if (= (mod lngth 2) 1)
(equal (rest xs) ys)
(equal xs ys)))))

View file

@ -0,0 +1,26 @@
# Iterative #
PROC palindrome = (STRING s)BOOL:(
FOR i TO UPB s OVER 2 DO
IF s[i] /= s[UPB s-i+1] THEN GO TO return false FI
OD;
else: TRUE EXIT
return false: FALSE
);
# Recursive #
PROC palindrome r = (STRING s)BOOL:
IF LWB s >= UPB s THEN TRUE
ELIF s[LWB s] /= s[UPB s] THEN FALSE
ELSE palindrome r(s[LWB s+1:UPB s-1])
FI
;
# Test #
main:
(
STRING t = "ingirumimusnocteetconsumimurigni";
FORMAT template = $"sequence """g""" "b("is","isnt")" a palindrome"l$;
printf((template, t, palindrome(t)));
printf((template, t, palindrome r(t)))
)

View file

@ -0,0 +1,5 @@
function is_palindro(s)
{
if ( s == reverse(s) ) return 1;
return 0
}

View file

@ -0,0 +1,6 @@
function is_palindro_r(s)
{
if ( length(s) < 2 ) return 1;
if ( substr(s, 1, 1) != substr(s, length(s), 1) ) return 0;
return is_palindro_r(substr(s, 2, length(s)-2))
}

View file

@ -0,0 +1,5 @@
BEGIN {
pal = "ingirumimusnocteetconsumimurigni"
print is_palindro(pal)
print is_palindro_r(pal)
}

View file

@ -0,0 +1,6 @@
function isPalindrome(str:String):Boolean
{
for(var first:uint = 0, second:uint = str.length - 1; first < second; first++, second--)
if(str.charAt(first) != str.charAt(second)) return false;
return true;
}

View file

@ -0,0 +1,9 @@
function Palindrome (Text : String) return Boolean is
begin
for Offset in 0..Text'Length / 2 - 1 loop
if Text (Text'First + Offset) /= Text (Text'Last - Offset) then
return False;
end if;
end loop;
return True;
end Palindrome;

View file

@ -0,0 +1,7 @@
IsPalindrome( Str ){
StringLower, str, str
str := (RegexReplace(str,"\W+" ))
Loop, Parse, Str
reversedStr := A_LoopField . ReversedStr
Return ( ReversedStr = Str )
}

View file

@ -0,0 +1,52 @@
;AutoIt Version: 3.2.10.0
$mystring="In girum imus nocte, et consumimur igni"
MsgBox(0, "Palindrome", $mystring & " is palindrome: " & isPalindrome($mystring))
;output is: "In girum imus nocte, et consumimur igni is palindrome: True"
$mystring="Madam, I'm Adam."
MsgBox(0, "Palindrome", $mystring & " is palindrome: " & isPalindrome($mystring))
;output is: "Madam, I'm Adam. is palindrome: True"
$mystring="no salàlas no"
MsgBox(0, "Palindrome", $mystring & " is palindrome: " & isPalindrome($mystring))
;output is: "no salàlas no is palindrome: False"
Func isPalindrome($Str_palindrome)
$palindrome="False"
$Str_palindrome=StringLower($Str_palindrome)
$str_length = StringLen($Str_palindrome)
$new_str="" ;to rebuild string with only alphanumeric characters
For $i = 1 to $str_length
$nth_chr = StringTrimRight(StringRight($Str_palindrome, $i),$i-1)
if StringIsAlpha($nth_chr) Then
$new_str=$new_str & $nth_chr ; add in string if alphabet
EndIf
if StringIsAlNum($nth_chr) Then
$new_str=$new_str & $nth_chr ; add in string if numeric
EndIf
Next
$Str_palindrome=$new_str ;string without punctuations and spaces
$Str_reverse=reverse($Str_palindrome) ;reverse this string
;compare characters from both strings until half string is compared
For $i=1 to $str_length/2
$First=StringLeft($Str_palindrome, 1)
$Last=StringLeft($Str_reverse, 1)
If $First == $Last Then
$palindrome="True"
EndIf
Next
Return $palindrome
EndFunc
; returns reverse of input string
Func reverse($string)
$str_length = StringLen($string)
$rev_str = ""
For $i = 1 to $str_length
$rev_str = $rev_str & StringTrimRight(StringRight($string, $i), $i-1)
Next
Return $rev_str
EndFunc

View file

@ -0,0 +1,32 @@
DECLARE FUNCTION isPalindrome% (what AS STRING)
DATA "My dog has fleas", "Madam, I'm Adam.", "1 on 1", "In girum imus nocte et consumimur igni"
DIM L1 AS INTEGER, w AS STRING
FOR L1 = 1 TO 4
READ w
IF isPalindrome(w) THEN
PRINT CHR$(34); w; CHR$(34); " is a palindrome"
ELSE
PRINT CHR$(34); w; CHR$(34); " is not a palindrome"
END IF
NEXT
FUNCTION isPalindrome% (what AS STRING)
DIM whatcopy AS STRING, chk AS STRING, tmp AS STRING * 1, L0 AS INTEGER
FOR L0 = 1 TO LEN(what)
tmp = UCASE$(MID$(what, L0, 1))
SELECT CASE tmp
CASE "A" TO "Z"
whatcopy = whatcopy + tmp
chk = tmp + chk
CASE "0" TO "9"
PRINT "Numbers are cheating! ("; CHR$(34); what; CHR$(34); ")"
isPalindrome = 0
EXIT FUNCTION
END SELECT
NEXT
isPalindrome = ((whatcopy) = chk)
END FUNCTION

View file

@ -0,0 +1,27 @@
test$ = "A man, a plan, a canal: Panama!"
PRINT """" test$ """" ;
IF FNpalindrome(FNletters(test$)) THEN
PRINT " is a palindrome"
ELSE
PRINT " is not a palindrome"
ENDIF
END
DEF FNpalindrome(A$) = (A$ = FNreverse(A$))
DEF FNreverse(A$)
LOCAL B$, P%
FOR P% = LEN(A$) TO 1 STEP -1
B$ += MID$(A$,P%,1)
NEXT
= B$
DEF FNletters(A$)
LOCAL B$, C%, P%
FOR P% = 1 TO LEN(A$)
C% = ASC(MID$(A$,P%))
IF C% > 64 AND C% < 91 OR C% > 96 AND C% < 123 THEN
B$ += CHR$(C% AND &5F)
ENDIF
NEXT
= B$

View file

@ -0,0 +1,4 @@
v_$0:8p>:#v_:18p08g1-08p >:08g`!v
~->p5p ^ 0v1p80-1g80vj!-g5g80g5_0'ev
:a^80+1:g8<>8g1+:18pv>0"eslaF">:#,_@
[[relet]]-2010------>003-x -^"Tru"<

View file

@ -0,0 +1,18 @@
v> "emordnilap a toN",,,,,,,,,,,,,,,,@,,,,,,,,,,,,,,,"Is a palindrome" <
2^ < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < <
4 ^_v ^_v ^_v ^_v ^_v ^_v ^_v ^_v ^_v ^_v ^_v ^_v
8 ^_v # ^_v # ^_v # ^_v # ^_v # ^_v # ^_v # ^_v # ^_v # ^_v # ^_v # ^_v # ^_v
*^_v ^_v ^_v ^_v ^_v ^_v ^_v ^_v ^_v ^_v ^_v ^_v ^_v
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
>"dennis sinned" v
" 2
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" 0
> ^- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 9
_^ v_^ v_^ v_^ v_^ v_^ v_^ v_^ v_^ v_^ v_^ v_^ v_^ p
v_^ # v_^ # v_^ # v_^ # v_^ # v_^ # v_^ # v_^ # v_^ # v_^ # v_^ # v_^ # v_^
v_^ v_^ v_^ v_^ v_^ v_^ v_^ v_^ v_^ v_^ v_^ v_^
^< < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < <
>09g8p09g1+09pv
|: < <
^<

View file

@ -0,0 +1 @@
zz{ri}f[^^<-==

View file

@ -0,0 +1,7 @@
#include <string>
#include <algorithm>
bool is_palindrome(std::string const& s)
{
return std::equal(s.begin(), s.end(), s.rbegin());
}

View file

@ -0,0 +1,7 @@
#include <string>
#include <algorithm>
bool is_palindrome(std::string const& s)
{
return std::equal(s.begin(), s.begin()+s.length()/2, s.rbegin());
}

View file

@ -0,0 +1,12 @@
#include <string.h>
int palindrome(const char *s)
{
int i,l;
l = strlen(s);
for(i=0; i<l/2; i++)
{
if ( s[i] != s[l-i-1] ) return 0;
}
return 1;
}

View file

@ -0,0 +1,10 @@
int palindrome(const char *s)
{
const char *t; /* t is a pointer that traverses backwards from the end */
for (t = s; *t != '\0'; t++) ; t--; /* set t to point to last character */
while (s < t)
{
if ( *s++ != *t-- ) return 0;
}
return 1;
}

View file

@ -0,0 +1,6 @@
int palindrome_r(const char *s, int b, int e)
{
if ( e <= 1 ) return 1;
if ( s[b] != s[e-1] ) return 0;
return palindrome_r(s, b+1, e-1);
}

View file

@ -0,0 +1,15 @@
#include <stdio.h>
#include <string.h>
/* testing */
int main()
{
const char *t = "ingirumimusnocteetconsumimurigni";
const char *template = "sequence \"%s\" is%s palindrome\n";
int l = strlen(t);
printf(template,
t, palindrome(t) ? "" : "n't");
printf(template,
t, palindrome_r(t, 0, l) ? "" : "n't");
return 0;
}

View file

@ -0,0 +1,2 @@
(defn palindrome? [s]
(= s (apply str (reverse s))))

View file

@ -0,0 +1,7 @@
(defn palindrome? [s]
(loop [i 0
j (dec (. s length))]
(cond (>= i j) true
(= (get s i) (get s j))
(recur (inc i) (dec j))
:else false)))

View file

@ -0,0 +1,3 @@
isPalindrome = (str) ->
stripped = str.toLowerCase().replace /\W/g, ""
stripped == (stripped.split "").reverse().join ""

View file

@ -0,0 +1,7 @@
strings = [
"In girum imus nocte et consumimur igni"
"A man, a plan, a canal: Panama!"
"There is no spoon."
]
console.log "'#{str}' : #{isPalindrome str}" for str in strings

View file

@ -0,0 +1,2 @@
(defun palindrome-p (s)
(string= s (reverse s)))

View file

@ -0,0 +1,22 @@
import std.traits, std.algorithm;
bool isPalindrome1(C)(in C[] s) pure /*nothrow*/
if (isSomeChar!C) {
auto s2 = s.dup; // not nothrow
s2.reverse(); // works on Unicode too, not nothrow
return s == s2;
}
void main() {
alias isPalindrome1 pali;
assert(pali(""));
assert(pali("z"));
assert(pali("aha"));
assert(pali("sees"));
assert(!pali("oofoe"));
assert(pali("deified"));
assert(!pali("Deified"));
assert(pali("amanaplanacanalpanama"));
assert(pali("ingirumimusnocteetconsumimurigni"));
assert(pali("salàlas"));
}

View file

@ -0,0 +1,26 @@
import std.traits;
bool isPalindrome2(C)(in C[] s) pure if (isSomeChar!C) {
dchar[] dstr;
foreach (dchar c; s) // not nothrow
dstr ~= c;
for (int i; i < dstr.length / 2; i++)
if (dstr[i] != dstr[$ - i - 1])
return false;
return true;
}
void main() {
alias isPalindrome2 pali;
assert(pali(""));
assert(pali("z"));
assert(pali("aha"));
assert(pali("sees"));
assert(!pali("oofoe"));
assert(pali("deified"));
assert(!pali("Deified"));
assert(pali("amanaplanacanalpanama"));
assert(pali("ingirumimusnocteetconsumimurigni"));
assert(pali("salàlas"));
}

View file

@ -0,0 +1,39 @@
import std.stdio, core.exception, std.traits;
// assume alloca() to be pure for this program
extern(C) pure nothrow void* alloca(in size_t size);
bool isPalindrome3(C)(in C[] s) pure if (isSomeChar!C) {
auto p = cast(dchar*)alloca(s.length * 4);
if (p == null)
// no fallback heap allocation used
throw new OutOfMemoryError();
dchar[] dstr = p[0 .. s.length];
// use std.utf.stride for an even lower level version
int i = 0;
foreach (dchar c; s) { // not nothrow
dstr[i] = c;
i++;
}
dstr = dstr[0 .. i];
foreach (j; 0 .. dstr.length / 2)
if (dstr[j] != dstr[$ - j - 1])
return false;
return true;
}
void main() {
alias isPalindrome3 pali;
assert(pali(""));
assert(pali("z"));
assert(pali("aha"));
assert(pali("sees"));
assert(!pali("oofoe"));
assert(pali("deified"));
assert(!pali("Deified"));
assert(pali("amanaplanacanalpanama"));
assert(pali("ingirumimusnocteetconsumimurigni"));
assert(pali("salàlas"));
}

View file

@ -0,0 +1,23 @@
bool isPalindrome4(in string str) pure nothrow {
if (str.length == 0) return true;
immutable(char)* s = str.ptr;
immutable(char)* t = &(str[$ - 1]);
while (s < t)
if (*s++ != *t--) // ugly
return false;
return true;
}
void main() {
alias isPalindrome4 pali;
assert(pali(""));
assert(pali("z"));
assert(pali("aha"));
assert(pali("sees"));
assert(!pali("oofoe"));
assert(pali("deified"));
assert(!pali("Deified"));
assert(pali("amanaplanacanalpanama"));
assert(pali("ingirumimusnocteetconsumimurigni"));
//assert(pali("salàlas"));
}

View file

@ -0,0 +1,7 @@
uses
SysUtils, StrUtils;
function IsPalindrome(const aSrcString: string): Boolean;
begin
Result := SameText(aSrcString, ReverseString(aSrcString));
end;

View file

@ -0,0 +1,8 @@
def isPalindrome(string :String) {
def upper := string.toUpperCase()
def last := upper.size() - 1
for i => c ? (upper[last - i] != c) in upper(0, upper.size() // 2) {
return false
}
return true
}

View file

@ -0,0 +1,4 @@
open list string
isPalindrome xs = xs == reverse xs
isPalindrome <| string.toList "ingirumimusnocteetconsumimurigni"

View file

@ -0,0 +1,4 @@
reverse = foldl (flip (::)) (nil xs)
foldl f z (x::xs) = foldl f (f z x) xs
foldl _ z [] = z

View file

@ -0,0 +1,2 @@
is_palindrome(String) ->
String == lists:reverse(String).

View file

@ -0,0 +1,8 @@
function isPalindrome(sequence s)
for i = 1 to length(s)/2 do
if s[i] != s[$-i+1] then
return 0
end if
end for
return 1
end function

View file

@ -0,0 +1,2 @@
USING: kernel sequences ;
: palindrome? ( str -- ? ) dup reverse = ;

View file

@ -0,0 +1,20 @@
class Palindrome
{
// Function to test if given string is a palindrome
public static Bool isPalindrome (Str str)
{
str == str.reverse
}
// Give it a test run
public static Void main ()
{
echo (isPalindrome(""))
echo (isPalindrome("a"))
echo (isPalindrome("aa"))
echo (isPalindrome("aba"))
echo (isPalindrome("abb"))
echo (isPalindrome("salàlas"))
echo (isPalindrome("In girum imus nocte et consumimur igni".lower.replace(" ","")))
}
}

View file

@ -0,0 +1,8 @@
: first over c@ ;
: last >r 2dup + 1- c@ r> swap ;
: palindrome? ( c-addr u -- f )
begin
dup 1 <= if 2drop true exit then
first last <> if 2drop false exit then
1 /string 1-
again ;

View file

@ -0,0 +1,14 @@
program palindro
implicit none
character(len=*), parameter :: p = "ingirumimusnocteetconsumimurigni"
print *, is_palindro_r(p)
print *, is_palindro_r("anothertest")
print *, is_palindro2(p)
print *, is_palindro2("test")
print *, is_palindro(p)
print *, is_palindro("last test")
contains

View file

@ -0,0 +1,26 @@
! non-recursive
function is_palindro(t)
logical :: is_palindro
character(len=*), intent(in) :: t
integer :: i, l
l = len(t)
is_palindro = .false.
do i=1, l/2
if ( t(i:i) /= t(l-i+1:l-i+1) ) return
end do
is_palindro = .true.
end function is_palindro
! non-recursive 2
function is_palindro2(t) result(isp)
logical :: isp
character(len=*), intent(in) :: t
character(len=len(t)) :: s
integer :: i
forall(i=1:len(t)) s(len(t)-i+1:len(t)-i+1) = t(i:i)
isp = ( s == t )
end function is_palindro2

View file

@ -0,0 +1,9 @@
recursive function is_palindro_r (t) result (isp)
implicit none
character (*), intent (in) :: t
logical :: isp
isp = len (t) == 0 .or. t (: 1) == t (len (t) :) .and. is_palindro_r (t (2 : len (t) - 1))
end function is_palindro_r

View file

@ -0,0 +1 @@
end program palindro

View file

@ -0,0 +1,27 @@
ZapGremlins := function(s)
local upper, lower, c, i, n, t;
upper := "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
lower := "abcdefghijklmnopqrstuvwxyz";
t := [ ];
i := 1;
for c in s do
n := Position(upper, c);
if n <> fail then
t[i] := lower[n];
i := i + 1;
else
n := Position(lower, c);
if n <> fail then
t[i] := c;
i := i + 1;
fi;
fi;
od;
return t;
end;
IsPalindrome := function(s)
local t;
t := ZapGremlins(s);
return t = Reversed(t);
end;

View file

@ -0,0 +1,13 @@
//Setting a var from an argument passed to the script
str=argument0
//Takes out all spaces/anything that is not a letter or a number and turns uppercase letters to lowercase
str=string_lettersdigits(string_lower(string_replace(str,' ','')));
inv='';
//for loop that reverses the sequence
for (i=0;i<string_length(str);i+=1;)
{
inv=inv+string_copy(str,string_length(str)-i,1);
}
//returns true if the sequence is a palindrome else returns false
if str=inv{check=ture;}else{check=false;}
return(check);

View file

@ -0,0 +1,12 @@
package pal
func IsPal(s string) bool {
mid := len(s) / 2
last := len(s) - 1
for i := 0; i < mid; i++ {
if s[i] != s[last-i] {
return false
}
}
return true
}

View file

@ -0,0 +1,3 @@
def isPalindrome = { String s ->
s == s?.reverse()
}

View file

@ -0,0 +1,5 @@
println isPalindrome("")
println isPalindrome("a")
println isPalindrome("abcdefgfedcba")
println isPalindrome("abcdeffedcba")
println isPalindrome("abcedfgfedcb")

View file

@ -0,0 +1,4 @@
def isPalindrome = { String s ->
def n = s.size()
n < 2 || s[0..<n/2] == s[-1..(-n/2)]
}

View file

@ -0,0 +1,5 @@
def isPalindrome
isPalindrome = { String s ->
def n = s.size()
n < 2 || (s[0] == s[n-1] && isPalindrome(s[1..<(n-1)]))
}

View file

@ -0,0 +1 @@
is_palindrome x = x == reverse x

View file

@ -0,0 +1,3 @@
is_palindrome_r x | length x <= 1 = True
| head x == last x = is_palindrome_r . tail. init $ x
| otherwise = False

View file

@ -0,0 +1,17 @@
result = Palindrome( "In girum imus nocte et consumimur igni" ) ! returns 1
END
FUNCTION Palindrome(string)
CHARACTER string, CopyOfString
L = LEN(string)
ALLOCATE(CopyOfString, L)
CopyOfString = string
EDIT(Text=CopyOfString, UpperCase=L)
L = L - EDIT(Text=CopyOfString, End, Left=' ', Delete, DO=L) ! EDIT returns number of deleted spaces
DO i = 1, L/2
Palindrome = CopyOfString(i) == CopyOfString(L - i + 1)
IF( Palindrome == 0 ) RETURN
ENDDO
END

View file

@ -0,0 +1,3 @@
procedure main(arglist)
every writes(s := !arglist) do write( if palindrome(s) then " is " else " is not", " a palindrome.")
end

View file

@ -0,0 +1,3 @@
procedure palindrome(s) #: return s if s is a palindrome
return s == reverse(s)
end

View file

@ -0,0 +1,5 @@
procedure palindrome(x) #: return x if s is x palindrome
local i
every if x[i := 1 to (*x+ 1)/2] ~== x[-i] then fail
return x
end

View file

@ -0,0 +1 @@
Text isPalindrome? = method(self chars == self chars reverse)

View file

@ -0,0 +1 @@
isPalin0=: -: |.

View file

@ -0,0 +1,4 @@
isPalin0 'ABBA'
1
isPalin0 -.&' ' tolower 'In girum imus nocte et consumimur igni'
1

View file

@ -0,0 +1,6 @@
isPalin1=: 0:`($:@(}.@}:))@.({.={:)`1:@.(1>:#)
isPalin2=: monad define
if. 1>:#y do. 1 return. end.
if. ({.={:)y do. isPalin2 }.}:y else. 0 end.
)

View file

@ -0,0 +1,12 @@
foo=: foo,|.foo=:2000$a.
ts=:6!:2,7!:2 NB. time and space required to execute sentence
ts 'isPalin0 foo'
2.73778e_5 5184
ts 'isPalin1 foo'
0.0306667 6.0368e6
ts 'isPalin2 foo'
0.104391 1.37965e7
'isPalin1 foo' %&ts 'isPalin0 foo'
1599.09 1164.23
'isPalin2 foo' %&ts 'isPalin0 foo'
3967.53 2627.04

View file

@ -0,0 +1,4 @@
public static boolean pali(String testMe){
StringBuilder sb = new StringBuilder(testMe);
return testMe.equalsIgnoreCase(sb.reverse().toString());
}

View file

@ -0,0 +1,9 @@
public static boolean rPali(String testMe){
if(testMe.length()<=1){
return true;
}
if(!(testMe.charAt(0)+"").equalsIgnoreCase(testMe.charAt(testMe.length()-1)+"")){
return false;
}
return rPali(testMe.substring(1, testMe.length()-1));
}

View file

@ -0,0 +1,3 @@
public static boolean pali(String testMe){
return testMe.matches("|(?:(.)(?<=(?=^.*?(\\1\\2?)$).*))+(?<=(?=^\\2$).*)");
}

View file

@ -0,0 +1,5 @@
String.prototype.reverse = function(){ return this.split("").reverse().join(""); }
function palindrome(str) { return str == str.reverse(); }
alert(palindrome("ingirumimusnocteetconsumimurigni"));

View file

@ -0,0 +1,15 @@
String.prototype.reverse = function () {
return this.split('').reverse().join('');
};
String.prototype.isPalindrome = function () {
var s = this.toLowerCase().replace(/[^a-z]/g, '');
return (s.reverse() === s);
};
('A man, a plan, a canoe, pasta, heros, rajahs, ' +
'a coloratura, maps, snipe, percale, macaroni, ' +
'a gag, a banana bag, a tan, a tag, ' +
'a banana bag again (or a camel), a crepe, pins, ' +
'Spam, a rut, a Rolo, cash, a jar, sore hats, ' +
'a peon, a canal Panama!').isPalindrome();

View file

@ -0,0 +1,22 @@
Print isPalindrome("In girum imus nocte et consumimur igni")
Print isPalindrome("atta")
Function isPalindrome(string$)
string$ = Lower$(removeSpaces$(string$))
reverseString$ = reverseString$(string$)
If string$ = reverseString$ Then isPalindrome = 1
End Function
Function reverseString$(string$)
For i = Len(string$) To 1 Step -1
reverseString$ = reverseString$ + Mid$(string$, i, 1)
Next i
End Function
Function removeSpaces$(string$)
For i = 1 To Len(string$)
If Mid$(string$, i, 1) <> " " Then
removeSpaces$ = removeSpaces$ + Mid$(string$, i, 1)
End If
Next i
End Function

View file

@ -0,0 +1,3 @@
to palindrome? :w
output equal? :w reverse :w
end

View file

@ -0,0 +1 @@
function ispalindrome(s) return s == string.reverse(s) end

View file

@ -0,0 +1,3 @@
define(`palindrorev',`ifelse(`$1',invert(`$1'),`yes',`no')')dnl
palindrorev(`ingirumimusnocteetconsumimurigni')
palindrorev(`this is not palindrome')

View file

@ -0,0 +1,7 @@
define(`striptwo',`substr(`$1',1,eval(len(`$1')-2))')dnl
define(`cmplast',`ifelse(`striptwo(`$1')',,`yes',dnl
substr(`$1',0,1),substr(`$1',eval(len(`$1')-1),1),`yes',`no')')dnl
define(`palindro',`dnl
ifelse(eval(len(`$1')<1),1,`yes',cmplast(`$1'),`yes',`palindro(striptwo(`$1'))',`no')')dnl
palindro(`ingirumimusnocteetconsumimurigni')
palindro(`this is not palindrome')

View file

@ -0,0 +1,15 @@
function trueFalse = isPalindrome(string)
trueFalse = all(string == fliplr(string)); %See if flipping the string produces the original string
if not(trueFalse) %If not a palindrome
string = lower(string); %Lower case everything
trueFalse = all(string == fliplr(string)); %Test again
end
if not(trueFalse) %If still not a palindrome
string(isspace(string)) = []; %Strip all space characters out
trueFalse = all(string == fliplr(string)); %Test one last time
end
end

View file

@ -0,0 +1,5 @@
>> isPalindrome('In girum imus nocte et consumimur igni')
ans =
1

View file

@ -0,0 +1,6 @@
fn isPalindrome s =
(
local reversed = ""
for i in s.count to 1 by -1 do reversed += s[i]
return reversed == s
)

View file

@ -0,0 +1,15 @@
fn isPalindrome_r s =
(
if s.count <= 1 then
(
true
)
else
(
if s[1] != s[s.count] then
(
return false
)
isPalindrome_r (substring s 2 (s.count-2))
)
)

View file

@ -0,0 +1,3 @@
local p = "ingirumimusnocteetconsumimurigni"
format ("'%' is a palindrome? %\n") p (isPalindrome p)
format ("'%' is a palindrome? %\n") p (isPalindrome_r p)

View file

@ -0,0 +1,68 @@
argc IS $0
argv IS $1
LOC Data_Segment
DataSeg GREG @
LOC @+1000
ItsPalStr IS @-Data_Segment
BYTE "It's palindrome",10,0
LOC @+(8-@)&7
NoPalStr IS @-Data_Segment
BYTE "It is not palindrome",10,0
LOC #100
GREG @
% input: $255 points to where the string to be checked is
% returns $255 0 if not palindrome, not zero otherwise
% trashs: $0,$1,$2,$3
% return address $4
DetectPalindrome LOC @
ADDU $1,$255,0 % $1 = $255
2H LDB $0,$1,0 % get byte at $1
BZ $0,1F % if zero, end (length)
INCL $1,1 % $1++
JMP 2B % loop
1H SUBU $1,$1,1 % ptr last char of string
ADDU $0,DataSeg,0 % $0 to data seg.
3H CMP $3,$1,$255 % is $0 == $255?
BZ $3,4F % then jump
LDB $3,$1,0 % otherwise get the byte
STB $3,$0,0 % and copy it
INCL $0,1 % $0++
SUB $1,$1,1 % $1--
JMP 3B
4H LDB $3,$1,0
STB $3,$0,0 % copy the last byte
% now let us compare reversed string and straight string
XOR $0,$0,$0 % index
ADDU $1,DataSeg,0
6H LDB $2,$1,$0 % pick char from rev str
LDB $3,$255,$0 % pick char from straight str
BZ $3,PaliOk % finished as palindrome
CMP $2,$2,$3 % == ?
BNZ $2,5F % if not, exit
INCL $0,1 % $0++
JMP 6B
5H XOR $255,$255,$255
GO $4,$4,0 % return false
PaliOk NEG $255,0,1
GO $4,$4,0 % return true
% The Main for testing the function
% run from the command line
% $ mmix ./palindrome.mmo ingirumimusnocteetconsumimurigni
Main CMP argc,argc,2 % argc > 2?
BN argc,3F % no -> not enough arg
ADDU $1,$1,8 % argv+1
LDOU $255,$1,0 % argv[1]
GO $4,DetectPalindrome
BZ $255,2F % if not palindrome, jmp
SETL $0,ItsPalStr % pal string
ADDU $255,DataSeg,$0
JMP 1F
2H SETL $0,NoPalStr % no pal string
ADDU $255,DataSeg,$0
1H TRAP 0,Fputs,StdOut % print
3H XOR $255,$255,$255
TRAP 0,Halt,0 % exit(0)

View file

@ -0,0 +1 @@
PalindromeQ[i_String] := StringReverse[i] == i

View file

@ -0,0 +1,3 @@
palindromep(s) := block([t], t: sremove(" ", sdowncase(s)), sequal(t, sreverse(t)))$
palindromep("Sator arepo tenet opera rotas"); /* true */

View file

@ -0,0 +1,12 @@
def reverse(s:string)
StringBuilder.new(s).reverse.toString()
end
def palindrome?(s:string)
s.equals(reverse(s))
end
puts palindrome?("anna") # ==> true
puts palindrome?("Erik") # ==> false
puts palindrome?("palindroom-moordnilap") # ==> true
puts nil # ==> null

View file

@ -0,0 +1,15 @@
MODULE Palindrome;
IMPORT Text;
PROCEDURE isPalindrome(string: TEXT): BOOLEAN =
VAR len := Text.Length(string);
BEGIN
FOR i := 0 TO len DIV 2 - 1 DO
IF Text.GetChar(string, i) # Text.GetChar(string, (len - i - 1)) THEN
RETURN FALSE;
END;
END;
RETURN TRUE;
END isPalindrome;
END Palindrome.

View file

@ -0,0 +1,16 @@
using System;
using System.Console;
using Nemerle.Utility.NString; //contains methods Explode() and Implode() which convert string -> list[char] and back
module Palindrome
{
IsPalindrome( text : string) : bool
{
Implode(Explode(text).Reverse()) == text;
}
Main() : void
{
WriteLine("radar is a palindrome: {0}", IsPalindrome("radar"));
}
}

View file

@ -0,0 +1,5 @@
Clean( text : string ) : string
{
def sepchars = Explode(",.;:-?!()' ");
Concat( "", Split(text, sepchars)).ToLower()
}

View file

@ -0,0 +1,16 @@
y='In girum imus nocte et consumimur igni'
-- translation: We walk around in the night and
-- we are burnt by the fire (of love)
say
say 'string = 'y
say
pal=isPal(y)
if pal==0 then say "The string isn't palindromic."
else say 'The string is palindromic.'
method isPal(x) static
x=x.upper().space(0) /* removes all blanks (spaces). */
return x==x.reverse() /* returns 1 if exactly equal, */

View file

@ -0,0 +1,10 @@
let is_palindrome str =
let last = String.length str - 1 in
try
for i = 0 to last / 2 do
let j = last - i in
if str.[i] <> str.[j] then raise Exit
done;
(true)
with Exit ->
(false)

View file

@ -0,0 +1,14 @@
let rem_space str =
let len = String.length str in
let res = String.create len in
let rec aux i j =
if i >= len
then (String.sub res 0 j)
else match str.[i] with
| ' ' | '\n' | '\t' | '\r' ->
aux (i+1) (j)
| _ ->
res.[j] <- str.[i];
aux (i+1) (j+1)
in
aux 0 0

View file

@ -0,0 +1,20 @@
bundle Default {
class Test {
function : Main(args : String[]) ~ Nil {
IsPalindrome("aasa")->PrintLine();
IsPalindrome("acbca")->PrintLine();
IsPalindrome("xx")->PrintLine();
}
function : native : IsPalindrome(s : String) ~ Bool {
l := s->Size();
for(i := 0; i < l / 2; i += 1;) {
if(s->Get(i) <> s->Get(l - i - 1)) {
return false;
};
};
return true;
}
}
}

View file

@ -0,0 +1,14 @@
function v = palindro_r(s)
if ( length(s) == 1 )
v = true;
return;
elseif ( length(s) == 2 )
v = s(1) == s(2);
return;
endif
if ( s(1) == s(length(s)) )
v = palindro_r(s(2:length(s)-1));
else
v = false;
endif
endfunction

View file

@ -0,0 +1,3 @@
function v = palindro(s)
v = all( (s == s(length(s):-1:1)) == 1);
endfunction

View file

@ -0,0 +1,2 @@
palindro_r("ingirumimusnocteetconsumimurigni")
palindro("satorarepotenetoperarotas")

View file

@ -0,0 +1,3 @@
fun {IsPalindrome S}
{Reverse S} == S
end

View file

@ -0,0 +1,7 @@
ispal(s)={
s=Vec(s);
for(i=1,#v\2,
if(v[i]!=v[#v-i+1],return(0))
);
1
};

View file

@ -0,0 +1,5 @@
<?php
function is_palindrome($string) {
return $string == strrev($string);
}
?>

View file

@ -0,0 +1,5 @@
<?php
function is_palindrome($string) {
return preg_match('/^(?:(.)(?=.*(\1(?(2)\2|))$))*.?\2?$/', $string);
}
?>

View file

@ -0,0 +1,18 @@
is_palindrome: procedure (text) returns (bit(1));
declare text character (*) varying;
text = remove_blanks(text);
text = lowercase(text);
return (text = reverse(text));
remove_blanks: procedure (text);
declare text character (*) varying;
declare (i, j) fixed binary (31);
j = 0;
do i = 1 to length(text);
if substr(text, i, 1) = ' ' then
do; j = j + 1; substr(text, j, 1) = substr(text, i, 1); end;
end;
return (substr(text, 1, j));
end remove_blanks;
end is_palindrome;

View file

@ -0,0 +1,23 @@
program Palindro;
{ RECURSIVE }
function is_palindro_r(s : String) : Boolean;
begin
if length(s) <= 1 then
is_palindro_r := true
else begin
if s[1] = s[length(s)] then
is_palindro_r := is_palindro_r(copy(s, 2, length(s)-2))
else
is_palindro_r := false
end
end; { is_palindro_r }
{ NON RECURSIVE; see [[Reversing a string]] for "reverse" }
function is_palindro(s : String) : Boolean;
begin
if s = reverse(s) then
is_palindro := true
else
is_palindro := false
end;

View file

@ -0,0 +1,19 @@
procedure test_r(s : String; r : Boolean);
begin
write('"', s, '" is ');
if ( not r ) then
write('not ');
writeln('palindrome')
end;
var
s1, s2 : String;
begin
s1 := 'ingirumimusnocteetconsumimurigni';
s2 := 'in girum imus nocte';
test_r(s1, is_palindro_r(s1));
test_r(s2, is_palindro_r(s2));
test_r(s1, is_palindro(s1));
test_r(s2, is_palindro(s2))
end.

View file

@ -0,0 +1,16 @@
sub palin(Str $s --> Bool) {
my @chars = $s.lc.comb(/\w/);
while @chars > 1 {
return False unless @chars.shift eq @chars.pop;
}
return True;
}
my @tests =
"A man, a plan, a canal: Panama.",
"My dog has fleas",
"Madam, I'm Adam.",
"1 on 1",
"In girum imus nocte et consumimur igni";
for @tests { say (palin($_) ?? "Yes" !! "No"),"\t",$_ };

View file

@ -0,0 +1,37 @@
# Palindrome.pm
package Palindrome;
use strict;
use warnings;
use Exporter 'import';
our @EXPORT = qw(palindrome palindrome_c palindrome_r palindrome_e);
sub palindrome
{
my $s = (@_ ? shift : $_);
return $s eq reverse $s;
}
sub palindrome_c
{
my $s = (@_ ? shift : $_);
for my $i (0 .. length($s) >> 1)
{
return 0 unless substr($s, $i, 1) eq substr($s, -1 - $i, 1);
}
return 1;
}
sub palindrome_r
{
my $s = (@_ ? shift : $_);
if (length $s <= 1) { return 1; }
elsif (substr($s, 0, 1) ne substr($s, -1, 1)) { return 0; }
else { return palindrome_r(substr($s, 1, -1)); }
}
sub palindrome_e
{
(@_ ? shift : $_) =~ /^(.?|(.)(?1)\2)$/ + 0
}

Some files were not shown because too many files have changed in this diff Show more