language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include <stdio.h>
#include "vector.h"
int main()
{
vector v1;
vector v2;
vector z;
vector a;
printf("Ingrese x para vector1: ");
scanf("%d",&v1.x);
printf("Ingrese y para vector1: ");
scanf("%d",&v1.y);
printf("Ingrese x para vector2: ");
scanf("%d",&v2.x);
printf("Ingrese y para vector2: ");
scanf("%d",&v2.y);
z=addvec(v1, v2);
a=multvec(v1, v2);
printf("z = [%d %d]\n", z.x, z.y);
printf("a = [%d %d]\n", a.x, a.y);
return 0;
}
|
C
|
// C code file for a file ADT where we can read a single bit at a
// time, or write a single bit at a time
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "bitfile.h"
// open a bit file in "r" (read) mode or "w" (write) mode
struct bitfile *bitfile_open(char *filename, char *mode) {
struct bitfile *result = malloc(sizeof(struct bitfile));
result->file = fopen(filename, mode);
result->buffer = 0;
result->index = 0;
result->is_EOF = 0;
result->is_read_mode = strcmp(mode, "r") == 0;
return result;
}
// write a bit to a file; the file must have been opened in write mode
void bitfile_write_bit(struct bitfile *this, int bit) {
this->buffer = this->buffer | bit << this->index;
this->index++;
if (this->index == 8) {
this->buffer = fputc(this->buffer, this->file);
this->buffer = 0;
this->index = 0;
}
}
// read a bit from a file; the file must have been opened in read mode
int bitfile_read_bit(struct bitfile *this) {
if (this->index == 0) {
this->buffer = fgetc(this->file);
}
int bit = this->buffer & 1;
this->buffer >>= 1;
this->index++;
if (this->index == 8)
this->index = 0;
return bit;
}
// close a bitfile; flush any partially-filled buffer if file is open
// in write mode
void bitfile_close(struct bitfile *this) {
if (this->index != 0 || this->buffer != 0) {
fputc(this->buffer, this->file);
}
fclose(this->file);
free(this);
}
// check for end of file
int bitfile_end_of_file(struct bitfile *this) {
this->is_EOF = feof(this->file);
return this->is_EOF;
}
|
C
|
#include <stdio.h>
#include <math.h>
#include <mpi.h>
double f(double x,int n) {
int i,j;
double res;
res = 0.0;
for(i=1;i<=n;i++) {
for(j=1;j<=n;j++) {
double r1 = sin( ((pow(x,i) + pow(x,j))/2) );
double r2 = 1 - cos( (pow(x,i) + pow(x,j))/2 );
res += r1 * r2;
}
}
return -3 + res;
}
int main(int argc, char** argv) {
int rank,np;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &np);
double epsilon;
int n;
if(argc < 3) {
printf("Using default values for epsilon and n\n");
epsilon = pow(2,-30);
n = 100;
}else {
epsilon = atof(argv[1]);
n = atoi(argv[2]);
}
double startTime;
if(rank == 0) {
startTime = MPI_Wtime();
}
double start = 0.0; double end = 1.0;
while(end-start > epsilon) {
double mid = (start+end)/2;
double midVal = f(mid,n);
if(midVal>=0) {
end = mid;
}else {
start = mid;
}
}
printf("Root is in [%1.50f,%1.50f]\n",start,end);
double stopTime = MPI_Wtime();
printf("This took %.5f seconds\n", stopTime-startTime);
MPI_Finalize();
return 0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
int main()
{
int i,n;
//clrscr();
scanf("%d", &n);
for(i=1;i<=n;i=i+1);
{
printf("%d", i);
}
getch();
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<math.h>
struct node{
int key;
struct node *back;
};
typedef struct node Node;
Node * getnode()
{
return (Node *)malloc(sizeof(Node));
}
Node * push(Node * top, int a)
{
Node *temp;
if(top==NULL)
{
top=getnode();
top->key=a;
top->back=NULL;
}
else
{
temp=getnode();
temp->key=a;
temp->back=top;
top=temp;
}
return top;
}
Node * pop(Node *top)
{
Node *temp=top;
top=top->back;
free(temp);
return top;
}
void po2res(char *postfix, Node *top)
{
int k=0,b[2],result;
while(postfix[k]!='\0')
{
if(isdigit(postfix[k]))
{
int a=(int)postfix[k]-(int)'0';
top=push(top,a);
}
else
{
for(int j=0;j<2;j++)
{
b[j]=top->key;
top=pop(top);
}
if(postfix[k]=='+')
result=b[1]+b[0];
else if(postfix[k]=='-')
result=b[1]-b[0];
else if(postfix[k]=='*')
result=b[1]*b[0];
else if(postfix[k]=='/')
result=b[1]/b[0];
else if(postfix[k]=='%')
result=b[1]%b[0];
else if(postfix[k]=='^')
result=pow(b[1],b[0]);
top=push(top,result);
printf("%d%c%d=%d\n",b[1],postfix[k],b[0],result);
}
k++;
}
}
void main()
{
Node *top;
top=NULL;
char *postfix=(char *)malloc(100);
scanf("%s",postfix);
po2res(postfix,top);
}
|
C
|
/* functions related to quadric error metrics */
/* compute the quadric error for a query position of a vertex */
starreal quadricerrorquery(struct tetcomplex *mesh,
tag vtag,
starreal v[3])
{
struct quadric *q;
starreal quad;
/* fetch the quadric for this vertex */
q = (struct quadric *) arraypoolforcelookup(&surfacequadrics, vtag);
assert(q != NULL);
/* return zero if this is not a surface vertex */
if (q->hasquadric == false) return 0.0;
/* evaluate quadric */
/* Q(v) = v'Av + 2b'v + c */
quad = v[0]*v[0]*q->a2 + 2*v[0]*v[1]*q->ab + 2*v[0]*v[2]*q->ac + 2*v[0]*q->ad
+ v[1]*v[1]*q->b2 + 2*v[1]*v[2]*q->bc + 2*v[1]*q->bd
+ v[2]*v[2]*q->c2 + 2*v[2]*q->cd
+ q->d2;
/*
if (quad > 1.0e-8)
{
printf("Encountered a large quadric error of %g\n", quad);
printf("Quadric:\n");
printf(" a2 = %g\n", q->a2);
printf(" ab = %g\n", q->ab);
printf(" ac = %g\n", q->ac);
printf(" ad = %g\n", q->ad);
printf(" b2 = %g\n", q->b2);
printf(" bc = %g\n", q->bc);
printf(" bd = %g\n", q->bd);
printf(" c2 = %g\n", q->c2);
printf(" cd = %g\n", q->cd);
printf(" d2 = %g\n", q->d2);
printf("Vertex:\n");
printf(" x = %g\n", v[0]);
printf(" y = %g\n", v[1]);
printf(" z = %g\n", v[2]);
}
assert(quad < 1.0e-8);
*/
return quad;
}
/* compute the quadric error for a particular vertex's current position */
starreal quadricerror(struct tetcomplex *mesh,
tag vtag)
{
/* fetch this vertex's current position */
starreal *v = ((struct vertex *) tetcomplextag2vertex(mesh, vtag))->coord;
return quadricerrorquery(mesh, vtag, v);
}
/* compute the quadric error at a vertex, normalized to
be comparable to tetrahedron quality measures */
starreal quadricerrortet(struct tetcomplex *mesh,
tag vtag)
{
/* return the quadric error of this vertex scaled
by the quadric scale and offset by the quadric offset */
starreal qe = improvebehave.quadricoffset -
(improvebehave.quadricscale * quadricerror(mesh, vtag));
/* scale down so that perfect corresponds to equilateral */
if (improvebehave.qualmeasure == QUALMINSINE ||
improvebehave.qualmeasure == QUALWARPEDMINSINE)
{
qe *= SINEEQUILATERAL;
}
/* don't return negative qualities */
if (qe < 0.0) return 0.0;
return qe;
}
bool hasquadric(tag vtag)
{
struct quadric *q = (struct quadric *) arraypoolforcelookup(&surfacequadrics, vtag);
assert(q != NULL);
return q->hasquadric;
}
/* compute the gradient of the quadric error for query point */
void quadricgradquery(struct tetcomplex *mesh,
tag vtag,
starreal v[3],
starreal grad[3])
{
struct quadric *q;
/* fetch the quadric for this vertex */
q = (struct quadric *) arraypoolforcelookup(&surfacequadrics, vtag);
assert(q != NULL);
/* return a zero gradient if this is not a surface vertex */
if (q->hasquadric == false)
{
grad[0] = grad[1] = grad[2] = 0.0;
return;
}
/* grad(Q) = 2Av + 2b */
/* A = nn', b = dn */
/* so */
/* grad(Q) = 2 [xa2 + yab + zac + ad] */
/* [xab + yb2 + zbc + bd] */
/* [xac + ybc + zc2 + cd] */
/* negative because we want to *reduce* quadric error... */
grad[0] = -2.0 * (v[0]*q->a2 + v[1]*q->ab + v[2]*q->ac + q->ad);
grad[1] = -2.0 * (v[0]*q->ab + v[1]*q->b2 + v[2]*q->bc + q->bd);
grad[2] = -2.0 * (v[0]*q->ac + v[1]*q->bc + v[2]*q->c2 + q->cd);
/* scale gradient by quadric scale factor */
/*
grad[0] *= improvebehave.quadricscale;
grad[1] *= improvebehave.quadricscale;
grad[2] *= improvebehave.quadricscale;
*/
return;
}
/* compute the gradient of the quadric error for a vertex */
void quadricgrad(struct tetcomplex *mesh,
tag vtag,
starreal grad[3])
{
starreal *v;
/* fetch this vertex's position */
v = ((struct vertex *) tetcomplextag2vertex(mesh, vtag))->coord;
/* compute the gradient for the vertex's current position */
quadricgradquery(mesh, vtag, v, grad);
return;
}
/* compute the gradient of the quadric error, scaled for tet comparison */
void quadricgradtet(struct tetcomplex* mesh,
tag vtag,
starreal grad[3])
{
quadricgrad(mesh, vtag, grad);
/* vscale(improvebehave.quadricscale, grad, grad); */
}
/* add a quadric for a newly inserted vertex */
bool combinedincidentfacets(struct tetcomplex* mesh,tag vtx1, tag vtx2,tag vtx3,tag vtx4,tag boundfacelist[][3],int *boundfacenumber){
proxipool *pool;
arraypool *star;
link2dposition pos2d;
linkposition pos1d;
tag vertexandlink[2];
bool ghostfound = false;
tag looptag=0;
tag incidenttets[MAXINCIDENTTETS][4];
int numincident=0;
bool noghostflag = false;
int i,j;
tag prelooptag;
tag tetboundfacelist[4][3];
int tetboundfacenumber = 0;
pool = mesh->vertexpool;
if(vtx1 & 1 == GHOSTVERTEX & 1){
star = arraypoollookup(&(mesh->stars),vtx1);
link2diteratorinit(pool,star->linkhead,vtx1,&pos2d);
link2diterate(&pos2d,vertexandlink);
while(vertexandlink[0] != STOP){
if(vertexandlink[0] == GHOSTVERTEX){
ghostfound = true;
break;
}
link2diterate(&pos2d,vertexandlink);
}
if(ghostfound){
linkringiteratorinit(mesh->moleculepool,vertexandlink[1],vtx1,&pos1d);
prelooptag = STOP;
looptag = linkringiterate(&pos1d);
while(looptag != STOP){
if(prelooptag!=STOP){
boundfacelist[*boundfacenumber][0] = vtx1;
boundfacelist[*boundfacenumber][1] = prelooptag;
boundfacelist[*boundfacenumber][2] = looptag;
}
prelooptag = looptag;
looptag = linkringiterate(&pos1d);
*boundfacenumber+=1;
}
}
}
if(!ghostfound){
getincidenttets(mesh,vtx1,vtx2,vtx3,vtx4,incidenttets,&numincident,&noghostflag);
for(i=0;i<numincident;i++){
tetboundfacenumber = 0;
boundfaces(mesh,incidenttets[i][0],incidenttets[i][1],incidenttets[i][2],incidenttets[i][3],tetboundfacelist,&tetboundfacenumber);
for(j=0;j<tetboundfacenumber;j++){
if(tetboundfacelist[j][0] != vtx1 && tetboundfacelist[j][1] != vtx1 && tetboundfacelist[j][2] != vtx1)
continue;
boundfacelist[*boundfacenumber][0] = tetboundfacelist[j][0];
boundfacelist[*boundfacenumber][1] = tetboundfacelist[j][1];
boundfacelist[*boundfacenumber][2] = tetboundfacelist[j][2];
*boundfacenumber += 1;
}
}
}
ghostfound = false;
if(vtx2 & 1 == GHOSTVERTEX & 2){
star = arraypoollookup(&(mesh->stars),vtx2);
link2diteratorinit(pool,star->linkhead,vtx2,&pos2d);
link2diterate(&pos2d,vertexandlink);
while(vertexandlink[0] != STOP){
if(vertexandlink[0] == GHOSTVERTEX){
ghostfound = true;
break;
}
link2diterate(&pos2d,vertexandlink);
}
if(ghostfound){
linkringiteratorinit(mesh->moleculepool,vertexandlink[1],vtx2,&pos1d);
prelooptag = STOP;
looptag = linkringiterate(&pos1d);
while(looptag != STOP){
if(prelooptag!=STOP){
boundfacelist[*boundfacenumber][0] = vtx2;
boundfacelist[*boundfacenumber][1] = prelooptag;
boundfacelist[*boundfacenumber][2] = looptag;
}
prelooptag = looptag;
looptag = linkringiterate(&pos1d);
*boundfacenumber+=1;
}
}
}
if(!ghostfound){
getincidenttets(mesh,vtx2,vtx1,vtx4,vtx3,incidenttets,&numincident,&noghostflag);
for(i=0;i<numincident;i++){
tetboundfacenumber = 0;
boundfaces(mesh,incidenttets[i][0],incidenttets[i][1],incidenttets[i][2],incidenttets[i][3],tetboundfacelist,&tetboundfacenumber);
for(j=0;j<tetboundfacenumber;j++){
if(tetboundfacelist[j][0] != vtx2 && tetboundfacelist[j][1] != vtx2 && tetboundfacelist[j][2] != vtx2)
continue;
if(tetboundfacelist[j][0] == vtx1 || tetboundfacelist[j][1] != vtx1 || tetboundfacelist[j][2] == vtx1)
continue;
boundfacelist[*boundfacenumber][0] = tetboundfacelist[j][0];
boundfacelist[*boundfacenumber][1] = tetboundfacelist[j][1];
boundfacelist[*boundfacenumber][2] = tetboundfacelist[j][2];
*boundfacenumber += 1;
}
}
}
}
bool addquadric(struct tetcomplex *mesh,
tag vtag,
tag faces[][3],
int numfaces)
{
int i,j;
proxipool *pool = mesh->vertexpool;
struct vertex *newv, *vptr[3];
struct quadric *vquads[3];
starreal e1[3], e2[3], normal[3];
starreal facearea, d, normfactor;
/* create quadric */
struct quadric *q = (struct quadric *) arraypoolforcelookup(&surfacequadrics, vtag);
/* initialize quadric */
q->hasquadric = true;
q->a2 = q->ab = q->ac = q->ad
= q->b2 = q->bc = q->bd
= q->c2 = q->cd
= q->d2 = 0.0;
q->numfaces = 0;
q->facesum = 0.0;
q->edge2harm = 0.0;
newv = (struct vertex *) proxipooltag2object(pool, vtag);
vcopy(newv->coord, q->origpos);
/* accumulate fundamental quadric for each incident face */
for (i=0; i<numfaces; i++)
{
/* get the actual vertices */
vptr[0] = (struct vertex *) proxipooltag2object(pool, faces[i][0]);
vptr[1] = (struct vertex *) proxipooltag2object(pool, faces[i][1]);
vptr[2] = (struct vertex *) proxipooltag2object(pool, faces[i][2]);
/* get original vertex positions */
vquads[0] = (struct quadric *) arraypoolforcelookup(&surfacequadrics, faces[i][0]);
vquads[1] = (struct quadric *) arraypoolforcelookup(&surfacequadrics, faces[i][1]);
vquads[2] = (struct quadric *) arraypoolforcelookup(&surfacequadrics, faces[i][2]);
/* compute face normal */
/*
vsub(vptr[1]->coord, vptr[0]->coord, e1);
vsub(vptr[2]->coord, vptr[0]->coord, e2);
*/
vsub(vquads[1]->origpos, vquads[0]->origpos, e1);
vsub(vquads[2]->origpos, vquads[0]->origpos, e2);
cross(e1, e2, normal);
/* face area is 1/2 the length of the cross product */
facearea = vlength(normal) / 2.0;
if (facearea < 1.e-14 && 0)
{
printf("In addquadric, face (%d %d %d) has odd area %g.\n", (int) faces[i][0], (int) faces[i][1], (int) faces[i][2], facearea);
for (j=0; j<3; j++)
{
printf(" %d = (%g %g %g)\n", j, vquads[j]->origpos[0], vquads[j]->origpos[1], vquads[j]->origpos[2]);
}
}
/* normalize the normal */
vscale(1.0 / (facearea * 2.0), normal, normal);
/* compute the orthogonal distance from the plane of this face to
the origin */
d = -dot(normal, vptr[0]->coord);
q->numfaces++;
q->facesum += facearea;
/* add on 1/2 of 1 / l^2, because every edge will be counted twice */
if (vlength(e1) > 0.0 && vlength(e2) > 0.0)
{
q->edge2harm += (0.5 / (vlength(e1) * vlength(e1)));
q->edge2harm += (0.5 / (vlength(e2) * vlength(e2)));
}
/* accumulate the fundamental quadric from this face */
/* normal = [a b c] */
q->a2 += normal[0] * normal[0] * facearea;
q->ab += normal[0] * normal[1] * facearea;
q->ac += normal[0] * normal[2] * facearea;
q->ad += normal[0] * d * facearea;
q->b2 += normal[1] * normal[1] * facearea;
q->bc += normal[1] * normal[2] * facearea;
q->bd += normal[1] * d * facearea;
q->c2 += normal[2] * normal[2] * facearea;
q->cd += normal[2] * d * facearea;
q->d2 += d * d * facearea;
}
/* compute normalization */
/* quadric must have at least 3 surrounding faces */
assert(q->numfaces >= 3);
/* compute harmonic mean */
q->edge2harm = ((starreal) q->numfaces) / q->edge2harm;
/* compute normalization factor */
normfactor = q->edge2harm * q->facesum;
/* if the facesum is zero, bail */
if (q->facesum <= 0.0)
{
return false;
}
assert(q->edge2harm != 0.0);
assert(q->facesum != 0.0);
assert(normfactor != 0.0);
/* scale quadric by normalization factor */
q->a2 /= normfactor;
q->ab /= normfactor;
q->ac /= normfactor;
q->ad /= normfactor;
q->b2 /= normfactor;
q->bc /= normfactor;
q->bd /= normfactor;
q->c2 /= normfactor;
q->cd /= normfactor;
q->d2 /= normfactor;
return true;
}
/* normalize quadric by dividing by the sum of the face areas
and the harmonic mean of the edge lengths squared */
void normalizequadrics(struct tetcomplex *mesh)
{
struct quadric *q;
tag vertextag;
starreal normfactor; /* normalization factor */
/* check each quadric */
proxipool *pool = mesh->vertexpool;
vertextag = proxipooliterate(pool, NOTATAG);
while (vertextag != NOTATAG)
{
/* get the quadric for this vertex */
q = (struct quadric *) arraypoolforcelookup(&surfacequadrics, vertextag);
assert(q != NULL);
/* if this isn't a surface vertex, move on */
if (q->hasquadric == false)
{
/* move to next vertex */
vertextag = proxipooliterate(pool, vertextag);
continue;
}
/* normalize this vertex's quadric */
if (improvebehave.verbosity > 5)
{
printf("Normalizing quadric for vertex %d\n", (int) vertextag);
printf(" Quadric has %d incident faces\n", q->numfaces);
}
/* quadric must have at least 3 surrounding faces */
assert(q->numfaces >= 3);
/* compute harmonic mean */
q->edge2harm = ((starreal) q->numfaces) / q->edge2harm;
/* compute normalization factor */
normfactor = q->edge2harm * q->facesum;
if (improvebehave.verbosity > 5)
{
printf(" Edge length harmonic mean is %g\n", q->edge2harm);
printf(" Face area sum is %g\n", q->facesum);
printf(" Norm factor is %g\n", normfactor);
printf("Quadric:\n");
printf(" a2 = %g\n", q->a2);
printf(" ab = %g\n", q->ab);
printf(" ac = %g\n", q->ac);
printf(" ad = %g\n", q->ad);
printf(" b2 = %g\n", q->b2);
printf(" bc = %g\n", q->bc);
printf(" bd = %g\n", q->bd);
printf(" c2 = %g\n", q->c2);
printf(" cd = %g\n", q->cd);
printf(" d2 = %g\n", q->d2);
}
assert(normfactor != 0.0);
/* scale quadric by normalization factor */
q->a2 /= normfactor;
q->ab /= normfactor;
q->ac /= normfactor;
q->ad /= normfactor;
q->b2 /= normfactor;
q->bc /= normfactor;
q->bd /= normfactor;
q->c2 /= normfactor;
q->cd /= normfactor;
q->d2 /= normfactor;
vertextag = proxipooliterate(pool, vertextag);
}
}
/* create quadrics for all surface vertices */
void collectquadrics(tetcomplex *mesh)
{
struct arraypool facepool;
int numfaces = 0;
int i,j;
struct vertex *vptr[3];
tag vertextag;
tag *face;
starreal normal[3], e1[3], e2[3], facearea, d;
struct quadric *q;
proxipool *pool = mesh->vertexpool;
/* initialize the arraypool that stores the quadrics */
arraypoolinit(&surfacequadrics, sizeof(struct quadric), LOG2TETSPERSTACKBLOCK, 0);
/* allocate pool for faces */
arraypoolinit(&(facepool), sizeof(tag)*3, LOG2TETSPERSTACKBLOCK, 0);
/* find the surface faces */
getsurface(mesh, &facepool, &numfaces);
/* initialize all vertices to have no quadric */
vertextag = proxipooliterate(pool, NOTATAG);
while (vertextag != NOTATAG)
{
/* initialize this vertex to have no quadric */
((struct quadric *) arraypoolforcelookup(&surfacequadrics, vertextag))->hasquadric = false;
/* move to next vertex */
vertextag = proxipooliterate(pool, vertextag);
}
/* accumulate quadrics from each face to their vertices */
for (i=0; i<numfaces; i++)
{
/* fetch this face from the pool */
face = (tag *) arraypoolfastlookup(&facepool, (unsigned long) i);
/* get the actual vertices */
vptr[0] = (struct vertex *) proxipooltag2object(pool, face[0]);
vptr[1] = (struct vertex *) proxipooltag2object(pool, face[1]);
vptr[2] = (struct vertex *) proxipooltag2object(pool, face[2]);
assert(vptr[0] != NULL);
assert(vptr[1] != NULL);
assert(vptr[2] != NULL);
/*
printf("here are the vertex positions at the start\n");
printf("vptr[0]->coord is %p, vptr[0]->coord is (%g %g %g)\n", vptr[0]->coord, vptr[0]->coord[0], vptr[0]->coord[1], vptr[0]->coord[2]);
printf("vptr[1]->coord is %p, vptr[1]->coord is (%g %g %g)\n", vptr[1]->coord, vptr[1]->coord[0], vptr[1]->coord[1], vptr[1]->coord[2]);
printf("vptr[2]->coord is %p, vptr[2]->coord is (%g %g %g)\n", vptr[2]->coord, vptr[2]->coord[0], vptr[2]->coord[1], vptr[1]->coord[2]);
printf("vptr is %p\n", vptr[0]);
*/
/* compute face normal */
vsub(vptr[1]->coord, vptr[0]->coord, e1);
vsub(vptr[2]->coord, vptr[0]->coord, e2);
cross(e1, e2, normal);
/* face area is 1/2 the length of the cross product */
facearea = vlength(normal) / 2.0;
/* normalize the normal */
vscale(1.0 / (facearea * 2.0), normal, normal);
/* compute the orthogonal distance from the plane of this face to
the origin */
d = -dot(normal, vptr[0]->coord);
/* accumulate the quadric at each of the face's vertices */
for (j=0; j<3; j++)
{
/* fetch the quadric */
q = (struct quadric *) arraypoolforcelookup(&surfacequadrics, face[j]);
assert(q != NULL);
/* if it is not set, initialize it */
if (q->hasquadric == false)
{
q->hasquadric = true;
q->a2 = q->ab = q->ac = q->ad
= q->b2 = q->bc = q->bd
= q->c2 = q->cd
= q->d2 = 0.0;
q->numfaces = 0;
q->facesum = 0.0;
q->edge2harm = 0.0;
q->origpos[0] = vptr[j]->coord[0];
q->origpos[1] = vptr[j]->coord[1];
q->origpos[2] = vptr[j]->coord[2];
/*
vcopy(vptr[j]->coord, q->origpos);
*/
}
q->numfaces++;
q->facesum += facearea;
/* add on 1/2 of 1 / l^2, because every edge will be counted twice */
q->edge2harm += (0.5 / (vlength(e1) * vlength(e1)));
q->edge2harm += (0.5 / (vlength(e2) * vlength(e2)));
/* accumulate the fundamental quadric from this face */
/* normal = [a b c] */
q->a2 += normal[0] * normal[0] * facearea;
q->ab += normal[0] * normal[1] * facearea;
q->ac += normal[0] * normal[2] * facearea;
q->ad += normal[0] * d * facearea;
q->b2 += normal[1] * normal[1] * facearea;
q->bc += normal[1] * normal[2] * facearea;
q->bd += normal[1] * d * facearea;
q->c2 += normal[2] * normal[2] * facearea;
q->cd += normal[2] * d * facearea;
q->d2 += d * d * facearea;
}
}
/* now, go through quadrics again to normalize them */
normalizequadrics(mesh);
}
/* do a bunch of checks on quadrics */
void checkquadricsstream(FILE *o, tetcomplex *mesh)
{
tag vertextag;
starreal avgquad = 0.0;
starreal minquad = HUGEFLOAT;
starreal maxquad = 0.0;
starreal thisquad;
starreal avggrad = 0.0;
starreal mingrad = HUGEFLOAT;
starreal maxgrad = 0.0;
starreal thisdot;
starreal avgdot = 0.0;
starreal maxdot = 0.0;
starreal mindot = HUGEFLOAT;
starreal thisgrad;
starreal offset[] = {-10.0, -10.0, -10.0};
starreal correctgrad[] = {1.0, 1.0, 1.0};
starreal testpos[3];
starreal grad[3];
starreal normgrad[3];
struct quadric *q;
int numquads = 0;
/* check each quadric */
proxipool *pool = mesh->vertexpool;
vertextag = proxipooliterate(pool, NOTATAG);
while (vertextag != NOTATAG)
{
/* get the quadric error for this vertex */
thisquad = quadricerror(mesh, vertextag);
quadricgrad(mesh, vertextag, grad);
thisgrad = vlength(grad);
q = (struct quadric *) arraypoolforcelookup(&surfacequadrics, vertextag);
assert(q != NULL);
if (q->hasquadric == false)
{
/* move to next vertex */
vertextag = proxipooliterate(pool, vertextag);
continue;
}
/* offset the vertex to a new position */
vadd(q->origpos, offset, testpos);
/* compute the gradient for this new position */
quadricgradquery(mesh, vertextag, testpos, grad);
vscale(1.0 / vlength(grad), grad, normgrad);
/* compute the dot product of this with the expected grad */
thisdot = dot(correctgrad, normgrad);
/*
if (vertextag < 100)
{
printf("Testing quadric gradient for vertex %d.\n", (int) vertextag);
printf(" Original position is (%g %g %g)\n", q->origpos[0], q->origpos[1], q->origpos[2]);
printf(" The offset position is (%g %g %g)\n", testpos[0], testpos[1], testpos[2]);
printf(" The gradient is (%g %g %g)\n", grad[0], grad[1], grad[2]);
printf(" The normalized gradient is (%g %g %g)\n", normgrad[0], normgrad[1], normgrad[2]);
}
*/
/* accumulate statistics */
if (thisquad != 0.0)
{
avgquad += thisquad;
avggrad += thisgrad;
avgdot += thisdot;
numquads++;
}
if (thisquad > maxquad) maxquad = thisquad;
if (thisquad < minquad) minquad = thisquad;
if (thisgrad > maxgrad) maxgrad = thisgrad;
if (thisgrad < mingrad) mingrad = thisgrad;
if (thisdot > maxdot) maxdot = thisdot;
if (thisdot < mindot) mindot = thisdot;
/* move to next vertex */
vertextag = proxipooliterate(pool, vertextag);
}
avgquad /= (starreal) numquads;
avggrad /= (starreal) numquads;
avgdot /= (starreal) numquads;
fprintf(o, "Quadriccheck:\n");
fprintf(o, " Average quadric error: %g\n", avgquad);
fprintf(o, " Number non-zero: %d\n", numquads);
fprintf(o, " Minimum quadric error: %g\n", minquad);
fprintf(o, " Maximum quadric error: %g\n", maxquad);
fprintf(o, " Average gradient mag: %g\n", avggrad);
fprintf(o, " Minimum gradient mag: %g\n", mingrad);
fprintf(o, " Maximum gradient mag: %g\n", maxgrad);
fprintf(o, " Average dot mag: %g\n", avgdot);
fprintf(o, " Minimum dot mag: %g\n", mindot);
fprintf(o, " Maximum dot mag: %g\n", maxdot);
}
void checkquadrics(tetcomplex *mesh)
{
checkquadricsstream(stdout, mesh);
}
|
C
|
#include "list.h"
#include <stdlib.h>
#include <string.h>
/**
* add_node_end - Add a new node to the end of a double circular linked list
* @list: A pointer to the head of the linkd list
* @str: the string to copy into the node
* Return: pointer to the created node
*/
List *add_node_end(List **list, char *str)
{
List *node, *tmp = *list;
if (!list)
return (NULL);
if (!*list)
{
node = malloc(sizeof(List));
if (!node)
return (NULL);
node->str = strdup(str);
if (str != NULL && node->str == NULL)
{
free(node);
return (NULL);
}
node->next = node;
node->prev = node;
*list = node;
return (node);
}
while (tmp)
{
if (tmp->next == *list)
break;
tmp = tmp->next;
}
node = malloc(sizeof(List));
if (!node)
return (NULL);
node->str = strdup(str);
if (str != NULL && node->str == NULL)
{
free(node);
return (NULL);
}
tmp->next = node;
node->prev = tmp;
node->next = *list;
(*list)->prev = node;
return (node);
}
/**
* add_node_begin - Add a new node to the beginning of a double linked list
* @list: A pointer to the head of the linkd list
* @str: the string to copy into the node
* Return: pointer to the created node
*/
List *add_node_begin(List **list, char *str)
{
List *node, *tmp = *list;
if (!list)
return (NULL);
node = malloc(sizeof(List));
if (!node)
return (NULL);
node->str = strdup(str);
if (str != NULL && node->str == NULL)
{
free(node);
return (NULL);
}
if (!*list)
{
node->next = node;
node->prev = node;
*list = node;
return (node);
}
node->next = *list;
(*list)->prev = node;
while (tmp)
{
if (tmp->next == *list)
break;
tmp = tmp->next;
}
tmp->next = node;
*list = node;
if (!(*list)->prev)
(*list)->prev = tmp;
return (node);
}
|
C
|
/** @file main.c
*
* kernel.c: Kernel main (entry) function
*
* Author: Satvik Dhandhania <sdhandha@andrew.cmu.edu>
* Vallari Mehta <vallarim@andrew.cmu.edu>
*
* Date: 25th Nov 2015
*/
//Given in src code
#include <kernel.h>
#include <task.h>
#include <sched.h>
#include <device.h>
#include <assert.h>
#include <lock.h>
//Imported from Lab3
#include <exports.h>
#include <arm/psr.h>
#include <arm/reg.h>
#include <arm/exception.h>
#include <arm/interrupt.h>
#include <arm/timer.h>
#define SWI_VECTOR 0x08
#define PC_OFFSET 0x08
#define MASK_ONE 0x1
#define OFFSET_MASK 0xFFF
#define POSITIVE_OFFSET 0xe51ff000
#define NEGATIVE_OFFSET 0xe59ff000
#define NEW_INSTRUCTION1 0xe51ff004
#define MASK_CHECK_LDR 0xFF7FF000
#define IRQ_VECTOR 0x18
#define TEN_MILLIS_MATCH_VALUE 32500
#define SET_SWI 1
#define SET_IRQ 2
//Storing U-boot registers
uint32_t stack_pointer, link_register;
//SWI Restore variables
unsigned int swi_instruction1;
unsigned int swi_instruction2;
unsigned int *swi_address;
//IRQ Restore variables
unsigned int irq_instruction1;
unsigned int irq_instruction2;
unsigned int *irq_address;
//Timer Restore Variables
//volatile unsigned long timer_count = 0;
unsigned long CPSR;
unsigned long OSMR0; // OS_TIMER_MATCH_REGISTER_0
unsigned long OIER; // OS_TIMER_INTERRUPT_ENABLE_REGISTER
unsigned long ICLR; // Interrupt Controller Level Register
unsigned long ICMR; // Interrupt Controller Mask Register
extern void irq_stack_setup();
extern void user_mode_setup();
extern void swihandler();
extern void irq_wrapper();
extern void set_timer();
uint32_t global_data;
extern int hijacking(unsigned int base_vector, int mode);
int kmain(int argc __attribute__((unused)), char** argv __attribute__((unused)), uint32_t table, uint32_t spointer ,uint32_t lregister)
{
app_startup();
global_data = table;
/* add your code up to assert statement */
stack_pointer = spointer; // Storing stack pointer
link_register = lregister; //storing link register
//Replacing SWI handler with our custom handler
if(hijacking(SWI_VECTOR, SET_SWI )==0xbadc0de)
return 0xbadc0de;
//Replacing IRQ handler with our custom handler
if(hijacking(IRQ_VECTOR, SET_IRQ )==0xbadc0de)
return 0xbadc0de;
//Setting timer variable as per our applications need
set_timer();
mutex_init();
user_mode_setup(argc,argv); //Initializes stack for the user
return -255;
assert(0); /* should never get here */
}
|
C
|
//
// ARGS: sort Algo, file to sort, -o, file to print to, -k, col to sort on, filesize
// 0 1 2 3 4 5 6
#include "root.h"
#include <sys/times.h> /* times() */
int sort_column;
void swap(Record * a, Record * b)
{
Record tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
int main( int argc, char ** argv)
{
char * to_sort = argv[1];
char * out = argv[3];
FILE * time_out;
char line[200];
int sort_col; sscanf (argv[5], "%d", &sort_col);
int num_rows, i, ch, swaps;
char attribute[10];
Record * records;
FILE * in_fd;
FILE * out_fd;
int rows;
double t1, t2;
struct tms tb1, tb2;
double ticspersec;
ticspersec = (double) sysconf(_SC_CLK_TCK);
t1 = (double) times(&tb1);
sscanf (argv[6], "%d", &rows);
sscanf (argv[5], "%d", &sort_column);
if((in_fd = fopen(argv[1], "rt")) == 0)
{
perror("Could not open file for sort\n");
}
records = (Record *) malloc(sizeof(Record) * rows);
while (fscanf(in_fd, "%s %s %s %s",records[i].ssn,records[i].last, records[i].first, records[i].income) != EOF)
{
i++;
}
num_rows = i;
swaps = 1;
while (swaps != 0)
{
swaps = 0;
for(i=0; i<(rows-1); i++)
{
switch(sort_column)
{
case 1:
if( strcmp(records[i].ssn, records[i+1].ssn)>0 )
{
swap(&records[i], &records[i+1]);
swaps++;
}
break;
case 2:
if( strcmp(records[i].last, records[i+1].last)>0 )
{
swap(&records[i], &records[i+1]);
swaps++;
}
break;
case 3:
if( strcmp(records[i].first, records[i+1].first)>0 )
{
swap(&records[i], &records[i+1]);
swaps++;
}
break;
case 4:
if( strcmp(records[i].income, records[i+1].income)>0 )
{
swap(&records[i], &records[i+1]);
swaps++;
}
break;
}
}
}
out_fd = fopen(argv[3], "wt");
for(i=0; i<num_rows; i++)
{
fprintf(out_fd, "%s %s %s %s\n", records[i].ssn, records[i].last, records[i].first, records[i].income);
}
fclose(out_fd);
free(records);
t2 = (double) times(&tb2);
time_out = fopen("timeData.txt", "at");
fprintf(time_out, "Bubble sort took %lf seconds\n",(t2 - t1) / ticspersec);
fclose(time_out);
return 0;
}
|
C
|
/**
* @brief It defines the die interpreter
*
* @file die.h
* @author Ana Roa González
* @version 1.0
* @date 06-03-2018
*/
#ifndef DIE_H
#define DIE_H
#include "../include/types.h"
typedef struct _Die Die;
/**
* @author Ana Roa González
* @brief Crea un dado
* @return Puntero a Die
*/
Die* die_create();
/**
* @author Ana Roa González
* @brief Destruye un dado
* @param dado: Puntero a Die
* @return ERROR o OK
*/
STATUS die_destroy(Die* dado);
/**
* @author Ana Roa González
* @brief Devuelve el id del dado
* @param dado: Puntero a Die
* @return Tipo Id
*/
Id die_get_id(Die* dado);
/**
* @author Ana Roa González
* @brief Modifica el id del dado
* @param dado: Puntero a Die
* @paaram id:Tipo Id
* @return ERROR o OK
*/
STATUS die_set_id(Die* dado, Id id);
/**
* @author Ana Roa González
* @brief Devuelve el ultimo numero sacado por el dado
* @param dado: Puntero a Die
* @return Tipo entero
*/
int die_get_numero(Die* dado);
/**
* @author Ana Roa González
* @brief Modifica el ultimo sacado por el dado
* @param dado: Puntero a Die
* @param numero: Tipo entero
* @return ERROR o OK
*/
STATUS die_set_numero(Die* dado, int numero);
/**
* @author Ana Roa González
* @brief Genera un numero aleatorio
* @param a: Tipo entero
* @param b: Tipo entero
* @return Tipo entero
*/
int aleatorio(int a, int b);
/**
* @author Ana Roa González
* @brief Tira el dado
* @param dado: Puntero a Die
* @return ERROR o OK
*/
STATUS die_roll(Die* dado);
/**
* @author Ana Roa González
* @brief Imprime el dado
* @param pf: Tipo FILE
* @param dado: Puntero a Die
* @return ERROR o OK
*/
STATUS die_print(FILE* pf ,Die* dado);
#endif
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_lstmap.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gbudau <gbudau@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/11/29 20:22:20 by gbudau #+# #+# */
/* Updated: 2020/12/28 20:34:00 by gbudau ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static t_list *clear_list(t_list **lst, void (*del)(void *))
{
ft_lstclear(lst, del);
return (NULL);
}
t_list *ft_lstmap(t_list *lst, void *(*f)(void *), void (*del)(void *))
{
t_list *trav;
t_list *new_lst;
t_list *temp;
void *content;
trav = lst;
new_lst = NULL;
while (trav != NULL)
{
content = f(trav->content);
if (content == NULL)
return (clear_list(&new_lst, del));
temp = ft_lstnew(content);
if (temp == NULL)
return (clear_list(&new_lst, del));
ft_lstadd_front(&new_lst, temp);
trav = trav->next;
}
ft_lstrev(&new_lst);
return (new_lst);
}
|
C
|
#include<stdio.h>
void main()
{
int money;
printf("ENTER THE SUM OF MONEY\n");
scanf("%d",&money);
int denomination[9];
for(int i=0;i<9;i++)
{
denomination[i]=0;
}
int h=money%10;
if(h>=5)
{
h=h-5;
denomination[2]=1;
}
if(h%2==0)
{
denomination[1]=h/2;
}
else
{
denomination[0]=1;
h=h-1;
denomination[1]=h/2;
}
int m=money;
m=m-(m%10);
m=m/10;
int f=m%10;
if(f>=5)
{
f=f-5;
denomination[5]=1;
}
if(f%2==0)
{
denomination[4]=f/2;
}
else
{
denomination[3]=1;
denomination[4]=(f-1)/2;
}
m=m-(m%10);
m=m/10;
int k=m%10;
if(k>=5)
{
k=k-5;
denomination[7]=1;
}
denomination[6]=k;
m=m-(m%10);
m=m/10;
if(m>=2)
{
if(m%2==0)
{
denomination[8]=m/2;
}
else
{
m=m-1;
denomination[7]=denomination[7]+2;
denomination[8]=m/2;
}
}
else
{
denomination[7]=denomination[7]+2;
}
int den[9]={1,2,5,10,20,50,100,500,2000};
for(int n=0;n<9;n++)
{
if(denomination[n]>0)
{
printf("THE NUMBER OF NOTES OF RS %d DENOMINATIONS ARE = %d",den[n],denomination[n]);
printf("\n");
}
}
}
|
C
|
/*
** list_rev.c for list_rev in ~/c/rendu/piscine/j6
**
** Made by jean-daniel michaud
** Login <michau_j@epita.fr>
**
** Started on Tue Oct 2 21:03:41 2001 jean-daniel michaud
** Last update Thu Oct 4 02:04:49 2001 jean-daniel michaud
*/
#include "list.h"
#include "dlist.h"
void dlist_rev(t_dlist **dlist)
{
t_dlist *tmp;
t_dlist *l;
if (!(*dlist))
return;
l = *dlist;
while (l->next != 0)
{
tmp = l->next;
l->next = l->prev;
l->prev = tmp;
l = tmp;
}
tmp = l->next;
l->next = l->prev;
l->prev = tmp;
*dlist = l;
}
|
C
|
#include "push_swap.h"
void ft_free_arr(char **arr)
{
int i;
i = 0;
while (arr[i])
free(arr[i++]);
free(arr);
arr = NULL;
}
|
C
|
#include <stdio.h> /* tells the compiler to include information about the standard input/output library */
/* Exercise 1-7 Write a program to print the value of EOF */
main()
{
printf( "The value of EOF is %d\n" , EOF ); // Print the EOF value (numeric)
}
|
C
|
#include <stdio.h>
#include <string.h>
int lowerToUpper(char []);
int main(void)
{
char inputWord[40];
printf("Type a word in the lower case: ");
scanf("%s", inputWord);
if(lowerToUpper(inputWord) == 1){
printf("The word in the upper case: %s\n", inputWord);
}
return 0;
}
int lowerToUpper(char a[])
{
char *cptr;
cptr = a;
while(*cptr != '\0')
{
if(*cptr >='a' && *cptr <= 'z')
{
*cptr = *cptr + 'A' - 'a';
cptr++;
}
else
{
return 0;
}
}
return 1;
}
|
C
|
#include<stdio.h>
int main(){
int t,n,x,y;
scanf("%d",&t);
while(t--){
int ans=0;
scanf("%d",&n);
while(n--){
scanf("%d %d",&x,&y);
if((y-x)>5) {
ans++;}
}
printf("%d\n",ans);
}
}
|
C
|
#include <stdio.h>
int main() {
int m[6] = {2,1,3,4,5}; //数组初始化末尾不会赋值0
int n[6] = {5,6,7,8,9};
int *pm = m;
int *pn = n;
int tmp;
int i;
while(*pm) {
tmp = *pm;
*pm = *pn;
*pn = tmp;
*pm++;
*pn++;
}
printf("After m exchange:");
for(i=0;i<5;i++) {
printf("%d",m[i]);
}
printf("\n");
printf("After n exchange:");
for(i=0;i<5;i++) {
printf("%d",n[i]);
}
printf("\n");
return 0;
}
|
C
|
#include <stdio.h>
#ifndef FLAG
#define FLAG ""
#endif
static const char* flag =
"the flag is in this binary, you'll never find it!\0"
"Look at this photograph\n"
"Every time I do, it makes me laugh\n"
"How did our eyes get so red?\n"
"And what the hell is on Joey's head?\n"
"And this is where I grew up\n"
"I think the present owner fixed it up\n"
"I never knew we ever went without\n"
"The second floor is hard for sneaking out\n"
"And this is where I went to school\n"
"Most of the time had better things to do\n"
"Criminal record says I broke in twice\n"
"I must've done it half a dozen times\n"
"I wonder if it's too late\n"
"Should I go back and try to graduate?\n"
"Life's better now than it was back then\n"
"If I was them, I wouldn't let me in\n"
"\n"
"Oh, oh, oh\n"
"Oh, God, I, I\n"
"Every memory of looking out the back door\n"
"I had the photo album spread out on my bedroom floor\n"
"It's hard to say it, time to say it\n"
"Goodbye, goodbye\n"
"Every memory of walking out the front door\n"
"I found the photo of the friend that I was looking for\n"
"It's hard to say it, time to say it\n"
"Goodbye, goodbye\n"
"(Goodbye)\n"
"\n"
"Remember the old arcade?\n"
"Blew every dollar that we ever made\n"
"The cops hated us hangin' out\n"
"They say somebody went and burned it down\n"
"We used to listen to the radio\n"
"And sing along with every song we know\n"
"We said someday we'd find out how it feels\n"
"To sing to more than just the steering wheel\n"
"Kim's the first girl I kissed\n"
"I was so nervous that I nearly missed\n"
"She's had a couple of kids since then\n"
"I haven't seen her since God knows when\n"
"\n"
"Oh, oh, oh\n"
"Oh, God, I, I\n"
"Every memory of looking out the back door\n"
"I had the photo album spread out on my bedroom floor\n"
"It's hard to say it, time to say it\n"
"Goodbye, goodbye\n"
"Every memory of walking out the front door\n"
"I found the photo of the friend that I was looking for\n"
"It's hard to say it, time to say it\n"
"Goodbye, goodbye\n"
"\n"
"I miss that town\n"
"I miss their faces\n"
"You can't erase\n"
"You can't replace it\n"
"I miss it now\n"
"I can't believe it\n"
"So hard to stay\n"
"Too hard to leave it\n"
"If I could, I'd relive those days\n"
"I know the one thing that would never change\n"
"\n"
"Every memory of looking out the back door\n"
"I had the photo album spread out on my bedroom floor\n"
"It's hard to say it, time to say it\n"
"Goodbye, goodbye\n"
"Every memory of walking out the front door\n"
"I found the photo of the friend that I was looking for\n"
"It's hard to say it, time to say it\n"
"Congratulations, You found a flag\n"
FLAG "\n"
"Goodbye, goodbye\n"
"\n"
"Look at this photograph\n"
"Every time I do, it makes me laugh\n"
"Every time I do, it makes me\n"
;
int main(int argc, char** argv) {
printf("%s\n", flag);
(void) argc;
(void) argv;
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(int argc, char *argv[])
{
double a=0, b=0, c=0, x=0, x1=0, x2=0, d=0;
printf("Entrer les valeurs de a, de b et de c:\n");
scanf("%lf %lf %lf", &a, &b, &c);
d=pow(b,2)-4*a*c;
if (d>0)
{
printf("Il y a deux solutions:\n");
x1=(-b-sqrt(d))/2*a;
x2=(-b+sqrt(d))/2*a;
printf("Les solutions sont: %lf et %lf", x1, x2);
}
else if(d<0)
{
printf("pas de solutions\n");
}
else
{
printf("Il y a une seule solution.");
x=(-b)/(2*a);
printf("Cette solution est: %lf", x);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdarg.h>
void print_integer(int num)
{
printf("%d", num);
}
void print_float(float fnum)
{
printf("%f", fnum);
}
int simple_printf(const char *format, ...)
{
va_list var_arg;
char cvalue;
char *svalue;
va_start(var_arg, format);
while (*format) {
switch (*format) {
case '%':
format++;
switch (*format) {
case 'd':
print_integer(va_arg(var_arg, int));
break;
case 'f':
print_float(va_arg(var_arg, double));
break;
case 's':
svalue = va_arg(var_arg, char *);
while (*svalue)
putchar(*svalue++);
break;
case 'c':
cvalue = va_arg(var_arg, int);
putchar(cvalue);
break;
default:
goto error;
break;
}
break;
default:
putchar(*format);
break;
}
format++;
}
error:
va_end(var_arg);
}
int main(void)
{
simple_printf("== %d %f %s %c ===\n", 1234, 33.44, "string", 'c');
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../include/database.h"
#include "../include/venta.h"
#include "../include/inventario.h"
#include "../include/login.h"
#include <stdbool.h>
#if defined(__WIN32) //Windows detectado
#include <windows.h>
#include <conio.h>
#elif defined(__linux__) //Linux detectado
#include <unistd.h>
#include "../include/getch.h"
#endif
#define MAX_FACTURAS 100
#define MAX_LETTERS 50
// Variables globales.
facturas Facturas[MAX_FACTURAS];
struct products;
//TODO Preguntar si puedo en este caso usar la estructura
//TODO para que le pase cantidad a Facturas.cantidad y asi poder
//TODO pasarselo a venta_return_contabilidad.
int obtener_ventas_suma()
{
int sum = 0;
for (size_t i = 0; i < MAX_FACTURAS; i++)
{
if (Facturas[i].full)
sum += Facturas[i].Total;
}
return sum;
}
void llenar_facturas(unsigned id, unsigned cantidad)
{
bool temp = true;
for (size_t i = 0; i < MAX_FACTURAS && temp; i++)
{
if (!Facturas[i].full)
{
if ((Facturas[i].Precio = get_price_by_id(id)) == -1)
{
printf("No se pudo obtener el precio deseado");
return;
}
Facturas[i].full = true;
strcpy(Facturas[i].nombre_cliente, get_username());
strcpy(Facturas[i].nombre_producto, get_name_by_id(id));
Facturas[i].id_producto_deseado = id;
Facturas[i].Cantidad = cantidad;
Facturas[i].Total = Facturas[i].Precio * Facturas[i].Cantidad;
Facturas[i].TotalaPagar += Facturas[i].Total;
temp = false;
}
}
}
void inicializar_facturas()
{
for (size_t i = 0; i < MAX_FACTURAS; i++)
{
Facturas[i].full = false;
}
}
/**
* @brief Regresa al usuario a lo que es el menu de inicio de los modulos
*
* @return true El usuario ha salido del modulo y se va al menu inicial del programa
* @return false No se ejecutara la funcion
*/
bool go_back()
{
if (GO_BACK_OUT_VENTAS)
{
clear_screen();
login_menu();
}
return false;
}
/**
* @brief Da el total de todas las facturas/ventas realizadas al momento
*
*/
void cash_register()
{
char c;
clear_screen();
//Quiero imprimir todos los totales de las facturas para el reporte de caja
printf("\t\t\t\aEstas en la Caja Registradora\n");
if (Facturas[0].full)
{
printf("\t\t\aEl total generado ha sido de: %d.\n\n", obtener_ventas_suma());
printf("Presione cualquier tecla para volver al menu principal...");
getch();
}
else
{
printf("No se ha realizado ninguna venta el dia de hoy =( ");
printf("Presione cualquier tecla para salir: ");
getch();
}
}
/**
* @brief Esta funcion eliminara totalmente las ventas hechas
* Permite editar cualquier factura, con la clave y usuario del admin
* Introduciendo el nombre del cliente se elimina automaticamente la factura
*/
void delete_orders()
{
char str[50];
clear_screen();
getchar();
printf("Cual de estas estas facturas desea eliminar.\n");
print_factura();
printf("\nIngre el nombre de usario: ");
fgets(str, sizeof(str), stdin);
for (size_t i = 0; i < MAX_FACTURAS; i++)
{
if (!strcmp(str, Facturas[i].nombre_cliente))
{
Facturas[i].eliminado = true;
}
}
clear_screen();
printf("Pedido elimando con exito!\n");
}
/**
* @brief Permite editar cualquier factura, con la clave y usuario del admin
*
* @return int
*/
int edit_orders()
{
int available_quantity = 0;
unsigned id = 0;
char c;
bool flag;
char _temp[sizeof(int) + sizeof(unsigned)];
unsigned temp = 0;
int cantidad;
getchar();
clear_screen();
for (size_t i = 0; i < MAX_FACTURAS; i++)
{
if (1) //ver si es admin o no, si es puede editar, sino sale error
{
printf("\n\aEstas ahora en el editor de pedidos\n"
"\nSolo podras editar las cantidades de productos a vender\n"
"Ingrese el id del producto: ");
scanf("%u", &id);
getchar();
printf("\n\t\aIngrese la cantidad (positivo para suma, negativo para resta):");
fgets(_temp, sizeof(_temp), stdin);
sscanf(_temp, "%d", &Facturas[i].Cantidad);
cantidad = Facturas[i].Cantidad;
cantidad *= -1;
flag = edit_availableQuantity(id, cantidad);
printf("Exito!");
break;
}
else
{
printf("No puede acceder a esta opcion porque no es Admin");
getchar();
}
clear_screen();
}
if (flag)
{
clear_screen();
printf("\t\t\aHa modificado la cantidad del producto\n\n"
"\tPresiona 'm' para volver al menu anterior o cualquier otra tecla "
"\tpara salir.\n");
while ((c = getchar()) != '\n' || (c = getchar()) != '\r')
if (c == 'm')
return true;
else
exit(0);
}
else
{
printf("\a\tEl producto que has intentado modificar no existe.\n"
"\tVerifica que hayas ingresado un id existente.\n"
"Presione cualquier tecla para volver a menu Ventas...");
getch();
}
return false;
}
/**
* @brief Imprime el encabezado del modulo ventas opcion 1
*
*/
void print_factura()
{
printf("\t*************Bienvenido a Colmado Hackeando la NASA (VENTAS) *************\n\n"
"%-20s%-20s%-20s%-20s%-20s%-20s\n",
"Nombre cliente:", "Producto:", "Cantidad:", "Precio:", "Total:", "Total a pagar:");
for (size_t i = 0; i < MAX_FACTURAS; i++)
{
if (Facturas[i].full)
printf("%-20s%-20s%-20u%-20u%-20u\t%-20.2f\n",
Facturas[i].nombre_cliente, Facturas[i].nombre_producto,
Facturas[i].Cantidad, Facturas[i].Precio, Facturas[i].Total, Facturas[i].TotalaPagar);
}
}
/**
* @brief Pregunta si va a agregar articulos, sino da el total a pagar de la factura
*
* @return int
*/
bool sell_products()
{
char c[10];
char temp;
int flag = 0;
unsigned id, cantidad;
clear_screen();
printf("Estas en comprar producto.\n");
report_inventory();
putchar('\n');
printf("Ingrese el id del producto que desea comprar:");
scanf("%u", &id);
getchar();
printf("Ingrese la cantidad que desea comprar:");
scanf("%u", &cantidad);
getchar();
llenar_facturas(id, cantidad);
flag = -cantidad;
edit_availableQuantity(id, flag);
printf("Desea continuar? 's' para si, cualquier otra tecla para no.\n");
fgets(c, sizeof(c), stdin);
sscanf(c, "%c", &temp);
if (temp == 's' || temp == 'S')
return true;
else
ventas_menu();
return false;
}
/**
* @brief Menu de inicio para el modulo ventas
* @return true si el usuario no salio y se imprime el menu
* @return false el usuario salio y se para
*/
bool ventas_menu()
{
char _temp[sizeof(short)];
short temp = 0;
int time = 1;
/**Sistema de carga para ingresar al modulo */
clear_screen();
printf("Ingresando al Modulo Ventas...\n");
system_loading(time);
do
{
if (temp != 0)
printf("Elige una opcion valida por favor\n");
/** ******Menu de Ventas ***** */
printf("\a\n\t\tBienvenido al Modulo Ventas\n"
"\t\t\tSeleccione la opcion que desea realizar: \n"
"\t1) Vender\n"
"\t2) Ver Ventas realizadas\n"
"\t3) Editar Pedidos\n"
"\t4) Eliminar Pedidos\n"
"\t5) Caja Registradora\n"
"\t6) Volver al Menu Principal\n");
fgets(_temp, sizeof(_temp), stdin);
sscanf(_temp, "%hd", &temp);
} while (temp < 0 || temp > 6);
switch (temp)
{
case SELL_PRODUCTS:
/*void print_encabezado_factura();//ver si es necesario agregarla o si solo se puede llamar a
agregar_mas_articulos*/
if (sell_products())
return sell_products();
else
ventas_menu();
getchar();
case SEE_ORDERS:
clear_screen();
print_factura();
getchar();
getchar();
ventas_menu();
break;
case EDIT_ORDERS:
for (; edit_orders();)
;
return ventas_menu();
break;
case DELETE_ORDERS:
delete_orders();
return false;
case CASH_REGISTER:
cash_register();
getchar();
break;
case GO_BACK_OUT_VENTAS:
go_back();
return false;
break;
default:
fprintf(stderr, "\n\aHaz elegido una opcion incorrecta\n");
break;
}
return true;
}
|
C
|
#include<stdio.h>
int n[100001];
int lsearch(int request, int len);
int main()
{
int len,query;
scanf("%d",&len);
for(int i = 0; i<len ;i++)
{
scanf("%d", &n[i]);
}
scanf("%d", &query);
printf("%d", lsearch(query, len));
return 0;
}
int lsearch(int request, int len)
{
for(int i = 0 ; i < len; i++)
{
if(n[i] == request)
{
return i+1;
}
}
return -1;
}
|
C
|
#include <stdio.h>
int main()
{
int max = -1000000;
int min = 1000000;
for (int i = 0; i < 5; i++)
{
int k;
scanf("%d", &k);
if (k > max)
max = k;
if (k < min)
min = k;
}
printf("%d\n%d", max, min);
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
int main(){
char name[20], sign[20];
printf("Ingresa tu nombre: ");gets(name);
printf("Ingresa tu signo: ");gets(sign);
if(strcmp(sign, "aries") == 0){
printf("%s es aries.", name);
}
else{
printf("%s no es aries.", name);
}
return 0;
}
|
C
|
/******************************************************************************
*
* Module: PWM
*
* File Name: pwm-config.h
*
* Description: Config file for the AVR PWM driver
*
* Author: Kirollos Ashraf
*
*******************************************************************************/
#ifndef __PWM_CONFIG_H__
#define __PWM_CONFIG_H__
/*******************************************************************************
* Definitions *
*******************************************************************************/
/* Frequency of the pwm output signal can be calculated as follows:
* ----------------------------------------------------------------
* pwm 0, pwm 2 => Frequency = F_CPU / (prescaler * 256)
* pwm 1A, pwm 1B => Frequency = F_CPU / (prescaler * (1 + top))
*
* You can control the values of the prescaler or the top values from below
*/
/* prescaler to use with PWM 0 */
/* Available values:
* PWM_0_PRESCALLER_1 - PWM_0_PRESCALLER_8
* PWM_0_PRESCALLER_64 - PWM_0_PRESCALLER_256
* PWM_0_PRESCALLER_1024
*/
#define PWM_0_PRESCALER PWM_0_PRESCALLER_64
/* prescaler to use with PWM 1A or PWM 1B */
/* Available values:
* PWM_1_PRESCALLER_1 - PWM_1_PRESCALLER_8
* PWM_1_PRESCALLER_64 - PWM_1_PRESCALLER_256
* PWM_1_PRESCALLER_1024
*/
#define PWM_1_PRESCALER PWM_1_PRESCALLER_64
/* top value to be used with PWM 1A or PWM 1B, can be 16-bit unsigned data */
#define PWM_1_TOP (255U)
/* prescaler to use with PWM 2 */
/* Available values:
* PWM_2_PRESCALLER_1 - PWM_2_PRESCALLER_8
* PWM_2_PRESCALLER_32 - PWM_2_PRESCALLER_64
* PWM_2_PRESCALLER_128 - PWM_2_PRESCALLER_256
* PWM_2_PRESCALLER_1024
*/
#define PWM_2_PRESCALER PWM_2_PRESCALLER_64
#endif /* __PWM_CONFIG_H__ */
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_handle_wstr.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ajanmot <ajanmot@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/11/30 18:56:09 by ajanmot #+# #+# */
/* Updated: 2017/11/30 18:56:10 by ajanmot ### ########.fr */
/* */
/* ************************************************************************** */
#include "../include/include.h"
#include <stdio.h>
static size_t ft_calc_wstrlen(wchar_t *str, int precision, size_t i)
{
if (!*str || !precision)
return (i);
else if (*str <= 0x7F)
return (ft_calc_wstrlen(str + 1, precision - 1, i + 1));
else if (*str <= 0x7FF && precision >= 2)
return (ft_calc_wstrlen(str + 1, precision - 2, i + 2));
else if (*str <= 0xFFFF && precision >= 3)
return (ft_calc_wstrlen(str + 1, precision - 3, i + 3));
else if (*str <= 0x10FFFF && precision >= 4)
return (ft_calc_wstrlen(str + 1, precision - 4, i + 4));
else
return (i);
}
static size_t ft_wstrlen(wchar_t *str)
{
size_t i;
i = 0;
while (*str)
{
if (*str <= 0x7F)
i++;
else if (*str <= 0x7FF)
i += 2;
else if (*str <= 0xFFFF)
i += 3;
else if (*str <= 0x10FFFF)
i += 4;
str++;
}
return (i);
}
ssize_t ft_handle_wstr(char **format, va_list *args, t_spec *spec)
{
wchar_t *str;
size_t strlen;
(void)format;
str = va_arg(*args, wchar_t*);
strlen = spec->got_precision ? ft_calc_wstrlen(str, spec->precision, 0)
: ft_wstrlen(str);
if (spec->got_width && !spec->right_pad)
ft_width_pad(strlen, spec->width, spec->zeroes_pad ? '0' : ' ');
ft_putnwstr(str, strlen);
if (spec->got_width && spec->right_pad)
ft_width_pad(strlen, spec->width, ' ');
return (spec->got_width ? ft_max(strlen, spec->width) : (int)strlen);
}
|
C
|
/*
** EPITECH PROJECT, 2020
** fd
** File description:
** fd
*/
#include "my.h"
int pipe_loop_ext(piping_t *piping, shell_t *shell, char **envp, pid_t pid)
{
int x = 0;
int stock_stdin = dup(0);
int stock_stdout = dup(1);
dup2(piping->fd[0], 0);
dup2(piping->fd[1], 1);
x = my_function(shell, envp);
dup2(stock_stdin, 0);
dup2(stock_stdout, 1);
if (pid != -1)
exit((x != 0) ? x : 0);
if (x != 0)
return x;
return 0;
}
int set_fd(piping_t *piping)
{
int fd[2];
while (piping->next != NULL) {
pipe(fd);
piping->fd[1] = fd[1];
piping->next->fd[0] = fd[0];
piping = piping->next;
}
return 0;
}
|
C
|
/**
* Mensajes
*
* Aquí están contenidos todos los mensajes de
* información, error, etc. del programa
*/
#define INFO_HELP "TP1-Procesos - 1.0 - Alberto Fernández Martínez\nAsignatura Sistemas Operativos (UNED) - Curso 2011-2012\n\nusage: TP1-Procesos [arguments]\n\nArguments:\n\t-gui\t\tLoad up graphical user interface\n\t-h\t\tShows this help\n"
#define INFO_START "******************************************************\n* Bienvenido al primer trabajo de Sistemas Operativos\n******************************************************\n* Introduce una de las siguientes opciones:\n*\t- Cargar datos desde un archivo de texto (a)\n*\t- Introducir datos manualmente (m)\n*\t- Salir del programa (e)\n******************************************************\n* Opción: "
#define INFO_PARSINGFILE "* Cargando datos desde el fichero de texto...\n*\n"
#define INFO_PARSINGTEXT "* Procesando línea %d: '%s'...\n"
#define EN_FIN "* Interfaz gráfica no implementada por falta de tiempo\n"
// Error messages
#define ERROR_ARG "TP1-Procesos: invalid option -- '%s'\nUsage: TP1-Procesos [-gui] [-h]\n"
#define ERROR_OPTION "* Opción inválida, vuelve a introducirla ('e' para salir): "
#define ERROR_FILEOPEN "* El archivo especificado '%s' no se pudo abrir.\n"
#define FUU "* Let's get back to work... (opción): "
#define ERROR_LINEDIGIT "*\n* Error en línea %d: formato incorrecto en la %s columna. \n* Corriga la entrada y vuelva a intentarlo\n*\n* Saliendo del programa...\n******************************************************\n"
#define INFO_FIRSTC "primera"
#define INFO_SECONDC "segunda"
#define INFO_FILENAME "* Introduzca el nombre del archivo: "
#define INFO_SAVEFILE "* Introduce el nombre del archivo a guardar: "
#define ERROR_SAVEFILE "* No se pudo acceder al fichero para su escritura, especifique otro\n"
#define INFO_OPTIONFILE "******************************************************\n* Gracias, sus datos han sido cargados correctamente:\n*\t- Ver por pantalla 'v'\n*\t- Escribir en fichero de texto 'w'\n*\t- Ver, escribir y salir 'c'\n******************************************************\n* Opción: "
#define INFO_RESULT "*******************************\n* RESULTADOS DE LA PLANIFICACIÓN"
#define INFO_RESULT_FCFS "* Planificación FCFS"
#define INFO_RESULT_SRT "* Planificación SRT"
#define INFO_RESULT_RR "* Planificación Round Robin con cuanto q=%d"
#define INFO_RESULT_SEPARATOR "\n*******************************\n"
#define INFO_SUCCESS_WRITE "******************************************************\n* Gracias, los datos se han guardado correctamente en el fichero '%s'\n******************************************************\n"
#define MAN_IN "* Introduzca el tiempo de %s del proceso %d: "
#define MAN_LL "llegada"
#define MAN_S "servicio"
#define MAN_ERROR_N "* ERROR! Debe especificar un número correcto\n"
#define MAN_MORE "* ¿Desea introducir más procesos? (y/n): "
#define MAN_RR "* Introduzca el valor del cuanto para el algoritmo Round Robin: "
#define ERROR_QUANT "* El cuanto especificado no es correcto\n"
#define ERROR_QUANT_NE "* El cuanto no existe en el fichero\n"
#define PRINT_RESULT "Proceso %d: Tf=%d Tr=%d Te=%d\n"
#define PRINT_AVG "\nTiempo promedio de retorno = %.2f\nTiempo promedio de espera = %.2f\n"
#define MAX_PROCESS 20
/**
* Estructuras de datos
*
* Estas son las estructuras de datos que
* usaremos a lo largo del programa
*/
/**
* FILE_STATUS
*
* Esta estructura se usa para cuando queremos
* abrir un archivo, podemos devolver el estado
* y el nombre del fichero
*/
struct FILE_STATUS_s
{
int status;
char* filename;
};
typedef struct FILE_STATUS_s FILE_STATUS;
/**
* PROCESS
*
* Contiene la información necesaria de cada proceso
*
* TF = Tiempo de finalizacion
* TR = Tiempo de retorno
* TE = Tiempo de espera
*/
struct PROCESS_s
{
int TF;
int TR;
int TE;
};
/**
* PLANNER_RESULT
*
* Contiene la información del resultado de
* ejecutar un algoritmo de planificación sobre un
* PLANNER_INPUT; contiene un array de 20 PROCESS
* para los procesos, 2 float para las medias de
* espera y retorno y un int para el número de procesos
* en total
*/
struct PLANNER_RESULT_s
{
struct PROCESS_s processes[MAX_PROCESS];
float average_return;
float average_wait;
int num;
};
typedef struct PLANNER_RESULT_s PLANNER_RESULT;
/**
* PLANNER_INPUT
*
* Contiene la información que debe pasarse
* a los respectivos algoritmos de planificación
*
* La estructura es similar a PLANNER_RESULT, pero
* con solamente los tiempos de llegada / servicicio
* el cuanto, el número de procesos, y por último
* 'idle' indica el tiempo al principio del algoritmo
* en que el procesador está a la espera de que llegue
* el primer proceso
*/
struct PLANNER_INPUT_s
{
struct
{
int t_llegada;
int t_servicio;
} times[MAX_PROCESS];
int quant;
int num;
int idle;
};
typedef struct PLANNER_INPUT_s PLANNER_INPUT;
/**
* Forward declarations
*/
int proccess_arguments(int argc, char* argv[]);
PLANNER_RESULT fcfs_algorithm(PLANNER_INPUT data);
char* trim(char *s, const char *trimChars);
|
C
|
#include "queue.h"
static ComandQueue cmdQueue;
uint8_t getNumberCmd() {
return (cmdQueue.nextCmd > cmdQueue.firstCmd) ? cmdQueue.nextCmd - cmdQueue.firstCmd :
cmdQueue.nextCmd - cmdQueue.firstCmd - (~((uint8_t) MAX_LENGTH_QUEUE)+1);
}
void addCommand(Command* cmd, uint16_t size) {
if(cmdQueue.lengthQueue < MAX_LENGTH_QUEUE) {
cmdQueue.commandBuffer[cmdQueue.nextCmd].cmd = *cmd;
cmdQueue.commandBuffer[cmdQueue.nextCmd].size = size;
cmdQueue.nextCmd = RINGINC(cmdQueue.nextCmd, MAX_LENGTH_QUEUE);
cmdQueue.lengthQueue = getNumberCmd();
}
}
queueItem* dequeuingCommand() {
uint8_t itemp;
if(cmdQueue.lengthQueue > 0) {
itemp = cmdQueue.firstCmd;
cmdQueue.firstCmd = RINGINC(cmdQueue.firstCmd, MAX_LENGTH_QUEUE);
cmdQueue.lengthQueue = (getNumberCmd() == MAX_LENGTH_QUEUE) ? 0 : getNumberCmd();
return &cmdQueue.commandBuffer[itemp];
}
return 0;
}
|
C
|
/* fichero marathon.c */
/* Un marathon tiene 26 millas y 385 yardas. */
/* Una milla tiene 1760 yardas. */
/* Calcula la distancia del marathon en kilómetros. */
#include <stdio.h>
void main(void) {
int millas, yardas;
float kilometros;
millas=26;
yardas=385;
kilometros=1.609*(millas+yardas/1760);
printf("\nUn marathon tiene %f kilometros.\n\n", kilometros);
}
|
C
|
/* ** por compatibilidad se omiten tildes **
================================================================================
TRABAJO PRACTICO 3 - System Programming - ORGANIZACION DE COMPUTADOR II - FCEN
================================================================================
funciones auxiliares para rutinas de atencion de interrupciones
*/
#include "colors.h"
#include "screen.h"
// rutina de atencion de interrupcion de teclado. Dependiendo el scan code realiza determinada accion
void rutina_teclado(unsigned char scan_code) {
if (scan_code == 0x32)
print_modo_mapa();
if (scan_code == 0x12)
print_modo_estado();
switch (scan_code) {
case 0xB:
print("0", 79, 0, C_BG_RED | C_FG_WHITE);
break;
case 0x52:
print("0", 79, 0, C_BG_RED | C_FG_WHITE);
break;
case 0x2:
print("1", 79, 0, C_BG_RED | C_FG_WHITE);
break;
case 0x4F:
print("1", 79, 0, C_BG_RED | C_FG_WHITE);
break;
case 0x3:
print("2", 79, 0, C_BG_RED | C_FG_WHITE);
break;
case 0x50:
print("2", 79, 0, C_BG_RED | C_FG_WHITE);
break;
case 0x4:
print("3", 79, 0, C_BG_RED | C_FG_WHITE);
break;
case 0x51:
print("3", 79, 0, C_BG_RED | C_FG_WHITE);
break;
case 0x5:
print("4", 79, 0, C_BG_RED | C_FG_WHITE);
break;
case 0x4B:
print("4", 79, 0, C_BG_RED | C_FG_WHITE);
break;
case 0x6:
print("5", 79, 0, C_BG_RED | C_FG_WHITE);
break;
case 0x4C:
print("5", 79, 0, C_BG_RED | C_FG_WHITE);
break;
case 0x7:
print("6", 79, 0, C_BG_RED | C_FG_WHITE);
break;
case 0x4D:
print("6", 79, 0, C_BG_RED | C_FG_WHITE);
break;
case 0x8:
print("7", 79, 0, C_BG_RED | C_FG_WHITE);
break;
case 0x47:
print("7", 79, 0, C_BG_RED | C_FG_WHITE);
break;
case 0x9:
print("8", 79, 0, C_BG_RED | C_FG_WHITE);
break;
case 0x48:
print("8", 79, 0, C_BG_RED | C_FG_WHITE);
break;
case 0xA:
print("9", 79, 0, C_BG_RED | C_FG_WHITE);
break;
case 0x49:
print("9", 79, 0, C_BG_RED | C_FG_WHITE);
break;
default:
break;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct studentGrades
{
char name[20];
int grade;
};
typedef struct studentGrades studentGrades;
void bubbleSort1(studentGrades *a, int n);
void bubbleSort2(studentGrades *a, int n);
int main()
{
int *a; // dynamic array pointer
int i, n;
struct studentGrades *s;
struct studentGrades p[3];
puts("please enter student's info for array p:");
for (i = 0; i < 3; i++)
{
printf("enter name:\n");
scanf("%s", p[i].name);
printf("enter grade:\n");
scanf("%d", &p[i].grade);
}
printf("This is the information that you have entered for array P:\n");
for (i = 0; i < 3; i++)
{
printf("%s: ", p[i].name);
printf("grade %d:\n", p[i].grade);
}
// dynamic array s set up and initialization
printf("How many grades to be entered for dynamic array s?");
scanf_s("%d", &n);
a = (int*)calloc(n, sizeof(int)); // creating a dynamic array for pointer a using size n
// creating a dynamic array for pointer s using size n
s = (studentGrades*)calloc(n, sizeof(studentGrades));
printf("Enter %d student's name and grade for dynamic array s:\n", n);
for (i = 0; i < n; i++) {
printf("enter name:\n");
scanf("%s", s[i].name);
printf("enter grade:\n");
scanf("%d", &s[i].grade);
}
printf("This is the information that you have entered for array s before sorting:\n");
for (i = 0; i < 3; i++)
{
printf("%s: ", s[i].name);
printf("grade %d:\n", s[i].grade);
}
bubbleSort2(p, 3); // function call
bubbleSort2(s, n);
printf("This is the information that you have entered for array p after sorting:\n");
for (i = 0; i < n; i++)
{
printf("%s: ", p[i].name);
printf("grade %d:\n", p[i].grade);
}
printf("This is the information that you have entered for array s after sorting:\n");
for (i = 0; i < n; i++)
{
printf("%s: ", s[i].name);
printf("grade %d:\n", s[i].grade);
}
free(s); // release pointer
return(0);
}
void bubbleSort1(studentGrades *a, int n) // array notation
{
int i, temp, j;
for (i = 0; i < n - 1; i++)
{
for (j = 0; j < n - 1; j++)
{
if (a[j].grade > a[j + 1].grade);
{
temp = a[j].grade;
a[j].grade = a[j + 1].grade;
a[j + 1].grade = temp;
}
}
}
}
void bubbleSort2(studentGrades *a, int n)
{
int i, temp, j;
for (i = 0; j < n - 1; i++)
{
for (j = 0; j < n - 1; j++)
{
if ((*(a + j)).grade > (*(a + j + 1)).grade) // same as if(a[j].grade >a[j+1].grade)
{
temp = (*(a + j)).grade; // same as temp=a[j].grade;
(*(a + j)).grade = (*(a + j + 1)).grade; // same as a[j].grade=a[j+1].grade;
(*(a + j + 1)).grade = temp; // same as a[j+a] = temp;
}
}
}
}
|
C
|
#include<stdio.h>
int main()
{
char a[1000],s;
int i,j,t;
printf("enter string \n");
gets(a);
for(j=0;a[j]!='\0';j++);
j--;
if(j%2==0)
t=j/2+1;
else
t=j/2;
for(i=0;i<=t;i++)
{
s=a[i];
a[i]=a[j];
a[j]=s;
j--;
}
printf("%s",a);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
void merge(int* a,int l,int mid,int h){
int n = mid-l+1;
int m = h-mid;
int a1[n];
int a2[m];
for(int i=0;i<n;i++) a1[i] = a[l+i];
for(int i=0;i<m;i++) a2[i] = a[mid+1+i];
int i=0,j=0,k=l;
while(i<n && j<m){
if(a1[i]<=a2[j]) a[k]=a1[i++];
else a[k]=a2[j++];
k++;
}
while(i<n) a[k++]=a1[i++];
while(j<m) a[k++]=a2[j++];
}
void merge1(int* a,int la,int* b,int lb){
int i=la-1,j=lb-la-1,k=lb-1;
while(i>=0 && j>=0){
if(a[i]<=b[j]){
b[k]=b[j];
j--;
}else{
b[k]=a[i];
i--;
}
k--;
}
while(i>=0){
b[k]=a[i];
k--,i--;
}
}
void merge2(int* a,int i,int j,int la){
int k=j+1;
while(i<=j && k<=la){
if(a[i]<=a[k]) i++;
else{
int t=a[k];
int idx = k;
while(idx!=i){
a[idx]=a[idx-1];
idx--;
}
a[i]=t;
i++;
j++;
k++;
}
}
}
void MergeSort(int* a,int l,int h){
if(l<h){
int mid = (l+h)/2;
MergeSort(a,l,mid);
MergeSort(a,mid+1,h);
merge(a,l,mid,h);
}
}
int main(){
int a[] = {1,3,8,12};
int b[] = {1,3,8,12,2,5,9,10,43,19,55,6,13,7};
int la = sizeof(a)/sizeof(a[0]);
int lb = sizeof(b)/sizeof(b[0]);
//int* res = merge(a,la,b,lb);
//merge1(a,la,b,lb);
//merge2(b,0,3,lb);
MergeSort(b,0,lb-1);
for(int i=0;i<lb;i++){
printf("%d ",b[i]);
}
printf("\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <tgmath.h>
int main() {
int cases;
scanf("%d", &cases);
int i;
for (i=0;i<cases;i++){
long int nthterm;
scanf("%ld", &nthterm);
long long int modulo = pow(10, 9) + 7;
printf("%lld\n", (long long int)powl((nthterm % modulo) ,2%modulo)%modulo) ;
}
return 0;
}
|
C
|
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#define RECV_SIZE 1024
#define PORT 14456
void dieWithError(char* message);
unsigned long resolveName(char* name);
void sendToServer(int sock, char* message);
unsigned int isOpen = 0;
unsigned int quit = 0;
int main(int argc, char** argv)
{
int sock;
struct sockaddr_in serverAddr;
char* serverIP;
FILE* istream;
char* line = NULL;
size_t lineSize = 0;
int lineCount = 0;
//make sure argument format is correct
if(argc < 2 || argc > 3){
fprintf(stderr, "Usage: %s <server> [inputFile]\n", argv[0]);
exit(1);
}
serverIP = argv[1]; //get server name
//pick the input source, file or stdin
if(argc == 3){
istream = fopen(argv[2], "r");
} else {
istream = stdin;
}
while(quit == 0){
if(isOpen == 0){
//printf("trying to open another connection\n");
//sleep(1);
if((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){ //create tcp socket
dieWithError("socket failed()");
}
//construct server address structure
memset(&serverAddr, 0, sizeof(serverAddr)); //zero out structure
serverAddr.sin_family = AF_INET; //internet address family
serverAddr.sin_addr.s_addr = resolveName(serverIP); //server ip address
serverAddr.sin_port = htons(PORT); //server port
if(connect(sock, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0){
dieWithError("connect() failed");
}
isOpen = 1;
}
//printf("looping\n");
while(isOpen){
lineCount = getline(&line, &lineSize, istream);
line[lineCount-1] = '\0';
sendToServer(sock, line);
}
//printf("closing\n");
close(sock);
}
//printf("quitting\n");
return 0;
}
void sendToServer(int sock, char* message)
{
int mlen = strlen(message);
int rlen = 0;
char buffer[RECV_SIZE];
if(send(sock, message, mlen, 0) != mlen){
dieWithError("send() sent a different number of bytes than expected");
}
if((rlen = recv(sock, buffer, RECV_SIZE, 0)) < 0){
dieWithError("recv() failed");
}
buffer[rlen] = '\0';
//check if the server is closing the connection or quitting
if(strstr(buffer, "CLOSING") == buffer){
isOpen = 0;
}
if(strstr(buffer, "QUITTING") == buffer){
isOpen = 0;
quit = 1;
}
// if(strstr(buffer, "LIST") == buffer){
// while(1){
// printf("waiting list\n");
// if((rlen = recv(sock, buffer, RECV_SIZE, 0)) < 0){
// dieWithError("recv() failed");
// }
// printf("got\n");
// buffer[rlen] = '\0';
// if(strcmp(buffer, "ENDLIST") == 0){
// break;
// }
// printf("SERVER list-> %s\n", buffer);
// }
// }
printf("SERVER %s\n", buffer);
}
unsigned long resolveName(char* name)
{
struct hostent *host;
if((host = gethostbyname(name)) == NULL){
dieWithError("gethostbyname() failed");
}
return *((unsigned long *)host->h_addr_list[0]);
}
void dieWithError(char* message)
{
fprintf(stderr, "%s\n", message);
exit(1);
}
|
C
|
/*
* Remove Element
*
* Given an array and a value, remove all instances of that value
* in place and return the new length.
*
* The order of elements can be changed. It doesn't matter what you
* leave beyond the new length.
*
*/
/* C solution */
int removeElement(int A[], int n, int elem) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int i = 0, p = 0;
for (i = 0; i < n; i++) {
if (A[i] != elem) {
A[p++] = A[i];
}
}
return p;
}
/* Java solution */
public class Solution {
public int removeElement(int[] A, int elem) {
int p = 0, i;
for (i = 0; i < A.length; i++) {
if (A[i] != elem) {
A[p++] = A[i];
}
}
return p;
}
}
|
C
|
/*
* ASUS xtion color channel
*/
#include "xtion-color.h"
#include "xtion-endpoint.h"
#include "xtion-control.h"
static inline struct xtion_color *endp_color(struct xtion_endpoint *endp)
{ return container_of(endp, struct xtion_color, endp); }
static void color_start(struct xtion_endpoint* endp)
{
struct xtion_color *color = endp_color(endp);
if(!endp->active_buffer) {
endp->active_buffer = xtion_endpoint_get_next_buf(endp);
if(!endp->active_buffer)
return;
}
endp->active_buffer->pos = 0;
color->last_full_values[0] = 0;
color->last_full_values[1] = 0;
color->last_full_values[2] = 0;
color->open_nibbles = 0;
color->current_channel_idx = 0;
color->current_channel = 0;
color->line_count = 0;
}
static unsigned int channel_map[4] = {0, 1, 2, 1}; // UYVY
static inline void color_put_byte(struct xtion_color* color, struct xtion_buffer *buffer, u8 val) {
u8 *vaddr = vb2_plane_vaddr(&buffer->vb.vb2_buf, 0);
if(buffer->pos >= vb2_plane_size(&buffer->vb.vb2_buf, 0)) {
dev_warn(&color->endp.xtion->dev->dev, "buffer overflow");
return;
}
vaddr[buffer->pos] = val;
buffer->pos++;
color->last_full_values[color->current_channel] = val;
color->current_channel_idx = (color->current_channel_idx+1) % 4;
color->current_channel = channel_map[color->current_channel_idx];
if(++color->line_count == 2*color->endp.pix_fmt.width) {
color->last_full_values[0] = 0;
color->last_full_values[1] = 0;
color->last_full_values[2] = 0;
color->line_count = 0;
}
}
static inline int color_unpack_nibble(struct xtion_color *color, struct xtion_buffer *buffer, u32 nibble) {
if(nibble < 0xd) {
color_put_byte(color, buffer, color->last_full_values[color->current_channel] + (__s8)(nibble - 6));
} else if(nibble == 0xf) {
return 1;
}
return 0;
}
static void color_unpack(struct xtion_color *color, const u8 *data, unsigned int size)
{
struct xtion_buffer *buffer = color->endp.active_buffer;
u32 c = *data;
u32 temp;
if(color->open_nibbles == 1) {
/* The high nibble of the first input byte belongs to the last output byte */
temp = (c >> 4) | color->stashed_nibble;
color_put_byte(color, buffer, temp);
/* Process low nibble */
if(color_unpack_nibble(color, buffer, c & 0xF)) {
if(size == 1) {
color->open_nibbles = 2;
return;
}
/* Take one full byte */
data++;
size--;
color_put_byte(color, buffer, *data);
}
data++;
size--;
} else if(color->open_nibbles == 2) {
/* Take one full byte */
color_put_byte(color, buffer, c);
data++;
size--;
}
while(size > 2) {
c = *data;
/* Process high nibble */
if(color_unpack_nibble(color, buffer, c >> 4)) {
/* Take one full byte */
temp = (c & 0xF) << 4;
data++;
c = *data;
temp |= (c >> 4);
size--;
color_put_byte(color, buffer, temp);
}
/* Process low nibble */
if(color_unpack_nibble(color, buffer, c & 0xF)) {
/* Take one full byte */
data++;
size--;
color_put_byte(color, buffer, *data);
}
data++;
size--;
}
/* Be careful with the last two bytes, we might not have enough data
* to process them fully. */
if(size == 2) {
c = *data;
/* Process high nibble */
if(color_unpack_nibble(color, buffer, c >> 4)) {
/* Take one full byte */
temp = (c & 0xF) << 4;
data++;
c = *data;
temp |= (c >> 4);
size--;
color_put_byte(color, buffer, temp);
}
/* Process low nibble */
if(color_unpack_nibble(color, buffer, c & 0xF)) {
if(size == 1) {
color->open_nibbles = 2;
return;
}
/* Take one full byte */
data++;
size--;
color_put_byte(color, buffer, *data);
}
data++;
size--;
}
if(size == 1) {
c = *data;
/* Process high nibble */
if(color_unpack_nibble(color, buffer, c >> 4)) {
/* We want to take a full byte, but we do not have the second nibble */
color->stashed_nibble = (c & 0xF) << 4;
color->open_nibbles = 1;
return;
}
/* Process low nibble */
if(color_unpack_nibble(color, buffer, c & 0xF)) {
/* We want to take a full byte, but this is the last byte */
color->open_nibbles = 2;
return;
}
}
color->open_nibbles = 0;
}
static void color_data(struct xtion_endpoint* endp, const u8* data, unsigned int size)
{
struct xtion_color *color = endp_color(endp);
u8* vaddr;
if(!endp->active_buffer)
return;
vaddr = vb2_plane_vaddr(&endp->active_buffer->vb.vb2_buf, 0);
if(!vaddr)
return;
if(size != 0)
color_unpack(color, data, size);
}
static void color_end(struct xtion_endpoint *endp)
{
if(!endp->active_buffer)
return;
endp->active_buffer->vb.vb2_buf.planes[0].bytesused = endp->active_buffer->pos;
endp->active_buffer->vb.timestamp = endp->packet_system_timestamp;
endp->active_buffer->vb.sequence = endp->frame_id;
vb2_set_plane_payload(&endp->active_buffer->vb.vb2_buf, 0, endp->active_buffer->pos);
vb2_buffer_done(&endp->active_buffer->vb.vb2_buf, VB2_BUF_STATE_DONE);
endp->active_buffer = 0;
}
const struct xtion_endpoint_config xtion_color_endpoint_config = {
.name = "color",
.addr = 0x82,
.start_id = 0x8100,
.end_id = 0x8500,
.pix_fmt = V4L2_PIX_FMT_UYVY,
.pixel_size = 2,
.buffer_size = sizeof(struct xtion_buffer),
.cmos_index = 0,
.settings_base = XTION_P_IMAGE_BASE,
.endpoint_register = XTION_P_GENERAL_STREAM0_MODE,
.endpoint_mode = XTION_VIDEO_STREAM_COLOR,
.image_format = XTION_IMG_FORMAT_YUV422,
.bulk_urb_size = 20480,
.handle_start = color_start,
.handle_data = color_data,
.handle_end = color_end,
};
static int xtion_color_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct xtion_endpoint *endp = container_of(ctrl->handler, struct xtion_endpoint, ctrl_handler);
switch(ctrl->id) {
case V4L2_CID_POWER_LINE_FREQUENCY:
switch(ctrl->val) {
case V4L2_CID_POWER_LINE_FREQUENCY_DISABLED:
return xtion_set_param(endp->xtion, XTION_P_IMAGE_FLICKER, 0);
case V4L2_CID_POWER_LINE_FREQUENCY_50HZ:
return xtion_set_param(endp->xtion, XTION_P_IMAGE_FLICKER, 50);
case V4L2_CID_POWER_LINE_FREQUENCY_60HZ:
return xtion_set_param(endp->xtion, XTION_P_IMAGE_FLICKER, 60);
default:
return -EINVAL;
}
break;
case V4L2_CID_AUTOGAIN:
return xtion_set_param(endp->xtion, XTION_P_IMAGE_AUTO_EXPOSURE_MODE, ctrl->val);
case V4L2_CID_GAIN:
return xtion_set_param(endp->xtion, XTION_P_IMAGE_AGC, ctrl->val);
case V4L2_CID_WHITE_BALANCE_TEMPERATURE:
return xtion_set_param(endp->xtion, XTION_P_IMAGE_COLOR_TEMPERATURE, ctrl->val);
case V4L2_CID_AUTO_WHITE_BALANCE:
return xtion_set_param(endp->xtion, XTION_P_IMAGE_AUTO_WHITE_BALANCE_MODE, ctrl->val);
}
return 0;
}
static const struct v4l2_ctrl_ops xtion_color_ctrl_ops = {
.s_ctrl = xtion_color_s_ctrl,
};
int xtion_color_init(struct xtion_color *color, struct xtion *xtion)
{
int rc;
rc = xtion_endpoint_init(&color->endp, xtion, &xtion_color_endpoint_config);
if(rc != 0)
return rc;
v4l2_ctrl_new_std_menu(&color->endp.ctrl_handler, &xtion_color_ctrl_ops,
V4L2_CID_POWER_LINE_FREQUENCY, V4L2_CID_POWER_LINE_FREQUENCY_60HZ,
0, V4L2_CID_POWER_LINE_FREQUENCY_DISABLED);
v4l2_ctrl_new_std(&color->endp.ctrl_handler, &xtion_color_ctrl_ops,
V4L2_CID_GAIN, 0, 1500, 1, 100
);
v4l2_ctrl_new_std(&color->endp.ctrl_handler, &xtion_color_ctrl_ops,
V4L2_CID_AUTOGAIN, 0, 1, 1, 1
);
v4l2_ctrl_new_std(&color->endp.ctrl_handler, &xtion_color_ctrl_ops,
V4L2_CID_WHITE_BALANCE_TEMPERATURE, 0, 15000, 1, 5000
);
v4l2_ctrl_new_std(&color->endp.ctrl_handler, &xtion_color_ctrl_ops,
V4L2_CID_AUTO_WHITE_BALANCE, 0, 1, 1, 1
);
if(color->endp.ctrl_handler.error) {
dev_err(&color->endp.xtion->dev->dev, "could not register ctrl: %d\n", color->endp.ctrl_handler.error);
}
v4l2_ctrl_handler_setup(&color->endp.ctrl_handler);
return 0;
}
void xtion_color_release(struct xtion_color* color)
{
xtion_endpoint_release(&color->endp);
}
|
C
|
#ifndef BCI_TUAFILTER_H_INCLUDED
#define BCI_TUAFILTER_H_INCLUDED
//Ten-unit average filter
typedef struct TUAFilter_t
{
float components[10];
int index;
} TUAFilter;
/**
* Initializes a ten-unit average filter
* @param filter TUA filter to initialize
*/
void filter_Init_TUA(TUAFilter *filter);
/**
* Filters an input
* @param filter TUA filter to use
* @param componentIn Input reading
* @return Filtered value
*/
float filter_TUA(TUAFilter *filter, const float componentIn);
#endif //BCI_TUAFILTER_H_INCLUDED
|
C
|
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <stdbool.h>
#define NUM_SUITS 4
#define NUM_RANKS 13
#define NUM_CARDS 5
/* external variables */
int num_in_rank[NUM_RANKS] ;
int num_in_suit[NUM_SUITS] ;
bool straight , flush ,four ,three ;
int pairs ; /*can be 0,1,or 2 */
//prototypes
void read_cards(void) ;
void analyze_hand(void) ;
void print_result(void) ;
int main(void)
{
/***************************************************
* main : Calls read_cards , analyze_hand , and *
* print_result repeatedly . *
**************************************************/
for ( ; ; ){
read_cards() ;
analyze_hand() ;
print_result() ;
}
/*
const char rank_code[] = {'2','3','4','5','6','7','8','9','10','J','Q','K','A' } ;
//梅花 club 方块 diamond 红桃 heart 黑桃 spade
const char suit_code[] = {'c','d','h','s'} ;
srand((unsigned) time (NULL) ) ;
//Seed the random-number generator with current time.
//so that the numbers will be different every time when we run.
printf("Enter number of cards in hand :") ;
scanf("%d",&num_cards) ;
printf("Your hand :\n") ;
for ( ; num_cards > 0 ; num_cards--) {
suit = rand() % NUM_SUITS ;
rank = rand() % NUM_RANKS ;
if ( ! in_hand[suit][rank])
in_hand[suit][rank] = TRUE ;
printf(" %c%c",rank_code[rank] , suit_code[suit]) ;
if ( num_cards % 7 == 0 )
printf("\n") ;
}
printf("\n") ;
*/
return 0 ;
}
void read_cards(void)
{
bool card_exits[NUM_RANKS][NUM_SUITS] ;
char ch , rank_ch , suit_ch ;
int rank , suit ;
bool bad_card ;
int cards_read = 0 ;
for (rank = 0 ; rank < NUM_RANKS ; rank++){
num_in_rank[rank] = 0 ;
for ( suit = 0 ; suit < NUM_SUITS ; suit++)
card_exits[rank][suit] = false ;
}
for ( suit = 0 ; suit < NUM_SUITS ; suit++)
num_in_suit[suit] = 0 ;
while( cards_read < NUM_CARDS ) {
bad_card = false ;
printf("Enter a card : ") ;
rank_ch = getchar() ;
switch (rank_ch) {
case '0' : exit(EXIT_SUCCESS) ;
case '2' : rank = 0 ; break ;
case '3' : rank = 1 ; break ;
case '4' : rank = 2 ; break ;
case '5' : rank = 3 ; break ;
case '6' : rank = 4 ; break ;
case '7' : rank = 5 ; break ;
case '8' : rank = 6 ; break ;
case '9' : rank = 7 ; break ;
case 't' : case 'T' : rank = 8 ; break ;
case 'j' : case 'J' : rank = 9 ; break ;
case 'q' : case 'Q' : rank = 10 ; break ;
case 'k' : case 'K' : rank = 11 ; break ;
case 'a' : case 'A' : rank = 12 ; break ;
default : bad_card = true ;
}
suit_ch = getchar() ;
switch (suit_ch) {
case 'c': case 'C' : suit = 0 ; break ;
case 'd': case 'D' : suit = 1 ; break ;
case 'h': case 'H' : suit = 2 ; break ;
case 's': case 'S' : suit = 3 ; break ;
default : bad_card = true ;
}
while( (ch = getchar() ) != '\n' )
if (ch != ' ' )
bad_card = true ;
if ( bad_card)
printf("Bad card; ignored.\n") ;
else if ( card_exits[rank][suit] )
printf("Duplicate card ; ignored.\n") ;
else {
num_in_suit[suit]++ ;
num_in_rank[rank]++ ;
card_exits[rank][suit] = true ;
cards_read++ ;
}
}
}
/********************************************************
* analyze_hand : Determines whether the hand contains *
* a straight, a flush , four-of-a-kind, *
* and/or three-of-a-kind;determines the *
* number of pairs;stores the results *
* into the external variables straight, *
* flush, four,three,and pairs. *
********************************************************/
void analyze_hand(void)
{
int num_consec = 0 ;
int rank , suit ;
straight = false ;
flush = false ;
four = false ;
three = false ;
pairs = 0 ;
/* check for flush */
for( suit = 0 ; suit < NUM_SUITS ; suit++)
if ( num_in_suit[suit] == NUM_CARDS)
flush = true ;
/* check for straight */
rank = 0 ;
while( num_in_rank[rank] == 0)
rank++ ;
for( ; rank < NUM_RANKS && num_in_rank[rank] > 0 ; rank++)
num_consec++ ;
if ( num_consec == NUM_CARDS ) {
straight = true ;
return ;
}
/* check for 4-of-a-kind, 3-of-a-kind, and pairs */
for( rank = 0 ; rank < NUM_RANKS ; rank++) {
if (num_in_rank[rank] == 4 )
four = true ;
if ( num_in_rank[rank] == 3 )
three = true ;
if ( num_in_rank[rank] == 2 )
pairs++ ;
}
}
void print_result(void)
{
if ( straight && flush )
printf("Straigh flush") ;
else if( four)
printf("Four of a kind");
else if( three && pairs == 1)
printf("Full house") ;
else if( flush )
printf("Flush") ;
else if ( straight )
printf("straight");
else if ( three )
printf("Three of a kind ") ;
else if ( pairs == 2)
printf("Two pairs") ;
else if ( pairs == 1)
printf("Pair") ;
else
printf("High card") ;
printf("\n\n") ;
}
/*
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <ctype.h>
#define NUM_CARDS 5
#define RANK 0
#define SUIT 1
int hand[NUM_CARDS][2] ;
bool straight,flush ,four ,three ;
int pairs ;
void read_cards(void) ;
void analyze_hand(void);
void print_result(void) ;
int main(void)
{
for ( ; ; ) {
read_cards() ;
analyze_hand() ;
print_result() ;
}
return 0 ;
}
void read_cards(void)
{
char rank_ch , suit_ch, ch ;
int i ,rank , suit ;
bool bad_card , duplicate_card ;
int cards_read = 0 ;
while( cards_read < NUM_CARDS ) {
bad_card = false ;
printf("Enter a card : ") ;
rank_ch = getchar() ;
switch (rank_ch) {
case '0' : exit(EXIT_SUCCESS) ;
case '2' : rank = 0 ; break ;
case '3' : rank = 1 ; break ;
case '4' : rank = 2 ; break ;
case '5' : rank = 3 ; break ;
case '6' : rank = 4 ; break ;
case '7' : rank = 5 ; break ;
case '8' : rank = 6 ; break ;
case '9' : rank = 7 ; break ;
case 't' : case 'T' : rank = 8 ; break ;
case 'j' : case 'J' : rank = 9 ; break ;
case 'q' : case 'Q' : rank = 10 ; break ;
case 'k' : case 'K' : rank = 11 ; break ;
case 'a' : case 'A' : rank = 12 ; break ;
default : bad_card = true ;
}
suit_ch = getchar() ;
switch (suit_ch) {
case 'c': case 'C' : suit = 0 ; break ;
case 'd': case 'D' : suit = 1 ; break ;
case 'h': case 'H' : suit = 2 ; break ;
case 's': case 'S' : suit = 3 ; break ;
default : bad_card = true ;
}
while( (ch = getchar() ) != '\n' )
if (ch != ' ' )
bad_card = true ;
if (bad_card) {
printf("Bad card ; ignored.\n") ;
continue ;
}
duplicate_card = false ;
for( i = 0 ; i < cards_read ; i++)
if ( hand[i][RANK] == rank && hand[i][SUIT] == suit ){
printf("Duplicate card; ignored.\n") ;
duplicate_card = true ;
break ;
}
if ( !duplicate_card){
hand[cards_read][RANK] = rank ;
hand[cards_read][SUIT] = suit ;
cards_read++ ;
}
}
}
void analyze_hand(void)
{
int rank , suit , card , pass , run ;
straight = true ;
flush = true ;
four = false ;
three = false ;
pairs = 0 ;
//sort cards by rank
for( pass = 1 ; pass < NUM_CARDS ; pass++)
for( card = 0 ; card < NUM_CARDS - pass ; card++){
rank = hand[card][RANK] ;
suit = hand[card][SUIT] ;
if ( hand[card + 1][RANK] < rank ){
hand[card][RANK] = hand[card + 1][RANK] ;
hand[card][SUIT] = hand[card + 1][SUIT] ;
hand[card + 1][RANK] = rank ;
hand[card + 1][SUIT] = suit ;
}
}
//check for flush
suit = hand[0][SUIT] ;
for ( card = 1 ; card < NUM_CARDS ; card++)
if( hand[card][SUIT] != suit)
flush = false ;
// check for straight
for( card = 0 ; card < NUM_CARDS - 1; card ++ )
if ( hand[card][RANK] + 1 != hand[card + 1][RANK] )
straight = false ;
// check for 4-of-a-kind ,
card = 0 ;
while( card < NUM_CARDS) {
rank = hand[card][RANK] ;
run = 0 ;
do {
run++ ;
card++ ;
}while(card < NUM_CARDS &&hand[card][RANK] == rank ) ;
switch(run){
case 2 : pairs++ ; break ;
case 3 : three = true ; break ;
case 4 : four = true ; break ;
}
}
*******************************************************
for ( pass = 0 ; pass < NUM_CARDS - 1 ; pass++ )
for(card = pass + 1; card < NUM_CARDS ; card++ ){
if( hard[card][RANK] < hand[pass][RANK] ){
rank = hand[pass][RANK] ;
suit = hand[PASS][SUIT] ;
hand[pass][RANK] = hand[card][RANK] ;
HAND[pass][SUIT] = hand[card][SUIT] ;
hand[card][RANK] = rank;
hand[card][SUIT] = suit ;
}
}
********************************************************
}
void print_result(void)
{
if ( straight && flush )
printf("Straigh flush") ;
else if( four)
printf("Four of a kind");
else if( three && pairs == 1)
printf("Full house") ;
else if( flush )
printf("Flush") ;
else if ( straight )
printf("straight");
else if ( three )
printf("Three of a kind ") ;
else if ( pairs == 2)
printf("Two pairs") ;
else if ( pairs == 1)
printf("Pair") ;
else
printf("High card") ;
printf("\n\n") ;
}
*/
|
C
|
#ifndef _H8300_DELAY_H
#define _H8300_DELAY_H
#include <asm/param.h>
/*
* Copyright (C) 2002 Yoshinori Sato <ysato@sourceforge.jp>
*
* Delay routines, using a pre-computed "loops_per_second" value.
*/
static inline void __delay(unsigned long loops)
{
__asm__ __volatile__ ("1:\n\t"
"dec.l #1,%0\n\t"
"bne 1b"
:"=r" (loops):"0"(loops));
}
/*
* Use only for very small delays ( < 1 msec). Should probably use a
* lookup table, really, as the multiplications take much too long with
* short delays. This is a "reasonable" implementation, though (and the
* first constant multiplications gets optimized away if the delay is
* a constant)
*/
extern unsigned long loops_per_jiffy;
static inline void udelay(unsigned long usecs)
{
usecs *= 4295; /* 2**32 / 1000000 */
usecs /= (loops_per_jiffy*HZ);
if (usecs)
__delay(usecs);
}
#endif /* _H8300_DELAY_H */
|
C
|
#include <stdio.h>
typedef struct{
int blobsize;
int *blob;
}cpt_hdl;
int disp_pkey(const int **blob){
printf("blob = %d\n", **blob);
}
int main(void){
cpt_hdl *pkey;
cpt_hdl pkey_mem;
int *keybuf;
int *keybuf_addr;
int *keybuf_addr_addr;
int keybuf_addr_mem;
int **keybufa1;
int keybufa2;
int a1 = 88;
int *a1_ptr;
pkey_mem.blobsize = 99;
pkey_mem.blob = &a1;
pkey = &pkey_mem;
a1_ptr = &a1;
keybuf_addr=(int*)&pkey;
printf("keybuf_addr = 0x%x\n", *keybuf_addr); //0xf18944f0
keybuf_addr_addr = (int*)&keybuf_addr;
printf("keybuf_addr_addr = 0x%x\n", *keybuf_addr_addr);
keybuf_addr=(int*)&a1_ptr;
printf("keybuf_addr = 0x%x\n", *keybuf_addr); //0xf189452c
keybuf=pkey->blob;
printf("keybuf = %d\n", *keybuf); //88
keybuf=(int*)pkey->blob;
printf("keybuf = %d\n", *keybuf); //88
keybufa1=(int**)&pkey->blob;
printf("keybuf = %d\n", **keybufa1); //88
keybuf_addr=(int*)&pkey->blob;
printf("keybuf_addr = 0x%x\n", *keybuf_addr); //0xf189452c
disp_pkey((const int**)&pkey->blob); //88
return 0;
}
|
C
|
/*
-------------------------------------
Author: Anshul Khatri
ID: 193313680
Email: khat3680@mylaurier.ca
Version 2020-06-25
-------------------------------------
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "process.h"
Process* create_process(long pid, int time, int arrival){
Process* p = (Process*) malloc(sizeof(Process));
if (time <= 0){
fprintf(stderr,"Error(create_process): invalid time -set to 0\n");
p->time = 0;
}
else
p->time = time;
if (arrival < 0){
fprintf(stderr,"Error(create_process): invalid arrival time -set to 0\n");
p->arrival = 0; }
else
p->arrival = arrival;
if(pid <= 0){
fprintf(stderr,"Error(create_process): invalid pid -set to random\n");
p->PID = get_UPID();
}
else
p->PID = pid;
return p;
}
void destroy_process(Process **p){
assert(*p != NULL);
(*p)->PID = 0;
(*p)->time = 0;
(*p)->arrival = 0;
free(*p);
*p = NULL;
return;
}
void print_process(Process *p){
assert(p != NULL);
char info[30];
strcpy(info,"");
get_process_info(p,info);
printf("%s",info);
return;
}
Process* copy_process(Process *p1){
assert(p1 != NULL);
Process *p2 = (Process*)malloc(sizeof(Process));
p2->PID = p1->PID;
p2->time = p1->time;
p2->arrival = p1->arrival;
return p2;
}
void get_process_info(Process *p, char *info){
assert(p != NULL);
char process[30];
sprintf(process,"[%u](%lu,%u)",p->arrival,p->PID,p->time);
strcpy(info,process);
return;
}
int is_equal_process(Process *p1, Process *p2){
assert(p1 != NULL && p2 != NULL);
if(p1->PID != p2->PID)
return False;
if(p1->time != p2->time)
return False;
return True;
}
unsigned long get_UPID(){
static int counter = 10000;
// Get higher 5
unsigned long higher5 = rand()% (39999 - 10000 + 1 ) + 10000;
higher5 = higher5 * 100000;
int lower5 = counter;
counter++;
return higher5 + lower5;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
#define SIZE 100
char stack[SIZE];
int top = -1;
void push(char item)
{
if(top >= SIZE-1)
{
printf("\nStack Overflow.");
}
else
{
top = top+1;
stack[top] = item;
}
}
char pop()
{
char item ;
if(top <0)
{
printf("stack under flow: invalid infix expression");
exit(1);
}
else
{
item = stack[top];
top = top-1;
return(item);
}
}
int isoper(char sym)
{
if(sym == '^' || sym == '*' || sym == '/' || sym == '+' || sym =='-')
{
return 1;
}
else
{
return 0;
}
}
void Eval(char prefix[],int k)
{
int i;
char ch;
int val;
int A, B;
for (i = k; i>=0; i--) {
ch = prefix[i];
if (isdigit(ch)) {
push(ch-'0');
}
else if (isoper(ch)==1) {
A = pop();
B = pop();
switch (ch)
{
case '*':
val = A * B;
break;
case '/':
val = A / B;
break;
case '+':
val = A + B;
break;
case '-':
val = A - B;
break;
}
push(val);
}
}
printf(" \n Result of expression evaluation : %d \n", pop());
}
int main()
{ int i;
char prefix[SIZE];
printf("\nEnter prefix expression (pl.put '.'@the end) : \n");
for (i = 0; i <= SIZE - 1; i++) {
scanf("%c", &prefix[i]);
if (prefix[i] == '.')
{
break;
}
}
char alp;
for(int j=0;j<=i;j++)
{ alp=prefix[j];
if(isalpha(alp))
{
printf("enter the value of %c \t",alp);
scanf(" %c",&prefix[j]);
}
}
Eval(prefix,i);
return 0;
}
|
C
|
#include<stdio.h>
void swap(int a,int b,int arr[])
{
int c = arr[a];
arr[a] = arr[b];
arr[b] = c;
}
void sink(int arr[],int i,int n)
{
if(i >= n-1) // if i == last element/size so return
return;
int current = i;
int left = 2*i; // Left child of Parent
int right = 2*i + 1; // Right child of Parent
if(left < n && arr[left] > arr[current]) // Checking if the left child is max than parent or not
{
current = left;
}
if(right < n && arr[right] > arr[current]) // Checking if the right child is max than parent or not
{
current = right;
}
if(i != current) // if i changes means the parent is smaller than left or right or from both than swap
{
swap(i,current,arr); // swaping initial i with the changed i
sink(arr,current,n); // Recursive call for another part
}
}
void heapify(int arr[],int n)
{
for(int i=n/2;i>=0;i--) // Starting loop from the bottom parent of the tree
{
sink(arr,i,n); // sinking
}
}
int main()
{
int n;
scanf("%d",&n); // Scanning size of array
int arr[n];
for(int i=0;i<n;i++)
{
scanf("%d",&arr[i]); // Scanning elements of array
}
heapify(arr,n); // Heapifying array
for(int i=0;i<n;i++)
{
printf("%d ",arr[i]); // Printing array
}
return 0;
}
|
C
|
#ifndef F_CPU
#define F_CPU 1000000UL
#endif
#include <avr/io.h>
#include <util/delay.h>
#include <avr/eeprom.h>
#include <avr/power.h>
#include <avr/sleep.h>
#include <avr/interrupt.h>
#define LED_PIN0 (1 << PB0)
#define LED_PIN1 (1 << PB1)
#define LED_PIN2 (1 << PB2)
#define KEY0 (1 << PB3)
#define KEY1 (1 << PB4)
typedef int bool;
#define true 1
#define false 0
void lockedState();
void clear();
typedef enum { RELEASED=0, PRESSED } key_t;
uint8_t savedCode = 0b111111; // EEPROM memory where we save the state
uint8_t savedState = 0b111110; // EEPROM memory where we save the code
uint8_t code = 0b000000; // The lock code. Set to volatile so compiler won't make changes
/* @return uint8_t
@parameters bool
Function to create a uint8_t that represents a 6 bit input pattern
Uses debouncing and delays to hanlde switch bouncing
Shifts code << 1, adds 0b0 if KEY0 is pushed, 0b1 if KEY1
Uses uint8_t to keep track of inputed code and button press count
Turns on BLUE LED when button is pressed to indicate a press
Checks to see if pressCount = 0b111111, indicating 6 inputs and that we have our 6 bit code, returns
Checks what state we are in and sets LED's accordingly
*/
uint8_t codeInput(bool lockFlag){
uint8_t pressCount = 0b000000; //How many times inputs were pressed
uint8_t enteredCode = 0b000000; // Our input code
uint8_t b0_history = 0;
uint8_t b1_history = 0;
key_t keystate = RELEASED;
while(1){
bool clicked = false;
//Button 0
b0_history = b0_history << 1;
if ((PINB & KEY0) == 0){ // low if button is pressed!
b0_history = b0_history | 0x1;
}
// Update the key state based on the latest 6 samples
if ((b0_history & 0b111111) == 0b111111){
keystate = PRESSED;
clicked = true;
_delay_ms(5);
}
if ((b0_history & 0b00111111) == 0){
keystate = RELEASED;
}
/* KEY0 PRESSED
Set BLUE LED to on
Shifts enteredCode << 1
Adds 0b0 to least significant bit
Increases pressCount via same method
*/
if (keystate == PRESSED && clicked){
DDRB = LED_PIN1|LED_PIN2;
PORTB = LED_PIN1;
enteredCode = enteredCode << 1;
enteredCode = enteredCode | 0b0;
pressCount = pressCount << 1;
pressCount = pressCount | 0b1;
_delay_ms(175);
}
clicked = false;
// Button 1
b1_history = b1_history << 1;
if ((PINB & KEY1) == 0){ // low if button is pressed!
b1_history = b1_history | 0x1;
}
// Update the key state based on the latest 6 samples
if ((b1_history & 0b111111) == 0b111111){
keystate = PRESSED;
clicked = true;
_delay_ms(5);
}
if ((b1_history & 0b00111111) == 0){
keystate = RELEASED;
}
/* KEY1 PRESSED
Set BLUE LED to on
Shifts enteredCode << 1
Adds 0b1 to least significant bit
Increases pressCount via same method
*/
if (keystate == PRESSED && clicked){
DDRB = LED_PIN1|LED_PIN2;
PORTB = LED_PIN1;
enteredCode = enteredCode << 1;
enteredCode = enteredCode | 0b1;
pressCount = pressCount << 1;
pressCount = pressCount | 0b1;
_delay_ms(175);
}
clicked = false;
/* Check to see if we entered 6 bit code
If pressCount = 0b111111, we have entered our 6 bit input
Clear LED's and return our 6 bit code
*/
if (pressCount == 0b111111){
clear();
return enteredCode;
}
// Checks what state we are in and sets LED's accordingly
if(lockFlag){
DDRB = LED_PIN1 | LED_PIN2;
PORTB = LED_PIN2;
}else {
DDRB = LED_PIN1|LED_PIN0;
PORTB = LED_PIN1;
_delay_ms(5);
PORTB = LED_PIN0; // Using delays here to get full power to each LED to be brighter
_delay_ms(5);
}
}
}
/* Representation of the unlocked state
Sets GREEN and YELLOW LED's to on
Calls the function codeInput that creates our 6 bit code
Saves state and code to EEPROM
Calls lockedState which represents being locked. */
void startState(){
DDRB = LED_PIN1|LED_PIN0;
PORTB = LED_PIN0;
PORTB = LED_PIN1;
code = codeInput(false);
savedCode = code;
eeprom_write_byte(&savedCode, code);
eeprom_write_byte(&savedState, 0b100000);
_delay_ms(75);
lockedState();
}
/* Representation of the locked state
Sets RED LED to on
Gets a user inputed 6 bit code via codeInput
Compares the lock code to the new user input
If equal changes state to unlocked state, clears LED's
Saves state and code to EEPROM
Else, flashes YELLOW LED 5 times to signal invalid code
*/
void lockedState(){
uint8_t codeAttempt = 0b000000;
DDRB = LED_PIN1 | LED_PIN2;
PORTB = LED_PIN2;
codeAttempt = codeInput(true);
if (codeAttempt == code){
clear();
code = 0b000000;
savedCode = code;
eeprom_update_byte(&savedCode, code);
eeprom_update_byte(&savedState, 0b000000);
_delay_ms(75);
startState();
} else {
for (volatile int i = 0; i < 5; i++){
DDRB = LED_PIN0|LED_PIN1;
PORTB = LED_PIN1;
_delay_ms(100);
clear();
_delay_ms(100);
}
lockedState();
}
}
// Clear DDRB & PORTB to turn off all LED's
void clear(){
DDRB = 0b000000;
PORTB = 0b000000;
}
/*Entry point
If button is held down on startup will reset pin
Checks to see if last state was a locked state
If was locked, loads code from EEPROM memory and sets state to locked
*/
int main(void){
uint8_t history = 0;
key_t keystate = RELEASED;
//If button is held down on startup, it will reset code.
for(int i =0 ; i <1000;i++){
// Get a sample of the key pin
history = history << 1;
if ((PINB & KEY1) == 0) // low if button is pressed!
history = history | 0x1;
// Update the key state based on the latest 6 samples
if ((history & 0b111111) == 0b111111){
keystate = PRESSED;
}
// Turn on the LED based on the state
if (keystate == PRESSED){
_delay_ms(2000);
startState();
}
}
/*Checks to see if we were last in a lockedState
If we were we load that code into code
Return to a locked state with the perviously used code
*/
if(eeprom_read_byte(&savedState) == 0b100000){
code = eeprom_read_byte(&savedCode);
lockedState();
} // Else we just enter the startState and ready to accept input
startState();
}
|
C
|
/**************************************************************************************
* LED--ʾʵ *
ʵسչڲƵߣLEDʾ
ע뽫74HC595ģJP595̽Ƭ̽ӣ
***************************************************************************************/
#include "reg51.h" //ļж˵ƬһЩܼĴ
#include "intrins.h"
typedef unsigned int u16; //ͽ
typedef unsigned char u8;
//--ʹõIO--//
sbit SRCLK=P3^6;
sbit RCLK=P3^5;
sbit SER=P3^4;
//LEDλѡҲܵλѡΪҪ䶯̬ɨ
//ǰ16λͺ16λ෴ģҲ˵õ3595͵ƽȻõ4595͵ƽ
u8 code ledwei[]=
{
0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80,
};
u8 code ledduan1[]=
{
/*-- : --*/
/*-- 12; ¶ӦĵΪx=16x16 --*/
0x40,0x44,0x54,0x64,0x45,0x7E,0x44,0x44,0x44,0x7E,0x45,0x64,0x54,0x44,0x40,0x00,
0x00,0x00,0x00,0xFF,0x49,0x49,0x49,0x49,0x49,0x49,0x49,0xFF,0x00,0x00,0x00,0x00,
};
u8 code ledduan2[]=
{
/*-- : --*/
/*-- 12; ¶ӦĵΪx=16x16 --*/
0x00,0x00,0xF0,0x10,0x10,0x10,0x10,0xFF,0x10,0x10,0x10,0x10,0xF0,0x00,0x00,0x00,
0x00,0x00,0x0F,0x04,0x04,0x04,0x04,0xFF,0x04,0x04,0x04,0x04,0x0F,0x00,0x00,0x00,
};
/*******************************************************************************
* : delay
* : ʱi=1ʱԼʱ10us
*******************************************************************************/
void delay(u16 i)
{
while(i--);
}
/*******************************************************************************
* : Hc595SendByte(u8 dat1,u8 dat2,u8 dat3,u8 dat4)
* : ͨ595ĸֽڵ
* : dat14595ֵ
* * dat2: 3595ֵ
* * dat32595ֵ
* * dat41595ֵ
* :
*******************************************************************************/
void Hc595SendByte(u8 dat1,u8 dat2,u8 dat3,u8 dat4)
{
u8 a;
SRCLK = 1;
RCLK = 1;
for(a=0;a<8;a++) //8λ
{
SER = dat1 >> 7; //λʼ
dat1 <<= 1;
SRCLK = 0; //ʱ
_nop_();
_nop_();
SRCLK = 1;
}
for(a=0;a<8;a++) //8λ
{
SER = dat2 >> 7; //λʼ
dat2 <<= 1;
SRCLK = 0; //ʱ
_nop_();
_nop_();
SRCLK = 1;
}
for(a=0;a<8;a++) //8λ
{
SER = dat3 >> 7; //λʼ
dat3 <<= 1;
SRCLK = 0; //ʱ
_nop_();
_nop_();
SRCLK = 1;
}
for(a=0;a<8;a++) //8λ
{
SER = dat4 >> 7; //λʼ
dat4 <<= 1;
SRCLK = 0; //ʱ
_nop_();
_nop_();
SRCLK = 1;
}
RCLK = 0;
_nop_();
_nop_();
RCLK = 1;
}
/*******************************************************************************
* : main
* :
* :
* :
*******************************************************************************/
void main()
{
u8 i;
while(1)
{
for(i=0;i<16;i++)
{
Hc595SendByte(~ledwei[i+16],~ledwei[i],ledduan1[16+i],ledduan1[i]);
delay(10);
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include "util.h"
#include "msgqueuelib.h"
/**
* Generate a unique key (unsigned int) from a name. Makes an XOR of all the
* characters of the name. The key is used to create/link a shared memory, a
* message queue or a semaphore.
*
* @param name Name of the shared mem segment, msg queue or semaphore.
*
* @return The key generated.
*/
unsigned int mkkey( unsigned char * name )
{
unsigned int value = 0 ;
int i ;
for( i = 0 ; *name != '\0' ; name++, i++ ) {
unsigned int j = (i % 4)*8 ;
value ^= (*name << j) ;
}
return value ;
}
unsigned int IpcMsgCreate( const char * name, unsigned int * the_key )
{
unsigned int mykey, msgid ;
int ok ;
struct msqid_ds buf ;
mykey = mkkey( (unsigned char *)name ) ;
//printf( "Name '%s', Key: %08x\n", name, mykey ) ;
ok = msgget( mykey, IPC_CREAT | 0x1FF ) ;
if ( ok == -1 ) exit( 1 ) ;
msgid = ok ;
ok = msgctl( msgid, IPC_STAT, &buf ) ;
buf.msg_perm.mode = 0x1ff ;
ok = msgctl( msgid, IPC_SET, &buf ) ;
ok = msgctl( msgid, IPC_STAT, &buf ) ;
*the_key = mykey ;
return msgid ;
}
unsigned int IpcMsgBind( const char * name, unsigned int * the_key )
{
int mykey, ok, msgid ;
struct msqid_ds buf ;
mykey = mkkey( (unsigned char *)name ) ;
//printf( "Name '%s', Key: %08x\n", name, mykey ) ;
ok = msgget( mykey, 0x1FF ) ;
if ( ok == -1 ) return ok ;
msgid = ok ;
ok = msgctl( msgid, IPC_STAT, &buf ) ;
buf.msg_perm.mode = 0x1ff ;
ok = msgctl( msgid, IPC_SET, &buf ) ;
ok = msgctl( msgid, IPC_STAT, &buf ) ;
*the_key = mykey ;
return msgid ;
}
unsigned int IpcMsgCheck( int mykey )
{
int ok ;
ok = msgget( mykey, 0x1FF ) ;
return ok ;
}
int IpcMsgRemove( int msgid )
{
struct msqid_ds buf ;
int ok ;
ok = msgctl( msgid, IPC_RMID, &buf ) ;
return ok ;
}
|
C
|
#include <stdio.h>
/**
* main - prints all possible combinations of single digit numbers
* Return: returns 0
*/
int main(void)
{
int Z;
for (Z = '0'; Z <= '9'; Z++)
{
putchar(Z);
if (Z < '9')
{
putchar(',');
putchar(' ');
}
}
putchar('\n');
return (0);
}
|
C
|
#include <stdio.h>
#define INF __INT_MAX__
int col;
void printShortestpath(long long dist[][col], int size)
{
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if (dist[i][j] == INF)
{
printf("INF ");
}
else
{
printf("%lld ", dist[i][j]);
}
}
printf("\n");
}
}
int floydWarshall(int graph[][col], int size)
{
long long dist[size][size];
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
dist[i][j] = graph[i][j];
}
}
for (int k = 0; k < size; k++)
{
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if (dist[i][k] + dist[k][j] < dist[i][j])
{
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
printShortestpath(dist, size);
}
int main()
{
int size = 4;
col = size;
int graph[4][4] = {
{0, 7, 5, INF},
{INF, 0, 7, 6},
{INF, INF, 0, INF},
{4, 1, 11, 0}};
floydWarshall(graph, size);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* checker.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: anaroste <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/03/10 09:33:17 by anaroste #+# #+# */
/* Updated: 2018/04/12 12:44:22 by anaroste ### ########.fr */
/* */
/* ************************************************************************** */
#include "../header/checker.h"
static int ft_read(char ***tab)
{
char *tmp;
char *tmp2;
char *str;
char *rom;
str = malloc(1);
*str = '\0';
tmp = NULL;
while (get_next_line(0, &tmp) > 0)
{
rom = ft_strjoin(str, tmp);
tmp2 = str;
str = ft_strjoin(rom, " ");
ft_strdel(&tmp2);
ft_strdel(&tmp);
ft_strdel(&rom);
}
*tab = ft_strsplit(str, ' ');
ft_strdel(&str);
return (0);
}
static void ft_piledel(char **tab, t_pile *pile)
{
free(tab);
free(pile->a);
free(pile->b);
}
static int error_checker(int ac, char **av)
{
int i;
i = 1;
if (ac == 1)
return (1);
while (av[i])
{
if (ft_isint(av[i]) == 1)
{
write(1, "Error\n", 6);
return (1);
}
}
}
int main(int ac, char **av)
{
t_pile pile;
int i;
char **tab;
i = 0;
if (error_checker(ac, av) == 1)
return (0);
if (!(pile.a = (int *)malloc(sizeof(int) * ac)))
return (0);
if (!(pile.b = (int *)malloc(sizeof(int) * ac)))
return (0);
pile.a[0] = ac - 1;
pile.b[0] = 0;
while (++i < ac)
pile.a[i] = ft_atoi(av[i]);
ft_read(&tab);
if (!(ft_check(tab, &pile)))
write(1, "KO\n", 3);
else
write(1, "OK\n", 3);
i = 0;
while (tab[i])
free(tab[i++]);
ft_piledel(tab, &pile);
return (0);
}
|
C
|
#include<GL/glut.h>
#include<stdio.h>
#include<math.h>
#define Round(a)((int)(a+0.5))
float xc;
float yc;
float rx;
float ry;
void setpixel(float x,float y)
{
glBegin(GL_POINTS);
glColor3f(0.0f,1.0f,1.0f);
glVertex2f(x,y);
glEnd();
glFlush();
}
void init()
{
glClearColor(0.0f,0.0f,1.0f,1.0f);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0,500,0,500,-1,1);
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
float x=0;
float y=ry;
if(rx<ry)
{
for(x=0;x<=rx;x+=0.01)
{
y=sqrt((1-((x*x)/(rx*rx)))*(ry*ry));
setpixel(x+xc,y+yc);
setpixel(-x+xc,y+yc);
setpixel(-x+xc,-y+yc);
setpixel(x+xc,-y+yc);
}
}
else
{
for(y=0;y<=ry;y+=0.1)
{
x=sqrt((1-((y*y)/(ry*ry)))*(rx*rx));
setpixel(x+xc,y+yc);
setpixel(-x+xc,y+yc);
setpixel(-x+xc,-y+yc);
setpixel(x+xc,-y+yc);
}
}
glutSwapBuffers();
}
int main(int argc,char **argv)
{
printf("Enter centre:");
scanf("%f%f",&xc,&yc);
printf("Enter radius:");
scanf("%f%f",&rx,&ry);
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_RGB|GLUT_DOUBLE);
glutInitWindowSize(500,500);
glutInitWindowPosition(150,150);
glutCreateWindow("NEW ELLIPSE");
glutDisplayFunc(display);
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
//glOrtho(0,500,0,500,-1,1);
init();
glutMainLoop();
return 0;
}
|
C
|
#pragma once
enum ShowWindowFlags : int
{
/// <summary>
/// minimizes a window, even if the thread that owns the window is not responding.
/// this flag should only be used when minimizing windows from a different thread.
/// </summary>
sw_forceminimize = SW_FORCEMINIMIZE,
/// <summary>
/// hides the window and activates another window.
/// </summary>
sw_hide = SW_HIDE,
/// <summary>
/// maximizes the specified window.
/// </summary>
sw_maximize = SW_MAXIMIZE,
/// <summary>
/// minimizes the specified window and activates the next top-level window in the z
/// <order.
/// </summary>
sw_minimize = SW_MINIMIZE,
/// <summary>
/// activates and displays the window. if the window is minimized or maximized, the
/// system restores it to its original size and position. an application should specify this
/// flag when restoring a minimized window.
/// </summary>
sw_restore = SW_RESTORE,
/// <summary>
/// activates the window and displays it in its current size and position.
/// </summary>
sw_show = SW_SHOW,
/// <summary>
/// sets the show state based on the sw_ value specified in the startupinfo
/// structure passed to the createprocess function by the program that started the application.
/// </summary>
sw_showdefault = SW_SHOWDEFAULT,
/// <summary>
/// activates the window and displays it as a maximized window.
/// </summary>
sw_showmaximized = SW_SHOWMAXIMIZED,
/// <summary>
/// activates the window and displays it as a minimized window.
/// </summary>
sw_showminimized = SW_SHOWMINIMIZED,
/// <summary>
/// displays the window as a minimized window. this value is similar to
/// sw_showminimized, except the window is not activated.
/// </summary>
sw_showminnoactive = SW_SHOWMINNOACTIVE,
/// <summary>
/// displays the window in its current size and position. this value is similar to
/// sw_show, except that the window is not activated.
/// </summary>
sw_showna = SW_SHOWNA,
/// <summary>
/// displays a window in its most recent size and position. this value is similar to
/// sw_shownormal, except that the window is not activated.
/// </summary>
sw_shownoactivate = SW_SHOWNOACTIVATE,
/// <summary>
/// activates and displays a window. if the window is minimized or maximized, the
/// system restores it to its original size and position. an application should specify this
/// flag when displaying the window for the first time.
/// </summary>
sw_shownormal = SW_SHOWNORMAL,
};
DEFINE_ENUM_FLAG_OPERATORS(ShowWindowFlags)
|
C
|
#include <stdio.h>
void sort(char let[5][4])
{
int i, j, k, l, ret;
char word1[4];
char word2[4];
for(k = 0; k < 4; k++) //this outter loop exists to run these 2 inner loops. the outter loop is basically
{ //required to make sure this bubble sort in the most inner loop fully goes through
//the 2d matrix and test the if condition on every element
for(i = 0; i < 4; i++)
{
for(j = 0; j < 4; j++) //the two inner loops are just normal loops that go through a 2d matrix
{
word1[j] = let[i][j];
word2[j] = let[i+1][j]; //this puts together the row and row+1 into a word so they can be compared (bubble sort)
ret = strcmp(word1,word2);
if(ret > 0)
{
char temp; //swapping of rows
temp = let[i][j];
let[i][j] = let[i+1][j];
let[i+1][j] = temp;
}
}
}
}
}
int main(void)
{
int row, col, i, j;
char let[5][4];
printf("Enter the 5 strings one by one delimited by new line.\n\n");
//takes in a string and deconstructs every character so it has a spot n the 2d array
for(row = 0; row < 5; row++)
{
char word[4];
scanf("%s",word);
for(col = 0; col < 4; col++)
{
char letter;
letter = word[col];
let[row][col] = letter;
}
}
sort(let); //sorts the 2d matrix
printf("\n");
printf("Sorted strings: \n\n");
for (i = 0; i < 5; i++)
{
for (j = 0; j < 4; j++)
{
printf("%c",let[i][j]);
}
printf("\n");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <locale.h>
int main()
{
setlocale(LC_ALL, "");
int minhaIdade = 23;
int maeIdade = 48; int paiIdade = 49;
printf("Minha idade = %i.\n", minhaIdade);
printf("Minha idade = %i.\nPai idade = %i.\nMe idade = %i.", minhaIdade, paiIdade, maeIdade);
return 0;
}
|
C
|
#include <stdio.h>
int f(int x, int y)
{
return 10 * x + y;
}
int main(void)
{
int i, j;
i = 0;
j = f(++i, ++i);
printf("%d\n", j);
return 0;
}
|
C
|
#include "PawnCmd.h"
#include <string.h>
static void PawnCmdSystem_Wait_Init(PawnCmdSystem_T * sys, PawnCmdData_Wait_T * cmd);
static int PawnCmdSystem_Wait_Update(PawnCmdSystem_T * sys, PawnCmdData_Wait_T * cmd, float seconds);
static void PawnCmdSystem_Move_Init(PawnCmdSystem_T * sys, PawnCmdData_Move_T * cmd);
static int PawnCmdSystem_Move_Update(PawnCmdSystem_T * sys, PawnCmdData_Move_T * cmd, float seconds);
static void PawnCmdSystem_Pickup_Init(PawnCmdSystem_T * sys, PawnCmdData_Pickup_T * cmd);
static int PawnCmdSystem_Pickup_Update(PawnCmdSystem_T * sys, PawnCmdData_Pickup_T * cmd, float seconds);
static void PawnCmdSystem_Drop_Init(PawnCmdSystem_T * sys, PawnCmdData_Drop_T * cmd);
static int PawnCmdSystem_Drop_Update(PawnCmdSystem_T * sys, PawnCmdData_Drop_T * cmd, float seconds);
static float interpolate(float a, float b, float p)
{
return a * (1 - p) + b * p;
}
void PawnCmdSystem_Init(PawnCmdSystem_T * sys, MapItemList_T * map_item_list, int x, int y, int z, float move_speed)
{
sys->current.type = e_PCT_NULL;
sys->state = e_PCS_Finished;
Position_Set(&sys->position, x, y, z);
sys->held_item = NULL;
sys->move_speed = move_speed;
sys->vispos_x = x;
sys->vispos_y = y;
sys->vispos_z = z;
sys->map_item_list = map_item_list;
}
static void PawnCmdSystem_InitCmd(PawnCmdSystem_T * sys, PawnCmd_T * cmd)
{
switch(cmd->type)
{
case e_PCT_Wait:
PawnCmdSystem_Wait_Init(sys, &cmd->data.wait);
break;
case e_PCT_Move:
PawnCmdSystem_Move_Init(sys, &cmd->data.move);
break;
case e_PCT_Pickup:
PawnCmdSystem_Pickup_Init(sys, &cmd->data.pickup);
break;
case e_PCT_Drop:
PawnCmdSystem_Drop_Init(sys, &cmd->data.drop);
break;
case e_PCT_NULL:
default:
break;
}
}
// returning 0 means Cmd has ended
static int PawnCmdSystem_UpdateCmd(PawnCmdSystem_T * sys, PawnCmd_T * cmd, float seconds)
{
int result;
switch(cmd->type)
{
case e_PCT_Wait:
result = PawnCmdSystem_Wait_Update(sys, &cmd->data.wait, seconds);
break;
case e_PCT_Move:
result = PawnCmdSystem_Move_Update(sys, &cmd->data.move, seconds);
break;
case e_PCT_Pickup:
result = PawnCmdSystem_Pickup_Update(sys, &cmd->data.pickup, seconds);
break;
case e_PCT_Drop:
result = PawnCmdSystem_Drop_Update(sys, &cmd->data.drop, seconds);
break;
case e_PCT_NULL:
default:
result = 0;
break;
}
return result;
}
void PawnCmdSystem_Update(PawnCmdSystem_T * sys, float seconds)
{
int result;
if(sys->state == e_PCS_Loaded)
{
PawnCmdSystem_InitCmd(sys, &sys->current);
sys->state = e_PCS_Running;
}
if(sys->state == e_PCS_Running)
{
result = PawnCmdSystem_UpdateCmd(sys, &sys->current, seconds);
if(result == 0)
{
sys->state = e_PCS_Finished;
}
}
}
int PawnCmdSystem_IsFinished(PawnCmdSystem_T * sys)
{
return sys->state == e_PCS_Finished;
}
int PawnCmdSystem_AttemptToSet(PawnCmdSystem_T * sys, const PawnCmd_T * new_command)
{
int result;
result = sys->state == e_PCS_Finished;
if(result)
{
memcpy(&sys->current, new_command, sizeof(PawnCmd_T));
sys->state = e_PCS_Loaded;
}
return result;
}
void PawnCmd_NULL_Init(PawnCmd_T * cmd)
{
cmd->type = e_PCT_NULL;
}
void PawnCmd_Wait_Init(PawnCmd_T * cmd, float time)
{
cmd->type = e_PCT_Wait;
cmd->data.wait.timer = time;
}
static void PawnCmdSystem_Wait_Init(PawnCmdSystem_T * sys, PawnCmdData_Wait_T * cmd)
{
sys->timer = 0;
}
static int PawnCmdSystem_Wait_Update(PawnCmdSystem_T * sys, PawnCmdData_Wait_T * cmd, float seconds)
{
int result;
sys->timer += seconds;
if(sys->timer < cmd->timer)
{
result = 1;
}
else
{
result = 0;
sys->timer = cmd->timer;
}
return result;
}
void PawnCmd_Move_Init(PawnCmd_T * cmd, const Position_T * target)
{
cmd->type = e_PCT_Move;
Position_Copy(&cmd->data.move.target, target);
}
static void PawnCmdSystem_Move_Init(PawnCmdSystem_T * sys, PawnCmdData_Move_T * cmd)
{
sys->timer = 0;
sys->flags = 0;
}
static int PawnCmdSystem_Move_Update(PawnCmdSystem_T * sys, PawnCmdData_Move_T * cmd, float seconds)
{
int result;
float p;
sys->timer += seconds;
if(sys->flags == 1)
{
result = 0;
}
else if(sys->timer < sys->move_speed)
{
result = 1;
p = sys->timer / sys->move_speed;
sys->vispos_x = interpolate(sys->position.x, cmd->target.x, p);
sys->vispos_y = interpolate(sys->position.y, cmd->target.y, p);
sys->vispos_z = interpolate(sys->position.z, cmd->target.z, p);
}
else
{
sys->timer = sys->move_speed;
result = 0;
Position_Copy(&sys->position, &cmd->target);
sys->flags = 1;
sys->vispos_x = cmd->target.x;
sys->vispos_y = cmd->target.y;
sys->vispos_z = cmd->target.z;
}
return result;
}
void PawnCmd_Pickup_Init(PawnCmd_T * cmd, Item_T * item)
{
cmd->type = e_PCT_Pickup;
cmd->data.pickup.item = item;
}
static void PawnCmdSystem_Pickup_Init(PawnCmdSystem_T * sys, PawnCmdData_Pickup_T * cmd)
{
sys->flags = 0;
}
static int PawnCmdSystem_Pickup_Update(PawnCmdSystem_T * sys, PawnCmdData_Pickup_T * cmd, float seconds)
{
int result;
if(sys->flags == 1)
{
result = 0;
}
else
{
sys->flags = 1;
MapItemList_Remove(sys->map_item_list, cmd->item);
sys->held_item = cmd->item;
result = 0;
}
return result;
}
void PawnCmd_Drop_Init(PawnCmd_T * cmd)
{
cmd->type = e_PCT_Drop;
cmd->data.drop.item = NULL;
}
static void PawnCmdSystem_Drop_Init(PawnCmdSystem_T * sys, PawnCmdData_Drop_T * cmd)
{
sys->flags = 0;
}
static int PawnCmdSystem_Drop_Update(PawnCmdSystem_T * sys, PawnCmdData_Drop_T * cmd, float seconds)
{
int result;
MapItem_T map_item;
if(sys->flags == 1)
{
result = 0;
}
else
{
sys->flags = 1;
map_item.pos.x = sys->position.x;
map_item.pos.y = sys->position.y;
map_item.pos.z = sys->position.z;
map_item.item = sys->held_item;
sys->held_item = NULL;
MapItemList_Add(sys->map_item_list, map_item.pos.x,
map_item.pos.y,
map_item.pos.z,
map_item.item);
result = 0;
}
return result;
}
|
C
|
#if 1
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<pthread.h>
#include<unistd.h>
#include<arpa/inet.h>
void Usage()
{
printf("usage: ./server [ip][port]\n");
}
void ProcessRequest(int client_fd,struct sockaddr_in* client_addr)
{
char buf[1024] = {0};
for(;;)
{
ssize_t read_size = read(client_fd,buf,sizeof(buf));
if(read_size<0)
{
perror("read");
continue;
}
if(read_size == 0)
{
printf("client: %s %d say bye",\
inet_ntoa(client_addr->sin_addr),\
ntohs(client_addr->sin_port));
close(client_fd);
break;
}
buf[read_size] = '\0';
printf("client: %s %dsay %s",\
inet_ntoa(client_addr->sin_addr),\
ntohs(client_addr->sin_port));
write(client_fd,buf,strlen(buf));
}
return;
}
typedef struct Arg
{
int fd;
struct sockaddr_in addr;
}Arg;
void * CreateWorker(void * ptr)
{
Arg * arg = (Arg*)ptr;
ProcessRequest(arg->fd,&arg->addr);
free(arg);
return NULL;
}
int main(int argc, char* argv[])
{
if(argc != 3)
{
Usage();
return 1;
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(argv[1]);
addr.sin_port = htons(atoi(argv[2]));
int fd = socket(AF_INET,SOCK_STREAM,0);
if(fd<0)
{
perror("socket");
return 1;
}
int ret = bind(fd,(struct sockaddr*)&addr,sizeof(addr));
if(ret<0)
{
perror("bind");
return 1;
}
ret = listen(fd,10);
if(ret<0)
{
perror("listen");
return 1;
}
for(;;)
{
struct sockaddr_in client_addr;
socklen_t len = sizeof(client_addr);
int client_fd = accept(fd,\
(struct sockaddr*)&client_addr,&len);
if(client_fd<0)
{
perror("accept");
continue;
}
pthread_t tid = 0;
Arg* arg = (Arg*)malloc(sizeof(Arg));
arg->fd = client_fd;
arg->addr = client_addr;
pthread_create(&tid,NULL,CreateWorker,(void*)arg);
pthread_detach(tid);
}
return 0;
}
#endif
#if 0
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
void Usage() {
printf("usage: ./server [ip] [port]\n");
}
void ProcessRequest(int client_fd, struct sockaddr_in* client_addr) {
char buf[1024] = {0};
for (;;) {
ssize_t read_size = read(client_fd, buf, sizeof(buf));
if (read_size < 0) {
perror("read");
continue;
}
if (read_size == 0) {
printf("client: %s say bye!\n", inet_ntoa(client_addr->sin_addr));
close(client_fd);
break;
}
buf[read_size] = '\0';
printf("client: %s say: %s\n", inet_ntoa(client_addr->sin_addr), buf);
write(client_fd, buf, strlen(buf));
}
return ;
}
typedef struct Arg {
int fd;
struct sockaddr_in addr;
} Arg;
void* CreateWorker(void* ptr) {
Arg* arg = (Arg*)ptr;
ProcessRequest(arg->fd, &arg->addr);
free(arg);
return NULL;
}
int main(int argc, char* argv[]) {
if (argc != 3) {
Usage();
return 1;
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(argv[1]);
addr.sin_port = htons(atoi(argv[2]));
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0) {
perror("socket");
return 1;
}
int ret = bind(fd, (struct sockaddr*)&addr, sizeof(addr));
if (ret < 0) {
perror("bind");
return 1;
}
ret = listen(fd, 10);
if (ret < 0) {
perror("listen");
return 1;
}
for (;;) {
struct sockaddr_in client_addr;
socklen_t len = sizeof(client_addr);
int client_fd = accept(fd, (struct sockaddr*)&client_addr, &len);
if (client_fd < 0) {
perror("accept");
continue;
}
pthread_t tid = 0;
Arg* arg = (Arg*)malloc(sizeof(Arg));
arg->fd = client_fd;
arg->addr = client_addr;
pthread_create(&tid, NULL, CreateWorker, (void*)arg);
pthread_detach(tid);
}
return 0;}
#endif
|
C
|
#include<stdio.h>
int main()
/*{
int n;
printf("How many times you wanna print?\n");
scanf("%d", &n);
for(int i=1; i<=n; i=i+1)
{
printf("Code Likha h...Count kr\n");
}
return 0;
}*/
/*{
int n, i=0;
printf("How many times you wanna print?\n");
scanf("%d", &n);
while (i<n)
{
printf("Code likha h\n");
i++;
}
return 0;
}*/
{
int n, i=0;
printf("How many times you wanna print?\n");
scanf("%d", &n);
do
{
printf("Code likha h\n");
i++;
}
while(i<n);
return 0;
}
|
C
|
#include <stdio.h>
#include <sys/fcntl.h>
int main(void)
{
int dev;
char c;
dev = open("/dev/simple_sensor_dev", O_RDWR);
scanf("%c", &c);
close(dev);
return 0;
}
|
C
|
#include <stdio.h>
int main() {
int i = 0, c;
while ((c = getchar()) != EOF)
{
/* code */
if (c != 10)
{
/* code */
++i;
} else
{
/* code */
break;
}
}
printf("%d\n", i);
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "Prototypes.h"
int testASCII()
{
int i =0;
for(i=0; i<256; i++)
{
printf("%d = %c \n", i, (char)i);
}
return 0;
}
|
C
|
#ifndef ANGLES_H
#define ANGLES_H
#include <stdbool.h>
#include "inc/point.h"
#define ANGLE_0 0
#define ANGLE_45 45
#define ANGLE_90 90
#define ANGLE_135 135
#define ANGLE_180 180
#define ANGLE_225 225
#define ANGLE_270 270
#define ANGLE_315 315
/**
* @brief AngleCorrection
* @param angle
* @return
*/
int16_t AngleCorrection(const int16_t input_angle);
/**
* @brief Creates a directional vector to describes a parametric equation for
* some line angle.
*
* If angle is not valid, set directional vector to ANGLE_0 direction.
*
* @param angle[in|out]
* @return Directional vector pointing at @p angle.
*/
Point AngleGetDirectionVector(const int16_t angle);
/**
* @brief AngleIsValid
* @param angle
* @return
*/
bool AngleIsValid(const int16_t angle);
#endif // ANGLES_H
|
C
|
/*
* iterador.c
*
* Created on: 7 de Mai de 2013
* Author: Antnio
*/
#include <stdlib.h>
# include "iterador.h"
#include "noSimples.h"
// estrutura de dados necessria para iterador de vector
struct _itVector{
void ** vector;
int corrente;
int numElems;
};
// estrutura de dados necessria para iterador de lista ligada
struct _itNoSimples{
noSimples primeiro;
noSimples corrente;
};
// estrutura de dados necessria para iterador de tabela de disperso
struct _itTabDis{
void ** vector;
int tamanho;
int posCor, posPri;
noSimples corrente;
};
struct _iterador{
int tipo; // 0- em vector; 1- em lista ligada simples; 2 - tabela de disperso
union _ed{
struct _itVector itV; // serve para vector
struct _itNoSimples itLS; // serve para lista ligada simples
struct _itTabDis itTD; // serve para a tabela de disperso
} itED;
};
/* Prototipos das funcoes associadas a um iterador */
/***********************************************
criaIterador - Criacao da instancia da estrutura associada a um iterador para um vector com n elementos.
Parametros:
vector - endereco do vector a iterar
n - numero de elementos no vector
Retorno: apontador para a instancia criada
Pre-condicoes: vector != NULL && n > 0
***********************************************/
iterador criaIteradorVector(void ** vector, int n){
iterador it = malloc(sizeof(struct _iterador));
if (it == NULL) return NULL;
it->tipo = 0;
it->itED.itV.numElems = n;
it->itED.itV.vector = vector;
it->itED.itV.corrente = 0;
return it;
}
/***********************************************
criaIterador - Criacao da instancia da estrutura associada a um iterador para uma lista ligada simples com n elementos.
Parametros:
no - endereco do primeiro n
n - numero de elementos no vector
Retorno: apontador para a instancia criada
Pre-condicoes: no != NULL && n > 0
***********************************************/
iterador criaIteradorListaSimples(void * no){
iterador it = malloc(sizeof(struct _iterador));
if (it == NULL) return NULL;
it->tipo = 1;
it->itED.itLS.primeiro = no;
it->itED.itLS.corrente = no;
return it;
}
/***********************************************
criaIterador - Criacao da instancia da estrutura associada a um iterador para uma tabela de disperso com tamanho tam.
Parametros:
vector - endereco da tabela de disperso
tam - tamanho da tabela de disperso
Retorno: apontador para a instancia criada
Pre-condicoes: vector != NULL && n > 0
***********************************************/
iterador criaIteradorTabDispersao(void* * vector, int tam){
int i;
iterador it = malloc(sizeof(struct _iterador));
if (it == NULL) return NULL;
it->itED.itTD.vector = vector;
it->tipo = 2;
it->itED.itTD.tamanho = tam;
it->itED.itTD.posCor=0;
for(i=0;i<tam && it->itED.itTD.vector[i]==NULL;i++);
if(i==tam){
it->itED.itTD.corrente = NULL;
it->itED.itTD.posCor = tam;
it->itED.itTD.posPri = tam;
}
else{
it->itED.itTD.posCor=i;
it->itED.itTD.posPri=i;
it->itED.itTD.corrente = it->itED.itTD.vector[it->itED.itTD.posCor];
}
return it;
}
/***********************************************
destroiIterador - Liberta a memoria ocupada pela instancia da estrutura associada ao iterador.
Parametros:
it - iterador a destruir
Retorno:
Pre-condicoes: it != NULL
***********************************************/
void destroiIterador (iterador it){
free(it);
}
/***********************************************
temSeguinteIterador - Indica se existe mais elementos para iterar no iterador.
Parametros:
it - iterador
Retorno: 1- caso exista mais elementos; 0- caso contrario
Pre-condicoes: it != NULL
***********************************************/
int temSeguinteIterador(iterador it){
if ((it->tipo == 0) && (it->itED.itV.corrente == it->itED.itV.numElems))
return 0;
if ((it->tipo == 1) && (it->itED.itLS.corrente == NULL))
return 0;
if((it->tipo == 2) && (it->itED.itTD.corrente == NULL))
return 0;
return 1;
}
/***********************************************
seguinteIterador - Consulta o seguinte elemento no iterador.
Parametros:
it - iterador
Retorno: endereco do elemento
Pre-condicoes: it != NULL && temSeguinteIterador(it) == 1
***********************************************/
void * seguinteIterador(iterador it){
void * elem = NULL;
int i;
switch (it->tipo){
case 0:{
elem = it->itED.itV.vector[it->itED.itV.corrente++];
break;
}
case 1:{
elem = elemNoSimples(it->itED.itLS.corrente);
it->itED.itLS.corrente = segNoSimples(it->itED.itLS.corrente);
break;
}
case 2:{
elem = elemNoSimples(it->itED.itTD.corrente);
if(segNoSimples(it->itED.itTD.corrente)!=NULL){
it->itED.itTD.corrente = segNoSimples(it->itED.itTD.corrente);
}
else{
for(i=it->itED.itTD.posCor+1;i<it->itED.itTD.tamanho && it->itED.itTD.vector[i]==NULL;i++);
if(i==it->itED.itTD.tamanho){
it->itED.itTD.corrente = NULL;
it->itED.itTD.posCor = i;
it->itED.itTD.posPri = i;
}
else{
it->itED.itTD.posCor=i;
it->itED.itTD.posPri=i;
it->itED.itTD.corrente = it->itED.itTD.vector[it->itED.itTD.posCor];
}
}
break;
}
}
return elem;
}
/***********************************************
iniciaIterador - coloca o iterador no incio da iterao.
Parametros:
it - iterador
Retorno:
Pre-condicoes: it != NULL
***********************************************/
void iniciaIterador(iterador it){
if (it->tipo == 0)
it->itED.itV.corrente = 0;
else
if(it->tipo == 1)
it->itED.itLS.corrente = it->itED.itLS.primeiro;
else
if (it->tipo == 2){
it->itED.itTD.posCor = it->itED.itTD.posPri;
it->itED.itTD.corrente = it->itED.itTD.vector[it->itED.itTD.posPri];
}
}
|
C
|
#include<stdio.h>
void main()
{
int a;
a=7>15 & 4<6;
printf("%d\n",a);
}
|
C
|
#include <stdio.h>
//Comparar edades
int main(){
int edad=0;
printf("Introduce tu edad [0-150]: ");
scanf("%d",&edad); // 30
//operadores lógicos
// AND -> &&
// OR -> ||
// NOT -> !
if (edad > 0 && edad <= 12){ // 1 - 12
printf("Eres generación alpha y tienes %d",edad);
if(edad < 9){
printf("\nEres un infante");
}else{
printf("\nEres aborrecente");
}
}else if (edad > 12 && edad <= 25){ // else if (30 < 25) -> false
printf("Eres generación y, y tienes %d anios",edad);
// 35....32605
}else if (edad > 25 && edad <= 45){ // else if (30 < 25) -> false
printf("Eres generación x, y tienes %d anios",edad);
// 35....32605
}else if (edad > 45 && edad < 150){ // else if (30 < 25) -> false
printf("Eres generación BB, y tienes %d anios",edad);
// 35....32605
}
else{
printf("Introduce una edad válida [0-150]");
}
printf("\nFin programa");
return 0;
}
|
C
|
#include "index.h"
#include <fcntl.h>
// gpio ϴ ϴ Ȯϴ° ߰ (2015.08.12)
void gpioExport(char *gpioNumber)
{
int fp;
char location[40];
strcpy(location, "/sys/class/gpio/export");
strcat(location, gpioNumber);
fp = open("/sys/class/gpio/export", O_WRONLY);
#ifdef DEBUG_OPEN
if(fp == -1)
{
perror("gpioExport : ");
exit(0);
}
#endif
write(fp, gpioNumber, 3);
close(fp);
}
void gpioDirection(char *gpioNumber, char *inout)
{
int fp;
char fpData[100];
char readResult[10];
strcpy(fpData, "/sys/class/gpio/gpio");
strcat(fpData, gpioNumber);
strcat(fpData, "/direction");
//
// fpRead = open(fpData, O_RDONLY);
// n = read(fpRead, readResult, 10);
// readResult[n] = '\0';
//
// if(strcmp(readResult, inout) != -1)
// {
// return;
// }
fp = open(fpData, O_WRONLY);
#ifdef DEBUG_OPEN
if(fp == -1)
{
perror("gpioDirection : ");
exit(0);
}
#endif
write(fp, inout, 4);
close(fp);
}
void gpioValueWrite(char *gpioNumber, char *value)
{
int fp;
static char fpData[100];
char readResult[10];
strcpy(fpData, "/sys/class/gpio/gpio");
strcat(fpData, gpioNumber);
strcat(fpData, "/value");
printf("fpData ======== %s\n\n", fpData);
printf("value ========= %s\n\n", value);
fp = open(fpData, O_WRONLY);
#ifdef DEBUG_OPEN
if(fp == -1)
{
perror("gpioValueWrite : ");
exit(0);
}
#endif
write(fp, value, 3);
close(fp);
}
char* gpioValueRead(char *gpioNumber)
{
int fp;
char fpData[100];
static char result[2];
strcpy(fpData, "/sys/class/gpio/gpio");
strcat(fpData, gpioNumber);
strcat(fpData, "/value");
fp = open(fpData, O_RDONLY);
#ifdef DEBUG_OPEN
if(fp == -1)
{
perror("gpioValueRead : ");
exit(0);
}
#endif
read(fp, result, 255);
printf("\n\n result : %s\n\n", result);
close(fp);
return result;
}
void gpioDrive(char *gpioNumber, char *setting)
{
char fpData[100];
int fp;
strcpy(fpData, "/sys/class/gpio/gpio");
strcat(fpData, gpioNumber);
strcat(fpData, "/drive");
fp = open(fpData, O_WRONLY);
#ifdef DEBUG_OPEN
if(fp == -1)
{
perror("gpioDrive : ");
exit(0);
}
#endif
write(fp, setting, 7);
close(fp);
}
int gpioPair(char *gpioNumber, char *gpioPair)
{
int readResult;
int fp;
char fpData[100];
strcpy(fpData, "/var/www/project_os/DB/gpio_pair/");
strcat(fpData, gpioNumber);
fp = open(fpData, O_RDONLY);
#ifdef DEBUG_OPEN
if(fp == -1)
{
perror("gpioPair : ");
exit(0);
}
#endif
readResult = read(fp, gpioPair, 3);
close(fp);
return readResult;
}
void DBWrite(char *gpioNumber, char *setting)
{
char fpData[100];
int fp;
int result;
result = atoi(gpioNumber);
strcpy(fpData, "/var/www/project_os/DB/gpio/");
strcat(fpData, gpioNumber);
printf("%s\n", fpData );
if((fp = open(fpData, O_WRONLY | O_TRUNC)) == -1)
{
perror("DBWRITE : ");
close(fp);
//exit(0);
}
write(fp, setting, strlen(setting));
close(fp);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct bst
{
int info;
struct bst *lNode;
struct bst *rNode;
}*root=NULL,*temp=NULL,*t1,*t2;
static int index;
void insertNode();
void create();
void delete();
void deleteSearch(struct bst *t,int data) ;
void delete1(struct bst *t) ;
int smallest(struct bst *t) ;
int largest(struct bst *t) ;
void find(struct bst *t,int data);
void insertSearch(struct bst *t);
void inorder(struct bst *t);
void preorder(struct bst *t);
void postorder(struct bst *t);
int height(struct bst *t);
int flag =1;
int main()
{
int opt,h,data;
char ch='y';
do
{
printf("\n Program for Binary Search Tree....\n") ;
printf("\n1.To insert an element in BST(Please maintain Acending order)::\n") ;
printf("\n2.To Delete an element from created BST::\n") ;
printf("\n3.To Search an element in Created BST..::\n") ;
printf("\n4.Inorder Traversal...................::\n ") ;
printf("\n5.Preorder Traversal.................::\n") ;
printf("\n6.Postorder Traversal.................::\n") ;
printf("\n7.Hight of BST is.....................::\n") ;
printf("\nEnter your Choice......................::") ;
scanf("%d",&opt) ;
switch(opt)
{
case 1:insertNode();
break;
case 2:
delete();
break;
case 3:printf("\nEnter an Element for search :");
scanf("%d",&data);
index=0;
find(root,data);
break;
case 4:inorder(root);
break;
case 5:preorder(root);
break;
case 6:postorder(root);
break;
case 7:h=height(root);
printf("\nHeight of given BST is..::%d",h) ;
break;
default:printf("\n Hello you Entered wrong Choice ..\n") ;
}printf("\nDo you want to continue ?? [y/n]:") ;
scanf("\n%c",&ch) ;
}while(ch == 'y' || ch == 'Y');
}
void insertNode()
{
create();
if(root==NULL)
root=temp;
else
insertSearch(root);
}
void create()
{
int data;
temp=(struct bst*)malloc(1*sizeof(struct bst));
printf("\nEnter a element to insert in BST:") ;
scanf("%d",&data) ;
temp->info=data;
temp->lNode=NULL;
temp->rNode=NULL;
}
void insertSearch(struct bst *t)
{
if( (temp->info > t->info) && (t->rNode !=NULL) )
insertSearch(t->rNode) ;
else if( (temp->info > t->info) && (t->rNode==NULL) )
t->rNode=temp;
if( (temp->info < t->info) && (t->lNode !=NULL))
insertSearch(t->lNode) ;
else if( (temp ->info < t->info) && (t->lNode==NULL) )
t->lNode=temp;
}
void find(struct bst *t,int data)
{
if(root ==NULL)
{
printf("\nsorry In BST there is no element::\n");
return;
}
if(t->info==data)
{
printf("\nElement found in BST successfuly at Index ::%d",index);
}
else if(data < t->info)
{
index=2*index+1;
find(t->lNode,data);
}
else if(data > t->info)
{
index=2*index+2;
find(t->rNode,data);
}
else
printf("\nElement not found in BST::\n");
return;
}
/* To check for the deleted node */
void delete()
{
int data;
if (root == NULL)
{
printf("No elements in a tree to delete");
return;
}
printf("Enter the data to be deleted : ");
scanf("%d", &data);
t1 = root;
t2 = root;
deleteSearch(root,data);
}
/* Search for the appropriate position to insert the new node */
void deleteSearch(struct bst *t,int data)
{
if ((data > t->info))
{
t1 = t;
deleteSearch(t->rNode, data);
}
else if ((data < t->info))
{
t1 = t;
deleteSearch(t->lNode, data);
}
else if ((data==t->info))
{
delete1(t);
}
}
/* To delete a node */
void delete1(struct bst *t)
{
int k;
/* To delete leaf node */
if ( (t->lNode == NULL) && (t->rNode == NULL) )
{
if (t1->lNode == t)
{
t1->lNode = NULL;
}
else
{
t1->rNode = NULL;
}
t = NULL;
free(t);
return;
}
/* To delete node having one left hand child */
else if ((t->rNode == NULL))
{
if (t1 == t)
{
root = t->lNode;
t1 = root;
}
else if (t1->lNode == t)
{
t1->lNode = t->lNode;
}
else
{
t1->rNode = t->lNode;
}
t = NULL;
free(t);
return;
}
/* To delete node having right hand child */
else if (t->lNode == NULL)
{
if (t1 == t)
{
root = t->rNode;
t1 = root;
}
else if (t1->rNode == t)
t1->rNode = t->rNode;
else
t1->lNode = t->rNode;
t == NULL;
free(t);
return;
}
/* To delete node having two child */
else if ((t->lNode != NULL) && (t->rNode != NULL))
{
t2 = root;
if (t->rNode != NULL)
{
k = smallest(t->rNode);
flag = 1;
}
else
{
k =largest(t->lNode);
flag = 2;
}
deleteSearch(root, k);
t->info = k;
}
}
/* To find the smallest element in the right sub tree */
int smallest(struct bst *t)
{
t2 = t;
if (t->lNode != NULL)
{
t2 = t;
return(smallest(t->lNode));
}
else
return (t->info);
}
/* To find the largest element in the left sub tree */
int largest(struct bst *t)
{
if (t->rNode != NULL)
{
t2 = t;
return(largest(t->rNode));
}
else
return(t->info);
}
void inorder(struct bst *t)
{
if(root == NULL)
{
printf("\nSorry In BST there is no element::\n") ;
return;
}
if(t->lNode !=NULL)
inorder(t->lNode);
printf("%d ->",t->info);
if(t->rNode != NULL)
inorder(t->rNode);
}
void preorder(struct bst *t)
{
if(root==NULL)
{
printf("\nSorry In BST there is no Element::\n") ;
return;
}
printf("%d ->",t->info) ;
if(t->lNode !=NULL)
preorder(t->lNode);
if(t->rNode !=NULL)
preorder(t->rNode);
}
void postorder(struct bst *t)
{
if(root==NULL)
{
printf("\nsorry In BST there is no Element::\n") ;
return;
}
if(t->lNode !=NULL)
postorder(t->lNode);
if(t->rNode !=NULL)
postorder(t->rNode);
printf("%d ->",t->info) ;
}
int height(struct bst *t)
{
int hL,hR;
if(!t)
return 0;
hL=height(t->lNode);
hR=height(t->lNode);
if(hL>hR )
return hL+1;
else
return hR+1;
}
|
C
|
#include <stdio.h>
int posOfFile(int *history, int lookup)
{
}
int main(int argc, char const *argv[])
{
int history[] = {1, 2, 3, 4, 5, -2, 6, 7, 8, 9, -3, 10, 11, -1, -2, 0};
int lookup = 1;
printf("%d", posOfFile(history, lookup));
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "complexo.h"
int main(){
Complexo_t *p, *q;
bool x;
x = Construtor(&p);
if(x == false){
printf("Memoria nao foi alocada.\n");
exit(1);
}
x = Construtor(&q);
if(x == false){
printf("Memoria nao foi alocada.\n");
exit(1);
}
PreencheComplexoDeReais(p, 1, 2);
PreencheComplexoDeReais(q, 2, 3);
SomaComplexos(p, q);
x = Destrutor(&q);
if(x == false){
printf("Memoria nao foi liberada corretamente.\n");
}
x = Construtor(&q);
if(x == false){
printf("Memoria nao foi liberada corretamente.\n");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
int main()
{
freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
float n, a, b,s1,s2;
scanf("%f",&n);
while(n--){
scanf("%f %f",&a,&b);
s1=(a+b)/2;s2=(a-b)/2;
if(s1!=(int)s1||s2!=(int)s2||s1<0||s2<0) printf("impossible\n");
else printf("%d %d\n",(int)s1,(int)s2);
}
return 0;
}
|
C
|
#include<iostream>
#include<stdio.h>
int main()
{
double a, b, c, x = 0, y = 0;
char ch;
while (1)
{
printf("请输入一元二次函数的系数(以空格隔开):");
scanf("%lf%lf%lf", &a, &b, &c);
printf("你输入的函数为y=%gx^2%+gx%+g\n图像如下\n", a, b, c);
do //外层循环控制Y坐标的象限
{
if (y == 40)
{
printf("|---------|---------|---------|---------|---------|---------|---------|---------");
} //控制很坐标的输出
else
do //内层循环控制点的输入输出及X的象限
{
if (x == 40 && (int)y % 10 == 0)
printf("-"); //控制纵坐标的刻度
else if (x == 40 && (int)y % 10 != 0)
printf("|"); //控制纵坐标的刻度线
else if ((4 - y / 10) + 0.08 >= a*(x / 10 - 4)*(x / 10 - 4) + b*(x / 10 - 4) + c
&& (4 - y / 10) - 0.08 <= a*(x / 10 - 4)*(x / 10 - 4) + b*(x / 10 - 4) + c) //4-y/10以及x/10-4将循环次数像坐标值的转换
printf("|"); //当横纵坐标的值符合输入的函数,输出图像点
else
printf(" "); //当没有坐标系和函数点时输出空格
x++;
} while (x < 80);
y++;
printf(""); //控制每行的换行
x = 0;
} while (y < 80);
printf("还想画吗?(Y/N):");
getchar();
scanf("%c", &ch);
if (ch == 'N' || ch == 'n')
break;
x = 0;
y = 0;
}
system("pause");
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* reverse.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nbrucker <nbrucker@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/12/03 10:24:37 by nbrucker #+# #+# */
/* Updated: 2017/12/03 10:24:37 by nbrucker ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
int ft_issort_reverse(t_ps *lst)
{
int max;
t_ps *start;
start = lst;
max = ft_max(lst);
while (lst->x != max)
lst = lst->next;
while (lst->next->x != max)
{
if (lst->x < lst->next->x)
return (-1);
lst = lst->next;
}
lst = start;
if (ft_index(lst, max) == 0)
return (1);
else if (ft_index(lst, max) <= ft_len(lst) - ft_index(lst, max))
return (0);
return (2);
}
void ft_rotate_sort_reverse(t_ps **b, t_op **algo)
{
while (ft_issort_reverse(*b) == 0)
ft_rotate(b, 'b', algo);
while (ft_issort_reverse(*b) == 2)
ft_reverse_rotate(b, 'b', algo);
}
|
C
|
//
// main.c
// Exe4.23
//
// Created by Francesco Parrucci on 17/01/19.
// Copyright © 2019 Francesco Parrucci. All rights reserved.
//
/*
MODIFICA IL PROGRAMMA DELLA FIGURA 4.6 IN MODO CHE UTILIZZI SOLTANTO DEGLI INTERI PER CALCORARE L'INTERESSE COMPOSTO.
(SUGGERIMENTO: TRATTATE TUTTE LE CIFRE MONETARIE COME QUANTITA' INTERE DI CENTESIMI. IN SEGUITO "SEPARATE" IL RISULTATO DALLE
SUE PORZIONI DI DOLLARI E CENTESIMI, UTILIZZANDO RISPETTIVAMENTE LE OPERAZIONI DI DIVISIONE E MODULO. INSERITE UN PUNTO)
*/
/* Calculating compound interest */
#include <stdio.h>
#include <math.h>
main()
{
int year, ammount, principal = 1000, rate = 5;
printf("%4s%21s\n", "Year", "Amount on deposit");
for (year = 1; year <= 10; year++) {
ammount = (int) (100 * principal * pow(1 + ((float)rate / 100), year));
printf("%4d%21d.%2d corrispettivo intero\n", year, ammount/100 , ammount%100);
}
return 0;
}
|
C
|
// proc.c, 159
/*
need to include "syscall.h" to call the new OS services
program a void-returning Init that has no input
loop forever:
call get_time_call() to get current time in seconds
convert time to a smaller time str
call write_call to show time_str
...
... see demo run to issue calls to perform the same...
...
}
}
*/
// all user processes are coded here
// processes do not R/W kernel data or call kernel code, only via syscalls
// include spede.h and kernel.h
#include "spede.h"
#include "kernel.h"
#include "misc.h"
#include "syscall.h"
#include "proc.h"
#define STRWIDTH 4
char str[] = " ";
void Clock() {
int second, last_second;
second = last_second = 0;
display(second);
while(1){
second = get_time_call();
if(last_second != second) {
last_second = second;
display(second);
}
}
}
void display(int num) {
static unsigned short *p = (unsigned short*)VIDEO_START + CORNER - STRWIDTH;
unsigned i;
itos(num, str);
for(i = 0; i < STRWIDTH; ++i)
*(p + i) = str[i] + VIDEO_MASK;
}
void Init() {
char hold[STR_SIZE];
while(1) {
write_call("The time is ");
write_call(str);
write_call(".\n");
write_call("What do you say to a cup of coffee? ");
read_call(hold);
write_call("The answer is ");
write_call(hold);
write_call(".\n");
}
}
|
C
|
#include <stdio.h>
int main(int argc, const char * argv[]) {
int x = 1, y = 2;
x = x + y;
printf("...%d.....%d\n", x, y);
return 0;
}
|
C
|
// Demonstrate basic pointer arithmetic
#include <stdio.h>
void print0_ptr(int *p){ // print int pointed at by p
printf("%ld: %d\n",(long) p, *p); // address and 0th elem
}
int main(){
int x = 21;
int *p; // declare a pointer
int a[] = {5,10,15}; // declare array, auto size
p = a; // point p at a
print0_ptr(p);
p = a+1; // point p at a plus offset
print0_ptr(p);
p++; // increase p: pointer arithmetic
print0_ptr(p);
p+=2; // increase p (!!!)
print0_ptr(p);
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
/* 変数宣言 */
int n; /* 近似次数 */
double x, y = 1.0; /* 独立変数、従属変数 */
/* 途中の計算に必要な変数の宣言 */
int i; /* 繰り返し変数の宣言 */
double f = 1.0, p = 1.0; /* 階乗値,累乗値 */
/* データの読み込み(倍精度, 整数) */
scanf("%lf%d",&x,&n);
for (i=1; i<=n; i++) {
f *= (double)i;
p *= x;
y += p / f;
}
/* e^x の近似値の表示 */
printf("マクローリン展開による次数 %d までの e^(%g) の近似値\n"
" =%21.16g\n", n, x, y);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: poliveir <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/17 20:39:12 by poliveir #+# #+# */
/* Updated: 2021/03/22 17:02:28 by poliveir ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *ft_substr(char const *s, unsigned int start, size_t len)
{
char *ptr;
size_t i;
size_t length;
if (!s)
return (NULL);
length = ft_strlen(s);
if (start > length)
return (ft_strdup(""));
if (len > length)
len = length;
if ((start + len) < (length + 1))
if (!(ptr = (char*)malloc(len + 1)))
return (NULL);
if ((start + len) >= (length + 1))
if (!(ptr = (char*)malloc(len)))
return (NULL);
i = 0;
while (i < len && s[start] != '\0')
{
ptr[i++] = s[start++];
}
ptr[i] = '\0';
return (ptr);
}
char *ft_strchr(const char *s, int c)
{
int i;
i = 0;
while (s[i] != '\0')
{
if (s[i] == (char)c)
return ((char*)&s[i]);
i++;
}
if (s[i] == (char)c)
return ((char*)&s[i]);
return (0);
}
char *ft_strjoin(char const *s1, char const *s2)
{
char *ptr;
size_t i;
size_t len;
size_t j;
if (!s1 || !s2)
return (NULL);
len = ft_strlen(s1) + ft_strlen(s2);
if (!(ptr = (char*)malloc(len + 1)))
return (NULL);
i = 0;
while (s1[i] != '\0')
{
ptr[i] = s1[i];
i++;
}
j = 0;
while (i < len)
{
ptr[i] = s2[j];
i++;
j++;
}
ptr[i] = '\0';
return (ptr);
}
char *ft_strdup(const char *s1)
{
char *ptr;
int i;
if (!(ptr = (char*)(malloc((sizeof(char) * ft_strlen(s1)) + 1))))
return (NULL);
else
{
i = 0;
while (s1[i] != '\0')
{
ptr[i] = s1[i];
i++;
}
ptr[i] = '\0';
}
return (ptr);
}
size_t ft_strlen(const char *s)
{
size_t i;
i = 0;
while (s[i] != '\0')
i++;
return (i);
}
|
C
|
/*
** EPITECH PROJECT, 2019
** corewar asm
** File description:
** manipulation of bytes
*/
#include <stdlib.h>
#include <stdio.h>
#include "operator_abstract.h"
#include "corewar.h"
int reverse_bytes(int nb)
{
int reversed_bytes = 0;
int index = 0;
int next_byte = 0;
for (; index < 4; ++index) {
next_byte = (nb >> BITS_PER_BYTES * index) & 0xff;
reversed_bytes = reversed_bytes | next_byte
<< (BITS_PER_BYTES * 3 - BITS_PER_BYTES * index);
}
return reversed_bytes;
}
params_t **get_type_of_instruction(pc_t *pc, vm_t *vm)
{
params_t **params = malloc(sizeof(params_t *) * 3);
char to_decode = vm->memory[(pc->adress + 1) % MEM_SIZE];
for (int i = 0; i < 3; i++)
params[i] = malloc(sizeof(params_t));
params[0]->type = 0b00000011 & to_decode >> 6;
params[0]->size = (params[0]->type == 1) ? 1 : params[0]->size;
params[0]->size = (params[0]->type == 2) ? DIR_SIZE : params[0]->size;
params[0]->size = (params[0]->type == 3) ? IND_SIZE : params[0]->size;
params[1]->type = 0b00000011 & to_decode >> 4;
params[1]->size = (params[1]->type == 1) ? 1 : params[1]->size;
params[1]->size = (params[1]->type == 2) ? DIR_SIZE : params[1]->size;
params[1]->size = (params[1]->type == 3) ? IND_SIZE : params[1]->size;
params[2]->type = 0b00000011 & to_decode >> 2;
params[2]->size = (params[2]->type == 1) ? 1 : params[2]->size;
params[2]->size = (params[2]->type == 2) ? DIR_SIZE : params[2]->size;
params[2]->size = (params[2]->type == 3) ? IND_SIZE : params[2]->size;
return params;
}
|
C
|
#define doller 20 //定义给定多少钱
#define price 1 // 定义每瓶的价格
#include <stdio.h>
#include <stdlib.h>
int Drink_Water(int arr[]){
int total = doller;
int empty = doller;
while (empty >= 2) {
total += empty / 2;
empty = empty / 2 + empty % 2;
}
return total;
}
int main(){
int arr[doller / price] = {0};
int ret = Drink_Water(arr);
printf("%d\n", ret);
return 0;
}
|
C
|
// find better solutions !!! use UNION FIND by which algorithms ????
// learn a lot from this !!!
int _hash(char* s, int primer)
{
int i = 0;
int c = s[i ++];
int t = 0;
while (c)
{
t = ((t << 8) + c) % primer;
c = s[i ++];
}
return t;
}
void am_sort(int* n, int s, int e, int* m)
{
if (s >= e)
return;
int t;
if (n[s] > n[e])
{
t = n[s];
n[s] = n[e];
n[e] = t;
t = m[s];
m[s] = m[e];
m[e] = t;
}
if (s + 1 == e)
return;
int cs = s;
int ce = e;
for (int i = s + 1; i <= e; i ++)
{
while (n[i] < n[s]) i ++;
while (n[e] > n[s]) e --;
if (i >= e)
{
t = n[s];
n[s] = n[e];
n[e] = t;
t = m[s];
m[s] = m[e];
m[e] = t;
}
else
{
t = n[i];
n[i] = n[e];
n[e] = t;
t = m[i];
m[i] = m[e];
m[e] = t;
}
}
am_sort(n, cs, e - 1, m);
am_sort(n, e + 1, ce, m);
}
void am_strsort(char** n, int s, int e)
{
if (s >= e)
return;
char* t;
if (strcmp(n[s], n[e]) > 0)
{
t = n[s];
n[s] = n[e];
n[e] = t;
}
int cs = s;
int ce = e;
for (int i = s + 1; i <= e; i ++)
{
while (strcmp(n[i], n[s]) < 0) i ++;
while (strcmp(n[e], n[s]) > 0) e --;
if (i >= e)
{
t = n[s];
n[s] = n[e];
n[e] = t;
}
else
{
t = n[i];
n[i] = n[e];
n[e] = t;
}
}
am_strsort(n, cs, e - 1);
am_strsort(n, e + 1, ce);
}
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *columnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
char*** accountsMerge(char*** accounts, int accountsRowSize, int *accountsColSizes, int** columnSizes, int* returnSize)
{
int primer;
int pri[] = {5, 11, 17, 31, 67, 131, 257, 521, 1031, 2053, 4099, 8209, 16411, 32771, 65551, 131101, 262147, 524309, 1048583, 2097169, 4194319, 8388617};
int pri_l = sizeof(pri)/sizeof(pri[0]);
int ol = 0;
for (int i = 0; i < accountsRowSize; i ++)
ol += accountsColSizes[i] - 1;
for (int i = 0; i < pri_l; i ++)
{
primer = pri[i];
if (primer / ol > 3)
break;
}
short* hash = calloc(sizeof(short*), primer);
int as_id = 1;
char** as = calloc(sizeof(char*), ol+ 1);
int* sames = calloc(sizeof(int), ol + 1);
int* names = calloc(sizeof(int), accountsRowSize);
for (int i = 0; i < accountsRowSize; i ++)
{
char** c = accounts[i];
if (accountsColSizes[i] > 0)
{
int mi = 0;
int merge[10];
int oid = as_id;
for (int j = 1; j < accountsColSizes[i]; j ++)
{
char* mail = c[j];
int h = _hash(mail, primer);
while (hash[h] && strcmp(mail, as[hash[h]]))
h = (h + 1) % primer;
if (hash[h] && sames[hash[h]])
merge[mi ++] = names[sames[hash[h]] - 1]; // careful here, must use the current id not the one in sames
else if (!hash[h])
{
as[as_id] = mail;
hash[h] = as_id ++;
}
}
int tid;
if (mi)
{
tid = merge[0];
for (int k = 0; k < accountsRowSize; k ++)
for (int l = 0; l < mi; l ++)
{
if (names[k] == merge[l])
names[k] = tid;
}
}
else
{
tid = i + 1;
}
for (oid; oid < as_id; oid ++)
sames[oid] = tid;
names[i] = tid;
}
}
for (int i = 0; i < accountsRowSize; i ++)
sames[i] = i;
am_sort(names, 0, accountsRowSize - 1, sames);
int rs = 0;
int* cs = malloc(sizeof(int) * accountsRowSize);
char*** ret = malloc(sizeof(char**) * accountsRowSize);
for (int i = 0; i < accountsRowSize; i ++)
{
int oi = i;
int x = names[i];
int l = accountsColSizes[sames[i]];
while (i + 1 < accountsRowSize && names[i + 1] == x)
{
i ++;
l += accountsColSizes[sames[i]] - 1;
}
char** rt = malloc(sizeof(char*) * l);
ret[rs] = rt;
int ri = 0;
rt[ri ++] = accounts[sames[oi]][0];
for (int k = oi; k <= i; k ++)
for (int j = 1; j < accountsColSizes[sames[k]]; j ++)
rt[ri ++] = accounts[sames[k]][j];
am_strsort(rt, 1, l - 1);
int al = 2;
for (int k = 2; k < l; k ++)
if (strcmp(rt[k], rt[k - 1]))
rt[al ++] = rt[k];
cs[rs] = al;
rs ++;
}
*returnSize = rs;
*columnSizes = cs;
return ret;
}
|
C
|
/*
Given an input array
a={1,2,3,6,2,8----}
product of all numbers=p=a[0]*a[1]*---a[n-1] where n is size of array
output arrau should be b={p/a[0],p/a[1],p/a[2]-----}. you should not use division operator.Time complexity should be less than o(n2).
*/
/*
this one is simple
you will need two array of same size
solution as example:
{a,b,c,d,e,f}
generate
{1,a,ab,abc,abcd,abcde}
and
{bcdef,cdef,def,ef,f,1}
now do a dot product of the above two array
you are done..
complexity O(3n)= O(n)
the above array are easily calculable as they can be generated the first from the front of array and other from back with 1 multiplcation for each element.
*/
#include <iostream>
using namespace std;
int *prodExceptCurrElem(int *arr, int len)
{
if(!arr || len < 0) return NULL;
int *newArr = new int[len];
int i = 0, prodSoFar = 1;
for(i = 0;i < len; ++i) {
newArr[i] = prodSoFar;
prodSoFar *= arr[i];
}
prodSoFar = 1;
for(i = len-1; i >= 0; i--) {
newArr[i] *= prodSoFar;
prodSoFar *= arr[i];
}
for(i = 0; i < len; ++i)
cout << i << " : " << newArr[i] << " ";
cout << endl;
return newArr;
}
int main()
{
int a[] = {1,2,3,6,2,8};
int len = sizeof(a)/sizeof(a[0]);
int *b = prodExceptCurrElem(a, len);
for(int i = 0; i < len; ++i)
cout << i << " : " << b[i] << " ";
cout << endl;
return 0;
}
|
C
|
/** @file input.c Documented input module.
*
* Julien Lesgourgues, 27.08.2010
*/
#include "input.h"
/**
* Use this routine to extract initial parameters from files 'xxx.ini'
* and/or 'xxx.pre'. They can be the arguments of the main() routine.
*
* If class is embedded into another code, you will probably prefer to
* call directly input_init() in order to pass input parameters
* through a 'file_content' structure.
*/
int input_init_from_arguments(
int argc,
char **argv,
params_struct * params,
data_struct * data,
ErrorMsg errmsg
) {
/** Summary: */
/** - define local variables */
struct file_content fc;
struct file_content fc_input;
struct file_content fc_precision;
char input_file[_ARGUMENT_LENGTH_MAX_];
char precision_file[_ARGUMENT_LENGTH_MAX_];
int i;
char extension[5];
/** - Initialize the two file_content structures (for input
parameters and precision parameters) to some null content. If no
arguments are passed, they will remain null and inform
init_params() that all parameters take default values. */
fc.size = 0;
fc_input.size = 0;
fc_precision.size = 0;
input_file[0]='\0';
precision_file[0]='\0';
/** If some arguments are passed, identify eventually some 'xxx.ini'
and 'xxx.pre' files, and store their name. */
if (argc > 1) {
for (i=1; i<argc; i++) {
strncpy(extension,(argv[i]+strlen(argv[i])-4),4);
extension[4]='\0';
if (strcmp(extension,".ini") == 0) {
zelda_test(input_file[0] != '\0',
"You have passed more than one input file with extension '.ini', choose one.");
strcpy(input_file,argv[i]);
}
if (strcmp(extension,".pre") == 0) {
zelda_test(precision_file[0] != '\0',
"You have passed more than one precision with extension '.pre', choose one.");
strcpy(precision_file,argv[i]);
}
}
}
/** - if there is an 'xxx.ini' file, read it and store its content. */
if (input_file[0] != '\0')
zelda_call(parser_read_file(input_file,&fc_input,errmsg));
/** - if there is an 'xxx.pre' file, read it and store its content. */
if (precision_file[0] != '\0')
zelda_call(parser_read_file(precision_file,&fc_precision,errmsg));
/** - if one or two files were read, merge their contents in a
single 'file_content' structure. */
if ((input_file[0]!='\0') || (precision_file[0]!='\0'))
zelda_call(parser_cat(&fc_input,&fc_precision,&fc,errmsg));
zelda_call(parser_free(&fc_input));
zelda_call(parser_free(&fc_precision));
/** - now, initialize all parameters given the input 'file_content'
structure. If its size is null, all parameters take their
default values. */
zelda_call(input_init(
&fc,
params,
data,
errmsg));
zelda_call(parser_free(&fc));
return _SUCCESS_;
}
/**
* Initialize each parameters, first to its default values, and then
* from what can be interpreted from the values passed in the input
* 'file_content' structure. If its size is null, all parameters keep
* their default values.
*/
//
int input_init(
struct file_content * pfc,
params_struct * params,
data_struct * data,
ErrorMsg errmsg
) {
/** Summary: */
/** - define local variables */
int flag1,flag2,flag3;
double param1,param2,param3;
int n,entries_read;
int int1,fileentries;
double fnu_factor;
double * pointer1;
char string1[_ARGUMENT_LENGTH_MAX_];
double Omega_tot;
int i;
FILE * param_output;
FILE * param_unused;
char param_output_name[_LINE_LENGTH_MAX_];
char param_unused_name[_LINE_LENGTH_MAX_];
/** - set all parameters (input and precision) to default values */
zelda_call(input_default_params(
params,
data));
/** - if entries passed in file_content structure, carefully read
and interpret each of them, and tune accordingly the relevant
input parameters */
// ============
// = Modality =
// ============
zelda_call(parser_read_string(pfc,
"modality",
&(string1),
&(flag1),
errmsg));
if (flag1 == _TRUE_) {
int flag2 = _FALSE_;
if (strcmp(string1,"vinfall") == 0) {
params->modality = VINFALL;
flag2=_TRUE_;
}
if (strcmp(string1,"vinfall_isolation") == 0) {
params->modality = VINFALL_ISOLATION;
flag2=_TRUE_;
}
zelda_test(flag2 == _FALSE_,
"could not identify what to compute, set modality to a value between the following: vinfall, vinfall_isolation");
}
// ==========================
// = File naming parameters =
// ==========================
zelda_read_string("root",params->root);
zelda_read_string("input_format", params->input_format);
zelda_read_string("results_filename", params->results_filename);
// ===========================
// = Cuts-related parameters =
// ===========================
parser_read_list_of_integers(
pfc,
"columns_to_cut",
&entries_read,
&(params->columns_to_cut),
&flag2,
errmsg
);
if (flag2==_TRUE_)
params->n_cuts = entries_read;
parser_read_list_of_doubles(
pfc,
"cuts",
&entries_read,
&(params->cuts),
&flag2,
errmsg);
if (params->n_cuts>0)
zelda_test((entries_read!=2*params->n_cuts) || flag2 == _FALSE_, "the 'cuts' field should have exactly double the entries of the field 'columns_to_cut'");
// ======================
// = Separation binning =
// ======================
zelda_read_double("r_min", params->r_min);
zelda_read_double("r_max", params->r_max);
zelda_read_int("n_box_bins", params->n_box_bins);
// Parse the binning mode
zelda_call(parser_read_string(pfc,
"binning_mode",
&(string1),
&(flag1),
errmsg));
if (flag1 == _TRUE_) {
int flag2 = _FALSE_;
if (strcmp(string1,"lin") == 0) {
params->binning_mode = LIN_BINNING;
flag2=_TRUE_;
}
if (strcmp(string1,"log") == 0) {
params->binning_mode = LOG_BINNING;
flag2=_TRUE_;
}
if (strcmp(string1,"custom") == 0) {
params->binning_mode = CUSTOM_BINNING;
flag2=_TRUE_;
}
zelda_test(flag2 == _FALSE_,
"could not identify the requested separation binning, set 'binning_mode' to a value between the following: lin, log, custom");
}
// If the user did not provide a custom binning, then we read the number
// of separation bins from the parameters file.
if (params->binning_mode != CUSTOM_BINNING) {
zelda_read_int("n_separation_bins",params->n_separation_bins);
}
// It the user selected to provide a custom binning, read it from the 'custom_bin_edges'
// and 'custom_bin_midpoints' fields.
else {
// We read the edges of the bins and 'n_separation_bins' from the field 'custom_bin_edges'
parser_read_list_of_doubles(
pfc,
"custom_bin_edges",
&entries_read,
&(params->r_edges),
&flag2,
errmsg);
// Check that the user provided at least two bin edges
zelda_test((entries_read<2) || (flag2 == _FALSE_), "the 'custom_bin_edges' field should have at least two entries.");
// Define n_separation_bins, r_min, r_max
params->n_separation_bins = entries_read-1;
params->r_min = params->r_edges[0];
params->r_max = params->r_edges[params->n_separation_bins];
// Check that the bins are sorted in increasing order
int i_bin;
for (i_bin=0; i_bin<params->n_separation_bins; ++i_bin)
zelda_test(params->r_edges[i_bin] > params->r_edges[i_bin+1],
"please ensure that the field 'custom_bin_edges' is a comma separated list sorted in increasing order");
// Read the midpoints
parser_read_list_of_doubles(
pfc,
"custom_bin_midpoints",
&entries_read,
&(params->r_midpoints),
&flag2,
errmsg);
// If no midpoints are specified, compute them linearly from the r_edges array.
if (flag2 == _FALSE_) {
free(params->r_midpoints);
zelda_alloc(params->r_midpoints, params->n_separation_bins*sizeof(double));
for (i_bin=0; i_bin<params->n_separation_bins; ++i_bin)
params->r_midpoints[i_bin] = 0.5*(params->r_edges[i_bin+1] + params->r_edges[i_bin]);
}
// If the midpoints are specified, check that they are actually midpoints.
else if (entries_read==params->n_separation_bins) {
for (i_bin=0; i_bin<params->n_separation_bins; ++i_bin) {
double r = params->r_midpoints[i_bin];
zelda_test( (r >= params->r_edges[i_bin+1]) || (r <= params->r_edges[i_bin]),
"The midpoints you specified in 'custom_bin_midpoints' are not in the correct range wrt 'custom_bin_edges'","");
}
}
else {
ERRORPRINT("Please make sure that 'custom_bin_midpoints' is a comma separated list with one element less than 'custom_bin_edges'.\n","");
return _FAILURE_;
}
} // End of if (CUSTOM_BINNING)
// ======================
// = Intermediate files =
// ======================
zelda_call(parser_read_string(pfc,
"store_blocks_results",
&(string1),
&(flag1),
errmsg));
if ((flag1 == _TRUE_) && ((strstr(string1,"y") != NULL) || (strstr(string1,"Y") != NULL) || atoi(string1) > 0))
params->store_blocks_results = 1;
// Output format for blocks' results
zelda_read_string("output_format", params->output_format);
// =======================
// = Isolation criterion =
// =======================
// If r_isolation is not specified in the parameters file,
// just take it to be equal to r_max. THIS MUST BE BELOW zelda_read_double(R_MAX)!
zelda_call(parser_read_double(pfc,"r_isolation",¶m1,&flag1,errmsg));
if (flag1 == _FALSE_)
params->r_isolation = params->r_max;
else
params->r_isolation = param1;
zelda_read_int("n_neighbours_max",params->n_neighbours_max);
// ================
// = Edge effects =
// ================
zelda_read_double("side_of_box", params->side_of_box);
zelda_call(parser_read_string(pfc,
"remove_galaxies_on_the_edges",
&(string1),
&(flag1),
errmsg));
if ((flag1 == _TRUE_) && ((strstr(string1,"y") != NULL) || (strstr(string1,"Y") != NULL) || atoi(string1) > 0))
params->remove_galaxies_on_the_edges = _TRUE_;
else
params->remove_galaxies_on_the_edges = _FALSE_;
// ====================
// = Debug parameters =
// ====================
zelda_read_int("n_gals_per_block",params->n_gals_per_block);
zelda_read_int("verbose",params->verbose);
// =============================
// = Dump parameters to a file =
// =============================
zelda_call(parser_read_string(pfc,"write parameters",&string1,&flag1,errmsg));
if ((flag1 == _TRUE_) && ((strstr(string1,"y") != NULL) || (strstr(string1,"Y") != NULL))) {
sprintf(param_output_name,"%s%s",params->root,"parameters.ini");
sprintf(param_unused_name,"%s%s",params->root,"unused_parameters");
zelda_open(param_output,param_output_name,"w");
zelda_open(param_unused,param_unused_name,"w");
fprintf(param_output,"# List of input/precision parameters actually read\n");
fprintf(param_output,"# (all other parameters set to default values)\n");
fprintf(param_output,"#\n");
fprintf(param_output,"# This file, written by Zelda, can be used as the input file\n");
fprintf(param_output,"# of another run\n");
fprintf(param_output,"#\n");
fprintf(param_unused,"# List of input/precision parameters passed\n");
fprintf(param_unused,"# but not used (just for info)\n");
fprintf(param_unused,"#\n");
for (i=0; i<pfc->size; i++) {
if (pfc->read[i] == _TRUE_)
fprintf(param_output,"%s = %s\n",pfc->name[i],pfc->value[i]);
else
fprintf(param_unused,"%s = %s\n",pfc->name[i],pfc->value[i]);
}
fprintf(param_output,"#\n");
fclose(param_output);
fclose(param_unused);
}
return _SUCCESS_;
}
/**
* All default parameter values (for input parameters)
*/
int input_default_params(
params_struct * params,
data_struct * data
) {
params->modality = VINFALL;
strcpy(params->root, "./");
strcpy(params->input_format, "gal_blocks_%d_%d_%d.dat");
strcpy(params->results_filename, "results_font2008_z2.dat");
params->n_box_bins=10;
params->side_of_box=500.;
params->remove_galaxies_on_the_edges=_TRUE_;
params->n_gals_per_block=0;
params->store_blocks_results=_FALSE_;
strcpy(params->output_format, "vinfall_blocks_%d_%d_%d.dat");
params->verbose=0;
params->n_neighbours_max=1;
// Binning related parameters
params->r_min=0.;
params->r_max=50.; // r_max also determines the default value of r_isolation
params->n_separation_bins=10;
params->binning_mode=LIN_BINNING;
// Cuts-related parameters
params->n_cuts=0;
params->columns_to_cut=NULL;
params->cuts=NULL;
return _SUCCESS_;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "math.h"
#include "mpi.h" //MPI kutuphanesi
#define PI acos(-1)
#define N 500000000
#define MASTER 0
double f(double x) {
return 4 / (1 + x * x); // return 1 / (1 + pow(x, 2));
}
int main(void) {
int rank, size;
MPI_Init(NULL, NULL);
double t1, t2;
t1 = MPI_Wtime(); // start clock
MPI_Status status;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int i, chunkSize = N / size;
double toplam = 0.0;
double masterToplam = 0.0;
for (i = rank * chunkSize + 1; i <= (rank + 1) * chunkSize; i++)
toplam += f((double)i / (double)N);
printf("rank = %d --> toplam = %f\n", rank, toplam);
if (rank != MASTER)
MPI_Send(&toplam, 1, MPI_DOUBLE, MASTER, 777+rank, MPI_COMM_WORLD);
else {
for (i = 1; i < size; i++) {
MPI_Recv(&masterToplam, 1, MPI_DOUBLE, i, 777+i, MPI_COMM_WORLD, &status);
toplam += masterToplam;
}
printf("Appr. PI = %.16f\n", toplam / (double)N);
printf("Exact PI = %.16f\n", PI);
}
MPI_Barrier(MPI_COMM_WORLD);
t2 = MPI_Wtime(); // stop clock
printf("Elapsed time = %f sec.\n", t2 - t1);
MPI_Finalize();
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "binary_trees.h"
/**
* binary_tree_is_bst-function that checks if a binary
*tree is a valid Binary Search Treer
* of a binary tree of a node in a binary tree
*@tree: is a pointer to the root node of the tree to check
*Return: always success.
**/
int binary_tree_is_bst(const binary_tree_t *tree)
if (tree == NULL)
return (0);
if ((*tree).right == NULL || (*tree).left == NULL)
return (1);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sujilee <sujilee@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/31 14:37:43 by sujilee #+# #+# */
/* Updated: 2021/05/31 14:39:55 by sujilee ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/get_next_line.h"
int buf_check(char *buf)
{
while (*buf)
{
if (*buf == '\n')
return (1);
buf++;
}
return (0);
}
void ft_strdel(char **as)
{
if (as)
{
free(*as);
*as = 0;
}
return ;
}
int get_line(char **str, char **line)
{
int i;
char *temp;
i = 0;
while ((*str)[i] != '\n' && (*str)[i] != '\0')
i++;
if ((*str)[i] == '\n')
{
if (i == 0)
*line = ft_strdup("");
else
*line = ft_substr(*str, 0, i);
temp = ft_strdup(&(*str)[i + 1]);
free(*str);
*(str) = temp;
if ((*str)[0] == '\0')
ft_strdel(str);
}
else
{
*line = ft_strdup(*str);
ft_strdel(str);
return (0);
}
return (1);
}
int result(int len, int fd, char **str, char **line)
{
if (len < 0)
return (-1);
else if (len == 0 && str[fd] == 0)
{
ft_strdel(&str[fd]);
*line = ft_strdup("");
return (0);
}
else
return (get_line(&str[fd], line));
}
int get_next_line(int fd, char **line)
{
int len;
char *temp;
static char *str[OPEN_MAX];
char *buf;
if (fd < 0 || line == 0 || BUFFER_SIZE == 0 ||
!(buf = (char *)malloc(sizeof(char) * (BUFFER_SIZE + 1))))
return (-1);
while ((len = read(fd, buf, BUFFER_SIZE)) > 0)
{
buf[len] = '\0';
if (str[fd] == 0)
str[fd] = ft_strdup(buf);
else
{
temp = ft_strjoin(str[fd], buf);
free(str[fd]);
str[fd] = temp;
}
if (buf_check(buf))
break ;
}
free(buf);
buf = 0;
return (result(len, fd, str, line));
}
|
C
|
#include <stdio.h>
int main(void) {
int l,w,h;
scanf("%d%d%d",&l,&w,&h);
printf("%d",l*w*h);
return 0;
}
|
C
|
/**
* Descripción: Define las funciones y estrucutras utilizadas para space
*
* @file space.h
* @author Miguel Manzano
* @version 1.1
* @date 11-02-2018
* @copyright GNU Public License
* Comments:
*/
#ifndef SPACE_H
#define SPACE_H
#include "types.h"
#include "set.h"
typedef struct _Space Space;
#define MAX_SPACES 100
#define FIRST_SPACE 1
/* Name: space_create
* @brief Creamos un espacio mediante un puntero (newSpace) que apunta a id (parametro introducido de tipo long)
* @param Id: long id
* @return Space
*/
Space* space_create(Id id);
/* Name: space_destroy
* @brief Libera la memoria dinamica reservada para el espacio del paramentro introducido, devolviendo un OK (1)
* @param Space*: valor space
* @return STATUS
*/
STATUS space_destroy(Space* space);
/* Name: space_get_id
* @brief Devuelve el valor id del espacio introducido por parametro
* @param Space*: valor space
* @return Id
*/
Id space_get_id(Space* space);
/* Name: space_set_name
* @brief Esta funcion permite modificar el nombre introducido por parametro, devolviendo un OK tras la modificacion
* @param Space*: valor space
* @param char*: valor name
* @return STATUS
*/
STATUS space_set_name(Space* space, char* name);
/* Name: space_get_name
* @brief Devuelve el valor name del espacio introducido por parametro
* @param Space*: valor space
* @return char
*/
const char* space_get_name(Space* space);
/* Name: space_set_north
* @brief Esta funcion permite modificar la direccion norte a la introducida mediante el parametro id, devolviendo un OK tras la modificacion
* @param Space*: valor space
* @param Id: long id
* @return STATUS
*/
STATUS space_set_north(Space* space, Id id);
/* Name: space_get_north
* @brief Devuelve el valor de direccion norte del espacio introducido por parametro
* @param Space*: valor space
* @return Id
*/
Id space_get_north(Space* space);
/* Name: space_set_south
* @brief Esta funcion permite modificar la direccion sur a la introducida mediante el parametro id, devolviendo un OK tras la modificacion
* @param Space*: valor space
* @param Id: long id
* @return STATUS
*/
STATUS space_set_south(Space* space, Id id);
/* Name: space_get_south
* @brief Devuelve el valor de direccion sur del espacio introducido por parametro
* @param Space*: valor space
* @return Id
*/
Id space_get_south(Space* space);
/* Name: space_set_east
* @brief Esta funcion permite modificar la direccion este a la introducida mediante el parametro id, devolviendo un OK tras la modificacion
* @param Space*: valor space
* @param Id: long id
* @return STATUS
*/
STATUS space_set_east(Space* space, Id id);
/* Name: space_get_east
* @brief Devuelve el valor de direccion este del espacio introducido por parametro
* @param Space*: valor space
* @return Id
*/
Id space_get_east(Space* space);
/* Name: space_set_west
* @brief Esta funcion permite modificar la direccion oeste a la introducida mediante el parametro id, devolviendo un OK tras la modificacion
* @param Space*: valor space
* @param Id: long id
* @return STATUS
*/
STATUS space_set_west(Space* space, Id id);
/* Name: space_get_west
* @brief Devuelve el valor de direccion oeste del espacio introducido por parametro
* @param Space*: valor space
* @return Id
*/
Id space_get_west(Space* space);
/* Name: space_set_object
* @brief Esta funcion permite modificar el valor object por el valor introducido mediante el parametro value (tipo BOOL) , devolviendo un OK tras la modificacion
* @param Space*: valor space
* @param BOOL: value
* @return STATUS
*/
STATUS space_set_object(Space* space, Id value);
/* Name: space_get_object
* @brief Devuelve el valor object del espacio introducido por parametro
* @param Space*: valor space
* @return BOOL
*/
Conjunto* space_get_object(Space* space);
/* Name: space_print
* @brief Imprime la información introducida por el usuario
* @param Space*: valor space
* @return STATUS
*/
STATUS space_print(Space* space);
#endif
|
C
|
#include<stdio.h>
#include<math.h>
int main()
{
double x, y, angle, pi, radian;
pi = 3.1415926;
printf("x, y, angle=");
scanf("%lf%lf%lf", &x, &y, &angle);
radian = pi * angle / 180.0;
printf("%lf\n", 0.50 * x * y * sin(radian));
}
|
C
|
// A. Matriz serpentina
#define MAX 20
int main(){
int m[MAX][MAX];
int i=0,j=0,k=1,N,M,t, pos;
scanf("%d%d", &N, &M);
t=N*M;
for (i=0;i<N; i++)
for (j=0; j<M; j++){
pos = ((i+1)%2==0)?M-j-1:j;
m[i][pos]=k++;
}
for (i=0;i<N; i++){
for (j=0; j<M; j++)
printf("%d ",m[i][j]);
printf ("\n");
}
return 0;
}
|
C
|
/* vim: set sw=4 ts=4:
* Author: Liu DongMiao <liudongmiao@gmail.com>
* Created : Tue 14 Aug 2012 09:12:11 AM CST
* Modified : Tue 14 Aug 2012 10:42:20 AM CST
*/
/*
* Add a field-searching capability, so sorting may be done on fields within
* lines, each field sorted according to an independent set of options. (The
* index for this book was sorted with ``-df'' for the index category and ``-n''
* for the page numbers.)
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#ifdef _STDIO_H
#define getline getline2
#endif
#ifdef _STDLIB_H
#define qsort qsort2
#endif
#define MAXLINES 5000 /* max #lines to be sorted */
#define MAXLEN 1000 /* max length of any input line */
int getline(char *, int);
char *lineptr[MAXLINES]; /* pointers to text lines */
int readlines(char *lineptr[], int nlines);
void writelines(char *lineptr[], int nlines);
void qsort(void *lineptr[], int left, int right, int (*comp)(void *, void *));
int numcmp(const char *, const char *);
int dictcmp(const char *s1, const char *s2, int igncase);
int fieldcmp(const char *s1, const char *s2);
#define REVERSE 0x1
#define NUMERIC 0x2
#define IGNCASE 0x4
#define DICTION 0x8
#define MAXFIELD 10
int fields[MAXFIELD] = {-1};
/* sort input lines */
int main(int argc, char **argv)
{
int nlines; /* number of input lines read */
int *field = fields;
char lineptr2[MAXLINES][MAXLEN];
nlines = MAXLINES;
while (nlines-- > 0) {
lineptr[nlines] = lineptr2[nlines];
}
while (field - fields < MAXFIELD && *++argv) {
if (**argv == '-') {
*field = 0;
while (*++*argv) {
switch (**argv) {
case 'r':
*field |= REVERSE;
break;
case 'n':
*field |= NUMERIC;
break;
case 'f':
*field |= IGNCASE;
break;
case 'd':
*field |= DICTION;
break;
}
}
if (*field & NUMERIC) {
printf("options nd is incompatible, use n\n");
}
}
field++;
*field = -1;
}
if ((nlines = readlines(lineptr, MAXLINES)) >= 0) {
qsort((void **)lineptr, 0, nlines - 1, (int (*)(void *, void *))fieldcmp);
writelines(lineptr, nlines);
return 0;
} else {
printf("error: input too big to sort\n");
return 1;
}
}
/* readlines: read input lines */
int readlines(char *lineptr[], int maxlines)
{
int len, nlines;
nlines = 0;
while (nlines < maxlines && (len = getline(lineptr[nlines], MAXLEN)) > 0) {
lineptr[nlines++][len - 1] = '\0';
}
return nlines;
}
/* writelines: write output lines */
void writelines(char *lineptr[], int nlines)
{
while (nlines-- > 0)
printf("%s\n", *lineptr++);
}
/* qsort: sort v[left]...v[right] into increasing order */
void qsort(void *v[], int left, int right,
int (*comp)(void *, void*))
{
int i, last;
void swap(void *v[], int i, int j);
if (left >= right) /* do nothing if array contains */
return; /* fewer than two elements */
swap(v, left, (left + right) / 2);
last = left;
for (i = left+1; i <= right; i++)
if ((*comp)(v[i], v[left]) < 0)
swap(v, ++last, i);
swap(v, left, last);
qsort(v, left, last - 1, comp);
qsort(v, last + 1, right, comp);
}
/* swap: interchange v[i] and v[j] */
void swap(void *v[], int i, int j)
{
void *temp;
temp = v[i];
v[i] = v[j];
v[j] = temp;
}
/* nummcp: compare s1 and s2 numerically */
int numcmp(const char *s1, const char *s2)
{
double v1, v2;
v1 = atof(s1);
v2 = atof(s2);
if (v1 < v2)
return -1;
else if (v1 > v2)
return 1;
else
return 0;
}
/* dictcmp */
int dictcmp(const char *s1, const char *s2, int igncase)
{
igncase = (igncase) ? 0x20 : 0;
while (1) {
while (*s1 && !isalnum(*s1) && !isblank(*s1))
s1++;
while (*s2 && !isalnum(*s2) && !isblank(*s2))
s2++;
if (!*s1 || !*s2) {
break;
}
if ((*s1 | igncase) < (*s2 | igncase))
return -1;
else if ((*s1 | igncase) > (*s2 | igncase))
return 1;
s1++, s2++;
}
if ((*s1 | igncase) < (*s2 | igncase))
return -1;
else if ((*s1 | igncase) > (*s2 | igncase))
return 1;
else
return 0;
}
#define SETFIELD(x) do {\
while (*x && !isblank(*x)) \
x++;\
if (*x != '\0') {\
*x = '\0';\
x++;\
}\
} while (0)
int fieldcmp(const char *s1, const char *s2)
{
int result = 0;
int *field = fields;
char *s1dup, *s2dup;
char *current1, *next1;
char *current2, *next2;
s1dup = strdup(s1), s2dup = strdup(s2);
current1 = s1dup, current2 = s2dup;
while (*field != -1 && *current1 && *current2) {
next1 = current1, next2 = current2;
SETFIELD(next1);
SETFIELD(next2);
if (*field & NUMERIC) {
result = numcmp(current1, current2);
} else if (*field & DICTION) {
result = dictcmp(current1, current2, *field & IGNCASE);
} else if (*field & IGNCASE) {
result = strcasecmp(current1, current2);
} else {
result = strcmp(current1, current2);
}
if (result) {
result = (*field & REVERSE) ? -result : result;
break;
}
current1 = next1, current2 = next2;
field++;
}
if (!result) {
result = strcmp(current1, current2);
}
free(s1dup), free(s2dup);
return result;
}
int getline(char *s, int lim)
{
int c;
char *x = s;
while (lim-- > 0 && (c = getchar()) != EOF && c != '\n') {
*x++ = c;
}
if (c == '\n') {
*x++ = c;
}
*x = '\0';
return (x - s);
}
|
C
|
/*
============================================================================
Programmname: DameHilfsfunktionenSteinSetzen.c
Autor : Andreas Danek, Daniel Janen
Datum : 18.03.2009
Thema : Projektarbeit
Version : 1.0
Programmschnittstelle: Funktionen
============================================================================
*/
/*
============================================================================
Prprozessoranweisungen
============================================================================
*/
#include "Funktionen.h"
/*
========================================================================
Funktion DameAusgewaehlterSteinVorhanden()
@aufruf: DameSteinSetzen()
@beschreibung: berprft, ob es den ausgewhlten Stein auf dem Spielfeld
gibt
@param ixKoordinate: Die x-Koordinate des gewhlten Steines
@param iyKoordinate: Die y-Koordinate des gewhlten Steines
@return OK: der gewhlte Stein ist vorhanden
@return NOTOK: der gewhlte Stein ist nicht vorhanden
========================================================================
*/
int DameAusgewaehlterSteinVorhanden(int ixKoordinate,int iyKoordinate)
{
if ((cSpielFeld[ixKoordinate][iyKoordinate] == cSpielsteine[0]) ||
(cSpielFeld[ixKoordinate][iyKoordinate] == cSpielsteine[2]))
{
return OK;
}
ZeichneFeld(8, 8);
color(1);
printf("\nFehler: W\204hlen Sie einen vorhandenen Stein aus\n");
color(0);
return NOTOK;
}
/*
========================================================================
Funktion DameBewegeStein()
@aufruf: DameSteinSetzen()
@beschreibung: bewege stein von koordinaten nach ziel
@param ixZiel: gewhlte x-Zielkoordinate
@param iyZiel: gewhlte y-Zielkoordinate
@param ixKoordinate: Die x-Koordinate des gewhlten Steines
@param iyKoordinate: Die y-Koordinate des gewhlten Steines
@return OK: der Stein wurde bewegt
========================================================================
*/
int DameBewegeStein(int ixKoordinate,int iyKoordinate,int ixZiel,int iyZiel)
{
if (iyZiel > 0 && iyZiel < 7)
{
cSpielFeld[ixZiel][iyZiel] = cSpielFeld[ixKoordinate][iyKoordinate];
}
else
{
cSpielFeld[ixZiel][iyZiel] = cSpielsteine[2];
}
cSpielFeld[ixKoordinate][iyKoordinate] = SCHWARZ;
return OK;
}
/*
========================================================================
Funktion DameKannSteinBewegtWerden(int ixKoordinate,int iyKoordinate,
int iRueckgabe)
@aufruf: DameSteinSetzen()
@beschreibung: berprft ob der ausgewhlte Stein berhaupt bewegt
werden kann
@param ixKoordinate: Die x-Koordinate des gewhlten Steines
@param iyKoordinate: Die y-Koordinate des gewhlten Steines
@param iRueckgabe: Rueckgabewert, welcher verndert wird
@return iRueckgabe: gibt an ob der Stein bewegt werden kann (0) oder
nicht (1)
========================================================================
*/
int DameKannSteinBewegtWerden(int ixKoordinate,int iyKoordinate, int iRueckgabe)
{
if (ixKoordinate == 0)
{
iRueckgabe = ZielfeldLeer(ixKoordinate+1,iyKoordinate+iSpieler);
if (cSpielFeld[ixKoordinate][iyKoordinate] == cSpielsteine[2])
{
iRueckgabe *= ZielfeldLeer(ixKoordinate+1,iyKoordinate-iSpieler);
}
return iRueckgabe;
}
if (ixKoordinate == 7)
{
iRueckgabe = ZielfeldLeer(ixKoordinate-1,iyKoordinate+iSpieler);
if (cSpielFeld[ixKoordinate][iyKoordinate] == cSpielsteine[2])
{
iRueckgabe *= ZielfeldLeer(ixKoordinate-1,iyKoordinate-iSpieler);
}
return iRueckgabe;
}
if (7 > ixKoordinate > 0)
{
iRueckgabe = ZielfeldLeer(ixKoordinate+1,iyKoordinate+iSpieler);
iRueckgabe *= ZielfeldLeer(ixKoordinate-1,iyKoordinate+iSpieler);
if (cSpielFeld[ixKoordinate][iyKoordinate] == cSpielsteine[2])
{
iRueckgabe *= ZielfeldLeer(ixKoordinate+1,iyKoordinate-iSpieler);
iRueckgabe *= ZielfeldLeer(ixKoordinate-1,iyKoordinate-iSpieler);
}
return iRueckgabe;
}
ZeichneFeld(8, 8);
color(1);
printf("\nFehler: W\204hlen Sie einen bewegbaren Stein aus\n");
color(0);
return NOTOK;
}
/*
========================================================================
int DameBelegeIyzielStein(int iyKoordinate)
@aufruf: DameSteinSetzen()
@beschreibung: Belegt die iyZiel Koordinate fr einen Stein
@param iyKoordinate: Die y-Koordinate des gewhlten Steines
@return iyZiel: y-Zielkoordinate, nach wo gesetzt werden soll
========================================================================
*/
int DameBelegeZielStein(int *ixZielReturn, int *iyZielReturn, int ixKoordinate, int iyKoordinate)
{
int ixZiel, iyZiel;
ZeichneFeld(8,8);
do
{
printf("\nWohin soll der Stein bewegt werden?\n");
PositionEingeben(&ixZiel, &iyZiel, 8, 8, 0);
if ((iyZiel != iyKoordinate+iSpieler) || ((ixZiel != ixKoordinate+1) && (ixZiel != ixKoordinate-1)))
{
ZeichneFeld(8,8);
printf("\nW\204hlen Sie eine korrekte Zielposition aus\n");
}
}while (((ixZiel != ixKoordinate+1) && (ixZiel != ixKoordinate-1)) || (iyZiel != iyKoordinate+iSpieler));
*ixZielReturn = ixZiel;
*iyZielReturn = iyZiel;
return OK;
}
/*
========================================================================
int DameBelegeIyzielDame(int iyKoordinate)
@aufruf: DameSteinSetzen()
@beschreibung: Belegt die iyZiel Koordinate fr eine Dame
@param iyKoordinate: Die y-Koordinate des gewhlten Steines
@return iyZiel: y-Zielkoordinate, nach wo gesetzt werden soll
========================================================================
*/
int DameBelegeZielDame(int *ixZielReturn, int *iyZielReturn, int ixKoordinate, int iyKoordinate)
{
int ixZiel, iyZiel;
ZeichneFeld(8,8);
do
{
PositionEingeben(&ixZiel, &iyZiel, 8, 8, 0);
if (((iyZiel != iyKoordinate+iSpieler) && (iyZiel != iyKoordinate-iSpieler)) ||
((ixZiel != ixKoordinate+1) && (ixZiel != ixKoordinate-1)))
{
ZeichneFeld(8,8);
printf("\nW\204hlen Sie eine korrekte Zielposition aus\n");
}
}while (((ixZiel != ixKoordinate+1) && (ixZiel != ixKoordinate-1)) ||
((iyZiel != iyKoordinate+iSpieler) && (iyZiel != iyKoordinate-iSpieler)));
*ixZielReturn = ixZiel;
*iyZielReturn = iyZiel;
return OK;
}
|
C
|
#include <stdio.h>
int main() {
int i,j;
char c[2]="01";
for(i=1;i<=6;++i)
{
for(j=0;j<i;++j)
{
printf("%s",c);
}
printf("\n");
}
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int a[10]={1,2,3,4,5,6,7,8,9,10};
int i,sum=0;
for(i=0;i<9;i++)
{
sum=sum+a[i];
}
printf("sum of elements is %d",sum);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <assert.h>
#include <getopt.h>
#include "getline.h"
uint8_t codelen(uint8_t s);
uint8_t shortnote(uint8_t s);
uint8_t longnote(uint8_t s);
void decode(void);
void encode(void);
void printcode(uint8_t c);
void usage(FILE *out);
int reverse = 0;
char *infile = NULL;
FILE *in = NULL;
char *outfile = NULL;
FILE *out = NULL;
unsigned char morse[] = {
[0xa0] = 'a', // 1010 0000
[0x78] = 'b', // 0111 1000
[0x58] = 'c', // 0101 1000
[0x70] = 'd', // 0111 0000
[0xc0] = 'e', // 1100 0000
[0xd8] = 'f', // 1101 1000
[0x30] = 'g', // 0011 0000
[0xf8] = 'h', // 1111 1000
[0xe0] = 'i', // 1110 0000
[0x88] = 'j', // 1000 1000
[0x50] = 'k', // 0101 0000
[0xb8] = 'l', // 1011 1000
[0x20] = 'm', // 0010 0000
[0x60] = 'n', // 0110 0000
[0x10] = 'o', // 0001 0000
[0x98] = 'p', // 1001 1000
[0x28] = 'q', // 0010 1000
[0xb0] = 'r', // 1011 0000
[0xf0] = 's', // 1111 0000
[0x40] = 't', // 0100 0000
[0xd0] = 'u', // 1101 0000
[0xe8] = 'v', // 1110 1000
[0x90] = 'w', // 1001 0000
[0x68] = 'x', // 0110 1000
[0x48] = 'y', // 0100 1000
[0x38] = 'z', // 0011 1000
[0x84] = '.', // 1000 0100
[0xc4] = ',', // 1100 0100
[0xe4] = '?', // 1110 0100
};
uint8_t codelen(uint8_t s)
{
uint8_t i, hit;
hit = 0;
for(i = 0; i < 8; i++) {
if((s << i) & 0xFF) {
hit = i;
}
}
return hit;
}
uint8_t shortnote(uint8_t s)
{
uint8_t mask;
uint8_t len;
len = codelen(s);
mask = 0xFF << (8 - len);
s = s & mask;
s |= 0xc0 >> len;
return s;
}
uint8_t longnote(uint8_t s)
{
uint8_t mask;
uint8_t len;
len = codelen(s);
mask = 0xFF << (8 - len);
s = s & mask;
s |= 0x40 >> len;
return s;
}
void decode(void)
{
char *line = NULL;
size_t linecap = 0;
ssize_t len;
int i;
uint8_t s = 0x80;
char c;
while((len = int_getline(&line, &linecap, in)) > 0) {
s = 0x80;
for(i = 0; i < len; i++) {
c = line[i];
switch(c) {
case '.':
s = shortnote(s);
break;
case '-':
s = longnote(s);
break;
case '/':
fputc(' ', out);
break;
default:
if(s != 0x80) {
if(morse[s])
fputc(morse[s], out);
else
fputc('?', out);
}
s = 0x80;
break;
}
}
fputc('\n', out);
}
free(line);
}
void encode(void)
{
char *line = NULL;
size_t linelen = 0;
ssize_t len;
int i, j;
uint8_t c;
while((len = int_getline(&line, &linelen, in)) > 0) {
for(i = 0; i < len; i++) {
c = line[i];
if(c >= 'A' && c <= 'Z')
c -= 'A' - 'a';
switch(line[i]) {
case ' ':
fprintf(out, "/ ");
break;
default:
for(j = 0; j < sizeof(morse); j++)
if(morse[j] == c) {
printcode(j);
break;
}
}
}
fputc('\n', out);
}
free(line);
}
void printcode(uint8_t c)
{
int i;
int len;
len = codelen(c);
for(i = 0; i < len; i++) {
if(0x80 & (c << i))
fputc('.', out);
else
fputc('-', out);
}
fputc(' ', out);
}
void usage(FILE *out)
{
fprintf(out, "usage: morse [-r]\n");
}
void parseargs(int argc, char *argv[])
{
int c;
static struct option longopts[] = {
{ "help", no_argument, NULL, 'h' },
{ "reverse", no_argument, NULL, 'r' },
{ "out", required_argument, NULL, 'o' },
{ 0, 0, 0, 0 },
};
while((c = getopt_long(argc, argv, "hro:", longopts, NULL)) != -1)
switch(c) {
case 'o':
outfile = optarg;
break;
case 'r':
reverse = 1;
break;
case 'h':
usage(stdout);
exit(EXIT_SUCCESS);
case '?':
usage(stderr);
exit(EXIT_FAILURE);
}
switch(argc - optind) {
case 0:
break;
case 1:
infile = argv[optind];
break;
default:
usage(stderr);
exit(EXIT_FAILURE);
}
}
void openfiles(void)
{
if(infile != NULL) {
in = fopen(infile, "r");
if(in == NULL) {
perror("fopen");
exit(EXIT_FAILURE);
}
} else
in = stdin;
if(outfile != NULL) {
out = fopen(outfile, "w");
if(out == NULL) {
perror("fopen");
exit(EXIT_FAILURE);
}
} else
out = stdout;
}
int main(int argc, char *argv[])
{
parseargs(argc, argv);
openfiles();
if(reverse)
decode();
else
encode();
exit(EXIT_SUCCESS);
}
|
C
|
//C Primer Plusp318 10.13.13
#include <stdio.h>
#define ROWS 3
#define COLS 5
void scan_arr(double arr[][COLS]);
double row_average(double row[]);
double all_average(double arr[][COLS]);
double max_element(double arr[][COLS]);
int main(void)
{
double arr[ROWS][COLS];
scan_arr(arr);
int row;
for (row = 0; row < ROWS; row++)
{
printf("b.%5.2f\n", row_average(arr[row]));
}
printf("\nc.%5.2f\n", all_average(arr));
printf("\nd.%5.2f\n", max_element(arr));
return 0;
}
void scan_arr(double arr[][COLS])
{
int i, j;
for (i = 0; i < ROWS; i++)
{
for(j = 0; j < COLS; j++)
{
scanf("%lf", &arr[i][j]);
}
getchar();
}
}
double row_average(double row[])
{
int sum = 0;
int i;
for (i = 0; i < COLS; i++)
{
sum += row[i];
}
return (sum / COLS);
}
double all_average(double arr[][COLS])
{
int sum = 0;
int i, j;
for (i = 0; i < ROWS; i++)
{
for (j = 0; j < COLS; j++)
{
sum += arr[i][j];
}
}
return (sum / (ROWS * COLS));
}
double max_element(double arr[][COLS])
{
int m = arr[0][0];
int i, j;
for (i = 0; i < ROWS; i++)
{
for (j = 0; j < COLS; j++)
{
if (arr[i][j] > m)
{
m = arr[i][j];
}
}
}
return m;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[]){
int arg;
for(arg=0;arg<argc;arg++){
if(argv[arg][0]=='-'){
if(argv[arg][1]=='n')
printf("option = %s value = %s\n","n",argv[arg]+2);
else
printf("option = %s \n",argv[arg]+1);
}
else
printf("argument = %d : %s\n",arg,argv[arg]);
}
exit(0);
}
|
C
|
// Problem #17 --- Number of letters written numbers one, two..one thousand
#include <stdio.h>
int main() {
int ones_column[] = {0, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8, 8, 7, 7, 9, 8, 8};
int tens_column[] = {0, 0, 6, 6, 5, 5, 5, 7, 6, 6};
int total = 8984; // 891*10 + 9*7 + 11 is "hundred and" and "hundred" and "one thousand"
int remainder = 0;
for (int i = 1; i < 100; i++) {
if ( (remainder = (i % 100)) < 20 ) {
total += ones_column[remainder];
} else {
total += tens_column[(remainder - (remainder = i % 10)) / 10];
total += ones_column[remainder];
}
}
for (int i = 100; i < 1000; i++) {
if ( (remainder = (i % 100)) < 20 ) {
total += ones_column[remainder];
total += ones_column[(i - remainder) / 100];
} else {
total += ones_column[(i - remainder) / 100];
total += tens_column[(remainder - (remainder = i % 10)) / 10];
total += ones_column[remainder];
}
}
printf("%d\n", total);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.