Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if all duplicates in an array are grouped

I want to check if all similar integers in an array or list are grouped. {2, 2, 5, 5, 5, 1, 7, 7, 5, 7} should give false. While {2, 2, 5, 5, 5, 1, 7, 7, 7} should give true. This is what I have so far and it prints true when it should be false:

public class testing1 {

  public static void main(String[] args){
    int [] x = {2, 2, 5, 5, 5, 1, 7, 7, 5, 7};
    System.out.println(isGrouped(x));

  }

  public static boolean isGrouped(int[] x){
    for(int i = 0; i < x.length; i++){
      for(int j = i + 1; j < x.length; j++){
        if(x[i] == x[j]) 
          return true;
      }
    }
    return false;
  }
}
like image 316
John P. Avatar asked Mar 09 '23 02:03

John P.


1 Answers

Your answer, as mentioned in other answers does not take care of all the cases and hence will not work for a number of cases. Also, you don't need 2 loops here. You could store the already seen elements in a hash and for every element in the list if it appears for the first time or not. If it's not appearing for the first time and if the previous element is not the same as this, then it should be false.

Here is the code:

public class testing1 {

  public static void main(String[] args){
    int [] x = {2, 2, 5, 5, 5, 1, 7, 7, 5, 7};
    System.out.println(isGrouped(x));
  }

  public static boolean isGrouped(int[] x){

      int prev = x[0] ;

    Hashtable<Integer, Integer> hashtable = 
              new Hashtable<Integer, Integer>();
    hashtable.put(x[0], 0);
    for (int i = 1 ; i < x.length ; i ++)
    {
        if (hashtable.get(x[i]) != null && prev == x[i]){
            hashtable.put(x[i], hashtable.get(x[i]) + 1);
        }

        else if (hashtable.get(x[i]) != null && prev != x[i]){
            return false;
        }

        else{
            hashtable.put(x[i], 0);
        }
        prev = x[i];
    }
    return true ;
    }

}

This also stores the count of the number of occurrences of each element. Hope this helps :)

like image 69
Rajesh d m Avatar answered Apr 02 '23 16:04

Rajesh d m