Example #1
0
int goSomewhere(struct state *s, char **a, int penalty){
    int i,j, is, js, k, wx=0, wy=0, stage=-1;
	unsigned int change = 0, end = 0;
    struct state *ns;
	char * answer;
	char move='U';
	unsigned int *c = malloc( ((s-> world_w+1) * s->world_h+1) * sizeof( unsigned int ));
	
	if (c == NULL ){}
	for(i=0; i<((s-> world_w+1) * s->world_h+1); i++){
		c[i]=UINT_MAX;  
	}
	
	c[point_to_index(s, s->robot_x, s->robot_y)]=0;	
	
	put(s, 1, 1, O_EMPTY);
	move_robot(s, 1, 1);
	ns = copy(s);
	
	do{
	    free(s);
	    s = copy(ns);
		update_world(ns, s);
		change++;
		stage++;
		end = 0;
		for(i=1; i <= s->world_w; i++){
			for(j=1; j <= s->world_h; j++){
				if(c[point_to_index(s,i,j)]==stage){
					if(get(s, i, j) == O_LIFT_OPEN || get(s, i, j) == O_LAMBDA){
						wx=i;
						wy=j;
						end=stage;
						break;
					}
					//consider four cells - (-1, 0), (1, 0), (0, -1), (0, 1)
					for(k = 1; k<=4; k++){
						if(k==1) {is= 0 ; js=-1;}
						if(k==2) {is= 0 ; js= 1;}
						if(k==3) {is=-1 ; js= 0;}
						if(k==4) {is= 1 ; js= 0;}						
						if(bounded(s,i+is,j+js)	&& c[point_to_index(s, i+is, j+js)]==UINT_MAX){
							//can we go there?
							if(	!bounded(s, i+is, j+js+1) || (get(s, i+is, j+js+1) != O_EMPTY || get(ns, i+is, j+js+1) != O_ROCK)){	
								if(get(s, i+is, j+js)==O_LIFT_OPEN 
								|| get(s, i+is, j+js)==O_LAMBDA 
								|| get(s, i+is, j+js)==O_EARTH 
								|| get(s, i+is, j+js)==O_EMPTY){
									if((bounded(s, i+is, j+js+1) && get(s, i+is, j+js+1)==O_ROCK)
										|| (bounded(s, i+is+1, j+js+1) && get(s, i+is+1, j+js)==O_ROCK && get(s, i+is+1, j+js+1)==O_ROCK)
										|| (bounded(s, i+is-1, j+js+1) && get(s, i+is-1, j+js)==O_ROCK && get(s, i+is-1, j+js+1)==O_ROCK)){
										c[point_to_index(s, i+is, j+js)]=stage+penalty;
									}else{
										c[point_to_index(s, i+is, j+js)]=stage+1;
									}
									change = 0;
							    }
							}
						}
					}
				}
			}
		}
	}while(change <= penalty && end == 0);
	
	//debug
	//dump(s);
	
	if(0){
		for(j=s->world_h; j>0; j--){
			for(i=1; i<=s->world_w; i++){
				if(c[point_to_index(s, i, j)]==UINT_MAX){
					printf("X");
				}else{
					printf("%u", c[point_to_index(s, i, j)]);
				}
			}
			printf("\n");
		}
		printf("\n");
	}
	
	i=0;
	if(end>0){
		answer = malloc( (end+2)*sizeof( char ));
		if (answer == NULL ){}
		
		while(end>0){
			for(k=1; k<=4;k++){
				if(k==1) {is=-1; js= 0;move='R';}
				if(k==2) {is= 1; js= 0;move='L';}						
				if(k==3) {is= 0; js=-1;move='U';}
				if(k==4) {is= 0; js= 1;move='D';}
				if( bounded(s, wx+is, wy+js) && c[point_to_index(s, wx+is, wy+js)] < end) {
					end = c[point_to_index(s, wx+is, wy+js)];
					answer[i++]=move;
					wx = wx+is;
					wy = wy+js;
					break;
				}
			}
		}
		answer[i]='\0';
		reverse(answer,0,strlen(answer)-1);
	}else{
		answer = malloc(1*sizeof( char ));
		if (answer == NULL ){}
		answer[0]='\0';
     	*a=answer;
		free(c);
		return 1;
	}
	*a=answer;
	free(c);
	return 0;
}
int B011001::loadTextureBMP(char* file)
{
	unsigned int   texture_ID;
	FILE*          file_Pointer;
	unsigned short magic;      // Image magic
	unsigned int   dx,dy,size; // Image dimensions
	unsigned short nbp,bpp;    // Planes and bits per pixel
	unsigned char* image;      // Image data
	unsigned int   k;          // Counter

	//  Open file
	file_Pointer = fopen(file,"rb");

	if (!file_Pointer) fatal("Cannot open file %s\n", file);
	
	//  Check image magic
	if (fread(&magic,2,1,file_Pointer)!=1) fatal("Cannot read magic from %s\n",file);
	if (magic!=0x4D42 && magic!=0x424D) fatal("Image magic not BMP in %s\n",file);
	
	//  Seek to and read header
	if (fseek(file_Pointer,16,SEEK_CUR) || fread(&dx ,4,1,file_Pointer)!=1 || fread(&dy ,4,1,file_Pointer)!=1 ||
		fread(&nbp,2,1,file_Pointer)!=1 || fread(&bpp,2,1,file_Pointer)!=1 || fread(&k,4,1,file_Pointer)!=1)
		fatal("Cannot read header from %s\n",file);
	
	//  Reverse bytes on big endian hardware (detected by backwards magic)
	if (magic==0x424D)
	{
		reverse(&dx,4);
		reverse(&dy,4);
		reverse(&nbp,2);
		reverse(&bpp,2);
		reverse(&k,4);
	}
	
	//  Check image parameters
	if (dx<1 || dx>65536) fatal("%s image width out of range: %d\n",file,dx);
	if (dy<1 || dy>65536) fatal("%s image height out of range: %d\n",file,dy);
	if (nbp!=1)  fatal("%s bit planes is not 1: %d\n",file,nbp);
	if (bpp!=24) fatal("%s bits per pixel is not 24: %d\n",file,bpp);
	if (k!=0)    fatal("%s compressed files not supported\n",file);

#ifndef GL_VERSION_2_0
	//  OpenGL 2.0 lifts the restriction that texture size must be a power of two
	for (k=1;k<dx;k*=2);
	if (k!=dx) fatal("%s image width not a power of two: %d\n",file,dx);
	for (k=1;k<dy;k*=2);
	if (k!=dy) fatal("%s image height not a power of two: %d\n",file,dy);
#endif

	//  Allocate image memory
	size = 3*dx*dy;
	image = (unsigned char*) malloc(size);
	if (!image) fatal("Cannot allocate %d bytes of memory for image %s\n",size,file);
	//  Seek to and read image
	if (fseek(file_Pointer,20,SEEK_CUR) || fread(image,size,1,file_Pointer)!=1) fatal("Error reading data from image %s\n",file);
	fclose(file_Pointer);
	//  Reverse colors (BGR -> RGB)
	for (k=0;k<size;k+=3)
	{
		unsigned char temp = image[k];
		image[k]   = image[k+2];
		image[k+2] = temp;
	}

	//  Generate 2D texture
	glGenTextures(1,&texture_ID);
	glBindTexture(GL_TEXTURE_2D,texture_ID);
	//  Copy image
	glTexImage2D(GL_TEXTURE_2D,0,3,dx,dy,0,GL_RGB,GL_UNSIGNED_BYTE,image);
	if (glGetError()) fatal("Error in glTexImage2D %s %dx%d\n",file,dx,dy);
	//  Scale linearly when image size doesn't match
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);

	//  Free image memory
	free(image);
	//  Return texture name
	return texture_ID;
}
Example #3
0
int reversed_binary_value(...)
{
    return reverse(sizeof...(digits), digits...);
}
Example #4
0
// performs the backtrace algorithm
void CBandedSmithWaterman::Traceback(unsigned int& referenceAl, string& cigarAl, const string& s1, const string& s2, unsigned int bestRow, unsigned int bestColumn, const unsigned int rowOffset, const unsigned int columnOffset){


	unsigned int currentRow		 = bestRow;
	unsigned int currentColumn	 = bestColumn;
	unsigned int currentPosition = ((currentRow + rowOffset) * (mBandwidth + 2)) + (columnOffset - currentRow + currentColumn);


	// record the numbers of row and column before the current row and column
	unsigned int previousRow	= bestRow;
	unsigned int previousColumn	= bestColumn;

	unsigned int gappedAnchorLen = 0;
	unsigned int gappedQueryLen  = 0;
	unsigned int numMismatches   = 0;

	bool keepProcessing = true;
	while(keepProcessing) {
		unsigned int nVerticalGap = 0;
		unsigned int nHorizontalGap = 0;
		switch(mPointers[currentPosition].Direction){
			case Directions_DIAGONAL:
				nVerticalGap = mPointers[currentPosition].mSizeOfVerticalGaps;
				for(unsigned int i = 0; i < nVerticalGap; i++){
					mReversedAnchor[gappedAnchorLen++] = GAP;
					mReversedQuery[gappedQueryLen++]   = s2[currentRow];

					numMismatches++;

					previousRow = currentRow;
					previousColumn = currentColumn;

					currentRow--;
				}
				break;

			case Directions_STOP:
				keepProcessing = false;
				//mReversedAnchor[gappedAnchorLen+1]='\0';
				//mReversedQuery [gappedQueryLen+1]='\0';
				break;

			case Directions_UP:

				mReversedAnchor[gappedAnchorLen++] = s1[currentColumn];
				mReversedQuery[gappedQueryLen++]   = s2[currentRow];

				if(s1[currentColumn] != s2[currentRow]) numMismatches++;
				previousRow = currentRow;
				previousColumn = currentColumn;

				currentRow--;
				currentColumn--;
				break;

			case Directions_LEFT:
				nHorizontalGap =  mPointers[currentPosition].mSizeOfHorizontalGaps;
				for(unsigned int i = 0; i < nHorizontalGap; i++){

					mReversedAnchor[gappedAnchorLen++] = s1[currentColumn];
					mReversedQuery[gappedQueryLen++]   = GAP;

					numMismatches++;

					previousRow = currentRow;
					previousColumn = currentColumn;


					currentColumn--;
				}
				break;
		}
		currentPosition = ((currentRow + rowOffset) * (mBandwidth + 2)) + (columnOffset - currentRow + currentColumn);
	}

	// correct the reference and query sequence order
	mReversedAnchor[gappedAnchorLen] = 0;
	mReversedQuery [gappedQueryLen] = 0;
	reverse(mReversedAnchor, mReversedAnchor + gappedAnchorLen);
	reverse(mReversedQuery,  mReversedQuery  + gappedQueryLen);

	//alignment.Reference = mReversedAnchor;
	//alignment.Query     = mReversedQuery;

	// assign the alignment endpoints
	//alignment.ReferenceBegin = previousColumn;
	//alignment.ReferenceEnd   = bestColumn;
	referenceAl  = previousColumn;
	/*  
	if(alignment.IsReverseComplement){
		alignment.QueryBegin = s2.length() - bestRow - 1; 
		alignment.QueryEnd   = s2.length() - previousRow - 1;
	} else {
		alignment.QueryBegin = previousRow; 
		alignment.QueryEnd   = bestRow;
	}
	*/
	
	//alignment.QueryLength	= alignment.QueryEnd - alignment.QueryBegin + 1;
	//alignment.NumMismatches = numMismatches;

	const unsigned int alLength = strlen(mReversedAnchor);
	unsigned int m = 0, d = 0, i = 0;
	bool dashRegion = false;
	ostringstream oCigar;

	if ( previousRow != 0 )
		oCigar << previousRow << 'S';

	for ( unsigned int j = 0; j < alLength; j++ ) {
		// m
		if ( ( mReversedAnchor[j] != GAP ) && ( mReversedQuery[j] != GAP ) ) {
			if ( dashRegion ) {
				if ( d != 0 ) oCigar << d << 'D';
				else          oCigar << i << 'I';
			}
			dashRegion = false;
			m++;
			d = 0;
			i = 0;
		}
		// I or D
		else {
			if ( !dashRegion )
				oCigar << m << 'M';
			dashRegion = true;
			m = 0;
			if ( mReversedAnchor[j] == GAP ) {
				if ( d != 0 ) oCigar << d << 'D';
				i++;
				d = 0;
			}
			else {
				if ( i != 0 ) oCigar << i << 'I';
				d++;
				i = 0;
			}
		}
	}
	
	if      ( m != 0 ) oCigar << m << 'M';
	else if ( d != 0 ) oCigar << d << 'D';
	else if ( i != 0 ) oCigar << i << 'I';

	if ( ( bestRow + 1 ) != s2.length() )
		oCigar << s2.length() - bestRow - 1 << 'S';

	cigarAl = oCigar.str();
	

	// correct the homopolymer gap order
	CorrectHomopolymerGapOrder(alLength, numMismatches);

}
Example #5
0
//------------------------------------------------------------------
//
// MenuLayerMainMenu
//
//------------------------------------------------------------------
MenuLayerMainMenu::MenuLayerMainMenu()
{
    _touchListener = EventListenerTouchOneByOne::create();
    _touchListener->setSwallowTouches(true);
    _touchListener->onTouchBegan = CC_CALLBACK_2(MenuLayerMainMenu::onTouchBegan, this);
    _touchListener->onTouchMoved = CC_CALLBACK_2(MenuLayerMainMenu::onTouchMoved, this);
    _touchListener->onTouchEnded = CC_CALLBACK_2(MenuLayerMainMenu::onTouchEnded, this);
    _touchListener->onTouchCancelled = CC_CALLBACK_2(MenuLayerMainMenu::onTouchCancelled, this);
    
    _eventDispatcher->addEventListenerWithFixedPriority(_touchListener, 1);

    // Font Item    
    auto spriteNormal = Sprite::create(s_MenuItem, Rect(0,23*2,115,23));
    auto spriteSelected = Sprite::create(s_MenuItem, Rect(0,23*1,115,23));
    auto spriteDisabled = Sprite::create(s_MenuItem, Rect(0,23*0,115,23));

    auto item1 = MenuItemSprite::create(spriteNormal, spriteSelected, spriteDisabled, CC_CALLBACK_1(MenuLayerMainMenu::menuCallback, this) );
    
    // Image Item
    auto item2 = MenuItemImage::create(s_SendScore, s_PressSendScore, CC_CALLBACK_1(MenuLayerMainMenu::menuCallback2, this) );

    // Label Item (LabelAtlas)
    auto labelAtlas = LabelAtlas::create("0123456789", "fonts/labelatlas.png", 16, 24, '.');
    auto item3 = MenuItemLabel::create(labelAtlas, CC_CALLBACK_1(MenuLayerMainMenu::menuCallbackDisabled, this) );
    item3->setDisabledColor( Color3B(32,32,64) );
    item3->setColor( Color3B(200,200,255) );
    
    // Font Item
    auto item4 = MenuItemFont::create("I toggle enable items", [&](Object *sender) {
		_disabledItem->setEnabled(! _disabledItem->isEnabled() );
	});

    item4->setFontSizeObj(20);
    item4->setFontName("Marker Felt");
    
    // Label Item (LabelBMFont)
    auto label = LabelBMFont::create("configuration", "fonts/bitmapFontTest3.fnt");
    auto item5 = MenuItemLabel::create(label, CC_CALLBACK_1(MenuLayerMainMenu::menuCallbackConfig, this));

    // Testing issue #500
    item5->setScale( 0.8f );

    // Events
    MenuItemFont::setFontName("Marker Felt");
    // Bugs Item
    auto item6 = MenuItemFont::create("Bugs", CC_CALLBACK_1(MenuLayerMainMenu::menuCallbackBugsTest, this));

    // Font Item
    auto item7= MenuItemFont::create("Quit", CC_CALLBACK_1(MenuLayerMainMenu::onQuit, this));
    
    auto item8 = MenuItemFont::create("Remove menu item when moving", CC_CALLBACK_1(MenuLayerMainMenu::menuMovingCallback, this));
    
    auto color_action = TintBy::create(0.5f, 0, -255, -255);
    auto color_back = color_action->reverse();
    auto seq = Sequence::create(color_action, color_back, NULL);
    item7->runAction(RepeatForever::create(seq));

    auto menu = Menu::create( item1, item2, item3, item4, item5, item6, item7, item8,  NULL);
    menu->alignItemsVertically();
    
    
    // elastic effect
    auto s = Director::getInstance()->getWinSize();
    
    int i=0;
    Node* child;
    auto pArray = menu->getChildren();
    Object* pObject = NULL;
    CCARRAY_FOREACH(pArray, pObject)
    {
        if(pObject == NULL)
            break;

        child = static_cast<Node*>(pObject);

        auto dstPoint = child->getPosition();
        int offset = (int) (s.width/2 + 50);
        if( i % 2 == 0)
            offset = -offset;
        
        child->setPosition( Point( dstPoint.x + offset, dstPoint.y) );
        child->runAction( 
                          EaseElasticOut::create(MoveBy::create(2, Point(dstPoint.x - offset,0)), 0.35f) 
                        );
        i++;
    }

    _disabledItem = item3; item3->retain();
    _disabledItem->setEnabled( false );

    addChild(menu);
    menu->setPosition(Point(s.width/2, s.height/2));
}
Example #6
0
void ProteomeInfo::sortPeptideInfoDescending( vector< PeptideInfo * > & vpPeptideInfoInput, string sKey )
{	
	LessPeptideInfo lessPeptideInfoSort( sKey );
	sort( vpPeptideInfoInput.begin(), vpPeptideInfoInput.end(), lessPeptideInfoSort );
	reverse( vpPeptideInfoInput.begin(), vpPeptideInfoInput.end() );	
}	
Example #7
0
obj applyCC( obj (*func)(obj, obj), obj v1, obj v2){
	if(type(v1)==LIST && type(v2)==LIST) {
		list l1=ul(v1), l2=ul(v2);
		list l=nil;
		for(; l1 && l2; l1=rest(l1), l2=rest(l2)){
			l= cons(call_fn(func, first(l1), first(l2)), l); 
		}
		if(l1 || l2) error("unmatched num. of elems. in the lists");
		return List2v(reverse(l));
	}
	obj lt,rt;
	if(type(v1)==tDblArray && type(v2)==tDblArray){
		int len = udar(v1).size;
		if(len != udar(v2).size) error("num mismatch");
		obj rr = dblArray(len);
//		obj rr = new dblarr(len);
		double* v = udar(rr).v;
		for(int i=0; i<len; i++){
			lt = Double(udar(v1).v[i]);//íxÇ¢
			rt = Double(udar(v2).v[i]);
			obj rx = call_fnr(func, lt,rt);
		//	release(lt);
		//	release(rt);
			if(type(rx)!=tDouble) error("array: type mismatch");//kore mondai
			v[i] = udbl(rx);
			release(rx);
		}
		return rr;
	}
	if(isVec(type(v1)) && isVec(type(v2))){
		int len=size(v1);
		if(len!=size(v2)) error("num mismatch");
		obj rr = aArray(len);
		for(int i=0; i<len; i++){
			lt = ind(v1,i);
			rt = ind(v2,i);
			uar(rr).v[i] = call_fnr(func, lt, rt); 
		//	release(lt);
		//	release(rt);
		}
		return rr;
	}
	if( type(v1)==LIST && isVec(type(v2))){
		list l=nil, l1=ul(v1);
		int len=size(v2);
		for(int i=0; i<len; i++,l1=rest(l1)){
			if(! l1) error("num mismatch");
			rt = ind(v2,i);
			l = cons(call_fn(func, first(l1), rt), l);
			release(rt);
		}
		return List2v(reverse(l));
	}
	if( isVec(type(v1)) && type(v2)==LIST){
		list l=nil, l2=ul(v2);
		int len=size(v1);
		for(int i=0; i<len; i++,l2=rest(l2)){
			if(! l2) error("num mismatch");
			lt=ind(v1,i);
			l=cons(call_fn(func, lt, first(l2)), l);
			release(lt);
		}
		return List2v(reverse(l));
	}
	error("operation not defined.");
	return nil;
}
  bool OBMoleculeFormat::ReadChemObjectImpl(OBConversion* pConv, OBFormat* pFormat)
  {
    std::istream &ifs = *pConv->GetInStream();
    if (!ifs.good())
      return false;

    OBMol* pmol = new OBMol;

    std::string auditMsg = "OpenBabel::Read molecule ";
    std::string description(pFormat->Description());
    auditMsg += description.substr(0,description.find('\n'));
    obErrorLog.ThrowError(__FUNCTION__,
                          auditMsg,
                          obAuditMsg);

    if(pConv->IsOption("C",OBConversion::GENOPTIONS))
      return DeferMolOutput(pmol, pConv, pFormat);

    bool ret=true;
   if(pConv->IsOption("separate",OBConversion::GENOPTIONS))
   {
     //On first call, separate molecule and put fragments in MolArray.
     //On subsequent calls, remove a fragment from MolArray and send it for writing
     //Done this way so that each fragment can be written to its own file (with -m option)
     if(!StoredMolsReady)
     {
       while(ret) //do all the molecules in the file
       {
         ret = pFormat->ReadMolecule(pmol,pConv);

         if(ret && (pmol->NumAtoms() > 0 || (pFormat->Flags()&ZEROATOMSOK)))
         {
           vector<OBMol> SepArray = pmol->Separate(); //use un-transformed molecule
           //Add an appropriate title to each fragment
           if(SepArray.size()>1)
             for(int i=0;i<SepArray.size();++i)
             {
               stringstream ss;
               ss << pmol->GetTitle() << '#' << i+1;
               string title = ss.str();
               SepArray[i].SetTitle(title);
             }
           else
              SepArray[0].SetTitle(pmol->GetTitle());

           copy(SepArray.begin(),SepArray.end(),back_inserter(MolArray));
         }
       }
       reverse(MolArray.begin(),MolArray.end());
       StoredMolsReady = true;
       //Clear the flags of the input stream(which may have found eof) to ensure will
       //try to read anothe molecule and allow the stored ones to be sent for output.
       pConv->GetInStream()->clear();
     }

     if(MolArray.empty()) //normal end of fragments
       ret =false;
     else
     {
       // Copying is needed because the OBMol passed to AddChemObject will be deleted.
       // The OBMol in the vector is deleted here.
       OBMol* pMolCopy = new OBMol( MolArray.back());
       MolArray.pop_back();
       ret = pConv->AddChemObject(
           pMolCopy->DoTransformations(pConv->GetOptions(OBConversion::GENOPTIONS), pConv))!=0;
     }
     if(!ret)
       StoredMolsReady = false;

     delete pmol;
     return ret;
   }

    ret=pFormat->ReadMolecule(pmol,pConv);

    OBMol* ptmol = NULL;
    //Molecule is valid if it has some atoms
    //or the format allows zero-atom molecules and it has a title or properties
    if(ret && (pmol->NumAtoms() > 0 
      || (pFormat->Flags()&ZEROATOMSOK && (*pmol->GetTitle() || pmol->HasData(1)))))
    {
      ptmol = static_cast<OBMol*>(pmol->DoTransformations(pConv->GetOptions(OBConversion::GENOPTIONS),pConv));
      if(ptmol && (pConv->IsOption("j",OBConversion::GENOPTIONS)
                || pConv->IsOption("join",OBConversion::GENOPTIONS)))
      {
        //With j option, accumulate all mols in one stored in this class
        if(pConv->IsFirstInput())
          _jmol = new OBMol;
        pConv->AddChemObject(_jmol);
        //will be discarded in WriteChemObjectImpl until the last input mol. This complication
        //is needed to allow joined molecules to be from different files. pOb1 in AddChem Object
        //is zeroed at the end of a file and _jmol is in danger of not being output.
        *_jmol += *ptmol;
        delete ptmol;
        return true;
      }
    }
    else
      delete pmol;

    // Normal operation - send molecule to be written
    ret = ret && (pConv->AddChemObject(ptmol)!=0); //success of both writing and reading
    return ret;
  }
 constexpr bool test1(int n) {
   char stuff[100] = "foobarfoo";
   const char stuff2[100] = "oofraboof";
   reverse(stuff, stuff + n); // expected-note {{cannot refer to element 101 of array of 100 elements}}
   return equal(stuff, stuff + n, stuff2, stuff2 + n);
 }
Example #10
0
void back(int foot)
{
	Nova=reverse(Nova);
	forward(foot);
}
Example #11
0
void right(int foot)
{
	Nova=reverse(Left[Nova][Head]);
	forward(foot);
}
Example #12
0
int main(void) {
        List lista;
        ListNode temp_node;
        int i;
        double temp_array[6];
        lista = create();
        if(add(&lista, 1, 10.5) == -1)
        {
                printf("apetuxe h eisagwgh neou stoixeiou sti listas\n");
                return 0;
        }
        if(add(&lista, 2, 76) == -1)
        {
                printf("apetuxe h eisagwgh neou stoixeiou sti listas\n");
                return 0;
        }
        if(add(&lista, 1, 63) == -1)
        {
                printf("apetuxe h eisagwgh neou stoixeiou sti listas\n");
                return 0;
        }
        if(add(&lista, 3, 109.73) == -1)
        {
                printf("apetuxe h eisagwgh neou stoixeiou sti listas\n");
                return 0;
        }
        if(add(&lista, 2, 1903.78) == -1)
        {
                printf("apetuxe h eisagwgh neou stoixeiou sti listas\n");
                return 0;
        }

        if(add(&lista, 6, 7.5) == -1)
        {
                printf("apetuxe h eisagwgh neou stoixeiou sti listas\n");
                return 0;
        }
//        PrintAll(lista);        //63, 1903.78, 10.5, 109.73, 76, 7.5
        i=1;
        temp_node=lista.Head;
        while(i<=lista.megethos){
             temp_array[i-1]=temp_node->dedomena;
             i=i+1;
             temp_node=temp_node->epomenos;
        }
        reverse(&lista);
        temp_node=lista.Head;
        for(i=0;i<6;i++){
             if(temp_array[5-i]!=temp_node->dedomena)
                  break;
             else{
                  temp_node=temp_node->epomenos;
             } 
        }
        if(i==6)
             printf("OK\n");
        else
             printf("Error\n");
//        printf("\nlista meta tin antistrofi:\n\n");
//        PrintAll(lista);
//        reverse(&lista);
//        printf("\nlista meta tin antistrofi:\n\n");
//        PrintAll(lista);
        destroy(&lista);
        return 1;
}
Example #13
0
 void rotate(int nums[], int n, int k) {
     k = k % n;
     reverse(nums, nums + n);  //可以换成迭代器
     reverse(nums, nums + k);
     reverse(nums + k, nums + n);
 }
