Skip to content

Instantly share code, notes, and snippets.

@dkohlsdorf
Last active March 18, 2019 23:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dkohlsdorf/6b515e211508ed99cee7 to your computer and use it in GitHub Desktop.
Save dkohlsdorf/6b515e211508ed99cee7 to your computer and use it in GitHub Desktop.
Interview Question Sparse Vector
//Given two sparse vectors. Write a function to find a dot product of these vectors.
// [0,4,0,0,1,0,0,10,0]
// [2,0,0,0,3,0,0,0,0]
// 3
x = (4, 1), (1, 4), (10, 7)
y = (2, 0), (3, 4)
public int dot(double[] x, double[] y) throws Exception {
if(x.length != y.length) {
throw new Exception("Error in dot product: x and y are not of equal length");
}
double dotproduct = 0;
for(int i = 0; i < x.length; i++) {
dotproduct += x[i] * y[i];
}
return dotproduct;
}
class SparseVectorEntry {
private int position;
private int value;
public SparseVectorEntry(int value, int position) {
this.position = position;
this.value = value;
}
public int getPosition() {
return position;
}
public int getValue() {
return value;
}
public void setPosition(int position) {
this.position = position;
}
public void setValue(int value) {
this.value = value;
}
}
x = (4, 1), (1, 4), (10, 7)
y = (2, 0), (3, 4)
public int dot(SparseVectorEntry[] x, SparseVectorEntry[] y) {
int pointerX = 0;
int pointerY = 0;
double dotproduct = 0;
while(pointerX < x.length && pointerY < y.length) {
if(x[pointerX].getPosition() < y[pointerY].getPosition()) {
pointerX++;
} else if(x[pointerX].getPosition() > y[pointerY].getPosition()) {
pointerY++;
} else {
dotproduct += x[pointerX].getValue() * y[pointerY].getValue();
positionX++;
positionY++;
}
}
return dotproduct;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment