Example #1
0
void Solver::guess(int index) { //Where slot=0-80
	Sudoku s = Sudoku();
	s.setField(_field);
	s.print();
	usleep(300);
	bool succes = false;
	for (int option : missing[index]) {
		if (_field.get(index) >= option) { // We have tried this slot before
			continue;
		}
		if (_field.fit(index, option)) {
			_field.set(index, option);
			succes = true;
			break;
		}
	}
	if (succes) {
		if (_field.countEmpty(true) > 0) {
			// Find the the next empty slot in the vector
			int curIndex = std::distance(emptySlots.begin(), std::find(emptySlots.begin(), emptySlots.end(), index));
			guess(emptySlots.at(curIndex + 1));
		} else {
			return;
		}
	} else {
		_field.set(index, 0);
		// Find the the previous tried slot in the vector
		int curIndex = std::distance(emptySlots.begin(), std::find(emptySlots.begin(), emptySlots.end(), index));
		guess(emptySlots.at(curIndex - 1));
	}
}
Example #2
0
bool GameManager::gamePlay(int index,int qType,bool &gameOver){
    int turn=0;
    
    if(turn==0){
        //Computer's turn
        if(computer==-1){//i.e. if card not yet chosen
            //Randomly choose person card
            computer = rand()%24;
            turn+=1;
        }else{
            turn+=1;//Next player's turn
            return guess(turn,index,qType,gameOver);
        }
    }else{
        //User's turn
        if(user==-1){//i.e. if card not yet chosen
            //Randomly choose person card
            bool same;//test to see if user card chosen is same as computer
            do{
                same=false;
                user = rand()%24;
                if(user==computer){
                    same = true;
                }
            }while(same);
            turn-=1;
        }else{
            turn-=1;//Next player's turn
            return guess(turn,index,qType,gameOver);
        }
    }
}
Example #3
0
int guess(int l,int r,int s)
{
    if(l==r && l==s)
        return 1;
    if(diff==-1)
    {
        int m=(l+r)/2;
        diff=fabs(s-m);
        if(diff==0)
            return 0;
        return guess(l,r,s);
    }
    else
    {
        int m1=l+(r-l+1)/4,m2=l+(3*(r-l+1))/4,m=(l+r)/2;
        int d1=fabs(s-m1),d2=fabs(s-m2);
        if(d1==0 || d2==0)
            return 1;
        if(d1<=diff)
                return 1+guess(l,m-1,s);
        else
        {
            if(d2>d1)
                return 2+guess(l,m-1,s);
            else
                return 2+guess(m+1,r,s);
        }

    }
}
 int guessNumber(int n) {
     int l=0, r=n, m;
     while(l<=r) {
         m = (r-l)/2+l;
         if(guess(m) == 0) return m;
         else if(guess(m)==-1) r=m-1;
         else if(guess(m)==1) l=m+1;
     }
     return -1;
 }
Example #5
0
 int guessNumber(int n) {
     int left = 1, right = n+1;
     int mid = left+(right-left)/2;
     while (mid!=right && guess(mid)!=0) {
         if (guess(mid)==-1)
             right = mid;
         else
             left = mid+1;
         mid = left+(right-left)/2;
     }
     return mid;
 }
 int guessNumber(int n) {
 	int low = 1, high = n;
 	int mid;
 	while(low < high) {
         mid = low +(high - low)/2; 
 		if(guess(mid) == 0)
 			return mid;
 		else if(guess(mid) == -1)
 			high = mid-1;
 		else
 			low = mid +1;
 	}
 	return low;
 }
Example #7
0
 int guessNumber(int n) {
     if (guess(n) == 0) 
         return n;
     int begin = 1, end = n;
     while (begin < end) {
         //We cannot use (begin + end)/2 here!
         int mid = begin + (end - begin) / 2, index = guess(mid);
         if (index == 0)
             return mid;
         else if (index == 1) begin = mid;
         else end = mid;
     }
     return begin;
 }
Example #8
0
 /**
  * @param n: An integer
  * @return: how much money you need to have to guarantee a win
  */
 int guess(vector<vector<int>>& dp, int s, int e) {
     if(s >= e) {
         return 0;
     }
     if(dp[s][e] != 0) {
         return dp[s][e];
     }
     int res = INT_MAX;
     for(int i = s; i <= e; i++) {
         res = min(res, i + max(guess(dp, s, i - 1), guess(dp, i + 1, e)));
     }
     dp[s][e] = res;
     return res;
 }
 int guessNumber(int n) {
     long long int l = 1, r = n;
     while (l <= r)
     {
         long long int mid = (l+r) >> 1;
         if (guess(mid) == 0)
             return mid;
         else if (guess(mid) == 1)
             l = mid + 1;
         else
             r = mid - 1;
     }
     return l;
 }
//利用二分查找,根据guess的返回值判断是在上半部分还是下半部分
int guessNumber(int n) {
    long begin=1,end=n,mid=(begin+end)/2;
    int check=guess(mid);
    while(check!=0 && begin<=end){
        if(check>0){
            begin=mid+1;
        }else{
            
            end=mid-1;
        }
        mid=(begin+end)/2;
        check=guess(mid);
    }
    return mid;
}
	int guessNumber(int n) {
		size_t left = 1, right = n;
		while (guess(right) > 0) right <<= 1;
		if (guess(right) == 0) return right;
		while (left + 1 < right) {
			size_t mid = left + (right - left) / 2;
			int x = guess(mid);
			if (x == 0) return mid;
			if (x < 0) right = mid;
			if (x > 0) left = mid;
		}
		if (guess(left) == 0) return left;
		if (guess(right) == 0) return right;
		return -1;
	}
 int guessNumber(int n) {
     int start = 1;
     int end = n;
     while(start <= end){
         int mid = start + (end - start)/2;
         if(guess(mid) == 0) return mid;
         else if (guess(mid) == 1) {
             start = mid + 1;
         }
         else {
             end = mid - 1;
         }
     }
     return start;
 }
