Count distinct elements in a VectorTag(s): Language


Submitted by T GUIRADO
/**
  ** This method counts distinct elements from a given position in vector
  ** containing series of element.
  ** Arguments : source   = vector containing the vectors of elements
  **             position = which element to search, first position = 0
  **             count    = serie length
  **
  ** ex :
  ** source = A,B,C  D,E,F  D,F,G
  ** length is 3
  ** from position 0 in each series we have  A,D,D
  ** this method returns 2 because there are 2 distinct elements (A and D)
  ** from position 2 in each series we have  C,F,G
  ** this method returns 2 because there are 3 distinct elements (C,FandG)
  **/
  protected synchronized int countDistinctElements
      (Vector source,int position,int count){
    Vector v = null;
    for (int i = 0 ; i < source.size() ; i++) {
      boolean isFound = false;
      if ( i % count == position ) {
        if ( null != v ) {
          for (int j = 0 ; j < v.size() ; j++) {
            if ( source.elementAt(i).equals(v.elementAt(j) ) ) {
              isFound = true;
              j = v.size();
            }
          }
        }
        if ( !isFound ) {
          if ( null == v ) v = new Vector(1, 1);
          v.addElement( (String)source.elementAt(i) );
        }
        i += count - position;
      }
    }
    try {
       return v.size();
    }
    catch ( Exception e ) {
       return 0;
    }
  }
Submitted by bdobby2000
protected static int countDistinctElements ( Vector source, int position, int count )
   throws IllegalArgumentException , IndexOutOfBoundsException
{
  List list = source.subList(position, position+count);
  Set set = new HashSet();
  set.addAll(list);
  return set.size();
}

blog comments powered by Disqus