CMPS 10 Winter 2011- Homework Assignment 3 Chapter 2 (p.76 ...
CMPS 10 Winter 2011- Homework Assignment 3 Chapter 2 (p.76 ...
CMPS 10 Winter 2011- Homework Assignment 3 Chapter 2 (p.76 ...
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
6.) code_dist = dist + k<br />
7.) if ( code_dist < 26 )<br />
8.) Codei = ‘a’ + code_dist<br />
9.) else<br />
<strong>10</strong>.) Codei = ‘a’ + code_dist – 26<br />
11.) set i to i+1<br />
12.) print Code<br />
13.) STOP<br />
Explanation: This algorithm assumes that alphabets ‘a’ –‘z’ have consecutive values<br />
assigned to them, for example, as in ASCII code. (see page 141 in Text, 5 th ed). Thus ‘b’<br />
=’a’+1, ‘c’ = ‘a’ + 2 so on. Each character has a fixed distance from ‘a’. In step 5, we<br />
compute the distance of ith letter in text from ‘a’. In step 6, we add k to this value to get<br />
distance of coded letter. If this code_dist is less then 26, we can get the character by adding it<br />
to ‘a’ as in step 8. If code_dist is greater than 26, we wrap around. A code_dist of 27 would<br />
actually be distance 1.<br />
22. Design and implement an algorithm that is given as input an integer value k 0<br />
and a list of k numbers N1, N2, … , Nk. Your algorithm should reverse the order of the<br />
numbers in the list. That is, if the original list contained:<br />
N1 = 5, N2 = 13, N3 = 8, N4 = 27, N5 = <strong>10</strong> (k = 5)<br />
Then when your algorithm has completed, the values stored in the list will be:<br />
N1 = <strong>10</strong>, N2 = 27, N3 = 8, N4 = 13, N5 = 5.<br />
Solution:<br />
There are several possible solutions to this problem. Here is one possible algorithm:<br />
Step Operation<br />
1.) Input k and N1 … Nk<br />
2.) Create and set i to 1, and create Temp<br />
3.) Repeat steps 4, 5, 6, and 7 while (i k/2) (See note in explanation)<br />
4.) Set Temp to Ni<br />
5.) Set Ni to N(k + 1 – i)<br />
6.) Set N(k + 1 – i) to Temp<br />
7.) Set i to i + 1<br />
8.) STOP<br />
Explanation: This algorithm reverses the list in place by utilizing a temporary storage<br />
variable. One could replace lines 4-6 with a line saying “Swap Ni and N(k + 1 – i)” if an<br />
appropriate “swap” algorithm were available. In step 3, we assume integer division for<br />
“k/2,” which truncates the answer. For example, if k = 5, we get 5/2 = 2. Therefore, again<br />
using k = 5, we swap N1 with N(5 + 1 – 1) (or N5) and we swap N2 with N(5 + 1 – 2) (or N4). Due<br />
to integer division, we stop at this point and leave N3 alone, which is correct. If we are using<br />
real number division, the algorithm will attempt to swap N3 with N3. This does not change