示例#1
0
def countLinesWithoutDuplicates(fileName):
    count = 0
    for line in base.getInputLines(fileName):
        splitLine = line.split(' ')
        if len(splitLine) == len(set(splitLine)):
            count += 1
    return count
示例#2
0
def countLinesWithoutAnagrams(fileName):
    count = 0
    for line in base.getInputLines(fileName):
        sortedWords = [''.join(sorted(w)) for w in line.split(' ')]
        if len(sortedWords) == len(set(sortedWords)):
            count += 1
    return count
示例#3
0
def lifeSupportRating(fileName):
    readings = list(base.getInputLines(fileName))
    oxygenGeneratorRating, co2ScrubberRating = splitLists(readings)
    o2rating = int(oxygenGeneratorRating, 2)
    co2rating = int(co2ScrubberRating, 2)
    return "O2: {} ({}), CO2: {} ({}), Rating: {}".format(
        oxygenGeneratorRating, o2rating, co2ScrubberRating, co2rating,
        o2rating * co2rating)
def readLines(fileName, ignoreDiagonals=False):
    pattern = re.compile(r"(\d+),(\d+) -> (\d+),(\d+)")
    for line in base.getInputLines(fileName):
        match = pattern.match(line)
        if match:
            x1, y1, x2, y2 = match.groups()
            if not ignoreDiagonals or x1 == x2 or y1 == y2:
                yield lines.Line((x1, y1), (x2, y2))
示例#5
0
    def readMyFlips(self, fileName):
        """
        No new taxes.
        :return:
        """

        for line in base.getInputLines(fileName):
            self.flip(line)
示例#6
0
    def readDirections(self, fileName):
        move = None
        for pair in base.getInputLines(fileName, delimiter=', '):
            direction = pair[0]
            value = int(pair[1:])
            logger.debug("{}: Pos: {}: Heading:{}".format(
                pair, self.pos, self.heading))
            func = self.transformationFuncs[direction]

            self._move(*func(direction, value))
示例#7
0
def parseFile(fileName):
    total = 0
    length = 0
    sp = stringprocessor.StringDecoder()
    for line in base.getInputLines(fileName):
        processed = sp.processLine(line)
        print("Original: <{}>. Current <{}>. Diff: {} - {} = {}".format(
            line, processed, len(line), len(processed),
            len(line) - len(processed)))
        total += len(line) - len(processed)
    return total
 def readReindeer(self, fileName):
     deers = []
     pattern = re.compile(
         "(\w+) can fly (\d+) km/s for (\d+) seconds, but then must rest for (\d+) seconds."
     )
     for line in base.getInputLines(fileName):
         match = pattern.match(line)
         deers.append(
             Reindeer(match.group(1), int(match.group(2)),
                      int(match.group(3)), int(match.group(4))))
     return deers
示例#9
0
    def readInput(self, fileName):
        masksCurrent = None

        for line in base.getInputLines(fileName):
            if (line):
                prefix, suffix = line.split(' = ')
                if prefix == "mask":
                    masksCurrent = self.createMasks(suffix)
                else:
                    self.write(int(prefix.strip('me[] ')), suffix,
                               masksCurrent)
示例#10
0
def readIDs(fileName):
    firstIgnored = False
    ids = []
    offset = 0
    for stamp in base.getInputLines(fileName, delimiter=','):
        if not firstIgnored:
            firstIgnored = True
        elif stamp == 'x':
            offset += 1
        else:
            ids.append((int(stamp), offset))
            offset += 1
    return ids
