Exemple #1
0
int findEmpty(int i,int j)
{
  //  printf("Hi1\n");
  if(*(*(ptr+i)+j)==0)
    {
      put[count].xCordinate= i;
      put[count].yCordinate = j;
      //count+=1;
      solveSudoku(i,j,1);
    }
  if(i>=8 && j>=8)
    {
      printf("Sudoku successful \n");
      return 1;
    }
  else if(j!=8)
    {
      findEmpty(i,j+1);
    }
  else
    {
      findEmpty(i+1,0);
    }
  return 1;
}
//given a page table, same data, and a pagenum, store the data in a CacheLoc and link the PageNum to the CacheLoc
void AddToPageTable(struct PageTable* pt, struct Memory* MemoryBank, int pageNum, char* data, char* name, int offset, int length)
{
    int min = INT_MIN;
    int index = 0;
    int* memLocs;// = malloc(sizeof(int));
    
    int i;
    for (i = 0; i < numPages; i++)
    {
        //look for the first -1 you can find.
        if (pt->PageNumber[i] == -1)
        {
            //if the pagenum is -1 and the cacheLoc is -1, find a frame in CacheMem to store stuff
            index = i;
            memLocs = findEmpty(MemoryBank, 1);
            
            break;
        }
        else if(pt->PageNumber[i] > min) //Otherwise just overwrite the smallest indexed thing
        {
            index = i;
            min = pt->PageNumber[i];
        }
    }
    
    
    //reassign pt->pageNumber[index] to pageNum(provided)
    /*DO I NEED TO SET NAME HERE? SHOULD I HAVE THAT PASSED AS AN ARGUMENT?********/
    pt->Name = name;                        //set the name too just in case
    pt->PageNumber[index] = pageNum;
    pt->MemoryLocation[index] = memLocs[0]; //store actual data in the frame we have reserved
    pt->offset = offset;
    pt->bytesincache = length;
    pt->PageTableUseTime = clock();
}
Exemple #3
0
int Overlays::play(const Common::String &name, int loopId, bool loopForever, bool startNow, int a6) {
	assert(name.size() <= 12);

	int32 hash = MIXArchive::getHash(name);
	int index = findByHash(hash);
	if (index < 0) {
		index = findEmpty();
		if (index < 0) {
			return index;
		}
		_videos[index].loaded = true;
		_videos[index].name = name;
		_videos[index].hash = hash;
		_videos[index].vqaPlayer = new VQAPlayer(_vm, &_vm->_surfaceFront);

		// repeat forever
		_videos[index].vqaPlayer->setBeginAndEndFrame(0, 0, -1, kLoopSetModeJustStart, nullptr, nullptr);
	}

	Common::String resourceName = Common::String::format("%s.VQA", name.c_str());
	_videos[index].vqaPlayer->open(resourceName);
	_videos[index].vqaPlayer->setLoop(
		loopId,
		loopForever ? -1 : 0,
		startNow ? kLoopSetModeImmediate : kLoopSetModeEnqueue,
		nullptr, nullptr);

	return index;
}
Exemple #4
0
int Overlays::play(const Common::String &name, int loopId, int loopForever, int startNow, int a6) {
	int id = mix_id(name);
	int index = findById(id);
	if (index < 0) {
		index = findEmpty();
		if (index < 0) {
			return index;
		}
		_videos[index].id = id;
		_videos[index].vqaPlayer = new VQAPlayer(_vm, &_vm->_surfaceGame);

		// repeat forever
		_videos[index].vqaPlayer->setBeginAndEndFrame(0, 0, -1, kLoopSetModeJustStart, nullptr, nullptr);
		_videos[index].loaded = true;
	}

	Common::String resourceName = Common::String::format("%s.VQA", name.c_str());
	_videos[index].vqaPlayer->open(resourceName);
	_videos[index].vqaPlayer->setLoop(
		loopId,
		loopForever ? -1 : 0,
		startNow ? kLoopSetModeImmediate : kLoopSetModeEnqueue,
		nullptr, nullptr);

	return index;
}
Exemple #5
0
void Map::generate(TCODRandom* random) {
    // Generate a random map
    
    // Throw out the old map
    map.clear();
    
    int numRooms = random->getInt(20, 30);
    
    for(int i = 0; i < numRooms; i++) {
        // Make some rooms
        make_rectangle(random->getInt(0, 20), random->getInt(0, 20), random->getInt(3, 10), random->getInt(3, 10));
    }
    
    // Flood fill from a single point and delete everything else.
    std::set<std::pair<int, int>> reachable;
    
    // We need to remember what we already queued
    std::set<std::pair<int, int>> tested;
    // Start at a random place and flood fill from there.
    std::list<std::pair<int, int>> queue = {findEmpty(random)};
    
    while(queue.size() > 0) {
        // Grab a random place
        auto toVisit = queue.front();
        queue.pop_front();
        
        if(getTile(toVisit.first, toVisit.second).isPassable()) {
            // We can go here!
            
            // This tile is reachable
            reachable.insert(toVisit);
            
            std::vector<std::pair<int, int>> offsets = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
            for(auto offset : offsets) {
                auto nextToVisit = std::make_pair(toVisit.first + offset.first, toVisit.second + offset.second);
                
                if(!tested.count(nextToVisit)) {
                
                    // Try this potentially reachable spot next.
                    queue.push_back(nextToVisit);
                    // Don't queue it again
                    tested.insert(nextToVisit);   
                }
                
            }
        }
    }
    
    for(auto& kv : map) {
        if(!reachable.count(kv.first) && kv.second.isPassable()) {
            // This is a passable place that isn't reachable.
            
            // Make it impassable as a hack. The player will never know because
            // they can never get there, but it won't be chosen when we ask for
            // a passable spot.
            kv.second = Tile(kv.second.getCharacter(), false);
        }
    }
    
}
Exemple #6
0
/* {{{ solve() solves sudoku, returns true if solved, false if failed
 * algorithm: if not solved seek for last in row, column or box and push it to
 * depth-search stack, add free cells found from checked marked as forbidden and
 * ready to be solved rows, columns and boxes to RCB-stack and use it instead of
 * counters. if not solved after RCB checks, try depth-search , if it fails, 
 * unroll depth-search stack till next valid value for empty space. Failing to
 * unroll and solution counter is 0 means data is bad and there is no solution.
 */
bool solve(Sudoku * sudoku){
  int solution = 0;
  DSStack dsstack;
  dsstack.stackPointer = NULL;
  RCBStack rstack;
  if(sudoku->emptyCells == 0){
    solution = 1;
    cleanPrintSudoku(sudoku);
    return true;
  }
  initRCBStack(&rstack);
  while(true){
    if(RCBsearch(sudoku, &rstack, &dsstack)){
      solution++;
      cleanPrintSudoku(sudoku);
    }
    /* {{{ Depth Search-block start */
    int matrix, row , column;
    if(!findEmpty(sudoku, &matrix, &row, &column)){
      if(!unrollDSStack(sudoku, &matrix, &row , &column, &dsstack)){
        if(!solution) 
          return false; /* no free spaces in sudoku and stack is empty - we got bad data */
        else
          return true;
      }
    }
    fillCellInSudoku(sudoku, matrix, row, column, NULL, stackCellDS, &dsstack);
    if(!sudoku->emptyCells){
      solution++;
      cleanPrintSudoku(sudoku);
    } /* }}} Depth Search-block end*/
  }
} /* }}} */
int solve()
{
    int row, col,num;
    short tdomain[9][9];
    short tcnt[9][9];
    if (!findEmpty(&row, &col))
        return 1;

    int i,j,rowtab,coltab;
    short isok=0;

    for (j=0;j<10;j++)
        if(domain[row][col] & (1<<j))
            isok|=1<<j;

    for (num = 1; num <= 9; num++)
    {
        if (isok & (1<<num))
        {
            memcpy(tdomain,domain,sizeof(domain));
            memcpy(tcnt,cnt,sizeof(cnt));

            block(row,col,num);

            if (solve())
                return 1;

            memcpy(domain,tdomain,sizeof(tdomain));
            memcpy(cnt,tcnt,sizeof(tcnt));
        }
    }
    return 0;
}
Exemple #8
0
/*This function simulate a action on the cache
 *@param cache * c, the cache we using
 *@param cacheParam p, the current state of the cache
 *@param memAddr a, the memory address
 *@return new state of the cache
 */ 
cacheParam rSim(cache* c, cacheParam p, memAddr a, int * state){
  int numLines = p.E;
  int prevHits = p.hit;
  //calculate tag size
  int tagSize = 64 - (p.s + p.b);
  //extract tag
  memAddr input = a >> (p.s + p.b);
  //caculate set Index
  unsigned long long temp = (a << tagSize);
  unsigned long long setIndex = temp  >> (tagSize + p.b); 
  //search for hit cache
  cache_set * set = c -> set;
  cache_set cacheset= set[setIndex];
  int lineIndex; //counter
  block line;
  int isFull = 1;
  for (lineIndex = 0; lineIndex < numLines; lineIndex++){
    line = cacheset.blocks[lineIndex];
    if (line.v){
      if (line.tag == input){
	p.hit++;
	line.lru++;
	cacheset.blocks[lineIndex] = line;
	*state = 0;
      }
    } else if (!(line.v) && (isFull)){
      //set have an empty line
      isFull = 0;
    } 
  }
  if (prevHits == p.hit) {
    //a miss occur
    p.miss++;
    *state = 1;
  } else return p;

  int usedLines = highestLRU(cacheset, p);
  int lruCache = findLRU(cacheset, p);
  //if miss we have to evict a cache or fill a empty cache
  if (isFull){
   
    cacheset.blocks[lruCache].tag = input;
    cacheset.blocks[lruCache].lru = usedLines + 1;
    p.evict++;
    *state = 2;
    
  } else {
    int empty = findEmpty(cacheset, p);
    cacheset.blocks[empty].v = 1;
    cacheset.blocks[empty].tag = input;
    cacheset.blocks[empty].lru = usedLines + 1;
  }


  return p;


}
Exemple #9
0
int Overlays::play(const Common::String &name, int loopId, bool loopForever, bool startNow, int a6) {
	assert(name.size() <= 12);
	if (loopId < 0) {
		warning("Overlays::play - loop id can't be a negative number!");
		return -1;
	}

	int32 hash = MIXArchive::getHash(name);
	int index = findByHash(hash);
	if (index < 0) {
		index = findEmpty();
		if (index < 0) {
			return index;
		}
		_videos[index].loaded = true;
		_videos[index].name = name;
		_videos[index].hash = hash;
		_videos[index].loopId = loopId;
		_videos[index].enqueuedLoopId = -1;
		_videos[index].loopForever = loopForever;
		_videos[index].vqaPlayer = new VQAPlayer(_vm, &_vm->_surfaceFront, Common::String::format("%s.VQA", name.c_str()));

		if (!_videos[index].vqaPlayer) {
			resetSingle(index);
			return -1;
		}
		// TODO? Removed as redundant
		// repeat forever
		//_videos[index].vqaPlayer->setBeginAndEndFrame(0, 0, -1, kLoopSetModeJustStart, nullptr, nullptr);
	}

	bool skipNewVQAPlayerOpen = false;
	if (_videos[index].vqaPlayer
	    && !startNow
	    && _videos[index].vqaPlayer->getFrameCount() > 0
	) {
		skipNewVQAPlayerOpen = true;
		_videos[index].enqueuedLoopId = loopId;
	}

	if (skipNewVQAPlayerOpen || _videos[index].vqaPlayer->open()) {
		_videos[index].vqaPlayer->setLoop(
			loopId,
			loopForever ? -1 : 0,
			startNow ? kLoopSetModeImmediate : kLoopSetModeEnqueue,
			nullptr, nullptr);
	} else {
		resetSingle(index);
		return -1;
	}
	return index;
}
Exemple #10
0
int solveSudoku(int i, int j, int no)
{ 
  int a=i, b=j;
  //if(((searchRow(0,j,no,a)==1) || (searchCol(i,0,no,b)==1) || (searchMat(i/3,j/3,a,b,no)==1)) || (no>9))      
  printf("count= %d ,(%d,%d) = %d\n",count,i,j,no);
  if(no>9)      
    {
      printf("count =%d , (%d,%d) = %d\n",count,i,j,no);
      printf("No Greter than 9 hence backtrack\n");
      *(*(ptr+put[count].xCordinate)+put[count].yCordinate) = 0;
      count -= 1;
      printf("count =%d, (%d,%d) = %d\n",count,i,j,no);
      //*(*(ptr+put[count].xCordinate)+put[count].yCordinate) = 0;
      solveSudoku(put[count].xCordinate,put[count].yCordinate,(put[count].valuePut)+1);
      //count += 1;
      //  return 1;
      findEmpty (put[count].xCordinate,put[count].yCordinate);
      return 1;
    }

  /* if(no>9)
     return 0;*/
  //a=i;
  //b=j;

  if((searchRow(0,j,no,a)==0) && (searchCol(i,0,no,b)==0) && (searchMat(i/3,j/3,a,b,no)==0))      
    {
      *(*(ptr+i)+j)= no;
      put[count].valuePut = no;
      count+=1;
      return 1;
    }
  else
    {
      solveSudoku(i,j,no+1);
      return 1;
    }
  return 1;
}
Exemple #11
0
int main(int argc,char *argv[])
{
  FILE *fp ;
  
  int i,j;
  
  fp=fopen(argv[1],"r");
  
  /*row and column size allocation */
  ptr = (int **)malloc(sizeof(int *)*9);      
  for (i=0;i<9;i++)
    {
      *(ptr+i) = (int *)malloc(sizeof(int)*9);           // col size allocation
    }

  /*scanning and printing Chars in grid */
    for(i=0;i<9;i++)
    {
      // fseek(fp,0,1);
      for(j=0;j<9;j++)
	{
	  fscanf(fp,"%d",*(ptr+i)+j);
          printf("%d\t",*(*(ptr+i)+j));
        	}
       printf("\n");
    }
    findEmpty(0,0);
    for(i=0;i<9;i++)
      {
	for(j=0;j<9;j++)
	  {
	   printf("%d\t",*(*(ptr+i)+j));
	  }
	printf("\n");
      }
    return 0;
}
Exemple #12
0
int* findEmpty(int (&grid)[9][9], int x, int y)
{
//     int* cell = 0;
//
//     for (int i = x + 1; i < 9; i++)
//     {
//         for (int j = y; j < 9; j++)
//         {
//             if (grid[j][i] != 0)
//                 continue;
//             cell = new int[2];
//             cell[0] = j;
//             cell[1] = i;
//             return cell;
//         }
//     }
//
//     for (int i = 0; i <= x; i++)
//     {
//         for (int j = 0; j < 9; j++)
//         {
//             if (i == x && j == y) //Condifitons initiales => boucle finie
//                 return cell;
//
//             if (grid[j][i] != 0)
//                 continue;
//             cell = new int[2];
//             cell[0] = j;
//             cell[1] = i;
//             return cell;
//         }
//     }
//
//     return cell;
    return findEmpty(grid);
}
Exemple #13
0
/* returns the index in the buffer array */
int readPage(Buffer * buf, DiskAddress diskPage) {
   int num, available = 0, toEvict; /* available is set to 1 if there are any unpinned pages */
   long oldest = -1;
   /* check if this file has been opened before in persistent */
   if (checkPersistentFiles(buf, diskPage.FD) == -1) {
      buf->numPersistentFiles += 1;
      buf->persistentFDs = (int *)realloc(buf->persistentFDs, sizeof(int) * buf->numPersistentFiles);
      buf->persistentFDs[buf->numPersistentFiles-1] = diskPage.FD;
   }

   /* buffer check for page */
   for (num = 0; num < buf->nBufferBlocks; num++) {
      if (buf->buffer_timestamp[num] != -1 && buf->pages[num].address.FD == diskPage.FD && buf->pages[num].address.pageId == diskPage.pageId) { /* found page in buffer */
         buf->buffer_timestamp[num] = time(NULL); 
         return num;
      }
   }

   /* if this is reached, then the page is not in the buffer */
   num = findEmpty(buf);
   if (num != -1) {
      /* bring page to buffer */
      tfs_readPage(diskPage.FD, diskPage.pageId, 
                  (unsigned char *)buf->pages[num].block);

      /* sets page metadata */
      buf->pages[num].address = diskPage; 
      buf->buffer_timestamp[num] = time(NULL);         
      
      buf->numBufferOccupied++;
      return num;
   }
   
   /* 
    * Implement LRU eviction.
    * all pageslots are full, check if they're all pinned 
    */
   for (num = 0; num < buf->nBufferBlocks; num++) {
      if(buf->pin[num] == 0) { /* if the page is unpinned */
         if (oldest == -1) { /* initial timestamp */
            oldest = buf->buffer_timestamp[num];
            toEvict = num;
         }
         else if (oldest > buf->buffer_timestamp[num]) { /* found an older time stamp */
            oldest = buf->buffer_timestamp[num];
            toEvict = num;
         }
         available = 1;
      }
   }
   if (available == 0) { /* all the pages are pinned */
      return -1; /* error */
   }
   /* at this point a page needs to be evicted */
   flushPage(buf, buf->pages[toEvict].address);
   /* bring page to buffer */
   tfs_readPage(diskPage.FD, diskPage.pageId, (unsigned char *)buf->pages[toEvict].block);
   /* set other bits*/
   buf->pages[toEvict].address = diskPage;
   buf->buffer_timestamp[toEvict] = time(NULL); 
   
   return toEvict;
}
Exemple #14
0
//Execute par le thread principal (controleur)
int main (int argc, char **argv)
{
    if (argc != 6)
        return EXIT_FAILIURE;

    signal(SIGALRM, sigHandler);

    std::string pathGrilleVide = argv[1];
    std::string pathGrilleSolution = argv[2];
    std::string pathArrivee = argv[3];
    int tempsMax = atoi(argv[4]);
    pathResultat = argv[5];

    int grille[9][9];
    int solution[9][9];

    mainThread = pthread_self();

    loadGrid(pathGrilleVide, grille);
//     printGrid(grille);

    loadGrid(pathGrilleSolution, solution);
// 	printGrid(solution);

    for (int i = 0; i < 5; i++)
    {
        joueurs[i] == 0;
    }

    //creaation des thread joueur par defaut

    joueurs[0] = new Joueur();
    joueurs[1] = new Joueur();
    joueurs[2] = new Joueur();

    joueurs[0]->thread = new pthread_t();
    joueurs[1]->thread = new pthread_t();
    joueurs[2]->thread = new pthread_t();
    int un=1;
    int deux=2;
    int trois=3;
    pthread_create(joueurs[0]->thread, NULL, jouer, &un);
    pthread_create(joueurs[1]->thread, NULL, jouer, &deux);
    pthread_create(joueurs[2]->thread, NULL, jouer, &trois);

    joueurs[0]->tid = 1;
    joueurs[1]->tid = 2;
    joueurs[2]->tid = 3;

    joueurs[0]->etat = "Inconnu";
    joueurs[1]->etat = "Inconnu";
    joueurs[2]->etat = "Inconnu";

    listeJoueurs.insert(std::pair<int, Joueur*>(joueurs[0]->tid, joueurs[0]));
    listeJoueurs.insert(std::pair<int, Joueur*>(joueurs[1]->tid, joueurs[1]));
    listeJoueurs.insert(std::pair<int, Joueur*>(joueurs[2]->tid, joueurs[2]));


    // Creation des deux autres thread
    pthread_t accueil_t;
    pthread_t alarm_t;

    pthread_create(&accueil_t, NULL, accueil, (void*)pathArrivee.c_str());
    pthread_create(&alarm_t, NULL, minuterie, (void*)&tempsMax);

    sem_init(&file1_sem, 0, 0);

    int* empty = findEmpty(grille);
    int col = 0, ln = 0;
    do
    {
        //============================================================
        // BOUCLE POUR TROUVER LES ZERO ET LES ENVOYER DANS LA FILE 1
        if (empty == 0)
            break;


        if (pthread_mutex_trylock(&file1_lock) == 0)
        {
// 	  std::cout<<"je prend le mutex pour le broadcast"<<std::endl;
            if (file1.size() < 4)
            {
                MessageCJ* msg = new MessageCJ();
                msg->colonne = empty[0];
                msg->ligne = empty[1];

                bool duplicate = false;
                std::queue<MessageCJ*> temp;

                while(!file1.empty())
                {

                    temp.push(new MessageCJ((*file1.front())));
                    file1.pop();
                }

                while(!temp.empty())
                {
                    MessageCJ* tmpMsg = new MessageCJ((*temp.front()));
                    file1.push(tmpMsg);
                    temp.pop();
                    if (tmpMsg->colonne == msg->colonne && tmpMsg->ligne == msg->ligne)
                        duplicate = true;

                }

                if (!duplicate)
                {
                    std::list<int> opts = getOptions(grille, msg->colonne, msg->ligne);

                    msg->choiceList = opts;
                    file1.push(msg);
                    pthread_cond_broadcast(&nonEmpty);
// 		      std::cout<<"je broadcast "<<file1.size()<<std::endl;
                    // sem_post(&file1_sem);
                }

                delete empty;

                col = msg->colonne;
                ln = msg->ligne;

            }

            pthread_mutex_unlock( &file1_lock );
// 	    std::cout<<"je rend le mutex pour le broadcast "<<file2.size()<<std::endl;
        }


        //==========================
        //BOUCLE POUR LIRE LA FILE 2

        if(pthread_mutex_trylock(&file2_lock) == 0)
        {
            if (file2.size() > 0)
            {
                _MessageJC* msg = new _MessageJC((*file2.front()));
                file2.pop();
                if (listeJoueurs.find(msg->tid)->second->etat != "Elimine")
                {
//                     std::cout<<"ANS = "<<msg->choice<<" ? "<<solution[msg->colonne][msg->ligne]<<std::endl;
//                     if (msg->choice == 0)
//                         std::cout<<"LE CIEL NOUS TOMBE SUR LA TETE PAR TOUTATIS!!!"<<std::endl;

                    //pthread_cond_broadcast(&nonFullFile2);
                    if (solution[msg->colonne][msg->ligne] == msg->choice)
                    {
                        //If win!
                        grille[msg->colonne][msg->ligne] = msg->choice;
                        Joueur* vainqueur = listeJoueurs.find(msg->tid)->second;
                        vainqueur->score++;
                    }
                    else
                    {
                        //if noob!
                        Joueur* looser = listeJoueurs.find(msg->tid)->second;
                        looser->score--;
                        looser->nbErreur++;
                        if (looser->score <= -10)
                        {

                            eliminateLooser(&listeJoueurs, msg->tid, joueurs);
                            std::cout<<"Better luck next time, NOOB! "<<msg->tid<<std::endl;

                        }

                    }
                }
                pthread_mutex_unlock(&file2_lock);

            }
            else
            {
                pthread_mutex_unlock(&file2_lock);

                sleep(1);
            }
        }


        pthread_mutex_lock(&nouveauJoueurs_lock);
        if (nouveauxJoueurs.size() > 0)
        {
            if (nouveauxJoueurs.front() == 0)
                pthread_cancel(accueil_t);
            else if (playerCount < 5 )
            {


                for (int i = 0; i < 5 && playerCount < 5 && nouveauxJoueurs.size() > 0; i++)
                {
                    if (joueurs[i] == 0)
                    {

                        int id = nouveauxJoueurs.front();
                        if (id == 0)
                            pthread_cancel(accueil_t);
                        else
                        {
                            nouveauxJoueurs.pop();
                            joueurs[i] = listeJoueurs.find(id)->second;
                            playerCount++;
                            joueurs[i]->etat = "Inconnu";
                            pthread_create(joueurs[i]->thread, NULL, jouer, &joueurs[i]->tid);
                        }
                    }
                }
            }
        }
        pthread_mutex_unlock(&nouveauJoueurs_lock);

        empty = findEmpty(grille, col, ln);
        //printGrid(grille);
//         std::cout<<std::endl;
    } while (empty != 0 && nbJoueurActifs() > 0);

    // Si on se rend ici, soit tous les joueurs sont morts, soit on a fini la grille
    int max = 0;
    for (std::map<int, Joueur*>::iterator it = listeJoueurs.begin(); it != listeJoueurs.end(); it++)
    {

        if (it->second->etat == "Inconnu")
        {
            if (it->second->score > max)
                max = it->second->score;
        }
    }

    for (std::map<int, Joueur*>::iterator it = listeJoueurs.begin(); it != listeJoueurs.end(); it++)
    {

        if (it->second->etat == "Inconnu")
        {
            if (it->second->score == max)
                it->second->etat = "Vainqueur";
            else
                it->second->etat = "Perdant";
        }
    }


    pthread_cancel(accueil_t);
    pthread_cancel(alarm_t);

    writeResults();
    dispose();

    return EXIT_SUCCESS;

}