How to write on a file from Top to Bottom in C - c

I would like to ask if its possible to write on a file from top to bottom?
The current code below will flip and image Vertically.
This uses left to right writing to a file.
On the other hand, I am having problem on how would I do the flip image Horizontally if I follow the left to right pattern on writing to a file.
Note: I have other option here, which is to swap lines from top to bottom.
Who knows maybe there's a way to follow the Vertical Flip pattern.
I would appreciate any help you guys can give. Thanks.
//Flip Vertically
for(y = WIDTH-1 ; y >= 0 ; y--) {
for(x = 0 ; x < HEIGHT; x++) {
p = (unsigned char *)datap + ((WIDTH) * y * 3) + (x * 3);
// output pixel
if(fwrite(p, sizeof(char), 3, outfp) != 3) {
cleanUpBeforeExit(infp, outfp, datap, E_FILE_WRITE_ERROR);
}
}
}

Beware that the terms that you use are very ambiguous. Flip vertically, flip horizontally can be understood two ways, as can top-to-bottom when speaking of a file.
Hence I'll give a general answer.
Assume you write the pixels in the usual scanning order, top row first, left pixel first, i.e. by addressing Image[Column + Row * Pitch] in a double loop (outer on Row, inner on Column). You can also reverse the loop traversal order.
Then you will obtain a left-right mirroring (pixels move horizontally) by writing Image[(Width - 1 - Column) + Row * Pitch], and a top-bottom mirroring (pixels move vertically) with Image[Column + (Height - 1 - Row) * Pitch].
You can combine the two modifications to achieve a 180° rotation.

When writing to a file would normally write data from start-of-file towards end-of-file. Writing in any other order will in most cases make your program more complicated and give worse performance.
So what you need is to access your data in the correct order depending on how you want to flip the data.
Something like:
#include <stdio.h>
#define WIDTH 2
#define HEIGHT 3
void print_element(char* p)
{
// Here I just print to stdout but you can just save it to a file
printf("%c %c %c ", *p, *(p+1), *(p+2));
}
int main()
{
char data[3 * HEIGHT][3 * WIDTH] = {{'a', 'b', 'c', 'd', 'e', 'f'},
{'g', 'h', 'i', 'j', 'k', 'l'},
{'m', 'n', 'o', 'p', 'q', 'r'}};
char* datap = (char*)data;
char* p;
printf("Normal\n");
for(int y = 0; y < HEIGHT; y++)
{
for(int x = 0 ; x < WIDTH; x++)
{
p = datap + ((WIDTH) * y * 3) + (x * 3);
print_element(p);
}
printf("\n");
}
printf("\nFlip horizontal\n");
for(int y = HEIGHT-1 ; y >= 0 ; y--)
{
for(int x = 0 ; x < WIDTH; x++)
{
p = datap + ((WIDTH) * y * 3) + (x * 3);
print_element(p);
}
printf("\n");
}
printf("\nFlip vertical\n");
for(int y = 0; y < HEIGHT; y++)
{
for(int x =WIDTH-1; x >= 0; x--)
{
p = datap + ((WIDTH) * y * 3) + (x * 3);
print_element(p);
}
printf("\n");
}
printf("\nFlip both\n");
for(int y = HEIGHT-1 ; y >= 0 ; y--)
{
for(int x = WIDTH-1; x >= 0; x--)
{
p = datap + ((WIDTH) * y * 3) + (x * 3);
print_element(p);
}
printf("\n");
}
return 0;
}
This will produce:
Normal
a b c d e f
g h i j k l
m n o p q r
Flip horizontal
m n o p q r
g h i j k l
a b c d e f
Flip vertical
d e f a b c
j k l g h i
p q r m n o
Flip both
p q r m n o
j k l g h i
d e f a b c

Related

why is the character not moving correctly in a dynamic 2d array?

I have troubles with moving my character.
The Program should behave like this:
Read from the input two numbers separated by a space, rows and cols.
Create a 2D grid (array) of characters with dimensions of rows rows and cols columns. Initialize the characters in the grid to '.' (dot).
Place the turtle in position (0, 0) - the zero row and the zero column (top left).
Load characters sequentially from the program input. The characters will be separated by a white character (a space or a line).
If you hit the 'x' character, print the grid to the Program Output and exit the program.
If you encounter characters '<', '>', '^', 'v', Move the turtle in the corresponding direction (Left, Right, Up, Down).
If you encounter the character 'o', enter the character' o ' in the grid at the current position of the turtle.
If the turtle were to make a move that would take it out of the grid (e.g. to position (0, 0) it would receive the command to go to the left), then “teleport” the turtle to the opposite side of the grid.
My program (I do not why but when I press ">" or "<" it moves by two, not one):
#include <stdio.h>
#include <stdlib.h>
int main(){
int rows, cols;
int i;
int j;
int x = 0, y = 0;
char symbol = 'o';
scanf("%d %d", &rows, &cols);
char* pole = (char*)malloc(rows * cols * sizeof(char));
for (i = 0; i < rows; i++){
for(j = 0; j < cols; j++)
pole[i * rows + j] = '.';
}
pole[x * rows + y] = 'o';
while(symbol != 'x'){
scanf("%c", &symbol);
if (symbol == '^') x--;
else if (symbol == 'v') x++;
else if (symbol == '>') y++;
else if (symbol == '<') y--;
else if (symbol == 'o') pole[x * rows + y] = 'o';
if(0 < y)
y = rows - 1;
else if(y > rows)
y = 0;
if(x < 0)
x = cols - 1;
else if(x > cols)
x = 0;
}
for (i = 0; i < rows; i++){
for(j = 0; j < cols; j++){
printf("%c", pole[i * rows + j]);
}
printf("\n");
}
return 0;
}
It should be like this:
3 3
o
>
v
o
>
v
o
x
o..
.o.
..o
But I have this:
3 3
o
>
v
o
>
v
o
x
o..
..o
..o
You've done a great job in your code but what's causing an error, in output is if(0<y) this if statement. Let's say you have this as your grid
and with pole[x * rows + y] = 'o'; 0,0 is already set to 'o' while your turtle stays at (0,0).
Now, with your input stream,
1: 'o' - The 'o' at (0,0) gets overwritten with'o'
2: > - y gets incremented by 1
3: v - x gets incremented by 1
so now your turtle is at (1,1) i.e. position 4 at grid but now when if(0<y) is encountered it comes to be true cause y<0 where y=1 at the moment so y is changed to y=rows-1 i.e. 2 in this case
So, now your turtle is at (0,2) i.e. position 5 at the grid, and now when 'o' is given as input it is set to 5th position of the grid.
This same thing will happen again n again with y no matter where you want it using '>', after if(0<y) y will be set to last column of the grid irrespective of the value of x
And if just in case y actually becomes less than 0 there will be an run time error in your code.
So, as it's solution you should use if(y<0) instead, in this case y will only be set to last column if user enters '<' when turtle is at anywhere in the first column of the grid.
The code seems to work as expected for the input you have given when you change if (0 < y) to if (0 > y) (i.e., the opposite relation). By the way, I would suggest you to write it if (y < 0), which is more readable, at least for me.
(Thanks, Lundin, for a hint to this line.)

The program with a 2d array does not work correctly

The essence of the program is that I set the size of the array with two numbers, then I use the input "v", "<", ">" , "^". I set the direction where the turtle will move. When checking the code, with the help of tests, I realized that my program was not working correctly when I wrote in terminal
5 15
o
v
o
v
o
v
o
>
v
o
>
o
>
^
o
^
o
^
o
^
o
>
>
o
v
o
v
o
v
o
v
o
^
^
>
o
>
^
o
^
<
o
>
>
>
o
v
o
v
o
v
o
v
o
^
^
>
o
>
^
o
^
<
o
v
v
>
v
o
v
>
o
>
>
v
o
v
o
v
o
v
v
o
x
When entering, i have this:
But, the correct result is:
My code
#include <stdio.h>
#include <stdlib.h>
int main()
{
int hor;
int vert;
int x = 0;
int y = 0;
int i, a;
char znacka = 'z';
scanf("%d%d", &vert, &hor);
char* arr = (char*)malloc(vert * hor * sizeof(char));
arr[x *vert + y] = 'o';
for ( i = 0; i < vert; i++ )
{
for( a = 0; a < hor; a++ )
arr[ i * vert + a ] = '.';
}
while( znacka != 'x' )
{
scanf("%c", &znacka);
if ( znacka == '^' ) x--;
else if ( znacka == 'v' ) x++;
else if ( znacka == '>' ) y++;
else if ( znacka == '<' ) y--;
else if ( znacka == 'o' ) arr[x *vert + y] = 'o';
if(y < 0)
y = vert - 1;
else if(y > vert)
y = 0;
if(x < 0)
x = hor - 1;
else if(x > hor)
x = 0;
}
for ( i = 0; i < vert; i++ )
{
for( a = 0; a < hor; a++ )
{
printf("%c",arr [i *vert + a]);
}
printf("\n");
}
free(arr);
return 0;
}
What could be the problem?
Thank you for your attention and help!
I can't figure out what my problem is.
EDIT: This looks like an assignment, so it doesn't help you for me to simply provide a final-worked example. So I'm just giving "power-hints".
The indexing into the grid is not correct, it looks to be transposing x & y:
arr[x *vert + y] = 'o'; // produces a rotated grid (I think)
If you have an array of size vert * hor that represents a hor by vert grid (i.e: width by length), then the index into the grid at x,y is:
x + ( y * width )
Re-factoring into the program:
arr[ x + ( y * hor ) ] = 'o';
Where the top-left cell is at ( 0, 0 ) and the bottom-right at ( hor-1, vert-1 ).
You need to firstly ensure that the output is being drawn correctly, otherwise any test-result is moot.
A good start at debugging might be to define a 7x13 array, and fill it with rows of '0000000', '1111111', ... 'ccccccc'. Then use this to check the grid printing functions. Once this array prints out OK, then try drawing an x to (4,7) and verify it's in the centre, etc. etc.
Right now you have a bunch of stuff that's not quite right, so you need to establish a base-line of what works, and then keep fixing various code blocks from there.

How can I code k-map for 4 variable function in C?

I'm trying to create a 4-variable kmap but I am not sure how to create the left side (00->10) of kmap. Thank you for your help. :)
Here is my code
#include <stdio.h>
int main()
{
unsigned int w, x, y, z;
unsigned int f;
/* Print header for K-map. */
printf(" yz \n");
printf(" 00 01 11 10 \n");
printf(" ______________\n");
/* row-printing loop */
for (w = 0; 2 > w; w = w + 1)
{
for (x = 0; 2 > x; x++){
printf("w=%u%x | ", w,x);
}
/* Loop over input variable b in binary order. */
for (y = 0; 2 > y; y = y + 1)
{
/* Loop over d in binary order.*/
for (z = 0; 2 > z; z = z + 1)
{
/* Use variables b and d to calculate *
* input variable c (iterated in *
* Gray code order). */
/* CALCULATE c HERE. */
y = x^z;
/* Calculate and print one K-map entry *
* (function F(a,b,c) ). */
/* INSERT CODE HERE. */
f = (w|~x) & (~w|~y) & (w|~x|~y) & 1;
printf("%u ", f);
}
}
/* End of row reached: print a newline character. */
printf("\n");
}
return 0;
}
For further information, this is what I have to do "Demonstrate its work using f(w,x,y,z) = xy'+w'z and g(w,x,y,z) = w'xyz'+ w + x' as examples"
You have four variables x,y,w,z so you need a kmap with 4x4=16 fields, like the second example in https://www.geeksforgeeks.org/introduction-of-k-map-karnaugh-map/. For the position of the variables and their negations in the kmap replace A,B,C,D with x,y,w,z in the picture :
The translation of letters to binary digits is
Simplify all the terms until no more terms can be simpified, the
output of the example below in this step is: ['10**', '1*0*', '1**0', '*110'] which is same as AB' + AC' + AD' + BCD'
source : https://github.com/zhcHoward/Kmap
So you basically need a square matrix
int matrix[4][4];
/*initialize matrix with '0'*/
for(int i = 0; i < 4; i++)
for(int j = 0; j < 4; j++)
matrix[i][j] = 0;
/* then needed fields to '1' i.e. xy', in most implementations the array is flattened for this */
Source code for a kmap solver is i.e. in http://krunalsiddhapathak.blogspot.com/2013/05/blog-post.html and in https://github.com/Ghost---Shadow/karnaugh-map-simplifier/blob/master/KarnaughMap/Map.cpp
For the verfication step ("Demonstrate that,...") see this .cpp code https://github.com/Ghost---Shadow/karnaugh-map-simplifier/blob/master/KarnaughMap/Simplifier.cpp and for background (POS, SOP, quad, octant,...) https://github.com/tasnim007/K-Map-Solver----Java-Project, https://www.geeksforgeeks.org/introduction-of-k-map-karnaugh-map/ and http://www.nzdl.org/cgi-bin/library?e=d-00000-00---off-0cdl--00-0----0-10-0---0---0direct-10---4-------0-1l--11-en-50---20-about---00-0-1-00-0--4----0-0-11-10-0utfZz-8-00&cl=CL2.4&d=HASHfb0a7f85db79899f86b6a0.8.1.5&gt=1

Nested loops for creating a spiral shape pattern in c

I need to make a spiral pattern made of stars '*' using nested for loops. I managed to make outter lines, now I don't know how to repeat smaller swirls in the same place.
What I should have:
*********
*
******* *
* * *
* *** * *
* * * *
* ***** *
* *
*********
Any help would be greatly appreciated.
After being thoroughly nerd-sniped, I came up with this:
#include <stdio.h>
void print_spiral(int size)
{
for (int y = 0; y < size; ++y)
{
for (int x = 0; x < size; ++x)
{
// reflect (x, y) to the top left quadrant as (a, b)
int a = x;
int b = y;
if (a >= size / 2) a = size - a - 1;
if (b >= size / 2) b = size - b - 1;
// calculate distance from center ring
int u = abs(a - size / 2);
int v = abs(b - size / 2);
int d = u > v ? u : v;
int L = size / 2;
if (size % 4 == 0) L--;
// fix the top-left-to-bottom-right diagonal
if (y == x + 1 && y <= L) d++;
printf((d + size / 2) % 2 == 0 ? "X" : " ");
}
printf("\n");
}
}
As others mentioned, it might be more intuitive to allocate an array representing the grid, and draw the spiral into the array (within which you can move freely), then print the array. But, this solution uses O(1) memory.
It could almost certainly be optimized and simplified a bit, but I'll "leave that as an exercise for the reader" as I've already spent too much time on this ;-)
Update
I'm not going to spend any more time on this, but I had an idea for a second attempt that might result in simpler code. If you check the output at increasingly large sizes, a pattern emerges:
Within each quadrant, the pattern is regular and can be easily coded. I think you would just have to carefully classify the (x, y) coordinates into one of the four quadrants and then apply the appropriate pattern.
The most sensible approach is to create a 2d array, then fill it with the * that you want.
Alternatively, you can try to come up with some "just in time" logic to avoid a buffer. This is more complicated.
I came up with an approach by thinking of the spiral as four different triangles that form a square. Here I have printed "a,b,c,d" for each of the four triangles to show what I mean:
aaaaaaaaaac
c
baaaaaac c
b c c
b baac c c
b b dd c c
b b c c
b dddddd c
b c
dddddddddd
There are two tricky parts to this. One is to align the diagonals correctly. Not so hard with with trial and error. The other tricky party is that not all squares divide into alternating lines the same way. You can see in the example above a square n=11, the left side is shifted by one. Perhaps there is a better solution, but this attempts to create alternating rows and columns.
n = 11;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
// top
if (j > i - 2 && j < n - i && i % 2 == (n&1)) printf("a");
// left
else if (j < i - 1 && j < n - i && j % 2 == (n & 1)) printf("b");
// right
else if (j > n - i -1&& j > i && j % 2 == ((n+1) & 1)) printf("c");
// bottom
else if (j < i + 1 && j > n - i - 1 && i % 2 == ((n + 1) & 1)) printf("d");
else printf(" ");
}
printf("\n");
}
I would recommend taking a look at the NCurses library. It contains many methods for moving the cursor in the terminal window, such as mvaddch() and curs_set().
Here is a document that contains everything you'd need to know on how to use NCurses.
However, if you don't want to use external libraries, then you could define a 2D array of ints or bools and then print a * where an index is 1 or true, respectively.
Example of the latter:
#include <stdbool.h> //You need to include this header file if you want to use 'bool's
...
//Using a 10x10 array for this example
bool stars[10][10] = { /* initialize the 2D array here */ };
...
//Get the length of a row
int rowLength = (sizeof stars[0]) / (sizeof stars[0][0]);
//Get the amount of rows
int rowAmount = (sizeof stars) / (sizeof stars[0]));
//Print the spiral using the array "stars"
for(int r = 0; r < rowAmount; r++){
for(int c = 0; c < rowLength; c++){
if(stars[r][c])
printf("*");
else
printf(" ");
}
printf("\n");
}
...

Error in C program to find integer triplets (x,y,z) such that n^x + n^y = n^z for given range of n

I want to make a C program compatible for DEV-C++ 4.9.9.2 to find integer triplets (x,y,z) such that for any integer n the equation n^x + n^y = n^z holds where n is any integer in the range [a,b]. The c program would have an input of only a and b and find such possible triplets.
The code that I wrote isn't working. What's the error in it?
for (n = a ; n <= b ; n++) {
for (x = a ; x < b ; x++) {
for (y = a ; y < b ; y++) {
for (z = a ; z = b ; z++) {
c = pow(n, x);
d = pow(n, y);
e = pow(n, z);
f = c + d;
if (e = f) {
printf("(%d , %d , %d) : %d", x,y,z,n);
}
}
}
}
}
I'm a novice in C.
C correction
Try changing
if (e=f)
into
if (e==f)
The first does assignment, the second tests equality.
(Note that you may also get overflow if the numbers tested get larger than your datatype.)
Maths approach
If y==x, then:
n^x + n^x = n^z
2n^x = n^z
=> n == 0 or n == 2
Now, assume y>x and n!=0.
n^x + n^y = n^z
n^x ( 1 + n^(y-x)) = n^z
=> 1+n^(y-x) = n^(z-x)
=> 1 = 0 ( modulo n)
=> impossible unless n==0 (in which case any x,y works) or n==1 (which does not work)
So this equation has solutions for any x,y if n==0.
Otherwise, the only solutions are with n==2, x==y and z=x+1.
Change
if (e = f)
to
if (e == f)
The first one assigns f to e, enable compiler warnings for such mistakes. The second one equates the LHS to the RHS.
Secondly, assuming your program is a brute force, i.e., loops for all values of x, y and z, you might want to change this statement:
for (z = a ; z = b ; z++)
to
for (z = a ; z < b ; z++)
Your implementation is O(n^4) , actually it can be done in O(n^3) .Here is the code
for (n = a ; n <= b ; n++) {
for (x = a ; x < b ; x++) {
for (y = a ; y < b ; y++) {
{
c = pow(n, x);
d = pow(n, y);
f = c + d;
e = pow(f,1.0/n);
if (e >= a && e < b) {
z = e;
printf("(%d , %d , %d) : %d", x,y,z,n);
}
}
}
}
}

Resources