示例#11
0
    def readInput(self, fileName):
        self.state = ST_INITIAL

        for line in base.getInputLines(fileName):
            # print("{}: {}".format(self.state, line))
            if not line:
                pass
            elif line[:12] == "your ticket:":
                msg = '\n'.join([
                    "{}: {}".format(rule.name, rule.ranges)
                    for rule in self.rules
                ])
                logger.debug(
                    "{}.{}: STATE CHANGE => ST_YOUR_TICKET: {} rules:\n{}".
                    format(self.__class__.__name__,
                           inspect.currentframe().f_code.co_name,
                           len(self.rules), msg))
                self.state = ST_YOUR_TICKET
            elif line == "nearby tickets:":
                logger.debug(
                    "{}.{}: STATE CHANGE => ST_NEARBY_TICKETS: My ticket: {}".
                    format(self.__class__.__name__,
                           inspect.currentframe().f_code.co_name,
                           self.myTicket))
                self.state = ST_NEARBY_TICKETS
            elif self.state == ST_INITIAL:
                match = re.match(r"(.+): (\d+)-(\d+) or (\d+)-(\d+)", line)
                if match:
                    # print(match.groups())
                    self.rules.append(
                        TicketRule(*match.groups()[1:],
                                   name=match.groups()[0]))
            elif self.state == ST_YOUR_TICKET:
                if self.myTicket:
                    logger.warning("{}.{}: Duplicated my ticket?".format(
                        self.__class__.__name__,
                        inspect.currentframe().f_code.co_name))
                self.myTicket = [int(num) for num in line.split(',')]
            elif self.state == ST_NEARBY_TICKETS:
                ticket = [int(num) for num in line.split(',')]
                ticketValid = True
                for val in ticket:
                    if not self._isValid(val):
                        self.invalidValueSum += val
                        ticketValid = False
                if ticketValid:
                    self.tickets.append(ticket)
        logger.debug("{}.{}: Valid tickets:\n{}".format(
            self.__class__.__name__,
            inspect.currentframe().f_code.co_name,
            '\n'.join([str(ticket) for ticket in self.tickets])))
示例#12
0
def readHands(fileName):
    hand = []
    for line in base.getInputLines(fileName):
        # print(line)
        if not line:
            pass
        elif line[:6] == "Player":
            if hand:
                yield hand[::-1]
                hand.clear()
        else:
            # print(line)
            hand.append(int(line))
    yield hand[::-1]
示例#13
0
def readVectors(fileName):
    for instruction in base.getInputLines(fileName):
        direction, distance = instruction.split()

        unitVectors = {"forward": (1, 0),
                       "up": (0, -1),
                       "down": (0, 1),
                       }

        vector = tuple([x * int(distance) for x in unitVectors[direction]])
        logging.debug("{}(\"{}\"): direction: \"{}\", distance: {}, vector: {}".format(sys._getframe().f_code.co_name,
                                                                                       instruction, direction, distance,
                                                                                       vector))
        yield vector
示例#14
0
def totalRepeats(fileName):
    firstDigit = None
    total = 0
    for line in base.getInputLines(fileName):
        for char in line:
            currentDigit = int(char)
            if not firstDigit:
                firstDigit = currentDigit
            elif currentDigit == prevDigit:
                total += currentDigit
            prevDigit = currentDigit
    if prevDigit == firstDigit:
        total += firstDigit
    return total
示例#15
0
 def _populateCubes(self, fileName):
     logger.debug("Starting: {}.{}: file: {}".format(
         self.__class__.__name__,
         inspect.currentframe().f_code.co_name, fileName))
     rowID = 0
     for row in base.getInputLines(fileName):
         for colID in range(len(row)):
             if row[colID] == "#":
                 self.activeCubes.append(self.cubeClass(
                     (rowID,
                      colID)))  # Cube auto-pads out additional dimensions
         rowID += 1
     logger.debug("Ending: {}.{}: # of cubes: {}".format(
         self.__class__.__name__,
         inspect.currentframe().f_code.co_name, len(self.activeCubes)))
class TestStringEncoder(unittest.TestCase):
    fsTest = ["test2015_08a.txt", "test2015_08b.txt"]
    sd = stringprocessor.StringDecoder()
    se = stringprocessor.StringEncoder()
    lines = [
        line for fileName in fsTest for line in base.getInputLines(fileName)
    ]
    expecteds = [0, 3, 7, 1, 2, 2, 6]

    def test_processLine_allFromFile(self):
        for i in range(len(self.lines)):
            processed = self.sd.processLine(self.lines[i])
            msg = "{}: {}: <{}>, <{}>".format(i, self.expecteds[i],
                                              self.lines[i], processed)
            self.assertEqual(self.expecteds[i], len(processed), msg)
示例#17
0
    def _populateSeats(self, fileName, immediateAdjacency, threshold):
        logger.debug("Starting: {}.{}: file: {}".format(self.__class__.__name__, inspect.currentframe().f_code.co_name,
                                                        fileName))
        rowID = 0
        for row in base.getInputLines(fileName):
            for colID in range(len(row)):
                if row[colID] == "L" or row[colID] == "#":
                    self._addSeatToCollective(Seat(row[colID], (rowID, colID), threshold), immediateAdjacency)

            self.seatingPlan.append(list(row))
            # print(row)
            rowID += 1
        self.dims = (len(self.seatingPlan), len(self.seatingPlan[0]))
        logger.debug("Ending: {}.{}: Dimensions: {}. # of seats: {}".format(
            self.__class__.__name__, inspect.currentframe().f_code.co_name, self.dims, len(self.seatsUnresolved)))
