Участник:Alvant/TaskRandomFlipMatrix

Материал из DISCOPAL
Перейти к: навигация, поиск

https://leetcode.com/problems/random-flip-matrix

import numpy as np
from typing import Tuple
 
 
FLIPS_MAX_NUM = 1000
 
 
class Solution:
 
    def __init__(self, n_rows: int, n_cols: int):
        self.n_rows = n_rows
        self.n_cols = n_cols
 
        num_flips = min(FLIPS_MAX_NUM, self.n_rows * self.n_cols)
 
        # The dirtiest trick: choose flips beforehand
        self.positions_to_flip = np.random.choice(
            np.arange(num_flips),  # If try to play fair — self.n_rows * self.n_cols — exceed memory limit
            size=num_flips,
            replace=False
        )
 
        self.current_flip_position_index = 0
 
    def flip(self) -> Tuple[int, int]:
        position = self.positions_to_flip[self.current_flip_position_index]
        coords = (position // self.n_cols, position % self.n_cols)
        self.current_flip_position_index += 1
 
        if self.current_flip_position_index == self.n_rows * self.n_cols:
            self.current_flip_position_index = 0
 
        return coords
 
    def reset(self) -> None:
        # If try to play fair, exceed time limit
        #
        # > self.current_flip_position_index = 0
        # > np.random.shuffle(self.positions_to_flip)
 
        # So...
        pass