Skip to content

Instantly share code, notes, and snippets.

@sage-git
Created May 21, 2018 15:52
Show Gist options
  • Save sage-git/ad8a6712c96c0eee9f6def2a654ef3a1 to your computer and use it in GitHub Desktop.
Save sage-git/ad8a6712c96c0eee9f6def2a654ef3a1 to your computer and use it in GitHub Desktop.
count bits with correlation2d
#!/usr/bin/python
# find 5 in line using correlation2d
from __future__ import print_function
import sys
import numpy as np
from scipy import signal
def main():
H = 9
W = 9
G = np.zeros((H, W), dtype=int)
G[0:5, 4:9] = np.eye(5, dtype=int)
G[4:9, 0:5] = np.eye(5, dtype=int)[:, -1::-1]
G[1, 4:9] = 2
G[4:9, 6] = 1
G[0:3, 0:3] = 1
np.savetxt(sys.stdout, G, "%d")
mask_h = np.zeros((5, 5), dtype=int)
mask_h[2, :] = 1
mask_s = np.eye(5, dtype=int)
print("----")
np.savetxt(sys.stdout, mask_h, "%d")
print("----")
np.savetxt(sys.stdout, mask_s, "%d")
print("----")
N = signal.correlate2d(G, mask_h, mode="same", boundary="fill")
np.savetxt(sys.stdout, N, "%d")
print("----")
N = signal.correlate2d(G, mask_h.T, mode="same", boundary="fill")
np.savetxt(sys.stdout, N, "%d")
print("----")
N = signal.correlate2d(G, mask_s, mode="same", boundary="fill")
np.savetxt(sys.stdout, N, "%d")
print("----")
N = signal.correlate2d(G, mask_s[:, -1::-1], mode="same", boundary="fill")
np.savetxt(sys.stdout, N, "%d")
if __name__ == '__main__':
main()
#!/usr/bin/python
# count 1 among a hexagonal map
from __future__ import print_function
import numpy as np
from scipy import signal
def print_hex(grid):
H, W = grid.shape
for i, v in enumerate(grid):
print(" "*i + ("{} "*W).format(*v))
def main():
height = 8
width = 10
grid = np.array(np.random.rand(height, width) + 0.2, dtype=int)
print_hex(grid)
mask = np.array([
[0, 1, 1],
[1, 1, 1],
[1, 1, 0],
])
N = signal.correlate2d(grid, mask, mode="same", boundary="wrap")
print("Count - periodic boundary")
print_hex(N)
N = signal.correlate2d(grid, mask, mode="same", boundary="fill")
print("Count - zero fill over boundary")
print_hex(N)
if __name__ == '__main__':
main()
#!/usr/bin/python
# create minesweeper number map using correlation2d function
from __future__ import print_function
import sys
import numpy as np
from scipy import signal
def print_mines_grid(mine_map, number_map):
M = np.array(number_map, dtype=str)
M[number_map == 0] = "_"
M[mine_map == 1] = "m"
np.savetxt(sys.stdout, M, "%s")
def main():
H = 16
W = 16
nMine = 40
grid = np.zeros(H*W, dtype=int)
grid[:nMine] = 1
np.random.shuffle(grid)
grid = grid.reshape((H, W))
np.savetxt(sys.stdout, grid, "%d")
print("----")
mask = np.array([
[1, 1, 1],
[1, 0, 1],
[1, 1, 1]
] )
N = signal.correlate2d(grid, mask, mode="same", boundary="fill")
print_mines_grid(grid, N)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment