void StudentTree::Balance(int min, int max, LinkedList* list, bool bstId)
{
    if (min <= max)
    {
        list->IteratorReset();

        int middleNode = (int)ceil(((double)min + max) / 2);
        TREE_NODE* node = list->IteratorGoTo(middleNode);

        //*node->data->bstId = *node->data->bstName = 0;
        //node->data->bstId = node->data->bstName = 0;
        node->left = node->right = 0;

        if (bstId)
        {
            node->data->bstId = 0;
            InsertSortedId(&(this->bstId->root), node);
        }
        else
        {
            node->data->bstName = 0;
            InsertSortedName(&(this->bstName->root), node);
        }

        Balance(min, middleNode - 1, list, bstId);
        Balance(middleNode + 1, max, list, bstId);
    }
}
Node AVL_tree::Remove(Node& node, data d){

  if(node == NULL)
    return NULL;

  if(d < node->d)
    node->left = Remove(node->left,d);
  else if(d > node->d)
    node->right = Remove(node->right,d);
  else{ // d == node->d
    Node l = node->left;
    Node r = node->right;
    delete(node);
    --mSize;
    if(r == NULL)
      return l; 
    Node min = FindMin(r);
    min->right = ExtractMin(r);
    min->left = l;
    Balance(min);
    return min;
  }
  Balance(node);
  return node;
}
Exemple #3
0
/*******************************************************************************
  Função recursiva que insere os elementos de uma lista numa arvore vazia de modo
  que ela fique balanceada.
  
  Recursive function that inserts an ordered array of elements in a tree in order
  that the is built a balanced tree.
*******************************************************************************/
static void Balance (PtABPNode *proot, int plist[], int pbegin, int pend)
{
	unsigned int Median;

	if (pbegin <= pend)
	{
		Median = (pbegin + pend) >> 1;	/* (pbegin+pend)/2 - calculating the middle position */
		ABPInsertRec (proot, plist[Median]);	/* inserir elemento central - insert the central element */
		Balance (proot, plist, pbegin, Median-1);	/* subarvore esquerda - left subtree */
		Balance (proot, plist, Median+1, pend);	/* subarvore direita - right subtree */
	}
void StudentTree::Balance()
{
    tempLList->Free();
    GenerateInOrder(bstId->root, false, tempLList);
    DeleteTree(&(bstId->root));
    Balance(0, tempLList->Size()-1, tempLList, true);

    tempLList->Free();
    GenerateInOrder(bstName->root, false, tempLList);
    DeleteTree(&(bstName->root));
    Balance(0, tempLList->Size()-1, tempLList, false);
}
static bool Balance(TreeNode* node, int& height){
    if(node == NULL){
        height = 0;
        return true;
    }
    
    int left = 0, right = 0;
    if(!Balance(node->left, left) || !Balance(node->right, right) || abs(left-right) > 1){
        return false;
    }
        
    height = left > right ? left + 1 : right + 1;
    return true;
} 
Exemple #6
0
NodeT *deleteNode(NodeT *root, int value)
{
    NodeT *minNode;
    if(root == NULL)
        return NULL;
    else
        if(root->data > value)
            root->left = deleteNode(root->left, value);
        else
            if(root->data < value)
               root->right = deleteNode(root->right, value);
            else // found the node that I want to delete
            {
                if(root->left == NULL)
                {
                        minNode = root;
                        root = root->right;
                        free(minNode);
                }
                else
                    if(root->right == NULL)
                    {
                        minNode = root;
                        root = root->left;
                        free(minNode);
                    }
                    else
                    {
                        minNode = findMin(root->right);
                        root->data=minNode->data;
                        root->right = deleteNode(root->right, minNode->data);
                    }
            }
    return Balance(root);
}
Exemple #7
0
int ntree::Insert(const char *dat,int size,int place){
	ops[1]++;
	if (place<0) return 0;
	if (size<=0) return 0;
	if (!dat) return 0;
	if (place>=siz) return 0;

	int s=0,oplace=place;
	for (int i=0;i<MAXNTN;i++){
		if (!data[i])continue;
		s+=data[i]->Insert(dat,size,place);
		if (s){
			siz+=s;
			Balance((ntree**)data+i);
			break;
		}
		place-=data[i]->Size();
	}

	if (!s){
		printf("no add! %d,%d,%d\n",oplace,size,siz);
	}

	return s;
}
void KnapsackRandomize(void *a) {
	TRAIN_ANNEAL *anneal;
	int dimensions,i,  holdingEverythingAlready, pt;
	unsigned char *position;

	anneal = (TRAIN_ANNEAL*)a;
	position = (unsigned char*)anneal->train.trial_position;
	dimensions = anneal->train.position_size/sizeof(unsigned char);

	/* check for strange case where we have everything!
		This means that the max allowed knapsack weight is greater than the total of grabbing everything.
		This is kind of pointless, but don't go into an endless loop! */
	holdingEverythingAlready = 1;
	for (i=0;i<dimensions;i++) {
		if (!position[i]) {
			holdingEverythingAlready = 0;
			break;
		}
	}

	if (!holdingEverythingAlready) {
		/* try to add something */
		pt = RandNextIntRange(anneal->train.random, 0, dimensions); /* prime */
		while (position[pt]) {
			pt = RandNextIntRange(anneal->train.random, 0, dimensions);
		}

		/* add the item we found */
		position[pt] = 1;

		/* We probably need to drop something now. */
		Balance((KNAPSACK_PARAMS*)anneal->train.params, position, dimensions);
	}
}
bool cCharStuff::cBankerAI::DoAI(int c, P_CHAR pBanker, const QString& comm)
{
	P_CHAR pc_currchar = currchar[c];

	string search2("BALANCE");
	string search3("WITHDRAW") ;
	string search4("CHECK") ;

	if (SrvParams->useSpecialBank())
	{
		if ((comm.contains(SrvParams->specialBankTrigger(), false)) &&(!(pc_currchar->dead)))
		{
			openspecialbank(c, currchar[c]);
			return true;
		}
	}
    else if ((comm.contains("BANK")) &&(!(pc_currchar->dead)))
	{
		OpenBank(c);
		return true;
	}
    else if ((comm.contains("BALANCE")) &&(!(pc_currchar->dead)))
	{
		return Balance(c, pBanker);
	}
	else if ((comm.contains("WITHDRAW")) &&(!(pc_currchar->dead)))
	{
		return Withdraw(c, pBanker, comm.latin1());
	}
	else if ((comm.contains("CHECK")) &&(!(pc_currchar->dead)))
	{
		return BankCheck(c, pBanker, comm.latin1());
	}
	return true;
}
Exemple #10
0
AVL* Delete(AVL* root, KEY_TYPE key){
    if (root != NULL){
        if (key == root->key){
            AVL* toFree = root;
            if (root->rchild == NULL){
                root = root->lchild;
                free(toFree);
            } else if (root->lchild == NULL){
                root = root->rchild;
                free(toFree);
            } else {
                AVL* minNode = root->rchild;
                while (minNode->lchild != NULL){
                    minNode = minNode->lchild;
                }
                root->key = minNode->key;
                root->rchild = Delete(root->rchild, root->key);
            }
        } else if (key < root->key){
            root->lchild = Delete(root->lchild, key);
        } else if (key > root->key){
            root->rchild = Delete(root->rchild, key);
        }
        root = Balance(root);
    }
    return root;
}
Node AVL_tree::ExtractMin(Node& node){
  if(node->left == NULL){
    return node->right;
  }
  node->left = ExtractMin(node->left);
  Balance(node);
  return node;
}
void b2DynamicTree::RemoveLeaf(int32 leaf)
{
	if (leaf == m_root)
	{
		m_root = b2_nullNode;
		return;
	}

	int32 parent = m_nodes[leaf].parent;
	int32 grandParent = m_nodes[parent].parent;
	int32 sibling;
	if (m_nodes[parent].child1 == leaf)
	{
		sibling = m_nodes[parent].child2;
	}
	else
	{
		sibling = m_nodes[parent].child1;
	}

	if (grandParent != b2_nullNode)
	{
		// Destroy parent and connect sibling to grandParent.
		if (m_nodes[grandParent].child1 == parent)
		{
			m_nodes[grandParent].child1 = sibling;
		}
		else
		{
			m_nodes[grandParent].child2 = sibling;
		}
		m_nodes[sibling].parent = grandParent;
		FreeNode(parent);

		// Adjust ancestor bounds.
		int32 index = grandParent;
		while (index != b2_nullNode)
		{
			index = Balance(index);

			int32 child1 = m_nodes[index].child1;
			int32 child2 = m_nodes[index].child2;

			m_nodes[index].aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb);
			m_nodes[index].height = 1 + b2Max(m_nodes[child1].height, m_nodes[child2].height);

			index = m_nodes[index].parent;
		}
	}
	else
	{
		m_root = sibling;
		m_nodes[sibling].parent = b2_nullNode;
		FreeNode(parent);
	}

	//Validate();
}
Exemple #13
0
AVL* Insert(AVL* root, KEY_TYPE key){
    if (root == NULL){
        root = (AVL*)malloc(sizeof(AVL));
		if (root == NULL){
            printf("out of memory");
			exit(0);
		}
        root->key = key;
        root->height = 0;
        root->lchild = root->rchild = NULL;
    } else if (key < root->key){
        root->lchild = Insert(root->lchild, key);
        root = Balance(root);
    } else if (key > root->key){
        root->rchild = Insert(root->rchild, key);
        root = Balance(root);
    }
    return root;
}
Exemple #14
0
	static pNode raw_Insert(pNode p, int K, Handle& h)
	{
		if (!p) return h = new Node(K);

		if (K < p->Key)
			p->Left = raw_Insert(p->Left, K, h);
		else
			p->Right = raw_Insert(p->Right, K, h);
		Balance(p);
		return p;
	}	
Exemple #15
0
void AVLDeleteRec (PtAVLNode *proot, int pelem)	/* recursiva */
{
	if (*proot == NULL) { Error = NO_ELEM; return; }	/* arvore vazia ou elemento inexistente */

	if ((*proot)->Elem > pelem)
			AVLDeleteRec (&(*proot)->PtLeft, pelem);
	else	if ((*proot)->Elem < pelem)
				AVLDeleteRec (&(*proot)->PtRight, pelem);
			else { Error = OK; NodeDelete (proot); }

	Balance (proot);	/* reequilibrar a árvore */
}
Exemple #16
0
void AVLInsertRec (PtAVLNode *proot, int pelem)	/* inserção recursiva - recursive insertion */
{
	if (*proot == NULL) 	/* inserir o elemento - inserting the element */
	{ if ((*proot = AVLNodeCreate (pelem)) == NULL) return; }
	else	if ((*proot)->Elem > pelem)	/* subarvore esquerda - left subtree */
				AVLInsertRec (&(*proot)->PtLeft, pelem);
			else	if ((*proot)->Elem < pelem)	/* subarvore direita - right subtree */
						AVLInsertRec (&(*proot)->PtRight, pelem);
					else { Error = REP_ELEM; return; }	/* o elemento já existe - element already exists */

	Balance (proot);	/* reequilibrar a árvore - balancing the tree */
}
Exemple #17
0
 //traverse down the tree, and find the right spot
 void InsertHelper (Node* node, int val) {
   if (val < node->val) {
     //if the left child is null, stick it in there
     if (node->left == 0) {
       node->left = new Node (val);
       //check for the balanced factor, rebalanced if needed
       Balance (node);
     }
     else
       //otherwise recursivly search the left subtree
       InsertHelper (node->left, val);
   }
   else {
     if (node->right == 0) {
       node->right = new Node (val);
       //check for the balanced factor, rebalanced if needed
       Balance (node);
     }
     else
       InsertHelper (node->right, val);
   }
 }
