Skip to content

Instantly share code, notes, and snippets.

@priyankvex
Last active December 26, 2018 14:52
Show Gist options
  • Save priyankvex/527d356fa961698497b679e713aa3745 to your computer and use it in GitHub Desktop.
Save priyankvex/527d356fa961698497b679e713aa3745 to your computer and use it in GitHub Desktop.
scammingthecodinginterview.com : Problem 012 : Bishops attacking each other
"""
Scamming the coding interview.
Subscribe to our newsletter at https://scammingthecodinginterview.com/
to get a coding or design problem daily in your inbox and become exceptionally good at
coding interviews.
"""
from fractions import Fraction
from functools import reduce
from operator import mul
def find_bishop_pairs_attacking_each_other(n, m, bishops):
coordinate_sum_map = {}
coordinate_diff_map = {}
for b in bishops:
sum = b[0] + b[1]
diff = b[0] - b[1]
coordinate_diff_map[diff] = coordinate_diff_map.get(diff, 0) + 1
coordinate_sum_map[sum] = coordinate_sum_map.get(sum, 0) + 1
attacking_pairs = 0
for k, v in coordinate_sum_map.items():
temp = nCk(v, 2)
attacking_pairs += temp
for k, v in coordinate_diff_map.items():
temp = nCk(v, 2)
attacking_pairs += temp
return attacking_pairs
def nCk(n,k):
return int(reduce(mul, (Fraction(n-i, i+1) for i in range(k)), 1))
if __name__ == '__main__':
m = 5
n = int(input())
bishops = []
for i in range(0, n):
temp = input().split(" ")
x = int(temp[0])
y = int(temp[1])
bishops.append((x, y))
# bishops = [(1, 1), (1, 5), (3, 3), (5, 1), (5, 5)]
attacks = find_bishop_pairs_attacking_each_other(0, 0, bishops)
print(attacks)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment