Matrix Transpose With odd row Reversed - c

I know how to transpose a matrix, But how to transpose a matrix with odd row Reversed form.
Example 3*3 Matrix
1 2 3
4 5 6
7 8 9
Output
1 6 7
2 5 8
3 4 9

Here is a solution that breaks the problem into smaller subproblems. The function reverse_row() is a function that reverses an array in place, and the function transpose_array() transposes an array in place.
The first function, reverse_row() is called in a loop on the rows of the 2d array with odd indices, then the transpose_array() function is called on the resulting array. Note that the test if (i % 2) {} is used to determine if an array index is odd or even, since i % 2 evaluates to 0 only when i is even; you could also avoid this test and simply increment i by two at each iteration (starting from 1), as suggested by #Lưu Vĩnh Phúc in the comments:
for (size_t i = 1; i < MATRIX_SZ; i += 2) {
reverse_row(MATRIX_SZ, array[i]);
}
Also note that to transpose a square matrix in place, you do not need to iterate over all of the elements, but only the elements above or below the diagonal, swapping with the appropriate element. In this case, I have chosen to iterate over the elements below the diagonal, swapping with the corresponding element above the diagonal. Of course, the elements on the diagonal remain unchanged so are not iterated over at all.
Here is the code, using a 4X4 array as input. This code works for square matrices, and could be adapted to work for rectangular matrices. This would require care in choosing the size of the array used to represent the matrix, or dynamic allocation.
#include <stdio.h>
#define MATRIX_SZ 4
void print_array(size_t n, int arr[n][n]);
void reverse_row(size_t n, int arr[n]);
void transpose_array(size_t n, int arr[n][n]);
int main(void)
{
int array[MATRIX_SZ][MATRIX_SZ] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
puts("Before transformation:");
print_array(MATRIX_SZ, array);
putchar('\n');
for (size_t i = 0; i < MATRIX_SZ; i++) {
if (i % 2) {
reverse_row(MATRIX_SZ, array[i]);
}
}
transpose_array(MATRIX_SZ, array);
puts("After transformation:");
print_array(MATRIX_SZ, array);
putchar('\n');
return 0;
}
void print_array(size_t n, int arr[n][n])
{
for (size_t i = 0; i < n; i++) {
for (size_t j = 0; j < n; j++) {
printf("%5d", arr[i][j]);
}
putchar('\n');
}
}
void reverse_row(size_t n, int arr[n])
{
size_t mid = n / 2;
for (size_t i = 0; i < mid; i++) {
size_t swap_dx = n - 1 - i;
int temp = arr[i];
arr[i] = arr[swap_dx];
arr[swap_dx] = temp;
}
}
void transpose_array(size_t n, int arr[n][n])
{
for (size_t i = 0; i < n; i++) {
for (size_t j = 0; j < i; j++) {
int temp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = temp;
}
}
}
And here is the program output:
Before transformation:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
After transformation:
1 8 9 16
2 7 10 15
3 6 11 14
4 5 12 13

If I have understood the assignment correctly then the program can look the following way.
#include <stdio.h>
#define MAX_VALUE 100
int main(void)
{
while ( 1 )
{
printf( "Enter the size of an array (0 - Exit): " );
size_t n;
if ( scanf( "%zu", &n ) != 1 || n == 0 ) break;
putchar('\n');
n %= MAX_VALUE;
int a[n][n];
for ( size_t i = 0; i < n; i++ )
{
for ( size_t j = 0; j < n; j++ )
{
a[i][j] = n * i + j;
}
}
for (size_t i = 0; i < n; i++)
{
for (size_t j = 0; j < n; j++)
{
printf("%3d ", a[i][j]);
}
putchar('\n');
}
putchar('\n');
for (size_t i = 0; i < n; i++)
{
for (size_t j = i; j < n; j++)
{
if (j % 2 == 1 && i < n / 2)
{
int tmp = a[j][i];
a[j][i] = a[j][n - i - 1];
a[j][n - i - 1] = tmp;
}
if (i != j)
{
int tmp = a[i][j];
a[i][j] = a[j][i];
a[j][i] = tmp;
}
}
}
for (size_t i = 0; i < n; i++)
{
for (size_t j = 0; j < n; j++)
{
printf("%3d ", a[i][j]);
}
putchar('\n');
}
putchar('\n');
}
return 0;
}
Its output might look like
Enter the size of an array (0 - Exit): 10
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
50 51 52 53 54 55 56 57 58 59
60 61 62 63 64 65 66 67 68 69
70 71 72 73 74 75 76 77 78 79
80 81 82 83 84 85 86 87 88 89
90 91 92 93 94 95 96 97 98 99
0 19 20 39 40 59 60 79 80 99
1 18 21 38 41 58 61 78 81 98
2 12 22 37 42 57 62 77 82 97
3 13 23 36 43 56 63 76 83 96
4 14 24 34 44 55 64 75 84 95
5 15 25 35 45 54 65 74 85 94
6 16 26 33 46 53 66 73 86 93
7 17 27 32 47 52 67 72 87 92
8 11 28 31 48 51 68 71 88 91
9 10 29 30 49 50 69 70 89 90
Enter the size of an array (0 - Exit): 3
0 1 2
3 4 5
6 7 8
0 5 6
1 4 7
2 3 8
Enter the size of an array (0 - Exit): 0
The compiler should support Variable Length Arrays. Otherwise you can rewrite the program for an array with a fixed size.

