Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to verify if a two-dimensional array has two equals rows

Define a method in which, given a two-dimensional array, evaluates if it has at least two identical rows

I've tried to come up with an algorithm to do it but I didn't go very far. This is what I got:

public static boolean righeUguali(int[][] a){
    boolean rUguali=false;

    for(int i=0; i<a.length; i++)
        for(int j=0; i<a[i].length; j++)
            if(Arrays.equals(a[i],a[j]))
                rUguali = true;
    return rUguali;

could you help me fix this code?

like image 872
Daniele Avatar asked Jan 26 '26 06:01

Daniele


1 Answers

  • You need to ensure that you are not comparing the row with itself. You ensure that by starting j with i+1
  • Both loops need to iterate over the rows
  • The fist of the two rows cannot be the last one, otherwise there would be no second row left to compare it to.
  • optimization: you can terminate as soon as you found two equal rows

Here the modified code:

public static boolean righeUguali(int[][] a){
    for(int i=0; i<a.length-1; i++)
        for(int j=i+1; i<a.length; j++)
            if(Arrays.equals(a[i],a[j]))
                return true;
    return false;
}
like image 147
MrSmith42 Avatar answered Jan 28 '26 20:01

MrSmith42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!