int main() { int n,i,j; scanf("%d%d", &n, &k); hashInit(); scanf("%d", A+1); amax=(amin=A[1]); for(i=2; i<=n; i++) { scanf("%d", A+i); if(A[i]>amax) amax=A[i]; if(A[i]<amin) amin=A[i]; } for(j=1; j<k; j++) hashInsert(A[j]); for(i=1; j<n; i++, j++) { hashInsert(A[j]); A[i-1]=findMax(); printf("%d ",findMin()); hashDelete(A[i]); } hashInsert(A[j]); A[i-1]=findMax(); printf("%d\n",findMin()); for(i=0; i<n-k; i++) printf("%d ",A[i]); printf("%d\n",A[i]); scanf("%d", A); return 0; }
void lookUpOrCreateChunkHeaderPage(TupleIdBitmap* tupleIdBitmap, BlockNumber chunkPageNumber) { Bool wasFoundBeforeInsert; PageTableEntry* page = hashInsert(tupleIdBitmap->pageTable, (void*)&chunkPageNumber, &wasFoundBeforeInsert); if (!wasFoundBeforeInsert) { memset(page, 0, sizeof(PageTableEntry)); page->blockNumber = chunkPageNumber; page->isChunk = True; tupleIdBitmap->numberOfEntries++; tupleIdBitmap->numberOfChunks++; } else if (!page->isChunk) { memset(page, 0, sizeof(PageTableEntry)); page->blockNumber = chunkPageNumber; page->isChunk = True; tupleIdBitmap->numberOfPages--; tupleIdBitmap->numberOfChunks++; } }
extern "C" BOOLEAN _using_(char *file) { DLLExportReader reader(file); if (reader.Read()) { std::string rootName = reader.Name(); unsigned npos = rootName.find_last_of(DIR_SEP); if (npos != std::string::npos && npos != rootName.size()-1) { rootName = rootName.substr(npos+1); } char *dllName = (char *)calloc(1, rootName.size() + 1); strcpy(dllName, rootName.c_str()); for (DLLExportReader::iterator it = reader.begin(); it != reader.end(); ++it) { char *name = (char *)calloc(1, (*it)->name.size() + 1); strcpy(name, (*it)->name.c_str()); data *p = (data *)calloc(1, sizeof(data)); p->name = name; p->dllName = dllName; hashInsert(p); } } return TRUE; }
// Inserts the given function from the handle into it's registry void registerEvent( void * handle, const char * eventName, void (*handler)(void* ) ){ Handle * hand = ( Handle * ) handle; HashTable * tab = hand->registry; hashInsert( tab, ( char * )eventName, handler ); }
static HASH_NODE *make_temp(void) { char tempBuffer[128]; static int nextTemp = 0; HASH_NODE *newsymbol = NULL; snprintf(tempBuffer, sizeof(tempBuffer), "__temp%d", nextTemp); ++nextTemp; newsymbol = hashInsert(Table, tempBuffer, SYMBOL_IDENTIFIER); newsymbol->tokentype = TOKEN_TYPE_VAR; return newsymbol; }
static HASH_NODE *make_label(void) { char labelBuffer[128]; static int nextLabel = 0; HASH_NODE *newsymbol = NULL; snprintf(labelBuffer, sizeof(labelBuffer), "__label%d", nextLabel); ++nextLabel; newsymbol = hashInsert(Table, labelBuffer, SYMBOL_LABEL); newsymbol->tokentype = TOKEN_TYPE_LABEL; return newsymbol; }
TAC_NODE* initializeVector(TAC_NODE* initializeList, HASH_NODE* vector, int i){ if(initializeList == NULL){ return initializeList; }else{ char str[25]; sprintf(str,"%d", i); HASH_NODE* index = hashInsert(str, SYMBOL_LIT_INT); return joinTacs(createTacNode(TAC_VECTOR_ASSIGN, vector, index, initializeList->result), initializeVector(initializeList->next, vector, ++i)); } }
int ObjCache::add(void *obj,void **victim) { *victim=0; HashNode *hnode = hashFind(obj); //printf("hnode=%p\n",hnode); if (hnode) // move object to the front of the LRU list, since it is used // most recently { //printf("moveToFront=%d\n",hnode->index); moveToFront(hnode->index); m_hits++; } else // object not in the cache. { void *lruObj=0; if (m_freeCacheNodes!=-1) // cache not full -> add element to the cache { // remove element from free list int index = m_freeCacheNodes; m_freeCacheNodes = m_cache[index].next; // add to head of the list if (m_tail==-1) { m_tail = index; } m_cache[index].prev = -1; m_cache[index].next = m_head; if (m_head!=-1) { m_cache[m_head].prev = index; } m_head = index; m_count++; } else // cache full -> replace element in the cache { //printf("Cache full!\n"); lruObj = m_cache[m_tail].obj; hashRemove(lruObj); moveToFront(m_tail); // m_tail indexes the emptied element, which becomes m_head } //printf("numEntries=%d size=%d\n",m_numEntries,m_size); m_cache[m_head].obj = obj; hnode = hashInsert(obj); hnode->index = m_head; *victim = lruObj; m_misses++; } return m_head; }
/******************************************************************************* * Attempts to insert a Website into a hash table and BST. * * Pre: pList points to a list with a hash table and BST. * pWebsite is initialized. * * Post: The Website has been inserted or destroyed. * * Return: true iff the Website was successfully inserted. ******************************************************************************/ bool listInsert(ListHead *pList, Website *pWebsite) { if(hashInsert(pList, pWebsite)) { bstInsert(pList, pWebsite); return true; } else { websiteFree(pWebsite); return false; } }
//检测链表中是否有回路 //方法一: 使用Hash bool checkHasLoop(struct node *head) { hash h; struct node *current = head; while (current != NULL) { hashInsert(h, current); if (hashExist(h, current->next)) { return true; } current = current->next; } return true; }
void tupleIdBitmapCreatePageTable(TupleIdBitmap* tupleIdBitmap) { int hashTableSize = TupleIdBitmapHashtableStartSize; int hashTableFlags = HashElement | HashBlobs; SHashtableSettings settings; memset(&settings, 0, sizeof(HashtableSettings)); settings.keyLen = sizeof(BlockNumber); settings.valLen = sizeof(PageTableEntry); tupleIdBitmap->pageTable = createHashtable("TupleIdBitmap", hashTableSize, &settings, hashTableFlags); if (tupleIdBitmap->status == TupleIdBitmapOnePage) { Bool hashTableItemFound; PageTableEntry* page = hashInsert(tupleIdBitmap->pageTable, tupleIdBitmap->onePageEntry.blockNumber, &hashTableItemFound); memcpy(page, &tupleIdBitmap->onePageEntry, sizeof(PageTableEntry)); } tupleIdBitmap->status = TupleIdBitmapHash; }
int main(){ /* int i=0; int id; initHashTable(); srand(9999); for(;i<10;i++){ id=(int)((((float)rand())/RAND_MAX)*100000) % 10000; A_hashInsert(id); } printf("id %d position %d\n",id,A_search(id)); printf("9426 is locate in %d.\n",A_search(9426)); */ int i=0,id; HashTable table; HashTableLinkInit(&table); for(;i<10;i++){ id=(int)((((float)rand())/RAND_MAX)*100000) % 10000; hashInsert(&table,id); } printf("%d\n",linkHashSearch(&table,id)->id); //Link node=linkHashSearch(table,id return 1; }
int maxMatch(size_t value, size_t *ptr, size_t n) { /* * c: the current maxMatch's length * r: the last bytes save the match's length * the firsh bytes save the match's index * if the c=5 and the recall=ptr-m=40, so * r=40<<8+5 */ size_t c=0,r=0,*p=hTable[value]; /* * m: the maxMatch's index and the l represent the current * match length * */ size_t i,j,m,l,s; if(*ptr==n||p[0]==0){ r=(size_t)buffer[*ptr]; hashInsert(buffer[*ptr],*ptr); if(*ptr>SLIDEWIN-1) hashDelete(buffer[*ptr-SLIDEWIN],*ptr-SLIDEWIN); (*ptr)++; //return((int)r); }else{ /* * version 1.2 * j=m=hTable[value][1+(rand()%(hTable[value][0]))]; s=*ptr; c=0; while(buffer[j]==buffer[s]){ j++; s++; c++; if(s>=n||c>=((2<<MATCHLEN-1)-1)) break; } */ for(i=1;i<=p[0];i++){ l=0; s=*ptr; j=p[i]; while(buffer[j]==buffer[s]){ j++; s++; l++; if(s>=n||l>=((2<<MATCHLEN-1)-1)) break; } if(l>c){ c=l; m=j-l; } } r=*ptr-m; r=(r<<MATCHLEN)+c; /* * insert the match string with the last one to hash * table and delete * the same length of string from hash table header * */ for(i=0;i<c;i++){ hashInsert(buffer[*ptr],*ptr); if(*ptr>SLIDEWIN-1) hashDelete(buffer[*ptr-SLIDEWIN],*ptr-SLIDEWIN); (*ptr)++; } r=r<<8; } return((int)r); }
Status HashIndex::buildIndex(unsigned chunkType) { if(hashTable == NULL) { string filename; getTempIndexFilename(filename, chunkManager.meta->pid, chunkManager.meta->type, chunkType); hashTable = new MemoryBuffer(HASH_CAPACITY); hashTableSize = hashTable->getSize() / sizeof(unsigned) - 1; hashTableEntries = (ID*)hashTable->getBuffer(); nextHashValue = 0; } const uchar* begin, *limit, *reader; ID x,y; ID startID = 0; unsigned _offset = 0; if(chunkType == 1) { begin = reader = chunkManager.getStartPtr(1); if(chunkManager.getStartPtr(chunkType) == chunkManager.getEndPtr(chunkType)) return OK; x = 0; reader = Chunk::readXId(reader, x); insertFirstValue(x); hashInsert(x, 1); while(startID <= x) startID += HASH_RANGE; reader = Chunk::skipId(reader, 1); limit = chunkManager.getEndPtr(1); while(reader < limit) { x = 0; _offset = reader - begin + 1; reader = Chunk::readXId(reader, x); if(x >= startID) { hashInsert(x, _offset); while(startID <= x) startID += HASH_RANGE; } else if(x == 0) break; reader = Chunk::skipId(reader, 1); } } if(chunkType == 2) { if(chunkManager.getStartPtr(chunkType) == chunkManager.getEndPtr(chunkType)) return OK; begin = reader = chunkManager.getStartPtr(2); x = y = 0; reader = Chunk::readXId(reader, x); reader = Chunk::readYId(reader, y); insertFirstValue(x + y); hashInsert(x + y, 1); while(startID <= x + y) startID += HASH_RANGE; limit = chunkManager.getEndPtr(2); while(reader < limit) { x = y = 0; _offset = reader - begin + 1; reader = Chunk::readXId(reader, x); reader = Chunk::readYId(reader, y); if(x + y >= startID) { hashInsert(x + y, _offset); while(startID <= x + y) startID += HASH_RANGE; } else if( x + y == 0) { break; } } } return OK; }
/* Small FSM. States indicate what the machine is looking for *next*, * so eg _cfgKEYSTART means "looking for the token that indicates the start * of a key" */ struct configFile *_cfgParseConfigFile (struct configFile *cfg) { char *currentSectionString="DEFAULT"; char *currentStringStart=NULL; char *currentKey=NULL; unsigned int filePos=0, state=_cfgKEYSTART; hash_table *tempHash; /* Create the default section. */ tempHash=hashConstructTable (31); hashInsert (currentSectionString, tempHash, cfg->sections); while (filePos < cfg->bbdgSize) { switch (state) { case _cfgKEYSTART: if (cfg->bbdg[filePos]=='[') { filePos++; currentStringStart=(char *) &(cfg->bbdg[filePos]); state=_cfgSECTIONEND; break; } if (isCommentStart(cfg->bbdg[filePos])) { filePos++; state=_cfgCOMMENTEND; break; } if ( !isspace (cfg->bbdg[filePos]) ) { currentStringStart=(char *) &(cfg->bbdg[filePos]); state=_cfgKEYEND; } else { filePos ++; } break; case _cfgCOMMENTEND: if (cfg->bbdg[filePos]=='\n') { state=_cfgKEYSTART; } filePos++; break; case _cfgSECTIONEND: if (cfg->bbdg[filePos]==']') { cfg->bbdg[filePos]='\0'; currentSectionString=currentStringStart; state=_cfgKEYSTART; } filePos++; break; case _cfgKEYEND: if (isspace (cfg->bbdg[filePos]) || isKeyValSep(cfg->bbdg[filePos])) { if (isKeyValSep(cfg->bbdg[filePos])) { cfg->bbdg[filePos]='\0'; } else { cfg->bbdg[filePos]='\0'; filePos++; } currentKey=currentStringStart; state=_cfgCOLON; } else { //Do this in search routine instead (with strcasecmp) //cfg->bbdg[filePos] = tolower(cfg->bbdg[filePos]); filePos++; } break; case _cfgCOLON: if (isKeyValSep(cfg->bbdg[filePos]) || cfg->bbdg[filePos]=='\0') { state=_cfgVALSTART; } filePos++; break; case _cfgVALSTART: if (!myisblank(cfg->bbdg[filePos])) { currentStringStart=(char *) &(cfg->bbdg[filePos]); state=_cfgVALEND; } else { filePos ++; } break; case _cfgVALEND: if (cfg->bbdg[filePos]=='\n' || isCommentStart(cfg->bbdg[filePos])) { /* First see if the current section exists. */ tempHash=hashLookup (currentSectionString, cfg->sections); if (tempHash==NULL) { tempHash=hashConstructTable (31); hashInsert (currentSectionString, tempHash, cfg->sections); } /* Now stick it in the table. */ if (isCommentStart(cfg->bbdg[filePos])) { cfg->bbdg[filePos]='\0'; hashInsert (currentKey, currentStringStart, tempHash); state=_cfgCOMMENTEND; } else { cfg->bbdg[filePos]='\0'; hashInsert (currentKey, currentStringStart, tempHash); state=_cfgKEYSTART; } } filePos++; break; } } return cfg; }
int compress(FILE* inputFile, FILE* outputFile, int compressionLevel) { struct BitwiseBufferedFile* w = openBitwiseBufferedFile(NULL, 1, -1, outputFile); uint8_t readByte[LOCAL_BYTE_BUFFER_LENGTH]; size_t indexLength = INITIAL_INDEX_LENGTH; size_t bufferedBytes; int byteIndex = 0; struct LZ78HashTableEntry* hashTable; uint32_t childIndex = 257; uint32_t lookupIndex = ROOT_INDEX; uint32_t indexLengthMask = (1 << INITIAL_INDEX_LENGTH) - 1; uint32_t child; if((compressionLevel < MIN_COMPRESSION_LEVEL || compressionLevel > MAX_COMPRESSION_LEVEL) || inputFile == NULL || w == NULL) { errno = EINVAL; if(w != NULL) closeBitwiseBufferedFile(w); return -1; } uint32_t hashTableEntries = compressionParameters[compressionLevel - MIN_COMPRESSION_LEVEL].hashTableEntries; uint32_t moduloMask = hashTableEntries - 1; uint32_t maxChild = compressionParameters[compressionLevel - MIN_COMPRESSION_LEVEL].maxChild; hashTable = hashCreate(hashTableEntries, moduloMask); if(hashTable == NULL) { closeBitwiseBufferedFile(w); return -1; } if(writeBitBuffer(w, (uint32_t)compressionLevel, 3) == -1) goto exceptionHandler; while(!feof(inputFile) && !ferror(inputFile)) { bufferedBytes = fread(readByte, 1, LOCAL_BYTE_BUFFER_LENGTH, inputFile); for(byteIndex = 0; byteIndex < bufferedBytes; byteIndex++) { child = hashLookup(hashTable, lookupIndex, readByte[byteIndex], moduloMask); if(child != ROOT_INDEX) lookupIndex = child; //ROOT_INDEX means NOT FOUND else { if(writeBitBuffer(w, lookupIndex, indexLength) == -1 || hashInsert(hashTable, lookupIndex, readByte[byteIndex], childIndex, moduloMask) == -1) goto exceptionHandler; childIndex++; if((childIndex & indexLengthMask) == 0) //A power of 2 is reached { //The length of the transmitted index is incremented indexLength++; //The next power of 2 mask is set indexLengthMask = (indexLengthMask << 1) | 1; } //readByte value is also the right index to start with next time //because you have to start from the last character recognized lookupIndex = readByte[byteIndex] + 1; //ROOT_INDEX = 0 so ASCII characters are indexed in [1, 257] if (childIndex == maxChild) //hash table is full { if(hashReset(hashTable, hashTableEntries, moduloMask) == NULL) goto exceptionHandler; //hash table was not successfully created childIndex = FIRST_CHILD; //starts from the beginning indexLength = INITIAL_INDEX_LENGTH; indexLengthMask = (1 << INITIAL_INDEX_LENGTH) - 1; } } } } if(ferror(inputFile)) { errno = EBADFD; goto exceptionHandler; } if(writeBitBuffer(w, lookupIndex, indexLength) == -1 || writeBitBuffer(w, ROOT_INDEX, indexLength) == -1) goto exceptionHandler; hashDestroy(hashTable, hashTableEntries); return closeBitwiseBufferedFile(w); exceptionHandler: hashDestroy(hashTable, hashTableEntries); closeBitwiseBufferedFile(w); return -1; }
void MainWin::createPages() { DIRRES *dir; QTreeWidgetItem *item, *topItem; m_firstItem = NULL; LockRes(); foreach_res(dir, R_DIRECTOR) { /* Create console tree stacked widget item */ m_currentConsole = new Console(stackedWidget); m_currentConsole->setDirRes(dir); m_currentConsole->readSettings(); /* The top tree item representing the director */ topItem = new QTreeWidgetItem(treeWidget); topItem->setText(0, dir->name()); topItem->setIcon(0, QIcon(":images/server.png")); /* Set background to grey for ease of identification of inactive Director */ QBrush greyBrush(Qt::lightGray); topItem->setBackground(0, greyBrush); m_currentConsole->setDirectorTreeItem(topItem); m_consoleHash.insert(topItem, m_currentConsole); /* Create Tree Widget Item */ item = new QTreeWidgetItem(topItem); item->setText(0, tr("Console")); if (!m_firstItem){ m_firstItem = item; } item->setIcon(0,QIcon(QString::fromUtf8(":images/utilities-terminal.png"))); /* insert the cosole and tree widget item into the hashes */ hashInsert(item, m_currentConsole); /* Set Color of treeWidgetItem for the console * It will be set to green in the console class if the connection is made. */ QBrush redBrush(Qt::red); item->setForeground(0, redBrush); m_currentConsole->dockPage(); /* * Create instances in alphabetic order of the rest * of the classes that will by default exist under each Director. */ // new bRestore(); new Clients(); new FileSet(); new Jobs(); createPageJobList("", "", "", "", NULL); #ifdef HAVE_QWT JobPlotPass pass; pass.use = false; if (m_openPlot) new JobPlot(NULL, pass); #endif new MediaList(); new Storage(); if (m_openBrowser) new restoreTree(); if (m_openDirStat) new DirStat(); treeWidget->expandItem(topItem); stackedWidget->setCurrentWidget(m_currentConsole); }
int main() { printf("Hello\n"); printf("Enter a command followed by a number between 0 and 999 inclusive to perform operation on hash table\n"); printf("Valid commands are: insert #, delete #, search #, list #.\n"); printf("Enter searchlist to print entire table\n"); printf("Enter term to print table and exit .\n"); Hashtable * newTable = makeTable(10); char * regex = " \n"; char str [100]; while(1) { printf("Enter: "); char * result = fgets(str, 100, stdin); char * token1 = strtok(result, regex); char * token2 = strtok(NULL, regex); long long val; if(token2 != NULL) { char * end_ptr = 0; val = strtoll(token2,&end_ptr,10); if((end_ptr != 0 && *end_ptr != '\n' && *end_ptr != '\0') || overflow(val)){ printf("Error: invalid input. %s is outside valid range (0 - 999)\n", token2); continue; } } if(token1 == NULL) { printf("Error: invalid input. \n"); continue; } else if(strcasecmp(token1,"searchlist") == 0) { hashListFull(newTable); } else if(strcasecmp(token1, "term") == 0) { hashListFull(newTable); term(newTable); printf("You've been terminated\n"); break; } else if(strcasecmp(token1,"insert") == 0) { if(token2 == NULL) { printf("Error: No number listed\n"); continue; } if(hashInsert(val,newTable)) { printf("True \n"); } else { printf("False \n"); } }else if(strcasecmp(token1,"search") == 0) { if(token2 == NULL) { printf("Error: No number listed\n"); continue; } if(search(val,newTable)) { printf("True\n"); } else { printf("False\n"); } }else if(strcasecmp(token1,"delete") == 0){ if(token2 == NULL) { printf("Error: No number listed\n"); continue; } if(hashDelete(val,newTable)) { printf("True \n"); } else { printf("False\n"); } }else if(strcasecmp(token1, "list") == 0) { if(token2 == NULL) { printf("Error: No index listed\n"); continue; } if(isNull(hash(val),newTable)) { printf("False\n"); }else { printf("List #%i :", hash(val)); hashList(hash(val),newTable); printf("\n"); } }else{ printf("Error: invalid input. %s is not recognized keyword: insert, search,list,delete\n", token1); continue; } } return 0; }