day 10, simple grid walk, refactor into lib
This commit is contained in:
		
							
								
								
									
										35
									
								
								lib/grid.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										35
									
								
								lib/grid.py
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,35 @@
 | 
			
		||||
from typing import Any
 | 
			
		||||
from typing import Optional
 | 
			
		||||
 | 
			
		||||
"""
 | 
			
		||||
same convention as SVG
 | 
			
		||||
           W
 | 
			
		||||
(0,0)┌───────────► x
 | 
			
		||||
     │                
 | 
			
		||||
  H  │                
 | 
			
		||||
     │                
 | 
			
		||||
     │                
 | 
			
		||||
     ▼                
 | 
			
		||||
     y
 | 
			
		||||
grid G store list of rows
 | 
			
		||||
to get G(x,y), must first extract row y and then col y => G[y][x]
 | 
			
		||||
"""
 | 
			
		||||
 | 
			
		||||
def grid_geom(G:list[list[Any]]) -> tuple[int,int]:
 | 
			
		||||
    H = len(G)
 | 
			
		||||
    W = len(G[0])
 | 
			
		||||
    return W, H
 | 
			
		||||
 | 
			
		||||
def in_grid(G:list[list[Any]], x:int, y:int) -> bool:
 | 
			
		||||
    W, H = grid_geom(G)
 | 
			
		||||
    return x>=0 and x<W and y>=0 and y<H
 | 
			
		||||
 | 
			
		||||
def get_in_grid(G:list[list[Any]], x:int, y:int) -> Optional[Any]:
 | 
			
		||||
    if in_grid(G, x,y):
 | 
			
		||||
        return G[y][x]
 | 
			
		||||
 | 
			
		||||
UP = (0,-1) ; RIGHT = (1,0) ; DOWN = (0,1) ; LEFT = (-1,0)
 | 
			
		||||
 | 
			
		||||
MOVE4 = [ UP, RIGHT, DOWN, LEFT ]
 | 
			
		||||
DIAG4 = [(1,1),(-1,-1),(1,-1),(-1,1)]
 | 
			
		||||
MOVE8 = MOVE4 + DIAG4
 | 
			
		||||
		Reference in New Issue
	
	Block a user