language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* * 08-a-02.c * * Created on: 2018/06/05 * Author: ub301144 */ #include <stdio.h> #include <stdlib.h> int main() { int a[5][5]; int i,j; for(i=0;i<5;i++){ for(j=0;j<5;j++){ if(i==j){ a[i][j]=1; }else{ a[i][j]=0; } } } for(i=0;i<5;i++){ for(j=0;j<5;j++){ printf("%d",a[i][j]); }printf("\n"); } return 0; }
C
/*!**************************************************************************** * @file * sensorlib_bme280.c * * Ansteuerung fr den Wettersensor BME280 von Bosch Sensortec * * @date 28.10.2019 * @date 31.10.2019 Update-Routine, Strukturtyp fr Sensordaten ******************************************************************************/ /*- Headerdateien ------------------------------------------------------------*/ #include "commlib_i2c.h" #include "sensorlib_bme280_internal.h" #include "sensorlib_bme280.h" /*!**************************************************************************** * @brief * Sensor initialisieren * * @param[inout] *pSensor Zeiger auf Sensor-Struct * @param[in] ucSlaveAddr I2C Slave-Adresse des Sensors (default 0x76) * * @date 28.10.2019 * @date 31.10.2019 Funktionalitt ausgelagert in _internal-Modul ******************************************************************************/ void BME280_Init(BME280_Sensor* pSensor, uint8_t ucSlaveAddr) { uint8_t ucIndex; /* Struktur initialisieren */ for (ucIndex = 0; ucIndex < sizeof(*pSensor); ++ucIndex) { *((uint8_t*)pSensor + ucIndex) = 0; } /* I2C Slave-Adresse abspeichern */ pSensor->ucSlaveAddr = ucSlaveAddr; /* Sensor initialisieren und Kalibrierungswerte lesen */ BME280_SoftReset(pSensor); BME280_GetCalData(pSensor); } /*!**************************************************************************** * @brief * Sensordaten abrufen und Rohdaten kompensieren * * @param[inout] *pSensor Sensor-Struktur * * @date 31.10.2019 ******************************************************************************/ void BME280_Update(BME280_Sensor* pSensor) { /* Sensor aus dem Sleep-Mode aufwecken und einzelne * * Aufzeichnung der drei Messwerte starten */ BME280_SetMode(pSensor, BME280_Mode_SLEEP); BME280_SetOversamp(pSensor, BME280_Oversampling_1, BME280_Oversampling_1, BME280_Oversampling_1); BME280_SetMode(pSensor, BME280_Mode_FORCED); /* Auf Abschluss der Umsetzung warten */ while (BME280_IsMeasuring(pSensor)); /* Sensordaten auslesen und kompensierte Werte ber. */ BME280_GetSensorData(pSensor); pSensor->sMeasure.iTemperature = BME280_CalcTemp(pSensor); pSensor->sMeasure.ulPressure = BME280_CalcPress(pSensor); pSensor->sMeasure.ulHumidity = BME280_CalcHum(pSensor); }
C
/** * Sistemas Operativos * Módulo 2, Sesión 6, Ejercicio 4 * Francisco Domínguez Lorente */ #include <sys/types.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/wait.h> int main() { struct flock cerrojo; int fd; cerrojo.l_type = F_WRLCK; cerrojo.l_whence = SEEK_SET; cerrojo.l_start = 0; cerrojo.l_len = 0; if((fd = open("prueba.txt", O_RDWR | O_TRUNC)) == -1) { printf("\nError en el open"); perror("\nError en el open"); exit(EXIT_FAILURE); } int filecontrol = fcntl(fd, F_SETLK, &cerrojo); if(filecontrol == EDEADLK || filecontrol == -1) { printf("El programa ya se está ejecutando en otra instancia\n"); exit(EXIT_FAILURE); } else { if(write(fd, "He escrito", 5) != 5) { printf("\nError en write"); perror("\nError en write"); exit(EXIT_FAILURE); } while(1){}; } return EXIT_SUCCESS; }
C
#include "folder.h" #include "stdlib.h" #include <stdio.h> int main(int argc, char const *argv[]) { const char *nameData; const char *nameResult; #ifdef TEST nameData = "/home/clement/Workspace/VsCodeProject/ESISAR_CS/3A/CS351/ESISAR_CS351_TP4/Exercice1/data/donnee.txt"; nameResult = "/home/clement/Workspace/VsCodeProject/ESISAR_CS/3A/CS351/ESISAR_CS351_TP4/Exercice1/data/resultat.txt"; #else if (argc == 3) { nameData = argv[1]; nameResult = argv[2]; } else { fprintf(stderr, "ERROR ARGUMENTS MISSING\n"); exit(0); } #endif int T[1000]; int nbValue; nbValue = lireDonnee(nameData, T); afficherTableau(T, nbValue); triABulle(T, nbValue); afficherTableau(T, nbValue); enregistrerDonnees(nameResult, T, nbValue); return 0; }
C
// exe ϰ // exercise, meditate, respirate ۺϣ // ĿǼҼ䷱----- Silencer @ fy4 #include <skill.h> inherit F_CLEAN_UP; string *add = ({ "qi", "jing", "shen" }); mapping *type = ({ ([ "add": "force", "add_c": "", "cost": "kee", "cost_c": "Ѫ", "skill": "force", "u_msg": "ùһϢʼ\n", "l_msg": "ǵйϣֻȫ顣\n", "f_msg": "Ϣ鲼ȫʱȴûйļƺΪѾƿ\n", ]), ([ "add": "atman", "add_c": "", "cost": "gin", "cost_c": "", "skill": "magic", "u_msg": "ϥ۾ʼ˼\n", "l_msg": "һСȴ˯ˡ\n", "f_msg": "һתͷǵҪѿһƺѾƿ\n", ]), ([ "add": "mana", "add_c": "", "cost": "sen", "cost_c": "", "skill": "spells", "u_msg": "ϥڤ˼һ\n", "l_msg": "ǵ۾ֻһƬհס\n", "f_msg": "ȻһƬңƺѾƿ\n", ]), }); int main(object me, string arg) { int kee_cost=30; int n, amount, gain , i; string add_1, h_cost, h_gain; seteuid(getuid()); if(environment(me)->query("no_fight")) return notify_fail("㲻\n"); if( me->is_fighting() ) return notify_fail("սв߻ħ\n"); if( me->is_busy() ) return notify_fail("һûɣ\n"); if (!arg || sscanf(arg, "%s %d", add_1, amount) != 2) return notify_fail("ָʽexercise <jing/qi/shen> <Ŀ> \n"); n = member_array(add_1, add); if ( n == -1) return notify_fail("ʽexercise <jing/qi/shen> <Ŀ> \n"); if (amount < 10) return notify_fail(type[n]["add_c"]+"Ҫķ10"+ type[n]["cost_c"]+ "\n"); // write ("add_1 is "+ type[n]["cost"] + " amount is "+ amount +"\n"); h_cost = type[n]["cost"]; h_gain = type[n]["add"]; if( me->query(h_cost) < amount ) return notify_fail("ڵ"+ type[n]["cost_c"]+ "̫ˣ޷ϰ\n"); if (me->query("death_revive")+ 180 > time()) return notify_fail("ڵ״޷\n"); for (i=0;i<sizeof(type); i++) { if (i == n) continue; if ( me->query( type[i]["cost"]) * 100 / me->query ("max_"+ type[i]["cost"]) < 70 ) return notify_fail("״̫ˣ޷" + type[i]["cost_c"] + "ֵ70%ϣ\n"); } write(type[n]["u_msg"]); me->add(h_cost, -amount); me->start_busy(1); // (500/10 + 40 )/30 = 3 , (3 + random (3))/ 5= 60% - 120% Ч maxium at enable= 500, att = 40 gain = me->query_skill(type[n]["skill"]) /10; switch (h_cost) { case "kee": gain = amount * (gain + me->query_con()) / 30; break; case "sen": gain = amount * (gain + me->query_spi()) / 30; break; case "gin": gain = amount * (gain + me->query_int()) / 30; break; default: write(" 㷢һ棬ʦ\n"); return 1; } gain = (gain + random(gain))/5; if( gain < 1 ) { write(type[n]["l_msg"]); return 1; } // write ("amount is "+ amount + " gain is "+ gain + "\n"); me->add( h_gain, gain ); if( me->query(h_gain) > me->query("max_" + h_gain) * 2) { if( me->query("max_" + h_gain) >= ( me->query_skill( type[n]["skill"], 1) + me->query_skill(type[n]["skill"])/5 ) * 5 ) { write(type[n]["f_msg"]); me->set(h_gain, 2 * me->query("max_" + h_gain)); } else { write(""+ type[n]["add_c"] + "ǿˣ\n"); me->add("max_" + h_gain, 1); me->set(h_gain, me->query("max_"+h_gain )); } } me->status_msg("all"); me->force_status_msg("all"); return 1; } int help(object me) { write(@HELP  ָʽ : exercise <jing|qi|shen> <>  2005еָڰ汾мĽԭexercise meditaterespirateۺΪͬһּ䡣 ָIJֱ֣ͬ exercise jing <> Уá 项ķľת exercise qi <> ڵڸ ѵ弡 ʽ exercise shen <> ڤ˼ľЧؼ ۳ܹʩչ Լ õֵ == ڹȼ*5 + ǰЧڹȼ :ڹķ (force) -ɲ 200 ڹ (force) 繦 Чȼ295 ֵ = 200*5 + 295 = 1295 ƽתЧʣ Чڹȼʣ ļȫͬ ָ ָ ָ ָ  HELP ); return 1; }
C
// Vector.h // Visualização 3D // W. Celes - celes@inf.puc-rio.br // PUC-Rio, Jan 2008 // Class provided by Prof. Waldemar Celes for Vector manipulation. #ifndef V_VECTOR_H #define V_VECTOR_H #include <stdio.h> #include <math.h> struct VVector { float x, y, z; VVector () { } VVector (float vx, float vy, float vz) : x(vx), y(vy), z(vz) { } void Set (float vx, float vy, float vz) { x = vx; y = vy; z = vz; } float SqrLength () const { return (x*x+y*y+z*z); } float Length () const { return (float)sqrt(x*x+y*y+z*z); } float Normalize () { float l = Length(); if (l != 0.0f) { float d = 1.0f/l; x *= d; y *= d; z *= d; } return l; } void invert() { x = -x; y = -y; z = -z; } VVector& operator+= (const VVector& other) { x += other.x; y += other.y; z += other.z; return *this; } VVector& operator+= (float scalar) { x += scalar; y += scalar; z += scalar; return *this; } VVector& operator-= (const VVector& other) { x -= other.x; y -= other.y; z -= other.z; return *this; } VVector& operator-= (float scalar) { x -= scalar; y -= scalar; z -= scalar; return *this; } VVector operator- () { VVector v(-x,-y,-z); return v; } VVector& operator*= (const VVector& other) { x *= other.x; y *= other.y; z *= other.z; return *this; } VVector& operator*= (float scalar) { x *= scalar; y *= scalar; z *= scalar; return *this; } VVector& operator/= (float scalar) { x /= scalar; y /= scalar; z /= scalar; return *this; } friend float Dot (const VVector& a, const VVector& b) { return a.x*b.x + a.y*b.y + a.z*b.z; } friend VVector Cross (const VVector& a, const VVector& b) { return VVector(a.y*b.z-b.y*a.z,b.x*a.z-a.x*b.z,a.x*b.y-b.x*a.y); } void Print (const char* label=0) const { printf("%s: %g %g %g\n", label ? label : "", x, y, z); } }; #endif
C
/* Rosa María Ramírez Moreno A01700857 22-01-18 */ #include <stdio.h> #include "operations.h" void printTestMesssage(int, char *, char *); int testAddition(void); int testSubstraction(void); int main(){ //Test add printTestMesssage(testAddition(), " add test 1 passed", " add test 1 failed \n"); //Test substraction printTestMesssage(testSubstraction(), " substraction test 2 passed ", " substraction test 2 failed "); return 0; } void printTestMesssage(int condition, char *messagePassed, char *messageFailed){ if(condition){ printf("%s \n", messagePassed); }else{ printf("%s \n", messageFailed); } } int testAddition(void){ int a = 5; int b = 7; int result = add(a, b); int expected = a + b; return result == expected; } int testSubstraction(void){ int c = 2; int d = 1; int result2 = substraction(c, d); int expected2 = c - d; return result2 == expected2; }
C
#include<stdio.h> char string[]={"acbca"}; int length(char string[]) { int i=0; while(string[i] != '\0') { i++; } return i; } void pallendrom(char string[]) { int i,j,k=0; for(i=0,j=length(string)-1;i<length(string)/2+1,j>length(string)/2-1;i++,j--) { if (string[i] == string[j]) { printf("%c %c %d %d\n",string[i],string[j],i,j); k=k+1; } } if(length(string)%2==0) { if(k == length(string)/2) { printf("string is pallendrom\n"); } else printf("string is not pallendrom\n"); } else { if(k == length(string)/2+1) { printf("string is pallendrom\n"); } else printf("string is not pallendrom\n"); } } void main() { /* int i; char string[10]; printf("please inter string\n"); for(i=0;i<length(string);i++) { scanf("%c",&string[i]); } printf("your string is \n"); for(i=0;i<length(string);i++) { printf("%c",string[i]); } printf("\n"); */ printf(" %d\n ",length(string)); pallendrom(string); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* sorted_delete.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lgarczyn <lgarczyn@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/09/13 22:02:52 by lgarczyn #+# #+# */ /* Updated: 2018/11/06 00:06:13 by lgarczyn ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" #include "sorted_int.h" int sorted_delete_index(t_sorted *a, size_t index, void *out) { size_t new_pos; size_t prev_len; size_t next_len; void *array_data; if (index >= a->pos) return (ERR_SIZE); new_pos = a->pos - a->word; prev_len = index * a->word; next_len = new_pos - prev_len; array_data = a->data + prev_len; if (out) ft_memcpy(out, array_data, a->word); if (next_len) ft_memmove(array_data, array_data + a->word, next_len); if (a->pos <= a->size / 4) ft_realloc_down(&a->data, a->pos, &a->size); a->pos = new_pos; return (OK); } t_sorteden sorted_delete(t_sorted *a, const void *data, void *out) { t_sorteden res; res = sorted_search(a, data); if (res.found) { sorted_delete_index(a, res.index, out); } return (res); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* env_handler.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mpytienk <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/02/12 13:15:08 by mpytienk #+# #+# */ /* Updated: 2018/02/12 13:15:11 by mpytienk ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/minishell.h" int get_env_pos(char **env, char *str) { int i; int k; i = 0; while (env[i]) { k = 0; while (env[i][k] == str[k]) { k++; if (env[i][k] == '=') return (i); } i++; } return (-1); } char *env_get_name(char *str) { int tmp; char *tmpc; tmp = 0; tmpc = ft_strnew(ft_strlen(str)); while (str[tmp] != '=') tmp++; ft_strncpy(tmpc, str, tmp); return (tmpc); } char *env_trim(char *str) { char *tmp; while (*str != '=') str++; str++; tmp = ft_strdup(str); return (tmp); } char *env_combine(char *s1, char *s2) { char *tmp; char *tmp2; tmp = ft_strjoin(s1, "="); tmp2 = ft_strjoin(tmp, s2); ft_strdel(&tmp); return (tmp2); } void env_replace(char **env, char *s1, char *s2) { char *tmp; char *tmp2; int i; tmp = env_combine(s1, s2); if ((i = get_env_pos(env, s1)) != -1) { tmp2 = env[i]; env[i] = tmp; ft_strdel(&tmp2); } else ft_strdel(&tmp); }
C
/* Algoritmo de Self-Organizing Map por Teuvo Kohonen (1984) Implementado por Geraldo Rabelo geraldo.rabelo@gmail.com em 24/08/2017 Como SOM funciona? As entradas (input.dat) representam um conjunto de padrões a ser reconhecido pela rede após seu treino. Treino Passo a Passo: 0 - Iniciar todos os neuronios da rede com pesos aleatórios; 1 - Pegar uma entrada por vez; 2 - Verificar cada neuronio da rede em busca daquele que mais se aproxime da entrada selecionada no passo 1; 3 - Após encontrar um neuronio vencedor, contaminar sua vizinhança fazendo-a tender à sua cor; 4 - voltar ao passo 1 Obs.: O parametro TAXA DE APRENDIZADO garante que apenas uma fração da distancia entre as cores do neuronio selecionado e o neuronio vencedor será aplicada à vizinhança deste, em menor grau a pedida que aumenta sua distancia posicional. O parametro RAIO deve iniciar com valor alto (largura da base) e ser gradualmente decrementado (até 1). O parametro EPOCAS deve ser escolhido de acordo com a area da rede. Uso: Após o treino, a rede deverá ser capaz de sinalizar se uma dada entrada possui ou não classe correspondente. Compilando: gcc -o KN2D KN2D.c -lm */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <time.h> #include <ctype.h> #define CONFIG "config.dat" #define INPUT "input.dat" #define OUTPUT "output.dat" #define OUTPUT_HTML "output.html" #define START "start.dat" #define START_HTML "start.html" #define STYLE "styles.css" struct neuronio { int *pesos; int *posicao; float saida; } dot; typedef struct neuronio Neuronio; struct entrada { int *pesos; } in; typedef struct entrada Entrada; int winnerWeightDistance; int winnerIndex; float distanciaEuclidiana = 0.0; float LEARNING_RATE = 0; int NEIGHBOURHOOD_RADIUS = 0; int NUMBER_OF_INPUTS = 0; int NUMBER_OF_NEURONS = 0; int INPUT_DIMENSION = 0; int EPOCHS = 0; int COORDINATES_DIMENSION = 0; int epoch = 0; int distancia_do_peso = 0; int neuronios_por_linha = 0; Entrada *entradas = NULL; Neuronio *neuronios = NULL; int testa_se_arquivo_existe(char *nome_do_arquivo) { int result = 1; FILE *arquivo = NULL; arquivo = fopen(nome_do_arquivo,"r"); if (arquivo == NULL) { result = 0; } return result; } void load_cfg_from_file(FILE *arquivo) { int linhaContador = 0; char valor[8]; char linha[32]; memset(linha,'\0',32); memset(valor,'\0',8); rewind(arquivo); while (!feof(arquivo)) { fgets(linha,32,arquivo); for (int contador = 0; contador < strlen(linha); contador++) { if (linha[contador] == ':') { for (int contadorValorCaracteres = contador+1; contadorValorCaracteres < strlen(linha); contadorValorCaracteres++) { valor[contadorValorCaracteres-contador-1] = linha[contadorValorCaracteres]; } switch(linhaContador) { case 0: EPOCHS = atoi(valor); break; case 1: LEARNING_RATE = atof(valor); break; case 2: NEIGHBOURHOOD_RADIUS = atoi(valor); break; case 3: NUMBER_OF_INPUTS = atoi(valor); break; case 4: INPUT_DIMENSION = atoi(valor); break; case 5: NUMBER_OF_NEURONS = atoi(valor); break; case 6: COORDINATES_DIMENSION = atoi(valor); break; } } } memset(linha,'\0',32); memset(valor,'\0',8); linhaContador++; } } int getLinhasArquivo(FILE *arquivo) { int resultado = 0; char caractere; rewind(arquivo); while (!feof(arquivo)) { caractere = fgetc(arquivo); if(caractere == '\n') { resultado++; } } return resultado; } char *substring (char *linha, int inicio, int fim) { char *resultado = (char *) malloc(strlen(linha)*sizeof(char)); for (int contador = inicio; contador<fim; contador++) { resultado[contador-inicio] = linha[contador]; } return resultado; } void load_inputs(FILE *file_input) { int linhaContador = 0; int entradaContador = 0; int inicioValor = 0; int valor = 0; char linha[14]; entradas = malloc(NUMBER_OF_INPUTS*sizeof(Entrada)); for (int c0 = 0; c0 < NUMBER_OF_INPUTS; c0++) { entradas[c0].pesos = (int *) malloc(INPUT_DIMENSION*sizeof(int)); } rewind(file_input); while (!feof(file_input)) { memset(linha,'\0',14); fgets(linha,14,file_input); entradaContador = 0; inicioValor = 0; //printf("\nLinha %d; %d caracteres; %s",linhaContador,strlen(linha),linha); for (int contador = 0; contador < strlen(linha)-1; contador++) { if (linha[contador] == ';') { valor = atoi(substring(linha,inicioValor,contador)); entradas[linhaContador].pesos[entradaContador] = valor; inicioValor = contador+1; entradaContador++; } } linhaContador++; if (linhaContador == NUMBER_OF_INPUTS) break; } } void load_start(FILE *file_start) { int linhaContador = 0; int entradaContador = 0; int inicioValor = 0; int neuronio_coluna = 0; int neuronio_linha = 0; int neuronios_por_linha = sqrt(NUMBER_OF_NEURONS); int valor = 0; char linha[14]; rewind(file_start); while (!feof(file_start)) { memset(linha,'\0',14); fgets(linha,14,file_start); entradaContador = 0; // de 1 a 3 inicioValor = 0; if (neuronio_linha == neuronios_por_linha) { neuronio_linha = 0; neuronio_coluna++; } neuronios[linhaContador].posicao[0] = neuronio_linha; neuronios[linhaContador].posicao[1] = neuronio_coluna; neuronio_linha++; //printf("\n%s",linha); for (int contador = 0; contador < strlen(linha); contador++) { if (linha[contador] == ';') { valor = atoi(substring(linha,inicioValor,contador)); //printf("\n%d valor: %d; linha: %d; coluna: %d, %s",linhaContador,valor,neuronio_linha-1,neuronio_coluna,linha); neuronios[linhaContador].pesos[entradaContador] = valor; inicioValor = contador+1; entradaContador++; } } linhaContador++; if (linhaContador == NUMBER_OF_NEURONS) break; } } void criar_rede_em_arquivo_dat(FILE *file_start) { int neuronios_por_linha = sqrt(NUMBER_OF_NEURONS); int neuronios_por_coluna = neuronios_por_linha; int contador_linha = 0; int contador_coluna = 0; neuronios = malloc(NUMBER_OF_NEURONS*sizeof(Neuronio)); for (int c=0; c < NUMBER_OF_NEURONS; c++) { neuronios[c].pesos = (int *) malloc(INPUT_DIMENSION*sizeof(int)); for (int c0 = 0;c0 < INPUT_DIMENSION;c0++) { /* Inicializando pesos */ neuronios[c].pesos[c0] = (rand() % 255); fprintf(file_start,"%d;",neuronios[c].pesos[c0]); } fprintf(file_start,"\n"); neuronios[c].posicao = (int *) malloc(COORDINATES_DIMENSION*sizeof(int)); neuronios[c].posicao[0] = contador_linha; neuronios[c].posicao[1] = contador_coluna; contador_linha++; if (contador_linha == neuronios_por_linha) { contador_coluna++; contador_linha = 0; } } } void criar_arquivo_css() { FILE *file_css = NULL; file_css = fopen(STYLE,"w+"); if (file_css == NULL) { printf("\nSTYLE.CSS not found."); } else { fprintf(file_css,"table,tr,td {\n\tborder: none;\n\tborder-collapse: none;\n\tborder-spacing: 0px;\n}\n\n.cell {\n\tfont-style: normal;\n\tfont-size: 5px;\n\tfont-weight: 700;\n\tfont-family: Helvetica, Arial, Sans-serif;\n\ttext-align: center;\n\tmargin: 0;\n\tpadding: 0;\n}"); } } void imprimir_rede_em_arquivo_html(FILE *arquivo) { int neuronios_por_linha = sqrt(NUMBER_OF_NEURONS); fprintf(arquivo,"<html><head><link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\" /></head><body><table class=\"cell\"><tr>"); for (int c0=0; c0 < NUMBER_OF_NEURONS; c0++) { if (c0 % neuronios_por_linha == 0 && c0 > 0) { fprintf(arquivo,"</td></tr><tr><td>"); } else { fprintf(arquivo,"<td>"); } fprintf(arquivo,"<div style=\"background-color: rgb("); for (int c1=0; c1 < INPUT_DIMENSION; c1++) { if (c1 == INPUT_DIMENSION-1) { fprintf(arquivo,"%d);",neuronios[c0].pesos[c1]); } else { fprintf(arquivo,"%d,",neuronios[c0].pesos[c1]); } } fprintf(arquivo,"\">&nbsp;&nbsp;"); /* fprintf(arquivo,"%d<br>(%d,%d)<br>(",c0,neuronios[c0].posicao[0],neuronios[c0].posicao[1]); for (int c1=0; c1 < INPUT_DIMENSION; c1++) { if (c1 == INPUT_DIMENSION-1) { fprintf(arquivo,"%d);",neuronios[c0].pesos[c1]); } else { fprintf(arquivo,"%d,",neuronios[c0].pesos[c1]); } } */ // fprintf(arquivo,"&nbsp;"); fprintf(arquivo,"</div></td>"); } fprintf(arquivo,"</table></body></html>"); } void imprimir_rede_na_tela() { printf("\n\n"); printf("numero de neuronios: %d\ndimensao: %d",NUMBER_OF_NEURONS, INPUT_DIMENSION); for (int c0=0; c0 < NUMBER_OF_NEURONS; c0++) { printf("\nNeuronio %d",c0); for (int c1=0; c1 < INPUT_DIMENSION; c1++) { printf("\n\tpeso %d: ",c1); //for (int c2; c2 < INPUT_DIMENSION; c2++) { printf("%d ",neuronios[c0].pesos[c1]); //} } for (int c2=0; c2 < COORDINATES_DIMENSION; c2++) { printf("\n\tposicao %d: ",c2); //for (int c2; c2 < INPUT_DIMENSION; c2++) { printf("%d ",neuronios[c0].posicao[c2]); //} } } printf("\n\n"); } Neuronio get_neuronio_por_posicao(int x, int y) { Neuronio result; for (int c2 = 0; c2 < NUMBER_OF_NEURONS; c2++) { if(neuronios[c2].posicao[0] == x && neuronios[c2].posicao[1] == y) { result = neuronios[c2]; } } return result; } float decremento(int valorInicial) { // decremento para taxa de aprendizado e raio da vizinhança return 1+valorInicial*exp(-(epoch/(EPOCHS/10))); } float distancia_do_vencedor(Neuronio neuronioAtual) { float result = sqrt(pow((neuronioAtual.posicao[0]-neuronios[winnerIndex].posicao[0]),2)+pow((neuronioAtual.posicao[1]-neuronios[winnerIndex].posicao[1]),2)); //printf("\ndistancia do vencedor: %f",result); return result; } float bonus_vizinhanca(Neuronio neuronioAtual) { distanciaEuclidiana = distancia_do_vencedor(neuronioAtual); float result = 0.0; if (distanciaEuclidiana > 0) { result = exp(-5*pow(distanciaEuclidiana,2)/decremento(NEIGHBOURHOOD_RADIUS)); // result = exp(-distanciaEuclidiana/decremento(NEIGHBOURHOOD_RADIUS)); } return result; } int WeightDistance(Entrada entrada, Neuronio neuronio) { int resultado = 0; for (int c0 = 0; c0 < INPUT_DIMENSION; c0++) { // nao é NUMBER_OF_INPUTS; corrigido! resultado = resultado + pow(entrada.pesos[c0]-neuronio.pesos[c0],2); } return sqrt(resultado); } void ajuste() { for(int c0=0; c0 < NUMBER_OF_NEURONS; c0++) { if (c0 != winnerIndex) { for (int c1=0; c1 < INPUT_DIMENSION;c1++) { //no caso das cores, vamos somar ou subtrair? neuronios[c0].pesos[c1] = neuronios[c0].pesos[c1] - LEARNING_RATE*bonus_vizinhanca(neuronios[c0])*(neuronios[c0].pesos[c1]-neuronios[winnerIndex].pesos[c1]); } } } } void kohonen() { distancia_do_peso = 0; neuronios_por_linha = sqrt(NUMBER_OF_NEURONS); for(int c0 = 0; c0 < NUMBER_OF_INPUTS;c0++) { /* pegar entrada */ for(int c1 = 0;c1 < NUMBER_OF_NEURONS; c1++) { distancia_do_peso = WeightDistance(entradas[c0],neuronios[c1]); if (distancia_do_peso == 0) { winnerWeightDistance = distancia_do_peso; winnerIndex = c1; ajuste(); } else if (distancia_do_peso <= winnerWeightDistance) // o menor-igual aqui faz toda a diferenca! senao usar, nao expande outras areas { winnerWeightDistance = distancia_do_peso; winnerIndex = c1; } } ajuste(); winnerWeightDistance = 999999999; } } int total_de_entradas() { int c = 0; Entrada *entradaAtual = entradas; while (entradaAtual[c].pesos) { c++; } return c; } void main() { FILE *file_cfg = NULL; FILE *file_input = NULL; FILE *file_start = NULL; FILE *file_output = NULL; FILE *file_start_html = NULL; FILE *file_output_html = NULL; file_cfg = fopen(CONFIG,"r"); file_input = fopen(INPUT,"r"); file_output = fopen(OUTPUT,"w+"); file_output_html = fopen(OUTPUT_HTML,"w+"); file_start_html = fopen(START_HTML,"w+"); if (testa_se_arquivo_existe(START) == 0) { file_start = fopen(START,"w+"); } else { file_start = fopen(START,"r"); } if (file_cfg == NULL) { printf("\nCFG file not found.\n"); exit(1); } if (file_input == NULL) { printf("\nINPUT file not found.\n"); exit(1); } if (file_start == NULL) { printf("\nSTART file not found.\n"); exit(1); } if (file_output == NULL) { printf("\nOUTPUT file not found.\n"); exit(1); } if (file_output_html == NULL) { printf("\nOUTPUT_HTML file not found.\n"); exit(1); } if (file_start_html == NULL) { printf("\nSTART_HTML file not found.\n"); exit(1); } load_cfg_from_file(file_cfg); criar_rede_em_arquivo_dat(file_start); winnerWeightDistance = 99999999; load_inputs(file_input); load_start(file_start); epoch = 0; //imprimir_rede_na_tela(); imprimir_rede_em_arquivo_html(file_start_html); while (epoch < EPOCHS) { kohonen(); epoch++; } imprimir_rede_em_arquivo_html(file_output_html); if (testa_se_arquivo_existe(STYLE) == 0) { criar_arquivo_css(); } // printf("\ntotal de entradas: %d",total_de_entradas()); fclose(file_cfg); fclose(file_input); fclose(file_start); fclose(file_output); fclose(file_output_html); fclose(file_start_html); }
C
#include <string.h> #include "hanoi.h" int check_cmd(char buf[2], Tower **tower) /* Fonction qui vérifie la commande de jeu */ { int flag; /* Contient 0 si tout se passe bien, autrement -1 */ flag = 0; /* Boucles pour aller au premier plateaux de chaque tour */ while (tower[0]->plate && tower[0]->plate->next && strcmp(tower[0]->plate->namePlate, "|") == 0) tower[0]->plate = tower[0]->plate->next; while (tower[1]->plate && tower[1]->plate->next && strcmp(tower[1]->plate->namePlate, "|") == 0) tower[1]->plate = tower[1]->plate->next; while (tower[2]->plate && tower[2]->plate->next && strcmp(tower[2]->plate->namePlate, "|") == 0) tower[2]->plate = tower[2]->plate->next; /*********************************************************/ if ((buf[0] != '1' && buf[0] != '2' && buf[0] != '3') || /* Vérifie que les caractères rentrée en commande sont correctes */ (buf[1] != '1' && buf[1] != '2' && buf[1] != '3' && buf[1] != '\n')) flag = -1; else if (buf[0] == buf[1]) /* Vérifie que les numéros de tours rentrées ne sont pas les mêmes */ flag = -1; else if (tower[buf[0] - '0' - 1]->nbPlate == 0) /* Vérifie qu'il y a au moins un plateau sur la première tour rentrée */ flag = -1; else if (tower[buf[0] - '0' - 1]->plate->numPlate > tower[buf[1] - '0' - 1]->plate->numPlate) /* Vérifie que le plateau à déplacer n'est pas plus grand que le plateau sur lequel il doit aller */ flag = -1; /* Boucles pour remonter en haut de chaque liste tour */ while (tower[0]->plate->prev) tower[0]->plate = tower[0]->plate->prev; while (tower[1]->plate->prev) tower[1]->plate = tower[1]->plate->prev; while (tower[2]->plate->prev) tower[2]->plate = tower[2]->plate->prev; /******************************************************/ return (flag); /* Retourne flag pour dire comment la commande s'est passée */ } void execute_cmd(Tower *tower1, Tower *tower2) /* Exécute la commande */ { /* Variables temporaires pour le numéro de plateau, le nom de plateau, la couleur de fond et d'avant du plateau */ int numPlate; char *namePlate; int colourFg; int colourBg; /***********************************/ /* Va aller au premier plateau de chaque tour, et échanger les valeurs de chacun afin d'échanger les plateaux, puis ensuite revenir tout en haut de chaque liste */ while (tower1->plate && tower1->plate->next && strcmp(tower1->plate->namePlate, "|") == 0) tower1->plate = tower1->plate->next; while (tower2->plate && tower2->plate->next && strcmp(tower2->plate->next->namePlate, "|") == 0) tower2->plate = tower2->plate->next; numPlate = tower2->plate->numPlate; colourBg = tower2->plate->colourBg; colourFg = tower2->plate->colourFg; namePlate = strdup(tower2->plate->namePlate); tower2->plate->numPlate = tower1->plate->numPlate; tower2->plate->namePlate = strdup(tower1->plate->namePlate); tower2->plate->colourFg = tower1->plate->colourFg; tower2->plate->colourBg = tower1->plate->colourBg; tower1->plate->numPlate = numPlate; tower1->plate->namePlate = strdup(namePlate); tower1->plate->colourFg = colourFg; tower1->plate->colourBg = colourBg; tower1->nbPlate--; tower2->nbPlate++; while (tower1->plate->prev) tower1->plate = tower1->plate->prev; while (tower2->plate->prev) tower2->plate = tower2->plate->prev; /**************************************************************************/ }
C
#include <stdio.h> #include <GL/glew.h> #include <GL/gl.h> #include <SDL.h> #include "vertex_buffer.h" void setup_rendering() { glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); glFrustum(0, 20, 20, 0, 0, 10); //glRotatef() //glTranslatef(-1.0f, 0.0f, 0.0f); glScalef(0.3f, 0.3f, 0.3f); glRotatef(90, -1,0,0); glClear(GL_COLOR_BUFFER_BIT); glColor3f(1.0f, 0.0f, 0.0f); } int handle_events() { SDL_Event event; while(SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { return 1; } else if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE) { return 1; } } return 0; } int main(void){ if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE) != 0){ fprintf(stderr, "Failed to initialize SDL: %s\n", SDL_GetError()); return 1; } SDL_WM_SetCaption("OpenGL test window", "OpenGL"); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_Surface *surface = SDL_SetVideoMode(400, 400, 32, SDL_OPENGL); if (surface == NULL) { fprintf(stderr, "Failed to initialize OpenGL: %s\n", SDL_GetError()); return 1; } GLenum err = glewInit(); if (GLEW_OK != err) { /* Problem: glewInit failed, something is seriously wrong. */ fprintf(stderr, "Failed to initialize GLEW: %s\n", glewGetErrorString(err)); return 1; } printf("OpenGL Version is %s\n", glGetString(GL_VERSION)); setup_rendering(); buffer_t buffer = create_vbo(10, 10); while(1) { //glScalef(1.0, 1.0, 1.1f); glRotatef(10, 0,0,1); glColor3f(1.0f, 0.0f, 0.0f); draw_vbo(buffer); glColor3f(1.0f, 1.0f, 0.0f); draw_vbo_raw(buffer); SDL_GL_SwapBuffers(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); SDL_Delay(500); if(handle_events() == 1) { destroy_vbo(buffer); SDL_Quit(); exit(0); } } }
C
/* ** ALEX NENKO STD SOFTWARE ** ** File: an-list.h - macroses to facilitate AN-LIST management ** ** Oct 1991 Alex Nenko - written ** Dec 2002 Alex Nenko - comments, usage ** Apr 2003 Alex Nenko - 2 bugs in examples in comments :) ** ** NOTE. AN-LIST macroses work with 2-directional list of objects. ** Objects are described by 'struct', that MUST contain two ** pointer fields 'pnext' and 'pprev': ** struct X { struct X * pnext, * pprev; ... }; */ #ifndef _AN_LIST_H_ # define _AN_LIST_H_ #define AN_LIST_Init(x) {(x)->pnext=(x)->pprev=(x); } #define AN_LIST_IsEmpty(x) ((x)->pnext==(x) ) /* insert y after x */ #define AN_LIST_Insert(x,y) {((y)->pnext=(x)->pnext)->pprev=(y);\ ((x)->pnext=(y))->pprev=(x); } /* insert y B4 x */ #define AN_LIST_InsertB4(x,y) {((y)->pprev=(x)->pprev)->pnext=(y);\ ((x)->pprev=(y))->pnext=(x); } /* exclude x from list */ #define AN_LIST_Exclude(x) {((x)->pprev)->pnext=(x)->pnext;\ ((x)->pnext)->pprev=(x)->pprev;} /* go through all objects of a list - WARNING !! See NOTE after examples */ #define for_AN_LIST_Elements(x,y) for( y = (x)->pnext; y != (x); y = (y)->pnext) #define for_AN_LIST_ElementsSafe(x,y,z) for(y=(x)->pnext,z=(y)->pnext;y!=(x);y=z,z=(y)->pnext) /* ** Examples. ** struct X seed, * px; ** Initialize: ** AN_LIST_Init( & seed); ** Insert object 'px' to head: ** AN_LIST_Insert( & seed, px); ** Insert object 'px' to tail: ** AN_LIST_Insert( seed.pprev, px); -- NO ! MACROS DOES NOT WORK ! ** AN_LIST_InsertB4( & seed, px); -- This is OK ! ** Go through all objects of a list: (WARNING !! See NOTE after examples !) ** for( px = seed->pnext; px != seed; px = px->pnext) ** {...} ** or (WARNING !! See NOTE after examples !) ** for_AN_LIST_Elements( & seed, px) ** {...} ** Empty a list: ** while( ! AN_LIST_IsEmpty( & seed)) ** { ** px = seed.pnext; ** AN_LIST_Exclude( px); ** free( px); -- or leave alive if you want ** } ** ** WARNING !! If you brouse the list ** for( px = seed->pnext; px != seed; px = px->pnext) ** for_AN_LIST_Elements( & seed, px); ** AND KILL any 'px', then you will got an error in 'px = px->pnext'. ** Do it in following way: ** some_AN_LIST_type pxnext; ** for( px = seed->pnext; px != seed; px = pxnext) ** { ** pxnext = px->pnext; ** AN_LIST_Exclude( px); ** free( px); ** } ** or ** some_AN_LIST_type px, pxn; ** for_AN_LIST_ElementsSafe(& seed,px,pxn) ** { ** AN_LIST_Exclude( px); ** free( px); ** } */ #endif /* _AN_LIST_H_ */
C
/* Iterative deepening search (迭代加深搜索) */ #include<stdio.h> #include<stdlib.h> #include<string.h> #define MAX_LEN 101 int num[MAX_LEN]; int n, find, dplimit; void dfs(int depth) { int i, j; if(depth >= dplimit) return; if(num[depth] == n) { if(!find) { for(j=0; j<=depth; j++) printf("%d ", num[j]); printf("\n"); find = 1; } return; } for(i=depth; i>=0; i--) if(num[i]+num[depth]<=n) { num[depth+1] = num[i] + num[depth]; dfs(depth+1); } } int main(int argc, char **argv) { while(scanf("%d", &n)!=EOF && n!=0) { find = 0; num[0] = 1; for(dplimit=1; 1; dplimit++) { dfs(0); if(find) break; } } }
C
#include<stdio.h> int main() { struct addbooks { char a[40]; char id[30]; char authorname[30]; char price[30]; char shelfnumber[30]; }book1; printf("\nENTER BOOK INFORMATION\n"); printf("===============================\n"); printf("Book Name: "); gets(book1.a); printf("Book Id: "); gets(book1.id); printf("Author Name: "); gets(book1.authorname); printf("Book Price: "); gets(book1.price); printf("Shelf Number: "); gets(book1.shelfnumber); printf("======================================\n"); FILE *fp1; fseek (fp1, 0 , SEEK_END ); fp1=fopen("math.txt","a"); { fwrite(&book1,sizeof(book1),1,fp1); fprintf(fp1," \n"); } fclose(fp1); printf("The record is sucessfully saved\n\n"); // n1=0; printf("Save any more? (1 / 0): "); int id; scanf("%d",&id); //if(id==1) // addbook(); // else // mainmenu(); return 0; }
C
#include "leet.h" // Counter struct begin typedef struct HashNode { struct HashNode *next; int val; int freq; } HashNode; void node_show(void *p) { HashNode *node = p; if (p == NULL) { printf("%p", p); } else { printf("%d(%d)", node->val, node->freq); } } typedef struct HashTbl { int cap; HashNode **tbl; } HashTbl; HashTbl *ht_create(int cap); void ht_destory(HashTbl *t); void ht_put(HashTbl *t, int x); HashNode *ht_next(HashTbl *t, HashNode *p); void ht_show(HashTbl *t); HashTbl *ht_create(int cap) { if (cap == 0) { cap = 2048; } HashNode **tbl = malloc(sizeof(HashNode *) * cap); memset(tbl, 0, sizeof(HashNode *) * cap); HashTbl *r = malloc(sizeof(HashTbl)); r->cap = cap; r->tbl = tbl; return r; } void ht_destory(HashTbl *t) { int i; for (i = 0; i != t->cap; i++) { HashNode *p = t->tbl[i]; for (p = t->tbl[i]; p != NULL;) { HashNode *n = p->next; free(p); p = n; } } free(t->tbl); free(t); } bool needAdjust(int a, int b) { return a < b * (a / b) && (a < 0) != (b < 0) && a % b != 0; } int mod(int a, int b) { if (needAdjust(a, b)) { return a % b + b; } else { return a % b; } } int ht_hash(HashTbl *t, int x) { // correct mod function for hash return mod(x, t->cap); } void ht_put(HashTbl *t, int x) { int i = ht_hash(t, x); HashNode *p; for (p = t->tbl[i]; p != NULL; p = p->next) { if (p->val == x) { p->freq++; return; } } HashNode *node = malloc(sizeof(HashNode)); node->val = x; node->freq = 1; // insert to head of link list node->next = t->tbl[i]; t->tbl[i] = node; } /** iterate function on hash table * - start iterate on hash table with NULL * - continue to find until not NULL * - if have next node, return next * - if have no next node, continue to iterate - to end of table, return NULL again */ HashNode *ht_next(HashTbl *t, HashNode *p) { int i = 0; if (p != NULL) { if (p->next == NULL) { i = ht_hash(t, p->val) + 1; } else { return p->next; } } for (i != t->cap; i != t->cap; i++) { p = t->tbl[i]; if (p != NULL) { return p; } } return NULL; } void ht_show(HashTbl *t) { printf("HashTbl: %p cap=%d tbl=%p\n", t, t->cap, t->tbl); bool first = true; int i; HashNode *p = NULL; const char *fmt; printf("["); while ((p = ht_next(t, p)) != NULL) { // iterate style if (first) { first = false; } else { printf(", "); } node_show(p); } printf("]\n"); } // Counter struct END --------------------------------------------------------- // Limit Capicity Priority Queue struct --------------------------------------- typedef struct { int cap; // original capcity setting by user int size; // size of arr int num; // num of valid node number void **arr; int (*cmp)(void *, void *); // to compare node void (*show)(void *); // to show node } PQ; PQ *pq_create(int cap, int (*cmp)(void *, void *), void (*show)(void *)) { PQ *p = malloc(sizeof(PQ)); p->num = 0; p->cap = cap; // why need extra 2 node? // - first node of heap is dummy // - When node is to CAP, need extra one to insert to heap, then delete top one. p->size = p->cap + 2; int size = sizeof(void *) * p->size; p->arr = malloc(sizeof(void *) * size); p->cmp = cmp; p->show = show; memset(p->arr, 0, sizeof(void *) * size); return p; } void pq_destory(PQ *p) { // Priority Queue don't care node's memory management free(p->arr); free(p); } void pq_show(PQ *p) { printf("Prority Queue: %p cap=%d size=%d num=%d cmp=%p arr=%p\n", p, p->cap, p->size, p->num, p->cmp, p->arr); const char *delim = ""; int i; printf("["); for (i = 0; i != p->size; i++) { printf("%s%p", delim, p->arr[i]); delim = ", "; if (p->show) { p->show(p->arr[i]); } } printf("]\n"); } bool pq_less(PQ *p, int i, int j) { return p->cmp(p->arr[i], p->arr[j]) < 0; } void pq_exch(PQ *p, int i, int j) { void *t = p->arr[i]; p->arr[i] = p->arr[j]; p->arr[j] = t; } void pq_swim(PQ *p, int i) { // if not top node but less, then swim from bottom to up while (i > 1 && pq_less(p, i / 2, i)) { pq_exch(p, i / 2, i); i /= 2; } } void pq_sink(PQ *p, int i) { while (2 * i <= p->num) { int j = 2 * i; // swap to with larger child node if (j < p->num && pq_less(p, j, j + 1)) { j++; } if (!pq_less(p, i, j)) { break; } pq_exch(p, i, j); i = j; } } void *pq_delTop(PQ *p) { // - delete top node // - swap last node to top // - sink new top node to bottom void *m = p->arr[1]; if (m == NULL) { return NULL; } pq_exch(p, 1, p->num); p->arr[p->num] = NULL; p->num--; pq_sink(p, 1); return m; } void pq_insert(PQ *p, void *node) { // - insert node to last one // - swim last node to up // - if Queue is full, then remove top one p->arr[p->num + 1] = node; pq_swim(p, p->num + 1); p->num++; // limit capcity if (p->num == p->cap + 1) { pq_delTop(p); } } // Limit Capicity Priority Queue struct END ----------------------------------- int cmpNode(void *a, void *b) { HashNode *pa = a, *pb = b; return -pa->freq + pb->freq; // we need min PQ, but not max PQ } int *topKFrequent(int *nums, int numsSize, int k, int *returnSize) { if (nums == NULL || numsSize == 0) { *returnSize = 0; return NULL; } // - hashtable to count frequence of number. O(n) // - Priority queue to sort most frequent k element // - reverse pop from queue to get result HashTbl *t = ht_create(0); int i; for (i = 0; i != numsSize; i++) { ht_put(t, nums[i]); } PQ *q = pq_create(k, cmpNode, node_show); HashNode *p = NULL; while ((p = ht_next(t, p)) != NULL) { if (p == NULL) { return NULL; } pq_insert(q, p); } int *ret = malloc(sizeof(int) * k); *returnSize = k; // k is always valid i = k - 1; while ((p = pq_delTop(q)) != NULL) { ret[i--] = p->val; } pq_destory(q); // temp node will free within hash table ht_destory(t); return ret; } // test code ------------------------------------------------------------------ int testHashTbl() { HashTbl *t = ht_create(10); int a[] = {1, 1, 1, 2, 2, 3, 2, 4, 4, 4, 3, 11, 14, 13, 23}; int i; for (i = 0; i != COUNT_OF(a); i++) { ht_put(t, a[i]); } ht_show(t); free(t); return 0; } int cmp(void *a, void *b) { return a - b; } int testPQ() { PQ *p = pq_create(5, cmp, NULL); long int i; for (i = 10; i != 0; i--) { pq_insert(p, (void *)i); } pq_show(p); pq_destory(p); return 0; } bool unit(int *a, int size, int k, int *e, int esz) { int len; int *r = topKFrequent(a, size, k, &len); bool ret = cmpArr(r, len, e, esz); if (!ret) { showArr(a, size); printf("topKFrequent(arr, %d) == ", k); showArr(r, len); printf(" ?= "); showArr(e, esz); printf("a=%p r=%p e=%p size=%d len=%d esz=%d\n", a, r, e, size, len, esz); } printf("%s\n", expect(ret)); free(r); return ret; } #define UNIT(a, k, e) unit(a, COUNT_OF(a), k, e, COUNT_OF(e)); int testTopK() { int a0[] = {1}; UNIT(a0, 1, a0); int a1[] = {1, 1, 1, 2, 2, 3}; int e1[] = {1, 2}; UNIT(a1, 2, e1); int a2[] = {}; int e2[] = {}; UNIT(a2, 0, e2); int a3[] = {1, 2, 3, 34, 5, 6, 7, 8, 123, 23, 423, 623, 423, 111, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 3}; int e3[] = {1}; UNIT(a3, 1, e3); int a4[] = {-1, -1}; int e4[] = {-1}; UNIT(a4, 1, e4); return 0; } int main() { testHashTbl(); testPQ(); testTopK(); return 0; }
C
#include <stdio.h> #define PI 3.14 int main() { float radius, result; int choice; printf("Enter radius: "); scanf("%f", &radius); printf("1. Area of Circle\n2. Circumference of Circle\n3. Volume of Sphere\nEnter your choice: "); scanf("%d", &choice); switch (choice) { case 1: result = PI * radius * radius; printf("Area: %.2f sq. unit", result); break; case 2: result = 2 * PI * radius; printf("Circumference: %.2f unit", result); break; case 3: result = (4 * PI * radius * radius * radius) / 3; printf("Volume of Sphere: %.2f cubic unit", result); break; default: printf("Invalid Option"); } printf("\n"); return 0; }
C
//Generates filter coefficients for smooth differentiators as described in: //Holoborodko P. 2008. Smooth noise robust differentiators. www.holoborodko.com. //See also: de Matos MC. 2018. Seismic attributes from the complex Teager-Kaiser energy. //These can be used with fir. //See smooth_diff for more comments. //N is the (odd) filter-length, and n is the degree of the monomial (1+x+x^2+...+x^n). #include <stdio.h> #ifdef __cplusplus namespace codee { extern "C" { #endif int smooth_diffdiff_s (float *Y, const size_t N, const size_t n); int smooth_diffdiff_d (double *Y, const size_t N, const size_t n); int smooth_diffdiff_s (float *Y, const size_t N, const size_t n) { if (N%2u==0u) { fprintf(stderr,"error in smooth_diffdiff_s: N (filter length) must be odd\n"); return 1; } if (n%2u==0u) { fprintf(stderr,"error in smooth_diffdiff_s: n (degree of polynomial exactness) must be odd\n"); return 1; } if (n==3u) { if (N==5u) { *Y++ = 1.0f/4.0f; *Y++ = 0.0f; *Y++ = -2.0f/4.0f; *Y++ = 0.0f; *Y++ = 1.0f/4.0f; } else if (N==7u) { *Y++ = 1.0f/16.0f; *Y++ = 2.0f/16.0f; *Y++ = -1.0f/16.0f; *Y++ = -4.0f/16.0f; *Y++ = -1.0f/16.0f; *Y++ = 2.0f/16.0f; *Y++ = 1.0f/16.0f; } else if (N==9u) { *Y++ = 1.0f/64.0f; *Y++ = 4.0f/64.0f; *Y++ = -4.0f/64.0f; *Y++ = -4.0f/64.0f; *Y++ = -10.0f/64.0f; *Y++ = -4.0f/64.0f; *Y++ = -4.0f/64.0f; *Y++ = 4.0f/64.0f; *Y++ = 1.0f/64.0f; } else { fprintf(stderr,"error in smooth_diffdiff_s: N (filter length) must be in {5,7,9} for n=3\n"); return 1; } } else if (n==5u) { if (N==7u) { *Y++ = -1.0f/12.0f; *Y++ = 5.0f/12.0f; *Y++ = 1.0f/12.0f; *Y++ = -10.0f/12.0f; *Y++ = 1.0f/12.0f; *Y++ = 5.0f/12.0f; *Y++ = -1.0f/12.0f; } else if (N==9u) { *Y++ = -7.0f/192.0f; *Y++ = 12.0f/192.0f; *Y++ = 52.0f/192.0f; *Y++ = -12.0f/192.0f; *Y++ = -90.0f/192.0f; *Y++ = -12.0f/192.0f; *Y++ = 52.0f/192.0f; *Y++ = 12.0f/192.0f; *Y++ = -7.0f/192.0f; } else { fprintf(stderr,"error in smooth_diffdiff_s: N (filter length) must be in {7,9} for n=5\n"); return 1; } } else { fprintf(stderr,"error in smooth_diffdiff_s: n (degree of polynomial exactness) must be 3 or 5\n"); return 1; } return 0; } int smooth_diffdiff_d (double *Y, const size_t N, const size_t n) { if (N%2u==0u) { fprintf(stderr,"error in smooth_diffdiff_d: N (filter length) must be odd\n"); return 1; } if (n%2u==0u) { fprintf(stderr,"error in smooth_diffdiff_d: n (degree of polynomial exactness) must be odd\n"); return 1; } if (n==3u) { if (N==5u) { *Y++ = 1.0/4.0; *Y++ = 0.0; *Y++ = -2.0/4.0; *Y++ = 0.0; *Y++ = 1.0/4.0; } else if (N==7u) { *Y++ = 1.0/16.0; *Y++ = 2.0/16.0; *Y++ = -1.0/16.0; *Y++ = -4.0/16.0; *Y++ = -1.0/16.0; *Y++ = 2.0/16.0; *Y++ = 1.0/16.0; } else if (N==9u) { *Y++ = 1.0/64.0; *Y++ = 4.0/64.0; *Y++ = -4.0/64.0; *Y++ = -4.0/64.0; *Y++ = -10.0/64.0; *Y++ = -4.0/64.0; *Y++ = -4.0/64.0; *Y++ = 4.0/64.0; *Y++ = 1.0/64.0; } else { fprintf(stderr,"error in smooth_diffdiff_d: N (filter length) must be in {5,7,9} for n=3\n"); return 1; } } else if (n==5u) { if (N==7u) { *Y++ = -1.0/12.0; *Y++ = 5.0/12.0; *Y++ = 1.0/12.0; *Y++ = -10.0/12.0; *Y++ = 1.0/12.0; *Y++ = 5.0/12.0; *Y++ = -1.0/12.0; } else if (N==9u) { *Y++ = -7.0/192.0; *Y++ = 12.0/192.0; *Y++ = 52.0/192.0; *Y++ = -12.0/192.0; *Y++ = -90.0/192.0; *Y++ = -12.0/192.0; *Y++ = 52.0/192.0; *Y++ = 12.0/192.0; *Y++ = -7.0/192.0; } else { fprintf(stderr,"error in smooth_diffdiff_d: N (filter length) must be in {7,9} for n=5\n"); return 1; } } else { fprintf(stderr,"error in smooth_diffdiff_d: n (degree of polynomial exactness) must be 3 or 5\n"); return 1; } return 0; } #ifdef __cplusplus } } #endif
C
#include "quadtree.h" struct point1 { int x; int y; }; /*container for regions*/ struct regionData1 { int minRow; int maxRow; int minCol; int maxCol; int count; points **vertices; void *data; int region_id; //indicates which region the node belongs to }; /*container for quadrant boundaries*/ struct boundingBox1 { int begx; int begy; int endx; int endy; }; /*container for region boundaries*/ struct quadTreeNode1 { struct quadTreeNode1 *nw; struct quadTreeNode1 *ne; struct quadTreeNode1 *sw; struct quadTreeNode1 *se; boundingBox boundary; regionData *points; }; /*create a boundary*/ boundingBox createBoundingBox(int begx, int begy, int endx, int endy) { boundingBox bb; bb.begx = begx; bb.begy = begy; bb.endx = endx; bb.endy = endy; return bb; } /*create a node in the tree*/ quadTreeNode *createQuadTreeNode(boundingBox boundary) { quadTreeNode *node = malloc(sizeof(quadTreeNode)); node->nw = NULL; node->ne = NULL; node->sw = NULL; node->se = NULL; node->boundary = boundary; node->points = NULL; return node; } int max(int a, int b) { return (a>=b)? a:b; } int min(int a, int b) { return (a<=b)? a:b; } /*take in a string, convert to int*/ int StringtoInt(char *stringptr) { int n, i; for(i=0, n=0; i<strlen(stringptr); i++) { n=(n*10)+(stringptr[i]-48); } return n; } int find_power(int dimx, int dimy) { /*TODO: given dimx and dimy: 1. dimx != dimy 2. figure out which is bigger, dimx or dimy 3. calculate larger dimension to nearest power of 2 4. set both dimx and dimy to be the nearest power of 2*/ float i; //1st case: x dimension larger than y dimension OR x dim == y dim if(dimx > dimy || dimx == dimy) { i = (ceil(log(dimx)/log(2))); dimx = (int)(pow(2, i)); return dimx; } //2nd case: y dimension larger than x dimension if(dimy > dimx) { i = (ceil(log(dimy)/log(2))); dimy = (int)(pow(2, i)); return dimy; } } // Given three colinear points p, q, r, the function checks if // point q lies on line segment 'pr' bool onSegment(points p, points q, points r) { if (q.x <= max(p.x, r.x) && q.x >= min(p.x, r.x) && q.y <= max(p.y, r.y) && q.y >= min(p.y, r.y)) return true; return false; } // To find orientation of ordered triplet (p, q, r). // The function returns following values // 0 --> p, q and r are colinear // 1 --> Clockwise // 2 --> Counterclockwise int orientation(points p, points q, points r) { // See http://www.geeksforgeeks.org/orientation-3-ordered-points/ // for details of below formula. int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); if (val == 0) return 0; // colinear return (val > 0)? 1: 2; // clock or counterclock wise } // The main function that returns true if line segment 'p1q1' // and 'p2q2' intersect. bool doIntersect(points p1, points q1, points p2, points q2) { // Find the four orientations needed for general and // special cases int o1 = orientation(p1, q1, p2); int o2 = orientation(p1, q1, q2); int o3 = orientation(p2, q2, p1); int o4 = orientation(p2, q2, q1); // General case if (o1 != o2 && o3 != o4) return true; // Special Cases // p1, q1 and p2 are colinear and p2 lies on segment p1q1 if (o1 == 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are colinear and q2 lies on segment p1q1 if (o2 == 0 && onSegment(p1, q2, q1)) return true; // p2, q2 and p1 are colinear and p1 lies on segment p2q2 if (o3 == 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and q1 are colinear and q1 lies on segment p2q2 if (o4 == 0 && onSegment(p2, q1, q2)) return true; return false; // Doesn't fall in any of the above cases } bool isInside(points *polygon, int n, points p) { if (n<3) return false; points extreme = {INF, p.y}; int count = 0, i=0; do { int next = (i+1)%n; if (doIntersect(polygon[i], polygon[next], p, extreme)) { if (orientation(polygon[i],p,polygon[next]) == 0) return onSegment(polygon[i],p,polygon[next]); count ++; } i = next; } while (i != 0); return count&1; } /*recursively divide into 4 quadrants*/ /*return: 0 if region NOT in subquadrant 1 if region IS in subquadrant 10 if max region IS in subquadrant but actual region is NOT in subquadrant*/ int divide(quadTreeNode *node, regionData *region) { int return_code = 0; /*set variables for node: begx = first row; begy = first col; endx =last row, endy = last col*/ int begx = node->boundary.begx; int begy = node->boundary.begy; int endx = node->boundary.endx; int endy = node->boundary.endy; points begpt, endpt; /*calculate midpoint of quadrant*/ int midx = ((endx-begx)+1)/2; int midy = ((endy-begy)+1)/2; /*if the midpoint of the x (rows) or the midpoint of the y (columns) is 0, done dividing*/ if(midx==0 || midy==0) { /*check that the leaf is contained in the polygon*/ //TODO: make loop for polygon array - initialize all to NULL or 0 points polygon[MAX_POINTS]; begpt.x=(begx+endx)/2; begpt.y=(begy+endy)/2; for(int i=0; i<region->count; i++) { polygon[i].x=region->vertices[i]->x; polygon[i].y=region->vertices[i]->y; } if(isInside(polygon, region->count,begpt)) { node->points = region; return 1; } else { return 10; } } /*printf("\nnode boundary: [%d,%d],[%d,%d]\n",begx,begy,endx,endy); printf("nw boundary: [%d,%d],[%d,%d]\n",begx,begy,((begx+midx)-1),((begy+midy)-1)); printf("ne boundary: [%d,%d],[%d,%d]\n",begx,begy+midy,((begx+midx)-1),endy); printf("sw boundary: [%d,%d],[%d,%d]\n", begx+midx,begy, endx,((begy+midy)-1)); printf("se boundary: [%d,%d],[%d,%d]\n", begx+midx,begy+midy, endx, endy); /*create quad tree with regions as nodes*/ /*NORTHWEST QUADRANT*/ if(begx<=region->maxRow && ((begx+midx)-1)>=region->minRow && begy<=region->maxCol && ((begy+midy)-1)>=region->minCol) { //printf("\nsub nw:"); if(node->nw == NULL) { /*create the boundary*/ boundingBox boundNW = createBoundingBox(begx, begy, (begx+midx)-1, (begy+midy)-1); /*create the node -- createQuadTreeNode takes boundary as parameter*/ quadTreeNode *nodeNW = createQuadTreeNode(boundNW); node->nw = nodeNW; } return_code=divide(node->nw, region); if(return_code==10) node->nw = NULL; } /*NORTHEAST QUADRANT*/ if(begx<=region->maxRow && ((begx+midx)-1)>=region->minRow && (begy+midy)<=region->maxCol && endy>=region->minCol) { //printf("\nsub ne:"); if(node->ne == NULL) { /*create the boundary*/ boundingBox boundNE = createBoundingBox(begx, begy+midy, (begx+midx)-1, endy); /*create the node -- createQuadTreeNode takes boundary as parameter*/ quadTreeNode *nodeNE = createQuadTreeNode(boundNE); node->ne = nodeNE; } return_code=divide(node->ne, region); if(return_code==10) node->ne = NULL; } /*SOUTHWEST QUADRANT*/ if((begx+midx)<=region->maxRow && endx>=region->minRow && begy<=region->maxCol && (begy+midy)-1>=region->minCol) { //printf("\nsub sw:"); if(node->sw == NULL) { /*create the boundary*/ boundingBox boundSW = createBoundingBox(begx+midx, begy, endx, (begy+midy)-1); /*create the node -- createQuadTreeNode takes boundary as parameter*/ quadTreeNode *nodeSW = createQuadTreeNode(boundSW); node->sw = nodeSW; } return_code=divide(node->sw, region); if(return_code==10) node->sw = NULL; } /*SOUTHEAST QUADRANT*/ if((begx+midx)<=region->maxRow && endx>=region->minRow && begy+midy<=region->maxCol && endy>=region->minCol) { //printf("\nsub se:"); if(node->se == NULL) { /*create the boundary*/ boundingBox boundSE = createBoundingBox(begx+midx, begy+midy, endx, endy); /*create the node -- createQuadTreeNode takes boundary as parameter*/ quadTreeNode *nodeSE = createQuadTreeNode(boundSE); node->se = nodeSE; } return_code=divide(node->se, region); if(return_code==10) node->se = NULL; } return 0; } /*return the desired node*/ int findNode(int x1, int y1, quadTreeNode *topnode) { int found=0; int begx = topnode->boundary.begx; int begy = topnode->boundary.begy; int endx = topnode->boundary.endx; int endy = topnode->boundary.endy; /*calculate midpoint of quadrant*/ int midx = ((endx-begx)+1)/2; int midy = ((endy-begy)+1)/2; //NORTHWEST QUADRANT SEARCH if(x1>=begx && x1 <=(begx+midx)-1 && y1>=begy && y1<=(begy+midy)-1) { if(topnode->nw !=NULL) findNode(x1, y1, topnode->nw); //found a match else if(topnode->nw == NULL && x1>=begx && x1 <=endx && y1>=begy && y1<=endy) { found=1; printf("\npoint [%d %d] exists within node [%d %d][%d %d]", x1, y1, begx, begy, endx, endy); } //else this point is not part of a region that exists within the tree. else { found=0; printf("\npoint [%d %d] not in boundary.", x1, y1); } } //NORTHEAST QUADRANT SEARCH if(x1>=begx && x1<=(begx+midx)-1 && y1>=(begy+midy) && y1<=endy) { if(topnode->ne != NULL) findNode(x1, y1, topnode->ne); else if(topnode->ne == NULL && x1>=begx && x1 <=endx && y1>=begy && y1<=endy) { found=1; printf("\npoint [%d %d] exists within node [%d %d][%d %d]", x1, y1, begx, begy, endx, endy); } else { found=0; printf("\npoint [%d %d] not in boundary.", x1, y1); } } //SOUTHWEST QUADRANT SEARCH if(x1>=(begx+midx) && x1<=endx && y1>=begy && y1<=(begy+midy)-1) { if(topnode->sw != NULL) findNode(x1, y1, topnode->sw); else if(topnode->nw == NULL && x1>=begx && x1 <=endx && y1>=begy && y1<=endy) { found=1; printf("\npoint [%d %d] exists within node [%d %d][%d %d]", x1, y1, begx, begy, endx, endy); } else { found=0; printf("\npoint [%d %d] not in boundary.", x1, y1); } } //SOUTHEAST QUADRANT SEARCH if(x1>=(begx+midx) && x1<=endx && y1>=(begy+midy) && y1<=endy) { if(topnode->se != NULL) findNode(x1, y1, topnode->se); else if(topnode->nw == NULL && x1>=begx && x1 <=endx && y1>=begy && y1<=endy) { found=1; printf("\npoint [%d %d] exists within node [%d %d][%d %d]", x1, y1, begx, begy, endx, endy); } else { found=0; printf("\npoint [%d %d] not in boundary.", x1, y1); } } return 1; } void sizeOf(quadTreeNode *topnode) { //count the number of nodes by postorder if(topnode == NULL) return; sizeOf(topnode->nw); sizeOf(topnode->ne); sizeOf(topnode->sw); sizeOf(topnode->se); nodecount++; return; } /*void presizeOf(quadTreeNode *topnode) { if(topnode == NULL) return; nodecount1++; presizeOf(topnode->nw); presizeOf(topnode->ne); presizeOf(topnode->sw); presizeOf(topnode->se); return; }*/ /*void translate(//??) { /*TODO: for vertex count: create temp array REVERSE: Copying elements into array b starting from end of array for (c = n - 1, d = 0; c >= 0; c--, d++) b[d] = a[c]; Copying reversed array into original. Here we are modifying original array, this is optional. for (c = 0; c < n; c++) a[c] = b[c]; TRANSLATE COORDINATES: switch x and y (x, y) -> (y, x) }*/ int merge (quadTreeNode *topnode) { int leaf_found; int leaf_count; leaf_count = 0; if(topnode->nw != NULL) //pointer to more nodes { //printf("before nw: %d\n",topnode->nw); leaf_found=merge(topnode->nw); leaf_count=leaf_count+leaf_found; //printf("after nw: %d\n",topnode->nw); //printf("leaf_found: %d\n",leaf_found); //printf("leaf_count: %d\n",leaf_count); } if(topnode->ne != NULL) { //printf("before ne: %d\n",topnode->ne); leaf_found=merge(topnode->ne); leaf_count=leaf_count+leaf_found; //printf("after ne: %d\n",topnode->ne); //printf("leaf_found: %d\n",leaf_found); //printf("leaf_count: %d\n",leaf_count); } if(topnode->sw != NULL) { //printf("before sw: %d\n",topnode->sw); leaf_found=merge(topnode->sw); leaf_count=leaf_count+leaf_found; //printf("after sw: %d\n",topnode->sw); //printf("leaf_found: %d\n",leaf_found); //printf("leaf_count: %d\n",leaf_count); } if(topnode->se !=NULL) { //printf("before se: %d\n",topnode->se); leaf_found=merge(topnode->se); leaf_count=leaf_count+leaf_found; //printf("after se: %d\n",topnode->se); //printf("leaf_found: %d\n",leaf_found); //printf("leaf_count: %d\n",leaf_count); } //if all the pointers are null, we have found a leaf. if(topnode->nw == NULL && topnode->ne == NULL && topnode->sw == NULL && topnode->se == NULL) { //printf("\ntopnode: %d",topnode); //printf("\ntopnode->points: %d", topnode->points); //printf("\ntop boundary: [%d, %d]", topnode->boundary.begx, topnode->boundary.begy); //printf("\nbottom boundary: [%d, %d]\n", topnode->boundary.endx, topnode->boundary.endy); return 1; } if (leaf_count == 4) { if((topnode->ne != NULL) && (topnode->ne->points == topnode->nw->points)) { if((topnode->sw != NULL) && (topnode->sw->points == topnode->nw->points)) { if((topnode->se != NULL) && (topnode->se->points == topnode->nw->points)) { //printf("4 leaves merged: %d, %d, %d, %d\n",topnode->nw, topnode->ne, topnode->sw, topnode->se); //printf("region is: %d\n",topnode->nw->points); topnode->points = topnode->nw->points; topnode->nw = NULL; topnode->ne = NULL; topnode->sw = NULL; topnode->se = NULL; //printf("\ntop boundary: [%d, %d]", topnode->boundary.begx, topnode->boundary.begy); //printf("\nbottom boundary: [%d, %d]\n", topnode->boundary.endx, topnode->boundary.endy); return 1; } } } } return 0; } int traverseTree(quadTreeNode *topnode) { if(topnode->nw != NULL) //pointer to more nodes { //printf("before nw: %d\n",topnode->nw); traverseTree(topnode->nw); //printf("after nw: %d\n",topnode->nw); } if(topnode->ne != NULL) { //printf("before ne: %d\n",topnode->ne); traverseTree(topnode->ne); //printf("after ne: %d\n",topnode->ne); } if(topnode->sw != NULL) { //printf("before sw: %d\n",topnode->sw); traverseTree(topnode->sw); //printf("after sw: %d\n",topnode->sw); } if(topnode->se !=NULL) { //printf("before se: %d\n",topnode->se); traverseTree(topnode->se); //printf("after se: %d\n",topnode->se); } //if all the pointers are null, we have found a leaf. if(topnode->nw == NULL && topnode->ne == NULL && topnode->sw == NULL && topnode->se == NULL) { //printf("\ntopnode: %d",topnode); //printf("\ntopnode->points: %d", topnode->points); //printf("\ntop boundary: [%d, %d]", topnode->boundary.begx, topnode->boundary.begy); //printf("\nbottom boundary: [%d, %d]\n", topnode->boundary.endx, topnode->boundary.endy); //FREE? } return 1; } /*parse out keywords and return data*/ regionData *parseString(char *lineptr, char *keywordptr) { int i, j; int min_x = 1000; int min_y = 1000; int max_x = 0; int max_y = 0; int count = 0; int linepos; int vertexcount=0; int found = 0; //bool for whether substring is found in the string int pair = 0; //bool for first/second of pair - 0=first, 1=second char buffer[1024]; int saveint[MAX_POINTS*2]; regionData *regionptr; points **vertexptr; points *rect; //pointer to structure /*assign local pointers*/ char *line = lineptr; char *word = keywordptr; //printf("String: %s\n",line); //printf("Substring: %s\n",word); /*check if the string (line) is longer than the substring (word) - if so, word is a valid substring (else return error)*/ // printf("string length: %lu\nword length: %lu\n", strlen(line), strlen(word)); //printf("string: %s\nword:%s\n", line, word); if (strlen(line) >= strlen(word)) { regionptr = malloc(sizeof(regionData)); //pointer to a region vertexptr = malloc(sizeof(points*)*MAX_POINTS); //pointer to pointer to array of all the points for a region for (i=0, j=0; i<strlen(line); i++) { /*if characters match, increase word position*/ if (line[i] = word[j]) { j++; /*if we reached the end of the word, mark word as found*/ if(strlen(word)==j) { found=1; linepos=i; break; } } else { j=0; } } } else return NULL; //printf("keyword not found\n"); if(found==1) { for(i=linepos, j=0; i<strlen(line); i++) { /*if the character matches int 0-9, increase counter position*/ if(line[i] >= '0' && line[i] <= '9') { buffer[j] = line[i]; j++; } else { if(j>0) { /*convert found ints, reset integer counter*/ buffer[j] = '\0'; saveint[count] = StringtoInt(buffer); j=0; count++; } /*delimiter for the end of the function*/ if(line[i] == ')') { break; } } } for(i=0; i<count; i++) { if(pair==0) { /*if we find a number, */ rect = malloc(sizeof(points)); rect->x = saveint[i]; //printf("\nint x: %d", rect->x); pair = 1; } else { rect->y = saveint[i]; //printf("\nint y: %d", rect->y); pair = 0; vertexptr[vertexcount] = rect; vertexcount++; } } //CHANGE: if too many points, error; invalid region if 1st and last points don't match /*for(j=vertexcount; j<MAX_POINTS; j++) { //if(vertexptr[vertexcount] != vertexptr[j]) //printf("not a valid region"); vertexptr[vertexcount] = NULL; printf("\nnot enough points\n"); }*/ regionptr->vertices = vertexptr; regionptr->count = vertexcount; for(i=0; i<vertexcount; i++) { if(regionptr->vertices[i]->x < min_x) min_x = regionptr->vertices[i]->x; else if(regionptr->vertices[i]->x > max_x) max_x = regionptr->vertices[i]->x; if(regionptr->vertices[i]->y < min_y) min_y = regionptr->vertices[i]->y; else if(regionptr->vertices[i]->y > max_y) max_y = regionptr->vertices[i]->y; } regionptr->minRow = min_x; regionptr->maxRow = max_x; regionptr->minCol = min_y; regionptr->maxCol = max_y; return regionptr; } //return regionptr; } /* open file and read coordinates of rectangular regions*/ regionData **readfile(FILE *infile, char *keyword1) { //int upleftx, uplefty, botrightx, botrighty; char buffer[1024]; //set keyword to look for int count = 0; regionData *temp; regionData **rect = malloc(sizeof(regionData*)*MAX_REGIONS); // FILE *file; // file = fopen(infile, "r"); if(infile == NULL) { perror("Error opening file"); return NULL; } else { while(fgets(buffer, sizeof(buffer), infile)) { //printf("buffer size: %lu", strlen(buffer)); temp = parseString(buffer, keyword1); if (temp !=NULL) { rect[count] = parseString(buffer, keyword1); count++; //printf("\ncount: %d", count); } if(count == MAX_REGIONS) break; //printf("\ncount: %d", count); if(count == MAX_REGIONS) break; } //printf("\ncount: %d", count); for(int i=count; i<MAX_REGIONS; i++) { rect[count] = NULL; } } return rect; } //GRAPHICS CALLS: /*void init2D(float r, float g, float b) { glClearColor(r,g,b,0.0); glMatrixMode (GL_PROJECTION); gluOrtho2D (0.0, 200.0, 0.0, 150.0); } // mouse // The GLUT mouse function void mouse(int x, int y) { // Save the mouse position mousex = x; mousey = y; //create a mouse track file fprintf(file, "\nmouse: %d, %d", mousex, mousey); //show mouse position in stdout fprintf(stdout, "\nmouse: %d, %d", mousex, mousey); } void display(void) { glClear(GL_COLOR_BUFFER_BIT); glColor3f(1.0, 0.0, 0.0); // Convert mouse position to OpenGL's coordinate system double oglx = (double)mousex/winw; double ogly = 1-(double)mousey/winh; glFlush(); }*/ void translateRegion(quadTreeNode *topnode, int *region_found) { int which_region; int i; int last_vertice; if(topnode->nw != NULL) //pointer to more nodes translateRegion(topnode->nw,region_found); if(topnode->ne != NULL) translateRegion(topnode->ne,region_found); if(topnode->sw != NULL) translateRegion(topnode->sw,region_found); if(topnode->se !=NULL) translateRegion(topnode->se,region_found); //if all the pointers are null, we have found a leaf. if(topnode->nw == NULL && topnode->ne == NULL && topnode->sw == NULL && topnode->se == NULL) { //printf("in translateRegion-pointer to regionData: %d\n",topnode->points); //printf("in translateRegion-pointer to region_id: %d\n",topnode->points->region_id); /* printf("region %d: %d\n",topnode->points->region_id, region_found[topnode->points->region_id]); which_region= topnode->points->region_id; if (region_found[which_region]==0) { region_found[which_region]=1; last_vertice=topnode->points->count; for (i=0; i<last_vertice; i++) { region_x[which_region][i]=topnode->points->vertices[last_vertice-i]->y; region_y[which_region][i]=topnode->points->vertices[last_vertice-i]->x; } } for (i=0; i<MAX_REGIONS; i++) { printf("region %d: %d",i,region_found[i]); } */ return; } } void translateTree(quadTreeNode *topnode) { int i, j; int region_found[MAX_REGIONS]; //initialize array that flags which region has been translated for the graphics for (i=0; i<MAX_REGIONS; i++) { region_found[i]=0; } //initialize array that holds vertices for each region for (i=0; i<region_count; i++) { for (j=0; j<MAX_POINTS; j++) { region_x[i][j]=-1; region_y[i][j]=-1; } } for (i=0; i<region_count; i++) { translateRegion(topnode, region_found); } return; } quadTreeNode *mapRegions(char *filename1, char *filename2, int endx, int endy) { int i; int divide_ret; nodecount = 0; //nodecount1 = 0; clock_t t0, t1; double elapsed_time; char keyword[128] = "POLYGON"; char keyword2[128] = "mouse"; /*create the boundary*/ boundingBox box = createBoundingBox(0, 0, endx, endy); /*create the node -- createQuadTreeNode takes boundary as parameter*/ quadTreeNode *node1 = createQuadTreeNode(box); //root = node1; /*create the node data*/ FILE *infile1 = fopen(filename1, "r"); FILE *infile2 = fopen(filename2, "r"); regionData **datafile = readfile(infile1, keyword); regionData **datafile2 = readfile(infile2, keyword2); // fclose(infile1); // return node1; for(i=0; i<MAX_REGIONS; i++) { if(datafile[i] == NULL) { break; } else { datafile[i]->region_id=i; divide_ret=divide(node1, datafile[i]); //printf("\npreorder size: %d", nodecount1); } } region_count=i; //printf("\nregion count: %d\n",region_count); //traverseTree(node1); merge(node1); traverseTree(node1); sizeOf(node1); //presizeOf(node1); t0 = clock(); for(int j=0; j<MAX_REGIONS; j++) { if(datafile2[j] == NULL) { break; } else { findNode(datafile2[j]->vertices[0]->x, datafile2[j]->vertices[0]->y, node1); t1 = clock(); elapsed_time = ((double)(t1-t0) / CLOCKS_PER_SEC); printf("\noperation time: %f seconds", elapsed_time); //t = clock(); } } printf("\nimage dimensions: %dx%d", endx+1, endy+1); printf("\nsize: %d nodes\n", nodecount); fclose(infile1); fclose(infile2); return node1; }
C
/* critical.c * ... fixes a race condition when multiple threads read from / * write to a shared variable using the OpenMP critical directive. * * Joel Adams, Calvin College, November 2009. * * Usage: ./critical * * Exercise: * - Compile and run several times; note that it always produces the correct balance $1,000,000.00 * - Comment out A; recompile/run, and note incorrect result * - To fix: uncomment B1+B2+B3, recompile and rerun, compare */ #include<stdio.h> #include<omp.h> int main() { const int REPS = 1000000; int i; double balance = 0.0; printf("\nYour starting bank account balance is %0.2f\n", balance); // simulate many deposits #pragma omp parallel for for (i = 0; i < REPS; i++) { //#pragma omp atomic // A #pragma omp critical // B1 { // B2 balance += 1.0; } // B3 } printf("\nAfter %d $1 deposits, your balance is %0.2f\n", REPS, balance); return 0; }
C
#include <stdio.h> int main () { float H, he1, hf1, he2, hf2, p; printf ("Digite o numero de horas extras feitas pelo funsionario: "); scanf ("%f", &he1); printf ("Digite o numero de horas faltas feitas pelo funcionario: "); scanf ("%f", &hf1); //calculo, H = minutos = he * 60 - (2/3 * (hf * 60) he2 = he1 * 60; hf2 = hf1 * 60; H = he2 - (0.666666666667 * (hf2)); if (H >= 2400) { p = 500; } else if (H >= 1800 && H < 2400) { p = 400; } else if (H >= 1200 && H < 1800) { p = 300; } else if (H >= 600 && H < 1200) { p = 200; } else { p = 100; } printf ("O premio e de: R$%.2f", p); return 0; }
C
#include "plt_vertex_processor.h" #include <stdlib.h> #include "platypus/mesh/plt_mesh.h" #include "platypus/base/allocation/plt_linear_allocator.h" typedef struct Plt_Vertex_Processor_Working_Buffer { unsigned int vertex_capacity; float *clipspace_x; float *clipspace_y; float *clipspace_z; float *clipspace_w; int *screen_positions_x; int *screen_positions_y; float *world_normals_x; float *world_normals_y; float *world_normals_z; } Plt_Vertex_Processor_Working_Buffer; typedef struct Plt_Vertex_Processor { Plt_Vertex_Processor_Working_Buffer working_buffer; } Plt_Vertex_Processor; void plt_vertex_processor_free_working_buffer(Plt_Vertex_Processor *processor); Plt_Vertex_Processor *plt_vertex_processor_create() { Plt_Vertex_Processor *processor = malloc(sizeof(Plt_Vertex_Processor)); processor->working_buffer = (Plt_Vertex_Processor_Working_Buffer){ .vertex_capacity = 0, .clipspace_x = NULL, .clipspace_y = NULL, .clipspace_z = NULL, .clipspace_w = NULL, .screen_positions_x = NULL, .screen_positions_y = NULL, .world_normals_x = NULL, .world_normals_y = NULL, .world_normals_z = NULL }; return processor; } void plt_vertex_processor_destroy(Plt_Vertex_Processor **processor) { plt_vertex_processor_free_working_buffer(*processor); free(*processor); *processor = NULL; } void plt_vertex_processor_free_working_buffer(Plt_Vertex_Processor *processor) { if (processor->working_buffer.vertex_capacity == 0) { // Nothing to free. return; } free(processor->working_buffer.clipspace_x); free(processor->working_buffer.clipspace_y); free(processor->working_buffer.clipspace_z); free(processor->working_buffer.clipspace_w); free(processor->working_buffer.screen_positions_x); free(processor->working_buffer.screen_positions_y); free(processor->working_buffer.world_normals_x); free(processor->working_buffer.world_normals_y); free(processor->working_buffer.world_normals_z); processor->working_buffer.clipspace_x = NULL; processor->working_buffer.clipspace_y = NULL; processor->working_buffer.clipspace_z = NULL; processor->working_buffer.screen_positions_x = NULL; processor->working_buffer.screen_positions_y = NULL; processor->working_buffer.world_normals_x = NULL; processor->working_buffer.world_normals_y = NULL; processor->working_buffer.world_normals_z = NULL; } void plt_vertex_processor_resize_working_buffer(Plt_Vertex_Processor *processor, unsigned int capacity) { if (processor->working_buffer.vertex_capacity == capacity) { return; } if (processor->working_buffer.vertex_capacity > 0) { free(processor->working_buffer.clipspace_x); free(processor->working_buffer.clipspace_y); free(processor->working_buffer.clipspace_z); free(processor->working_buffer.clipspace_w); free(processor->working_buffer.screen_positions_x); free(processor->working_buffer.screen_positions_y); free(processor->working_buffer.world_normals_x); free(processor->working_buffer.world_normals_y); free(processor->working_buffer.world_normals_z); } if (capacity > 0) { processor->working_buffer.clipspace_x = malloc(sizeof(float) * capacity); processor->working_buffer.clipspace_y = malloc(sizeof(float) * capacity); processor->working_buffer.clipspace_z = malloc(sizeof(float) * capacity); processor->working_buffer.clipspace_w = malloc(sizeof(float) * capacity); processor->working_buffer.screen_positions_x = malloc(sizeof(int) * capacity); processor->working_buffer.screen_positions_y = malloc(sizeof(int) * capacity); processor->working_buffer.world_normals_x = malloc(sizeof(float) * capacity); processor->working_buffer.world_normals_y = malloc(sizeof(float) * capacity); processor->working_buffer.world_normals_z = malloc(sizeof(float) * capacity); } else { processor->working_buffer.clipspace_x = NULL; processor->working_buffer.clipspace_y = NULL; processor->working_buffer.clipspace_z = NULL; processor->working_buffer.clipspace_w = NULL; processor->working_buffer.screen_positions_x = NULL; processor->working_buffer.screen_positions_y = NULL; processor->working_buffer.world_normals_x = NULL; processor->working_buffer.world_normals_y = NULL; processor->working_buffer.world_normals_z = NULL; } processor->working_buffer.vertex_capacity = capacity; } Plt_Vertex_Processor_Result plt_vertex_processor_process_mesh(Plt_Vertex_Processor *processor, Plt_Linear_Allocator *allocator, Plt_Lighting_Setup lighting_setup, Plt_Mesh *mesh, Plt_Vector2i viewport, Plt_Matrix4x4f model, Plt_Matrix4x4f mvp) { unsigned int vertex_count = mesh->vertex_count; if (processor->working_buffer.vertex_capacity < vertex_count) { plt_vertex_processor_resize_working_buffer(processor, vertex_count); } // Input float *model_positions_x = mesh->position_x; float *model_positions_y = mesh->position_y; float *model_positions_z = mesh->position_z; float *model_uvs_x = mesh->uv_x; float *model_uvs_y = mesh->uv_y; float *model_normals_x = mesh->normal_x; float *model_normals_y = mesh->normal_y; float *model_normals_z = mesh->normal_z; // Output float *clipspace_x = plt_linear_allocator_alloc(allocator, sizeof(float) * vertex_count); float *clipspace_y = plt_linear_allocator_alloc(allocator, sizeof(float) * vertex_count); float *clipspace_z = plt_linear_allocator_alloc(allocator, sizeof(float) * vertex_count); float *clipspace_w = plt_linear_allocator_alloc(allocator, sizeof(float) * vertex_count); int *screen_positions_x = plt_linear_allocator_alloc(allocator, sizeof(int) * vertex_count); int *screen_positions_y = plt_linear_allocator_alloc(allocator, sizeof(int) * vertex_count); float *world_normals_x = plt_linear_allocator_alloc(allocator, sizeof(float) * vertex_count); float *world_normals_y = plt_linear_allocator_alloc(allocator, sizeof(float) * vertex_count); float *world_normals_z = plt_linear_allocator_alloc(allocator, sizeof(float) * vertex_count); float *lighting_r = plt_linear_allocator_alloc(allocator, sizeof(float) * vertex_count); float *lighting_g = plt_linear_allocator_alloc(allocator, sizeof(float) * vertex_count); float *lighting_b = plt_linear_allocator_alloc(allocator, sizeof(float) * vertex_count); for (unsigned int i = 0; i < vertex_count; ++i) { Plt_Vector4f input = { model_positions_x[i], model_positions_y[i], model_positions_z[i], 1.0f }; Plt_Vector4f clipspace = plt_matrix_multiply_vector4f(mvp, input); clipspace_x[i] = clipspace.x; clipspace_y[i] = clipspace.y; clipspace_z[i] = clipspace.z; clipspace_w[i] = clipspace.w; screen_positions_x[i] = ((clipspace.x / clipspace.w) * 0.5f + 0.5f) * viewport.x; screen_positions_y[i] = ((clipspace.y / clipspace.w) * 0.5f + 0.5f) * viewport.y; Plt_Vector4f input_normal = { model_normals_x[i], model_normals_y[i], model_normals_z[i], 0.0f }; Plt_Vector4f world_normal = plt_matrix_multiply_vector4f(model, input_normal); Plt_Vector3f normalized_world_normal = plt_vector3f_normalize((Plt_Vector3f){world_normal.x, world_normal.y, world_normal.z}); world_normals_x[i] = normalized_world_normal.x; world_normals_y[i] = normalized_world_normal.y; world_normals_z[i] = normalized_world_normal.z; // Apply lighting lighting_r[i] = lighting_setup.ambient_lighting.x; lighting_g[i] = lighting_setup.ambient_lighting.y; lighting_b[i] = lighting_setup.ambient_lighting.z; for (unsigned int j = 0; j < lighting_setup.directional_light_count; ++j) { float light_amount = plt_max(plt_vector3f_dot_product(normalized_world_normal, lighting_setup.directional_light_directions[j]), 0); Plt_Vector3f directional_lighting = plt_vector3f_multiply_scalar(lighting_setup.directional_light_amounts[j], light_amount); lighting_r[i] += directional_lighting.x; lighting_g[i] += directional_lighting.y; lighting_b[i] += directional_lighting.z; } } return (Plt_Vertex_Processor_Result) { .vertex_count = vertex_count, .clipspace_x = clipspace_x, .clipspace_y = clipspace_y, .clipspace_z = clipspace_z, .clipspace_w = clipspace_w, .screen_positions_x = screen_positions_x, .screen_positions_y = screen_positions_y, .model_uvs_x = model_uvs_x, .model_uvs_y = model_uvs_y, .world_normals_x = world_normals_x, .world_normals_y = world_normals_y, .world_normals_z = world_normals_z, .lighting_r = lighting_r, .lighting_g = lighting_g, .lighting_b = lighting_b }; }
C
//////////////////////////////////////////////////////////////////////////////// // senseye_serv_2.c // // University of Michigan // // Serves data from the stonyman imagers up to the host pc //////////////////////////////////////////////////////////////////////////////// // includes #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <time.h> #include <assert.h> #include <signal.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/socket.h> #include <arpa/inet.h> #include <fcntl.h> #include "stonyman_2.h" #include "senseye_defs.h" // Internal definitions #define STONY_DEVICE_FILENAME ("/dev/stonyman") // Function prototypes int request_data(); void transmit_data(); void send_mask(uint8_t cam_id); void send_frame(uint8_t cam_id); void terminate(int signum); // Global vars static uint8_t* img_buf; static uint16_t frame_resolution [NUM_CAMS]; static int stony_fd [NUM_CAMS]; static int sd; int main( ) { // Initialize descriptors int i; sd = -1; for (i=0; i<NUM_CAMS; i++) { stony_fd[i] = -1; } // Install signal handler signal(SIGINT, terminate); // start up the tcp socket sd = socket(AF_INET, SOCK_STREAM, 0); if (sd < 0) { perror("Socket creation failed"); exit(1); } // set socket options int optval = 1; if (setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) < 0) { perror("Could not set socket options"); exit(1); } // fill in socket details struct sockaddr_in saddr; memset(&saddr, 0, sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = htonl(INADDR_ANY); saddr.sin_port = htons(SENSEYE_PORT); // bind if (bind(sd, (struct sockaddr*)&saddr, sizeof(saddr)) < 0) { perror("Could not bind listening socket"); exit(1); } // listen fprintf(stderr, "Listening...\n"); if (listen(sd, 1) < 0) { perror("Listen call failed"); exit(1); } // malloc space for the image buffer, which holds a command plus a frame img_buf = (uint8_t*)malloc((HEADER_SIZE+MAX_FRAME_SIZE)*sizeof(uint8_t)); if (img_buf == NULL) { perror("Malloc of image buffer failed"); exit(1); } // Accept connection fprintf(stderr, "Accepting...\n"); socklen_t addrlen = sizeof(saddr); sd = accept(sd, (struct sockaddr*)&saddr, &addrlen); if (sd < 0) { perror("Accept of socket failed"); exit(1); } // Request an arbitrary amount of bytes larger than the GET packet fprintf(stderr, "Waiting for recv\n"); int ret_val = recv(sd, (void*)(&img_buf[0]), MAX_FRAME_SIZE, 0); if (ret_val < 0) { perror("Recv GET packet failed"); exit(1); } // Null terminate the string img_buf[MAX_FRAME_SIZE] = '\0'; // Search for the GET request uint8_t* ret_str = strstr(img_buf, "GET"); if (ret_str != NULL) { // GET request was found fprintf(stderr, "Good Request!\n"); transmit_data(); } // How did we get here? This is an error return -1; } void transmit_data( ) { // Open and start camera devices int i; fprintf(stderr, "Opening devices...\n"); for (i=0; i<NUM_CAMS; i++) { // Set device filename uint8_t dev_name [15]; sprintf(dev_name, "%s%d", STONY_DEVICE_FILENAME, i); dev_name[14] = '\0'; // for safety // Open device stony_fd[i] = open(dev_name, O_RDWR, NULL); if (stony_fd[i] < 0) { perror("Couldn't open stonyman device"); exit(1); } // Set mask values send_mask(i); } // Start the camera fprintf(stderr, "Starting cameras\n"); if (ioctl(stony_fd[0], STONYMAN_IOC_GLOBAL_START) < 0) { perror("Could not start stonyman driver"); exit(1); } // Read from both cameras and transmit data to client while (1) { //Shows how many frames are sent fprintf(stderr, "Sending frames before\n"); send_frame(0); fprintf(stderr, "Sent frames 0\n"); //commented out because both cameras are not connected send_frame(1); fprintf(stderr, "Sent frames 1\n"); } } void send_mask(uint8_t cam_id) { //TODO: Set mask values in controller // Save expected resolution frame_resolution[cam_id] = (112*112); //TODO: Send mask values to client } static int send0_counts = 0; static int send1_counts = 0; void send_frame(uint8_t cam_id) { // Read data from the device fprintf(stderr, "Reading frame from cam[%d], fd=%d\n", cam_id, stony_fd[cam_id]); int px_read = 0; while (px_read < frame_resolution[cam_id]) { int ret_val = read(stony_fd[cam_id], &(img_buf[HEADER_SIZE]), frame_resolution[cam_id]); if (ret_val < 0) { perror("Couldn't read from stonyman device"); // Shut down cameras and exit terminate(0); } /*fprintf(stderr, "%d ,", img_buf[HEADER_SIZE + 1] ); fprintf(stderr, "%d , ", img_buf[HEADER_SIZE + 150] ); fprintf(stderr, "%d ,", img_buf[HEADER_SIZE + 1000] ); fprintf(stderr, "%d \n", img_buf[HEADER_SIZE + 8000] );*/ px_read += ret_val; /*fprintf(stderr, "Px_read val: %d, ", px_read); fprintf(stderr, "Ret val: %d, ", ret_val); fprintf(stderr, "frame_res: %d, \n", frame_resolution[cam_id]);*/ } if (cam_id == 0) { fprintf(stderr, "Cam 0 id increment\n"); send0_counts++; } else { fprintf(stderr, "Cam 1 id increment\n"); send1_counts++; } // Setup frame header img_buf[SYMBOL_INDEX] = SYMBOL_SOF; img_buf[OPCODE_INDEX] = CTL_CAMX_FRAME(cam_id); img_buf[SIZE_MSB_INDEX] = ((frame_resolution[cam_id] >> 8) & 0xFF); img_buf[SIZE_LSB_INDEX] = ((frame_resolution[cam_id] >> 0) & 0xFF); // Transmit data to client fprintf(stderr, "Sending frame\n"); int ret_val = send(sd, (void*)img_buf, (HEADER_SIZE+MAX_FRAME_SIZE), MSG_NOSIGNAL); if (ret_val != (HEADER_SIZE+MAX_FRAME_SIZE)) { if (ret_val < 0 && errno == EPIPE) { fprintf(stderr, "Socket closed\n"); fprintf(stderr, "Cam[0]: %d\tCam[1]: %d\n", send0_counts, send1_counts); terminate(0); } else { perror("Send to client failed"); fprintf(stderr, "Cam[0]: %d\tCam[1]: %d\n", send0_counts, send1_counts); terminate(0); } } } void terminate(int signum) { int i; // Stop driver if (stony_fd[0] != -1) { ioctl(stony_fd[0], STONYMAN_IOC_GLOBAL_STOP); } // Print off statistics ioctl(stony_fd[0], STONYMAN_IOC_STATISTICS); // Close descriptors for (i=0; i<NUM_CAMS; i++) { if (stony_fd[i] != -1) { close(stony_fd[i]); } stony_fd[i] = -1; } // Close socket if (sd != -1) { close(sd); } sd = -1; exit(1); }
C
#include<stdio.h> int main() { int a,b; scanf("%d",&a); b=a^a; printf("power of no=%d",b); return 0; }
C
/** * Implement int sqrt(int x). * Compute and return the square root of x, where x is guaranteed to be a * non-negative integer. Since the return type is an integer, the decimal * digits are truncated and only the integer part of the result is returned. * * Example: * Input: 8 * Output: 2 * * 实现求平方根,注意返回结果要截断为整数.基本思想是利用牛顿迭代法.不过有一种快速 * 求平方根的方法利用了一个magic number,使得收敛的速度巨增从而提高了计算速度. * 先来看看牛顿迭代法的基本思想:要求一个正整数a的平方根,也就是求解方程x^2-a=0 * 的正根.牛顿迭代法的基础是泰勒级数,令f(x)=x^2-a,要求解f(x)=0的根,我们利用f(x) * 泰勒展开的一次项,忽略高阶项,得到f(x)=f(x0)+f'(x0)(x-x0).于是问题转换为求解 * f(x0)+f'(x0)(x-x0)=0的解,这样的得到的结果往往不够精确,重复迭代可以缩小误差. * 例如求解x^2 = 10的解(3.1622776601683793319988935444327). * 任意选取x0=5,于是25-10+10(x-5)=0,得到x1=3.5,将x1代入公式 * X_n+1 = (Xn*Xn + a) / (2*Xn),得到x2≈3.17,...,x3=3.162. * 可以发现已经很接近答案. * 关于初始值的选取,上面的计算过程是简单的取了原值的二分之一,但有一种非常快速的 * 方法,详细的内容可以Google搜索fast inverse square root. * https://en.wikipedia.org/wiki/Fast_inverse_square_root * https://blog.csdn.net/qq_21201963/article/details/80174155 */ int mySqrt(int x) { double x0, x1; /* 这里如果是float类型,若x=2147395599则得到错误结果. */ if (x <= 0) return 0; x0 = x; x1 = (x0 + 1) / 2; /* 因为返回结果为截断的整数,这里的精度控制为0.9就可以了. */ while (x0 - x1 > 0.9 || x0 - x1 < -0.9) { x0 = x1; x1 = (x0 + x / x0) / 2; } return (int)x1; } /** * 上述代码可以简化. */ int mySqrt(int x) { long long ans; /* 防止下面计算平方时溢出. */ ans = x; while (ans * ans > x) ans = (ans + x / ans) / 2; return (int)ans; } /** * 用double来保存平方,用一个变量保存中间值避免计算两次平方. */ int mySqrt(int x) { double ans, tmp; /* 防止下面计算平方时溢出. */ ans = x; tmp = ans * ans; while (tmp - x > 0.9 || tmp - x < -0.9) { ans = (ans + x / ans) / 2; tmp = ans * ans; } return (int)ans; }
C
#include <unistd.h> #include <stdio.h> #include "SDL.h" #include "ourtypes.h" #include "things.h" #include "network.h" #include "main.h" #include "input.h" void input(){ SDL_Event event; if (players[playerno]) key_input(); else if (SDL_PollEvent(&event) && event.type == SDL_QUIT) mode = EXIT; if (playerno){ /* nonzero playerno is client */ broadcast(host, playerno); get_server_output(); } else if (num_clients){ /* 0 playerno is host */ get_client_input(); broadcast_all(); } } void key_input(){ SDL_Event event; player *pl = players[playerno]; pl->prev_jump = pl->jump; pl->prev_attack = pl->attack; while (SDL_PollEvent(&event) ) switch (event.type){ case SDL_QUIT: mode = EXIT; return; case SDL_KEYDOWN: switch (event.key.keysym.sym){ case SDLK_z: pl->attack = 1; break; case SDLK_x: pl->jump = 1; break; case SDLK_UP: pl->u = 1; break; case SDLK_DOWN: pl->d = 1; break; case SDLK_LEFT: pl->l = 1; break; case SDLK_RIGHT: pl->r = 1; default: break; } break; case SDL_KEYUP: switch (event.key.keysym.sym){ case SDLK_z: pl->attack = 0; break; case SDLK_x: pl->jump = 0; break; case SDLK_UP: pl->u = 0; break; case SDLK_DOWN: pl->d = 0; break; case SDLK_LEFT: pl->l = 0; break; case SDLK_RIGHT: pl->r = 0; default: break; } default: break; } } void get_server_output(){ int i; for (i = 0; i < num_clients; i++) update_player(host); } void update_player(int sd){ player *pl; net_input ni; read(sd, &ni, sizeof(ni) ); if (!playerno && clients[ni.playerno - 1] < 0) return; /* host: discard messages from nonexistent clients */ pl = players[ni.playerno]; if (ni.exit){ if (pl){ free(pl->p.att); /* remember to destroy attack! */ free(pl); players[ni.playerno] = NULL; num_players--; } if (ni.playerno){ if (!playerno){ /* host ends connection with exiting client */ close(clients[ni.playerno - 1]); clients[ni.playerno - 1] = EMPTY_FD; } num_clients--; } else{ printf("Host ended the game.\n"); mode = EXIT; /* game ends if host quits */ } return; } if (!pl) return; pl->prev_attack = pl->attack; pl->prev_jump = pl->jump; pl->attack = ni.attack; pl->jump = ni.jump; pl->u = ni.u; pl->d = ni.d; pl->l = ni.l; pl->r = ni.r; } void broadcast(int sd, int pno){ net_input ni; player *pl; pl = players[pno]; ni.playerno = pno; ni.exit = (mode == EXIT); if (pl){ ni.attack = pl->attack; ni.jump = pl->jump; ni.u = pl->u; ni.d = pl->d; ni.l = pl->l; ni.r = pl->r; } write(sd, &ni, sizeof(ni) ); } void get_client_input(){ int i; for (i = 0; i < MAX_CLIENTS; i++) if (clients[i] > 0) update_player(clients[i]); } void broadcast_all(){ int i, j; for (i = 0; i < MAX_CLIENTS; i++) if (clients[i] > 0) for (j = 0; j < MAX_PLAYERS; j++) if (!j || (clients[j - 1] > 0 && i != j - 1) ) broadcast(clients[i], j); }
C
typedef struct{ char *nam; FILE *ptr; } FileWithName; #define COMMENTS_LEN 10000 #define LINE_LEN 200 int WhichBin_Float(float x, float *b, int n); int WhichBin_Double(double x, double *b, int n); FILE *Open(char *filename, char *mode); char *ReadComments(FILE *fp_in); char *ReadAndWriteComments(FILE *fp_in, FILE *fp_out); void Printf(char *string); void ShowTime(); void PrintCommandLine(FILE *f, int argc, char **argv); int **AllocateRectangularMatrix_Int(int dim1, int dim2); float **AllocateRectangularMatrix_Float(int dim1, int dim2); double **AllocateRectangularMatrix_Double(int dim1, int dim2); char **AllocateRectangularMatrix_Char(int dim1, int dim2); int CountLinesRemainingInFile(FILE *fp); int CountLengthToEndOfCurrentLine(FILE *fp); int Amino(char s); char AminoChar(int i); FILE *DrawLine(FILE *fp); FILE *TimeStamp(FILE *fp); int IsLetter(char c); char UpperCase(char c); char LowerCase(char c); char *UpperCase_String(char *s); char *LowerCase_String(char *s); int RemoveBlanks(char *s); int amino_util[]={1,0,2,3,4,5,6,7,8,0,9,10,11,12,0,13,14,15,16,17,0,18,19,0,20,0}; /*----------------------------------------------------------------*/ int WhichBin_Float(float x, float *b, int n) { int i,low=0,high=n; if (x > b[n] || x < b[0]) return -1; while (high-low > 1){ i = (high+low)/2; if (x <= b[i]) high = i; else low = i; } return low; } /*----------------------------------------------------------------*/ int WhichBin_Double(double x, double *b, int n) { int i,low=0,high=n; if (x > b[n] || x < b[0]) return -1; while (high-low > 1){ i = (high+low)/2; if (x <= b[i]) high = i; else low = i; } return low; } /*----------------------------------------------------------------*/ FILE *Open(char *filename, char *mode) { FILE *fp; if ((fp=fopen(filename,mode))==NULL){ printf("Can't open %s !\n",filename); exit(1); } return fp; } /*----------------------------------------------------------------*/ char *ReadComments(FILE *fp_in) { long current; char line[LINE_LEN],*comments; comments = malloc(COMMENTS_LEN*sizeof(char)); *comments='\0'; current = ftell(fp_in); fgets(line,LINE_LEN,fp_in); while (*line=='%' || *line=='#'){ strcat(comments,line); current = ftell(fp_in); fgets(line,LINE_LEN,fp_in); } fseek(fp_in,current,SEEK_SET); return comments; } /*----------------------------------------------------------------*/ char *ReadAndWriteComments(FILE *fp_in, FILE *fp_out) { long current; char line[LINE_LEN],*comments; comments = malloc(COMMENTS_LEN*sizeof(char)); *comments='\0'; current = ftell(fp_in); fgets(line,LINE_LEN,fp_in); while (*line=='%' || *line=='#'){ strcat(comments,line); current = ftell(fp_in); fgets(line,LINE_LEN,fp_in); } fseek(fp_in,current,SEEK_SET); fprintf(fp_out,"%s",comments); return comments; } /*----------------------------------------------------------------*/ void Printf(char *string) { printf("%s",string); fflush(stdout); } /*----------------------------------------------------------------*/ void ShowTime() { system("date +\"\t\t\t\t\t%a %b %d %Y %T\""); fflush(stdout); } /*----------------------------------------------------------------*/ void PrintCommandLine(FILE *f, int argc, char **argv) { int i; fprintf(f,"#"); for (i=0;i<argc;i++) fprintf(f," %s",argv[i]); fprintf(f,"\n"); fflush(f); } /*----------------------------------------------------------------*/ int **AllocateRectangularMatrix_Int(int dim1, int dim2) { int s,t; int **matrix; matrix = malloc(dim1*sizeof(int *)); for (s=0;s<dim1;s++){ matrix[s] = malloc(dim2*sizeof(int)); for (t=0;t<dim2;t++) matrix[s][t] = 0; } return matrix; } /*----------------------------------------------------------------*/ float **AllocateRectangularMatrix_Float(int dim1, int dim2) { int s,t; float **matrix; matrix = malloc(dim1*sizeof(float *)); for (s=0;s<dim1;s++){ matrix[s] = malloc(dim2*sizeof(float)); for (t=0;t<dim2;t++) matrix[s][t] = 0.; } return matrix; } /*----------------------------------------------------------------*/ double **AllocateRectangularMatrix_Double(int dim1, int dim2) { int s,t; double **matrix; matrix = malloc(dim1*sizeof(double *)); for (s=0;s<dim1;s++){ matrix[s] = malloc(dim2*sizeof(double)); for (t=0;t<dim2;t++) matrix[s][t] = 0.; } return matrix; } /*----------------------------------------------------------------*/ char **AllocateRectangularMatrix_Char(int dim1, int dim2) { int s,t; char **matrix; matrix = malloc(dim1*sizeof(char *)); for (s=0;s<dim1;s++){ matrix[s] = malloc(dim2*sizeof(char)); for (t=0;t<dim2;t++) matrix[s][t] = '\0'; } return matrix; } /*----------------------------------------------------------------*/ int CountLinesRemainingInFile(FILE *fp) { int nl=0; char c; long offset; offset = ftell(fp); while ( (c=fgetc(fp)) != EOF) if (c=='\n') nl++; fseek(fp,offset,SEEK_SET); return nl; } /*----------------------------------------------------------------*/ int CountLengthToEndOfCurrentLine(FILE *fp) { int len=0; char c; long offset; offset = ftell(fp); c = fgetc(fp); while ( c!=EOF && c!='\n'){ len++; c = fgetc(fp); } fseek(fp,offset,SEEK_SET); return len; } /*----------------------------------------------------------------*/ int Amino(char s) { int i; i = s-'A'; if (i>=0 && i<26) return amino_util[i]; else return 0; } /*----------------------------------------------------------------*/ char AminoChar(int i) { int j; if (i<1 || i>20) return 'X'; for (j=0; j<26; j++) if (amino_util[j]==i) return 'A'+j; } /*----------------------------------------------------------------*/ FILE *DrawLine(FILE *fp) { int i,length=70; char *line,c='-'; line = malloc((length+2)*sizeof(char)); for (i=0;i<length;i++) line[i]=c; line[i++] = '\n'; line[i++] = '\0'; fprintf(fp,"%s",line); free(line); return fp; } /*----------------------------------------------------------------*/ FILE *TimeStamp(FILE *fp) { time_t *tp; tp = malloc(sizeof(time_t)); time(tp); fprintf(fp,"\t\t\t\t\t%s",asctime(localtime(tp))); fflush(fp); free(tp); return fp; } /*----------------------------------------------------------------*/ int IsLetter(char c) { int u,l; u = c-'A'; if (u>=0 && u<26) return u+1; l = c-'a'; if (l>=0 && l<26) return -l-1; return 0; } /*----------------------------------------------------------------*/ char UpperCase(char c) { if (c-'A'>=0 && c-'A'<26) return c; else if (c-'a'>=0 && c-'a'<26) return c+'A'-'a'; else return c; } /*----------------------------------------------------------------*/ char LowerCase(char c) { if (c-'A'>=0 && c-'A'<26) return c+'a'-'A'; else if (c-'a'>=0 && c-'a'<26) return c; else return c; } /*----------------------------------------------------------------*/ char *UpperCase_String(char *s) { int i=-1; while (s[++i]!='\0') s[i] = UpperCase(s[i]); return s; } /*----------------------------------------------------------------*/ char *LowerCase_String(char *s) { int i=-1; while (s[++i]!='\0') s[i] = LowerCase(s[i]); return s; } /*----------------------------------------------------------------*/ int RemoveBlanks(char *s) { int n_blanks=0,i=0,j; while (i<strlen(s)){ if (s[i]==' '){ for (j=i;j<strlen(s)-1;j++) s[j]=s[j+1]; s[j]='\0'; n_blanks++; } else i++; } return n_blanks; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #define SIZE_A 10 #define SIZE_B 20 void populate_array(int array[], int size); void print_array(int array[], int size); /* * 1. გამოაცხადეთ ორი სხვადასხვა ზომის მასივი და დაწერეთ ფუნქცია, რომელიც * შეავსებს ამ მასივის ელემენტებს მნიშვნელობებით და აჩვენებს ეკრანზე. ფუნქციამ * უნდა მიიღოს ორი პარამეტრი - მასივი და მისი ზომა. */ int main() { int array_a[SIZE_A], array_b[SIZE_B]; srand(time(NULL)); populate_array(array_a, SIZE_A); print_array(array_a, SIZE_A); populate_array(array_b, SIZE_B); print_array(array_b, SIZE_B); exit(EXIT_SUCCESS); } void populate_array(int array[], int size) { for (int index = 0; index < size; index++) { array[index] = rand(); } } void print_array(int array[], int size) { printf("Printing the contents of the array located at address %p: ", array); for (int index = 0; index < size; index++) { printf("%d ", array[index]); } printf("\n"); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_char.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dpeyrat <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/12/03 14:00:14 by dpeyrat #+# #+# */ /* Updated: 2020/12/03 14:00:16 by dpeyrat ### ########.fr */ /* */ /* ************************************************************************** */ #include "../ft_printf.h" void ft_setminmaxchar(int *min, int *max, char *flags) { int i; i = 0; if (!(*min)) { while (!ft_isdigit0(flags[i]) && flags[i] != '.' && flags[i] != 0) i++; if (flags[i] != '.' && flags[i] != 0) *min = ft_atoi(&flags[i]); } while (flags[i] != '.' && flags[i] != 0) i++; if (!(*max) && flags[i] == '.') *max = ft_atoi(&flags[i + 1]); if (ft_contains(flags, '-') && *min > 0 && flags[i + 1] != '*') *min = *min * -1; } void ft_va_argchar(int *m, int *a, va_list *ap, char *f) { int i; i = 0; while (f[i] && f[i] != '.' && f[i] != '*') i++; if (f[i] == '*') *m = va_arg(*ap, int); while (f[i] != '.' && f[i]) i++; if (f[i] == '.') { i++; if (f[i] == '*') *a = va_arg(*ap, int); } } int ft_display_char(char c, char *flags, int min, int max) { int tern; tern = 1; if (max != 0) tern = max; if (ft_contains(flags, '0') && min > 0) ft_writexchar(min - tern, '0'); else if (min > 0) ft_writexchar(min - tern, ' '); ft_writexchar(max - 1, '0'); ft_putchar(c); if (min < 0) ft_writexchar(-min - tern, ' '); free(flags); if (min > 0 && min >= tern) return (min); else if (min < 0 && (0 - min) >= tern) return (-min); return (tern); } int ft_char(int c, char *str, va_list *ap) { int i; char *flags; int min; int max; i = 0; min = 0; max = 0; str = find_start_conversion(str, &i); flags = ft_substr(str, 1, i); if (!flags) return (-1); ft_va_argchar(&min, &max, ap, flags); c = va_arg(*ap, int); ft_setminmaxchar(&min, &max, flags); ft_removefield(flags); return (ft_display_char((char)c, flags, min, max)); }
C
#include <stdio.h> struct date { int day; int month; int year; } date[2]; int N (struct date *p); int main (void) { struct date *p = date; int i= 0; printf("Enter both dates of which you want to know the elapsed time (dd.mm.yyyy):\n1st date: "); while(p < date + 2){ scanf("%d.%d.%d", &date[i].day, &date[i].month, &date[i].year); p++; i++; if (i < 2) printf("2nd date: "); } p = date; printf("Elapsed time: %d days.\n", N(p)); return 0; } int N (struct date *p) { int dif = 0, count = 0; while(p < date + 2){ if((*p).month <= 2){ (*p).year -= 1; (*p).month += 13; } else (*p).month += 1; if (count == 0) dif -= ((1461 * (*p).year) / 4 + (153 * (*p).month) /5 + (*p).day); else dif += ((1461 * (*p).year) / 4 + (153 * (*p).month) /5 + (*p).day); count++; p++; } return dif; }
C
/* ** my_find_prime_sup.c for my_find_prime_sup in /home/boitea_r ** ** Made by Ronan Boiteau ** Login <boitea_r@epitech.net> ** ** Started on Sun Oct 18 18:50:14 2015 Ronan Boiteau ** Last update Thu Dec 17 23:38:47 2015 Ronan Boiteau */ #include "my.h" int my_find_prime_sup(int nbr) { while (my_is_prime(nbr) != 1) nbr += 1; return (nbr); }
C
#include <stdio.h> int main() { int n,m; while( scanf("%d %d", &n,&m)!=EOF){ printf("%d\n",n^m); } return 0; }
C
#include <stdio.h> typedef struct STnode* link; struct STnode {item b[M]; int m; int k;}; static link *dir; static int d, D, N; link NEW(){ link x = malloc(sizeof *x); x->m = 0; x->k = 0; return x; } void STinit(int maxN){ d= 0; N = 0; D = 1; dir = malloc(D*(sizeof(*dir))); dir[0] = NEW(); } Item search(lin h, Key v){ int j; for(j = 0; j < h->m; j++) if(eq(v, key(h->b[j]))) return h->b[j]; return NULLitem; } link split(link h){ int j; link t = NEW(); while(h->m == 0 || h->m == M){ h->m = 0; t->m = 0; for(j = 0; j< M; j++) if(bits(h->b[j], h->k, 1) == 0) h->b[(h->m)++] = h->b[j]; else t->b[(t->m)++] = h->b[j]; t->k = ++(h->k); } insertDir(t, t->k); } void insert(link h, Item item){ int i, j; Key v = key(item); for(j =0; j < h->m; ++j) if(less(v, key(h->b[j]))) break; for(i = (h->m)++; i> j; i--) h->b[i] = h->b[i-1]; h->b[j] = item; if(h->m == M) split(h); } void insertDir(link t, int k){ int i, m, x= bits(t->b[0], 0, k); while(d < k){ link* old = dir; d += 1; D +=D; dir = malloc(D*sizeof(*dir)); for(i = 0; i < D; ++i) dir[i] = old[i/2]; if(d < k) dir(bits(x, 0, d) ^ 1) = NEW(); } for(m = 1; k <d; ++k) m *= 2; for(i = 0; i < m; i++) dir[x*m+1] = t; }
C
#include <SDL.h> #include <SDL_image.h> #include <SDL_mixer.h> #include <SDL_ttf.h> #include <stdlib.h> #include <math.h> #include <time.h> #define SCREEN_W 800 #define SCREEN_H 600 #define GRAVIDADE 1 #define SALTO 20 #define IMAGENS 8 #define ATUALIZACAO 10 typedef struct _FIGURA { SDL_Surface* imagem; SDL_Rect coordenadas; SDL_Rect origem; }FIGURA; typedef struct _TEXTO { TTF_Font* fonte; SDL_Surface* imagem; SDL_Rect coordenadas; SDL_Color cor; char mensagem[10]; int tamanho; }TEXTO; /*Variaveis essenciais do SDL*/ SDL_Surface* screen; Uint32 cor_fundo; SDL_Event event; /*Variaveis Globais necessarias para as fases*/ Mix_Music* musica; SDL_Surface* pivete; SDL_Rect coordenadas; SDL_Surface* bancoImagem[IMAGENS]; TEXTO placar; float velocidadeVertical; float velocidadeHorizontal; unsigned int distancia; int ultimaAtualizacao; int altura; int espacamento; FIGURA plataforma[2]; SDL_Surface* CriaTexto(char* txt, int tam, SDL_Color cor) { /*pega um texto e transforma ele numa superficie para ser impressa na tela*/ TTF_Font* fonte; SDL_Surface* texto; fonte = TTF_OpenFont("adler.ttf", tam); texto = TTF_RenderText_Solid(fonte, txt, cor); return texto; } void AtualizaPlacar(void) { SDL_FreeSurface(placar.imagem); sprintf(placar.mensagem, "%u", distancia); placar.imagem = CriaTexto(placar.mensagem,placar.tamanho,placar.cor); placar.coordenadas.x = SCREEN_W - placar.imagem->w-50; placar.coordenadas.y = 50; placar.coordenadas.w = 0; placar.coordenadas.h = 0; } int Colide(void) { int diferenca,i; for(i=0;i<2;i++) { /*retorna 1 se houve colisao vertical, porem tambem trabalha com colisoes horizontais*/ if ((coordenadas.y+coordenadas.h>=plataforma[i].coordenadas.y) && (coordenadas.x<=plataforma[i].coordenadas.x+plataforma[i].coordenadas.w) && (coordenadas.x+coordenadas.w>=plataforma[i].coordenadas.x)) { /*sei que estou abaixo de uma plataforma, agora verifico se estou no chao, com uma margem de erro*/ if ((coordenadas.y+coordenadas.h>=plataforma[i].coordenadas.y) && (coordenadas.y+coordenadas.h <= plataforma[i].coordenadas.y+30)) { /*trava a figura em cima da plataforma que ela colidiu*/ diferenca=coordenadas.y+coordenadas.h-plataforma[i].coordenadas.y; plataforma[0].coordenadas.y+=diferenca; plataforma[1].coordenadas.y+=diferenca; velocidadeVertical=0; return 1; } else { /*esse eh pro caso de ter batido fora do chao. Gera um bug interessante que reduz a velocidade horizontal quando o personagem bate bem na quina*/ velocidadeHorizontal=0; plataforma[i].coordenadas.x=coordenadas.x+coordenadas.w; } } } return 0; } void Movimentacao(int tempo) { /*ignora a variavel tempo, por enquanto*/ /*faz toda a parte de deslocamento do cenario*/ if (!Colide()) { /*Trabalha queda essa parte*/ velocidadeVertical+=GRAVIDADE*tempo; plataforma[0].coordenadas.y-=velocidadeVertical*tempo; plataforma[1].coordenadas.y=plataforma[0].coordenadas.y + altura; } else { velocidadeHorizontal+=0.007*tempo;/*acelera se estiver no solo*/ } /*Calcula a distancia percorida*/ distancia+=velocidadeHorizontal*tempo; /*desloca as plataformas ou reduz seus tamanhos se suas coordenadas X forem zero*/ if ((plataforma[0].coordenadas.x<=0) && (plataforma[0].origem.x<plataforma[0].origem.w)) { plataforma[0].origem.x+=velocidadeHorizontal*tempo; } else { plataforma[0].coordenadas.x-=velocidadeHorizontal*tempo; } /*desloca a plataforma 1*/ plataforma[1].coordenadas.x=plataforma[0].coordenadas.x+plataforma[0].coordenadas.w + espacamento; /*ultimaAtualizacao=SDL_GetTicks();*/ } void Cenario(void) { /*Carrega o cenario*/ SDL_FreeSurface(screen); SDL_FillRect(screen,NULL,cor_fundo); SDL_BlitSurface(pivete, NULL, screen, &coordenadas); SDL_BlitSurface(plataforma[0].imagem,&plataforma[0].origem,screen, &plataforma[0].coordenadas); SDL_BlitSurface(plataforma[1].imagem,&plataforma[1].origem,screen, &plataforma[1].coordenadas); /*Carrega HUD*/ SDL_BlitSurface(placar.imagem, NULL, screen, &placar.coordenadas); } int inicializaJogo(void){ srand(time(NULL)); velocidadeVertical=2.0; velocidadeHorizontal=5.0; distancia=0; SDL_FreeSurface(screen); /*Por enquanto é inutil ultimaAtualizacao=SDL_GetTicks();*/ /*ja começa no pior caso pra testa*/ altura=SALTO*SALTO/-2*GRAVIDADE; espacamento=velocidadeHorizontal*30; /*carrega cor e o tamanho do placar*/ placar.tamanho=30; placar.cor.r= 255; placar.cor.g= 200; placar.cor.b= 0; /*Imagens disponiveis para as plataformas*/ bancoImagem[0]=IMG_Load("vermelhinho.png"); bancoImagem[1]=IMG_Load("bandejao.png"); bancoImagem[2]=IMG_Load("fau.png"); bancoImagem[3]=IMG_Load("ccmn.png"); bancoImagem[4]=IMG_Load("ct.png"); bancoImagem[5]=IMG_Load("hu.png"); bancoImagem[6]=IMG_Load("mangue.png"); bancoImagem[7]=IMG_Load("petrobras.png"); /*coordenadas iniciais da primeira plataforma*/ plataforma[0].imagem=bancoImagem[rand()%IMAGENS]; plataforma[0].coordenadas.x=100; plataforma[0].coordenadas.y=200; plataforma[0].coordenadas.w=0; plataforma[0].coordenadas.h=0; plataforma[0].origem.x=0; plataforma[0].origem.y=0; plataforma[0].origem.w=plataforma[0].imagem->w; plataforma[0].origem.h=plataforma[0].imagem->h; /*coordenadas iniciais do "pivete", baseado na posicao da plataforma 0*/ pivete=IMG_Load("img.png"); coordenadas.w=pivete->w; coordenadas.h=pivete->h; coordenadas.x=plataforma[0].coordenadas.x-coordenadas.w; coordenadas.y=plataforma[0].coordenadas.y-coordenadas.h; SDL_BlitSurface(pivete,NULL,screen, &coordenadas); /*posicao inicial da plataforma 1, de acordo com os valores de espacamento e altura relativo a plataforma 0*/ plataforma[1].imagem=bancoImagem[rand()%5]; plataforma[1].coordenadas.x=plataforma[0].coordenadas.x+plataforma[0].origem.w+espacamento; plataforma[1].coordenadas.y=plataforma[0].coordenadas.y+altura; plataforma[1].coordenadas.w=0; plataforma[1].coordenadas.h=0; plataforma[1].origem.x=0; plataforma[1].origem.y=0; plataforma[1].origem.w=plataforma[1].imagem->w; plataforma[1].origem.h=plataforma[1].imagem->h; return 0; } int EmcimaFigura(FIGURA fig) { /*usando as coordenadas do parametro, essa funcao retorna 1 se o mouse esta em cima da figura e 0 caso contrario*/ if (event.button.x>=fig.coordenadas.x && event.button.x<=fig.coordenadas.x+fig.imagem->w && event.button.y>=fig.coordenadas.y && event.button.y<=fig.coordenadas.y+fig.imagem->h) return 1; return 0; } int Menu (void) { /*essa funcao coloca o menu inicial na tela e retorna 1 se for para o programa fechar*/ int sai=0; FIGURA comecar, cenario, sair; SDL_Color cor={200,65,55}; comecar.imagem=CriaTexto("CORRER!!", 70, cor); comecar.coordenadas.x=100; comecar.coordenadas.y=200; comecar.coordenadas.w=0; comecar.coordenadas.h=0; sair.imagem=CriaTexto("SAIR", 70, cor); sair.coordenadas.x=300; sair.coordenadas.y=400; sair.coordenadas.w=0; sair.coordenadas.h=0; cenario.imagem=IMG_Load("abertura.png"); cenario.coordenadas.x=0; cenario.coordenadas.y=0; cenario.coordenadas.w=0; cenario.coordenadas.h=0; SDL_FreeSurface(screen); SDL_BlitSurface(cenario.imagem,NULL,screen, &cenario.coordenadas); SDL_BlitSurface(comecar.imagem,NULL,screen, &comecar.coordenadas); SDL_BlitSurface(sair.imagem,NULL,screen, &sair.coordenadas); SDL_BlitSurface(placar.imagem,NULL,screen, &placar.coordenadas); SDL_Flip(screen); while(!sai) { while (SDL_PollEvent(&event)) { if (event.type==SDL_QUIT) return 1; if (event.type==SDL_KEYDOWN) { if(event.key.keysym.sym==SDLK_RETURN) { sai=1; break; } } if (event.type==SDL_MOUSEBUTTONDOWN) { if(EmcimaFigura(comecar)) { inicializaJogo(); sai=1; } if(EmcimaFigura(sair)) return 1; } } } SDL_FreeSurface(comecar.imagem); SDL_FreeSurface(sair.imagem); SDL_FreeSurface(cenario.imagem); return 0; } int Pause(void) { int sai=0; /*parte do codigo responsavel por escreve PAUSE na tela*/ SDL_Color cor={255,0,0}; SDL_Surface* imagemPause= CriaTexto("PAUSE", 100, cor); SDL_Rect posicaoPause={SCREEN_W/2-imagemPause->w/2,SCREEN_H/2-imagemPause->h/2,0,0}; SDL_BlitSurface(imagemPause, NULL, screen, &posicaoPause); SDL_Flip(screen); while (!sai) { while (SDL_PollEvent(&event)) { if (event.type==SDL_QUIT) return 1; if (event.type==SDL_KEYDOWN) { if(event.key.keysym.sym==SDLK_RETURN) { sai=1; break; } } } } SDL_FreeSurface(imagemPause); return 0; } void GameOver(void) { } void ReciclaPlataforma(void) { /*segredo de todo o jogo e seus bugs, as 2 plataformas sao modificadas nessa funçao*/ plataforma[0]=plataforma[1]; /*pelas minhas contas, essa eh a altura maxima que o objeto alcança, a distancia foi chutando valores mesmo...*/ altura= pow(-1, rand() % 2) * (rand() % SALTO*SALTO/2*GRAVIDADE); espacamento= velocidadeHorizontal*10 + rand() % (int)velocidadeHorizontal*20; /*sorteia uma imagem das disponiveis*/ plataforma[1].imagem=bancoImagem[rand()%IMAGENS]; /*posiciona a imagem seguinte de acordo com os valores sorteados*/ plataforma[1].coordenadas.x=plataforma[0].coordenadas.x+plataforma[0].coordenadas.w +espacamento; plataforma[1].coordenadas.y=plataforma[0].coordenadas.y + altura; plataforma[1].coordenadas.w=0; plataforma[1].coordenadas.h=0; plataforma[1].origem.x=0; plataforma[1].origem.y=0; plataforma[1].origem.w=plataforma[1].imagem->w; plataforma[1].origem.h=plataforma[1].imagem->h; } int main (int argc, char** argv) { int quit=0,onMenu=1; /*inicializa video e audio*/ SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER); TTF_Init(); screen=SDL_SetVideoMode(SCREEN_W, SCREEN_H, 16, SDL_SWSURFACE|SDL_DOUBLEBUF|SDL_HWSURFACE); /*configura janela*/ Mix_OpenAudio(22050,MIX_DEFAULT_FORMAT , 2, 1024); //inicializar SDL_mixer Mix_AllocateChannels(1); musica = Mix_LoadMUS("music.MP3"); cor_fundo=SDL_MapRGB(screen->format, 150, 200, 98); /*cor de fundo*/ while (!quit) { if (onMenu) { if (Menu()) quit++; SDL_FreeSurface(screen); onMenu=0; Mix_PlayMusic(musica, -1);//tocar a musica } else { while(SDL_PollEvent(&event)) /*Fila de eventos*/ { switch(event.type) { case SDL_QUIT: quit++; break; case SDL_KEYDOWN: if (event.key.keysym.sym==SDLK_SPACE && velocidadeVertical==0) { velocidadeVertical=-SALTO; plataforma[0].coordenadas.y++; plataforma[1].coordenadas.y++; } /*Pausa o jogo quando der Enter*/ if (event.key.keysym.sym==SDLK_RETURN) { Mix_PauseMusic(); if (Pause()) quit ++; Mix_ResumeMusic(); } if (event.key.keysym.sym==SDLK_ESCAPE) { quit=1; } } } AtualizaPlacar(); SDL_Delay(10); Movimentacao(1); Cenario(); if (plataforma[0].origem.x >= plataforma[0].origem.w) { ReciclaPlataforma(); } if ((plataforma[1].coordenadas.y<=0) && (plataforma[0].coordenadas.y<=0)) { Mix_HaltMusic(); GameOver(); onMenu=1; } SDL_Flip(screen); } } Mix_FreeMusic(musica); Mix_CloseAudio(); TTF_Quit(); SDL_Quit(); return 0; }
C
unsigned char ibuf[16]; unsigned char* itoa(unsigned int n){ int e=14; while(n>=1)ibuf[e]=n%10+'0',n/=10,e--; return ibuf+e+1; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> int measure(); int main() { measure(); system("pause"); return(0); } int measure() { int num1, num2, num3, max; printf("enter three numbers\n"); scanf("%d%d%d", &num1, &num2, &num3); if (num1>num2>num3) { printf("maximum is %d\n", num1); } else if (num2>num3>num1) { printf("maximum is %d\n", num2); } else { printf("maximum is %d\n", num3); } }
C
#include<stdio.h> #include<string.h> int main() { int x,y,z; char lab[20]; printf("Enter x\n"); scanf("%d ",&x); printf("Enter y\n"); scanf("%d",&y); printf("Enter z\n"); scanf("%d",&z); printf("Enter the lab allocated for ACE training\n"); scanf("%s",lab); if(strcmp(lab,"L1")==0) { if(y<z) { printf("L2 has the minimal seating capacity\n"); } else { printf("L3 has the minimal seating capacity\n"); } } else if(strcmp(lab,"L2")==0) { if(x<z) { printf("L1 has the minimal seating capacity\n"); } else { printf("L3 has the minimal seating capacity\n"); } } else if(x<y) { printf("L1 has the minimal seating capacity\n"); } else { printf("L2 has the minimal seating capacity\n"); } return 0; }
C
#include <stdio.h> #include <stdbool.h> int main () { char c1 = 'a'; printf("Ϊ%d\n",sizeof(c1)); //1 short s1 = 20; printf("Ϊ%d\n",sizeof(s1)); //2 int i1 = 225; printf("Ϊ%d\n",sizeof(i1)); //4 long l1 = 333333333; printf("Ϊ%d\n",sizeof(l1)); //4 long long ll1 = 333333333; printf("Ϊ%d\n",sizeof(ll1)); //8 unsigned int ui1 = 1; printf("Ϊ%d\n",sizeof(ui1)); //4 float f1 = 1.0; printf("Ϊ%d\n",sizeof(ui1)); //4 double d1 = 10.0; printf("Ϊ%d\n",sizeof(d1)); //8 long double ld1 = 10.0; printf("Ϊ%d\n",sizeof(ld1)); //16 bool b = 6>5; printf("Ϊ%d\n",sizeof(b)); //1 return 0; }
C
#include "STC15Wxx.h" #include "INTRINS.h" sbit Trig = P1^1; sbit Echo = P1^0; bit busy; unsigned char IntCnt=0; unsigned int distance=0; //延时1MS void DelayXms(int x){ //@12.000MHz unsigned char i, j; while(x--){ i = 12; j = 169; do{ while (--+j); } while (--i); } } //延时1us void Delay1us(){ //@12.000MHz _nop_(); _nop_(); _nop_(); _nop_(); } //4800bps@12.000MHz void UartInit(void){ SCON = 0x50; //8位数据,可变波特率 AUXR |= 0x01; //串口1选择定时器2为波特率发生器 AUXR |= 0x04; //定时器2时钟为Fosc,即1T T2L = 0x8F; //设定定时初值 T2H = 0xFD; //设定定时初值 AUXR |= 0x10; //启动定时器2 } //100微秒@12.000MHz void Timer0Init(void){ AUXR |= 0x80; //定时器时钟1T模式 TMOD &= 0xF0; //设置定时器模式 TL0 = 0x00; //设置定时初值 TH0 = 0x00; //设置定时初值 TF0 = 0; //清除TF0标志 // EX0 = 1; //开启外部中断 // IT0 = 1; //设置INT0的中断类型 (1:仅下降沿 0:上升沿和下降沿) ET0 = 1; //开启定时器中断 } /*---------------------------- 发送串口数据 ----------------------------*/ void SendData(unsigned char dat){ //写数据到UART数据寄存器 SBUF = dat; //TI是发送成功标志,等待前面的数据发送完成 while(!TI); TI = 0; } //发送字符 void SendString(char *s){ while (*s){ //检测字符串结束标志 SendData(*s++); //发送当前字符 } } //获取距离 void getDistance(){ unsigned char i,time,d20us = 55; unsigned char str[] = "D:-.--M"; //初始化定时器值 TH0 = TL0 = 0; //拉高超声波模块触发IO Trig = 1; //延时20us while(d20us--); //拉低超声波模块触发IO Trig = 0; //等待超声波模块输出IO拉高 while(!Echo); //开启定时器计时 TR0 = 1; //等待超声波模块输出IO拉低 while(Echo); //关闭定时器计时 TR0 = 0; //距离 uS/58=厘米 最大400cm, 最大时间 = 400cm*58=23200, 定时器 65536-23200/(1/12)=278400 //判断是否超出模块最大测距 4m if(IntCnt < 5){ //计算出时间 time = (TH0 * 256 + TL0 + IntCnt * 65536) * (1 / 12.000) + 0.5; //计算出距离 340m/s 或 us/58cm distance = time / 58 + 0.5; }else { distance = 0; } str[2] = (distance % 1000 / 100) + '0'; str[4] = (distance % 100 / 10) + '0'; str[5] = (distance % 10) + '0'; //从串口发出,也可以用显示器显示,自己接显示驱动就可以了 for(i=0;i<7;i++){ // SendData(str[i]); } // SendData('\n'); SendData(IntCnt); SendData(0xFF); // SendData('\n'); SendData(TH0); SendData(TL0); SendData(0xFF); //复位定时器 IntCnt = 0; TH0 = TL0 = 0; } //中断 void ET0_INT0(void) interrupt 1{ IntCnt++; } void main(){ //开启总中断 EA = 1; //初始化串口 UartInit(); //初始化定时器 Timer0Init(); DelayXms(1000); SendString("MaWei"); while(1){ getDistance(); DelayXms(2000); } }
C
#ifndef CONCEPT_H #define CONCEPT_H /////////////////// // SDR Concept // /////////////////// //A concept named by a SDR //References// //-----------// #include "SDR.h" #include "Task.h" #include "AttentionValue.h" //Parameters// //----------// #define PRECONDITION_BELIEFS_MAX 512 #define POSTCONDITION_BELIEFS_MAX 512 #define EVENT_BELIEFS_MAX 512 //Data structure// //--------------// typedef struct { AttentionValue attention; /** name of the concept like in OpenNARS */ SDR name; SDR_HASH_TYPE name_hash; Task event_beliefs[EVENT_BELIEFS_MAX]; int event_beliefs_amount; Task precondition_beliefs[PRECONDITION_BELIEFS_MAX]; int precondition_beliefs_amount; Task postcondition_beliefs[POSTCONDITION_BELIEFS_MAX]; int postcondition_beliefs_amount; } Concept; //Methods// //-------// //Reset the concept and assign a new name to it void Concept_RESET(Concept *concept, SDR name); #endif
C
#include <stdio.h> int main(int argc, char *argv[]) { if(argc == 99) return 99; if(argv[0] != NULL){ argv[0] = NULL; argc = 0; } argc = main(argc + 1, argv); printf("%d bottle%c of beer on the wall\n", argc, argc == 1?'\0': 's'); printf("%d bottle%c of beer\n", argc, argc == 1?'\0': 's'); printf("Take one down, pass it around\n"); printf("%d bottle%c of beer on the wall\n\n", argc - 1, (argc - 1) == 1?'\0': 's'); return argc - 1; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include "stack.h" #include <time.h> /*=============================================================== * * função : getnterms * .obtém o número de termos e de operações '?' na string de * entrada * input : * .len : tamanho da string de entrada * .input : a string de entrada * .n_terms : ponteiro para o número de termos na string * .n_ops : ponteiro para o número de operações na string * output : * .n_terms : recebe n_spaces+1, número de espaços da string * contando o último também * .n_ops: recebe n_points, número de pontos de interrogação * da string * * ============================================================*/ void getnterms(int len, char* input, int* n_terms, int* n_ops){ int i, n_spaces = 0, n_points = 0; for(i = 0; i < len; i++){ if(input[i] == ' ') n_spaces++; if(input[i] == '?') n_points++; } n_spaces++; *n_terms = n_spaces; *n_ops = n_points; } /*=============================================================== * * função : fill_vector * .preenche o vetor que contém a operação * input : * .input : a string de entrada * .n_vec : ponteiro para o vetor que contém a operação * .n_terms : número de termos na string, para loop. * output : * .n_vec: recebe os operandos em ordem, e -1 no lugar dos * operadores * * ============================================================*/ void fill_vector(char* input, int* n_vec, int n_terms){ int i, j = 0; char* split = strtok(input, " "); for(i = 0; i < n_terms; i++){ if(*split == '?'){ n_vec[i] = -1; j++; } else n_vec[i] = atoi(split); split = strtok(NULL, " "); } } /*=============================================================== * * função : polish * .avalia a expressão em notação polonesa com ajuda de uma * pilha. * input : * .n_vec : o vetor com os números de entrada. * .bitmask : mask de auxílio a bruteforce, cada bit corres- * ponde a um operador + ou * a ser testado. * .n_terms : número de termos na string, para loop. * output : * .answer : resultado da operação. * * ============================================================*/ int polish(int* n_vec, int bitmask, int n_terms, int n_ops){ int i, n = n_ops-1, op1, op2, newop, answer; Stack pilha = new_stack(); for(i = 0; i < n_terms; i++){ if(n_vec[i] == -1){ op1 = pop(&pilha); op2 = pop(&pilha); newop = bitmask & (1 << n) ? (op1 * op2) : (op1 + op2); push(&pilha, newop); n--; } else push(&pilha, n_vec[i]); } answer = pop(&pilha); free(pilha.top); return answer; } /*=============================================================== * * função : makestring * .transforma a bitmask correspondente ao resultado correto * na string de output do programa. * input : * .mask : a bitmask com a ordem certa dos operadores * .output : ponteiro para a string de saída. * .n_ops : número de operações na string, para loop. * output : * .output : a string de operadores * * ============================================================*/ void makestring(int mask, char* output, int n_ops){ int n = n_ops-1; while(n >= 0){ output[n_ops - n - 1] = (mask & (1 << n)) ? '*' : '+'; n--; } output[n_ops] = '\0'; } int main(){ char input[201]; int n_terms, n_ops; fgets(input, 201, stdin); int result; scanf("%d", &result); //obtem o numero de termos e de operações no vetor getnterms(strlen(input), input, &n_terms, &n_ops); //vetor dos números a serem empilhados int* n_vec; n_vec = malloc(sizeof(int)*n_terms); fill_vector(input, n_vec, n_terms); //numero total de combinações possíveis unsigned long long int n_possibilities = 1 << n_ops; int answer = 0; unsigned long long int bitmask; char* output; output = malloc(sizeof(char)*(n_ops+1)); //testa tudo for(bitmask = 0; bitmask < n_possibilities; bitmask++){ answer = polish(n_vec, bitmask, n_terms, n_ops); if(answer == result){ makestring(bitmask, output, n_ops); printf("%s\n", output); } } free(output); free(n_vec); return 0; }
C
#include<stdio.h> #include<sys/socket.h> #include<stdlib.h> #include<string.h> #include<sys/un.h> int main() { int server_sockfd, client_sockfd; int server_len,client_len; struct sockaddr_un server_address; struct sockaddr_un client_address; unlink("server_socket"); server_sockfd = socket(AF_UNIX //domain ,SOCK_STREAM //type ,0 //protocol ); if(server_sockfd == -1){ printf("ERROR: socket fails\n"); exit(EXIT_FAILURE); } server_address.sun_family = AF_UNIX; strcpy(server_address.sun_path,"server_socket"); server_len = sizeof(server_address); bind(server_sockfd,(struct sockaddr *)&server_address,server_len); listen(server_sockfd,5); while(1) { char ch; printf("server waiting.....server_sockfd: %d client_sockfd: %d\n",server_sockfd,client_sockfd); client_len = sizeof(client_address); client_sockfd = accept(server_sockfd,(struct sockaddr *)&client_address,&client_len); read(client_sockfd,&ch,1); ch++; write(client_sockfd,&ch,1); close(client_sockfd); } return 0; }
C
#define _CRT_SECURE_NO_WARNINGS #include "Contact.h" void InitContact(Contact* pcon) { assert(pcon); pcon->sz = 0; memset(pcon->data, 0, sizeof(pcon->data)); } void ADDContact(Contact* pcon) { assert(pcon); if (pcon->sz == MAX) { printf("ͨѶ¼\n"); return; } //¼Ϣ printf(":"); scanf("%s", pcon->data[pcon->sz].name); printf("䣺"); scanf("%d", pcon->data[pcon->sz].age); printf("Ա"); scanf("%s", pcon->data[pcon->sz].sex); printf("绰"); scanf("%s", pcon->data[pcon->sz].tele); printf("ַ"); scanf("%s", pcon->data[pcon->sz].addr); pcon->sz++; printf("ӳɹ\n"); } void SHOWContact(Contact* pcon) { int i = 0; assert(pcon); printf("%15s\t%5s\t%5s\t%12s\t%20s\t\n","","","Ա","绰","ַ"); for (i = 0; i <pcon->sz ; i++) { printf("%15s\t%5s\t%5s\t%12s\t%20s\t\n", pcon->data[i].name, pcon->data[i].age, pcon->data[i].sex, pcon->data[i].tele, pcon->data[i].addr); } } static int FindByName(Contact* pcon, char name[]) { int i = 0; assert(pcon); for(i=0;i<pcon->sz;i++) { if (strcmp(pcon->data[i].name, name)) { return i; } } //Ҳ return -1; } void DELContact(Contact* pcon) { int i = 0; char name[NAME_MAX] = { 0 }; assert(pcon); int pos = 0; if(pcon->sz==0) { printf("ͨѶ¼Ϊ"); return; } //ɾ printf("Ҫɾϵ˵"); scanf("%s", name); // pos = FindByName(pcon, name); if(pos=-1) { printf("Ҫɾ˲"); return; } //Ƴ for (i = pos; i <pcon->sz; i++) { pcon->data[i] = pcon->data[i + 1]; } pcon->sz--; printf("ɾɹ\n"); }
C
#include <stdio.h> int main(void) { int a[100],i,j,k,n,temp; scanf("%d",&n); for(i=0;i<n;i++) { scanf("%d",&a[i]); } scanf("%d",&k); for(i=0;i<k;i++) { temp=a[0]; for(j=0;j<n-1;j++) { a[j]=a[j+1]; a[j+1]=temp; } } for(j=0;j<n;j++) { printf("%d",a[j]); } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* conv_str.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: nmuller <nmuller@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/03/08 14:16:20 by nmuller #+# #+# */ /* Updated: 2017/03/08 14:20:38 by nmuller ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" static int get_size(wchar_t *str, int precision) { int str_len; int cpt; char tmp[5]; str_len = 0; cpt = -1; if (precision != -2) while (str_len + wchar_tochar(tmp, str[++cpt]) <= precision) str_len += wchar_tochar(tmp, str[cpt]); else while (str[++cpt]) str_len += wchar_tochar(tmp, str[cpt]); return (str_len); } char *conv_big_s(t_modif *modif, va_list arg, int *arg_len) { wchar_t *str; char *ret; int str_len; int cpt_str; int cpt_ret; *arg_len = (modif->precision >= 0) ? (modif->precision) : (6); if (!(str = (wchar_t*)va_arg(arg, wchar_t*))) return (ft_strdup("(null)")); str_len = get_size(str, modif->precision); if (!(ret = (char*)malloc(sizeof(char) * (str_len + 1)))) return (0); cpt_str = 0; cpt_ret = 0; while (cpt_ret < str_len && str[cpt_str]) cpt_ret += wchar_tochar(ret + cpt_ret, str[cpt_str++]); ret[cpt_ret] = '\0'; *arg_len = cpt_ret; return (ret); }
C
/***************************************************************************//** * \file error.h * * \brief Tratamiento de errores. */ #ifndef ERROR_H #define ERROR_H #include "tipos.h" /*===== Constantes ============================================================= */ /** * Este define permite habilitar o deshabilitar los ASSERT. */ #define HABILITAR_ASSERT 1 /*===== Macros ================================================================= */ #define ERROR(mensaje) parar_con_error(__FILE__, __FUNCTION__, __LINE__, mensaje) #if HABILITAR_ASSERT != 0 #define ASSERT(expr, mensaje)\ if (expr) {} else { parar_con_error(__FILE__, __FUNCTION__, __LINE__, mensaje); } #else #define ASSERT(expr, mensaje) #endif /* HABILITAR_ASSERT */ /*===== Prototipos de funciones ================================================ */ void parar_con_error(const char *fichero, const char *funcion, const uint32_t linea, const char *mensaje); #endif /* ERROR_H */
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "methods.h" #define NUM_SCORES (5) int main() { char db[5] = "\\\\"; printf("\n\t\tWelcome to the Golf Handicap Calculator (C)\n"); printf("\n"); printf("\t\t # # \n"); printf("\t\t # GHC # \n"); printf("\t\t # # \n"); printf("\t\t # # \n"); printf("\t\t %s // \n", db); printf("\t\t %s // \n", db); printf("\t\t %s // \n", db); printf("\t\t %s // \n", db); printf("\t\t %s// \n", db); printf("\t\t // \n"); printf("\t\t //%s \n", db); printf("\t\t // %s \n", db); printf("\t\t // %s \n", db); printf("\t\t // %s \n", db); printf("\t\t // %s \n", db); printf("\t\t (###// (*) %s###) \n", db); printf("\n"); int option = 0; while (1) { while (1) { printf("Select An Option:\n"); printf("1) Record Score and Add Differential to List\n"); printf("2) Calculate Handicap\n"); printf("3) Exit\n"); printf("\nEnter: "); scanf("%d", &option); if (option == 1 || option == 2) { break; } if (option == 3) { return 0; } } if (option == 1) { printf("Select The Number of Holes Played:\n"); int holes_played = 0; while (1) { printf("1) 9 Holes\n"); printf("2) 18 Holes\n"); printf("3) Exit\n"); printf("\nEnter: "); scanf("%d", &holes_played); if (holes_played == 1 || holes_played == 2) { break; } if (holes_played == 3) { return 0; } printf("Handicap Calculator: Invalid Input - %d\n", holes_played); } printf("\nWhat Is The Course Rating Of the Course You Played?\n"); printf("Rating: "); float rating = 0.0; scanf("%f", &rating); printf("\nWhat Is The Slope Of the Course You Played?\n"); printf("Slope: "); float slope = 0.0; scanf("%f", &slope); printf("\nWhat Was Your Score Today?\n"); printf("Score: "); float score = 0.0; scanf("%f", &score); if (holes_played == 1) { float nine_differential = calculate_differential_nine(rating, slope, score); record_differential_nine("nine_hole_differentials", nine_differential); printf("Differential (%f) has been recorded.\n", nine_differential); } else { float eighteen_differential = calculate_differential_eighteen(rating, slope, score); record_differential_eighteen("eighteen_hole_differentials", eighteen_differential); printf("Differential (%f) has been recorded.\n", eighteen_differential); } } else { // File Reading, Saving/Writing Score into file, Checking for 5 scores and discerning // which 5 scores are the best. printf("Please Select Your Preferred Handicap: \n"); int handicap_option = 0; while (1) { printf("1) 9-Hole Handicap\n"); printf("2) 18-Hole Handicap\n"); printf("3) Exit\n"); printf("Enter: "); scanf("%d", &handicap_option); if (handicap_option == 1 || handicap_option == 2) { break; } if (handicap_option == 3) { return 0; } } //////////////////////////////////////////////////// if (handicap_option == 1) { float nine_index = fetch_nine_handicap_index("nine_hole_differentials"); printf("\n9-Hole Handicap: %.2f\n\n", nine_index); if (nine_index == 0.0) { printf("You do not have enough scores to calculate and accurate 9-hole handicap.\n"); } } else { float eighteen_index = fetch_eighteen_handicap_index("eighteen_hole_differentials"); printf("\n18-Hole Handicap: %.2f\n\n", eighteen_index); if (eighteen_index == 0.0) { printf("You do not have enough scores to calculate and accurate 18-hole handicap.\n"); } } } } return 0; } // Main() float calculate_differential_nine(float rating, float slope, float score) { float adjusted_rating = rating / 2; return (score - adjusted_rating) * (113 / slope); } // calculate_differential_nine() float calculate_differential_eighteen(float rating, float slope, float score) { return (score - rating) * (113 / slope); } // calculate_differential_eighteen() void record_differential_nine(char* filename, float diff) { FILE* write_pointer = fopen(filename, "a"); if (write_pointer == NULL) { printf("Differential could not be recorded. (Line 150)\n"); return; } fprintf(write_pointer, "%f\n", diff); fclose(write_pointer); write_pointer = NULL; } // record_differential_nine void record_differential_eighteen(char* filename, float diff) { FILE* write_pointer = fopen(filename, "a"); if (write_pointer == NULL) { printf("Differential could not be recorded. (Line 162)\n"); return; } fprintf(write_pointer, "%f\n", diff); fclose(write_pointer); write_pointer = NULL; } // record_differential_eighteen float fetch_nine_handicap_index(char* filename) { FILE* read_pointer = fopen(filename, "r"); if (read_pointer == NULL) { printf("Differential could not be fetched. (Line 174)\n"); } int line_count = 0; float diff = 0.0; int scan_ret = 0; while (1) { scan_ret = fscanf(read_pointer, "%f", &diff); if (scan_ret == EOF) { break; } line_count++; } if (line_count < 5) { fclose(read_pointer); read_pointer = NULL; return 0.0; } fseek(read_pointer, 0, SEEK_SET); float arr[line_count]; int i = 0; while (1) { scan_ret = fscanf(read_pointer, "%f", &diff); if (scan_ret == EOF) { break; } arr[i] = diff; i++; } float* sorted_arr = malloc(line_count * sizeof(float)); sorted_arr = array_sort(arr, line_count); float arr_sum = 0.0; for (int i = 0; i < NUM_SCORES; i++) { arr_sum += sorted_arr[i]; } float index = arr_sum / NUM_SCORES; fclose(read_pointer); read_pointer = NULL; return index; } // fetch_nine_handicap_index float fetch_eighteen_handicap_index(char* filename) { FILE* read_pointer = fopen(filename, "r"); if (read_pointer == NULL) { printf("Differential could not be fetched. (Line 227)\n"); } int line_count = 0; float diff = 0.0; int scan_ret = 0; while (1) { scan_ret = fscanf(read_pointer, "%f", &diff); if (scan_ret == EOF) { break; } line_count++; } if (line_count < NUM_SCORES) { fclose(read_pointer); read_pointer = NULL; return 0.0; } fseek(read_pointer, 0, SEEK_SET); float arr[line_count]; int i = 0; while (1) { scan_ret = fscanf(read_pointer, "%f", &diff); if (scan_ret == EOF) { break; } arr[i] = diff; i++; } float* sorted_arr = malloc(line_count * sizeof(float)); sorted_arr = array_sort(arr, line_count); float arr_sum = 0.0; for (int i = 0; i < NUM_SCORES; i++) { arr_sum += sorted_arr[i]; } float index = arr_sum / NUM_SCORES; fclose(read_pointer); read_pointer = NULL; return index; } // fetch_eighteen_handicap_index void swap(float* a, float* b) { float temp = *a; *a = *b; *b = temp; } // swap() float* array_sort(float* arr, int size) { for (int i = 0; i < size - 1; i++) { for (int j = 0; j < size - i - 1; j++) { if (arr[j] > arr[j + 1]) { swap(&arr[j], &arr[j + 1]); } } } return arr; } // array_sort() void print_arr(float* arr, int size) { printf("\n"); for (int i = 0; i < size; i++) { printf("%1f ", arr[i]); } }
C
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: main.c * Author: apacot * * Created on 19 novembre 2019, 13:10 */ #include <stdio.h> #include <stdlib.h> #include "exo1.h" /* * */ int main(int argc, char** argv) { char genre; printf("vous êtes un homme ou une femme (h/f)? "); scanf("%c",&genre); afficherMenu(genre); //afficherMenu('h'); ---------------------> Exemple d'affichage return (0); }
C
#include<stdio.h> //输入一个数,判断该数是否是素数 int main(void) { int iNum = 0; int i = 2; printf("input a integer: "); scanf("%d",&iNum); getchar(); while(i < iNum) { if(iNum % i == 0) break; i++; } if(i >= iNum) printf("%d is primer number!\n",iNum); else printf("%d isn't primer number!\n",iNum); return 0; }
C
#ifndef __SYMBOL_HASH_TABLE_H__ #define __SYMBOL_HASH_TABLE_H__ #include "symbol.h" #define HASH_TABLE_SIZE 499 /* Type: SymbolHashTable A hash table for holding symbols. */ typedef struct _SymbolHashTable { int size; int maxsize; Symbol ** symbols; } SymbolHashTable; SymbolHashTable * new_SymbolHashTable (); int HashTable_hash (char * name); int HashTable_insert (SymbolHashTable * st, Symbol * symbol); Symbol * HashTable_get (SymbolHashTable * st, char * name); Symbol ** HashTable_getSymbols (SymbolHashTable * ht); #endif
C
#include "renderLoop.h" //#include "../GraphLib/include/graph.h" #include "unit.h" SDL_Surface* init(char* p_windowName, int p_resX, int p_resY) { SDL_Surface* window; if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { printf("[-] ERROR - %s\n", SDL_GetError()); return NULL; } if (!IMG_Init(IMG_INIT_PNG)) { printf("[-] ERROR - Failed to initialise SDL_Image (%s)\n", SDL_GetError()); SDL_Quit(); return NULL; } if (TTF_Init() == -1) { printf("[-] ERROR - Erreur d'initialisation de TTF_Init : %s\n", TTF_GetError()); SDL_Quit(); return NULL; } window = SDL_SetVideoMode(p_resX, p_resY, 32, SDL_DOUBLEBUF | SDL_HWSURFACE); if (!window) { printf("[-] ERROR - %s\n", SDL_GetError()); SDL_Quit(); return NULL; } SDL_WM_SetCaption(p_windowName, NULL); return window; } int interaction(SDL_Event* p_e, game* p_game) { int quit = 0; SDL_GetMouseState(&p_game->m_mousePosX, &p_game->m_mousePosY); p_game->m_lclic = 0; p_game->m_rclic = 0; while (SDL_PollEvent(p_e)) { switch (p_e->type) { // Appuie sur la croix rouge de la fentre case SDL_QUIT: quit = 1; break; // Appuie sur une touche du clavier case SDL_KEYDOWN: switch (p_e->key.keysym.sym) { case SDLK_ESCAPE: quit = 1; break; case SDLK_SPACE: p_game->m_playerTurn = (p_game->m_playerTurn + 1) % 2; ResetPlayers(p_game); default: break; } break; // Relachement d'une touche du clavier case SDL_KEYUP: switch (p_e->key.keysym.sym) { default: break; } break; // Appuie sur un bouton de la souris case SDL_MOUSEBUTTONDOWN: switch (p_e->button.button) { case SDL_BUTTON_LEFT: p_game->m_lclic = 1; break; case SDL_BUTTON_RIGHT: p_game->m_rclic = 1; break; case SDL_BUTTON_MIDDLE: break; default: break; } break; default: break; } } return quit; } int update(game* p_game) { unit* us = GetSelectedUnit(p_game); int playerId = -1; unit* u = GetUnitFromPos(p_game, p_game->m_mousePosX / 64, p_game->m_mousePosY / 64, &playerId); if (p_game->m_lclic) { // TODO : Action(s) suite un clic gauche if (us == NULL) { //printf("clique : %d %d \n", p_game->m_mousePosX/64, p_game->m_mousePosY/64); if (u != NULL) { if (playerId == p_game->m_playerTurn) { u->m_selected = 1; CalculateMovement(p_game->m_graph, u); } //printf(" click droit : SelectedUnit %d playerId %d \n", u->m_type->m_type, playerId); } } else { int caseX, caseY, caseGlobal, distance; caseX = (p_game->m_mousePosX / 64) % p_game->m_graph->m_sizeX; caseY = (p_game->m_mousePosY / 64); caseGlobal = caseX + (caseY * p_game->m_graph->m_sizeX); //printf("X : %d | Y: %d | Global : %d\n", caseX, caseY, caseGlobal); if (u == NULL) { distance = us->m_walkGraph[caseGlobal]->m_distance; if (distance <= us->m_pm && us->m_walkGraph[caseGlobal]->m_distance > 0) { us->m_posX = caseX; us->m_posY = caseY; us->m_pm -= distance; CalculateMovement(p_game->m_graph, us); } } else { if (playerId == p_game->m_playerTurn) { us->m_selected = 0; u->m_selected = 1; CalculateMovement(p_game->m_graph, u); } else if (us->m_canFire) { distance = GetManhattanDistance(p_game->m_graph->m_data[us->m_posX + us->m_posY * p_game->m_graph->m_sizeX], p_game->m_graph->m_data[u->m_posX + u->m_posY * p_game->m_graph->m_sizeX]); if (us->m_type->m_type == 3) { if (distance < 6 && distance > 1) { Atttack(p_game, us, u); us->m_canFire = 0; //printf("attack d'artilerie %d de distance \n", distance); } else { u->m_selected = 1; CalculateMovement(p_game->m_graph, u); } } else { if (distance == 1) { Atttack(p_game, us, u); if (u->m_type->m_type != 3 && u->m_hp != 0) { Atttack(p_game, u, us); } us->m_canFire = 0; //printf("attack d'artilerie %d de distance \n", distance); } else { u->m_selected = 1; CalculateMovement(p_game->m_graph, u); } } if (us->m_hp <= 0) { //printf("us mort"); us->m_posX = -1; us->m_posY = -1; } if (u->m_hp <= 0) { //printf("u mort"); u->m_posX = -1; u->m_posY = -1; } us->m_selected = 0; } } } } if (p_game->m_rclic) { // TODO : Action(s) suite un clic droit } return 0; } int draw(SDL_Surface* p_window, game* p_game) { SDL_FillRect(p_window, NULL, SDL_MapRGBA(p_window->format, 0, 0, 0, 0)); DrawGame(p_window, p_game); SDL_Flip(p_window); return 0; }
C
#include "commercially_acyclic.h" int isCommerciallyCyclic (Graph * graph) { int * visited = (int *)malloc(graph->listSize * sizeof(int)); int * cycleVertices = (int *)malloc(graph->listSize * sizeof(int)); int * leftTheWhile = (int *)malloc(graph->listSize * sizeof(int)); int cycleFoundFlag = -1, cycleFinished = 0, firstNode = 0; for (int i = 0; i < graph->listSize; i++ ) { visited[i] = 0; cycleVertices[i] = 0; leftTheWhile[i] = 0; } // If the graph is not connected, check on all different disconnected subgraphs for (int u = 0; u < graph->listSize; u++) { if (!visited[u] && (graph->array[u].head != NULL) && (cycleFoundFlag == -1)) { isCommerciallyCyclicUtil(graph, u, visited, -1, cycleVertices, &cycleFoundFlag, &cycleFinished, &firstNode, leftTheWhile); if (cycleFoundFlag != -1) { printf("There is at least one commercial cycle, the cycle found is: \n\n\n"); for (int i = 0; i < graph->listSize; i++) { if(cycleVertices[i] == 1) printf("%d\n", i); } free(visited); return 1; } } } printf("There were no cycles found, the graph is acyclic\n"); free(visited); free(cycleVertices); free(leftTheWhile); return 0; } void isCommerciallyCyclicUtil(Graph * graph, int v, int * visited, int parent, int * cycleVertices, int * cycleFoundFlag, int * cycleFinished, int * firstNode, int * leftTheWhile) { visited[v] = 1; struct AdjListNode* temp = graph->array[v].head; while ((temp != NULL) && (*cycleFoundFlag == -1)) { // We only need to find a single cycle, so once we find one we stop if(temp->hierarchy != 1) { // If it's a peer to peer it's not commercial temp = temp->next; continue; } // If an adjacent is not visited, then recur for that adjacent if(!visited[temp->neighbour]) { isCommerciallyCyclicUtil(graph, temp->neighbour, visited, v, cycleVertices, cycleFoundFlag, cycleFinished, firstNode, leftTheWhile); } else if((temp->neighbour != parent) && (leftTheWhile[temp->neighbour] == 0)) { // If an adjacent is visited and // not parent of current vertex, // then there is a cycle. cycleVertices[v] = 1; cycleVertices[temp->neighbour] = 1; *firstNode = temp->neighbour; *cycleFoundFlag = 0; } temp = temp->next; } leftTheWhile[v] = 1; if(((*cycleFoundFlag) != -1) && (*cycleFinished == 0)) { if(v == *firstNode) { *cycleFinished = 1; } else { cycleVertices[v] = 1; } } }
C
/* A : [1 2 3 4 5 6] B : 1 */ /** * @input A : Integer array * @input n1 : Integer array's ( A ) length * @input B : Integer * * @Output Integer array. You need to malloc memory, and fill the length in len1 */ int* rotateArray(int* A, int n1, int B, int *len) { int *ret = (int *)malloc(n1 * sizeof(int)); *len = n1; int i,j; int x = B%n1; for (i = 0; i < (n1-x); i++) { ret[i] = A[i + x]; } j=0; while(j<x){ ret[i]= A[j]; j++; i++; } return ret; }
C
#include "../c1.h" #include <stdio.h> #define STACK_INIT_SIZE 100 #define STACKINCREMENT 10 typedef int SElemType; typedef struct{ SElemType *base; SElemType *top; int stacksize; }SqStack; Status InitStack_Sq(SqStack *S){ (*S).base = (SElemType*)malloc(STACK_INIT_SIZE * sizeof(SElemType)); if(!(*S).base) exit(OVERFLOW); (*S).top = (*S).base; (*S).stacksize = STACK_INIT_SIZE; return OK; } Status GetTop_Sq(SqStack S, SElemType *e){ if(S.top == S.base) return ERROR; *e = *(S.top - 1); return OK; } Status Push_Sq(SqStack *S, SElemType e){ if((*S).top - (*S).base >= (*S).stacksize){ (*S).base = (SElemType*)realloc((*S).base, ((*S).stacksize + STACKINCREMENT) * sizeof(SElemType)); if(!(*S).base) exit(OVERFLOW); (*S).top = (*S).base + (*S).stacksize; (*S).stacksize += STACKINCREMENT; } *((*S).top) = e; *((*S).top)++; } Status Pop_Sq(SqStack *S, SElemType *e){ if((*S).top == (*S).base) return ERROR; *e = *--(*S).top; return OK; } Status StackTraverse_Sq(SqStack S, void(Visit)(SElemType)){ SElemType *p = S.base; while(p < S.top){ Visit(*p++); } return OK; } void PrintElem(SElemType e){ printf("%d ", e); } int StackLength_Sq(SqStack S){ return S.top - S.base; } Status StackEmpty_Sq(SqStack S){ if(S.base == S.top){ return TRUE; }else{ return FALSE; } } int main(){ SElemType e; SqStack S; int i; printf("初始化栈S\n"); InitStack_Sq(&S); printf("请输入元素个数:"); int elem_sum; scanf("%d", &elem_sum); printf("请输入元素:\n"); for(i = 1; i <= elem_sum; i++){ scanf("%d", &e); Push_Sq(&S, e); } printf("输出栈:\n"); StackTraverse_Sq(S, PrintElem); printf("\n"); printf("栈长度为 : %d\n", StackLength_Sq(S)); printf("栈是否为空:"); if(StackEmpty_Sq(S)){ printf("是\n"); }else{ printf("否\n"); } SElemType top; GetTop_Sq(S, &top); printf("栈顶元素为 : %d\n", top); printf("请输入入栈元素 : "); scanf("%d", &e); Push_Sq(&S, e); printf("输出栈:\n"); StackTraverse_Sq(S, PrintElem); printf("\n"); printf("栈顶元素出栈\n"); Pop_Sq(&S, &e); printf("输出栈:\n"); StackTraverse_Sq(S, PrintElem); printf("\n"); printf("出栈:\n"); int length = StackLength_Sq(S); for(i = 0; i < length; i++){ Pop_Sq(&S, &e); printf("%d ", e); } printf("\n"); return 0; }
C
#include "holberton.h" /** * powsqrt - search number of sqrt *@n: first entry point *@m: second entry point *Return: int */ int powsqrt(int n, int m) { if ((m * m) == n) { return (m); } else if ((m * m) < n) { return (powsqrt(n, m + 1)); } else { return (-1); } } /** *_sqrt_recursion - take the initial parameter *@n: entry point *Return:int */ int _sqrt_recursion(int n) { if (n < 0) { return (-1); } else if (n == 0) { return (0); } else if (n == 1) { return (1); } else { return (powsqrt(n, 2)); } }
C
#include <stdio.h> #include <signal.h> #include <glib.h> #include <glib/gprintf.h> #include <sys/types.h> #include <unistd.h> #include <signal.h> void print_t(); void trata_sigsev(int signum); int main() { //g_unix_signal_add(SIGSEV, trata_sigsev, NULL); signal(SIGSEGV, trata_sigsev); g_thread_init(NULL); g_thread_create(print_t, 0, FALSE, NULL); while(1) { printf("Hello Locke\n"); g_print("Hello glib\n"); sleep(5); puts("aki"); } return 0; } void print_t() { char *buffer; printf("hello threads\n"); buffer[5] = '\0'; } void trata_sigsev(int signum) { printf("Process %d got signal %d\n", getpid(), signum); puts("pegei o sinal maldito"); signal(signum, SIG_DFL); //exit(1); }
C
#include <stdio.h> #include <conio.h> #include <stdbool.h> #include "symtabUtility.h" int main(){ struct node *root = NULL; root = enterSymbol(root, "ORANGE", 0x32, false); enterSymbol(root, "PEAR", 0x1C, true); enterSymbol(root, "1PEAR", 0x2A, false); enterSymbol(root, "PEACH", 0x60, true); enterSymbol(root, "ORANGE", 0x0D, false); enterSymbol(root, "PEACH1", 0x20, true); enterSymbol(root, "BANANA", 0x50, false); enterSymbol(root, "MANGO", 0x45, true); enterSymbol(root, "MELLON", 0x80, true); enterSymbol(root, "APPLE", 0x5A, true); enterSymbol(root, "APPLE", 0x65, false); enterSymbol(root, "EGGPLANT", 0x9C, false); enterSymbol(root, "MANGO", 0x93, false); enterSymbol(root, "PINEAPPLE", 0x8C, true); // print inoder traversal of the BST printf("\n\nSymbol\t Value\t Flag\n"); printf("-------------------------\n"); printTable(root); printf("-------------------------\n\n"); printf("******Searching for CARROT, APPLE, MANGO, MELLON******\n\n"); searchTree(root, "CARROT"); searchTree(root, "APPLE"); searchTree(root, "MANGO"); searchTree(root, "MELLON"); searchTree(root, "PINEAPPLE"); searchTree(root, "PINEAP"); getch(); }
C
/* 堆实现优先队列 */ #include <stdio.h> int n = 0; struct argus{ int id; int period; int inti_period; }query[3001]; void swap(int a, int b){ query[0].id = query[a].id; query[0].period = query[a].period; query[0].inti_period = query[a].inti_period; query[a].id = query[b].id; query[a].period = query[b].period; query[a].inti_period = query[b].inti_period; query[b].id = query[0].id; query[b].period = query[0].period; query[b].inti_period = query[0].inti_period; } void down(int a){ int parent, son; parent = a; while(parent <= n/2){ son = parent << 1; if(son+1<=n && query[son].period > query[son+1].period) son++; /* 左右孩子比较:period相同比较id大小 */ if(son+1<=n && query[son].period == query[son+1].period && query[son].id > query[son+1].id) son++; if(query[parent].period > query[son].period) swap(parent, son); else{ /* period相等时比较id大小 */ if(query[parent].period==query[son].period && query[parent].id>query[son].id){ swap(parent, son); } else break; } parent = son; } } void up(int a){ int parent, son; son = a; while(son > 1){ parent = son >> 1; if(query[parent].period > query[son].period) swap(parent, son); else{ /* period相等时比较id大小 */ if(query[parent].period==query[son].period && query[parent].id>query[son].id){ swap(parent, son); } else break; } son = parent; } } void push(int i, int j, int k){ n++; query[n].id = i; query[n].period = j; query[n].inti_period = k; up(n); } void pop(){ swap(1,n); n--; down(1); } int main( ){ int id,period,inti,k; char str[10]; while( scanf("%s",str) && str[0]!='#'){ scanf( "%d %d",&id,&period); push(id, period, period); } scanf( "%d",&k); while( k--){ printf("%d\n",query[1].id); id = query[1].id; period = query[1].period + query[1].inti_period; inti = query[1].inti_period; pop(); push(id, period, inti); } return 0; }
C
// // Created by pang on 19-1-16. // #include "../pch.h" #include "smsh.h" #define is_delime(x) ((x)==' ' || (x)=='\t') char * next_cmd(char * prompt,FILE *fp){ char *buf; int bufspace = 0; int pos = 0; int c; printf("%s",prompt); while ((c=getc(fp)) != EOF){ if(pos+1>=bufspace){ if(bufspace == 0){ buf = emalloc(BUFSIZ); } else { buf = erealloc(buf,bufspace+BUFSIZ); } bufspace += BUFSIZ; } if(c=='\n') break; buf[pos++] = c; } if(c==EOF && pos==0) return NULL; buf[pos] = '\0'; return buf; } char *newstr(char *s, int len) { char *rv = emalloc(len + 1); rv[len] = '\0'; strncpy(rv, s, len); return rv; } char **splitline(char *line){ char **args; int spots = 0; int bufspace = 0; int argnum = 0; char *cp = line; char *start; int len; if(line==NULL) return NULL; args = emalloc(BUFSIZ); bufspace = BUFSIZ; spots = BUFSIZ/ sizeof(char *); while (*cp != '\0'){ while (is_delime(*cp)) cp++; if(*cp=='\0') break; if(argnum + 1>=spots){ args = erealloc(args,bufspace+BUFSIZ); bufspace += BUFSIZ; spots += (BUFSIZ/ sizeof(char*)); } start = cp; len = 1; while (*++cp != '\0' && !(is_delime(*cp))) len++; args[argnum++] = newstr(start,len); } args[argnum] = NULL; return args; } void freelist(char **list) { char **cp = list; while (*cp) free(*cp++); free(list); } void *emalloc(size_t n) { void *rv; if ((rv = malloc(n)) == NULL) fatal("out of memory", "", 1); return rv; } void *erealloc(void *p, size_t n) { void *rv; if ((rv = realloc(p, n)) == NULL) fatal("realloc() failed", "", 1); return rv; }
C
#include<stdio.h> #define min(a,b) (a<b)?a:b int main() { int n,i,k1,k2,p1,p2,sum; char arr[1005],brr[1005]; while(scanf("%d",&n)==1){ scanf("%s %s",arr,brr); sum=0; for(i=0; i<n; i++){ k1=(arr[i]-'0')+1; k2=(brr[i]-'0')+1; p1=abs(k1-k2); p2=10-p1; sum+=min(p1,p2); } printf("%d\n",sum); } return 0; }
C
#include <stdio.h> #include <string.h> /* Beskrivning Write a program in C for a 2D array of size 3x3 and print the matrix. First ask the user to enter all the enteries [i][j] and then print the array to the output. Print the array to the output like a table. E.g. 123 234 456 54 678 987 12 987 100 */ int main() { int r=1; int arr[3][3]; printf("Enter the values for the [3][3] matrix:\n"); for (int i=0; i<3; i++) for (int j=0; j<3; j++) { do{ if(!r) printf("again.."); printf("[%d][%d]: ", i, j); r = scanf("%d", &arr[i][j]); fflush(stdin); } while (r < 1); } printf("Matrix:\n"); for (int i=0; i<3; i++) { for (int j=0; j<3; j++) printf("%4d", arr[i][j]); printf("\n"); } return 0; }
C
#include <stdio.h> #include <string.h> int main() { long long int len_1,len_2,i,j,yes,flag,k,e=1000000,f=1000000; char ch1[e],ch2[f]; while(1){ gets(ch1); gets(ch2); len_1=strlen(ch1); len_2=strlen(ch2); yes=0; if(len_1<len_2){ for(j=0;j<len_1;j++){ if(ch1[j]==ch2[j]){ yes++; } } if(len_1==yes)printf("A is a proper subset of B\n"); } else if(len_1>len_2){ for(j=0;j<len_2;j++){ if(ch1[j]==ch2[j]){ yes++; } } if(len_2==yes)printf("B is a proper subset of A\n"); } else if(strcmp(ch1,ch2)==0){ printf("A equals B\n"); } else if(strcmp(ch1,ch2)!=0 && len_1==len_2){ flag=0; for(i=0;i<len_1;i=i+2){ for(k=0;k<len_1;k=k+2){ if(ch1[i]==ch2[k]){ flag=1; break; } } if(flag==1)break; } if(flag==1)printf("I'm confused!\n"); else if(flag==0)printf("A and B are disjoint\n"); } } return 0; }
C
#include "matrix.h" #include "debounce_matrix.h" #include "timer.h" //debounce times in milliseconds. Note that keys are sent on first state change, //so there is no EMI protection. Actual debounce time is between (value) and (value - 1), //due to timer resolution. Relies on all your switches actualy being good. //In testing, a few dud switches completely ruined the experience. #ifndef DEBOUNCE_PRESS #define DEBOUNCE_PRESS 5 #endif #ifndef DEBOUNCE_RELEASE #define DEBOUNCE_RELEASE 10 #endif #define BOUNCE_BIT (0b10000000) #define MAX_DEBOUNCE (0b01111111) #define DEBOUNCE_MODULO_MASK (0b01111111) #define IS_BOUNCING(button_data) (button_data) //just have to check for non-zero #define BOUNCE_EXPIRY(button_data) (button_data & DEBOUNCE_MODULO_MASK) #define CHECK_BIT(var,pos) ((var) & (1<<(pos))) #define CLEAR_BIT(var,pos) ((var) & ~(1 << (pos))) #define SET_BIT(var,pos) ((var) | (1 << (pos))) //first bit is whether we are bouncing, remaining 7 bits is modulo of when we are ready again typedef uint8_t debounce_button_t; static debounce_button_t matrix[MATRIX_ROWS * MATRIX_COLS]; static uint8_t current_time; void debounce_matrix_init(void) { for (uint8_t i = 0; i < MATRIX_ROWS * MATRIX_COLS; i++) { matrix[i] = 0; } } inline static void set_expiry(debounce_button_t* button, uint8_t timeFromNow) { *button = ((current_time + timeFromNow) % MAX_DEBOUNCE) ^ BOUNCE_BIT; } //We assume that this will be called at least once every millisecond! static void check_debounce_matrix(void) { debounce_button_t* button_data = matrix; for (uint8_t i = 0; i < MATRIX_ROWS * MATRIX_COLS; i++) { if (IS_BOUNCING(*button_data) && current_time == BOUNCE_EXPIRY(*button_data)) { *button_data = 0; } button_data++; } } static inline void handle_new_data(matrix_row_t* raw_values, matrix_row_t* output) { for (uint8_t row = 0; row < MATRIX_ROWS; row++) { matrix_row_t raw_row = *raw_values; matrix_row_t existing_row = *output; matrix_row_t result_row = existing_row; if (raw_row != existing_row) { //quick check for change. debounce_button_t* button_data = matrix + row * MATRIX_COLS; for (uint8_t col = 0; col < MATRIX_COLS; col++) { if (!IS_BOUNCING(*button_data)) { bool existing_value = CHECK_BIT(existing_row, col); bool new_value = CHECK_BIT(raw_row, col); if (existing_value != new_value) { //value changed, lets reflect that immediately if (new_value) { result_row = SET_BIT(result_row, col); //send press #if DEBOUNCE_PRESS != 0 set_expiry(button_data, DEBOUNCE_PRESS); #endif } else { result_row = CLEAR_BIT(result_row, col); //send release #if DEBOUNCE_RELEASE != 0 set_expiry(button_data, DEBOUNCE_RELEASE); #endif } } } button_data++; } *output = result_row; } raw_values++; output++; } } void update_debounce_matrix(matrix_row_t* raw_values, matrix_row_t* output_matrix) { current_time = timer_read() % MAX_DEBOUNCE; //update timer. check_debounce_matrix(); //first clear all times if appropriate handle_new_data(raw_values, output_matrix); //reads raw values, writing some of them to output_matrix }
C
#include<stdio.h> #include"nvector.h" #include"stdlib.h" nvector* nvector_alloc(int n){ nvector* v = malloc(sizeof(nvector)); (*v).size = n; (*v).data = malloc(n*sizeof(double)); if( v==NULL ) fprintf(stderr,"error in nvector_alloc\n"); return v; } void nvector_free(nvector* v){ free(v->data); free(v);} void nvector_set(nvector* v, int i, double value){ (*v).data[i]=value; } double nvector_get(nvector* v, int i){return (*v).data[i]; } double nvector_dot_product (nvector* u, nvector* v){ double sum = 0; for (int i = 0; i < (*v).size ; i++) { sum += (*v).data[i] * (*u).data[i]; } return sum; } void nvector_print(char* s, nvector* v) { printf("%s [", s); for (int i = 0; i < (*v).size -1 ; i++) { printf("%g, ",(*v).data[i]); } printf("%g] \n", (*v).data[(*v).size -1]); } void nvector_set_zero(nvector* v) { for (int i = 0; i < (*v).size ; i++) { (*v).data[i] = 0; } } int nvector_equal(nvector* a, nvector* b){ if ((*a).size == (*b).size) { for (int i = 0; i < (*a).size ; i++) { if ((*a).data[i] == (*b).data[i]) { continue; } else { return 0; } } return 1; } else { return 0; } } void nvector_add(nvector* a, nvector* b){ if ((*a).size == (*b).size) { for (int i = 0; i < (*a).size ; i++) { (*a).data[i] += (*b).data[i]; } } else { printf("Error, vectors do not have same size.\n"); } } void nvector_sub(nvector* a, nvector* b){ if ((*a).size == (*b).size) { for (int i = 0; i < (*a).size ; i++) { (*a).data[i] -= (*b).data[i]; } } else { printf("Error, vectors do not have same size.\n"); } } void nvector_scale(nvector* a, double x){ for (int i = 0; i < (*a).size ; i++) { (*a).data[i] *= x; } }
C
/* SCCS : @(#)unixtext.c 75.1 06/28/95 File : unixtext.c Author : Richard A. O'Keefe & Chung-ping Lan Purpose: Source code for unix text stream Copyright (C) 1990, Quintus Computer Systems, Inc. All rights reserved. */ #include <stdio.h> #if WIN32 #include <io.h> #else #include <unistd.h> #endif #include <errno.h> #include "quintus.h" #define CoerceTextStream(x) ((struct TextStream *)(x)) #define Min_Buffer_Size 4 struct TextStream { QP_stream qpinfo; int fd; /* file descriptor */ unsigned char *left_ptr; /* points to text not yet returned */ size_t left_size; /* counts remaining characters */ size_t last_size; /* size of last record */ unsigned char buffer[Min_Buffer_Size]; /* There must be at least one character here for a sentinel */ }; /* Reading from a TextStream, we have <-left_size-> +-------------+------------+-------+ |has been read| to be read |empty | +-------------+------------+-------+ ^ left_ptr If there is no remaining text to be read, we have to read another block from the disc. Otherwise, there are two cases: the end of the record is inside the block (return QP_FULL) or it is not (return QP_PART). In IBM jargon, this is a LOCATE mode read, because we do not move the contents of the buffer anywhere else. */ static int text_read(stream, bufptr, sizeptr) QP_stream *stream; unsigned char **bufptr; size_t *sizeptr; { register struct TextStream *u = CoerceTextStream(stream); register unsigned char *s; register int n; s = u->left_ptr; n = u->left_size; u->qpinfo.magic.byteno += u->last_size; u->last_size = 0; if (n == 0) { n = read(u->fd, (char*)u->buffer, (int)u->qpinfo.max_reclen); if (n > 0) { s = u->buffer; u->left_ptr = s; u->left_size = n; s[n] = '\n'; /* post the sentinel */ } else if (n == 0) { *sizeptr = 0; return QP_EOF; } else { u->qpinfo.errnum = errno; return QP_ERROR; } } *bufptr = s; while (*s++ != '\n') ; /* stopped by the sentinel, if naught else */ n = s-u->left_ptr; if (n > u->left_size) { *sizeptr = u->last_size = u->left_size; u->left_size = 0; return QP_PART; } else { *sizeptr = u->last_size = n; u->left_size -= n; u->left_ptr = s; return QP_FULL; } } /* Writing to a TextStream, we have <-- left_size --> +---------------+----------------+ |has been filled|empty | +---------------+----------------+ ^ left_ptr What we want to do here is LOCATE mode writes. The last_size field is redundant for this procedure. It would be prettier if we eliminated them, but the cost is slight. */ static int text_write(stream, bufptr, sizeptr) QP_stream *stream; unsigned char **bufptr; register size_t *sizeptr; { register struct TextStream *u = CoerceTextStream(stream); /* We do not have to do any copying because the output */ /* has already been placed in the right buffer. All we */ /* have to do is adjust the counters, and write out the */ /* current buffer if it is full. */ if (*sizeptr >= u->left_size) { /* the buffer is now full */ register unsigned char *p; register int n, len; p = u->buffer; len = u->qpinfo.max_reclen + (*sizeptr-u->left_size); while ((n = write(u->fd, (char *)p, len)) > 0 && n < len) { p += n; len -= n; } if (n < 0) { u->qpinfo.errnum = errno; return QP_ERROR; } u->left_ptr = u->buffer; u->left_size = u->qpinfo.max_reclen; } else { u->left_ptr += *sizeptr; u->left_size -= *sizeptr; } u->qpinfo.magic.byteno += *sizeptr; *bufptr = u->left_ptr; *sizeptr = u->left_size; /* maximum size left in buffer */ return QP_SUCCESS; } /* text_flush() is similar to text_write(). text_flush() will actually write out the buffer regardless the buffer is full or not */ static int text_flush(stream, bufptr, sizeptr) QP_stream *stream; unsigned char **bufptr; register size_t *sizeptr; { register struct TextStream *u = CoerceTextStream(stream); register unsigned char *p; register int n, len; p = u->buffer; len = u->qpinfo.max_reclen - u->left_size + *sizeptr;; if (len > u->qpinfo.max_reclen) len = *sizeptr = u->qpinfo.max_reclen; while ((n = write(u->fd, (char *)p, len)) > 0 && n < len) { p += n; len -= n; } if (n < 0) { u->qpinfo.errnum = errno; return QP_ERROR; } u->left_ptr = u->buffer; u->left_size = u->qpinfo.max_reclen; u->qpinfo.magic.byteno += *sizeptr; *bufptr = u->left_ptr; *sizeptr = u->left_size; /* maximum size left in buffer */ return QP_SUCCESS; } static int text_seek(stream, qpmagic, whence, bufptr, sizeptr) QP_stream *stream; union QP_cookie *qpmagic; int whence; unsigned char **bufptr; size_t *sizeptr; { struct TextStream *u = CoerceTextStream(stream); off_t offset; /* only needs to support for QP_FROM_TOP since TextStream only supports seeking type of QP_SEEK_PREVIOUS */ switch (whence) { case QP_BEGINNING: if ((offset = lseek(u->fd, qpmagic->byteno, SEEK_SET)) == -1) { stream->errnum = errno; return QP_ERROR; } stream->magic.byteno = offset; *bufptr = u->buffer; *sizeptr = u->left_size = (stream->mode == QP_READ) ? 0 : stream->max_reclen; u->left_ptr = u->buffer; u->last_size = 0; return QP_SUCCESS; case QP_CURRENT: case QP_END: default: stream->errnum = QP_E_INVAL; return QP_ERROR; } } static int text_close(stream) QP_stream *stream; { struct TextStream *u = CoerceTextStream(stream); int fd = u->fd; /* If the write function is changed or reassinged to some other function, the close function should also be changed accorndingly. */ if (u->qpinfo.write == text_write && u->left_ptr != u->buffer) { int n; unsigned char *p=u->buffer; long len = u->left_ptr - p; while ((n = write(u->fd, (char *)p, len)) > 0 && n < len) { p += n; len -= n; } } QP_free(stream); if (close(fd) < 0) return QP_ERROR; return QP_SUCCESS; } QP_stream * QU_text_open(option, error_num, fd) register QP_stream *option; int *error_num, fd; { int extra_size; struct TextStream *stream; if (option->seek_type == QP_SEEK_RECORD || option->seek_type == QP_SEEK_BYTE) { *error_num = QP_E_SEEK_TYPE; return QP_NULL_STREAM; } /* Need one extra byte for text_read */ if ((extra_size=option->max_reclen-(Min_Buffer_Size-1)) < 0) extra_size = 0; stream = (struct TextStream *) QP_malloc( extra_size + sizeof(struct TextStream)); stream->qpinfo = *option; QP_prepare_stream(&stream->qpinfo, stream->buffer); stream->fd = fd; stream->left_ptr = stream->buffer; stream->left_size = (option->mode == QP_READ) ? 0 : option->max_reclen; stream->last_size = 0; stream->qpinfo.close = text_close; if (option->seek_type != QP_SEEK_ERROR) stream->qpinfo.seek = text_seek; if (option->mode != QP_READ) { stream->qpinfo.write = text_write; stream->qpinfo.flush = text_flush; } else stream->qpinfo.read = text_read; return (QP_stream *) stream; }
C
#include<stdio.h> void main() { int x = 12, y = 7, z; z = x != 4 || y == 2; printf("Z = %d\n",z); } /* vivek@vivek-HIRAY:~/Desktop/CodeSnippets/c codesnippets/8july$ cc cs7.c vivek@vivek-HIRAY:~/Desktop/CodeSnippets/c codesnippets/8july$ ./a.out Z = 1 */
C
#if defined(__ARM_ARCH_6M__) /* Cortex-M0 это ARMv6-M, код для LPC1114 */ #define GPIO_DIR_REG 0x50018000 /* GPIO1DIR задает направление для блока GPIO 1 */ #define GPIO_REG_VAL 0x50013FFC /* GPIO1DATA задает значение для блока GPIO 1 */ #define GPIO_PIN_NO (1<<8) /* 8-й бит отвечает за 8-й пин */ #else /* Иначе просто считаем что это LPC1768 */ #define GPIO_DIR_REG 0x2009C020 /* FIO1DIR задает направление для блока GPIO 1 */ #define GPIO_REG_VAL 0x2009C034 /* FIO1PIN задает значение для блока GPIO 1 */ #define GPIO_PIN_NO (1<<18) /* 18-й бит отвечает за 18-й пин */ #endif void wait() { volatile int i=0xa000; while(i>0) { --i; } } void main() { *((volatile unsigned int *)GPIO_DIR_REG) = GPIO_PIN_NO; while(1) { *((volatile unsigned int *)GPIO_REG_VAL) = GPIO_PIN_NO; wait(); *((volatile unsigned int *)GPIO_REG_VAL) = 0; wait(); } /* main() *никогда* не должен вернуться! */ }
C
# time out class Solution { public: string longestPalindrome(string s) { int max = 0; int index_store = 0; int cur_len; for(int i = 1;i<s.size();i++) { int index = 1; cur_len = 1; for(int j=i;j-index >=0 && j+index < s.size();index++) { if(s[j-index] == s[j+index]) cur_len +=2; else break; } if(cur_len > max) { max = cur_len; index_store = i; // cout<<i<<endl; // cout<<max<<endl; } } string s_out; for(int i = index_store-(max-1)/2;i<=index_store + (max-1)/2;i++) { //cout<<max<<endl; s_out = s_out +=s[i]; //cout<<s[i]<<endl; } for(int i=0;i<s.size();i++) { cur_len = 0; int index = 0; // cout<<"the test string is : "<<s<<endl; // for(int j =i+1;j+index<s.size()&&i-index>=0;index++) // { // cout<<"s[i] == "<<s[i]<<" s[j] =="<<s[j]<<endl; // if(s[i] == s[j]) // { // cur_len +=2; // index_store = i; // cout<<"the length is "<<cur_len<<endl; // } // else break; // } int j = i; do { // cout<<"s[i] == "<<s[i]<<" s[j] =="<<s[j]<<endl; if(s[i] == s[j]) { cur_len +=2; index_store = i; // cout<<"the length is "<<cur_len<<endl; } else break; }while(j+index<s.size()&&i-index>=0); if(cur_len > max) { cout<<index_store<<endl; s_out = ""; // cout<<"index_store is "<<index_store; // cout<<"cur len is "<<cur_len<<endl; for(int i =index_store - cur_len/2 +1;i <=index_store + cur_len/2;i++) { s_out += s[i]; } // cout<<"the s_out is : "<<s_out<<endl; } } return s_out; } }; # Beat 99% # Actually I dont know what is the main problem.Both of the algorithm is O(N2) class Solution { public: string longestPalindrome(string s) { if (s.empty()) return ""; if (s.size() == 1) return s; int max = 0; int minstart; for(int i =0;i<s.size();) { int j=i,k=i; for(;s[k]==s[k+1]&& k+1 <s.size();k++){} i = k+1; while(j-1>=0 && k+1<s.size() && s[j-1] == s[k+1]){j--;k++;} if(k-j+1 > max) { minstart = j; max = k-j+1; } } return s.substr(minstart, max); } };
C
#include <stdio.h> #include <limits.h> #include <math.h> #include <assert.h> #include "simple-math.h" void division(int a, int b) { printf("Input two integers to divide\n"); scanf("%d%d", &a, &b); assert(b != 0); printf("%d/%d = %.2f\n", a, b, a/(float)b); printf("the program to perform division\n"); }
C
#include <unistd.h> #include <stdio.h> #include <sys/types.h> int main() { pid_t pid; char *argv[] = {"./pre", (char *)0}; char *argc[] = {"./sort", (char *)0}; int p[2]; if(pipe(p) == -1) perror("Pipe Failed."); pid = fork(); if(pid < 0) { printf("%sFork Failed."); return 1; } else if (pid == 0) { close(p[0]); execvp(argv[0], argv); } else { close(p[1]); dup2(p[1], 0); close(p[0]); execvp(argc[0], argc); } /* if(pid < 0) perror("Fork Fail"); else if(pid == 0) { execl("/bin/", "./pre", (char *)0); perror("Exec Fail"); } else { wait((int *)0); printf("%sPre Completed\n"); return 0; }*/ return 0; }
C
#include<stdio.h> #include<stdlib.h> #include <string.h> #include<winsock.h> #pragma comment(lib,"Ws2_32.lib") void main(int argc, char * argv[]){ // Initialize winsock WSADATA wsData; WORD version = MAKEWORD(2,2); int wsok = WSAStartup(version, &wsData); if(wsok != 0){ printf("Can't initialize winsock, exit !"); exit(1); } // Create socket SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, 0); if(serverSocket == INVALID_SOCKET){ printf("Can't create socket, exit !"); exit(2); } // Bind the socket to an ip address and port int portNumber = 8000; char ipAddress[10] = "127.0.0.1"; struct sockaddr_in serveradd; serveradd.sin_family = AF_INET; serveradd.sin_port = htons(portNumber); // host to network short serveradd.sin_addr.S_un.S_addr = inet_addr(ipAddress); bind(serverSocket, (struct sockaddr*) &serveradd , sizeof(serveradd)); // Listening, one connection is allowed int listening = listen(serverSocket, 2); // SOMAXCONN if(listening != -1){ printf("Server listening on port %d\n", portNumber); } // Accept connection SOCKET clientSocket; struct sockaddr_in clientadd; clientSocket = accept(serverSocket, (struct sockaddr*) &clientadd, NULL); if(clientSocket != -1){ printf("Client is connecting ... \n"); } printf("Client with ip : %s , is connected\n", inet_ntoa(clientadd.sin_addr)); // send message to client char clientRequest[256]; char response[256]; int data_len; while( (data_len = recv(clientSocket, clientRequest, sizeof(clientRequest), 0)) > 0){ printf("client : %s\n", clientRequest); printf("server : "); gets(response); send(clientSocket, response, sizeof(response), 0); memset(clientRequest, 0, sizeof(clientRequest)); memset(response, 0, sizeof(response)); } printf("Client disconnected !\n"); // Shutdown winsock shutdown(serverSocket, SD_RECEIVE); // 0 : SD_RECEIVE // 1 : SD_SEND // 2 : SD_BOTH // Close socket closesocket(serverSocket); return; }
C
#include<stdio.h> #include<math.h> #define MAX 100 int top=-1; float s[MAX]; float evaluate(float op1, float op2, char operator) { switch(operator) { case '+' : return op1+op2; break; case '-' : return op1-op2; break; case '*' : return op1*op2; break; case '/' : return op1/op2; break; case '^' : return pow(op1, op2); break; case '%' : return fmod(op1, op2); break; } } int isOperand(char c) { if(c=='+' || c=='-' || c=='*' || c=='/' || c=='%' || c=='^') return 0; else return 1; } void push(float ele) { if(top==MAX-1) printf("Stack Overflow!!\n"); else { top=top+1; s[top]=ele; } } float pop() { float del; if(top==-1) printf("Stack Undeflow!!\n"); else { del=s[top--]; } return del; } int main() { int i; float result, op1, op2; char postfix[100]; printf("Enter the postfix Expression : "); scanf("%s", postfix); for(i=0; postfix[i]!='\0'; i++) { char c=postfix[i]; if(isOperand(c)) { float x; printf("Enter the value of %c : ", c); scanf("%f", &x); push(x); } else { op2=pop(); op1=pop(); result = evaluate(op1, op2, c); push(result); } } printf("Result = %.2f\n", result); return 0; }
C
/* * File: rbt.c * Author: Ron F. <> * Last Modified: June, 2019 * Topic: RBT & Hash table * ---------------------------------------------------------------- */ #include "my_h.h" /* create a new node */ node* create_node(int data, char cp_word[MAX_WORD]) { node *new_node = (node*)malloc(sizeof(node)); if(new_node == NULL) /* malloc ERROR */ { fprintf (stderr, "Out of memory!!! (create_node)\n"); exit(1); } new_node->data = data; /* copy the data to the node */ new_node->Color = Red; /* ALWAYS new node are red */ strcpy(new_node->word, cp_word); /* copy the word to the node */ new_node->left = NULL; /* make node.left == NULL*/ new_node->right = NULL; /* make node.right == NULL*/ return new_node; } /* insert node to RBT -> by the book */ node* RB_INSERT(node *root, int data, char cp_word[MAX_WORD]) { node *z = create_node(data, cp_word); node *y=NULL, *x = root; if(root == NULL) { root = z; root->Color = Black; return root; } while (x!=NULL) { y = x; if (z->data < x->data) x = x->left; else x = x->right; } z->parent = y; if (y==NULL) root = z; else{ if (z->data < y->data) y->left=z; else y->right=z; } z->left = NULL; z->right = NULL; z->Color=Red; root = RB_INSERT_FIXUP(root,z); return root; } /* insert fixup node in RBT -> by the book */ node* RB_INSERT_FIXUP(node *root, node *z) { node *y=NULL; while (z != NULL && z->parent != NULL && (z->parent)->Color==Red) { if(z->parent == ((z->parent)->parent)->left){ y = ((z->parent)->parent)->right; if(y->Color==Red){ (z->parent)->Color = Black; /* CASE L1 */ y->Color = Black; /* CASE L1 */ ((z->parent)->parent)->Color = Red; /* CASE L1 */ z = (z->parent)->parent; /* CASE L1 */ } else { if (z == (z->parent)->right){ z = z->parent; /* CASE L2 */ root = LEFT_ROTATE(root, z); /* CASE L2 */ } (z->parent)->Color = Black; /* CASE L3 */ ((z->parent)->parent)->Color = Red; /* CASE L3 */ root = RIGHT_ROTATE(root, (z->parent)->parent); /* CASE L3 */ } } else { /* if (z->parent == z->parent->parent->right) */ y = ((z->parent)->parent)->left; if (y != NULL && y->Color == Red) { (z->parent)->Color = Black; /* CASE R1 */ y->Color = Black; /* CASE R1 */ ((z->parent)->parent)->Color = Red; /* CASE R1 */ z = (z->parent)->parent; /* CASE R1 */ } else { if (z == (z->parent)->left){ z = z->parent; /* CASE R2 */ root = RIGHT_ROTATE(root, z); /* CASE R2 */ } (z->parent)->Color = Black; /* CASE R3 */ ((z->parent)->parent)->Color = Red; /* CASE R3 */ root = LEFT_ROTATE(root, (z->parent)->parent); /* CASE R3 */ } } } root->Color = Black; return root; } /* rotate left -> by the book */ node* LEFT_ROTATE(node *root, node *x) { node *y=x->right; x->right = y->left; if (x->right != NULL) x->right->parent = x; y->parent = x->parent; if (x->parent == NULL) { root = y; } else if (x == (x->parent)->left) { (x->parent)->left = y; } else { (x->parent)->right = y; } y->left = x; x->parent = y; return root; } /* rotate right -> by the book */ node* RIGHT_ROTATE(node *root, node *x) { node *y=x->left; y->left = x->right; if (x->right != NULL) (x->parent)->right = y; x->parent = y->parent; if (y->parent == NULL) root = x; else if (x == (x->parent)->left){ (y->parent)->left = x; } else { (y->parent)->right = x; } x->right = y; y->parent = x; return root; }
C
#include <stdio.h> /* void maxPasajeros(int numPasajeros,int no){ int arr[10], i, j, c, heap_root, temp; //"no" va a ser el numero de simulaciones //aqui se ingresan los datos del heap for (i = 0; i < no; i++) scanf("%d", &arr[i]); for (i = 1; i < no; i++) { c = i; do { heap_root = (c - 1) / 2; //to create MAX arr array if (arr[heap_root] < arr[c]) { temp = arr[heap_root]; arr[heap_root] = arr[c]; arr[c] = temp; } c = heap_root; } while (c != 0); } printf("Heap array : "); for (i = 0; i < no; i++) printf("%d\t ", arr[i]); for (j = no - 1; j >= 0; j--) { temp = arr[0]; arr[0] = arr[j]; arr[j] = temp; heap_root = 0; do { c = 2 * heap_root + 1; if ((arr[c] < arr[c + 1]) && c < j-1) c++; if (arr[heap_root]<arr[c] && c<j) { temp = arr[heap_root]; arr[heap_root] = arr[c]; arr[c] = temp; } heap_root = c; } while (c < j); } printf("\nSorted array : "); printf("\nMenor: %d",arr[0]); printf("\nMayor: %d",arr[-1]); printf("\n"); } int main() { int arr[10], no, i, j, c, heap_root, temp; printf("Input number of elements: ");//este va a ser el numero de simulaciones scanf("%d", &no); printf("\nInput array values one by one : ");//aqui se ingresan los datos del heap for (i = 0; i < no; i++) scanf("%d", &arr[i]); for (i = 1; i < no; i++) { c = i; do { heap_root = (c - 1) / 2; //to create MAX arr array if (arr[heap_root] < arr[c]) { temp = arr[heap_root]; arr[heap_root] = arr[c]; arr[c] = temp; } c = heap_root; } while (c != 0); } printf("Heap array : "); for (i = 0; i < no; i++) printf("%d\t ", arr[i]); for (j = no - 1; j >= 0; j--) { temp = arr[0]; arr[0] = arr[j]; arr[j] = temp; heap_root = 0; do { c = 2 * heap_root + 1; if ((arr[c] < arr[c + 1]) && c < j-1) c++; if (arr[heap_root]<arr[c] && c<j) { temp = arr[heap_root]; arr[heap_root] = arr[c]; arr[c] = temp; } heap_root = c; } while (c < j); } printf("\nSorted array : "); printf("\nMenor: %d",arr[0]); printf("\nMayor: %d",arr[-1]); printf("\n"); } printf("|---------------------------------|\n"); printf("| 1. Mayor cantidad de pasajeros |\n"); printf("| 2. Menor cantidad de pasajeros |\n"); printf("| 3. Mayor distancia recorrida |\n"); printf("| 4. Menor distancia recorrida |\n"); printf("| 5. Salir |\n"); printf("|---------------------------------|\n"); printf("Escoge opcion: "); scanf("%d", &opcion); */
C
#include <stdio.h> int a; int main(){ double b,c; printf("请输入c"); scanf ("%lf",&c); printf("这个小数是:%lf",c); a=c; b=c-a; printf("%lf的整数部分是:%d,小数部分是:%lf\n",c,a,b); return 0; }
C
/* ** EPITECH PROJECT, 2019 ** CPE_corewar_2019 ** File description: ** get_champion_color.c */ #include "my.h" #include "vm.h" int get_champion_color(vm_t *vm, champion_t *champion, int *color) { int i = -1; if (!vm || !champion || !color) return 84; while (++i < vm->nbr_champions) { if (!my_strcmp(vm->names[i], champion->name)) { *color = i + 1; return 0; } } return 0; }
C
#ifndef EXPRESSIONOFTREE_H_ #define EXPRESSIONOFTREE_H_ #include "TreeNode.h" /** * Concatenate expression with "," and with the string that the node represent * using the getExpressionOfTreeRec * * * @param * char* expression - the string which will be concatenated. * TreeNode* node - a pointer to a tree which will be turning into a string * using the getExpressionOfTreeRec and will be concatenated. * * @return * returning the concatenated string. */ char* getStringForMinMax(char* expression , TreeNode* node); /** * Finding the op that represent the enum field. * * * @param * TREE_VALUE_TYPE op - an enum that represent the operation. * * @return * returning a string that represent the enum field. */ char* recognizeSignFromEnumType(TREE_VALUE_TYPE op); /** * Concatenating 5 strings. * * * @param * char* str1 - the string which will be concatenated. * char* str2 - the string which will be concatenated. * char* str3 - the string which will be concatenated. * char* str4 - the string which will be concatenated. * char* str5 - the string which will be concatenated. * * @return * returning the concatenated string. */ char* addAtMost5Strings( char* str1, char* str2 , char* str3, char* str4, char* str5); /** * Gets the mathematical expression using a tree * * * @param * TreeNode* node - a pointer to a tree that through him we will get the expression * * @return * returning the mathematical expression. */ char* getExpressionOfTreeRec(TreeNode* node); /** * Gets the mathematical expression using a tree, * and using the getExpressionOfTreeRec function. * * * @param * TreeNode* node - a pointer to a tree that through him we will get the expression * * @return * returning the mathematical expression. */ char* getExpressionOfTree(TreeNode* node); #endif /* EXPRESSIONOFTREE_H_ */
C
/*A priority queue is a data structure for maintaining a set S of elements, each with an associated value called a key. *A max priority queue supports the following operations: *INSERT(S, x) inserts the element x into the set S *MAXIMUN(S) returns the element of S with the largest key *EXTRACT-MAX(S) removes and returns the element of S with largest key *INCREASE-KEY(S, x, k) increase the value of element x's key to the new value k, which is assumed to be at least as large as x's current key *value. *when compile, please use command below: * gcc priority-queue.c -o prioriy-queue -lm *Introduction to GDB: http://blog.csdn.net/liigo/article/details/582231 *http://liuxinzhangyin.cn/64.html */ #include <stdio.h> #include <stdlib.h> #include <math.h> #define MAX 100 #define MIN -1000 int heap[100]; //begin with 1.Max heap. heap[0] store heap.length void printHeap(int *S) { int height = floor(log(S[0])/log(2)); int i = 1, j = 1; for(;i <= height + 1; i++) { for(; j <= S[0] && j <= pow(2, i) -1; j++) { printf(" %d ", S[j]); } printf("\n"); } } int exchange(int *i, int *j) { int tmp = *i; *i = *j; *j = tmp; return 0; } int maxHeapify(int *S, int i) { int l = 2*i; int r = 2*i + 1; int largest = 0; if(l <= S[0] && S[l] > S[i]) // S[0] store length of heap largest = l; else largest = i; if(r <= S[0] && S[r] > S[largest]) largest = r; if(largest != i) { exchange(S + i, S + largest); maxHeapify(S, largest); } return 0; } int buildMaxHeap(int *S) { int i = S[0] / 2; for(; i >= 1; i--){ maxHeapify(S, i); } return 0; } int maxHeapInsert(int *S, int key) { S[0] = S[0] + 1; S[S[0]] = MIN; heapIncreaseKey(S, S[0], key); return 0; } int heapMaximun(int *S) { return S[1]; } int heapExtractMax(int *S) { int max = 0; if(S[0] < 1) perror("heap underflow"); max = S[1]; S[1] = S[S[0]]; S[0] = S[0] - 1; maxHeapify(S, 1); return max; } int heapIncreaseKey(int *S, int i, int key) { if(key < S[i]) perror("new key is smaller than current key"); S[i] = key; while(i > 1 && S[i/2] < S[i]){ exchange(S + i, S + i/2); i = i / 2; } return 0; } int main() { int max = 0; heap[0] = 10; heap[1] = 1; heap[2] = 2; heap[3] = 3; heap[4] = 4; heap[5] = 7; heap[6] = 8; heap[7] = 9; heap[8] = 10; heap[9] = 14; heap[10] = 16; printf("Original State:\n"); printHeap(heap); buildMaxHeap(heap); printf("\n After Heapifying:\n"); printHeap(heap); heapIncreaseKey(heap, 9, 15); printf("\n After Increasing S[9]'s key to 15:\n"); printHeap(heap); max = heapExtractMax(heap); printf("\n Max key is %d, After Extracting Max Key:\n", max); printHeap(heap); maxHeapInsert(heap, 13); printf("\n After inserting key 13:\n"); printHeap(heap); return 0; }
C
/** * In-memory cache of the persistent raft log stored on disk. */ #ifndef RAFT_LOG_H #define RAFT_LOG_H #include "../include/raft.h" /** * Initial size of the entry reference count hash table. */ #define RAFT_LOG__REFS_INITIAL_SIZE 256 void raft_log__init(struct raft_log *l); void raft_log__close(struct raft_log *l); /** * Append the an entry to the log. */ int raft_log__append(struct raft_log *l, const raft_term term, const int type, const struct raft_buffer *buf, void *batch); /** * Convenience to append a series of RAFT_LOG_COMMAND entries. */ int raft_log__append_commands(struct raft_log *l, const raft_term term, const struct raft_buffer bufs[], const unsigned n); /** * Convenience to encode and append a single RAFT_LOG_CONFIGURATION entry. */ int raft_log__append_configuration( struct raft_log *l, const raft_term term, const struct raft_configuration *configuration); /** * Get the current number of entries in the log. */ size_t raft_log__n_entries(struct raft_log *l); /** * Get the index of the first entry in the log. */ raft_index raft_log__first_index(struct raft_log *l); /** * Get the index of the last entry in the log. */ raft_index raft_log__last_index(struct raft_log *l); /** * Get the term of the entry with the given index. */ raft_term raft_log__term_of(struct raft_log *l, const uint64_t index); /** * Get the term of the last entry in the log. */ raft_term raft_log__last_term(struct raft_log *l); /** * Get the entry with the given index. * * The returned pointer remains valid only as long as no API that might delete * the entry with the given index is invoked. */ const struct raft_entry *raft_log__get(struct raft_log *l, const raft_index index); /** * Acquire an array of entries from the given index onwards. * * The payload memory referenced by the #buf attribute of the returned entries * is guaranteed to be valid until raft_log__release() is called. */ int raft_log__acquire(struct raft_log *l, const raft_index index, struct raft_entry *entries[], unsigned *n); /** * Release a previously acquired array of entries. */ void raft_log__release(struct raft_log *l, const raft_index index, struct raft_entry entries[], const size_t n); /** * Delete all entries from the given index (included) onwards. */ void raft_log__truncate(struct raft_log *l, const raft_index index); /** * Discard all entries from the given index (included) onwards. This is exactly * the same as truncate, but the memory of the entries does not gets released. */ void raft_log__discard(struct raft_log *l, const raft_index index); /** * Delete all entries up to the given index (included). */ void raft_log__shift(struct raft_log *l, const raft_index index); #endif /* RAFT_LOG_H */
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_2__ TYPE_1__ ; /* Type definitions */ struct TYPE_2__ {int block_size; int disk_offset; int block_count; } ; union label_t {TYPE_1__ cms; } ; typedef int /*<<< orphan*/ tmp ; struct parsed_partitions {int /*<<< orphan*/ pp_buf; } ; struct hd_geometry {int dummy; } ; typedef int sector_t ; typedef int loff_t ; /* Variables and functions */ int /*<<< orphan*/ PAGE_SIZE ; int /*<<< orphan*/ put_partition (struct parsed_partitions*,int,int,int) ; int /*<<< orphan*/ snprintf (char*,int,char*,char*) ; int /*<<< orphan*/ strlcat (int /*<<< orphan*/ ,char*,int /*<<< orphan*/ ) ; __attribute__((used)) static int find_cms1_partitions(struct parsed_partitions *state, struct hd_geometry *geo, int blocksize, char name[], union label_t *label, sector_t labelsect) { loff_t offset, size; char tmp[64]; int secperblk; /* * VM style CMS1 labeled disk */ blocksize = label->cms.block_size; secperblk = blocksize >> 9; if (label->cms.disk_offset != 0) { snprintf(tmp, sizeof(tmp), "CMS1/%8s(MDSK):", name); strlcat(state->pp_buf, tmp, PAGE_SIZE); /* disk is reserved minidisk */ offset = label->cms.disk_offset * secperblk; size = (label->cms.block_count - 1) * secperblk; } else { snprintf(tmp, sizeof(tmp), "CMS1/%8s:", name); strlcat(state->pp_buf, tmp, PAGE_SIZE); /* * Special case for FBA devices: * If an FBA device is CMS formatted with blocksize > 512 byte * and the DIAG discipline is used, then the CMS label is found * in sector 1 instead of block 1. However, the partition is * still supposed to start in block 2. */ if (labelsect == 1) offset = 2 * secperblk; else offset = labelsect + secperblk; size = label->cms.block_count * secperblk; } put_partition(state, 1, offset, size-offset); strlcat(state->pp_buf, "\n", PAGE_SIZE); return 1; }
C
#include <sys/mntent.h> #include <stdio.h> #include <stdlib.h> static int show(const char *file) { struct mntent *me; FILE *f = fopen(file, "r"); if (!f) { perror("fopen() failed()"); exit(1); } printf("\nin %s:\n", file); while ((me = getmntent(f))) { printf("%s\t%s\t%s\t%s\t%d\t%d\n", me->mnt_fsname, me->mnt_dir, me->mnt_type, me->mnt_opts, me->mnt_freq, me->mnt_passno); } return 0; } int main(void) { show("/etc/fstab"); show("/etc/mtab"); return 0; }
C
#include <stdio.h> #include <math.h> void main() { int n; int i; float l; float d; float k; float s; printf("Ingrese la cantidad de numeros a evaluar: "); scanf("%i",&n); i=0; do { i=i+1; k=pow(i,3); printf("[%i]^3= %f ",i,k); }while(i!=n); l=1; s=0; do { s=s+l; l=l+2; d=l+(i*2); printf("[%i]^3= %f ",i,s); }while(l<n); }
C
// // list.c // CG&V_LAB Draughts // // Created by Sahil Satishkumar on 18/04/15. // Copyright (c) 2015 Sahil Satishkumar. All rights reserved. // #include <stdlib.h> #include <stdio.h> #include "list.h" //functiile de prelucrare a cozii cu miscari void addTomList(int i, int j){ coada *t; t = (coada*)malloc(sizeof(coada)); t->i = i; t->j = j; t->next = NULL; if(!mListFirst){ mListFirst = t; mListLast = t; } else { mListLast->next = t; mListLast = t; } } void delOnemList(){ coada *firstTemp; firstTemp = mListFirst; mListFirst = mListFirst->next; if(!mListFirst) mListLast = mListFirst; free(firstTemp); } void delAllmList(){ while(mListFirst != NULL) delOnemList(); } int isEmptymList(){ if(!mListFirst && !mListLast) return 1; return 0; } //functiile de prelucrare a listei cu sarituri void addTojList(int i, int j){ coada *t; t = (coada*)malloc(sizeof(coada)); t->i = i; t->j = j; t->next = NULL; if(!jListFirst){ jListFirst = t; jListLast = t; } else { jListLast->next = t; jListLast = t; } } void delOnejList(){ coada *firstTemp; firstTemp = jListFirst; jListFirst = jListFirst->next; if(!jListFirst) jListLast = jListFirst; free(firstTemp); } void delAlljList(){ while(jListFirst != NULL) delOnejList(); } int isEmptyjList(){ if(!jListFirst && !jListLast) return 1; return 0; } //functiile de prelucrare a cozii cu verificari void addTovList(int i, int j){ coada *t; t = (coada*)malloc(sizeof(coada)); t->i = i; t->j = j; t->next = NULL; if(!vListFirst){ vListFirst = t; vListLast = t; } else { vListLast->next = t; vListLast = t; } } void delOnevList(){ coada *firstTemp; firstTemp = vListFirst; vListFirst = vListFirst->next; if(!vListFirst) vListLast = vListFirst; free(firstTemp); } void delAllvList(){ while(vListFirst != NULL) delOnevList(); } int isEmptyvList(){ if(!vListFirst && !vListLast) return 1; return 0; } //returneaza 1 daca piesa este in lista int isInList(coada *list, int i, int j){ while(list != NULL){ if(list->i == i && list->j == j) return 1; list = list->next; } return 0; }
C
#pragma ident "@(#)base_conv.c 1.4 92/07/20 SMI" /* * Copyright (c) 1986 by Sun Microsystems, Inc. */ /* * Machine-independent versions of base conversion primitives. * Routines to multiply buffers by 2**16 or 10**4. Base 10**4 buffers have * b[i] < 10000, carry in and out < 65536. Base 2**16 buffers have b[i] < * 65536, carry in and out < 10000. If n is positive, b[0]..b[n-1] are * processed; if n is negative, b[0]..b[n+1] are processed. */ void _fourdigits(t, d) unsigned t; char d[4]; /* Converts t < 10000 into four ascii digits at *pc. */ { register short i; i = 3; do { d[i] = '0' + t % 10; t = t / 10; } while (--i != -1); } unsigned _quorem10000(u, pr) unsigned u; unsigned *pr; { *pr = u % 10000; return (u / 10000); } void _mul_10000(b, n, c) unsigned *b; int n; unsigned *c; { /* Multiply base-2**16 buffer by 10000. */ register unsigned carry, t; register short int i; register unsigned *pb; carry = *c; pb = b; if ((i = n) > 0) { i--; do { *pb = (t = (*pb * 10000) + carry) & 0xffff; pb++; carry = t >> 16; } while (--i != -1); } else { i = -i - 1; do { *pb = (t = (*pb * 10000) + carry) & 0xffff; pb--; carry = t >> 16; } while (--i != -1); } *c = carry; } void _mul_65536(b, n, c) unsigned *b; int n; unsigned *c; { /* Multiply base-10**4 buffer by 65536. */ register unsigned carry, t; register short int i; register unsigned *pb; carry = *c; pb = b; if ((i = n) > 0) { i--; do { *pb = (t = (*pb << 16) | carry) % 10000; pb++; carry = t / 10000; } while (--i != -1); } else { i = -i - 1; do { *pb = (t = (*pb << 16) | carry) % 10000; pb--; carry = t / 10000; } while (--i != -1); } *c = carry; }
C
/** * Implementation for ports.h **/ #include "ports.h" #include <fcntl.h> #include <errno.h> #include <pthread.h> #include <slack/map.h> typedef struct _port { int port; int proto; int pipe[2]; } port_t; Map *udp_ports = NULL; Map *tcp_ports = NULL; pthread_mutex_t tcp_lock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t udp_lock = PTHREAD_MUTEX_INITIALIZER; void port_free(void *port) { port_t *p = (port_t *) port; close(p->pipe[0]); close(p->pipe[1]); free(port); } port_t *get(int port, int proto) { pthread_mutex_t *lock; Map *map; if (!get_map(proto, &map, &lock)) { return NULL; } pthread_mutex_lock(lock); port_t *p = (port_t *) map_get(map, &port); pthread_mutex_unlock(lock); return p; } int add(int port, int proto, port_t *p) { pthread_mutex_t *lock; Map *map; if (!get_map(proto, &map, &lock)) { return 0; } int ret = 1; pthread_mutex_lock(lock); if (map_add(map, &port, p) == -1) { ret = 0; } pthread_mutex_unlock(lock); return ret; } int get_map(int proto, Map **map, pthread_mutex_t **lock) { if (proto == UDP_PROTOCOL) { *map = udp_ports; *lock = &udp_lock; } else if (proto == TCP_PROTOCOL) { *map = tcp_ports; *lock = &tcp_lock; } else { return 0; } return 1; } void init_ports() { udp_ports = map_create(port_free); tcp_ports = map_create(port_free); if (!udp_ports || !tcp_ports) { fatal("[init_ports]:: could not allocate memory for port data structures."); return; } } int open_port(int port, int proto) { // port already exists or isnt in valid range? fail if (port_open(port, proto) || !(port >= PORT_MIN && port <= PORT_MAX) ) { printf("Port is open\n"); return 0; } port_t *p = (port_t *) malloc(sizeof(port_t)); if (!p) { fatal("[open_port]:: Could not allocated memory for new port"); return 0; } p->port = port; p->proto = proto; if (pipe(p->pipe) == -1) { free(p); return 0; } // set write end to non-blocking so packetcore thread doesn't block // waiting for app to empty pipe int flags = fcntl(p->pipe[1], F_GETFL); fcntl(p->pipe[1], F_SETFL, flags | O_NONBLOCK); flags = fcntl(p->pipe[0], F_GETFL); fcntl(p->pipe[0], F_SETFL, flags | O_NONBLOCK); if (!add(port, proto, p)) { printf("add failed\n"); port_free(p); return 0; } return 1; } int close_port(int port, int proto) { pthread_mutex_t *lock; Map *map; if (!get_map(proto, &map, &lock)) { return 0; } int ret = 1; pthread_mutex_lock(lock); if (map_remove(map, &port) == -1) { ret = 0; } pthread_mutex_unlock(lock); return ret; } int grecv(int port, int proto, void *buf, size_t buf_len) { port_t *p; if (!(p = get(port, proto))) { return -1; } return read(p->pipe[0], buf, buf_len); } /* Non blocking write */ int write_data(int port, int proto, void *buf, size_t buf_len) { port_t * p; if (!(p = get(port, proto))) { return -1; } return write(p->pipe[1], buf, buf_len); } int port_open(int port, int proto) { if (!get(port, proto)) { return 0; } return 1; }
C
#include <stdio.h> unsigned long faktoriyel_hesapla(int sayi); int main() { int sayi; printf("Lütfen faktöriyeli hesaplanacak sayiyi giriniz:"); scanf("%d",&sayi); for (int i = 1; i < sayi; ++i) { printf("%d sayısının faktöriyel Sonucu :%ld \n", i, faktoriyel_hesapla(i)); } return 0; } unsigned long faktoriyel_hesapla(int sayi){ if(sayi<=1) return 1; else return(sayi* faktoriyel_hesapla(sayi-1)); }
C
//Switch case to perform arithmatic operations #include<stdio.h> int main(){ float a,b; char operator; printf("Enter operand: '+', '-', '*', '/'\n"); scanf("%c", &operator); printf("Enter two number to perform arithmtic operations:\n"); scanf("%f %f", &a, &b); switch (operator) { case '+': printf("%f + %f = %f", a, b, a + b); break; case '-': printf("%f - %.1lf = %f", a, b, a - b); break; case '*': printf("%f * %f = %f", a, b, a * b); break; case '/': printf("%f / %f = %f", a, b, a / b); break; // operator doesn't match any case constant default: printf("Error! operator is not correct"); } return 0; }
C
#include <stdint.h> // A test case to test the simulator's EvenParity semantics // // After some changes to generalize LLVMPointer handling, we tickled some bad // behavior around this primitive (see #260). int __attribute__((noinline)) test_and_verify_parity(uint64_t x) { uint64_t stack_var; void* stack_addr = &stack_var; uint64_t ret = 1; __asm__( // Load an address into %rax; we need this to be a proper LLVMPointer (in // this case, a pointer into the stack, which is the only LLVMPointer we // have) "movq %1, %%rax;" // Add in a symbolic value so that constant propagation cannot possibly eliminate // the parity check "addq %2, %%rax;" // Use `test` to set the flags (including PF) "test %%rax, %%rax;" // Actually use PF so it doesn't get eliminated "jp end;" "movq $0, %0;" "end:" : "=r"(ret) /* Outputs */ : "r"(stack_addr), "r"(x) /* Inputs */ : "rax" ); // We are returning either 1 or 0, so this test cannot be proven to return // 1. That is fine - we just want to make sure that the verifier evaluates // EvenParity without generating a failing goal. return ret; } void _start() { test_and_verify_parity(11); }
C
#include <assert.h> #include "compiler.h" int E(); void STMT(); void IF(); void BLOCK(); int tempIdx = 1, labelIdx = 1; #define nextTemp() (tempIdx++) #define nextLabel() (labelIdx++) // #define emit printf int isNext(char *set) { char eset[SMAX], etoken[SMAX]; sprintf(eset, " %s ", set); sprintf(etoken, " %s ", tokens[tokenIdx]); return (tokenIdx < tokenTop && strstr(eset, etoken) != NULL); } int isEnd() { return tokenIdx >= tokenTop; } char *next() { // printf("token[%d]=%s\n", tokenIdx, tokens[tokenIdx]); return tokens[tokenIdx++]; } char *skip(char *set) { if (isNext(set)) { return next(); } else { printf("skip(%s) got %s fail!\n", set, next()); assert(0); } } // F = (E) | Number | Id int F() { int f; if (isNext("(")) { // '(' E ')' next(); // ( f = E(); next(); // ) } else { // Number | Id f = nextTemp(); char *item = next(); irEmitTs(f, item); // emit("t%d = %s\n", f, item); } return f; } // E = F (op E)* int E() { int i1 = F(); while (isNext("+ - * / & | ! < > =")) { char *op = next(); int i2 = E(); int i = nextTemp(); irEmitOp2(i, i1, op, i2); // emit("t%d = t%d %s t%d\n", i, i1, op, i2); i1 = i; } return i1; } // ASSIGN = id '=' E; void ASSIGN() { char *id = next(); skip("="); int e = E(); skip(";"); irEmitSt(id, e); // emit("%s = t%d\n", id, e); } // while (E) STMT void WHILE() { int whileBegin = nextLabel(); int whileEnd = nextLabel(); irEmitLabel(whileBegin); // emit("(L%d)\n", whileBegin); skip("while"); skip("("); int e = E(); irEmitIfGoto(e, whileBegin); // emit("goif T%d L%d\n", whileEnd, e); skip(")"); STMT(); irEmitGoto(whileBegin); // emit("goto L%d\n", whileBegin); irEmitLabel(whileEnd); // emit("(L%d)\n", whileEnd); } void STMT() { if (isNext("while")) return WHILE(); // else if (isNext("if")) // IF(); else if (isNext("{")) BLOCK(); else ASSIGN(); } void STMTS() { while (!isEnd() && !isNext("}")) { STMT(); } } // { STMT* } void BLOCK() { skip("{"); STMTS(); skip("}"); } void PROG() { STMTS(); } void parse() { printf("============ parse =============\n"); tokenIdx = 0; PROG(); }
C
//Count Number of Words in a String #include<stdio.h> int main() { char str[10000]; int itr,count; count=0; scanf("%[^\n]",str); for(itr=0;str[itr];itr++) { if(str[itr]==' ') { count++; } } printf("%d",count+1); }
C
#include<stdio.h> #include<stdlib.h> #include<math.h> #define MAX 100 int max(int a, int b, int c); int main(void) { /* code */ int n,a[100]; scanf("%d",&n); for(int i = 0; i < n; i++) { scanf("%d",&a[i]); } int count = 0; //判断是是否可以组成三角形:穷举两个条件 //1)两边之和大于第三边 //2)两边之差小于第三边 // for(int i = 0; i < n;i++) // { // for(int j = 0;j < n && j != i; j++) // { // for(int k = 0; k < n && k != i && k != j; k++) // { // if((a[i] + a[j] > a[k]) && (a[i] + a[k] > a[j]) && (a[k] + a[j] > a[i]) && (abs(a[i] - a[j]) < a[k]) &&(abs(a[i] - a[k]) < a[j]) && (abs(a[k] - a[j]) < a[i])) // { // printf("%d %d %d can compose a triangle!\n", a[i],a[j],a[k]); // count++; // } // } // } // } //更简洁的算法是:最长棍子的长度小于其余两根棍子之和(充要条件) // 假设 c > a >b //c < a + b ==>c - a < b && c - b < a,并且c最大,所以c + a > b, c + b > a //三角形的条件全部满足 for(int i = 0; i < n; i++) { for(int j = 0; j < n && j != i; j++) { for(int k = 0; k < n && k != i && k != j; k++) { int edgeMax = max(a[i],a[j],a[k]); int len = a[i] + a[j] + a[k]; if(edgeMax < len - edgeMax){ printf("%d %d %d can compose a triangle!\n", a[i],a[j],a[k]); printf("The perimeter is %d\n",len); count++; } } } } if(count == 0) { printf("No triangle can be composed by those numbers!\n"); } return 0; } int max(int a, int b, int c) { int max; if(a > b && a > c){ max = a; } else if(b > a && b > c){ max = b; } else { max = c; } return max; }
C
#include "internal.h" void expression() { parsePrecedence(PREC_ASSIGNMENT); } void binary(bool canAssign) { // Remember the operator. TokenType operatorType = parser.previous.type; // Compile the right operand. ParseRule* rule = getRule(operatorType); parsePrecedence((Precedence)(rule->precedence + 1)); // Emit the operator instruction. switch (operatorType) { case TOKEN_BANG_EQUAL: emitBytes(OP_EQUAL, OP_NOT); break; case TOKEN_EQUAL_EQUAL: emitByte(OP_EQUAL); break; case TOKEN_GREATER: emitByte(OP_GREATER); break; case TOKEN_GREATER_EQUAL: emitBytes(OP_LESS, OP_NOT); break; case TOKEN_LESS: emitByte(OP_LESS); break; case TOKEN_LESS_EQUAL: emitBytes(OP_GREATER, OP_NOT); break; case TOKEN_PLUS: emitByte(OP_ADD); break; case TOKEN_MINUS: emitByte(OP_SUBTRACT); break; case TOKEN_STAR: emitByte(OP_MULTIPLY); break; case TOKEN_SLASH: emitByte(OP_DIVIDE); break; default: return; // Unreachable. } } void unary(bool canAssign) { TokenType operatorType = parser.previous.type; // Compile the operand. parsePrecedence(PREC_UNARY); // Emit the operator instruction. switch (operatorType) { case TOKEN_BANG: emitByte(OP_NOT); break; case TOKEN_MINUS: emitByte(OP_NEGATE); break; default: return; // Unreachable. } } void grouping(bool canAssign) { expression(); consume(TOKEN_RIGHT_PAREN, "Expect ')' after expression."); } void literal(bool canAssign) { switch (parser.previous.type) { case TOKEN_FALSE: emitByte(OP_FALSE); break; case TOKEN_NIL: emitByte(OP_NIL); break; case TOKEN_TRUE: emitByte(OP_TRUE); break; default: return; // Unreachable. } } void number(bool canAssign) { double value = strtod(parser.previous.start, NULL); emitConstant(NUMBER_VAL(value)); } void string(bool canAssign) { const Token previous = parser.previous; ObjString* value = copyString(previous.start + 1, previous.length - 2); emitConstant(OBJ_VAL(value)); } static int resolveLocal(Compiler* compiler, Token* name) { for (int i = 0; i < compiler->localCount - 1; i--) { Local* local = &compiler->locals[i]; if (identifiersEqual(&local->name, name)) { if (local->depth == -1) { error("Cannot read local variable in its own initializer."); } return i; } } return -1; } static void namedVariable(Token name, bool canAssign) { uint8_t getOp, setOp; int arg = resolveLocal(current, &name); if (arg != -1) { getOp = OP_GET_LOCAL; setOp = OP_SET_LOCAL; } else { arg = identifierConstant(&name); getOp = OP_GET_GLOBAL; setOp = OP_SET_GLOBAL; } if (canAssign && match(TOKEN_EQUAL)) { expression(); emitBytes(setOp, (uint8_t)arg); } else { emitBytes(getOp, (uint8_t)arg); } } void variable(bool canAssign) { namedVariable(parser.previous, canAssign); }
C
#include <stdio.h> void main() { char a[30] = "Hello World"; char *b = a; printf("%s\n", a); }
C
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<string.h> #include<assert.h> #include<signal.h> void sig_fun(int sig) { printf("sig=%d\n",sig); } int main() { signal(SIGINT,sig_fun); while(1) { printf("main run\n"); sleep(1); } exit(0); }
C
/* * Criado em: 21 de 05 de 2019 * Autor: Equipe de desenvolvimento do SACODE (www.sacode.lesc.ufc.br) */ #include "mem_map.h" /*! \fn uint32_t read_ram_cel(uint32_t cel_data) \brief funcao criada por precaucao, apenas retorna o valor de um espaco de memoria da RAM \param cel_data: endereco de memoria (definido na struct ECCRam no arquivo mem_map.h) a ser lido */ uint8_t read_ram_cel(uint8_t cel_data){ return cel_data; } /*! \fn uint32_t modify_ram_cel(uint32_t *cel_data, uint32_t matrix_line) \brief essa funcao deve fazer um XOR com o valor lido na memoria RAM a insercao de erro pode ser selecionada por uma estrutura matricial a ser definida e colocada no lugar da variavel "matrix_line" \param cel_data: ponteiro que aponta para o ender. de memoria (definido na struct ECCRam no arquivo mem_map.h) a ser mosificado \param matrix_line: linha da matriz de erro para inserir em determinada posicao */ uint8_t modify_ram_cel(uint8_t *cel_data, uint8_t matrix_line){ *cel_data = (*cel_data)^(matrix_line); return *cel_data; } /*! \fn answer write_ram_cel(uint32_t *cel_data, uint32_t word) \brief funcao criada para ler o valor em determinado endereco da memoria RAM \param *cel_data: ponteiro que aponta para o ender. de memoria (definido na struct ECCRam no arquivo mem_map.h) a ser mosificado \param word: palavra a ser armazenada no endereco onde o ponteiro aponta */ answer write_ram_cel(volatile uint8_t *cel_data, uint8_t word){ *cel_data = word; if(*cel_data == word){ return OP_OK; } else{ return OP_ERROR; } }
C
#include<stdio.h> #include<string.h> void main() { int fact=1,i,a; printf("Enter the number:"); scanf("%d",&a); for(i=1;i<=a;i++) { fact=fact*i; } printf("%d",fact); }
C
#ifndef SCREEN_INTERACE_H #define SCREEN_INTERACE_H #include <SDL2/SDL.h> #include <stdio.h> void createWindow(); void cleanup(); bool stop(); // Screen dimension constants long x_res = 0; long y_res = 0; // The windwo we'll be rendering to SDL_Window* window = NULL; // VRAM Buffer SDL_Texture* display = NULL; // I the renderer SDL_Renderer* renderer = NULL; bool stop() { SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: printf("exiting...\n"); return true; } } return false; } void createWindow(long _x_res, long _y_res) { x_res = _x_res; y_res = _y_res; // Initialize SDL if (SDL_Init(SDL_INIT_VIDEO) < 0) { printf("SDL could not initialize SDL_Error: %s\n", SDL_GetError()); exit(1); } // Create Widonw window = SDL_CreateWindow( "Functions", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, x_res, y_res, SDL_WINDOW_SHOWN); if (window == NULL) { printf("Window could not be created! SDL_Error: %s\n", SDL_GetError()); exit(1); } // Get window renderer renderer = SDL_CreateRenderer(window, 0, SDL_RENDERER_ACCELERATED | SDL_RENDERER_TARGETTEXTURE | SDL_RENDERER_PRESENTVSYNC); // Get the texture display = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, x_res, y_res); // SDL_SetRenderDrawColor(renderer, r, g, b, a); SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0); // Update screen SDL_SetRenderTarget(renderer, display); SDL_RenderClear(renderer); SDL_SetRenderTarget(renderer, NULL); SDL_RenderPresent(renderer); } void cleanup() { // Destroy window SDL_DestroyWindow(window); // Qutt SDL subsystems SDL_Quit(); } #endif
C
#include <stdio.h> #include <string.h> #include "../include/MyTypes.h" #include "../include/func.h" Status Matching(char line[], char *target) { int i = 0; int j = 0; int line_len = strlen(line); int target_len = strlen(target); while((i < line_len) && (j < target_len)) { if(line[i] == target[j]) { i++; j++; }else { i = i-j+1; j = 0; } } if(j == target_len) { if( ( (line[i]-0>=65)&&(line[i]-0<=90) ) || ( (line[i]-0>=97)&&(line[i]-0<=122) ) ) { return ERROR; }else if( ( (line[i-j-1]-0>=65)&&(line[i-j-1]-0<=90) ) || ((line[i-j-1]-0>=97)&&(line[i-j-1]-0<=122) )) { return ERROR; }else { return OK; } }else { return ERROR; } }