user1687879
user1687879

Reputation: 39

How to compare arrays with duplicates as sets?

I have two arrays potentially with duplicates. I need to compare them as sets.

For example {1, 4, 9, 16, 9, 7, 4, 9, 11} is equivalent to {11, 11, 7, 9, 16, 4, 1}. I have tried a lot of ways, but I keep getting errors or wrong answers. Here is the code I have now:

import java.util.Scanner;
public class sameElement{
  public static void main(String[] args){
        int[] value1 = {11, 7, 9, 16, 4, 1};
        int[] value2 = {11, 11, 7, 9, 16, 4, 1};
   sort(value1);
   sort(value2);
   System.out.println(sameSet(value1, value2));

   }
public static boolean sameSet(int[] a, int[] b){
int j = 0;
int counter2 = 0;
for(int i = 0; i < b.length; i++){
  if(a[j] == b[i]){j++;}
  else{counter2++;};}

   }
public static int[] sort (int[] a){
  for (int i = 0; i < a.length; i++) {
    for (int i2 = i + 1; i2 < a.length; i2++){
        if (a[i] > a[i2]){
          int temp = a[i2];
          a[i2] = a[i];
          a[i] = temp;}
         }
     }
return a;
 }
}

Upvotes: 3

Views: 3545

Answers (6)

Amit Deshpande
Amit Deshpande

Reputation: 19185

Below is the code I have come with.

  1. Check the Length of array to determine which the largest.
  2. Use largest array for outer loop
  3. For each element in largest array iterate over smaller array
  4. check for each element if not found then declare as not equal.

Here is the code.

public static void main(String[] args) {

    int[] value1 = { 11, 7, 9, 16, 4, 1 };
    int[] value2 = { 11, 11, 7, 9, 16, 4, 1 };

    int[] firstArray = null;
    int[] secondArray = null;
    //Max Length Array should be used for outer loop
    if(value2.length >value1.length)
    {
        firstArray = value2;
        secondArray = value1;
    }
    else
    {
        firstArray = value1;
        secondArray = value2;
    }
    boolean equal = true;
    for (int i = 0; i < firstArray.length; i++) {
        boolean found = false;//each iteration initialise found to false
        for (int j = 0; j < secondArray.length; j++) {
            if (firstArray[i] == secondArray[j]) {
                found = true;
                break;// as there is no point running the loop
            }

        }
        if (!found) {
            equal = false;//check after each iteration if found is false if false arrays are not equal and break
            break;
        }

    }
    System.out.println(equal);


}

Upvotes: 0

Adam
Adam

Reputation: 36703

TreeSet is a an sorted set, so it will do the sort and duplicate removal your're after for free. So all you have to do is load your arrays into it and then use .equals().

Integer[] value1 = { 11, 7, 9, 16, 4, 1 };
Integer[] value2 = { 11, 11, 7, 9, 16, 4, 1 };

Set<Integer> tSet1 = new TreeSet<Integer>(Arrays.asList(value1));
Set<Integer> tSet2 = new TreeSet<Integer>(Arrays.asList(value2));

System.out.println(tSet1);
System.out.println(tSet2);

System.out.println(tSet1.equals(tSet2));

Output

[1, 4, 7, 9, 11, 16]
[1, 4, 7, 9, 11, 16]
true

Upvotes: 5

PermGenError
PermGenError

Reputation: 46408

        int[] value1 = {11, 7, 9, 16, 4, 1};
        int[] value2 = {11, 11, 7, 9, 16, 4, 1};
        HashSet<Integer> set = new HashSet<Integer>();
        HashSet<Integer> set2 = new HashSet<Integer>();

           for(int i=0; i<value1.length;i++) {
                  set.add(value1[i]);
           }
        for(int j=0; j<value2.length; j++) {
                 set2.add(value2[j]);
           }
          now do the sorting and compare both the sets

Upvotes: 0

Azodious
Azodious

Reputation: 13872

I've modified your sameSet method and it doesn't require your arrays to be sorted and takes care of duplicates without removing them.

public static boolean sameSet(int[] a, int[] b)
{
    for (int i = 0; i < a.length; i++)
    {
        boolean match = false;
        for (int j = 0; j < b.length; j++)
        {
            if (a[i] == b[j])
            {
                match = true;
                break;
            }
        }
        if (!match)
            return false;
    }
    return true;
}

I has a lot of room to be optimized but at present serves the purpose.

Upvotes: 0

user180100
user180100

Reputation:

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.util.HashSet;
import java.util.Set;


public class Test {
    public static class SameElement {
        /**
         * Constructor.
         */
        private SameElement()
        {
            // avoid instatiation
        }

        /**
         * Check if the provided 2 arrays have the same elements ignoring order and duplicates
         * 
         * @param val1 1st array
         * @param val2 2nd array
         * @return true if so.
         */
        public static boolean sameSet(int[] val1, int[] val2)
        {
            return toSet(val1).equals(toSet(val2));
        }

        /**
         * Transform provided array of int into a {@link Set} of {@link Integer}.
         * 
         * @param vals Array of int to use
         * @return a {@link Set} of {@link Integer} (empty if vals is null)
         */
        private static Set<Integer> toSet(int[] vals)
        {
            final Set<Integer> set = new HashSet<Integer>();
            if (vals != null) {
                for (final int i : vals) {
                    set.add(i);
                }
            }
            return set;
        }
    }

    @org.junit.Test
    public void testSameSet()
    {
        int[] value1 = { 11, 7, 9, 16, 4, 1 };
        int[] value2 = { 11, 11, 7, 9, 16, 4, 1 };
        int[] value3 = { 8, 11, 11, 7, 9, 16, 4, 1 };
        assertTrue(SameElement.sameSet(value1, value2));
        assertFalse(SameElement.sameSet(value3, value1));
        assertFalse(SameElement.sameSet(value3, value2));
        assertFalse(SameElement.sameSet(null, value2));
        assertFalse(SameElement.sameSet(value1, null));
        assertTrue(SameElement.sameSet(null, null)); // check against your requirements
    }
}

Upvotes: 1

basiljames
basiljames

Reputation: 4847

Use Arrays.sort to sort your arrays.

Upvotes: 1

Related Questions