Exemple #18
0
/******************************************************************************************
* AVLbalance()
*
* Arguments:    h:  ponteiro para um no da arvore
*
* Returns: link retorna um no da arvore
* Description:  balanceia a arvore AVL
*****************************************************************************************/
link AVLbalance(link h){
    int balanceFactor;
    if (h==NULL) 
        return h;
    balanceFactor = Balance(h);
    if(balanceFactor > 1){
        if (Balance(h->l) >= 0) 
            h=rotR(h);
        else                 
            h=rotLR(h);
    }
    else if(balanceFactor < -1){
        if (Balance(h->r) <= 0) 
            h = rotL(h);
        else                 
            h = rotRL(h);
    } else{
        int peso_left = peso(h->l); 
        int peso_right = peso(h->r);
        h->peso = peso_left > peso_right ?  peso_left + 1 : peso_right + 1;
    }
    return h; 
}
Exemple #19
0
PtABPNode ABPBalance (PtABPNode proot)
{
	int *List; PtABPNode NewABP = NULL;
	unsigned int Count = 0, n = ABPSize (proot);	/* número de nos - number of nodes */

	if (proot == NULL) { Error = ABP_EMPTY; return NULL; }	/* a arvore está vazia - empyt tree */	
				/* criar a sequência - creating the array */
	if ((List = (int *) calloc (n, sizeof (int))) == NULL) { Error = NO_MEM ; return NULL; }	

    Error = OK;
	ListInOrder (proot, List, &Count);	/* preencher a sequência - filling the array */
	Balance (&NewABP, List, 0, n-1);	/* balancear a arvore - balancing the tree */
	free (List);	/* libertar a sequência - releasing the array */

	return NewABP;
}
Node AVL_tree::Insert(Node& node, Node& newNode, bool save){
  if(node == NULL){ // If empty, insert it...
    node = newNode;
    ++mSize;
    if(save)
      saveEEPROM(node);
    return node;
  }
  /* Now check if we should go left or right */
  else if(newNode->d < node->d){ // If left
    Insert(node->left, newNode, save);
  }
  else if(newNode->d > node->d){ // If right
    Insert(node->right, newNode, save);
  }
  Balance(node);
  return node;
}
Exemple #21
0
NodeT *insertNode(NodeT *root, int value)
{
    if(root == NULL)
    {
        NodeT *p=createNode(value);
        return p;
    }
    else
    {
        if(value > root->data)
            root -> right = insertNode(root->right, value);
        else
            root -> left = insertNode(root->left, value);

        root->height = maxim(compHeight(root->left), compHeight(root->right)) +1;

        return Balance(root);
    }
}
Exemple #22
0
int ntree::Remove(int p1,int p2){
	ops[3]++;
	int ss=Size();
	p1=BND(p1,0,ss);
	p2=BND(p2,0,ss);
	if (p1==p2 || p2==0)return 0;
	int s=0;

	for (int i=0;i<MAXNTN;i++){
		if (!data[i])continue;
		int ss=data[i]->Size();
		s+=data[i]->Remove(p1,p2);
		Balance((ntree**)data+i);
		p1-=ss;
		p2-=ss;
	}
	Resize();
	return s;
}
Node AVL_tree::Insert(Node& node, data d, bool save){
  if(node == NULL){ // If empty, insert it...
    node = new TreeNode(d);
    node->status = false;
    node->timerid = 255;
    ++mSize;
    if(save)
      saveEEPROM(node);
    return node;
  }
  /* Now check if we should go left or right */
  else if(d < node->d){ // If left
    Insert(node->left, d, save);
  }
  else if(d > node->d){ // If right
    Insert(node->right, d, save);
  }
  Balance(node);
  return node;
}
bool StudentTree::LoadFromFile(char* filename, int mode)
{
    //UnloadFile();

    fileBufferSize = 0;

    tempUint = GetfileSize(filename);
    if (!tempUint)
        return false;

    fileBuffer = (char*)realloc(fileBuffer, tempUint * sizeof(char));

    if (!fileBuffer)
        return false;

    fileObj = fopen(filename, "rw");
    if (!fileObj)
        return false;

    fileBufferSize = fread(fileBuffer, sizeof (char), tempUint, fileObj);

    if (fileBufferSize != tempUint)
    {
        fileBuffer = (char*)realloc(fileBuffer, 0);
        return false;
    }

    tempUint = fclose(fileObj);
    if (tempUint)
        return false;

    ParseFile();
    Balance();
    SetMode(mode);

    return true;
}
Exemple #25
0
/**
 * Get the current wallet balance.
 * @return Current wallet balance.
 */
