language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include "function_pointers.h" /** * int_index - Print the int index * @array: Print the index of the array * @size: Store the size of array * @cmp: Function pointer compare * Return: Integer index */ int int_index(int *array, int size, int (*cmp)(int)) { int i, index; if (array != NULL && cmp != NULL) { if (size <= 0) return (-1); for (i = 0; i < size; i++) { if ((*cmp)(array[i])) { index = i; return (index); } } if (i == size) return (-1); } return (-1); }
C
/* * Mode_ColorBlending.c * * Created on: 04.06.2013 * Author: Jean-Martin George */ #include "Mode_ColorBlending.h" #include "Modes.h" #define LEFT_RIGHT 0 #define RIGHT_LEFT 1 static RGB_Color_t currentColor = {0, 0, 0}; static RGB_Color_t startColor = {0, 0, 0}; static RGB_Color_t endColor = {0, 0, 0}; static uint16_t timeCounter = 0; static uint8_t colorIt = 0; static RGB_Color_t colorItTable[LED_MATRIX_SIZE_COL]; static uint8_t tableIt = 0; static uint8_t timerColorChange = 0; static uint8_t colorStep = 0; RGB_Color_t ColorBlending__getCurrentColor (void) { RGB_Color_t color; color.red = currentColor.red; color.green = currentColor.green; color.blue = currentColor.blue; return color; } RGB_Color_t ColorBlending__getCurrentColorCol (uint8_t col) { RGB_Color_t color; color.red = colorItTable[col].red; color.green = colorItTable[col].green; color.blue = colorItTable[col].blue; return color; } void ColorBlending__calcCurrentColor (uint8_t timerColorChange, uint8_t colorStep) { uint8_t colorFactor = 255; timeCounter = timeCounter + uC__getTaskIncrement(); if (timeCounter >= timerColorChange) { timeCounter = 0; if ((currentColor.red == endColor.red) && (currentColor.green == endColor.green) && (currentColor.blue == endColor.blue)) { if (colorIt < (NUMBER_OF_BLENDING_COLORS - 1)) { colorIt++; } else { colorIt = 0; } } startColor.red = colorFactor * pgm_read_byte(&RGB_BlendingColors[(colorIt * 3)]); startColor.green = colorFactor * pgm_read_byte(&RGB_BlendingColors[(colorIt * 3) + 1]); startColor.blue = colorFactor * pgm_read_byte(&RGB_BlendingColors[(colorIt * 3)+ 2]); if (colorIt < (NUMBER_OF_BLENDING_COLORS - 1)) { endColor.red = colorFactor * pgm_read_byte(&RGB_BlendingColors[((colorIt + 1) * 3)]); endColor.green = colorFactor * pgm_read_byte(&RGB_BlendingColors[((colorIt + 1) * 3) + 1]); endColor.blue = colorFactor * pgm_read_byte(&RGB_BlendingColors[((colorIt + 1) * 3) + 2]); } else { endColor.red = colorFactor * pgm_read_byte(&RGB_BlendingColors[0]); endColor.green = colorFactor * pgm_read_byte(&RGB_BlendingColors[1]); endColor.blue = colorFactor * pgm_read_byte(&RGB_BlendingColors[2]); } if (currentColor.red < endColor.red) { if ((currentColor.red + colorStep) < endColor.red) { currentColor.red = currentColor.red + colorStep; } else { currentColor.red = endColor.red; } } else { if (currentColor.red > endColor.red) { if ((currentColor.red - colorStep) > endColor.red) { currentColor.red = currentColor.red - colorStep; } else { currentColor.red = endColor.red; } } } if (currentColor.green < endColor.green) { if ((currentColor.green + colorStep) < endColor.green) { currentColor.green = currentColor.green + colorStep; } else { currentColor.green = endColor.green; } } else { if (currentColor.green > endColor.green) { if ((currentColor.green - colorStep) > endColor.green) { currentColor.green = currentColor.green - colorStep; } else { currentColor.green = endColor.green; } } } if (currentColor.blue < endColor.blue) { if ((currentColor.blue + colorStep) < endColor.blue) { currentColor.blue = currentColor.blue + colorStep; } else { currentColor.blue = endColor.blue; } } else { if (currentColor.blue > endColor.blue) { if ((currentColor.blue - colorStep) > endColor.blue) { currentColor.blue = currentColor.blue - colorStep; } else { currentColor.blue = endColor.blue; } } } if (tableIt < (LED_MATRIX_SIZE_COL - 1)) { tableIt++; } else { tableIt = 0; } colorItTable[tableIt].red = currentColor.red; colorItTable[tableIt].green = currentColor.green; colorItTable[tableIt].blue = currentColor.blue; } } void ColorBlending__x10 (uint8_t blendingMode) { uint16_t linIt, colIt; RGB_Color_t *l_currentColor; RGB_Color_t l_currentColorB; switch (blendingMode) { case BLENDING_MODE_SLOW: case BLENDING_MODE_SLOW_2_COLORS: { timerColorChange = 20; colorStep = 2; break; } case BLENDING_MODE_FAST: case BLENDING_MODE_FAST_2_COLORS: { timerColorChange = 1; colorStep = 1; break; } case BLENDING_MODE_SWEEP: { timerColorChange = 50; colorStep = 10; break; } case BLENDING_MODE_SWEEP_FAST: { timerColorChange = 1; colorStep = 10; break; } default: { timerColorChange = 20; colorStep = 1; break; } } ColorBlending__calcCurrentColor(timerColorChange, colorStep); if ((blendingMode == BLENDING_MODE_SWEEP) || (blendingMode == BLENDING_MODE_SWEEP_FAST)) { for (colIt = 1; colIt <= LED_MATRIX_SIZE_COL; colIt++) { l_currentColor = &colorItTable[colIt - 1]; for (linIt = 1; linIt <= LED_MATRIX_SIZE_LIN; linIt++) { LEDMatrix__setRGBColor(linIt, colIt, *l_currentColor); } } } else /* without sweep */ { l_currentColor = &currentColor; if ((blendingMode == BLENDING_MODE_SLOW_2_COLORS) || (blendingMode == BLENDING_MODE_FAST_2_COLORS)) { for (linIt = 1; linIt <= LED_MATRIX_SIZE_LIN; linIt++) { if ((linIt % 2 ) == 0) { l_currentColorB = *l_currentColor; } else { /* shift colors */ l_currentColorB = LEDMatrix__getRGBColorFromComponents((*l_currentColor).blue, (*l_currentColor).red, (*l_currentColor).green); } for (colIt = 1; colIt <= LED_MATRIX_SIZE_COL; colIt++) { LEDMatrix__setRGBColor(linIt, colIt, l_currentColorB); } } } else { LEDMatrix__setRGBColorForMatrix(*l_currentColor); } } }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "../def.h" #include "../var.h" #define SOURCE 0 #define RESULTS 1 int is_in_image(int height,int width,int i,int j,int y,int x){ return y+i >= 0 && y+i < width && x+j >= 0 && x+j < height; } void eight_expansion(imgdata idata,int y,int x){ } void four_expansion(unsigned char data[2][256][256]){ int i,j; int x,y; for(y = 0; y < 256; y++){ for(x = 0; x < 256; x++){ if(data[SOURCE][y][x] == BLACKVALUE){ for(i = -1; i <= 1; i++){ for(j = -1; j <= 1; j++){ if(i == 0 || j == 0){ if(is_in_image(256,256,i,j,y,x)){ data[RESULTS][y+i][x+j] = BLACKVALUE; } } } } } } } for(y = 0; y < 256; y++){ for(x = 0; x < 256; x++){ data[SOURCE][y][x] = data[RESULTS][y][x]; } } } void four_comtraction(unsigned char data[2][256][256]){ int i,j; int x,y; for(y = 0; y < 256; y++){ for(x = 0; x < 256; x++){ if(data[SOURCE][y][x] == WHITEVALUE){ for(i = -1; i <= 1; i++){ for(j = -1; j <= 1; j++){ if(i == 0 || j == 0){ if(is_in_image(256,256,i,j,y,x)){ data[RESULTS][y+i][x+j] = WHITEVALUE; } } } } } } } for(y = 0; y < 256; y++){ for(x = 0; x < 256; x++){ data[SOURCE][y][x] = data[RESULTS][y][x]; } } } int main(int argc, char *argv[]){ imgdata idata; unsigned char data[2][256][256] = {0}; int x, y; // 例題プログラム if (argc < 3) printf("使用法:cpbmp コピー元.bmp コピー先.bmp\n"); else { if (readBMPfile(argv[1], &idata) > 0) printf("指定コピー元ファイル%sが見つかりません\n",argv[1]); else {} for (y = 0; y < idata.height; y++){ for (x = 0; x < idata.width; x++){ data[SOURCE][y][x] = idata.source[RED][y][x]; data[RESULTS][y][x] = idata.source[RED][y][x]; } } four_expansion(data); four_comtraction(data); four_comtraction(data); four_expansion(data); for (y = 0; y < idata.height; y++){ for (x = 0; x < idata.width; x++){ idata.results[RED][y][x] = idata.results[BLUE][y][x] = idata.results[GREEN][y][x] = data[RESULTS][y][x]; } } } if (writeBMPfile(argv[2], &idata) > 0) printf("コピー先ファイル%sに保存できませんでした\n",argv[2]); }
C
#pragma GCC optimize "-O3" #include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> #include<assert.h> #include<stdbool.h> #include<limits.h> typedef double dbl; int main(){ int n; dbl v, x, f, t; while(scanf("%d %lf %lf %lf %lf", &n, &v, &x, &f, &t) == 5){ int m = ceil(v/x); dbl a = v / m; dbl z = n * t + (n + 1) * (a/f) + (m - 1) * (2 * t + 2 * (a/f)); printf("%.10f\n", z); } return 0; }
C
#include<stdio.h> #include<math.h> int main() { int n,temp,sum=0; float mean,var,sd; printf("Enter a no : "); scanf("%d",&n); int a[n]; for(int i=0;i<n;i++) scanf("%d",&a[i]); for(int i=1;i<n-1;i++) { for(int j=0;j<n-i;j++) { if(a[j]>a[j+1]) { temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } for(int i=0;i<n;i++) sum+=a[i]; mean=sum/n*1.0; sum=0; for(int i=0;i<n;i++) sum+=(a[i]-mean)*(a[i]-mean); var=sum/n*1.0; sd=sqrt(var); printf("%f",sd); return 0; }
C
//given an array of size n+2, with elements in the range 1 to n //find the two repeating elements //using count array //O(n) time //O(n) space #include<stdio.h> void findRepeat(int a[], int n) { int count[n-2]; int i; for(i=0;i<n-2;i++) //an auxillary to keep track of count count[i]=0; for(i=0;i<n;i++) { if(count[a[i]-1]==1) //if repeating (-1 cause indxing starts from 0 printf("%d ",a[i]); else count[a[i]-1]++; } printf("\n"); } int main() { int n; scanf("%d",&n); int i; int a[n]; for(i=0;i<n;i++) scanf("%d", &a[i]); findRepeat(a,n); return 0; }
C
#include <unistd.h> #include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include "head.h" int archivo_accion(char *buffer, int cliente, char *ip){ int archivo, opcion; char datos[200]; opcion = get(buffer, datos); if(opcion == 1){ //ver bd if( archivo_abrir(datos, &archivo) < 0){ write(cliente, "error", 5); return 0; } archivo_enviar(cliente, archivo); close(archivo); } else if(opcion == 2){ //mensaje completado printf("Guardar: %s;%s\n", datos, ip); } return 0; } int archivo_abrir(char *nombre, int *archivo){ char direccion[100]; memset(direccion, 0, sizeof direccion); //limpia sprintf(direccion, "bd/%s", nombre); //direccion del archivo if( (*archivo = open(direccion, O_RDWR)) < 0){ //abrir, sino error perror ("open(archivo_abrir)"); return -1; } return 0; } int archivo_enviar(int cliente, int archivo){ char buffer[512]; memset(buffer, 0, sizeof buffer); //limpia while(read(archivo, buffer, sizeof buffer) > 0){ write(cliente, buffer, strlen(buffer)); memset(buffer, 0, sizeof buffer); } return 0; }
C
// implemention a memory allocate and free demo #define Allocatesize 1000 static char allocbuf[Allocatesize]; static char *allocp=allocbuf; char *alloc(int n){ if(allocbuf+Allocatesize-allocp>=n){ //fit the space limitation allocp+=n; return allocp-n; //old pointer } else return 0; } void afree(char *p){//free storage pointed to by p if (p>=allocbuf&&p<=allocbuf+Allocatesize) allocp=p; }
C
#include <stdio.h> #include <ctype.h> int main() { int va1 = 'h'; int va2 = '2'; if (isdigit(va1)) { printf("va1 = |%c| һ\n", va1); } else { printf("va1 = |%c| һ\n", va1); } if (isdigit(va2)) { printf("va2 = |%c| һ\n", va2); } else { printf("va2 = |%c| һ\n", va2); } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_putullnbr.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jelefebv <jelefebv@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/01/07 16:41:41 by jelefebv #+# #+# */ /* Updated: 2015/02/13 14:57:45 by jelefebv ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include "ft_printf.h" char *ft_putullnbr(unsigned long long n) { char *str; if (!(str = (char *)malloc(sizeof(char) * 21))) return (NULL); str[0] = '\0'; if (n < 10) str = ft_keepstring('0' + n, str); else { str = ft_putullnbr(n / 10); str = ft_keepstring('0' + n % 10, str); } return (str); } char *ft_putuhhnbr(unsigned char n) { char *str; if (!(str = (char *)malloc(sizeof(char) * 21))) return (NULL); str[0] = '\0'; if (n < 10) str = ft_keepstring('0' + n, str); else { str = ft_putuhhnbr(n / 10); str = ft_keepstring('0' + n % 10, str); } return (str); } char *ft_putulnbr(unsigned long n) { char *str; if (!(str = (char *)malloc(sizeof(char) * 21))) return (NULL); str[0] = '\0'; if (n < 10) str = ft_keepstring('0' + n, str); else { str = ft_putulnbr(n / 10); str = ft_keepstring('0' + n % 10, str); } return (str); } char *ft_putuhnbr(unsigned short n) { char *str; if (!(str = (char *)malloc(sizeof(char) * 21))) return (NULL); str[0] = '\0'; if (n < 10) str = ft_keepstring('0' + n, str); else { str = ft_putuhnbr(n / 10); str = ft_keepstring('0' + n % 10, str); } return (str); } char *ft_putju(uintmax_t n) { char *str; if (!(str = (char *)malloc(sizeof(char) * 21))) return (NULL); str[0] = '\0'; if (n < 10) str = ft_keepstring('0' + n, str); else { str = ft_putju(n / 10); str = ft_keepstring('0' + n % 10, str); } return (str); }
C
#include <stdio.h> #include <string.h> int ft_strncmp(char *s1, char *s2, unsigned int n); int main(void) { printf("1 la repond : %d\n", strncmp("dsfwer", "sdfdsf", 3)); printf("1 la repond : %d\n", ft_strncmp("dsfwer", "sdfdsf", 3)); printf("2 la repond : %d\n", strncmp("dsfwer", "sdfdsf", 1)); printf("2 la repond : %d\n", ft_strncmp("dsfwer", "sdfdsf", 1)); printf("3 la repond : %d\n", strncmp("asdfg", "asf", 5)); printf("3 la repond : %d\n", ft_strncmp("asdfg", "asf", 5)); printf("4 la repond : %d\n", strncmp("asfffff", "asf", 3)); printf("4 la repond : %d\n", ft_strncmp("asfffff", "asf", 3)); printf("5 la repond : %d\n", strncmp("asdfg", "Asf", 1)); printf("5 la repond : %d\n", ft_strncmp("asdfg", "Asf", 1)); }
C
#include <ctype.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "error.h" char *FILENAME = "file.txt"; #define pprintf(format, ...) \ printf ("[PID %d] " format, getpid (), ##__VA_ARGS__) int tube[2]; enum { R, W }; void child (void) { close (tube[W]); // I won't write for (;;) { char c; int n = read (tube[R], &c, 1); check (n, "Cannot read"); if (n == 0) break; if (isalpha(c)) { c = toupper (c); } n = write (STDOUT_FILENO, &c, 1); check (n, "Cannot write"); } close (tube[R]); } void father (void) { int newline = 1; int line = 1; char str[16]; close (tube[R]); // I won't read int fd = open (FILENAME, O_RDONLY); check (fd, "Cannot open %s file", FILENAME); for (;;) { char c; int n = read (fd, &c, 1); check (n, "Cannot read from file %s", FILENAME); if (n == 0) break; if (newline) { snprintf (str, 16, "\t%d ", line); write (tube[W], str, strlen (str)); newline = 0; } n = write (tube[W], &c, 1); check (n, "Cannot write"); if (c == '\n') { line++; newline = 1; } } close (tube[W]); } int main (int argc, char *argv[]) { if (argc > 1) FILENAME = argv[1]; pipe (tube); if (fork ()) { // father father (); } else { //child child (); } return 0; }
C
#include <string.h> #include <stdlib.h> #include <sys/stat.h> #include <stdio.h> #include <time.h> #include <stdbool.h> #define SEP '/' int count_levels(const char * path){ int i = 0, levels = 0; bool escaped = false; while(path[i] != '\0'){ if (escaped) { escaped = false; continue; } if (path[i] == '\\') escaped = true; if (path[i] == SEP) levels++; i++; } return levels; } char * utils_relative(const char * from, const char * to){ // determine shared prefix; int i = 0, last_sep = 0; while(from[i] != '\0' && to[i] != '\0' && from[i] == to[i]){ if (from[i] == SEP){ last_sep = i; } i++; } int dots = count_levels(&from[last_sep +1]); char * rel = malloc((dots == 0 ? 2 : (dots * 3)) + strlen(&to[last_sep]) + 1); rel[0] = 0; /*if (dots == 0){*/ /*strcpy(rel, "./");*/ /*}*/ while (dots--){ strcat(rel, "../"); } strcat(rel, &to[last_sep + 1]); return rel; } bool utils_newer(const char * a, const char * b) { struct stat sta; struct stat stb; int resa = lstat(a, &sta); if (resa == -1) return false; int resb = lstat(b, &stb); if (resb == -1) return true; #ifdef __MACH__ if (sta.st_mtimespec.tv_sec == stb.st_mtimespec.tv_sec) { return sta.st_mtimespec.tv_nsec > stb.st_mtimespec.tv_nsec; } return sta.st_mtimespec.tv_sec > stb.st_mtimespec.tv_sec; #else if (sta.st_mtim.tv_sec == stb.st_mtim.tv_sec) { return sta.st_mtim.tv_nsec > stb.st_mtim.tv_nsec; } return sta.st_mtim.tv_sec > stb.st_mtim.tv_sec; #endif }
C
#include <stdio.h> //Compiler version gcc 6.3.0 int main() { int x, y, i, p; scanf("%d", &x); for(i = 1, p = 1; i <= x; i *= 10, p *= 2) y += p*((x/i)%10); printf("%d", y); return 0; }
C
/* Nombre Fichero: include/pila.h */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define TAM_MATRICULA 10 typedef struct Aux Coche_t; struct Aux { char matricula[TAM_MATRICULA]; Coche_t *sig; }; /*Añade un nuevo nodo al principio de la lista y rellena el nodo con la clave pasada como parametro. [IN/OUT] incio. Puntero al primer nodo de la lista. [IN] matricula. Nuevo elemento a añadir. Devuelve 0 si todo ha salido bien o -1 si ha habido errores*/ int aniadirPrincipio(Coche_t **pcab, const char *matricula); /*Muestra por pantalla informacion sobre la lista [IN] inicio. Lista a mostrar por pantalla Devuelve 0 si todo ha salido bien o -1 si ha habido errores*/ int listar(Coche_t *inicio); /*Borra el primer elemento de la lista [IN/OUT] incio. Puntero al primer nodo de la lista Devuelve 0 si todo ha salido bien o -1 si ha habido errores*/ int borrarAlPrincipio(Coche_t **inicio); /*Libera toda la memoria reservada. [IN/OUT] incio. Puntero al primer nodo de la lista*/ void liberarMemoria(Coche_t **inicio);
C
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #define PATH_MAX 1024 int main(void){ char *pathname; if(chdir("/home/choiseungseo") < 0){ fprintf(stderr, "chdir error\n"); exit(1); } pathname = malloc(PATH_MAX); if(getcwd(pathname, PATH_MAX) == NULL){ fprintf(stderr, "getcwd error\n"); exit(1); } printf("current directory = %s\n", pathname); exit(1); }
C
//BinaryGap int solution (int n) { int count =0,temp = 0; int flag = 0; while(n/2 != 0) { if (n%2 == 1 && flag == 0) { flag = 1; } else if (n%2 == 1 && flag == 1 ) { if ( count > temp) temp = count; count = 0; } if (n%2 == 0 && flag == 1){ count++; } n = n/2; } return count > temp ? count:temp; }
C
/* Nome:Aula 7 - While Copyright: ESAMC - Francisco Author: Elton Date: 13/04/2020 - 20:10 Description: Exerccio 6 - Nmeros em crescente para dar 1220400 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <conio.h> int main () { int n; //pega apenas uma varivel printf("Digite um nmero qualquer que dever ir somando 10 em 10 at chegar ao grande nmero de 1220400"); scanf("%d", &n); while(n < 1220400) //Enquanto ela for menor que 1220400... { n= n + 10; //n vai fazer mais 10 at que chuegue ao grande nmero printf(" Number deu: %d \n", n); } }
C
/* Example code for Exercises in C. Copyright 2019 Allen Downey License: Creative Commons Attribution-ShareAlike 3.0 */ #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { int num, den; } Rational; /* Make a rational. */ Rational *make_rational(int num, int den) { Rational *rational = malloc(sizeof(rational)); rational->num = num; rational->den = den; return rational; } /* Print a rational. */ void print_rational(Rational *rational) { printf("%d/%d\n", rational->num, rational->den); } /* Comparator function for sorting rationals. int compare (const void * r1, const void * r2) r1 = Rational(*r1); r2 = Rat ional(#Tr) double fr1 = (r1->min/fre1 > fr2){ if double fr1( r1->min, r1->den); if double fr1( r2->min, r2->den); fir (frc[i] = (r1->min)/ /* Sort rows in ascending order by floating-point approximation. */ // TODO: write this function int main () { int n = 3; Rational *rat_array[n]; rat_array[2] = make_rational(1, 2); rat_array[0] = make_rational(2, 3); rat_array[1] = make_rational(3, 4); for (int i=0; i<n; i++) { print_rational(rat_array[i]); } printf("sorting...\n"); // sort_rationals(rat_array, n); for (int i=0; i<n; i++) { print_rational(rat_array[i]); } }
C
#include<stdio.h> #include<stdlib.h> #include<math.h> #include "utils.h" double distToLineSegment(double px, double py, double x1, double y1, double x2, double y2) { double diffx, diffy, v1x, v1y, v2x, v2y; diffx = x2 - x1; diffy = y2 - y1; v1x = px - x1; v1y = py - y1; v2x = px - x2; v2y = py - y2; if ((v1x*diffx + v1y*diffy)*(v2x*diffx+v2y*diffy) <0) { return fabs((y2-y1)*px - (x2-x1)*py + x2*y1 - y2*x1)/hypot(x1-x2,y1-y2); } else { //recycling these doubles since they've been allocated // diffx = dist(px, py, x1, y1); diffx = hypot(px-x1, py- y1); // diffy = dist(px, py, x2, y2); diffy = hypot(px-x2, py- y2); return (diffx > diffy ? diffy : diffx); } } double distPtToLine(double px, double py, double x1, double y1, double x2, double y2) { // similar to the function above but ignores special cases related to line segments double diffx, diffy, v1x, v1y, v2x, v2y; diffx = x2 - x1; diffy = y2 - y1; v1x = px - x1; v1y = py - y1; v2x = px - x2; v2y = py - y2; return fabs((y2-y1)*px - (x2-x1)*py + x2*y1 - y2*x1)/hypot(x1-x2,y1-y2); } double dist(double x1, double y1, double x2, double y2) { return hypot(x1-x2,y1-y2); } int doIntersect(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) { // if either segment is actually just a point, return false double t1, t2, determ; // double zero = 0.0; // double one = 1.0; if ((x1-x2)==0.0 && (y1-y2)==0.0) { // printf("\tcase 8\t"); //DEBUG return 0; } if ((x3-x4)==0.0 && (y3-y4)==0.0) { // printf("\tcase 9\t"); //DEBUG return 0; } determ = (x2-x1)*(y3-y4)-(x3-x4)*(y2-y1); // printf("determ: %f\n", determ); // if the lines are parallel, check cases: if (determ==0.0) { if (x2-x1==0.0) // lines are vertical { if (x3==x2) { t1 = (y3-y1) / (y2-y1); t2 = (y4-y1) / (y2-y1); // printf("\tcase 1\t"); //DEBUG return ((t1 > 0 && t1 < 1) || (t2 > 0 && t2 < 1)); } else { // printf("\tcase 2\t"); //DEBUG return 0; } } else if (y2 - y1==0.0) { // lines are horizontal if (y3==y2) { t1 = (x3-x1) / (x2-x1); t2 = (x4-x1) / (x2-x1); // printf("\tcase 3\t"); //DEBUG return ((t1 > 0 && t1 < 0.9999999999999) || (t2 > 0 && t2 < 0.9999999999999)); } else { // printf("\tcase 4\t"); //DEBUG return 0; } } else { t1 = (x3-x1) / (x2-x1); t2 = (y3-y1) / (y2-y1); if (t1==t2 && t1 >0 && t2 > 0 && t1 < 0.9999999999999&& t2 < 0.9999999999999) { // printf("\tcase 5\t"); //DEBUG return 1; } t1 = (x4-x1) / (x2-x1); t2 = (y4-y1) / (y2-y1); if (t1==t2 && t1 >0 && t2 > 0 && t1 < 0.9999999999999 && t2 < 0.9999999999999) { // printf("\tcase 6\t"); //DEBUG return 1; } else { // printf("\tcase 7\t"); //DEBUG return 0; } } } t1 = ((y3-y4)*(x3-x1)+(x4-x3)*(y3-y1))/determ; t2 = ((y1-y2)*(x3-x1)+(x2-x1)*(y3-y1))/determ; // printf("\tt1: %e\tt2: %e\n", t1,t2); //DEBUG if (t1 > 0 && t1 < 0.9999999999999 && t2 > 0 && t2 < 0.9999999999999) { return 1; } else { return 0; } } void swapDoublePoints(double* p1, double* p2) { double x, y; x=p1[0]; y=p1[1]; p1[0]=p2[0]; p1[1]=p2[1]; p2[0]=x; p2[1]=y; } double sq(double x) { return x*x; } double rightTurnAngle(double x1, double y1, double x2, double y2, double x3, double y3) { // for points p1 = (x1, y1), ... , p3 = (x3,y3), returns the angle between p1p2 and p2p3. Negative means a right turn // (i.e. clockwise) positive means a left turn (counterclockwise). double d12, d23, xprod, dprod, theta; d12 = hypot(x2-x1,y2-y1); d23 = hypot(x3-x2,y3-y2); xprod = (x1-x2)*(y3-y2)-(y1-y2)*(x3-x2); dprod = ((x1-x2)*(x3-x2)+(y3-y2)*(y1-y2))/(d12*d23); // printf("xpr: %f\tdpr: %f\td12: %f\td23: %f\n",xprod, dprod, d12, d23); return (xprod<0 ? -acos(dprod) : acos(dprod)); } double getRotationalAngleToSegment(double* origin, double* radial_pt, double* seg_p1, double* seg_p2) { double rad, dp1, dp2; rad = hypot(origin[0]-radial_pt[0],origin[1]-radial_pt[1]); double d_eps = rad*1.0e-12; dp1 = hypot(origin[0]-seg_p1[0],origin[1]-seg_p1[1]); dp2 = hypot(origin[0]-seg_p2[0],origin[1]-seg_p2[1]); // printf("rad = %f\tdp1 = %f\tdp2 = %f\td_eps = %f\n",rad,dp1,dp2,d_eps); double t1, t2, a0,b0, a1, b1, x0,y0, A,B,C, xnew, ynew, ang1, ang2,dts; // if the origin happens to be one of the two segments, that is a special case: if (dp1<d_eps) { // printf("p1 = origin\n"); return rightTurnAngle(radial_pt[0],radial_pt[1],origin[0], origin[1], seg_p2[0], seg_p2[1]); } if (dp2<d_eps) { // printf("p2 = origin\n"); return rightTurnAngle(radial_pt[0],radial_pt[1],origin[0], origin[1], seg_p1[0], seg_p1[1]); } // if the radius does not intersect along the line segment, return NaN unless it hits one of the endpoints. // - this happens to also exclude cases where origin and rad pt are separated by the p12 segment // if (!(((dp1<=rad) &&(rad<=dp2)) || ((dp2<=rad) &&(rad<=dp1)))) dts = distToLineSegment(origin[0],origin[1],seg_p1[0],seg_p1[1],seg_p2[0], seg_p2[1]); // printf("dts: %f\n",dts); if (rad < dts) { a0 = nan(""); a1 = nan(""); // check the endpoints: if (dp1<=rad) a0 = rightTurnAngle(radial_pt[0],radial_pt[1],origin[0], origin[1], seg_p1[0], seg_p1[1]); if (dp2<=rad) a1 = rightTurnAngle(radial_pt[0],radial_pt[1],origin[0], origin[1], seg_p2[0], seg_p2[1]); if (!isnan(a0) && !isnan(a1)) { return (fabs(a0)>fabs(a1) ? a1 : a0); } else if (!isnan(a0)) { return a0; } else if (!isnan(a1)) { return a1; } else { return nan(""); } } // otherwise find the intersection point a0 = seg_p1[0]; b0 = seg_p1[1]; a1 = seg_p2[0]; b1 = seg_p2[1]; x0 = origin[0]; y0 = origin[1]; // printf("(a0,b0)=(%f,%f)\n",a0,b0); // printf("(a1,b1)=(%f,%f)\n",a1,b1); // printf("(x0,y0)=(%f,%f)\n",x0,y0); A = sq(a0-a1)+sq(b0-b1); B = 2*((a0-a1)*(a1-x0) + (b0-b1)*(b1-y0) ); C = sq(a1-x0)+sq(b1-y0)-sq(rad); // printf("A = %f\n",A); // printf("B = %f\n",B); // printf("C = %f\n",C); // printf("r = %f\n",rad); // printf("disc = %f",sq(B)-4*A*C); ang1 = nan(""); ang2 = nan(""); t1 = (-B + sqrt(sq(B)-4*A*C))/(2*A); t2 = (-B - sqrt(sq(B)-4*A*C))/(2*A); // printf("t1: %f\tt2: %f\n",t1,t2); if (t1>=0 && t1 <= 1.0) { xnew = a1+t1*(a0-a1); ynew = b1+t1*(b0-b1); // printf("t1: x=%f, y=%f\n", xnew,ynew); ang1 = rightTurnAngle(radial_pt[0],radial_pt[1],x0, y0, xnew, ynew); } if (t2>=0 && t2 <= 1.0) { xnew = a1+t2*(a0-a1); ynew = b1+t2*(b0-b1); ang2 = rightTurnAngle(radial_pt[0],radial_pt[1],x0, y0, xnew, ynew); } // printf("ang1: %f\tang2: %f\n",ang1, ang2); if (!isnan(ang1) && !isnan(ang2)) { return (fabs(ang1)>fabs(ang2) ? ang2 : ang1); } else if (!isnan(ang1)) { return ang1; } else if (!isnan(ang2)) { return ang2; } else { return nan(""); } return nan(""); }
C
//#include <stdio.h> //#pragma warning(disable:4996) // //#define MAX 100 // //typedef struct node { // int data; // struct node *left; // struct node *right; // struct node *parent; //}NODE; // //int N = 0, data[MAX] = { 0 }, end = 0, print = 0; // end , print Ʈ // //NODE *queue[MAX]; //NODE *head = NULL; // //void levelorder_walk(NODE *x) { // // queue[end] = x; // end++; // // while (queue[print] != NULL) { // printf("\n%d ", queue[print]->data); // // if (queue[print]->left != NULL) { // queue[end] = queue[print]->left; // end++; // } // if (queue[print]->right != NULL) { // queue[end] = queue[print]->right; // end++; // } // // if (queue[print]->parent != NULL) { // printf("( %d ڽ : %d) / ", queue[print]->parent->data, queue[print]->data); // } // // queue[print] = NULL; // print++; // } //} // //void postorder_walk(NODE *x) { // if (x != NULL) { // postorder_walk(x->left); // postorder_walk(x->right); // printf("%d ", x->data); // } //} // //void preorder_walk(NODE *x) { // if (x != NULL) { // printf("%d ", x->data); // preorder_walk(x->left); // preorder_walk(x->right); // } //} // //void inorder_walk(NODE *x) { // if (x != NULL) { // inorder_walk(x->left); // printf("%d ", x->data); // inorder_walk(x->right); // } //} // //NODE *make_node(NODE *x, int data) { // x->data = data; // x->left = NULL; // x->right = NULL; // x->parent = NULL; // // return x; //} // //void insert_binary(NODE *T, NODE *z) { // NODE *y = NULL; // NODE *x = T; // T = head // // while (x != NULL) { // y = x; // if (z->data < x->data) { // x = x->left; // } // else { // x = x->right; // } // } // z->parent = y; // // if (y == NULL) { // head = z; // } // else if (z->data < y->data) { // y->left = z; // } // else { // y->right = z; // } //} // //NODE *search_binary(NODE *x, int k) { // if (x == NULL || k == x->data) { // return x; // } // // if (k < x->data) { // return search_binary(x->left, k); // } // return search_binary(x->right, k); //} // //NODE *find_max(NODE *x) { // while (x->right != NULL) { // x = x->right; // } // return x; //} // //NODE *find_min(NODE *x) { // while (x->left != NULL) { // x = x->left; // } // return x; //} // //NODE *find_successor(NODE *x) { // if (x->right != NULL) { // return find_min(x->right); // } // NODE *y = x->parent; // // while (y != NULL && x == y->right) { // x = y; // y = y->parent; // } // return y; //} // //NODE *find_prodecessor(NODE *x) { // if (x->left != NULL) { // return find_max(x->left); // } // NODE *y = x->parent; // // while (y != NULL && x == y->left) { // x = y; // y = y->parent; // } // return y; //} // //void *del_binary(NODE *T, NODE *z) { // NODE *x, *y; // // if (z->left == NULL || z->right == NULL) { // y = z; // } // else { // y = find_successor(z); // } // // if (y->left != NULL) { // x = y->left; // } // else { // x = y->right; // } // // if (x != NULL) { // x->parent = y->parent; // } // // if (y->parent == NULL) { // head = x; // } // else if (y == y->parent->left) { // y->parent->left = x; // } // else { // y->parent->right = x; // } // // if (y != z) { // z->data = y->data; // // } //} // //void print_binary() { // printf("Inorder ȸ : "); // inorder_walk(head); // printf("\n\n"); // // printf("Preorder ȸ : "); // preorder_walk(head); // printf("\n\n"); // // printf("Postorder ȸ : "); // postorder_walk(head); // printf("\n\n"); // // printf("Levelorder ȸ : "); // levelorder_walk(head); // // printf("ִ밪 : %d / ּҰ : %d\n", find_max(head)->data, find_min(head)->data); //} // //void main() { // // FILE *fp = fopen("input.txt", "r"); // fscanf(fp, "%d", &N); // // for (int i = 0; i < N; i++) { // fscanf(fp, "%d", &data[i]); // } // // for (int i = 0; i < N; i++) { // NODE *temp = malloc(sizeof(NODE)); // temp = make_node(temp, data[i]); // // insert_binary(head, temp); // } // // print_binary(); // // int input = 0; // scanf("%d", &input); // // if (search_binary(head, input) != NULL) { // printf(" : %d\n", search_binary(head, input)->data); // // NODE *target = search_binary(head, input); // // if (find_successor(target) != NULL && find_prodecessor(target) != NULL) { // printf("Successor : %d\n", find_successor(target)->data); // printf("Prodecessor : %d\n\n", find_prodecessor(target)->data); // } // // del_binary(head, target); // } // // print_binary(); // // getchar(); // getchar(); //}
C
#define _CRT_SECURE_NO_DEPRECATE 1 #include <stdio.h> //int main() //{ // unsigned int i; // for (i = 9; i >= 0; i--) // { // printf("%u\n", i); // } // return 0; //} unsigned int i = 0; int main() { int count = 0; for (i = 0; i <= 255; i++) { printf("hello world\n"); count++; } printf("count=%d\n", count); return 0; }
C
#include <stdio.h> void mad_add(const int a[4][3], const int b[4][3], int c[2][4][3]); void mat_printf(const int m[2][4][3]); int main(void) { int tensu1[4][3] = { {91, 63, 78}, {67, 72, 46}, {89, 34, 53}, {32, 54, 34} }; int tensu2[4][3] = { {9, 6, 7}, {6, 7, 4}, {8, 3, 5}, {3, 5, 3} }; int sum[2][4][3]; mad_add(tensu1, tensu2, sum); mat_printf(sum); return 0; } void mad_add(const int a[4][3], const int b[4][3], int c[2][4][3]) { for(int i = 0; i < 2; i++){ for(int j = 0; j < 4; j++){ for(int k = 0; k < 3; k++){ if(i == 0){ c[0][j][k] = a[j][k]; }else if(i == 1){ c[1][j][k] = b[j][k]; } } } } } void mat_printf(const int m[2][4][3]) { for(int i = 0; i < 2; i++){ printf("%d回目\n", i + 1); for(int j = 0; j < 4; j++){ for(int k = 0; k < 3; k++){ printf("%d ", m[i][j][k]); } printf("\n"); } } }
C
#include "x_syscalls.h" #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include <sys/shm.h> #include <sys/wait.h> // declaration void x_error(const char*); void *x_malloc(size_t); void x_chdir(const char*); pid_t x_fork(); pid_t x_wait(int*); pid_t x_getpid(void); pid_t x_getppid(void); void x_setpgrp(void); key_t x_ftok(const char*, int); int x_semget(key_t, int, int); void x_semctl(int, int, int); void x_semop(int, struct sembuf*, int); int x_shmget(key_t, size_t, int); void x_shmctl(int, int, struct shmid_ds*); void *x_shmat(int, const void*, int); void x_shmdt(const void*); // implementation void *x_malloc(size_t size) { void *ptr; ptr = malloc(size); if(ptr == NULL) { x_error("can't allocate memory"); } return ptr; } void x_chdir(const char *path) { int retval; retval = chdir(path); if(retval < 0) { x_error("can't change dir"); } } pid_t x_fork() { pid_t pid; pid = fork(); if(pid < 0) { x_error("can't fork"); } return pid; } pid_t x_wait(int *status) { pid_t pid; pid = wait(status); if(pid < 0) { x_error("can't perform wait"); } return pid; } pid_t x_getpid(void) { pid_t pid; pid = getpid(); if(pid < 0) { x_error("can't get a process identifier"); } return pid; } pid_t x_getppid(void) { pid_t pid; pid = getppid(); if(pid < 0) { x_error("can't get a process identifier"); } return pid; } void x_setpgrp(void) { int retval; retval = setpgrp(); if(retval < 0) { x_error("can't set PGID"); } } key_t x_ftok(const char *pathname, int proj_id) { key_t key; key = ftok(pathname, proj_id); if(key < 0) { x_error("can't get a System V IPC key"); } return key; } int x_semget(key_t key, int nsems, int semflg) { int semid; semid = semget(key, nsems, semflg); if(semid < 0) { if(errno == EEXIST) { semid = x_semget(key, nsems, 0); x_semctl(semid, nsems, IPC_RMID); semid = x_semget(key, nsems, semflg); } else { x_error("can't get a semaphore set identifier"); } } return semid; } void x_semctl(int semid, int semnum, int cmd) { int retval; retval = semctl(semid, semnum, cmd); if(retval < 0) { x_error("can't perform semaphore control operations"); } } void x_semop(int semid, struct sembuf *sops, int nsops) { int retval; retval = semop(semid, sops, nsops); if(retval < 0) { if(errno == EINTR) { x_semop(semid, sops, nsops); } else { x_error("can't perform semaphore operations"); } } } int x_shmget(key_t key, size_t size, int shmflg) { int shmid; shmid = shmget(key, size, shmflg); if(shmid < 0) { if(errno == EEXIST) { shmid = x_shmget(key, 0, 0); x_shmctl(shmid, IPC_RMID, NULL); shmid = x_shmget(key, size, shmflg); } else { x_error("can't allocate a shred memory segment"); } } return shmid; } void x_shmctl(int shmid, int cmd, struct shmid_ds *buf) { int retval; retval = shmctl(shmid, cmd, buf); if(retval < 0) { x_error("can't control shared memory"); } } void *x_shmat(int shmid, const void *shmaddr, int shmflg) { void *ptr; ptr = shmat(shmid, shmaddr, shmflg); if(ptr == NULL) { x_error("can't attach the shared memory segment"); } return ptr; } void x_shmdt(const void *shmaddr) { int retval; retval = shmdt(shmaddr); if(retval < 0) { x_error("can't detach the shared memory segment"); } } void x_error(const char *message) { perror(message); exit(X_ERROR_EXIT); }
C
/* ** sort_tab.c for sort_tab in /home/leandre/TEST_FOLDER ** ** Made by Léandre Blanchard ** Login <leandre.blanchard@epitech.eu> ** ** Started on Sat Sep 16 15:36:40 2017 Léandre Blanchard ** Last update Sun Jan 7 11:07:19 2018 Léandre Blanchard */ #include <string.h> static int test_order(char **tab) { if (!tab) return (0); for (int i = 0; tab[i + 1]; ++i) { if (strcmp(tab[i], tab[i + 1]) > 0) return (1); } return (0); } int sort_tab(char **tab) { char *swap; while (test_order(tab)) { for (int i = 0; tab[i + 1]; ++i) { if (strcmp(tab[i], tab[i + 1]) > 0) { swap = tab[i]; tab[i] = tab[i + 1]; tab[i + 1] = swap; } } } return (0); }
C
//when a function is called inside #include<stdio.h> #include<stdlib.h> struct Node{ int data; struct Node *next,*prev; }; void push(struct Node **head,int data){ struct Node *newnode=(struct Node*)malloc(sizeof(struct Node)); newnode->data=data; newnode->next=(*head); newnode->prev=NULL; if((*head)!=NULL) (*head)->prev=newnode; (*head)=newnode; } void printlist(struct Node *node){ while(node){ printf(" %d ",node->data); node=node->next; } } void deleteNode(struct Node** delt) { struct Node *del=(*delt); if (del->next != NULL) del->next->prev = del->prev; if (del->prev != NULL) del->prev->next = del->next; free(del); } void removed(struct Node** head_ref) { if ((*head_ref) == NULL || (*head_ref)->next == NULL) return; struct Node* ptr1, *ptr2; for (ptr1 = *head_ref; ptr1 != NULL; ptr1 = ptr1->next) { ptr2 = ptr1->next; while (ptr2 != NULL) { if (ptr1->data == ptr2->data) { struct Node* next = ptr2->next; deleteNode(&ptr2); ptr2 = next; } else ptr2 = ptr2->next; } } } int main() { struct Node *head=NULL; int n,num; printf("enter number of terms:"); scanf("%d",&n); printf("enter terms:"); while(n--){ scanf("%d",&num); push(&head,num); } printf("before remove linked list is:"); printlist(head); removed(&head); printf("after remove linked list is:"); printlist(head); return 0; }
C
#include <stdio.h> #include <stdlib.h> int N; int temp[50]; int head=0; void findDependencies(int row, int matrix[N][N]){ for(int col = 0; col < N; col++){ if(matrix[row][col] == 1){ // printf("%d ", col); temp[head] = col; head++; matrix[row][col] = 0; findDependencies(col, matrix); } } return; } int cmpfunc (const void * a, const void * b) { return ( *(int*)a - *(int*)b ); } int main() { int K; scanf("%d",&N); scanf("%d",&K); int pre[K]; int post[K]; int matrix[N][N]; for (int i = 0; i < K; i++) { scanf("%d %d", &pre[i], &post[i]); // printf("%d %d\n", pre[i], post[i]); } for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { matrix[i][j] = 0; } } printf("\n"); for (int i = 0; i < K; i++) { matrix[pre[i]][post[i]] = 1; } int col,row; for (row = 0; row < N; row++) { int test[N][N]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { test[i][j] = matrix[i][j]; } } for (int i = 0; i < 100; ++i) { temp[i] = -1; } head =0; findDependencies(row, test); int i = 0; while(temp[i] != -1){ i++; } int len = i; int array[len]; for (int i = 0; i < len; ++i) { array[i] = temp[i]; } qsort(array, len, sizeof(int), cmpfunc); for (int i = 0; i < len; ++i) { if(array[i] == row || array[i] == array[i+1]){ array[i] = -1; } } for (int i = 0; i < len-1; i++) { if(array[i] == -1){ for (int j = i; j < len-1; j++) { array[j] = array[j+1]; } len = len-1; } } if(array[len-1] == -1){ len--; } for (int i = 0; i < len; ++i) { printf("%d ", array[i]); } if(len == 0){ printf("-"); } printf("\n"); } return 0; }
C
//ray.c #include <stdlib.h> #include <stdio.h> #include <math.h> #include "light.h" void makeppm(char *file, unsigned char *ppm, int wd, int ht){ /*file pointer set to the output file to write (,"w")*/ FILE *fp; fp = fopen("test1.ppm", "w"); /*print the ppm file header*/ fprintf(fp, "P6 %d %d %d\n", wd, ht, 255); /* from data ppm[] holds, 3 (size of pixel element), size of ppm[], to fp (the file pointer) */ fwrite(ppm, 3, wd*ht, fp); /*close the file*/ fclose(fp); } int main(){ ray_t ray; //pixel dimensions for the output resolution of ppm image int wid = 640; int hgt = 480; //allocate memory for spheres, initialize sphere data sphere_t *sph; int num = 2; sph = (sphere_t*)malloc(sizeof(sphere_t) * num); sph[0].ctr.x = 0.5; sph[0].ctr.y = 0.8; sph[0].ctr.z = 4.0; sph[0].radius = 0.5; sph[0].sclr.r = 0.3; sph[0].sclr.g = 0.0; sph[0].sclr.b = 0.0; sph[1].ctr.x = -0.5; sph[1].ctr.y = 0.15; sph[1].ctr.z = 4.2; sph[1].radius = 0.6; sph[1].sclr.r = 0.0; sph[1].sclr.g = 0.3; sph[1].sclr.b = 0.0; //initiate the plane plane_t pln; pln.norm.x = 0.0; pln.norm.y = 1.0; pln.norm.z = 0.0; pln.D = -1.0; //light origin and color levels light_t light; light.origin.x = 5.0; light.origin.y = 10.0; light.origin.z = -2.0; light.amount.r = 1.0; light.amount.g = 1.0; light.amount.b = 1.0; //unsigned char array, height * width * 3(for r,g,b) unsigned char ppm[3*wid*hgt]; //loop through columns and rows of the image int x, y; for(y=0; y<hgt; y++){ for(x=0; x<wid; x++){ //initialize origin and direction of ray ray.or.x = 0; ray.or.y = 0; ray.or.z = 0; ray.dir.x = -0.67 + x/480.0; ray.dir.y = 0.5 - y/480.0; ray.dir.z = 1.0; //initialize the 0.0 - 1.0 background color color_t rgb; rgb.r = 0.1; rgb.g = 0.3; rgb.b = 0.5; //initialize t to a large number double t = 20000.0; /*check the value returned by plane_intersect() to determine hit or miss*/ //plane intersect flag xpnt_t plnx = plane_intersect(&ray, &pln); //if plane intersection happens, floor function on x,y,z //then bitwise function to determine checkerboard if(plnx.flag == 1){ if((int)floor(plnx.p.x) + (int)floor(plnx.p.y) + (int)floor(plnx.p.z) & 1){ rgb.r = 0.0; rgb.g = 0.0; rgb.b = 0.0; } else { rgb.r = 1.0; rgb.g = 1.0; rgb.b = 1.0; } color_t RGB1 = pln_lighting(&light, &ray, &plnx); rgb.r *= RGB1.r; rgb.g *= RGB1.g; rgb.b *= RGB1.b; } //loop through spheres to determine closest t int i; int closest_i = -1; for(i=0; i<2; i++){ if(intersect(&ray, &sph[i], &t) == 1){ closest_i = i; } //process lighting on pixel for the closest t if(closest_i >= 0){ color_t RGB2 = do_lighting(&light, &ray, &sph[closest_i], &t); rgb.r = sph[closest_i].sclr.r + RGB2.r; rgb.g = sph[closest_i].sclr.g + RGB2.g; rgb.b = sph[closest_i].sclr.b + RGB2.b; } } //while sphere intersect returns a hit, process rgb values //while(intersect(&ray, &sph, &t) == 1); //capping rgb at or below 1.0 if(rgb.r > 1.0) rgb.r = 1.0; if(rgb.g > 1.0) rgb.g = 1.0; if(rgb.b > 1.0) rgb.b = 1.0; //(x+y*width)*3 = current pixel * rgb then //+0, +1 or +2 to access correct color in pixel. //rgb factor for each pixel multiplied by max color value 255 ppm[(x + y*wid)*3 + 0] = (unsigned char)(rgb.r*255.0); ppm[(x + y*wid)*3 + 1] = (unsigned char)(rgb.g*255.0); ppm[(x + y*wid)*3 + 2] = (unsigned char)(rgb.b*255.0); } } //output the ppm, and free memory used for sphere makeppm("test1.ppm", ppm, wid, hgt); free(sph); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* bloc.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: oouklich <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/01/25 20:31:54 by oouklich #+# #+# */ /* Updated: 2019/02/10 14:40:54 by oouklich ### ########.fr */ /* */ /* ************************************************************************** */ #include "fillit.h" void *change_t_coordn(t_coordn *xy, int n) { if (max(xy[0].y, xy[1].y, xy[2].y, xy[3].y) < n - 1) { t_coordn_yplus(xy); return ((void*)xy); } else if (max(xy[0].y, xy[1].y, xy[2].y, xy[3].y) == n - 1 && max(xy[0].x, xy[1].x, xy[2].x, xy[3].x) < n - 1) { fix_yt_coordn(xy); t_coordn_xplus(xy); return ((void*)xy); } else return (NULL); } void *t_coordn_yplus(t_coordn *xy) { int m; m = -1; while (++m < 4) xy[m].y++; return ((void*)xy); } void *t_coordn_xplus(t_coordn *xy) { int m; m = -1; while (++m < 4) xy[m].x++; return ((void*)xy); } char **delete_caract_from_bloc(char **bloc, int n, char c) { int i; int j; i = -1; while (++i < n) { j = -1; while (++j < n) { if (bloc[i][j] == c) bloc[i][j] = '.'; } } return (bloc); } char **add_t_coordn_to_bloc(char **bloc, t_coordn *xy) { int m; m = 0; while (xy[m].x >= 0) { bloc[xy[m].x][xy[m].y] = xy[m].c; m++; } return (bloc); }
C
//// //// Created by macbook air on 2020-03-27. //// // //#include <stdio.h> // //typedef struct _empInfo{ // int empNum; // int age; //}EmpInfo; // //int main(void){ // // EmpInfo empInfoArr[1000]; // EmpInfo ei; // int eNum; // // printf("사번과 나이 입력 : "); // scanf("%d %d",&(ei.empNum),&(ei.age)); // empInfoArr[ei.empNum] = ei; // // fflush(stdin); // // printf("확인하고 싶은 직원의 사번 입력 : "); // scanf("%d",&eNum); // // ei = empInfoArr[eNum]; // printf("사번 : %d, 나이 %d \n",ei.empNum,ei.age); // // return 0; //}
C
#include <stdio.h> #include <stdlib.h> int isJolly(int num[], int size){ int* exist = (int*) calloc(size, sizeof(int)); int i = 1; for(; i < size; i++){ int index = abs(num[i] - num[i-1]); if(index > size-1 || exist[index]){ free(exist); return 0; } exist[index] = 1; } free(exist); return 1; } int* readNumbers(int count){ int *numbers = (int*) calloc(count, sizeof(int)); int i = 0; for(; i < count; i++) fscanf(stdin, "%d", &numbers[i]); return numbers; } int main(void){ int num = 0, last = 0; while(fscanf(stdin, "%d", &num) == 1 && num > 0){ int* numbers = readNumbers(num); if(isJolly(numbers, num)) printf("Jolly\n"); else printf("Not jolly\n"); free(numbers); } return 0; }
C
/** @file: 03-divisao.c * @author: Guilherme N. Ramos (gnramos@unb.br) * @disciplina: Algoritmos e Programação de Computadores * * Exemplos de utilização do operador de divisão. Em C, só é possível dividir * valores numéricos. */ #include <stdio.h> int main () { printf("Divisão:\n"); /* Escreva o resultado da operação 3 / 2 na posição indicada por %d. A * divisão de valores inteiros também é um valor inteiro. */ printf(" 3 / 2 = %d\n", 3 / 2); /* Escreva o resultado da operação 2 / 3 na posição indicada por %d. */ printf(" 2 / 3 = %d\n", 2 / 3); /* Escreva o resultado da operação 2 / 3.0 na posição indicada por %f. A * divisão de valores inteiros por reais é um valor real. */ printf(" 2 / 3.0 = %f\n", 2 / 3.0); /* Escreva o resultado da operação 2.0 / 3 na posição indicada por %f. A * divisão de valores reais por inteiros é um valor real. */ printf(" 2.0 / 3 = %f\n", 2.0 / 3); /* Escreva o resultado da operação 2.0 / 3.0 na posição indicada por %f. A * divisão de valores reais também é um valor real. */ printf(" 2.0 / 3.0 = %f\n", 2.0 / 3.0); /* Divisão por zero (0) não é uma operação válida! */ /* printf(" 2.0 / 0.0 = %f\n", 2.0 / 0.0); */ return 0; /* Não houve erro(s). */ }
C
/* calculator.c * CALCULADORA POLACA * Equipo 06 * 22/07/2017 */ #include <stdio.h> #include "scanner.h" #include "stackOfDoublesModule.h" int main(void){ double op2; Token dato; Token *t; t = &dato; while ((GetNextToken(t)) != EOF) { switch (t->type) { case Number: push(t->val); break; case Addition: push(pop() + pop()); break; case Multiplication: push(pop() * pop()); break; case Substraction: op2 = pop(); push(pop() - op2); break; case Division: op2 = pop(); if (op2 != 0.0) push(pop() / op2); else printf("error: zero divisor\n"); break; case PopResult: printf("Resultado: %.2f \n", pop()); break; default: printf("Invalido lexema %c \n",t->errorLexema); break; } } return 0; }
C
#include<stdio.h> main(){ int vetorX[100]; //100 primeiros naturais multiplos de 5 int vetorA[100]; //100 primeiros naturais ímpares int vetorC[30] = { 5,15,20,30,45,55,60,65,80,95,100,105,110,120,130,145,155,160,165,170,175,190,195,200,230,235,240,245,250,255}; int vetorCA[130]; int auxA = 0, aux; int tamXCA = 0; int CUA[130]; int XCA[230]; int i, j, repete = 0, n = 0; //----------Conjunto C----- printf("\nConjunto C = {"); for(i = 0; i < 30; i++){ printf("%d, ", vetorC[i]); } printf("}\n"); //------------CONJUNTO X------------------ printf("\nConjunto X = {"); for(i = 0; i < 100; i++){ vetorX[i] = i * 5; printf ("%d, ", vetorX[i]); } printf("}\n"); //------------CONJUNTO A------------------ printf("\nConjunto A = {"); for(i = 0; i < 200; i++){ if (i%2 == 1) { vetorA[auxA] = i; printf ("%d, ", vetorA[auxA]); auxA++; } } printf("}\n"); //------------CONJUNTO CuA------------------ for(i = 0; i < 130; i++){ if (i < 100) { vetorCA[i] = vetorA[i]; } if (i >= 100) { vetorCA[i] = vetorC[i - 100]; } } for (i = 0; i < 130; i++) { if (i == 0) { CUA[n] = vetorCA[i]; n++; } else { repete = 0; //percorre o vetor distinto verificando se o valor v[i] existe no mesmo for (j = 0; j < n; j++) { if(vetorCA[i] == CUA[j]) { repete++; } } //se o valor v[i] não foi encontrado no vetor distinto, então adiciona if (repete < 1) { CUA[n] = vetorCA[i]; n++;// aumenta o tamanho do vetor distinto } } } printf("\nConjunto CUA = {"); for (i = 0; i < n; i++) printf("%d, ", CUA[i]); printf("}\n"); //------------CONJUNTO X-(CuA)------------------ for (i = 0; i < 100; i++) { aux = 0; for (j = 0; j < 130; j++){ if (vetorX[i] != CUA[j]){ aux++; } } if (aux == 130){ XCA[tamXCA] = vetorX[i]; tamXCA++; } } printf("\nConjunto X-(CuA) = {"); for (i = 0; i < tamXCA; i++){ printf("%d,", XCA[i]); } printf("}\n\n"); }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #include <ctype.h> #include "List.h" #include "Hashtable.h" #include "Graph.h" /*/ #define HASZNALOM_A_MALLOC_FREE_POINTERET true #include "debugmalloc/debugmalloc.h" //*/ int main() { Graph *graph = g_create(); char inp[NODE_LENGTH] = ""; while(strcmp(inp, "exit") != 0) { scanf("%s", inp); if(strcmp(inp, "add_edge") == 0) { char from[NODE_LENGTH], to[NODE_LENGTH]; int w = 1; if(graph->weighted) scanf("%s %s %d", from, to, &w); else scanf("%s %s", from, to); g_add_edge(graph, from, to, w); if(!graph->directed) g_add_edge(graph, to, from, w); } else if(strcmp(inp, "display") == 0) g_display_edges(graph); else if( strcmp(inp,"list") == 0 ) g_display(graph); else if(strcmp(inp, "remove_edge") == 0) { char from[NODE_LENGTH], to[NODE_LENGTH]; scanf("%s %s", from, to); g_remove_edge(graph, from, to); } else if(strcmp(inp, "remove_node") == 0) { char nod[NODE_LENGTH]; scanf("%s", nod); g_remove_node(graph, nod); } else if(strcmp(inp, "add_node") == 0) { char nod[NODE_LENGTH]; scanf("%s", nod); g_add_node(graph, nod); } else if(strcmp(inp, "bfs") == 0) { char nod[NODE_LENGTH]; scanf("%s", nod); g_bfs(graph, nod); } else if(strcmp(inp, "dfs") == 0) { char nod[NODE_LENGTH]; scanf("%s", nod); g_dfs(graph, nod); } else if( strcmp(inp, "bell") == 0 || strcmp(inp, "bellman_ford") == 0 ) { char nod[NODE_LENGTH]; scanf("%s", nod); g_bellman_ford(graph, nod); } else if( strcmp( inp, "dijk") == 0 || strcmp(inp, "dijkstra") == 0 ) { char nod[NODE_LENGTH]; scanf("%s", nod); g_dijkstra(graph, nod); } else if( strcmp( inp, "mst") == 0 ) { char minmax[NODE_LENGTH]; scanf("%s", minmax); g_mst(graph, minmax); } else if(strcmp(inp, "load") == 0) { char file[NODE_LENGTH]; scanf("%s", file); printf("Do you wish to proceed, if you do, your current graph will be lost? (Y/N)\n"); char yn = '0'; while(tolower(yn) != 'y' && tolower(yn) != 'n') { scanf("%c", &yn); if(tolower(yn) == 'y') { if( g_load(graph, file) ) printf("Loaded graph from '%s'\n", file); else printf("Failed to load graph from '%s'\n", file ); } } } else if( strcmp(inp, "save") == 0 ) { char file[NODE_LENGTH]; scanf("%s", file); if( g_save(graph, file) ) printf("Saved graph to '%s'\n", file); else printf("Failed to save graph to '%s'\n", file ); } else if(strcmp(inp, "+w") == 0) graph->weighted = true; else if(strcmp(inp, "-w") == 0) graph->weighted = false; else if(strcmp(inp, "+d") == 0) graph->directed = true; else if(strcmp(inp, "-d") == 0) graph->directed = false; else if(strcmp(inp, "prop") == 0 || strcmp(inp, "properties") == 0 ) g_display_properties(graph); else if(strcmp(inp, "exit") != 0) printf("\'%s\' is not recognized as a command.\n", inp); } g_free(graph); //debugmalloc_dump(); return 0; }
C
#include <stddef.h> float finduniq(const float *nums, size_t n) { if(nums[0] == nums[1] && nums[2] != nums[0]) { return nums[2]; } else if(nums[0] != nums[1] && nums[0] != nums[2]) { return nums[0]; } else if(nums[0] != nums[1] && nums[0] == nums[2]) { return nums[1]; } for(size_t i = 3; i < n; i++) { if(nums[i] != nums[0]) { return nums[i]; } } return 0./.0; }
C
#include <stdio.h> int main(void) { int a; int b; int c; printf("Quelle est la valeur de a ?\n"); // on demande la valeur de a scanf("%i", &a); // recopie la saisie de l'utilisateur printf("Quelle est la valeur de b ?\n"); // on demande la valeur de b scanf("%i", &b); // recopie la saisie c = a * b; // calcul du produit printf("Le produit est égal à %i\n", c); // impression du résultat return 0; }
C
// testIfAPointIsOnTheTriangle.c // Julian Saknussemm // ?/?/? // Class Name // The objective of the program is to determine whether or not a point // lies within a triangle. // This is determined by satisfying the following rule: // A point P(x,y) is inside triangle A(x0,y0), B(x1,y1), C(x2,y2) // iff // P is on the same side of the line AB as C // P is on the same side of the line BC as A // and // P is on the same side of the line AC as B // // A special case exits for a vertical line (inf gradient) when // testing the side of the line #include <stdio.h> #include <stdlib.h> #define UNDER = -1 #define ON_THE_LINE = 0 #define OVER = 1 int isPointOnLine( double px, double py, double m, double b ) if( py < m * px + b ) { return UNDER; }else if ( py == m * px + b ){ return ON_THE_LINE; } else { return OVER; } } int twoPointsSameSide( double px, double py, double m,double b, double lx,double ly) { // two points lie on the same side of a line return (test2( px,py, m,b )==test2(lx,ly,m,b)); } int tritest(double x0,double y0,double x1,double y1,double x2,double y2, double px, double py){ int line1, line2, line3; // line eqns double m01 = (y1-y0)/(x1-x0); // b: y - y1 = m( x - x1 ), x = 0 double b01 = m01 // -x1 + y1; double m02, m12, b02, b12; m02 = (y2-y0)/(x2-x0); m12 = (y2-y1)/(x2-x1); b02 = m02 // -x2 + y2; b12 = m12 // -x2 + y2; // vertical line checks if( x1 == x0 ) { line1 = ( (px <= x0) == (x2 <= x0) ); } else { line1 = twoPointsSameSide( px, py, m01, b01,x2,y2); } if( x1 == x2 ) { line2 = ( (px <= x2) == (x0 <= x2) ); } else { line2 = test1(px,py, m12, b12,x0,y0); } if( x2 == x0 ) { line3 = ( (px <= x0 ) == (x1 <= x0) );} else { line3 = test1(px, py, m02,b02,x1,y1); } return line1 && line2 && line3; } int main(int argc, char// argv[]) { double x0,y0,x1,y1,x2,y2,px; double py; int scanfsReturnValueAggregatedOverAllScanfs = 0; //get input printf("Triangle Vertex A (x,y): "); scanfsReturnValueAggregatedOverAllScanfs += scanf("%lf,%lf", &x0,&y0); printf("Triangle Vertex B (x,y): "); scanfsReturnValueAggregatedOverAllScanfs += scanf("%lf,%lf", &x1,&y1); printf("Triangle Vertex C (x,y): "); scanfsReturnValueAggregatedOverAllScanfs += scanf("%lf,%lf", &x2,&y2); printf("Test Point (x,y): "); scanfsReturnValueAggregatedOverAllScanfs += scanf("%lf,%lf", &px,&py); // print error if( scanfsReturnValueAggregatedOverAllScanfs != 8 ) { printf("You're stupid and didn't put in the right inputs!\n"); return 1; } // print answer printf("Point (%.2lf,%.2lf) is ", px,py); if(tritest(x0,y0,x1,y1,x2,y2,px,py)) printf("inside"); else printf("outside the Triangle\n"); return EXIT_SUCCESS; }
C
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 1996, 2013 Oracle and/or its affiliates. All rights reserved. */ #include <sys/types.h> #include <ctype.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> typedef struct { char *name; /* API name */ u_int used_mask; /* Bits used. */ } API; API **api_list, **api_end; typedef struct { char *name; /* Flag name */ int api_cnt; /* APIs that use this flag. */ API **api, **api_end; u_int value; /* Bit value */ } FLAG; FLAG **flag_list, **flag_end; int verbose; char *progname; int add_entry(char *, char *); void define_print(char *, u_int); void dump_api(void); void dump_flags(void); int flag_cmp_alpha(const void *, const void *); int flag_cmp_api_cnt(const void *, const void *); int generate_flags(void); int parse(void); void print_api_mask(void); void print_api_remainder(void); void print_flag_value(void); int syserr(void); int usage(void); int main(int argc, char *argv[]) { enum { API_MASK, API_REMAINDER, FLAG_VALUE } output; int ch; if ((progname = strrchr(argv[0], '/')) == NULL) progname = argv[0]; else ++progname; output = FLAG_VALUE; while ((ch = getopt(argc, argv, "mrv")) != EOF) switch (ch) { case 'm': output = API_MASK; break; case 'r': output = API_REMAINDER; break; case 'v': verbose = 1; break; case '?': default: return (usage()); } argc -= optind; argv += optind; if (parse() || generate_flags()) return (EXIT_FAILURE); switch (output) { case API_MASK: print_api_mask(); break; case API_REMAINDER: print_api_remainder(); break; case FLAG_VALUE: print_flag_value(); break; } if (verbose) { dump_api(); dump_flags(); } return (EXIT_SUCCESS); } int parse() { int lc; char *p, *api, buf[256]; api = NULL; /* * Read the method name/flag pairs. */ for (lc = 1; fgets(buf, sizeof(buf), stdin) != NULL; ++lc) { if ((p = strchr(buf, '\n')) != NULL) *p = '\0'; else { fprintf( stderr, "%s: %d: line too long\n", progname, lc); return (1); } /* Ignore any empty line or hash mark. */ if (buf[0] == '\0' || buf[0] == '#') continue; /* * A line without leading whitespace is an API name, a line * with leading whitespace is a flag name. */ if (isspace(buf[0])) { if ((p = strtok(buf, " \t")) == NULL || *p == '#') continue; /* A flag without an API makes no sense. */ if (api == NULL) goto format; /* Enter the pair into the array. */ if (add_entry(api, p)) return (1); } else { if ((p = strtok(buf, " \t")) == NULL) continue; if (api != NULL) free(api); if ((api = strdup(p)) == NULL) return (syserr()); } if ((p = strtok(NULL, " \t")) != NULL && *p != '#') goto format; } return (0); format: fprintf(stderr, "%s: format error: line %d\n", progname, lc); return (1); } int add_entry(char *api_name, char *flag_name) { FLAG **fpp, *fp; API **app, *ap, **p; u_int cnt; /* Search for this api's API structure. */ for (app = api_list; app != NULL && *app != NULL && app < api_end; ++app) if (strcmp(api_name, (*app)->name) == 0) break; /* Allocate new space in the API array if necessary. */ if (app == NULL || app == api_end) { cnt = app == NULL ? 100 : (u_int)(api_end - api_list) + 100; if ((api_list = realloc(api_list, sizeof(API *) * cnt)) == NULL) return (syserr()); api_end = api_list + cnt; app = api_list + (cnt - 100); memset(app, 0, (u_int)(api_end - app) * sizeof(API *)); } /* Allocate a new API structure and fill in the name if necessary. */ if (*app == NULL && ((*app = calloc(sizeof(API), 1)) == NULL || ((*app)->name = strdup(api_name)) == NULL)) return (syserr()); ap = *app; /* * There's a special keyword, "__MASK=<value>" that sets the initial * flags value for an API, and so prevents those flag bits from being * chosen for that API's flags. */ if (strncmp(flag_name, "__MASK=", sizeof("__MASK=") - 1) == 0) { ap->used_mask |= strtoul(flag_name + sizeof("__MASK=") - 1, NULL, 0); return (0); } /* Search for this flag's FLAG structure. */ for (fpp = flag_list; fpp != NULL && *fpp != NULL && fpp < flag_end; ++fpp) if (strcmp(flag_name, (*fpp)->name) == 0) break; /* Realloc space in the FLAG array if necessary. */ if (fpp == NULL || fpp == flag_end) { cnt = fpp == NULL ? 100 : (u_int)(flag_end - flag_list) + 100; if ((flag_list = realloc(flag_list, sizeof(FLAG *) * cnt)) == NULL) return (syserr()); flag_end = flag_list + cnt; fpp = flag_list + (cnt - 100); memset(fpp, 0, (u_int)(flag_end - fpp) * sizeof(FLAG *)); } /* Allocate a new FLAG structure and fill in the name if necessary. */ if (*fpp == NULL && ((*fpp = calloc(sizeof(FLAG), 1)) == NULL || ((*fpp)->name = strdup(flag_name)) == NULL)) return (syserr()); fp = *fpp; ++fp->api_cnt; /* Check to see if this API is already listed for this flag. */ for (p = fp->api; p != NULL && *p != NULL && p < fp->api_end; ++p) if (strcmp(api_name, (*p)->name) == 0) { fprintf(stderr, "duplicate entry: %s / %s\n", api_name, flag_name); return (1); } /* Realloc space in the FLAG's API array if necessary. */ if (p == NULL || p == fp->api_end) { cnt = p == NULL ? 20 : (u_int)(fp->api_end - fp->api) + 20; if ((fp->api = realloc(fp->api, sizeof(API *) * cnt)) == NULL) return (syserr()); fp->api_end = fp->api + cnt; p = fp->api + (cnt - 20); memset(p, 0, (u_int)(fp->api_end - fp->api) * sizeof(API *)); } *p = ap; return (0); } void dump_api() { API **app; printf("=============================\nAPI:\n"); for (app = api_list; *app != NULL; ++app) printf("%s (%#x)\n", (*app)->name, (*app)->used_mask); } void dump_flags() { FLAG **fpp; API **api; char *sep; printf("=============================\nFLAGS:\n"); for (fpp = flag_list; *fpp != NULL; ++fpp) { printf("%s (%#x, %d): ", (*fpp)->name, (*fpp)->value, (*fpp)->api_cnt); sep = ""; for (api = (*fpp)->api; *api != NULL; ++api) { printf("%s%s", sep, (*api)->name); sep = ", "; } printf("\n"); } } int flag_cmp_api_cnt(const void *a, const void *b) { FLAG *af, *bf; af = *(FLAG **)a; bf = *(FLAG **)b; if (af == NULL) { if (bf == NULL) return (0); return (1); } if (bf == NULL) { if (af == NULL) return (0); return (-1); } if (af->api_cnt > bf->api_cnt) return (-1); if (af->api_cnt < bf->api_cnt) return (1); return (strcmp(af->name, bf->name)); } int generate_flags() { FLAG **fpp; API **api; u_int mask; /* Sort the FLAGS array by reference count, in reverse order. */ qsort(flag_list, (u_int)(flag_end - flag_list), sizeof(FLAG *), flag_cmp_api_cnt); /* * Here's the plan: walk the list of flags, allocating bits. For * each flag, we walk the list of APIs that use it and find a bit * none of them are using. That bit becomes the flag's value. */ for (fpp = flag_list; *fpp != NULL; ++fpp) { mask = 0xffffffff; /* Set to all 1's */ for (api = (*fpp)->api; *api != NULL; ++api) mask &= ~(*api)->used_mask; /* Clear API's bits */ if (mask == 0) { fprintf(stderr, "%s: ran out of bits at flag %s\n", progname, (*fpp)->name); return (1); } (*fpp)->value = mask = 1 << (ffs(mask) - 1); for (api = (*fpp)->api; *api != NULL; ++api) (*api)->used_mask |= mask; /* Set bit for API */ } return (0); } int flag_cmp_alpha(const void *a, const void *b) { FLAG *af, *bf; af = *(FLAG **)a; bf = *(FLAG **)b; if (af == NULL) { if (bf == NULL) return (0); return (1); } if (bf == NULL) { if (af == NULL) return (0); return (-1); } return (strcmp(af->name, bf->name)); } void print_api_mask() { API **app; char *p, buf[256]; /* Output a mask for the API. */ for (app = api_list; *app != NULL; ++app) { (void)snprintf( buf, sizeof(buf), "_%s_API_MASK", (*app)->name); for (p = buf; *p != '\0'; ++p) if (islower(*p)) *p = toupper(*p); else if (!isalpha(*p)) *p = '_'; define_print(buf, (*app)->used_mask); } } void print_api_remainder() { API **app; int unused, i; /* Output the bits remaining for the API. */ for (app = api_list; *app != NULL; ++app) { for (i = unused = 0; i < 32; ++i) if (!((*app)->used_mask & (1 << i))) ++unused; printf("%s: %d bits unused\n", (*app)->name, unused); } } void print_flag_value() { FLAG **fpp; /* Sort the FLAGS array in alphabetical order. */ qsort(flag_list, (u_int)(flag_end - flag_list), sizeof(FLAG *), flag_cmp_alpha); /* Output each flag's value. */ for (fpp = flag_list; *fpp != NULL; ++fpp) define_print((*fpp)->name, (*fpp)->value); } void define_print(char *name, u_int value) { char *sep; switch (strlen(name) / 8) { case 0: sep = "\t\t\t\t\t"; break; case 1: sep = "\t\t\t\t"; break; case 2: sep = "\t\t\t"; break; case 3: sep = "\t\t"; break; default: sep = "\t"; break; } printf("#define\t%s%s%#010x\n", name, sep, value); } int syserr(void) { fprintf(stderr, "%s: %s\n", progname, strerror(errno)); return (1); } int usage() { (void)fprintf(stderr, "usage: %s [-mrv]\n", progname); return (EXIT_FAILURE); }
C
#include<stdio.h> int main() { int a,b,c,s=0; for(a=1;a<5;a++) { for(b=1;b<5;b++) if(a!=b) for(c=1;c<5;c++) if(a!=c&&b!=c) printf("%d\n",a*100+b*10+c); } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* print.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mstratu <mstratu@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/10/22 18:37:25 by mstratu #+# #+# */ /* Updated: 2019/10/22 19:42:07 by mstratu ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/ft_ssl.h" void encode(unsigned char *str, uint32_t *hash, unsigned int len) { unsigned int i; unsigned int pos_of_has; i = 0; pos_of_has = 0; while (i < len) { str[i] = (unsigned char)(hash[pos_of_has] & 0xff); str[i + 1] = (unsigned char)((hash[pos_of_has] >> 8) & 0xff); str[i + 2] = (unsigned char)((hash[pos_of_has] >> 16) & 0xff); str[i + 3] = (unsigned char)((hash[pos_of_has] >> 24) & 0xff); i += 4; pos_of_has++; } } void conversion(unsigned char *res, uint8_t len) { uint8_t i; int num; i = 0; while (i < len) { num = hex_len((unsigned long)res[i]); if (num == 1) { ft_putchar('0'); print_hex((unsigned long)res[i]); } else print_hex((unsigned long)res[i]); i++; } } int hex_len(unsigned long num) { int res; res = 1; while (num > 15) { num /= 16; res++; } return (res); } void print_hex(unsigned long num) { char *tab; tab = "0123456789abcdef"; if (num > 15) { print_hex(num / 16); print_hex(num % 16); } else ft_putchar(tab[num]); } void print_buff_hash(uint32_t *hash, uint8_t len) { unsigned char res[len]; encode(res, hash, len); conversion(res, len); }
C
#include <stdio.h> int main(){ int a,b; int i; int ans=0; scanf("%d %d",&a,&b); for(i=1;i<b-a;i++){ ans+=i; } ans-=a; printf("%d",ans); return 0; } ./Main.c: In function main: ./Main.c:8:2: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result] scanf("%d %d",&a,&b); ^
C
#include<stdio.h> void f_binary(int n); int main() { int n; printf("Է : "); scanf_s("%d", &n); f_binary(n); return 0; } void f_binary(int n) { if (n==0||n==1) { printf("%d", n); } else { f_binary(n / 2); printf("%d", n % 2); } }
C
#include <stdio.h> #include <sys/types.h> #include <unistd.h> void main() x { int pid=fork(); if(pid<0) printf("Process creation failed"); else if(pid==0) printf("\nChild process executing\n PID: %d\nParent PID: %d\n",getpid(),getppid()); else printf("\nParent process executing\n PID: %d\n",getpid()); }
C
/** * Practice using #define macros to customize C language */ #include <stdio.h> #define run() main() #define print printf int run() { print("Hello World!\n"); return 0; }
C
//Common Function #include <stdio.h> #include <string.h> #include <stdlib.h> #include "../../include/common.h" #define BLUE "\x1B[34m" #define GREEN "\x1B[42m" #define RED "\x1B[41m" #define RESET "\x1B[0m" #define ZONES 4 void show_msg(int type, const char *msg) { if(type == 0) printf(RED "%s" RESET, msg); else printf(GREEN "%s" RESET, msg); printf("\n"); } void error(const char *msg) { perror(msg); exit(0); } int split(char *str, char c, char ***arr) { int count = 1; int token_len = 1; int i = 0; char *p; char *t; p = str; while (*p != '\0') { if (*p == c) count++; p++; } *arr = (char**) malloc(sizeof(char*) * count); if (*arr == NULL) exit(1); p = str; while (*p != '\0') { if (*p == c) { (*arr)[i] = (char*) malloc( sizeof(char) * token_len ); if ((*arr)[i] == NULL) exit(1); token_len = 0; i++; } p++; token_len++; } (*arr)[i] = (char*) malloc( sizeof(char) * token_len ); if ((*arr)[i] == NULL) exit(1); i = 0; p = str; t = ((*arr)[i]); while (*p != '\0') { if (*p != c && *p != '\0') { *t = *p; t++; } else { *t = '\0'; i++; t = ((*arr)[i]); } p++; } return count; } /*char **splitMyConf(char *conf) { char delim[] = ";"; char *token; char tabConf[4][8]; int i = 0; int j; //char *conf_cpy = strcpy(conf_cpy, conf); for (token = strtok(conf, delim); token; token = strtok(NULL, delim)) { //printf("%s\n", token); char _delim[] = ":"; //printf("First token=%s\n", token); strcpy(tabConf[i], token); printf("tabConf %d -> %s\n", i, tabConf[i]); i++; //second_split(token, conf, _delim); } return tabConf; }*/ char *append(const char *s, char c) { int len = strlen(s); char buf[len+2]; strcpy(buf, s); buf[len] = c; buf[len + 1] = 0; return strdup(buf); } char **splitIt(char *string) { char **arr = NULL; split(string, ' ', &arr); return (arr); } /*void getMyConf(char *path_file) { int c; FILE *file; file = fopen(path_file, "r"); char *all_conf = malloc(sizeof(char*) + 1); char **tabConf; if (file) { while ((c = getc(file)) != EOF) { all_conf = append(all_conf, c); } //printf("My conf line : %s\n =============\n", all_conf); fclose(file); tabConf = splitMyConf(all_conf); printf("Places totales du terrain : \n"); printf("\t\tZone A -> %s\n", tabConf[0]); printf("\t\tZone B -> %s\n", tabConf[1]); printf("\t\tZone C -> %s\n", tabConf[2]); printf("\t\tZone D -> %s\n", tabConf[3]); } }*/
C
#define _CRT_SECURE_NO_WARNINGS #include "server.h" int ExceptionFilter( DWORD Code, EXCEPTION_POINTERS *ExceptionPointers ) { printf("[EXCEPTION] ExceptionCode=0x%x, EIP=0x%x, ESP=0x%x\n", Code, ExceptionPointers->ContextRecord->Eip, ExceptionPointers->ContextRecord->Esp); Log("[EXCEPTION] ExceptionCode=0x%x, EIP=0x%x, ESP=0x%x\n", Code, ExceptionPointers->ContextRecord->Eip, ExceptionPointers->ContextRecord->Esp); return EXCEPTION_EXECUTE_HANDLER; } BOOLEAN CmdHandleUser( char* User, int *UserId ) { DWORD i; __try { // Now search if the given username exists for (i = gUserCount-1; i >= 0; i--) { if (0 == _stricmp(gUserData[i].Username, User)) { *UserId = i; return TRUE; } } } __except(ExceptionFilter(GetExceptionCode(), GetExceptionInformation())) { } *UserId = -1; return FALSE; } BOOLEAN CmdHandlePass( int UserId, char *Password ) { char tempPass[DEFAULT_MAX_PASS_LEN]; tempPass[0] = '\0'; strcpy(tempPass, Password); if (0 == strcmp(gUserData[UserId].Password, tempPass)) { return TRUE; } return FALSE; } BOOLEAN CmdHandleInfo( int UserId, char *Details, char *Output, int *OutLength ) { DWORD param = 1; DWORD fields; WORD size; BOOLEAN ret = TRUE; int i; __try { fields = sscanf_s(Details, "%d", &param); // Get the number of fields to return size = (WORD)(fields * param * FIELD_SIZE); // 'fields' should be 1 (one field identified by sscanf_s), 'param' - number of fields to return // If either of those is 0, nothing will be returned if (param > 3) { // Make sure we don't return more than needed (size will be maximum 3 * FIELD_SIZE = 75) ret = FALSE; __leave; } *OutLength = size; printf("size = %d\n", size); // Copy in Output the computed size for (i = 0; i < size; i++) { Output[i] = ((char*)(&gUserData[UserId]))[i]; } ret = TRUE; } __except(ExceptionFilter(GetExceptionCode(), GetExceptionInformation())) { } return ret; } void _AddFileToOutput( char *File, char *Output, int *OutLength ) { int len = strlen(File); // Add file name to Output, but replace '.txt' with ' ' strcat_s(Output, DEFAULT_BUFLEN, File); *OutLength += len - 3; Output[*OutLength - 1] = ' '; // Output[*OutLength] = 0; // } void CmdHandleList( int UserId, char *Output, int *OutLength ) { WIN32_FIND_DATAA FindFileData; HANDLE hFind; char folder[32]; sprintf_s(folder, 20, "..\\msgs\\%d\\*.txt", UserId); printf("Searching in folder: %s\n", folder); hFind = FindFirstFileA(folder, &FindFileData); if (hFind == INVALID_HANDLE_VALUE) { printf ("FindFirstFile failed (%d)\n", GetLastError()); return; } //printf ("The first file found is %s\n", FindFileData.cFileName); _AddFileToOutput(FindFileData.cFileName, Output, OutLength); while (FindNextFileA(hFind, &FindFileData)) { //printf ("The next file found is %s\n", FindFileData.cFileName); _AddFileToOutput(FindFileData.cFileName, Output, OutLength); } FindClose(hFind); } void CmdHandleGet( int UserId, char *Message, char *Output, int *OutLength ) { FILE *file; char filename[64]; sprintf_s(filename, 64, "..\\msgs\\%d\\%s.txt", UserId, Message); printf("Opening file: %s\n", filename); fopen_s(&file, filename, "r"); if (NULL == file) { sprintf_s(Output, DEFAULT_BUFLEN, "[ERROR] Message not found."); *OutLength = strlen(Output); printf("Error opening message file\n"); return; } sprintf_s(Output, DEFAULT_BUFLEN, "[OK]\n"); *OutLength = strlen(Output); *OutLength += fread_s(&Output[*OutLength], DEFAULT_BUFLEN, 1, DEFAULT_BUFLEN, file); fclose(file); } HANDLE CmdHandleCreateMsg(char* filePath, int UserId) { char directoryPath[10]; sprintf_s(directoryPath, 10, "..\\msgs\\%d", UserId); BOOL newDirectory = CreateDirectoryA( directoryPath, NULL ); if (ERROR_ALREADY_EXISTS == newDirectory) { Log("Directory already exists %s\n", directoryPath); } else { Log("Directory created %s\n", directoryPath); } char dest[64]; sprintf_s(dest, 64, "..\\msgs\\%d\\%s.txt", UserId, filePath); return createFile(dest); } void CmdHandleWriteMsg(HANDLE fileHandle) { TestMAPHandle(fileHandle); }
C
#include "holberton.h" /** * infinite_add - prints an integer as if it were a string * @n1: integer to print * @n2: char * @r: buffer * @size_r: size * Return: void */ char *infinite_add(char *n1, char *n2, char *r, int size_r) { int a, b, n = 0, k = 0; for (a = 0; n1[a] != '\0'; a++) ; for (b = 0; n2[b] != '\0'; b++) ; if (b >= (size_r - 1) || a >= (size_r - 1)) return (0); r[size_r] = '\0'; while (a > 0 && b > 0) { n = n + (n1[a - 1] - '0') + (n2[b - 1] - '0'); r[size_r - 1] = (n % 10 + '0'); n = n / 10; a--; b--; size_r--; } while (a > 0 || b > 0) { if (a > 0) { n = n + (n1[a - 1] - '0'); a--; } else n = n + (n2[b - 1] - '0'); b--; r[size_r - 1] = (n % 10 + '0'); n = n / 10; size_r--; } if (n != 0) r[size_r - 1] = (n + '0'); else size_r++; for (k = 0; r[k + size_r - 1] != '\0'; k++) r[k] = r[k + size_r - 1]; r[k] = '\0'; return (r); }
C
#include <stdio.h> #include <locale.h> int main() { setlocale(LC_ALL,""); int X, Y, x, y, z, i; float A, B, C, total, Total; printf("Temos 3 tipos de produto:\nTipo A---R$10.00---Cdigo 1---desconto de 20%\nTipo B---R$20.00---Cdigo 2---desconto de 10%\nTipo C---R$30.00---Cdigo 3---sem desconto"); printf("Qual o produto que deseja comprar!\nCdigo: "); scanf("%d", &i); while((i>-1)&&(i<4)) { if(i==1) { printf("Quantas unidades desse produto deseja comprar?\nQuantidade: "); scanf("%d", &x); X= x*10; A= X-((X*2)/10); } if(i==2) { printf("Quantas unidades desse produto deseja comprar?\nQuantidade: "); scanf("%d", &y); Y= y*20; B= Y-(Y/10); } if(i==3) { printf("Quantas unidades desse produto deseja comprar?\nQuantidade: "); scanf("%d", &z); C= z*30; } if(i==0) break; printf("Se deseja comprar outro produto digite o cdigo, seno digite 0 para finalizar a compra.\nCdigo:"); scanf("%d", &i); } printf("\n\nOs valores so:\nA---R$ %.2f\nB---R$ %.2f\nC---R$ %.2f", A, B, C); total= A+B+C; if(total>=80) { printf("\nSua compra foi maior que R$80.00 ento tera um desconto de 10%\n"); Total=total-(total/10); printf("Total---R$ %.2f",Total); }else{ printf("\nTotal---R$ %.2f", total); } return 0; }
C
/* * ===================================================================================== * * Filename: list.c * * Description: list * * Version: 1.0 * Created: Thursday 04 July 2013 04:29:19 CST * Revision: none * Compiler: gcc * * Author: Zhang Dongsheng (mars), zhangdongsheng1224@gmail.com * Organization: HANGZHOU DIANZI UNIVERSITY * * ===================================================================================== */ #include <stdio.h> #include <stdlib.h> #include "list.h" link freelist; void initNodes(int N) { int i; freelist = malloc((N + 1) * sizeof(*freelist)); for (i = 0; i < N + 1; ++i) freelist[i].next = &freelist[i + 1]; freelist[N].next = NULL; } link newNode(int i) { link x = deleteNext(freelist); x->item = i; x->next = x; return x; } void freeNode(link x) { insertNext(freelist, x); } // x 后面插入 t void insertNext(link x, link t) { t->next = x->next; x->next = t; } // 取出 x 的下一个节点 link deleteNext(link x) { link t = x->next; x->next = t->next; return t; } link Next(link x) { return x->next; } int Item(link x) { return x->item; }
C
#include "Mapping.h" int equidistribute( const realArray & w, realArray & r ); // define F(x) 1.+(x) #define F(x) 1.+(x)+(x)*(x) int main() { Range R(0,10); realArray w(R),r(R); real h=1./(R.getBound()-R.getBase()); for( int i=R.getBase(); i<=R.getBound(); i++ ) { w(i)=F((i-R.getBase())*h); } w.display("here is w"); equidistribute( w,r ); r.display("here is r"); // check if the function is equi-distributed for( i=R.getBase()+1; i<=R.getBound(); i++ ) { w(i)=F(r(i)); printf("equi = %e\n",.5*(w(i)+w(i-1))*(r(i)-r(i-1))); } }
C
#include <stdio.h> int main_prob04_4(void) { int num; printf(" Էϼ : "); scanf("%d", &num); num = ~num + 1; printf(" : %d\n\n", num); int num2; num2 = 3 << 3; // 3Ʈ ̵, 2^3=8 num2 = num2 >> 2; // 2Ʈ ̵, 2^2=4 printf("3 * 8 / 4 = %d\n\n", num2); return 0; }
C
// { dg-do run } // Shows that problem of initializing one object's secondary base from // another object via a user defined copy constructor for that base, // the pointer for the secondary vtable is not set after implicit // copying of the outer class, but rather has the pointer to the main // vtable for the secondary base left over from the user defined copy // constructor for that base. // Correct answer is B::beefy. // g++ prints A::beefy, which is wrong. Cfront gets it right. // prms-id: 2846 extern "C" int printf(const char *, ...); extern "C" void exit(int); class B; class A { public: A(void){} A(const A&){} virtual void print(void) const { } B compute(void) const; }; class C { public: C() { } C(C& o) { } // with it, things are wrong, without it, they're ok virtual void beefy(void) const { printf("A::beefy\n"); exit(1); } }; class B : private A, public C { public: B(const A& x, int){} void beefy(void) const { printf("B::beefy\n"); } }; B A::compute(void) const { B sub(*this, 1); return sub; } int main () { A titi; titi.compute().beefy(); return 0; }
C
/* Code to compute a Number Theoretic Transform for multiplication in the ring F_q[x] / <x^n+1>. n = 1024, q = 59393 */ #include "FFT_1024_59393.h" #ifdef TESTFFT #include <stdio.h> #include <sys/time.h> #endif /*Set n and q*/ static const FFTSHORT n = 1024; static const FFTSHORT q = 59393; #include "FFT_1024_59393_constants.c" /* We use Gentleman-Sande, decimation-in-frequency FFT, for the forward FFT. Note that we will not perform the usual scambling / bit-reversal procedure here because we will invert the fourier transform using decimation-in-time. */ void FFT_forward_1024_59393(FFTSHORT x[1024]) { FFTSHORT index, step; FFTSHORT i,j,m; FFTSHORT t0,t1; step = 1; for (m = n>>1; m >= 1; m=m>>1) { index = 0; for (j = 0 ; j < m; ++j) { for (i = j; i < n; i += (m<<1)) { ADD_MOD(t0, x[i], x[i+m], q); ADD(t1, x[i], q - x[i+m]); MUL_MOD(x[i+m], t1, W[index], q); x[i] = t0; } SUB_MODn(index, index, step); } step = step << 1; } } /* We use Cooley-Tukey, decimation-in-time FFT, for the inverse FFT. Note that we will not perform the usual scambling / bit-reversal procedure here because we will the forward fourier transform is using decimation-in-frequency. */ void FFT_backward_1024_59393(FFTSHORT x[1024]) { FFTSHORT index, step; FFTSHORT i,j,m; FFTSHORT t0,t1; step = n>>1; for (m = 1; m < n; m=m<<1) { index = 0; for (j = 0 ; j < m; ++j) { for (i = j; i < n; i += (m<<1)) { t0 = x[i]; t0 -= (t0 >= q) ? q : 0; MUL_MOD(t1, x[i+m], W_rev[index], q); ADD(x[i], t0, t1); ADD(x[i+m], t0, q - t1); } SUB_MODn(index, index, step); } step = step >> 1; } for (i = 0; i < n; ++i) { x[i] -= (x[i] >= q) ? q : 0; } } /* We use Gentleman-Sande, decimation-in-frequency FFT, for the forward FFT. We premultiply x by the 2n'th roots of unity to affect a Discrete Weighted Fourier Transform, so when we apply pointwise multiplication we obtain the negacyclic convolution, i.e. multiplication modulo x^n+1. Note that we will not perform the usual scambling / bit-reversal procedure here because we will invert the fourier transform using decimation-in-time. */ void FFT_twisted_forward_1024_59393(FFTSHORT x[1024]) { FFTSHORT index, step; FFTSHORT i,j,m; FFTSHORT t0,t1; //Pre multiplication for twisted FFT j = 0; for (i = 0; i < n>>1; ++i) { MUL_MOD(x[j], x[j], W[i], q); j++; MUL_MOD(x[j], x[j], W_sqrt[i], q); j++; } step = 1; for (m = n>>1; m >= 1; m=m>>1) { index = 0; for (j = 0 ; j < m; ++j) { for (i = j; i < n; i += (m<<1)) { ADD_MOD(t0, x[i], x[i+m], q); ADD(t1, x[i], q - x[i+m]); MUL_MOD(x[i+m], t1, W[index], q); x[i] = t0; } SUB_MODn(index, index, step); } step = step << 1; } } /* We use Cooley-Tukey, decimation-in-time FFT, for the inverse FFT. We postmultiply x by the inverse of the 2n'th roots of unity * n^-1 to affect a Discrete Weighted Fourier Transform, so when we apply pointwise multiplication we obtain the negacyclic convolution, i.e. multiplication modulo x^n+1. Note that we will not perform the usual scambling / bit-reversal procedure here because we will the forward fourier transform is using decimation-in-frequency. */ void FFT_twisted_backward_1024_59393(FFTSHORT x[1024]) { FFTSHORT index, step; FFTSHORT i,j,m; FFTSHORT t0,t1; step = n>>1; for (m = 1; m < n; m=m<<1) { index = 0; for (j = 0 ; j < m; ++j) { for (i = j; i < n; i += (m<<1)) { t0 = x[i]; t0 -= (t0 >= q) ? q : 0; MUL_MOD(t1, x[i+m], W_rev[index], q); ADD(x[i], t0, t1); ADD(x[i+m], t0, q - t1); } SUB_MODn(index, index, step); } step = step >> 1; } //Post multiplication for twisted FFT j = 0; for (i = 0; i < n>>1; ++i) { MUL_MOD(x[j], x[j], W_rev[i], q); j++; MUL_MOD(x[j], x[j], W_sqrt_rev[i], q); j++; } } void _FFT_forward_1024_59393(FFTSHORT *x) { FFT_twisted_forward_1024_59393(x); } void _FFT_backward_1024_59393(FFTSHORT *x) { int i; FFT_twisted_backward_1024_59393(x); for (i=0; i<1024; ++i) MUL_MOD(x[i], x[i], 59335, 59393); }
C
/** @file task1.c * Demonstrates semaphores to contol the synchronization of threads. * * This program starts a number of processes that are synchronized with * semaphores to control the text output. * * @author Robert van Engelen * Modified 3/1/21 with permission by CAC **/ #include <stdlib.h> #include <stdio.h> #include <unistd.h> #ifdef _POSIX_THREADS # include <pthread.h> #endif #include <semaphore.h> void *text(void *arg); int counter = 0; int code[] = { 0,1,2,3,4,5,6 }; int sem_wait(sem_t *sem); int sem_post(sem_t *sem); int pthread_mutex_lock(pthread_mutex_t *mutex); int pthread_mutex_unlock(pthread_mutex_t *mutex); static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; sem_t sema[7]; int main() { int i, j; pthread_t tid[7]; pthread_mutex_t mutex; int ret; int counter; for (i = 0; i < 7; i++) { pthread_create(&tid[i], NULL, text, (void *) &code[i]); } for (j=0;j<7;j++) { pthread_join(tid[j],NULL); } return 0; } void *text(void *arg) { int ret; pthread_mutex_lock(&mutex); //pthread_mutex_lock(); int n = *(int*)arg; if(n!=counter) { if(n==1) { sem_wait(&sema[1]); } if (n==2) { sem_wait(&sema[2]); } if(n==3) { sem_wait(&sema[3]); } if(n==4) { sem_wait(&sema[4]); } if(n==5) { sem_wait(&sema[5]); } if(n==6) { sem_wait(&sema[6]); } if(n==7) { sem_wait(&sema[7]); } } if (n==counter) { counter++; } switch (n) { case 0: printf("A semaphore S is an integer-valued variable which can take only non-negative\n"); printf("values. Exactly two operations are defined on a semaphore:\n\n"); sem_post(&sema[1]); //counter++; break; case 1: printf("Signal(S): If there are processes that have been suspended on this semaphore,\n"); printf(" wake one of them, else S := S+1.\n\n"); sem_post(&sema[2]); //counter++; break; case 2: printf("Wait(S): If S>0 then S:=S-1, else suspend the execution of this process.\n"); printf(" The process is said to be suspended on the semaphore S.\n\n"); sem_post(&sema[3]); //counter++; break; case 3: printf("The semaphore has the following properties:\n\n"); sem_post(&sema[4]); //counter++; break; case 4: printf("1. Signal(S) and Wait(S) are atomic instructions. In particular, no\n"); printf(" instructions can be interleaved between the test that S>0 and the\n"); printf(" decrement of S or the suspension of the calling process.\n\n"); sem_post(&sema[5]); //counter++; break; case 5: printf("2. A semaphore must be given an non-negative initial value.\n\n"); sem_post(&sema[6]); //counter++; break; case 6: printf("3. The Signal(S) operation must waken one of the suspended processes. The\n"); printf(" definition does not specify which process will be awakened.\n\n"); sem_post(&sema[7]); //counter++; break; } pthread_mutex_unlock(&mutex); //sem_post(sem_t *); pthread_exit(0); }
C
/* * Escreva um programa que calcule a resistência equivalente(Re) de um circuito elétrico * composto de três resistores R1, R2, R3, ligados em paralelo. Os valores dos resistores * deverão ser lidos pelo programa. */ #include <stdio.h> #include <math.h> #include <stdlib.h> int main(){ double re, r1, r2, r3; printf("Digite os valores das três resistências\n"); scanf("%lf\n", &r1); scanf("%lf\n", &r2); scanf("%lf", &r3); printf("a resistência Equivalente é %.2f: \n",((r1 * r2 * r3) / (r1+ r2 + r3))); }
C
#include<stdio.h> #include<stdlib.h> void main(int argc, char *argv[]) { int arg; for(arg=0;arg<argc;arg++) { if(argv[arg][0]=='-') { printf("option:%s\n",argv[arg]+1); } else printf("argument %d: %s\n",arg,argv[arg]); } exit (0); }
C
#include <stdio.h> #include <stdlib.h> #include "Queue.h" // Static queues void SinitQueue (SQueue q){ q->front=0; q->lenght=0; int SisEmptyQ (SQueue q){ if ((q->length)==0) return 1; return 0; } int Senqueue (SQueue q, int x){ if ((q->length)==MAX) return 1; pos=(q->front)+(q->length)%Max; //? n percebi o pq da %Max q->values[pos]=x; q->length++; return 0; } int Sdequeue (SQueue q, int *x) { if (SisEmptyQ(q)) return 1; *x=q->values[q->front]; q->front=(q->front+1)%Max; //? %Max q->length--; return 0; } int Sfront (SQueue q, int *x) { if (SisEmptyQ(q)) return 1; *x=q->values[q->front]; return 0; } void ShowSQueue (SQueue q){ int i, p; printf ("%d Items: ", q->length); for (i=0, p=q->front; i<q->length; i++) { printf ("%d ", q->values[p]); p = (p+1)%Max; } putchar ('\n'); } // Queues with dynamic arrays int dupQueue (DQueue q){ int i, j, r = 0; int *aux = malloc(2*q->size,(sizeof(int))); if(aux == NULL) r = 1; else{ for (i = q->front; j = 0; j < q->size; j++, i = (i+1)%q->size) { aux[j] = q->values[i]; } free(q->values); q->values = aux; q->size = 2*q->size; q->front = 0; } return r; } void DinitQueue (DQueue q) { q->size=1; q->front=0; q->length=0; q->values=malloc(sizeof(int)); //? sizeof(int) } int DisEmptyQ (DQueue s) { if (q->length==0) return 1; return 0; } int Denqueue (DQueue q, int x){ if (q->length==q->size) dupQueue(q); pos=(q->front)+(q->length)%(q->size); q->values[pos]=x; q->length++; return 0; } int Ddequeue (DQueue q, int *x){ if (DisEmptyQ(q)) return 1; *x=q->values[q->front]; q->front0=((q->front) + 1)%q->size; //? %q->size q->length--; return 0; } int Dfront (DQueue q, int *x){ if (DisEmptyQ(q)) return 1; *x=q->values[q->front]; return 0; } void ShowDQueue (DQueue q){ int i, p; printf ("%d Items: ", q->length); for (i=0, p=q->front; i<q->length; i++) { printf ("%d ", q->values[p]); p = (p+1)%q->size; } putchar ('\n'); }
C
//* A program that inputs for a string of characters //* and outputs every character +2 //* (Exmp: 123 -> 345; 567 -> 789; 163 -> 385; abc -> cde etc.) #include <cs50.h> #include <stdio.h> #include <string.h> #include <ctype.h> int main(void) { string s = get_string(""); for (int i = 0, n = strlen(s); i < n; i++) { int j = s[i] + 2; printf("%c ", j); } { printf ("\n"); } }
C
#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ void main(){ int i,j,temp,arr_num[5] = { 23, 90, 9, 25, 16}; for (i=3; i>=0;i--) for (j=4; j>=4-i;j--) { if(arr_num[j] < arr_num[j-1]) { temp=arr_num[j]; arr_num[j]= arr_num[j-1]; arr_num[j-1]= temp; } } printf("\n The sortedd array "); for(i=0;i<5;i++) printf("\n%d", arr_num[i]); getch(); }
C
#include <stdio.h> struct instruct { int data1; int data2; }; struct outstruct { struct instruct a; struct instruct b; }; struct outstruct make_outstruct(int a1, int a2, int b1, int b2) { struct outstruct res; res.a.data1 = a1; res.a.data2 = a2; res.b.data1 = b1; res.b.data2 = b2; return res; } void print_instruct(struct instruct s) { printf("{ %d, %d }", s.data1, s.data2); } void print_outstruct(struct outstruct s) { printf("{ "); print_instruct(s.a); printf(", "); print_instruct(s.b); printf(" }\n"); }
C
#include <stdlib.h> #include <stdio.h> #include <assert.h> #include "util.h" void test_min() { int test_util_numbers[5] = {43, 2, 76, 954, 7}; int min_index = min(test_util_numbers, 5); assert(min_index == 1); } void test_max() { int test_util_numbers[5] = {43, 2, 76, 954, 7}; int max_index = max(test_util_numbers, 5); assert(max_index == 3); } void test_swap() { int test_util_numbers[5] = {43, 2, 76, 954, 7}; swap(test_util_numbers, 0, 1); assert(test_util_numbers[0] == 2); assert(test_util_numbers[1] == 43); } void test_check_arr_equal() { int test_util_numbers[5] = {43, 2, 76, 954, 7}; int compare[5] = {43, 2, 76, 954, 7}; assert(check_arr_equal(test_util_numbers, compare, 5)); } void test_util() { printf("test_util"); test_min(); printf("."); test_max(); printf("."); test_swap(); printf("."); test_check_arr_equal(); printf("."); printf("pass\n"); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <stdbool.h> #include <windows.h> #include "Menu.h" #include "Play.h" #include "Prepare_game.h" #include "Results.h" #include "Settings.h" #include "Wheel.h" #include "Release_memory.h" //stany //TURN_OFF, PREPARE_GAME, SETTINGS, RESULTS, GUESS_LETTER, GAME_MENU, SPIN, GUESS_WORD, BUY, WIN, SAVE,WHEEL, INIT, MENU, STOP, NUMBER //tablica wskaznikow na funkcje state(*tab[NUMBER])(cur_data *data) = {release_players, do_prepare_game, do_settings, do_results, do_guess_letter, do_game_menu, do_spin,do_guess_word, do_buy, do_win, do_save, do_wheel, do_init, do_menu, NULL}; //funkcja obslugujaca stany state run_state(state state_cur,cur_data *data) { return tab[state_cur](data); }; int main(int argc, char ** argv) { if (argc != 2) { printf("Za malo argumentow.\n"); return 0; } else if (strcmp(argv[1],"h")==0) { write_help(); } else { cur_data data; int i; sscanf_s(argv[1], "%d", &i); //przeksztalcenie char* na int data.number_players = i; if (data.number_players >= 1 && data.number_players <= 4) { change_category(&(data.category)); //wybor kategorii data.state_cur = WHEEL; //pierwszy stan while (data.state_cur != STOP) { data.state_cur = run_state(data.state_cur, &data); } printf("Wylaczenie gry."); printf("%d %d ", data.tab_player, data.tab_word); } else { printf("Niepoprawna liczba graczy"); } } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { int i; srand(time(NULL)); for(i=0; i<1000000; i++) { printf("%d\n", rand()); } return 0; }
C
//#include <dirent.h> #include "dirent2.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #define MAX_LEN 65535 int main(void) { DIR *dir; struct dirent *file; int found = 0; char buf[MAX_LEN] = ""; dir = opendir("E:\\Workstation"); //这里改成需要显示文件目录的文件位置 if (dir) { while ((file = readdir(dir)) != NULL) { //printf("%s\n", file->d_name); if ((strcmp(file->d_name, ".") == 0) || (strcmp(file->d_name, "..") == 0)) continue; strcat_s(buf, sizeof(buf), file->d_name); //文件全部存到buf中 strcat_s(buf, sizeof(buf), " "); //这里可以改变输出格式,文件是几个空格相隔还是换行符相隔 } } printf("%s ", buf); //return buf; //返回的是一个包含了所有文件的字符串类型 system("pause"); return 0; }
C
#include "cg.h" #include "pv.h" inline double dis_pp(Point a, Point b) { return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y)); } inline double dis_pl(Point p, Point a, Point b) { Vector v1 = b - a, v2 = p - a; return fabs(cross(v1, v2)) / length(v1); } inline double dis_ps(Point p, Point a, Point b) { Vector v1 = b - a, v2 = p - a, v3 = p - b; if (a == b) return length(p - a); if (sgn(dot(v1, v2)) < 0) return length(v2); if (sgn(dot(v1, v3)) > 0) return length(v3); return fabs(cross(v1, v2)) / length(v1); }
C
/* ** trace_func1.c for corewar in /u/a1/august_e/corewar/vm/execute ** ** Made by eric augustin ** Login <august_e@epita.fr> ** ** Started on Sun Dec 22 15:51:03 2002 eric augustin ** Last update Sun Dec 22 15:51:11 2002 eric augustin */ #include <stdlib.h> #include <unistd.h> #include "trace.h" #include "../common/my_itoa.h" #include "../common/my_strlen.h" void tr0(t_func_arg *arg) { arg = arg; write(STDOUT_FILENO, " \n", 2); } void tr1(t_func_arg *arg) { char *str; str = my_itoa(arg->n); write(STDOUT_FILENO, " ", 1); write(STDOUT_FILENO, str, my_strlen(str)); free(str); write(STDOUT_FILENO, "\n", 1); } void tr2(t_func_arg *arg) { char *str; write(STDOUT_FILENO, " r", 2); str = my_itoa(arg->rx - 1); write(STDOUT_FILENO, str, my_strlen(str)); free(str); write(STDOUT_FILENO, ", r", 3); str = my_itoa(arg->ry - 1); write(STDOUT_FILENO, str, my_strlen(str)); free(str); write(STDOUT_FILENO, "\n", 1); } void tr3(t_func_arg *arg) { char *str; write(STDOUT_FILENO, " r", 2); str = my_itoa(arg->rx - 1); write(STDOUT_FILENO, str, my_strlen(str)); free(str); write(STDOUT_FILENO, ", ", 2); str = my_itoa(arg->n); write(STDOUT_FILENO, str, my_strlen(str)); free(str); write(STDOUT_FILENO, "\n", 1); } void tr4(t_func_arg *arg) { char *str; write(STDOUT_FILENO, " r", 2); str = my_itoa(arg->rx - 1); write(STDOUT_FILENO, str, my_strlen(str)); free(str); write(STDOUT_FILENO, "\n", 1); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <poemic_defs.h> PaStream* openStream() { PaError err; PaDeviceIndex devout,ndev; const PaDeviceInfo *info; PaStreamParameters param; PaStream *handle; int i; err = Pa_Initialize(); ndev = Pa_GetDeviceCount(); printf("List of available output devices:\n"); for(i=0; i<ndev;i++) { info = Pa_GetDeviceInfo((PaDeviceIndex) i); if(info->maxOutputChannels > 0) printf("output device %d: %s\n", i, info->name); } printf("Choose the number of the output device you want to use:"); scanf("%d", &devout); memset(&param, 0, sizeof(PaStreamParameters)); param.device = (PaDeviceIndex) devout; param.channelCount = 1; param.sampleFormat = paFloat32; Pa_OpenStream(&handle, NULL, &param,44100,256, paNoFlag, NULL, NULL); Pa_StartStream(handle); return handle; } void writeStream(PaStream *handle, float frequency, float duration, float amplitude) { int i,j,dur, count = 0; dur = duration*44100/256; float index, index2, control, cr, *buf, *wave; cr = 44100/256; index = 0.f; buf = (float*) malloc(256*sizeof(float)); wave = sine_table(2048, 0); for(j = 0;j < dur;j++){ oscillator(buf, frequency+oscillator(&control,5.f,5.f, wave, &index2,2048, 1,cr),envelope(duration,cr,&count)*amplitude,wave,&index,2048,256,44100); Pa_WriteStream(handle, buf, 256); } free(buf); free(wave); } void closeStream(PaStream *handle) { Pa_StopStream(handle); Pa_CloseStream(handle); Pa_Terminate(); }
C
#include "hash.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> struct node{ struct node *next; name x; number p; } struct hash{ node *a, *b, *c, *d, *e, *f, *g, *h, *i, *j, *k, *l, *m, *n, *o, *p, *q, *r, *s, *t, *u, *v, *w, *x, *y, *z, *current; } hash *newHash() { hash *h = (hash*)malloc(sizeof(hash)); h->a = (node*)malloc(sizeof(node); h->a->next = NULL; h->b = (node*)malloc(sizeof(node); h->b->next = NULL; h->c = (node*)malloc(sizeof(node); h->c->next = NULL; h->d = (node*)malloc(sizeof(node); h->d->next = NULL; h->e = (node*)malloc(sizeof(node); h->e->next = NULL; h->f = (node*)malloc(sizeof(node); h->f->next = NULL; h->g = (node*)malloc(sizeof(node); h->g->next = NULL; h->h = (node*)malloc(sizeof(node); h->h->next = NULL; h->i = (node*)malloc(sizeof(node); h->i->next = NULL; h->j = (node*)malloc(sizeof(node); h->j->next = NULL; h->k = (node*)malloc(sizeof(node); h->k->next = NULL; h->l = (node*)malloc(sizeof(node); h->l->next = NULL; h->m = (node*)malloc(sizeof(node); h->m->next = NULL; h->n = (node*)malloc(sizeof(node); h->n->next = NULL; h->o = (node*)malloc(sizeof(node); h->o->next = NULL; h->p = (node*)malloc(sizeof(node); h->p->next = NULL; h->q = (node*)malloc(sizeof(node); h->q->next = NULL; h->r = (node*)malloc(sizeof(node); h->r->next = NULL; h->s = (node*)malloc(sizeof(node); h->s->next = NULL; h->t = (node*)malloc(sizeof(node); h->t->next = NULL; h->u = (node*)malloc(sizeof(node); h->u->next = NULL; h->v = (node*)malloc(sizeof(node); h->v->next = NULL; h->w = (node*)malloc(sizeof(node); h->w->next = NULL; h->x = (node*)malloc(sizeof(node); h->x->next = NULL; h->y = (node*)malloc(sizeof(node); h->y->next = NULL; h->z = (node*)malloc(sizeof(node); h->z->next = NULL; h->current = h->a; return h; } void freeHash(hash *h){ h->current = h->a; while(h->current->next != NULL){ h->current = h->a->next; free(h->a); h->a = h->current; } h->current = h->a; while(h->current->next != NULL){ h->current = h->a->next; free(h->a); h->a = h->current; } h->current = h->a; while(h->current->next != NULL){ h->current = h->a->next; free(h->a); h->a = h->current; } h->current = h->a; while(h->current->next != NULL){ h->current = h->a->next; free(h->a); h->a = h->current; } h->current = h->a; while(h->current->next != NULL){ h->current = h->a->next; free(h->a); h->a = h->current; } h->current = h->a; while(h->current->next != NULL){ h->current = h->a->next; free(h->a); h->a = h->current; } h->current = h->a; while(h->current->next != NULL){ h->current = h->a->next; free(h->a); h->a = h->current; } h->current = h->a; while(h->current->next != NULL){ h->current = h->a->next; free(h->a); h->a = h->current; } h->current = h->a; while(h->current->next != NULL){ h->current = h->a->next; free(h->a); h->a = h->current; } h->current = h->a; while(h->current->next != NULL){ h->current = h->a->next; free(h->a); h->a = h->current; } h->current = h->a; while(h->current->next != NULL){ h->current = h->a->next; free(h->a); h->a = h->current; } h->current = h->a; while(h->current->next != NULL){ h->current = h->a->next; free(h->a); h->a = h->current; } h->current = h->a; while(h->current->next != NULL){ h->current = h->a->next; free(h->a); h->a = h->current; } h->current = h->a; while(h->current->next != NULL){ h->current = h->a->next; free(h->a); h->a = h->current; } h->current = h->a; while(h->current->next != NULL){ h->current = h->a->next; free(h->a); h->a = h->current; } h->current = h->a; while(h->current->next != NULL){ h->current = h->a->next; free(h->a); h->a = h->current; } h->current = h->a; while(h->current->next != NULL){ h->current = h->a->next; free(h->a); h->a = h->current; } h->current = h->a; while(h->current->next != NULL){ h->current = h->a->next; free(h->a); h->a = h->current; } h->current = h->a; while(h->current->next != NULL){ h->current = h->a->next; free(h->a); h->a = h->current; } h->current = h->a; while(h->current->next != NULL){ h->current = h->a->next; free(h->a); h->a = h->current; } h->current = h->a; while(h->current->next != NULL){ h->current = h->a->next; free(h->a); h->a = h->current; } h->current = h->a; while(h->current->next != NULL){ h->current = h->a->next; free(h->a); h->a = h->current; } h->current = h->a; while(h->current->next != NULL){ h->current = h->a->next; free(h->a); h->a = h->current; } h->current = h->a; while(h->current->next != NULL){ h->current = h->a->next; free(h->a); h->a = h->current; } h->current = h->a; while(h->current->next != NULL){ h->current = h->a->next; free(h->a); h->a = h->current; } h->current = h->a; while(h->current->next != NULL){ h->current = h->a->next; free(h->a); h->a = h->current; } h->current = h->a; while(h->current->next != NULL){ h->current = h->a->next; free(h->a); h->a = h->current; } } void searchHash(hash *h, char *s){ if(s[0] == 'a') h->current = h->a; else if(s[0] == 'b') h->current = h->b; else if(s[0] == 'c') h->current = h->c; else if(s[0] == 'd') h->current = h->d; else if(s[0] == 'e') h->current = h->e; else if(s[0] == 'f') h->current = h->f; else if(s[0] == 'g') h->current = h->g; else if(s[0] == 'h') h->current = h->h; else if(s[0] == 'i') h->current = h->i; else if(s[0] == 'j') h->current = h->j; else if(s[0] == 'k') h->current = h->k; else if(s[0] == 'l') h->current = h->l; else if(s[0] == 'm') h->current = h->m; else if(s[0] == 'n') h->current = h->n; else if(s[0] == 'o') h->current = h->o; else if(s[0] == 'p') h->current = h->p; else if(s[0] == 'q') h->current = h->q; else if(s[0] == 'r') h->current = h->r; else if(s[0] == 's') h->current = h->s; else if(s[0] == 't') h->current = h->t; else if(s[0] == 'u') h->current = h->u; else if(s[0] == 'v') h->current = h->v; else if(s[0] == 'w') h->current = h->w; else if(s[0] == 'x') h->current = h->x; else if(s[0] == 'y') h->current = h->y; else if(s[0] == 'z') h->current = h->z; else printf("The name is incorrect.\n"); } void searchNode(hash *h, char *s, char *t){ if(h->current->next == NULL){ node *new = (node*)malloc(sizeof(node)); h->current->next = new; new->x = s; new->p = t; new->next = NULL; } else{ h->current = h->current->next; while(1){ if(h->current->x[1] } } } void insert(hash *h){ char s[100], t[100]; printf("Write the name: "); fgets(s, sizeof(s), stdin); printf("Write the phone number: "); fgets(t, sizeof(t), stdin); s[strlen(s) - 1] = '\0'; t[strlen(t) - 1] = '\0'; h->current = h->a; searchHash(h, s); searchNode(h, s, t); } void main(){ int c; hash *h = newHash(); while(1){ printf("This is telephone directory. What do you want to do?\n"); printf("1. Insert\n2. Search(By name)\n3. Delete\n4. Quit\n: "); scanf("%d", &c); if(c == 1) insert(h); else if(c == 2) search(h); else if(c == 3) delete(h); else if(c == 4) break; else printf("Please chosse 1 or 2 or 3 or 4.\n"); } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { char a[101], b[101],hantei; int kup = 0,aketa = 0,bketa = 0,kdiff,kaisu,i,cketa,sum, c[101],khantei = 0,daisho; fgets(a,101,stdin); //引数の間違いを訂正 fgets(b,101,stdin); while(1) { hantei = a[aketa]; if(hantei == '\n') // = を == break; aketa++; } while(1) { hantei = b[bketa]; if(hantei == '\n') // = を == break; bketa++; } if(aketa < bketa) { kaisu = aketa; daisho = 0; kdiff = bketa - aketa; cketa = bketa; } else if(aketa > bketa) { kaisu = bketa; daisho = 1; kdiff = aketa - bketa; cketa = aketa; } else { kaisu = aketa; daisho = 2; kdiff = 0; if((a[0] - '0') + (b[0] - '0') > 9) { kdiff ++; cketa = aketa + 1; } else cketa = aketa; } for(;kaisu != 0;kaisu--) // kdiff を kaisu { sum = (a[aketa - 1] - '0') + (b[bketa - 1] - '0'); if(sum > 9) { kup = 1; sum = sum - 10; } else kup = 0; c[kaisu + kdiff - 1] = sum + khantei; if(kup == 1) // = を == khantei = 1; else khantei = 0; aketa--; bketa--; } if(daisho == 0) { for(i = 0; i < kdiff; i++) { c[i] = b[i] - '0'; } if(khantei == 1) { c[kdiff - 1] = (b[kdiff - 1] - '0') + 1; } } else if(daisho == 1) { for(i = 0; i < kdiff; i++) { c[i] = a[i] - '0'; } if(khantei == 1) { c[kdiff - 1] = (a[kdiff - 1] - '0') + 1; } } else if(daisho == 2 && khantei == 1) { c[0] = khantei; } for(i = 0; i < cketa; i++) { printf("%d", c[i]); } printf("\n"); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* expansion.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: csinglet <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/12/14 23:16:30 by csinglet #+# #+# */ /* Updated: 2018/12/14 23:16:31 by csinglet ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" static void append_env_var(char **dest, char *addition) { if (*dest == NULL) *dest = ft_strdup(addition); else *dest = ft_strjoin_free_s1(*dest, addition); free(addition); addition = NULL; } static int ft_copy_until_env_var(char **dest, char *src) { int i; int quote_flag; i = 0; quote_flag = 0; while (src[i] != '\0') { if (src[i] == '"') { while (src[i] == '"') i++; quote_flag ^= (1 << 0); } if (quote_flag == 0 && (src[i] == '$' || src[i] == '~')) break ; i++; } *dest = ft_strndup(src, i); return (i); } static int get_var_name(char **dest, char *src) { int i; i = 0; if (*src == '~') { *dest = ft_strdup("~"); i = 1; } else if (*src == '$') { while (src[i] != ' ' && src[i] != '\0') i++; *dest = ft_strndup(src, i); } return (i); } static char *get_env_value(t_mini *m, char *name) { int i; char *value; char *test; i = 2; value = NULL; if (*name == '~' && (test = env_search(m->env, "HOME")) != NULL) value = ft_strdup(test); else if (name[1] == '-' && (test = env_search(m->env, "OLDPWD")) != NULL) value = ft_strdup(test); else if ((test = env_search(m->env, name + 1)) != NULL) value = ft_strdup(env_search(m->env, name + 1)); else value = ft_strdup(name); free(name); name = NULL; return (value); } char *expand_env_vars(t_mini *mini, char *src) { int bytes_copied; char *expanded; char *env_var_name; char *env_var_value; char *cut; bytes_copied = 0; expanded = NULL; env_var_name = NULL; env_var_value = NULL; cut = NULL; while (src[bytes_copied] != '\0') { bytes_copied += ft_copy_until_env_var(&cut, src + bytes_copied); append_env_var(&expanded, cut); if (src[bytes_copied] != '\0') { bytes_copied += get_var_name(&env_var_name, src + bytes_copied); env_var_value = get_env_value(mini, env_var_name); append_env_var(&expanded, env_var_value); } } return (expanded); }
C
#include<stdio.h> #include<string.h> char *str_tok(char* str,const char* token); int main(){ char str[] = "s s s s"; char *current = strtok(str," "); while(current != NULL){ printf("%s\n",current); str_tok(NULL," "); return 0;} char *str_tok(char* str,const char* token){ char *tmp; int size = strlen(str); static int start = 0; // 토큰이 잘리는 시작점 인덱스 static int last; //현재 스트링을 돌고있는 지점 인덱스 if(str != NULL){ tmp = str;} //첫번째 단계 for(int i=start;i<size;i++){ while(tmp != '\0'){ if(tmp[i] == token){ tmp[i] = '\0'; start = i; start++; return &tmp[i]} start++; }
C
#include<stdio.h> int main(){ double a[100],n; int i; scanf("%lf",&n); a[0]=n; for(i=0;i<100;i++){ a[i+1]=a[i]/2.0; printf("N[%d] = %.4lf\n",i,a[i]); } return 0; }
C
/* Tests the SMV memory domain system. Adapted from the original * SMV userland testcases. * *@author Marcela S. Melara */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <smv_lib.h> #include <memdom_lib.h> #define MAIN_THREAD 0 static int test_memdom_create() { printf("-- Test: main thread memdom create... "); int memdom_id = -1; // main thread create memdoms memdom_id = memdom_create(); if (memdom_id == -1) { printf("memdom_create returned %d\n", memdom_id); return -1; } if (memdom_kill(memdom_id)) { printf("memdom_kill returned %d\n", memdom_id); return -1; } printf("success\n"); return 0; } static int test_memdom_create_fail() { printf("-- Test: main thread memdom create fail... "); int memdom_id = -1; int i = 0; int j = 0; int err = 0; // main thread create memdoms for (i = 0; i < MAX_MEMDOM; i++) { memdom_id = memdom_create(); if (memdom_id == -1) { printf("memdom_create returned %d\n", memdom_id); err = -1; goto out; } } memdom_id = memdom_create(); if (memdom_id != -1) { printf("Expected %d, got %d\n", -1, memdom_id); err = -1; } out: for (j = 1; j < i; j++) { if (memdom_kill(j)) { printf("memdom_kill returned %d\n", j); err = -1; } } if (!err) printf("success\n"); return err; } static int test_memdom_alloc() { printf("-- Test: main thread memdom alloc... "); int memdom_id = -1; char *str; int err = 0; memdom_id = memdom_create(); if (memdom_id == -1) { printf("memdom_create returned %d\n", memdom_id); return -1; } // need to add this domain to the main thread smv_join_domain(memdom_id, MAIN_THREAD); memdom_priv_add(memdom_id, MAIN_THREAD, MEMDOM_ALLOCATE | MEMDOM_READ | MEMDOM_WRITE); str = memdom_alloc(memdom_id, 6*sizeof(char)); if (str == NULL) { err = -1; goto out; } sprintf(str, "hello"); printf("allocated: %s\n", str); memdom_free(str); out: if (memdom_kill(memdom_id)) { printf("memdom_kill returned %d\n", memdom_id); err = -1; } if (!err) printf("success\n"); return err; } static int test_memdom_queries() { printf("-- Test: main thread memdom queries... "); int memdom_id = -1; int str_memdom_id = -1; char *str; int err = 0; memdom_id = memdom_main_id(); if (memdom_id != 0) { printf("Expected %d, got %d\n", 0, memdom_id); return -1; } memdom_id = memdom_create(); if (memdom_id == -1) { printf("memdom_create returned %d\n", memdom_id); return -1; } // need to add this domain to the main thread smv_join_domain(memdom_id, MAIN_THREAD); memdom_priv_add(memdom_id, MAIN_THREAD, MEMDOM_ALLOCATE | MEMDOM_READ | MEMDOM_WRITE); str = memdom_alloc(memdom_id, 6*sizeof(char)); if (str == NULL) { err = -1; str_memdom_id = memdom_id; goto out; } sprintf(str, "hello"); str_memdom_id = memdom_query_id(str); if (str_memdom_id != memdom_id) { printf("Expected memdom_id %d, got %d\n", memdom_id, str_memdom_id); memdom_free(str); err = -1; goto out; } memdom_free(str); memdom_id = memdom_private_id(); if (memdom_id != 0) { printf("Expected %d, got %d\n", 0, memdom_id); err = -1; } out: if (memdom_kill(str_memdom_id)) { printf("memdom_kill returned %d\n", str_memdom_id); err = -1; } if (!err) printf("success\n"); return err; } int main(){ smv_main_init(0); int success = 0; int total_tests = 4; // single memdom_create --> expect success if (!test_memdom_create()) { success++; } // create all possible memdoms + one out of bounds --> expect fail if (!test_memdom_create_fail()) { success++; } // query the memdom id for different parts of the system --> expect success if (!test_memdom_queries()) { success++; } // allocate a buffer in main thread's memory domain --> expect success if (!test_memdom_alloc()) { success++; } printf("%d / %d memdom operations tests passed\n", success, total_tests); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_ls_option_t.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sdurr <sdurr@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/12/16 08:43:54 by sdurr #+# #+# */ /* Updated: 2015/03/13 17:50:48 by sdurr ### ########.fr */ /* */ /* ************************************************************************** */ #include <sys/stat.h> #include "ft_ls.h" #include "libft.h" #include <stdlib.h> #include <stdio.h> static t_list *end_link(t_list *s, t_list *t) { t_list *begin; begin = s; while (s->next != NULL) { if (ft_strcmp(s->s, t->s) > 0) s = exchange_link(s, t); s = s->next; } return (begin); } t_list *tri_ascii(t_list *s) { t_list *t; t_list *begin; begin = s; t = s; t = t->next; while (s->next != NULL) { if (s->n == 2 && (s = s->next)) t = t->next; while (s->n != 2 && s->next != NULL) { while (t->next != NULL && t->n != 2) { if (ft_strcmp(s->s, t->s) > 0) s = exchange_link(s, t); t = t->next; } t = s; t = t->next; s = s->next; } } s = end_link(begin, t); return (begin); }
C
#include "lists.h" /** * add_node_end - this function add a node to the tail of the linked list * @head: this is the parameter pointing to the head of the linked list * @str: this is the text to set in the node * * Return: returns a copy of the node; */ list_t *add_node_end(list_t **head, const char *str) { list_t *copy; list_t *last = *head; size_t cont = 0; copy = malloc(sizeof(list_t)); copy->str = strdup(str); while (str[cont]) cont++; copy->len = cont; copy->next = NULL; if (*head == NULL) { *head = copy; return (copy); } while (last->next != NULL) { last = last->next; } last->next = copy; return (copy); }
C
/* ** EPITECH PROJECT, 2021 ** my_env ** File description: ** my_env */ #include "my.h" #include "42sh.h" #include <stddef.h> #include <stdlib.h> int check_env_error(char **av, int i) { if (av[1] == NULL) return (0); for (i = 0; av[i] != NULL; i++); if (i > 3) { my_puterror("setenv: Too many arguments.\n"); return (1); } if (!(av[1][0] >= 'a' && av[1][0] <= 'z') && !(av[1][0] >= 'A' && av[1][0] <= 'Z')) { my_puterror("setenv: Variable name must begin with a letter.\n"); return (1); } for (i = 1; av[1][i] != '\0'; i++) if (!is_alpha_num(av[1][i])) { my_puterror("setenv: Variable name "); my_puterror("must contain alphanumeric characters.\n"); return (1); } return (0); } static void put_last_env_var(char **env, char *new, int i) { for (i = 0; env[i] != NULL; i++); env[i] = new; env[i + 1] = NULL; ret = 0; } static int print_env(char **av, char **env) { if (av[1] == NULL) { my_env(env); ret = 0; return -1; } return 0; } char **my_setenv(char **env, char **av) { int i; char *new; if (check_env_error(av, 0)) { ret = -1; return (env); } if (print_env(av, env) == -1) return (env); new = my_strcat_3(av[1], "=", av[2]); i = check_env(env, av[1]); if (i != -1) { free(env[i]); env[i] = new; ret = 0; return (env); } put_last_env_var(env, new, i); return (env); } char **my_unsetenv(char **env, char **av) { int i; int j; for (i = 1; av[i] != NULL; i++) { j = check_env(env, av[i]); if (j != -1) { free(env[j]); for (j = j + 1; env[j] != NULL; j++) env[j - 1] = env[j]; env[j - 1] = NULL; } } ret = 0; return (env); }
C
#include<stdio.h> #include<stdlib.h> #include <stdio.h> #define n 4096 // block size in bytes int prevBlock; int flag; int file_size; //-------------------------------------------------------------disk storage level implementation-------------------------------------------------------- int writeBlock(int blockNum,char *buff,int offset,int length) { int pos = (blockNum-1)*4096 + offset; int count; FILE *fs = fopen("./storage/disk.vs","r+"); fseek(fs,pos,SEEK_SET); count = 0; while(count != length) { putc(buff[count],fs); count ++ ; } fclose(fs); return 1; } int readBlock(int blockNum,int offset,int length) { int pos = (blockNum-1)*4096 + offset; char c; int count; FILE *fs = fopen("./storage/disk.vs","r+"); fseek(fs,pos,SEEK_SET); count = 0; while(count != length) { c = getc(fs); printf("%c",c); count ++ ; } fclose(fs); return 1; } int readNextBlockNo(int blockNum) { int pos = (blockNum-1)*4096; FILE *fs = fopen("./storage/disk.vs","r+"); int next; fseek(fs,pos,SEEK_SET); fscanf(fs,"%d",&next); fclose(fs); return next; } //--------------------------------------------------------------allocation Level Implementation------------------------------------------------------- int writeToFAT(char *path, int blockNo, int size) { FILE *p= fopen("./storage/allocation.txt", "a"); fprintf(p,"%s %d %d\n", path, blockNo, size); fclose(p); return 1; } int search_free() { int i=0, x=0; FILE *p; char c; p=fopen("./storage/free.txt","rb+"); while((c=fgetc(p)) != EOF) { x++; if(c=='1') //1=free 0=used { fseek(p,i,SEEK_SET); fputc('0',p); break; } i=ftell(p); } fclose(p); return x; } void initialise_free() { FILE *q = fopen("./storage/free.txt","w"); int i=1; while(i!=n) { fprintf(q,"1"); i++; } fclose(q); } int storeFile(FILE *fs) { int count,i; char buff[4090],t[6]; char c; count = 0; while(count != 4090) { c = getc(fs); if(c == EOF) break; buff[count] = c; count ++ ; } i=search_free(); if(flag == 0) flag = i; sprintf(t,"%05d ",0); writeBlock(i,t,0,6); writeBlock(i,buff,6,4090); if(prevBlock != 0) { sprintf(t,"%05d ",i); writeBlock(prevBlock,t,0,6); } prevBlock = i; file_size = file_size + count ; if(feof(fs)) return -1; return count; } //--------------------------------------------------------------------User-level implementation---------------------------------------------------------------- int checkFileExist(char *filename) { FILE *p= fopen("./storage/allocation.txt", "r"); char temp[50]; int t; while(!feof(p)) { fscanf(p,"%s",temp); fscanf(p,"%d",&t); fscanf(p,"%d",&t); if(strcmp(temp,filename)==0) { printf("\nFile with the similar name exists...!!! \n\n"); fclose(p); return 0; } } fclose(p); return 1; } int readFileByName(char *filename) { FILE *p= fopen("./storage/allocation.txt", "r"); char temp[50]; int inode,size,found=0; while(!feof(p)) { fscanf(p,"%s",temp); fscanf(p,"%d",&inode); fscanf(p,"%d",&size); if(strcmp(temp,filename)==0) { readFileByInode(inode, size); found=1; break; } } if(found==0) printf("\nFILE NOT FOUND...!!!\n"); fclose(p); return 1; } int readFileByInode(int inode,int size) { int tmp = inode; int t = size; int length; while(1) { if(t > 4090) length = 4090; else length = t; readBlock(tmp,6,length); tmp=readNextBlockNo(tmp); if(tmp==0) break; t = t-4090; } } int deleteFileByName(char *filename) { FILE *p= fopen("./storage/allocation.txt", "r"); char temp[50]; int inode,size,found=0; while(!feof(p)) { fscanf(p,"%s",temp); fscanf(p,"%d",&inode); fscanf(p,"%d",&size); if(strcmp(temp,filename)==0) { deleteFileByInode(inode,filename); found=1; break; } } if(found==0) printf("\nFILE NOT FOUND...!!!\n"); fclose(p); return 1; } int deleteFileByInode(int inode,char *filename) { int k=inode; int i, x; FILE *p; char c; while(k != 0) { p=fopen("./storage/free.txt","rb+"); i=0; x=0; while((c=fgetc(p)) != EOF) { x++; if(x==k) { fseek(p,i,SEEK_SET); fputc('1',p); break; } i=ftell(p); } fclose(p); k=readNextBlockNo(k); } } int checkDiskSpace() { int free=0, used=0,total=0; FILE *p; char c; p=fopen("./storage/free.txt","rb+"); while((c=fgetc(p)) != EOF) { if(c=='1') free++; else used++; } free=free*4096; used=used*4096; total=free+used; printf("\nDisk Size: %d bytes \nUsed Space: %d bytes\nFree Space: %d bytes\n ",free,used,total); fclose(p); return 1; } //----------------------------------------------------------------------------Main------------------------------------------------------------------------------------- int main() { int choice,inode; char path[50],name[50],file[50]; /*initialise_free(); */ //for initialising free block list printf("\n"); do { printf("Operations menu:\n"); printf("1. Store a file\n"); printf("2. Delete a file\n"); printf("3. Read a file\n"); printf("4. detail\n"); printf("5. Exit.\n"); printf("Enter your choice..: "); scanf("%d",&choice); switch(choice) { case 1 : prevBlock = 0; flag = 0; file_size = 0; printf("\nEnter the source file path: "); scanf("%s",path); printf("\nEnter name of file: "); scanf("%s",name); if(checkFileExist(name)) { FILE *fs = fopen(path,"r"); while(storeFile(fs) != -1) ; writeToFAT(name,flag,file_size); fclose(fs); printf("\nsuccessfully written in disk...\n\n"); } break; case 2 : printf("\nFile name: "); scanf("%s", file); deleteFileByName(file); printf("\n"); break; case 3 : printf("\nFile name: "); scanf("%s", file); readFileByName(file); break; case 4 : checkDiskSpace(); printf("\n"); break; default : printf("Please enter a valid choice !!!\n\n"); break; } } while (choice != 5); }
C
/* * Project: Gauss-Jordan elimination method by columns (KJI-form) * Implemented with MPI * File: main.c * Author: Chris Aslanoglou */ #include <stdio.h> #include <stdlib.h> #include <mpi.h> #include <time.h> #include <unistd.h> #include "gauss_jordan.h" gauss_jordan gj; int main(int argc, char** argv) { srand(time(NULL)); if (argc != 3) { fprintf(stderr, "Usage: %s [dimension (not augmented)] [use k-group distribution]\n", argv[0]); exit(EXIT_SUCCESS); } int dimension = atoi(argv[1]); if (dimension <= 0 || (dimension % 2 != 0)) { fprintf(stderr, "[dimension] must be a positive even number\n"); exit(EXIT_SUCCESS); } int groupsDistribution = atoi(argv[2]); if (groupsDistribution < 0 || groupsDistribution > 1) { fprintf(stderr, "[use k-group distribution must be either 0 or 1]\n"); exit(EXIT_SUCCESS); } // Create augmented random array float** augmented_m = create_augmented_matrix(dimension); int augmented_n = dimension + 1; /* Initial test case int augmented_n = 5; float **augmented_m = NULL; augmented_m = malloc((augmented_n - 1) * sizeof(float*)); int i; for (i = 0; i < augmented_n - 1; i++) { augmented_m[i] = malloc(augmented_n * sizeof(float)); } augmented_m[0][0] = 0; augmented_m[0][1] = 2; augmented_m[0][2] = 0; augmented_m[0][3] = 1; augmented_m[0][4] = 0; augmented_m[1][0] = 2; augmented_m[1][1] = 2; augmented_m[1][2] = 3; augmented_m[1][3] = 2; augmented_m[1][4] = -2; augmented_m[2][0] = 4; augmented_m[2][1] = -3; augmented_m[2][2] = 0; augmented_m[2][3] = 1; augmented_m[2][4] = -7; augmented_m[3][0] = 6; augmented_m[3][1] = 1; augmented_m[3][2] = -6; augmented_m[3][3] = -5; augmented_m[3][4] = 6; * */ column_t* my_cols = init(augmented_n, augmented_m, groupsDistribution); MPI_Barrier(MPI_COMM_WORLD); gj_kgi_main_loop(my_cols); if (gj.my_rank == 0) { // Master process has b-vector // printf("Master printing solution\n"); // print_column(my_cols[gj.group_number]); } // All processes must reach to the barrier for the de-allocation process and // the termination of the MPI framework, or else, master process doesn't get // finalize properly MPI_Barrier(MPI_COMM_WORLD); destroy(&my_cols); MPI_Finalize(); return (EXIT_SUCCESS); }
C
#include <stdio.h> int main() { int NUM,arr[100],t,i,j,brr[100],prr[100],temp=0,count=0,swap; scanf("%d %d",&NUM,&t); for(i=0;i<NUM;i++) { scanf("%d",&arr[i]); } for(i=0;i<t;i++) { scanf("%d",&brr[i]); } for(i=0;i<NUM;i++) { count=0; for(j=0;j<t;j++) { if(brr[i]!='$' && brr[j]!='$') { if(arr[i]==brr[j]) { count++; brr[j]='$'; } } } if(count!=0) { prr[temp]=arr[i]; temp++; } } for(i=0;i<temp;i++) { for(j=i+1;j<temp;j++) { if(prr[i]!='$' && prr[j]!='$') { if(prr[i]>prr[j]) { swap=prr[i]; prr[i]=prr[j]; prr[j]=swap; } } } } for(i=0;i<temp;i++) { printf("%d ",prr[i]); } return 0; }
C
#include <stdio.h> void board(int, int); int checkWin(); char square[3][3] = {{'\40', '\40', '\40'}, {'\40', '\40', '\40'}, {'\40', '\40', '\40'}}; // 40 is octal for 32, which is the ASCII value for blank spaces int main(){ int turn = 1, row, col; int winCheck = checkWin(); while(winCheck == 0){ board(turn, winCheck); do{ printf("Row: "); scanf("%i", &row); }while(row < 1 || row > 3); do{ printf("Column: "); scanf("%i", &col); }while(col < 1 || col > 3); if(square[row - 1][col - 1] == '\40'){ if(turn % 2 != 0) square[row - 1][col - 1] = 'X'; else square[row - 1][col - 1] = 'O'; turn++; winCheck = checkWin(); }else{ printf("(%i, %i) occupied!\n", row, col); } } board(turn, winCheck); return 0; } void board(int turn, int winCheck){ printf("\n"); printf(" %c | %c | %c \n", square[0][0], square[0][1], square[0][2]); printf("---+---+---\n"); printf(" %c | %c | %c \n", square[1][0], square[1][1], square[1][2]); printf("---+---+---\n"); printf(" %c | %c | %c \n", square[2][0], square[2][1], square[2][2]); if(winCheck == 0){ if(turn % 2 != 0) printf("X's turn\n\n"); else printf("O's turn\n\n"); }else if(winCheck == 1){ if(turn % 2 == 0) printf("X wins!\n\n"); else printf("O wins!\n\n"); }else{ printf("Draw\n\n"); } } int checkWin(){ if((square[0][0] == 'X' && square[0][1] == 'X' && square[0][2] == 'X') || (square[0][0] == 'O' && square[0][1] == 'O' && square[0][2] == 'O')) return 1; else if((square[1][0] == 'X' && square[1][1] == 'X' && square[1][2] == 'X') || (square[1][0] == 'O' && square[1][1] == 'O' && square[1][2] == 'O')) return 1; else if((square[2][0] == 'X' && square[2][1] == 'X' && square[2][2] == 'X') || (square[2][0] == 'O' && square[2][1] == 'O' && square[2][2] == 'O')) return 1; else if((square[0][0] == 'X' && square[1][0] == 'X' && square[2][0] == 'X') || (square[0][0] == 'O' && square[1][0] == 'O' && square[2][0] == 'O')) return 1; else if((square[0][1] == 'X' && square[1][1] == 'X' && square[2][1] == 'X') || (square[0][1] == 'O' && square[1][1] == 'O' && square[2][1] == 'O')) return 1; else if((square[0][2] == 'X' && square[1][2] == 'X' && square[2][2] == 'X') || (square[0][2] == 'O' && square[1][2] == 'O' && square[2][2] == 'O')) return 1; else if((square[0][0] == 'X' && square[1][1] == 'X' && square[2][2] == 'X') || (square[0][0] == 'O' && square[1][1] == 'O' && square[2][2] == 'O')) return 1; else if((square[0][2] == 'X' && square[1][1] == 'X' && square[2][0] == 'X') || (square[0][2] == 'O' && square[1][1] == 'O' && square[2][0] == 'O')) return 1; else if(square[0][0] != '\40' && square[0][1] != '\40' && square[0][2] != '\40' && square[1][0] != '\40' && square[1][1] != '\40' && square[1][2] != '\40' && square[2][0] != '\40' && square[2][1] != '\40' && square[2][2] != '\40') return 2; else return 0; }
C
/** * Keil project template * * Before you start, select your target, on the right of the "Load" button * * @author Tilen Majerle * @email tilen@majerle.eu * @website http://stm32f4-discovery.com * @ide Keil uVision 5 * @conf PLL parameters are set in "Options for Target" -> "C/C++" -> "Defines" * @packs STM32F4xx Keil packs version 2.2.0 or greater required * @stdperiph STM32F4xx Standard peripheral drivers version 1.4.0 or greater required */ /* Include core modules */ #include "stm32f4xx.h" #include <string.h> #include "SST25VF016B.h" #include "GLCD.h" #include "fmc_sdram.h" #include "picture.c" /* Private functions ---------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ #define PICTURE_ADDR (0) /* PICTURE address in SPI FLASH */ uint8_t buffer[960]; void ILI9488_DrawBMP(uint16_t _usX, uint16_t _usY, uint16_t _usWidth, uint16_t _usHeight) { uint32_t index_x = 0; uint32_t index_y = 0; uint16_t temp; for (index_y = 0; index_y < _usHeight; index_y++) { df_read( &buffer[0] , sizeof(buffer) ); for (index_x = 0; index_x < _usWidth; index_x++) { temp = *( index_x*2+1+buffer ); temp = ( (temp<<8) | *( index_x*2+0+buffer ) ); LCD_SetPixel_16bpp(index_x, index_y, temp); } } } /******************************************************************************* * Function Name : main * Description : Main Programme * Input : None * Output : None * Return : None * Attention : None *******************************************************************************/ int main(void) { uint16_t count; FMC_SDRAM_Init(); LCD_Init(); SPI_FLASH_Init(); SPI_FLASH_Test(); SSTF016B_Erase( PICTURE_ADDR/SEC_SIZE , ( PICTURE_ADDR+sizeof(picture) )/SEC_SIZE +1 ); /* ??????? */ df_write_open( PICTURE_ADDR ); /* ??????? */ LCD_Clear(LCD_COLOR_RED); GUI_Text( ( LCD_X_SIZE - strlen("Writing To SPI Flash")*8 ) / 2, LCD_Y_SIZE / 2 - 8, "Writing To SPI Flash", LCD_COLOR_WHITE, LCD_COLOR_BLUE); for(count=0;count<sizeof(picture)/255;count++) { df_write( (uint8_t*)&picture[count*255],255); df_write_close(); } df_write( (uint8_t*)&picture[count*255],sizeof(picture)%255); df_write_close(); df_read_open( PICTURE_ADDR ); /* ??????? */ ILI9488_DrawBMP(0,0,480,272); while (1) { } } /************************ (C) COPYRIGHT HAOYU Electronics *****END OF FILE****/
C
#include "timer3.h" #include <stdint.h> #include <avr/io.h> #include <avr/interrupt.h> void (*timer3_overflow_callback)(void); void (*timer3_compa_callback)(void); ISR(TIMER3_OVF_vect) { if (timer3_overflow_callback) timer3_overflow_callback(); } ISR(TIMER3_COMPA_vect) { if (timer3_compa_callback) timer3_compa_callback(); } void timer3_init(void) { TCCR3B = _BV(CS32); // CS32: prescaler = 1/256, 1.0486 ms cycle, 16uS tic. } void timer3_set_overflow_callback(void (*callback)(void)) { timer3_overflow_callback = callback; if (timer3_overflow_callback) TIMSK3 |= _BV(TOIE3); else TIMSK3 &= ~(_BV(TOIE3)); } void timer3_set_compa_callback(void (*callback)(void)) { timer3_compa_callback = callback; if (timer3_compa_callback) TIMSK3 |= _BV(OCIE3A); else TIMSK3 &= ~(_BV(OCIE3A)); }
C
#include <gtk/gtk.h> #include "cairo_util.h" // Draw a rounded rectangle starting at x,y with size Sx, Sy. // The round factor gives the radius of the rounded rectangle by radius = min(Sx, Sy)*RoundFactor void CairoRoundedRectangle(cairo_t *cr, double x, double y, double Sx, double Sy, double RoundFactor, int Filled) { double Radius = Sx < Sy ? Sx : Sy; Radius *= RoundFactor; cairo_new_sub_path (cr); cairo_arc (cr, x + Sx - Radius, y + Radius, Radius, -G_PI/2, 0.0); cairo_arc (cr, x + Sx - Radius, y + Sy - Radius, Radius, 0.0, G_PI/2); cairo_arc (cr, x + Radius, y + Sy - Radius, Radius, G_PI/2, G_PI); cairo_arc (cr, x + Radius, y + Radius, Radius, G_PI, 3*G_PI/2); cairo_close_path (cr); if ( Filled ) cairo_fill(cr); else cairo_stroke(cr); } // Affiche une bulle : Rectangle arrondi avec un "bec" // La taille du rectangle de base est Sx, Sy, l'arrondi fait Sy*0.45, le bec est au centre de la droite du bas, les angles sont de 45° // Si PositionBec = 0 : en dessous void CairoBulle(cairo_t *cr, double x, double y, double Sx, double Sy, double RoundFactor, double SizeBec, int Filled, int PositionBec) { double Radius = Sx < Sy ? Sx : Sy; Radius *= RoundFactor; cairo_new_sub_path (cr); switch ( PositionBec ) { case BEC_DESSOUS: // Commence en haut à gauche cairo_move_to(cr, x+Radius, y); // Haut gauche cairo_line_to(cr, x+Sx-Radius, y); // Ligne du haut cairo_arc (cr, x + Sx - Radius, y + Radius, Radius, -G_PI/2, 0.0); cairo_line_to(cr, x+Sx, y + Sy - Radius); cairo_arc (cr, x + Sx - Radius, y + Sy - Radius, Radius, 0.0, G_PI/2); // Droite avec Bec dessous cairo_line_to(cr, x+Sx/2.0+SizeBec, y+Sy); cairo_line_to(cr, x+Sx/2.0, y+Sy+SizeBec); cairo_line_to(cr, x+Sx/2.0-SizeBec, y+Sy); cairo_line_to(cr, x+Radius, y+Sy); cairo_arc (cr, x + Radius, y + Sy - Radius, Radius, G_PI/2, G_PI); cairo_line_to(cr, x, y+Radius); cairo_arc (cr, x + Radius, y + Radius, Radius, G_PI, 3*G_PI/2); break; case BEC_DESSUS: // Commence en haut à gauche, droite jusqu'au bec cairo_move_to(cr, x+Radius, y); // Haut gauche cairo_line_to(cr, x+Sx/2.0-SizeBec, y); cairo_line_to(cr, x+Sx/2.0, y-SizeBec); cairo_line_to(cr, x+Sx/2.0+SizeBec, y); cairo_line_to(cr, x+Sx-Radius, y); // Fin de la ligne du dessus cairo_arc (cr, x + Sx - Radius, y + Radius, Radius, -G_PI/2, 0.0); cairo_line_to(cr, x+Sx, y + Sy - Radius); cairo_arc (cr, x + Sx - Radius, y + Sy - Radius, Radius, 0.0, G_PI/2); cairo_line_to(cr, x+Radius, y+Sy); cairo_arc (cr, x + Radius, y + Sy - Radius, Radius, G_PI/2, G_PI); cairo_line_to(cr, x, y+Radius); cairo_arc (cr, x + Radius, y + Radius, Radius, G_PI, 3*G_PI/2); break; case BEC_DROITE: // Commence en haut à gauche cairo_move_to(cr, x+Radius, y); // Haut gauche cairo_line_to(cr, x+Sx-Radius, y); // Ligne du haut complète cairo_arc (cr, x + Sx - Radius, y + Radius, Radius, -G_PI/2, 0.0); // Coté droit avec bec cairo_line_to(cr, x+Sx, y+Sy/2.0-SizeBec); cairo_line_to(cr, x+Sx+SizeBec, y+Sy/2); cairo_line_to(cr, x+Sx, y+Sy/2.0+SizeBec); cairo_line_to(cr, x+Sx, y + Sy - Radius); // Arrondi bas droite cairo_arc (cr, x + Sx - Radius, y + Sy - Radius, Radius, 0.0, G_PI/2); cairo_line_to(cr, x+Radius, y+Sy); cairo_arc (cr, x + Radius, y + Sy - Radius, Radius, G_PI/2, G_PI); cairo_line_to(cr, x, y+Radius); cairo_arc (cr, x + Radius, y + Radius, Radius, G_PI, 3*G_PI/2); break; case BEC_GAUCHE: // Commence en haut à gauche cairo_move_to(cr, x+Radius, y); // Haut gauche cairo_line_to(cr, x+Sx-Radius, y); // Ligne du haut complète cairo_arc (cr, x + Sx - Radius, y + Radius, Radius, -G_PI/2, 0.0); // Coté droit cairo_line_to(cr, x+Sx, y + Sy - Radius); // Arrondi bas droite cairo_arc (cr, x + Sx - Radius, y + Sy - Radius, Radius, 0.0, G_PI/2); cairo_line_to(cr, x+Radius, y+Sy); cairo_arc (cr, x + Radius, y + Sy - Radius, Radius, G_PI/2, G_PI); // Coté gauche avec bec cairo_line_to(cr, x, y+Sy/2.0+SizeBec); cairo_line_to(cr, x-SizeBec, y+Sy/2); cairo_line_to(cr, x, y+Sy/2.0-SizeBec); cairo_line_to(cr, x, y+Radius); cairo_arc (cr, x + Radius, y + Radius, Radius, G_PI, 3*G_PI/2); break; } cairo_close_path (cr); if ( Filled ) cairo_fill(cr); else cairo_stroke(cr); }
C
#include <stdio.h> #include <stdlib.h> #include <c_interface.h> /* * We'd like to be able to override the node's function table to * point to our own functions. * * First we need to add a few functions to the node function table. * - start * - longpoll * - shortpoll * - query */ /* * Optional. * This method is run once the Node is successfully added to the ISY * and we get a return result from Polyglot. Only happens once. */ static void start(struct node *self) { loggerf(DEBUG, "%s: get ST=%s\n", self->name, self->ops.getDriver(self, "ST")); self->ops.setDriver(self, "ST", "1", 1, 1, 2); loggerf(DEBUG, "%s: get ST=%s\n", self->name, self->ops.getDriver(self, "ST")); self->ops.setDriver(self, "ST", "0", 1, 1, 2); loggerf(DEBUG, "%s: get ST=%s\n", self->name, self->ops.getDriver(self, "ST")); self->ops.setDriver(self, "ST", "1", 1, 1, 2); loggerf(DEBUG, "%s: get ST=%s\n", self->name, self->ops.getDriver(self, "ST")); self->ops.setDriver(self, "ST", "0", 1, 1, 2); loggerf(DEBUG, "%s: get ST=%s\n", self->name, self->ops.getDriver(self, "ST")); } /* */ static void short_poll(struct node *self) { logger(DEBUG, "shortPoll\n"); if (atoi(self->ops.getDriver(self, "ST")) == 1) self->ops.setDriver(self, "ST", "0", 1, 1, 2); else self->ops.setDriver(self, "ST", "1", 1, 1, 2); loggerf(DEBUG, "%s: get ST=%s\n", self->name, self->ops.getDriver(self, "ST")); } static void long_poll(struct node *self) { logger(DEBUG, "longPoll\n"); } /* * Called by ISY to report all drivers for this node. This is done in * the parent class, so you don't need to override this method unless * there is a need. */ static void query(struct node *self) { self->ops.reportDrivers(self); } /* * Example command received from ISY. * set DON on TemplateNode. * Set the ST (status) driver to 1 or "true" */ static void cmd_on(struct node *self, char *id, char *value, int uom) { self->ops.setDriver(self, "ST", "1", 1, 1, 2); } /* * Example command received from ISY. * set DOF on TemplateNode. * Set the ST (status) driver to 0 or "false" */ static void cmd_off(struct node *self, char *id, char *value, int uom) { self->ops.setDriver(self, "ST", "0", 1, 1, 2); } /* * Not really a ping, but don't care... It's an example. */ static void cmd_ping(struct node *self, char *id, char *value, int uom) { loggerf(DEBUG, "cmd_ping: Enter: id = %s value = %s\n", id, value); } /* * Create a Template Node structure */ struct node *TemplateNode(char *address, char *parent, char *name) { struct node *n; n = allocNode("templatenodeid", address, parent, name); if (n == NULL) return n; /* * Create an array containing the variable names(drivers), values and * uoms(units of measure) from ISY. This is how ISY knows what kind * of variable to display. Check the UOM's in the WSDK for a complete list. * UOM 2 is boolean so the ISY will display 'True/False' */ addDriver(n, "ST", "1", 2); /* * Create an array of commands. If ISY sends a command to the NodeServer, * this tells it which method to call. DON calls setOn, etc. */ addCommand(n, "DON", cmd_on); addCommand(n, "DOF", cmd_off); addCommand(n, "PING", cmd_ping); /* * When a node is allocation it has a default set of node operations * pre-defined. If we want to override those, we can do so here. * * In this case, override the start, shortPoll, and longPoll node * operations. */ setNodeStart(n, start); setNodeLongPoll(n, long_poll); setNodeShortPoll(n, short_poll); setNodeQuery(n, query); /* Set the node's hint. The hint is a way to represent the node type. */ setNodeHint(n, '1', '2', '3', '4'); return n; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> int main(int argc, char *argv[]) { char buf[20] = { 0 }; memset(buf, 'A', sizeof(buf)); sprintf(buf, "hello"); printf("%s\n", buf); for (int i = 0; i < sizeof(buf); i++) { printf("%c", buf[i] == 0 ? '@' : buf[i]); } return 0; }
C
/**********************************************************/ //公司名称: //创建时间:2012-10-16 //作者:ke //文件名:mytimer.c //功能描述:该文件提供了单位为ms的标准定时和延时函数,需要timer.c的支持 /**********************************************************/ #include <stdio.h> #include "stm32f1xx_hal.h" #include "mytimer.h" //u32 gmy_sys_tick; /*系统全局计时器*/ /******************************************************************* 函数原形:void sys_tick_init (void) 功能: 初始化系统时钟 *******************************************************************/ //void sys_tick_init (void) //{ // gmy_sys_tick = 0; // TIM3_Int_Init(10-1,7200-1); /*初始化定时器3作为系统全局时钟,定时1ms*/ //} /******************************************************************* 函数原形:void timer_tick (void) 功能: 系统时钟自加 *******************************************************************/ //void timer_tick (void) //{ // gmy_sys_tick++; /*软件系统主时钟,1ms自加1*/ //} /******************************************************************* 函数原形:u32 time_now (void) 功能: 返回系统时钟 返回: 系统时钟计数值 *******************************************************************/ //u32 time_now (void) //{ // return gmy_sys_tick; /*返回软件系统主时钟单位ms*/ //} /******************************************************************* 函数原形:u32 past_time_get (TIMER* ptimer) 功能: 返回指定定时器超过的时间 参数: 定时器的地址 返回: 超过的时间单位ms *******************************************************************/ u32 past_time_get (TIMER* ptimer) { u32 time_now_temp = HAL_GetTick (); time_now_temp -= ptimer->rec_tick_val; return time_now_temp; /*返回软件时间超过时间单位ms*/ } /******************************************************************* 函数原形:void time_out_set (TIMER* stimer, u32 timeout) 功能: 设置指定定时器定时时间 参数: timer定时器的地址,timeout定时时间 *******************************************************************/ void time_out_set (TIMER* stimer, u32 timeout) { if (stimer == 0) { printf ("stimer memory error!!\r\n"); return; } stimer->time_out_val = timeout; /*初始化TIMER结构体所有成员*/ stimer->rec_tick_val = HAL_GetTick (); stimer->is_time_out = 0; } /******************************************************************* 函数原形:u8 is_time_out (TIMER* otimer) 功能: 查询指定定时器是否超时 参数: timer定时器的地址 返回: 超时标志 1表示超时,否则没有超时 *******************************************************************/ u8 is_time_out (TIMER* otimer) { u32 time_now_temp; if (otimer == 0) { printf ("otimer memory error!!\r\n"); return 0; } time_now_temp = past_time_get (otimer); if (time_now_temp < (otimer->time_out_val)) { otimer->is_time_out = 0; } else { otimer->is_time_out = 1; } return otimer->is_time_out; } /******************************************************************* 函数原形:void delay_se (u32 sec) 功能: 秒延时 参数: sec延时时间,sec<=4294967 *******************************************************************/ TIMER tsec; void delay_se (u32 sec) { time_out_set (&tsec, sec*1000); while (is_time_out (&tsec) == 0); }
C
// // linkedListStringVer.c // // Created by Kazuhiro Tobita on 11/12/2019. // #include <stdio.h> #define string txt1 = "airpods" #define string txt2 = "is a kind of eyerphones" struct node_struct { char character; struct node * next; struct node * prev; }; struct mystring_struct { struct node * head; struct node * tail; }; struct node_type * node_new(char expr) { node_struct * n; n = malloc(sizeof(struct node_struct)); n->character = expr; n->prev = n->prev = NULL; return n; }; struct mystring_type * empty_string_new(){ struct mystring_struct * s; s = malloc(sizeof(struct mystring_type)); s->head = s->tail = NULL; return s; }; struct mystring_type * put_string(char * str) { //create a new empty string struct mystring_struct * s; s = empty_string_new(); for(int i=0; str->[i] != '\0'; i++){ if(s->head == NULL) s->head = node_new(str[i]); /* else { s->tail = node_new(str[i]); s->tail->next = s->tail; s->tail = s->tail; } */ } return s; }; int compare_string(struct mystring_type * ms1, struct mystring_type * ms2) { int result = 0; len1 = stlren(ms1); len2 = strlen(ms2); if(len1 > len2) result 1; else if(len1 == len2) result 0; else result -1; return result; } int search_string(struct mystring_type * txt, struct mystring_type * terms) { int result = 1; for(int i=0; txt[i] != '\n'; i++) { struct node_struct * n1; n1 = node_new(txt[i]); for(int j=0; terms[j] != '\n'; j++) { struct node_struct n2; n2 = node_new(terms[j]); if(n1 != n2){ result = 0; break; } } } return result; } }
C
/* Maximum Bipartite Matching */ # include <stdio.h> # include <math.h> # define s(a) ((a)*(a)) # define SIZE 200 # define Q SIZE+1 typedef struct{ double x,y; }Point; int t,match[SIZE]; int d[SIZE][SIZE]; double dist(Point a,Point b) { return sqrt(s(a.x-b.x)+s(a.y-b.y)); } void MaximumBipartiteMatching(void) { int i,j,k; int level[SIZE],p[SIZE]; int q[Q],r,f; int last; for(i=0;i<t;i++) if(match[i]==-1){ for(j=0;j<=t;j++){ level[j]=0; p[j]=-1; } last=-1; level[i]=1; r=f=0; q[r]=i; r++; if(r==Q) r=0; while(r!=f){ j=q[f]; f++; if(f==Q) f=0; if(level[j]%2){ for(k=0;k<t;k++) if(d[j][k] && level[k]==0){ if(match[k]==-1){ level[k]=level[j]+1; p[k]=j; last=k; break; } else{ level[k]=level[j]+1; p[k]=j; q[r]=k; r++; if(r==Q) r=0; } } } else{ k=match[j]; level[k]=level[j]+1; p[k]=j; q[r]=k; r++; if(r==Q) r=0; } if(last!=-1) break; } while(last!=-1){ match[last]=p[last]; match[p[last]]=last; last=p[p[last]]; } } } int main(void) { int n,m,s,v; Point g[SIZE/2],h[SIZE/2]; int i,j; while(scanf("%d%d%d%d",&n,&m,&s,&v)==4){ for(i=0;i<n;i++) scanf("%lf%lf",&g[i].x,&g[i].y); for(i=0;i<m;i++) scanf("%lf%lf",&h[i].x,&h[i].y); t=m+n; for(i=0;i<t;i++){ match[i]=-1; for(j=0;j<t;j++) d[i][j]=0; } for(i=0;i<n;i++) for(j=0;j<m;j++) if(dist(g[i],h[j])<=s*v) d[i][n+j]=d[n+j][i]=1; MaximumBipartiteMatching(); j=0; for(i=0;i<n;i++) if(match[i]==-1) j++; printf("%d\n",j); } return 0; }
C
#include <unistd.h> #include <stdlib.h> #include <stdio.h> #define PRINT_ERR_EXIT(_msg) {perror(_msg); exit(1);} int main(void) { int cnt; cnt = unlink("linux.txt"); if (cnt == -1) PRINT_ERR_EXIT("Unlink linux.txt") printf("Unlink linux.txt success!!!\n"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <readline/readline.h> #include <readline/history.h> #include <string.h> #include <unistd.h> #include <ctype.h> #include <fcntl.h> #include <sys/types.h> #include <sys/wait.h> #include <assert.h> #define MAXARGS 100 #define PIPE_READ 0 #define PIPE_WRITE 1 /* COMPILAR__ gcc Aula6.1.c -lreadline ALTERAR ERROR CODES__ perror(); Output-> prints to screen ": SYSTEM_ERROR_SPECIFIC_STRING" */ typedef struct command { char *cmd; // string apenas com o comando int argc; // número de argumentos char *argv[MAXARGS+1]; // vector de argumentos do comando struct command *next; // apontador para o próximo comando } COMMAND; // variáveis globais char* inputfile = NULL; // nome de ficheiro (em caso de redireccionamento da entrada padrão) char* outputfile = NULL; // nome de ficheiro (em caso de redireccionamento da saída padrão) int background_exec = 0; // indicação de execução concorrente com a mini-shell (0/1) // declaração de funções COMMAND* parse(char* linha); void print_parse(COMMAND* commlist); void execute_commands(COMMAND* commlist); void free_commlist(COMMAND* commlist); // include do código do parser da linha de comandos #include "parser.c" int main(int argc, char* argv[]) { char *linha; COMMAND *com; while (1) { if ((linha = readline("my_prompt$ ")) == NULL) exit(0); if (strlen(linha) != 0) { add_history(linha); com = parse(linha); //objecto command == input da linha if (com) { //print_parse(com); execute_commands(com); free_commlist(com); } } free(linha); } } void print_parse(COMMAND* commlist) { int n, i; printf("---------------------------------------------------------\n"); printf("BG: %d IN: %s OUT: %s\n", background_exec, inputfile, outputfile); n = 1; while (commlist != NULL) { printf("#%d: cmd '%s' argc '%d' argv[] '", n, commlist->cmd, commlist->argc); i = 0; while (commlist->argv[i] != NULL) { printf("%s,", commlist->argv[i]); i++; } printf("%s'\n", commlist->argv[i]); commlist = commlist->next; n++; } printf("---------------------------------------------------------\n"); } void free_commlist(COMMAND *commlist){ // ... // Esta função deverá libertar a memória alocada para a lista ligada. // ... COMMAND* com; while(commlist != NULL) { com = commlist->next; free(commlist); commlist = com; } background_exec=0; } void execute_commands(COMMAND *commlist) { // ... // Esta função deverá "executar" a "pipeline" de comandos da lista commlist. // ... if(strcmp(commlist->argv[0],"exit")==0) { exit(EXIT_SUCCESS); } pid_t pid; int fd[2]; // crio pipe, para partilhar pai e filho if(pipe(fd) == -1) { perror("Error"); exit(0); } // cria child, pos guardado em pid if((pid=fork()) == -1) { perror("Error"); exit(0); } //fd[0] read, fd[1] write //parent if(pid) { wait(NULL); } //child else { if(inputfile != NULL) { int file; /* Abre o ficheiro e guarda file descriptor */ if ((file = open(inputfile, O_RDONLY)) < 0 ) { perror("Error"); exit(EXIT_FAILURE); } /* Duplica o file descriptor e substitui pelo STDIN */ dup2(file, STDIN_FILENO); //dup2(source,destino) } if(outputfile!=NULL) { int file; /* Abre o ficheiro e guarda o file descriptor */ if ((file = open(outputfile, O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU)) < 0) { perror("Error"); exit(EXIT_FAILURE); } /* Duplica o file descriptor e substitui pelo STDOUT */ dup2(file, STDOUT_FILENO); //dup2(source,destino) } if(execvp(commlist->cmd,commlist->argv) < 0) { //versao generica do execlp, 2 argumentos execvp(comando,vector com argumentos) //exec error perror("Error"); exit(EXIT_FAILURE); } } }
C
/* Md. Imran Hosen Id: 2619150011 www.github.com/MdImranHosen */ #include<stdio.h> #include<conio.h> void main(){ char s[5]; system("cls"); printf("\n Enter any operator:"); gets(s); switch(s[0]) { case'>': if(s[1]=='=') printf("\n Greater than or equal"); else printf("\n Greater than"); break; case'<': if(s[1]=='=') printf("\n Less than or equal"); else printf("\n Less than"); break; case'=': if(s[1]=='=') printf("\n Equal to"); else printf("\n Assignment"); break; case'!': if(s[1]=='=') printf("\nNot Equal"); else printf("\n Bit Not"); break; case'&': if(s[1]=='&') printf("\nLogical AND"); else printf("\n Bitwise AND"); break; case'|': if(s[1]=='|') printf("\nLogical OR"); else printf("\nBitwise OR"); break; case'+': printf("\n Addition"); break; case'-': printf("\nSubstraction"); break; case'*': printf("\nMultiplication"); break; case'/': printf("\nDivision"); break; case'%': printf("Modulus"); break; default: printf("\n Not a operator"); } getch(); }
C
#include<header.h> int size_of_file(const char *file) { struct stat buf; if(stat(file,&buf) != 0) { perror("error:"); return 0; } else return buf.st_size; }
C
#include<stdio.h> #include<stdlib.h> struct Node{ int data; struct Node *next; }; void print(struct Node *ptr){ while(ptr!=NULL){ printf("%d ",ptr->data); ptr=ptr->next; } printf("\n"); } struct Node *insertBeg(struct Node *head,int data){ if(head==NULL) { head=(struct Node *)malloc(sizeof(struct Node )); head->data=data; head->next=NULL; return head; } struct Node *temp=(struct Node *)malloc(sizeof(struct Node)); temp->data=data; temp->next=head; head=temp; return head; } struct Node *insertLast(struct Node *head,int data){ if(head==NULL){ head=(struct Node *)malloc(sizeof(struct Node)); head->data=data; head->next=NULL; return head; } else{ struct Node *ptr=head; while(ptr->next!=NULL){ ptr=ptr->next; } struct Node *temp=(struct Node *)malloc(sizeof(struct Node)); temp->data=data; temp->next=NULL; ptr->next=temp; return head; } } struct Node *delBeg(struct Node *head){ if(head==NULL) return NULL; struct Node *temp=head; head=head->next; free(temp); return head; } struct Node *delLast(struct Node *head){ if(head==NULL){ return NULL; } struct Node *ptr=head; if(!ptr->next){ free(head); return NULL; } while(ptr->next->next!=NULL){ ptr=ptr->next; } ptr->next=NULL; return head; } struct Node *insertInbetween(struct Node *head,int n,int d){ struct Node *ptr=head; int i=1; if(head==NULL) { head=(struct Node *)malloc(sizeof(struct Node)); head->data=d; head->next=NULL; return head; } while(i<n && (ptr->next!=NULL)){ i++; ptr=ptr->next; } // printf("**** %d ****",ptr->data); struct Node *temp=(struct Node *)malloc(sizeof(struct Node)); temp->data=d; if(ptr->next!=NULL){ temp->next=ptr->next->next; } else{ temp->next=NULL; } ptr->next=temp; return head; } int main(){ int d,i=0; printf("Press -1 To End insertion Operation\n"); struct Node *head; struct Node *ptr; scanf("%d",&d); while(d!=-1){ if(i==0){ head=(struct Node *)malloc(sizeof(struct Node)); head->data=d; head->next=NULL; ptr=head; } else{ struct Node *temp=(struct Node *)malloc(sizeof(struct Node )); temp->data=d; temp->next=NULL; ptr->next=temp; ptr=ptr->next; } i++; scanf("%d",&d); } head=insertLast(head,5); head=insertLast(head,7); head=insertBeg(head,0); head=insertBeg(head,9); head=insertInbetween(head,2,55);//send the node number head=delBeg(head); head=delLast(head); print(head); return 0; }
C
// Está com os problemas na parte da biblioteca ainda Orlando. Como mudamos de liguagem ficou um pouco mais corrido entao estamos postando essa para realizar alterações //posteriormente #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include <limits.h> # include <sys/socket.h> #include <pthread.h> #include <sys/un.h> #include <signal.h> int main(void){ struct sockaddr_un serverAdress; struct sockadder serverScokAddrPtr; int socket_fd, nbytes, serverAdressLength; char buffer[256]; socket_fd = socket(PF_LOCAL,SOCK_STREAM, 0); if(socket_fd < 0){ printf("Erro ao criar cliente\a\n"); return 1; } serverAdress.sun_family= AF_LOCAL; sprintf(serverAdress.sun_path,"demo_socket"); serverScokAddrPtr = (struct sockaddr*) &serverAdress; serverAdressLength = sizeof(serverAdress); if(connect(socket_fd, serverScokAddrPtr, serverAdressLength)){ printf("Conexão do cliente falhou\a\n"); return 1; } printf("(Cliente) Escreva uma mensagem aqui:"); fgets(buffer, 255, stdin); write(socket_fd, buffer, strlen(buffer)); nbytes = read(socket_fd, buffer, 256); buffer[nbytes] = '\0'; printf("Resposta do servidor : [%s]\n", buffer); return 0; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> char* numbertostring(char* str, int i); char numberString0To19[20][10] = {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",\ "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen",\ "seventeen", "eighteen", "nineteen"}; char numberStringX0[10][10] = {"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}; int main() { int i; long result = 0; char* buffer; for(i = 1; i <= 1000; i++) { // Here is the best solution to allocate dynamic memory, if // allocate inside function, then there is no good way to free the memory. // You can free the memory after return from function, but it is hard to read. // So managing the buffer outside function will be clearer and easier. buffer = (char*) malloc(100); result = result + strlen(numbertostring(buffer, i)); free(buffer); } printf("%li\n", result); } /* * Function Name: numbertostring * input: * str: the dynamic buffer pointer allocated outside the function * i: integer number from 1 to 1000 * output: String converted from input integer number */ char* numbertostring(char* str, int i) { if( i >= 0 && i <= 19) return numberString0To19[i]; else if( i >= 20 && i < 1000 ) { if( i/100 != 0 ) { strcpy(str, numberString0To19[i/100]); if ( i%100 == 0) { strcat(str, "hundred"); } else { strcat(str, "hundredand"); if( i%100 >= 0 && i%100 <= 19 ) { strcat(str, numberString0To19[i%100]); } else { strcat(str, numberStringX0[(i/10)%10]); strcat(str, numberString0To19[i%10]); } } } else { strcpy(str, numberStringX0[i/10]); strcat(str, numberString0To19[i%10]); } return str; } else if( i == 1000 ) return "onethousand"; return NULL; }
C
#ifndef VEC_H #define VEC_H #include <math.h> typedef struct vec3_t { double x, y, z; } Vec3; Vec3 vec_create(double x, double y, double z); Vec3 vec_cross(Vec3 v1, Vec3 v2); double vec_dot(Vec3 v1, Vec3 v2); double vec_length(Vec3 v); #endif /* end of include guard: VEC_H */
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> //#include <wiringPi.h> #define ledPin 21 #define dit 100; #define dah 300; #pragma warning(disable:4996) static const char* space[2] = { "*", "*******" }; static const char* alpha[30] = { ".-", //A "-...", //B "-.-.", //C "-..", //D ".", //E "..-.", //F "--.", //G "....", //H "..", //I ".---", //J "-.-", //K ".-..", //L "--", //M "-.", //N "---", //O ".--.", //P "--.-", //Q ".-.", //R "...", //S "-", //T "..-", //U "...-", //V ".--", //W "-..-", //X "-.--", //Y "--..", //Z }; static const char* num[10] = { "-----", //0 ".----", //1 "..---", //2 "...--", //3 "....-", //4 ".....", //5 "-....", //6 "--...", //7 "---..", //8 "----.", //9 }; void main() { char toMorse[200]; char morsingCode[500] = ""; static const char nullByte[1] = "0"; char ch; int c = 0; int index = 0; //wiringPiSetup(); //pinMode(ledPin, OUTPUT); printf("to morse: "); fgets(toMorse, 200, stdin); while (true) { ch = toMorse[index++]; c = ch; if (ch == '\n') { break; } if (c >= 48 && c <= 57) //number { c = c - 48; strcat(morsingCode, num[c]); strcat(morsingCode, space[0]); } else if (c >= 65 && c <= 90) //character { c = c - 65; strcat(morsingCode, alpha[c]); strcat(morsingCode, space[0]); } else if (c == 32) //space { strcat(morsingCode, space[1]); } } strcat(morsingCode, nullByte); puts(morsingCode); index = 0; while (true) { if (morsingCode[index] == '0') { break; } else if(morsingCode[index] == '.') { printf("kurz "); //delay(dit); } else if (morsingCode[index] == '-') { printf("lang "); //delay(dah); } else if (morsingCode[index] == '*') { printf("pause "); //delay(dah); } index++; } }
C
#include "server.h" int main(void) { volatile int ser_sock = 0; volatile struct sockaddr cli_addr = {0}; volatile char r_buff[] = "\0"; const char w_buff[] = "hello client"; const socklen_t cli_len = sizeof(struct sockaddr); while(1) { recvfrom(ser_sock, r_buff, sizeof(r_buff), 0, &cli_addr, &cli_len); sendto(ser_sock, w_buff, strlen(w_buff), 0, &cli_addr, cli_len); printf("from client Msg:%s\n", r_buff); } return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<ctype.h> int main() { char a; scanf("%c",&a); if(isdigit(a)){ printf("hello"); } }