Files
java-interview-lab/matrix/output/09-pitfalls.txt
T

45 lines
1.3 KiB
Plaintext

Six classic mistakes, each reproduced
=====================================
1. in-place transpose with the inner loop starting at j = 0 instead of j = i + 1
input
[1 2 3]
[4 5 6]
[7 8 9]
result (identical to the input, every pair was swapped twice)
[1 2 3]
[4 5 6]
[7 8 9]
2. product result allocated as rows(A) x rows(A) instead of rows(A) x cols(B)
2x3 times 3x4, correct result shape 2x4
wrong version -> ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2
3. spiral without the 'is there still a row / column left?' checks
input [[1, 2, 3]] (a single row)
wrong = [1, 2, 3, 2, 1]
correct = [1, 2, 3]
4. layer rotation with i <= last instead of i < last (the corner is moved twice)
input
[1 2 3]
[4 5 6]
[7 8 9]
wrong
[9 4 7]
[8 5 2]
[3 6 1]
correct
[7 4 1]
[8 5 2]
[9 6 3]
5. 'copy' made with clone() is shallow
original = [[1, 2], [3, 4]]; copy = original.clone(); copy[0][0] = 99
original[0][0] is now 99 (the rows are shared)
copyOf() makes new rows: changing deep[1][1] left original[1][1] at 4
6. int overflow in the dot product
[[50000]] * [[50000]] with plain multiply = -1794967296 (true value 2500000000)
multiplyExact -> ArithmeticException: integer overflow