Making a diamond with specific widht and height in c (gnuplot) - c

So I am trying to make a program that outputs the coordinates of a diamond of n width and n height and then represent the figure.out that is done with the program with gnuplot. I have this code done already but I want to make it easier.
#include <stdio.h>
#include <stdlib.h>
#define DEF 10
int main()
{
float def_an,def_al,slope,i,j,height,width;
FILE *out = fopen ( "diamond.out", "w" );
if(out==NULL)
{
printf("Wrong output");
return 1;
}
printf("Introduce the height: ");
scanf("%f", &height);
printf("Introduce the width: ");
scanf("%f", &width);
def_al=(height/DEF);
def_an=(width/DEF);
slope=(height/width);
for(j=0;j<= height/2;j+=def_al)
{
for(i=((j-(height/2))/slope);i<=(((height/2)-j)/slope);i+=def_an)
{
printf("%.2f %.2f\n",i,j);
fprintf (out, "%.2f %.2f\n", i,j );
}
}
for(j=(0-def_al);j>= -height/2;j-=def_al)
{
for(i=(((-height/2)-j)/slope);i<=((j-(-height/2))/slope);i+=def_an)
{
printf("%.2f %.2f\n",i,j);
fprintf (out, "%.2f %.2f\n", i,j );
}
}
fclose(out);
return 0;
}

Plotting a bunch of customized diamonds is not as straightforward as you might think.
Of course, you can use the suggestions Eldrad mentioned in the comments, but the plotting style with polygons is for splot and "3D"-plotting (which probably could also be used for 2D as well).
So, instead of plotting data you could draw objects (check help polygon) in a for loop from data in a datablock.
The example below is just gnuplot code. You have to create this text with C or any other language and send it to gnuplot.
Code:
### plotting diamonds in custom size
reset session
# x, y, width, height
$Diamonds <<EOD
0 0 3 5
5 0 2 1
4 4 3 2
-7 5 4 4
-6 -6 3 5
6 -6 7 2
EOD
x(n) = word($Diamonds[n],1)
y(n) = word($Diamonds[n],2)
w(n) = word($Diamonds[n],3)
h(n) = word($Diamonds[n],4)
set size square
set xrange [-10:10]
set yrange [-10:10]
do for [i=1:|$Diamonds|] {
set object i polygon from x(i),y(i)+h(i)/2. to x(i)+w(i)/2.,y(i) to x(i),y(i)-h(i)/2. to x(i)-w(i)/2.,y(i) to x(i),y(i)+h(i)/2.
set object i fc lt i fillstyle solid 1.0 border
}
plot NaN notitle # empty dummy plot or plot something else
### end of code
Result:

Related

Solving code-forces "1A Theatre Square" in C

novice programmer here trying to get better at C, so i began doing code problems on a website called codeforces. However i seem to be stuck, i have written code that appears to work in practice but the website does not accept it as right.
the problem :
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a. What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.1
Source :
https://codeforces.com/problemset/problem/1/A
I did have a hard time completely understanding the math behind the problem and used this source's answer from a user named "Joshua Pan" to better understand the problem
Source :
https://www.quora.com/How-do-I-solve-the-problem-Theatre-Square-on-Codeforces
This is my code :
#include<stdio.h>
#include<math.h>
int main(void)
{
double n,m,a;
scanf("%lf %lf %lf", &n,&m,&a);
printf("%1.lf\n", ceil(n/a)*ceil(m/a));
return 0;
}
I compiled it using "gcc TheatreSquare.c -lm"
When given the sample input 6,6,4 my code produces the correct output 4, however the website does not accept this code as correct, i could be wrong but maybe im using format specifiers incorrectly?
Thanks in advance.
Typical double (IEEE754 64-bit floating point) doesn't have enough accuracy for the problem.
For example, for input
999999999 999999999 1
Your program may give output
999999998000000000
While the actual answer is
999999998000000001
To avoid this, you shouldn't use floating point data type.
You can add #include <inttypes.h> and use 64-bit integer type int64_t for this calculation.
"%" SCNd64 is for reading and "%" PRId64 is for writing int64_t.
cell(n/a) on integers can be done by (n + a - 1) / a.
You can solve this using integers.
#include <stdio.h>
int main()
{
unsigned long n, m, a = 1;
unsigned long na, ma, res = 0;
scanf("%lu %lu %lu", &n, &m, &a);
na = n/a;
if (n%a != 0)
na++;
ma = m/a;
if (m%a != 0)
ma++;
res = na * ma;
printf("%lu", res);
return 0;
}
This code will fail in the Codeforce platform, on the test 9 (see below). But if you compile it and run it locally with the same inputs, the result is correct.
> Test: #9, time: 15 ms., memory: 3608 KB, exit code: 0, checker exit code: 1, verdict: WRONG_ANSWER
> Input 1000000000 1000000000 1
> Output 2808348672 Answer 1000000000000000000
> Checker Log wrong answer 1st numbers differ - expected: '1000000000000000000', found: '2808348672'
EDIT:
The problem described above is due to the fact that I'm running a 64-bit machine and the online compiler is probably using 32-bit. The unsigned long variables overflow.
The following code will pass all the tests.
#include <stdio.h>
int main()
{
unsigned long long n, m, a = 1;
unsigned long long na, ma, res = 0;
scanf("%llu %llu %llu", &n, &m, &a);
na = n/a;
if (n%a != 0)
na++;
ma = m/a;
if (m%a != 0)
ma++;
res = na * ma;
printf("%llu", res);
return 0;
}
Use the code below it will pass all the test cases we need to use long long for all variable declaration to get output.
#include <stdio.h>
#include <math.h>
int main(){
long long n,m,a,l,b;
scanf("%lld%lld%lld",&n,&m,&a);
l= n/a;
if(n%a != 0)
l++;
b= m/a;
if(m%a != 0)
b++;
printf("%lld",l*b);
return 0;
}
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a.
import java.util.Scanner;
public class theatre_square {
public static void main(String[] args) {
long a,b,c;
Scanner s = new Scanner(System.in);
a = s.nextLong();
b = s.nextLong();
c = s.nextLong();
long result = 0;
if(a>=c){
if(a%c==0)
result = a/c;
else
result = a/c + 1; // some part is left
}else{ // area of rectangle < area of square then 1 square is required
result = 1;
}
if(b>=c){
if(b%c==0)
result *= b/c;
else
result *= b/c + 1;
}
System.out.println(result);
}
}
case 1 . 2 2 3 => 1
length = 2 so 2 < 3 then only 1 square required <br>
breadth = 2 so 2 < 3 then covered in previous square so output 1
intial view
0 0
0 0
after adding 1 square ( r= remaining or left)
1 1 r
1 1 r
r r r
case 2 . 6 6 4 => 4
length = 2 so 6 > 4 then only 2 square required <br>
breadth = 2 so 6 > 4 then 2 square required
intial view
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
after adding 4 square ( r= remaining or left)
1 1 1 1 2 2 r r
1 1 1 1 2 2 r r
1 1 1 1 2 2 r r
1 1 1 1 2 2 r r
3 3 3 3 4 4 r r
3 3 3 3 4 4 r r
r r r r r r r r
r r r r r r r r
You can try the following:
import math
x,y,z=list(map(float, input().split()))
print(math.ceil(x/z)*math.ceil(y/z))
Here is the code for the above problem in CPP. We need a long long variable to store the value as we may have a very large value.
GUIDANCE ABOUT THE QUESTION:
As we are given the hint of edges so we have to cover them nicely. For a rectangle, we know that we have a length and height which is shown as n * m and the square is of a*a so we will try to cover the length first and decide its squares first
for that, we divide it by k, and then if any remainder exists we will add one more and the same for height.
I hope it will help you
HERE IS THE CODE
#include<iostream>
using namespace std;
int main()
{
long long n,m,k,l=0,o=0;
cin>>n>>m>>k;
l=n/k;
if(n%k!=0)
{
l++;
}
o=m/k;
if(m%k!=0)
{
o++;
}
cout<<l*o;
}

Why am I getting 0 as the output? Can you find the mistake?

The problem is about inputting two sides and the included angle for 6 different triangular plots. We need to find the area of each of these plots.
I wrote this code using 2-D and 1-D arrays and passing the 2-D array to a void function which prints the areas of each of the plots. These are the inputs and their respective outputs I got. I am using Ubuntu 18.04 LTS Terminal.
RUN OF THE PROGRAM
Input:
1
137.4
80.9
0.78
2
155.2
92.62
0.89
3
149.3
97.93
1.35
4
160.0
100.25
9.00
5
155.6
68.95
1.25
6
149.7
120.0
1.75
Output:
Entered Data is:
1.000000 137.399994 80.900002 0.780000
2.000000 155.199997 92.620003 0.890000
3.000000 149.300003 97.930000 1.350000
4.000000 160.000000 100.250000 9.000000
5.000000 155.600006 68.949997 1.250000
6.000000 149.699997 120.000000 1.750000
Area of plot 1 is: 0.000000.
Area of plot 2 is: 0.000000.
Area of plot 3 is: 0.000000.
Area of plot 4 is: 0.000000.
Area of plot 5 is: 0.000000.
Area of plot 6 is: 0.000000.
Program:
#include <stdio.h>
#include <math.h>
void area(float p[6][4],int m,int n);
int main()
{
float a[6][4];
int i,j;
printf("Enter the plot no.,two sides and included angle.\n");
for(i=0;i<6;i++)
{
for(j=0;j<4;j++)
{
scanf("%f",&a[i][j]);
}
}
printf("Entered Data is:\n");
for(i=0;i<6;i++)
{
for(j=0;j<4;j++)
{
printf("%f ",a[i][j]);
}
printf("\n");
}
printf("\n");
area(a,6,4);
return 0;
}
void area(float p[6][4],int m,int n)
{
float ar[6];
int i;
for(i=0;i<6;i++)
{
ar[i] = (1/2)*(p[i][1])*(p[i][2])*sin(p[i][3]);
printf("Area of plot %d is: %f.\n",i+1,ar[i]);
}
}
In this expression:
ar[i] = (1/2)*(p[i][1])*(p[i][2])*sin(p[i][3]);
(1/2) evaluates as zero, which means the whole thing comes out as zero (because zero times anything is zero). The reason for it being zero is because it's integer division, which gives a truncated integer as its result. Use 0.5 instead.
(1.0/2.0) * (p[i][1]) * (p[i][2]) * sin(p[i][3]);

Length of the intercept from intersection of a line with a cylinder (ring)

I have some sources with coordinates (xn, yn, zn) w.r.t a center C of a ring and unit vectors (ns_ux, ns_uy, ns_uz) along my line of sight. I want to calculate whether these sources pass through a cylinder of inner and outer radius 9.5 and 10.5 units, respectively. If they intersect this cylinder (or I call it ring, sometimes), then I would like to calculate the length of this intercept. My position is outside of this ring and there are sources which lie beyond the center C on the other side. These sources, therefore will pass through this ring twice. This picture should help visualize this problem.
#define PI 3.142
int main(){
int k,number=200;
float r_min=9.50000;
float r_max=10.500000;
float step=0.3;
float z_c = 3.0;
float ns_ux[number],ns_uy[number],ns_uz[number],xn[number], yn[number],zn[number],l[number],b[number],ns[number],x_comp,y_comp,z_comp,radial;
FILE* val= NULL;
val=fopen("novae_uniform_unitvectors.txt", "r");
for(k=0;k<=(number-1);k++){
fscanf(val,"%f %f %f %f %f %f %f %f %f", &xn[k], &yn[k], &zn[k], &ns_ux[k], &ns_uy[k], &ns_uz[k], &l[k], &b[k], &ns[k]);
float u=0.;
for (u=0.;u<=30.;u=u+step){
x_comp=xn[k]+u*ns_ux[k];
vector addition : calculating the x_comp w.r.t the center C when stepped by 'u' units along my l.o.s.
y_comp=yn[k]+u*ns_uy[k];
radial=pow((x_comp*x_comp+y_comp*y_comp),0.5);
if (radial >=r_min && radial <=r_max){
z_comp=zn[k]+u*ns_uz[k];
checking if the height is consistent with the ring's height
if(z_comp >=-z_c && z_comp <= z_c)
printf("%f\t%f\t%f\t%f\n",l[k],u, z_comp, radial);
}
}
}
return 0.;
}
This 'radial' values gives me a list of points where my line of sight intersects with the ring. But, I require only the end points to calculate the length of the intercept on the ring.
e.g. in the case listed below, my l.o.s. passes through the ring at I and then comes off at II. Then it keeps going until it hits the ring again at III and then come out of it at IV. I need to store only I, II , III and IV points in my file. How would I be able to do it ?
longitude..........u........ z_comp........radial
121.890999 0.100000 0.016025 9.561846 I
121.890999 0.200000 0.038453 9.538050
121.890999 0.300000 0.060881 9.515191 II
121.890999 4.799998 1.070159 9.518372 III
121.890999 4.899998 1.092587 9.541364
121.890999 4.999998 1.115016 9.565292
...... skipping to save space........
121.890999 7.399995 1.653297 10.400277
121.890999 7.499995 1.675725 10.444989
121.890999 7.599995 1.698153 10.490416 IV
Figured out a way to store only the final and initial values by using a boolean operator as follows (continued from the code in the question) :
define bool change = true;
...(rest of the program)...
if(radial >= r_min && radial <= r_max) {
z_comp = zn[k] + u * ns_uz[k];
if (z_comp >= -z_c && z_comp <= z_c)
if (change) {
printf("%f\t%f\t%f\t%f\t", l[k], b[k], ns[k], radial[i]);
change = !change;
}
} else { // if the condition of radial and z_comp is not met
if (!change) {
fprintf(fp, "%f\n", radial[i - 1]);
change = !change;
}
}
This would store only the first and the last values of the radial component (i.e. the end points of the intercept of the line of sight vector on the ring)

Why does this code print the sine curve upside down

The y values generated seem correct. See printf print out which prints increasing y vals. But when sent to SetPixel function it seems to print the sin e curve as if multiplied by -1???
What is wrong?
#include <windows.h>
//#include <stdio.h>
#include <math.h>
int main()
{
HWND console = GetConsoleWindow();
HDC dc = GetDC(console);
int pixel =0;
COLORREF C1= RGB(255,0,0); /* red */
for (double i = 0; i< 6.3; i+=0.05)
{
SetPixel(dc,pixel,(int)(100+50*sin(i)),C1);
/*printf("%d ", (int)(100+50*sin(i))); // prints numbers as expected, eg 100 102 104 107 109 112 etc */
pixel+=1;
}
ReleaseDC(console, dc);
return 0;
}
AFTER FEEDBACK
Due to Windows co-ordinate system starting (0,0) at top left you can just change sign of sin function like this:
SetPixel(dc,pixel,(int)(100+50*-sin(i)),C1);
That works.
The coordinate system isn't quite what you're expecting: y == 0 is the top, not the bottom, of the screen.
See Windows Coordinate System:
The x-coordinates increase to the right; y-coordinates increase from top to bottom.
The following illustrates it nicely (it talks about Java coordinates, but Windows coordinates are the same):
An easy way to work around this is to flip the sign of sin():
SetPixel(dc,pixel,(int)(100-50*sin(i)),C1);
↑

Making The Console Window Somewhat Static

Sorry if the title is poor, I could not think of a better one.
I saw a little console memory game program written in C++ recently that inspired me (just for the heck of it) to replicate in C (mainly for a certian aspect of this program that stuck out to me).
It intrigued me when I saw how the console window had sort of a static effect for example if you flipped a "card":
//Console Screen Before "Card Flip"
1 2 3
1 * * *
2 * * *
3 * * *
Flip Which Card? (x,y): _
Lets say I entered 1,1 a possible output of the program may have been:
//Console Screen After "Card Flip"
1 2 3
1 9 * *
2 * * *
3 * * *
Flip Which Card? (x,y): _
This is actually what insipred me to replicate the program, in all honesty that's my only goal is to replicate this sort of static console.
My guess is that the author of this program just clears the screen after every user input and reprints the updated matrix (in this case the unmasked value of 1,1).
So I decided to write a sort of setup screen for the initialization of a similar program:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int flips, x, y;
do
{
printf("*****Game Setup*****");
printf("\n\tGrid Size (x):_");
printf("\nGrid Size (y): ");
printf("\nAmount of Flips (0 is Unlimited): \n");
scanf("%d", &x);
system("cls");
}
while(x <= 0);
do
{
printf("*****Game Setup*****");
printf("\nGrid Size(x): %d", x);
printf("\n\tGrid Size(y):_");
printf("\nAmount of Flips (0 is Unlmited): \n");
scanf("%d", &y);
system("cls");
}
while(y <= 0);
do
{
printf("*****Game Setup*****");
printf("\nGrid Size(x): %d", x);
printf("\nGrid Size(y): %d", y);
printf("\n\tAmount of Flips (0 is Unlmited):_\n");
scanf("%d", &flips);
system("cls");
}
while(flips < 0);
if(!flips) printf("Beginning %d by %d Memory Game with Unlimited Flips...", x ,y);
else printf("Beginning %d by %d Memory Game with %d Flips...", x, y, flips);
return 0;
}
It works as expected but I feel like there is probably a better way to achieve this same effect, doing it this way would increase the length of my code exponentially, and can't be efficient. Not only that but by using this method the "UI" is lousy at best, I think it would be a lot better if I could somehow just move the flashing input cursor appropriately
For Example:
*****Game Setup*****
Grid Size (x): _
Grid Size (y):
...
Then I would enter 1 for example and the cursor would simply "move" down to the next area:
*****Game Setup*****
Grid Size(x): 1
Grid Size(y): _
...
I was thinking of accomplishing the latter with the %n specifier with printf somehow although I am not quite sure if that is even possible (I know very little about %n).
So is there a better way of doing this (more efficiently)?
And if so is there a way to "move" the cursor as described above?
How would YOU do something like this?
This whole concept just really peaked my curiosity.

Resources