fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <math.h>
  5. #include <ctype.h>
  6. #define MAX_LENGTH 256
  7.  
  8. void read_input(char *input, size_t size) {
  9. if (fgets(input, size, stdin) == NULL) {
  10. fprintf(stderr, "Error reading input.\n");
  11. exit(1);
  12. }
  13. input[strcspn(input, "\n")] = '\0';
  14. }
  15.  
  16. void invertSymmetry(char *result) {
  17. while (*result) {
  18. *result = (*result == '1') ? 'i' : (*result == 'i' ? '1' : *result);
  19. ++result;
  20. }
  21. }
  22.  
  23. // Функция для создания фиксированной матрицы 2 на 256
  24. char* thirdFunction(char matrix[2][MAX_LENGTH], int rows) {
  25. static char result[MAX_LENGTH]; // Статический массив для возвращаемой строки
  26. memset(result, '0', MAX_LENGTH); // Инициализация нулями
  27.  
  28. printf("Высота: %d\n", rows);
  29. int columns = strlen(matrix[0]);
  30. printf("Длина: %d\n", columns);
  31.  
  32. printf("\nПолученная матрица:\n");
  33. for (int i = 0; i < rows; i++) {
  34. printf("%s\n", matrix[i]);
  35. }
  36.  
  37. int x, z, r, y = 0, g;
  38. char current_result[columns + 1];
  39. current_result[0] = '\0';
  40.  
  41. int j = columns - 1;
  42. while (j >= 0 || y != 0) {
  43. x = 0; g = 0; r = 0;
  44.  
  45. int skip = 0;
  46.  
  47. for (int i = 0; i < rows; i++) {
  48. char n = (j >= 0) ? matrix[i][j] : '0';
  49. if (n == '1') {
  50. x += 1;
  51. } else if (n == 'i') {
  52. x -= 1;
  53. } else if (n == ',' || n == '.') {
  54. memmove(current_result + 1, current_result, strlen(current_result) + 1);
  55. current_result[0] = ',';
  56. skip = 1;
  57. break;
  58. }
  59. }
  60.  
  61. if (skip) {
  62. j--;
  63. continue;
  64. }
  65. x += y;
  66. r = (x < 0) ? -1 : 1;
  67. z = abs(x) % 3;
  68. if (z == 2) {
  69. z = -1;
  70. g = 1;
  71. }
  72. z *= r;
  73. g *= r;
  74. memmove(current_result + 1, current_result, strlen(current_result) + 1);
  75.  
  76. if (z == -1) {
  77. current_result[0] = 'i';
  78. } else if (z == 1) {
  79. current_result[0] = '1';
  80. } else if (z == 0) {
  81. current_result[0] = '0';
  82. }
  83. y = x / 3;
  84. y = y * r;
  85. y += g;
  86.  
  87. if (j >= 0) {
  88. j--;
  89. }
  90. }
  91.  
  92. // Удаление ведущих '0' с изменением самого массива
  93. /*char *first_nonzero = current_result;
  94.   while (*first_nonzero == '0') {
  95.   first_nonzero++;
  96.   }*/
  97.  
  98. // Если вся строка была из '0', оставляем один '0'
  99. /*if (*first_nonzero == '\0') {
  100.   first_nonzero--; // Вернемся на последний '0'
  101.   }*/
  102.  
  103. // Перезаписываем массив с найденного элемента
  104. /*size_t new_length = strlen(first_nonzero) + 1; // +1 для '\0'
  105.   memmove(current_result, first_nonzero, new_length);*/
  106.  
  107. //printf("Resulting string: %s\n", current_result);
  108.  
  109. // Копируем результат в result, чтобы передать его в основную функцию
  110. strncpy(result, current_result, MAX_LENGTH - 1);
  111. result[MAX_LENGTH - 1] = '\0'; // Обеспечиваем завершающий ноль
  112.  
  113. return result;
  114. }
  115.  
  116.  
  117.  
  118. // Функция для выполнения основной логики
  119. void newFunction(char input1[], char input2[]) {
  120. int n1 = strlen(input1);
  121. int n2 = strlen(input2);
  122.  
  123. // Найти позиции запятой или точки
  124. char* comma1_pos = strpbrk(input1, ",.");
  125. char* comma2_pos = strpbrk(input2, ",.");
  126.  
  127. if (comma1_pos) {
  128. n1 = comma1_pos - input1; // Индекс до запятой
  129. }
  130.  
  131. if (comma2_pos) {
  132. n2 = comma2_pos - input2; // Индекс до запятой
  133. }
  134.  
  135. int a1 = strlen(input1);
  136. int a2 = strlen(input2);
  137.  
  138. // Добавляем разницу в длине до запятой
  139. if (n1 < n2) {
  140. a1 += (n2 - n1);
  141. }
  142.  
  143. if (n2 < n1) {
  144. a2 += (n1 - n2);
  145. }
  146.  
  147. // Берем максимальную длину строк
  148. int max_a = (a1 > a2) ? a1 : a2;
  149. int n = 2;
  150.  
  151. char matrix[2][MAX_LENGTH];
  152. memset(matrix, '0', sizeof(matrix)); // Заполняем нулями
  153. matrix[0][max_a] = '\0'; // Добавляем нуль-терминатор
  154. matrix[1][max_a] = '\0';
  155.  
  156. int start_idx1 = (n1 < n2) ? n2 - n1 : 0;
  157. memcpy(matrix[0] + start_idx1, input1, strlen(input1));
  158.  
  159. int start_idx2 = (n2 < n1) ? n1 - n2 : 0;
  160. memcpy(matrix[1] + start_idx2, input2, strlen(input2));
  161.  
  162. // Получаем результат из thirdFunction
  163. char* result = thirdFunction(matrix, n);
  164. printf("\nРезультат третьей функции: %s\n", result);
  165. }
  166.  
  167.  
  168.  
  169. void newAdd(char input1[], char input2[]) {
  170. char temp[MAX_LENGTH];
  171. // Найти позиции запятых или точек
  172. char* comma1_pos = strpbrk(input1, ",.");
  173. char* comma2_pos = strpbrk(input2, ",.");
  174.  
  175. int len1 = strlen(input1);
  176. int len2 = strlen(input2);
  177.  
  178. int index1 = comma1_pos ? (int)(comma1_pos - input1) + 1 : len1;
  179. int index2 = comma2_pos ? (int)(comma2_pos - input2) + 1 : len2;
  180.  
  181. int n = (len1 - index1) + (len2 - index2);
  182.  
  183. // Функция для удаления первого вхождения '.' или ','
  184. void removeChar(char* str) {
  185. char* pos = strpbrk(str, ",.");
  186. if (pos) {
  187. memmove(pos, pos + 1, strlen(pos)); // Сдвиг влево
  188. }
  189. }
  190.  
  191. removeChar(input1);
  192. removeChar(input2);
  193.  
  194. // Сохраняем длины строк после удаления
  195. len1 = strlen(input1);
  196. len2 = strlen(input2);
  197.  
  198. // Проверяем длины и меняем местами, если вторая строка длиннее
  199. if (len2 > len1) {
  200. strcpy(temp, input2);
  201. strcpy(input2, input1);
  202. strcpy(input1, temp);
  203. int templen = len2;
  204. len2 = len1;
  205. len1 = templen;
  206. } else {
  207. strcpy(temp, input1);
  208. }
  209. // Инвертируем строку temp (предположим, что invertSymmetry это функция инверсии)
  210. invertSymmetry(temp);
  211.  
  212. // Вычисляем len как разницу длин строк
  213. char matrix[len2][MAX_LENGTH];
  214. memset(matrix, '0', sizeof(matrix)); // Инициализируем весь массив нулями (пустыми символами)
  215.  
  216.  
  217. int len=len1-len2;
  218. int s = len2 - 1; // Начнем с нижней строки и будем уменьшать s
  219. for (int i = 0; i < len2; i++) {
  220. if (input2[i] == '1') {
  221. // Копируем строку input1 в matrix[s], с учетом уменьшения отступа
  222. memcpy(matrix[s] + (len2 - 1 - s), input1, MAX_LENGTH - (len2 - 1 - s));
  223. }
  224. else if (input2[i] == 'i') {
  225. // Копируем строку temp в matrix[s], с учетом уменьшения отступа
  226. memcpy(matrix[s] + (len2 - 1 - s), temp, MAX_LENGTH - (len2 - 1 - s));
  227. }
  228. else if (input2[i] == '0') { matrix[s][len1+len2-1] = '\0';}
  229. // Уменьшаем s, двигаясь вверх по матрице
  230. s--;
  231. }
  232. /*
  233.   // Выводим результат
  234.   for (int i = 0; i < len2; i++) {
  235.   // Добавляем символы '/' для пустых мест
  236.   for (int j = 0; j < len; j++) {
  237.   if (matrix[i][j] == '\0') {
  238.   //matrix[i][j] = ' '; // Заполняем пустые места
  239.   }
  240.   }
  241.   printf("matrix[%d]: %s\n", i, matrix[i]);
  242.   }
  243.  
  244.  
  245.   // Вывод результатов
  246.   /*printf("Значение n: %d\n", n);
  247.   printf("Первая строка после удаления: %s\n", input1);
  248.   printf("Вторая строка после удаления: %s\n", input2);
  249.   printf("Первая строка после инверсии: %s\n", temp);
  250.   printf("Длина первой строки после удаления: %d\n", len1);
  251.   printf("Длина второй строки после удаления: %d\n", len2);*/
  252.  
  253. char* result = thirdFunction(matrix, len2);
  254. n=strlen(result)-n;
  255. if (n>0 && n!=(len1+len2)){
  256. memmove(result + n + 1, result + n, strlen(result) - n + 1);
  257. result[n] = ',';}
  258. printf("\nРезультат третьей функции: %s\n", result);
  259.  
  260. }
  261.  
  262.  
  263. /*
  264. void binary_and() {
  265.   char input1[100];
  266.   char input2[100];
  267.   int matrix[2][MAX_LENGTH];
  268.   printf("\nEnter the first ternary symmetric number: ");
  269.   read_input(input1, MAX_LENGTH);
  270.   printf("Enter the second ternary symmetric number: ");
  271.   read_input(input2, MAX_LENGTH);
  272.  
  273.   ArrayResult result = CreateAnArray(input1, input2, matrix);
  274.  
  275.   int columns = result.column;
  276.   int wq = result.row;
  277.  
  278.   char final_result[MAX_LENGTH] = {0};
  279.   int result_index = 0;
  280.  
  281.   printf("\nColumns: %d\n", columns);
  282.   printf("wq: %d\n", wq);
  283.  
  284.   for (int j = 0; j < columns; j++) {
  285.   if (matrix[0][j] == 'i' || matrix[1][j] == 'i') {
  286.   final_result[result_index++] = 'i';
  287.   } else if (matrix[0][j] == '0' || matrix[1][j] == '0') {
  288.   final_result[result_index++] = '0';
  289.   } else if (matrix[0][j] == '1' && matrix[1][j] == '1') {
  290.   final_result[result_index++] = '1';
  291.   } else if (matrix[0][j] == ',' || matrix[0][j] == '.' || matrix[1][j] == ',' || matrix[1][j] == '.') {
  292.   final_result[result_index++] = ',';
  293.   } else {
  294.   final_result[result_index++] = '0';
  295.   }
  296.   }
  297.   final_result[result_index] = '\0';
  298.   printf("\nResulting string: %s\n", final_result);
  299. }
  300.  
  301. void binary_or() {
  302.   char input1[100];
  303.   char input2[100];
  304.   int matrix[2][MAX_LENGTH];
  305.   printf("\nEnter the first ternary symmetric number: ");
  306.   read_input(input1, MAX_LENGTH);
  307.   printf("Enter the second ternary symmetric number: ");
  308.   read_input(input2, MAX_LENGTH);
  309.  
  310.   ArrayResult result = CreateAnArray(input1, input2, matrix);
  311.  
  312.   int columns = result.column;
  313.   int wq = result.row;
  314.  
  315.   char final_result[MAX_LENGTH] = {0};
  316.   int result_index = 0;
  317.  
  318.   printf("\nColumns: %d\n", columns);
  319.   printf("wq: %d\n", wq);
  320.  
  321.   printf("\nResulting matrix:\n");
  322.   for (int i = 0; i < 2; i++) {
  323.   for (int j = 0; j < columns; j++) {
  324.   printf("%c ", matrix[i][j]);
  325.   }
  326.   printf("\n");
  327.   }
  328.  
  329.   for (int j = 0; j < columns; j++) {
  330.   if (matrix[0][j] == '1' || matrix[1][j] == '1') {
  331.   final_result[result_index++] = '1';
  332.   } else if (matrix[0][j] == '0' || matrix[1][j] == '0') {
  333.   final_result[result_index++] = '0';
  334.   } else if (matrix[0][j] == 'i' && matrix[1][j] == 'i') {
  335.   final_result[result_index++] = 'i';
  336.   } else if (matrix[0][j] == ',' || matrix[0][j] == '.' || matrix[1][j] == ',' || matrix[1][j] == '.') {
  337.   final_result[result_index++] = ',';
  338.   } else {
  339.   final_result[result_index++] = '0';
  340.   }
  341.   }
  342.   final_result[result_index] = '\0';
  343.   printf("\nResulting string: %s\n", final_result);
  344. }
  345. */
  346.  
  347. void threeToTen() {
  348. char input[256];
  349.  
  350. printf("\nEnter a string: ");
  351. read_input(input, MAX_LENGTH);
  352.  
  353. char *delimiter = strpbrk(input, ".,");
  354. int n = (delimiter) ? (delimiter - input - 1) : (strlen(input) - 1);
  355.  
  356. double result = 0;
  357.  
  358. for (int i = 0; input[i] != '\0'; i++) {
  359. if (input[i] == '.' || input[i] == ',') {
  360. continue;
  361. } else if (input[i] == 'i') {
  362. result += -1 * pow(3, n);
  363. } else if (isdigit(input[i])) {
  364. result += (input[i] - '0') * pow(3, n);
  365. }
  366. n--;
  367. }
  368. printf("Decimal value: %.10f\n", result);
  369. }
  370.  
  371. void symmetry(const char *input, int isNegative) {
  372. printf("Non-symmetrical result: %s\n", input);
  373. size_t len = strlen(input);
  374. char result[MAX_LENGTH] = "";
  375. int x = 0, y = 0, z = 0;
  376.  
  377. for (int i = len - 1; i >= 0; i--) {
  378. if (input[i] == ',') {
  379. memmove(result + 1, result, strlen(result) + 1);
  380. result[0] = ',';
  381. continue;
  382. }
  383.  
  384. x = input[i] - '0';
  385. z = y + x;
  386.  
  387. if (z <= 1) {
  388. memmove(result + 1, result, strlen(result) + 1);
  389. result[0] = z + '0';
  390. y = 0;
  391. } else if (z == 2) {
  392. memmove(result + 1, result, strlen(result) + 1);
  393. result[0] = 'i';
  394. y = 1;
  395. } else if (z == 3) {
  396. memmove(result + 1, result, strlen(result) + 1);
  397. result[0] = '0';
  398. y = 1;
  399. }
  400. }
  401.  
  402. if (y != 0) {
  403. memmove(result + 1, result, strlen(result) + 1);
  404. result[0] = y + '0';
  405. }
  406.  
  407. if (isNegative) {
  408. invertSymmetry(result);
  409. }
  410.  
  411. printf("Symmetrical result: %s\n", result);
  412. }
  413.  
  414. void whole_part(char *part) {
  415. long long number = strtoll(part, NULL, 10);
  416.  
  417. if (number == 0) {
  418. part[0] = '0';
  419. part[1] = '\0';
  420. } else {
  421. char buffer[2];
  422. part[0] = '\0';
  423.  
  424. while (number > 0) {
  425. sprintf(buffer, "%d", number % 3);
  426. memmove(part + 1, part, strlen(part) + 1);
  427. part[0] = buffer[0];
  428. number /= 3;
  429. }
  430. }
  431. }
  432.  
  433. void fraction_part(char *part) {
  434. double fractionalValue = atof(part) / pow(10, strlen(part));
  435. char buffer[2];
  436. part[0] = '\0';
  437.  
  438. for (int i = 0; i < 15; i++) {
  439. fractionalValue *= 3;
  440. int digit = (int)fractionalValue;
  441. fractionalValue -= digit;
  442. sprintf(buffer, "%d", digit);
  443. strcat(part, buffer);
  444. }
  445. }
  446.  
  447. void translation() {
  448. char input[256];
  449. char firstPart[128] = "";
  450. char secondPart[128] = "";
  451. int isNegative = 0;
  452.  
  453. printf("\nEnter a string: ");
  454. read_input(input, MAX_LENGTH);
  455.  
  456. if (strchr(input, '-') != NULL) {
  457. isNegative = 1;
  458. memmove(input, input + 1, strlen(input));
  459. }
  460.  
  461. char *delimiter = strpbrk(input, ".,");
  462.  
  463. if (delimiter) {
  464. size_t firstLen = delimiter - input;
  465. strncpy(firstPart, input, firstLen);
  466. firstPart[firstLen] = '\0';
  467.  
  468. strcpy(secondPart, delimiter + 1);
  469. } else {
  470. strcpy(firstPart, input);
  471. }
  472.  
  473. whole_part(firstPart);
  474. if (strlen(secondPart) > 0) {
  475. fraction_part(secondPart);
  476. } else {
  477. strcpy(secondPart, "0");
  478. }
  479.  
  480. char combined[MAX_LENGTH] = "";
  481. snprintf(combined, sizeof(combined), "%s,%s", firstPart, secondPart);
  482.  
  483. symmetry(combined, isNegative);
  484. }
  485.  
  486. int main() {
  487. int choice;
  488. char input1[MAX_LENGTH], input2[MAX_LENGTH];
  489. int n; // Размер матрицы
  490.  
  491. int matrix[MAX_LENGTH][MAX_LENGTH]; // Матрица произвольного размера
  492.  
  493. do {
  494. printf("\nМеню:\n");
  495. printf("1. From Ternary\n");
  496. printf("2. From Decimal\n");
  497. printf("3. сложения\n");
  498. printf("4. вычитание\n");
  499. printf("5. умножение\n");
  500. printf("0. Выход\n");
  501. printf("Введите ваш выбор: ");
  502.  
  503. if (scanf("%d", &choice) != 1) {
  504. fprintf(stderr, "Неверный ввод. Выход.\n");
  505. break;
  506. }
  507.  
  508. while (getchar() != '\n'); // Ожидаем ввода
  509.  
  510. switch (choice) {
  511. case 1:
  512. translation();
  513. break;
  514. case 2:
  515. threeToTen();
  516. break;
  517. case 3:
  518. printf("Введите первую строку: ");
  519. read_input(input1, MAX_LENGTH);
  520. printf("Введите вторую строку: ");
  521. read_input(input2, MAX_LENGTH);
  522. newFunction(input1, input2);
  523. break;
  524. case 4:
  525. printf("Введите первую строку: ");
  526. read_input(input1, MAX_LENGTH);
  527. printf("Введите вторую строку: ");
  528. read_input(input2, MAX_LENGTH);
  529. invertSymmetry(input2);
  530. newFunction(input1, input2);
  531. break;
  532. case 5:
  533. printf("Введите первую строку: ");
  534. read_input(input1, MAX_LENGTH);
  535. printf("Введите вторую строку: ");
  536. read_input(input2, MAX_LENGTH);
  537. newAdd(input1, input2);
  538. break;
  539. case 0:
  540. printf("Выход из программы.\n");
  541. break;
  542. default:
  543. printf("Неверный выбор. Попробуйте снова.\n");
  544. }
  545. } while (choice != 0);
  546.  
  547. return 0;
  548. }
  549.  
Success #stdin #stdout #stderr 0s 5288KB
stdin
Standard input is empty
stdout
Меню:
1. From Ternary
2. From Decimal
3.  сложения
4.  вычитание
5.  умножение
0. Выход
Введите ваш выбор: 
stderr
Неверный ввод. Выход.