2015may FE PM Question
2015may FE PM Question
2015may FE PM Question
Question Nos. Q1 Q6 Q7 , Q8
Question Selection Compulsory Select 1 of 2
Examination Time 13:30 - 16:00 (150 minutes)
Instructions:
1. Use a pencil. If you need to change an answer, erase your previous answer completely
and neatly. Wipe away any eraser debris.
2. Mark your examinee information and test answers in accordance with the instructions
below. Your answer will not be graded if you do not mark properly. Do not mark or
write on the answer sheet outside of the prescribed places.
(1) Examinee Number
Write your examinee number in the space provided, and mark the appropriate space
below each digit.
(2) Date of Birth
Write your date of birth (in numbers) exactly as it is printed on your examination
admission card, and mark the appropriate space below each digit.
(3) Question Selection
For Q7 and Q8, mark the of the question you select to answer in the Selection
Column on your answer sheet.
(4) Answers
Mark your answers as shown in the following sample question.
[Sample Question]
In which month is this spring Fundamental IT Engineer Examination conducted?
Answer group
a) April b) May c) June d) July
Since the correct answer is b) May , mark your answer sheet as follows:
[Sample Answer]
Sample b
-1-
Notations used for pseudo-language
In questions that use pseudo-language, the following notations are used unless otherwise
stated.
[Logical constants]
true, false
-2-
[Operators and their priorities]
Type of operation Operator Priority
Unary operation +, , not High
Multiplication, division , , %
Addition, subtraction +,
Relational operation >, <, , , =,
Logical product and
Logical sum or Low
Note: With division of integers, integer quotient is returned as a result.
The % operator indicates a remainder operation.
___________________________________________________________________________
In questions that use E-R diagrams, the following notations are used unless otherwise
stated.
(Relationship name)
Entity name Entity name one-to-one
(Relationship name)
Entity name Entity name one-to-many
(Relationship name)
Entity name Entity name many-to-many
___________________________________________________________________________
Company names and product names appearing in the test questions are trademarks or registered
trademarks of their respective companies. Note that the and symbols are not used within.
-3-
Questions Q1 through Q6 are all compulsory. Answer every question.
Q1. Read the following description concerning memory management, and then answer
Subquestions 1 and 2.
Many applications for mobile devices make use of data that is partially stored in a data
buffer on a storage media of the devices. Most of the data is stored in an external server
accessed through the Internet. When a user tries to access data not found in the device, the
application connects to the server to retrieve the data. The new data will replace some of
the data existing in the device due to memory constraints. An efficient implementation
reduces the number of times data is retrieved from the server. This efficiency is influenced
by factors such as the amount of a data buffer needed to store the partial data, the method
of determining the data to be replaced by the new data, and the pattern of how the user
accesses the data.
In the case of an application that accesses 6 different data blocks repeatedly by using a data
buffer that can hold 5 data blocks, fetching data from an external server is necessary all the
time.
Figure 1 illustrates how the data buffer is being replaced in this case. In Figure 1, the set
of data blocks at the top represents the data being accessed by the application, and the set
of data blocks at the bottom represents the data buffer and its corresponding data. When
the application accesses the data block [6], it is fetched from the server and replaces [1].
When the application accesses [1] after [6], it is fetched from the server and replaces [2],
and so on.
This uses a First-In-First-Out (FIFO) method. But if the data buffer can hold 6 data blocks,
then there will be only 6 fetches at the start of the application, and there is no need to fetch
data till the end of the application.
[1] [2] [3] [4] [5] [6] [1] [2] [3] [4] [5] [6] [1] [2] [3]
-4-
Subquestion 1
From the answer groups below, select the correct answer to be inserted into each blank
_______ in the following description.
Assuming that an application for a mobile device accesses 6 data blocks [1], [2], , [6] in
the following order.
[1] [2] [3] [5] [6] [1] [2] [3] [4] [6] [1] [2] [5] [6] [4] [1] [2]
The device has a data buffer that can hold 5 data blocks. When the application starts, the
data blocks [1], [2], , [5] have already been loaded into the data buffer in this sequence.
When the FIFO method is used, at the point shown above immediately after the data
block [6] is accessed, the contents of the data buffer will be ___A___ , and at the end of
the series of data block accesses, the contents of the data buffer will be ___B___ with a
total of ___C___ data block replacements for the entire duration of the application.
a) [1] [2] [3] [6] [4] b) [1] [2] [5] [6] [4]
c) [4] [1] [2] [5] [6] d) [4] [2] [3] [5] [6]
e) [5] [6] [1] [2] [4] f) [6] [1] [2] [3] [4]
Subquestion 2
From the answer group below, select the correct answer to be inserted into each blank
_______ in Table 1.
-5-
The second alternative is called the Least Recently Used (LRU) method. In the LRU
method, the system keeps track of which data block was used when while it remains in the
data buffer. The least recently used data block is the data block that is replaced when a
new data block needs space.
Table 1 shows the analysis of the two methods for different program behaviors.
Here, the data buffer can hold only 5 data blocks.
Answer group
a) For the first 5 data blocks, once they are loaded into the data buffer, no replacement
will take place during their repeated use. For the next 3 data blocks, replacement
will always take place for each succeeding data block access.
b) For the first 5 data blocks, once they are loaded into the data buffer, no replacement
will take place during their repeated use. Similarly, for the next 3 data blocks, once
they are loaded, no replacement will take place during their repeated use.
c) No data blocks out of 8 will stay in the data buffer permanently during the program
execution. All 8 data blocks will be subject to the replacement.
d) The 3 data blocks out of 8 will stay in the data buffer permanently during the
program execution. Other 5 data blocks will be subject to the replacement.
-6-
Q2. Read the following description concerning a database for student management, and then
answer Subquestions 1 and 2.
Based on the above requirements, Ms. T is designing the database for the system. Figure 1
shows an E-R diagram of the database she is now creating. This E-R diagram is
incomplete, and one-to-many relationship from ___A___ to MarksCategory is missing.
-7-
Subquestion 1
From the answer groups below, select the correct answer to be inserted into each blank
_______ in the above description and Figure 1.
Subquestion 2
From the answer group below, select the correct answer to be inserted into each blank
_______ in the following SQL statement.
At the end of a semester, the responsible lecturer outputs the list of all students with total
marks for the specified class and subject as shown below, based on the data in the database.
Total marks of each student is sum of individual marks of mark items multiplied with their
contribution percentages. For example, when the total marks of the subject CNET will be
evaluated by the mark items Lab, Test, Project, Practical exam, and Final exam with
percentages 15%, 15%, 20%, 20%, and 30% respectively, the total marks will be:
Here, ClassID and SubjectID are given by the host variables :ClassID and :SubjectID
respectively.
-8-
SELECT Student.StudentID, StudentName,
_____D_____ AS TotalMarks
FROM Class, Student, Marks, MarksCategory
WHERE Class.ClassID = :ClassID
AND Marks.SubjectID = :SubjectID
AND Class.ClassID = Student.ClassID
AND _____E_____
GROUP BY _____F_____
Answer group
a) AVG(Marks * Percentage)
b) Student.StudentID = Marks.StudentID
AND Marks.SubjectID = MarksCategory.SubjectID
c) Student.StudentID = Marks.StudentID
AND Marks.SubjectID = MarksCategory.SubjectID
AND Marks.MarksID = MarksCategory.MarksID
d) Student.StudentID, StudentName
e) StudentID
f) StudentID, StudentName
g) SUM(Marks * Percentage) / 100
-9-
Q3. Read the following description concerning network trouble-shooting, and then answer
Subquestions 1 and 2.
Company U has setup its IP network which mainly provides Intranet application services,
network-based office automation, and the Internet access services to its employees. The
network can be accessed via wired Ethernet connections within the company covering two
physical rooms. In the network, Internet access router and 3 Layer-2 switches (SW1, SW2
and SW3) are installed. Figure 1 shows the configuration of the network in Company U.
- 10 -
In Company U, Mr. M has a responsibility to take care of any technical problems relevant
to the network services. Based on his 3-year experiences, he has developed a procedure
for network trouble-shooting which can cover 90% of daily network problems. The
procedure uses bottom-up approach to identify the causes of the problems according with
OSI reference model as shown in Table 1.
Subquestion 1
From the answer group below, select the correct answer to be inserted into each blank
_______ in the following description.
One day, an organization change was performed. A large number of employees changed
their workplaces from room 1 to room 2, or from room 2 to room 1. After the change,
some employees made complaints about the network connection. When being informed
about the problems, Mr. M took the first step to determine whether the problems can be
categorized as Layer 1 or 2 problems or not, by checking the information in the Layer-2
switches used by those employees.
Table 2 shows the list of users who could not use the network, and Table 3 shows the
snapshot of the switch usage data taken by Mr. M.
- 11 -
Judging from Table 2 and Table 3, Mr. M found out that ___A___ had cabling or switch
port problems. He solved these problems by taking the steps such as checking the cable
plugging status, replacing the network cable, and changing the plugging switch port.
Also, Mr. M found out that ___B___ had MAC configuration problem. He solved this
problem by changing the MAC filter setting.
Answer group
a) User A, User B and User E b) User A and User C
c) User A and User D d) User C
e) User C and User D f) User D
Subquestion 2
From the answer groups below, select the correct answer to be inserted into each blank
_______ in the following description.
Mr. M was informed that User Fs PC could not send IP packets to both Intranet and the
Internet. By checking the IP address configuration in Table 4 and the IP routing table in
Table 5, Mr. M found out that this was a Layer 3 problem concerning the IP routing table.
Accordingly, he added the missing routing record _____C_____ to the IP routing table
in Table 5, and then User Fs PC was able to access both Intranet and the Internet.
Here, the IP addresses of interfaces R0, R1, R2 and R3 at Internet access router in Figure 1
are configured as 10.10.100.254, 10.10.1.254, 10.10.2.254 and 202.170.10.1, respectively.
After clearing Layer 1-3 problems, Mr. M set about solving the remaining problem related
to Web site accesses from a Web browser. In order to identify the cause, he tried to access
the Web site http://www.itpec.org, whose IP address is 64.22.66.88, from the user PCs
Web browser. As the test result showed that _____D_____ , he was confident that the
cause of the problem was DNS misconfiguration. Then he changed the related settings,
and the problem was solved.
- 12 -
Answer group for C
Destination Netmask Gateway
a) 0.0.0.0 0.0.0.0 10.10.1.254
b) 0.0.0.0 0.0.0.0 10.10.2.254
c) 0.0.0.0 0.0.0.0 202.170.10.1
d) 10.0.0.0 255.0.0.0 10.10.1.254
e) 10.10.0.0 255.255.0.0 10.10.2.254
f) 10.10.2.0 255.255.255.0 202.170.10.1
- 13 -
Q4. Read the following description concerning Web site security, and then answer
Subquestions 1 through 3.
A mid-sized company has developed a Web application for online sales reporting system to
enable its sales force to process sales data from remote sites. The application transfers
certain secured sales data through the Internet, and that is a big concern for the company.
Therefore, the company has established an SSL (Secure Sockets Layer) enabled Web site
for this application.
Processing information securely through the Internet means that the information need to be
transmitted between the sender and the receiver in a manner that makes it difficult for other
people to intercept and read. SSL takes care of this, and it works through a combination of
programs and encryption/decryption routines that exist on both the application on the Web
site and the browser program on the user computer.
Subquestion 1
From the answer group below, select the correct answer to be inserted into each blank
_______ in Figure 1.
In HTTPS communication, the handshake is the most complicated phase in the process.
The handshake synchronizes the client and the server up with the encryption methods and
keys that will be used for the subsequent communication.
The HTTPS handshake consists of multiple steps as shown in Figure 1.
(2) _____A_____ .
- 14 -
Answer group
a) Browser sends a copy of the SSL certificate to the server
b) Browser verifies the certificate and sends an acknowledgment message to the server
c) Server sends a copy of the SSL certificate to the browser
d) Server sends a digitally signed acknowledgement to the browser
Subquestion 2
From the answer group below, select the correct answer to be inserted into each blank
_______ in Figure 2.
The HTTPS protocol has several commands such as GET, POST, PUT and DELETE. The
application uses POST command to transfer secured sales data from remote sites. The
software developer wanted to test if SSL is properly configured or not, so he used a
network monitoring tool and made a POST request to the server https://www.example.com
(IP address: 93.184.216.119) from his PC (IP address: 192.168.1.103).
In the monitoring tool, he found a Server Hello packet header as shown in Figure 2.
Here, the port number for https service is 443.
Frame 43: 1414 bytes on wire (11312 bits), 1414 bytes captured (11312 bits) on interface 0
Ethernet II, Src: Tp-LinkT_d0:d2:44 (74:ea:3a:d0:d2:44), Dst: Azurewav_e7:10:41 (48:5d:60:e7:10:41)
Internet Protocol Version 4, Src: _____D_____ , Dst: _____E_____
Transmission Control Protocol, Src Port: https (443), Dst Port: 3par-evts (5781), Seq: 1, Ack: 230, Len: 13
Source port: https (443)
Destination port: 3par-evts (5781)
[Stream index: 6]
Sequence number: 1 (relative sequence number)
[Next sequence number: 1361 (relative sequence number)]
Acknowledgment number: 230 (relative ack number)
Header length: 20 bytes
Figure 2. Server Hello packet header
Answer group
a) 93.184.216.119
b) 192.168.1.103
- 15 -
Subquestion 3
From the answer group below, select the correct answer to be inserted into each blank
_______ in the following description.
Once SSL was configured properly and tested successfully as well, the software developer
started a browser on his PC and tried to browse the Web pages. He found that the system
was working smoothly with non-secured Web pages. When he tried to browse a secured
page at https://www.example.com/order, he got the security message as shown in Figure 3.
Source code
<!DOCTYPE html>
<html>
<head>
<title>Secured Page</title>
<link rel="stylesheet" type="text/css"
(1)
href="http://www.example.com/themes/main.css">
<link rel="stylesheet" type="text/css"
(2)
href="http://www.example.com/themes/header.css">
<script type="text/javascript"
(3)
src="https://www.example.com/scripts/jquery.js"></script>
</head>
<body>
<h1>Order Form</h1>
<div>
(4) <img src="http://www.example.com/images/shirt.jpg">
<h4>Polo T-Shitr</h4>
</div>
<form action="/order/create" method="post"> Quantity:
<input type="text" name="quantity" value="1">
<input type="submit" value="Buy">
</form>
</body>
</html>
- 16 -
When the software developer opened the source file, he found the HTML (HyperText
Markup Language) source code of the requested Web page, as shown in Figure 4. HTML
is used most commonly for publishing Web pages.
In HTML, the contents are encoded using <tags> for annotating and formatting. Different
tags are used for different purposes. A few of them are used to mention external resources
such as images, link and Java scripts.
The tag <link rel="" > is used for making a relational link to an external resource
of type style sheets.
The tag <script src="" > is used for embedding Java script files.
The tag <img src="" > is used for embedding images to the page.
Here, rel="" and src="" contain path information for a physical file. The path can
be either an absolute (full) path or a relative path.
In the HTML source code in Figure 4, four tags (marked as (1), (2), (3) and (4) with )
refer to the external resources. Out of these tags, the tags that caused the security message
as shown in Figure 3 were _____F_____ .
Answer group
a) (1), (2) and (3) b) (1), (2), (3) and (4)
c) (1), (2) and (4) d) (1), (3) and (4)
- 17 -
Q5. Read the following description concerning program development and testing, and then
answer Subquestion.
Ministry of Labor (MOL) maintains a statistic file that contains the information about
population and employment status by state.
A staff of MOL creates a program which reads the statistic file and outputs a statistic report.
[Program description]
(1) Each record of the statistic file has 4 fields. Those are, from left to right, the name of
the state, population, adult population, employed and unemployed. The following is
an example of the contents of the statistic file:
(2) For each record, the program calculates and outputs the labor force rate and
unemployment rate, by using the following formulas:
(3) When all the records are processed, the program outputs the total of population, adult
population, employed and unemployed, and the nationwide values of labor force rate
and unemployment rate. After that, the program outputs the highest unemployment
rate with the name of that state, and the lowest unemployment rate with the name of
that state.
(4) The following is an example of the statistic report:
- 18 -
[Program]
character type: State, StateHigh "????", StateLow "????"
integer type: Pop, AdultPop, Emp, Unemp
integer type: TotalPop 0, TotalAdultPop 0,
TotalEmp 0, TotalUnemp 0
float type: LaborRate, UnempRate
X float type: UnempRateHigh 0.0, UnempRateLow 100.0
Note: The function GetRecord(v1, v2, ) reads the next record from the statistic file,
and stores the values into variables v1, v2, .
The function Put(p1, p2, ) prints variables/constants p1, p2, in one line.
- 19 -
Subquestion
From the answer groups below, select the correct answer to be inserted into each blank
_______ in the following description.
Note that the shaded parts _______ are not shown.
The program development is now in test phase, and testing is performed by using various
test cases. Four test cases and their test results are shown below:
[Test case 1]
This is the case where two states have the same unemployment rate for both the highest
and lowest rates. In this case, the program outputs the following report.
[Test case 2]
This is the particular case where all the states have 0% unemployment rate. In this case,
expected output cannot be obtained. According to the program logic, the states shown on
the last two lines are as follows:
- 20 -
[Test case 3]
The problem in test case 2 can be resolved by changing the operator > to on line Y ,
and changing the operator < to on line Z .
After this change, another particular case where all the states have 100% unemployment
rate is tested. The problem is resolved, and the program outputs the following report.
[Test case 4]
After the change mentioned in test case 3, test case 1 is tested again. This time, because
the program logic is changed, the program outputs the following report.
Incidentally, the problem mentioned above can be resolved in a different way by replacing
the initial values on line X by, for example, the following values:
- 21 -
Q6. Read the following description of a heap sort program and the program itself, and then
answer Subquestions 1 through 3.
Heap is a kind of tree-based data structure. A heap can be defined as a binary tree, in
which for each node, the values of its children are less than or equal to the node value (this
is called max heap) or greater than or equal to the node value (min heap).
In a max heap, for each node except the root node, the value of the node is less than or
equal to the value of its parent. Hence, in a max heap, the root contains the maximum
value.
[Program Description]
(1) The program HeapSort sorts a given array A[] with n elements by adopting the heap
sort algorithm. Heap sort is a comparison-based sorting algorithm. Figure 1 shows an
example of a max heap and its array representation. The node index i is associated
with A[i]. Here, the index of array A[] starts at 1.
1
7 Number of elements n : 6
2 3
6 4 (index) 1 2 3 4 5 6
4 5 6 Values in A[]: 7 6 4 2 5 3
2 5 3
Figure 1. Example of a max heap and its array representation (heap size = 6)
(2) For any arbitrary node index i, the index of its left child is 2 i, the index of its right
child is 2 i + 1, and the index of its parent is (integer quotient of) i 2.
(3) The program BuildHeap builds a max heap on the input array A[].
(4) Sorting operation proceeds as follows:
(i) Build the max heap with n elements A[1], A[2], , A[n]. Then, the maximum
value among them is obtained in the root A[1]. So, exchange the value in A[1]
with the value in A[n]. Thus, the maximum value is obtained in A[n].
(ii) Discard the sorted element A[n] from the heap. In the heap with n-1 elements,
any parent node except the root node keeps the heap property, but the new root
node may violate the heap property as it has been exchanged with the last node.
(iii) Build the max heap with n-1 elements A[1], A[2], , A[n-1]. Then, the
maximum value among them is obtained in A[1]. So, exchange the value in A[1]
with the value in A[n-1]. Thus, the next-maximum value is obtained in A[n-1].
(iv) In this way, execute the same process repeatedly for the heap size n-2 down to the
heap size 2. Eventually, A[] will contain n sorted elements in ascending order.
- 22 -
[Program]
BuildHeap(A, n)
i n
i 2
temp A[1]
A[1] A[i]
A[i] temp
i i - 1
Heapify(A, 1, i)
i: n 2, i 1, -1
Heapify(A, i, n)
lChild _____A_____
rChild _____B_____
lChild heapsize and A[lChild] > A[i]
X largest lChild
largest i
rChild heapsize and A[rChild] > A[largest]
Y largest rChild
largest i
temp A[i]
A[i] A[largest]
A[largest] temp
Heapify(A, largest, heapsize)
- 23 -
Subquestion 1
From the answer group below, select the correct answer to be inserted into each blank
_______ in the above program.
Answer group
a) 2 i b) 2 i + 1
c) 2 i + 2 d) i 2
Subquestion 2
From the answer groups below, select the correct answer to be inserted into each blank
_______ in the following description and Figure 4.
Consider the case where the unsorted data shown in Figure 2 is passed to HeapSort.
1
3 Number of elements n : 5
2 3
5 7 (index) 1 2 3 4 5
4 5 values in A[]: 3 5 7 1 9
1 9
First, HeapSort executes BuildHeap(A, n). When returned from BuildHeap(A, n), the
max heap is built in A[], and the root A[1] contains the maximum value 9, as shown in
Figure 3.
During this process, the program Heapify is called several times, and largest lChild
on line X is executed ___C___ time(s), and largest rChild on line Y is
executed ___D___ time(s).
1
9 Number of elements n : 5
2 3
5 7 (index) 1 2 3 4 5
4 5 Values in A[]: 9 5 7 1 3
1 3
- 24 -
Next, HeapSort executes the following 3 steps repeatedly in the loop, while i 2.
Step 1: Exchange the values of A[1] and A[i], and A[i] becomes the sorted element.
Step 2: Decrement the heap size i by 1.
Step 3: Execute Heapify(A, 1, i) to set the next maximum value in root A[1].
Figure 4 shows the contents of i and A[] at some checkpoints in the loop. This shows how
the sorting operation proceeds. Here, shaded parts indicate the sorted elements.
c) 3 1 5 7 d) 3 5 1 7
e) 7 3 5 1 f) 7 5 3 1
c) 3 1 5 d) 3 5 1
e) 5 1 3 f) 5 3 1
- 25 -
Subquestion 3
From the answer group below, select the correct answer to be inserted into the blank
_______ in the following description.
Consider another case where the unsorted data shown in Figure 5 is passed to HeapSort.
1
2 Number of elements n : 7
2 3
5 6 (index) 1 2 3 4 5 6 7
4 5 6 7 Values in A[]: 2 5 6 3 7 8 4
3 7 8 4
HeapSort first executes BuildHeap(A, n). When returned from BuildHeap(A, n), the
max heap is built in A[], and the values in A[] are as follows:
(index) 1 2 3 4 5 6 7
Values in A[]: ____________G____________
Answer group
a) 8 5 7 2 3 4 6
b) 8 5 7 2 3 6 4
c) 8 7 6 3 5 2 4
d) 8 7 6 3 5 4 2
e) 8 7 6 5 3 2 4
f) 8 7 6 5 3 4 2
- 26 -
Concerning questions Q7 and Q8, select one of the two questions.
Then, mark the in the selection area on the answer sheet, and answer the question.
If two questions are selected, only the first question will be graded.
Q7. Read the following description of a C program and the program itself, and then answer
Subquestion.
This program is a simple text editor which is able to perform editing operations on a line of
text.
[Program Description]
(1) The editor first gets a line of text to edit. Then, the editor repeatedly accepts editor
commands D (delete), F (find), or I (insert), until it receives Q (quit) command.
(2) The editor command D deletes a specified character string from the text, F finds a
specified character string in the text, and I inserts a specified character string into
the text at a specified location.
(3) The following 5 functions are used in the program.
(4) Assuming that the length of any input character string and the length of source after
editing operations range between 1 and 99. Also, it is assumed to be no errors in input
character strings and arguments. The editor does not check for overflows.
- 27 -
(5) The following is a sample run of the text editor program. For each input character
string, to show whether it contains space characters or not, an underline ("_") is used
instead of a space (" ").
Enter the source string:
> Internet_use_is_growing_rapidly.
Enter D(Delete), I(Insert), F(Find), or Q(Quit)> d
String to delete> _growing
New source: Internet_use_is_rapidly.
- 28 -
[Program]
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void) {
char source[MAX_LEN], command;
source[0] = '\0';
printf("Enter the source string: \n> ");
fgets(source, sizeof(source), stdin);
source[strlen(source)-1] = '\0';
for (command = get_command();
command != 'Q'; command = get_command()) {
do_edit(source, command);
printf("New source: %s\n\n", source);
}
printf("String after editing: %s\n", source);
return (0);
}
- 29 -
char * do_edit(char *source, char command) {
char str[MAX_LEN], buf[4];
int index;
switch (command) {
case 'D':
printf("String to delete> ");
fgets(str, sizeof(str), stdin);
str[strlen(str)-1] = '\0';
index = pos(source, str);
if (index == NOT_FOUND)
printf("'%s' not found\n", str);
else
deleted(source, index, strlen(str));
break;
case 'I':
printf("String to insert> ");
fgets(str, sizeof(str), stdin);
str[strlen(str)-1] = '\0';
printf("Position of insertion> ");
fgets(buf, sizeof(buf), stdin);
sscanf(buf, "%d", &index);
_____B_____ ;
break;
case 'F':
printf("String to find> ");
fgets(str, sizeof(str), stdin);
str[strlen(str)-1] = '\0';
index = _____C_____ ;
if (index == NOT_FOUND)
printf("'%s' not found\n", str);
else
printf("'%s' found at position %d\n", str, index);
break;
default:
printf("Invalid edit command '%c' \n", command);
}
return (source);
}
- 30 -
char get_command(void) {
char command, buf[100];
_____E_____ ;
while (!found && i <= (int)strlen(source) - find_len) {
strncpy(substring, &source[i], find_len);
_____F_____ ;
if (strcmp(substring, to_find) == 0)
found = 1;
else
++i;
}
if (found)
position = i;
else
position = NOT_FOUND;
return (position);
}
- 31 -
Subquestion
From the answer groups below, select the correct answer to be inserted into each blank
_______ in the above program.
- 32 -
Q8. Read the following description of Java programs and the programs themselves, and then
answer Subquestion.
[Program Description]
Rock-paper-scissors is a hand game played by two (or more) people, where each player
simultaneously forms one of three shapes (rock, scissors and paper) with his/her
outstretched hand. The rock beats scissors, the scissors beats paper, and the paper beats
rock. If both players throw the same shape, the game is tied.
This game is implemented as two-player game; single player vs. computer. Computer
chooses the shape randomly. A winner gets one point. After playing three times, the
program ends automatically.
The program uses the following java classes from java.util and java.io packages.
ArrayList Resizable-array implementation of the List interface. Implements all
optional list operations, and permits all elements, including null. In
addition to implementing the List interface, this class provides methods to
manipulate the size of the array that is used internally to store the list.
Collections The class consists exclusively of static methods that operate on or return
collections. It contains polymorphic algorithms that operate on collections,
wrappers, which return a new collection backed by a specified collection,
and a few other odds and ends.
- 33 -
List An ordered collection (also known as a sequence). The user of this interface
has precise control over where in the list each element is inserted. The user
can access elements by their integer index (position in the list), and search
for elements in the list.
BufferedReader It reads text from a character-input stream, buffering characters so as to
provide for the efficient reading of characters, arrays, and lines. The
method readLine() reads a line of text.
InputStreamReader An InputStreamReader is a bridge from byte streams to character
streams. Each invocation of one of an InputStreamReaders method
read() may cause one or more bytes to be read from the underlying byte-
input stream. To enable the efficient conversion of bytes to characters, more
bytes may be read ahead from the underlying stream than are necessary to
satisfy the current read operation. For top efficiency, consider wrapping an
InputStreamReader within a BufferedReader.
When the program is executed, the following result, for example, will be printed out.
- 34 -
[Program 1]
public interface GameLoop {
public void startGame();
public void playGame();
public void endGame();
}
[Program 2]
// Object list of this class can be sorted by score.
public class Player implements _____A_____ {
private String name;
private int score;
public Player(String name) {
setName(name);
score = 0;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
// This is overridden method, that used to sort players by their scores in descending order.
public int compareTo(Player p) {
return p.getScore() - this.score;
}
public String toString() {
return name;
}
}
[Program 3]
import java.util.ArrayList;
import java.util.List;
_____B_____ class Game implements GameLoop {
protected List<Player> players;
public Game() {
players = new ArrayList<Player>();
}
public void play() {
startGame();
}
}
- 35 -
[Program 4]
public class GamePlayer extends Player {
private int choice;
public GamePlayer(String name) {
super(name);
}
public void incScore() {
setScore(getScore() + 1);
}
public int getChoice() {
return choice;
}
public void setChoice(int choice) {
this.choice = choice;
}
}
[Program 5]
public class GameLogic {
// If game is tied, this method return null value,
// otherwise returns the information about the player who beats.
_____C_____ GamePlayer checkWinner(GamePlayer player1,
GamePlayer player2) {
GamePlayer winner;
if (player1.getChoice() == player2.getChoice())
return null;
else {
if (player1.getChoice() < player2.getChoice()) {
if ( _____D_____ == 1)
winner = player2;
else
winner = player1;
}
else {
if ( _____D_____ == 1)
winner = player1;
else
winner = player2;
}
winner.incScore();
return winner;
}
}
}
- 36 -
[Program 6]
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Collections;
public class RoPaScGame extends Game {
// Read data from keyboard input stream.
public BufferedReader reader;
private final int PLAYCOUNT = 3;
public RoPaScGame() {
super();
InputStreamReader input = new InputStreamReader(System.in);
reader = new BufferedReader(input);
}
public void initGame() {
players.clear();
players.add(new GamePlayer("Computer"));
players.add(new GamePlayer("Player"));
}
public void startGame() {
initGame();
System.out.println("Input r (rock), p (paper) or s (scissors)");
for (int count = 0; count < PLAYCOUNT; count++) {
playGame();
}
endGame();
}
public void playGame() {
GamePlayer computer = (GamePlayer) players.get(0);
GamePlayer player = (GamePlayer) players.get(1);
computer.setChoice((int)(Math.random() * 3));
boolean isCorrect = false;
System.out.println("_________________________");
while (!isCorrect) {
System.out.println("Input your choice");
char choice = readInput();
switch (choice) {
case 'r': player.setChoice(0);
isCorrect = true;
break;
case 'p': player.setChoice(1);
isCorrect = true;
break;
case 's': player.setChoice(2);
isCorrect = true;
break;
- 37 -
default: System.out.println("Wrong shape");
break;
}
}
GamePlayer winner = GameLogic.checkWinner(player,computer);
if (winner != null)
System.out.println("Winner is " + winner);
else
System.out.println("The game is tied");
}
public void endGame() {
_____E_____ .sort(players);
Player p1 = players.get(0);
Player p2 = players.get(1);
System.out.println("_________________________");
System.out.println(p1 + " vs. " + p2);
System.out.println(p1 + "'s score :\t" + p1.getScore());
System.out.println(p2 + "'s score :\t" + p2.getScore());
if (p1.getScore() != p2.getScore())
System.out.println(p1 + " won.");
else
System.out.println("End in a tie.");
System.out.println("_________________________");
}
public char readInput() {
String result = null;
try {
result = reader.readLine();
}
catch (Exception e) {
}
return result.charAt(0);
}
}
[Program 7]
public class TestGame {
public static void main(String[] args) {
Game game = new RoPaScGame();
game.play();
}
}
- 38 -
Subquestion
From the answer groups below, select the correct answer to be inserted into each blank
_______ in the above programs.
- 39 -