language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include<stdio.h> #include<string.h> #include<stdbool.h> int main() { char word[100]; scanf("%s", &word); bool con = true; for(int i = 1; i < strlen(word); i++) { if(word[i] >= 'a' && word[i] <= 'z') { con = false; break; } } if(con) { for(int i = 0; i < strlen(word); i++) { if(word[i] >= 'A' && word[i] <= 'Z') { word[i]+=32; } else { word[i]-=32; } } } printf("%s\n", word); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_printf_utils.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lpinheir <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/03/24 23:34:42 by lpinheir #+# #+# */ /* Updated: 2021/05/01 13:15:21 by lpinheir ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" int get_inverted(char *cpypointer) { while (!(ft_isalpha(*cpypointer)) && *cpypointer != '\0') { if (*cpypointer == '-') return (1); else if (*cpypointer == '%') break ; cpypointer++; } return (0); } static int get_num_n_zero(va_list args, int **inverted) { int num; num = va_arg(args, int); if (num < 0) { **inverted = 1; return (-1 * num); } return (num); } static int get_num_zero(va_list args, int **inverted) { int num; num = va_arg(args, int); if (num < 0) **inverted = 1; return (-1 * num); } int get_width(char *cpypointer, va_list args, int *inverted) { while (!(ft_isalpha(*cpypointer)) && *cpypointer != '\0') { if (*cpypointer == '*') return (get_num_n_zero(args, &inverted)); else if (ft_isdigit(*cpypointer)) { if (*cpypointer == '0') { cpypointer++; if (*cpypointer == '*') return (get_num_zero(args, &inverted)); else if (ft_isdigit(*cpypointer) && *cpypointer != '0') return (-1 * ft_atoi(cpypointer)); cpypointer--; } else return (ft_atoi(cpypointer)); } else if (*cpypointer == '.' || *cpypointer == '%') break ; cpypointer++; } return (0); } int get_precision(char *cpypointer, va_list args) { int control; control = -1; while (!(ft_isalpha(*cpypointer)) && *cpypointer != '\0') { if (*cpypointer == '.') control = 0; else if (*cpypointer == '*' && control == 0) return (va_arg(args, int)); else if (ft_isdigit(*cpypointer) && control == 0) return (ft_atoi(cpypointer)); else if (*cpypointer == '%') break ; cpypointer++; } return (control); }
C
#include<stm32f4xx.h> #include<stm32f4xx_gpio.h> #include<stm32f4xx_rcc.h> #include<stm32f4xx_usart.h> #include<misc.h> void InitializeGPIO() { GPIO_InitTypeDef PortD; RCC_AHB1PeriphClockCmd (RCC_AHB1Periph_GPIOD , ENABLE); PortD.GPIO_Pin = GPIO_Pin_13; PortD.GPIO_Mode = GPIO_Mode_OUT; PortD.GPIO_Speed = GPIO_Speed_25MHz; PortD.GPIO_OType = GPIO_OType_PP; PortD.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_Init(GPIOD,&PortD); } void USART_Initialize() { GPIO_InitTypeDef PortB; RCC_AHB1PeriphClockCmd (RCC_AHB1Periph_GPIOB , ENABLE); GPIO_PinAFConfig(GPIOB,GPIO_PinSource11,GPIO_AF_USART3); //USART3_RX GPIO_PinAFConfig(GPIOB,GPIO_PinSource10,GPIO_AF_USART3); //USART3_TX PortB.GPIO_Pin = GPIO_Pin_11| GPIO_Pin_10; PortB.GPIO_Mode = GPIO_Mode_AF; PortB.GPIO_Speed = GPIO_Speed_25MHz; PortB.GPIO_OType = GPIO_OType_PP; PortB.GPIO_PuPd = GPIO_PuPd_UP; GPIO_Init(GPIOB,&PortB); USART_InitTypeDef usart; RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE); usart.USART_BaudRate=9600; usart.USART_WordLength=USART_WordLength_8b; usart.USART_StopBits=USART_StopBits_1; usart.USART_Parity=USART_Parity_No; usart.USART_Mode=USART_Mode_Rx | USART_Mode_Tx;; usart.USART_HardwareFlowControl=USART_HardwareFlowControl_None; USART_Init(USART3,&usart); USART_Cmd(USART3,ENABLE) ; USART_ITConfig(USART3, USART_IT_RXNE, ENABLE); USART_ITConfig(USART3, USART_IT_TC, ENABLE); // NVIC_EnableIRQ(USART3_IRQn); } void InitializeNVIC() { NVIC_InitTypeDef A; A.NVIC_IRQChannel=USART3_IRQn; A.NVIC_IRQChannelPreemptionPriority=0; A.NVIC_IRQChannelSubPriority=0; A.NVIC_IRQChannelCmd=ENABLE; NVIC_Init(&A); } int main(void) { InitializeGPIO(); //GPIO_SetBits (GPIOD,GPIO_Pin_13); USART_Initialize(); InitializeNVIC(); while(1) { } } void USART3_IRQHandler() { //char a; // RXNE handler // if(USART_GetITStatus(USART3, USART_IT_RXNE) != RESET) // { // USART_ClearITPendingBit (USART3 , USART_IT_RXNE); // If received 'a', toggle LED and transmit 'A' if(USART_ReceiveData(USART3) == 'a') { GPIO_ResetBits (GPIOD,GPIO_Pin_13); USART_SendData(USART3, 'A'); } // } }
C
#include "disassembler/disassembler.h" #include <assert.h> #include <base/print_format.h> #include <stdbool.h> #include <stdio.h> #define MNEMONIC "%-8s" const char *indirect_memory_encoding_to_string(enum indirect_memory_encoding encoding) { static const char *mapping[8] = { "bx+si", "bx+di", "bp+si", "bp+di", "si", "di", "bp", "bx", }; return mapping[encoding]; } int print_prefix(char *buffer, size_t buffer_size, const struct instruction *instruction) { switch (instruction->rep_mode) { case rm_rep: return snprintf(buffer, buffer_size, "rep "); case rm_repne: return snprintf(buffer, buffer_size, "repne "); case rm_none: break; default: assert(0); break; } return 0; } int print_mnemonic(char *buffer, size_t buffer_size, const struct instruction *instruction) { return snprintf(buffer, buffer_size, MNEMONIC, instruction_type_to_string(instruction->type)); } int print_immediate(char *buffer, size_t buffer_size, const struct operand *operand) { switch (operand->size) { case os_8: return snprintf(buffer, buffer_size, HEX_8, operand->data.as_immediate.immediate_8); case os_16: return snprintf(buffer, buffer_size, HEX_16, operand->data.as_immediate.immediate_16); default: assert(0); return 0; } } int print_pointer_size(char *buffer, size_t buffer_size, enum operand_size size) { switch (size) { case os_8: return snprintf(buffer, buffer_size, "BYTE PTR "); case os_16: return snprintf(buffer, buffer_size, "WORD PTR "); default: assert(0); return 0; } } int print_indirect(char *buffer, size_t buffer_size, enum operand_size size, enum segment_register segment_register, enum indirect_memory_encoding ime, i16 displacement) { int inc = 0; inc += print_pointer_size(buffer, buffer_size, size); inc += snprintf(buffer + inc, buffer_size - inc, "%s:[%s", segment_register_to_string(segment_register), indirect_memory_encoding_to_string(ime)); if (displacement == 0) { return inc + snprintf(buffer + inc, buffer_size - inc, "]"); } if (displacement < 0) { inc += snprintf(buffer + inc, buffer_size - inc, "-"); displacement *= -1; } else { inc += snprintf(buffer + inc, buffer_size - inc, "+"); } switch (size) { case os_8: return inc + snprintf(buffer + inc, buffer_size - inc, HEX_8 "]", displacement); case os_16: return inc + snprintf(buffer + inc, buffer_size - inc, HEX_16 "]", displacement); default: assert(0); return 0; } } int print_operand(char *buffer, size_t buffer_size, const struct operand *operand, u32 offset, u8 instruction_size) { switch (operand->type) { case ot_indirect: { return print_indirect(buffer, buffer_size, operand->size, operand->data.as_indirect.seg_reg, operand->data.as_indirect.encoding, 0); } case ot_displacement: { return print_indirect( buffer, buffer_size, operand->size, operand->data.as_displacement.seg_reg, operand->data.as_displacement.encoding, operand->data.as_displacement.displacement); } case ot_register: switch (operand->size) { case os_8: return snprintf(buffer, buffer_size, "%s", register_8_to_string(operand->data.as_register.reg_8)); case os_16: return snprintf(buffer, buffer_size, "%s", register_16_to_string(operand->data.as_register.reg_16)); default: assert(0); return 0; } case ot_direct: { int inc = print_pointer_size(buffer, buffer_size, operand->size); return inc + snprintf(buffer + inc, buffer_size - inc, "%s:" HEX_16, segment_register_to_string(operand->data.as_direct.seg_reg), operand->data.as_direct.address); } case ot_direct_with_segment: return snprintf(buffer, buffer_size, HEX_16 ":" HEX_16, operand->data.as_direct_with_segment.segment, operand->data.as_direct_with_segment.offset); case ot_immediate: return print_immediate(buffer, buffer_size, operand); case ot_segment_register: return snprintf(buffer, buffer_size, "%s", segment_register_to_string(operand->data.as_segment_register.reg)); case ot_jump: { u16 new_addr = offset + instruction_size + operand->data.as_jump.offset; return snprintf(buffer, buffer_size, HEX_16, new_addr); } case ot_far_jump: return snprintf(buffer, buffer_size, HEX_16 ":" HEX_16, operand->data.as_far_jump.segment, operand->data.as_far_jump.offset); case ot_offset: { int inc = snprintf(buffer, buffer_size, "%s:", segment_register_to_string(operand->data.as_offset.seg_reg)); switch (operand->size) { case os_8: return inc + snprintf(buffer + inc, buffer_size - inc, HEX_8, operand->data.as_offset.offset); case os_16: return inc + snprintf(buffer + inc, buffer_size - inc, HEX_16, operand->data.as_offset.offset); default: assert(0); return 0; } } case ot_ds_si: { int inc = print_pointer_size(buffer, buffer_size, operand->size); return inc + snprintf(buffer + inc, buffer_size - inc, "ds:[si]"); } case ot_es_di: { int inc = print_pointer_size(buffer, buffer_size, operand->size); return inc + snprintf(buffer + inc, buffer_size - inc, "es:[di]"); } case ot_none: return 0; default: assert(0); return 0; } } int print_buffer(char *buffer, size_t buffer_size, const struct instruction *instruction) { int inc = 0; unsigned i = 0; for (; i < instruction->instruction_size; ++i) { inc += snprintf(buffer + inc, buffer_size - inc, "%02x ", instruction->buffer[i]); } for (; i < 8; ++i) { inc += snprintf(buffer + inc, buffer_size - inc, " "); } return inc; } static enum instruction_type no_operand_mnemonics[] = { // it_lodsb, // it_lodsw, it_popf, it_pushf, }; static bool must_print_operands(enum instruction_type it) { for (unsigned i = 0; i < ARRAY_SIZE(no_operand_mnemonics); ++i) { if (it == no_operand_mnemonics[i]) { return false; } } return true; } int disassemble(char *buffer, size_t buffer_size, const struct instruction *instruction, u32 offset) { int inc = 0; inc += snprintf(buffer + inc, buffer_size - inc, HEX_16 " ", offset); inc += print_buffer(buffer + inc, buffer_size - inc, instruction); inc += print_prefix(buffer + inc, buffer_size - inc, instruction); inc += print_mnemonic(buffer + inc, buffer_size - inc, instruction); bool mpo = must_print_operands(instruction->type); if (mpo) { inc += print_operand(buffer + inc, buffer_size - inc, &instruction->destination, offset, instruction->instruction_size); if (instruction->source.type != ot_none) { inc += snprintf(buffer + inc, buffer_size - inc, ", "); } inc += print_operand(buffer + inc, buffer_size - inc, &instruction->source, offset, instruction->instruction_size); } return inc; }
C
#include<stdio.h> struct process { int pid; int status; int priority; int at; int bt; int ct; int wt; int tt; }; void main() { int i, time = 0, burst_time = 0, current,n; char c; float w_time = 0; float t_time = 0; float avg_w_time; float avg_t_time; printf("Enter Total Number of Processes: "); scanf("%d", &n); struct process pro[n]; for(i=0;i<n;i++) { pro[i].pid = i+1; printf("Enter details for process no. %d:\n", pro[i].pid); printf("Enter Arrival Time: "); scanf("%d", &pro[i].at); printf("Enter Burst Time: "); scanf("%d", &pro[i].bt); printf("Enter Priority: "); scanf("%d", &pro[i].priority); pro[i].status = 0; burst_time = burst_time + pro[i].bt; } struct process temp; int k, j; for(k = 0; k < n-1; k++) { for(j = i+1 ; j < n; j++) { if(pro[k].at > pro[j].at) { temp = pro[k]; pro[k] = pro[j]; pro[j] = temp; } } } pro[n].priority = 9999; printf("-----------------------------------------------------------------"); printf("\nProcess \tPriority\tArrival time\tBurst time\tWaiting Time"); for(time = pro[0].at; time < burst_time;) { current = n; for(i=0;i<n;i++) { if(pro[i].at <= time && pro[i].status != 1 && pro[i].priority < pro[current].priority) { current = i; } } time = time + pro[current].bt; pro[current].ct = time; pro[current].tt = pro[current].ct - pro[current].at; pro[current].wt = pro[current].ct - pro[current].at - pro[current].bt; pro[current].status = 1; t_time = t_time + pro[current].tt; w_time = w_time + pro[current].wt; printf("\nP%d\t\t%d\t\t%d\t\t%d\t\t%d", pro[current].pid, pro[current].priority, pro[current].at, pro[current].bt, pro[current].wt); } printf("\n\n-----------------------------------------------------------------\n\n"); avg_t_time = t_time/n; avg_w_time = w_time/n; printf("\nAverage waiting time: %f\n", avg_w_time); printf("Average Turnaround Time: %f", avg_t_time); }
C
#include <stdio.h> #define file_in "../numeri.txt" #define file_out "../output.txt" int main() { FILE *fp_in, *fp_out; int x1, x2, x3, max, min, n_scartati = 0, check; if ((fp_in = fopen(file_in, "r")) == NULL) { printf("Errore nell'aperture file input.\n"); return 1; } if ((fp_out = fopen(file_out, "w")) == NULL) { printf("Errore nell'apertura file output.\n"); return 2; } fscanf(fp_in, "%d %d", &x1, &x2); min = max = x1; if(x2>max) max=x2; if(x2<min) min=x2; do { fscanf(fp_in, "%d", &x3); check = 0; while (!check) { if ((x3!=x1+x2) && (x3!=x1-x2) && (x3!=x1*x2) && (x3!=x1/x2 && x2!=0)) { fscanf(fp_in, "%d", &x3); if (feof(fp_in)) check=1; n_scartati++; } else { check = 1; if (x3>max) max=x3; if(x3<min) min=x3; } } x1=x2; x2=x3; } while (!feof(fp_in)); fprintf(fp_out, "Numero massimo: %d.\n", max); fprintf(fp_out, "Numero minimo: %d.\n", min); fprintf(fp_out, "Numeri scartati: %d.\n", n_scartati); fclose(fp_out); fclose(fp_in); return 0; }
C
/* ============================================================================ Roll no.:23103 Name:Abhishek Agashe Class:SE-9 Batch:E-9 Problem Statement:Perform following String operations without pointers to arrays (without using the library functions): a) substring b) palindrome c) compare d) copy e) Reverse. ============================================================================ */ #include <stdio.h> #include <stdlib.h> int length(char s[]) { int len=0; int i=0; while(s[i]!='\0') { len=len+1; i++; } return len; } void copy(char s1[],char s2[]) { int len=length(s2); int i; for(i=0;i<len;i++) { s1[i]=s2[i]; } s1[i]='\0'; } void reverse(char s1[]) { int len=length(s1); char s2[len]; copy(s2,s1); int i,j=len-1; for(i=0;i<len;i++) { s1[i]=s2[j--]; } } void palin(char s1[]) { int len=length(s1); char s2[len]; copy(s2,s1); reverse(s2); int i,flag=0; for(i=0;i<len;i++) { if(s2[i]!=s1[i]) { flag=1; break; } } if(flag==1) { printf("%s is not a palindrome string\n",s1); } else if(flag==0) { printf("%s is a palindrome string\n",s1); } } int compare(char s1[],char s2[]) { int i,flag=1; int len1=length(s1); int len2=length(s2); int len; if(len1>=len2) { len=len2; } else { len=len1; } for(i=0;i<len;i++) { if(s1[i]!=s2[i]) { flag=0; return ((int)s1[i]-(int)s2[i]); } } if(flag==1) { return 0; } } void subString(char s1[],char s2[]) { int len1=length(s1); int len2=length(s2); int i,j=0,c=0; for(i=0;i<len1;i++) { if(j==len2) { break; } if(s1[i]==s2[j]) { j++; } else { j=0; i=c; c++; } } if(j==len2) { printf("%s is a part of %s\n\n",s2,s1); } else { printf("%s is not a part of %s\n\n",s2,s1); } } int main(void) { char s1[50],s2[50]; int len,l; printf("Enter a string\n"); scanf("%s",s1); printf("\n\n"); int ch; do { printf("Select the Options:\n"); printf("1. Length\n"); printf("2. Palindrome\n"); printf("3. String Compare\n"); printf("4. Copy\n"); printf("5. Reverse\n"); printf("6. Substring\n"); printf("7. Exit\n\n"); scanf("%d",&ch); switch(ch) { case 1:printf("String : %s\n",s1); len=length(s1); printf("Length of String : %d\n",len); printf("\n\n"); break; case 2:printf("String : %s\n",s1); palin(s1); printf("\n\n"); break; case 3:printf("Enter a string to compare it with %s: ",s1); scanf("%s",s2); printf("String 1: %s\n",s1); printf("String 2: %s\n",s2); l=compare(s1,s2); printf("Returned Value: %d\n\n",l); break; case 4:printf("Enter a string to copy it in %s: ",s1); scanf("%s",s2); printf("Before Copying:\n"); printf("String 1: %s\n",s1); printf("String 2: %s\n\n",s2); copy(s1,s2); printf("After Copying:\n"); printf("String 1: %s\n",s1); printf("String 2: %s\n\n",s2); break; case 5:printf("Before Reversing:\n"); printf("String : %s\n\n",s1); reverse(s1); printf("After Reversing:\n"); printf("String : %s\n\n",s1); break; case 6:printf("Enter a string to check if it is a part of %s: ",s1); scanf("%s",s2); printf("String 1: %s\n",s1); printf("String 2: %s\n",s2); subString(s1,s2); printf("\n\n"); break; case 7:printf("END\n\n"); break; default:printf("Enter Again/n"); } } while(ch!=7); return EXIT_SUCCESS; }
C
#define _CRT_SECURE_NO_WARNINGS 1 void bubble_sort() { ? int a[] = {1, 34, 23, 55, 22, 11}; int i,j,k; for(i=0;i<5;i++) { for(j=0;j<5-i;j++) if(a[j]>a[j+1]) { k=a[j]; a[j]=a[j+1]; a[j+1]=k; printf("%d\n", a[j]); // a[j] ^= a[j+1] ^= a[j]; } } void insert_sort() { int i, j, m, tmp; int a[10] = {1, 34, 23, 55, 22, 11, 45, 67, 35, 26}; #if 1 for(i=0;i<10;i++) { m=a[i]; for(j=i-1;j >= 0;j--) { if(a[j] < m) break; else a[j+1] = a[j]; } a[j+1] = m; } #else for(i = 1; i < 10; i++) { m = 5; if(i != m){ j = i; tmp = a[i]; while(j > m){ a[j] = a[j-1]; j--; } a[j] = tmp; } } quick_sort(int L[],int first,int end) { int pos; if(end>first) { pos=quick(first,end,L); quick_sort(L,first,pos-1); quick_sort(L,pos+1,end); } } quick(int first,int end,int L[]) { int left=first, right=end,key; key=L[first]; while(left<right) { while((left<right)&&(L[right]>=key)) { right--; printf("left:%d right:\n",left); } if(left<right) { L[left++]=L[right]; // printf("left2:%d right: \n",left); } while((left<right)&&(L[left]<=key)) left++; if(left<right) L[right--]=L[left]; } L[left]=key; // printf("left3:%d right: \n",left); return left; }
C
#pragma once #include<stdio.h> #include <device_functions.h> #include "cuda_runtime.h" #include "device_launch_parameters.h" #include<iostream> #include<math.h> #include"Matrix.h" __device__ double norm( double* mat, int col,int matrow, int matcol) { double ans = 0; for (int i = 0; i < matrow; i++) { ans += (mat[i*matcol+col] * mat[i*matcol+col]); } return sqrt(ans); } __device__ double dot_prod(double* a, double* e, int x, int y,int arow, int acol, int ecol) { double ans = 0; for (int i = 0; i < arow; i++) { ans =ans+ (a[(i*acol)+x] * e[(i*ecol)+y]); } return ans; } double norm_host(Matrix &mat, int col) { double ans = 0; for (int i = 0; i < mat.row; i++) { ans += (mat.p[i * mat.col + col] * mat.p[i * mat.col + col]); } return sqrt(ans); } double dot_prod_host(Matrix &a, Matrix &e, int x, int y) { double ans = 0; for (int i = 0; i < a.row; i++) { ans = ans + (a.p[(i * a.col) + x] * e.p[(i * e.col) + y]); } return ans; }
C
#include "ext2.h" #include "utility.h" #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #define BYTE 8 #define KB 1024 #define SB_OFFSET 1024 #define EXT2_S_IFDIR 0x4000 // Global filesystem structure static EXT2 *ext2fs = NULL; static LLDIRLIST *make_lldirlist_node(LLDIR *ld); static void lldirlist_insert(LLDIRLIST **head, LLDIR *ld); static void get_blocks(int **blocks, int block, int indirection, int *n, int max); static int get_block_from_inode(INODETABLE *it, int **blocks); static int read_block_bitmap(int bgn, BITMAP *bbm); // Initializes the file system void ext2_init(char *disk) { unsigned int i; unsigned int offset; ext2fs = (EXT2 *)safe_malloc(sizeof(EXT2), "Failed to allocate memory for file system!"); ext2fs->sb = (SUPERBLOCK *)safe_malloc(sizeof(SUPERBLOCK), "Failed to allocate memory for superblock!"); // Open filesystem ext2fs->fd = safe_open(disk, O_RDWR, "Unable to open disk!"); // Read superblock from filesystem lseek(ext2fs->fd, SB_OFFSET, SEEK_SET); safe_read(ext2fs->fd, ext2fs->sb, sizeof(SUPERBLOCK), "Failed to read from disk!"); // Calculate block size for filesystem ext2fs->block_size = KB << ext2fs->sb->s_log_block_size; // Calculate number of block groups ext2fs->n_bg = ext2fs->sb->s_free_blocks_count / ext2fs->sb->s_blocks_per_group; if(ext2fs->n_bg == 0) ext2fs->n_bg++; ext2fs->bg = (BLOCKGROUP **)safe_malloc(ext2fs->n_bg * sizeof(BLOCKGROUP *), "Failed to allocate memory for block group descriptor table!"); // Read block group descriptors, start at third block for 1kb systems or // second block for larger block systems offset = (ext2fs->block_size == KB) ? 2 * KB : ext2fs->block_size; for(i = 0; i < ext2fs->n_bg; ++i) { ext2fs->bg[i] = (BLOCKGROUP *)safe_malloc(sizeof(BLOCKGROUP), "Failed to allocate memory for block group descriptor!"); lseek(ext2fs->fd, offset, SEEK_SET); read(ext2fs->fd, ext2fs->bg[i], sizeof(BLOCKGROUP)); offset += sizeof(BLOCKGROUP); } // Initialize open files list ext2fs->maxfiles = 2; ext2fs->open_files = (EXT2_FILE **)safe_malloc(ext2fs->maxfiles * sizeof(EXT2_FILE *), ""); ext2fs->nfiles = 0; } // Checks if file system has been initialized int ext2checkfs() { if(!ext2fs) return 0; return 1; } // closes the filesystem, frees memory void ext2_close() { unsigned int i; if(ext2fs->fd != -1) close(ext2fs->fd); free(ext2fs->sb); for(i = 0; i < ext2fs->n_bg; ++i) free(ext2fs->bg[i]); free(ext2fs->bg); free(ext2fs); } int ext2_get_blocksize() { return ext2fs->block_size; } int ext2_read_block(int blockid, char *buf, int count, int offset) { lseek(ext2fs->fd, ext2fs->block_size * blockid + offset, SEEK_SET); return read(ext2fs->fd, buf, count); } int ext2_write_block(int blockid, const char *buf, int count, int offset) { lseek(ext2fs->fd, ext2fs->block_size * blockid + offset, SEEK_SET); return write(ext2fs->fd, buf, count); } int ext2_add_blocks(EXT2_FILE *ext2fd, int nblocks) { BITMAP bbm; int free_blocks[nblocks], len; int nbytes, mask, blockid; int i, j; int maxindex, indirection; nbytes = read_block_bitmap(0, &bbm); mask = 1; blockid = 0; len = 0; for(i = 0; i < nbytes; ++i) { for(j = 0; j < BYTE; ++j) { if(!(bbm[i] & (mask << j))) free_blocks[len++] = blockid; blockid++; if(len == nblocks) break; } if(len == nblocks) break; } if(len < nblocks) return -1; for(i = 0; i < nblocks; ++i) { maxindex = ext2fd->inode->i_blocks / (2 << ext2fs->sb->s_log_block_size); printf("maxindex = %d\n", maxindex); if(maxindex <= 11) { ext2fd->inode->i_block[maxindex] = free_blocks[i]; ext2fd->inode->i_blocks += ext2fs->block_size / 512; } else { } } maxindex = ext2fd->inode->i_blocks / (2 << ext2fs->sb->s_log_block_size); printf("maxindex = %d\n", maxindex); return nblocks; } int ext2_insert_file(EXT2_FILE *ext2fd) { int index; int i; ext2fd->nblocks = get_block_from_inode(ext2fd->inode, &ext2fd->blocks); // Check for closed files that can be replaced for(i = 0; i < ext2fs->nfiles; i++) { if(ext2fs->open_files[i] == NULL) { ext2fs->open_files[i] = ext2fd; return i; } } index = ext2fs->nfiles; ext2fs->open_files[ext2fs->nfiles++] = ext2fd; if(ext2fs->nfiles == ext2fs->maxfiles) { ext2fs->maxfiles *= 2; ext2fs->open_files = (EXT2_FILE **)safe_realloc(ext2fs->open_files, sizeof(EXT2_FILE *) * ext2fs->maxfiles, ""); } return index; } int ext2_delete_file(int index) { EXT2_FILE *ext2fd; if(index >= ext2fs->nfiles) { error_msg("File cannot be closed, it wasn't opened!"); return -1; } if(!(ext2fd = ext2fs->open_files[index])) { error_msg("File cannot be closed, it wasn't opened!"); return -1; } if(ext2fd->content) free(ext2fd->content); if(ext2fd->inode) free(ext2fd->inode); free(ext2fd); ext2fs->open_files[index] = NULL; return 0; } EXT2_FILE *ext2_get_file(int index) { if(index < 0) return NULL; if(index >= ext2fs->nfiles) return NULL; return ext2fs->open_files[index]; } LLDIRLIST *ext2_get_root() { INODETABLE it; LLDIRLIST *rootdir; ext2_get_inode(&it, 2); rootdir = ext2_read_dir(&it); return rootdir; } LLDIRLIST *ext2_read_dir(INODETABLE *it) { LLDIR *ld; LLDIRLIST *head = NULL; int *blocks; int n, i; unsigned int offset; // Check that the current inode is for a directory if(!(it->i_mode & EXT2_S_IFDIR)) { fprintf(stderr, "Inode found is not a directory!\n"); exit(69); } n = get_block_from_inode(it, &blocks); // Iteratively read / store linked list directory structures offset = 0; ld = (LLDIR *)malloc(sizeof(LLDIR)); for(i = 0; i < n; ++i) { while(offset < ext2fs->block_size) { lseek(ext2fs->fd, blocks[i] * ext2fs->block_size + offset, SEEK_SET); read(ext2fs->fd, ld, sizeof(LLDIR)); lldirlist_insert(&head, ld); offset += ld->rec_len; } offset = 0; } free(ld); return head; } LLDIRLIST *ext2_read_subdir(LLDIRLIST *root, char *subdir, int type, int *file) { LLDIRLIST *ptr; LLDIRLIST *newdir = NULL; INODETABLE it; for(ptr = root; ptr; ptr = ptr->next) { if(memcmp(ptr->ld->name, subdir, ptr->ld->name_len) == 0) { switch(type) { case EXT2_FT_DIR: ext2_get_inode(&it, ptr->ld->inode); newdir = ext2_read_dir(&it); return newdir; case EXT2_FT_REG_FILE: (*file) = ptr->ld->inode; return root; default: error_msg("Invalid filetype!"); return NULL; } } } return newdir; } void ext2_print_lldirlist(LLDIRLIST *lldir) { int i; if(!lldir) return; ext2_print_lldirlist(lldir->next); printf("%03d ", lldir->ld->inode); for(i = 0; i < lldir->ld->name_len; ++i) printf("%c", lldir->ld->name[i]); printf("\n"); } void ext2_free_lldirlist(LLDIRLIST *t) { if(!t) return; ext2_free_lldirlist(t->next); free(t->ld); free(t); } void ext2_get_inode(INODETABLE *it, int inode) { inode--; lseek(ext2fs->fd, ext2fs->bg[0]->bg_inode_table * ext2fs->block_size + (inode * ext2fs->sb->s_inode_size), SEEK_SET); safe_read(ext2fs->fd, it, ext2fs->sb->s_inode_size, "Unable to read inode!"); } void ext2_update_inode(INODETABLE *it, int inode) { inode--; lseek(ext2fs->fd, ext2fs->bg[0]->bg_inode_table * ext2fs->block_size + (inode * ext2fs->sb->s_inode_size), SEEK_SET); if(write(ext2fs->fd, it, ext2fs->sb->s_inode_size) <= 0) error_msg("Failed to write inode!"); } int ext2_read_inode_bitmap(int bgn, BITMAP *ibm) { int nbytes; nbytes = (float)(ext2fs->sb->s_inodes_per_group / BYTE); (*ibm) = (BITMAP)malloc(nbytes); lseek(ext2fs->fd, (ext2fs->bg[bgn]->bg_inode_bitmap) * ext2fs->block_size, SEEK_SET); read(ext2fs->fd, (*ibm), nbytes); return nbytes; } int ext2_get_free_block(int bgn) { BITMAP bbm; int nbytes, blockid, mask, i, j; nbytes = read_block_bitmap(bgn, &bbm); blockid = 0; mask = 1; for(i = 0; i < nbytes; ++i) { for(j = 0; j < BYTE; ++j) { if(!(bbm[i] & (mask << j))) return blockid; blockid++; } } free(bbm); return 0; } static int read_block_bitmap(int bgn, BITMAP *bbm) { int nbytes; nbytes = (float)(ext2fs->sb->s_blocks_per_group / BYTE); (*bbm) = (BITMAP)safe_malloc(nbytes, ""); lseek(ext2fs->fd, ext2fs->bg[bgn]->bg_block_bitmap * ext2fs->block_size, SEEK_SET); safe_read(ext2fs->fd, (*bbm), nbytes, ""); return nbytes; } static int get_block_from_inode(INODETABLE *it, int **blocks) { int i, n, maxindex; int indir_list[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3 }; n = 0; maxindex = it->i_blocks / (2 << ext2fs->sb->s_log_block_size); (*blocks) = (int *)safe_malloc(maxindex * sizeof(int), ""); for(i = 0; i < 15; ++i) { get_blocks(blocks, it->i_block[i], indir_list[i], &n, maxindex); } return n; } static void get_blocks(int **blocks, int block, int indirection, int *n, int max) { unsigned int newblocks[ext2fs->block_size / 4], i; int ln; lseek(ext2fs->fd, ext2fs->block_size * block, SEEK_SET); if(indirection == 0) { ln = (*n); if(ln < max) { (*blocks)[ln++] = block; } (*n) = ln; } else { safe_read(ext2fs->fd, newblocks, ext2fs->block_size, ""); for(i = 0; i < ext2fs->block_size / 4; ++i) { get_blocks(blocks, newblocks[i], indirection - 1, n, max); if((*n) >= max) break; } } } static LLDIRLIST *make_lldirlist_node(LLDIR *ld) { LLDIRLIST *tmp; tmp = (LLDIRLIST *)malloc(sizeof(LLDIRLIST)); tmp->ld = (LLDIR *)malloc(sizeof(LLDIR)); memcpy(tmp->ld, ld, sizeof(LLDIR)); tmp->next = NULL; return tmp; } ; static void lldirlist_insert(LLDIRLIST **head, LLDIR *ld) { LLDIRLIST *new_node = make_lldirlist_node(ld); if((*head)) new_node->next = (*head); (*head) = new_node; }
C
#include<stdio.h> int main(){ int a=1,b=2,c=3,d=4,e=5,f=6,g=7,h=8,i=9,j=10; printf("%d",a); printf("%d",b); printf("%d",c); printf("%d",d); printf("%d",e); printf("%d",f); printf("%d",g); printf("%d",h); printf("%d",i); printf("%d",j); return 0; }
C
#include<stdio.h> #include<string.h> #pragma warning(disable:4996) struct student{ char name[20]; int korean, english, math; double average; }; //ݷ!!! ü ٸ Ÿ int main() { struct student s1; //ü struct student s2 = { "ڳ", 90, 78, 86 }; //ü s1.korean = 100; //ü ʱȭ~ s1.english = 100; s1.math = 100; strcpy(s1.name, ""); s1.average = (double)(s1.korean + s1.english + s1.math) / 3; s2.average = (double)(s2.korean + s2.english + s2.math) / 3; //~ printf("%s : %5.2f\n", s1.name, s1.average); printf("%s : %5.2f\n", s2.name, s2.average); }
C
/* * This file is part of HuDK. * ASM and C open source software development kit for the NEC PC Engine. * Licensed under the MIT License * (c) 2016-2021 MooZ */ #include "tilemap.h" #include <errno.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "../utils/log.h" void tilemap_destroy(tilemap_t *map) { if(map->layer) { for(int i=0; i<map->layer_count; i++) { if(map->layer[i].name) { free(map->layer[i].name); } if(map->layer[i].data) { free(map->layer[i].data); } } free(map->layer); } if(map->name) { free(map->name); } if(map->tileset) { for(int i=0; i<map->tileset_count; i++) { tileset_destroy(map->tileset+i); } free(map->tileset); } memset(map, 0, sizeof(tilemap_t)); } int tilemap_create(tilemap_t *map, const char *name, int width, int height, int tile_width, int tile_height, int tileset_count) { memset(map, 0, sizeof(tilemap_t)); map->name = strdup(name); if(map->name == NULL) { log_error("failed to set tilemap name: %s", strerror(errno)); return 0; } map->tileset = (tileset_t*)malloc(tileset_count * sizeof(tileset_t)); if(map->tileset == NULL) { log_error("failed to allocate tilesets: %s", strerror(errno)); tilemap_destroy(map); return 0; } map->tileset_count = tileset_count; map->width = width; map->height = height; map->tile_width = tile_width; map->tile_height = tile_height; return 1; } int tilemap_add_layer(tilemap_t *map, const char *name) { int next_layer_count = map->layer_count+1; tilemap_layer_t *layers = (tilemap_layer_t*)realloc(map->layer, next_layer_count * sizeof(tilemap_layer_t)); if(layers == NULL) { log_error("failed to add layer %s: %s", name, strerror(errno)); return 0; } layers[map->layer_count].name = strdup(name); layers[map->layer_count].data = (int*)malloc(map->width * map->height * sizeof(int)); if(layers[map->layer_count].data == NULL) { log_error("failed to allocate layer %s data: %s", name, strerror(errno)); return 0; } map->layer = layers; map->layer_count = next_layer_count; return 1; } int tilemap_compress(tilemap_t *map) { int *id, *dict; int *first, *last; int total, max_id; int i; last = (int*)malloc(2 * map->tileset_count * sizeof(int)); if(last == NULL) { log_error("failed to allocate aux buffer."); return 0; } memset(last, 0, map->tileset_count * sizeof(int)); max_id = 0; first = last + map->tileset_count; for(i=0, total=0; i<map->tileset_count; i++) { int n = map->tileset[i].first_gid + map->tileset[i].tile_count; if(n > max_id) { max_id = n; } first[i] = total; total += map->tileset[i].tile_count; } id = (int*)malloc((max_id + total) * sizeof(int)); if(id == NULL) { log_error("failed to allocate id buffer."); free(last); return 0; } dict = id + total; for(i=0; i<max_id; i++) { dict[i] = -1; } int tiles_used = 0; for(i=0; i<map->layer_count; i++) { int y; for(y=0; y<map->height; y++) { int x; for(x=0; x<map->width; x++) { int tile_id = map->layer[i].data[x + (y * map->width)]; int tileset_id; for(tileset_id=0; tileset_id<map->tileset_count; tileset_id++) { tileset_t *tileset = map->tileset + tileset_id; if((tile_id >= tileset->first_gid) && (tile_id < (tileset->first_gid + tileset->tile_count))) { break; } } if(tileset_id >= map->tileset_count) { log_error("invalid tile id %d.", tile_id); continue; } if(dict[tile_id] < 0) { int index = first[tileset_id] + last[tileset_id]; id[index] = tile_id; dict[tile_id] = index; last[tileset_id]++; tiles_used++; } } } } int start = 0; for(i=0; i<map->tileset_count; i++) { int j=0; for(j=first[i]; j<(first[i]+last[i]); j++) { int k = id[j]; dict[k] += start - first[i]; } start += last[i]; } // recreate tileset start = 0; for(i=0; i<map->tileset_count; i++) { int j; tileset_t tileset; tileset_create(&tileset, map->tileset[i].name, start, last[i], map->tileset[i].tile_width, map->tileset[i].tile_height); start += last[i]; int dst_stride = tileset.tile_width * tileset.tile_count; int src_stride = map->tileset[i].tile_width * map->tileset[i].tile_count; for(j=0; j<tileset.tile_count; j++) { int k = id[j+first[i]] - map->tileset[i].first_gid; uint8_t *dst_ptr = tileset.tiles + j * tileset.tile_width; uint8_t *src_ptr = map->tileset[i].tiles + k * map->tileset[i].tile_width; int x, y; for(y=0; y<tileset.tile_height; y++) { for(x=0; x<tileset.tile_width; x++) { dst_ptr[x + (y*dst_stride)] = src_ptr[x + (y*src_stride)]; } } } tileset.palette_count = 0; int *palette_dict = (int*)malloc(2 * map->tileset[i].palette_count * sizeof(int)); int *palette_id = palette_dict + map->tileset[i].palette_count; for(j=0; j<map->tileset[i].palette_count; j++) { palette_dict[j] = -1; } for(j=0; j<tileset.tile_count; j++) { int k = id[j+first[i]] - map->tileset[i].first_gid; int l = map->tileset[i].palette_index[k]; if(palette_dict[l] < 0) { palette_dict[l] = tileset.palette_count; palette_id[tileset.palette_count] = l; tileset.palette_count++; } tileset.palette_index[j] = palette_dict[l]; } tileset.palette = (uint8_t*)malloc(tileset.palette_count*3*16); for(j=0; j<tileset.palette_count; j++) { int dst = j*3*16; int src = palette_id[j]*3*16; memcpy(tileset.palette+dst, map->tileset[i].palette+src, 3*16); } free(palette_dict); tileset_destroy(&map->tileset[i]); memcpy(&map->tileset[i], &tileset, sizeof(tileset_t)); } // recreate tilemap for(i=0; i<map->layer_count; i++) { int y; for(y=0; y<map->height; y++) { int x; for(x=0; x<map->width; x++) { int tile_id = map->layer[i].data[x + (y * map->width)]; map->layer[i].data[x + (y * map->width)] = dict[tile_id]; } } } free(last); free(id); return 1; }
C
/* * week5.2.c * * Created: 22-3-2016 11:25:00 * Author : sander */ #include <avr/io.h> #include "uart0.h" #include "lcd.h" char character; void wait( int ms ) { for (int tms=0; tms<ms; tms++) { _delay_ms( 1 ); // library function (max 30 ms at 8MHz) } } // send/receive uart - dB-meter int main( void ) { char buffer[16]; // declare string buffer DDRB = 0xFF; // set PORTB for output DDRC = 0xFF; init(); // initialize LCD-display usart0_init(); // initialize USART0 usart0_start(); while (1) { wait(50); // every 50 ms (busy waiting) PORTB ^= BIT(7); // toggle bit 7 for testing uart0_receiveString( buffer ); // receive string from uart char tempBuffer[16]; for (int i = 0; i <= 8; i++) { tempBuffer[i] = buffer[(i+1)]; } clear(); display_text(tempBuffer, 8); } }
C
// // sysmem.c // // // Created by Neil Singh on 6/25/17. // // #include <sys/stat.h> #include <sys/types.h> #include <sys/fcntl.h> #include <sys/errno.h> #include <sys/mman.h> extern unsigned int sys_errno(); extern unsigned int sys_brk(void* addr); extern void* sys_sbrk(int offset); extern void* sys_mmap(void* addr, size_t length, int prot, int flags, int fd, off_t offset); extern int sys_munmap(void* addr, size_t length); extern int sys_msync(void* addr, size_t length, int flags); unsigned int brk(void* b) { int ret = sys_brk(b); if (ret < 0) { errno = -ret; return -1; } return ret; } caddr_t sbrk(int incr) { void* ret = sys_sbrk(incr); if ((int)ret == -1) { errno = ENOMEM; return NULL; } return ret; } void* mmap(void* addr, size_t length, int prot, int flags, int fd, off_t offset) { unsigned int ret = (unsigned int)sys_mmap(addr, length, prot, flags, fd, offset); if (ret > (unsigned int)(-__ELASTERROR)) { errno = -ret; return (void*)-1; } return (void*)ret; } int munmap(void* addr, size_t length) { int ret = sys_munmap(addr, length); if (ret < 0) { errno = -ret; return -1; } return ret; } int msync(void *addr, size_t length, int flags) { int ret = sys_msync(addr, length, flags); if (ret < 0) { errno = -ret; return -1; } return ret; }
C
/* Atividade 28 - Binrio */ #include <stdio.h> #include <locale.h> void inverter(unsigned int n) { if(n < 10) printf("%u", n); else { printf("%u", n % 10); inverter(n / 10); } } int main() { setlocale(LC_ALL, "Portuguese"); unsigned int n; printf("\n Digite n: "); scanf("%u", &n); printf("\n Dgitos invertidos: "); inverter(n); return 0; }
C
/* * sensereversal.c * * Created on: Feb 17, 2015 * Author: harshit */ #include <stdio.h> #include <stdlib.h> #include <assert.h> #include "sensereversal.h" void SenseReversalOpenMP_BarrierInit(long num_threads, SenseReversalOpenMP_Barrier* barrier){ int i; barrier->count = num_threads; barrier->mysense = (int*)malloc(sizeof(int)*num_threads); barrier->max_count = num_threads; barrier->global_sense = FALSE; for(i=0;i<num_threads;i++){ barrier->mysense[i] = TRUE; } } void SenseReversalOpenMP_Barrier_Wait(SenseReversalOpenMP_Barrier* barrier,long threadid){ assert(threadid < barrier->max_count); #pragma omp critical { barrier->count--; } if(barrier->count==0){ barrier->count = barrier->max_count; barrier->global_sense = barrier->mysense[threadid]; } else{ //printf("entering while 1 by %d\n", threadid); while(barrier->global_sense != barrier->mysense[threadid]); //printf("leaving while 1 by %d\n", threadid); } if(barrier->mysense[threadid]==1){ barrier->mysense[threadid] = 0; } else{ barrier->mysense[threadid] =1; } }
C
// all the lines that start with a hash are treated by the preprocessor (cpp) // to include header files such as this ones, macros extension or conditional rendering #include <unistd.h> #include <stdio.h> #include <string.h> int main(void) { char c[19]; sprintf(c, "Hello World!\n"); write(1, c, strlen(c)); return 0; }
C
#ifndef PUBLIC_FUNCTION_H #define PUBLIC_FUNCTION_H #include <QString> #include <QDebug> inline void RecoverData(unsigned char* psrc, unsigned char* pdst, int len) { unsigned char i; for(i = 0; i < len; i ++) { pdst[len - i - 1] = psrc[i]; } } inline void RecoverSelfData(unsigned char* pdat, int len) { unsigned char i, j, tmp; for(i = 0; i < len/2; i ++) { j = len - i - 1; tmp = pdat[i]; pdat[i] = pdat[j]; pdat[j] = tmp; } } inline void BytesSetZero(unsigned char* pbuf, int len) { for(int i = 0; i < len; i ++) { pbuf[i] = 0; } } // len==2,两个字节调换, len==4,前后16bit调换 inline void SwitchHighLow(unsigned char* pdat, int len) { unsigned char i,j; unsigned char tmp; for(i = 0; i < len; i ++) { j = len + i; tmp = pdat[i]; pdat[i] = pdat[j]; pdat[j] = tmp; } } //将16进制转换成Ascii码 inline void MakeCodeToAsii(unsigned char * psrc, unsigned char * pdst, int len) { int i; if(len == 0) return; for(i = len - 1; i>= 0; i --) { unsigned char val = psrc[i]; unsigned char tmp; //处理高4位 tmp = val >> 4; if(tmp <= 9) tmp = tmp + '0'; else tmp = tmp - 0x0A + 'A'; pdst[2 * i] = tmp; //处理低4位 tmp = val & 0x0F; if(tmp <= 9) tmp = tmp + '0'; else tmp = tmp - 0x0A + 'A'; pdst[2 * i + 1] = tmp; } } //将Ascii码转换成16进制 inline void MakeAsiiToCode(unsigned char * psrc, unsigned char * pdst, int len) { int i; if(len == 0) return; for(i = 0; i < len; i ++) { unsigned char val; unsigned char tmp; //处理高4位 tmp = psrc[2 * i]; if(tmp >= 'A') tmp = tmp - 'A' + 0x0A; else tmp = tmp - '0'; val = tmp << 4; //处理低4位 tmp = psrc[2 * i + 1]; if(tmp >= 'A') tmp = tmp - 'A' + 0x0A; else tmp = tmp - '0'; val |= (tmp & 0x0F); pdst[i] = val; } } inline void ShowBufferHex(QString msg, unsigned char * pbuf, int len) { QString strBuf; for(int i=0; i<len; i++) { QString s; s.sprintf("0x%02x ", pbuf[i]); strBuf += s; } msg += strBuf; qDebug()<< msg; } #endif // PUBLIC_FUNCTION_H
C
#include <stdio.h> /** * A função piso_log_2 recebe um inteiro N > 0 e devolve piso(log_2 N), ou seja, devolve * o único inteiro i tal que 2^i <= N < 2^(i+1). */ int piso_log_2(int N) { int i, n; i = 0; n = N; while (n > 1) { // n == N / 2^i n = n / 2; i++; } return i; } /** * */ int pisoLog2R(int N, int i) { if (N > 1) { int n = N / 2; return pisoLog2R(n, i+1); } else { return i; } } /** * A função piso_log_2 recebe um inteiro N > 0 e devolve piso(log_2 N), ou seja, devolve * o único inteiro i tal que 2^i <= N < 2^(i+1). * Algoritmo recursivo. */ int piso_log_2_R(int N) { return pisoLog2R(N, 0); } int main() { printf("\n"); int N; printf("Digite N: "); scanf("%d", &N); printf("piso(log_2 %d) = %d\n", N, piso_log_2(N)); printf("piso(log_2 %d) R = %d\n", N, piso_log_2_R(N)); }
C
#include <stdio.h> #include <stdlib.h> void min_swaps (int arr[], int n) { int min = 0; int max = 0; int l = 0; int r = 0; int i = 0; min = arr[0]; max = arr[0]; for (i = 1; i < n; i++) { if (arr[i] <= min) { min = arr[i]; r = i; } if (arr[i] > max) { max = arr[i]; l = i; } } if (l > r) { printf ("Minimum number of swaps to move min and max to corners is %d\n", (l + (n - r - 2))); } else { printf ("Minimum number of swaps to move min and max to corners is %d\n", (l + (n - r - 1))); } } void print_array (int arr[], int n) { int i = 0; for (i = 0; i < n; i++) { printf ("%d ", arr[i]); } printf ("\n"); } int main () { int arr[] = {3, 1, 5, 3, 5, 5, 2}; int n = 0; n = sizeof (arr) / sizeof (int); printf ("Array: "); print_array (arr, n); min_swaps (arr, n); return 0; }
C
/* * bmp.c */ #include "FImage.h" #include <stdio.h> long FImageLoad_BMP(self,filename) image self; char *filename; { char buf[1024]; if (filename == 0 || strlen(filename) == 0 || strequal("-",filename) || strequal("stdin",filename)) sprintf(buf,"bmptopnm"); else sprintf(buf,"bmptopnm %s",filename); return FImageLoadPipe_PNM(self,buf); } long FImageSave_BMP(self,filename,comment) image self; char *filename; char *comment; { char buf[1024]; if (filename == 0 || strlen(filename) == 0 || strequal(filename,"-") || strequal(filename,"stdout")) sprintf(buf,"ppmtobmp"); else sprintf(buf,"ppmtobmp > %s",filename); return FImageSavePipe_PNM(self,buf); } long FImageMagic_BMP(fp) FILE *fp; { char magic_char = getc(fp); ungetc(magic_char,fp); return (magic_char == 'B' || magic_char == 'M'); }
C
#include <stdio.h> #include <stdlib.h> int power(int base, int exp){ int res = base; while (exp > 1){ res *= base; exp--; } return res; } int main(){ int N, D, i, j, res, min, max; scanf("%d %d", &N, &D); int T[N][2]; for (i = 0; i < N; i++) for (j = 0; j < 2; j++) scanf("%d", &T[i][j]); for (i = 0; i < (N - 1); i++){ for (j = i + 1; j < N; j++){ res = power(abs(T[j][0] - T[i][0]), D) + power(abs(T[j][1] - T[i][1]), D); if (i == 0 && j == 1){ min = max = res; } else{ if (res < min) min = res; if (res > max) max = res; } } } printf("%d %d\n", min, max); return 0; }
C
/* ============================================================================ Name : ps_hs_b_omp.c Author : Adrian Kempf Version : Copyright : Description : Prefix-sums with blocked Hillis-Steele algorithm. Did not expect all processors to be free --> block number could be below 40. ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <omp.h> #include <math.h> int main(int argc, char **argv) { if((argc < 2) || (strcmp("-help", *(argv + 1)) == 0)) { (void) fprintf(stderr,"Usage: ps_hs_omp -help | {integer }*\n"); return EXIT_FAILURE; } int n = atoi(*(argv+1)); int* prefix_sums = (int*)malloc(n*sizeof(int)); int* prefix_sums_work = (int*)malloc(n*sizeof(int)); double time1, time2; FILE* input_file = fopen ("test", "r"); int j = 0; int m = 0; fscanf (input_file, "%i", &j); while (!feof (input_file)) { if(m == n) { break; } prefix_sums[m] = j; prefix_sums_work[m] = j; fscanf (input_file, "%i", &j); m++; } fclose (input_file); (void) fprintf(stdout, "max_threads: \t%i\n", omp_get_max_threads()); time1 = omp_get_wtime(); fprintf(stdout, "%d | %d | %d |\n", n, omp_get_max_threads(), n/omp_get_max_threads()); int as = (int) ceil(((double)n/(double)omp_get_max_threads())); int* b_array = NULL; fprintf(stdout, "%d\n", as); // #pragma omp parallel for for(int b = 0; b < n; b += as) { int* temp = NULL; int length = 0; int* prefix_sums_temp = NULL; if((b + as) > n) // BUG? XXX { length = (n-b); prefix_sums_temp = (int*)malloc((n-b)*sizeof(int)); fprintf(stdout, "last%d\n", b); } else { length = as; fprintf(stdout, "%d|%d\n", b, as); prefix_sums_temp = (int*)malloc(as*sizeof(int)); } int* partial_ps_sums = (prefix_sums + b); int k_counter = 0; for(int k = 1; k < length; k <<= 1) { k_counter++; // #pragma omp parallel for //try with and without this for(int i = 0; i < k; i++) { prefix_sums_temp[i] = partial_ps_sums[i]; } // #pragma omp parallel for //try with and without this for(int i = k; i < length; i++) { prefix_sums_temp[i] = partial_ps_sums[i-k] + partial_ps_sums[i]; } temp = partial_ps_sums; partial_ps_sums = prefix_sums_temp; prefix_sums_temp = temp; if(((k_counter % 2) == 1) && ((k<<1) >= length)) { //not optimal, better with pointer array //could also be parallized --> communication !!?? for(int i = 0; i < length; i++) { prefix_sums_temp[i] = partial_ps_sums[i]; } } for(int i = 0; i < length; i++) { (void) fprintf(stdout, "%i ", partial_ps_sums[i]); } fprintf(stdout, "\n"); } // free(prefix_sums_temp); } //just by one single processor int size = 0; for(int b = as; b < n; b += as) { size++; b_array = realloc(b_array, size*sizeof(int)); if(size == 1) { b_array[size-1] = prefix_sums[b-1]; } else { b_array[size-1] = prefix_sums[b-1] + b_array[size-2]; } } int add = 0; /* Calculate final prefix sums as combination of single blocks */ //parallized TODO for(int b = as; b < n; b += as) { int length = 0; if((b + as) > n) // BUG? XXX { length = (n-b); } else { length = as; } for(int i = 0; i < length; i++) { prefix_sums[b+i] += b_array[add]; } add++; } time2 = omp_get_wtime(); (void) fprintf(stdout, "time: \t\t%f\n", (time2-time1)); for(int i = 0; i < n; i++) { (void) fprintf(stdout, "%i ", prefix_sums[i]); } (void) fprintf(stdout,"\n"); return EXIT_SUCCESS; }
C
 #define arm2index(x) x-(regexEngine_max_bit_length-regexEngine_bit_start) #define shift_to_bit32(x) ((31-x)*sizeof(char)) #define shift_by_bits32(x) (x*sizeof(char)) int32_t string_to_bin(int len, char * s) { int32_t x = 0; for(int i = 0; i < len; i++) x = (x << 1) | (s[i] == '1' ? 1 : 0); return x; } uint64_t string_to_bin64(int len, char * s) { uint64_t x = 0; for(int i = 0; i < len; i++) x = (x << 1) | (s[i] == '1' ? 1 : 0); return x; } int32_t binary(int start, int end, char * s) { int32_t x = 0; for(int i = end; i <= start; i++) x = (x << 1) | (s[arm2index(i)] == '1' ? 1 : 0); return x; } #define SIGN_EXTEND(to, from, value) ( \ ( \ ( \ (value) << (to - from) \ ) \ >> (to - from) \ ) \ ) #define ZERO_EXTEND(to, from, value) ( \ ( \ (unsigned)( \ (value) << (to - from) \ ) \ >> (to - from) \ ) \ ) void extract_h(char * to, char * from, int locationstart,int locationend) { int ii = 0; for (int i = locationend; i <= locationstart; i++) { to[ii] = from[arm2index(i)]; ii++; } to[ii] = 0; } #define extract(to,from,locationstart,locationend) char to[(locationstart-locationend)+2]; extract_h(to,from,locationstart,locationend)
C
// // main.c // rc4 // // Created by Grace Akpan on 9/8/16. // Copyright © 2016 Grace Akpan. All rights reserved. // #include <stdio.h> #include <stdlib.h> #include <string.h> #define SIZE 256 typedef unsigned char uns8; typedef unsigned short uns16; static uns8 state[SIZE]; int i; uns8 j; // function declaration uns8* encryptMessage(uns8 key[], uns8 msg[]); void rc4_init(uns8 key[]); uns8* charCopy(uns8* szString, uns8 c); uns8 rc4_setup(); int main (void){ uns8 key[] = "zxcvb"; uns8 msg[] = "This class is easier than I thought."; uns8* temp = (uns8*)malloc(100*sizeof(uns8)); uns8* encr = (uns8*)malloc(100*sizeof(uns8)); uns8* decr = (uns8*)malloc(100*sizeof(uns8)); temp = encryptMessage(key, msg); strcat((char*)encr, (const char*)temp); printf("Encrypted value: %s \n\n", encr); // reset temp temp = (uns8*)malloc(100*sizeof(uns8)); temp = encryptMessage(key, encr); strcat((char*)decr, (const char*)temp); printf("Decrypted value: %s \n\n", decr); return 0; } /** * used to encrypt/decrypt a plaintext message */ uns8* encryptMessage(uns8 key[], uns8 msg[]){ int in = 0; uns8* res = (uns8*)malloc(100*sizeof(uns8)); uns8* final = (uns8*)malloc(100*sizeof(uns8)); rc4_init(key); while(in < strlen((const char*)msg)){ char m = msg[in]; // XOR each 8 bits of plaintext with the 8 bits generate in order // to create a cyphertext uns8 str = (uns8)m^rc4_setup(); res = charCopy(res, str); // concatenate encrypted character an array of strings strcat((char*)final,(const char*)res); in++; } return final; } /** * perform initial permutation of the state array */ void rc4_init(uns8 key[]){ uns8 t; uns8 keyArray[SIZE]; // initialize the state array for(i = 0; i < SIZE; i++) state[i] = i; // initialize key array to match the length of state array for(i = 0; i < SIZE; i++) keyArray[i] = key[i%sizeof(key, SIZE)]; // perform permutation for(i = 0, j = 0; i < SIZE; i++){ j = (j + state[i] + keyArray[i]) % SIZE; // perform swap indexes of state array to increase randomness t = state[i]; state[i] = state[j]; state[j] = t; } } /** * generate an 8 bit cyphertext for each 8 bit of plaintext */ uns8 rc4_setup(){ uns8 t; // generate 8 bits that are XOR'd with each 8 bits of plaintext to // produce a cyphertext i = (i+1) % SIZE; j = (j+state[i]) % SIZE; // swap state array index to increase randomness t = state[i]; state[i] = state[j]; state[j] = t; return state[(state[i]+state[j])%SIZE]; } /** * copy encrypted character to a temporary array */ uns8* charCopy(uns8* szString, uns8 c){ asprintf((char**)&szString, "%c", c); return szString; }
C
#define FUSE_USE_VERSION 31 #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <fuse.h> #include <errno.h> #include <string.h> #include <pthread.h> #include <sys/types.h> #include <linux/limits.h> static char wd[PATH_MAX]; static int sleepy_open(const char *path, struct fuse_file_info *fi) { return 0; } static void *nested_fsync(void *) { int fd; strcat(wd, "/mount/b"); fd = open(wd, O_RDWR); fsync(fd); return NULL; } static int sleepy_write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { int fd; pthread_t t; pthread_create(&t, NULL, nested_fsync, NULL); return size; } static int sleepy_flush(const char *path, struct fuse_file_info *fi) { printf("eating a flush(%s)\n", path); while (1) sleep(100); return 0; } static int sleepy_opendir(const char *path, struct fuse_file_info *fi) { printf("opendir for %s\n", path); return 0; } static int sleepy_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi, enum fuse_readdir_flags) { if (strcmp(path, "/") != 0) return -ENOENT; if (filler(buf, ".", NULL, 0, FUSE_FILL_DIR_PLUS)) return -ENOMEM; if (filler(buf, "..", NULL, 0, FUSE_FILL_DIR_PLUS)) return -ENOMEM; if (filler(buf, "a", NULL, 0, FUSE_FILL_DIR_PLUS)) return -ENOMEM; if (filler(buf, "b", NULL, 0, FUSE_FILL_DIR_PLUS)) return -ENOMEM; return 0; } static int sleepy_getattr(const char *path, struct stat *sb, struct fuse_file_info *fi) { struct timespec now; if (clock_gettime(CLOCK_REALTIME, &now) < 0) return -EINVAL; sb->st_uid = sb->st_gid = 0; sb->st_atim = sb->st_mtim = sb->st_ctim = now; sb->st_size = 0; if (strcmp(path, "/") == 0) { sb->st_mode = S_IFDIR | 00755; sb->st_nlink = 2; } else if (strcmp(path, "/a") == 0 || strcmp(path, "/b") == 0) { sb->st_nlink = 1; sb->st_mode = S_IFREG | 00755; } else { return -ENOENT; } return 0; } static void *sleepy_init(struct fuse_conn_info *info, struct fuse_config *config) { config->intr = 0; return NULL; } const struct fuse_operations sleepy_fuse = { .open = sleepy_open, .opendir = sleepy_opendir, .readdir = sleepy_readdir, .getattr = sleepy_getattr, .write = sleepy_write, .flush = sleepy_flush, .init = sleepy_init, }; int main(int argc, char *argv[]) { getcwd(wd, sizeof(wd)); if (fuse_main(argc, argv, &sleepy_fuse, NULL)) { printf("fuse_main failed\n"); exit(1); } printf("fuse main exited\n"); exit(1); }
C
// 用一组连续地址的存储单元实现队列 // 会出现插入一个新元素,造成数组越界,而破坏程序 // 且删除的元素,内存有没有使用,基于此 // 将队头和队尾连在一起,形成循环队列 // 循环队列使用一位数组实现 // 必须为它设置一个最大队列长度 // 其中如何判断队列是否为满和空的状态 // 1. 增加一个标志位 // 2. 约定一个在队头的上一个的存储单元,即队尾的下一个存储单元不使用 #include <stdlib.h> #include <string.h> #define QUEUE_MAX_SIZE 100 typedef struct Element { int data; }Element; typedef struct Queue { Element * base; int front; int rear; }Queue; // 函数返回值 typedef enum Status { OK, UNKNOWN_ERR, WRONG_INPUT, ILLEGAL_OPT, OVER_FLOW, } Status; // bool 类型 typedef enum bool { false, true, } bool; Status init_queue(Queue * q) { if (!q) { return WRONG_INPUT; } q->base = (Element *)malloc(sizeof(Element) * QUEUE_MAX_SIZE); if (!q->base){ return OVER_FLOW; } memset(q->base, 0, sizeof(Element) * QUEUE_MAX_SIZE); q->front = q->rear = 0; return OK; } Status destroy_queue(Queue * q) { if (!q) { return WRONG_INPUT; } free(q->base); q->front = q->rear = 0; return OK; } Status clear_queue(Queue * q) { if (!q) { return WRONG_INPUT; } if (!q->base) { return WRONG_INPUT; } memset(q->base, 0, sizeof(Element) * QUEUE_MAX_SIZE); q->front = q->rear = 0; return OK; } bool queue_empty(Queue * q) { if (!q) { return WRONG_INPUT; } if ((q->rear - q->front) != 0) { return false; } return true; } int queue_length(Queue * q) { if (!q) { return WRONG_INPUT; } return (q->rear - q->front + QUEUE_MAX_SIZE) % QUEUE_MAX_SIZE; } Status queue_head(Queue * q, Element * e) { if (!q) { return WRONG_INPUT; } if (!q->base) { return WRONG_INPUT; } if (queue_empty(q)) { return WRONG_INPUT; } *e = q->base[q->front % QUEUE_MAX_SIZE]; return OK; } Status queue_end(Queue * q, Element * e) { if (!q) { return WRONG_INPUT; } if (!q->base) { return WRONG_INPUT; } if (queue_empty(q)) { return WRONG_INPUT; } *e = q->base[q->rear - 1 % QUEUE_MAX_SIZE]; return OK; } Status enqueue(Queue * q, Element e) { if (!q) { return WRONG_INPUT; } if (!q->base) { return WRONG_INPUT; } // 队列已满 if ((q->rear + 1) % QUEUE_MAX_SIZE == q->front){ return ILLEGAL_OPT; } q->base[q->rear] = e; q->rear = (q->rear + 1) % QUEUE_MAX_SIZE; return OK; } Status dequeue(Queue * q, Element * e) { if (!q) { return WRONG_INPUT; } if (!q->base) { return WRONG_INPUT; } // 队列已空 if (queue_empty(q)) { return WRONG_INPUT; } *e = q->base[q->front]; q->front = (q->front + 1) % QUEUE_MAX_SIZE; return OK; } typedef int (*Visit)(Element * e); Status queue_traverse(Queue * q, Visit v) { if (!q) { return WRONG_INPUT; } if (!q->base) { return WRONG_INPUT; } for (int i = 0; i < queue_length(q); ++i) { v(&q->base[(q->front +i) % QUEUE_MAX_SIZE]); } return OK; } #define TEST_QUEUE #include "test_queue.h"
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <pthread.h> #include <poll.h> #include <sys/ioctl.h> #include "Gpio_func.h" int main () { int device_one; int arg[2]; long long retval; // Set multiplexer pins mux_gpio_set(77, 0); mux_gpio_set(34, 0); mux_gpio_set(36, 1); // Open the module device_one = open("/dev/HCSR_1", O_RDWR); arg[0] = 6; arg[1] = 13; ioctl(device_one, 0, arg); arg[0] = 0; arg[1] = 5; printf("Setting sensor to ONE_SHOT mode.\n"); ioctl(device_one, 1, arg); printf("Making a measurement.\n"); write(device_one, arg, sizeof(int)*2); printf("Sleeping for 4 seconds."); sleep(4); printf("Making a second measurement.\n"); write(device_one, arg, sizeof(int)*2); sleep(4); printf("Making a third measurement.\n"); write(device_one, arg, sizeof(int)*2); sleep(4); printf("Making a fourth measurement.\n"); write(device_one, arg, sizeof(int)*2); sleep(4); printf("Making a fifth measurement.\n"); write(device_one, arg, sizeof(int)*2); sleep(4); printf("Making a sixth measurement.\n"); printf("This is to test the limit of the buffer.\n"); write(device_one, arg, sizeof(int)*2); printf("Reading the first measurement in the queue. (Originally second)\n"); printf("This will also trigger a measurement reading.\n"); read(device_one, &retval, sizeof(long long)); printf("The read value is %llu", retval); printf("Writing with non-zero first argument. This will reset the buffer and trigger a measurement.\n"); arg[0] = 1; arg[1] = 5; write(device_one, arg, sizeof(int)*2); printf("Reading the recent measurement.\n"); read(device_one, &retval, sizeof(long long)); printf("The read value is %llu\n", retval); arg[0] = 1; arg[1] = 5; write(device_one, arg, sizeof(int)*2); arg[0] = 1; arg[1] = 10; printf("Setting sensor to PERIODIC_SAMPLING mode. Frequency: %d\n", arg[1]); ioctl(device_one, 1, arg); arg[0] = 1; arg[1] = 10; printf("Starting sampling.\n"); write(device_one, arg, sizeof(int)*2); printf("Reading a measurement. This will block till there is a reading.\n"); read(device_one, &retval, sizeof(long long)); printf("The read value is %llu\n", retval); arg[0] = 0; arg[1] = 10; printf("Stopping the sampling.\n"); write(device_one, arg, sizeof(int)*2); close(device_one); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "teste.h" #define TAMANHO 5 int main(){ Filme f, *a=&f; char valor[20]; a->opcao = 0; a->inicio = 0; a->fim = 0; a->vazia = 1; while(a->opcao != 4){ menu(a); getchar(); switch(a->opcao){ case 1: printf("Digite a string: "); fgets(valor,20,stdin); adicionar(a,valor); fflush(stdin); break; case 2: strcpy(valor,retirar()); printf("Retirada a string %s da fila\n", valor); break; case 3: imprimir(a); case 4: break; default: printf("Opcao invalida!\n"); } } }
C
#include <stdio_ext.h>//LINUX //#include <stdio.h>//WINDOWS #include <stdlib.h> #include <string.h> #include "arrayEmployees.h" #include "utn.h" int main() { Employee employee[CANT_EMPLEADOS]; int indiceBuscado; int salirPrograma=FALSE; int opcion; int opcionCase2; int opcionCase4; int i; int idEmployee; int indexEmployee; int cantEmpleadosSuperaProm=0; float promSalarioTotal; float auxSalarioProm; float salarioTotal; float auxSalarioTotal; if(initEmployees(employee, CANT_EMPLEADOS)==0) { printf("Array de empleados inicializados\n\n"); } else { printf("Error en inicializacion del array\n"); } do{ opcion=menuOpcion(); switch(opcion) { case 1: indiceBuscado=findEmptyIndex(employee, CANT_EMPLEADOS); if(indiceBuscado!=-1) { if(addEmployee(employee, indiceBuscado, CANT_EMPLEADOS, employee->name, employee->lastName, employee->sector, employee->salary) == 0) { printf("\nDatos del Empleado cargados correctamente en el indice %d\n\n", indiceBuscado); } else { printf("Error de carga\n\n"); } } break; case 2: //system("cls");//WINDOWS system("clear");//LINUX if(utn_getInt(&idEmployee, 3, 1, CANT_EMPLEADOS, "\n**MODIFICACION DE DATOS**\n\nIngrese el ID: ", "No existe el numero ingresado")==0) { indexEmployee = findEmployeeById(employee, idEmployee, CANT_EMPLEADOS); if(indexEmployee == -1) { printf("No se encontro el ID\n"); } else { printf("\n\nID\tNOMBRE\t\tAPELLIDO\tSECTOR\tSALARIO\t\tINDEX\n"); printEmployees(employee,indexEmployee,CANT_EMPLEADOS); printf("\nOPCIONES DE MODIFICACION: \n\n\t1. Nombre \n\t2. Apellido \n\t3. Sector \n\t4. Salario\n"); if(utn_getInt(&opcionCase2, 3, 1, 4, "\n\tIngrese una opcion: ", "\n\tError")==0 && editEmployeeData(employee, indexEmployee, CANT_EMPLEADOS, opcionCase2)==0) { printf("\n\tModificacion exitosa\n"); } else { printf("\n\tError en la modificacion\n"); } } } break; case 3: if(utn_getInt(&idEmployee, 3, 1, CANT_EMPLEADOS, "\n**BORRAR DATOS DE EMPLEADO**\n\nIngrese el ID: ", "No existe el numero ingresado")==0 && removeEmployee(employee, idEmployee, CANT_EMPLEADOS)==0) { printf("Baja exitosa\n\n"); } else { printf("Error en la baja del empleado\n\n"); } break; case 4: //system("cls");//WINDOWS system("clear");//LINUX printf("**DATOS DE LOS EMPLEADOS**\n\n"); printf("INFORME POR:\n\n"); printf("1. Lista en orden alfabetico\n2. Total / promedio de salarios y Cant de empleados que superan el promedio"); if(utn_getInt(&opcionCase4, 3, 1, 2, "\n\nIngrese la opcion: ", "No existe la opcion ingresada")==0) { switch(opcionCase4) { case 1: if(sortEmployees(employee, CANT_EMPLEADOS, 0)==0) { printf("\n\nID\tNOMBRE\t\tAPELLIDO\tSECTOR\tSALARIO\t\tINDEX\n"); for(i=0;i<CANT_EMPLEADOS;i++) { if(employee[i].isEmpty==FALSE) { printEmployees(employee,i,CANT_EMPLEADOS); } } } else { printf("\n\nNO HAY DATOS CARGADOS"); } break; case 2: auxSalarioTotal = getTotalSalary(employee, CANT_EMPLEADOS); if(auxSalarioTotal == -1) { printf("\nNO HAY SALARIOS"); } else { salarioTotal = auxSalarioTotal; printf("\nSALARIO TOTAL: $%.2f\n", salarioTotal); } auxSalarioProm = getAverageSalary(employee, CANT_EMPLEADOS); if(auxSalarioProm == -1) { printf("\nNO HAY PROMEDIO\n"); } else { promSalarioTotal = auxSalarioProm; printf("PROMEDIO DEL SALARIO TOTAL: $%.2f\n", promSalarioTotal); } for(i=0;i < CANT_EMPLEADOS; i++) { if(employee[i].salary > promSalarioTotal && employee[i].isEmpty == FALSE) { cantEmpleadosSuperaProm++; } } printf("CANTIDAD DE EMPLEADOS QUE SUPERAN EL PROMEDIO DEL SALARIO: %d\n", cantEmpleadosSuperaProm); break; } } break; case 9: salirPrograma = TRUE; break; default: printf("\nNO EXISTE LA OPCION, Intente nuevamente\n"); } printf("\n"); system("pause"); system("clear");//LINUX //system("cls");//WINDOWS }while(salirPrograma==FALSE); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_printf_conv_03.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jmartini <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/03/23 16:05:50 by jmartini #+# #+# */ /* Updated: 2021/03/23 16:05:52 by jmartini ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" void ft_pf_conv_x(t_struct *fl, va_list args) { int len; int nlen; unsigned long int n; n = va_arg(args, unsigned int); nlen = ft_pf_nbrlen_hex(n); len = nlen; if (fl->zero && fl->prc < 0 && fl->width < 0) fl->prc = fl->zero; if (fl->zero > fl->width) fl->width = fl->zero; if (!ft_pf_exist_write(n, len, fl)) return ; fl->prc -= nlen; if (fl->prc > 0) len = fl->prc + nlen; if (!fl->pad) ft_pf_width_write(fl, len); ft_pf_precision_write(fl); ft_pf_putnbr_hex(n); fl->cnt += nlen; if (fl->pad) ft_pf_width_write(fl, len); } void ft_pf_conv_upx(t_struct *fl, va_list args) { int len; int nlen; unsigned long int n; n = va_arg(args, unsigned int); nlen = ft_pf_nbrlen_hex(n); len = nlen; if (fl->zero && fl->prc < 0 && fl->width < 0) fl->prc = fl->zero; if (fl->zero > fl->width) fl->width = fl->zero; if (!ft_pf_exist_write(n, len, fl)) return ; fl->prc -= nlen; if (fl->prc > 0) len = fl->prc + nlen; if (!fl->pad) ft_pf_width_write(fl, len); ft_pf_precision_write(fl); ft_pf_putnbr_hex_up(n); fl->cnt += nlen; if (fl->pad) ft_pf_width_write(fl, len); } void ft_pf_conv_n(t_struct *fl, va_list args) { int *n; n = va_arg(args, int *); *n = fl->cnt; }
C
#include "threading.h" #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <time.h> // Optional: use these functions to add debug or error prints to your application #define DEBUG_LOG(msg,...) //#define DEBUG_LOG(msg,...) printf("threading: " msg "\n" , ##__VA_ARGS__) #define ERROR_LOG(msg,...) printf("threading ERROR: " msg "\n" , ##__VA_ARGS__) #define CONVERT_MS_TO_US 1000U void* threadfunc(void* thread_param) { bool status = true; struct thread_data *thread_func_args = (struct thread_data *)thread_param; if ( 0 != usleep(thread_func_args->wait_to_obtain_ms * CONVERT_MS_TO_US)) { status = false; } if ( 0 != pthread_mutex_lock(thread_func_args->mutex)) { status = false; } if ( 0 != usleep(thread_func_args->wait_to_release_ms * CONVERT_MS_TO_US)) { status = false; } if ( 0 != pthread_mutex_unlock(thread_func_args->mutex)) { status = false; } thread_func_args->thread_complete_success = status; // TODO: wait, obtain mutex, wait, release mutex as described by thread_data structure // hint: use a cast like the one below to obtain thread arguments from your parameter //struct thread_data* thread_func_args = (struct thread_data *) thread_param; return thread_param; } bool start_thread_obtaining_mutex(pthread_t *thread, pthread_mutex_t *mutex,int wait_to_obtain_ms, int wait_to_release_ms) { /** * TODO: allocate memory for thread_data, setup mutex and wait arguments, pass thread_data to created thread * using threadfunc() as entry point. * * return true if successful. * * See implementation details in threading.h file comment block */ struct thread_data *thread_param = malloc(sizeof(struct thread_data)); int status; thread_param->wait_to_obtain_ms = wait_to_obtain_ms; thread_param->wait_to_release_ms = wait_to_release_ms; thread_param->mutex = mutex; thread_param->thread_complete_success = false; // Thread on complettion will set this to true. status = pthread_create(thread, NULL, &threadfunc, (void *)thread_param); if (status != 0) { return false; } return true; }
C
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int makethread(void *(*fn)(void *), void *arg) { int err; pthread_t tid; pthread_attr_t attr; err = pthread_attr_init(&attr); if (err != 0) { return err; } err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); if (err == 0) { err = pthread_create(&tid, &attr, fn, arg); } pthread_attr_destroy(&attr); return err; } void *hello(void *who) { char *w = (char *)who; printf("hello %s\n", w); return NULL; } int main() { char w[512]; strcpy(w, "Drav"); int err = makethread(hello, (void *)w); printf("err = %d\n", err); return 0; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_3__ TYPE_1__ ; /* Type definitions */ struct TYPE_3__ {char* name; unsigned char size; char* spec_proc; char* spec_ea; char* ea_allowed; char* cpus; unsigned char* cycles; int op_mask; int op_match; int /*<<< orphan*/ * cpu_mode; } ; typedef TYPE_1__ opcode_struct ; /* Variables and functions */ int EA_ALLOWED_LENGTH ; int /*<<< orphan*/ ID_INPUT_SEPARATOR ; int /*<<< orphan*/ ID_TABLE_START ; int MAX_LINE_LENGTH ; int MAX_NAME_LENGTH ; int MAX_SPEC_EA_LENGTH ; int MAX_SPEC_PROC_LENGTH ; int NUM_CPUS ; char UNSPECIFIED_CH ; int /*<<< orphan*/ check_atoi (char*,int*) ; int /*<<< orphan*/ check_strsncpy (char*,char*,int) ; int /*<<< orphan*/ error_exit (char*) ; scalar_t__ fgetline (char*,int,int /*<<< orphan*/ ) ; int /*<<< orphan*/ g_input_file ; TYPE_1__* g_opcode_input_table ; int /*<<< orphan*/ skip_spaces (char*) ; scalar_t__ strcmp (char*,int /*<<< orphan*/ ) ; scalar_t__ strlen (char*) ; void populate_table(void) { char* ptr; char bitpattern[17]; opcode_struct* op; char buff[MAX_LINE_LENGTH]; int i; int temp; buff[0] = 0; /* Find the start of the table */ while(strcmp(buff, ID_TABLE_START) != 0) if(fgetline(buff, MAX_LINE_LENGTH, g_input_file) < 0) error_exit("Premature EOF while reading table"); /* Process the entire table */ for(op = g_opcode_input_table;;op++) { if(fgetline(buff, MAX_LINE_LENGTH, g_input_file) < 0) error_exit("Premature EOF while reading table"); if(strlen(buff) == 0) continue; /* We finish when we find an input separator */ if(strcmp(buff, ID_INPUT_SEPARATOR) == 0) break; /* Extract the info from the table */ ptr = buff; /* Name */ ptr += skip_spaces(ptr); ptr += check_strsncpy(op->name, ptr, MAX_NAME_LENGTH); /* Size */ ptr += skip_spaces(ptr); ptr += check_atoi(ptr, &temp); op->size = (unsigned char)temp; /* Special processing */ ptr += skip_spaces(ptr); ptr += check_strsncpy(op->spec_proc, ptr, MAX_SPEC_PROC_LENGTH); /* Specified EA Mode */ ptr += skip_spaces(ptr); ptr += check_strsncpy(op->spec_ea, ptr, MAX_SPEC_EA_LENGTH); /* Bit Pattern (more processing later) */ ptr += skip_spaces(ptr); ptr += check_strsncpy(bitpattern, ptr, 17); /* Allowed Addressing Mode List */ ptr += skip_spaces(ptr); ptr += check_strsncpy(op->ea_allowed, ptr, EA_ALLOWED_LENGTH); /* CPU operating mode (U = user or supervisor, S = supervisor only */ ptr += skip_spaces(ptr); for(i=0;i<NUM_CPUS;i++) { op->cpu_mode[i] = *ptr++; ptr += skip_spaces(ptr); } /* Allowed CPUs for this instruction */ for(i=0;i<NUM_CPUS;i++) { ptr += skip_spaces(ptr); if(*ptr == UNSPECIFIED_CH) { op->cpus[i] = UNSPECIFIED_CH; op->cycles[i] = 0; ptr++; } else { op->cpus[i] = '0' + i; ptr += check_atoi(ptr, &temp); op->cycles[i] = (unsigned char)temp; } } /* generate mask and match from bitpattern */ op->op_mask = 0; op->op_match = 0; for(i=0;i<16;i++) { op->op_mask |= (bitpattern[i] != '.') << (15-i); op->op_match |= (bitpattern[i] == '1') << (15-i); } } /* Terminate the list */ op->name[0] = 0; }
C
#include <clink/clink.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char **argv) { if (argc > 2 || (argc == 2 && strcmp(argv[1], "--help") == 0)) { fprintf(stderr, "usage: %s [compiler (default $CXX)]\n" " list #include paths used by a C++ compiler\n", argv[0]); return EXIT_FAILURE; } const char *compiler = argc == 2 ? argv[1] : NULL; char **includes = NULL; size_t includes_len = 0; int rc = clink_compiler_includes(compiler, &includes, &includes_len); if (rc) { fprintf(stderr, "clink_compiler_includes: %s\n", strerror(rc)); return EXIT_FAILURE; } for (size_t i = 0; i < includes_len; ++i) printf("%s\n", includes[i]); for (size_t i = 0; i < includes_len; ++i) free(includes[i]); free(includes); return EXIT_SUCCESS; }
C
//#include<stdio.h> // ////void swap1(int a, int b) ////{ //// int tmp = a; //// a = b; //// b = tmp; ////} //// ////void swap2(int* pa, int* pb) ////{ //// int tmp = *pa; //// *pa = *pb; //// *pb = tmp; ////} // //int main() //{ // //int i = 10; // //char c = 'y'; // // //int* pi = &i; // //char* pc = &c; // // //printf("%d\n", sizeof(pi)); //32λƽ̨464λƽ̨8 // //printf("%d\n", sizeof(pc)); //32λƽ̨464λƽ̨8 // // //// һdouble͵ָָڴַΪ0Ŀռ // //double* pd = NULL; // // //// Կָнòзʣdouble͵ı // //// ִгڴ0 ~255Ϊϵͳռڴ棬û // //double d = *pd; // // //// mnΪǸʼֵ // //int m = 10; // //int n = 20; // // //// constָ룬ָָ޸ģֵָ޸ // //const int* pm = &m; // //pm = &n; // ȷָ޸ // ////*pm = 30; // ָռֵ(*pm)޸ // // //// constγָָ޸ģֵָ޸ // //int* const pn = &n; // ////pn = &m; // ָ(pn)޸ // //*pn = 40; // ȷָռֵ(*pn)޸ // // //int a = 10; // //int b = 20; // // //swap1(a, b); // ֵݽab // //printf("a=%d b=%d\n", a, b); // abδ // // //swap2(&a, &b); // ַݽab // //printf("a=%d b=%d\n", a, b); // ab˽ // // return 0; //}
C
//Sohaib Wasif //0874921 //07/02/2020 //CIS*3490 //A2-1.1 //Brute force for inversion int bruteInv(int x [], int s) { int cnt = 0; for(int i = 0; i<s-1; i++){ for(int j = i+1; j < s; j++){ if(x[i] > x[j]){ cnt++; } } } return cnt; }
C
#include <stdio.h> int help() { system("cls"); printf("\n-------Welcome to QUIZ GAME-------"); printf("\n-------How To Play-------"); printf("\n___________________________"); printf("\n >> You will be given 4 options and you have to press A, B ,C or D for the right option."); printf("\n >> Each question carries two marks."); printf("\n >> Negative marking for wrong answers, one mark will be deducted!"); printf("\n >> You will have to complete the warm-up round within the time limit."); printf("\n >> Then next proceed to the challenging round."); printf("\n\n\t!!!!!!!!!!!!! ALL THE BEST !!!!!!!!!!!!!"); return 1; }
C
#include <conio.h> void out_char(unsigned int data){ unsigned char output; output = data &255; printf("%c",output ); } void out_data(unsigned int data){ printf("%u", data); } unsigned int input(){ unsigned int input_data; if (_kbhit()){ input_data = (unsigned int)_getch(); } else{ input_data = 0; } return input_data; }
C
int fact(int n); int main() { int n=4; int i = fact(n); print_t(n); print_t(i); return 0; } int fact(int n) { if(n==1) return 1; else { return n*fact(n-1); } }
C
#include <stdio.h> #define R_RT 0 #define R_WG 1 long double power(int x, int y) { long double p = 1; if (y > 0) for (int i = 0; i < y; i++) p = p * x; if (y < 0) for (int i = 0; i > y; i--) p = p / x; return p; } int main(void) { int a, n, num; long double result; num = scanf("%d%d", &a, &n); if (num == 2 && n > 0) { result = power(a, n); printf("%.0Lf\n", result); return R_RT; } return R_WG; }
C
#include "monty.h" /** * _mod - will perfom the second element module the top one * * @stack: double pointer to the start of the stack * @line: current line number * * Return: void */ void _mod(stack_t **stack, unsigned int line) { int elems = 0; stack_t *curr; if (*stack == NULL) m_error_handler(13, line, NULL, NULL); elems++; curr = *stack; while (curr->next) { elems++; curr = curr->next; } if (elems < 2) m_error_handler(13, line, NULL, NULL); if (curr->n == 0) m_error_handler(11, line, NULL, NULL); curr->prev->n = curr->prev->n % curr->n; _pop(stack, line); } /** * _pchar - prints the char at the top of the stack * * @stack: double pointer to the start of the stack * @line: current line number * * Return: void */ void _pchar(stack_t **stack, unsigned int line) { stack_t *curr; if (*stack == NULL) m_error_handler(15, line, NULL, NULL); curr = *stack; while (curr->next) { curr = curr->next; } if (curr->n < 0 || curr->n > 127) m_error_handler(14, line, NULL, NULL); printf("%c\n", curr->n); }
C
#include<stdio.h> #include<stdlib.h> /* * ṹ嶨ʹ */ struct student { char name[21]; int age; int score; char addr[51]; }; //ͬʱ //struct student { // char name[21]; // int age; // int score; // char addr[51]; //}stu = { "",18,100,"вƽ·22" }; int main_stu01() { //ṹ //ṹ ṹ //struct student stu; ////stu.name = ""; //strcpy(stu.name, ""); //stu.age = 18; //stu.score = 100; //strcpy(stu.addr, "вƽ·22"); struct student stu = {"", 18, 100, "вƽ·22"}; printf("%s\n", stu.name); printf("䣺%d\n", stu.age); printf("ɼ%d\n", stu.score); printf("ַ%s\n", stu.addr); return EXIT_SUCCESS; } int main_stu02(void) { struct student stu; //עƱǵַԲҪ"&" scanf("%s%d%d%s", stu.name, &stu.age, &stu.score, stu.addr); printf("%s\n", stu.name); printf("䣺%d\n", stu.age); printf("ɼ%d\n", stu.score); printf("ַ%s\n", stu.addr); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* start_bfs_head.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: cnella <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/10/25 14:57:53 by cnella #+# #+# */ /* Updated: 2019/10/25 14:57:53 by cnella ### ########.fr */ /* */ /* ************************************************************************** */ #include "lem_in.h" t_tree *traverse(t_lem_in *lem_in, t_tree *node, t_room *dst) { t_tree *res; int augmentation; t_room *intersection; if (!do_traverse(node, dst)) return (NULL); augmentation = node->augmentation; if (in_route(node->room, dst)) { augmentation--; if (augmentation < 0) return (NULL); intersection = dst; } else if (out_route(node->room, dst)) intersection = NULL; else intersection = node->intersection; res = tree_createchild(lem_in, node, dst); res->augmentation = augmentation; res->intersection = intersection; return (res); } t_tree *stop_traverse(t_lem_in *lem_in, t_tree *node) { t_tree *res; if (node->parent->room->next != NULL) { res = go_begin(lem_in, node); return (res); } return (NULL); } t_route *build_end_traverse(t_tree *node) { if (node->augmentation > 0) { return (route_tree(node)); } return (NULL); } /* ** Перебирает соединения текущего уровня узла. ** Хранит новый список соединений узла. ** Возвращает найденный путь, если есть */ t_route *sortout_node(t_lem_in *lem_in, t_tree *node, t_glist **next_nodes) { t_glist *curr; t_tree *new_node; t_route *res; new_node = NULL; mark_visited(node); if (node && node->room->type == end) { if ((res = build_end_traverse(node)) != NULL) return (res); new_node = stop_traverse(lem_in, node); if (new_node != NULL) ft_add_glist(next_nodes, ft_new_glist(new_node, sizeof(t_tree))); return (NULL); } curr = node->room->links; while (curr != NULL) { new_node = traverse(lem_in, node, curr->gen.room); if (new_node != NULL) ft_add_glist(next_nodes, ft_new_glist(new_node, sizeof(t_tree))); curr = curr->next; } return (NULL); } /* ** Перебирает узлы текущего уровня. ** Хранит список узлов следующего уровня. ** Возвращает лист дерева с первым найденным путем, если есть. */ t_route *sort_out_nodes(t_lem_in *lem_in, t_glist *nodes, t_glist **next_nodes) { t_glist *curr; t_route *res; curr = nodes; while (curr != NULL) { if ((res = sortout_node(lem_in, curr->gen.tree, next_nodes))) return (res); curr = curr->next; } return (NULL); }
C
#include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<stdio.h> #include<string.h> #include<stdlib.h> #define FLAGS O_WRONLY|O_CREAT|O_TRUNC #define MODE S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH int main(void){ const char* pathname; int fd; char pn[30]; printf("Input the pathname:[<30 strings]"); gets(pn); printf("OPENING FILE %s\n",pn); pathname=pn; if((fd=open(pathname,FLAGS,MODE))==-1) { printf("ERROR,OPEN FILE FAILED!\n"); exit(1); } printf("FILE OPEN!\n"); printf("FD=%d\n",fd); return 0; }
C
#include "Sort.h" void sort(int *v, int size) { int i, j; for (i = 0; i < size; i++) { for (j = i+1; j < size; j++) { if (v[i] > v[j]) { int aux = v[i]; v[i] = v[j]; v[j] = aux; } } } }
C
// // main.c // Project 2 // // Created by Daniel Choi on 10/2/19. // Copyright © 2019 Daniel Choi. All rights reserved. // #include <stdio.h> #include <stdlib.h> #include <string.h> #include "RecursiveDescent.h" #include "TableDriven.h" #include "ExpressionTree.h" int main(int argc, const char * argv[]) { char input[15]; printf("CSC173 Project 2 by Yoo Choi\n"); //Create productions Production E = new_Production("<E>"); Production_add_to_body(E, "<C>", 1); Production_add_to_body(E, "<ET>", 1); Production ET = new_Production("<ET>"); Production_add_to_body(ET, "|", 1); Production_add_to_body(ET, "<E>", 1); Production_add_to_body(ET, "", 2); Production C = new_Production("<C>"); Production_add_to_body(C, "<S>", 1); Production_add_to_body(C, "<CT>", 1); Production CT = new_Production("<CT>"); Production_add_to_body(CT, ".", 1); Production_add_to_body(CT, "<C>", 1); Production_add_to_body(CT, "", 2); Production S = new_Production("<S>"); Production_add_to_body(S, "<A>", 1); Production_add_to_body(S, "<ST>", 1); Production ST = new_Production("<ST>"); Production_add_to_body(ST, "*", 1); Production_add_to_body(ST, "<ST>", 1); Production_add_to_body(ST, "", 2); Production A = new_Production("<A>"); Production_add_to_body(A, "(", 1); Production_add_to_body(A, "<E>", 1); Production_add_to_body(A, ")", 1); Production_add_to_body(A, "<X>", 2); Production X = new_Production("<X>"); char* alphabet[26] = {"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"}; for (int i = 1; i < 27; i++){ Production_add_to_body(X, alphabet[i-1], i); } //Create our grammar Production* grammar = (Production*)malloc(sizeof(Production) * 8); grammar[0] = E; grammar[1] = ET; grammar[2] = C; grammar[3] = CT; grammar[4] = S; grammar[5] = ST; grammar[6] = A; grammar[7] = X; int grammar_size = 8; int** table = create_parsing_table(grammar, grammar_size); //Read input and print results. Ends on end-of-file in standard input while (true){ printf("\nEnter a regular expression, max 20 characters. Press \"Ctrl + D\" to quit: "); scanf("%20s", input); //take input if (feof(stdin)){ printf("\n\nQuit program\n\n"); break; } /* * Part 1: Recursive-Descent Parser */ bool valid = recursive_desc_parser(input); /* * Part 2: Table-Driven Parser AND * Part 3: Build an expression tree, and print in prefix notation */ if (valid) { Tree tree = table_driven_parser(input, table, grammar, grammar_size); printf("\nPart 2: Table-driven parser\nInputed expression: %s\n", input); //if the tree is either NULL or if E() ended before the end of the string, print ERROR if (tree == NULL){ printf("ERROR: Invalid expression\n"); } else { //otherwise, print our tree print_Tree(tree); LinkedList stack = new_LinkedList(); createStack(tree, stack); //LinkedList_print_string_list(stack); Tree expressionTree = createExpressionTree(stack); //print_Tree(expressionTree); printf("\nPart 3: Prefix notation of expression tree\n"); printPrefixExpTree(expressionTree); printf("\n"); LinkedList_free(stack, false); free_Tree(expressionTree); free_Tree(tree); } } } //free table and grammar for (int i = 0; i < grammar_size; i++){ free(table[i]); } free(table); for (int i = 0; i < grammar_size; i++){ Production_free(grammar[i]); } free(grammar); }
C
/* Time: O(n) Space: O(n) * Note: The returned array must be malloced, assume caller calls free(). */ int* productExceptSelf(int* nums, int numsSize, int* returnSize) { *returnSize = numsSize; int *result = (int *)malloc(sizeof(int)*numsSize); memset(result, 1, numsSize*sizeof(result[0])); // Fill up result array with 1s int pre = 1; for(int i=0; i<numsSize; i++) { result[i] = pre; pre *= nums[i]; } int post = 1; for(int i=numsSize-1; i>=0; i--) { result[i] *= post; post *= nums[i]; } return result; }
C
#ifndef INCL_HELPER_FUNCTIONS #define INCL_HELPER_FUNCTIONS #include "arduino.h" #include "robot_functions.h" #include <EEPROM.h> inline int servoAngleToDuty(int angle); inline void debugSerialBegin(); inline void debugPrint(const char* message); inline void debugPrintln(const char* message); inline void debugPrint(int number); inline void debugPrintln(int number); inline void debugPrintln(); inline int length(const char* source); inline int indexOf(char* source, char* target); inline void substring(char* source, int startIndex, int endIndex, char* dest); inline void substring(char* source, int startIndex, char* dest); inline void substring(char* source, int startIndex, int endIndex, char* dest, int destLength); inline void trim(char* source, int sourceLength); inline boolean equals(char* first, char* second); inline boolean equalsIgnoreCase(char* first, char* second); inline void strcpy(char* source, char* dest, int destLength); inline void concat(char* first, const char* second, char* dest, int destLength); inline void concatInt(char* first, int second, char* dest, int destLength); inline void eepromWriteInt(int address, int value); inline int eepromReadInt(int address); /************************************************************************/ /* Convenience method for writing an angle (-90 to 90) to a servo */ /* Assumes that PWM clock for all outputs is 8MHz/256 */ /************************************************************************/ int servoAngleToDuty(int angle) { // 255 => ~8ms // want to map 1.5ms to 0, 1ms to -90 and 2ms to 90 //int duration = (255 * 15 + 255*5*angle/90)/81; int contribution = 255*angle; return (255 * 15 + (((255*angle)/90)*5))/81; //double duty = ((double)angle)/180.0 + 1.5; } //============================================================================================ // Gets the length of the character array //============================================================================================ int length(const char* source) { int length = 0; for(; source[length] != '\0'; length++); return length; } //============================================================================================ // Gets the index of the given string, or -1 if not found //============================================================================================ int indexOf(char* source, char* target) { int targetLength = length(target); int sourceLength = length(source); int index = -1; for(int i = 0; i <= sourceLength - targetLength && index == -1; i++) { boolean foundTarget = true; for(int n = 0; n < targetLength && i+n < sourceLength; n++) { if(source[i+n] != target[n]) foundTarget = false; } if(foundTarget) index = i; } return index; } //============================================================================================ // Returns a substring of the character array // First is inclusive, second is exclusive // Returns itself if bounds are bad // Assumes beginning / end if either bound is negative //============================================================================================ void substring(char* source, int startIndex, int endIndex, char* dest) { substring(source, startIndex, endIndex, dest, 20); } //============================================================================================ // Returns a substring of the character array // First is inclusive, second is exclusive // Returns itself if bounds are bad // Assumes beginning / end if either bound is negative //============================================================================================ void substring(char* source, int startIndex, char* dest) { substring(source, startIndex, length(source), dest, 30); } //============================================================================================ // Returns a substring of the character array // First is inclusive, second is exclusive // Returns itself if bounds are bad // Assumes beginning / end if either bound is negative //============================================================================================ void substring(char* source, int startIndex, int endIndex, char* dest, int destLength) { char temp[destLength]; if(startIndex < 0) startIndex == 0; if(endIndex < 0) endIndex == 0; if(endIndex < startIndex) { dest[0] = '\0'; return; } if(endIndex >= length(source)) endIndex = length(source); if(destLength < endIndex - startIndex + 1) { dest[0] = '\0'; return; } for(int i = 0; i < endIndex - startIndex; i++) { temp[i] = source[startIndex + i]; } for(int i = 0; i < endIndex - startIndex; i++) dest[i] = temp[i]; dest[endIndex - startIndex] = '\0'; } //============================================================================================ // Removing leading and trailing spaces or new lines //============================================================================================ void trim(char* source, int sourceLength) { char temp[sourceLength]; int startIndex = 0; int endIndex = length(source)-1; for(; startIndex < length(source) && (source[startIndex] == ' ' || source[startIndex] == '\n' || source[startIndex] == '\t'); startIndex++); for(; endIndex >= 0 && (source[endIndex] == ' ' || source[endIndex] == '\n' || source[startIndex] == '\t'); endIndex--); endIndex++; substring(source, startIndex, endIndex, temp, sizeof(temp)-1); strcpy(temp, source, sourceLength-1); } //============================================================================================ // Tests if two character arrays are equal //============================================================================================ boolean equals(char* first, char* second) { if(length(first) != length(second)) return false; for(int i = 0; i < length(first); i++) { if(first[i] != second[i]) return false; } return true; } //============================================================================================ // Tests if two character arrays are equal, ignoring case //============================================================================================ boolean equalsIgnoreCase(char* first, char* second) { if(length(first) != length(second)) return false; for(int i = 0; i < length(first); i++) { int firstChar = first[i]; int secondChar = second[i]; // Make them lowercase if(firstChar >= 'A' && firstChar <= 'Z') firstChar += 'a' - 'A'; if(secondChar >= 'A' && secondChar <= 'Z') secondChar += 'a' - 'A'; if(firstChar != secondChar) return false; } return true; } //============================================================================================ // Copies one array into the other //============================================================================================ void strcpy(char* source, char* dest, int destLength) { if(destLength < length(source) + 1) { dest[0] = '\0'; return; } for(int i = 0; i < length(source); i++) { dest[i] = source[i]; } dest[length(source)] = '\0'; } //============================================================================================ // Concatenates two character arrays //============================================================================================ void concat(char* first, const char* second, char* dest, int destLength) { char temp[destLength]; if(destLength < length(first) + length(second) + 1) { dest[0] = '\0'; return; } for(int i = 0; i < length(first); i++) temp[i] = first[i]; for(int i = 0; i < length(second); i++) temp[i + length(first)] = second[i]; temp[length(second) + length(first)] = '\0'; for(int i = 0; i < length(second) + length(first); i++) dest[i] = temp[i]; dest[length(second) + length(first)] = '\0'; } //============================================================================================ // Concatenates a character array with an integer //============================================================================================ void concatInt(char* first, int second, char* dest, int destLength) { char secondChar[20]; sprintf (secondChar, "%i", second); concat(first, secondChar, dest, destLength); } //============================================================================================ // Serial functions //============================================================================================ void debugSerialBegin() { if(Robot::serialDebug) { Serial.begin(9600); } } void debugPrint(const char* message) { if(Robot::serialDebug) { Serial.print(message); } } void debugPrintln(const char* message) { if(Robot::serialDebug) { Serial.println(message); } } void debugPrint(int number) { if(Robot::serialDebug) { Serial.print(number); } } void debugPrintln(int number) { if(Robot::serialDebug) { Serial.println(number); } } void debugPrintln() { if(Robot::serialDebug) { Serial.println(); } } /******************************************************************* * A way to write an 'int' (2 Bytes) to EEPROM * EEPROM library natively supports only bytes. * Note it takes around 8ms to write an int to EEPROM *******************************************************************/ void eepromWriteInt(int address, int value) { union u_tag { byte b[2]; //assumes 2 bytes in an int int INTtime; } time; time.INTtime=value; EEPROM.write(address , time.b[0]); EEPROM.write(address+1, time.b[1]); } /******************************************************** * A way to read int (2 Bytes)from EEPROM * EEPROM library natively supports only bytes ********************************************************/ int eepromReadInt(int address) { union u_tag { byte b[2]; int INTtime; } time; time.b[0] = EEPROM.read(address); time.b[1] = EEPROM.read(address+1); return time.INTtime; } #endif
C
#include <stdio.h> void change_value(int a, int vlaue) { a = value; printf("%d in change_value \n", a); } int main(void) { int a = 10; change_value(a, 30); printf("%d in main \n", a); return 0; } // 매개 변수는 오른쪽에서 왼쪽으로 쌓이고 위에서 밑으로 쌓인다. void change_value(int x, int val) { x = val; printf("x : %d in change_value \n", x); } int main(void) { int x = 10; change_value(x, 20); printf("x : %d in main \n", x); } // call by value : 값을 단순하게 복사함, 인자를 값으로 전달했기 때문에
C
/* * pid.c * * Created on: Mar 28, 2018 * Author: atmelfan */ #include "pid.h" float pid_update(pid* pid, float set, float actual, float dt){ /*Calc error and update running integral*/ float error = set - actual; pid->integral_val += error*dt; /*Limit integral value*/ if(pid->integral_val > PID_MAX_INTEGRAL){ pid->integral_val = PID_MAX_INTEGRAL; }else if(pid->integral_val < -PID_MAX_INTEGRAL){ pid->integral_val = -PID_MAX_INTEGRAL; } /*PID*/ float out = error*pid->Kp + pid->Ki*pid->integral_val + pid->Kd*(error - pid->error_val)/dt; /*Save error value to next time*/ pid->error_val = error; return out; }
C
/***************************************************************************** * bit_sets.c * * Randy Miller * * Counts the number of bits set *****************************************************************************/ #include "main.h" #include <stdio.h> #include <stdlib.h> #define BITS_PER_BYTE 8 //Different methods #define NAIVE 0 #define LOOKUP 1 #define KERNIGHAN 2 #define SIZE 3 #define PARALLEL 4 #define MSB 5 #define BEST 6 static unsigned char BitsSetTable[256]; static const int S[] = {1, 2, 4, 8, 16}; static const int B[] = {0x55555555, 0x33333333, 0x0F0F0F0F, 0x00FF00FF, 0x0000FFFF}; static inline void generate_table(void) { BitsSetTable[0] = 0; for (int i = 0; i < 256; i++) BitsSetTable[i] = (i & 1) + BitsSetTable[i / 2]; } int bits_set(void) { int value, v, result, method, pos; unsigned char *p; //generate the table used for LOOKUP algorithmically generate_table(); printf("Which method should we use to count the number of bits set? Here are your options:\n\n"); printf("0. The naive way\n"); printf("1. By a lookup table\n"); printf("2. By Brian Kernighan's way\n"); printf("3. Assuming different sized values (we'll assume only 32-bit values)\n"); printf("4. In parallel\n"); printf("5. From the most-significant bit up to a given position\n"); printf("6. Supposedly, the best method\n"); do { printf("Please type one of the ints in the option list above:\n"); scanf("%d", &method); }while (method < NAIVE || method > BEST); if (method == MSB) { do { printf("Please pick a bit position:\n"); scanf("%d", &pos); } while(pos < 0 || pos > 31); } //get input printf("Count the bits set in:\n"); scanf("%d", &value); v = value; //count the bits set switch (method) { case NAIVE: for (result = 0; v; v >>= 1) result += v & 1; break; case LOOKUP: p = (unsigned char *) &v; result = BitsSetTable[p[0]] + BitsSetTable[p[1]] + BitsSetTable[p[2]] + BitsSetTable[p[3]]; break; case KERNIGHAN: for (result = 0; v; result++) v &= v - 1; break; case SIZE: result = ((v & 0xfff) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f; result += (((v & 0xfff000) >> 12) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f; result += ((v >> 24) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f; break; case PARALLEL: result = v - ((v >> 1) & B[0]); result = ((result >> S[1]) & B[1]) + (result & B[1]); result = ((result >> S[2]) + result) & B[2]; result = ((result >> S[3]) + result) & B[3]; result = ((result >> S[4]) + result) & B[4]; break; case MSB: result = v >> (sizeof(v) * BITS_PER_BYTE - pos); result = result - ((result >> 1) & ~0UL/3); result = (result & ~0UL/5) + ((result >> 2) & ~0UL/5); result = (result + (result >> 4)) & ~0UL/17; result = (result * (~0UL/255)) >> ((sizeof(v) - 1) * BITS_PER_BYTE); break; case BEST: v = v - ((v >> 1) & 0x55555555); v = (v & 0x33333333) + ((v >> 2) & 0x33333333); result = (((v + (v >> 4)) & 0xF0F0F0F0) * 0x1010101) >> 24; break; default: return 1; break; } printf("The number of bits set in %d is %d\n", value, result); return 0; }
C
/* wallclock.h for CIS*3090 B. Gardner, 24-Oct-11 #include or copy/paste the following functions into your program. They implement Pilot's PI_StartTime(), PI_EndTime() style of timing. This version gets accurate wall clock time from an OpenMP library function, rather than clock() which returns CPU time. To call it from a non-OpenMP program it is necessary to adjust a property: Visual Studio: Configuration Properties > C/C++ > Language [Intel C/C++] > OpenMP Support: "Generate Sequential Code" Command line compilation: Add option /Qopenmp_stubs to the icl command If you don't do the above, you will get a linker error. If this is an OpenMP program, you should NOT do the above since you will already have "Generate Parallel Code" or /Qopenmp. Call StartTime() to start timing (duh), then when you want to finish timing, print the seconds returned by EndTime() using "%lf" format. */ #include <omp.h> // helper function, don't call this directly static double TimeHelper( int reset ) { static double start = 0.0; if ( reset ) { start = omp_get_wtime(); return 0.0; } return (double)(omp_get_wtime()-start); } // StartTime resets timer // EndTime returns no. of wal lclock seconds elapsed since StartTime void StartTime() { TimeHelper( 1 ); // reset timer } double EndTime() { return TimeHelper( 0 ); }
C
#include<stdio.h> #include<stdbool.h> #include <stdlib.h> /* * Created by Rebecca D'souza on 30/03/18 * */ int top = -1; struct Queen{ int row; int column; int id; }; struct Queen stack[1000]; void print(struct Queen queen){ printf("Queen %d is placed at [%d,%d]\n",queen.id,queen.row,queen.column); } void push(struct Queen queen){ stack[++top] = queen; } struct Queen pop(){ return stack[top--]; } bool noConflict(struct Queen queen){ for(int i = 0;i<top+1;i++) if(stack[i].id<queen.id) { struct Queen x = stack[i]; if (x.column==queen.column||abs(queen.row-x.row)==abs(queen.column-x.column)) return false; } return true; } void main() { int N , filled = 1; scanf("%d",&N); bool repeat; struct Queen queen[N + 1]; queen[1].id = 1; queen[1].row = 1; queen[1].column = 1; push(queen[1]); while (filled < N) { repeat = true; queen[filled + 1].id = filled + 1; queen[filled + 1].row = filled + 1; queen[filled + 1].column = 1; push(queen[filled + 1]); while (repeat) if (noConflict(stack[top])) { filled++; repeat = false; } else if (stack[top].column != N) { stack[top].column++; if (noConflict(stack[top])) { filled++; repeat = false; } } else if (stack[top].column == N) { pop(); filled--; if (stack[top].column == N) { pop(); filled--; } stack[top].column++; repeat = true; } } for (int x = 0; x < top+1; x++) print(stack[x]); printf("\n"); for(int i = 0;i<N;i++) printf(" _"); printf("\n"); for (int i = top; i >= 0; i--) { for (int j = 1; j < N+1; j++) if (j == stack[i].column) printf("|Q"); else printf("|_"); printf("|\n"); } printf("\n"); }
C
#pragma once /* Defines the function pointer as a type for convenience This function is intended to provided the linked list with the way to destruct/free up the void* data IF the data needs special way to free up */ typedef void(*destruct_data_function)(void*); /* Each node contains a void* data so that it can store any type of data Also it contains another node pointer pointing to the next node */ typedef struct node { void* data; struct node* next; } node_t; /* function related to node */ node_t* construct_node(void); node_t* construct_node_overload1(node_t*, void*); void destruct_node(node_t*); void* get_data(node_t*); node_t* get_next(node_t*); void set_next(node_t*, node_t*); /* A linked list contains 1. head node pointer 2. element size (used to allocate memory for void* data) 3. number of elements(length) 4. the destruct function */ typedef struct linked_list { node_t* head; unsigned int element_size; unsigned int length; destruct_data_function destruct_data_fn; } linked_list_t; /* Functions related to linked list */ linked_list_t* construct_linked_list(destruct_data_function, unsigned int); void destruct_linked_list(linked_list_t*); int is_list_empty(linked_list_t*); void push_front(linked_list_t*, void*); void push_back(linked_list_t*, void*); void pop_front(linked_list_t*); unsigned int get_element_size(linked_list_t*); unsigned int get_length(linked_list_t*); unsigned int get_index(linked_list_t*, void*); void* get_by_index(linked_list_t*, unsigned int); int delete_by_index(linked_list_t*, unsigned int); int delete_data(linked_list_t*, void*);
C
#include <stdio.h> int main ( void ) { int min, max, sumValue = 0, minValue = 999999; scanf( "%d %d", &min, &max ); for( int i = 1; i <= 100; ++ i ) { int powValue = i * i; if( powValue > max ) break; if( min <= powValue && powValue <= max ) { if( minValue > powValue ) minValue = powValue; sumValue += powValue; } } if( sumValue == 0 ) printf( "-1" ); else printf( "%d\n%d", sumValue, minValue ); return 0; }
C
//***********************************************************************/ // Author : Garry // Original Date : May,28 2004 // Module Name : string.h // Module Funciton : // This module and string.cpp countains the // string operation method. // Last modified Author : // Last modified Date : // Last modified Content : // 1. // 2. // Lines number : //***********************************************************************/ #ifndef __STRING__ #define __STRING__ #define MAX_STRING_LEN 512 //Max string length. BOOL StrCmp(LPSTR,LPSTR); //String compare functions. //#define strcmp StrCmp WORD StrLen(LPSTR); //Get the string's length. //#define strlen StrLen BOOL Hex2Str(DWORD,LPSTR); //Convert the first parameter(hex format) //to string. BOOL Str2Hex(LPSTR,DWORD*); //Convert the string to hex number. BOOL Str2Int(LPSTR,DWORD*); //Convert the string to int. BOOL Int2Str(DWORD,LPSTR); //Convert the 32 bit int to string. VOID PrintLine(LPSTR); //Print the string at a new line. VOID StrCpy(LPSTR,LPSTR); //Copy one string to the second string. //#define strcpy StrCpy VOID ConvertToUper(LPSTR); //Convert the string's characters from low to uper. INT FormString(LPSTR,LPSTR,LPVOID*); //Memory manipulating functions. void* memcpy(void* dst,const void* src,size_t count); void* memset(void* dst,int val,size_t count); void* memzero(void* dst,size_t count); int memcmp(const void* p1,const void* p2,int count); void* memchr (const void * buf,int chr,size_t cnt); void *memmove(void *dst,const void *src,int n); //Standard C Lib string operations. char* strcat(char* dst,const char* src); char* strcpy(char* dst,const char* src); //char* strchr(const char* string,int ch); char * strchr (const char *s, int c_in); char * strrchr(const char * str,int ch); char * strstr(const char *s1,const char *s2); int strcmp(const char* src,const char* dst); int strlen(const char* s); //Array bound guaranteed string operations. char* strncpy(char *dest,char *src,unsigned int n); int strncmp ( char * s1, char * s2, size_t n); //Flags to control the trimming. #define TRIM_LEFT 0x1 #define TRIM_RIGHT 0x2 //Trim space in a string. void strtrim(char * dst,int flag); int strtol(const char *nptr, char **endptr, int base); void ToCapital(LPSTR lpszString); //Find the first bit in a given integer. int ffs(int x); #endif //string.h
C
/* Title- Write a C program to accept string with multiple spaces from user and print it with a sinlge space as a delimiter. Eg: Input String: _____India_____is_my_________country___________________ Output String: India_is_my_country (Consider _ as space) Author- Bhakare Mahesh Santosh ID- 492 Batch- TechnOrbit(PPA-8) */ #include<stdio.h> void main() { char str[100]; int i=0; printf("enter the string: "); fgets(str,sizeof(str),stdin); i=0; printf("string with removed spaces is: "); while(str[i]!='\0') { if(str[i]==32) { i++; continue; } else { break; } } while(str[i]!='\0') { if(str[i]==32 && str[i+1]==32 || str[i]==32 && str[i+1]==10 || str[i]==32 && str[i+1]=='\0' ) { i++; continue; } printf("%c",str[i]); i++; } printf("\n"); }
C
#include <stdio.h> #include <string.h> int contavogais(char *nome){ //DESENVOLVER A LOGICA DE CONTAR VOGAIS int i, tam, cont=0; tam=strlen(nome); for (i=0;i<tam;i++){ if( nome[i]=='a' || nome[i]=='e' || nome[i]=='i' || nome[i]=='o' || nome[i]=='u' || nome[i]=='A' || nome[i]=='E' || nome[i]=='I' || nome[i]=='O' || nome[i]=='U') { cont++; } } return cont; } int main(){ char nome[100]; int qtdVogais; printf("\nEntre com uma frase: \n"); gets(nome); qtdVogais=contavogais(nome); printf("\n\nEsta frase tem %d Vogais!", qtdVogais); }
C
#include <lib500.h> #include <stdio.h> // this is copied directly from turbo.asm // with only small modifications word read_bit() FASTNAKED { __asm load_threshold: ld hl, 0x6800 xor a ; counts the HIGH (positive) semiwave read_bit_loop_H: inc a bit 7, (hl) jr nz, read_bit_loop_H ; counts the LOW (negative) semiwave read_bit_loop_L: inc a bit 7, (hl) jr z, read_bit_loop_L threshold: ld l, a ld h, 0 ret __endasm; } // read two bits and save bit length value // the first bit is to acquire the lost synch // the second is the good one word read_some_bits() FASTNAKED { __asm di ld a, 2 out (0x41), a call _read_bit call _read_bit ld a, (0x8666) out (0x41), a ei ret __endasm; } byte s[255]; void text_inspect() { cls(); while(1) { word b = read_some_bits(); sprintf(s, "%d\r\n", b); rom_prints(s); } } word draw_h_hl; byte draw_h_x; byte draw_h_c; void draw_horizontal_bar(byte x, byte y, byte color) { draw_h_hl = 0x4000 + gr3_getrow(y); draw_h_x = (x >> 1); draw_h_c = color | (color << 4); if(x>=2) { __asm ld a, (_draw_h_hl) ld l, a ld a, (_draw_h_hl+1) ld h, a ld a, (_draw_h_x) ld b, a ld a, (_draw_h_c) ld c, a draw_h_loop: ld (hl), c inc hl djnz draw_h_loop __endasm; } if(x % 2 == 1) gr3_pset(x-1, y, color); /* for(byte xx=0; xx<=x; xx++) { gr3_pset(xx, y, color); } */ } byte bars[256]; void main() { static byte t; static word j; static byte ruler; set_border(BLACK); gr_mode(GR_MODE_3); set_bank1(7); gr_mem_fill(0x00); while(1) { for(t=0; t<255; t++) bars[t] = 0; for(j=0; j<512; j++) { byte i = read_some_bits(); bars[i]++; } for(t=0;t<192;t++) { ruler = t % 8 == 0 ? DARK_GREY : BLACK; draw_horizontal_bar(159, t, ruler); //draw_horizontal_bar(159, t, GREEN); byte w = bars[t]; if(w>159) w=159; draw_horizontal_bar(w, t, YELLOW); } } set_bank1(1); rom_getc(); gr_mode(GR_MODE_OFF); cls(); }
C
#include <stdio.h> #include <stdlib.h> typedef int ElementType; typedef struct Node *PtrToNode; typedef PtrToNode Stack; struct Node { ElementType Element; PtrToNode Next; }; /* START: fig3_40.txt */ int IsEmpty( Stack S ) { return S->Next == NULL; } /* END */ /* START: fig3_41.txt */ Stack CreateStack( void ) { Stack S; S = malloc( sizeof( struct Node ) ); if( S == NULL ) printf( "Out of space!!!" ); S->Next = NULL; MakeEmpty( S ); return S; } void MakeEmpty( Stack S ) { if( S == NULL ) printf( "Must use CreateStack first" ); else while( !IsEmpty( S ) ) Pop( S ); } /* END */ void DisposeStack( Stack S ) { MakeEmpty( S ); free( S ); } /* START: fig3_42.txt */ void Push( ElementType X, Stack S ) { PtrToNode TmpCell; TmpCell = malloc( sizeof( struct Node ) ); if( TmpCell == NULL ) printf( "Out of space!!!" ); else { TmpCell->Element = X; TmpCell->Next = S->Next; S->Next = TmpCell; } } /* END */ /* START: fig3_43.txt */ ElementType Top( Stack S ) { if( !IsEmpty( S ) ) return S->Next->Element; printf( "Empty stack" ); return 0; /* Return value used to avoid warning */ } /* END */ /* START: fig3_44.txt */ void Pop( Stack S ) { PtrToNode FirstCell; if( IsEmpty( S ) ) printf( "Empty stack" ); else { FirstCell = S->Next; S->Next = S->Next->Next; free( FirstCell ); } } /* END */ main( ) { Stack S; int i; S = CreateStack( ); for( i = 0; i < 10; i++ ) Push( i, S ); while( !IsEmpty( S ) ) { printf( "%d\n", Top( S ) ); Pop( S ); } DisposeStack( S ); return 0; }
C
#include <stdio.h> #include <stdlib.h> // Structure for each node. struct node { int data; struct node *link; }; // Global variables struct node *front = NULL, *rear = NULL; int **graph; int total_node; int *visited; int *node_name; // int graph[100][100]; // int graph[100][100]={ // {0,1,1,1,0}, // {1,0,1,0,0}, // {1,1,0,0,1}, // {1,0,0,0,0}, // {0,0,1,0,0} // }; // int graph[100][100]={ // {0,1,0,1,0,0}, // {1,0,1,0,1,0}, // {0,1,0,0,0,0}, // {1,0,0,0,0,0}, // {0,1,0,0,0,1}, // {0,0,0,0,1,0} // }; // Function to check QUEUE is empty. int is_empty() { if (NULL == front && NULL == rear) return 1; else return 0; } // Function for enqueue operation. void enqueue(int item) { struct node *new_node = (struct node *)malloc(sizeof(struct node)); if (NULL == new_node) { printf("\n\tOVERFLOW!\n"); } else { new_node->data = item; new_node->link = NULL; if (is_empty()) front = rear = new_node; else { rear->link = new_node; rear = new_node; } } } // Function for dequeue operation. int dequeue() { if (is_empty()) { printf("\n\tUNDERFLOW!"); return -1; } else { int item = front->data; struct node *del = front; if (front == rear) front = rear = NULL; else front = front->link; del->link = NULL; free(del); return item; } } // Function to print visiting nodes. void show_visiting_node(int node_index) { printf("\n\t VISITING NODE : %d ", node_name[node_index]); } // BFS Algorithm. void bfs(int node) { // Starting node. visited[node] = 1; show_visiting_node(node); while (1) { for (int i = 0; i < total_node; i++) { // Exploring all the adjacent nodes. if (1 == graph[node][i] && 0 == visited[i]) { // Enqueue the unvisied nodes. enqueue(i); visited[i] = 1; show_visiting_node(i); } } // When queue is empty. if (is_empty()) return; else node = dequeue(); // Dequeue next node from the queue. } } int main() { // total_node=6; scanf("%d", &total_node); printf("\n TOTAL NUMBER OF NODES : %d",total_node); // Allocating memeory. visited = (int *)calloc(total_node, sizeof(int)); node_name = (int *)calloc(total_node, sizeof(int)); graph = (int **)malloc(total_node * sizeof(int *)); for (int i = 0; i < total_node; i++) graph[i] = (int *)malloc(total_node * sizeof(int)); // Name of the nodes. printf("\n NAME OF %d NODES : ", total_node); for (int i = 0; i < total_node; i++){ scanf("%d", &node_name[i]); printf("%d",node_name[i]); printf(" ");} printf("\n"); // Adjacency Matrix of given graph. printf("\n Adjacency Matrix \n"); for (int i = 0; i < total_node; i++) { for (int j = 0; j < total_node; j++) scanf("%d", &graph[i][j]); } for (int i=0;i<total_node;i++){ for(int j=0;j<total_node;j++){ printf( "%d",graph[i][j]); printf(" "); } printf("\n"); } // BFS calling for components of graph. printf("\n Breadth-first search :\n"); for (int node = 0; node < total_node; node++) if (0 == visited[node]) bfs(node); printf("\n"); return 0; } /* 0 1 1 1 0 1 0 1 0 0 1 1 0 0 1 1 0 0 0 0 0 0 1 0 0 0 1 0 1 0 0 1 0 1 0 1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 */
C
/* * Interface para o programa de séries. * * Autores: * Allan Silva Domingues 9293290 * Eduardo Garcia Misiuk 9293230 * Raul Wagner Martins Costa 9293032 */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "db.h" #include "utils.h" int main (int argc, char *argv[]) { SERIES_DATABASE *db = NULL; int opt = 1; int error; // Inicializando o arquivo; create_file (DB_FILE_NAME, &db); printf ("==================== SERIES ====================\n"); printf ("Bem-vindo! Selecione uma das opções abaixo:\n"); while (opt != 0) { printf ("0 - Sair\n"); printf ("1 - Gerar arquivo da base de dados aleatório\n"); printf ("2 - Buscar por uma série\n"); printf ("3 - Mostrar todas as séries\n"); printf ("Opção escolhida: "); scanf ("%d", &opt); getc (stdin); switch (opt) { case 0: printf ("Finalizando o programa...\n"); break; case 1: printf ("Gerando arquivos...\n"); error = generate_random_file (db); // TODO: verificação de erros da função generate_random_file (); if (error == 0) printf ("Arquivos gerados com sucesso!\n"); break; case 2: printf ("Digite o ID da série: "); search_series(db); break; case 3: printf ("Séries contidas no sistema:\n"); all_series (db); break; default: printf ("Opção %d não é válida!\n", opt); break; } } // Destruindo o arquivo; destroy_file (&db); return EXIT_SUCCESS; }
C
/** * COP3514 Project 10 * This program is a modified version from project 9. * In this program, the LinkedList maintains order * and includes an option to delete entries from it. * * @author John Cameron (jcameron2) */ #include "car.h" #include "readline.h" #include <stdio.h> #include <stdlib.h> #include <string.h> /** * Appends an element to the end of a LinkedList * @param list The LinkedList to append the element to * @return A pointer to the LinkedList */ struct car *append_to_list(struct car *list) { struct car *cur, *new_node, *prev; new_node = malloc(sizeof(struct car)); if (new_node == NULL) { printf("Database is full; can't add more cars.\n"); return list; } printf("Enter make:\n"); read_line(new_node->make, LEN); printf("Enter model:\n"); read_line(new_node->model, LEN); printf("Enter color:\n"); read_line(new_node->color, LEN); printf("Enter year:\n"); scanf("%d", &new_node->year); printf("Enter city mpg:\n"); scanf("%d", &new_node->city_mpg); printf("Enter highway mpg:\n"); scanf("%d", &new_node->highway_mpg); printf("Enter quantity:\n"); scanf("%d", &new_node->quantity); /* * Check whether the car has already existed by * make, model, color, and manufacture year. * If so, print an error message and exit */ for (cur = list, prev = NULL; cur != NULL; prev = cur, cur = cur->next) if (strcmp(cur->make, new_node->make) == 0 && strcmp(cur->model, new_node->model) == 0 && strcmp(cur->color, new_node->color) == 0 && cur->year == new_node->year) { printf("car already exists.\n"); // Not adding anything to the list // Therefore, free the memory that was just allocated free(new_node); return list; } if (cur == NULL && prev != NULL) { //The list is not empty // Loop through the LinkedList and find the first node in it that // is positioned higher alphabetically than the node being currently added. for (cur = list, prev = NULL; cur != NULL; prev = cur, cur = cur->next) { // Compare each car structure to determine if the // new node should be inserted at this position if (car_cmp(new_node, cur) > 0) { if (prev != NULL) { // There is a previous node of where the new_node is being inserted to. // Make sure that the previous node is pointing to the new node and that // the new node is pointing to the original value pointed by the previous node prev->next = new_node; new_node->next = cur; return list; } else { // There is not a previous node of where the new node is being inserted to. // Therefore, the new node is going to be the first node of the LinkedList. new_node->next = cur; return new_node; } } } // Found nothing that is alphabetically higher than the node being inserted // Append the new node to the end of the LinkedList prev->next = new_node; return list; } else { // If the list is empty, the function should // return the pointer to the newly created car return new_node; } } struct car *delete_from_list(struct car *list) { char make[LEN + 1]; char model[LEN + 1]; char color[LEN + 1]; int year; printf("Enter make:\n"); read_line(make, LEN); printf("Enter model:\n"); read_line(model, LEN); printf("Enter color:\n"); read_line(color, LEN); printf("Enter year:\n"); scanf("%d", &year); struct car *cur, *prev; // Find a car structure in the LinkedList that // matches the input supplied by the user for (cur = list, prev = NULL; cur != NULL && (strcmp(cur->make, make) != 0 || strcmp(cur->model, model) != 0 || strcmp(cur->color, color) || cur->year != year); prev = cur, cur = cur->next); if (cur == NULL) { printf("car does not exist\n"); return list; } if (prev == NULL) // If there isn't a previous node for the current one, // then the element to be removed must be the first entry. // Simply set the initial element to the next one in the list. list = list->next; else // The cur node is the one that needs to be deleted. // Set the next node of the previous node to the next node // of the current node (since the current node is being deleted) prev->next = cur->next; printf("Deleted car make: %s, model: %s, color: %s, year: %d\n", cur->make, cur->model, cur->color, cur->year); //Free memory occupied by the node being deleted free(cur); return list; } /** * Prints each element in the list which matches a certain make and model * This function will prompt the user to enter the make and model * @param list The LinkedList to search in */ void find_car(struct car *list) { char make[LEN + 1]; char model[LEN + 1]; printf("Enter make:\n"); read_line(make, LEN); printf("Enter model:\n"); read_line(model, LEN); struct car *p; int foundModel = 0; for (p = list; p != NULL; p = p->next) if (strcmp(p->make, make) == 0 && strcmp(p->model, model) == 0) { printf("color: %s, year: %d, city mpg: %d, highway mpg: %d, quantity: %d\n", p->color, p->year, p->city_mpg, p->highway_mpg, p->quantity); foundModel = 1; } if (!foundModel) printf("no cars were found with that make and model.\n"); } /** * Prints each element in the list * @param list The LinkedList */ void printList(struct car *list) { struct car *p; printf("Make\tModel\t\tYear\tColor\tCity MPG\tHighway MPG\tQuantity\n"); for (p = list; p != NULL; p = p->next) printf("%s\t%-10s\t%d\t%s\t%d\t\t%d\t\t%d\n", p->make, p->model, p->year, p->color, p->city_mpg, p->highway_mpg, p->quantity); } /** * Clears the LinkedList by freeing the memory allocated * @param list The LinkedList to clear */ void clearList(struct car *list) { struct car *p; while (list != NULL) { p = list; list = list->next; if (p != NULL) free(p); } } /** * Compares two car structures * @param a First car structure * @param b Second car structure * @return -1 if a is less than b, 1 if a is greater than b, 0 if a is equal to b */ int car_cmp(struct car *a, struct car *b) { // Compare the make of the two car structures first int makeCompare = strcmp(a->make, b->make); if (makeCompare > 0) { return -1; } else { // Then compare the model of the two car structures return strcmp(b->model, a->model); } }
C
#include <stdint.h> #include <time.h> enum CARD_STATE { CARD_STATE_NULL, CARD_STATE_DATALESS, CARD_STATE_ACTIVE }; struct CardTimestampData { time_t time; uint32_t price; uint32_t amount; }; struct Card { uint8_t state; char name[64]; struct CardTimestampData data[365*20]; //20 years worth max unsigned int dataLength; }; int x = sizeof(struct Card); //1 GB int main(){ return 0; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_4__ TYPE_1__ ; /* Type definitions */ struct TYPE_4__ {scalar_t__ length; scalar_t__ data; } ; typedef TYPE_1__ ASN1_IA5STRING ; /* Variables and functions */ int X509_V_ERR_PERMITTED_VIOLATION ; int X509_V_ERR_UNSUPPORTED_NAME_SYNTAX ; int X509_V_OK ; scalar_t__ ia5casecmp (char const*,char const*) ; char* strchr (char const*,char) ; scalar_t__ strncmp (char const*,char const*,int) ; __attribute__((used)) static int nc_email(ASN1_IA5STRING *eml, ASN1_IA5STRING *base) { const char *baseptr = (char *)base->data; const char *emlptr = (char *)eml->data; const char *baseat = strchr(baseptr, '@'); const char *emlat = strchr(emlptr, '@'); if (!emlat) return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX; /* Special case: initial '.' is RHS match */ if (!baseat && (*baseptr == '.')) { if (eml->length > base->length) { emlptr += eml->length - base->length; if (ia5casecmp(baseptr, emlptr) == 0) return X509_V_OK; } return X509_V_ERR_PERMITTED_VIOLATION; } /* If we have anything before '@' match local part */ if (baseat) { if (baseat != baseptr) { if ((baseat - baseptr) != (emlat - emlptr)) return X509_V_ERR_PERMITTED_VIOLATION; /* Case sensitive match of local part */ if (strncmp(baseptr, emlptr, emlat - emlptr)) return X509_V_ERR_PERMITTED_VIOLATION; } /* Position base after '@' */ baseptr = baseat + 1; } emlptr = emlat + 1; /* Just have hostname left to match: case insensitive */ if (ia5casecmp(baseptr, emlptr)) return X509_V_ERR_PERMITTED_VIOLATION; return X509_V_OK; }
C
#include <stdio.h> #include <math.h> int main() { int nTestcase; int src, dst; int distance, sqrtDistance; int i; scanf("%d", &nTestcase); for (i = 0; i< nTestcase; i++) { scanf("%d %d", &src, &dst); distance = dst - src; sqrtDistance = (int)sqrt(distance); if (distance == sqrtDistance * sqrtDistance) printf("%d\n", 2 * sqrtDistance - 1); else if (distance <= sqrtDistance * sqrtDistance + sqrtDistance) printf("%d\n", 2 * sqrtDistance); else printf("%d\n", 2 * sqrtDistance + 1); } }
C
// dracula.c // Implementation of your "Fury of Dracula" Dracula AI #include <stdlib.h> #include <stdio.h> #include <time.h> #include "DracView.h" #include "Game.h" #include "Map.h" #include "Places.h" #include "Queue.h" #include "Set.h" typedef enum DRACULA_MESSAGE { PLACING_TRAP, PLACING_VAMPIRE, HIDING, DOUBLE_BACKING, NOTHING } DraculaMessage; char *givePresetMessage(DracView gameState, DraculaMessage code); void decideDraculaMove(DracView gameState) { Round roundNum = giveMeTheRound(gameState); //LocationID GLocation = whereIs(gameState, PLAYER_LORD_GODALMING); //LocationID SLocation = whereIs(gameState, PLAYER_DR_SEWARD); //LocationID HLocation = whereIs(gameState, PLAYER_VAN_HELSING); //LocationID MLocation = whereIs(gameState, PLAYER_MINA_HARKER); LocationID DLocation = whereIs(gameState, PLAYER_DRACULA); if (roundNum == 0) { registerBestPlay("FR", givePresetMessage(gameState, 6)); } else { // Creating an empty set which will be filled with all legal moves by Dracula in current state Set options = newSet(); // connections[] contains all locations Dracula can reach in one round minus the ones currently in his trail int numConnections = 0; LocationID *connections = whereCanIgo(gameState, &numConnections, TRUE, TRUE); int numOptions = numConnections; int i; for (i = 0; i < numConnections; i++) { setAdd(options, connections[i]); } if (doneHide(gameState) == FALSE && idToType(DLocation) != SEA) { setAdd(options, HIDE); numOptions++; } if (doneDoubleBack(gameState) == FALSE) { setAdd(options, DOUBLE_BACK_1); numOptions++; if (roundNum >= 2) { setAdd(options, DOUBLE_BACK_2); numOptions++; } if (roundNum >= 3) { setAdd(options, DOUBLE_BACK_3); numOptions++; } if (roundNum >= 4) { setAdd(options, DOUBLE_BACK_4); numOptions++; } if (roundNum >= 5) { setAdd(options, DOUBLE_BACK_5); numOptions++; } } if (numOptions == 0) { setAdd(options, TELEPORT); numOptions++; } LocationID * optionsArray = copySetToArray(options); srand(time(NULL)); int choiceIndex = rand() % numOptions; int messageCode = rand() % 5; char * choice; if (optionsArray[choiceIndex] >= MIN_MAP_LOCATION && optionsArray[choiceIndex] <= MAX_MAP_LOCATION) { choice = idToAbbrev(optionsArray[choiceIndex]); } else if (optionsArray[choiceIndex] == HIDE) { choice = "HI"; } else if (optionsArray[choiceIndex] == DOUBLE_BACK_1) { choice = "D1"; } else if (optionsArray[choiceIndex] == DOUBLE_BACK_2) { choice = "D2"; } else if (optionsArray[choiceIndex] == DOUBLE_BACK_3) { choice = "D3"; } else if (optionsArray[choiceIndex] == DOUBLE_BACK_4) { choice = "D4"; } else if (optionsArray[choiceIndex] == DOUBLE_BACK_5) { choice = "D5"; } else if (optionsArray[choiceIndex] == TELEPORT) { choice = "TP"; } registerBestPlay(choice, givePresetMessage(gameState, messageCode)); free(optionsArray); disposeSet(options); free(connections); } } // Returns a witty message depending on game features. // As Dracula, this is pretty useless, but it'll be funny to read later. char *givePresetMessage(DracView gameState, DraculaMessage code) { switch (code) { case 0: return "Quiet as a bat."; case 1: return "Where is she?!"; case 2: return "Bats have nine lives."; case 3: return "If you hit me, you'll be charged for bat-tery."; case 4: return "You know I'm bat, I'm bat, I'm really really bat."; default: return "Mwuhahahaha"; } }
C
#include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include "main.h" const float inf = (float) 99999999.0; const float undefined = (float) 67108864.0; const float BIG_DIGIT = (float) 88888888.0; typedef struct { float *array; size_t used; size_t size; } Array; typedef struct { float **array; size_t used; size_t size; } PointerArray; void initPointerArray(PointerArray *a, size_t initialSize) { a->array = malloc(initialSize * sizeof(float *)); a->used = 0; a->size = initialSize; } void initArray(Array *a, size_t initialSize) { a->array = malloc(initialSize * sizeof(float)); a->used = 0; a->size = initialSize; } void insertPointerArray(PointerArray *a, float *element) { if (a->used == a->size) { a->size *= 2; a->array = realloc(a->array, a->size * sizeof(float *)); } a->array[a->used++] = element; } void insertArray(Array *a, float element) { if (a->used == a->size) { a->size *= 2; a->array = realloc(a->array, a->size * sizeof(float)); } a->array[a->used++] = element; } void printPointerArray(PointerArray *a, unsigned short inner_array_length) { for (int i = 0; i < a->used; ++i) { for (int j = 0; j < inner_array_length; ++j) { printf("%f ", a->array[i][j]); } printf("\n"); } printf("\n"); } void printArray(Array *a) { for (int i = 0; i < a->used; ++i) { printf("%f ", a->array[i]); } printf("\n"); } void freePointerArray(PointerArray *a) { free(a->array); a->array = NULL; a->used = a->size = 0; } void freeArray(Array *a) { free(a->array); a->array = NULL; a->used = a->size = 0; } void insert_positive_value(struct BasicInput *input, PointerArray *constraint_matrix, Array *right_side_array, int i) { insertPointerArray(constraint_matrix, input->constraint_matrix[i]); insertArray(right_side_array, input->right_side_matrix[i][0]); } void insert_negative_value(struct BasicInput *input, PointerArray *constraint_matrix, Array *right_side_array, int i) { float *constraint_matrix_row = malloc(input->coefficients_length * sizeof(float)); for (int j = 0; j < input->coefficients_length; ++j) { constraint_matrix_row[j] = -input->constraint_matrix[i][j]; } insertPointerArray(constraint_matrix, constraint_matrix_row); insertArray(right_side_array, -input->right_side_matrix[i][0]); } void remake_right_side_matrix(struct BasicInput *input, PointerArray *constraint_matrix, Array *right_side_array) { for (int i = 0; i < input->right_side_matrix_length; ++i) { if (input->right_side_matrix[i][1] == -1) { // <= insert_negative_value(input, constraint_matrix, right_side_array, i); } else if (input->right_side_matrix[i][1] == 0) { // == insert_negative_value(input, constraint_matrix, right_side_array, i); insert_positive_value(input, constraint_matrix, right_side_array, i); } else if (input->right_side_matrix[i][1] == 1) { // >= insert_positive_value(input, constraint_matrix, right_side_array, i); } } } void insert_positive_bound(struct BasicInput *input, PointerArray *constraint_matrix, Array *right_side_array, int i) { float *constraint_matrix_row = malloc(input->coefficients_length * sizeof(float)); for (int j = 0; j < input->coefficients_length; ++j) { if (i != j) { constraint_matrix_row[j] = 0; } else { constraint_matrix_row[j] = 1; } } insertPointerArray(constraint_matrix, constraint_matrix_row); insertArray(right_side_array, input->bounds[i][0]); } void insert_negative_bound(struct BasicInput *input, PointerArray *constraint_matrix, Array *right_side_array, int i) { float *constraint_matrix_row = malloc(input->coefficients_length * sizeof(float)); for (int j = 0; j < input->coefficients_length; ++j) { if (i != j) { constraint_matrix_row[j] = 0; } else { constraint_matrix_row[j] = -1; } } insertPointerArray(constraint_matrix, constraint_matrix_row); insertArray(right_side_array, -input->bounds[i][1]); } void remake_bounds(struct BasicInput *input, PointerArray *constraint_matrix, Array *right_side_array) { for (int i = 0; i < input->bounds_length; ++i) { if (input->bounds[i][0] > -inf && input->bounds[i][1] < +inf) { insert_negative_bound(input, constraint_matrix, right_side_array, i); insert_positive_bound(input, constraint_matrix, right_side_array, i); } else if (input->bounds[i][0] <= -inf && input->bounds[i][1] < +inf) { insert_negative_bound(input, constraint_matrix, right_side_array, i); } else if (input->bounds[i][0] > -inf && input->bounds[i][1] >= +inf) { insert_positive_bound(input, constraint_matrix, right_side_array, i); } } } struct RemasteredInput remaster_basic_input(struct BasicInput input) { PointerArray new_constraint_matrix; initPointerArray(&new_constraint_matrix, 1); Array new_right_side_array; initArray(&new_right_side_array, 1); remake_right_side_matrix(&input, &new_constraint_matrix, &new_right_side_array); remake_bounds(&input, &new_constraint_matrix, &new_right_side_array); struct RemasteredInput output; output.coefficients = input.coefficients; output.coefficients_length = input.coefficients_length; output.constraint_matrix = new_constraint_matrix.array; output.constraint_matrix_length = (int) new_constraint_matrix.used; output.right_side_array = new_right_side_array.array; output.right_side_array_length = (int) new_right_side_array.used; return output; } Array get_obj_vector(int units, int zeroes) { Array obj; initArray(&obj, 1); for (int i = 0; i < units; ++i) { insertArray(&obj, 1); } for (int i = 0; i < zeroes; ++i) { insertArray(&obj, 0); } return obj; } float *multiply_matrix_and_vector(float **matrix, int matrix_length, int coefficients_length, float *vector, int vector_length, float *return_vector) { for (int i = 0; i < vector_length; ++i) { return_vector[i] = 0; } for (int i = 0; i < matrix_length; ++i) { for (int j = 0; j < coefficients_length; ++j) { return_vector[i] += matrix[i][j] * vector[j]; } } return return_vector; } PointerArray get_newA_matrix(float **constraint_matrix, int constraint_matrix_length, float *right_side_array, int right_side_array_length, int vars_length, Array B) { PointerArray newA_matrix; initPointerArray(&newA_matrix, 1); for (int i = 0; i < vars_length; ++i) { Array tmp_value; initArray(&tmp_value, 1); for (int j = 0; j < vars_length; ++j) { insertArray(&tmp_value, 0); } for (int j = 0; j < vars_length; ++j) { if (i == j) { insertArray(&tmp_value, -1); } else { insertArray(&tmp_value, 0); } } for (int j = 0; j < constraint_matrix_length; ++j) { bool inside_of_B = false; for (int k = 0; k < B.used; ++k) { if ((int) B.array[k] == j) { insertArray(&tmp_value, constraint_matrix[j][i]); inside_of_B = true; break; } } if (!inside_of_B) { inside_of_B = false; insertArray(&tmp_value, 0); } } insertPointerArray(&newA_matrix, tmp_value.array); } for (int i = 0; i < vars_length; ++i) { Array tmp_value1, tmp_value2; initArray(&tmp_value1, 1); initArray(&tmp_value2, 1); for (int j = 0; j < vars_length; ++j) { if (i == j) { insertArray(&tmp_value1, -1); } else { insertArray(&tmp_value1, 0); } } for (int j = 0; j < vars_length; ++j) { if (i == j) { insertArray(&tmp_value1, 1); } else { insertArray(&tmp_value1, 0); } } for (int j = 0; j < constraint_matrix_length; ++j) { insertArray(&tmp_value1, 0); } insertPointerArray(&newA_matrix, tmp_value1.array); for (int j = 0; j < vars_length; ++j) { if (i == j) { insertArray(&tmp_value2, 1); } else { insertArray(&tmp_value2, 0); } } for (int j = 0; j < vars_length; ++j) { if (i == j) { insertArray(&tmp_value2, 1); } else { insertArray(&tmp_value2, 0); } } for (int j = 0; j < constraint_matrix_length; ++j) { insertArray(&tmp_value2, 0); } insertPointerArray(&newA_matrix, tmp_value2.array); } return newA_matrix; } Array get_sense_vector(int vars_length) { Array sense; initArray(&sense, 1); for (int i = 0; i < vars_length; ++i) { insertArray(&sense, 0); } for (int i = 0; i < vars_length * 2; i += 2) { insertArray(&sense, -1); insertArray(&sense, 1); } return sense; } Array get_rhs_vector(float *coefficients, int vars_length) { Array rhs; initArray(&rhs, 1); for (int i = 0; i < vars_length; ++i) { insertArray(&rhs, 0); } for (int i = 0; i < vars_length; ++i) { insertArray(&rhs, coefficients[i]); insertArray(&rhs, coefficients[i]); } return rhs; } Array get_B(float **constraint_matrix, int constraint_matrix_length, int coefficients_length, float *right_side_array, int right_side_array_length, float *vector) { Array B; initArray(&B, 1); float multiply_result[constraint_matrix_length]; multiply_matrix_and_vector(constraint_matrix, constraint_matrix_length, coefficients_length, vector, right_side_array_length, multiply_result); for (int i = 0; i < constraint_matrix_length; ++i) { if (multiply_result[i] == right_side_array[i]) { insertArray(&B, (float) i); } } return B; } Array get_lb_vector(int vars_length, Array B, int matrix_length) { Array lb; initArray(&lb, 1); for (int i = 0; i < vars_length; ++i) { insertArray(&lb, 0); } for (int i = 0; i < vars_length; ++i) { insertArray(&lb, -inf); } for (int i = 0; i < matrix_length; ++i) { bool inside_of_B = false; for (int j = 0; j < B.used; ++j) { if (i == (int) B.array[j]) { insertArray(&lb, 0); inside_of_B = true; break; } } if (!inside_of_B) { insertArray(&lb, -inf); inside_of_B = false; } } return lb; } struct AnotherOneOutput function2(struct RemasteredInput input, struct FloatVector vector) { struct AnotherOneOutput output; output.vars_length = input.coefficients_length; output.constrs_length = input.constraint_matrix_length; Array obj = get_obj_vector(input.coefficients_length, input.constraint_matrix_length + input.coefficients_length); output.obj = obj.array; output.obj_length = 2 * input.coefficients_length + input.constraint_matrix_length; Array B = get_B(input.constraint_matrix, input.constraint_matrix_length, input.coefficients_length, input.right_side_array, input.right_side_array_length, vector.values); PointerArray newA = get_newA_matrix(input.constraint_matrix, input.constraint_matrix_length, input.right_side_array, input.right_side_array_length, input.coefficients_length, B); output.newA = newA.array; output.newA_length = 2 * input.coefficients_length + input.constraint_matrix_length; Array sense = get_sense_vector(input.coefficients_length); output.sense = sense.array; output.sense_length = 3 * input.coefficients_length; Array rhs = get_rhs_vector(input.coefficients, input.coefficients_length); output.rhs = rhs.array; output.rhs_length = input.coefficients_length * 3; Array lb = get_lb_vector(input.coefficients_length, B, input.constraint_matrix_length); output.lb = lb.array; output.lb_length = 2 * input.coefficients_length + input.constraint_matrix_length; return output; } Array get_obj_fun_coefficients(float *coefficients, int coefficients_length, int constrs_matrix_length) { Array obj_fun_coefficients; initArray(&obj_fun_coefficients, 1); for (int i = 0; i < coefficients_length; ++i) { insertArray(&obj_fun_coefficients, coefficients[i]); insertArray(&obj_fun_coefficients, -coefficients[i]); } for (int i = 0; i < constrs_matrix_length; ++i) { insertArray(&obj_fun_coefficients, 0); } return obj_fun_coefficients; } PointerArray get_constrs_matrix(float **constraint_matrix, int constraint_matrix_rows, int constraint_matrix_columns) { PointerArray constrs_matrix; initPointerArray(&constrs_matrix, 1); for (int i = 0; i < constraint_matrix_rows; ++i) { Array constrs_matrix_row; initArray(&constrs_matrix_row, 1); for (int j = 0; j < constraint_matrix_columns; ++j) { insertArray(&constrs_matrix_row, constraint_matrix[i][j]); insertArray(&constrs_matrix_row, -constraint_matrix[i][j]); } for (int j = 0; j < constraint_matrix_rows; ++j) { if (i == j) { insertArray(&constrs_matrix_row, -1); } else { insertArray(&constrs_matrix_row, 0); } } insertPointerArray(&constrs_matrix, constrs_matrix_row.array); } return constrs_matrix; } Array get_low_bounds(int vars, int constrs) { Array low_bounds; initArray(&low_bounds, 1); for (int i = 0; i < 2 * vars; ++i) { insertArray(&low_bounds, 0); } for (int i = 0; i < constrs; ++i) { insertArray(&low_bounds, 0); } return low_bounds; } struct CanonicalForm to_canonical_form(struct RemasteredInput input) { struct CanonicalForm output; Array obj_fun_coefficients = get_obj_fun_coefficients(input.coefficients, input.coefficients_length, input.constraint_matrix_length); output.obj_fun_coefficients = obj_fun_coefficients.array; output.obj_fun_coefficients_length = (int) obj_fun_coefficients.used; PointerArray constrs_matrix = get_constrs_matrix(input.constraint_matrix, input.constraint_matrix_length, input.coefficients_length); output.constrs_matrix = constrs_matrix.array; output.constrs_matrix_rows = (int) constrs_matrix.used; output.constrs_matrix_columns = (int) input.coefficients_length * 2 + input.constraint_matrix_length; output.right_hand_side = input.right_side_array; output.right_hand_side_length = input.right_side_array_length; Array low_bounds = get_low_bounds(input.coefficients_length, input.constraint_matrix_length); output.low_bounds = low_bounds.array; output.low_bounds_length = (int) low_bounds.used; return output; } float *get_zeroes_line(int length, float *line) { for (int i = 0; i < length; ++i) { line[i] = 0; } return line; } float *get_undefined_positions(float *vector, int vector_length) { Array positions; initArray(&positions, 1); for (int i = 0; i < vector_length; ++i) { if (vector[i] == undefined) { insertArray(&positions, (float) i); } } return positions.array; } int get_undefined_count(float *vector, int vector_length) { int count = 0; for (int i = 0; i < vector_length; ++i) { if (vector[i] == undefined) { ++count; } } return count; } float *get_defined_positions(float *vector, int vector_length) { Array positions; initArray(&positions, 1); for (int i = 0; i < vector_length; ++i) { if (vector[i] != undefined && vector[i] != 0.0) { insertArray(&positions, (float) i); } } return positions.array; } int get_defined_count(float *vector, int vector_length) { int count = 0; for (int i = 0; i < vector_length; ++i) { if (vector[i] != undefined && vector[i] != 0.0) { ++count; } } return count; } PointerArray get_constraint_matrix(float **matrix, int matrix_columns, int matrix_rows, float *undefined_positions, int undefined_positions_count, float *defined_positions, int defined_positions_count) { PointerArray constraint_matrix; initPointerArray(&constraint_matrix, 1); int c0_length = 3 * matrix_columns + matrix_rows; float *c0 = NULL; // 1 for (int i = 0; i < undefined_positions_count; ++i) { c0 = malloc(sizeof(float) * c0_length); get_zeroes_line(c0_length, c0); c0[matrix_columns + (int) undefined_positions[i]] = 1; c0[2 * matrix_columns + matrix_rows + (int) undefined_positions[i]] = -1 / BIG_DIGIT; insertPointerArray(&constraint_matrix, c0); } // 2 for (int i = 0; i < undefined_positions_count; ++i) { c0 = malloc(sizeof(float) * c0_length); get_zeroes_line(c0_length, c0); c0[matrix_columns + (int) undefined_positions[i]] = 1; c0[2 * matrix_columns + matrix_rows + (int) undefined_positions[i]] = -BIG_DIGIT; insertPointerArray(&constraint_matrix, c0); } // 3 for (int i = 0; i < defined_positions_count; ++i) { c0 = malloc(sizeof(float) * c0_length); get_zeroes_line(c0_length, c0); c0[(int) defined_positions[i]] = -1; for (int j = 2 * matrix_columns; j < 2 * matrix_columns + matrix_rows; ++j) { c0[j] = matrix[j - 2 * matrix_columns][(int) defined_positions[i]]; } insertPointerArray(&constraint_matrix, c0); } // 4 for (int i = 0; i < undefined_positions_count; ++i) { c0 = malloc(sizeof(float) * c0_length); get_zeroes_line(c0_length, c0); c0[(int) undefined_positions[i]] = -1; for (int j = 2 * matrix_columns; j < 2 * matrix_columns + matrix_rows; ++j) { c0[j] = matrix[j - 2 * matrix_columns][(int) undefined_positions[i]]; } c0[2 * matrix_columns + matrix_rows + (int) undefined_positions[i]] = BIG_DIGIT; insertPointerArray(&constraint_matrix, c0); } // 5 for (int i = 0; i < matrix_columns; ++i) { c0 = malloc(sizeof(float) * c0_length); get_zeroes_line(c0_length, c0); c0[i] = -1; for (int j = 2 * matrix_columns; j < 2 * matrix_columns + matrix_rows; ++j) { c0[j] = matrix[j - 2 * matrix_columns][i]; } insertPointerArray(&constraint_matrix, c0); } // 6 for (int i = 0; i < matrix_rows; ++i) { c0 = malloc(sizeof(float) * c0_length); get_zeroes_line(c0_length, c0); for (int j = 0; j <= undefined_positions_count; ++j) { c0[matrix_columns + (int) undefined_positions[j]] = matrix[i][(int) undefined_positions[j]]; } insertPointerArray(&constraint_matrix, c0); } // 7 for (int i = 0; i < undefined_positions_count; ++i) { c0 = malloc(sizeof(float) * c0_length); get_zeroes_line(c0_length, c0); c0[matrix_columns + (int) undefined_positions[i]] = 1; insertPointerArray(&constraint_matrix, c0); } // 8 for (int i = 0; i < defined_positions_count; ++i) { c0 = malloc(sizeof(float) * c0_length); get_zeroes_line(c0_length, c0); c0[matrix_columns + (int) defined_positions[i]] = 1; insertPointerArray(&constraint_matrix, c0); } return constraint_matrix; } PointerArray get_right_side(float **matrix, int matrix_columns, int matrix_rows, float *undefined_positions, int undefined_positions_count, float *defined_positions, int defined_positions_count, float *vector, float *right_side_array) { PointerArray right_side; initPointerArray(&right_side, 1); int c0_length = 2; float *c0 = NULL; // 1 for (int i = 0; i < undefined_positions_count; ++i) { c0 = malloc(sizeof(float) * c0_length); get_zeroes_line(c0_length, c0); c0[0] = 0; c0[1] = 1; insertPointerArray(&right_side, c0); } // 2 for (int i = 0; i < undefined_positions_count; ++i) { c0 = malloc(sizeof(float) * c0_length); get_zeroes_line(c0_length, c0); c0[0] = 0; c0[1] = -1; insertPointerArray(&right_side, c0); } // 3 for (int i = 0; i < defined_positions_count; ++i) { c0 = malloc(sizeof(float) * c0_length); get_zeroes_line(c0_length, c0); c0[0] = 0; c0[1] = 0; insertPointerArray(&right_side, c0); } // 4 for (int i = 0; i < undefined_positions_count; ++i) { c0 = malloc(sizeof(float) * c0_length); get_zeroes_line(c0_length, c0); c0[0] = BIG_DIGIT; c0[1] = -1; insertPointerArray(&right_side, c0); } // 5 for (int i = 0; i < matrix_rows; ++i) { c0 = malloc(sizeof(float) * c0_length); get_zeroes_line(c0_length, c0); c0[0] = 0; c0[1] = 1; insertPointerArray(&right_side, c0); } // 6 for (int i = 0; i < matrix_columns; ++i) { c0 = malloc(sizeof(float) * c0_length); get_zeroes_line(c0_length, c0); float k = 0; for (int j = 0; j < defined_positions_count; ++j) { k += matrix[j][i] * vector[(int) defined_positions[j]]; } c0[0] = right_side_array[i] - k; c0[1] = 1; insertPointerArray(&right_side, c0); } // 7 for (int i = 0; i < undefined_positions_count; ++i) { c0 = malloc(sizeof(float) * c0_length); get_zeroes_line(c0_length, c0); c0[0] = 0; c0[1] = 1; insertPointerArray(&right_side, c0); } // 8 for (int i = 0; i < defined_positions_count; ++i) { c0 = malloc(sizeof(float) * c0_length); get_zeroes_line(c0_length, c0); c0[0] = vector[(int) defined_positions[i]]; c0[1] = 0; insertPointerArray(&right_side, c0); } return right_side; } struct ToPartialProblemOutput to_partial_problem(struct ToPartialProblemInput input) { struct ToPartialProblemOutput output; int undefined_positions_count = get_undefined_count(input.vector, input.matrix_columns); float *undefined_positions = get_undefined_positions(input.vector, input.matrix_columns); int defined_positions_count = get_defined_count(input.vector, input.matrix_columns); float *defined_positions = get_defined_positions(input.vector, input.matrix_columns); PointerArray constraint_matrix; initPointerArray(&constraint_matrix, 1); constraint_matrix = get_constraint_matrix(input.matrix, input.matrix_columns, input.matrix_rows, undefined_positions, undefined_positions_count, defined_positions, defined_positions_count); PointerArray right_side; initPointerArray(&right_side, 1); right_side = get_right_side(input.matrix, input.matrix_columns, input.matrix_rows, undefined_positions, undefined_positions_count, defined_positions, defined_positions_count, input.vector, input.right_side_array); output.constraint_matrix = constraint_matrix.array; output.constraint_matrix_rows = (int) constraint_matrix.used; output.constraint_matrix_columns = 3 * input.matrix_columns + input.matrix_rows; output.right_side = right_side.array; output.right_side_rows = (int) right_side.used; output.right_side_columns = 2; output.nz = input.vector_length; output.nx = output.constraint_matrix_columns - output.nz; return output; } Array get_objfun_coeffs(int vars, int constrA) { Array objfun_coeffs; initArray(&objfun_coeffs, 4 * vars + 2 * constrA); for (int i = 0; i < 2 * vars + 2 * constrA; ++i) { insertArray(&objfun_coeffs, 0); } for (int i = 0; i < vars; ++i) { insertArray(&objfun_coeffs, 1); } for (int i = 0; i < vars; ++i) { insertArray(&objfun_coeffs, 0); } return objfun_coeffs; } PointerArray get_constrs_matrix_MPEC(float **matrixA, int matrixA_rows, int matrixA_columns, float **matrixB, int matrixB_rows, int matrixB_columns, float **matrixC, int matrixC_rows, int matrixC_columns) { PointerArray constrs_matrix; initPointerArray(&constrs_matrix, 1); // 1 for (int i = 0; i < matrixA_rows; ++i) { Array constrs_matrix_row; initArray(&constrs_matrix_row, 1); for (int j = 0; j < matrixA_columns; ++j) { insertArray(&constrs_matrix_row, matrixA[i][j]); } for (int j = 0; j < matrixA_rows; ++j) { if (i == j) { insertArray(&constrs_matrix_row, -1); } else { insertArray(&constrs_matrix_row, 0); } } for (int j = 0; j < 3 * matrixA_columns + matrixA_rows; ++j) { insertArray(&constrs_matrix_row, 0); } insertPointerArray(&constrs_matrix, constrs_matrix_row.array); } // 2 for (int i = 0; i < matrixA_columns; ++i) { Array constrs_matrix_row1; Array constrs_matrix_row2; initArray(&constrs_matrix_row1, 1); initArray(&constrs_matrix_row2, 1); for (int j = 0; j < matrixA_rows + matrixA_columns; ++j) { insertArray(&constrs_matrix_row1, 0); insertArray(&constrs_matrix_row2, 0); } for (int j = 0; j < matrixA_rows; ++j) { insertArray(&constrs_matrix_row1, matrixA[j][i]); insertArray(&constrs_matrix_row2, matrixA[j][i]); } for (int j = 0; j < matrixA_columns; ++j) { if (i == j) { insertArray(&constrs_matrix_row1, -1); insertArray(&constrs_matrix_row2, -1); } else { insertArray(&constrs_matrix_row1, 0); insertArray(&constrs_matrix_row2, 0); } } // constrs_matrix_row1 for (int j = 0; j < 2 * matrixA_columns; ++j) { insertArray(&constrs_matrix_row1, 0); } // constrs_matrix_row2 for (int j = 0; j < matrixA_columns; ++j) { insertArray(&constrs_matrix_row2, 0); } for (int j = 0; j < matrixA_columns; ++j) { if (i == j) { insertArray(&constrs_matrix_row2, inf); } else { insertArray(&constrs_matrix_row2, 0); } } insertPointerArray(&constrs_matrix, constrs_matrix_row1.array); insertPointerArray(&constrs_matrix, constrs_matrix_row2.array); } // 3 for (int i = 0; i < matrixA_columns; ++i) { Array constrs_matrix_row; initArray(&constrs_matrix_row, 1); for (int j = 0; j < matrixA_columns; ++j) { if (i == j) { insertArray(&constrs_matrix_row, 1); } else { insertArray(&constrs_matrix_row, 0); } } for (int j = 0; j < 2 * matrixA_rows + 2 * matrixA_columns; ++j) { insertArray(&constrs_matrix_row, 0); } for (int j = 0; j < matrixA_columns; ++j) { if (i == j) { insertArray(&constrs_matrix_row, -inf); } else { insertArray(&constrs_matrix_row, 0); } } insertPointerArray(&constrs_matrix, constrs_matrix_row.array); } // 4 for (int i = 0; i < matrixB_rows; ++i) { Array constrs_matrix_row; initArray(&constrs_matrix_row, 1); for (int j = 0; j < matrixA_columns; ++j) { insertArray(&constrs_matrix_row, 0); } for (int j = 0; j < matrixB_columns; ++j) { insertArray(&constrs_matrix_row, matrixB[i][j]); } for (int j = 0; j < 3 * matrixA_columns + matrixA_rows; ++j) { insertArray(&constrs_matrix_row, 0); } insertPointerArray(&constrs_matrix, constrs_matrix_row.array); } // 5 for (int i = 0; i < matrixC_rows; ++i) { Array constrs_matrix_row; initArray(&constrs_matrix_row, 1); for (int j = 0; j < 2 * matrixA_rows + matrixA_columns; ++j) { insertArray(&constrs_matrix_row, 0); } for (int j = 0; j < matrixC_columns; ++j) { insertArray(&constrs_matrix_row, matrixC[i][j]); } for (int j = 0; j < 2 * matrixA_columns; ++j) { insertArray(&constrs_matrix_row, 0); } insertPointerArray(&constrs_matrix, constrs_matrix_row.array); } // 6 for (int i = 0; i < matrixA_columns; ++i) { Array constrs_matrix_row1; Array constrs_matrix_row2; initArray(&constrs_matrix_row1, 1); initArray(&constrs_matrix_row2, 1); for (int j = 0; j < matrixA_columns; ++j) { if (i == j) { insertArray(&constrs_matrix_row1, 1); insertArray(&constrs_matrix_row2, 1); } else { insertArray(&constrs_matrix_row1, 0); insertArray(&constrs_matrix_row2, 0); } } for (int j = 0; j < 2 * matrixA_rows + matrixA_columns; ++j) { insertArray(&constrs_matrix_row1, 0); insertArray(&constrs_matrix_row2, 0); } for (int j = 0; j < matrixA_columns; ++j) { if (i == j) { insertArray(&constrs_matrix_row1, -1); insertArray(&constrs_matrix_row2, 1); } else { insertArray(&constrs_matrix_row1, 0); insertArray(&constrs_matrix_row2, 0); } } for (int j = 0; j < matrixA_columns; ++j) { insertArray(&constrs_matrix_row1, 0); insertArray(&constrs_matrix_row2, 0); } insertPointerArray(&constrs_matrix, constrs_matrix_row1.array); insertPointerArray(&constrs_matrix, constrs_matrix_row2.array); } return constrs_matrix; } Array get_sense_array(int matrixA_rows, int matrixA_columns, int matrixB_rows, int matrixC_rows) { Array sense_array; initArray(&sense_array, 1); for (int i = 0; i < matrixA_rows; ++i) { insertArray(&sense_array, 0); } for (int i = 0; i < matrixA_columns; ++i) { insertArray(&sense_array, 1); insertArray(&sense_array, -1); } for (int i = 0; i < matrixA_columns; ++i) { insertArray(&sense_array, -1); } for (int i = 0; i < matrixB_rows; ++i) { insertArray(&sense_array, 1); } for (int i = 0; i < matrixC_rows; ++i) { insertArray(&sense_array, 1); } for (int i = 0; i < matrixA_columns; ++i) { insertArray(&sense_array, 1); insertArray(&sense_array, -1); } return sense_array; } Array get_right_hand_side(int matrixA_rows, int matrixA_columns, float *vector_x0, int vector_x0_length, float *vector_b, int vector_b_length, float *vector_c, int vector_c_length) { Array right_hand_side; initArray(&right_hand_side, 1); for (int i = 0; i < matrixA_rows + matrixA_columns; ++i) { insertArray(&right_hand_side, 0); } for (int i = 0; i < matrixA_columns; ++i) { insertArray(&right_hand_side, inf); } for (int i = 0; i < matrixA_columns; ++i) { insertArray(&right_hand_side, 0); } for (int i = 0; i < vector_b_length; ++i) { insertArray(&right_hand_side, vector_b[i]); } for (int i = 0; i < vector_c_length; ++i) { insertArray(&right_hand_side, vector_c[i]); } for (int i = 0; i < vector_x0_length; ++i) { insertArray(&right_hand_side, vector_x0[i]); insertArray(&right_hand_side, vector_x0[i]); } return right_hand_side; } PointerArray get_bounds(int matrixA_rows, int matrixA_columns) { PointerArray bounds; initPointerArray(&bounds, 1); for (int i = 0; i < matrixA_columns; ++i) { Array bounds_row; initArray(&bounds_row, 1); insertArray(&bounds_row, 0); insertArray(&bounds_row, inf); insertPointerArray(&bounds, bounds_row.array); } for (int i = 0; i < 2 * matrixA_rows + matrixA_columns; ++i) { Array bounds_row; initArray(&bounds_row, 1); insertArray(&bounds_row, -inf); insertArray(&bounds_row, inf); insertPointerArray(&bounds, bounds_row.array); } for (int i = 0; i < matrixA_columns; ++i) { Array bounds_row; initArray(&bounds_row, 1); insertArray(&bounds_row, 0); insertArray(&bounds_row, inf); insertPointerArray(&bounds, bounds_row.array); } for (int i = 0; i < matrixA_columns; ++i) { Array bounds_row; initArray(&bounds_row, 1); insertArray(&bounds_row, 0); insertArray(&bounds_row, 1); insertPointerArray(&bounds, bounds_row.array); } return bounds; } struct MPEC_solver_output solve_inverse_via_MPEC(struct MPEC_solver_input input) { struct MPEC_solver_output output; Array objfun_coeffs; objfun_coeffs = get_objfun_coeffs(input.vector_x0_length, input.matrixA_rows); output.objfun_coeffs = objfun_coeffs.array; output.objfun_coeffs_length = (int) objfun_coeffs.used; PointerArray constrs_matrix; initPointerArray(&constrs_matrix, 1); constrs_matrix = get_constrs_matrix_MPEC(input.matrixA, input.matrixA_rows, input.matrixA_columns, input.matrixB, input.matrixB_rows, input.matrixB_columns, input.matrixC, input.matrixC_rows, input.matrixC_columns); output.constrs_matrix = constrs_matrix.array; output.constrs_matrix_rows = (int) constrs_matrix.used; output.constrs_matrix_columns = 2 * input.matrixA_rows + 4 * input.matrixA_columns; Array sense_array; initArray(&sense_array, 1); sense_array = get_sense_array(input.matrixA_rows, input.matrixA_columns, input.matrixB_rows, input.matrixC_rows); output.sense_array = sense_array.array; output.sense_array_length = (int) sense_array.used; Array right_hand_side; initArray(&right_hand_side, 1); right_hand_side = get_right_hand_side(input.matrixA_rows, input.matrixA_columns, input.vector_x0, input.vector_x0_length, input.vector_b, input.vector_b_length, input.vector_c, input.vector_c_length); output.right_hand_side = right_hand_side.array; output.right_hand_side_length = (int) right_hand_side.used; PointerArray bounds; initPointerArray(&bounds, 1); bounds = get_bounds(input.matrixA_rows, input.matrixA_columns); output.bounds = bounds.array; output.bounds_rows = 2 * input.matrixA_rows + 4 * input.matrixA_columns; output.bounds_columns = 2; output.nbin = input.vector_x0_length; output.nx = output.constrs_matrix_columns - output.nbin; return output; } struct P_matrix get_P_matrix(int n, int m) { struct P_matrix p; PointerArray matrix; initPointerArray(&matrix, 1); for (int i = 0; i < 3 * n + m; ++i) { Array row; initArray(&row, 1); for (int j = 0; j < 3 * n + m; ++j) { insertArray(&row, 0); } insertPointerArray(&matrix, row.array); } for (int i = 0; i < n; ++i) { matrix.array[i][i + n] = 1; } p.matrix = matrix.array; p.matrix_side = 3 * n + m; return p; }
C
#include <stdio.h> #include <stdlib.h> #include "lang_oop_coordinates.h" /* * Author : Diego Pacheco * DataStructure : Language-C * Problem : OOP * Complexity : - * Source : - */ static void coordinate_setx(Coordinate *this, int x){ if (this!=NULL){ this->x=x; } } static void coordinate_sety(Coordinate *this, int y){ if (this!=NULL){ this->y=y; } } static void coordinate_print(Coordinate *this){ if (this!=NULL){ printf("Coordinate[x: %d, y: %d]\n", this->x,this->y); }else{ printf("Coordinate is NULL\n"); } } Coordinate *newCoordinate(void){ Coordinate *c = malloc(sizeof(Coordinate)); if(c!=0){ c->setx = &coordinate_setx; c->sety = &coordinate_sety; c->print = &coordinate_print; c->x = 0; c->y = 0; } return c; } void destroyCoordinate(Coordinate *this){ if(this!=NULL){ free(this); } }
C
// // AVL树.c // C数据结构与算法学习 // // Created by 冯才凡 on 2019/11/8. // Copyright © 2019 冯才凡. All rights reserved. // #include "AVL树.h" #include <stdlib.h> #define Max(x,y) ((x)>(y) ? (x) : (y)); /* 单旋、双旋: https://juejin.im/post/5d62064c6fb9a06b2c329a6f */ // 返回节点高度 int avlHeight(AVLPosition P) { if (NULL == P) { return -1; }else{ return P->height; } } /* P节点是检测出的不平衡节点: P有个左子树P->left, 左子树右旋:就是将P作为P->left的右子树,将P->left顶替掉P的位置。 注意2点:1、两个节点也是可以直接旋转的,因为没有大小比较, 2、不需要管整个过程是否平衡,因为这是调用之前判断的 Left表示将要旋转的子树 */ AVLTree singleRReroteWithLeft(AVLPosition P) { AVLPosition left; left = P->left; P->left = left->right; //将left原来的右子树当做P的左子树 left->right = P; left->height = 1 + Max(avlHeight(left->left), avlHeight(left->right)); P->height = 1 + Max(avlHeight(P->left), avlHeight(P->right)); return left; } /* P节点是检测出的不平衡节点: P有个右子树P->right, 右子树左旋:就是将P作为P->right的左子树,将P->left顶替掉P的位置。 同理注意2点:1、两个节点也是可以直接旋转的,因为没有大小比较, 2、不需要管整个过程是否平衡,因为这是调用之前判断的 Right表示将要旋转的子树 */ AVLTree singleLReroteWiithRight(AVLPosition P) { AVLPosition right; right = P->right; P->right = right->left; //将right原来的左子树当做P的右子树 right->left = P; right->height = 1 + Max(avlHeight(right->left), avlHeight(right->right)); P->height = 1 + Max(avlHeight(P->left), avlHeight(P->right)); return right; } /* P节点是检测出的不平衡节点, P有个左子树,P的左子树p->left有一个右子树, 双旋转:先p->left的右子树P->left->right左旋,再P树右旋 Left表示将要旋转的子树 */ AVLTree DoubleReroteWithLeft(AVLPosition P) { P->left = singleLReroteWiithRight(P->left); return singleRReroteWithLeft(P); } /* P节点是检测出的不平衡节点, P有个右子树,P的右子树p->right有一个左子树, 双旋转:先p->right的左子树P->right->left右旋,再P树左旋 Right表示将要旋转的子树 */ AVLTree DoubleReroteWithRight(AVLPosition P) { P->right = singleRReroteWithLeft(P->right); return singleLReroteWiithRight(P); } AVLTree avlMakeEmpty(AVLTree T) { if (NULL != T) { avlMakeEmpty(T->left); avlMakeEmpty(T->right); free(T); } return NULL; } // AVLPosition avlFind(AVLElement X, AVLTree T) { if (X < T->element) { avlFind(X, T->left); }else if (X > T->element) { avlFind(X, T->right); }else if (X == T->element) { AVLPosition temp; temp = T; return temp; } return NULL; } // 最小值肯定是一直往左子树查找 AVLPosition avlFindMin(AVLTree T) { if (NULL != T) { if (NULL != T->left) { avlFindMin(T->left); }else{ return T; } } return NULL; } // 最大值肯定是一直往右子树查找 AVLPosition avlFindMax(AVLTree T) { if(NULL != T) { if (NULL != T->right) { avlFindMax(T); }else{ return T; } } return NULL; } /* 先进行插入,然后再调整平衡 */ AVLTree avlInSert(AVLElement X, AVLTree T) { if (NULL == T) { T = malloc(sizeof(struct AVLTreeNode)); if (NULL == T) { return NULL; }else{ T->element = X; T->height = 0; T->left = T->right = NULL; } }else if (X < T->element) { // 先插入,再旋转, 且这里肯定是插入在左子树的 T->left = avlInSert(X, T->left); if (avlHeight(T->left) - avlHeight(T->right) == 2) { //当递归回溯到这个节点时就可以进行旋转调整平衡了 if (X < T->left->element) { //插入的节点是在左子树上,则以T->left为原点,将T节点右旋(注意旋转之后将T->left的右节点当做T的左节点使用) T = singleRReroteWithLeft(T); }else{ T = DoubleReroteWithLeft(T); } } }else if (X > T->element) { // T->right = avlInSert(X, T->right); if (avlHeight(T->right) - avlHeight(T->left) == 2) { if (X > T->left->element) { T = singleLReroteWiithRight(T); }else{ T = DoubleReroteWithRight(T); } } } T->height = 1 + Max(avlHeight(T->left), avlHeight(T->right)); return T; } /* 同理删除,先删除,再调整平衡。但是删除的话,同样要借助FindMin函数来替换掉 这里可以简单地画图进行实践。 */ AVLTree avlDelete(AVLElement X, AVLTree T) { if ( NULL == T) { return NULL; }else if (X < T->element) { // 删除的是左子树节点。 T->left = avlDelete(X, T->left); // 删完左子树上的节点后,左子树高度降低。所以应该调整右子树 if (avlHeight(T->right) - avlHeight(T->left) == 2) { AVLTree temp = T->right; //子树的左子树高于右子树,则需要对T进行一次双旋转,让其回到平衡状态; //子树的左子树低于右子树,则直接对T进行一次右子树左旋就可以了。 if (avlHeight(temp->left) > avlHeight(temp->right)) { T = DoubleReroteWithRight(T); }else{ T = singleLReroteWiithRight(T); } } }else if (X > T->element) { //删除的是右子树上的节点 T->right = avlDelete(X, T->right); // 删除右子树节点后,右子树节点高度肯定小于等于左子树高度。所以应该调整左子树 if (avlHeight(T->left) - avlHeight(T->right) == 2) { AVLTree temp = T->left; //子树的右子树高于左子树,则需要对T进行一次双旋转,让其回到平衡状态; //子树的右子树低于左子树,则直接对T进行一次左子树右旋就可以了。 if (avlHeight(temp->right) > avlHeight(temp->left)) { T = DoubleReroteWithLeft(T); }else{ T = singleLReroteWiithRight(T); } } }else if (T->left && T->right) { /* 找的节点是有左右子树的话 如果是左子树高度小于右子树,则用右子树的最小值替换当前节点,然后再去删除最小节点; 如果是左子树高度大于右子树,则用左子树的最大值替换当前节点,然后再去删除最大节点。 */ if (avlHeight(T->left) < avlHeight(T->right)) { //左子树比右子树低,将右子树的最小值代替root AVLPosition tempCell = avlFindMin(T->right); T->element = tempCell->element; T->right = avlDelete(T->element, T->right); }else { //左子树比右子树高,将左子树的最大值代替root AVLPosition temp = avlFindMax(T->left); T->element = temp->element; T->left = avlDelete(T->element, T->left); } }else{ /* 找到的节点是叶子节点或者只有一个子树的节点,则直接用子树替换当期节点,然后free。 */ AVLPosition tempCell = T; if (T->left == NULL) { T = T->right; }else if (T->right == NULL){ T = T->left; } free(tempCell); } T->height = 1 + Max(avlHeight(T->left), avlHeight(T->right)); return T; } // 检索 AVLElement avlRetrieve(AVLPosition P) { return P->element; }
C
#include <stdio.h> #include <stdlib.h> #include "LinkedList.h" #include "Controller.h" #include "Employee.h" #include "menu.h" /**************************************************** Menu: 1. Cargar los datos de los empleados desde el archivo data.csv (modo texto). 2. Cargar los datos de los empleados desde el archivo data.bin (modo binario). 3. Alta de empleado 4. Modificar datos de empleado 5. Baja de empleado 6. Listar empleados 7. Ordenar empleados 8. Guardar los datos de los empleados en el archivo data.csv (modo texto). 9. Guardar los datos de los empleados en el archivo data.bin (modo binario). 10. Salir *****************************************************/ #define PATH_FILE_LAST_ID "last_id.bin" int main() { setbuf(stdout, NULL); int option; int result; int nextId = 1; int lenPath = 150; char path[lenPath]; //int auxNextId; LinkedList* listEmployees = ll_newLinkedList(); if (listEmployees == NULL){ puts("No se pudo iniciar la lista"); exit(EXIT_FAILURE); } //employee_restoreLastId(PATH_FILE_LAST_ID, &nextId); do{ option = menu(); switch(option) { case optMainLoadEmployeesTextFile: controller_loadNameOfFile(path, lenPath); result = controller_loadFromText(path, listEmployees); if (result == 1){ employee_findHighestId(listEmployees, &nextId); puts("Se cargaron los datos desde el archivo"); } else if (result == 2){ puts("Carga de datos cancelada por el usuario"); } else if(result == 3){ puts("No se pudo leer el archivo, asegurese de que exista"); } else{ puts("Ocurrio un error al cargar los datos del archivo"); } break; case optMainLoadEmployeesBinaryFile: controller_loadNameOfFile(path, lenPath); result = controller_loadFromBinary(path, listEmployees); if (result == 1){ employee_findHighestId(listEmployees, &nextId); puts("Se cargaron los datos desde el archivo"); } else if (result == 2){ puts("Carga de datos cancelada por el usuario"); } else if(result == 3){ puts("No se pudo leer el archivo, asegurese de que exista"); } else{ puts("Ocurrio un error al cargar los datos del archivo"); } break; case optMainRegisterEmployee: result = controller_addEmployee(listEmployees, &nextId); if (result == 1){ puts("Alta exitosa"); } else{ puts("No se pudo dar de alta el empleado"); } break; case optMainEditEmployee: if (ll_isEmpty(listEmployees)){ puts("NO hay empleados cargados en el sistema"); } else{ result = controller_editEmployee(listEmployees); if (result){ puts("Exito al modificar los datos del empleado"); } else{ puts("Ocurrio un error al modificar el empleado"); } } break; case optMainDeleteEmployee: if (ll_isEmpty(listEmployees)){ puts("NO hay empleados cargados en el sistema"); } else{ result = controller_removeEmployee(listEmployees); if (result == 1){ puts("Exito al eliminar al empleado"); } else if (result == 2){ puts("Eliminacion cancelada por el usuario"); } else{ puts("Ocurrio un error al eliminar el empleado"); } } break; case optMainReportEmployees: if (ll_isEmpty(listEmployees)){ puts("NO hay empleados cargados en el sistema"); } else{ result = controller_ListEmployee(listEmployees); if (!result){ puts("Ocurrio un error al mostrar empleados"); } } break; case optMainSortEmployees: if (ll_isEmpty(listEmployees)){ puts("NO hay empleados cargados en el sistema"); } else{ result = controller_sortEmployee(listEmployees); if (result == 1){ puts("Empleados ordenados"); } else if (result == 2){ puts("No se selecciono metodo de ordenamiento"); } else{ puts("Ocurrio un error al ordenar los empleados"); } } break; case optMainSaveEmployeesTextFile: if (!ll_isEmpty(listEmployees)){ controller_loadNameOfFile(path, lenPath); result = controller_saveAsText(path, listEmployees); if (result){ if (result == 1){ printf("Empleados guardados con exito en el archivo: %s\n", path); } else if(result == 5){ puts("Guardado cancelado por el usuario"); } else{ puts("Ocurrio un error al intentar guardar el archivo"); } } else{ puts("Ocurrio un error, datos no validos para guardar el archivo"); } } else{ puts("No hay empleados para guardar en el archivo"); } break; case optMainSaveEmployeesBinaryFile: if (!ll_isEmpty(listEmployees)){ controller_loadNameOfFile(path, lenPath); result = controller_saveAsBinary(path, listEmployees); if (result){ if (result == 1){ printf("Empleados guardados con exito en el archivo: %s\n", path); } else if(result == 5){ puts("Guardado cancelado por el usuario"); } else{ puts("Ocurrio un error al intentar guardar el archivo"); } } else{ puts("Ocurrio un error, datos no validos para guardar el archivo"); } } else{ puts("No hay empleados para guardar en el archivo"); } break; case optMainExitMenu: break; default: puts("Opcion invalida"); break; } puts("\n"); } while(option != optMainExitMenu); ll_deleteLinkedList(listEmployees); puts("FIN DEL PROGRAMA"); return EXIT_SUCCESS; }
C
#include <stdio.h> #include <stdlib.h> void inizializzaArrayRandom(double v[], int dim, double max_value); void vec_print(double v[], int dim); void vec_print(double v[], int dim); double* vec_sum(double v[], int dim); double* vec_rec(double v1[], double v2[], int dim1, int dim2); int main(int argc, char **argv) { int dim1 = 10; double max_value = 10; //double v1[dim1]; //inizializzaArrayRandom(v1, dim1, max_value); //printf("dim1=%d\nmax_value=%lf\n",dim1, max_value); printf("\n"); /******************************************************** * TEST inizializzaArrayRandom * ********************************************************/ printf("Inizializzo l'array con numeri random..."); double v1[dim1]; inizializzaArrayRandom(v1, dim1, max_value); printf(" done.\n\n"); /******************************************************** * TEST vec_print v1 * ********************************************************/ printf("v1: "); vec_print(v1, dim1); printf("\n\n"); /******************************************************** * TEST allocate vectors * ********************************************************/ /*printf("Alloco il vettore v2...\n"); printf("Alloco il vettore v3...\n"); printf("v2: "); vec_print(v2, dim2); printf("\n"); // printf("v3: "); vec_print(v3, dim3); printf("\n\n"); */ /******************************************************** * TEST vec_sum v3 * ********************************************************/ /*printf("Calcolo il vettore somma...\n\n"); double *sum = vec_sum(v3, dim3); vec_print(sum, dim3); printf("\n"); free(sum); */ /******************************************************** * TEST vec_rec v3 * ********************************************************/ /*printf("Calcolo il vettore v3 a meno delle ricorrenze dei valori in v4...\n\n"); double* v4=( double *) malloc (dim3*sizeof(double)); v4[0]= 4.8; v4[1]= 0.5; v4[2]= -4.2; v4[3]= -2.5; v4[4]= 2.3; double *v2_rec = vec_rec(v3, v4, dim2, dim3); vec_print(v2_rec, dim3); printf("\n"); free(v2_rec); */ return 0; } void inizializzaArrayRandom(double v[], int dim, double max_value) { srand(3); int i; for (i=0;i<dim;i++){ v[i]=rand() % 10; } } // da qui in poi definire le funzioni chiamate nel main. void vec_printf(double v[],int dim){ for (int i=0;i<dim;i++){ printf("lf\n",v[i]); } return; }
C
#include "ds/queue_array.h" #include <stdio.h> #include <stdlib.h> #include <string.h> void enqueue(Queue_Array* queue, void* value) { if (queue == NULL) { printf("error: queue doesn't exists. please create one before enqueueing.\n"); return; } queue->rear++; if (queue->front == -1) queue->front++; alloc_buffer(queue); queue->copy_value_to_node(queue, value); } void* dequeue(Queue_Array* queue, void* buffer) { if (queue == NULL) { printf("error: queue doesn't exists. please create one before enqueueing.\n"); return NULL; } if (queue->front == -1) { printf("error: queue is empty. please enqueue something.\n"); return NULL; } free_buffer(queue); queue->copy_value_to_buffer(buffer, queue); if (queue->front == queue->rear) { queue->front = -1; queue->rear = -1; } else queue->front++; return buffer; } void print_queue(Queue_Array* queue) { if (queue == NULL) { printf("error: queue doesn't exists. please create one before enqueueing.\n"); return; } if (queue->front == -1) { printf("error: queue is empty. please enqueue something.\n"); return; } for (int i = queue->front; i <= queue->rear; i++) { queue->print_node_value(queue, i); printf(" <= "); } printf("\n\n"); }
C
#include "gui/window.h" #include <stdlib.h> #include <stdio.h> #include <assert.h> #include "input/input.h" #define GLV_MAJOR 3 #define GLV_MINOR 3 #define WINDEF_TITLE "[NEW DOCUMENT]" /** window_t is a wrapper around the GLFWwindow with some additional data.*/ struct window_t { uint flags; GLFWwindow* gwin; /**< glfw window handle*/ int width; /**< width of the window in px*/ int height; /**< height of the window in px*/ strbuf title; /**< title of the window titlebar*/ int shouldclose; /**< window close flag*/ // TODO use flags instead. document* doc; /**< document attached to window */ }; /** Internal glfw error callback */ static void _win_glfw_onerror(int error, const char* desc) { printf("E: %s: code=%d: %s.\n", __func__, error, desc); // TODO should abort here? } /** Internal glfw key callback */ static void _win_glfw_keycb(GLFWwindow* gwin, int key, __attribute__((unused)) int scancode, int action, int mods) { inp_onkey(glfwGetWindowUserPointer(gwin), key, action, mods); } /** Initialize glfw and set gl hints/flags*/ static int _win_initglfw() { /* Initialize the library */ if(! glfwInit()) { printf("E: %s: Failed to init GLFW.\n", __func__); return 1; } glfwSetErrorCallback(_win_glfw_onerror); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, GLV_MAJOR); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, GLV_MINOR); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); return 0; } /** Create a glfw window. * Note: Creating multile windows is NOT supported right now. * \return glfw window handle * //TODO ensure that this is called only once! */ static GLFWwindow* _win_create_glfwwindow(uint width, uint height, strbuf* title) { /* Create a windowed mode window and its OpenGL context */ char* titlec = sb_create_cstr(title); GLFWwindow* window = glfwCreateWindow(width, height, titlec, NULL, NULL); sb_destroy_cstr(titlec); if (!window) { printf("E: %s: Failed to create glfw window.\n", __func__); glfwTerminate(); exit(1); } /* Make the window's context current */ glfwMakeContextCurrent(window); if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { printf("E: %s:Failed to init glad!\n", __func__); exit(1); } /* Set key callback */ glfwSetKeyCallback(window, _win_glfw_keycb); return window; } int win_initmodule() { return _win_initglfw(); } window* win_create(uint width, uint height) { window* win = malloc(sizeof(window)); win->flags = 0; win->gwin = NULL; win->width = width; win->height = height; win->title = sb_createfrom_str(WINDEF_TITLE); win->shouldclose = 0; win->doc = NULL; win->gwin = _win_create_glfwwindow(win->width, win->height, &win->title); flag_set(&win->flags, f_init); // Set window pointer glfwSetWindowUserPointer(win->gwin, win); return win; } void win_destroy(window* win) { assert(win != NULL); if(flag_isset(win->flags, f_dead)) { printf("E: %s: Double destroy.\n", __func__); return; } sb_destroy(&win->title); // Glfw stuff glfwDestroyWindow(win->gwin); glfwTerminate(); // Set flags flag_unset(&win->flags, f_init); flag_set(&win->flags, f_dead); win = NULL; printf("%s: window destoryed.\n", __func__); } void win_settitle(window* win, strbuf title) { win->title = title; char* titlec = sb_create_cstr(&title); glfwSetWindowTitle(win->gwin, titlec); sb_destroy_cstr(titlec); } void win_update(window* win) { GLFWwindow* gwin = win->gwin; // Check for close flags if(win->shouldclose == 1) { printf("%s: window close flag set.\n", __func__); glfwSetWindowShouldClose(gwin, GLFW_TRUE); } // Update window and framebuffer sizes { int width, height; glfwGetWindowSize(gwin, &width, &height); win->width = width; win->height = height; glViewport(0, 0, width, height); } // Swap buffers glfwSwapBuffers(win->gwin); } void win_clear(__attribute__((unused)) window* win) { glClearColor(255, 255, 255, 255); glClear(GL_COLOR_BUFFER_BIT); } // Makes the thread sleep and resumes it on events void win_waitevents() { glfwWaitEvents(); } void win_setclose(window* win, int val) { win->shouldclose = val; } int win_shouldclose(const window* win) { return win->shouldclose || glfwWindowShouldClose(win->gwin); } void win_setdoc(window* win, document* doc) { assert(win && doc); win->doc = doc; } inline document* win_getdoc(const window* win) { assert(win); return win->doc; }
C
#include "seqlist.h" int main(void) { seq_plist l; datatype data; int ret; l = init_seqlist(); //初始化顺序表 while(1){ printf("请输入整数:"); ret = scanf("%d",&data); if(ret == 0) //输入为字符 break; else if(data > 0){ //输入为正整数 insert_seqlist(data,l); show_seqlist(l); }else{ //输入为负整数 del_seqlist(-data,l); show_seqlist(l); } } return 0; } seq_plist init_seqlist(void) { seq_plist p; p = (seq_plist)malloc(sizeof(seq_list)); if(p == NULL){ perror("malloc"); exit(1); } p->last = -1; return p; } bool full_seqlist(seq_plist l) { if(l->last == SIZE-1) return true; else return false; } void insert_seqlist(datatype data,seq_plist l) { int i,j; if(full_seqlist(l)){ printf("The seqlist is full!\n"); return; } //寻找插入的位置 for(i = 0; i <= l->last;i++) if(data < l->data[i]) break; //向后移动后面的数据 for(j = l->last; j >= i; j--) l->data[j+1] = l->data[j]; //插入新数据 l->data[i] = data; //last++ l->last++; return; } bool empty_seqlist(seq_plist l) { if(l->last == -1) return true; else return false; } void del_seqlist(datatype data,seq_plist l) { int i,j; if(empty_seqlist(l)){ printf("The seqlist is empty!\n"); return; } //寻找要删除的数据 for(i = 0; i <= l->last; i++) if(data == l->data[i]) break; //向前移动后面的数据 if(i > l->last){ //data不存在 printf("%d is not in seqlist!\n",data); return ; }else{ for(j = i; j < l->last; j++) l->data[j] = l->data[j+1]; } //将 last-- l->last--; } void show_seqlist(seq_plist l) { int i; for(i = 0; i <= l->last;i++) printf("%d\t",l->data[i]); printf("\n"); }
C
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <glob.h> #define PAT "abcd" int main() { glob_t globres; int i,err; err = glob(PAT, GLOB_NOCHECK, NULL, &globres); if(err) { printf("ERROR CODE:%d\n",err); exit(1); } printf("globres.gl_pathc = %ld\n",globres.gl_pathc); for(i = 0 ; i < globres.gl_pathc ; i++) { puts(globres.gl_pathv[i]); } globfree(&globres); exit(0); }
C
bool isprime(int n) { if(n==2)return true; else if(n%2==0)return false; for(int i=3;i*i<=n;i+=2)if(n%i==0)return false; return true; }
C
/*while do_while 循环语句*/ #include <stdio.h> int main(void) { int a = 100; while (a > 1) //while(判断条件),True——执行下程序段,False——跳过 { printf("%d>1\n", a); a = a - 1; } do //do_while :至少执行一次循环,之后再判断while { printf("a=%d\n", a); a = a + 1; } while (a < 100); //注意分号 return 0; }
C
#include "bitvector.h" #include <string.h> static unsigned int getIndex(unsigned int bitnum) { return bitnum / ELEMENT_SIZE; } static unsigned int getMask(unsigned int bitnum) { return 1 << (bitnum % ELEMENT_SIZE); } void vBitVectorClearAll(bitvector_t* vector) { memset((void*) vector, 0, sizeof(bitvector_t)); } void vBitVectorSetAll(bitvector_t* vector) { memset((void*) vector, 255, sizeof(bitvector_t)); } char cBitVectorGet(bitvector_t* vector, unsigned int bitnum) { return (vector->m_bits[getIndex(bitnum)] & getMask(bitnum)) ? 1 : 0; } void vBitVectorSet(bitvector_t* vector, unsigned int bitnum) { vector->m_bits[getIndex(bitnum)] |= getMask(bitnum); } void vBitVectorClear(bitvector_t* vector, unsigned int bitnum) { vector->m_bits[getIndex(bitnum)] &= ~getMask(bitnum); } void vBitVectorToggle(bitvector_t* vector, unsigned int bitnum) { vector->m_bits[getIndex(bitnum)] ^= getMask(bitnum); } void vBitVectorOREQ(bitvector_t* dest, bitvector_t* vector){ unsigned int index = ARRAY_SIZE; while(index--) dest->m_bits[index] |= vector->m_bits[index]; } void vBitVectorANDEQ(bitvector_t* dest, bitvector_t* vector){ unsigned int index = ARRAY_SIZE; while(index--) dest->m_bits[index] &= vector->m_bits[index]; } void vBitVectorXOREQ(bitvector_t* dest, bitvector_t* vector){ unsigned int index = ARRAY_SIZE; while(index--) dest->m_bits[index] ^= vector->m_bits[index]; } unsigned int ulBitVectorSize(void) { return MAX_TORRENT_SIZE; }
C
/* Programming Exercise 11-11 */ // Write a program that reads in up to 10 strings or to EOF, whichever comes first. Have it // offer the user a menu with five choices: print the original list of strings, print the strings // in ASCII collating sequence, print the strings in order of increasing length, print the // strings in order of the length of the first word in the string, and quit. Have the menu // recycle until the user enters the quit request. The program, of course, should actually // perform the promised tasks. #include <stdio.h> #include <string.h> #include <stdbool.h> #include <ctype.h> #define LEN 80 #define MAX 10 void function1(int cnt, char *s[]); void function2(int cnt, char *s[]); void function3(int cnt, char *s[]); void function4(int cnt, char *s[]); char * s_gets(char * st, int n); int main(void) { char s[MAX][LEN]; char *strptr[MAX]; int cnt = 0; for (int i = 0; i < MAX; i++) strptr[i] = s[i]; puts("Enter up to 10 strings (or just Enter to finish):"); while (s_gets(s[cnt], LEN) && s[cnt][0] != '\0') { cnt++; if (cnt == 10) break; } while(true) { puts(""); puts("1. print the original list of strings"); puts("2. print the strings in ASCII collating sequence"); puts("3. print the strings in order of increasing length"); puts("4. print the strings in order of the length of the first word in the string"); puts("5. quit"); printf("Please make a choice: "); char ch = getchar(); while (getchar() != '\n') continue; switch(ch) { case '1': function1(cnt, strptr); break; case '2': function2(cnt, strptr); break; case '3': function3(cnt, strptr); break; case '4': function4(cnt, strptr); break; case '5': puts("Bye!"); return 0; default : puts("Error!"); return 0; } } puts("Bye!"); return 0; } void function1(int cnt, char *s[]) { for (int i = 0; i < cnt; i++) { for (int j = 0; j < strlen(s[i]); j++) { printf("%c", s[i][j]); } puts(""); } puts(""); } void function2(int cnt, char *s[]) { char *temp; for (int i = 0; i < cnt - 1; i++) { for (int j = i + 1; j < cnt; j++) { if (strcmp(s[i], s[j]) > 0) { temp = s[i]; s[i] = s[j]; s[j] = temp; } } } for (int m = 0; m < cnt; m++) { for (int n = 0; n < strlen(s[m]); n++) { printf("%c", s[m][n]); } puts(""); } puts(""); } void function3(int cnt, char *s[]) { char *temp; for (int i = 0; i < cnt - 1; i++) { for (int j = i + 1; j < cnt; j++) { if (strlen(s[i]) > strlen(s[j])) { temp = s[i]; s[i] = s[j]; s[j] = temp; } } } for (int m = 0; m < cnt; m++) { for (int n = 0; n < strlen(s[m]); n++) { printf("%c", s[m][n]); } puts(""); } puts(""); } void function4(int cnt, char *s[]) { char *temp; for (int i = 0; i < cnt - 1; i++) { for (int j = i + 1; j < cnt; j++) { int first_word_si = -1, first_word_sj = -1; int k = 0, l = 0; char chi, chj; do { chi = s[i][k]; k++; first_word_si++; } while(!isspace(chi)); do { chj = s[j][l]; l++; first_word_sj++; } while(!isspace(chj)); if (first_word_si > first_word_sj) { temp = s[i]; s[i] = s[j]; s[j] = temp; } } } for (int m = 0; m < cnt; m++) { for (int n = 0; n < strlen(s[m]); n++) { printf("%c", s[m][n]); } puts(""); } puts(""); } char * s_gets(char * st, int n) { char * ret_val; char * find; ret_val = fgets(st, n, stdin); if (ret_val) { find = strchr(st, '\n'); // look for newline if (find) // if the address is not NULL, *find = '\0'; // place a null character there else while (getchar() != '\n') continue; } return ret_val; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> int main(int argc, char* argv[]){ long long n; if(argc != 2){ printf("Enter a binary number: "); return EXIT_FAILURE; } else{ sscanf(argv[1], "%lld", &n); int decimal = 0, i = 0, retenue = 0; while(n != 0){ retenue = n%10; n /= 10; decimal += retenue*pow(2,i); i++; } printf("%d\n", decimal); } return 0; }
C
int panduan(char a){ int result=0; if((a>='a'&&a<='z')||(a>='A'&&a<='Z')||(a>='0'&&a<='9')||(a=='_')) result=1; return result; } int first(char b){ int result=0; if((b>='a'&&b<='z')||(b>='A'&&b<='Z')||(b=='_')) result=1; return result; } int main(int argc, char* argv[]) { int i,n,j,len,flag; int panduan(char a); int first(char b); char s[81]; scanf("%d\n",&n); for(i=0;i<n;i++){ gets(s); len=strlen(s); flag=1; if(first(*s)==0) flag=0; else if(first(*s)==1){ for(j=1;j<len;j++){ if(panduan(*(s+j))==0){ flag=0; break; } } } if(flag==1){ printf("1\n"); } else{ printf("0\n"); } } return 0; }
C
#define _GNU_SOURCE #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <fcntl.h> #include <time.h> #include <sched.h> #include "../cacheutils.h" #define CORE1 1 #define CORE2 0 #define CACHE_HIT_THRESHOLD 65 #define WINDOW_SIZE 1000 #define OFFSET (64 * 21) volatile char __attribute__((aligned(4096))) data[4096]; size_t event_internal = 500000; void pin_to_core(int core) { cpu_set_t cpuset; pthread_t thread; thread = pthread_self(); CPU_ZERO(&cpuset); CPU_SET(core, &cpuset); pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset); } void write_speculative2(void* ptr) { speculation_start(s); *(char*)ptr ^= 1; speculation_end(s); } int cnt = 0; size_t volatile t_sync = 0; void* accessor(void* dummy) { pin_to_core(CORE2); int seed = time(NULL); srand(seed); printf("Go!\n"); while(1) { sched_yield(); size_t r = rand() % event_internal + 1; wait(r); //wait(event_internal); write_speculative2(data); //write_speculative2(data+OFFSET); // CONTROL (Error Rate) cnt++; } } int main() { memset(data, 1, sizeof(data)); pin_to_core(CORE1); int pos = 0, t = 0; int start = time(NULL); int current = time(NULL); maccess(data); flush(data); mfence(); size_t begin = rdtsc(); flush_reload_t(data); size_t end = rdtsc(); mfence(); printf("F+R blind_spot: %d\n", end - begin); float acc_arr[100] = {0}; size_t window_size = 3200; // Make sure the blind spot rate is less than 10% size_t delta = 0; pthread_t pt; pthread_create(&pt, NULL, accessor, NULL); while(1) { /* F+R */ flush(data); wait(window_size); if (reload_t(data) < CACHE_HIT_THRESHOLD) pos++; current = time(NULL); if(start != current) { start = current; printf("window_cycle: %ld; %d / %d (%.2f)\n", wait(window_size), pos, cnt, pos * 100.0 / cnt); t++; pos = 0; cnt = 0; if (t == 1000) { t = 0; event_internal = event_internal * 4 / 5; printf("event internal alters!!!\n\n"); if (event_internal < 500) break; } } } }
C
#include <stdio.h> int main(void){ int total = 0; int n_iter = 1000000; #pragma omp parallel for for(int i=0; i<n_iter; i++){ total++; } printf("Value: %d", total); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> /* Ajai Gill 1015577 10/14/2018 Assignment 4 */ typedef struct node{ int bFactor; char *key; int frequency; struct node *left, *right; }AVL_Node; void BuildTree(AVL_Node **root, FILE *file); AVL_Node *SearchTree(AVL_Node *root, char *key); AVL_Node *CreateNode(char *key); void InsertNode(char *key, AVL_Node **root); void DeleteNode(char *key, AVL_Node **root); void UpdateBFactors(AVL_Node *root); int CalculateHeight(AVL_Node *root); void InsertionAnalysis(AVL_Node **root, char *keyEntered); void DeletionAnalysis(AVL_Node **root, char *keyDeleted); void Restructure(AVL_Node *x, AVL_Node *y, AVL_Node *z, AVL_Node **prevNode, int changeRoot); void SizeAndCount(unsigned long long *size, unsigned long long *count, AVL_Node *root); unsigned long long KeyToInt(char *key); void FindAllAbove(AVL_Node *root, int threshold); AVL_Node *FindMax(AVL_Node *root); AVL_Node *FindMin(AVL_Node *root); void SetXYZ(AVL_Node **x, AVL_Node **y, AVL_Node **z); void PrintTree(AVL_Node *tree); int main() { AVL_Node *tree = NULL; FILE *file = NULL; int userChoice = 0; int avlBool = 0; AVL_Node *nodeFound = NULL; char key[10]; unsigned long height = 0; unsigned long long size = 0; unsigned long long count = 0; long threshold = -1; while(userChoice != 7) { printf("1. Initialization\n2. Find\n3. Insert\n4. Remove\n5. Check Height, Size, and Total Count\n6. Find All (above a given frequency)\n7. Exit\n"); printf("avl/> "); scanf("%d", &userChoice); switch(userChoice) { case 1: file = fopen("A4_data_f18.txt", "r"); BuildTree(&tree, file); avlBool = 1; fclose(file); break; case 2: if(avlBool) { printf("Please provide the key you want to find: "); scanf("%s", key); nodeFound = SearchTree(tree, key); if(KeyToInt(nodeFound->key) == KeyToInt(key)) { printf("Key: %s Frequency: %d\n", nodeFound->key, nodeFound->frequency); } else { printf("No_such_key\n"); } } else { printf("AVL tree not initialized!!!\n"); } break; case 3: if(avlBool) { printf("Please provide the key you want to insert: "); scanf("%s", key); InsertNode(key, &tree); UpdateBFactors(tree); nodeFound = SearchTree(tree, key); printf("Key: %s Frequency: %d\n", nodeFound->key, nodeFound->frequency); } else { printf("AVL tree not initialized!!!\n"); } break; case 4: if(avlBool) { printf("Please provide the key you want to delete: "); scanf("%s", key); DeleteNode(key, &tree); DeletionAnalysis(&tree, key); UpdateBFactors(tree); } else { printf("AVL tree not initialized!!!\n"); } break; case 5: if(avlBool) { height = CalculateHeight(tree); SizeAndCount(&size, &count, tree); printf("Height: %lu Size: %llu Count: %llu\n", height, size, count); } else { printf("AVL tree not initialized!!!\n"); } break; case 6: if(avlBool) { while(threshold < 0) { printf("Please provide the threshold you want: "); scanf("%ld", &threshold); } FindAllAbove(tree, threshold); } else { printf("AVL tree not initialized!!!\n"); } break; } height = 0; size = 0; count = 0; threshold = -1; } } /*Takes the variables and rotates the keys until the restructuring is done Checks which case the x, y and z are in and performs the correct rotations*/ void Restructure(AVL_Node *x, AVL_Node *y, AVL_Node *z, AVL_Node **prevNode, int changeRoot) { if(x->left == y && y->right == z) { y->right = z->left; z->left = y; x->left = z->right; z->right = x; if(!changeRoot && KeyToInt((*prevNode)->key) > KeyToInt(z->key)) { (*prevNode)->left = z; } else if(!changeRoot && KeyToInt((*prevNode)->key) < KeyToInt(z->key)) { (*prevNode)->right = z; } else if(changeRoot) { *prevNode = z; } } else if(x->right == y && y->left == z) { y->left = z->right; z->right = y; x->right = z->left; z->left = x; if(!changeRoot && KeyToInt((*prevNode)->key) > KeyToInt(z->key)) { (*prevNode)->left = z; } else if(!changeRoot && KeyToInt((*prevNode)->key) < KeyToInt(z->key)) { (*prevNode)->right = z; } else if(changeRoot) { *prevNode = z; } } else if(x->right == y && y->right == z) { x->right = y->left; y->left = x; if(!changeRoot && KeyToInt((*prevNode)->key) > KeyToInt(y->key)) { (*prevNode)->left = y; } else if(!changeRoot && KeyToInt((*prevNode)->key) < KeyToInt(y->key)) { (*prevNode)->right = y; } else if(changeRoot) { *prevNode = y; } } else if(x->left == y && y->left == z) { x->left = y->right; y->right = x; if(!changeRoot && KeyToInt((*prevNode)->key) > KeyToInt(y->key)) { (*prevNode)->left = y; } else if(!changeRoot && KeyToInt((*prevNode)->key) < KeyToInt(y->key)) { (*prevNode)->right = y; } else if(changeRoot) { *prevNode = y; } } } /*Analyzes the deletion process to check if we need to restructure*/ void DeletionAnalysis(AVL_Node **root, char *keyDeleted) { AVL_Node *temp = NULL; AVL_Node *x = NULL; AVL_Node *y = NULL; AVL_Node *z = NULL; AVL_Node **nodeArray = NULL; int i = 0; int arraySize = 0; int bFactorError = 0; temp = *root; /*finds the previous key to where the key deleted was*/ while(KeyToInt(temp->key) != KeyToInt(keyDeleted)) { arraySize += 1; nodeArray = realloc(nodeArray, sizeof(struct node*) * (arraySize)); nodeArray[arraySize - 1] = temp; if(KeyToInt(temp->key) > KeyToInt(keyDeleted)) { if(temp->left != NULL) { temp = temp->left; } else { break; } } else if(KeyToInt(temp->key) < KeyToInt(keyDeleted)) { if(temp->right != NULL) { temp = temp->right; } else { break; } } } /*travels up list until finds a bfactor error*/ for(i = arraySize - 1; i >= 0; i--) { if(nodeArray[i]->bFactor >= 2 || nodeArray[i]->bFactor <= -2) { bFactorError = 1; x = nodeArray[i]; break; } } if(bFactorError) { SetXYZ(&x, &y, &z); if((i - 1) < 0) { Restructure(x, y, z, root, 1); } else { Restructure(x, y, z, &(nodeArray[i - 1]), 0); } } } /*sets up the x, y and z variables*/ void SetXYZ(AVL_Node **x, AVL_Node **y, AVL_Node **z) { if(CalculateHeight((*x)->left) > CalculateHeight((*x)->right)) { *y = (*x)->left; } else { *y = (*x)->right; } if(CalculateHeight((*y)->left) > CalculateHeight((*y)->right)) { *z = (*y)->left; } else { *z = (*y)->right; } } /*deletes or reduces the frequency of a node*/ void DeleteNode(char *key, AVL_Node **root) { AVL_Node *toDelete = NULL; AVL_Node *toSwap = NULL; AVL_Node *prevNode = NULL; char *keyToCopy = NULL; char *keyToDelete = NULL; toDelete = *root; while(KeyToInt(toDelete->key) != KeyToInt(key)) { prevNode = toDelete; if(KeyToInt(toDelete->key) > KeyToInt(key)) { toDelete = toDelete->left; } else if(KeyToInt(toDelete->key) < KeyToInt(key)) { toDelete = toDelete->right; } if(toDelete == NULL) { printf("No_such_key\n"); return; } } if(toDelete->frequency > 1) { toDelete->frequency -= 1; } else if(toDelete->right == NULL && toDelete->left == NULL) { if(prevNode->left == toDelete) { prevNode->left = NULL; } else { prevNode->right = NULL; } keyToDelete = toDelete->key; free(keyToDelete); toDelete->key = NULL; free(toDelete); } else if(toDelete->right != NULL && toDelete->left == NULL) { toSwap = FindMin(toDelete->right); keyToCopy = strcpy(malloc(strlen(toSwap->key) + 1), toSwap->key); toDelete->frequency = toSwap->frequency; DeleteNode(toSwap->key, &(toDelete)); keyToDelete = toDelete->key; free(keyToDelete); toDelete->key = keyToCopy; } else if(toDelete->left != NULL) { toSwap = FindMax(toDelete->left); keyToCopy = strcpy(malloc(strlen(toSwap->key) + 1), toSwap->key); toDelete->frequency = toSwap->frequency; DeleteNode(toSwap->key, &(toDelete)); keyToDelete = toDelete->key; free(keyToDelete); toDelete->key = keyToCopy; } UpdateBFactors(*root); } /*goes down the left sub tree and finds the max key*/ AVL_Node *FindMax(AVL_Node *root) { if(root->right != NULL) { return FindMin(root->right); } else { return root; } } /*goes down the right sub tree and finds the min key*/ AVL_Node *FindMin(AVL_Node *root) { if(root->left != NULL) { return FindMin(root->left); } else { return root; } } /*searches through the tree and prints out keys within the threshold*/ void FindAllAbove(AVL_Node *root, int threshold) { if(root->frequency >= threshold) { printf("Key: %s Frequency: %d\n", root->key, root->frequency); } if(root->left != NULL) { FindAllAbove(root->left, threshold); } if(root->right != NULL) { FindAllAbove(root->right, threshold); } } /*helper function that prints the tree*/ void PrintTree(AVL_Node *tree) { printf("Key: %s Frequency: %d\n", tree->key, tree->frequency); if(tree->left != NULL) { PrintTree(tree->left); } if(tree->right != NULL) { PrintTree(tree->right); } } /*provides the size and count of the tree*/ void SizeAndCount(unsigned long long *size, unsigned long long *count, AVL_Node *root) { *size += 1; *count += root->frequency; if(root->left != NULL) { SizeAndCount(size, count, root->left); } if(root->right != NULL) { SizeAndCount(size, count, root->right); } } /*Goes through the file and adds tree keys to the tree*/ void BuildTree(AVL_Node **root, FILE *file) { char *keyToCopy = NULL; keyToCopy = malloc(15); while(!feof(file)) { fscanf(file, "%s", keyToCopy); InsertNode(keyToCopy, root); } UpdateBFactors(*root); } /*Analyzes whether or not the tree has become unbalanced*/ void InsertionAnalysis(AVL_Node **root, char *keyEntered) { AVL_Node *temp = *root; AVL_Node *x = NULL; AVL_Node *y = NULL; AVL_Node *z = NULL; AVL_Node **nodeArray = NULL; int arraySize = 0; int i = 0; int bFactorError = 0; while(KeyToInt(temp->key) != KeyToInt(keyEntered)) { arraySize += 1; nodeArray = realloc(nodeArray, sizeof(struct node*) * (arraySize)); nodeArray[arraySize - 1] = temp; if(KeyToInt(temp->key) > KeyToInt(keyEntered)) { temp = temp->left; } else if(KeyToInt(temp->key) < KeyToInt(keyEntered)) { temp = temp->right; } } arraySize += 1; nodeArray = realloc(nodeArray, sizeof(struct node*) * (arraySize)); nodeArray[arraySize - 1] = temp; for(i = arraySize - 1; i >= 0; i--) { z = y; y = x; x = nodeArray[i]; if(nodeArray[i]->bFactor >= 2 || nodeArray[i]->bFactor <= -2) { bFactorError = 1; break; } } if(bFactorError) { if((i - 1) < 0) { Restructure(x, y, z, root, 1); } else { Restructure(x, y, z, &(nodeArray[i - 1]), 0); } } free(nodeArray); } /*updates the balance factors of every tree key*/ void UpdateBFactors(AVL_Node *root) { int left = 0; int right = 0; if(root->left != NULL) { left = CalculateHeight(root->left); } if(root->right != NULL) { right = CalculateHeight(root->right); } root->bFactor = left - right; if(root->left != NULL) { UpdateBFactors(root->left); } if(root->right != NULL) { UpdateBFactors(root->right); } } /*Calculates the height of a given tree*/ int CalculateHeight(AVL_Node *root) { int heightL = 0; int heightR = 0; if(root == NULL) { return 0; } if(root->left != NULL) { heightL = CalculateHeight(root->left); } if(root->right != NULL) { heightR = CalculateHeight(root->right); } if(heightR > heightL) { return heightR + 1; } else { return heightL + 1; } } /*Inserts a node to the correct spot of the tree*/ void InsertNode(char *key, AVL_Node **root) { AVL_Node *node; AVL_Node *toInsertTo; toInsertTo = SearchTree(*root, key); if(toInsertTo == NULL) { node = CreateNode(key); *root = node; } else if(KeyToInt(toInsertTo->key) > KeyToInt(key)) { node = CreateNode(key); toInsertTo->left = node; } else if(KeyToInt(toInsertTo->key) < KeyToInt(key)) { node = CreateNode(key); toInsertTo->right = node; } else if(KeyToInt(toInsertTo->key) == KeyToInt(key)) { toInsertTo->frequency += 1; } UpdateBFactors(*root); InsertionAnalysis(root, key); } /*Initializes a new tree node*/ AVL_Node *CreateNode(char *key) { AVL_Node *node; node = malloc(sizeof(struct node)); node->key = malloc(strlen(key) + 1); node->key[0] = '\0'; strcat(node->key, key); node->bFactor = 0; node->frequency = 1; node->left = NULL; node->right = NULL; return node; } /*Searches a tree for the right key and returns the node*/ AVL_Node *SearchTree(AVL_Node *root, char *key) { if(root == NULL) { return NULL; } else if(KeyToInt(root->key) == KeyToInt(key)) { return root; } else { if(KeyToInt(root->key) > KeyToInt(key) && root->left != NULL) { return SearchTree(root->left, key); } else if(KeyToInt(root->key) < KeyToInt(key) && root->right != NULL) { return SearchTree(root->right, key); } else { return root; } } } /*Converts the key into and unsigned long long*/ unsigned long long KeyToInt(char *key) { return strtoull(key, NULL, 36); }
C
#include <stdio.h> #include <stdlib.h> #include "simulation.h" float rand_float(float min,float max) { float rand_normal=(float)rand()/(float)(RAND_MAX); return min+(max-min)*rand_normal; } simulation_t* simulation_new(unsigned int width,unsigned int height,unsigned int max_particles) { simulation_t* simulation=malloc(sizeof(simulation_t)); simulation->grid=grid_new(width,height); simulation->particle_system=particle_system_new(max_particles); return simulation; } void simulation_handle_sources(simulation_t* simulation) { int i,x,y; //Loop over all inflows, make sure they are fluid for(y=0;y<simulation->grid->height;y++) for(x=0;x<simulation->grid->width;x++) { if((GRID_CELL_FLAGS(simulation->grid,x,y)&INFLOW)&&GRID_CELL_TYPE(simulation->grid,x,y)!=FLUID) { simulation_set_cell(simulation,FLUID,x,y); } } //Loop over particles and delete any that lie in an outflow for(i=0;i<simulation->particle_system->num_particles;i++) { particle_t* particle=simulation->particle_system->particles+i; //We compute the cell in which the particle lies in the same manner as for particle_system_mark_grid_cells int cell_x=(int)floor(particle->position_x+0.5); int cell_y=(int)floor(particle->position_y+0.5); //Now, check if the cell is out of bounds or solid if(GRID_CELL_FLAGS(simulation->grid,cell_x,cell_y)&OUTFLOW) { //Delete the particle particle_system_delete_particle(simulation->particle_system,i); /*Since the current particle has been deleted, there is a different particle at this location, and that also needs to be checked, so for the next loop iteration, use the same i*/ i--; } } } void simulation_step(simulation_t* simulation,float delta_t) { simulation_handle_sources(simulation); //Save the current grid velocities grid_save_velocities(simulation->grid); //Apply gravity force grid_apply_gravity(simulation->grid,delta_t); //Here we solve for the pressure grid_project(simulation->grid,delta_t); //Compute velocity delta grid_calculate_velocity_delta(simulation->grid); //Update particle velocities using new grid velocities grid_transfer_to_particle_system(simulation->grid,simulation->particle_system); //Advect particles particle_system_advect(simulation->particle_system,simulation->grid,delta_t); //Remove any particles that are in invalid postions particle_system_remove_invalid_particles(simulation->particle_system,simulation->grid); //Determine which grid cells contain fluid particle_system_mark_grid_cells(simulation->particle_system,simulation->grid); //Compute velocities on grid from particle velocities particle_system_transfer_to_grid(simulation->particle_system,simulation->grid); } void simulation_set_cell(simulation_t* simulation,grid_cell_type_t type,unsigned int x,unsigned int y) { if(x<1||y<1||x>=simulation->grid->width-1||y>=simulation->grid->height-1)return; //Nothing to be done if the target cell is already the right type if(GRID_CELL_TYPE(simulation->grid,x,y)==type)return; //Assign type GRID_CELL_SET_TYPE(simulation->grid,x,y,type); //If the new type is fluid, some particles need to be added as well if(type==FLUID) { float fx=(float)x,fy=(float)y; particle_system_add_particle(simulation->particle_system,fx+rand_float(-0.5,-1.0/6.0),fy+rand_float(-0.5,-1.0/6.0)); particle_system_add_particle(simulation->particle_system,fx+rand_float(-1.0/6.0,1.0/6.0),fy+rand_float(-0.5,-1.0/6.0)); particle_system_add_particle(simulation->particle_system,fx+rand_float(1.0/6.0,0.5),fy+rand_float(-0.5,-1.0/6.0)); particle_system_add_particle(simulation->particle_system,fx+rand_float(-0.5,-1.0/6.0),fy+rand_float(-1.0/6.0,1.0/6.0)); particle_system_add_particle(simulation->particle_system,fx+rand_float(-1.0/6.0,1.0/6.0),fy+rand_float(-1.0/6.0,1.0/6.0)); particle_system_add_particle(simulation->particle_system,fx+rand_float(1.0/6.0,0.5),fy+rand_float(-1.0/6.0,1.0/6.0)); particle_system_add_particle(simulation->particle_system,fx+rand_float(-0.5,-1.0/6.0),fy+rand_float(1.0/6.0,0.5)); particle_system_add_particle(simulation->particle_system,fx+rand_float(-1.0/6.0,1.0/6.0),fy+rand_float(1.0/6.0,0.5)); particle_system_add_particle(simulation->particle_system,fx+rand_float(1.0/6.0,0.5),fy+rand_float(1.0/6.0,0.5)); } } void simulation_set_rect(simulation_t* simulation,grid_cell_type_t type,unsigned int x1,unsigned int y1,unsigned int x2,unsigned int y2) { int x,y; for(y=y1;y<=y2;y++) for(x=x1;x<=x2;x++) { simulation_set_cell(simulation,type,x,y); } } void simulation_free(simulation_t* simulation);
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* lm_create_hole.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hklein <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/14 22:41:15 by hklein #+# #+# */ /* Updated: 2019/02/14 22:51:58 by hklein ### ########.fr */ /* */ /* ************************************************************************** */ #include "lem_in.h" int setup_hole(t_lm *lm, char **tab, int start) { t_hole *buf; if (!(buf = init_hole())) return (1); if (!(buf->name = ft_strdup(tab[0]))) return (1); buf->coord[0] = ft_atoi(tab[1]); buf->coord[1] = ft_atoi(tab[2]); buf->start = start; buf->next = lm->holes; lm->holes = buf; return (0); } int create_hole(t_lm *lm, char **line) { char **tab; int start; start = !ft_strcmp((*line), "##start") ? 1 : 0; start = !start && !ft_strcmp((*line), "##end") ? -1 : start; if (start != 0) { ft_strdel(line); if (get_next_line(0, line) < 0) return (-2); } if (!(tab = ft_strsplit((*line), ' '))) return (-2); if (ft_tab_len(tab) != 3) return (ft_tabdel(&tab) + 1); if (tab[0][0] == '#' || tab[0][0] == 'L' || get_hole(tab[0], lm->holes) || !ft_is_str_digit(tab[1]) || !ft_is_str_digit(tab[2])) return (ft_tabdel(&tab) - 2); if (setup_hole(lm, tab, start)) return (ft_tabdel(&tab) - 2); return (ft_tabdel(&tab)); }
C
TEST(DwMap, DwMap) { DwMap<int, DwString> m; EXPECT_TRUE(m.isEmpty()); for(int i = 0; i < 10000; i++) { m[i] = DwString::number(i, 16); } EXPECT_FALSE(m.isEmpty()); EXPECT_EQ(10000, m.count()); } TEST(DwMap, iterator) { DwMap<int, DwString> m; m[100] = "aaa"; m[200] = "bbb"; m[300] = "ccc"; DwString s; for(DwMap<int, DwString>::const_iterator it = m.begin(); it != m.end(); ++it) { s += it->second; } EXPECT_EQ(DwString("aaabbbccc"), s); } TEST(DwMap, find) { DwMap<int, DwString> m; m[300] = "ccc"; m[100] = "aaa"; m[200] = "bbb"; m.insert(400, "sdfs"); DwMap<int, DwString>::const_iterator it = m.find(100); EXPECT_TRUE(it != m.end()); EXPECT_EQ(DwString("aaa"), it->second); EXPECT_EQ(DwString("bbb"), m[200]); EXPECT_EQ(DwString("ccc"), m.value(300)); } TEST(DwMap, insert_remove) { DwMap<int, DwString> m; m[300] = "ccc"; m[100] = "aaa"; m[200] = "bbb"; m.insert(150, "111"); m.remove(200); DwString s; int keySum = 0; for(DwMap<int, DwString>::const_iterator it = m.begin(); it != m.end(); ++it) { keySum += it->first; s += it->second; } EXPECT_EQ(100 + 150 + 300, keySum); EXPECT_EQ(DwString("aaa111ccc"), s); }
C
/* Goal: Building a command line calculator. Example: I/P = 5 / 2 + 3 - 4 x 2 = O/P = -2.5 Requirements: 1) Accepts a maximum of 80 characters input. 2) Every valid expression entered, must end with an '=' sign to be computed. 3) The only valid operations are '+' , '-' , '/' and 'x'. 4) The calculator must follow BODMAS rule to return the correct answer. 5) For wrong inputs, an error must be thrown, along with a guide to help the user rectify the error. Test Cases: Functional Test Cases: 1) '5 / 2 + 3 - 4 x 2 ='. 2) Valid expression that is 80 char long. 3) Check for BODMAS: a) '5 / 2 + 3 - 4 x 2 =' b) '3 - 4 x 2 + 5 / 2 =' a) and b) must yield the same result. 4) '65111.9 / 5.3 ='. Negative Test Cases: 1) '-5 + 10 =' , expression starting off with operation. 2) '/5 + 10 =' and 'x5 + 10 =' must throw an error. 3) Enter an expression > 80 chars. 4) No '=' to terminate the expression. 5) Unknown operation used. 6) Division by zero exception. 7) Only '='. 8) Repeated operands: '5//2 ='. Design: 1) I/P: Terminal, input string, scan input. 2) Pre-validation 3) Tokenize 4) Linked-List. Node ---> | value | operation | next | 5) Walk n Reduce ---> BODMAS 6) O/P */ #include<stdio.h> #include<stdlib.h> #include <string.h> #include<ctype.h> #include "calc.h" /* Remove spaces from the input string */ void RemoveSpaces(char* source){ char* i = source; char* j = source; while(*j != 0) { *i = *j++; if(*i != ' ') i++; } *i = 0; } /* Pre-validating input before further processing */ int pre_validating_input_string(char * input , int flag){ int length = strlen(input); int equal_to_count = 0; int left = 0; //Count of left paranthesis int right = 0; //Count of right paranthesis if(length > 80){ printf("ERROR: Please enter expression lesser than 80 characters\n"); return 1; } if(length == 0){ printf("ERROR: Please enter a string\n"); return 1; } if(flag){ if(*(input + length - 2) != '='){ printf("ERROR: Expression must end with an '=' sign.\n"); return 1; } } if(*input == '/' | *input == '*'){ printf("ERROR: Invalid expression. Cannot start with '/' or '*'\n"); return 1; } for(int i = 0 ; i < length - 1 ; i++){ if(*(input + i) == '=') equal_to_count++; if(*(input + i) == '(') left++; if(*(input + i) == ')') right++; if(equal_to_count > flag){ printf("ERROR: Cannot have more than one equal to sign.\n"); return 1; } if(*(input + i) == '.'){ continue; } if((i != 0) && ((*(input + i) == '+') | (*(input + i) == '-') \ | (*(input + i) == '/') | (*(input + i) == '*'))){ if(((*(input + i - 1) == '+') | (*(input + i - 1) == '-')\ | (*(input + i - 1) == '/') | (*(input + i - 1) == '*'))){ printf("ERROR: Repeated operators\n"); return 1; } } if(!isdigit(*(input + i)) && (*(input + i) != '+') && (*(input + i) != '-') \ && (*(input + i) != '/') && (*(input + i) != '*') && (*(input + i) != '=') \ && (*(input + i) != '(') && (*(input + i) != ')')){ printf("ERROR: Unknown operation used.\n"); return 1; } } if(left != right){ printf("ERROR: Unbalanced parantheses\n"); return 1; } return 0; } /* Case where string starts with +/- */ int starting_operator_correction(char * input){ if(*input == '-' | *input == '+'){ return 1; } return 0; } /* prepend a string to another */ void prepend_string(char* s, const char* t) { size_t len = strlen(t); size_t i; memmove(s + len, s, strlen(s) + 1); for (i = 0; i < len; ++i) { s[i] = t[i]; } }
C
/* Dane Kirkpatrick * 1004843 * [email protected] */ #ifndef NAME #define NAME struct name_data { int size; struct name_basics * array; struct node *nconst_root; struct node *primaryName_root; }; struct name_basics { char *nconst; char *primaryName; }; struct name_data * get_name(char *dir); void freeNameArr(struct name_basics * arr, int size); void build_pnindex(struct name_data *arr); void build_nindex(struct name_data *arr); struct name_basics * find_primary_name(struct name_data *data, char *title); struct name_basics * find_nconst(struct name_data *data, char *nconst); #endif
C
#include <stdio.h> #include <stdint.h> #include <math.h> void print_sin_cos(double step) { for (double x=0;x<=1;x+=step) { printf("sin(%f)=%f\n", x, sin(x)); printf("cos(%f)=%f\n", x, cos(x)); } } int main() { double step = 0; printf("Enter the desired step (es. 0.1):\n"); if (scanf("%lf", &step)==1) print_sin_cos(step); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/wait.h> #define SLEEP_TIME 1 int main(int argc, char* argv[]) { if (argc < 4) { printf("Not enoughr arguments, consumer got %d arguments", argc); }else{ char* pipeFilename = argv[1]; char* filename = argv[2]; int N = atoi(argv[3]); FILE* file = fopen(filename, "w"); FILE* pipe = fopen(pipeFilename, "r"); char buffer [N + 1]; for (int read = fread(buffer, sizeof(char), N, pipe); read != 0; read = fread(buffer, sizeof(char), N, pipe)) { buffer[read] = '\0'; fprintf(file, "%s", buffer); } } return 0; }
C
/* Redo exercise 4 using a switch . */ #include<stdio.h> int main() { char ch; int period_sub = 0, excla_sub = 0; printf("Enter the characters:\n"); while ( (ch=getchar()) != '#' ) { switch(ch) { case '.': printf("!"); period_sub++; case '!': printf("!!"); excla_sub++; case '#': break; default: putchar(ch); } } printf("\n"); printf("Period sub = %d, Exclamation sub = %d", period_sub, excla_sub); return 0; }
C
#include "mount.h" #include "inode.h" #include "unixv6fs.h" int test(struct unix_filesystem *u) { int err = 0; int numeroInode = 0; int numeroSecteur = 0; int offset = 0; struct inode inodePourTest; printf("\nEntrez le numero de l'inode: "); scanf("%d", &numeroInode); err = inode_read(u, numeroInode, &inodePourTest); if (!err) { inode_print(&inodePourTest); printf("\nEntrez l'offset: "); scanf("%d", &offset); numeroSecteur = inode_findsector(u,&inodePourTest,offset); if (numeroSecteur >=0) { printf("\nNumero de secteur: %d.\n", numeroSecteur); } else { printf("Problème, erreur = %d", numeroSecteur); err = numeroSecteur; } } return err; }
C
/* misc.c - common routines * * adftools - A complete package for maintaining image-files for the best * Amiga-emulator out there: UAE - http://www.freiburg.linux.de/~uae/ * * Copyright (C)2002-2015 Rikard Bosnjakovic <[email protected]> */ #include <adflib.h> #include <ctype.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "error.h" #include "misc.h" #include "zfile.h" /* "12345678" -> 1, "12354foo1234" -> 0 */ int isdigits (char *str) { register int i; for (i = 0; i < strlen (str); i++) if (!isdigit (str[i])) return 0; return 1; } /* checks if the buffer (the bootblock) is an adf-file */ int is_adf_file (unsigned char *buf) { if ((buf[0] != 'D') && (buf[1] != 'O') && (buf[2] != 'S')) return 0; return 1; } /* "apan.apan.ap.jpg.gurka.iff" -> "apan.apan.ap.jpg.gurka" */ char * strip_extension (char *str) { char *p, *s; s = strdup (str); p = rindex (s, '.'); if (p != NULL) /* found extension */ *p = 0; return s; } char * strip_trailing_slashes (char *path) { char *p = path; while (p[strlen (p)-1] == '/') p[strlen (p)-1] = '\0'; return p; } /* "/foo/bar/gazonk.jpg" -> "gazonk.jpg" */ char * basename (char *filename) { char *p; for (p = filename; *p == '/'; ++p) /* do nothing if "/", "//" etc */ ; if (*p == '\0') return (p - 1); p = strrchr (filename, '/'); if (p == NULL) return (filename); else return (p + 1); } /* old code */ /* char * */ /* basename (char *filename) */ /* { */ /* char *p, *s; */ /* s = strdup (filename); */ /* p = rindex (s, '/'); */ /* if (p != NULL) */ /* s = (p + 1); */ /* return s; */ /* } */ /* "/foo/bar/gazonk.jpg" -> "/foo/bar" */ /* char * */ /* dirname (char *filename) */ /* { */ /* char *p, *s; */ /* s = strdup (filename); */ /* p = rindex (s, '/'); */ /* if (p != NULL) */ /* *p = 0; */ /* return s; */ /* } */ /* string representation of dosType */ char * get_adf_dostype (char dostype) { switch (dostype) { case 0: return "DOS0 (OFS)"; case 1: return "DOS1 (FFS)"; case 2: return "DOS2 (I-OFS))"; case 3: return "DOS3 (I-FFS)"; case 4: return "DOS4 (DC-OFS)"; case 5: return "DOS5 (DC-FFS)"; default: return "Unknown-FS"; } return "ApanAP-FS"; } /* mounts an adf-image */ int mount_adf (char *filename, struct Device **dev, struct Volume **vol, int rw) { char *errmsg = "Can't mount the device '%s' (perhaps not a DOS-disk or adf-file)"; /* check existence and readability of the file */ if (access (filename, F_OK | R_OK) == -1) { notify ("Can't access '%s': %s.\n", filename, strerror (errno)); return 0; } if (rw == READ_WRITE) *dev = adfMountDev (n_zfile_open(filename, "rw", 1), rw); else *dev = adfMountDev (n_zfile_open(filename, "r", 0), rw); if (!*dev) { error (0, errmsg, filename); return 0; } *vol = adfMount (*dev, 0, rw); if (!*vol) { error (0, errmsg, filename); adfUnMountDev (*dev); return 0; } return 1; } /* prints a nice header for the adf-image. it *must* be mounted */ void print_volume_header (char *filename, struct Volume *volume) { register int i; if (!volume) return; /* print header, consisting of filename and the (mounted) volume name */ /* volName can be NULL for some hardfiles, no idea why. */ if (volume->volName) { printf ("%s (%s)\n", filename, volume->volName); for (i = 0; i < (strlen (filename) + 3 + strlen (volume->volName)); i++) putchar ('='); putchar ('\n'); } else { printf ("%s\n", filename); for (i = 0; i < strlen (filename); i++) putchar ('='); putchar ('\n'); } } /* a null-function callback for adf-lib */ static void null_function (void) { }; /* initialize the adf-lib */ /* TODO: add an atexit() */ void init_adflib (void) { int true = 1; adfEnvInitDefault(); /* redirect errors and warnings to the big black void */ adfChgEnvProp (PR_EFCT, null_function); adfChgEnvProp (PR_WFCT, null_function); /* yes, we want to use directory caching */ adfChgEnvProp (PR_USEDIRC, (void *)&true); } /* shut down the adflib */ void cleanup_adflib (void) { adfEnvCleanUp(); zfile_exit(); } /* puts access bits in a readable string */ char * access2str (long access) { static char str[8+1]; strcpy (str, "----RWED"); if (hasD (access)) str[7] = '-'; if (hasE (access)) str[6] = '-'; if (hasW (access)) str[5] = '-'; if (hasR (access)) str[4] = '-'; if (hasA (access)) str[3] = 'A'; if (hasP (access)) str[2] = 'P'; if (hasS (access)) str[1] = 'S'; if (hasH (access)) str[0] = 'H'; return (str); } /* a temporary function until it's implemeted in adflib */ void change_to_root_dir (struct Volume *volume) { register int i; for (i = 0; i < 42; i++) adfParentDir (volume); } /* split first word off of rest and put it in first */ char * splitc (char *first, char *rest) { char *p; p = strchr (rest, '/'); if (p == NULL) { if ((first != rest) && (first != NULL)) first[0] = 0; return NULL; } *p = 0; if (first != NULL) strcpy (first, rest); if (first != rest) strcpy (rest, p + 1); return rest; } /* allocate a buffer big enough for a bootblock */ unsigned char * allocate_bootblock_buf (void) { unsigned char *bootblock; bootblock = malloc (BOOTBLOCK_SIZE); if (!bootblock) return NULL; memset (bootblock, 0, BOOTBLOCK_SIZE); return bootblock; } /* read bootblock bytes into a buffer */ unsigned char * read_bootblock (char *filename) { unsigned char *bootblock; FILE *file; bootblock = allocate_bootblock_buf(); if (!bootblock) return NULL; memset (bootblock, 0, BOOTBLOCK_SIZE); file = f_zfile_open (filename, "r", 0); if (!file) { free (bootblock); return NULL; } if (fread (bootblock, BOOTBLOCK_SIZE, 1, file) != 1) { /* error? */ if (ferror (file)) { /* yes */ free (bootblock); fclose (file); return NULL; } else if (!feof (file)) /* no error, but not end of file either. bloody hell! */ return NULL; } /* all went fine */ fclose (file); return bootblock; }
C
#include <sys/mman.h> #include <unistd.h> #include "lib.h" #include <dispatch/dispatch.h> dispatch_semaphore_t semaphore; #ifdef __APPLE__ #include <dispatch/dispatch.h> #else #include <semaphore.h> #endif struct rk_sema { #ifdef __APPLE__ dispatch_semaphore_t sem; #else sem_t sem; #endif }; static inline void rk_sema_init(struct rk_sema *s, uint32_t value) { #ifdef __APPLE__ dispatch_semaphore_t *sem = &s->sem; *sem = dispatch_semaphore_create(value); #else sem_init(&s->sem, 0, value); #endif } static inline void rk_sema_wait(struct rk_sema *s) { #ifdef __APPLE__ dispatch_semaphore_wait(s->sem, DISPATCH_TIME_FOREVER); #else int r; do { r = sem_wait(&s->sem); } while (r == -1 && errno == EINTR); #endif } static inline void rk_sema_post(struct rk_sema *s) { #ifdef __APPLE__ dispatch_semaphore_signal(s->sem); #else sem_post(&s->sem); #endif } void* CreateSharedMem(const char* name, off_t size){ int fd; void* ret; if((fd = shm_open(name, O_CREAT | O_RDWR, 0666)) == -1){ fprintf(stderr, "Error: Cannot create shared memory!\n"); perror(strerror(errno)); handleExit(0); } if(ftruncate(fd, size) == -1){ fprintf(stderr, "Error: Cannot clean shared memory!\n"); perror(strerror(errno)); handleExit(0); } if((ret = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)) == MAP_FAILED){ fprintf(stderr, "Error: Cannot map memory to process!\n"); perror(strerror(errno)); handleExit(0); } return ret; } void* GetSharedMem(const char* name, off_t size){ int fd; void* ret; if((fd = shm_open(name, O_RDWR, 0666)) == -1){ fprintf(stderr, "Error: Cannot load shared memory!\n"); perror(strerror(errno)); handleExit(0); } if((ret = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)) == MAP_FAILED){ fprintf(stderr, "Error: Cannot map memory to process!\n"); perror(strerror(errno)); handleExit(0); } return ret; } void ReleaseSharedMem(void* addr, size_t len, const char* name){ munmap(addr, len); shm_unlink(name); } void CloseSharedMem(void* addr, size_t len){ munmap(addr, len); } sem_t* CreateSemaphore(const char* name, unsigned int initVal){ sem_t* s = sem_open(name, O_CREAT | O_RDWR, 0666, initVal); if(s == SEM_FAILED){ fprintf(stderr, "Error: Cannot create semaphore!\n"); perror(strerror(errno)); handleExit(0); } return s; } sem_t* GetSemaphore(const char* name){ sem_t* s = sem_open(name, O_RDWR); if(s == SEM_FAILED){ fprintf(stderr, "Error: Cannot load semaphore!\n"); perror(strerror(errno)); handleExit(0); } return s; } void Take(sem_t* s){ if(sem_wait(s) == -1){ fprintf(stderr, "Error: Cannot load semaphore!\n"); perror(strerror(errno)); handleExit(0); } } void Release(sem_t* s){ if(sem_post(s) == -1){ fprintf(stderr, "Error: Cannot release semaphore!\n"); perror(strerror(errno)); handleExit(0); } } void CloseSemaphore(sem_t* s){ if(sem_close(s)) perror(strerror(errno)); } void RemoveSemaphore(const char* name){ if(sem_unlink(name) == -1){ fprintf(stderr, "Error: Cannot remove semaphore!.\n"); perror(strerror(errno)); } } int GetValue(sem_t* sem){ int ret; // if(sem_getvalue(sem, &ret) == -1){ // fprintf(stderr, "Error: Cannot get semaphore value!\n"); // perror(strerror(errno)); // handleExit(0); // } // return ret; return 0; }
C
/* Advanced Programming BlackJack Homework - Sockets Salomón Charabati October '19 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <netdb.h> #include "sockets.h" // Include own sockets library #include "sockets.h" #include "blackjack.h" #define SERVICE_PORT 8642 #define BUFFER_SIZE 1024 void usage(char * program); void communicationLoop(int connection_fd); int main(int argc, char * argv[]) { int client_fd; printf("\n=== CLIENT PROGRAM ===\n"); if (argc != 3) usage(argv[0]); client_fd = connectToServer(argv[1], argv[2]); communicationLoop(client_fd); // Closing the socket printf("Closing the connection socket\n"); close(client_fd); return 0; } // Show the user how to run this program void usage(char * program) { printf("Usage:\n%s {server_address} {port_number}\n", program); exit(EXIT_FAILURE); } // Do the actual receiving and sending of data void communicationLoop(int connection_fd) { char buffer[BUFFER_SIZE]; int balance; player_t playerClientSide; int bet; int chars_read; printf("Welcome to BlackJack!\n"); // INITIAL BALANCE PART printf("Enter you initial balance: "); scanf("%d",&balance); playerClientSide.balance = balance; // Handshake // Send a request with initial balance sprintf(buffer, "BALANCE:%d", playerClientSide.balance); send(connection_fd, buffer, strlen(buffer)+1, 0); printf("GAME READY! GOOD LUCK\n"); chars_read = receiveMessage(connection_fd,buffer,BUFFER_SIZE); while(1) { // BETTING PART printf("How much do you want to bet?\n"); scanf(" %d", &bet); sprintf(buffer,"BET: %d",bet); send(connection_fd,buffer,strlen(buffer)+1,0); // Send the proposed bet to the server // Check for server's response to bet proposed chars_read = receiveMessage(connection_fd,buffer,BUFFER_SIZE); if(strncmp(buffer,"Not valid",BUFFER_SIZE) == 0) { printf("You don't have enough money for placing that bet!\n"); break; }else{ printf("OKAY, you're betting %d in this hand\n",bet); } send(connection_fd,"OKAY",5,0); // DEALING CARDS PART // First card is automatically dealt and received here chars_read = receiveMessage(connection_fd,buffer,BUFFER_SIZE); printf("%s",buffer); // While the player hits, is below 21 or has exactly 21 while(1) { printf("Do you want to hit or stay (h/s)?: \n"); scanf(" %s", buffer); send(connection_fd,buffer,strlen(buffer)+1,0); chars_read = receiveMessage(connection_fd,buffer,BUFFER_SIZE); if(strncmp(buffer,"s",2) == 0 ||(strncmp(buffer,"Bust.",5) == 0 ) || (strncmp(buffer,"BLACKJACK!\n",15) == 0)) break; printf("%s",buffer); } send(connection_fd,"OKAY",5,0); // RESULTS PART chars_read = receiveMessage(connection_fd,buffer,BUFFER_SIZE); printf("%s",buffer); } }
C
int main() { int n,i,j,b,c,d,e,f; char a[1000][1000]; scanf("%d",&n); for(i=0;i<n;i++){ for(j=0;j<n;j++){ scanf("%d",&a[i][j]); }} c=-1; for(i=0;i<n;i++){ for(j=0;j<n;j++){ if(a[i][j]==0) {c=i;d=j; break;}} if(c!=-1){break;} } e=-1; for(i=n-1;i>=0;i--){ for(j=n-1;j>=0;j--){ if(a[i][j]==0){ e=i;f=j;break;}} if(e!=-1){ break;} } b=(e-c-1)*(f-d-1); printf("%d",b); return 0; }