CoinInterface::Balance
CoinInterface::getBalance ()
{
  const JsonRpc::JsonData res = rpc.executeRpc ("getbalance");
  return Balance(res);
}
void b2DynamicTree::InsertLeaf(int32 leaf)
{
	++m_insertionCount;

	if (m_root == b2_nullNode)
	{
		m_root = leaf;
		m_nodes[m_root].parent = b2_nullNode;
		return;
	}

	// Find the best sibling for this node
	b2AABB leafAABB = m_nodes[leaf].aabb;
	int32 index = m_root;
	while (m_nodes[index].IsLeaf() == false)
	{
		int32 child1 = m_nodes[index].child1;
		int32 child2 = m_nodes[index].child2;

		float32 area = m_nodes[index].aabb.GetPerimeter();

		b2AABB combinedAABB;
		combinedAABB.Combine(m_nodes[index].aabb, leafAABB);
		float32 combinedArea = combinedAABB.GetPerimeter();

		// Cost of creating a new parent for this node and the new leaf
		float32 cost = 2.0f * combinedArea;

		// Minimum cost of pushing the leaf further down the tree
		float32 inheritanceCost = 2.0f * (combinedArea - area);

		// Cost of descending into child1
		float32 cost1;
		if (m_nodes[child1].IsLeaf())
		{
			b2AABB aabb;
			aabb.Combine(leafAABB, m_nodes[child1].aabb);
			cost1 = aabb.GetPerimeter() + inheritanceCost;
		}
		else
		{
			b2AABB aabb;
			aabb.Combine(leafAABB, m_nodes[child1].aabb);
			float32 oldArea = m_nodes[child1].aabb.GetPerimeter();
			float32 newArea = aabb.GetPerimeter();
			cost1 = (newArea - oldArea) + inheritanceCost;
		}

		// Cost of descending into child2
		float32 cost2;
		if (m_nodes[child2].IsLeaf())
		{
			b2AABB aabb;
			aabb.Combine(leafAABB, m_nodes[child2].aabb);
			cost2 = aabb.GetPerimeter() + inheritanceCost;
		}
		else
		{
			b2AABB aabb;
			aabb.Combine(leafAABB, m_nodes[child2].aabb);
			float32 oldArea = m_nodes[child2].aabb.GetPerimeter();
			float32 newArea = aabb.GetPerimeter();
			cost2 = newArea - oldArea + inheritanceCost;
		}

		// Descend according to the minimum cost.
		if (cost < cost1 && cost < cost2)
		{
			break;
		}

		// Descend
		if (cost1 < cost2)
		{
			index = child1;
		}
		else
		{
			index = child2;
		}
	}

	int32 sibling = index;

	// Create a new parent.
	int32 oldParent = m_nodes[sibling].parent;
	int32 newParent = AllocateNode();
	m_nodes[newParent].parent = oldParent;
	m_nodes[newParent].userData = NULL;
	m_nodes[newParent].aabb.Combine(leafAABB, m_nodes[sibling].aabb);
	m_nodes[newParent].height = m_nodes[sibling].height + 1;

	if (oldParent != b2_nullNode)
	{
		// The sibling was not the root.
		if (m_nodes[oldParent].child1 == sibling)
		{
			m_nodes[oldParent].child1 = newParent;
		}
		else
		{
			m_nodes[oldParent].child2 = newParent;
		}

		m_nodes[newParent].child1 = sibling;
		m_nodes[newParent].child2 = leaf;
		m_nodes[sibling].parent = newParent;
		m_nodes[leaf].parent = newParent;
	}
	else
	{
		// The sibling was the root.
		m_nodes[newParent].child1 = sibling;
		m_nodes[newParent].child2 = leaf;
		m_nodes[sibling].parent = newParent;
		m_nodes[leaf].parent = newParent;
		m_root = newParent;
	}

	// Walk back up the tree fixing heights and AABBs
	index = m_nodes[leaf].parent;
	while (index != b2_nullNode)
	{
		index = Balance(index);

		int32 child1 = m_nodes[index].child1;
		int32 child2 = m_nodes[index].child2;

		b2Assert(child1 != b2_nullNode);
		b2Assert(child2 != b2_nullNode);

		m_nodes[index].height = 1 + b2Max(m_nodes[child1].height, m_nodes[child2].height);
		m_nodes[index].aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb);

		index = m_nodes[index].parent;
	}

	//Validate();
}
Exemple #27
0
void main(void)
{
  // USER CODE BEGIN (Main,2)
  signed int ret_left;
  signed int ret_right;
  volatile signed int gyrovalue;
  unsigned char ledvalue;
  volatile signed int winkel = 0.0;
  volatile signed int val_x;
  volatile signed int val_y;
  volatile signed int val_z;

  unsigned char counter = 0;
  unsigned char timebase = 20; // * 5 ms

  // USER CODE END

  MAIN_vInit();

  // USER CODE BEGIN (Main,3)

  BalanceInit();

  // USER CODE END

  while(1)
  {

   // USER CODE BEGIN (Main,4)
   while(0 == timerevent);
   timerevent = 0;

   counter--;
   if (counter == 0)
   {
   		counter = timebase;		   
	   ReadSensorData();
	   Balance();
	   
	   // start reading the data, they will be get then
	   
	   gyrovalue = ReadSpinValue();
	   winkel = GetCurrentAngle();
	   ledvalue = ReadSpinValueRaw();
	   val_x = ReadAccelValue(DIRECTION_X) + 512;
	   val_y = ReadAccelValue(DIRECTION_Y) + 512;
	   val_z = ReadAccelValue(DIRECTION_Z) + 512;
	   
	   P10_OUT_P7 = (gyrovalue > 35) ? 0 : 1;
	   P10_OUT_P6 =	(gyrovalue > 25) ? 0 : 1;
	   P10_OUT_P5 =	(gyrovalue > 15) ? 0 : 1;
	   P10_OUT_P4 =	(gyrovalue > 5) ? 0 : 1;
	   P10_OUT_P3 =	(gyrovalue < -5) ? 0 : 1;
	   P10_OUT_P2 =	(gyrovalue < -15) ? 0 : 1;
	   P10_OUT_P1 =	(gyrovalue < -25) ? 0 : 1;
	   P10_OUT_P0 =	(gyrovalue < -35) ? 0 : 1;
	   // do some kind of stuff
	   //ret_left = 00;
	   //ret_right = 00;
	   //SetMotorSpeeds(&ret_left, &ret_right);
	   
	
	   //SetMotorSpeedsNoReturn(links_p, rechts_p);
	   // faehrt vorwärts hoffentlich
	   // und au langsam
	   //SetMotorSpeedsNoReturn(speed, speed);//20, 20);
	}
   // USER CODE END

  }

} //  End of function main
 bool isBalanced(TreeNode* root) {
     if(root == NULL) return true;
     int height = 0;
     return Balance(root, height);
 }
