Program - Rotating matrix 90 degrees clockwise.
I am a beginner in coding. I came across this question on GeeksforGeeks. I found the solutions very complex so tried applying my logic. But I don't know if my logic is appropriate for the program. Kindly guide me.
#include<stdio.h>
int main()
{
int A = 0 , a = 0 , b = 0;
int arr[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
printf("90 Degree rotation: \n");
printf("\n");
for(A = 2; A >= 0; A--)
{
for(a = 0; a < 3 ; a++)
{
for(b = 0; b < 3 ; b++)
{
if(b==A)
printf("%d\t",arr[a][b]);
}
}
printf("\n");
}
}
Input
1 2 3
4 5 6
7 8 9
Output
3 6 9
2 5 8
1 4 7
This is you matrix, with the axis you chose :
b ->
a 1 2 3
| 4 5 6
V 7 8 9
That is, for a fixed a for instance, if you increase b, you print "the next number" (provided b is not 2). Similarly, if you increase a with the same b, you take the same column, but the next line.
So, you can have the following pseudo program, to print a full column (on a line):
print_column(b):
for a from 0 to 2
print arr[a][b]
print newline
What do you want ? You want to print the following :
3 6 9
2 5 8
1 4 7
That is printing the last column, then the middle one, then the first one, which is done by the following pseudo-program:
print the 3rd column of arr
print the 2nd column of arr
print the 1st column of arr
or, more concisely :
for b from 2 to 0
print the b-th column of arr.
So, the final pseudo code is (inlining the print_column procedure):
for b from 2 to 0
for a from 0 to 2
print arr[a][b]
print newline
Or, in C:
for(b = 2; b >= 0 ; b--)
{
for(a = 0; a < 3 ; a++)
{
printf("%d\t",arr[a][b]);
}
printf("\n");
}
Related
How do I make my code have an output like this:
Enter your number: 4
1 1 1 2
2 2 2 3
3 3 3 4
4 4 4 5
I can't seem to figure out how to make it so the last digit prints the next value iteration.
#include <stdio.h>
int main(){
int num;
int i = 1;
printf("Enter your number: ");
scanf("%d", &num);
for(i = 1; i<=num; i++){
for(int j = 0; j<num; ++j)
{
printf("%d ",i);
}
printf("\n");
}
Doing this using nested loops are simple and doesn't require any kind of special calculations, if-statements or other more or less fancy stuff. Just keep it simple.
Your task is:
for each row:
print "rowindex+1 and a space" n-1 times
print "rowindex+2 and a newline" 1 time
"for each row" is one simple loop.
"n-1 times" is another (nested) simple loop.
So keep it simple... just two ordinary for-loops like:
#include <stdio.h>
int main()
{
int n = 4;
for (int i = 0; i < n; i++) // for each row
{
for (int j = 0; j < n-1; j++) // n-1 times
{
printf("%d ", i + 1);
}
printf("%d\n", i + 2); // 1 time
}
return 0;
}
Here is something kind of from out in the left field, and off topic, leaving behind not only the requirements of the homework, but the C language. However, we will find our way back.
We can solve this problem (sort of) using text processing at the Unix prompt:
We can treat the smallest square
12
23
as an initial seed kernel, which is fed through a little command pipeline to produce a square of the next size (up to a single digit limitation):
We define this function:
next()
{
sed -e 's/\(.\).$/\1&/' | awk '1; END { print $0 | "tr \"[1-9]\" \"[2-8]\"" }'
}
Then:
$ next
12
23
[Ctrl-D][Enter]
112
223
334
Now, copy the 3x3 square and paste it into next:
$ next
112
223
334
[Ctrl-D][Enter]
1112
2223
3334
4445
Now, several steps in one go, by piping through multiple instances of next:
$ next | next | next | next | next
12
23
[Ctrl-D][Enter]
1111112
2222223
3333334
4444445
5555556
6666667
7777778
The text processing rule is:
For each line of input, repeat the second-to-last character. E.g ABC becomes ABBC, or 1112 becomes 11112. This is easily done with sed.
Add a new line at the end which is a copy of the last line, with each digit replaced by its successor. E.g. if the last line is 3334, make it 4445. The tr utility helps here
To connect this to the homework problem: a C program could be written which works in a similar way, starting with an array which holds the 1 2 2 3 square, and grows it. The requirement for nested loops would be satisfied because there would be an outer loop iterating on the number of "next" operations, and then an inner loop performing the edits on the array: replicating the next-to-last column, and adding the new row at the bottom.
#include <stdio.h>
#include <stdlib.h>
#define DIM 25
int main(int argc, char **argv)
{
if (argc != 2) {
fputs("wrong usage\n", stderr);
return EXIT_FAILURE;
}
int n = atoi(argv[1]);
if (n <= 2 || n > DIM) {
fputs("invalid n\n", stderr);
return EXIT_FAILURE;
}
int array[DIM][DIM] = {
{ 1, 2 },
{ 2, 3 }
};
/* Grow square from size 2 to size n */
for (int s = 2; s < n; s++) {
for (int r = 0; r < s; r++) {
array[r][s] = array[r][s-1];
array[r][s-1] = array[r][s-2];
}
for (int c = 0; c <= s; c++) {
array[s][c] = array[s-1][c] + 1;
}
}
/* Dump it */
for (int r = 0; r < n; r++) {
for (int c = 0; c < n; c++)
printf("%3d ", array[r][c]);
putchar('\n');
}
return 0;
}
#include<stdio.h>
int main(){
int n;
printf("Enter the number: ");
scanf("%d",&n);
for(int i =1; i<=n; i++){
for(int j=1;j<=n;j++) {
if(j==n)
printf("%d\t",i+1);
else
printf("%d\t",i);
}
printf("\n");
}
return 0;}
Nested loops will drive you crazy, trying figure out their boundaries.
While I usually oppose adding more variables, in this case it seems justified to keep track of things simply.
#include <stdio.h>
int main() {
int n = 4, val = 1, cnt1 = 1, cnt2 = 0;
for( int i = 1; i < n*n+1; i++ ) { // notice the 'square' calculation
printf( "%d ", val );
if( ++cnt1 == n ) // tired of this digit? start the next digit
cnt1 = 0, val++;
if( ++cnt2 == n ) // enough columns output? start the next line
cnt2 = 0, putchar( '\n' );
}
return 0;
}
1 1 1 2
2 2 2 3
3 3 3 4
4 4 4 5
A single example of desired output is hard to go by, especially when the code doesn't help... Anyway, here's the output when 'n' = 5.
1 1 1 1 2
2 2 2 2 3
3 3 3 3 4
4 4 4 4 5
5 5 5 5 6
All of these kinds of assignments are to try to get you to recognize a pattern.
The pattern you are given
1 1 1 2
2 2 2 3
3 3 3 4
4 4 4 5
is very close to
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
which is an easy nested loop. Write a solution to the easier pattern. Once you have that you can then you can fix it.
Hint: Notice that the only thing that changes is the last item of the inner loop.
Edit
This totally breaks the spirit of the assignment, and if you, dear student, ever try to submit something like this your professor will... probably not care, but also know full well that you didn’t do it. If I were your professor you’d lose marks, even if I knew you weren’t cheating and had written something this awesome yourself.
Single loop. Stuff added to pretty print numbers wider than one digit (except the very last). Maths, yo.
#include <stdio.h>
#include <math.h>
void print_off_by_one_square( int n )
{
int width = (int)log10( n ) + 1;
for (int k = 0; k++ < n*n ;)
printf( "%*d%c", width, (k+n)/n, (k%n) ? ' ' : '\n' );
}
int main(void)
{
int n;
printf( "n? " );
fflush( stdout );
if ((scanf( "%d", &n ) != 1) || (n < 0))
fprintf( stderr, "%s\n", "Not cool, man, not cool at all." );
else
print_off_by_one_square( n );
return 0;
}
The way it works is pretty simple, actually, but I’ll leave it as an exercise for the reader to figure out on his or her own.
Here is a different concept. Some of the answers are based on the idea that we first think about
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
and then tweak the logic for the item in the last line.
But we can regard it like this also:
We have a tape which goes like this:
1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4
and we are blindly cutting the tape into four-element pieces to form a 4x4 square. Suppose someone deletes the first item from the tape, and then adds 5:
1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5
Now, if we cut that tape blindly by the same process, we will get the required output:
1 1 1 2
2 2 2 3
3 3 3 4
4 4 4 5
Suppose we have a linear index through the tape, a position p starting at 0.
In the unshifted tape, item p is calculated using p / 4 + 1, right?
In the shifted tape, this is just (p + 1) / 4 + 1. Of course we substitute the square size for 4.
Thus:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
if (argc != 2) {
fputs("wrong usage\n", stderr);
return EXIT_FAILURE;
}
int n = atoi(argv[1]);
int m = n * n;
if (n <= 0) {
fputs("invalid n\n", stderr);
return EXIT_FAILURE;
}
for (int p = 0; p < m; p++) {
printf("%3d ", (p + 1) / n + 1);
if (p % n == n - 1)
putchar('\n');
}
return 0;
}
$ ./square 2
1 2
2 3
$ ./square 3
1 1 2
2 2 3
3 3 4
$ ./square 4
1 1 1 2
2 2 2 3
3 3 3 4
4 4 4 5
I have this assignment to get and transpose a matrix using dynamic memory allocation in C
I did it by converting the linear position to (i,j) and swapping i,j
old and new element positions are perfect,
somehow the swap is not working as i intended,
might seem like i'm making others problem solve for me, but i'm blank at this point so help will be really appreciated
Here's the code:
#include <stdio.h>
#include <stdlib.h>
int main(){
int m,n;
printf("Enter the order of matrix, m*n:\n");
scanf("%d %d",&m,&n);
int *matrix_ptr;
matrix_ptr = (int *) malloc(m*n*sizeof(int));
printf("Enter the elements of %d*%d matrix\n",m,n);
for(int i=0; i<m*n; i++){
scanf("%d", matrix_ptr+i);
}
// Transposing the matrix
for(int i=0; i<m*n; i++){
int i_index = i / n;
int j_index = i % n;
// (i_index)*n + j_index gives the linear position
int new_linear_pos = (j_index)*n + i_index;
int temp = *(matrix_ptr + new_linear_pos);
*(matrix_ptr + new_linear_pos) = *(matrix_ptr + i);
*(matrix_ptr + i) = temp;
if(i==0){
printf("\nThe transpose is:\n");
}
printf("%d ", *(matrix_ptr+i));
if((i+1)%n == 0){
printf("\n");
}
}
}
The output:
You are swapping all values twice and you are printing the ones at the beginning of the line after the second swap. The first swap happened with i equal 1 and 2
Let's say you have this matrix at the begin:
1 2 3
4 5 6
7 8 9
swap index 0 with 0 stays the same thing. Prints 1
swap index 1 with 3: prints 4
1 4 3
2 5 6
7 8 9
swap index 2 with 6: prints 7\n
1 4 7
2 5 6
3 8 9
swap index 3 with 1: prints 4
1 2 7
4 5 6
3 8 9
etc...
The solution would be to swap elements only once.
The easiest fix would be a if (i > new_linear_pos) continue; //already swapped
So i got an assignment in class to make an empty sudoku that every time creates a random solution of 9x9.
I got to the point where i get different number each row and column but not on every 3x3 matrix and i cannot figure out how to go on from here.
We didnt learn recursion yet and can use only the libraries listed in the code.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NINE 9
#define ONE 1
void solve_sudoku(int board[9][9])
{
srand(time(0));
int count = 0;
for (int i = 0;i <= NINE;i++)
{
for (int j = 0;j < NINE;j++)
{
board[i][j] =(rand() % NINE)+ONE;
for (int k = 0;k < 9;k++)
{
int clone_i = i;
int clone_j = j;
while (board[i][k] == board[i][j])
{
if (j == k)
{
break;
}
count++;
board[i][j] = (rand() % NINE) + ONE;
k = 0;
}
while(board[k][j]==board[i][j])
{
if (i == k)
{
break;
}
count++;
board[i][j] = (rand() % NINE) + ONE;
k = 0;
}
if (count > 300 || (board[i][j] == board[i][k] && j != k))
{
for (int i = clone_i;i < clone_i + 1;i++)
for (int l = 0;l < 9;l++)
{
board[i][l] = 0;
}
count = 0;
k = 0;
j = 0;
}
}
}
}
}
void print_sudoku(int board[][9])
{
printf("The soduko solution is: \n");
for (int i = 0;i < NINE;i++)
{
for (int k = 0;k < NINE;k++)
{
printf("%d ", board[i][k]);
}
printf("\n");
}
}
int main()
{
int sud[9][9] = { 0 };
int matrix_size = 9;
solve_sudoku(sud);
print_sudoku(sud);
return 0;
}
I take you to mean that you need to generate random 9 x 9 grids of digits that meet the Sudoku criterion that each row, column and block contains all nine digits. In that case, you are going about it a very difficult way. Perhaps that was inspired by viewing the program as a solver, instead of what it really needs to be: a generator.
Consider that it is easy to write down at least one valid Sudoku algorithmically:
1 2 3 | 4 5 6 | 7 8 9
4 5 6 | 7 8 9 | 1 2 3
7 8 9 | 1 2 3 | 4 5 6
------+-------+------
2 3 4 | 5 6 7 | 8 9 1
5 6 7 | 8 9 1 | 2 3 4
8 9 1 | 2 3 4 | 5 6 7
------+-------+------
3 4 5 | 6 7 8 | 9 1 2
6 7 8 | 9 1 2 | 3 4 5
9 1 2 | 3 4 5 | 6 7 8
Now consider that you can always transform one valid Sudoku into a different one by swapping two rows or two columns such that no entries move from one block to another. For example, you can swap the first row with the third, or the fifth column with the sixth. If you perform a bunch of random swaps of that kind on a valid starting Sudoku then you will end up with a random grid that meets the Sudoku criteria.
Note that it is a different story if you need to produce only Sudoku that can be solved by deduction alone, without trial & error. For that you probably do need a solver-based approach, but that starts with a bona fide solver, and nothing in your code is anything like that.
Hello a beginner here who needs some of your help. My C program is good and does what it is supposed to do only that it is not supposed to use any kind of if statements. I wrote it that way as I saw it would be easier so that I can then replace the if statements. I have been trying to replace the if statements but am now stuck. What can I use instead of the if statement to still produce the same output.
The program is supposed to generate a sequence of thirty random integers between 0 and 9 and then print out the sequence both forward and backwards. Then print out a count of how many times each number between 0 and 9 appeared in the sequence.
This is the output
Here is a sequence of 30 random numbers between 0 and 9:
3 6 7 5 3 5 6 2 9 1 2 7 0 9 3 6 0 6 2 6 1 8 7 9 2 0 2 3 7 5
Printing them backwards, that's:
5 7 3 2 0 2 9 7 8 1 6 2 6 0 6 3 9 0 7 2 1 9 2 6 5 3 5 7 6 3
There were 3 0's
There were 2 1's
There were 5 2's
There were 4 3's
There were no 4's
There were 3 5's
There were 5 6's
There were 4 7's
There was only 1 8
There were 3 9's
This is my C program
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, j, array[30]={0}, count=0,check;
srand(time(NULL));
for(i=0;i<30;i++)
array[i]=rand()%10;
for(i=0;i<30;i++)
printf("%d ",array[i]);
printf("\n\n");
for(i=29;i>=0;i--)
printf("%d ",array[i]);
printf("\n\n");
for(i=0;i<30;i++){
check=array[i];
if(array[i]!=-1)
array[i]=-1;
if(check == -1)
continue;
count =1;
for(j=0;j<30;j++){
if((i==j) || (array[j]==-1))
continue;
if(check==array[j]){
count++;
array[j]=-1;
}
}
printf("There were %d %d's\n",count,check);
}
return 0;
}
You'll understand the algorithm from comments:
#include <stdio.h>
#include <stdlib.h>
//time.h is needed for time()
#include <time.h>
int main()
{
int i, array[30] = {0};
srand(time(NULL));
//generate and print 30 random numbers
for(i = 0; i < 30; i++){
array[i] = rand() % 10;
printf("%d ", array[i]);
}
puts("\n\n");
//print these numbers backwards
for(i = 29; i >= 0; i--)
printf("%d ",array[i]);
puts("\n\n");
// print out a count of how many times each number
// between 0 and 9 appeared in the sequence.
int count[10] = {0};
for(i = 0; i < 30; i++)
count[array[i]]++;
//output the count for each number
for(i = 0; i < 10; i++)
printf("There were %d %d's\n",count[i], i);
return 0;
}
Output:
9 2 3 9 8 4 3 8 1 3 6 4 3 2 5 3 2 3 0 1 9 0 3 5 1 3 3 8 2 0
0 2 8 3 3 1 5 3 0 9 1 0 3 2 3 5 2 3 4 6 3 1 8 3 4 8 9 3 2 9
There were 3 0's
There were 3 1's
There were 4 2's
There were 9 3's
There were 2 4's
There were 2 5's
There were 1 6's
There were 0 7's
There were 3 8's
There were 3 9's
The following is a simplification of your original source while removing the if statements. There are implied if statements in several places where a logical expression is used as part of a source code statement.
For instance for(j = 0; j < 30 && match >= 0; j++) has several logical expressions but no if appears in this statement. The logical expressions are j < 30 and match >= 0 and the complete expression of j < 30 && match >= 0.
This example uses a logical expression and the evaluation short circuit behavior of the C compiler (see Short-circuit evaluation in Wikipedia) in the statement array[j] == match && ++count && (array[j] = -1); so that if the logical expression array[j] == match evaluates to false then the rest of the statement will not be executed.
We also depend on the preincrement operator with the ++count to increment count and then take the resulting value to check if it is false (zero) or true (non-zero). Since the variable count is initialized to zero and when incremented will always be non-zero then the next logical expression in the statement is evaluated the (array[j] = -1). We put the assignment statement within parenthesis to enforce the order of evaluation. We want the variable array[j] to be assigned the value of -1 and for the result to then be used in the logical statement. Since this is the last logical expression of the entire logical statement, whether it evaluates to false (zero) or true (non-zero) doesn't matter as what we want is the side effect of assigning the value of -1 to the array element.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int i, array[30] = {0};
srand(time(NULL));
for(i = 0; i < 30; i++)
array[i] = rand() % 10;
for(i = 0; i < 30; i++)
printf("%d ", array[i]);
printf("\n\n");
for(i = 29; i >= 0; i--)
printf("%d ",array[i]);
printf("\n\n");
for(i = 0; i < 30; i++){
int j;
int count = 0;
int match = array[i];
for(j = 0; j < 30 && match >= 0; j++){
array[j] == match && ++count && (array[j] = -1);
// replaces the following if as value of count is
// tested after it is incremented so will always be nonzero.
// if (array[j] == match) {
// count++; array[j] = -1;
// }
}
// if this is a valid array element value we are trying to match
// then print the count and the value being matched. printf()
// is a function that returns an int indicating number of character written.
match >= 0 && printf("There were %d %d's\n", count, match);
}
return 0;
}
An example output.
8 2 4 0 8 0 8 1 1 4 6 9 3 9 7 6 3 9 0 1 0 7 1 2 4 0 3 0 2 3
3 2 0 3 0 4 2 1 7 0 1 0 9 3 6 7 9 3 9 6 4 1 1 8 0 8 0 4 2 8
There were 3 8's
There were 3 2's
There were 3 4's
There were 6 0's
There were 4 1's
There were 2 6's
There were 3 9's
There were 4 3's
There were 2 7's
I want to sort a 2*n matrix, n is given in the input. Make a program to output a matrix. Here is the requirement:
the first column MUST be sorted in ASC, and
the second column in DESC if possible.
For example, let n = 5, and the matrix is
3 4
1 2
3 5
1 6
7 3
The result should be
1 6
1 2
3 5
3 4
7 3
So I write down the code like this. First line input the value n, and the following lines like above.
#include <stdio.h>
#define TWO_16 65536
#define TWO_15 32768
int v[100000][2];
int z[100000];
int vec[100000];
int n;
int main()
{
int i, j;
scanf ("%d", &n); // give the value of n;
for (i = 1; i <= n; i++) // filling the matrix;
{
scanf ("%d%d", &v[i][0], &v[i][1]);
z[i] = TWO_16 * v[i][0] + TWO_15 - v[i][1];
vec[i] = i;
}
for (i = 1; i <= n; i++)
for (j = 1; j <= i; j++)
{
if (z[j] > z[i])
{
int t = vec[i];
vec[i] = vec[j];
vec[j] = t;
}
}
for (i = 1; i <= n; i++) // output the matrix
printf("%d %d\n",v[vec[i]][0],v[vec[i]][1]);
return 0;
}
But in gcc, the output is
1 6
3 5
3 4
1 2
7 3
What's more, when the first line is changed to "1 2" and the second is changed to "3 4" in input, the result also changed.
What's the problem of my code?
Additional information:
I use z[] because I use a function that satisfy the requirement of this problem, so I can simply sort them. And vec[] stores the original index, because moving arrays may cost lots of time. So v[vec[i]][0] means the 'new' array's item i.
Note that v[0] is NOT used. n is less than 100000, not equal.
You are comparing values stored in z[], but swapping elements of vec.
So when in the begginig you have:
i vec z
------------------
1 1 z[1]
2 2 z[2]
3 3 z[3]
...
After for e.g. swapping 2 with 3
i vec z
------------------
1 1 z[1]
2 3 z[2]
3 2 z[3]
...
you will have improper mapping between vec and z.
So in another iteration you will again compare z[2] with z[3] and again you will have to swap elements of vec. That's why you should at least also swap elements of z or index elements of z using elements of vec
i vec z
------------------
1 1 z[vec[1]] = z[1]
2 3 z[vec[2]] = z[3]
3 2 z[vec[3]] = z[2]
...
Adding this should do the trick
...
int t = vec[i];
vec[i] = vec[j];
vec[j] = t;
//Add this also when swapping vec
t = z[i];
z[i] = z[j];
z[j] = t;
...
Array index start with 0, so your for cicles must start from 0
if (z[j] > z[i]): you want to sort v but you are comparing z and sorting vec. By sorting vec and comparing z bubble sort cannot work. You must use the same array.