Skip to content

Random Block Solution


import torch
import random

random.seed(123)

foo = torch.zeros(size=(10,10), dtype=torch.int32)
i, j = random.randint(0, 7), random.randint(0, 7)
foo[i:(i+3), j:(j+3)] = 1

Explanation

  1. Instantiate a 10x10 tensor of 32-bit integer 0s.

    foo = torch.zeros(size=(10,10), dtype=torch.int32)
    
    print(foo)
    # tensor([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    #         [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    #         [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    #         [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    #         [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    #         [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    #         [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    #         [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    #         [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    #         [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=torch.int32)
    

    By default, torch.zeros() creates floats, so we explicitly tell it to use 32-bit integers with dtype=torch.int32.

  2. Randomly choose the top-left cell of the 3x3 block.

    We choose random a random (i,j) element such that the entire 3x3 block will fit inside foo.

    import random
    
    random.seed(123)
    i, j = random.randint(0, 7), random.randint(0, 7)
    print(i)  # 0
    print(j)  # 4
    
  3. Select the 3x3 block and update 0s to 1s.

    foo[i:(i+3), j:(j+3)] = 1
    
    print(foo)
    # tensor([[0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
    #         [0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
    #         [0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
    #         [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    #         [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    #         [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    #         [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    #         [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    #         [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    #         [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=torch.int32)
    

Bonus
We can plot the array as an image using matplotlib.pyplot.imshow() with cmap='gray'.

import matplotlib.pyplot as plt
plt.imshow(foo, cmap='gray')