Exemple #29
0
/*******************************************************************************
  main : Main routine.
*******************************************************************************/
int main(void)
{
    s32 i;
//u32 Licence;
    u16 Count_FPS=0, Second=0;//,Offset, Result
//  u8 N[20];
//  u8 T_Unit[15]={'u','S','u','S','m','S','S'};

    NVIC_SetVectorTable(NVIC_VectTab_FLASH, 0x0C000);   // For Application #1
//NVIC_SetVectorTable(NVIC_VectTab_FLASH, 0x14000);   // For Application #2
//NVIC_SetVectorTable(NVIC_VectTab_FLASH, 0x1C000);   // For Application #3
//NVIC_SetVectorTable(NVIC_VectTab_FLASH, 0x24000);   // For Application #4

//Note: 用 IAR_V4.x 编译时,变更 App#n 还要同时修改 lnkarm.xcl 文件中的对应项
//      用 IAR_V5.x 编译时,变更 App#n 还要同时修改 xxxxxx.icf 文件中的对应项

    __USB_Init();

    if(__Get(FPGA_OK)== 0) {
        __Display_Str(6*8, 30, YEL, PRN, "      FPGA configuration error       ");
        while (1) {};
    }

    __Display_Str(48, 50, WHT, PRN, APP_VERSION);
    Y_Attr = (Y_attr*)__Get(VERTICAL);
    X_Attr = (X_attr*)__Get(HORIZONTAL);
    G_Attr = (G_attr*)__Get(GLOBAL);
    T_Attr = (T_attr*)__Get(TRIGGER);
    Load_Attr();                                 // 赋值Y_Attr等
    i = Load_Param();
    if(i == 0)  // 读取预设开机参数
        __Display_Str(6*8, 30, GRN, PRN, "     Reload parameter form disk       ");
    else
        __Display_Str(6*8, 30, YEL, PRN, "     Parameter record not found       ");
//  i = Load_Param(); // 读取预设开机参数

    /*--------------------------- LICENCE_CTRL_DEMO --------------------------------
    Offset = Seek_Proj(PROJECT_ID);
    if(Offset >= 2048){                          // Project ID not found
      Offset = Seek_Blank();
      if(Offset == 2048){
        __Display_Str(6*8, 50, GRN, PRN,   "         Licence record full         ");
        while (1){};
      } else {
        Result  = Add_Proj(PROJECT_ID, Offset);  // Set project ID
        Result &= Add_Cnt(DEMOCNT, Offset);      // Set max demo run counter
        Result &= Add_Str((u32)PROJECT_STR, Offset);
        if(Result != 1){
          __Display_Str(6*8,50,GRN, PRN,   "       Project ID writen error       ");
          Delayms(500);
        }
      }
    }
    Licence = Get_Lic(Offset);                   // Get project licence record
    if(__Ident(DEVELOPER_ID, PROJECT_ID, Licence)!= 1){
      __Display_Str(6*8, 50, GRN, PRN,   "Please input project licence:00000000");
      Licence = Input_Lic((6+29)*8, 50);         // Input Licence
      if(__Ident(DEVELOPER_ID, PROJECT_ID, Licence)!=1)  Result = 0;
      else{                                      // Licence correct
        Result  = Add_Lic(Licence, Offset);
        if(Result == 1)
          __Display_Str(6*8,50,GRN, PRN, "          Licence writen ok          ");
        else
          __Display_Str(6*8,50,GRN, PRN, "         Licence writen error        ");
        Delayms(500);
      }
      if(Result != 1){
        __Display_Str(6*8, 30, GRN, PRN, "      Push any key to next step      ");
        while(Key_Buffer == 0){};
      }
    }
    //  --------------------------------------------------------------------------*/

    Beep_mS = 500;
    Balance();
    App_init();
    Key_Buffer=0;

//--------------------------------- 主循环 -------------------------------------
    while (1) {
        if(PD_Cnt == 0) {
            __Set(BACKLIGHT, 0);     // 关闭背光
            __Set(STANDBY, EN);      // 进入省电状态
        } else {
            Synchro();                              // 同步显示各个轨迹波形数据
            Count_FPS++;
            if(Second != Sec_Cnt) {
                Second = Sec_Cnt;
                Result_FPS = Count_FPS;
                Count_FPS = 0;
                Update_Battery();
                for(i=0; i<9; ++i)  Display_Value(i); // 每秒刷新测量值
            }
            Display_Meter();
            Display_Title();
            if(Update) {                            // 处理按键后需要刷新的项目
                Update_Range();
                Update_Base();
                Update_Output();
                Update_Trig();
                Update_Mark();
                __Set(BACKLIGHT, 10*(Title[BK_LIGHT][CLASS].Value+1));
                if(Current != FILE) Update_View_Area();
                _D_V_Source.Flag |= UPDAT;            // Updat delta V
                _Delta_V.Flag    |= UPDAT;
                _Delta_T.Flag    |= UPDAT;            // Updat delta T
                Update = 0;                           // Update finish
            }
            Blink = 0;
        }
        if((_State.Value == HOLD)&&((__Get(FIFO_FULL)!= 0)||(__Get(FIFO_START)== 0))) {
//    if((_State.Value == HOLD)&&(Twink== 1)){
            _State.Value = 2;
            _State.Flag |= UPDAT;
        }
//------------------------------ 按键处理循环 ----------------------------------
        if(Key_Buffer) {
            if(PD_Cnt == 0)  App_init();          // 退出省电状态
            PD_Cnt = 600;                         // 600秒
            if(Key_Buffer == KEY_P) {
                _State.Value = (_State.Value == 0)? 1 : 0;       // "RUN/HOLD" 状态互换
//        _State.Value = 1-_State.Value;                 // "RUN/HOLD" 状态互换
                _State.Flag |= UPDAT;                          // 置相应的更新标志
                if((Current == FILE)&&(_Curr[2].Value == BUF)) reset_parameter();
                if(_Mode == SGL) {
                    for(i=0; i<4*X_SIZE; ++i)  TrackBuff[i] = 0; // 清除旧的显示波形
                    __Set(FIFO_CLR, W_PTR);                      // FIFO写指针复位
                }
            }
            if(Key_Buffer== KEY2) {
                if((Current == TRACK1)||(Current == TRACK2)) {
                    Delay_Cnt = 2000;
                    while (Delay_Cnt > 0) {
                        if((__Get(KEY_STATUS)& KEY2_STATUS)!=0) break;
                    }
                    if(Delay_Cnt == 0)  Calibrat(Current);             // 模拟通道校准
                }
            }
            if(Key_Buffer== KEY3) {
                Save_Param();                             // 保存当前操作设置参数
                if(Current != FILE) {
                    Print_Str(91, 0, 0x0405, PRN, "! Save the current setting !");
                    Delayms(500);
                }
            }
            if(Key_Buffer== KEY4) {
                if(Current == FILE) {
                    Print_Str(230, 0, (SCRN<<8)+ TEXT1, PRN, " >   ");
                    if(_Curr[0].Value == SAVE) {
                        switch (_Curr[2].Value) {
                        case BMP:
                            i = Save_Bmp(_Curr[1].Value);
                            break;
                        case DAT:
                            i=Save_Dat(_Curr[1].Value);
                            Delayms(1000);
                            break;
                        case BUF:
                            i=Save_Buf(_Curr[1].Value);
                            break;
                        case CSV:
                            i=Save_Csv(_Curr[1].Value);
                            break;
                        }
                        _Curr[1].Value++;
                    } else {
                        i=0;
                        if(_Curr[2].Value==DAT) i = Load_Dat(_Curr[1].Value);
                        if(_Curr[2].Value==BUF) i = Load_Buf(_Curr[1].Value);
                    }
                    if       (i == OK  ) Print_Str(230, 0, (SCRN<<8)+ TEXT1, PRN, " OK  ");
                    else {
                        if     (i == EMPT) Print_Str(230, 0, (SCRN<<8)+ TEXT1, PRN, " NONE");
                        else if(i == OVER) Print_Str(230, 0, (SCRN<<8)+ TEXT1, PRN, " FULL");
                        else               Print_Str(230, 0, (SCRN<<8)+ TEXT1, PRN, " ERR ");
                    }
                    Delayms(1000);
                    _Curr[1].Flag |= UPDAT;
                    _Curr[2].Flag |= UPDAT;
                }
            }
            if(Key_Buffer == K_ITEM_DEC) { //------------------ "Item-" Key
                if(Current < METER_0) {
                    _Curr[_Det].Flag |= UPDAT;
                    if(Current == TRACK1)  Current = VOLUME;
                    else                   Current --;
                    if(Current == RUNNING) Current --;               // Jump over Item 4
                    if(_Det >2)  _Det =0;
                    _Curr[_Det].Flag |= BLINK;
                    _Curr[0].Flag |= UPDAT;
                    _Curr[1].Flag |= UPDAT;
                    _Curr[2].Flag |= UPDAT;
                    _Curr[3].Flag |= UPDAT;
                } else {
                    Meter[Current-METER_0].Flag |= UPDAT;
                    if(Current == METER_0) Current = METER_8;
                    else                   Current --;
                    Meter[Current-METER_0].Flag |= BLINK;
                }
            }
            if(Key_Buffer == K_ITEM_S) { //------------------ "Item_Select"  Key
                if(Current < METER_0)  Current = METER_0;
                else                   Current = TRACK1;
            }
            if(Key_Buffer == K_ITEM_INC) { //------------------ "Item+" Key
                if(Current < METER_0) {
                    _Curr[_Det].Flag |= UPDAT;
                    if(Current == VOLUME)  Current = TRACK1;
                    else                   Current ++;
                    if(Current == RUNNING) Current ++;              // Jump over RUNNING
                    if(_Det >2)    _Det =0;
                    _Curr[_Det].Flag |= BLINK;
                    _Curr[0].Flag |= UPDAT;
                    _Curr[1].Flag |= UPDAT;
                    _Curr[2].Flag |= UPDAT;
                    _Curr[3].Flag |= UPDAT;
                } else {
                    Meter[Current-METER_0].Flag |= UPDAT;
                    if(Current == METER_8) Current  = METER_0;
                    else                   Current ++;
                    Meter[Current-METER_0].Flag |= BLINK;
                }
            }
            if(Key_Buffer == K_INDEX_DEC) { //--------------------- "Index-" Key
                if(Current < METER_0) {
                    if((Current == TRIGG)&&(Detail[Current]==2)) {        // 触发电平调节
                        if(V_Trigg[_Trigg[SOURCE].Value].Value > MIN_Y+4)
                            V_Trigg[_Trigg[SOURCE].Value].Value--;
                    } else if((Current == BK_LIGHT)||(Current == VOLUME)) { // 背光或音量调节
                        if(_Curr[1].Value > 0)   _Curr[1].Value--;
                    } else if((Current == T_BASE)&&(_Det == XPOSI)) {     // X_POSI调节
                        if(_Curr[_Det].Value > 30) _Curr[_Det].Value -= 30;
                        else if(_Curr[_Det].Value > 0) _Curr[_Det].Value--;
                        _X_View.Flag |= UPDAT;                              // 刷新X_View
                    } else {                                              // 当前项为其他
                        if(_Curr[_Det].Value > 0) _Curr[_Det].Value--;
                        else if(_Curr[_Det].MARK & CIRC) _Curr[_Det].Value =_Curr[_Det].Limit;
                    }
                    if((Current == T_BASE)&&(_Det == MODE)) {    // T_BASE MODE 选择
                        Title[RUNNING][STATE].Value = RUN;         // STATE = RUNNING
                        Title[RUNNING][STATE].Flag |= UPDAT;       // 刷新 RUNNING STATE
                    }
                    if(((Current == OUTPUT)&&(Title[OUTPUT][SOURCE].Value != DIGI))&&
                            (Title[OUTPUT][FRQN].Value > 10))
                        Title[OUTPUT][FRQN].Value = 10;            // 模拟信号频率上限为20KHz
                    if((Current == FILE)&&(_Curr[0].Value == LOAD)) {
                        if(_Curr[2].Value == BMP) _Curr[2].Value = BUF;  // 只能Load Dat,Buf文件
                        if(_Curr[2].Value == CSV) _Curr[2].Value = BUF;  // 只能Load Dat,Buf文件
                    }
                    _Curr[0].Flag |= UPDAT;
                    _Curr[1].Flag |= UPDAT;
                    _Curr[2].Flag |= UPDAT;
                    _Curr[3].Flag |= UPDAT;
                } else {
                    Meter[Current-METER_0].Flag |= UPDAT;
                    if(Meter[Current-METER_0].Item  > VBT)
                        Meter[Current-METER_0].Item -= 1;          // 改变测量项目
                    else
                        Meter[Current-METER_0].Item  = TL;//MIN;
                    if(Meter[Current-METER_0].Item == FPS)
                        Meter[Current-METER_0].Track = 4;
                    if(Meter[Current-METER_0].Item == TL)//MIN)
                        Meter[Current-METER_0].Track = 0;
                }
            }
            if(Key_Buffer == K_INDEX_S) { //----------------- "Index_Select" Key
                if(Current < METER_0) {                        // 改变Detail
                    _Curr[_Det].Flag |= UPDAT;
                    if(_Det < 3)    _Det += 1;
                    else            _Det  = 0;
                    if(_Curr[_Det].MARK & NOT)                        _Det  = 0;
                    if(_Curr[_Det].MARK & NUM2)                       _Det  = 0;
                    if((_Curr[_Det].MARK & NUM3)&&(Current != FILE))  _Det  = 0;
                    _Curr[_Det].Flag |= BLINK;
                } else {                                       // 改变测量对象
                    Meter[Current-METER_0].Flag |= UPDAT;
                    if(Meter[Current-METER_0].Track <=  TRACK4)
                        Meter[Current-METER_0].Track += 1;
                    if(Meter[Current-METER_0].Track > TRACK4)
                        Meter[Current-METER_0].Track  = TRACK1;
                }
            }
            if(Key_Buffer == K_INDEX_INC) { //--------------------- "Index+" Key
                if(Current < METER_0) {
                    if((Current == TRIGG)&&(Detail[Current]==2)) {        // 触发电平调节
                        if(V_Trigg[_Trigg[SOURCE].Value].Value < MAX_Y-4)
                            V_Trigg[_Trigg[SOURCE].Value].Value++;
                    } else if((Current == BK_LIGHT)||(Current == VOLUME)) { // 背光或音量调节
                        if(_Curr[1].Value < _Curr[1].Limit)   _Curr[1].Value++;
                    } else if((Current == T_BASE)&&(_Det == XPOSI)) {     // X_POSI调节
                        if(_Curr[_Det].Value <(_Curr[_Det].Limit-30))  _Curr[_Det].Value += 30;
                        else if(_Curr[_Det].Value < _Curr[_Det].Limit) _Curr[_Det].Value ++;
                        _X_View.Flag |= UPDAT;
                    } else {                                              // 当前项为其他
                        if(_Curr[_Det].Value < _Curr[_Det].Limit)  _Curr[_Det].Value++;
                        else if(_Curr[_Det].MARK & CIRC)   _Curr[_Det].Value  = 0;
                    }
                    if((Current == T_BASE)&&(_Det == MODE)) {    // T_BASE MODE 选择
                        Title[RUNNING][STATE].Value = RUN;         // STATE = RUNNING
                        Title[RUNNING][STATE].Flag |= UPDAT;       // 刷新 RUNNING STATE
                    }
                    if((Current == OUTPUT)&&(Title[OUTPUT][SOURCE].Value != DIGI)) {
                        if(Title[OUTPUT][FRQN].Value > 10)
                            Title[OUTPUT][FRQN].Value = 10;          // 模拟信号频率上限为20KHz
                    }
                    if((Current == FILE)&&(_Curr[0].Value == 1)) { // 只能Load Dat,Buf文件
                        if(_Curr[2].Value == BMP) _Curr[2].Value = DAT;
                        if(_Curr[2].Value == CSV) _Curr[2].Value = DAT;
                    }
                    _Curr[0].Flag |= UPDAT;
                    _Curr[1].Flag |= UPDAT;
                    _Curr[2].Flag |= UPDAT;
                    _Curr[3].Flag |= UPDAT;
                } else {
                    Meter[Current-METER_0].Flag |= UPDAT;
                    if(Meter[Current-METER_0].Item < TL)//MIN)
                        Meter[Current-METER_0].Item += 1;          // 改变测量项目
                    else
                        Meter[Current-METER_0].Item  = VBT;
                    if(Meter[Current-METER_0].Item == VBT)
                        Meter[Current-METER_0].Track = 4;
                    if(Meter[Current-METER_0].Item == VPP)
                        Meter[Current-METER_0].Track = 0;
                }
            }
            Key_Buffer=0;
            Update = 1;
        }
    }
}
Exemple #30
0
void Balance(ntree **ntt,int ){
	if (!ntt) return;
	for (;;){
		ntree *nt=*ntt;
		if (!nt) return;
		if (nt->type!=1) return;

		if (nt->dad){
			if (!nt->data[0]){
//				printf("SliceL\n");
				*ntt=(ntree*)nt->data[1];
				DoDad(nt->dad,*ntt);
				continue;
			}
			if (!nt->data[1] ){
//				printf("SliceR\n");
				*ntt=(ntree*)nt->data[0];
				DoDad(nt->dad,*ntt);
				continue;
			}

			if (nt->Size()<16){
				Balance((ntree**)nt->data+0);
				Balance((ntree**)nt->data+1);
//				printf("Null thingy (%x,%x,%x)\n",nt,nt->data[0],nt->data[1]);
				if (nt->Size()>=16){
					printf("aaarrrrggghh\n");
					continue;
				}
				((ndata*)nt->data[0])->SplitTo((ndata*)nt->data[1],0);
				nt->data[0]=NULL;
				continue;
			} //killer
		}

		for (int hh=0;hh<MAXNTN;hh++){
			ndata *ev=(ndata*)nt->data[hh];
			if (ev && ev->type==0){
				int  ss=ev->Size();
				if (ss>48*2){
					int sp=ss/2;
					ntree *nk=GetNT();
					nk->dad=nt;
					nk->data[0]=ev;
					nk->data[0]->dad=nk;
					nt->data[hh]=nk;
					nk->Resize();
					nk->cnt10=ev->cnt10;

					nk->data[1]=GetND();
					nk->data[1]->dad=nk;
					((ndata*)nk->data[0])->SplitTo((ndata*)nk->data[1],sp);
					Balance((ntree**)nt->data+hh);
				}
			}
		}

		nt->Resize();
		int d0=0,d1=0;
		if (nt->data[0])d0=nt->data[0]->maxdepth;
		if (nt->data[1])d1=nt->data[1]->maxdepth;

		if ( (d1>1) && (d1>d0*2) ){
//			printf("splittingL (%x,%d,%d)\n",nt,d0,d1);
			ntree *nx=(ntree*)nt->data[1];
			*ntt=nx;
			nx->dad=nt->dad;

			nt->data[1]=nx->data[0];
			DoDad(nt,nt->data[1]);

			nx->data[0]=nt;
			nt->dad=nx;
			nt->Resize();
			nx->Resize();

			Balance((ntree**)nx->data+0);
			Balance((ntree**)nx->data+1);
			break;
		}

		if ( (d0>1) && (d0>d1*2) ){
//	         printf("splittingR (%x,%d,%d)\n",nt,d0,d1);
			ntree *nx=(ntree*)nt->data[0];
			*ntt=nx;
			nx->dad=nt->dad;

			nt->data[0]=nx->data[1];
			DoDad(nt,nt->data[0]);

			nx->data[1]=nt;
			nt->dad=nx;
			nt->Resize();
			nx->Resize();

			Balance((ntree**)nx->data+0);
			Balance((ntree**)nx->data+1);
			break;
		}
		break;
	}
}