Skip to content

Instantly share code, notes, and snippets.

@dpmcmlxxvi
Last active August 29, 2015 14:26
Show Gist options
  • Save dpmcmlxxvi/0299f96fd4eec23071a3 to your computer and use it in GitHub Desktop.
Save dpmcmlxxvi/0299f96fd4eec23071a3 to your computer and use it in GitHub Desktop.
Compute the number of unique lines in a grid
#!/usr/bin/python
#
# Compute the number of unique lines in a grid
# @author Daniel Pulido <dpmcmlxxvi@gmail.com>
# @copyright Copyright (c) 2015 Daniel Pulido <dpmcmlxxvi@gmail.com>
# @file uniquelines.py
# @license MIT License (http://opensource.org/licenses/MIT)
#
import math
def uniquelines(nrows, ncols):
"""
:param nrows: Number of rows
:param ncols: Number of columns
"""
def gridscan():
for row in range(nrows):
for col in range(ncols):
yield col, row
lines = set()
for point1 in gridscan():
for point2 in gridscan():
if point1 == point2: continue
dc = point1[0]-point2[0]
dr = point2[1]-point1[1]
R = math.sqrt(dc*dc + dr*dr)
theta = math.atan2(dc, dr)
rho = (point2[1] * point1[0] - point1[1] * point2[0]) / R
line = (rho,theta)
if line not in lines:
lines.add(line)
# Account for ambiguous 180 rotation
numLines = len(lines)/2
return numLines
def main():
# Define grid sizes to compute
for M in range(1, 10):
for N in range(M, 10):
count = uniquelines(M,N)
print "M = ", M, " N = ", N, " Count = ", count
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment