diff --git a/作業/C語言考前掙扎.pdf b/作業/C語言考前掙扎.pdf new file mode 100644 index 0000000..efd4f4f Binary files /dev/null and b/作業/C語言考前掙扎.pdf differ diff --git a/作業/exam/exam.zip b/作業/exam/exam.zip new file mode 100644 index 0000000..d4de816 Binary files /dev/null and b/作業/exam/exam.zip differ diff --git a/作業/exam/exam/exam_1.cpp b/作業/exam/exam/exam_1.cpp new file mode 100644 index 0000000..eee5fcb --- /dev/null +++ b/作業/exam/exam/exam_1.cpp @@ -0,0 +1,264 @@ +#include +#include +#include +#include +#include + +typedef struct node { + int coef; + int exp; + int root; + struct node* rlink; + struct node* llink; +} node; +node *head, *tail, *current, *prev, *temp ,*head_root , *current_root , *tail_root; + +void init_f() { + head = (node *)malloc(sizeof(node)); + tail = (node *)malloc(sizeof(node)); + head->rlink = tail; + tail->llink = head; + + head_root = (node *)malloc(sizeof(node)); + tail_root = (node *)malloc(sizeof(node)); + + head_root->rlink = tail_root; + tail_root->llink = head_root; +} + +void read_poly(char str[] ){ + int argCount ; + while (1) { + + node* newNode = (node*)malloc(sizeof(node)); + + argCount = sscanf(str, "%dx^%d%s", &newNode->coef, &newNode->exp, str); + + if (argCount >= 2) { // \ŪYƩM + + newNode->llink = tail->llink; + newNode->rlink = tail; + tail->llink->rlink = newNode; + tail->llink = newNode; + + if (argCount == 2) { + break ; + } + + } else { + if(!isdigit(newNode->coef)){ + newNode->exp = 0; + + newNode->llink = tail->llink; + newNode->rlink = tail; + tail->llink->rlink = newNode; + tail->llink = newNode; + + break ; + + }else{ +// printf("newNode->coef = %d\n",newNode->coef); +// printf("isdigit(newNode->coef) = %d",isdigit(newNode->coef)); + + free(newNode); + break ; + } + + } + } +} + +void compact(char str[]){ /* strťաAܱo */ + int i, j; + + for (i = j = 0; str[i]; i++, j++) { + for (; str[i]==' '; i++); + str[j] = str[i]; + } + str[j] = '\0'; + printf("\nťի᪺rG%s",str); +} + +void clear_node(){ + // O + current = head->rlink; + while (current != tail) { + temp = current; + current = current->rlink; + free(temp); + } + current_root = head_root->rlink; + while (current_root != tail_root) { + temp = current_root; + current_root = current_root->rlink; + free(temp); + } + free(head); + free(tail); + free(head_root); + free(tail_root); +} + + +void show( int n, int mode){ + int i; + if(mode == 0){ + printf("\n{p(x)= "); + current = head->rlink; + + while (current != tail) { + if(abs(current->coef)>1){ + printf("%s%d", current->coef > 1? "":"\b",current->coef); + }else if(current->coef == -1){ + printf("%s", current->exp == 0? "\b-1":"\b-"); + } + switch(current->exp){ + case 0: + if(current->coef == 1 ) printf("1+"); + else printf("+"); + break; + case 1: + printf("x+"); + break; + default: + printf("x^%d+",current->exp); + } + current = current->rlink; + } + printf("\b "); + + }else { /* mode==1Aܩұo */ + + current_root = head_root->rlink; + + while(current_root != tail_root){ + printf("%d ",current_root->root); + current_root = current_root->rlink; + } + + } + +} + +int findRoot() /* ڡAұoѦsJq[]A^ǮڪӼ */ +{ + + current_root = head_root->rlink; + + int r, c = 0, i, j, k, sum; + int sign[2] = {1,-1}; + + current = tail->llink; + r = abs(current->coef); /* X̧CY */ + + if (current->exp != 0) { /* ̧C >= 1Ah0i */ + if ((i = current->exp) > 0) { + node* newNode = (node*)malloc(sizeof(node)); + + newNode->root = 0; /* ̧CƳ]i */ + + newNode->llink = tail_root->llink; + newNode->rlink = tail_root; + tail_root->llink->rlink = newNode; + tail_root->llink = newNode; + c = 1; + } + current = head->rlink; + while(current!=tail){ + current->exp -= i; /* Ҧƴhi */ + current = current->rlink; + } + } + + +// r = abs(p[2*p[0]]); /* X̧CY */ + + for (i = 1; i <= r; i++) { /* Ҽ{㰣r]iA`Nt */ + if (r%i != 0) continue; /* 㰣riNLA~Ҽ{U@i */ + + for (j = 0; j < 2; j++) { /* j0ANҼ{+iҡFj1ANҼ{-ip */ + for (sum = 0, current = head->rlink ; current!= tail ; current = current->rlink) /* pC@G(Y*x^)ò֥[sum */ + sum += current->coef *(int)(pow(sign[j]*i,current->exp)); + if (sum == 0) { + node* newNode = (node*)malloc(sizeof(node)); + newNode->root = sign[j]*i; /* bingo! o{XG󪺾ƮڡANgJq}C */ + + newNode->llink = tail_root->llink; + newNode->rlink = tail_root; + tail_root->llink->rlink = newNode; + tail_root->llink = newNode; + c = 1; + } + } + } + + return c; +} + +void sort(){ + + //YSƩΥu@ + if (head->rlink == tail || head->rlink->rlink == tail) { + return; + } + + int flag = 1; + while(flag){ + flag = 0; + current = head->rlink; + + while(current->rlink != tail){ + temp = current->rlink; + + if(current->exp < temp->exp ){ + temp->llink = current->llink; + current->rlink = temp->rlink; + + temp->rlink->llink = current; + temp->rlink = current; + + current->llink->rlink = temp; + current->llink = temp; + + flag = 1; + } + else{ + current = current->rlink; + } + } + } +} + +int main() { + char str[100]; + int poly_num ,c , high; + init_f(); + + printf("\n*** ѦhƮ ***\n\nJh ==> "); + + if (fgets(str, sizeof(str), stdin) == NULL) { + printf("J~I\n"); + return 1; + } + compact(str); + read_poly(str); + sort(); + + current = head->rlink; + high= current->exp; + + show(c,0); + c = findRoot(); + + if (c > 0) { + printf("\n\nѱoƮڬG"); + show(c,1); + } + else + printf("\n\nƮڤsb\n"); + clear_node(); + return 0; +} + + + diff --git a/作業/exam/exam/exam_2.cpp b/作業/exam/exam/exam_2.cpp new file mode 100644 index 0000000..8974824 --- /dev/null +++ b/作業/exam/exam/exam_2.cpp @@ -0,0 +1,290 @@ +#include +#include +#include +#include +#include +#define MAX 100 + +// === ܼƫŧi === +char input[MAX]; +char postfix[MAX]; +char postfix_1[MAX]; //ܥ +char stack[MAX]; +double numStack[MAX]; +int top = -1; +int numTop = -1; + +// === 禡ŧi === +int get_priority(char op); +int is_operator(char c); +double calculate(double a, double b, char op); +void convert_to_postfix(); +double evaluate_postfix(); +double evaluate_infix(char *expr); +double parse_number(char **expr); + +int get_priority(char c){ + if(c=='+' || c=='-'){ + return 1; + }else if(c=='*' || c=='/' || c=='%' ){ + return 2; + }else if(c=='^' || c=='s' || c=='c' ){ + return 3; + }else{ + return 0; + } +} + +// === ˬdrO_Bl === +int is_operator(char c) { + return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^' || c == '%' ||c == 's' || c == 'c'); +} + +// === B === +double calculate(double a, double b, char op) { + switch(op) { + case '+': return a + b; + case '-': return a - b; + case '*': return a * b; + case '/': + if(b != 0) return a / b; + printf("~GƤରsI\n"); + exit(1); + case '^': return pow(a, b); + case '%': return (int)a % (int)b; + + case 's': return sin(b); + case 'c': return cos(b); + default: return 0; + } +} + +//ܥ +void convert_to_postfix_forprint() { + int i = 0, j; + int postfix_index = 0; + top = -1; + char number_str[MAX]; + int is_negative; + + while(input[i] != '\0') { + if(isdigit(input[i]) || input[i] == '.' || (input[i] == '-' && (i == 0 || input[i-1] == '(' || is_operator(input[i-1])))) { + // BzƦr]]Atơ^ + is_negative = 0; + int num_len = 0; + + // ˬdO_t + if(input[i] == '-') { + is_negative = 1; + i++; + } + + // Ʀrr + while(input[i] != '\0' && (isdigit(input[i]) || input[i] == '.')) { + number_str[num_len++] = input[i++]; + } + number_str[num_len] = '\0'; + i--; // ^h@ӦmA]~h while |A[@ + + // XƦr + printf("%s ", number_str); + if(is_negative) { + printf("- "); + } + + // NƦr[JǪF + for(j = 0; j < num_len; j++) { + postfix_1[postfix_index++] = number_str[j]; + } + postfix_1[postfix_index++] = ' '; + if(is_negative) { + postfix_1[postfix_index++] = '-'; + postfix_1[postfix_index++] = ' '; + } + } + else if(input[i] == '(') { + stack[++top] = input[i]; + } + else if(input[i] == ')') { + while(top >= 0 && stack[top] != '(') { + printf("%c ", stack[top]); + postfix_1[postfix_index++] = stack[top]; + postfix_1[postfix_index++] = ' '; + top--; + } + if(top >= 0) top--; + } + else if(is_operator(input[i])) { + // pGOBztƪ + if(input[i-1] != 'o'){ + if(!(input[i] == '-' && (i == 0 || input[i-1] == '(' || is_operator(input[i-1])))) { + while(top >= 0 && stack[top] != '(' && + (get_priority(stack[top]) > get_priority(input[i]) || + (get_priority(stack[top]) == get_priority(input[i]) && input[i] != '^'))) { + printf("%c ", stack[top]); + postfix_1[postfix_index++] = stack[top]; + postfix_1[postfix_index++] = ' '; + top--; + } + stack[++top] = input[i]; + } + } + + } + i++; + } + + while(top >= 0) { + printf("%c ", stack[top]); + postfix_1[postfix_index++] = stack[top]; + postfix_1[postfix_index++] = ' '; + top--; + } + postfix_1[postfix_index] = '\0'; + printf("\n"); +} + +// === ഫǪF === +//p +void convert_to_postfix() { + int i = 0 , j; + int postfix_index = 0; + top = -1; + + while(input[i] != '\0') { + if(isdigit(input[i]) || input[i] == '.' || (input[i] == '-' && (i == 0 || input[i-1] == '(' || is_operator(input[i-1])))) { // ˬdO_ƦrBpIάOt]BOF}lAκbAιBū᭱^ + char *end; + double num = strtod(&input[i], &end); //strtod r괫BI + int len = end - &input[i]; //pƦrrꪺ ƦrݪO}Om +// printf("%.1f ", num); + for(j = 0; j < len; j++) { + postfix[postfix_index++] = input[i+j]; + } + postfix[postfix_index++] = ' '; + i += len - 1; + } + else if(input[i] == '(') { + stack[++top] = input[i]; + } + else if(input[i] == ')') { + while(top >= 0 && stack[top] != '(') { +// printf("%c ", stack[top]); + postfix[postfix_index++] = stack[top]; + postfix[postfix_index++] = ' '; + top--; + } + if(top >= 0) top--; + } + else if(is_operator(input[i])) { + + if(input[i-1]!='o'){ + while(top >= 0 && stack[top] != '(' && (get_priority(stack[top]) > get_priority(input[i]) || (get_priority(stack[top]) == get_priority(input[i]) && input[i] != '^'))) { +// printf("%c ", stack[top]); + postfix[postfix_index++] = stack[top]; + postfix[postfix_index++] = ' '; + top--; + } + stack[++top] = input[i]; + } + } + i++; + } + + while(top >= 0) { +// printf("%c ", stack[top]); + postfix[postfix_index++] = stack[top]; + postfix[postfix_index++] = ' '; + top--; + } + postfix[postfix_index] = '\0'; +// printf("\n"); +} + +// === pǪF === +double evaluate_postfix() { + int i; + numTop = -1; + char *token = strtok(postfix, " "); + +// printf("\npL{G\n"); + + while(token != NULL) { +// printf("BzаOG'%s'\n", token); + + if(isdigit(token[0]) || (token[0] == '-' && isdigit(token[1]))) { + double num = atof(token); + numStack[++numTop] = num; +// printf("JƦrG%.2f\n", num); + }else if(token[0] == 's'|| token[0] == 'c' ){ + if(numTop < 1) { +// printf("Bl '%c' ʤ֨B⤸\n", token[0]); + exit(1); + } + double b = numStack[numTop--]; + double result = calculate(0, b, token[0]); + numStack[++numTop] = result; +// printf("pG%c %.2f = %.4f\n", token[0], b, result); + + }else if(is_operator(token[0])) { + if(numTop < 1) { +// printf("Bl '%c' ʤ֨B⤸\n", token[0]); + exit(1); + } + double b = numStack[numTop--]; + double a = numStack[numTop--]; + double result = calculate(a, b, token[0]); + numStack[++numTop] = result; +// printf("pG%.2f %c %.2f = %.4f\n", a, token[0], b, result); + } + else { +// printf("~GаO '%s'\n", token); + exit(1); + } + +// printf("e|G"); + for(i = 0; i <= numTop; i++) { +// printf("%.2f ", numStack[i]); + } +// printf("\n\n"); + + token = strtok(NULL, " "); + } + + if(numTop != 0) { +// printf("~Gp⵲|Ѿl %d Ӥ\n", numTop + 1); + exit(1); + } + return numStack[numTop]; +} + +int main() { + + printf("пJǪܦ(䴩+-*/%^()B) => "); + + fgets(input, MAX, stdin); + input[strcspn(input, "\n")] = 0; + + printf("\nǪܪkG "); + convert_to_postfix_forprint(); //ܥ +// printf("\np⪺ǪܪkG "); + convert_to_postfix(); + double postfix_result = evaluate_postfix(); + printf("\nB⵲GG%.4f", postfix_result); + + printf("\t(TȬG"); + if(strcmp(input,"10+20*(50-30)/2^4-6*8")==0){ + printf("%g",10+20*(50-30)/pow(2,4)-6*8); + }else if(strcmp(input,"10+20*(-50+30)/-2^4-6*8")==0){ + printf("%g",10+20*(-50+30)/pow(-2,4)-6*8); + }else if(strcmp(input,"10.5+20.8*(50.1-30.6)/2.5^4-6.6*8.2")==0){ + printf("%g",10.5+20.8*(50.1-30.6)/pow(2.5,4)-6.6*8.2); + }else if(strcmp(input,"10.5+20.8*(-50.1+30.6)/2.5^-4-6.6*8.2")==0){ + printf("%g",10.5+20.8*(-50.1+30.6)/pow(2.5,-4)-6.6*8.2); + }else if(strcmp(input,"10-30*(-40-20)%2^4+7.5*-6")==0){ + printf("%g",10-30*(-40-20)%(int)pow(2,4)+7.5*-6); + }else if(strcmp(input,"1+sin((-50.2+sin(3.8*20)*cos(-30-100%40))*2^-2.5)*cos(123.456)")==0){ + printf("%g",1+sin((-50.2+sin(3.8*20)*cos(-30-100%40))*(int)pow(2,-2.5))*cos(123.456)); + }printf(")"); + + return 0; +} diff --git a/作業/exam/exam_1.cpp b/作業/exam/exam_1.cpp new file mode 100644 index 0000000..eee5fcb --- /dev/null +++ b/作業/exam/exam_1.cpp @@ -0,0 +1,264 @@ +#include +#include +#include +#include +#include + +typedef struct node { + int coef; + int exp; + int root; + struct node* rlink; + struct node* llink; +} node; +node *head, *tail, *current, *prev, *temp ,*head_root , *current_root , *tail_root; + +void init_f() { + head = (node *)malloc(sizeof(node)); + tail = (node *)malloc(sizeof(node)); + head->rlink = tail; + tail->llink = head; + + head_root = (node *)malloc(sizeof(node)); + tail_root = (node *)malloc(sizeof(node)); + + head_root->rlink = tail_root; + tail_root->llink = head_root; +} + +void read_poly(char str[] ){ + int argCount ; + while (1) { + + node* newNode = (node*)malloc(sizeof(node)); + + argCount = sscanf(str, "%dx^%d%s", &newNode->coef, &newNode->exp, str); + + if (argCount >= 2) { // \ŪYƩM + + newNode->llink = tail->llink; + newNode->rlink = tail; + tail->llink->rlink = newNode; + tail->llink = newNode; + + if (argCount == 2) { + break ; + } + + } else { + if(!isdigit(newNode->coef)){ + newNode->exp = 0; + + newNode->llink = tail->llink; + newNode->rlink = tail; + tail->llink->rlink = newNode; + tail->llink = newNode; + + break ; + + }else{ +// printf("newNode->coef = %d\n",newNode->coef); +// printf("isdigit(newNode->coef) = %d",isdigit(newNode->coef)); + + free(newNode); + break ; + } + + } + } +} + +void compact(char str[]){ /* strťաAܱo */ + int i, j; + + for (i = j = 0; str[i]; i++, j++) { + for (; str[i]==' '; i++); + str[j] = str[i]; + } + str[j] = '\0'; + printf("\nťի᪺rG%s",str); +} + +void clear_node(){ + // O + current = head->rlink; + while (current != tail) { + temp = current; + current = current->rlink; + free(temp); + } + current_root = head_root->rlink; + while (current_root != tail_root) { + temp = current_root; + current_root = current_root->rlink; + free(temp); + } + free(head); + free(tail); + free(head_root); + free(tail_root); +} + + +void show( int n, int mode){ + int i; + if(mode == 0){ + printf("\n{p(x)= "); + current = head->rlink; + + while (current != tail) { + if(abs(current->coef)>1){ + printf("%s%d", current->coef > 1? "":"\b",current->coef); + }else if(current->coef == -1){ + printf("%s", current->exp == 0? "\b-1":"\b-"); + } + switch(current->exp){ + case 0: + if(current->coef == 1 ) printf("1+"); + else printf("+"); + break; + case 1: + printf("x+"); + break; + default: + printf("x^%d+",current->exp); + } + current = current->rlink; + } + printf("\b "); + + }else { /* mode==1Aܩұo */ + + current_root = head_root->rlink; + + while(current_root != tail_root){ + printf("%d ",current_root->root); + current_root = current_root->rlink; + } + + } + +} + +int findRoot() /* ڡAұoѦsJq[]A^ǮڪӼ */ +{ + + current_root = head_root->rlink; + + int r, c = 0, i, j, k, sum; + int sign[2] = {1,-1}; + + current = tail->llink; + r = abs(current->coef); /* X̧CY */ + + if (current->exp != 0) { /* ̧C >= 1Ah0i */ + if ((i = current->exp) > 0) { + node* newNode = (node*)malloc(sizeof(node)); + + newNode->root = 0; /* ̧CƳ]i */ + + newNode->llink = tail_root->llink; + newNode->rlink = tail_root; + tail_root->llink->rlink = newNode; + tail_root->llink = newNode; + c = 1; + } + current = head->rlink; + while(current!=tail){ + current->exp -= i; /* Ҧƴhi */ + current = current->rlink; + } + } + + +// r = abs(p[2*p[0]]); /* X̧CY */ + + for (i = 1; i <= r; i++) { /* Ҽ{㰣r]iA`Nt */ + if (r%i != 0) continue; /* 㰣riNLA~Ҽ{U@i */ + + for (j = 0; j < 2; j++) { /* j0ANҼ{+iҡFj1ANҼ{-ip */ + for (sum = 0, current = head->rlink ; current!= tail ; current = current->rlink) /* pC@G(Y*x^)ò֥[sum */ + sum += current->coef *(int)(pow(sign[j]*i,current->exp)); + if (sum == 0) { + node* newNode = (node*)malloc(sizeof(node)); + newNode->root = sign[j]*i; /* bingo! o{XG󪺾ƮڡANgJq}C */ + + newNode->llink = tail_root->llink; + newNode->rlink = tail_root; + tail_root->llink->rlink = newNode; + tail_root->llink = newNode; + c = 1; + } + } + } + + return c; +} + +void sort(){ + + //YSƩΥu@ + if (head->rlink == tail || head->rlink->rlink == tail) { + return; + } + + int flag = 1; + while(flag){ + flag = 0; + current = head->rlink; + + while(current->rlink != tail){ + temp = current->rlink; + + if(current->exp < temp->exp ){ + temp->llink = current->llink; + current->rlink = temp->rlink; + + temp->rlink->llink = current; + temp->rlink = current; + + current->llink->rlink = temp; + current->llink = temp; + + flag = 1; + } + else{ + current = current->rlink; + } + } + } +} + +int main() { + char str[100]; + int poly_num ,c , high; + init_f(); + + printf("\n*** ѦhƮ ***\n\nJh ==> "); + + if (fgets(str, sizeof(str), stdin) == NULL) { + printf("J~I\n"); + return 1; + } + compact(str); + read_poly(str); + sort(); + + current = head->rlink; + high= current->exp; + + show(c,0); + c = findRoot(); + + if (c > 0) { + printf("\n\nѱoƮڬG"); + show(c,1); + } + else + printf("\n\nƮڤsb\n"); + clear_node(); + return 0; +} + + + diff --git a/作業/exam/exam_1.exe b/作業/exam/exam_1.exe new file mode 100644 index 0000000..82f69a6 Binary files /dev/null and b/作業/exam/exam_1.exe differ diff --git a/作業/exam/exam_2.cpp b/作業/exam/exam_2.cpp new file mode 100644 index 0000000..1ac49b0 --- /dev/null +++ b/作業/exam/exam_2.cpp @@ -0,0 +1,296 @@ +#include +#include +#include +#include +#include +#define MAX 100 + +// === ܼƫŧi === +char input[MAX]; +char postfix[MAX]; +char postfix_1[MAX]; //ܥ +char stack[MAX]; +double numStack[MAX]; +int top = -1; +int numTop = -1; + +// === 禡ŧi === +int get_priority(char op); +int is_operator(char c); +double calculate(double a, double b, char op); +void convert_to_postfix(); +double evaluate_postfix(); +double evaluate_infix(char *expr); +double parse_number(char **expr); + +int get_priority(char c){ + if(c=='+' || c=='-'){ + return 1; + }else if(c=='*' || c=='/' || c=='%' ){ + return 2; + }else if(c=='^' || c=='s' || c=='c' ){ + return 3; + }else{ + return 0; + } +} + +// === ˬdrO_Bl === +int is_operator(char c) { + return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^' || c == '%' ||c == 's' || c == 'c'); +} + +// === B === +double calculate(double a, double b, char op) { + switch(op) { + case '+': return a + b; + case '-': return a - b; + case '*': return a * b; + case '/': + if(b != 0) return a / b; + printf("~GƤରsI\n"); + exit(1); + case '^': return pow(a, b); + case '%': return (int)a % (int)b; + + case 's': return sin(b); + case 'c': return cos(b); + default: return 0; + } +} + +//ܥ +void convert_to_postfix_forprint() { + int i = 0, j; + int postfix_index = 0; + top = -1; + char number_str[MAX]; + int is_negative; + + while(input[i] != '\0') { + if(isdigit(input[i]) || input[i] == '.' || (input[i] == '-' && (i == 0 || input[i-1] == '(' || is_operator(input[i-1])))) { + // BzƦr]]Atơ^ + is_negative = 0; + int num_len = 0; + + // ˬdO_t + if(input[i] == '-') { + is_negative = 1; + i++; + } + + // Ʀrr + while(input[i] != '\0' && (isdigit(input[i]) || input[i] == '.')) { + number_str[num_len++] = input[i++]; + } + number_str[num_len] = '\0'; + i--; // ^h@ӦmA]~h while |A[@ + + // XƦr + printf("%s ", number_str); + if(is_negative) { + printf("- "); + } + + // NƦr[JǪF + for(j = 0; j < num_len; j++) { + postfix_1[postfix_index++] = number_str[j]; + } + postfix_1[postfix_index++] = ' '; + if(is_negative) { + postfix_1[postfix_index++] = '-'; + postfix_1[postfix_index++] = ' '; + } + } + else if(input[i] == '(') { + stack[++top] = input[i]; + } + else if(input[i] == ')') { + while(top >= 0 && stack[top] != '(') { + printf("%c ", stack[top]); + postfix_1[postfix_index++] = stack[top]; + postfix_1[postfix_index++] = ' '; + top--; + } + if(top >= 0) top--; + } + else if(is_operator(input[i])) { + // pGOBztƪ + if(input[i] == '+' && input[i-1] == '('){ + + } + else if(input[i-1] != 'o'){ + if(!(input[i] == '-' && (i == 0 || input[i-1] == '(' || is_operator(input[i-1])))) { + while(top >= 0 && stack[top] != '(' && + (get_priority(stack[top]) > get_priority(input[i]) || + (get_priority(stack[top]) == get_priority(input[i]) && input[i] != '^'))) { + printf("%c ", stack[top]); + postfix_1[postfix_index++] = stack[top]; + postfix_1[postfix_index++] = ' '; + top--; + } + stack[++top] = input[i]; + } + } + + } + i++; + } + + while(top >= 0) { + printf("%c ", stack[top]); + postfix_1[postfix_index++] = stack[top]; + postfix_1[postfix_index++] = ' '; + top--; + } + postfix_1[postfix_index] = '\0'; + printf("\n"); +} + +// === ഫǪF === +//p +void convert_to_postfix() { + int i = 0 , j; + int postfix_index = 0; + top = -1; + + while(input[i] != '\0') { + + if(isdigit(input[i]) || input[i] == '.' || (input[i] == '-' && (i == 0 || input[i-1] == '(' || is_operator(input[i-1])))) { // ˬdO_ƦrBpIάOt]BOF}lAκbAιBū᭱^ + char *end; + double num = strtod(&input[i], &end); //strtod r괫BI + int len = end - &input[i]; //pƦrrꪺ ƦrݪO}Om + printf("%.1f ", num); + for(j = 0; j < len; j++) { + postfix[postfix_index++] = input[i+j]; + } + postfix[postfix_index++] = ' '; + i += len - 1; + }else if(input[i] == '(') { + stack[++top] = input[i]; + } + else if(input[i] == ')') { + while(top >= 0 && stack[top] != '(') { + printf("%c ", stack[top]); + postfix[postfix_index++] = stack[top]; + postfix[postfix_index++] = ' '; + top--; + }if(top >= 0) top--; + }else if(is_operator(input[i])) { + if(input[i] == '+' && input[i-1] == '('){ + + }else if(input[i-1]!='o' ){ + while(top >= 0 && stack[top] != '(' && (get_priority(stack[top]) > get_priority(input[i]) || (get_priority(stack[top]) == get_priority(input[i]) && input[i] != '^'))) { + printf("%c ", stack[top]); + postfix[postfix_index++] = stack[top]; + postfix[postfix_index++] = ' '; + top--; + } + stack[++top] = input[i]; + } + } + i++; + } + + while(top >= 0) { + printf("%c ", stack[top]); + postfix[postfix_index++] = stack[top]; + postfix[postfix_index++] = ' '; + top--; + } + postfix[postfix_index] = '\0'; + printf("\n"); +} + +// === pǪF === +double evaluate_postfix() { + int i; + numTop = -1; + char *token = strtok(postfix, " "); + + printf("\npL{G\n"); + + while(token != NULL) { + printf("BzаOG'%s'\n", token); + + if(isdigit(token[0]) || (token[0] == '-' && isdigit(token[1]))) { + double num = atof(token); + numStack[++numTop] = num; + printf("JƦrG%.2f\n", num); + }else if(token[0] == 's'|| token[0] == 'c' ){ + if(numTop < 1) { + printf("Bl '%c' ʤ֨B⤸\n", token[0]); + exit(1); + } + double b = numStack[numTop--]; + double result = calculate(0, b, token[0]); + numStack[++numTop] = result; + printf("pG%c %.2f = %.2f\n", token[0], b, result); + + }else if(is_operator(token[0])) { + if(numTop < 1) { + printf("Bl '%c' ʤ֨B⤸\n", token[0]); + exit(1); + } + double b = numStack[numTop--]; + double a = numStack[numTop--]; + double result = calculate(a, b, token[0]); + numStack[++numTop] = result; + printf("pG%.2f %c %.2f = %.2f\n", a, token[0], b, result); + } + else { + printf("~GаO '%s'\n", token); + exit(1); + } + + printf("e|G"); + for(i = 0; i <= numTop; i++) { + printf("%.2f ", numStack[i]); + } + printf("\n\n"); + + token = strtok(NULL, " "); + } + + if(numTop != 0) { + printf("~Gp⵲|Ѿl %d Ӥ\n", numTop + 1); + exit(1); + } + return numStack[numTop]; +} + +int main() { + + printf("пJǪܦ(䴩+-*/%^()B) => "); + + fgets(input, MAX, stdin); + input[strcspn(input, "\n")] = 0; + + printf("\nǪܪkG "); + convert_to_postfix_forprint(); //ܥ + printf("\np⪺ǪܪkG "); + convert_to_postfix(); + double postfix_result = evaluate_postfix(); + printf("\nB⵲GG%.4f", postfix_result); + + printf("\t(TȬG"); + if(strcmp(input,"10+20*(50-30)/2^4-6*8")==0){ + printf("%g",10+20*(50-30)/pow(2,4)-6*8); + }else if(strcmp(input,"10+20*(-50+30)/-2^4-6*8")==0){ + printf("%g",10+20*(-50+30)/pow(-2,4)-6*8); + }else if(strcmp(input,"10.5+20.8*(50.1-30.6)/2.5^4-6.6*8.2")==0){ + printf("%g",10.5+20.8*(50.1-30.6)/pow(2.5,4)-6.6*8.2); + }else if(strcmp(input,"10.5+20.8*(-50.1+30.6)/2.5^-4-6.6*8.2")==0){ + printf("%g",10.5+20.8*(-50.1+30.6)/pow(2.5,-4)-6.6*8.2); + }else if(strcmp(input,"10-30*(-40-20)%2^4+7.5*-6")==0){ + printf("%g",10-30*(-40-20)%(int)pow(2,4)+7.5*-6); + }else if(strcmp(input,"1+sin((-50.2+sin(3.8*20)*cos(-30-100%40))*2^-2.5)*cos(123.456)")==0){ + printf("%g",1+sin((-50.2+sin(3.8*20)*cos(-30-100%40))*pow(2,-2.5))*cos(123.456)); + }else if(strcmp(input,"100*(sin(sin(sin(50.2*cos((30+100%40)*sin(60/5.5)))+20*(50/30.0)^3.5-6*8)))^2")==0){ + printf("%g",100*pow(sin(sin(sin(50.2*cos((30+100%40)*sin(60/5.5)))+20*pow(50/30.0,3.5)-6*8)),2)); + }else if(strcmp(input,"100*(sin(sin(sin(+50.2*cos((30+100%40)*sin(60/5.5)))+20*(+50/30.0)^3.5-6*8)))^2")==0){ + printf("%g",100*pow(sin(sin(sin(50.2*cos((30+100%40)*sin(60/5.5)))+20*pow(50/30.0,3.5)-6*8)),2)); + }printf(")"); + + return 0; +} diff --git a/作業/exam/exam_2.exe b/作業/exam/exam_2.exe new file mode 100644 index 0000000..cba0565 Binary files /dev/null and b/作業/exam/exam_2.exe differ diff --git a/作業/exam/main.cpp b/作業/exam/main.cpp new file mode 100644 index 0000000..8bfb763 --- /dev/null +++ b/作業/exam/main.cpp @@ -0,0 +1,266 @@ +#include +#include +#include +#include +#include + +typedef struct node { + int coef; + int exp; + int root; + struct node* rlink; + struct node* llink; +} node; +node *head, *tail, *current, *prev, *temp ,*head_root , *current_root , *tail_root; + +void init_f() { + head = (node *)malloc(sizeof(node)); + tail = (node *)malloc(sizeof(node)); + head->rlink = tail; + tail->llink = head; + + head_root = (node *)malloc(sizeof(node)); + tail_root = (node *)malloc(sizeof(node)); + + head_root->rlink = tail_root; + tail_root->llink = head_root; +} + +void read_poly(char str[] ){ + int argCount ; + while (1) { + + node* newNode = (node*)malloc(sizeof(node)); + + argCount = sscanf(str, "%dx^%d%s", &newNode->coef, &newNode->exp, str); + + if (argCount >= 2) { // \ŪYƩM + + newNode->llink = tail->llink; + newNode->rlink = tail; + tail->llink->rlink = newNode; + tail->llink = newNode; + + if (argCount == 2) { + break ; + } + + } else { + if(!isdigit(newNode->coef)){ + newNode->exp = 0; + + newNode->llink = tail->llink; + newNode->rlink = tail; + tail->llink->rlink = newNode; + tail->llink = newNode; + + break ; + + }else{ +// printf("newNode->coef = %d\n",newNode->coef); +// printf("isdigit(newNode->coef) = %d",isdigit(newNode->coef)); + + free(newNode); + break ; + } + + } + } +} + +void compact(char str[]){ /* strťաAܱo */ + int i, j; + + for (i = j = 0; str[i]; i++, j++) { + for (; str[i]==' '; i++); + str[j] = str[i]; + } + str[j] = '\0'; + printf("\nťի᪺rG%s\n",str); +} + +void clear_node(){ + // O + current = head->rlink; + while (current != tail) { + temp = current; + current = current->rlink; + free(temp); + } + free(head); + free(tail); + free(head_root); + free(tail_root); +} + + +void show( int n, int mode){ + int i; + if(mode == 0){ + printf("\n{p(x)= "); + current = head->rlink; + + while (current != tail) { + if(abs(current->coef)>1){ + printf("%s%d", current->coef > 1? "":"\b",current->coef); + }else if(current->coef == -1){ + printf("%s", current->exp == 0? "\b-1":"\b-"); + } + switch(current->exp){ + case 0: + if(current->coef == 1 ) printf("1+"); + else printf("+"); + break; + case 1: + printf("x+"); + break; + default: + printf("x^%d+",current->exp); + } + current = current->rlink; + } + printf("\b "); + + }else { /* mode==1Aܩұo */ + + current_root = head_root->rlink; + + while(current_root != tail_root){ + printf("%d ",current_root->root); + current_root = current_root->rlink; + } + + } + +} + +int findRoot() /* ڡAұoѦsJq[]A^ǮڪӼ */ +{ + + current_root = head_root->rlink; + + int r, c = 0, i, j, k, sum; + int sign[2] = {1,-1}; + + current = tail->llink; + r = abs(current->coef); /* X̧CY */ + + if (current->exp != 0) { /* ̧C >= 1Ah0i */ + if ((i = current->exp) > 0) { + node* newNode = (node*)malloc(sizeof(node)); + + newNode->root = 0; /* ̧CƳ]i */ + + newNode->llink = tail_root->llink; + newNode->rlink = tail_root; + tail_root->llink->rlink = newNode; + tail_root->llink = newNode; + c = 1; + } + current = head->rlink; + while(current!=tail){ + current->exp -= i; /* Ҧƴhi */ + current = current->rlink; + } + } + + +// r = abs(p[2*p[0]]); /* X̧CY */ + + for (i = 1; i <= r; i++) { /* Ҽ{㰣r]iA`Nt */ + if (r%i != 0) continue; /* 㰣riNLA~Ҽ{U@i */ + + for (j = 0; j < 2; j++) { /* j0ANҼ{+iҡFj1ANҼ{-ip */ + for (sum = 0, current = head->rlink ; current!= tail ; current = current->rlink) /* pC@G(Y*x^)ò֥[sum */ + sum += current->coef *(int)(pow(sign[j]*i,current->exp)); + if (sum == 0) { + node* newNode = (node*)malloc(sizeof(node)); + newNode->root = sign[j]*i; /* bingo! o{XG󪺾ƮڡANgJq}C */ + + newNode->llink = tail_root->llink; + newNode->rlink = tail_root; + tail_root->llink->rlink = newNode; + tail_root->llink = newNode; + c = 1; + } + } + } + + return c; +} + +void sort(){ + + //YSƩΥu@ + if (head->rlink == tail || head->rlink->rlink == tail) { + return; + } + + int flag = 1; + while(flag){ + flag = 0; + current = head->rlink; + + while(current->rlink != tail){ + temp = current->rlink; + + if(current->exp < temp->exp ){ + temp->llink = current->llink; + current->rlink = temp->rlink; + + temp->rlink->llink = current; + temp->rlink = current; + + current->llink->rlink = temp; + current->llink = temp; + + flag = 1; + } + else{ + current = current->rlink; + } + } + } +} + +int main() { + char str[100]; + int poly_num ,c , high; + init_f(); + + printf("\n*** ѦhƮ ***\n\nJh ==> "); + + if (fgets(str, sizeof(str), stdin) == NULL) { + printf("J~I\n"); + return 1; + } + + compact(str); + read_poly(str); + + sort(); + + current = head->rlink; + high= current->exp; + + show(c,0); + + c = findRoot(); + + if (c > 0) { + printf("\n\nѱoƮڬG"); + show(c,1); + } + else + printf("\n\nƮڤsb\n"); + + + + clear_node(); + + + return 0; +} + + + diff --git a/作業/exam/main.exe b/作業/exam/main.exe new file mode 100644 index 0000000..604530a Binary files /dev/null and b/作業/exam/main.exe differ diff --git a/作業/test/DS4_test.cpp b/作業/test/DS4_test.cpp new file mode 100644 index 0000000..b8e1625 --- /dev/null +++ b/作業/test/DS4_test.cpp @@ -0,0 +1,375 @@ +#include +#include +#include +#include +#include + +#define MAX_NAME_LENGTH 24 + +//ŧi禡쫬 +void init_f(); +void readStudentsFromFile(char* filename); +void insertStudent(char* name, int english, int math); +void printStudentList(); +void sort(int mode , int target); +void modify_list(); +void add_data(char* name, int english, int math); +void remove_data(char* name); +void choose_subject(); + +// wqǥ͸`Ic +typedef struct Student { + char name[MAX_NAME_LENGTH]; + int english; + int math; + struct Student* llink; + struct Student* rlink; +} Student; + +Student *head, *tail, *current, *prev, *temp ,**arr; +FILE* file; +int list_length ; + +void init_f() { + head = (Student *) malloc(sizeof(Student)); + tail = (Student *) malloc(sizeof(Student)); + +// head->llink = head; // 쵲Vۤv +// head->rlink = head; // k쵲Vۤv +// tail = head; + +// head->llink = tail; + head->rlink = tail; +// tail->rlink = head; + tail->llink = head; +} + +// bJsǥ͸`I +void insertStudent(char* name, int english, int math) { + + Student* newNode = (Student*)malloc(sizeof(Student)); + + strcpy(newNode->name, name); + newNode->english = english; + newNode->math = math; + +// J + newNode->llink = tail->llink; + newNode->rlink = tail; + tail->llink->rlink = newNode; + tail->llink = newNode; +} + +//W[ +void add_data(char* name, int english, int math){ + Student* newNode = (Student*)malloc(sizeof(Student)); + + strcpy(newNode->name, name); + newNode->english = english; + newNode->math = math; + + newNode->llink = tail->llink; + newNode->rlink = tail; + tail->llink->rlink = newNode; + tail->llink = newNode; + printf("%s wW[\n", name); +} + +//ָ +void remove_data(char* name){ + + prev = head; + current = head->rlink; + + while(current!=tail &&strcmp(name,current->name)!=0){ + prev=current; + current=current->rlink; + } + if(current != tail){ + + current->rlink->llink = prev; + prev->rlink = current->rlink; + printf("%s wR\n", name); + free(current); + }else /* 䤣ƫhܿ~ */ + printf(" %s bC\n", name); + +} + +// qŪǥ͸ +void readStudentsFromFile(char* filename) { + file = fopen(filename, "r"); + if (file == NULL) { + printf("Lk}ɮ %s\n", filename); + exit(0); + } + + char line[100]; + int lineCount = 0; + + // Le| + while (lineCount < 4 && fgets(line, sizeof(line), file)) { + lineCount++; + } + + // Ūǥ͸ + char name[MAX_NAME_LENGTH]; + int english, math; + // %[ ]ܭnŪJ@ӦrŶX + // %23[^\t]uŪ̦h23ӦršAJ\tv ^D O\tNŪ + while(fgets(line, sizeof(line), file)!=NULL){ + if(isalpha(line[0])){ + sscanf(line, "%23[^\t]\t%d\t%d\n", name, &english, &math); + insertStudent(name, english, math); + }else if(line[0]=='*'){ + break; + } + } +// flocseե `ϥbmodify_list +// fclose(file); +} + +// ***᪺W[δָ +void modify_list(){ + char name[MAX_NAME_LENGTH]; + int english, math; + char line[100]; + + while(fgets(line, sizeof(line), file)!=NULL){ + if(line[0]=='+'){ + sscanf(line, "%*[^ ] %[^\t]\t%d\t%d\n", name, &english, &math); + printf("\n===============================\n"); + printf("W[@\n\n"); + add_data(name, english, math); + printStudentList(); + }else if(line[0]=='-'){ + sscanf(line, "%*[^ ] %[^\t]\t%d\t%d\n", name, &english, &math); + printf("\n===============================\n"); + printf("R@\n\n"); + remove_data(name); + printStudentList(); + } + } + fclose(file); +} + +// CLǥͦC +void printStudentList() { + + current = head->rlink; + + printf("\nqY}l\n"); + printf("\nmW\t\t^\tƾ\n"); + printf("--------------------------------\n"); + + while (current != tail) { + printf("%-15s\t%d\t%d\n", current->name, current->english, current->math); + current = current->rlink; + } + + current = tail->llink; + + printf("\nq}l\n"); + printf("\nmW\t\t^\tƾ\n"); + printf("--------------------------------\n"); + while (current != head) { + printf("%-15s\t%d\t%d\n", current->name, current->english, current->math); + current = current->llink; + } +} + +//̷modeiƧ +void sort(int mode , int target){ + list_length = 0; + //YSƩΥu@ + if (head->rlink == tail || head->rlink->rlink == tail) { + return; + } + + current = head->rlink; + while(current!=tail){ + list_length++; + current = current->rlink; + } + + Student **arr = (Student**)malloc(list_length*(sizeof(Student*))); + current = head->rlink; + for(int i = 0; i < list_length; i++) { + arr[i] = current; + current = current->rlink; + } + + for(int i = 0; i < list_length-1; i++) { + for(int j = 0; j < list_length-1-i; j++) { + if(mode==0) { + if(strcmp(arr[j]->name, arr[j+1]->name) > 0){ + Student *temp = arr[j]; + arr[j] = arr[j+1]; + arr[j+1] = temp; + } + }else if(mode==1){ + if(arr[j]->english < arr[j+1]->english ){ + Student *temp = arr[j+1]; + arr[j+1] = arr[j]; + arr[j] = temp; + } + } else if(mode==2){ + if(arr[j]->math < arr[j+1]->math ){ + Student *temp = arr[j+1]; + arr[j+1] = arr[j]; + arr[j] = temp; + } + } + } + } + + if(target != -1){ + if(target != 0 && target<=list_length){ + printf("ƦW%dǥͬ\n\n" + "mW\t\t^\tƾ\n%-15s\t%d\t%d", target, arr[target-1]->name, arr[target-1]->english, arr[target-1]->math); + printf("\n*****************************\n"); + }else if(target == 0 && target >= list_length){ + printf("\n*****************************\n"); + printf("Ƥsb"); + printf("\n*****************************\n"); + } + } + + + // ܱƧǫ᪺G + printf("\nƦW\tmW\t\t^\tƾ\n"); + printf("---------------------------------------------\n"); + for(int i = 0; i < list_length; i++) { + printf("%d\t%-15s\t%d\t%d\n", i+1, arr[i]->name, arr[i]->english, arr[i]->math); + } + printf("---------------------------------------------\n"); + +} + +//ܬؤαƦW +void choose_subject(){ + int subject ,number , i=1; + + printf("\nJܪ\n" + "1 ƾ 2 ^ ==> "); + subject = getche(); + switch(subject){ + case '1': + printf("\nJƦW(JЫEnter) ==> "); + scanf("%d",&number); + printf("\nƾ"); + sort(1,number); + break; + case '2': + printf("\nJƦW(JЫEnter) ==> "); + scanf("%d",&number); + printf("\n^"); + sort(2,number); + break; + default : + printf("J~"); + break; + } +} + +//Ҧ`I +void freeAllNodes() { + current = head->rlink; + while (current != tail) { + temp = current; + current = current->rlink; + free(temp); + } + free(head); // head `I + free(tail); // tail `I + free(arr); +} + +int main() { + char mode ,sort_mode , name[15]; + int english , math; + init_f(); + readStudentsFromFile("YunTechStudents.txt"); + + printStudentList(); + modify_list(); + + while(1){ + printf("\n******* ܶiƧǩάOƦWnWǥ *******\n" + "*--------------------------------------*\n" + "* 1 iƧ 2 ܱƦWnWǥ 3 *\n" + "* 4 ܭlC 5 Me 6 W[@ *\n" + "* 7 R@ *\n" + "\nпܥ\\ ==> "); // \\ b|ܶýX + mode = getche(); + switch(mode){ + case '1': + printf("\n\nܱƧǤ覡\n" + "*--------------------------------------*\n" + "1 Wr 2 ^妨Z 3 ƾǦZ \n" + "\nпܱƧǤ覡 ==> "); + sort_mode = getche(); + switch(sort_mode){ + case '1': + printf("\n\nHWriƧ\n"); + sort(0 ,-1); + break; + case '2': + printf("\n\nH^妨ZiƧ\n"); + sort(1 ,-1); + break; + case '3': + printf("\n\nHƾǦZiƧ\n"); + sort(2 ,-1); + break; + default: + printf("\nJ~\n"); + break; + } + break; + case '2': + choose_subject(); + break; + case '3': + printf("\n\n¨ϥΡABye~\n"); + freeAllNodes(); + return 0; + case '4': + printStudentList(); + break; + case '5': + system("cls"); + break; + case '6': + printf("\nJWr ==> "); +// scanf("%[^\n]",name); + + while(getchar() != '\n'); // Mwİ + fgets(name, sizeof(name), stdin); + name[strcspn(name, "\n")] = '\0'; // + + printf("\nJ^妨Z ==> "); + scanf("%d",&english); + printf("\nJƾǦZ ==> "); + scanf("%d",&math); + add_data(name,english,math); + + printStudentList(); + break; + case '7': + printf("\nRJWr ==> "); +// scanf("%[^\n]",name); + + while(getchar() != '\n'); // Mwİ + fgets(name, sizeof(name), stdin); + name[strcspn(name, "\n")] = '\0'; // + remove_data(name); + + printStudentList(); + break; + default: + printf("\nJ~\n"); + break; + } + } +} diff --git a/作業/test/DS4_test.exe b/作業/test/DS4_test.exe new file mode 100644 index 0000000..b380247 Binary files /dev/null and b/作業/test/DS4_test.exe differ diff --git a/作業/test/YunTechStudents.txt b/作業/test/YunTechStudents.txt new file mode 100644 index 0000000..665b05c --- /dev/null +++ b/作業/test/YunTechStudents.txt @@ -0,0 +1,18 @@ +YunTech EE Department (2024) +====================================== +Name English Math +---------------+-------+-------------- +Steve Jobs 50 60 +Tom Cruise 30 40 +Marie Jane 70 80 +Barrack Obama 46 77 +John Tyler 98 96 +U. S. Grant 97 88 +Robert Redford 22 33 +Bruce Lee 90 90 +************************************** ++ Oliver Hardy 90 80 ++ Slim Pickens 88 82 +- Marie Jane 0 0 ++ James Bond 88 82 +- Barrack Obama 0 0 \ No newline at end of file diff --git a/作業/test/YunTechStudents2.txt b/作業/test/YunTechStudents2.txt new file mode 100644 index 0000000..ceade09 --- /dev/null +++ b/作業/test/YunTechStudents2.txt @@ -0,0 +1,20 @@ +YunTech EE Department (2024) +====================================== +Name English Math +---------------+-------+-------------- +Steve Jobs 50 60 +Tom Cruise 30 40 +Marie Jane 70 80 +Barrack Obama 46 77 +John Tyler 98 96 +U. S. Grant 97 88 +Robert Redford 22 33 +Bruce Lee 90 90 +************************************** +- Steve Jobs 0 0 ++ Oliver Hardy 90 80 ++ Slim Pickens 88 82 +- Marie Jane 0 0 ++ James Bond 88 82 +- Barrack Obama 0 0 +- James Bond 0 0 \ No newline at end of file diff --git a/作業/test/double_pointer.cpp b/作業/test/double_pointer.cpp new file mode 100644 index 0000000..08a34a2 --- /dev/null +++ b/作業/test/double_pointer.cpp @@ -0,0 +1,65 @@ +#include +#include +#include + +void convert(int n, int b, char **result, int *size) { + // pݭn + int temp = n; + *size = 0; + while (temp > 0) { + temp /= b; + (*size)++; + } + + // tmO + *result = (char*)malloc((*size + 1) * sizeof(char)); + if (*result == NULL) { + printf("OtmѡI\n"); + return; + } + + // iഫ + int i = *size - 1; + while (n > 0) { + int remainder = n % b; + if (remainder < 10) { + (*result)[i] = remainder + '0'; + } else { + (*result)[i] = (remainder - 10) + 'A'; + } + n /= b; + i--; + } + (*result)[*size] = '\0'; // K[r굲 +} + +int main() { + int n, b; + char *result; // ΨӦsഫG + int size; // G + + while(1) { + printf("\nJഫQi쥿 ==> "); + scanf("%d", &n); + + if(n == -1) break; + + printf("\nJഫ ==> "); + scanf("%d", &b); + + convert(n, b, &result, &size); // ǤJЪ} + + printf("(%d)_10 = (", n); + for(int i = 0; i < size; i++) { + printf("%c", result[i]); + } + printf(")_%d\n", b); + + free(result); // tmO + } + + printf("{N...N~\n"); + system("pause"); + + return 0; +} diff --git a/作業/test/double_pointer.exe b/作業/test/double_pointer.exe new file mode 100644 index 0000000..f6d4c86 Binary files /dev/null and b/作業/test/double_pointer.exe differ diff --git a/作業/test/ds2_test.cpp b/作業/test/ds2_test.cpp new file mode 100644 index 0000000..c2aac9c --- /dev/null +++ b/作業/test/ds2_test.cpp @@ -0,0 +1,196 @@ +#include +#include +#include +#include +#include + +typedef struct node { + int coef; + int exp; + struct node* rlink; + struct node* llink; +} node; +node *head, *tail, *current, *prev, *temp; + +void init_f() { + head = (node *)malloc(sizeof(node)); + tail = (node *)malloc(sizeof(node)); + head->rlink = tail; + tail->llink = head; +} + +void read_poly(char str[] ){ + int argCount ; + while (1) { + + node* newNode = (node*)malloc(sizeof(node)); + + argCount = sscanf(str, "%dx^%d%s", &newNode->coef, &newNode->exp, str); + + if (argCount >= 2) { // \ŪYƩM + + newNode->llink = tail->llink; + newNode->rlink = tail; + tail->llink->rlink = newNode; + tail->llink = newNode; + + if (argCount == 2) { + break ; + } + + } else { + if(!isdigit(newNode->coef)){ + newNode->exp = 0; + + newNode->llink = tail->llink; + newNode->rlink = tail; + tail->llink->rlink = newNode; + tail->llink = newNode; + + break ; + + }else{ +// printf("newNode->coef = %d\n",newNode->coef); +// printf("isdigit(newNode->coef) = %d",isdigit(newNode->coef)); + + free(newNode); + break ; + } + + } + } +} + +void clear_node(){ + // O + current = head->rlink; + while (current != tail) { + temp = current; + current = current->rlink; + free(temp); + } + free(head); + free(tail); +} + + +void show(int p[], int n, int mode){ + int i; + if(mode == 0){ + printf("\n{p(x)= "); + current = head->rlink; + while (current != tail) { + if(abs(current->coef)>1){ + printf("%s%d", current->coef > 1? "":"\b",current->coef); + }else if(current->coef == -1){ + printf("%s", current->exp == 0? "\b-1":"\b-"); + } + switch(current->exp){ + case 0: + if(current->coef == 1 ) printf("1+"); + else printf("+"); + break; + case 1: + printf("x+"); + break; + default: + printf("x^%d+",current->exp); + } + current = current->rlink; + } + printf("\b "); + + }else { /* mode==1Aܩұo */ + for (i = 0; i < n; i++) printf("%dB",p[i]); + if (n > 0) printf("\b\b "); + } + +} + +int findRoot(int q[]) /* ڡAұoѦsJq[]A^ǮڪӼ */ +{ + int r, c = 0, i, j, k, sum; + int sign[2] = {1,-1}; + + current = tail->llink; + r = abs(current->coef); /* X̧CY */ + + if (current->exp != 0) { /* ̧C >= 1Ah0i */ + if ((i = current->exp) > 0) q[c++] = 0; /* ̧CƳ]i */ + current = head->rlink; + while(current!=tail){ + current->exp -= i; /* Ҧƴhi */ + current = current->rlink; + } + } + + +// r = abs(p[2*p[0]]); /* X̧CY */ + + for (i = 1; i <= r; i++) { /* Ҽ{㰣r]iA`Nt */ + if (r%i != 0) continue; /* 㰣riNLA~Ҽ{U@i */ + + for (j = 0; j < 2; j++) { /* j0ANҼ{+iҡFj1ANҼ{-ip */ + for (sum = 0, current = head->rlink ; current!= tail ; current = current->rlink) /* pC@G(Y*x^)ò֥[sum */ + sum += current->coef *(int)(pow(sign[j]*i,current->exp)); + if (sum == 0) q[c++] = sign[j]*i; /* bingo! o{XG󪺾ƮڡANgJq}C */ + } + } + + return c; +} + + +int main() { + char str[100]; + int poly_num , *q ,c , high; + init_f(); + + printf("\n*** ѦhƮ ***\n\nJh ==> "); + + if (fgets(str, sizeof(str), stdin) == NULL) { + printf("J~I\n"); + return 1; + } + + +/* + 1x^2-100x^0 + 1x^3-2x^2-1x^1+2x^0 + 1x^3-7x^2+4x^1+12x^0 + 1x^4+3x^3-66x^2+52x^1+120x^0 + 3x^4+9x^3-198x^2+156x^1+360x^0 + 1x^2-1x^1 + 2x^ 3 -201 x^2+ 97 x^1 +300 + 2x^12-195x^11-500x^10 + 6x^4 - 1x^3 -25x^2 + 4x^1 + 4 + 1x^5-1x^3-1x^2-1x^1+1x^0 + 1x^5+1x^3+1x^2+1x^1+1x^0 + 1x^3+1x^0 +*/ + + read_poly(str); + + current = head->rlink; + high= current->exp; + + show(q,c,0); + + q = (int *)malloc((high + 1) *sizeof(int)); /* p[1]̰ơA̦ȳЫبŶ}CsҨDoƮ */ + + c = findRoot(q); + + if (c > 0) { + printf("\n\nѱoƮڬG"); + show(q,c,1); + } + else + printf("\n\nƮڤsb\n"); + + + + clear_node(); + + + return 0; +} diff --git a/作業/test/ds2_test.exe b/作業/test/ds2_test.exe new file mode 100644 index 0000000..093b757 Binary files /dev/null and b/作業/test/ds2_test.exe differ diff --git a/作業/test/fuzzy_HW1.c b/作業/test/fuzzy_HW1.c new file mode 100644 index 0000000..15397cf --- /dev/null +++ b/作業/test/fuzzy_HW1.c @@ -0,0 +1,74 @@ +#include +#include +#include + +int main(){ + int a , i; + double u1 ,u2 , u1uu2 , u1iu2 , u1b , u2b , u1cu2b , u1bcu2; + +// for(i=0;i<11;i++){ +// u1=exp(-(pow(i-4,2))/8); +// printf("u1(%d)=%f\n",i,u1); +// } +// printf("\n\n"); +// for(i=0;i<11;i++){ +// u2=exp(-(pow(i-8,2))/8); +// printf("u2(%d)=%f\n",i,u2); +// } + +// for(i=0;i<11;i++){ +// u1=exp(-(pow(i-4,2))/8); +// u2=exp(-(pow(i-8,2))/8); +// if(u1>u2){ +// printf("u1uu2(%d)=%f\n",i,u1); +// }else{ +// printf("u1uu2(%d)=%f\n",i,u2); +// } +// } +// printf("\n\n"); +// for(i=0;i<11;i++){ +// u1=exp(-(pow(i-4,2))/8); +// u2=exp(-(pow(i-8,2))/8); +// if(u1 +#include + +void mul (int **a,int**b,int **c, int m , int k , int n){ + int i , j ,l , sum; + for (i=0;i +#include +#include + +int main() { + printf("1+sin((-50.2+sin(3.8*20)*cos(-30-100%40))*(int)pow(2,-2.5))*cos(123.456) = %g\n",1+sin((-50.2+sin(3.8*20)*cos(-30-100%40))*pow(2,-2.5))*cos(123.456)); + printf("sin((-50.2+sin(3.8*20) = %g\n",sin((-50.2+sin(3.8*20)))); + + printf("\n*** ѦhƮ ***\n\nJh ==> "); + +// 1+sin((-50.2+sin(3.8*20)*cos(-30-100%40))*2^-2.5)*cos(123.456) + return 0; +} diff --git a/作業/test/try.exe b/作業/test/try.exe new file mode 100644 index 0000000..ae3f629 Binary files /dev/null and b/作業/test/try.exe differ diff --git a/作業/unit0/Makefile.win b/作業/unit0/Makefile.win new file mode 100644 index 0000000..a8848bc --- /dev/null +++ b/作業/unit0/Makefile.win @@ -0,0 +1,28 @@ +# Project: Project1 +# Makefile created by Dev-C++ 5.11 + +CPP = g++.exe -D__DEBUG__ +CC = gcc.exe -D__DEBUG__ +WINDRES = windres.exe +OBJ = Untitled1.o +LINKOBJ = Untitled1.o +LIBS = -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib" -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/lib" -static-libgcc -g3 +INCS = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include" +CXXINCS = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include/c++" +BIN = unit0_bowling_1.exe +CXXFLAGS = $(CXXINCS) -g3 +CFLAGS = $(INCS) -g3 +RM = rm.exe -f + +.PHONY: all all-before all-after clean clean-custom + +all: all-before $(BIN) all-after + +clean: clean-custom + ${RM} $(OBJ) $(BIN) + +$(BIN): $(OBJ) + $(CC) $(LINKOBJ) -o $(BIN) $(LIBS) + +Untitled1.o: Untitled1.c + $(CC) -c Untitled1.c -o Untitled1.o $(CFLAGS) diff --git a/作業/unit0/Untitled1.c b/作業/unit0/Untitled1.c new file mode 100644 index 0000000..6db1285 --- /dev/null +++ b/作業/unit0/Untitled1.c @@ -0,0 +1,55 @@ +#include +#include +#include + +typedef struct game { + char name[8]; /* ɪ̩mW */ + int score; /* o */ +}GAME; + + +int main(){ + + int i=0 ,j=0 ,n ; + GAME temp; + char input[20]; + GAME * bowling = (GAME*)malloc(sizeof(GAME)); + printf("Jɪ̸T\n"); + while(1){ + + printf("%dɪ̦Wr o => ",i+1); + +// fgets(input,sizeof(input),stdin); + if(fgets(input,sizeof(input),stdin) == NULL||(strcmp(input,"\n")) == 0 ){ + break; + } + + bowling = (GAME*)realloc(bowling ,(i+1)* sizeof(GAME)); + sscanf(input,"%s%d",bowling[i].name,&bowling[i].score); + i++; + n=i; + } + + for(i=0;i + +typedef struct game { + char name[8]; /* ɪ̩mW */ + int score; /* o */ + }GAME; + +void bubble_sort(GAME arr[], int total) { + int i,j; + for (i = 0; i < total - 1; i++) { + for (j = 0; j < total - i - 1; j++) { + if (arr[j].score < arr[j + 1].score) { + GAME temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + } + } + } +} + + +int main(){ + GAME bowling[] = {{"Jack",198},{"Tom",185},{"Bob",210},{"Fred",205},{"Mary",170}}; + int total =sizeof (bowling)/sizeof(bowling[0]); + + bubble_sort(bowling,total); + int i,j; + + printf("ZƦ\n"); + printf("---------\n"); + for(j=0;j +#include +#include + +typedef struct game { + char name[8]; // ɪ̩mW + int score; // o +} GAME; + +int main() { + GAME *bowling = NULL; + int total = 0; + int i, j; + char input[32]; + + printf("гvJɪ̪T...\n"); + while (1) { + printf("J%dɪ̦Wr o => ", total + 1); + + if (fgets(input, sizeof(input), stdin) == NULL) { + break; + } + + if (strcmp(input, "\n") == 0) { + break; + } + + GAME *temp = realloc(bowling, (total + 1) * sizeof(GAME)); + if (temp == NULL) { + printf("Memory allocation error\n"); + free(bowling); + return 1; + } + bowling = temp; + + sscanf(input, "%s %d", bowling[total].name, &bowling[total].score); + total++; + } + + printf("\nZƦW\n============\n"); + + // Sorting + for (i = 0; i < total - 1; i++) { + for (j = 0; j < total - i - 1; j++) { + if (bowling[j].score < bowling[j+1].score) { + GAME temp = bowling[j]; + bowling[j] = bowling[j+1]; + bowling[j+1] = temp; + } + } + } + + // Printing results + for (i = 0; i < total; i++) { + if (i == 0) + printf("%d. %s %d ax\n", i + 1, bowling[i].name, bowling[i].score); + else if (i == 1) + printf("%d. %s %d ȭx\n", i + 1, bowling[i].name, bowling[i].score); + else if (i == 2) + printf("%d. %s %d ux\n", i + 1, bowling[i].name, bowling[i].score); + else + printf("%d. %s %d\n", i + 1, bowling[i].name, bowling[i].score); + } + + free(bowling); + return 0; +} diff --git a/作業/unit0/bowling_2.exe b/作業/unit0/bowling_2.exe new file mode 100644 index 0000000..3222215 Binary files /dev/null and b/作業/unit0/bowling_2.exe differ diff --git a/作業/unit0/bowling_2.o b/作業/unit0/bowling_2.o new file mode 100644 index 0000000..9da13a8 Binary files /dev/null and b/作業/unit0/bowling_2.o differ diff --git a/作業/unit0/bowling_2_claude.c b/作業/unit0/bowling_2_claude.c new file mode 100644 index 0000000..138f980 --- /dev/null +++ b/作業/unit0/bowling_2_claude.c @@ -0,0 +1,114 @@ +#include +#include +#include + +typedef struct Player { + char name[8]; + int score; + struct Player* next; +} Player; + +Player* createPlayer(const char* name, int score) { + Player* newPlayer = (Player*)malloc(sizeof(Player)); + if (newPlayer == NULL) { + fprintf(stderr, "Ot\n"); + exit(1); + } + strncpy(newPlayer->name, name, 7); + newPlayer->name[7] = '\0'; + newPlayer->score = score; + newPlayer->next = NULL; + return newPlayer; +} + +void addPlayer(Player** head, const char* name, int score) { + Player* newPlayer = createPlayer(name, score); + newPlayer->next = *head; + *head = newPlayer; +} + +void sortPlayers(Player** head) { + int swapped; + Player* ptr1; + Player* lptr = NULL; + + if (*head == NULL) + return; + + do { + swapped = 0; + ptr1 = *head; + + while (ptr1->next != lptr) { + if (ptr1->score < ptr1->next->score) { + int tempScore = ptr1->score; + char tempName[8]; + strcpy(tempName, ptr1->name); + + ptr1->score = ptr1->next->score; + strcpy(ptr1->name, ptr1->next->name); + + ptr1->next->score = tempScore; + strcpy(ptr1->next->name, tempName); + + swapped = 1; + } + ptr1 = ptr1->next; + } + lptr = ptr1; + } while (swapped); +} + +void printResults(Player* head) { + printf("\nZƦW\n============\n"); + int rank = 1; + while (head != NULL) { + if (rank == 1) + printf("%d. %s %d ax\n", rank, head->name, head->score); + else if (rank == 2) + printf("%d. %s %d ȭx\n", rank, head->name, head->score); + else if (rank == 3) + printf("%d. %s %d ux\n", rank, head->name, head->score); + else + printf("%d. %s %d\n", rank, head->name, head->score); + head = head->next; + rank++; + } +} + +void freeList(Player* head) { + Player* temp; + while (head != NULL) { + temp = head; + head = head->next; + free(temp); + } +} + +int main() { + Player* head = NULL; + char input[32]; + char name[8]; + int score; + + printf("гvJɪ̪T...\n"); + + while (1) { + printf("Jɪ̦Wr o]ΫEnter^=> "); + if (fgets(input, sizeof(input), stdin) == NULL || strcmp(input, "\n") == 0) { + break; + } + + if (sscanf(input, "%7s %d", name, &score) == 2) { + addPlayer(&head, name, score); + } else { + printf("J榡~AЭsJC\n"); + } + } + + sortPlayers(&head); + printResults(head); + freeList(head); + + return 0; +} diff --git a/作業/unit0/bowling_2_claude.o b/作業/unit0/bowling_2_claude.o new file mode 100644 index 0000000..798830a Binary files /dev/null and b/作業/unit0/bowling_2_claude.o differ diff --git a/作業/unit0/bowling_2_gpt.c b/作業/unit0/bowling_2_gpt.c new file mode 100644 index 0000000..7ebfc12 --- /dev/null +++ b/作業/unit0/bowling_2_gpt.c @@ -0,0 +1,73 @@ +#include +#include +#include + +typedef struct game { + char name[8]; // ɪ̩mW + int score; // o +} GAME; + + +int main() { + GAME *bowling ; // ʺAtO骺 + int total = 0; // ɪ̼ƶq + int i , j ,temp; + char input[32]; // ȦsΨӳBzJ + + printf("гvJɪ̪T...\n"); + while (1) { + // ܿJɪ̦WٻPo + printf("J%dɪ̦Wr o => ", total + 1); + + // Ū@J + fgets(input, sizeof(input), stdin); + + // YUJAJL{ + if (strcmp(input, "\n") == 0) { + break; + } + + // ʺAtOŶHOssɪ̸ + bowling = (GAME *)malloc( (total + 1) * sizeof(GAME)); + +// printf("tO}: %p\n", (void *)bowling); + + // ѪRJW٩Mo + sscanf(input, "%s %d", bowling[total].name, &bowling[total].score); + + total++; + } + + // ܿJG + + + + printf("\nZƦW\n============\n"); + + for (i=0 ; i3) + printf("%d. %s %d\n", i + 1, bowling[i].name, bowling[i].score); + } + + // ʺAO + free(bowling); + + return 0; +} + diff --git a/作業/unit0/bowling_2_gpt.exe b/作業/unit0/bowling_2_gpt.exe new file mode 100644 index 0000000..d3b0d53 Binary files /dev/null and b/作業/unit0/bowling_2_gpt.exe differ diff --git a/作業/unit0/bowling_2_gpt.o b/作業/unit0/bowling_2_gpt.o new file mode 100644 index 0000000..687ba76 Binary files /dev/null and b/作業/unit0/bowling_2_gpt.o differ diff --git a/作業/unit0/pointer_func.c b/作業/unit0/pointer_func.c new file mode 100644 index 0000000..0ee180e --- /dev/null +++ b/作業/unit0/pointer_func.c @@ -0,0 +1,30 @@ +#include +#include + +void swap(int *,int *); + +int main(){ + + int x=14,y=62; + int ptr_a = &x,ptr_b = &y; + + printf("Initial ...\n"); + printf("x=%d , y=%d\n",x,y); + swap (&x,&y); + + printf("\nEnd swap ...\n"); + printf("x=%d , y=%d\n",x,y); + return 0; +} + +void swap(int *a,int *b){ + int temp; + printf("\nin swap ...\n"); + printf("a=%d , b=%d\n",*a,*b); + temp = *a; + *a=*b; + *b=temp; + printf("\nafter swap ...\n"); + printf("a=%d , b=%d\n",*a,*b); +} + diff --git a/作業/unit0/pointer_func.o b/作業/unit0/pointer_func.o new file mode 100644 index 0000000..44cffda Binary files /dev/null and b/作業/unit0/pointer_func.o differ diff --git a/作業/unit0/unit0_bowling_1.dev b/作業/unit0/unit0_bowling_1.dev new file mode 100644 index 0000000..1607cfa --- /dev/null +++ b/作業/unit0/unit0_bowling_1.dev @@ -0,0 +1,62 @@ +[Project] +FileName=unit0_bowling_1.dev +Name=Project1 +Type=1 +Ver=2 +ObjFiles= +Includes= +Libs= +PrivateResource= +ResourceIncludes= +MakeIncludes= +Compiler= +CppCompiler= +Linker= +IsCpp=0 +Icon= +ExeOutput= +ObjectOutput= +LogOutput= +LogOutputEnabled=0 +OverrideOutput=0 +OverrideOutputName= +HostApplication= +UseCustomMakefile=0 +CustomMakefile= +CommandLine= +Folders= +IncludeVersionInfo=0 +SupportXPThemes=0 +CompilerSet=0 +CompilerSettings=0000000000000000001000000 +UnitCount=1 + +[VersionInfo] +Major=1 +Minor=0 +Release=0 +Build=0 +LanguageID=1033 +CharsetID=1252 +CompanyName= +FileVersion= +FileDescription=Developed using the Dev-C++ IDE +InternalName= +LegalCopyright= +LegalTrademarks= +OriginalFilename= +ProductName= +ProductVersion= +AutoIncBuildNr=0 +SyncProduct=1 + +[Unit1] +FileName=Untitled1.c +CompileCpp=0 +Folder= +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd= + diff --git a/作業/unit0/unit0_bowling_1.exe b/作業/unit0/unit0_bowling_1.exe new file mode 100644 index 0000000..89d1ec4 Binary files /dev/null and b/作業/unit0/unit0_bowling_1.exe differ diff --git a/作業/unit0/unit0_bowling_1.layout b/作業/unit0/unit0_bowling_1.layout new file mode 100644 index 0000000..3097a4e --- /dev/null +++ b/作業/unit0/unit0_bowling_1.layout @@ -0,0 +1,13 @@ +[Editors] +Order=0 +Focused=0 +[Editor_0] +CursorCol=76 +CursorRow=23 +TopLine=7 +LeftChar=1 +[Editor_1] +CursorCol=1 +CursorRow=1 +TopLine=1 +LeftChar=1 diff --git a/作業/unit1/binary-search-solves-equation.o b/作業/unit1/binary-search-solves-equation.o deleted file mode 100644 index 33075b9..0000000 Binary files a/作業/unit1/binary-search-solves-equation.o and /dev/null differ diff --git a/作業/unit1/binary-search-solves-equation/Makefile.win b/作業/unit1/binary-search-solves-equation/Makefile.win new file mode 100644 index 0000000..9dbc7a2 --- /dev/null +++ b/作業/unit1/binary-search-solves-equation/Makefile.win @@ -0,0 +1,28 @@ +# Project: Project1 +# Makefile created by Dev-C++ 5.11 + +CPP = g++.exe +CC = gcc.exe +WINDRES = windres.exe +OBJ = test_3.o +LINKOBJ = test_3.o +LIBS = -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib" -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/lib" -static-libgcc +INCS = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include" +CXXINCS = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include/c++" +BIN = Project1.exe +CXXFLAGS = $(CXXINCS) +CFLAGS = $(INCS) +RM = rm.exe -f + +.PHONY: all all-before all-after clean clean-custom + +all: all-before $(BIN) all-after + +clean: clean-custom + ${RM} $(OBJ) $(BIN) + +$(BIN): $(OBJ) + $(CC) $(LINKOBJ) -o $(BIN) $(LIBS) + +test_3.o: test_3.cpp + $(CC) -c test_3.cpp -o test_3.o $(CFLAGS) diff --git a/作業/unit1/binary-search-solves-equation/Project1.dev b/作業/unit1/binary-search-solves-equation/Project1.dev new file mode 100644 index 0000000..83e966c --- /dev/null +++ b/作業/unit1/binary-search-solves-equation/Project1.dev @@ -0,0 +1,52 @@ +[Project] +FileName=Project1.dev +Name=Project1 +Type=1 +Ver=2 +ObjFiles= +Includes= +Libs= +PrivateResource= +ResourceIncludes= +MakeIncludes= +Compiler= +CppCompiler= +Linker= +IsCpp=0 +Icon= +ExeOutput= +ObjectOutput= +LogOutput= +LogOutputEnabled=0 +OverrideOutput=0 +OverrideOutputName= +HostApplication= +UseCustomMakefile=0 +CustomMakefile= +CommandLine= +Folders= +IncludeVersionInfo=0 +SupportXPThemes=0 +CompilerSet=0 +CompilerSettings=0000000000000000000000000 +UnitCount=0 + +[VersionInfo] +Major=1 +Minor=0 +Release=0 +Build=0 +LanguageID=1033 +CharsetID=1252 +CompanyName= +FileVersion= +FileDescription=Developed using the Dev-C++ IDE +InternalName= +LegalCopyright= +LegalTrademarks= +OriginalFilename= +ProductName= +ProductVersion= +AutoIncBuildNr=0 +SyncProduct=1 + diff --git a/作業/unit1/binary-search-solves-equation/Project1.layout b/作業/unit1/binary-search-solves-equation/Project1.layout new file mode 100644 index 0000000..852965c --- /dev/null +++ b/作業/unit1/binary-search-solves-equation/Project1.layout @@ -0,0 +1,13 @@ +[Editor_1] +CursorCol=3 +CursorRow=40 +TopLine=16 +LeftChar=1 +[Editor_0] +CursorCol=11 +CursorRow=10 +TopLine=1 +LeftChar=1 +[Editors] +Order= +Focused=0 diff --git a/作業/unit1/binary-search-solves-equation.c b/作業/unit1/binary-search-solves-equation/binary-search-solves-equation.c similarity index 87% rename from 作業/unit1/binary-search-solves-equation.c rename to 作業/unit1/binary-search-solves-equation/binary-search-solves-equation.c index a1a14a9..5b00ed3 100644 --- a/作業/unit1/binary-search-solves-equation.c +++ b/作業/unit1/binary-search-solves-equation/binary-search-solves-equation.c @@ -2,8 +2,8 @@ #include #include -#define f(x) (x+sin(x)-1) -//#define f(x) ((x)*(x)) +//#define f(x) (x+sin(x)-1) +#define f(x) ((x)*(x)) //#define f(x) ((x)*exp(x)*(x)*exp(x)) int main() { @@ -14,9 +14,6 @@ int main() { printf("N\t϶\t\t\t\t\n"); printf("-------+-------------------------------+-------------\n"); - printf("%.10f\n",f(num)); - - //Ѭ0.510973 if(f(num)==(num+sin(num)-1)){ while (upper - lower > precision && i < count ) { mid = (lower + upper) / 2.0; @@ -36,12 +33,11 @@ int main() { } } - //Ѭ0 if(f(num)==(num*num)){ while (upper - lower > precision && i < count ) { mid = (lower + upper) / 2.0; printf("#%d\t[%.10f,%.10f]\t=%.10f\n",i+1,lower,upper,mid); -// printf("\nf(mid)=%.10f, f(lower)=%.10f, f(upper)=%.10f\n",f(mid),f(lower),f(upper)); + printf("\nf(mid)=%.10f, f(lower)=%.10f, f(upper)=%.10f\n",f(mid),f(lower),f(upper)); if (fabs(f(mid)) < precision) { break; @@ -58,7 +54,6 @@ int main() { } } - //ߤ@Ѭ0,ͪѩҦp-5t if(f(num)==((num)*exp(num)*(num)*exp(num))){ while (upper - lower > precision && i < count ) { mid = (lower + upper) / 2.0; diff --git a/作業/unit1/binary-search-solves-equation/binary-search-solves-equation.o b/作業/unit1/binary-search-solves-equation/binary-search-solves-equation.o new file mode 100644 index 0000000..eee68e9 Binary files /dev/null and b/作業/unit1/binary-search-solves-equation/binary-search-solves-equation.o differ diff --git a/作業/unit1/binary-search-solves-equation/main.c b/作業/unit1/binary-search-solves-equation/main.c new file mode 100644 index 0000000..41934e9 --- /dev/null +++ b/作業/unit1/binary-search-solves-equation/main.c @@ -0,0 +1,79 @@ +#include +#include +#include + +//#define f(x) (x+sin(x)-1) +//#define f(x) ((x)*(x)) +#define f(x) ((x)*exp(x)*(x)*exp(x)) + +int main() { + int count = 1000 , i=0; + double precision = 1e-10 ; + //numܸѭӤ{ + double mid , lower=-20 , upper=100, num=2; + + if(f(num)==(num+sin(num)-1)){ + while (upper - lower > precision && i < count ) { + mid = (lower + upper) / 2.0; + + printf("#%d\t[%.10f,%.10f]\t=%.10f\n",i+1,lower,upper,mid); + + if (fabs(f(mid)) < precision) { + break; + } + + i++; + if ( f(mid) * f(lower) < 0) { + upper = mid; + } else { + lower = mid; + } + } + } + + if(f(num)==(num*num)){ + while (upper - lower > precision && i < count ) { + mid = (lower + upper) / 2.0; + + printf("\n#%d\t[%.10f,%.10f]\t=%.10f\n",i+1,lower,upper,mid); + printf("\nf(mid)=%f, f(lower)=%f, f(upper)=%f\n",f(mid),f(lower),f(upper)); + + if (fabs(f(mid)) < precision) { + break; + } + + i++; + if ( f(mid) > precision) { + if(mid>0){ + upper = mid; + } else if(mid<0){ + lower = mid; + } + } + } + } + + if(f(num)==((num)*exp(num)*(num)*exp(num))){ + while (upper - lower > precision && i < count ) { + mid = (lower + upper) / 2.0; + + printf("#%d\t[%.10f,%.10f]\t=%.10f\n",i+1,lower,upper,mid); +// printf("mid=%.10f,f(mid)=%.10f\n",mid,f(mid)); + if (fabs(f(mid)) < precision) { + break; + } + + i++; + if ( f(mid) > precision) { + if(mid>0){ + upper = mid; + } else if(mid<0){ + lower = mid; + } + } + } + } + + printf("\n׬%f",mid); + return 0; +} diff --git a/作業/unit1/binary-search-solves-equation/main.o b/作業/unit1/binary-search-solves-equation/main.o new file mode 100644 index 0000000..5052b45 Binary files /dev/null and b/作業/unit1/binary-search-solves-equation/main.o differ diff --git a/作業/unit1/binary-search-solves-equation/test.c b/作業/unit1/binary-search-solves-equation/test.c new file mode 100644 index 0000000..d81fecc --- /dev/null +++ b/作業/unit1/binary-search-solves-equation/test.c @@ -0,0 +1,34 @@ +#include +#include +#include + +#define f(x) ((x) + sin(x) - 1) + +int main() { + int count = 1000, i = 0; + double precision = 1e-15; + double epsilon = 1e-15; + double mid, lower = 0, upper = 2; + + while ((upper - lower > precision) && (i < count)) { + mid = (lower + upper) / 2.0; + double f_mid = f(mid); + + printf("#%d\t[%.15f,%.15f]\t=%.15f\tf(mid)=%.15e\n", i+1, lower, upper, mid, f_mid); + + if (fabs(f_mid) < epsilon) { + break; + } + + i++; + if (f_mid * f(lower) < 0) { + upper = mid; + } else { + lower = mid; + } + } + + printf("׬%.15f\n", mid); + printf("f(mid) = %.15e\n", f(mid)); + return 0; +} diff --git a/作業/unit1/binary-search-solves-equation/test.o b/作業/unit1/binary-search-solves-equation/test.o new file mode 100644 index 0000000..d8c694f Binary files /dev/null and b/作業/unit1/binary-search-solves-equation/test.o differ diff --git a/作業/unit1/binary-search-solves-equation/test_1.c b/作業/unit1/binary-search-solves-equation/test_1.c new file mode 100644 index 0000000..7f616bb --- /dev/null +++ b/作業/unit1/binary-search-solves-equation/test_1.c @@ -0,0 +1,49 @@ +#include +#include + +#define EPSILON 1e-6 +#define MAX_ITERATIONS 100 + +double f(double x, double a) { + return x * x - a; +} + +double bisection_method(double a, double left, double right) { + double mid; + int iterations = 0; + + while (right - left > EPSILON && iterations < MAX_ITERATIONS) { + mid = (left + right) / 2; + + if (f(mid, a) == 0.0) { + return mid; + } else if (f(mid, a) * f(left, a) < 0) { + right = mid; + } else { + left = mid; + } + + iterations++; + } + + return (left + right) / 2; +} + +int main() { + double a, result; + + printf("пJ@ӥ a ӨD x^2 = a: "); + scanf("%lf", &a); + + if (a < 0) { + printf("~Ga ODt\n"); + return 1; + } + + result = bisection_method(a, 0, a > 1 ? a : 1); + + printf("{ x^2 = %.6f Ѭ x = %.6f\n", a, result); + printf("ҡG%.6f^2 = %.6f\n", result, result * result); + + return 0; +} diff --git a/作業/unit1/binary-search-solves-equation/test_1.o b/作業/unit1/binary-search-solves-equation/test_1.o new file mode 100644 index 0000000..7cf53c1 Binary files /dev/null and b/作業/unit1/binary-search-solves-equation/test_1.o differ diff --git a/作業/unit1/binary-search-solves-equation/test_2.c b/作業/unit1/binary-search-solves-equation/test_2.c new file mode 100644 index 0000000..1e17f87 --- /dev/null +++ b/作業/unit1/binary-search-solves-equation/test_2.c @@ -0,0 +1,32 @@ +#include +#include +#include<> +int main(){ + double x,mid ,precision=1e-10; + int i=0, count=1000; + printf("Jx"); + scanf("%lf",&x); + double upper=x,lower=0; + mid=(upper+lower)/2; + + while (fabs((mid*mid)-x)> precision && i < count){ + mid=(upper+lower)/2; + printf("#%d\t[%f,%f]\t=%f\n",i+1,lower,upper,mid); + i++; + if(fabs(mid-x) x){ + upper=mid; +// lower=mid; + }else{ +// upper=mid; + lower=mid; + + } + + + + } + printf("%f",mid); + return 0; +} diff --git a/作業/unit1/binary-search-solves-equation/test_2.o b/作業/unit1/binary-search-solves-equation/test_2.o new file mode 100644 index 0000000..e7e33b1 Binary files /dev/null and b/作業/unit1/binary-search-solves-equation/test_2.o differ diff --git a/作業/unit1/binary-search-solves-equation/test_3.cpp b/作業/unit1/binary-search-solves-equation/test_3.cpp new file mode 100644 index 0000000..e60fe80 --- /dev/null +++ b/作業/unit1/binary-search-solves-equation/test_3.cpp @@ -0,0 +1,44 @@ +#include +#include +#include +#define f(x) ((x) * (x) - a) // wq{ f(x) + +using namespace std; + +int main() { + + double a; + cout << "ڪƭ a= "; + cin >> a; + cout << "----------------------------------------"<< endl; + double c=sqrt(a); + double left = 0, right = 20; // ]wd + double b = 1e-10; + double mid; + int i = 0; + + while ((right - left) > b) { + mid = (left + right) / 2.0; + i++; + printf("#%d [%f %f ]\n", i, left, right); + + if (f(mid) == 0.0) { + cout << "ڪȬ: " << mid << " B f(x)= " << f(mid) << endl; + return 0; + } + + if (f(left) * f(mid) < 0) { + right = mid; // + } else { + left = mid; // k + } + } + cout << "-----------------------------------------"<< endl; + int d=((mid - c) / (c)) * 100 ; + if(d>0) + d=d; + else + d=-d; + cout << "sqrt("<< a <<"): " << sqrt(a) << " ~tȬ(%)" << d << endl; + return 0; +} diff --git a/作業/unit1/binary-search-solves-equation/test_3.o b/作業/unit1/binary-search-solves-equation/test_3.o new file mode 100644 index 0000000..18e2568 Binary files /dev/null and b/作業/unit1/binary-search-solves-equation/test_3.o differ diff --git a/作業/unit1/binary-search-square-root/Makefile.win b/作業/unit1/binary-search-square-root/Makefile.win new file mode 100644 index 0000000..c93a9d6 --- /dev/null +++ b/作業/unit1/binary-search-square-root/Makefile.win @@ -0,0 +1,28 @@ +# Project: Project1 +# Makefile created by Dev-C++ 5.11 + +CPP = g++.exe +CC = gcc.exe +WINDRES = windres.exe +OBJ = binary-search-square-root.o +LINKOBJ = binary-search-square-root.o +LIBS = -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib" -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/lib" -static-libgcc +INCS = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include" +CXXINCS = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include/c++" +BIN = Project1.exe +CXXFLAGS = $(CXXINCS) +CFLAGS = $(INCS) +RM = rm.exe -f + +.PHONY: all all-before all-after clean clean-custom + +all: all-before $(BIN) all-after + +clean: clean-custom + ${RM} $(OBJ) $(BIN) + +$(BIN): $(OBJ) + $(CC) $(LINKOBJ) -o $(BIN) $(LIBS) + +binary-search-square-root.o: binary-search-square-root.c + $(CC) -c binary-search-square-root.c -o binary-search-square-root.o $(CFLAGS) diff --git a/作業/unit1/binary-search-square-root/Project1.dev b/作業/unit1/binary-search-square-root/Project1.dev new file mode 100644 index 0000000..95433df --- /dev/null +++ b/作業/unit1/binary-search-square-root/Project1.dev @@ -0,0 +1,62 @@ +[Project] +FileName=Project1.dev +Name=Project1 +Type=1 +Ver=2 +ObjFiles= +Includes= +Libs= +PrivateResource= +ResourceIncludes= +MakeIncludes= +Compiler= +CppCompiler= +Linker= +IsCpp=0 +Icon= +ExeOutput= +ObjectOutput= +LogOutput= +LogOutputEnabled=0 +OverrideOutput=0 +OverrideOutputName= +HostApplication= +UseCustomMakefile=0 +CustomMakefile= +CommandLine= +Folders= +IncludeVersionInfo=0 +SupportXPThemes=0 +CompilerSet=0 +CompilerSettings=0000000000000000000000000 +UnitCount=1 + +[VersionInfo] +Major=1 +Minor=0 +Release=0 +Build=0 +LanguageID=1033 +CharsetID=1252 +CompanyName= +FileVersion= +FileDescription=Developed using the Dev-C++ IDE +InternalName= +LegalCopyright= +LegalTrademarks= +OriginalFilename= +ProductName= +ProductVersion= +AutoIncBuildNr=0 +SyncProduct=1 + +[Unit1] +FileName=E:\ѮvЧ\@~\unit1\binary-search-square-root.c +CompileCpp=0 +Folder= +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd= + diff --git a/作業/unit1/binary-search-square-root.exe b/作業/unit1/binary-search-square-root/Project1.exe similarity index 98% rename from 作業/unit1/binary-search-square-root.exe rename to 作業/unit1/binary-search-square-root/Project1.exe index 4fd176d..59a3ef9 100644 Binary files a/作業/unit1/binary-search-square-root.exe and b/作業/unit1/binary-search-square-root/Project1.exe differ diff --git a/作業/unit1/binary-search-square-root/Project1.layout b/作業/unit1/binary-search-square-root/Project1.layout new file mode 100644 index 0000000..a52f300 --- /dev/null +++ b/作業/unit1/binary-search-square-root/Project1.layout @@ -0,0 +1,8 @@ +[Editor_0] +CursorCol=2 +CursorRow=18 +TopLine=1 +LeftChar=1 +[Editors] +Order=0 +Focused=0 diff --git a/作業/unit1/binary-search-square-root.c b/作業/unit1/binary-search-square-root/binary-search-square-root.c similarity index 97% rename from 作業/unit1/binary-search-square-root.c rename to 作業/unit1/binary-search-square-root/binary-search-square-root.c index c232726..f5786f3 100644 --- a/作業/unit1/binary-search-square-root.c +++ b/作業/unit1/binary-search-square-root/binary-search-square-root.c @@ -34,7 +34,7 @@ int main() { } if(x<1){ - lower=0 , upper=1 ,i=0; + lower=x , upper=1 ,i=0; printf("\nϥΤGjMkDѹL{pU...\n"); printf("\nN\t϶\t\t\t\t\n"); printf("-------+-------------------------------+-------------\n"); diff --git a/作業/unit1/binary-search-square-root.o b/作業/unit1/binary-search-square-root/binary-search-square-root.o similarity index 100% rename from 作業/unit1/binary-search-square-root.o rename to 作業/unit1/binary-search-square-root/binary-search-square-root.o diff --git a/作業/unit1/binary-search-square-root/main.c b/作業/unit1/binary-search-square-root/main.c new file mode 100644 index 0000000..8ddf853 --- /dev/null +++ b/作業/unit1/binary-search-square-root/main.c @@ -0,0 +1,52 @@ +#include +#include +#include + +int main() { + int i; + double precision = 1e-10 , x; + + printf("***Jx(x>0)p⥭***\n"); + printf("Jx=> "); + scanf("%lf",&x); + double mid , lower , upper; + + + if(x<0){ + printf("~! XȤ<1"); + return 1; + } + + if(x>1){ + lower=0 , upper=x , i=0; + while (upper - lower > precision) { + mid = (lower + upper) / 2.0; + printf("#%d\t[%.10f,%.10f]\t=%.10f\n",i+1,lower,upper,mid); + i++; + if (mid * mid > x) { + upper = mid; + } else { + lower = mid; + } + } + } + + if(x<1){ + lower=x , upper=1 ,i=0; + while (upper - lower > precision) { + mid = (lower + upper) / 2.0; + printf("#%d\t[%.10f,%.10f]\t=%.10f\n",i+1,lower,upper,mid); + i++; + if (mid * mid > x) { + upper = mid; + } else { + lower = mid; + } + } + } + + printf("%fڬ%.10f\n",x,mid); + printf("sqrt(%f)G%.10f\n",x,sqrt(x)); + + return 0; +} diff --git a/作業/unit1/binary-search-square-root/main.o b/作業/unit1/binary-search-square-root/main.o new file mode 100644 index 0000000..698dc95 Binary files /dev/null and b/作業/unit1/binary-search-square-root/main.o differ diff --git a/作業/unit1/binary-search-square-root/test.c b/作業/unit1/binary-search-square-root/test.c new file mode 100644 index 0000000..50f2778 --- /dev/null +++ b/作業/unit1/binary-search-square-root/test.c @@ -0,0 +1,44 @@ +#include +#include +#include + +int main() { + int x; + double precision = 1e-5; + + printf("***Jx(x>0)p⥭***\n"); + + // MſJwİ + int c; + while ((c = getchar()) != '\n' && c != EOF); + + // ϥ fgets M sscanf ŪJ + char input[100]; + if (fgets(input, sizeof(input), stdin) == NULL) { + printf("ŪJɵoͿ~\n"); + return 1; + } + + if (sscanf(input, "%d", &x) != 1 || x <= 0) { + printf("LĪJCпJ@ӥơC\n"); + return 1; + } + + int lower = 0, upper = x; + double ans = sqrt(x); + double mid; + + while (upper - lower > precision) { + mid = (lower + upper) / 2.0; + if (mid * mid > x) { + upper = mid; + } else { + lower = mid; + } + } + + printf("%dڬ%f\n", x, mid); + printf("sqrt(%d)G%f\n", x, ans); + + return 0; +} diff --git a/作業/unit1/binary-search-square-root/test.o b/作業/unit1/binary-search-square-root/test.o new file mode 100644 index 0000000..e73f98c Binary files /dev/null and b/作業/unit1/binary-search-square-root/test.o differ diff --git a/作業/unit1/matrix multiplication/Makefile.win b/作業/unit1/matrix multiplication/Makefile.win new file mode 100644 index 0000000..dca9b0a --- /dev/null +++ b/作業/unit1/matrix multiplication/Makefile.win @@ -0,0 +1,28 @@ +# Project: Project3 +# Makefile created by Dev-C++ 5.11 + +CPP = g++.exe +CC = gcc.exe +WINDRES = windres.exe +OBJ = test3.o +LINKOBJ = test3.o +LIBS = -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib" -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/lib" -static-libgcc +INCS = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include" +CXXINCS = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include/c++" +BIN = Project3.exe +CXXFLAGS = $(CXXINCS) +CFLAGS = $(INCS) +RM = rm.exe -f + +.PHONY: all all-before all-after clean clean-custom + +all: all-before $(BIN) all-after + +clean: clean-custom + ${RM} $(OBJ) $(BIN) + +$(BIN): $(OBJ) + $(CC) $(LINKOBJ) -o $(BIN) $(LIBS) + +test3.o: test3.c + $(CC) -c test3.c -o test3.o $(CFLAGS) diff --git a/作業/unit1/matrix multiplication/Project3.dev b/作業/unit1/matrix multiplication/Project3.dev new file mode 100644 index 0000000..3c704c8 --- /dev/null +++ b/作業/unit1/matrix multiplication/Project3.dev @@ -0,0 +1,62 @@ +[Project] +FileName=Project3.dev +Name=Project3 +Type=1 +Ver=2 +ObjFiles= +Includes= +Libs= +PrivateResource= +ResourceIncludes= +MakeIncludes= +Compiler= +CppCompiler= +Linker= +IsCpp=0 +Icon= +ExeOutput= +ObjectOutput= +LogOutput= +LogOutputEnabled=0 +OverrideOutput=0 +OverrideOutputName= +HostApplication= +UseCustomMakefile=0 +CustomMakefile= +CommandLine= +Folders= +IncludeVersionInfo=0 +SupportXPThemes=0 +CompilerSet=0 +CompilerSettings=0000000000000000000000000 +UnitCount=1 + +[VersionInfo] +Major=1 +Minor=0 +Release=0 +Build=0 +LanguageID=1033 +CharsetID=1252 +CompanyName= +FileVersion= +FileDescription=Developed using the Dev-C++ IDE +InternalName= +LegalCopyright= +LegalTrademarks= +OriginalFilename= +ProductName= +ProductVersion= +AutoIncBuildNr=0 +SyncProduct=1 + +[Unit1] +FileName=E:\ѮvЧ\@~\matrix-multiplication\matrix-multiplication.c +CompileCpp=0 +Folder= +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd= + diff --git a/作業/unit1/matrix-multiplication/matrix-multiplication.exe b/作業/unit1/matrix multiplication/Project3.exe similarity index 64% rename from 作業/unit1/matrix-multiplication/matrix-multiplication.exe rename to 作業/unit1/matrix multiplication/Project3.exe index 33e786d..a543c96 100644 Binary files a/作業/unit1/matrix-multiplication/matrix-multiplication.exe and b/作業/unit1/matrix multiplication/Project3.exe differ diff --git a/作業/unit1/matrix multiplication/Project3.layout b/作業/unit1/matrix multiplication/Project3.layout new file mode 100644 index 0000000..ede1280 --- /dev/null +++ b/作業/unit1/matrix multiplication/Project3.layout @@ -0,0 +1,18 @@ +[Editor_1] +CursorCol=17 +CursorRow=3 +TopLine=1 +LeftChar=1 +[Editors] +Order=0 +Focused=0 +[Editor_0] +CursorCol=16 +CursorRow=74 +TopLine=64 +LeftChar=1 +[Editor_2] +CursorCol=26 +CursorRow=41 +TopLine=1 +LeftChar=1 diff --git a/作業/unit1/matrix multiplication/by_me.c b/作業/unit1/matrix multiplication/by_me.c new file mode 100644 index 0000000..1b7b395 --- /dev/null +++ b/作業/unit1/matrix multiplication/by_me.c @@ -0,0 +1,69 @@ +#include +#include + +void mul(int **a ,int **b,int **c ,int m , int k ,int n){ + int i , j , l ,sum; + + for (i=0;i +#include +#include + +#define MAX_LINE_LENGTH 1000 + +// tx}O +int** allocateMatrix(int rows, int cols) { + int i; + int** matrix = (int**)malloc(rows * sizeof(int*)); + for (i = 0; i < rows; i++) { + matrix[i] = (int*)malloc(cols * sizeof(int)); + } + return matrix; +} + +// x}O +void freeMatrix(int** matrix, int rows) { + int i ; + for (i = 0; i < rows; i++) { + free(matrix[i]); + } + free(matrix); +} + +// x}k +void mul(int **a, int **b, int **c, int m, int k, int n) { + int i , j , l ; + for (i = 0; i < m; i++) { + for (j = 0; j < n; j++) { + c[i][j] = 0; + for (l = 0; l < k; l++) { + c[i][j] += a[i][l] * b[l][j]; + } + } + } +} + +// Ūx}ê^ +int** readMatrix(FILE* file, int* rows, int* cols) { + char line[MAX_LINE_LENGTH]; + int** matrix = NULL; + *rows = 0; + *cols = 0; + + while (fgets(line, sizeof(line), file)) { + if (strlen(line) <= 1) break; // Ŧܯx} + + (*rows)++; + int tempCols = 0; + char* token = strtok(line, " \t\n"); + + while (token != NULL) { + tempCols++; + token = strtok(NULL, " \t\n"); + } + + if (*cols == 0) { + *cols = tempCols; + matrix = allocateMatrix(*rows, *cols); + } + + if (tempCols != *cols) { + printf("~Gx}CƤ@P\n"); + exit(1); + } + + // sŪӦæsxƾ + int col = 0; + token = strtok(line, " \t\n"); + while (token != NULL) { + matrix[*rows - 1][col++] = atoi(token); + token = strtok(NULL, " \t\n"); + } + } + + return matrix; +} + +int main() { + int i , j ; + FILE *file = fopen("matrix_input.txt", "r"); + if (file == NULL) { + printf("Lk}ɮ\n"); + return 1; + } + + int m, k1, k2, n; + int **arr_a, **arr_b, **arr_c; + + // ŪĤ@ӯx} + arr_a = readMatrix(file, &m, &k1); + + // ŪĤGӯx} + arr_b = readMatrix(file, &k2, &n); + + fclose(file); + + // ˬdx}O_iHۭ + if (k1 != k2) { + printf("~Goӯx}Lkۭ\n"); + freeMatrix(arr_a, m); + freeMatrix(arr_b, k2); + return 1; + } + + // tGx}Ŷ + arr_c = allocateMatrix(m, n); + + // x}k + mul(arr_a, arr_b, arr_c, m, k1, n); + + // XG + printf("x}kGG\n"); + for (i = 0; i < m; i++) { + for (j = 0; j < n; j++) { + printf("%d ", arr_c[i][j]); + } + printf("\n"); + } + + // O + freeMatrix(arr_a, m); + freeMatrix(arr_b, k1); + freeMatrix(arr_c, m); + + return 0; +} diff --git a/作業/unit1/matrix multiplication/by_me_2.o b/作業/unit1/matrix multiplication/by_me_2.o new file mode 100644 index 0000000..0ef738d Binary files /dev/null and b/作業/unit1/matrix multiplication/by_me_2.o differ diff --git a/作業/unit1/matrix multiplication/main.c b/作業/unit1/matrix multiplication/main.c new file mode 100644 index 0000000..8f8d4d8 --- /dev/null +++ b/作業/unit1/matrix multiplication/main.c @@ -0,0 +1,72 @@ +#include +#include + +void mul(int **a, int **b, int **c, int n) { + int i, j, k, sum; + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + sum = 0; + for (k = 0; k < n; k++) { + sum += a[i][k] * b[k][j]; + } + c[i][j] = sum; + } + } +} + +int main() { + int i, j, n = 2; + + int ary_a[2][2]={{1,2},{3,4}}; + int ary_b[2][2]={{5,6},{7,8}}; + + // ʺAtO鵹x} + int **arr_a = (int **)malloc(n * sizeof(int *)); + int **arr_b = (int **)malloc(n * sizeof(int *)); + int **arr_c = (int **)malloc(n * sizeof(int *)); + + if (arr_a == NULL || arr_b == NULL || arr_c == NULL) { + printf("Ot\n"); + return 1; + } + + for (i = 0; i < n; i++) { + arr_a[i] = (int *)malloc(n * sizeof(int)); + arr_b[i] = (int *)malloc(n * sizeof(int)); + arr_c[i] = (int *)malloc(n * sizeof(int)); + + if (arr_a[i] == NULL || arr_b[i] == NULL || arr_c[i] == NULL) { + printf("Ot\n"); + return 1; + } + } + + for (i = 0; i < 2; i++) { + for (j = 0; j < 2; j++) { + arr_a[i][j] = ary_a[i][j]; + arr_b[i][j] = ary_b[i][j]; + } + } + + // ix}k + mul(arr_a, arr_b, arr_c, n); + + // XG + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + printf("arr_c[%d][%d] = %d\n", i, j, arr_c[i][j]); + } + } + + // O + for (i = 0; i < n; i++) { + free(arr_a[i]); + free(arr_b[i]); + free(arr_c[i]); + } + free(arr_a); + free(arr_b); + free(arr_c); + + return 0; +} diff --git a/作業/unit1/matrix multiplication/main.exe b/作業/unit1/matrix multiplication/main.exe new file mode 100644 index 0000000..980b144 Binary files /dev/null and b/作業/unit1/matrix multiplication/main.exe differ diff --git a/作業/unit1/matrix multiplication/main.o b/作業/unit1/matrix multiplication/main.o new file mode 100644 index 0000000..46bfcb9 Binary files /dev/null and b/作業/unit1/matrix multiplication/main.o differ diff --git a/作業/unit1/matrix-product.c b/作業/unit1/matrix multiplication/matrix-product.c similarity index 100% rename from 作業/unit1/matrix-product.c rename to 作業/unit1/matrix multiplication/matrix-product.c diff --git a/作業/unit1/matrix multiplication/matrix-product.o b/作業/unit1/matrix multiplication/matrix-product.o new file mode 100644 index 0000000..d6cabd4 Binary files /dev/null and b/作業/unit1/matrix multiplication/matrix-product.o differ diff --git a/作業/unit1/matrix-multiplication/matrix_input.txt b/作業/unit1/matrix multiplication/matrix_input.txt similarity index 88% rename from 作業/unit1/matrix-multiplication/matrix_input.txt rename to 作業/unit1/matrix multiplication/matrix_input.txt index 48f0cc9..16cfc87 100644 --- a/作業/unit1/matrix-multiplication/matrix_input.txt +++ b/作業/unit1/matrix multiplication/matrix_input.txt @@ -1,5 +1,5 @@ 1 2 3 4 -5 6 7 8 +5 6 7 5 9 10 11 12 -1 -2 -3 diff --git a/作業/unit1/matrix multiplication/read_data_byme.c b/作業/unit1/matrix multiplication/read_data_byme.c new file mode 100644 index 0000000..b568394 --- /dev/null +++ b/作業/unit1/matrix multiplication/read_data_byme.c @@ -0,0 +1,21 @@ +#include +#include +#include + +define colMAX 100 +define rowMAX 100 + +int main(){ + int i , j ; + FILE *file; + char line; + if((file = fopen("matrix_input.txt","r"))==NULL){ + return 1 ; + } + fget(line,sizeof(line),file); + + + + + return 0; +} diff --git a/作業/unit1/matrix multiplication/read_matrix.c b/作業/unit1/matrix multiplication/read_matrix.c new file mode 100644 index 0000000..e19dfca --- /dev/null +++ b/作業/unit1/matrix multiplication/read_matrix.c @@ -0,0 +1,160 @@ +#include +#include +#include + +void mul(int **a, int **b, int **c, int m, int k, int n) { + int i , j , l ; + for (i = 0; i < m; i++) { + for (j = 0; j < n; j++) { + c[i][j] = 0; + for (l = 0; l < k; l++) { + c[i][j] += a[i][l] * b[l][j]; + } + } + } +} + +void read_matrix(FILE *file,int *m,int *k,int *n){ + char line[1000]; +// int *m = 0, *k1 = 0, *k2 = 0, *n = 0; + int *k1 , *k2; + int i, j, temp; + char *token; + + while (fgets(line, sizeof(line), file)) { + if (strlen(line) <= 1) { + break; + } + j = 0; + token = strtok(line, " \n"); + while (token != NULL) { + j++; + token = strtok(NULL, " \n"); + } + if (*k1 == 0) *k1 = j; + m++; + + } + // ŪĤGӯx} + while (fgets(line, sizeof(line), file)) { + j = 0; + token = strtok(line, " \n"); + while (token != NULL) { + j++; + token = strtok(NULL, " \n"); + } + if (*n == 0) *n = j; + k2++; + *k2 = k2; + } + printf("OK"); +// if (*k1!=*k2) return 1; +// if (*k1==*k2){ +} + +int main() { + FILE *file ; + + int *m , *k , *n ; + int i, j, temp; + char *token; + + if ((file = fopen("matrix_input.txt", "r")) == NULL){ + printf("Lk}\n"); + return 1; + } + + // ŪĤ@ӯx} +// while (fgets(line, sizeof(line), file)) { +// if (strlen(line) <= 1) { +// break; +// } +// j = 0; +// token = strtok(line, " \n"); +// while (token != NULL) { +// j++; +// token = strtok(NULL, " \n"); +// } +// if (k1 == 0) k1 = j; +// +// m++; +// } +// +// // ŪĤGӯx} +// while (fgets(line, sizeof(line), file)) { +// j = 0; +// token = strtok(line, " \n"); +// while (token != NULL) { +// j++; +// token = strtok(NULL, " \n"); +// } +// if (n == 0) n = j; +// k2++; +// } + + read_matrix(file,&m,&k,&n); + + printf("Ĥ@ӯx}: %d %d C\n", *m, *k); + printf("ĤGӯx}: %d %d C\n", *k, *n); + printf("m = %d, k1 = %d, k2 = %d, n = %d\n\n", *m, *k , *k , *n); + + + //ھm,k,ntmOŶ + int **arr_a = (int**)malloc(m * sizeof(int*)); + int **arr_b = (int**)malloc(k * sizeof(int*)); + int **arr_c = (int**)malloc(m * sizeof(int*)); + for(i=0;i +#include +#include + +#define MAX_LINE_LENGTH 1000 + +// tx}O +int** allocateMatrix(int rows, int cols) { + int i; + int** matrix = (int**)malloc(rows * sizeof(int*)); + for (i = 0; i < rows; i++) { + matrix[i] = (int*)malloc(cols * sizeof(int)); + } + return matrix; +} + +// x}O +void freeMatrix(int** matrix, int rows) { + int i ; + for (i = 0; i < rows; i++) { + free(matrix[i]); + } + free(matrix); +} + +// x}k +void mul(int **a, int **b, int **c, int m, int k, int n) { + int i , j , l ; + for (i = 0; i < m; i++) { + for (j = 0; j < n; j++) { + c[i][j] = 0; + for (l = 0; l < k; l++) { + c[i][j] += a[i][l] * b[l][j]; + } + } + } +} + +// Ūx}ê^ +int** readMatrix(FILE* file, int* rows, int* cols) { + char line[MAX_LINE_LENGTH]; + int** matrix = NULL; + *rows = 0; + *cols = 0; + + while (fgets(line, sizeof(line), file)) { + if (strlen(line) <= 1) break; // Ŧܯx} + + (*rows)++; + int tempCols = 0; + char* token = strtok(line, " \t\n"); + + while (token != NULL) { + tempCols++; + token = strtok(NULL, " \t\n"); + } + + if (*cols == 0) { + *cols = tempCols; + matrix = allocateMatrix(*rows, *cols); + } + + if (tempCols != *cols) { + printf("~Gx}CƤ@P\n"); + exit(1); + } + + // sŪӦæsxƾ + int col = 0; + token = strtok(line, " \t\n"); + while (token != NULL) { + matrix[*rows - 1][col++] = atoi(token); + token = strtok(NULL, " \t\n"); + } + } + + return matrix; +} + +int main() { + int i , j ; + FILE *file = fopen("matrix_input.txt", "r"); + if (file == NULL) { + printf("Lk}ɮ\n"); + return 1; + } + + int m, k1, k2, n; + int **arr_a, **arr_b, **arr_c; + + // ŪĤ@ӯx} + arr_a = readMatrix(file, &m, &k1); + + // ŪĤGӯx} + arr_b = readMatrix(file, &k2, &n); + + fclose(file); + + // ˬdx}O_iHۭ + if (k1 != k2) { + printf("~Goӯx}Lkۭ\n"); + freeMatrix(arr_a, m); + freeMatrix(arr_b, k2); + return 1; + } + + // tGx}Ŷ + arr_c = allocateMatrix(m, n); + + // x}k + mul(arr_a, arr_b, arr_c, m, k1, n); + + // XG + printf("x}kGG\n"); + for (i = 0; i < m; i++) { + for (j = 0; j < n; j++) { + printf("%d ", arr_c[i][j]); + } + printf("\n"); + } + + // O + freeMatrix(arr_a, m); + freeMatrix(arr_b, k1); + freeMatrix(arr_c, m); + + return 0; +} diff --git a/作業/unit1/matrix multiplication/test1.o b/作業/unit1/matrix multiplication/test1.o new file mode 100644 index 0000000..d0d9bf1 Binary files /dev/null and b/作業/unit1/matrix multiplication/test1.o differ diff --git a/作業/unit1/matrix multiplication/test2.c b/作業/unit1/matrix multiplication/test2.c new file mode 100644 index 0000000..f735b93 --- /dev/null +++ b/作業/unit1/matrix multiplication/test2.c @@ -0,0 +1,109 @@ +#include +#include +#include + +#define MAX_SIZE 10 /* wqx}̤jjp */ + +/* ơGŪx} */ +int readMatrix(int matrix[MAX_SIZE][MAX_SIZE], int *cols, FILE *file) { + int i = 0, j = 0, temp; + char ch; + + while (fscanf(file, "%d", &temp) == 1) { + matrix[i][j] = temp; + j++; + + /* ˬdeO_ */ + ch = fgetc(file); + if (ch == '\n') { + if (i == 0) { + *cols = j; // Ĥ@檺C + } + i++; /* U@ */ + j = 0; /* mCp */ + } + if (ch == EOF) break; + } + return i; /* ^ */ +} + +/* ơGLŦ */ +void skipEmptyLines(FILE *file) { + char ch; + while ((ch = fgetc(file)) != EOF) { + if (!isspace(ch) || ch == '\n') { + ungetc(ch, file); // NDťզrŰh^yAdzƤU@Ū + break; + } + } +} + +/* ơGLXx} */ +void printMatrix(int matrix[MAX_SIZE][MAX_SIZE], int rows, int cols) { + int i, j; + for (i = 0; i < rows; i++) { + for (j = 0; j < cols; j++) { + printf("%d ", matrix[i][j]); + } + printf("\n"); + } +} + +/* ơGx}k */ +void multiplyMatrix(int a[MAX_SIZE][MAX_SIZE], int b[MAX_SIZE][MAX_SIZE], int c[MAX_SIZE][MAX_SIZE], + int rowsA, int colsA, int colsB) { + int i, j, k; + for (i = 0; i < rowsA; i++) { + for (j = 0; j < colsB; j++) { + c[i][j] = 0; + for (k = 0; k < colsA; k++) { + c[i][j] += a[i][k] * b[k][j]; + } + } + } +} + +int main() { + FILE *file; + int matrixA[MAX_SIZE][MAX_SIZE] = {0}, matrixB[MAX_SIZE][MAX_SIZE] = {0}, result[MAX_SIZE][MAX_SIZE] = {0}; + int rowsA = 0, colsA = 0, rowsB = 0, colsB = 0; + + /* }ɮ */ + file = fopen("matrix_input.txt", "r"); + if (file == NULL) { + printf("Lk}ɮ\n"); + return 1; + } + + /* Ūx} A */ + rowsA = readMatrix(matrixA, &colsA, file); + + /* LŦ */ + skipEmptyLines(file); + + /* Ūx} B */ + rowsB = readMatrix(matrixB, &colsB, file); + + /* ɮ */ + fclose(file); + + /* LXx}jp */ + printf("x} A: %d x %d\n", rowsA, colsA); + printf("x} B: %d x %d\n", rowsB, colsB); + + /* ˬdx}O_iHۭ */ + if (colsA != rowsB) { + printf("~Goӯx}Lkۭ\n"); + return 1; + } + + /* x}k */ + multiplyMatrix(matrixA, matrixB, result, rowsA, colsA, colsB); + + /* LXG */ + printf("x}kGG\n"); + printMatrix(result, rowsA, colsB); + + return 0; +} + diff --git a/作業/unit1/matrix multiplication/test2.o b/作業/unit1/matrix multiplication/test2.o new file mode 100644 index 0000000..e286f52 Binary files /dev/null and b/作業/unit1/matrix multiplication/test2.o differ diff --git a/作業/unit1/matrix-multiplication/matrix-multiplication.c b/作業/unit1/matrix multiplication/test3.c similarity index 98% rename from 作業/unit1/matrix-multiplication/matrix-multiplication.c rename to 作業/unit1/matrix multiplication/test3.c index 4b14e19..25126d8 100644 --- a/作業/unit1/matrix-multiplication/matrix-multiplication.c +++ b/作業/unit1/matrix multiplication/test3.c @@ -111,8 +111,8 @@ int main() { read_matrix(file, arr_b, k, n); mul(arr_a, arr_b, arr_c, m, k, n); - - printf("x}ۭGG\n"); + + printf("Gx}G\n"); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { printf("%d ", arr_c[i][j]); @@ -132,6 +132,6 @@ int main() { for (i = 0; i < k; i++) { free(arr_b[i]); } - system("pause"); + return 0; } diff --git a/作業/unit1/matrix multiplication/test3.exe b/作業/unit1/matrix multiplication/test3.exe new file mode 100644 index 0000000..0416f1e Binary files /dev/null and b/作業/unit1/matrix multiplication/test3.exe differ diff --git a/作業/unit1/matrix multiplication/test3.o b/作業/unit1/matrix multiplication/test3.o new file mode 100644 index 0000000..0dedeb6 Binary files /dev/null and b/作業/unit1/matrix multiplication/test3.o differ diff --git a/作業/unit1/matrix-multiplication.zip b/作業/unit1/matrix-multiplication.zip deleted file mode 100644 index 4b48eb5..0000000 Binary files a/作業/unit1/matrix-multiplication.zip and /dev/null differ diff --git a/作業/unit1/停機問題.docx b/作業/unit1/停機問題.docx deleted file mode 100644 index dc8ffe2..0000000 Binary files a/作業/unit1/停機問題.docx and /dev/null differ diff --git a/作業/unit12/.vscode/c_cpp_properties.json b/作業/unit12/.vscode/c_cpp_properties.json new file mode 100644 index 0000000..cea4d3f --- /dev/null +++ b/作業/unit12/.vscode/c_cpp_properties.json @@ -0,0 +1,18 @@ +{ + "configurations": [ + { + "name": "windows-gcc-x64", + "includePath": [ + "${workspaceFolder}/**" + ], + "compilerPath": "gcc", + "cStandard": "${default}", + "cppStandard": "${default}", + "intelliSenseMode": "windows-gcc-x64", + "compilerArgs": [ + "" + ] + } + ], + "version": 4 +} \ No newline at end of file diff --git a/作業/unit12/.vscode/launch.json b/作業/unit12/.vscode/launch.json new file mode 100644 index 0000000..373bd65 --- /dev/null +++ b/作業/unit12/.vscode/launch.json @@ -0,0 +1,24 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "C/C++ Runner: Debug Session", + "type": "cppdbg", + "request": "launch", + "args": [], + "stopAtEntry": false, + "externalConsole": true, + "cwd": "e:/code/C++/unit12", + "program": "e:/code/C++/unit12/build/Debug/outDebug", + "MIMode": "gdb", + "miDebuggerPath": "gdb", + "setupCommands": [ + { + "description": "Enable pretty-printing for gdb", + "text": "-enable-pretty-printing", + "ignoreFailures": true + } + ] + } + ] +} \ No newline at end of file diff --git a/作業/unit12/.vscode/settings.json b/作業/unit12/.vscode/settings.json new file mode 100644 index 0000000..c9e66f1 --- /dev/null +++ b/作業/unit12/.vscode/settings.json @@ -0,0 +1,59 @@ +{ + "C_Cpp_Runner.cCompilerPath": "gcc", + "C_Cpp_Runner.cppCompilerPath": "g++", + "C_Cpp_Runner.debuggerPath": "gdb", + "C_Cpp_Runner.cStandard": "", + "C_Cpp_Runner.cppStandard": "", + "C_Cpp_Runner.msvcBatchPath": "C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Auxiliary/Build/vcvarsall.bat", + "C_Cpp_Runner.useMsvc": false, + "C_Cpp_Runner.warnings": [ + "-Wall", + "-Wextra", + "-Wpedantic", + "-Wshadow", + "-Wformat=2", + "-Wcast-align", + "-Wconversion", + "-Wsign-conversion", + "-Wnull-dereference" + ], + "C_Cpp_Runner.msvcWarnings": [ + "/W4", + "/permissive-", + "/w14242", + "/w14287", + "/w14296", + "/w14311", + "/w14826", + "/w44062", + "/w44242", + "/w14905", + "/w14906", + "/w14263", + "/w44265", + "/w14928" + ], + "C_Cpp_Runner.enableWarnings": true, + "C_Cpp_Runner.warningsAsError": false, + "C_Cpp_Runner.compilerArgs": [], + "C_Cpp_Runner.linkerArgs": [], + "C_Cpp_Runner.includePaths": [], + "C_Cpp_Runner.includeSearch": [ + "*", + "**/*" + ], + "C_Cpp_Runner.excludeSearch": [ + "**/build", + "**/build/**", + "**/.*", + "**/.*/**", + "**/.vscode", + "**/.vscode/**" + ], + "C_Cpp_Runner.useAddressSanitizer": false, + "C_Cpp_Runner.useUndefinedSanitizer": false, + "C_Cpp_Runner.useLeakSanitizer": false, + "C_Cpp_Runner.showCompilationTime": false, + "C_Cpp_Runner.useLinkTimeOptimization": false, + "C_Cpp_Runner.msvcSecureNoWarnings": false +} \ No newline at end of file diff --git a/作業/unit12/DS7.cpp b/作業/unit12/DS7.cpp new file mode 100644 index 0000000..d75c2ee --- /dev/null +++ b/作業/unit12/DS7.cpp @@ -0,0 +1,135 @@ +#include +#include +#include + +#define MAX_V 100 /*̤j`I*/ +#define Infinite 1073741823 + +long int dist[MAX_V+1][MAX_V+1]; +int N; // `Iƶq +int source, sink; // _IMI + +void init(); +bool floydWarshall(); +void output_path(); +void output_step(); + +int main() { + + init(); + + // ˬdO_sbtvj + if (floydWarshall()) { + output_path(); + printf("\nϧΤsbtvjALkp̵u|\n"); + } else { + output_path(); + } + + return 0; +} + +void init(){ + FILE *fptr; + int i, j, weight; + + fptr = fopen("shortestPath.dat", "r"); + if (fptr == NULL) { + perror("shortestPath.dat"); + exit(1); + } + + fscanf(fptr, "%d", &N); // Ūϧθ`I + + // lƶZx} + for (i = 1; i <= N; i++) { + for (j = 1; j <= N; j++) { + if (i == j) + dist[i][j] = 0; // ۨۨZ0 + else + dist[i][j] = Infinite; // Lw]Laj + } + } + + // Ū䪺v + while (fscanf(fptr, "%d %d %d", &i, &j, &weight) != EOF) + dist[i][j] = weight; // ]m۳s䪺v + + + fclose(fptr); + printf("ɮפvpU\n"); + output_step(); + + printf("\nJ_l`I (1~%d): ", N); + scanf("%d", &source); + printf("Jؼи`I (1~%d): ", N); + scanf("%d", &sink); +} + +bool floydWarshall(){ + int k, i, j; + + // Floyd Warshall ֤ߺtk + for (k = 1; k <= N; k++) { + for (i = 1; i <= N; i++) { + for (j = 1; j <= N; j++) { + // pGgL k I|񪽱|uAsZ + if (dist[i][k] != Infinite && + dist[k][j] != Infinite && + dist[i][k] + dist[k][j] < dist[i][j]) { + dist[i][j] = dist[i][k] + dist[k][j]; + } + } + } + } + + // ˬdO_sbtvj + for (i = 1; i <= N; i++) { + if (dist[i][i] < 0) { + return true; // sbtvj + } + } + + return false; // sbt +} + + +void output_step(){ + int i, j; + + // XDC + printf("\t"); + for (j = 1; j <= N; j++) { + printf("V%d\t", j); + } + printf("\n"); + + // XZx} + for (i = 1; i <= N; i++) { + printf("V%d\t", i); + for (j = 1; j <= N; j++) { + if (dist[i][j] == Infinite) + printf("\t"); + else + printf("%2ld\t", dist[i][j]); + } + printf("\n"); + } +} + +void output_path(){ + int i, j; + + // XDC + printf("\n`I̵uZx}G\n"); + + output_step(); + + // ˬd_II| + if (dist[source][sink] == Infinite) { + printf("\n`I V%d `I V%d S|\n", source, sink); + } else { + printf("\nq`I V%d `I V%d ̵uZG%ld\n", + source, sink, dist[source][sink]); + } +} diff --git a/作業/unit12/DS7.exe b/作業/unit12/DS7.exe new file mode 100644 index 0000000..c71532c Binary files /dev/null and b/作業/unit12/DS7.exe differ diff --git a/作業/unit12/DS7.zip b/作業/unit12/DS7.zip new file mode 100644 index 0000000..b0f7a53 Binary files /dev/null and b/作業/unit12/DS7.zip differ diff --git a/作業/unit12/DS7/DS7.cpp b/作業/unit12/DS7/DS7.cpp new file mode 100644 index 0000000..4e19c05 --- /dev/null +++ b/作業/unit12/DS7/DS7.cpp @@ -0,0 +1,131 @@ +#include +#include + +#define MAX_V 100 /*̤j`I*/ +#define Infinite 1073741823 + +long int dist[MAX_V+1][MAX_V+1]; +int N; // `Iƶq +int source, sink; // _IMI + +void init(); +int floydWarshall(); +void output_path(); +void output_step(); + +int main() { + + init(); + + // ˬdO_sbtvj + if (floydWarshall()) { + output_path(); + printf("\nϧΤsbtvjALkp̵u|\n"); + } else { + output_path(); + } + + return 0; +} + +void init(){ + FILE *fptr; + int i, j, weight; + + fptr = fopen("shortestPath.dat", "r"); + if (fptr == NULL) { + perror("shortestPath.dat"); + exit(1); + } + + fscanf(fptr, "%d", &N); // Ūϧθ`I + + // lƶZx} + for (i = 1; i <= N; i++) { + for (j = 1; j <= N; j++) { + if (i == j) + dist[i][j] = 0; // ۨۨZ0 + else + dist[i][j] = Infinite; // Lw]Laj + } + } + + // Ū䪺v + while (fscanf(fptr, "%d %d %d", &i, &j, &weight) != EOF) + dist[i][j] = weight; // ]m۳s䪺v + + fclose(fptr); + printf("ɮפvpU\n"); + output_step(); + + printf("\nJ_l`I (1~%d): ", N); + scanf("%d", &source); + printf("Jؼи`I (1~%d): ", N); + scanf("%d", &sink); +} + +int floydWarshall(){ + int k, i, j; + + for (k = 1; k <= N; k++) { + for (i = 1; i <= N; i++) { + for (j = 1; j <= N; j++) { + // pGgL k I|񪽱|uAsZ + if (dist[i][k] != Infinite && + dist[k][j] != Infinite && + dist[i][k] + dist[k][j] < dist[i][j]) { + dist[i][j] = dist[i][k] + dist[k][j]; + } + } + } + } + + // ˬdO_sbtvj + for (i = 1; i <= N; i++) { + if (dist[i][i] < 0) { + return 1; // sbtvj + } + } + + return 0; // sbtvj +} + + +void output_step(){ + int i, j; + + printf("\t"); + for (j = 1; j <= N; j++) { + printf("V%d\t", j); + } + printf("\n"); + + // XZx} + for (i = 1; i <= N; i++) { + printf("V%d\t", i); + for (j = 1; j <= N; j++) { + if (dist[i][j] == Infinite) + printf("\t"); + else + printf("%2ld\t", dist[i][j]); + } + printf("\n"); + } +} + +void output_path(){ + int i, j; + + // XDC + printf("\n`I̵uZx}G\n"); + + output_step(); + + // ˬd_II| + if (dist[source][sink] == Infinite) { + printf("\n`I V%d `I V%d S|\n", source, sink); + } else { + printf("\nq`I V%d `I V%d ̵uZG%ld\n", + source, sink, dist[source][sink]); + } +} diff --git a/作業/unit12/DS7/shortestPath.dat b/作業/unit12/DS7/shortestPath.dat new file mode 100644 index 0000000..fcb6ad8 --- /dev/null +++ b/作業/unit12/DS7/shortestPath.dat @@ -0,0 +1,13 @@ +7 +1 2 4 +1 3 6 +1 4 6 +2 3 1 +2 5 7 +3 5 6 +3 6 4 +4 3 2 +4 6 5 +5 7 6 +6 5 1 +6 7 8 diff --git a/作業/unit12/DS7/shortestPath_1.dat b/作業/unit12/DS7/shortestPath_1.dat new file mode 100644 index 0000000..b378f5b --- /dev/null +++ b/作業/unit12/DS7/shortestPath_1.dat @@ -0,0 +1,25 @@ +7 +1 2 4 +1 3 6 +1 4 6 +2 3 1 +2 5 7 +3 5 6 +3 6 4 +4 3 2 +4 6 5 +5 7 -6 +6 5 1 +6 7 8 +2 1 4 +3 1 6 +4 1 6 +3 2 1 +3 4 2 +5 2 7 +5 3 6 +5 6 1 +6 4 5 +6 3 4 +7 5 6 +7 6 8 diff --git a/作業/unit12/DS7/shortestPath_2.dat b/作業/unit12/DS7/shortestPath_2.dat new file mode 100644 index 0000000..24e4e93 --- /dev/null +++ b/作業/unit12/DS7/shortestPath_2.dat @@ -0,0 +1,15 @@ +8 +1 2 1 +1 3 3 +2 3 1 +2 5 3 +2 4 5 +3 5 1 +3 6 4 +4 5 3 +4 7 8 +5 6 4 +5 7 7 +6 8 7 +7 6 6 +7 8 2 diff --git a/作業/unit12/DS7_down.cpp b/作業/unit12/DS7_down.cpp new file mode 100644 index 0000000..7b14042 --- /dev/null +++ b/作業/unit12/DS7_down.cpp @@ -0,0 +1,186 @@ +#include +#include +#include + +#define MAX_V 100 /*̤j`I*/ +#define Infinite 1073741823 + +long int dist[MAX_V+1][MAX_V+1]; +int path[MAX_V+1][MAX_V+1]; // lܸ|x} +int N; // `Iƶq +int source, sink; // _IMI + +void init(); +bool floydWarshall(); +void output_path(); +void output_step(); +void print_path(int start, int end); + +int main() { + init(); + + // ˬdO_sbtvj + if (floydWarshall()) { + printf("\nĵiGϧΤsbtvjAp⵲GiणTI\n"); + output_path(); + } else { + output_path(); + } + + return 0; +} + +void init(){ + FILE *fptr; + int i, j, weight,line_count=0; + char line[256]; + + fptr = fopen("shortestPath_down_1.dat", "r"); + if (fptr == NULL) { + perror("shortestPath_up_1.dat"); + exit(1); + } + + // p`I + while (fgets(line, sizeof(line), fptr)) { + line_count++; + } + N = line_count; + rewind(fptr); + + // lƶZx}P|x} + for (i = 1; i <= N; i++) { + for (j = 1; j <= N; j++) { + if (i == j) { + dist[i][j] = 0; + path[i][j] = i; + } else { + dist[i][j] = Infinite; + path[i][j] = -1; + } + } + } + + // ŪUTx} + for (i = 1; i <= N; i++) { + for (j = 1; j < i; j++) { + if (fscanf(fptr, "%d", &weight) == 1) { + if (weight != 0) { // uBzDsv + dist[i][j] = weight; + path[i][j] = i; + // ]OLVϡAҥH٦m]n]w + if (i != j) { + dist[j][i] = weight; + path[j][i] = j; + } + } + } + } + // LӦѾlr + fgets(line, sizeof(line), fptr); + } + + fclose(fptr); + printf("ɮפvpU\n"); + output_step(); + + printf("\nJ_l`I (1~%d): ", N); + scanf("%d", &source); + printf("Jؼи`I (1~%d): ", N); + scanf("%d", &sink); +} + +bool floydWarshall(){ + int k, i, j; + bool has_negative_cycle = false; + long int temp_dist[MAX_V+1][MAX_V+1]; + + // Dn Floyd-Warshall tk + for (k = 1; k <= N; k++) { + for (i = 1; i <= N; i++) { + for (j = 1; j <= N; j++) { + if (dist[i][k] != Infinite && + dist[k][j] != Infinite && + dist[i][k] + dist[k][j] < dist[i][j]) { + dist[i][j] = dist[i][k] + dist[k][j]; + path[i][j] = path[k][j]; + } + } + } + } + + // ƻsثeZx} + for (i = 1; i <= N; i++) { + for (j = 1; j <= N; j++) { + temp_dist[i][j] = dist[i][j]; + } + } + + // A@Nˬdtvj + for (k = 1; k <= N; k++) { + for (i = 1; i <= N; i++) { + for (j = 1; j <= N; j++) { + if (dist[i][k] != Infinite && + dist[k][j] != Infinite && + dist[i][k] + dist[k][j] < temp_dist[i][j]) { + has_negative_cycle = true; + goto end_check; // tvj᪽X + } + } + } + } + +end_check: + return has_negative_cycle; +} + +void print_path(int start, int end) { + if (start == end) { + printf("I%d", start); + return; + } + if (path[start][end] == -1) { + printf("L|"); + return; + } + print_path(start, path[start][end]); + printf(" %d", end); +} + +void output_step(){ + int i, j; + + printf("\t"); + for (j = 1; j <= N; j++) { + printf("V%d\t", j); + } + printf("\n"); + + for (i = 1; i <= N; i++) { + printf("V%d\t", i); + for (j = 1; j <= N; j++) { + if (dist[i][j] == Infinite) + printf("\t"); + else + printf("%2ld\t", dist[i][j]); + } + printf("\n"); + } +} + +void output_path(){ + int i, j; + + printf("\n`I̵uZx}G\n"); + output_step(); + + if (dist[source][sink] == Infinite) { + printf("\n`I V%d `I V%d S|\n", source, sink); + } else { + printf("\nq`I V%d `I V%d ̵uZG%ld\n", + source, sink, dist[source][sink]); + printf("̵u|G"); + print_path(source, sink); + printf("\n"); + } +} diff --git a/作業/unit12/DS7_down.exe b/作業/unit12/DS7_down.exe new file mode 100644 index 0000000..6a79e2e Binary files /dev/null and b/作業/unit12/DS7_down.exe differ diff --git a/作業/unit12/DS7_matrix.cpp b/作業/unit12/DS7_matrix.cpp new file mode 100644 index 0000000..b1a53be --- /dev/null +++ b/作業/unit12/DS7_matrix.cpp @@ -0,0 +1,179 @@ +#include +#include +#include + +#define MAX_V 100 /*̤j`I*/ +#define Infinite 1073741823 + +long int dist[MAX_V+1][MAX_V+1]; +int path[MAX_V+1][MAX_V+1]; // lܸ|x} +int N; // `Iƶq +int source, sink; // _IMI + +void init(); +bool floydWarshall(); +void output_path(); +void output_step(); +void print_path(int start, int end); + +int main() { + init(); + + // ˬdO_sbtvj + if (floydWarshall()) { + printf("\nĵiGϧΤsbtvjAp⵲GiणTI\n"); + output_path(); + } else { + output_path(); + } + + return 0; +} + +void init() { + FILE *fptr; + int i, j, weight, line_count = 0; + char line[256]; + + fptr = fopen("shortestPath_matrix.dat", "r"); + if (fptr == NULL) { + perror("shortestPath_matrix.dat"); + exit(1); + } + + // p`I + while (fgets(line, sizeof(line), fptr)) { + line_count++; + } + N = line_count; + rewind(fptr); + + // lƶZx}P|x} + for (i = 1; i <= N; i++) { + for (j = 1; j <= N; j++) { + if (i == j) { + dist[i][j] = 0; + path[i][j] = i; + } else { + dist[i][j] = Infinite; + path[i][j] = -1; + } + } + } + + // Ūx} + for (i = 1; i <= N; i++) { + for (j = 1; j <= N; j++) { + if (fscanf(fptr, "%d", &weight) == 1) { + if (weight != 0 && i != j) { // uBzDsBD﨤uv + dist[i][j] = weight; + path[i][j] = i; + } + } + } + } + + fclose(fptr); + printf("ɮפvpU\n"); + output_step(); + + printf("\nJ_l`I (1~%d): ", N); + scanf("%d", &source); + printf("Jؼи`I (1~%d): ", N); + scanf("%d", &sink); +} + +bool floydWarshall(){ + int k, i, j; + bool has_negative_cycle = false; + long int temp_dist[MAX_V+1][MAX_V+1]; + + // Dn Floyd-Warshall tk + for (k = 1; k <= N; k++) { + for (i = 1; i <= N; i++) { + for (j = 1; j <= N; j++) { + if (dist[i][k] != Infinite && + dist[k][j] != Infinite && + dist[i][k] + dist[k][j] < dist[i][j]) { + dist[i][j] = dist[i][k] + dist[k][j]; + path[i][j] = path[k][j]; + } + } + } + } + + // ƻsثeZx} + for (i = 1; i <= N; i++) { + for (j = 1; j <= N; j++) { + temp_dist[i][j] = dist[i][j]; + } + } + + // A@Nˬdtvj + for (k = 1; k <= N; k++) { + for (i = 1; i <= N; i++) { + for (j = 1; j <= N; j++) { + if (dist[i][k] != Infinite && + dist[k][j] != Infinite && + dist[i][k] + dist[k][j] < temp_dist[i][j]) { + has_negative_cycle = true; + goto end_check; // tvj᪽X + } + } + } + } + +end_check: + return has_negative_cycle; +} + +void print_path(int start, int end) { + if (start == end) { + printf("I%d", start); + return; + } + if (path[start][end] == -1) { + printf("L|"); + return; + } + print_path(start, path[start][end]); + printf(" %d", end); +} + +void output_step(){ + int i, j; + + printf("\t"); + for (j = 1; j <= N; j++) { + printf("V%d\t", j); + } + printf("\n"); + + for (i = 1; i <= N; i++) { + printf("V%d\t", i); + for (j = 1; j <= N; j++) { + if (dist[i][j] == Infinite) + printf("\t"); + else + printf("%2ld\t", dist[i][j]); + } + printf("\n"); + } +} + +void output_path(){ + int i, j; + + printf("\n`I̵uZx}G\n"); + output_step(); + + if (dist[source][sink] == Infinite) { + printf("\n`I V%d `I V%d S|\n", source, sink); + } else { + printf("\nq`I V%d `I V%d ̵uZG%ld\n", + source, sink, dist[source][sink]); + printf("̵u|G"); + print_path(source, sink); + printf("\n"); + } +} diff --git a/作業/unit12/DS7_matrix.exe b/作業/unit12/DS7_matrix.exe new file mode 100644 index 0000000..49dddb6 Binary files /dev/null and b/作業/unit12/DS7_matrix.exe differ diff --git a/作業/unit12/DS7_new.cpp b/作業/unit12/DS7_new.cpp new file mode 100644 index 0000000..3a64f14 --- /dev/null +++ b/作業/unit12/DS7_new.cpp @@ -0,0 +1,167 @@ +#include +#include +#include + +#define MAX_V 100 /*̤j`I*/ +#define Infinite 1073741823 + +long int dist[MAX_V+1][MAX_V+1]; +int path[MAX_V+1][MAX_V+1]; // lܸ|x} +int N; // `Iƶq +int source, sink; // _IMI + +void init(); +bool floydWarshall(); +void output_path(); +void output_step(); +void print_path(int start, int end); + +int main() { + init(); + + // ˬdO_sbtvj + if (floydWarshall()) { + printf("\nĵiGϧΤsbtvjAp⵲GiणTI\n"); + output_step(); +// output_path(); + } else { + output_path(); + } + + return 0; +} + +void init(){ + FILE *fptr; + int i, j, weight; + + fptr = fopen("shortestPath.dat", "r"); + if (fptr == NULL) { + perror("shortestPath.dat"); + exit(1); + } + + fscanf(fptr, "%d", &N); // Ūϧθ`I + + // lƶZx}P|x} + for (i = 1; i <= N; i++) { + for (j = 1; j <= N; j++) { + if (i == j) { + dist[i][j] = 0; + path[i][j] = i; + } else { + dist[i][j] = Infinite; + path[i][j] = -1; + } + } + } + + while (fscanf(fptr, "%d %d %d", &i, &j, &weight) != EOF) { + dist[i][j] = weight; + path[i][j] = i; + } + + fclose(fptr); + printf("ɮפvpU\n"); + output_step(); + + printf("\nJ_l`I (1~%d): ", N); + scanf("%d", &source); + printf("Jؼи`I (1~%d): ", N); + scanf("%d", &sink); +} + +bool floydWarshall(){ + int k, i, j; + bool has_negative_cycle = false; + long int temp_dist[MAX_V+1][MAX_V+1]; + + // Dn Floyd-Warshall tk + for (k = 1; k <= N; k++) { + for (i = 1; i <= N; i++) { + for (j = 1; j <= N; j++) { + if (dist[i][k] != Infinite && + dist[k][j] != Infinite && + dist[i][k] + dist[k][j] < dist[i][j]) { + dist[i][j] = dist[i][k] + dist[k][j]; + path[i][j] = path[k][j]; + } + } + } + } + + // ƻsثeZx} + for (i = 1; i <= N; i++) { + for (j = 1; j <= N; j++) { + temp_dist[i][j] = dist[i][j]; + } + } + + // A@Nˬdtvj + for (k = 1; k <= N; k++) { + for (i = 1; i <= N; i++) { + for (j = 1; j <= N; j++) { + if (dist[i][k] != Infinite && + dist[k][j] != Infinite && + dist[i][k] + dist[k][j] < temp_dist[i][j]) { + has_negative_cycle = true; + goto end_check; // tvj᪽X + } + } + } + } + +end_check: + return has_negative_cycle; +} + +void print_path(int start, int end) { + if (start == end) { + printf("I%d", start); + return; + } + if (path[start][end] == -1) { + printf("L|"); + return; + } + print_path(start, path[start][end]); + printf(" %d", end); +} + +void output_step(){ + int i, j; + + printf("\t"); + for (j = 1; j <= N; j++) { + printf("V%d\t", j); + } + printf("\n"); + + for (i = 1; i <= N; i++) { + printf("V%d\t", i); + for (j = 1; j <= N; j++) { + if (dist[i][j] == Infinite) + printf("\t"); + else + printf("%2ld\t", dist[i][j]); + } + printf("\n"); + } +} + +void output_path(){ + int i, j; + + printf("\n`I̵uZx}G\n"); + output_step(); + + if (dist[source][sink] == Infinite) { + printf("\n`I V%d `I V%d S|\n", source, sink); + } else { + printf("\nq`I V%d `I V%d ̵uZG%ld\n", + source, sink, dist[source][sink]); + printf("̵u|G"); + print_path(source, sink); + printf("\n"); + } +} diff --git a/作業/unit12/DS7_new.exe b/作業/unit12/DS7_new.exe new file mode 100644 index 0000000..5eb2ee3 Binary files /dev/null and b/作業/unit12/DS7_new.exe differ diff --git a/作業/unit12/DS7_up.cpp b/作業/unit12/DS7_up.cpp new file mode 100644 index 0000000..0b252b6 --- /dev/null +++ b/作業/unit12/DS7_up.cpp @@ -0,0 +1,186 @@ +#include +#include +#include + +#define MAX_V 100 /*̤j`I*/ +#define Infinite 1073741823 + +long int dist[MAX_V+1][MAX_V+1]; +int path[MAX_V+1][MAX_V+1]; // lܸ|x} +int N; // `Iƶq +int source, sink; // _IMI + +void init(); +bool floydWarshall(); +void output_path(); +void output_step(); +void print_path(int start, int end); + +int main() { + init(); + + // ˬdO_sbtvj + if (floydWarshall()) { + printf("\nĵiGϧΤsbtvjAp⵲GiणTI\n"); + output_path(); + } else { + output_path(); + } + + return 0; +} + +void init(){ + FILE *fptr; + int i, j, weight,line_count=0; + char line[256]; + + fptr = fopen("shortestPath_up_1.dat", "r"); + if (fptr == NULL) { + perror("shortestPath_up_1.dat"); + exit(1); + } + + // p`I + while (fgets(line, sizeof(line), fptr)) { + line_count++; + } + N = line_count; + rewind(fptr); + + // lƶZx}P|x} + for (i = 1; i <= N; i++) { + for (j = 1; j <= N; j++) { + if (i == j) { + dist[i][j] = 0; + path[i][j] = i; + } else { + dist[i][j] = Infinite; + path[i][j] = -1; + } + } + } + + // ŪWTx} + for (i = 1; i <= N; i++) { + for (j = i; j <= N; j++) { + if (fscanf(fptr, "%d", &weight) == 1) { + if (weight != 0) { // uBzDsv + dist[i][j] = weight; + path[i][j] = i; + // ]OLVϡAҥH٦m]n]w + if (i != j) { + dist[j][i] = weight; + path[j][i] = j; + } + } + } + } + // LӦѾlr + fgets(line, sizeof(line), fptr); + } + + fclose(fptr); + printf("ɮפvpU\n"); + output_step(); + + printf("\nJ_l`I (1~%d): ", N); + scanf("%d", &source); + printf("Jؼи`I (1~%d): ", N); + scanf("%d", &sink); +} + +bool floydWarshall(){ + int k, i, j; + bool has_negative_cycle = false; + long int temp_dist[MAX_V+1][MAX_V+1]; + + // Dn Floyd-Warshall tk + for (k = 1; k <= N; k++) { + for (i = 1; i <= N; i++) { + for (j = 1; j <= N; j++) { + if (dist[i][k] != Infinite && + dist[k][j] != Infinite && + dist[i][k] + dist[k][j] < dist[i][j]) { + dist[i][j] = dist[i][k] + dist[k][j]; + path[i][j] = path[k][j]; + } + } + } + } + + // ƻsثeZx} + for (i = 1; i <= N; i++) { + for (j = 1; j <= N; j++) { + temp_dist[i][j] = dist[i][j]; + } + } + + // A@Nˬdtvj + for (k = 1; k <= N; k++) { + for (i = 1; i <= N; i++) { + for (j = 1; j <= N; j++) { + if (dist[i][k] != Infinite && + dist[k][j] != Infinite && + dist[i][k] + dist[k][j] < temp_dist[i][j]) { + has_negative_cycle = true; + goto end_check; // tvj᪽X + } + } + } + } + +end_check: + return has_negative_cycle; +} + +void print_path(int start, int end) { + if (start == end) { + printf("I%d", start); + return; + } + if (path[start][end] == -1) { + printf("L|"); + return; + } + print_path(start, path[start][end]); + printf(" %d", end); +} + +void output_step(){ + int i, j; + + printf("\t"); + for (j = 1; j <= N; j++) { + printf("V%d\t", j); + } + printf("\n"); + + for (i = 1; i <= N; i++) { + printf("V%d\t", i); + for (j = 1; j <= N; j++) { + if (dist[i][j] == Infinite) + printf("\t"); + else + printf("%2ld\t", dist[i][j]); + } + printf("\n"); + } +} + +void output_path(){ + int i, j; + + printf("\n`I̵uZx}G\n"); + output_step(); + + if (dist[source][sink] == Infinite) { + printf("\n`I V%d `I V%d S|\n", source, sink); + } else { + printf("\nq`I V%d `I V%d ̵uZG%ld\n", + source, sink, dist[source][sink]); + printf("̵u|G"); + print_path(source, sink); + printf("\n"); + } +} diff --git a/作業/unit12/DS7_up.exe b/作業/unit12/DS7_up.exe new file mode 100644 index 0000000..78a4748 Binary files /dev/null and b/作業/unit12/DS7_up.exe differ diff --git a/作業/unit12/all-pairs-shortest-path-v1.c b/作業/unit12/all-pairs-shortest-path-v1.c deleted file mode 100644 index 57e7ccd..0000000 --- a/作業/unit12/all-pairs-shortest-path-v1.c +++ /dev/null @@ -1,135 +0,0 @@ -/* -Program: all-pairs-shortest-path-v1.c (Report comments/bugs to chikh@yuntech.edu.tw) -Function: @Floyd-WarshalltkAHѪshortestPath.datɮק@J -Notes: - 1) Floyd-WarshalltkuʺAWv(dynamic programming)k - 2) ŪƩҥε{XۮѪshortestPath.cվ禡쫬(prototype)BץΥܼ - 3) Ѧ https://www.geeksforgeeks.org/floyd-warshall-algorithm-dp-16/ - P https://www.programiz.com/dsa/floyd-warshall-algorithm -*/ - -#include -#include /* for exit() */ - -#define MAX_V 100 /* ̤jI */ -#define Inf 1073741823 /* 2^30-1jƦrA{]LjȡFilimits.hwqINT_MAX */ - -void init(int A[][MAX_V], int Y[][MAX_V], int *N) /* ŪJɡB]w۾Fx}AƵc@l */ -{ - FILE *fptr; - int i, j; - int weight; - - if ((fptr=fopen("shortestPath.dat","r")) == NULL) { /* }Ҹ */ - perror("shortestPath.dat"); - exit(1); - } - - fscanf(fptr,"%d",N); /* Ūϧθ`I */ - for (i = 1; i <= *N; i++ ) - for (j = 1; j <= *N; j++) { - A[i][j] = (i==j)? 0: Inf; /* lA[1..N][1..N]۾Fx}AҦw] */ - Y[i][j] = (i==j)? i: -1; - } - - while (fscanf(fptr,"%d %d %d",&i,&j,&weight) != EOF) { - A[i][j] = weight; /* ŪsIiPj䪺v */ - Y[i][j] = i; /* Y[i][j]w]i */ - } - - fclose(fptr); -} - -/* UfloydWarshall()禡NCGI(i,j)p̵uZȡAðOigѭǤ~IF̵u */ -void floydWarshall(int A[][MAX_V], int Y[][MAX_V], int N) -{ - int i, j, k; - - for (k = 1; k <= N; k++) - for (i = 1; i < N; i++) - for (j = 1; j <= N; j++) - if (A[i][k] + A[k][j] < A[i][j]) { //if (A[i][k] != Inf && A[k][j] != Inf && A[i][k] + A[k][j] < A[i][j]) { - A[i][j] = A[i][k] + A[k][j]; - Y[i][j] = Y[k][j]; /* g Y[i][j] = k */ - } - /* WGhforjΩץCGI(i,j)ZȡA˵_gk(@ӥi઺~I)opZ */ - /* - dNline 53gkAg Y[i][j] = kAPǥiϤtO?! - zѡGline 37iAYGI(i,j)sbANY[i][j]w]iC - ]Abline 53AYkPjsbAgY[k][j]PgkNqۦPANje~IkC - YkPjLsAh]Y[i][j] = Y[k][j]ANij̫@Ӥ~INѱqkj|ҰO̫ - @Ӥ~IMw(Y[k][j]ثeҪkjZj̪񪺤~I)C - zLline 53]mYx}eANi^o̵u| - */ -} - -void printMatrix(int A[][MAX_V], int N) -{ - int i, j; - - printf("\n\nBoI(i,j)x}TpUG\n "); - for (i = 1; i <= N; i++) printf("%4d",i); - for (i = 0; i <= N; i++) printf("%4s",i==0? "\n +":"----"); - - for (i = 1; i <= N; i++) { - printf("\nI%d |",i); - for (j = 1; j <= N; j++) { - if (A[i][j] == Inf) - printf("%5s",""); /* somewhat weird to use %5s instead of %4s here */ - else - printf("%4d",A[i][j]); - } - //printf("\n"); - } -} - -int backtrack(int A[][MAX_V], int Y[][MAX_V], int source, int dest) -{ - int distance, k = Y[source][dest]; /* ksourcedest~I */ - - if (source == dest) { - printf("I%d ",source); - return A[source][dest]; - } - if (Y[source][dest] == -1) { - printf("I%dP%dS|sb:( ",source,dest); - return Inf; - } - distance = backtrack(A,Y,source,k); - printf(" %d ",dest); - - return distance+A[k][dest]; -} - -void traverseMatrix(int A[][MAX_V],int Y[][MAX_V]) -{ - int distance, source, sink; - - printf("\n\ndߥGI̵u|\nI(0hXd) => "); - scanf("%d",&source); - if (source == 0) return; - printf("I(0hXd) => "); - scanf("%d",&sink); - if (sink == 0) return; - - printf("̵u|G"); - distance = backtrack(A,Y,source,sink); - printf("\b\b (ҸgZ`M=%d)(dA[%d][%d]=%d)",distance,source,sink,A[source][sink]); /* ٰ̫ܦhl"" */ -} - -int main() -{ - int N, A[MAX_V][MAX_V], Y[MAX_V][MAX_V] = {0}; - /* NϩҧtI`ơFA[1..N][1..N]ϧΪ۾Fx} */ - /* Y[1..N][1..N]OGI(i,j)Zj̪񪺤~IANΩ̵u|^ */ - - printf("\n*** all-pairs shortest-path D ***"); - - init(A,Y,&N); /* ŪJɡB]w۾Fx}AçƵc@l */ - floydWarshall(A,Y,N); - printMatrix(A,N); - //printMatrix(Y,N); - traverseMatrix(A,Y); - - return 0; -} diff --git a/作業/unit12/all-pairs-shortest-path-v2.c b/作業/unit12/all-pairs-shortest-path-v2.c deleted file mode 100644 index 47f40d3..0000000 --- a/作業/unit12/all-pairs-shortest-path-v2.c +++ /dev/null @@ -1,130 +0,0 @@ -/* -Program: all-pairs-shortest-path-v2.c (Report comments/bugs to chikh@yuntech.edu.tw) -Function: קall-pairs-shortest-path-v1.cϱoAPYx}̹ϤI`Ƨ@tmAקK - wtmLj100x100}CŶӧΦO -*/ - -#include -#include /* for exit() */ - -#define Inf 1073741823 /* 2^30-1jƦrA{]LjȡFilimits.hwqINT_MAX */ - -void init(int ***A, int ***Y) /* ŪJɡB]w۾Fx}AƵc@l */ -{ - FILE *fptr; - int i, j; - int weight, N; - - if ((fptr=fopen("shortestPath.dat","r")) == NULL) { /* }Ҹ */ - perror("shortestPath.dat"); - exit(1); - } - - fscanf(fptr,"%d",&N); /* Ūϧθ`I */ - - *A = (int **)malloc((N+1)*sizeof(int *)); - *Y = (int **)malloc((N+1)*sizeof(int *)); - for (i = 0; i <= N; i++) { - (*A)[i] = (int *)malloc((N+1)*sizeof(int)); - (*Y)[i] = (int *)malloc((N+1)*sizeof(int)); - } - - (*A)[0][0] = N; - for (i = 1; i <= N; i++ ) - for (j = 1; j <= N; j++) { - (*A)[i][j] = (i==j)? 0: Inf; /* lA[1..N][1..N]۾Fx}AҦw] */ - (*Y)[i][j] = (i==j)? i: -1; - } - - while (fscanf(fptr,"%d %d %d",&i,&j,&weight) != EOF) { - (*A)[i][j] = weight; /* ŪsIiPj䪺v */ - (*Y)[i][j] = i; - } - - fclose(fptr); -} - -void floydWarshall(int ***A, int ***Y) -{ - int i, j, k; - int N = (*A)[0][0]; //Lkϥsizeof(A[0])/sizeof(A[0][0])PŪסA]Hmalloc()tmұoOŶ㵲c - - for (k = 1; k <= N; k++) - for (i = 1; i <= N; i++) - for (j = 1; j <= N; j++) - if ((*A)[i][k] + (*A)[k][j] < (*A)[i][j]) { - (*A)[i][j] = (*A)[i][k] + (*A)[k][j]; - (*Y)[i][j] = (*Y)[k][j]; - } - //WGhforjΩ˵/ץCGI(i,j)_gk(~I)opZ -} - -void printMatrix(int **A) -{ - int i, j; - int N = A[0][0]; - - for (i = 1; i <= N; i++) { - for (j = 1; j <= N; j++) { - if (A[i][j] == Inf) - printf("%5s",""); - else - printf("%4d",A[i][j]); - } - printf("\n"); - } -} - -void backtrack(int **Y, int source, int dest) -{ - int k = Y[source][dest]; - - if (source == dest) { - printf("I%d ",source); - return; - } - if (Y[source][dest] == -1) { - printf("I%dP%dS|sb ",source,dest); - return; - } - backtrack(Y,source,k); - printf(" %d ",dest); -} - -void traverseMatrix(int **Y) -{ - int i, j, k, source, sink; - - printf("\nI => "); - scanf("%d",&source); - printf("I => "); - scanf("%d",&sink); - - printf("̵u|G"); - backtrack(Y,source,sink); - printf("\b\b "); -} - -void freeMemory(int **A, int **Y) -{ - int i, N = A[0][0]; - - for (i = 0; i <= N; i++) { - free(A[i]); - free(Y[i]); - } - free(A); - free(Y); -} - -int main() { - int **A, **Y; - - init(&A,&Y); /* ŪJɡB]w۾Fx}AçƵc@l */ - floydWarshall(&A,&Y); - printMatrix(A); - traverseMatrix(Y); - freeMemory(A,Y); - - return 0; -} diff --git a/作業/unit12/all-pairs-shortest-path-v3.c b/作業/unit12/all-pairs-shortest-path-v3.c deleted file mode 100644 index d8e9da6..0000000 --- a/作業/unit12/all-pairs-shortest-path-v3.c +++ /dev/null @@ -1,142 +0,0 @@ -/* -Program: all-pairs-shortest-path-v3.c (Report comments/bugs to chikh@yuntech.edu.tw) -Function: קall-pairs-shortest-path-v2.cAsWۭqadjMatrixƫAtAPYGx}A - x}̹ϤI`Ƨ@tmABקKϥΤThСAPǪDz߭t -*/ - -#include -#include /* for exit() */ - -#define Inf 1073741823 /* 2^30-1jƦrA{]LjȡFilimits.hwqINT_MAX */ - -typedef struct adjMatrix { - int **A; /* A[][]x}AHй@ */ - int **Y; /* Y[][]x}AHй@ */ - int size; /* x}סAΥHܤWzGx}N NxN } */ -} adjMatrix; - -adjMatrix init() /* ŪJɡB]w۾Fx}AƵc@l */ -{ - FILE *fptr; - int i, j; - int weight, N; - static adjMatrix adj; - - if ((fptr=fopen("shortestPath.dat","r")) == NULL) { /* }Ҹ */ - perror("shortestPath.dat"); - exit(1); - } - - fscanf(fptr,"%d",&N); /* Ūϧθ`I */ - - adj.A = (int **)malloc((N+1)*sizeof(int *)); - adj.Y = (int **)malloc((N+1)*sizeof(int *)); - for (i = 0; i <= N; i++) { - adj.A[i] = (int *)malloc((N+1)*sizeof(int)); - adj.Y[i] = (int *)malloc((N+1)*sizeof(int)); - } - - adj.size = N; - for (i = 1; i <= N; i++ ) - for (j = 1; j <= N; j++) { - adj.A[i][j] = (i==j)? 0: Inf; /* lA[1..N][1..N]۾Fx}AҦw] */ - adj.Y[i][j] = (i==j)? i: -1; - } - - while (fscanf(fptr,"%d %d %d",&i,&j,&weight) != EOF) { - adj.A[i][j] = weight; /* ŪsIiPj䪺v */ - adj.Y[i][j] = i; - } - - fclose(fptr); - - return adj; -} - -void floydWarshall(adjMatrix *adj) { - int i, j, k; - int N = adj->size; - - for (k = 1; k <= N; k++) - for (i = 1; i <= N; i++) - for (j = 1; j <= N; j++) - if (adj->A[i][k] + adj->A[k][j] < adj->A[i][j]) { - adj->A[i][j] = adj->A[i][k] +adj->A[k][j]; - adj->Y[i][j] = adj->Y[k][j]; - } -} - -void printMatrix(adjMatrix *adj) -{ - int i, j, N = adj->size; - - printf("\n\nBoI(i,j)x}TpUG\n "); - for (i = 1; i <= N; i++) printf("%4d",i); - for (i = 0; i <= N; i++) printf("%4s",i==0? "\n +":"----"); - - for (i = 1; i <= N; i++) { - printf("\nI%d |",i); - for (j = 1; j <= N; j++) { - if (adj->A[i][j] == Inf) - printf("%5s",""); /* somewhat weird to use %5s instead of %4s here */ - else - printf("%4d",adj->A[i][j]); - } - //printf("\n"); - } -} - -void backtrack(adjMatrix *adj, int source, int dest) -{ - int k = adj->Y[source][dest]; - - if (source == dest) { - printf("I%d ",source); - return; - } - if (adj->Y[source][dest] == -1) { - printf("I%dP%dS|sb ",source,dest); - return; - } - backtrack(adj,source,k); - printf(" %d ",dest); -} - -void traverseMatrix(adjMatrix *adj) { - int source, sink; - - printf("\n\ndߥGI̵u|\nI(0hXd) => "); - scanf("%d",&source); - if (source == 0) return; - printf("I(0hXd) => "); - scanf("%d",&sink); - if (sink == 0) return; - - printf("̵u|G"); - backtrack(adj,source,sink); - printf("\b\b "); -} - -void freeMemory(adjMatrix *adj) { - int i, N = adj->size; - - for (i = 0; i <= N; i++) { - free(adj->A[i]); - free(adj->Y[i]); - } - free(adj->A); - free(adj->Y); -} - -int main() -{ - printf("\n*** all-pairs shortest-path D ***"); - - adjMatrix adj = init(); /* ŪJɡB]w۾Fx}AçƵc@l */ - floydWarshall(&adj); - printMatrix(&adj); - traverseMatrix(&adj); - freeMemory(&adj); - - return 0; -} diff --git a/作業/unit12/bfs/bfs.cpp b/作業/unit12/bfs/bfs.cpp new file mode 100644 index 0000000..2a6b95a --- /dev/null +++ b/作業/unit12/bfs/bfs.cpp @@ -0,0 +1,161 @@ +/* ϧΪl: ۾FCPsujMk(BFS)*/ +#include +#include +#define MAX_V 100 /*̤j`I*/ +#define TRUE 1 +#define FALSE 0 + +/*wqƵc*/ +typedef struct node_tag { + int vertex; + struct node_tag *link; +} Node; + +/*wqCc*/ +typedef struct { + int items[MAX_V]; + int front; + int rear; +} Queue; + +Node *adjlist[MAX_V+1]; /*ŧi۾FC*/ +int visited[MAX_V+1]; /*OIO_wX*/ +int total_vertex; + +void build_adjlist(void); +void show_adjlist(void); +void bfs(int); +Node *searchlast(Node *); + +/*Cާ@*/ +Queue* createQueue() { + Queue *q = (Queue*)malloc(sizeof(Queue)); + q->front = -1; + q->rear = -1; + return q; +} + +int isEmpty(Queue* q) { + return q->front == -1; +} + +void enqueue(Queue* q, int value) { + if(q->front == -1) + q->front = 0; + q->rear++; + q->items[q->rear] = value; +} + +int dequeue(Queue* q) { + int item = q->items[q->front]; + if(q->front == q->rear) { + q->front = -1; + q->rear = -1; + } else { + q->front++; + } + return item; +} + +int main() +{ + build_adjlist(); /*H۾FCܹϧ*/ + show_adjlist(); /*ܦC*/ + puts("\n------Breadth First Search------"); + bfs(1); /*ϧΤsujMAHI1ҩlI*/ + printf("\n"); + return 0; +} + +void build_adjlist() +{ + FILE *fptr; + Node *node,*lastnode; + int vi,vj ,weight; + fptr = fopen("dfs_1.dat", "r"); + if (fptr == NULL) { + perror("dfs.dat"); + exit(0); + } + /* Ū`I` */ + fscanf(fptr, "%d", &total_vertex); + for (vi = 1; vi <= total_vertex; vi++) { + /*]w}CΦUCҩl*/ + visited[vi] = FALSE; + adjlist[vi] = (Node *)malloc(sizeof(Node)); + adjlist[vi]->vertex = vi; + adjlist[vi]->link = NULL; + } + /* Ū`I */ + for (vi = 1; vi <= total_vertex; vi++) + for (vj = 1; vj <= total_vertex; vj++) { + fscanf(fptr,"%d",&weight); + /* ɥH۾Fx}榡xs,H1N۾F + 0 N۾FAN۾FI쵲bUC */ + if (weight != 0) { + node = (Node *)malloc(sizeof(Node)); + node->vertex = vj; + node->link = NULL; + lastnode = searchlast(adjlist[vi]); + lastnode->link = node; + } + } + fclose(fptr); +} + +/*ܦU۾FC*/ +void show_adjlist() +{ + int index; + Node *ptr; + puts("Head adjacency nodes"); + puts("------------------------------"); + for (index = 1; index <= total_vertex; index++) { + printf("V%-2d ",adjlist[index]->vertex); + ptr = adjlist[index]->link; + while (ptr != NULL) { + printf("--> V%d ",ptr->vertex); + ptr = ptr->link; + } + printf("\n"); + } +} + +/*ϧΤsujM*/ +void bfs(int start) +{ + Queue* q = createQueue(); + Node* ptr; + + // N_l`I[JC + enqueue(q, start); + visited[start] = TRUE; + + while(!isEmpty(q)) { + // qCX`IæLX + int currentVertex = dequeue(q); + printf("V%d ", currentVertex); + + // NҦ۾FBX`I[JC + ptr = adjlist[currentVertex]->link; + while(ptr != NULL) { + if(!visited[ptr->vertex]) { + enqueue(q, ptr->vertex); + visited[ptr->vertex] = TRUE; + } + ptr = ptr->link; + } + } + + free(q); +} + +/*jMC̫`I*/ +Node *searchlast(Node *linklist) +{ + Node *ptr; + ptr = linklist; + while (ptr->link != NULL) + ptr = ptr->link; + return ptr; +} diff --git a/作業/unit12/bfs/bfs.exe b/作業/unit12/bfs/bfs.exe new file mode 100644 index 0000000..a1f6911 Binary files /dev/null and b/作業/unit12/bfs/bfs.exe differ diff --git a/作業/unit12/bfs/bfs_down_triangle.cpp b/作業/unit12/bfs/bfs_down_triangle.cpp new file mode 100644 index 0000000..163ecc2 --- /dev/null +++ b/作業/unit12/bfs/bfs_down_triangle.cpp @@ -0,0 +1,242 @@ +/* ϧΪl: ۾FCPsujMk(BFS) - tv */ +#include +#include +#include +#define MAX_V 100 /*̤j`I*/ +#define TRUE 1 +#define FALSE 0 + +/*wqƵc*/ +typedef struct node_tag { + int vertex; + struct node_tag *link; +} Node; + +/*wqCc*/ +typedef struct { + int items[MAX_V]; + int front; + int rear; +} Queue; + +Node *adjlist[MAX_V+1]; /*ŧi۾FC*/ +int visited[MAX_V+1]; /*OIO_wX*/ +int total_vertex; +int weight_matrix[MAX_V+1][MAX_V+1]; /* xsvx} */ + +void build_adjlist(void); +void show_adjlist(void); +void show_weight_matrix(void); +void bfs(int); +Node *searchlast(Node *); + +/*Cާ@*/ +Queue* createQueue() { + Queue *q = (Queue*)malloc(sizeof(Queue)); + q->front = -1; + q->rear = -1; + return q; +} + +int isEmpty(Queue* q) { + return q->front == -1; +} + +void enqueue(Queue* q, int value) { + if(q->front == -1) + q->front = 0; + q->rear++; + q->items[q->rear] = value; +} + +int dequeue(Queue* q) { + int item = q->items[q->front]; + if(q->front == q->rear) { + q->front = -1; + q->rear = -1; + } else { + q->front++; + } + return item; +} + +int main() +{ + build_adjlist(); /*H۾FCܹϧ*/ + show_weight_matrix(); /*vx}*/ + show_adjlist(); /*ܦC*/ + puts("\n------Breadth First Search------"); + bfs(1); /*ϧΤsujMAHI1ҩlI*/ + printf("\n"); + return 0; +} + +void build_adjlist() +{ + FILE *fptr; + Node *node, *lastnode; + int vi, vj; + char line[256]; + int weight; + int line_count = 0; + + fptr = fopen("down_1.dat", "r"); + if (fptr == NULL) { + perror("down_1.dat"); + exit(0); + } + + // p`I + while (fgets(line, sizeof(line), fptr)) { + line_count++; + } + total_vertex = line_count; // קG1 + rewind(fptr); + + // lvx}0 + for(int i = 0; i <= total_vertex; i++) + for(int j = 0; j <= total_vertex; j++) + weight_matrix[i][j] = 0; + + // lƬ۾FC + for (vi = 1; vi <= total_vertex; vi++) { + visited[vi] = FALSE; + adjlist[vi] = (Node *)malloc(sizeof(Node)); + adjlist[vi]->vertex = vi; + adjlist[vi]->link = NULL; + } + + // ŪUTίx} + for (vi = 1; vi <= total_vertex; vi++) { + // קGuŪviӤ]UT^ + for (vj = 1; vj < vi; vj++) { + if (fscanf(fptr, "%d", &weight) != 1) { + printf("Error reading weight at vi=%d, vj=%d\n", vi, vj); + continue; + } + + // xsvx} + weight_matrix[vi][vj] = weight; + weight_matrix[vj][vi] = weight; // ]OLVϡAҥHxs + + // Y۾FY]weight = 1^Ahإ߳s + if (weight == 1) { + // [J vi -> vj s + node = (Node *)malloc(sizeof(Node)); + node->vertex = vj; + node->link = NULL; + lastnode = searchlast(adjlist[vi]); + lastnode->link = node; + + // [J vj -> vi s]]OLVϡ^ + node = (Node *)malloc(sizeof(Node)); + node->vertex = vi; + node->link = NULL; + lastnode = searchlast(adjlist[vj]); + lastnode->link = node; + } + } + // Ū﨤u]@wO0AiHL^ + fscanf(fptr, "%d", &weight); + } + + fclose(fptr); +} + +/* קvx}ơAϨM */ +void show_weight_matrix() +{ + int i, j; + printf("\n=== Weight Matrix ===\n"); + printf(" "); + for(j = 1; j <= total_vertex; j++) { + printf("V%-3d", j); + } + printf("\n"); + + for(i = 1; i <= total_vertex; i++) { + printf("V%-3d", i); + for(j = 1; j <= total_vertex; j++) { + printf("%-4d", weight_matrix[i][j]); + } + printf("\n"); + } + printf("\n"); +} + +/*ܦU۾FC*/ +void show_adjlist() +{ + int index; + Node *ptr; + puts("Head adjacency nodes"); + puts("------------------------------"); + for (index = 1; index <= total_vertex; index++) { + printf("V%-2d ",adjlist[index]->vertex); + ptr = adjlist[index]->link; + while (ptr != NULL) { + printf("--> V%d ",ptr->vertex); + ptr = ptr->link; + } + printf("\n"); + } +} + +/*ϧΤsujM*/ +void bfs(int start) +{ + Queue* q = createQueue(); + Node* ptr; + + // N_l`I[JC + enqueue(q, start); + visited[start] = TRUE; + + while(!isEmpty(q)) { + // qCX`IæLX + int currentVertex = dequeue(q); + printf("V%d ", currentVertex); + + // NҦ۾FBX`I[JCAë`IsƧ + int neighbors[MAX_V]; + int neighborCount = 0; + + // ҦXݪ۾F`I + ptr = adjlist[currentVertex]->link; + while(ptr != NULL) { + if(!visited[ptr->vertex]) { + neighbors[neighborCount++] = ptr->vertex; + } + ptr = ptr->link; + } + + // N۾F`IsƧ + for(int i = 0; i < neighborCount - 1; i++) { + for(int j = 0; j < neighborCount - i - 1; j++) { + if(neighbors[j] > neighbors[j + 1]) { + int temp = neighbors[j]; + neighbors[j] = neighbors[j + 1]; + neighbors[j + 1] = temp; + } + } + } + + // ǥ[JC + for(int i = 0; i < neighborCount; i++) { + enqueue(q, neighbors[i]); + visited[neighbors[i]] = TRUE; + } + } + + free(q); +} + +/*jMC̫`I*/ +Node *searchlast(Node *linklist) +{ + Node *ptr; + ptr = linklist; + while (ptr->link != NULL) + ptr = ptr->link; + return ptr; +} diff --git a/作業/unit12/bfs/bfs_down_triangle.exe b/作業/unit12/bfs/bfs_down_triangle.exe new file mode 100644 index 0000000..dec1788 Binary files /dev/null and b/作業/unit12/bfs/bfs_down_triangle.exe differ diff --git a/作業/unit12/bfs/bfs_up_triangle.cpp b/作業/unit12/bfs/bfs_up_triangle.cpp new file mode 100644 index 0000000..a316943 --- /dev/null +++ b/作業/unit12/bfs/bfs_up_triangle.cpp @@ -0,0 +1,242 @@ +/* ϧΪl: ۾FCPsujMk(BFS) - tv */ +#include +#include +#include +#define MAX_V 100 /*̤j`I*/ +#define TRUE 1 +#define FALSE 0 + +/*wqƵc*/ +typedef struct node_tag { + int vertex; + struct node_tag *link; +} Node; + +/*wqCc*/ +typedef struct { + int items[MAX_V]; + int front; + int rear; +} Queue; + +Node *adjlist[MAX_V+1]; /*ŧi۾FC*/ +int visited[MAX_V+1]; /*OIO_wX*/ +int total_vertex; +int weight_matrix[MAX_V+1][MAX_V+1]; /* xsvx} */ + +void build_adjlist(void); +void show_adjlist(void); +void show_weight_matrix(void); +void bfs(int); +Node *searchlast(Node *); + +/*Cާ@*/ +Queue* createQueue() { + Queue *q = (Queue*)malloc(sizeof(Queue)); + q->front = -1; + q->rear = -1; + return q; +} + +int isEmpty(Queue* q) { + return q->front == -1; +} + +void enqueue(Queue* q, int value) { + if(q->front == -1) + q->front = 0; + q->rear++; + q->items[q->rear] = value; +} + +int dequeue(Queue* q) { + int item = q->items[q->front]; + if(q->front == q->rear) { + q->front = -1; + q->rear = -1; + } else { + q->front++; + } + return item; +} + +int main() +{ + build_adjlist(); /*H۾FCܹϧ*/ + show_weight_matrix(); /*vx}*/ + show_adjlist(); /*ܦC*/ + puts("\n------Breadth First Search------"); + bfs(1); /*ϧΤsujMAHI1ҩlI*/ + printf("\n"); + return 0; +} + +void build_adjlist() +{ + FILE *fptr; + Node *node, *lastnode; + int vi, vj; + char line[256]; + int weight; + int line_count = 0; + + fptr = fopen("up_1.dat", "r"); + if (fptr == NULL) { + perror("up_1.dat"); + exit(0); + } + + while (fgets(line, sizeof(line), fptr)) { + line_count++; + } + total_vertex = line_count ; + rewind(fptr); // mɮ׫Ш}YHsŪx} + + /* lvx}0 */ + for(int i = 0; i <= total_vertex; i++) + for(int j = 0; j <= total_vertex; j++) + weight_matrix[i][j] = 0; + + /* lƬ۾FC */ + for (vi = 1; vi <= total_vertex; vi++) { + visited[vi] = FALSE; + adjlist[vi] = (Node *)malloc(sizeof(Node)); + adjlist[vi]->vertex = vi; + adjlist[vi]->link = NULL; + } + + /* ŪWTίx} */ + for (vi = 1; vi <= total_vertex; vi++) { + /* ŪӦ檺ƭ */ + for (vj = vi ; vj <= total_vertex; vj++) { + if (fscanf(fptr, "%d", &weight) != 1) { + printf("Error reading weight at vi=%d, vj=%d\n", vi, vj); + continue; + } + + /* xsvx} */ + weight_matrix[vi][vj] = weight; + weight_matrix[vj][vi] = weight; /* ]OLVϡAҥHxs */ + + /* Y۾FY]weight = 1^Ahإ߳s */ + if (weight == 1) { + /* [J vi -> vj s */ + node = (Node *)malloc(sizeof(Node)); + node->vertex = vj; + node->link = NULL; + lastnode = searchlast(adjlist[vi]); + lastnode->link = node; + + /* [J vj -> vi s]]OLVϡ^ */ + node = (Node *)malloc(sizeof(Node)); + node->vertex = vi; + node->link = NULL; + lastnode = searchlast(adjlist[vj]); + lastnode->link = node; + } + } + /* U@ */ + fscanf(fptr, "%*[^\n]"); + fscanf(fptr, "%*c"); + } + + fclose(fptr); +} + +/* קvx}ơAϨM */ +void show_weight_matrix() +{ + int i, j; + printf("\n=== Weight Matrix ===\n"); + printf(" "); + for(j = 1; j <= total_vertex; j++) { + printf("V%-3d", j); + } + printf("\n"); + + for(i = 1; i <= total_vertex; i++) { + printf("V%-3d", i); + for(j = 1; j <= total_vertex; j++) { + printf("%-4d", weight_matrix[i][j]); + } + printf("\n"); + } + printf("\n"); +} + +/*ܦU۾FC*/ +void show_adjlist() +{ + int index; + Node *ptr; + puts("Head adjacency nodes"); + puts("------------------------------"); + for (index = 1; index <= total_vertex; index++) { + printf("V%-2d ",adjlist[index]->vertex); + ptr = adjlist[index]->link; + while (ptr != NULL) { + printf("--> V%d ",ptr->vertex); + ptr = ptr->link; + } + printf("\n"); + } +} + +/*ϧΤsujM*/ +void bfs(int start) +{ + Queue* q = createQueue(); + Node* ptr; + + // N_l`I[JC + enqueue(q, start); + visited[start] = TRUE; + + while(!isEmpty(q)) { + // qCX`IæLX + int currentVertex = dequeue(q); + printf("V%d ", currentVertex); + + // NҦ۾FBX`I[JCAë`IsƧ + int neighbors[MAX_V]; + int neighborCount = 0; + + // ҦXݪ۾F`I + ptr = adjlist[currentVertex]->link; + while(ptr != NULL) { + if(!visited[ptr->vertex]) { + neighbors[neighborCount++] = ptr->vertex; + } + ptr = ptr->link; + } + + // N۾F`IsƧ + for(int i = 0; i < neighborCount - 1; i++) { + for(int j = 0; j < neighborCount - i - 1; j++) { + if(neighbors[j] > neighbors[j + 1]) { + int temp = neighbors[j]; + neighbors[j] = neighbors[j + 1]; + neighbors[j + 1] = temp; + } + } + } + + // ǥ[JC + for(int i = 0; i < neighborCount; i++) { + enqueue(q, neighbors[i]); + visited[neighbors[i]] = TRUE; + } + } + + free(q); +} + +/*jMC̫`I*/ +Node *searchlast(Node *linklist) +{ + Node *ptr; + ptr = linklist; + while (ptr->link != NULL) + ptr = ptr->link; + return ptr; +} diff --git a/作業/unit12/bfs/bfs_up_triangle.exe b/作業/unit12/bfs/bfs_up_triangle.exe new file mode 100644 index 0000000..021dd66 Binary files /dev/null and b/作業/unit12/bfs/bfs_up_triangle.exe differ diff --git a/作業/unit12/bfs/dfs.dat b/作業/unit12/bfs/dfs.dat new file mode 100644 index 0000000..fa925fa --- /dev/null +++ b/作業/unit12/bfs/dfs.dat @@ -0,0 +1,10 @@ +0 1 1 0 0 0 0 0 0 0 +1 0 0 1 1 0 0 0 0 0 +1 0 0 0 0 1 1 0 0 0 +0 1 0 0 0 0 0 1 0 0 +0 1 0 0 0 0 0 1 0 0 +0 0 1 0 0 0 0 0 1 0 +0 0 1 0 0 0 0 0 1 0 +0 0 0 1 1 0 0 0 0 1 +0 0 0 0 0 1 1 0 0 1 +0 0 0 0 0 0 0 1 1 0 \ No newline at end of file diff --git a/作業/unit12/bfs/down_1.dat b/作業/unit12/bfs/down_1.dat new file mode 100644 index 0000000..2060205 --- /dev/null +++ b/作業/unit12/bfs/down_1.dat @@ -0,0 +1,10 @@ +0 +1 0 +1 0 0 +0 1 0 0 +0 1 0 0 0 +0 0 1 0 0 0 +0 0 1 0 0 0 0 +0 0 0 1 1 0 0 0 +0 0 0 0 0 1 1 0 0 +0 0 0 0 0 0 0 1 1 0 diff --git a/作業/unit12/bfs/down_2.dat b/作業/unit12/bfs/down_2.dat new file mode 100644 index 0000000..f76d854 --- /dev/null +++ b/作業/unit12/bfs/down_2.dat @@ -0,0 +1,9 @@ +0 +1 0 +0 1 0 +0 0 1 0 +0 0 1 0 0 +0 0 0 1 0 0 +0 0 0 1 0 0 0 +0 0 0 0 1 0 1 0 +0 0 0 1 1 0 0 0 0 \ No newline at end of file diff --git a/作業/unit12/bfs/up_1.dat b/作業/unit12/bfs/up_1.dat new file mode 100644 index 0000000..d8c2c96 --- /dev/null +++ b/作業/unit12/bfs/up_1.dat @@ -0,0 +1,9 @@ +0 1 0 0 0 0 0 0 0 + 0 1 0 0 0 0 0 0 + 0 1 1 0 0 0 0 + 0 0 1 1 0 1 + 0 0 0 1 1 + 0 0 0 0 + 0 1 0 + 0 0 + 0 \ No newline at end of file diff --git a/作業/unit12/bfs/up_2.dat b/作業/unit12/bfs/up_2.dat new file mode 100644 index 0000000..1bf3d6e --- /dev/null +++ b/作業/unit12/bfs/up_2.dat @@ -0,0 +1,10 @@ +0 1 1 0 0 0 0 0 0 0 + 0 0 1 1 0 0 0 0 0 + 0 0 0 1 1 0 0 0 + 0 0 0 0 1 0 0 + 0 0 0 1 0 0 + 0 0 0 1 0 + 0 0 1 0 + 0 0 1 + 0 1 + 0 \ No newline at end of file diff --git a/作業/unit12/bfs/聖.dat b/作業/unit12/bfs/聖.dat new file mode 100644 index 0000000..1bf3d6e --- /dev/null +++ b/作業/unit12/bfs/聖.dat @@ -0,0 +1,10 @@ +0 1 1 0 0 0 0 0 0 0 + 0 0 1 1 0 0 0 0 0 + 0 0 0 1 1 0 0 0 + 0 0 0 0 1 0 0 + 0 0 0 1 0 0 + 0 0 0 1 0 + 0 0 1 0 + 0 0 1 + 0 1 + 0 \ No newline at end of file diff --git a/作業/unit12/dfs/dfs.cpp b/作業/unit12/dfs/dfs.cpp new file mode 100644 index 0000000..de6884c --- /dev/null +++ b/作業/unit12/dfs/dfs.cpp @@ -0,0 +1,127 @@ +/* file name: dfs.c */ +/* ϧΪl: ۾FCPܦVujMk(DFS)*/ + +#include +#include + +#define MAX_V 100 /*̤j`I*/ +#define TRUE 1 +#define FALSE 0 + +/*wqƵc*/ +typedef struct node_tag { + int vertex; + struct node_tag *link; +} Node; + +Node *adjlist[MAX_V+1]; /*ŧi۾FC*/ +int visited[MAX_V+1]; /*OIO_wX*/ +int total_vertex; + + +void build_adjlist(void); +void show_adjlist(void); +void dfs(int); +Node *searchlast(Node *); + +int main() +{ + build_adjlist(); /*H۾FCܹϧ*/ + show_adjlist(); /*ܦC*/ + puts("\n------Depth Fisrt Search------"); + dfs(1); /*ϧΤܦVujMAHI1ҩlI*/ + printf("\n"); + return 0; +} + +void build_adjlist() +{ + FILE *fptr; + Node *node,*lastnode; + int vi,vj ,weight; + + fptr = fopen("dfs.dat", "r"); + if (fptr == NULL) { + perror("dfs.dat"); + exit(0); + } + + /* Ū`I` */ + fscanf(fptr, "%d", &total_vertex); + for (vi = 1; vi <= total_vertex; vi++) { + /*]w}CΦUCҩl*/ + visited[vi] = FALSE; + adjlist[vi] = (Node *)malloc(sizeof(Node)); + adjlist[vi]->vertex = vi; + adjlist[vi]->link = NULL; + } + + /* Ū`I */ + for (vi = 1; vi <= total_vertex; vi++) + for (vj = 1; vj <= total_vertex; vj++) { + fscanf(fptr,"%d",&weight); + /* ɥH۾Fx}榡xs,H1N۾F + 0 N۾FAN۾FI쵲bUC */ + if (weight != 0) { + node = (Node *)malloc(sizeof(Node)); + node->vertex = vj; + node->link = NULL; + lastnode = searchlast(adjlist[vi]); + lastnode->link = node; + } + } + fclose(fptr); +} + +/*ܦU۾FC*/ +void show_adjlist() +{ + int index; + Node *ptr; + + puts("Head adjacency nodes"); + puts("------------------------------"); + for (index = 1; index <= total_vertex; index++) { + printf("V%-2d ",adjlist[index]->vertex); + ptr = adjlist[index]->link; + while (ptr != NULL) { + printf("--> V%d ",ptr->vertex); + ptr = ptr->link; + } + printf("\n"); + } +} + +/*ϧΤܦVujM*/ +void dfs(int v) +{ + Node *ptr; + int w; + + printf("V%d ",adjlist[v]->vertex); + visited[v] = TRUE; /*]wvIwXL*/ + ptr = adjlist[v]->link; /*X۾FI*/ + + do { + /* YI|XAhHIsҩlI~ + ܦVujMkXA_hP۾FI + Ҧ۳s`IwX */ + w = ptr->vertex; + if (!visited[w]) + dfs(w); + else + ptr = ptr->link; + } while (ptr != NULL); +} + +/*jMC̫`I*/ +Node *searchlast( Node *linklist ) +{ + Node *ptr; + + ptr = linklist; + while (ptr->link != NULL) + ptr = ptr->link; + return ptr; +} + diff --git a/作業/unit12/dfs/dfs.dat b/作業/unit12/dfs/dfs.dat new file mode 100644 index 0000000..2cbfb09 --- /dev/null +++ b/作業/unit12/dfs/dfs.dat @@ -0,0 +1,11 @@ +10 +0 1 1 0 0 0 0 0 0 0 +1 0 0 1 1 0 0 0 0 0 +1 0 0 0 0 1 1 0 0 0 +0 1 0 0 0 0 0 1 0 0 +0 1 0 0 0 0 0 1 0 0 +0 0 1 0 0 0 0 0 1 0 +0 0 1 0 0 0 0 0 1 0 +0 0 0 1 1 0 0 0 0 1 +0 0 0 0 0 1 1 0 0 1 +0 0 0 0 0 0 0 1 1 0 diff --git a/作業/unit12/dfs/dfs.exe b/作業/unit12/dfs/dfs.exe new file mode 100644 index 0000000..7e7b8ef Binary files /dev/null and b/作業/unit12/dfs/dfs.exe differ diff --git a/作業/unit12/dfs/dfs_down_triangle.cpp b/作業/unit12/dfs/dfs_down_triangle.cpp new file mode 100644 index 0000000..0b74b85 --- /dev/null +++ b/作業/unit12/dfs/dfs_down_triangle.cpp @@ -0,0 +1,178 @@ +/* file name: dfs.c */ +/* ϧΪl: ۾FCPܦVujMk(DFS)*/ + +#include +#include + +#define MAX_V 100 /*̤j`I*/ +#define TRUE 1 +#define FALSE 0 + +/*wqƵc*/ +typedef struct node_tag { + int vertex; + struct node_tag *link; +} Node; + +Node *adjlist[MAX_V+1]; /*ŧi۾FC*/ +int visited[MAX_V+1]; /*OIO_wX*/ +int total_vertex; + + +void build_adjlist(void); +void show_adjlist(void); +void show_weight_matrix(void); +void dfs(int); +Node *searchlast(Node *); +int weight_matrix[MAX_V+1][MAX_V+1]; /* xsvx} */ + +int main() +{ + build_adjlist(); /*H۾FCܹϧ*/ + show_weight_matrix(); /*vx}*/ + show_adjlist(); /*ܦC*/ + puts("\n------Depth Fisrt Search------"); + dfs(1); /*ϧΤܦVujMAHI1ҩlI*/ + printf("\n"); + return 0; +} + +void build_adjlist() +{ + FILE *fptr; + Node *node, *lastnode; + int vi, vj, weight; + char line[256]; + int line_count = 0; + + fptr = fopen("down_1.dat", "r"); + if (fptr == NULL) { + perror("down_1.dat"); + exit(0); + } + + // p`I + while (fgets(line, sizeof(line), fptr)) { + line_count++; + } + total_vertex = line_count; // `IƵ + rewind(fptr); + + // lư}CΦUCҩl + for (vi = 1; vi <= total_vertex; vi++) { + visited[vi] = FALSE; + adjlist[vi] = (Node *)malloc(sizeof(Node)); + adjlist[vi]->vertex = vi; + adjlist[vi]->link = NULL; + } + + // ŪUTx} + for (vi = 1; vi <= total_vertex; vi++) { + // uŪviӤ]UT^ + for (vj = 1; vj < vi; vj++) { + if (fscanf(fptr, "%d", &weight) != 1) { + printf("Error reading weight at vi=%d, vj=%d\n", vi, vj); + continue; + } + + // xsvx} + weight_matrix[vi][vj] = weight; + weight_matrix[vj][vi] = weight; // ]OLVϡAҥHxs + + // pG۾F]weight = 1^Ahإ߳s + if (weight == 1) { + // [J vi -> vj s + node = (Node *)malloc(sizeof(Node)); + node->vertex = vj; + node->link = NULL; + lastnode = searchlast(adjlist[vi]); + lastnode->link = node; + + // [J vj -> vi s]]OLVϡ^ + node = (Node *)malloc(sizeof(Node)); + node->vertex = vi; + node->link = NULL; + lastnode = searchlast(adjlist[vj]); + lastnode->link = node; + } + } + // Ū﨤u]@wO0^ + fscanf(fptr, "%d", &weight); + } + + fclose(fptr); +} + +/*ܦU۾FC*/ +void show_adjlist() +{ + int index; + Node *ptr; + + puts("Head adjacency nodes"); + puts("------------------------------"); + for (index = 1; index <= total_vertex; index++) { + printf("V%-2d ",adjlist[index]->vertex); + ptr = adjlist[index]->link; + while (ptr != NULL) { + printf("--> V%d ",ptr->vertex); + ptr = ptr->link; + } + printf("\n"); + } +} + +/* קvx}ơAϨM */ +void show_weight_matrix() +{ + int i, j; + printf("\n=== Weight Matrix ===\n"); + printf(" "); + for(j = 1; j <= total_vertex; j++) { + printf("V%-3d", j); + } + printf("\n"); + + for(i = 1; i <= total_vertex; i++) { + printf("V%-3d", i); + for(j = 1; j <= total_vertex; j++) { + printf("%-4d", weight_matrix[i][j]); + } + printf("\n"); + } + printf("\n"); +} + +/*ϧΤܦVujM*/ +void dfs(int v) +{ + Node *ptr; + int w; + + printf("V%d ",adjlist[v]->vertex); + visited[v] = TRUE; /*]wvIwXL*/ + ptr = adjlist[v]->link; /*X۾FI*/ + + do { + /* YI|XAhHIsҩlI~ + ܦVujMkXA_hP۾FI + Ҧ۳s`IwX */ + w = ptr->vertex; + if (!visited[w]) + dfs(w); + else + ptr = ptr->link; + } while (ptr != NULL); +} + +/*jMC̫`I*/ +Node *searchlast( Node *linklist ) +{ + Node *ptr; + + ptr = linklist; + while (ptr->link != NULL) + ptr = ptr->link; + return ptr; +} + diff --git a/作業/unit12/dfs/dfs_down_triangle.exe b/作業/unit12/dfs/dfs_down_triangle.exe new file mode 100644 index 0000000..d41fd26 Binary files /dev/null and b/作業/unit12/dfs/dfs_down_triangle.exe differ diff --git a/作業/unit12/dfs/dfs_up_triangle.cpp b/作業/unit12/dfs/dfs_up_triangle.cpp new file mode 100644 index 0000000..95515fc --- /dev/null +++ b/作業/unit12/dfs/dfs_up_triangle.cpp @@ -0,0 +1,178 @@ +/* file name: dfs.c */ +/* ϧΪl: ۾FCPܦVujMk(DFS)*/ + +#include +#include + +#define MAX_V 100 /*̤j`I*/ +#define TRUE 1 +#define FALSE 0 + +/*wqƵc*/ +typedef struct node_tag { + int vertex; + struct node_tag *link; +} Node; + +Node *adjlist[MAX_V+1]; /*ŧi۾FC*/ +int visited[MAX_V+1]; /*OIO_wX*/ +int total_vertex; + + +void build_adjlist(void); +void show_adjlist(void); +void show_weight_matrix(void); +void dfs(int); +Node *searchlast(Node *); +int weight_matrix[MAX_V+1][MAX_V+1]; /* xsvx} */ + +int main() +{ + build_adjlist(); /*H۾FCܹϧ*/ + show_weight_matrix(); /*vx}*/ + show_adjlist(); /*ܦC*/ + puts("\n------Depth Fisrt Search------"); + dfs(1); /*ϧΤܦVujMAHI1ҩlI*/ + printf("\n"); + return 0; +} + +void build_adjlist() +{ + FILE *fptr; + Node *node, *lastnode; + int vi, vj, weight; + char line[256]; + int line_count = 0; + + fptr = fopen("up_1.dat", "r"); + if (fptr == NULL) { + perror("up_2.dat"); + exit(0); + } + + // p`I + while (fgets(line, sizeof(line), fptr)) { + line_count++; + } + total_vertex = line_count; + rewind(fptr); + + // lư}CΦUCҩl + for (vi = 1; vi <= total_vertex; vi++) { + visited[vi] = FALSE; + adjlist[vi] = (Node *)malloc(sizeof(Node)); + adjlist[vi]->vertex = vi; + adjlist[vi]->link = NULL; + } + + // ŪWTx} + for (vi = 1; vi <= total_vertex; vi++) { + /* ŪӦ檺ƭ */ + for (vj = vi ; vj <= total_vertex; vj++) { + if (fscanf(fptr, "%d", &weight) != 1) { + printf("Error reading weight at vi=%d, vj=%d\n", vi, vj); + continue; + } + + // xsvx} + weight_matrix[vi][vj] = weight; + weight_matrix[vj][vi] = weight; // ]OLVϡAҥHxs + + // pG۾F]weight = 1^Ahإ߳s + if (weight == 1) { + // [J vi -> vj s + node = (Node *)malloc(sizeof(Node)); + node->vertex = vj; + node->link = NULL; + lastnode = searchlast(adjlist[vi]); + lastnode->link = node; + + // [J vj -> vi s]]OLVϡ^ + if (vi != vj) { // קK + node = (Node *)malloc(sizeof(Node)); + node->vertex = vi; + node->link = NULL; + lastnode = searchlast(adjlist[vj]); + lastnode->link = node; + } + } + } + } + + fclose(fptr); +} + +/*ܦU۾FC*/ +void show_adjlist() +{ + int index; + Node *ptr; + + puts("Head adjacency nodes"); + puts("------------------------------"); + for (index = 1; index <= total_vertex; index++) { + printf("V%-2d ",adjlist[index]->vertex); + ptr = adjlist[index]->link; + while (ptr != NULL) { + printf("--> V%d ",ptr->vertex); + ptr = ptr->link; + } + printf("\n"); + } +} + +/* קvx}ơAϨM */ +void show_weight_matrix() +{ + int i, j; + printf("\n=== Weight Matrix ===\n"); + printf(" "); + for(j = 1; j <= total_vertex; j++) { + printf("V%-3d", j); + } + printf("\n"); + + for(i = 1; i <= total_vertex; i++) { + printf("V%-3d", i); + for(j = 1; j <= total_vertex; j++) { + printf("%-4d", weight_matrix[i][j]); + } + printf("\n"); + } + printf("\n"); +} + +/*ϧΤܦVujM*/ +void dfs(int v) +{ + Node *ptr; + int w; + + printf("V%d ",adjlist[v]->vertex); + visited[v] = TRUE; /*]wvIwXL*/ + ptr = adjlist[v]->link; /*X۾FI*/ + + do { + /* YI|XAhHIsҩlI~ + ܦVujMkXA_hP۾FI + Ҧ۳s`IwX */ + w = ptr->vertex; + if (!visited[w]) + dfs(w); + else + ptr = ptr->link; + } while (ptr != NULL); +} + +/*jMC̫`I*/ +Node *searchlast( Node *linklist ) +{ + Node *ptr; + + ptr = linklist; + while (ptr->link != NULL) + ptr = ptr->link; + return ptr; +} + diff --git a/作業/unit12/dfs/dfs_up_triangle.exe b/作業/unit12/dfs/dfs_up_triangle.exe new file mode 100644 index 0000000..e7789e4 Binary files /dev/null and b/作業/unit12/dfs/dfs_up_triangle.exe differ diff --git a/作業/unit12/dfs/down_1.dat b/作業/unit12/dfs/down_1.dat new file mode 100644 index 0000000..2060205 --- /dev/null +++ b/作業/unit12/dfs/down_1.dat @@ -0,0 +1,10 @@ +0 +1 0 +1 0 0 +0 1 0 0 +0 1 0 0 0 +0 0 1 0 0 0 +0 0 1 0 0 0 0 +0 0 0 1 1 0 0 0 +0 0 0 0 0 1 1 0 0 +0 0 0 0 0 0 0 1 1 0 diff --git a/作業/unit12/dfs/down_2.dat b/作業/unit12/dfs/down_2.dat new file mode 100644 index 0000000..f76d854 --- /dev/null +++ b/作業/unit12/dfs/down_2.dat @@ -0,0 +1,9 @@ +0 +1 0 +0 1 0 +0 0 1 0 +0 0 1 0 0 +0 0 0 1 0 0 +0 0 0 1 0 0 0 +0 0 0 0 1 0 1 0 +0 0 0 1 1 0 0 0 0 \ No newline at end of file diff --git a/作業/unit12/dfs/up_1.dat b/作業/unit12/dfs/up_1.dat new file mode 100644 index 0000000..d8c2c96 --- /dev/null +++ b/作業/unit12/dfs/up_1.dat @@ -0,0 +1,9 @@ +0 1 0 0 0 0 0 0 0 + 0 1 0 0 0 0 0 0 + 0 1 1 0 0 0 0 + 0 0 1 1 0 1 + 0 0 0 1 1 + 0 0 0 0 + 0 1 0 + 0 0 + 0 \ No newline at end of file diff --git a/作業/unit12/dfs/up_2.dat b/作業/unit12/dfs/up_2.dat new file mode 100644 index 0000000..1bf3d6e --- /dev/null +++ b/作業/unit12/dfs/up_2.dat @@ -0,0 +1,10 @@ +0 1 1 0 0 0 0 0 0 0 + 0 0 1 1 0 0 0 0 0 + 0 0 0 1 1 0 0 0 + 0 0 0 0 1 0 0 + 0 0 0 1 0 0 + 0 0 0 1 0 + 0 0 1 0 + 0 0 1 + 0 1 + 0 \ No newline at end of file diff --git a/作業/unit12/down_1.dat b/作業/unit12/down_1.dat new file mode 100644 index 0000000..2060205 --- /dev/null +++ b/作業/unit12/down_1.dat @@ -0,0 +1,10 @@ +0 +1 0 +1 0 0 +0 1 0 0 +0 1 0 0 0 +0 0 1 0 0 0 +0 0 1 0 0 0 0 +0 0 0 1 1 0 0 0 +0 0 0 0 0 1 1 0 0 +0 0 0 0 0 0 0 1 1 0 diff --git a/作業/unit12/down_2.dat b/作業/unit12/down_2.dat new file mode 100644 index 0000000..f76d854 --- /dev/null +++ b/作業/unit12/down_2.dat @@ -0,0 +1,9 @@ +0 +1 0 +0 1 0 +0 0 1 0 +0 0 1 0 0 +0 0 0 1 0 0 +0 0 0 1 0 0 0 +0 0 0 0 1 0 1 0 +0 0 0 1 1 0 0 0 0 \ No newline at end of file diff --git a/作業/unit12/shortestPath.c b/作業/unit12/shortestPath.c new file mode 100644 index 0000000..e302293 --- /dev/null +++ b/作業/unit12/shortestPath.c @@ -0,0 +1,174 @@ +/* file name: shortestPath.c */ +/* Q Dijkstra tkD̵u| */ + +#include +#include + +#define MAX_V 100 /*̤j`I*/ +#define VISITED 1 +#define NOTVISITED 0 +#define Infinite 1073741823 + +/* A[1..N][1..N] ϧΪ۾Fx} */ +/* D[i] i=1..N ΨxsY_lIi`I̵uZ */ +/* S[1..N] ΨӰOIO_wgXL */ +/* P[1..N] ΨӰO̪gL`I */ + +long int A[MAX_V+1][MAX_V+1]; +long int D[MAX_V+1]; +long int S[MAX_V+1], P[MAX_V+1]; +int source , sink , N; +int step = 1; + +int top = -1; /*|*/ +int Stack[MAX_V+1]; /*|Ŷ*/ + +void init(void); +int minD(void); +void output_step(void); +void output_path(void); +void push(int); +int pop(void); + +int main(){ + int t,I; + + init(); + output_step(); + printf("\n"); + for (step =2;step <=N; step++) { + /* minD Ǧ^@tϱoD[t] ̤p */ + t = minD(); + S[t] = VISITED; + /* XgLtI|ϸ|Yu`I*/ + for (I=1; I <= N; I++) + if ((S[I] == NOTVISITED) && (D[t]+A[t][I] <= D[I])) { + D[I] = D[t] + A[t][I]; + P[I] = t; + } + output_step(); + printf("\n"); + } + output_path(); + + return 0; +} + +void init(){ + FILE *fptr; + int i,j; + int weight; + + fptr = fopen("shortestPath_2.dat","r"); + if (fptr == NULL) { + perror("shortestPath.dat"); + exit(1); + } + + fscanf(fptr, "%d", &N); /*Ūϧθ`I*/ + for (i=1; i<=N; i++ ) + for (j=1; j<=N; j++) + A[i][j] = Infinite; /*_lA[1..N][1..N]۾Fx}*/ + + while (fscanf(fptr,"%d %d %d", &i, &j, &weight) != EOF) + A[i][j] = weight; /*Ūi`Ij`Ivweight */ + fclose(fptr); + + + + printf("Enter source node : "); + scanf("%d", &source); + printf("Enter sink node : "); + scanf("%d", &sink); + + /* _lU}C*/ + for (i = 1; i <= N; i++) { + S[i] = NOTVISITED; /*UI]|X*/ + D[i] = A[source][i]; /*O_lIܦUI̵uZ*/ + P[i] = source; + } + S[source] = VISITED; /*l_`I]wgX*/ + D[source] = 0; +} + +int minD(){ + int i,t; + long int minimum = Infinite; + + for (i=1; i<=N; i++) + if ((S[i] == NOTVISITED) && D[i] < minimum) { + minimum = D[i]; + t = i; + } + + return t; +} + +/* ܥثeD}CPP}Cp */ +void output_step(){ + int i; + + printf("\n Step #%d",step); + printf("\n================================================\n"); + for (i=1; i<=N; i++) + printf(" D[%d]", i); + printf("\n"); + for (i=1; i<=N; i++) + if (D[i] == Infinite) + printf(" ----"); + else + printf("%6ld",D[i]); + printf("\n================================================\n"); + for (i=1; i<=N; i++) + printf(" P[%d]", i); + printf("\n"); + for (i=1; i<=N;i++) + printf("%6ld", P[i]); +} + +/*̵ܳu|*/ +void output_path(){ + int node = sink; + + /*P_O__lIIεL|ܲI*/ + if ((sink == source) || (D[sink] == Infinite)) { + printf("\nNode %d has no Path to Node %d", source, sink); + return; + } + + printf("\n"); + printf(" The shortest Path from V%d to V%d :", source, sink); + printf("\n------------------------------------------\n"); + + /*ѲI}lNW@gL`IJ|ܨ_l`I*/ + printf(" V%d", source); + while (node != source) { + push(node); + node = P[node]; + } + while(node != sink) { + node = pop(); + printf(" --%ld-->",A[P[node]][node]); + printf("V%d", node); + } + + printf("\n Total length : %ld\n", D[sink]); +} + +void push(int value){ + if (top >= MAX_V) { + printf("Stack overflow!\n"); + exit(1); + }else + Stack[++top] = value; +} + +int pop(){ + if (top < 0) { + printf("Stack empty!\n"); + exit(1); + } + + return Stack[top--]; +} + diff --git a/作業/unit12/shortestPath.exe b/作業/unit12/shortestPath.exe new file mode 100644 index 0000000..a081242 Binary files /dev/null and b/作業/unit12/shortestPath.exe differ diff --git a/作業/unit12/shortestPath_1.dat b/作業/unit12/shortestPath_1.dat new file mode 100644 index 0000000..510ff56 --- /dev/null +++ b/作業/unit12/shortestPath_1.dat @@ -0,0 +1,25 @@ +7 +1 2 4 +1 3 6 +1 4 6 +2 3 1 +2 5 7 +3 5 6 +3 6 4 +4 3 2 +4 6 5 +5 7 -6 +6 5 1 +6 7 8 +2 1 4 +3 1 6 +4 1 6 +3 2 1 +3 4 2 +5 2 7 +5 3 6 +5 6 1 +6 4 5 +6 3 4 +7 5 -6 +7 6 8 diff --git a/作業/unit12/shortestPath_2.dat b/作業/unit12/shortestPath_2.dat new file mode 100644 index 0000000..24e4e93 --- /dev/null +++ b/作業/unit12/shortestPath_2.dat @@ -0,0 +1,15 @@ +8 +1 2 1 +1 3 3 +2 3 1 +2 5 3 +2 4 5 +3 5 1 +3 6 4 +4 5 3 +4 7 8 +5 6 4 +5 7 7 +6 8 7 +7 6 6 +7 8 2 diff --git a/作業/unit12/shortestPath_down_1.dat b/作業/unit12/shortestPath_down_1.dat new file mode 100644 index 0000000..998ac01 --- /dev/null +++ b/作業/unit12/shortestPath_down_1.dat @@ -0,0 +1,7 @@ +0 +4 0 +6 1 0 +6 0 2 0 +0 0 6 0 0 +0 0 4 5 1 0 +0 0 0 0 6 8 0 diff --git a/作業/unit12/shortestPath_down_2.dat b/作業/unit12/shortestPath_down_2.dat new file mode 100644 index 0000000..f76d854 --- /dev/null +++ b/作業/unit12/shortestPath_down_2.dat @@ -0,0 +1,9 @@ +0 +1 0 +0 1 0 +0 0 1 0 +0 0 1 0 0 +0 0 0 1 0 0 +0 0 0 1 0 0 0 +0 0 0 0 1 0 1 0 +0 0 0 1 1 0 0 0 0 \ No newline at end of file diff --git a/作業/unit12/shortestPath_matrix.dat b/作業/unit12/shortestPath_matrix.dat new file mode 100644 index 0000000..8be19ea --- /dev/null +++ b/作業/unit12/shortestPath_matrix.dat @@ -0,0 +1,7 @@ +0 4 6 6 0 0 0 +4 0 1 0 7 0 0 +6 1 0 2 6 4 0 +6 0 2 0 0 5 0 +0 0 6 0 0 1 6 +0 0 4 5 1 0 8 +0 0 0 0 6 8 0 diff --git a/作業/unit12/shortestPath_up_1.dat b/作業/unit12/shortestPath_up_1.dat new file mode 100644 index 0000000..dcb930a --- /dev/null +++ b/作業/unit12/shortestPath_up_1.dat @@ -0,0 +1,7 @@ +0 4 6 6 0 0 0 + 0 1 0 7 0 0 + 0 2 6 4 0 + 0 0 5 0 + 0 1 6 + 0 8 + 0 \ No newline at end of file diff --git a/作業/unit12/shortestPath_up_2.dat b/作業/unit12/shortestPath_up_2.dat new file mode 100644 index 0000000..1bf3d6e --- /dev/null +++ b/作業/unit12/shortestPath_up_2.dat @@ -0,0 +1,10 @@ +0 1 1 0 0 0 0 0 0 0 + 0 0 1 1 0 0 0 0 0 + 0 0 0 1 1 0 0 0 + 0 0 0 0 1 0 0 + 0 0 0 1 0 0 + 0 0 0 1 0 + 0 0 1 0 + 0 0 1 + 0 1 + 0 \ No newline at end of file diff --git a/作業/unit12/up_1.dat b/作業/unit12/up_1.dat new file mode 100644 index 0000000..d8c2c96 --- /dev/null +++ b/作業/unit12/up_1.dat @@ -0,0 +1,9 @@ +0 1 0 0 0 0 0 0 0 + 0 1 0 0 0 0 0 0 + 0 1 1 0 0 0 0 + 0 0 1 1 0 1 + 0 0 0 1 1 + 0 0 0 0 + 0 1 0 + 0 0 + 0 \ No newline at end of file diff --git a/作業/unit12/up_2.dat b/作業/unit12/up_2.dat new file mode 100644 index 0000000..1bf3d6e --- /dev/null +++ b/作業/unit12/up_2.dat @@ -0,0 +1,10 @@ +0 1 1 0 0 0 0 0 0 0 + 0 0 1 1 0 0 0 0 0 + 0 0 0 1 1 0 0 0 + 0 0 0 0 1 0 0 + 0 0 0 1 0 0 + 0 0 0 1 0 + 0 0 1 0 + 0 0 1 + 0 1 + 0 \ No newline at end of file diff --git a/作業/unit13/quicksort.cpp b/作業/unit13/quicksort.cpp new file mode 100644 index 0000000..16928f9 --- /dev/null +++ b/作業/unit13/quicksort.cpp @@ -0,0 +1,74 @@ +/* file name: quickSort.c */ +/* ֳtƧ */ + +#include +void quickSort(int[], int, int, int); +void printDashLine(void); + +int main() +{ + int data[20]; + int size = 0, i; + printf("\nпJ(J 0 ܵ): "); + /* nDJƦrJƦr 0 */ + do { + scanf("%d", &data[size]); + } while(data[size++] != 0); + + printDashLine(); + quickSort(data, 0, size-2, size); + printDashLine(); + + printf("ѤpܤjƧǫ᪺: "); + for (i = 0; i < size-1; i++) + printf("%d ", data[i]); + printf("\n"); + + return 0; +} + +void quickSort(int data[], int left, int right, int size) +{ + /* left P right OƧǸƨ */ + int lbase, rbase, temp, i; + if (left < right) { + lbase = left+1; + while(data[lbase] < data[left]) + lbase++; + rbase = right; + while(data[rbase] > data[left]) + rbase--; + + /* YlbaseprbaseAhƹ */ + while (lbase < rbase) { + temp = data[lbase]; + data[lbase] = data[rbase]; + data[rbase] = temp; + lbase++; + while(data[lbase] < data[left]) + lbase++; + rbase--; + while (data[rbase] > data[left]) + rbase--; + } + + /* lbasejrbaseAhrbaseƻPĤ@ */ + temp = data[left]; + data[left] = data[rbase]; + data[rbase] = temp; + printf("Processing: "); + for (i = 0; i < size-1; i++) + printf("%3d ", data[i]); + printf("\n"); + quickSort(data, left, rbase-1, size); + quickSort(data, rbase+1, right, size); + } +} + +void printDashLine() +{ + for(int i = 0; i < 62; i++) + printf("-"); + printf("\n"); +} + diff --git a/作業/unit13/quicksort.exe b/作業/unit13/quicksort.exe new file mode 100644 index 0000000..b805ae4 Binary files /dev/null and b/作業/unit13/quicksort.exe differ diff --git a/作業/unit13/quicksort_v2.cpp b/作業/unit13/quicksort_v2.cpp new file mode 100644 index 0000000..80ba3e4 --- /dev/null +++ b/作業/unit13/quicksort_v2.cpp @@ -0,0 +1,68 @@ +/* file name: quickSort.c */ +/* ֳtƧ - Ѥjp */ +#include +void quickSort(int[], int, int, int); +void printDashLine(void); +int main() +{ + int data[20]; + int size = 0, i; + printf("\nпJ(J 0 ܵ): "); + /* nDJƦrJƦr 0 */ + do { + scanf("%d", &data[size]); + } while(data[size++] != 0); + + printDashLine(); + quickSort(data, 0, size-2, size); + printDashLine(); + + printf("ѤjܤpƧǫ᪺: "); // קﴣܤr + for (i = 0; i < size-1; i++) + printf("%d ", data[i]); + printf("\n"); + return 0; +} +void quickSort(int data[], int left, int right, int size) +{ + /* left P right OƧǸƨ */ + int lbase, rbase, temp, i; + if (left < right) { + lbase = left+1; + while(data[lbase] > data[left]) // קŸ + lbase++; + rbase = right; + while(data[rbase] < data[left]) // קŸ + rbase--; + + /* YlbaseprbaseAhƹ */ + while (lbase < rbase) { + temp = data[lbase]; + data[lbase] = data[rbase]; + data[rbase] = temp; + lbase++; + while(data[lbase] > data[left]) // קŸ + lbase++; + rbase--; + while (data[rbase] < data[left]) // קŸ + rbase--; + } + + /* lbasejrbaseAhrbaseƻPĤ@ */ + temp = data[left]; + data[left] = data[rbase]; + data[rbase] = temp; + printf("ƧǹL{: "); + for (i = 0; i < size-1; i++) + printf("%3d ", data[i]); + printf("\n"); + quickSort(data, left, rbase-1, size); + quickSort(data, rbase+1, right, size); + } +} +void printDashLine() +{ + for(int i = 0; i < 62; i++) + printf("-"); + printf("\n"); +} diff --git a/作業/unit13/quicksort_v2.exe b/作業/unit13/quicksort_v2.exe new file mode 100644 index 0000000..2ff9314 Binary files /dev/null and b/作業/unit13/quicksort_v2.exe differ diff --git a/作業/unit2/DS2/DS2.zip b/作業/unit2/DS2.zip similarity index 100% rename from 作業/unit2/DS2/DS2.zip rename to 作業/unit2/DS2.zip diff --git a/作業/unit2/DS2/DS2.c b/作業/unit2/DS2/DS2.c index c82bf2b..0f843e5 100644 --- a/作業/unit2/DS2/DS2.c +++ b/作業/unit2/DS2/DS2.c @@ -269,9 +269,9 @@ int main() { // 1x^3-2x^2-1x^1+2x^0 // 1x^5-1x^3-1x^2-1x^1+1x^0 -// 1x^2-100x^0 -// 1x^2+100x^0 +// 1x^2-100x^0 1x^1+100x^0 // 3x^4+9x^3-198x^2+156x^1+360x^0 +// 1x^3+1x^0 int facF[30], facL[30], root[60], ans[60] ,new_ans[8]; find_factor(A, facF, facL, len, &countF, &countL); diff --git a/作業/unit2/DS2/DS2.exe b/作業/unit2/DS2/DS2.exe index ea5f7c1..26eec09 100644 Binary files a/作業/unit2/DS2/DS2.exe and b/作業/unit2/DS2/DS2.exe differ diff --git a/作業/unit2/DS2/DS2_usingLinkedlist.c b/作業/unit2/DS2/DS2_usingLinkedlist.c new file mode 100644 index 0000000..c2aac9c --- /dev/null +++ b/作業/unit2/DS2/DS2_usingLinkedlist.c @@ -0,0 +1,196 @@ +#include +#include +#include +#include +#include + +typedef struct node { + int coef; + int exp; + struct node* rlink; + struct node* llink; +} node; +node *head, *tail, *current, *prev, *temp; + +void init_f() { + head = (node *)malloc(sizeof(node)); + tail = (node *)malloc(sizeof(node)); + head->rlink = tail; + tail->llink = head; +} + +void read_poly(char str[] ){ + int argCount ; + while (1) { + + node* newNode = (node*)malloc(sizeof(node)); + + argCount = sscanf(str, "%dx^%d%s", &newNode->coef, &newNode->exp, str); + + if (argCount >= 2) { // \ŪYƩM + + newNode->llink = tail->llink; + newNode->rlink = tail; + tail->llink->rlink = newNode; + tail->llink = newNode; + + if (argCount == 2) { + break ; + } + + } else { + if(!isdigit(newNode->coef)){ + newNode->exp = 0; + + newNode->llink = tail->llink; + newNode->rlink = tail; + tail->llink->rlink = newNode; + tail->llink = newNode; + + break ; + + }else{ +// printf("newNode->coef = %d\n",newNode->coef); +// printf("isdigit(newNode->coef) = %d",isdigit(newNode->coef)); + + free(newNode); + break ; + } + + } + } +} + +void clear_node(){ + // O + current = head->rlink; + while (current != tail) { + temp = current; + current = current->rlink; + free(temp); + } + free(head); + free(tail); +} + + +void show(int p[], int n, int mode){ + int i; + if(mode == 0){ + printf("\n{p(x)= "); + current = head->rlink; + while (current != tail) { + if(abs(current->coef)>1){ + printf("%s%d", current->coef > 1? "":"\b",current->coef); + }else if(current->coef == -1){ + printf("%s", current->exp == 0? "\b-1":"\b-"); + } + switch(current->exp){ + case 0: + if(current->coef == 1 ) printf("1+"); + else printf("+"); + break; + case 1: + printf("x+"); + break; + default: + printf("x^%d+",current->exp); + } + current = current->rlink; + } + printf("\b "); + + }else { /* mode==1Aܩұo */ + for (i = 0; i < n; i++) printf("%dB",p[i]); + if (n > 0) printf("\b\b "); + } + +} + +int findRoot(int q[]) /* ڡAұoѦsJq[]A^ǮڪӼ */ +{ + int r, c = 0, i, j, k, sum; + int sign[2] = {1,-1}; + + current = tail->llink; + r = abs(current->coef); /* X̧CY */ + + if (current->exp != 0) { /* ̧C >= 1Ah0i */ + if ((i = current->exp) > 0) q[c++] = 0; /* ̧CƳ]i */ + current = head->rlink; + while(current!=tail){ + current->exp -= i; /* Ҧƴhi */ + current = current->rlink; + } + } + + +// r = abs(p[2*p[0]]); /* X̧CY */ + + for (i = 1; i <= r; i++) { /* Ҽ{㰣r]iA`Nt */ + if (r%i != 0) continue; /* 㰣riNLA~Ҽ{U@i */ + + for (j = 0; j < 2; j++) { /* j0ANҼ{+iҡFj1ANҼ{-ip */ + for (sum = 0, current = head->rlink ; current!= tail ; current = current->rlink) /* pC@G(Y*x^)ò֥[sum */ + sum += current->coef *(int)(pow(sign[j]*i,current->exp)); + if (sum == 0) q[c++] = sign[j]*i; /* bingo! o{XG󪺾ƮڡANgJq}C */ + } + } + + return c; +} + + +int main() { + char str[100]; + int poly_num , *q ,c , high; + init_f(); + + printf("\n*** ѦhƮ ***\n\nJh ==> "); + + if (fgets(str, sizeof(str), stdin) == NULL) { + printf("J~I\n"); + return 1; + } + + +/* + 1x^2-100x^0 + 1x^3-2x^2-1x^1+2x^0 + 1x^3-7x^2+4x^1+12x^0 + 1x^4+3x^3-66x^2+52x^1+120x^0 + 3x^4+9x^3-198x^2+156x^1+360x^0 + 1x^2-1x^1 + 2x^ 3 -201 x^2+ 97 x^1 +300 + 2x^12-195x^11-500x^10 + 6x^4 - 1x^3 -25x^2 + 4x^1 + 4 + 1x^5-1x^3-1x^2-1x^1+1x^0 + 1x^5+1x^3+1x^2+1x^1+1x^0 + 1x^3+1x^0 +*/ + + read_poly(str); + + current = head->rlink; + high= current->exp; + + show(q,c,0); + + q = (int *)malloc((high + 1) *sizeof(int)); /* p[1]̰ơA̦ȳЫبŶ}CsҨDoƮ */ + + c = findRoot(q); + + if (c > 0) { + printf("\n\nѱoƮڬG"); + show(q,c,1); + } + else + printf("\n\nƮڤsb\n"); + + + + clear_node(); + + + return 0; +} diff --git a/作業/unit2/Makefile.win b/作業/unit2/Makefile.win new file mode 100644 index 0000000..b8ef98a --- /dev/null +++ b/作業/unit2/Makefile.win @@ -0,0 +1,28 @@ +# Project: Project1 +# Makefile created by Dev-C++ 5.11 + +CPP = g++.exe +CC = gcc.exe +WINDRES = windres.exe +OBJ = poly-integer-root.o +LINKOBJ = poly-integer-root.o +LIBS = -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib" -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/lib" -static-libgcc +INCS = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include" +CXXINCS = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include/c++" +BIN = Project1.exe +CXXFLAGS = $(CXXINCS) +CFLAGS = $(INCS) +RM = rm.exe -f + +.PHONY: all all-before all-after clean clean-custom + +all: all-before $(BIN) all-after + +clean: clean-custom + ${RM} $(OBJ) $(BIN) + +$(BIN): $(OBJ) + $(CC) $(LINKOBJ) -o $(BIN) $(LIBS) + +poly-integer-root.o: poly-integer-root.c + $(CC) -c poly-integer-root.c -o poly-integer-root.o $(CFLAGS) diff --git a/作業/unit2/NODUMMY.c b/作業/unit2/NODUMMY.c new file mode 100644 index 0000000..3ca5721 --- /dev/null +++ b/作業/unit2/NODUMMY.c @@ -0,0 +1,90 @@ +#include +#include + +void output_P(int P[]); +void Padd(int A[], int B[], int C[],int lenA,int lenB); + +void output_P(int P[]) { + int i; + for(i=1;iB[j]){ + C[k++] = A[i++]; + C[k++] = A[i++]; + count++; + } + if(A[i] + +int main(){ + int A[10]={0}; + int *B=(int *)malloc(10*sizeof(int)); + printf("A=%d\n",sizeof(A)); + printf("B=%d\n",sizeof(B)); + B=&A; + printf("B=%d\n",sizeof(B)); + return 0; +} diff --git a/作業/unit2/Untitled1.o b/作業/unit2/Untitled1.o new file mode 100644 index 0000000..54e9a9e Binary files /dev/null and b/作業/unit2/Untitled1.o differ diff --git a/作業/unit2/claude.c b/作業/unit2/claude.c new file mode 100644 index 0000000..cfef293 --- /dev/null +++ b/作業/unit2/claude.c @@ -0,0 +1,94 @@ +#include +#include +#include + +void count_root(int arrR[], int arrL[], int ans[], int countF, int countL, int *len_ans) { + int i, j, k = 0; + for (i = 0; i < countF; i++) { + for (j = 0; j < countL; j++) { + if (arrL[j] != 0 && arrR[i] != 0 && arrL[j] % arrR[i] == 0) { + ans[k++] = arrL[j] / arrR[i]; + } + } + } + *len_ans = k; +} + +void plus_root_negative(int arr[], int *len) { + int i, new_len = *len * 2; + for (i = 0; i < *len; i++) { + arr[*len + i] = -arr[i]; + } + *len = new_len; +} + +void find_factor(int num, int fac[], int *count) { + int i, j = 0; + for (i = 1; i <= sqrt(abs(num)); i++) { + if (num % i == 0) { + fac[j++] = i; + if (i != num / i) { + fac[j++] = num / i; + } + } + } + *count = j; +} + +double evaluate_polynomial(int A[], int len, double x) { + double result = 0; + int i; + for (i = 0; i < len; i += 2) { + result += A[i] * pow(x, A[i+1]); + } + return result; +} + +void Substitute(int len_root, int arr[], int ans[], int A[], int len_A, int *len_ans) { + int i, j = 0; + double result; + for (i = 0; i < len_root; i++) { + result = evaluate_polynomial(A, len_A, arr[i]); + if (fabs(result) < 1e-10) { // ϥΤpHȨӳBzBI~t + ans[j++] = arr[i]; + } + } + *len_ans = j; +} + +int main() { + int i, len, countF, countL, len_root = 0, len_ans = 0; + int A[] = { 2, 2, 1, 0, -100}; // x^3 - 2x^2 - x + 2 + int facF[100], facL[100], root[200], ans[100]; + len = sizeof(A) / sizeof(A[0]); + + find_factor(abs(A[0]), facF, &countF); + find_factor(abs(A[len-2]), facL, &countL); + + printf("̰趵]Ƭ: "); + for (i = 0; i < countF; i++) { + printf("%d ", facF[i]); + } + printf("\n`ƶ]Ƭ: "); + for (i = 0; i < countL; i++) { + printf("%d ", facL[i]); + } + printf("\n"); + + count_root(facF, facL, root, countF, countL, &len_root); + plus_root_negative(root, &len_root); + + printf("i઺ڡG\n"); + for (i = 0; i < len_root; i++) { + printf("root[%d] = %d\n", i, root[i]); + } + + Substitute(len_root, root, ans, A, len, &len_ans); + + printf("hڡG\n"); + for (i = 0; i < len_ans; i++) { + printf("x = %d\n", ans[i]); + } + + return 0; +} diff --git a/作業/unit2/claude.exe b/作業/unit2/claude.exe new file mode 100644 index 0000000..8556cb4 Binary files /dev/null and b/作業/unit2/claude.exe differ diff --git a/作業/unit2/claude.o b/作業/unit2/claude.o new file mode 100644 index 0000000..a7c7a8b Binary files /dev/null and b/作業/unit2/claude.o differ diff --git a/作業/unit2/main.c b/作業/unit2/main.c new file mode 100644 index 0000000..4973ad2 --- /dev/null +++ b/作業/unit2/main.c @@ -0,0 +1,59 @@ +#include +#include +#include +//#define f(x) (x*x*x-2*x*x-x+2) +//#define f(x) (x*x-100) +#define f(x) (3*x*x*x*x+9*x*x*x-198*x*x+156*x+360) + +void binary_search ( int *ans){ + int count = 1000 , i=0; + double mid , lower=-15 , upper=20; + while ((f(mid)) != 0 && i < count ) { + mid = (lower + upper) / 2.0; + + printf("#%d\t[%f,%f]\t=%f\n",i+1,lower,upper,mid); + + if (fabs(f(mid)) == 0) { + break; + } + + i++; + if ( f(mid) * f(lower) < 0) { + upper = mid; + } else { + lower = mid; + } + }*ans = mid; +} + +void Exhaustive(int a, int b, int *ans, int *count) { + *count = 0; + int i; + for (i = a; i <= b; i++) { + if (f(i) == 0) { + ans[*count] = i; + (*count)++; + } + } +} + +int main() { + + int i , x , lower=-200 , upper=200 ; + int ans[10]; + int *count; + + Exhaustive(lower,upper,ans,&count); + if (count > 0) { + printf("*** ѦhƮ ***\n"); + printf("\n{p(x)= 3^4+9x^3-198x^2+156+360\n"); + printf("\nѱoƮڬ"); + for (i = 0; i < count; i++) { + printf(" %d ", ans[i]); + } + } else { + printf("bwd򤺨SƸѡC\n"); + } + + return 0; +} diff --git a/作業/unit2/main.o b/作業/unit2/main.o new file mode 100644 index 0000000..876b89e Binary files /dev/null and b/作業/unit2/main.o differ diff --git a/作業/unit2/oddMagic.c b/作業/unit2/oddMagic.c new file mode 100644 index 0000000..926f51c --- /dev/null +++ b/作業/unit2/oddMagic.c @@ -0,0 +1,58 @@ +#include +#include +#define MAX 15 + +int Square[MAX][MAX]; +int N; + +int main(){ + int i , j ,row=0 , col=0 , num=2; + do { + printf("\nEnter odd matrix size : "); + scanf("%d",&N); + + if( N % 2 == 0 || N <= 0 || N > 15){ + printf("should be > 0 and 15 odd number"); + }else{ + break; + } + }while(1); + + while(1){ + Square[0][(N-1)/2] = 1; + col=(N-1)/2; + if((row-1)<0 && (col+10 && (col+10 && (col+1N*N) + break; + } + +// for(i=0;i +#include +#include +#include + +#define MAX 10 + +// xsC@c +struct Term { + int coefficient; // Y + int exponent; // +}; + +//pi઺ +void count_root(int arrR[],int arrL[],int ans[],int countF,int countL ,int *len_ans){ + int i , j ,k=0; + for(i=0;i1 && A[i+1]==1){ + printf("x^%d",A[i]); //Ƥj1 YƵ1 + }else if(A[i]==1 && A[i+1]!=1){ //=1 YƤ1 + printf("%dx",A[i+1]); + }else if(A[i]==0 && A[i+1]!=1){ //=0 YƤ1 + printf("%d",A[i+1]); + }else if(A[i]==1 && A[i+1]==1){ //=1 Y=1 + printf("x"); + }else if(A[i]==1 && A[i+1]==-1){ //=1 Y=-1 + printf("-x"); + }flag_Max = 1; //X=1 + }else if(flag_x == 1 && flag_const==0){// x@ + if(A[i+1]>0){ // x@ + if(A[i+1]==1){ + printf("+x",A[i+1]); + }else{ + printf("+%dx",A[i+1]); + } + }else if(A[i+1]<0){ //x@t + if(A[i+1]==-1){ + printf("-x",A[i+1]); + }else{ + printf("%dx",A[i+1]); + } + } + }else if(flag_const==1){ // `ƶ + if(A[i+1]>0){ //`ƶ>0 + printf("+%d",A[i+1]); + }else if(A[i+1]<0) { //`ƶ<0 + printf("%d",A[i+1]); + } + }else if(flag_Max==1 && flag_x==0 && flag_const==0) { //h + if(A[i+1]>0){ //Y>1 + if(A[i+1]==1){ //Y=1 + printf("x^%d",A[i]); + }else{ //YƤ1 + printf("+%dx^%d",A[i+1],A[i]); + } + }else if(A[i+1]<0){ //Y<1 + if(A[i+1]==-1){ //Y=-1 + printf("-x^%d",A[i]); + }else{ //YƤ1 + printf("%dx^%d",A[i+1],A[i]); + } + } + }i++; + } + printf("\n"); +} + +int main() { + int i,j, len, countF, countL, len_root, len_ans ,len_new ; + char input[100]; + struct Term terms[MAX]; + int term_count = 0; + printf("\n*** ѦhƮ ***\n"); + + // 1. ŪJ + printf("\nпJhG "); + fgets(input, sizeof(input), stdin); + input[strcspn(input, "\n")] = 0; // + + // 2. BzC@ + char *ptr = input; + while (*ptr && term_count < MAX) { + int coef = 0, exp = 0; + int is_negative = 0; + + // ˬdt + if (*ptr == '-') { + is_negative = 1; + ptr++; + } else if (*ptr == '+') { + ptr++; + } + + // Lťզr + while (isspace(*ptr)) ptr++; + + // 3. ѪRC@ + if (sscanf(ptr, "%dx^%d", &coef, &exp) == 2) { + // 㪺 ax^b Φ + ptr = strchr(ptr, '^') + 1; + } else if (sscanf(ptr, "%dx", &coef) == 1) { + // ax ΦAƬ1 + exp = 1; + ptr = strchr(ptr, 'x') + 1; + } else if (sscanf(ptr, "x^%d", &exp) == 1) { + // x^b ΦAYƬ1 + coef = 1; + ptr = strchr(ptr, '^') + 1; + } else if (strncmp(ptr, "x", 1) == 0) { + // W xAYƬ1AƬ1 + coef = 1; + exp = 1; + ptr++; + } else { + // ]O`ƶ + sscanf(ptr, "%d", &coef); + exp = 0; + while (isdigit(*ptr)) ptr++; + } + + // 4. Bzt + if (is_negative) { + coef = -coef; + } + + // 5. xsG + terms[term_count].coefficient = coef; + terms[term_count].exponent = exp; + term_count++; + + // XeH]Ωոա^ +// printf(" %d: Y = %d, = %d\n", term_count, coef, exp); + + // ʨU@ '+' '-' Ÿ + while (*ptr && *ptr != '+' && *ptr != '-') ptr++; + } + +// int *A = (int*)malloc(((term_count*2)+1) * sizeof(int)) ; + len = ((term_count*2)+1); + int A[len]; + +// printf("term_count=%d\n",term_count); +// printf("((term_count*2)+1)=%d\n",((term_count*2)+1)); +// printf("sizeof(A)=%d\n",sizeof(A)); + + A[0]=term_count; + for (i = 1 , j=0 ; i < term_count*2 ; i++ , j++ ){ + A[i]= terms[j].exponent; + A[i+1]= terms[j].coefficient; +// printf("A[%d]=%d\n",i,terms[j].exponent); +// printf("A[%d]=%d\n",i+1,terms[j].coefficient); + i++; + } + +// printf("A[]= "); +// for (i = 0; i < len; i++) { +// printf(" %d ",A[i]); +// } +// printf("\n"); + +// 1x^3-2x^2-1x^1+2x^0 +// 1x^5-1x^3-1x^2-1x^1+1x^0 +// 1x^2-100x^0 1x^1+100x^0 +// 3x^4+9x^3-198x^2+156x^1+360x^0 + + int facF[30], facL[30], root[60], ans[60] ,new_ans[8]; + find_factor(A, facF, facL, len, &countF, &countL); + +// printf("̰趵]Ƭ: "); +// for (i = 0; i < countF; i++) { +// printf("%d ", facF[i]); +// } +// printf("\n`ƶ]Ƭ: "); +// for (i = 0; i < countL; i++) { +// printf("%d ", facL[i]); +// } +// printf("\n"); + + count_root(facF, facL, root, countF, countL, &len_root); + plus_root_negative(root, &len_root); + +// printf("i઺ڡG\n"); +// for (i = 0; i < len_root; i++) { +// printf("root[%d] = %d\n", i, root[i]); +// } + + //Xh + output(A,len); + // pi઺ + Substitute(len_root, root, ans, A, len, &len_ans); + + //hl + remove_duplicates(ans,len_ans,new_ans,&len_new); + + if(len_new==0){ + printf("\nƮڤsb"); + return 1 ; + } + + if(len_new>0){ + printf("\nѱoƮڬG"); + for (i = 0; i < len_new; i++) { + if(i +#include +#define DUMMY -1 + +void output_P(int P[], int size); +void Padd(int A[], int B[], int C[]); +char compare(int a, int b); + +void output_P(int P[], int size) { + int i; + int first = 1; + for (i = 2; i < size; i += 2) { + if (P[i+1] != 0) { + if (!first) { + printf(" + "); + } + if (P[i] > 1) { + printf("%dx^%d", P[i+1], P[i]); + } else if (P[i] == 1) { + printf("%dx", P[i+1]); + } else { + printf("%d", P[i+1]); + } + first = 0; + } + } + if (first) { // pGh0 + printf("0"); + } + printf("\n"); +} + +void Padd(int A[], int B[], int C[]) { + int i = 2, j = 2, k = 2; + int sizeA = A[1], sizeB = B[1]; + while (i < sizeA * 2 + 2 || j < sizeB * 2 + 2) { + if (i >= sizeA * 2 + 2) { + C[k] = B[j]; + C[k+1] = B[j+1]; + j += 2; + } else if (j >= sizeB * 2 + 2) { + C[k] = A[i]; + C[k+1] = A[i+1]; + i += 2; + } else if (A[i] > B[j]) { + C[k] = A[i]; + C[k+1] = A[i+1]; + i += 2; + } else if (A[i] < B[j]) { + C[k] = B[j]; + C[k+1] = B[j+1]; + j += 2; + } else { + C[k] = A[i]; + C[k+1] = A[i+1] + B[j+1]; + if (C[k+1] == 0) { + k -= 2; // pGYƬ0AK[o@ + } + i += 2; + j += 2; + } + k += 2; + } + C[1] = (k - 2) / 2; + C[0] = DUMMY; + printf("A: "); + output_P(A, sizeA * 2 + 2); + printf("B: "); + output_P(B, sizeB * 2 + 2); + printf("C = A + B: "); + output_P(C, k); +} + +char compare(int a, int b) { + if (a > b) return '>'; + if (a < b) return '<'; + return '='; +} + +int main() { + int A[] = { DUMMY, 4, 4, 5, 3, 2, 2, 3, 0, 2 }; + int B[] = { DUMMY, 3, 3, 6, 1, 5, 0, 1 }; + int C[13] = { DUMMY }; + + Padd(A, B, C); + return 0; +} diff --git a/作業/unit2/polynominal.o b/作業/unit2/polynominal.o new file mode 100644 index 0000000..ab31197 Binary files /dev/null and b/作業/unit2/polynominal.o differ diff --git a/作業/unit2/test.c b/作業/unit2/test.c new file mode 100644 index 0000000..4b07c1a --- /dev/null +++ b/作業/unit2/test.c @@ -0,0 +1,67 @@ +#include +#include +#define MAX 15 + +int Square[MAX][MAX]; +int N; + +void printSquare() { + int i ,j; + for (i = 0; i < N; i++) { + for (j = 0; j < N; j++) { + printf("%d\t", Square[i][j]); + } + printf("\n"); + } +} + +int main() { + int row, col, num, i ,j; + + do { + printf("\nпJ_Ƥ}jp (1-15_): "); + scanf("%d", &N); + + if (N % 2 == 0 || N <= 0 || N > 15) { + printf("J~GO1-15_\n"); + } else { + break; + } + } while (1); + + // lƤ} + for (i = 0; i < N; i++) { + for (j = 0; j < N; j++) { + Square[i][j] = 0; + } + } + + row = 0; + col = N / 2; +// printf("col=%d\n", col); + num = 1; + + while (num <= N * N) { + Square[row][col] = num; + + // ˬdU@Ӧm + int nextRow = (row - 1 + N) % N; + int nextCol = (col + 1) % N; + + if (Square[nextRow][nextCol] != 0) { + // pGU@ӦmwQΡAhU + row = (row + 1) % N; + } else { + // _hAʨkWm + row = nextRow; + col = nextCol; + } + + num++; + } + + printf("\n%d x %d ]}:\n\n", N, N); + printSquare(); + + return 0; +} diff --git a/作業/unit2/test.o b/作業/unit2/test.o new file mode 100644 index 0000000..4396c70 Binary files /dev/null and b/作業/unit2/test.o differ diff --git a/作業/unit3/DS3.cpp b/作業/unit3/DS3.cpp new file mode 100644 index 0000000..e951a9d --- /dev/null +++ b/作業/unit3/DS3.cpp @@ -0,0 +1,267 @@ +#include +#include +#include +#include +#include +#define MAX 100 + +// === ܼƫŧi === +char input[MAX]; +char postfix[MAX]; +char postfix_1[MAX]; //ܥ +char stack[MAX]; +double numStack[MAX]; +int top = -1; +int numTop = -1; + +// === 禡ŧi === +int get_priority(char op); +int is_operator(char c); +double calculate(double a, double b, char op); +void convert_to_postfix(); +double evaluate_postfix(); +double evaluate_infix(char *expr); +double parse_number(char **expr); + +int get_priority(char c){ + if(c=='+' || c=='-'){ + return 1; + }else if(c=='*' || c=='/'){ + return 2; + }else if(c=='^'){ + return 3; + }else{ + return 0; + } +} + +// === ˬdrO_Bl === +int is_operator(char c) { + return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^'); +} + +// === B === +double calculate(double a, double b, char op) { + switch(op) { + case '+': return a + b; + case '-': return a - b; + case '*': return a * b; + case '/': + if(b != 0) return a / b; + printf("~GƤରsI\n"); + exit(1); + case '^': return pow(a, b); + default: return 0; + } +} + +//ܥ +void convert_to_postfix_forprint() { + int i = 0, j; + int postfix_index = 0; + top = -1; + char number_str[MAX]; + int is_negative; + + while(input[i] != '\0') { + if(isdigit(input[i]) || input[i] == '.' || (input[i] == '-' && (i == 0 || input[i-1] == '(' || is_operator(input[i-1])))) { + // BzƦr]]Atơ^ + is_negative = 0; + int num_len = 0; + + // ˬdO_t + if(input[i] == '-') { + is_negative = 1; + i++; + } + + // Ʀrr + while(input[i] != '\0' && (isdigit(input[i]) || input[i] == '.')) { + number_str[num_len++] = input[i++]; + } + number_str[num_len] = '\0'; + i--; // ^h@ӦmA]~h while |A[@ + + // XƦr + printf("%s ", number_str); + if(is_negative) { + printf("- "); + } + + // NƦr[JǪF + for(j = 0; j < num_len; j++) { + postfix_1[postfix_index++] = number_str[j]; + } + postfix_1[postfix_index++] = ' '; + if(is_negative) { + postfix_1[postfix_index++] = '-'; + postfix_1[postfix_index++] = ' '; + } + } + else if(input[i] == '(') { + stack[++top] = input[i]; + } + else if(input[i] == ')') { + while(top >= 0 && stack[top] != '(') { + printf("%c ", stack[top]); + postfix_1[postfix_index++] = stack[top]; + postfix_1[postfix_index++] = ' '; + top--; + } + if(top >= 0) top--; + } + else if(is_operator(input[i])) { + // pGOBztƪ + if(!(input[i] == '-' && (i == 0 || input[i-1] == '(' || is_operator(input[i-1])))) { + while(top >= 0 && stack[top] != '(' && + (get_priority(stack[top]) > get_priority(input[i]) || + (get_priority(stack[top]) == get_priority(input[i]) && input[i] != '^'))) { + printf("%c ", stack[top]); + postfix_1[postfix_index++] = stack[top]; + postfix_1[postfix_index++] = ' '; + top--; + } + stack[++top] = input[i]; + } + } + i++; + } + + while(top >= 0) { + printf("%c ", stack[top]); + postfix_1[postfix_index++] = stack[top]; + postfix_1[postfix_index++] = ' '; + top--; + } + postfix_1[postfix_index] = '\0'; + printf("\n"); +} + +// === ഫǪF === +//p +void convert_to_postfix() { + int i = 0 , j; + int postfix_index = 0; + top = -1; + + while(input[i] != '\0') { + if(isdigit(input[i]) || input[i] == '.' || (input[i] == '-' && (i == 0 || input[i-1] == '(' || is_operator(input[i-1])))) { // ˬdO_ƦrBpIάOt]BOF}lAκbAιBū᭱^ + char *end; + double num = strtod(&input[i], &end); //strtod r괫BI + int len = end - &input[i]; //pƦrrꪺ ƦrݪO}Om +// printf("%.1f ", num); + for(j = 0; j < len; j++) { + postfix[postfix_index++] = input[i+j]; + } + postfix[postfix_index++] = ' '; + i += len - 1; + } + else if(input[i] == '(') { + stack[++top] = input[i]; + } + else if(input[i] == ')') { + while(top >= 0 && stack[top] != '(') { +// printf("%c ", stack[top]); + postfix[postfix_index++] = stack[top]; + postfix[postfix_index++] = ' '; + top--; + } + if(top >= 0) top--; + } + else if(is_operator(input[i])) { + while(top >= 0 && stack[top] != '(' && (get_priority(stack[top]) > get_priority(input[i]) || (get_priority(stack[top]) == get_priority(input[i]) && input[i] != '^'))) { +// printf("%c ", stack[top]); + postfix[postfix_index++] = stack[top]; + postfix[postfix_index++] = ' '; + top--; + } + stack[++top] = input[i]; + } + i++; + } + + while(top >= 0) { +// printf("%c ", stack[top]); + postfix[postfix_index++] = stack[top]; + postfix[postfix_index++] = ' '; + top--; + } + postfix[postfix_index] = '\0'; +// printf("\n"); +} + +// === pǪF === +double evaluate_postfix() { + int i; + numTop = -1; + char *token = strtok(postfix, " "); + +// printf("\npL{G\n"); + + while(token != NULL) { +// printf("BzаOG'%s'\n", token); + + if(isdigit(token[0]) || (token[0] == '-' && isdigit(token[1]))) { + double num = atof(token); + numStack[++numTop] = num; +// printf("JƦrG%.2f\n", num); + } + else if(is_operator(token[0])) { + if(numTop < 1) { + printf("Bl '%c' ʤ֨B⤸\n", token[0]); + exit(1); + } + double b = numStack[numTop--]; + double a = numStack[numTop--]; + double result = calculate(a, b, token[0]); + numStack[++numTop] = result; +// printf("pG%.2f %c %.2f = %.2f\n", a, token[0], b, result); + } + else { + printf("~GаO '%s'\n", token); + exit(1); + } + +// printf("e|G"); +// for(i = 0; i <= numTop; i++) { +// printf("%.2f ", numStack[i]); +// } +// printf("\n\n"); + + token = strtok(NULL, " "); + } + + if(numTop != 0) { +// printf("~Gp⵲|Ѿl %d Ӥ\n", numTop + 1); + exit(1); + } + return numStack[numTop]; +} + +int main() { + + printf("пJǪܦ(䴩+-*/^()B) => "); + + fgets(input, MAX, stdin); + input[strcspn(input, "\n")] = 0; + + printf("\nǪܪkG "); + convert_to_postfix_forprint(); //ܥ + convert_to_postfix(); + double postfix_result = evaluate_postfix(); + printf("\nB⵲GG%.4f", postfix_result); + + printf("\t(TȬG"); + if(strcmp(input,"10+20*(50-30)/2^4-6*8")==0){ + printf("%g",10+20*(50-30)/pow(2,4)-6*8); + }else if(strcmp(input,"10+20*(-50+30)/-2^4-6*8")==0){ + printf("%g",10+20*(-50+30)/pow(-2,4)-6*8); + }else if(strcmp(input,"10.5+20.8*(50.1-30.6)/2.5^4-6.6*8.2")==0){ + printf("%g",10.5+20.8*(50.1-30.6)/pow(2.5,4)-6.6*8.2); + }else if(strcmp(input,"10.5+20.8*(-50.1+30.6)/2.5^-4-6.6*8.2")==0){ + printf("%g",10.5+20.8*(-50.1+30.6)/pow(2.5,-4)-6.6*8.2); + }printf(")"); + + + return 0; +} diff --git a/作業/unit3/DS3.exe b/作業/unit3/DS3.exe index 0f87075..f008051 100644 Binary files a/作業/unit3/DS3.exe and b/作業/unit3/DS3.exe differ diff --git a/作業/unit3/DS3_try.c b/作業/unit3/DS3_try.c new file mode 100644 index 0000000..fc6a257 --- /dev/null +++ b/作業/unit3/DS3_try.c @@ -0,0 +1,116 @@ +#include +#include +#define MAX 50 +char infix_q[MAX]; +int compare(char stack_o , char infix_o); +void infix_to_postfix(); + + + +int get_priority(char c){ + if(c=='+' || c=='-'){ + return 1; + }else if(c=='*' || c=='/'){ + return 2; + }else if(c=='^'){ + return 3; + }else{ + return 0; + } +} + +int main(){ + int i=0; + for(i=0;i= index_i/2 ? 1 : 0; +} + + +void infix_to_postfix() { + int rear = 0, top = 0, flag = 0, i = 0; + char stack_t[MAX]; + int tag = 1; + for(i = 0; i < MAX; i++) { + stack_t[i] = '\0'; + } + + + fgets(infix_q, MAX, stdin); + infix_q[strcspn(infix_q, "\n")] = 0; + + i = 0; + while(infix_q[i] != '\0') { + i++; + rear++; + } + infix_q[rear] = '#'; + printf("\tǪܪkG"); + stack_t[top] = '#'; + + for(flag = 0; flag <= rear; flag++) { + tag = 1; + switch(infix_q[flag]) { + case ')': + while(stack_t[top] != '(') { + printf("%c", stack_t[top--]); + } + top--; + break; + case '#': + while(stack_t[top] != '#') { + printf("%c", stack_t[top--]); + } + break; + case '(': + case '*': + case '/': + case '^': + while(compare(stack_t[top], infix_q[flag]) == 1) { + printf("%c", stack_t[top--]); + } + stack_t[++top] = infix_q[flag]; + break; + case '+': + case '-': + if(tag==1){ + while(compare(stack_t[top], infix_q[flag]) == 1) { + printf("%c", stack_t[top--]); + } + stack_t[++top] = infix_q[flag]; + break; + }else if(tag==2){ + + } + + + default: + if(infix_q[flag] != ' ') { // Ů + printf("%c", infix_q[flag]); + } + break; + } + } +} diff --git a/作業/unit3/DS3_try.o b/作業/unit3/DS3_try.o new file mode 100644 index 0000000..93c86cf Binary files /dev/null and b/作業/unit3/DS3_try.o differ diff --git a/作業/unit3/Makefile.win b/作業/unit3/Makefile.win new file mode 100644 index 0000000..e2b0299 --- /dev/null +++ b/作業/unit3/Makefile.win @@ -0,0 +1,28 @@ +# Project: Project1 +# Makefile created by Dev-C++ 5.11 + +CPP = g++.exe +CC = gcc.exe +WINDRES = windres.exe +OBJ = ../../../ѮvЧ/@~/unit3/DS3.o +LINKOBJ = ../../../ѮvЧ/@~/unit3/DS3.o +LIBS = -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib" -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/lib" -static-libgcc +INCS = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include" +CXXINCS = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include/c++" +BIN = Project1.exe +CXXFLAGS = $(CXXINCS) +CFLAGS = $(INCS) +RM = rm.exe -f + +.PHONY: all all-before all-after clean clean-custom + +all: all-before $(BIN) all-after + +clean: clean-custom + ${RM} $(OBJ) $(BIN) + +$(BIN): $(OBJ) + $(CC) $(LINKOBJ) -o $(BIN) $(LIBS) + +../../../ѮvЧ/@~/unit3/DS3.o: ../../../ѮvЧ/@~/unit3/DS3.c + $(CC) -c ../../../ѮvЧ/@~/unit3/DS3.c -o ../../../ѮvЧ/@~/unit3/DS3.o $(CFLAGS) diff --git a/作業/unit3/Project1.dev b/作業/unit3/Project1.dev new file mode 100644 index 0000000..e589c42 --- /dev/null +++ b/作業/unit3/Project1.dev @@ -0,0 +1,62 @@ +[Project] +FileName=Project1.dev +Name=Project1 +Type=1 +Ver=2 +ObjFiles= +Includes= +Libs= +PrivateResource= +ResourceIncludes= +MakeIncludes= +Compiler= +CppCompiler= +Linker= +IsCpp=0 +Icon= +ExeOutput= +ObjectOutput= +LogOutput= +LogOutputEnabled=0 +OverrideOutput=0 +OverrideOutputName= +HostApplication= +UseCustomMakefile=0 +CustomMakefile= +CommandLine= +Folders= +IncludeVersionInfo=0 +SupportXPThemes=0 +CompilerSet=0 +CompilerSettings=0000000000000000000000000 +UnitCount=1 + +[VersionInfo] +Major=1 +Minor=0 +Release=0 +Build=0 +LanguageID=1033 +CharsetID=1252 +CompanyName= +FileVersion= +FileDescription=Developed using the Dev-C++ IDE +InternalName= +LegalCopyright= +LegalTrademarks= +OriginalFilename= +ProductName= +ProductVersion= +AutoIncBuildNr=0 +SyncProduct=1 + +[Unit1] +FileName=..\..\..\ѮvЧ\@~\unit3\DS3.c +CompileCpp=0 +Folder= +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd= + diff --git a/作業/unit3/Project1.exe b/作業/unit3/Project1.exe new file mode 100644 index 0000000..2fe8fe9 Binary files /dev/null and b/作業/unit3/Project1.exe differ diff --git a/作業/unit3/Project1.layout b/作業/unit3/Project1.layout new file mode 100644 index 0000000..ef35a90 --- /dev/null +++ b/作業/unit3/Project1.layout @@ -0,0 +1,13 @@ +[Editor_1] +CursorCol=1 +CursorRow=1 +TopLine=1 +LeftChar=1 +[Editor_0] +CursorCol=1 +CursorRow=47 +TopLine=28 +LeftChar=1 +[Editors] +Order=0 +Focused=0 diff --git a/作業/unit3/claude.c b/作業/unit3/claude.c new file mode 100644 index 0000000..ca92024 --- /dev/null +++ b/作業/unit3/claude.c @@ -0,0 +1,274 @@ +#include +#include +#include +#include +#include +#define MAX 100 + +// === ܼƫŧi === +char input[MAX]; +char postfix[MAX]; +char stack[MAX]; +double numStack[MAX]; +int top = -1; +int numTop = -1; + +// === 禡ŧi === +int get_priority(char op); +int is_operator(char c); +double calculate(double a, double b, char op); +void convert_to_postfix(); +double evaluate_postfix(); +double evaluate_infix(char *expr); +double parse_number(char **expr); + +// === ˬdBlu === +//int get_priority(char op) { +// switch(op) { +// case '+': case '-': return 1; +// case '*': case '/': return 2; +// case '^': return 3; +// default: return 0; +// } +//} + +int get_priority(char c){ + if(c=='+' || c=='-'){ + return 1; + }else if(c=='*' || c=='/'){ + return 2; + }else if(c=='^'){ + return 3; + }else{ + return 0; + } +} + + +// === ˬdrO_Bl === +int is_operator(char c) { + return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^'); +} + +// === B === +double calculate(double a, double b, char op) { + switch(op) { + case '+': return a + b; + case '-': return a - b; + case '*': return a * b; + case '/': + if(b != 0) return a / b; + printf("~GƤରsI\n"); + exit(1); + case '^': return pow(a, b); + default: return 0; + } +} + +// === ѪRƦr]]ABIơ^ === +double parse_number(char **expr) { + char *end; + double result = strtod(*expr, &end); + *expr = end; + return result; +} + +// === ഫǪF === +void convert_to_postfix() { + int i = 0 , j; + int postfix_index = 0; + top = -1; + +// printf("ǪܪkG"); + + while(input[i] != '\0') { + if(isdigit(input[i]) || input[i] == '.' || (input[i] == '-' && (i == 0 || input[i-1] == '(' || is_operator(input[i-1])))) { + char *end; + double num = strtod(&input[i], &end); + int len = end - &input[i]; + printf("%.1f ", num); + for(j = 0; j < len; j++) { + postfix[postfix_index++] = input[i+j]; + } + postfix[postfix_index++] = ' '; + i += len - 1; + } + else if(input[i] == '(') { + stack[++top] = input[i]; + } + else if(input[i] == ')') { + while(top >= 0 && stack[top] != '(') { + printf("%c ", stack[top]); + postfix[postfix_index++] = stack[top]; + postfix[postfix_index++] = ' '; + top--; + } + if(top >= 0) top--; + } + else if(is_operator(input[i])) { + while(top >= 0 && stack[top] != '(' && + (get_priority(stack[top]) > get_priority(input[i]) || + (get_priority(stack[top]) == get_priority(input[i]) && input[i] != '^'))) { + printf("%c ", stack[top]); + postfix[postfix_index++] = stack[top]; + postfix[postfix_index++] = ' '; + top--; + } + stack[++top] = input[i]; + } + i++; + } + + while(top >= 0) { + printf("%c ", stack[top]); + postfix[postfix_index++] = stack[top]; + postfix[postfix_index++] = ' '; + top--; + } + postfix[postfix_index] = '\0'; + printf("\n"); +} + +// === pǪF === +double evaluate_postfix() { + int i; + numTop = -1; + char *token = strtok(postfix, " "); + +// printf("\npL{G\n"); + + while(token != NULL) { +// printf("BzаOG'%s'\n", token); + + if(isdigit(token[0]) || (token[0] == '-' && isdigit(token[1]))) { + double num = atof(token); + numStack[++numTop] = num; +// printf("JƦrG%.2f\n", num); + } + else if(is_operator(token[0])) { + if(numTop < 1) { +// printf("~GBl '%c' ʤ֨ާ@\n", token[0]); + exit(1); + } + double b = numStack[numTop--]; + double a = numStack[numTop--]; + double result = calculate(a, b, token[0]); + numStack[++numTop] = result; +// printf("pG%.2f %c %.2f = %.2f\n", a, token[0], b, result); + } + else { +// printf("~GаO '%s'\n", token); + exit(1); + } + +// printf("e|G"); + for(i = 0; i <= numTop; i++) { +// printf("%.2f ", numStack[i]); + } +// printf("\n\n"); + + token = strtok(NULL, " "); + } + + if(numTop != 0) { +// printf("~Gp⵲|Ѿl %d Ӥ\n", numTop + 1); + exit(1); + } + + return numStack[numTop]; +} + +// === p⤤ǪF === +double evaluate_infix(char *expr) { + char opStack[MAX]; + double valStack[MAX]; + int opTop = -1; + int valTop = -1; + + printf("\nǭpL{G\n"); + + while(*expr) { + if(isspace(*expr)) { + expr++; + continue; + } + + if(isdigit(*expr) || *expr == '.' || (*expr == '-' && (valTop == -1 || opStack[opTop] == '('))) { + double num = parse_number(&expr); + valStack[++valTop] = num; + printf("JƦr: %f\n", num); + } + else if(*expr == '(') { + opStack[++opTop] = *expr++; + printf("JA\n"); + } + else if(*expr == ')') { + printf("BzkA\n"); + while(opTop >= 0 && opStack[opTop] != '(') { + char op = opStack[opTop--]; + double b = valStack[valTop--]; + double a = valStack[valTop--]; + valStack[++valTop] = calculate(a, b, op); + printf("p: %f %c %f = %f\n", a, op, b, valStack[valTop]); + } + if(opTop >= 0) opTop--; // A + expr++; + } + else if(is_operator(*expr)) { + while(opTop >= 0 && opStack[opTop] != '(' && + (get_priority(opStack[opTop]) > get_priority(*expr) || + (get_priority(opStack[opTop]) == get_priority(*expr) && *expr != '^'))) { + char op = opStack[opTop--]; + double b = valStack[valTop--]; + double a = valStack[valTop--]; + valStack[++valTop] = calculate(a, b, op); + printf("p: %f %c %f = %f\n", a, op, b, valStack[valTop]); + } + opStack[++opTop] = *expr++; + printf("JBl: %c\n", *(expr-1)); + } + else { + expr++; // Lr + } + } + + while(opTop >= 0) { + char op = opStack[opTop--]; + double b = valStack[valTop--]; + double a = valStack[valTop--]; + valStack[++valTop] = calculate(a, b, op); + printf("p: %f %c %f = %f\n", a, op, b, valStack[valTop]); + } + + return valStack[valTop]; +} + +int main() { + + printf("пJǪܦ(䴩+-*/^()B) => "); + + fgets(input, MAX, stdin); + input[strcspn(input, "\n")] = 0; + + printf("\nǪܪkG "); + convert_to_postfix(); + double postfix_result = evaluate_postfix(); + printf("\nB⵲GG%.2f", postfix_result); + + printf("\t(TȬG"); + if(strcmp(input,"10+20*(50-30)/2^4-6*8")==0){ + printf("%g",10+20*(50-30)/pow(2,4)-6*8); + }else if(strcmp(input,"10+20*(-50+30)/-2^4-6*8")==0){ + printf("%g",10+20*(-50+30)/pow(-2,4)-6*8); + }else if(strcmp(input,"10.5+20.8*(50.1-30.6)/2.5^4-6.6*8.2")==0){ + printf("%g",10.5+20.8*(50.1-30.6)/pow(2.5,4)-6.6*8.2); + }else if(strcmp(input,"10.5+20.8*(-50.1+30.6)/2.5^-4-6.6*8.2")==0){ + printf("%g",10.5+20.8*(-50.1+30.6)/pow(2.5,-4)-6.6*8.2); + }printf(")"); + +// printf("\n=== Ǫp ===\n"); +// double infix_result = evaluate_infix(input); +// printf("ǭp⵲GG%f\n", infix_result); + + return 0; +} diff --git a/作業/unit3/claude.exe b/作業/unit3/claude.exe new file mode 100644 index 0000000..1cc834b Binary files /dev/null and b/作業/unit3/claude.exe differ diff --git a/作業/unit3/claude.o b/作業/unit3/claude.o new file mode 100644 index 0000000..f1e4cff Binary files /dev/null and b/作業/unit3/claude.o differ diff --git a/作業/unit3/claude_easy.c b/作業/unit3/claude_easy.c new file mode 100644 index 0000000..000465c --- /dev/null +++ b/作業/unit3/claude_easy.c @@ -0,0 +1,136 @@ +#include +#include +#define MAX 100 + +// ŧiܼ +char input[MAX]; // xsJ⦡ +char stack[MAX]; // ΨӼȦsBl| +int top = -1; // |ݦm + +// === |򥻾ާ@ === +void push(char c) { + top++; + stack[top] = c; +} + +char pop() { + char c = stack[top]; + top--; + return c; +} + +// === ˬdBlu === +int get_priority(char op) { + switch(op) { + case '+': + case '-': + return 1; + case '*': + case '/': + return 2; + case '^': + return 3; + case 'n': // tudz̰ + return 4; + default: + return 0; + } +} + +// === ˬdrO_Bl === +int is_operator(char c) { + return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^'); +} + +// === ˬdO_t === +int is_negative_sign(char *expr, int pos) { + // pGOĤ@ӦrANOt + if (pos == 0) return 1; + + // ˬde@ӫDťզr + int prev = pos - 1; + while (prev >= 0 && expr[prev] == ' ') prev--; + + if (prev < 0) return 1; // pGeOťաA]Ot + + // pGe@ӦrOBlΥAANOt + return (is_operator(expr[prev]) || expr[prev] == '('); +} + +// === Dnഫ禡 === +void convert_to_postfix() { + int i = 0; + + printf("ǪܪkG"); + + while(input[i] != '\0') { + char now = input[i]; + + // BzƦr]]ttơ^ + if (now >= '0' && now <= '9') { + printf("%c", now); + while(input[i+1] >= '0' && input[i+1] <= '9') { + i++; + printf("%c", input[i]); + } + printf(" "); + } + // Bzt + else if (now == '-' && is_negative_sign(input, i)) { + push('n'); // ϥίSr'n'ܭt + i++; + // XƦr + while(input[i] >= '0' && input[i] <= '9') { + printf("%c", input[i]); + i++; + } + printf(" "); + // Xt + printf("-"); + i--; // ^h@ӦmA]while`ٷ|[@ + } + // BzA + else if(now == '(') { + push(now); + } + // BzkA + else if(now == ')') { + while(top >= 0 && stack[top] != '(') { + char op = pop(); + printf("%c ", op == 'n' ? ' ' : op); + } + if(top >= 0) { + pop(); // A + } + } + // BzBl + else if(is_operator(now)) { + while(top >= 0 && get_priority(stack[top]) >= get_priority(now)) { + char op = pop(); + printf("%c ", op == 'n' ? ' ' : op); + } + push(now); + } + + i++; + } + + // X|ѤUҦBl + while(top >= 0) { + char op = pop(); + printf("%c ", op == 'n' ? ' ' : op); + } +} + +int main() { + printf("=== ǭp ===\n"); + printf("oӵ{iH@몺⦡ഫǪܪk\n"); + printf("iHϥΪŸG+, -, *, /, ^, (, )\n"); + printf("пJ⦡G"); + + gets(input); + convert_to_postfix(); + + printf("\n"); + return 0; +} diff --git a/作業/unit3/claude_easy.exe b/作業/unit3/claude_easy.exe new file mode 100644 index 0000000..da9db69 Binary files /dev/null and b/作業/unit3/claude_easy.exe differ diff --git a/作業/unit3/claude_easy.o b/作業/unit3/claude_easy.o new file mode 100644 index 0000000..98c20f7 Binary files /dev/null and b/作業/unit3/claude_easy.o differ diff --git a/作業/unit3/gpt.c b/作業/unit3/gpt.c new file mode 100644 index 0000000..c49cd79 --- /dev/null +++ b/作業/unit3/gpt.c @@ -0,0 +1,179 @@ +#include +#include +#include +#include // [JƾǹB + +#define N 50 +#define OP 6 + +char op[OP] = {'(','+','-','*','/','^'}; // W[ ^ B +int op_priority[OP] = {0,1,1,2,2,3}; // N ^ uų] 3 + +int priority(char c); +void to_postfix(char infix[], char postfix[]); + +char stack[N]; // This is a global variable. +int top = -1; + +// ------------------------- +// N item J| +// ------------------------- +void push(char item) { + if (top >= N - 1) { + printf("Stack full!\n"); + exit(-1); + } + stack[++top] = item; +} + +// ------------------------------------ +// Ǧ^|ݪơAëDX +// ------------------------------------ +int pop() { + if (top == -1) { + printf("Stack empty!\n"); + exit(-1); + } + return stack[top--]; +} + +// ---------------------- +// P_O_Ű| +// ---------------------- +bool IsEmpty(void) { + return (top < 0) ? true : false; +} + +// ---------------------- +// P_|O_ +// ---------------------- +bool IsFull() { + return (top >= N - 1) ? true : false; +} + +// -------------------------- +// Ǧ^|ݪ +// -------------------------- +char top_data() { + return stack[top]; +} + +// --------------------------- +// Ǧ^Bl c u +// --------------------------- +int priority(char c) { + int i; + for (i = 0; i < OP; i++) { + if (op[i] == c) + return op_priority[i]; + } + return -1; +} + +// ------------------------------------ +// Nminfixনmpostfix +// ------------------------------------ +void to_postfix(char infix[], char postfix[]) { + int i = 0, j = -1; + char x, y; + + while ((x = infix[i++]) != '\0') { + if (x >= '0' && x <= '9') { + // BzhƦr + while (infix[i] >= '0' && infix[i] <= '9') { + postfix[++j] = x; + x = infix[i++]; + } + postfix[++j] = x; // NƦrsJ postfix + postfix[++j] = ' '; // ΪŮjƦr + } else { + switch (x) { + case '(': + push(x); + break; + case ')': + while (!IsEmpty() && (y = pop()) != '(') { + postfix[++j] = y; + postfix[++j] = ' '; + } + break; + case '+': + case '-': + case '*': + case '/': + case '^': + while (!IsEmpty() && priority(top_data()) > priority(x)) { + postfix[++j] = pop(); + postfix[++j] = ' '; + } + push(x); + break; + default: + break; + } + } + } + while (!IsEmpty()) { + postfix[++j] = pop(); + postfix[++j] = ' '; + } + postfix[j] = '\0'; +} + +bool IsDigit(char c) { + return c >= '0' && c <= '9'; +} + +int calculate(char postfix[]) { + int point = 0, num = 0; + while (postfix[point] != '\0') { + if (IsDigit(postfix[point])) { + num = 0; + // BzhƦr + while (postfix[point] != ' ') { + num = num * 10 + (postfix[point] - '0'); + point++; + } + push(num); // NƦrJ| + } else { + if (postfix[point] != ' ') { + int a = pop(); + int b = pop(); + int c = 0; + switch (postfix[point]) { + case '+': + c = b + a; + break; + case '-': + c = b - a; + break; + case '*': + c = b * a; + break; + case '/': + c = b / a; + break; + case '^': + c = (int)pow(b, a); // ƹB + break; + } + push(c); + } + } + point++; + } + return pop(); // ̫᪺G +} + +int main(void) { + char infix[50], postfix[50]; + + printf("пJB⦡: "); + scanf("%s", infix); + to_postfix(infix, postfix); + printf("\nǦ : %s \tǦ : %s\n", infix, postfix); + printf("סG %d\n", calculate(postfix)); + + return 0; +} + diff --git a/作業/unit3/gpt.o b/作業/unit3/gpt.o new file mode 100644 index 0000000..78b8214 Binary files /dev/null and b/作業/unit3/gpt.o differ diff --git a/作業/unit3/stack.c b/作業/unit3/stack.c new file mode 100644 index 0000000..bb876fa --- /dev/null +++ b/作業/unit3/stack.c @@ -0,0 +1,54 @@ +#include +#include +#include +#define MAX 100 + +int stack[MAX]; +int top = -1; + +int main() { + char option; + int i ; + while(1){ + printf("\n*****************************\n"); + printf(" <1>insert(push)\n"); + printf(" <2>delete(pop)\n"); + printf(" <3>list\n"); + printf(" <4>quit\n"); + printf("\n*****************************\n"); + printf("Please enter your choiceG "); + option = getche(); + switch(option){ + case'1': + if (top >= MAX-1) /* |wAܿ~ */ + printf("Stack is full !"); + else { + top++; + printf("\n\n Enter item to insert:"); + scanf( "%d", &stack[top]); + } + break; + case'2': + if (top < 0) /* |SƦsbAܿ~ */ + printf("\n No item, stack is empty !\n"); + else { + printf("\n\n Item %d deleted\n", stack[top]); + top --; + } + break; + + case'3': + printf("\nثe|Ʀr: "); + for(i=0;i<=top;i++){ + printf("%d ",stack[i]); + } + printf("\n"); + break; + case'4': + return 1; + break; + } + } + + return 0; +} diff --git a/作業/unit3/stack.o b/作業/unit3/stack.o new file mode 100644 index 0000000..c53c0e5 Binary files /dev/null and b/作業/unit3/stack.o differ diff --git a/作業/unit3/try.c b/作業/unit3/try.c new file mode 100644 index 0000000..fac61ae --- /dev/null +++ b/作業/unit3/try.c @@ -0,0 +1,212 @@ +#include +#include +#include +#include +#include +#define MAX 100 + +// === ܼƫŧi === +char input[MAX]; +char postfix[MAX]; +char stack[MAX]; +double numStack[MAX]; +int top = -1; +int numTop = -1; + +// === 禡ŧi === +int get_priority(char op); +int is_operator(char c); +double calculate(double a, double b, char op); +void convert_to_postfix(); +double evaluate_postfix(); + +// === ˬdBlu === +int get_priority(char c){ + if(c=='+' || c=='-'){ + return 1; + }else if(c=='*' || c=='/'){ + return 2; + }else if(c=='^'){ + return 3; + }else{ + return 0; + } +} + +// === ˬdrO_Bl === +int is_operator(char c) { + return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^'); +} + +// === B === +double calculate(double a, double b, char op) { + switch(op) { + case '+': return a + b; + case '-': return a - b; + case '*': return a * b; + case '/': + if(b != 0) return a / b; + printf("~GƤରsI\n"); + exit(1); + case '^': return pow(a, b); + default: return 0; + } +} + +// === ഫǪF === +void convert_to_postfix() { + int i = 0, j; + int postfix_index = 0; + top = -1; + char number_str[MAX]; + int is_negative; + + while(input[i] != '\0') { + if(isdigit(input[i]) || input[i] == '.' || + (input[i] == '-' && (i == 0 || input[i-1] == '(' || is_operator(input[i-1])))) { + // BzƦr]]Atơ^ + is_negative = 0; + int num_len = 0; + + // ˬdO_t + if(input[i] == '-') { + is_negative = 1; + i++; + } + + // Ʀrr + while(input[i] != '\0' && (isdigit(input[i]) || input[i] == '.')) { + number_str[num_len++] = input[i++]; + } + number_str[num_len] = '\0'; + i--; // ^h@ӦmA]~h while |A[@ + + // XƦr + printf("%s ", number_str); + if(is_negative) { + printf("- "); + } + + // NƦr[JǪF + for(j = 0; j < num_len; j++) { + postfix[postfix_index++] = number_str[j]; + } + postfix[postfix_index++] = ' '; + if(is_negative) { + postfix[postfix_index++] = '-'; + postfix[postfix_index++] = ' '; + } + } + else if(input[i] == '(') { + stack[++top] = input[i]; + } + else if(input[i] == ')') { + while(top >= 0 && stack[top] != '(') { + printf("%c ", stack[top]); + postfix[postfix_index++] = stack[top]; + postfix[postfix_index++] = ' '; + top--; + } + if(top >= 0) top--; + } + else if(is_operator(input[i])) { + // pGOBztƪ + if(!(input[i] == '-' && (i == 0 || input[i-1] == '(' || is_operator(input[i-1])))) { + while(top >= 0 && stack[top] != '(' && + (get_priority(stack[top]) > get_priority(input[i]) || + (get_priority(stack[top]) == get_priority(input[i]) && input[i] != '^'))) { + printf("%c ", stack[top]); + postfix[postfix_index++] = stack[top]; + postfix[postfix_index++] = ' '; + top--; + } + stack[++top] = input[i]; + } + } + i++; + } + + while(top >= 0) { + printf("%c ", stack[top]); + postfix[postfix_index++] = stack[top]; + postfix[postfix_index++] = ' '; + top--; + } + postfix[postfix_index] = '\0'; + printf("\n"); +} + +// === pǪF === +double evaluate_postfix() { + int i; + numTop = -1; + char *token = strtok(postfix, " "); + + printf("\npL{G\n"); + + while(token != NULL) { + printf("BzаOG'%s'\n", token); + + if(isdigit(token[0]) || (token[0] == '-' && isdigit(token[1]))) { + double num = atof(token); + numStack[++numTop] = num; + printf("JƦrG%.2f\n", num); + } + else if(is_operator(token[0])) { + if(numTop < 1) { + printf("~GBl '%c' ʤ֨ާ@\n", token[0]); + exit(1); + } + double b = numStack[numTop--]; + double a = numStack[numTop--]; + double result = calculate(a, b, token[0]); + numStack[++numTop] = result; + printf("pG%.2f %c %.2f = %.2f\n", a, token[0], b, result); + } + else { + printf("~GаO '%s'\n", token); + exit(1); + } + + printf("e|G"); + for(i = 0; i <= numTop; i++) { + printf("%.2f ", numStack[i]); + } + printf("\n\n"); + + token = strtok(NULL, " "); + } + + if(numTop != 0) { + printf("~Gp⵲|Ѿl %d Ӥ\n", numTop + 1); + exit(1); + } + + return numStack[numTop]; +} + +int main() { + printf("пJǪܦ(䴩+-*/^()B) => "); + + fgets(input, MAX, stdin); + input[strcspn(input, "\n")] = 0; + + printf("\nǪܪkG "); + convert_to_postfix(); + double postfix_result = evaluate_postfix(); + printf("\nB⵲GG%.2f", postfix_result); + + printf("\t(TȬG"); + if(strcmp(input,"10+20*(50-30)/2^4-6*8")==0){ + printf("%g",10+20*(50-30)/pow(2,4)-6*8); + }else if(strcmp(input,"10+20*(-50+30)/-2^4-6*8")==0){ + printf("%g",10+20*(-50+30)/pow(-2,4)-6*8); + }else if(strcmp(input,"10.5+20.8*(50.1-30.6)/2.5^4-6.6*8.2")==0){ + printf("%g",10.5+20.8*(50.1-30.6)/pow(2.5,4)-6.6*8.2); + }else if(strcmp(input,"10.5+20.8*(-50.1+30.6)/2.5^-4-6.6*8.2")==0){ + printf("%g",10.5+20.8*(-50.1+30.6)/pow(2.5,-4)-6.6*8.2); + } + printf(")"); + + return 0; +} diff --git a/作業/unit3/try.o b/作業/unit3/try.o new file mode 100644 index 0000000..d3d2a55 Binary files /dev/null and b/作業/unit3/try.o differ diff --git a/作業/unit3/新增資料夾/DS3.cpp b/作業/unit3/work.c similarity index 100% rename from 作業/unit3/新增資料夾/DS3.cpp rename to 作業/unit3/work.c diff --git a/作業/unit3/work.exe b/作業/unit3/work.exe new file mode 100644 index 0000000..dd2a422 Binary files /dev/null and b/作業/unit3/work.exe differ diff --git a/作業/unit3/work.o b/作業/unit3/work.o new file mode 100644 index 0000000..02c3ecb Binary files /dev/null and b/作業/unit3/work.o differ diff --git a/作業/unit4/DS4.c b/作業/unit4/DS4.c new file mode 100644 index 0000000..0ec9e23 --- /dev/null +++ b/作業/unit4/DS4.c @@ -0,0 +1,441 @@ +#include +#include +#include +#include +#include + +#define MAX_NAME_LENGTH 24 + +//ŧi禡쫬 +void init_f(); +void insertStudent(char* name, int english, int math); +void modify_list(); +void add_data(char* name, int english, int math); +void remove_data(char* name); +void readStudentsFromFile(char* filename); +void printStudentList(); +void sort_name(); +void sort_eng(); +void sort_math(); +void choose_subject(); +void find_student(int number , int mode); + +// wqǥ͸`Ic +typedef struct Student { + char name[MAX_NAME_LENGTH]; + int english; + int math; + struct Student* llink; + struct Student* rlink; +} Student; + +Student *head, *tail, *current, *prev, *temp; +FILE* file; + +//]@ headANk쵲ҫV +void init_f() { + head = (Student *) malloc(sizeof(Student)); // head + head->llink = head; // 쵲Vۤv + head->rlink = head; // k쵲Vۤv + tail = head; +} + +// bJsǥ͸`I +void insertStudent(char* name, int english, int math) { + + Student* newNode = (Student*)malloc(sizeof(Student)); + strcpy(newNode->name, name); + + newNode->english = english; + newNode->math = math; + + if(head->rlink == tail) { + // oOĤ@ӴJ`I + head->rlink = newNode; + tail->llink = newNode; + newNode->llink = head; + newNode->rlink = tail; + } else { + //OĤ@ J + newNode->llink = tail->llink; + newNode->rlink = tail; + tail->llink->rlink = newNode; + tail->llink = newNode; + } +} + +// ***᪺W[δָ +void modify_list(){ + char name[MAX_NAME_LENGTH]; + int english, math; + char line[100]; + + while(fgets(line, sizeof(line), file)!=NULL){ + if(line[0]=='+'){ + sscanf(line+2, "%23[^\t]\t%d\t%d\n", name, &english, &math); + printf("\n*******************************\n"); + printf("W[@\n\n"); + add_data(name, english, math); + printStudentList(); + }else if(line[0]=='-'){ + sscanf(line+2, "%23[^\t]\t%d\t%d\n", name, &english, &math); + printf("\n*******************************\n"); + printf("R@\n\n"); + remove_data(name); + printStudentList(); + } + } + fclose(file); +} + +//W[ +void add_data(char* name, int english, int math){ + Student* newNode = (Student*)malloc(sizeof(Student)); + strcpy(newNode->name, name); + + newNode->english = english; + newNode->math = math; + + newNode->llink = tail->llink; + newNode->rlink = tail; + tail->llink->rlink = newNode; + tail->llink = newNode; + printf("%s wW[\n\n", name); +} + +//ָ +void remove_data(char* name){ + + prev = head; + current = head->rlink; + + while(current!=tail &&strcmp(name,current->name)!=0){ + prev=current; + current=current->rlink; + } + if(current != tail){ + + current->rlink->llink = prev; + prev->rlink = current->rlink; + printf("%s wR\n\n", name); + free(current); + }else /* 䤣ƫhܿ~ */ + printf(" %s bC\n", name); + +} + +// qŪǥ͸ +void readStudentsFromFile(char* filename) { + file = fopen(filename, "r"); + if (file == NULL) { + printf("Lk}ɮ %s\n", filename); + return; + } + + char line[100]; + int lineCount = 0; + + // Le| + while (lineCount < 4 && fgets(line, sizeof(line), file)) { + lineCount++; + } + + // Ūǥ͸ + char name[MAX_NAME_LENGTH]; + int english, math; + // %[ ]ܭnŪJ@ӦrŶX + // %23[^\t]uŪ̦h23ӦršAJ\tv ^D O\tNŪ + // Y\ŪƷ|^3 YŪ uŪnameΨSŪƫh^ǭȤ3 + while(fgets(line, sizeof(line), file)!=NULL){ + if(isalpha(line[0])){ + sscanf(line, "%23[^\t]\t%d\t%d\n", name, &english, &math); + insertStudent(name, english, math); + }else if(line[0]=='*'){ + break; + } + } +// flocseե `ϥbmodify_list +// fclose(file); +} + +// CLǥͦC +void printStudentList() { + + current = head->rlink; + + printf("\nqY}l\n"); + printf("\nmW\t\t^\tƾ\n"); + printf("--------------------------------\n"); + + while (current != tail) { + printf("%-15s\t%d\t%d\n", current->name, current->english, current->math); + current = current->rlink; + } + + current = tail->llink; + + printf("\nq}l\n"); + printf("\nmW\t\t^\tƾ\n"); + printf("--------------------------------\n"); + while (current != head) { + printf("%-15s\t%d\t%d\n", current->name, current->english, current->math); + current = current->llink; + } +} + +//̷ӦWriƧ +void sort_name(){ + + //YSƩΥu@ + if (head->rlink == tail || head->rlink->rlink == tail) { + return; + } + + int flag = 1; + while(flag){ + flag = 0; + current = head->rlink; + + while(current->rlink != tail){ + temp = current->rlink; + + if(strcmp(current->name,temp->name) > 0){ +// uϥΨӸ`Ii`I洫 +// n`NЧܫ᪺ +// YUC{ǥ洫ЫV}|X +// ]iHhŧiӸ`I current->llinktemp->rlink +// o˴NiHL޶ + temp->llink = current->llink; + current->rlink = temp->rlink; + + temp->rlink->llink = current; + temp->rlink = current; + + current->llink->rlink = temp; + current->llink = temp; + + flag = 1; + } + else{ + current = current->rlink; + } + } + } +} + +//̷ӭ^妨ZiƧ +void sort_eng(){ + + //YSƩΥu@ + if (head->rlink == tail || head->rlink->rlink == tail) { + return; + } + + int flag = 1; + while(flag){ + flag = 0; + current = head->rlink; + + while(current->rlink != tail){ + temp = current->rlink; + + if(current->english < temp->english){ +// uϥΨӸ`Ii`I洫 +// n`NЧܫ᪺ +// YUC{ǥ洫ЫV}|X +// ]iHhŧiӸ`I current->llinktemp->rlink +// o˴NiHL޶ + temp->llink = current->llink; + current->rlink = temp->rlink; + + temp->rlink->llink = current; + temp->rlink = current; + + current->llink->rlink = temp; + current->llink = temp; + + flag = 1; + } + else{ + current = current->rlink; + } + } + } +} + +//̷ӭ^妨ZiƧ +void sort_math(){ + + //YSƩΥu@ + if (head->rlink == tail || head->rlink->rlink == tail) { + return; + } + + int flag = 1; + while(flag){ + flag = 0; + current = head->rlink; + + while(current->rlink != tail){ + temp = current->rlink; + + if(current->math < temp->math){ +// uϥΨӸ`Ii`I洫 +// n`NЧܫ᪺ +// YUC{ǥ洫ЫV}|X +// ]iHhŧiӸ`I current->llinktemp->rlink +// o˴NiHL޶ + temp->llink = current->llink; + current->rlink = temp->rlink; + + temp->rlink->llink = current; + temp->rlink = current; + + current->llink->rlink = temp; + current->llink = temp; + + flag = 1; + } + else{ + current = current->rlink; + } + } + } +} + +//ܬؤαƦW +void choose_subject(){ + int subject ,number , i=1; + + printf("\nJܪ\n" + "1 ƾ 2 ^ ==> "); + subject = getche(); + switch(subject){ + case '1': + printf("\nJƦW(JЫEnter) ==> "); + scanf("%d",&number); + sort_math(); + find_student(number , 1); + + printf("\nҦpU"); + printf("\nƦW\tmW\t\t^\tƾ"); + printf("\n-----------------------------------\n"); + Student* current = head->rlink; + while (current != tail) { + printf("%d\t%-15s\t%d\t%d\n",i++, current->name, current->english, current->math); + current = current->rlink; + } + break; + case '2': + printf("\nJƦW(JЫEnter) ==> "); + scanf("%d",&number); + sort_eng(); + find_student(number , 2); + + printf("\nҦpU"); + printf("\nƦW\tmW\t\t^\tƾ"); + printf("\n-----------------------------------\n"); + current = head->rlink; + while (current != tail) { + printf("%d\t%-15s\t%d\t%d\n",i++, current->name, current->english, current->math); + current = current->rlink; + } + break; + default : + printf("J~"); + break; + } +} + + +//ھڬؤαƦWǥ +void find_student(int number , int mode){ + current = head->rlink; + + int i = 1; + while (current != tail && i < number) { + current = current->rlink; + i++; + } + if(current!=tail && number != 0){ + printf("\n*****************************\n"); + if(mode == 1 ){ + printf("ƾ"); + }else if(mode == 2){ + printf("^"); + } + printf("ƦW%dǥͬ\n\n" + "mW\t\t^\tƾ\n%-15s\t%d\t%d", number, current->name, current->english, current->math); + printf("\n*****************************\n"); + }else{ + printf("\n*****************************\n"); + printf("Ƥsb"); + printf("\n*****************************\n"); + } +} + +//Ҧ`I +void freeAllNodes() { + current = head->rlink; + while (current != tail) { + Student* temp = current; + current = current->rlink; + free(temp); + } + free(head); // head `I +} + +int main() { + char mode ,sort_mode; + init_f(); + readStudentsFromFile("YunTechStudents2.txt"); + printStudentList(); + modify_list(); + + while(1){ + printf("\n******* ܶiƧǩάOƦWnWǥ *******\n" + "*--------------------------------------*\n" + "* 1 iƧ 2 ܱƦWnWǥ 3 *\n" + "\nпܥ\\ ==> "); // \\ b|ܶýX + mode = getche(); + switch(mode){ + case '1': + printf("\n\nܱƧǤ覡\n" + "*--------------------------------------*\n" + "1 Wr 2 ^妨Z 3 ƾǦZ \n" + "\nпܱƧǤ覡 ==> "); + sort_mode = getche(); + switch(sort_mode){ + case '1': + printf("\n\nHWriƧ\n"); + sort_name(); + printStudentList(); + break; + case '2': + printf("\n\nH^妨ZiƧ\n"); + sort_eng(); + printStudentList(); + break; + case '3': + printf("\n\nHƾǦZiƧ\n"); + sort_math(); + printStudentList(); + break; + default: + printf("\nJ~\n"); + break; + } + break; + case '2': + choose_subject(); + break; + case '3': + printf("\n\n¨ϥΡABye~\n"); + freeAllNodes(); + return 0; + default: + printf("\nJ~\n"); + break; + } + } +} diff --git a/作業/unit4/DS4.exe b/作業/unit4/DS4.exe new file mode 100644 index 0000000..fe836ab Binary files /dev/null and b/作業/unit4/DS4.exe differ diff --git a/作業/unit4/DS4.o b/作業/unit4/DS4.o new file mode 100644 index 0000000..b7ee53a Binary files /dev/null and b/作業/unit4/DS4.o differ diff --git a/作業/unit4/DS4.zip b/作業/unit4/DS4.zip new file mode 100644 index 0000000..5479b58 Binary files /dev/null and b/作業/unit4/DS4.zip differ diff --git a/作業/unit4/DS4/DS4.c b/作業/unit4/DS4/DS4.c new file mode 100644 index 0000000..e5f159a --- /dev/null +++ b/作業/unit4/DS4/DS4.c @@ -0,0 +1,438 @@ +#include +#include +#include +#include +#include + +#define MAX_NAME_LENGTH 24 + +//ŧi禡쫬 +void init_f(); +void readStudentsFromFile(char* filename); +void insertStudent(char* name, int english, int math); +void printStudentList(); +void sort_name(); +void sort_eng(); +void sort_math(); +void modify_list(); +void add_data(char* name, int english, int math); +void remove_data(char* name); +void choose_subject(); +void find_student(int number , int mode); + +// wqǥ͸`Ic +typedef struct Student { + char name[MAX_NAME_LENGTH]; + int english; + int math; + struct Student* llink; + struct Student* rlink; +} Student; + +Student *head, *tail, *current, *prev, *temp; +FILE* file; + +void init_f() { + head = (Student *) malloc(sizeof(Student)); + tail = (Student *) malloc(sizeof(Student)); + +// head->llink = head; // 쵲Vۤv +// head->rlink = head; // k쵲Vۤv +// tail = head; + +// head->llink = tail; + head->rlink = tail; +// tail->rlink = head; + tail->llink = head; +} + +// bJsǥ͸`I +void insertStudent(char* name, int english, int math) { + + Student* newNode = (Student*)malloc(sizeof(Student)); + + strcpy(newNode->name, name); + newNode->english = english; + newNode->math = math; + +// J + newNode->llink = tail->llink; + newNode->rlink = tail; + tail->llink->rlink = newNode; + tail->llink = newNode; +} + +//W[ +void add_data(char* name, int english, int math){ + Student* newNode = (Student*)malloc(sizeof(Student)); + + strcpy(newNode->name, name); + newNode->english = english; + newNode->math = math; + + newNode->llink = tail->llink; + newNode->rlink = tail; + tail->llink->rlink = newNode; + tail->llink = newNode; + printf("%s wW[\n", name); +} + +//ָ +void remove_data(char* name){ + + prev = head; + current = head->rlink; + + while(current!=tail &&strcmp(name,current->name)!=0){ + prev=current; + current=current->rlink; + } + if(current != tail){ + + current->rlink->llink = prev; + prev->rlink = current->rlink; + printf("%s wR\n", name); + free(current); + }else /* 䤣ƫhܿ~ */ + printf(" %s bC\n", name); + +} + +// qŪǥ͸ +void readStudentsFromFile(char* filename) { + file = fopen(filename, "r"); + if (file == NULL) { + printf("Lk}ɮ %s\n", filename); + return; + } + + char line[100]; + int lineCount = 0; + + // Le| + while (lineCount < 4 && fgets(line, sizeof(line), file)) { + lineCount++; + } + + // Ūǥ͸ + char name[MAX_NAME_LENGTH]; + int english, math; + // %[ ]ܭnŪJ@ӦrŶX + // %23[^\t]uŪ̦h23ӦršAJ\tv ^D O\tNŪ + while(fgets(line, sizeof(line), file)!=NULL){ + if(isalpha(line[0])){ + sscanf(line, "%23[^\t]\t%d\t%d\n", name, &english, &math); + insertStudent(name, english, math); + }else if(line[0]=='*'){ + break; + } + } +// flocseե `ϥbmodify_list +// fclose(file); +} + +// ***᪺W[δָ +void modify_list(){ + char name[MAX_NAME_LENGTH]; + int english, math; + char line[100]; + + while(fgets(line, sizeof(line), file)!=NULL){ + if(line[0]=='+'){ + sscanf(line, "%*[^ ] %[^\t]\t%d\t%d\n", name, &english, &math); + printf("\n===============================\n"); + printf("W[@\n\n"); + add_data(name, english, math); + printStudentList(); + }else if(line[0]=='-'){ + sscanf(line, "%*[^ ] %[^\t]\t%d\t%d\n", name, &english, &math); + printf("\n===============================\n"); + printf("R@\n\n"); + remove_data(name); + printStudentList(); + } + } + fclose(file); +} + +// CLǥͦC +void printStudentList() { + + current = head->rlink; + + printf("\nqY}l\n"); + printf("\nmW\t\t^\tƾ\n"); + printf("--------------------------------\n"); + + while (current != tail) { + printf("%-15s\t%d\t%d\n", current->name, current->english, current->math); + current = current->rlink; + } + + current = tail->llink; + + printf("\nq}l\n"); + printf("\nmW\t\t^\tƾ\n"); + printf("--------------------------------\n"); + while (current != head) { + printf("%-15s\t%d\t%d\n", current->name, current->english, current->math); + current = current->llink; + } +} + +//̷ӦWriƧ +void sort_name(){ + + //YSƩΥu@ + if (head->rlink == tail || head->rlink->rlink == tail) { + return; + } + + int flag = 1; + while(flag){ + flag = 0; + current = head->rlink; + + while(current->rlink != tail){ + temp = current->rlink; + + if(strcmp(current->name,temp->name) > 0){ +// uϥΨӸ`Ii`I洫 +// n`NЧܫ᪺ +// YUC{ǥ洫ЫV}|X +// ]iHhŧiӸ`I current->llinktemp->rlink +// o˴NiHL޶ + temp->llink = current->llink; + current->rlink = temp->rlink; + + temp->rlink->llink = current; + temp->rlink = current; + + current->llink->rlink = temp; + current->llink = temp; + + flag = 1; + } + else{ + current = current->rlink; + } + } + } +} + +//̷ӭ^妨ZiƧ +void sort_eng(){ + + //YSƩΥu@ + if (head->rlink == tail || head->rlink->rlink == tail) { + return; + } + + int flag = 1; + while(flag){ + flag = 0; + current = head->rlink; + + while(current->rlink != tail){ + temp = current->rlink; + + if(current->english < temp->english){ +// uϥΨӸ`Ii`I洫 +// n`NЧܫ᪺ +// YUC{ǥ洫ЫV}|X +// ]iHhŧiӸ`I current->llinktemp->rlink +// o˴NiHL޶ + temp->llink = current->llink; + current->rlink = temp->rlink; + + temp->rlink->llink = current; + temp->rlink = current; + + current->llink->rlink = temp; + current->llink = temp; + + flag = 1; + } + else{ + current = current->rlink; + } + } + } +} + +//̷ӼƾǦZiƧ +void sort_math(){ + + //YSƩΥu@ + if (head->rlink == tail || head->rlink->rlink == tail) { + return; + } + + int flag = 1; + while(flag){ + flag = 0; + current = head->rlink; + + while(current->rlink != tail){ + temp = current->rlink; + + if(current->math < temp->math){ +// uϥΨӸ`Ii`I洫 +// n`NЧܫ᪺ +// YUC{ǥ洫ЫV}|X +// ]iHhŧiӸ`I current->llinktemp->rlink +// o˴NiHL޶ + temp->llink = current->llink; + current->rlink = temp->rlink; + + temp->rlink->llink = current; + temp->rlink = current; + + current->llink->rlink = temp; + current->llink = temp; + + flag = 1; + } + else{ + current = current->rlink; + } + } + } +} + +//ܬؤαƦW +void choose_subject(){ + int subject ,number , i=1; + + printf("\nJܪ\n" + "1 ƾ 2 ^ ==> "); + subject = getche(); + switch(subject){ + case '1': + printf("\nJƦW(JЫEnter) ==> "); + scanf("%d",&number); + sort_math(); + find_student(number , 1); + + printf("\nҦpU"); + printf("\nƦW\tmW\t\t^\tƾ"); + printf("\n-----------------------------------\n"); + current = head->rlink; + while (current != tail) { + printf("%d\t%-15s\t%d\t%d\n",i++, current->name, current->english, current->math); + current = current->rlink; + } + break; + case '2': + printf("\nJƦW(JЫEnter) ==> "); + scanf("%d",&number); + sort_eng(); + find_student(number , 2); + + printf("\nҦpU"); + printf("\nƦW\tmW\t\t^\tƾ"); + printf("\n-----------------------------------\n"); + current = head->rlink; + while (current != tail) { + printf("%d\t%-15s\t%d\t%d\n",i++, current->name, current->english, current->math); + current = current->rlink; + } + break; + default : + printf("J~"); + break; + } +} + +//ھڬؤαƦWǥ +void find_student(int number , int mode){ + current = head->rlink; + + int i = 1; + while (current != tail && i < number) { + current = current->rlink; + i++; + } + if(current!=tail && number != 0){ + printf("\n*****************************\n"); + if(mode == 1 ){ + printf("ƾ"); + }else if(mode == 2){ + printf("^"); + } + printf("ƦW%dǥͬ\n\n" + "mW\t\t^\tƾ\n%-15s\t%d\t%d", number, current->name, current->english, current->math); + printf("\n*****************************\n"); + }else{ + printf("\n*****************************\n"); + printf("Ƥsb"); + printf("\n*****************************\n"); + } +} + +//Ҧ`I +void freeAllNodes() { + current = head->rlink; + while (current != tail) { + temp = current; + current = current->rlink; + free(temp); + } + free(head); // head `I + free(tail); // tail `I +} + +int main() { + char mode ,sort_mode; + init_f(); + readStudentsFromFile("YunTechStudents.txt"); + printStudentList(); + modify_list(); + + while(1){ + printf("\n******* ܶiƧǩάOƦWnWǥ *******\n" + "*--------------------------------------*\n" + "* 1 iƧ 2 ܱƦWnWǥ 3 *\n" + "\nпܥ\\ ==> "); // \\ b|ܶýX + mode = getche(); + switch(mode){ + case '1': + printf("\n\nܱƧǤ覡\n" + "*--------------------------------------*\n" + "1 Wr 2 ^妨Z 3 ƾǦZ \n" + "\nпܱƧǤ覡 ==> "); + sort_mode = getche(); + switch(sort_mode){ + case '1': + printf("\n\nHWriƧ\n"); + sort_name(); + printStudentList(); + break; + case '2': + printf("\n\nH^妨ZiƧ\n"); + sort_eng(); + printStudentList(); + break; + case '3': + printf("\n\nHƾǦZiƧ\n"); + sort_math(); + printStudentList(); + break; + default: + printf("\nJ~\n"); + break; + } + break; + case '2': + choose_subject(); + break; + case '3': + printf("\n\n¨ϥΡABye~\n"); + freeAllNodes(); + return 0; + default: + printf("\nJ~\n"); + break; + } + } +} diff --git a/作業/unit4/DS4/DS4.exe b/作業/unit4/DS4/DS4.exe new file mode 100644 index 0000000..4b8d2b0 Binary files /dev/null and b/作業/unit4/DS4/DS4.exe differ diff --git a/作業/unit4/DS4/YunTechStudents.txt b/作業/unit4/DS4/YunTechStudents.txt new file mode 100644 index 0000000..665b05c --- /dev/null +++ b/作業/unit4/DS4/YunTechStudents.txt @@ -0,0 +1,18 @@ +YunTech EE Department (2024) +====================================== +Name English Math +---------------+-------+-------------- +Steve Jobs 50 60 +Tom Cruise 30 40 +Marie Jane 70 80 +Barrack Obama 46 77 +John Tyler 98 96 +U. S. Grant 97 88 +Robert Redford 22 33 +Bruce Lee 90 90 +************************************** ++ Oliver Hardy 90 80 ++ Slim Pickens 88 82 +- Marie Jane 0 0 ++ James Bond 88 82 +- Barrack Obama 0 0 \ No newline at end of file diff --git a/作業/unit4/DS4/sheng_v2.cpp b/作業/unit4/DS4/sheng_v2.cpp new file mode 100644 index 0000000..e941d89 --- /dev/null +++ b/作業/unit4/DS4/sheng_v2.cpp @@ -0,0 +1,364 @@ +#include +#include +#include +#include + +typedef struct Student +{ + char name[40]; + int eng; + int math; + struct Student *prev; + struct Student *next; +} Student; +Student *head = NULL, *tail = NULL, *current; + +// sW`I쵲C +void addToList(const char *name, int eng, int math) +{ + // tms`IO + Student *newStudent = (Student*)malloc(sizeof(Student)); + // ƻsƨs`I + strncpy(newStudent->name, name, sizeof(newStudent->name) - 1); + newStudent->name[sizeof(newStudent->name) - 1] = '\0'; + newStudent->eng = eng; + newStudent->math = math; + newStudent->next = NULL; + // pGOĤ@Ӹ`I + if (head == NULL) + { + newStudent->prev = NULL; + head = tail = newStudent; + } + else // [J + { + newStudent->prev = tail; + tail->next = newStudent; + tail = newStudent; + } +} + +// ܩҦǥ͸ +void displayList() +{ + //Student * + current = head; + printf("ǥ͸ƦC(qY}l)G\n\n"); + printf("mW\t\t\t\t^\tƾ\n"); + printf("---------------------------------------------\n"); + for(int i=0; current!=NULL; current=current->next,i++) + { + printf("%d.\t%-16s\t%d\t%d\n\n", i+1, current->name, current->eng, current->math); + } + printf("---------------------------------------------\n"); +} +// q}lCL +void displayList_inverse() +{ + Student *current = tail; + printf("ǥ͸ƦC(q}l)G\n\n"); + printf("mW\t\t\t\t^\tƾ\n"); + printf("---------------------------------------------\n"); + for(int i=0; current!=NULL; current=current->prev,i++) + { + printf("%d.\t%-16s\t%d\t%d\n\n", i+1, current->name, current->eng, current->math); + } + printf("---------------------------------------------\n"); +} +// ҦʺAt`I +void cleanup() +{ + Student *current = head; + while (current != NULL) + { + Student *temp = current; + current = current->next; + free(temp); + } + head = tail = NULL; +} +// s᪺R +void deletedate(const char *name, int eng, int math) +{ + Student *current = head; + while(current != NULL) + { + if(strcmp(current->name, name) == 0) + { + if(current->prev != NULL) current->prev->next = current->next; + else head = current->next; + + if(current->next != NULL) current->next->prev = current->prev; + else tail = current->prev; + + free(current); + return; + } + current = current->next; + } +} +// re᪺Ů +void trim(char *str) +{ + char *end; + while(isspace(*str)) str++; + if(*str == 0) return; + end = str + strlen(str) - 1; + while(end > str && isspace(*end)) end--; + end[1] = '\0'; +} +//void displayOriginal(Student **array, int length) +//{ +// printf("\nlƦCG\n\n"); +// printf("mW\t\t\t\t^\tƾ\n"); +// printf("---------------------------------------------\n"); +// for(int i = 0; i < length; i++) { +// printf("%d.\t%-16s\t%d\t%d\n\n", i+1, array[i]->name, array[i]->eng, array[i]->math); +// } +// printf("---------------------------------------------\n"); +//}//pGQbƧǫ٦switch,NU + +void displayOriginal() +{ + //Student * + current = head; + printf("\nlƦCG\n\n"); + printf("mW\t\t\t\t^\tƾ\n"); + printf("---------------------------------------------\n"); + for(int i = 0; current != NULL; i++) { + printf("%d.\t%-16s\t%d\t%d\n\n", i+1, current->name, current->eng, current->math); + current = current->next; + } + printf("---------------------------------------------\n"); +} +// ƧǨ +void bubble_name() +{ + int length = 0; + Student *current = head; + // p + while(current != NULL) + { + length++; + current = current->next; + } + // ЫثwƲ + Student **array = (Student**)malloc(length * sizeof(Student*)); + current = head; + for(int i = 0; i < length; i++) + { + array[i] = current; + current = current->next; + } + // ܭl + //displayOriginal(array, length); + // WrƧ + for(int i = 0; i < length-1; i++) + { + for(int j = 0; j < length-1-i; j++) + { + if(strcmp(array[j]->name, array[j+1]->name) > 0) + { + Student *temp = array[j]; + array[j] = array[j+1]; + array[j+1] = temp; + } + } + } + + // ܱƧǫ᪺G + printf("ǥ͸ƦC(̦WrƧ)G\n\n"); + printf("mW\t\t\t\t^\tƾ\n"); + printf("---------------------------------------------\n"); + for(int i = 0; i < length; i++) { + printf("%d.\t%-16s\t%d\t%d\n\n", i+1, array[i]->name, array[i]->eng, array[i]->math); + } + printf("---------------------------------------------\n"); + + free(array); +} + +// ^妨ZƧ +void bubble_eng() +{ + int length = 0; + Student *current = head; + + // p + while(current != NULL) { + length++; + current = current->next; + } + + // ЫثwƲ + Student **array = (Student**)malloc(length * sizeof(Student*)); + current = head; + for(int i = 0; i < length; i++) { + array[i] = current; + current = current->next; + } + + // ܭl + //displayOriginal(array, length); + + // ^妨ZƧ + for(int i = 0; i < length-1; i++) { + for(int j = 0; j < length-1-i; j++) { + if(array[j]->eng < array[j+1]->eng) { + Student *temp = array[j]; + array[j] = array[j+1]; + array[j+1] = temp; + } + } + } + + // ܱƧǫ᪺G + printf("ǥ͸ƦC(̭^妨ZƧ)G\n\n"); + printf("mW\t\t\t\t^\tƾ\n"); + printf("---------------------------------------------\n"); + for(int i = 0; i < length; i++) { + printf("%d.\t%-16s\t%d\t%d\n\n", i+1, array[i]->name, array[i]->eng, array[i]->math); + } + printf("---------------------------------------------\n"); + + free(array); +} + +// ƾǦZƧ +void bubble_math() +{ + int length = 0; + Student *current = head; + + // p + while(current != NULL) { + length++; + current = current->next; + } + + // ЫثwƲ + Student **array = (Student**)malloc(length * sizeof(Student*)); + current = head; + for(int i = 0; i < length; i++) { + array[i] = current; + current = current->next; + } + + // ܭl + //displayOriginal(array, length); + + // ƾǦZƧ + for(int i = 0; i < length-1; i++) { + for(int j = 0; j < length-1-i; j++) { + if(array[j]->math < array[j+1]->math) { + Student *temp = array[j]; + array[j] = array[j+1]; + array[j+1] = temp; + } + } + } + + // ܱƧǫ᪺G + printf("ǥ͸ƦC(̼ƾǦZƧ)G\n\n"); + printf("mW\t\t\t\t^\tƾ\n"); + printf("---------------------------------------------\n"); + for(int i = 0; i < length; i++) { + printf("%d.\t%-16s\t%d\t%d\n\n", i+1, array[i]->name, array[i]->eng, array[i]->math); + } + printf("---------------------------------------------\n"); + + free(array); +} +void select() +{ + Student *current=head; + int j; + printf("пܬdݲĴXW\n\n"); + scanf("%d",&j); + for(int i=1;inext; + } + printf("\n%d. Name = %s Eng = %d\tMath = %d",j,current->name,current->eng,current->math); +} + +int main() +{ + FILE *file; + char line[100]; + char name[40]; + int eng, math; + char op; + + file = fopen("YunTechStudents.txt", "r"); + while(fgets(line, sizeof(line), file)) + { + if(strstr(line, "****") != NULL) + break; + if(sscanf(line, "%[^\t]%d%d", name, &eng, &math) == 3) + { + trim(name); + addToList(name, eng, math); + } + } + displayList(); + displayList_inverse(); + + while(fgets(line, sizeof(line), file)) + { + op = line[0]; + if(op == '+' || op == '-') + { + char fullname[40]; + if(sscanf(line + 1, " %[^0-9]%d%d", fullname, &eng, &math) == 3) + { + trim(fullname); + if(op == '+') + { + addToList(fullname, eng, math); + printf("\nsWƬ:\t%s\t%d\t%d\n\n", fullname, eng, math); + } + else + { + deletedate(fullname, eng, math); + printf("\nRƬ:\t%s\t%d\t%d\n\n", fullname, eng, math); + } + displayList(); + displayList_inverse(); + } + } + } + + int choice; + while(1) + { + printf("\n\nпJ\n\n"); + printf("1. HWrƦC\t2. H^ƱƦC\t3. HƾǤƱƦC\t4. ܭ쥻\t5. }\n\n"); + scanf("%d",&choice); + switch(choice) + { + case 1: + bubble_name(); + select(); + break; + case 2: + bubble_eng(); + select(); + break; + case 3: + bubble_math(); + select(); + break; + case 4: + displayOriginal(); + break; + case 5: + printf("\nwA"); + cleanup(); + exit(0); + break; + } + } + fclose(file); + return 0; +} diff --git a/作業/unit4/DS4/sheng_v2.exe b/作業/unit4/DS4/sheng_v2.exe new file mode 100644 index 0000000..980373e Binary files /dev/null and b/作業/unit4/DS4/sheng_v2.exe differ diff --git a/作業/unit4/DS4_try.c b/作業/unit4/DS4_try.c new file mode 100644 index 0000000..ba46a16 --- /dev/null +++ b/作業/unit4/DS4_try.c @@ -0,0 +1,315 @@ +#include +#include +#include +#include + +#define MAX_NAME_LENGTH 24 + +FILE* file; + +// wqǥ͸`Ic +typedef struct Student { + char name[MAX_NAME_LENGTH]; + int english; + int math; + struct Student* llink; + struct Student* rlink; +} Student; +Student *head, *tail, *current, *prev, *temp; + +//]@ headANk쵲ҫV +void init_f() { + head = (Student *) malloc(sizeof(Student)); // head + head->llink = head; // 쵲Vۤv + head->rlink = head; // k쵲Vۤv + tail = head; +} + +// bJsǥ͸`I +void insertStudent(char* name, int english, int math) { + + Student* newNode = (Student*)malloc(sizeof(Student)); + strcpy(newNode->name, name); + + newNode->english = english; + newNode->math = math; + + if(head->rlink == tail) { + // oOĤ@ӴJ`I + head->rlink = newNode; + tail->llink = newNode; + newNode->llink = head; + newNode->rlink = tail; + } else { + //OĤ@ J + newNode->llink = tail->llink; + newNode->rlink = tail; + tail->llink->rlink = newNode; + tail->llink = newNode; + } +} + +// **᪺W[δָ +void modify_list(){ + char name[MAX_NAME_LENGTH]; + int english, math; + char line[100]; + +// while(fgets(line, sizeof(line), file)!=NULL){ +// if(line[0]=='+'){ +// sscanf(line+2, "%23[^\t]\t%d\t%d\n", name, &english, &math); +// printf("\n*******************************\n"); +// printf("W[@\n\n"); +// printf("%s\n",name); +// add_data(name, english, math); +// printStudentList(); +// }else if(line[0]=='-'){ +// sscanf(line+2, "%23[^\t]\t%d\t%d\n", name, &english, &math); +// printf("\n*******************************\n"); +// printf("֤@\n\n"); +// printf("%s\n",name); +// remove_data(name); +// printStudentList(); +// } +// } + fclose(file); +} + +//W[ +void add_data(char* name, int english, int math){ + Student* newNode = (Student*)malloc(sizeof(Student)); + strcpy(newNode->name, name); + + newNode->english = english; + newNode->math = math; + + newNode->llink = tail->llink; + newNode->rlink = tail; + tail->llink->rlink = newNode; + tail->llink = newNode; + printf("%s wW[\n", name); +} + +//ָ +void remove_data(char* name){ + + prev = head; + current = head->rlink; + + while(current!=tail &&strcmp(name,current->name)!=0){ + prev=current; + current=current->rlink; + } + if(current != head){ + + current->rlink->llink = prev; + prev->rlink = current->rlink; + printf("%s wQR\n", name); + free(current); + }else /* 䤣ƫhܿ~ */ + printf(" %s bC\n", name); + +} + +// qŪǥ͸ +void readStudentsFromFile(char* filename) { + file = fopen(filename, "r"); + if (file == NULL) { + printf("Lk}ɮ %s\n", filename); + return; + } + + char line[100]; + int lineCount = 0; + + // Le| + // | + while (lineCount < 4 && fgets(line, sizeof(line), file)) { + lineCount++; + } + + // Ūǥ͸ + char name[MAX_NAME_LENGTH]; + int english, math; + // %23[^\t]uŪ̦h23ӦršAJ\tv ^D O\tNŪ + // Y\ŪƷ|^3 YŪ uŪnameΨSŪƫh^ǭȤ3 + while(fgets(line, sizeof(line), file)!=NULL){ + if(isalpha(line[0])){ + sscanf(line, "%23[^\t]\t%d\t%d\n", name, &english, &math); + insertStudent(name, english, math); + }else if(line[0]=='*'){ + break; + } + } +} + +// CLǥͦC +void printStudentList() { + + Student* current = head->rlink; + printf("qY}l\n"); + printf("\nmW\t\t^\tƾ\n"); + printf("--------------------------------\n"); + + while (current != tail) { + printf("%-15s\t%d\t%d\n", current->name, current->english, current->math); + current = current->rlink; + } + + current = tail->llink; + + printf("\nq}l\n"); + printf("\nmW\t\t^\tƾ\n"); + printf("--------------------------------\n"); + while (current != head) { + printf("%-15s\t%d\t%d\n", current->name, current->english, current->math); + current = current->llink; + } +} + +void sort_name(){ + Student* temp ; + Student* current; + + //YSƩΥu@ + if (head->rlink == tail || head->rlink->rlink == tail) { + return; + } + + int flag = 1; + while(flag){ + flag = 0; + current = head->rlink; + + while(current->rlink != tail){ + temp = current->rlink; + + if(strcmp(current->name,temp->name) < 0){ +// uϥΨӸ`Ii`I洫 +// n`NЧܫ᪺ +// YUC{ǥ洫ЫV}|X +// ]iHhŧiӸ`I current->llinktemp->rlink +// o˴NiHL޶ + temp->llink = current->llink; + current->rlink = temp->rlink; + + temp->rlink->llink = current; + temp->rlink = current; + + current->llink->rlink = temp; + current->llink = temp; + + flag = 1; + } + else{ + current = current->rlink; + } + } + } + print("HWrƧ\n"); +// printStudentList(); +} + + +void sort_eng(){ + Student* temp ; + Student* current; + + //YSƩΥu@ + if (head->rlink == tail || head->rlink->rlink == tail) { + return; + } + + int flag = 1; + while(flag){ + flag = 0; + current = head->rlink; + + while(current->rlink != tail){ + temp = current->rlink; + + if(current->english < temp->english){ +// uϥΨӸ`Ii`I洫 +// n`NЧܫ᪺ +// YUC{ǥ洫ЫV}|X +// ]iHhŧiӸ`I current->llinktemp->rlink +// o˴NiHL޶ + temp->llink = current->llink; + current->rlink = temp->rlink; + + temp->rlink->llink = current; + temp->rlink = current; + + current->llink->rlink = temp; + current->llink = temp; + + flag = 1; + } + else{ + current = current->rlink; + } + } + } + print("H^妨ZƧ\n"); +// printStudentList(); +} + +void sort_math(){ + Student* temp ; + Student* current; + + //YSƩΥu@ + if (head->rlink == tail || head->rlink->rlink == tail) { + return; + } + + int flag = 1; + while(flag){ + flag = 0; + current = head->rlink; + + while(current->rlink != tail){ + temp = current->rlink; + + if(current->math < temp->math){ +// uϥΨӸ`Ii`I洫 +// n`NЧܫ᪺ +// YUC{ǥ洫ЫV}|X +// ]iHhŧiӸ`I current->llinktemp->rlink +// o˴NiHL޶ + temp->llink = current->llink; + current->rlink = temp->rlink; + + temp->rlink->llink = current; + temp->rlink = current; + + current->llink->rlink = temp; + current->llink = temp; + + flag = 1; + } + else{ + current = current->rlink; + } + } + } + print("HƾǦZƧ\n"); +// printStudentList(); +} + + +int main() { + init_f(); + readStudentsFromFile("YunTechStudents.txt"); +// printStudentList(); + modify_list(); + + sort_name(); + + sort_math(); + + sort_eng(); + + + return 0; +} diff --git a/作業/unit4/DS4_try.o b/作業/unit4/DS4_try.o new file mode 100644 index 0000000..086f7ac Binary files /dev/null and b/作業/unit4/DS4_try.o differ diff --git a/作業/unit4/DS4_v2(try).c b/作業/unit4/DS4_v2(try).c new file mode 100644 index 0000000..dc43368 --- /dev/null +++ b/作業/unit4/DS4_v2(try).c @@ -0,0 +1,472 @@ +#include +#include +#include +#include +#include + +#define MAX_NAME_LENGTH 24 + +//ŧi禡쫬 +void init_f(); +void insertStudent(char* name, int english, int math); +void modify_list(); +void add_data(char* name, int english, int math); +void remove_data(char* name); +void readStudentsFromFile(char* filename); +void printStudentList(); +void sort_name(); +void sort_eng(); +void sort_math(); +void choose_subject(); +void find_student(int number , int mode); + +// wqǥ͸`Ic +typedef struct Student { + char name[MAX_NAME_LENGTH]; + int english; + int math; + struct Student* llink; + struct Student* rlink; +} Student; + +Student *head, *tail, *current, *prev, *temp; +FILE* file; + +//]@ headANk쵲ҫV +void init_f() { + head = (Student *) malloc(sizeof(Student)); // head + head->llink = head; // 쵲Vۤv + head->rlink = head; // k쵲Vۤv + tail = head; +} + +// bJsǥ͸`I +void insertStudent(char* name, int english, int math) { + + Student* newNode = (Student*)malloc(sizeof(Student)); + strcpy(newNode->name, name); + + newNode->english = english; + newNode->math = math; + + if(head->rlink == tail) { + // oOĤ@ӴJ`I + head->rlink = newNode; + tail->llink = newNode; + newNode->llink = head; + newNode->rlink = tail; + } else { + //OĤ@ J + newNode->llink = tail->llink; + newNode->rlink = tail; + tail->llink->rlink = newNode; + tail->llink = newNode; + } +} + +// ***᪺W[δָ +void modify_list(){ + char name[MAX_NAME_LENGTH]; + int english, math; + char line[100]; + + while(fgets(line, sizeof(line), file)!=NULL){ + if(line[0]=='+'){ + sscanf(line+2, "%23[^\t]\t%d\t%d\n", name, &english, &math); + printf("\n*******************************\n"); + printf("W[@\n\n"); + add_data(name, english, math); + printStudentList(); + }else if(line[0]=='-'){ + sscanf(line+2, "%23[^\t]\t%d\t%d\n", name, &english, &math); + printf("\n*******************************\n"); + printf("R@\n\n"); + remove_data(name); + printStudentList(); + } + } + fclose(file); +} + +//W[ +void add_data(char* name, int english, int math){ + Student* newNode = (Student*)malloc(sizeof(Student)); + strcpy(newNode->name, name); + + newNode->english = english; + newNode->math = math; + + newNode->llink = tail->llink; + newNode->rlink = tail; + tail->llink->rlink = newNode; + tail->llink = newNode; + printf("%s wW[\n\n", name); +} + +//ָ +void remove_data(char* name){ + + prev = head; + current = head->rlink; + + while(current!=tail &&strcmp(name,current->name)!=0){ + prev=current; + current=current->rlink; + } + if(current != tail){ + + current->rlink->llink = prev; + prev->rlink = current->rlink; + printf("%s wR\n\n", name); + free(current); + }else /* 䤣ƫhܿ~ */ + printf(" %s bC\n", name); + +} + +// qŪǥ͸ +void readStudentsFromFile(char* filename) { + file = fopen(filename, "r"); + if (file == NULL) { + printf("Lk}ɮ %s\n", filename); + return; + } + + char line[100]; + int lineCount = 0; + + // Le| + while (lineCount < 4 && fgets(line, sizeof(line), file)) { + lineCount++; + } + + // Ūǥ͸ + char name[MAX_NAME_LENGTH]; + int english, math; + // %[ ]ܭnŪJ@ӦrŶX + // %23[^\t]uŪ̦h23ӦršAJ\tv ^D O\tNŪ + // Y\ŪƷ|^3 YŪ uŪnameΨSŪƫh^ǭȤ3 + while(fgets(line, sizeof(line), file)!=NULL){ + if(isalpha(line[0])){ + sscanf(line, "%23[^\t]\t%d\t%d\n", name, &english, &math); + insertStudent(name, english, math); + }else if(line[0]=='*'){ + break; + } + } +// flocseե `ϥbmodify_list +// fclose(file); +} + +// CLǥͦC +void printStudentList() { + + current = head->rlink; + + printf("\nqY}l\n"); + printf("\nmW\t\t^\tƾ\n"); + printf("--------------------------------\n"); + + while (current != tail) { + printf("%-15s\t%d\t%d\n", current->name, current->english, current->math); + current = current->rlink; + } + + current = tail->llink; + + printf("\nq}l\n"); + printf("\nmW\t\t^\tƾ\n"); + printf("--------------------------------\n"); + while (current != head) { + printf("%-15s\t%d\t%d\n", current->name, current->english, current->math); + current = current->llink; + } +} + +//̷ӦWriƧ +void sort_name(){ + + //YSƩΥu@ + if (head->rlink == tail || head->rlink->rlink == tail) { + return; + } + + int flag = 1; + while(flag){ + flag = 0; + current = head->rlink; + + while(current->rlink != tail){ + temp = current->rlink; + + if(strcmp(current->name,temp->name) > 0){ +// uϥΨӸ`Ii`I洫 +// n`NЧܫ᪺ +// YUC{ǥ洫ЫV}|X +// ]iHhŧiӸ`I current->llinktemp->rlink +// o˴NiHL޶ + temp->llink = current->llink; + current->rlink = temp->rlink; + + temp->rlink->llink = current; + temp->rlink = current; + + current->llink->rlink = temp; + current->llink = temp; + + flag = 1; + } + else{ + current = current->rlink; + } + } + } +} + +//̷ӭ^妨ZiƧ +void sort_eng(){ + + //YSƩΥu@ + if (head->rlink == tail || head->rlink->rlink == tail) { + return; + } + + int flag = 1; + while(flag){ + flag = 0; + current = head->rlink; + + while(current->rlink != tail){ + temp = current->rlink; + + if(current->english < temp->english){ +// uϥΨӸ`Ii`I洫 +// n`NЧܫ᪺ +// YUC{ǥ洫ЫV}|X +// ]iHhŧiӸ`I current->llinktemp->rlink +// o˴NiHL޶ + temp->llink = current->llink; + current->rlink = temp->rlink; + + temp->rlink->llink = current; + temp->rlink = current; + + current->llink->rlink = temp; + current->llink = temp; + + flag = 1; + } + else{ + current = current->rlink; + } + } + } +} + +//̷ӭ^妨ZiƧ +void sort_math(){ + + //YSƩΥu@ + if (head->rlink == tail || head->rlink->rlink == tail) { + return; + } + + int flag = 1; + while(flag){ + flag = 0; + current = head->rlink; + + while(current->rlink != tail){ + temp = current->rlink; + + if(current->math < temp->math){ +// uϥΨӸ`Ii`I洫 +// n`NЧܫ᪺ +// YUC{ǥ洫ЫV}|X +// ]iHhŧiӸ`I current->llinktemp->rlink +// o˴NiHL޶ + temp->llink = current->llink; + current->rlink = temp->rlink; + + temp->rlink->llink = current; + temp->rlink = current; + + current->llink->rlink = temp; + current->llink = temp; + + flag = 1; + } + else{ + current = current->rlink; + } + } + } +} + +//ܬؤαƦW +void choose_subject() { + int subject, number; + char mode; + + printf("\nJܪ\n" + "1 ƾ 2 ^ ==> "); + mode = getche(); + + if (mode != '1' && mode != '2') { + printf("\nJ~\n"); + return; + } + + printf("\nJƦW(JЫEnter) ==> "); + scanf("%d", &number); + + // ھڿܪضiƧ + if (mode == '1') { + sort_math(); + } else { + sort_eng(); + } + + find_student(number, mode - '0'); + + // ܧƦWC + printf("\nҦpU"); + printf("\nƦW\tmW\t\t^\tƾ"); + printf("\n-----------------------------------\n"); + + current = head->rlink; + int actualRank = 1; // ڱƦW]Ҽ{P^ + int position = 1; // mp + int prevScore = -1; // e@Ӥ + + while (current != tail) { + int currentScore; + if (mode == '1') { + currentScore = current->math; + } else { + currentScore = current->english; + } + + // pGeƻPe@ӤƤPAsڱƦWem + if (currentScore != prevScore) { + actualRank = position; + } + + printf("%d\t%-15s\t%d\t%d\n", + actualRank, + current->name, + current->english, + current->math); + + prevScore = currentScore; + position++; // mû[1 + current = current->rlink; + } +} + + +//ھڬؤαƦWǥ +void find_student(int number, int mode) { + current = head->rlink; + int actualRank = 1; // ڱƦW + int position = 1; // mp + int prevScore = -1; // e@Ӥ + + printf("\n*****************************\n"); + printf("%sƦW%dǥͬG\n\n", + (mode == 1) ? "ƾ" : "^", number); + printf("mW\t\t^\tƾ\n"); + + // MĤ@ƪơAlprevScore + if (current != tail) { + prevScore = (mode == 1) ? current->math : current->english; + } + + while (current != tail) { + int currentScore = (mode == 1) ? current->math : current->english; + + // pGeƻPe@ӤƤPAsڱƦW + if (currentScore != prevScore) { + actualRank = position; + } + + // pGؼбƦWALXӥ͸ + if (actualRank == number) { + printf("%-15s\t%d\t%d\n", + current->name, + current->english, + current->math); + } + + prevScore = currentScore; + position++; + current = current->rlink; + } + printf("*****************************\n"); +} + +//Ҧ`I +void freeAllNodes() { + current = head->rlink; + while (current != tail) { + Student* temp = current; + current = current->rlink; + free(temp); + } + free(head); // head `I +} + +int main() { + char mode ,sort_mode; + init_f(); + readStudentsFromFile("YunTechStudents.txt"); + printStudentList(); + modify_list(); + + while(1){ + printf("\n******* ܶiƧǩάOƦWnWǥ *******\n" + "*--------------------------------------*\n" + "* 1 iƧ 2 ܱƦWnWǥ 3 *\n" + "\nпܥ\\ ==> "); // \\ b|ܶýX + mode = getche(); + switch(mode){ + case '1': + printf("\n\nܱƧǤ覡\n" + "*--------------------------------------*\n" + "1 Wr 2 ^妨Z 3 ƾǦZ \n" + "\nпܱƧǤ覡 ==> "); + sort_mode = getche(); + switch(sort_mode){ + case '1': + printf("\n\nHWriƧ\n"); + sort_name(); + printStudentList(); + break; + case '2': + printf("\n\nH^妨ZiƧ\n"); + sort_eng(); + printStudentList(); + break; + case '3': + printf("\n\nHƾǦZiƧ\n"); + sort_math(); + printStudentList(); + break; + default: + printf("\nJ~\n"); + break; + } + break; + case '2': + choose_subject(); + break; + case '3': + printf("\n\n¨ϥΡABye~\n"); + freeAllNodes(); + return 0; + default: + printf("\nJ~\n"); + break; + } + } +} diff --git a/作業/unit4/DS4_v2(try).exe b/作業/unit4/DS4_v2(try).exe new file mode 100644 index 0000000..766c99a Binary files /dev/null and b/作業/unit4/DS4_v2(try).exe differ diff --git a/作業/unit4/Doubly Linked List.c b/作業/unit4/Doubly Linked List.c new file mode 100644 index 0000000..f13198d --- /dev/null +++ b/作業/unit4/Doubly Linked List.c @@ -0,0 +1,75 @@ +#include +#include + +// wq`Ic +typedef struct Node { + int data; + struct Node* prev; + struct Node* next; +} Node; + +// wqV쵲Cc +typedef struct { + Node* head; + Node* tail; +} DoublyLinkedList; + +// lV쵲C +void initList(DoublyLinkedList* list) { + list->head = NULL; + list->tail = NULL; +} + +// bJs`I +void insertAtTail(DoublyLinkedList* list, int data) { + Node* newNode = (Node*)malloc(sizeof(Node)); + newNode->data = data; + newNode->next = NULL; + + if (list->tail == NULL) { + newNode->prev = NULL; + list->head = newNode; + list->tail = newNode; + } else { + newNode->prev = list->tail; + list->tail->next = newNode; + list->tail = newNode; + } +} + +// qYMæLXC +void printListForward(DoublyLinkedList* list) { + Node* current = list->head; + printf("qY: "); + while (current != NULL) { + printf("%d ", current->data); + current = current->next; + } + printf("\n"); +} + +// qYMæLXC +void printListBackward(DoublyLinkedList* list) { + Node* current = list->tail; + printf("qY: "); + while (current != NULL) { + printf("%d ", current->data); + current = current->prev; + } + printf("\n"); +} + +// Dƥܨ +int main() { + DoublyLinkedList list; + initList(&list); + + insertAtTail(&list, 10); + insertAtTail(&list, 20); + insertAtTail(&list, 30); + + printListForward(&list); + printListBackward(&list); + + return 0; +} diff --git a/作業/unit4/Doubly Linked List.o b/作業/unit4/Doubly Linked List.o new file mode 100644 index 0000000..a4a69e8 Binary files /dev/null and b/作業/unit4/Doubly Linked List.o differ diff --git a/作業/unit4/Makefile.win b/作業/unit4/Makefile.win new file mode 100644 index 0000000..4140a50 --- /dev/null +++ b/作業/unit4/Makefile.win @@ -0,0 +1,28 @@ +# Project: Project9 +# Makefile created by Dev-C++ 5.11 + +CPP = g++.exe +CC = gcc.exe +WINDRES = windres.exe +OBJ = slist.o +LINKOBJ = slist.o +LIBS = -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib" -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/lib" -static-libgcc +INCS = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include" +CXXINCS = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include/c++" +BIN = Project.exe +CXXFLAGS = $(CXXINCS) +CFLAGS = $(INCS) +RM = rm.exe -f + +.PHONY: all all-before all-after clean clean-custom + +all: all-before $(BIN) all-after + +clean: clean-custom + ${RM} $(OBJ) $(BIN) + +$(BIN): $(OBJ) + $(CC) $(LINKOBJ) -o $(BIN) $(LIBS) + +slist.o: slist.c + $(CC) -c slist.c -o slist.o $(CFLAGS) diff --git a/作業/unit4/Project.dev b/作業/unit4/Project.dev new file mode 100644 index 0000000..1647df6 --- /dev/null +++ b/作業/unit4/Project.dev @@ -0,0 +1,65 @@ +[Project] +FileName=Project.dev +Name=Project9 +Type=1 +Ver=2 +ObjFiles= +Includes= +Libs= +PrivateResource= +ResourceIncludes= +MakeIncludes= +Compiler= +CppCompiler= +Linker= +IsCpp=0 +Icon= +ExeOutput= +ObjectOutput= +LogOutput= +LogOutputEnabled=0 +OverrideOutput=0 +OverrideOutputName= +HostApplication= +UseCustomMakefile=0 +CustomMakefile= +CommandLine= +Folders= +IncludeVersionInfo=0 +SupportXPThemes=0 +CompilerSet=0 +CompilerSettings=0000000000000000000000000 +UnitCount=1 + +[VersionInfo] +Major=1 +Minor=0 +Release=0 +Build=0 +LanguageID=1033 +CharsetID=1252 +CompanyName= +FileVersion= +FileDescription=Developed using the Dev-C++ IDE +InternalName= +LegalCopyright= +LegalTrademarks= +OriginalFilename= +ProductName= +ProductVersion= +AutoIncBuildNr=0 +SyncProduct=1 + +[Unit2] +FileName=DS4.c + +[Unit1] +FileName=sList-v3.c +CompileCpp=0 +Folder= +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd= + diff --git a/作業/unit4/Project.exe b/作業/unit4/Project.exe new file mode 100644 index 0000000..9751eb6 Binary files /dev/null and b/作業/unit4/Project.exe differ diff --git a/作業/unit4/Project.layout b/作業/unit4/Project.layout new file mode 100644 index 0000000..ea6ebd6 --- /dev/null +++ b/作業/unit4/Project.layout @@ -0,0 +1,13 @@ +[Editor_0] +CursorCol=1 +CursorRow=106 +TopLine=67 +LeftChar=1 +[Editor_1] +CursorCol=1 +CursorRow=1 +TopLine=1 +LeftChar=1 +[Editors] +Order=0 +Focused=-1 diff --git a/作業/unit4/Student.c b/作業/unit4/Student.c new file mode 100644 index 0000000..c18bc4a --- /dev/null +++ b/作業/unit4/Student.c @@ -0,0 +1,109 @@ +#include +#include +#include + +#define MAX_NAME_LENGTH 24 + +// wqǥ͸`Ic +typedef struct StudentNode { + char name[MAX_NAME_LENGTH]; + int english; + int math; + struct StudentNode* prev; + struct StudentNode* next; +} StudentNode; + +// wqV쵲Cc +typedef struct { + StudentNode* head; + StudentNode* tail; +} StudentList; + +// lƾǥͦC +void initList(StudentList* list) { + list->head = NULL; + list->tail = NULL; +} + +// bJsǥ͸`I +void insertStudent(StudentList* list, char* name, int english, int math) { + int i=0; + StudentNode* newNode = (StudentNode*)malloc(sizeof(StudentNode)); + while(name[i]!='\0'){ + newNode->name[i] = name[i]; +// printf("%c",name[i]); + i++; + } + newNode->name[i] = '\0'; + + newNode->english = english; + newNode->math = math; + newNode->next = NULL; + + if (list->tail == NULL) { + newNode->prev = NULL; + list->head = newNode; + list->tail = newNode; + } else { + newNode->prev = list->tail; + list->tail->next = newNode; + list->tail = newNode; + } +} + +// qŪǥ͸ +void readStudentsFromFile(StudentList* list, const char* filename) { + FILE* file = fopen(filename, "r"); + if (file == NULL) { + printf("Lk}ɮ %s\n", filename); + return; + } + + char line[100]; + int lineCount = 0; + + // Le| + // | + while (lineCount < 4 && fgets(line, sizeof(line), file)) { + lineCount++; + } + + // Ūǥ͸ + char name[MAX_NAME_LENGTH]; + int english, math; + while (fscanf(file, "%49[^\t]\t%d\t%d\n", name, &english, &math) == 3) { + insertStudent(list, name, english, math); + } + + fclose(file); +} + +// CLǥͦC +void printStudentList(StudentList* list) { + StudentNode* current_head = list->head; + StudentNode* current_tail = list->tail; + printf("mW\t\t^\tƾ\n"); + printf("qY}l\n"); + printf("--------------------------------\n"); + while (current_head != NULL) { + printf("%-15s\t%d\t%d\n", current_head->name, current_head->english, current_head->math); + current_head = current_head->next; + } + + printf("\nq}l\n"); + printf("--------------------------------\n"); + while (current_tail != NULL) { + printf("%-15s\t%d\t%d\n", current_tail->name, current_tail->english, current_tail->math); + current_tail = current_tail->prev; + } +} + +int main() { + StudentList list; + initList(&list); + + readStudentsFromFile(&list, "YunTechStudents.txt"); + printStudentList(&list); + + return 0; +} diff --git a/作業/unit4/Student.o b/作業/unit4/Student.o new file mode 100644 index 0000000..8146559 Binary files /dev/null and b/作業/unit4/Student.o differ diff --git a/作業/unit4/TWICE.c b/作業/unit4/TWICE.c new file mode 100644 index 0000000..3cb7093 --- /dev/null +++ b/作業/unit4/TWICE.c @@ -0,0 +1,316 @@ +#include +#include +#include +#include + +#define MAX_NAME_LENGTH 24 + +FILE* file; + +// wqǥ͸`Ic +typedef struct Student { + char name[MAX_NAME_LENGTH]; + int english; + int math; + struct Student* llink; + struct Student* rlink; +} Student; +Student *head, *tail, *current, *prev, *temp; + +//]@ headANk쵲ҫV +void init_f() { + head = (Student *) malloc(sizeof(Student)); // head + head->llink = head; // 쵲Vۤv + head->rlink = head; // k쵲Vۤv + tail = head; +} + +// bJsǥ͸`I +void insertStudent(char* name, int english, int math) { + + Student* newNode = (Student*)malloc(sizeof(Student)); + strcpy(newNode->name, name); + + newNode->english = english; + newNode->math = math; + + if(head->rlink == tail) { + // oOĤ@ӴJ`I + head->rlink = newNode; + tail->llink = newNode; + newNode->llink = head; + newNode->rlink = tail; + } else { + //OĤ@ J + newNode->llink = tail->llink; + newNode->rlink = tail; + tail->llink->rlink = newNode; + tail->llink = newNode; + } +} + +// **᪺W[δָ +void modify_list(){ + char name[MAX_NAME_LENGTH]; + int english, math; + char line[100]; + + while(fgets(line, sizeof(line), file)!=NULL){ + if(line[0]=='+'){ + sscanf(line+2, "%23[^\t]\t%d\t%d\n", name, &english, &math); + printf("\n*******************************\n"); + printf("W[@\n\n"); + printf("%s\n",name); + add_data(name, english, math); + printStudentList(); + }else if(line[0]=='-'){ + sscanf(line+2, "%23[^\t]\t%d\t%d\n", name, &english, &math); + printf("\n*******************************\n"); + printf("֤@\n\n"); + printf("%s\n",name); + remove_data(name); + printStudentList(); + } + } + fclose(file); +} + +//W[ +void add_data(char* name, int english, int math){ + Student* newNode = (Student*)malloc(sizeof(Student)); + strcpy(newNode->name, name); + + newNode->english = english; + newNode->math = math; + + newNode->llink = tail->llink; + newNode->rlink = tail; + tail->llink->rlink = newNode; + tail->llink = newNode; + printf("%s wW[\n", name); +} + +//ָ +void remove_data(char* name){ + + prev = head; + current = head->rlink; + + while(current!=tail &&strcmp(name,current->name)!=0){ + prev=current; + current=current->rlink; + } + if(current != head){ + + current->rlink->llink = prev; + prev->rlink = current->rlink; + printf("%s wQR\n", name); + free(current); + }else /* 䤣ƫhܿ~ */ + printf(" %s bC\n", name); + +} + +// qŪǥ͸ +void readStudentsFromFile(char* filename) { + file = fopen(filename, "r"); + if (file == NULL) { + printf("Lk}ɮ %s\n", filename); + return; + } + + char line[100]; + int lineCount = 0; + + // Le| + // | + while (lineCount < 4 && fgets(line, sizeof(line), file)) { + lineCount++; + } + + // Ūǥ͸ + char name[MAX_NAME_LENGTH]; + int english, math; + // %23[^\t]uŪ̦h23ӦršAJ\tv ^D O\tNŪ + // Y\ŪƷ|^3 YŪ uŪnameΨSŪƫh^ǭȤ3 + while(fgets(line, sizeof(line), file)!=NULL){ + if(isalpha(line[0])){ + sscanf(line, "%23[^\t]\t%d\t%d\n", name, &english, &math); + insertStudent(name, english, math); + }else if(line[0]=='*'){ + break; + } + } + fclose(file); +} + +// CLǥͦC +void printStudentList() { + + Student* current = head->rlink; + printf("qY}l\n"); + printf("\nmW\t\t^\tƾ\n"); + printf("--------------------------------\n"); + + while (current != tail) { + printf("%-15s\t%d\t%d\n", current->name, current->english, current->math); + current = current->rlink; + } + + current = tail->llink; + + printf("\nq}l\n"); + printf("\nmW\t\t^\tƾ\n"); + printf("--------------------------------\n"); + while (current != head) { + printf("%-15s\t%d\t%d\n", current->name, current->english, current->math); + current = current->llink; + } +} + +void sort_name(){ + Student* temp ; + Student* current; + + //YSƩΥu@ + if (head->rlink == tail || head->rlink->rlink == tail) { + return; + } + + int flag = 1; + while(flag){ + flag = 0; + current = head->rlink; + + while(current->rlink != tail){ + temp = current->rlink; + + if(strcmp(current->name,temp->name) < 0){ +// uϥΨӸ`Ii`I洫 +// n`NЧܫ᪺ +// YUC{ǥ洫ЫV}|X +// ]iHhŧiӸ`I current->llinktemp->rlink +// o˴NiHL޶ + temp->llink = current->llink; + current->rlink = temp->rlink; + + temp->rlink->llink = current; + temp->rlink = current; + + current->llink->rlink = temp; + current->llink = temp; + + flag = 1; + } + else{ + current = current->rlink; + } + } + } + print("HWrƧ\n"); +// printStudentList(); +} + + +void sort_eng(){ + Student* temp ; + Student* current; + + //YSƩΥu@ + if (head->rlink == tail || head->rlink->rlink == tail) { + return; + } + + int flag = 1; + while(flag){ + flag = 0; + current = head->rlink; + + while(current->rlink != tail){ + temp = current->rlink; + + if(current->english < temp->english){ +// uϥΨӸ`Ii`I洫 +// n`NЧܫ᪺ +// YUC{ǥ洫ЫV}|X +// ]iHhŧiӸ`I current->llinktemp->rlink +// o˴NiHL޶ + temp->llink = current->llink; + current->rlink = temp->rlink; + + temp->rlink->llink = current; + temp->rlink = current; + + current->llink->rlink = temp; + current->llink = temp; + + flag = 1; + } + else{ + current = current->rlink; + } + } + } + print("H^妨ZƧ\n"); +// printStudentList(); +} + +void sort_math(){ + Student* temp ; + Student* current; + + //YSƩΥu@ + if (head->rlink == tail || head->rlink->rlink == tail) { + return; + } + + int flag = 1; + while(flag){ + flag = 0; + current = head->rlink; + + while(current->rlink != tail){ + temp = current->rlink; + + if(current->math < temp->math){ +// uϥΨӸ`Ii`I洫 +// n`NЧܫ᪺ +// YUC{ǥ洫ЫV}|X +// ]iHhŧiӸ`I current->llinktemp->rlink +// o˴NiHL޶ + temp->llink = current->llink; + current->rlink = temp->rlink; + + temp->rlink->llink = current; + temp->rlink = current; + + current->llink->rlink = temp; + current->llink = temp; + + flag = 1; + } + else{ + current = current->rlink; + } + } + } + print("HƾǦZƧ\n"); +// printStudentList(); +} + + +int main() { + init_f(); + readStudentsFromFile("YunTechStudents.txt"); +// printStudentList(); +// modify_list(); + + sort_name(); + + sort_math(); + + sort_eng(); + + + return 0; +} diff --git a/作業/unit4/TWICE.o b/作業/unit4/TWICE.o new file mode 100644 index 0000000..1fc8660 Binary files /dev/null and b/作業/unit4/TWICE.o differ diff --git a/作業/unit4/Untitled11 b/作業/unit4/Untitled11 new file mode 100644 index 0000000..e69de29 diff --git a/作業/unit4/YunTechStudents.txt b/作業/unit4/YunTechStudents.txt new file mode 100644 index 0000000..665b05c --- /dev/null +++ b/作業/unit4/YunTechStudents.txt @@ -0,0 +1,18 @@ +YunTech EE Department (2024) +====================================== +Name English Math +---------------+-------+-------------- +Steve Jobs 50 60 +Tom Cruise 30 40 +Marie Jane 70 80 +Barrack Obama 46 77 +John Tyler 98 96 +U. S. Grant 97 88 +Robert Redford 22 33 +Bruce Lee 90 90 +************************************** ++ Oliver Hardy 90 80 ++ Slim Pickens 88 82 +- Marie Jane 0 0 ++ James Bond 88 82 +- Barrack Obama 0 0 \ No newline at end of file diff --git a/作業/unit4/YunTechStudents2.txt b/作業/unit4/YunTechStudents2.txt new file mode 100644 index 0000000..ceade09 --- /dev/null +++ b/作業/unit4/YunTechStudents2.txt @@ -0,0 +1,20 @@ +YunTech EE Department (2024) +====================================== +Name English Math +---------------+-------+-------------- +Steve Jobs 50 60 +Tom Cruise 30 40 +Marie Jane 70 80 +Barrack Obama 46 77 +John Tyler 98 96 +U. S. Grant 97 88 +Robert Redford 22 33 +Bruce Lee 90 90 +************************************** +- Steve Jobs 0 0 ++ Oliver Hardy 90 80 ++ Slim Pickens 88 82 +- Marie Jane 0 0 ++ James Bond 88 82 +- Barrack Obama 0 0 +- James Bond 0 0 \ No newline at end of file diff --git a/作業/unit4/dlist.c b/作業/unit4/dlist.c new file mode 100644 index 0000000..2f97c80 --- /dev/null +++ b/作業/unit4/dlist.c @@ -0,0 +1,185 @@ +/* file name: dList.c */ +/* V䵲C[JPR */ + +#include +#include +#include + +void init_f(void); /* lƦCAإߤ@Ÿ`I head */ +void insert_f(void); /* J */ +void sort_f(void); /* ƧǨ */ +void delete_f(void); /* R */ +void display_f(void); /* X */ +void modify_f(void); /* ק */ +void flushBuffer(void); + +struct Student { + char name[20]; /* mW */ + int score; /* */ + struct Student *llink; /* `I쵲 */ + struct Student *rlink; /* `Ik쵲 */ +}; +struct Student *ptr, *head, *tail, *current, *prev, *temp; + +int main(void) +{ + char option1; + + init_f(); + while(1) { + printf("\nV쵲CB@\n"); + printf("************\n"); + printf(" 1.insert\n"); + printf(" 2.delete\n"); + printf(" 3.display\n"); + printf(" 4.modify\n"); + printf(" 5.quit\n"); + printf("*************\n"); + printf("пJﶵ(1-5): "); + option1 = getchar(); + flushBuffer(); + switch (option1) { + case '1': + insert_f(); + break; + case '2': + delete_f(); + break; + case '3': + display_f(); + break; + case '4': + modify_f(); + break; + case '5': + printf("\n{\n"); + exit(0); + } + } + return 0; +} + +void init_f(void) /* ]@ headANk쵲ҫV */ +{ + ptr = (struct Student *) malloc(sizeof(struct Student)); + strcpy(ptr->name, "0"); + ptr->llink = ptr; + ptr->rlink = ptr; + head = ptr; + tail = ptr; +} + +void insert_f(void) +{ + ptr = (struct Student *) malloc(sizeof(struct Student)); + printf("\n mW: "); + scanf("%s", ptr->name); + printf(" Z: "); + scanf("%d", &ptr->score); + flushBuffer(); + + /* HưCƦC */ + prev = head; + current = head->rlink; + while (current != head && current->score > ptr->score) { + prev = current; + current = current->rlink; + } + ptr->rlink = current; + ptr->llink = prev; + prev->rlink = ptr; + current->llink = ptr; +} + +void delete_f(void) +{ + char del_name[20]; + printf("\n RmW: "); + scanf("%s", del_name); + flushBuffer(); + prev = head; + current = head->rlink; + while (current != head && strcmp(del_name, current->name) != 0) { + prev = current; + current = current->rlink; + } + if (current != head) { + prev->rlink = current->rlink; + current->rlink->llink = prev; + printf(" %s wQR\n", del_name); + free(current); + } + else /* 䤣ƫhܿ~ */ + printf(" %s bC\n", del_name); +} + +void modify_f(void) +{ + char n_temp[20]; + printf("\n ק諸mW: "); + scanf("%s", n_temp); + prev = head; + current = head->rlink; + while (current != head && strcmp(n_temp, current->name)) { + prev = current; + current = current->rlink; + } + if (current == head) { + printf(" %s SbC\n", n_temp); + } + else { + printf(" ******************\n"); + printf(" mW : %s\n", current->name); + printf(" : %d\n", current->score); + printf(" ******************\n"); + printf(" пJs: "); + scanf("%d", ¤t->score); + flushBuffer(); + printf(" %s wQק\n", n_temp); + //Nק諸`I[JAm + //N current `Iw tempAísվ㥪Bk`I + temp = current; + prev->rlink = current->rlink; + current->rlink->llink = prev; + //AN temp `I[JC + /* HưCƦC */ + prev = head; + current = head->rlink; + while (current != head && current->score > temp->score) { + prev = current; + current = current->rlink; + } + temp->rlink = current; + temp->llink = prev; + prev->rlink = temp; + current->llink = temp; + } +} + +void display_f(void) +{ + int count = 0; + if (head->rlink == head) { + printf("\n CL\n"); + } + else { + printf("\n"); + printf(" NAME SCORE\n"); + printf(" ----------------------\n"); + current = head->rlink; + while (current != head) { + printf(" %-15s %3d\n", current->name, current->score); + count++; + current = current->rlink; + } + printf(" ----------------------\n"); + printf(" `@ %d \n", count); + } +} + +void flushBuffer(void) +{ + while(getchar() != '\n') + continue; +} + diff --git a/作業/unit4/list.txt b/作業/unit4/list.txt new file mode 100644 index 0000000..f02855b --- /dev/null +++ b/作業/unit4/list.txt @@ -0,0 +1,9 @@ +1 jeff 80 +2 tim 90 +3 jack 84 +4 sam 85 +5 poson 76 +6 dan 14 +7 ren 40 +8 eric 96 +9 ben 36 diff --git a/作業/unit4/sList-v2.zip b/作業/unit4/sList-v2.zip new file mode 100644 index 0000000..d82d5bf Binary files /dev/null and b/作業/unit4/sList-v2.zip differ diff --git a/作業/unit4/sList-v2/list.txt b/作業/unit4/sList-v2/list.txt new file mode 100644 index 0000000..f02855b --- /dev/null +++ b/作業/unit4/sList-v2/list.txt @@ -0,0 +1,9 @@ +1 jeff 80 +2 tim 90 +3 jack 84 +4 sam 85 +5 poson 76 +6 dan 14 +7 ren 40 +8 eric 96 +9 ben 36 diff --git a/作業/unit4/sList-v2/sList-v2.c b/作業/unit4/sList-v2/sList-v2.c new file mode 100644 index 0000000..0a7bf2f --- /dev/null +++ b/作業/unit4/sList-v2/sList-v2.c @@ -0,0 +1,272 @@ +/* sList.c */ +#include +#include +#include + +/* wq@V FILE */ +FILE *fptr; + +/* 禡쫬ŧi */ +void init_f(void); +void insertStudent(int id, char* name, double score); +void readFromFile(const char* filename); +void saveToFile(const char* filename); +void insert(void); +void del(void); +void modify(void); +void display(void); + +// wqǥ͸`Ic +typedef struct Student { + long int id; + char name[10]; + double score; + struct Student *rlink; + struct Student *llink; +} Student; +Student *head, *pNode ,*tail, *current, *prev, *temp ; + +//]@ headANk쵲ҫV +void init_f() { + head = (Student *) malloc(sizeof(Student)); + tail = (Student *) malloc(sizeof(Student)); + + // l head M tail + head->llink = NULL; + head->rlink = tail; + + tail->llink = head; + tail->rlink = NULL; +} + +// bJsǥ͸`I +void insertStudent(int id, char* name, double score) { + + Student* newNode = (Student*)malloc(sizeof(Student)); + + + newNode->id = id; + strcpy(newNode->name, name); + newNode->name[9] = '\0'; + newNode->score = score; + + // Je + newNode->rlink = tail; + newNode->llink = tail->llink; + tail->llink->rlink = newNode; + tail->llink = newNode; +} + +// Ū +void readFromFile(const char* filename) { + char line[100]; + FILE* fptr = fopen(filename, "r"); + if (fptr == NULL) { + printf("Lk}ɮ %s\n", filename); + return; + } + + long int id; + char name[10]; + double score; + while(fgets(line ,sizeof(line) ,fptr)!=NULL){ + if(sscanf(line,"%ld\t%9s\t%lf", &id, name, &score) == 3){ + insertStudent(id, name, score); + } + } + fclose(fptr); + printf("ɮ׸\n"); +} + +// s +void saveToFile(const char* filename ) { + FILE* fptr = fopen(filename, "w"); + if (fptr == NULL) { + printf("Lk}ɮ %s igJ\n", filename); + return; + } + Student* current = head->rlink; + while (current != tail ) { + fprintf(fptr, "%ld\t%s\t%.lf\n", current->id, current->name, current->score); + current = current->rlink; + } + + fclose(fptr); + printf("Ƥw\\xs %s\n", filename); +} + +//ܦC +void printStudentList() { + + Student* current = head->rlink; + printf("\n*******************************"); + + if (current != NULL) { + printf("\n%6s %10s %8s\n", "ID", "Name", "Score"); + printf("-------------------------------\n"); + while (current != tail) { + printf("%6ld %10s %8.1f\n", current->id,current->name, current->score); + /* NвU@Ӹ`I */ + current = current->rlink; + } + } + /* YOŪAhX쵲CL */ + else { + printf("\n쵲CL\n"); + } + printf("*******************************\n\n"); +} + +int main(){ + init_f(); + readFromFile("list.txt"); + printStudentList(); + /* QΤ@ϥοܥ\ඵ */ + int choice; + do { + printf("************************\n"); + printf("쵲CB@\n"); + printf("1. [J@`I\n"); + printf("2. R@`I\n"); + printf("3. ק@`I\n"); + printf("4. ܩҦ`I\n"); + printf("5. \n"); + printf("п: "); + scanf("%d", &choice); + switch (choice) { + case 1: + insert(); + break; + case 2: + del(); + break; + case 3: + modify(); + break; + case 4: + printStudentList(); + break; + case 5: + printf("\n{\n"); + saveToFile("list.txt"); + exit(0); + default: + printf("JXTAЭsJ\n"); + } + printf("\n"); + } while(choice != 5); + getchar(); + return 0; +} + +/* ӤƥѤjܤp[J@`I쵲C */ +void insert() +{ + /* Q malloc() 禡tmO*/ + Student* newNode = (Student*)malloc(sizeof(Student)); + + printf("\nпJID: "); + scanf("%ld", &newNode->id); + printf("пJmW: "); + scanf("%s", newNode->name); + printf("пJ: "); + scanf("%lf", &newNode->score); + + /* [J@`I쵲C */ + current = head->rlink; + prev = head; + + // Je + newNode->rlink = tail; + newNode->llink = tail->llink; + tail->llink->rlink = newNode; + tail->llink = newNode; +} + +/* RY@`I*/ +void del() +{ + long int deleteID; + /* N current ЫV head U@Ӹ`I */ + current = head->rlink; + prev = head; + /* P_쵲CO_ */ + if (current != NULL) { + /* YOŪAhMR`I */ + printf("\nпJR ID: "); + scanf("%ld", &deleteID); + /* MR`I */ + while ((current != tail) && (current->id != deleteID)) { + prev = current; + current = current->rlink; + } + /* YAhNR */ + if (current != tail) { + current->rlink->llink = prev; + prev->rlink = current->rlink; + printf("ID: %ld wR\n", current->id); + + free(current); + } + /* YSAhX䤣R`IT*/ + else { + printf("\n䤣R`I\n"); + } + } + /* YOŪAhX쵲COŪT */ + else { + printf("쵲COŪ\n"); + } +} + +/* קY@`I */ +void modify() +{ + Student *temp; + long int modifyID; + double modifyScore; + int flag = 0; + printf("\nпJק`I ID: "); + scanf("%ld", &modifyID); + current = head->rlink; + prev = head; + + /* Mק諸`I */ + while (current != tail) { + if (current->id == modifyID) { + printf("ثeק`IƦpU:\n"); + printf("%6ld %10s %8.1f\n\n", current->id,current->name, current->score); + printf("пJק諸: "); + scanf("%lf", &modifyScore); + current->score = modifyScore; + flag = 1; + break; + } + else { + prev = current; + current = current->rlink; + } + } + /* P_O_ק諸`I */ + if (flag != 0) { + /* N current `Iw temp */ +// temp = current; +// prev->rlink = current->rlink; + /* N temp `I[J쵲C */ +// current = head->rlink; +// prev = head; +// while ((current != tail) && (temp->score < current->score)) { +// prev = current; +// current = current->rlink; +// } +// prev->rlink = temp; +// temp->rlink = current; + } + else { + printf("䤣ק諸`I\n"); + } +} + + + + diff --git a/作業/unit4/sList-v3.c b/作業/unit4/sList-v3.c new file mode 100644 index 0000000..36e8829 --- /dev/null +++ b/作業/unit4/sList-v3.c @@ -0,0 +1,449 @@ +/* sList.c */ +#include +#include +#include + +/* wq@V FILE */ +FILE *fptr; + +/* 禡쫬ŧi */ +void init_f(void); +void insertStudent(int id, char* name, double score); +void readFromFile(const char* filename); +void saveToFile(const char* filename, int flag); +void insert(void); +void del(void); +void modify(void); +void display(void); + +// wqǥ͸`Ic +typedef struct Student { + long int id; + char name[10]; + double score; + struct Student *rlink; + struct Student *llink; +} Student; +Student *head, *pNode ,*tail, *current, *prev, *temp , *originalHead ,*originalTail; + +//]@ headANk쵲ҫV +void init_f() { + head = (Student *) malloc(sizeof(Student)); + tail = (Student *) malloc(sizeof(Student)); + + // l head M tail + head->llink = NULL; + head->rlink = tail; + + tail->llink = head; + tail->rlink = NULL; + + // lƭlǦC + originalHead = (Student *) malloc(sizeof(Student)); + originalTail = (Student *) malloc(sizeof(Student)); + + originalHead->llink = NULL; + originalHead->rlink = originalTail; + originalTail->llink = originalHead; + originalTail->rlink = NULL; +} + +// bJsǥ͸`I +void insertStudent(int id, char* name, double score) { + + Student* newNode = (Student*)malloc(sizeof(Student)); + + + newNode->id = id; + strcpy(newNode->name, name); + newNode->name[9] = '\0'; + newNode->score = score; + + // Je + newNode->rlink = tail; + newNode->llink = tail->llink; + tail->llink->rlink = newNode; + tail->llink = newNode; +} + +/* sWơGJ`IlǦC */ +void insertOriginalList(int id, char* name, double score) { + Student* newNode = (Student*)malloc(sizeof(Student)); + + newNode->id = id; + strncpy(newNode->name, name, 9); + newNode->name[9] = '\0'; + newNode->score = score; + + // JlCe + newNode->rlink = originalTail; + newNode->llink = originalTail->llink; + originalTail->llink->rlink = newNode; + originalTail->llink = newNode; +} + +// Ū +void readFromFile(const char* filename) { + char line[100]; + FILE* fptr = fopen(filename, "r"); + if (fptr == NULL) { + printf("Lk}ɮ %s\n", filename); + return; + } + + long int id; + char name[10]; + double score; + while(fgets(line ,sizeof(line) ,fptr)!=NULL){ + if(sscanf(line,"%ld\t%9s\t%lf", &id, name, &score) == 3){ + insertStudent(id, name, score); + insertOriginalList(id, name, score); // JlǦC + } + } + fclose(fptr); + printf("ɮ׸\n"); +} + +// s +void saveToFile(const char* filename , int flag) { + FILE* fptr = fopen(filename, "w"); + if (fptr == NULL) { + printf("Lk}ɮ %s igJ\n", filename); + return; + } + + if(flag == 2){ + Student* current = head->rlink; + while (current != tail ) { + fprintf(fptr, "%ld\t%s\t%.lf\n", current->id, current->name, current->score); + current = current->rlink; + } + }else if(flag == 1){ + Student* current = originalHead->rlink; + while (current != originalTail ) { + fprintf(fptr, "%ld\t%s\t%.lf\n", current->id, current->name, current->score); + current = current->rlink; + } + } + + + fclose(fptr); + printf("Ƥw\\xs %s\n", filename); +} + +//ܦC +void printStudentList() { + + Student* current = head->rlink; + printf("\n*******************************"); + + if (current != NULL) { + printf("\n%6s %10s %8s\n", "ID", "Name", "Score"); + printf("-------------------------------\n"); + while (current != tail) { + printf("%6ld %10s %8.1f\n", current->id,current->name, current->score); + /* NвU@Ӹ`I */ + current = current->rlink; + } + } + /* YOŪAhX쵲CL */ + else { + printf("\n쵲CL\n"); + } + printf("*******************************\n\n"); +} + +/* sWܭlǸƪ */ +void printOriginalList() { + Student* current = originalHead->rlink; + printf("\n*******************************"); + + if (current != originalTail) { + printf("\n%6s %10s %8s\n", "ID", "Name", "Score"); + printf("-------------------------------\n"); + while (current != originalTail) { + printf("%6ld %10s %8.1f\n", current->id, current->name, current->score); + current = current->rlink; + } + } else { + printf("\n쵲CL\n"); + } + printf("*******************************\n\n"); +} + +void sort_id(){ + Student* temp ; + Student* current; + + //YSƩΥu@ + if (head->rlink == tail || head->rlink->rlink == tail) { + return; + } + + int flag = 1; + while(flag){ + flag = 0; + current = head->rlink; + + while(current->rlink != tail){ + temp = current->rlink; + + if(current->id > temp->id){ +// uϥΨӸ`Ii`I洫 +// n`NЧܫ᪺ +// YUC{ǥ洫ЫV}|X +// ]iHhŧiӸ`I current->llinktemp->rlink +// o˴NiHL޶ + temp->llink = current->llink; + current->rlink = temp->rlink; + + temp->rlink->llink = current; + temp->rlink = current; + + current->llink->rlink = temp; + current->llink = temp; + + flag = 1; + } + else{ + current = current->rlink; + } + } + } +} + +void sort_score(){ + Student* temp; + Student* current; + + //YSƩΥu@ + if (head->rlink == tail || head->rlink->rlink == tail) { + return; + } + + int flag = 1; + while(flag){ + flag = 0; + current = head->rlink; + + while(current->rlink != tail){ + temp = current->rlink; + + if(current->score < temp->score){ +// uϥΨӸ`Ii`I洫 +// n`NЧܫ᪺ +// YUC{ǥ洫ЫV}|X +// ]iHhŧiӸ`I current->llinktemp->rlink +// o˴NiHL޶ + temp->llink = current->llink; + current->rlink = temp->rlink; + + temp->rlink->llink = current; + temp->rlink = current; + + current->llink->rlink = temp; + current->llink = temp; + + flag = 1; + } + else{ + current = current->rlink; + } + } + } +} + +int main(){ + init_f(); + readFromFile("list.txt"); + printStudentList(); + int flag = 0; + /* QΤ@ϥοܥ\ඵ */ + int choice; + do { + printf("************************\n"); + printf("쵲CB@\n"); + printf("1. [J@`I\n"); + printf("2. R@`I\n"); + printf("3. ק@`I\n"); + printf("4. ܩҦ`I\n"); + printf("5. ܭlJ쪺\n"); + printf("6. ܦZѰܧCƦC\n"); + printf("7. IDѤpjƦC\n"); + + printf("8. \n"); + printf("п: "); + scanf("%d", &choice); + switch (choice) { + case 1: + insert(); + break; + case 2: + del(); + break; + case 3: + modify(); + break; + case 4: + printStudentList(); + break; + case 5: + printOriginalList(); + flag = 1; + break; + case 6: + sort_score(); + printStudentList(); + flag = 2; + break; + case 7: + sort_id(); + printStudentList(); + flag = 2; + break; + case 8: + printf("\n{\n"); + saveToFile("list.txt",flag); + exit(0); + default: + printf("JXTAЭsJ\n"); + } + printf("\n"); + } while(choice != 8); + getchar(); + return 0; +} + +/* ӤƥѤjܤp[J@`I쵲C */ +void insert() +{ + /* Q malloc() 禡tmO*/ + Student* newNode = (Student*)malloc(sizeof(Student)); + + printf("\nпJID: "); + scanf("%ld", &newNode->id); + printf("пJmW: "); + scanf("%s", newNode->name); + printf("пJ: "); + scanf("%lf", &newNode->score); + + /* [J@`I쵲C */ + current = head->rlink; + prev = head; + + // Je + newNode->rlink = tail; + newNode->llink = tail->llink; + tail->llink->rlink = newNode; + tail->llink = newNode; + + // JlǦC + insertOriginalList(newNode->id, newNode->name, newNode->score); +} + +void deleteFromOriginalList(long int deleteID) { + Student* current = originalHead->rlink; + Student* prev = originalHead; + + while (current != originalTail) { + if (current->id == deleteID) { + current->rlink->llink = prev; + prev->rlink = current->rlink; + free(current); + break; + } + prev = current; + current = current->rlink; + } +} + +/* RY@`I*/ +void del() +{ + long int deleteID; + /* N current ЫV head U@Ӹ`I */ + current = head->rlink; + prev = head; + /* P_쵲CO_ */ + if (current != NULL) { + /* YOŪAhMR`I */ + printf("\nпJR ID: "); + scanf("%ld", &deleteID); + /* MR`I */ + while ((current != tail) && (current->id != deleteID)) { + prev = current; + current = current->rlink; + } + /* YAhNR */ + if (current != tail) { + current->rlink->llink = prev; + prev->rlink = current->rlink; + printf("ID: %ld wR\n", current->id); + + deleteFromOriginalList(deleteID); + + free(current); + } + /* YSAhX䤣R`IT*/ + else { + printf("\n䤣R`I\n"); + } + } + /* YOŪAhX쵲COŪT */ + else { + printf("쵲COŪ\n"); + } +} + +/* קY@`I */ +void modify() +{ + Student *temp; + long int modifyID; + double modifyScore; + int flag = 0; + printf("\nпJק`I ID: "); + scanf("%ld", &modifyID); + current = head->rlink; + prev = head; + + /* Mק諸`I */ + while (current != tail) { + if (current->id == modifyID) { + printf("ثeק`IƦpU:\n"); + printf("%6ld %10s %8.1f\n\n", current->id, + current->name, current->score); + printf("пJק諸: "); + scanf("%lf", &modifyScore); + current->score = modifyScore; + flag = 1; + break; + } + else { + prev = current; + current = current->rlink; + } + } + /* P_O_ק諸`I */ + if (flag != 0) { + /* N current `Iw temp */ + temp = current; + prev->rlink = current->rlink; + /* N temp `I[J쵲C */ + current = head->rlink; + prev = head; + while ((current != tail) && (temp->score < current->score)) { + prev = current; + current = current->rlink; + } + prev->rlink = temp; + temp->rlink = current; + } + else { + printf("䤣ק諸`I\n"); + } +} + + + + diff --git a/作業/unit4/sList-v3.zip b/作業/unit4/sList-v3.zip new file mode 100644 index 0000000..8f878e5 Binary files /dev/null and b/作業/unit4/sList-v3.zip differ diff --git a/作業/unit4/sList-v3/list.txt b/作業/unit4/sList-v3/list.txt new file mode 100644 index 0000000..f02855b --- /dev/null +++ b/作業/unit4/sList-v3/list.txt @@ -0,0 +1,9 @@ +1 jeff 80 +2 tim 90 +3 jack 84 +4 sam 85 +5 poson 76 +6 dan 14 +7 ren 40 +8 eric 96 +9 ben 36 diff --git a/作業/unit4/sList-v3/sList-v3.c b/作業/unit4/sList-v3/sList-v3.c new file mode 100644 index 0000000..36e8829 --- /dev/null +++ b/作業/unit4/sList-v3/sList-v3.c @@ -0,0 +1,449 @@ +/* sList.c */ +#include +#include +#include + +/* wq@V FILE */ +FILE *fptr; + +/* 禡쫬ŧi */ +void init_f(void); +void insertStudent(int id, char* name, double score); +void readFromFile(const char* filename); +void saveToFile(const char* filename, int flag); +void insert(void); +void del(void); +void modify(void); +void display(void); + +// wqǥ͸`Ic +typedef struct Student { + long int id; + char name[10]; + double score; + struct Student *rlink; + struct Student *llink; +} Student; +Student *head, *pNode ,*tail, *current, *prev, *temp , *originalHead ,*originalTail; + +//]@ headANk쵲ҫV +void init_f() { + head = (Student *) malloc(sizeof(Student)); + tail = (Student *) malloc(sizeof(Student)); + + // l head M tail + head->llink = NULL; + head->rlink = tail; + + tail->llink = head; + tail->rlink = NULL; + + // lƭlǦC + originalHead = (Student *) malloc(sizeof(Student)); + originalTail = (Student *) malloc(sizeof(Student)); + + originalHead->llink = NULL; + originalHead->rlink = originalTail; + originalTail->llink = originalHead; + originalTail->rlink = NULL; +} + +// bJsǥ͸`I +void insertStudent(int id, char* name, double score) { + + Student* newNode = (Student*)malloc(sizeof(Student)); + + + newNode->id = id; + strcpy(newNode->name, name); + newNode->name[9] = '\0'; + newNode->score = score; + + // Je + newNode->rlink = tail; + newNode->llink = tail->llink; + tail->llink->rlink = newNode; + tail->llink = newNode; +} + +/* sWơGJ`IlǦC */ +void insertOriginalList(int id, char* name, double score) { + Student* newNode = (Student*)malloc(sizeof(Student)); + + newNode->id = id; + strncpy(newNode->name, name, 9); + newNode->name[9] = '\0'; + newNode->score = score; + + // JlCe + newNode->rlink = originalTail; + newNode->llink = originalTail->llink; + originalTail->llink->rlink = newNode; + originalTail->llink = newNode; +} + +// Ū +void readFromFile(const char* filename) { + char line[100]; + FILE* fptr = fopen(filename, "r"); + if (fptr == NULL) { + printf("Lk}ɮ %s\n", filename); + return; + } + + long int id; + char name[10]; + double score; + while(fgets(line ,sizeof(line) ,fptr)!=NULL){ + if(sscanf(line,"%ld\t%9s\t%lf", &id, name, &score) == 3){ + insertStudent(id, name, score); + insertOriginalList(id, name, score); // JlǦC + } + } + fclose(fptr); + printf("ɮ׸\n"); +} + +// s +void saveToFile(const char* filename , int flag) { + FILE* fptr = fopen(filename, "w"); + if (fptr == NULL) { + printf("Lk}ɮ %s igJ\n", filename); + return; + } + + if(flag == 2){ + Student* current = head->rlink; + while (current != tail ) { + fprintf(fptr, "%ld\t%s\t%.lf\n", current->id, current->name, current->score); + current = current->rlink; + } + }else if(flag == 1){ + Student* current = originalHead->rlink; + while (current != originalTail ) { + fprintf(fptr, "%ld\t%s\t%.lf\n", current->id, current->name, current->score); + current = current->rlink; + } + } + + + fclose(fptr); + printf("Ƥw\\xs %s\n", filename); +} + +//ܦC +void printStudentList() { + + Student* current = head->rlink; + printf("\n*******************************"); + + if (current != NULL) { + printf("\n%6s %10s %8s\n", "ID", "Name", "Score"); + printf("-------------------------------\n"); + while (current != tail) { + printf("%6ld %10s %8.1f\n", current->id,current->name, current->score); + /* NвU@Ӹ`I */ + current = current->rlink; + } + } + /* YOŪAhX쵲CL */ + else { + printf("\n쵲CL\n"); + } + printf("*******************************\n\n"); +} + +/* sWܭlǸƪ */ +void printOriginalList() { + Student* current = originalHead->rlink; + printf("\n*******************************"); + + if (current != originalTail) { + printf("\n%6s %10s %8s\n", "ID", "Name", "Score"); + printf("-------------------------------\n"); + while (current != originalTail) { + printf("%6ld %10s %8.1f\n", current->id, current->name, current->score); + current = current->rlink; + } + } else { + printf("\n쵲CL\n"); + } + printf("*******************************\n\n"); +} + +void sort_id(){ + Student* temp ; + Student* current; + + //YSƩΥu@ + if (head->rlink == tail || head->rlink->rlink == tail) { + return; + } + + int flag = 1; + while(flag){ + flag = 0; + current = head->rlink; + + while(current->rlink != tail){ + temp = current->rlink; + + if(current->id > temp->id){ +// uϥΨӸ`Ii`I洫 +// n`NЧܫ᪺ +// YUC{ǥ洫ЫV}|X +// ]iHhŧiӸ`I current->llinktemp->rlink +// o˴NiHL޶ + temp->llink = current->llink; + current->rlink = temp->rlink; + + temp->rlink->llink = current; + temp->rlink = current; + + current->llink->rlink = temp; + current->llink = temp; + + flag = 1; + } + else{ + current = current->rlink; + } + } + } +} + +void sort_score(){ + Student* temp; + Student* current; + + //YSƩΥu@ + if (head->rlink == tail || head->rlink->rlink == tail) { + return; + } + + int flag = 1; + while(flag){ + flag = 0; + current = head->rlink; + + while(current->rlink != tail){ + temp = current->rlink; + + if(current->score < temp->score){ +// uϥΨӸ`Ii`I洫 +// n`NЧܫ᪺ +// YUC{ǥ洫ЫV}|X +// ]iHhŧiӸ`I current->llinktemp->rlink +// o˴NiHL޶ + temp->llink = current->llink; + current->rlink = temp->rlink; + + temp->rlink->llink = current; + temp->rlink = current; + + current->llink->rlink = temp; + current->llink = temp; + + flag = 1; + } + else{ + current = current->rlink; + } + } + } +} + +int main(){ + init_f(); + readFromFile("list.txt"); + printStudentList(); + int flag = 0; + /* QΤ@ϥοܥ\ඵ */ + int choice; + do { + printf("************************\n"); + printf("쵲CB@\n"); + printf("1. [J@`I\n"); + printf("2. R@`I\n"); + printf("3. ק@`I\n"); + printf("4. ܩҦ`I\n"); + printf("5. ܭlJ쪺\n"); + printf("6. ܦZѰܧCƦC\n"); + printf("7. IDѤpjƦC\n"); + + printf("8. \n"); + printf("п: "); + scanf("%d", &choice); + switch (choice) { + case 1: + insert(); + break; + case 2: + del(); + break; + case 3: + modify(); + break; + case 4: + printStudentList(); + break; + case 5: + printOriginalList(); + flag = 1; + break; + case 6: + sort_score(); + printStudentList(); + flag = 2; + break; + case 7: + sort_id(); + printStudentList(); + flag = 2; + break; + case 8: + printf("\n{\n"); + saveToFile("list.txt",flag); + exit(0); + default: + printf("JXTAЭsJ\n"); + } + printf("\n"); + } while(choice != 8); + getchar(); + return 0; +} + +/* ӤƥѤjܤp[J@`I쵲C */ +void insert() +{ + /* Q malloc() 禡tmO*/ + Student* newNode = (Student*)malloc(sizeof(Student)); + + printf("\nпJID: "); + scanf("%ld", &newNode->id); + printf("пJmW: "); + scanf("%s", newNode->name); + printf("пJ: "); + scanf("%lf", &newNode->score); + + /* [J@`I쵲C */ + current = head->rlink; + prev = head; + + // Je + newNode->rlink = tail; + newNode->llink = tail->llink; + tail->llink->rlink = newNode; + tail->llink = newNode; + + // JlǦC + insertOriginalList(newNode->id, newNode->name, newNode->score); +} + +void deleteFromOriginalList(long int deleteID) { + Student* current = originalHead->rlink; + Student* prev = originalHead; + + while (current != originalTail) { + if (current->id == deleteID) { + current->rlink->llink = prev; + prev->rlink = current->rlink; + free(current); + break; + } + prev = current; + current = current->rlink; + } +} + +/* RY@`I*/ +void del() +{ + long int deleteID; + /* N current ЫV head U@Ӹ`I */ + current = head->rlink; + prev = head; + /* P_쵲CO_ */ + if (current != NULL) { + /* YOŪAhMR`I */ + printf("\nпJR ID: "); + scanf("%ld", &deleteID); + /* MR`I */ + while ((current != tail) && (current->id != deleteID)) { + prev = current; + current = current->rlink; + } + /* YAhNR */ + if (current != tail) { + current->rlink->llink = prev; + prev->rlink = current->rlink; + printf("ID: %ld wR\n", current->id); + + deleteFromOriginalList(deleteID); + + free(current); + } + /* YSAhX䤣R`IT*/ + else { + printf("\n䤣R`I\n"); + } + } + /* YOŪAhX쵲COŪT */ + else { + printf("쵲COŪ\n"); + } +} + +/* קY@`I */ +void modify() +{ + Student *temp; + long int modifyID; + double modifyScore; + int flag = 0; + printf("\nпJק`I ID: "); + scanf("%ld", &modifyID); + current = head->rlink; + prev = head; + + /* Mק諸`I */ + while (current != tail) { + if (current->id == modifyID) { + printf("ثeק`IƦpU:\n"); + printf("%6ld %10s %8.1f\n\n", current->id, + current->name, current->score); + printf("пJק諸: "); + scanf("%lf", &modifyScore); + current->score = modifyScore; + flag = 1; + break; + } + else { + prev = current; + current = current->rlink; + } + } + /* P_O_ק諸`I */ + if (flag != 0) { + /* N current `Iw temp */ + temp = current; + prev->rlink = current->rlink; + /* N temp `I[J쵲C */ + current = head->rlink; + prev = head; + while ((current != tail) && (temp->score < current->score)) { + prev = current; + current = current->rlink; + } + prev->rlink = temp; + temp->rlink = current; + } + else { + printf("䤣ק諸`I\n"); + } +} + + + + diff --git a/作業/unit4/slist.c b/作業/unit4/slist.c new file mode 100644 index 0000000..36e8829 --- /dev/null +++ b/作業/unit4/slist.c @@ -0,0 +1,449 @@ +/* sList.c */ +#include +#include +#include + +/* wq@V FILE */ +FILE *fptr; + +/* 禡쫬ŧi */ +void init_f(void); +void insertStudent(int id, char* name, double score); +void readFromFile(const char* filename); +void saveToFile(const char* filename, int flag); +void insert(void); +void del(void); +void modify(void); +void display(void); + +// wqǥ͸`Ic +typedef struct Student { + long int id; + char name[10]; + double score; + struct Student *rlink; + struct Student *llink; +} Student; +Student *head, *pNode ,*tail, *current, *prev, *temp , *originalHead ,*originalTail; + +//]@ headANk쵲ҫV +void init_f() { + head = (Student *) malloc(sizeof(Student)); + tail = (Student *) malloc(sizeof(Student)); + + // l head M tail + head->llink = NULL; + head->rlink = tail; + + tail->llink = head; + tail->rlink = NULL; + + // lƭlǦC + originalHead = (Student *) malloc(sizeof(Student)); + originalTail = (Student *) malloc(sizeof(Student)); + + originalHead->llink = NULL; + originalHead->rlink = originalTail; + originalTail->llink = originalHead; + originalTail->rlink = NULL; +} + +// bJsǥ͸`I +void insertStudent(int id, char* name, double score) { + + Student* newNode = (Student*)malloc(sizeof(Student)); + + + newNode->id = id; + strcpy(newNode->name, name); + newNode->name[9] = '\0'; + newNode->score = score; + + // Je + newNode->rlink = tail; + newNode->llink = tail->llink; + tail->llink->rlink = newNode; + tail->llink = newNode; +} + +/* sWơGJ`IlǦC */ +void insertOriginalList(int id, char* name, double score) { + Student* newNode = (Student*)malloc(sizeof(Student)); + + newNode->id = id; + strncpy(newNode->name, name, 9); + newNode->name[9] = '\0'; + newNode->score = score; + + // JlCe + newNode->rlink = originalTail; + newNode->llink = originalTail->llink; + originalTail->llink->rlink = newNode; + originalTail->llink = newNode; +} + +// Ū +void readFromFile(const char* filename) { + char line[100]; + FILE* fptr = fopen(filename, "r"); + if (fptr == NULL) { + printf("Lk}ɮ %s\n", filename); + return; + } + + long int id; + char name[10]; + double score; + while(fgets(line ,sizeof(line) ,fptr)!=NULL){ + if(sscanf(line,"%ld\t%9s\t%lf", &id, name, &score) == 3){ + insertStudent(id, name, score); + insertOriginalList(id, name, score); // JlǦC + } + } + fclose(fptr); + printf("ɮ׸\n"); +} + +// s +void saveToFile(const char* filename , int flag) { + FILE* fptr = fopen(filename, "w"); + if (fptr == NULL) { + printf("Lk}ɮ %s igJ\n", filename); + return; + } + + if(flag == 2){ + Student* current = head->rlink; + while (current != tail ) { + fprintf(fptr, "%ld\t%s\t%.lf\n", current->id, current->name, current->score); + current = current->rlink; + } + }else if(flag == 1){ + Student* current = originalHead->rlink; + while (current != originalTail ) { + fprintf(fptr, "%ld\t%s\t%.lf\n", current->id, current->name, current->score); + current = current->rlink; + } + } + + + fclose(fptr); + printf("Ƥw\\xs %s\n", filename); +} + +//ܦC +void printStudentList() { + + Student* current = head->rlink; + printf("\n*******************************"); + + if (current != NULL) { + printf("\n%6s %10s %8s\n", "ID", "Name", "Score"); + printf("-------------------------------\n"); + while (current != tail) { + printf("%6ld %10s %8.1f\n", current->id,current->name, current->score); + /* NвU@Ӹ`I */ + current = current->rlink; + } + } + /* YOŪAhX쵲CL */ + else { + printf("\n쵲CL\n"); + } + printf("*******************************\n\n"); +} + +/* sWܭlǸƪ */ +void printOriginalList() { + Student* current = originalHead->rlink; + printf("\n*******************************"); + + if (current != originalTail) { + printf("\n%6s %10s %8s\n", "ID", "Name", "Score"); + printf("-------------------------------\n"); + while (current != originalTail) { + printf("%6ld %10s %8.1f\n", current->id, current->name, current->score); + current = current->rlink; + } + } else { + printf("\n쵲CL\n"); + } + printf("*******************************\n\n"); +} + +void sort_id(){ + Student* temp ; + Student* current; + + //YSƩΥu@ + if (head->rlink == tail || head->rlink->rlink == tail) { + return; + } + + int flag = 1; + while(flag){ + flag = 0; + current = head->rlink; + + while(current->rlink != tail){ + temp = current->rlink; + + if(current->id > temp->id){ +// uϥΨӸ`Ii`I洫 +// n`NЧܫ᪺ +// YUC{ǥ洫ЫV}|X +// ]iHhŧiӸ`I current->llinktemp->rlink +// o˴NiHL޶ + temp->llink = current->llink; + current->rlink = temp->rlink; + + temp->rlink->llink = current; + temp->rlink = current; + + current->llink->rlink = temp; + current->llink = temp; + + flag = 1; + } + else{ + current = current->rlink; + } + } + } +} + +void sort_score(){ + Student* temp; + Student* current; + + //YSƩΥu@ + if (head->rlink == tail || head->rlink->rlink == tail) { + return; + } + + int flag = 1; + while(flag){ + flag = 0; + current = head->rlink; + + while(current->rlink != tail){ + temp = current->rlink; + + if(current->score < temp->score){ +// uϥΨӸ`Ii`I洫 +// n`NЧܫ᪺ +// YUC{ǥ洫ЫV}|X +// ]iHhŧiӸ`I current->llinktemp->rlink +// o˴NiHL޶ + temp->llink = current->llink; + current->rlink = temp->rlink; + + temp->rlink->llink = current; + temp->rlink = current; + + current->llink->rlink = temp; + current->llink = temp; + + flag = 1; + } + else{ + current = current->rlink; + } + } + } +} + +int main(){ + init_f(); + readFromFile("list.txt"); + printStudentList(); + int flag = 0; + /* QΤ@ϥοܥ\ඵ */ + int choice; + do { + printf("************************\n"); + printf("쵲CB@\n"); + printf("1. [J@`I\n"); + printf("2. R@`I\n"); + printf("3. ק@`I\n"); + printf("4. ܩҦ`I\n"); + printf("5. ܭlJ쪺\n"); + printf("6. ܦZѰܧCƦC\n"); + printf("7. IDѤpjƦC\n"); + + printf("8. \n"); + printf("п: "); + scanf("%d", &choice); + switch (choice) { + case 1: + insert(); + break; + case 2: + del(); + break; + case 3: + modify(); + break; + case 4: + printStudentList(); + break; + case 5: + printOriginalList(); + flag = 1; + break; + case 6: + sort_score(); + printStudentList(); + flag = 2; + break; + case 7: + sort_id(); + printStudentList(); + flag = 2; + break; + case 8: + printf("\n{\n"); + saveToFile("list.txt",flag); + exit(0); + default: + printf("JXTAЭsJ\n"); + } + printf("\n"); + } while(choice != 8); + getchar(); + return 0; +} + +/* ӤƥѤjܤp[J@`I쵲C */ +void insert() +{ + /* Q malloc() 禡tmO*/ + Student* newNode = (Student*)malloc(sizeof(Student)); + + printf("\nпJID: "); + scanf("%ld", &newNode->id); + printf("пJmW: "); + scanf("%s", newNode->name); + printf("пJ: "); + scanf("%lf", &newNode->score); + + /* [J@`I쵲C */ + current = head->rlink; + prev = head; + + // Je + newNode->rlink = tail; + newNode->llink = tail->llink; + tail->llink->rlink = newNode; + tail->llink = newNode; + + // JlǦC + insertOriginalList(newNode->id, newNode->name, newNode->score); +} + +void deleteFromOriginalList(long int deleteID) { + Student* current = originalHead->rlink; + Student* prev = originalHead; + + while (current != originalTail) { + if (current->id == deleteID) { + current->rlink->llink = prev; + prev->rlink = current->rlink; + free(current); + break; + } + prev = current; + current = current->rlink; + } +} + +/* RY@`I*/ +void del() +{ + long int deleteID; + /* N current ЫV head U@Ӹ`I */ + current = head->rlink; + prev = head; + /* P_쵲CO_ */ + if (current != NULL) { + /* YOŪAhMR`I */ + printf("\nпJR ID: "); + scanf("%ld", &deleteID); + /* MR`I */ + while ((current != tail) && (current->id != deleteID)) { + prev = current; + current = current->rlink; + } + /* YAhNR */ + if (current != tail) { + current->rlink->llink = prev; + prev->rlink = current->rlink; + printf("ID: %ld wR\n", current->id); + + deleteFromOriginalList(deleteID); + + free(current); + } + /* YSAhX䤣R`IT*/ + else { + printf("\n䤣R`I\n"); + } + } + /* YOŪAhX쵲COŪT */ + else { + printf("쵲COŪ\n"); + } +} + +/* קY@`I */ +void modify() +{ + Student *temp; + long int modifyID; + double modifyScore; + int flag = 0; + printf("\nпJק`I ID: "); + scanf("%ld", &modifyID); + current = head->rlink; + prev = head; + + /* Mק諸`I */ + while (current != tail) { + if (current->id == modifyID) { + printf("ثeק`IƦpU:\n"); + printf("%6ld %10s %8.1f\n\n", current->id, + current->name, current->score); + printf("пJק諸: "); + scanf("%lf", &modifyScore); + current->score = modifyScore; + flag = 1; + break; + } + else { + prev = current; + current = current->rlink; + } + } + /* P_O_ק諸`I */ + if (flag != 0) { + /* N current `Iw temp */ + temp = current; + prev->rlink = current->rlink; + /* N temp `I[J쵲C */ + current = head->rlink; + prev = head; + while ((current != tail) && (temp->score < current->score)) { + prev = current; + current = current->rlink; + } + prev->rlink = temp; + temp->rlink = current; + } + else { + printf("䤣ק諸`I\n"); + } +} + + + + diff --git a/作業/unit4/slist.o b/作業/unit4/slist.o new file mode 100644 index 0000000..1fe39c7 Binary files /dev/null and b/作業/unit4/slist.o differ diff --git a/作業/unit4/slist_file_sort.c b/作業/unit4/slist_file_sort.c new file mode 100644 index 0000000..d56d92a --- /dev/null +++ b/作業/unit4/slist_file_sort.c @@ -0,0 +1,280 @@ +#include +#include +#include + +struct Node { + long int id; + char name[10]; + double score; + struct Node *next; +}; + +struct LinkedList { + struct Node *head; + struct Node *tail; +}; + +struct Node* createNode() { + struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); + if (newNode == NULL) { + printf("Ot\n"); + exit(1); + } + newNode->next = NULL; + return newNode; +} + +void insertNode(struct LinkedList* list, long int id, const char* name, double score) { + struct Node* newNode = createNode(); + newNode->id = id; + strncpy(newNode->name, name, 9); + newNode->name[9] = '\0'; + newNode->score = score; + + if (list->head == NULL) { + list->head = newNode; + list->tail = newNode; + } else { + list->tail->next = newNode; + list->tail = newNode; + } +} + +void printList(struct LinkedList* list) { + struct Node* current = list->head; + while (current != NULL) { + printf("Ǹ: %ld, mW: %s, : %.2f\n", current->id, current->name, current->score); + current = current->next; + } +} + +void freeList(struct LinkedList* list) { + struct Node* current = list->head; + while (current != NULL) { + struct Node* temp = current; + current = current->next; + free(temp); + } + list->head = NULL; + list->tail = NULL; +} + +//Ū +void readFromFile(struct LinkedList* list, const char* filename) { + FILE* file = fopen(filename, "r"); + if (file == NULL) { + printf("Lk}ɮ %s\n", filename); + return; + } + + long int id; + char name[10]; + int score; + + while (fscanf(file, "%ld %9s %d", &id, name, &score) == 3) { + insertNode(list, id, name, score); + } + + fclose(file); +} + +void saveToFile(struct LinkedList* list, const char* filename) { + FILE* file = fopen(filename, "w"); + if (file == NULL) { + printf("Lk}ɮ %s igJ\n", filename); + return; + } + + struct Node* current = list->head; + while (current != NULL) { + fprintf(file, "%ld %s %d\n", current->id, current->name, current->score); + current = current->next; + } + + fclose(file); + printf("Ƥw\xs %s\n", filename); +} + +void inputFromKeyboard(struct LinkedList* list) { + long int id; + char name[10]; + double score; + + printf("пJǸ: "); + scanf("%ld", &id); + printf("пJmW (̦h9Ӧr): "); + scanf("%9s", name); + printf("пJ: "); + scanf("%lf", &score); + + insertNode(list, id, name, score); + printf("Ƥw\K[C\n"); +} + +void deleteNode(struct LinkedList* list, long int id) { + struct Node* current = list->head; + struct Node* prev = NULL; + + if (current != NULL && current->id == id) { + list->head = current->next; + free(current); + if (list->head == NULL) { + list->tail = NULL; + } + printf("Ǹ %ld ƤwR\n", id); + return; + } + + while (current != NULL && current->id != id) { + prev = current; + current = current->next; + } + + if (current == NULL) { + printf("䤣Ǹ %ld \n", id); + return; + } + + prev->next = current->next; + if (current == list->tail) { + list->tail = prev; + } + free(current); + printf("Ǹ %ld ƤwR\n", id); +} + +void copyList(struct LinkedList* source, struct LinkedList* dest) { + freeList(dest); + struct Node* current = source->head; + while (current != NULL) { + insertNode(dest, current->id, current->name, current->score); + current = current->next; + } +} + +void sortByScore(struct LinkedList* list) { + if (list->head == NULL || list->head->next == NULL) return; + + struct Node* sorted = NULL; + struct Node* current = list->head; + + while (current != NULL) { + struct Node* next = current->next; + if (sorted == NULL || sorted->score < current->score) { + current->next = sorted; + sorted = current; + } else { + struct Node* search = sorted; + while (search->next != NULL && search->next->score > current->score) { + search = search->next; + } + current->next = search->next; + search->next = current; + } + current = next; + } + + list->head = sorted; + while (sorted->next != NULL) { + sorted = sorted->next; + } + list->tail = sorted; +} + +void sortById(struct LinkedList* list) { + if (list->head == NULL || list->head->next == NULL) return; + + struct Node* sorted = NULL; + struct Node* current = list->head; + + while (current != NULL) { + struct Node* next = current->next; + if (sorted == NULL || sorted->id > current->id) { + current->next = sorted; + sorted = current; + } else { + struct Node* search = sorted; + while (search->next != NULL && search->next->id < current->id) { + search = search->next; + } + current->next = search->next; + search->next = current; + } + current = next; + } + + list->head = sorted; + while (sorted->next != NULL) { + sorted = sorted->next; + } + list->tail = sorted; +} + +int main() { + struct LinkedList originalList = {NULL, NULL}; + struct LinkedList scoreList = {NULL, NULL}; + struct LinkedList idList = {NULL, NULL}; + int choice, sortChoice; + long int id_to_delete; + const char* filename = "list.txt"; + + readFromFile(&originalList, filename); + + do { + printf("\n1. ܸ\n"); + printf("2. qLJs\n"); + printf("3. RSw\n"); + printf("4. xsðhX\n"); + printf("пܾާ@ (1-4): "); + scanf("%d", &choice); + + switch(choice) { + case 1: + printf("ܤ覡G\n"); + printf("1. l\n"); + printf("2. ZƧǡ]C^\n"); + printf("3. ǸƧǡ]pj^\n"); + scanf("%d", &sortChoice); + + switch(sortChoice) { + case 1: + printf("\nlǪ:\n"); + printList(&originalList); + break; + case 2: + copyList(&originalList, &scoreList); + sortByScore(&scoreList); + printf("\nZƧǪơ]C^:\n"); + printList(&scoreList); + break; + case 3: + copyList(&originalList, &idList); + sortById(&idList); + printf("\nǸƧǪơ]pj^:\n"); + printList(&idList); + break; + default: + printf("LĪ\n"); + } + break; + case 2: + inputFromKeyboard(&originalList); + break; + case 3: + printf("пJnRǸ: "); + scanf("%ld", &id_to_delete); + deleteNode(&originalList, id_to_delete); + break; + case 4: + saveToFile(&originalList, filename); + break; + default: + printf("LĪܡAЭsJ\n"); + } + } while (choice != 4); + + freeList(&originalList); + freeList(&scoreList); + freeList(&idList); + return 0; +} diff --git a/作業/unit4/slist_file_sort.exe b/作業/unit4/slist_file_sort.exe new file mode 100644 index 0000000..096fdd0 Binary files /dev/null and b/作業/unit4/slist_file_sort.exe differ diff --git a/作業/unit4/slist_file_sort.o b/作業/unit4/slist_file_sort.o new file mode 100644 index 0000000..18b85b1 Binary files /dev/null and b/作業/unit4/slist_file_sort.o differ diff --git a/作業/unit4/slist_test.c b/作業/unit4/slist_test.c new file mode 100644 index 0000000..a11fe5a --- /dev/null +++ b/作業/unit4/slist_test.c @@ -0,0 +1,77 @@ +#include +#include +#include + +struct Node { + long int id; + char name[10]; + double score; + struct Node *next; +}; + +struct Node* createNode() { + struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); + if (newNode == NULL) { + printf("Ot\n"); + exit(1); + } + newNode->next = NULL; + return newNode; +} + +void insertNode(struct Node** head) { + struct Node* newNode = createNode(); + + printf("пJǸ: "); + scanf("%ld", &(newNode->id)); + + printf("пJmW (̦h9Ӧr): "); + scanf("%9s", newNode->name); + + printf("пJ: "); + scanf("%lf", &(newNode->score)); + + if (*head == NULL) { + *head = newNode; + } else { + struct Node* current = *head; + while (current->next != NULL) { + current = current->next; + } + current->next = newNode; + } + + printf("ƲK[\\n"); +} + +void printList(struct Node* head) { + struct Node* current = head; + while (current != NULL) { + printf("Ǹ: %ld, mW: %s, : %.2f\n", current->id, current->name, current->score); + current = current->next; + } +} + +int main() { + struct Node* head = NULL; + char choice; + + + do { + insertNode(&head); + printf("O_~J? (y/n): "); + scanf(" %c", &choice); + } while (choice == 'y' || choice == 'Y'); + + printf("\nCҦ:\n"); + printList(head); + + // O]Τӧ{^ + while (head != NULL) { + struct Node* temp = head; + head = head->next; + free(temp); + } + + return 0; +} diff --git a/作業/unit4/slist_test.o b/作業/unit4/slist_test.o new file mode 100644 index 0000000..25fb8ac Binary files /dev/null and b/作業/unit4/slist_test.o differ diff --git a/作業/unit4/slist_test_file.c b/作業/unit4/slist_test_file.c new file mode 100644 index 0000000..1cbfdf2 --- /dev/null +++ b/作業/unit4/slist_test_file.c @@ -0,0 +1,188 @@ +#include +#include +#include + +struct Node { + long int id; + char name[10]; + double score; + struct Node *next; +}; + +struct LinkedList { + struct Node *head; + struct Node *tail; +}; + +struct Node* createNode() { + struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); + if (newNode == NULL) { + printf("Ot\n"); + exit(1); + } + newNode->next = NULL; + return newNode; +} + +void insertNode(struct LinkedList* list, long int id, const char* name, double score) { + struct Node* newNode = createNode(); + newNode->id = id; + strncpy(newNode->name, name, 9); + newNode->name[9] = '\0'; + newNode->score = score; + + if (list->head == NULL) { + list->head = newNode; + list->tail = newNode; + } else { + list->tail->next = newNode; + list->tail = newNode; + } +} + +void printList(struct LinkedList* list) { + struct Node* current = list->head; + while (current != NULL) { + printf("Ǹ: %ld, mW: %s, : %.2f\n", current->id, current->name, current->score); + current = current->next; + } +} + +void freeList(struct LinkedList* list) { + struct Node* current = list->head; + while (current != NULL) { + struct Node* temp = current; + current = current->next; + free(temp); + } + list->head = NULL; + list->tail = NULL; +} + +void readFromFile(struct LinkedList* list, const char* filename) { + FILE* file = fopen(filename, "r"); + if (file == NULL) { + printf("Lk}ɮ %s\n", filename); + return; + } + + long int id; + char name[10]; + double score; + + while (fscanf(file, "%ld %9s %lf", &id, name, &score) == 3) { + insertNode(list, id, name, score); + } + + fclose(file); +} + +void saveToFile(struct LinkedList* list, const char* filename) { + FILE* file = fopen(filename, "w"); + if (file == NULL) { + printf("Lk}ɮ %s igJ\n", filename); + return; + } + + struct Node* current = list->head; + while (current != NULL) { + fprintf(file, "%ld %s %.2f\n", current->id, current->name, current->score); + current = current->next; + } + + fclose(file); + printf("Ƥw\xs %s\n", filename); +} + +void inputFromKeyboard(struct LinkedList* list) { + long int id; + char name[10]; + double score; + + printf("пJǸ: "); + scanf("%ld", &id); + printf("пJmW (̦h9Ӧr): "); + scanf("%9s", name); + printf("пJ: "); + scanf("%lf", &score); + + insertNode(list, id, name, score); + printf("Ƥw\K[C\n"); +} + +void deleteNode(struct LinkedList* list, long int id) { + struct Node* current = list->head; + struct Node* prev = NULL; + + // pGnROY`I + if (current != NULL && current->id == id) { + list->head = current->next; + free(current); + if (list->head == NULL) { + list->tail = NULL; // pGRCšAs tail + } + printf("Ǹ %ld ƤwR\n", id); + return; + } + + // jMnR`I + while (current != NULL && current->id != id) { + prev = current; + current = current->next; + } + + // pGSnR`I + if (current == NULL) { + printf("䤣Ǹ %ld \n", id); + return; + } + + // R`I + prev->next = current->next; + if (current == list->tail) { + list->tail = prev; // pGRO`IAs tail + } + free(current); + printf("Ǹ %ld ƤwR\n", id); +} + +int main() { + struct LinkedList list = {NULL, NULL}; + int choice; + long int id_to_delete; + const char* filename = "list.txt"; + + readFromFile(&list, filename); + + do { + printf("\n1. ܩҦ\n"); + printf("2. qLJs\n"); + printf("3. RSw\n"); + printf("4. xsðhX\n"); + printf("пܾާ@ (1-4): "); + scanf("%d", &choice); + + switch(choice) { + case 1: + printf("\nҦ:\n"); + printList(&list); + break; + case 2: + inputFromKeyboard(&list); + break; + case 3: + printf("пJnRǸ: "); + scanf("%ld", &id_to_delete); + deleteNode(&list, id_to_delete); + break; + case 4: + saveToFile(&list, filename); + break; + default: + printf("LĪܡAЭsJ\n"); + } + } while (choice != 4); + + freeList(&list); + return 0; +} diff --git a/作業/unit4/slist_test_file.o b/作業/unit4/slist_test_file.o new file mode 100644 index 0000000..0bee680 Binary files /dev/null and b/作業/unit4/slist_test_file.o differ diff --git a/作業/unit4/test.c b/作業/unit4/test.c new file mode 100644 index 0000000..db2a2c3 --- /dev/null +++ b/作業/unit4/test.c @@ -0,0 +1,17 @@ +#include +#include + +int main() +{ + char str[30] = "-20.30300 This is test"; + char *ptr; + double ret; + int i = 0; + ret = strtod(&str[4], &ptr); + int len = ptr - &str[i]; + printf("Ʀr]double^O %f\n", ret); + printf("rŦ곡O |%s|\n", ptr); + printf("len =%d ,&ptr=%d ,&str[i]=%d ", len ,&ptr ,&str[i]); + + return(0); +} diff --git a/作業/unit4/test.exe b/作業/unit4/test.exe new file mode 100644 index 0000000..f1dbccc Binary files /dev/null and b/作業/unit4/test.exe differ diff --git a/作業/unit4/test.o b/作業/unit4/test.o new file mode 100644 index 0000000..09bb3f3 Binary files /dev/null and b/作業/unit4/test.o differ diff --git a/作業/unit4/try.c b/作業/unit4/try.c new file mode 100644 index 0000000..ba77bde --- /dev/null +++ b/作業/unit4/try.c @@ -0,0 +1,290 @@ +#include +#include + +// wq`Ic +typedef struct Node { + int value; + struct Node* next; +} Node; + +// wq쵲Cc +typedef struct { + Node* head; + int length; + size_t memoryUsed; // sWGlܰOϥ +} LinkedList; + +int i; + +// ƭ쫬 +Node* createNode(int value); +void initLinkedList(LinkedList* list); +void push(LinkedList* list, int value); +Node* pop(LinkedList* list); +void unshift(LinkedList* list, int value); +Node* shift(LinkedList* list); +void insert(LinkedList* list, int index, int value); +Node* removeNode(LinkedList* list, int index); +void get(LinkedList* list, int index); +void printAll(LinkedList* list); +void freeLinkedList(LinkedList* list); + +// D +int main() { + LinkedList list; + initLinkedList(&list); + int choice, value, index; + + while (1) { + printf("\n쵲Cާ@:\n"); + printf("1. Push (qsW`I)\n"); + printf("2. Pop (q`I)\n"); + printf("3. Unshift (qYsW`I)\n"); + printf("4. Shift (qY`I)\n"); + printf("5. Insert (bwmJ`I)\n"); + printf("6. Remove (wm`I)\n"); + printf("7. Get (wm`I)\n"); + printf("8. Print All (ܩҦ`I)\n"); + printf("0. hX\n"); + printf("пJA: "); + scanf("%d", &choice); + + switch (choice) { + case 0: + printf("{\n"); + freeLinkedList(&list); + return 0; + case 1: + printf("JnsW: "); + scanf("%d", &value); + push(&list, value); + break; + case 2: + { + Node* popped = pop(&list); + if (popped) { + printf("uX: %d\n", popped->value); + free(popped); + list.memoryUsed -= sizeof(Node); + } else { + printf("C\n"); + } + } + break; + case 3: + printf("JnsW: "); + scanf("%d", &value); + unshift(&list, value); + break; + case 4: + { + Node* shifted = shift(&list); + if (shifted) { + printf(": %d\n", shifted->value); + free(shifted); + } else { + printf("C\n"); + } + } + break; + case 5: + printf("JJm: "); + scanf("%d", &index); + printf("JnJ: "); + scanf("%d", &value); + insert(&list, index, value); + break; + case 6: + printf("Jnm: "); + scanf("%d", &index); + { + Node* removed = removeNode(&list, index); + if (removed) { + printf(": %d\n", removed->value); + free(removed); + list.memoryUsed -= sizeof(Node); + } else { + printf("LĪm\n"); + } + } + break; + case 7: + printf("Jnm: "); + scanf("%d", &index); + get(&list, index); + break; + case 8: + printAll(&list); + break; + default: + printf("LĪ,ЭsJ\n"); + } + } + + return 0; +} + +// Ыطs`I +Node* createNode(int value) { + Node* newNode = (Node*)malloc(sizeof(Node)); + if (newNode == NULL) { + printf("Ot\n"); + exit(1); + } + newNode->value = value; + newNode->next = NULL; + return newNode; +} + +// l쵲C +void initLinkedList(LinkedList* list) { + list->head = NULL; + list->length = 0; + list->memoryUsed = 0; +} + +// qsW`I +void push(LinkedList* list, int value) { + Node* newNode = createNode(value); + if (list->length == 0) { + list->head = newNode; + } else { + Node* currentNode = list->head; + while (currentNode->next != NULL) { + currentNode = currentNode->next; + } + currentNode->next = newNode; + } + list->length++; + list->memoryUsed += sizeof(Node); +} + +// q`I +Node* pop(LinkedList* list) { + + if (list->length == 0) { + return NULL; + } else if (list->length == 1) { + Node* temp = list->head; + list->head = NULL; + list->length = 0; + return temp; + } else { + Node* currentNode = list->head; + for (i = 1; i <= list->length - 2; i++) { + currentNode = currentNode->next; + } + Node* temp = currentNode->next; + currentNode->next = NULL; + list->length--; + return temp; + } +} + +// qYsW`I +void unshift(LinkedList* list, int value) { + Node* newNode = createNode(value); + if (list->length == 0) { + list->head = newNode; + } else { + newNode->next = list->head; + list->head = newNode; + } + list->length++; + list->memoryUsed += sizeof(Node); +} + +// qY`I +Node* shift(LinkedList* list) { + if (list->length == 0) { + return NULL; + } else { + Node* temp = list->head; + list->head = list->head->next; + list->length--; + return temp; + } +} + +// qsW`I +void insert(LinkedList* list, int index, int value) { + if (index < 0 || index > list->length) { + return; + } else if (index == 0) { + unshift(list, value); + } else if (index == list->length) { + push(list, value); + } else { + Node* newNode = createNode(value); + Node* currentNode = list->head; + for ( i = 0; i < index - 1; i++) { + currentNode = currentNode->next; + } + newNode->next = currentNode->next; + currentNode->next = newNode; + list->length++; + } +} + +// q`I +Node* removeNode(LinkedList* list, int index) { + if (index < 0 || index >= list->length) { + return NULL; + } else if (index == 0) { + return shift(list); + } else if (index == list->length - 1) { + return pop(list); + } else { + Node* currentNode = list->head; + for ( i = 0; i < index - 1; i++) { + currentNode = currentNode->next; + } + Node* temp = currentNode->next; + currentNode->next = currentNode->next->next; + list->length--; + return temp; + } +} + +// o`IT +void get(LinkedList* list, int index) { + if (index < 0 || index >= list->length) { + printf("޶WXd\n"); + } else { + Node* currentNode = list->head; + for ( i = 0; i < index; i++) { + currentNode = currentNode->next; + } + printf(" %d : %d\n", index, currentNode->value); + } +} + +// 쵲CT +void printAll(LinkedList* list) { + + + if (list->length == 0) { + printf("쵲C\n"); + } else { + Node* currentNode = list->head; + while (currentNode != NULL) { + printf("%d ", currentNode->value); + currentNode = currentNode->next; + } + printf("\n"); + } +} + +// sWG쵲C +void freeLinkedList(LinkedList* list) { + Node* current = list->head; + while (current != NULL) { + Node* temp = current; + current = current->next; + free(temp); + } + list->head = NULL; + list->length = 0; + list->memoryUsed = 0; + printf("ҦOw\n"); +} diff --git a/作業/unit4/try.o b/作業/unit4/try.o new file mode 100644 index 0000000..3bb25b7 Binary files /dev/null and b/作業/unit4/try.o differ diff --git a/作業/unit4/老師解答/YunTechStudents.txt b/作業/unit4/老師解答/YunTechStudents.txt new file mode 100644 index 0000000..d0c309a --- /dev/null +++ b/作業/unit4/老師解答/YunTechStudents.txt @@ -0,0 +1,18 @@ +YunTech EE Department (2024) +====================================== +Name English Math +---------------+-------+-------------- +Steve Jobs 50 60 +Tom Cruise 30 40 +Marie Jane 70 80 +Barrack Obama 46 77 +John Tyler 98 96 +U. S. Grant 97 88 +Robert Redford 22 33 +Bruce Lee 90 90 +************************************** ++ Oliver Hardy 90 80 ++ Slim Pickens 88 82 +- Marie Jane 0 0 ++ James Bond 88 82 +- Barrack Obama 0 0 \ No newline at end of file diff --git a/作業/unit4/老師解答/YunTechStudents2.txt b/作業/unit4/老師解答/YunTechStudents2.txt new file mode 100644 index 0000000..5be8c1e --- /dev/null +++ b/作業/unit4/老師解答/YunTechStudents2.txt @@ -0,0 +1,20 @@ +YunTech EE Department (2024) +====================================== +Name English Math +---------------+-------+-------------- +Steve Jobs 50 60 +Tom Cruise 30 40 +Marie Jane 70 80 +Barrack Obama 46 77 +John Tyler 98 96 +U. S. Grant 97 88 +Robert Redford 22 33 +Bruce Lee 90 90 +************************************** +- Steve Jobs 0 0 ++ Oliver Hardy 90 80 ++ Slim Pickens 88 82 +- Marie Jane 0 0 ++ James Bond 88 82 +- Barrack Obama 0 0 +- James Bond 0 0 \ No newline at end of file diff --git a/作業/unit4/老師解答/file-records-adds-drops-v1.c b/作業/unit4/老師解答/file-records-adds-drops-v1.c new file mode 100644 index 0000000..96b64f2 --- /dev/null +++ b/作業/unit4/老師解答/file-records-adds-drops-v1.c @@ -0,0 +1,285 @@ +/* +Program: file-records-adds-drops-v1.c (Report comments/bugs to chikh@yuntech.edu.tw) +Function: uƵcPtkvĥ|@~Ѧҵ{XAnDWҵ{C + {wqstudentƫAΥHظm@VChǥͪZơAèϥheadPtail + ФOVC +Notes: 1) {{VCAF٫oѼƶǨӶǥhlͪӸ`xZAŧiheadBtailPtotal(`I + Ӽ)ܼơAHDn + 2) headPtailܼơA{N]showAll()BsortName()BsortEng()BsortMath() + 禡ǤJhead޼ơAHQPǵoQѼƶǻ򥻧Φ + 3) YheadPtailŧimain()ϰܼơAPǤ]Dp{T + 4) sscanf()ΪkA˳ۦѮvz@g޳Nu http://ccckmit.wikidot.com/cp:sscanf +*/ + +#include +#include /* for malloc(), calloc() */ +#include /* for strcmp() */ +#include /* for getche() */ + +typedef struct student student; +struct student { + char name[24]; + int eng, math; + student *prev; + student *next; +} *head, *tail, dummy; + +int total = 0; + +void traceBack(student *tail) /* qYܧܨC@Ӹ`Ie */ +{ + student *ptr; /* VC@`IҥΪ */ + + printf("\n^ܾǥͬpUG\n"); + for (ptr = tail; ptr != NULL; ptr = ptr->prev) + printf("%s\t%d\t%d\n",ptr->name,ptr->eng,ptr->math); +} + +void showAll(student *head, student *tail) /* ܦCC@Ӹ`Ie */ +{ + student *ptr; /* VC@`IҥΪ */ + + printf("ǥ\t\t^\tƾ\n---------------+-------+-----\n"); + for (ptr = head; ptr != NULL; ptr = ptr->next) + printf("%s\t%d\t%d\n",ptr->name,ptr->eng,ptr->math); + + traceBack(tail); +} + +/* ǤJ޼Ƭ@r(ĴpSteve Jobs 50 60)AqѨmWB^BƾǬ즨Z + ƧΦs`IAç`I[JC(վtail) */ +void addRecord(char line[], int showEntireList) +{ + char name[24], str[24]; + student *ptr = tail; + + //tail = tail->next = (student *)malloc(sizeof(student)); //Ыطs`IһݪŶAætailҫǥ᪺ͬ + tail = tail->next = (student *)calloc(1,sizeof(student)); + tail->prev = ptr; + + while (1) { + if (sscanf(line,"%[A-Za-z.] %[^\n]",str,line) == 0) { /* ŪjpgrΥyIզ^WrAŪJstrAĤ@Ӫťդ᪺Ҧr]line */ + sscanf(line,"%d %d",&tail->eng,&tail->math); + break; + } + sprintf(tail->name,tail->name[0]=='\0'? "%s%s": "%s %s",tail->name,str); /* Ū쪺^W[JtailЩҫ`Iname줧 */ + } + tail->next = NULL; + total++; /* `IӼƼW1 */ + if (showEntireList) { //qYܦCҦ + printf("\nW[@ơG%s\t%d\t%d\n\n",tail->name,tail->eng,tail->math); + showAll(head,tail); + } +} + +/* ǤJ޼Ƭ@r(ĴpSteve Jobs 50 60)ANqmW(^BƾǬ즨Z)ǥH + CO_Wr۲Ū(ؼ)`IAYANӸ`Ie`Is_ */ +void deleteRecord(char line[]) +{ + char fullName[24] = {0}, str[24]; + student *ptr; + int score; + + while (1) { + if (sscanf(line,"%[a-zA-Z.] %[^\n]",str,line) == 0) break; + sprintf(fullName,fullName[0]=='\0'? "%s%s" : "%s %s",fullName,str); //sprintf(fullName,fullName[0]=='\0'? "%s%s " : "%s %s ",fullName,str); + } + + for (ptr = head; ptr != NULL; ptr = ptr->next) + if (!strcmp(ptr->name,fullName)) break; /* AߧYj */ + + if (ptr != NULL) { /* ptršANo{ؼ */ + if (ptr->prev==NULL) { /* YNQR`IOCYAhվheadؼФU@`I */ + head = ptr->next; + head->prev = NULL; + } + else { + ptr->prev->next = ptr->next; /* e@`IPؼФU@`Is_(¶Lؼи`I) */ + if (ptr != tail) + ptr->next->prev = ptr->prev; /* U@`IprevVe@`I */ + else + tail = ptr->prev; + } + printf("\n@ơG%s\t%d\t%d\n\n",ptr->name,ptr->eng,ptr->math); + free(ptr); /* Rؼи`IҦŶ */ + total--; /* `IӼƤ1 */ + showAll(head,tail); + } + else + printf("(%s)bƪsb\n",fullName); +} + +/* ǤJ޼ƬC}Y}Pް}CindexName[]_l}A禡NHm(last name)@ƧǨ̾ */ +int sortName(student *head, student *indexName[]) /* ЬŪĤG椸uƲߡGCy}Cvq62-67e */ +{ + int i, j; + char lastName[20], nextLastName[20], firstName[20]; + student *ptr, *temp; + + for (i = 0, ptr = head; ptr != NULL; i++, ptr = ptr->next) + indexName[i] = ptr; /* indexName[i]OsCi`I}ANǦiƧ */ + + for (i = 0; i < total-1; i++) /* wƧǪk */ + for (j = 0; j < total-i-1; j++) { + sscanf(indexName[j]->name,"%s %s %s",lastName,lastName,lastName); + sscanf(indexName[j+1]->name,"%s %s %s",nextLastName,nextLastName,nextLastName); + if (strcmp(lastName,nextLastName) > 0) { /* Yjm > j+1mAh洫 */ + temp = indexName[j]; + indexName[j] = indexName[j+1]; + indexName[j+1] = temp; + } + } + + return 1; +} + +/* ǤJ޼ƬC}Y}Pް}CindexEng[]_l}ANH^妨ZC@ƧǨ̾ڡF + 禡B@zPWsortName()ۦP */ +int sortEng(student *head, student *indexEng[]) +{ + int i, j; + student *ptr, *temp; + + for (i = 0, ptr = head; ptr != NULL; ptr = ptr->next) + indexEng[i++] = ptr; /* indexEng[i]OsCi`I}ANǦiƧ */ + + for (i = 0; i < total-1; i++) /* wƧǪkagain */ + for (j = 0; j < total-i-1; j++) + if (indexEng[j]->eng < indexEng[j+1]->eng) { /* Yj^妨Z < j+1^妨ZAh洫 */ + temp = indexEng[j]; + indexEng[j] = indexEng[j+1]; + indexEng[j+1] = temp; + } + + return 1; +} + +/* ǤJ޼ƬC}Y}Pް}CindexMath[]_l}A禡NHƾǦZC@ƧǨ̾ڡF + 禡B@zPWsortEng()ۦP */ +int sortMath(student *head, student *indexMath[]) +{ + int i, j; + student *ptr, *temp; + + for (i = 0, ptr = head; ptr != NULL; i++, ptr = ptr->next) + indexMath[i] = ptr; /* indexMath[i]OsCi`I}ANǦiƧ */ + + for (i = 0; i < total-1; i++) /* wƧǪkagain */ + for (j = 0; j < total-i-1; j++) + if (indexMath[j]->math < indexMath[j+1]->math) { /* YjƾǦZ < j+1ƾǦZAh洫 */ + temp = indexMath[j]; + indexMath[j] = indexMath[j+1]; + indexMath[j+1] = temp; + } + + return 1; +} + +void queryUser(student *head, student *indexName[], student *indexEng[], student *indexMath[]) +{ + int i, n; + int engSorted = 0, mathSorted = 0; /* O^ƧǻPƾǬƧǬO_wL */ + + while (1) { + printf("\n**************************************************************************************\n" \ + "* 1 HmƧ 2 H^Ƨ 3 ^nW 4 HƾDZƧ 5 ƾDznW 0 *\n" \ + "**************************************************************************************\n" \ + "ܱN@\\H(0--5) ==> "); + switch (getche()) { + case '1': + printf("\n\nHmƧǵGpUG\n"); + sortName(head,indexName); + for (i = 0; i < total; i++) + printf("%s\t%d\t%d\n",indexName[i]->name,indexName[i]->eng,indexName[i]->math); + break; + case '2': + printf("\n\nH^妨ZƧǵGpUG\n"); + engSorted = sortEng(head,indexEng); + for (i = 0; i < total; i++) + printf("%s\t%d\t%d\n",indexEng[i]->name,indexEng[i]->eng,indexEng[i]->math); + break; + case '3': + if (!engSorted) + printf("\n|H^즨ZC@ƧǡAХ\'2\'\\\n"); + else { + printf("\nd߭^nWơAJn (1-%d) ==> ",total); + scanf("%d",&n); + printf("^%d̡G%s\t%d\t%d\n",n,indexEng[n-1]->name,indexEng[n-1]->eng,indexEng[n-1]->math); + } + break; + case '4': + printf("\n\nHƾǦZƧǵGpUG\n"); + mathSorted = sortMath(head,indexMath); + for (i = 0; i < total; i++) + printf("%s\t%d\t%d\n",indexMath[i]->name,indexMath[i]->eng,indexMath[i]->math); + break; + case '5': + if (!mathSorted) + printf("\n|HƾǬ즨ZC@ƧǡAХ\'4\'\\\n"); + else { + printf("\nd߼ƾDznWơAJn (1-%d) ==> ",total); + scanf("%d",&n); + printf("ƾDz%d̡G%s\t%d\t%d\n",n,indexMath[n-1]->name,indexMath[n-1]->eng,indexMath[n-1]->math); + } + break; + case '0': + return; + default: + printf("Īܬ0--5AЭsJ\n"); + system("pause"); + } + } +} + +int main() +{ + int i; + char line[120], mode; /* modeΩϤWƪu@Ҧ */ + + tail = &dummy; /* dummyȮɥγ~`IAɤJ`INϱotailheadlB@קKXAPǥizѳo˼gPAktO? */ + + FILE *inputFile;/* Jɮצb{N */ + if ((inputFile=fopen("YunTechStudents.txt","r")) == NULL) { /* ]w}ɼҦJγ~A˵ɮץi_}ҡAYinputšANɮפsb */ + printf("Jɤsb\n"); + exit(1); /* hX{ */ + } + + for (i = 0; i < 4; i++) fgets(line,120,inputFile); /* Jɶ}Y|CrƱ */ + while (fgets(line,120,inputFile) != NULL) { /* IJɮץݡAN|ƥiŪAưj餺ʧ@ */ + //Ū@CeAsJlinerܼƤ + if (!strcmp(line,"**************************************\n")) break; /* wŪjuANt@BzҦ */ + addRecord(line,0); //Ū쪺Ce(ĴpSteve Jobs 50 60)addRecord()ѨJCFfalseNݱqYܦCҦ + } + + printf("Ĥ@qŪA@%dO\n\n",total); + head = dummy.next; /* wheadVdummy.nextҫ`I */ + head->prev = NULL; + showAll(head,tail); + + printf("\nHWJɮ\"ju\"HWơAN}lW ...\n"); //system("pause"); + getche(); + + while (fgets(line,120,inputFile) != NULL) { + sscanf(line,"%c %[^\n]s",&mode,line); /* Ū'+''-']JmodeܼƤAɩwPBzҦ */ + if (mode == '+') /* W[ */ + addRecord(line,1); /* ClineܼƥaddRecord()ѨһݸơAñqYܦCҦ */ + else if (mode == '-') /* R */ + deleteRecord(line); /* lineҧtmWNdeleteRecord()AYsbCANӵñqYܦCҦ */ + else + printf("OAsorry :(\n"); + } + fclose(inputFile); + + student *indexName[100], *indexEng[100], *indexMath[100]; /* 쪺ް}CAw]iO100Ӹ`I} */ + /* YQϥΦpWTwת}CAitotalƭȤtӼƪ}CAЯdNUgk */ + /* + student **indexName = (student **)malloc(total*sizeof(student *)), + **indexEng = (student **)malloc(total*sizeof(student *)), + **indexMath = (student **)malloc(total*sizeof(student *)); + */ + + queryUser(head,indexName,indexEng,indexMath); /* ͥ\Aè̿ﶵ\ */ + printf("{ABye\n"); + + return 0; +} diff --git a/作業/unit4/老師解答/file-records-adds-drops-v1.exe b/作業/unit4/老師解答/file-records-adds-drops-v1.exe new file mode 100644 index 0000000..5083620 Binary files /dev/null and b/作業/unit4/老師解答/file-records-adds-drops-v1.exe differ diff --git a/作業/unit4/老師解答/file-records-adds-drops-v2.c b/作業/unit4/老師解答/file-records-adds-drops-v2.c new file mode 100644 index 0000000..a0549d7 --- /dev/null +++ b/作業/unit4/老師解答/file-records-adds-drops-v2.c @@ -0,0 +1,290 @@ +/* +Program: file-records-adds-drops-v2.c (Report comments/bugs to chikh@yuntech.edu.tw) +Function: }file-records-adds-drops-v1.cAϱoƧǤ覡iHзǨƮwqsort()@ +Notes: 1) {{VCAF٫oѼƶǨӶǥhlͪӸ`xZAŧiheadBtailPtotal(`I + Ӽ)ܼơAHDn + 2) headPtailܼơA{N]showAll()BsortName()BsortEng()BsortMath() + 禡ǤJhead޼ơAHQPǵoQѼƶǻ򥻧Φ + 3) YheadPtailŧimain()ϰܼơAPǤ]Dp{T + 4) sscanf()ΪkA˳ۦѮvz@g޳Nu http://ccckmit.wikidot.com/cp:sscanf +*/ + +#include +#include /* for malloc(), calloc(), qsort() */ +#include /* for strcmp() */ +#include /* for getche() */ + +typedef struct student student; +struct student { + char name[24]; + int eng, math; + student *prev; + student *next; +} *head, *tail, dummy; + +int total = 0; + +void traceBack(student *tail) /* qYܧܨC@Ӹ`Ie */ +{ + student *ptr; /* VC@`IҥΪ */ + + printf("\n^ܾǥͬpUG\n"); + for (ptr = tail; ptr != NULL; ptr = ptr->prev) + printf("%s\t%d\t%d\n",ptr->name,ptr->eng,ptr->math); +} + +void showAll(student *head, student *tail) /* ܦCC@Ӹ`Ie */ +{ + student *ptr; /* VC@`IҥΪ */ + + printf("ǥ\t\t^\tƾ\n---------------+-------+-----\n"); + for (ptr = head; ptr != NULL; ptr = ptr->next) + printf("%s\t%d\t%d\n",ptr->name,ptr->eng,ptr->math); + + traceBack(tail); +} + +/* ǤJ޼Ƭ@r(ĴpSteve Jobs 50 60)AqѨmWB^BƾǬ즨Z + ƧΦs`IAç`I[JC(վtail) */ +void addRecord(char line[], int showEntireList) +{ + char name[24], str[24]; + student *ptr = tail; + + //tail = tail->next = (student *)malloc(sizeof(student)); //Ыطs`IһݪŶAætailҫǥ᪺ͬ + tail = tail->next = (student *)calloc(1,sizeof(student)); + tail->prev = ptr; + + while (1) { + if (sscanf(line,"%[A-Za-z.] %[^\n]",str,line) == 0) { /* ŪjpgrΥyIզ^WrAŪJstrAĤ@Ӫťդ᪺Ҧr]line */ + sscanf(line,"%d %d",&tail->eng,&tail->math); + break; + } + sprintf(tail->name,tail->name[0]=='\0'? "%s%s": "%s %s",tail->name,str); /* Ū쪺^W[JtailЩҫ`Iname줧 */ + } + tail->next = NULL; + total++; /* `IӼƼW1 */ + if (showEntireList) { //qYܦCҦ + printf("\nW[@ơG%s\t%d\t%d\n\n",tail->name,tail->eng,tail->math); + showAll(head,tail); + } +} + +/* ǤJ޼Ƭ@r(ĴpSteve Jobs 50 60)ANqmW(^BƾǬ즨Z)ǥH + CO_Wr۲Ū(ؼ)`IAYANӸ`Ie`Is_ */ +void deleteRecord(char line[]) +{ + char fullName[24] = {0}, str[24]; + student *ptr; + int score; + + while (1) { + if (sscanf(line,"%[a-zA-Z.] %[^\n]",str,line) == 0) break; + sprintf(fullName,fullName[0]=='\0'? "%s%s" : "%s %s",fullName,str); //sprintf(fullName,fullName[0]=='\0'? "%s%s " : "%s %s ",fullName,str); + } + + for (ptr = head; ptr != NULL; ptr = ptr->next) + if (!strcmp(ptr->name,fullName)) break; /* AߧYj */ + + if (ptr != NULL) { /* ptršANo{ؼ */ + if (ptr->prev==NULL) { /* YNQR`IOCYAhվheadؼФU@`I */ + head = ptr->next; + head->prev = NULL; + } + else { + ptr->prev->next = ptr->next; /* e@`IPؼФU@`Is_(¶Lؼи`I) */ + if (ptr != tail) + ptr->next->prev = ptr->prev; /* U@`IprevVe@`I */ + else + tail = ptr->prev; + } + printf("\n@ơG%s\t%d\t%d\n\n",ptr->name,ptr->eng,ptr->math); + free(ptr); /* Rؼи`IҦŶ */ + total--; /* `IӼƤ1 */ + showAll(head,tail); + } + else + printf("(%s)bƪsb\n",fullName); +} + +int nameAscend(const void *a, const void *b) /* WҦ */ +{ + student **x = (student **)a; + student **y = (student **)b; + + char lastName[16], nextLastName[16]; + + sscanf((**x).name,"%s %s %s",lastName,lastName,lastName); + sscanf((**y).name,"%s %s %s",nextLastName,nextLastName,nextLastName); + + return strcmp(lastName,nextLastName); //return strcmp((**x).name,(**y).name); +} + +int engDescend(const void *a, const void *b) /* Ҧ */ +{ + student **x = (student **)a; + student **y = (student **)b; + + return (**y).eng - (**x).eng; +} + +int mathDescend(const void *a, const void *b) /* Ҧ */ +{ + student **x = (student **)a; + student **y = (student **)b; + + return (**y).math - (**x).math; +} + +int sortName(student *head, student *indexName[]) /* ЬŪĤG椸uƲߡGCy}Cvq62-67e */ +{ + int i, j; + char lastName[20], nextLastName[20], firstName[20]; + student *ptr, *temp; + + for (i = 0, ptr = head; ptr != NULL; i++, ptr = ptr->next) + indexName[i] = ptr; /* indexName[i]OsCi`I}ANǦiƧ */ + + qsort(indexName,total,sizeof(indexName[0]),nameAscend); + + return 1; +} + +/* ǤJ޼ƬC}Y}Pް}CindexEng[]_l}ANH^妨ZC@ƧǨ̾ڡF + 禡B@zPWsortName()ۦP */ +int sortEng(student *head, student *indexEng[]) +{ + int i, j; + student *ptr, *temp; + + for (i = 0, ptr = head; ptr != NULL; ptr = ptr->next) + indexEng[i++] = ptr; /* indexEng[i]OsCi`I}ANǦiƧ */ + + qsort(indexEng,total,sizeof(indexEng[0]),engDescend); + + return 1; +} + +/* ǤJ޼ƬC}Y}Pް}CindexMath[]_l}A禡NHƾǦZC@ƧǨ̾ڡF + 禡B@zPWsortEng()ۦP */ +int sortMath(student *head, student *indexMath[]) +{ + int i, j; + student *ptr, *temp; + + for (i = 0, ptr = head; ptr != NULL; i++, ptr = ptr->next) + indexMath[i] = ptr; /* indexMath[i]OsCi`I}ANǦiƧ */ + + qsort(indexMath,total,sizeof(indexMath[0]),mathDescend); + + return 1; +} + +void queryUser(student *head, student *indexName[], student *indexEng[], student *indexMath[]) +{ + int i, n; + int engSorted = 0, mathSorted = 0; /* O^ƧǻPƾǬƧǬO_wL */ + + while (1) { + printf("\n**************************************************************************************\n" \ + "* 1 HmƧ 2 H^Ƨ 3 ^nW 4 HƾDZƧ 5 ƾDznW 0 *\n" \ + "**************************************************************************************\n" \ + "ܱN@\\H(0--5) ==> "); + switch (getche()) { + case '1': + printf("\n\nHmƧǵGpUG\n"); + sortName(head,indexName); + for (i = 0; i < total; i++) + printf("%s\t%d\t%d\n",indexName[i]->name,indexName[i]->eng,indexName[i]->math); + break; + case '2': + printf("\n\nH^妨ZƧǵGpUG\n"); + engSorted = sortEng(head,indexEng); + for (i = 0; i < total; i++) + printf("%s\t%d\t%d\n",indexEng[i]->name,indexEng[i]->eng,indexEng[i]->math); + break; + case '3': + if (!engSorted) + printf("\n|H^즨ZC@ƧǡAХ\'2\'\\\n"); + else { + printf("\nd߭^nWơAJn (1-%d) ==> ",total); + scanf("%d",&n); + printf("^%d̡G%s\t%d\t%d\n",n,indexEng[n-1]->name,indexEng[n-1]->eng,indexEng[n-1]->math); + } + break; + case '4': + printf("\n\nHƾǦZƧǵGpUG\n"); + mathSorted = sortMath(head,indexMath); + for (i = 0; i < total; i++) + printf("%s\t%d\t%d\n",indexMath[i]->name,indexMath[i]->eng,indexMath[i]->math); + break; + case '5': + if (!mathSorted) + printf("\n|HƾǬ즨ZC@ƧǡAХ\'4\'\\\n"); + else { + printf("\nd߼ƾDznWơAJn (1-%d) ==> ",total); + scanf("%d",&n); + printf("ƾDz%d̡G%s\t%d\t%d\n",n,indexMath[n-1]->name,indexMath[n-1]->eng,indexMath[n-1]->math); + } + break; + case '0': + return; + default: + printf("Īܬ0--5AЭsJ\n"); + system("pause"); + } + } +} + +int main() +{ + int i; + char line[120], mode; /* modeΩϤWƪu@Ҧ */ + + tail = &dummy; /* dummyȮɥγ~`IAɤJ`INϱotailheadlB@קKXAPǥizѳo˼gPAktO? */ + + FILE *inputFile;/* Jɮצb{N */ + if ((inputFile=fopen("YunTechStudents.txt","r")) == NULL) { /* ]w}ɼҦJγ~A˵ɮץi_}ҡAYinputšANɮפsb */ + printf("Jɤsb\n"); + exit(1); /* hX{ */ + } + + for (i = 0; i < 4; i++) fgets(line,120,inputFile); /* Jɶ}Y|CrƱ */ + while (fgets(line,120,inputFile) != NULL) { /* IJɮץݡAN|ƥiŪAưj餺ʧ@ */ + //Ū@CeAsJlinerܼƤ + if (!strcmp(line,"**************************************\n")) break; /* wŪjuANt@BzҦ */ + addRecord(line,0); //Ū쪺Ce(ĴpSteve Jobs 50 60)addRecord()ѨJCFfalseNݱqYܦCҦ + } + + printf("Ĥ@qŪA@%dO\n\n",total); + head = dummy.next; /* wheadVdummy.nextҫ`I */ + head->prev = NULL; + showAll(head,tail); + + printf("\nHWJɮ\"ju\"HWơAN}lW ...\n"); //system("pause"); + getche(); + + while (fgets(line,120,inputFile) != NULL) { + sscanf(line,"%c %[^\n]s",&mode,line); /* Ū'+''-']JmodeܼƤAɩwPBzҦ */ + if (mode == '+') /* W[ */ + addRecord(line,1); /* ClineܼƥaddRecord()ѨһݸơAñqYܦCҦ */ + else if (mode == '-') /* R */ + deleteRecord(line); /* lineҧtmWNdeleteRecord()AYsbCANӵñqYܦCҦ */ + else + printf("OAsorry :(\n"); + } + fclose(inputFile); + + student *indexName[100], *indexEng[100], *indexMath[100]; /* 쪺ް}CAw]iO100Ӹ`I} */ + /* YQϥΦpWTwת}CAitotalƭȤtӼƪ}CAЯdNUgk */ + /* + student **indexName = (student **)malloc(total*sizeof(student *)), + **indexEng = (student **)malloc(total*sizeof(student *)), + **indexMath = (student **)malloc(total*sizeof(student *)); + */ + + queryUser(head,indexName,indexEng,indexMath); /* ͥ\Aè̿ﶵ\ */ + printf("{ABye\n"); + + return 0; +} diff --git a/作業/unit4/老師解答/file-records-adds-drops.zip b/作業/unit4/老師解答/file-records-adds-drops.zip new file mode 100644 index 0000000..4371850 Binary files /dev/null and b/作業/unit4/老師解答/file-records-adds-drops.zip differ diff --git a/作業/unit4/老師解答/sscanf.c b/作業/unit4/老師解答/sscanf.c new file mode 100644 index 0000000..1970e62 --- /dev/null +++ b/作業/unit4/老師解答/sscanf.c @@ -0,0 +1,86 @@ +/* +Program: sscanf.c +Function: isscanf()Pqsort()Ϊk +Note: sצ۳۱бª http://ccckmit.wikidot.com/cp:sscanf +*/ + +#include + +int ascend(const void *a, const void *b); //tXqsort()ҥΨơAΩǤJGjpYAΩ{WλĪG + +int main() { + char name[20], tel[50], field[20], areaCode[20], code[20]; + int age; + + sscanf("name:john age:40 tel:082-313530", "%s", name); + printf("%s\n", name); + sscanf("name:john age:40 tel:082-313530", "%8s", name); + printf("%s\n", name); + sscanf("name:john age:40 tel:082-313530", "%[^:]", name); + printf("%s\n", name); + sscanf("name:john age:40 tel:082-313530", "%[^:]:%s", field, name); + printf("%s %s\n", field, name); + sscanf("name:john age:40 tel:082-313530", "name:%s age:%d tel:%s", name, &age, tel); + printf("%s %d %s\n", name, age, tel); + sscanf("name:john age:40 tel:082-313530", "%*[^:]:%s %*[^:]:%d %*[^:]:%s", name, &age, tel); + printf("%s %d %s\n", name, age, tel); + + char protocol[10], site[50], path[50]; + sscanf("http://ccckmit.wikidot.com/cp/list/hello.txt", + "%[^:]:%*2[/]%[^/]/%[a-zA-Z0-9._/-]", + protocol, site, path); + printf("protocol=%s site=%s path=%s\n", protocol, site, path); + + /*-----------------------------------------------------------------------*/ + + char str[30]; +// char line[] = "Steve Jobs 50 60"; + char line[] = "U. S. Grant 97 88"; + int s1, s2; + + for (;;) { + if (sscanf(line,"%[A-Za-z.] %[^\n]",str,line)==0) { + sscanf(line,"%d %d",&s1,&s2); + printf("\n̥GƦrGs1 = %d; s2 = %d\n",s1,s2); + break; + } + printf("\nŪXŰOG%-10sѾleG%s",str,line); + } + + + char fullName[] = "U. S. Grant", tmp[3][24]; + + s1 = sscanf(fullName,"%s %s %s",tmp[0],tmp[1],tmp[2]); + printf("\nĤ@ؤkXmG%s",tmp[s1-1]); + + s1 = sscanf(fullName,"%s %s %s",str,str,str); + printf("\nĤGؤkXmG%s",str); + + for (;;) { + if (sscanf(fullName,"%s %[^\n]",str,fullName) < 2) { + printf("\nĤTؤkXmG%s",fullName); + break; + } + } + + /*-----------------------------------------------------------------------*/ + + char bigName[][12] = {"Jobs", "Cruise", "Jane", "Obama", "Tyler", "Grant", "Redford", "Lee"}; + int i, count = sizeof(bigName)/sizeof(bigName[0]), + size = sizeof(bigName[0]); + + qsort(bigName,count,size,ascend); + + printf("\n\nƧǫᵲGpU:\n"); + for (i = 0; i < count; i++) + printf("%s\n",bigName[i]); + + return 0; +} + +int ascend(const void *a, const void *b) /* WҦ */ +{ + char *x = (char *)a; + char *y = (char *)b; + return strcmp(x,y); +} diff --git a/作業/unit4/老師解答/sscanf.exe b/作業/unit4/老師解答/sscanf.exe new file mode 100644 index 0000000..aa022a3 Binary files /dev/null and b/作業/unit4/老師解答/sscanf.exe differ diff --git a/作業/unit5/.vscode/c_cpp_properties.json b/作業/unit5/.vscode/c_cpp_properties.json new file mode 100644 index 0000000..cea4d3f --- /dev/null +++ b/作業/unit5/.vscode/c_cpp_properties.json @@ -0,0 +1,18 @@ +{ + "configurations": [ + { + "name": "windows-gcc-x64", + "includePath": [ + "${workspaceFolder}/**" + ], + "compilerPath": "gcc", + "cStandard": "${default}", + "cppStandard": "${default}", + "intelliSenseMode": "windows-gcc-x64", + "compilerArgs": [ + "" + ] + } + ], + "version": 4 +} \ No newline at end of file diff --git a/作業/unit5/.vscode/launch.json b/作業/unit5/.vscode/launch.json new file mode 100644 index 0000000..af6ca4c --- /dev/null +++ b/作業/unit5/.vscode/launch.json @@ -0,0 +1,24 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "C/C++ Runner: Debug Session", + "type": "cppdbg", + "request": "launch", + "args": [], + "stopAtEntry": false, + "externalConsole": true, + "cwd": "e:/code/C++/unit5", + "program": "e:/code/C++/unit5/build/Debug/outDebug", + "MIMode": "gdb", + "miDebuggerPath": "gdb", + "setupCommands": [ + { + "description": "Enable pretty-printing for gdb", + "text": "-enable-pretty-printing", + "ignoreFailures": true + } + ] + } + ] +} \ No newline at end of file diff --git a/作業/unit5/.vscode/settings.json b/作業/unit5/.vscode/settings.json new file mode 100644 index 0000000..bb879da --- /dev/null +++ b/作業/unit5/.vscode/settings.json @@ -0,0 +1,59 @@ +{ + "C_Cpp_Runner.cCompilerPath": "gcc", + "C_Cpp_Runner.cppCompilerPath": "g++", + "C_Cpp_Runner.debuggerPath": "gdb", + "C_Cpp_Runner.cStandard": "", + "C_Cpp_Runner.cppStandard": "", + "C_Cpp_Runner.msvcBatchPath": "C:/Program Files/Microsoft Visual Studio/VR_NR/Community/VC/Auxiliary/Build/vcvarsall.bat", + "C_Cpp_Runner.useMsvc": false, + "C_Cpp_Runner.warnings": [ + "-Wall", + "-Wextra", + "-Wpedantic", + "-Wshadow", + "-Wformat=2", + "-Wcast-align", + "-Wconversion", + "-Wsign-conversion", + "-Wnull-dereference" + ], + "C_Cpp_Runner.msvcWarnings": [ + "/W4", + "/permissive-", + "/w14242", + "/w14287", + "/w14296", + "/w14311", + "/w14826", + "/w44062", + "/w44242", + "/w14905", + "/w14906", + "/w14263", + "/w44265", + "/w14928" + ], + "C_Cpp_Runner.enableWarnings": true, + "C_Cpp_Runner.warningsAsError": false, + "C_Cpp_Runner.compilerArgs": [], + "C_Cpp_Runner.linkerArgs": [], + "C_Cpp_Runner.includePaths": [], + "C_Cpp_Runner.includeSearch": [ + "*", + "**/*" + ], + "C_Cpp_Runner.excludeSearch": [ + "**/build", + "**/build/**", + "**/.*", + "**/.*/**", + "**/.vscode", + "**/.vscode/**" + ], + "C_Cpp_Runner.useAddressSanitizer": false, + "C_Cpp_Runner.useUndefinedSanitizer": false, + "C_Cpp_Runner.useLeakSanitizer": false, + "C_Cpp_Runner.showCompilationTime": false, + "C_Cpp_Runner.useLinkTimeOptimization": false, + "C_Cpp_Runner.msvcSecureNoWarnings": false +} \ No newline at end of file diff --git a/作業/unit5/DS5.cpp b/作業/unit5/DS5.cpp new file mode 100644 index 0000000..49ada7a --- /dev/null +++ b/作業/unit5/DS5.cpp @@ -0,0 +1,54 @@ +#include +#include +#include + +int count_num = 0 , count = 1 , temp ; + +int calculate(int i ,int count_num, int num ){ + int a = 0; + if(num>=i) { + num -= i; + count_num++; + }else if(num!=0){ + count_num++; + printf("\n̤p]\\˯ȭn = %d\n",(count_num+i+temp)*2*100); + printf("\n]ˤ覡\\YzơG\n\n"); + printf("%dơA\\%d\n",count,i); + count++; + a = num; + return a; + }else{ + printf("\n̤p]\\˯ȭn = %d\n",(count_num+i+temp)*2*100); + printf("\n]ˤ覡Yz\n\n"); + a = num; + return a; + } + + a = calculate(i,count_num,num); + + if(num != temp - i || temp%i==0){ + printf("%dơA\\%d\n",count,i); + }else { + printf("%dơA\\%d\n",count,a); + } + + count++; + return a; +} + +int main(){ + int num ,i=0; + printf("*** ̤p]˭nlH]L{ ***\n\nJ}j ==> "); + scanf("%d",&num); + if(num<=0){ + printf("\nJ~"); + return 0; + } + + i = sqrt(num); + temp = num ; + + calculate(i,count_num,num); + + return 0; +} diff --git a/作業/unit5/DS5.exe b/作業/unit5/DS5.exe new file mode 100644 index 0000000..78b2978 Binary files /dev/null and b/作業/unit5/DS5.exe differ diff --git a/作業/unit5/DS5_not_Recursion.cpp b/作業/unit5/DS5_not_Recursion.cpp new file mode 100644 index 0000000..a377b9c --- /dev/null +++ b/作業/unit5/DS5_not_Recursion.cpp @@ -0,0 +1,37 @@ +#include +#include +#include + +int main(){ + int num ,i=0 , j=1 ,temp; + printf("*** ̤p]˭nlH]L{ ***\n\nJ}j ==> "); + scanf("%d",&num); + temp = num ; + while(1){ + if(pow(i,2)<=temp) i++; + else break; + } + i--; + + printf("\n]ˤ覡Yz\n\n"); + + while(1){ + if(temp>=i){ + printf("%dơA%d\n",j,i); + temp -= i; + j++; + }else if(temp!=0){ + printf("%dơA%d\n",j,temp); + j++; + break; + }else{ + break; + } + } + j--; + + printf("\n̤p]˯ȭn = %d\n",(j+i+num)*2*100); + + + return 0; +} diff --git a/作業/unit5/DS5_not_Recursion.exe b/作業/unit5/DS5_not_Recursion.exe new file mode 100644 index 0000000..4e65eed Binary files /dev/null and b/作業/unit5/DS5_not_Recursion.exe differ diff --git a/作業/unit5/Makefile.win b/作業/unit5/Makefile.win new file mode 100644 index 0000000..44d8be4 --- /dev/null +++ b/作業/unit5/Makefile.win @@ -0,0 +1,28 @@ +# Project: Project1 +# Makefile created by Dev-C++ 5.11 + +CPP = g++.exe +CC = gcc.exe +WINDRES = windres.exe +OBJ = gcd.o +LINKOBJ = gcd.o +LIBS = -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib" -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/lib" -static-libgcc +INCS = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include" +CXXINCS = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include/c++" +BIN = Project1.exe +CXXFLAGS = $(CXXINCS) +CFLAGS = $(INCS) +RM = rm.exe -f + +.PHONY: all all-before all-after clean clean-custom + +all: all-before $(BIN) all-after + +clean: clean-custom + ${RM} $(OBJ) $(BIN) + +$(BIN): $(OBJ) + $(CPP) $(LINKOBJ) -o $(BIN) $(LIBS) + +gcd.o: gcd.cpp + $(CPP) -c gcd.cpp -o gcd.o $(CXXFLAGS) diff --git a/作業/unit5/Project1.dev b/作業/unit5/Project1.dev new file mode 100644 index 0000000..b65d61b --- /dev/null +++ b/作業/unit5/Project1.dev @@ -0,0 +1,62 @@ +[Project] +FileName=Project1.dev +Name=Project1 +Type=1 +Ver=2 +ObjFiles= +Includes= +Libs= +PrivateResource= +ResourceIncludes= +MakeIncludes= +Compiler= +CppCompiler= +Linker= +IsCpp=1 +Icon= +ExeOutput= +ObjectOutput= +LogOutput= +LogOutputEnabled=0 +OverrideOutput=0 +OverrideOutputName= +HostApplication= +UseCustomMakefile=0 +CustomMakefile= +CommandLine= +Folders= +IncludeVersionInfo=0 +SupportXPThemes=0 +CompilerSet=0 +CompilerSettings=0000000000000000000000000 +UnitCount=1 + +[VersionInfo] +Major=1 +Minor=0 +Release=0 +Build=0 +LanguageID=1033 +CharsetID=1252 +CompanyName= +FileVersion= +FileDescription=Developed using the Dev-C++ IDE +InternalName= +LegalCopyright= +LegalTrademarks= +OriginalFilename= +ProductName= +ProductVersion= +AutoIncBuildNr=0 +SyncProduct=1 + +[Unit1] +FileName=gcd.cpp +CompileCpp=1 +Folder= +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd= + diff --git a/作業/unit5/Project1.exe b/作業/unit5/Project1.exe new file mode 100644 index 0000000..b673bc6 Binary files /dev/null and b/作業/unit5/Project1.exe differ diff --git a/作業/unit5/Project1.layout b/作業/unit5/Project1.layout new file mode 100644 index 0000000..c440945 --- /dev/null +++ b/作業/unit5/Project1.layout @@ -0,0 +1,13 @@ +[Editor_0] +CursorCol=12 +CursorRow=30 +TopLine=1 +LeftChar=1 +[Editor_1] +CursorCol=1 +CursorRow=1 +TopLine=9 +LeftChar=1 +[Editors] +Order=0 +Focused=0 diff --git a/作業/unit5/dir-all.c b/作業/unit5/dir-all.c new file mode 100644 index 0000000..173665c --- /dev/null +++ b/作業/unit5/dir-all.c @@ -0,0 +1,63 @@ +/* +Program: dir-all.c (Report comments/bugs to chikh@yuntech.edu.tw) +Function: ܫwؿҦɮפTAĴpROCJ c:\temp\ ˵ĪG +Note: + 1. {ϥdirent.hAӼYɩwqؿcƫAAӼYɦ + C:\Program Files (x86)\Dev-Cpp\MinGW64\x86_64-w64-mingw32\include + 2. ROCJΦ c:\\temp\\ aܿJ c:\temp\ Yi + TAݨӤݦb|yzrꤤhµ˱׽uAЦPǹıӷLt + 3. Dev-C++Ѫdirent.hҩwqdirentcpUG + struct dirent + { + long d_ino; // Always zero + unsigned short d_reclen; // Always zero + unsigned short d_namlen; // Length of name in d_name + char d_name[260];// File name + }; +*/ + +#include +#include +#include +#include + +int main() +{ + DIR *dpdf; //ŧi|A opendirft ΨӦs}Ҹ|Om + struct dirent *epdf; + char directoryPath[128], fileName[256]; + long i, fileSize, fileCount; + FILE *fp; + + system("cls"); + printf("\nJؿ| ==> "); + scanf("%127[^\n]%*c",directoryPath); + + if ((dpdf=opendir(directoryPath)) == NULL) { //opendirDIRAhm + printf("ؿsb!\n"); + return -1; + } + printf("ؿҦɮ׸TpU ...\n=============================================\n"); + while (epdf = readdir(dpdf)) { //ŪɮשҦbؿAundpdfҫešAYNۦɮצsbA]iJjBz + if (strcmp(epdf->d_name,".")==0 || strcmp(epdf->d_name,"..")==0) continue; //oɦW@w|sb @wnư ]oOtΦ۰ʥͦ ]|۰ Alinux|Q + sprintf(fileName,"%s%s",directoryPath,epdf->d_name); // |+ɦW + if ((fp=fopen(fileName,"rb")) == NULL) { // }ɮסA}ɼҦ"J+X+rDrqY" + //printf("File open error\n"); + printf("%-50s *lؿ*\n",epdf->d_name); + } + else { + fseek(fp,0,SEEK_END); /* ɮŪgY̧ܳ */ + fileSize = ftell(fp); /* 򪾩ҦbmA⬰ɮת */ + fclose(fp); + printf("%-50s %d bytes\n",epdf->d_name,fileSize); + fileCount++; + } + } + + closedir(dpdf); //ؿƵc + printf("=============================================\nƧ@%dɮ!\n",fileCount); + + return 0; +} + + diff --git a/作業/unit5/factorUsingIterative.c b/作業/unit5/factorUsingIterative.c new file mode 100644 index 0000000..906f71f --- /dev/null +++ b/作業/unit5/factorUsingIterative.c @@ -0,0 +1,57 @@ +/* + file name: factorUsingIterative.c + Description: Factorial numbers count using iterative + Qΰj鰵Np +*/ + +#include +#include +#include + +/* ƭ쫬ŧi */ +long Factorial(long); +void flushBuffer(void); + +int main() +{ + char ch; + long n; + + printf("-----Factorial counting using Iterative-----"); + do { + printf("\nEnter a number(0 <= n <= 12) to count n!: "); + scanf("%ld",&n); + flushBuffer(); + if (n < 0 || n > 12) + printf("Input out of range!\n"); + else + printf("%ld! = %ld\n", n, Factorial(n)); + + printf("Continue(y/n)? "); + ch = toupper(getchar()); + } while (ch == 'Y'); + + return 0; +} + +long Factorial(long n) +{ + long sum = 1; + int i; + + if (n == 0 || n ==1) /* n=0 n=1 , 0!=1, 1!=1 */ + return (1); /* GǦ^1 */ + else { + for (i = 2; i<= n; i++) /* sum OثeM */ + sum *= i; /* sum P i ۭM^ sum */ + } + return (sum); +} + +void flushBuffer() +{ + while (getchar() != '\n') { + continue; + } +} + diff --git a/作業/unit5/factorUsingIterative.o b/作業/unit5/factorUsingIterative.o new file mode 100644 index 0000000..888169e Binary files /dev/null and b/作業/unit5/factorUsingIterative.o differ diff --git a/作業/unit5/factorUsingRecursive.c b/作業/unit5/factorUsingRecursive.c new file mode 100644 index 0000000..4c0e5c1 --- /dev/null +++ b/作業/unit5/factorUsingRecursive.c @@ -0,0 +1,53 @@ +/* + file name: factorUsingRecursive.c + Description: QλjIsp N +*/ + +#include +#include +#include + +/* ƭ쫬ŧi */ +long Factorial(long); +void flushBuffer(void); + +int main() +{ + char ch; + unsigned long n; + + printf("-----Factorial counting Using Recursive----"); + do { + printf("\nEnter a number( 0<=n<=12 ) to count n!: "); + scanf("%ld", &n); +// flushBuffer(); + fflush(stdin); + /* n Ȧb@tΤWL 13 | overflow o줣T */ + if (n < 0 || n >12) + printf("WXd!\n"); + else + printf("%ld! = %ld\n", n, Factorial(n) ); + + printf("Continue(y/n)? "); + ch = toupper(getchar()); + } while (ch == 'Y'); + + return 0; +} + +/* QλjIsۤvpN */ +long Factorial(long n) +{ + if ( n == 1 || n== 0) + return (1); + else + return( n * Factorial(n-1)); +} + +//void flushBuffer() +//{ +// while (getchar() != '\n') { +// continue; +// } +//} + diff --git a/作業/unit5/factorUsingRecursive.o b/作業/unit5/factorUsingRecursive.o new file mode 100644 index 0000000..a0cfaba Binary files /dev/null and b/作業/unit5/factorUsingRecursive.o differ diff --git a/作業/unit5/folder_info.cpp b/作業/unit5/folder_info.cpp new file mode 100644 index 0000000..17e4405 --- /dev/null +++ b/作業/unit5/folder_info.cpp @@ -0,0 +1,98 @@ +#include +#include +#include +#include +#include // ΩˬdO_ؿ + +// ܼƫŧi +FILE *fp; +long fileCount = 0; + +// sWYƻU禡 +void printIndent(int level) { + printf("|"); + for(int i = 0; i < level; i++) { + printf(" "); // ChYƨӪŮ + } +} + +// קאּj +void open_folder(char *path, int level) { + DIR *dir; + struct dirent *entry; + char fullPath[512]; + struct stat statbuf; + long fileSize; + + // }ҥؿ + if ((dir = opendir(path)) == NULL) { + printf("Lk}ҥؿ: %s\n", path); + return; + } + + // Ūؿe + while ((entry = readdir(dir)) != NULL) { + // L . M .. + if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) + continue; + + // cا| + snprintf(fullPath, sizeof(fullPath), "%s/%s", path, entry->d_name); + + // oɮ׸T + if (stat(fullPath, &statbuf) == -1) { + printf("Lkoɮ׸T: %s\n", fullPath); + continue; + } + + // LXثehŪY + printIndent(level); + + // P_Oؿ٬Oɮ + if (S_ISDIR(statbuf.st_mode)) { + // Oؿ + printf("[Ƨ] %s\n", entry->d_name); + // jBzlؿ + open_folder(fullPath, level + 1); + } else { + // Oɮ + if ((fp = fopen(fullPath, "rb")) != NULL) { + fseek(fp, 0, SEEK_END); + fileSize = ftell(fp); + fclose(fp); + printf(" %s (%ld bytes)\n", entry->d_name, fileSize); + fileCount++; + } else { + printf("%s (LkŪ)\n", entry->d_name); + } + } + } + + closedir(dir); +} + +int main() { + char directoryPath[128]; + + system("cls"); + printf("\nJؿ| ==> "); + scanf("%127[^\n]%*c", directoryPath); + + // |׽u]pGܡ^ + size_t len = strlen(directoryPath); + if (len > 0 && (directoryPath[len-1] == '\\' || directoryPath[len-1] == '/')) { + directoryPath[len-1] = '\0'; + } + + if (opendir(directoryPath) == NULL) { + printf("ؿsb!\n"); + return -1; + } + + printf("\nؿecpUG\n=======================================\n"); + open_folder(directoryPath, 0); + printf("=======================================\n"); + printf("`@ %ld ɮ\n", fileCount); + + return 0; +} diff --git a/作業/unit5/folder_info.exe b/作業/unit5/folder_info.exe new file mode 100644 index 0000000..592dc6e Binary files /dev/null and b/作業/unit5/folder_info.exe differ diff --git a/作業/unit5/gcd-indent.cpp b/作業/unit5/gcd-indent.cpp new file mode 100644 index 0000000..6a042c2 --- /dev/null +++ b/作業/unit5/gcd-indent.cpp @@ -0,0 +1,31 @@ +#include +#include + +void gcd(int a , int b ){ + int temp , r; + r = a % b; + + if(r!=0){ + if(b>a){ + temp = a; + a = b; + b = temp; + } + r = a % b; + printf("gcd(%d,%d)\n",a,b); + a = r; + + gcd(a,b); + }else{ + printf("gcd(%d,%d)\n",b,a); + printf("\nans = %d",b); + } +} + +int main(){ + int a , b ,ans; + printf("Jӥ ==> "); + scanf("%d %d",&a,&b); + gcd(a,b); + return 0 ; +} diff --git a/作業/unit5/gcd-indent.exe b/作業/unit5/gcd-indent.exe new file mode 100644 index 0000000..adf00bc Binary files /dev/null and b/作業/unit5/gcd-indent.exe differ diff --git a/作業/unit5/gcd.cpp b/作業/unit5/gcd.cpp new file mode 100644 index 0000000..f00626b --- /dev/null +++ b/作業/unit5/gcd.cpp @@ -0,0 +1,61 @@ +#include +#include + +void gcd(int a , int b ){ + int temp , r; + r = a % b; + + if(r!=0){ + if(b>a){ + temp = a; + a = b; + b = temp; + } + r = a % b; + printf("gcd(%d,%d)\n",a,b); + a = r; + + gcd(a,b); + }else{ + printf("gcd(%d,%d)\n",b,a); + printf("\nans = %d",b); + } +} + +int main(){ + int a , b ,ans; + printf("Jӥ ==> "); + scanf("%d %d",&a,&b); + gcd(a,b); + return 0 ; +} + + +//#include +//#include +// +//int gcd(int a, int b) { +// // LXepBJ +// printf("gcd(%d,%d)\n", a, b); +// +// // 򥻱pGpG b 0Ah a ̤j] +// if (b == 0) { +// return a; +// } +// +// // jpGgcd(a,b) = gcd(b,a%b) +// return gcd(b, a % b); +//} +// +//int main() { +// int a, b, ans; +// printf("Jӥ ==> "); +// scanf("%d %d", &a, &b); +// +// printf("%d\n",a % b); +// +// ans = gcd(a, b); +// printf("\nans = %d\n", ans); +// +// return 0; +//} diff --git a/作業/unit5/gcd.exe b/作業/unit5/gcd.exe new file mode 100644 index 0000000..9fa73bd Binary files /dev/null and b/作業/unit5/gcd.exe differ diff --git a/作業/unit5/gcd.o b/作業/unit5/gcd.o new file mode 100644 index 0000000..0465d14 Binary files /dev/null and b/作業/unit5/gcd.o differ diff --git a/作業/unit5/narcissistic-number.cpp b/作業/unit5/narcissistic-number.cpp new file mode 100644 index 0000000..6f8a47b --- /dev/null +++ b/作業/unit5/narcissistic-number.cpp @@ -0,0 +1,85 @@ +#include +#include +#include + +// pbwiU +int getDigitCount(int num, int base) { + int count = 0; + while (num > 0) { + count++; + num /= base; + } + return count; +} + +// ˬdO_i +int isArmstrong(int num, int base) { + int originalNum = num; + int digitCount = getDigitCount(num, base); + int sum = 0; + + while (num > 0) { + int digit = num % base; + sum += pow(digit, digitCount); + num /= base; + } + + return (sum == originalNum); +} + +// NƦrഫwir +void printNumber(int num, int base) { + if (num < 10) { + printf("%d", num); + } else { + printf("%c", 'A' + (num - 10)); + } +} + +int main() { + int count = 0; + int targetCount; + int base; + int num = 1; + + printf("ph֭Ӫi? ==> "); + scanf("%d", &targetCount); + + printf("J(<16) ==> "); + scanf("%d", &base); + + if (base < 2 || base > 16) { + printf("򩳥b215\n"); + return 1; + } + + printf("\nb%diUe%dӪiơG\n", base, targetCount); + + while (count < targetCount) { + if (isArmstrong(num, base)) { + printf("#%d\t", count + 1); + + // LXƦri + int temp = num; + int digits[32]; + int digitCount = 0; + + // ഫwi + while (temp > 0) { + digits[digitCount++] = temp % base; + temp /= base; + } + + // ϦVLXƦr + for (int i = digitCount - 1; i >= 0; i--) { + printNumber(digits[i], base); + } + printf("\n"); + + count++; + } + num++; + } + + return 0; +} diff --git a/作業/unit5/narcissistic-number.exe b/作業/unit5/narcissistic-number.exe new file mode 100644 index 0000000..be8c25e Binary files /dev/null and b/作業/unit5/narcissistic-number.exe differ diff --git a/作業/unit5/narcissistic-number_claude.cpp b/作業/unit5/narcissistic-number_claude.cpp new file mode 100644 index 0000000..6f8a47b --- /dev/null +++ b/作業/unit5/narcissistic-number_claude.cpp @@ -0,0 +1,85 @@ +#include +#include +#include + +// pbwiU +int getDigitCount(int num, int base) { + int count = 0; + while (num > 0) { + count++; + num /= base; + } + return count; +} + +// ˬdO_i +int isArmstrong(int num, int base) { + int originalNum = num; + int digitCount = getDigitCount(num, base); + int sum = 0; + + while (num > 0) { + int digit = num % base; + sum += pow(digit, digitCount); + num /= base; + } + + return (sum == originalNum); +} + +// NƦrഫwir +void printNumber(int num, int base) { + if (num < 10) { + printf("%d", num); + } else { + printf("%c", 'A' + (num - 10)); + } +} + +int main() { + int count = 0; + int targetCount; + int base; + int num = 1; + + printf("ph֭Ӫi? ==> "); + scanf("%d", &targetCount); + + printf("J(<16) ==> "); + scanf("%d", &base); + + if (base < 2 || base > 16) { + printf("򩳥b215\n"); + return 1; + } + + printf("\nb%diUe%dӪiơG\n", base, targetCount); + + while (count < targetCount) { + if (isArmstrong(num, base)) { + printf("#%d\t", count + 1); + + // LXƦri + int temp = num; + int digits[32]; + int digitCount = 0; + + // ഫwi + while (temp > 0) { + digits[digitCount++] = temp % base; + temp /= base; + } + + // ϦVLXƦr + for (int i = digitCount - 1; i >= 0; i--) { + printNumber(digits[i], base); + } + printf("\n"); + + count++; + } + num++; + } + + return 0; +} diff --git a/作業/unit5/narcissistic-number_claude.exe b/作業/unit5/narcissistic-number_claude.exe new file mode 100644 index 0000000..f2355ba Binary files /dev/null and b/作業/unit5/narcissistic-number_claude.exe differ diff --git a/作業/unit5/number-conversion'.c b/作業/unit5/number-conversion'.c new file mode 100644 index 0000000..2332a27 --- /dev/null +++ b/作業/unit5/number-conversion'.c @@ -0,0 +1,43 @@ +#include +#include + +char ans[20]; + +int i ; + +void convert(int n, int b); + +void convert(int n, int b){ + if(n==0) return; + convert( n / b , b); + + if(n % b <10){ + printf("%c",n % b + '0'); + }else { + printf("%c",(n % b)-10 + 'A'); + } + +} + +int main(){ + int n , b ,count ; + while(1){ + i = 0; + printf("\nJഫQi쥿 ==> "); + scanf("%d",&n); + + if(n<=-1) break; + + printf("\nJഫ ==> "); + scanf("%d",&b); + printf("(%d)_10 = (",n); + + convert(n,b); + + printf(")_%d\n",b); + } + printf("\n{N..."); + system("pause"); + + return 0; +} diff --git a/作業/unit5/number-conversion'.exe b/作業/unit5/number-conversion'.exe new file mode 100644 index 0000000..c06ac04 Binary files /dev/null and b/作業/unit5/number-conversion'.exe differ diff --git a/作業/unit5/number-conversion.c b/作業/unit5/number-conversion.c new file mode 100644 index 0000000..c008c9f --- /dev/null +++ b/作業/unit5/number-conversion.c @@ -0,0 +1,43 @@ +#include +#include + +int ans[20], i; + +void convert(int n, int b); + +void convert(int n, int b){ + + if(n==0) return; + convert( n / b , b); +// if(n "); + scanf("%d",&n); + + if(n<=-1) break; + + printf("\nJഫ ==> "); + scanf("%d",&b); + printf("(%d)_10 = (",n); + convert(n,b); +// for(count=i+1;count<21;count++){ +// printf("%d",ans[count]); +// } + printf(")_%d\n",b); + } + printf("\n{N..."); + system("pause"); + + return 0; +} diff --git a/作業/unit5/number-conversion.exe b/作業/unit5/number-conversion.exe new file mode 100644 index 0000000..b3d4055 Binary files /dev/null and b/作業/unit5/number-conversion.exe differ diff --git a/作業/unit5/partition_integer.cpp b/作業/unit5/partition_integer.cpp new file mode 100644 index 0000000..2e9da3b --- /dev/null +++ b/作業/unit5/partition_integer.cpp @@ -0,0 +1,35 @@ +#include +#include + +void PrintPartitions(int n, int max, int* partition, int index) { + // 򥻱p + if (n == 0) { + // n 0 ɡAܧ@ؤΤ覡AXG + for (int i = 0; i < index; i++) { + printf("%d", partition[i]); + if (i < index - 1) { + printf(" "); + } + } + printf("\n"); + return; + } + + // jp + for (int i = (max > n) ? n : max; i >= 1; i--) { + partition[index] = i; + PrintPartitions(n - i, i, partition, index + 1); + } +} + +int main() { + int num; + printf("JΪ ==> "); + scanf("%d", &num); + + int* partition = (int*) calloc(num, sizeof(int)); + PrintPartitions(num, num, partition, 0); + + free(partition); + return 0; +} diff --git a/作業/unit5/partition_integer.exe b/作業/unit5/partition_integer.exe new file mode 100644 index 0000000..329a713 Binary files /dev/null and b/作業/unit5/partition_integer.exe differ diff --git a/作業/unit5/prime-factoring-array.c b/作業/unit5/prime-factoring-array.c new file mode 100644 index 0000000..b93e7f3 --- /dev/null +++ b/作業/unit5/prime-factoring-array.c @@ -0,0 +1,42 @@ +#include +#include + +void factor(int n , int i ){ + int count = 0; + + if(n==i) { + printf(" x %d",i); + return; + } + + if(n<=1) return; + + while (n % i ==0){ + count++; + n /= i; + } + + if(count>1 ) printf(" x %d^%d",i,count); + else if (count==1 ) printf(" x %d",i); + + factor(n , i+1); +} + +int main(){ + int i= 2 , n ; + printf("J@ӥƨöi]\n"); + printf("JƦr ==> "); + scanf("%d",&n); + if(n==2) { + printf("\n%d = 1 x 2",n); + }else{ + printf("\n%d = 1",n); + } + + factor(n,i); + + printf("\n"); + system("pause"); + + return 0; +} diff --git a/作業/unit5/prime-factoring-array.exe b/作業/unit5/prime-factoring-array.exe new file mode 100644 index 0000000..c09a0d1 Binary files /dev/null and b/作業/unit5/prime-factoring-array.exe differ diff --git a/作業/unit5/river_in_tower.cpp b/作業/unit5/river_in_tower.cpp new file mode 100644 index 0000000..4aa3af5 --- /dev/null +++ b/作業/unit5/river_in_tower.cpp @@ -0,0 +1,25 @@ +#include + + +void move(int n, char A, char B, char C) +{ + if (n == 1) { + + printf("L1q%cηh%c\n",A,C); + return; + } + + move(n-1,A,C,B); + + printf("L%dq%cηh%c\n",n,A,C); + move(n-1,B,A,C); +} + +int main() +{ + int n = 3; /* L` */ + move(n,'A','B','C'); /* ABBBCOάWW */ + + return 0; +} + diff --git a/作業/unit5/river_in_tower.exe b/作業/unit5/river_in_tower.exe new file mode 100644 index 0000000..87882b2 Binary files /dev/null and b/作業/unit5/river_in_tower.exe differ diff --git a/作業/unit5/try_DS5.cpp b/作業/unit5/try_DS5.cpp new file mode 100644 index 0000000..6b65f34 --- /dev/null +++ b/作業/unit5/try_DS5.cpp @@ -0,0 +1,117 @@ +#include +#include +#include + +int priority(char op) { + switch(op) { + case '+' : case '-' : return 1; + case '*' : case '/' : case '%' : return 2; + case '^' : return 3; + default : return 0; + } +} + +void printf_postfix(char str[105][10], int len) { + int i = 0; + for (i = 0; i < len; i++) { + if (str[i][0] != '0') printf("%s ", str[i]); + } + printf("\n"); +} + +double cal(char op, double p1, double p2) { + switch(op) { + case '+' : return p1 + p2; + case '-' : return p1 - p2; + case '*' : return p1 * p2; + case '/' : return p1 / p2; + case '%' : return (int)p1 % (int)p2; + case '^' : return pow(p1, p2); + } +} + +void oper(char str[105][10], int len) { + double now[105] = {0.0}; + + int L = 0, top = 0; + while (L < len) { + switch(str[L][0]) { + case '+' : case '-' : case '*' : case '/' : case '%' : case '^' : + now[top-1] = cal(str[L][0], now[top-1], now[top]); + top--; + break; + default : + now[++top] = atof(str[L]); + } + L++; + } + printf("\nB⵲G=%5f\n\n", now[top]); +} + +void infix_to_postfix(char* str) { + char infix[105][10] = {' '}, stack[105], now[10]; + + int L = 0, R = 0, top = 0, i, j, flag = 0; + while (str[L] != '\0') { + switch(str[L]) { + case '(' : + stack[++top] = str[L]; + if (str[L+1] == '-') { flag = 1; L++; } + break; + case ')' : + while (stack[top] != '(') { + infix[R++][0] = stack[top--]; + } + top--; + break; + case '+' : case '-' : case '*' : case '/' : case '%' : case '^' : + while (priority(stack[top]) >= priority(str[L])) { + infix[R++][0] = stack[top--]; + } + stack[++top] = str[L]; + if (str[L+1] == '-') { flag = 1; L++; } + break; + default : + i = 0; + while (str[L] == '.' || (str[L] >= '0' && str[L] <= '9')) { + now[i++] = str[L++]; + } + if (flag) { + infix[R][0] = '0'; infix[R+2][0] = '-'; flag = 0; + for (j = 0; j < i; j++) infix[R+1][j] = now[j]; + R += 2; + } else { + for (j = 0; j < i; j++) infix[R][j] = now[j]; + } + L--; R++; + } + L++; + } + + while (top) { + infix[R++][0] = stack[top--]; + } + + printf_postfix(infix, R); + oper(infix, R); +} + +int main() { + printf("%5f", 1+sin((-50.2+sin(3.8*20)*cos(-30-100%40))*pow(2, -2.5))*cos(123.456)); + char str[105] = {'\0'}; + while (printf("JǦ(䴩+ - * / ^ () sin() cos()B) => ")) { + scanf("%s", str); + + printf("\nǦG"); + infix_to_postfix(str); + } + return 0; +} + +/* +10+20*(50-30)/2^4-6*8 +10.5+20.8*(50.1-30.6)/2.5^4-6.6*8.2 +10-30*(-40-20)%2^4+7.5*-6 +1+sin((-50.2+sin(3.8*20)*cos(-30-100%40))*2^-2.5)*cos(123.456) +*/ + diff --git a/作業/unit5/try_DS5.exe b/作業/unit5/try_DS5.exe new file mode 100644 index 0000000..228fff4 Binary files /dev/null and b/作業/unit5/try_DS5.exe differ diff --git a/作業/unit7/DS6.cpp b/作業/unit7/DS6.cpp new file mode 100644 index 0000000..ea18903 --- /dev/null +++ b/作業/unit7/DS6.cpp @@ -0,0 +1,334 @@ +/*Notes: Ji + w={"Mary":10, "Tom":3, "Charlie":5, "Bob":6, "Dickens":20, 4:9, "z":0, "Za":12, "aZ":8} + w={10:10, 20:3, 5:5, 17:6, 23:20, 18:9, 3:0, 9:12} + w={10:10, 5:5, 9:6, 3:20, 7:9} + w={"A":10, "B":3, "Charlie":5, "Bob":6, "Dickens":20} + w={"A":6,"B":5,"C":3,"D":10} + w={"A":6,"B":5} + del w["A"] + del w["Dickens"] + del w["Mary"] + del w["aZ"] + del w + w["Mary"]=1 + w["Tom"]+=2 + w[4]? + w? +*/ + +#include /* for sscanf(), printf() */ +#include +#include /* for strstr(), strtok(), strtok_r() */ +#include + +/* wqstudentc */ +typedef struct student { + char name[20]; /* ǥͩmW */ + int score; /* ǥͦZ */ + struct student *llink; /* l쵲 */ + struct student *rlink; /* kl쵲 */ +}student; + +void show(void); /* X */ +void insert(char [], int); /* Nƥ[JGjM */ +void removing(char []); /* NƱqGjM𤤲 */ +void inorder(struct student *); /* ƥHǪkX */ +void free_all_nodes(struct student *node); +void find_newroot(void); /* jMs`I */ + +student *search_p(struct student *node); +student *search(char []); /* jM`I */ + +student *root, *ptr, *prev; + +int main(){ + char *token, key[12], line[128]; + const char *s = " ={},"; /* jŰOr */ + int value; + char *rest ,choice[3]; + + printf("Jsr媺zAw{\n"); + while (1) { + printf("\nO => "); + fgets(line,128,stdin); /* ϥgets()Ū]iHA]gets()]ŪJrƪAiɭPxsJr}CŶz */ + if (line[0]=='\n') break; /* JŦrhj */ + if (strstr(line,"{")) { /* linet"{" */ + sscanf(line,"w = {%[^}]}",line); + rest = line; + while (token = strtok_r(rest,s,&rest)) { /* strtok_r()ΪkiѨ http://bit.ly/3VcvbbZ */ + /* printf("%s\n",token); */ + if (strstr(token,":")) {/* tokent":" */ + sscanf(token,"%[^:]:%d",key,&value); + insert(key,value); +// printf("Token #%d: =%s; =%d\n",++i,key,value); + } + } + }else if (strstr(line,"del")) { + if(strcmp(line,"del w\n")==0){ + printf("LkPŪNR@ӤANRӦr(y/n) => "); + fgets(choice, sizeof(choice), stdin); + if(strcmp(choice,"y\n")==0){ + free_all_nodes(root); + root = NULL; + }else{ + printf("RҦr\n"); + } + }else{ + if(sscanf(line,"del w[%[^]]]",key)==1){ + if(strcmp(key,root->name)==0){ + // printf("Rw[%s]root`I\n",key); + find_newroot(); + // printf("sroot`Iw[%s]\n",root->name); + }else{ + removing(key); + } + } + } + }else if (strstr(line,"+=")) { /* linet"+=" */ + sscanf(line,"w[%[^]]] +=%d",key,&value); + student *modify_node; + if((modify_node = search(key)) == NULL){ /* 䤣ƫhܿ~ */ + printf("~! %s bGjM!\n", key); + }else{ + modify_node->score += value; + printf("s]w[%s]=%d\n",key,modify_node->score); + } + }else if (strstr(line,"=")) { /* linet"=" */ + sscanf(line,"w[%[^]]] = %d",key,&value); + student *add_node; + if (root == NULL){ + insert(key,value); + printf("s]w[%s]=%d\n",key,root->score); + }else{ + if((add_node = search(key)) == NULL){ /* 䤣ƫhsW */ + insert(key,value); + printf("%s bGjM!\n", key); + printf("s]w[%s]=%d\n",key,value); + }else{ + add_node->score = value; + printf("s]w[%s]=%d\n",key,add_node->score); + } + } + }else if (sscanf(line,"w[%[^]]]?",key)==1){ + student *read_node; + if((read_node = search(key)) == NULL){ /* 䤣ƫhsW */ + printf("~! %s bGjM!\n", key); + }else{ + printf("r夸w[%s]=%d\n",key,read_node->score); + } + }else if (strstr(line,"?")) show(); + else printf("ykLk{Asorry!\n"); + } + + printf("\n{Abye ~\n"); + return 0; +} + +/* BzGjMANsWƥ[JܤGjM */ +void insert(char name[], int score){ + struct student *node, *prev; + /* Ƥwsbhܿ~ */ + if (search(name) != NULL) { + printf("%s wsb!\n", name); + return; + } + ptr = (struct student *) malloc(sizeof(struct student)); + strcpy(ptr->name, name); + ptr->score = score; + ptr->llink = ptr->rlink = NULL; + if (root == NULL) /* ڸ`INULLp */ + root = ptr; + else { /* ڸ`INULLp */ + node = root; + while (node != NULL) { /* jMƴJI */ + prev = node; + if(strcmp(ptr->name, node->name) < 0) + node = node->llink; + else + node = node->rlink; + } + if (strcmp(ptr->name, prev->name) < 0) + prev->llink = ptr; + else + prev->rlink = ptr; + } +} + +/* NƱqGjM𤤲 */ +void removing(char name[]){ + student *del_node = search(name); + if (del_node == NULL) { + printf("%s bGjM!\n", name); + return; + } + + student *parent = search_p(del_node); + + // BzSl`Ip + if (del_node->llink == NULL && del_node->rlink == NULL) { + if (parent->llink == del_node) { + parent->llink = NULL; + } else { + parent->rlink = NULL; + } + }else if (del_node->llink == NULL || del_node->rlink == NULL) { // Bz@䦳l`Ip + student *child = (del_node->llink != NULL) ? del_node->llink : del_node->rlink; + if (parent->llink == del_node) { + parent->llink = child; + } else { + parent->rlink = child; + } + }else{ //Bz䦳l`Ip + if(del_node == parent->rlink){ + parent->rlink = del_node->llink; + if(del_node->llink->rlink != NULL){ //YR`Il`I٦k`Ip + student *child = del_node->llink->rlink; + printf("%s\n",child->name); + while(child->rlink!= NULL){ //k`I̩ + child = child->rlink; + printf("%s\n",child->name); + } + child->rlink = del_node->rlink; + }else parent->rlink->rlink = del_node->rlink; //Sh + + }else{ + parent->llink = del_node->llink; + if(del_node->rlink->llink != NULL){ //YR`Il`I٦`Ip + student *child = del_node->rlink->llink; + printf("%s\n",child->name); + while(child->llink!= NULL){ //䥪`I̩ + child = child->llink; + printf("%s\n",child->name); + } + child->llink = del_node->llink; + }else parent->llink->rlink = del_node->rlink; //Sh + } + } + free(del_node); /* O */ + printf("Rw[%s]\n",name); +} + +/* XơANƿXܿù */ +void show(void){ + /* P_ڸ`IO_NULL */ + if (root == NULL) { + puts("GjMOŪ!"); + return; + } +// printf("root%s\n", root->name); + printf("rܼƤxs(keyGvalue)pU\n"); + inorder(root); /* HǪkX */ +} + +/* HǪkXơAĻj覡 */ +void inorder(struct student *node ){ + if(node != NULL) { + + inorder(node->llink); + printf("%sG%d\n", node->name, node->score); + inorder(node->rlink); + } +} + +void find_newroot(){ /* jMs`I s̤j*/ + struct student *newroot_node ,*prev; + + if(root->llink == NULL && root->rlink == NULL){ + printf("Rw[%s]\n",root->name); + free(root); + root = NULL; + return; + } + + if(root->llink!=NULL){ //䥪s̤j + newroot_node = root->llink; + + while(newroot_node->rlink!=NULL){ //ڪN`I + prev = newroot_node; + newroot_node = newroot_node->rlink; + } + if(newroot_node->llink!=NULL){ //Ysڸ`I`I + prev->rlink = newroot_node->llink; + }else prev->rlink = NULL; + + if(newroot_node != root->llink ){ //Ysڸ`I쥻ڪ`I + newroot_node->llink = root->llink; + newroot_node->rlink = root->rlink; + }else{ //Ysڸ`I쥻ڪ`I + newroot_node->rlink = root->rlink; + } + printf("Rw[%s]\n",root->name); + free(root); + root = newroot_node; + }else if(root->rlink!=NULL){ //ks̤p + newroot_node = root->rlink; + + while(newroot_node->llink!=NULL){ //ڪN`I + prev = newroot_node; + newroot_node = newroot_node->llink; + } + if(newroot_node->rlink!=NULL){ //Ysڸ`Ik`I + prev->llink = newroot_node->rlink; + }else prev->llink = NULL; + + if(newroot_node != root->rlink ){ //Ysڸ`I쥻ڪk`I + newroot_node->llink = root->llink; + newroot_node->rlink = root->rlink; + }else{ //Ysڸ`I쥻ڪk`I + newroot_node->llink = root->llink; + } + printf("Rw[%s]\n",root->name); + free(root); + root = newroot_node; + } +} + +/* jMtargetҦb`I */ +struct student *search(char target[]){ + struct student *node; + node = root; + while(node != NULL){ + if (strcmp(target, node->name) == 0) + return node; + else + /* targetpثe`IAjM */ + if (strcmp(target, node->name) < 0) + node = node->llink; + else /* targetjثe`IAkjM */ + node = node->rlink; + } + return node; +} + +/* jMnode`I */ +struct student *search_p(struct student *node){ + struct student *parent; + parent = root; + while (parent != NULL) { + if (strcmp(node->name, parent->name) < 0) { + if (strcmp(node->name, parent->llink->name) == 0) + return parent; + else + parent = parent->llink; + }else { + if (strcmp(node->name, parent->rlink->name) == 0) + return parent; + else + parent = parent->rlink; + } + } + return NULL; +} + +/* jҦ`IO */ +void free_all_nodes(struct student *node) { + if (node == NULL) return; + + // j񥪤l + free_all_nodes(node->llink); + // Ajkl + free_all_nodes(node->rlink); + printf("R'w[%s]=%d'`I\n",node->name,node->score); + // ̫e`I + free(node); +} diff --git a/作業/unit7/DS6.exe b/作業/unit7/DS6.exe new file mode 100644 index 0000000..7f1f1b8 Binary files /dev/null and b/作業/unit7/DS6.exe differ diff --git a/作業/unit7/Threaded Binary Tree.cpp b/作業/unit7/Threaded Binary Tree.cpp new file mode 100644 index 0000000..8be507c --- /dev/null +++ b/作業/unit7/Threaded Binary Tree.cpp @@ -0,0 +1,454 @@ +/*Notes: Ji + w={"Mary":10, "Tom":3, "Charlie":5, "Bob":6, "Dickens":20, 4:9, "z":0, "Za":12, "aZ":8} + w={10:10, 20:3, 5:5, 17:6, 23:20, 18:9, 3:0, 9:12} + w={10:10, 5:5, 9:6, 3:20, 7:9} + w={"A":10, "B":3, "C":5, "D":20 ,"E":30 } + w={"D":10, "C":3, "B":5, "A":6} + del w["A"] + del w["Dickens"] + del w["Mary"] + del w["aZ"] + del w + w={"B":3, "A":10} + w["A"]=10 + w["B"]=20 + w["Tom"]+=2 + w[4]? + w? +*/ + +#include /* for sscanf(), printf() */ +#include +#include /* for strstr(), strtok(), strtok_r() */ +#include + +/* wqdictc */ +typedef struct dict { /* ޽uGjM`IƵcA@r */ + char key[20]; /* Ӹ`Iuv(key)e */ + int value; /* uvuȡv(value)e */ + struct dict *llink; /* VlکΤ޽uγ~ */ + struct dict *rlink; /* VklکΤ޽uγ~ */ + int lbit; /* llink O_` */ + int rbit; /* rlink O_` */ + } dict; + +void show(void); /* X */ +void insert(char [], int); /* Nƥ[JGjM */ +void insert_left(struct dict *s, struct dict *t); +void insert_right(struct dict *s, struct dict *t); +void removing(char []); /* NƱqGjM𤤲 */ +void inorder(struct dict *); /* ƥHǪkX */ +void free_all_nodes(struct dict *node); + +dict *search_p(struct dict *node); +dict *search(char []); /* jM`I */ +dict *insuc(dict *ptr); + +dict *root = NULL, *ptr, *prev ,*head = NULL ; + +int main(){ + + head = (dict *)malloc(sizeof(dict)); + if (head == NULL) { + printf("OtѡI\n"); + return 1; + } + head->lbit = head->rbit = 1; + head->rlink = head; + head->llink = root; + + char *token, key[12], line[128]; + const char *s = " ={},"; /* jŰOr */ + int value; + char *rest ,option; + + printf("Jsr媺zAw{\n"); + while (1) { + printf("\nO => "); + fgets(line,128,stdin); /* ϥgets()Ū]iHA]gets()]ŪJrƪAiɭPxsJr}CŶz */ + if (line[0]=='\n') break; /* JŦrhj */ + if (strstr(line,"{")) { /* linet"{" */ + sscanf(line,"w = {%[^}]}",line); + rest = line; + while (token = strtok_r(rest,s,&rest)) { /* strtok_r()ΪkiѨ http://bit.ly/3VcvbbZ */ + /* printf("%s\n",token); */ + if (strstr(token,":")) {/* tokent":" */ + sscanf(token,"%[^:]:%d",key,&value); +// printf("key=%s,value=%d\n",key,value); + insert(key,value); + } + } + }else if (strstr(line,"del")) { + if(sscanf(line,"del w[%[^]]]",key)){ + removing(key); + printf("\nsroot`Iw[%s]\n",root->key); + }else{ + printf("LkPŪNR@ӤANRӦr? (y/n) => "); + scanf("%c",&option); + fflush(stdin); + if (option == 'y' || option == 'Y') { + free_all_nodes(root); + root = NULL; + }else{ + printf("RҦr\n"); + } + } + }else if (strstr(line,"+=")) { /* linet"+=" */ + sscanf(line,"w[%[^]]] +=%d",key,&value); + dict *modify_node; + if((modify_node = search(key)) == NULL){ /* 䤣ƫhܿ~ */ + printf("~! %s bGjM!\n", key); + }else{ + modify_node->value += value; + printf("s]w[%s]=%d\n",key,modify_node->value); + } + }else if (strstr(line,"=")) { /* linet"=" */ + sscanf(line,"w[%[^]]] = %d",key,&value); + dict *add_node; + if (root == NULL){ + insert(key,value); + printf("s]w[%s]=%d\n",key,root->value); + }else{ + if((add_node = search(key)) == NULL){ /* 䤣ƫhsW */ + insert(key,value); + printf("%s bGjM!\n", key); + printf("s]w[%s]=%d\n",key,value); + }else{ + add_node->value = value; + printf("s]w[%s]=%d\n",key,add_node->value); + } + } + }else if (sscanf(line,"w[%[^]]]?",key)==1){ + dict *read_node; + if((read_node = search(key)) == NULL){ /* 䤣ƫhsW */ + printf("~! %s bGjM!\n", key); + }else{ + printf("r夸w[%s]=%d\n",key,read_node->value); + } + }else if (strstr(line,"?")) show(); + else printf("ykLk{Asorry!\n"); + } + printf("\n{ARҦ`IAbye ~\n"); + free_all_nodes(root); + free(head); + + return 0; +} + +void insert(char key[], int value) { + // ˬdO_wsb + if (search(key) != NULL) { + printf("%s wsb!\n", key); + return; + } + + // إ߷s`I + ptr = (struct dict *) malloc(sizeof(struct dict)); + strcpy(ptr->key, key); + ptr->value = value; + ptr->lbit = ptr->rbit = 0; + ptr->llink = ptr->rlink = head; // TlƬ NULL + + // Bzž𪺱p + if (root == NULL) { + root = ptr; + head->llink = root; // head 쵲V root + root->llink = head; // root V head + root->rlink = head; // root kV head + return; + } + + // M䴡Jm + dict *current = root; + dict *parent; + + while (1) { + parent = current; + if (strcmp(ptr->key, current->key) < 0) { // + if (current->lbit == 0) { // 촡Jm + insert_left(current, ptr); + break; + } + current = current->llink; + }else { // k + if (current->rbit == 0) { // 촡Jm + insert_right(current, ptr); + break; + } + current = current->rlink; + } + } +} + +// bY`I贡Js`I +void insert_left(struct dict *s, struct dict *t) { + t->llink = s->llink; // s`Il`IV`Il`I + t->rlink = s; // s`Ikl`IV`I + t->lbit = s->lbit; // s`I~ӭ`I줸 + t->rbit = 0; // ]wk줸޽u + s->llink = t; // `Il`IVs`I + s->lbit = 1; // ]w줸`쵲 + + if (t->lbit == 1) { + dict *p = t->llink; + while (p->rbit == 1) + p = p->rlink; + p->rlink = t; + } +} + +// bY`Ik贡Js`I +void insert_right(struct dict *s, struct dict *t) { + t->rlink = s->rlink; // s`Ikl`IV`Ikl`I + t->rbit = s->rbit; // s`I~ӭ`Ik줸 + t->llink = s; // s`Il`IV`I + t->lbit = 0; // ]w줸޽u + s->rlink = t; // `Ikl`IVs`I + s->rbit = 1; // ]wk줸`쵲 + + // MeX`Içs޽u + if (t->rbit == 1) { + dict *p = t->rlink; + while (p->lbit == 1) + p = p->llink; + p->llink = t; + } +} + +/* NƱqGjM𤤲 */ +void removing(char key[]) { + dict *del_node = search(key); + if (del_node == NULL) { + printf("%s bGjM!\n", key); + return; + } + + dict *parent = search_p(del_node); + + //Y`I + if (del_node->lbit == 0 && del_node->rbit == 0) { + if (parent == NULL) { // ROڸ`I + root = NULL; + head->llink = head; + } else if (parent->llink == del_node) { + parent->llink = del_node->llink; // ~ӥ޽u + parent->lbit = 0; + } else { + parent->rlink = del_node->rlink; // ~ӥk޽u + parent->rbit = 0; + } + free(del_node); + } + + // Yul + else if (del_node->lbit == 1 && del_node->rbit == 0) { + dict *left_child = del_node->llink; + dict *successor = del_node->rlink; // Os~`I + + // 쥪l𪺳̥k`I + dict *rightmost = left_child; + while (rightmost->rbit == 1) { + rightmost = rightmost->rlink; + } + + // ss + rightmost->rlink = successor; + if (parent == NULL) { + root = left_child; + head->llink = root; + } else if (parent->llink == del_node) { + parent->llink = left_child; + } else { + parent->rlink = left_child; + } + free(del_node); + } + + // Yukl + else if (del_node->lbit == 0 && del_node->rbit == 1) { + dict *right_child = del_node->rlink; + dict *predecessor = del_node->llink; // OseX`I + + // kl𪺳̥`I + dict *leftmost = right_child; + while (leftmost->lbit == 1) { + leftmost = leftmost->llink; + } + + // ss + leftmost->llink = predecessor; + if (parent == NULL) { + root = right_child; + head->llink = root; + } else if (parent->llink == del_node) { + parent->llink = right_child; + } else { + parent->rlink = right_child; + } + free(del_node); + } + + // YӤl + else { + // 䥪l𤤳̤j`I + dict *predecessor = del_node->llink; + dict *pred_parent = del_node; + + while (predecessor->rbit == 1) { + pred_parent = predecessor; + predecessor = predecessor->rlink; + } + + // ƻs~`IƾڨQR`I + strcpy(del_node->key, predecessor->key); + del_node->value = predecessor->value; + + // ~`I + if (pred_parent == del_node) { + del_node->llink = predecessor->llink; + del_node->lbit = predecessor->lbit; + } else { + pred_parent->rlink = predecessor->rlink; + pred_parent->rbit = predecessor->rbit; + } + + free(predecessor); + } + + printf("Rw[%s]\n", key); +} + +void show(void) { + if (root == NULL) { + puts("GjMOŪ!"); + return; + } + printf("rܼƤxs(keyGvalue)pU\n"); + inorder(root); +} + +// ϥΤ޽uSʶi椤ǹM +void inorder(dict *root) { + + if (root == NULL) { + printf("GjMOŪ!\n"); + return; + } + + dict *current = root; + + // ̥䪺`I + while (current->lbit == 1) { + current = current->llink; + } + + while (1) { + + printf("%sG%d\n", current->key, current->value); + + current = insuc(current); + + if (current == NULL || current == head) { + break; + } + } +} + +// M䤤ǫ~`I +dict *insuc(dict *ptr) { + if (ptr == NULL) return NULL; + + // pGkl + if (ptr->rbit == 1) { + // ܥkl + ptr = ptr->rlink; + // M@줣A + while (ptr->lbit == 1) { + ptr = ptr->llink; + } + return ptr; + } + // pGSklAh^k޽uV`I + return ptr->rlink; +} + +/* jMtargetҦb`I */ +struct dict *search(char target[]) { + struct dict *node = root; + + while (node != NULL && node != head) { // [J head ˬdHY`I + int cmp = strcmp(target, node->key); + if (cmp == 0) { + return node; // ؼи`I + } else if (cmp < 0) { // target pثe`IAjM + if (node->lbit == 0) { // pGO޽u + return NULL; // N䤣ؼ + } + node = node->llink; + } else { // target jثe`IAkjM + if (node->rbit == 0) { // pGkO޽u + return NULL; // N䤣ؼ + } + node = node->rlink; + } + } + return NULL; // 䤣ؼ +} + +/* jMnode`I */ +struct dict *search_p(struct dict *node) { + if (node == NULL || node == root) { + return NULL; + } + + struct dict *current = root; + struct dict *parent = NULL; + + while (current != NULL && current != head) { + int cmp = strcmp(node->key, current->key); + + if (cmp == 0) { // ؼи`IA^`I + return parent; + } + + parent = current; // s`I + + if (cmp < 0) { // ؼЦbl + if (current->lbit == 0) { // pGO޽u + return NULL; // 䤣ؼ + } + current = current->llink; + } else { // ؼЦbkl + if (current->rbit == 0) { // pGO޽u + return NULL; // 䤣ؼ + } + current = current->rlink; + } + } + + return NULL; // Sؼи`I +} + +// Ҧ`I +void free_all_nodes(struct dict *root) { + if (root == NULL) { + return; + } + + dict *current = root; + dict *temp; + + // ̥䪺`I + while (current->lbit == 1) { + current = current->llink; + } + + // ϥΤ޽uSʹM`I + while (current != head) { + temp = current; + current = insuc(current); + printf("R'w[%s]=%d'`I\n", temp->key, temp->value); + free(temp); + } + root = NULL; +} diff --git a/作業/unit7/Threaded Binary Tree.exe b/作業/unit7/Threaded Binary Tree.exe new file mode 100644 index 0000000..96f6a7d Binary files /dev/null and b/作業/unit7/Threaded Binary Tree.exe differ diff --git a/作業/unit7/Threaded Binary Tree_bit.cpp b/作業/unit7/Threaded Binary Tree_bit.cpp new file mode 100644 index 0000000..a3c321c --- /dev/null +++ b/作業/unit7/Threaded Binary Tree_bit.cpp @@ -0,0 +1,524 @@ +/*Notes: Ji + w={"Mary":10, "Tom":3, "Charlie":5, "Bob":6, "Dickens":20, 4:9, "z":0, "Za":12, "aZ":8} + w={10:10, 20:3, 5:5, 17:6, 23:20, 18:9, 3:0, 9:12} + w={10:10, 5:5, 9:6, 3:20, 7:9} + w={"A":10, "B":3, "C":5, "Bob":6, "D":20} + w={"D":10, "C":3, "B":5, "A":6} + del w["A"] + del w["Dickens"] + del w["Mary"] + del w["aZ"] + del w + w={"B":3, "A":10} + w["A"]=10 + w["B"]=20 + w["Tom"]+=2 + w[4]? + w? +*/ + +#include /* for sscanf(), printf() */ +#include +#include /* for strstr(), strtok(), strtok_r() */ +#include + +/* wqdictc */ +typedef struct dict { /* ޽uGjM`IƵcA@r */ + char key[20]; /* Ӹ`Iuv(key)e */ + int value; /* uvuȡv(value)e */ + struct dict *llink; /* VlکΤ޽uγ~ */ + struct dict *rlink; /* VklکΤ޽uγ~ */ + int lbit; /* llink O_` */ + int rbit; /* rlink O_` */ + } dict; + +void show(void); /* X */ +void insert(char [], int); /* Nƥ[JGjM */ +void insert_left(struct dict *s, struct dict *t); +void insert_right(struct dict *s, struct dict *t); +void removing(char []); /* NƱqGjM𤤲 */ +void inorder(struct dict *); /* ƥHǪkX */ +void free_all_nodes(struct dict *node); +void find_newroot(void); /* jMs`I */ + +dict *search_p(struct dict *node); +dict *search(char []); /* jM`I */ +dict *insuc(dict *ptr); + +dict *root = NULL, *ptr, *prev ,*head = NULL ; + +int main(){ + + head = (dict *)malloc(sizeof(dict)); + if (head == NULL) { + printf("OtѡI\n"); + return 1; + } + head->lbit = head->rbit = 1; + head->rlink = head; + head->llink = root; + + char *token, key[12], line[128]; + const char *s = " ={},"; /* jŰOr */ + int value; + char *rest ,option; + + printf("Jsr媺zAw{\n"); + while (1) { + printf("\nO => "); + fgets(line,128,stdin); /* ϥgets()Ū]iHA]gets()]ŪJrƪAiɭPxsJr}CŶz */ + if (line[0]=='\n') break; /* JŦrhj */ + if (strstr(line,"{")) { /* linet"{" */ + sscanf(line,"w = {%[^}]}",line); + rest = line; + while (token = strtok_r(rest,s,&rest)) { /* strtok_r()ΪkiѨ http://bit.ly/3VcvbbZ */ + /* printf("%s\n",token); */ + if (strstr(token,":")) {/* tokent":" */ + sscanf(token,"%[^:]:%d",key,&value); +// printf("key=%s,value=%d\n",key,value); + insert(key,value); +// printf("Token #%d: =%s; =%d\n",++i,key,value); + } + } + }else if (strstr(line,"del")) { + if(sscanf(line,"del w[%[^]]]",key)){ + if(strcmp(key,root->key)==0){ +// printf("Rw[%s]root`I\n",key); + find_newroot(); +// printf("sroot`Iw[%s]\n",root->key); + }else removing(key); + }else{ + printf("LkPŪNR@ӤANRӦr? (y/n) => "); + scanf("%c",&option); + fflush(stdin); + if (option == 'y' || option == 'Y') { + free_all_nodes(root); + root = NULL; + }else{ + printf("RҦr\n"); + } + } + }else if (strstr(line,"+=")) { /* linet"+=" */ + sscanf(line,"w[%[^]]] +=%d",key,&value); + dict *modify_node; + if((modify_node = search(key)) == NULL){ /* 䤣ƫhܿ~ */ + printf("~! %s bGjM!\n", key); + }else{ + modify_node->value += value; + printf("s]w[%s]=%d\n",key,modify_node->value); + } + }else if (strstr(line,"=")) { /* linet"=" */ + sscanf(line,"w[%[^]]] = %d",key,&value); + dict *add_node; + if (root == NULL){ + insert(key,value); + printf("s]w[%s]=%d\n",key,root->value); + }else{ + if((add_node = search(key)) == NULL){ /* 䤣ƫhsW */ + insert(key,value); + printf("%s bGjM!\n", key); + printf("s]w[%s]=%d\n",key,value); + }else{ + add_node->value = value; + printf("s]w[%s]=%d\n",key,add_node->value); + } + } + }else if (sscanf(line,"w[%[^]]]?",key)==1){ + dict *read_node; + if((read_node = search(key)) == NULL){ /* 䤣ƫhsW */ + printf("~! %s bGjM!\n", key); + }else{ + printf("r夸w[%s]=%d\n",key,read_node->value); + } + }else if (strstr(line,"?")) show(); + else printf("ykLk{Asorry!\n"); + } + printf("\n{ARҦ`IAbye ~\n"); + free_all_nodes(root); + free(head); + + return 0; +} + +// ק᪺insert +void insert(char key[], int value) { + // ˬdO_wsb + if (search(key) != NULL) { + printf("%s wsb!\n", key); + return; + } + + // إ߷s`I + ptr = (struct dict *) malloc(sizeof(struct dict)); + strcpy(ptr->key, key); + ptr->value = value; + ptr->lbit = ptr->rbit = 0; + ptr->llink = ptr->rlink = NULL; // TlƬ NULL + + // Bzž𪺱p + if (root == NULL) { + root = ptr; + head->llink = root; // head 쵲V root + root->llink = head; // root V head + root->rlink = head; // root kV head + return; + } + + // M䴡Jm + dict *current = root; + dict *parent; + + while (1) { + parent = current; + if (strcmp(ptr->key, current->key) < 0) { // + if (current->lbit == 0) { // 촡Jm + insert_left(current, ptr); + break; + } + current = current->llink; + }else { // k + if (current->rbit == 0) { // 촡Jm + insert_right(current, ptr); + break; + } + current = current->rlink; + } + } +} + +// bY`I贡Js`I +void insert_left(struct dict *s, struct dict *t) { + t->llink = s->llink; // s`Il`IV`Il`I + t->rlink = s; // s`Ikl`IV`I + t->lbit = s->lbit; // s`I~ӭ`I줸 + t->rbit = 0; // ]wk줸 + s->llink = t; // `Il`IVs`I + s->lbit = 1; // ]w줸`쵲 + + if (t->lbit == 1) { + dict *p = t->llink; + while (p->rbit == 1) + p = p->rlink; + p->rlink = t; + } +} + +// bY`Ik贡Js`I]ھڹϤҥܡ^ +void insert_right(struct dict *s, struct dict *t) { + t->rlink = s->rlink; // s`Ikl`IV`Ikl`I + t->rbit = s->rbit; // s`I~ӭ`Ik줸 + t->llink = s; // s`Il`IV`I + t->lbit = 0; // ]w줸 + s->rlink = t; // `Ikl`IVs`I + s->rbit = 1; // ]wk줸`쵲 + + // MeX`Içs޽u + if (t->rbit == 1) { + dict *p = t->rlink; + while (p->lbit == 1) + p = p->llink; + p->llink = t; + } +} + +/* NƱqGjM𤤲 */ +void removing(char key[]) { + dict *del_node = search(key); + if (del_node == NULL) { + printf("%s bGjM!\n", key); + return; + } + + dict *parent = search_p(del_node); + + // Case 1: `I (Sl`I) + if (del_node->lbit == 0 && del_node->rbit == 0) { + if (parent == NULL) { // ROڸ`I + root = NULL; + head->llink = head; + } else if (parent->llink == del_node) { + parent->llink = del_node->llink; // ~ӥ + parent->lbit = 0; + } else { + parent->rlink = del_node->rlink; // ~ӥk + parent->rbit = 0; + } + free(del_node); + } + + // Case 2: ul + else if (del_node->lbit == 1 && del_node->rbit == 0) { + dict *left_child = del_node->llink; + dict *successor = del_node->rlink; // Os~`I + + // 쥪l𪺳̥k`I + dict *rightmost = left_child; + while (rightmost->rbit == 1) { + rightmost = rightmost->rlink; + } + + // ss + rightmost->rlink = successor; + if (parent == NULL) { + root = left_child; + head->llink = root; + } else if (parent->llink == del_node) { + parent->llink = left_child; + } else { + parent->rlink = left_child; + } + free(del_node); + } + + // Case 3: ukl + else if (del_node->lbit == 0 && del_node->rbit == 1) { + dict *right_child = del_node->rlink; + dict *predecessor = del_node->llink; // OseX`I + + // kl𪺳̥`I + dict *leftmost = right_child; + while (leftmost->lbit == 1) { + leftmost = leftmost->llink; + } + + // ss + leftmost->llink = predecessor; + if (parent == NULL) { + root = right_child; + head->llink = root; + } else if (parent->llink == del_node) { + parent->llink = right_child; + } else { + parent->rlink = right_child; + } + free(del_node); + } + + // Case 4: Ӥl + else { + // 줤ǫ~`I]kl𤤳̤p`I^ + dict *successor = del_node->rlink; + dict *succ_parent = del_node; + + while (successor->lbit == 1) { + succ_parent = successor; + successor = successor->llink; + } + + // ƻs~`IƾڨQR`I + strcpy(del_node->key, successor->key); + del_node->value = successor->value; + + // ~`I + if (succ_parent == del_node) { + del_node->rlink = successor->rlink; + del_node->rbit = successor->rbit; + } else { + succ_parent->llink = successor->llink; + succ_parent->lbit = successor->lbit; + } + + free(successor); + } + + printf("Rw[%s]\n", key); +} + +void find_newroot() { + struct dict *newroot_node, *prev; + + if(root->lbit == 0 && root->rbit == 0 ){ + printf("Rw[%s]\n", root->key); + free(root); + root = NULL; + return; + } + + if (root->lbit == 1) { // lA䥪l𤤳̤j`I + newroot_node = root->llink; + prev = root; + + // 쥪l𤤳̤j`I + while (newroot_node->rbit == 1) { + prev = newroot_node; + newroot_node = newroot_node->rlink; + } + + // Bzsڸ`Is + if (newroot_node != root->llink) { + // pGsڤOڪl`I + prev->rbit = newroot_node->rbit; // ~ӷsڪkA + prev->rlink = newroot_node->rlink; // ~ӷsڪk + + newroot_node->lbit = root->lbit; // ~ӭڪЪA + newroot_node->llink = root->llink; // ~ӭڪl + newroot_node->rbit = root->rbit; // ~ӭڪkЪA + newroot_node->rlink = root->rlink; // ~ӭڪkl + } else { + // pGsڬOڪl`I + newroot_node->rbit = root->rbit; // ~ӭڪkЪA + newroot_node->rlink = root->rlink; // ~ӭڪkl + } + + } else if (root->rbit == 1) { // klAkl𤤳̤p`I + newroot_node = root->rlink; + prev = root; + + // kl𤤳̤p`I + while (newroot_node->lbit == 1) { + prev = newroot_node; + newroot_node = newroot_node->llink; + } + + // Bzsڸ`Is + if (newroot_node != root->rlink) { + // pGsڤOڪkl`I + prev->lbit = newroot_node->lbit; // ~ӷsڪA + prev->llink = newroot_node->llink; // ~ӷsڪ + + newroot_node->lbit = root->lbit; // ~ӭڪЪA + newroot_node->llink = root->llink; // ~ӭڪl + newroot_node->rbit = root->rbit; // ~ӭڪkЪA + newroot_node->rlink = root->rlink; // ~ӭڪkl + } else { + // pGsڬOڪkl`I + newroot_node->lbit = root->lbit; // ~ӭڪЪA + newroot_node->llink = root->llink; // ~ӭڪl + } + } + + // sY`Is + if(root != NULL){ + head->llink = newroot_node; + printf("Rw[%s]\n", root->key); + free(root); + root = newroot_node; + } +} + +void show(void) { + if (root == NULL) { + puts("GjMOŪ!"); + return; + } + printf("rܼƤxs(keyGvalue)pU\n"); + inorder(root); +} + +// ϥΤ޽uSʶi椤ǹM +void inorder(dict *root) { + if (root == NULL) { + printf("GjMOŪ!\n"); + return; + } + + dict *current = root; + // ̥䪺`I + while (current->lbit == 1) { + current = current->llink; + } + + // ϥΤ޽uSʹM + while (current != head) { + printf("%sG%d\n", current->key, current->value); + current = insuc(current); + } +} + +// M䤤ǫ~`I +dict *insuc(dict *ptr) { + dict *current; + + // YkЬO]rbit = 0^A^k + if (ptr->rbit == 0) { + return ptr->rlink; + } + + // _hk@BA@F̥䪺`I + current = ptr->rlink; + while (current->lbit == 1) { + current = current->llink; + } + return current; +} + +/* jMtargetҦb`I */ +struct dict *search(char target[]) { + struct dict *node = root; + + while (node != NULL && node != head) { // [J head ˬdHY`I + int cmp = strcmp(target, node->key); + if (cmp == 0) { + return node; // ؼи`I + } else if (cmp < 0) { // target pثe`IAjM + if (node->lbit == 0) { // pGO + return NULL; // N䤣ؼ + } + node = node->llink; + } else { // target jثe`IAkjM + if (node->rbit == 0) { // pGkO + return NULL; // N䤣ؼ + } + node = node->rlink; + } + } + return NULL; // 䤣ؼ +} + +/* jMnode`I */ +struct dict *search_p(struct dict *node) { + if (node == NULL || node == root) { + return NULL; + } + + struct dict *current = root; + struct dict *parent = NULL; + + while (current != NULL && current != head) { + int cmp = strcmp(node->key, current->key); + + if (cmp == 0) { // ؼи`IA^`I + return parent; + } + + parent = current; // s`I + + if (cmp < 0) { // ؼЦbl + if (current->lbit == 0) { // pGO + return NULL; // 䤣ؼ + } + current = current->llink; + } else { // ؼЦbkl + if (current->rbit == 0) { // pGO + return NULL; // 䤣ؼ + } + current = current->rlink; + } + } + + return NULL; // Sؼи`I +} + +// Ҧ`IDj +void free_all_nodes(struct dict *root) { + if (root == NULL) { + return; + } + + dict *current = root; + dict *temp; + + // ̥䪺`I + while (current->lbit == 1) { + current = current->llink; + } + + // ϥΤ޽uSʹM`I + while (current != head) { + temp = current; + current = insuc(current); + printf("R'w[%s]=%d'`I\n", temp->key, temp->value); + free(temp); + } + root = NULL; +} diff --git a/作業/unit7/Threaded Binary Tree_bit.exe b/作業/unit7/Threaded Binary Tree_bit.exe new file mode 100644 index 0000000..e3fd86e Binary files /dev/null and b/作業/unit7/Threaded Binary Tree_bit.exe differ diff --git a/作業/unit7/Threaded Binary Tree_stack.cpp b/作業/unit7/Threaded Binary Tree_stack.cpp new file mode 100644 index 0000000..6d6836c --- /dev/null +++ b/作業/unit7/Threaded Binary Tree_stack.cpp @@ -0,0 +1,416 @@ +/*Notes: Ji + w={"Mary":10, "Tom":3, "Charlie":5, "Bob":6, "Dickens":20, 4:9, "z":0, "Za":12, "aZ":8} + w={10:10, 20:3, 5:5, 17:6, 23:20, 18:9, 3:0, 9:12} + w={10:10, 5:5, 9:6, 3:20, 7:9} + w={"A":10, "B":3, "Charlie":5, "Bob":6, "Dickens":20} + w={"D":10, "C":3, "B":5, "A":6} + del w["A"] + del w["Dickens"] + del w["Mary"] + del w["aZ"] + del w + w["Mary"]=1 + w["Tom"]+=2 + w[4]? + w? +*/ + +#include /* for sscanf(), printf() */ +#include +#include /* for strstr(), strtok(), strtok_r() */ +#include +#define MAX_STACK 100 // wq|jp + +/* wqdictc */ +typedef struct dict { /* ޽uGjM`IƵcA@r */ + char key[20]; /* Ӹ`Iuv(key)e */ + int value; /* uvuȡv(value)e */ + struct dict *llink; /* VlکΤ޽uγ~ */ + struct dict *rlink; /* VklکΤ޽uγ~ */ + int lbit; /* llink O_` */ + int rbit; /* rlink O_` */ + } dict; + +// wq|c +typedef struct { + dict* data[MAX_STACK]; + int top; +} Stack; + +void show(void); /* X */ +void insert(char [], int); /* Nƥ[JGjM */ +void removing(char []); /* NƱqGjM𤤲 */ +void inorder(struct dict *); /* ƥHǪkX */ +void free_all_nodes(struct dict *node); +void find_newroot(void); /* jMs`I */ + +dict *search_p(struct dict *node); +dict *search(char []); /* jM`I */ + +dict *root = NULL, *ptr, *prev ,*head = NULL ; + +// |ާ@ +void initStack(Stack *s) { + s->top = -1; +} + +int isEmpty(Stack *s) { + return s->top == -1; +} + +int isFull(Stack *s) { + return s->top == MAX_STACK - 1; +} + +void push(Stack *s, dict* node) { + if (!isFull(s)) { + s->data[++(s->top)] = node; + } +} + +dict* pop(Stack *s) { + if (!isEmpty(s)) { + return s->data[(s->top)--]; + } + return NULL; +} + +void inorder(struct dict *root) { + if (root == NULL) { + return; + } + + Stack stack; + initStack(&stack); + dict *current = root; + + while (current != NULL || !isEmpty(&stack)) { + // NҦl`IJ| + while (current != NULL) { + push(&stack, current); + current = current->llink; + } + + // q|X`IóBz + current = pop(&stack); + if (current != NULL) { + printf("%sG%d\n", current->key, current->value); + // ʨkl`I + current = current->rlink; + } + } +} + +// Dj覡Ҧ`I +void free_all_nodes(struct dict *root) { + if (root == NULL) { + return; + } + + Stack stack; + initStack(&stack); + dict *current = root; + dict *last_processed = NULL; + + while (current != NULL || !isEmpty(&stack)) { + if (current != NULL) { + push(&stack, current); + current = current->llink; + } else { + dict *peek = stack.data[stack.top]; + + // pGkl`IsbB|Bz + if (peek->rlink != NULL && last_processed != peek->rlink) { + current = peek->rlink; + } else { + peek = pop(&stack); + printf("R'w[%s]=%d'`I\n", peek->key, peek->value); + last_processed = peek; + free(peek); + current = NULL; + } + } + } +} + +void show(void) { + if (root == NULL) { + puts("GjMOŪ!"); + return; + } + printf("rܼƤxs(keyGvalue)pU\n"); + inorder(root); +} + +int main(){ + + head = (dict *)malloc(sizeof(dict)); + if (head == NULL) { + printf("OtѡI\n"); + return 1; + } + head->lbit = head->rbit = 1; + head->rlink = head; + head->llink = root; + + char *token, key[12], line[128]; + const char *s = " ={},"; /* jŰOr */ + int value; + char *rest ,option; + + + printf("Jsr媺zAw{\n"); + while (1) { + printf("\nO => "); + fgets(line,128,stdin); /* ϥgets()Ū]iHA]gets()]ŪJrƪAiɭPxsJr}CŶz */ + if (line[0]=='\n') break; /* JŦrhj */ + if (strstr(line,"{")) { /* linet"{" */ + sscanf(line,"w = {%[^}]}",line); + rest = line; + while (token = strtok_r(rest,s,&rest)) { /* strtok_r()ΪkiѨ http://bit.ly/3VcvbbZ */ + /* printf("%s\n",token); */ + if (strstr(token,":")) {/* tokent":" */ + sscanf(token,"%[^:]:%d",key,&value); + insert(key,value); +// printf("Token #%d: =%s; =%d\n",++i,key,value); + } + } + }else if (strstr(line,"del")) { + if(sscanf(line,"del w[%[^]]]",key)){ + if(strcmp(key,root->key)==0){ +// printf("Rw[%s]root`I\n",key); + find_newroot(); +// printf("sroot`Iw[%s]\n",root->key); + }else removing(key); + }else{ + printf("LkPŪNR@ӤANRӦr? (y/n) => "); + scanf("%c",&option); + fflush(stdin); + if (option == 'y' || option == 'Y') { + free_all_nodes(root); + root = NULL; + }else{ + printf("RҦr\n"); + } + } + }else if (strstr(line,"+=")) { /* linet"+=" */ + sscanf(line,"w[%[^]]] +=%d",key,&value); + dict *modify_node; + if((modify_node = search(key)) == NULL){ /* 䤣ƫhܿ~ */ + printf("~! %s bGjM!\n", key); + }else{ + modify_node->value += value; + printf("s]w[%s]=%d\n",key,modify_node->value); + } + }else if (strstr(line,"=")) { /* linet"=" */ + sscanf(line,"w[%[^]]] = %d",key,&value); + dict *add_node; + if (root == NULL){ + insert(key,value); + printf("s]w[%s]=%d\n",key,root->value); + }else{ + if((add_node = search(key)) == NULL){ /* 䤣ƫhsW */ + insert(key,value); + printf("%s bGjM!\n", key); + printf("s]w[%s]=%d\n",key,value); + }else{ + add_node->value = value; + printf("s]w[%s]=%d\n",key,add_node->value); + } + } + }else if (sscanf(line,"w[%[^]]]?",key)==1){ + dict *read_node; + if((read_node = search(key)) == NULL){ /* 䤣ƫhsW */ + printf("~! %s bGjM!\n", key); + }else{ + printf("r夸w[%s]=%d\n",key,read_node->value); + } + }else if (strstr(line,"?")) show(); + else printf("ykLk{Asorry!\n"); + } + printf("\n{ARҦ`IAbye ~\n"); + free_all_nodes(root); + free(head); + + return 0; +} + +/* BzGjMANsWƥ[JܤGjM */ +void insert(char key[], int value){ + struct dict *node, *prev; + /* Ƥwsbhܿ~ */ + if (search(key) != NULL) { + printf("%s wsb!\n", key); + return; + } + ptr = (struct dict *) malloc(sizeof(struct dict)); + strcpy(ptr->key, key); + ptr->value = value; + ptr->llink = ptr->rlink = NULL; + ptr->lbit = ptr->rbit = 0; + if (root == NULL){/* ڸ`INULLp */ + root = ptr; + ptr->lbit = ptr->rbit = 1; + }else{ /* ڸ`INULLp */ + node = root; + while (node != NULL) { /* jMƴJI */ + prev = node; + if(strcmp(ptr->key, node->key) < 0) + node = node->llink; + else + node = node->rlink; + } + if (strcmp(ptr->key, prev->key) < 0){ + prev->llink = ptr; + prev->lbit = 1; + }else{ + prev->rlink = ptr; + prev->rbit = 1; + } + } +} + +/* NƱqGjM𤤲 */ +void removing(char key[]){ + dict *del_node = search(key); + if (del_node == NULL) { + printf("%s bGjM!\n", key); + return; + } + + dict *parent = search_p(del_node); + + // BzSl`Ip + if (del_node->llink == NULL && del_node->rlink == NULL) { + if (parent == NULL) { // ROڸ`I + root = NULL; + } else if (parent->llink == del_node) { + parent->llink = NULL; + } else { + parent->rlink = NULL; + } + }else if (del_node->llink == NULL || del_node->rlink == NULL) { // Bz@䦳l`Ip + dict *child = (del_node->llink != NULL) ? del_node->llink : del_node->rlink; + + if (parent == NULL) { //ROڸ`I + root = child; + } else if (parent->llink == del_node) { + parent->llink = child; + } else { + parent->rlink = child; + } + }else{ //Bz䦳l`Ip + if(del_node == parent->rlink){ + parent->rlink = del_node->llink; + if(del_node->llink->rlink != NULL){ //YR`Il`I٦k`Ip + dict *child = del_node->llink->rlink; + printf("%s\n",child->key); + while(child->rlink!= NULL){ //k`I̩ + child = child->rlink; + printf("%s\n",child->key); + } + child->rlink = del_node->rlink; + }else parent->rlink->rlink = del_node->rlink; //Sh + + }else{ + parent->llink = del_node->llink; + if(del_node->rlink->llink != NULL){ //YR`Il`I٦`Ip + dict *child = del_node->rlink->llink; + printf("%s\n",child->key); + while(child->llink!= NULL){ //䥪`I̩ + child = child->llink; + printf("%s\n",child->key); + } + child->llink = del_node->llink; + }else parent->llink->rlink = del_node->rlink; //Sh + } + } + free(del_node); /* O */ + printf("Rw[%s]\n",key); +} + +void find_newroot(){ /* jMs`I s̤j*/ + struct dict *newroot_node ,*prev; + + if(root->llink!=NULL){ //䥪s̤j + newroot_node = root->llink; + + while(newroot_node->rlink!=NULL){ //ڪN`I + prev = newroot_node; + newroot_node = newroot_node->rlink; + } + if(newroot_node->llink!=NULL){ //Ysڸ`I`I + prev->rlink = newroot_node->llink; + }else prev->rlink = NULL; + + if(newroot_node != root->llink ){ //Ysڸ`I쥻ڪ`I + newroot_node->llink = root->llink; + newroot_node->rlink = root->rlink; + }else{ //Ysڸ`I쥻ڪ`I + newroot_node->rlink = root->rlink; + } + printf("Rw[%s]\n",root->key); + free(root); + root = newroot_node; + }else if(root->rlink!=NULL){ //ks̤p + newroot_node = root->rlink; + + while(newroot_node->llink!=NULL){ //ڪN`I + prev = newroot_node; + newroot_node = newroot_node->llink; + } + if(newroot_node->rlink!=NULL){ //Ysڸ`Ik`I + prev->llink = newroot_node->rlink; + }else prev->llink = NULL; + + if(newroot_node != root->rlink ){ //Ysڸ`I쥻ڪk`I + newroot_node->llink = root->llink; + newroot_node->rlink = root->rlink; + }else{ //Ysڸ`I쥻ڪk`I + newroot_node->llink = root->llink; + } + printf("Rw[%s]\n",root->key); + free(root); + root = newroot_node; + } + +} + +/* jMtargetҦb`I */ +struct dict *search(char target[]){ + struct dict *node; + node = root; + while(node != NULL) + { + if (strcmp(target, node->key) == 0) + return node; + else + /* targetpثe`IAjM */ + if (strcmp(target, node->key) < 0) + node = node->llink; + else /* targetjثe`IAkjM */ + node = node->rlink; + } + return node; +} + +/* jMnode`I */ +struct dict *search_p(struct dict *node){ + struct dict *parent; + parent = root; + while (parent != NULL) { + if (strcmp(node->key, parent->key) < 0) { + if (strcmp(node->key, parent->llink->key) == 0) + return parent; + else + parent = parent->llink; + } + else { + if (strcmp(node->key, parent->rlink->key) == 0) + return parent; + else + parent = parent->rlink; + } + } + return NULL; +} diff --git a/作業/unit7/binarySearchTree.c b/作業/unit7/binarySearchTree.c new file mode 100644 index 0000000..28e7392 --- /dev/null +++ b/作業/unit7/binarySearchTree.c @@ -0,0 +1,307 @@ +/* file name: binarySearchTree.c */ +/* QΤGjMBzơиJBxsBsWBRBקBX */ + +#include +#include +#include + +/* wqstudentc */ +struct student { + char name[20]; /* ǥͩmW */ + int score; /* ǥͦZ */ + struct student *llink; /* l쵲 */ + struct student *rlink; /* kl쵲 */ +}; + + +void insert_f(void); /* sW */ +void delete_f(void); /* R */ +void modify_f(void); /* ק */ +void show_f(void); /* X */ +void process(char [], int); /* Nƥ[JGjM */ +void removing(char []); /* NƱqGjM𤤲 */ +struct student *replace(struct student *); /* MN`I */ +void connecting(struct student *, char); /* վ쵲 */ +void inorder(struct student *); /* ƥHǪkX */ +void flushBuffer(void); + +struct student *search(char []); /* jM`I */ +struct student *search_re_r(struct student *); /* jMklN`I */ +struct student *search_re_l(struct student *); /* jMlN`I */ +struct student *search_p(struct student *); /* jM`I */ + +struct student *root, *ptr; +int main(void) +{ + char option; + + while(1) { + puts(""); + puts("********************"); + puts(" <1> insert"); + puts(" <2> delete"); + puts(" <3> modify"); + puts(" <4> show"); + puts(" <5> quit"); + puts("********************"); + printf("Enter your choice: "); + option = getchar(); + flushBuffer(); + printf("\n"); + switch(option) { + case '1': + insert_f(); + break; + case '2': + delete_f(); + break; + case '3': + modify_f(); + break; + case '4': + show_f(); + break; + case '5': + exit(0); + default : + puts("ﶵ~!"); + } + } + return 0; +} + +/* sWơAsW@s */ +void insert_f(void) +{ + char name[20]; + int score; + puts("=====INSERT DATA====="); + printf("mW: "); + scanf("%s", name); + printf(": "); + scanf("%d", &score); + flushBuffer(); + process(name, score); +} + +/* RơANƱqGjM𤤧R */ +void delete_f(void) +{ + char name[20]; + if (root == NULL) { + puts("GjMOŪ!"); + return; + } + puts("=====DELETE DATA====="); + printf("пJRmW: "); + scanf("%s", name); + flushBuffer(); + removing(name); +} + +/* קơAקǥͦZ */ +void modify_f(void) +{ + struct student *node; + char name[20]; + + /* P_ڸ`IO_NULL */ + if (root == NULL) { + puts("GjMOŪ!"); + return; + } + puts("=====MODIFY DATA===== "); + printf("пJק諸mW: "); + scanf("%s", name); + flushBuffer(); + if ((node = search(name)) == NULL) + printf("%s bGjM!\n", name); + else { + /* CXƪp */ + printf("mW: %s\n", node->name); + printf(": %d\n\n", node->score); + printf("пJs: "); + scanf("%d", &node->score); + flushBuffer(); + printf("%s wQק\n", name); + } +} + +/* XơANƿXܿù */ +void show_f(void) +{ + /* P_ڸ`IO_NULL */ + if (root == NULL) { + puts("GjMOŪ!"); + return; + } + puts("=====SHOW DATA====="); + inorder(root); /* HǪkX */ +} + +/* BzGjMANsWƥ[JܤGjM */ +void process(char name[], int score) +{ + struct student *node, *prev; + /* Ƥwsbhܿ~ */ + if (search(name) != NULL) { + printf("%s wsb!\n", name); + return; + } + ptr = (struct student *) malloc(sizeof(struct student)); + strcpy(ptr->name, name); + ptr->score = score; + ptr->llink = ptr->rlink = NULL; + if (root == NULL) /* ڸ`INULLp */ + root = ptr; + else { /* ڸ`INULLp */ + node = root; + while (node != NULL) { /* jMƴJI */ + prev = node; + if(score > node->score) + node = node->rlink; + else + node = node->llink; + } + if (score < prev->score) + prev->llink = ptr; + else + prev->rlink = ptr; + } +} + +/* NƱqGjM𤤲 */ +void removing(char name[]) +{ + struct student *del_node; + if((del_node = search(name)) == NULL) /* 䤣ƫhܿ~ */ + { + printf("%s bGjM!\n", name); + return; + } + /* `I𸭸`Ip */ + if (del_node->llink != NULL || del_node->rlink != NULL) + del_node = replace(del_node); + else /* `I𸭸`Ip */ + if(del_node == root) + root = NULL; + else + connecting(del_node, 'n'); + free(del_node); /* O */ + printf("%s wQR!\n", name); +} + +/* MRD𸭸`IN`I */ +struct student *replace(struct student *node) +{ + struct student *re_node; + /* kl䤣N`IA|jMlO_sbN`I */ + if ((re_node = search_re_r(node->rlink)) == NULL) + re_node = search_re_l(node->llink); + if (re_node->rlink != NULL) /* N`Iklsbp */ + connecting(re_node, 'r'); + else + if (re_node->llink != NULL) /* N`Ilsbp */ + connecting(re_node, 'l'); + else /* N`I𸭸`Ip */ + connecting(re_node, 'n'); + strcpy(node->name, re_node->name); + node->score = re_node->score; + return re_node; +} + +/* վGjM쵲Alink r ܳBzk쵲A l Bz쵲A + m hN쵲V NULL */ +void connecting(struct student *node, char link) +{ + struct student *parent; + parent = search_p(node); /* jM`I */ + /* `I`Il𪺪p */ + if (node->score > parent->score) + if(link == 'r') /* linkr */ + parent->rlink = node->rlink; + else /* linkm */ + parent->rlink = NULL; + else /* `I`Ikl𪺪p */ + if (link == 'l') /* linkl */ + parent->llink = node->llink; + else /* linkm */ + parent->llink = NULL; +} + +/* HǪkXơAĻj覡 */ +void inorder(struct student *node) +{ + if(node != NULL) { + inorder(node->llink); + printf("%-10s %d\n", node->name, node->score); + inorder(node->rlink); + } +} + +/* jMtargetҦb`I */ +struct student *search(char target[]) +{ + struct student *node; + node = root; + while(node != NULL) + { + if (strcmp(target, node->name) == 0) + return node; + else + /* targetpثe`IAjM */ + if (strcmp(target, node->name) < 0) + node = node->llink; + else /* targetjثe`IAkjM */ + node = node->rlink; + } + return node; +} + +/* jMklN`I */ +struct student *search_re_r(struct student *node) +{ + struct student *re_node; + re_node = node; + while (re_node != NULL && re_node->llink != NULL) + re_node = re_node->llink; + return re_node; +} + +/* jMlN`I */ +struct student *search_re_l(struct student *node) +{ + struct student *re_node; + re_node = node; + while (re_node != NULL && re_node->rlink != NULL) + re_node = re_node->rlink; + return re_node; +} + +/* jMnode`I */ +struct student *search_p(struct student *node) +{ + struct student *parent; + parent = root; + while (parent != NULL) { + if (node->score > parent->score) { + if (parent->rlink == node) + return parent; + else + parent = parent->rlink; + } + else { + if (parent->llink == node) + return parent; + else + parent = parent->llink; + } + } + return NULL; +} + +void flushBuffer() +{ + while (getchar() != '\n') + continue; +} diff --git a/作業/unit7/binarySearchTree.exe b/作業/unit7/binarySearchTree.exe new file mode 100644 index 0000000..ea8c5f1 Binary files /dev/null and b/作業/unit7/binarySearchTree.exe differ diff --git a/作業/unit7/binarySearchTree_byname.c b/作業/unit7/binarySearchTree_byname.c new file mode 100644 index 0000000..6fe522f --- /dev/null +++ b/作業/unit7/binarySearchTree_byname.c @@ -0,0 +1,307 @@ +/* file name: binarySearchTree.c */ +/* QΤGjMBzơиJBxsBsWBRBקBX */ + +#include +#include +#include + +/* wqstudentc */ +struct student { + char name[20]; /* ǥͩmW */ + int score; /* ǥͦZ */ + struct student *llink; /* l쵲 */ + struct student *rlink; /* kl쵲 */ +}; + + +void insert_f(void); /* sW */ +void delete_f(void); /* R */ +void modify_f(void); /* ק */ +void show_f(void); /* X */ +void process(char [], int); /* Nƥ[JGjM */ +void removing(char []); /* NƱqGjM𤤲 */ +struct student *replace(struct student *); /* MN`I */ +void connecting(struct student *, char); /* վ쵲 */ +void inorder(struct student *); /* ƥHǪkX */ +void flushBuffer(void); + +struct student *search(char []); /* jM`I */ +struct student *search_re_r(struct student *); /* jMklN`I */ +struct student *search_re_l(struct student *); /* jMlN`I */ +struct student *search_p(struct student *); /* jM`I */ + +struct student *root, *ptr; +int main(void) +{ + char option; + + while(1) { + puts(""); + puts("********************"); + puts(" <1> insert"); + puts(" <2> delete"); + puts(" <3> modify"); + puts(" <4> show"); + puts(" <5> quit"); + puts("********************"); + printf("Enter your choice: "); + option = getchar(); + flushBuffer(); + printf("\n"); + switch(option) { + case '1': + insert_f(); + break; + case '2': + delete_f(); + break; + case '3': + modify_f(); + break; + case '4': + show_f(); + break; + case '5': + exit(0); + default : + puts("ﶵ~!"); + } + } + return 0; +} + +/* sWơAsW@s */ +void insert_f(void) +{ + char name[20]; + int score; + puts("=====INSERT DATA====="); + printf("mW: "); + scanf("%s", name); + printf(": "); + scanf("%d", &score); + flushBuffer(); + process(name, score); +} + +/* RơANƱqGjM𤤧R */ +void delete_f(void) +{ + char name[20]; + if (root == NULL) { + puts("GjMOŪ!"); + return; + } + puts("=====DELETE DATA====="); + printf("пJRmW: "); + scanf("%s", name); + flushBuffer(); + removing(name); +} + +/* קơAקǥͦZ */ +void modify_f(void) +{ + struct student *node; + char name[20]; + + /* P_ڸ`IO_NULL */ + if (root == NULL) { + puts("GjMOŪ!"); + return; + } + puts("=====MODIFY DATA===== "); + printf("пJק諸mW: "); + scanf("%s", name); + flushBuffer(); + if ((node = search(name)) == NULL) + printf("%s bGjM!\n", name); + else { + /* CXƪp */ + printf("mW: %s\n", node->name); + printf(": %d\n\n", node->score); + printf("пJs: "); + scanf("%d", &node->score); + flushBuffer(); + printf("%s wQק\n", name); + } +} + +/* XơANƿXܿù */ +void show_f(void) +{ + /* P_ڸ`IO_NULL */ + if (root == NULL) { + puts("GjMOŪ!"); + return; + } + puts("=====SHOW DATA====="); + inorder(root); /* HǪkX */ +} + +/* BzGjMANsWƥ[JܤGjM */ +void process(char name[], int score) +{ + struct student *node, *prev; + /* Ƥwsbhܿ~ */ + if (search(name) != NULL) { + printf("%s wsb!\n", name); + return; + } + ptr = (struct student *) malloc(sizeof(struct student)); + strcpy(ptr->name, name); + ptr->score = score; + ptr->llink = ptr->rlink = NULL; + if (root == NULL) /* ڸ`INULLp */ + root = ptr; + else { /* ڸ`INULLp */ + node = root; + while (node != NULL) { /* jMƴJI */ + prev = node; + if(strcmp(ptr->name, node->name) < 0) + node = node->llink; + else + node = node->rlink; + } + if (strcmp(ptr->name, prev->name) < 0) + prev->llink = ptr; + else + prev->rlink = ptr; + } +} + +/* NƱqGjM𤤲 */ +void removing(char name[]) +{ + struct student *del_node; + if((del_node = search(name)) == NULL) /* 䤣ƫhܿ~ */ + { + printf("%s bGjM!\n", name); + return; + } + /* `I𸭸`Ip */ + if (del_node->llink != NULL || del_node->rlink != NULL) + del_node = replace(del_node); + else /* `I𸭸`Ip */ + if(del_node == root) + root = NULL; + else + connecting(del_node, 'n'); + free(del_node); /* O */ + printf("%s wQR!\n", name); +} + +/* MRD𸭸`IN`I */ +struct student *replace(struct student *node) +{ + struct student *re_node; + /* kl䤣N`IA|jMlO_sbN`I */ + if ((re_node = search_re_r(node->rlink)) == NULL) + re_node = search_re_l(node->llink); + if (re_node->rlink != NULL) /* N`Iklsbp */ + connecting(re_node, 'r'); + else + if (re_node->llink != NULL) /* N`Ilsbp */ + connecting(re_node, 'l'); + else /* N`I𸭸`Ip */ + connecting(re_node, 'n'); + strcpy(node->name, re_node->name); + node->score = re_node->score; + return re_node; +} + +/* վGjM쵲Alink r ܳBzk쵲A l Bz쵲A + m hN쵲V NULL */ +void connecting(struct student *node, char link) +{ + struct student *parent; + parent = search_p(node); /* jM`I */ + /* `I`Il𪺪p */ + if (strcmp(node->name, parent->name) < 0) + if(link == 'r') /* linkr */ + parent->llink = node->rlink; + else /* linkm */ + parent->llink = NULL; + else /* `I`Ikl𪺪p */ + if (link == 'l') /* linkl */ + parent->rlink = node->llink; + else /* linkm */ + parent->rlink = NULL; +} + +/* HǪkXơAĻj覡 */ +void inorder(struct student *node) +{ + if(node != NULL) { + inorder(node->llink); + printf("%-10s %d\n", node->name, node->score); + inorder(node->rlink); + } +} + +/* jMtargetҦb`I */ +struct student *search(char target[]) +{ + struct student *node; + node = root; + while(node != NULL) + { + if (strcmp(target, node->name) == 0) + return node; + else + /* targetpثe`IAjM */ + if (strcmp(target, node->name) < 0) + node = node->llink; + else /* targetjثe`IAkjM */ + node = node->rlink; + } + return node; +} + +/* jMklN`I */ +struct student *search_re_r(struct student *node) +{ + struct student *re_node; + re_node = node; + while (re_node != NULL && re_node->llink != NULL) + re_node = re_node->llink; + return re_node; +} + +/* jMlN`I */ +struct student *search_re_l(struct student *node) +{ + struct student *re_node; + re_node = node; + while (re_node != NULL && re_node->rlink != NULL) + re_node = re_node->rlink; + return re_node; +} + +/* jMnode`I */ +struct student *search_p(struct student *node) +{ + struct student *parent; + parent = root; + while (parent != NULL) { + if (strcmp(node->name, parent->name) < 0) { + if (strcmp(node->name, parent->llink->name) == 0) + return parent; + else + parent = parent->llink; + } + else { + if (strcmp(node->name, parent->rlink->name) == 0) + return parent; + else + parent = parent->rlink; + } + } + return NULL; +} + +void flushBuffer() +{ + while (getchar() != '\n') + continue; +} diff --git a/作業/unit7/binarySearchTree_byname.exe b/作業/unit7/binarySearchTree_byname.exe new file mode 100644 index 0000000..efc5438 Binary files /dev/null and b/作業/unit7/binarySearchTree_byname.exe differ diff --git a/作業/unit7/tokenization.c b/作業/unit7/tokenization.c new file mode 100644 index 0000000..eb2d7be --- /dev/null +++ b/作業/unit7/tokenization.c @@ -0,0 +1,62 @@ +/* +Program: tokenization.c (Report comments/bugs to chikh@yuntech.edu.tw) +Function: JBrAqTA@~wƷx +Notes: Ji + w={"Mary":10, "Tom":3, "Charlie":5, "Bob":6, "Dickens":20, 4:9, "z":0, "Za":12, "aZ":8} + del w["Dickens"] + w["Mary"]=1 + w["Tom"]+=2 + w[4]? + w? +*/ + +#include /* for sscanf(), printf() */ +#include /* for strstr(), strtok(), strtok_r() */ + +int main() +{ + char *token, key[12], line[128]; + const char *s = " ={},"; /* jŰOr */ + int value, i = 0; + char *rest; + + printf("\n*** qrŪŰO(token){ ***\n\nJsr媺zAw{\n"); + while (1) { + printf("\nO => "); + fgets(line,128,stdin); /* ϥgets()Ū]iHA]gets()]ŪJrƪAiɭPxsJr}CŶz */ + if (line[0]=='\n') break; /* JŦrhj */ + if (strstr(line,"{")) { /* linet"{" */ + sscanf(line,"w = {%[^}]}",line); + /* printf("jAr %s\n",line); */ + rest = line; + while (token = strtok_r(rest,s,&rest)) { /* strtok_r()ΪkiѨ http://bit.ly/3VcvbbZ */ + /* printf("%s\n",token); */ + if (strstr(token,":")) {/* tokent":" */ + sscanf(token,"%[^:]:%d",key,&value); + printf("Token #%d: =%s; =%d\n",++i,key,value); + } + } + } + else if (strstr(line,"del")) { /* linet"del" */ + sscanf(line,"del w[%[^]]]",key); + printf("RBG=%s\n",key); + } + else if (strstr(line,"+=")) { /* linet"+=" */ + sscanf(line,"w[%[^]]] +=%d",key,&value); + printf("WBG=%sFB⤸=%d\n",key,value); + } + else if (strstr(line,"=")) { /* linet"=" */ + sscanf(line,"w[%[^]]] = %d",key,&value); + printf("BG=%s; B⤸=%d\n",key,value); + } + else if (sscanf(line,"w[%[^]]]?",key)==1) + printf("ŪȹBG=%s\n",key); + else if (strstr(line,"?")) + printf("ܾӦr夺e(ЦPǹ@A@~@)\n"); + else + printf("ykLk{Asorry!\n"); + } + + printf("\n{Abye ~\n"); + return 0; +} diff --git a/作業/unit7/try.cpp b/作業/unit7/try.cpp new file mode 100644 index 0000000..6657346 --- /dev/null +++ b/作業/unit7/try.cpp @@ -0,0 +1,203 @@ +#include +#include +#include +#include + +/* wq޽uGjM𵲺c */ +typedef struct student { + char name[20]; /* ǥͩmW */ + int score; /* ǥͦZ */ + struct student *left; /* l */ + struct student *right; /* kl */ + int leftThread; /* uаO */ + int rightThread; /* kuаO */ +} student; + +/* ܼ */ +student *root = NULL; +student *head = NULL; + +/* ƭ쫬 */ +void insert(char [], int); +void remove_node(char []); +void show_tree(); +student *search(char []); +student *find_inorder_successor(student *); +student *find_inorder_predecessor(student *); +void free_tree(student *); + +/* Mǫ~`I */ +student *find_inorder_successor(student *node) { + if (node->rightThread) + return node->right; + + node = node->right; + while (!node->leftThread) + node = node->left; + return node; +} + +/* MǫeX`I */ +student *find_inorder_predecessor(student *node) { + if (node->leftThread) + return node->left; + + node = node->left; + while (!node->rightThread) + node = node->right; + return node; +} + +/* J`I */ +void insert(char name[], int score) { + student *new_node, *current, *parent; + + /* ˬd`IO_wsb */ + if (search(name) != NULL) { + printf("%s wsb!\n", name); + return; + } + + new_node = (student *)malloc(sizeof(student)); + strcpy(new_node->name, name); + new_node->score = score; + new_node->leftThread = new_node->rightThread = 1; + + if (root == NULL) { + /* إߪY`I */ + head = (student *)malloc(sizeof(student)); + head->leftThread = head->rightThread = 0; + head->right = head; + head->left = new_node; + + /* Ĥ@Ӹ`I */ + new_node->left = head; + new_node->right = head; + root = new_node; + return; + } + + current = root; + while (1) { + parent = current; + if (strcmp(name, current->name) < 0) { + if (current->leftThread) + break; + current = current->left; + } else { + if (current->rightThread) + break; + current = current->right; + } + } + + if (strcmp(name, parent->name) < 0) { + /* l`I */ + new_node->left = parent->left; + new_node->right = parent; + parent->left = new_node; + parent->leftThread = 0; + } else { + /* kl`I */ + new_node->right = parent->right; + new_node->left = parent; + parent->right = new_node; + parent->rightThread = 0; + } +} + +/* ǹM */ +void show_tree() { + student *current; + + if (root == NULL) { + printf("OŪ!\n"); + return; + } + + current = root; + while (!current->leftThread) + current = current->left; + + printf("rܼƤxs(keyGvalue)pU\n"); + while (current != head) { + printf("%sG%d\n", current->name, current->score); + current = find_inorder_successor(current); + } +} + +/* jM`I */ +student *search(char target[]) { + student *current = root; + + while (current != NULL) { + if (strcmp(target, current->name) == 0) + return current; + + if (strcmp(target, current->name) < 0) { + if (current->leftThread) + break; + current = current->left; + } else { + if (current->rightThread) + break; + current = current->right; + } + } + return NULL; +} + +/* R`I */ +void remove_node(char name[]) { + student *node = search(name); + if (node == NULL) { + printf("%s b!\n", name); + return; + } + + // R`I@Ao̷|hӸ`ݭnBz + printf("R`I@b޽uGjM𤤸AݭnSOBzuC\n"); +} + +/* 𪺰O */ +void free_tree(student *node) { + if (node == NULL) return; + + if (!node->leftThread) + free_tree(node->left); + if (!node->rightThread) + free_tree(node->right); + + printf("R'w[%s]=%d'`I\n", node->name, node->score); + free(node); +} + +int main() { + char line[128], key[20]; + int value; + + printf("Jsr媺zA{\n"); + while (1) { + printf("\nO => "); + fgets(line, 128, stdin); + + if (line[0] == '\n') break; + + if (sscanf(line, "w[%[^]]] = %d", key, &value) == 2) { + insert(key, value); + printf("sWw[%s]=%d\n", key, value); + } else if (sscanf(line, "w[%[^]]]?", key) == 1) { + student *found = search(key); + if (found) + printf("r夸w[%s]=%d\n", key, found->score); + else + printf("~! %s b!\n", key); + } else if (line[0] == 'w' && line[1] == '?') { + show_tree(); + } + } + + free_tree(root); + free(head); + return 0; +} diff --git a/作業/unit7/try.exe b/作業/unit7/try.exe new file mode 100644 index 0000000..8a87522 Binary files /dev/null and b/作業/unit7/try.exe differ diff --git a/作業/「資料結構與演算法」期中考作答可用輸入.txt b/作業/「資料結構與演算法」期中考作答可用輸入.txt new file mode 100644 index 0000000..b237495 --- /dev/null +++ b/作業/「資料結構與演算法」期中考作答可用輸入.txt @@ -0,0 +1,19 @@ +同學上傳作答內容所用網頁 https://bit.ly/47uMxaE + +第1題可用輸入 +2x^0 - 1x^1 +1 x^3 -2x^2 +3x^4+9x^3-198x^2+156x^1+360x^0 +1x^5-10000x^3 ++1198x^9-119800x^7+40000x^6-1000x^8+6x^10 + + +第2題可用輸入 +10.5+20.8*(50.1-30.6)/2.5^4-6.6*8.2 +10-30*(-40-20)%2^4+7.5*-6 +1+sin((-50.2+sin(3.8*20)*cos(-30-100%40))*2^-2.5)*cos(123.456) +100*(sin(sin(sin(+50.2*cos((30+100%40)*sin(60/5.5)))+20*(+50/30.0)^3.5-6*8)))^2 + +100*(sin(sin(sin(50.2*cos((30+100%40)*sin(60/5.5)))+20*(50/30.0)^3.5-6*8)))^2 + + + diff --git a/作業/期中考/math_fun.cpp b/作業/期中考/math_fun.cpp new file mode 100644 index 0000000..2703a5f --- /dev/null +++ b/作業/期中考/math_fun.cpp @@ -0,0 +1,41 @@ +#include +#include +#include + + +int main(){ + int i = abs(-5); // ϥ abs() + long l = labs(-5L); // ϥ labs() + double d = fabs(-5.0); // ϥ fabs() + +// Ȩ fabs() + double x1 = -5.7; + printf("Ȭ: %.2f\n", fabs(x1)); // X: 5.70 + +// pow() + double base = 2.0, exponent = 3.0; + printf("23謰: %.2f\n", pow(base, exponent)); // X: 8.00 + +// ڨ sqrt() + double x2 = 16.0; + printf("16ڬ: %.2f\n", sqrt(x2)); // X: 4.00 + +// L˥h floor() + double x3 = 3.5; + printf("L˥hᬰ: %.2f\n", floor(10/2)); // X: 3.00 + +// Li ceil() + + printf("Liᬰ: %.2f\n", ceil(x3)); // X: 4.00 + +// |ˤJ round() + + printf("|ˤJᬰ: %.2f\n", round(x3)); // X: 4.00 + + int j=1 ,k=3; + j -= k ; + printf("%d",j); + + + return 0; +} diff --git a/作業/期中考/math_fun.exe b/作業/期中考/math_fun.exe new file mode 100644 index 0000000..bcdb161 Binary files /dev/null and b/作業/期中考/math_fun.exe differ diff --git a/作業/期中考/string_fun.cpp b/作業/期中考/string_fun.cpp new file mode 100644 index 0000000..fa4fc00 --- /dev/null +++ b/作業/期中考/string_fun.cpp @@ -0,0 +1,123 @@ +#include +#include +#include + +int main(){ + + // YJt\n ϥΦƲ\n + // N\nm\0 + name[strcspn(name, "\n")] = '\0'; + +// strlen() - pr + char str[] = "Hello"; + int length = strlen(str); // G 5 + printf("strlen(Hello) = %d\n",length); + +// strcpy() - ƻsr + char dest[50]; + char src[] = "Hello"; + strcpy(dest, src); // dest {b]t "Hello" + printf("strcpy(dest, Hello) => dest = %s\n",dest); + +// strcat() - sr + char str1[50] = "Hello "; + char str2[] = "World"; + strcat(str1, str2); // str1 {bO "Hello World" + printf("strcat(str1 = Hello, str2 = World) => str1 = %s\n",str1); + +// strcmp() - r + char str3[] = "Hello"; + char str4[] = "Hello"; + int result = strcmp(str3, str4); // ۦP^ 0Astr1 j str2 ^ǥơAp^ǭt + printf("strcmp(Hello, Hello) = %d\n",result); + +// strchr() - MrbrꤤĤ@X{m + char str5[] = "Hello"; + char *p1 = strchr(str5 , 'l'); // VĤ@ 'l' m + printf("strchr(Hello, 'l') = %p\n",*p1); + + +// strstr() - MlrbrꤤĤ@X{m + char str6[] = "Hello World HELLO"; + char *p2 = strstr(str6, "World"); // V "World" }lm +// char *p3 = strstr(NULL, " "); + printf("strstr(str6, World) = %d\n",p2 - str6 ); +// printf("strstr(, HELLO) = %d\n",p3 - str6 ); + + +// strchr禡 +// ƭ쫬Gchar *strchr(const char *str, int c) +// \GbrꤤMwrĤ@X{m +// ^ȡG +// +// YrA^Ӧrw +// YSA^ NULL +// +// `NGĤGӰѼMO int AڤW|Qഫ char ӷjM + +// char str[] = "programming"; +// char *p; +// // Mr 'g' +// p = strchr(str, 'g'); +// if (p != NULL) { +// printf(" 'g' m: %ld\n", p - str); // XG3 +// printf("qӦm쵲lr: %s\n", p); // XGgramming +// } +// +// // MҦ 'm' m +// char *temp = str; +// while ((temp = strchr(temp, 'm')) != NULL) { +// printf(" 'm' m: %ld\n", temp - str); +// temp++; // U@Ӧm~jM +// } +// +// // M䤣sbr +// p = strchr(str, 'z'); +// if (p == NULL) { +// printf("䤣r 'z'\n"); +// } + + +// strstr() +// ƭ쫬Gchar *strstr(const char *haystack, const char *needle) +// \GbDr]haystack^Mlr]needle^Ĥ@X{m +// ^ȡG +// +// YlrA^lrꭺX{mw +// YSA^ NULL +// +// `NGϤjpg + +// char str[] = "This is a simple example of strstr function"; +// char *p; +// +// // 򥻷jM +// p = strstr(str, "simple"); +// if (p != NULL) { +// printf("lrꪺm: %ld\n", p - str); // XG10 +// printf("qӦm쵲r: %s\n", p); // XGsimple example of strstr function +// } +// +// // jMƥX{lr +// char text[] = "hello hello hello"; +// char *temp = text; +// while ((temp = strstr(temp, "hello")) != NULL) { +// printf(" 'hello' m: %ld\n", temp - text); +// temp++; // U@Ӧm~jM +// } +// +// // jMŦr +// p = strstr(str, ""); +// if (p != NULL) { +// printf("Ŧrǰtr_lm\n"); // |ǰt_lm +// } +// +// // Ϥjpgd +// p = strstr(str, "SIMPLE"); // |A]jpgP +// if (p == NULL) { +// printf("䤣 'SIMPLE'A]OϤjpg\n"); +// } + + return 0; +} + diff --git a/作業/期中考/string_fun.exe b/作業/期中考/string_fun.exe new file mode 100644 index 0000000..2cb3d6d Binary files /dev/null and b/作業/期中考/string_fun.exe differ diff --git a/作業/老師程式/indirect-recursion-examples.zip b/作業/老師程式/indirect-recursion-examples.zip new file mode 100644 index 0000000..4145f5f Binary files /dev/null and b/作業/老師程式/indirect-recursion-examples.zip differ diff --git a/作業/老師程式/recursive-check-path.c b/作業/老師程式/recursive-check-path.c new file mode 100644 index 0000000..d47d0fc --- /dev/null +++ b/作業/老師程式/recursive-check-path.c @@ -0,0 +1,57 @@ +/* +Program: recursive-check-path.c +Function: Hj覡˵rO_NĪؿ|CĪ|׽uέYz^Ʀrզ + rA{]isValidPath()Md˵D^Ʀr(׽u)AѾl^ƦrcheckPathChar() + BzAcheckPathChar()BL{Yo{׽urANIsisValidPath()AzLoGӨ禡۩IsAF + ˵ĪG +Note: {YChatGPTͲĤ@ΨҡAѮvA[HXRgAƧUPǴxjH +*/ + +#include +#include + +int isValidPath(char *path); +int checkPathChar(char *path); + +int isValidPath(char *path) { + if (path[0] == '\0') + return 0; //^0ANpath"L"| + else if (path[0] == '/') + return checkPathChar(path+1); //˵path+1NrO_ĸ| + else if (isalnum(path[0])) + return checkPathChar(path); //IscheckPathChar()˵pathNrO_ĸ| + else + return 0; //^0ANpath"L"| +} + +int checkPathChar(char *path) { + if (path[0] == '\0') + return 1; //^1ANpath""| + else if (isalnum(path[0])) //Upath^ƦrAh~IscheckPathChar˵UӪrO_ŦX + return checkPathChar(path+1); + else if ((path[0] == '/') && (path[1] != '/')) //sX{"//" + return isValidPath(path+1); + else + return 0; //^0ANpath"L"| +} + +int main() { + char *paths[] = { + "/home/user/docs", // + "/home/user//docs", //L(tsGӥ׽u'/'Ÿ) + "/home/user/abc!", //L(]tD^Ʀr) + "/documents", // + "!valid/start", //L + "/home/1234" // + }; + + int i, count = sizeof(paths)/sizeof(paths[0]); + + for (i = 0; i < count; i++) + if (isValidPath(paths[i])) + printf("\"%s\" ĸ| \n",paths[i]); + else + printf("\"%s\" Dĸ| X\n",paths[i]); + + return 0; +} diff --git a/作業/老師程式/recursive-check-path.exe b/作業/老師程式/recursive-check-path.exe new file mode 100644 index 0000000..0321961 Binary files /dev/null and b/作業/老師程式/recursive-check-path.exe differ diff --git a/作業/老師程式/recursive-series=proc.c b/作業/老師程式/recursive-series=proc.c new file mode 100644 index 0000000..7685545 --- /dev/null +++ b/作業/老師程式/recursive-series=proc.c @@ -0,0 +1,33 @@ +/* +Program: recursive-series-proc.c (Report comments/bugs to chikh@yuntech.edu.tw) +Function: Hj覡GӼƦCiӧOۭAANӧOn[`AGӦVqi椺n + (inner product)BC{]mul()ƱMdiƦCۭBA⭼nG浹add() + 禡@[`Fadd()AIsmul()AnDmul()pѾlnApйBCzLoGӨƤ + ۩IsAFĪG +*/ + +#include + +int mul(int *, int *, int); +int add(int *, int *, int, int); + +int mul(int *A, int *B, int i) { + int c; + if ((c=A[i]*B[i]) == 0) + return 0; + else + return add(A,B,i+1,c); //c֥[ +} + +int add(int *A, int *B, int i, int c) { + return c+mul(A,B,i); +} + +int main() { + int A[] = { 1, 2, 3, 4, 5, 0}, + B[] = {-1,-2,-3,-4,-5, 0}; //̥0ANƦCܦAB]Nbi@q + + printf("\nGƦCӧOnM = %d",mul(A,B,0)); + + return 0; +} diff --git a/作業/老師解答/unit2/poly-integer-root-v3.c b/作業/老師解答/unit2/poly-integer-root-v3.c index a3f5e8a..2b23353 100644 --- a/作業/老師解答/unit2/poly-integer-root-v3.c +++ b/作業/老師解答/unit2/poly-integer-root-v3.c @@ -62,7 +62,6 @@ int findRoot(int p[], int q[]) /* if (p[2*p[0]-1] != 0) { /* ̧C >= 1Ah0i */ if ((i=p[2*p[0]-1]) > 0) q[c++] = 0; /* ̧CƳ]i */ - printf("\ni = %d\n",i); for (j = 1; j < 2*p[0]; j+=2) p[j] -= i;/* Ҧƴhi */ } @@ -92,8 +91,7 @@ void show(int p[], int n, int mode) printf("%s",p[i]==0? "\b-1":"\b-"); switch(p[i]) { case 0: - if(p[i+1]==1) printf("1+"); - else printf("+"); + printf("+"); break; case 1: printf("x+"); diff --git a/作業/老師解答/unit2/poly-integer-root-v3.exe b/作業/老師解答/unit2/poly-integer-root-v3.exe index d70f7ae..9770fec 100644 Binary files a/作業/老師解答/unit2/poly-integer-root-v3.exe and b/作業/老師解答/unit2/poly-integer-root-v3.exe differ