Related

Matrix in C arraya

I have to fill a 6x5 array with numbers: 52, 62, 72 etc till array is full. But I don't have an idea how to do it. Thank you for the help.
I tried this:
int main() {
int a[6][5];
int start = 52;
for (int i = 0; i < 6; i++)
for (int j = 0; j < 5; j++) {
a[i][j] = start;
start++;
}
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 5; j++)
printf("%d ", a[i][j]);
printf("\n");
}
return 0;
}
If you wish to increment by 10 horizontally and by 1 vertically, you can modify your code this way:
#include <stdio.h>
int main() {
int a[6][5];
int start = 52, col_incr = 10, row_incr = 1;
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 5; j++) {
a[i][j] = start + i * row_incr + j * col_incr;
}
}
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 5; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}
return 0;
}
Output:
52 62 72 82 92
53 63 73 83 93
54 64 74 84 94
55 65 75 85 95
56 66 76 86 96
57 67 77 87 97
Your code would appear to work just fine. It produces:
52 53 54 55 56
57 58 59 60 61
62 63 64 65 66
67 68 69 70 71
72 73 74 75 76
77 78 79 80 81
If you expect to see:
52 62 72 ...
You just need to increment by 10 when initializing your matrix, instead of incrementing by 1 using the ++ operator.
You can do everything inside two nested for loops:
#include <stdio.h>
int main() {
int a[6][5];
int start = 52;
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 5; j++) {
a[i][j] = start;
start += 10;
printf("%d ", a[i][j]);
}
printf("\n");
}
return 0;
}
Note: start += 10 equals to start = start + 10
This will result:
52 62 72 82 92
102 112 122 132 142
152 162 172 182 192
202 212 222 232 242
252 262 272 282 292
302 312 322 332 342

BINGO GAME in C , MATRIX WITH 3 Dimensions?

How can I generate some random cards with numbers, but I need manipulate them as a 3 dimenson matrix . [players][n][n] .. n = The dimenson
My program generates only one card, how can I generate more cards? The index of the cards will be set in the variable players( jogadores in the program) that is the first dimension of the Matrix
#include <stdio.h>
#include <stdlib.h>
int n, soma;
int jogadores;
int menu;
int
main()
{
srand(123);
printf("Número de jogadores: \n");
do {
scanf("%d", &jogadores);
} while (jogadores < 2 || jogadores > 10);
printf("Numero de jogadores salvo \n Escolha a dimensao das cartelas: \n");
do {
scanf("%d", &n);
} while (n < 2 || n > 9);
printf("\n Dimensao das cartelas salva \n ");
//printf(" %d %d \n ",jogadores,n);
int value = 10 * n;
// I need to add the dimensiona _jogadores_ ==> cartela [jogadores][n][n]
int cartela[n][n];
// Loop number of players
// for (int q = 0; q <=jogadores;q++)
// {
// Loop lines of the card
for (int i = 0; i <= n; i++) {
// Loop rows of the card
for (int j = 0; j < n; j++) {
do {
soma = 0;
// Colocar a dimensão jogadores
cartela[i][j] = rand() % value;
for (int l = 0; l < n; l++) {
for (int c = 0; c < n; c++) {
if (cartela[i][j] == cartela[l][c] && (i != l && j != c)) {
soma++;
}
}
}
} while (soma != 0);
}
}
// for (int j = 0; j < jogadores; j++)
// {
for (int l = 0; l < n; l++) {
for (int c = 0; c < n; c++) {
printf("\t %d", cartela[l][c]);
}
printf("\n");
}
// }
//while(1)
//{
//}
return 0;
}
That's my code, and like I said before, the biggest question is how can i use the 3 dimension matrix to get more cards.
A few things ...
The main issue is that you should break down the main into some separate functions.
That way, you can create a function that creates a card. Then, you can call it N times for the number of players.
The card creation you have could take a long time and is very slow. Better to fill the array linearly and then randomly swap cells. This guarantees uniqueness but is much faster.
Here's a refactored version:
#include <stdio.h>
#include <stdlib.h>
int n, soma;
int jogadores;
int menu;
void
card_print(int n,int card[n][n],const char *reason)
{
printf("\n");
printf("%s:\n",reason);
for (int irow = 0; irow < n; ++irow) {
for (int icol = 0; icol < n; ++icol)
printf(" %2d",card[irow][icol]);
printf("\n");
}
}
void
card_init(int n,int card[n][n])
{
int cardno = 0;
for (int irow = 0; irow < n; ++irow) {
for (int icol = 0; icol < n; ++icol)
card[irow][icol] = cardno++;
}
// randomly swap cells in card
int passmax = n * n;
for (int passno = 0; passno < passmax; ++passno) {
int irow = rand() % n;
int jrow = rand() % n;
int icol = rand() % n;
int jcol = rand() % n;
int tmp = card[irow][icol];
card[irow][icol] = card[jrow][jcol];
card[jrow][jcol] = tmp;
}
}
int
main()
{
srand(123);
printf("Número de jogadores: \n");
do {
scanf("%d", &jogadores);
} while (jogadores < 2 || jogadores > 10);
printf("Numero de jogadores salvo \n Escolha a dimensao das cartelas: \n");
do {
scanf("%d", &n);
} while (n < 2 || n > 9);
printf("\n Dimensao das cartelas salva \n ");
//printf(" %d %d \n ",jogadores,n);
//int value = 10 * n;
// I need to add the dimensiona _jogadores_ ==> cartela [jogadores][n][n]
int cartela[n][n];
card_init(n,cartela);
card_print(n,cartela,"Single");
int players[jogadores][n][n];
for (int iplayer = 0; iplayer < jogadores; ++iplayer) {
char msg[100];
card_init(n,players[iplayer]);
sprintf(msg,"Player %d",iplayer);
card_print(n,players[iplayer],msg);
}
return 0;
}
Here's the program output for 3 players and card dimension 7:
Número de jogadores:
Numero de jogadores salvo
Escolha a dimensao das cartelas:
Dimensao das cartelas salva
Single:
13 34 19 44 15 5 47
7 25 32 48 16 28 0
9 11 2 17 18 4 42
36 41 12 23 8 39 6
24 38 31 29 27 20 26
1 21 37 3 14 10 22
46 43 35 45 40 33 30
Player 0:
7 30 17 23 11 2 15
10 38 0 21 34 25 3
6 40 12 46 18 22 41
47 26 19 36 13 16 31
33 28 1 35 27 14 4
20 39 5 8 42 29 32
9 43 44 45 24 37 48
Player 1:
0 8 22 18 2 5 21
20 29 16 10 7 42 24
14 1 37 17 3 13 32
31 6 23 39 15 11 45
28 9 43 25 19 4 36
35 12 47 38 40 30 44
41 33 48 27 46 34 26
Player 2:
40 44 18 3 28 5 43
13 39 42 16 17 4 35
27 23 14 45 37 41 30
21 22 15 9 0 26 47
46 12 11 31 2 7 20
8 29 48 38 33 32 1
24 6 25 36 19 34 10

Bubble Sort Algorithm in C – Is this it?

I'm currently a CS50x student.
I've been toying around with the search and sorting algorithms. Trying to understand them in code. Now, on the topic of bubble sort: I created what I think is a bubble sort algorithm. But I couldn't quite fit in the idea of the swap count that needs to be set to non-zero value. My algorithm (below) does sort all numbers. Where would I fit in the swap idea though? If anyone could be so kind to explain I'd really appreciate it.
#import <stdio.h>
#import <cs50.h>
int main(void)
{
// Creating an unsorted array
int count = 10;
int array[count];
for (int z = 0; z < count; z++)
scanf("%i", &array[z]);
// Bubble Sort
int buffer;
for (int b = 0; b < count; b++)
{
int a = 0;
while (a < count)
{
if (array[a] > array[a+1])
{
buffer = array[a];
array[a] = array[a+1];
array[a+1] = buffer;
}
a++;
}
}
printf("Sorted: ");
for (int b = 0; b < count; b++)
printf("%i ", array[b]);
printf("\n");
}
The directive is #include, not #import. The idea of counting swaps is to break the outer loop if nothing is out of sequence (because there were no swaps needed in the inner loop). This code implements that:
#include <stdio.h>
int main(void)
{
// Creating an unsorted array
int count = 10;
int array[count];
for (int z = 0; z < count; z++)
scanf("%i", &array[z]);
putchar('\n');
printf("%8s:", "Unsorted");
for (int b = 0; b < count; b++)
printf(" %i", array[b]);
printf("\n");
// Bubble Sort
for (int b = 0; b < count; b++)
{
int a = 0;
int num_swaps = 0;
while (a < count - 1)
{
if (array[a] > array[a+1])
{
int buffer = array[a];
array[a] = array[a+1];
array[a+1] = buffer;
num_swaps++;
}
a++;
}
if (num_swaps == 0)
break;
}
printf("%8s:", "Sorted");
for (int b = 0; b < count; b++)
printf(" %i", array[b]);
printf("\n");
return 0;
}
Sample runs (source bs97.c compiled to bs97; home-brew random number generator random — the options used generate 10 numbers between 10 and 99 inclusive):
$ random -n 10 10 99 | bs97
Unsorted: 68 47 85 39 52 54 31 81 19 59
Sorted: 19 31 39 47 52 54 59 68 81 85
$ random -n 10 10 99 | bs97
Unsorted: 75 85 36 11 35 87 59 63 26 36
Sorted: 11 26 35 36 36 59 63 75 85 87
$ random -n 10 10 99 | bs97
Unsorted: 90 27 64 90 76 79 52 46 98 99
Sorted: 27 46 52 64 76 79 90 90 98 99
$ random -n 10 10 99 | bs97
Unsorted: 53 60 87 89 38 68 73 10 69 84
Sorted: 10 38 53 60 68 69 73 84 87 89
$
Note that the code avoids trailing blanks in the output.
You could also define int num_swaps = 1; outside the sorting for loop and test it in the main loop condition:
for (int b = 0; b < count - 1 && num_swaps > 0; b++)
{
num_swaps = 0;
and remove the if (num_swaps == 0) break; from the end of the loop. The inner loop could be a for loop too. And the first cycle of the outer loop moves the largest value to the end of the array, so you can shorten the inner cycle so it has less work to do. The printing code should be factored into a function, too.
#include <stdio.h>
static void dump_array(const char *tag, int size, int data[size])
{
printf("%8s (%d):", tag, size);
for (int i = 0; i < size; i++)
printf(" %i", data[i]);
printf("\n");
}
int main(void)
{
// Creating an unsorted array
int count = 10;
int array[count];
for (int z = 0; z < count; z++)
{
if (scanf("%i", &array[z]) != 1)
{
fprintf(stderr, "Failed to read number %d\n", z + 1);
return 1;
}
}
putchar('\n');
dump_array("Unsorted", count, array);
// Bubble Sort
int num_swaps = 1;
for (int b = 0; b < count - 1 && num_swaps > 0; b++)
{
num_swaps = 0;
for (int a = 0; a < count - b - 1; a++)
{
if (array[a] > array[a + 1])
{
int buffer = array[a];
array[a] = array[a + 1];
array[a + 1] = buffer;
num_swaps++;
}
}
}
dump_array("Sorted", count, array);
return 0;
}
Sample output:
$ random -n 10 10 99 | bs97
Unsorted (10): 31 82 81 40 12 17 70 44 90 12
Sorted (10): 12 12 17 31 40 44 70 81 82 90
$

Magic Square Code Help, want to know where it moves the number down Programming in C

# include <stdio.h>
# include <stdlib.h>
int main(void)
{
int s;
int row;
int column;
int k;
int array[99][99] ;
printf("Enter the dimension of the square : ") ;
scanf("%d", &s) ;
if (s % 2 == 0)
{
printf("Please enter an even number") ;
goto last;
}
column = (s + 1) / 2 ;
row = 1 ;
int sqr1 = s*s;
for(k = 1 ; k <= sqr1 ; k++)
{
array[row][column] = k ;
if(k % s == 0)
{
row = (row + 1);
goto loop ;
}
if(row == 1)
row = s ;
else
row = row - 1 ;
if(column == s)
column = 1;
else
column = column + 1 ;
loop : ;
}
for (row = 1 ; row <= s ; row++)
{
for (column = 1 ; column <= s ; column++)
{
printf("%d\t", array[row][column]) ;
}
printf("\n\n") ;
}
last : ;
return 0;
}
I was wondering if anyone could tell me where the code puts the number down. Say I wanted a 3x3 magic square. The output would be:
https://i.stack.imgur.com/BYTSn.png
I was wondering where in the code it would move the 4 down because the 1 is already there. Same thing with the 7 moving down. The principle is you go 1 up and 1 to the right everytime and if there is something there you move down and keep going.
What About:
#include <stdio.h>
#include <string.h>
#define N (3)
int main( int argc, char * argv[] )
{
int square[ N ][ N ];
int i = N / 2;
int j = N - 1;
int num = 1;
memset( square, 0, sizeof(square) );
while( num <= N * N )
{
if( (i == -1) && (j == N) )
{
i = 0;
j = N - 2;
}
else
{
if( i < 0 )
i = N - 1;
if( j == N )
j = 0;
}
if( square[i][j] )
{
i++;
j = j - 2;
continue;
}
else
{
square[i][j] = num;
num++;
}
j++;
i--;
}
printf("N = %d\n", N );
printf("Sum = %d\n\n", N * (N * N + 1) / 2 );
for( i = 0; i < N; i++ )
{
for( j = 0; j < N; j++ )
printf("%3d ", square[i][j]);
printf("\n");
}
return 0;
}
Outputs:
N = 3
Sum = 15
2 7 6
9 5 1
4 3 8
N = 5
Sum = 65
9 3 22 16 15
2 21 20 14 8
25 19 13 7 1
18 12 6 5 24
11 10 4 23 17
N = 7
Sum = 175
20 12 4 45 37 29 28
11 3 44 36 35 27 19
2 43 42 34 26 18 10
49 41 33 25 17 9 1
40 32 24 16 8 7 48
31 23 15 14 6 47 39
22 21 13 5 46 38 30
N = 9
Sum = 369
35 25 15 5 76 66 56 46 45
24 14 4 75 65 55 54 44 34
13 3 74 64 63 53 43 33 23
2 73 72 62 52 42 32 22 12
81 71 61 51 41 31 21 11 1
70 60 50 40 30 20 10 9 80
59 49 39 29 19 18 8 79 69
48 38 28 27 17 7 78 68 58
37 36 26 16 6 77 67 57 47
References:
https://en.wikipedia.org/wiki/Siamese_method
https://en.wikipedia.org/wiki/Magic_square

EXC_BAD_ACCESS/KERN_INVALID_ADDRESS during the training of a neural network

I'm compiling my neural network in c99 on MAC OS X Yosemite.
gdb wasn't giving me a lot of information so I used a lot of printf to define where is my problem.
Here is what gdb is giving me:
entering into error output 0
0.000000
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000000
0x0000000000000000 in ?? ()
and here is my code:
127 for (int k = 0; k < 94; k++)
128 {
129 printf("\nentering into error output %d\n", k);
130 printf("\n%lf\n", results[k]);
131 printf("\n%lf\n", outputNeuron[k].output(&outputNeuron[k]));
132 printf("\n%lf\n", sigmoid.derivative(outputNeuron[k].output(&outputNeuron[k])));
133
134 outputNeuron[k].error =
135 sigmoid.derivative(outputNeuron[k].output(&outputNeuron[k])) *
136 (results[k] - outputNeuron[k].output(&outputNeuron[k]));
137
138 printf("\n adjustWeights output %d\n", k);
139 outputNeuron[k].adjustWeights(&outputNeuron[k]);
140
141 printf("\nerror output %d ok\n", k);
142 }
If you need anything more, just ask cause I think you are my last hope
edit:
77 TNeuron outputNeuron[94];
78 if (is_empty(file))
79 for (int k = 0; k < 94; k++)
80 {
81 outputNeuron[k] = TNeuron_create();
82 outputNeuron[k].randomizeWeights(&outputNeuron[k]);
83 }
file is empty for now
and here is TNeuron_create():
37 TNeuron TNeuron_create()
38 {
39 struct TNeuron This;
40 TNeuron_Init(&This);
41 return This;
42 }
43
44 void TNeuron_Init(struct TNeuron *This)
45 {
46 This->output = TNeuron_output;
47
48 This->randomizeWeights = TNeuron_randomizeWeights;
49
50 This->adjustWeights = TNeuron_adjustWeights;
51
52 for (int i = 0; i < 20; i++)
53 for (int j = 0; j < 20; j++)
54 {
55 This->inputs[i][j] = 0;
56 This->weights[i][j] = 0;
57 }
58
59 This->error = 0;
60
61 This->biasWeight = 0;
62 }
edit 2:
5 double TNeuron_output(struct TNeuron *This)
6 {
7 TSigmoid sigmoid = TSigmoid_create();
8
9 double op = 0;
10 for (int i = 0; i < 20; i++)
11 for (int j = 0; j < 20; j++)
12 op += This->weights[i][j] * This->inputs[i][j];
13
14 return sigmoid.output(op + This->biasWeight);
15 }

Resources