Пример #1
0
 // get value as string
 // might contain '\n' if list or compound
 std::string Tag::asString() const {
     if (isIntType(type)) return std::to_string(payload->tagInt);
     else if (isFloatType(type)) return std::to_string(payload->tagFloat);
     else if (type == tagTypeString) return *payload->tagString;
     else if (isListType(type) || type == tagTypeCompound) {
         std::string str = std::to_string(getListSize()) + " entries\n{\n";
         for (int32_t i = 0; i < getListSize(); i++) {
             // limit output to 10-15 lines
             if (isListType(type) && i >= 10 && getListSize() > 15) {
                 str += "  ... and " + std::to_string(getListSize()-10) + " more\n";
                 break;
             }
             Tag * tag = getListItemAsTag(i);
             if (tag != NULL) {
                 std::string content = "  " + tag->toString();
                 // indent content
                 for (size_t pos = content.find_first_of('\n'); pos != std::string::npos; pos = content.find_first_of('\n', pos+1)) {
                     content = content.replace(pos, 1, "\n  ");
                 }
                 str += content + "\n";
             }
             else str += "  ERROR\n";
         }
         str += "}";
         return str;
     }
     return "";
 }
Пример #2
0
 TreeNode *sortedListToBST(ListNode *head) {
     if (head == NULL) {
         return NULL;
     }
     int size = getListSize(head);
     return convertHelper(head, size);
 }
Пример #3
0
char* tableToString(HashTable* t) {

	// get the total number of variable in the hashtable
	int i, numOfVariable = 0;

	for (i = 0; i < HTSIZE; i++) {
		numOfVariable += getListSize(t->table[i]);
	}

	// allocate memory for string representation of hashtable
	// assuming each variable will require 20 characters
	char* str = (char*) malloc(20 * numOfVariable * sizeof(char));

	// empty the string
	str[0] = '\0';

	// loop through the hashtable and add each list to the string
	for (i = 0; i < HTSIZE; i++) {
		char* list = listToString(t->table[i]);

		// concatenate the "list" string to the string
		if (list == NULL) {
			strcat(str, "EMPTY LIST");
		} else {
			strcat(str, list);
		}

		// insert a newline to separate terms
		strcat(str, "\n");
	}

	return str;
}
Пример #4
0
 // gets child at the given path if type is compound or list
 // returns 0 on error
 // format: "list.42.intHolder..myInt."
 // (multiple dots are like one dot, dots at the end are ignored)
 Tag * Tag::getSubTag(std::string path) {
     size_t dotPos = path.find_first_of('.');
     std::string first = path.substr(0, dotPos);
     std::string rest  = "";
     if (dotPos < path.length()) rest = path.substr(dotPos+1);
     DEBUG printf("getSubTag: path='%s', first='%s', rest='%s' at tag '%s'\n", path.c_str(), first.c_str(), rest.c_str(), name.c_str());
     if (path.length() <= 0) return this; // recursion anchor
     if (first.length() <= 0) return getSubTag(rest); // allows "foo..bar." == "foo.bar"
     Tag * tag = NULL;
     if (isListType(type) || type == tagTypeCompound) {
         for (int32_t i = 0; i < getListSize(); i++) {
             tag = getListItemAsTag(i);
             if (tag == NULL) continue; // didn't get a tag ... why?
             if (first.compare(tag->getName()) == 0)
                 break;
             else tag = NULL; // do not remember incorrect tags
         }
     }
     // we still found no matching tag, try interpreting first as number and getting n-th tag
     if (tag == NULL) {
         try {
             tag = getListItemAsTag(stoi(first));
             DEBUG printf("getting tag #%i\n", stoi(first));
         }
         catch (const std::invalid_argument& ia) {
             tag = NULL;
         }
     }
     // still no luck? we're out of ideas, return nothing
     if (tag == NULL) return NULL;
     return tag->getSubTag(rest);
 }
