4

In this program, I need to get the solutions of a linear system and this system have n variables and n equations. I need to extract the coefficients of the equations in a text file (.txt) and put them on a matrix. The first line of the text file has a number, which is the number of equations in the system. The other lines, have the equations.

For example, if I have the following text file:

3
2x - 3y = 0
4x + z = 12
5y - 6z = 10

The matrix with the coefficients will be:

|2 -3  0  0|
|4  0  1 12|
|0  5 -6 10|

I know how to get the solutions of the linear system, but how can I get only the coefficients of the system (without a library)? I tried functions that only read numbers from a string(vector of char) but they won't work if the coefficient is a letter (return 0) or doesn't exist.

Rules:

The equations of the system need to be LINEAR, otherwise the program will be closed.

If the coefficient and the variable of the equation doesn't exist, the coefficient is 0.

If the coefficient doesn't exist, but the variable exists, (x, y, z for example), the coefficient is 1.

The variable can be any letter, it doesn't need to be x, y and z.

The code:

#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define MAXCHAR 1000
#include "LinkedList.c"

//in the future use STRTOK e SSCANF (SPRINTF maybe)

int main() {
FILE *fp;
char str[MAXCHAR];
int character;
int c = 0;
char fileaddress[50];
char *cp;
char *variaveis;
char *p;

int quant = 0;
int numDeEquacoes = 0;

printf("Enter the address of the file you want to open: ");

gets(fileaddress);
printf(fileaddress);


//int coeficientes[3][3];

fp = fopen(fileaddress, "r");
if (fp == NULL){
    printf("\n");
    printf("Cannot open file %s",fileaddress);
    return 1;
}
    printf("\n");

while (fgets(str, MAXCHAR, fp) != NULL)
{
    quant++;

    if(quant==1)
    {
        numDeEquacoes = (str[0] - '0');
    }

    printf("%s", str);

    //gets(str, sizeof(str), stdin);
        printf("Variables of equation: ");

        for(cp=str; *cp; ++cp)
            if(isalpha(*cp))
            {
               printf("%c", *cp, "\n");
               //scanf("%c", )
            }

            //THE CODE THAT RESULTS IN ONLY NUMBERS
            while (*p)
            {
                if ( isdigit(*p) || ( (*p=='-'||*p=='+') && isdigit(*(p+1))) )
                {
                    long val = strtol(p, &p, 10); 
                    printf("%ld\n Coefficients:", val, "\n");
                }
                else
                {
                    p++;
                }
            }//ENDS HERE


        //printf("Variaveis: ", variaveis);
        //printf("\n");

    //variaveis = strstr(str);
    //printf(variaveis);


}

fclose(fp);

if(quant-1!=numDeEquacoes)
{
    printf("The number of equations is wrong!\n");
    printf("The number of equations is: %i", numDeEquacoes,"\n");
    printf("The variable quant is: %i", quant,"\n");

    return 0;
}

//int coeficientes[numDeEquacoes][numDeEquacoes];

//printf("coef:",coeficientes);

return 0;
}
Community
  • 1
  • 1
Grandtour
  • 828
  • 1
  • 7
  • 27
  • 2
    You need to elaborate your question and show what you've tried. Short answer: parse each line of text yourself and extract the coefficient. That's shouldn't be too difficult. `scanf` won't do the job. – Jabberwocky Oct 05 '18 at 11:24
  • 3
    You need to write a parser. Before writing the parser, you need to exactly define the expected format of what to parse. – alk Oct 05 '18 at 11:26
  • What is the significance of the '3' on the first line? – Bathsheba Oct 05 '18 at 11:33
  • '3' means that in this linear system, there are 3 equations – Grandtour Oct 05 '18 at 11:35
  • 1
    What symbols would you expect for say the `4` case? – Bathsheba Oct 05 '18 at 11:36
  • You mean, 4 equations or 4 variables? – Grandtour Oct 05 '18 at 11:37
  • @Grandtour 4 variables of course. you'd have x, y, z and ??? – Jabberwocky Oct 05 '18 at 11:47
  • 1
    The variables can be any letter, that is another problem – Grandtour Oct 05 '18 at 12:14
  • @Grandtour you write _"I tried functions that only read numbers from a string(vector of char) but they won't work if the coefficient is a letter or doesn't exist"_: you should show us that failing code in your question, this may help us to provide better answers – Jabberwocky Oct 05 '18 at 12:21
  • I have already changed – Grandtour Oct 05 '18 at 12:51
  • I once wrote an answer to a somehow similar question. It was for C++. However, I think it would be not too hard to translate it to C, and the part prior coding is language agnostic. So, it might be of help (or at least good for some inspiration): [SO: How to rearrange a string equation?](https://stackoverflow.com/a/50021308/7478597) – Scheff's Cat Oct 05 '18 at 13:59
  • "The variables can be any letter, that is another problem" upper or lower case? ascii only or any utf8 character? are the numbers always written in decimal or sometimes octal or hex? are there random numbers of spaces between numbers and signs or tabs or some other white space? are the new lines `\n` or `\r\n`? how many new lines between data sets? .... Please specify your format constraints or delete the question ... You also may want to point out that when the number is 1 it is omitted - that will be a special case – technosaurus Oct 08 '18 at 09:13
  • I have changed the question. Respectively, yes (both); utf8; decimal always; yes there are random white spaces or another kinds of spaces; yes, there is a number in the first line of the file that is the number of lines(the number is given). – Grandtour Oct 09 '18 at 10:59
  • Hi, any progress with this? My answer wasn't very popular, so I will ask some details to work in the C solution: Upper-case and lower-case are considered different variables? integer coefficients or decimal too? any limit on **n**? – gustavovelascoh Oct 11 '18 at 11:11
  • In the order, no; decimal too; no, but I think if **n** is big, the program will be very slow. – Grandtour Oct 11 '18 at 12:20

2 Answers2

0

You should read the signals (+ or -) and multiply the coefficients. If the signal is +, multiply by +1, else, by -1. If there isn't a variable (or letter), the coefficient is 0.

S.I.M.P.L.E
  • 127
  • 1
  • 1
  • 9
-2

I don't have time right now to code it in C, but I have this python approach, for if you want to check the algorithm. The output I got is

[[2, -3, 0, 0],
 [4, 0, 1, 12],
 [0, 5, -6, 10]]

You have to check if there is a sign (+ or -) or not (assume +), get the number (1 if it not exist), and store the letter (variable). Then restart the process at each sign (+,- or =) and space.

For the matrix, start a column counter and an array for column indexes, and each time you find a variable search in the array for the index, and if it doesn't exist, assign that counter as the column index for that variable and increment it.

Here the code:

# - For reading the coefficients:
# 3
# 2x - 3y = 0
# 4x + z = 12
# 5y - 6z = 10

def get_index(d, c):
    if c in d.keys():
        return d[c] 
    else:
        return -1
s=1 #sign
n_fg = 0 #number exist
eq_fg = 0 #equal flag
s_fg = 0 #sign flag
letter = '' # store current letter (variable)
coef =''
curr_idx = 0

N = int(input())

letter_idx = {}

mat = [[0 for i in range(N+1)] for i in range(N)]

for i in range(N):

    l = input()
    coef = ''
    eq_fg = 0
    s_fg = 0
    s = 1
    ls = len(l)
    k = 0 # position in line str

    for c in l:

        if c == '-':
            s_fg = 1
            s=-1
        elif c == '+':
            s_fg = 1
            s = 1
        elif c.isalpha():
            if n_fg == 0:
                coef = 1
            letter = c
        elif c.isdigit():
            n_fg = 1
            coef += c

            if k == ls-1:
                if coef is '':
                    coef = 1
                coef = s*int(coef)
                if eq_fg == 0:
                    j = get_index(letter_idx,letter)
                    if j == -1:
                        j = curr_idx
                        letter_idx[letter] = j
                        curr_idx+=1
                else:
                    j = N
                mat[i][j] = coef

        elif (c == ' ' and s_fg != 1) :
            if coef is '':
                coef = 1
            coef = s*int(coef)
            if eq_fg == 0:
                j = get_index(letter_idx,letter)
                if j == -1:
                    j = curr_idx
                    letter_idx[letter] = j
                    curr_idx+=1
            else:
                j = N
            mat[i][j] = coef
            coef = ''
            n_fg = 0
        elif c == ' ' and s_fg == 1:
            s_fg = 0
        elif c == '=':
            eq_fg = 1
            s_fg = 1
            s = 1
        k+=1

print(mat)
gustavovelascoh
  • 1,079
  • 1
  • 10
  • 25