Created
April 30, 2013 07:32
-
-
Save mcliment/5487162 to your computer and use it in GitHub Desktop.
Kata Gasolinera en Python (http://www.subgurim.net/Articulos/mundo-web/196/kata-de-las-gasolineras.aspx)
This file contains hidden or 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
#!/usr/bin/python | |
# -*- coding: utf-8-1 -*- | |
import random, math | |
size = 1000 | |
numOfStations = 10 | |
minStationDistance = 5 | |
minPointDistance = 200 | |
def dist(x1, y1, x2, y2): | |
d = math.sqrt(math.pow(x2-x1,2) + math.pow(y2-y1,2)) | |
return d | |
def getStations(): | |
stations = dict() | |
while len(stations) < numOfStations: | |
x = random.randint(1, size) | |
y = random.randint(1, size) | |
isValid = True | |
for s in stations.keys(): | |
if (dist(x, y, stations[s][0], stations[s][1])) < minStationDistance: | |
isValid = False | |
break | |
if isValid: | |
stations[len(stations)] = [x,y] | |
return stations | |
def main(argv=None): | |
stations = getStations() | |
a = [random.randint(1, size), random.randint(1,size)] | |
b = [random.randint(1, size), random.randint(1,size)] | |
while dist(a[0], a[1], b[0], b[1]) < minPointDistance: | |
print b | |
b = [random.randint(1, size), random.randint(1,size)] | |
# El primer número debe ser menor siempre | |
if (a[0] <= b[0]): | |
X = random.randint(a[0], b[0]) | |
else: | |
X = random.randint(b[0], a[0]) | |
if (a[1] <= b[1]): | |
Y = random.randint(a[1], b[1]) | |
else: | |
Y = random.randint(b[1], a[1]) | |
currDist = size * math.sqrt(2) # max. distancia posible | |
for s in stations.keys(): | |
if (dist(X, Y, stations[s][0], stations[s][1])) < currDist: | |
nearest = s | |
currDist = dist(X, Y, stations[s][0], stations[s][1]) | |
print "Estoy en %0d, %0d" % (X, Y) | |
print "La gasolinera más cercana está en %0d, %0d a una distancia de %0d" % (stations[nearest][0], stations[nearest][1], dist(X, Y, stations[nearest][0], stations[nearest][1])) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment