|  | 
|  | 1 | +package grid | 
|  | 2 | + | 
|  | 3 | +// SubgridLocation represents the coordinates of a found subgrid in the grid | 
|  | 4 | +type SubgridLocation struct { | 
|  | 5 | +	Subgrid [][]byte // Subgrid is the subgrid that was found in the grid | 
|  | 6 | +	StartX  int      // StartX is the starting x-coordinate of the subgrid in the grid | 
|  | 7 | +	StartY  int      // StartY is the starting y-coordinate of the subgrid in the grid | 
|  | 8 | +	EndX    int      // EndX is the ending x-coordinate of the subgrid in the grid | 
|  | 9 | +	EndY    int      // EndY is the ending y-coordinate of the subgrid in the grid | 
|  | 10 | +} | 
|  | 11 | + | 
|  | 12 | +// FindSubgridsInGrid searches for subgrids in a given grid | 
|  | 13 | +// | 
|  | 14 | +// '.' could be any character in the grid. All other characters need an exact match. | 
|  | 15 | +// wildcardCharacter in subgrid can match any character in grid | 
|  | 16 | +func FindSubgridsInGrid(grid, subgrid [][]byte, wildcardCharacter byte) []SubgridLocation { | 
|  | 17 | +	var result []SubgridLocation | 
|  | 18 | + | 
|  | 19 | +	for i, row := range grid { | 
|  | 20 | +		for j := range row { | 
|  | 21 | +			sgl := checkIndexForSubgrid(i, j, grid, subgrid, wildcardCharacter) | 
|  | 22 | +			if len(sgl.Subgrid) != 0 { | 
|  | 23 | +				result = append(result, sgl) | 
|  | 24 | +			} | 
|  | 25 | +		} | 
|  | 26 | +	} | 
|  | 27 | +	return result | 
|  | 28 | +} | 
|  | 29 | + | 
|  | 30 | +func checkIndexForSubgrid(i, j int, grid, subgrid [][]byte, wildcardCharacter byte) SubgridLocation { | 
|  | 31 | +	var result SubgridLocation | 
|  | 32 | + | 
|  | 33 | +	for si, row := range subgrid { | 
|  | 34 | +		for sj := range row { | 
|  | 35 | +			// Check whether subgrid exceeds the bounds of grid | 
|  | 36 | +			if i+len(subgrid) > len(grid) || j+len(subgrid[0]) > len(grid[0]) { | 
|  | 37 | +				return result | 
|  | 38 | +			} | 
|  | 39 | + | 
|  | 40 | +			// Check whether the character matches or is the wildcard character | 
|  | 41 | +			if !(subgrid[si][sj] == wildcardCharacter || subgrid[si][sj] == grid[i+si][j+sj]) { | 
|  | 42 | +				return result | 
|  | 43 | +			} | 
|  | 44 | +		} | 
|  | 45 | +	} | 
|  | 46 | + | 
|  | 47 | +	result.Subgrid = subgrid | 
|  | 48 | +	result.StartX = j | 
|  | 49 | +	result.StartY = i | 
|  | 50 | +	result.EndX = j + len(subgrid[0]) - 1 | 
|  | 51 | +	result.EndY = i + len(subgrid) - 1 | 
|  | 52 | + | 
|  | 53 | +	return result | 
|  | 54 | +} | 
0 commit comments