Example #13
0
int main(int argc, const char * argv[]) {
    //-------------- Problem 1
//    problem1(20);
  
    
    // -------------- Problem 2
    int dim = 40;
    mVector res(dim);
    mVector guess(dim);
    for (int i = 0; i != dim; i++) {
        guess[i] = 1;
    }
    Matrix A = CreateHilbertMatrix(dim);
    mVector b = CreateHilbertRHS(dim);
    for (int i = 20; i <= 200 ; i += 10) {
        int dim = i;
        mVector res(dim);
        mVector guess(dim);
        for (int i = 0; i != dim; i++) {
            guess[i] = 1;
        }
        Matrix A = CreateHilbertMatrix(dim);
        mVector b = CreateHilbertRHS(dim);
        std::cout << dim << ",";
        std::cout << CGSolver(A, b, res, guess, 10E-14, 200) << "\\\\" <<endl;
    }
//    std::cout << CGSolver(A, b, res, guess, 10E-14, 100) << endl;
//    std::cout << res;
    

    // --------------Problem 3
//    Matrix prob3(5,5);
//    prob3 = {10,1,2,3,4,1,9,-1,2,-3,2,-1,7,3,-5,3,2,3,12,-1,4,-3,-5,-1,15};
//    mVector rhs3(5);
//    rhs3 = {12,-27,14,-17,12};
//    mVector res3(5);
//    mVector guess3(5);
//    mVector Jacobi(5);
//    mVector GS(5);
//    double precision = 10E-5;
//    std::cout <<"CG: " <<CGSolver(prob3, rhs3, res3, guess3, precision, 100) << std::endl;
//    std::cout << res3;
//    std::cout <<"Jacobi: "<< IterativeMethods::JacobiSolve(prob3, rhs3, guess3, Jacobi, precision) << std::endl;
//    std::cout << Jacobi;
//    std::cout << "GS: " << IterativeMethods::GaussSolve(prob3, rhs3, guess3, GS, precision) << std::endl;
//    std::cout << GS;
    return 0;
}
Example #14
0
void
eval_factor(void)
{
	push(cadr(p1));
	eval();

	push(caddr(p1));
	eval();

	p2 = pop();
	if (p2 == symbol(NIL))
		guess();
	else
		push(p2);

	factor();

	// more factoring?

	p1 = cdddr(p1);
	while (iscons(p1)) {
		push(car(p1));
		eval();
		factor_again();
		p1 = cdr(p1);
	}
}
Example #15
0
//function to recursively solve sudoku oldgrid by guessing and backtracking
int guess(char oldgrid[9][9][10]) {
	char i,j,k;
	for(i=0;i<9;++i)
		for(j=0;j<9;++j)
			if(!oldgrid[i][j][0])
				for(k=1;k<10;++k)
					if(oldgrid[i][j][k]) {
						char newgrid[9][9][10];
						//guessing
						guessed(oldgrid,newgrid,i,j,k);
						//solving according to guess
						solve(newgrid);
						//checking if solved
						if(solved(newgrid)) {
							output(newgrid);
							return 1;
						}
						//guessing recursively
						if(guess(newgrid))
							return 1;
						//eliminating guess
						oldgrid[i][j][k]=0;
						solve(oldgrid);
					}
	return 0;
}
Example #16
0
// ----------------------------------------------------------------------------
// takeGuess(string guessInput)
//
// Creates new guess from provided input string and then determines if guess
// was a letter or word and runs corresponding guest function.
// If guess was correct and solves puzzle returns 1, if guess was correct and
// puzzle is not solved returns 0, if guess was incorrect updates pieces of
// man and returns 0.
// ----------------------------------------------------------------------------
bool Game::takeGuess(string guessInput)
{
	// Create new guess from input
	Guess guess(guessInput);
	// Store guess in players guess list
	player.addGuess(guess);

	// Flag for any correct letters guessed
	int correct = 0;

	// If input guess length was equal to 1
	if (guess.getGuess().length() == 1)
		// Attempt to guess a letter
	if (guessLetter(guess))
		// Flag if guess was correct
		++correct;

	// If input guess length was greater than 1
	if (guess.getGuess().length() > 1)
		// Attempt to guess answer with input
	if (guessWord(guess))
		return 1;

	// If player.partialAnswerString now equals answer return 1
	if (guessWord(player.getPartialAnswerString()))
		return 1;

	// Add a piece to man if guess was incorrect
	if (!correct)
		man.addPiece();

	return 0;

}
Example #17
0
int main()
{
    uart_init();
    char in[40]; // input buffer
    while(1)
    {
        if(!gameStarted) 
            intro();
        unsigned int theGuess = randInt(lowerBound, upperBound);
        guess(theGuess);
        read_echo(in);
        if(in[0] == 'h')
            lowerBound = theGuess;
        else if(in[0] == 'l')
            upperBound = theGuess;
        else if(in[0] == 'y')
        {
            printLine("I win");
            gameStarted = 0;
            printLine("press any key to continue...");
            uart_receive();
        }
        else if(isReset(in))
        {
            gameStarted = false;
            printLine("press any key to continue...");
            uart_receive();
        }
   }
}
Example #18
0
void
eval_draw(void)
{
	F = cadr(p1);
	T = caddr(p1);

	if (T == symbol(NIL)) {
		push(F);
		rewrite();
		guess();
		T = pop();
		F = pop();
	}

	push(get_binding(T));
	push(get_arglist(T));

	draw_main();

	p2 = pop();
	p1 = pop();
	set_binding_and_arglist(T, p1, p2);

	// return value

	push(symbol(NIL));
}
Example #19
0
void RecursiveSolver::solve(Sudoku& sudoku) {
	this->_field = sudoku.getField();
	options = findMissing();
	
	for(map<int,vector<int>>::iterator it = options.begin(); it != options.end(); ++it) {
		cout << it->first << " " << ": ";
		for (vector<int>::iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) {
			cout << *it2 << ", ";
		}
		cout << endl;
	}
	map<int,vector<int>>::iterator it = options.begin();
	count = 0;
	
	int status = -1;
	do {
		status = guess(it->first);
		switch(status) {
		case RETURN_NEXT:
			it = std::next(it);
			break;
		case RETURN_PREV:
			it = std::prev(it);
			break;
		}
	} while(status != RETURN_EXIT);
	
	
	sudoku.setField(_field);
}
Example #20
0
int main(void)
{
	int secret;
	create(&secret);
	guess(secret);
	return 0;
}
Example #21
0
int guess(int cell)
{
	int num;
	if (cell >= 81) return TRUE;
	if (board[cell]) return guess(cell+1);
	for (num=1; num<10; num++)
	{
		if (check(cell, num))
		{
			board[cell] = num;
			if (guess(cell+1)) return TRUE;
		}
	}
	board[cell] = 0;
	return FALSE;
}
Example #22
0
int main( int argc, char const *argv[] )
{
	// Used in old random method
	// init();
	// For the number of  words guessed
	int i;
	// How long it took
	struct timeval length;
	// For seeding rand
	gettimeofday( & length, NULL );
	// Seed rand with call to srand
	srand( length.tv_usec );
	// Set values to zero, because this will
	// now hold the differnece
	length.tv_sec = 0;
	length.tv_usec = 0;
	// Set the starting index for new random method
	starting_index = rand() % WORDS_LENGTH;
	// Guess / type all the words
	for ( i = 0; i < WORDS_LENGTH; ++i )
	{
		// Make the user type a random word
		guess( words[ random_word() ], & length );
	}
	// Tell them how long they took
	printf( "You took " );
	print_time( & length );
	printf( "\n" );
	// Return clean exit
	return 0;
}
Example #23
0
std::pair<std::vector<typename TF::real_t>,typename TF::real_t> FindRootsGSL(
	const TF &f
){
	std::vector<typename TF::real_t> guess(f.arity());
	f.DefaultGuess(&guess[0]);
	return FindRootsGSL(f, &guess[0]);
}
Example #24
0
bool ComputerPlayer::actEasy(Map* cMap) {
    
    //This is simply guessing
    switch (cMap->hit(guess())) {
        case MapRepresentationHit:
            
            //Made a hit, meaning it was a successful play
            return true;
            
            break;
            
        case MapRepresentationMissed:
            
            //Still performed an action, and thats a successful play
            return true;
            
            break;
            
        case MapRepresentationOccupied:
            
            //It's not legal to make a move on that spot, so its not a success
            return false;
            
            break;
            
            //Shouldnt reach that
        default:
            
            return false;
            
            break;
            
    }
    
}
	void DoubleExponentialCalibration::compute() {
        if (vegaWeighted_) {
            Real weightsSum = 0.0;
            for (Size i=0; i<times_.size() ; i++) {
                Real stdDev = std::sqrt(blackVols_[i]* blackVols_[i]* times_[i]);
                // when strike==forward, the blackFormulaStdDevDerivative becomes
                weights_[i] = CumulativeNormalDistribution().derivative(.5*stdDev);
                weightsSum += weights_[i];
            }
            // weight normalization
            for (Size i=0; i<times_.size() ; i++) {
                weights_[i] /= weightsSum;
            }
        }

        // there is nothing to optimize
        if (sigmaIsFixed_ && b1IsFixed_ && b2IsFixed_ && lambdaIsFixed_) {
			dblexpEndCriteria_ = EndCriteria::None;
            //error_ = interpolationError();
            //maxError_ = interpolationMaxError();
            return;
        } else {

			DoubleExponentialError costFunction(this);

            Array guess(4);
            guess[0] = sigma_;
            guess[1] = b1_;
            guess[2] = b2_;
            guess[3] = lambda_;

            std::vector<bool> parameterAreFixed(4);
            parameterAreFixed[0] = sigmaIsFixed_;
            parameterAreFixed[1] = b1IsFixed_;
            parameterAreFixed[2] = b2IsFixed_;
            parameterAreFixed[3] = lambdaIsFixed_;

            ProjectedCostFunction projectedDoubleExponentialCostFunction(costFunction,
									guess, parameterAreFixed);

            Array projectedGuess
				(projectedDoubleExponentialCostFunction.project(guess));

            // NoConstraint constraint;
			//PositiveConstraint constraint;
			BoundaryConstraint constraint(0.0, 1.0);
			Problem problem(projectedDoubleExponentialCostFunction, constraint, projectedGuess);
			dblexpEndCriteria_ = optMethod_->minimize(problem, *endCriteria_);
            Array projectedResult(problem.currentValue());
			Array result(projectedDoubleExponentialCostFunction.include(projectedResult));

            sigma_ = result[0];
            b1_ = result[1];
            b2_ = result[2];
            lambda_ = result[3];

            validateDoubleExponentialParameters(sigma_, b1_, b2_, lambda_);
        }
    }
 int get(int left, int right) {
     if (left == right) return left;
     int mid = left + (right-left)/2;
     int temp = guess(mid);
     if (!temp) return mid;
     if (temp > 0) return get(mid+1, right);
     else return get(left, mid-1);
 }
Example #27
0
bool ComputerPlayer::actMedium(Map* cMap) {
    
    /*
     * Try to guess until hitting something, then try to find the completed shape
     * using an algorithm similar to DFS. once hit, put all of the adjacent legal coordinates
     * into a stack, and try them one by one until the stack is empty. every time there is a
     * successful hit, put all of the hit's adjacent coordiantes into the stack. once the stack
     * is empty, guess.
     */
    
    
    //This will be used as the hitting position, the starting value is not considered
    Coordinate cHit = Coordinate(0,0);
    
    //if the stack is empty - guess
    if (m_vcCoordiantes.empty()) {
        
        //Calling the guess
        cHit = guess();
        
    }
    else {
        
        //The stack is not empty, and that requires to try every coordinate stored in it
        cHit = m_vcCoordiantes.top();
        
        //Pop the saved coordinate
        m_vcCoordiantes.pop();
        
    }
    
    //Make a hit with the coordinate given
    switch (cMap->hit(cHit)) {
        case MapRepresentationHit:
            
            //Made a successful hit, put the adjacent coordiantes into a stack
            addAdjacentIntoStack(cHit);
            
            //A successful play
            return true;
            
            break;
            
        case MapRepresentationMissed:
            
            //Its not a good hit, but still a successful play.
            return true;
            
        case MapRepresentationOccupied:
            
            //Its not a legal move, so its not a successful play
            return false;
            
            //Shouldnt reach that
        default: return false; break;
    }
    
}
Example #28
0
int main()
{
    int i;
    while (scanf("%d", &i) != EOF)
    {
        guess(i);
    }
    return 0;
}
Example #29
0
int main() {
    Queens queens;
    Constraints constraints;

    while (queens.size() < SIZE) {
        guess(queens, constraints);
    }
    print(queens);
}
Example #30
0
static void convert_font(const font_params &param, FILE *infp, FILE *outfp)
{
  string s;
  while (get_line(infp, &s)) {
    put_string(s, outfp);
    if (s.length() >= 8
	&& strncmp(&s[0], "charset", 7))
      break;
  }
  while (get_line(infp, &s)) {
    s += '\0';
    string name;
    const char *p = s.contents();
    while (csspace(*p))
      p++;
    while (*p != '\0' && !csspace(*p))
      name += *p++;
    while (csspace(*p))
      p++;
    for (const char *q = s.contents(); q < p; q++)
      putc(*q, outfp);
    char *next;
    char_metric metric;
    metric.width = (int)strtol(p, &next, 10);
    if (next != p) {
      printf("%d", metric.width);
      p = next;
      metric.type = (int)strtol(p, &next, 10);
      if (next != p) {
	name += '\0';
	guess(name.contents(), param, &metric);
	if (metric.sk == 0) {
	  if (metric.left_ic == 0) {
	    if (metric.ic == 0) {
	      if (metric.depth == 0) {
		if (metric.height != 0)
		  printf(",%d", metric.height);
	      }
	      else
		printf(",%d,%d", metric.height, metric.depth);
	    }
	    else
	      printf(",%d,%d,%d", metric.height, metric.depth, metric.ic);
	  }
	  else
	    printf(",%d,%d,%d,%d", metric.height, metric.depth, metric.ic,
		   metric.left_ic);
	}
	else
	  printf(",%d,%d,%d,%d,%d", metric.height, metric.depth, metric.ic,
		 metric.left_ic, metric.sk);
      }
    }
    fputs(p, outfp);
  }
}