示例#18
0
def nextBus(fileName):
    shortestWait = float('inf')
    idNearest = None
    timestamp = None
    for stamp in base.getInputLines(fileName, delimiter=','):
        if stamp == 'x':
            pass
        elif timestamp:
            delay = timestamp % int(stamp)
            if delay < shortestWait:
                shortestWait = delay
                idNearest = int(stamp)
        else:
            timestamp = -int(stamp)
    return (shortestWait * idNearest, shortestWait, idNearest)
示例#19
0
def readVectorsV2(fileName):
    aim = [1, 0]
    for instruction in base.getInputLines(fileName):
        direction, distString = instruction.split()

        distance = int(distString)
        if direction == "down":
            aim[1] += distance
        elif direction == "up":
            aim[1] -= distance
        elif direction == "forward":
            moveVector = tuple([x * distance for x in aim])
            yield moveVector
        else:
            logging.warning("{}(\"{}\"): Unrecognised direction: \"{}\"".format(sys._getframe().f_code.co_name,
                                                                                fileName, direction))
示例#20
0
    def _readTiles(fileName):
        tileBuffer = []
        for line in base.getInputLines(fileName):
            # print(line)
            if not line:
                pass

            elif line[:4] == "Tile" and tileBuffer:
                yield Tile(tileBuffer)
                tileBuffer.clear()
                tileBuffer.append(line.strip())

            else:
                tileBuffer.append(line.strip())

        yield Tile(tileBuffer)
示例#21
0
    def __init__(self, fileName):
        self.cards = []
        self.sequence = []
        currentCard = []
        for line in base.getInputLines(fileName):
            if ',' in line:
                self.sequence.extend(line.split(','))

            elif not line:
                if currentCard:
                    self.addCard(currentCard)
                    currentCard = []

            else:
                currentCard.append(line.split())

        if currentCard:
            self.addCard(currentCard)
示例#22
0
 def _parseFile(self, fileName):
     """
     Read section one of the file into a RuleTree and section two into a list of tokens to be validated
     :param fileName:
     :return:
     """
     for definition in base.getInputLines(fileName):
         if ':' in definition:
             node = RuleSet(definition)
             if not node:
                 pass
             elif node.terminals:
                 self.nodesEvaluated[node.id] = node.terminals
             else:
                 self.nodesUnevaluated[node.id] = node
                 self._addToWaitingLists(node.id, node.nonTerminals)
         elif definition:
             self.tokensUnvalidated.append(definition)
class TestStringDecoder(unittest.TestCase):
    fsTest = ["test2015_08a.txt", "test2015_08b.txt"]

    lines = [
        line for fileName in fsTest for line in base.getInputLines(fileName)
    ]
    expecteds = [0, 3, 7, 1, 2, 2, 6]
    # ['""', '"abc"', '"aaa\\"aaa"', '"\\x27"', '"\\\\\\xf3"', '"\\\\\\""', '"b\\\\\\\\xda"']
    # [r'""', r'"abc"', r'"aaa\"aaa"', r'"\x27"', r'"\\\xf3"', r'"\\\""', r'"b\\\\xda"']
    # print(lines)

    sd = stringprocessor.StringDecoder()

    def test_processLine_abc_fromFile(self):
        processed = self.sd.processLine(self.lines[1])
        self.assertEqual(3, len(processed))

    def test_processLine_abc_fromString(self):
        processed = self.sd.processLine('\"abc\"')
        self.assertEqual(3, len(processed))

    def test_processLine_abc_fromString2(self):
        processed = self.sd.processLine('"abc"')
        self.assertEqual(3, len(processed))

    def test_processLine_empty_fromFile(self):
        processed = self.sd.processLine(self.lines[0])
        self.assertEqual(0, len(processed))

    def test_processLine_empty_fromString(self):
        processed = self.sd.processLine('\"\"')
        self.assertEqual(0, len(processed))

    def test_processLine_empty_fromString2(self):
        processed = self.sd.processLine('""')
        self.assertEqual(0, len(processed))

    def test_processLine_allFromFile(self):
        for i in range(len(self.lines)):
            processed = self.sd.processLine(self.lines[i])
            msg = "{}: {}: <{}>, <{}>".format(i, self.expecteds[i],
                                              self.lines[i], processed)
            self.assertEqual(self.expecteds[i], len(processed), msg)
