Saturday, August 1, 2020

Product of arrays except self

Code looks simple after looking at the answer 😆, i copied it from
https://leetcode.com/problems/product-of-array-except-self/solution/

In the first loop, you try to multiply all the array values to your left.
Since for the first entry has no left value, we can enter 1 for array location -0.

In the second loop, all you need to do is repeat the same for right.
However, you have 2 statements here.
1st statement , gives the final product ( except self ) to the location.
For the last entry there is no entry to right, we will replace it with 1 ( R=1).
R which represents the product of values to its Right is multiplied with Z[i].
R is loaded similar to the left product logic as mentioned above.

Code
module top;
  int a[5] = { 5,4,3,2,2 };
  int z[5];
  int R=1;
  initial begin
    z[0] = 1;
    for(int i=1; i< $size(a);i++) z[i] = z[i-1] * a[i-1];
   
    for(int i=$size(a)-1;i >=0;i--) begin //{
      z[i] = z[i] * R;
      R *= a[i];
    end //}
    $display("Array:%p",a);
    $display("Products:%p",z);
  end
endmodule

Answer
# vsim -voptargs=+acc=npr
# run -all
# Array:'{5, 4, 3, 2, 2}
# Products:'{48, 60, 80, 120, 120}

2 comments:

  1. I got one more solution for this.
    module top;
    int a[5];
    int p[5];

    initial begin
    foreach(a[i]) a[i] = $urandom_range(1, 6);
    $display("a = %p", a);
    for(int i = 0; i < $size(a); i++) begin
    p[i] = 1;
    for(int j = 0; j < $size(a); j++) begin
    if(i != j)
    p[i] = p[i] * a[j] ;
    end
    end
    $display("p = %p", p);
    end
    endmodule



    //result
    # KERNEL: a = '{5, 6, 2, 2, 6}
    # KERNEL: p = '{144, 120, 360, 360, 120}

    ReplyDelete
    Replies
    1. Well done.

      One more way to do it using the 'with' and 'product' in system verilog.

      module top;
      int a[5] = { 5,6,5,6,2 };
      int p[5];

      initial begin
      foreach (p[i]) begin
      p[i] = a.product() with ((item.index == i ? 1 : item));
      end
      $display("P:%p",p);
      end

      endmodule

      Delete

Constraint to have N elements distributed in M bins

Code to distribute N elements into M bins, you add unique keyword to have each bin will have unique number of elements. class test; param...