ITPEC FE Subject B October 2024 Question 16
From the answer group below, select the correct combination of answers to be inserted into A through C in the program.
Function hammingDistance receives two strings as argument and returns Hamming distance as the return value. Hamming distance is a metric used to measure the difference between two strings of equal length. It counts the number of positions at which the corresponding characters are different. For instance, the return value is 2 when the function hammingDistance( is called, because positions 2 and 5 have different characters.
It can also be extended to strings of different lengths by considering the unmatched characters as differences. For instance, the return value is 5 when the function hammingDistance( is called, because of two differences in first six characters and addition of three extra unmatched characters.
Answer group
Explanation
A: length2 < length1, B: is not equal to, C: distance + remainingLength — compare up to the shorter length, count the positions that differ, then add the leftover characters.
- •A:
minLengthstarts aslength1and must be replaced bylength2only whenlength2is smaller, so the loop never reads past the end of the shorter string. - •B: Hamming distance counts positions that differ, so
distancegoes up when the characters are not equal. - •C: every character of the longer string beyond
minLengthhas no partner and counts as one difference;remainingLengthis that count, added to the mismatches the loop found.
Check with hammingDistance(: minLength is 6, positions 2 and 5 differ so distance is 2, remainingLength is 3, and the result is 2 + 3 = 5, as the description says.
Answer (d)
Why not others:
- •(e), (f), (g) and (h) —
length2 > length1setsminLengthto the longer length; in the example the loop runs to 9 and reads characters 7 to 9 of"101010", which do not exist - •(a) and (b) — "is equal to" counts matching positions, 4 in the example; (b) returns 4 + 3 = 7, and (a) returns
remainingLengthalone, 3, discarding the loop's count - •(c) —
distance + minLengthadds the length of the overlap instead of the unmatched part: 2 + 6 = 8
Key rule: When comparing sequences of different lengths, loop only to the shorter length and handle the unmatched tail separately.
String Processing · AI-written, may contain errors
This question comes from an official ITPEC past paper. ITPEC Practice is an independent study tool and is not affiliated with ITPEC. See the official FE past-paper collection or Report an issue.