create a matrix with specific conditions - c

I would like to create a matrix with these specifics
text of exercise
write a program that reads a number k > 0 and a permutation of the first K numbers (from 0 to k-1) that does not fix any element and produce (printing on consecutive lines) permutations p0, . . . , ph such that (1) p0 is permutation given in input; (2) fro every i > 0, pi is the smallest permutation of K cthat does not fix any element and does not collide with any other permutation from p0 and pi−1. We say that 2 permutations p1, p2 ok
K collides if exists and index i from 1 to k such that p1(i) = p2(i).
my ideas i wanted to create a k*k matrix amd the first row will be the imput of a vector i will declare. I tought to fill the matrix in these way : let's take a specific element v[i][j]
v[i][j]is in the matrix if 1)v[k][j] from k =0,...,i-1 is different from v[i][j],1)v[i][k] from k =0,...,i-1 is different from v[i][j],v[i][j] is different from i , and from the remaining possibilities for v[i][j] it is the minimum from the remainin number 0,...k-1
code implementations
#include <stdio.h>
#include <stdlib.h>
#define N 50
typedef int matrix[N][N];
int min(int vector[],int n)
{
int i;
int p=0;
int min=vector[0];
for(i=0; i<n;i++)
{
if (vector[i]<=min)
{
min=vector[i];
p=i;
}
}
return min;
}
int main()
{
int k;
printf("\n insert a number ");
scanf("%d",&k);
int v[k][k];//creation of matrix I wanted
int input[k];//first row
int arrayindex[k]={0};// array from 0 to k
for(int u=0; u<k;u++)
{
arrayindex[u]=u;
}
printf("insert component of vector:");
for(int l=0;l<k;l++)
{
printf("input[%d]= ",l);
scanf("%d",&input[l]);
}
//print vector
for(int l=0;l<k;l++)
{
printf("%d",input[l]);
}
printf("\n\n");
// copy first row
for(int j=0;j<k;j++)
{
v[0][j]=input[j];
}
//printf of first row
for(int j=0;j<k;j++)
{
printf("\nv[0][%d]=%d ",j,v[0][j]);
}
//try to fill matrix
for(int i=1; i<k;i++)
{
for(int j=0;j<k;j++)
{
if (j=0){
v[i][j]!=v[i-1][j];
v[i][j]!=j;
v[i][j]=min(arrayindex,k);}
if(j!=0)
v[i][j]!=v[i-1][j];
v[i][j]!=v[i][j-1];
v[i][j]!=j;
v[i][j]=min(arrayindex,k);
}
}
//print of matrix
printf("\n the matrix is:\n ");
for(int i=0; i<k;i++)
{ printf("\n");
for(int j=0;j<k;j++)
{
printf("%d",v[i][j]);
}
}
return 0;
}
the problem in this code is in the section called try to fill matrix . When I compile nothing appear on the screen .Where is the problem ? is at least idea correct?

Related

How to create loops for ordering vectors

I have a homework problem that asks for my code to read a 10-length vector, order it in ascendant order and then print it. I'm trying to do this using a variable int k as a countable index, where the code verifies whether a particular position in the vector is greater than the other positions, and adds 1 to k for each smaller variable. Then, I create a second vector, and atrribute for its kth position this value of the first vector.
The compilation isn't pointing out any mistakes. The code runs, I inform the 10 values of the vector, then it returns a big number and crashes.
Could anyone help me? Thanks in advance.
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
int main ()
{
setlocale(LC_ALL, "Portuguese");
//creates two double vectors
double v[10], w[10];
//creates a int variable to be a countable index
int k = 0;
//asks for the user to inform the values of the vector
for (int i=0; i<=9; i++)
{
printf("Digite um número:\n");
scanf("%lf", &v[i]);
}
//Here, I create this loop to verify whether each position of the vector v is greater than the other positions.
for (int j=9; j>=0; j--)
{
//For the case j=9, I verify if it is greater than all the predecessor values, and add 1 to k for each case
if (j==9)
{
for (int t=j-1; t>=0; t--)
{
if (v[j]>v[t])
{
k+=1;
}
}
//I attribute this value of v to the kth position of the new vector, and restart the countable index
w[k]=v[j];
k=0;
continue;
}
//I do the same for the case in which j=0, verifying whether it is greater than the subsequent values
else if (j==0)
{
for (int s=j+1; s<=9; s++)
{
if (v[j]>v[s])
{
k+=1;
}
}
w[k]=v[j];
k=0;
continue;
}
//For all the other values of the vector, I test both whether they are greater than the
//predecessors and the subsequent values, and add 1 to k for each case
else
{
for (int t=j-1; t>=0; t--)
{
if (v[j]>v[t])
{
k+=1;
}
}
for (int s=j+1; s<=9; s--)
{
if (v[j]>v[s])
{
k+=1;
}
}
//I attribute this value to the kth position of the new vector and restart the countable index
w[k]=v[j];
k=0;
}
//Here my loop ends
}
//I print the new vector
for (int p=0; p<=9; p++)
{
printf(" %lf ",w[p]);
}
system("pause");
return 0;
}
for (int s=j+1; s<=9; s--) should have s++. I don't see anything else wrong but I'll check with gdb if that doesn't fix it.

C language. How to find the maximum minimum. (2D arrays)

I have written code that allows you to enter one dimension of a NxN double array. It will then print random numbers in a 2D array and it finds the maximum and minimum number of each row. It then prints them and their coordinates (row and column).
ATTENTION!!!!
I have altered my code in such a way that it finds the minimum number of the maximum. I now don't know how to find it's coordinates
My code is as follows:
int N, i, j, min=1000, max, m , o;
time_t t;
int masyvas[100][100], minmax[100];
printf("Enter one dimension of a NxN array\n");
scanf("%d", &N);
srand((unsigned) time(&t));
for (i=0; i<N; i++)
{
for (j=0; j<N; j++)
{
masyvas[i][j] = rand() % 10;
printf("%4d", masyvas[i][j]);
}
printf("\n");
}
int k, l, idkeymax, idkeymin;
for(k=0; k<N; k++)
{
max=-1000;
for(l=0; l<N; l++)
{
if(max<masyvas[k][l])
{
max=masyvas[k][l];
}
}
minmax[k]=max;
}
for(m=0; m<N; m++)
{if(minmax[m]<min)
min=minmax[m];
}
printf("maziausias skaicius tarp didziausiu yra %d eiluteje %d stulpelyje %d\n",min);
Here's the pseudo code of what you need to do.
for row in grid {
row_max = max_in_row(row)
grid_min = min(grid_min, row_max)
}
Step one is to write a routine that finds the max and location in a list. You could do this as one big function, but it's much easier to understand and debug in pieces.
You also need the index where it was found. Since C can't return multiple values, we'll need a struct to store the number/index pair. Any time you make a struct, make routines to create and destroy it. It might seem like overkill for something as trivial as this, but it will make your code much easier to understand and debug.
typedef struct {
int num;
size_t idx;
} Int_Location_t;
static Int_Location_t* Int_Location_new() {
return calloc(1, sizeof(Int_Location_t));
}
static void Int_Location_destroy( Int_Location_t* loc ) {
free(loc);
}
Now we can make a little function that finds the max number and position in a row.
static Int_Location_t* max_in_row(int *row, size_t num_rows) {
Int_Location_t *loc = Int_Location_new();
/* Start with the first element as the max */
loc->num = row[0];
loc->idx = 0;
/* Compare starting with the second element */
for( size_t i = 1; i < num_rows; i++ ) {
if( row[i] > loc->num ) {
loc->num = row[i];
loc->idx = i;
}
}
return loc;
}
Rather than starting with some arbitrary max or min, I've used an alternative technique where I set the max to be the first element and then start checking from the second one.
Now that I have a function to find the max in a row, I can now loop over it, get the max of each row, and compare it with the minimum for the whole table.
int main() {
int grid[3][3] = {
{10, 12, 15},
{-50, -15, -10},
{1,2,3}
};
int min = INT_MAX;
size_t row = 0;
size_t col = 0;
for( size_t i = 0; i < 3; i++ ) {
Int_Location_t *max = max_in_row(grid[i], 3);
printf("max for row %zu is %d at %zu\n", i, max->num, max->idx);
if( max->num < min ) {
min = max->num;
col = max->idx;
row = i;
}
Int_Location_destroy(max);
}
printf("min for the grid is %d at row %zu, col %zu\n", min, row, col);
}
I used a different technique for initializing the minimum location, because getting the first maximum would require repeating some code in the loop. Instead I set min to the lowest possible integer, INT_MAX from limits.h which is highest possible integers. This allows the code to be used with any range of integers, there are no restrictions. This is a very common technique when working with min/max algorithms.

Array of structure changes the contents itself

I am currently working on a simple code to store and display top-right triangular matrix. Well, everything was fine till I tried to input 4x4 matrix structure and gave the input. The first array of structure's (called a) last value changed although I did not put any code to change ANY of the values in a. It happens in the mReorder() function. Then I tried some try-and-errors find out the problem in the 3rd row of mReorder() function. I wonder why and how to solve it.
Here is my complete code:
#include<stdio.h>
//CMO fashion
typedef struct
{
int row;
int col;
int val;
}term;
#define MAX_TERMS 10
term a[MAX_TERMS], b[MAX_TERMS];
void mReorder(void);
int main()
{
int n, i, j;
printf("Enter the number of rows: ");
scanf("%d", &n);
if (n<1 || n>MAX_TERMS)
{
printf("\nInvalid number of rows!!");
exit(0);
}
i=nCount(n);
mRead(n,i);
for (j=0; j<i+1; j++) printf("\n%d\t%d\t%d", a[j].col, a[j].row, a[j].val);
mReorder();
for (j=0; j<i+1; j++) printf("\n%d\t%d\t%d", a[j].col, a[j].row, a[j].val);
printf("\n");
for (j=0; j<i+1; j++) printf("\n%d\t%d\t%d", b[j].col, b[j].row, b[j].val);
mDisplay();
return 0;
}
void mReorder(void)
{
int i, j, k, m=1;
b[0].col=a[0].col;
b[0].row=a[0].row;
b[0].val=a[0].val;
for(i=0; i<a[0].col; i++)
for (j=1; j<=a[0].val; j++)
if (a[j].row==i)
{
b[m].col=a[j].col;
b[m].row=a[j].row;
b[m].val=a[j].val;
m++;
}
}
void mDisplay(void)
{
int i, j, k, m=1;
printf("\nThe resulting matrix is:\n");
for (i=0; i<b[0].col; i++)
{
//printf("\na");
for (k=0; k<i; k++) printf("%5c", '-');
for (j=i; j<b[0].col; j++)
{
printf("%5d", b[m].val);
m++;
}
printf("\n");
}
}
void mRead(int n, int x)
{
int i, j, m=1, val;
printf("\nEnter %d elements of the matrix: \n", x);
a[0].row=a[0].col=n;
a[0].val=x;
for (i=0; i<n; i++)
{
for (j=0; j<=i; j++)
{
scanf("%d", &val);
a[m].row=j;
a[m].col=i;
a[m].val=val;
m++;
}
}
}
int nCount(int n)
{
if (n==1)
return 1;
return (n+nCount(n-1));
}
Can you explain what's going on here?
You allocate enough space for 10 term items, but nCount(4) returns 10, and nCount(5) returns 15, etc. If you specify a value bigger than 4, you overflow your array boundaries, leading to undefined behaviour — which is something to be avoided at all costs. In practice, one of your two arrays tramples over the other, but what happens when you access the other array out of bounds is entirely up to the compiler. It may appear to work; it may crash horribly; it may corrupt other data structures.
Nominally, since you allocate 10 elements in the arrays a and b, you should be OK with the 4x4 data, but in mRead(), you set m = 1 to start with, so you end up writing to a[10] in the last iteration of the loop, which is outside the bounds of the array. Remember, C arrays are indexed from 0, so an array defined as SomeType array[N]; has elements from array[0] to array[N-1].
Note that you can rewrite nCount() as a simple (non-recursive) function:
static inline int nCount(int n) { return (n + 1) * n / 2; }
(which would need to appear before it is called, of course). Or, if you're stuck using an archaic compiler that doesn't support C99 or C11, drop the inline keyword.

Transfering a 2-dimensional array into a single dimension array

I'm trying to make a program in C that transfers a 2-dimensions-array(a matrix to be particular) into a single-dimension-array. For example, if we have a matrix with L lines and C columns, it should turn into a a single line newL=L*C. Therefore, if the matrix has 3 lines and 4 columns, the new array will have 3*4=12 as its size.
The matrix should turn to this:
1 2
--> 1 2 3 4
3 4
The problem I'm facing right now, is how to assign the matrix to the array without having random values or repeated values.
The piece of code I'm concerned with, goes like this:
for(k=1;k<=t;k++)
{
for(i=1;i<=l;i++)
{
for(j=1;j<=c;j++)
{
v[k]=m[i][j];
}
}
}
k,i and j are counters of the matrix(2-dimensions-array) and the the array. two of which; i and j, are counters for the matrix and k is the array's counter. Notice that each one of them starts from 1 and goes to its size and in this size I will use 2 lines and 2 columns for the matrix therefore the array will have a size of 4(2*2).
l is the number of lines in the array.
c is the number of colunms in the array.
t is the size of the array. t=l*c
Executing the code gives me this as a return:
1 2
--> 4 4 4 4
3 4
Simply said, the piece of code will ALWAYS give the last value of the matrix to the array. So if I replace 4 with 5 in the matrix, the array will have 5 5 5 5.
EDIT:
Here is the full code to understand what I'm trying to do:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int c,i,j,l,k,t;
printf("Donner le nombres des lignes: ");
scanf("%d",&l);
printf("Donner le nombres des colonnes: ");
scanf("%d",&c);
int m[l][c];
t=l*c;
int v[t];
for(i=0;i<l;i++)
{
for(j=0;j<c;j++)
{
printf("Donner m[%d][%d]: ",i+1,j+1);
scanf("%d",&m[i][j]);
}
}
for(i=0;i<l;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",m[i][j]);
}
printf("\n");
}
printf("\n\n\n\n");
for(k=1;k<=t;k++)
{
for(i=1;i<=l;i++)
{
for(j=1;j<=c;j++)
{
v[k]=m[i][j];
}
}
}
for(k=0;k<t;k++)
{
printf("%d\t",v[k]);
}
system("pause");
}
Thank you guys for the help, I found the correct way to do it.
You need not the outer loop
Array indices are zero-based in C
Thus, we have:
for(k = 0, i = 0; i < o; i++)
{
for(j = 0; j < p; j++)
{
v[k++] = m[i][j];
}
}
where o and p - dimensions of the matrix m
If we have a multidimensional array like this:
int nums[3][3];
And we have:
int all[9];
And we've got:
int a, b;
We'll reference each of the nums like this:
nums[a][b];
Now think of what the values of a and b will actually be:
for (a = 0; a < 3; a++) {
for (b = 0; b < 3; b++)
all[((a * 3) + b)] = nums[a][b];
}
This will work so long as you multiply a with the number of elements it will iterate:
int nums[5][5];
int all[25];
int a, b;
for (a = 0; a < 5; a++) {
for (b = 0; b < 5; b++)
all[((a * 5) + b)] = nums[a][b];
}
You mention your question is "how to I fix the code?" I think plenty of people have given you the correct answer. This is your code along with the corrected code.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int c,i,j,l,k,t;
printf("Donner le nombres des lignes: ");
scanf("%d",&l);
printf("Donner le nombres des colonnes: ");
scanf("%d",&c);
int m[l][c];
t=l*c;
int v[t];
for(i=0;i<l;i++)
{
for(j=0;j<c;j++)
{
printf("Donner m[%d][%d]: ",i+1,j+1);
scanf("%d",&m[i][j]);
}
}
for(i=0;i<l;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",m[i][j]);
}
printf("\n");
}
printf("\n\n\n\n");
/* corrected code below */
k = 0;
for(i=0;i<l;i++)
{
for(j=0;j<c;j++)
{
v[k]=m[i][j];
k++;
}
}
/* corrected code above */
for(k=0;k<t;k++)
{
printf("%d\t",v[k]);
}
system("pause");
}
As long as the new array is the correct size, something like the following should work:
k=0;
for(i=0;i<l;i++){
for(j=0;j<c;j++){
v[k]=m[i][j];
k++;
}
}
Essentially, you are traversing over the matrix (your lines and columns--as you put it) and at the same time increasing the position (k) in the new array where you want that value to be put.
This:
for(k=1;k<=t;k++)
for(i=1;i<=l;i++)
for(j=1;j<=c;j++)
v[k]=m[i][j];
does not do what you think. Think about when you first loop through the j part, you will be setting all the 0th element of v the entire time, finally the last value you set will stick (ie, the one in position 1, 1 which happens to be 4). Then you will increment k to 1 and repeat it again, resulting in all 4's. You want this:
for(i = 0; i < l; i++)
for(j = 0; j < c; j++)
v[i*l+j] = m[i][j]; // i*l + j gives you the equivelent position in a 1D vector.
Make sure your v vector is the right size ie. int v[l*c];. Also remember that in c zero indexing is used.If you really do need 1 based indexing (which you dont ...) then do this:
int k = 1;
for(i = 1; i <= l; i++)
for(j = 1; j <= c; j++)
v[k++]=m[i][j];
But remember that this will make any further operations on this vector Gross. So dont do this ....
If you just want to access the matrix elements as a single dimension array, you could declare an int pointer v:
int m[3][4];
int *v = (int*)m;
// then access for example m[1][1] as v[5]
Or, to actually copy the array, use a double for (as in the other answers), a single for like below
int vv[12];
for(i = 0; i < 12; i++)
vv[i] = m[i/4][i%4];
or just use memcpy:
memcpy(vv, m, 12*sizeof(int));

Sorting 2d matrix cols and rows in C

Given set two - dimensional integers. The array consists of 5 rows and 10 columns.
Each value in the system is a random number between 0 and 20.
Have to write a program that performs the sorting of the array values as follows:
First there arrange the values in each column so that they are sorted in ascending order (top to bottom), then - so there can sort the columns right "comes right" by comparing pairs of values in different columns in the same row (a "comparison lexicography"): comparing two values ​​in two columns in the first row, if they are the same compared to the values in the second row, and so on, and accordingly change the order of columns (see example in the third printing of the array, below).
To display the array before sorting and after each of the two phases of the emergency.
for example :
I stuck with the sorting of the each cols. I don't get the sorting i want. I would like to get your help please.
This is my code:
#include "stdio.h"
#include "conio.h"
#include "malloc.h"
#include "stdlib.h"
#define N 5
#define M 10
#define LOW 0
#define HIGH 20
void initRandomArray(int arr[N][M]);
void printArray(int arr[N][M]);
void SortInColumn(int arr[N][M],int m);
int main()
{
int arr[N][M];
int m;
m=M;
srand((unsigned)time(NULL)); //To clear the stack of Random Number
initRandomArray(arr);
printf("Before sorting:\n");
printArray(arr);
printf("Sorting elements in each column:\n");
SortInColumn(arr,M);
system("pause");
return 0;
}
void initRandomArray(int arr[N][M])
{
int i,j;
for (i=0 ; i<N ; i++)
for (j=0 ; j<M ; j++)
{
arr[i][j]=LOW+rand()%(HIGH-LOW+1);
}
}
void printArray(int arr[N][M])
{
int i,j;
for (i=0 ; i<N ; i++)
{
for (j=0 ; j<M ; j++)
printf("%d ", arr[i][j]);
printf("\n");
}
}
void SortInColumn(int arr[][M],int m)
{
int i,j;
int temp;
for( i=m-1 ; i>=0 ; i--)
{
for(j=0; j<N-1; j++)
if (arr[i][j]>arr[i][j+1]) // compare adjacent item
{
temp=arr[i][j];
arr[i][j]=arr[i][j+1];
arr[i][j+1]=temp;
}
}
for (i=0 ; i<N ; i++)
{
for (j=0 ; j<M ; j++)
printf("%d ", arr[i][j]);
printf("\n");
}
}
This is mine, and it runs and gives the correct answer.
Basically, you did two things wrong.
you need three loops instead of two. The outer loop loops around each columns. the second loop makes sure you compare each column N-1 times since for each run you get one item in the right place. The inner loop do the adjacent comparison.
you need to change the comparison between arr[i][k] and arr[i][k+1] to arr[i][k] to arr[i+1][k]. Because you want to compare them in the same column, you hold the value k (column) unchanged and change the rows i.
void SortInColumn(int arr[][M],int m)
{
int i,j,k;
int temp;
for( k=0 ; k<m ; ++k)
{
for(j=0; j<N-1; j++)
{
for(i=0; i < N-1 - j; i++)
{
if (arr[i][k]>arr[i+1][k]) // compare adjacent item
{
temp=arr[i][k];
arr[i][k]=arr[i+1][k];
arr[i+1][k]=temp;
}
}
}
}
}
BTW, this algorithm is very bad in performance in general. You may want to try something else.
Let's look at your SortInColum function. I've changed the formatting to get a better understanding of what's going on, and renamed some variables.
void SortInColumn(int arr[][M],int m)
{
int row,col;
int temp;
for( row=m-1 ; row>=0 ; row--) // foreach row
{
for(col=0; col<N-1; col++) { // foreach column
if (arr[row][col]>arr[row][col+1]) { // comparing adjacent entries
// in different cols? Why?
temp=arr[row][col];
arr[row][col]=arr[row][col+1];
arr[row][j+1]=temp;
}
}
printArray(arr);
}
This function (given some changes) will sorts a single column, you can then call this for each column. Hopefully this gives you a good starting point.

Resources