Untitled

mail@pastecode.io avatar
unknown
python
2 years ago
2.2 kB
5
Indexable
Never
def solve2(inp_filename):
    with open(inp_filename) as file:
        lines = [s.strip() for s in file.readlines()]
        
    commands = []
    for line in lines:
        cmd, coords = line.split(' ')
        coords = [s.split('=') for s in coords.split(',')]
        ranges = dict()
        for ax, range_str in coords:
            lims = list(map(int, range_str.split('..')))
            ranges[ax] = lims
        commands.append((cmd, ranges))
        
    Xsets = { ax:set() for ax in 'xyz' }
    for cmd, ranges in commands:
        for ax, lims in ranges.items():
            Xsets[ax].add(lims[0])
            Xsets[ax].add(lims[1] + 1)
    
    XI = { ax:dict() for ax in 'xyz' }
    IX = { ax:[] for ax in 'xyz' }
    for ax in 'xyz':
        X = list(sorted(Xsets[ax]))
        for x in X:
            XI[ax][x] = len(XI[ax])
            IX[ax].append(x)
            
    lengths = [len(XI[ax]) for ax in 'xyz']
    print(lengths, np.prod(lengths))
    
    Flags = np.zeros(tuple(lengths), dtype=np.uint8)
            
    for cmdi, (cmd, ranges) in enumerate(commands):
        subst_ranges = { ax: [0, 0] for ax in 'xyz' }
        for ax, lims in ranges.items():
            subst_ranges[ax][0] = XI[ax][lims[0]]
            subst_ranges[ax][1] = XI[ax][lims[1] + 1]
            
        x0, x1 = subst_ranges['x'][0], subst_ranges['x'][1]
        y0, y1 = subst_ranges['y'][0], subst_ranges['y'][1]
        z0, z1 = subst_ranges['z'][0], subst_ranges['z'][1]
            
        Flags[x0:x1, y0:y1, z0:z1] = 1 if cmd == 'on' else 0

    print(f"{len(commands)} commands executed")
    
    X = np.array(IX['x'], dtype=np.int64)
    X = X[1:] - X[:-1]
    X = np.array(X, dtype=np.uint64)
    
    Y = np.array(IX['y'], dtype=np.int64)
    Y = Y[1:] - Y[:-1]
    Y = np.array(Y, dtype=np.uint64)
    
    Z = np.array(IX['z'], dtype=np.int64)
    Z = Z[1:] - Z[:-1]
    Z = np.array(Z, dtype=np.uint64)
    
    Muls = np.zeros((len(X), len(Y), len(Z)), dtype=np.uint64)
    for x in range(len(X)):
        Muls[x,:,:] = X[x] * Y.reshape((-1,1)) @ Z.reshape((1,-1))
        
    ans2 = np.sum(Muls * Flags[:-1,:-1,:-1])
    return ans2
        
# solve2('input_short.tmp')
solve2('input')