if j >= n or (dd[i] - dd[j]) > 3: # print(dd[i], dd[j]) break else: # print("success") alternatives[i] += 1 if j - i > 2: skip = True return alternatives part_2_res = part_2(test_data) print(part_2_res) print(sum(part_2_res.values())) print(prod(part_2_res.values())) # print(part_2_res.value()) # print(prod(part_2_res.values()) + part_2_res.values()[0]) # Had to look at : https://github.com/mattr555/advent-of-code/blob/master/2020/day10.py # I had no idea how to solve this one. data = set(data).union({0}) dp = [0] * (max(data) + 4) dp[0] = 1 for i in range(len(dp)): dp[i] += dp[i - 1] if i - 1 in data else 0 dp[i] += dp[i - 2] if i - 2 in data else 0 dp[i] += dp[i - 3] if i - 3 in data else 0 print(dp[-1])
for id, border_tile in border_tiles.items(): print(id, border_tile) print('\n') # print(border_tiles) # Part 1 all_borders = list(itertools.chain(*list(border_tiles.values()))) corner_ids = set() for id, borders in border_tiles.items(): count = sum([all_borders.count(border) for border in borders]) if count == 24: corner_ids.add(int(id[0:4])) print(corner_ids) print('Answer 1:', math.prod(corner_ids), '\n') # Part 2 start_id = str(corner_ids.pop()) + '-DEF' print(f"Starting at tile {start_id}") # Map tiles to image grid search_tiles = border_tiles search_tiles = { id: search_tiles[id] for id in search_tiles if id[0:4] != start_id[0:4] } image_grid = {(0, 0): start_id} side_names = {0: 'top', 1: 'right', 2: 'bottom', 3: 'left'}
def solve(nr, start, end=None, sub_packets=None): cur_pos = start cur_numbers = [] nr_packets = 1 version_sum = 0 while True: if cur_pos > len(nr): break if end and cur_pos+6 > end: break if sub_packets and nr_packets == sub_packets +1: break nr_packets += 1 version_sum += int(nr[cur_pos:cur_pos+3], 2) type_id = int(nr[cur_pos+3:cur_pos+6], 2) cur_pos += 6 if type_id == 4: value = "" while True: bits = nr[cur_pos:cur_pos+5] gr = bits[0] value += bits[1:] cur_pos += 5 if gr == '0': break cur_numbers.append(int(value, 2)) else: length_type_id = nr[cur_pos] cur_pos += 1 sub_bit_length = None sub_length = None if length_type_id == '0': sub_bit_length = int(nr[cur_pos:cur_pos+15], 2) cur_pos += 15 elif length_type_id == '1': sub_length = int(nr[cur_pos:cur_pos+11], 2) cur_pos += 11 new_end = cur_pos+sub_bit_length if sub_bit_length else None sub_values, new_position, sub_version_sum = solve(nr, cur_pos, new_end, sub_length) version_sum += sub_version_sum cur_pos = new_position match type_id: case 0: cur_numbers.append(sum(sub_values)) case 1: cur_numbers.append(math.prod(sub_values)) case 2: cur_numbers.append(min(sub_values)) case 3: cur_numbers.append(max(sub_values)) case 5: cur_numbers.append(int(sub_values[0] > sub_values[1])) case 6: cur_numbers.append(int(sub_values[0] < sub_values[1])) case 7: cur_numbers.append(int(sub_values[0] == sub_values[1])) return cur_numbers, cur_pos, version_sum
while (y < height): # Check if we hit a tree if grid[y][x] == '#': tree_count += 1 # Increase x and y by their steps x += x_step y += y_step return tree_count #-----------------------# # Part 1 - Single slope # #-----------------------# res = tree_count_in_slope(3, 1) print("Part 1: {res}") #----------------------------# # Part 2 - Product of slopes # #----------------------------# # Define all slopes slopes = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)] # Calculate tree_count per slope and take the product res = math.prod( [tree_count_in_slope(x_step, y_step) for x_step, y_step in slopes]) print("Part 2: {res}")
#!/usr/bin/python3 import math print(math.prod(sorted(list(zip(list(map(lambda x: (math.ceil((int(str(open( \ "input.txt", mode='r').read()).strip().split("\n")[0]) / x)) * x) - int( \ str(open("input.txt", mode='r').read()).strip().split("\n")[0]), list(map( \ int, list(filter(lambda x: x != 'x', str(open("input.txt", mode='r').read()\ ).strip().split("\n")[1].split(","))))))),list(map(int, list(filter(lambda \ x: x != 'x', str(open("input.txt", mode='r').read()).strip().split("\n") \ [1].split(",")))))))).pop(0))) """ ___ __ __ _ ___ / _ \__ __/ /_/ / ___ ___ (_)__ / _/_ _____ / ___/ // / __/ _ \/ _ \/ _ \ / (_-< / _/ // / _ \ /_/ \_, /\__/_//_/\___/_//_/ /_/___/ /_/ \_,_/_//_/ /___/ """
# with open(r'.\Day13\inputtest.txt') as thefile: # busses = thefile.read().strip().split(',') #get a list of tuples, with bus and their index busses = [(int(bus), index) for index, bus in enumerate(busses) if bus != "x"] # just, whatevs, let's just search numbusses = len(busses) timestamp = None i = 1 incrementby = 1 lockedin = 0 #once we find a match for a given bus, we are locked in and don't need to keep checking it for bus in busses[lockedin:numbusses]: while timestamp is None: if ((i + bus[1]) % bus[0] == 0 ): #if the current i is divisible by the current bus number and if bus[0] == busses[numbusses - 1][0]: #found the final match, record timestamp timestamp = i else: lockedin += 1 incrementby = prod([ bus[0] for bus in busses[0:lockedin] ]) #start incrementing by the product of all busses matched break i += incrementby print(timestamp)
def isDisivible(currentWeight, remainder): if currentWeight == sum(remainder): return True if currentWeight > sum(remainder): return False for element in remainder: if isDisivible(currentWeight + element, [w for w in remainder if w != element]): return True return False configurations = set() i = 0 while len(configurations) == 0: i += 1 for legConfiguration in combinations(weights, i): if sum(legConfiguration) != totalWeight / 3: continue if isDisivible(0, [w for w in weights if w not in legConfiguration]): configurations.add(legConfiguration) print(min([prod(c) for c in configurations]))
def solve(length): for c in combinations(n, length): if sum(c) == 2020: return prod(c)
def sum_prod(seq_a, seq_b): result = math.prod(seq_a) + math.prod(seq_b) return result
def get_answer() -> int: data = get_data() perms = itertools.permutations(data, 3) for group in perms: if sum(group) == 2020: return math.prod(group)
from .lib.paths import get_day from math import prod if __name__ == "__main__": data = [c == "#" for c in "".join(get_day(3).read_text().split())] width = len(get_day(3).read_text().split()[0]) length = int(len(data) / width) paths = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)] print( prod( map( lambda x: sum([ data[ind] for ind in [ x[1] * i * width + (x[0] * i) % width for i in range(0, int(length / x[1])) ] ]), paths, ))) print( prod([ sum([ data[ind] for ind in [ i * width * x + (y * i) % width for i in range(0, int(length / x)) ] ]) for y, x in paths ]))
def _generate_attention_mask(self, sizes): size = math.prod(sizes) return torch.tril(torch.ones((size, size))).to(self.device, torch.bool)
def _clahe(image, kernel_size, clip_limit, nbins): """Contrast Limited Adaptive Histogram Equalization. Parameters ---------- image : (N1,...,NN) ndarray Input image. kernel_size : int or N-tuple of int Defines the shape of contextual regions used in the algorithm. clip_limit : float Normalized clipping limit between 0 and 1 (higher values give more contrast). nbins : int Number of gray bins for histogram ("data range"). Returns ------- out : (N1,...,NN) ndarray Equalized image. The number of "effective" graylevels in the output image is set by `nbins`; selecting a small value (e.g. 128) speeds up processing and still produces an output image of good quality. A clip limit of 0 or larger than or equal to 1 results in standard (non-contrast limited) AHE. """ ndim = image.ndim dtype = image.dtype # pad the image such that the shape in each dimension # - is a multiple of the kernel_size and # - is preceded by half a kernel size pad_start_per_dim = [k // 2 for k in kernel_size] pad_end_per_dim = [(k - s % k) % k + int(np.ceil(k / 2.)) for k, s in zip(kernel_size, image.shape)] image = np.pad(image, [[p_i, p_f] for p_i, p_f in zip(pad_start_per_dim, pad_end_per_dim)], mode='reflect') # determine gray value bins bin_size = 1 + NR_OF_GRAY // nbins lut = np.arange(NR_OF_GRAY, dtype=np.min_scalar_type(NR_OF_GRAY)) lut //= bin_size image = lut[image] # calculate graylevel mappings for each contextual region # rearrange image into flattened contextual regions ns_hist = [int(s / k) - 1 for s, k in zip(image.shape, kernel_size)] hist_blocks_shape = np.array([ns_hist, kernel_size]).T.flatten() hist_blocks_axis_order = np.array( [np.arange(0, ndim * 2, 2), np.arange(1, ndim * 2, 2)]).flatten() hist_slices = [ slice(k // 2, k // 2 + n * k) for k, n in zip(kernel_size, ns_hist) ] hist_blocks = image[tuple(hist_slices)].reshape(hist_blocks_shape) hist_blocks = np.transpose(hist_blocks, axes=hist_blocks_axis_order) hist_block_assembled_shape = hist_blocks.shape hist_blocks = hist_blocks.reshape((math.prod(ns_hist), -1)) # Calculate actual clip limit kernel_elements = math.prod(kernel_size) if clip_limit > 0.0: clim = int(np.clip(clip_limit * kernel_elements, 1, None)) else: # largest possible value, i.e., do not clip (AHE) clim = kernel_elements hist = np.apply_along_axis(np.bincount, -1, hist_blocks, minlength=nbins) hist = np.apply_along_axis(clip_histogram, -1, hist, clip_limit=clim) hist = map_histogram(hist, 0, NR_OF_GRAY - 1, kernel_elements) hist = hist.reshape(hist_block_assembled_shape[:ndim] + (-1, )) # duplicate leading mappings in each dim map_array = np.pad(hist, [[1, 1] for _ in range(ndim)] + [[0, 0]], mode='edge') # Perform multilinear interpolation of graylevel mappings # using the convention described here: # https://en.wikipedia.org/w/index.php?title=Adaptive_histogram_ # equalization&oldid=936814673#Efficient_computation_by_interpolation # rearrange image into blocks for vectorized processing ns_proc = [int(s / k) for s, k in zip(image.shape, kernel_size)] blocks_shape = np.array([ns_proc, kernel_size]).T.flatten() blocks_axis_order = np.array( [np.arange(0, ndim * 2, 2), np.arange(1, ndim * 2, 2)]).flatten() blocks = image.reshape(blocks_shape) blocks = np.transpose(blocks, axes=blocks_axis_order) blocks_flattened_shape = blocks.shape blocks = np.reshape(blocks, (math.prod(ns_proc), math.prod(blocks.shape[ndim:]))) # calculate interpolation coefficients coeffs = np.meshgrid(*tuple([np.arange(k) / k for k in kernel_size[::-1]]), indexing='ij') coeffs = [np.transpose(c).flatten() for c in coeffs] inv_coeffs = [1 - c for dim, c in enumerate(coeffs)] # sum over contributions of neighboring contextual # regions in each direction result = np.zeros(blocks.shape, dtype=np.float32) for iedge, edge in enumerate(np.ndindex(*([2] * ndim))): edge_maps = map_array[tuple( [slice(e, e + n) for e, n in zip(edge, ns_proc)])] edge_maps = edge_maps.reshape((math.prod(ns_proc), -1)) # apply map edge_mapped = np.take_along_axis(edge_maps, blocks, axis=-1) # interpolate edge_coeffs = np.prod([[inv_coeffs, coeffs][e][d] for d, e in enumerate(edge[::-1])], 0) result += (edge_mapped * edge_coeffs).astype(result.dtype) result = result.astype(dtype) # rebuild result image from blocks result = result.reshape(blocks_flattened_shape) blocks_axis_rebuild_order =\ np.array([np.arange(0, ndim), np.arange(ndim, ndim * 2)]).T.flatten() result = np.transpose(result, axes=blocks_axis_rebuild_order) result = result.reshape(image.shape) # undo padding unpad_slices = tuple([ slice(p_i, s - p_f) for p_i, p_f, s in zip(pad_start_per_dim, pad_end_per_dim, image.shape) ]) result = result[unpad_slices] return result
def solve_p2(inp): return prod([int("".join(x), 2) for x in calculate_p2(inp)])
prev_cuboid[axis_index][1], ) if prev_cuboid[axis_index][1] > coords[axis][1] else None, ) for region_index, region in enumerate(current_axis_regions): if ( region_index != 1 and all( prev_axis_intersection is not None for prev_axis_intersection in prev_axis_intersecting_regions ) and region is not None ): next_processed_cuboids.add( ( *prev_axis_intersecting_regions, region, *prev_cuboid[axis_index + 1 :], ) ) prev_axis_intersecting_regions.append(current_axis_regions[1]) processed_cuboids = next_processed_cuboids.copy() print( sum( math.prod(max_coord - min_coord + 1 for min_coord, max_coord in cuboid) for cuboid in processed_cuboids ) )
#my_utils.print_list(puzzle.decoded_image) # puzzle.print(False) # print(puzzle) def test1(): this_tile = tiles[0] voisins = [] for tile in tiles[1:]: if tile.near_frontiere(this_tile): voisins.append(tile) for tile in voisins: if this_tile.bas in tile.get_all_borders(): tile_bas = tile for tile in voisins: if this_tile.haut in tile.get_all_borders(): tile_haut = tile tile_haut.orientate(this_tile.haut, "bas") tile_haut.print() this_tile.print() tile_bas.orientate(this_tile.bas, "haut") tile_bas.print() # test1() res1 = prod([int(coin.number) for coin in puzzle.coins()]) print(res1) res2 = puzzle.count_roughness() print(res2)
filename = os.path.join(os.path.dirname(os.path.realpath(__file__)), "input.txt") data = [ [int(i) for i in "9" + line.strip() + "9"] for line in open(filename).readlines() ] data = [[9] * len(data[0])] + data + [[9] * len(data[0])] offsets = [[-1, 0], [1, 0], [0, -1], [0, 1]] lowpoints, basins, visited = 0, [], [[False] * len(data[0]) for _ in range(len(data))] for row in range(1, len(data) - 1): for col in range(1, len(data[0]) - 1): lowpoints += ( data[row][col] + 1 if data[row][col] < min([data[row + r][col + c] for r, c in offsets]) else 0 ) if data[row][col] < 9 and not visited[row][col]: basins.append(0) q = deque([(row, col)]) while q: r, c = q.popleft() if not visited[r][c]: visited[r][c] = True basins[-1] += 1 q.extend( [(r + a, c + b) for a, b in offsets if data[r + a][c + b] < 9] ) print("Part 1:", lowpoints) print("Part 2:", math.prod(sorted(basins)[-3:])) # print(math.prod(sorted(basins)))
def matrix_shape(eps_core: Tensor) -> Tuple[int, int]: assert is_eps(eps_core) out_size = eps_core.shape[-1] in_total_size = math.prod(eps_core.shape[:-1]) return out_size, in_total_size
def problem_1() -> int: diffs = get_jolt_differences(data) result: int = math.prod(diff for jolt, diff in diffs.items() if jolt in [1, 3]) return result
def __init__(self, cfg): super().__init__() # Get parameters. assert cfg.DATA.TRAIN_CROP_SIZE == cfg.DATA.TEST_CROP_SIZE self.cfg = cfg # Prepare input. spatial_size = cfg.DATA.TRAIN_CROP_SIZE temporal_size = cfg.DATA.NUM_FRAMES in_chans = cfg.DATA.INPUT_CHANNEL_NUM[0] use_2d_patch = cfg.MVIT.PATCH_2D self.patch_stride = cfg.MVIT.PATCH_STRIDE if use_2d_patch: self.patch_stride = [1] + self.patch_stride # Prepare output. num_classes = cfg.MODEL.NUM_CLASSES embed_dim = cfg.MVIT.EMBED_DIM # Prepare backbone num_heads = cfg.MVIT.NUM_HEADS mlp_ratio = cfg.MVIT.MLP_RATIO qkv_bias = cfg.MVIT.QKV_BIAS self.drop_rate = cfg.MVIT.DROPOUT_RATE depth = cfg.MVIT.DEPTH drop_path_rate = cfg.MVIT.DROPPATH_RATE mode = cfg.MVIT.MODE self.cls_embed_on = cfg.MVIT.CLS_EMBED_ON self.sep_pos_embed = cfg.MVIT.SEP_POS_EMBED if cfg.MVIT.NORM == "layernorm": norm_layer = partial(nn.LayerNorm, eps=1e-6) else: raise NotImplementedError("Only supports layernorm.") self.num_classes = num_classes self.patch_embed = stem_helper.PatchEmbed( dim_in=in_chans, dim_out=embed_dim, kernel=cfg.MVIT.PATCH_KERNEL, stride=cfg.MVIT.PATCH_STRIDE, padding=cfg.MVIT.PATCH_PADDING, conv_2d=use_2d_patch, ) self.input_dims = [temporal_size, spatial_size, spatial_size] assert self.input_dims[1] == self.input_dims[2] self.patch_dims = [ self.input_dims[i] // self.patch_stride[i] for i in range(len(self.input_dims)) ] num_patches = math.prod(self.patch_dims) dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth) ] # stochastic depth decay rule if self.cls_embed_on: self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) pos_embed_dim = num_patches + 1 else: pos_embed_dim = num_patches if self.sep_pos_embed: self.pos_embed_spatial = nn.Parameter( torch.zeros(1, self.patch_dims[1] * self.patch_dims[2], embed_dim)) self.pos_embed_temporal = nn.Parameter( torch.zeros(1, self.patch_dims[0], embed_dim)) self.pos_embed_class = nn.Parameter(torch.zeros(1, 1, embed_dim)) else: self.pos_embed = nn.Parameter( torch.zeros(1, pos_embed_dim, embed_dim)) if self.drop_rate > 0.0: self.pos_drop = nn.Dropout(p=self.drop_rate) pool_q = [[] for i in range(cfg.MVIT.DEPTH)] pool_kv = [[] for i in range(cfg.MVIT.DEPTH)] stride_q = [[] for i in range(cfg.MVIT.DEPTH)] stride_kv = [[] for i in range(cfg.MVIT.DEPTH)] for i in range(len(cfg.MVIT.POOL_Q_STRIDE)): stride_q[cfg.MVIT.POOL_Q_STRIDE[i] [0]] = cfg.MVIT.POOL_Q_STRIDE[i][1:] if cfg.MVIT.POOL_KVQ_KERNEL is not None: pool_q[cfg.MVIT.POOL_Q_STRIDE[i][0]] = cfg.MVIT.POOL_KVQ_KERNEL else: pool_q[cfg.MVIT.POOL_Q_STRIDE[i][0]] = [ s + 1 if s > 1 else s for s in cfg.MVIT.POOL_Q_STRIDE[i][1:] ] for i in range(len(cfg.MVIT.POOL_KV_STRIDE)): stride_kv[cfg.MVIT.POOL_KV_STRIDE[i] [0]] = cfg.MVIT.POOL_KV_STRIDE[i][1:] if cfg.MVIT.POOL_KVQ_KERNEL is not None: pool_kv[cfg.MVIT.POOL_KV_STRIDE[i] [0]] = cfg.MVIT.POOL_KVQ_KERNEL else: pool_kv[cfg.MVIT.POOL_KV_STRIDE[i][0]] = [ s + 1 if s > 1 else s for s in cfg.MVIT.POOL_KV_STRIDE[i][1:] ] dim_mul, head_mul = torch.ones(depth + 1), torch.ones(depth + 1) for i in range(len(cfg.MVIT.DIM_MUL)): dim_mul[cfg.MVIT.DIM_MUL[i][0]] = cfg.MVIT.DIM_MUL[i][1] for i in range(len(cfg.MVIT.HEAD_MUL)): head_mul[cfg.MVIT.HEAD_MUL[i][0]] = cfg.MVIT.HEAD_MUL[i][1] self.norm_stem = norm_layer(embed_dim) if cfg.MVIT.NORM_STEM else None self.blocks = nn.ModuleList() for i in range(depth): num_heads = round_width(num_heads, head_mul[i]) embed_dim = round_width(embed_dim, dim_mul[i], divisor=num_heads) dim_out = round_width( embed_dim, dim_mul[i + 1], divisor=round_width(num_heads, head_mul[i + 1]), ) self.blocks.append( MultiScaleBlock( dim=embed_dim, dim_out=dim_out, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, drop_rate=self.drop_rate, drop_path=dpr[i], norm_layer=norm_layer, kernel_q=pool_q[i] if len(pool_q) > i else [], kernel_kv=pool_kv[i] if len(pool_kv) > i else [], stride_q=stride_q[i] if len(stride_q) > i else [], stride_kv=stride_kv[i] if len(stride_kv) > i else [], mode=mode, has_cls_embed=self.cls_embed_on, )) embed_dim = dim_out self.norm = norm_layer(embed_dim) self.head = head_helper.TransformerBasicHead( embed_dim, num_classes, dropout_rate=cfg.MODEL.DROPOUT_RATE, act_func=cfg.MODEL.HEAD_ACT, ) if self.sep_pos_embed: trunc_normal_(self.pos_embed_spatial, std=0.02) trunc_normal_(self.pos_embed_temporal, std=0.02) trunc_normal_(self.pos_embed_class, std=0.02) else: trunc_normal_(self.pos_embed, std=0.02) if self.cls_embed_on: trunc_normal_(self.cls_token, std=0.02) self.apply(self._init_weights)
def get_borders(image): b = [ image[0], image[-1], "".join([line[0] for line in image]), "".join([line[-1] for line in image]) ] return b + [b[::-1] for b in b] def pretty_print(array_2d): print('\n' + '\n'.join([''.join(a) for a in array_2d]) + '\n') def intersect(a, b): return len([i for j in b for i in a if i == j]) lines = [line.rstrip('\n') for line in open('data.in').read().split('\n\n')] tiles = {} for line in lines: line = line.split('\n') tiles[int(re.findall('\d+', line[0])[0])] = line[1:] borders = {i: get_borders(t) for i, t in tiles.items()} shared = {k: sum(intersect(borders[k], borders[p]) for p in tiles if k != p) // 2 for k in tiles} corners = [i for i in tiles if shared[i] == 2] print(prod(corners))