I have been working on a coding challenge for some time just for fun, the problem is this:  

**Given a rectangular matrix containing only digits, calculate the number of different 2 × 2 squares in it.** 

The 2x2 matrices may be overlapping. Inputs can be up to 100 x 100 matrices and will be rectangular but not necessarily square. I was able to solve this problem using nested loops, the problem is that it is too slow for inputs that are large matrices and it exceeds the time limit (4000ms) of the coding challenge. This is how I initially solved it.

```
def differentSquares(matrix)
    i = 0
    squares = []
    while i < matrix.length - 1 
        j = 0
        while j < matrix[i].length - 1 
            current = [matrix[i][j], matrix[i][j+1], matrix[i+1][j], matrix[i+1][j+1]]
            squares << current if !squares.include?(current)
            j += 1 
        end 
        i += 1 
    end 
    squares.length 
end

```

I have considered somehow using a hash because they are much faster to iterate through than an array, but I can't figure out how to do that. Can anyone help me find an implementation that is faster than a nested loop? 

Examples of input and expected output: 

```
input:   
[[2,5,3,4,3,1,3,2],   
 [4,5,4,1,2,4,1,3],   
 [1,1,2,1,4,1,1,5],   
 [1,3,4,2,3,4,2,4],   
 [1,5,5,2,1,3,1,1],   
 [1,2,3,3,5,1,2,4],   
 [3,1,4,4,4,1,5,5],   
 [5,1,3,3,1,5,3,5],   
 [5,4,4,3,5,4,4,4]] 

expected output: 54  

another input:   
[[1,2,1],   
 [2,2,2],   
 [2,2,2],   
 [1,2,3],   
 [2,2,1]]

expected output: 6   

```