Пример #5
0
treeNode* myTree(treeNode *head,char inBoard[BOARDROWS][BOARDCOLS],char pColour, char cColour){
    char boardHolder[BOARDROWS][BOARDCOLS];
    int numChildren;
    node* ptr;
    if (head->board[0][0] != 'W' && head->board[0][0] != 'B' && head->board[0][0] != 'O' ){  
        copyBoard(inBoard,head->board);
    }
    if (head->numChildren == 0){
        node* moves = getMoves(head->board,cColour,pColour);
        numChildren = getListSize(moves);
        head->numChildren = numChildren;
        //printf("Generated %i moves from the head node.\n", numChildren);
        head->children = malloc(sizeof(treeNode) * numChildren);
        for(int i=0;i<numChildren;i++){
	  // printf("for\n");
            copyBoard(head->board,boardHolder);
            applyMove(moves,boardHolder);
	    //printBoard(boardHolder);
            head->children[i] = malloc(sizeof(treeNode));
            copyBoard(boardHolder,head->children[i]->board);
            head->children[i]->numChildren = 0;
	    ptr = moves->next;
	    free(moves);
	    moves = ptr;
        }
    }else{//this should happen when there are already children in the tree
      for(int i=0;i<head->numChildren;i++){
	head->children[i] = myTree(head->children[i],head->children[i]->board,cColour,pColour);
      }
    }
    return head;
}
Пример #6
0
char* listToString(List* list) {
	if (list == NULL)
		return NULL;

	// allocate memory for string
	// assuming each variable will require 20 characters to represent it
	int size = getListSize(list);
	char* str = (char*) malloc(20 * size * sizeof(char));

	// empty the string
	str[0] = '\0';

	if (isEmpty(list))
		return NULL;

	// loop through the list and add each term to the string
	Node* n = list->head;
	while (n != NULL) {
		char* variable = VariableToString(n);

		// concatenate the "variable" string to the polynomial string
		strcat(str, variable);

		// add a space to separate terms
		strcat(str, " ");

		// go to the next node
		n = n->next;
	}

	return str;

}
void COptionsOrganizerDlg::ajourButtons(int selected) {
  if(selected < 0) {
    selected = getSelectedIndex();
  }
  GetDlgItem(IDC_BUTTONRENAME  )->EnableWindow((selected >= 0             )?TRUE:FALSE);
  GetDlgItem(IDC_BUTTONDELETE  )->EnableWindow((selected >= 0             )?TRUE:FALSE);
  GetDlgItem(IDC_BUTTONMOVEUP  )->EnableWindow((selected >  0             )?TRUE:FALSE);
  GetDlgItem(IDC_BUTTONMOVEDOWN)->EnableWindow((selected >= 0)
                                            && (selected < getListSize()-1)?TRUE:FALSE);
}
Пример #8
0
//CHANGED! I added a special version of this to the OnLinePlanner so that it doesn't use the
// actual hand to show the results
void
OnLinePlanner::showGrasp(int i)
{
	assert (i>=0 && i<getListSize());
	const GraspPlanningState *s = getGrasp(i);
	s->execute(mSolutionClone);
	bool l; double e;
	mEnergyCalculator->analyzeCurrentPosture(s->getHand(), s->getObject(), l, e, false);
	DBGA("Re-computed energy: " << e);
}
UCHAR IgmpMemberCnt(
	IN PLIST_HEADER pList)
{
	if(pList == NULL)
	{
		DBGPRINT(RT_DEBUG_ERROR, ("%s: membert list doesn't exist.\n", __FUNCTION__));
		return 0;
	}

	return getListSize(pList);
}
void COptionsOrganizerDlg::OnButtonDelete() {
  const int selected = getSelectedIndex();
  if(selected >= 0) {
    const bool wasLast = selected == getListSize()-1;
    m_nameList.remove(selected);
    updateListCtrl();
    if(wasLast && (selected > 0)) {
      setSelectedIndex(m_nameListCtrl, selected-1);
    }
  }
}
Пример #11
0
void insertionSort(List *list) {
    printf("size: %d \n", getListSize(list));
    int key, i, j, mudou = 0;
    int size = getListSize(list);
    for (j = 1; j < size; j++) {
        key = getNumber(list, j);
        i = j - 1;
        while (i >= 0 && getNumber(list, i) > key) {
            positionChange(list, (i + 1), i);
            i = i - 1;
            mudou = 1;
        }
        get(list, i + 1)->number = key;
        if (mudou) {
            mudou = 0;
            show(list);
        }

    }
}
Пример #12
0
UCHAR IgmpMemberCnt(
	IN PLIST_HEADER pList)
{
	if(pList == NULL)
	{
		MTWF_LOG(DBG_CAT_ALL, DBG_SUBCAT_ALL, DBG_LVL_ERROR, ("%s: membert list doesn't exist.\n", __FUNCTION__));
		return 0;
	}

	return getListSize(pList);
}
Пример #13
0
 // gets the ith item of a list or compound
 // NULL if out of bounds or no list or compound
 Tag * Tag::getListItemAsTag(int32_t i) const {
     if (i < 0 || i >= getListSize()) return NULL;
     if (isListType(type)) {
         return createTagFromPayload(std::to_string(i),
                 payload->tagList.type,
                 payload->tagList.values->at(i));
     }
     if (type == tagTypeCompound) {
         return payload->tagCompound->at(i);
     }
     return NULL;
 }
