Example #1
0
def calculateConsensus(agentStore: AgentStore, W: Point, step=0.05, limit=0.05) -> Tuple[Point, int]:
    agents = agentStore.getAgents()
    n = len(agents)
    faultyAgents: Set[str] = set()
    gradients: List[Point] = cast(List[Point], [None for _ in agents])
    stepCounter = 0
    while True:
        stepCounter += 1
        for index, agent in enumerate(agents):
            isFaultyOrThrow(n, len(faultyAgents))
            try:
                agentCost = agent.queryCost(W)
                if isInTown(W, agentCost):
                    gradients[index] = agentCost
                else:
                    faultyAgents.update([agent.agentId])
                    gradients[index] = Point.faultyPoint()
            except:
                faultyAgents.update([agent.agentId])
                gradients[index] = Point.faultyPoint()
        g = correctGradient(gradients, n, len(faultyAgents))
        if closeEnough(g, limit):
            return Point(W.x, W.y), stepCounter
        else:
            W.x = W.x - step * g.x
            W.y = W.y - step * g.y
Example #2
0
    def test_parse_input(self):
        graph, start, end = parse_input(EXAMPLE_1)

        p = Point(9, 6)
        expected = {Point(9, 5), Point(2, 8)}

        self.assertEqual(expected, graph[p])

        self.assertEqual(Point(9, 2), start)
        self.assertEqual(Point(13, 16), end)
Example #3
0
class ShipState:
    position: Point = Point(0, 0)
    orientation: Orientation = Orientation.East
    waypoint: Point = Point(10, 1)

    def displace_in_direction(self, direction: Orientation, steps: int):
        dx, dy = direction.as_coords()
        self.position = self.position.displace(dx * steps, dy * steps)

    def displace_front(self, steps: int):
        self.displace_in_direction(self.orientation, steps)

    def turn(self, direction: TurnDirection, steps: int):
        if direction == TurnDirection.Clockwise:
            self.orientation = Orientation((self.orientation + steps) % 4)
        else:
            self.orientation = Orientation((self.orientation - steps) % 4)

    def move(self, line: str) -> "ShipState":
        instruction, steps = line[0], int(line[1:])

        if instruction in "NESW":
            direction = Orientation.from_char(instruction)
            self.displace_in_direction(direction, steps)
        elif instruction == "L":
            num_turns = steps // 90
            self.turn(TurnDirection.CounterClockwise, num_turns)
        elif instruction == "R":
            num_turns = steps // 90
            self.turn(TurnDirection.Clockwise, num_turns)
        elif instruction == "F":
            self.displace_front(steps)

        return self

    def move_waypoint(self, line: str) -> "ShipState":
        instruction, steps = line[0], int(line[1:])

        if instruction in "NESW":
            displacement = Orientation.from_char(instruction).as_coords().times(steps)
            self.waypoint = self.waypoint.displace(*displacement)
        elif instruction in "LR":
            degrees = -1 * steps if instruction == "R" else steps
            self.waypoint = self.waypoint.rotate(degrees)
        elif instruction == "F":
            displacement = self.waypoint.times(steps)
            self.position = self.position.displace(*displacement)

        return self
