News for hackers. Stuff that matters.
Re:Puzzle: LgN algorithm for Index == Value by spaghetti on Saturday April 11, 2009 @11:41PM (#558129)
bool f(vector<int> v){

/* use 0-based indice*/ int lowerBound = 0; int upperBound = v.size() - 1;

while(1){

		if(lowerBound == upperBound) return v[lowerBound] == lowerBound;
		
		int i = lowerBound + (upperBound - lowerBound) / 2;
		
		if(v[i] == i){
			
			return true;
			
		}else if(v[i] < i){
			
			lowerBound = i + 1;
			
		}else if(v[i] > i){
			
			upperBound = i - 1;
			
		}
	}
}
Re:Puzzle: LgN algorithm for Index == Value by shrughes on Saturday April 11, 2009 @11:58PM (#558145)
Typo alert! You meant

    int i = lowerBound + (upperBound - lowerBound) / 2;
Re:Puzzle: LgN algorithm for Index == Value by spaghetti on Sunday April 12, 2009 @12:14AM (#558163)
ok corrected. thanks.
Re:Puzzle: LgN algorithm for Index == Value by bf on Monday April 13, 2009 @02:04AM (#559469)
Your function crashes when passed an empty vector. Defensive programming please! :-)
Re:Puzzle: LgN algorithm for Index == Value by spaghetti on Monday April 13, 2009 @11:30PM (#560944)
good point. add

    if(v.size() == 0) return false;
Re:Puzzle: LgN algorithm for Index == Value by bf on Monday April 13, 2009 @02:07AM (#559475)
And don't get me started with passing by value! Okay, I'll stop being a dick.