Writing an equals method to compare two arrays - java

I have the following code, I believe something is off in my equals method but I can't figure out what's wrong.
public class Test {
private double[] info;
public Test(double[] a){
double[] constructor = new double[a.length];
for (int i = 0; i < a.length; i++){
constructor[i] = a[i];
}
info = constructor;
}
public double[] getInfo(){
double[] newInfo = new double[info.length];
for(int i = 0; i < info.length; i++){
newInfo[i] = info[i];
}
return newInfo;
}
public double[] setInfo(double[] a){
double[] setInfo = new double[a.length];
for(int i = 0; i < a.length; i++){
setInfo[i] = a[i];
}
return info;
}
public boolean equals(Test x){
return (this.info == x.info);
}
}
and in my tester class I have the following code:
public class Tester {
public static void main(String[] args) {
double[] info = {5.0, 16.3, 3.5 ,79.8}
Test test1 = new Test();
test 1 = new Test(info);
Test test2 = new Test(test1.getInfo());
System.out.print("Tests 1 and 2 are equal: " + test1.equals(test2));
}
}
the rest of my methods seem to function correctly, but when I use my equals method and print the boolean, the console prints out false when it should print true.

You are just comparing memory references to the arrays. You should compare the contents of the arrays instead.
Do this by first comparing the length of each array, then if they match, the entire contents of the array one item at a time.
Here's one way of doing it (written without using helper/utility functions, so you understand what's going on):
public boolean equals(Test x) {
// check if the parameter is null
if (x == null) {
return false;
}
// check if the lengths are the same
if (this.info.length != x.info.length) {
return false;
}
// check the elements in the arrays
for (int index = 0; index < this.info.length; index++) {
if (this.info[index] != x.info[index]) {
return false;
} Aominè
}
// if we get here, then the arrays are the same size and contain the same elements
return true;
}
As #Aominè commented above, you could use a helper/utility function such as (but still need the null check):
public boolean equals(Test x) {
if (x == null) {
return false;
}
return Arrays.equals(this.info, x.info);
}

Related

Method with int and int[] parameters

I have a method with two parameters but they are different types (int , int[]). The problem is in the caller, Eclipse will not compile because it says both of the parameters need to be integer types. The caller looks like this:
boolean uniqueTorF = isUnique(count, userArray[i]);
The method is this:
public static boolean isUnique(int oneCount, int[] multiCount) {
for (int i = 0; i < multiCount.length; i++) {
if (oneCount == multiCount[i]) {
return false;
}
}
return true;
}
This is my entire code:
public static void main(String[] args) {
int[] userArray;
userArray = new int[5];
int validCount = 0, i = 0, uniqueSoFar = 0;
System.out.println("Please print out 5 numbers between 50 and 100. ");
Scanner entry = new Scanner(System.in);
while (validCount < 5) {
int count = entry.nextInt();
boolean validTorF = isValid(count);
boolean uniqueTorF = isUnique(count, userArray[i]);
if (validTorF == true) {
userArray[i] = count;
validCount++;
i++;
if (uniqueTorF == true){
uniqueSoFar++;
}
} else {
System.out.println("That is not a valid number.");
}
}
}
public static boolean isValid(int validParameter) {
if (validParameter > 50 && validParameter < 100) {
return true;
} else {
return false;
}
}
public static boolean isUnique(int oneCount, int[] multiCount) {
for (int i = 0; i < multiCount.length; i++) {
if (oneCount == multiCount[i]) {
return false;
}
}
return true;
}
}
Get rid of the index [i]. userArray[i] is a single element of the array. userArray is the entire array.
boolean uniqueTorF = isUnique(count, userArray);
I'll bet it's saying the params ARE both integer types, not that they SHOULD BE. You're passing count and userArray[i], but you probably should be passing count and userArray.
Defined method expects second argument as array whereas the caller is sending specific element. So send the entire array as argument
The reason of the error is because you are passing the parameters wrongly...
When you do this:
boolean foo = isUnique(count, userArray[i]);
Then you are invoking the method with 2 int parameters, but you need a int, int [] instead...
You are for sure looking for something more like this:
boolean foo = isUnique(count, userArray);

How can I compare ArrayList of integer 2D array with int in java

