Created
July 7, 2016 05:09
-
-
Save mpurdon/be72a953bc1cb30a0ab7d13eb269836b to your computer and use it in GitHub Desktop.
Given a tic tac toe grid, determine if three points form a straight line. Better than hard-coding the solutions like a noob.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
""" | |
There are a few algorithms for determining collinearity, | |
since we are in two dimensional space with limited neighbours | |
we can afford to use the simpler first difference one. | |
""" | |
from __future__ import print_function | |
from operator import itemgetter | |
def equal_differences(values): | |
""" | |
Check if all values in the list of differences are the same | |
""" | |
# print('Checking if all values are equal in {}'.format(values)) | |
first_element = values[0] | |
num_matching = values.count(first_element) | |
total_values = len(values) | |
# print('{} occurs {} times out of a possible {}'.format(first_element, num_matching, total_values)) | |
return not values or num_matching == total_values | |
def first_difference(values): | |
""" | |
A generator to get the first differences of a list of values | |
""" | |
iterable = iter(values) | |
previous_element = next(iterable) | |
for current_element in iterable: | |
yield current_element - previous_element | |
previous_element = current_element | |
def are_colinear(points): | |
""" | |
Determine if a set of points are colinear (on the same straight line) | |
""" | |
if not points: | |
return False | |
sorted_points = sorted(points, key=itemgetter(0, 1)) | |
# print('Points: {}'.format(sorted_points)) | |
x, y = zip(*sorted_points) | |
diff_x = list(first_difference(x)) | |
diff_y = list(first_difference(y)) | |
# print('X: {}'.format(x)) | |
# print('diff X: {}'.format(diff_x)) | |
# print('y: {}'.format(y)) | |
# print('diff y: {}'.format(diff_y)) | |
return all(map(equal_differences, [diff_x, diff_y])) | |
if __name__ == "__main__": | |
all_points = [ | |
[ | |
(0, 2), | |
(1, 1), | |
(2, 0), | |
], | |
[ | |
(0, 2), | |
(1, 2), | |
(2, 0), | |
], | |
[ | |
(0, 2), | |
(0, 1), | |
(0, 0), | |
], | |
[ | |
(2, 2), | |
(2, 0), | |
(2, 1), | |
], | |
[ | |
(1, 1), | |
(1, 1), | |
(1, 1), | |
], | |
[] | |
] | |
for points in all_points: | |
print('Points {} are colinear: {}'.format(points, 'yes' if are_colinear(points) else 'no')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment