_Bool consulta(int chave, char tipo_colisao) { FILE *f; Registro reg; bool result = false; int i=0, hash; switch (tipo_colisao) { case 'l': f = fopen("files/lisch.dat", "r+b"); break; case 'e': f = fopen("files/eisch.dat", "r+b"); break; } hash = hashing(chave); fseek(f, hash*sizeof(Registro), SEEK_SET); fread(®, sizeof(Registro), 1, f); while ((reg.chave != chave)&&(reg.prox != -1)) { fseek(f, reg.prox*sizeof(Registro), SEEK_SET); fread(®, sizeof(Registro), 1, f); } fclose(f); if (reg.chave == chave) return true; return false; }
rt_table_t *rt_table_find(u_int32_t dest_addr) { rt_table_t *rt_entry; hash_value hash; unsigned int index; /* Calculate index */ index = hashing(&dest_addr, &hash); rt_entry = routing_table[index]; /* Handle collisions: */ while (rt_entry != NULL) { if (rt_entry->hash != hash) { rt_entry = rt_entry->next; continue; } if (memcmp(&dest_addr, &rt_entry->dest_addr, sizeof(u_int32_t)) == 0) return rt_entry; rt_entry = rt_entry->next; } return NULL; }
/** * Returns true if word is in dictionary else false. */ bool check(const char* word) { // copy word in lowercase int l = strlen(word); char* w = malloc(l); for( int i = 0; i < l; i++) w[i] = tolower(word[i]); // add end of string w[l] = '\0'; // hash the word int index = hashing(w); // if NULL its not there if (hashtable[index] == NULL) return false; else { node* cursor = hashtable[index]; while ( cursor->next != NULL) { if (strcmp(w, cursor->word)) return true; else { cursor = cursor->next; } } } return false; }
/** * Leitura de palavras do arquivo * @param arquivo String com as palavras a serem lidas * @param argv nome do arquivo */ void read_words(char arquivo[], char** argv) { int i = 0, j = 0, hash, countPosicao = 0; char caracter, word[MAX]; fprintf(stderr, "conteudo do arquivo: %s\n", argv); do { //fprintf(stderr, "aqui > %c\n", arquivo[33] ); if ((arquivo[i] >= 65) && (arquivo[i] <= 122)) { word[j] = tolower(arquivo[i]); //Transforma todas as letras em minúsculas //fprintf(stderr, "arquivo > %c; word > %c\n", arquivo[i],word[j] ); j++; i++; } else if (j > 0) { word[j] = '\0'; // encerra string countPosicao++; // incrementa a posição de palavra fprintf(stderr, "palavra lida = %s;\n posicao = %d;\n", word, countPosicao); hash = hashing(word); if (insere_palavra(hash, word, argv, countPosicao)) { fprintf(stderr, "Palavra '%s' inserida com sucesso!\n", word); } if (arquivo[i + 1] != '\0' || arquivo[i + 1] != EOF) { j = 0; i++; } } } while (arquivo[i] != '\0'); fprintf(stderr, "fim da função read_words\n"); }
rt_table_t *rt_table_find(u_int32_t dest) { rt_table_t *entry; hash_value hash; unsigned int index; /* Calculate index */ index = hashing(&dest, &hash); entry = routing_table[index]; /* printf("Trying to find %s in table\n", ip_to_str(dest)); */ /* Handle collisions: */ while(entry != NULL) { if(entry->hash != hash) continue; if(memcmp(&dest, &entry->dest, sizeof(u_int32_t)) == 0) return entry; entry = entry->next; } return NULL; }
static void Make_SeedTable(Fasta *fst, int **table_value, unsigned short **table_num){ int i,j; int hashsize = primes((int)(par.blocksize*1.2)); int start, end, num, seedvalue, M_b=idata_b->blocknum[idata_b->cnt]; struct seed *hash = (struct seed *)my_malloc(hashsize * sizeof(struct seed), "hash"); struct seed *seedlist_temp = (struct seed *)my_malloc(par.blocksize * sizeof(struct seed), "seedlist_temp"); for(i=0; i<M_b; i++){ for(j=0; j<hashsize; j++) hash[j].value = -1; start = i*par.blocksize; if(i==M_b-1) end = fst->length - window[par.kmer_ba]; else end = (i+1)*par.blocksize; for(j=start; j<end; j++){ seedvalue = SeedScoring_masked(fst, j, par.kmer_ba); if(seedvalue != -1) hashing(seedvalue, hash, hashsize); } num=0; for(j=0; j<hashsize; j++){ if(hash[j].value != -1) seedlist_temp[num++] = hash[j]; } table_value[i] = (int *)my_malloc((num+1) * sizeof(int), "table_b_value[i]"); table_num[i] = (unsigned short *)my_malloc((num+1) * sizeof(unsigned short), "table_b_num[i]"); for(j=0; j<num; j++){ table_value[i][j] = seedlist_temp[j].value; table_num[i][j] = seedlist_temp[j].num; } table_value[i][num] = -1; /* guard */ } free(seedlist_temp); free(hash); return; }
void rt_table_delete(u_int32_t dest_addr) { rt_table_t *rt_entry, *prev; hash_value hash; unsigned int index; /* Calculate index */ index = hashing(&dest_addr, &hash); for (prev = NULL, rt_entry = routing_table[index]; rt_entry != NULL; prev = rt_entry, rt_entry = rt_entry->next) { if (rt_entry->hash != hash) continue; if (memcmp(&dest_addr, &rt_entry->dest_addr, sizeof(u_int32_t)) == 0) { if (prev == NULL) routing_table[index] = rt_entry->next; else prev->next = rt_entry->next; precursor_list_destroy(rt_entry); if (rt_entry->hcnt != INFTY) k_del_rte(dest_addr, 0, 0); /* Make sure any timers are removed... */ timer_remove(&rt_entry->rt_timer); timer_remove(&rt_entry->hello_timer); timer_remove(&rt_entry->ack_timer); free(rt_entry); return; } } }
int findValue(unsigned int value) { unsigned int position = hashing(value); unsigned int nextPosition = hashing2(value); if (hashMatrix[position] == NULL) { printf("value not found on hash table\n"); return -1; } else if (hashMatrix[position] == value) { printf("value found on hash table\n"); return (position); } else { while(hashMatrix[position] != NULL) { position = (position + nextPosition); if(position >= matrixSize ) { position = (position - matrixSize); } if(hashMatrix[position] == value) { printf("value found on hash table\n"); return (position); } } printf("value not found on hash table\n"); return -1; } }
int main(void) { int i, chave, chavesutilizadas[QTDCHAVES] = {0}, numcolisoes = 0; char listanomes[QTDPESSOAS][TAMNOME]; /*lista com chave e nome*/ char listanumeros[QTDPESSOAS][TAMCEL]; /*lista com chave e numero*/ char aux1[TAMNOME], aux2[TAMCEL]; srand(time(NULL)); for(i=0; i<QTDPESSOAS; i++) { strcpy(aux1, geranome(aux1)); chave = hashing(aux1); if(chavesutilizadas[chave] == 0) { strcpy(listanomes[chave], aux1); chavesutilizadas[chave] = 1; strcpy(listanumeros[chave], geranumero(aux2)); } else { printf("Colisao! Posicionando nome em outra posicao.\n"); chave = QTDCHAVES + numcolisoes; strcpy(listanomes[chave], aux1); if(numcolisoes < 5) numcolisoes++; strcpy(listanumeros[chave], geranumero(aux2)); } } imprimir(listanomes, chavesutilizadas, numcolisoes); /*TODO: solicitar nome e imprimir o mesmo.*/ printf("Por favor, digite o nome desejado: "); scanf("%s", aux1); /*fgets(aux1, TAMNOME+1, stdin);*/ chave = hashing(aux1); if(strncmp(aux1, listanomes[chave], TAMNOME)) printf("O numero de telefone desta pessoa e: %s.\n", listanumeros[chave]); else for(chave=QTDPESSOAS; chave<(QTDPESSOAS+numcolisoes); chave++) { if(strncmp(aux1, listanomes[chave],TAMNOME)) printf("O numero de telefone desta pessoa e: %s.\n", listanumeros[chave]); } return 0; }
//thx thaw <3 std::string bf(void (*hashing)(unsigned char*, unsigned int, unsigned char*), const unsigned char* hash, unsigned int hs, const std::string& charset, unsigned int min, unsigned int max) { std::string result("not found"); unsigned int* idx = new unsigned int[max]; unsigned char* input = new unsigned char[hs]; unsigned char* output = new unsigned char[hs]; unsigned int charset_size = charset.size() - 1; unsigned int size = min; unsigned int i; for(i = 0; i < size; ++i) input[i] = charset[idx[i] = 0]; while(size <= max) { hashing(input, size, output); if(!memcmp(hash, output, hs)) { result = ""; for(i = 0; i < size; ++i) result += charset[idx[i]]; break; } for(i = 0; i < size; ++i) { if(idx[i] == charset_size) { input[i] = charset[idx[i] = 0]; if(i + 1 == size) { i = ++size - 1; input[i] = charset[idx[i] = 0]; break; } } else { input[i] = charset[++idx[i]]; break; } } } delete[] idx; delete[] input; delete[] output; return result; }
//---------------------------------------- // hash table 에 data를 넣는 함수 void insert(int data) { // hash함수를 통해서 저장할 버킷(bucket)의 index를 구한다. int idx = hashing(data); // 해당 버킷의 list에 추가한다. push_front(&hash_table[idx], data); }
void Table::add(const char * key, const Student& aStudent) { int index = hashing(key); Node * newNode = new Node(aStudent); newNode->next = table[index]; table[index] = newNode; size++; }
_Bool inserir(int chave, char *nome, int idade, char tipo_colisao) { FILE *f; Registro reg; bool result; int r, hash; result = consulta(chave, tipo_colisao); if (result) { return false; } else { switch (tipo_colisao) { case 'l': f = fopen("files/lisch.dat", "r+b"); break; case 'e': f = fopen("files/eisch.dat", "r+b"); break; } fseek(f, TAMANHO_ARQUIVO*sizeof(Registro), SEEK_SET); fread(&r, sizeof(int), 1, f); if (r == -1) { return true; } else { hash = hashing(chave); fseek(f, hash*sizeof(Registro), SEEK_SET); fread(®, sizeof(Registro), 1, f); if (reg.marcador) { fclose(f); switch (tipo_colisao) { case 'l': lisch(chave, nome, idade, hash, r); break; case 'e': eisch(chave, nome, idade, hash, r); break; } } else { reg.chave = chave; strcpy(reg.nome, nome); reg.idade = idade; reg.prox = -1; reg.marcador = true; fseek(f, hash*sizeof(Registro), SEEK_SET); fwrite(®, sizeof(Registro), 1, f); fclose(f); } return true; } } }
void insertbyname(vector<knox>& vct1,array<vector<knox>,100>& dic,string &s1,string &s2,string &s3) { knox knoxtemp(s1,s2,s3); int viradress=hashing(s3); dic.at(viradress).push_back(knoxtemp); vct1.push_back(knoxtemp); sort(vct1.begin(),vct1.end(),[](knox &knox1,knox &knox2)->bool{return (knox1.servicenumber<knox2.servicenumber?true:false);}); totnumber++; cout<<"Insertion complete!"<<endl; }
void createdic(vector<knox>& readinvect,array<vector<knox>,100>& dic) { auto iter=readinvect.begin(); int viradress; while(iter!=readinvect.end()) { viradress=hashing((*iter).studentname); dic.at(viradress).push_back(*iter); iter++; } }
int main() { int answ=0,i; char sent[200]; scanf("%[^\n]s",sent); i=strlen(sent); answ=hashing(sent,i); printf("%d",answ); return 0; }
Datum _ltree_compress(PG_FUNCTION_ARGS) { GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0); GISTENTRY *retval = entry; if (entry->leafkey) { /* ltree */ ltree_gist *key; ArrayType *val = DatumGetArrayTypeP(entry->key); int4 len = LTG_HDRSIZE + ASIGLEN; int num = ArrayGetNItems(ARR_NDIM(val), ARR_DIMS(val)); ltree *item = (ltree *) ARR_DATA_PTR(val); if (ARR_NDIM(val) != 1) ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), errmsg("array must be one-dimensional"))); key = (ltree_gist *) palloc(len); key->len = len; key->flag = 0; MemSet(LTG_SIGN(key), 0, ASIGLEN); while (num > 0) { hashing(LTG_SIGN(key), item); num--; item = NEXTVAL(item); } retval = (GISTENTRY *) palloc(sizeof(GISTENTRY)); gistentryinit(*retval, PointerGetDatum(key), entry->rel, entry->page, entry->offset, key->len, FALSE); } else if (!LTG_ISALLTRUE(entry->key)) { int4 i, len; ltree_gist *key; BITVECP sign = LTG_SIGN(DatumGetPointer(entry->key)); ALOOPBYTE( if ((sign[i] & 0xff) != 0xff) PG_RETURN_POINTER(retval); );
int main(){ char str[200]; int i=0; long hashes[3000] = {0}; for(i=0; i<3000 && strcmp(str,"vsmisal") != 0;i++){ scanf("%s",str); hashes[i]=hashing(str); } comparing(hashes,i); return 0; }
/** * Loads dictionary into memory. Returns true if successful else false. */ bool load(const char* dictionary) { // open file FILE* fp = fopen(dictionary, "r"); if (fp == NULL) return false; // temp character to store word char t[LENGTH + 1]; while (fgets(t, sizeof(t), fp)) { // change /n to /0 t[strlen(t) - 1] = '\0'; // creat temp node node* temp = malloc(sizeof(node)); // copy the word to the temp->word strncpy(temp->word, t, LENGTH + 1); // hash the word int index = hashing(t); // if nothing there set it to point to the word if (hashtable[index] == NULL) { hashtable[index] = temp; } // else set temps next to hashtables next and then set hashtable to temp (prepend the word) else { temp->next = hashtable[index]->next; hashtable[index]->next = temp; } words++; } fclose(fp); return true; }
/** * * @param word - palavra a ser buscada * @return ponteiro para palavra buscada ou NULL caso não encontre */ Palavra busca_palavra(char** word) { int hash = hashing(word); NoPalavra* buscada; NoPalavra* p; // Vetor não nulo if (vet[hash].vet != NULL) { buscada = vet[hash].vet; for (p = buscada; p != NULL; p = buscada->proxPalavra) { if (strcmp(buscada->palavra, word) != 0) { return buscada; } } } // Vetor nulo - insere na primeira posição if (vet[hash].vet == NULL) { return NULL; } }
void rt_table_delete(u_int32_t dest) { rt_table_t *entry, *prev; hash_value hash; unsigned int index; /* Calculate index */ index = hashing(&dest, &hash); entry = routing_table[index]; prev = NULL; for(; entry != NULL; prev = entry, entry = entry->next) { if(entry->hash != hash) continue; if(memcmp(&dest, &entry->dest, sizeof(u_int32_t)) == 0) { if(prev == NULL) routing_table[index] = entry->next; else prev = entry->next; total_entries--; precursor_list_destroy(entry); if(!IS_INFTY(entry->hcnt)) { k_del_rte(dest, 0, 0); /* k_del_arp(entry->dest); */ } /* Make sure any timers are removed... */ if(entry->timer_id) timer_remove(entry->timer_id); if(entry->hello_timer_id) timer_remove(entry->hello_timer_id); if(entry->ack_timer_id) timer_remove(entry->ack_timer_id); free(entry); return; } } }
void insertValue(unsigned int value) { unsigned int position = hashing(value); unsigned int nextPosition = hashing2(value); if (hashMatrix[position] == NULL) { hashMatrix[position] = value; } else { while(hashMatrix[position] != NULL) { position = (position + nextPosition); if(position >= matrixSize) { position = (position - matrixSize); } } hashMatrix[position] = value; } }
void main() { int data_arr[] = {0,1,2,3,4,5,6,7,8,9,10,15,23,67,90,112,122,245,687,878}; node *h[HASHVAL] = {NULL}; int x,n,i; char ch; int sch = 0; clrscr(); n = 20; printf("Original Array Data : \n"); for(i=0;i<20;i++) printf("%d ",data_arr[i]); hashing (data_arr,h,n) ; while(!(ch=='n')) { printf("\nEnter the Element for Search : "); fflush(stdin); scanf("%d",&sch); x = hashsear(h,sch); if(x!=-1) printf("Data Found. \n\n ",x); else printf("Data Not Found. "); printf("\nDo You want to continue (y,n)? : "); fflush(stdin); scanf("%c",&ch); } printf("\nPress Any Key to continue...."); getch(); }
float media(char tipo_colisao) { FILE *f; Registro reg, reg_apoio; int i, hash; float acesso, qtd=0, cont=0; switch (tipo_colisao) { case 'l': f = fopen("files/lisch.dat", "r+b"); break; case 'e': f = fopen("files/eisch.dat", "r+b"); break; } for (i = 0; i < TAMANHO_ARQUIVO; i++) { fseek(f, i*sizeof(Registro), SEEK_SET); fread(®, sizeof(Registro), 1, f); if (reg.marcador) { qtd += 1; hash = hashing(reg.chave); fseek(f, hash*sizeof(Registro), SEEK_SET); fread(®_apoio, sizeof(Registro), 1, f); while (reg.chave != reg_apoio.chave) { fseek(f, reg_apoio.prox*sizeof(Registro), SEEK_SET); fread(®_apoio, sizeof(Registro), 1, f); cont += 1; } cont += 1; } } fclose(f); if (qtd >0) { acesso = cont/qtd; return acesso; } return 0; }
void Hash::insert(int x) { if(!contains(x)) { if(isfull()) { int p = x%m_length; std::cout<<"key of "<<x<<" is "<<p<<std::endl; if(table[p]->getvalue()==-1 && p>=0 && p<m_length) { table[p] = new hashnode(x, false); } else { int count = 1; int newkey =p; while(table[newkey]->getvalue()!=-1 && newkey>=0 && newkey<m_length) { newkey = hashing(p,count); std::cout<<"new key of "<<x<<" is "<<newkey<<std::endl; count ++; if(p + count>m_length) { count = count - m_length; } } table[newkey] = new hashnode(x, false); } } else { std::cout<<"rehashing for "<<x<<std::endl; rehash(x); } } }
int main() { FILE *fp; char ifname[50],ofname[50]; big a,b,p,q,x,y,d,r,s,k,hash; epoint *g; long seed; int bits; miracl instance; miracl *mip=&instance; char mem[MR_BIG_RESERVE(11)]; /* reserve space on the stack for 11 bigs */ char mem1[MR_ECP_RESERVE(1)]; /* and one elliptic curve points */ memset(mem,0,MR_BIG_RESERVE(11)); memset(mem1,0,MR_ECP_RESERVE(1)); /* get public data */ #ifndef MR_EDWARDS fp=fopen("common.ecs","rt"); if (fp==NULL) { printf("file common.ecs does not exist\n"); return 0; } fscanf(fp,"%d\n",&bits); #else fp=fopen("edwards.ecs","rt"); if (fp==NULL) { printf("file edwards.ecs does not exist\n"); return 0; } fscanf(fp,"%d\n",&bits); #endif mirsys(mip,bits/4,16); /* Use Hex internally */ a=mirvar_mem(mip,mem,0); b=mirvar_mem(mip,mem,1); p=mirvar_mem(mip,mem,2); q=mirvar_mem(mip,mem,3); x=mirvar_mem(mip,mem,4); y=mirvar_mem(mip,mem,5); d=mirvar_mem(mip,mem,6); r=mirvar_mem(mip,mem,7); s=mirvar_mem(mip,mem,8); k=mirvar_mem(mip,mem,9); hash=mirvar_mem(mip,mem,10); innum(mip,p,fp); /* modulus */ innum(mip,a,fp); /* curve parameters */ innum(mip,b,fp); innum(mip,q,fp); /* order of (x,y) */ innum(mip,x,fp); /* (x,y) point on curve of order q */ innum(mip,y,fp); fclose(fp); /* randomise */ printf("Enter 9 digit random number seed = "); scanf("%ld",&seed); getchar(); irand(mip,seed); ecurve_init(mip,a,b,p,MR_PROJECTIVE); /* initialise curve */ g=epoint_init_mem(mip,mem1,0); epoint_set(mip,x,y,0,g); /* initialise point of order q */ /* calculate r - this can be done offline, and hence amortized to almost nothing */ bigrand(mip,q,k); ecurve_mult(mip,k,g,g); /* see ebrick.c for method to speed this up */ epoint_get(mip,g,r,r); divide(mip,r,q,q); /* get private key of signer */ fp=fopen("private.ecs","rt"); if (fp==NULL) { printf("file private.ecs does not exist\n"); return 0; } innum(mip,d,fp); fclose(fp); /* calculate message digest */ printf("file to be signed = "); gets(ifname); strcpy(ofname,ifname); strip(ofname); strcat(ofname,".ecs"); if ((fp=fopen(ifname,"rb"))==NULL) { printf("Unable to open file %s\n",ifname); return 0; } hashing(mip,fp,hash); fclose(fp); /* calculate s */ xgcd(mip,k,q,k,k,k); mad(mip,d,r,hash,q,q,s); mad(mip,s,k,k,q,q,s); fp=fopen(ofname,"wt"); otnum(mip,r,fp); otnum(mip,s,fp); fclose(fp); memset(mem,0,MR_BIG_RESERVE(11)); memset(mem1,0,MR_ECP_RESERVE(1)); return 0; }
rt_table_t *rt_table_insert(u_int32_t dest, u_int32_t next, u_int8_t hops, u_int32_t seqno, u_int32_t life, u_int16_t flags) { rt_table_t *entry; hash_value hash; unsigned int index; /* Calculate hash key */ index = hashing(&dest, &hash); entry = routing_table[index]; /* printf("rt_table_insert(): Adding dest=%s, nex_hop=%s\n", ip_to_str(dest), ip_to_str(next)); */ #ifdef DEBUG log(LOG_INFO, 0, "rt_table_insert: Inserting %s into bucket %d", ip_to_str(dest), index); if(entry != NULL) log(LOG_INFO, 0, "rt_table_insert: Collision in bucket %s detected!", index); #endif /* Check if we already have an entry for dest */ while(entry != NULL) { if(memcmp(&entry->dest, &dest, sizeof(u_int32_t)) == 0) return NULL; } if((entry = (rt_table_t *)malloc(sizeof(rt_table_t))) == NULL) { fprintf(stderr, "insert_rt_table: Malloc failed!\n"); exit(-1); } entry->dest = dest; entry->next_hop = next; entry->dest_seqno = seqno; entry->expire = get_currtime() + life; entry->flags = flags; entry->hcnt = hops; entry->last_hcnt = 0; entry->last_life = life; entry->precursors = NULL; entry->hash = hash; entry->ack_timer_id = 0; entry->hello_timer_id = 0; /* Insert first in bucket... */ entry->next = routing_table[index]; routing_table[index] = entry; total_entries++; /* We should also update our own sequence number whenever our neighbor set changes. (AODV draft v.8, section 8.4.1.) */ if(hops == 1) this_host->seqno++; /* Add route to kernel routing table ... */ if(dest == next) k_add_rte(dest, 0, 0, hops); else k_add_rte(dest, next, 0, hops); /* flush_rt_cache(); */ #ifdef DEBUG log(LOG_INFO, 0, "rt_table_insert: New timer for %s, life=%d", ip_to_str(entry->dest), life); #endif entry->timer_id = timer_new(life, route_expire_timeout, entry); return entry; }
void Filehash(char read_buffer[] , int *newsockfd) { char write_buffer[1024]; bzero(write_buffer,1024); char v[6]="Verify",c[8]="CheckAll"; int t=0,i; for(i=0;i<6;i++) if(v[i]!=read_buffer[9+i]) t=1; if(t==1) { for(i=0;i<8;i++) if(c[i]!=read_buffer[9+i]) t=2; } if(t==0) { char l1[500],l2[400]; int k=0; i=16; while(i!=strlen(read_buffer)) { l1[k]=read_buffer[i]; k++; i++; } l1[k]='\0'; hashing(l1,newsockfd); bzero(write_buffer,1024); strcpy(write_buffer,"END"); if(write(*newsockfd, write_buffer, 1024) < 0) { error("\nERROR: Writing to socket"); exit(1); } } if(t==1) { system("ls -l |grep -v ^d | awk '{print $9}' | tail -n +2 > fd"); int flag=0; FILE *file = fopen ( "fd", "r" ); if ( file != NULL ) { char line [500]; while ( fgets ( line, sizeof(line), file ) != NULL ) { char te[400]; int k=0; i=0; while(line[i]!='\n') { te[k]=line[i]; k++; i++; } te[k]='\0'; hashing(te,newsockfd); } flag=1; } else error("Error in file opening"); if(flag==1) { bzero(write_buffer, 1024); strcpy(write_buffer,"END"); if(write(*newsockfd, write_buffer, 1024) < 0) { error("\nERROR: Writing to socket"); exit(1); } } system("rm -rf fd"); } }
void SupervisedAlgorithmTest::linearRegressionWithTileFeatures() { // simple sine curve estimation // training samples multimap<double, double> X; for (int i = 0; i < 100; i++) { double x = -M_PI_2 + 2 * M_PI * random->nextReal(); // @@>> input noise? double y = sin(2 * x); // @@>> output noise? X.insert(make_pair(x, y)); } // train int nbInputs = 1; double gridResolution = 8; int memorySize = 512; int nbTilings = 16; Random<double> random; UNH<double> hashing(&random, memorySize); Range<double> inputRange(-M_PI_2, M_PI_2); TileCoderHashing<double> coder(&hashing, nbInputs, gridResolution, nbTilings, true); PVector<double> x(nbInputs); Adaline<double> adaline(coder.dimension(), 0.1 / coder.vectorNorm()); IDBD<double> idbd(coder.dimension(), 0.001); // This value looks good Autostep<double> autostep(coder.dimension()); int traininCounter = 0; ofstream outFileError("visualization/linearRegressionWithTileFeaturesTrainError.dat"); while (++traininCounter < 100) { for (multimap<double, double>::const_iterator iter = X.begin(); iter != X.end(); ++iter) { x[0] = inputRange.toUnit(iter->first); // normalized and unit generalized const Vector<double>* phi = coder.project(&x); adaline.learn(phi, iter->second); idbd.learn(phi, iter->second); autostep.learn(phi, iter->second); } // Calculate the error double mse[3] = { 0 }; for (multimap<double, double>::const_iterator iterMse = X.begin(); iterMse != X.end(); ++iterMse) { x[0] = inputRange.toUnit(iterMse->first); const Vector<double>* phi = coder.project(&x); mse[0] += pow(iterMse->second - adaline.predict(phi), 2) / X.size(); mse[1] += pow(iterMse->second - idbd.predict(phi), 2) / X.size(); mse[2] += pow(iterMse->second - autostep.predict(phi), 2) / X.size(); } if (outFileError.is_open()) outFileError << mse[0] << " " << mse[1] << " " << mse[2] << endl; } outFileError.close(); // output ofstream outFilePrediction("visualization/linearRegressionWithTileFeaturesPrediction.dat"); for (multimap<double, double>::const_iterator iter = X.begin(); iter != X.end(); ++iter) { x[0] = inputRange.toUnit(iter->first); const Vector<double>* phi = coder.project(&x); if (outFilePrediction.is_open()) outFilePrediction << iter->first << " " << iter->second << " " << adaline.predict(phi) << " " << idbd.predict(phi) << " " << autostep.predict(phi) << endl; } outFilePrediction.close(); }
void SupervisedAlgorithmTest::logisticRegressionWithTileFeatures() { // simple sine curve estimation // training samples multimap<double, double> X; double minValue = 0, maxValue = 0; for (int i = 0; i < 50; i++) { double x = random->nextGaussian(0.25, 0.2); // @@>> input noise? double y = 0; // @@>> output noise? X.insert(make_pair(x, y)); if (x < minValue) minValue = x; if (x > maxValue) maxValue = x; } for (int i = 50; i < 100; i++) { double x = random->nextGaussian(0.75, 0.2); // @@>> input noise? double y = 1; // @@>> output noise? X.insert(make_pair(x, y)); if (x < minValue) minValue = x; if (x > maxValue) maxValue = x; } // train int nbInputs = 1; int memorySize = 512; double gridResolution = 10; int nbTilings = 16; PVector<double> x(nbInputs); Random<double> random; UNH<double> hashing(&random, memorySize); Range<double> inputRange(minValue, maxValue); TileCoderHashing<double> coder(&hashing, nbInputs, gridResolution, nbTilings, true); SemiLinearIDBD<double> semiLinearIdbd(coder.dimension(), 0.001 / x.dimension()); // This value looks good int traininCounter = 0; ofstream outFileError("visualization/logisticRegressionWithTileFeaturesTrainError.dat"); while (++traininCounter < 100) { for (multimap<double, double>::const_iterator iter = X.begin(); iter != X.end(); ++iter) { x[0] = inputRange.toUnit(iter->first); // normalized and unit generalized const Vector<double>* phi = coder.project(&x); semiLinearIdbd.learn(phi, iter->second); } // Calculate the error double crossEntropy = 0; for (multimap<double, double>::const_iterator iterCrossEntropy = X.begin(); iterCrossEntropy != X.end(); ++iterCrossEntropy) { x[0] = inputRange.toUnit(iterCrossEntropy->first); const Vector<double>* phi = coder.project(&x); crossEntropy += -iterCrossEntropy->second * log(semiLinearIdbd.predict(phi)) - (1.0 - iterCrossEntropy->second) * log(1.0 - semiLinearIdbd.predict(phi)); } if (outFileError.is_open()) outFileError << crossEntropy << endl; } outFileError.close(); // output ofstream outFilePrediction("visualization/logisticRegressionWithTileFeaturesPrediction.dat"); for (multimap<double, double>::const_iterator iter = X.begin(); iter != X.end(); ++iter) { x[0] = inputRange.toUnit(iter->first); const Vector<double>* phi = coder.project(&x); if (outFilePrediction.is_open()) outFilePrediction << iter->first << " " << iter->second << " " << semiLinearIdbd.predict(phi) << endl; } outFilePrediction.close(); }