Code for searching similar entires in multiple two-dimensional arrays - java

I´m trying to write the code for the problem described in my previous topic. The suggested solution was to use hashmaps to find similar entries in multiple arrays (arrays have the same number of columns, but they might have different number of rows).
Below is my sample code based on a code snippet of the user John B provided here. For simplicity and for debugging purpose, I created just 3 different one-dimensional rows instead of two-dimensional arrays. Also, for simplicity, the function equalRows should return true or false instead of row indexes.
So, in the below code the function equalRows should return false, because array3 has {1,3,4} and it does have {1,2,3}. Instead the function returns true. Why does it happen?
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) {
int[] array1 = {1,2,3};
int[] array2 = {1,2,3};
int[] array3 = {1,3,4};
boolean answ = equalRows(array1,array2,array3);
System.out.println(answ);
}
static class Row extends Object {
private int value;
private volatile int hashCode = 0;
public Row(int val) {
this.value = val;
}
#Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if((obj == null) || (obj.getClass() != this.getClass()))
return false;
// object must be Row at this point
Row row = (Row)obj;
return (value == row.value);
}
#Override
public int hashCode () {
final int multiplier = 7;
if (hashCode == 0) {
int code = 31;
code = multiplier * code + value;
hashCode = code;
}
return hashCode;
}
}
private static Map<Row, Integer> map(int[] array) {
Map<Row, Integer> arrayMap = new HashMap<Row, Integer>();
for (int i=0; i<array.length; i++)
arrayMap.put(new Row(array[i]), i);
return arrayMap;
}
private static boolean equalRows(int[] array1, int[] array2, int[] array3){
Map<Row, Integer> map1 = map(array1);
Map<Row, Integer> map2 = map(array2);
for (int i=0; i<array3.length; i++){
Row row = new Row(array3[i]);
Integer array1Row = map1.get(row);
Integer array2Row = map2.get(row);
if (array1Row != null || array2Row != null) {
return false;
}
}
return true;
}
}
Edit#1
Code is updated subject to suggested solution.
Edit#2
I checked out the suggested solution, but the function returns false even for: int[] array1 = {1,2,3}; int[] array2 = {1,2,3}; int[] array3 = {1,2,3}, although it should be true. I think the problem is with the function hashcode. So, any solution?

This line is wrong, it immediately returns true:
if (array1Row != null && array2Row != null) {
return true;
}
What you must do is this (completely invert the logic):
if (array1Row == null || array2Row == null) {
return false;
}

It is only getting as far as testing the first element in each array and returning true because they match.
You need to return false if any fail to match and then return true if there are no failures.
I'd also put a test of the lengths at the start of the equalRows method.

Related

Writing an equals method to compare two arrays

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);
}

Comparing the values of two arrays using recursion?

