So I have 2d array filled with random numbers .For example:
#define d 4
int main(void)
{
int a[d][d];
int primary[d], secondary[d];
size_t i, j;
srand(time(NULL));
/* fill array with random numbers */
for (i = 0; i < d; i++)
for (j = 0; j < d; j++)
a[i][j] = rand() % 100;
/* save diagonals */
for (i = 0; i < d; i++)
{
primary[i] = a[i][i];
secondary[i] = a[d - (i + 1)][i];
How to mirror horizontally diagonals?
For example:
1 0 0 2
0 3 4 0
0 5 6 0
7 0 0 8
8 0 0 7
0 6 5 0
0 4 3 0
2 0 0 1
Task is to print main matrix and then print matrix with mirrored diagonals however i got no ideas how cycle for this should look like.
I thought about cycle for rotating matrix for 180 degrees however I will loose the positions of elements that are not included to the diagonals.
Or can i save diagonal and then reverse it somehow.
Here is code for matrix and diagonal what should i do now.
Hope for your help.
One of approaches is the following
#include <stdio.h>
#define N 4
int main(void)
{
int a[N][N] =
{
{ 1, 0, 0, 2 },
{ 0, 3, 4, 0 },
{ 0, 5, 6, 0 },
{ 7, 0, 0, 8 }
};
for ( size_t i = 0; i < N; i++ )
{
for ( size_t j = 0; j < N; j++ ) printf( "%d ", a[i][j] );
printf( "\n" );
}
printf( "\n" );
for ( size_t i = 0; i < N * N / 2; i++ )
{
int tmp = a[i / N][i % N];
a[i / N][i % N] = a[(N * N - i - 1) / N][(N * N - i - 1) % N];
a[(N * N - i - 1) / N][(N * N - i - 1) % N] = tmp;
}
for ( size_t i = 0; i < N; i++ )
{
for ( size_t j = 0; j < N; j++ ) printf( "%d ", a[i][j] );
printf( "\n" );
}
printf( "\n" );
return 0;
}
The program output is
1 0 0 2
0 3 4 0
0 5 6 0
7 0 0 8
8 0 0 7
0 6 5 0
0 4 3 0
2 0 0 1
The same can be written using pointers. For example
#include <stdio.h>
#define N 4
int main(void)
{
int a[N][N] =
{
{ 1, 0, 0, 2 },
{ 0, 3, 4, 0 },
{ 0, 5, 6, 0 },
{ 7, 0, 0, 8 }
};
for ( size_t i = 0; i < N; i++ )
{
for ( size_t j = 0; j < N; j++ ) printf( "%d ", a[i][j] );
printf( "\n" );
}
printf( "\n" );
for ( int *first = ( int * )a, *last = ( int * )a + N * N;
first < last;
++first, --last )
{
int tmp = first[0];
first[0] = last[-1];
last[-1] = tmp;
}
for ( size_t i = 0; i < N; i++ )
{
for ( size_t j = 0; j < N; j++ ) printf( "%d ", a[i][j] );
printf( "\n" );
}
printf( "\n" );
return 0;
}
Related
I have to solve it in C language. I have arrays with n integers. L and U are lower and upper bound. I have to reverse numbers in array which is in [L,U]. I tried it by this way, but in some cases the answer is wrong. What mist be changed in the code? Or is there any other logic to complete the task?
#include <stdio.h>
int main() {
int x, arr[100], n, l, u, a, temp, temp1;
scanf("%d%d%d", &n, &l, &u);
for (int i = 0; i < n; i++) {
scanf("%d", &x); // read elements of an array
arr[i] = x;
}
a = n / 2;
for (int i = 0; i < a; i++) {
for (int j = a; j < n; j++) {
if (arr[i] >= l && arr[i] <= u) {
if (arr[j] >=l && arr[j] < u) {
temp = arr[j];
temp1 = arr[i];
arr[i] = temp;
arr[j] = temp1;
}
}
}
}
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
}
sample input:
10(number of integers) -7(lower bound) 5(upper bound)
-10 -9 5 -2 -3 7 10 6 -8 -5
sample output:
-10 -9 -5 -3 -2 7 10 6 -8 5
my output:
-10 -9 -5 -2 -3 7 10 6 -8 5
There is an O(N) solution that does not require nesting of loops.
First, with the code as you as you have it, declare an additional array and some other helper variables that keeps track of what indices need to be swapped.
int left, right;
int swaplist[100] = {0};
int swapcount = 0;
Your can keep your initial intake loop exactly as you have it, but amended to append the index of the newly scanned value to the swaplist array if the value is between the lower and upper bounds.
for (int i = 0; i < n; i++) {
scanf("%d", &x); // read elements of an array
arr[i] = x;
if ((x >= l) && (x <= u)) {
swaplist[swapcount++] = i;
}
}
Then a single loop to iterate over "swaplist" and do the swaps against the original array.
left = 0;
right = swapcount-1;
while (left < right) {
int leftindex = table[left];
int rightindex = table[right];
int tmp = arr[leftindex];
arr[leftindex] = arr[rightindex];
arr[rightindex] = tmp;
left++; right--;
}
You made a valiant attempt. Your nested for() loops are appropriate for some kinds of sorting algorithms, but not for what seems to be the purpose of this task.
From the sample input and desired output, you really want to establish a 'bracket' at either end of the array, then shift both toward the centre, swapping elements whose value happens to satisfy low <= n <= high value. (In this case, -7 <= n <= 5).
Here's a solution:
#include <stdio.h>
int swap( int arr[], size_t l, size_t r ) { // conventional swap algorithm
int t = arr[l];
arr[l] = arr[r];
arr[r] = t;
return 1;
}
int main() {
int arr[] = { -10, -9, 5, -2, -3, 7, 10, 6, -8, -5, }; // your data
size_t i, sz = sizeof arr/sizeof arr[0];
for( i = 0; i < sz; i++ ) // showing original version
printf( "%d ", arr[i] );
putchar( '\n' );
#define inRange( x ) ( -7 <= arr[x] && arr[x] <= 5 ) // a good time for a macro
size_t L = 0, R = sz - 1; // 'L'eft and 'R'ight "brackets"
do {
while( L < R && !inRange( L ) ) L++; // scan from left to find a target
while( L < R && !inRange( R ) ) R--; // scan from right to find a target
} while( L < R && swap( arr, L, R ) && (L+=1) > 0 && (R-=1) > 0 );
for( i = 0; i < sz; i++ ) // showing results
printf( "%d ", arr[i] );
putchar( '\n' );
return 0;
}
-10 -9 5 -2 -3 7 10 6 -8 -5
-10 -9 -5 -3 -2 7 10 6 -8 5
If I have understood the assignment correctly you need to reverse elements of an array that satisfy some condition.
If so then these nested for loops
for (int i = 0; i < a; i++) {
for (int j = a; j < n; j++) {
if (arr[i] >= l && arr[i] <= u) {
if (arr[j] >=l && arr[j] < u) {
temp = arr[j];
temp1 = arr[i];
arr[i] = temp;
arr[j] = temp1;
}
}
}
}
do not make sense.
It is enough to use only one for loop as shown in the demonstration program below.
#include <stdio.h>
int main( void )
{
int a[] = { 1, 10, 2, 3, 20, 4, 30, 5, 40, 6, 7, 50, 9 };
const size_t N = sizeof( a ) / sizeof( *a );
for (size_t i = 0; i < N; i++)
{
printf( "%d ", a[i] );
}
putchar( '\n' );
int l = 10, u = 50;
for (size_t i = 0, j = N; i < j; i++ )
{
while (i < j && !( l <= a[i] && a[i] <= u )) ++i;
if (i < j)
{
while (i < --j && !( l <= a[j] && a[j] <= u ));
if (i < j)
{
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
}
for (size_t i = 0; i < N; i++)
{
printf( "%d ", a[i] );
}
putchar( '\n' );
}
The program output is
1 10 2 3 20 4 30 5 40 6 7 50 9
1 50 2 3 40 4 30 5 20 6 7 10 9
You could write a separate function as for example
#include <stdio.h>
void reverse_in_range( int a[], size_t n, int low, int upper )
{
for (size_t i = 0, j = n; i < j; )
{
while (i < j && !( low <= a[i] && a[i] <= upper )) ++i;
if (i < j)
{
while (i < --j && !( low <= a[j] && a[j] <= upper ));
if (i < j)
{
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
++i;
}
}
}
}
int main( void )
{
int a[] = { 1, 10, 2, 3, 20, 4, 30, 5, 40, 6, 7, 50, 9 };
const size_t N = sizeof( a ) / sizeof( *a );
for (size_t i = 0; i < N; i++)
{
printf( "%d ", a[i] );
}
putchar( '\n' );
reverse_in_range( a, N, 10,50 );
for (size_t i = 0; i < N; i++)
{
printf( "%d ", a[i] );
}
putchar( '\n' );
}
Thanks for everyone help. I read all of them, but I found another way to solve this problem. I will write it just in case. (some variable names are random, so in case of questions, comment).
#include <stdio.h>
int main() {
int x, main[100], n, l, u, a = 0, arr[100], temp, m = 0,f=0,c,d;
scanf("%d%d%d", &n, &l, &u);
for (int i = 0; i < n; i++) {
scanf("%d", &x); // read elements of an array
main[i] = x;
if (x >= l && x <= u) {
a++; //check if element is in range [l,u] and increasing a. later "a" will be used a length of the array "arr". this array cootains elements, which in in [u,l].
}
}
//add [u,l] elements in new array "arr"
for (int i = 0; i < n; i++) {
if (main[i] >= l && main[i] <= u) {
arr[m] = main[i];
m++; //index counter of "arr",
}
}
d=0;
for(int i=0;i<n;i++){
if(main[i]==arr[d]){
c=arr[a-d-1];
main[i]=c;
d++;
}
}
for(int i=0;i<n;i++){
printf("%d ",main[i]);
}
}
My best guess is that scanf is very annoying, on top of that, your format is ambiguous.
How will %d%d%d read 1234? Will it give you 12 3 and 4? 1 23 and 4? ...
try to do
scanf("%d %d %d" ...); // or
scanf("%d, %d, %d" ...);
something like that. Note that scanf is not recommended to be used, getc is a neat alternative, though also annoying when you want to read numbers with more than one digit, but you could create a function read_number, which, based on getc, will read a number as a string and return the int value with stoi.
In which way i can find indexes of my random numbers and store them.
Example:
300, 2, 43, 12, 0, 1, 90
Values -> 0 1 2 12 43 90 300
Indexes -> 0 1 2 3 4 5 6
So. Can i store instead of my values their indexes?
Like This
300 2 43 12 0 1 90
6 2 4 3 0 1 5
And will it possible for negative numbers also?
EDIT: (correction to my previously posted incorrect solution)
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int val;
int in0;
int in1;
} pair_t;
int cmpVal( const void *a, const void *b ) { return ((pair_t*)a)->val - ((pair_t*)b)->val; }
int cmpOrg( const void *a, const void *b ) { return ((pair_t*)a)->in0 - ((pair_t*)b)->in0; }
int main() {
int i;
int unsort[] = { 300, 2, 43, 12, 0, 1, 90 };
const int n = sizeof unsort/sizeof unsort[0];
// Make a copy in unsorted order including orginal sequence.
pair_t *worken = malloc( n * sizeof *worken );
for( i = 0; i < n; i++ )
worken[i].val = unsort[i], worken[i].in0 = i;
// Sort by value ascending
qsort( worken, n, sizeof pair_t, cmpVal );
// Register this sequence with each element
for( i = 0; i < n; i++ )
worken[i].in1 = i;
// Restore original sequence
qsort( worken, n, sizeof pair_t, cmpOrg );
// Copy the indices (of sorted version) to 'persistant' array.
int sorted[n] = { 0 };
for( i = 0; i < n; i++ )
sorted[i] = worken[i].in1;
// Toss 'working' buffer.
free( worken );
// List original sequence
for( i = 0; i < n; i++ )
printf( "%4d", unsort[ i ] );
putchar( '\n' );
// List corresponding indices (as if sorted)
for( i = 0; i < n; i++ )
printf( "%4d", sorted[ i ] );
putchar( '\n' );
return 0;
}
Output
300 2 43 12 0 1 90
6 2 4 3 0 1 5
Trivial assignment loop to "replace values with indices" in original array left out for clarity...
EDIT #2:
The OP suggests the unsorted array is to have its values replaced(!) with indices indicating the sort order.
This following does as much with the proviso that array values are not near the top end of values for ints.
#include <stdio.h>
#include <limits.h>
void show( int u[], size_t cnt ) { // Show current array values
for( size_t i = 0; i < cnt; i++ )
printf( "%4d", u[ i ] );
putchar( '\n' );
}
void oddSort( int u[], size_t cnt ) {
show( u, cnt );
// Succesively find and replace highest values with decreasing large int values.
int peak = INT_MAX;
for( size_t set = 0; set < cnt; set++ ) {
int maxID = 0;
while( u[maxID] >= peak ) maxID++; // find first non-replaced value
for( size_t i = maxID + 1; i < cnt; i++ )
if( u[i] < peak && u[i] > u[maxID] )
maxID = i;
u[maxID] = peak--;
}
// transpose down to 0, 1, 2...
for( size_t i = 0; i < cnt; i++ )
u[i] -= peak + 1;
show( u, cnt );
}
int main() {
{
int u[] = { 300, 2, 43, 12, 0, 1, 90 };
oddSort( u, sizeof u/sizeof u[0] );
}
putchar( '\n' );
{
// Test with negatives (coincidentally lowest value in first pos)
int u[] = { -256, 300, 2, 43, 12, 0, 1, 90 };
oddSort( u, sizeof u/sizeof u[0] );
}
return 0;
}
Output:
300 2 43 12 0 1 90
6 2 4 3 0 1 5
-256 300 2 43 12 0 1 90
0 7 3 5 4 1 2 6
I should build a function that gets an array and it's size and return a pointer
to new array (i need do create new array by using malloc and realloc) that find the identical numbers and duplicates them in the row
for example the array:{1,8,8,70,2,2,2,5,5,2} and size 10 suppose to return a pointer to this array
{1,8,8,8,8,70,2,2,2,2,2,2,5,5,5,5,2}. Any clue what's wrong with my code??
int * duplicateArray(int* arr, int n)
{
int g = 1;
int i,j=0;
int *p = (int*)(calloc)(n, sizeof(int));
assert(p);
for (i = 0; i < n-1; i++)
{
if (arr[i] == arr[i + 1])
{
p= (int*)(realloc)(p, n+g * sizeof(int));
n=n+g;
assert(p);
p[j] = arr[i];
j++;
p[j] = arr[i+1];
}
else
p[j] = arr[i];
j++;
}
return p;
}
The approach used by you when the memory is constantly reallocated is inefficient.
Also the function should return not only the pointer to the dynamically allocated array but also the number of elements in the allocated array. Otherwise the user of the function will not know how many elements are in the allocated array. To use a sentinel value for an integer dynamically allocated array is not a good idea.
I suggest to split the task into two separate tasks that will correspond to two separate functions..
The first function will count the number of repeated elements in a given array.
The second function will create dynamically an array with the specified size based on the returned value of the first function and copy elements of the source array to the newly created array.
Here is a demonstrative program
#include <stdio.h>
#include <stdlib.h>
size_t countRepeated( const int a[], size_t n )
{
size_t repeated = 0;
for ( size_t i = 0; i != n; )
{
size_t m = 1;
while ( ++i != n && a[i] == a[i-1] ) ++m;
if ( m != 1 ) repeated += m;
}
return repeated;
}
int * copyWithDuplication( const int a[], size_t n, size_t m )
{
int *result = m == 0 ? NULL : calloc( m, sizeof( int ) );
if ( result )
{
for ( size_t i = 0, j = 0; j != m && i != n; )
{
result[j++] = a[i++];
size_t k = 1;
while ( j != m && i != n && a[i] == a[i-1] )
{
result[j++] = a[i++];
++k;
}
if ( k != 1 )
{
while ( j != m && k-- ) result[j++] = a[i-1];
}
}
}
return result;
}
int main(void)
{
int a[] = { 1, 8, 8, 70, 2, 2, 2, 5, 5, 2 };
const size_t N = sizeof( a ) / sizeof( *a );
for ( size_t i = 0; i < N; i++ )
{
printf( "%d ", a[i] );
}
putchar( '\n' );
size_t m = N + countRepeated( a, N );
int *b = copyWithDuplication( a, N, m );
if ( b )
{
for ( size_t i = 0; i < m; i++ )
{
printf( "%d ", b[i] );
}
putchar( '\n' );
}
free( b );
return 0;
}
The program output is
1 8 8 70 2 2 2 5 5 2
1 8 8 8 8 70 2 2 2 2 2 2 5 5 5 5 2
And here is another more interesting demonstrative program.
#include <stdio.h>
#include <stdlib.h>
size_t countRepeated( const int a[], size_t n )
{
size_t repeated = 0;
for ( size_t i = 0; i != n; )
{
size_t m = 1;
while ( ++i != n && a[i] == a[i-1] ) ++m;
if ( m != 1 ) repeated += m;
}
return repeated;
}
int * copyWithDuplication( const int a[], size_t n, size_t m )
{
int *result = m == 0 ? NULL : calloc( m, sizeof( int ) );
if ( result )
{
for ( size_t i = 0, j = 0; j != m && i != n; )
{
result[j++] = a[i++];
size_t k = 1;
while ( j != m && i != n && a[i] == a[i-1] )
{
result[j++] = a[i++];
++k;
}
if ( k != 1 )
{
while ( j != m && k-- ) result[j++] = a[i-1];
}
}
}
return result;
}
int main(void)
{
int a[] = { 1, 8, 8, 70, 2, 2, 2, 5, 5, 2 };
const size_t N = sizeof( a ) / sizeof( *a );
for ( size_t i = 0; i < N; i++ )
{
printf( "%d ", a[i] );
}
putchar( '\n' );
size_t m = N + countRepeated( a, N );
for ( size_t i = 0; i < m; i++ )
{
int *b = copyWithDuplication( a, N, i + 1 );
if ( b )
{
for ( size_t j = 0; j < i + 1; j++ )
{
printf( "%d ", b[j] );
}
putchar( '\n' );
}
free( b );
}
return 0;
}
Its output is
1 8 8 70 2 2 2 5 5 2
1
1 8
1 8 8
1 8 8 8
1 8 8 8 8
1 8 8 8 8 70
1 8 8 8 8 70 2
1 8 8 8 8 70 2 2
1 8 8 8 8 70 2 2 2
1 8 8 8 8 70 2 2 2 2
1 8 8 8 8 70 2 2 2 2 2
1 8 8 8 8 70 2 2 2 2 2 2
1 8 8 8 8 70 2 2 2 2 2 2 5
1 8 8 8 8 70 2 2 2 2 2 2 5 5
1 8 8 8 8 70 2 2 2 2 2 2 5 5 5
1 8 8 8 8 70 2 2 2 2 2 2 5 5 5 5
1 8 8 8 8 70 2 2 2 2 2 2 5 5 5 5 2
Any clue what's wrong with my code??
If the parameter n is 1, then your program will allocate an array for 1 element of type int, but will write nothing to it. It won't copy anything from the input buffer.
You are accessing both the input arr and the output array p out of bounds, which causes undefined behavior. The loop
for (i = 0; i < n-1; i++)
will not count from 0 to the function parameter n minus 2, because n is being incremented inside the loop. This causes your loop to have more iterations than it is supposed to, which causes both the input and the output array to be accessed out of bounds.
Also, there doesn't seem to be much point in your variable g, as it never changes and always has the value 1.
The function prototype
int * duplicateArray(int* arr, int n);
does not seem meaningful, as the calling function has no way of knowing the size of the returned array. If you use the function prototype
void duplicateArray ( const int *p_input_array, int num_input, int **pp_output_array, int *p_num_output );
instead, the function duplicateArray can write the address of the new array to *pp_output_array and the number of elements in the array to *p_num_output. That way, the calling function will effectively be able to receive two "return values" instead of only one.
Here is my implementation of the function duplicateArray and also of the calling function:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
void duplicateArray( const int *p_input_array, int num_input, int **pp_output_array, int *p_num_output )
{
int i = 0, j = 0;
// In the most extreme case, the output array must be 2 times larger than
// the input buffer, so we allocate double the size of the input buffer.
int *p_output_array = (int*)malloc( num_input * 2 * sizeof(int) );
assert( p_output_array != NULL );
while ( i < num_input )
{
int num_repetitions;
int k = p_input_array[i++];
//count the number of repetitions
for ( num_repetitions = 0; i < num_input && p_input_array[i] == k; num_repetitions++, i++ );
if ( num_repetitions == 0 )
{
p_output_array[j++] = k;
}
else
{
for ( int l = 0; l < num_repetitions + 1; l++ )
{
p_output_array[j++] = k;
p_output_array[j++] = k;
}
}
}
//shrink the array to the actually needed size
p_output_array = (int*)realloc( p_output_array, j * sizeof(int) );
assert( p_output_array != NULL );
*pp_output_array = p_output_array;
*p_num_output = j;
}
int main()
{
int arr[] = { 1, 8, 8, 70, 2, 2, 2, 5, 5, 2 };
int *p;
int num;
duplicateArray( arr, sizeof(arr)/sizeof(*arr), &p, &num );
for ( int i = 0; i < num; i++ ) {
printf( "%d\n", p[i] );
}
free( p );
}
So today i tried to implement a quicksort. It's almost working but somehow skips one element.
example : 5 2 8 2 3 4 1 5 7 -5 -1 -9 2 4 5 7 6 1 4
output : -5 -1 -9 1 2 2 3 2 1 4 4 4 5 5 5 6 7 7 8
In this case it skips -9. Here is code of the function.
test = quicksort_asc(0,size,tab,size) // this is function call
int quicksort_asc(int l, int r, int tab[], int tabSize) //l is first index, r is last index, tabSize is tabsize-1 generally
{
int i,buffer,lim,pivot,flag=0;
if(l == r)
return 0;
lim = l-1;
pivot = tab[r-1];
printf("pivot:%d\n",pivot);
for (i = l; i <= r-1; ++i)
{
if(tab[i] < pivot) {
lim++;
buffer = tab[lim];
tab[lim] = tab[i];
tab[i] = buffer;
flag = 1;
}
}
if(flag == 0)
return 0;
buffer = tab[lim+1];
tab[lim+1] = pivot;
tab[r-1] = buffer;
quicksort_asc(l,lim+1,tab,lim+1);//left side
quicksort_asc(lim+1,tabSize,tab,tabSize);//right side
}
This is my array length count code. 100 is maximum size, 0 is a stop value.
Count is size.
int count=0;
for (int i = 0; i < 100; i++)
{
test = scanf("%d",&vec[i]);
if(vec[i] == 0) break;
count++;
}
return count;
It seems nobody hurries to help you.:)
For starters the last parameter is redundant.
int quicksort_asc(int l, int r, int tab[], int tabSize);
^^^^^^^^^^^
All you need is the pointer to the first element of the array and starting and ending indices.
Also instead of the type int for the indices it is better to use the type size_t. However as you are using the expression statement
lim = l-1;
then o'k let the indices will have the type int though you could use another approach without this expression statement.
So the function should be declared like
void quicksort_asc( int tab[], int l, int r );
The variable flag is redundant. When it is equal to 0 it means that all elements before the pivot value are greater than or equal to it. But nevertheless you have to swap the pivot value with the first element that is greater than or equal to the pivot.
This loop
for (i = l; i <= r-1; ++i)
has one iteration redundant. It should be set like
for (i = l; i < r-1; ++i)
This call
quicksort_asc(lim+1,tabSize,tab,tabSize);
^^^^^ ^^^^^^^
shall be substituted for this call
quicksort_asc( lim + 2, r, tab );
^^^^^^^ ^^
because the pivot value is not included in this sub-array.
Here is a demonstrative program.
#include <stdio.h>
void quicksort_asc( int tab[], int l, int r )
{
if ( l + 1 < r )
{
int lim = l - 1;
int pivot = tab[r - 1];
for ( int i = l; i < r - 1; ++i )
{
if ( tab[i] < pivot )
{
lim++;
int tmp = tab[lim];
tab[lim] = tab[i];
tab[i] = tmp;
}
}
tab[r - 1] = tab[lim + 1];
tab[lim + 1] = pivot;
quicksort_asc( tab, l, lim + 1 );
quicksort_asc( tab, lim + 2, r );
}
}
int main(void)
{
int a[] = { 5, 2, 8, 2, 3, 4, 1, 5, 7, -5, -1, -9, 2, 4, 5, 7, 6, 1, 4 };
const int N = ( int )( sizeof( a ) / sizeof( *a ) );
for ( int i = 0; i < N; i++ )
{
printf( "%d ", a[i] );
}
putchar( '\n' );
quicksort_asc( a, 0, N );
for ( int i = 0; i < N; i++ )
{
printf( "%d ", a[i] );
}
putchar( '\n' );
return 0;
}
Its output is
5 2 8 2 3 4 1 5 7 -5 -1 -9 2 4 5 7 6 1 4
-9 -5 -1 1 1 2 2 2 3 4 4 4 5 5 5 6 7 7 8
I have a matrix with n*n dimensions. For given integer k I have to print elements from diagonals.
From picture: for k=0, it has to print a vector: 1,12,23,34.
How do i do this?
A straightforward approach can look the following way
#include <stdio.h>
#define N 4
int main(void)
{
int a[N][N] =
{
{ 1, 2, 3, 4 },
{ 11, 12, 13, 14 },
{ 21, 22, 23, 24 },
{ 31, 32, 33, 34 }
};
int k;
printf( "Select a diagonal (%d, %d): ", -N, N );
scanf( "%d", &k );
if ( k < 0 )
{
for ( int i = -k, j = 0; i < N; i++, j++ )
{
printf( "%d ", a[i][j] );
}
}
else
{
for ( int i = 0, j = k; j < N; i++, j++ )
{
printf( "%d ", a[i][j] );
}
}
putchar( '\n' );
return 0;
}
The program output might look like
Select a diagonal (-4, 4): 2
3 14
or
Select a diagonal (-4, 4): -2
21 32
Or instead of the if-else statement with separate loops you can use one loop as for example
int i = k < 0 ? -k : 0;
int j = k > 0 ? k : 0;
for ( ; i < N && j < N; i++, j++ )
{
printf( "%d ", a[i][j] );
}
putchar( '\n' );
pseudo code:
function(martrix, k){
rowmax = matrix.length;
colmax = matrix[0].length;
output = []
for i = 0 to max(rowmax, colmax):
if k > 0 : x = i + k
if k < 0 : y = i + k
if(x < rowmax and y < colmax):
output.append(matrix[x][y])
}