Пример #1
0
int min(uint16_t move, int ply) {
    //printf("ply: %d\n", ply);
    //bboards[0] |= move;
    update_ply(ply);
    update_analysis(move, 0);
    int min_score = 2;
    if(check_win(0)){
        //bboards[0] ^= move;
        undo_analysis(move, 0);
        return 1;
    }
    //uint16_t next_move = 1;
    for(int i = 0; i < 16; i++) {
        //printf("max: %d\n", i);
        if(is_legal(1 << i)){
            int score = max(1 << i, ply + 1);
            if(score < min_score)
                min_score = score;
        }
        //next_move <<= 1;
    }
    //printf("whew\n");
    //bboards[0] ^= move;
    undo_analysis(move, 0);
    if(min_score != 2)
        return min_score;
    else
        return 0;
}
Пример #2
0
// evaluate black's move
// returns the evaluation of the strongest
// opponent reply
int max(uint16_t move, int ply) {
    //bboards[1] |= move;
    update_ply(ply);
    update_analysis(move, 1);
    int max_score = -2;
    if(check_win(1)){
        //bboards[1] ^= move;
        undo_analysis(move, 1);
        return -1;
    }
    //uint16_t next_move = 1;
    for(int i = 0; i < 16; i++) {
        //printf("min: %d\n", i);
        if(is_legal(1 << i)){
            int score = min(1 << i, ply + 1);
            if(score > max_score)
                max_score = score;
        }
        //next_move <<= 1;
    }
    //printf("whew\n");
    //bboards[1] ^= move;
    undo_analysis(move, 1);
    if(max_score != -2)
        return max_score;
    else
        return 0;
}
Пример #3
0
int match_kmp(circular_buffer *text, const char *target) {
    int m = strlen(target);
    int *jumps = kmp_jump_table(target, m);
    int target_idx = 0;
    int text_idx = 0;
    char text_char = 0;

    while ((text_char = buf_get(text, text_idx)) != -1)
    {
        if (target_idx >= m) /* match condition */
        {
            return 1;
        }

        if (!is_legal(text_char))
        {
            target_idx = 0;
        }
        else
        {
            target_idx = jumps[get_idx(target_idx, text_char)];
        }
        text_idx++;
    }

    free(jumps);
    return target_idx >= m;
}
Пример #4
0
 vector<vector<int> > generateMatrix(int n) {
     vector<vector<int> > grid;
     if(n == 0)
         return grid;
         
     int size = n;
     int direct = 0, cnt = 0;
     for(int i = 0; i < size; i++) {
         vector<int> tmp;
         for(int j = 0; j < size; j++) {
             tmp.push_back(0);
         }
         grid.push_back(tmp);
     }
     
     int x = 0, y = 0;
     
     while(true) {
         grid[x][y] = (++cnt);
         
         if(cnt >= n*n)
             break;
             
         if(!is_legal(size, grid, x, y, direct))
             direct = (direct + 1) % 4;
         x += dx[direct];
         y += dy[direct];
         
     } 
     
     return grid;
 }
Пример #5
0
uint16_t best_move(int side) {
    // returns best move, otherwise 0 if no legal moves exist
    hide_cursor();
    uint16_t best_move = 0;
    int best_score = 2 * side - 1;
    // calculate this so we don't have to branch =D
    // if side is 0 (white), we use a factor of (1)
    // if side is 1 (black), we negate (-1)
    int branch = -2 * side + 1;
    // 2 * side - 1 = score 
    uint16_t move = 1;
    for(int i = 0; i < 16; i++){
        //printf("considering move : 0x%X\n", move);
        if(is_legal(move)){
            int score = minimax[side](move, 0);
            //printf("finite recursion\n");
            if(score * branch > best_score * branch){
                best_score = score;
                best_move = move; 
            }
        }
        move <<= 1;
    }
    show_cursor();
    return best_move;
}
Пример #6
0
void		ft_get_options(t_args *args, char *av)
{
	if (args->options->f == 1)
		args->options->color = 0;
	else if (is_legal(av) == 1)
		find_options(args->options, av);
	else
		invalid_option(args, av);
}
Пример #7
0
bool can_cut(const Polygon_2& polygon, Polygon_2::Vertex_circulator p, Polygon_2::Vertex_circulator c, Polygon_2::Vertex_circulator n, 
	     const boost::unordered_map<Point_3, boost::unordered_set<Segment_3_undirected> >& point2edges)
{
  Segment_2 seg(*p, *n);
  Point_2 mid((p->x()+n->x())/2.0, (p->y()+n->y())/2.0);
  return (CGAL::left_turn(*p, *c, *n) &&
	  is_legal(*p, *c, *n, point2edges) &&
	  !intersects_boundary(polygon, seg, true, false) &&
	  polygon.has_on_bounded_side(mid));
}
Пример #8
0
int JPAKE_STEP1_process(JPAKE_CTX *ctx, const JPAKE_STEP1 *received)
    {
    if(!is_legal(received->p1.gx, ctx))
	{
	JPAKEerr(JPAKE_F_JPAKE_STEP1_PROCESS, JPAKE_R_G_TO_THE_X3_IS_NOT_LEGAL);
	return 0;
	}

    if(!is_legal(received->p2.gx, ctx))
	{
	JPAKEerr(JPAKE_F_JPAKE_STEP1_PROCESS, JPAKE_R_G_TO_THE_X4_IS_NOT_LEGAL);
	return 0;
	}

   /* verify their ZKP(xc) */
    if(!verify_zkp(&received->p1, ctx->p.g, ctx))
	{
	JPAKEerr(JPAKE_F_JPAKE_STEP1_PROCESS, JPAKE_R_VERIFY_X3_FAILED);
	return 0;
	}

   /* verify their ZKP(xd) */
    if(!verify_zkp(&received->p2, ctx->p.g, ctx))
	{
	JPAKEerr(JPAKE_F_JPAKE_STEP1_PROCESS, JPAKE_R_VERIFY_X4_FAILED);
	return 0;
	}

   /* g^xd != 1 */
    if(BN_is_one(received->p2.gx))
	{
	JPAKEerr(JPAKE_F_JPAKE_STEP1_PROCESS, JPAKE_R_G_TO_THE_X4_IS_ONE);
	return 0;
	}

   /* Save the bits we need for later */
    BN_copy(ctx->p.gxc, received->p1.gx);
    BN_copy(ctx->p.gxd, received->p2.gx);

    return 1;
    }
Пример #9
0
void	ft_get_options(t_args *args, char *av)
{
	if (ft_strcmp(av, "--color") == 0)
	{
		if (args->options->f == 0)
			args->options->color = 1;
	}
	else if (is_legal(av) == 1)
		find_options(args->options, av);
	else
		invalid_option(args, av);
}
Пример #10
0
int Goban::legal_moves(int moves[]) const
{
  int nlegal = 0;
  for (int i = 0; i < empty_points.length(); i++) {
    int point = empty_points[i];
    if (is_legal(point, side)) {
      moves[nlegal++] = point;
    }
  }
  moves[nlegal++] = PASS;
  return nlegal;
}
Пример #11
0
// recursive DFS for calculating score of all subtree nodes
long parallel_dfs(char* board, int blackPrisoners, int whitePrisoners, int depth, int color, int turnNumber)
{
	char tempBoard[BOARD_SIZE * BOARD_SIZE];
	int tempBlackPrisoners;
	int tempWhitePrisoners;
	int legalMoves = 0;
	
	// printf("%d - %d", my_rank, depth);
	// fflush(stdout);

	get_black_score(board, turnNumber);
	get_white_score(board, turnNumber);
	
	long nodeScore = calculate_influence(board);
	long subTreeScore = 0;
	
	int move;
	
	if ( depth <= MAX_PARALLEL_DEPTH )
	{
		for ( int i = 0; i < BOARD_SIZE * BOARD_SIZE && legalMoves < MAX_RANDOM_MOVES; i++ )
		{
			move = rand() % ( BOARD_SIZE * BOARD_SIZE );
			if ( is_legal(move, board, turnNumber) == 0 ) 
			{
				legalMoves++;
				memcpy( tempBoard, board, BOARD_SIZE * BOARD_SIZE * sizeof(char) );
				
				tempBlackPrisoners = blackPrisoners;
				tempWhitePrisoners = whitePrisoners;
				
				tempBoard[move] = color;
				test_capture( tempBoard, &tempBlackPrisoners, &tempWhitePrisoners, move, color );
				
				subTreeScore += parallel_dfs(tempBoard, tempBlackPrisoners, tempWhitePrisoners, depth + 1, color, turnNumber + 2);
			}
		}
		// pass move
		// printf("legalMoves = %d\n", legalMoves);
		
		legalMoves++;
		tempBlackPrisoners = blackPrisoners;
		tempWhitePrisoners = whitePrisoners;
		subTreeScore += parallel_dfs( board, tempBlackPrisoners, tempWhitePrisoners, depth + 1, color, turnNumber);
		
		return nodeScore + ((subTreeScore * 5 * depth )/ legalMoves);
	}
	
	return nodeScore;
}
Пример #12
0
// backtrack - completes the filling of the board using recursive backtracking
int backtrack(int row, int col) {
	
	// If the board is full, then we have a solution!!!
	if (is_full_board())
		return 1;


	if (board[row][col] != ' ') {
		if (col == BOARD_SIZE - 1) {
			if (backtrack(row + 1, 0))
				return 1;
		} else {
			if (backtrack(row, col + 1))
				return 1;
		}
	}

	int i;

	// Iterate through all possible sudoku numbers
	for (i = 0; i < BOARD_SIZE; i++) {
		if (is_legal(row, col, i + 1 + '0')) {
				
			// Temporarily assign i to the board
			board[row][col] = i + 1 + '0';

			// Check recursively if i results in a solved board 
			if (col == BOARD_SIZE - 1) {
				if (backtrack(row + 1, 0))
					return 1;
			} else {
				if (backtrack(row, col + 1))
					return 1;
			}
		}
	}
		
	// At the is point none of the numbers will result in a solved
	// board, thus we must initiate backtracking
	board[row][col] = ' ';
	return 0;
}
Пример #13
0
bool is_strictly_convex(const Polygon_2& polygon, 
			const boost::unordered_map<Point_3, boost::unordered_set<Segment_3_undirected> >& point2edges)
{
  Polygon_2::Vertex_circulator start = polygon.vertices_circulator();
  Polygon_2::Vertex_circulator c = start;
  Polygon_2::Vertex_circulator p = c;
  Polygon_2::Vertex_circulator n = c;
  --p;
  ++n;
  do
  {
    if (!CGAL::left_turn(*p, *c, *n) || 
	!is_legal(*p, *c, *n, point2edges))
      return false;

    ++p;
    ++c;
    ++n;
  } while (c != start);
  return true;
}
Пример #14
0
void main(void)
    {
    char post[256];
    init_stack();
    init_queue();
    init_tree();
    while (1)
	{
	printf("\n\nInput Postfix expression -> ");
	gets(post);
	if (*post == NULL)
	    {
	    printf("\n Program ends...");
	    exit(0);
	    }
	if (!is_legal(post))
	    {
	    printf("\nExpression is not legal.");
	    continue;
	    }

	head->right = make_parse_tree(post);

        printf("\nPreorder   traverse -> ");
        preorder_traverse(head->right);

        printf("\nInorder    traverse -> ");
        inorder_traverse(head->right);

        printf("\nPostorder  traverse -> ");
        postorder_traverse(head->right);

        printf("\nLevelorder traverse -> ");
        levelorder_traverse(head->right);
	}
    }
Пример #15
0
double score_seq( int s, char* seq, int ip )
{
    double score = 0.0;
    if( !is_legal( seq ) ) return score;

    int length = strlen( seq );
    int* ix = get_iindx( length );

    double betaScale = 1.0;
    double kT = ( betaScale*( ( temperature+K0 )*GASCONST ) )/1000.; /* in Kcal */
    model_detailsT md;
    set_model_details( &md );

    char* secstr = strdup( seq );
    secstr[0] = 0;
    fold_constrained = 0;
    paramT* params = get_scaled_parameters( temperature, md );
    double min_en = fold_par( seq, secstr, params, fold_constrained, 0 );
    if( strncmp( secstr + ip,
                 cnf->hairpin_ss, strlen( cnf->hairpin_ss ) ) != 0
        || strcmp( secstr + length - strlen( cnf->tail3p_ss ),
                   cnf->tail3p_ss ) != 0 ) {
        free( params );
        free( secstr );
        free( ix );
        return score;
    }
    if( !is_legal_pair_content( seq, secstr, ip ) ) {
        free( params );
        free( secstr );
        free( ix );
        return score;
    }
    #pragma omp atomic update
    num_scored++;

    double pf_scale = exp( -( 1.07*min_en )/kT/length );
    pf_paramT* pf_params = get_boltzmann_factors( temperature, betaScale, md, pf_scale );
    // Either patch fold_vars.h by inserting following at line 166
    //
    // #ifdef _OPENMP
    // #pragma omp threadprivate(iindx)
    // #endif
    //
    // or uncomment this pragma below
    //
    // #pragma omp critical(pf_fold)
    double e = pf_fold_par( seq, NULL, pf_params, 1, fold_constrained, 0 );
    FLT_OR_DBL* ppm = export_bppm();

#define pr_ij(i,j) (i == j? 0.0 : (i < j ? ppm[ix[i]-j] : ppm[ix[j]-i]))

    score = cnf->s_max;
    int i, o;
    for( i = 1; i <= length; i++ ) {
        for( o = 1; o <= strlen( cnf->hairpin_ss ); o++ ) {
            int j = ip + o;
            double v = pr_ij( i, j );
            score -= v * ( 1.0 - v );
        }
    }
    score *= cnf->s_scale;

    free( pf_params );
    free( params );
    free( secstr );
    free( ix );
    return score;
}
Пример #16
0
/* TODO: accuracy */
int ranged_attack( entity_t *atk, int tx, int ty )
{
	weapon_t *wpn;
	int cx = atk->x, cy = atk->y;

	if( !atk->in_hand )
	{
		if( atk == player )
		{
			buf_t *msg = bufnew( "You're not wielding anything!" );
			push_message( msg );
			bufdestroy( msg );
		}
		return 0;
	}

	if( atk->in_hand->type != ITEMTYPE_WEAPON )
	{
		if( atk == player )
		{
			buf_t *msg = bufnew( "You're not wielding a weapon!" );
			push_message( msg );
			bufdestroy( msg );
		}
		return 0;
	}

	wpn = (weapon_t*)atk->in_hand->specific;

	if( wpn->type != WEAPONTYPE_HANDGUN )
	{
		if( atk == player )
		{
			buf_t *msg = bufnew( "You're not wielding a ranged weapon!" );
			push_message( msg );
			bufdestroy( msg );
		}
		return 0;
	}

	/* consume ammo */
	if( wpn->ammo_loaded >= 1 )
	{
		wpn->ammo_loaded -= 1;
	}
	else
	{
		buf_t *msg = bufnew( "The clip is empty!" );
		push_message( msg );
		bufdestroy( msg );
		return 0;
	}

	if( atk == player )
	{
		buf_t *msg = bufnew( "You shoot your weapon!" );
		push_message( msg );
		bufdestroy( msg );
	}

	while( 1 )
	{
		cx += tx;
		cy += ty;
		
		if( is_legal( cx, cy ) &&
			( dungeon[atk->z]->terrain[cx][cy]->flags & TILEFLAG_SOLID ) )
		{
			/* you hit something solid */
			break;
		}
	
		attrset( COLOR_PAIR( C_RED ) );
		mvaddch( cy+2, cx, '*' );

		entity_t *e = entity_find_by_position( cx, cy, atk->z );
		if( e )
		{
			buf_t *msg = bufprintf( "You hit the %s!", e->name->data );
			push_message( msg );
			bufdestroy( msg );

			take_damage( e, wpn );

			break;
		}
	}

	refresh();
	msleep( 100 );

	return 1;
}
Пример #17
0
Value name_NT_InCheck(qsearch)(Pos* pos, Stack* ss, Value alpha, BETA_ARG
                               Depth depth)
{
  assert(InCheck == !!pos_checkers());
  assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
  assert(PvNode || (alpha == beta - 1));
  assert(depth <= DEPTH_ZERO);

  Move pv[MAX_PLY+1];
  TTEntry *tte;
  Key posKey;
  Move ttMove, move, bestMove;
  Value bestValue, value, ttValue, futilityValue, futilityBase, oldAlpha;
  int ttHit, ttPv, givesCheck, evasionPrunable;
  Depth ttDepth;
  int moveCount;

  if (PvNode) {
    oldAlpha = alpha; // To flag BOUND_EXACT when eval above alpha and no available moves
    (ss+1)->pv = pv;
    ss->pv[0] = 0;
  }

  bestMove = 0;
  moveCount = 0;

  // Check for an instant draw or if the maximum ply has been reached
  if (is_draw(pos) || ss->ply >= MAX_PLY)
    return ss->ply >= MAX_PLY && !InCheck ? evaluate(pos) : VALUE_DRAW;

  assert(0 <= ss->ply && ss->ply < MAX_PLY);

  // Decide whether or not to include checks: this fixes also the type of
  // TT entry depth that we are going to use. Note that in qsearch we use
  // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
  ttDepth = InCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS
                                                : DEPTH_QS_NO_CHECKS;

  // Transposition table lookup
  posKey = pos_key();
  tte = tt_probe(posKey, &ttHit);
  ttValue = ttHit ? value_from_tt(tte_value(tte), ss->ply) : VALUE_NONE;
  ttMove = ttHit ? tte_move(tte) : 0;
  ttPv = ttHit ? tte_is_pv(tte) : 0;

  if (  !PvNode
      && ttHit
      && tte_depth(tte) >= ttDepth
      && ttValue != VALUE_NONE // Only in case of TT access race
      && (ttValue >= beta ? (tte_bound(tte) &  BOUND_LOWER)
                          : (tte_bound(tte) &  BOUND_UPPER)))
    return ttValue;

  // Evaluate the position statically
  if (InCheck) {
    ss->staticEval = VALUE_NONE;
    bestValue = futilityBase = -VALUE_INFINITE;
  } else {
    if (ttHit) {
      // Never assume anything on values stored in TT
      if ((ss->staticEval = bestValue = tte_eval(tte)) == VALUE_NONE)
         ss->staticEval = bestValue = evaluate(pos);

      // Can ttValue be used as a better position evaluation?
      if (ttValue != VALUE_NONE)
        if (tte_bound(tte) & (ttValue > bestValue ? BOUND_LOWER : BOUND_UPPER))
          bestValue = ttValue;
    } else
      ss->staticEval = bestValue =
      (ss-1)->currentMove != MOVE_NULL ? evaluate(pos)
                                       : -(ss-1)->staticEval + 2 * Tempo;

    // Stand pat. Return immediately if static value is at least beta
    if (bestValue >= beta) {
      if (!ttHit)
        tte_save(tte, posKey, value_to_tt(bestValue, ss->ply), ttPv,
                 BOUND_LOWER, DEPTH_NONE, 0, ss->staticEval,
                 tt_generation());

      return bestValue;
    }

    if (PvNode && bestValue > alpha)
      alpha = bestValue;

    futilityBase = bestValue + 128;
  }

  ss->history = &(*pos->counterMoveHistory)[0][0];

  // Initialize move picker data for the current position, and prepare
  // to search the moves. Because the depth is <= 0 here, only captures,
  // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
  // be generated.
  mp_init_q(pos, ttMove, depth, to_sq((ss-1)->currentMove));

  // Loop through the moves until no moves remain or a beta cutoff occurs
  while ((move = next_move(pos, 0))) {
    assert(move_is_ok(move));

    givesCheck = gives_check(pos, ss, move);

    moveCount++;

    // Futility pruning
    if (   !InCheck
        && !givesCheck
        &&  futilityBase > -VALUE_KNOWN_WIN
        && !advanced_pawn_push(pos, move)) {
      assert(type_of_m(move) != ENPASSANT); // Due to !advanced_pawn_push

      futilityValue = futilityBase + PieceValue[EG][piece_on(to_sq(move))];

      if (futilityValue <= alpha) {
        bestValue = max(bestValue, futilityValue);
        continue;
      }

      if (futilityBase <= alpha && !see_test(pos, move, 1)) {
        bestValue = max(bestValue, futilityBase);
        continue;
      }
    }

    // Detect non-capture evasions that are candidates to be pruned
    evasionPrunable =    InCheck
                     && (depth != DEPTH_ZERO || moveCount > 2)
                     &&  bestValue > VALUE_MATED_IN_MAX_PLY
                     && !is_capture(pos, move);

    // Don't search moves with negative SEE values
    if (  (!InCheck || evasionPrunable)
        &&  !see_test(pos, move, 0))
      continue;

    // Speculative prefetch as early as possible
    prefetch(tt_first_entry(key_after(pos, move)));

    // Check for legality just before making the move
    if (!is_legal(pos, move)) {
      moveCount--;
      continue;
    }

    ss->currentMove = move;
    ss->history = &(*pos->counterMoveHistory)[moved_piece(move)][to_sq(move)];

    // Make and search the move
    do_move(pos, move, givesCheck);
#if PvNode
    value =  givesCheck
           ? -qsearch_PV_true(pos, ss+1, -beta, -alpha, depth - ONE_PLY)
           : -qsearch_PV_false(pos, ss+1, -beta, -alpha, depth - ONE_PLY);
#else
    value =  givesCheck
           ? -qsearch_NonPV_true(pos, ss+1, -beta, depth - ONE_PLY)
           : -qsearch_NonPV_false(pos, ss+1, -beta, depth - ONE_PLY);
#endif
    undo_move(pos, move);

    assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);

    // Check for a new best move
    if (value > bestValue) {
      bestValue = value;

      if (value > alpha) {
        bestMove = move;

        if (PvNode) // Update pv even in fail-high case
          update_pv(ss->pv, move, (ss+1)->pv);

        if (PvNode && value < beta) // Update alpha here!
          alpha = value;
        else
          break; // Fail high
      }
    }
  }

  // All legal moves have been searched. A special case: If we're in check
  // and no legal moves were found, it is checkmate.
  if (InCheck && bestValue == -VALUE_INFINITE)
    return mated_in(ss->ply); // Plies to mate from the root

  tte_save(tte, posKey, value_to_tt(bestValue, ss->ply), ttPv,
           bestValue >= beta ? BOUND_LOWER :
           PvNode && bestValue > oldAlpha  ? BOUND_EXACT : BOUND_UPPER,
           ttDepth, bestMove, ss->staticEval, tt_generation());

  assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);

  return bestValue;
}
Пример #18
0
void triangulate(const Polygon_2& polygon, 
		 Cut_iter cuts_begin, Cut_iter cuts_end,
		 const boost::unordered_map<Point_3, boost::unordered_set<Segment_3_undirected> >& point2edges,
		 Out_iter triangles)
{
  typedef CGAL::Triangulation_vertex_base_2<Kernel>                     Vb;
  typedef CGAL::Triangulation_vertex_base_with_info_2<Point_3, Kernel, Vb>     Info;
  typedef CGAL::Constrained_triangulation_face_base_2<Kernel>           Fb;
  typedef CGAL::Triangulation_data_structure_2<Info,Fb>              TDS;
  typedef CGAL::Exact_predicates_tag                               Itag;
  typedef CGAL::Constrained_Delaunay_triangulation_2<Kernel, TDS, Itag> CDT;
  typedef CDT::Vertex_handle Vertex_handle;

  static log4cplus::Logger logger = log4cplus::Logger::getInstance("polygon_utils");

  Polygon_2 p(polygon);
  LOG4CPLUS_TRACE(logger, "Triangulating " << pp(p));
  if (p.size() < 3) return;

  bool vertical = is_vertical(p);
  if (vertical)
  {
    LOG4CPLUS_TRACE(logger, "Polygon is vertical.  Rotating.");
    p = yz_swap_neg(p);
  }

  bool reverse = !p.is_counterclockwise_oriented();
  if (reverse)
    p.reverse_orientation();

  CDT cdt;

  boost::unordered_map<Point_3, Vertex_handle> point2handle;
  for (Polygon_2::Vertex_iterator it = p.vertices_begin(); it != p.vertices_end(); ++it)
  {
    Vertex_handle h = cdt.insert(*it);
    point2handle[*it] = h;
    h->info() = *it;//it->z();
  }

  Polygon_2::Vertex_circulator start = p.vertices_circulator();
  Polygon_2::Vertex_circulator c = start;
  Polygon_2::Vertex_circulator n = c;
  ++n;
  do
  {
    Vertex_handle ch = point2handle[*c];//cdt.insert(*c);
    Vertex_handle nh = point2handle[*n];//cdt.insert(*n);
//     ch->info() = c->z();
//     nh->info() = n->z();
//     cdt.insert_constraint(*c, *n);
    cdt.insert_constraint(ch, nh);
    ++c;
    ++n;
  } while (c != start);

  for (Cut_iter c_it = cuts_begin; c_it != cuts_end; ++c_it)
  {
    Polyline_2 cut = *c_it;
    LOG4CPLUS_TRACE(logger, "Adding cut: " << pp(cut));
    if (vertical)
      cut = yz_swap_neg(cut);
    for (Polyline_2::const_iterator c = cut.begin(); c != cut.end(); ++c)
    {
      Polyline_2::const_iterator n = c;
      ++n;
      if (n != cut.end())
      {
	const Point_3& cp = *c;
	const Point_3& np = *n;
	if (point2handle.find(cp) == point2handle.end())
	{
	  Vertex_handle h = cdt.insert(cp);
	  point2handle[cp] = h;
	  h->info() = cp;//cp.z();
	}
	if (point2handle.find(np) == point2handle.end())
	{
	  Vertex_handle h = cdt.insert(np);
	  point2handle[np] = h;
	  h->info() = np;//np.z();
	}

	Vertex_handle ch = point2handle[*c];//cdt.insert(*c);
	Vertex_handle nh = point2handle[*n];//cdt.insert(*n);
// 	ch->info() = c->z();
// 	nh->info() = n->z();
// 	cdt.insert_constraint(*c, *n);
	cdt.insert_constraint(ch, nh);
	LOG4CPLUS_TRACE(logger, "  " << pp(Segment_2(*c, *n)));
      }
    }
  }

  // Loop through the triangulation and store the vertices of each triangle
  for (CDT::Finite_faces_iterator ffi = cdt.finite_faces_begin();
       ffi != cdt.finite_faces_end();
       ++ffi)
  {
    Triangle t;
    Point_3 center = centroid(ffi->vertex(0)->info(), ffi->vertex(1)->info(), ffi->vertex(2)->info());
    if (p.has_on_bounded_side(center) && 
	is_legal(ffi->vertex(0)->info(), ffi->vertex(1)->info(), ffi->vertex(2)->info(), point2edges))
    {
      for (int i = 0; i < 3; ++i)
      {
	int idx = reverse ? 2-i : i;
	if (!vertical)
	{
// 	  Point_3 p(ffi->vertex(i)->point());
// 	  p = Point_3(p.x(), p.y(), ffi->vertex(i)->info());
	  Point_3 p(ffi->vertex(i)->info());
	  t[idx] = p;
	}
	else
	{
// 	  Point_3 p(ffi->vertex(i)->point());
// 	  p = Point_3(p.x(), p.y(), ffi->vertex(i)->info());
	  Point_3 p(ffi->vertex(i)->info());
	  t[idx] = yz_swap_pos(p);
	}
      }
      LOG4CPLUS_TRACE(logger, "Adding tile: " << pp_tri(t));
      *triangles++ = t;
    }
  }
}
Пример #19
0
Polygon_2 cut_ear(const Polygon_2& polygon, Triangle_iter triangles, 
		  const boost::unordered_map<Point_3, boost::unordered_set<Segment_3_undirected> >& point2edges)
{
  static log4cplus::Logger logger = log4cplus::Logger::getInstance("polygon_utils");

  LOG4CPLUS_TRACE(logger, "Cutting ear of " << pp(polygon));;

  Polygon_2 ret(polygon);
  Polygon_2::Vertex_circulator start = ret.vertices_circulator();
  Polygon_2::Vertex_circulator c = start;
  Polygon_2::Vertex_circulator p = c - 1;
  Polygon_2::Vertex_circulator n = c + 1;
  // Do a run preferring to get rid of collinear points
  do
  {
    Polygon_2::Vertex_circulator pp = p - 1;
    if (!is_legal(*pp, *p, *c, point2edges) &&
	can_cut(polygon, p, c, n, point2edges))
//     if (!is_legal(*pp, *p, *c, point2edges) &&
// 	is_legal(*p, *c, *n, point2edges))
    {
      *triangles++ = Triangle(*p, *c, *n);
      ret.erase(c);
      return ret;
    }
    Polygon_2::Vertex_circulator ppp = pp - 1;
    if (!is_legal(*pp, *p, *c, point2edges) &&
	can_cut(polygon, ppp, pp, p, point2edges))
//     if (!is_legal(*pp, *p, *c, point2edges) &&
// 	is_legal(*p, *c, *n, point2edges))
    {
      *triangles++ = Triangle(*ppp, *pp, *p);
      ret.erase(pp);
      return ret;
    }
    ++p;
    ++c;
    ++n;
  } while (c != start);

  // Okay, just take any cut
  do
  {
    if (can_cut(polygon, p, c, n, point2edges))
    {
      *triangles++ = Triangle(*p, *c, *n);
      ret.erase(c);
      return ret;
    }
    ++p;
    ++c;
    ++n;
  } while (c != start);

  // Okay, really just take any cut
  do
  {
//     if (can_cut(polygon, p, c, n, point2edges))
    if (is_legal(*p, *c, *n, point2edges))
    {
      *triangles++ = Triangle(*p, *c, *n);
      ret.erase(c);
      return ret;
    }
    ++p;
    ++c;
    ++n;
  } while (c != start);

  LOG4CPLUS_DEBUG(logger, "Polygon is not strictly convex");
  LOG4CPLUS_DEBUG(logger, "  Original: " << pp(polygon));
  LOG4CPLUS_DEBUG(logger, "   Current: " << pp(ret));
  throw logic_error("Polygon is not strictly convex");
}
Пример #20
0
void test_legality(int matrix[HEIGHT][WIDTH], int expected_value) {
    test ( is_legal(matrix) == expected_value ? "Pass" : "Fail" );
}
Пример #21
0
// Called on process 0, calculates all the legal moves in the current turn and divides them up to all the processors
// Waits until all processors have finished their calculation and then returns the optimum move.
int get_move_mpi(GameBoard* goBoard, int color)
{
	int legalMoves = 0;
	char tempBoard[BOARD_SIZE * BOARD_SIZE + 4];
	long possibleMoves[BOARD_SIZE * BOARD_SIZE + 1];
	long bestMove = 0;
	int bestMoveIndex;
	int tempBlackPrisoners;
	int tempWhitePrisoners;
	
	MPI_Request requestArray[BOARD_SIZE * BOARD_SIZE + 1];
	MPI_Status	statusArray[BOARD_SIZE * BOARD_SIZE + 1];
	
	for ( int i = 0; i < BOARD_SIZE * BOARD_SIZE; i++ )
	{
		if ( is_legal(i, goBoard->board, goBoard->turnNumber) == 0 )
		{
			legalMoves++;
			memcpy( tempBoard, goBoard->board, (BOARD_SIZE * BOARD_SIZE) * sizeof(char) );
			
			tempBlackPrisoners = goBoard->blackPrisoners;
			tempWhitePrisoners = goBoard->whitePrisoners;
			
			tempBoard[i] = color;
			test_capture( tempBoard, &tempBlackPrisoners, &tempWhitePrisoners, i, color );
			
			tempBoard[BOARD_SIZE * BOARD_SIZE] = (char) tempBlackPrisoners;
			tempBoard[BOARD_SIZE * BOARD_SIZE + 1] = (char) tempWhitePrisoners;
			tempBoard[BOARD_SIZE * BOARD_SIZE + 2] = (char) goBoard->turnNumber + 2;
			tempBoard[BOARD_SIZE * BOARD_SIZE + 3] = (char) color;
			// last four entries of tempBoard contain blackPrisoners, whitePrisoners, turnNumber, and current color.
			
			MPI_Send(tempBoard, BOARD_SIZE * BOARD_SIZE + 4, MPI_CHAR, legalMoves, 19, MPI_COMM_WORLD); // send board to processor with rank equal to legalMoves
			
			MPI_Irecv( &possibleMoves[i], 1, MPI_LONG, legalMoves, 19, MPI_COMM_WORLD, &requestArray[legalMoves - 1] ); // start non-blocking receive
		} else
		{
			possibleMoves[i] = 0;
		}
	}
	
	legalMoves++;
	memcpy( tempBoard, goBoard->board, (BOARD_SIZE * BOARD_SIZE) * sizeof(char));
	tempBoard[BOARD_SIZE * BOARD_SIZE] = (char) goBoard->blackPrisoners;
	tempBoard[BOARD_SIZE * BOARD_SIZE + 1] = (char) goBoard->whitePrisoners;
	tempBoard[BOARD_SIZE * BOARD_SIZE + 2] = (char) goBoard->turnNumber + 2;
	tempBoard[BOARD_SIZE * BOARD_SIZE + 3] = (char) color;
				
	MPI_Send(tempBoard, BOARD_SIZE * BOARD_SIZE + 4, MPI_CHAR, legalMoves, 19, MPI_COMM_WORLD); // send board to processor with rank equal to legalMoves
	
	MPI_Irecv(&possibleMoves[BOARD_SIZE * BOARD_SIZE], 1, MPI_LONG, legalMoves, 19, MPI_COMM_WORLD, &requestArray[legalMoves - 1]); // start non-blocking receive
	
	// wait until all IRecv is complete
	MPI_Waitall(legalMoves, requestArray, statusArray);
	
	if (debug)
	{
		for (int i = BOARD_SIZE - 1; i >= 0 ; i--)
		{
			printf("\n%d:\n", i);
			for (int j = 0; j < BOARD_SIZE; j++)
			{
				printf("%ld ", possibleMoves[i * BOARD_SIZE + j]);
			}
			printf("\n");
			fflush(stdout);
		}
		printf( "PASS: %ld\n", possibleMoves[BOARD_SIZE * BOARD_SIZE] );
	}
	
	do
	{
		bestMoveIndex = rand() % ( BOARD_SIZE * BOARD_SIZE );
	} while (is_legal(bestMoveIndex, goBoard->board, goBoard->turnNumber) != 0);
	
	bestMove = possibleMoves[bestMoveIndex];	
	
	// check each possible move and select the best outcome
	if (color == BLACK)
	{
		for (int i = 0; i < BOARD_SIZE * BOARD_SIZE + 1; i++)
		{
			if ( possibleMoves[i] > bestMove && possibleMoves[i] != 0)
			{
				bestMove = possibleMoves[i];
				bestMoveIndex = i;
			}
		}
	} else
	{
		for (int i = 0; i < BOARD_SIZE * BOARD_SIZE + 1; i++)
		{
			if ( possibleMoves[i] < bestMove && possibleMoves[i] != 0)
			{
				bestMove = possibleMoves[i];
				bestMoveIndex = i;
			}
		}
	}
	
	//printf("BEST MOVE: %ld BEST MOVE INDEX: %d\n", bestMove, bestMoveIndex);
	//fflush (stdout);
	
	if (bestMoveIndex == BOARD_SIZE * BOARD_SIZE)
	{
		return -1; // passing move
	}
	
	return bestMoveIndex;
}
Пример #22
0
//纯文本协议,以特殊字符作为结束符
int ISGWIntf::handle_input(ACE_HANDLE /*fd = ACE_INVALID_HANDLE*/)
{
    lastrtime_ = ISGWAck::instance()->get_time();
    //接收消息
    int ret = this->peer().recv((char*)recv_buf_ + recv_len_,
                                MAX_RECV_BUF_LEN - recv_len_); //, &timeout    
    switch(ret)
    {
        case -1:
        {
            ACE_DEBUG((LM_ERROR, "[%D] ISGWIntf recv failed"
				",ret=%d"
                ",errno=%d"
                ",errmsg=%s"
                ",ip=%s"
                "\n"
                , ret
                , errno
                , strerror(errno)
                , remote_addr_.get_host_addr()
                ));
			if (errno == EWOULDBLOCK || errno == EAGAIN || errno == EINPROGRESS)
            {
                return 0;
            }
            return -1;
        }
        break;
        case 0:
        {
            ACE_DEBUG((LM_NOTICE, "[%D] ISGWIntf recv succ"
                ",connection closed by foreign host"
				",ret=%d,ip=%s\n"
				, ret, remote_addr_.get_host_addr()
				));
            return -1;
        }
        break;
        default: //接收成功
        recv_len_ += ret;
        ACE_DEBUG((LM_TRACE, "[%D] ISGWIntf recv succ,recv_len=%d,ret=%d,recv_buf=%s\n"
            , recv_len_, ret, recv_buf_));

        //粗略判断消息是否结束(即是否已经有一个完整的消息包)
        //因为此处判断可能包括了垃圾数据里面的结束符
        if ( strstr(recv_buf_, MSG_SEPARATOR) == NULL) //未结束,继续接收
        {
            if ( recv_len_ < MAX_RECV_BUF_LEN )
            {
                ACE_DEBUG((LM_WARNING, "[%D] ISGWIntf recv succ,no end"
                    ",recv_len=%d,recv_buf=%s\n"
                    , recv_len_, recv_buf_));
                return 0;
            }
            else
            {
                ACE_DEBUG((LM_ERROR, "[%D] ISGWIntf recv failed,illegal msg"
                    ",reach max buff len and have no msg end,discard it,ip=%s\n"
                    , remote_addr_.get_host_addr()
                    ));
                return -1; //消息非法
            }
        }
		
    }
    
    //已经获得完整的消息
    
    //判断消息是否非法
    if (is_legal(recv_buf_) != 0)
    {
    	ACE_DEBUG((LM_ERROR, "[%D] ISGWIntf recv failed,illegal msg,discard it"
            ",ip=%s\n", remote_addr_.get_host_addr()
            ));
    	recv_len_ = 0; // reset the recv pos indicator 
    	//memset(recv_buf_, 0x0, sizeof(recv_buf_));
    	return 0;
    }

    char *msg_start = recv_buf_;
    char *msg_end = NULL;
    int proced_len = 0; //已经处理的长度
    int pend_len = recv_len_; //pend_len 未处理的消息长度

    //proced_len 必须小于recv_len_ 避免处理到了buf后面的垃圾数据 
    while ((msg_end = strstr(msg_start, MSG_SEPARATOR)) != NULL && proced_len < recv_len_)
    {
        msg_len_ = msg_end + strlen(MSG_SEPARATOR)-msg_start;
        // 看看是否会处理到后面的垃圾数据(不完整的消息)
        if((proced_len+msg_len_) > recv_len_)
        {
            ACE_DEBUG((LM_WARNING, "[%D] ISGWIntf proc no end msg"
                ",proced_len=%d,msg_len_=%d,recv_len_=%d\n"
                , proced_len, msg_len_, recv_len_
                ));
            break;
        }
        if (msg_len_ > strlen(MSG_SEPARATOR) && process(msg_start, get_handle(), get_seq(), msg_len_) != 0)
        {
            //如果解析或者处理出错(后端无处理能力),整个消息一起丢弃,并导致断开连接    		
            return -1;
        }
        
        proced_len += msg_len_;
        pend_len -= msg_len_;
        msg_start = msg_end + strlen(MSG_SEPARATOR);  
        
        ACE_DEBUG((LM_TRACE, "[%D] ISGWIntf proc msg succ,msg_len=%d,proced_len=%d,pend_len=%d\n"
			, msg_len_, proced_len, pend_len));
    }
    
    //移动剩下的数据
    if (msg_start!=recv_buf_)
    {
        memmove(recv_buf_, msg_start, pend_len);
        ACE_DEBUG((LM_TRACE, "[%D] ISGWIntf proc msg move,start=%d,pend_len=%d\n"
            , (msg_start-recv_buf_), pend_len));
    }
    
    //memset(recv_buf_+pend_len, 0x0, sizeof(recv_buf_)-pend_len);
    recv_len_ = pend_len; // reset the recv pos indicator    
    
    return 0;
}
Пример #23
0
int table_idx(char ch)
{
    /* compute what index to use for a given character (32-127 range) */
    assert(is_legal(ch)); /* in case illegal chars */
    return ch - PRINT_MIN; /* guaranteed >= 0, < PRINT_RANGE */
}
Пример #24
0
void triangulate(const Polygon& polygon, Triangle_iter triangles, 
		 const boost::unordered_map<Point_3, boost::unordered_set<Segment_3_undirected> >& point2edges)
{
  typedef CGAL::Triangulation_vertex_base_2<Kernel>                     Vb;
  typedef CGAL::Triangulation_vertex_base_with_info_2<bool, Kernel, Vb>     Info;
  typedef CGAL::Constrained_triangulation_face_base_2<Kernel>           Fb;
  typedef CGAL::Triangulation_data_structure_2<Info,Fb>              TDS;
  typedef CGAL::Exact_predicates_tag                               Itag;
  typedef CGAL::Constrained_Delaunay_triangulation_2<Kernel, TDS, Itag> CDT;

  static log4cplus::Logger tlogger = log4cplus::Logger::getInstance("polygon_utils");

  LOG4CPLUS_TRACE(tlogger, "Triangulating " << pp(polygon));

  if (polygon.size() < 3) return;

  Polygon p = polygon;
  bool vertical = is_vertical(p);
  if (vertical)
  {
    LOG4CPLUS_TRACE(tlogger, "Polygon is vertical.  Rotating.");
    p = yz_swap_neg(p);
  }

  bool reverse = !p.is_counterclockwise_oriented();

  // THIS IS BAD, BAD, BAD!
  {
    typename Polygon::Vertex_circulator start = p.vertices_circulator();
    typename Polygon::Vertex_circulator c = start;
    typename Polygon::Vertex_circulator n = c;
    typename Polygon::Vertex_circulator prev = c;
    ++n;
    --prev;
    Polygon_2 newp;
    do
    {
      if (!CGAL::collinear(*prev, *c, *n))
	newp.push_back(*c);
      ++prev;
      ++c;
      ++n;
    } while (c != start);
    p = newp;
  }

  CDT cdt;
  typename Polygon::Vertex_circulator start = p.vertices_circulator();
  typename Polygon::Vertex_circulator c = start;
  typename Polygon::Vertex_circulator n = c;
  do
  {
    cdt.insert_constraint(*c, *n);
    ++c;
    ++n;
  } while (c != start);

  // Loop through the triangulation and store the vertices of each triangle
  for (CDT::Finite_faces_iterator ffi = cdt.finite_faces_begin();
       ffi != cdt.finite_faces_end();
       ++ffi)
  {
    Triangle t;
    Point_3 center = centroid(ffi->vertex(0)->point(), ffi->vertex(1)->point(), ffi->vertex(2)->point());
    if (p.has_on_bounded_side(center) && 
	is_legal(ffi->vertex(0)->point(), ffi->vertex(1)->point(), ffi->vertex(2)->point(), point2edges))
    {
      for (int i = 0; i < 3; ++i)
      {
	int idx = reverse ? 2-i : i;
	if (!vertical)
	  t[idx] = ffi->vertex(i)->point();
	else
	  t[idx] = yz_swap_pos(ffi->vertex(i)->point());
      }
      LOG4CPLUS_TRACE(tlogger, "Adding tile: " << pp_tri(t));
      *triangles = t;
      ++triangles;
    }
  }
}
Пример #25
0
// Every processor other than 0 will loop in this function until a terminate signal (comm with count 0) is received.
void dfs_mpi()
{
	MPI_Status probeStatus;
	int count;
	int legalMoves;
	long subtreeScore;
	long nodeScore;
	char tempBoard[BOARD_SIZE * BOARD_SIZE];
	int tempWhitePrisoners;
	int tempBlackPrisoners;
	int color;
	int turnNumber;
	
	while (1)
	{
		MPI_Probe(0, 19, MPI_COMM_WORLD, &probeStatus);
		MPI_Get_count(&probeStatus, MPI_CHAR, &count);
		
		if (count == 0) 
		{ 
			return; // exit 
		} else 
		{
			legalMoves = 0;
			//printf("%d: receiving %d\n", my_rank, count);
			//fflush(stdout);
			char board[count];
			MPI_Recv(board, count, MPI_CHAR, 0, 19, MPI_COMM_WORLD, MPI_STATUS_IGNORE ); // receive board state from process 0
			
			turnNumber = (int) board[count - 2];
			color = (int) board[count - 1];
			
			get_black_score(board, turnNumber);
			get_white_score(board, turnNumber);
			nodeScore = calculate_influence(board);
			subtreeScore = 0;
			
			// only focus on expanding groups in the early turns
			if (turnNumber < EARLY_TURNS)
			{
				#pragma omp parallel default(shared) private(tempBoard) reduction(+: subtreeScore, legalMoves)
				#pragma omp for 
				for ( int i = 0; i < BOARD_SIZE * BOARD_SIZE; i++ )
				{
					if ( has_neighbors_color(i, board, color) && (is_legal (i, board, turnNumber) == 0) )
					{
						legalMoves++;
						memcpy( tempBoard, board, BOARD_SIZE * BOARD_SIZE * sizeof(char) );
						tempBlackPrisoners = (int) board[count - 4];
						tempWhitePrisoners = (int) board[count - 3];
						tempBoard[i] = color;
						
						//subtreeScore += parallel_dfs(tempBoard, tempBlackPrisoners, tempWhitePrisoners, 1, color, turnNumber + 2);
						subtreeScore += parallel_dfs_group_focused(tempBoard, tempBlackPrisoners, tempWhitePrisoners, 1, color, turnNumber + 2);
					}
				}																				
			} else
			{
				// iterate through all legal moves using openMP for additional parallelization
				// calculate the score of each subtree using a recursive depth-first search
				#pragma omp parallel default(shared) private(tempBoard) reduction(+: subtreeScore, legalMoves)
				#pragma omp for 
				for ( int i = 0; i < BOARD_SIZE * BOARD_SIZE; i++ )
				{
					if ( is_legal (i, board, turnNumber) == 0 )
					{
						legalMoves++;
						memcpy( tempBoard, board, BOARD_SIZE * BOARD_SIZE * sizeof(char) );
						tempBlackPrisoners = (int) board[count - 4];
						tempWhitePrisoners = (int) board[count - 3];
						tempBoard[i] = color;
						
						//subtreeScore += parallel_dfs(tempBoard, tempBlackPrisoners, tempWhitePrisoners, 1, color, turnNumber + 2);
						subtreeScore += parallel_dfs_group_focused(tempBoard, tempBlackPrisoners, tempWhitePrisoners, 1, color, turnNumber + 2);
					}
				}
				
				// check score for passing move
				legalMoves++;
				memcpy( tempBoard, board, BOARD_SIZE * BOARD_SIZE * sizeof(char) );
				tempBlackPrisoners = board[count - 3];
				tempWhitePrisoners = board[count - 2];
				
				//subtreeScore += parallel_dfs(tempBoard, tempBlackPrisoners, tempWhitePrisoners, 1, color, turnNumber + 2);
				subtreeScore += parallel_dfs_group_focused(tempBoard, tempBlackPrisoners, tempWhitePrisoners, 1, color, turnNumber + 2);
			}
			
			nodeScore = nodeScore + ((subtreeScore)/ legalMoves);
			
			// send results back to process 0
			MPI_Send( &nodeScore, 1, MPI_LONG, 0, 19, MPI_COMM_WORLD );
		}
	}
}