Пример #14
0
void
OnLinePlanner::executeGrasp(int i)
{
	assert (i>=0 && i<getListSize());
	mRefHand->getIVRoot()->removeChild(mRefHand->getIVRoot()->getByName("curveX"));
	mRefHand->getIVRoot()->removeChild(mRefHand->getIVRoot()->getByName("curveZ"));
	const GraspPlanningState *s = getGrasp(i);
	s->execute(mRefHand);
	mRefHand->setTransparency(0);
	showSolutionClone(false);
	graspItGUI->getIVmgr()->emitProcessWorldPlanner(i);
}
Пример #15
0
int main() {
  int i;
  List *l = NULL;

  List *(* listAddFunc)(List *, void *) = append;
#ifdef DEMO_PREPEND
  listAddFunc = prepend;
#endif

  for (i=0; i < 40; ++i) {
    int *tp = (int *)malloc(sizeof(int));
    *tp = i;
    l = listAddFunc(l, tp);
  }

#ifdef DEMO_CIRCULARITY
  while (l->head != NULL) {
    void *vSav = listPop(&(l->head));
    if (vSav != NULL) {
      printf("vS: %d\n", *(int *)vSav);
      free(vSav);
    }
    break;
  }
#endif

  printList(l);
  printf("\n");

  i = 8;

  printf("Size: %d\n", getListSize(l));
  l = removeElem(l, &i, intPtrComp);

  printf("Size: %d\n", getListSize(l));
  printList(l);
  printf("\n");
  destroyList(l);
  return 0;
}
Пример #16
0
void bubbleSort(List *list) {
    int swap, i, j;
    int size = getListSize(list);
    swap = 1;
    while (swap) {
        swap = 0;
        for (j = 0; j < size - 1; j++) {
            if (getNumber(list, j) > getNumber(list, (j + 1))) {
                positionChange(list, (j + 1), (j));
                swap = 1;
            }
        }
        if (swap)
            show(list);
    }
}
Пример #17
0
void                    removeInListAtPos(struct s_list<T>*& begin, int pos)
{ 
  if (pos >= 0 && pos < getListSize(*begin))
    {
      if (pos == 0)
	{
	  begin = begin->next;
	  return ;
	}
      struct s_list<T>		*save = begin;
      for (int i = 1; i < pos && save->next != NULL; i++)
	save = save->next;
      save->next = save->next->next;
      
    }
}
Пример #18
0
T*			getElemInListAtPos(struct s_list<T>& begin, int pos)
{
  struct s_list<T>	*save = &begin;
  int			cpt = 0;
  

  if (pos > 0 && pos < getListSize(begin))
    {
      while (save)
	{
	  if (pos == cpt)
	    return &save->data;
	  cpt++;
	  save = save->next;
	}
    }
  return NULL;
}
Пример #19
0
void selectionSort(List *list) {
    int menor, i, j, aux, mudou = 0;
    int size = getListSize(list);
    for (i = 0; i < size - 1; i++) {
        menor = i;
        for (j = i + 1; j < size; j++) {
            if (getNumber(list, menor) > getNumber(list, j)) {
                menor = j;
                mudou = 1;
            }
        }
        positionChange(list, menor, i);
        if (mudou) {
            show(list);
            mudou = 0;
        }

    }
}
Пример #20
0
    ListNode *rotateRight(ListNode *head, int k) {
        if (head == NULL || head->next == NULL)
            return head;

        ListNode*   original_tail = NULL;
        int     size = getListSize(head, original_tail);

        k = k%size;
        if (k == 0)
            return  head;

        k = size - k;
        ListNode*   newTail = getNodeByIndex(head, k - 1);
        assert(newTail && newTail->next);

        original_tail->next = head;
        head = newTail->next;
        newTail->next = NULL;
        return head;
    }
