def part1_try_2_rec(ground: Ground, coord: Coord) -> bool: groundXRange = ground.xRange() groundYRange = ground.yRange() inbounds = coord.x in groundXRange and coord.y in groundYRange if inbounds: ground.water_set.add(coord) else: return FloodingFeedback.OUT_OF_BOUNDS # print(prettyPrint(ground)) below = coord.moveByCoord(Coord(0, 1)) right = coord.moveByCoord(Coord(1, 0)) left = coord.moveByCoord(Coord(-1, 0)) downFeedback = False rightFeedback = True leftFeedback = True emptyBelow = below not in ground.clay_set and below not in ground.water_set if emptyBelow: downFeedback = part1_try_2_rec(ground, below) if downFeedback == FloodingFeedback.OUT_OF_BOUNDS: return FloodingFeedback.OUT_OF_BOUNDS if right not in ground.clay_set and right not in ground.water_set: rightFeedback = part1_try_2_rec(ground, right) if left not in ground.clay_set and left not in ground.water_set: leftFeedback = part1_try_2_rec(ground, left) if (rightFeedback == FloodingFeedback.OUT_OF_BOUNDS or leftFeedback == FloodingFeedback.OUT_OF_BOUNDS): return FloodingFeedback.OUT_OF_BOUNDS return FloodingFeedback.FULL
def next(self, direction: Coord): if direction in self.directions: return (self.coord.moveByCoord(direction), direction) else: # not in direction. we have to turn clockWiseDirection = direction.turnClockwise() counterClockWiseDireciton = direction.turnCounterClockwise() if clockWiseDirection in self.directions: return (self.coord.moveByCoord(clockWiseDirection), clockWiseDirection) elif counterClockWiseDireciton in self.directions: return (self.coord.moveByCoord(counterClockWiseDireciton), counterClockWiseDireciton) raise Exception("No direction available")
def ray_intersects(p: Coord, edge: Edge): a, b = edge.a, edge.b if a.y > b.y: a, b = b, a if p.y == a.y or p.y == b.y: p = Coord(p.x, p.y + _eps) intersect = False if (p.y > b.y or p.y < a.y) or (p.x > max(a.x, b.x)): return intersect if p.x < min(a.x, b.x): intersect = True else: if abs(a.x - b.x) > _tiny: m_red = (b.y - a.y) / float(b.x - a.x) else: m_red = _huge if abs(a.x - p.x) > _tiny: m_blue = (p.y - a.y) / float(p.x - a.x) else: m_blue = _huge intersect = m_blue >= m_red return intersect
def pretty_str(self): max_x = max(map(lambda coord: coord.x, self.board.keys())) max_y = max(map(lambda coord: coord.y, self.board.keys())) coord_to_unit = dict() for unit in self.units: coord_to_unit[unit.position] = unit pretty_list = [] for y in range(max_y + 1): for x in range(max_x + 1): current_coord = Coord(x, y) if current_coord in coord_to_unit: u = coord_to_unit[current_coord] #print("Hello", u, self.attacks_this_round) unit_str = coord_to_unit[current_coord].allegiance.value if u in self.moves_this_round: unit_str = bold(unit_str) if u in self.attacks_this_round: unit_str = red(unit_str) pretty_list.append(unit_str) elif current_coord in self.board: pretty_list.append(self.board[current_coord].__repr__()) else: pretty_list.append('.') pretty_list.append('\n') return "".join(pretty_list)
def parse(file): clay_set: Set[Coord] = set() lines = file.readlines() for line in lines: xCoordStart = None xCoordEnd = None yCoordStart = None yCoordEnd = None parts = line.strip().split(", ") if parts[0].startswith("x"): xCoordStart = int(parts[0].split("=")[1]) xCoordEnd = xCoordStart yCoordParts = parts[1].split("=")[1].split("..") yCoordStart = int(yCoordParts[0]) yCoordEnd = int(yCoordParts[1]) else: # starts with y yCoordStart = int(parts[0].split("=")[1]) yCoordEnd = yCoordStart xCoordParts = parts[1].split("=")[1].split("..") xCoordStart = int(xCoordParts[0]) xCoordEnd = int(xCoordParts[1]) for x in range(xCoordStart, xCoordEnd + 1): for y in range(yCoordStart, yCoordEnd + 1): clay_set.add(Coord(x, y)) return clay_set
def parse(file): board: Dict[Coord, any] = dict() units: List[Unit] = [] lines = file.readlines() for y, line in enumerate(lines): for x, cell in enumerate(line): if cell == "#": board[Coord(x, y)] = WALL elif cell == ".": pass elif cell == "G": #units[Coord(x, y)] = Unit(Allegiace.GOBLIN, Coord(x, y)) units.append(Unit(Allegiace.GOBLIN, Coord(x, y))) elif cell == "E": #units[Coord(x, y)] = Unit(Allegiace.ELF, Coord(x, y)) units.append(Unit(Allegiace.ELF, Coord(x, y))) elif cell == "\n": pass else: exit("Invalid input") return Game(board, units)
def initTrackAndCarts(): tracks = dict() carts = [] for y, line in enumerate(lines): for x, cell in enumerate(line): if cell == " " or cell == "\n": continue if cell in ['v', '^', '<', '>']: a = {'v': south, '^': north, '<': west, '>': east} c = Cart(next(nameGenerator), Coord(x, y), a[cell]) print(c) carts.append(c) location = Coord(x, y) directions = getDirectionsFromSign(cell) cellSign = cell if cell in ['v', '^']: cellSign = "|" elif cell in ['<', '>']: cellSign = "-" t = Track(cellSign, location, directions) tracks[location] = t for track in tracks.values(): if track.sign == '/': if neighbourInDirectionIsVerticalTrack(track, north, tracks): track.directions = [north, west] elif neighbourInDirectionIsVerticalTrack(track, south, tracks): track.directions = [south, east] elif track.sign == '\\': if neighbourInDirectionIsVerticalTrack(track, north, tracks): track.directions = [north, east] elif neighbourInDirectionIsVerticalTrack(track, south, tracks): track.directions = [south, west] return (tracks, carts)
def prettyPrint(ground: Ground): clay_set = ground.clay_set water_spring = ground.water_spring water_coord_set = ground.water_set xs = list(map(lambda c: c.x, clay_set)) xMin = min(xs) xMax = max(xs) ys = list(map(lambda c: c.y, clay_set)) yMax = max(ys) #yMin = min(ys) pretty_list = [] for y in range(0, yMax + 1): for x in range(xMin, xMax + 1): if Coord(x, y) == water_spring: pretty_list.append("+") elif Coord(x, y) in clay_set: pretty_list.append("#") elif Coord(x, y) in water_coord_set: pretty_list.append("~") else: pretty_list.append(".") pretty_list.append("\n") return "".join(pretty_list)
def prettyPrint(tracks, carts): carts_dict = dict() for cart in carts: carts_dict[cart.position] = cart track_coords = list(map(lambda x: x.coord, tracks.values())) max_x = max(map(lambda coord: coord.x, track_coords)) max_y = max(map(lambda coord: coord.y, track_coords)) out = [] for y in range(max_y+1): out.append([]) for x in range(max_x+1): c = Coord(x, y) if c in carts_dict: out[-1].append(carts_dict[c].sign()) elif c in tracks: out[-1].append(tracks[c].sign) else: out[-1].append(" ") o = ["".join(row) for row in out] #print(chr(27) + "[2J") print("\n\n\n\n\n\n") print("\n".join(o))
def search(self, start: Coord, goal: Coord) -> int: # possible moves xTranslation = [-1, 0, 1, 1, 1, 0, -1, -1] yTranslation = [-1, -1, -1, 0, 1, 1, 1, 0] # initial cost of move cost = 0 # fringe priority queue fringe = [] heappush(fringe, (cost + self.heuristic(start, goal), cost, start)) # stores visited positions visited = set() # loop until fringe is empty while fringe: # pop item from priority queue fringe _, currCost, cell = heappop(fringe) # goal state; goal node reached, search terminated if cell == goal: return currCost # if cell already visited, skip if cell in visited: continue # add current position to visited set visited.add(cell) # check for potential neighbours for i in range(8): neighbour = Coord(cell.x + xTranslation[i], cell.y + yTranslation[i]) # check validity of each neighbour if self.isMoveValid(visited, cell, neighbour): # append neighbour to fringe heappush(fringe, (currCost + self.heuristic(neighbour, goal), currCost + 1, neighbour))
def run_for_rectangles(plane: Plane): rect = Rectangle(Coord(-1, 3), Coord(4, -1)) print_values('rectangle', rectangles.find_area(plane, rect, NUMBERS_TO_GENERATE))
with open('localities_2.csv', 'r') as file: loc_2 = file.read().split('\n') newlocation = [] for i in loc_2: found = False il = i.lower() for j in loc_1: jl = j.lower() if math.sqrt(fuzz.ratio(jl, il) * fuzz.token_set_ratio(jl, il)) > 75: print(jl, math.sqrt(fuzz.ratio(jl, il) * fuzz.token_set_ratio(jl, il))) found = True break if found: pass else: newlocation.append(i) print(i) if len(newlocation) != 0: newlocations = ('\n').join(newlocation).strip('\n') with open('toAdd.txt', 'w') as file: file.write(newlocations) c = Coord('toAdd.txt', 'toAdd.txt') os.remove('toAdd.txt') c.getCoord() with open('localities.txt', 'a') as file: file.write('\n' + newlocations) else: print('Nothing to update')
def __init__(self, grid: np.ndarray): self.grid = grid self.xLim, self.yLim = np.shape(grid) self.illegalMoves = { Coord(2, 0): Coord(3, 0), Coord(3, 0): Coord(2, 0), Coord(0, 2): Coord(0, 3), Coord(0, 3): Coord(0, 2), Coord(1, 2): Coord(1, 3), Coord(1, 3): Coord(1, 2), Coord(2, 2): Coord(2, 3), Coord(2, 3): Coord(2, 2), Coord(0, 17): Coord(0, 18), Coord(0, 18): Coord(0, 17), Coord(1, 17): Coord(1, 18), Coord(1, 18): Coord(1, 17), Coord(2, 17): Coord(2, 18), Coord(2, 18): Coord(2, 17) }
left = coord.moveByCoord(Coord(-1, 0)) downFeedback = False rightFeedback = True leftFeedback = True emptyBelow = below not in ground.clay_set and below not in ground.water_set if emptyBelow: downFeedback = part1_try_2_rec(ground, below) if downFeedback == FloodingFeedback.OUT_OF_BOUNDS: return FloodingFeedback.OUT_OF_BOUNDS if right not in ground.clay_set and right not in ground.water_set: rightFeedback = part1_try_2_rec(ground, right) if left not in ground.clay_set and left not in ground.water_set: leftFeedback = part1_try_2_rec(ground, left) if (rightFeedback == FloodingFeedback.OUT_OF_BOUNDS or leftFeedback == FloodingFeedback.OUT_OF_BOUNDS): return FloodingFeedback.OUT_OF_BOUNDS return FloodingFeedback.FULL if __name__ == "__main__": #f = open("day_17.example.data") f = open("day_17.data") clay_set = parse(f) water_spring = Coord(x=500, y=0) g = Ground(water_spring, clay_set) # print(prettyPrint(g)) part1_try_2(g) print(len(g.water_set))
def run_for_polygons(plane: Plane): square = Polygon([ Edge(a=Coord(x=-1, y=3), b=Coord(x=4, y=3)), Edge(a=Coord(x=4, y=3), b=Coord(x=4, y=-1)), Edge(a=Coord(x=4, y=-1), b=Coord(x=-1, y=-1)), Edge(a=Coord(x=-1, y=-1), b=Coord(x=-1, y=3)) ]) square_hole = Polygon([ Edge(a=Coord(x=0, y=0), b=Coord(x=10, y=0)), Edge(a=Coord(x=10, y=0), b=Coord(x=10, y=10)), Edge(a=Coord(x=10, y=10), b=Coord(x=0, y=10)), Edge(a=Coord(x=0, y=10), b=Coord(x=0, y=0)), Edge(a=Coord(x=2.5, y=2.5), b=Coord(x=7.5, y=2.5)), Edge(a=Coord(x=7.5, y=2.5), b=Coord(x=7.5, y=7.5)), Edge(a=Coord(x=7.5, y=7.5), b=Coord(x=2.5, y=7.5)), Edge(a=Coord(x=2.5, y=7.5), b=Coord(x=2.5, y=2.5)) ]) random_shape = Polygon([ Edge(a=Coord(x=0, y=0), b=Coord(x=2.5, y=2.5)), Edge(a=Coord(x=2.5, y=2.5), b=Coord(x=0, y=10)), Edge(a=Coord(x=0, y=10), b=Coord(x=2.5, y=7.5)), Edge(a=Coord(x=2.5, y=7.5), b=Coord(x=7.5, y=7.5)), Edge(a=Coord(x=7.5, y=7.5), b=Coord(x=10, y=10)), Edge(a=Coord(x=10, y=10), b=Coord(x=10, y=0)), Edge(a=Coord(x=10, y=0), b=Coord(x=2.5, y=2.5)) ]) print_values('square', polygons.find_area(plane, square, NUMBERS_TO_GENERATE)) print_values('square_hole', polygons.find_area(plane, square_hole, NUMBERS_TO_GENERATE)) print_values('random_shape', polygons.find_area(plane, random_shape, NUMBERS_TO_GENERATE))
def __init__(self, travelTimeData: Queue): Process.__init__(self) self.travelTimeData = travelTimeData self.idealTravelTimes = dict() # initialization of ideal grid, with original unrestricted travel space grid = [ [0, 0, 0, 0, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, -1, -1, 0, 0, 0, -1, -1, -1, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, -1, -1, 0, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0 ], [ 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0 ], [ 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0 ], [ 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0 ], [ 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0 ], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, 0] ] floormap = np.array(grid).transpose(1, 0) shortestPathfinder = Pathfinder(floormap) exitPoints = [Location.getCoords(i)[0] for i in range(1, 9)] entryPoints = [Location.getCoords(i)[1] for i in range(1, 9)] for exitPoint in exitPoints: if exitPoint == None: continue else: for entryPoint in entryPoints: self.idealTravelTimes[( exitPoint, entryPoint)] = shortestPathfinder.search( exitPoint, entryPoint) del self.idealTravelTimes[(Coord(19, 8), Coord(19, 8))] for path, time in self.idealTravelTimes.items(): print(f"{path}: {time}")
def test_shortest_path_direction(self): origo = Coord(0, 0) other = Coord(4, 4) blocks1 = { Coord(0, 1), Coord(1, 1), Coord(1, 0), Coord(1, -1), } step = origo.shortest_path_direction(other, blocks1) self.assertEqual(step, Coord(-1, 0)) blocks2 = { Coord(0, 1), Coord(1, 1), Coord(1, 0), } step = origo.shortest_path_direction(other, blocks2) self.assertEqual(step, Coord(0, -1)) other2 = Coord(-4, -4) blocks2 = { Coord(0, -1), Coord(-1, -1), Coord(-1, 0), } step = origo.shortest_path_direction(other2, blocks2) self.assertEqual(step, Coord(1, 0))
def matchPlace(text): text = text.lower() max_ratio = 0 found_string = None for string in places: ratio = fuzz.ratio(string, text) if ratio > max_ratio: found_string = string max_ratio = ratio return found_string if __name__ == "__main__": if not os.path.exists('newCoords.txt'): open('newCoords.txt', 'w').close() c = Coord('localities.txt', 'newCoords.txt') c.getCoord() else: print('Coordinate File Exists') updateStatus, toUpdate = checkForUpdates() print(toUpdate, updateStatus) if updateStatus: generateGraph('newCoords.txt', cc=15) else: generateGraph('newCoords.txt') dist_duration = [] if not os.path.isfile('dist_duration_large.pkl'): dist_duration = fetchDetails(nodes, dist_duration) with open('dist_duration_large.pkl', 'wb') as file: