Constraint for Sub square matrix

I have a 5x5 matrix where i need to constraint all the sub square matrix such that only one element in the sub square has the max value. I kind of have a solution where it is working for 3x3 matrix. The problem with this approach is it is not scalable. I have to write separate constraint for 2x2 as well. In general, what is the best way to constraint a sub square matrix?



// 00 01 02 03 04
// 10 11 12 13 14
// 20 21 22 23 24
// 30 31 32 33 34
// 40 41 42 43 44
  
class questions;
  rand bit [7:0] arr[5][5];
  rand bit [7:0] arr_sb[3][3];
  rand bit [7:0] max_element;
  
  constraint ab {
    foreach (arr[i,j])
      if (i<($size(arr)-2) && j<($size(arr)-2)) arr[i][j] == arr_sb[i][j]; 
  
  }
 
  constraint cd {
    arr_sb.sum(item1) with (item1.sum(item2) with (int'(item2==max_element))) ==1;
    foreach (arr_sb[i,j]){
      arr_sb[i][j] <= max_element;
    }
  }
  
          
  endclass

module tb;
  questions q1;
  
  initial begin
    q1 = new();
    repeat (3) begin
    if (!q1.randomize)$display ("Error");
      $display ("arr_sb %p",q1.arr_sb);
      $display ("arr %p",q1.arr);
      $display ("max element %d",q1.max_element);
    
    end
  end
  
endmodule


In reply to rag123:

You can create a reusable class to hold each array, and then create interconnected constraints between the class objects

class parent #(type elem_t);
  int size;
  rand elem_t arr[][];
  rand elem_t max_element;
  function new(int size);
    this.size = size;
    arr = new[size];
    foreach(arr[i]) arr[i]=new[size];
  endfunction
endclass
class sub #(type elem_t);
  int size;
  rand parent#(elem_t) p;
  rand elem_t arr_sub[][];
  
  function new(int size, parent#(elem_t) p);
    this.size = size;
    this.p = p;
    arr_sub = new[size];
    foreach(arr_sub[i]) arr_sub[i]=new[size];
  endfunction
  constraint ab {
    foreach (arr_sub[i,j]) p.arr[i][j] == arr_sub[i][j]; 
  }
  constraint cd {
    arr_sub.sum(item1) with (item1.sum(item2) with (int'(item2==p.max_element))) ==1;
    foreach (arr_sub[i,j]) arr_sub[i][j] <= p.max_element;
  }
endclass

class questions;
  typedef bit [5:0] elem_t;
  rand parent#(elem_t) p;
  rand sub#(elem_t) s2;
  rand sub#(elem_t) s3;

  function new;
    p = new(5);
    s2 = new(2,p);
    s3 = new(3,p);
  endfunction
endclass
 
module tb;
  questions q1;
 
  initial begin
    q1 = new();
    repeat (3) begin
      assert(q1.randomize);
      $display ("arr_sub2 %p",q1.s2.arr_sub);
      $display ("arr_sub3 %p",q1.s3.arr_sub);
      $display ("arr %p",q1.p.arr);
      $display ("max element %d",q1.p.max_element);
    end
  end
 
endmodule