IPA FE Subject B sample Question 12

A question IPA Japan published in 基本情報技術者試験 科目B サンプル問題 問12, translated into English. ITPEC is based on the same exams.

From the answer group below, select the correct answer to be inserted into blank in the program. Here, the array index starts at 1.

The function simRatio compares the two character-type arrays s1 and s2, each with one or more elements, that are given as arguments, and if their numbers of elements are equal, returns (the number of pairs of elements with the same index whose characters match ÷ the number of elements in s1) as a real number, as an index of how similar the sequences of the arrays are. For example, the return value is 1 when all elements of the arrays match, and 0 when none of the elements match.
If the numbers of elements of the two arrays are not equal, the function returns −1.

The table shows examples of s1 and s2 given to the function simRatio and the return values. In the program, areas outside the arrays must not be referenced.

Table Examples of s1 and s2 given to the function simRatio and the return values

s1s2Return value
{"a", "p", "p", "l", "e"}{"a", "p", "p", "l", "e"}1
{"a", "p", "p", "l", "e"}{"a", "p", "r", "i", "l"}0.4
{"a", "p", "p", "l", "e"}{"m", "e", "l", "o", "n"}0
{"a", "p", "p", "l", "e"}{"p", "e", "n"}-1
[Program]
○ real: simRatio(character []: s1, character []: s2)
integer: i, cnt ← 0
if (the number of elements in s1 ≠ the number of elements in s2)
return -1
endif
for (increase i from 1 to the number of elements in s1 by 1)
if (blank)
cnt ← cnt + 1
endif
endfor
return cnt ÷ the number of elements in s1 /* calculated as real numbers */

Answer group

Explanation

s1[i] = s2[i] — cnt must count the indexes where the two arrays hold the same character, so the elements compared share the loop index.

The function returns cnt ÷ the number of elements, and the description defines the numerator as the number of pairs with the same index whose characters match. So cnt goes up when s1[i] equals s2[i].

Check with the table: "apple" and "april" match at indexes 1 and 2 only, so cnt = 2 and the return value is 2 ÷ 5 = 0.4; "apple" and "melon" match nowhere, giving 0; "apple" with itself gives 5 ÷ 5 = 1.

Answer (d)

Why not others:

  • •(b) — counts the mismatches instead: the table's rows would give 0, 0.6 and 1 instead of 1, 0.4 and 0
  • •(a) and (c) — index s2 by cnt, which is 0 on the first pass, so s2[0] is outside the array, which the program must not reference; cnt is also not a position in either array

Key rule: When comparing two arrays position by position, index both with the same loop variable; a counter that tracks results must never be used as an index.

String Processing · AI-written, may contain errors

This question comes from the past questions IPA Japan publishes, translated into English by ITPEC Practice. ITPEC Practice is an independent study tool and is not affiliated with IPA or ITPEC. See the original paper (PDF) or Report an issue.