import java.util.Random;
public class Mutation {
public Mutation()
{
}
private ArrayList<int[][]> allWords=new ArrayList<int[][]>();
public ArrayList<int[][]> wordGenrator(int noOfWords)
{
int rand,j;
int word[][]=new int[8][8];
for(int i=0;i<noOfWords;i++)
{
for(j=0;j<8;j++)
{
rand = new Random().nextInt(2);
System.out.print(rand);
word[i][j]=rand;
}
System.out.print("\n");
allWords.add(word);
}
return allWords;
}
public boolean isExistWordOfAllOnes()
{
int counter;
for(int i=0;i<5;i++)
{
counter=0;
for(int j=0;j<8;j++)
{
if(equals(this.allWords.get(i)[i][j]==1)
{
counter++;
}
}
if(counter==8)
{
return true;
}
}
return false;
}
The loop is running well, but this is not comparing correctly. I want to do if allword(i) have all 1's then return true otherwise false.
Now this is my whole code of same class.. I'm calling these functions in another main class...
As far as I read your code and your text I think you have a int[5][8] Array and you'd like to check whether there is at least one "1" in every row of the array or not. In that case you juse need to change the the Code as followed
public boolean isExistWordOfAllOnes()
{
int counter;
for(int i=0;i<5;i++)
{
counter=0;
for(int j=0;j<8;j++)
{
if(this.allWords.get(i)[i][j]==1)
{
counter++;
}
}
if(counter < 1) // If there were no 1's then count should still be 0
{ // and the method returns false as a row was found
return false; // in which there wasn't a 1
}
}
return true;
}
That ; should be a )
if(equals(this.allWords.get(i)[i][j]==1);
Also, the == is already comparing two things, thus the "equals" is not. Get rid of the equals.
This should be outside the for:
allWords.add(word);
With that change, there will only be one word[][], thus, change the i for a 1:
this.allWords.get(1)...
The problem is with 2D array initialization
What will be value of 2D array if noOfWords=1?
int word[][]=new int[8][8];
for(int i=0;i<noOfWords;i++)
{
for(j=0;j<8;j++)
{
rand = new Random().nextInt(2);
System.out.print(rand);
word[i][j]=rand;
}
System.out.print("\n");
allWords.add(word);
}
Look at the inline comments.
public boolean isExistWordOfAllOnes()
{
int counter;
for(int i=0;i<5;i++) // iterate all the words that are 2D arrays
{
counter=0;
for(int j=0;j<8;j++) // row
{
for (int k = 0; k < 8; k++) { // column
if (this.allWords.get(i)[j][k]==1) { // if it is equal to 1
counter++;
}
}
}
if(counter==8*8)//total 64 ones in 8*8 2D array
{
return true;
}
}
return false;
}

Using Arrays.sort, empty array returned

I'm using the Arrays.sort method to sort an array of my own Comparable objects. Before I use sort the array is full, but after I sort the array and print it to System nothing is printing out. EDIT. the array prints nothing at all. not empty line(s), just nothing.
here is the code for my method which uses sort :
public LinkedQueue<Print> arraySort(LinkedQueue<Print> queue1)
{
Print[] thing = new Print[queue1.size()];
LinkedQueue<Print> newQueue = new LinkedQueue<Print>();
for(int i = 0; i <queue1.size(); i++)
{
Print ob = queue1.dequeue();
thing[i] = ob;
System.out.println(thing[i]); //printing works here
}
Arrays.sort(thing);
for(int j = 0;j<thing.length-1;j++)
{
System.out.println(thing[j]); //printing does not work here
newQueue.enqueue(thing[j]);
}
return newQueue;
}
and here is the class for the Comparable object called Print.
public class Print implements Comparable<Print>
{
private String name;
private int numPages,arrivalTime,startTime,endTime;
public Print(String n, int p, int time, int sTime, int eTime)
{
name = n;
numPages = p;
arrivalTime = time;
startTime = sTime;
endTime = eTime;
}
public int getPages()
{
return numPages;
}
public int compareTo(Print other)
{
if(this.getPages()<other.getPages())
return -1;
else if(this.getPages()>other.getPages())
return 1;
else
return 0;
}
public String toString()
{
return name+"("+numPages+" pages) - printed "+startTime+"-"+endTime+" minutes";
}
}
Your last for loop doesn't print the last element in the array. If the array has only one element, it won't print anything at all. Change to:
for (int j = 0; j < thing.length; j++) //clean code uses spaces liberally :)
{
System.out.println(thing[j]);
newQueue.enqueue(thing[j]);
}
or (if supported by the JDK/JRE version used):
for (Print p : thing)
{
System.out.println(p);
newQueue.enqueue(p);
}
I hope the problem is this part of code
for(int i = 0; i <queue1.size(); i++)
{
Print ob = queue1.dequeue();
thing[i] = ob;
System.out.println(thing[i]); //printing works here
}
replace the above with
for(int i = 0; !queue1.isEmpty() ; i++)
{
Print ob = queue1.dequeue();
thing[i] = ob;
System.out.println(thing[i]); //printing works here
}

ADT LinkedList intersecting set error

I have a test code for an ADT of LinkedList, which implements interface NumList.java, and is implemented in a NumLinkedList.java, and am using it in a NumSet.java.
I am trying to make it so that my NumSet has methods where I can create a set from a double array input, and use intercept/union and print methods to use and print the data.
but my test code is showing that my test NumSet values are empty, namely testProof and testProof2.
So now my testProof is returning an empty variable, which means nothing is saving into it.
static public NumSet intersect(NumSet S1, NumSet S2) //check 2nd for and if//
{
NumSet intersectAnswer = new NumSet();
for (int i = 0; i < S1.set.size()-1; i++)
{
for(int j = 0; j < S2.set.size()-1; j++)
{
double FUZZ = 0.0001;
if (Math.abs(S1.set.lookup(i) - S2.set.lookup(j)) < FUZZ) // double values, this is more precise than ==.
{
intersectAnswer.set.insert(1, S1.set.lookup(i));
}
}
}
return intersectAnswer;
}
is the method for testProof, and the following is where testProof is defined.
public static void main(String[] args)
{
double[] a = {1.3,2,3,4,101.9};
double[] b = {3,7,13,901,-29.1,0.05};
NumArrayList test;
test = new NumArrayList();
test.printTest(); //runs test code in NumList
//ok below is running. what is wrong with intersect?
NumSet test2;
test2 = new NumSet(a);
NumSet test4;
test4 = new NumSet(b);
NumSet testProof;
NumSet testProof2;
test2.print(); //print out test 2
System.out.println();
test4.print();
System.out.println();
testProof = intersect(test2,test4);
I have initialized as
public class NumSet
{
private NumList set;
public NumSet(double[] sth)
{
//moves elements of sth into set.
set = new NumLinkedList();
for(int i = 0; i < sth.length; i++)
{
set.insert(0,sth[i]);
}
set.removeDuplicates();
}
public NumSet()
{
set = new NumLinkedList();
}
int numSet = 0;
and my intercept, union and print are below:
public NumSet intersect(NumSet S1, NumSet S2) //check 2nd for and if//
{
NumSet intersectAnswer = new NumSet();
for (int i = 0; i < S1.set.size()-1; i++)
{
for(int j = 0; j < S2.set.size()-1; j++)
{
if (S1.set.lookup(i) == S2.set.lookup(j))
{
intersectAnswer.set.insert(0, S1.set.lookup(i));
}
}
}
// intersectAnswer.set.removeDuplicates(); unnecessary, sets are already removed of duplicates
return intersectAnswer;
}
public NumSet union(NumSet S1, NumSet S2)
{ //check logic.
NumSet unionAnswer = new NumSet();
for (int i = 1; i < S1.set.size()+1; i++)
{
unionAnswer.set.insert(1, S1.set.lookup(i));
}
for (int i = 1; i < S2.set.size()+1; i++)
{
unionAnswer.set.insert(1, S2.set.lookup(i));
}
unionAnswer.set.removeDuplicates();
return unionAnswer;
}
public void print()
{
for (int i = 0; i < set.size()-1; i++)
{
System.out.print(set.lookup(i) + ",");
}
System.out.print(set.lookup(set.size()-1));
}
the lookup and size are referred to from my NumLinkedList.java and are as below
public int size() // measure size of list by counting counter++;
{
return nItem;
}
public double lookup(int i)
{
if( i <0 || i >= size()) //cannot lookup nonexistant object
{
System.out.println("out of bounds " + i + " < 0 or > " + size() );
//how do I break out of this loop?
System.out.println("just returning 0 for the sake of the program");
return 0;
}
if(i == 0)
{
return head.value;
}
double answer = 0;
Node currNode = head;
for(int j = 0; j < i+1; j++) //move to ith node and save value
{
answer = currNode.value;
currNode = currNode.next;
}
return answer;
}
and finally my test code is as below, where testProof and testProof2 are.
public static void main(String[] args)
{
double[] a = {1.3,2,3,4,101.9};
double[] b = {3,7,13,901,-29.1,0.05};
NumArrayList test;
test = new NumArrayList();
test.printTest(); //runs test code in NumList
//ok below is running. what is wrong with intersect?
NumSet test2;
test2 = new NumSet(a);
NumSet test4;
test4 = new NumSet(b);
NumSet testProof;
NumSet testProof2;
test2.print();
System.out.println();
testProof = test2.intersect(test2, test4);
System.out.println("tried intersect");
testProof.print();
System.out.println();
System.out.println("tried test.print()");
testProof2 = test2.union(test2,test4);
System.out.println("tried union");
testProof2.print();
System.out.println();
System.out.println("NumSet ran fully.");
I'd suggest you implement you NumSet Class with integer values rather than double values while you debug because comparing two double values tends to add some unneeded complexity to your code at this debug stage.
You might want to look at your removeDuplicates() method, I think that might hold the answer to your problem. Unfortunately I don't see it within the code you posted.
Actually, this part of code within the intersect() method is destined to fail from the start,
if (S1.set.lookup(i) == S2.set.lookup(j))
Because of your use of doubles, == is a very imprecise method of comparing two different values, a better way would be to allow for a certain amount of precision error, i.e.
double final FUZZ = 0.0001
if (Math.abs(S1.set.lookup(i) - S2.set.lookup(j)) < FUZZ )
//...

Recursive with void method?

I have a problem with one of my program (my programming language is java) :
I have an object Douglas-Peucker which is an array of Points and I have an algorithm, the Douglas-Peucker algorithm. I want to work directly on this array of Points and here the problem begin. This is Douglas-Peucker algorithm :
protected Point[] coinImage;
// My constructor
public Peucker(Point [] tab) {
coinImage = new Point[tab.length];
for(int i = 0; i < coinImage.length; i++) {
coinImage[i] = new Point(tab[i].x, tab[i].y);
}
}
public Point[] algoDouglasPeucker() {
return douglasPeuckerAux(0,coinImage.length - 1);
}
public Point[] douglasPeuckerAux(int startIndex, int endIndex) {
double dmax = 0;
int index = 0;
for(int i = startIndex + 1; i < endIndex; i++) {
double distance = this.distancePointSegment(this.coinImage[i], this.coinImage[startIndex], this.coinImage[endIndex]);
if(distance > dmax) {
index = i;
dmax = distance;
}
} ***
if(dmax >= this.epsilon) {
Point[] recResult1 = douglasPeuckerAux(startIndex,index);
Point[] recResult2 = douglasPeuckerAux(index,endIndex);
Point [] result = this.unionTabPoint(recResult1, recResult2);
return result;
}
else {
return new Point[] { coinImage[0],coinImage[endIndex] };
}
}
*** my problem is here : both methods have a specific type of return : array of Point or I want to change this because I want to work directly on my attribut (coinImage).
How change this in void methods ?
Help me please !
Sorry I forget one method : I also want to change the type of this method :
public Point[] unionTabPoint(Point [] P1,Point [] P2) {
Point[] res = new Point[P1.length + P2.length];
for(int i = 0; i < P1.length;i++) {
res[i] = new Point(P1[i].x,P1[i].y);
}
int k = 0;
for(int j = P1.length; j < res.length; j++) {
res[j] = new Point(P2[k].x,P2[k].y);
k++;
}
return res;
}
She return the union of two array but without specific order.
Well the basic layout for a void recursive method is like this:
int i = 0;
public void recursive(){
if(i == 6){
return;
}
i++;
recursive();
}
You can keep looping the method, as it would return the the next line, of the method that called it. In this case, the return, would reach the '}' and terminate the method, as it is finished.
Hope I helped :D
Java is doing call by reference. It is possible to use an local instance of your result and/or use it in your parameterlist, for example method(x, y, Point[]) and force the method as a result, what is your method call. Like:
public void doSome(x,y) { x==0 ? return : doSome(x-1, y-1); }
I hope this is what you looking for ...(if not pls clarify more)
public void douglasPeuckerAux(int startIndex, int endIndex) {
...
Point[] newCoinImage = new Point[] { coinImage[0],coinImage[endIndex] };
coinImage = newCoinImage;
}
public void unionTabPoint(Point [] P1,Point [] P2) {
...
coinImage = res;
}

Categories