Пример #1
0
  /**
   * Count the common keys between two vectors.
   *
   * @param o The other vector.
   * @return The number of keys appearing in both this and the other vector.
   */
  public int countCommonKeys(SparseVector o) {
    int count = 0;
    Iterator<VectorEntry> i1 = fastIterator();
    Iterator<VectorEntry> i2 = o.fastIterator();

    VectorEntry e1 = i1.hasNext() ? i1.next() : null;
    VectorEntry e2 = i2.hasNext() ? i2.next() : null;

    while (e1 != null && e2 != null) {
      final long k1 = e1.getKey();
      final long k2 = e2.getKey();
      if (k1 < k2) {
        e1 = i1.hasNext() ? i1.next() : null;
      } else if (k2 < k1) {
        e2 = i2.hasNext() ? i2.next() : null;
      } else {
        count += 1;
        e1 = i1.hasNext() ? i1.next() : null;
        e2 = i2.hasNext() ? i2.next() : null;
      }
    }
    return count;
  }
Пример #2
0
  /**
   * Compute the dot product between two vectors.
   *
   * @param o The other vector.
   * @return The dot (inner) product between this vector and {@var o}.
   */
  public double dot(SparseVector o) {
    double dot = 0;

    Iterator<VectorEntry> i1 = fastIterator();
    Iterator<VectorEntry> i2 = o.fastIterator();

    VectorEntry e1 = i1.hasNext() ? i1.next() : null;
    VectorEntry e2 = i2.hasNext() ? i2.next() : null;

    while (e1 != null && e2 != null) {
      final long k1 = e1.getKey();
      final long k2 = e2.getKey();
      if (k1 < k2) {
        e1 = i1.hasNext() ? i1.next() : null;
      } else if (k2 < k1) {
        e2 = i2.hasNext() ? i2.next() : null;
      } else {
        dot += e1.getValue() * e2.getValue();
        e1 = i1.hasNext() ? i1.next() : null;
        e2 = i2.hasNext() ? i2.next() : null;
      }
    }
    return dot;
  }