Problem Solving ‘Techniques G.Arunkumar,, A.P/C.S ~ MMC
Unit
Text Processing and Pattern Searching: Text line length adjustment ~ Left and right justification of text ~
Keyword searching in text — Text line editing — Linear pattern search,
Recursive algorithms: Towers of Hanoi ~ Permutation generation,
Text line length adjustment
Aim
To verify the text line length adjustment
Problem description
Ina given set of lines the text length should be re format, So, that the text line of more than n
characters that is maximum 40 character should be displayed
The output line maximum number of words that occupy less than or n characters should be printed. No
word should extend across two lines, If suppose user give more than 40 characters then infinite loop will
occurs.
Character length starts with 1
String length function starts with 1
No words in a file should not be splitted.
Example
Flowers are beaut
Tful.
This is wrong.
Flowers are beautiful.
This is correct.
Flowers-actual is stores from 0-6 (7) elements.
Algorithm description
‘Read the line length limit and add one to it, to allow for a space.
‘Initialize the word characters counts to 0 and end of line flag to false.
* No end of line means, read the next character and store it,
* Ifcharacter is a space or a new paragraph then reset character count for new line.
Add current word length to current line length,
When it across the line length limit then move to next line.
© Write out the current word and re-init
© [fat end of input line then, set end of input line flag and move to next line.
Implementation
tHinclude
define size 40
Main()
FILE"$p;
Char a{ 100], str[50),
Ep=fopen(“sk.ee”,"r"
While( feof)
a
Fscanfifp, "%6s", &a);
empty, length;
1-BSc (CS) - Unit Il Page 1Problem Solving ‘Techniques G.Arunkumar., A.PIC.S - MMC
Empty-size-strlen(a)-1;
Iffempty> length)
t
Streat(str.a);
Streat(str,”
}
Else
f
Printf('%6s\n", str);
For(i-0;i<50;i+-+)
Sirfi]="0";
Streat(str,”
}
Lfeofp)
Printf('"96s\n", str);
}
Felose({p);
GetchQ;
}
Applications
© Text processing,
Report writing and
© File management.
Text Justification Algorithm
Purpose
The Text Justification algorithm will ensure that the output from your program is both left and right
justified when displayed in a mono-spaced font such as Courier.
+ This paragraph is an example of such justification. All the lines (except the last) of the output from
a given run of your program should have the same length, and the last line is to be no longer than
the other lines,
Overview
This pseudocode illustrates the Text Justification algorithm at a high level and how it should fit in to
the Markov Chain programming assignment as a whole. The following sections describe the steps in more
detail
build Markov Chain data structures;
while( more words to generate ) {
generate next word;
iff word is short enough to fit on current output line )
add word and trailing space(s) to the line;
1 Two spaces if it is the end of'a sentence. See below
else {
1-BSc (CS) -U Page 2Problem Solving ‘Techniques G.Arunkumar,, A.P/C.S ~ MMC
add spaces to justify the line; // details in phase 3
print the line;
clear the linked list;
add the word and trailing spaces to the line;
3
3
iff output line is not emtpy )
print output line;
Algorithm Description
© Construct a linked list that represents the current line of output.
* For each word in the output, add a node to the end of the list representing that word, then add another
node to the end to signify the amount of space between that word and the next (initially, this is one
space).
* You should also keep track of these space nodes in some type of array structure, to facilitate fast
random access.
© When adding a new word would cause the combined length of all the words and spaces in the list to
exceed the line length, stop.
+ Remove the last node of the list (remember, this is the space from the last word on the line).
© Then distribute additional spaces among the space nodes (you can choose a reference randomly from
the array you kept around and add a space to that node) until the combined length of the words and
spaces in the list is equal to the prescribed line length. (Actually, you don't want all the space to be
distributed randomly; see phase 3 below.)
‘© Traverse the list and output each word and set of spaces in order.
© Output a newline and start over. When you run out of words, output the remaining list without adding
extra space, then terminate,
Incremental Enhancement Plan
You are allowed to jump directly to Phase 3 if you wish, but the intermediate approaches may help you to get
there.
Phase 1. Simply output one word per line, Or perhaps a fixed number (12 will probably work well) of words
per line, Then you can debug the Markov Chain parts of your code before worrying about justifying the
output. (If you get this far, and your Markov Chain algorithm is correct, you should earn about 60% of the
correctness points for this assignment),
Phase 2. Don't output each word as you generate it. Instead, add it to a linked list of strings, one node for each
word. Keep track of the total width of all of the words in your list (plus the spaces that will separate them
when they are printed). When the width exceeds the output width, print all but the last word, and begin a new
linked list containing just that last word, (If you get this far, and your Markov Chain algorithm is correct, you
should earn about 80% of the correctness points for this problem)
Phase 3. Add (to your linked list of strings) nodes containing the spaces that separate the words (after you add
a word to your list, you can add the space(s) that follow it). There will normally be one space, but if the word.
1 BSc (CS) - Uni Page 3Problem Solving ‘Techniques G.Arunkumar,, A.P/C.S ~ MMC
ends with a period, exclamation point, or question mark, there should be two spaces, For example, if the text
so far is "Hello. I love you" The list will look like:
mene.” | Pf [por »
peroves *D pile
Next, create an array (or ArrayList) of N references to the "space nodes" in the list (where N+1 is the
number of words on this line). Calculate how many additional spaces (call this number M) must be added to
the line in order to obtain a justified line.
IfM<\, randomly select M different array positions, and add one space to the string stored in each of the
corresponding "space nodes"
IfM> N, add one space to each of the Nspace nodes, subtract N from M. Repeat this process until M newlength then
unten Tine to0 tong ~cannot loft and right justify)
cle
bbogin (line cam be loft and right justtiod)
‘Space :~ "; start := 1;
while Vine{start)= space) and (start <=oldtength) do
‘begin {allow for new paragraph with leading blanks)
writelspace)
end:
spaces := 0:
Unvartent: start =< position =0) and (nspaces >0) do
‘begin (ser up template according to current space count)
delta = roundinspaces / extrespaces):
if delta =0 then delta := 1;
if extraspeces >nspaces then
pibreblock = enreqpecee dt napacee
spacediock := 1;
noxt ‘= (delta +1) div 2;
invariant: after current iteration extrasoaces = number of
‘spaces still to be added to line \ spaceblock spaces to be
‘added aher (next — delta word WY =< next =< nspaces +
dona 1 delta >= 1}
while (next 0) do
begin (designate space position for curren template
se)
tempat tempat net + specbiock
{for position == start t@ odlenyth do
W ine|position|~space then
begin (wnte extra spaces # any at current location}
‘Soace :~ space +1;
for j := 1 to tamplatolispace] do
writelspace)
else
write Vine|position)};
writen
ond,
Keyword searching in text
Algorithm description:
1. Establish the word and word length wlength of the search word.
2. Initialize the match-count nmatches, set preceding character set pointer for word array i to 1.
3. While not at end-of-file do
a. While not end of line do
i. Read next character;
ii, If current text character chr matches i character in word then
1. Extend partial match i by 1,
2. If'a word pattern match then
a. Read next character then
b. Ifpreceding and following character not alphabetic then
i, Update match count nmatches
¢. Reinitialize pointer to word array i,
d. Save following character post as preceding character.
3. save current text character as preceding character for match,
4, reset word array pointer i to first position;
Page 5Problem Solving ‘echniques G.Arunkumar,, A.P/C.S ~ MMC
b, read past end-of-line
4. Read word-match count nmatches.
The implementation has been designed to handle only lower-case alphabetic characters.
Pascal implementation.
procedure wordsearch( word, wlength,nmatches);
type letters = a°)7b' Pe". ...0.72"5
var i, chr, pre, post, alphabet;
begin
alphabet = [*a’,...’2"];
pre=";
ie
while not eoftinput) do
begin
while not eoln(input) do
begin
read(chr);
if chr = word{i] then
begin
init;
if >wlength then
begin
read(post);
iffnot(pre in alphabet)) and (not(post in alphabet)) then
begin
nmatches = nmatches + ;
end
pre = post;
end
end
else
begin
pre = chr;
end
end;
readIn;
end
end
Text Line Editing
Problem:
Design and implement an algorithm that will search a line of text for a particular pattern or substring. Should
the patter be found it is to be replaced by another given pattern.
1-BSc (CS) - Unit Il Page 6Problem Solving ‘Techniques G.Arunkumar., A.PIC.S - MMC
Algorithm description:
1. Establish the textline, the search pattern, and the replacement pattern and their associated lengths i
characters.
2. Set the initial values for the position in the old text, the new text, and the search pattern,
3. While all pattern positions in the text have not been examined do
a. Ifcurrent text and pattern characters match then
i, Extend indices to next pattern/text character pair,
ii, Ifa complete match then
1. Copy new pattern into current position in edited line,
2. Move past old pattern in text,
3. Reset pointer for search pattern
b. Else
i. Copy current text character to next position in edited text,
ii, Reset search pattern pointer,
iii, Move pattern to next text position,
4. Copy the leftover characters in the original text line.
5. Retum the edited line of text.
Pascal implementatia
procedure textedit(text,newtext, pattern newpattern,newtexhlength,textlength, patlength,newpatlength);
var ijk,in;
begin
ri
Py
k-0;
while ic=textlength ~ patlength +1 do
begin
iftexr{itj-1]-pattern{j] then
begin
its
if j>patlength then
begin
for in=1 to newpatlength do
begin
kek+H;
newtext{k] = newpatternfin]
end;
patlength;
else
iit;
Page 7Problem Solving hi iques G.Arunkumar., A.PIC.S - MMC
end
end
while i0}
position := 2; match
recover{0] :~ 0; rocover{1] := 0;
{invariant: patten[1.match ~1] matches pattern (position ~ match
1.position ~1) A recoverfposition ~1] = match ~1 A
position = 0}
Position := 1; match := 1;
Wavariant: (match ~ patiength then
begin {count and recover from complete match)
matches := nmatches +1;
restart (recover, match, position)
end
end
else {recover from mismatch}
restart recover, match, position)
ond
{assert: nmatches number of times pattern found in string}
end
Towers of Hanoi
Tower of Hanoi, is a mathematical puzzle which consists of three towers (pegs) and more than one
rings is as depicted ~
These rings are of different sizes and stacked upon in an ascending order, i.e. the smaller one sits over
the larger one. There are other variations of the puzzle where the number of disks increase, but the tower
count remains the same.
Rules
The mission is to move all the disks to some another tower without violating the sequence of
arrangement, A few rules to be followed for Tower of Hanoi are —
+ Only one disk can be moved among the towers at any given time.
+ Only the "top" disk can be removed.
+ No large disk can sit over a small disk.
Following is an animated representation of solving a Tower of Hanoi puzzle with three disks
Page 10Problem Solving ‘Techniques G.Arunkumar., A.PIC.S - MMC
L
Tower of Hanoi puzzle with n disks can be solved in minimum 2°1 steps. This presentation shows
that a puzzle with 3 disks has taken 2° - 1 =7 steps.
Algorithm
To write an algorithm for Tower of Hanoi, first we need to learn how to solve this problem with lesser amount
of disks, say > 1 or 2. We mark three towers with name, source, destination and aux (only to help moving
the disks). If we have only one disk, then it can easily be moved from source to destination peg.
Ifwe have 2 disks
+ First, we move the smaller (top) disk to aux peg.
+ Then, we move the larger (bottom) disk to destination peg.
+ And finally, we move the smaller disk fiom aux to destination peg.
sn
‘Source estates
So now, we are in a position to design an algorithm for Tower of Hanoi with more than two disks. We
divide the stack of disks in two parts. The largest disk (n" disk) is in one part and all other (n-1) disks are in
the second part.
Our ultimate aim is to move disk n from source to destination and then put all other (n1) disks onto it,
We can imagine to apply the same in a recursive way for all given set of disks.
The steps to follow are ~
Step 1 = Move n-I disks from source to aux
Step 2 ~ Move n'* disk from source to dest
Step 3 ~ Move n-I disks from aux to dest
A recursive algorithm for Tower of Hanoi can be driven as follows —
START
Procedure Hanoi(disk, source, dest, aux)
IF disk == 1, THEN
‘move disk from source to dest
ELSE
Hanoidisk - 1, source, aux, dest) Step 1
move disk from source to dest —_// Step 2
Hanoi(disk ~ I, aux, dest, source) // Step 3
1-BSc (CS) - Unit Il Page 11Problem Solving lechniques G.Arunkumar,, A.P/C.S ~ MMC
ENDIF
\D Procedure
sToP
Example
#include
include
#define MAX 10
int list{ MAX] = {1,8,4,6,03,5,2,7,9};
void display(){
int i
printé{"[");
#/ navigate through all items
for(i= 0; i list[i+1) ¢
temp = list{j};
list
list{j+1] = temp;
swapped = true;
printf(" => swapped [%d, %d]\n" list) list{+1]);
} else {
printf(" -> not swapped\n");
1
}
// if no number was swapped that means
1) array is sorted now, break the loop.
ift'swapped) {
break;
}
printit"Iteration %d: "(i+1));
1-BSc (CS) - Unit Il Page 12Problem Solving lechniques G.Arunkumar,, A.P/C.S ~ MMC
display();
i
}
int main() {
print{"Input Array:
display);
printf("\n");
bubbleSort);
printf("\nOutput Array: ");
display();
Output
Input Array: [1846035279]
Items compared: [ 1, 8 ] => not swapped
Items compared: [ 8, 4] => swapped [4, 8]
Items compared: [ 8, 6 ] => swapped [6, 8]
Items compared: [ 8, 0 ] => swapped [0, 8]
Items compared: [ 8, 3 ] => swapped (3, 8]
Items compared: [ 8, 5 ] => swapped [5, 8]
Items compared: [ 8, 2 ] => swapped [2, 8]
Items compared: [ 8, 7 ] —> swapped [7, 8]
Items compared: [ 8, 9 ] => not swapped
Iteration H#: [1460352789]
Items compared: [ 1, 4] -> not swapped
Items compared: [ 4, 6 ] —> not swapped
Items compared: [ 6, 0] => swapped [0, 6]
Items compared: [ 6, 3 ] => swapped [3, 6]
Items compared: [ 6, 5 ] -> swapped [5, 6]
Items compared: [ 6, 2 ] -> swapped [2, 6]
Items compared: [ 6, 7 ] => not swapped
Items compared: [ 7, 8 ] => not swapped
Iteration 2#: [1403526789]
Items compared: [ 1,4 ] => not swapped
Items compared: [ 4, 0 ] => swapped [0, 4]
Items compared: [ 4,3 ] => swapped [3, 4]
Items compared: [ 4, 5 ] => not swapped
Items compared: [ 5, 2 ] => swapped [2, 5]
Items compared: [ 5, 6 ] => not swapped
Items compared: [ 6, 7] => not swapped
Iteration 3#: [1034256789]
Items compared: [ 1, 0] => swapped [0, 1]
Items compared: [ 1,3] => not swapped
Items compared: [ 3, 4 ] => not swapped
1-BSc (CS) - Unit Il Page 13Problem Solving ‘Techniques G.Arunkumar,, A.P/C.S ~ MMC
Items compared: [ 4, 2 ] -> swapped [2, 4]
Items compared: [ 4, 5 ] => not swapped
Items compared: [ 5, 6 ] => not swapped
Iteration 4#: [0132456789]
Items compared: [ 0, 1 ] —> not swapped
Items compared: [ 1, 3 ] => not swapped
Items compared: [ 3, 2 ] => swapped [2, 3]
Items compared: [ 3, 4 ] => not swapped
Items compared: [ 4, 5 ] => not swapped
Iteration 54: [0123456789]
Items compared: [ 0, 1 ] => not swapped
Items compared: [ 1, 2 ] => not swapped
Items compared: [ 2, 3 ] => not swapped
Items compared: [ 3, 4 ] => not swapped
Output Array: [0123456789]
Permutation Generation
Heap’s algorithm is used to generate all permutations of n objects. The idea is to generate each
permutation from the previous permutation by choosing a pair of elements to interchange, without
disturbing the other n-2 elements,
Following is the illustration of generating all the permutations. of n given numbers.
Example:
Input: 123
Output: 123
213
312
132
231
321
Algorithm:
1. The algorithm generates (n-1)! permutations of the first n-1 elements, adjoining the last element
to each of these. This will generate all of the permutations that end with the last element,
2. If nis odd, swap the first and last element and if n is even, then swap the i" element (i is the
counter starting from 0) and the last element and repeat the above algorithm till i is less than n.
3. In each iteration, the algorithm will produce all the permutations that end with the current last
element
Implementation:
J/ C++ program to print all permutations using
1 Heap's algorithm,
#include
using namespace std:
1 Prints the array
void printArr(int af], int n)
1-BSc (CS) - Unit Il Page 14Problem Solving ‘echniques G.Arunkumar,, A.P/C.S ~ MMC
{
for (int 1= 0; i