Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,8 @@
---
category:
- Recursion
- String manipulation
- Classic CS problems and programs
- Palindromes
from: http://rosettacode.org/wiki/Palindrome_detection
note: Text processing

View file

@ -0,0 +1,22 @@
A [[wp:Palindrome|palindrome]] is a phrase which reads the same backward and forward.
{{task heading}}
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
'''''For extra credit:'''''
* Support Unicode characters.
* Write a second function (possibly as a wrapper to the first) which detects ''inexact'' palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
{{task heading|Hints}}
* 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]].
{{task heading|Related tasks}}
{{Related tasks/Word plays}}
{{Template:Strings}}
<br><br>

View file

@ -0,0 +1,2 @@
F is_palindrome(s)
R s == reversed(s)

View file

@ -0,0 +1,32 @@
* Reverse b string 25/06/2018
PALINDRO CSECT
USING PALINDRO,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) "
ST R15,8(R13) "
LR R13,R15 "
LA R8,BB @b[1]
LA R9,AA+L'AA-1 @a[n-1]
LA R6,1 i=1
LOOPI C R6,=A(L'AA) do i=1 to length(a)
BH ELOOPI leave i
MVC 0(1,R8),0(R9) substr(b,i,1)=substr(a,n-i+1,1)
LA R8,1(R8) @b=@b+1
BCTR R9,0 @a=@a-1
LA R6,1(R6) i=i+1
B LOOPI end do
ELOOPI XPRNT AA,L'AA print a
CLC BB,AA if b=a
BNE SKIP
XPRNT MSG,L'MSG then print msg
SKIP L R13,4(0,R13) epilog
LM R14,R12,12(R13) "
XR R15,R15 "
BR R14 exit
AA DC CL32'INGIRUMIMUSNOCTEETCONSUMIMURIGNI' a
BB DS CL(L'AA) b
MSG DC CL23'IT IS A TRUE PALINDROME'
YREGS
END PALINDRO

View file

@ -0,0 +1,59 @@
org 100h
jmp demo
;;; Is the $-terminated string at DE a palindrome?
;;; Returns: zero flag set if palindrome
palin: mov h,d ; Find end of string
mov l,e
mvi a,'$'
cmp m ; The empty string is a palindrome
rz
pend: inx h ; Scan until terminator found
cmp m
jnz pend
dcx h ; Move to last byte of text
ptest: ldax d ; Load char at left pointer
cmp m ; Compare to char at right pointer
rnz ; If not equal, not a palindrome
inx d ; Move pointers
dcx h
mov a,d ; Check if left pointer is before right pointer
cmp h ; High byte
jc ptest
mov a,e ; Low byte
cmp l
jc ptest
xra a ; Made it to the end - set zero flag
ret ; Return
;;; Test the routine on a few examples
demo: lxi h,words ; Word list pointer
loop: mov e,m ; Load word pointer
inx h
mov d,m
inx h
mov a,e ; Stop when zero reached
ora d
rz
push h ; Keep word list pointer
call pstr ; Print word
call palin ; Check if palindrome
lxi d,no
jnz print ; Print "no" if not a palindrome
lxi d,yes ; Print "yes" otherwise
print: call pstr
pop h
jmp loop
;;; Print strint using CP/M keeping DEHL registers
pstr: push d
push h
mvi c,9
call 5
pop h
pop d
ret
yes: db ': yes',13,10,'$'
no: db ': no',13,10,'$'
words: dw w1,w2,w3,w4,0
w1: db 'rotor$'
w2: db 'racecar$'
w3: db 'level$'
w4: db 'rosetta$'

View file

@ -0,0 +1,49 @@
cpu 8086
org 100h
section .text
jmp demo
;;; Check if the $-terminated string in [DS:SI] is a palindrome.
;;; Returns with zero flag set if so.
;;; Destroyed: AL, CX, SI, DI, ES.
palin: push es ; Set ES=DS.
pop ds
mov al,'$' ; Find end of string
mov cx,-1
mov di,si
repne scasb
dec di ; Move back to last actual character
.loop: cmp si,di
ja .ok ; If SI > DI, it is a palindrome
lodsb
dec di ; Compare left character to right character
cmp al,[di]
jne .no ; If not equal, not a palindrome
jmp .loop ; Otherwise, try next pair of characters
.ok: cmp al,al ; Set zero flag
.no: ret ; Return
;;; Try the routine on a couple of strings
demo: mov si,words
.loop: lodsw ; Grab word pointer
test ax,ax ; Zero?
jz .done ; Then we are done
mov dx,ax ; Otherwise, print word
mov ah,9
int 21h
xchg bp,si ; Keep array pointer in BP
xchg si,dx ; Put word pointer in SI
call palin ; Check if it is a palindrome
mov dx,yes ; Print 'yes'...
jz .print ; ...if it is a palindrome
mov dx,no ; Otherwise, print 'no'
.print: int 21h
xchg si,bp ; Restore array pointer
jmp .loop ; Get next word.
.done: ret
yes: db ': yes',13,10,'$' ; Yes and no
no: db ': no',13,10,'$'
words: dw .w1,.w2,.w3,.w4,.w5,0
.w1: db 'rotor$' ; Words to check
.w2: db 'racecar$'
.w3: db 'level$'
.w4: db 'redder$'
.w5: db 'rosetta$'

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;Power
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,4 @@
{} 'abc'
0
{} '⍋racecar⍋'
1

View file

@ -0,0 +1,4 @@
() 'abc'
0
() 'nun'
1

View file

@ -0,0 +1,5 @@
inexact{Aa(⎕A,⎕a) ()(⎕a,⎕a)[Aa/Aa]}
inexact 'abc,-cbA2z'
0
inexact 'abc,-cbA2'
1

View file

@ -0,0 +1,54 @@
@ Check whether the ASCII string in [r0] is a palindrome
@ Returns with zero flag set if palindrome.
palin: mov r1,r0 @ Find end of string
1: ldrb r2,[r1],#1 @ Grab character and increment pointer
tst r2,r2 @ Zero yet?
bne 1b @ If not try next byte
sub r1,r1,#2 @ Move R1 to last actual character.
2: cmp r0,r1 @ When R0 >= R1,
cmpgt r2,r2 @ make sure zero is set,
bxeq lr @ and stop (the string is a palindrome).
ldrb r2,[r1],#-1 @ Grab [R1] (end) and decrement.
ldrb r3,[r0],#1 @ Grab [R0] (begin) and increment
cmp r2,r3 @ Are they equal?
bxne lr @ If not, it's not a palindrome.
b 2b @ Otherwise, try next pair.
@ Try the function on a couple of strings
.global _start
_start: ldr r8,=words @ Word pointer
1: ldr r9,[r8],#4 @ Grab word and move pointer
tst r9,r9 @ Null?
moveq r7,#1 @ Then we're done; syscall 1 = exit
swieq #0
mov r1,r9 @ Print the word
bl print
mov r0,r9 @ Test if the word is a palindrome
bl palin
ldreq r1,=yes @ "Yes" if it is a palindrome
ldrne r1,=no @ "No" if it's not a palindrome
bl print
b 1b @ Next word
@ Print zero-terminated string [r1] using Linux syscall
print: push {r7,lr} @ Keep R7 and link register
mov r2,r1 @ Find end of string
1: ldrb r0,[r2],#1 @ Grab character and increment pointer
tst r0,r0 @ Zero yet?
bne 1b @ If not, keep going
sub r2,r2,r1 @ Calculate length of string (bytes to write)
mov r0,#1 @ Stdout = 1
mov r7,#4 @ Syscall 4 = write
swi #0 @ Make the syscall
pop {r7,lr} @ Restore R7 and link register
bx lr
@ Strings
yes: .asciz ": yes\n" @ Output yes or no
no: .asciz ": no\n"
w1: .asciz "rotor" @ Words to test
w2: .asciz "racecar"
w3: .asciz "level"
w4: .asciz "redder"
w5: .asciz "rosetta"
words: .word w1,w2,w3,w4,w5,0

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,68 @@
BYTE FUNC Palindrome(CHAR ARRAY s)
BYTE l,r
l=1 r=s(0)
WHILE l<r
DO
IF s(l)#s(r) THEN RETURN (0) FI
l==+1 r==-1
OD
RETURN (1)
BYTE FUNC IsIgnored(BYTE c)
IF (c>=' AND c<='/) OR
(c>=': AND c<='@) OR
(c>='[ AND c<='_) THEN
RETURN (1)
FI
RETURN (0)
BYTE FUNC ToUpper(BYTE c)
IF c>='a AND c<='z THEN
RETURN (c-'a+'A)
FI
RETURN (c)
BYTE FUNC InexactPalindrome(CHAR ARRAY s)
BYTE l,r,lc,rc
l=1 r=s(0)
WHILE l<r
DO
WHILE IsIgnored(s(l))
DO
l==+1
IF l>=r THEN RETURN (1) FI
OD
WHILE IsIgnored(s(r))
DO
r==-1
IF l>=r THEN RETURN (1) FI
OD
lc=ToUpper(s(l))
rc=ToUpper(s(r))
IF lc#rc THEN RETURN (0) FI
l==+1 r==-1
OD
RETURN (1)
PROC Test(CHAR ARRAY s)
IF Palindrome(s) THEN
PrintF("'%S' is a palindrome%E%E",s)
ELSEIF InexactPalindrome(s) THEN
PrintF("'%S' is an inexact palindrome%E%E",s)
ELSE
PrintF("'%S' is not a palindrome%E%E",s)
FI
RETURN
PROC Main()
Test("rotavator")
Test("13231+464+989=989+464+13231")
Test("Was it a car or a cat I saw?")
Test("Did Hannah see bees? Hannah did.")
Test("This sentence is not a palindrome.")
Test("123 456 789 897 654 321")
RETURN

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,2 @@
function Palindrome (Text : String) return Boolean is
(for all i in Text'Range => Text(i)= Text(Text'Last-i+Text'First));

View file

@ -0,0 +1,75 @@
use framework "Foundation"
------ CASE-INSENSITIVE PALINDROME, IGNORING SPACES ? ----
-- isPalindrome :: String -> Bool
on isPalindrome(s)
s = intercalate("", reverse of characters of s)
end isPalindrome
-- toSpaceFreeLower :: String -> String
on spaceFreeToLower(s)
script notSpace
on |λ|(s)
s is not space
end |λ|
end script
intercalate("", filter(notSpace, characters of toLower(s)))
end spaceFreeToLower
--------------------------- TEST -------------------------
on run
isPalindrome(spaceFreeToLower("In girum imus nocte et consumimur igni"))
--> true
end run
-------------------- GENERIC FUNCTIONS -------------------
-- filter :: (a -> Bool) -> [a] -> [a]
on filter(f, xs)
tell mReturn(f)
set lst to {}
set lng to length of xs
repeat with i from 1 to lng
set v to item i of xs
if |λ|(v, i, xs) then set end of lst to v
end repeat
return lst
end tell
end filter
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- toLower :: String -> String
on toLower(str)
set ca to current application
((ca's NSString's stringWithString:(str))'s ¬
lowercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text
end toLower

View file

@ -0,0 +1,14 @@
on isPalindrome(txt)
set txt to join(txt, "") -- In case the input's a list (array).
return (txt = join(reverse of txt's characters, ""))
end isPalindrome
on join(lst, delim)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to delim
set txt to lst as text
set AppleScript's text item delimiters to astid
return txt
end join
return isPalindrome("Radar")

View file

@ -0,0 +1,3 @@
considering case
return isPalindrome("Radar")
end considering

View file

@ -0,0 +1,3 @@
ignoring case, white space, hyphens and punctuation
return isPalindrome("Was it a 😀car, or a c😀at-I-saw?")
end ignoring

View file

@ -0,0 +1,26 @@
100 DATA"MY DOG HAS FLEAS"
110 DATA"MADAM, I'M ADAM."
120 DATA"1 ON 1"
130 DATA"IN GIRUM IMUS NOCTE ET CONSUMIMUR IGNI"
140 DATA"A man, a plan, a canal: Panama!"
150 DATA"KAYAK"
160 DATA"REDDER"
170 DATA"H"
180 DATA""
200 FOR L1 = 1 TO 9
210 READ W$ : GOSUB 300" IS PALINDROME?
220 PRINT CHR$(34); W$; CHR$(34); " IS ";
230 IF NOT PALINDROME THEN PRINT "NOT ";
240 PRINT "A PALINDROME"
250 NEXT
260 END
300 REMIS PALINDROME?
310 PA = 1
320 L = LEN(W$)
330 IF L = 0 THEN RETURN
340 FOR L0 = 1 TO L / 2 + .5
350 PA = MID$(W$, L0, 1) = MID$(W$, L - L0 + 1, 1)
360 IF PALINDROME THEN NEXT L0
370 RETURN

View file

@ -0,0 +1,5 @@
palindrome?: $[seq] -> seq = reverse seq
loop ["abba" "boom" "radar" "civic" "great"] 'wrd [
print [wrd ": palindrome?" palindrome? wrd]
]

View file

@ -0,0 +1,5 @@
IsPalindrome(Str){
Loop, Parse, Str
ReversedStr := A_LoopField . ReversedStr
return, (ReversedStr == Str)?"Exact":(RegExReplace(ReversedStr,"\W")=RegExReplace(Str,"\W"))?"Inexact":"False"
}

View file

@ -0,0 +1,31 @@
;== AutoIt Version: 3.3.8.1
Global $aString[7] = [ _
"In girum imus nocte, et consumimur igni", _ ; inexact palindrome
"Madam, I'm Adam.", _ ; inexact palindrome
"salàlas", _ ; exact palindrome
"radar", _ ; exact palindrome
"Lagerregal", _ ; exact palindrome
"Ein Neger mit Gazelle zagt im Regen nie.", _ ; inexact palindrome
"something wrong"] ; no palindrome
Global $sSpace42 = " "
For $i = 0 To 6
If _IsPalindrome($aString[$i]) Then
ConsoleWrite('"' & $aString[$i] & '"' & StringLeft($sSpace42, 42-StringLen($aString[$i])) & 'is an exact palindrome.' & @LF)
Else
If _IsPalindrome( StringRegExpReplace($aString[$i], '\W', '') ) Then
ConsoleWrite('"' & $aString[$i] & '"' & StringLeft($sSpace42, 42-StringLen($aString[$i])) & 'is an inexact palindrome.' & @LF)
Else
ConsoleWrite('"' & $aString[$i] & '"' & StringLeft($sSpace42, 42-StringLen($aString[$i])) & 'is not a palindrome.' & @LF)
EndIf
EndIf
Next
Func _IsPalindrome($_string)
Local $iLen = StringLen($_string)
For $i = 1 To Int($iLen/2)
If StringMid($_string, $i, 1) <> StringMid($_string, $iLen-($i-1), 1) Then Return False
Next
Return True
EndFunc

View file

@ -0,0 +1,7 @@
"In girum imus nocte, et consumimur igni" is an inexact palindrome.
"Madam, I'm Adam." is an inexact palindrome.
"salàlas" is an exact palindrome.
"radar" is an exact palindrome.
"Lagerregal" is an exact palindrome.
"Ein Neger mit Gazelle zagt im Regen nie." is an inexact palindrome.
"something wrong" is not a palindrome.

View file

@ -0,0 +1,80 @@
' OPTION _EXPLICIT ' For QB64. In VB-DOS remove the underscore.
DIM txt$
' Palindrome
CLS
PRINT "This is a palindrome detector program."
PRINT
INPUT "Please, type a word or phrase: ", txt$
IF IsPalindrome(txt$) THEN
PRINT "Is a palindrome."
ELSE
PRINT "Is Not a palindrome."
END IF
END
FUNCTION IsPalindrome (AText$)
' Var
DIM CleanTXT$, RvrsTXT$
CleanTXT$ = CleanText$(AText$)
RvrsTXT$ = RvrsText$(CleanTXT$)
IsPalindrome = (CleanTXT$ = RvrsTXT$)
END FUNCTION
FUNCTION CleanText$ (WhichText$)
' Var
DIM i%, j%, c$, NewText$, CpyTxt$, AddIt%, SubsTXT$
CONST False = 0, True = NOT False
SubsTXT$ = "AIOUE"
CpyTxt$ = UCASE$(WhichText$)
j% = LEN(CpyTxt$)
FOR i% = 1 TO j%
c$ = MID$(CpyTxt$, i%, 1)
' See if it is a letter. Includes Spanish letters.
SELECT CASE c$
CASE "A" TO "Z"
AddIt% = True
CASE " ", "¡", "¢", "£"
c$ = MID$(SubsTXT$, ASC(c$) - 159, 1)
AddIt% = True
CASE ""
c$ = "E"
AddIt% = True
CASE "¤"
c$ = "¥"
AddIt% = True
CASE ELSE
AddIt% = False
END SELECT
IF AddIt% THEN
NewText$ = NewText$ + c$
END IF
NEXT i%
CleanText$ = NewText$
END FUNCTION
FUNCTION RvrsText$ (WhichText$)
' Var
DIM i%, c$, NewText$, j%
j% = LEN(WhichText$)
FOR i% = 1 TO j%
NewText$ = MID$(WhichText$, i%, 1) + NewText$
NEXT i%
RvrsText$ = NewText$
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,43 @@
get "libhdr"
let palindrome(s) = valof
$( let l = s%0
for i = 1 to l/2
unless s%i = s%(l+1-i)
resultis false
resultis true
$)
let inexact(s) = valof
$( let temp = vec 1+256/BYTESPERWORD
temp%0 := 0
for i = 1 to s%0 do
$( let ch = s%i | 32
if '0'<=ch & ch<='9' | 'a'<=ch & ch<='z' then
$( temp%0 := temp%0 + 1
temp%(temp%0) := ch
$)
$)
resultis palindrome(temp)
$)
let check(s) =
palindrome(s) -> "exact palindrome",
inexact(s) -> "inexact palindrome",
"not a palindrome"
let start() be
$( let tests = vec 8
tests!0 := "rotor"
tests!1 := "racecar"
tests!2 := "RACEcar"
tests!3 := "level"
tests!4 := "redder"
tests!5 := "rosetta"
tests!6 := "A man, a plan, a canal: Panama"
tests!7 := "Egad, a base tone denotes a bad age"
tests!8 := "This is not a palindrome"
for i = 0 to 8 do
writef("'%S': %S*N", tests!i, check(tests!i))
$)

View file

@ -0,0 +1,3 @@
Pal
Pal1
Pal2 {𝕩𝕩}

View file

@ -0,0 +1,11 @@
OPTION COMPARE TRUE
INPUT "Enter your line... ", word$
IF word$ = REVERSE$(word$) THEN
PRINT "This is an exact palindrome!"
ELIF EXTRACT$(word$, "[[:punct:]]|[[:blank:]]", TRUE) = REVERSE$(EXTRACT$(word$, "[[:punct:]]|[[:blank:]]", TRUE)) THEN
PRINT "This is an inexact palindrome!"
ELSE
PRINT "Not a palindrome."
ENDIF

View file

@ -0,0 +1,15 @@
@echo off
setlocal enabledelayedexpansion
set /p string=Your string :
set count=0
:loop
if "!%string%:~%count%,1!" neq "" (
set reverse=!%string%:~%count%,1!!reverse!
set /a count+=1
goto loop
)
set palindrome=isn't
if "%string%"=="%reverse%" set palindrome=is
echo %string% %palindrome% a palindrome.
pause
exit

View file

@ -0,0 +1,19 @@
@echo off
set /p testString=Your string (all same case please) :
call :isPalindrome result %testString: =%
if %result%==1 echo %testString% is a palindrome
if %result%==0 echo %testString% isn't a palindrome
pause
goto :eof
:isPalindrome
set %1=0
set string=%2
if "%string:~2,1%"=="" (
set %1=1
goto :eof
)
if "%string:~0,1%"=="%string:~-1%" (
call :isPalindrome %1 %string:~1,-1%
)
goto :eof

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,34 @@
( ( palindrome
= a
. @(!arg:(%?a&utf$!a) ?arg !a)
& palindrome$!arg
| utf$!arg
)
& ( desep
= x
. @(!arg:?x (" "|"-"|",") ?arg)
& !x desep$!arg
| !arg
)
& "In girum imus nocte et consumimur igni"
"Я иду с мечем, судия"
"The quick brown fox"
"tregða, gón, reiði - er nóg að gert"
"人人為我,我為人人"
"가련하시다 사장집 아들딸들아 집장사 다시 하련가"
: ?candidates
& whl
' ( !candidates:%?candidate ?candidates
& out
$ ( !candidate
is
( palindrome$(low$(str$(desep$!candidate)))
& indeed
| not
)
a
palindrome
)
)
&
);

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,21 @@
using System;
class Program
{
static string Reverse(string value)
{
char[] chars = value.ToCharArray();
Array.Reverse(chars);
return new string(chars);
}
static bool IsPalindrome(string value)
{
return value == Reverse(value);
}
static void Main(string[] args)
{
Console.WriteLine(IsPalindrome("ingirumimusnocteetconsumimurigni"));
}
}

View file

@ -0,0 +1,15 @@
using System;
using System.Linq;
class Program
{
static bool IsPalindrome(string text)
{
return text == new String(text.Reverse().ToArray());
}
static void Main(string[] args)
{
Console.WriteLine(IsPalindrome("ingirumimusnocteetconsumimurigni"));
}
}

View file

@ -0,0 +1,17 @@
using System;
static class Program
{
//As an extension method (must be declared in a static class)
static bool IsPalindrome(this string sentence)
{
for (int l = 0, r = sentence.Length - 1; l < r; l++, r--)
if (sentence[l] != sentence[r]) return false;
return true;
}
static void Main(string[] args)
{
Console.WriteLine("ingirumimusnocteetconsumimurigni".IsPalindrome());
}
}

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) <= b ) 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,54 @@
% Reverse a string
str_reverse = proc (s: string) returns (string)
chs: array[char] := array[char]$predict(0, string$size(s))
for c: char in string$chars(s) do
array[char]$addl(chs, c)
end
return (string$ac2s(chs))
end str_reverse
% 'Normalize' a string (remove everything but letters and make uppercase)
normalize = proc (s: string) returns (string)
chs: array[char] := array[char]$predict(0, string$size(s))
for c: char in string$chars(s) do
if c>='a' cand c<='z' then
c := char$i2c(char$c2i(c) - 32)
end
if c>='A' cand c<='Z' then
array[char]$addh(chs, c)
end
end
return (string$ac2s(chs))
end normalize
% Check if a string is an exact palindrome
palindrome = proc (s: string) returns (bool)
return (s = str_reverse(s))
end palindrome
% Check if a string is an inexact palindrome
inexact_palindrome = proc (s: string) returns (bool)
return (palindrome(normalize(s)))
end inexact_palindrome
% Test cases
start_up = proc ()
po: stream := stream$primary_output()
tests: array[string] := array[string]$[
"rotor", "racecar", "RACEcar", "level", "rosetta",
"A man, a plan, a canal: Panama",
"Egad, a base tone denotes a bad age",
"This is not a palindrome"
]
for test: string in array[string]$elements(tests) do
stream$puts(po, "\"" || test || "\": ")
if palindrome(test) then
stream$putl(po, "exact palindrome")
elseif inexact_palindrome(test) then
stream$putl(po, "inexact palindrome")
else
stream$putl(po, "not a palindrome")
end
end
end start_up

View file

@ -0,0 +1,19 @@
identification division.
function-id. palindromic-test.
data division.
linkage section.
01 test-text pic x any length.
01 result pic x.
88 palindromic value high-value
when set to false low-value.
procedure division using test-text returning result.
set palindromic to false
if test-text equal function reverse(test-text) then
set palindromic to true
end-if
goback.
end function palindromic-test.

View file

@ -0,0 +1,2 @@
(defn palindrome? [s]
(= s (clojure.string/reverse s)))

View file

@ -0,0 +1,5 @@
(defn palindrome? [^String s]
(loop [front 0 back (dec (.length s))]
(or (>= front back)
(and (= (.charAt s front) (.charAt s back))
(recur (inc front) (dec back)))))

View file

@ -0,0 +1,12 @@
String::isPalindrome = ->
for i in [0...@length / 2] when @[i] isnt @[@length - (i + 1)]
return no
yes
String::stripped = -> @toLowerCase().replace /\W/gi, ''
console.log "'#{ str }' : #{ str.stripped().isPalindrome() }" for str in [
'In girum imus nocte et consumimur igni'
'A man, a plan, a canal: Panama!'
'There is no spoon.'
]

View file

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

View file

@ -0,0 +1,13 @@
;; Project : Palindrome detection
(defun palindrome(x)
(if (string= x (reverse x))
(format t "~d" ": palindrome" (format t x))
(format t "~d" ": not palindrome" (format t x))))
(terpri)
(setq x "radar")
(palindrome x)
(terpri)
(setq x "books")
(palindrome x)
(terpri)

View file

@ -0,0 +1,36 @@
MODULE BbtPalindrome;
IMPORT StdLog;
PROCEDURE ReverseStr(str: ARRAY OF CHAR): POINTER TO ARRAY OF CHAR;
VAR
top,middle,i: INTEGER;
c: CHAR;
rStr: POINTER TO ARRAY OF CHAR;
BEGIN
NEW(rStr,LEN(str$) + 1);
top := LEN(str$) - 1; middle := (top - 1) DIV 2;
FOR i := 0 TO middle DO
rStr[i] := str[top - i];
rStr[top - i] := str[i];
END;
IF ODD(LEN(str$)) THEN rStr[middle + 1] := str[middle + 1] END;
RETURN rStr;
END ReverseStr;
PROCEDURE IsPalindrome(str: ARRAY OF CHAR): BOOLEAN;
BEGIN
RETURN str = ReverseStr(str)$;
END IsPalindrome;
PROCEDURE Do*;
VAR
x: CHAR;
BEGIN
StdLog.String("'salalas' is palindrome?:> ");
StdLog.Bool(IsPalindrome("salalas"));StdLog.Ln;
StdLog.String("'madamimadam' is palindrome?:> ");
StdLog.Bool(IsPalindrome("madamimadam"));StdLog.Ln;
StdLog.String("'abcbda' is palindrome?:> ");
StdLog.Bool(IsPalindrome("abcbda"));StdLog.Ln;
END Do;
END BbtPalindrome.

View file

@ -0,0 +1,70 @@
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;

View file

@ -0,0 +1,3 @@
def palindrome(s)
s == s.reverse
end

View file

@ -0,0 +1,11 @@
def palindrome_imperative(s) : Bool
mid = s.size // 2
last = s.size - 1
(0...mid).each do |i|
if s[i] != s[last - i]
return false
end
end
true
end

View file

@ -0,0 +1,5 @@
def palindrome_2(s)
mid = s.size // 2
mid.times { |j| return false if s[j] != s[-1 - j] }
true
end

View file

@ -0,0 +1,6 @@
require "benchmark"
Benchmark.ips do |x|
x.report("declarative") { palindrome("hannah") }
x.report("imperative1") { palindrome_imperative("hannah")}
x.report("imperative2") { palindrome_2("hannah")}
end

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;
s2.reverse(); // works on Unicode too, not nothrow.
return s == s2;
}
void main() {
alias pali = isPalindrome1;
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 @@
bool isPalindrome(String s){
for(int i = 0; i < s.length/2;i++){
if(s[i] != s[(s.length-1) -i])
return false;
}
return true;
}

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,5 @@
func isPalindrom(str) {
str == str.Reverse()
}
print(isPalindrom("ingirumimusnocteetconsumimurigni"))

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,8 @@
;; returns #t or #f
(define (palindrome? string)
(equal? (string->list string) (reverse (string->list string))))
;; to strip spaces, use the following
;;(define (palindrome? string)
;;(let ((string (string-replace string "/\ /" "" "g")))
;;(equal? (string->list string) (reverse (string->list string)))))

View file

@ -0,0 +1,18 @@
is_palindrome (a_string: STRING): BOOLEAN
-- Is `a_string' a palindrome?
require
string_attached: a_string /= Void
local
l_index, l_count: INTEGER
do
from
Result := True
l_index := 1
l_count := a_string.count
until
l_index >= l_count - l_index + 1 or not Result
loop
Result := (Result and a_string [l_index] = a_string [l_count - l_index + 1])
l_index := l_index + 1
end
end

View file

@ -0,0 +1,4 @@
open list string
isPalindrome xs = xs == reverse xs
isPalindrome <| 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,3 @@
defmodule PalindromeDetection do
def is_palindrome(str), do: str == String.reverse(str)
end

View file

@ -0,0 +1,45 @@
import String exposing (reverse, length)
import Html exposing (Html, Attribute, text, div, input)
import Html.Attributes exposing (placeholder, value, style)
import Html.Events exposing (on, targetValue)
import Html.App exposing (beginnerProgram)
-- The following function (copied from Haskell) satisfies the
-- rosettacode task description.
is_palindrome x = x == reverse x
-- The remainder of the code demonstrates the use of the function
-- in a complete Elm program.
main = beginnerProgram { model = "" , view = view , update = update }
update newStr oldStr = newStr
view : String -> Html String
view candidate =
div []
([ input
[ placeholder "Enter a string to check."
, value candidate
, on "input" targetValue
, myStyle
]
[]
] ++
[ let testResult =
is_palindrome candidate
statement =
if testResult then "PALINDROME!" else "not a palindrome"
in div [ myStyle] [text statement]
])
myStyle : Attribute msg
myStyle =
style
[ ("width", "100%")
, ("height", "20px")
, ("padding", "5px 0 0 5px")
, ("font-size", "1em")
, ("text-align", "left")
]

View file

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

View file

@ -0,0 +1,18 @@
-module( palindrome ).
-export( [is_palindrome/1, task/0] ).
is_palindrome( String ) -> String =:= lists:reverse(String).
task() ->
display( "abcba" ),
display( "abcdef" ),
Latin = "In girum imus nocte et consumimur igni",
No_spaces_same_case = lists:append( string:tokens(string:to_lower(Latin), " ") ),
display( Latin, No_spaces_same_case ).
display( String ) -> io:fwrite( "Is ~p a palindrom? ~p~n", [String, is_palindrome(String)] ).
display( String1, String2 ) -> io:fwrite( "Is ~p a palindrom? ~p~n", [String1, is_palindrome(String2)] ).

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,14 @@
include std/sequence.e -- reverse
include std/console.e -- display
include std/text.e -- upper
include std/utils.e -- iif
IsPalindrome("abcba")
IsPalindrome("abcdef")
IsPalindrome("In girum imus nocte et consumimur igni")
procedure IsPalindrome(object s)
display("Is '[]' a palindrome? ",{s},0)
s = remove_all(' ',upper(s))
display(iif(equal(s,reverse(s)),"true","false"))
end procedure

View file

@ -0,0 +1,11 @@
ISPALINDROME
=LAMBDA(s,
LET(
lcs, FILTERP(
LAMBDA(c, " " <> c)
)(
CHARS(LOWER(s))
),
CONCAT(lcs) = CONCAT(REVERSE(lcs))
)
)

View file

@ -0,0 +1,24 @@
CHARS
=LAMBDA(s,
MID(s, ROW(INDIRECT("1:" & LEN(s))), 1)
)
FILTERP
=LAMBDA(p,
LAMBDA(xs,
FILTER(xs, p(xs))
)
)
REVERSE
=LAMBDA(xs,
LET(
n, ROWS(xs),
SORTBY(
xs,
SEQUENCE(n, 1, n, -1)
)
)
)

View file

@ -0,0 +1,3 @@
let isPalindrome (s: string) =
let arr = s.ToCharArray()
arr = Array.rev arr

View file

@ -0,0 +1,6 @@
isPalindrome "abcba"
val it : bool = true
isPalindrome ("In girum imus nocte et consumimur igni".Replace(" ", "").ToLower());;
val it : bool = true
isPalindrome "abcdef"
val it : bool = false

View file

@ -0,0 +1,27 @@
#APPTYPE CONSOLE
FUNCTION stripNonAlpha(BYVAL s AS STRING) AS STRING
DIM sTemp AS STRING = ""
DIM c AS STRING
FOR DIM i = 1 TO LEN(s)
c = MID(s, i, 1)
IF INSTR("ABCDEFGHIJKLMNOPQRSTUVWXYZ", c, 0, 1) THEN
sTemp = stemp & c
END IF
NEXT
RETURN sTemp
END FUNCTION
FUNCTION IsPalindrome(BYVAL s AS STRING) AS INTEGER
FOR DIM i = 1 TO STRLEN(s) \ 2 ' only check half of the string, as scanning from both ends
IF s{i} <> s{STRLEN - (i - 1)} THEN RETURN FALSE 'comparison is not case sensitive
NEXT
RETURN TRUE
END FUNCTION
PRINT IsPalindrome(stripNonAlpha("A Toyota"))
PRINT IsPalindrome(stripNonAlpha("Madam, I'm Adam"))
PRINT IsPalindrome(stripNonAlpha("the rain in Spain falls mainly on the rooftops"))
PAUSE

View file

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

View file

@ -0,0 +1,11 @@
/* created by Aykayayciti Earl Lamont Montgomery
April 9th, 2018 */
function is_palindrome(a)
a = strUpper(a).replace(" ", "")
b = a[-1:0]
return b == a
end
a = "mom"
> is_palindrome(a)

View file

@ -0,0 +1,5 @@
/* created by Aykayayciti Earl Lamont Montgomery
April 9th, 2018 */
b = "mom"
> strUpper(b).replace(" ", "") == strUpper(b[-1:0]) ? "Is a palindrome" : "Is not a palindrome"

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,31 @@
variable temp-addr
: valid-char? ( addr1 u -- f ) ( check for valid character )
+ dup C@ 48 58 within
over C@ 65 91 within or
swap C@ 97 123 within or ;
: >upper ( c1 -- c2 )
dup 97 123 within if 32 - then ;
: strip-input ( addr1 u -- addr2 u ) ( Strip characters, then copy stripped string to temp-addr )
pad temp-addr !
temp-addr @ rot rot 0 do dup I 2dup valid-char? if
+ C@ >upper temp-addr @ C! 1 temp-addr +!
else 2drop
then loop drop temp-addr @ pad - ;
: get-phrase ( -- addr1 u )
." Type a phrase: " here 1024 accept here swap -trailing cr ;
: position-phrase ( addr1 u -- addr1 u addr2 u addr1 addr2 u )
temp-addr @ over 2over 2over drop swap ;
: reverse-copy ( addr1 addr2 u -- addr1 addr2 )
0 do over I' 1- I - + over I + 1 cmove loop 2drop ;
: palindrome? ( -- )
get-phrase strip-input position-phrase reverse-copy compare 0= if
." << Valid >> Palindrome."
else ." << Not >> a Palindrome."
then cr ;

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,76 @@
' version 20-06-2015
' compile with: fbc -s console "filename".bas
#Ifndef TRUE ' define true and false for older freebasic versions
#Define FALSE 0
#Define TRUE Not FALSE
#EndIf
Function reverse(norm As String) As Integer
Dim As String rev
Dim As Integer i, l = Len(norm) -1
rev = norm
For i = 0 To l
rev[l-i] = norm[i]
Next
If norm = rev Then
Return TRUE
Else
Return FALSE
End If
End Function
Function cleanup(in As String, action As String = "") As String
' action = "" do nothing, [l|L] = convert to lowercase,
' [s|S] = strip spaces, [p|P] = strip punctuation.
If action = "" Then Return in
Dim As Integer i, p_, s_
Dim As String ch
action = LCase(action)
For i = 1 To Len(action)
ch = Mid(action, i, 1)
If ch = "l" Then in = LCase(in)
If ch = "p" Then
p_ = 1
ElseIf ch = "s" Then
s_ = 1
End If
Next
If p_ = 0 And s_ = 0 Then Return in
Dim As String unwanted, clean
If s_ = 1 Then unwanted = " "
If p_ = 1 Then unwanted = unwanted + "`~!@#$%^&*()-=_+[]{}\|;:',.<>/?"
For i = 1 To Len(in)
ch = Mid(in, i, 1)
If InStr(unwanted, ch) = 0 Then clean = clean + ch
Next
Return clean
End Function
' ------=< MAIN >=------
Dim As String test = "In girum imus nocte et consumimur igni"
'IIf ( cond, true, false ), true and false must be of the same type (num, string, UDT)
Print
Print " reverse(test) = "; IIf(reverse(test) = FALSE, "FALSE", "TRUE")
Print " reverse(cleanup(test,""l"")) = "; IIf(reverse(cleanup(test,"l")) = FALSE, "FALSE", "TRUE")
Print " reverse(cleanup(test,""ls"")) = "; IIf(reverse(cleanup(test,"ls")) = FALSE, "FALSE", "TRUE")
Print "reverse(cleanup(test,""PLS"")) = "; IIf(reverse(cleanup(test,"PLS")) = FALSE, "FALSE", "TRUE")
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print : Print "Hit any key to end program"
Sleep
End

View file

@ -0,0 +1 @@
isPalindrome[x] := x == reverse[x]

View file

@ -0,0 +1 @@
isPalindrome["x\u{1f638}x"]

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