示例#24
0
def countDigits(fileName):
    """
    Count the digits in each position of a set of numbers.  Do not assume same lengths or exclusive membership of a
    digit set.

    :param fileName: Input file
    :return: (total count of numbers, [counts of each digit])
    """
    counts = []

    for digits in base.getInputLines(fileName):
        # print("\"{}\", len:{}".format(digits, len(digits)))
        shortfall = len(digits) - len(counts)
        counts.extend([dict() for i in range(shortfall)])
        for i in range(len(digits)):
            if digits[i] in counts[i]:
                counts[i][digits[i]] += 1
            else:
                counts[i][digits[i]] = 1
    return counts
示例#25
0
    def readFile(self, fileName):
        for line in base.getInputLines(fileName):
            ingredients, allergens = self._processLine(line)
            # print("ingredients: {}, allergens: {}".format(ingredients, allergens))
            for allergen in allergens:
                unAllocatedIngredients = [i for i in ingredients if i not in self.ingredientsResolved]
                if allergen not in self.allergenCandidates:
                    self.allergenCandidates[allergen] = set(unAllocatedIngredients)
                else:
                    self.allergenCandidates[allergen] &= set(unAllocatedIngredients)
                if len(self.allergenCandidates[allergen]) == 1:
                    candidate = self.allergenCandidates[allergen].pop()
                    self.ingredientsResolved[candidate] = allergen
            for ingredient in ingredients:
                if ingredient in self.ingredientCounts:
                    self.ingredientCounts[ingredient] += 1
                else:
                    self.ingredientCounts[ingredient] = 1

        resolved = True
        while resolved:
            resolved = False
            toBeDeleted = []
            for allergen, candidates in self.allergenCandidates.items():
                if len(candidates) > 0:
                    candidates -= set([k for k in self.ingredientsResolved.keys()])

                if len(candidates) == 1:
                    candidate = self.allergenCandidates[allergen].pop()
                    self.ingredientsResolved[candidate] = allergen
                    resolved = True
                if not len(candidates):
                    toBeDeleted.append(allergen)
            for candidate in toBeDeleted:
                del self.allergenCandidates[candidate]

        self.part1 = sum([val for k, val in self.ingredientCounts.items() if k not in self.ingredientsResolved])
        sortedByValue = sorted(self.ingredientsResolved.items(), key=lambda kv: kv[1])
        self.part2 = ','.join([k for k, v in sortedByValue])
示例#26
0
    def _populateTree(self, fileName):
        BooleanOpTree.evaluatedOutputs.clear()

        nodes = []
        for definition in base.getInputLines(fileName):
            node = self._turnDefinitionIntoTreeNode(definition)
            if node and node.unresolvedInputs:
                nodes.append(node)

        nodeCount = len(nodes) + 1
        while nodeCount > len(nodes):
            nodeCount = len(nodes)
            print("Starting loop: {} nodes.".format(nodeCount))
            activeNodes = nodes[:]
            nodes = []
            for node in activeNodes:
                node.evaluate()
                if node.unresolvedInputs:
                    nodes.append(node)

        self.evaluatedOutputs = {k: v for k, v in BooleanOpTree.evaluatedOutputs.items()}

        print("evaluatedOutputs: ", sorted(BooleanOpTree.evaluatedOutputs))
示例#27
0
 def readRepetitions(self, fileName):
     for line in base.getInputLines(fileName):
         self.repetitions.append(line.strip())
 def readStream(self, fileName):
     for line in base.getInputLines(fileName):
         for char in line:
             self.inject(char)
示例#29
0
def checksumFromFile(fileName):
    total = 0
    for row in base.getInputLines(fileName):
        entries = [int(e) for e in row.split('\t')]
        total += max(entries) - min(entries)
    return total
示例#30
0
def factorsFromFile(fileName):
    total = 0
    for row in base.getInputLines(fileName):
        entries = sorted([int(e) for e in row.split('\t')])
        total += findIntegerDivision(entries)
    return total