static int insert_buffer(losig_list* losig, lofig_list* lofig, int optim_level, long index)
{
   double capa, init_capa;
   cell_list* buffer;
   chain_list* namechain, *sigchain=NULL;
   char* signame;
   lofig_list* model;
   losig_list* losig_buf;
   loins_list* loins_buf;
   locon_list* locon;
   losig_list* losig_vdd=NULL, *losig_vss=NULL, *losig_aux;
   ptype_list* ptype, *buffer_ptype;
   double delay, best_delay, init_delay;
   loins_list* loins;
   chain_list* lofigchain,*newlofigchain=NULL;
   int buffer_is_better=0, change=1;    /*flags*/
   chain_list* pred;
   chain_list* temp;


   buffer=getCellbuffer();
   /*no buffer in library*/
   if (!buffer) return 0;
   
   if (!losig->NAMECHAIN) {
      fprintf(stderr,"insert_buffer: no name on signal\n");
      autexit(1);
   }

   best_delay=critical_delay(lofig);
   init_capa=getcapacitance(losig->NAMECHAIN->DATA);

   /*add buffer to netlist*/
   signame=getautoname(losig->NAMECHAIN->DATA);
   namechain=addchain(NULL,signame);
   losig_buf=addlosig(lofig,index,namechain,INTERNAL);
   putcapacitance(signame,0);
   putdelay(signame,0);
   model=getlofig(buffer->BEFIG->NAME,'A');
   
   /*search vdd and vss*/
   for (locon=lofig->LOCON; locon; locon=locon->NEXT) {
      if (isvdd(locon->NAME)) losig_vdd=locon->SIG;
      if (isvss(locon->NAME)) losig_vss=locon->SIG;
   }
   
   /*build list of signal*/
   for (locon=model->LOCON;locon; locon=locon->NEXT) {
      if (locon->DIRECTION==UNKNOWN) {
         fprintf(stderr,"BEH: 'linkage %s' in figure '%s' isn't accepted\n",
         locon->NAME,model->NAME);
         autexit(1);
      }
      if (isvdd(locon->NAME)) losig_aux=losig_vdd;
      else if (isvss(locon->NAME)) losig_aux=losig_vss;
      else if (locon->DIRECTION==OUT) losig_aux=losig_buf;
      else if (locon->DIRECTION==IN) losig_aux=losig;
      else {
         fprintf(stderr,"insert_buffer: buffer port '%s' unknown\n",locon->NAME);
         autexit(1);
      }
      sigchain=addchain(sigchain,losig_aux);
   }

   
   sigchain=reverse(sigchain);
   loins_buf=addloins(lofig,signame,model,sigchain);
   freechain(sigchain);
   /*to check changes*/
   init_delay=getdelay(losig->NAMECHAIN->DATA);
   init_capa=getcapacitance(losig->NAMECHAIN->DATA);
   loins_capacitance(loins_buf,1/*add capa*/);
  
   /*lofigchain*/
   for (locon=loins_buf->LOCON;locon; locon=locon->NEXT) {
      if (locon->DIRECTION==UNKNOWN) {
         fprintf(stderr,"BEH: 'linkage %s' in figure '%s' isn't accepted\n",
         locon->NAME,loins_buf->INSNAME);
         autexit(1);
      }
      if (isvdd(locon->NAME)) losig_aux=losig_vdd;
      else if (isvss(locon->NAME)) losig_aux=losig_vss;
      else if (locon->DIRECTION==OUT) losig_aux=losig_buf;
      else if (locon->DIRECTION==IN) losig_aux=losig;
      else {
         fprintf(stderr,"insert_buffer: buffer port '%s' unknown\n",locon->NAME);
         autexit(1);
      }
      ptype=getptype(losig_aux->USER,LOFIGCHAIN);
      if (!ptype) losig_aux->USER=addptype(losig_aux->USER,LOFIGCHAIN,addchain(NULL,locon));
      else ptype->DATA=addchain(ptype->DATA,locon);
   }
   
   /*move all instance after buffer*/
   ptype=getptype(losig->USER,LOFIGCHAIN);
   buffer_ptype=getptype(losig_buf->USER,LOFIGCHAIN);
   if (!ptype || !buffer_ptype) {
      fprintf(stderr,"insert_buffer: LOFIGCHAIN not found\n");
      autexit(1);
   }
   
   for (lofigchain=((chain_list*)ptype->DATA)->NEXT/*first is entry of buffer*/;
        lofigchain; lofigchain=lofigchain->NEXT) {
      locon=(locon_list*) lofigchain->DATA;
      if (locon->DIRECTION==UNKNOWN) {
         fprintf(stderr,"BEH: 'linkage %s' isn't accepted\n",
         locon->NAME);
         autexit(1);
      }
      /*do not move drivers and port of circuit*/
      if (locon->TYPE==EXTERNAL || locon->DIRECTION!=IN) {
         newlofigchain=addchain(newlofigchain,locon);
         continue;
      }
      
      loins=locon->ROOT;
      /*change capacitance*/
      loins_capacitance(loins,0/*remove  capa*/);
      /*change netlist*/
      locon->SIG=losig_buf;
      buffer_ptype->DATA=addchain(buffer_ptype->DATA,locon);
      loins_capacitance(loins,1/*add capa*/);
   }
   
   /*put back drivers*/
   freechain(((chain_list*)ptype->DATA)->NEXT/*first is entry of buffer*/);
   ((chain_list*)ptype->DATA)->NEXT=newlofigchain;
   
   /*eval all changes*/
   propagate_loins_delay(loins_buf);

   /*relaxation algorithm*/
   while (change) {
      change=0;
      pred=NULL;
      buffer_ptype=getptype(losig_buf->USER,LOFIGCHAIN);
      ptype=getptype(losig->USER,LOFIGCHAIN);
      if (!buffer_ptype || !buffer_ptype->DATA) {
         fprintf(stderr,"insert_buffer: LOFIGCHAIN is empty\n");
         autexit(1);
      }
      
      /*put critical path before buffer*/
      for (lofigchain=buffer_ptype->DATA; lofigchain->NEXT/*last is buffer output*/;
           lofigchain=lofigchain->NEXT) {
         locon=lofigchain->DATA;
         loins=locon->ROOT;
      
         /*change capacitance*/
         loins_capacitance(loins,0/*remove capa*/);
         /*change netlist*/
         locon->SIG=losig;
         ptype->DATA=addchain(ptype->DATA,locon);
         loins_capacitance(loins,1/*add capa*/);

         /*put over*/
         if (pred) pred->NEXT=lofigchain->NEXT;
         else buffer_ptype->DATA=lofigchain->NEXT;
      
         /*eval all changes*/
         propagate_loins_delay(loins);
         propagate_loins_delay(loins_buf);
         delay=critical_delay(lofig);
      
         if (delay<best_delay) {
            /*finish change*/
            best_delay=delay; 
            change=1;   /*flag of change*/
            buffer_is_better=1;
            lofigchain->NEXT=NULL;
            freechain(lofigchain);
            break;
         }
         else {
            /*remove change*/
            if (pred) pred->NEXT=lofigchain;
            else buffer_ptype->DATA=lofigchain;
            
            /*unchange capacitance*/
            loins_capacitance(loins,0/*remove capa*/);
            /*unchange netlist*/
            locon->SIG=losig_buf;
            temp=ptype->DATA;
            ptype->DATA=temp->NEXT;
            temp->NEXT=NULL;
            freechain(temp);
            loins_capacitance(loins,1/*add capa*/);
            /*avoid change*/
            propagate_loins_delay(loins_buf);
            propagate_loins_delay(loins);
            
            /*for next loop*/
            pred=lofigchain;
         }
      }
      
   }/*end of while*/
   
   if (buffer_is_better) {
      /*chose the best buffer*/
      change_instance(loins_buf, losig_buf, lofig, optim_level);
   }   
   else {  /*if insert buffer is worst than before, remove it*/
      /*remove all references of buffer in lofigchain*/
      for (locon=loins_buf->LOCON; locon; locon=locon->NEXT) {
         losig_aux=locon->SIG;
         ptype=getptype(losig_aux->USER,LOFIGCHAIN);
         if (!ptype) break;
         pred=NULL;
         for (lofigchain=ptype->DATA; lofigchain; lofigchain=lofigchain->NEXT) {
            if (lofigchain->DATA==locon) {
               if (pred) pred->NEXT=lofigchain->NEXT;
               else ptype->DATA=lofigchain->NEXT;
               lofigchain->NEXT=NULL;
               freechain(lofigchain);
               break;
            }
            pred=lofigchain;
         }
      }
      
      buffer_ptype=getptype(losig_buf->USER,LOFIGCHAIN);
      ptype=getptype(losig->USER,LOFIGCHAIN);
      if (buffer_ptype) {
       for (lofigchain=buffer_ptype->DATA; lofigchain; lofigchain=lofigchain->NEXT) {
         locon=lofigchain->DATA;
         loins=locon->ROOT;
         /*change capacitance*/
         loins_capacitance(loins,0/*remove capa*/);
         /*change netlist*/
         locon->SIG=losig;
         ptype->DATA=addchain(ptype->DATA,locon);
         loins_capacitance(loins,1/*add capa*/);
         propagate_loins_delay(loins);
       }
      
       freechain(buffer_ptype->DATA);
       buffer_ptype->DATA=NULL;
      }
      
      loins_capacitance(loins_buf,0/*remove capa*/);
      dellosig(lofig,index);
      delloins(lofig,loins_buf->INSNAME);
      propagate_losig_delay(losig);
   
      /*verify no change on timing*/
      delay=critical_delay(lofig);
      capa=getcapacitance(losig->NAMECHAIN->DATA);
      //01/09/2004 xtof's modification: rounding problem
      if ((int)(capa + 0.5)!=(int)(init_capa + 0.5) || (int)(delay + 0.5)!=(int)(best_delay + 0.5) 
       || (int)(init_delay + 0.5)!=(int)(getdelay(losig->NAMECHAIN->DATA) + 0.5)) {
         fprintf(stderr,
         "insert_buffer: compute error %e!=%e fF   %f!=%f ps    %f!=%f ps\n",
         capa,init_capa,delay,best_delay, init_delay, getdelay(losig->NAMECHAIN->DATA));
         autexit(1);
      }   
   
   }
      
   return buffer_is_better;
}
bool isPalindrome(unsigned int x){
	return x == reverse(x);
}
Example #16
0
File: ansi.c Project: s114898/30010
void window(int x1, int y1, int x2, int y2, char* title, char style){
	int i, title_len;	
	char tl,tr,bl,br,hl,vl,lt,rt;

	if(style == 1){
	tl = 218;
	tr = 191;
	bl = 192;
	br = 217;
	hl = 196;
	vl = 179;
	lt = 180;
	rt = 195;
	}
	else{
	tl = 201;
	tr = 187;
	bl = 200;
	br = 188;
	hl = 205;
	vl = 186;
	lt = 185;
	rt = 204;
	}

	title_len = strlen(title);

	/* Draw top/title */
	gotoxy(x1, y1);
	printf("%c%c",tl,lt);
	reverse(1);
	printf(" %s ",title);
	if(style == 1){
		printf("%*c", x2-x1-5-title_len,0);
		reverse(0);
		printf("%c%c",rt,tr);	
	}
	else{
		reverse(0);
		printf("%c",rt);
		for(i = x1+4+title_len; i<x2-1;i++)
			printf("%c",hl);
		printf("%c",tr);
	}

	/* Draw sides */
	for(i=(y1+1); i<y2; i++){
		gotoxy(x1,i);
		printf("%c",vl);
		gotoxy(x2,i);
		printf("%c",vl);
	}

	/* Draw bottom */
	gotoxy(x1,y2);
	printf("%c",bl);
	for(i = x1+1; i < x2; i++){
		printf("%c",hl);
	}
	printf("%c",br);
} 
Example #17
0
/* The application returns:
 *    < 0 : connection or similar error
 *      0 : no errors, all tests passed
 *    > 0 : could not send all the data to server
 */