Example #4
0
 def Decrypt(self, sk, c):
     l = int((math.log(self.curve.p, 2) + 8 - 1) // 8)
     l = 2 * l
     lt = 2 * l + 2
     C1_hex = c[:lt]
     x1 = int(C1_hex[2:2 + l], 16)
     y1 = int(C1_hex[2 + l:], 16)
     C1 = Point.Point(self.curve, x1, y1, False)
     if self.curve.testPoint(C1.x, C1.y, C1.z) == False:
         raise Exception("The point %s is not the one on %s" %
                         (C1, self.curve))
     C3 = c[len(c) - 64:]
     C2 = c[lt:len(c) - 64]
     Q = C1 * sk
     x2, y2 = Q.cToHex()
     t = KDF(x2 + y2, len(C2))
     if int(t, 16) == 0:
         raise Exception("Error! t = 0")
     m = hex(int(C2, 16) ^ int(t, 16))[2:].zfill(len(C2))
     u = hashlib.sha256(
         int.to_bytes(int(x2 + m + y2, 16),
                      len(x2 + m + y2) // 2,
                      byteorder='big')).hexdigest()
     if u != C3:
         raise Exception("Error! u != C3")
     return m
Example #5
0
def calculate_biodiversity(grid: Grid) -> int:
    total = 0
    for i, xy in enumerate(itertools.product(range(5), range(5))):
        if Point(*reversed(xy)) in grid:
            total += 2 ** i

    return total
Example #6
0
def print_world(graph, oxygen=None):
    start_x = min(p.x for p in graph.keys())
    end_x = max(p.x for p in graph.keys())

    start_y = min(p.y for p in graph.keys())
    end_y = max(p.y for p in graph.keys())

    for y in range(end_y, start_y - 1, -1):
        row = []
        for x in range(start_x, end_x + 1):
            row.append("*" if Point(x, y) in graph else " ")

            if Point(x, y) == oxygen:
                row[-1] = "O"

        print("".join(row))
Example #7
0
def grid_generator(start: Grid) -> typing.Iterable[Grid]:
    current_grid = start
    while True:
        next_grid = set()
        for x, y in itertools.product(range(5), range(5)):

            point = Point(x, y)
            num_adjacent_bugs = len(current_grid.intersection(point.neighbors()))

            if point not in current_grid and num_adjacent_bugs in [1, 2]:
                next_grid.add(point)

            if point in current_grid and num_adjacent_bugs == 1:
                next_grid.add(point)

        yield frozenset(next_grid)
        current_grid = next_grid
Example #8
0
def parse_input(string: str) -> Grid:
    points = set()
    for y, row in enumerate(string.strip().splitlines()):
        for x, character in enumerate(row):
            if character == "#":
                points.add(Point(x, y))

    return frozenset(points)
Example #9
0
 def as_coords(self) -> Point:
     # fmt: off
     return Point(*{
         Orientation.North: ( 0,  1),
         Orientation.East:  ( 1,  0),
         Orientation.South: ( 0, -1),
         Orientation.West:  (-1,  0),
     }[self])
Example #10
0
    def neighbors(self, point: Point, collected_keys: t.Set[str]):
        """Get neighbors (including open passages) to a point, taking into account collected keys"""
        unopened_doors = {
            point
            for point, door_name in self.doors.items()
            if door_name.lower() not in collected_keys
        }

        return self.points.intersection(point.neighbors()) - unopened_doors
Example #11
0
def correctGradient(gradients: List[Point], n: int, f: int) -> Point:
    sortedGradients = sorted(gradients, key=lambda g: math.sqrt(math.pow(g.x, 2) + math.pow(g.y, 2)))
    for i in range(n - f, n):
        sortedGradients[i] = clipNorm(sortedGradients[i], sortedGradients[f])
    x, y = 0.0, 0.0
    for gi in sortedGradients:
        x += gi.x
        y += gi.y
    return Point(x, y)
Example #12
0
def parse_input(raw: str) -> SeatMap:
    seat_map = {}

    for y, line in enumerate(raw.splitlines()):
        for x, char in enumerate(line):
            p = Point(x, y)
            status = {".": SeatStatus.Floor, "L": SeatStatus.Empty}[char]

            seat_map[p] = status

    return seat_map
Example #13
0
    def blocked_via_right_wall_shot(self, bubble):
        starting_point_left = Point(209, 413)
        starting_point_right = Point(234, 413)

        bubble_x_offset = 24 if is_odd(bubble[1][0]) else 12
        # bubble_x_offset = 0
        bubble_middle = Point(17 + 24 * bubble[1][1] + bubble_x_offset - 12, bubble[1][0] * 24 + 18 + 25)
        bubble_left = Point(bubble_middle.x - 12, bubble_middle.y)
        bubble_right = Point(bubble_middle.x + 12, bubble_middle.y)

        for offset in xrange(-4, 4, 4):
            line_left = Line(starting_point_left.x + offset, starting_point_left.y, bubble_left.x, bubble_left.y)
            line_right = Line(starting_point_right.x + offset, starting_point_right.y, bubble_right.x, bubble_right.y)
            first = self.check_if_line_is_clear_right(line_left)
            second = self.check_if_line_is_clear_right(line_right)
            if not first and not second:
                bubble[0].shoot_location = Point(first[0], first[1])
                print "RIGHT shoot at color:{} count:{} location:{},{} x:{} y:{}".format(bubble[0].bubble_data,
                                                                                   bubble[0].neighbors_count,
                                                                                   bubble[1][1], bubble[1][0],
                                                                                   bubble[0].shoot_location.x,
                                                                                   bubble[0].shoot_location.y)

                return False
        return True
Example #14
0
    def populate(self):
        self.tape.run()

        x, y = 0, 0
        for code in map(Codes, self.tape.output):
            if code == Codes.Newline:
                x *= 0
                y += 1
                continue

            if code in [
                    Codes.Scaffold, Codes.Up, Codes.Right, Codes.Down,
                    Codes.Left
            ]:
                self.points.add(Point(x, y))

            x += 1
Example #15
0
def parse_input(string):
    points = set()

    grid = []
    for y, row in enumerate(string.strip("\n").splitlines()):
        grid.append([])
        for x, character in enumerate(row):
            grid[-1].append(character)
            if character == ".":
                points.add(Point(x, y))

    portal_pairs = collections.defaultdict(list)
    for y, row in enumerate(grid):
        for x, character in enumerate(row):
            if not character.isalpha():
                continue

            character_point = Point(x, y)

            neighboring_points = points.intersection(
                character_point.neighbors())
            if not neighboring_points:
                continue

            neighboring_point = list(neighboring_points)[0]
            direction_to_other_letter = character_point.direction_to(
                neighboring_point).inverse_direction()
            other_letter_coords = character_point.move_by_direction(
                direction_to_other_letter)
            other_letter = grid[other_letter_coords.y][other_letter_coords.x]

            portal_pairs["".join(sorted(other_letter +
                                        character))].append(neighboring_point)

    graph = collections.defaultdict(set)

    for p in points:
        graph[p].update(points.intersection(p.neighbors()))

    for point_pair in portal_pairs.values():
        if len(point_pair) < 2:
            continue

        p1, p2, = point_pair
        graph[p1].add(p2)
        graph[p2].add(p1)

    graph = dict(graph.items())

    start, end = portal_pairs["AA"][0], portal_pairs["ZZ"][0]

    return graph, start, end
Example #16
0
def visible_neighbors(seats: SeatMap,
                      origin: Point) -> typing.List[SeatStatus]:
    directions = Point.directions8
    statuses = []

    for x, y in directions:
        for magnitude in itertools.count(1):
            dx, dy = x * magnitude, y * magnitude
            p = origin.displace(dx, dy)

            if p not in seats:
                break

            if seats[p] != SeatStatus.Floor:
                statuses.append(seats[p])
                break

    return statuses
Example #17
0
def parse_input(_in: str) -> World:
    _in = _in.strip()
    points = set()
    keys, doors = dict(), dict()
    entrance = None

    for y, row in enumerate(_in.splitlines()):
        for x, character in enumerate(row):
            if character == "#":
                continue

            point = Point(x, y)
            points.add(point)

            if character.isalpha() and character.islower():
                keys[point] = character

            if character.isalpha() and character.isupper():
                doors[point] = character

            if character == "@":
                entrance = point

    return World(points, keys, doors, entrance)
def keypress(event):
    print(event.keycode)
    active = flags.get_flag_value("active")
    #__Движение объекта__
    if event.keycode == 87:  #Создать клетчку(клавиша W)
        canv.delete("all")
        active.move(Point(0, -k, 0))
        active.draw()
    if event.keycode == 83:  #Создать клетчку(клавиша S)
        canv.delete("all")
        active.move(Point(0, k, 0))
        active.draw()
    if event.keycode == 65:  #Создать клетчку(клавиша A)
        canv.delete("all")
        active.move(Point(-k, 0, 0))
        active.draw()
    if event.keycode == 68:  #Создать клетчку(клавиша D)
        canv.delete("all")
        active.move(Point(k, 0, 0))
        active.draw()
    if event.keycode == 81:  #Создать клетчку(клавиша Z)
        canv.delete("all")
        active.move(Point(0, 0, k))
        active.draw()
    if event.keycode == 69:  #Создать клетчку(клавиша E)
        canv.delete("all")
        active.move(Point(0, 0, -k))
        active.draw()
    #____________________

    #__Вращение объекта__
    if event.keycode == 38:  #Создать клетчку(клавиша ↑)
        canv.delete("all")
        active.turn(Point(k, 0, 0))
        active.draw()

    if event.keycode == 40:  #Создать клетчку(клавиша ↓)
        canv.delete("all")
        active.turn(Point(-k, 0, 0))
        active.draw()

    if event.keycode == 37:  #Создать клетчку(клавиша ←)
        canv.delete("all")
        active.turn(Point(0, -k, 0))
        active.draw()

    if event.keycode == 39:  #Создать клетчку(клавиша →)
        canv.delete("all")
        active.turn(Point(0, k, 0))
        active.draw()

    if event.keycode == 98:  #Создать клетчку(клавиша 1 numpad)
        canv.delete("all")
        active.turn(Point(0, 0, k))
        active.draw()

    if event.keycode == 97:  #Создать клетчку(клавиша 2 numpad)
        canv.delete("all")
        active.turn(Point(0, 0, -k))
        active.draw()

    if event.keycode == 49:  #Создать клетчку(клавиша 1)
        canv.delete("all")
        flags.edit_flags("active", figure1)
        flags.get_flag_value("active").draw()

    if event.keycode == 50:  #Создать клетчку(клавиша 2)
        canv.delete("all")
        flags.edit_flags("active", figure2)
        flags.get_flag_value("active").draw()
from tkinter import *
from lib import Point, Canvas3D, Line, Figure, Flags
from math import cos, sin, acos, sqrt, fabs

root = Tk()
root.minsize(1280, 720)
root.maxsize(1280, 720)

canv = Canvas(root, width=1100, height=720, bg="white")
canv3D = Canvas3D(canv, Point(1100 / 2, 720 / 2, 200000))

k = 5

flags = Flags()
flags.edit_flags("active", 0)


#__Functions__#
def keypress(event):
    print(event.keycode)
    active = flags.get_flag_value("active")
    #__Движение объекта__
    if event.keycode == 87:  #Создать клетчку(клавиша W)
        canv.delete("all")
        active.move(Point(0, -k, 0))
        active.draw()
    if event.keycode == 83:  #Создать клетчку(клавиша S)
        canv.delete("all")
        active.move(Point(0, k, 0))
        active.draw()
    if event.keycode == 65:  #Создать клетчку(клавиша A)
Example #20
0
def clipNorm(current: Point, largest: Point) -> Point:
    currentNorm = math.sqrt(math.pow(current.x, 2) + math.pow(current.y, 2))
    largestPossibleNorm = math.sqrt(math.pow(largest.x, 2) + math.pow(largest.y, 2))
    return Point(largestPossibleNorm / currentNorm * current.x, largestPossibleNorm / currentNorm * current.y)
Example #21
0
def part_2(raw: str):
    ship = ShipState()
    [ship.move_waypoint(line) for line in raw.splitlines()]
    return Point(0, 0).manhattan_distance_to(ship.position)
Example #22
0
def isInTown(mettingPoint: Point, gradient: Point) -> bool:
    location = Point(mettingPoint.x - gradient.x, mettingPoint.y - gradient.y)
    return TOWN_END_X > location.x >= TOWN_START_X and TOWN_END_Y > location.y >= TOWN_START_Y
Example #23
0
 def __init__(self, curve):
     self.curve = curve
     self.g = Point.Point(self.curve, self.curve.gx, self.curve.gy, False)
Example #24
0
def calculateAgentCost():
    payload: Any = request.json
    initialVector: Any = payload["w"]
    w = Point(float(initialVector["x"]), float(initialVector["y"]))
    newGradient = AGENT.calculateGradient(w)
    return jsonify({"grad": {"x": newGradient.x, "y": newGradient.y}})
Example #25
0
from store import AgentStore
from typing import Any
from consensus import calculateConsensus

ENV_NAME = os.getenv("ALG_ENV", "dev")
ALG_SERVER_W_X = os.getenv("ALG_SERVER_W_X")
ALG_SERVER_W_Y = os.getenv("ALG_SERVER_W_Y")
ALG_STEP_SIZE = float(os.getenv("ALG_STEP_SIZE", "0.05"))
ALG_LIMIT = float(os.getenv("ALG_LIMIT", "0.05"))

server = Flask(__name__)
if ENV_NAME != "prod":
    print("Running in DEV mode!")
    server.config["DEBUG"] = True

W: Point = Point(float(ALG_SERVER_W_X), float(ALG_SERVER_W_Y))
AGENT_STORE = AgentStore()


@server.route("/agents", methods=["GET"])
def getRegisteredAgents():
    return jsonify(list(map(lambda a: a.toDict(), AGENT_STORE.getAgents())))


@server.route("/register", methods=["POST"])
def registerAgent():
    payload: Any = request.json
    agentId = str(payload["id"])
    agentUrl = str(payload["url"])
    agent = Agent(agentId, agentUrl)
    registered = AGENT_STORE.addAgent(agent)
Example #26
0
 def __init__(self, tape):
     self.tape = tape
     self.position = Point(0, 0)
     self.graph = collections.defaultdict(set)
     self.oxygen = None
Example #27
0
class Explorer:
    def __init__(self, tape):
        self.tape = tape
        self.position = Point(0, 0)
        self.graph = collections.defaultdict(set)
        self.oxygen = None

    def explore(self):
        places_to_visit = collections.deque([self.position])
        visited = {self.position}

        while places_to_visit:
            next_point = places_to_visit.pop()
            self.move_to(next_point)

            unvisited_neighbors = set(self.position.neighbors()) - visited
            for neighbor in unvisited_neighbors:
                status = self.explore_adjacent_point(neighbor)

                if status == StatusCode.Wall:
                    visited.add(neighbor)

                if status in [StatusCode.Step, StatusCode.Oxygen]:
                    self.graph[self.position].add(neighbor)
                    self.graph[neighbor].add(self.position)
                    places_to_visit.append(neighbor)

                if status == StatusCode.Oxygen:
                    self.oxygen = neighbor

            visited.add(self.position)

    def find_path(self, start, end):
        import heapq as h

        distances = {start: 0}
        heap = [(0, start)]
        prev_node = dict()

        while end not in prev_node:
            weight, node = h.heappop(heap)

            unvisited_neighbors = self.graph[node] - distances.keys()

            for neighbor in unvisited_neighbors:
                prev_node[neighbor] = node

                distance = weight + 1
                distances[neighbor] = weight
                h.heappush(heap, (distance, neighbor))

        cur_node = end
        path = [end]

        while cur_node != start:
            previous_node = prev_node[cur_node]
            path.append(previous_node)
            cur_node = previous_node

        return list(reversed(path))[1:]

    def distances_from(self, start):
        import heapq as h

        distances = {start: 0}
        heap = [(0, start)]

        while heap:
            weight, node = h.heappop(heap)

            unvisited_neighbors = self.graph[node] - distances.keys()

            for neighbor in unvisited_neighbors:
                distance = weight + 1
                distances[neighbor] = weight
                h.heappush(heap, (distance, neighbor))

        return distances

    def move_direction(self, direction):
        input_code = direction_to_int(direction)
        status_code = self.tape.run_until_output(provide_input=input_code)[0]
        status = StatusCode(status_code)

        if status != StatusCode.Wall:
            self.position = self.position.displace(*direction.value)

        return status

    def move_to(self, destination):
        if self.position == destination:
            return

        for point in self.find_path(self.position, destination):
            self.move_direction(self.position.direction_to(point))

    def explore_adjacent_point(self, point):
        direction = self.position.direction_to(point)
        status = self.move_direction(direction)

        if status != StatusCode.Wall:
            self.move_direction(direction.inverse_direction())

        return status
Example #28
0
def part1():
    explorer = Tape.tape_from_challenge(15, Explorer)
    explorer.explore()
    path_to_oxygen = explorer.find_path(Point(0, 0), explorer.oxygen)
    return len(path_to_oxygen)