I am trying to check if two arrays have the same length, and the same values in the same exact position.
My current code looks like this:
public class MyArray {
private int size;
private int[] array;
private boolean isSorted; //to check if array is sorted
private static int arrCount; //used to identify which MyArray object
public MyArray(){
size = 10;
array = new int[10];
arrCount+=1;
}
public MyArray(int Size){
size = Size;
array = new int[Size];
arrCount+=1;
}
public MyArray(MyArray arrOther){
this.size = arrOther.getSize();
this.array = arrOther.getArray();
arrCount+=1;
}
public int getSize(){
return size;
}
public int[] getArray(){
return array;
}
#Override
public boolean equals(Object other){
if (other instanceof MyArray){
MyArray second = (MyArray) other;
if (second.getSize() == this.getSize())
return equalsHelper(this.getArray(), second.getArray(), 0, (size-1));
}
//else
return false;
}
private boolean equalsHelper(int[] first, int[] second, int iStart, int iEnd) {
if (iStart == iEnd) {
return true;
}
if (first[iStart] == second[iStart]) {
if (equalsHelper(first, second, (iStart + 1), iEnd)) {
return true;
}
}
return false;
}
}//end class
for some reason it always returns true even if the arrays are in different order.
the equals method is called in the main program here:
--main method--
if (MA2.equals(MA1)) //the arrays are identical here
{
System.out.println("The first and second arrays are equal.");
}
else {System.out.println("The first and second arrays are NOT equal.");}
MA2.sort(); //the order of the elements changes
System.out.println("The second array has been sorted in ascending order.");
if (MA2.equals(MA1))
{
System.out.println("The first and second arrays are equal.");
}
else {System.out.println("The first and second arrays are NOT equal.");}
First check (preferably) outside of your helper should be to see if both the arrays have equal lengths. Makes no sense to continue otherwise.
equalsHelper should return true if end of array is reached.
I see no reason to have 2 separate pointers for index since the arrays are required to be of the same size and the same index is being checked.
Invocation:
....
....
if(first.length != second.length)
return false;
return equalsHelper(first, second, 0);
The helper method...
private boolean equalsHelper(int[] first, int[] second, int indx) {
if(indx == first.length)
return true;
if(first[indx] != second[indx)
return false;
return equalsHelper(first, second, indx+1);
}
Firstly, iStart and iEnd are redundant. use .length
String[] array = new String[10];
int size = array.length;
If you're trying to compare contents of arrays that may be identical, you need to pass through it manually.
for(int i = 0: (i > first.length || i > second.length; i++){
if(first[i] != second[i]){
return false;
}
}
return true
Your next problem is
if (iStart == iEnd){
return first[iEnd] == second[iEnd]; //return true or false
Your logic here is wrong. You can't directly compare arrays like this. It's comparing the memory address. This will always be false unless you pass through the exact same array when the method is called - which i don't think is what you're trying to do
Array lengths are set manually, so it's a conscious effort to get a difference.
Let me suggest using an ArrayList if you're expecting differing lengths. They're also more flexible.
ArrayList <Integer> a = new ArrayList <int>();
ArrayList <Integer> b = new ArrayList <int>();
Then you'll need to check their lengths. ArrayList uses the .length() method instead of an Array[].length property
if(a.length() == b.length()){
then if you want to see if each value in each index is identical, you'll need to pass through the array manually as shown above.

.contains() method not working -- finding an int in array Java

I have been looking for hours, all over the internet and SO, but cannot find anything that I understand! ( Very new at Java )
Upon compiling, it cannot find symbol of the contain method.
Here is the code:
public class LotteryTicket {
private String nameOfBuyer;
private int[] numberList;
private boolean search(int val) {
if (val >= 1 && val <= 50) {
if (numberList.contains(val)) {
return true;
} else {
return false;
}
}
}
I am very new at learning, and I do not know why this is happening.
int[] is a primitive array and does not have a method .contains(). If you used List<Integer> instead, that would give you a .contains() method to call.
Also, your search method must return a value even when val < 1 or val > 50.
If you need numberList to be an int[], you could try this:
private boolean search(int val) {
if (numberList != null && val >= 1 && val <= 50) {
for(int number : numberList) {
if (number == val) {
return true;
}
}
}
return false;
}
Or, you could do this:
private boolean search(int val) {
if (numberList != null && val >= 1 && val <= 50) {
return Arrays.asList(numberList).contains(val);
}
return false;
}
The List interface defines the method contains. Think of an interface as a contract that classes can "sign" (in Java this is done with the keyword implements) which says that the class must have certain things in its implementation. A very common implementation of the List interface is ArrayList, but Lists do not work very well with the primitive int type, so what you want to do is make an ArrayList of Integers.
The simplest way to make an ArrayList of Integers is to make an array of Integers first (I know, Java has a lot of weird steps required to get things working).
In addition, you want to make sure that boolean methods always return a boolean value or you will get a compiler error.
Here's a working example:
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
public class LotteryTicket {
private String nameOfBuyer;
private List<Integer> numberList;
private boolean search(int val) {
return (val >= 1 && val <=50) && numberList.contains(val);
}
public static void main(String[] args) {
LotteryTicket lt = new LotteryTicket();
Integer[] numberList = new Integer[] {2, 3, 4, 5, 42, 6};
lt.numberList = new ArrayList<Integer>(Arrays.asList(numberList));
System.out.println(lt.search(42)); // prints "true\n"
System.out.println(lt.search(25)); // prints "false\n"
}
}

issue with Arrays.asList()

I have a very simple program and I just need to check an array for a value in it.
I have a class called bulkBean. this is it.
public class bulkBean {
private int installmentNo;
private double amount;
public int getInstallmentNo() {
return installmentNo;
}
public void setInstallmentNo(int installmentNo) {
this.installmentNo = installmentNo;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
}
Now I have an array of this bulkBean type in my program, this is my program.
import java.util.Arrays;
public class test {
public static boolean scan_bulkList(bulkBean[] bulkList, int i) {
int[] arr = new int[bulkList.length];
for(int x=0;x<bulkList.length;x++){
arr[x] = bulkList[x].getInstallmentNo();
}
for(int j = 0; j< arr.length ;j++){
System.out.println("INFO: array "+j+" = "+arr[j]);
}
if (Arrays.asList(arr).contains(i) == true) {
return true;
} else {
return false;
}
}
public static void main(String[] arg){
bulkBean bb1 = new bulkBean();
bb1.setInstallmentNo(1);
bb1.setAmount(5500);
bulkBean bb2 = new bulkBean();
bb2.setInstallmentNo(2);
bb2.setAmount(4520);
bulkBean[] bulkArray = new bulkBean[2];
bulkArray[0] = bb1;
bulkArray[1] = bb2;
boolean a = scan_bulkList(bulkArray,1);
System.out.println("val = "+a);
}
}
I create 2 instances of bulk bean and I set values to them. Then I added those two instances to an array. Then I pass that array to the method to check for a value(also given as a parameter. In this case it is 1.). If the array contains that value, it should return true, otherwise false.
whatever value I enter, it return false.
Why do I get this issue?
Arrays.asList() returns a List which has a single element - an array. So, you are actually comparing against an array. You need to compare against each value in the array.
As TheListMind told, Arrays.asList() taken on an int[] gives you a list containing the array.
Personally, I would construct directly the List instead of constructing the array, or even better (no need of array instanciation), test while iterating the bulk array :
for(int x=0;x<bulkList.length;x++){
if (bulkList[x].getInstallmentNo() == i){
return true;
}
}
return false;
The mistake you made here is , you created the int array which must be Integer array because Arrays.asList().contains(Object o); makes the input parameter also Integer(Integer i). int is not an object Integer is the object. Hope it will work.
int[] arr = new int[bulkList.length];
change to:
Integer[] arr = new Integer[bulkList.length];
Change the method as below to avoid complications:
public static boolean scan_bulkList(bulkBean[] bulkList, int i) {
int[] arr = new int[bulkList.length];
for(int x=0;x<bulkList.length;x++){
arr[x] = bulkList[x].getInstallmentNo();
if (bulkList[x].getInstallmentNo()==i) {
return true;
}
}
return false;
}

How do you declare an array where user can specify dimension?

I want a function / data structure that can do this:
func(int dim){
if(dim == 1)
int[] array;
else if (dim == 2)
int[][] array;
else if (dim == 3)
int[][][] array;
..
..
.
}
anyone know how?
Edit
Or you could use Array.newInstance(int.class, sizes). Where sizes is an int[] containing the desired sizes. It will work better because you could actually cast the result to an int[][][]...
Original Answer
You could use the fact that both int[] and Object[] are Objects. Given that you want a rectangular multidimensional array with sizes given by the list sizes
Object createIntArray(List<Integer> sizes) {
if(sizes.size() == 1) {
return new int[sizes.get(0)];
} else {
Object[] objArray = new Object[sizes.get(0)];
for(int i = 0; i < objArray.length; i++) {
objArray[i] = createIntArray(sizes.subList(1, sizes.size());
}
return objArray;
}
}
You lose all static type checking, but that will happen whenever you want a dynamically dimensioned array.
If your purpose is to create a truly dynamic array, then you should look at the Array object in the JDK. You can use that to dynamically generate an array of any dimension. Here is an example:
public void func(int dim) {
Object array = Array.newInstance(int.class, new int[dim]);
// do something with the array
}
Once the array Object has been created, you can use the methods of the java.lang.reflect.Array class to access, add, remove elements from the multi-dimension array that was created. In also includes utility methods to determine the length of the array instance.
You can even check the dimension of the array using:
public int getDimension(Object array) {
int dimension = 0;
Class cls = array.getClass();
while (cls.isArray()) {
dimension++;
cls = cls.getComponentType();
}
return dimension;
}
People have post good solutions already, but I thought it'd be cool (and good practice) if you wrap the dynamic multidimensional array into a class, which can use any data structure to represent the multi-dimensional array. I use hash table so you have virtually unlimited size dimensions.
public class MultiDimArray{
private int myDim;
private HashMap myArray;
public MultiDimArray(int dim){
//do param error checking
myDim = dim;
myArray= new HashMap();
}
public Object get(Integer... indexes){
if (indexes.length != myDim){throw new InvalidArgumentException();}
Object obj = myArray;
for (int i = 0; i < myDim; i++){
if(obj == null)
return null;
HashMap asMap = (HashMap)obj;
obj = asMap.get(indexes[i]);
}
return obj;
}
public void set(Object value, Integer... indexes){
if (indexes.length != myDim){throw new InvalidArgumentException();}
HashMap cur = myArray;
for (int i = 0; i < myDim - 1; i++){
HashMap temp = (HashMap)cur.get(indexes[i]);
if (temp == null){
HashMap newDim = new HashMap();
cur.put(indexes[i], newDim);
cur = newDim;
}else{
cur = temp;
}
}
cur.put(indexes[myDim -1], value);
}
}
and you can use the class like this:
Object myObj = new Object();
MultiDimArray array = new MultiDimArray(3);
array.put(myObj, 0, 1, 2);
array.get(0, 1, 2); //returns myObj
array.get(4, 5, 6); //returns null
What about a class like following?
class DynaArray {
private List<List> repository = new ArrayList<List>();
public DynaArray (int dim) {
for (int i = 0; i < dim; i++) {
repository.add(new ArrayList());
}
}
public List get(int i) {
return repository.get(i);
}
public void resize(int i) {
// resizing array code
}
}

Categories