int main(int argc, char**argv)
{
	int c, ret, fd, fd_recv, i = 0, timeout = 0;
	bool flood = false;
	struct sockaddr_in6 addr6_send = { 0 }, addr6_recv = { 0 };
	struct sockaddr_in addr4_send = { 0 }, addr4_recv = { 0 };
	struct sockaddr *addr_send, *addr_recv;
	int family, addr_len;
	unsigned char buf[MAX_BUF_SIZE];
	const struct in6_addr any = IN6ADDR_ANY_INIT;
	const char *target = NULL;
	fd_set rfds;
	struct timeval tv = {};

	opterr = 0;

	while ((c = getopt (argc, argv, "F")) != -1) {
		switch (c) {
		case 'F':
			flood = true;
			break;
		}
	}

	if (optind < argc)
		target = argv[optind];

	if (!target) {
		printf("usage: %s [-F] <IPv{6|4} address of the echo-server>\n",
		       argv[0]);
		printf("\nThe -F (flood) option will prevent the client from "
		       "waiting the data.\n"
		       "The -F option will stress test the server.\n");
		exit(-EINVAL);
	}

	if (inet_pton(AF_INET6, target, &addr6_send.sin6_addr) != 1) {
		if (inet_pton(AF_INET, target, &addr4_send.sin_addr) != 1) {
			printf("Invalid address family\n");
			exit(-EINVAL);
		} else {
			addr_send = (struct sockaddr *)&addr4_send;
			addr_recv = (struct sockaddr *)&addr4_recv;
			addr4_send.sin_port = htons(SERVER_PORT);
			addr4_recv.sin_family = AF_INET;
			addr4_recv.sin_addr.s_addr = INADDR_ANY;
			addr4_recv.sin_port = htons(CLIENT_PORT);
			family = AF_INET;
			addr_len = sizeof(addr4_send);
		}
	} else {
		addr_send = (struct sockaddr *)&addr6_send;
		addr_recv = (struct sockaddr *)&addr6_recv;
		addr6_send.sin6_port = htons(SERVER_PORT);
		addr6_recv.sin6_family = AF_INET6;
		addr6_recv.sin6_addr = any;
		addr6_recv.sin6_port = htons(CLIENT_PORT);
		family = AF_INET6;
		addr_len = sizeof(addr6_send);
	}

	addr_send->sa_family = family;
	addr_recv->sa_family = family;

	fd = socket(family, SOCK_DGRAM, IPPROTO_UDP);
	if (fd < 0) {
		perror("socket");
		exit(-errno);
	}

	ret = bind(fd, addr_recv, addr_len);
	if (ret < 0) {
		perror("bind");
		exit(-errno);
	}

	ret = connect(fd, addr_send, addr_len);
	if (ret < 0) {
		perror("connect");
		exit(-errno);
	}

	do {
		while (data[i].buf) {
			ret = send(fd, data[i].buf, data[i].len, 0);
			if (ret < 0) {
				perror("send");
				goto out;
			}

			if (flood) {
				i++;
				continue;
			}

			FD_ZERO(&rfds);
			FD_SET(fd, &rfds);
			tv.tv_sec = MAX_TIMEOUT;
			tv.tv_usec = 0;

			ret = select(fd + 1, &rfds, NULL, NULL, &tv);
			if (ret < 0) {
				perror("select");
				goto out;
			} else if (ret == 0) {
				if (data[i].expecting_reply) {
					fprintf(stderr,
						"Timeout while waiting "
						"idx %d len %d\n",
						i, data[i].len);
					timeout = i;
				}
				i++;
				continue;
			} else if (!FD_ISSET(fd, &rfds)) {
				fprintf(stderr, "Invalid fd\n");
				ret = i;
				goto out;
			}

			ret = recv(fd, buf, sizeof(buf), 0);
			if (ret <= 0) {
				perror("recv");
				ret = -EINVAL;
				goto out;
			}

			reverse(buf, ret);

			if (data[i].len != ret ||
			    memcmp(data[i].buf, buf, ret) != 0) {
				fprintf(stderr,
					"Check failed idx %d len %d\n",
					i, ret);
				ret = i;
				goto out;
			} else {
				printf(".");
				fflush(stdout);
			}

			i++;
		}

		if (flood)
			i = 0;

	} while (flood);

	ret = timeout;

	printf("\n");

out:
	close(fd);

	exit(ret);
}
Example #18
0
bool book::addBook()
{
	this->hide();
	return reverse(ui.vipLineEdit->text().toInt(), ui.bookTimeDateTimeEdit->dateTime(), ui.rowComboBox->currentText().toInt());
}
Example #19
0
obj subs0(obj v, obj * vars){
	assert(!! v);
	switch(v->type){
	case tSymbol:
		if(vars){		// macro
			obj vp = search_assoc(*vars, v);
			if(vp) return vp;
		//	vp = searchFunc(v, specials);
		//	if(vp) {release(vp); return retain(v);}
			obj (*func)(obj) = searchFunc(v, specials);
			if(func) return retain(v);
			vp = find_var(v);
			if(vp) {release(vp); return retain(v);}
			assert(0);
		//	return ref2var(add_assoc(*vars, v, Null()));
		} else {		// quasi-quote
			obj vp = find_var(v);
			if(vp) return vp;
			return retain(v);
		}
    case tAssign:{
		obj vp = search_assoc(*vars, car(v));	//macro-locals
		if(vp) goto nex;
	/*	vp = searchFunc(car(v), specials);		// not needed because cant assign to global
		if(vp) {release(vp); vp = retain(v); return vp;}
		vp = find_var(v);
		if(vp) {release(vp); vp = retain(v); return vp;}
	*/	vp = ref2var(nil);
		add_assoc(vars, car(v), vp);
nex:		return operate(tAssign, vp, subs0(cdr(v), vars));
	}
    case tArray:{
		obj r = aArray(uar(v).size);
		for(int i=0; i < uar(v).size; i++) uar(r).v[i] = subs0(uar(v).v[i], vars);
		return r;
	}
    case LIST:		//list
	case POW:
	case MULT:
	case DIVIDE:
	case ARITH:
	case CONDITION:
	case tIf:
	case tExec:
        {
		list l = phi();
		for(list s=ul(v); s; s=rest(s))  l = cons(subs0(first(s), vars), l);
		return render(type(v), reverse(l));
        }
	case tReturn:
		if(!uref(v)) return retain(v);
	case tMinus:
		return encap(v->type, subs0(uref(v), vars));
	case tClosure:
	case tArrow:
		return render(type(v), list3(subs0(em0(v),vars), subs0(em1(v), vars), nil));
	case tDefine:
	case tSyntaxDef:
		assert(0);
	case tInd:
	case tWhile:
		{
		obj st = subs0(cdr(v), vars);
		if(type(st)==LIST) st->type = tExec;
		return operate(v->type, subs0(car(v), vars), st);
		}
	case tOp:
		return operate(v->type, subs0(car(v), vars), subs0(cdr(v), vars));
	case INT:
	case tDouble:
	case TOKEN:
	case tNull:
	case tLAVec:
	case tDblArray:
	case tIntArr:
	case tDblAr2:
	case IMAGE:
	case STRING:
	case tBreak:
		return retain(v);
    default:
        break;
	}
	print(v);
	assert(0);
	return v;
}
Example #20
0
void Copenclspectrometer::filter_signal_zfactor(float *psamples, int *psamplenum, int start, int stop, float fmax)
{
//return;
  float fact[] = {64, 32, 16, 8, 4};
  int   i;
  float cutfrequency;
  int   scut;
  int   arsize;
  int   precision = 0;

  m_bhalfband = false;
  arsize = (int)(sizeof(fact) / sizeof(float));
  for (i = 0; i < arsize; i++)
    {
      if ((int)(2. * fmax) < (m_sampling_frequency / fact[i]) - precision)
	{
	  scut = fact[i] / 2;
	  cutfrequency = (float)m_sampling_frequency / fact[i];
#ifdef USEFIR_KERNEL
	  switch (scut * 2)
	    {
	    case 4:
	      m_pfir_coefs = xcoeffs4; // cuttoff = f / 4 samplingf = f / 2
	      break;
	    case 8:
	      m_pfir_coefs = xcoeffs8;
	      break;
	    case 16:
	      m_pfir_coefs = xcoeffs16;
	      break;
	    case 32:
	      m_pfir_coefs = xcoeffs32;
	    default:
	      m_pfir_coefs = xcoeffs64;
	      break;
	    }
	  if (scut >= 2)
	    {
	      m_bhalfband = true;
	      m_kfirparams.intracksize = *psamplenum;
	      m_kfirparams.decimation = scut;
//#define CPU_FIR
#ifdef CPU_FIR
	      double t1 = SDL_GetTicks();
	      m_bhalfband = false;
	      //downsample(psamples, *psamplenum, scut);
	      filterloop(psamples, m_pfir_coefs, &m_kfirparams);
	      double t2 = SDL_GetTicks();
	      //printf("filtering took %fms\n", t2 - t1);
#endif
	    }
#else
	  double t1 = SDL_GetTicks();
	  DSPCPPfilter_low_pass_Butterworth(psamples, *psamplenum, m_sampling_frequency, cutfrequency);
	  reverse(psamples, *psamplenum);
	  DSPCPPfilter_low_pass_Butterworth(psamples, *psamplenum, m_sampling_frequency, cutfrequency);
	  reverse(psamples, *psamplenum);
	  downsample(psamples, *psamplenum, scut);
	  double t2 = SDL_GetTicks();
	  //printf("filtering took %fms\n", t2 - t1);
#endif
	  m_kparams.tracksize /= scut;
	  m_kparams.start_sample /= scut;
	  m_kparams.stop_sample /= scut;
	  m_kparams.sampling_frequency = 2 * cutfrequency;
	  m_kparams.N = get_N(m_kparams.sampling_frequency);
	  *psamplenum /= scut;
	  //printf("cutoff=%f decimation=%d\n", cutfrequency, m_kfirparams.decimation);
	  return;
	}
    }
}
Example #21
0
inline list evalList(list l){
	push(List2v((list)nil));
	for(;l;) ul(sp0) = cons(eval(fpp(l)), ul(sp0));
	obj rr = pop(&is);
	return reverse(strip2list(rr));
}
Example #22
0
void print(char *str) {
	reverse(str);
	printf("\nreversed: %s\n", str);
}
Example #23
0
void GraphsListN::addGraph( vector< short unsigned int > iVertices, const vector< bool > &bVerticesLinkable, const unsigned int &iType, bool bSpherical, const short unsigned int &iVertexSupp1, const short unsigned int &iVertexSupp2, const unsigned int &iDataSupp )
{
	unsigned int short iTemp, i;
	
	if( bSpherical )
	{
		if( iType == 0 ) // An
		{
			// on veut une fois les A_n (et pas une fois pour chaque sens de lecture)
			if( iVertices.front( ) > iVertices.back( ) )
				reverse( iVertices.begin( ), iVertices.end( ) );
		}
		else if( iType == 1 ) // Bn
		{
			iVertices.push_back( iVertexSupp1 );
		}
		else if( iType == 3 ) // Dn
		{
			if( iVerticesCount > 4 )
			{
				iTemp = iVertices[ iVerticesCount - 2 ];
				iVertices[ iVerticesCount - 2 ] = min( iTemp, iVertexSupp1 );
				iVertices.push_back( max( iTemp, iVertexSupp1 ) );
			}
			else
			{
				if( iVertices[0] > iVertices[2] )
				{
					iTemp = iVertices[0];
					iVertices[0] = iVertices[2];
					iVertices[2] = iTemp;
				}
				
				if( iVertexSupp1 < iVertices[0] )
				{
					iVertices.push_back( iVertices[2] );
					iVertices[2] = iVertices[0];
					iVertices[0] = iVertexSupp1;
				}
				else if( iVertexSupp1 < iVertices[2] )
				{
					iVertices.push_back( iVertices[2] );
					iVertices[2] = iVertexSupp1;
				}
				else
					iVertices.push_back( iVertexSupp1 );
				
			}
		}
		else if( iType == 4 ) // En
		{
			if( iVerticesCount == 6 )
			{
				if( iVertices.front( ) > iVertices.back( ) )
					reverse( iVertices.begin( ), iVertices.end( ) );
			}
			iVertices.push_back( iVertexSupp1 );
		}
		else if( iType == 5 ) // Fn
		{
			iVertices.push_back( iVertexSupp1 );
			if( iVertices.front( ) > iVertices.back( ) )
				reverse( iVertices.begin( ), iVertices.end( ) );
		}
		else if( iType == 7 ) // Hn
		{
			iVertices.push_back( iVertexSupp1 );
		}
	}
	else
	{
		if( iType == 0 && iDataSupp )
		{
			int iMinIndex(0);
			unsigned int iMinValue( iVertices[0] );
			
			iVertices.push_back( iVertexSupp1 );
			vector< short unsigned int > iVerticesTemp( iVertices );
			
			// on répère le sommet avec l'indice le plus petit
			for( i = 1; i < iVerticesCount; i++ )
			{
				if( iVertices[i] < iMinValue )
				{
					iMinValue = iVertices[i];
					iMinIndex = i;
				}
			}
				
			// et le sens de parcours
			int iDirection( iVertices[ !iMinIndex ? (iVerticesCount - 1) : (iMinIndex - 1) ] > iVertices[ iMinIndex == (int)( iVerticesCount - 1 ) ? 0 : ( iMinIndex + 1 ) ] ? 1 : -1 );
			
			// on réordonne
			for( unsigned int j(0); j < iVerticesCount; j++ )
			{
				iVertices[j] = iVerticesTemp[iMinIndex];
				
				iMinIndex += iDirection;
				if( iMinIndex == -1 )
					iMinIndex = iVerticesCount - 1;
				else if( iMinIndex == (int)iVerticesCount )
					iMinIndex = 0;
			}
		}
		else if( iType == 1 ) // TBn
		{
			if( iVerticesCount == 4 ) // TB3
			{
				i = iVertices[1];
				iTemp = max( iVertices[0], iVertices[2] );
				iVertices[1] = min( iVertices[0], iVertices[2] ); 
				iVertices[2] = iTemp;
				iVertices[0] = i;
				
				iVertices.insert( iVertices.begin( ), iVertexSupp1 );
			}
			else // autres \tilde Bn
			{	
				iTemp = min( iVertices[ iVerticesCount - 3 ], iVertexSupp1 );
				iVertices.push_back( max( iVertices[ iVerticesCount - 3 ], iVertexSupp1 ) );
				iVertices[ iVerticesCount - 3 ] = iTemp;
				
				iVertices.insert( iVertices.begin( ), iVertexSupp2 );
			}
		}
		else if( iType == 2 ) // \tilde Cn
		{
			iVertices.insert( iVertices.begin( ), iVertexSupp1 );
			iVertices.push_back( iVertexSupp2 );
				
			if( iVertices[0] > iVertices[ iVerticesCount - 1 ] )
				reverse( iVertices.begin( ), iVertices.end( ) );
		}
		else if( iType == 3 ) // \tilde Dn
		{
			if( iVerticesCount >= 6 )
			{
				// le vecteur iVerticesBase contient la base (i.e. sans les 4 extrémités)
				#ifdef _MSC_VER
					vector< short unsigned int > iVerticesBase;
					iTemp = iVerticesCount - 3;
					for( i = 1; i < iTemp; i++ )
						iVerticesBase.push_back( iVertices[i] );
				#else
					vector< short unsigned int > iVerticesBase( iVertices.begin( ) + 1, iVertices.begin( ) + iVerticesCount - 3 ); // ne marche pas sous Visual Studio 2010 & 2012 malheureusement
				#endif

				// on regarde si on doit modifier l'ordre
				if( iVerticesBase[0] > iVerticesBase[ iVerticesCount - 5 ] )
				{
					reverse( iVerticesBase.begin( ), iVerticesBase.end( ) );
					
					// ajout des 4 extrémités
					iVerticesBase.push_back( min( iVertices[0], iVertexSupp1 ) );
					iVerticesBase.push_back( max( iVertices[0], iVertexSupp1 ) );
					iVerticesBase.insert( iVerticesBase.begin( ), max( iVertices[ iVerticesCount - 3 ], iVertexSupp2 ) );
					iVerticesBase.insert( iVerticesBase.begin( ), min( iVertices[ iVerticesCount - 3 ], iVertexSupp2 ) );
				}
				else
				{
					// ajout des 4 extrémités
					iVerticesBase.push_back( min( iVertices[ iVerticesCount - 3 ], iVertexSupp2 ) );
					iVerticesBase.push_back( max( iVertices[ iVerticesCount - 3 ], iVertexSupp2 ) );
					iVerticesBase.insert( iVerticesBase.begin( ), max( iVertices[0], iVertexSupp1 ) );
					iVerticesBase.insert( iVerticesBase.begin( ), min( iVertices[0], iVertexSupp1 ) );
				}

				iVertices = iVerticesBase;
			}
			else // le TD4, "+" est traité différemment
			{
				vector<short unsigned int> iVerticesTemp( 4, 0 );
				iVerticesTemp[0] = iVertices[0];
				iVerticesTemp[1] = iVertices[2];
				iVerticesTemp[2] = iVertexSupp1;
				iVerticesTemp[3] = iVertexSupp2;
				sort( iVerticesTemp.begin( ), iVerticesTemp.end( ) );
				iVerticesTemp.push_back( iVertices[1] );
				iVertices = iVerticesTemp;
			}
		}
		else if( iType == 4 ) // \tilde En
		{
			if( iVerticesCount == 7 ) // TE6
			{
				// TODO: refaire l'encodage de ce graphe et modifer la fonction bIsSubgraphOf_spherical_euclidean?
				vector< short unsigned int > iVerticesTemp;
				unsigned int iMin( min( min( iVertices[1], iVertices[3] ), iVertexSupp1 ) );
				
				if( iMin == iVertices[1] )
				{
					iVerticesTemp.push_back( iVertices[0] );
					iVerticesTemp.push_back( iVertices[1] );
					
					if( min( iVertices[3], iVertexSupp1 ) == iVertices[3] )
					{
						iVerticesTemp.push_back( iVertices[3] );
						iVerticesTemp.push_back( iVertices[4] );
						iVerticesTemp.push_back( iVertexSupp1 );
						iVerticesTemp.push_back( iVertexSupp2 );
					}
					else
					{
						iVerticesTemp.push_back( iVertexSupp1 );
						iVerticesTemp.push_back( iVertexSupp2 );
						iVerticesTemp.push_back( iVertices[3] );
						iVerticesTemp.push_back( iVertices[4] );
					}
				}
				else if( iMin == iVertices[3] )
				{
					iVerticesTemp.push_back( iVertices[4] );
					iVerticesTemp.push_back( iVertices[3] );
					
					if( min( iVertices[1], iVertexSupp1 ) == iVertices[1] )
					{
						iVerticesTemp.push_back( iVertices[1] );
						iVerticesTemp.push_back( iVertices[0] );
						iVerticesTemp.push_back( iVertexSupp1 );
						iVerticesTemp.push_back( iVertexSupp2 );
					}
					else
					{
						iVerticesTemp.push_back( iVertexSupp1 );
						iVerticesTemp.push_back( iVertexSupp2 );
						iVerticesTemp.push_back( iVertices[1] );
						iVerticesTemp.push_back( iVertices[0] );
					}
				}
				else
				{
					iVerticesTemp.push_back( iVertexSupp2 );
					iVerticesTemp.push_back( iVertexSupp1 );
					
					if( min( iVertices[1], iVertices[3] ) == iVertices[1] )
					{
						iVerticesTemp.push_back( iVertices[1] );
						iVerticesTemp.push_back( iVertices[0] );
						iVerticesTemp.push_back( iVertices[3] );
						iVerticesTemp.push_back( iVertices[4] );
					}
					else
					{
						iVerticesTemp.push_back( iVertices[3] );
						iVerticesTemp.push_back( iVertices[4] );
						iVerticesTemp.push_back( iVertices[1] );
						iVerticesTemp.push_back( iVertices[0] );
					}	
				}
				
				iVerticesTemp.push_back( iVertices[2] );
				iVertices = iVerticesTemp;
			}
			else if( iVerticesCount == 8  ) // TE7
			{
				if( iVertices.front( ) > iVertices.back( ) ) // la base du \tilde E7 est symétrique
					reverse( iVertices.begin( ), iVertices.end( ) );
				
				iVertices.push_back( iVertexSupp1 );
			}
			else // TE8
			{
				iVertices.push_back( iVertexSupp1 );
			}
		}
		else if( iType == 5 )
		{
			iVertices.push_back( iVertexSupp1 );
		}
		else if( iType == 6 && iDataSupp ) // \tilde G_2
		{
			iVertices.push_back( iVertexSupp1 );
		}
	}
	
	Graph g( iVertices, ptr_map_vertices_indexToLabel, bVerticesLinkable, iType, bSpherical, iDataSupp );

	auto it( lower_bound( graphs.begin(), graphs.end(), g ) );
	if( it == graphs.end() || !(*it == g) )
		graphs.insert( it, g );
}
int main(int argc, char **argv) {
  char *s = argv[1];
  reverse(s);
  printf("%s\n", s);
}
Example #25
0
void main()
{
	int n,num,num1,flag=0;

	while(1)
	{
		clrscr();
		printf("\n\t\t\t******  LINKED LIST OPERATION  ******\n");
		printf("\t\t\t......_________________________......\n");

		printf("\nWELCOME,WHAT YOU WANT TO DO ?::");
		printf("\n_____________________________\n\n");

		printf("\nINSERTION--PRESS 1\n");
		printf("\nDELETION --PRESS 2\n");
		printf("\nSEARCH   --PRESS 3\n");
		printf("\nCOUNT    --PRESS 4\n");
		printf("\nDISPLAY  --PRESS 5\n");
		printf("\nREVERSE  --PRESS 6\n");
		printf("\nEXIT     --PRESS 7\n");
		printf("\n\nENTER YOUR CHOICE::\n");
		scanf("%d",&n);

		switch(n)
		{
			case 1:
					while(1)
					{
						flag=0;
						clrscr();
						printf("INSERT A NODE ::\n");

						printf("\t\tAT FIRST      -PRESS 1.\n");
						printf("\t\tAFTER A NODE  -PRESS 2.\n");
						printf("\t\tBEFORE A NODE -PRESS 3.\n");
						printf("\t\tAT LAST       -PRESS 4.\n");
						printf("\t\tEXIT FROM HERE-PRESS 5.\n");
						printf("\n\nENTER YOUR CHOICE::\n");
						scanf("%d",&n);
						switch(n)
						{
							case 1:
									printf("\nENTER A ELEMENT FOR INSERTION\n");
									scanf("%d",&num);
									finsert(num);
									printf("\n%d IS INSERT AT FIRST PROPERLY\n",num);
									break;
							case 2:
									printf("\nENTER A ELEMENT FOR INSERTION\n");
									scanf("%d",&num);
									printf("AFTER WHICH ELEMENT YOU WANT TO INSERT\n");
									scanf("%d",&num1);
									ainsert(num,num1);
									break;
							case 3:
									printf("ENTER A ELEMENT FOR INSERTION\n");
									scanf("%d",&num);
									printf("BEFORE WHICH ELEMENT YOU WANT TO INSERT\n");
									scanf("%d",&num1);
									binsert(num,num1);
									break;
							case 4:
									printf("ENTER  AN ELEMENT FOR INSERT IN LAST\n");
									scanf("%d",&num);
									linsert(num);
									break;
							case 5:
									printf("\nTHANK YOU FOR USING INSERT OPERETION\n");
									flag=1;
									break;

						}
						getch();
						if(flag==1)
							break;
					}
					break;
			case 2:
					while(1)
					{
						flag=0;
						clrscr();
						printf("DELETE A NODE ::\n");

						printf("\t\tAT FIRST      -PRESS 1.\n");
						printf("\t\tAFTER A NODE  -PRESS 2.\n");
						printf("\t\tBEFORE A NODE -PRESS 3.\n");
						printf("\t\tAT LAST       -PRESS 4.\n");
						printf("\t\tEXACT A NODE  -PRESS 5.\n");
						printf("\t\tEXIT FROM HERE-PRESS 6.\n");
						printf("\n\nENTER YOUR CHOICE::\n");
						scanf("%d",&n);
						switch(n)
						{
							case 1:
									fdelete();
									break;
							case 2:
									printf("\nENTER AFTER WHICH ELEMENT YOU WANT TO DELETE A NODE\n");
									scanf("%d",&num);
									adelete(num);
									break;
							case 3:
									printf("\nENTER BEFORE WHICH ELEMENT YOU WANT TO DELETE A NODE\n");
									scanf("%d",&num);
									bdelete(num);
									break;
							case 4:
									ldelete();
									break;
							case 5:
									printf("WHICH ELEMENT CONTAIN NODE YOU WANT TO DELETE:\n");
									scanf("%d",&num);
									edelete(num);
									break;
							case 6:
									printf("THANK YOU FOR USING DELETE OPERETION");
									flag=1;
									break;
						}
						getch();
						if(flag==1)
							break;
					}
					break;
			case 3:
					printf("WHICH ELEMENT YOU WANT TO SEARCH ?");
					scanf("%d",&num);
					search(num);
					break;
			case 4:
					num=count();
					printf("AT PRESENT LINKLIST CONTAIN %d NODES\n",num);
					break;

			case 5:
					fdisplay();
					break;
			case 6:
					reverse();
					printf("\nREVERSE OPERATION IS COMPLETED SUCESSFULLY\n");
					break;
			case 7:
					printf("\n\nTHANK YOU FOR USING THIS PROGRAM\n");
					getch();
					exit(0);
		}
		getch();
	}
}
Example #26
0
void hamilton()
{
    int s=1,t;
    int ansi=2,i,j,w;
    int temp;
    bool visit[410]= {false};
    for(i=1; i<=n; i++)
    {
        if(map[s][i])break;
    }
    t=i;
    visit[s]=visit[t]=true;
    ans[0]=s;
    ans[1]=t;
    while(true)
    {
        while(true)
        {
            for ( i = 1; i <=n; ++i)
            {
                if(map[t][i]&&!visit[i])
                {
                    ans[ansi++]=i;
                    visit[i]=true;
                    t=i;
                    break;
                }
            }
            if(i>n)break;
        }
        w=ansi-1;
        i=0;
        reverse(i,w);
        temp=s;
        s=t;
        t=temp;
        while(true)
        {
            for ( i = 1; i <=n; ++i)
            {
                if(map[t][i]&&!visit[i])
                {
                    ans[ansi++]=i;
                    visit[i]=true;
                    t=i;
                    break;
                }
            }
            if(i>n)
                break;
        }
        if(!map[s][t])
        {
            for(i=1; i<ansi-2; i++)
                if(map[ans[i]][t]&&map[s][ans[i+1]])break;
            w=ansi-1;
            i++;
            t=ans[i];
            reverse(i,w);
        }
        if(ansi==n)
            return ;
        for(j=1; j<=n; j++)
        {
            if(visit[j])continue;
            for(i=1; i<ansi-1; i++)if(map[ans[i]][j])break;
            if(map[ans[i]][j])break;
        }
        s=ans[i-1];
        t=j;
        reverse(0,i-1);
        reverse(i,ansi-1);
        ans[ansi++]=j;
        visit[j]=true;
    }
}
Example #27
0
Action* BasicTest::actionScale()
{
    auto scale = ScaleBy::create(1.33f, 1.5f);
    return RepeatForever::create(Sequence::create(scale, scale->reverse(), nullptr));
}
bool HighScoresScene::init()
{
	if (!Layer::init())
	{
		return false;
	}

	Size visibleSize = Director::getInstance()->getVisibleSize();
	Vec2 origin = Director::getInstance()->getVisibleOrigin();

	auto backgroundSprite = Sprite::create();
	backgroundSprite->retain();
	backgroundSprite->setTextureRect(Rect(0,0,visibleSize.width,visibleSize.height));
	backgroundSprite->setColor(Color3B(WHITE,WHITE,WHITE));
	backgroundSprite->setPosition(visibleSize.width / 2, visibleSize.height / 2);

	titleSprite = Sprite::create();
	titleSprite->retain();
	titleSprite->setTextureRect(Rect(0,0,visibleSize.width - BORDER_WIDTH,BORDER_HEIGHT));
	titleSprite->setColor(Color3B(BLACK,BLACK,BLACK));
	titleSprite->setPosition(visibleSize.width + visibleSize.width / 2 + BORDER_WIDTH / 2, BORDER_HEIGHT / 2 + BORDER_HEIGHT * 4);

	auto titleLabel = Label::createWithTTF("High Scores","Roboto-Light.ttf",MENU_FONT_SIZE);
	titleLabel->setColor(Color3B(WHITE,WHITE,WHITE));
	titleLabel->setPosition(BORDER_WIDTH + titleLabel->getContentSize().width / 2,BORDER_HEIGHT / 2);

	classicSprite = Sprite::create();
	classicSprite->retain();
	classicSprite->setTextureRect(Rect(0,0,visibleSize.width,BORDER_HEIGHT));
	classicSprite->setColor(Color3B(WHITE,WHITE,WHITE));
	classicSprite->setPosition(visibleSize.width + visibleSize.width / 2, BORDER_HEIGHT / 2 + BORDER_HEIGHT * 3);

	auto classicLabel = Label::createWithTTF("Classic","Roboto-Light.ttf",MENU_FONT_SIZE);
	classicLabel->setColor(Color3B(BLACK,BLACK,BLACK));
	classicLabel->setPosition(BORDER_WIDTH * 2 + classicLabel->getContentSize().width / 2,BORDER_HEIGHT / 2);

	arcadeSprite = Sprite::create();
	arcadeSprite->retain();
	arcadeSprite->setTextureRect(Rect(0,0,visibleSize.width,BORDER_HEIGHT));
	arcadeSprite->setColor(Color3B(WHITE,WHITE,WHITE));
	arcadeSprite->setPosition(visibleSize.width + visibleSize.width / 2, BORDER_HEIGHT / 2 + BORDER_HEIGHT * 2);

	auto arcadeLabel = Label::createWithTTF("Arcade Mode","Roboto-Light.ttf",MENU_FONT_SIZE);
	arcadeLabel->setColor(Color3B(BLACK,BLACK,BLACK));
	arcadeLabel->setPosition(BORDER_WIDTH * 2 + arcadeLabel->getContentSize().width / 2,BORDER_HEIGHT / 2);

	speedSprite = Sprite::create();
	speedSprite->retain();
	speedSprite->setTextureRect(Rect(0,0,visibleSize.width,BORDER_HEIGHT));
	speedSprite->setColor(Color3B(WHITE,WHITE,WHITE));
	speedSprite->setPosition(visibleSize.width + visibleSize.width / 2, BORDER_HEIGHT / 2 + BORDER_HEIGHT);

	auto speedLabel = Label::createWithTTF("Speed Mode","Roboto-Light.ttf",MENU_FONT_SIZE);
	speedLabel->setColor(Color3B(BLACK,BLACK,BLACK));
	speedLabel->setPosition(BORDER_WIDTH * 2 + speedLabel->getContentSize().width / 2,BORDER_HEIGHT / 2);

	undefinedSprite = Sprite::create();
	undefinedSprite->retain();
	undefinedSprite->setTextureRect(Rect(0,0,visibleSize.width,BORDER_HEIGHT));
	undefinedSprite->setColor(Color3B(WHITE,WHITE,WHITE));
	undefinedSprite->setPosition(visibleSize.width + visibleSize.width / 2, BORDER_HEIGHT / 2);

	auto undefinedLabel = Label::createWithTTF("Hard Mode","Roboto-Light.ttf",MENU_FONT_SIZE);
	undefinedLabel->setColor(Color3B(BLACK,BLACK,BLACK));
	undefinedLabel->setPosition(BORDER_WIDTH * 2 + undefinedLabel->getContentSize().width / 2, BORDER_HEIGHT / 2);

	addChild(backgroundSprite);
	addChild(titleSprite);
	titleSprite->addChild(titleLabel);
	addChild(classicSprite);
	classicSprite->addChild(classicLabel);
	addChild(arcadeSprite);
	arcadeSprite->addChild(arcadeLabel);
	addChild(speedSprite);
	speedSprite->addChild(speedLabel);
	addChild(undefinedSprite);
	undefinedSprite->addChild(undefinedLabel);

	auto border = new Border(this);

	auto keyboardListener = EventListenerKeyboard::create();
	keyboardListener->onKeyReleased = CC_CALLBACK_2(HighScoresScene::onKeyReleased, this);

	setKeypadEnabled(true);

	auto touchSpriteListener = EventListenerTouchOneByOne::create();

	touchSpriteListener->setSwallowTouches(true);
	touchSpriteListener->onTouchBegan = [&](cocos2d::Touch* touch, cocos2d::Event* event)
	{
		if(classicSprite->getBoundingBox().containsPoint(touch->getLocation()))
		{
			classicOnTouchBegan(touch,event);

			return true;
		}
		else if(arcadeSprite->getBoundingBox().containsPoint(touch->getLocation()))
		{
			arcadeOnTouchBegan(touch,event);

			return true;
		}
		else if(speedSprite->getBoundingBox().containsPoint(touch->getLocation()))
		{
			speedOnTouchBegan(touch,event);

			return true;
		}
		else if(undefinedSprite->getBoundingBox().containsPoint(touch->getLocation()))
		{
			undefinedOnTouchBegan(touch,event);

			return true;
		}
		return false;
	};

	Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(touchSpriteListener,this);

	auto move = MoveBy::create(MENU_MOVE_DT,Vec2(visibleSize.width, 0));

	showAction = EaseExponentialOut::create(move->reverse());
	showAction->retain();

	hideAction = EaseExponentialIn::create(move->clone());
	hideAction->retain();

	CocosDenshion::SimpleAudioEngine::getInstance()->playEffect("menu-in.ogg");

	classicSprite->runAction(showAction->clone());
	arcadeSprite->runAction(showAction->clone());
	speedSprite->runAction(showAction->clone());
	undefinedSprite->runAction(showAction->clone());
	titleSprite->runAction(showAction->clone());

	return true;
}
Example #29
0
std::vector<int> Pathfinder::getPathFrom(int start) const
{
    if (goal_(start)) return {start};

    // Record shortest path costs for every node we examine.
    std::unordered_map<int, PathNodePtr> nodes;
    // Maintain a heap of nodes to consider.
    std::vector<int> open;
    int goalLoc = -1;
    PathNodePtr goalNode;

    // The heap functions confusingly use operator< to build a heap with the
    // *largest* element on top.  We want to get the node with the *least* cost,
    // so we have to order nodes in the opposite way.
    auto orderByCost = [&] (int lhs, int rhs)
    {
        return nodes[lhs]->estTotalCost > nodes[rhs]->estTotalCost;
    };

    nodes.emplace(start, make_node(-1, 0, 0));
    open.push_back(start);

    // A* algorithm.  Decays to Dijkstra's if estimate function is always 0.
    while (!open.empty()) {
        auto loc = open.front();
        pop_heap(std::begin(open), std::end(open), orderByCost);
        open.pop_back();
        if (goal_(loc)) {
            goalLoc = loc;
            goalNode = nodes[loc];
            break;
        }

        auto &curNode = nodes[loc];
        curNode->visited = true;
        for (auto n : neighbors_(loc)) {
            auto nIter = nodes.find(n);
            auto step = stepCost_(loc, n);

            if (nIter != nodes.end()) {
                auto &nNode = nIter->second;
                if (nNode->visited) {
                    continue;
                }

                // Are we on a shorter path to the neighbor node than what
                // we've already seen?  If so, update the neighbor's node data.
                if (curNode->costSoFar + step < nNode->costSoFar) {
                    nNode->prev = loc;
                    nNode->costSoFar = curNode->costSoFar + step;
                    nNode->estTotalCost = nNode->costSoFar + estimate_(n);
                    make_heap(std::begin(open), std::end(open), orderByCost);
                }
            }
            else {
                // We haven't seen this node before.  Add it to the open list.
                nodes.emplace(n, make_node(loc, curNode->costSoFar + step, 
                    curNode->costSoFar + step + estimate_(n)));
                open.push_back(n);
                push_heap(std::begin(open), std::end(open), orderByCost);
            }
        }
    }

    if (!goalNode) {
        return {};
    }

    // Build the path from the chain of nodes leading to the goal.
    std::vector<int> path = {goalLoc};
    auto n = goalNode;
    while (n->prev != -1) {
        path.push_back(n->prev);
        n = nodes[n->prev];
    }
    reverse(std::begin(path), std::end(path));
    return path;
}
    bool isPalindrome2(int x) 
	{
        return (x>=0 && x == reverse(x));
    }