Find a representative submatrix You have a matrix of size m x n.

Each cell in the matrix has a uniformly random integer value v, where 0 ≤ v &lt; i, and i ≤ (m x n). (Meaning, the matrix contains a maximum of m x n distinct values, but it may have fewer.)

1) Write a function that accepts input values of m, n, i, and returns a matrix that meets the criteria above.

2) Write a second function that accepts the output of the first function as input, and returns the smallest contiguous submatrix that contains every value of v (by returning the submatrix itself, or its coordinates). By “smallest” I mean the submatrix containing the fewest cells. 

(If it helps you visualize, the original inspiration for this problem was wondering how to find the smallest rectangle within a GIF that contained all the colors in its palette.)
APL (23 + 56 = 79)

Function 1 (23):

{¯1+⍵⍴(V⍴⍺?⍺)[V?V←×/⍵]}


This takes i as its left argument and m n as its right argument, like so:

      +mat←8 {¯1+⍵⍴(V⍴⍺?⍺)[V?V←×/⍵]} 5 5
2 4 7 1 3
7 5 6 7 3
3 1 2 4 6
0 4 2 6 1
5 5 0 0 6


Function 2 (56):

{⊃V[⍋≢∘∊¨V←V/⍨{∧/⍵∊⍨∪∊M}¨V←⊃,/{↓∘⍵¨¯1+,⍳⍴⍵}¨↑∘⍵¨,⍳⍴M←⍵]}


This takes the output from the first function as its right argument, like so:

      {⊃V[⍋≢∘∊¨V←V/⍨{∧/⍵∊⍨∪∊M}¨V←⊃,/{↓∘⍵¨¯1+,⍳⍴⍵}¨↑∘⍵¨,⍳⍴M←⍵]} mat
7 5 6
3 1 2
0 4 2