Find saddle point - C - c

I need to find the saddle point of a matrix loading a file with a sequence of numbers. In this case my matrix is 4x3. The sequence of numbers (content of the file) is: 3 -4 8 5 2 7 12 7 9 0 1 2. The functions and some variables are in spanish, I will try to comment everything so you guys can understand it. The thing is that my output is always the same: "the saddle point is in row 0 and column 2" and that´s not true. I'm doing something wrong and I can't spot the problem. Thanks guys!
#include <stdio.h>
#include <stdlib.h>
#define M 4
#define N 3
int escribeMat(int matriz[M][N]);
int Punto_de_silla_Mat(int matriz[M][N]);
int main()
{
int numeros, i, j;
int matriz[M][N];
FILE *fichero;
fichero = fopen("C:\\Users\\diego\\Documents\\Practicas_TP\\Ficheros\\numeros.txt", "r");
if (fichero == NULL){
printf("Error, el archivo no se ha abierto correctamente");
return 0;
}
else{
for(i=0;i<M;i++){
for(j=0;j<N;j++){
fscanf(fichero, "%d", &matriz[i][j]);
}
}
escribeMat(matriz);
Punto_de_silla_Mat(matriz);
return 0;
}
}
int escribeMat(int matriz[M][N]){ //function that prints the matrix
int i, j;
for(i=0;i<M;i++){
for(j=0;j<N;j++){
printf("%3d", matriz[i][j]);
}
printf("\n");
}
}
int Punto_de_silla_Mat(int matriz[M][N]){
int i=0,j=0,k=0;
int P_fila=0,P_columna=0, encontrado=0;
for(i=0;i<N;i++){
P_fila=i; //row
P_columna=j; //column
encontrado=0; //flag
for(j=0;j<M;j++){
if(matriz[i][j] < matriz[P_fila][P_columna]){
P_fila = i;
P_columna = j;}
for(k=0;k<N;k++){
if(matriz[k][P_columna] > matriz[P_fila][P_columna]){
encontrado = 1;
break;
}
}
}
}
if(encontrado == 1){
printf("El punto de silla la fila %d y en la columna %d", matriz[P_fila][P_columna], P_fila, P_columna); //found it + position
}else
printf("No hay punto de silla"); //there is no saddle point.
}
Edit 1: Added the missing argument in printf. But still the output should be 7, row 2 and column 1 and I'm getting number 0, row 2 and column 3.
printf("El punto de silla es %d y está en la fila %d y en la columna %d", matriz[P_fila][P_columna], P_fila, P_columna); //saddle point number + position
Edit 2: Removed int numeros. Changed the funtion escribeMat from int to void. Added return to Punto_De_silla function.
#include <stdio.h>
#include <stdlib.h>
#define M 4
#define N 3
void escribeMat(int matriz[M][N]);
int Punto_de_silla_Mat(int matriz[M][N]);
int main()
{
int i, j;
int matriz[M][N];
FILE *fichero;
fichero = fopen("C:\\Users\\diego\\Documents\\Practicas_TP\\Ficheros\\numeros.txt", "r");
if (fichero == NULL){
printf("Error, el archivo no se ha abierto correctamente");
return 0;
}
else{
for(i=0;i<M;i++){
for(j=0;j<N;j++){
fscanf(fichero, "%d", &matriz[i][j]);
}
}
escribeMat(matriz);
Punto_de_silla_Mat(matriz);
/* if(Punto_de_silla_Mat(matriz) == 1){
printf("El punto de silla es %d y esta en la fila %d y en la columna %d", matriz[P_fila][P_columna], P_fila, P_columna);
}
else
printf("No hay punto de silla"); */
return 0;
}
}
void escribeMat(int matriz[M][N]){ //function that prints the matrix on screen
int i, j;
for(i=0;i<M;i++){
for(j=0;j<N;j++){
printf("%3d", matriz[i][j]);
}
printf("\n");
}
}
int Punto_de_silla_Mat(int matriz[M][N]){
int i=0,j=0,k=0;
int P_fila=0,P_columna=0, encontrado=0;
for(i=0;i<N;i++){
P_fila=i; //row
P_columna=j; //column
encontrado=0; //flag
for(j=0;j<M;j++){
if(matriz[i][j] < matriz[P_fila][P_columna]){
P_fila = i;
P_columna = j;}
for(k=0;k<N;k++){
if(matriz[k][P_columna] > matriz[P_fila][P_columna]){
encontrado = 1;
break;
}
}
}
}
if(encontrado == 1){
printf("El punto de silla es %d y esta en la fila %d y en la columna %d", matriz[P_fila][P_columna], P_fila, P_columna); //saddle point number + position
}else
printf("No hay punto de silla"); //there is no saddle point.
return 0;
}
Still the program is not finding the saddle point.
Edit 3: Swapped M and N at the for loops. Still not getting expected results.
int Punto_de_silla_Mat(int matriz[M][N]){
int i=0,j=0,k=0;
int P_fila=0,P_columna=0, encontrado=0;
for(i=0;i<M;i++){
P_fila=i; //row
P_columna=j; //column
encontrado=0; //flag
for(j=0;j<N;j++){
if(matriz[i][j] < matriz[P_fila][P_columna]){
P_fila = i;
P_columna = j;}
for(k=0;k<M;k++){
if(matriz[k][P_columna] > matriz[P_fila][P_columna]){
encontrado = 1;
break;
}
}
}
}
if(encontrado == 1){
printf("El punto de silla es %d y esta en la fila %d y en la columna %d", matriz[P_fila][P_columna], P_fila, P_columna); //saddle point number + position
}else
printf("No hay punto de silla"); //there is no saddle point.
return 0;
Edit 4:
Changed the position of a } in the second for loop. The where two for loops executing at the same time. Nevertheless I'm getting the same wrong result.

Related

Linker command failed _main not found

I'm a college student beginner in C language. I was trying to run a program in which a matrix initializes with all values = 0, then the user enters values and finally the program searches a user input number inside a matrix, telling the row and column of said value.
But this error:
Undefined symbols for architecture x86_64:
"_main", referenced from:
implicit entry/start for main executable
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
won't stop coming up (I use visual studio code for mac) and I cannot get rid of it.
I've been searching all over internet but I can't find a solution and my teacher said "never heard of this error." I would appreciate your help :)
The function in which I need help is CercadorNumero.
I have two libraries, main library and functions library.
main:
#include <stdio.h>
#include <stdlib.h>
#define FILA 3
#define COLUMNA 3
void printMatriu (int entraMatriu[FILA][COLUMNA]);
int sumaFila (int matriu[][COLUMNA], int numFila);
int CercadorNumero (int buscaMatriu[FILA][COLUMNA], int valor, int *p, int *f); //p i f indicaran les cordenades
int main(int argc, char *argv[])
{
int matriu [FILA][COLUMNA];
for (int i=0; i<FILA; i++){
for (int j=0; j<COLUMNA; j++)
{
matriu[i][j]=0;
}
}
for (int i=0; i<FILA; i++)
{
for (int j=0; j<COLUMNA; j++)
{
do{
printf("Entrant el valor de la columna %d, fila %d: ", i+1, j+1);
scanf("%2d", &matriu[i][j]);
}while(matriu[i][j]<0 || matriu[i][j]>15);
}
printf("\n");
}
printMatriu(matriu);
int suma, numFila;
for(int i = 0; i < FILA; i++)
{
suma = sumaFila(matriu, i);
printf("La suma de la fila %d es: %d\n", i+1, suma);
}
int resultat, numCercar, columnaTrobada, filaTrobada;
do{
printf("Diga'm el numero que vols buscar: \n");
scanf("%d", &numCercar);
resultat = CercadorNumero (matriu, numCercar, &columnaTrobada, &filaTrobada);
if (resultat == 1)
{
printf("%d Trobat a les coordenades: %d %d", numCercar, columnaTrobada, filaTrobada);
} else
{
printf("valor no trobat");
}
} while(numCercar<0 || numCercar>100);
return 0;
}
functions:
#include <stdio.h>
#define FILA 3
#define COLUMNA 3
void printMatriu (int entraMatriu[FILA][COLUMNA]){
for (int i=0; i<FILA; i++){
for (int j=0; j<COLUMNA; j++){
printf("%2d ", entraMatriu[i][j]);
}
printf("\n");
}
}
int sumaFila (int matriu[][COLUMNA], int numFila)
{
int suma=0;
for (int j = 0; j < COLUMNA; j++)
{
suma = suma + matriu[numFila][j];
}
return suma;
}
int CercadorNumero (int buscaMatriu[FILA][COLUMNA], int valor, int *p, int *f)
{
int valorResultat = 0;
*p = 0;
*f = 0;
for (int i = 0; i < FILA; i++)
{
for (int j = 0; j < COLUMNA;)
{
if (buscaMatriu[i][j] == valor)
{
valorResultat = 1;
*p = i; //posició de memoria p guarda el valor de i en el moment que es igual al valor (fila)
*f = j; //posició de memoria f guarda el valor de j en el moment que es igual al valor (columna)
return valorResultat;
} else j++;
}
}
return valorResultat;
}

I can´t get out my array from a function to the main in c

In escribirVect(suma[MAX]), the compiler tells me that suma is undeclared but I declared it in my function sumarV, how can I use my variable 'suma' in main?
#include <stdio.h>
#define MAX 10
void leerVect(int vect[MAX]);
void escribirVect (int v[MAX]);
void sumarV (int vector1[MAX], int vector2[MAX]);
int main ()
{
int vector1[MAX], vector2[MAX];
printf("Introduzca los valores del primer vector: \n");
leerVect(vector1);
printf("Introduzca los valores del segundo vector: \n");
leerVect(vector2);
sumarV(vector1, vector2);
escribirVect(suma[MAX]); // here is the problem
return 0;
}
void leerVect(int v[MAX])
{
int i;
for (i=0; i<MAX; i++)
{
printf("Introduzca el valor de v[%d]: ", i);
scanf("%d", &v[i]);
}
}
void escribirVect (int v[MAX])
{
int i;
for (i=0; i<MAX; i++)
{
printf("El valor de la suma de el elemento v[%d] es: %d \n", i, v[i]);
}
}
void sumarV (int vector1[MAX], int vector2[MAX])
{
int suma[MAX], i; //here is the problem
for (i=0; i<MAX; i++)
{
suma[i]=vector1[i]+vector2[i]; //here is the problem
}
}
The problem disappears when I comment 'here is the problem' inside the code.
Declare suma in main and pass it to sumaV()
int main ()
{
int vector1[MAX], vector2[MAX], suma[MAX];
...
sumarV(vector1, vector2, suma);
Then, in the function
void sumarV (int vector1[MAX], int vector2[MAX], int suma[MAX])
{
int i;
for (i=0; i<MAX; i++)
{
suma[i]=vector1[i]+vector2[i];
}
}
Finally, don't pass the number of elements
escribirVect(suma[MAX]); // here is the problem
just pass the array, which decays into a pointer to the first element:
escribirVect(suma);

Function pointer debug error

When I run my code with Ctrl + F5 in Visual Studio I get this error:
Debug Error !
Program: name of my program bla bla
Run-Time Check Failure#2-S
My code
// fig07_26.cpp : definisce il punto di ingresso dell'applicazione console.
// Programma di ordinamente multifunzione che fa uso dei puntatori a funzioni
#include <stdio.h>
#define SIZE 10
//Prototipi di funzione
void bubble(int work[], const int size, int(*compare) (int a, int b));
int ascending(int a, int b);
int descending(int a, int b);
int main()
{
int order; // 1 per ordinamento ascendente 2 per quello discendente
int counter; // contatore
// inizializza il vettore a
int a[SIZE] = { 2,5,3,6,1,5,8,0,6,1 };
printf("Enter 1 to sort ascending order\n" "Enter 2 to sort descending order: \n");
scanf_s("%d", &order);
printf("\nData items printed in original order");
for (counter = 1; counter < SIZE; counter++) {
printf("%5d", a[counter]);
}
// Ordina il vettore in ordine ascendente; passa la funzione ascending
// come argomento per specificare l'ordinamento ascendente
if (order == 1) {
bubble(a, SIZE, ascending);
printf("\nData items in ascending order");
}
else
{
bubble(a, SIZE, descending);
printf("\nData items in descending order");
}
// visualizza il vettore ordinato
for (counter = 0; counter < SIZE; counter++) {
printf("%5d", a[counter]);
}
printf("\n");
return 0;
}
/** Bubble sort multifunzione: Il parametro compare è un puntatore a una funzione di comparazione che determina il senso
dell'ordinamento **/
void bubble(int work[], const int size, int (*compare) (int a, int b)) {
int pass; //contatore dei passaggi
int count; //contatore dei confronti
void swap(int *element1Ptr, int *element2Ptr); // prototipo
// ciclo per controllare i passaggi
for (pass = 1; pass < size; pass++) {
// ciclo per controllare i confronti
for (count = 0; count < size; count++)
{
// Scambia gli elementi adicenti se non sono in ordine
if ( (*compare) (work[count], work[count + 1]) ) {
swap(&work[count], &work[count + 1]);
}
}
}
}
// Scambia i valori nelle locazioni di memoria puntate da element1Ptr e element2Ptr
void swap(int *element1Ptr, int *element2Ptr) {
int hold; // variabile temporanea
hold = *element1Ptr;
*element1Ptr = *element2Ptr;
*element2Ptr = hold;
}
// Determina se gli elementi non sono in ordine rispetto a un ordinamento ascendente
int ascending(int a, int b) {
return b < a; // effettua uno scambio se b è minore di a
}
// Determina se gli elementi sono in ordine rispetto a un ordinamento discendente
int descending(int a, int b) {
return b > a;
}

Getting an error using a second BCast with MPI in C

Im having troubles with the following code
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
//1 mostrar lista
//2 borrar elementos
//3 ordenar lista
//4 añadir elemento
int main(int argc,char**argv){
int rank;
int *list; //Lista
int *liste; //Lista encargados
int *perm; //Permutaciones
int *capa; //Capacidad
int size;
int i;
int aux;
const int root = 0;
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&size);
if(rank==root){
perm = (int*)malloc(size*sizeof(int));
capa = (int*)malloc(size*sizeof(int));
for(i=0;i<size;i++){
scanf("%d",&aux);
capa[i]=aux;
}
for(i=0;i<size;i++){
scanf("%d",&aux);
perm[i]=aux;
}
}
//printf("\n[%d]: Antes de Bcast: %d %d %d %d\n",rank,capa[0],capa[1],capa[2],capa[4]);
MPI_Bcast(&capa[0],size,MPI_INT,root,MPI_COMM_WORLD);
MPI_Bcast(&perm[0],size,MPI_INT,root,MPI_COMM_WORLD);
//MPI_Bcast(&aux,1,MPI_INT,root,MPI_COMM_WORLD);
printf("\n[%d]: Despues de Bcast capa: %d %d %d %d\n",rank,capa[0],capa[1],capa[2],capa[3]);
printf("\n[%d]: Despues de Bcast perm: %d %d %d %d\n",rank,perm[0],perm[1],perm[2],perm[3]);
MPI_Finalize();
return 0;
}
Well there is nothing special, Im just trying to Bcast two arrays of ints (for now Im trying with 4-lenght strings of ints, that why the last printfs are statics).
Anyway, I tried first just with the "capa" string and it worked, but when I tried it with both strings, Im getting a segmentation fault error but I dont know why, both string are the same size, the only differences are their values.
EDIT:
Just changed the code to this and worked:
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
//1 mostrar lista
//2 borrar elementos
//3 ordenar lista
//4 añadir elemento
int main(int argc,char**argv){
int rank;
int *list; //Lista
int *liste; //Lista encargados
int *perm; //Permutaciones
int *capa; //Capacidad
int size;
int i;
int aux;
const int root = 0;
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&size);
perm = (int*)malloc(size*sizeof(int));
capa = (int*)malloc(size*sizeof(int));
if(rank==root){
for(i=0;i<size;i++){
scanf("%d",&aux);
capa[i]=aux;
}
for(i=0;i<size;i++){
scanf("%d",&aux);
perm[i]=aux;
}
}
//printf("\n[%d]: Antes de Bcast: %d %d %d %d\n",rank,capa[0],capa[1],capa[2],capa[4]);
MPI_Bcast(&capa[0],size,MPI_INT,root,MPI_COMM_WORLD);
MPI_Bcast(&perm[0],size,MPI_INT,root,MPI_COMM_WORLD);
//MPI_Bcast(&aux,1,MPI_INT,root,MPI_COMM_WORLD);
printf("\n[%d]: Despues de Bcast capa: %d %d %d %d\n",rank,capa[0],capa[1],capa[2],capa[3]);
printf("\n[%d]: Despues de Bcast perm: %d %d %d %d\n",rank,perm[0],perm[1],perm[2],perm[3]);
MPI_Finalize();
return 0;
}

Programming Gaussian elimination with total pivoting (in c)

I'm programming in c the gaussian elimination with total pivoting of a matrix nxn, but when I solve the system, it comes out with a lot of errors (if the solution is 5.23, it writes me 4.88, for example). The numbers are approximated, but not correct. I think that the error is in the gaussian elimination code, and not in the solution of the systems (backward and forward substitution). Anyway, I will post it, maybe I'm wrong and the mistake is in there:
void eliminaciogaussianapivotatgetotal(int n, double a[][max], double m[][max], double p[][max], double q[][max])
{
int i,j,k,c,f;
double l,t,auxi;
for(k=0;k<(n-1);k++)
{
f=k;
c=k;
for (i=k;i<n;i++)
{
for (j=k;j<n;j++)
{
if (fabs(a[i][j])>a[f][c])
{
f=i;
c=j;
}
}
}
printf("%d,%d\n",f,c);
for (j=0;j<n;j++) //Canvia la fila de la matriu introduïda
{
l=0.;
l=a[k][j];
a[k][j]=a[f][j];
a[f][j]=l;
}
for (j=0;j<n;j++) //Canvia la fila de la matriu P
{
t=0;
t=p[k][j];
p[k][j]=p[f][j];
p[f][j]=t;
}
for (i=0; i<n; i++)//Canvia la columna de la matriu introduïda
{
l=0;
l=a[i][k];
a[i][k]=a[i][c];
a[i][c]=l;
}
for (i=0; i<n; i++)//Canvia la columna de la matriu Q
{
t=0;
t=q[i][k];
q[i][k]=q[i][c];
q[i][c]=t;
}
if (fabs(a[k][k])<=tol)//Algun pivot pel camí és 0.
{
printf("____________________________________________________\n");
printf("ERROR: S'ha trobat un pivot massa petit o 0.\n");
exit(0);
}
for(i=k+1;i<n;i++)
{
auxi=0;
auxi=(a[i][k]/a[k][k]);
for (j=k; j<n; j++)
{
a[i][j]=a[i][j]-(auxi*a[k][j]);
}
m[i][k]=auxi;
}
if (k>0)
{
for (j=0;j<n;j++) //Canvia la fila de la matriu introduïda
{
l=0;
l=m[k][j];
m[k][j]=m[f][j];
m[f][j]=l;
}
for (i=0;i<n;i++) //Canvia la fila de la matriu introduïda
{
l=0;
l=m[i][k];
m[i][k]=m[i][c];
m[i][c]=l;
}
}
}
// if(fabs(a[n-1][n-1])<=tol) //El sistema no és CD (no té solució o en té infinites).
// {
// printf("____________________________________________________\n");
// printf("ERROR: La matriu no és invertible => El sistema no té solució única!\n");
// exit(0);
// }
}
And here the backward and forward substitution:
void resoluciosistematriangularinferior(int n, double a[][max], double b[], double x[])
{
int i, j;
double sum;
x[0]=b[0]/a[0][0];
for (i=1; i<n; i++)
{
sum=0;
for(j=0; j<i; j++)
{
sum=sum+((a[i][j])*(x[j]));
}
x[i]=1/a[i][i]*(b[i]-sum);
}
}
void resoluciosistematriangularsuperior(int n, double a[][max], double b[], double x[])
{
int i, j;
double sum;
x[n-1]=b[n-1]/a[n-1][n-1];
for (i=(n-2); i>=0; i--)
{
sum=0;
for(j=i+1; j<n; j++)
{
sum=sum+((a[i][j])*(x[j]));
}
x[i]=1/a[i][i]*(b[i]-sum);
}
}
All the matrices are declared as nameofmatrix[max][max], where max is a define of 150 on preprocessor. Thank you for the help, I don't know what to do.

Resources