Пример #21
0
void shellSort(List *list) {
    int size = getListSize(list);
    int i = size / 2;
    int chave, k, mudou;
    while (i != 0) {
        do {
            chave = 1;
            mudou = 0;
            for (k = 0; k < size - i; k++) {
                if (getNumber(list, k) > getNumber(list, (k + 1))) {
                    positionChange(list, k, (k + 1));
                    chave = 0;
                    mudou = 1;
                }
            }
            if (mudou)
                show(list);
        } while (chave == 0);
        i = i / 2;
    }
}
Пример #22
0
treeNode * makeTree(node * list, int layer){
  char boardHolder[BOARDROWS][BOARDCOLS];
  node* ptr;
  if(layer==2) return NULL; //We should put the evaluation function here
  layer++;
  
  treeNode * temp = malloc(sizeof(treeNode));
  int listLength = getListSize(list);
  temp->numChildren = listLength;
  temp->children = malloc(sizeof(treeNode) * listLength);
  temp->nodePtr = malloc(sizeof(node));
  for(int i = 0; i < listLength; i++){
    applyMove(list,boardHolder);
    temp->children[i] = makeTree(getMoves(boardHolder, computerColour, playerColour), layer);
    setNode(temp->nodePtr, ptr->origin.x, ptr->origin.y, ptr->jumpDest.x, ptr->jumpDest.y, ptr->dir, ptr->jumps);
    printf("made %d child\n", i+1);
    ptr = list->next;
    free(list);
    list = ptr;
  }
  return temp;
}
Пример #23
0
 ListNode* mergeKLists(vector<ListNode*>& lists) {
     multimap<int,int> mp;
     int K = lists.size();
     if(K==0) return NULL;
     for(int i=0; i<K; i++)
         mp.insert(pair<int,int>(getListSize(lists[i]),i));
     while(mp.size()>=2)
     {
         auto it = mp.begin();
         int size1 = it->first;
         int idx1 = it->second;
         mp.erase(it);
         it = mp.begin();
         int size2 = it->first;
         int idx2 = it->second;
         mp.erase(it);
         int new_idx = min(idx1, idx2);
         lists[new_idx] = mergeTwoLists(lists[idx1], lists[idx2]);
         mp.insert(pair<int,int>(size1+size2,new_idx));
     }
     return lists[0];
 }
Пример #24
0
//Remove a node based off of its data
int removeLinkDataByValue(VyNode* head, void* data)
{
	int i;
	int numNodes = getListSize(head);
	//Loop through the nodes
	for(i = 0;i < numNodes;i++)
	{
		//Check to see if the data matches the desired value
	    if(head->data == data)
	    {
			//Remove the node from the list
			VyNode* temp = head->nextNode;
			if(head->nextNode != NULL)
				head->nextNode = head->nextNode->nextNode;
			free(temp);
			//Return success
			return 1;
	    }
	    head = head->nextNode;
	}
	//Node was not found return failure
	return 0;
}
Пример #25
0
int Search::printDtm() {
    int side = getSide();
    u64 friends = side == WHITE ? getBitmap<WHITE>() : getBitmap<BLACK>();
    u64 enemies = side == BLACK ? getBitmap<WHITE>() : getBitmap<BLACK>();
    display();
    int res = side ? getGtb().getDtm<WHITE, true>(chessboard, chessboard[RIGHT_CASTLE_IDX], 100) : getGtb().getDtm<BLACK, true>(chessboard, chessboard[RIGHT_CASTLE_IDX], 100);
    cout << " res: " << res;
    incListId();
    generateCaptures(side, enemies, friends);
    generateMoves(side, friends | enemies);
    _Tmove *move;
    u64 oldKey = 0;
    cout << "\n succ. \n";
    int best = -_INFINITE;
    for (int i = 0; i < getListSize(); i++) {
        move = &gen_list[listId].moveList[i];
        makemove(move, false, false);
        cout << "\n" << decodeBoardinv(move->type, move->from, getSide()) << decodeBoardinv(move->type, move->to, getSide()) << " ";
        res = side ? -getGtb().getDtm<BLACK, true>(chessboard, chessboard[RIGHT_CASTLE_IDX], 100) : getGtb().getDtm<WHITE, true>(chessboard, chessboard[RIGHT_CASTLE_IDX], 100);
        if (res != -INT_MAX) {
            cout << " res: " << res;
        }
        cout << "\n";
        takeback(move, oldKey, false);
        if (res > best) {
            best = res;
        }
    }
    if (best > 0) {
        best = _INFINITE - best;
    } else if (best < 0) {
        best = -(_INFINITE - best);
    }
    cout << endl;
    decListId();
    return best;
}
Пример #26
0
/*
 * Returns true if a linked list of ints, starting at HEAD, is a palindrome. Runs in O(n) time with O(1) space complexity.
 * My method was to split the linked list in half, reverse the second half, then make side by side comparisons
 * of the two new linked lists. This only incurs 4 O(n) loops through the list, plus an additional 2 O(n) loops
 * to restore the linked list back to normal. The last 2 loops are for cleanup purposes, since my list is
 * dynamically allocated.
 */
bool isPalindrome(ListNode* head) {
  if (!head || !head->next) return true;

  ListNode* listFirstHead = head;
  ListNode* listFirstIter = head;
  ListNode* listSecondHead = NULL;
  ListNode* listSecondIter = NULL;
  int size = getListSize(head);

  //SPLIT THE LIST
  for (int i=0; i<size/2-1; ++i){
    listFirstIter = listFirstIter->next;
  }
  listSecondHead = listFirstIter->next; //found second half
  listSecondHead = reverseList(listSecondHead);
  listFirstIter->next = NULL;   //cuts first half off from second half
  //Note that second half of linked list will alway be 0 or 1 element longer than the first half

  //ITERATE THROUGH THE TWO HALFS TO CHECK IF THE LINKED LIST IS A PALINDROME
  listFirstIter = listFirstHead;
  listSecondIter = listSecondHead;
  while (listFirstIter && listSecondIter) {
    if (listFirstIter->val != listSecondIter->val) return false;
    else {
      listFirstIter = listFirstIter->next;
      listSecondIter = listSecondIter->next;
    }
  }

  //Optional-ish: Restore the Linked List (for cleanup later)
  listSecondHead = reverseList(listSecondHead);
  listFirstIter = getTail(listFirstHead);
  listFirstIter->next = listSecondHead;

  return true;
}
Пример #27
0
//Get the data from the list at a specified point
void* getLinkData(VyNode* head, int pos)
{
	if(getListSize(head) < pos-1)
	  return NULL;
	return (getNodeAtSpot(head,pos))->data;
}
Пример #28
0
int Search::quiescence(int alpha, int beta, const char promotionPiece, int N_PIECE, int depth) {
    if (!getRunning()) {
        return 0;
    }
    ASSERT(chessboard[KING_BLACK + side]);
    if (!(numMovesq++ & 1023)) {
        setRunning(checkTime());
    }

    int score = getScore(side, N_PIECE, alpha, beta, false);
    if (score >= beta) {
        return beta;
    }
    ///************* hash ****************
    char hashf = Hash::hashfALPHA;
    u64 zobristKeyR = chessboard[ZOBRISTKEY_IDX] ^_random::RANDSIDE[side];

    _TcheckHash checkHashStruct;

    if (checkHash<Hash::HASH_GREATER, smp>(true, alpha, beta, depth, zobristKeyR, checkHashStruct)) {
        return checkHashStruct.res;
    };
    if (checkHash<Hash::HASH_ALWAYS, smp>(true, alpha, beta, depth, zobristKeyR, checkHashStruct)) {
        return checkHashStruct.res;
    };

///********** end hash ***************
/**************Delta Pruning ****************/
    char fprune = 0;
    int fscore;
    if ((fscore = score + (promotionPiece == NO_PROMOTION ? VALUEQUEEN : 2 * VALUEQUEEN)) < alpha) {
        fprune = 1;
    }
/************ end Delta Pruning *************/
    if (score > alpha) {
        alpha = score;
    }

    incListId();

    u64 friends = getBitmap<side>();
    u64 enemies = getBitmap<side ^ 1>();
    if (generateCaptures<side>(enemies, friends)) {
        decListId();

        return _INFINITE - (mainDepth + depth);
    }
    if (!getListSize()) {
        --listId;
        return score;
    }
    _Tmove *move;
    _Tmove *best = nullptr;
    u64 oldKey = chessboard[ZOBRISTKEY_IDX];
    if (checkHashStruct.hashFlag[Hash::HASH_GREATER]) {
        sortHashMoves(listId, checkHashStruct.phasheType[Hash::HASH_GREATER]);
    } else if (checkHashStruct.hashFlag[Hash::HASH_ALWAYS]) {
        sortHashMoves(listId, checkHashStruct.phasheType[Hash::HASH_ALWAYS]);
    }
    while ((move = getNextMove(&gen_list[listId]))) {
        if (!makemove(move, false, true)) {
            takeback(move, oldKey, false);
            continue;
        }
/**************Delta Pruning ****************/
        if (fprune && ((move->type & 0x3) != PROMOTION_MOVE_MASK) && fscore + PIECES_VALUE[move->capturedPiece] <= alpha) {
            INC(nCutFp);
            takeback(move, oldKey, false);
            continue;
        }
/************ end Delta Pruning *************/
        int val = -quiescence<side ^ 1, smp>(-beta, -alpha, move->promotionPiece, N_PIECE - 1, depth - 1);
        score = max(score, val);
        takeback(move, oldKey, false);
        if (score > alpha) {
            if (score >= beta) {
                decListId();
                ASSERT(checkHashStruct.rootHash[Hash::HASH_GREATER]);
                ASSERT(checkHashStruct.rootHash[Hash::HASH_ALWAYS]);
                recordHash<smp>(getRunning(), checkHashStruct.rootHash, depth, Hash::hashfBETA, zobristKeyR, score, move);
                return beta;
            }
            best = move;
            alpha = score;
            hashf = Hash::hashfEXACT;
        }
    }
    ASSERT(checkHashStruct.rootHash[Hash::HASH_GREATER]);
    ASSERT(checkHashStruct.rootHash[Hash::HASH_ALWAYS]);
    recordHash<smp>(getRunning(), checkHashStruct.rootHash, depth, hashf, zobristKeyR, score, best);

    decListId();

    return score;
}
Пример #29
0
//Function to read in messages from each connection and call the corresponding callback
void messageReader(SSLParser sslParser, StandardParser standardParser, UDPParser udpParser, TimeoutFunction timeoutFunction )
{
	int size = getListSize(connNode);
	int i;
	//Loop through all active connections
	for(i = 0;i < size;i++)
	{
		VyConnNode* node = getNodeAtSpot(connNode,i)->data;
		//If it is a TCP connection make sure it is still alive
		if(node->type == TCP_CONNECTION && timeoutFunction != NULL)
		{
		  //If a great deal of time has passed with no response call the timeout function
		  if(node->lastPing++ > 100000000)
		  {
			  //timeoutFunction(node);
		  }
		  //If a short deal of time has time request a ping
		  else if(node->lastPing == 10000000)
		  {	
		      VyConn* conn = node->data;
		      uuid_t* id = generateUniqueID();
		      char* cID = printUniqueID(id);
		      free(id);
		      VyMessage* m = generateNewMessage(cID,"Ping","Request",strlen("Request")+1);
		      sendMessage(conn->socket,m);
		      destroyVyMessage(m);
		      free(cID);
		  }
		}
		VyMessage* message = NULL;
		//Attempt to read in data from the socket and parse it correctly with the assigned callbacks
		if(node->type == TCP_CONNECTION)
		{
			VyConn* conn = node->data;
			message = readMessage(conn);
			if(message != NULL)
			{
				//VyLog(1,"TCP message recieved\r\n");
				standardParser(node, message);
			}
		}
		else if(node->type == SSL_CONNECTION)
		{
			VySSL* ssl = (VySSL*)node->data;
			message = readSSLMessage(ssl);
			if(message != NULL)
			{
				//VyLog(1,"SSL message recieved\r\n");
				sslParser(node, message);
			}
		}
		else if(node->type == UDP_CONNECTION)
		{
			VyConn* conn = node->data;
			message = readUDPMessage(conn);
			if(message != NULL)
			{
				//VyLog(1,"UDP message recieved\r\n");
				udpParser(node, message);
			}
		}
		if(message != NULL)
		   destroyVyMessage(message);
	}
}
Пример #30
0
int Search::search(int depth, int alpha, int beta, _TpvLine *pline, int N_PIECE, int *mateIn) {
    ASSERT_RANGE(depth, 0, MAX_PLY);
    INC(cumulativeMovesCount);
    *mateIn = INT_MAX;
    ASSERT_RANGE(side, 0, 1);
    if (!getRunning()) {
        return 0;
    }
    int score = -_INFINITE;
    /* gtb */
    if (gtb && pline->cmove && maxTimeMillsec > 1000 && gtb->isInstalledPieces(N_PIECE) && depth >= gtb->getProbeDepth()) {
        int v = gtb->getDtm<side, false>(chessboard, (uchar) chessboard[RIGHT_CASTLE_IDX], depth);
        if (abs(v) != INT_MAX) {
            *mateIn = v;
            int res = 0;
            if (v == 0) {
                res = 0;
            } else {
                res = _INFINITE - (abs(v));
                if (v < 0) {
                    res = -res;
                }
            }
            ASSERT_RANGE(res, -_INFINITE, _INFINITE);
            ASSERT(mainDepth >= depth);
            return res;
        }
    }
    u64 oldKey = chessboard[ZOBRISTKEY_IDX];
#ifdef DEBUG_MODE
    double betaEfficiencyCount = 0.0;
#endif
    ASSERT(chessboard[KING_BLACK]);
    ASSERT(chessboard[KING_WHITE]);
    ASSERT(chessboard[KING_BLACK + side]);
    int extension = 0;
    int is_incheck_side = inCheck<side>();
    if (!is_incheck_side && depth != mainDepth) {
        if (checkInsufficientMaterial(N_PIECE)) {
            if (inCheck<side ^ 1>()) {
                return _INFINITE - (mainDepth - depth + 1);
            }
            return -lazyEval<side>() * 2;
        }
        if (checkDraw(chessboard[ZOBRISTKEY_IDX])) {
            return -lazyEval<side>() * 2;
        }
    }
    if (is_incheck_side) {
        extension++;
    }
    depth += extension;
    if (depth == 0) {
        return quiescence<side, smp>(alpha, beta, -1, N_PIECE, 0);
    }

    //************* hash ****************
    u64 zobristKeyR = chessboard[ZOBRISTKEY_IDX] ^_random::RANDSIDE[side];

    _TcheckHash checkHashStruct;

    if (checkHash<Hash::HASH_GREATER, smp>(false, alpha, beta, depth, zobristKeyR, checkHashStruct)) {
        return checkHashStruct.res;
    };
    if (checkHash<Hash::HASH_ALWAYS, smp>(false, alpha, beta, depth, zobristKeyR, checkHashStruct)) {
        return checkHashStruct.res;
    };
    ///********** end hash ***************

    if (!(numMoves & 1023)) {
        setRunning(checkTime());
    }
    ++numMoves;
    ///********* null move ***********
    int n_pieces_side;
    _TpvLine line;
    line.cmove = 0;

    if (!is_incheck_side && !nullSearch && depth >= NULLMOVE_DEPTH && (n_pieces_side = getNpiecesNoPawnNoKing<side>()) >= NULLMOVES_MIN_PIECE) {
        nullSearch = true;
        int nullScore = -search<side ^ 1, smp>(depth - (NULLMOVES_R1 + (depth > (NULLMOVES_R2 + (n_pieces_side < NULLMOVES_R3 ? NULLMOVES_R4 : 0)))) - 1, -beta, -beta + 1, &line, N_PIECE, mateIn);
        nullSearch = false;
        if (nullScore >= beta) {
            INC(nNullMoveCut);
            return nullScore;
        }
    }
    ///******* null move end ********
    /**************Futility Pruning****************/
    /**************Futility Pruning razor at pre-pre-frontier*****/
    bool futilPrune = false;
    int futilScore = 0;
    if (depth <= 3 && !is_incheck_side) {
        int matBalance = lazyEval<side>();
        if ((futilScore = matBalance + FUTIL_MARGIN) <= alpha) {
            if (depth == 3 && (matBalance + RAZOR_MARGIN) <= alpha && getNpiecesNoPawnNoKing<side ^ 1>() > 3) {
                INC(nCutRazor);
                depth--;
            } else
                ///**************Futility Pruning at pre-frontier*****
            if (depth == 2 && (futilScore = matBalance + EXT_FUTILY_MARGIN) <= alpha) {
                futilPrune = true;
                score = futilScore;
            } else
                ///**************Futility Pruning at frontier*****
            if (depth == 1) {
                futilPrune = true;
                score = futilScore;
            }
        }
    }
    /************ end Futility Pruning*************/
    incListId();
    ASSERT_RANGE(KING_BLACK + side, 0, 11);
    ASSERT_RANGE(KING_BLACK + (side ^ 1), 0, 11);
    u64 friends = getBitmap<side>();
    u64 enemies = getBitmap<side ^ 1>();
    if (generateCaptures<side>(enemies, friends)) {
        decListId();
        score = _INFINITE - (mainDepth - depth + 1);
        return score;
    }
    generateMoves<side>(friends | enemies);
    int listcount = getListSize();
    if (!listcount) {
        --listId;
        if (is_incheck_side) {
            return -_INFINITE + (mainDepth - depth + 1);
        } else {
            return -lazyEval<side>() * 2;
        }
    }
    _Tmove *best = nullptr;
    if (checkHashStruct.hashFlag[Hash::HASH_GREATER]) {
        sortHashMoves(listId, checkHashStruct.phasheType[Hash::HASH_GREATER]);
    } else if (checkHashStruct.hashFlag[Hash::HASH_ALWAYS]) {
        sortHashMoves(listId, checkHashStruct.phasheType[Hash::HASH_ALWAYS]);
    }
    INC(totGen);
    _Tmove *move;
    bool checkInCheck = false;
    int countMove = 0;
    char hashf = Hash::hashfALPHA;
    while ((move = getNextMove(&gen_list[listId]))) {
        countMove++;
        INC(betaEfficiencyCount);
        if (!makemove(move, true, checkInCheck)) {
            takeback(move, oldKey, true);
            continue;
        }
        checkInCheck = true;
        if (futilPrune && ((move->type & 0x3) != PROMOTION_MOVE_MASK) && futilScore + PIECES_VALUE[move->capturedPiece] <= alpha && !inCheck<side>()) {
            INC(nCutFp);
            takeback(move, oldKey, true);
            continue;
        }
        //Late Move Reduction
        int val = INT_MAX;
        if (countMove > 4 && !is_incheck_side && depth >= 3 && move->capturedPiece == SQUARE_FREE && move->promotionPiece == NO_PROMOTION) {
            currentPly++;
            val = -search<side ^ 1, smp>(depth - 2, -(alpha + 1), -alpha, &line, N_PIECE, mateIn);
            ASSERT(val != INT_MAX);
            currentPly--;
        }
        if (val > alpha) {
            int doMws = (score > -_INFINITE + MAX_PLY);
            int lwb = max(alpha, score);
            int upb = (doMws ? (lwb + 1) : beta);
            currentPly++;
            val = -search<side ^ 1, smp>(depth - 1, -upb, -lwb, &line, move->capturedPiece == SQUARE_FREE ? N_PIECE : N_PIECE - 1, mateIn);
            ASSERT(val != INT_MAX);
            currentPly--;
            if (doMws && (lwb < val) && (val < beta)) {
                currentPly++;
                val = -search<side ^ 1, smp>(depth - 1, -beta, -val + 1, &line, move->capturedPiece == SQUARE_FREE ? N_PIECE : N_PIECE - 1, mateIn);
                currentPly--;
            }
        }
        score = max(score, val);
        takeback(move, oldKey, true);
        move->score = score;
        if (score > alpha) {
            if (score >= beta) {
                decListId();
                ASSERT(move->score == score);
                INC(nCutAB);
                ADD(betaEfficiency, betaEfficiencyCount / (double) listcount * 100.0);
                ASSERT(checkHashStruct.rootHash[Hash::HASH_GREATER]);
                ASSERT(checkHashStruct.rootHash[Hash::HASH_ALWAYS]);
                recordHash<smp>(getRunning(), checkHashStruct.rootHash, depth - extension, Hash::hashfBETA, zobristKeyR, score, move);
                setKillerHeuristic(move->from, move->to, 0x400);
                return score;
            }
            alpha = score;
            hashf = Hash::hashfEXACT;
            best = move;
            move->score = score;    //used in it
            updatePv(pline, &line, move);
        }
    }
    ASSERT(checkHashStruct.rootHash[Hash::HASH_GREATER]);
    ASSERT(checkHashStruct.rootHash[Hash::HASH_ALWAYS]);
    recordHash<smp>(getRunning(), checkHashStruct.rootHash, depth - extension, hashf, zobristKeyR, score, best);
    decListId();
    return score;
}