Data Structures & AlgorithmsHardTCS NQT · counting

Problem: How many ways are there to place 2 non-attacking rooks on a 3 x 3 board (distinct squares, different rows and different columns; order does not matter)? Run the code.

Problem: How many ways are there to place 2 non-attacking rooks on a 3 x 3 board (distinct squares, different rows and different columns; order does not matter)? Run the code.
from itertools import combinations
cells = [(r, c) for r in range(3) for c in range(3)]
print(sum(1 for a, b in combinations(cells, 2) if a[0] != b[0] and a[1] != b[1]))
What is printed?
  1. A. 36
  2. B. 18
  3. C. 9
  4. D. 6

Correct answer: B. 18

Choose two rows (3 ways), two columns (3 ways) and a matching (2 ways), giving 3 * 3 * 2 = 18. Ignoring the matching step gives 9.

More Coding Interview Problems questions

Exams that ask this topic