示例#1
0
    if len(passport['hcl']) != 7 or passport['hcl'][0] != '#':
        return False
    for c in passport['hcl'][1:]:
        if c.isdigit() or c in 'abcdef':
            continue
        return False

    if passport['ecl'] not in ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth']:
        return False

    if len(passport['pid']) != 9 or not passport['pid'].isdigit():
        return False

    return True


def part_1(data):
    return sum(map(validate_passport, data))


def part_2(data):
    return sum([validate_passport(passport, False) for passport in data])


if __name__ == '__main__':
    print('Day 4')
    data = read_input('../inputs/day4.txt')
    passports = data.split('\n\n')
    print('\tPart 1: {}'.format(part_1(passports)))
    print('\tPart 2: {}'.format(part_2(passports)))
示例#2
0
    than the length of the line.

    Instead of actually duplicating the text string, I use
    the modulo operator to figure out what position it loops back on
    itself to, since we know the string pattern is repeated
    """
    if y >= len(row):
        return y % len(row)

    else:
        return y


if __name__ == '__main__':

    lines = read_input('day3_input.txt')

    slopes = [(1,1), (1,3), (1,5), (1,7), (2,1)]
    slope_tree_count = []

    for slope in slopes:

        tree_counter = 0
        x = 0
        y = 0

        for line in lines:
            print("="*20)
            print(f"{x}, {y}")

            if evaluate_if_hit_tree(
示例#3
0
            aaaabbaaaabbaaa
            aaaabbaabbaaaaaaabbbabbbaaabbaabaaa
            babaaabbbaaabaababbaabababaaab
            aabbbbbaabbbaaaaaabbbbbababaaaaabbaaabba'''

        messages = [msg.strip() for msg in test_msgs.splitlines()]
        rule = Rule(test_rules)

        self.assertEqual(count_match_message(rule, messages), 3)

        test_rules = test_rules.replace('11: 42 31', '11: 42 31 | 42 11 31')
        test_rules = test_rules.replace('8: 42', '8: 42 | 42 8')
        rule = Rule(test_rules)
        self.assertEqual(count_match_message(rule, messages), 12)


if __name__ == '__main__':
    print('Day 19')
    data: List[str] = read_input('../inputs/day19.txt').split('\n\n')
    rule_str = data[0]
    messages = data[1].splitlines()
    rule = Rule(rule_str)
    print('\tPart 1: {}'.format(count_match_message(rule, messages)))

    updated_rules = rule_str.replace('11: 42 31', '11: 42 31 | 42 11 31')
    updated_rules = updated_rules.replace('8: 42', '8: 42 | 42 8')
    rule = Rule(updated_rules)
    print('\tPart 2: {}'.format(count_match_message(rule, messages)))

    # unittest.main()
示例#4
0
    permutations_iter = itertools.permutations(unvisited_vertices)
    for permutation in permutations_iter:
        circuit = [initial_vertex, initial_vertex]
        circuit[1:1] = permutation
        cost = 0
        for source, destination in zip(circuit, circuit[1:]):
            cost = cost + distances[source][destination]
        if cost < min_cost:
            min_circuit = circuit
            min_cost = cost
    return min_circuit, min_cost


if __name__ == "__main__":
    # build our moons array(our entry point is also considered a moon)
    moons = utilities.read_input('input.txt')

    # build our 2-D matrix with the distances
    distances = utilities.calc_distances(moons)

    # run the brute force algorithm
    circuit, cost = BF(distances, moons[0], moons)

    # calculate average running speed of BF for our problem
    t = timeit.Timer(functools.partial(BF, distances, moons[0], moons))
    timeit_results = t.autorange()

    # print the results from NN
    utilities.print_alg_results("brute force", distances, circuit, cost,
                                timeit_results)
示例#5
0
    def test_part_1(self):
        rule, _, nearby_tickets = interpret_data(test_input)

        self.assertEqual(part_1(rule, nearby_tickets), 71)

    def test_part_2(self):
        rule, my_ticket, nearby_tickets = interpret_data(test_input2)
        part_1(rule, nearby_tickets)
        part_2(rule, my_ticket)
        self.assertEqual(rule.rule_index.get('row'), 0)
        self.assertEqual(rule.rule_index.get('class'), 1)
        self.assertEqual(rule.rule_index.get('seat'), 2)

    def test_part_2_2(self):
        rule, my_ticket, nearby_tickets = interpret_data(test_input)
        part_1(rule, nearby_tickets)
        part_2(rule, my_ticket)
        self.assertEqual(rule.rule_index.get('row'), 0)
        self.assertEqual(rule.rule_index.get('class'), 1)
        self.assertEqual(rule.rule_index.get('seat'), 2)


if __name__ == '__main__':
    print('Day 16')
    data: str = read_input('../inputs/day16.txt')
    rule, my_ticket, nearby_tickets = interpret_data(data)

    print('\tPart 1: {}'.format(part_1(rule, nearby_tickets)))
    print('\tPart 2: {}'.format(part_2(rule, my_ticket)))
    unittest.main()
示例#6
0
def main(config):
    # Read config from an external json file
    inputs = read_input(config)

    for key in inputs:

        url = inputs[key]['url']

        start = eval(inputs[key]['start'])

        duration = inputs[key]['duration']

        step = inputs[key]['step']

        input_point = inputs[key]['input_point']

        control_point = inputs[key]['control_point']

        faults = inputs[key]['fault']

        # PREPARE OUTPUT FILE
        # -------------
        measurement_tags = requests.get('{0}/measurements'.format(url)).json()
        outFileName = "{}_results.csv".format(key)
        if os.path.exists(outFileName):
            os.remove(outFileName)
            outFile = open(outFileName, "w", newline="")
            writer = csv.DictWriter(outFile,
                                    fieldnames=sorted(measurement_tags))
            writer.writeheader()
        else:
            outFile = open(outFileName, "w", newline="")
            writer = csv.DictWriter(outFile,
                                    fieldnames=sorted(measurement_tags))
            writer.writeheader()

        # RUN SIMULATION
        # -------------
        # Reset simulation
        print(
            'Resetting simulation to start in a certain day of year at a certain time in seconds.'
        )
        res = requests.put('{0}/reset'.format(url), data={'start': start})
        # Set simulation step
        print('Setting simulation step to {0}.'.format(step))
        res = requests.put('{0}/step'.format(url), data={'step': step})
        print('============ Started running simulation for {} ============\n'.
              format(key))
        timeStep = 1
        # Initialize u
        input = requests.get('{0}/inputs'.format(url)).json()
        u = ctrlInitialize(input)
        # Simulation Loop
        while timeStep <= int(duration / step):
            # Advance simulation
            y = requests.post('{0}/advance'.format(url), data=u).json()
            for j in range(len(input_point)):

                # Measurement from the previous step
                measurement = y[input_point[j]]

                # Add bias Air Temperature measurement
                control_value = eval(faults[j].format(measurement))

                # Write biased value to the control input of Air Temperature of selected floor and zone
                u['{}_u'.format(control_point)] = control_value

                # Activate Air Temperature measurement of selected floor and zone
                u['{}_activate'.format(control_point)] = 1

                # Updated u is passed to the emulator through the "advance" call above

            print("Simulated step {0}.".format(timeStep))
            timeStep += 1
            print("Current time {0} seconds.\n".format(y["time"]))
            writer.writerow(dict(sorted(y.items(), key=lambda x: x[0])))

        print('============= Simulation complete. =================\n')