Palindrome: A palindrome is a word, phrase, number or other sequence
of units that can be read the same way in either direction (the adjus-
tment of punctuation and spaces between words is generally permitted).
Examples:
Phrases: Dammit, I'm mad!
Quotations: Able was I ere I saw Elba.
Madam, I'm Adam.
Names: Some people have names that are palindromes.Lon Nol (1913-
1985) was Prime Minister of Cambodia.
Palindromic names are very common in Finland. Examples
include Emma Lamme,Sanna Rannas, Anni Linna and Asko Oksa.
Words: civic,radar,level,rotator,rececar,reviver.
The command "Level, madam, level!", composed only of words
that are themselves palindromes, is both a character-by-
character and a word-by-word palindrome.
Numbers: 5335, 123454321
Dates: 01/02/2010 (dd/mm/yyyy format)
Method 1:
#!/bin/bash
# SCRIPT: palindrome1.sh
# USAGE: palindrome.sh or palindrome.sh STRING
# PURPOSE: Script to test if a given string is a palindrome.
#
# In this script I uses the well known method, compare first character
# with last character, up to middle of the string. One mismatch in the
# scanning leads to immediate termination of the scanning as it is
# not a palindrome. To extract character from string, I will use cut
# command with the -c option with the position number.
#
#####################################################################
# Arguments Checking #
#####################################################################
if [ $# -eq 0 ]
then
echo -n "Enter a String: "
read orgstr
else
orgstr=$*
fi
# You can also use single statement
#[ $# -eq 0 ] && (echo -n "Enter a String:"; read String) || String=$*
#####################################################################
# Variable Initialization #
#####################################################################
# Remove all punctuations from input string and convert upper case to
# lower or lower case to upper.
String="$(echo $orgstr | sed 's/[^[:alnum:]]//g' | \
tr '[:upper:]' '[:lower:]')"
Flag=0
# Find length of the string.
len=${#String}
#You can also calculate string length using bellow commands.
#len=`echo $str | wc -c`
#len=$((len-1))
#get the mid value up to which the comparison would be done.
mid=$((len/2))
#####################################################################
# Main Script Starts Here #
#####################################################################
for ((i=1;i<=mid;i++))
do
c1=`echo $String|cut -c$i` # extracts from beginning
c2=`echo $String|cut -c$len` # extracts from last
if [ $c1 != $c2 ]
then
Flag=1
break 2 # break N breaks out of N levels of loop.
fi
let len--
done
if [ $Flag -eq 0 ]
then
echo "\"$orgstr\" is a Palindrome"
else
echo "\"$orgstr\" is not a Palindrome"
fi
OUTPUT:
[root@www ]# ./palindrome1.sh Dammit, I\'m mad!
"Dammit, I'm mad!" is a Palindrome
[root@www ]# ./palindrome1.sh
Enter a String: 01/02/2010
"01/02/2010" is a Palindrome
[root@www ]# ./palindrome1.sh Hello world
"Hello world" is not a Palindrome
Method 2:
#!/bin/bash
# SCRIPT: palindrome2.sh
# USAGE: palindrome.sh or palindrome.sh STRING
# PURPOSE: Script to test if a given string is a palindrome.
#
# In this script I uses the well known method, compare first character
# with last character, up to middle of the string. One mismatch in the
# scanning leads to immediate termination of the scanning as it is
# not a palindrome. To extract a character from the string, I will use
# string manipulation operations.So you need to know how to manipulate
# strings to understand this script. I will give little bit of explan-
# tion at the end of this script.
#
#####################################################################
# Arguments Checking #
#####################################################################
[ $# -eq 0 ] && { echo -n "Enter a String: "; read orgstr ;} || \
orgstr=$*
#####################################################################
# Variable Initialization #
#####################################################################
# Remove all punctuations from input string and convert upper case to
# lower or lower case to upper.
String="$(echo $orgstr | sed 's/[^[:alnum:]]//g' | \
tr '[:upper:]' '[:lower:]')"
# Find length of the string.
len=${#String}
#get the mid value up to which the comparison would be done
mid=$(($len/2))
i=0
Flag=0
#####################################################################
# Main Script Starts Here #
#####################################################################
while [ $i -lt $mid ]
do
fchar=${String:$i:1}
let i++
bchar=${String: -$i:1}
if [ "$fchar" != $bchar ]
then
Flag=1
break 2 # break N breaks out of N levels of loop.
fi
done
if [ $Flag -eq 0 ]
then
echo "\"$orgstr\" is a Palindrome"
else
echo "\"$orgstr\" is not a Palindrome"
fi
Substring Extraction:
${string:position}
Extracts substring from $string at $position.
${string:position:length}
Extracts $length characters of substring from $string at $position
Bash numbers first character of string as '0'.
${string: 0: 1} will extracts one character from the 0th character of
the string, ie it will only get the 0th character. ${string: 2: 1}
will get the third character. Also ${string: -1: 1} will extracts the
last one character, ${string: -3:1} will get the third last character.
Note: ${string: -1:1} in this construct don't forget to give space
before -1, otherwise you will get full string.
For example
[root@localhost www]# tempvar=madam
[root@localhost www]# echo ${tempvar: -1:1}
m
[root@localhost www]# echo ${tempvar:-1:1}
madam
You can also use following command
[root@localhost www]# echo ${tempvar:(-1):1}
m
OUTPUT:
[root@www ]# ./palindrome2.sh Able was I ere I saw Elba
"Able was I ere I saw Elba" is a Palindrome
[root@www ]# ./palindrome2.sh 123454321
"123454321" is a Palindrome
[root@www ]# ./palindrome2.sh
Enter a String: 12345654321
"12345654321" is a Palindrome
[root@www ]# ./palindrome2.sh
Enter a String: 1234564321
"1234564321" is not a Palindrome
Method 3:
#!/bin/bash
# SCRIPT: palindrome3.sh
# USAGE: palindrome.sh or palindrome.sh STRING
# PURPOSE: Script to test if a given string is a palindrome.
#
# This simply uses the 'rev' utility which is used to reverse lines of
# a file. Then check if the reverse of the string is same as the
# original.rev command is part of util-linux-ng or util-linux package.
#
if `which rev &>/dev/null` # Checks rev command exist or not
then
[ $# -eq 0 ] && { echo -n "Enter a String: "; read orgstr ;} || \
orgstr=$*
String="$(echo $orgstr | sed 's/[^[:alnum:]]//g' | \
tr '[:upper:]' '[:lower:]')"
if [ "$(echo $String | rev)" = "$String" ]
then
echo "\"$orgstr\" is a palindrome"
else
echo "\"$orgstr\" is not a palindrome"
fi
else
echo "Install util-linux or util-linux-ng package"
fi
OUTPUT:
[root@www ]# ./palindrome3.sh 01/02/2010
"01/02/2010" is a palindrome
[root@www ]# ./palindrome3.sh 01/03/2010
"01/03/2010" is not a palindrome
[root@www ]# ./palindrome3.sh
Enter a String: Hello World
"Hello World" is not a palindrome
[root@www ]# ./palindrome3.sh
Enter a String: rotator
"rotator" is a palindrome
Method 4:
#!/bin/bash
# SCRIPT: palindrome4.sh
# USAGE: palindrome.sh or palindrome.sh STRING
# PURPOSE: Script to test if a given string is a palindrome.
#
# In this method we are not using 'rev' command to reverse the string.
# Using Substring Removal method or Substring Extraction method we
# will reverse the string, then compare it with oldstring.
#
#####################################################################
# Arguments Checking #
#####################################################################
[ $# -eq 0 ] && { echo -n "Enter a String: "; read orgstr ;} || \
orgstr=$*
#####################################################################
# Variable Initialization #
#####################################################################
String="$(echo $orgstr | sed 's/[^[:alnum:]]//g' | \
tr '[:upper:]' '[:lower:]')"
oldstring=$String
newstring=
#####################################################################
# Main Script Starts Here #
#####################################################################
while [ -n "$String" ]
do
temp=${String#?}
letter=${String%"$temp"}
String=$temp
newstring=${letter}${newstring}
done
if [ "$oldstring" = "$newstring" ]
then
echo "\"$orgstr\" is a palindrome"
else
echo "\"$orgstr\" is not a palindrome"
fi
# ${string#substring} is a Substing Removal operation. If you want to
# use Substring Extraction method, use bellow code.
#i=0
#while [ $i -lt ${#String} ]
#do
# letter=${String:$i:1}
# newstring=${letter}${newstring}
# let i++;
#done
#
#if [ "$String" = "$newstring" ]
#then
# echo "\"$orgstr\" is a palindrome"
#else
# echo "\"$orgstr\" is not a palindrome"
#fi
Substring Removal:
${string#substring}
Strips shortest match of $substring from front of $string.
Example:
[root@www]# tempvar=madam
[root@www]# echo ${tempvar#m}
adam
[root@www]# echo ${tempvar#ma}
dam
[root@www]# echo ${tempvar#?}
adam
${string%substring}
Strips shortest match of $substring from back of $string.
Example:
[root@www]# temp=${tempvar#?}
[root@www]# echo $temp
adam
[root@www]# echo ${tempvar%$temp}
m
OUTPUT:
[root@www ]# ./palindrome4.sh Madam, I\'m Adam
"Madam, I'm Adam" is a palindrome
[root@www ]# ./palindrome4.sh Madam I Adam
"Madam I Adam" is not a palindrome
[root@www ]# ./palindrome4.sh
Enter a String: 123454321
"123454321" is a palindrome
[root@www ]# ./palindrome4.sh
Enter a String: 1234564321
"1234564321" is not a palindrome
Saturday, July 31, 2010
Posted by venu k
14 comments | 4:18 PM
Thursday, July 29, 2010
Posted by venu k
7 comments | 9:34 AM
#!/bin/bash#!/bin/bash
# SCRIPT: insertionsort.sh
#
# LOGIC: Here, sorting takes place by inserting a particular element
# at the appropriate position, that’s why the name insertion sorting.
# In the First iteration, second element ARRAY[1] is compared with
# the first element ARRAY[0]. In the second iteration third element
# is compared with first and second element. In general, in every
# iteration an element is compared with all the elements before it.
# While comparing if it is found that the element can be inserted at
# a suitable position, then space is created for it by shifting the
# other elements one position up and inserts the desired element at
# the suitable position. This procedure is repeated for all the
# elements in the list.
#
#####################################################################
# Define Functions Here #
#####################################################################
printnumbers()
{
echo ${ARRAY[*]}
}
sortnumbers()
{
for((i=1;i<count;i++))
do
Temp=${ARRAY[i]}
j=$((i-1))
while [ $Temp -lt ${ARRAY[j]} ]
do
ARRAY[j+1]=${ARRAY[j]}
let j--
if [ $j == -1 ]
then
break
fi
done
ARRAY[j+1]=$Temp
done
}
#####################################################################
# Variable Initialization #
#####################################################################
echo "Enter numbers to be sorted"
read -a ARRAY
count=${#ARRAY[@]}
#####################################################################
# Main Script Starts Here #
#####################################################################
echo "---------------------------------------------------------------"
echo "Numbers Before Sort:"
printnumbers
sortnumbers
echo "Numbers After Sort: "
printnumbers
echo "---------------------------------------------------------------"
OUTPUT:
[root@www blog]# sh insertionsort.sh
Enter Numbers to be Sorted :
12 76 34 -34 67 9 -56 5 99 -3 17
---------------------------------------------------------------
Numbers Before Sort:
12 76 34 -34 67 9 -56 5 99 -3 17
Numbers After Sort:
-56 -34 -3 5 9 12 17 34 67 76 99
---------------------------------------------------------------
NOTE: If we complement the while condition in this program, it will
give out the sorted array in descending order.
Posted by venu k
9 comments | 9:29 AM
#!/bin/bash#!/bin/bash
# SCRIPT: selectionsort.sh
#
# LOGIC : Here, to sort the data in ascending order, the first element
# ARRAY[0] is compared with all the other elements till the end of the
# array. If it is greater than any other the elements then they are
# interchanged. So after the first iteration of the outer for loop
# smallest element will be placed at the first position. The same pro-
# cedure is repeated for the other elements too.
#
#####################################################################
# Define Functions Here #
#####################################################################
printnumbers()
{
echo ${ARRAY[*]}
}
swap()
{
temp=${ARRAY[$1]}
ARRAY[$1]=${ARRAY[$2]}
ARRAY[$2]=$temp
}
sortnumbers()
{
for ((i=0;i<count;i++))
do
min=$i
for ((j=i+1;j<count;j++))
do
if [ ${ARRAY[j]} -lt ${ARRAY[min]} ]
then
min=$j
fi
done
swap $i $min
done
}
#####################################################################
# Variable Initialization #
#####################################################################
echo "Enter Numbers to be Sorted : "
read -a ARRAY
count=${#ARRAY[@]}
#####################################################################
# Main Script Starts Here #
#####################################################################
echo "---------------------------------------------------------------"
echo "Numbers Before Sort:"
printnumbers
sortnumbers
echo "Numbers After Sort: "
printnumbers
echo "---------------------------------------------------------------"
OUTPUT:
[root@www blog]# sh selectionsort.sh
Enter Numbers to be Sorted :
34 76 -8 12 23 5 9 -2 88 41 62
---------------------------------------------------------------
Numbers Before Sort:
34 76 -8 12 23 5 9 -2 88 41 62
Numbers After Sort:
-8 -2 5 9 12 23 34 41 62 76 88
---------------------------------------------------------------
NOTE: If we complement the if condition in this program, it will give
out the sorted array in descending order.
Posted by venu k
14 comments | 9:23 AM
#!/bin/bash
# SCRIPT: bubblesort.sh
# LOGIC:
# Bubble sort is a simple sorting, it works by repeatedly stepping
# through the list to be sorted, comparing two items at a time and
# swapping them if they are in the wrong order. If you are sorting
# the data in Ascending order, at the end of the first pass, the
# "heaviest" element has move to bottom. In the second pass, the
# comparisons are made till the last but one position and now second
# largest element is placed at the last but one position. And so
# forth.
#
#####################################################################
# Define Functions Here #
#####################################################################
printnumbers()
{
echo ${ARRAY[*]}
#You can also use bellow code
#for ((i=0;i<count;i++))
#do
#echo -n " ${ARRAY[i]} "
#done
}
exchange()
{
temp=${ARRAY[$1]}
ARRAY[$1]=${ARRAY[$2]}
ARRAY[$2]=$temp
}
sortnumbers()
{
for (( last=count-1;last>0;last--))
do
for((i=0;i<last;i++))
do
j=$((i+1))
if [ ${ARRAY[i]} -gt ${ARRAY[j]} ]
then
exchange $i $j
fi
done
done
}
#####################################################################
# Variable Initialization #
#####################################################################
echo "Enter Numbers to be Sorted"
read -a ARRAY
count=${#ARRAY[@]}
#####################################################################
# Main Script Starts Here #
#####################################################################
echo "--------------------------------------------------------------"
echo "Numbers Before Sort:"
printnumbers
echo
sortnumbers
echo "Numbers After Sort: "
printnumbers
echo "--------------------------------------------------------------"
OUTPUT:
[root@www blog]# sh bubblesort.sh
Enter Numbers to be Sorted :
78 34 12 98 21 8 36 98 12 88 7 5 61 -12 62 -1 77 -46
------------------------------------------------------
Numbers Before Sort:
78 34 12 98 21 8 36 98 12 88 7 5 61 -12 62 -1 77 -46
Numbers After Sort:
-46 -12 -1 5 7 8 12 12 21 34 36 61 62 77 78 88 98 98
------------------------------------------------------
NOTE: If we complement the if condition in this program, it will give
out the sorted array in descending order.
Method2: Without Using Arrays
#!/bin/bash
# SCRIPT: bubblesort2.sh
# Without using arrays
#
#####################################################################
# Define Functions Here #
#####################################################################
printnumbers()
{
k=1
while [ $k -le $max ]
do
eval echo -n "\$x$k"
echo -n " "
let k++
done
echo
}
#####################################################################
# Variable Initialization #
#####################################################################
echo -n "Enter Total Numbers to be Sorted : "
read max
count=1
while [ $count -le $max ]
do
echo -n "Enter number $count: "
read x$count
let count++
done
#####################################################################
# Main Script Starts Here #
#####################################################################
echo -e "\nElements Before Sort"
printnumbers
for (( last=count-1;last>0;last--))
do
for ((i=1;i<last;i++))
do
j=$((i+1))
eval sval=\$x$i
eval nval=\$x$j
#The eval command evaluates the command line to complete any shell
#substitutions necessary and then executes the command. So $i and $j
#substituted first then $x1 and $x2 evaluated.
if [ $sval -gt $nval ]
then
eval x$i=$nval
eval x$j=$sval
fi
done
done
echo "Elements After Sort: "
printnumbers
OUTPUT:
[root@www shell]# sh bubblesort2.sh
Enter Total Numbers to be Sorted : 6
Enter number 1: 12
Enter number 2: -4
Enter number 3: 6
Enter number 4: -11
Enter number 5: 43
Enter number 6: 9
Elements Before Sort
12 -4 6 -11 43 9
Elements After Sort:
-11 -4 6 9 12 43
Subscribe to:
Posts (Atom)