Equating Two Arrays

From CompSciWiki
Revision as of 09:48, 8 April 2010 by JustinS (Talk | contribs)

Jump to: navigation, search

Back to the Program-A-Day homepage

Problem

This problem envolves you seeing if two hard coded arrays are equal. You should use two int arrays to equate. Even though your arrays are hard coded into your program, you should not assume to know the length of the arrays. In other words use:
 array.length
Remember that your arrays start indexing at 0 and that you should watch out for loops indexing arrays out of bounds. These are the most common pitfalls with a problem like this. If you can try to structure your code so that your loop is only comparing to the length of one of the arrays and not both of them. Print out whether your arrays are equal or not to the console using:
System.out.println ();
 

...By Students

Solution

The Solution to this problem is to use a boolean value to say whether or not the arrays are equal. Assume that they are equal at first and initialize you boolean variable to true. Once you have your two int arrays set up in the code the next part is to start finding a solution to the problem. The best way is to start by checking the two lengths of the arrays by doing this:

if (array1.length == array2.length)
{
}
else
  equals = false;

This is done because if the two arrays are not equal in length then the are obviously not equal. By checking this simple property first you save yourself later on from having to check the length of two arrays when iterating through them as well as some computing time. The next step is to actually compare the values of the two arrays together by iterating through them with a loop. The best kind of loop for this task would be a for loop.

for (int i = 0; i < array1.length; i++)
{
  if (array1[i] != array2[i])
    equals = false;
}

Code

Solution Code

Back to the Program-A-Day homepage