IPA FE Subject B 2025 Question 4

A question IPA Japan published in 令和7年度 基本情報技術者試験 科目B 公開問題 問4, 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 description. Here, the array index starts at 1.

The function search receives two character-type arrays as the arguments data and key respectively, searches data for all the sequences that are the same as the sequence of the elements of key, and returns an array that stores all the indexes of the first elements of those sequences. If none is found, it returns an array with 0 elements.
When the function search is called as search({"a", "b", "a", "b", "c", "a", "b", "c"}, {"a", "b", "c"}), the number of times the conditional expression on the line /*** β ***/ is true is blank.

[Program]
/* key is an array with one or more elements */
○ integer []: search(character []: data, character []: key)
integer: i, j, lenData, lenKey
integer []: result ← {} // array with 0 elements
lenData ← the number of elements in data
lenKey ← the number of elements in key
/* The loop is not executed when (lenData - lenKey + 1) is 0 or less */
for (increase i from 1 to (lenData - lenKey + 1) by 1)
for (increase j from 1 to lenKey by 1) // α
if (data[i + j - 1] is equal to key[j]) /*** β ***/
if (j is equal to lenKey)
add the value of i to the end of result
endif
else
exit the for block marked α
endif
endfor
endfor
return result

Answer group

Explanation

8 — the β condition is true once for every character that matches, including the matches made before a mismatch ends the loop at α.

lenData is 8 and lenKey is 3, so i runs from 1 to 6. For each start position i, the inner loop compares data[i + j - 1] with key[j] for j = 1, 2, 3; each match makes β true, and the first mismatch leaves the loop at α.

iComparisonsβ true
1a = a, b = b, a ≠ c2
2b ≠ a0
3a = a, b = b, c = c, so 3 is stored3
4b ≠ a0
5c ≠ a0
6a = a, b = b, c = c, so 6 is stored3

β is true 2 + 3 + 3 = 8 times, and the function returns {3, 6}.

Answer (h)

Why not others:

  • •(b) 2 — the number of sequences found (3 and 6), not the number of true comparisons
  • •(d) 4 — the number of times β is false (at i = 1, 2, 4 and 5), each one ending the inner loop
  • •(f) 6 — counts only the two full matches and forgets the two true comparisons at i = 1 before the mismatch
  • •(a) 1, (c) 3, (e) 5, (g) 7, (i) 9 and (j) 10 — do not match the trace: the loops make 12 comparisons in all, of which 8 are true

Key rule: When counting how often a condition is true in a nested loop with an early exit, trace every pass of the outer loop, including the partial matches that end in a break.

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.