diff --git a/CMakeLists.txt b/CMakeLists.txt index 60901084..455926f8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -13,12 +13,15 @@ include_directories(function_timer/include) # include_directories(${CMAKE_BINARY_DIR}/include) # link_directories(${CMAKE_BINARY_DIR}/lib/${CMAKE_BUILD_TYPE}) -set(CMAKE_C_STANDARD 99) +set(CMAKE_C_STANDARD 11) set(CMAKE_C_STANDARD_REQUIRED ON) add_subdirectory(conversions) add_subdirectory(misc) add_subdirectory(project_euler) +add_subdirectory(sorting) +add_subdirectory(searching) +add_subdirectory(numerical_methods) if(USE_OPENMP) find_package(OpenMP) diff --git a/DIRECTORY.md b/DIRECTORY.md index 2200cf13..a161aefc 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -5,15 +5,6 @@ * [Udp Client](https://github.com/TheAlgorithms/C/blob/master/client_server/UDP_Client.c) * [Udp Server](https://github.com/TheAlgorithms/C/blob/master/client_server/UDP_Server.c) -## Computer Oriented Statistical Methods - * [Gauss Elimination](https://github.com/TheAlgorithms/C/blob/master/computer_oriented_statistical_methods/Gauss_Elimination.c) - * [Lagrange Theorem](https://github.com/TheAlgorithms/C/blob/master/computer_oriented_statistical_methods/lagrange_theorem.C) - * [Mean](https://github.com/TheAlgorithms/C/blob/master/computer_oriented_statistical_methods/MEAN.C) - * [Median](https://github.com/TheAlgorithms/C/blob/master/computer_oriented_statistical_methods/MEDIAN.C) - * [Seidal](https://github.com/TheAlgorithms/C/blob/master/computer_oriented_statistical_methods/Seidal.C) - * [Simpson'S 1-3Rd Rule](https://github.com/TheAlgorithms/C/blob/master/computer_oriented_statistical_methods/simpson's%201-3rd%20rule.c) - * [Variance](https://github.com/TheAlgorithms/C/blob/master/computer_oriented_statistical_methods/variance.c) - ## Conversions * [Binary To Decimal](https://github.com/TheAlgorithms/C/blob/master/conversions/binary_to_decimal.c) * [Binary To Hexadecimal](https://github.com/TheAlgorithms/C/blob/master/conversions/binary_to_hexadecimal.c) @@ -206,6 +197,16 @@ * [Tower Of Hanoi](https://github.com/TheAlgorithms/C/blob/master/misc/Tower_Of_Hanoi.c) * [Union Find](https://github.com/TheAlgorithms/C/blob/master/misc/union_Find.c) +## Numerical Methods + * [Gauss Elimination](https://github.com/TheAlgorithms/C/blob/master/numerical_methods/Gauss_Elimination.c) + * [Lagrange Theorem](https://github.com/TheAlgorithms/C/blob/master/numerical_methods/lagrange_theorem.C) + * [Mean](https://github.com/TheAlgorithms/C/blob/master/numerical_methods/MEAN.C) + * [Median](https://github.com/TheAlgorithms/C/blob/master/numerical_methods/MEDIAN.C) + * [Newton-Raphson-Root](https://github.com/TheAlgorithms/C/blob/master/numerical_methods/newton-raphson-root.c) + * [Seidal](https://github.com/TheAlgorithms/C/blob/master/numerical_methods/Seidal.C) + * [Simpsons 1-3Rd Rule](https://github.com/TheAlgorithms/C/blob/master/numerical_methods/simpsons_1-3rd%20rule.c) + * [Variance](https://github.com/TheAlgorithms/C/blob/master/numerical_methods/variance.c) + ## Project Euler * Problem 01 * [Sol1](https://github.com/TheAlgorithms/C/blob/master/project_euler/Problem%2001/sol1.c) @@ -257,6 +258,8 @@ * [Sol2](https://github.com/TheAlgorithms/C/blob/master/project_euler/Problem%2023/sol2.c) * Problem 25 * [Sol1](https://github.com/TheAlgorithms/C/blob/master/project_euler/Problem%2025/sol1.c) + * Problem 26 + * [Sol1](https://github.com/TheAlgorithms/C/blob/master/project_euler/Problem%2026/sol1.c) ## Searching * [Binary Search](https://github.com/TheAlgorithms/C/blob/master/searching/Binary_Search.c) @@ -296,4 +299,5 @@ * [Selection Sort](https://github.com/TheAlgorithms/C/blob/master/sorting/Selection_Sort.c) * [Shaker Sort](https://github.com/TheAlgorithms/C/blob/master/sorting/shaker_sort.c) * [Shell Sort](https://github.com/TheAlgorithms/C/blob/master/sorting/shell_Sort.c) + * [Shell Sort2](https://github.com/TheAlgorithms/C/blob/master/sorting/shell_Sort2.c) * [Stooge Sort](https://github.com/TheAlgorithms/C/blob/master/sorting/Stooge_Sort.c) diff --git a/client_server/client.c b/client_server/client.c index bd208362..a223478b 100644 --- a/client_server/client.c +++ b/client_server/client.c @@ -1,66 +1,71 @@ -// Write CPP code here -#include -#include -#include +// Write CPP code here +#include +#include +#include #include -#include -#include -#define MAX 80 -#define PORT 8080 -#define SA struct sockaddr -void func(int sockfd) -{ - char buff[MAX]; - int n; - for (;;) { - bzero(buff, sizeof(buff)); - printf("Enter the string : "); - n = 0; - while ((buff[n++] = getchar()) != '\n') - ; - write(sockfd, buff, sizeof(buff)); - bzero(buff, sizeof(buff)); - read(sockfd, buff, sizeof(buff)); - printf("From Server : %s", buff); - if ((strncmp(buff, "exit", 4)) == 0) { - printf("Client Exit...\n"); - break; - } - } -} - -int main() -{ - int sockfd, connfd; - struct sockaddr_in servaddr, cli; - - // socket create and varification - sockfd = socket(AF_INET, SOCK_STREAM, 0); - if (sockfd == -1) { - printf("socket creation failed...\n"); - exit(0); - } +#include +#include +#include +#define MAX 80 +#define PORT 8080 +#define SA struct sockaddr +void func(int sockfd) +{ + char buff[MAX]; + int n; + for (;;) + { + bzero(buff, sizeof(buff)); + printf("Enter the string : "); + n = 0; + while ((buff[n++] = getchar()) != '\n') + ; + write(sockfd, buff, sizeof(buff)); + bzero(buff, sizeof(buff)); + read(sockfd, buff, sizeof(buff)); + printf("From Server : %s", buff); + if ((strncmp(buff, "exit", 4)) == 0) + { + printf("Client Exit...\n"); + break; + } + } +} + +int main() +{ + int sockfd, connfd; + struct sockaddr_in servaddr, cli; + + // socket create and varification + sockfd = socket(AF_INET, SOCK_STREAM, 0); + if (sockfd == -1) + { + printf("socket creation failed...\n"); + exit(0); + } else - printf("Socket successfully created..\n"); - bzero(&servaddr, sizeof(servaddr)); - - // assign IP, PORT - servaddr.sin_family = AF_INET; - servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); - servaddr.sin_port = htons(PORT); - - // connect the client socket to server socket - if (connect(sockfd, (SA*)&servaddr, sizeof(servaddr)) != 0) { - printf("connection with the server failed...\n"); - exit(0); - } + printf("Socket successfully created..\n"); + bzero(&servaddr, sizeof(servaddr)); + + // assign IP, PORT + servaddr.sin_family = AF_INET; + servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); + servaddr.sin_port = htons(PORT); + + // connect the client socket to server socket + if (connect(sockfd, (SA *)&servaddr, sizeof(servaddr)) != 0) + { + printf("connection with the server failed...\n"); + exit(0); + } else - printf("connected to the server..\n"); - - // function for chat - func(sockfd); - - // close the socket - close(sockfd); -} + printf("connected to the server..\n"); + + // function for chat + func(sockfd); + + // close the socket + close(sockfd); +} diff --git a/computer_oriented_statistical_methods/Gauss_Elimination.c b/computer_oriented_statistical_methods/Gauss_Elimination.c deleted file mode 100644 index e35fa7ba..00000000 --- a/computer_oriented_statistical_methods/Gauss_Elimination.c +++ /dev/null @@ -1,100 +0,0 @@ -#include -#include -void display(float a[20][20],int n) -{ - int i,j; - for(i=0;i>>\n",i+1); - for(j=0;j<=n;j++) - { - printf("r%d%d : ",i,j); - scanf("%f",&m[i][j]); - } - printf("\n"); - } - printf(":::::::::::: Current Matrix ::::::::::::\n\n"); - display(m,n); - - for(i=0;i>>>>>>>>>>>>>>>>>>>>>>>-------- %d\n",i+1); - m[20][20]=interchange(m,i,n); - display(m,n); - printf("\n_______________________________________\n"); - m[20][20]=eliminate(m,i,n); - display(m,n); - } - printf("\n\n Values are : \n"); - for(i=n-1;i>=0;i--) - { - l=n-1; - mul=0; - for(j=0;j -#include -#include -void main() -{ - int a[10],n,i,j,temp,sum=0; - float mean; - clrscr(); - printf("Enter no. for Random Numbers :"); - scanf("%d",&n); - for(i=0;i -//#include -#include - -void main() -{ - int a[10],n,i,j,temp; - float mean,median; - clrscr(); - printf("Enter no. for Random Numbers :"); - scanf("%d",&n); - for(i=0;i -#include -#include -void main() -{ - float a,b,c,a1,a2,a3,b1,b2,b3,c1,c2,c3,d1,d2,d3,x1,x2,x3; - clrscr(); - printf("Enter values of eq1:"); - scanf("%f%f%f%f",&a1,&a2,&a3,&d1); - printf("Enter values of eq2:"); - scanf("%f%f%f%f",&b1,&b2,&b3,&d2); - printf("Enter values of eq3:"); - scanf("%f%f%f%f",&c1,&c2,&c3,&d3); - x1=x2=x3=0.0; - do - { - a=x1; - b=x2; - c=x3; - x1=(1/a1)*(d1-(a2*x2)-(a3*x3)); - x2=(1/b2)*(d2-(b1*x1)-(b3*x3)); - x3=(1/c3)*(d3-(c1*x1)-(c2*x2)); - }while(fabs(x1-a)>0.0001&&fabs(x2-b)>0.0001&&fabs(x3-c)>0.0001); - printf("x1=%f\nx2=%f\nx3=%f",x1,x2,x3); - getch(); -} \ No newline at end of file diff --git a/computer_oriented_statistical_methods/lagrange_theorem.C b/computer_oriented_statistical_methods/lagrange_theorem.C deleted file mode 100644 index 1b4694bb..00000000 --- a/computer_oriented_statistical_methods/lagrange_theorem.C +++ /dev/null @@ -1,45 +0,0 @@ -#include -#include -#include -#include -void main() -{ - float x[20],y[20],a,sum,p; - int n,i,j; - clrscr(); - printf("Enter the no of entry to insert->"); - scanf("%d",&n); - - for(i=0;i",i); - scanf("%f",&x[i]); - printf("enter the value of y%d->",i); - scanf("%f",&y[i]); - } - printf("\n X \t\t Y \n"); - printf("----------------------------\n"); - for(i=0;i%f",sum); - getch(); - -}} \ No newline at end of file diff --git a/computer_oriented_statistical_methods/simpson's 1-3rd rule.c b/computer_oriented_statistical_methods/simpson's 1-3rd rule.c deleted file mode 100644 index fe083b89..00000000 --- a/computer_oriented_statistical_methods/simpson's 1-3rd rule.c +++ /dev/null @@ -1,41 +0,0 @@ -#include -#include - -float f(float x) -{ - return 1.0+x*x*x; //This is the expresion of the function to integrate? -} - -void main() -{ - int i,n; - float a,b,h,x,s2,s3,sum,integral; - - printf("enter the lower limit of the integration:"); - scanf("%f",&a); - printf("enter the upper limit of the integration:"); - scanf("%f",&b); - printf("enter the number of intervals:"); - scanf("%d",&n); - - h=(b-a)/n; - sum=f(a)+f(b); - s2=s3=0.0; - - for(i=1;i int decimal_to_octal(int decimal) { - if( (decimal<8) && (decimal>0) ) + if ((decimal < 8) && (decimal > 0)) { return decimal; } - else if(decimal==0) + else if (decimal == 0) { return 0; } else { - return ( (decimal_to_octal(decimal/8)*10) + decimal%8 ); + return ((decimal_to_octal(decimal / 8) * 10) + decimal % 8); } } -void main() +int main() { - int octalNumber,decimalNumber; + int octalNumber, decimalNumber; printf("\nEnter your decimal number : "); - scanf("%d",&decimalNumber); + scanf("%d", &decimalNumber); octalNumber = decimal_to_octal(decimalNumber); - printf("\nThe octal of %d is : %d" ,decimalNumber,octalNumber); + printf("\nThe octal of %d is : %d", decimalNumber, octalNumber); + return 0; } diff --git a/conversions/hexadecimal_to_octal.c b/conversions/hexadecimal_to_octal.c index 097ba87c..7340dcd1 100644 --- a/conversions/hexadecimal_to_octal.c +++ b/conversions/hexadecimal_to_octal.c @@ -4,81 +4,82 @@ int main() { - char hex[17]; +#define MAX_STR_LEN 17 + char hex[MAX_STR_LEN]; long long octal, bin, place; int i = 0, rem, val; /* Input hexadecimal number from user */ printf("Enter any hexadecimal number: "); - gets(hex); + fgets(hex, MAX_STR_LEN, stdin); octal = 0ll; bin = 0ll; place = 0ll; /* Hexadecimal to binary conversion */ - for(i=0; hex[i]!='\0'; i++) + for (i = 0; hex[i] != '\0'; i++) { bin = bin * place; - switch(hex[i]) + switch (hex[i]) { - case '0': - bin += 0; - break; - case '1': - bin += 1; - break; - case '2': - bin += 10; - break; - case '3': - bin += 11; - break; - case '4': - bin += 100; - break; - case '5': - bin += 101; - break; - case '6': - bin += 110; - break; - case '7': - bin += 111; - break; - case '8': - bin += 1000; - break; - case '9': - bin += 1001; - break; - case 'a': - case 'A': - bin += 1010; - break; - case 'b': - case 'B': - bin += 1011; - break; - case 'c': - case 'C': - bin += 1100; - break; - case 'd': - case 'D': - bin += 1101; - break; - case 'e': - case 'E': - bin += 1110; - break; - case 'f': - case 'F': - bin += 1111; - break; - default: - printf("Invalid hexadecimal input."); + case '0': + bin += 0; + break; + case '1': + bin += 1; + break; + case '2': + bin += 10; + break; + case '3': + bin += 11; + break; + case '4': + bin += 100; + break; + case '5': + bin += 101; + break; + case '6': + bin += 110; + break; + case '7': + bin += 111; + break; + case '8': + bin += 1000; + break; + case '9': + bin += 1001; + break; + case 'a': + case 'A': + bin += 1010; + break; + case 'b': + case 'B': + bin += 1011; + break; + case 'c': + case 'C': + bin += 1100; + break; + case 'd': + case 'D': + bin += 1101; + break; + case 'e': + case 'E': + bin += 1110; + break; + case 'f': + case 'F': + bin += 1111; + break; + default: + printf("Invalid hexadecimal input."); } place = 10000; @@ -87,36 +88,36 @@ int main() place = 1; /* Binary to octal conversion */ - while(bin > 0) + while (bin > 0) { rem = bin % 1000; - switch(rem) + switch (rem) { - case 0: - val = 0; - break; - case 1: - val = 1; - break; - case 10: - val = 2; - break; - case 11: - val = 3; - break; - case 100: - val = 4; - break; - case 101: - val = 5; - break; - case 110: - val = 6; - break; - case 111: - val = 7; - break; + case 0: + val = 0; + break; + case 1: + val = 1; + break; + case 10: + val = 2; + break; + case 11: + val = 3; + break; + case 100: + val = 4; + break; + case 101: + val = 5; + break; + case 110: + val = 6; + break; + case 111: + val = 7; + break; } octal = (val * place) + octal; @@ -129,4 +130,4 @@ int main() printf("Octal number = %lld", octal); return 0; -} +} diff --git a/function_timer b/function_timer index 327ddab3..e0dc782b 160000 --- a/function_timer +++ b/function_timer @@ -1 +1 @@ -Subproject commit 327ddab3e895c26026eeb39ed7e0b44d82597137 +Subproject commit e0dc782b7b0f162299d10d94b0132f111d89c22f diff --git a/hash/test_program.c b/hash/test_program.c index 3f741bc6..1ce85c85 100644 --- a/hash/test_program.c +++ b/hash/test_program.c @@ -1,20 +1,20 @@ -/* - author: Christian Bender - This file contains a simple test program for each hash-function. -*/ - -#include -#include "hash.h" - -int main(void) -{ - char s[] = "hello"; - - /* actual tests */ - printf("sdbm: %s --> %llX\n", s, sdbm(s)); - printf("djb2: %s --> %llX\n", s, djb2(s)); - printf("xor8: %s --> %X\n", s, xor8(s)); /* 8 bit */ - printf("adler_32: %s --> %X\n", s, adler_32(s)); /* 32 bit */ - - return 0; -} +/* + author: Christian Bender + This file contains a simple test program for each hash-function. +*/ + +#include +#include "hash.h" + +int main(void) +{ + char s[] = "hello"; + + /* actual tests */ + printf("sdbm: %s --> %llX\n", s, sdbm(s)); + printf("djb2: %s --> %llX\n", s, djb2(s)); + printf("xor8: %s --> %X\n", s, xor8(s)); /* 8 bit */ + printf("adler_32: %s --> %X\n", s, adler_32(s)); /* 32 bit */ + + return 0; +} diff --git a/misc/CMakeLists.txt b/misc/CMakeLists.txt index be8a549f..493bc06e 100644 --- a/misc/CMakeLists.txt +++ b/misc/CMakeLists.txt @@ -1,3 +1,8 @@ + +if(USE_OPENMP) + find_package(OpenMP) +endif() + # If necessary, use the RELATIVE flag, otherwise each source file may be listed # with full pathname. RELATIVE may makes it easier to extract an executable name # automatically. @@ -11,6 +16,9 @@ foreach( testsourcefile ${APP_SOURCES} ) # Make sure YourLib is linked to each app target_link_libraries( ${testname} function_timer ) set_target_properties(${testname} PROPERTIES LINKER_LANGUAGE C) + if(OpenMP_C_FOUND) + target_link_libraries(${testname} OpenMP::OpenMP_C) + endif() install(TARGETS ${testname} DESTINATION "bin/misc") endforeach( testsourcefile ${APP_SOURCES} ) diff --git a/misc/rselect.c b/misc/rselect.c index 9679bf00..af9be942 100644 --- a/misc/rselect.c +++ b/misc/rselect.c @@ -1,54 +1,77 @@ #include -#include -#include -void swap(int *a ,int *b) -{int t;t =*a;*a=*b;*b=t;} -int part(int a[],int l,int r,int n,int pivot,int pindex) -{int p1=l,p2=r; - while(p2>p1) +#include +#include +void swap(int *a, int *b) +{ + int t; + t = *a; + *a = *b; + *b = t; +} +int part(int a[], int l, int r, int n, int pivot, int pindex) +{ + int p1 = l, p2 = r; + while (p2 > p1) { - if (a[p1] > pivot && a[p2] pivot && a[p2] < pivot) + { + swap(&a[p1], &a[p2]); + } else { - if (a[p1] <=pivot) - {p1++;} - if (a[p2]>=pivot) - {p2--;} + if (a[p1] <= pivot) + { + p1++; + } + if (a[p2] >= pivot) + { + p2--; + } } } - swap(&a[pindex],&a[p2]); + swap(&a[pindex], &a[p2]); return p2; } -int rselect(int a[],int l,int r,int n,int o) +int rselect(int a[], int l, int r, int n, int o) { - int pivot,pindex,pactual; - if (r>l) + int pivot, pindex, pactual; + if (r > l) { - pindex = rand()%(r-l+1); - pivot = a[pindex]; - pactual = part(a,l,r,n,pivot,pindex); - - if (pactual == o) - {return a[pactual];} - - if (o < pactual) - {rselect(a,l,pactual-1,n,o);} - - if (o>pactual) - {rselect(a,pactual+1,r,n,o-pactual);} + pindex = rand() % (r - l + 1); + pivot = a[pindex]; + pactual = part(a, l, r, n, pivot, pindex); + + if (pactual == o) + { + return a[pactual]; + } + + if (o < pactual) + { + rselect(a, l, pactual - 1, n, o); + } + + if (o > pactual) + { + rselect(a, pactual + 1, r, n, o - pactual); + } } - if (r==l) - {return a[l];} + if (r == l) + { + return a[l]; + } + return -1; } int main() -{srand(time(NULL)); - int n,o,i,*a; - scanf("%d %d",&n,&o); - a = (int*)malloc(n*sizeof(int)); - for (i=0;i - +#include void strng(int a) { - int j=a; - int sum=0; - int b,i,fact=1; - while(a>0) + int j = a; + int sum = 0; + int b, i, fact = 1; + while (a > 0) { - fact=1; - b=a%10; - for(i=1;i<=b;i++) + fact = 1; + b = a % 10; + for (i = 1; i <= b; i++) { - fact=fact*i; + fact = fact * i; } - a=a/10; - sum=sum+fact; + a = a / 10; + sum = sum + fact; } - if(sum==j) - printf("%d is a strong number",j); + if (sum == j) + printf("%d is a strong number", j); else - printf("%d is not a strong number",j); + printf("%d is not a strong number", j); } -void main() +int main() { int a; printf("Enter the number to check"); - scanf("%d",&a); + scanf("%d", &a); strng(a); + return 0; } diff --git a/numerical_methods/CMakeLists.txt b/numerical_methods/CMakeLists.txt new file mode 100644 index 00000000..4e5d0fe2 --- /dev/null +++ b/numerical_methods/CMakeLists.txt @@ -0,0 +1,26 @@ +if(USE_OPENMP) + find_package(OpenMP) +endif(USE_OPENMP) +# If necessary, use the RELATIVE flag, otherwise each source file may be listed +# with full pathname. RELATIVE may makes it easier to extract an executable name +# automatically. +file( GLOB APP_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.c ) +# file( GLOB APP_SOURCES ${CMAKE_SOURCE_DIR}/*.c ) +# AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR} APP_SOURCES) +foreach( testsourcefile ${APP_SOURCES} ) + # I used a simple string replace, to cut off .cpp. + string( REPLACE ".c" "" testname ${testsourcefile} ) + string( REPLACE " " "_" testname ${testsourcefile} ) + + add_executable( ${testname} ${testsourcefile} ) + + # Make sure YourLib is linked to each app + target_link_libraries( ${testname} function_timer ) + set_target_properties(${testname} PROPERTIES LINKER_LANGUAGE C) + if(OpenMP_C_FOUND) + target_link_libraries(${testname} OpenMP::OpenMP_C) + endif() + + install(TARGETS ${testname} DESTINATION "bin/stats") + +endforeach( testsourcefile ${APP_SOURCES} ) diff --git a/numerical_methods/Gauss_Elimination.c b/numerical_methods/Gauss_Elimination.c new file mode 100644 index 00000000..38f6fb31 --- /dev/null +++ b/numerical_methods/Gauss_Elimination.c @@ -0,0 +1,104 @@ +#include +#include + +#define ARRAY_SIZE 20 + +void display(float a[ARRAY_SIZE][ARRAY_SIZE], int n) +{ + int i, j; + for (i = 0; i < n; i++) + { + for (j = 0; j <= n; j++) + { + printf("%.2f \t", a[i][j]); + } + printf("\n"); + } +} + +float interchange(float m[ARRAY_SIZE][ARRAY_SIZE], int i, int n) +{ + float tmp[ARRAY_SIZE][ARRAY_SIZE]; + float max = fabs(m[i][i]); + int j, k = i; + + for (j = i; j < n; j++) + { + if (max < fabs(m[j][i])) + { + max = fabs(m[j][i]); + k = j; + } + } + for (j = 0; j <= n; j++) + { + tmp[i][j] = m[i][j]; + m[i][j] = m[k][j]; + m[k][j] = tmp[i][j]; + } + return m[ARRAY_SIZE - 1][ARRAY_SIZE - 1]; +} +float eliminate(float m[ARRAY_SIZE][ARRAY_SIZE], int i, int n) +{ + float tmp; + int k = 1, l, j; + for (j = i; j < n - 1; j++) + { + tmp = -((m[i + k][i]) / (m[i][i])); + for (l = 0; l <= n; l++) + { + m[i + k][l] = (m[i + k][l]) + (m[i][l] * tmp); + } + k++; + } + return m[ARRAY_SIZE - 1][ARRAY_SIZE - 1]; +} +int main(void) +{ + int i, j, n, k = 0, l; + float m[ARRAY_SIZE][ARRAY_SIZE], mul, tmp[ARRAY_SIZE][ARRAY_SIZE], val, ans[ARRAY_SIZE]; + + printf("Total No.of Equations : "); + scanf("%d", &n); + + printf("\n"); + for (i = 0; i < n; i++) + { + + printf("Enter Co-efficient Of Equations %d & Total --->>>\n", i + 1); + for (j = 0; j <= n; j++) + { + printf("r%d%d : ", i, j); + scanf("%f", &m[i][j]); + } + printf("\n"); + } + printf(":::::::::::: Current Matrix ::::::::::::\n\n"); + display(m, n); + + for (i = 0; i < n - 1; i++) + { + printf("\n------->>>>>>>>>>>>>>>>>>>>>>>>-------- %d\n", i + 1); + m[ARRAY_SIZE - 1][ARRAY_SIZE - 1] = interchange(m, i, n); + display(m, n); + printf("\n_______________________________________\n"); + m[ARRAY_SIZE - 1][ARRAY_SIZE - 1] = eliminate(m, i, n); + display(m, n); + } + printf("\n\n Values are : \n"); + for (i = n - 1; i >= 0; i--) + { + l = n - 1; + mul = 0; + for (j = 0; j < k; j++) + { + mul = mul + m[i][l] * ans[l]; + l--; + } + k++; + ans[i] = (m[i][n] - mul) / m[i][i]; + printf("X%d = %.2f\n", i + 1, ans[i]); + } + + return 0; +} diff --git a/numerical_methods/MEAN.C b/numerical_methods/MEAN.C new file mode 100644 index 00000000..160c8b75 --- /dev/null +++ b/numerical_methods/MEAN.C @@ -0,0 +1,39 @@ +#include +#include +#include +#include + +#define MAX_LEN INT_MAX + +int main(int argc, char **argv) +{ + int a[MAX_LEN], n = 10, i, j, temp, sum = 0; + float mean; + + if (argc == 2) + { + n = atoi(argv[1]); + if (n >= MAX_LEN) + { + fprintf(stderr, "Maximum %d!\n", MAX_LEN); + return 1; + } + } + + printf("Random Numbers Generated are : "); + for (i = 0; i < n; i++) + { + a[i] = rand() % 100; + printf("%2d, ", a[i]); + } + putchar('\n'); + + for (i = 0; i < n; i++) + sum = sum + a[i]; + + mean = sum / (float)n; + printf("\nMean :"); + printf("%f", mean); + + return 0; +} diff --git a/numerical_methods/MEDIAN.C b/numerical_methods/MEDIAN.C new file mode 100644 index 00000000..ad24cdef --- /dev/null +++ b/numerical_methods/MEDIAN.C @@ -0,0 +1,51 @@ +#include +#include +#include + +int main() +{ + int a[10], n, i, j, temp; + float mean, median; + + printf("Enter no. for Random Numbers :"); + scanf("%d", &n); + for (i = 0; i < n; i++) + { + a[i] = rand() % 100; + } + printf("Random Numbers Generated are :\n"); + for (i = 0; i < n; i++) + { + printf("\n%d", a[i]); + } + printf("\n"); + printf("\nSorted Data:"); + for (i = 0; i < n; i++) + { + for (j = 0; j < n; j++) + { + if (a[i] < a[j]) + { + temp = a[i]; + a[i] = a[j]; + a[j] = temp; + } + } + } + for (i = 0; i < n; i++) + { + printf("\n%d", a[i]); + } + + if (n % 2 == 0) + { + median = (a[n / 2] + a[(n / 2) - 1]) / 2; + } + else + { + median = a[n / 2]; + } + printf("\nMedian is : %f", median); + + return 0; +} diff --git a/numerical_methods/Seidal.C b/numerical_methods/Seidal.C new file mode 100644 index 00000000..d073d879 --- /dev/null +++ b/numerical_methods/Seidal.C @@ -0,0 +1,27 @@ +#include +#include + +int main() +{ + float a, b, c, a1, a2, a3, b1, b2, b3, c1, c2, c3, d1, d2, d3, x1, x2, x3; + + printf("Enter values of eq1:"); + scanf("%f%f%f%f", &a1, &a2, &a3, &d1); + printf("Enter values of eq2:"); + scanf("%f%f%f%f", &b1, &b2, &b3, &d2); + printf("Enter values of eq3:"); + scanf("%f%f%f%f", &c1, &c2, &c3, &d3); + x1 = x2 = x3 = 0.0; + do + { + a = x1; + b = x2; + c = x3; + x1 = (1 / a1) * (d1 - (a2 * x2) - (a3 * x3)); + x2 = (1 / b2) * (d2 - (b1 * x1) - (b3 * x3)); + x3 = (1 / c3) * (d3 - (c1 * x1) - (c2 * x2)); + } while (fabs(x1 - a) > 0.0001 && fabs(x2 - b) > 0.0001 && fabs(x3 - c) > 0.0001); + printf("x1=%f\nx2=%f\nx3=%f", x1, x2, x3); + + return 0; +} \ No newline at end of file diff --git a/numerical_methods/lagrange_theorem.C b/numerical_methods/lagrange_theorem.C new file mode 100644 index 00000000..397cd9f5 --- /dev/null +++ b/numerical_methods/lagrange_theorem.C @@ -0,0 +1,46 @@ +#include +#include +#include + +int main() +{ + float x[20], y[20], a, sum, p; + int n, i, j; + + printf("Enter the no of entry to insert->"); + scanf("%d", &n); + + for (i = 0; i < n; i++) + { + printf("enter the value of x%d->", i); + scanf("%f", &x[i]); + printf("enter the value of y%d->", i); + scanf("%f", &y[i]); + } + printf("\n X \t\t Y \n"); + printf("----------------------------\n"); + for (i = 0; i < n; i++) + { + printf("%f\t", x[i]); + printf("%f\n", y[i]); + } + printf("\nenter the value of x for interpolation:"); + scanf("%f", &a); + sum = 0; + for (i = 0; i < n; i++) + { + p = 1.0; + for (j = 0; j < n; j++) + { + + if (i != j) + { + p = p * (a - x[j]) / (x[i] - x[j]); + } + sum = sum + y[i] * p; + } + printf("ans is->%f", sum); + + return 0; + } +} \ No newline at end of file diff --git a/numerical_methods/newton-raphson-root.c b/numerical_methods/newton-raphson-root.c new file mode 100644 index 00000000..eb67204b --- /dev/null +++ b/numerical_methods/newton-raphson-root.c @@ -0,0 +1,68 @@ +/*** + * approximate solution for f(x) = 0 + * given f(x) and f'(x) + **/ + +#include +#include +#include +#include +#include +#include /* requires minimum of C99 */ + +/** + * f(x) + */ +double complex function(double complex x) +{ + return x * x - 3.; /* x^2 = 3 - solution is sqrt(3) */ + // return x * x - 2.; /* x^2 = 2 - solution is sqrt(2) */ +} + +/** + * f'(x) + */ +double complex d_function(double complex x) +{ + return 2. * x; +} + +int main(int argc, char **argv) +{ + const double accuracy = 1e-10; + double delta = 1; + double complex cdelta = 1; + + /* initialize random seed: */ + srand(time(NULL)); + + double complex root = (rand() % 100 - 50) + (random() % 100 - 50) * I; + + unsigned long counter = 0; + while (delta > accuracy && counter < ULONG_MAX) + { + cdelta = function(root) / d_function(root); + root += -cdelta; + counter++; + delta = fabs(cabs(cdelta)); + +#if defined(DEBUG) || !defined(NDEBUG) + if (counter % 50 == 0) + { + double r = creal(root); + double c = cimag(root); + + printf("Iter %5lu: Root: %4.4g%c%4.4gi\t\tdelta: %.4g\n", counter, r, + c >= 0 ? '+' : '-', c >= 0 ? c : -c, delta); + } +#endif + } + + double r = creal(root); + double c = fabs(cimag(root)) < accuracy ? 0 : cimag(root); + + printf("Iter %5lu: Root: %4.4g%c%4.4gi\t\tdelta: %.4g\n", counter, r, + c >= 0 ? '+' : '-', c >= 0 ? c : -c, delta); + + return 0; +} \ No newline at end of file diff --git a/numerical_methods/simpsons_1-3rd rule.c b/numerical_methods/simpsons_1-3rd rule.c new file mode 100644 index 00000000..a055cc1e --- /dev/null +++ b/numerical_methods/simpsons_1-3rd rule.c @@ -0,0 +1,41 @@ +#include +#include + +float f(float x) +{ + return 1.0 + x * x * x; //This is the expresion of the function to integrate? +} + +int main() +{ + int i, n; + float a, b, h, x, s2, s3, sum, integral; + + printf("enter the lower limit of the integration:"); + scanf("%f", &a); + printf("enter the upper limit of the integration:"); + scanf("%f", &b); + printf("enter the number of intervals:"); + scanf("%d", &n); + + h = (b - a) / n; + sum = f(a) + f(b); + s2 = s3 = 0.0; + + for (i = 1; i < n; i += 3) + { + x = a + i * h; + s3 = s3 + f(x) + f(x + h); + } + + for (i = 3; i < n; i += 3) + { + x = a + i * h; + s2 = s2 + f(x); + } + + integral = (h / 3.0) * (sum + 2 * s2 + 4 * s3); + printf("\nValue of the integral = %9.4f\n", integral); + + return 0; +} \ No newline at end of file diff --git a/computer_oriented_statistical_methods/variance.c b/numerical_methods/variance.c similarity index 100% rename from computer_oriented_statistical_methods/variance.c rename to numerical_methods/variance.c diff --git a/project_euler/Problem 03/sol1.c b/project_euler/Problem 03/sol1.c index 369ec72d..680b2882 100644 --- a/project_euler/Problem 03/sol1.c +++ b/project_euler/Problem 03/sol1.c @@ -6,47 +6,61 @@ e.g. for 10, largest prime factor = 5. For 17, largest prime factor = 17. #include #include -int isprime(int no) { +int isprime(int no) +{ int sq; - if (no == 2) { + if (no == 2) + { return 1; } - else if (no%2 == 0) { + else if (no % 2 == 0) + { return 0; } sq = ((int)(sqrt(no))) + 1; - for (int i = 3; i < sq; i + 2) { - if (no%i == 0) { + for (int i = 3; i < sq; i += 2) + { + if (no % i == 0) + { return 0; } } return 1; } -int main() { +int main() +{ int maxNumber = 0; int n = 0; int n1; scanf("%d", &n); if (isprime(n) == 1) printf("%d", n); - else { - while (n % 2 == 0) { + else + { + while (n % 2 == 0) + { n = n / 2; } - if (isprime(n) == 1) { + if (isprime(n) == 1) + { printf("%d\n", n); } - else { + else + { n1 = ((int)(sqrt(n))) + 1; - for (int i = 3; i < n1; i + 2) { - if (n%i == 0) { - if (isprime((int)(n / i)) == 1) { + for (int i = 3; i < n1; i += 2) + { + if (n % i == 0) + { + if (isprime((int)(n / i)) == 1) + { maxNumber = n / i; break; } - else if (isprime(i) == 1) { + else if (isprime(i) == 1) + { maxNumber = i; } } diff --git a/project_euler/Problem 05/sol.c b/project_euler/Problem 05/sol.c index 12599033..b3190d2e 100644 --- a/project_euler/Problem 05/sol.c +++ b/project_euler/Problem 05/sol.c @@ -1,28 +1,34 @@ #include -unsigned long gcd(unsigned long a, unsigned long b) { +unsigned long gcd(unsigned long a, unsigned long b) +{ unsigned long r; - if (a > b) { + if (a > b) + { unsigned long t = a; a = b; b = t; } - while (r = a % b) { + while ((r = (a % b))) + { a = b; b = r; } return b; } -unsigned long lcm(unsigned long a, unsigned long b) { +unsigned long lcm(unsigned long a, unsigned long b) +{ unsigned long long p = (unsigned long long)a * b; return p / gcd(a, b); } -int main(void) { +int main(void) +{ unsigned long ans = 1; unsigned long i; - for (i = 1; i <= 20; i++) { + for (i = 1; i <= 20; i++) + { ans = lcm(ans, i); } printf("%lu\n", ans); diff --git a/project_euler/Problem 08/sol1.c b/project_euler/Problem 08/sol1.c index 1c57045e..2615648b 100644 --- a/project_euler/Problem 08/sol1.c +++ b/project_euler/Problem 08/sol1.c @@ -1,13 +1,12 @@ #include -#include #include -int64_t get_product(FILE *fp, long start_pos, int num_digits) +long long int get_product(FILE *fp, long start_pos, int num_digits) { - char ch = ' '; /* temporary variable to store character read from file */ - uint8_t num = 0; /* temporary variable to store digit read */ - int64_t prod = 1; /* product accumulator */ - int count = 0; /* we use this variable to count number of bytes of file read */ + char ch = ' '; /* temporary variable to store character read from file */ + unsigned char num = 0; /* temporary variable to store digit read */ + long long int prod = 1; /* product accumulator */ + int count = 0; /* we use this variable to count number of bytes of file read */ /* accumulate product for num_digits */ for (int i = 0; i < num_digits; i++, count++) @@ -49,7 +48,7 @@ int main(int argc, char *argv[]) { int position = 0; int num_digits = 4; - int64_t prod, max_prod = 0; + long long int prod, max_prod = 0; /* if second command-line argument is ge=iven, * use it as the number of digits to compute diff --git a/project_euler/Problem 08/sol2.c b/project_euler/Problem 08/sol2.c index 67371886..5a9e2155 100644 --- a/project_euler/Problem 08/sol2.c +++ b/project_euler/Problem 08/sol2.c @@ -1,6 +1,5 @@ #include #include -#include #include /* for memmove */ int main(int argc, char *argv[]) @@ -8,9 +7,9 @@ int main(int argc, char *argv[]) int position = 0, num_bad_chars = 0; int num_digits = 4; char ch; - uint8_t num, num_prev; - uint8_t *buffer = NULL; - int64_t prod = 1, max_prod = 0; + unsigned char num, num_prev; + unsigned char *buffer = NULL; + long long int prod = 1, max_prod = 0; /* if second command-line argument is given, * use it as the number of digits to compute @@ -20,7 +19,7 @@ int main(int argc, char *argv[]) num_digits = atoi(argv[1]); /* allocate memory to store past values */ - buffer = calloc(num_digits, sizeof(uint8_t)); + buffer = calloc(num_digits, sizeof(unsigned char)); if (!buffer) { perror("Unable to allocate memory for buffer"); diff --git a/project_euler/Problem 14/sol1.c b/project_euler/Problem 14/sol1.c index e8af5ad6..aabbd60d 100644 --- a/project_euler/Problem 14/sol1.c +++ b/project_euler/Problem 14/sol1.c @@ -2,27 +2,24 @@ #include #ifdef _OPENMP - #include - #pragma message ("Using OpenMP parallelization") -#else - #pragma message ("Not using OpenMP parallelization") +#include #endif /** - * Computes the length of collatz sequence for a given - * starting number + * Computes the length of collatz sequence for a given + * starting number **/ long long collatz(long long start_num) { long long length = 1; - - while (start_num != 1) /* loop till we reach 1 */ + + while (start_num != 1) /* loop till we reach 1 */ { - if(start_num & 0x01) /* check for odd */ + if (start_num & 0x01) /* check for odd */ start_num = 3 * start_num + 1; else - start_num >>= 1; /* simpler divide by 2 */ - length ++; + start_num >>= 1; /* simpler divide by 2 */ + length++; } return length; @@ -33,39 +30,39 @@ int main(int argc, char **argv) long long max_len = 0, max_len_num = 0; long long MAX_NUM = 1000000; - if (argc == 2) /* set commandline argumnet as the maximum iteration number */ + if (argc == 2) /* set commandline argumnet as the maximum iteration number */ { MAX_NUM = atoll(argv[1]); printf("Maximum number: %lld\n", MAX_NUM); } - /** - * Since the computational values for each iteration step are independent, - * we can compute them in parallel. However, the maximum values should be +/** + * Since the computational values for each iteration step are independent, + * we can compute them in parallel. However, the maximum values should be * updated in synchrony so that we do not get into a "race condition". - * + * * To compile with supporintg gcc or clang, the flag "-fopenmp" should be passes * while with Microsoft C compiler, the flag "/fopenmp" should be used. - * + * * Automatically detects for OPENMP using the _OPENMP macro. **/ - #ifdef _OPENMP - #pragma omp parallel for shared(max_len, max_len_num) schedule(guided) - #endif +#ifdef _OPENMP +#pragma omp parallel for shared(max_len, max_len_num) schedule(guided) +#endif for (long long i = 1; i < MAX_NUM; i++) { long long L = collatz(i); if (L > max_len) { - max_len = L; /* length of sequence */ - max_len_num = i; /* starting number */ + max_len = L; /* length of sequence */ + max_len_num = i; /* starting number */ } - #if defined(_OPENMP) && defined(DEBUG) +#if defined(_OPENMP) && defined(DEBUG) printf("Thread: %2d\t %3lld: \t%5lld\n", omp_get_thread_num(), i, L); - #elif defined(DEBUG) +#elif defined(DEBUG) printf("%3lld: \t%5lld\n", i, L); - #endif +#endif } printf("Start: %3lld: \tLength: %5lld\n", max_len_num, max_len); diff --git a/project_euler/Problem 25/sol1.c b/project_euler/Problem 25/sol1.c index 7d189e53..75682022 100644 --- a/project_euler/Problem 25/sol1.c +++ b/project_euler/Problem 25/sol1.c @@ -1,5 +1,6 @@ #include #include +#include #include #include diff --git a/project_euler/Problem 26/sol1.c b/project_euler/Problem 26/sol1.c new file mode 100644 index 00000000..bb9d9da8 --- /dev/null +++ b/project_euler/Problem 26/sol1.c @@ -0,0 +1,74 @@ +#include +#include +#include +#include +#ifdef _OPENMP +#include +#endif + +#define MAX_DENO 2000 +#define MAX_LEN (MAX_DENO + 10) + +int compare(const void *a, const void *b) +{ + return (*(unsigned short *)a - *(unsigned short *)b); +} + +int main(int argc, char *argv[]) +{ + unsigned short max_digits = 0, max_idx_number = 0; + + clock_t start_time = clock(); +#ifdef _OPENMP +#pragma omp for +#endif + for (unsigned short deno = 2; deno < MAX_DENO; deno++) + { + unsigned short remainders[MAX_LEN]; + unsigned short rem = 1, *rem_ptr = remainders; + memset(remainders, (unsigned short)-1, MAX_LEN * sizeof(unsigned short)); + // remainders[0] = 1; + // printf("1/%-4u\t ", deno); + unsigned short index = 0, num_digits; + + while (rem != 0) + { + rem = (rem * 10) % deno; + if (rem == 0) + { + index = 0; + break; + } + rem_ptr = (unsigned short *)bsearch(&rem, remainders, MAX_LEN, sizeof(unsigned short), compare); + // printf("%2d, ", rem); + // printf("(%14p), ", rem_ptr); + if (rem_ptr != NULL) + break; + remainders[index] = rem; + rem_ptr = remainders; + index++; + } + + num_digits = index - (rem_ptr - remainders); + // printf("\n\t(%14p, %14p, %4u, %4u)\n", rem_ptr, remainders, index, num_digits); +#ifdef _OPENMP +#pragma omp critical + { +#endif + if (num_digits > max_digits) + { + max_digits = num_digits; + max_idx_number = deno; + // printf("\t (%u, %u)\n ", max_digits, max_idx_number); + } +#ifdef _OPENMP + } +#endif + } + clock_t end_time = clock(); + + printf("Time taken: %.4g ms\n", 1e3 * (double)(end_time - start_time) / CLOCKS_PER_SEC); + printf("Maximum digits: %hu\t Denominator: %hu\n", max_digits, max_idx_number); + + return 0; +} diff --git a/searching/CMakeLists.txt b/searching/CMakeLists.txt new file mode 100644 index 00000000..9ff68ec4 --- /dev/null +++ b/searching/CMakeLists.txt @@ -0,0 +1,23 @@ +if(USE_OPENMP) + find_package(OpenMP) +endif() + +# If necessary, use the RELATIVE flag, otherwise each source file may be listed +# with full pathname. RELATIVE may makes it easier to extract an executable name +# automatically. +file( GLOB APP_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.c ) +# file( GLOB APP_SOURCES ${CMAKE_SOURCE_DIR}/*.c ) +# AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR} APP_SOURCES) +foreach( testsourcefile ${APP_SOURCES} ) + # I used a simple string replace, to cut off .cpp. + string( REPLACE ".c" "" testname ${testsourcefile} ) + add_executable( ${testname} ${testsourcefile} ) + # Make sure YourLib is linked to each app + target_link_libraries( ${testname} function_timer ) + set_target_properties(${testname} PROPERTIES LINKER_LANGUAGE C) + if(OpenMP_C_FOUND) + target_link_libraries(${testname} OpenMP::OpenMP_C) + endif() + install(TARGETS ${testname} DESTINATION "bin/searching") + +endforeach( testsourcefile ${APP_SOURCES} ) diff --git a/searching/Linear_Search.c b/searching/Linear_Search.c index e507bb0c..5c85d697 100644 --- a/searching/Linear_Search.c +++ b/searching/Linear_Search.c @@ -1,27 +1,32 @@ #include -int linearsearch(int *arr, int size, int val){ +int linearsearch(int *arr, int size, int val) +{ int i; - for (i = 0; i < size; i++){ + for (i = 0; i < size; i++) + { if (arr[i] == val) return 1; } return 0; } -void main(){ - int n,i,v; +int main() +{ + int n, i, v; printf("Enter the size of the array:\n"); - scanf("%d",&n); //Taking input for the size of Array + scanf("%d", &n); //Taking input for the size of Array int a[n]; printf("Enter the contents for an array of size %d:\n", n); - for (i = 0; i < n; i++) scanf("%d", &a[i]);// accepts the values of array elements until the loop terminates// + for (i = 0; i < n; i++) + scanf("%d", &a[i]); // accepts the values of array elements until the loop terminates// printf("Enter the value to be searched:\n"); scanf("%d", &v); //Taking input the value to be searched - if (linearsearch(a,n,v)) + if (linearsearch(a, n, v)) printf("Value %d is in the array.\n", v); else printf("Value %d is not in the array.\n", v); + return 0; } diff --git a/searching/Other_Binary_Search.c b/searching/Other_Binary_Search.c index 3337ce19..85a65099 100644 --- a/searching/Other_Binary_Search.c +++ b/searching/Other_Binary_Search.c @@ -2,7 +2,6 @@ #include #define len 5 - int binarySearch(int array[], int leng, int searchX) { int pos = -1, right, left, i = 0; @@ -10,14 +9,14 @@ int binarySearch(int array[], int leng, int searchX) left = 0; right = leng - 1; - while(left <= right) + while (left <= right) { pos = left + (right - left) / 2; - if(array[pos] == searchX) + if (array[pos] == searchX) { return pos; } - else if(array[pos] > searchX) + else if (array[pos] > searchX) { right = pos - 1; } @@ -29,10 +28,9 @@ int binarySearch(int array[], int leng, int searchX) return -1; /* not found */ } - -void main(int argc, char *argv[]) +int main(int argc, char *argv[]) { - int array[len] = { 5, 8 , 10 , 14 ,16 }; + int array[len] = {5, 8, 10, 14, 16}; int position; position = binarySearch(array, len, 5); @@ -44,5 +42,5 @@ void main(int argc, char *argv[]) printf("The number %d exist in array at position : %d \n", 5, position); } - + return 0; } diff --git a/searching/pattern_search/CMakeLists.txt b/searching/pattern_search/CMakeLists.txt new file mode 100644 index 00000000..f23ecb5b --- /dev/null +++ b/searching/pattern_search/CMakeLists.txt @@ -0,0 +1,23 @@ +if(USE_OPENMP) + find_package(OpenMP) +endif() + +# If necessary, use the RELATIVE flag, otherwise each source file may be listed +# with full pathname. RELATIVE may makes it easier to extract an executable name +# automatically. +file( GLOB APP_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.c ) +# file( GLOB APP_SOURCES ${CMAKE_SOURCE_DIR}/*.c ) +# AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR} APP_SOURCES) +foreach( testsourcefile ${APP_SOURCES} ) + # I used a simple string replace, to cut off .cpp. + string( REPLACE ".c" "" testname ${testsourcefile} ) + add_executable( ${testname} ${testsourcefile} ) + # Make sure YourLib is linked to each app + target_link_libraries( ${testname} function_timer ) + set_target_properties(${testname} PROPERTIES LINKER_LANGUAGE C) + if(OpenMP_C_FOUND) + target_link_libraries(${testname} OpenMP::OpenMP_C) + endif() + install(TARGETS ${testname} DESTINATION "bin/searching/pattern") + +endforeach( testsourcefile ${APP_SOURCES} ) diff --git a/searching/pattern_search/Makefile b/searching/pattern_search/Makefile deleted file mode 100644 index b8c8aeb1..00000000 --- a/searching/pattern_search/Makefile +++ /dev/null @@ -1,14 +0,0 @@ -CC = gcc -FLAG = -o - -all: naive_search rabin_karp_search boyer_moore_search - -naive_search : naive_search.c - $(CC) $(FLAG) naive_search naive_search.c -rabin_karp_search : rabin_karp_search - $(CC) $(FLAG) rabin_karp_search rabin_karp_search.c -boyer_moore_search: boyer_moore_search boyer_moore_search.c - $(CC) $(FLAG) boyer_moore_search boyer_moore_search.c - -clean: - rm naive_search rabin_karp_search boyer_moore_search diff --git a/sorting/Bubble_Sort_2.c b/sorting/Bubble_Sort_2.c index f11fd63e..c141ba91 100644 --- a/sorting/Bubble_Sort_2.c +++ b/sorting/Bubble_Sort_2.c @@ -1,56 +1,47 @@ #include #include -#define MAX 20 +#define MAX 20 #define TRUE 1 #define FALSE 0 - int main() { - int i , arraySort[MAX] ={0} , isSort = FALSE, changePlace; - - - /* For example + int i, arraySort[MAX] = {0}, isSort = FALSE, changePlace; + + /* For example Insertion random values in array to test */ - - - for(i = 0 ; i < MAX; i++) + + for (i = 0; i < MAX; i++) { - arraySort[i] = rand()%101 ; + arraySort[i] = rand() % 101; } - -/* Algorithm of bubble methods */ - - while(isSort) + /* Algorithm of bubble methods */ + + while (isSort) { - isSort = FALSE; + isSort = FALSE; - for( i = 0 ; i < MAX - 1 ; i++) - { - if(arraySort[i] > arraySort[i+1]) - { - changePlace = arratSort[i]; - arraySort[i] = arraySort[i+1]; - arraySort[i+1] = changePlace ; - isSort = TRUE; - } - - } + for (i = 0; i < MAX - 1; i++) + { + if (arraySort[i] > arraySort[i + 1]) + { + changePlace = arraySort[i]; + arraySort[i] = arraySort[i + 1]; + arraySort[i + 1] = changePlace; + isSort = TRUE; + } + } } /* See if it works */ - - for(i = 0 ; i < MAX; i++) + + for (i = 0; i < MAX; i++) { - printf("%d\n", arraySort[i]); + printf("%d\n", arraySort[i]); } - - - return EXIT_SUCCESS; - } diff --git a/sorting/CMakeLists.txt b/sorting/CMakeLists.txt new file mode 100644 index 00000000..7033d577 --- /dev/null +++ b/sorting/CMakeLists.txt @@ -0,0 +1,23 @@ +if(USE_OPENMP) + find_package(OpenMP) +endif() + +# If necessary, use the RELATIVE flag, otherwise each source file may be listed +# with full pathname. RELATIVE may makes it easier to extract an executable name +# automatically. +file( GLOB APP_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.c ) +# file( GLOB APP_SOURCES ${CMAKE_SOURCE_DIR}/*.c ) +# AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR} APP_SOURCES) +foreach( testsourcefile ${APP_SOURCES} ) + # I used a simple string replace, to cut off .cpp. + string( REPLACE ".c" "" testname ${testsourcefile} ) + add_executable( ${testname} ${testsourcefile} ) + # Make sure YourLib is linked to each app + target_link_libraries( ${testname} function_timer ) + set_target_properties(${testname} PROPERTIES LINKER_LANGUAGE C) + if(OpenMP_C_FOUND) + target_link_libraries(${testname} OpenMP::OpenMP_C) + endif() + install(TARGETS ${testname} DESTINATION "bin/sorting") + +endforeach( testsourcefile ${APP_SOURCES} ) diff --git a/sorting/Pancake_Sort.c b/sorting/Pancake_Sort.c index 4869d3b5..96271704 100644 --- a/sorting/Pancake_Sort.c +++ b/sorting/Pancake_Sort.c @@ -24,13 +24,13 @@ int findMax(int arr[], int n) for (maxElementIdx = 0, i = 0; i < n; ++i) if (arr[i] > arr[maxElementIdx]) - maxElementIdx = i; + maxElementIdx = i; return maxElementIdx; } // Sorts the array using flip operations -int pancakeSort(int *arr, int n) +void pancakeSort(int *arr, int n) { // Start from the complete array and one by one reduce current size by one for (int curr_size = n; curr_size > 1; --curr_size) @@ -39,13 +39,13 @@ int pancakeSort(int *arr, int n) int maxElementIdx = findMax(arr, curr_size); // Move the maximum element to end of current array if it's not already at the end - if (maxElementIdx != curr_size-1) - { + if (maxElementIdx != curr_size - 1) + { // To move at the end, first move maximum number to beginning - flip(arr, maxElementIdx); + flip(arr, maxElementIdx); // Now move the maximum number to end by reversing current array - flip(arr, curr_size-1); + flip(arr, curr_size - 1); } } } @@ -53,26 +53,29 @@ int pancakeSort(int *arr, int n) // Displays the array, passed to this method void display(int arr[], int n) { - for(int i = 0; i < n; i++) + for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); -} +} + +#define N 50 // Driver program to test above function int main() -{ - int arr[] = {23, 10, 20, 11, 12, 6, 7}; - int n = sizeof(arr)/sizeof(arr[0]); +{ + int arr[N]; + for (int i = 0; i < N; i++) + arr[i] = rand() % (N << 1); /* random numbers from 0 to 2N */ printf("Original array: "); - display(arr, n); + display(arr, N); - pancakeSort(arr, n); + pancakeSort(arr, N); printf("Sorted array: "); - display(arr, n); + display(arr, N); return 0; -} \ No newline at end of file +} \ No newline at end of file diff --git a/sorting/Stooge_Sort.c b/sorting/Stooge_Sort.c index 8b265adb..f7ef862f 100644 --- a/sorting/Stooge_Sort.c +++ b/sorting/Stooge_Sort.c @@ -1,24 +1,24 @@ #include -void stoogesort(int [], int, int); - -void main() +void stoogesort(int[], int, int); + +int main() { int arr[100], i, n; - + printf("How many elements do you want to sort: "); scanf("%d", &n); - for (i = 0;i < n; i++) + for (i = 0; i < n; i++) scanf(" %d", &arr[i]); stoogesort(arr, 0, n - 1); printf("Sorted array : \n"); - for (i = 0;i < n;i++) + for (i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); + return 0; } - - + void stoogesort(int arr[], int i, int j) { int temp, k; diff --git a/sorting/merge_sort.c b/sorting/merge_sort.c index 6533713f..ea2bfba3 100644 --- a/sorting/merge_sort.c +++ b/sorting/merge_sort.c @@ -1,91 +1,92 @@ #include +#include -void swap (int *a,int *b)//To swap the variables// +void swap(int *a, int *b) //To swap the variables// { int t; - t= *a; - *a=*b; - *b=t; - + t = *a; + *a = *b; + *b = t; } -void merge(int a[],int l,int r,int n)//To merge // -{ int *b = (int*)malloc(n*sizeof(int)); -int c=l; - int p1,p2; - p1 = l;p2=((l+r)/2)+1; - while ((p1<((l+r)/2)+1) &&(p2 a[r]) + swap(&a[l], &a[r]); + } + else if (l == r) { - if (a[l]>a[r]) - swap(&a[l],&a[r]); - } - else if(l==r) - {} else - {mergesort(a,n,l,(l+r)/2); - mergesort(a,n,((l+r)/2)+1,r); - merge(a,l,r,n); - + { + merge_sort(a, n, l, (l + r) / 2); + merge_sort(a, n, ((l + r) / 2) + 1, r); + merge(a, l, r, n); } - } -int main(void) { //main function// -int *a,n,i; -scanf("%d",&n); -a = (int*)malloc(n*sizeof(int)); -for (i=0;isplitchar) == 0) { @@ -390,7 +390,6 @@ void nearsearch(Tptr p, char *s, int d) nearsearch(p->hikid, s, d); } - #define NUMBER_OF_STRING 3 int main(int argc, char *argv[]) diff --git a/sorting/radix_sort_2.c b/sorting/radix_sort_2.c index 6f0aa062..27428276 100644 --- a/sorting/radix_sort_2.c +++ b/sorting/radix_sort_2.c @@ -1,42 +1,44 @@ //sorting of array list using Radix sort #include -#define range 10 // Range for integers is 10 as digits range from 0-9 +#define range 10 // Range for integers is 10 as digits range from 0-9 // Utility function to get the maximum value in ar[] -int MAX(int ar[], int size){ - int i, max = ar[0]; - for(i = 0; imax) - max = ar[i]; - } - return max; +int MAX(int ar[], int size) +{ + int i, max = ar[0]; + for (i = 0; i < size; i++) + { + if (ar[i] > max) + max = ar[i]; + } + return max; } // Counting sort according to the digit represented by place -void countSort(int arr[],int n,int place) +void countSort(int arr[], int n, int place) { - int i,freq[range]={0}; + int i, freq[range] = {0}; int output[n]; - + // Store count of occurences in freq[] - for(i=0;i=0;i--) + for (i = n - 1; i >= 0; i--) { - output[freq[(arr[i]/place)%range]-1]=arr[i]; - freq[(arr[i]/place)%range]--; + output[freq[(arr[i] / place) % range] - 1] = arr[i]; + freq[(arr[i] / place) % range]--; } - + // Copy the output array to arr[], so it contains numbers according to the current digit - for(i=0;i -#include -#include - -#define ELEMENT_NR 20000 -#define ARRAY_LEN(x) (sizeof(x) / sizeof((x)[0])) -const char *notation = "Shell Sort Big O Notation:\ - \n--> Best Case: O(n log(n)) \ - \n--> Average Case: depends on gap sequence \ - \n--> Worst Case: O(n)"; - -void show_data(int arr[], int len) -{ - int i; - - for (i = 0; i < len; i++) - printf("%3d ", arr[i]); - printf("\n"); -} - -void swap(int *a, int *b) -{ - int tmp; - - tmp = *a; - *a = *b; - *b = tmp; -} - -void shellSort(int array[], int len) -{ - int i, j, gap; - - for (gap = len / 2; gap > 0; gap = gap / 2) - for (i = gap; i < len; i++) - for (j = i - gap; j >= 0 && array[j] > array[j + gap]; j = j - gap) - swap(&array[j], &array[j + gap]); -} - -/** - * Optimized algorithm - takes half the time as other - **/ -void shell_sort2(int array[], int LEN) -{ - const int gaps[] = {701, 301, 132, 57, 23, 10, 4, 1}; - const int gap_len = 8; - int i, j, g; - - for (g = 0; g < gap_len; g++) - { - int gap = gaps[g]; - for (i = gap; i < LEN; i++) - { - int tmp = array[i]; - - for (j = i; j >= gap && (array[j - gap] - tmp) > 0; j -= gap) - array[j] = array[j - gap]; - array[j] = tmp; - } - } -#ifdef DEBUG - for (i = 0; i < LEN; i++) - printf("%s\t", data[i]); -#endif -} - -int main(int argc, char *argv[]) -{ - int i; - int array[ELEMENT_NR]; - int array2[ELEMENT_NR]; - int range = 500; - int size; - clock_t start, end; - double time_spent; - - srand(time(NULL)); - for (i = 0; i < ELEMENT_NR; i++) - { - array[i] = rand() % range + 1; - array2[i] = array[i]; - } - - size = ARRAY_LEN(array); - - show_data(array, size); - start = clock(); - shellSort(array, size); - end = clock(); - time_spent = (double)(end - start) / CLOCKS_PER_SEC; - - printf("Data Sorted\n"); - show_data(array, size); - - printf("%s\n", notation); - printf("Time spent sorting: %.4g ms\n", time_spent * 1e3); - - printf("--------------------------\n"); - start = clock(); - shell_sort2(array2, size); - end = clock(); - time_spent = (double)(end - start) / CLOCKS_PER_SEC; - - printf("Data Sorted\n"); - show_data(array2, size); - - printf("%s\n", notation); - printf("Time spent sorting: %.4g ms\n", time_spent * 1e3); - - return 0; -} +#include +#include +#include + +#define ELEMENT_NR 20000 +#define ARRAY_LEN(x) (sizeof(x) / sizeof((x)[0])) +const char *notation = "Shell Sort Big O Notation:\ + \n--> Best Case: O(n log(n)) \ + \n--> Average Case: depends on gap sequence \ + \n--> Worst Case: O(n)"; + +void show_data(int arr[], int len) +{ + int i; + + for (i = 0; i < len; i++) + printf("%3d ", arr[i]); + printf("\n"); +} + +void swap(int *a, int *b) +{ + int tmp; + + tmp = *a; + *a = *b; + *b = tmp; +} + +void shellSort(int array[], int len) +{ + int i, j, gap; + + for (gap = len / 2; gap > 0; gap = gap / 2) + for (i = gap; i < len; i++) + for (j = i - gap; j >= 0 && array[j] > array[j + gap]; j = j - gap) + swap(&array[j], &array[j + gap]); +} + +int main(int argc, char *argv[]) +{ + int i; + int array[ELEMENT_NR]; + int range = 500; + int size; + clock_t start, end; + double time_spent; + + srand(time(NULL)); + for (i = 0; i < ELEMENT_NR; i++) + array[i] = rand() % range + 1; + + size = ARRAY_LEN(array); + + show_data(array, size); + start = clock(); + shellSort(array, size); + end = clock(); + time_spent = (double)(end - start) / CLOCKS_PER_SEC; + + printf("Data Sorted\n"); + show_data(array, size); + + printf("%s\n", notation); + printf("Time spent sorting: %.4g ms\n", time_spent * 1e3); + + return 0; +} diff --git a/sorting/shell_Sort2.c b/sorting/shell_Sort2.c new file mode 100644 index 00000000..3aeab0d9 --- /dev/null +++ b/sorting/shell_Sort2.c @@ -0,0 +1,81 @@ +#include +#include +#include +#include "function_timer.h" + +#define ELEMENT_NR 20000 +#define ARRAY_LEN(x) (sizeof(x) / sizeof((x)[0])) + +void show_data(int arr[], int len) +{ + int i; + + for (i = 0; i < len; i++) + printf("%3d ", arr[i]); + printf("\n"); +} + +void swap(int *a, int *b) +{ + int tmp; + + tmp = *a; + *a = *b; + *b = tmp; +} + +/** + * Optimized algorithm - takes half the time as other + **/ +void shell_sort(int array[], int LEN) +{ + const int gaps[] = {701, 301, 132, 57, 23, 10, 4, 1}; + const int gap_len = 8; + int i, j, g; + + for (g = 0; g < gap_len; g++) + { + int gap = gaps[g]; + for (i = gap; i < LEN; i++) + { + int tmp = array[i]; + + for (j = i; j >= gap && (array[j - gap] - tmp) > 0; j -= gap) + array[j] = array[j - gap]; + array[j] = tmp; + } + } +#ifdef DEBUG + for (i = 0; i < LEN; i++) + printf("%s\t", data[i]); +#endif +} + +int main(int argc, char *argv[]) +{ + int i; + int array[ELEMENT_NR]; + int range = 500; + int size; + double time_spent; + + srand(time(NULL)); + for (i = 0; i < ELEMENT_NR; i++) + array[i] = rand() % range + 1; + + size = ARRAY_LEN(array); + + function_timer *timer = new_timer(); + + show_data(array, size); + start_timer(timer); + shell_sort(array, size); + time_spent = end_timer(timer); + + printf("Data Sorted\n"); + show_data(array, size); + + printf("Time spent sorting: %.4g s\n", time_spent); + + return 0; +}