language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "wm_config.h"
#include "wm_regs.h"
#include <reent.h>
#include <string.h>
#include <stdarg.h>
int sendchar(int ch)
{
#if WM_CONFIG_DEBUG_UART1
tls_reg_write32(HR_UART1_INT_MASK, 0x3);
if(ch == '\n')
{
while (tls_reg_read32(HR_UART1_FIFO_STATUS) & 0x3F);
tls_reg_write32(HR_UART1_TX_WIN, '\r');
}
while(tls_reg_read32(HR_UART1_FIFO_STATUS) & 0x3F);
tls_reg_write32(HR_UART1_TX_WIN, (char)ch);
tls_reg_write32(HR_UART1_INT_MASK, 0x0);
#else
tls_reg_write32(HR_UART0_INT_MASK, 0x3);
if(ch == '\n')
{
while (tls_reg_read32(HR_UART0_FIFO_STATUS) & 0x3F);
tls_reg_write32(HR_UART0_TX_WIN, '\r');
}
while(tls_reg_read32(HR_UART0_FIFO_STATUS) & 0x3F);
tls_reg_write32(HR_UART0_TX_WIN, (char)ch);
tls_reg_write32(HR_UART0_INT_MASK, 0x0);
#endif
return ch;
}
//function: תַ
//paramter:
//str : ת֮ڴbuffer
//num : Ҫת
//base : ʮƣʮ
//width :
//opflag : bit
#define P_ALIGN_BIT (0x01<<0) // bit=1 bit=0Ҷ
#define P_FILL_BIT (0x01<<1) //bit = 1'0'' '
#define P_BIG_BIT (0x01<<2) //bit=1дСд
int Int2Str(char *str,int num,char base,char width,int opflag)
{
char temp;
int len = 0;
signed char k = 0;
char *str_bk;
signed char k_bk;
if(num <0)
{
num = -num;
*str='-';
str++;
len++;
}
if(0 == num)
{
*str = '0';
str ++;
k ++;
}
while(num)
{
temp= num%base;
if(temp > 9) // insert hexdecimal--ABCDEF--
{
temp-=10;
if(opflag & P_BIG_BIT)
*str = temp + 'A';
else
*str = temp + 'a';
}
else
{
*str = temp + '0';
}
num=num/base;
str++;
k++;
}
if(opflag&P_ALIGN_BIT) //
{
str_bk = str;
k_bk = k; //ȱָͳȣ֮
str --;
k --;
while(k>0)
{
temp = *str;
*str = *(str-k);
*(str-k) = temp;
str--;
k-=2;
}
k = k_bk;
str = str_bk;
}
//ȵ' '
while(width>k)
{
if(opflag&P_FILL_BIT)
{
*str++ ='0';
}
else
{
*str++ =' ';
}
k++;
}
len=len+k;
*str-- = '\0';
k--;
if(0 == (opflag&P_ALIGN_BIT)) //Ҷ
{
//
while(k>0)
{
temp = *str;
*str = *(str-k);
*(str-k) = temp;
str--;
k-=2;
}
}
return len;
}
static void Mac2Str(unsigned char *inchar, char *outtxt)
{
unsigned char hbit,lbit;
unsigned int i;
for(i = 0; i < 6; i++)
{
hbit = (*(inchar + i) & 0xf0) >> 4;
lbit = *(inchar + i ) & 0x0f;
if (hbit > 9)
outtxt[3 * i] = 'A' + hbit - 10;
else
outtxt[3 * i]= '0' + hbit;
if (lbit > 9)
outtxt[3 * i + 1] = 'A' + lbit - 10;
else
outtxt[3 * i + 1] = '0' + lbit;
outtxt[3 * i + 2] = '-';
}
outtxt[3 * (i - 1) + 2] = 0;
return;
}
int wm_vprintf(const char *fmt, va_list arg_ptr)
{
unsigned char width=0; //
unsigned int len; //ݿ
char *fp = (char *)fmt;
//va_list arg_ptr;
char *pval;
int opflag = 0;
char store[20];
char c;
int i;
char* str;
//va_start(arg_ptr, fmt); //arg_ptr ָһ
while (*fp !='\0')
{
c = *fp++;
if (c != '%')
{
sendchar(c);
}
else
{
width = 0; //ȡݿ
opflag = 0;
if('-' == *fp)
{
opflag |= P_ALIGN_BIT;//
fp ++;
}
if('0' == *fp) //ǰ油
{
opflag |= P_FILL_BIT; //
fp ++;
}
while(*fp>='0'&&*fp<='9')
{
width = width * 10 + (*fp) - '0';
fp++;
}
if('.' == *fp) //ʱûã
{
fp ++;
while(*fp>='0'&&*fp<='9')
{
fp++;
}
}
while('l' == *fp || 'h' == *fp)
{
fp ++;
}
switch (*fp)
{
case 'c':
case 'C':
c = (char)va_arg(arg_ptr, int);
sendchar(c);
break;
case 'd':
case 'i':
case 'u':
i = va_arg(arg_ptr, int);
str = store;
Int2Str(store,i,10,width,opflag);
while( *str != '\0') sendchar(*str++);
break;
case 'x':
case 'X':
i = va_arg(arg_ptr, int);
str = store;
if('X' == *fp)
{
opflag |= P_BIG_BIT;
}
Int2Str(store,i,16,width,opflag);
while( *str != '\0') sendchar(*str++);
break;
case 'o':
i = va_arg(arg_ptr, int);
str = store;
Int2Str(store,i,8,width,opflag);
while( *str != '\0') sendchar(*str++);
break;
case 's':
case 'S':
pval=va_arg(arg_ptr,char*);
len = strlen(pval);
if((width > len) && (0 == (opflag&P_ALIGN_BIT))) //Ҷ
{
for(i = 0;i < (width - len);i ++) //߲ո
{
sendchar(' ');
}
}
for(i=0;i < len;i++)
{
sendchar(pval[i]);
}
if((width > len) && (opflag&P_ALIGN_BIT)) //
{
for(i = 0;i < (width - len);i ++) //ұ߲ո
{
sendchar(' ');
}
}
break;
case 'M':
pval=va_arg(arg_ptr,char*);
len = 17;/* xx-xx-xx-xx-xx-xx */
if((width > len) && (0 == (opflag&P_ALIGN_BIT))) //Ҷ
{
for(i = 0;i < (width - len);i ++) //߲ո
{
sendchar(' ');
}
}
Mac2Str((unsigned char *)pval, store);/* mac length */
str = store;
while( *str != '\0') sendchar(*str++);
if((width > len) && (opflag&P_ALIGN_BIT)) //
{
for(i = 0;i < (width - len);i ++) //ұ߲ո
{
sendchar(' ');
}
}
break;
case '%':
sendchar('%');
break;
default:
break;
}
fp++;
}
}
//va_end(arg_ptr);
return 0;
}
int wm_printf(const char *fmt,...)
{
va_list ap;
va_start(ap, fmt);
wm_vprintf(fmt,ap);
va_end(ap);
return 0;
}
int wm_sprintf(char *str, const char *fmt,...)
{
unsigned int num = 0; //صij
unsigned char width=0; //
unsigned int len; //ݿ
char *fp = (char *)fmt;
va_list arg_ptr;
int arg_num;
char *pval;
int i;
int opflag = 0;
char c;
va_start(arg_ptr, fmt); //arg_ptr ָһ
while (*fp !='\0')
{
c = *fp++;
if (c != '%')
{
*str++ = c;
num++;
}
else
{
width = 0; //ȡҪλ
opflag = 0;
if('-' == *fp)
{
opflag |= P_ALIGN_BIT;//
fp ++;
}
if('0' == *fp) //ǰ油
{
opflag |= P_FILL_BIT; //
fp ++;
}
while(*fp>='0'&&*fp<='9')
{
width = width * 10 + (*fp) - '0';
fp++;
}
if('.' == *fp) //ʱûã
{
fp ++;
while(*fp>='0'&&*fp<='9')
{
fp++;
}
}
while('l' == *fp)
{
fp ++;
}
switch (*fp)
{
case 'c':
case 'C':
arg_num = va_arg(arg_ptr, int);
*str++ = (char)arg_num;
num ++;
break;
case 'd':
case 'i':
case 'u':
arg_num = va_arg(arg_ptr, int);
len = Int2Str(str,arg_num,10,width,opflag);
str+=len;num+=len;
break;
case 'x':
case 'X':
if('X' == *fp)
{
opflag |= P_BIG_BIT;
}
arg_num = va_arg(arg_ptr, int);
len = Int2Str(str,arg_num,16,width,opflag);
str+=len;num+=len;
break;
case 'o':
arg_num = va_arg(arg_ptr, int);
len = Int2Str(str,arg_num,8,width,opflag);
str+=len;num+=len;
break;
case 's':
case 'S':
pval=va_arg(arg_ptr,char *);
len = strlen(pval);
if((width > len) && (0 == (opflag&P_ALIGN_BIT))) //Ҷ
{
for(i = 0;i < (width - len);i ++) //߲ո
{
*str ++ = ' ';
num ++;
}
}
for(i=0;i < len;i++)
{
*str++=pval[i];
}
num +=len;
if((width > len) && (opflag&P_ALIGN_BIT)) //
{
for(i = 0;i < (width - len);i ++) //ұ߲ո
{
*str ++ = ' ';
num ++;
}
}
break;
case '%':
*str++ = '%';
num ++;
break;
default:
break;
}
fp++;
}
}
*str = '\0';
va_end(arg_ptr);
return num;
}
_ssize_t _write_r (struct _reent *r, int file, const void *ptr, size_t len)
{
size_t i;
char *p;
p = (char*) ptr;
for (i = 0; i < len; i++)
{
#if 0
if (*p == '\n')
{
sendchar('\r');
}
#endif
sendchar(*p++);
}
return len;
}
_ssize_t _read_r(struct _reent *r, int file, void *ptr, size_t len)
{
return 0;
}
int _close_r(struct _reent *r, int file)
{
return 0;
}
_off_t _lseek_r(struct _reent *r, int file, _off_t ptr, int dir)
{
return (_off_t)0; /* Always indicate we are at file beginning. */
}
int _fstat_r(struct _reent *r, int file, struct stat *st)
{
return 0;
}
int _isatty(int file)
{
return 1;
}
void abort(void)
{
while(1);
}
extern char end[];
extern char __HeapLimit[];
static char *heap_ptr = end;
static char *heap_end = __HeapLimit;
/**
* @brief This function is used to extend current heap size, Limit is __HeapLimit
*
* @param[in] None
*
* @return None
*
* @note Normally, it is just used in gcc mode.
*/
void * _sbrk_r(struct _reent *_s_r, ptrdiff_t nbytes)
{
char *base;
base = heap_ptr;
if(base + nbytes > heap_end)
{
return (void *)-1;
}
heap_ptr += nbytes;
return base;
}
void * tls_reserve_mem_lock(int nbytes)
{
if(heap_end - (nbytes + 4) <= heap_ptr)
{
return NULL;
}
heap_end -= (nbytes + 4);
return (void *)((((int)heap_end + 3) >> 2) << 2);
}
void tls_reserve_mem_unlock(void)
{
heap_end = __HeapLimit;
}
|
C
|
/*
** EPITECH PROJECT, 2017
** init.c
** File description:
** blabla
*/
#include "my.h"
char **double_tab(char *buffer, int size)
{
int j = 0;
int i = 0;
int count = 0;
char **tab = malloc(sizeof(char *) * (size + 1));
int nb = 0;
nb = my_strlen(buffer) / my_getnbr(buffer);
while (buffer[j] != '\0') {
tab[i] = malloc(sizeof(char) * nb);
for (count = 0; buffer[j] != '\n'; ++count) {
tab[i][count] = buffer[j];
++j;
}
tab[i][count] = '\0';
++i;
++j;
}
tab[i] = 0;
return (tab);
}
|
C
|
#include <stdlib.h>
struct point {
int x;
int y;
};
int main() {
int* a = (int*) malloc(4*sizeof(int));
int b;
a[0] = 1;
a[1] = 2;
a[2] = 3;
a[3] = 4;
struct point* p = (struct point*) a;
b = p[1].x;
return 0;
}
|
C
|
#include <math.h>
#include "nric.h"
double carlson_rf( double x, double y, double z ) {
double alamb, ave, delx, dely, delz, e2, e3, sqrtx, sqrty, sqrtz, xt, yt, zt;
const double ERRTOL = 0.0025, TINY = 1.5e-38, BIG = 3.0e37,
C1 = 1.0/24.0, C2 = 0.1, C3 = 3.0/44.0, C4 = 1.0/14.0;
if ( dmin3( x, y, z ) < 0.0 || dmin3( x + y, y + z, z + x ) < TINY || dmax3( x, y, z ) > BIG ) nrerror( "Invalid arguments in rf." );
xt = x;
yt = y;
zt = z;
do {
sqrtx = sqrt(xt);
sqrty = sqrt(yt);
sqrtz = sqrt(zt);
alamb = sqrtx*sqrty + sqrty*sqrtz + sqrtz*sqrtx;
xt = 0.25*(xt + alamb);
yt = 0.25*(yt + alamb);
zt = 0.25*(zt + alamb);
ave = (xt + yt + zt)/3.0;
delx = (ave - xt)/ave;
dely = (ave - yt)/ave;
delz = (ave - zt)/ave;
} while ( dmax3( fabs(delx), fabs(dely), fabs(delz) ) > ERRTOL );
e2 = delx*dely - delz*delz;
e3 = delx*dely*delz;
return (1.0 + (C1*e2 - C2 - C3*e3)*e2 + C4*e3)/sqrt(ave);
}
double carlson_rd( double x, double y, double z ) {
double alamb, ave, delx, dely, delz, ea, eb, ec, ed, ee, fac, sqrtx, sqrty, sqrtz, sum, xt, yt, zt;
const double ERRTOL = 0.0015, TINY = 1.0e-25, BIG = 4.5e21,
C1 = 3.0/14.0, C2 = 1.0/6.0, C3 = 9.0/22.0, C4 = 3.0/26.0, C5 = 0.25*C3, C6 = 1.5*C4;
if ( dmin( x, y ) < 0.0 || dmin( x+y, z ) < TINY || dmax3( x, y, z ) > BIG ) nrerror( "Invalid arguments in rd." );
xt = x;
yt = y;
zt = z;
sum = 0.0;
fac = 1.0;
do {
sqrtx = sqrt(xt);
sqrty = sqrt(yt);
sqrtz = sqrt(zt);
alamb = sqrtx*sqrty + sqrty*sqrtz + sqrtz*sqrtx;
sum += fac/(sqrtz*(zt + alamb));
fac *= 0.25;
xt = 0.25*(xt + alamb);
yt = 0.25*(yt + alamb);
zt = 0.25*(zt + alamb);
ave = 0.2*(xt + yt + 3.0*zt);
delx = (ave - xt)/ave;
dely = (ave - yt)/ave;
delz = (ave - zt)/ave;
} while ( dmax3( fabs(delx), fabs(dely), fabs(delz) ) > ERRTOL );
ea = delx*dely;
eb = delz*delz;
ec = ea - eb;
ed = ea - 6.0*eb;
ee = ed + 2.0*ec;
return 3.0*sum + fac*(1.0 + ed*(-C1 + C5*ed - C6*delz*ee) + delz*(C2*ee + delz*(-C3*ec + delz*C4*ea)))/(ave*sqrt(ave));
}
double carlson_rj( double x, double y, double z, double p ) {
double a, alamb, alpha, ans, ave, b, beta, delp, delx, dely, delz, ea, eb, ec, ed, ee, fac,
pt, rcx, rho, sqrtx, sqrty, sqrtz, sum, tau, xt, yt, zt;
const double ERRTOL = 0.0015, TINY = 2.5e-13, BIG = 9.0e11, C1 = 3.0/11.0, C2 = 1.0/3.0, C3 = 3.0/22.0, C4 = 3.0/26.0,
C5 = 0.75*C3, C6 = 1.5*C4, C7 = 0.5*C2, C8 = 2.0*C3;
if ( dmin3( x, y, z ) < 0.0 || dmin( dmin3( x+y, y+z, x+x ), fabs(p) ) < TINY || dmax( dmax3( x, y, z ), fabs(p) ) > BIG )
nrerror( "Invalid arguments in carlson_rj." );
sum = 0.0;
fac = 1.0;
if ( p > 0.0 ) {
xt = x;
yt = y;
zt = z;
pt = p;
} else {
xt = dmin3( x, y, z );
zt = dmax3( x, y, z );
yt = x + y + z - xt - zt;
a = 1.0/(yt - p);
b = a*(zt - yt)*(yt - xt);
pt = yt + b;
rho = xt*zt/yt;
tau = p*pt/yt;
rcx = carlson_rc( rho, tau );
}
do {
sqrtx = sqrt(xt);
sqrty = sqrt(yt);
sqrtz = sqrt(zt);
alamb = sqrtx*sqrty + sqrty*sqrtz + sqrtz*sqrtx;
alpha = dsqr( pt*(sqrtx + sqrty + sqrtz) + sqrtx*sqrty*sqrtz );
beta = pt*dsqr( pt + alamb );
sum += fac*carlson_rc( alpha, beta );
fac *= 0.25;
xt = 0.25*(xt + alamb);
yt = 0.25*(yt + alamb);
zt = 0.25*(zt + alamb);
pt = 0.25*(pt + alamb);
ave = 0.2*(xt + yt + zt + pt + pt);
delx = (ave - xt)/ave;
dely = (ave - yt)/ave;
delz = (ave - zt)/ave;
delp = (ave - pt)/ave;
} while ( dmax( dmax3( fabs(delx), fabs(dely), fabs(delz) ), fabs(delp) ) > ERRTOL );
ea = delx*dely + dely*delz + delz*delx;
eb = delx*dely*delz;
ec = delp*delp;
ed = ea - 3.0*ec;
ee = eb + 2.0*delp*(ea - ec);
ans = 3.0*sum + fac*(1.0 + ed*(-C1 + C5*ed - C6*ee) + eb*(C7 + delp*(-C8 + delp*C4)) + delp*ea*(C2 - delp*C3) - C2*delp*ec)/(ave*sqrt(ave));
if ( p < 0.0 ) ans = a*(b*ans + 3.0*(rcx - carlson_rf( xt, yt, zt )));
return ans;
}
double carlson_rc( double x, double y ) {
double alamb, ave, s, w, xt, yt;
const double ERRTOL = 0.0012, TINY = 1.69e-38, SQRTNY = 1.3e-19, BIG = 3.0e37, TNBG = TINY*BIG,
COMP1 = 2.236/SQRTNY, COMP2 = TNBG*TNBG/25.0, C1 = 0.3, C2 = 1.0/7.0, C3 = 0.375, C4 = 9.0/22.0;
if ( x < 0.0 || y == 0.0 || (x + fabs(y)) < TINY || (x + fabs(y)) > BIG || (y < -COMP1 && x > 0.0 && x < COMP2) )
nrerror( "Invalid arguments in carlson_rc" );
if ( y > 0.0 ) {
xt = x;
yt = y;
w = 1.0;
} else {
xt = x - y;
yt = -y;
w = sqrt(x)/sqrt(xt);
}
do {
alamb = 2.0*sqrt(xt)*sqrt(yt) + yt;
xt = 0.25*(xt + alamb);
yt = 0.25*(yt + alamb);
ave = (xt + yt + yt)/3.0;
s = (yt - ave)/ave;
} while ( fabs(s) > ERRTOL );
return w*(1.0 + s*s*(C1 + s*(C2 + s*(C3 + s*C4))))/sqrt(ave);
}
/*
* Legendre elliptic function of the second kind, E(phi, k) evaluated using
* Carlson's elliptic functions Rf and Rd. The argument ranges are 0 <= phi <= pi/2
* and 0 <= ksin(phi) <= 1.
*/
double legendre_e( double phi, double k ) {
double s, c, cc, q, ks;
if ( phi < 0.0 || phi > PI/2.0 ) nrerror( "Argument phi out of range in legendre_f." );
s = sin(phi);
ks = k*s;
if ( ks < 0.0 || ks > 1.0 ) nrerror( "Argument k sin(phi) out of range in legendre_f." );
c = cos(phi);
cc = c*c;
q = (1.0 - ks)*(1.0 + ks);
return s*(carlson_rf( cc, q, 1.0 ) - dsqr(ks))*carlson_rd( cc, q, 1.0 );
}
/*
* Legendre elliptic function of the first kind, F(phi, k) evaluated using
* Carlson's elliptic functions Rf. The argument ranges are 0 <= phi <= pi/2
* and 0 <= ksin(phi) <= 1.
*/
double legendre_f( double phi, double k ) {
double s, c, cc, q, ks;
if ( phi < 0.0 || phi > PI/2.0 ) nrerror( "Argument phi out of range in legendre_f." );
s = sin(phi);
ks = k*s;
if ( ks < 0.0 || ks > 1.0 ) nrerror( "Argument k sin(phi) out of range in legendre_f." );
c = cos(phi);
cc = c*c;
q = (1.0 - ks)*(1.0 + ks);
return s*carlson_rf( cc, q, 1.0 );
}
/*
* Legendre elliptic function of the third kind, Pi(phi,n,k) evaluated using
* Carlson's elliptic functions Rj and Rf. The sign convention on n is opposite
* Abramowtz and Stegun. The ranges are 0 <= phi <= pi/2 and 0 <= ksin(phi) <= 1.
*/
double legendre_pi( double phi, double n, double k ) {
double s, c, cc, nss, q, ks;
if ( phi < 0.0 || phi > PI/2.0 ) nrerror( "Argument phi out of range in legendre_f." );
s = sin(phi);
ks = k*s;
if ( ks < 0.0 || ks > 1.0 ) nrerror( "Argument k sin(phi) out of range in legendre_f." );
nss = n*s*s;
c = cos(phi);
cc = c*c;
q = (1.0 - ks)*(1.0 + ks);
return s*(carlson_rf( cc, q, 1.0 ) - nss*carlson_rj( cc, q, 1.0, 1.0 + nss )/3.0);
}
void jacobian_sncndn( double uu, double mmc, double *sn, double *cn, double *dn ) {
double a, b, c, d, mc, u;
double *m, *n;
int i, ii, l, bo;
const int N = 20;
const double CA = 0.00001;
m = dvector( 1, N );
n = dvector( 1, N );
mc = mmc;
u = uu;
if ( mc ) {
bo = (mc < 0.0);
if ( bo ) {
d = 1.0 - mc;
mc /= -1.0/d;
u *= (d = sqrt(d));
}
a = 1.0;
*dn = 1.0;
for ( i = 1; i <= N; ++i ) {
l = i;
m[i] = a;
n[i] = (mc = sqrt(mc));
c = 0.5*(a + mc);
if ( fabs(a - mc) <= CA*a ) break;
mc *= a;
a = c;
}
u *= c;
*sn = sin(u);
*cn = cos(u);
if ( *sn ) {
a = (*cn)/(*sn);
c *= a;
for ( ii = l; ii >= 1; --ii ) {
b = m[ii];
a *= c;
c *= (*dn);
*dn = (n[ii] + a)/(b + a);
a = c/b;
}
a = 1.0/sqrt(c*c + 1.0);
*sn = dsign( a, *sn );
*cn = c*(*sn);
}
if ( bo ) {
a = *dn;
*dn = *cn;
*cn = a;
*sn /= d;
}
} else {
*cn = 1.0/cosh(u);
*dn = *cn;
*sn = tanh(u);
}
free_dvector( n, 1, N );
free_dvector( m, 1, N );
}
|
C
|
#include "demo.h"
#include "sqlite3.h"
#include <iostream>
using namespace std;
class SQL {
public:
int Run(const char *query, const char *dbName = "Sqlite_Test.db")
{
int rt = 0;
try
{
//Testing
//throw std::logic_error( "Test exception handling" );
sqlite3 *db;
char *szErrMsg = 0;
// open database
int rc = sqlite3_open(dbName, &db);
if(rc)
{
std::cout << "Can't open database\n";
} else {
std::cout << "Open database successfully\n";
}
rc = sqlite3_exec(db, query, this->callback, 0, &szErrMsg);
if(rc != SQLITE_OK)
{
std::cout << "SQL Error: " << szErrMsg << std::endl;
sqlite3_free(szErrMsg);
}
// close database
if(db)
{
sqlite3_close(db);
}
}catch(...)
{
rt = 1;
}
return rt;
}
// This is the callback function to display the select data in the table
static int callback(void *NotUsed, int argc, char **argv, char **szColName)
{
for(int i = 0; i < argc; i++)
{
std::cout << szColName[i] << " = " << argv[i] << std::endl;
}
std::cout << "\n";
return 0;
}
};
int main(){
SQL sql;
return sql.Run("SELECT * FROM Employee");
}
|
C
|
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
char buf[] = "hello";
//strlen需要返回值,返回值就是字符串的长度
//从首元素开始,到结束符为止的长度,结束符不算(遇到'\0'结束)
int len = strlen(buf);
printf("len = %d\n", len);
printf("sizeof(buf) = %lu\n", sizeof(buf)); //多了一个'\0';
char buf2[] = "\0hello";
len = strlen(buf2);
printf("len = %d\n",len);
//sizeof()测数据类型的长度,不会因为遇到'\0'而提前结束
printf("sizeof(buf2) = %lu\n",sizeof(buf2));
return 0;
}
|
C
|
#include "Snake.h"
Snake *initSnake( int gridWith )
{
Snake *newSnake = (Snake*)malloc( sizeof( Snake ) );
if ( !newSnake )
{
fprintf( stderr, "Out of memory\n" );
return NULL;
}
newSnake->pGrid = initGrid( 25 );
newSnake->head = NULL;
newSnake->tail = NULL;
newSnake->dir = DIR_RIGHT;
newSnake->size = 0;
newSnake->speed = SPEED_NORMAL;
newSnake->error = 0;
newSnake->score = 0;
newSnake->skipRemove = 0;
return newSnake;
}
void insertAtTail( Snake *snake )
{
Segment *newSeg = (Segment*)malloc( sizeof( Segment ) );
if ( !newSeg )
{
fprintf( stderr, "Out of memory\n" );
return;
}
newSeg->next = NULL;
newSeg->previous = NULL;
newSeg->data.c = SYM_SEG;
if ( snake->head == NULL )
{
snake->head = newSeg;
snake->tail = newSeg;
newSeg->data.x = (int)( (float)(snake->pGrid->width / 2) );
newSeg->data.y = (int)( (float)(snake->pGrid->height / 2) );
}
else
{
newSeg->previous = snake->tail;
snake->tail->next = newSeg;
snake->tail = newSeg;
switch ( snake->dir )
{
case DIR_UP:
newSeg->data.x = newSeg->previous->data.x;
newSeg->data.y = newSeg->previous->data.y - 1;
if ( newSeg->data.y < 0 )
{
snake->error = ERR_OOB_TOP;
return;
}
break;
case DIR_DOWN:
newSeg->data.x = newSeg->previous->data.x;
newSeg->data.y = newSeg->previous->data.y + 1;
if ( newSeg->data.y > snake->pGrid->height - 1 )
{
snake->error = ERR_OOB_BOTTOM;
return;
}
break;
case DIR_LEFT:
newSeg->data.x = newSeg->previous->data.x - 1;
newSeg->data.y = newSeg->previous->data.y;
if ( newSeg->data.x < 0 )
{
snake->error = ERR_OOB_LEFT;
return;
}
break;
case DIR_RIGHT:
newSeg->data.x = newSeg->previous->data.x + 1;
newSeg->data.y = newSeg->previous->data.y;
if ( newSeg->data.x > snake->pGrid->width - 2 )
{
snake->error = ERR_OOB_RIGHT;
return;
}
break;
}
}
snake->size++;
updateGridAtPos( snake->pGrid, newSeg->data.x, newSeg->data.y, SYM_SEG );
}
void removeFromHead( Snake *snake )
{
if ( snake->head == NULL )
{
//fprintf( stderr, "No head to remove\n" );
return;
}
else if ( snake->head == snake->tail )
{
//fprintf( stderr, "Cannot of 0 segments\n" );
return;
}
else
{
updateGridAtPos( snake->pGrid, snake->head->data.x, snake->head->data.y, SYM_GRID );
Segment *temp = snake->head;
snake->head = snake->head->next;
snake->head->previous = NULL;
//printf( "Freed head\n" );
free( temp );
}
snake->size--;
}
SegData getFront( Snake *snake )
{
return snake->head->data;
}
void printError( Snake *snake )
{
char *output;
int i, j, charCount = 0;
for ( i = 0; i < snake->pGrid->height; i++ )
{
for ( j = 0; j < snake->pGrid->width; j++ )
{
charCount++;
if ( !i && !j ) // if this is the first character malloc
{
output = (char*)malloc( sizeof(char) * ( charCount + 1 ) );
output[ i * snake->pGrid->width + j ] = snake->pGrid->grid[i][j];
}
else // if this is not the first character, realloc
{
output = (char*)realloc( output, sizeof(char) * ( charCount + 1 ) );
output[ i * snake->pGrid->width + j ] = snake->pGrid->grid[i][j];
}
}
}
// since we're outputting a manually-built string, we need to manually add a NULL to the end
output = (char*)realloc( output, sizeof(char) * charCount + 1 );
output[ charCount ] = '\0';
printf( "\n\n\n\tScore: %d\n%s\n\n", snake->score, output );
switch ( snake->error )
{
case ERR_OOB_TOP:
printf( "ERR_OOB_TOP: Snake tried going off the top of the grid\n" );
break;
case ERR_OOB_BOTTOM:
printf( "ERR_OOB_BOTTOM: Snake tried going off the bottom of the grid\n" );
break;
case ERR_OOB_LEFT:
printf( "ERR_OOB_LEFT: Snake tried going off the left of the grid\n" );
break;
case ERR_OOB_RIGHT:
printf( "ERR_OOB_RIGHT: Snake tried going off the right of the grid\n" );
break;
case ERR_KEYP_ESC:
printf( "ERR_KEYP_ESC: User pressed escape, quitting...\n" );
break;
case ERR_HIT_ITSELF:
printf( "ERR_HIT_ITSELF: Snake tried moving over one of its own segments\n" );
break;
default:
printf( "An error has occurred for which there is no error message\n" );
break;
}
printf( "\n" );
free( output );
}
char getNextChar( Snake *snake )
{
if ( !snake->tail )
{
fprintf( stderr, "Tail is NULL, cannot retrieve next character\n" );
return '\0';
}
else
{
switch ( snake->dir )
{
case DIR_UP:
return getCharAtPos( snake->pGrid, snake->tail->data.x, snake->tail->data.y - 1 );
case DIR_DOWN:
return getCharAtPos( snake->pGrid, snake->tail->data.x, snake->tail->data.y + 1 );
case DIR_LEFT:
return getCharAtPos( snake->pGrid, snake->tail->data.x - 1, snake->tail->data.y );
case DIR_RIGHT:
return getCharAtPos( snake->pGrid, snake->tail->data.x + 1, snake->tail->data.y );
default:
return '\0';
}
}
}
int snakeHasSegmentAtPos( Snake *snake, int x, int y )
{
Segment *temp = snake->head;
while ( temp != NULL )
{
if ( temp->data.x == x && temp->data.y == y )
return 1;
temp = temp->next;
}
return 0;
}
int snakeWillHitItself( Snake *snake )
{
if ( !snake->tail )
{
fprintf( stderr, "Tail is NULL, cannot determine if snake will hit itself\n" );
return 0;
}
else
{
switch ( snake->dir )
{
case DIR_UP:
return snakeHasSegmentAtPos( snake, snake->tail->data.x, snake->tail->data.y - 1 );
case DIR_DOWN:
return snakeHasSegmentAtPos( snake, snake->tail->data.x, snake->tail->data.y + 1 );
case DIR_LEFT:
return snakeHasSegmentAtPos( snake, snake->tail->data.x - 1, snake->tail->data.y );
case DIR_RIGHT:
return snakeHasSegmentAtPos( snake, snake->tail->data.x + 1, snake->tail->data.y );
default:
return 1;
}
}
}
void generateSpecificPickupAtRandomLocation( Snake *snake, char pickupType )
{
if ( containsPickup( snake->pGrid, pickupType ) )
return;
unsigned randX = -1, randY = -1;
while ( ( invalidX( snake->pGrid, randX ) && invalidY( snake->pGrid, randY ) ) || snakeHasSegmentAtPos( snake, randX, randY ) )
{
randX = rand() % snake->pGrid->width - 1;
randY = rand() % snake->pGrid->height;
}
updateGridAtPos( snake->pGrid, randX, randY, pickupType );
}
void generateRandomPickupAtRandomLocation( Snake *snake )
{
unsigned randX = -1, randY = -1;
char randomChar, randC;
while ( ( invalidX( snake->pGrid, randX ) && invalidY( snake->pGrid, randY ) ) || snakeHasSegmentAtPos( snake, randX, randY ) )
{
randX = rand() % snake->pGrid->width - 1;
randY = rand() % snake->pGrid->height;
randC = rand() % 5;
}
switch ( randC )
{
case 0:
randomChar = PICKUP_FOOD;
break;
case 1:
randomChar = PICKUP_CULL;
break;
case 2:
randomChar = PICKUP_NORM;
break;
case 3:
randomChar = PICKUP_FAST;
break;
case 4:
randomChar = PICKUP_SLOW;
break;
}
if ( containsPickup( snake->pGrid, randomChar ) )
return;
updateGridAtPos( snake->pGrid, randX, randY, randomChar );
}
|
C
|
/* -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.
* File Name : user_led.c
* Creation Date :28-04-2019
* Last Modified : Sun 28 April 2019 20:10:11 PM MDT
* Created By : Harsimransingh and Yasir Shah
* Description: header file to control on board leds
* Functions:
* led_control() to turn on board leds on or off based on the inputs
* References:
_._._._._._._._._._._._._._._._._._._._._.*/
/*user libraries*/
#include "user_led.h"
/* -------------------------------*/
/**
* @Synopsis function to control the on board leds. Pin 53,54 and 55 are used.
*
* @Param led_color to select the led number
* @Param status to take input from user to turn led on or off
*/
/* ---------------------------------*/
void led_control(int led_color, int status)
{
FILE* file_ptr;
if (status != OFF && status != ON)
{
printf("\nINCORRECT LED STATUS\n");
}
if (led_color > LOAD && led_color < BLUE)
{
printf("INCORRECT LED NUMBER\n");
exit(-1);
}
if(led_color == BLUE)
{
file_ptr = fopen("/sys/devices/ocp.3/gpio-leds.8/leds/beaglebone:green:usr0/brightness", "w");
fprintf(file_ptr,"%i",status);
}
else if(led_color == RED)
{
file_ptr = fopen("/sys/devices/ocp.3/gpio-leds.8/leds/beaglebone:green:usr1/brightness", "w");
fprintf(file_ptr,"%i",status);
}
else if(led_color == GREEN)
{
file_ptr = fopen("/sys/devices/ocp.3/gpio-leds.8/leds/beaglebone:green:usr2/brightness", "w");
fprintf(file_ptr,"%i",status);
}
else if(led_color == DATA)
{
file_ptr = fopen("/sys/class/gpio/gpio68/value", "w");
fprintf(file_ptr,"%i",status);
}
else if(led_color == CLOCK)
{
file_ptr = fopen("/sys/class/gpio/gpio26/value", "w");
fprintf(file_ptr,"%i",status);
}
else if(led_color == LOAD)
{
file_ptr = fopen("/sys/class/gpio/gpio44/value", "w");
fprintf(file_ptr,"%i",status);
}
fclose(file_ptr);
}
|
C
|
#include <stdio.h>
//#include <malloc.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include "challenge_system.h"
#define FREE_NULL(e) free((e)); (e)=NULL;
#define ASSERT(test_number, test_condition) \
if (!(test_condition)) {printf("TEST %s FAILED\n", test_number); } \
else printf("TEST %s OK\n", test_number);
/*FOR DEBUG*/
void printResult(Result r) {
switch (r) {
case OK:
printf("OK\n");
break;
case NULL_PARAMETER:
printf("NULL_PARAMETER\n");
break;
case ILLEGAL_PARAMETER:
printf("ILLEGAL_PARAMETER\n");
break;
case ILLEGAL_TIME:
printf("ILLEGAL_TIME\n");
break;
case MEMORY_PROBLEM:
printf("MEMORY_PROBLEM\n");
break;
case NOT_IN_ROOM:
printf("NOT_IN_ROOM\n");
break;
case NO_AVAILABLE_CHALLENGES:
printf("NO_AVAILABLE_CHALLENGES\n");
break;
case ALREADY_IN_ROOM:
printf("ALREADY_IN_ROOM\n");
break;
}
}
void test_1() {
printf("test 1\n");
ChallengeRoomSystem *sys = NULL;
Result r = OK;
r = create_system("test_1.txt", &sys);
r = visitor_arrive(sys, "room_2", "visitor_1", 201, Medium, 5);
r = visitor_arrive(sys, "room_1", "visitor_2", 202, Easy, 8);
r = visitor_quit(sys, 203, 10);
ASSERT("1.1", r == NOT_IN_ROOM)
r = visitor_quit(sys, 201, 9);
ASSERT("1.2", r == OK)
int time;
r = best_time_of_system_challenge(sys, "challenge_2", &time);
ASSERT("1.3", time == 4)
r = change_system_room_name(sys, "room_1", "room_111");
r = visitor_arrive(sys, "room_1", "visitor_3", 203, Easy, 8);
//CHECKED WITH TIME=10; RESULT NULL_PARAMETER. SUPPORTED BY EX2 RULES?
ASSERT("1.4", r == ILLEGAL_TIME)
r = visitor_arrive(sys, "room_111", "visitor_3", 203, Easy, 8);
ASSERT("1.5", r == ILLEGAL_TIME)
r = visitor_arrive(sys, "room_111", "visitor_3", 203, Easy, 15);
ASSERT("1.6", r == OK)
r = visitor_arrive(sys, "room_111", "visitor_4", 204, Easy, 16);
ASSERT("1.7", r == NO_AVAILABLE_CHALLENGES)
r = change_challenge_name(sys, 11, "challenge_1111");
r = best_time_of_system_challenge(sys, "challenge_1111", &time);
ASSERT("1.8", time == 0)
char *namep = NULL;
r = most_popular_challenge(sys, &namep);
ASSERT("1.9", namep!=NULL && strcmp(namep, "challenge_1111")==0)
free(namep);
char *room = NULL;
r = system_room_of_visitor(sys, "visitor_4", &room);
ASSERT("1.10", r == NOT_IN_ROOM)
free(room);
r = system_room_of_visitor(sys, "visitor_3", &room);
ASSERT("1.11", r==OK && room!=NULL && strcmp(room, "room_111")==0)
free(room);
r = all_visitors_quit(sys, 17);
r = best_time_of_system_challenge(sys, "challenge_1111", &time);
ASSERT("1.12", time == 9)
r = best_time_of_system_challenge(sys, "challenge_4", &time);
ASSERT("1.13", time == 2)
char *most_popular_challenge = NULL, *challenge_best_time = NULL;
r = destroy_system(sys, 18, &most_popular_challenge, &challenge_best_time);
ASSERT("1.14",
most_popular_challenge!=NULL && strcmp(most_popular_challenge, "challenge_1111")==0)
ASSERT("1.15",
challenge_best_time!=NULL && strcmp(challenge_best_time, "challenge_4")==0)
FREE_NULL(most_popular_challenge);
FREE_NULL(challenge_best_time);
}
void test_2() {
printf("test 2\n");
ChallengeRoomSystem *sys = NULL;
Result r = OK;
r = create_system("test_2.txt", &sys);
r = visitor_arrive(sys, "room_1", "visitor_1", 201, Medium, 2);
ASSERT("2.1", r == NO_AVAILABLE_CHALLENGES)
r = visitor_arrive(sys, "room_1", "visitor_1", 201, Hard, 2);
ASSERT("2.2", r == OK)
r = visitor_arrive(sys, "room_1", "visitor_2", 202, All_Levels, 4);
ASSERT("2.3", r == NO_AVAILABLE_CHALLENGES)
r = visitor_quit(sys, 201, 5); //duration = 3 challenge_2
int time;
r = best_time_of_system_challenge(sys, "challenge_2", &time);
ASSERT("2.4", time == 3);
r = visitor_arrive(sys, "room_1", "visitor_2", 202, All_Levels, 6);
ASSERT("2.5", r == OK)
r = visitor_arrive(sys, "room_2", "visitor_1", 201, All_Levels, 8); //challenge_1
ASSERT("2.6", sys->all_rooms[1].challenges[0].visitor->visitor_id == 201)
r = visitor_arrive(sys, "room_3", "visitor_11", 211, Easy, 9);
r = visitor_arrive(sys, "room_3", "visitor_12", 212, Medium, 9);
r = visitor_arrive(sys, "room_3", "visitor_13", 213, Hard, 9);
r = visitor_arrive(sys, "room_3", "visitor_14", 214, All_Levels, 100);
ASSERT("2.7", r == NO_AVAILABLE_CHALLENGES)
r = visitor_arrive(sys, "room_2", "visitor_3", 223, Medium, 12); //challenge_6
ASSERT("2.8", sys->all_rooms[1].challenges[5].visitor->visitor_id == 223)
r = visitor_arrive(sys, "room_2", "visitor_4", 224, All_Levels, 13); //challenge_10
ASSERT("2.9", sys->all_rooms[1].challenges[9].visitor->visitor_id == 224)
r = visitor_arrive(sys, "room_2", "visitor_5", 225, All_Levels, 14); //challenge_2
ASSERT("2.10", r == OK)
char* namep = NULL;
r = system_room_of_visitor(sys, "visitor_1", &namep);
ASSERT("2.11", namep!=NULL && strcmp(namep, "room_2")==0)
FREE_NULL(namep);
r = system_room_of_visitor(sys, "visitor_9999", &namep);
ASSERT("2.12", r == NOT_IN_ROOM)
r = system_room_of_visitor(sys, "visitor_2", &namep);
ASSERT("2.13", namep!=NULL && strcmp(namep, "room_1")==0)
FREE_NULL(namep);
r = visitor_quit(sys, 223, 5);
ASSERT("2.14", r == ILLEGAL_TIME)
r = visitor_quit(sys, 202, 15); //duration = 9 challenge_2
r = visitor_quit(sys, 201, 18); //duration = 10 challenge_1
r = visitor_quit(sys, 211, 19); //duration = 10 challenge_3
r = visitor_quit(sys, 212, 19); //duration = 10 challenge_1
r = visitor_quit(sys, 213, 19); //duration = 10 challenge_2
r = system_room_of_visitor(sys, "visitor_13", &namep);
ASSERT("2.15", r == NOT_IN_ROOM)
r = best_time_of_system_challenge(sys, "challenge_2", &time);
ASSERT("2.16", time == 3);
r = best_time_of_system_challenge(sys, "challenge_8", &time);
ASSERT("2.17", time == 0);
ASSERT("2.18", r == OK)
r = best_time_of_system_challenge(sys, "challenge_12", &time);
ASSERT("2.19", r == ILLEGAL_PARAMETER);
r = best_time_of_system_challenge(sys, "challenge_1", &time);
ASSERT("2.20", time == 10);
/* in the system now: (room_2)
* visitor_3 223 in challenge_6
* visitor_4 224 in challenge_1
* visitor_5 225 in challenge_2 */
r = change_challenge_name(sys, 22, "challenge_22");
ASSERT("2.21", r == OK);
r = change_challenge_name(sys, 22, NULL);
ASSERT("2.22", r == NULL_PARAMETER);
r = change_challenge_name(sys, 222222, "challenge_22");
ASSERT("2.23", r == ILLEGAL_PARAMETER);
r = best_time_of_system_challenge(sys, "challenge_2", &time);
ASSERT("2.24", r == ILLEGAL_PARAMETER);
r = best_time_of_system_challenge(sys, "challenge_22", &time);
ASSERT("2.25", time == 3);
r = most_popular_challenge(sys, &namep);
ASSERT("2.26", namep!=NULL && strcmp(namep, "challenge_22")==0)
FREE_NULL(namep);
r = visitor_arrive(sys, "room_1", "visitor_9", 99, Hard, 20);
ASSERT("2.27", r == OK);
r = visitor_quit(sys, 99, 30); //duration = 10 challenge_2
r = visitor_arrive(sys, "room_4", "visitor_11", 1111, Hard, 30);
ASSERT("2.28", r == NO_AVAILABLE_CHALLENGES);
r = visitor_arrive(sys, "room_4", "visitor_11", 1111, Easy, 30);
r = visitor_arrive(sys, "room_4", "visitor_22", 2222, Easy, 30);
r = visitor_arrive(sys, "room_4", "visitor_33", 3333, Easy, 30);
ASSERT("2.28", r == NO_AVAILABLE_CHALLENGES);
r = visitor_arrive(sys, "room_4", "visitor_33", 3333, Medium, 30);
ASSERT("2.29", r == OK);
r = system_room_of_visitor(sys, "visitor_11", &namep);
ASSERT("2.30", namep!=NULL && strcmp(namep, "room_4")==0)
FREE_NULL(namep);
r = change_system_room_name(sys, "room_4", "room_99");
r = system_room_of_visitor(sys, "visitor_11", &namep);
ASSERT("2.31", namep!=NULL && strcmp(namep, "room_99")==0)
FREE_NULL(namep);
r = visitor_arrive(sys, "room_4", "visitor_44", 4444, All_Levels, 30);
ASSERT("2.32", r == NO_AVAILABLE_CHALLENGES);
r = visitor_arrive(sys, "room_99", "visitor_44", 4444, All_Levels, 30);
ASSERT("2.33", r == OK);
char *most_popular_challenge = NULL, *challenge_best_time = NULL;
r = destroy_system(sys, 25, &most_popular_challenge, &challenge_best_time);
ASSERT("2.34", r == ILLEGAL_TIME);
r = destroy_system(sys, 40, &most_popular_challenge, &challenge_best_time);
ASSERT("2.35",
most_popular_challenge!=NULL && strcmp(most_popular_challenge, "challenge_22")==0)
ASSERT("2.36",
challenge_best_time!=NULL && strcmp(challenge_best_time, "challenge_22")==0)
FREE_NULL(most_popular_challenge);
FREE_NULL(challenge_best_time);
}
void test_4() {
printf("test 4\n");
ChallengeRoomSystem *sys = NULL;
Result r = OK;
r = create_system("test_4.txt", &sys);
ASSERT("4.1", r == OK);
char *most_popular_challenge = NULL, *challenge_best_time = NULL;
r = destroy_system(sys, 25, &most_popular_challenge, &challenge_best_time);
ASSERT("4.2", r == OK);
ASSERT("4.3", most_popular_challenge==NULL && challenge_best_time==NULL)
FREE_NULL(most_popular_challenge);
FREE_NULL(challenge_best_time);
}
//test lexicographical differences
void test_5() {
printf("test 5:\n");
ChallengeRoomSystem *sys = NULL;
Result r = OK;
r = create_system("test_5.txt", &sys);
ASSERT("5.1", r == OK);
r = visitor_arrive(sys, "room_1", "visitor_1", 111, All_Levels, 0);
r = visitor_quit(sys, 111, 2); //duration = 2 bhallenge_2
char* namep = NULL;
r = most_popular_challenge(sys, &namep);
ASSERT("5.2", namep !=NULL && strcmp(namep, "bhallenge_2")==0)
FREE_NULL(namep);
r = visitor_arrive(sys, "room_1", "visitor_1", 111, All_Levels, 2);
r = visitor_arrive(sys, "room_1", "visitor_2", 222, All_Levels, 2);
r = visitor_arrive(sys, "room_2", "visitor_3", 333, All_Levels, 2);
r = all_visitors_quit(sys, 4);
ASSERT("5.3", r == OK);
char *popular_challenge = NULL, *challenge_best_time = NULL;
r = most_popular_challenge(sys, &popular_challenge);
ASSERT("5.4",
popular_challenge !=NULL && strcmp(popular_challenge, "bhallenge_2")==0)
FREE_NULL(popular_challenge);
r = change_challenge_name(sys, 22, "challenge_2");
r = most_popular_challenge(sys, &popular_challenge);
ASSERT("5.5",
popular_challenge !=NULL && strcmp(popular_challenge, "challenge_1")==0)
FREE_NULL(popular_challenge);
r = change_challenge_name(sys, 22, "bhallenge_2");
r = most_popular_challenge(sys, &popular_challenge);
ASSERT("5.6",
popular_challenge !=NULL && strcmp(popular_challenge, "bhallenge_2")==0)
FREE_NULL(popular_challenge);
r = visitor_arrive(sys, "room_1", "visitor_5", 555, All_Levels, 5);
r = visitor_arrive(sys, "room_1", "visitor_6", 666, All_Levels, 5);
r = destroy_system(sys, 25, &popular_challenge, &challenge_best_time);
ASSERT("5.7", r == OK);
ASSERT("5.8",
popular_challenge!=NULL && strcmp(popular_challenge, "bhallenge_2")==0)
ASSERT("5.9",
challenge_best_time!=NULL && strcmp(challenge_best_time, "bhallenge_2")==0)
FREE_NULL(popular_challenge);
FREE_NULL(challenge_best_time);
}
//test order of errors
void test_6() {
printf("test 6:\n");
ChallengeRoomSystem *sys = NULL;
Result r = OK;
r = create_system("test_6.txt", &sys);
ASSERT("6.1", r == OK);
r = visitor_arrive(sys, "room_1", "visitor_1", 1111, Easy, 5);
r = visitor_arrive(sys, "room_1", NULL, 2222, Hard, 2);
ASSERT("6.2", r == ILLEGAL_TIME);
r = visitor_arrive(NULL, "room_1", NULL, 2222, Hard, 5);
ASSERT("6.3", r == NULL_PARAMETER);
r = visitor_arrive(sys, "room_1", NULL, 2222, Hard, 5);
ASSERT("6.4", r == ILLEGAL_PARAMETER);
r = visitor_arrive(sys, NULL, "visitor_2", 2222, Hard, 5);
ASSERT("6.5", r == ILLEGAL_PARAMETER);
r = visitor_arrive(sys, NULL, "visitor_1", 1111, Hard, 5);
ASSERT("6.6", r == ILLEGAL_PARAMETER);
r = visitor_arrive(sys, NULL, "visitor_1", 1111, Hard, 5);
ASSERT("6.7", r == ILLEGAL_PARAMETER);
r = visitor_arrive(sys, "room_1", "visitor_1", 1111, Hard, 5);
ASSERT("6.8", r == ALREADY_IN_ROOM);
}
int main(int argc, char **argv) {
setvbuf(stdout, NULL, _IONBF, 0); //FOR OR ECLIPSE
test_1();
test_2();
test_4();
test_5();
test_6();
return 0;
}
|
C
|
#include <msp430.h>
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#ifndef RINGBUFFER_H__
#define RINGBUFFER_H__
/* forward declare the type */
struct ringbuffer;
void rb_init(struct ringbuffer* rb);
int rb_put(struct ringbuffer* rb, char *value);
const char* rb_get(struct ringbuffer* rb);
int rb_empty(const struct ringbuffer* rb);
int rb_full(const struct ringbuffer* rb);
#define E_RBEMPTY -1
#define E_RBFULL -1
#define BUFFERSIZE 32
struct ringbuffer {
size_t head;
size_t tail;
size_t count;
char *container[BUFFERSIZE];
};
#endif /* RINGBUFFER_H__ */
// helper functions
void UARTSendArray(unsigned char *TxArray, unsigned char ArrayLength);
void Init_UART(void);
void tempInit(void);
void process(void);
void OUTA_UART(unsigned char A);
char* format(int temp);
// variable declaration
static char input[17];
static char output[15];
struct ringbuffer data;
int if_UART = 0, if_TIMER = 0;
static int hour = 0, min = 0, sec = 0;
int main(void)
{
// variable to hold the temperature
int temp;
WDTCTL = WDTPW + WDTHOLD; // stop WDT
// initialize UART
Init_UART();
// initialize Temperature Sensor
tempInit();
// initialize Timer_A
TACCR0 = 4096; // set count top -> 4096 -> 1 sec
TACTL = TASSEL_1 | // clock source selection - use ACLK
MC0 | // up mode - count to TACCR0, then reset
ID_3; // clock divider - divide ACLK by 8
TACCTL0 = CCIE; // enable timer interrupt
// create ring buffer
rb_init(&data);
// enter LPM3, interrupts enabled
while(1)
{
// enter low power mode and enable interrupts
__bis_SR_register(LPM3_bits + GIE);
if (if_UART == 1) // if a command has been entered
{
process();
if_UART = 0;
OUTA_UART('\r');
OUTA_UART('\n');
}
else if (if_TIMER == 1) // if it has been five minuntes
{ // take a temp reading and save it
if(rb_full(&data))
{
data.tail++; // moves the tail ahead a space to keep the tail and head from meeting
data.tail %= BUFFERSIZE;
data.count--;
}
// get temperature reading
ADC10CTL0 |= ENC + ADC10SC; // enable conversion and start conversion
while(ADC10CTL1 & BUSY);
temp = ADC10MEM; // get temperature reading
ADC10CTL0 &= ~ENC; // disable adc conv
// save timestamp and temperature to string 'output'
if (sec < 10 && min > 10 && hour > 10)
sprintf(output, "%d%d0%d %d", hour, min, sec, temp);
else if (sec < 10 && min < 10 && hour > 10)
sprintf(output, "%d0%d0%d %d", hour, min, sec, temp);
else if (sec > 10 && min < 10 && hour < 10)
sprintf(output, "0%d0%d%d %d", hour, min, sec, temp);
else if (sec > 10 && min < 10 && hour > 10)
sprintf(output, "%d0%d%d %d", hour, min, sec, temp);
else if (sec < 10 && min > 10 && hour < 10)
sprintf(output, "0%d%d0%d %d", hour, min, sec, temp);
else if (sec < 10 && min < 10 && hour < 10)
sprintf(output, "0%d0%d0%d %d", hour, min, sec, temp);
//save string to ring buffer
rb_put(&data, output);
if_TIMER = 0;
}
}
}
/* ISR for receiving commands */
#pragma vector=USCIAB0RX_VECTOR
__interrupt void USCI0RX_ISR(void)
{
static int index = 0, count = 0;
static char data;
data = UCA0RXBUF;
data = tolower(data);
if (data != '\r' && count != 16)
{
input[index++] = data;
count++;
}
else
{
// store carriage return
input[index] = data;
// echo string to terminal
UARTSendArray(&input, index);
// reset variables
index = 0;
count = 0;
if_UART = 1;
__bic_SR_register_on_exit(LPM3_bits);
}
}
/* Timer A Interrupt - Real Time Clock */
#pragma vector=TIMER0_A0_VECTOR
__interrupt void timer0_isr(void)
{
// increment the second variable
sec += 1;
// if else statements deal with incrementing
// the min and hour variables
if (sec == 60)
{
sec = 0;
min += 1;
if (min == 60)
{
min = 0;
hour += 1;
if (hour == 24 && sec == 1)
{
sec = 0;
min = 0;
hour = 0;
}
}
}
// if it has been 5 minutes
// go to main and take a temp reading
if (min % 5 == 0 && sec == 0)
{
if_TIMER = 1;
__bic_SR_register_on_exit(LPM3_bits);
}
}
void process(void)
{
if (input[0] == 't')
{
// show current time
char time_char[7];
if (sec < 10 && min > 10 && hour > 10)
sprintf(time_char, "%d%d0%d", hour, min, sec);
else if (sec < 10 && min < 10 && hour > 10)
sprintf(time_char, "%d0%d0%d", hour, min, sec);
else if (sec > 10 && min < 10 && hour < 10)
sprintf(time_char, "0%d0%d%d", hour, min, sec);
else if (sec > 10 && min < 10 && hour > 10)
sprintf(time_char, "%d0%d%d", hour, min, sec);
else if (sec < 10 && min > 10 && hour < 10)
sprintf(time_char, "0%d%d0%d", hour, min, sec);
else if (sec < 10 && min < 10 && hour < 10)
sprintf(time_char, "0%d0%d0%d", hour, min, sec);
UARTSendArray(&time_char, 6);
}
else if (input[0] == 's')
{
//set current time
hour = (input[1]-48)*10 + (input[2]-48);
min = (input[3]-48)*10 + (input[4]-48);
sec = (input[5]-48)*10 + (input[6]-48);
}
else if (input[0] == 'o')
{
// show the oldest temp reading and its time stamp
if (data.count == 0)
UARTSendArray("No temperatures recorded.", 25);
else
{
// get the oldest reading
// to_screen = rb_get(&data);
// send to terminal
UARTSendArray(rb_get(&data), 15);
}
}
else if (input[0] == 'l')
{
if (data.count == 0)
UARTSendArray("No temperatures recorded.", 25);
while(!rb_empty(&data))
{
UARTSendArray(rb_get(&data), 15);
OUTA_UART('\n');
}
}
return;
}
void tempInit(void)
{
ADC10CTL0 = SREF_1 + REFON + ADC10ON + ADC10SHT_3 ; //1.5V ref,Ref on,64 clocks for sample
ADC10CTL1 = INCH_10+ ADC10DIV_3; //temp sensor is at 10 and clock/4
}
void Init_UART(void)
{
/* Use Calibration values for 1MHz Clock DCO */
DCOCTL = 0;
BCSCTL1 = CALBC1_1MHZ;
DCOCTL = CALDCO_1MHZ;
/* Configure Pin Muxing P1.1 RXD and P1.2 TXD */
P1SEL = BIT1 | BIT2 ;
P1SEL2 = BIT1 | BIT2;
/* Place UCA0 in Reset to be configured */
UCA0CTL1 = UCSWRST;
/* Configure */
UCA0CTL1 |= UCSSEL_2; // SMCLK
UCA0BR0 = 104; // 1MHz 9600
UCA0BR1 = 0; // 1MHz 9600
UCA0MCTL = UCBRS0; // modulation UCBRSx = 1
/* Take UCA0 out of reset */
UCA0CTL1 &= ~UCSWRST;
/* Enable USCI_A0 RX interrupt */
IE2 |= UCA0RXIE;
}
void UARTSendArray(unsigned char *TxArray, unsigned char ArrayLength){
while(ArrayLength--)
{ // loop until StringLength == 0 and post decrement
while(!(IFG2 & UCA0TXIFG)); // wait for TX buffer to be ready for new data
UCA0TXBUF = *TxArray; // write the character at the location specified py the pointer
TxArray++; // increment the TxString pointer to point to the next character
}
}
void OUTA_UART(unsigned char A)
{
do{
}while ((IFG2&0x02)==0);
UCA0TXBUF = A;
}
// Ring Buffer Functions
void rb_init(struct ringbuffer* rb) {
rb->head = 0;
rb->tail = BUFFERSIZE - 1;
rb->count = 0;
}
int rb_put(struct ringbuffer* rb, char *value) {
if(rb_full(rb)) {
return E_RBFULL;
}
rb->count++;
rb->container[rb->head++] = value;
rb->head %= BUFFERSIZE;
return 0;
}
const char* rb_get(struct ringbuffer* rb) {
rb->count--;
rb->tail++;
rb->tail %= BUFFERSIZE;
return rb->container[rb->tail];
}
int rb_empty(const struct ringbuffer* rb) {
return (rb->count == 0);
}
int rb_full(const struct ringbuffer* rb) {
return (rb->count == BUFFERSIZE);
}
|
C
|
/*Lab Test - Program that uses structures and functions to enter driver's licence information from standard input
and display them to standard output
Date: 12/4/18
Author: Louis Chavez
*/
#include <stdio.h>
#define K 21
#define N 11
struct date_of_birth
{
int day;
int month;
int year;
}; //end date_of_birth
struct info
{
char firstname[K];
char surname[K];
struct date_of_birth dob; //nested structure
int height;
int weight;
char eye_col[N];
}; //end info
//Function prototypes
//b - Function to input driver details from standard input
void input(struct info *); //pass by reference - passing info structure pointer (change and keep values) - no return value
//c - Function to display entered details to standard output
void dsp(struct info); //pass by value - passing info structure - no return value
int main()
{
//b - create variables for two separate people
struct info driver1, driver2;
//Call input() - input information of driver
input(&driver1); //passing address of variable '&'
input(&driver2);
//c
//Call dsp() - display entered information
dsp(driver1);
dsp(driver2);
getchar(); //borland
return 0;
} //end main
//Implement input(): Function to input details of driver from standard input - no return value
void input(struct info * driver)
{
static int num = 0; //counter for display purposes only - static allows variable to keep value
num++; //increment num for every entry
printf("\n\t Driver #%d\n", num);
//prompt firstname
printf("\n Enter Firstname:\n - ");
gets((*driver).firstname); //allows for wide space characters
//prompt surname
printf("\n Enter Surname:\n - ");
gets((*driver).surname);
//prompt date of birth
printf("\n Enter Date of Birth:\n dd - ");
scanf("%d", &(*driver).dob.day);
printf(" mm - ");
scanf("%d", &(*driver).dob.month);
printf(" yyyy - ");
scanf("%d", &(*driver).dob.year);
//prompt height
printf("\n Enter Height (cm):\n - ");
scanf("%d", &(*driver).height);
//prompt weight
printf("\n Enter Weight (kg):\n - ");
scanf("%d", &(*driver).weight);
//prompt eye colour
printf("\n Enter Eye Colour:\n - ");
scanf("%s", &(*driver).eye_col); //no wide space
flushall(); //clear input stream
} //end input()
//Implement dsp(): Function to display details entered onto standard output - no return value
void dsp(struct info driver)
{
static int num = 0; //static int counter for display purposes only - keeps value in function
num++; //increment num for every entry
printf("\n\t Driver #%d\n", num);
printf("\n Firstname: %s\n", driver.firstname);
printf(" Surname: %s\n", driver.surname);
printf(" DOB: %d/%d/%d\n", driver.dob.day, driver.dob.month, driver.dob.year);
printf(" Height: %d cm\n", driver.height);
printf(" Weight: %d kg\n", driver.weight);
printf(" Eye Colour: %s\n", driver.eye_col);
} //end dsp()
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* execute.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nbeny <nbeny@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/05/20 10:11:24 by nbeny #+# #+# */
/* Updated: 2017/05/20 10:11:25 by nbeny ### ########.fr */
/* */
/* ************************************************************************** */
#include "shell.h"
char *ft_path_istrue(char **cmd, t_env *e)
{
t_env *s;
char *tmp;
char *test;
char **path;
int i;
i = 0;
test = NULL;
s = ft_moove_env(e, "PATH\0", 5);
if (s != NULL)
{
path = ft_strsplit(s->value, ':');
tmp = ft_strjoin("/", cmd[0]);
while (path[i] != NULL)
{
test = ft_strjoin(path[i], tmp);
if (!access(test, X_OK))
break ;
ft_strdel(&test);
i++;
}
ft_free_tabstr(path);
ft_strdel(&tmp);
}
return (test);
}
void ft_execute_path(char *str, char **cmd, t_env *e)
{
pid_t pid;
pid_t w;
int status;
char **env;
pid = fork();
signal(SIGINT, sig_exe);
env = ft_list_to_tab(e);
if (pid == -1)
exit(EXIT_FAILURE);
else if (pid == 0 && !access(str, X_OK))
{
status = execve(str, cmd, env);
if (kill(pid, SIGINT) == -1)
exit(status);
exit(status);
}
else
{
w = waitpid(pid, &status, WCONTINUED);
if (w == -1)
exit(EXIT_FAILURE);
}
ft_free_tabstr(env);
ft_strdel(&str);
}
void ft_execute(char **cmd, t_env *e)
{
pid_t pid;
pid_t w;
int status;
char **env;
char *s;
pid = fork();
signal(SIGINT, sig_exe);
s = ft_string_return(e, cmd);
env = ft_list_to_tab(e);
if (pid == -1)
exit(EXIT_FAILURE);
if (pid == 0 && !access(s, X_OK))
{
status = execve(s, cmd, env);
if (kill(pid, SIGINT) == -1)
exit(status);
exit(status);
}
else if ((w = waitpid(pid, &status, WCONTINUED)) == -1)
exit(EXIT_FAILURE);
ft_free_tabstr(env);
ft_strdel(&s);
}
void ft_exit(t_exec *exe, t_env *e)
{
ft_free_tabstr(exe->cmd);
free(exe);
exe = NULL;
exit(EXIT_SUCCESS);
}
|
C
|
/*
** EPITECH PROJECT, 2018
** my_intlen
** File description:
** my_intlen
*/
#include "my.h"
int my_intlen(unsigned int nb)
{
int i = 0;
for (int j = 1; nb / j > 0; j *= 10)
i++;
return (i);
}
|
C
|
/*init.c*/
#include "init.h"
/* déclaration des tableaux de chaines de caractères statiques */
char* Type[] = {"FRUIT","LEGUME"};
char* Fruits[] = {"BANANE","KIWI","POIRE","POMME","ANANAS","DURIAN"};
char* Legumes[] = {"HARICOT","FENOUIL","POIREAU","AUBERGINE","COURGETTE","CAROTTE"};
char* Armes[] = {"EPLUCHEUR_LASER","MANDOLINE_SONIQUE","COUPERET","HACHOIR_NEURONIQUE","MIXEUR_BLASTER"};
char* Protections[]= {"CASQUE_EGOUTTOIR","CASQUE_ENTONNOIR","WOKLIER","TABLIER_ARMURE"};
char* Soins[] = {"HUMUS_NEUTRONIQUE","COMPOST_PROTONIQUE","ENGRAIS_IONIQUE"};
/*
* Fonction qui permet de retourner un tableau de champions "FRUIT" initialisés avec leurs compteurs .
*
* @param : void
* @return : Champion* (un tableau de Champion - type déclaré dans le fichier init.h)
*
*/
Champion* initFruits(){
int i;
Champion* campF = malloc(6*sizeof(Champion));
for(i=0;i<6;i++){
campF[i].type = Type[0];
campF[i].variete = Fruits[i];
}
campF[0].force = 10; campF[0].resistance = 10; campF[0].PV_max = 40; campF[0].PV_restant = 40; campF[0].cout_CE = 5; campF[0].nbDuels = 0; campF[0].boolGagner = -1;
campF[1].force = 12; campF[1].resistance = 15; campF[1].PV_max = 40; campF[1].PV_restant = 40; campF[1].cout_CE = 7; campF[1].nbDuels = 0; campF[1].boolGagner = -1;
campF[2].force = 15; campF[2].resistance = 20; campF[2].PV_max = 60; campF[2].PV_restant = 60; campF[2].cout_CE = 10; campF[2].nbDuels = 0; campF[2].boolGagner = -1;
campF[3].force = 20; campF[3].resistance = 20; campF[3].PV_max = 60; campF[3].PV_restant = 60; campF[3].cout_CE = 15; campF[3].nbDuels = 0; campF[3].boolGagner = -1;
campF[4].force = 20; campF[4].resistance = 25; campF[4].PV_max = 80; campF[4].PV_restant = 80; campF[4].cout_CE = 20; campF[4].nbDuels = 0; campF[4].boolGagner = -1;
campF[5].force = 25; campF[5].resistance = 25; campF[5].PV_max = 80; campF[5].PV_restant = 80; campF[5].cout_CE = 25; campF[5].nbDuels = 0; campF[5].boolGagner = -1;
return campF;
}
/*
* Fonction qui permet de retourner un tableau de champions "LEGUME" initialisés avec leurs compteurs .
*
* @param : void
* @return : Champion* (un tableau de Champion - type déclaré dans le fichier init.h)
*
*/
Champion* initLegumes() {
int i;
Champion* campL=malloc(6*sizeof(Champion));
for(i=0;i<6;i++){
campL[i].type = Type[1];
campL[i].variete = Legumes[i];
}
campL[0].force = 10; campL[0].resistance = 10; campL[0].PV_max = 40; campL[0].PV_restant = 40; campL[0].cout_CE = 5; campL[0].nbDuels = 0; campL[0].boolGagner = -1;
campL[1].force = 12; campL[1].resistance = 15; campL[1].PV_max = 40; campL[1].PV_restant = 40; campL[1].cout_CE = 7; campL[1].nbDuels = 0; campL[1].boolGagner = -1;
campL[2].force = 15; campL[2].resistance = 20; campL[2].PV_max = 60; campL[2].PV_restant = 60; campL[2].cout_CE = 10; campL[2].nbDuels = 0; campL[2].boolGagner = -1;
campL[3].force = 20; campL[3].resistance = 20; campL[3].PV_max = 60; campL[3].PV_restant = 60; campL[3].cout_CE = 15; campL[3].nbDuels = 0; campL[3].boolGagner = -1;
campL[4].force = 20; campL[4].resistance = 25; campL[4].PV_max = 80; campL[4].PV_restant = 80; campL[4].cout_CE = 20; campL[4].nbDuels = 0; campL[4].boolGagner = -1;
campL[5].force = 25; campL[5].resistance = 25; campL[5].PV_max = 80; campL[5].PV_restant = 80; campL[5].cout_CE = 25; campL[5].nbDuels = 0; campL[5].boolGagner = -1;
return campL;
}
/*
* Fonction qui permet de retourner un tableau d'armes initialisés avec leurs compteurs .
*
* @param : Arme* (un tableau de Arme - type déclaré dans le fichier init.h)
* @return : Arme* (tableau de Arme - modifié)
*
*/
void initArmes(Arme* tabArmes) {
int i;
for(i=0;i<5;i++){
tabArmes[i].nom = Armes[i];
}
tabArmes[0].cout_CE = 2; tabArmes[0].cout_CA = 1; tabArmes[0].portee = 2; tabArmes[0].degats[0] = 1; tabArmes[0].degats[1] = 2;
tabArmes[1].cout_CE = 5; tabArmes[1].cout_CA = 3; tabArmes[1].portee = 3; tabArmes[1].degats[0] = 1; tabArmes[1].degats[1] = 3;
tabArmes[2].cout_CE = 10; tabArmes[2].cout_CA = 5; tabArmes[2].portee = 5; tabArmes[2].degats[0] = 2; tabArmes[2].degats[1] = 6;
tabArmes[3].cout_CE = 20; tabArmes[3].cout_CA = 7; tabArmes[3].portee = 7; tabArmes[3].degats[0] = 4; tabArmes[3].degats[1] = 9;
tabArmes[4].cout_CE = 30; tabArmes[4].cout_CA = 10; tabArmes[4].portee = 11;tabArmes[4].degats[0] = 7; tabArmes[4].degats[1] = 12;
}
/*
* Fonction qui permet de retourner un tableau de protections initialisés avec leurs compteurs .
*
* @param : Protection* (un tableau de Protection - type déclaré dans le fichier init.h)
* @return : Protection* (tableau de Protection - modifié)
*
*/
void initProtections(Protection* tabProtects) {
int i;
for(i=0;i<4;i++){
tabProtects[i].nom = Protections[i];
}
tabProtects[0].cout_CE = 1; tabProtects[0].cout_CA = 2; tabProtects[0].portabilite = 25;
tabProtects[1].cout_CE = 3; tabProtects[0].cout_CA = 4; tabProtects[0].portabilite = 40;
tabProtects[2].cout_CE = 5; tabProtects[0].cout_CA = 6; tabProtects[0].portabilite = 60;
tabProtects[3].cout_CE = 10; tabProtects[0].cout_CA = 8; tabProtects[0].portabilite = 80;
}
/*
* Fonction qui permet de retourner un tableau de soins initialisés avec leurs compteurs .
*
* @param : Soin* (un tableau de Soin - type déclaré dans le fichier init.h)
* @return : Soin* (tableau deSoin - modifié)
*
*/
void initSoins(Soin* tabSoins) {
int i;
for(i=0;i<3;i++){
tabSoins[i].nom = Soins[i];
}
tabSoins[0].cout_CE = 1; tabSoins[0].cout_CA = 5; tabSoins[0].volume = 4; tabSoins[0].effet[0] = 2; tabSoins[0].effet[1] = 4;
tabSoins[1].cout_CE = 5; tabSoins[1].cout_CA = 10; tabSoins[1].volume = 3; tabSoins[1].effet[0] = 5; tabSoins[1].effet[1] = 8;
tabSoins[2].cout_CE = 7; tabSoins[2].cout_CA = 15; tabSoins[2].volume = 2; tabSoins[2].effet[0] = 8; tabSoins[2].effet[1] = 12;
}
/*
* Fonction qui permet de retourner un camp de legumes initialisé avec ses compteurs et sa liste de membres.
*
* @param : void
* @return : Camp* (pointeur de Camp - type déclaré dans le fichier init.h)
*
*/
Camp* CampLegumes () {
Camp* c = malloc(sizeof(Camp));
c->type = Type[1];
c->membres = initLegumes();
c->nb_membres = nbMembres;
c->CE = CE_camp;
c->CA = CA_camp;
return c;
}
/*
* Fonction qui permet de retourner un camp de fruits initialisé avec ses compteurs et sa liste de membres.
*
* @param : void
* @return : Camp* (pointeur de Camp - type déclaré dans le fichier init.h)
*
*/
Camp* CampFruits () {
Camp* c=malloc(sizeof(Camp));
c->type = Type[0];
c->membres = initFruits();
c->nb_membres = nbMembres;
c->CE = CE_camp;
c->CA = CA_camp;
return c;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
struct work_stuff {int nrepeats; int /*<<< orphan*/ forgetting_types; int /*<<< orphan*/ * previous_argument; } ;
typedef int /*<<< orphan*/ string ;
/* Variables and functions */
int demangle_args (struct work_stuff*,char const**,int /*<<< orphan*/ *) ;
int /*<<< orphan*/ free (char*) ;
int /*<<< orphan*/ string_delete (int /*<<< orphan*/ *) ;
__attribute__((used)) static int
demangle_nested_args (struct work_stuff *work, const char **mangled,
string *declp)
{
string* saved_previous_argument;
int result;
int saved_nrepeats;
/* The G++ name-mangling algorithm does not remember types on nested
argument lists, unless -fsquangling is used, and in that case the
type vector updated by remember_type is not used. So, we turn
off remembering of types here. */
++work->forgetting_types;
/* For the repeat codes used with -fsquangling, we must keep track of
the last argument. */
saved_previous_argument = work->previous_argument;
saved_nrepeats = work->nrepeats;
work->previous_argument = 0;
work->nrepeats = 0;
/* Actually demangle the arguments. */
result = demangle_args (work, mangled, declp);
/* Restore the previous_argument field. */
if (work->previous_argument)
{
string_delete (work->previous_argument);
free ((char *) work->previous_argument);
}
work->previous_argument = saved_previous_argument;
--work->forgetting_types;
work->nrepeats = saved_nrepeats;
return result;
}
|
C
|
#include <stdio.h>
#include <pthread.h>
#define MAXN 2
pthread_cond_t cond[MAXN];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void * function(void * args)
{
pthread_mutex_lock(&mutex);
printf("Waiting for a signal\n");
pthread_cond_wait(&cond[0], &mutex);
printf("Got signal!\n");
pthread_mutex_unlock(&mutex);
}
void * wake(void * args)
{
pthread_mutex_lock(&mutex);
pthread_cond_signal(&cond[0]);
pthread_cond_signal(&cond[0]);
printf("Done signaling\n");
pthread_mutex_unlock(&mutex);
}
int main()
{
pthread_t thread;
int b = 0;
pthread_create(&thread, NULL, function, &b);
pthread_t thread1;
int a = 1;
pthread_create(&thread1, NULL, function, &a);
pthread_t thread2;
pthread_create(&thread2, NULL, wake, NULL);
pthread_join(thread, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
printf("Done.!\n");
return 0;
}
|
C
|
#include<stdio.h>
//Ayush Sharma
//Scholar id :2012105
int main()
{
char n[500];
printf("Enter the value\n");
scanf("%s",n);
int i=0;
int d1=0,d2=0;
while(n[i]!='\0')
{
if(n[i]=='.')
{
d1++;
if(n[i+1]!='\0')
d2=1;
}
i++;
}
if(d1==1 && d2==1)
printf("Valid\n");
else
printf("Invalid\n");
}
|
C
|
#ifndef _INJECT_BUNDLE_H_
#define _INJECT_BUNDLE_H_
#ifdef __cplusplus
extern "C"
{
#endif
#ifdef __cplusplus
}
#endif
#endif
/***********************************************************************
* NAME
* inject_bundle -- Inject a dynamic library or bundle into a
* running process
*
* SYNOPSIS
* inject_bundle path_to_bundle [ pid ]
*
* DESCRIPTION
* The inject_bundle utility injects a dynamic library or bundle
* into another process. It does this by acquiring access to the
* remote process' mach task port (via task_for_pid()) and
* creating a new thread to call dlopen(). If the dylib or
* bundle exports a function called "run", it will be called
* separately.
*
* EXIT STATUS
* Exits 0 on success, -1 on error.
**********************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdarg.h>
#include <err.h>
#include <dlfcn.h>
#include <mach/mach.h>
#include <mach/mach_error.h>
#include <pthread.h>
#include <sys/param.h>
/***********************************************************************
* Mach Exceptions
***********************************************************************/
extern boolean_t exc_server(mach_msg_header_t *request, mach_msg_header_t *reply);
/**********************************************************************
* Remote task memory
**********************************************************************/
kern_return_t
remote_copyout(task_t task, void* src, vm_address_t dest, size_t n);
kern_return_t
remote_copyin(task_t task, vm_address_t src, void* dest, size_t n);
extern vm_address_t
remote_malloc(task_t task, size_t size);
extern kern_return_t
remote_free(task_t task, vm_address_t addr);
/**********************************************************************
* Remote threads
**********************************************************************/
typedef enum
{
UNINIT, // Remote thread not yet initialized (error returned)
CREATED, // Thread and remote stack created and allocated
RUNNING, // Thread is running
SUSPENDED, // Thread suspended, but still allocated
TERMINATED // Thread terminated and remote stack deallocated
} remote_thread_state_t;
typedef struct
{
remote_thread_state_t state;
task_t task;
thread_t thread;
vm_address_t stack;
size_t stack_size;
} remote_thread_t;
kern_return_t
create_remote_thread( mach_port_t task, remote_thread_t* rt, vm_address_t start_address, int argc, ... );
kern_return_t
join_remote_thread( remote_thread_t* remote_thread, void** return_value );
/**********************************************************************
* Bundle injection
**********************************************************************/
kern_return_t
remote_getpid(task_t task, pid_t* pid);
kern_return_t
inject_bundle( task_t task, const char* bundle_path, void** return_value);
|
C
|
#iclude<stdio>
#nclude<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
Int main()
{
int str[100] = {1,2,3,4,.....,100}
int array[4];
FILE *f;
f = fopen("input.txt" , "w");
FILE *f1;
f1 = fopen("output.txt", "r");
int i,j,status
int sum = 0;
int sum2 = 0;
int sum3 = 0;
int sum4 = 0;
int bigsum = 0;
int pid1;
for(i = 0; i<=3, i++)
{
pid1 = fork();
if(pid1 < 0)
{
printf("child process is not created");
}
else if(pid1 == 0)
{
if(j==0)
{
int m;
for(m=0; m<25; m++)
{
sum = sum + str[m];
}
fprintf(f, "%dn" , sum);
exit(0);
}
}
else if(j==1)
{
int n;
for(n = 25; n<50; n++)
{
sum2 = sum2+str[n];
}
fprintf(f,"%d\n", sum2);
exit(0);
}
else if(j ==2)
{
int h;
for(h = 50; h<75; h++)
{
sum3 = sum3+str[h];
}
fprintf(f,"%d\n", sum3);
exit(0);
}
else if(j ==3)
{
int e;
for(e = 75; e<100; e++)
{
sum4 = sum4+str[e];
}
fprintf(f,"%d\n", sum4);
exit(0);
}
}
else
{
wait(& status);
}
int bs;
for(bs = 0; bs <4; bs++)
{
fscanf(f1, "%d\n", &array[bs];
}
for(bs = 0; bs <4; bs++)
{
bigsum = bigsum +array[bs];
}
printf("Sum is:%d", bigsum);
fclose(f);
fclose(f1);
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
struct Node {
int data;
struct Node *next;
};
void printList(struct Node *n)
{
printf("Nodes: \n");
while (n != NULL)
{
printf("%d\n", n->data);
n = n->next;
}
}
void addNode(struct Node **n, int data)
{
/* n is a pointer to a pointer, head */
struct Node* newNode = NULL;
newNode = malloc(sizeof(struct Node));
newNode->data = data;
/* allocating memory assigning value to new node */
newNode->next = *n;
/* it's next value points to the current first node in the list */
*n = newNode;
/* the reference to the first node in the list, head, now points to newNode */
return;
}
void appendNode(struct Node **n, int data)
{
/* appends new node to list */
struct Node *cursor = *n;
/* duplicates head */
struct Node* newNode = NULL;
newNode = malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
/* initializes newNode with data, and next value pointing to null, as it will be last in list */
if (*n == NULL)
{
/* if head references null, list is empty, so it should reference newNode */
*n = newNode;
return;
}
else
{
while (cursor->next != NULL)
{
/* iterate through list until null pointer indicates last item reached */
cursor = cursor->next;
}
/* last item next pointer points to newNode */
cursor->next = newNode;
return;
}
}
void insertAfter(struct Node *prev, int data)
{
/* functions takes a node, and a value to be placed after the node */
struct Node* newNode = NULL;
newNode = malloc(sizeof(struct Node));
newNode->data = data;
/* allocate new node */
newNode->next = prev->next;
/* newNode points at whatever the preceding node was pointing at */
prev->next = newNode;
/* the previous node now points at newNode */
return;
}
void deleteNode(int key, struct Node **head_ref)
{
/* deletes given node, by traversing the list until ->next is nodeToDelete */
/* assign prevnode->next to nodeToDelete->next, then free nodeToDelete */
struct Node *cursor = *head_ref, *prev;
if (cursor->data == key)
{
*head_ref = cursor->next;
free(cursor);
return;
}
/* while cursor is not null and its data is not key */
while (cursor != NULL && cursor->data != key)
{
/* store prev node, and change cursor to look at next node */
prev = cursor;
cursor = cursor->next;
}
if (cursor == NULL)
{
return;
}
prev->next = cursor->next;
free(cursor);
}
int main(void)
{
struct Node* first = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
first = malloc(sizeof(struct Node));
second = malloc(sizeof(struct Node));
third = malloc(sizeof(struct Node));
first->data = 1;
first->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
int val = 4;
struct Node *head = first;
/* head is a pointer to the first node */
printList(head);
/* addNode is passed the address of head and a value to add */
appendNode(&head, val);
printList(head);
insertAfter(second, 5);
printList(head);
deleteNode(5, &head);
printList(head);
return 0;
}
|
C
|
#include <stdlib.h>
#include <gtk/gtk.h>
struct _MainWindow
{
GtkWidget *pWindow;
GtkWidget *pVBox;
GtkWidget *pEntry;
GtkWidget *pButton;
GtkWidget *pLabel;
};
typedef struct _MainWindow MainWindow;
void OnUpdate(GtkWidget *pEntry, gpointer data);
int main(int argc, char **argv)
{
MainWindow *pApp;
gtk_init(&argc, &argv);
pApp = g_malloc(sizeof(MainWindow));
pApp->pWindow = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(pApp->pWindow), "Le widget GtkEntry");
gtk_window_set_default_size(GTK_WINDOW(pApp->pWindow), 320, 200);
g_signal_connect(G_OBJECT(pApp->pWindow), "destroy", G_CALLBACK(gtk_main_quit), NULL);
pApp->pVBox = gtk_vbox_new(TRUE, 0);
gtk_container_add(GTK_CONTAINER(pApp->pWindow), pApp->pVBox);
/* Creation du GtkEntry */
pApp->pEntry = gtk_entry_new();
/* Insertion du GtkEntry dans la GtkVBox */
gtk_box_pack_start(GTK_BOX(pApp->pVBox), pApp->pEntry, TRUE, FALSE, 0);
pApp->pButton = gtk_button_new_with_label("Copier");
gtk_box_pack_start(GTK_BOX(pApp->pVBox), pApp->pButton, TRUE, FALSE, 0);
pApp->pLabel = gtk_label_new(NULL);
gtk_box_pack_start(GTK_BOX(pApp->pVBox), pApp->pLabel, TRUE, FALSE, 0);
/* Connexion du signal "activate" du GtkEntry */
g_signal_connect(G_OBJECT(pApp->pEntry), "activate", G_CALLBACK(OnUpdate), (gpointer) pApp);
/* Connexion du signal "clicked" du GtkButton */
/* La donnee supplementaire est la GtkVBox pVBox */
g_signal_connect(G_OBJECT(pApp->pButton), "clicked", G_CALLBACK(OnUpdate), (gpointer*) pApp);
gtk_widget_show_all(pApp->pWindow);
gtk_main();
g_free(pApp);
return EXIT_SUCCESS;
}
/* Fonction callback execute lors du signal "activate" */
void OnUpdate(GtkWidget *pEntry, gpointer data)
{
const gchar *sText;
MainWindow *pApp;
/* Recuperation de data */
pApp = (MainWindow*) data;
/* Recuperation du texte contenu dans le GtkEntry */
sText = gtk_entry_get_text(GTK_ENTRY(pApp->pEntry));
/* Modification du texte contenu dans le GtkLabel */
gtk_label_set_text(GTK_LABEL(pApp->pLabel), sText);
}
|
C
|
/*
* Copyright (C) 2017, Vector Li (idorax@126.com). All rights reserved.
*/
/**
* This small program is to detect a singly linked list has a loop or not.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct list_s {
int data;
struct list_s *next;
} list_t;
static void
show(list_t *head)
{
if (head == NULL)
return;
for (list_t *p = head; p != NULL; p = p->next)
printf("%d ", p->data);
printf("\n");
}
static void
fini(list_t *head)
{
list_t *p = head;
while (p != NULL) {
list_t *q = p;
p = p->next;
free(q);
}
}
static void
init(list_t **head, int *a, int n)
{
list_t *new = NULL;
list_t *cur = NULL;
for (int i = 0; i < n; i++) {
new = (list_t *)malloc(sizeof (list_t));
if (new == NULL) /* error: failed to malloc */
return;
new->data = a[i];
new->next = NULL;
if (*head == NULL)
*head = new;
else
cur->next = new;
cur = new;
}
}
static void
loop_init(list_t *head, int index, list_t **tail)
{
if (head == NULL) {
*tail = NULL;
return;
}
/* get the tail node */
list_t *p = head;
while (p->next != NULL)
p = p->next;
*tail = p;
/*
* find the node by index ([1..N]) to init the loop
*
* NOTE: If index == 0, don't init the loop
* If index > length of the list, don't init the loop either
*/
int cnt = index;
list_t *q = head;
while (--cnt > 0 && q != NULL)
q = q->next;
/* now init the loop */
if (cnt == 0)
(*tail)->next = q;
}
static void
loop_fini(list_t *tail)
{
if (tail != NULL)
tail->next = NULL;
}
/**
* Detect a singly linked list has a loop
*/
bool is_loop(list_t *head)
{
list_t *fast = head;
list_t *slow = head;
/*
* If loop does not exist, fast should firstly reach the end
* a) if the length of list is even, fast will be NULL
* b) if the length of list is odd, fast->next will be NULL
*/
while (fast != NULL && fast->next != NULL) {
fast = fast->next->next;
slow = slow->next;
/*
* Well, loop is found as the fast catches up with the slow
*/
if (fast == slow)
return true;
}
return false;
}
/**
* Get the length of the loop if a singly linked list has a loop
*/
int get_loop_length(list_t *head)
{
list_t *fast = head;
list_t *slow = head;
list_t *node = NULL;
/* get a node in the loop */
while (fast != NULL && fast->next != NULL) {
fast = fast->next->next;
slow = slow->next;
if (fast == slow) {
node = slow;
break;
}
}
/* no loop found hence the length should be zero */
if (node == NULL)
return 0;
/* now walk again to get the length of the loop */
int len = 1;
for (list_t *p = node->next; p != node; p = p->next)
len++;
return len;
}
/**
* Get the joint if a singly linked list has a loop
*/
list_t *
get_loop_joint(list_t *head)
{
list_t *fast = head;
list_t *slow = head;
list_t *node = NULL;
/* get a node in the loop */
while (fast != NULL && fast->next != NULL) {
fast = fast->next->next;
slow = slow->next;
if (fast == slow) {
node = slow;
break;
}
}
/* no loop found hence the joint should be NULL */
if (node == NULL)
return NULL;
/*
* The slow walks the loop from the node, and let the fast walk the
* list from its head. They should meet at the joint.
*
* Head Joint
* | |
* O-->O-->O-->O<--O<--O
* | ^
* V |
* O-->O-->O
* \
* Node
*
* x : The length from Head to Joint
* y1: The length from Joint to Node
* y2: The length from Node to Joint
*
* Total steps of the slow walked: x + y1
* Total steps of the fast walked: x + y1 + y2 + y1
* Note the fast and the slow have the same times to move,
* So x + y1 == (x + y1 + y2 + y1) / 2
* ==> 2x + 2y1 == x + 2y1 + y2
* ==> x == y2
*/
fast = head;
slow = node;
while (fast != slow) {
fast = fast->next;
slow = slow->next;
}
return slow;
}
/**
* Get the total length of a singly linked list even though it has a loop
*/
int get_total_length(list_t *head)
{
int len = get_loop_length(head);
list_t *joint = (len != 0) ? get_loop_joint(head) : NULL;
for (list_t *p = head; p != joint; p = p->next)
len++;
return len;
}
/**
* Covert string (its delimiter is ',') to an array of int, which is similar to
* strtok_r(). Note that the caller must free the memory of the array. e.g.
* char *s = "1,2,3,4,5,6"
* return {1, 2, 3, 4, 5, 6}
*/
static int *
str2list(char *s, int *len)
{
int n = 0;
/* get the number of elements in the string */
char *p = s;
while (*p != '\0') {
if (*p == ',')
n++;
p++;
}
n++; /* Note the number of elements == the number of ',' + 1 */
int *out = (int *)malloc(sizeof(int) * n);
if (out == NULL) {
*len = 0;
return NULL;
}
*len = n;
int j = 0;
for (p = s; *p != '\0'; p++) {
int k = 0;
char buf[16] = { 0 }; /* max int is 2 ** 31 - 1 == 2147483647 */
while (*p != ',' && *p != '\0') {
buf[k++] = *p;
p++;
}
*(out + j) = atoi(buf);
j++;
if (*p == '\0')
break;
}
return out;
}
int
main(int argc, char *argv[])
{
if (argc != 3) {
fprintf(stderr, "Usage: %s <num> <n1,n2,...>\n",
argv[0]);
return -1;
}
int idx = atoi(argv[1]);
int n = 0;
int *l = str2list(argv[2], &n);
list_t *head = NULL;
init(&head, l, n); /* create linked list */
free(l); /* destroy l */
show(head);
/* create a loop */
list_t *tail = NULL;
loop_init(head, idx, &tail);
if (is_loop(head)) {
int len = get_loop_length(head);
list_t *joint = get_loop_joint(head);
printf("LOOP FOUND\n");
printf("The length of loop is %d\n", len);
printf("The first joint is %d (%p)\n", joint->data, joint);
} else {
fprintf(stderr, "LOOP NOT FOUND\n");
}
printf("The total length is %d\n", get_total_length(head));
/* destroy the loop */
loop_fini(tail);
fini(head);
return 0;
}
|
C
|
#include "foo.h"
struct foo *g_foo_p = NULL;
void *hold_thread(void *arg)
{
int r = 0;
while (1) {
r = rand() % 5;
sleep(r);
if (r % 2 == 0) {
if (g_foo_p) {
foo_hold(g_foo_p);
fprintf(stderr, "count +1\n");
foo_read(g_foo_p);
} else {
pthread_exit(NULL);
}
}
}
}
void *release_thread(void *arg)
{
int r = 0;
while (1) {
r = rand() % 5;
sleep(r);
if (r % 3 == 0) {
if (g_foo_p) {
if (foo_rele(g_foo_p) == 1) {
g_foo_p = NULL;
} else {
fprintf(stderr, "count -1\n");
foo_read(g_foo_p);
}
} else {
pthread_exit(NULL);
}
}
}
}
int main(int argc, char *argv[])
{
int err;
pthread_t tid1, tid2;
g_foo_p = foo_alloc();
if (!g_foo_p) {
exit(1);
}
foo_read(g_foo_p);
err = pthread_create(&tid1, NULL, hold_thread, NULL);
if (err != 0) {
exit(2);
}
err = pthread_create(&tid2, NULL, release_thread, NULL);
if (err != 0) {
exit(3);
}
err = pthread_join(tid1, NULL);
if (err != 0) {
exit(4);
}
err = pthread_join(tid2, NULL);
if (err != 0) {
exit(5);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
char a[10], b[10], c[10];
void encode()
{
int m, n, i, k, j;
printf("\nEnter the message:");
scanf("%s", a);
printf("\nEnter the crc value:");
scanf("%s", b);
m = strlen(a);
n = strlen(b);
for (i = 0; i < n - 1; i++)
{
a[m + i] = '0';
}
printf("\nHence the message after adding redundancy bits is: %s\n", a);
}
void receivedata()
{
printf("\nEnter the data at the receivers side :");
scanf("%s", &a);
}
void decode()
{
int m, n, i, k, j;
m = strlen(a);
n = strlen(b);
for (i = 0; i < m; i++)
{
c[i] = a[i];
}
k = n;
while (k != (m + 1))
{
if (c[0] == '1')
{
for (i = 1; i < n; i++)
{
if (c[i] == b[i])
{
c[i - 1] = '0';
}
else
{
c[i - 1] = '1';
}
}
if (k != (m))
{
c[n - 1] = a[k];
}
k += 1;
}
else
{
for (i = 1; i < n; i++)
{
c[i - 1] = c[i];
}if (k != (m))
{
c[n - 1] = a[k];
}
k += 1;
}
}
j = 0;
printf("\nThe remainder is ");
for (i = 0; i < n - 1; i++)
{
printf("%c", c[i]);
}
for (i = 0; i < n - 1; i++)
{
if (c[i] != '0')
{
j = 1;
break;
}
}
if (j == 0)
{
printf("\nThe received message is accepted\n");
}
else
{
printf("\n\nThe received message is corrupted, ask the receiver to resend it\n");
}
}
int main()
{
printf("19BCE0488 MANSI RATURI");
encode();
receivedata();
decode();
return (0);
}
|
C
|
/*Ŀx,y,zС*/
//3 2222 11
#include <stdio.h>
int main(int argc, char *argv[])
{
int x,y,z;
scanf("%d %d %d",&x,&y,&z);
if(x<y){ //x<y
if(z<x)
printf("%d %d %d\n",z,x,y);//z<x<y
else if(y<z)
printf("%d %d %d\n",x,y,z);//x<y<z
else
printf("%d %d %d\n",x,z,y);//x<z<y
}
else{ // y<x
if(z<y)
printf("%d %d %d\n",z,y,x);//z<y<x
else if(x<z)
printf("%d %d %d\n",y,x,z);//y<x<z
else
printf("%d %d %d\n",y,z,x);//y<z<x
}
return 0;
}
//ʺϲٵ
|
C
|
/*
* uss.c
* algorithme esclave
* -- UH maitre esclave
*/
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include "pvm3.h"
#include "point.h"
/*
* programme esclave
*/
/* calcul enveloppe de 4 point */
void calcul_pointUH(pb_t *pb)
{
pb->pts1 = point_UH(pb->pts1);
pb->type = PB_FUS;
}
/*
* fusion
*/
void merge_data(pb)
pb_t *pb;
{
pb->taille1 = pb->taille1 + pb->taille2;
pb->pts1 = point_merge_UH(pb->pts1,pb->pts2);
point_free(pb->pts2);
pb->pts2 = NULL;
pb->taille2 = 0;
}
main()
{
extern pb_t *receive_pb();
int parent, sender[1]; /* pere et envoyeur (non utilise) */
pb_t *pb; /* probleme courant */
parent = pvm_parent();
/* tant que l'on recoit un probleme a traiter ... */
while ((pb = receive_pb(parent, sender)) != NULL) {
if (pb->type == PB_UH) /* on traite suivant le cas */
calcul_pointUH(pb);
else
merge_data(pb);
/* et on revoie la solution */
send_pb(parent, pb);
}
pvm_exit();
exit(0);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lglover <lglover@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/12/07 13:22:45 by lglover #+# #+# */
/* Updated: 2019/03/20 13:11:10 by lglover ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int check_line(char **line, char **rem)
{
if (!(*line = ft_strdup(*rem)))
{
ft_strdel(rem);
return (0);
}
return (1);
}
static int fill_line(char **rem, char **line)
{
char *nl_ptr;
if ((nl_ptr = ft_strchr(*rem, '\n')))
{
*nl_ptr = '\0';
if (!check_line(line, rem))
return (-1);
*rem = ft_strcpy(*rem, nl_ptr + 1);
}
else
{
if (!check_line(line, rem))
return (-1);
ft_strdel(rem);
}
return (1);
}
static int reconcat(char **file_data, char *buff)
{
char *tmp;
if (*file_data)
{
tmp = *file_data;
if (!(*file_data = ft_strjoin(*file_data, buff)))
{
ft_strdel(&tmp);
return (0);
}
ft_strdel(&tmp);
return (1);
}
else
{
if (!(*file_data = ft_strdup(buff)))
return (0);
return (1);
}
}
int ft_gnl(const int fd, char **line)
{
char buff[BUFF_SIZE + 1];
static char *data;
long read_result;
if (fd < 0 || !line || (read(fd, buff, 0) < 0) || BUFF_SIZE <= 0)
return (-1);
while ((read_result = read(fd, buff, BUFF_SIZE)))
{
buff[read_result] = '\0';
if (!reconcat(&data, buff))
return (-1);
if (ft_strchr(buff, '\n'))
break ;
}
if (!data || !data[0])
return (0);
return (fill_line(&data, line));
}
|
C
|
/**
* @file ada.c
* @author Julien Esposito
* @brief A Description of the most generic functions used by the
* ADA.
*/
/******************************************************************************/
/******************************************************************************/
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "ada_externals.h"
/******************************************************************************/
/******************************************************************************/
//
//#define DEBUG
//#define NO_CONSOLE
/**
* @fn CustomPrintf
*
* @brief I use the performance ADA as a static lib with my MATLAB environment.
*
* @details In MATLAB any message printed on the standard output is not re-directed to
* the MATLAB console. Hence, I print all my debug messages to a file opened in
* "append" mode, in order to see what I'm doing, and that is done via the
* this CustomPrintf.
*
* @param fmt - the format string, like for "printf".
*
* @return Nothing.
*/
#ifdef DEBUG
void CustomPrintf( char *fmt, ... )
{
va_list argptr;
char msg[ 2048 ];
va_start( argptr, fmt );
vsprintf( msg, fmt, argptr );
va_end( argptr );
#ifdef NO_CONSOLE
FILE* f = fopen( "im_calc_p1.txt", "a" );
fprintf( f, "%s", msg );
fclose( f );
#else
printf( "%s", msg );
#endif
return;
}
#else
void CustomPrintf( char *fmt, ... )
{
( void )fmt;
}
#endif
/**
* @fn ada_sqrt
*
* @brief This function is used to compute the square root of a _uint32_t.
*
* @param accSquared - a _uint32_t value to take the square root form.
*
* @return The square root as a _uint32_t value.
*/
uint32 ada_sqrt( uint32 accSquared )
{
return ( uint32 )sqrtf( ( float )accSquared );
}
|
C
|
#include <stdio.h>
void isprime(int n){
int i,count=0;
for(i=1;i<=n;i++)
if(!(n%i))
count++;
if(count<3)
printf("It is prime");
else
printf("It is not prime");
}
int main(){
int num,i;
printf("Enter number: ");
scanf("%d",&num);
for(i=1;i<=num;i++)
if(!(num%i))
printf("%d\n",i);
isprime(num);
return 0;
}
|
C
|
#include <stdio.h>
int main(void){
char ch1, ch2;
scanf("%c%c", &ch1, &ch2); // ΰ Է
printf("[%c%c]", ch1, ch2); // Էµ
return 0;
}
|
C
|
//
// main.c
// Based On G.P in C
//
// Created by yogendra singh on 3/3/21.
// Copyright © 2021 yadavboy. All rights reserved.
//
//Consider the following series:
//1,1,2,3,4,9,8,27,16,81,32,243,64,729,128,2187...
//This series is a mixture of 2 series – all the odd terms in this series form a geometric series and all the even terms form yet another geometric series.
//Write a program to find the Nth term in the series.
#include <stdio.h>
#include <math.h>
int main(int argc, const char * argv[]) {
int n , a , r , res ,term;
printf("Enter a Number \n ");
scanf("%d" , &n);
// for odd positions : term = (n+1)/2
if (n%2==1) {
a=1;
r=2;
term = (n+1)/2;
res = pow(2,term-1);
printf(" %d is a nth term of the series \n",res );
}
if (n%2==0) {
a=1;
r=3;
term = n/2;
res = pow(3,term-1);
printf(" %d is a nth term of the series \n",res );
}
return 0;
}
|
C
|
#ifndef __VECTOR_H__
#define __VECTOR_H__
//data type that has 3 floats in in.
//typedef struct
//{
//float x, y, z;
//}vec3d;
//typedef float vec3d[3];
//union
typedef union
{
struct
{
float x, y;
};
float v[2];
}Vector2D;
typedef union
{
struct
{
float x, y, z;
};
float v[3];
}Vector3D;
#define vector3d_add(a,b,c) (a.x = b.x +c.x, a.y = b.y + c.y, a.z = b.z + c.z)
#define vector3d_set(a,b,c) (a.x = b, a.y = c, a.z =d)
#define vector2d_add(a,b,c) (a.x = b.x +c.x, a.y = b.y + c.y)
#define vector2d_set(a,b,c) (a.x = b, a.y = c)
#endif
|
C
|
#include "sum.h"
int sum(int a[], int n)
{
if (n==0)
return 0;
else
return (a[n-1])+sum(a,n-1);
}
|
C
|
// *******************************************************
//
// circBufT.c
//
// Support for a circular buffer of uint32_t values on the
// Tiva processor.
// P.J. Bones UCECE
// Last modified: 15.8.2020
//
// *******************************************************
#include "main.h"
#include "circBufT.h"
// *******************************************************
// writeCircBuf: insert entry at the current windex location,
// advance windex, modulo (buffer size).
// *******************************************************
void writeCircBuf(circBuf_t *buffer, uint32_t entry) {
*(buffer->data + buffer->windex) = entry;
buffer->windex++;
if (buffer->windex >= buffer->size)
buffer->windex = 0;
}
// *******************************************************
// readCircBuf: return entry at the current rindex location,
// advance rindex, modulo (buffer size). The function deos not check
// if reading has advanced ahead of writing.
// *******************************************************
uint32_t readCircBuf(circBuf_t *buffer) {
uint32_t entry;
//get the data at the current read index
entry = buffer->data[buffer->rindex];
// Advance the read index
buffer->rindex++;
if (buffer->rindex >= buffer->size)
buffer->rindex = 0;
return entry;
}
|
C
|
#include <stdio.h>
int main(void)
{
int i,sign;
double sum=0;
sign=1;
/*
//1-1/2+1/3-...-1/100
for(i=1;i<=100;i++)
{
sum=sum+sign*1.0/i;
sign=-sign;
//printf("%lf\n",sum);
}
*/
//1/2-1/4+1/6-...-1/100
for(i=2;i<=100;i=i+2)
{
sum=sum+sign*1.0/i;
sign=-sign;
//printf("%lf\n",sum);
}
printf("%lf",sum);
}
|
C
|
/*
This programs collects the data of all text files into one text file.
The files that are packed are deleted from mentioned directory.
*/
#include <stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<dirent.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>
struct fileinfo
{
char name[300];
int size;
};
int main(int argc,char *argv[])
{
if(argc!=3)
{
printf("Invalid Arguments\n");
printf("usage: myexe Directory_name File_name\n");
return -1;
}
DIR *dir=NULL;
struct dirent *statd=NULL;
struct stat statf;
int fddest=0;
char name[300]={'\0'};
struct fileinfo fobj;
int fd=0;
char buf[1024];
int ret=0;
fddest=creat(argv[2],0777);
if(fddest==-1)
{
perror("creat");
return -1;
}
dir=opendir(argv[1]);
if(dir==NULL)
{
perror("opendir");
return -1;
}
chdir(argv[1]);
printf("Names of file are \n");
while((statd=readdir(dir))!=NULL)
{
sprintf(name,"%s/%s",argv[1],statd->d_name);
stat(statd->d_name,&statf);
if((S_ISREG(statf.st_mode)))
{
printf("%s\n",statd->d_name);
printf("%ld\n",statf.st_size);
strcpy(fobj.name,statd->d_name);
fobj.size=statf.st_size;
write(fddest,&fobj,sizeof(fobj));
memset(&fobj,0,sizeof(fobj));
fd=open(statd->d_name,O_RDONLY);
if(fd==-1)
{
perror("read");
return -1;
}
while((ret=read(fd,buf,sizeof(buf)))!=0)
{
write(fddest,buf,ret);
memset(buf,0,sizeof(buf));
}
close(fd);
unlink(statd->d_name);
}
}
closedir(dir);
return 0;
}
|
C
|
#pragma once
#include "als/als_math.h"
struct MeshVertex
{
MeshVertex() = default;
Vec3 position;
Vec3 normal;
Vec2 texCoords;
Vec3 tangent;
Vec3 bitangent;
bool operator==(const MeshVertex &other)
{
return
equals(this->position, other.position) &&
equals(this->normal, other.normal) &&
equals(this->texCoords, other.texCoords) &&
equals(this->tangent, other.tangent) &&
equals(this->bitangent, other.bitangent);
}
};
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define HIGH(X, W) ((X) >> (W >> 1))
//operator priority!
#define LOW(X, W) ((X) & ((1 << (W >> 1)) - 1))
#define INDEX(H, L, W) (H << (W >> 1) | L)
#define SQRU(W) (1 << (W >> 1))
#define CSIZE(U, W) (U >> (W >> 1))
#define POPU(u) do{ \
u = (0x55555555 & u) + (0x55555555 & (u >> 1)); \
u = (0x33333333 & u) + (0x33333333 & (u >> 2)); \
u = (0x0f0f0f0f & u) + (0x0f0f0f0f & (u >> 4)); \
u = (0x00ff00ff & u) + (0x00ff00ff & (u >> 8)); \
u = (0x0000ffff & u) + (0x0000ffff & (u >> 16)); \
} while(0)
#define TRUE 1
#define FALSE 0
struct veb{
int u;
int min, max;
struct veb *summary;
struct veb **cluster;
};
int population(int x);
void travel_veb(struct veb *root);
void swap(int *a, int *b);
struct veb *build_skeleton(int u);
int member(struct veb *root, int x);
int minimum(struct veb *root);
int maximum(struct veb *root);
int predecessor(struct veb *root, int x);
int successor(struct veb *root, int x);
void empty_insert(struct veb *root, int x);
int insert(struct veb *root, int x);
int delete(struct veb *root, int x);
void travel_veb(struct veb *root)
{
int i, u, w, csize;
u = root->u;
w = population(u - 1);
csize = CSIZE(u, w);
// printf("w = %d, csize = %d,", w, csize);
if (root) {
if (u == 2)
printf("veb->u = %d, min = %d, max = %d\n", root->u, root->min, root->max);
else {
printf("veb->u = %d, min = %d, max = %d\n", root->u, root->min, root->max);
travel_veb(root->summary);
for (i = 0; i < csize; i++)
travel_veb(root->cluster[i]);
}
/* when u == 2, cluster == NULL, but for loop access it.
printf("veb->u = %d, min = %d, max = %d\n", root->u, root->min, root->max);
travel_veb(root->summary);
for (i = 0; i < csize; i++)
travel_veb(root->cluster[i]);
*/
}
}
struct veb *
build_skeleton(int u)
{
int i, w, csize;
struct veb *v;
v = (struct veb *)malloc(sizeof (struct veb));
v->u = u;
v->min = v->max = -1;
w = population(u - 1);
csize = CSIZE(u, w);
printf("build test universe = %d, cluster number = %d, cluster universe = %d\n", u, csize, SQRU(w));
if (v->u == 2) {
v->summary = NULL;
v->cluster = NULL;
} else {
v->summary = build_skeleton(csize);
v->cluster = (struct veb **)malloc((sizeof (struct veb)) * csize);
for (i = 0; i < csize; i++)
v->cluster[i] = build_skeleton(SQRU(w));
}
return v;
}
int member(struct veb *v, int x)
{
int w;
w = population(v->u - 1);
if (v->min == x || v->max == x)
return TRUE;
else if (v->u == 2)
return FALSE;
else
return member(v->cluster[HIGH(x, w)], LOW(x, w));
}
int
predecessor(struct veb *v, int x)
{
int w, min_low, pre_cluster, offset;
w = population(v->u - 1);
if (v->u == 2) {
if (x == 1 && v->min == 0)
return 0;
else
return -1;
} else if (v->max != -1 && x > v->max)
return v->max;
else {
min_low = minimum(v->cluster[HIGH(x, w)]);
if (min_low != -1 && LOW(x, w) > min_low) {
offset = predecessor(v->cluster[HIGH(x, w)], LOW(x, w));
return INDEX(HIGH(x, w), offset, w);
} else {
pre_cluster = predecessor(v->summary, HIGH(x, w));
if (pre_cluster != -1) {
offset = maximum(v->cluster[pre_cluster]);
return INDEX(pre_cluster, offset, w);
} else {
if (v->min != -1 && x > v->min)
return v->min;
else
return -1;
}
}
}
}
int
successor(struct veb *v, int x)
{
int w, max_low, offset, succ_cluster;
w = population(v->u - 1);
if (v->u == 2) {
if (x == 0 && v->max == 1)
return 1;
else
return -1;
} else if (v->min != -1 && x < v->min) {
return v->min;
} else {
max_low = maximum(v->cluster[HIGH(x, w)]);
if (max_low != -1 && LOW(x, w) < max_low) {
offset = successor(v->cluster[HIGH(x, w)], LOW(x, w));
return INDEX(HIGH(x, w), offset, w);
} else {
succ_cluster = successor(v->summary, HIGH(x, w));
if (succ_cluster == -1)
return -1;
else {
offset = minimum(v->cluster[succ_cluster]);
return INDEX(succ_cluster, offset, w);
}
}
}
}
int
minimum(struct veb *v)
{
return v->min;
}
int maximum(struct veb *v)
{
return v->max;
}
void test_macro()
{
int i;
long long u = 0x20;
int w = population(u-1);
for (i = 0; i < u; i++)
printf("i = %d\t, word size = %d, high = %d, low = %d, sqru = %d, csize = %d\n",\
i, w, HIGH(i, w), LOW(i, w), SQRU(w), CSIZE(u, w));
}
int population(int u)
{
u = (0x55555555 & u) + (0x55555555 & (u >> 1)); \
u = (0x33333333 & u) + (0x33333333 & (u >> 2)); \
u = (0x0f0f0f0f & u) + (0x0f0f0f0f & (u >> 4)); \
u = (0x00ff00ff & u) + (0x00ff00ff & (u >> 8)); \
u = (0x0000ffff & u) + (0x0000ffff & (u >> 16)); \
return u;
}
void
empty_insert(struct veb *v, int x)
{
v->min = x;
v->max = x;
}
void swap(int *a, int *b)
{
int c;
c = *a;
*a = *b;
*b = c;
}
int
insert(struct veb *v, int x)
{
int w;
if (v->min == -1) {
empty_insert(v, x);
} else {
if (x < v->min)
swap(&x, &(v->min));
if (v->u > 2) {
w = population(v->u - 1);
if (minimum(v->cluster[HIGH(x, w)]) == -1) {
empty_insert(v->cluster[HIGH(x, w)], LOW(x, w));
insert(v->summary, HIGH(x, w));
} else
insert(v->cluster[HIGH(x, w)], LOW(x, w));
}
if (x > v->max)
v->max = x;
}
}
int
delete(struct veb *v, int x)
{
int w, csize;
int first_cluster, offset, summary_max;
w = population(v->u - 1);
csize = CSIZE(v->u, w);
if (v->min == v->max)
v->min = v->max = -1;
else if (v->u == 2) {
if (x == 0)
v->min = v->max;
else
v->max = v->min;
} else {
if (x == v->min) {
first_cluster = minimum(v->summary);
offset = minimum(v->cluster[first_cluster]);
x = INDEX(first_cluster, offset, w);
v->min = x;
}
delete(v->cluster[HIGH(x, w)], LOW(x, w));
if (minimum(v->cluster[HIGH(x, w)]) == -1) {
delete(v->summary, HIGH(x, w));
if (x == v->max) {
summary_max = maximum(v->summary);
if (summary_max == -1)
v->max = v->min;
else
v->max = INDEX(summary_max, maximum(v->cluster[summary_max]), w);
}
} else if (x == v->max)
v->max = INDEX(HIGH(x, w), maximum(v->cluster[HIGH(x, w)]), w);
}
}
int
main()
{
int u = 16;
struct veb *root;
root = build_skeleton(u);
travel_veb(root);
// printf("test population: %d\n", population(u - 1));
// test_macro();
printf("---------------------------insert test---------------------------\n");
insert(root, 2);
insert(root, 3);
insert(root, 4);
insert(root, 5);
insert(root, 7);
insert(root, 14);
insert(root, 15);
travel_veb(root);
printf("---------------------------delete test---------------------------\n");
delete(root, 2);
delete(root, 3);
travel_veb(root);
printf("---------------------------member test---------------------------\n");
printf("4 is %d the vebt\n", member(root, 4));
printf("3 is %d the vebt\n", member(root, 3));
printf("---------------------------predecessor test---------------------------\n");
int j;
for (j = 15; j >= 0; j--)
printf("predecessor of %d is %d\n", j, predecessor(root, j));
printf("---------------------------successor test---------------------------\n");
int i;
for (i = 0; i < 16; i++)
printf("successor of %d is %d\n", i, successor(root, i));
return 0;
}
|
C
|
/*****************************************************************************
*
* File: cellpool.c
* Author: Alex Stivala
* Created: April 2009
*
* Simple cell pool allocator. By allocating a big chunk of memory at
* initialization time, we can just get one cell at a time from it
* in a lock-free manner without having to call malloc() again,
* so that multiple threads can allocate cells from the pool without
* locking.
*
* On Linux,
* gcc version 4.1.0 or greater is required, in order to use the
* __sync_val_compare_and_swap() builtin
* (this module was developed on Linux 2.6.22 (x86) with gcc 4.1.3).
* On Solaris, we use the umem_cache_*() functions instead, rather
* than implement a cell pool allocator ourselves.
* (Actually, we don't since it turns out to be slower+less scalable than
* the trivial cellpool implemented here). Define USE_SOLARIS_UMEM to use
* the umem functions on Solaris.
*
* TODO don't even have facility to free/reuse cells, don't need it
* since we just terminate the process.
* TODO only one cell pool allowed (file static data). Should change
* to have handles so user can allocate different pools.
*
*
* $Id: cellpool.c 2324 2009-05-06 02:44:04Z astivala $
*
*****************************************************************************/
#undef USE_SOLARIS_UMEM /* slower than trivial celpool,. don't use */
#include <stdlib.h>
#include "cellpool.h"
#ifdef USE_SOLARIS_UMEM
#include <umem.h>
#else
#include "atomicdefs.h"
#endif
#ifdef USE_SOLARIS_UMEM
static umem_cache_t *cache; /* The Solaris umem cache */
#else
static void *cellpool; /* The cell pool. */
static size_t cellsize; /* size of a cell */
static size_t poolsize; /* total size of cell pool */
static void *nextcell; /* pointer to next cell in the pool
serialized with CAS logic in cellpool_alloc() */
#endif
/*
* cellpool_alloc()
*
* allocate a new cell of previously intialized size from pool
*
* Parameters:
* None.
*
* Return value:
* Pointer to new cell, or NULL if none available.
*
* Uses static data:
* nextcell -pointer to next cell in cellpool (read/write, CAS serialized)
*/
void *cellpool_alloc(void)
{
#ifdef USE_SOLARIS_UMEM
return umem_cache_alloc(cache, UMEM_DEFAULT);
#else
void *cell, *newnextcell;
#ifdef USE_THREADING
do
{
if ((char *)nextcell >= (char *)cellpool + poolsize)
return NULL;
cell = nextcell;
newnextcell = (char *)cell + cellsize;
}
while (CASPTR(&nextcell,cell,newnextcell) != cell);
#else
if ((char *)nextcell >= (char *)cellpool + poolsize)
return NULL;
cell = nextcell;
newnextcell = (char *)cell + cellsize;
nextcell = newnextcell;
#endif
return cell;
#endif
}
/*
* cellpool_initialize()
*
* initialize the cell pool
*
* Parameters:
* cell_size - Size of each cell
* num_cells - Number of cells to allocate
*
* Return value:
* Pointer to start of cell pool memory (first cell) or NULL
* on failure
*
* Uses static data:
* cellpool - the cell pool (write)
* cellsize - size of each cell (write)
* poolsize - total size of cell pool (write)
* nextcell - pointer to next cell in cellpool (write)
*/
void *cellpool_initialize(size_t cell_size, int num_cells)
{
#ifdef USE_SOLARIS_UMEM
cache = umem_cache_create("cellpool", cell_size, 0,
NULL, NULL, NULL, NULL, NULL, 0);
return cache;
#else
cellsize = cell_size;
poolsize = num_cells * cell_size;
if (!(cellpool = malloc(poolsize)))
return NULL;
nextcell = cellpool;
return cellpool;
#endif
}
|
C
|
#include <stdlib.h>
#include<stdio.h>
int Choose(int i,int map[21][21])
{
int who = 1;
int system(const char *string);
while (1)
{
system("cls");
printf("\n\n1ʼϷ\n\n2˳Ϸ\n\nѡ");
scanf_s("%d", &i);
if (i == 1)
{
DrawMap(map,who);
}
else if (i == 2)
{
exit(0);
}
else
{
system("cls");
continue;
}
}
}
int DrawMap(int map[21][21],int who)
{
system("cls");
int i, j;
for (i = 0; i < 21; i++)
{
map[0][i] = i;
map[i][0] = i;
printf("%d ", map[0][i]);
}
printf("\n\n\n");
for (i = 1; i < 10; i++)
{
printf("%d", map[i][0]);
for (j = 1; j < 10; j++)
{
if (map[i][j] == 0)
{
printf(" ");
}
else
{
printf(" %c", map[i][j]);
}
}
for (j = 10; j < 21; j++)
{
if (map[i][j] == 0)
{
printf(" ");
}
else
{
printf(" %c", map[i][j]);
}
}
printf("\n\n\n");
}
for (i = 10; i < 21; i++)
{
printf("%d", map[i][0]);
if (map[i][1] == 0)
{
printf(" ");
}
else
{
printf(" %c", map[i][1]);
}
for (j = 2; j < 10; j++)
{
if (map[i][j] == 0)
{
printf(" ");
}
else
{
printf(" %c", map[i][j]);
}
}
for (j = 10; j < 21; j++)
{
if (map[i][j] == 0)
{
printf(" ");
}
else
{
printf(" %c", map[i][j]);
}
}
printf("\n\n\n");
}
PutChess(map,who);
system("pause");
}
int PutChess(int map[21][21],int who)
{
char ch;
while (1)
{
int x=0, y=0;
while (who==1)
{
getchar();
printf("ɫַӣԿոֿ:");
scanf_s("\n%d %d", &x, &y);
if (!(x > 0 && x < 21) || !(y > 0 || y < 21)||map[x][y]!=0)
{
printf("Ƿ룡\n");
continue;
}
else
{
map[x][y] = '*';
fflush(stdin);
printf("壿(y/n):");
scanf_s("%c\n", &ch);
if (ch == y)
{
WithDraw(map, x, y);
}
else
{
Judge(map);
who = 2;
DrawMap(map, who);
break;
}
}
}
while (who==2)
{
getchar();
printf("ɫַӣԿոֿ:");
scanf_s("\n%d %d", &x, &y);
if (!(x > 0 && x < 21) || !(y > 0 || y < 21)||map[x][y]!=0)
{
printf("Ƿ룡\n");
continue;
}
else
{
map[x][y] = 'O';
fflush(stdin);
printf("壿(y/n):");
scanf_s("%c\n", &ch);
if (ch == y)
{
WithDraw(map, x, y);
}
else
{
Judge(map);
who = 1;
DrawMap(map, who);
break;
}
}
}
}
}
int WithDraw(int map[21][21],int x,int y)
{
map[x][y] = 0;
return 0;
}
int Judge(int map[21][21])
{
int i = 0, j = 0;
int x = 0, y = 0;
int flag = 0;
for (i = 1; i < 21; i++)
{
for (j = 1; j < 21; j++)
{
if (map[i][j] == '*')
{
for (x = i+1, y = j+1; x < i + 5, y < j + 5; x++, y++)
{
if (map[x][j] == '*')
{
flag = 1;
}
else if (map[i][y] == '*')
{
flag = 1;
}
else if (map[x][y] == '*')
{
flag = 1;
}
else
{
flag = 0;
}
}
for (x = i-1, y = j-1; x >i-5, y > j-5; x--, y--)
{
if (map[x][j] == '*')
{
flag = 1;
}
else if (map[i][y] == '*')
{
flag = 1;
}
else if (map[x][y] == '*')
{
flag = 1;
}
else
{
flag = 0;
}
}
Result(flag);
}
else if (map=='#')
{
flag = 0;
for (x = i+1, y = j+1; x < i + 5, y < j + 5; x++, y++)
{
if (map[x][j] == '#')
{
flag = 2;
}
else if (map[i][y] == '#')
{
flag = 2;
}
else if (map[x][y] == '#')
{
flag = 2;
}
}
for (x = i + 4, y = j + 4; x >= i, y >= j; x--, y--)
{
if (map[x][j] == '#')
{
flag = 2;
}
else if (map[i][y] == '#')
{
flag = 2;
}
else if (map[x][y] == '#')
{
flag = 2;
}
}
Result(flag);
}
}
}
}
int Result(int flag)
{
if (flag == 1)
{
printf("ڷʤ\n");
system("pause");
main();
}
else if (flag == 2)
{
printf("ʤ\n");
system("pause");
main();
}
else
{
return 0;
}
}
int x;
int main()
{
int map[21][21] = { 0 };
Choose(x,map);
}
|
C
|
#include <stdio.h>
int main()
{
int week,days,left;
const int w_d=7;
printf("if you want to end the program,enter 0.\n");
printf("please input the days:");
scanf("%d",&days);
while(days>0){
week=days/w_d;
left=days%w_d;
printf("%d day(s) are/is %d week(s) and %d day(s).\n",days,week,left);
printf("please input the days:");
scanf("%d",&days);
}
return 0;
}
|
C
|
// Reordering a list of strings in alphabetical order using array of pointers
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void reorder(int n, char *x[]);
int main()
{
int i,n=0;
char *x[10];
printf("Enter each string on a separate line below\n\n");
printf("Enter END when finished\n\n");
// read in the list of strings
do
{
// allocate memory
x[n] = (char*) malloc (12 * sizeof(char));
printf("String %d : ",n+1);
scanf(" %[^\n]", x[n]);
}while (strcmpi(x[n++],"END"));
// reorder the list of strings
reorder(--n,x);
// display the reordered list of strings
printf("\n\nReordered list of strings : \n");
for (i=0;i<n;i++) {
printf("\nstring %d: %s",i+1,x[i]);
}
return 0;
}
void reorder(int n, char *x[]) {
char *temp;
int i,item;
for(item=0;item<n-1;++item) {
// find the lowest of the remaining strings
for (i=item+1;i<n;++i) {
if (strcmpi(x[item], x[i]) > 0) {
// interchange the two strings
temp = x[item];
x[item] = x[i];
x[i] = temp;
}
}
}
return;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
void print_list(Node* head){
Node* current_node = head->next;
printf("%d ", head->data);
while (current_node != NULL){
printf("%d ", current_node->data);
current_node = current_node->next;
}
printf("\n");
}
void insert_node(Node* head, int data){
Node* current_node = head;
while (current_node->next != NULL){
current_node = current_node->next;
}
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = data;
new_node->next = NULL;
current_node->next = new_node;
}
void delete_node(Node* head, int data){
if (head->data == data){
*head = *head->next;
return;
}
Node* prev_node = head;
Node* current_node = head->next;
while (current_node != NULL){
if(current_node->data == data){
prev_node->next = current_node->next;
return;
}
prev_node = current_node;
current_node = current_node->next;
}
}
int main(){
Node* head = (Node*)malloc(sizeof(Node));
head->data = 1;
head->next = NULL;
print_list(head);
insert_node(head, 2);
insert_node(head, 3);
insert_node(head, 4);
insert_node(head, 5);
print_list(head);
delete_node(head, 1);
delete_node(head, 2);
delete_node(head, 5);
print_list(head);
return 0;
}
|
C
|
#include <mpi.h>
#include <stdio.h>
int main(int argc, char **argv) {
int myrank = 0;
int size = 0;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
printf("Process Hello from %d (total %d)\n", myrank, size);
MPI_Finalize();
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void selct(char *items,int count);
int main(void)
{
char s[255];
printf("Enter a string:");
scanf("%s",s);
selct(s,strlen(s));
printf("The sorted string is :%s\n",s);
return 0;
}
void selct(char *items,int count)
{
register int a,b,c;
int exchange;
char t;
for(a = 0;a<count-1;++a)
{
exchange = 0;
c = a;
t = items[a];
for(b =a +1;b<count;b++)
{
if(items[b]<t)
{
c = b;
t = items[b];
exchange = 1;
}
}
if(exchange)
{
items[c] = items[a];
items[a] = t;
}
}
}
|
C
|
/*ͨλña8
3λõ
ϸڿҪǡ
*/
#include <stdio.h>
int
main(void)
{
int nvar = 2;
printf("%d %d\r\n", nvar, nvar<<3);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* koch.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ovirchen <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/06/16 14:10:55 by ovirchen #+# #+# */
/* Updated: 2018/06/16 14:10:56 by ovirchen ### ########.fr */
/* */
/* ************************************************************************** */
#include "fractol.h"
static void draw_lines(t_mlx *all, int x_1, int y_1, int x_2, int y_2)
{
int x1;
int x2;
int y1;
int y2;
int d;
int x;
int y;
if (x_1 > x_2)
{
x1 = x_2;
x2 = x_1;
y1 = y_2;
y2 = y_1;
}
else
{
x1 = x_1;
x2 = x_2;
y1 = y_1;
y2 = y_2;
}
x = x1;
y = y1;
if (abs_int(x2 - x1) > abs_int(y2 - y1))
{
while (x <= x2)
{
y = y1 + (x - x1) * (y2 - y1) / (x2 - x1);
put_pixel(all, (int)x, (int)y, 0xffffff);
x++;;
}
}
else
{
d = y2 > y1 ? 1 : -1;
while (d * y <= d * y2)
{
x = x1 + (y - y1) * (x2 - x1) / (y2 - y1);
put_pixel(all, (int)x, (int)y, 0xffffff);
y += d;
}
}
}
static void draw_koch(t_mlx *all, double x1, double y1, double x2, double y2, int i)
{
double xd, yd, xb, yb, xc, yc, cos60, sin60;
if (i == 0)
{
draw_lines(all, x1, y1, x2, y2);
}
else
{
xb = x1 + (x2 - x1) * 1/3;
yb = y1 + (y2 - y1) * 1/3;
xd = x1 + (x2 - x1) * 2/3;
yd = y1 + (y2 - y1) * 2/3;
cos60 = 0.5;
sin60 = -0.866;
xc = xb + (xd - xb) * cos60 - sin60 * (yd - yb);
yc = yb + (xd - xb) * sin60 + cos60 * (yd - yb);
draw_koch(all, x1, y1, xb, yb, i - 1);
draw_koch(all, xb, yb, xc, yc, i - 1);
draw_koch(all, xc, yc, xd, yd, i - 1);
draw_koch(all, xd, yd, x2, y2, i - 1);
}
}
void koch(t_mlx *all)
{
int i;
i = -1;
while (++i < WIN_X * WIN_Y * 4)
all->map[i] = 0x000000;
draw_koch(all, 0, WIN_Y - 200, WIN_X - 1, WIN_Y - 200, all->max_iter);
mlx_put_image_to_window(all->mlx, all->win, all->img, 0, 0);
}
|
C
|
#include <stdio.h>
#include <math.h>
struct Point {
double X, Y;
};
double distance(struct Point a, struct Point b){
return sqrt(pow(a.X-b.X, 2) + pow(a.Y-b.Y, 2));
}
int main(){
struct Point A={1,10};
struct Point B={3,4};
printf("%.4f",distance(A,B));
}
|
C
|
#include "common.h"
char *minWindow(char *s, char *t) {
int left = 0;
int right = 0;
int start = 0;
int window[256] = {0};
int needs[256] = {0};
int i = 0;
int t_len = strlen(t);
int needs_size = 0;
for (i = 0; i < t_len; i++) {
if (needs[t[i]] == 0) {
needs_size++;
}
needs[t[i]]++;
}
int s_len = strlen(s);
int match = 0;
int minLen = INT_MAX;
while (right < s_len) {
char c1 = s[right];
if (needs[c1]) {
window[c1]++;
if (window[c1] == needs[c1]) {
match++;
}
}
right++;
while (match == needs_size) {
if (right - left < minLen) {
start = left;
minLen = right - left;
}
char c2 = s[left];
if (needs[c2]) {
window[c2]--;
if (window[c2] < needs[c2]) {
match--;
}
}
left++;
}
}
if (minLen == INT_MAX) {
return "";
} else {
char *a = malloc(s_len + 1);
memcpy(a, &s[start], minLen);
a[minLen] = '\0';
return a;
}
}
void test_minWindow() {
char *res = NULL;
res = minWindow("ADOBECODEBANC", "ABC");
ASSERT_EQ(strcmp(res, "BANC"), 0);
}
|
C
|
int titleToNumber(char* s) {
int sum = 0;
for(int i = 0; s[i] != '\0'; i++)
{
sum = sum*26 + (s[i] - 'A' + 1);
}
return sum;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "calculadora.h"
#include "Validador.h"
int mostrarResultado(int x, int y, int sum, int res, int prod, float div, int facx, int facy);
int main()
{
int x;
int y;
int option;
int isuma;
int iresta;
int iproducto;
float fdivision;
int ifactorialx;
int ifactorialy;
int flagprimeroperando=0;
int flagsegundooperando=0;
int flagcalcular=0;
printf("==========================================\n");
printf("== Elija una opcion ==\n");
printf("==========================================\n");
printf("| 1. Ingresar 1er operando (A=x) |\n");
printf("| 2. Ingresar 2do operando (B=y) |\n");
printf("| 3. Calcular todas las operaciones |\n");
printf("| 4. Informar resultados |\n");
printf("| 5. Salir |\n");
printf("==========================================\n");
do
{
printf("Ingrese una opcion \n\n");
scanf("%d/n/n", &option);
switch(option)
{
case 1:
printf("Ingresar 1er operando (A=x): ");
scanf("%d/n/n", &x);
flagprimeroperando=1;
break;
case 2:
printf("Ingresar 2do operando (B=y)): ");
scanf("%d/n/n", &y);
flagsegundooperando = 1;
break;
case 3:
if(flagprimeroperando == 1 && flagsegundooperando == 1)
{
isuma = suma(x,y);
iresta = resta(x, y);
iproducto = multiplicar(x, y);
fdivision = dividir(x, y);
ifactorialx = factorial(x);
ifactorialy = factorial(y);
flagcalcular = 1;
}
else
{
printf("Debe ingresar primer y segundo operando \n\n");
};
break;
case 4:
if(flagcalcular == 1)
{
mostrarResultado(x, y, isuma, iresta, iproducto, fdivision, ifactorialx, ifactorialy);
}
else
{
printf("Debe calcular primero los resultados");
};
break;
}
}while(!(option == 5));
return 0;
}
int mostrarResultado(int x, int y, int sum, int res, int prod, float div, int facx, int facy)
{
printf("El valor del 1er operando A=%d \n\n", x);
printf("El valor del 2do operando B=%d \n\n", y);
//suma
printf("El resultado de A+B es: %d \n\n",sum);
//resta
printf("El resultado de A-B es: %d \n\n",res);
//division
if(!(y==0))
{
printf("El resultado de A/B es: %.2f \n\n", div);
}
else
{
printf("No es posible dividir por cero\n\n");
}
//producto
printf("El resultado de A*B es: %d\n\n", prod);
//factorial
printf("El factorial de A es: %d y El factorial de B es: %d\n\n", facx, facy);
return 0;
}
|
C
|
#include<stdio.h>
struct node
{
struct node * link;
int info;
};
void reverse(struct node **head)
{
struct *prev=NULL;
struct *cur=head;
struct *after;
while(cur!=NULL)
{
after=cur->link;
cur->link=prev;
prev=cur;
cur=after;
}
}
|
C
|
#include <stdio.h>
#include <cs50.h>
#include <math.h>
/*This program gives you back an exact number of coins depending on how much change you have.
Please enter how much change is owed.*/
void Give_Change(int Change_Owed);
/*Asks for owed change, converts from dollars to cents, rounds, then runs through
Give change function*/
int main(void)
{
float Change_Owed_Float;
do
{
printf("How much change is owed? $: \n");
Change_Owed_Float = GetFloat();
}
while (Change_Owed_Float < 0.00);
//Converting from dollars to cents, then rounding, then converting from float to int
int Change_Owed = roundf(Change_Owed_Float * 100);
//Running change provided through Give Change function
Give_Change(Change_Owed);
}
//Calculates exact number of coins
void Give_Change(int Change_Owed)
{
int Num_Coins, quarters, dimes, nickels, pennies;
quarters = 25;
dimes = 10;
nickels = 5;
pennies = 1;
Num_Coins = 0;
//Calculates number of quarters, if any
while (Change_Owed >= 25)
{
Change_Owed = (Change_Owed - quarters);
Num_Coins++;
}
//Calculates number of dimes, if any
while (Change_Owed >= 10)
{
Change_Owed = (Change_Owed - dimes);
Num_Coins++;
}
//Calculate number of nickels, if any
while (Change_Owed >= 5)
{
Change_Owed = (Change_Owed - nickels);
Num_Coins++;
}
//Calculates number of pennies, if any
while (Change_Owed >= 1)
{
Change_Owed = (Change_Owed - pennies);
Num_Coins++;
}
//prints number of coins to the screen
printf("%d\n", Num_Coins);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <ctype.h>
#include <string.h>
#include <time.h>
#include "hash_map.h"
#define MAX_LINE 1000
typedef uint8_t byte;
enum INSTRUCTION_TYPE { A_INSTRUCTION, C_INSTRUCTION, LABEL };
enum A_INSTRUCTION_MODE { A_VALUE, A_SYMBOL };
int16_t rom_address = 0;
int16_t ram_address = 16;
typedef struct instruction {
enum INSTRUCTION_TYPE type;
enum A_INSTRUCTION_MODE a_instr_mode;
char* instruction_text;
union {
char* label;
char* symbol;
int16_t value;
struct {
char* dest;
char* comp;
char* jump;
} c_fields;
} data;
} instruction;
typedef struct c_node {
instruction* instr;
struct c_node* next;
} c_node;
char* int_to_bin16(int16_t num);
void assemble(c_node* head_instruction, Map m, char* dest);
instruction* new_instruction()
{
return (instruction*)malloc(sizeof(instruction));
}
void install_predefined_symbols(Map m)
{
map_add(m,"SP",int_to_bin16(0));
map_add(m,"LCL",int_to_bin16(1));
map_add(m,"ARG",int_to_bin16(2));
map_add(m,"THIS",int_to_bin16(3));
map_add(m,"THAT",int_to_bin16(4));
map_add(m,"R0",int_to_bin16(0));
map_add(m,"R1",int_to_bin16(1));
map_add(m,"R2",int_to_bin16(2));
map_add(m,"R3",int_to_bin16(3));
map_add(m,"R4",int_to_bin16(4));
map_add(m,"R5",int_to_bin16(5));
map_add(m,"R6",int_to_bin16(6));
map_add(m,"R7",int_to_bin16(7));
map_add(m,"R8",int_to_bin16(8));
map_add(m,"R9",int_to_bin16(9));
map_add(m,"R10",int_to_bin16(10));
map_add(m,"R11",int_to_bin16(11));
map_add(m,"R12",int_to_bin16(12));
map_add(m,"R13",int_to_bin16(13));
map_add(m,"R14",int_to_bin16(14));
map_add(m,"R15",int_to_bin16(15));
map_add(m,"SCREEN",int_to_bin16(16384));
map_add(m,"KBD",int_to_bin16(24576));
}
char* get_comp_inst(char* comp_instr)
{
if (strcmp(comp_instr, "0") == 0) {
return "0101010";
}
if (strcmp(comp_instr, "1") == 0) {
return "0111111";
}
if (strcmp(comp_instr, "-1") == 0) {
return "0111010";
}
if (strcmp(comp_instr, "D") == 0) {
return "0001100";
}
if (strcmp(comp_instr, "A") == 0) {
return "0110000";
}
if (strcmp(comp_instr, "!D") == 0) {
return "0001101";
}
if (strcmp(comp_instr, "!A") == 0) {
return "0110001";
}
if (strcmp(comp_instr, "-D") == 0) {
return "0001111";
}
if (strcmp(comp_instr, "-A") == 0) {
return "0110011";
}
if (strcmp(comp_instr, "D+1") == 0) {
return "0011111";
}
if (strcmp(comp_instr, "A+1") == 0) {
return "0110111";
}
if (strcmp(comp_instr, "D-1") == 0) {
return "0001110";
}
if (strcmp(comp_instr, "A-1") == 0) {
return "0110010";
}
if (strcmp(comp_instr, "D+A") == 0) {
return "0000010";
}
if (strcmp(comp_instr, "D-A") == 0) {
return "0010011";
}
if (strcmp(comp_instr, "A-D") == 0) {
return "0000111";
}
if (strcmp(comp_instr, "D&A") == 0) {
return "0000000";
}
if (strcmp(comp_instr, "D|A") == 0) {
return "0010101";
}
if (strcmp(comp_instr, "M") == 0) {
return "1110000";
}
if (strcmp(comp_instr, "!M") == 0) {
return "1110001";
}
if (strcmp(comp_instr, "-M") == 0) {
return "1110011";
}
if (strcmp(comp_instr, "M+1") == 0) {
return "1110111";
}
if (strcmp(comp_instr, "M-1") == 0) {
return "1110010";
}
if (strcmp(comp_instr, "D+M") == 0) {
return "1000010";
}
if (strcmp(comp_instr, "D-M") == 0) {
return "1010011";
}
if (strcmp(comp_instr, "M-D") == 0) {
return "1000111";
}
if (strcmp(comp_instr, "D&M") == 0) {
return "1000000";
}
if (strcmp(comp_instr, "D|M") == 0) {
return "1010101";
}
return "0101010";
}
char* get_dest_inst(char* dest_instr)
{
if (dest_instr == NULL) {
return "000";
}
if (strcmp(dest_instr, "M") == 0) {
return "001";
}
if (strcmp(dest_instr, "D") == 0) {
return "010";
}
if (strcmp(dest_instr, "MD") == 0) {
return "011";
}
if (strcmp(dest_instr, "A") == 0) {
return "100";
}
if (strcmp(dest_instr, "AM") == 0) {
return "101";
}
if (strcmp(dest_instr, "AD") == 0) {
return "110";
}
if (strcmp(dest_instr, "AMD") == 0) {
return "111";
}
return "000";
}
char* get_jmp_inst(char* jmp_instr)
{
if (jmp_instr == NULL) {
return "000";
}
if (strcmp(jmp_instr, "JGT") == 0) {
return "001";
}
if (strcmp(jmp_instr, "JEQ") == 0) {
return "010";
}
if (strcmp(jmp_instr, "JGE") == 0) {
return "011";
}
if (strcmp(jmp_instr, "JLT") == 0) {
return "100";
}
if (strcmp(jmp_instr, "JNE") == 0) {
return "101";
}
if (strcmp(jmp_instr, "JLE") == 0) {
return "110";
}
if (strcmp(jmp_instr, "JMP") == 0) {
return "111";
}
return "000";
}
c_node* list_add(c_node* head, instruction* instr)
{
c_node* new = malloc(sizeof(c_node));
new->instr = instr;
new->next = NULL;
if (head == NULL)
{
return new;
}
c_node* temp = head;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = new;
return head;
}
void print_instructions(c_node* head)
{
c_node* temp = head;
int i = 0;
while (temp != NULL) {
printf("%d. %s\n", i, temp->instr->instruction_text);
temp = temp->next;
i++;
}
}
char* int_to_bin16(int16_t num)
{
int i = 16; // number of bits
char* binary = (char*) malloc(i + 1);
binary[i] = '\0';
while(i > 0) {
binary[i-1] = (num & 1) ? '1' : '0';
i--;
num >>=1;
}
return binary;
}
instruction* parse_line (char line[], Map m)
{
int len = strlen(line);
if (!len) return NULL;
instruction* c = new_instruction();
c->instruction_text = malloc(strlen(line) + 1);
strcpy(c->instruction_text, line);
if (line[0] == '@') {
c->type = A_INSTRUCTION;
if (isdigit(line[1]) || line[1] == '-') {
char digits[6];
for (int i = 1; i <= 6; i++) {
digits[i-1] = line[i];
}
c->data.value = atoi(digits);
c->a_instr_mode = A_VALUE;
} else {
char* symbol = malloc(len);
for (int i = 1; i <= len; i++) {
symbol[i - 1] = line[i];
}
c->data.symbol = symbol;
c->a_instr_mode = A_SYMBOL;
}
rom_address++;
} else if (line[0] == '(') {
char* label = malloc(len-1);
// error handling: check that last char is ')'
c->type = LABEL;
for (int i = 1; i < len - 1; i++) {
label[i - 1] = line[i];
}
label[len-1] = '\0';
c->data.label = label;
if (map_get(m, label) != NULL) {
return NULL; // should signal error for duplicate labels
}
map_add(m, label, int_to_bin16(rom_address));
} else {
c->type = C_INSTRUCTION;
char* dest = malloc(sizeof(char) * 4);
char* comp = malloc(sizeof(char) * 4);
char* jump = malloc(sizeof(char) * 4);
int i = 0;
char* comp_ptr;
char* jmp_ptr;
if ((comp_ptr = strstr(line, "="))) {
while(line[i] != '=') {
dest[i] = line[i];
i++;
}
}
if ((jmp_ptr = strstr(line,";"))) {
for (i=1; i < 4; i++) {
jump[i-1] = *(jmp_ptr + i);
}
}
if (!comp_ptr) {
// we dont have dest
i = 0;
while(line[i] != ';') {
comp[i] = line[i];
i++;
}
} else if (jmp_ptr) {
// we have both dest and jump
i = 1;
while ((comp_ptr + i) != jmp_ptr) {
comp[i] = *(comp_ptr + i);
i++;
}
} else {
// we dont have jump
i = 1;
while (*(comp_ptr + i) != '\0') {
comp[i-1] = *(comp_ptr + i);
i++;
}
}
jump[3] = '\0';
comp[3] = '\0';
dest[3] = '\0';
c->data.c_fields.jump = jump;
c->data.c_fields.comp = comp;
c->data.c_fields.dest = dest;
rom_address++;
}
return c;
}
char* get_destination_filename(char* source_filename)
{
size_t substr_len = strlen(source_filename) - 3;
char* dest = malloc(substr_len + 5);
memcpy(dest, source_filename, substr_len);
strcat(dest,"hack");
return dest;
}
int get_instruction(char* line, FILE* fptr)
{
int i = 0;
line[i] = '\0';
char c;
while (1)
{
c = fgetc(fptr);
if (c == EOF) return -1;
if (c == '/' && i > 0 && line[i-1] == '/')
{
line[--i] = '\0';
while((c = fgetc(fptr)) != '\n' && c != EOF) {}
return c==EOF ? -1: 1;
}
else if (c == '\n')
{
line[i] = '\0';
return 1;
}
else if (!isspace(c))
{
line[i++] = c;
}
}
}
int main (int argc, char** argv)
{
clock_t t;
t = clock();
char* source_filename = argv[1];
FILE* fptr = fopen(source_filename,"r");
if (fptr == NULL) {
printf("File '%s' does not exist.\n", source_filename);
exit(1);
}
c_node* head = NULL;
Map m = new_map();
char* dest_filename = get_destination_filename(source_filename);
char c, line[MAX_LINE];
int i = 0;
instruction* instr = NULL;
install_predefined_symbols(m);
int should_continue;
do {
should_continue = get_instruction(line, fptr);
instr = parse_line(line,m);
if (instr != NULL) {
head = list_add(head,instr);
}
} while (should_continue != -1);
fclose(fptr);
print_instructions(head);
assemble(head, m, dest_filename);
t = clock() - t;
double time_taken = ((double)t)/CLOCKS_PER_SEC; // in seconds
printf("Time taken: %f\n", time_taken);
return 0;
}
void write_instruction(FILE *fptr, char* instruction)
{
fprintf(fptr, "%s\n", instruction);
}
void assemble(c_node* head, Map m, char* dest)
{
c_node* temp = head;
FILE* fptr = fopen(dest, "w");
char* bin_instr = NULL;
while (temp != NULL) {
instruction* instr = temp->instr;
switch(instr->type) {
case A_INSTRUCTION:
bin_instr = instr->a_instr_mode == A_SYMBOL ? map_get(m, instr->data.symbol) : int_to_bin16(instr->data.value);
if (bin_instr == NULL) {
bin_instr = int_to_bin16(ram_address++);
map_add(m, instr->data.symbol, bin_instr);
}
write_instruction(fptr, bin_instr);
break;
case C_INSTRUCTION:
bin_instr = malloc(sizeof(char) * 17);
strcpy(bin_instr, "111");
strcat(bin_instr, get_comp_inst(instr->data.c_fields.comp));
strcat(bin_instr, get_dest_inst(instr->data.c_fields.dest));
strcat(bin_instr, get_jmp_inst(instr->data.c_fields.jump));
write_instruction(fptr, bin_instr);
break;
case LABEL:
break;
}
if (bin_instr != NULL) {
// free(bin_instr);
bin_instr = NULL;
}
temp=temp->next;
}
fclose(fptr);
}
|
C
|
/**
******************************************************************************
* @file bsp_usart.c
* @version V1.0
* @date 2013-xx-xx
* @brief õprintfڣضprintf
******************************************************************************
* @attention
*
* ʵƽ̨: F103-ָ STM32
* ̳ :http://www.firebbs.cn
* Ա :https://fire-stm32.taobao.com
*
******************************************************************************
*/
#include "bsp_usart.h"
#define BSP_UART_RX_MAX 64
typedef struct
{
unsigned char buf[BSP_UART_RX_MAX];
unsigned short index;
unsigned char finish;
} bsp_usart_rx;
static bsp_usart_rx rx_buf;
/**
* @brief USART GPIO ,
* @param
* @retval
*/
void USART_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
// GPIOʱ
DEBUG_USART_GPIO_APBxClkCmd(DEBUG_USART_GPIO_CLK, ENABLE);
// ʱ
DEBUG_USART_APBxClkCmd(DEBUG_USART_CLK, ENABLE);
// USART TxGPIOΪ츴ģʽ
GPIO_InitStructure.GPIO_Pin = DEBUG_USART_TX_GPIO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(DEBUG_USART_TX_GPIO_PORT, &GPIO_InitStructure);
// USART RxGPIOΪģʽ
GPIO_InitStructure.GPIO_Pin = DEBUG_USART_RX_GPIO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(DEBUG_USART_RX_GPIO_PORT, &GPIO_InitStructure);
// ôڵĹ
// ò
USART_InitStructure.USART_BaudRate = DEBUG_USART_BAUDRATE;
// ֳ
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
// ֹͣλ
USART_InitStructure.USART_StopBits = USART_StopBits_1;
// Уλ
USART_InitStructure.USART_Parity = USART_Parity_No ;
// Ӳ
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
// ùģʽշһ
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
// ɴڵijʼ
USART_Init(DEBUG_USARTx, &USART_InitStructure);
NVIC_InitStructure.NVIC_IRQChannel = DEBUG_USART_IRQ;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
USART_ITConfig(DEBUG_USARTx, USART_IT_RXNE, ENABLE);
USART_ITConfig(DEBUG_USARTx, USART_IT_IDLE, DISABLE);
//USART_Cmd(USART2, ENABLE);
USART_ClearFlag(DEBUG_USARTx, USART_FLAG_TC);
// ʹܴ
USART_Cmd(DEBUG_USARTx, ENABLE);
rx_buf.finish = 0;
rx_buf.index = 0;
}
///ضc⺯printfڣضʹprintf
int fputc(int ch, FILE *f)
{
/* һֽݵ */
USART_SendData(DEBUG_USARTx, (uint8_t) ch);
/* ȴ */
while (USART_GetFlagStatus(DEBUG_USARTx, USART_FLAG_TXE) == RESET);
return (ch);
}
///ضc⺯scanfڣдʹscanfgetcharȺ
int fgetc(FILE *f)
{
/* ȴ */
while (USART_GetFlagStatus(DEBUG_USARTx, USART_FLAG_RXNE) == RESET);
return (int)USART_ReceiveData(DEBUG_USARTx);
}
void bsp_usart_send_str(unsigned char *str, int len)
{
int i;
for(i=0; i<len; i++)
{
USART_SendData(DEBUG_USARTx, (uint8_t)str[i]);
while(USART_GetFlagStatus(DEBUG_USARTx, USART_FLAG_TXE) == RESET);
}
}
unsigned char bsp_uart_get_rx_buf(unsigned char **buf, unsigned short* len)
{
if(rx_buf.finish)
{
*buf = rx_buf.buf;
*len = rx_buf.index;
return 1;
}
else
{
return 0;
}
}
void bsp_uart_rx_reset(void)
{
int i;
rx_buf.finish = 0;
rx_buf.index = 0;
for(i=0; i<BSP_UART_RX_MAX; i++)
{
rx_buf.buf[i] = 0;
}
}
void USART1_IRQHandler(void)
{
}
void USART2_IRQHandler(void)
{
if(USART_GetITStatus(USART2,USART_IT_RXNE) == SET)
{
if(rx_buf.finish == 0)
{
if(rx_buf.index == 0)
{
USART_ITConfig(DEBUG_USARTx, USART_IT_IDLE, ENABLE);
}
rx_buf.buf[rx_buf.index%128] = USART_ReceiveData(USART2);
rx_buf.index++;
}
}
if(USART_GetITStatus(USART2, USART_IT_IDLE) != RESET)
{
rx_buf.finish = 1;
USART_ITConfig(USART2, USART_IT_IDLE, DISABLE);
}
}
void USART3_IRQHandler(void)
{
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
char* strcpy(char* dest, const char* src)
{
char* inicio = dest;
while(*src)
{
*dest = *src;
}
*dest = '\0';
return inicio;
}
size_t strlen(const char* s)
{
size_t l = 0;
while(*s)
{
l++;
s++;
}
return l;
}
char* reemplazar_subcadena(char* s, const char* t, const char* r)
{
size_t l = strlen(t);
char aux[strlen(s)];
int coincidencias = 0;
while(*s)
{
if(*s == *t)
{
if(coincidencias == l)
{
}
}
}
}
int main()
{
char s[100] = "ana lana pana a veces retrocede sana";
char t[] = "ana";
char r[] = "soleado";
printf(reemplazar_subcadena());
}
|
C
|
#include<stdio.h>
char map[101][101];
char flag[101][101];
int queue[10000];
int main() {
int n, m, k, i, j, v;
int r, c, rc = 0;
int head, tail;
scanf("%d %d %d", &n, &m, &k);
for (i=1; i<=n; i++) for (j=1; j<=m; j++) {
map[i][j] = 0;
flag[i][j] = 0;
}
for (i=0; i<k; i++) {
scanf("%d %d", &r, &c);
map[r][c] = 1;
}
for (i=1; i<=n; i++) for (j=1; j<=m; j++) {
if (map[i][j]==0) continue;
if (flag[i][j]) continue;
head = tail = 0;
queue[head++] = (i<<16)|j;
flag[i][j] = 1;
while(tail<head) {
v = queue[tail++];
r = v>>16; c = v&0xffff;
if (r-1>=1&&map[r-1][c]&&flag[r-1][c]==0) { flag[r-1][c]=1; queue[head++]=((r-1)<<16)|c; }
if (r+1<=n&&map[r+1][c]&&flag[r+1][c]==0) { flag[r+1][c]=1; queue[head++]=((r+1)<<16)|c; }
if (c-1>=1&&map[r][c-1]&&flag[r][c-1]==0) { flag[r][c-1]=1; queue[head++]=(r<<16)|(c-1); }
if (c+1<=m&&map[r][c+1]&&flag[r][c+1]==0) { flag[r][c+1]=1; queue[head++]=(r<<16)|(c+1); }
}
if (rc<head) rc = head;
}
printf("%d\n", rc);
return 0;
}
|
C
|
#include<stdio.h>
int main(){
int a =2,b=4;
a=a+b; //a->6
b =a-b; //b->2
a = a-b; //a->4
return 0;
}
|
C
|
#include<stdio.h>
struct node
{
char c;
struct node *next;
};
struct node *create(struct node *head,char ch)
{
struct node *newRecord,*temp;
newRecord=(struct node *)malloc(sizeof(struct node));
newRecord->c=ch;
newRecord->next=NULL;
temp=head;
if(head==NULL)
head=newRecord;
else
{
while(temp->next!=NULL)
temp=temp->next;
temp->next=newRecord;
}
return head;
}
void display(struct node *head)
{
struct node *temp;
for(temp=head;temp!=NULL;temp=temp->next)
{
printf("%c",temp->c);
}
}
void reconstruct(struct node *head)
{
char construct[100];
int i=0;
struct node *temp;
for(temp=head;temp!=NULL;temp=temp->next)
{
construct[i]=temp->c;
i++;
}
construct[i]='\0';
printf("\n Reconstructed string is \t ");
printf("%s",construct);
}
void main()
{
int i;
char string[100];
struct node *head=NULL;
printf("Enter the string \t ");
gets(string);
for(i=0;i<strlen(string);i++)
{
head=create(head,string[i]);
}
printf("The Display of Link LIST \t ");
display(head);
reconstruct(head);
getch();
}
|
C
|
#include <stdio.h>
#include <string.h>
#include "WheelTimer.h"
#include "LinkedListApi.h"
void
print_(char *str){
printf("%s\n", str);
}
void wrapper_print(void *arg, int arg_size){
char *str = (char*)arg;
print_(str);
}
int
main(int argc, char **argv){
timer_t *wt = init_wheel_timer(); //initialize wall clock timer
/* Register the events to be triggered with Wheel timer now. */
wheel_timer_elem_t *wt_elem = register_app_event(wt, wrapper_print, "ben_event", strlen("ben_event"),12633, 1);
wt_elem = register_app_event(wt, wrapper_print, "Oana_event", strlen("Oana_event"), 5, 1); // special case when ben_event and Oana_event is triggered at 15th slot!
start_wheel_timer(wt); /* Wheel timer has started running in a separte thread. */
scanf("\n");
return 0;
}
|
C
|
//
// ex02_Task3.c
// Infor2_Exercise
//
// Created by 谭特 on 17/3/17.
// Copyright © 2017年 谭特. All rights reserved.
//
#include <stdio.h>
int isReverse(char A[], char B[]) {
//check if one or two of them are empty
if(A[0] == '\0' && B[0] == '\0'){
return 1;
}
if(A[0] == '\0' && B[0] != '\0'){
return 0;
}
if(B[0] == '\0' && A[0] != '\0'){
return 0;
}
//now we know both of them are unempty, get the length of them
int lenA=1, lenB=1;
for(; A[lenA]!='\0'; lenA++){
}
for(; B[lenB]!='\0'; lenB++){
}
//A and B should have the same length
if(lenA != lenB){
return 0;
}
for(int i=0; i<lenA; i++){
if(A[i] != B[lenA-i-1]){
return 0;
}
}
return 1;
}
int main(){
char A1[] = "";
char B1[] = "";
char A2[] = "";
char B2[] = "a";
char A3[] = "abac";
char B3[] = "cabab";
char A4[] = "cbbac";
char B4[] = "cabcc";
char A5[] = "cacb";
char B5[] = "bcac";
printf("Result1: %d\n", isReverse(A1, B1));
printf("Result2: %d\n", isReverse(A2, B2));
printf("Result3: %d\n", isReverse(A3, B3));
printf("Result4: %d\n", isReverse(A4, B4));
printf("Result5: %d\n", isReverse(A5, B5));
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* philo_bonus_print.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: agidget <agidget@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/08/11 15:31:44 by agidget #+# #+# */
/* Updated: 2021/08/11 16:32:47 by agidget ### ########.fr */
/* */
/* ************************************************************************** */
#include "philo_bonus.h"
void print_dead(t_philo *phil, long cur_time, int i)
{
sem_wait(phil->info->sem_dead);
if (cur_time - phil[i].last_meal > phil->info->t_die * 1e3)
{
printf("%.f %d died\n", cur_time * 1e-3, phil[i].num);
exit(1);
}
else
sem_post(phil->info->sem_dead);
}
void my_sleep(t_philo *phil, struct timeval start, int process, int i)
{
long cur_time;
long time_to;
t_gen *info;
info = phil->info;
cur_time = time_passed(&start);
if (process == EAT)
time_to = info->t_eat * 1e3 + cur_time;
if (process == SLEEP)
time_to = info->t_sleep * 1e3 + cur_time;
while (cur_time < time_to)
{
usleep(50);
cur_time = time_passed(&start);
print_dead(phil, cur_time, i);
}
}
void all_ate(t_philo *phil, int i)
{
phil[i].ate_num++;
sem_wait(phil->info->sem_ate);
if ((i == phil->info->qnt - 1) && phil[i].ate_num == phil->info->q_to_eat)
{
printf("All philos ate %d times\n", phil->info->q_to_eat);
exit(EXIT_SUCCESS);
}
else
sem_post(phil->info->sem_ate);
}
void one_philo(struct timeval start, t_philo *phil, int i)
{
long cur_time;
sem_wait(phil->info->sem_one);
if (phil->info->qnt == 1)
{
cur_time = time_passed(&start);
while (cur_time < phil->info->t_die * 1e3)
{
usleep(50);
cur_time = time_passed(&start);
}
printf("%.f %d died\n", cur_time * 1e-3, phil[i].num);
exit(EXIT_SUCCESS);
}
else
sem_post(phil->info->sem_one);
}
void print_status(struct timeval start, t_philo *phil, int i, int msg)
{
long cur_time;
sem_wait(phil->info->sem_print);
cur_time = time_passed(&start);
print_dead(phil, cur_time, i);
if (msg == FORK1)
{
printf("%.f %d has taken a fork\n", cur_time * 1e-3, phil[i].num);
one_philo(start, phil, i);
}
if (msg == FORK2)
printf("%.f %d has taken a fork\n", cur_time * 1e-3, phil[i].num);
if (msg == EAT)
{
printf("%.f %d is eating\n", cur_time * 1e-3, phil[i].num);
phil[i].last_meal = cur_time;
}
if (msg == SLEEP)
{
all_ate(phil, i);
printf("%.f %d is sleeping\n", cur_time * 1e-3, phil[i].num);
}
if (msg == THINK)
printf("%.f %d is thinking\n", cur_time * 1e-3, phil[i].num);
sem_post(phil->info->sem_print);
}
|
C
|
#include<stdio.h>
#include<string.h>
void main()
{
char s[30];
int i,count=0,l;
printf("Enter the string:");
scanf("%s",s);
l=strlen(s);
for(i=0;i<l;i++)
{
if(isdigit(s[i]))
{
count++;
}
}
if(count==l)
printf("\nNumeric");
else
printf("\n Not Numeric");
}
|
C
|
/*
* Class: CS 452
* Assignment: HW 3
* Author: Colby Blair
* Date Due: February xxth, 2012
*
* Comments: Works with AVR STK500 and an Atmega8515L (Atmege32 untested
* yet).
*
*/
#include <inttypes.h>
#include <avr/io.h>
#include <avr/pgmspace.h>
#include <avr/interrupt.h>
/*factor in which to scale down the button time count (cnt)*/
#define TIME_SCALE 7U
/*Music stuff*/
#define SONG_SIZE 9
int SONG_INDEX = 1;
uint8_t SONG[SONG_SIZE];
//0 for false, 1 for true
uint8_t ENABLE_MUSIC = 0;
uint8_t NOTE_COUNT = 0;
/*LED Echo stuff*/
uint8_t cnt = 0u; /*counts how long switch is pressed*/
uint8_t led_cnt = 0x00;
uint8_t which_switch = 0x00; /*records which switch is pressed*/
void delay (unsigned int dly)
{
unsigned int i;
for(i = dly; i != 0; i--) ;
}
/*Interrupt stuff*/
void init_Ex1(void)
{
//DDRB = 0xFF; // Set Port B as output
//TCCR0 = (1<<CS02)|(1<<CS00); // Timer clock = Sysclk/1024
TCCR0 = (1<<CS02)|(1<<CS10);
TIFR = 1<<TOV0; // Clear TOV0, any pending interrupts
TIMSK = 1<<TOIE0; // Enable Timer0 Overflow interrupt
} // END init_Ex1
void init_Ex2(void)
{
/*Output Compare Mode*/
TCCR1B = (1<<CS02)|(1<<CS10);
TCCR1B = ((1 << CS10) | (1 << CS11));
//TCCR1B = (1<<CS02);
/*Overflow Mode
TCCR1B = (1<<CS02)|(1<<CS10);
TIFR = 1<<TOV0; // Clear TOV0, any pending interrupts
TIMSK = (1<<TOIE0)|(1<<TOIE1);// Enable Timer0 and Timer1 Overflow interrupt
*/
}
// void interrupt [TIMER0_OVF_vect] ISR_TOV0 (void)
ISR(TIMER0_OVF_vect)
{
cnt++;
if(cnt == 15)
{
ENABLE_MUSIC = 1;
}
else if (cnt == 30)
{
/*reset count*/
cnt = 0;
/*LED Echo stuff*/
//PORTB = ~(led_cnt | which_switch);
PORTB = ~(led_cnt & 0xF0);
led_cnt -= 0xF0; //increment only for pins 4-7
//led_cnt += 16u; //increment only for pins 4-7
/*make sure led_cnt never has bits set in the lower 4 pins*/
led_cnt &= 0xF0;
/*Music Stuff*/
ENABLE_MUSIC = 0;
if(SONG_INDEX == SONG_SIZE - 1)
{
SONG_INDEX = 0; //start over song
}
else
{
SONG_INDEX++;
}
}
if(ENABLE_MUSIC == 1)
{
//PORTB = ~0x02;
}
else
{
//PORTB = ~0x01;
}
} // end ISR
ISR(TIMER1_OVF_vect)
{
//PORTB = ~PORTB;
}
void play_note(uint8_t period, uint8_t count)
{
if(period == 0)
{
PORTB = ~(~PORTB & 0xFE); // Toggle the LED
}
else
{
if (TCNT1 >= period)
{
PORTA = ~PORTA; // Toggle the Speaker
PORTB = ~(~PORTB | 0x02); // Toggle the LED
TCNT1 = 0; // Reset timer value
}
}
}
int main(void)
{
/*make Port B and A an output*/
DDRA = 0xff;
DDRB = 0xff;
/*make Port D an input*/
DDRD = 0x00;
/*shut off all LEDs*/
PORTB = ~0x00;
/*enable timer*/
init_Ex1();
init_Ex2();
/* Enable Interrupts */
sei();
SONG[0] = 90;
SONG[1] = 82;
SONG[2] = 76;
SONG[3] = 69;
SONG[4] = 62;
SONG[5] = 55;
SONG[6] = 49;
SONG[7] = 43;
SONG[8] = 0;
//SONG[1] = 10;
while(1)
{
play_note(SONG[SONG_INDEX], 1);
}
return(0);
}
|
C
|
#include <stdio.h>
int main ()
{
int height;
printf("plss enter your height");
scanf("%d", &height);
if(height>182)
{ printf("you are eligible for sports");
}
if(height==182)
{printf("YOU CAN WATCH THE MATCH");}
if(height<182)
{printf("u can_t even see the match");}
}
|
C
|
#include <r.h>
#include <stdio.h>
#include <math.h>
int main(void)
{
xorshift_state_initalize();
const size_t N = 1<<4;
printf("vec_t unit_vectors(size_t i) { switch(i %% %zu) { ", 2*N*N);
for(size_t i = 0; i < N; i++) {
for(size_t j = 0; j < (N*2); j++) {
float x = sin(M_PI*(i+1)/N)*cos(M_PI*j/N),
y = sin(M_PI*(i+1)/N)*sin(M_PI*j/N),
z = cos(M_PI*(i+1)/N);
printf("case %zu: return vec(%f, %f, %f); \n", 2*N*i + j, x, y, z);
}
}
printf("} return vec(0,0,0);}\n");
return 0;
}
|
C
|
/************************************************************************
*
* Compiler implementation for imperative programming language IFJ18
*
* Autors:
* Sasák Tomáš - xsasak01
* Venkrbec Tomáš - xvenkr01
* Krajči Martin - xkrajc21
* Dižová Natália - xdizov00
*
***********************************************************************/
#include "scanner.h"
// This constant is numerical difference between builtin functions with return value moved or not
#define NOCALL_CALL_DIFFERENCE 22
// Macros for instruction inside instruction list
#define DEFVAR 228
// User's functions
#define FUN_DEF 200
#define FUN_END 201
#define FUN_CALL 202 // function return is going to be saved
#define NOFUN_CALL 216 // function return value is not going to be saved
// If calls
#define IF_CALL 203
#define ELSE_CALL 204
#define IF_END 205
#define IF_COND_END 260
// While calls
#define WHILE_CALL 206
#define WHILE_END 207
#define WHILE_COND_END 238
// Built-in functions
#define INPUTS_CALL 208
#define INPUTI_CALL 209
#define INPUTF_CALL 210
#define PRINT_CALL 211
#define LENGTH_CALL 212
#define SUBSTR_CALL 213
#define ORD_CALL 214
#define CHR_CALL 215
#define NOINPUTS_CALL 230
#define NOINPUTI_CALL 231
#define NOINPUTF_CALL 232
#define NOPRINT_CALL 233
#define NOLENGTH_CALL 234
#define NOSUBSTR_CALL 235
#define NOORD_CALL 236
#define NOCHR_CALL 237
#define CONCAT_CALL 253
#define CONCAT_END 254
// Operators
#define ADD 217 // '+'
#define SUB 218 // '-'
#define MUL 219 // '*'
#define DIV 220 // '/'
#define MOVE 221 // '='
#define EQ 222 // '=='
#define LT 223 // '<'
#define LE 224 // '<='
#define GT 225 // '>'
#define GE 226 // '>='
#define NE 227 // '!='
#define CONCAT 252 // string + string
// Data stack instructions
#define EXPRESSION_CALL 255
#define EXPRESSION_END 256
#define ADDS 241
#define SUBS 242
#define MULS 243
#define DIVS 244
#define LTS 246
#define GTS 247
#define EQS 248
#define PUSHS 249
#define POPS 250
#define NOTS 251
// Empty instruction
#define NOP 299
typedef struct tokenList tTList;
typedef struct instructionList tIList;
typedef struct instructionNode tInstr;
typedef struct pointerNode tPtr;
typedef struct pointerList tPList;
/**
* Structure used for deallocating strings which are shared for multiple tokens to prevent double free (SEGABRT).
* Structure works as ADS single-linked list.
*/
typedef struct pointerList
{
tPtr *head; //< Pointer to the head of the single-linked list.
tPtr *active; //< Pointer to the last member of the list, which speed's up adding new member to the list.
}pointerList;
/**
* Structure which signifies one member(node) of single-linked list with strings to prevent double free.
* @see tTList
*/
typedef struct pointerNode
{
string freed; //< String which is going to get free.
tPtr *next; //< Pointer to the next member(node).
}pointerNode;
/**
* Structure ADS single-linked list which contains parameters saved as tokens of ONE instruction in instruction list.
* Example: ord(s, i) - token s and token i is in this list.
* @see tIList
*/
typedef struct tokenList
{
tToken param; //< Token which signifies one parameter of instruction.
tTList *next; //< Pointer to the next parameter. (single-linked list)
}tokenList;
/**
* Structure which signifies one instruction with parameters inside instruction list (single-linked list ADS).
* @see tIList
*/
typedef struct instructionNode
{
int instr; //< Macro of one instruction generated by parser, macros are in code_generator.h.
tTList *params; //< Pointer to the parameters of instruction (single-linked list).
tInstr *next; //< Pointer to the next instruction.
}instructionNode;
/**
* Structures which is main structure of the code generator, this ADS (single-linked list) signifies inside mid-code of compiler which is generated by parser, after parsing, this list is submited for code generator
* to generate final compiled code.
*/
typedef struct instructionList
{
tInstr *head; //< First generated instruction, head of the list.
tInstr *active; //< Latest generated instruction, to speed appending of list.
}instructionList;
/**
* This global structure is code generator data structure, which holds final list instructions
* and requests for builtted-in functions.
*/
typedef struct codegenData
{
tIList *ilist;
bool lengthRequest;
bool substrRequest;
bool ordRequest;
bool chrRequest;
int uniqueCounter;
bool inExpression;
}tcgData;
tcgData cgData;
tToken choose_return(tInstr *instruction);
void init_plist(tPList *plist);
void init_ilist(tIList *instrs);
void init_cgData();
void insert_instr(tIList *instrs, int instr);
void insert_param(tIList *instrs, tToken param);
void insert_ptr(tPList *plist, string freed);
bool search_ptr(tPList *ptr, string freed);
void free_ilist(tIList *instrs);
void free_plist(tPList *plist);
void generate_code();
void generate_instruction(FILE *f, tInstr *instruction);
int generate_if(FILE *f, tInstr *instruction, bool scoped, int uniqueIf);
int generate_while(FILE *f, tInstr *instruction, bool scoped, int uniqueWhile);
|
C
|
#pragma once
#ifndef STUDIO_H_
#define STUDIO_H_
typedef struct {
int id; //ӳID
char name[30]; //ӳ
int rowsCount; //λ
int colsCount; //λ
int seatsCount;
} studio_t;
//˫
typedef struct studio_node {
studio_t data; //ʵ
struct studio_node *next; //ָ
struct studio_node *prev; //ǰָ
} studio_node_t, *studio_list_t;
int Studio_Srv_Add(const studio_t *data);
int Studio_Srv_Modify(const studio_t *data);
int Studio_Srv_DeleteByID(int ID);
int Studio_Srv_FetchByID(int ID, studio_t *buf);
int Studio_Srv_FetchAll(studio_list_t list);
//ͨIDlistвҶӦӳ
studio_node_t *Studio_Srv_FindByID(studio_list_t list, int ID);
#endif //STUDIO_H_
|
C
|
/**
* @file app.h
* @brief 声明应用层的几个函数
* @author Shaobo Wang
* @date 2018-5-21
* @version A001
* @par Copyright (c): Shaobo Wang
*/
#ifndef APP_H
#define APP_H
/**
* 第一个应用层操作函数,接收8001,8002端口数据,计算结果发送给8003
* @param[in] argc 创建线程时传入的参数
*/
void* app_read_pthread_func_f(void* argc);
/**
* 第二个应用层操作函数,接收8004端口数据,计算结果发送给8004
* @param[in] argc 创建线程时传入的参数
*/
void* app_read_pthread_func_s(void* argc);
/**
* 第三个应用层操作函数,接收8005,8006,8007端口数据,计算结果发送给8007,8008
* @param[in] argc 创建线程时传入的参数
*/
void* app_read_pthread_func_t(void* argc);
/**
* 应用层写操作函数
* @param[in] argc 创建线程时传入的参数
*/
void* app_write_pthread_func(void* argc);
/**
* 用来创建前三个应用层操作线程的函数
*/
void app_read(void);
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
//#define MAXNUM 100
typedef char DataType;
struct SeqList
{
int MAXNUM;
int n;
DataType * element;
};
typedef struct SeqList *PSeqList;
PSeqList createNullList_seq(int m){
PSeqList palist = (PSeqList)malloc(sizeof(struct SeqList));
if(palist != NULL){
palist -> element =(DataType *)malloc(sizeof(DataType) * m);
if(palist ->element){
palist->MAXNUM = m;
palist->n=0;
return(palist);
}
else
free(palist);
}
printf("Out of space!! \n");
return NULL;
}
int isNullList_seq(PSeqList palist){
return (palist->n == 0);
}
int locate_seq(PSeqList palist,DataType x){
int q;
for(q=0;q<palist->n;q++)
if(palist->element[q] ==x) return(q);
return (-1);
}
int insertPre_seq(PSeqList palist,int p,DataType x){
int q;
if(palist->n >=palist->MAXNUM){
printf("Overflow! \n");
return(0);
}
if(isNullList_seq(palist)){
palist->element[0] = x;
palist->n=1;
return(1);
}
if(p<0||p>palist->n){
printf("Not exist! \n");
}
for(q=palist->n - 1;q >= p;q--){
palist->element[q+1] = palist->element[q];
palist->element[p] = x;
palist->n = palist->n + 1;
return (1);
}
}
int insertPost_seq(PSeqList palist,int p,DataType x){
int q;
if(palist->n >=palist->MAXNUM){
printf("Overflow! \n");
return(0);
}
if(isNullList_seq(palist)){
palist->element[0] = x;
palist->n=1;
return(1);
}
if(p<0||p>palist->n){
printf("Not exist! \n");
}
for(q=palist->n - 1;q >= p + 1;q--){
palist->element[q+1] = palist->element[q];
palist->element[p+1] = x;
palist->n = palist->n + 1;
return (1);
}
}
int deleteP_seq(PSeqList palist,int p){
int q;
if(p<0 || p>palist->n-1){
printf("Not exist! \n");
return(0);
}
for(q=p;q<palist->n-1;q++)
palist->element[q] = palist->element[q+1];
palist->n = palist->n-1;
return(1);
}
void main(){
int STATUS;
PSeqList a= createNullList_seq(1000);
STATUS = insertPre_seq(a,10,'A');
printf("STATUS=%d\n",STATUS);
printf("a.elemnet=%c----a.MAXNUM=%d-----a.n=%d\n",a->element[1],a->MAXNUM,a->n);
printf("a ==%d",a);
}
|
C
|
#include <stdio.h>
#include "graphlist.h"
int addEdgeTest();
int removeEdgeTest();
int addVertexTest();
int removeVertexTest();
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Wrong arguments count");
return -1;
}
char *inputFile = argv[1];
char *outputFile = argv[2];
struct Graph *graph = createGraphFromFile(inputFile);
printGraph(graph, NULL);
if (findVertexById(graph, 6) == NULL) addVertex(graph, 6);
addEdge(graph, 1, 6);
printGraph(graph, outputFile);
// Tests
printf("addEdgeTest: %s\n", !addEdgeTest() ? "success" : "error");
printf("removeEdgeTest: %s\n", !removeEdgeTest() ? "success" : "error");
printf("addVertexTest: %s\n", !addVertexTest() ? "success" : "error");
printf("removeVertexTest: %s\n", !removeVertexTest() ? "success" : "error");
return 0;
}
struct Graph *createTestGraph(int from, int to) {
struct Graph *graph = createGraph(to - from + 1);
graph->size = to - from + 1;
for (int i = 0; i <= to - from; ++i) {
struct Vertex vertex;
vertex.id = from++;
vertex.firstNeighbour = NULL;
graph->vertexes[i] = vertex;
}
return graph;
}
int addEdgeTest() {
struct Graph *graph = createTestGraph(1, 10);
struct Node *node;
addEdge(graph, 1, 2);
struct Vertex *vertex1 = &graph->vertexes[0];
struct Vertex *vertex2 = &graph->vertexes[1];
node = vertex1->firstNeighbour;
if (!(node != NULL &&
node->vertex == vertex2 &&
node->next == NULL))
return -1;
node = vertex2->firstNeighbour;
if (!(node != NULL &&
node->vertex == vertex1 &&
node->next == NULL))
return -1;
addEdge(graph, 1, 2);
node = vertex1->firstNeighbour;
if (!(node != NULL &&
node->vertex == vertex2 &&
node->next == NULL))
return -1;
node = vertex2->firstNeighbour;
if (!(node != NULL &&
node->vertex == vertex1 &&
node->next == NULL))
return -1;
struct Vertex *vertex3 = &graph->vertexes[2];
addEdge(graph, 1, 3);
node = vertex1->firstNeighbour;
if (!(node != NULL &&
((node->vertex == vertex2 && node->next != NULL && node->next->vertex == vertex3) ||
(node->vertex == vertex3 && node->next != NULL && node->next->vertex == vertex2)) &&
node->next->next == NULL))
return -1;
node = vertex3->firstNeighbour;
if (!(node != NULL &&
node->vertex == vertex1 &&
node->next == NULL))
return -1;
return 0;
}
int removeEdgeTest() {
struct Graph *graph = createTestGraph(1, 10);
struct Vertex *vertex1 = &(graph->vertexes[0]);
struct Node node1;
node1.vertex = vertex1;
node1.next = NULL;
struct Vertex *vertex2 = &(graph->vertexes[1]);
struct Node node2;
node2.vertex = vertex2;
node2.next = NULL;
struct Vertex *vertex3 = &(graph->vertexes[2]);
struct Node node3;
node3.vertex = vertex3;
node3.next = NULL;
vertex1->firstNeighbour = &node2;
vertex2->firstNeighbour = &node1;
removeEdge(graph, 1, 2);
if (!(vertex1->firstNeighbour == NULL &&
vertex2->firstNeighbour == NULL))
return -1;
vertex1->firstNeighbour = &node2;
vertex1->firstNeighbour->next = &node3;
vertex2->firstNeighbour = &node1;
vertex3->firstNeighbour = &node1;
removeEdge(graph, 1, 2);
if (!(vertex1->firstNeighbour == &node3 &&
vertex1->firstNeighbour->next == NULL &&
vertex2->firstNeighbour == NULL &&
vertex3->firstNeighbour == &node1 &&
vertex3->firstNeighbour->next == NULL))
return -1;
vertex1->firstNeighbour = &node2;
vertex1->firstNeighbour->next = &node3;
vertex2->firstNeighbour = &node1;
vertex3->firstNeighbour = &node1;
removeEdge(graph, 1, 3);
if (!(vertex1->firstNeighbour == &node2 &&
vertex1->firstNeighbour->next == NULL &&
vertex2->firstNeighbour == &node1 &&
vertex2->firstNeighbour->next == NULL &&
vertex3->firstNeighbour == NULL))
return -1;
return 0;
}
int addVertexTest() {
struct Graph *graph = createGraph(4);
int size = 0;
for (int i = 0; i < 16; ++i) {
addVertex(graph, i);
if (graph->size != ++size) return -1;
for (int j = 0; j <= i; ++j) {
if (graph->vertexes[j].id == i) goto vertexIsFound;
}
return -1;
vertexIsFound:;
}
return 0;
}
int removeVertexTest() {
struct Graph *graph = createTestGraph(1, 10);
struct Node node1;
struct Node node2;
struct Vertex *vertex1 = &graph->vertexes[0];
node1.vertex = vertex1;
node1.next = NULL;
vertex1->firstNeighbour = &node2;
struct Vertex *vertex2 = &graph->vertexes[1];
node2.vertex = vertex2;
node2.next = NULL;
vertex2->firstNeighbour = &node1;
removeVertex(graph, 1);
if (graph->size != 9) return -1;
for (int i = 0; i < 9; ++i) {
if (graph->vertexes[i].id == 1) return -1;
if (graph->vertexes[i].firstNeighbour == &node1) return -1;
}
return 0;
}
|
C
|
#define BOOL_OBJC
#include <stdio.h>
#include <bool.h>
int main(int argc, char* argv[])
{
// Declare and initialise boolean variables
BOOL b1 = YES;
BOOL b2 = NO;
// Print the boolean variables as strings to standard output
printf("Bool values: %s, %s\n", BLSTR(b1), BLSTR(b2));
// Print integer representation of boolean variables to standard output
printf("Integer values: %d, %d\n", b1, b2);
// Declare and initialise integer variables with the boolean values:
// ...using BLINT(boolean)
int i1 = BLINT(b1);
// ...using simple assignment
int i2 = b2;
return 0;
}
/*
Expected Output:
Bool values: true, false
Integer values: 1, 0
*/
|
C
|
#include "sort.h"
/**
* bubble_sort - sorts an array of integers in ascending order using the
* Bubble sort algorithm
*
* @array: Pointer to the beginning of an array
* @size: The size of the array
*
* Return: Nothing
*/
void bubble_sort(int *array, size_t size)
{
int flag = 1, tmp = 0;
size_t i;
if (size < 2 || !array)
return;
while (flag == 1)
{
flag = 0;
for (i = 0; i < size - 1; i++)
{
if (array[i] > array[i + 1])
{
tmp = array[i];
array[i] = array[i + 1];
array[i + 1] = tmp;
print_array(array, size);
flag = 1;
}
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void multiplicacaoMatrizFloat( float *m, float *n, float *p, int tamanho )
{
int i;
int j;
int k;
for ( i = 0; i < tamanho; ++i )
for ( j = 0; j < tamanho; ++j )
{
float soma = 0;
for ( k = 0; k < tamanho; ++k )
{
float a = m[ i * tamanho + k ];
float b = n[ k * tamanho + j ];
soma += a * b;
}
p[ i * tamanho + j ] = soma;
}
}
void multiplicacaoMatrizDouble( double *m, double *n, double *p, int tamanho )
{
int i;
int j;
int k;
for ( i = 0; i < tamanho; ++i )
for ( j = 0; j < tamanho; ++j )
{
double soma = 0;
for ( k = 0; k < tamanho; ++k )
{
double a = m[ i * tamanho + k ];
double b = n[ k * tamanho + j ];
soma += a * b;
}
p[ i * tamanho + j ] = soma;
}
}
void geraMatrizDefaultFloat( float *m, float *n, int tamanho )
{
int i = 0;
int j = 0;
for ( i = 0; i < tamanho; ++i )
{
for ( j = 0; j < tamanho; ++j )
{
m[ i*tamanho + j ] = 4;
n[ i*tamanho + j ] = 5;
}
}
}
void geraMatrizDefaultDouble( double *m, double *n, int tamanho )
{
int i = 0;
int j = 0;
for ( i = 0; i < tamanho; ++i )
{
for ( j = 0; j < tamanho; ++j )
{
m[ i*tamanho + j ] = 4;
n[ i*tamanho + j ] = 5;
}
}
}
void imprimeMatrizFloat( float *a, int tamanho )
{
int i = 0;
int j = 0;
for ( i = 0; i < tamanho; ++i )
{
for ( j = 0; j < tamanho; ++j )
{
printf("%.2f ", a[ i + j ]);
}
printf("\n");
}
}
void imprimeMatrizDouble( double *a, int tamanho )
{
int i = 0;
int j = 0;
for ( i = 0; i < tamanho; ++i )
{
for ( j = 0; j < tamanho; ++j )
{
printf("%.2lf ", a[ i + j ]);
}
printf("\n");
}
}
void criaMatrizesDouble( double **m, double **n, double **p, int tamanho )
{
int N = tamanho * tamanho;
(*m) = (double *)malloc( sizeof( double ) * N );
(*n) = (double *)malloc( sizeof( double ) * N );
(*p) = (double *)malloc( sizeof( double ) * N );
if ( m == NULL || n == NULL || p == NULL )
{
puts("Erro ao alocar as matrizes");
exit( 1 );
}
}
void criaMatrizesFloat( float **m, float **n, float **p, int tamanho )
{
int N = tamanho * tamanho;
(*m) = (float *)malloc( sizeof( float ) * N );
(*n) = (float *)malloc( sizeof( float ) * N );
(*p) = (float *)malloc( sizeof( float ) * N );
if ( m == NULL || n == NULL || p == NULL )
{
puts("Erro ao alocar as matrizes");
exit( 1 );
}
}
int main( int argc, char *argv[] )
{
int tamanho;
/*float *m = NULL;
float *n = NULL;
float *p = NULL;*/
double *m = NULL;
double *n = NULL;
double *p = NULL;
if ( argc < 2 )
{
tamanho = 1000;
}
else
{
tamanho = atoi( argv[ 1 ] );
}
/*criaMatrizesFloat( &m, &n, &p, tamanho );
geraMatrizDefaultFloat( m, n, tamanho );
multiplicacaoMatrizFloat( m, n, p, tamanho );*/
criaMatrizesDouble( &m, &n, &p, tamanho );
geraMatrizDefaultDouble( m, n, tamanho );
multiplicacaoMatrizDouble( m, n, p, tamanho );
imprimeMatrizDouble( m, tamanho );
printf("------------------------------------\n\n");
imprimeMatrizDouble( n, tamanho );
printf("------------------------------------\n\n");
imprimeMatrizDouble( p, tamanho );
/*imprimeMatrizFloat( m, tamanho );
printf("------------------------------------\n\n");
imprimeMatrizFloat( n, tamanho );
printf("------------------------------------\n\n");
imprimeMatrizFloat( p, tamanho );*/
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void actualizarRecuperados(int id, int recuperados);
void invertirCadena(char cadena[]);
void ordenarCaracteres(char cadena[]);
int main()
{
char cadena1[50]="Hola";
char cadena2[50]="algoritmo";
printf("%s\n", cadena1);
invertirCadena(cadena1);
printf("%s\n", cadena1);
printf("%s\n", cadena2);
ordenarCaracteres(cadena2);
printf("%s\n", cadena2);
return 0;
}
void invertirCadena(char cadena[])
{
char aux;
int largoCadena=strlen(cadena);
for(int i=0; i<largoCadena; i++)
{
for(int j = i + 1; j < largoCadena; j++)
{
aux=cadena[i];
cadena[i]=cadena[j];
cadena[j]=aux;
}
}
}
void ordenarCaracteres(char cadena[])
{
char aux;
int largoCadena=strlen(cadena);
for(int i=0; i<largoCadena; i++)
{
for(int j = i + 1; j < largoCadena; j++)
{
if(strcasecmp(cadena[i], cadena[j])<0)
{
aux=cadena[i];
cadena[i]=cadena[j];
cadena[j]=aux;
}
}
}
}
|
C
|
/*
* mi.c
*
* Created by on 2/6/11.
* Copyright 2011 __MyCompanyName__. All rights reserved.
*
*/
/*
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "functionsMCMC.h"
*/
/*
VARIABLES:
v1 and v2 are the vector for which the MI has to be calculated.
These vectors represent the adjacency matrix for the network reduced to
a one dimension vector.
ns is the size of vectors that has to be equal for both the vectors
and MI is the mutual information for the two vectors. In principle ns will
be the number of genes under consideration for the network.
FUNCTION:
adapted from rWMBAT R-package
*/
/*
int main()
{
int arr1[] = { 1 ,0, 1, 2, 1, 0, 0, 2};
int arr2[] = { 2, 1, 1, 1, 0, 0, 0, 6};
int size=sizeof(arr1)/sizeof(int);
int size2 = sizeof(arr2)/sizeof(int);
if (size != size2)
{
printf("Error: Vectors should be of same size\nThe program will exit now\n");
exit(0);
}
else
mutInfo(arr1, arr2, size);
}
*/
double mutInfo(int *v1, int *v2, int *ns, double *MI) //function declaration to calculate mutual information
{
int *Pa, *Pb, *Pab, n; // pointer declaration to probability of 'a', 'b' and their joint probability repectively
// Memory allocation to the pointers
Pa = (int *) calloc(3, sizeof(int));
Pb = (int *) calloc(3, sizeof(int));
Pab = (int *) calloc(9, sizeof(int));
//Assigning size of the vector
n = (int*)ns ; // cast warning***
//printf("%d\n\n",n);
int i,j,k;
for (k=0; k<9; k++)
Pab[k] = 0;
for (k = 0; k < 3; k++) {
Pb[k] = 0;
for (j = 0; j < n; j++)
if (v2[j] == k+1)
Pb[k]++;
}
for (k = 0; k < 3; k++) {
Pa[k] = 0;
for (j = 0; j < n; j++) {
if (v1[j] == k+1) {
Pa[k]++;
for (i = 0; i < 3; i++)
if (v2[j] == i+1)
Pab[i*2 +k]++;
}
}
}
*MI = n * log(n);
for (k = 0; k < 9; k++)
if (Pab[k]>0)
*MI = *MI + (Pab[k] * log(Pab[k])) ;
for (k = 0; k < 3; k++) {
if (Pb[k]>0)
*MI = *MI - (Pb[k] *log(Pb[k])) ;
if (Pa[k]>0)
*MI = *MI - (Pa[k] *log(Pa[k])) ;
}
*MI = *MI / (double) n;
*MI = *MI/ log(2);
return (*MI);
//printf ("%f\n\n",*MI);
free (Pa);
free (Pb);
free (Pab);
}
|
C
|
#define F_CPU 8000000UL
#include <inttypes.h>
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#ifndef _UV
#define _UV(x) (1 << (x))
#endif
#define _setbit(x, y) ((x) |= _UV(y))
#define _clrbit(x, y) ((x) &= ~_UV(y))
#define DRVPORT PORTB
#define DRVEN 0
#define XACT 0
#define YACT 1
#define ZACT 2
#define XPORT PORTB
#define XDIR 1
#define XCLK 2
#define XSTDBY 3
#define YPORT PORTC
#define YDIR 0
#define YCLK 1
#define YSTDBY 2
#define ZPORT PORTC
#define ZDIR 3
#define ZCLK 4
#define ZSTDBY 5
volatile uint8_t cmdbuf;
volatile int8_t cmd_ready;
ISR(USART_RXC_vect)
{
uint8_t c;
c = UDR;
if(bit_is_clear(UCSRA, FE)) {
cmdbuf = c;
cmd_ready = 1;
}
}
void InitSerial(void)
{
UCSRB = _UV(TXEN) | _UV(RXEN) | _UV(RXCIE);
UCSRC = _UV(URSEL) | _UV(UCSZ1) | _UV(UCSZ0); // 8 bit, no parity, 1 stop
UBRRL = 12; // 38.4 kbps
}
void InitIO(void)
{
DDRB = 0x0F;
DDRC = 0x3F;
}
int main()
{
uint8_t active = 0;
InitIO();
InitSerial();
sei(); // Enable interrupts
while(1) {
if(cmd_ready) {
switch(cmdbuf) {
case 'd':
_clrbit(DRVPORT, DRVEN);
break;
case 'D':
_setbit(DRVPORT, DRVEN);
break;
case 'x':
_clrbit(XPORT, XDIR);
_clrbit(XPORT, XSTDBY);
_setbit(active, XACT);
break;
case 'X':
_setbit(XPORT, XDIR);
_clrbit(XPORT, XSTDBY);
_setbit(active, XACT);
break;
case 'y':
_clrbit(YPORT, YDIR);
_clrbit(YPORT, YSTDBY);
_setbit(active, YACT);
break;
case 'Y':
_setbit(YPORT, YDIR);
_clrbit(YPORT, YSTDBY);
_setbit(active, YACT);
break;
case 'z':
_clrbit(ZPORT, ZDIR);
_clrbit(ZPORT, ZSTDBY);
_setbit(active, ZACT);
break;
case 'Z':
_setbit(ZPORT, ZDIR);
_clrbit(ZPORT, ZSTDBY);
_setbit(active, ZACT);
break;
case '0':
active = 0;
_setbit(XPORT, XSTDBY);
_setbit(YPORT, YSTDBY);
_setbit(ZPORT, ZSTDBY);
break;
}
cmd_ready = 0;
}
if(active & _UV(XACT)) _setbit(XPORT, XCLK);
if(active & _UV(YACT)) _setbit(YPORT, YCLK);
if(active & _UV(ZACT)) _setbit(ZPORT, ZCLK);
_delay_us(500);
if(active & _UV(XACT)) _clrbit(XPORT, XCLK);
if(active & _UV(YACT)) _clrbit(YPORT, YCLK);
if(active & _UV(ZACT)) _clrbit(ZPORT, ZCLK);
_delay_us(500);
}
}
|
C
|
/*
Bellman - Ford Algorithm for finding shortest path
*/
#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>
struct node
{
int u,v,w;
}B[1000];
int dist[1000];
void init(int N)
{
int i;
for( i=0 ; i <= N ; i++)
dist[i]=100000;
}
int main()
{
int i,j,N,E;
printf("Enter the number of nodes and edges :");
scanf("%d %d",&N,&E);
for(i=0;i<E;i++)
{
printf("Enter the from to and weight :");
scanf("%d %d %d",&B[i].u,&B[i].v,&B[i].w);
}
init(N);
dist[0] = 0;
for(i=0;i<N-1;i++)
{
for(j=0;j<E;j++)
{
if( dist[B[j].u]+B[j].w < dist[B[j].v] )
dist[B[j].v] = dist[B[j].u]+B[j].w;
}
}
for( i=0 ; i <= N ;i++ )
{
printf(" Shortest path of %d -> %d \n" , i , dist[i] );
}
}
|
C
|
#include<stdio.h>
#include<string.h>
#define V 4
#define INF 99999
void printM(int A[][V]){
for(int i=0;i<V;i++){
for(int j=0;j<V;j++){
if(A[i][j]==INF)
printf("%4s","INF");
else
printf("%4d",A[i][j]);
}
printf("\n");
}}
void floydW(int graph[][V]){
int A[V][V];
for(int i=0;i<V;i++){
for(int j=0;j<V;j++){
A[i][j]=graph[i][j];
}
}
for(int k=0;k<V;k++){
for(int i=0;i<V;i++){
for(int j=0;j<V;j++){
if(A[i][k]+A[k][j]<A[i][j]){
A[i][j]=A[i][k]+A[k][j];
}}}}
printM(A);
}
int main(){
int graph[V][V]= { {0, 5, INF, 10},
{INF, 0, 3, INF},
{INF, INF, 0, 1},
{INF, INF, INF, 0}
};
floydW(graph);
}
|
C
|
// lab3.c
// Conor Wolfin
// 10.26.2018
// HARDWARE SETUP:
// PORTA is connected to the segments of the LED display. and to the pushbuttons.
// PORTA.0 corresponds to segment a, PORTA.1 corresponds to segement b, etc.
// PORTB bits 4-6 go to a,b,c inputs of the 74HC138.
// PORTB bit 7 goes to the PWM transistor base.
#define ZERO_DIGIT 0b11000000
#define ONE_DIGIT 0b11111001
#define TWO_DIGIT 0b10100100
#define THREE_DIGIT 0b10110000
#define FOUR_DIGIT 0b10011001
#define FIVE_DIGIT 0b10010010
#define SIX_DIGIT 0b10000011
#define SEVEN_DIGIT 0b11111000
#define EIGHT_DIGIT 0b10000000
#define NINE_DIGIT 0b10011000
#define A_DIGIT 0b10001000
#define B_DIGIT 0b10000011
#define C_DIGIT 0b11000110
#define D_DIGIT 0b10100001
#define E_DIGIT 0b10000110
#define F_DIGIT 0b10001110
#define DP_DIGIT 0b01111111
#define COLON_DIGIT 0b00000000
#define F_CPU 16000000 // cpu speed in hertz
#define TRUE 1
#define FALSE 0
#define CW 0
#define CWW 1
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
//holds data to be sent to the segments. logic zero turns segment on
uint8_t segment_data[5] = {255,255,255,255,255};
//decimal to 7-segment LED display encodings, logic "0" turns on segment
uint8_t dec_to_7seg[12] = {ZERO_DIGIT, ONE_DIGIT, TWO_DIGIT, THREE_DIGIT, FOUR_DIGIT, FIVE_DIGIT, SIX_DIGIT, SEVEN_DIGIT, EIGHT_DIGIT, NINE_DIGIT, DP_DIGIT, COLON_DIGIT};
uint8_t hex_to_7seg[16] = {ZERO_DIGIT, ONE_DIGIT, TWO_DIGIT, THREE_DIGIT, FOUR_DIGIT, FIVE_DIGIT, SIX_DIGIT, SEVEN_DIGIT, EIGHT_DIGIT, NINE_DIGIT, A_DIGIT, B_DIGIT, C_DIGIT, D_DIGIT, E_DIGIT, F_DIGIT};
//Flag indicating when interrupt was triggered
volatile uint8_t flag=0;
//In Hex or Dec
uint8_t DecHex = 10;
/*********************************************************************/
// SPI_read(uint8_t currentBarGraph)
//Sends the bar graph data and then reads the SPI port.
/*********************************************************************/
uint16_t SPI_read(uint8_t currentBarGraph){
PORTB &= 0x7F;
SPDR = currentBarGraph;
while (bit_is_clear(SPSR,SPIF)){} //wait till 8 bits have been sent
PORTD = 0xFF;
PORTD = 0x00;
PORTE = 0x00;
PORTE = 0xFF;
return(SPDR); //return incoming data from SPDR
}
//******************************************************************************
// chk_buttons(uint8_t buttons)
//Checks the state of the button number passed to it. It shifts in ones till
//the button is pushed. Function returns a 1 only once per debounced button
//push so a debounce and toggle function can be implemented at the same time.
//Adapted to check all buttons from Ganssel's "Guide to Debouncing"
//Expects active low pushbuttons on PINA port. Debounce time is determined by
//external loop delay times 12.
//Edited to have a state array of size 8 for each button
//******************************************************************************
uint8_t chk_buttons(uint8_t buttons) {
//Gansels debounce with the state as an array that is used to check against the values that buttons is at
static uint16_t state[8] = {0}; //holds present state
state[buttons] = (state[buttons] << 1) | (! bit_is_clear(PINA, buttons)) | 0xE000;
if (state[buttons] == 0xF000) return 1;
return 0;
}
//***********************************************************************************
// segment_sum
//takes a 16-bit binary input value and places the appropriate equivalent 4 digit
//BCD segment code in the array segment_data for display.
//array is loaded at exit as: |digit3|digit2|colon|digit1|digit0|
//***********************************************************************************
void segsum(uint16_t sum) {
uint8_t i = 0;
uint8_t digitNum = 1;
uint16_t sumPlaceHolder = sum;
while(i < 4 && sumPlaceHolder > (DecHex-1))
{
sumPlaceHolder /= DecHex;
digitNum++;
i++;
}
//Parses 0-4 digits into seperate segment_data[] locations
switch(digitNum)
{
case 1:
segment_data[4] = hex_to_7seg[sum];
segment_data[3] = 0xFF;
segment_data[1] = 0xFF;
segment_data[0] = 0xFF;
break;
case 2:
segment_data[4] = hex_to_7seg[(sum % DecHex)];
segment_data[3] = hex_to_7seg[(sum / DecHex)];
segment_data[1] = 0xFF;
segment_data[0] = 0xFF;
break;
case 3:
segment_data[4] = hex_to_7seg[sum % DecHex];
segment_data[3] = hex_to_7seg[(sum/DecHex)%DecHex];
segment_data[1] = hex_to_7seg[(sum/(DecHex*DecHex))];
segment_data[0] = 0xFF;
break;
case 4:
segment_data[4] = hex_to_7seg[sum % DecHex];
segment_data[3] = hex_to_7seg[(sum/DecHex)%DecHex];
segment_data[1] = hex_to_7seg[(sum/(DecHex*DecHex))%DecHex];
segment_data[0] = hex_to_7seg[sum/(DecHex*DecHex*DecHex)];
default:
break;
}
}
//***********************************************************************************
// displaySwitch
//Takes the segment_data[] array that has the #_DIGIT values and displays it to the
//current LED digit (displayValue) and returns the next value that will be used for displaying
//***********************************************************************************
uint8_t displaySwitch(uint8_t displayValue)
{
switch(displayValue){
case 0:
PORTB = 0x07;
PORTA = segment_data[4];
break;
case 1:
PORTB = 0x17;
PORTA = segment_data[3];
break;
case 2:
PORTB = 0x27;
PORTA = segment_data[2];
break;
case 3:
PORTB = 0x37;
PORTA = segment_data[1];
break;
case 4:
PORTB = 0x47;
PORTA = segment_data[0];
break;
default:
break;
}
_delay_ms(1); //Adds delay for screen congruency
if(displayValue == 4) return 0; //Starts display back to 0
return ++displayValue;
}
//***********************************************************************************
// ButtonCheck(uint8_t buttonMode)
//Function for when the interrupt was triggered, executing next main loop
//Takes in the current value outputted and returns the adjusted value based on the number
//***********************************************************************************
uint8_t ButtonCheck(uint8_t buttonMode)
{
//PORTA to input w/ pullups
DDRA = 0x00;
PORTA = 0xFF;
//enable tristate buffer for pushbutton switches via DEC7 on the encoder
PORTB = 0x70;
uint8_t buttonLoop = 0;
_delay_us(10); //BUG"Added delay to get first button to work, need better fix
while(buttonLoop < 3)
{
if(chk_buttons(buttonLoop))
{
buttonMode ^= (1<<buttonLoop);
}
buttonLoop++;
}
DDRA = 0xFF;
return buttonMode;
}
//***********************************************************************************
// HexConversion(uint8_t currentButtonsPressed)
//Checks if the 3rd button is pressed for changing HEX and DEC mode
//***********************************************************************************
uint8_t HexConversion(uint8_t currentButtonsPressed)
{
if(0 == (currentButtonsPressed & 0x04))
{
return 0;
}
return 1;
}
//***********************************************************************************
// SetAdjustmentValue(uint8_t buttonMode)
//Changes the output to desired
//Takes in the current value outputted and returns the adjusted value based on the number
//***********************************************************************************
uint8_t SetAdjustmentValue(uint8_t buttonMode)
{
switch(buttonMode)
{
case 0:
return 1;
case 1:
return 2;
case 2:
return 4;
case 3:
return 0;
}
return 5;
}
//***********************************************************************************
// ISR(TIMER0_OVF_vect)
//Triggered when TimerCounter0 overflows
//Sets flag to be utilized in main
//*********************************************************************************
ISR(TIMER0_OVF_vect)
{
if(!flag)
flag = 1;
}
//***********************************************************************************
// int8_t EncoderValueDirection(uint8_t currentEncoderValue, uint8_t urrentAdjustment)
//Checks direction of encoders turning and returns if the turn was CW or CCW
//Returns positive currentAdjustment value (CW) or negative currentAdjustment value (CCW)
//*********************************************************************************
int8_t EncoderValueDirection(uint8_t currentEncoderValue, uint8_t currentAdjustmentValue)
{
//Tests current encoder value against previous encoder value
//Tests if forward by value 0x00 --> 0x01, returns pos adjustment value
//Tests else if reverse, 0x01 --> 0x00, returns neg adjustment value
//First If statment checks 0B000000__
//Second If statment checks 0B0000__00
static uint8_t previousEncoderValue = 0x0F;
if((previousEncoderValue & 0x03) == 0x00 && (currentEncoderValue & 0x03) == 0x01)
{
previousEncoderValue = (currentEncoderValue & 0x0F);
return currentAdjustmentValue;
}
else if((previousEncoderValue & 0x03) == 0x01 && (currentEncoderValue & 0x03) == 0x00)
{
previousEncoderValue = (currentEncoderValue & 0x0F);
return ((-1)*currentAdjustmentValue);
}
//Checks the second Encoder
if((previousEncoderValue & 0x0C) == 0x00 && (currentEncoderValue & 0x0C) == 0x04)
{
previousEncoderValue = (currentEncoderValue & 0x0F);
return currentAdjustmentValue;
}
else if((previousEncoderValue & 0x0C) == 0x04 && (currentEncoderValue & 0x0C) == 0x00)
{
previousEncoderValue = (currentEncoderValue & 0x0F);
return ((-1)*currentAdjustmentValue);
}
previousEncoderValue = currentEncoderValue;
return 0;
}
//***********************************************************************************
int main()
{
DDRA = 0xFF;
DDRB = 0xFF; //set port B as outputs
DDRD = (1 << PD2); //Sets Port pin2 D to output
DDRE = (1 << PE6); //Sets Port pin6 E to output
PORTD = 0x00; //set port D to LOW
PORTB = 0x10; //set port B to start with LED1
PORTE = 0xFF;
SPCR |= (1 << SPE) | (1 << MSTR);//Enable SPI communication in mastermode
TIMSK |= (1<<TOIE0); //enable interrupts
TCCR0 |= (1<<CS02) | (1<<CS00); //normal mode, prescale by 128
sei();
uint8_t currentEncoderValue = 0x0F; //Stores entire encoderValue
uint8_t currentDisplayDigit = 0; //Current LED to display on (0 == 1's digit
uint16_t currentValue = 0; //Current value stored from pushbuttons
uint8_t currentButtonsPressed = 0; //Buttons pressed
int8_t currentAdjustmentValue = 1; //The value to inc/dec by
while(1){
//Flag set to one when TIMER0 interrupt set
//Sets the value that will be increased by for bargraph
//currentAdjustmentValue = 1 | 2 | 4 | 0
if(flag)
{
//currentButtonsPressed = ButtonCheck(currentButtonsPressed);
/*if(HexConversion(currentButtonsPressed))
{
//Determines if previously in HEX and switches to HEX or vice versa (as well as L3 segment)
if(DecHex == 16)
{
segment_data[2] = 0xFF;
DecHex = 10;
}else{
segment_data[2] = 0b11111011;
DecHex = 16;
}
currentButtonsPressed &= 0x03;
} */
//currentAdjustmentValue = SetAdjustmentValue(currentButtonsPressed);
flag = 0;
currentEncoderValue = (SPI_read(currentAdjustmentValue));
currentValue += EncoderValueDirection(currentEncoderValue, currentAdjustmentValue);
}
//---------------------------------------------------------------------------
/*
// ENCODER VALUE TEST:
// outputs decoder values
//(also need to comment out segsum)
currentValue = (SPI_read(currentAdjustmentValue));
if(currentValue & 0x01)
{
segment_data[0] = dec_to_7seg[1];
}else{
segment_data[0] = dec_to_7seg[0];
}
if(currentValue & 0x02)
{
segment_data[1] = dec_to_7seg[1];
}else{
segment_data[1] = dec_to_7seg[0];
}
//Resets the current value that is incrimented
if(currentValue & 0x04)
{
segment_data[3] = dec_to_7seg[1];
}else{
segment_data[3] = dec_to_7seg[0];
}
//Resets the digits to avoid leftover numbers
if(currentValue & 0x08)
{
segment_data[4] = dec_to_7seg[1];
}else{
segment_data[4] = dec_to_7seg[0];
}
*/
if(currentValue > 1023)
{
segment_data[0] = 0xFF;
segment_data[1] = 0xFF;
segment_data[3] = 0xFF;
segment_data[4] = 0xFF;
currentValue -= 1023; //Change too = 1 if do not want roll over data
}
segsum(currentValue); //Divide the decimal value to the segment_data[] array
currentDisplayDigit = displaySwitch(currentDisplayDigit); //Display the current values stored in segment_data[] to current LED
}//while
return 0;
}//main
|
C
|
#include <stdio.h>
#include "ft_putstr_non_printable.c"
int main()
{
ft_putstr_non_printable("Hello\vWorld");
return (0);
}
|
C
|
/**
* Author: TripleZ
* Date: 6/17/2018
*
* Simplest implemention for "system" function.
*
**/
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <wait.h>
int mysys(char* command) {
pid_t pid;
pid = fork();
if (pid == 0) {
execl("/bin/sh", "sh", "-c", command, NULL);
} else {
wait(NULL);
}
}
int main (int argc, char* argv[]) {
printf("-----------------------------------------\n");
mysys("echo Hello world");
printf("-----------------------------------------\n");
mysys("ls /");
printf("-----------------------------------------\n");
}
|
C
|
// Exercise Nr: 4
// Name : Syed Sagheer Hussain
#include <msp430.h>
#include "templateEMP.h"
void turn_on(unsigned short);
unsigned short value(unsigned int);
int main () {
initMSP();
P1SEL &= ~BIT5;
P1SEL2 &= ~BIT5;
P2SEL &= ~(BIT0 + BIT1 + BIT4 + BIT5 + BIT6);
P2SEL2 &= ~(BIT0 + BIT1 + BIT4 + BIT5 + BIT6);
P1DIR &= ~BIT5;
P2DIR |= BIT0 + BIT1 + BIT4 + BIT5 + BIT6;
ADC10CTL0 = ADC10ON + ADC10SHT_2 ;
ADC10AE0 |= BIT5 ;
ADC10CTL1 = INCH_5 ;
while (1){
P2OUT &= ~BIT5;
P2OUT = BIT0 + BIT2 + BIT3 + BIT5 + BIT6;
// Start c o n v e r s i o n
ADC10CTL0 |= ENC + ADC10SC ;
// Wait until result is ready
while ( ADC10CTL1 & ADC10BUSY ) ;
// If result is ready , copy it to m1
//int m1 = ADC10MEM ;
P2OUT &= ~BIT6;
//unsigned int value = ADC10MEM;
if (ADC10MEM > 203 && ADC10MEM < 408){
P2OUT |= BIT6 ;
_clock();
// Print m1 to the serial console
}
if (ADC10MEM > 408 && ADC10MEM < 612){
int i;
for (i=0; i<2; i++){
P2OUT |= BIT6 ;
_clock();
}
}
if (ADC10MEM > 612 && ADC10MEM < 816){
int i;
for (i=0; i<3; i++){
P2OUT |= BIT6 ;
_clock();
}
}
if (ADC10MEM > 816){
int i;
for (i=0; i<4; i++){
P2OUT |= BIT6 ;
_clock();
}
}
serialPrintInt ( ADC10MEM ) ;
serialPrintln ( " " ) ;
}
}
unsigned short value(unsigned int poti){
if (poti>203 && poti<408)
return 1;
if (poti>408 && poti<612)
return 2;
if (poti>612 && poti<816)
return 3;
if (poti>816)
return 4;
else return 0;
}
void turn_on(unsigned short nr){
unsigned short i;
for(i=0; i<nr; i++){
P2OUT |= BIT6 ;
_clock();
}
}
void Clock (){
P2OUT |= BIT4;
P2OUT &= ~BIT4;
}
/*
if (ADC10MEM > 203 && ADC10MEM < 408){
P2OUT |= BIT6 ;
_clock();
// Print m1 to the serial console
}
if (ADC10MEM > 408 && ADC10MEM < 612){
int i;
for (i=0; i<2; i++){
P2OUT |= BIT6 ;
_clock();
}
}
if (ADC10MEM > 612 && ADC10MEM < 816){
int i;
for (i=0; i<3; i++){
P2OUT |= BIT6 ;
_clock();
}
}
if (ADC10MEM > 816){
int i;
for (i=0; i<4; i++){
P2OUT |= BIT6 ;
_clock();
}
} */
|
C
|
/*
** my_tablen.c for my_tablen in /home/svirch_n//current_project/wolf3D/wolf3d-2017-svirch_n
**
** Made by nicolas svirchevsky
** Login <svirch_n@pc-svirch_n>
**
** Started on Tue Jan 8 11:44:17 2013 nicolas svirchevsky
** Last update Tue Jan 8 11:44:36 2013 nicolas svirchevsky
*/
int my_tablen(char **tab)
{
int i;
i = 0;
while (tab[i])
i++;
return (i);
}
|
C
|
#ifndef INCLUDE_CORE_BOOTROM_H
#define INCLUDE_CORE_BOOTROM_H
#include "debug.h"
#include "types.h"
#include "memfn.h"
#define BOOTROM_SIZE 256
struct bootrom {
union conversion con;
u8 byte[BOOTROM_SIZE];
};
extern struct bootrom* new_bootrom(const char* path);
extern void free_bootrom(struct bootrom* this);
static inline u8
bootrom_rb
(struct bootrom* this, u16 address)
{
return this->byte[address];
}
static inline u16
bootrom_rw
(struct bootrom* this, u16 address)
{
this->con.lobyte = this->byte[address];
this->con.hibyte = this->byte[address + 1];
return this->con.word;
}
static inline void
bootrom_wb
(struct bootrom* this, u16 address, u8 data)
{
this->byte[address] = data;
}
static inline void
bootrom_ww
(struct bootrom* this, u16 address, u16 data)
{
this->con.word = data;
this->byte[address] = this->con.lobyte;
this->byte[address + 1] = this->con.hibyte;
}
#endif
|
C
|
#include "list.h"
#include <stdio.h>
#include <stdlib.h>
void initList(List *list){
list->head = NULL;
list->tail = NULL;
}
int sizeList(List *list){
Node *node = list->head;
int size = 0;
if(node == NULL){
return size = 0;
}
while(node != NULL){
size++;
node = node->next;
}
return size;
}
void isEmpty(List *list){
if(list->head == NULL){
return;
}
}
/*void addTail(List *list,DataType data){
Node *node = (Node *)malloc(sizeof(Node));
node->data = data;
node->next = NULL;
if(list->head == NULL){
list->head = node;
}else{
list->tail->next = node;
}
list->tail = node;
return;
}*/
void insertList(List *list ,int loc, DataType data){
Node *node = (Node *)malloc(sizeof(Node));
Node *prev = (Node *)malloc(sizeof(Node));
if(loc<=1){
node->data = data;
node->next = NULL;
if(list->head == NULL){
list->tail = node;
}else{
node->next = list->head;
}
list->head = node;
// return;
}else{
prev = list->head;
node->data = data;
node->next = NULL;
if(list->head == NULL){
list->tail = node;
}
for(int size=1;size<loc-1;size++){
prev = prev->next;
}
node->next = prev->next;
prev->next = node;
// return;
}
node = list->head;
while(node->next != NULL){
node = node->next;
}
list->tail = node;
}
void delList(List *list, int loc){
if(loc<=1){
list->head = list->head->next;
return;
}else{
Node *node = list->head;
for(int size= 1;size<loc-1;size++){
if(node == NULL){
return;
}
node = node->next;
}
node->next = node->next->next;
return;
}
}
DataType getdata(List *list, int loc){
Node *node = list->head;
int size = 1;
if(size != loc){
node = node->next;
size++;
}
return node->data;
}
Node* find(List *list, DataType data){
Node *node = list->head->next;
while(node && node->data != data){
node = node->next;
}
return node;
}
void printList(List *list){
Node *node = (Node *)malloc(sizeof(Node));
node = list->head;
while(node != NULL){
printf("%d\t",node->data);
node = node->next;
}
printf("\n");
return;
}
void clearList(List *list){
if(list->head == NULL){
return;
}
Node *p,*q;
p = list->head;
while(p){
q = p;
p = p->next;
free(q);
}
list->head = NULL;
return;
}
|
C
|
#include "holberton.h"
/**
* wildcmp - compares two strings to check whether identical
* @s1: first string
* @s2: second string
*
* Return: 1 if considered identical, 0 otherwise
*/
int wildcmp(char *s1, char *s2)
{
if (s1 && s2)
return (1);
else
return (0);
}
|
C
|
#include <stdio.h>
#include "dw_time.h"
int main(void)
{
Dw_time_type tm;
dw_get_local_time(&tm);
printf("dw time:%d-%d-%d %d:%d:%d\n",tm.year, tm.mon, tm.day, tm.hour, tm.min, tm.sec);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#define N 8 // chessboard size
/*
*八皇后问题
*http://ac.jobdu.com/problem.php?pid=1140
*/
int abs(int a);//math abstract number;
int x[N];//the position of the queen;
int place(int i,int j);//return if you can put the queen here;
void traceback(int index);//put the queen to the index's column;
int sum=0;
int abs(int a)
{
if(a<0){
return 0-a;
}else{
return a;
}
}
int place(int i,int j) //wether x[i] = j is legal ,means put queen on point(i,j);
{ //if legal ,k<i x[k] != j,abs(x[k] - k) != (j - i);
for(int k=0;k<i;k++){
if(x[k] == j || abs(i - k) == abs(j - x[k]) ){
return 0;
}
}
return 1;
}
void printChessboard()
{
printf("\n");
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
if(x[j] == i){
printf("Q ");
}else{
printf("# ");
}
}
printf("\n");
}
}
void put(int t, int n) //put the t's row
{
if(t==N){
sum++;
if(sum == n){
for(int k=0;k<N;k++){
printf("%d",x[k]+1);
}
printChessboard();
}
}else{
for(int k=0;k<N;k++){
x[t] = k;
if(place(t,k)){
put(t+1,n);
}
}
}
}
int main()
{
int n = 1;
put(0,n);
}
|
C
|
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
void handler(int signum) {
if (signum == SIGINT){
printf("CONTROL SIGNAL IS PRESSED!\n");
}
}
int main(){
void (*handlr)(int);
struct sigaction sa;
handlr = handler;
sa.sa_handler = *handlr;
while(1){
printf("/");
sleep(1);
if(sigaction(SIGINT, &sa, NULL) == -1)
perror("SIGACTION");
}
// so on
return 0;
}
|
C
|
#include <stdio.h>
#define ARRAY_LENGHT 20
typedef enum
{
success,
incorrect_input
} status_code;
status_code input(int a[ARRAY_LENGHT], int *n, int *k)
{
if (scanf("%d", n) != 1 || *n > ARRAY_LENGHT || *n < 2)
return incorrect_input;
for (int i = 0; i < *n; i++)
if (scanf("%d", &a[i]) != 1)
return incorrect_input;
if (scanf("%d", k) != 1 || *k < 1)
return incorrect_input;
return success;
}
void checking(int a[ARRAY_LENGHT], int *n, int k)
{
for (int i = 0; i < *n; i += 3)
if (a[i] % k == 0)
{
for (int j = i; j < *n; j++)
a[j] = a[j + 1];
(*n)--;
i--;
}
}
void output(int a[ARRAY_LENGHT], int n)
{
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
}
int main(void)
{
int a[ARRAY_LENGHT], n, k;
if (input(a, &n, &k))
return incorrect_input;
checking(a, &n, k);
output(a, n);
return success;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#pragma warning(disable:4996)
#define MAX_NODE 100
typedef struct _node //for adjacency list
{
int vertex; //꼭지점
//가중치 X
struct _node* next; //다음 노드를 가리키는 포인터
}node;
typedef struct _head // For indegree
{
int count;
struct _node* next;
}head;
head network[MAX_NODE];
node* GL[MAX_NODE];
FILE* fp = NULL;
int stack[MAX_NODE];
int check[MAX_NODE];
int top;
int name2int(char c) //char형 레이블을 배열 인덱스로 쓰기 용이하게 int형으로 변환해주는 함수
{
return c - 'A';
}
char int2name(int i) //배열 인덱스를 문자로 변환해주는 함수
{
return i + 'A';
}
void init_stack(void) //stack 초기화 함수
{
top = -1;
}
int push(int t) //stack push함수
{
if (top >= MAX_NODE - 1)
{
printf("Stack overflow !!!\n");
return -1;
}
stack[++top] = t;
return t;
}
int pop() //stack pop함수
{
if (top < 0)
{
printf("Stack underflow !!!\n");
return -1;
}
return stack[top--];
}
int isstack_empty() //stack이 비어있는지 검사하는 함수
{
return (top < 0);
}
void visit(int i) //그래프에서 노드 방문 (출력)하는 함수
{
printf("--> %c ", int2name(i));
}
void input_adjlist(node* h[], int* V, int* E) //For Directed Graph //NO Weight
{
char vertex[3]; //입력받을 연결(edge)된 노드를 저장할 임시변수 (끝에 null문자 고려)
int i, j;
node* t; //임시 node형 포인터 선언
printf("\nInput number of node & edge : ");
fscanf(fp, "%d %d", V, E); //node 갯수와 edge갯수 입력받음
for (i = 0; i < *V; i++)
{
h[i] = NULL; // 배열 a를 null로 초기화
}
for (j = 0; j < *E; j++)
{
printf("Input two node consist of edge : ");
fscanf(fp, "%s", vertex); //연결된 2개 노드 입력
i = name2int(vertex[0]); //1번째 노드 -> 배열 인덱스로 변환
t = (node*)malloc(sizeof(node)); //임시 변수 t에 동적할당
t->vertex = name2int(vertex[1]); // node 이름 저장
t->next = h[i]; //a[i]가 가리키던 포인터를 t의 next 포인터로 넘겨줌
h[i] = t; //포인터 t를 a[i]로 넘겨줌 (Head 뒤에 삽입, 기존 리스트를 앞으로 밀어내고 새로운 리스트 추가)
//※※※directed graph는 대칭 성분과 동일하게 입력하지 않음※※※
}
}
void set_count_indegree(head net[], int V) //내차수 계산 함수
{
int i, j;
int count; //내차수
node* t;
for (i = 0; i < V; i++)// V개의 노드에 대해서 indegree를 계산한다.
{
count = 0; //count 초기화
for (j = 0; j < V; j++) //V개의 노드에 대해서 count 계산
{
for (t = net[j].next; t; t = t->next) //노드 j에 연결되어 있는 노드 탐색
{
if (t->vertex == i) // 노드 j에 연결되어 있는 노드 중 노드 i가 있을 때
//즉 노드 j는 노드 i의 선행작업이다.
{
count++; //count up
}
}
}
net[i].count = count; //indegree를 대입한다.
}
}
void topsort(head net[], int V) //topological sort
{
int i, j, k;
node* ptr;
init_stack(); // 스택 초기화
set_count_indegree(net, V); //내차수 계산
printf("\nTopological Sorting");
for (i = 0; i < V; i++)
{
if (!net[i].count)// 내차수가 0인 노드를 스택에 push
{
push(i);
}
}
for (i = 0; i < V; i++)
{
if (isstack_empty()) //내차수가 0인 노드가 없거나(cyclic graph일때) 전부 방문하여 스택이 비었을때
{
return; // 종료
}
else
{
j = pop(); //스택에서 pop한 노드
printf(" -> %c", int2name(j)); //노드 방문(출력)
for (ptr = net[j].next; ptr; ptr = ptr->next)
//스택에서 pop한 노드 j 와 연결된 노드 탐색
{
k = ptr->vertex; //노드 ptr의 값 저장
net[k].count--; //노드 j 방문으로 해당 노드와 연결되어 있는 노드 k의 내차수 감소
if (!net[k].count)// 감소한 내차수가 0이라면 스택에 push
{
push(k); //내차수 0인 노드 push
}
}
}
}
}
void print_adjlist(node* a[], int V)
{
node* next_tmp; //다음 노드의 임시 포인터 변수, 이전 노드의 임시 포인터 변수 선언
for (int i = 0, j = 0; i < V; i++) //Vertex 수 만큼 반복
{
printf("\n |%c|", int2name(i)); // 해당 i(인덱스)를 노드 문자로 전환
next_tmp = a[i]; //node 포인터 배열 원소(해당 노드의 첫 포인터)를 임시 변수에 저장
while (next_tmp != NULL) //다음 노드 포인터(next)가 없을 때까지
{
printf(" -> %c", int2name(next_tmp->vertex)); //다음(현재) 노드 포인터가 가리키는 노드 출력
next_tmp = next_tmp->next; // 다음(현재) 노드 포인터를 다다음(다음) 노드 포인터로 업데이트
}
}
}
void delete_all_list(node* a[], int V) //list 동적할당 해제
{
node* s, * t;
for (int i = 0; i < V; i++)
{
for (s = a[i]; s != NULL; )
{
t = s;
s = s->next;
free(t);
}
}
}
void delete_all_head(head h[], int V) //head 동적할당 해제
{
node* s, * t;
for (int i = 0; i < V; i++)
{
for (s = h[i].next; s != NULL; )
{
t = s;
s = s->next;
free(t);
}
}
}
int main()
{
int V, E, k;
fp = fopen("graph_top.txt", "rt");
if (fp == NULL)
{
printf("파일을 열 수 없습니다.\n");
exit(1);
}
input_adjlist(GL, &V, &E);
printf("\nOriginal graph");
print_adjlist(GL, V); //adjacency list 출력
for (k = 0; k < V; k++) //network setting
{
network[k].next = GL[k];
}
topsort(network, V); //topsort 수행
//delete_all_list(GL, V);
delete_all_head(network, V);
fclose(fp);
return 0;
}
|
C
|
/*
Description
How far can you make a stack of cards overhang a table? If you have one card, you can create a maximum overhang of half a card length. (We're assuming that the cards must be perpendicular to the table.) With two cards you can make the top card overhang the bottom one by half a card length, and the bottom one overhang the table by a third of a card length, for a total maximum overhang of 1/2 + 1/3 = 5/6 card lengths. In general you can make n cards overhang by 1/2 + 1/3 + 1/4 + ... + 1/(n + 1) card lengths, where the top card overhangs the second by 1/2, the second overhangs tha third by 1/3, the third overhangs the fourth by 1/4, etc., and the bottom card overhangs the table by 1/(n + 1). This is illustrated in the figure below.
*/
#include<stdio.h>
int main()
{
int a=1;
double c;
scanf("%lf",&c);
while(c>0.000001)
{
a=1;
while(c>0.0)
{
c-=1.0/(double)(a+1.0);
a++;
}
printf("%d card(s)\n",a-1);
scanf("%lf",&c);
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* calc_coor.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ojessi <ojessi@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/06/09 20:25:11 by ojessi #+# #+# */
/* Updated: 2019/06/09 20:59:29 by ojessi ### ########.fr */
/* */
/* ************************************************************************** */
#include "fdf.h"
void iso(double *x, double *y, double z)
{
int previous_x;
int previous_y;
previous_x = *x;
previous_y = *y;
*x = (int)((previous_x - previous_y) * cos(0.523599));
*y = (int)(-z + (previous_x + previous_y) * sin(0.523599));
}
void x_rotation(double x, double *y, double *z, t_map *map)
{
int tmpx;
double tmpy;
double tmpz;
tmpx = x;
tmpy = *y;
tmpz = *z;
x = tmpx;
*y = (double)tmpy * cos(map->mouse->angel) + (double)tmpz *
sin(map->mouse->angel);
*z = (double)-tmpy * sin(map->mouse->angel) + (double)tmpz *
cos(map->mouse->angel);
}
void y_rotation(double *x, double y, double *z, t_map *map)
{
double tmpx;
int tmpy;
double tmpz;
tmpx = *x;
tmpy = y;
tmpz = *z;
*x = (double)tmpx * cos(map->mouse->angel) + (double)tmpz *
sin(map->mouse->angel);
y = tmpy;
*z = (double)-tmpx * sin(map->mouse->angel) + (double)tmpz *
cos(map->mouse->angel);
}
void z_rotation(double *x, double *y, double z, t_map *map)
{
double tmpx;
double tmpy;
int tmpz;
tmpx = *x;
tmpy = *y;
tmpz = z;
*x = (double)tmpx * cos(map->mouse->angel) - (double)tmpy *
sin(map->mouse->angel);
*y = (double)tmpx * sin(map->mouse->angel) + (double)tmpy *
cos(map->mouse->angel);
z = tmpy;
}
|
C
|
#include<stdio.h>
int Find(int *arr, int ROW, int COL, int data)
{
int row = 0;//Ϊ0
int col = COL - 1;//Ϊ3
if ((arr != NULL) && (ROW>0&&COL>0))//жǷΪ
{
while (row<ROW&&col >= 0)//ֱų
{
if (arr[row*col + col] == data)//ϽΪҵ
{
return 1;
}
else if (arr[col*row + col]>data)//ϽǴdataҪһ
{
--col;
}
else{
row++;//ϽСdataƶһ
}
}
}
return 0;
}
int main()
{
int arr[] = { 1,2,9,10,3,4,11,12,5,7,13,14,6,9,15,16};
int data = 0;
int ROW = 3;
int COL = 3;
printf("Ҫҵ֣");
scanf_s("&data");
int ret=Find(arr, ROW, COL, data);
if (ret == 1)
{
printf("ҵ\n");
}
else if (ret==0)
{
printf("Ҳ\n");
}
system("pause");
return 0;
}
|
C
|
#include "pqueue.h"
struct pqueue* pqueue_init(struct pqueue* queue,comparator_func* func)
{
queue->list = NULL;
queue->cmp = func;
return queue;
}
void pqueue_add(struct pqueue* queue,void* elem)
{
struct node* new_node = malloc(sizeof(struct node));
new_node->elem = elem;
new_node->next = NULL;
new_node->prev = NULL;
if(queue->list == NULL)
{
queue->list = new_node;
return;
}
struct node* curr = queue->list;
while(curr->next != NULL && queue->cmp(curr->elem,elem) > 0) curr = curr->next;
if(queue->cmp(curr->elem,elem) < 0)
{
new_node->prev = curr;
curr->next = new_node;
}
else
{
new_node->next = curr;
new_node->prev = curr->prev;
if(curr->prev != NULL) curr->prev->next = new_node;
else queue->list = new_node;
curr->prev = new_node;
}
}
void* pqueue_remove(struct pqueue* queue)
{
if (queue->list == NULL) {
return;
}
void* elem = queue->list->elem;
struct node* to_remove = queue->list;
if(queue->list->next != NULL) queue->list->next->prev = NULL;
queue->list = queue->list->next;
free(to_remove);
return elem;
}
void* pqueue_peek(struct pqueue* queue)
{
if(queue->list == NULL) {
return NULL;
} else {
return queue->list->elem;
}
}
/*
#include <stdio.h>
bool address_compare (void* a, void* b) {
if (*(int*)a > *(int*)b) {
return true;
} else {
return false;
}
}
int main() {
struct pqueue* queue = malloc(sizeof(struct pqueue));
queue = pqueue_init(&address_compare);
int a = 6;
int b = 4;
int c = 5;
int d = 10;
int e = 5;
int f = 4;
int g = 8;
pqueue_add(queue,&a);
pqueue_add(queue,&b);
pqueue_add(queue,&c);
pqueue_add(queue,&d);
pqueue_add(queue,&e);
pqueue_add(queue,&f);
pqueue_add(queue,&g);
printf("%d\n", *(int*)pqueue_peek(queue));
printf("%d\n", *(int*)pqueue_remove(queue));
printf("%d\n", *(int*)pqueue_peek(queue));
return 0;
}*/
|
C
|
#include <wiringPi.h>
void configure_pin(int port);
//Used [WiringPi docs](http://wiringpi.com/wp-content/uploads/2013/03/pins.pdf)
int pins[21];
bool isSetup = false;
int setup()
{
int setupValue = wiringPiSetup();
int i = 0;
for(i; i < 21; ++i)
{
pins[i] = 0;
}
setup = true;
return setupValue;
}
int turn_on(int port)
{
if(isSetup == false)
{
int setupReturn = setup();
if(setupReturn == -1)
{
return setupReturn;
}
}
configure_pin(port);
digitalWrite(port, 1);
return 1;
}
int turn_off(int port)
{
if(isSetup == false)
{
int setupReturn = setup();
if(setupReturn == -1)
{
return setupReturn;
}
}
configure_pin(port);
digitalWrite(port, 0);
return 1;
}
void configure_pin(int port)
{
if(pins[port] == -1)
{
pinMode(port, OUTPUT);
pins[port] = port;
}
}
|
C
|
/*
** socket_io.c for myirc in /home/pumpkin/Desktop/PSU_2015_myirc/src
**
** Made by Loik Gaonach
** Login <gaonac_l@epitech.net>
**
** Started on Fri May 27 19:00:11 2016 Loik Gaonach
** Last update Sun Jun 26 22:05:35 2016 julien
*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include "server.h"
#include "request.h"
char *read_socket(int fd)
{
int len;
int ret;
char *tmp;
len = 0;
if (ioctl(fd, FIONREAD, &len) == -1)
{
perror("read_socket:ioctl");
return (NULL);
}
if (len > 0)
{
if ((tmp = malloc(sizeof(char) * (len + 1))) == NULL)
return (NULL);
memset(tmp, 0, len + 1);
if ((ret = read(fd, tmp, len)) > 0)
return (tmp);
else if (ret == -1)
{
if (tmp)
free(tmp);
perror("read");
}
}
return (NULL);
}
int server_read(t_socket sock[], int fd)
{
int client_fd;
if ((client_fd = add_client_socket(sock, fd)))
add_responce(sock[client_fd].write_buff, strdup("BIENVENUE\n"));
return (0);
}
void parse_request(t_socket *sock, char *buff)
{
char *next;
char end;
end = 0;
while (!end)
{
if ((next = strchr(buff, '\n')))
{
push_request(sock->read_buff, buff, next - buff + 1);
buff = next + 1;
}
else
{
push_request(sock->read_buff, buff, strlen(buff));
end = 1;
}
}
}
int client_read(t_socket sock[], int fd)
{
char *tmp;
if ((tmp = read_socket(fd)))
{
parse_request(&sock[fd], tmp);
free(tmp);
return (0);
}
return (-1);
}
int client_write(t_socket sock[], int fd)
{
t_res *res;
unsigned int ret;
if (len_dllc(sock[fd].write_buff) > 0)
{
res = sock[fd].write_buff->nxt->data;
ret = write(fd, res->buff + res->i, strlen(res->buff));
if (ret != strlen(res->buff) - res->i)
res->i = ret;
else
{
free(res->buff);
free(res);
delete_elem_dllc(sock[fd].write_buff->nxt);
}
}
return (0);
}
|
C
|
#include<stdio.h>
int main()
{
int num;
scanf("%d",&num);
long long j=1,sum=0;
int i,n;
for(i=1;i<=num;i++)
{
j=j*i;
sum=sum+j;
}
printf("%lld",sum);
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int x=10,y=3;
{
int x=100,z=10;
printf("%d %d",x,z);
}
printf("%d%d",x,z);
}
output: 'z' undeclare(first use in this function)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.