Java Is This Java Code Correct for Comparing Array Elements?

  • Thread starter Thread starter courtrigrad
  • Start date Start date
  • Tags Tags
    Java
AI Thread Summary
The Java code provided for comparing array elements has a logical flaw; it incorrectly checks for differences rather than determining if all elements of one array are contained within another. The original function, named `isDifferent`, returns true if any elements are different, which is not aligned with the user's intent to check for subset inclusion. To achieve the desired functionality, the code should be modified to iterate through array 'a' and check if each element exists in array 'b'. A suggested approach involves using nested loops to verify the presence of each element from 'a' in 'b', returning false if any element is not found. This adjustment ensures the function accurately reflects the intended purpose of checking subset inclusion.
courtrigrad
Messages
1,236
Reaction score
2
Code:
 public class check
{
    public boolean isDifferent(int [] a, int [] b)
    {
     for(int i=0; i < a.length; i++)    //loop through your a array
    { 
        for(int j=0;j<b.length;j++)     //next loop through your b array
        {
            if( a[i] != b[j] )  // check for inequality
            {  
                return true;
            }
        } 
   }

   return false;
}
    }

is this correct?
 
Technology news on Phys.org
Yes it is, except that you'd have to use a.length() and b.length(). I have just a comment, that it might be better practice to capitalize class names. Use Check instead of check.
 
Errr. Probably not.
Your code checks A[n] = B[0->n] for all n in A.
I doubt that that was your intent.
The only way you could get false is if all elements had the same value.
 
Last edited:
how would i correct it?
 
courtrigrad said:
how would i correct it?
What are you trying to do?
 
i am trying to return true if any elemtns in a are in b and false if it is not
 
courtrigrad said:
i am trying to return true if any elemtns in a are in b and false if it is not
Change != to ==
 
NoTime said:
Change != to ==
No, the function isDifferent() returns true when the two arrays are different, so the code is correct.
 
ramollari said:
No, the function isDifferent() returns true when the two arrays are different, so the code is correct.
courtrigrad said:
i am trying to return true if any elemtns in a are in b and false if it is not
The OPs desired results seem different than what you say :confused:
 
  • #10
first of all,
the function is named as isDifferent()
which means it is supposed to check whether the arrays are different or not ... in which case the program is correct.

Even if it were supposed to check whether the arrays are same (if it is so , please change the name to isSame() to avoid confusion) , it is not right to change != to == since it might simply check the first element and if they are equal it will return which is not correct ... infact u have to exchange return true and return false ... that's all ...

-- AI
 
  • #11
no i think it would work, i just tested it
 
  • #12
It will always return true, unless the arrays a[] and b[] are both degenerate, and to most intents and purposes, useless.

Imagine a[0] = 3, then unless b[0] == 3, b[1] == 3, b[2] == 3, etc., the function will return true.

If all the elements of b[] are equal to 3, the function next checks a[1] against b[0] (which we already know is 3) so unless a[1] == 3 the function returns true, and so on.

So unless all the elements of both a[] and b[] contain exactly the same value (the number '3' in my example) the function returns true.

If you really want to know if the arrays a[] and b[] are different to each other, you need to write a different function.
 
  • #13
Here's a better version, though I've not tested it.

Code:
 public class check
{
    public boolean isDifferent(int[] a, int[] b)
    {
        if (a.length() != b.length()) return true;

        for (int i = 0; i < a.length(); i++)    //loop through your a array 
            if (a[i] != b[i])  // check for inequality
                return true;

        return false; // returns false if both arrays are same length and all elements match
    }
}
 
  • #14
There's an easier way!

The way you're doing it would work, too, though.

Now, assuming that the .equals() method works like I think it should for int[], you could simply have one line.

return !(a.equals(b));

if not, though, I would use something like ceptimus's code, except it is ".length" and not ".length()".
 
  • #15
The Idiot,
no that won't work either.

int a[] = {1,2,3};
int b[] = {1,2,3};
System.out.println(a.equals(b));
This will print false...
Similarly,
int a[] = {1,2,3};
int b[] = {1,3,4};
System.out.println(a.equals(b));
This also will print false...

However,
int a[] = {1,2,3};
int b[];
b=a;
System.out.println(a.equals(b));
This will print true ...

Can u see what it is doing?

Back to the problem,
If we note carefully , ceptimus has the same program as courtrigrad had except he added the vital condition of equal lengths to it...

courtrigrad,
replacing != with == would not work

If a = {1,2,3} and b={1,3,4}
replacing != with == will give true whereas it should be false.

The only way of achieving the "isSame()" function is exchanging the positions of return true and return false.

-- AI
P.S -> yes it is a.length and not a.length() as The Idiot mentions. (No pun intended :biggrin: )
 
Last edited:
  • #16
TenaliRaman said:
The Idiot,
no that won't work either.

int a[] = {1,2,3};
int b[] = {1,2,3};
System.out.println(a.equals(b));
This will print false...
Similarly,
int a[] = {1,2,3};
int b[] = {1,3,4};
System.out.println(a.equals(b));
This also will print false...

However,
int a[] = {1,2,3};
int b[];
b=a;
System.out.println(a.equals(b));
This will print true ...

Can u see what it is doing?

...Which is why I said "assuming it works the way I think it should."
 
  • #17
Arent u glad u got it cleared? :wink:

-- AI
Its always good to stand on one side and say this grass is greener than to stand on the fence and decide which grass is greener.
 
  • #18
guys thanks for the help but i think this is not what i was looking for. the program returns true if all of the elements in the first array are in the second array regardless of order.


Example

{1,2,3}
{3,2,1,5,6,7}

returns true


{1,2,3}
{3,6,4,8}
returns false

how wouls i then fix the program??

thanks
 
  • #19
Why are you calling the function, 'isDifferent'? Shouldn't it be called 'isaSubsetOf', or 'isContainedIn' if that's what you want it to do.
 
  • #20
yes, sorry, its just a generic method name...
 
  • #21
So, the array "a" needs to have all its elements in array "b"?

How about something like this?

Code:
for(int i = 0; i<a.length; i++)
{
     int j;
     for(j = 0; j<b.length; j++)
     {
          if(a[i] == b[j])
               break;
     }
     if(j == b.length) //a[i] was not found in b.
          return false;
}

return true; //all values were successfully found.
 

Similar threads

Back
Top